diff --git a/.github/ci.sh b/.github/ci.sh index 1344d235..958a1f95 100755 --- a/.github/ci.sh +++ b/.github/ci.sh @@ -2,13 +2,28 @@ set -xEeuo pipefail [[ "$RUNNER_OS" == 'Windows' ]] && IS_WIN=true || IS_WIN=false -BIN=bin +BIN=${PWD}/bin EXT="" $IS_WIN && EXT=".exe" mkdir -p "$BIN" is_exe() { [[ -x "$1/$2$EXT" ]] || command -v "$2" > /dev/null 2>&1; } +# The deps() function is primarily used for producing debug output to +# the CI logging files. For each platform, it will indicate which +# shared libraries are needed and if they are present or not. The +# '|| true' is used because statically linked binaries will cause +# ldd (and possibly otool) to exit with a non-zero status. +deps() { + case "$RUNNER_OS" in + Linux) ldd $1 || true ;; + macOS) otool -L $1 || true ;; + Windows) ldd $1 || true ;; + esac +} + +# Finds the cabal-built '$1' executable and copies it to the '$2' +# directory. extract_exe() { exe="$(cabal v2-exec which "$1$EXT")" name="$(basename "$exe")" @@ -45,63 +60,6 @@ setup_dist_bins() { strip dist/bin/cryptol* || echo "Strip failed: Ignoring harmless error" } -install_z3() { - is_exe "$BIN" "z3" && return - - case "$RUNNER_OS" in - Linux) file="ubuntu-18.04.zip" ;; - macOS) file="osx-10.15.7.zip" ;; - Windows) file="win.zip" ;; - esac - curl -o z3.zip -sL "https://github.com/Z3Prover/z3/releases/download/z3-$Z3_VERSION/z3-$Z3_VERSION-x64-$file" - - if $IS_WIN; then 7z x -bd z3.zip; else unzip z3.zip; fi - cp z3-*/bin/z3$EXT $BIN/z3$EXT - $IS_WIN || chmod +x $BIN/z3 - rm z3.zip -} - -install_cvc4() { - version="${CVC4_VERSION#4.}" # 4.y.z -> y.z - - case "$RUNNER_OS" in - Linux) file="x86_64-linux-opt" ;; - Windows) file="win64-opt.exe" ;; - macOS) file="macos-opt" ;; - esac - # Temporary workaround - if [[ "$RUNNER_OS" == "Linux" ]]; then - #latest="$(curl -sSL "http://cvc4.cs.stanford.edu/downloads/builds/x86_64-linux-opt/unstable/" | grep linux-opt | tail -n1 | sed -e 's/.*href="//' -e 's/\([^>]*\)">.*$/\1/')" - latest="cvc4-2021-03-13-x86_64-linux-opt" - curl -o cvc4 -sSL "https://cvc4.cs.stanford.edu/downloads/builds/x86_64-linux-opt/unstable/$latest" - else - curl -o cvc4$EXT -sSL "https://github.com/CVC4/CVC4/releases/download/$version/cvc4-$version-$file" - fi - $IS_WIN || chmod +x cvc4$EXT - mv cvc4$EXT "$BIN/cvc4$EXT" -} - -install_yices() { - ext=".tar.gz" - case "$RUNNER_OS" in - Linux) file="pc-linux-gnu-static-gmp.tar.gz" ;; - macOS) file="apple-darwin18.7.0-static-gmp.tar.gz" ;; - Windows) file="pc-mingw32-static-gmp.zip" && ext=".zip" ;; - esac - curl -o "yices$ext" -sL "https://yices.csl.sri.com/releases/$YICES_VERSION/yices-$YICES_VERSION-x86_64-$file" - - if $IS_WIN; then - 7z x -bd "yices$ext" - mv "yices-$YICES_VERSION"/bin/*.exe "$BIN" - else - tar -xzf "yices$ext" - pushd "yices-$YICES_VERSION" || exit - sudo ./install-yices - popd || exit - fi - rm -rf "yices$ext" "yices-$YICES_VERSION" -} - build() { ghc_ver="$(ghc --numeric-version)" cp cabal.GHC-"$ghc_ver".config cabal.project.freeze @@ -114,12 +72,11 @@ build() { } install_system_deps() { - install_z3 & - install_cvc4 & - install_yices & - wait - export PATH=$PWD/$BIN:$PATH - echo "$PWD/$BIN" >> "$GITHUB_PATH" + (cd $BIN && curl -o bins.zip -sL "https://github.com/GaloisInc/what4-solvers/releases/download/$SOLVER_PKG_VERSION/$BIN_ZIP_FILE" && unzip -o bins.zip && rm bins.zip) + chmod +x $BIN/* + cp $BIN/yices_smt2$EXT $BIN/yices-smt2$EXT + export PATH=$BIN:$PATH + echo "$BIN" >> "$GITHUB_PATH" is_exe "$BIN" z3 && is_exe "$BIN" cvc4 && is_exe "$BIN" yices } @@ -165,6 +122,19 @@ zip_dist() { tar -cvzf "$name".tar.gz "$name" } +zip_dist_with_solvers() { + : "${VERSION?VERSION is required as an environment variable}" + name="${name:-"cryptol-$VERSION-$RUNNER_OS-x86_64"}" + sname="${name}-with-solvers" + cp "$(which abc)" dist/bin/ + cp "$(which cvc4)" dist/bin/ + cp "$(which yices)" dist/bin/ + cp "$(which yices-smt2)" dist/bin/ + cp "$(which z3)" dist/bin/ + cp -r dist "$sname" + tar -cvzf "$sname".tar.gz "$sname" +} + output() { echo "::set-output name=$1::$2"; } ver() { grep Version cryptol.cabal | awk '{print $2}'; } set_version() { output cryptol-version "$(ver)"; } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e3330a41..00c6e8d9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,9 +9,7 @@ on: workflow_dispatch: env: - Z3_VERSION: "4.8.10" - CVC4_VERSION: "4.1.8" - YICES_VERSION: "2.6.2" + SOLVER_PKG_VERSION: "snapshot-20210917" jobs: config: @@ -57,6 +55,8 @@ jobs: ghc-version: ["8.6.5", "8.8.4", "8.10.2"] exclude: # https://gitlab.haskell.org/ghc/ghc/-/issues/18550 + - os: windows-latest + ghc-version: 8.8.4 - os: windows-latest ghc-version: 8.10.2 outputs: @@ -94,6 +94,8 @@ jobs: - shell: bash run: .github/ci.sh install_system_deps + env: + BIN_ZIP_FILE: ${{ matrix.os }}-bin.zip - shell: bash env: @@ -149,19 +151,27 @@ jobs: SIGNING_KEY: ${{ secrets.SIGNING_KEY }} run: .github/ci.sh sign cryptol.msi - - if: needs.config.outputs.release == 'true' - shell: bash - env: - SIGNING_PASSPHRASE: ${{ secrets.SIGNING_PASSPHRASE }} - SIGNING_KEY: ${{ secrets.SIGNING_KEY }} - run: .github/ci.sh sign ${NAME}.tar.gz - - shell: bash run: | NAME="${{ needs.config.outputs.name }}-${{ runner.os }}-x86_64" echo "NAME=$NAME" >> $GITHUB_ENV .github/ci.sh zip_dist $NAME + - shell: bash + run: | + NAME="${{ needs.config.outputs.name }}-${{ runner.os }}-x86_64" + echo "NAME=$NAME" >> $GITHUB_ENV + .github/ci.sh zip_dist_with_solvers $NAME + + - if: needs.config.outputs.release == 'true' + shell: bash + env: + SIGNING_PASSPHRASE: ${{ secrets.SIGNING_PASSPHRASE }} + SIGNING_KEY: ${{ secrets.SIGNING_KEY }} + run: | + .github/ci.sh sign ${NAME}.tar.gz + .github/ci.sh sign ${NAME}-with-solvers.tar.gz + - uses: actions/upload-artifact@v2 with: name: ${{ env.NAME }} @@ -169,6 +179,13 @@ jobs: if-no-files-found: error retention-days: ${{ needs.config.outputs.retention-days }} + - uses: actions/upload-artifact@v2 + with: + name: ${{ env.NAME }}-with-solvers + path: "${{ env.NAME }}-with-solvers.tar.gz*" + if-no-files-found: error + retention-days: ${{ needs.config.outputs.retention-days }} + - if: matrix.ghc-version == '8.6.5' uses: actions/upload-artifact@v2 with: @@ -197,17 +214,17 @@ jobs: matrix: suite: [test-lib] target: ${{ fromJson(needs.build.outputs.test-lib-json) }} - os: [ubuntu-latest, macos-latest] # , windows-latest] + os: [ubuntu-latest, macos-latest, windows-latest] continue-on-error: [false] include: - suite: rpc target: '' os: ubuntu-latest continue-on-error: false - - suite: rpc - target: '' - os: macos-latest - continue-on-error: false + #- suite: rpc + # target: '' + # os: macos-latest + # continue-on-error: false #- suite: rpc # target: '' # os: windows-latest @@ -219,7 +236,7 @@ jobs: - uses: haskell/actions/setup@v1 with: - ghc-version: '8.10.2' + ghc-version: '8.10.3' - if: matrix.suite == 'rpc' uses: actions/setup-python@v2 @@ -242,6 +259,8 @@ jobs: path: bin - shell: bash + env: + BIN_ZIP_FILE: ${{ matrix.os }}-bin.zip run: | set -x chmod +x dist/bin/cryptol @@ -249,6 +268,10 @@ jobs: chmod +x dist/bin/cryptol-eval-server chmod +x bin/test-runner .github/ci.sh install_system_deps + .github/ci.sh deps bin/abc* + .github/ci.sh deps bin/cvc4* + .github/ci.sh deps bin/yices-smt2* + .github/ci.sh deps bin/z3* ghc_ver="$(ghc --numeric-version)" cp cabal.GHC-"$ghc_ver".config cabal.project.freeze cabal v2-update @@ -271,6 +294,7 @@ jobs: build-push-image: runs-on: ubuntu-latest needs: [config] + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' strategy: fail-fast: false matrix: diff --git a/CHANGES.md b/CHANGES.md index 18e36fd4..d27ab0ff 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,12 @@ -# Next Release +# NEXT + +## Language changes + +* Update the implementation of the Prelude function `sortBy` to use + a merge sort instead of an insertion sort. This improves the both + asymptotic and observed performance on sorting tasks. + +# 2.12.0 ## Language changes * Updates to the layout rule. We simplified the specification and made @@ -6,9 +14,76 @@ - Paren blocks nested in a layout block need to respect the indentation if the layout block - We allow nested layout blocks to have the same indentation, which is - conveninet when writing `private` declarations as they don't need to + convenient when writing `private` declarations as they don't need to be indented as long as they are at the end of the file. +* New enumeration forms `[x .. y by n]`, `[x .. y down by n]` have been + implemented. These new forms let the user explicitly specify + the stride for an enumeration, as opposed to the previous + `[x, y .. z]` form (where the stride was computed from `x` and `y`). + +* Nested modules are now available (from pull request #1048). For example, the following is now valid Cryptol: + + module SubmodTest where + + import submodule B as C + + submodule A where + propA = C::y > 5 + + submodule B where + y : Integer + y = 42 + +## New features + +* What4 prover backends now feature an improved multi-SAT procedure + which is significantly faster than the old algorithm. Thanks to + Levent Erkök for the suggestion. + +* There is a new `w4-abc` solver option, which communicates to ABC + as an external process via What4. + +* Expanded support for declaration forms in the REPL. You can now + define infix operators, type synonyms and mutually-recursive functions, + and state signatures and fixity declarations. Multiple declarations + can be combined into a single line by separating them with `;`, + which is necessary for stating a signature together with a + definition, etc. + +* There is a new `:set path` REPL option that provides an alternative to + `CRYPTOLPATH` for controlling where to search for imported modules + (issue #631). + +* The `cryptol-remote-api` server now natively supports HTTPS (issue + #1008), `newtype` values (issue #1033), and safety checking (issue + #1166). + +* Releases optionally include solvers (issue #1111). See the + `*-with-solvers*` files in the assets list for this release. + +## Bug fixes + +* Closed issues #422, #436, #619, #631, #633, #640, #680, #734, #735, + #759, #760, #764, #849, #996, #1000, #1008, #1019, #1032, #1033, + #1034, #1043, #1047, #1060, #1064, #1083, #1084, #1087, #1102, #1111, + #1113, #1117, #1125, #1133, #1142, #1144, #1145, #1146, #1157, #1160, + #1163, #1166, #1169, #1175, #1179, #1182, #1190, #1191, #1196, #1197, + #1204, #1209, #1210, #1213, #1216, #1223, #1226, #1238, #1239, #1240, + #1241, #1250, #1256, #1259, #1261, #1266, #1274, #1275, #1283, and + #1291. + +* Merged pull requests #1048, #1128, #1129, #1130, #1131, #1135, #1136, + #1137, #1139, #1148, #1149, #1150, #1152, #1154, #1156, #1158, #1159, + #1161, #1164, #1165, #1168, #1170, #1171, #1172, #1173, #1174, #1176, + #1181, #1183, #1186, #1188, #1192, #1193, #1194, #1195, #1199, #1200, + #1202, #1203, #1205, #1207, #1211, #1214, #1215, #1218, #1219, #1221, + #1224, #1225, #1227, #1228, #1230, #1231, #1232, #1234, #1242, #1243, + #1244, #1245, #1246, #1247, #1248, #1251, #1252, #1254, #1255, #1258, + #1263, #1265, #1268, #1269, #1270, #1271, #1272, #1273, #1276, #1281, + #1282, #1284, #1285, #1286, #1287, #1288, #1293, #1294, and #1295. + # 2.11.0 ## Language changes diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..aa09e0c3 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,86 @@ +# Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Project maintainers are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Project maintainers have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may +be reported to the project maintainers responsible for enforcement at +[cryptol@galois.com](mailto:cryptol@galois.com). All complaints will be +reviewed and investigated promptly and fairly. + +All project maintainers are obligated to respect the privacy and security of the +reporter of any incident. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available +at [https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/Dockerfile b/Dockerfile index 58739509..b8afbb1a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,62 +1,21 @@ -FROM debian:buster-20210511 AS solvers - -# Install needed packages for building -RUN apt-get update \ - && apt-get install -y curl cmake gcc g++ git libreadline-dev unzip -RUN useradd -m user -RUN install -d -o user -g user /solvers -USER user -WORKDIR /solvers -RUN mkdir -p rootfs/usr/local/bin - -# Get Z3 4.8.8 from GitHub -RUN curl -L https://github.com/Z3Prover/z3/releases/download/z3-4.8.8/z3-4.8.8-x64-ubuntu-16.04.zip --output z3.zip && \ - unzip z3.zip && \ - mv z3-*/bin/z3 rootfs/usr/local/bin - -# Build abc from GitHub. (Latest version.) -RUN git clone https://github.com/berkeley-abc/abc.git && \ - ( cd abc && make -j$(nproc) ) && \ - cp abc/abc rootfs/usr/local/bin - -# Build Boolector release 3.2.1 from source -RUN curl -L https://github.com/Boolector/boolector/archive/3.2.1.tar.gz | tar xz && \ - ( cd boolector* && ./contrib/setup-lingeling.sh && ./contrib/setup-btor2tools.sh && ./configure.sh && cd build && make -j$(nproc) ) && \ - cp boolector*/build/bin/boolector rootfs/usr/local/bin - -# Install Yices 2.6.2 -RUN curl -L https://yices.csl.sri.com/releases/2.6.2/yices-2.6.2-x86_64-pc-linux-gnu-static-gmp.tar.gz | tar xz && \ - cp yices*/bin/yices-smt2 rootfs/usr/local/bin \ - && cp yices*/bin/yices rootfs/usr/local/bin - -# Install CVC4 1.8 -# The latest CVC4 1.8 and the release version has a minor discrepency between it, causing sbv to fail -# https://github.com/CVC4/CVC4/releases/download/1.8/cvc4-1.8-x86_64-linux-opt -#RUN latest="$(curl -sSL 'http://cvc4.cs.stanford.edu/downloads/builds/x86_64-linux-opt/unstable/' | grep linux-opt | tail -n1 | sed -e 's/.*href="//' -e 's/\([^>]*\)">.*$/\1/')" && \ -RUN latest="cvc4-2021-03-13-x86_64-linux-opt" && \ - curl --output rootfs/usr/local/bin/cvc4 -sSL "https://cvc4.cs.stanford.edu/downloads/builds/x86_64-linux-opt/unstable/$latest" - -# Install MathSAT 5.6.3 - Uncomment if you are in compliance with MathSAT's license. -# RUN curl -L https://mathsat.fbk.eu/download.php?file=mathsat-5.6.3-linux-x86_64.tar.gz | tar xz -# RUN cp mathsat-5.6.3-linux-x86_64/bin/mathsat rootfs/usr/local/bin - -# Set executable and run tests -RUN chmod +x rootfs/usr/local/bin/* - FROM haskell:8.8.4 AS build -RUN apt-get update && apt-get install -y libncurses-dev -COPY --from=solvers /solvers/rootfs / +RUN apt-get update && apt-get install -y libncurses-dev unzip RUN useradd -m cryptol COPY --chown=cryptol:cryptol . /cryptol USER cryptol WORKDIR /cryptol +RUN mkdir -p rootfs/usr/local/bin +WORKDIR /cryptol/rootfs/usr/local/bin +RUN curl -o solvers.zip -sL "https://github.com/GaloisInc/what4-solvers/releases/download/snapshot-20210917/ubuntu-18.04-bin.zip" +RUN unzip solvers.zip && rm solvers.zip && chmod +x * +WORKDIR /cryptol ENV PATH=/cryptol/rootfs/usr/local/bin:$PATH +RUN z3 --version ARG CRYPTOLPATH="/cryptol/.cryptol" ENV LANG=C.UTF-8 \ LC_ALL=C.UTF-8 COPY cabal.GHC-8.8.4.config cabal.project.freeze -RUN mkdir -p rootfs/usr/local/bin RUN cabal v2-update && \ cabal v2-build -j cryptol:exe:cryptol && \ cp $(cabal v2-exec which cryptol) rootfs/usr/local/bin && \ @@ -66,8 +25,8 @@ ENV PATH=/usr/local/bin:/cryptol/rootfs/usr/local/bin:$PATH RUN ! $(cryptol -c ":s prover=yices" | tail -n +2 | grep -q .) \ # && ! $(cryptol -c ":s prover=mathsat" | tail -n +2 | grep -q .) \ && ! $(cryptol -c ":s prover=cvc4" | tail -n +2 | grep -q .) \ - # && ! $(cryptol -c ":s prover=abc" | tail -n +2 | grep -q .) \ - && ! $(cryptol -c ":s prover=boolector" | tail -n +2 | grep -q .) \ + && ! $(cryptol -c ":s prover=abc" | tail -n +2 | grep -q .) \ + # && ! $(cryptol -c ":s prover=boolector" | tail -n +2 | grep -q .) \ && ! $(cryptol -c ":s prover=z3" | tail -n +2 | grep -q .) RUN mkdir -p rootfs/"${CRYPTOLPATH}" \ && cp -r lib/* rootfs/"${CRYPTOLPATH}" @@ -80,7 +39,6 @@ RUN apt-get update \ && apt-get clean && rm -rf /var/lib/apt/lists/* RUN useradd -m cryptol && chown -R cryptol:cryptol /home/cryptol COPY --from=build /cryptol/rootfs / -COPY --from=solvers /solvers/rootfs / USER cryptol ENV LANG=C.UTF-8 \ LC_ALL=C.UTF-8 diff --git a/README.md b/README.md index 5ceb2422..d33affc9 100644 --- a/README.md +++ b/README.md @@ -46,9 +46,7 @@ Cryptol currently uses Microsoft Research's [Z3 SMT solver](https://github.com/Z3Prover/z3) by default to solve constraints during type checking, and as the default solver for the `:sat` and `:prove` commands. Cryptol generally requires the most recent version -of Z3, but you can see the specific version tested in CI by looking for -the `Z3_VERSION` setting in [this -file](https://github.com/GaloisInc/cryptol/blob/master/.github/workflows/ci.yml). +of Z3, but you can see the specific version tested in CI by looking [here](https://github.com/GaloisInc/what4-solvers/releases/tag/snapshot-20210917). You can download Z3 binaries for a variety of platforms from their [releases page](https://github.com/Z3Prover/z3/releases). If you @@ -77,7 +75,7 @@ Cryptol builds and runs on various flavors of Linux, Mac OS X, and Windows. We regularly build and test it in the following environments: - macOS 10.15, 64-bit -- Ubuntu 18.04, 64-bit +- Ubuntu 20.04, 64-bit - Windows Server 2019, 64-bit ## Prerequisites diff --git a/cabal.GHC-8.10.2.config b/cabal.GHC-8.10.2.config index cf733092..46dba0c2 100644 --- a/cabal.GHC-8.10.2.config +++ b/cabal.GHC-8.10.2.config @@ -161,7 +161,7 @@ constraints: any.Cabal ==3.2.0.0, any.semigroups ==0.19.1, semigroups +binary +bytestring -bytestring-builder +containers +deepseq +hashable +tagged +template-haskell +text +transformers +unordered-containers, any.simple-get-opt ==0.4, - any.simple-smt ==0.9.4, + any.simple-smt ==0.9.7, any.splitmix ==0.0.5, splitmix -optimised-mixer +random, any.statistics ==0.15.2.0, diff --git a/cabal.GHC-8.10.3.config b/cabal.GHC-8.10.3.config index 80b233b5..f562fbe0 100644 --- a/cabal.GHC-8.10.3.config +++ b/cabal.GHC-8.10.3.config @@ -201,7 +201,7 @@ constraints: any.Cabal ==3.2.1.0, any.simple-get-opt ==0.4, any.simple-sendfile ==0.2.30, simple-sendfile +allow-bsd, - any.simple-smt ==0.9.5, + any.simple-smt ==0.9.7, any.splitmix ==0.1.0.3, splitmix -optimised-mixer, any.statistics ==0.15.2.0, diff --git a/cabal.GHC-8.6.5.config b/cabal.GHC-8.6.5.config index b7e0d3cb..50a7b7fb 100644 --- a/cabal.GHC-8.6.5.config +++ b/cabal.GHC-8.6.5.config @@ -164,7 +164,7 @@ constraints: any.Cabal ==2.4.0.1, any.semigroups ==0.19.1, semigroups +binary +bytestring -bytestring-builder +containers +deepseq +hashable +tagged +template-haskell +text +transformers +unordered-containers, any.simple-get-opt ==0.4, - any.simple-smt ==0.9.4, + any.simple-smt ==0.9.7, any.splitmix ==0.0.4, splitmix -optimised-mixer +random, any.statistics ==0.15.2.0, diff --git a/cabal.GHC-8.8.4.config b/cabal.GHC-8.8.4.config index c5c7b8c3..0f67db8f 100644 --- a/cabal.GHC-8.8.4.config +++ b/cabal.GHC-8.8.4.config @@ -161,7 +161,7 @@ constraints: any.Cabal ==3.0.1.0, any.semigroups ==0.19.1, semigroups +binary +bytestring -bytestring-builder +containers +deepseq +hashable +tagged +template-haskell +text +transformers +unordered-containers, any.simple-get-opt ==0.4, - any.simple-smt ==0.9.4, + any.simple-smt ==0.9.7, any.splitmix ==0.0.4, splitmix -optimised-mixer +random, any.statistics ==0.15.2.0, diff --git a/cry b/cry index 5566a095..34301f16 100755 --- a/cry +++ b/cry @@ -23,6 +23,7 @@ Available commands: rpc-test Run RPC server tests rpc-docs Check that the RPC documentation is up-to-date exe-path Print the location of the local executable + check-docs Check the exercises embedded in the documentation EOM } @@ -97,6 +98,10 @@ case $COMMAND in $DIR/cryptol-remote-api/check_docs.sh ;; + check-docs) + cabal v2-build exe:check-exercises + find ./docs/ProgrammingCryptol -name '*.tex' -print0 | xargs -0 -n1 cabal v2-exec check-exercises + ;; help) show_usage && exit 0 ;; diff --git a/cryptol-remote-api/CHANGELOG.md b/cryptol-remote-api/CHANGELOG.md index 1e0344fd..f35e2cae 100644 --- a/cryptol-remote-api/CHANGELOG.md +++ b/cryptol-remote-api/CHANGELOG.md @@ -1,5 +1,13 @@ # Revision history for `cryptol-remote-api` and `cryptol-eval-server` +## 2.12.2 -- YYYY-MM-DD + +* NEW CHANGELOG ENTRIES SINCE 2.12.0 GO HERE + +## 2.12.0 -- 2021-11-19 + +* v2.12 release + ## 2.11.1 -- 2021-06-23 * HTTPS/TLS support added. Enable by running server in `http` mode with `--tls` diff --git a/cryptol-remote-api/Dockerfile b/cryptol-remote-api/Dockerfile index 58acb2c4..3fd27ce7 100644 --- a/cryptol-remote-api/Dockerfile +++ b/cryptol-remote-api/Dockerfile @@ -1,59 +1,14 @@ ARG GHCVER="8.10.3" ARG GHCVER_BOOTSTRAP="8.10.2" -FROM debian:buster-20210511 AS solvers - -# Install needed packages for building -RUN apt-get update \ - && apt-get install -y curl cmake gcc g++ git libreadline-dev unzip -RUN useradd -m user -RUN install -d -o user -g user /solvers -USER user -WORKDIR /solvers -RUN mkdir -p rootfs/usr/local/bin - -# Get Z3 4.8.8 from GitHub -RUN curl -L https://github.com/Z3Prover/z3/releases/download/z3-4.8.8/z3-4.8.8-x64-ubuntu-16.04.zip --output z3.zip && \ - unzip z3.zip && \ - mv z3-*/bin/z3 rootfs/usr/local/bin - -# Build abc from GitHub. (Latest version.) -RUN git clone https://github.com/berkeley-abc/abc.git && \ - ( cd abc && make -j$(nproc) ) && \ - cp abc/abc rootfs/usr/local/bin - -# Build Boolector release 3.2.1 from source -RUN curl -L https://github.com/Boolector/boolector/archive/3.2.1.tar.gz | tar xz && \ - ( cd boolector* && ./contrib/setup-lingeling.sh && ./contrib/setup-btor2tools.sh && ./configure.sh && cd build && make -j$(nproc) ) && \ - cp boolector*/build/bin/boolector rootfs/usr/local/bin - -# Install Yices 2.6.2 -RUN curl -L https://yices.csl.sri.com/releases/2.6.2/yices-2.6.2-x86_64-pc-linux-gnu-static-gmp.tar.gz | tar xz && \ - cp yices*/bin/yices-smt2 rootfs/usr/local/bin \ - && cp yices*/bin/yices rootfs/usr/local/bin - -# Install CVC4 1.8 -# The latest CVC4 1.8 and the release version has a minor discrepency between it, causing sbv to fail -# https://github.com/CVC4/CVC4/releases/download/1.8/cvc4-1.8-x86_64-linux-opt -RUN latest="$(curl -sSL 'http://cvc4.cs.stanford.edu/downloads/builds/x86_64-linux-opt/unstable/' | grep linux-opt | tail -n1 | sed -e 's/.*href="//' -e 's/\([^>]*\)">.*$/\1/')" && \ - curl --output rootfs/usr/local/bin/cvc4 -sSL "https://cvc4.cs.stanford.edu/downloads/builds/x86_64-linux-opt/unstable/$latest" - -# Install MathSAT 5.6.3 - Uncomment if you are in compliance with MathSAT's license. -# RUN curl -L https://mathsat.fbk.eu/download.php?file=mathsat-5.6.3-linux-x86_64.tar.gz | tar xz -# RUN cp mathsat-5.6.3-linux-x86_64/bin/mathsat rootfs/usr/local/bin - -# Set executable and run tests -RUN chmod +x rootfs/usr/local/bin/* - FROM debian:buster-20210511 AS toolchain ARG PORTABILITY=false -RUN apt-get update && apt-get install -y libncurses-dev libz-dev \ +RUN apt-get update && apt-get install -y libncurses-dev libz-dev unzip \ build-essential curl libffi-dev libffi6 libgmp-dev libgmp10 libncurses-dev libncurses5 libtinfo5 libnuma-dev \ $(if ${PORTABILITY}; then echo git autoconf python3; fi) ENV GHCUP_INSTALL_BASE_PREFIX=/opt \ PATH=/opt/.ghcup/bin:$PATH RUN curl -o /usr/local/bin/ghcup "https://downloads.haskell.org/~ghcup/0.1.14/x86_64-linux-ghcup-0.1.14" && \ chmod +x /usr/local/bin/ghcup -COPY --from=solvers /solvers/rootfs / RUN ghcup install cabal --set ENV PATH=/root/.cabal/bin:$PATH ADD ./cryptol-remote-api/ghc-portability.patch . @@ -101,6 +56,9 @@ RUN cabal v2-update && \ ENV PATH=/usr/local/bin:/cryptol/rootfs/usr/local/bin:$PATH RUN mkdir -p rootfs/"${CRYPTOLPATH}" \ && cp -r lib/* rootfs/"${CRYPTOLPATH}" +WORKDIR /cryptol/rootfs/usr/local/bin +RUN curl -sL -o solvers.zip "https://github.com/GaloisInc/what4-solvers/releases/download/snapshot-20210917/ubuntu-18.04-bin.zip" && \ + unzip solvers.zip && rm solvers.zip && chmod +x * USER root RUN chown -R root:root /cryptol/rootfs @@ -110,7 +68,6 @@ RUN apt-get update \ && apt-get clean && rm -rf /var/lib/apt/lists/* RUN useradd -m cryptol && chown -R cryptol:cryptol /home/cryptol COPY --from=build /cryptol/rootfs / -COPY --from=solvers /solvers/rootfs / USER cryptol ENV LANG=C.UTF-8 \ LC_ALL=C.UTF-8 diff --git a/cryptol-remote-api/cryptol-eval-server/Main.hs b/cryptol-remote-api/cryptol-eval-server/Main.hs index aad84445..b64cfcdb 100644 --- a/cryptol-remote-api/cryptol-eval-server/Main.hs +++ b/cryptol-remote-api/cryptol-eval-server/Main.hs @@ -22,6 +22,8 @@ import CryptolServer.Check ( check, checkDescr ) import CryptolServer.ClearState ( clearState, clearStateDescr, clearAllStates, clearAllStatesDescr) import Cryptol.Eval (EvalOpts(..), defaultPPOpts) +import CryptolServer.Interrupt + ( interruptServer, interruptServerDescr ) import Cryptol.ModuleSystem (ModuleInput(..), loadModuleByPath, loadModuleByName) import Cryptol.ModuleSystem.Monad (runModuleM, setFocusedModule) import Cryptol.TypeCheck.AST (mName) @@ -166,4 +168,8 @@ cryptolEvalMethods = "clear all states" clearAllStatesDescr clearAllStates + , notification + "interrupt" + interruptServerDescr + interruptServer ] diff --git a/cryptol-remote-api/cryptol-remote-api.cabal b/cryptol-remote-api/cryptol-remote-api.cabal index 4cd02c5e..9dfcb34c 100644 --- a/cryptol-remote-api/cryptol-remote-api.cabal +++ b/cryptol-remote-api/cryptol-remote-api.cabal @@ -1,10 +1,10 @@ cabal-version: 2.4 name: cryptol-remote-api -version: 0.1.0.0 +version: 2.12.1 license: BSD-3-Clause license-file: LICENSE -author: David Thrane Christiansen -maintainer: dtc@galois.com +author: Galois, Inc. +maintainer: cryptol-team@galois.com category: Language extra-source-files: CHANGELOG.md @@ -42,7 +42,7 @@ common deps build-depends: base >=4.11.1.0 && <4.15, argo, - aeson >= 1.4.2, + aeson >= 1.4.2 && < 2.1, base64-bytestring >= 1.0, bytestring ^>= 0.10.8, containers >=0.6.0.1 && <0.7, @@ -74,12 +74,16 @@ library CryptolServer.ExtendSearchPath CryptolServer.Exceptions CryptolServer.FocusedModule + CryptolServer.Interrupt CryptolServer.LoadModule CryptolServer.Options CryptolServer.Names CryptolServer.Sat CryptolServer.TypeCheck + other-modules: + CryptolServer.AesonCompat + executable cryptol-remote-api import: deps, warnings, errors main-is: Main.hs @@ -90,7 +94,8 @@ executable cryptol-remote-api ghc-options: -threaded -rtsopts -with-rtsopts=-xb0x200000000 build-depends: - cryptol-remote-api, sbv + cryptol-remote-api, + sbv if os(linux) && flag(static) ld-options: -static -pthread diff --git a/cryptol-remote-api/cryptol-remote-api/Main.hs b/cryptol-remote-api/cryptol-remote-api/Main.hs index 50df6f28..fd9b0639 100644 --- a/cryptol-remote-api/cryptol-remote-api/Main.hs +++ b/cryptol-remote-api/cryptol-remote-api/Main.hs @@ -26,6 +26,8 @@ import CryptolServer.ExtendSearchPath ( extSearchPath, extSearchPathDescr ) import CryptolServer.FocusedModule ( focusedModule, focusedModuleDescr ) +import CryptolServer.Interrupt + ( interruptServer, interruptServerDescr ) import CryptolServer.LoadModule ( loadFile, loadFileDescr, loadModule, loadModuleDescr ) import CryptolServer.Names ( visibleNames, visibleNamesDescr ) @@ -113,4 +115,8 @@ cryptolMethods = "prove or satisfy" proveSatDescr proveSat + , notification + "interrupt" + interruptServerDescr + interruptServer ] diff --git a/cryptol-remote-api/docs/Cryptol.rst b/cryptol-remote-api/docs/Cryptol.rst index d2adc682..38f6144d 100644 --- a/cryptol-remote-api/docs/Cryptol.rst +++ b/cryptol-remote-api/docs/Cryptol.rst @@ -557,7 +557,7 @@ Parameter fields ``prover`` - The SMT solver to use to check for satisfiability. I.e., one of the following: ``w4-cvc4``, ``w4-yices``, ``w4-z3``, ``w4-boolector``, ``w4-offline``, ``w4-any``, ``cvc4``, ``yices``, ``z3``, ``boolector``, ``mathsat``, ``abc``, ``offline``, ``any``, ``sbv-cvc4``, ``sbv-yices``, ``sbv-z3``, ``sbv-boolector``, ``sbv-mathsat``, ``sbv-abc``, ``sbv-offline``, ``sbv-any``. + The SMT solver to use to check for satisfiability. I.e., one of the following: ``w4-cvc4``, ``w4-yices``, ``w4-z3``, ``w4-boolector``, ``w4-abc``, ``w4-offline``, ``w4-any``, ``cvc4``, ``yices``, ``z3``, ``boolector``, ``mathsat``, ``abc``, ``offline``, ``any``, ``sbv-cvc4``, ``sbv-yices``, ``sbv-z3``, ``sbv-boolector``, ``sbv-mathsat``, ``sbv-abc``, ``sbv-offline``, ``sbv-any``. @@ -611,6 +611,24 @@ Return fields +interrupt (notification) +~~~~~~~~~~~~~~~~~~~~~~~~ + +Interrupt the server, terminating it's current task (if one exists). + +Parameter fields +++++++++++++++++ + +No parameters + + +Return fields ++++++++++++++ + +No return fields + + + diff --git a/cryptol-remote-api/python/.gitignore b/cryptol-remote-api/python/.gitignore index 7f5679ad..15b02a54 100644 --- a/cryptol-remote-api/python/.gitignore +++ b/cryptol-remote-api/python/.gitignore @@ -128,3 +128,8 @@ dmypy.json # Pyre type checker .pyre/ + +# Files generated from running tests/cryptol/test_cryptol_api.py +*.crt +*.csr +*.key diff --git a/cryptol-remote-api/python/CHANGELOG.md b/cryptol-remote-api/python/CHANGELOG.md index 5eb58241..9891041a 100644 --- a/cryptol-remote-api/python/CHANGELOG.md +++ b/cryptol-remote-api/python/CHANGELOG.md @@ -1,5 +1,59 @@ # Revision history for `cryptol` Python package +## 2.12.4 -- YYYY-MM-DD + +* NEW CHANGELOG ENTRIES SINCE 2.12.2 GO HERE + +## 2.12.2 -- 2021-12-21 + +* Add an interface for Cryptol quasiquotation using an f-string-like syntax, + see `tests/cryptol/test_quoting` for some examples. +* Fix a bug with the client's `W4_ABC` solver, add a `W4_ANY` solver. +* Deprecate `CryptolType.from_python` and `CryptolType.convert` +* Remove `CryptolType` arguments to `to_cryptol` and `__to_cryptol__` + +## 2.12.0 -- 2021-11-19 + +* v2.12 release in tandem with Cryptol 2.12 release. See Cryptol release 2.12 + release notes for relevant Cryptol changes. No notable changes to RPC server + or client since 2.11.7. + +## 2.11.7 -- 2021-09-22 + +* Add a synchronous, type-annotated interface (`synchronous.py`). To use this + interface, connect using `c = cryptol.sync.connect()` and remove all + `.result()` calls. +* Add a single-connection, synchronous, type-annotated interface based on the + above. To use this interface, add `from cryptol.single_connection import *`, + connect using `connect()`, replace `c.eval(...).result()` with + `cry_eval(...)`, remove all `c.` prefixes, and remove all `.result()` calls. +* Update most of the tests to use the single-connection interface. + +## 2.11.6 -- 2021-09-10 + +* Add a `timeout` field to the `CryptolConnection` class which can be used + to set a default timeout for all RPC interactions. +* Add an optional `timeout` keyword parameter to each `CryptolConnection` method + which can specify a timeout for a particular method call. +* Add an `interrupt` method to the `CryptolConnection` class which interrupts + any active requests on the server. + +## 2.11.5 -- 2021-08-25 + +* From argo: Change the behavior of the `Command` `state` method so that after + a `Command` raises an exception, subsequent interactions will not also raise + the same exception. + +## 2.11.4 -- 2021-07-22 + +* Add client logging option. See the `log_dest` keyword argument on + `cryptol.connect` or the `logging` method on a `CryptolConnection` object. + +## 2.11.3 -- 2021-07-20 + +* Removed automatic reset from `CryptolConnection.__del__`. + + ## 2.11.2 -- 2021-06-23 * Ability to leverage HTTPS/TLS while _disabling_ verification of SSL certificates. diff --git a/cryptol-remote-api/python/cryptol/__init__.py b/cryptol-remote-api/python/cryptol/__init__.py index 751d0d0c..f88edf8e 100644 --- a/cryptol-remote-api/python/cryptol/__init__.py +++ b/cryptol-remote-api/python/cryptol/__init__.py @@ -16,17 +16,15 @@ from argo_client.connection import DynamicSocketProcess, ServerConnection, Serve from . import cryptoltypes from . import solver from .bitvector import BV +from .cryptoltypes import fail_with +from .quoting import cry, cry_f from .commands import * from .connection import * +# import everything from `.synchronous` except `connect` and `connect_stdio` +# (since functions with those names were already imported from `.connection`) +from .synchronous import Qed, Safe, Counterexample, Satisfiable, Unsatisfiable, CryptolSyncConnection +# and add an alias `sync` for the `synchronous` module +from . import synchronous +sync = synchronous - -__all__ = ['bitvector', 'commands', 'connections', 'cryptoltypes', 'solver'] - - -def fail_with(x : Exception) -> NoReturn: - "Raise an exception. This is valid in expression positions." - raise x - - -def cry(string : str) -> cryptoltypes.CryptolCode: - return cryptoltypes.CryptolLiteral(string) +__all__ = ['bitvector', 'commands', 'connection', 'cryptoltypes', 'opaque', 'quoting', 'single_connection', 'solver', 'synchronous'] diff --git a/cryptol-remote-api/python/cryptol/bitvector.py b/cryptol-remote-api/python/cryptol/bitvector.py index 424645ab..ec9e3111 100644 --- a/cryptol-remote-api/python/cryptol/bitvector.py +++ b/cryptol-remote-api/python/cryptol/bitvector.py @@ -1,8 +1,11 @@ from functools import reduce from typing import Any, List, Union, Optional, overload +from typing_extensions import Literal from BitVector import BitVector #type: ignore +ByteOrder = Union[Literal['little'], Literal['big']] + class BV: """A class representing a cryptol bit vector (i.e., a sequence of bits). @@ -211,7 +214,7 @@ class BV: return bin(self).count("1") @staticmethod - def from_bytes(bs : bytes, *, size : Optional[int] =None, byteorder : str ='big') -> 'BV': + def from_bytes(bs : Union[bytes,bytearray], *, size : Optional[int] = None, byteorder : ByteOrder = 'big') -> 'BV': """Convert the given bytes ``bs`` into a ``BV``. :param bs: Bytes to convert to a ``BV``. @@ -221,11 +224,13 @@ class BV: ``'big'``, ``little`` being the other acceptable value. Equivalent to the ``byteorder`` parameter from Python's ``int.from_bytes``.""" - if not isinstance(bs, bytes): - raise ValueError("from_bytes given not bytes value: {bs!r}") + if isinstance(bs, bytearray): + bs = bytes(bs) + elif not isinstance(bs, bytes): + raise ValueError(f"from_bytes given not a bytearray or bytes value: {bs!r}") if not byteorder == 'little' and not byteorder == 'big': - raise ValueError("from_bytes given not bytes value: {bs!r}") + raise ValueError("byteorder must be either 'little' or 'big'") if size == None: return BV(len(bs) * 8, int.from_bytes(bs, byteorder=byteorder)) diff --git a/cryptol-remote-api/python/cryptol/commands.py b/cryptol-remote-api/python/cryptol/commands.py index 888aee74..2a49640d 100644 --- a/cryptol-remote-api/python/cryptol/commands.py +++ b/cryptol-remote-api/python/cryptol/commands.py @@ -2,9 +2,10 @@ from __future__ import annotations import base64 +from abc import ABC from enum import Enum from dataclasses import dataclass -from typing import Any, List, Optional, Union +from typing import Any, Tuple, List, Dict, Optional, Union from typing_extensions import Literal import argo_client.interaction as argo @@ -20,7 +21,9 @@ def extend_hex(string : str) -> str: else: return string -def from_cryptol_arg(val : Any) -> Any: +CryptolValue = Union[bool, int, BV, Tuple, List, Dict, OpaqueValue] + +def from_cryptol_arg(val : Any) -> CryptolValue: """Return the canonical Python value for a Cryptol JSON value.""" if isinstance(val, bool): return val @@ -33,7 +36,7 @@ def from_cryptol_arg(val : Any) -> Any: elif tag == 'tuple': return tuple(from_cryptol_arg(x) for x in val['data']) elif tag == 'record': - return {k : from_cryptol_arg(val[k]) for k in val['data']} + return {k : from_cryptol_arg(val['data'][k]) for k in val['data']} elif tag == 'sequence': return [from_cryptol_arg(v) for v in val['data']] elif tag == 'bits': @@ -59,48 +62,59 @@ def from_cryptol_arg(val : Any) -> Any: class CryptolLoadModule(argo.Command): - def __init__(self, connection : HasProtocolState, mod_name : str) -> None: - super(CryptolLoadModule, self).__init__('load module', {'module name': mod_name}, connection) + def __init__(self, connection : HasProtocolState, mod_name : str, timeout: Optional[float]) -> None: + super(CryptolLoadModule, self).__init__('load module', {'module name': mod_name}, connection, timeout=timeout) def process_result(self, res : Any) -> Any: return res class CryptolLoadFile(argo.Command): - def __init__(self, connection : HasProtocolState, filename : str) -> None: - super(CryptolLoadFile, self).__init__('load file', {'file': filename}, connection) + def __init__(self, connection : HasProtocolState, filename : str, timeout: Optional[float]) -> None: + super(CryptolLoadFile, self).__init__('load file', {'file': filename}, connection, timeout=timeout) def process_result(self, res : Any) -> Any: return res class CryptolExtendSearchPath(argo.Command): - def __init__(self, connection : HasProtocolState, dirs : List[str]) -> None: - super(CryptolExtendSearchPath, self).__init__('extend search path', {'paths': dirs}, connection) + def __init__(self, connection : HasProtocolState, dirs : List[str], timeout: Optional[float]) -> None: + super(CryptolExtendSearchPath, self).__init__('extend search path', {'paths': dirs}, connection, timeout=timeout) def process_result(self, res : Any) -> Any: return res -class CryptolEvalExpr(argo.Command): - def __init__(self, connection : HasProtocolState, expr : Any) -> None: - super(CryptolEvalExpr, self).__init__( +class CryptolEvalExprRaw(argo.Command): + def __init__(self, connection : HasProtocolState, expr : Any, timeout: Optional[float]) -> None: + super(CryptolEvalExprRaw, self).__init__( 'evaluate expression', {'expression': expr}, - connection + connection, + timeout=timeout ) def process_result(self, res : Any) -> Any: - return from_cryptol_arg(res['value']) + return res['value'] -class CryptolCall(argo.Command): - def __init__(self, connection : HasProtocolState, fun : str, args : List[Any]) -> None: - super(CryptolCall, self).__init__( +class CryptolEvalExpr(CryptolEvalExprRaw): + def process_result(self, res : Any) -> Any: + return from_cryptol_arg(super(CryptolEvalExpr, self).process_result(res)) + + +class CryptolCallRaw(argo.Command): + def __init__(self, connection : HasProtocolState, fun : str, args : List[Any], timeout: Optional[float]) -> None: + super(CryptolCallRaw, self).__init__( 'call', {'function': fun, 'arguments': args}, - connection + connection, + timeout=timeout ) def process_result(self, res : Any) -> Any: - return from_cryptol_arg(res['value']) + return res['value'] + +class CryptolCall(CryptolCallRaw): + def process_result(self, res : Any) -> Any: + return from_cryptol_arg(super(CryptolCall, self).process_result(res)) @dataclass @@ -111,75 +125,103 @@ class CheckReport: error_msg: Optional[str] tests_run: int tests_possible: Optional[int] + + def __bool__(self) -> bool: + return self.success -class CryptolCheck(argo.Command): - def __init__(self, connection : HasProtocolState, expr : Any, num_tests : Union[Literal['all'],int, None]) -> None: +def to_check_report(res : Any) -> CheckReport: + if res['result'] == 'pass': + return CheckReport( + success=True, + args=[], + error_msg = None, + tests_run=res['tests run'], + tests_possible=res['tests possible']) + elif res['result'] == 'fail': + return CheckReport( + success=False, + args=[from_cryptol_arg(arg['expr']) for arg in res['arguments']], + error_msg = None, + tests_run=res['tests run'], + tests_possible=res['tests possible']) + elif res['result'] == 'error': + return CheckReport( + success=False, + args=[from_cryptol_arg(arg['expr']) for arg in res['arguments']], + error_msg = res['error message'], + tests_run=res['tests run'], + tests_possible=res['tests possible']) + else: + raise ValueError("Unknown check result " + str(res)) + +class CryptolCheckRaw(argo.Command): + def __init__(self, connection : HasProtocolState, + expr : Any, + num_tests : Union[Literal['all'],int, None], + timeout: Optional[float]) -> None: if num_tests: args = {'expression': expr, 'number of tests':num_tests} else: args = {'expression': expr} - super(CryptolCheck, self).__init__( + super(CryptolCheckRaw, self).__init__( 'check', args, - connection + connection, + timeout=timeout ) + def process_result(self, res : Any) -> Any: + return res + +class CryptolCheck(CryptolCheckRaw): def process_result(self, res : Any) -> 'CheckReport': - if res['result'] == 'pass': - return CheckReport( - success=True, - args=[], - error_msg = None, - tests_run=res['tests run'], - tests_possible=res['tests possible']) - elif res['result'] == 'fail': - return CheckReport( - success=False, - args=[from_cryptol_arg(arg['expr']) for arg in res['arguments']], - error_msg = None, - tests_run=res['tests run'], - tests_possible=res['tests possible']) - elif res['result'] == 'error': - return CheckReport( - success=False, - args=[from_cryptol_arg(arg['expr']) for arg in res['arguments']], - error_msg = res['error message'], - tests_run=res['tests run'], - tests_possible=res['tests possible']) - else: - raise ValueError("Unknown check result " + str(res)) + return to_check_report(super(CryptolCheck, self).process_result(res)) class CryptolCheckType(argo.Command): - def __init__(self, connection : HasProtocolState, expr : Any) -> None: + def __init__(self, connection : HasProtocolState, expr : Any, timeout: Optional[float]) -> None: super(CryptolCheckType, self).__init__( 'check type', {'expression': expr}, - connection + connection, + timeout=timeout ) def process_result(self, res : Any) -> Any: return res['type schema'] + class SmtQueryType(str, Enum): PROVE = 'prove' SAFE = 'safe' SAT = 'sat' -class CryptolProveSat(argo.Command): - def __init__(self, connection : HasProtocolState, qtype : SmtQueryType, expr : Any, solver : Solver, count : Optional[int]) -> None: - super(CryptolProveSat, self).__init__( +class CryptolProveSatRaw(argo.Command): + def __init__(self, + connection : HasProtocolState, + qtype : SmtQueryType, + expr : Any, + solver : Solver, + count : Optional[int], + timeout: Optional[float]) -> None: + super(CryptolProveSatRaw, self).__init__( 'prove or satisfy', {'query type': qtype, 'expression': expr, 'prover': solver.name(), 'hash consing': "true" if solver.hash_consing() else "false", 'result count': 'all' if count is None else count}, - connection + connection, + timeout=timeout ) self.qtype = qtype def process_result(self, res : Any) -> Any: + return res + +class CryptolProveSat(CryptolProveSatRaw): + def process_result(self, res : Any) -> Any: + res = super(CryptolProveSat, self).process_result(res) if res['result'] == 'unsatisfiable': if self.qtype == SmtQueryType.SAT: return False @@ -199,36 +241,49 @@ class CryptolProveSat(argo.Command): else: raise ValueError("Unknown SMT result: " + str(res)) +class CryptolProveRaw(CryptolProveSatRaw): + def __init__(self, connection : HasProtocolState, expr : Any, solver : Solver, timeout: Optional[float]) -> None: + super(CryptolProveRaw, self).__init__(connection, SmtQueryType.PROVE, expr, solver, 1, timeout) class CryptolProve(CryptolProveSat): - def __init__(self, connection : HasProtocolState, expr : Any, solver : Solver) -> None: - super(CryptolProve, self).__init__(connection, SmtQueryType.PROVE, expr, solver, 1) + def __init__(self, connection : HasProtocolState, expr : Any, solver : Solver, timeout: Optional[float]) -> None: + super(CryptolProve, self).__init__(connection, SmtQueryType.PROVE, expr, solver, 1, timeout=timeout) +class CryptolSatRaw(CryptolProveSatRaw): + def __init__(self, connection : HasProtocolState, expr : Any, solver : Solver, count : int, timeout: Optional[float]) -> None: + super(CryptolSatRaw, self).__init__(connection, SmtQueryType.SAT, expr, solver, count, timeout=timeout) class CryptolSat(CryptolProveSat): - def __init__(self, connection : HasProtocolState, expr : Any, solver : Solver, count : int) -> None: - super(CryptolSat, self).__init__(connection, SmtQueryType.SAT, expr, solver, count) + def __init__(self, connection : HasProtocolState, expr : Any, solver : Solver, count : int, timeout: Optional[float]) -> None: + super(CryptolSat, self).__init__(connection, SmtQueryType.SAT, expr, solver, count, timeout=timeout) +class CryptolSafeRaw(CryptolProveSatRaw): + def __init__(self, connection : HasProtocolState, expr : Any, solver : Solver, timeout: Optional[float]) -> None: + super(CryptolSafeRaw, self).__init__(connection, SmtQueryType.SAFE, expr, solver, 1, timeout=timeout) class CryptolSafe(CryptolProveSat): - def __init__(self, connection : HasProtocolState, expr : Any, solver : Solver) -> None: - super(CryptolSafe, self).__init__(connection, SmtQueryType.SAFE, expr, solver, 1) + def __init__(self, connection : HasProtocolState, expr : Any, solver : Solver, timeout: Optional[float]) -> None: + super(CryptolSafe, self).__init__(connection, SmtQueryType.SAFE, expr, solver, 1, timeout=timeout) + class CryptolNames(argo.Command): - def __init__(self, connection : HasProtocolState) -> None: - super(CryptolNames, self).__init__('visible names', {}, connection) + def __init__(self, connection : HasProtocolState, timeout: Optional[float]) -> None: + super(CryptolNames, self).__init__('visible names', {}, connection, timeout=timeout) def process_result(self, res : Any) -> Any: return res + class CryptolFocusedModule(argo.Command): - def __init__(self, connection : HasProtocolState) -> None: + def __init__(self, connection : HasProtocolState, timeout: Optional[float]) -> None: super(CryptolFocusedModule, self).__init__( 'focused module', {}, - connection + connection, + timeout=timeout ) def process_result(self, res : Any) -> Any: return res + class CryptolReset(argo.Notification): def __init__(self, connection : HasProtocolState) -> None: super(CryptolReset, self).__init__( @@ -237,6 +292,7 @@ class CryptolReset(argo.Notification): connection ) + class CryptolResetServer(argo.Notification): def __init__(self, connection : HasProtocolState) -> None: super(CryptolResetServer, self).__init__( @@ -244,3 +300,11 @@ class CryptolResetServer(argo.Notification): {}, connection ) + +class CryptolInterrupt(argo.Notification): + def __init__(self, connection : HasProtocolState) -> None: + super(CryptolInterrupt, self).__init__( + 'interrupt', + {}, + connection + ) diff --git a/cryptol-remote-api/python/cryptol/connection.py b/cryptol-remote-api/python/cryptol/connection.py index 6581ee0d..51d565e4 100644 --- a/cryptol-remote-api/python/cryptol/connection.py +++ b/cryptol-remote-api/python/cryptol/connection.py @@ -2,15 +2,18 @@ from __future__ import annotations import os +import sys from distutils.spawn import find_executable -from typing import Any, List, Optional, Union +from typing import Any, List, Optional, Union, TextIO from typing_extensions import Literal import argo_client.interaction as argo from argo_client.connection import DynamicSocketProcess, ServerConnection, ServerProcess, StdIOProcess, HttpProcess +from .custom_fstring import * +from .quoting import * from . import cryptoltypes from . import solver -from .commands import * +from .commands import * def connect(command : Optional[str]=None, @@ -18,7 +21,9 @@ def connect(command : Optional[str]=None, cryptol_path : Optional[str] = None, url : Optional[str] = None, reset_server : bool = False, - verify : Union[bool, str] = True) -> CryptolConnection: + verify : Union[bool, str] = True, + log_dest : Optional[TextIO] = None, + timeout : Optional[float] = None) -> CryptolConnection: """ Connect to a (possibly new) Cryptol server process. @@ -39,6 +44,14 @@ def connect(command : Optional[str]=None, only has an affect when ``connect`` is called with a ``url`` parameter or when the ``CRYPTOL_SERVER_URL`` environment variable is set. + :param log_dest: A destination to log JSON requests/responses to, e.g. ``log_dest=sys.stderr`` + will print traffic to ``stderr``, ``log_dest=open('foo.log', 'w')`` will log to ``foo.log``, + etc. + + :param timeout: Optional default timeout (in seconds) for methods. Can be modified/read via the + `timeout` member field on a `CryptolConnection` or the `get_default_timeout` and + `set_default_timeout` methods. Method invocations which specify the optional `timeout` keyword + parameter will cause the default to be ignored for that method. If no ``command`` or ``url`` parameters are provided, the following are attempted in order: @@ -56,27 +69,27 @@ def connect(command : Optional[str]=None, if command is not None: if url is not None: raise ValueError("A Cryptol server URL cannot be specified with a command currently.") - c = CryptolConnection(command, cryptol_path) + c = CryptolConnection(command, cryptol_path, log_dest=log_dest, timeout=timeout) # User-passed url? if c is None and url is not None: - c = CryptolConnection(ServerConnection(HttpProcess(url, verify=verify)), cryptol_path) + c = CryptolConnection(ServerConnection(HttpProcess(url, verify=verify)), cryptol_path, log_dest=log_dest) # Check `CRYPTOL_SERVER` env var if no connection identified yet if c is None: command = os.getenv('CRYPTOL_SERVER') if command is not None: command = find_executable(command) if command is not None: - c = CryptolConnection(command+" socket", cryptol_path=cryptol_path) + c = CryptolConnection(command+" socket", cryptol_path=cryptol_path, log_dest=log_dest, timeout=timeout) # Check `CRYPTOL_SERVER_URL` env var if no connection identified yet if c is None: url = os.getenv('CRYPTOL_SERVER_URL') if url is not None: - c = CryptolConnection(ServerConnection(HttpProcess(url,verify=verify)), cryptol_path) + c = CryptolConnection(ServerConnection(HttpProcess(url,verify=verify)), cryptol_path, log_dest=log_dest, timeout=timeout) # Check if `cryptol-remote-api` is in the PATH if no connection identified yet if c is None: command = find_executable('cryptol-remote-api') if command is not None: - c = CryptolConnection(command+" socket", cryptol_path=cryptol_path) + c = CryptolConnection(command+" socket", cryptol_path=cryptol_path, log_dest=log_dest, timeout=timeout) # Raise an error if still no connection identified yet if c is not None: if reset_server: @@ -92,7 +105,10 @@ def connect(command : Optional[str]=None, -def connect_stdio(command : str, cryptol_path : Optional[str] = None) -> CryptolConnection: +def connect_stdio(command : str, + cryptol_path : Optional[str] = None, + log_dest : Optional[TextIO] = None, + timeout : Optional[float] = None) -> CryptolConnection: """Start a new connection to a new Cryptol server process. :param command: The command to launch the Cryptol server. @@ -100,10 +116,19 @@ def connect_stdio(command : str, cryptol_path : Optional[str] = None) -> Cryptol :param cryptol_path: An optional replacement for the contents of the ``CRYPTOLPATH`` environment variable. + :param log_dest: A destination to log JSON requests/responses to, e.g. ``log_dest=sys.stderr`` + will print traffic to ``stderr``, ``log_dest=open('foo.log', 'w')`` will log to ``foo.log``, + etc. + + :param timeout: Optional default timeout (in seconds) for methods. Can be modified/read via the + `timeout` member field on a `CryptolConnection` or the `get_default_timeout` and + `set_default_timeout` methods. Method invocations which specify the optional `timeout` keyword + parameter will cause the default to be ignored for that method. + """ conn = CryptolStdIOProcess(command, cryptol_path=cryptol_path) - return CryptolConnection(conn) + return CryptolConnection(conn, log_dest=log_dest, timeout=timeout) class CryptolConnection: @@ -120,21 +145,36 @@ class CryptolConnection: sequential state dependencies between commands. """ most_recent_result : Optional[argo.Interaction] - proc: ServerProcess + + timeout : Optional[float] + """(Optional) default timeout in seconds for methods.""" def __init__(self, command_or_connection : Union[str, ServerConnection, ServerProcess], - cryptol_path : Optional[str] = None) -> None: + cryptol_path : Optional[str] = None, + *, + log_dest : Optional[TextIO] = None, + timeout : Optional[float] = None) -> None: self.most_recent_result = None + self.timeout = timeout if isinstance(command_or_connection, ServerProcess): - self.proc = command_or_connection - self.server_connection = ServerConnection(self.proc) + self.server_connection = ServerConnection(command_or_connection) elif isinstance(command_or_connection, str): - self.proc = CryptolDynamicSocketProcess(command_or_connection, cryptol_path=cryptol_path) - self.server_connection = ServerConnection(self.proc) + self.server_connection = ServerConnection(CryptolDynamicSocketProcess(command_or_connection, cryptol_path=cryptol_path)) else: self.server_connection = command_or_connection + if log_dest: + self.logging(on=True,dest=log_dest) + + def get_default_timeout(self) -> Optional[float]: + """Get the value of the optional default timeout for methods (in seconds).""" + return self.timeout + + def set_default_timeout(self, timeout : Optional[float]) -> None: + """Set the value of the optional default timeout for methods (in seconds).""" + self.timeout = timeout + # Currently disabled in (overly?) conservative effort to not accidentally # duplicate and share mutable state. @@ -154,96 +194,204 @@ class CryptolConnection: return self.most_recent_result.state() # Protocol messages - def load_file(self, filename : str) -> argo.Command: + def load_file(self, filename : str, *, timeout:Optional[float] = None) -> argo.Command: """Load a filename as a Cryptol module, like ``:load`` at the Cryptol REPL. + + :param timeout: Optional timeout for this request (in seconds). """ - self.most_recent_result = CryptolLoadFile(self, filename) + timeout = timeout if timeout is not None else self.timeout + self.most_recent_result = CryptolLoadFile(self, filename, timeout) return self.most_recent_result - def load_module(self, module_name : str) -> argo.Command: - """Load a Cryptol module, like ``:module`` at the Cryptol REPL.""" - self.most_recent_result = CryptolLoadModule(self, module_name) - return self.most_recent_result + def load_module(self, module_name : str, *, timeout:Optional[float] = None) -> argo.Command: + """Load a Cryptol module, like ``:module`` at the Cryptol REPL. - def eval(self, expression : Any) -> argo.Command: - """Evaluate a Cryptol expression, represented according to - :ref:`cryptol-json-expression`, with Python datatypes standing - for their JSON equivalents. + :param timeout: Optional timeout for this request (in seconds). """ - self.most_recent_result = CryptolEvalExpr(self, expression) + timeout = timeout if timeout is not None else self.timeout + self.most_recent_result = CryptolLoadModule(self, module_name, timeout) return self.most_recent_result - def evaluate_expression(self, expression : Any) -> argo.Command: + def eval_raw(self, expression : Any, *, timeout:Optional[float] = None) -> argo.Command: + """Like the member method ``eval``, but does not call + ``from_cryptol_arg`` on the ``.result()``. + + :param timeout: Optional timeout for this request (in seconds). + """ + if hasattr(expression, '__to_cryptol__'): + expression = cryptoltypes.to_cryptol(expression) + timeout = timeout if timeout is not None else self.timeout + self.most_recent_result = CryptolEvalExprRaw(self, expression, timeout) + return self.most_recent_result + + def eval(self, expression : Any, *, timeout:Optional[float] = None) -> argo.Command: + """Evaluate a Cryptol expression, with the result represented + according to :ref:`cryptol-json-expression`, with Python datatypes + standing for their JSON equivalents. + + :param timeout: Optional timeout for this request (in seconds). + """ + if hasattr(expression, '__to_cryptol__'): + expression = cryptoltypes.to_cryptol(expression) + timeout = timeout if timeout is not None else self.timeout + self.most_recent_result = CryptolEvalExpr(self, expression, timeout) + return self.most_recent_result + + def eval_f(self, s : str, *, timeout:Optional[float] = None) -> argo.Command: + """Parses the given string like ``cry_f``, then evalues it, with the + result represented according to :ref:`cryptol-json-expression`, with + Python datatypes standing for their JSON equivalents. + + :param timeout: Optional timeout for this request (in seconds). + """ + expression = to_cryptol_str_customf(s, frames=1, filename="") + return self.eval(expression, timeout=timeout) + + def evaluate_expression(self, expression : Any, *, timeout:Optional[float] = None) -> argo.Command: """Synonym for member method ``eval``. + + :param timeout: Optional timeout for this request (in seconds).""" + return self.eval(expression, timeout=timeout) + + def extend_search_path(self, *dir : str, timeout:Optional[float] = None) -> argo.Command: + """Extend the search path for loading Cryptol modules. + + :param timeout: Optional timeout for this request (in seconds).""" + timeout = timeout if timeout is not None else self.timeout + self.most_recent_result = CryptolExtendSearchPath(self, list(dir), timeout) + return self.most_recent_result + + def call_raw(self, fun : str, *args : List[Any], timeout:Optional[float] = None) -> argo.Command: + """Like the member method ``call``, but does not call + ``from_cryptol_arg`` on the ``.result()``. """ - return self.eval(expression) - - def extend_search_path(self, *dir : str) -> argo.Command: - """Load a Cryptol module, like ``:module`` at the Cryptol REPL.""" - self.most_recent_result = CryptolExtendSearchPath(self, list(dir)) + timeout = timeout if timeout is not None else self.timeout + encoded_args = [cryptoltypes.to_cryptol(a) for a in args] + self.most_recent_result = CryptolCallRaw(self, fun, encoded_args, timeout) return self.most_recent_result - def call(self, fun : str, *args : List[Any]) -> argo.Command: - encoded_args = [cryptoltypes.CryptolType().from_python(a) for a in args] - self.most_recent_result = CryptolCall(self, fun, encoded_args) + def call(self, fun : str, *args : List[Any], timeout:Optional[float] = None) -> argo.Command: + """Call function ``fun`` with specified ``args``. + + :param timeout: Optional timeout for this request (in seconds).""" + timeout = timeout if timeout is not None else self.timeout + encoded_args = [cryptoltypes.to_cryptol(a) for a in args] + self.most_recent_result = CryptolCall(self, fun, encoded_args, timeout) return self.most_recent_result - def check(self, expr : Any, *, num_tests : Union[Literal['all'], int, None] = None) -> argo.Command: + + def check_raw(self, expr : Any, *, num_tests : Union[Literal['all'], int, None] = None, timeout:Optional[float] = None) -> argo.Command: + """Like the member method ``check``, but does not call + `to_check_report` on the ``.result()``. + """ + timeout = timeout if timeout is not None else self.timeout + if num_tests == "all" or isinstance(num_tests, int) or num_tests is None: + self.most_recent_result = CryptolCheckRaw(self, expr, num_tests, timeout) + return self.most_recent_result + else: + raise ValueError('``num_tests`` must be an integer, ``None``, or the string literall ``"all"``') + + def check(self, expr : Any, *, num_tests : Union[Literal['all'], int, None] = None, timeout:Optional[float] = None) -> argo.Command: """Tests the validity of a Cryptol expression with random inputs. The expression must be a function with return type ``Bit``. If ``num_tests`` is ``"all"`` then the expression is tested exhaustively (i.e., against all possible inputs). If ``num_tests`` is omitted, Cryptol defaults to running 100 tests. + + :param timeout: Optional timeout for this request (in seconds). """ + timeout = timeout if timeout is not None else self.timeout if num_tests == "all" or isinstance(num_tests, int) or num_tests is None: - self.most_recent_result = CryptolCheck(self, expr, num_tests) + self.most_recent_result = CryptolCheck(self, expr, num_tests, timeout) return self.most_recent_result else: raise ValueError('``num_tests`` must be an integer, ``None``, or the string literall ``"all"``') - def check_type(self, code : Any) -> argo.Command: + def check_type(self, code : Any, *, timeout:Optional[float] = None) -> argo.Command: """Check the type of a Cryptol expression, represented according to :ref:`cryptol-json-expression`, with Python datatypes standing for their JSON equivalents. + + :param timeout: Optional timeout for this request (in seconds). """ - self.most_recent_result = CryptolCheckType(self, code) + timeout = timeout if timeout is not None else self.timeout + self.most_recent_result = CryptolCheckType(self, code, timeout) return self.most_recent_result - def sat(self, expr : Any, solver : solver.Solver = solver.Z3, count : int = 1) -> argo.Command: + def sat_raw(self, expr : Any, solver : solver.Solver = solver.Z3, count : int = 1, *, timeout:Optional[float] = None) -> argo.Command: + """Like the member method ``sat``, but does not call + `to_smt_query_result` on the ``.result()``. + """ + timeout = timeout if timeout is not None else self.timeout + self.most_recent_result = CryptolSatRaw(self, expr, solver, count, timeout) + return self.most_recent_result + + def sat(self, expr : Any, solver : solver.Solver = solver.Z3, count : int = 1, *, timeout:Optional[float] = None) -> argo.Command: """Check the satisfiability of a Cryptol expression, represented according to :ref:`cryptol-json-expression`, with Python datatypes standing for their JSON equivalents. Use the solver named `solver`, and return up to `count` solutions. + + :param timeout: Optional timeout for this request (in seconds). """ - self.most_recent_result = CryptolSat(self, expr, solver, count) + timeout = timeout if timeout is not None else self.timeout + self.most_recent_result = CryptolSat(self, expr, solver, count, timeout) return self.most_recent_result - def prove(self, expr : Any, solver : solver.Solver = solver.Z3) -> argo.Command: + def prove_raw(self, expr : Any, solver : solver.Solver = solver.Z3, *, timeout:Optional[float] = None) -> argo.Command: + """Like the member method ``prove``, but does not call + `to_smt_query_result` on the ``.result()``. + """ + timeout = timeout if timeout is not None else self.timeout + self.most_recent_result = CryptolProveRaw(self, expr, solver, timeout) + return self.most_recent_result + + def prove(self, expr : Any, solver : solver.Solver = solver.Z3, *, timeout:Optional[float] = None) -> argo.Command: """Check the validity of a Cryptol expression, represented according to :ref:`cryptol-json-expression`, with Python datatypes standing for their JSON equivalents. Use the solver named `solver`. + + :param timeout: Optional timeout for this request (in seconds). """ - self.most_recent_result = CryptolProve(self, expr, solver) + timeout = timeout if timeout is not None else self.timeout + self.most_recent_result = CryptolProve(self, expr, solver, timeout) return self.most_recent_result - def safe(self, expr : Any, solver : solver.Solver = solver.Z3) -> argo.Command: + def safe_raw(self, expr : Any, solver : solver.Solver = solver.Z3, *, timeout:Optional[float] = None) -> argo.Command: + """Like the member method ``safe``, but does not call + `to_smt_query_result` on the ``.result()``. + """ + timeout = timeout if timeout is not None else self.timeout + self.most_recent_result = CryptolSafeRaw(self, expr, solver, timeout) + return self.most_recent_result + + def safe(self, expr : Any, solver : solver.Solver = solver.Z3, *, timeout:Optional[float] = None) -> argo.Command: """Check via an external SMT solver that the given term is safe for all inputs, which means it cannot encounter a run-time error. + + :param timeout: Optional timeout for this request (in seconds). """ - self.most_recent_result = CryptolSafe(self, expr, solver) + timeout = timeout if timeout is not None else self.timeout + self.most_recent_result = CryptolSafe(self, expr, solver, timeout) return self.most_recent_result - def names(self) -> argo.Command: - """Discover the list of names currently in scope in the current context.""" - self.most_recent_result = CryptolNames(self) + def names(self, *, timeout:Optional[float] = None) -> argo.Command: + """Discover the list of names currently in scope in the current context. + + :param timeout: Optional timeout for this request (in seconds).""" + timeout = timeout if timeout is not None else self.timeout + self.most_recent_result = CryptolNames(self, timeout) return self.most_recent_result - def focused_module(self) -> argo.Command: - """Return the name of the currently-focused module.""" - self.most_recent_result = CryptolFocusedModule(self) + def focused_module(self, *, timeout:Optional[float] = None) -> argo.Command: + """Return the name of the currently-focused module. + + :param timeout: Optional timeout for this request (in seconds).""" + timeout = timeout if timeout is not None else self.timeout + self.most_recent_result = CryptolFocusedModule(self, timeout) return self.most_recent_result def reset(self) -> None: @@ -258,13 +406,13 @@ class CryptolConnection: CryptolResetServer(self) self.most_recent_result = None - def __del__(self) -> None: - # when being deleted, ensure we don't have a lingering state on the server - if self.most_recent_result is not None: - try: - CryptolReset(self) - except Exception: - pass + def interrupt(self) -> None: + """Interrupt the Cryptol server, cancelling any in-progress requests.""" + CryptolInterrupt(self) + + def logging(self, on : bool, *, dest : TextIO = sys.stderr) -> None: + """Whether to log received and transmitted JSON.""" + self.server_connection.logging(on=on,dest=dest) class CryptolDynamicSocketProcess(DynamicSocketProcess): @@ -321,7 +469,7 @@ class CryptolStdIOProcess(StdIOProcess): # current_expr = self.name # found_args = [] # while len(arg_types) > 0 and len(remaining_args) > 0: -# found_args.append(arg_types[0].from_python(remaining_args[0])) +# found_args.append(to_cryptol(remaining_args[0])) # current_expr = {'expression': 'call', 'function': self.name, 'arguments': found_args} # ty = self.connection.check_type(current_expr).result() # current_type = cryptoltypes.to_schema(ty) diff --git a/cryptol-remote-api/python/cryptol/cryptoltypes.py b/cryptol-remote-api/python/cryptol/cryptoltypes.py index 82df00cd..0d9aef61 100644 --- a/cryptol-remote-api/python/cryptol/cryptoltypes.py +++ b/cryptol-remote-api/python/cryptol/cryptoltypes.py @@ -1,103 +1,178 @@ from __future__ import annotations from collections import OrderedDict from abc import ABCMeta, abstractmethod +from dataclasses import dataclass import base64 from math import ceil import BitVector #type: ignore from .bitvector import BV from .opaque import OpaqueValue -from typing import Any, Dict, Iterable, List, NoReturn, Optional, TypeVar, Union - -from typing_extensions import Literal, Protocol +import typing +from typing import cast, Any, Dict, Iterable, List, NoReturn, Optional, TypeVar, Union +import typing_extensions +from typing_extensions import Protocol, runtime_checkable A = TypeVar('A') + +# ----------------------------------------------------------- +# CryptolJSON and CryptolCode +# ----------------------------------------------------------- + +def is_parenthesized(s : str) -> bool: + """Returns ``True`` iff the given string has balanced parentheses and is + enclosed in a matching pair of parentheses. + + :examples: + + >>> is_parenthesized(' ((a) b )') + True + >>> is_parenthesized('(a) (b)') + False + >>> is_parenthesized('(a') + False + """ + seen_one, depth = False, 0 + for c in s: + if depth > 0: + if c == '(': depth += 1 + if c == ')': depth -= 1 + else: # depth == 0 + if c == '(': + if not seen_one: seen_one, depth = True, 1 + # A new left paren after all parens have been closed means our + # string is not enclosed in a matching pair of parentheses + else: return False + if c == ')': + # A right paren with no matching left means our string does + # not have balanced parentheses + return False + # Return True if in the end all parentheses are balanced and we've seen at + # least one matching pair + return seen_one and depth == 0 + +def parenthesize(s : str) -> str: + """Encloses the given string ``s`` in parentheses if + ``is_parenthesized(s)`` is ``False``""" + return s if is_parenthesized(s) else f'({s})' + +JSON = Union[bool, int, float, str, Dict, typing.Tuple, List] + +@runtime_checkable class CryptolJSON(Protocol): - def __to_cryptol__(self, ty : CryptolType) -> Any: ... + """A ``Protocol`` for objects which can be converted to Cryptol JSON or + Cryptol strings.""" + def __to_cryptol__(self) -> JSON: ... + def __to_cryptol_str__(self) -> str: ... class CryptolCode(metaclass=ABCMeta): - def __call__(self, other : CryptolJSON) -> CryptolCode: - return CryptolApplication(self, other) - + """The base class for ``CryptolLiteral`` and ``CryptolApplication``.""" @abstractmethod - def __to_cryptol__(self, ty : CryptolType) -> Any: ... + def __to_cryptol__(self) -> JSON: ... + @abstractmethod + def __to_cryptol_str__(self) -> str: ... + def __str__(self) -> str: + return self.__to_cryptol_str__() + def __call__(self, *others : CryptolJSON) -> CryptolCode: + return CryptolApplication(self, *others) + +@dataclass class CryptolLiteral(CryptolCode): - def __init__(self, code : str) -> None: - self._code = code + """A string of Cryptol syntax.""" + _code : str - def __to_cryptol__(self, ty : CryptolType) -> Any: + def __to_cryptol__(self) -> JSON: return self._code + def __to_cryptol_str__(self) -> str: + return self._code +@dataclass class CryptolApplication(CryptolCode): - def __init__(self, rator : CryptolJSON, *rands : CryptolJSON) -> None: - self._rator = rator - self._rands = rands + """An application of a Cryptol function to some arguments.""" + _rator : CryptolJSON + _rands : typing.Sequence[CryptolJSON] - def __to_cryptol__(self, ty : CryptolType) -> Any: + def __init__(self, rator : CryptolJSON, *rands : CryptolJSON) -> None: + if all(isinstance(rand, CryptolJSON) for rand in rands): + self._rator = rator + self._rands = rands + else: + args_str = ", ".join(map(repr, [rator, *rands])) + raise ValueError("Arguments given to CryptolApplication must be CryptolJSON: " + args_str) + + def __repr__(self) -> str: + return f'CryptolApplication({", ".join(repr(x) for x in [self._rator, *self._rands])})' + + def __to_cryptol__(self) -> JSON: return {'expression': 'call', 'function': to_cryptol(self._rator), 'arguments': [to_cryptol(arg) for arg in self._rands]} -class CryptolArrowKind: - def __init__(self, dom : CryptolKind, ran : CryptolKind): - self.domain = dom - self.range = ran + def __to_cryptol_str__(self) -> str: + if len(self._rands) == 0: + return self._rator.__to_cryptol_str__() + else: + return ' '.join(parenthesize(x.__to_cryptol_str__()) for x in [self._rator, *self._rands]) - def __repr__(self) -> str: - return f"CryptolArrowKind({self.domain!r}, {self.range!r})" -CryptolKind = Union[Literal['Type'], Literal['Num'], Literal['Prop'], CryptolArrowKind] +# ----------------------------------------------------------- +# Converting Python terms to Cryptol JSON +# ----------------------------------------------------------- -def to_kind(k : Any) -> CryptolKind: - if k == "Type": return "Type" - elif k == "Num": return "Num" - elif k == "Prop": return "Prop" - elif k['kind'] == "arrow": - return CryptolArrowKind(k['from'], k['to']) +def to_cryptol(val : Any) -> JSON: + """Convert a ``CryptolJSON`` value, a Python value representing a Cryptol + term, or any combination of the two to Cryptol JSON.""" + if isinstance(val, bool): + return val + elif isinstance(val, tuple) and val == (): + return {'expression': 'unit'} + elif isinstance(val, tuple): + return {'expression': 'tuple', + 'data': [to_cryptol(x) for x in val]} + elif isinstance(val, dict): + return {'expression': 'record', + 'data': {k : to_cryptol(val[k]) + if isinstance(k, str) + else fail_with (TypeError("Record keys must be strings")) + for k in val}} + elif isinstance(val, int): + return val + elif isinstance(val, list): + return {'expression': 'sequence', + 'data': [to_cryptol(v) for v in val]} + elif isinstance(val, bytes) or isinstance(val, bytearray): + return {'expression': 'bits', + 'encoding': 'base64', + 'width': 8 * len(val), + 'data': base64.b64encode(val).decode('ascii')} + elif isinstance(val, BitVector.BitVector): + n = int(val) + byte_width = ceil(n.bit_length()/8) + return {'expression': 'bits', + 'encoding': 'base64', + 'width': val.length(), # N.B. original length, not padded + 'data': base64.b64encode(n.to_bytes(byte_width,'big')).decode('ascii')} + elif isinstance(val, BV): + return {'expression': 'bits', + 'encoding': 'hex', + 'width': val.size(), # N.B. original length, not padded + 'data': val.hex()[2:]} + elif isinstance(val, OpaqueValue): + return {'expression': 'variable', + 'identifier': val.identifier} + elif hasattr(val, '__to_cryptol__'): + code = val.__to_cryptol__() + if is_plausible_json(code): + # the call to is_plausible_json ensures this cast is OK + return cast(JSON, code) + else: + raise ValueError(f"Improbable JSON from __to_cryptol__: {val!r} gave {code!r}") else: - raise ValueError(f'Not a Cryptol kind: {k!r}') - -class CryptolProp: - pass - -class UnaryProp(CryptolProp): - def __init__(self, subject : CryptolType) -> None: - self.subject = subject - -class Fin(UnaryProp): - def __repr__(self) -> str: - return f"Fin({self.subject!r})" - -class Cmp(UnaryProp): - def __repr__(self) -> str: - return f"Cmp({self.subject!r})" - -class SignedCmp(UnaryProp): - def __repr__(self) -> str: - return f"SignedCmp({self.subject!r})" - -class Zero(UnaryProp): - def __repr__(self) -> str: - return f"Zero({self.subject!r})" - -class Arith(UnaryProp): - def __repr__(self) -> str: - return f"Arith({self.subject!r})" - -class Logic(UnaryProp): - def __repr__(self) -> str: - return f"Logic({self.subject!r})" - - -def to_cryptol(val : Any, cryptol_type : Optional[CryptolType] = None) -> Any: - if cryptol_type is not None: - return cryptol_type.from_python(val) - else: - return CryptolType().from_python(val) + raise TypeError("Unsupported value: " + str(val)) def fail_with(exn : Exception) -> NoReturn: raise exn @@ -114,306 +189,153 @@ def is_plausible_json(val : Any) -> bool: return False -class CryptolType: - def from_python(self, val : Any) -> Any: - if hasattr(val, '__to_cryptol__'): - code = val.__to_cryptol__(self) - if is_plausible_json(code): - return code - else: - raise ValueError(f"Improbable JSON from __to_cryptol__: {val!r} gave {code!r}") - # if isinstance(code, CryptolCode): - # return self.convert(code) - # else: - # raise ValueError(f"Expected Cryptol code from __to_cryptol__ on {val!r}, but got {code!r}.") - else: - return self.convert(val) - def convert(self, val : Any) -> Any: - if isinstance(val, bool): - return val - elif isinstance(val, tuple) and val == (): - return {'expression': 'unit'} - elif isinstance(val, tuple): - return {'expression': 'tuple', - 'data': [to_cryptol(x) for x in val]} - elif isinstance(val, dict): - return {'expression': 'record', - 'data': {k : to_cryptol(val[k]) - if isinstance(k, str) - else fail_with (TypeError("Record keys must be strings")) - for k in val}} - elif isinstance(val, int): - return val - elif isinstance(val, list): - return {'expression': 'sequence', - 'data': [to_cryptol(v) for v in val]} - elif isinstance(val, bytes) or isinstance(val, bytearray): - return {'expression': 'bits', - 'encoding': 'base64', - 'width': 8 * len(val), - 'data': base64.b64encode(val).decode('ascii')} - elif isinstance(val, BitVector.BitVector): - n = int(val) - byte_width = ceil(n.bit_length()/8) - return {'expression': 'bits', - 'encoding': 'base64', - 'width': val.length(), # N.B. original length, not padded - 'data': base64.b64encode(n.to_bytes(byte_width,'big')).decode('ascii')} - elif isinstance(val, BV): - return {'expression': 'bits', - 'encoding': 'hex', - 'width': val.size(), # N.B. original length, not padded - 'data': val.hex()[2:]} - elif isinstance(val, OpaqueValue): - return {'expression': 'variable', - 'identifier': val.identifier} - else: - raise TypeError("Unsupported value: " + str(val)) +# ----------------------------------------------------------- +# Cryptol kinds +# ----------------------------------------------------------- -class Var(CryptolType): - def __init__(self, name : str, kind : CryptolKind) -> None: - self.name = name - self.kind = kind +@dataclass +class CryptolArrowKind: + domain : CryptolKind + range : CryptolKind - def __repr__(self) -> str: - return f"Var({self.name!r}, {self.kind!r})" +CryptolKind = Union[typing_extensions.Literal['Type'], + typing_extensions.Literal['Num'], + typing_extensions.Literal['Prop'], + CryptolArrowKind] - - -class Function(CryptolType): - def __init__(self, dom : CryptolType, ran : CryptolType) -> None: - self.domain = dom - self.range = ran - - def __repr__(self) -> str: - return f"Function({self.domain!r}, {self.range!r})" - -class Bitvector(CryptolType): - def __init__(self, width : CryptolType) -> None: - self.width = width - - def __repr__(self) -> str: - return f"Bitvector({self.width!r})" - - def convert(self, val : Any) -> Any: - # XXX figure out what to do when width is not evenly divisible by 8 - if isinstance(val, int): - w = eval_numeric(self.width, None) - if w is not None: - return self.convert(int.to_bytes(val, int(w / 8), 'big', signed=True)) - else: - raise ValueError(f"Insufficent type information to serialize int as bitvector") - elif isinstance(val, bytearray) or isinstance(val, bytes): - return {'expression': 'bits', - 'encoding': 'base64', - 'width': eval_numeric(self.width, 8 * len(val)), - 'data': base64.b64encode(val).decode('ascii')} - elif isinstance(val, BitVector.BitVector): - return CryptolType.convert(self, val) - elif isinstance(val, BV): - return CryptolType.convert(self, val) - else: - raise ValueError(f"Not supported as bitvector: {val!r}") - -def eval_numeric(t : Any, default : A) -> Union[int, A]: - if isinstance(t, Num): - return t.number +def to_kind(k : Any) -> CryptolKind: + if k == "Type": return "Type" + elif k == "Num": return "Num" + elif k == "Prop": return "Prop" + elif k['kind'] == "arrow": + return CryptolArrowKind(k['from'], k['to']) else: - return default + raise ValueError(f'Not a Cryptol kind: {k!r}') +# ----------------------------------------------------------- +# Cryptol types +# ----------------------------------------------------------- + +class CryptolType: + def from_python(self, val : Any) -> NoReturn: + raise Exception("CryptolType.from_python is deprecated, use to_cryptol") + + def convert(self, val : Any) -> NoReturn: + raise Exception("CryptolType.convert is deprecated, use to_cryptol") + +@dataclass +class Var(CryptolType): + name : str + kind : CryptolKind + + def __str__(self) -> str: + return self.name + +@dataclass +class Function(CryptolType): + domain : CryptolType + range : CryptolType + + def __str__(self) -> str: + return f"({self.domain} -> {self.range})" + +@dataclass +class Bitvector(CryptolType): + width : CryptolType + + def __str__(self) -> str: + return f"[{self.width}]" + +@dataclass class Num(CryptolType): - def __init__(self, number : int) -> None: - self.number = number + number : int - def __repr__(self) -> str: - return f"Num({self.number!r})" + def __str__(self) -> str: + return str(self.number) +@dataclass class Bit(CryptolType): - def __init__(self) -> None: - pass - - def __repr__(self) -> str: - return f"Bit()" + def __str__(self) -> str: + return "Bit" +@dataclass class Sequence(CryptolType): - def __init__(self, length : CryptolType, contents : CryptolType) -> None: - self.length = length - self.contents = contents + length : CryptolType + contents : CryptolType - def __repr__(self) -> str: - return f"Sequence({self.length!r}, {self.contents!r})" + def __str__(self) -> str: + return f"[{self.length}]{self.contents}" +@dataclass class Inf(CryptolType): - def __repr__(self) -> str: - return f"Inf()" + def __str__(self) -> str: + return "inf" +@dataclass class Integer(CryptolType): - def __repr__(self) -> str: - return f"Integer()" + def __str__(self) -> str: + return "Integer" +@dataclass class Rational(CryptolType): - def __repr__(self) -> str: - return f"Rational()" + def __str__(self) -> str: + return "Rational" +@dataclass class Z(CryptolType): - def __init__(self, modulus : CryptolType) -> None: - self.modulus = modulus - - def __repr__(self) -> str: - return f"Z({self.modulus!r})" - - -class Plus(CryptolType): - def __init__(self, left : CryptolType, right : CryptolType) -> None: - self.left = left - self.right = right + modulus : CryptolType def __str__(self) -> str: - return f"({self.left} + {self.right})" + return f"(Z {self.modulus})" + +@dataclass +class TypeOp(CryptolType): + op : str + args : typing.Sequence[CryptolType] + + # we override the @dataclass __init__ and __repr__ because we want the + # syntax of variable numbers of arguments + def __init__(self, op : str, *args : CryptolType) -> None: + self.op = op + self.args = args def __repr__(self) -> str: - return f"Plus({self.left!r}, {self.right!r})" - -class Minus(CryptolType): - def __init__(self, left : CryptolType, right : CryptolType) -> None: - self.left = left - self.right = right + return "TypeOp(" + ", ".join(map(repr, [self.op, *self.args])) + ")" def __str__(self) -> str: - return f"({self.left} - {self.right})" - - def __repr__(self) -> str: - return f"Minus({self.left!r}, {self.right!r})" - -class Times(CryptolType): - def __init__(self, left : CryptolType, right : CryptolType) -> None: - self.left = left - self.right = right - - def __str__(self) -> str: - return f"({self.left} * {self.right})" - - def __repr__(self) -> str: - return f"Times({self.left!r}, {self.right!r})" - - -class Div(CryptolType): - def __init__(self, left : CryptolType, right : CryptolType) -> None: - self.left = left - self.right = right - - def __str__(self) -> str: - return f"({self.left} / {self.right})" - - def __repr__(self) -> str: - return f"Div({self.left!r}, {self.right!r})" - -class CeilDiv(CryptolType): - def __init__(self, left : CryptolType, right : CryptolType) -> None: - self.left = left - self.right = right - - def __str__(self) -> str: - return f"({self.left} /^ {self.right})" - - def __repr__(self) -> str: - return f"CeilDiv({self.left!r}, {self.right!r})" - -class Mod(CryptolType): - def __init__(self, left : CryptolType, right : CryptolType) -> None: - self.left = left - self.right = right - - def __str__(self) -> str: - return f"({self.left} % {self.right})" - - def __repr__(self) -> str: - return f"Mod({self.left!r}, {self.right!r})" - -class CeilMod(CryptolType): - def __init__(self, left : CryptolType, right : CryptolType) -> None: - self.left = left - self.right = right - - def __str__(self) -> str: - return f"({self.left} %^ {self.right})" - - def __repr__(self) -> str: - return f"CeilMod({self.left!r}, {self.right!r})" - -class Expt(CryptolType): - def __init__(self, left : CryptolType, right : CryptolType) -> None: - self.left = left - self.right = right - - def __str__(self) -> str: - return f"({self.left} ^^ {self.right})" - - def __repr__(self) -> str: - return f"Expt({self.left!r}, {self.right!r})" - -class Log2(CryptolType): - def __init__(self, operand : CryptolType) -> None: - self.operand = operand - - def __str__(self) -> str: - return f"(lg2 {self.operand})" - - def __repr__(self) -> str: - return f"Log2({self.operand!r})" - -class Width(CryptolType): - def __init__(self, operand : CryptolType) -> None: - self.operand = operand - - def __str__(self) -> str: - return f"(width {self.operand})" - - def __repr__(self) -> str: - return f"Width({self.operand!r})" - -class Max(CryptolType): - def __init__(self, left : CryptolType, right : CryptolType) -> None: - self.left = left - self.right = right - - def __str__(self) -> str: - return f"(max {self.left} {self.right})" - - def __repr__(self) -> str: - return f"Max({self.left!r}, {self.right!r})" - -class Min(CryptolType): - def __init__(self, left : CryptolType, right : CryptolType) -> None: - self.left = left - self.right = right - - def __str__(self) -> str: - return f"(min {self.left} {self.right})" - - def __repr__(self) -> str: - return f"Min({self.left!r}, {self.right!r})" + if self.op.isalnum(): + return "(" + " ".join(map(str, [self.op, self.args])) + ")" + elif len(self.args) == 2: + return f"({self.args[0]} {self.op} {self.args[1]})" + else: + raise NotImplementedError(f"__str__ for: {self!r}") +@dataclass class Tuple(CryptolType): - types : Iterable[CryptolType] + types : typing.Sequence[CryptolType] + # we override the @dataclass __init__ and __repr__ because we want the + # syntax of variable numbers of arguments def __init__(self, *types : CryptolType) -> None: self.types = types def __repr__(self) -> str: - return "Tuple(" + ", ".join(map(str, self.types)) + ")" + return "Tuple(" + ", ".join(map(repr, self.types)) + ")" + def __str__(self) -> str: + return "(" + ",".join(map(str, self.types)) + ")" + +@dataclass class Record(CryptolType): - def __init__(self, fields : Dict[str, CryptolType]) -> None: - self.fields = fields - - def __repr__(self) -> str: - return f"Record({self.fields!r})" + fields : Dict[str, CryptolType] + def __str__(self) -> str: + return "{" + ",".join(str(k) + " = " + str(self.fields[k]) for k in self.fields) + "}" def to_type(t : Any) -> CryptolType: + """Convert a Cryptol JSON type to a ``CryptolType``.""" if t['type'] == 'variable': return Var(t['name'], to_kind(t['kind'])) elif t['type'] == 'function': @@ -428,32 +350,10 @@ def to_type(t : Any) -> CryptolType: return Sequence(to_type(t['length']), to_type(t['contents'])) elif t['type'] == 'inf': return Inf() - elif t['type'] == '+': - return Plus(*map(to_type, t['arguments'])) - elif t['type'] == '-': - return Minus(*map(to_type, t['arguments'])) - elif t['type'] == '*': - return Times(*map(to_type, t['arguments'])) - elif t['type'] == '/': - return Div(*map(to_type, t['arguments'])) - elif t['type'] == '/^': - return CeilDiv(*map(to_type, t['arguments'])) - elif t['type'] == '%': - return Mod(*map(to_type, t['arguments'])) - elif t['type'] == '%^': - return CeilMod(*map(to_type, t['arguments'])) - elif t['type'] == '^^': - return Expt(*map(to_type, t['arguments'])) - elif t['type'] == 'lg2': - return Log2(*map(to_type, t['arguments'])) - elif t['type'] == 'width': - return Width(*map(to_type, t['arguments'])) - elif t['type'] == 'max': - return Max(*map(to_type, t['arguments'])) - elif t['type'] == 'min': - return Min(*map(to_type, t['arguments'])) elif t['type'] == 'tuple': return Tuple(*map(to_type, t['contents'])) + elif t['type'] == 'unit': + return Tuple() elif t['type'] == 'record': return Record({k : to_type(t['fields'][k]) for k in t['fields']}) elif t['type'] == 'Integer': @@ -462,45 +362,112 @@ def to_type(t : Any) -> CryptolType: return Rational() elif t['type'] == 'Z': return Z(to_type(t['modulus'])) + elif 'arguments' in t: + return TypeOp(t['type'], *map(to_type, t['arguments'])) else: raise NotImplementedError(f"to_type({t!r})") -class CryptolTypeSchema: - def __init__(self, - variables : OrderedDict[str, CryptolKind], - propositions : List[Optional[CryptolProp]], # TODO complete me! - body : CryptolType) -> None: - self.variables = variables - self.propositions = propositions - self.body = body + +# ----------------------------------------------------------- +# Cryptol props +# ----------------------------------------------------------- + +class CryptolProp: + pass + +@dataclass +class PropCon(CryptolProp): + con : str + args : typing.Sequence[CryptolType] + + # we override the @dataclass __init__ and __repr__ because we want the + # syntax of variable numbers of arguments + def __init__(self, con : str, *args : CryptolType) -> None: + self.con = con + self.args = args def __repr__(self) -> str: - return f"CryptolTypeSchema({self.variables!r}, {self.propositions!r}, {self.body!r})" + return "PropCon(" + ", ".join(map(repr, [self.con, *self.args])) + ")" + + def __str__(self) -> str: + if self.con.isalnum(): + return "(" + " ".join(map(str, [self.con, self.args])) + ")" + elif len(self.args) == 2: + return f"({self.args[0]} {self.con} {self.args[1]})" + else: + raise NotImplementedError(f"__str__ for: {self!r}") + +@dataclass +class And(CryptolProp): + left : CryptolProp + right : CryptolProp + + def __str__(self) -> str: + return f"({self.left} && {self.right})" + +@dataclass +class TrueProp(CryptolProp): + def __str__(self) -> str: + return "True" + +def to_prop(obj : Any) -> CryptolProp: + """Convert a Cryptol JSON proposition to a ``CryptolProp``.""" + if obj['prop'] == 'And': + return And(to_prop(obj['left']), to_prop(obj['right'])) + elif obj['prop'] == 'True': + return TrueProp() + # special cases for props which have irregular JSON structure + elif obj['prop'] == 'Literal': + return PropCon('Literal', to_type(obj['size']), to_type(obj['subject'])) + elif obj['prop'] == '>=': + return PropCon('>=', to_type(obj['greater']), to_type(obj['less'])) + # general cases for unary, binary, and unknown props + elif 'subject' in obj and len(obj) == 2: + return PropCon(obj['prop'], to_type(obj['subject'])) + elif 'left' in obj and 'right' in obj and len(obj) == 3: + return PropCon(obj['prop'], to_type(obj['left']), to_type(obj['right'])) + elif obj['prop'] == 'unknown': + return PropCon(obj['constructor'], *map(to_type, obj['arguments'])) + else: + raise NotImplementedError(f"to_prop({obj!r})") + + +# ----------------------------------------------------------- +# Cryptol type schema +# ----------------------------------------------------------- + +@dataclass +class CryptolTypeSchema: + variables : OrderedDict[str, CryptolKind] + propositions : List[CryptolProp] + body : CryptolType + + def __str__(self) -> str: + vstr, pstr = "", "()" + if len(self.variables) > 0: + vstr = "{" + ", ".join(self.variables.keys()) + "} " + if len(self.propositions) > 0: + pstr = "(" + ", ".join(map(str, self.propositions)) + ")" + return vstr + pstr + " => " + str(self.body) def to_schema(obj : Any) -> CryptolTypeSchema: + """Convert a Cryptol JSON type schema to a ``CryptolTypeSchema``.""" return CryptolTypeSchema(OrderedDict((v['name'], to_kind(v['kind'])) for v in obj['forall']), [to_prop(p) for p in obj['propositions']], to_type(obj['type'])) -def to_prop(obj : Any) -> Optional[CryptolProp]: - if obj['prop'] == 'fin': - return Fin(to_type(obj['subject'])) - elif obj['prop'] == 'Cmp': - return Cmp(to_type(obj['subject'])) - elif obj['prop'] == 'SignedCmp': - return SignedCmp(to_type(obj['subject'])) - elif obj['prop'] == 'Zero': - return Zero(to_type(obj['subject'])) - elif obj['prop'] == 'Arith': - return Arith(to_type(obj['subject'])) - elif obj['prop'] == 'Logic': - return Logic(to_type(obj['subject'])) +def to_schema_or_type(obj : Any) -> Union[CryptolTypeSchema, CryptolType]: + """Convert a Cryptol JSON type schema to a ``CryptolType`` if it has no + variables or propositions, or to a ``CryptolTypeSchema`` otherwise.""" + if 'forall' in obj and 'propositions' in obj and len(obj['forall']) > 0 and len(obj['propositions']) > 0: + return to_schema(obj) else: - return None - #raise ValueError(f"Can't convert to a Cryptol prop: {obj!r}") + return to_type(obj['type']) def argument_types(obj : Union[CryptolTypeSchema, CryptolType]) -> List[CryptolType]: + """Given a ``CryptolTypeSchema` or ``CryptolType`` of a function, return + the types of its arguments.""" if isinstance(obj, CryptolTypeSchema): return argument_types(obj.body) elif isinstance(obj, Function): diff --git a/cryptol-remote-api/python/cryptol/custom_fstring.py b/cryptol-remote-api/python/cryptol/custom_fstring.py new file mode 100644 index 00000000..f384b71d --- /dev/null +++ b/cryptol-remote-api/python/cryptol/custom_fstring.py @@ -0,0 +1,79 @@ +"""An interface for defining custom f-string wrappers""" + +from typing import Any, Callable, Dict, List +import builtins +import ast +import sys + +def customf(body : str, onAST : Callable[[ast.FormattedValue], List[ast.expr]], + globals : Dict[str, Any] = {}, locals : Dict[str, Any] = {}, + *, frames : int = 0, filename : str = "") -> str: + """This function parses the given string as if it were an f-string, + applies the given function to the AST of each of the formatting fields in + the string, then evaluates the result to get the resulting string. + + By default, the global and local variables used in the call to ``eval`` + are the value of ``sys.__getframe(1+frames).f_globals`` and the value of + ``sys.__getframe(1+frames).f_locals``, respectively. This is meant to + ensure that the all the variables which were in scope when the custom + f-string is formed are also in scope when it is evaluated. Thus, the value + of ``frames`` should be incremented for each wrapper function defined + around this function (e.g. see the definition of ``func_customf``). + + To add additional global or local variable values (which are combined with, + but take precedence over, the values mentioned in the previous paragraph) + use the ``globals`` and ``locals`` keyword arguments. + """ + # Get the global/local variable context of the previous frame so the local + # names 'body', 'onAST', etc. aren't shadowed our the call to ``eval`` + previous_frame = sys._getframe(1 + frames) + all_globals = {**previous_frame.f_globals, **globals} + all_locals = {**previous_frame.f_locals, **locals} + # The below line should be where any f-string syntax errors are raised + tree = ast.parse('f' + str(repr(body)), filename=filename, mode='eval') + if not isinstance(tree, ast.Expression) or not isinstance(tree.body, ast.JoinedStr): + raise ValueError(f'Invalid custom f-string: {str(repr(body))}') + joined_values : List[ast.expr] = [] + for node in tree.body.values: + if isinstance(node, ast.FormattedValue): + joined_values += onAST(node) + else: + joined_values += [node] + tree.body.values = joined_values + try: + return str(eval(compile(tree, filename=filename, mode='eval'), all_globals, all_locals)) + except SyntaxError as e: + # I can't think of a case where we would raise an error here, but if + # we do it's worth telling the user that the column numbers are all + # messed up + msg = '\nNB: Column numbers refer to positions in the original string' + raise type(e)(str(e) + msg).with_traceback(sys.exc_info()[2]) + +def func_customf(body : str, func : Callable, + globals : Dict[str, Any] = {}, locals : Dict[str, Any] = {}, + *, frames : int = 0, filename : str = "", + doConvFmtAfter : bool = False, + func_id : str = "_func_customf__func_id") -> str: + """Like ``customf``, but can be provided a function to apply to the values + of each of the formatting fields before they are formatted as strings, + instead of a function applied to their ASTs. + + Unless the parameter ``doConvFmtAfter`` is set to ``True``, any conversions + (i.e. ``{...!s}``, ``{...!r}``, or ``{...!a}``) or format specifiers + (e.g. ``{...:>30}`` or ``{...:+f}``) in the input string will be applied + before the given function is applied. For example, + ``func_customf('{5!r}', f)`` is the same as ``f'{f(repr(5))}'``, but + ``func_customf('{5!r}', f, doConvFmtAfter=True)`` is ``f'{repr(f(5))}'``. + """ + def onAST(node : ast.FormattedValue) -> List[ast.expr]: + kwargs = {'lineno': node.lineno, 'col_offset': node.col_offset} + func = ast.Name(id=func_id, ctx=ast.Load(), **kwargs) + if doConvFmtAfter or (node.conversion == -1 and node.format_spec is None): + node.value = ast.Call(func=func, args=[node.value], keywords=[], **kwargs) + else: + node_str = ast.JoinedStr(values=[node], **kwargs) + node_val = ast.Call(func=func, args=[node_str], keywords=[], **kwargs) + node = ast.FormattedValue(value=node_val, conversion=-1, format_spec=None, **kwargs) + return [node] + return customf(body, onAST, globals, {**locals, func_id:func}, frames=1+frames, + filename=filename) diff --git a/cryptol-remote-api/python/cryptol/opaque.py b/cryptol-remote-api/python/cryptol/opaque.py index 4078203e..881fb1e2 100644 --- a/cryptol-remote-api/python/cryptol/opaque.py +++ b/cryptol-remote-api/python/cryptol/opaque.py @@ -1,5 +1,8 @@ from typing import Any +from dataclasses import dataclass +# we freeze this class because ``OpaqueValue``s represent immutable objects +@dataclass(frozen=True) class OpaqueValue(): """A value from the Cryptol server which cannot be directly represented and/or marshalled to an RPC client. @@ -9,20 +12,5 @@ class OpaqueValue(): be consulted to compute the result.""" identifier : str - def __init__(self, identifier : str) -> None: - self.identifier = identifier - def __str__(self) -> str: return self.identifier - - def __repr__(self) -> str: - return f"Opaque({self.identifier!r})" - - def __eq__(self, other : Any) -> bool: - if not isinstance(other, OpaqueValue): - return False - else: - return self.identifier == other.identifier - - def __hash__(self) -> int: - return hash(self.identifier) diff --git a/cryptol-remote-api/python/cryptol/quoting.py b/cryptol-remote-api/python/cryptol/quoting.py new file mode 100644 index 00000000..7503c87f --- /dev/null +++ b/cryptol-remote-api/python/cryptol/quoting.py @@ -0,0 +1,84 @@ +"""Cryptol quasiquotation using an f-string-like syntax""" + +from typing import Any, Union + +from .bitvector import BV +from .opaque import OpaqueValue +from .commands import CryptolValue +from .cryptoltypes import CryptolJSON, CryptolLiteral, parenthesize +from .custom_fstring import * + +def to_cryptol_str(val : Union[CryptolValue, str, CryptolJSON]) -> str: + """Converts a ``CryptolValue``, string literal, or ``CryptolJSON`` into + a string of Cryptol syntax.""" + if isinstance(val, bool): + return 'True' if val else 'False' + elif isinstance(val, tuple): + return '(' + ', '.join(to_cryptol_str(x) for x in val) + ')' + elif isinstance(val, dict): + return '{' + ', '.join(f'{k} = {to_cryptol_str(v)}' for k,v in val.items()) + '}' + elif isinstance(val, int): + return str(val) + elif isinstance(val, list): + return '[' + ', '.join(to_cryptol_str(x) for x in val) + ']' + elif isinstance(val, BV): + if val.size() % 4 == 0: + return val.hex() + else: + return f'({val.to_signed_int()} : [{val.size()}])' + elif isinstance(val, OpaqueValue): + return str(val) + elif isinstance(val, str): + return f'"{val}"' + elif hasattr(val, '__to_cryptol_str__'): + return parenthesize(val.__to_cryptol_str__()) + else: + raise TypeError("Unable to convert value to Cryptol syntax: " + str(val)) + +def to_cryptol_str_customf(s : str, *, frames : int = 0, + filename : str = "") -> str: + """The function used to parse strings given to ``cry_f``""" + return func_customf(s, to_cryptol_str, frames=1+frames, + filename=filename) + +def cry(s : str) -> CryptolLiteral: + """Embed a string of Cryptol syntax as ``CryptolCode``""" + return CryptolLiteral(s) + +def cry_f(s : str) -> CryptolLiteral: + """Embed a string of Cryptol syntax as ``CryptolCode``, where the given + string is parsed as an f-string, and the values within brackets are + converted to Cryptol syntax using ``to_cryptol_str``. + + Like f-strings, values in brackets (``{``, ``}``) are parsed as python + expressions in the caller's context of local and global variables, and + to include a literal bracket in the final string, it must be doubled + (i.e. ``{{`` or ``}}``). The latter is needed when using explicit type + application or record syntax. For example, if ``x = [0,1]`` then + ``cry_f('length `{{2}} {x}')`` is equal to ``cry('length `{2} [0,1]')`` + and ``cry_f('{{ x = {x} }}')`` is equal to ``cry('{ x = [0,1] }')``. + + When formatting Cryptol, it is recomended to use this function rather + than any of python's built-in methods of string formatting (e.g. + f-strings, ``str.format``) as the latter will not always produce valid + Cryptol syntax. Specifically, this function differs from these methods + in the cases of ``BV``s, string literals, function application (this + function will add parentheses as needed), and dicts. For example, + ``cry_f('{ {"x": 5, "y": 4} }')`` equals ``cry('{x = 5, y = 4}')`` + but ``f'{ {"x": 5, "y": 4} }'`` equals ``'{"x": 5, "y": 4}'``. Only + the former is valid Cryptol syntax for a record. + + Note that any conversion or format specifier will always result in the + argument being rendered as a Cryptol string literal with the conversion + and/or formating applied. For example, `cry('f {5}')` is equal to + ``cry('f 5')`` but ``cry_f('f {5!s}')`` is equal to ``cry(`f "5"`)`` + and ``cry_f('f {5:+.2%}')`` is equal to ``cry('f "+500.00%"')``. + + :example: + + >>> x = BV(size=7, value=1) + >>> y = cry_f('fun1 {x}') + >>> cry_f('fun2 {y}') + 'fun2 (fun1 (1 : [7]))' + """ + return CryptolLiteral(to_cryptol_str_customf(s, frames=1)) diff --git a/cryptol-remote-api/python/cryptol/single_connection.py b/cryptol-remote-api/python/cryptol/single_connection.py new file mode 100644 index 00000000..c498463b --- /dev/null +++ b/cryptol-remote-api/python/cryptol/single_connection.py @@ -0,0 +1,244 @@ +"""A single-connection, synchronous, typed interface for the Cryptol bindings""" + +from __future__ import annotations + +import sys +from typing import Any, Optional, Union, List, Dict, TextIO, overload +from typing_extensions import Literal + +from .custom_fstring import * +from .quoting import * +from .solver import OfflineSmtQuery, Solver, OnlineSolver, OfflineSolver, Z3 +from .connection import CryptolValue, CheckReport +from . import synchronous +from .synchronous import Qed, Safe, Counterexample, Satisfiable, Unsatisfiable +from . import cryptoltypes + + +__designated_connection = None # type: Optional[synchronous.CryptolSyncConnection] + +def __get_designated_connection() -> synchronous.CryptolSyncConnection: + global __designated_connection + if __designated_connection is None: + raise ValueError("There is not yet a designated connection.") + else: + return __designated_connection + +def __set_designated_connection(conn: synchronous.CryptolSyncConnection) -> None: + global __designated_connection + __designated_connection = conn + +def connected() -> bool: + global __designated_connection + return __designated_connection is not None + +def connect(command : Optional[str]=None, + *, + cryptol_path : Optional[str] = None, + url : Optional[str] = None, + reset_server : bool = False, + verify : Union[bool, str] = True, + log_dest : Optional[TextIO] = None, + timeout : Optional[float] = None) -> None: + """ + Connect to a (possibly new) synchronous Cryptol server process. + + :param command: A command to launch a new Cryptol server in socket mode (if provided). + + :param cryptol_path: A replacement for the contents of + the ``CRYPTOLPATH`` environment variable (if provided). + + :param url: A URL at which to connect to an already running Cryptol + HTTP server. + + :param reset_server: If ``True``, the server that is connected to will be + reset. (This ensures any states from previous server usages have been + cleared.) + + :param verify: Determines whether a secure HTTP connection should verify the SSL certificates. + Corresponds to the ``verify`` keyword parameter on ``requests.post``. N.B., + only has an affect when ``connect`` is called with a ``url`` parameter + or when the ``CRYPTOL_SERVER_URL`` environment variable is set. + + :param log_dest: A destination to log JSON requests/responses to, e.g. ``log_dest=sys.stderr`` + will print traffic to ``stderr``, ``log_dest=open('foo.log', 'w')`` will log to ``foo.log``, + etc. + + :param timeout: Optional default timeout (in seconds) for methods. Can be modified/read via the + the `get_default_timeout` and `set_default_timeout` methods. Method invocations which specify + the optional `timeout` keyword parameter will cause the default to be ignored for that method. + + If no ``command`` or ``url`` parameters are provided, the following are attempted in order: + + 1. If the environment variable ``CRYPTOL_SERVER`` is set and referse to an executable, + it is assumed to be a Cryptol server and will be used for a new ``socket`` connection. + + 2. If the environment variable ``CRYPTOL_SERVER_URL`` is set, it is assumed to be + the URL for a running Cryptol server in ``http`` mode and will be connected to. + + 3. If an executable ``cryptol-remote-api`` is available on the ``PATH`` + it is assumed to be a Cryptol server and will be used for a new ``socket`` connection. + + """ + global __designated_connection + __set_designated_connection(synchronous.connect( + command=command, + cryptol_path=cryptol_path, + url=url, + reset_server=reset_server, + verify=verify, + log_dest=log_dest, + timeout=timeout)) + +def connect_stdio(command : str, + cryptol_path : Optional[str] = None, + log_dest : Optional[TextIO] = None, + timeout : Optional[float] = None) -> None: + """Start a new synchronous connection to a new Cryptol server process. + + :param command: The command to launch the Cryptol server. + + :param cryptol_path: An optional replacement for the contents of + the ``CRYPTOLPATH`` environment variable. + + :param log_dest: A destination to log JSON requests/responses to, e.g. ``log_dest=sys.stderr`` + will print traffic to ``stderr``, ``log_dest=open('foo.log', 'w')`` will log to ``foo.log``, + etc. + + :param timeout: Optional default timeout (in seconds) for methods. Can be modified/read via the + the `get_default_timeout` and `set_default_timeout` methods. Method invocations which specify + the optional `timeout` keyword parameter will cause the default to be ignored for that method. + + """ + __set_designated_connection(synchronous.connect_stdio( + command=command, + cryptol_path=cryptol_path, + log_dest=log_dest, + timeout=timeout)) + + +def get_default_timeout() -> Optional[float]: + """Get the value of the optional default timeout for methods (in seconds).""" + return __get_designated_connection().get_default_timeout() + +def set_default_timeout(timeout : Optional[float]) -> None: + """Set the value of the optional default timeout for methods (in seconds).""" + __get_designated_connection().set_default_timeout(timeout) + +def load_file(filename : str, *, timeout:Optional[float] = None) -> None: + """Load a filename as a Cryptol module, like ``:load`` at the Cryptol + REPL. + """ + __get_designated_connection().load_file(filename, timeout=timeout) + +def load_module(module_name : str, *, timeout:Optional[float] = None) -> None: + """Load a Cryptol module, like ``:module`` at the Cryptol REPL.""" + __get_designated_connection().load_module(module_name, timeout=timeout) + +def extend_search_path(*dir : str, timeout:Optional[float] = None) -> None: + """Extend the search path for loading Cryptol modules.""" + __get_designated_connection().extend_search_path(*dir, timeout=timeout) + +def cry_eval(expression : Any, *, timeout:Optional[float] = None) -> CryptolValue: + """Evaluate a Cryptol expression, with the result represented + according to :ref:`cryptol-json-expression`, with Python datatypes + standing for their JSON equivalents. + """ + return __get_designated_connection().eval(expression, timeout=timeout) + +def cry_eval_f(s : str, *, timeout:Optional[float] = None) -> CryptolValue: + """Parses the given string like ``cry_f``, then evalues it, with the + result represented according to :ref:`cryptol-json-expression`, with + Python datatypes standing for their JSON equivalents. + """ + expression = to_cryptol_str_customf(s, frames=1, filename="") + return cry_eval(expression, timeout=timeout) + +def call(fun : str, *args : List[Any], timeout:Optional[float] = None) -> CryptolValue: + """Evaluate a Cryptol functiom by name, with the arguments and the + result represented according to :ref:`cryptol-json-expression`, with + Python datatypes standing for their JSON equivalents. + """ + return __get_designated_connection().call(fun, *args, timeout=timeout) + +def check(expr : Any, *, num_tests : Union[Literal['all'], int, None] = None, timeout:Optional[float] = None) -> CheckReport: + """Tests the validity of a Cryptol expression with random inputs. The expression must be a function with + return type ``Bit``. + If ``num_tests`` is ``"all"`` then the expression is tested exhaustively (i.e., against all possible inputs). + If ``num_tests`` is omitted, Cryptol defaults to running 100 tests. + """ + return __get_designated_connection().check(expr, num_tests=num_tests, timeout=timeout) + +def check_type(code : Any, *, timeout:Optional[float] = None) -> Union[cryptoltypes.CryptolType, cryptoltypes.CryptolTypeSchema]: + """Check the type of a Cryptol expression, represented according to + :ref:`cryptol-json-expression`, with Python datatypes standing for + their JSON equivalents. + """ + return __get_designated_connection().check_type(code, timeout=timeout) + +@overload +def sat(expr : Any, solver : OfflineSolver, count : int = 1, *, timeout:Optional[float] = None) -> OfflineSmtQuery: ... +@overload +def sat(expr : Any, solver : OnlineSolver = Z3, count : int = 1, *, timeout:Optional[float] = None) -> Union[Satisfiable, Unsatisfiable]: ... +@overload +def sat(expr : Any, solver : Solver = Z3, count : int = 1, *, timeout:Optional[float] = None) -> Union[Satisfiable, Unsatisfiable, OfflineSmtQuery]: ... + +def sat(expr : Any, solver : Solver = Z3, count : int = 1, *, timeout:Optional[float] = None) -> Union[Satisfiable, Unsatisfiable, OfflineSmtQuery]: + """Check the satisfiability of a Cryptol expression, represented according to + :ref:`cryptol-json-expression`, with Python datatypes standing for + their JSON equivalents. Use the solver named `solver`, and return up to + `count` solutions. + """ + return __get_designated_connection().sat(expr, solver, count, timeout=timeout) + +@overload +def prove(expr : Any, solver : OfflineSolver, *, timeout:Optional[float] = None) -> OfflineSmtQuery: ... +@overload +def prove(expr : Any, solver : OnlineSolver = Z3, *, timeout:Optional[float] = None) -> Union[Qed, Counterexample]: ... +@overload +def prove(expr : Any, solver : Solver = Z3, *, timeout:Optional[float] = None) -> Union[Qed, Counterexample, OfflineSmtQuery]: ... + +def prove(expr : Any, solver : Solver = Z3, *, timeout:Optional[float] = None) -> Union[Qed, Counterexample, OfflineSmtQuery]: + """Check the validity of a Cryptol expression, represented according to + :ref:`cryptol-json-expression`, with Python datatypes standing for + their JSON equivalents. Use the solver named `solver`. + """ + return __get_designated_connection().prove(expr, solver, timeout=timeout) + +@overload +def safe(expr : Any, solver : OfflineSolver, *, timeout:Optional[float] = None) -> OfflineSmtQuery: ... +@overload +def safe(expr : Any, solver : OnlineSolver = Z3, *, timeout:Optional[float] = None) -> Union[Safe, Counterexample]: ... +@overload +def safe(expr : Any, solver : Solver = Z3, *, timeout:Optional[float] = None) -> Union[Safe, Counterexample, OfflineSmtQuery]: ... + +def safe(expr : Any, solver : Solver = Z3, *, timeout:Optional[float] = None) -> Union[Safe, Counterexample, OfflineSmtQuery]: + """Check via an external SMT solver that the given term is safe for all inputs, + which means it cannot encounter a run-time error. + """ + return __get_designated_connection().safe(expr, solver, timeout=timeout) + +def names(*, timeout:Optional[float] = None) -> List[Dict[str,Any]]: + """Discover the list of names currently in scope in the current context.""" + return __get_designated_connection().names(timeout=timeout) + +def focused_module(*, timeout:Optional[float] = None) -> Dict[str,Any]: + """Returns the name and other information about the currently-focused module.""" + return __get_designated_connection().focused_module(timeout=timeout) + +def reset() -> None: + """Resets the connection, causing its unique state on the server to be freed (if applicable). + After a reset a connection may be treated as if it were a fresh connection with the server if desired.""" + __get_designated_connection().reset() + +def reset_server() -> None: + """Resets the Cryptol server, clearing all states.""" + __get_designated_connection().reset_server() + +def interrupt() -> None: + """Interrupt the Cryptol server, cancelling any in-progress requests.""" + __get_designated_connection().interrupt() + +def logging(on : bool, *, dest : TextIO = sys.stderr) -> None: + """Whether to log received and transmitted JSON.""" + __get_designated_connection().logging(on=on,dest=dest) diff --git a/cryptol-remote-api/python/cryptol/solver.py b/cryptol-remote-api/python/cryptol/solver.py index cfdc293a..99484fcf 100644 --- a/cryptol-remote-api/python/cryptol/solver.py +++ b/cryptol-remote-api/python/cryptol/solver.py @@ -1,14 +1,23 @@ """Cryptol solver-related definitions""" -from typing import NewType +from abc import ABCMeta, abstractmethod +from typing import Any from dataclasses import dataclass @dataclass class OfflineSmtQuery(): - """An SMTLIB2 script -- produced when an `offline` prover is used.""" + """An SMTLIB2 script -- produced when an `offline` prover is used. Instances + of this class are neither truthy nor falsy, using an instance of this class + in an 'if' or 'while' statement will result in an error. + """ content: str -class Solver(): + def __bool__(self) -> Any: + raise ValueError("Offline SMT query has no value") + def __nonzero__(self) -> Any: + raise ValueError("Offline SMT query has no value") + +class Solver(metaclass=ABCMeta): """An SMT solver mode selectable for Cryptol. Compare with the `:set prover` options in the Cryptol REPL.""" __name: str @@ -27,31 +36,41 @@ class Solver(): """Returns whether hash consing is enabled (if applicable).""" return self.__hash_consing + @abstractmethod def without_hash_consing(self) -> 'Solver': """Returns an identical solver but with hash consing disabled (if applicable).""" - return Solver(name=self.__name, hash_consing=False) + pass + +class OnlineSolver(Solver): + def without_hash_consing(self) -> 'OnlineSolver': + return OnlineSolver(name=self.name(), hash_consing=False) + +class OfflineSolver(Solver): + def without_hash_consing(self) -> 'OfflineSolver': + return OfflineSolver(name=self.name(), hash_consing=False) # Cryptol-supported SMT configurations/solvers # (see Cryptol.Symbolic.SBV Haskell module) -CVC4: Solver = Solver("cvc4") -YICES: Solver = Solver("yices") -Z3: Solver = Solver("z3") -BOOLECTOR: Solver = Solver("boolector") -MATHSAT: Solver = Solver("mathsat") -ABC: Solver = Solver("abc") -OFFLINE: Solver = Solver("offline") -ANY: Solver = Solver("any") -SBV_CVC4: Solver = Solver("sbv-cvc4") -SBV_YICES: Solver = Solver("sbv-yices") -SBV_Z3: Solver = Solver("sbv-z3") -SBV_BOOLECTOR: Solver = Solver("sbv-boolector") -SBV_MATHSAT: Solver = Solver("sbv-mathsat") -SBV_ABC: Solver = Solver("sbv-abc") -SBV_OFFLINE: Solver = Solver("sbv-offline") -SBV_ANY: Solver = Solver("sbv-any") -W4_CVC4: Solver = Solver("w4-cvc4") -W4_YICES: Solver = Solver("w4-yices") -W4_Z3: Solver = Solver("w4-z3") -W4_BOOLECTOR: Solver = Solver("w4-boolector") -W4_OFFLINE: Solver = Solver("w4-offline") -W4_ABC: Solver = Solver("w4-any") +CVC4: OnlineSolver = OnlineSolver("cvc4") +YICES: OnlineSolver = OnlineSolver("yices") +Z3: OnlineSolver = OnlineSolver("z3") +BOOLECTOR: OnlineSolver = OnlineSolver("boolector") +MATHSAT: OnlineSolver = OnlineSolver("mathsat") +ABC: OnlineSolver = OnlineSolver("abc") +OFFLINE: OfflineSolver = OfflineSolver("offline") +ANY: OnlineSolver = OnlineSolver("any") +SBV_CVC4: OnlineSolver = OnlineSolver("sbv-cvc4") +SBV_YICES: OnlineSolver = OnlineSolver("sbv-yices") +SBV_Z3: OnlineSolver = OnlineSolver("sbv-z3") +SBV_BOOLECTOR: OnlineSolver = OnlineSolver("sbv-boolector") +SBV_MATHSAT: OnlineSolver = OnlineSolver("sbv-mathsat") +SBV_ABC: OnlineSolver = OnlineSolver("sbv-abc") +SBV_OFFLINE: OfflineSolver = OfflineSolver("sbv-offline") +SBV_ANY: OnlineSolver = OnlineSolver("sbv-any") +W4_CVC4: OnlineSolver = OnlineSolver("w4-cvc4") +W4_YICES: OnlineSolver = OnlineSolver("w4-yices") +W4_Z3: OnlineSolver = OnlineSolver("w4-z3") +W4_BOOLECTOR: OnlineSolver = OnlineSolver("w4-boolector") +W4_OFFLINE: OfflineSolver = OfflineSolver("w4-offline") +W4_ABC: OnlineSolver = OnlineSolver("w4-abc") +W4_ANY: OnlineSolver = OnlineSolver("w4-any") diff --git a/cryptol-remote-api/python/cryptol/synchronous.py b/cryptol-remote-api/python/cryptol/synchronous.py new file mode 100644 index 00000000..f9b54d45 --- /dev/null +++ b/cryptol-remote-api/python/cryptol/synchronous.py @@ -0,0 +1,381 @@ +"""A synchronous, typed interface for the Cryptol bindings""" + +from __future__ import annotations + +import sys +from typing import Any, Optional, Union, List, Dict, TextIO, overload +from typing_extensions import Literal +from dataclasses import dataclass + +from .custom_fstring import * +from .quoting import * +from .solver import OfflineSmtQuery, Solver, OnlineSolver, OfflineSolver, Z3 +from . import connection +from . import cryptoltypes +from .commands import * +from . import CryptolConnection, SmtQueryType + + +@dataclass +class Qed: + """The positive result of a 'prove' SMT query. All instances of this class + are truthy, i.e. evaluate to `True` in an 'if' or 'while' statement. + """ + def __bool__(self) -> Literal[True]: + return True + def __nonzero__(self) -> Literal[True]: + return True + +@dataclass +class Safe: + """The positive result of a 'safe' SMT query. All instances of this class + are truthy, i.e. evaluate to `True` in an 'if' or 'while' statement. + """ + def __bool__(self) -> Literal[True]: + return True + def __nonzero__(self) -> Literal[True]: + return True + +@dataclass +class Counterexample: + """The negative result of a 'prove' or 'safe' SMT query, consisting of a + type (either "predicate falsified" or "safety violation") and the list of + values which constitute the counterexample. All instances of this class are + falsy, i.e. evaluate to `False` in an 'if' or 'while' statement. (Note that + this is different from the behaivor of a plain list, which is truthy iff + it has nonzero length.) + """ + type : Union[Literal["predicate falsified"], Literal["safety violation"]] + assignments : List[CryptolValue] + + def __bool__(self) -> Literal[False]: + return False + def __nonzero__(self) -> Literal[False]: + return False + +@dataclass +class Satisfiable: + """The positive result of a 'sat' SMT query, consisting of a list of + models, where each model is a list of values satisfying the predicate. + All instances of this class are truthy, i.e. evaluate to `True` in an 'if' + or 'while' statement. (Note that this is different from the behaivor of a + plain list, which is truthy iff it has nonzero length.) + """ + models : List[List[CryptolValue]] + + def __bool__(self) -> Literal[True]: + return True + def __nonzero__(self) -> Literal[True]: + return True + +@dataclass +class Unsatisfiable: + """The negative result of a 'sat' SMT query. All instances of this class + are falsy, i.e. evaluate to `False` in an 'if 'or 'while' statement. + """ + def __bool__(self) -> Literal[False]: + return False + def __nonzero__(self) -> Literal[False]: + return False + + +def connect(command : Optional[str]=None, + *, + cryptol_path : Optional[str] = None, + url : Optional[str] = None, + reset_server : bool = False, + verify : Union[bool, str] = True, + log_dest : Optional[TextIO] = None, + timeout : Optional[float] = None) -> CryptolSyncConnection: + """ + Connect to a (possibly new) synchronous Cryptol server process. + + :param command: A command to launch a new Cryptol server in socket mode (if provided). + + :param cryptol_path: A replacement for the contents of + the ``CRYPTOLPATH`` environment variable (if provided). + + :param url: A URL at which to connect to an already running Cryptol + HTTP server. + + :param reset_server: If ``True``, the server that is connected to will be + reset. (This ensures any states from previous server usages have been + cleared.) + + :param verify: Determines whether a secure HTTP connection should verify the SSL certificates. + Corresponds to the ``verify`` keyword parameter on ``requests.post``. N.B., + only has an affect when ``connect`` is called with a ``url`` parameter + or when the ``CRYPTOL_SERVER_URL`` environment variable is set. + + :param log_dest: A destination to log JSON requests/responses to, e.g. ``log_dest=sys.stderr`` + will print traffic to ``stderr``, ``log_dest=open('foo.log', 'w')`` will log to ``foo.log``, + etc. + + :param timeout: Optional default timeout (in seconds) for methods. Can be modified/read via the + `timeout` property on a `CryptolSyncConnection` or the `get_default_timeout` and + `set_default_timeout` methods. Method invocations which specify the optional `timeout` keyword + parameter will cause the default to be ignored for that method. + + If no ``command`` or ``url`` parameters are provided, the following are attempted in order: + + 1. If the environment variable ``CRYPTOL_SERVER`` is set and referse to an executable, + it is assumed to be a Cryptol server and will be used for a new ``socket`` connection. + + 2. If the environment variable ``CRYPTOL_SERVER_URL`` is set, it is assumed to be + the URL for a running Cryptol server in ``http`` mode and will be connected to. + + 3. If an executable ``cryptol-remote-api`` is available on the ``PATH`` + it is assumed to be a Cryptol server and will be used for a new ``socket`` connection. + + """ + return CryptolSyncConnection(connection.connect( + command=command, + cryptol_path=cryptol_path, + url=url, + reset_server=reset_server, + verify=verify, + log_dest=log_dest, + timeout=timeout)) + +def connect_stdio(command : str, + cryptol_path : Optional[str] = None, + log_dest : Optional[TextIO] = None, + timeout : Optional[float] = None) -> CryptolSyncConnection: + """Start a new synchronous connection to a new Cryptol server process. + + :param command: The command to launch the Cryptol server. + + :param cryptol_path: An optional replacement for the contents of + the ``CRYPTOLPATH`` environment variable. + + :param log_dest: A destination to log JSON requests/responses to, e.g. ``log_dest=sys.stderr`` + will print traffic to ``stderr``, ``log_dest=open('foo.log', 'w')`` will log to ``foo.log``, + etc. + + :param timeout: Optional default timeout (in seconds) for methods. Can be modified/read via the + `timeout` property on a `CryptolSyncConnection` or the `get_default_timeout` and + `set_default_timeout` methods. Method invocations which specify the optional `timeout` keyword + parameter will cause the default to be ignored for that method. + + """ + return CryptolSyncConnection(connection.connect_stdio( + command=command, + cryptol_path=cryptol_path, + log_dest=log_dest, + timeout=timeout)) + + +class CryptolSyncConnection: + """A wrapper of ``CryptolConnection`` with a synchronous, typed interface.""" + connection : CryptolConnection + + def __init__(self, connection : CryptolConnection): + self.connection = connection + + @property + def timeout(self) -> Optional[float]: + return self.connection.timeout + + @timeout.setter + def timeout(self, timeout : Optional[float]) -> None: + self.connection.timeout = timeout + + def get_default_timeout(self) -> Optional[float]: + """Get the value of the optional default timeout for methods (in seconds).""" + return self.connection.get_default_timeout() + + def set_default_timeout(self, timeout : Optional[float]) -> None: + """Set the value of the optional default timeout for methods (in seconds).""" + self.connection.set_default_timeout(timeout) + + def load_file(self, filename : str, *, timeout:Optional[float] = None) -> None: + """Load a filename as a Cryptol module, like ``:load`` at the Cryptol + REPL. + """ + self.connection.load_file(filename, timeout=timeout).result() + + def load_module(self, module_name : str, *, timeout:Optional[float] = None) -> None: + """Load a Cryptol module, like ``:module`` at the Cryptol REPL.""" + self.connection.load_module(module_name, timeout=timeout).result() + + def extend_search_path(self, *dir : str, timeout:Optional[float] = None) -> None: + """Extend the search path for loading Cryptol modules.""" + self.connection.extend_search_path(*dir, timeout=timeout).result() + + def eval(self, expression : Any, *, timeout:Optional[float] = None) -> CryptolValue: + """Evaluate a Cryptol expression, with the result represented + according to :ref:`cryptol-json-expression`, with Python datatypes + standing for their JSON equivalents. + """ + return from_cryptol_arg(self.connection.eval_raw(expression, timeout=timeout).result()) + + def eval_f(self, s : str, *, timeout:Optional[float] = None) -> CryptolValue: + """Parses the given string like ``cry_f``, then evalues it, with the + result represented according to :ref:`cryptol-json-expression`, with + Python datatypes standing for their JSON equivalents. + """ + expression = to_cryptol_str_customf(s, frames=1, filename="") + return self.eval(expression, timeout=timeout) + + def call(self, fun : str, *args : List[Any], timeout:Optional[float] = None) -> CryptolValue: + """Evaluate a Cryptol functiom by name, with the arguments and the + result represented according to :ref:`cryptol-json-expression`, with + Python datatypes standing for their JSON equivalents. + """ + return from_cryptol_arg(self.connection.call_raw(fun, *args, timeout=timeout).result()) + + def check(self, expr : Any, *, num_tests : Union[Literal['all'], int, None] = None, timeout:Optional[float] = None) -> CheckReport: + """Tests the validity of a Cryptol expression with random inputs. The expression must be a function with + return type ``Bit``. + If ``num_tests`` is ``"all"`` then the expression is tested exhaustively (i.e., against all possible inputs). + If ``num_tests`` is omitted, Cryptol defaults to running 100 tests. + """ + return to_check_report(self.connection.check_raw(expr, num_tests=num_tests, timeout=timeout).result()) + + def check_type(self, code : Any, *, timeout:Optional[float] = None) -> Union[cryptoltypes.CryptolType, cryptoltypes.CryptolTypeSchema]: + """Check the type of a Cryptol expression, represented according to + :ref:`cryptol-json-expression`, with Python datatypes standing for + their JSON equivalents. + """ + return cryptoltypes.to_schema_or_type(self.connection.check_type(code, timeout=timeout).result()) + + @overload + def sat(self, expr : Any, solver : OfflineSolver, count : int = 1, *, timeout:Optional[float] = None) -> OfflineSmtQuery: ... + @overload + def sat(self, expr : Any, solver : OnlineSolver = Z3, count : int = 1, *, timeout:Optional[float] = None) -> Union[Satisfiable, Unsatisfiable]: ... + @overload + def sat(self, expr : Any, solver : Solver = Z3, count : int = 1, *, timeout:Optional[float] = None) -> Union[Satisfiable, Unsatisfiable, OfflineSmtQuery]: ... + + def sat(self, expr : Any, solver : Solver = Z3, count : int = 1, *, timeout:Optional[float] = None) -> Union[Satisfiable, Unsatisfiable, OfflineSmtQuery]: + """Check the satisfiability of a Cryptol expression, represented according to + :ref:`cryptol-json-expression`, with Python datatypes standing for + their JSON equivalents. Use the solver named `solver`, and return up to + `count` solutions. + + If the given solver is an `OnlineSolver`, the result is either an + instance of `Satisfiable`, which is always truthy, or `Unsatisfiable`, + which is always falsy - meaning the result will evaluate to `True` in + an 'if' or 'while' statement iff the given expression is satisfiable. + If the given solver is an `OfflineSolver`, an error will be raised if + the result is used in an 'if' or 'while' statement. + """ + if isinstance(solver, OfflineSolver): + res = self.connection.sat_raw(expr, solver, count, timeout=timeout).result() + if res['result'] == 'offline': + return OfflineSmtQuery(res['query']) + else: + raise ValueError("Expected an offline SMT result, got: " + str(res)) + elif isinstance(solver, OnlineSolver): + res = self.connection.sat_raw(expr, solver, count, timeout=timeout).result() + if res['result'] == 'unsatisfiable': + return Unsatisfiable() + elif res['result'] == 'satisfied': + return Satisfiable([[from_cryptol_arg(arg['expr']) for arg in m] for m in res['models']]) + else: + raise ValueError("Unexpected 'sat' SMT result: " + str(res)) + else: + raise ValueError("Unknown solver type: " + str(solver)) + + @overload + def prove(self, expr : Any, solver : OfflineSolver, *, timeout:Optional[float] = None) -> OfflineSmtQuery: ... + @overload + def prove(self, expr : Any, solver : OnlineSolver = Z3, *, timeout:Optional[float] = None) -> Union[Qed, Counterexample]: ... + @overload + def prove(self, expr : Any, solver : Solver = Z3, *, timeout:Optional[float] = None) -> Union[Qed, Counterexample, OfflineSmtQuery]: ... + + def prove(self, expr : Any, solver : Solver = Z3, *, timeout:Optional[float] = None) -> Union[Qed, Counterexample, OfflineSmtQuery]: + """Check the validity of a Cryptol expression, represented according to + :ref:`cryptol-json-expression`, with Python datatypes standing for + their JSON equivalents. Use the solver named `solver`. + + If the given solver is an `OnlineSolver`, the result is either an + instance of `Qed`, which is always truthy, or `Counterexample`, which + is always falsy - meaning the result will evaluate to `True` in an 'if' + or 'while' statement iff the given expression can be proved. If the + given solver is an `OfflineSolver`, an error will be raised if the + result is used in an 'if' or 'while' statement. + """ + if isinstance(solver, OfflineSolver): + res = self.connection.prove_raw(expr, solver, timeout=timeout).result() + if res['result'] == 'offline': + return OfflineSmtQuery(res['query']) + else: + raise ValueError("Expected an offline SMT result, got: " + str(res)) + elif isinstance(solver, OnlineSolver): + res = self.connection.prove_raw(expr, solver, timeout=timeout).result() + if res['result'] == 'unsatisfiable': + return Qed() + elif res['result'] == 'invalid': + return Counterexample(res['counterexample type'], [from_cryptol_arg(arg['expr']) for arg in res['counterexample']]) + else: + raise ValueError("Unexpected 'prove' SMT result: " + str(res)) + else: + raise ValueError("Unknown solver type: " + str(solver)) + + @overload + def safe(self, expr : Any, solver : OfflineSolver, *, timeout:Optional[float] = None) -> OfflineSmtQuery: ... + @overload + def safe(self, expr : Any, solver : OnlineSolver = Z3, *, timeout:Optional[float] = None) -> Union[Safe, Counterexample]: ... + @overload + def safe(self, expr : Any, solver : Solver = Z3, *, timeout:Optional[float] = None) -> Union[Safe, Counterexample, OfflineSmtQuery]: ... + + def safe(self, expr : Any, solver : Solver = Z3, *, timeout:Optional[float] = None) -> Union[Safe, Counterexample, OfflineSmtQuery]: + """Check via an external SMT solver that the given term is safe for all inputs, + which means it cannot encounter a run-time error. + + If the given solver is an `OnlineSolver`, the result is either an + instance of `Safe`, which is always truthy, or `Counterexample`, which + is always falsy - meaning the result will evaluate to `True` in an 'if' + or 'while' statement iff the given expression is safe. If the given + solver is an `OfflineSolver`, an error will be raised if the result is + used in an 'if' or 'while' statement. + """ + if isinstance(solver, OfflineSolver): + res = self.connection.safe_raw(expr, solver, timeout=timeout).result() + if res['result'] == 'offline': + return OfflineSmtQuery(res['query']) + else: + raise ValueError("Expected an offline SMT result, got: " + str(res)) + elif isinstance(solver, OnlineSolver): + res = self.connection.safe_raw(expr, solver, timeout=timeout).result() + if res['result'] == 'unsatisfiable': + return Safe() + elif res['result'] == 'invalid': + return Counterexample(res['counterexample type'], [from_cryptol_arg(arg['expr']) for arg in res['counterexample']]) + else: + raise ValueError("Unexpected 'safe' SMT result: " + str(res)) + else: + raise ValueError("Unknown solver type: " + str(solver)) + + def names(self, *, timeout:Optional[float] = None) -> List[Dict[str,Any]]: + """Discover the list of names currently in scope in the current context.""" + res = self.connection.names(timeout=timeout).result() + if isinstance(res, list) and all(isinstance(d, dict) and all(isinstance(k, str) for k in d.keys()) for d in res): + return res + else: + raise ValueError("Panic! Result of `names()` is malformed: " + str(res)) + + def focused_module(self, *, timeout:Optional[float] = None) -> Dict[str,Any]: + """Returns the name and other information about the currently-focused module.""" + res = self.connection.focused_module(timeout=timeout).result() + if isinstance(res, dict) and all(isinstance(k, str) for k in res.keys()): + return res + else: + raise ValueError("Panic! Result of `focused_module()` is malformed: " + str(res)) + + def reset(self) -> None: + """Resets the connection, causing its unique state on the server to be freed (if applicable). + After a reset a connection may be treated as if it were a fresh connection with the server if desired.""" + self.connection.reset() + + def reset_server(self) -> None: + """Resets the Cryptol server, clearing all states.""" + self.connection.reset_server() + + def interrupt(self) -> None: + """Interrupt the Cryptol server, cancelling any in-progress requests.""" + self.connection.interrupt() + + def logging(self, on : bool, *, dest : TextIO = sys.stderr) -> None: + """Whether to log received and transmitted JSON.""" + self.connection.server_connection.logging(on=on,dest=dest) diff --git a/cryptol-remote-api/python/poetry.lock b/cryptol-remote-api/python/poetry.lock index 26ae178e..18ea3eb7 100644 --- a/cryptol-remote-api/python/poetry.lock +++ b/cryptol-remote-api/python/poetry.lock @@ -1,14 +1,14 @@ [[package]] name = "argo-client" -version = "0.0.5" +version = "0.0.10" description = "A JSON RPC client library." category = "main" optional = false -python-versions = ">=3.7" +python-versions = ">=3.7.0,<4" [package.dependencies] -mypy = "*" -requests = "*" +requests = ">=2.26.0,<3.0.0" +urllib3 = ">=1.26.5" [[package]] name = "bitvector" @@ -20,33 +20,36 @@ python-versions = "*" [[package]] name = "certifi" -version = "2021.5.30" +version = "2021.10.8" description = "Python package for providing Mozilla's CA Bundle." category = "main" optional = false python-versions = "*" [[package]] -name = "chardet" -version = "4.0.0" -description = "Universal encoding detector for Python 2 and 3" +name = "charset-normalizer" +version = "2.0.9" +description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet." category = "main" optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" +python-versions = ">=3.5.0" + +[package.extras] +unicode_backport = ["unicodedata2"] [[package]] name = "idna" -version = "2.10" +version = "3.3" description = "Internationalized Domain Names in Applications (IDNA)" category = "main" optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" +python-versions = ">=3.5" [[package]] name = "mypy" version = "0.812" description = "Optional static typing for Python" -category = "main" +category = "dev" optional = false python-versions = ">=3.5" @@ -62,80 +65,81 @@ dmypy = ["psutil (>=4.0)"] name = "mypy-extensions" version = "0.4.3" description = "Experimental type system extensions for programs checked with the mypy typechecker." -category = "main" +category = "dev" optional = false python-versions = "*" [[package]] name = "requests" -version = "2.25.1" +version = "2.26.0" description = "Python HTTP for Humans." category = "main" optional = false -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*" [package.dependencies] certifi = ">=2017.4.17" -chardet = ">=3.0.2,<5" -idna = ">=2.5,<3" +charset-normalizer = {version = ">=2.0.0,<2.1.0", markers = "python_version >= \"3\""} +idna = {version = ">=2.5,<4", markers = "python_version >= \"3\""} urllib3 = ">=1.21.1,<1.27" [package.extras] -security = ["pyOpenSSL (>=0.14)", "cryptography (>=1.3.4)"] socks = ["PySocks (>=1.5.6,!=1.5.7)", "win-inet-pton"] +use_chardet_on_py3 = ["chardet (>=3.0.2,<5)"] [[package]] name = "typed-ast" version = "1.4.3" description = "a fork of Python 2 and 3 ast modules with type comment support" -category = "main" +category = "dev" optional = false python-versions = "*" [[package]] name = "typing-extensions" -version = "3.10.0.0" -description = "Backported and Experimental Type Hints for Python 3.5+" -category = "main" +version = "4.0.1" +description = "Backported and Experimental Type Hints for Python 3.6+" +category = "dev" optional = false -python-versions = "*" +python-versions = ">=3.6" [[package]] name = "urllib3" -version = "1.22" +version = "1.26.7" description = "HTTP library with thread-safe connection pooling, file post, and more." category = "main" optional = false -python-versions = "*" +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, <4" [package.extras] +brotli = ["brotlipy (>=0.6.0)"] secure = ["pyOpenSSL (>=0.14)", "cryptography (>=1.3.4)", "idna (>=2.0.0)", "certifi", "ipaddress"] socks = ["PySocks (>=1.5.6,!=1.5.7,<2.0)"] [metadata] lock-version = "1.1" -python-versions = ">=3.7.0" -content-hash = "4fec48a3684b15cd29af1c2f3db5a9033d34a1605ad11aec7babafd2f6bcb1b1" +python-versions = ">=3.7.0,<4" +content-hash = "bee495c33e4a9b337c16d6039644b59138929406641542ed7c8f434e38625811" [metadata.files] argo-client = [ - {file = "argo-client-0.0.5.tar.gz", hash = "sha256:9b2157f3ea953df812948c27eb762dbe8401bb9d0dc74f49310b6636320a0347"}, - {file = "argo_client-0.0.5-py3-none-any.whl", hash = "sha256:745239a231a0d891088ca2aedebd7ec075faf0f19c2f6b0ceafd252e3eed616d"}, + {file = "argo-client-0.0.10.tar.gz", hash = "sha256:a95e07201a5e23758e7bc6b2e1d594c61a71df02ff534ad7a8db32fdb991ed0b"}, + {file = "argo_client-0.0.10-py3-none-any.whl", hash = "sha256:d86e07bfc421faf9f25be6af2d4a0c7fd2ddef7a759488f6c05baa2ff2c1e390"}, ] bitvector = [ {file = "BitVector-3.5.0.tar.gz", hash = "sha256:cac2fbccf11e325115827ed7be03e5fd62615227b0bbf3fa5a18a842a221839c"}, ] certifi = [ - {file = "certifi-2021.5.30-py2.py3-none-any.whl", hash = "sha256:50b1e4f8446b06f41be7dd6338db18e0990601dce795c2b1686458aa7e8fa7d8"}, - {file = "certifi-2021.5.30.tar.gz", hash = "sha256:2bbf76fd432960138b3ef6dda3dde0544f27cbf8546c458e60baf371917ba9ee"}, + {file = "certifi-2021.10.8-py2.py3-none-any.whl", hash = "sha256:d62a0163eb4c2344ac042ab2bdf75399a71a2d8c7d47eac2e2ee91b9d6339569"}, + {file = "certifi-2021.10.8.tar.gz", hash = "sha256:78884e7c1d4b00ce3cea67b44566851c4343c120abd683433ce934a68ea58872"}, ] -chardet = [ - {file = "chardet-4.0.0-py2.py3-none-any.whl", hash = "sha256:f864054d66fd9118f2e67044ac8981a54775ec5b67aed0441892edb553d21da5"}, - {file = "chardet-4.0.0.tar.gz", hash = "sha256:0d6f53a15db4120f2b08c94f11e7d93d2c911ee118b6b30a04ec3ee8310179fa"}, +charset-normalizer = [ + {file = "charset-normalizer-2.0.9.tar.gz", hash = "sha256:b0b883e8e874edfdece9c28f314e3dd5badf067342e42fb162203335ae61aa2c"}, + {file = "charset_normalizer-2.0.9-py3-none-any.whl", hash = "sha256:1eecaa09422db5be9e29d7fc65664e6c33bd06f9ced7838578ba40d58bdf3721"}, ] idna = [ - {file = "idna-2.10-py2.py3-none-any.whl", hash = "sha256:b97d804b1e9b523befed77c48dacec60e6dcb0b5391d57af6a65a312a90648c0"}, - {file = "idna-2.10.tar.gz", hash = "sha256:b307872f855b18632ce0c21c5e45be78c0ea7ae4c15c828c20788b26921eb3f6"}, + {file = "idna-3.3-py3-none-any.whl", hash = "sha256:84d9dd047ffa80596e0f246e2eab0b391788b0503584e8945f2368256d2735ff"}, + {file = "idna-3.3.tar.gz", hash = "sha256:9d643ff0a55b762d5cdb124b8eaa99c66322e2157b69160bc32796e824360e6d"}, ] mypy = [ {file = "mypy-0.812-cp35-cp35m-macosx_10_9_x86_64.whl", hash = "sha256:a26f8ec704e5a7423c8824d425086705e381b4f1dfdef6e3a1edab7ba174ec49"}, @@ -166,8 +170,8 @@ mypy-extensions = [ {file = "mypy_extensions-0.4.3.tar.gz", hash = "sha256:2d82818f5bb3e369420cb3c4060a7970edba416647068eb4c5343488a6c604a8"}, ] requests = [ - {file = "requests-2.25.1-py2.py3-none-any.whl", hash = "sha256:c210084e36a42ae6b9219e00e48287def368a26d03a048ddad7bfee44f75871e"}, - {file = "requests-2.25.1.tar.gz", hash = "sha256:27973dd4a904a4f13b263a19c866c13b92a39ed1c964655f025f3f8d3d75b804"}, + {file = "requests-2.26.0-py2.py3-none-any.whl", hash = "sha256:6c1246513ecd5ecd4528a0906f910e8f0f9c6b8ec72030dc9fd154dc1a6efd24"}, + {file = "requests-2.26.0.tar.gz", hash = "sha256:b8aa58f8cf793ffd8782d3d8cb19e66ef36f7aba4353eec859e74678b01b07a7"}, ] typed-ast = [ {file = "typed_ast-1.4.3-cp35-cp35m-manylinux1_i686.whl", hash = "sha256:2068531575a125b87a41802130fa7e29f26c09a2833fea68d9a40cf33902eba6"}, @@ -202,11 +206,10 @@ typed-ast = [ {file = "typed_ast-1.4.3.tar.gz", hash = "sha256:fb1bbeac803adea29cedd70781399c99138358c26d05fcbd23c13016b7f5ec65"}, ] typing-extensions = [ - {file = "typing_extensions-3.10.0.0-py2-none-any.whl", hash = "sha256:0ac0f89795dd19de6b97debb0c6af1c70987fd80a2d62d1958f7e56fcc31b497"}, - {file = "typing_extensions-3.10.0.0-py3-none-any.whl", hash = "sha256:779383f6086d90c99ae41cf0ff39aac8a7937a9283ce0a414e5dd782f4c94a84"}, - {file = "typing_extensions-3.10.0.0.tar.gz", hash = "sha256:50b6f157849174217d0656f99dc82fe932884fb250826c18350e159ec6cdf342"}, + {file = "typing_extensions-4.0.1-py3-none-any.whl", hash = "sha256:7f001e5ac290a0c0401508864c7ec868be4e701886d5b573a9528ed3973d9d3b"}, + {file = "typing_extensions-4.0.1.tar.gz", hash = "sha256:4ca091dea149f945ec56afb48dae714f21e8692ef22a395223bcd328961b6a0e"}, ] urllib3 = [ - {file = "urllib3-1.22-py2.py3-none-any.whl", hash = "sha256:06330f386d6e4b195fbfc736b297f58c5a892e4440e54d294d7004e3a9bbea1b"}, - {file = "urllib3-1.22.tar.gz", hash = "sha256:cc44da8e1145637334317feebd728bd869a35285b93cbb4cca2577da7e62db4f"}, + {file = "urllib3-1.26.7-py2.py3-none-any.whl", hash = "sha256:c4fdf4019605b6e5423637e01bc9fe4daef873709a7973e195ceba0a62bbc844"}, + {file = "urllib3-1.26.7.tar.gz", hash = "sha256:4987c65554f7a2dbf30c18fd48778ef124af6fab771a377103da0585e2336ece"}, ] diff --git a/cryptol-remote-api/python/pyproject.toml b/cryptol-remote-api/python/pyproject.toml index 430de631..3bb93107 100644 --- a/cryptol-remote-api/python/pyproject.toml +++ b/cryptol-remote-api/python/pyproject.toml @@ -1,10 +1,11 @@ [tool.poetry] name = "cryptol" -version = "2.11.2" +version = "2.12.3" readme = "README.md" keywords = ["cryptography", "verification"] -description = "Cryptol client for the Cryptol 2.11 RPC server" -authors = ["Andrew Kent ", "Aaron Tomb "] +description = "Cryptol client for the Cryptol 2.12 RPC server" +authors = ["Galois, Inc. "] + license = "BSD License" include = [ "LICENSE", @@ -12,10 +13,10 @@ include = [ ] [tool.poetry.dependencies] -python = ">=3.7.0" +python = ">=3.7.0,<4" requests = "^2.25.1" BitVector = "^3.4.9" -argo-client = "0.0.5" +argo-client = "0.0.10" [tool.poetry.dev-dependencies] mypy = "^0.812" diff --git a/cryptol-remote-api/python/tests/cryptol/test-files/Types.cry b/cryptol-remote-api/python/tests/cryptol/test-files/Types.cry new file mode 100644 index 00000000..5ab30a52 --- /dev/null +++ b/cryptol-remote-api/python/tests/cryptol/test-files/Types.cry @@ -0,0 +1,28 @@ +module Types where + +b : Bit +b = True + +w : [16] +w = 42 + +z : Integer +z = 420000 + +m : Z 12 +m = 6 + +q : Rational +q = ratio 5 4 + +t : (Bit, Integer) +t = (False, 7) + +s : [3][3][8] +s = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + +r : {xCoord : [32], yCoord : [32]} +r = {xCoord = 12 : [32], yCoord = 21 : [32]} + +id : {n} (fin n) => [n] -> [n] +id a = a diff --git a/cryptol-remote-api/python/tests/cryptol/test_AES.py b/cryptol-remote-api/python/tests/cryptol/test_AES.py index 65e155a0..0f458629 100644 --- a/cryptol-remote-api/python/tests/cryptol/test_AES.py +++ b/cryptol-remote-api/python/tests/cryptol/test_AES.py @@ -2,36 +2,37 @@ import unittest from pathlib import Path import unittest import cryptol +from cryptol.single_connection import * from cryptol.bitvector import BV class TestAES(unittest.TestCase): def test_AES(self): - c = cryptol.connect(verify=False) - c.load_file(str(Path('tests','cryptol','test-files', 'examples','AES.cry'))) + connect(verify=False) + load_file(str(Path('tests','cryptol','test-files', 'examples','AES.cry'))) pt = BV(size=128, value=0x3243f6a8885a308d313198a2e0370734) key = BV(size=128, value=0x2b7e151628aed2a6abf7158809cf4f3c) - ct = c.call("aesEncrypt", (pt, key)).result() + ct = call("aesEncrypt", (pt, key)) expected_ct = BV(size=128, value=0x3925841d02dc09fbdc118597196a0b32) self.assertEqual(ct, expected_ct) - decrypted_ct = c.call("aesDecrypt", (ct, key)).result() + decrypted_ct = call("aesDecrypt", (ct, key)) self.assertEqual(pt, decrypted_ct) pt = BV(size=128, value=0x00112233445566778899aabbccddeeff) key = BV(size=128, value=0x000102030405060708090a0b0c0d0e0f) - ct = c.call("aesEncrypt", (pt, key)).result() + ct = call("aesEncrypt", (pt, key)) expected_ct = BV(size=128, value=0x69c4e0d86a7b0430d8cdb78070b4c55a) self.assertEqual(ct, expected_ct) - decrypted_ct = c.call("aesDecrypt", (ct, key)).result() + decrypted_ct = call("aesDecrypt", (ct, key)) self.assertEqual(pt, decrypted_ct) - self.assertTrue(c.safe("aesEncrypt")) - self.assertTrue(c.safe("aesDecrypt")) - self.assertTrue(c.check("AESCorrect").result().success) - # c.prove("AESCorrect") # probably takes too long for this script...? + self.assertTrue(safe("aesEncrypt")) + self.assertTrue(safe("aesDecrypt")) + self.assertTrue(check("AESCorrect")) + # prove("AESCorrect") # probably takes too long for this script...? diff --git a/cryptol-remote-api/python/tests/cryptol/test_CplxQNewtype.py b/cryptol-remote-api/python/tests/cryptol/test_CplxQNewtype.py index 7b7bb318..67212837 100644 --- a/cryptol-remote-api/python/tests/cryptol/test_CplxQNewtype.py +++ b/cryptol-remote-api/python/tests/cryptol/test_CplxQNewtype.py @@ -2,30 +2,31 @@ import unittest from pathlib import Path import unittest import cryptol +from cryptol.single_connection import * from cryptol.bitvector import BV class TestCplxQ(unittest.TestCase): def test_CplxQ(self): - c = cryptol.connect(reset_server=True, verify=False) - c.load_file(str(Path('tests','cryptol','test-files', 'CplxQNewtype.cry'))) + connect(verify=False) + load_file(str(Path('tests','cryptol','test-files', 'CplxQNewtype.cry'))) - forty_two = c.eval("fortyTwo").result() - cplx_forty_two1 = c.call("embedQ", forty_two).result() - cplx_forty_two2 = c.eval("CplxQ{ real = 42, imag = 0 }").result() - cplx_two = c.eval("cplxTwo").result() - cplx_forty = c.eval("cplxForty").result() - cplx_forty_two3 = c.call("cplxAdd", cplx_two, cplx_forty).result() - cplx_forty_two4 = c.eval("cplxMul (CplxQ{ real = 21, imag = 0 }) (CplxQ{ real = 2, imag = 0 })").result() - cplx_forty_two5 = c.eval("cplxAdd (CplxQ{ real = 41, imag = 0 }) (CplxQ{ real = 1, imag = 0 })").result() - cplx_forty_two6 = c.eval("CplxQ{ real = 42, imag = 0 }").result() + forty_two = cry_eval("fortyTwo") + cplx_forty_two1 = call("embedQ", forty_two) + cplx_forty_two2 = cry_eval("CplxQ{ real = 42, imag = 0 }") + cplx_two = cry_eval("cplxTwo") + cplx_forty = cry_eval("cplxForty") + cplx_forty_two3 = call("cplxAdd", cplx_two, cplx_forty) + cplx_forty_two4 = cry_eval("cplxMul (CplxQ{ real = 21, imag = 0 }) (CplxQ{ real = 2, imag = 0 })") + cplx_forty_two5 = cry_eval("cplxAdd (CplxQ{ real = 41, imag = 0 }) (CplxQ{ real = 1, imag = 0 })") + cplx_forty_two6 = cry_eval("CplxQ{ real = 42, imag = 0 }") - self.assertTrue(c.call("cplxEq", cplx_forty_two1, cplx_forty_two2).result()) - self.assertFalse(c.call("cplxEq", cplx_two, cplx_forty_two2).result()) - self.assertTrue(c.call("cplxEq", cplx_forty_two1, cplx_forty_two3).result()) - self.assertTrue(c.call("cplxEq", cplx_forty_two1, cplx_forty_two4).result()) - self.assertTrue(c.call("cplxEq", cplx_forty_two1, cplx_forty_two5).result()) - self.assertTrue(c.call("cplxEq", cplx_forty_two1, cplx_forty_two6).result()) + self.assertTrue(call("cplxEq", cplx_forty_two1, cplx_forty_two2)) + self.assertFalse(call("cplxEq", cplx_two, cplx_forty_two2)) + self.assertTrue(call("cplxEq", cplx_forty_two1, cplx_forty_two3)) + self.assertTrue(call("cplxEq", cplx_forty_two1, cplx_forty_two4)) + self.assertTrue(call("cplxEq", cplx_forty_two1, cplx_forty_two5)) + self.assertTrue(call("cplxEq", cplx_forty_two1, cplx_forty_two6)) diff --git a/cryptol-remote-api/python/tests/cryptol/test_DES.py b/cryptol-remote-api/python/tests/cryptol/test_DES.py index 9fd2b43e..1ed3c71f 100644 --- a/cryptol-remote-api/python/tests/cryptol/test_DES.py +++ b/cryptol-remote-api/python/tests/cryptol/test_DES.py @@ -2,44 +2,44 @@ import unittest from pathlib import Path import unittest import cryptol -from cryptol.cryptoltypes import CryptolApplication, CryptolLiteral +from cryptol.single_connection import * from cryptol.bitvector import BV class TestDES(unittest.TestCase): - def test_SHA256(self): - c = cryptol.connect(verify=False) - c.load_file(str(Path('tests','cryptol','test-files','examples','DEStest.cry'))) + def test_DES(self): + connect(verify=False) + load_file(str(Path('tests','cryptol','test-files','examples','DEStest.cry'))) # we can run the test suite as indended... - # vkres = c.eval('vktest DES').result() + # vkres = cry_eval('vktest DES') # self.assertTrue(all(passed for (_,_,passed) in vkres)) - # vtres = c.eval('vttest DES').result() + # vtres = cry_eval('vttest DES') # self.assertTrue(all(passed for (_,_,passed) in vtres)) - # kares = c.eval('katest DES').result() + # kares = cry_eval('katest DES') # self.assertTrue(all(passed for (_,_,passed) in kares)) # ...but we can also do it manually, using the python bindings more def test(key, pt0, ct0): - ct1 = c.call('DES.encrypt', key, pt0).result() - pt1 = c.call('DES.decrypt', key, ct0).result() + ct1 = call('DES.encrypt', key, pt0) + pt1 = call('DES.decrypt', key, ct0) self.assertEqual(ct0, ct1) self.assertEqual(pt0, pt1) # vktest - vk = c.eval('vk').result() + vk = cry_eval('vk') pt0 = BV(size=64, value=0) for (key, ct0) in vk: test(key, pt0, ct0) # vttest - vt = c.eval('vt').result() + vt = cry_eval('vt') key = BV(size=64, value=0x0101010101010101) for (pt0, ct0) in vt: test(key, pt0, ct0) # katest - ka = c.eval('ka').result() + ka = cry_eval('ka') for (key, pt0, ct0) in ka: test(key, pt0, ct0) diff --git a/cryptol-remote-api/python/tests/cryptol/test_EvenMansour.py b/cryptol-remote-api/python/tests/cryptol/test_EvenMansour.py index ed6bcf13..5980bd2d 100644 --- a/cryptol-remote-api/python/tests/cryptol/test_EvenMansour.py +++ b/cryptol-remote-api/python/tests/cryptol/test_EvenMansour.py @@ -2,24 +2,24 @@ import unittest from pathlib import Path import unittest import cryptol -from cryptol.cryptoltypes import CryptolApplication, CryptolLiteral +from cryptol.single_connection import * from cryptol.bitvector import BV class TestEvenMansour(unittest.TestCase): def test_EvenMansour(self): - c = cryptol.connect(verify=False) - c.load_file(str(Path('tests','cryptol','test-files','examples','contrib','EvenMansour.cry'))) + connect(verify=False) + load_file(str(Path('tests','cryptol','test-files','examples','contrib','EvenMansour.cry'))) - F_10_4 = c.eval('F:[10][4]').result() - self.assertTrue(c.call('is_a_permutation', F_10_4).result()) + F_10_4 = cry_eval('F:[10][4]') + self.assertTrue(call('is_a_permutation', F_10_4)) - Finv_10_4 = c.eval("F':[10][4]").result() + Finv_10_4 = cry_eval("F':[10][4]") digits = [ BV(size=4, value=i) for i in range(0,10) ] - # ^ the same as: c.eval('[0..9]:[_][4]').result() - self.assertTrue(c.call('is_inverse_permutation', digits, F_10_4, Finv_10_4).result()) + # ^ the same as: c.eval('[0..9]:[_][4]') + self.assertTrue(call('is_inverse_permutation', digits, F_10_4, Finv_10_4)) - self.assertTrue(c.check('E_and_D_are_inverses').result().success) + self.assertTrue(check('E_and_D_are_inverses')) if __name__ == "__main__": diff --git a/cryptol-remote-api/python/tests/cryptol/test_SHA256.py b/cryptol-remote-api/python/tests/cryptol/test_SHA256.py index 0ac3f744..9957c96f 100644 --- a/cryptol-remote-api/python/tests/cryptol/test_SHA256.py +++ b/cryptol-remote-api/python/tests/cryptol/test_SHA256.py @@ -2,30 +2,31 @@ import unittest from pathlib import Path import unittest import cryptol -from cryptol.cryptoltypes import CryptolApplication, CryptolLiteral +from cryptol.single_connection import * +from cryptol.cryptoltypes import CryptolLiteral from cryptol.bitvector import BV class TestSHA256(unittest.TestCase): def test_SHA256(self): - c = cryptol.connect(verify=False) - c.load_file(str(Path('tests','cryptol','test-files','examples','param_modules','SHA.cry'))) + connect(verify=False) + load_file(str(Path('tests','cryptol','test-files','examples','param_modules','SHA.cry'))) m1 = CryptolLiteral('"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"') - j1 = c.call('join', m1).result() - h1 = c.call('sha256', j1).result() + j1 = call('join', m1) + h1 = call('sha256', j1) expected_h1 = BV(size=256, value=0x248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1) self.assertEqual(h1, expected_h1) m2 = CryptolLiteral('""') - j2 = c.call('join', m2).result() - h2 = c.call('sha256', j2).result() + j2 = call('join', m2) + h2 = call('sha256', j2) expected_h2 = BV(size=256, value=0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855) self.assertEqual(h2, expected_h2) m3 = CryptolLiteral('"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"') - j3 = c.call('join', m3).result() - h3 = c.call('sha256', j3).result() + j3 = call('join', m3) + h3 = call('sha256', j3) expected_h3 = BV(size=256, value=0xcf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1) self.assertEqual(h3, expected_h3) diff --git a/cryptol-remote-api/python/tests/cryptol/test_basics.py b/cryptol-remote-api/python/tests/cryptol/test_basics.py index f95c050b..750d47d7 100644 --- a/cryptol-remote-api/python/tests/cryptol/test_basics.py +++ b/cryptol-remote-api/python/tests/cryptol/test_basics.py @@ -1,16 +1,14 @@ import unittest +from argo_client.interaction import ArgoException from pathlib import Path +import unittest +import io import os -from pathlib import Path -import subprocess import time -import unittest -import signal from distutils.spawn import find_executable import cryptol -import argo_client.connection as argo import cryptol.cryptoltypes -from cryptol import solver +from cryptol.single_connection import * from cryptol.bitvector import BV from BitVector import * #type: ignore @@ -19,27 +17,178 @@ from BitVector import * #type: ignore # focused on intricate Cryptol specifics per se. class BasicServerTests(unittest.TestCase): - # Connection to cryptol - c = None @classmethod def setUpClass(self): self.c = cryptol.connect(verify=False) - @classmethod - def tearDownClass(self): - if self.c: - self.c.reset() - def test_extend_search_path(self): - """Test that extending the search path acts as expected w.r.t. loads.""" + # Test that extending the search path acts as expected w.r.t. loads c = self.c c.extend_search_path(str(Path('tests','cryptol','test-files', 'test-subdir'))) - c.load_module('Bar') - ans1 = c.evaluate_expression("theAnswer").result() - ans2 = c.evaluate_expression("id theAnswer").result() + c.load_module('Bar').result() + ans1 = c.eval("theAnswer").result() + ans2 = c.eval("id theAnswer").result() self.assertEqual(ans1, ans2) + def test_logging(self): + c = self.c + c.extend_search_path(str(Path('tests','cryptol','test-files', 'test-subdir'))) + c.load_module('Bar').result() + + log_buffer = io.StringIO() + c.logging(on=True, dest=log_buffer) + _ = c.eval("theAnswer").result() + contents = log_buffer.getvalue() + + self.assertEqual(len(contents.strip().splitlines()), 2, + msg=f'log contents: {str(contents.strip().splitlines())}') + + _ = c.eval("theAnswer").result() + + + def test_check_timeout(self): + c = self.c + c.load_file(str(Path('tests','cryptol','test-files', 'examples','AES.cry'))).result() + + t1 = time.time() + with self.assertRaises(ArgoException): + c.check("\\(bv : [256]) -> ~ (~ (~ (~bv))) == bv", num_tests="all", timeout=1.0).result() + t2 = time.time() + self.assertLess(t2 - t1, 2.0) + + t1 = time.time() + with self.assertRaises(ArgoException): + c.check("\\(bv : [256]) -> ~ (~ (~ (~bv))) == bv", num_tests="all", timeout=5.0).result() + t2 = time.time() + self.assertLess(t2 - t1, 7) + + t1 = time.time() + c.check("\\(bv : [256]) -> ~ (~ (~ (~bv))) == bv", num_tests=10, timeout=5.0).result() + t2 = time.time() + self.assertLess(t2 - t1, 5) + + def test_interrupt(self): + # Check if this test is using a local server, if not we assume it's a remote HTTP server + if os.getenv('CRYPTOL_SERVER') is not None or find_executable('cryptol-remote-api'): + c = self.c + c.load_file(str(Path('tests','cryptol','test-files', 'examples','AES.cry'))) + + t1 = time.time() + c.check("\\(bv : [256]) -> ~ (~ (~ (~bv))) == bv", num_tests="all", timeout=30.0) + # ^ .result() intentionally omitted so we don't wait on it's result and we can interrupt + # it on the next line. We add a timeout just in case to the test fails + time.sleep(.5) + c.interrupt() + self.assertTrue(c.safe("aesEncrypt").result()) + t2 = time.time() + self.assertLess(t2 - t1, 15.0) # ensure th interrupt ended things and not the timeout + elif os.getenv('CRYPTOL_SERVER_URL') is not None: + c = self.c + other_c = cryptol.connect(verify=False) + # Since this is the HTTP server, due to client implementation details + # the requests don't return until they get a response, so we fork + # to interrupt the server + newpid = os.fork() + if newpid == 0: + time.sleep(5) + other_c.interrupt() + os._exit(0) + + c.load_file(str(Path('tests','cryptol','test-files', 'examples','AES.cry'))) + + t1 = time.time() + c.check("\\(bv : [256]) -> ~ (~ (~ (~bv))) == bv", num_tests="all", timeout=60.0) + self.assertTrue(c.safe("aesEncrypt").result()) + t2 = time.time() + self.assertLess(t2 - t1, 20.0) # ensure th interrupt ended things and not the timeout + else: + # Otherwise fail... since this shouldn't be possible + self.assertFalse("Impossible") + + + def test_prove_timeout(self): + c = self.c + c.load_file(str(Path('tests','cryptol','test-files', 'examples','AES.cry'))) + + pt = BV(size=128, value=0x3243f6a8885a308d313198a2e0370734) + key = BV(size=128, value=0x2b7e151628aed2a6abf7158809cf4f3c) + ct = c.call("aesEncrypt", (pt, key)).result() + expected_ct = BV(size=128, value=0x3925841d02dc09fbdc118597196a0b32) + self.assertEqual(ct, expected_ct) + + decrypted_ct = c.call("aesDecrypt", (ct, key)).result() + self.assertEqual(pt, decrypted_ct) + + pt = BV(size=128, value=0x00112233445566778899aabbccddeeff) + key = BV(size=128, value=0x000102030405060708090a0b0c0d0e0f) + ct = c.call("aesEncrypt", (pt, key)).result() + expected_ct = BV(size=128, value=0x69c4e0d86a7b0430d8cdb78070b4c55a) + self.assertEqual(ct, expected_ct) + + decrypted_ct = c.call("aesDecrypt", (ct, key)).result() + self.assertEqual(pt, decrypted_ct) + + self.assertTrue(c.safe("aesEncrypt").result()) + self.assertTrue(c.safe("aesDecrypt").result()) + self.assertTrue(c.check("AESCorrect").result().success) + t1 = time.time() + with self.assertRaises(ArgoException): + c.prove("AESCorrect", timeout=1.0).result() + t2 = time.time() + # check the timeout worked + self.assertGreaterEqual(t2 - t1, 1.0) + self.assertLess(t2 - t1, 5.0) + + # make sure things are still working + self.assertTrue(c.safe("aesEncrypt").result()) + + # set the timeout at the connection level + c.timeout = 1.0 + t1 = time.time() + with self.assertRaises(ArgoException): + c.prove("AESCorrect").result() + t2 = time.time() + # check the timeout worked + self.assertGreaterEqual(t2 - t1, 1.0) + self.assertLess(t2 - t1, 5.0) + + # make sure things are still working + c.timeout = None + self.assertTrue(c.safe("aesEncrypt").result()) + + c.timeout = 1.0 + t1 = time.time() + with self.assertRaises(ArgoException): + # override timeout with longer time + c.prove("AESCorrect", timeout=5.0).result() + t2 = time.time() + self.assertGreaterEqual(t2 - t1, 5.0) + self.assertLess(t2 - t1, 10.0) + + # make sure things are still working + c.timeout = None + self.assertTrue(c.safe("aesEncrypt").result()) + + +class BasicLoggingServerTests(unittest.TestCase): + # Connection to cryptol + log_buffer = None + + @classmethod + def setUpClass(self): + self.log_buffer = io.StringIO() + connect(verify=False, log_dest = self.log_buffer) + + def test_logging(self): + extend_search_path(str(Path('tests','cryptol','test-files', 'test-subdir'))) + load_module('Bar') + _ = cry_eval("theAnswer") + content_lines = self.log_buffer.getvalue().strip().splitlines() + + self.assertEqual(len(content_lines), 6, + msg=f'log contents: {str(content_lines)}') + if __name__ == "__main__": unittest.main() diff --git a/cryptol-remote-api/python/tests/cryptol/test_cryptol_api.py b/cryptol-remote-api/python/tests/cryptol/test_cryptol_api.py index 14d2ea28..844aa6f7 100644 --- a/cryptol-remote-api/python/tests/cryptol/test_cryptol_api.py +++ b/cryptol-remote-api/python/tests/cryptol/test_cryptol_api.py @@ -10,39 +10,32 @@ from distutils.spawn import find_executable import cryptol import argo_client.connection as argo import cryptol.cryptoltypes +from cryptol.single_connection import * from cryptol import solver from cryptol.bitvector import BV from BitVector import * #type: ignore class CryptolTests(unittest.TestCase): - # Connection to cryptol - c = None @classmethod def setUpClass(self): - self.c = cryptol.connect(verify=False) - self.c.load_file(str(Path('tests','cryptol','test-files', 'Foo.cry'))) - - @classmethod - def tearDownClass(self): - if self.c: - self.c.reset() + connect(verify=False) + load_file(str(Path('tests','cryptol','test-files', 'Foo.cry'))) def test_low_level(self): - c = self.c - x_val = c.evaluate_expression("x").result() + x_val = cry_eval("x") - self.assertEqual(c.eval("Id::id x").result(), x_val) - self.assertEqual(c.call('Id::id', bytes.fromhex('ff')).result(), BV(8,255)) + self.assertEqual(cry_eval("Id::id x"), x_val) + self.assertEqual(call('Id::id', bytes.fromhex('ff')), BV(8,255)) - self.assertEqual(c.call('add', b'\0', b'\1').result(), BV(8,1)) - self.assertEqual(c.call('add', bytes.fromhex('ff'), bytes.fromhex('03')).result(), BV(8,2)) + self.assertEqual(call('add', b'\0', b'\1'), BV(8,1)) + self.assertEqual(call('add', bytes.fromhex('ff'), bytes.fromhex('03')), BV(8,2)) # AMK: importing cryptol bindings into Python temporarily broken due to linear state usage changes # in argo approx 1 March 2020 # def test_module_import(self): - # c = self.c + # c = cryptol.connect() # cryptol.add_cryptol_module('Foo', c) # from Foo import add # self.assertEqual(add(b'\2', 2), BV(8,4)) @@ -55,123 +48,131 @@ class CryptolTests(unittest.TestCase): # self.assertEqual(add(BV(8,255), BV(8,1)), BV(8,0)) def test_sat_and_prove(self): - c = self.c # test a single sat model can be returned - rootsOf9 = c.sat('isSqrtOf9').result() - self.assertEqual(len(rootsOf9), 1) - self.assertTrue(int(rootsOf9[0]) ** 2 % 256, 9) + rootsOf9 = sat('isSqrtOf9') + self.assertTrue(rootsOf9) + self.assertEqual(len(rootsOf9.models), 1) + self.assertEqual(len(rootsOf9.models[0]), 1) + self.assertTrue(int(rootsOf9.models[0][0]) ** 2 % 256, 9) # check we can specify the solver - rootsOf9 = c.sat('isSqrtOf9', solver = solver.ANY).result() - self.assertEqual(len(rootsOf9), 1) - self.assertTrue(int(rootsOf9[0]) ** 2 % 256, 9) + rootsOf9 = sat('isSqrtOf9', solver = solver.ANY) + self.assertTrue(rootsOf9) + self.assertEqual(len(rootsOf9.models), 1) + self.assertEqual(len(rootsOf9.models[0]), 1) + self.assertTrue(int(rootsOf9.models[0][0]) ** 2 % 256, 9) # check we can ask for a specific number of results - rootsOf9 = c.sat('isSqrtOf9', count = 3).result() - self.assertEqual(len(rootsOf9), 3) - self.assertEqual([int(root) ** 2 % 256 for root in rootsOf9], [9,9,9]) + rootsOf9 = sat('isSqrtOf9', count = 3) + self.assertTrue(rootsOf9) + self.assertEqual(len(rootsOf9.models), 3) + for model in rootsOf9.models: + self.assertEqual(len(model), 1) + self.assertTrue(int(model[0]) ** 2 % 256, 9) # check we can ask for all results - rootsOf9 = c.sat('isSqrtOf9', count = None).result() - self.assertEqual(len(rootsOf9), 4) - self.assertEqual([int(root) ** 2 % 256 for root in rootsOf9], [9,9,9,9]) + rootsOf9 = sat('isSqrtOf9', count = None) + self.assertTrue(rootsOf9) + self.assertEqual(len(rootsOf9.models), 4) + for model in rootsOf9.models: + self.assertEqual(len(model), 1) + self.assertTrue(int(model[0]) ** 2 % 256, 9) # check for an unsat condition - self.assertFalse(c.sat('\\x -> isSqrtOf9 x && ~(elem x [3,131,125,253])').result()) + self.assertFalse(sat('\\x -> isSqrtOf9 x && ~(elem x [3,131,125,253])')) # check for a valid condition - self.assertTrue(c.prove('\\x -> isSqrtOf9 x ==> elem x [3,131,125,253]').result()) - self.assertTrue(c.prove('\\x -> isSqrtOf9 x ==> elem x [3,131,125,253]', solver.Z3).result()) - self.assertTrue(c.prove('\\x -> isSqrtOf9 x ==> elem x [3,131,125,253]', solver.W4_Z3).result()) - self.assertTrue(c.prove('\\x -> isSqrtOf9 x ==> elem x [3,131,125,253]', solver.W4_Z3.without_hash_consing()).result()) - self.assertTrue(c.prove('\\x -> isSqrtOf9 x ==> elem x [3,131,125,253]', solver.SBV_Z3).result()) - self.assertIsInstance(c.prove('\\(x : [8]) -> x == reverse (reverse x)', solver.OFFLINE).result(), solver.OfflineSmtQuery) - self.assertIsInstance(c.prove('\\(x : [8]) -> x == reverse (reverse x)', solver.SBV_OFFLINE).result(), solver.OfflineSmtQuery) - self.assertIsInstance(c.prove('\\(x : [8]) -> x == reverse (reverse x)', solver.W4_OFFLINE).result(), solver.OfflineSmtQuery) + self.assertTrue(prove('\\x -> isSqrtOf9 x ==> elem x [3,131,125,253]')) + self.assertTrue(prove('\\x -> isSqrtOf9 x ==> elem x [3,131,125,253]', solver.Z3)) + self.assertTrue(prove('\\x -> isSqrtOf9 x ==> elem x [3,131,125,253]', solver.W4_Z3)) + self.assertTrue(prove('\\x -> isSqrtOf9 x ==> elem x [3,131,125,253]', solver.W4_Z3.without_hash_consing())) + self.assertTrue(prove('\\x -> isSqrtOf9 x ==> elem x [3,131,125,253]', solver.SBV_Z3)) + self.assertIsInstance(prove('\\(x : [8]) -> x == reverse (reverse x)', solver.OFFLINE), solver.OfflineSmtQuery) + self.assertIsInstance(prove('\\(x : [8]) -> x == reverse (reverse x)', solver.SBV_OFFLINE), solver.OfflineSmtQuery) + self.assertIsInstance(prove('\\(x : [8]) -> x == reverse (reverse x)', solver.W4_OFFLINE), solver.OfflineSmtQuery) + def test_check(self): - c = self.c - res = c.check("\\x -> x==(x:[8])").result() + res = check("\\x -> x==(x:[8])") self.assertTrue(res.success) self.assertEqual(res.tests_run, 100) self.assertEqual(res.tests_possible, 256) self.assertFalse(len(res.args), 0) self.assertEqual(res.error_msg, None) - res = c.check("\\x -> x==(x:[8])", num_tests=1).result() + res = check("\\x -> x==(x:[8])", num_tests=1) self.assertTrue(res.success) self.assertEqual(res.tests_run, 1) self.assertEqual(res.tests_possible, 256) self.assertEqual(len(res.args), 0) self.assertEqual(res.error_msg, None) - res = c.check("\\x -> x==(x:[8])", num_tests=42).result() + res = check("\\x -> x==(x:[8])", num_tests=42) self.assertTrue(res.success) self.assertEqual(res.tests_run, 42) self.assertEqual(res.tests_possible, 256) self.assertEqual(len(res.args), 0) self.assertEqual(res.error_msg, None) - res = c.check("\\x -> x==(x:[8])", num_tests=1000).result() + res = check("\\x -> x==(x:[8])", num_tests=1000) self.assertTrue(res.success) self.assertEqual(res.tests_run, 256) self.assertEqual(res.tests_possible, 256) self.assertEqual(len(res.args), 0) self.assertEqual(res.error_msg, None) - res = c.check("\\x -> x==(x:[8])", num_tests='all').result() + res = check("\\x -> x==(x:[8])", num_tests='all') self.assertTrue(res.success) self.assertEqual(res.tests_run, 256) self.assertEqual(res.tests_possible, 256) self.assertEqual(len(res.args), 0) self.assertEqual(res.error_msg, None) - res = c.check("\\x -> x==(x:Integer)", num_tests=1024).result() + res = check("\\x -> x==(x:Integer)", num_tests=1024) self.assertTrue(res.success) self.assertEqual(res.tests_run, 1024) self.assertEqual(res.tests_possible, None) self.assertEqual(len(res.args), 0) self.assertEqual(res.error_msg, None) - res = c.check("\\x -> (x + 1)==(x:[8])").result() + res = check("\\x -> (x + 1)==(x:[8])") self.assertFalse(res.success) self.assertEqual(res.tests_possible, 256) self.assertEqual(len(res.args), 1) self.assertEqual(res.error_msg, None) - res = c.check("\\x -> (x / 0)==(x:[8])").result() + res = check("\\x -> (x / 0)==(x:[8])") self.assertFalse(res.success) self.assertEqual(res.tests_possible, 256) self.assertEqual(len(res.args), 1) self.assertIsInstance(res.error_msg, str) def test_safe(self): - c = self.c - res = c.safe("\\x -> x==(x:[8])").result() + res = safe("\\x -> x==(x:[8])") self.assertTrue(res) - res = c.safe("\\x -> x / (x:[8])").result() - self.assertEqual(res, [BV(size=8, value=0)]) + res = safe("\\x -> x / (x:[8])") + self.assertFalse(res) + self.assertEqual(res.assignments, [BV(size=8, value=0)]) - res = c.safe("\\x -> x / (x:[8])", solver.Z3).result() - self.assertEqual(res, [BV(size=8, value=0)]) + res = safe("\\x -> x / (x:[8])", solver.Z3) + self.assertFalse(res) + self.assertEqual(res.assignments, [BV(size=8, value=0)]) - res = c.safe("\\x -> x / (x:[8])", solver.W4_Z3).result() - self.assertEqual(res, [BV(size=8, value=0)]) + res = safe("\\x -> x / (x:[8])", solver.W4_Z3) + self.assertFalse(res) + self.assertEqual(res.assignments, [BV(size=8, value=0)]) def test_many_usages_one_connection(self): - c = self.c for i in range(0,100): - x_val1 = c.evaluate_expression("x").result() - x_val2 = c.eval("Id::id x").result() + x_val1 = cry_eval("x") + x_val2 = cry_eval("Id::id x") self.assertEqual(x_val1, x_val2) class HttpMultiConnectionTests(unittest.TestCase): - # Connection to server - c = None # Python initiated process running the server (if any) p = None # url of HTTP server @@ -216,26 +217,24 @@ class HttpMultiConnectionTests(unittest.TestCase): def test_reset_with_many_usages_many_connections(self): for i in range(0,100): time.sleep(.05) - c = cryptol.connect(url=self.url, verify=False) - c.load_file(str(Path('tests','cryptol','test-files', 'Foo.cry'))) - x_val1 = c.evaluate_expression("x").result() - x_val2 = c.eval("Id::id x").result() + connect(url=self.url, verify=False) + load_file(str(Path('tests','cryptol','test-files', 'Foo.cry'))) + x_val1 = cry_eval("x") + x_val2 = cry_eval("Id::id x") self.assertEqual(x_val1, x_val2) - c.reset() + reset() - def test_reset_server_with_many_usages_many_connections(self): + def test_server_with_many_usages_many_connections(self): for i in range(0,100): time.sleep(.05) - c = cryptol.connect(url=self.url, reset_server=True, verify=False) - c.load_file(str(Path('tests','cryptol','test-files', 'Foo.cry'))) - x_val1 = c.evaluate_expression("x").result() - x_val2 = c.eval("Id::id x").result() + connect(url=self.url, verify=False) + load_file(str(Path('tests','cryptol','test-files', 'Foo.cry'))) + x_val1 = cry_eval("x") + x_val2 = cry_eval("Id::id x") self.assertEqual(x_val1, x_val2) class TLSConnectionTests(unittest.TestCase): - # Connection to server - c = None # Python initiated process running the server (if any) p = None # url of HTTP server @@ -281,10 +280,10 @@ class TLSConnectionTests(unittest.TestCase): def test_tls_connection(self): if self.run_tests: - c = cryptol.connect(url=self.url, verify=False) - c.load_file(str(Path('tests','cryptol','test-files', 'Foo.cry'))) - x_val1 = c.evaluate_expression("x").result() - x_val2 = c.eval("Id::id x").result() + connect(url=self.url, verify=False) + load_file(str(Path('tests','cryptol','test-files', 'Foo.cry'))) + x_val1 = cry_eval("x") + x_val2 = cry_eval("Id::id x") self.assertEqual(x_val1, x_val2) if __name__ == "__main__": diff --git a/cryptol-remote-api/python/tests/cryptol/test_error_recovery.py b/cryptol-remote-api/python/tests/cryptol/test_error_recovery.py new file mode 100644 index 00000000..a4894250 --- /dev/null +++ b/cryptol-remote-api/python/tests/cryptol/test_error_recovery.py @@ -0,0 +1,32 @@ +import unittest +from pathlib import Path +import unittest +import cryptol +from cryptol.single_connection import * +from argo_client.interaction import ArgoException +from cryptol.bitvector import BV + + +class TestErrorRecovery(unittest.TestCase): + def test_ErrorRecovery(self): + connect(verify=False) + + with self.assertRaises(ArgoException): + load_file(str(Path('tests','cryptol','test-files','bad.cry'))) + + # test that loading a valid file still works after an exception + load_file(str(Path('tests','cryptol','test-files','Foo.cry'))) + + # ensure that we really did load the file with no errors + x_val1 = cry_eval("x") + x_val2 = cry_eval("Id::id x") + self.assertEqual(x_val1, x_val2) + + # test that a reset still works after an exception (this used to throw + # an error before the server even had a chance to respond because of + # the `connection.protocol_state()` call in `CryptolReset`) + reset() + + +if __name__ == "__main__": + unittest.main() diff --git a/cryptol-remote-api/python/tests/cryptol/test_quoting.py b/cryptol-remote-api/python/tests/cryptol/test_quoting.py new file mode 100644 index 00000000..64508c1a --- /dev/null +++ b/cryptol-remote-api/python/tests/cryptol/test_quoting.py @@ -0,0 +1,48 @@ +import unittest +from pathlib import Path +import unittest +import cryptol +from cryptol.single_connection import * +from cryptol.bitvector import BV +from cryptol.quoting import * + +class TestQuoting(unittest.TestCase): + def test_quoting(self): + connect(verify=False) + load_file(str(Path('tests','cryptol','test-files', 'M.cry'))) + + x = BV(size=8, value=1) + y = cry_f('g {x}') + z = cry_f('h {y}') + self.assertEqual(z, cry('h (g 0x01)')) + self.assertEqual(cry_eval(z), [x,x]) + + y = cry_eval_f('g {x}') + z = cry_eval_f('h {y}') + self.assertEqual(y, [x,x]) + self.assertEqual(z, [x,x]) + + self.assertEqual(cry_f('id {BV(size=7, value=1)}'), cry('id (1 : [7])')) + self.assertEqual(cry_eval_f('id {BV(size=7, value=1)}'), BV(size=7, value=1)) + + self.assertEqual(cry_f('{ {"a": x, "b": x} }'), cry('{a = 0x01, b = 0x01}')) + self.assertEqual(cry_f('{{a = {x}, b = {x}}}'), cry('{a = 0x01, b = 0x01}')) + + self.assertEqual(cry_f('id {5}'), cry('id 5')) + self.assertEqual(cry_f('id {5!s}'), cry('id "5"')) + self.assertEqual(cry_f('id {5:#x}'), cry('id "0x5"')) + self.assertEqual(cry_f('id {BV(4,5)}'), cry('id 0x5')) + + # Only here to check backwards compatability, the above syntax is preferred + y = cry('g')(cry_f('{x}')) + z = cry('h')(cry_f('{y}')) + self.assertEqual(str(z), str(cry('(h) ((g) (0x01))'))) + self.assertEqual(cry_eval(z), [x,x]) + self.assertEqual(str(cry('id')(cry_f('{BV(size=7, value=1)}'))), str(cry('(id) (1 : [7])'))) + # This is why this syntax is not preferred + with self.assertRaises(ValueError): + cry('g')(x) # x is not CryptolJSON + + +if __name__ == "__main__": + unittest.main() diff --git a/cryptol-remote-api/python/tests/cryptol/test_smt.py b/cryptol-remote-api/python/tests/cryptol/test_smt.py new file mode 100644 index 00000000..5cb9a6f3 --- /dev/null +++ b/cryptol-remote-api/python/tests/cryptol/test_smt.py @@ -0,0 +1,86 @@ +import unittest +from pathlib import Path +import unittest +import cryptol +import cryptol.solver as solver +from cryptol.single_connection import * +from cryptol.bitvector import BV + + +class TestSMT(unittest.TestCase): + def test_SMT(self): + connect(verify=False) + load_module('Cryptol') + + ex_true = '\(x : [8]) -> x+x == x+x' + ex_true_safe = safe(ex_true) + self.assertTrue(ex_true_safe) + self.assertIsInstance(ex_true_safe, cryptol.Safe) + ex_true_prove = prove(ex_true) + self.assertTrue(ex_true_prove) + self.assertIsInstance(ex_true_prove, cryptol.Qed) + ex_true_sat = sat(ex_true) + self.assertTrue(ex_true_sat) + self.assertIsInstance(ex_true_sat, cryptol.Satisfiable) + + ex_false = '\(x : [8]) -> x+2*x+1 == x' + ex_false_safe = safe(ex_false) + self.assertTrue(ex_false_safe) + self.assertIsInstance(ex_false_safe, cryptol.Safe) + ex_false_prove = prove(ex_false) + self.assertFalse(ex_false_prove) + self.assertIsInstance(ex_false_prove, cryptol.Counterexample) + self.assertEqual(ex_false_prove.type, "predicate falsified") + ex_false_sat = sat(ex_false) + self.assertFalse(ex_false_sat) + self.assertIsInstance(ex_false_sat, cryptol.Unsatisfiable) + + ex_partial = '\(x : [8]) -> if x < 0x0f then x == x else error "!"' + ex_partial_safe = safe(ex_partial) + self.assertFalse(ex_partial_safe) + self.assertIsInstance(ex_partial_safe, cryptol.Counterexample) + self.assertEqual(ex_partial_safe.type, "safety violation") + ex_partial_prove = prove(ex_partial) + self.assertFalse(ex_partial_prove) + self.assertIsInstance(ex_partial_prove, cryptol.Counterexample) + self.assertEqual(ex_partial_prove.type, "safety violation") + ex_partial_sat = sat(ex_partial) + self.assertTrue(ex_partial_sat) + self.assertIsInstance(ex_partial_sat, cryptol.Satisfiable) + + def test_each_online_solver(self): + # We test each solver that is packaged for use with what4 + # via https://github.com/GaloisInc/what4-solvers - the others + # are commented out for now. + ex_true = '\(x : [128]) -> negate (complement x + 1) == complement (negate x) + 1' + solvers = \ + [solver.CVC4, + solver.YICES, + solver.Z3, + #solver.BOOLECTOR, + #solver.MATHSAT, + solver.ABC, + #solver.OFFLINE, + solver.ANY, + solver.SBV_CVC4, + solver.SBV_YICES, + solver.SBV_Z3, + #solver.SBV_BOOLECTOR, + #solver.SBV_MATHSAT, + solver.SBV_ABC, + #solver.SBV_OFFLINE, + solver.SBV_ANY, + solver.W4_CVC4, + solver.W4_YICES, + solver.W4_Z3, + #solver.W4_BOOLECTOR, + #solver.W4_OFFLINE, + solver.W4_ABC, + solver.W4_ANY] + + for s in solvers: + self.assertTrue(prove(ex_true, s)) + + +if __name__ == "__main__": + unittest.main() diff --git a/cryptol-remote-api/python/tests/cryptol/test_types.py b/cryptol-remote-api/python/tests/cryptol/test_types.py new file mode 100644 index 00000000..1fd2327a --- /dev/null +++ b/cryptol-remote-api/python/tests/cryptol/test_types.py @@ -0,0 +1,74 @@ +import unittest +from argo_client.interaction import ArgoException +from pathlib import Path +import unittest +import cryptol +from cryptol.single_connection import * +from cryptol.opaque import OpaqueValue +from cryptol.bitvector import BV +from cryptol import cryptoltypes + + +class CryptolTypeTests(unittest.TestCase): + def test_types(self): + connect(verify=False) + load_file(str(Path('tests','cryptol','test-files','Types.cry'))) + + # Bits + self.assertEqual(cry_eval('b'), True) + self.assertEqual(check_type('b'), cryptoltypes.Bit()) + + # Words + self.assertEqual(cry_eval('w'), BV(size=16, value=42)) + self.assertEqual(check_type('w'), cryptoltypes.Bitvector(cryptoltypes.Num(16))) + + # Integers + self.assertEqual(cry_eval('z'), 420000) + self.assertEqual(check_type('z'), cryptoltypes.Integer()) + + # Modular integers - not supported as values + with self.assertRaises(ValueError): + cry_eval('m') + self.assertEqual(check_type('m'), cryptoltypes.Z(cryptoltypes.Num(12))) + + # Rationals - supported only as opaque values + self.assertIsInstance(cry_eval('q'), OpaqueValue) + self.assertEqual(check_type('q'), cryptoltypes.Rational()) + + # Tuples + self.assertEqual(cry_eval('t'), (False, 7)) + t_ty = cryptoltypes.Tuple(cryptoltypes.Bit(), cryptoltypes.Integer()) + self.assertEqual(check_type('t'), t_ty) + + # Sequences + self.assertEqual(cry_eval('s'), + [[BV(size=8, value=1), BV(size=8, value=2), BV(size=8, value=3)], + [BV(size=8, value=4), BV(size=8, value=5), BV(size=8, value=6)], + [BV(size=8, value=7), BV(size=8, value=8), BV(size=8, value=9)]]) + s_ty = cryptoltypes.Sequence(cryptoltypes.Num(3), + cryptoltypes.Sequence(cryptoltypes.Num(3), + cryptoltypes.Bitvector(cryptoltypes.Num(8)))) + self.assertEqual(check_type('s'), s_ty) + + # Records + self.assertEqual(cry_eval('r'), + {'xCoord': BV(size=32, value=12), + 'yCoord': BV(size=32, value=21)}) + r_ty = cryptoltypes.Record({ + 'xCoord': cryptoltypes.Bitvector(cryptoltypes.Num(32)), + 'yCoord': cryptoltypes.Bitvector(cryptoltypes.Num(32))}) + self.assertEqual(check_type('r'), r_ty) + + # Functions - not supported as values + with self.assertRaises(ArgoException): + cry_eval('id') + n = cryptoltypes.Var('n', 'Num') + id_ty = cryptoltypes.CryptolTypeSchema( + {n.name: n.kind}, [cryptoltypes.PropCon('fin', n)], + cryptoltypes.Function(cryptoltypes.Bitvector(n), + cryptoltypes.Bitvector(n))) + self.assertEqual(check_type('id'), id_ty) + + +if __name__ == "__main__": + unittest.main() diff --git a/cryptol-remote-api/python/tests/cryptol_eval/test_basics.py b/cryptol-remote-api/python/tests/cryptol_eval/test_basics.py index 731a6f56..ffaac247 100644 --- a/cryptol-remote-api/python/tests/cryptol_eval/test_basics.py +++ b/cryptol-remote-api/python/tests/cryptol_eval/test_basics.py @@ -102,10 +102,10 @@ class HttpMultiConnectionTests(unittest.TestCase): self.assertEqual(res, [BV(size=8,value=0xff), BV(size=8,value=0xff)]) c.reset() - def test_reset_server_with_many_usages_many_connections(self): + def test_server_with_many_usages_many_connections(self): for i in range(0,100): time.sleep(.05) - c = cryptol.connect(url=self.url, reset_server=True) + c = cryptol.connect(url=self.url) res = c.call('f', BV(size=8,value=0xff)).result() self.assertEqual(res, [BV(size=8,value=0xff), BV(size=8,value=0xff)]) diff --git a/cryptol-remote-api/run_rpc_tests.sh b/cryptol-remote-api/run_rpc_tests.sh index df46cbbf..b53be4ff 100755 --- a/cryptol-remote-api/run_rpc_tests.sh +++ b/cryptol-remote-api/run_rpc_tests.sh @@ -23,6 +23,7 @@ get_server() { } echo "Setting up python environment for remote server clients..." +poetry update poetry install echo "Typechecking code with mypy..." @@ -30,10 +31,10 @@ run_test poetry run mypy cryptol/ tests/ get_server cryptol-remote-api echo "Running cryptol-remote-api tests..." -run_test poetry run python -m unittest discover tests/cryptol +run_test poetry run python -m unittest discover --verbose tests/cryptol get_server cryptol-eval-server echo "Running cryptol-eval-server tests..." -run_test poetry run python -m unittest discover tests/cryptol_eval +run_test poetry run python -m unittest discover --verbose tests/cryptol_eval popd diff --git a/cryptol-remote-api/src/CryptolServer.hs b/cryptol-remote-api/src/CryptolServer.hs index f1731937..ab7406ea 100644 --- a/cryptol-remote-api/src/CryptolServer.hs +++ b/cryptol-remote-api/src/CryptolServer.hs @@ -85,6 +85,9 @@ modifyModuleEnv f = getTCSolver :: CryptolCommand SMT.Solver getTCSolver = CryptolCommand $ const $ view tcSolver <$> Argo.getState +getTCSolverConfig :: CryptolCommand SMT.SolverConfig +getTCSolverConfig = CryptolCommand $ const $ solverConfig <$> Argo.getState + liftModuleCmd :: ModuleCmd a -> CryptolCommand a liftModuleCmd cmd = do Options callStacks evOpts <- getOptions @@ -123,6 +126,7 @@ data ServerState = ServerState { _loadedModule :: Maybe LoadedModule , _moduleEnv :: ModuleEnv , _tcSolver :: SMT.Solver + , solverConfig :: SMT.SolverConfig } loadedModule :: Lens' ServerState (Maybe LoadedModule) @@ -138,14 +142,24 @@ tcSolver = lens _tcSolver (\v n -> v { _tcSolver = n }) initialState :: IO ServerState initialState = do modEnv <- initialModuleEnv - s <- SMT.startSolver (defaultSolverConfig (meSearchPath modEnv)) - pure (ServerState Nothing modEnv s) + -- NOTE: the "pure ()" is a callback which is invoked if/when the solver + -- stops for some reason. This is just a placeholder for now, and could + -- be replaced by something more useful. + let sCfg = defaultSolverConfig (meSearchPath modEnv) + s <- SMT.startSolver (pure ()) sCfg + pure (ServerState Nothing modEnv s sCfg) extendSearchPath :: [FilePath] -> ServerState -> ServerState extendSearchPath paths = over moduleEnv $ \me -> me { meSearchPath = nubOrd $ paths ++ meSearchPath me } +resetTCSolver :: CryptolCommand () +resetTCSolver = do + s <- getTCSolver + sCfg <- getTCSolverConfig + liftIO $ SMT.resetSolver s sCfg + instance FreshM CryptolCommand where liftSupply f = do serverState <- CryptolCommand $ const Argo.getState diff --git a/cryptol-remote-api/src/CryptolServer/AesonCompat.hs b/cryptol-remote-api/src/CryptolServer/AesonCompat.hs new file mode 100644 index 00000000..d0e9d2f4 --- /dev/null +++ b/cryptol-remote-api/src/CryptolServer/AesonCompat.hs @@ -0,0 +1,68 @@ +{-# LANGUAGE CPP #-} + +-- | A compatibility shim for papering over the differences between +-- @aeson-2.0.*@ and pre-2.0.* versions of @aeson@. +-- +-- TODO: When the ecosystem widely uses @aeson-2.0.0.0@ or later, remove this +-- module entirely. +module CryptolServer.AesonCompat where + +import Data.HashMap.Strict (HashMap) +import Data.Text (Text) + +#if MIN_VERSION_aeson(2,0,0) +import Data.Aeson.Key (Key) +import qualified Data.Aeson.Key as K +import Data.Aeson.KeyMap (KeyMap) +import qualified Data.Aeson.KeyMap as KM +#else +import qualified Data.HashMap.Strict as HM +#endif + +#if MIN_VERSION_aeson(2,0,0) +type KeyCompat = Key + +deleteKM :: Key -> KeyMap v -> KeyMap v +deleteKM = KM.delete + +fromListKM :: [(Key, v)] -> KeyMap v +fromListKM = KM.fromList + +keyFromText :: Text -> Key +keyFromText = K.fromText + +keyToText :: Key -> Text +keyToText = K.toText + +lookupKM :: Key -> KeyMap v -> Maybe v +lookupKM = KM.lookup + +toHashMapTextKM :: KeyMap v -> HashMap Text v +toHashMapTextKM = KM.toHashMapText + +toListKM :: KeyMap v -> [(Key, v)] +toListKM = KM.toList +#else +type KeyCompat = Text + +deleteKM :: Text -> HashMap Text v -> HashMap Text v +deleteKM = HM.delete + +fromListKM :: [(Text, v)] -> HashMap Text v +fromListKM = HM.fromList + +keyFromText :: Text -> Text +keyFromText = id + +keyToText :: Text -> Text +keyToText = id + +lookupKM :: Text -> HashMap Text v -> Maybe v +lookupKM = HM.lookup + +toHashMapTextKM :: HashMap Text v -> HashMap Text v +toHashMapTextKM = id + +toListKM :: HashMap Text v -> [(Text, v)] +toListKM = HM.toList +#endif diff --git a/cryptol-remote-api/src/CryptolServer/Check.hs b/cryptol-remote-api/src/CryptolServer/Check.hs index 497399f5..40ccc963 100644 --- a/cryptol-remote-api/src/CryptolServer/Check.hs +++ b/cryptol-remote-api/src/CryptolServer/Check.hs @@ -39,6 +39,7 @@ import CryptolServer liftModuleCmd, CryptolMethod(raise), CryptolCommand ) +import CryptolServer.AesonCompat (KeyCompat) import CryptolServer.Exceptions (evalPolyErr) import CryptolServer.Data.Expression ( readBack, getExpr, Expression) @@ -118,7 +119,7 @@ data CheckResult = , checkTestsPossible :: Maybe Integer } -convertServerTestResult :: ServerTestResult -> [(Text, JSON.Value)] +convertServerTestResult :: ServerTestResult -> [(KeyCompat, JSON.Value)] convertServerTestResult Pass = ["result" .= ("pass" :: Text)] convertServerTestResult (FailFalse args) = [ "result" .= ("fail" :: Text) diff --git a/cryptol-remote-api/src/CryptolServer/Data/Expression.hs b/cryptol-remote-api/src/CryptolServer/Data/Expression.hs index f8e46596..b6d4ee26 100644 --- a/cryptol-remote-api/src/CryptolServer/Data/Expression.hs +++ b/cryptol-remote-api/src/CryptolServer/Data/Expression.hs @@ -60,6 +60,7 @@ import Cryptol.Utils.RecordMap (recordFromFields, canonicalFields) import Argo import qualified Argo.Doc as Doc import CryptolServer +import CryptolServer.AesonCompat import CryptolServer.Exceptions import CryptolServer.Data.Type @@ -160,9 +161,9 @@ instance JSON.FromJSON TypeArguments where parseJSON = withObject "type arguments" $ \o -> TypeArguments . Map.fromList <$> - traverse elt (HM.toList o) + traverse elt (toListKM o) where - elt (name, ty) = (mkIdent name,) <$> parseJSON ty + elt (name, ty) = (mkIdent (keyToText name),) <$> parseJSON ty instance JSON.FromJSON Expression where parseJSON v = bool v <|> integer v <|> concrete v <|> obj v @@ -192,7 +193,7 @@ instance JSON.FromJSON Expression where TagRecord -> do fields <- o .: "data" flip (withObject "record data") fields $ - \fs -> Record <$> traverse parseJSON fs + \fs -> (Record . toHashMapTextKM) <$> traverse parseJSON fs TagSequence -> do contents <- o .: "data" flip (withArray "sequence") contents $ @@ -234,7 +235,7 @@ instance JSON.ToJSON Expression where ] toJSON (Record fields) = object [ "expression" .= TagRecord - , "data" .= object [ fieldName .= toJSON val + , "data" .= object [ keyFromText fieldName .= toJSON val | (fieldName, val) <- HM.toList fields ] ] diff --git a/cryptol-remote-api/src/CryptolServer/Data/Type.hs b/cryptol-remote-api/src/CryptolServer/Data/Type.hs index 07ca9d52..f830c2da 100644 --- a/cryptol-remote-api/src/CryptolServer/Data/Type.hs +++ b/cryptol-remote-api/src/CryptolServer/Data/Type.hs @@ -13,7 +13,6 @@ import qualified Data.Aeson as JSON import Data.Aeson ((.=), (.:), (.!=), (.:?)) import Data.Aeson.Types (Parser, typeMismatch) import Data.Functor ((<&>)) -import qualified Data.HashMap.Strict as HM import qualified Data.Text as T import qualified Cryptol.Parser.AST as C @@ -27,6 +26,7 @@ import Cryptol.Utils.PP (pp) import Cryptol.Utils.RecordMap (canonicalFields) import qualified Argo.Doc as Doc +import CryptolServer.AesonCompat newtype JSONSchema = JSONSchema Schema @@ -219,7 +219,7 @@ instance JSON.ToJSON JSONType where JSON.object [ "type" .= T.pack "record" , "fields" .= - JSON.object [ T.pack (show (pp f)) .= JSONType ns t' + JSON.object [ keyFromText (T.pack (show (pp f))) .= JSONType ns t' | (f, t') <- canonicalFields fields ] ] @@ -231,17 +231,17 @@ instance JSON.FromJSON JSONPType where where getType :: JSON.Value -> Parser (C.Type C.PName) getType (JSON.Object o) = - case HM.lookup "type" o of + case lookupKM "type" o of Just t -> asType t o Nothing -> - case HM.lookup "prop" o of + case lookupKM "prop" o of Just p -> asProp p o Nothing -> fail "Expected type or prop key" getType other = typeMismatch "object" other asType "record" = \o -> C.TRecord <$> ((o .: "fields") >>= getFields) where - getFields obj = recordFromFields <$> traverse (\(k, v) -> (mkIdent k,) . (emptyRange,) <$> getType v) (HM.toList obj) + getFields obj = recordFromFields <$> traverse (\(k, v) -> (mkIdent (keyToText k),) . (emptyRange,) <$> getType v) (toListKM obj) asType "variable" = \o -> C.TUser <$> (name <$> o .: "name") <*> (map unJSONPType <$> (o .:? "arguments" .!= [])) asType "number" = \o -> C.TNum <$> (o .: "value") asType "inf" = const $ pure $ C.TUser (name "inf") [] diff --git a/cryptol-remote-api/src/CryptolServer/Exceptions.hs b/cryptol-remote-api/src/CryptolServer/Exceptions.hs index 8b46bbf1..ad1374ea 100644 --- a/cryptol-remote-api/src/CryptolServer/Exceptions.hs +++ b/cryptol-remote-api/src/CryptolServer/Exceptions.hs @@ -25,12 +25,12 @@ import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as B8 import Data.Text (Text) import qualified Data.Text as T -import qualified Data.HashMap.Strict as HashMap import Cryptol.Parser import qualified Cryptol.TypeCheck.Type as TC import Argo +import CryptolServer.AesonCompat import CryptolServer.Data.Type cryptolError :: ModuleError -> [ModuleWarning] -> JSONRPCException @@ -167,7 +167,7 @@ unwantedDefaults defs = makeJSONRPCException 20210 "Execution would have required these defaults" (Just (JSON.object ["defaults" .= - [ jsonTypeAndString ty <> HashMap.fromList ["parameter" .= pretty param] + [ jsonTypeAndString ty <> fromListKM ["parameter" .= pretty param] | (param, ty) <- defs ] ])) evalInParamMod :: [CM.Name] -> JSONRPCException @@ -204,6 +204,6 @@ cryptolParseErr expr err = -- human-readable string jsonTypeAndString :: TC.Type -> JSON.Object jsonTypeAndString ty = - HashMap.fromList + fromListKM [ "type" .= JSONSchema (TC.Forall [] [] ty) , "type string" .= pretty ty ] diff --git a/cryptol-remote-api/src/CryptolServer/Interrupt.hs b/cryptol-remote-api/src/CryptolServer/Interrupt.hs new file mode 100644 index 00000000..26eea163 --- /dev/null +++ b/cryptol-remote-api/src/CryptolServer/Interrupt.hs @@ -0,0 +1,33 @@ +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE OverloadedStrings #-} +module CryptolServer.Interrupt + ( interruptServer + , interruptServerDescr + ) where + +import qualified Argo +import qualified Argo.Doc as Doc +import qualified Data.Aeson as JSON + +import CryptolServer + + + +------------------------------------------------------------------------ +-- Interrupt All Threads Command +data InterruptServerParams = InterruptServerParams + +instance JSON.FromJSON InterruptServerParams where + parseJSON = + JSON.withObject "params for \"interrupt\"" $ + \_ -> pure InterruptServerParams + +instance Doc.DescribedMethod InterruptServerParams () where + parameterFieldDescription = [] + +interruptServerDescr :: Doc.Block +interruptServerDescr = + Doc.Paragraph [Doc.Text "Interrupt the server, terminating it's current task (if one exists)."] + +interruptServer :: InterruptServerParams -> CryptolNotification () +interruptServer _ = CryptolNotification . const $ Argo.interruptAllThreads diff --git a/cryptol-remote-api/src/CryptolServer/LoadModule.hs b/cryptol-remote-api/src/CryptolServer/LoadModule.hs index 4f29aa00..63294f6d 100644 --- a/cryptol-remote-api/src/CryptolServer/LoadModule.hs +++ b/cryptol-remote-api/src/CryptolServer/LoadModule.hs @@ -25,7 +25,8 @@ loadFileDescr :: Doc.Block loadFileDescr = Doc.Paragraph [Doc.Text "Load the specified module (by file path)."] loadFile :: LoadFileParams -> CryptolCommand () -loadFile (LoadFileParams fn) = +loadFile (LoadFileParams fn) = do + resetTCSolver void $ liftModuleCmd (loadModuleByPath fn) newtype LoadFileParams @@ -49,7 +50,8 @@ loadModuleDescr :: Doc.Block loadModuleDescr = Doc.Paragraph [Doc.Text "Load the specified module (by name)."] loadModule :: LoadModuleParams -> CryptolCommand () -loadModule (LoadModuleParams mn) = +loadModule (LoadModuleParams mn) = do + resetTCSolver void $ liftModuleCmd (loadModuleByName mn) newtype JSONModuleName diff --git a/cryptol-remote-api/src/CryptolServer/Options.hs b/cryptol-remote-api/src/CryptolServer/Options.hs index fe0310cc..ab97ca33 100644 --- a/cryptol-remote-api/src/CryptolServer/Options.hs +++ b/cryptol-remote-api/src/CryptolServer/Options.hs @@ -12,7 +12,6 @@ import qualified Argo.Doc as Doc import Data.Aeson hiding (Options) import Data.Aeson.Types (Parser, typeMismatch) import Data.Coerce -import qualified Data.HashMap.Strict as HM import qualified Data.Text as T import Cryptol.Eval(EvalOpts(..)) @@ -20,6 +19,8 @@ import Cryptol.REPL.Monad (parseFieldOrder, parsePPFloatFormat) import Cryptol.Utils.Logger (quietLogger) import Cryptol.Utils.PP (PPOpts(..), PPFloatFormat(..), PPFloatExp(..), FieldOrder(..), defaultPPOpts) +import CryptolServer.AesonCompat + data Options = Options { optCallStacks :: Bool, optEvalOpts :: EvalOpts } newtype JSONEvalOpts = JSONEvalOpts { getEvalOpts :: EvalOpts } @@ -40,7 +41,7 @@ newtypeField :: forall wrapped bare proxy. (Coercible wrapped bare, FromJSON wrapped) => proxy wrapped bare -> Object -> T.Text -> bare -> Parser bare -newtypeField _proxy o field def = unwrap (o .:! field) .!= def where +newtypeField _proxy o field def = unwrap (o .:! keyFromText field) .!= def where unwrap :: Parser (Maybe wrapped) -> Parser (Maybe bare) unwrap = coerce @@ -85,7 +86,7 @@ instance FromJSON a => FromJSON (WithOptions a) where \o -> WithOptions <$> o .:! "options" .!= defaultOpts <*> - parseJSON (Object (HM.delete "options" o)) + parseJSON (Object (deleteKM "options" o)) defaultOpts :: Options defaultOpts = Options False theEvalOpts diff --git a/cryptol-remote-api/src/CryptolServer/Sat.hs b/cryptol-remote-api/src/CryptolServer/Sat.hs index 752a0853..23ec7094 100644 --- a/cryptol-remote-api/src/CryptolServer/Sat.hs +++ b/cryptol-remote-api/src/CryptolServer/Sat.hs @@ -118,10 +118,10 @@ offlineProveSat proverName cmd hConsing = do Left msg -> do raise $ proverError $ "error setting up " ++ proverName ++ ": " ++ msg Right smtlib -> pure $ OfflineSMTQuery $ T.pack smtlib - Right w4Cfg -> do + Right _w4Cfg -> do smtlibRef <- liftIO $ newIORef ("" :: Text) result <- liftModuleCmd $ - W4.satProveOffline w4Cfg hConsing False cmd $ \f -> do + W4.satProveOffline hConsing False cmd $ \f -> do withRWTempFile "smtOutput.tmp" $ \h -> do f h hSeek h AbsoluteSeek 0 diff --git a/cryptol-remote-api/test_docker.sh b/cryptol-remote-api/test_docker.sh index a643c7b8..ad5eb12b 100755 --- a/cryptol-remote-api/test_docker.sh +++ b/cryptol-remote-api/test_docker.sh @@ -1,5 +1,7 @@ #!/bin/bash +set -euo pipefail + DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" PROTO=${1:-"http"} @@ -25,10 +27,13 @@ pushd $DIR/python NUM_FAILS=0 echo "Setting up python environment for remote server clients..." +poetry update poetry install export CRYPTOL_SERVER_URL="$PROTO://localhost:8080/" -poetry run python -m unittest discover tests/cryptol + +echo "Running cryptol-remote-api tests with remote server at $CRYPTOL_SERVER_URL..." +poetry run python -m unittest discover --verbose tests/cryptol if [ $? -ne 0 ]; then NUM_FAILS=$(($NUM_FAILS+1)) fi diff --git a/cryptol.cabal b/cryptol.cabal index b6e31f47..4f908da8 100644 --- a/cryptol.cabal +++ b/cryptol.cabal @@ -1,6 +1,6 @@ Cabal-version: 2.4 Name: cryptol -Version: 2.11.0.99 +Version: 2.12.0.99 Synopsis: Cryptol: The Language of Cryptography Description: Cryptol is a domain-specific language for specifying cryptographic algorithms. A Cryptol implementation of an algorithm resembles its mathematical specification more closely than an implementation in a general purpose language. For more, see . License: BSD-3-Clause @@ -9,7 +9,7 @@ Author: Galois, Inc. Maintainer: cryptol@galois.com Homepage: http://www.cryptol.net/ Bug-reports: https://github.com/GaloisInc/cryptol/issues -Copyright: 2013-2020 Galois Inc. +Copyright: 2013-2021 Galois Inc. Category: Language Build-type: Simple extra-source-files: bench/data/*.cry @@ -63,10 +63,10 @@ library monad-control >= 1.0, monadLib >= 3.7.2, parameterized-utils >= 2.0.2, - pretty >= 1.1, + prettyprinter >= 1.7.0, process >= 1.2, - sbv >= 8.10 && < 8.16, - simple-smt >= 0.7.1, + sbv >= 8.10 && < 8.17, + simple-smt >= 0.9.7, stm >= 2.4, strict, text >= 1.1, @@ -232,6 +232,7 @@ executable cryptol , directory , filepath , haskeline >= 0.7 && < 0.9 + , exceptions , monad-control , text , transformers diff --git a/cryptol/REPL/Haskeline.hs b/cryptol/REPL/Haskeline.hs index a7fe2ae7..0ad7b00a 100644 --- a/cryptol/REPL/Haskeline.hs +++ b/cryptol/REPL/Haskeline.hs @@ -16,7 +16,7 @@ module REPL.Haskeline where import Cryptol.REPL.Command import Cryptol.REPL.Monad import Cryptol.REPL.Trie -import Cryptol.Utils.PP +import Cryptol.Utils.PP hiding (()) import Cryptol.Utils.Logger(stdoutLogger) import Cryptol.Utils.Ident(modNameToText, interactiveName) @@ -99,7 +99,7 @@ getInputLines :: String -> InputT REPL NextLine getInputLines = handleInterrupt (MTL.lift (handleCtrlC Interrupted)) . loop [] where loop ls prompt = - do mb <- getInputLine prompt + do mb <- fmap (filter (/= '\r')) <$> getInputLine prompt let newPropmpt = map (\_ -> ' ') prompt case mb of Nothing -> return NoMoreLines diff --git a/deps/argo b/deps/argo index 2481c425..afee6bb4 160000 --- a/deps/argo +++ b/deps/argo @@ -1 +1 @@ -Subproject commit 2481c42506c46be8b6562ab9dcef99fe85a54e5f +Subproject commit afee6bb49c7831a38316221e7b9721fbc65e88d7 diff --git a/docs/.nojekyll b/docs/.nojekyll new file mode 100644 index 00000000..e69de29b diff --git a/docs/CryptolPrims.md b/docs/CryptolPrims.md index 909e1da9..049630eb 100644 --- a/docs/CryptolPrims.md +++ b/docs/CryptolPrims.md @@ -25,13 +25,20 @@ Literals number : {val, rep} Literal val rep => rep length : {n, a, b} (fin n, Literal n b) => [n]a -> b - // '[a..b]' is syntactic sugar for 'fromTo`{first=a,last=b}' + // '[x..y]' is syntactic sugar for 'fromTo`{first=x,last=y}' fromTo : {first, last, a} (fin last, last >= first, Literal first a, Literal last a) => [1 + (last - first)]a - // '[a,b..c]' is syntactic sugar for 'fromThenTo`{first=a,next=b,last=c}' + // '[x .. < y]' is syntactic sugar for + // 'fromToLessThan`{first=x,bound=y}' + fromToLessThan : {first, bound, a} + (fin first, bound >= first, LiteralLessThan bound a) => + [bound - first]a + + // '[x,y..z]' is syntactic sugar for + // 'fromThenTo`{first=x,next=y,last=z}' fromThenTo : {first, next, last, a, len} ( fin first, fin next, fin last , Literal first a, Literal next a, Literal last a @@ -39,10 +46,30 @@ Literals , lengthFromThenTo first next last == len) => [len]a - // '[a .. < b]` is syntactic sugar for 'fromToLessThan`{first=a,bound=b}' - fromToLessThan : {first, bound, a} - (fin first, bound >= first, LiteralLessThan bound a) => - [bound - first]a + // '[x .. y by n]' is syntactic sugar for + // 'fromToBy`{first=x,last=y,stride=n}'. + primitive fromToBy : {first, last, stride, a} + (fin last, fin stride, stride >= 1, last >= first, Literal last a) => + [1 + (last - first)/stride]a + + // '[x ..< y by n]' is syntactic sugar for + // 'fromToByLessThan`{first=x,bound=y,stride=n}'. + primitive fromToByLessThan : {first, bound, stride, a} + (fin first, fin stride, stride >= 1, bound >= first, LiteralLessThan bound a) => + [(bound - first)/^stride]a + + // '[x .. y down by n]' is syntactic sugar for + // 'fromToDownBy`{first=x,last=y,stride=n}'. + primitive fromToDownBy : {first, last, stride, a} + (fin first, fin stride, stride >= 1, first >= last, Literal first a) => + [1 + (first - last)/stride]a + + // '[x ..> y down by n]' is syntactic sugar for + // 'fromToDownByGreaterThan`{first=x,bound=y,stride=n}'. + primitive fromToDownByGreaterThan : {first, bound, stride, a} + (fin first, fin stride, stride >= 1, first >= bound, Literal first a) => + [(first - bound)/^stride]a + Fractional Literals ------------------- diff --git a/docs/CryptolPrims.pdf b/docs/CryptolPrims.pdf index 5b5eaa9e..a905bafd 100644 Binary files a/docs/CryptolPrims.pdf and b/docs/CryptolPrims.pdf differ diff --git a/docs/ProgrammingCryptol.pdf b/docs/ProgrammingCryptol.pdf index 001ac0fb..37e4f632 100644 Binary files a/docs/ProgrammingCryptol.pdf and b/docs/ProgrammingCryptol.pdf differ diff --git a/docs/ProgrammingCryptol/appendices/Syntax.tex b/docs/ProgrammingCryptol/appendices/Syntax.tex index 7a082013..55d65be3 100644 --- a/docs/ProgrammingCryptol/appendices/Syntax.tex +++ b/docs/ProgrammingCryptol/appendices/Syntax.tex @@ -2,7 +2,8 @@ % markdown in ../../Syntax.md. If you make changes, please make them % there and then regenerate the .tex file using the Makefile. -\section{Layout}\label{layout} +\hypertarget{layout}{% +\section{Layout}\label{layout}} Groups of declarations are organized based on indentation. Declarations with the same indentation belong to the same group. Lines of text that @@ -32,7 +33,8 @@ containing \texttt{y} and \texttt{z}. This group ends just before \texttt{g}, because \texttt{g} is indented less than \texttt{y} and \texttt{z}. -\section{Comments}\label{comments} +\hypertarget{comments}{% +\section{Comments}\label{comments}} Cryptol supports block comments, which start with \texttt{/*} and end with \texttt{*/}, and line comments, which start with \texttt{//} and @@ -47,7 +49,8 @@ Examples: /* This is a /* Nested */ block comment */ \end{verbatim} -\section{Identifiers}\label{identifiers} +\hypertarget{identifiers}{% +\section{Identifiers}\label{identifiers}} Cryptol identifiers consist of one or more characters. The first character must be either an English letter or underscore (\texttt{\_}). @@ -64,8 +67,9 @@ name name1 name' longer_name Name Name2 Name'' longerName \end{verbatim} -\hypertarget{keywords-and-built-in-operators}{\section{Keywords and -Built-in Operators}\label{keywords-and-built-in-operators}} +\hypertarget{keywords-and-built-in-operators}{% +\section{Keywords and Built-in +Operators}\label{keywords-and-built-in-operators}} The following identifiers have special meanings in Cryptol, and may not be used for programmer defined names: @@ -73,8 +77,8 @@ be used for programmer defined names: \begin{verbatim} else include property let infixl parameter extern module then import infixr constraint - if newtype type as infix - private pragma where hiding primitive + if newtype type as infix by + private pragma where hiding primitive down \end{verbatim} The following table contains Cryptol's operators and their associativity @@ -83,41 +87,40 @@ with lowest precedence operators first, and highest precedence last. \begin{longtable}[]{@{}ll@{}} \caption{Operator precedences.}\tabularnewline \toprule -Operator & Associativity\tabularnewline +Operator & Associativity \\ \midrule \endfirsthead \toprule -Operator & Associativity\tabularnewline +Operator & Associativity \\ \midrule \endhead -\texttt{==\textgreater{}} & right\tabularnewline -\texttt{\textbackslash{}/} & right\tabularnewline -\texttt{/\textbackslash{}} & right\tabularnewline -\texttt{==} \texttt{!=} \texttt{===} \texttt{!==} & not -associative\tabularnewline +\texttt{==\textgreater{}} & right \\ +\texttt{\textbackslash{}/} & right \\ +\texttt{/\textbackslash{}} & right \\ +\texttt{==} \texttt{!=} \texttt{===} \texttt{!==} & not associative \\ \texttt{\textgreater{}} \texttt{\textless{}} \texttt{\textless{}=} \texttt{\textgreater{}=} \texttt{\textless{}\$} \texttt{\textgreater{}\$} \texttt{\textless{}=\$} -\texttt{\textgreater{}=\$} & not associative\tabularnewline -\texttt{\textbar{}\textbar{}} & right\tabularnewline -\texttt{\^{}} & left\tabularnewline -\texttt{\&\&} & right\tabularnewline -\texttt{\#} & right\tabularnewline +\texttt{\textgreater{}=\$} & not associative \\ +\texttt{\textbar{}\textbar{}} & right \\ +\texttt{\^{}} & left \\ +\texttt{\&\&} & right \\ +\texttt{\#} & right \\ \texttt{\textgreater{}\textgreater{}} \texttt{\textless{}\textless{}} \texttt{\textgreater{}\textgreater{}\textgreater{}} \texttt{\textless{}\textless{}\textless{}} -\texttt{\textgreater{}\textgreater{}\$} & left\tabularnewline -\texttt{+} \texttt{-} & left\tabularnewline -\texttt{*} \texttt{/} \texttt{\%} \texttt{/\$} \texttt{\%\$} & -left\tabularnewline -\texttt{\^{}\^{}} & right\tabularnewline -\texttt{@} \texttt{@@} \texttt{!} \texttt{!!} & left\tabularnewline -(unary) \texttt{-} \texttt{\textasciitilde{}} & right\tabularnewline +\texttt{\textgreater{}\textgreater{}\$} & left \\ +\texttt{+} \texttt{-} & left \\ +\texttt{*} \texttt{/} \texttt{\%} \texttt{/\$} \texttt{\%\$} & left \\ +\texttt{\^{}\^{}} & right \\ +\texttt{@} \texttt{@@} \texttt{!} \texttt{!!} & left \\ +(unary) \texttt{-} \texttt{\textasciitilde{}} & right \\ \bottomrule \end{longtable} +\hypertarget{built-in-type-level-operators}{% \section{Built-in Type-level -Operators}\label{built-in-type-level-operators} +Operators}\label{built-in-type-level-operators}} Cryptol includes a variety of operators that allow computations on the numeric types used to specify the sizes of sequences. @@ -125,29 +128,30 @@ numeric types used to specify the sizes of sequences. \begin{longtable}[]{@{}ll@{}} \caption{Type-level operators}\tabularnewline \toprule -Operator & Meaning\tabularnewline +Operator & Meaning \\ \midrule \endfirsthead \toprule -Operator & Meaning\tabularnewline +Operator & Meaning \\ \midrule \endhead -\texttt{+} & Addition\tabularnewline -\texttt{-} & Subtraction\tabularnewline -\texttt{*} & Multiplication\tabularnewline -\texttt{/} & Division\tabularnewline -\texttt{/\^{}} & Ceiling division (\texttt{/} rounded up)\tabularnewline -\texttt{\%} & Modulus\tabularnewline -\texttt{\%\^{}} & Ceiling modulus (compute padding)\tabularnewline -\texttt{\^{}\^{}} & Exponentiation\tabularnewline -\texttt{lg2} & Ceiling logarithm (base 2)\tabularnewline -\texttt{width} & Bit width (equal to \texttt{lg2(n+1)})\tabularnewline -\texttt{max} & Maximum\tabularnewline -\texttt{min} & Minimum\tabularnewline +\texttt{+} & Addition \\ +\texttt{-} & Subtraction \\ +\texttt{*} & Multiplication \\ +\texttt{/} & Division \\ +\texttt{/\^{}} & Ceiling division (\texttt{/} rounded up) \\ +\texttt{\%} & Modulus \\ +\texttt{\%\^{}} & Ceiling modulus (compute padding) \\ +\texttt{\^{}\^{}} & Exponentiation \\ +\texttt{lg2} & Ceiling logarithm (base 2) \\ +\texttt{width} & Bit width (equal to \texttt{lg2(n+1)}) \\ +\texttt{max} & Maximum \\ +\texttt{min} & Minimum \\ \bottomrule \end{longtable} -\section{Numeric Literals}\label{numeric-literals} +\hypertarget{numeric-literals}{% +\section{Numeric Literals}\label{numeric-literals}} Numeric literals may be written in binary, octal, decimal, or hexadecimal notation. The base of a literal is determined by its prefix: @@ -226,7 +230,8 @@ some examples: 0x_FFFF_FFEA \end{verbatim} -\section{Expressions}\label{expressions} +\hypertarget{expressions}{% +\section{Expressions}\label{expressions}} This section provides an overview of the Cryptol's expression syntax. @@ -302,7 +307,8 @@ f \x -> x // call `f` with one argument `x -> x` else z // call `+` with two arguments: `2` and `if ...` \end{verbatim} -\section{Bits}\label{bits} +\hypertarget{bits}{% +\section{Bits}\label{bits}} The type \texttt{Bit} has two inhabitants: \texttt{True} and \texttt{False}. These values may be combined using various logical @@ -311,29 +317,30 @@ operators, or constructed as results of comparisons. \begin{longtable}[]{@{}lll@{}} \caption{Bit operations.}\tabularnewline \toprule -Operator & Associativity & Description\tabularnewline +Operator & Associativity & Description \\ \midrule \endfirsthead \toprule -Operator & Associativity & Description\tabularnewline +Operator & Associativity & Description \\ \midrule \endhead -\texttt{==\textgreater{}} & right & Short-cut implication\tabularnewline -\texttt{\textbackslash{}/} & right & Short-cut or\tabularnewline -\texttt{/\textbackslash{}} & right & Short-cut and\tabularnewline -\texttt{!=} \texttt{==} & none & Not equals, equals\tabularnewline +\texttt{==\textgreater{}} & right & Short-cut implication \\ +\texttt{\textbackslash{}/} & right & Short-cut or \\ +\texttt{/\textbackslash{}} & right & Short-cut and \\ +\texttt{!=} \texttt{==} & none & Not equals, equals \\ \texttt{\textgreater{}} \texttt{\textless{}} \texttt{\textless{}=} \texttt{\textgreater{}=} \texttt{\textless{}\$} \texttt{\textgreater{}\$} \texttt{\textless{}=\$} -\texttt{\textgreater{}=\$} & none & Comparisons\tabularnewline -\texttt{\textbar{}\textbar{}} & right & Logical or\tabularnewline -\texttt{\^{}} & left & Exclusive-or\tabularnewline -\texttt{\&\&} & right & Logical and\tabularnewline -\texttt{\textasciitilde{}} & right & Logical negation\tabularnewline +\texttt{\textgreater{}=\$} & none & Comparisons \\ +\texttt{\textbar{}\textbar{}} & right & Logical or \\ +\texttt{\^{}} & left & Exclusive-or \\ +\texttt{\&\&} & right & Logical and \\ +\texttt{\textasciitilde{}} & right & Logical negation \\ \bottomrule \end{longtable} -\section{Multi-way Conditionals}\label{multi-way-conditionals} +\hypertarget{multi-way-conditionals}{% +\section{Multi-way Conditionals}\label{multi-way-conditionals}} The \texttt{if\ ...\ then\ ...\ else} construct can be used with multiple branches. For example: @@ -347,7 +354,8 @@ x = if y % 2 == 0 then 1 else 7 \end{verbatim} -\section{Tuples and Records}\label{tuples-and-records} +\hypertarget{tuples-and-records}{% +\section{Tuples and Records}\label{tuples-and-records}} Tuples and records are used for packaging multiple values together. Tuples are enclosed in parentheses, while records are enclosed in curly @@ -379,7 +387,8 @@ Ordering on tuples and records is defined lexicographically. Tuple components are compared in the order they appear, whereas record fields are compared in alphabetical order of field names. -\subsection{Accessing Fields}\label{accessing-fields} +\hypertarget{accessing-fields}{% +\subsection{Accessing Fields}\label{accessing-fields}} The components of a record or a tuple may be accessed in two ways: via pattern matching or by using explicit component selectors. Explicit @@ -441,7 +450,8 @@ only the first entry in the tuple. This behavior is quite handy when examining complex data at the REPL. -\subsection{Updating Fields}\label{updating-fields} +\hypertarget{updating-fields}{% +\subsection{Updating Fields}\label{updating-fields}} The components of a record or a tuple may be updated using the following notation: @@ -464,7 +474,8 @@ n = { pt = r, size = 100 } // nested record { n | pt.x -> x + 10 } == { pt = { x = 25, y = 20 }, size = 100 } \end{verbatim} -\section{Sequences}\label{sequences} +\hypertarget{sequences}{% +\section{Sequences}\label{sequences}} A sequence is a fixed-length collection of elements of the same type. The type of a finite sequence of length \texttt{n}, with elements of @@ -475,19 +486,25 @@ with elements of type \texttt{a} has type \texttt{{[}inf{]}\ a}, and \texttt{{[}inf{]}} is an infinite stream of bits. \begin{verbatim} -[e1,e2,e3] // A sequence with three elements +[e1,e2,e3] // A sequence with three elements -[t1 .. t3 ] // Sequence enumerations -[t1, t2 .. t3 ] // Step by t2 - t1 -[e1 ... ] // Infinite sequence starting at e1 -[e1, e2 ... ] // Infinite sequence stepping by e2-e1 +[t1 .. t2] // Enumeration +[t1 .. t2 down by n] // Enumeration (downward stride, ex. bound) +[t1, t2 .. t3] // Enumeration (step by t2 - t1) -[ e | p11 <- e11, p12 <- e12 // Sequence comprehensions +[e1 ...] // Infinite sequence starting at e1 +[e1, e2 ...] // Infinite sequence stepping by e2-e1 + +[ e | p11 <- e11, p12 <- e12 // Sequence comprehensions | p21 <- e21, p22 <- e22 ] -x = generate (\i -> e) // Sequence from generating function -x @ i = e // Sequence with index binding -arr @ i @ j = e // Two-dimensional sequence +x = generate (\i -> e) // Sequence from generating function +x @ i = e // Sequence with index binding +arr @ i @ j = e // Two-dimensional sequence \end{verbatim} Note: the bounds in finite sequences (those with \texttt{..}) are type @@ -497,28 +514,26 @@ expressions. \begin{longtable}[]{@{}ll@{}} \caption{Sequence operations.}\tabularnewline \toprule -Operator & Description\tabularnewline +Operator & Description \\ \midrule \endfirsthead \toprule -Operator & Description\tabularnewline +Operator & Description \\ \midrule \endhead -\texttt{\#} & Sequence concatenation\tabularnewline +\texttt{\#} & Sequence concatenation \\ \texttt{\textgreater{}\textgreater{}} \texttt{\textless{}\textless{}} & -Shift (right, left)\tabularnewline +Shift (right, left) \\ \texttt{\textgreater{}\textgreater{}\textgreater{}} -\texttt{\textless{}\textless{}\textless{}} & Rotate (right, -left)\tabularnewline +\texttt{\textless{}\textless{}\textless{}} & Rotate (right, left) \\ \texttt{\textgreater{}\textgreater{}\$} & Arithmetic right shift (on -bitvectors only)\tabularnewline -\texttt{@} \texttt{!} & Access elements (front, back)\tabularnewline -\texttt{@@} \texttt{!!} & Access sub-sequence (front, -back)\tabularnewline +bitvectors only) \\ +\texttt{@} \texttt{!} & Access elements (front, back) \\ +\texttt{@@} \texttt{!!} & Access sub-sequence (front, back) \\ \texttt{update} \texttt{updateEnd} & Update the value of a sequence at a -location (front, back)\tabularnewline +location (front, back) \\ \texttt{updates} \texttt{updatesEnd} & Update multiple values of a -sequence (front, back)\tabularnewline +sequence (front, back) \\ \bottomrule \end{longtable} @@ -529,14 +544,16 @@ There are also lifted pointwise operations. p1 # p2 // Split sequence pattern \end{verbatim} -\section{Functions}\label{functions} +\hypertarget{functions}{% +\section{Functions}\label{functions}} \begin{verbatim} \p1 p2 -> e // Lambda expression f p1 p2 = e // Function definition \end{verbatim} -\section{Local Declarations}\label{local-declarations} +\hypertarget{local-declarations}{% +\section{Local Declarations}\label{local-declarations}} \begin{verbatim} e where ds @@ -546,7 +563,9 @@ Note that by default, any local declarations without type signatures are monomorphized. If you need a local declaration to be polymorphic, use an explicit type signature. -\section{Explicit Type Instantiation}\label{explicit-type-instantiation} +\hypertarget{explicit-type-instantiation}{% +\section{Explicit Type +Instantiation}\label{explicit-type-instantiation}} If \texttt{f} is a polymorphic value with type: @@ -561,8 +580,9 @@ you can evaluate \texttt{f}, passing it a type parameter: f `{ tyParam = 13 } \end{verbatim} +\hypertarget{demoting-numeric-types-to-values}{% \section{Demoting Numeric Types to -Values}\label{demoting-numeric-types-to-values} +Values}\label{demoting-numeric-types-to-values}} The value corresponding to a numeric type may be accessed using the following notation: @@ -571,15 +591,26 @@ following notation: `t \end{verbatim} -Here \texttt{t} should be a type expression with numeric kind. The -resulting expression is a finite word, which is sufficiently large to -accommodate the value of the type: +Here \texttt{t} should be a finite type expression with numeric kind. +The resulting expression will be of a numeric base type, which is +sufficiently large to accommodate the value of the type: \begin{verbatim} -`t : {n} (fin n, n >= width t) => [n] +`t : {a} (Literal t a) => a \end{verbatim} -\section{Explicit Type Annotations}\label{explicit-type-annotations} +This backtick notation is syntax sugar for an application of the +\texttt{number} primtive, so the above may be written as: + +\begin{verbatim} +number`{t} : {a} (Literal t a) => a +\end{verbatim} + +If a type cannot be inferred from context, a suitable type will be +automatically chosen if possible, usually \texttt{Integer}. + +\hypertarget{explicit-type-annotations}{% +\section{Explicit Type Annotations}\label{explicit-type-annotations}} Explicit type annotations may be added on expressions, patterns, and in argument definitions. @@ -592,15 +623,18 @@ p : t f (x : t) = ... \end{verbatim} -\section{Type Signatures}\label{type-signatures} +\hypertarget{type-signatures}{% +\section{Type Signatures}\label{type-signatures}} \begin{verbatim} f,g : {a,b} (fin a) => [a] b \end{verbatim} -\section{Type Synonyms and Newtypes}\label{type-synonyms-and-newtypes} +\hypertarget{type-synonyms-and-newtypes}{% +\section{Type Synonyms and Newtypes}\label{type-synonyms-and-newtypes}} -\subsection{Type synonyms}\label{type-synonyms} +\hypertarget{type-synonyms}{% +\subsection{Type synonyms}\label{type-synonyms}} \begin{verbatim} type T a b = [a] b @@ -613,7 +647,8 @@ had instead written the body of the type synonym in line. Type synonyms may mention other synonyms, but it is not allowed to create a recursive collection of type synonyms. -\subsection{Newtypes}\label{newtypes} +\hypertarget{newtypes}{% +\subsection{Newtypes}\label{newtypes}} \begin{verbatim} newtype NewT a b = { seq : [a]b } @@ -647,7 +682,8 @@ of newtypes to extract the values in the body of the type. 6 \end{verbatim} -\section{Modules}\label{modules} +\hypertarget{modules}{% +\section{Modules}\label{modules}} A \textbf{\emph{module}} is used to group some related definitions. Each file may contain at most one module. @@ -661,7 +697,8 @@ f : [8] f = 10 \end{verbatim} -\section{Hierarchical Module Names}\label{hierarchical-module-names} +\hypertarget{hierarchical-module-names}{% +\section{Hierarchical Module Names}\label{hierarchical-module-names}} Module may have either simple or \textbf{\emph{hierarchical}} names. Hierarchical names are constructed by gluing together ordinary @@ -680,7 +717,8 @@ when searching for module \texttt{Hash::SHA256}, Cryptol will look for a file named \texttt{SHA256.cry} in a directory called \texttt{Hash}, contained in one of the directories specified by \texttt{CRYPTOLPATH}. -\section{Module Imports}\label{module-imports} +\hypertarget{module-imports}{% +\section{Module Imports}\label{module-imports}} To use the definitions from one module in another module, we use \texttt{import} declarations: @@ -701,7 +739,8 @@ import M // import all definitions from `M` g = f // `f` was imported from `M` \end{verbatim} -\section{Import Lists}\label{import-lists} +\hypertarget{import-lists}{% +\section{Import Lists}\label{import-lists}} Sometimes, we may want to import only some of the definitions from a module. To do so, we use an import declaration with an @@ -725,7 +764,8 @@ Using explicit import lists helps reduce name collisions. It also tends to make code easier to understand, because it makes it easy to see the source of definitions. -\section{Hiding Imports}\label{hiding-imports} +\hypertarget{hiding-imports}{% +\section{Hiding Imports}\label{hiding-imports}} Sometimes a module may provide many definitions, and we want to use most of them but with a few exceptions (e.g., because those would result to a @@ -748,7 +788,8 @@ import M hiding (h) // Import everything but `h` x = f + g \end{verbatim} -\section{Qualified Module Imports}\label{qualified-module-imports} +\hypertarget{qualified-module-imports}{% +\section{Qualified Module Imports}\label{qualified-module-imports}} Another way to avoid name collisions is by using a \textbf{\emph{qualified}} import. @@ -791,7 +832,8 @@ Such declarations will introduces all definitions from \texttt{A} and \texttt{X} but to use them, you would have to qualify using the prefix \texttt{B:::}. -\section{Private Blocks}\label{private-blocks} +\hypertarget{private-blocks}{% +\section{Private Blocks}\label{private-blocks}} In some cases, definitions in a module might use helper functions that are not intended to be used outside the module. It is good practice to @@ -832,7 +874,8 @@ private helper2 = 3 \end{verbatim} -\section{Parameterized Modules}\label{parameterized-modules} +\hypertarget{parameterized-modules}{% +\section{Parameterized Modules}\label{parameterized-modules}} \begin{verbatim} module M where @@ -850,7 +893,9 @@ f : [n] f = 1 + x \end{verbatim} -\section{Named Module Instantiations}\label{named-module-instantiations} +\hypertarget{named-module-instantiations}{% +\section{Named Module +Instantiations}\label{named-module-instantiations}} One way to use a parameterized module is through a named instantiation: @@ -887,8 +932,9 @@ Note that the only purpose of the body of \texttt{N} (the declarations after the \texttt{where} keyword) is to define the parameters for \texttt{M}. +\hypertarget{parameterized-instantiations}{% \section{Parameterized -Instantiations}\label{parameterized-instantiations} +Instantiations}\label{parameterized-instantiations}} It is possible for a module instantiation to be itself parameterized. This could be useful if we need to define some of a module's parameters @@ -923,8 +969,9 @@ In this case \texttt{N} has a single parameter \texttt{x}. The result of instantiating \texttt{N} would result in instantiating \texttt{M} using the value of \texttt{x} and \texttt{12} for the value of \texttt{y}. +\hypertarget{importing-parameterized-modules}{% \section{Importing Parameterized -Modules}\label{importing-parameterized-modules} +Modules}\label{importing-parameterized-modules}} It is also possible to import a parameterized module without using a module instantiation: diff --git a/docs/ProgrammingCryptol/crashCourse/CrashCourse.tex b/docs/ProgrammingCryptol/crashCourse/CrashCourse.tex index bdd280b2..7f17718b 100644 --- a/docs/ProgrammingCryptol/crashCourse/CrashCourse.tex +++ b/docs/ProgrammingCryptol/crashCourse/CrashCourse.tex @@ -97,7 +97,8 @@ Here is the response from Cryptol, in order: \begin{small} \begin{reploutVerb} True - [error] at :2:1--2:6 Value not in scope: false + [error] at :2:1--2:6 + Value not in scope: false False 0x4 True @@ -790,7 +791,7 @@ Here are Cryptol's responses: [] invalid sequence index: 12 -- Backtrace -- - (Cryptol::@) called at Cryptol:820:14--820:20 + (Cryptol::@) called at Cryptol:875:14--875:20 (Cryptol::@@) called at :9:1--9:28 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] 9 @@ -1021,8 +1022,7 @@ the result:\indSignature Cannot evaluate polymorphic value. Type: {n, m, a} (n * m == 12, Literal 12 a, fin m) => [n][m]a Cryptol> :t split [1..12] - split [1 .. 12] : {n, m, a} (n * m == 12, Literal 12 a, fin m) => - [n][m]a + split [1 .. 12] : {n, m, a} (n * m == 12, Literal 12 a, fin m) => [n][m]a \end{replPrompt} %% cryptol 1 said: : {a b c} (fin c,c >= 4,a*b == 12) => [a][b][c] @@ -1795,7 +1795,7 @@ is subtly different from \texttt{[k, k+1...]}. command to see the type Cryptol infers for this expression explicitly: \begin{replPrompt} Cryptol> :t [1:[_] .. 10] - [1 .. 10 : [_]] : {n} (n >= 4, n >= 1, fin n) => [10][n] + [1 .. 10 : [_]] : {n} (n >= 4, fin n) => [10][n] \end{replPrompt} Cryptol tells us that the sequence has precisely $10$ elements, and each element is at least $4$ bits wide. diff --git a/docs/RefMan/.gitignore b/docs/RefMan/.gitignore new file mode 100644 index 00000000..e69de29b diff --git a/docs/RefMan/RefMan.rst b/docs/RefMan/RefMan.rst index efb80dd6..dd9837d3 100644 --- a/docs/RefMan/RefMan.rst +++ b/docs/RefMan/RefMan.rst @@ -1,8 +1,3 @@ -.. Cryptol Reference Manual documentation master file, created by - sphinx-quickstart on Thu Apr 29 15:31:18 2021. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. - ######################## Cryptol Reference Manual ######################## @@ -22,7 +17,7 @@ Basic Syntax Declarations ============ -.. code-block:: cryptol +.. code-block:: cryptol f x = x + y + z @@ -126,7 +121,8 @@ not be used for programmer defined names: primitive parameter constraint - + down + by .. _Keywords: .. code-block:: none @@ -134,8 +130,8 @@ not be used for programmer defined names: else include property let infixl parameter extern module then import infixr constraint - if newtype type as infix - private pragma where hiding primitive + if newtype type as infix down + private pragma where hiding primitive by The following table contains Cryptol's operators and their @@ -246,7 +242,7 @@ type is inferred from context in which the literal is used. Examples: 0b1010 // : [4], 1 * number of digits 0o1234 // : [12], 3 * number of digits 0x1234 // : [16], 4 * number of digits - + 10 // : {a}. (Literal 10 a) => a // a = Integer or [n] where n >= width 10 @@ -356,7 +352,7 @@ in argument definitions. then y else z : Bit // the type annotation is on `z`, not the whole `if` [1..9 : [8]] // specify that elements in `[1..9]` have type `[8]` - + f (x : [8]) = x + 1 // type annotation on patterns .. todo:: @@ -442,15 +438,23 @@ following notation: `t -Here ``t`` should be a type expression with numeric kind. The resulting -expression is a finite word, which is sufficiently large to accommodate -the value of the type: +Here `t` should be a finite type expression with numeric kind. The resulting +expression will be of a numeric base type, which is sufficiently large +to accommodate the value of the type: .. code-block:: cryptol - `t : {n} (fin n, n >= width t) => [n] + `t : {a} (Literal t a) => a +This backtick notation is syntax sugar for an application of the +`number` primtive, so the above may be written as: +.. code-block:: cryptol + + number`{t} : {a} (Literal t a) => a + +If a type cannot be inferred from context, a suitable type will be +automatically chosen if possible, usually `Integer`. @@ -507,7 +511,7 @@ sign. Examples: (1,2,3) // A tuple with 3 component () // A tuple with no components - + { x = 1, y = 2 } // A record with two fields, `x` and `y` {} // A record with no fields @@ -520,7 +524,7 @@ Examples: (1,2) == (1,2) // True (1,2) == (2,1) // False - + { x = 1, y = 2 } == { x = 1, y = 2 } // True { x = 1, y = 2 } == { y = 2, x = 1 } // True @@ -539,7 +543,7 @@ component selectors are written as follows: (15, 20).0 == 15 (15, 20).1 == 20 - + { x = 15, y = 20 }.x == 15 Explicit record selectors may be used only if the program contains @@ -549,12 +553,12 @@ record. For example: .. code-block:: cryptol type T = { sign : Bit, number : [15] } - + // Valid definition: // the type of the record is known. isPositive : T -> Bit isPositive x = x.sign - + // Invalid definition: // insufficient type information. badDef x = x.f @@ -567,9 +571,9 @@ patterns use braces. Examples: .. code-block:: cryptol getFst (x,_) = x - + distance2 { x = xPos, y = yPos } = xPos ^^ 2 + yPos ^^ 2 - + f p = x + y where (x, y) = p @@ -605,14 +609,14 @@ notation: r = { x = 15, y = 20 } // a record t = (True,True) // a tuple n = { pt = r, size = 100 } // nested record - + // Setting fields { r | x = 30 } == { x = 30, y = 20 } { t | 0 = False } == (False,True) - + // Update relative to the old value { r | x -> x + 5 } == { x = 20, y = 20 } - + // Update a nested field { n | pt.x = 10 } == { pt = { x = 10, y = 20 }, size = 100 } { n | pt.x -> x + 10 } == { pt = { x = 25, y = 20 }, size = 100 } @@ -630,20 +634,25 @@ an infinite stream of bits. .. code-block:: cryptol - [e1,e2,e3] // A sequence with three elements - - [t1 .. t3 ] // Sequence enumerations - [t1, t2 .. t3 ] // Step by t2 - t1 - [e1 ... ] // Infinite sequence starting at e1 - [e1, e2 ... ] // Infinite sequence stepping by e2-e1 - - [ e | p11 <- e11, p12 <- e12 // Sequence comprehensions - | p21 <- e21, p22 <- e22 ] - - x = generate (\i -> e) // Sequence from generating function - x @ i = e // Sequence with index binding - arr @ i @ j = e // Two-dimensional sequence + [e1,e2,e3] // A sequence with three elements + [t1 .. t2] // Enumeration + [t1 .. t2 down by n] // Enumeration (downward stride, ex. bound) + [t1, t2 .. t3] // Enumeration (step by t2 - t1) + + [e1 ...] // Infinite sequence starting at e1 + [e1, e2 ...] // Infinite sequence stepping by e2-e1 + + [ e | p11 <- e11, p12 <- e12 // Sequence comprehensions + | p21 <- e21, p22 <- e22 ] + + x = generate (\i -> e) // Sequence from generating function + x @ i = e // Sequence with index binding + arr @ i @ j = e // Two-dimensional sequence Note: the bounds in finite sequences (those with `..`) are type expressions, while the bounds in infinite sequences are value @@ -658,7 +667,7 @@ expressions. +------------------------------+---------------------------------------------+ | ``>>`` ``<<`` | Shift (right, left) | +------------------------------+---------------------------------------------+ - | ``>>>` ``<<<`` | Rotate (right, left) | + | ``>>>`` ``<<<`` | Rotate (right, left) | +------------------------------+---------------------------------------------+ | ``>>$`` | Arithmetic right shift (on bitvectors only) | +------------------------------+---------------------------------------------+ @@ -692,6 +701,119 @@ Functions f p1 p2 = e // Function definition + +******************************************************************************** +Overloaded Operations +******************************************************************************** + +Equality +======== + +.. code-block:: cryptol + + Eq + (==) : {a} (Eq a) => a -> a -> Bit + (!=) : {a} (Eq a) => a -> a -> Bit + (===) : {a, b} (Eq b) => (a -> b) -> (a -> b) -> (a -> Bit) + (!==) : {a, b} (Eq b) => (a -> b) -> (a -> b) -> (a -> Bit) + +Comparisons +=========== + +.. code-block:: cryptol + + Cmp + (<) : {a} (Cmp a) => a -> a -> Bit + (>) : {a} (Cmp a) => a -> a -> Bit + (<=) : {a} (Cmp a) => a -> a -> Bit + (>=) : {a} (Cmp a) => a -> a -> Bit + min : {a} (Cmp a) => a -> a -> a + max : {a} (Cmp a) => a -> a -> a + abs : {a} (Cmp a, Ring a) => a -> a + + +Signed Comparisons +================== + +.. code-block:: cryptol + + SignedCmp + (<$) : {a} (SignedCmp a) => a -> a -> Bit + (>$) : {a} (SignedCmp a) => a -> a -> Bit + (<=$) : {a} (SignedCmp a) => a -> a -> Bit + (>=$) : {a} (SignedCmp a) => a -> a -> Bit + + +Zero +==== + +.. code-block:: cryptol + + Zero + zero : {a} (Zero a) => a + +Logical Operations +================== + +.. code-block:: cryptol + + Logic + (&&) : {a} (Logic a) => a -> a -> a + (||) : {a} (Logic a) => a -> a -> a + (^) : {a} (Logic a) => a -> a -> a + complement : {a} (Logic a) => a -> a + +Basic Arithmetic +================ + +.. code-block:: cryptol + + Ring + fromInteger : {a} (Ring a) => Integer -> a + (+) : {a} (Ring a) => a -> a -> a + (-) : {a} (Ring a) => a -> a -> a + (*) : {a} (Ring a) => a -> a -> a + negate : {a} (Ring a) => a -> a + (^^) : {a, e} (Ring a, Integral e) => a -> e -> a + +Integral Operations +=================== + +.. code-block:: cryptol + + Integral + (/) : {a} (Integral a) => a -> a -> a + (%) : {a} (Integral a) => a -> a -> a + (^^) : {a, e} (Ring a, Integral e) => a -> e -> a + toInteger : {a} (Integral a) => a -> Integer + infFrom : {a} (Integral a) => a -> [inf]a + infFromThen : {a} (Integral a) => a -> a -> [inf]a + + +Division +======== + +.. code-block:: cryptol + + Field + recip : {a} (Field a) => a -> a + (/.) : {a} (Field a) => a -> a -> a + +Rounding +======== + +.. code-block:: cryptol + + Round + ceiling : {a} (Round a) => a -> Integer + floor : {a} (Round a) => a -> Integer + trunc : {a} (Round a) => a -> Integer + roundAway : {a} (Round a) => a -> Integer + roundToEven : {a} (Round a) => a -> Integer + + + + ******************************************************************************** Type Declarations ******************************************************************************** @@ -774,7 +896,7 @@ identifiers using the symbol ``::``. .. code-block:: cryptol module Hash::SHA256 where - + sha256 = ... The structure in the name may be used to group together related @@ -853,7 +975,7 @@ to use a *hiding* import: :caption: module M module M where - + f = 0x02 g = 0x03 h = 0x04 @@ -863,9 +985,9 @@ to use a *hiding* import: :caption: module N module N where - + import M hiding (h) // Import everything but `h` - + x = f + g @@ -880,7 +1002,7 @@ Another way to avoid name collisions is by using a :caption: module M module M where - + f : [8] f = 2 @@ -889,9 +1011,9 @@ Another way to avoid name collisions is by using a :caption: module N module N where - + import M as P - + g = P::f // `f` was imported from `M` // but when used it needs to be prefixed by the qualifier `P` @@ -1097,20 +1219,20 @@ a module instantiation: .. code-block:: cryptol module M where - + parameter x : [8] y : [8] - + f : [8] f = x + y .. code-block:: cryptol module N where - + import `M - + g = f { x = 2, y = 3 } A *backtick* at the start of the name of an imported module indicates @@ -1121,3 +1243,6 @@ the parameters of a module. All value parameters are grouped in a record. This is why in the example ``f`` is applied to a record of values, even though its definition in ``M`` does not look like a function. + + + diff --git a/docs/RefMan/_build/doctrees/RefMan.doctree b/docs/RefMan/_build/doctrees/RefMan.doctree new file mode 100644 index 00000000..86068b0a Binary files /dev/null and b/docs/RefMan/_build/doctrees/RefMan.doctree differ diff --git a/docs/RefMan/_build/doctrees/environment.pickle b/docs/RefMan/_build/doctrees/environment.pickle new file mode 100644 index 00000000..e2efd362 Binary files /dev/null and b/docs/RefMan/_build/doctrees/environment.pickle differ diff --git a/docs/RefMan/_build/html/.buildinfo b/docs/RefMan/_build/html/.buildinfo new file mode 100644 index 00000000..a70cd673 --- /dev/null +++ b/docs/RefMan/_build/html/.buildinfo @@ -0,0 +1,4 @@ +# Sphinx build info version 1 +# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. +config: 3f9a4daf23c759ed9c684b18b96cc6ff +tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/docs/RefMan/_build/html/.nojekyll b/docs/RefMan/_build/html/.nojekyll new file mode 100644 index 00000000..e69de29b diff --git a/docs/RefMan/_build/html/RefMan.html b/docs/RefMan/_build/html/RefMan.html new file mode 100644 index 00000000..6392dfe7 --- /dev/null +++ b/docs/RefMan/_build/html/RefMan.html @@ -0,0 +1,1411 @@ + + + + + + + + + + Cryptol Reference Manual — Cryptol 2.11.0 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + + + +
+ +
+ + + + + + + + + + + + + + + + + + + +
+ + + + +
+
+
+
+ +
+

Cryptol Reference Manual

+
+
+
+

Basic Syntax

+
+

Declarations

+
f x = x + y + z
+
+
+
+

Type Signatures

+
f,g : {a,b} (fin a) => [a] b
+
+
+
+
+
+

Layout

+

Groups of declarations are organized based on indentation. +Declarations with the same indentation belong to the same group. +Lines of text that are indented more than the beginning of a +declaration belong to that declaration, while lines of text that are +indented less terminate a group of declarations. Consider, for example, +the following Cryptol declarations:

+
f x = x + y + z
+  where
+  y = x * x
+  z = x + y
+
+g y = y
+
+
+

This group has two declarations, one for f and one for g. All the +lines between f and g that are indented more than f belong to +f. The same principle applies to the declarations in the where block +of f, which defines two more local names, y and z.

+
+
+

Comments

+

Cryptol supports block comments, which start with /* and end with +*/, and line comments, which start with // and terminate at the +end of the line. Block comments may be nested arbitrarily.

+
/* This is a block comment */
+// This is a line comment
+/* This is a /* Nested */ block comment */
+
+
+
+

Todo

+

Document /** */

+
+
+
+

Identifiers

+

Cryptol identifiers consist of one or more characters. The first +character must be either an English letter or underscore (_). The +following characters may be an English letter, a decimal digit, +underscore (_), or a prime ('). Some identifiers have special +meaning in the language, so they may not be used in programmer-defined +names (see Keywords and Built-in Operators).

+
+
Examples of identifiers
+
name    name1    name'    longer_name
+Name    Name2    Name''   longerName
+
+
+
+
+
+

Keywords and Built-in Operators

+

The following identifiers have special meanings in Cryptol, and may +not be used for programmer defined names:

+
+
Keywords
+
else       include    property    let       infixl       parameter
+extern     module     then        import    infixr       constraint
+if         newtype    type        as        infix        down
+private    pragma     where       hiding    primitive    by
+
+
+
+

The following table contains Cryptol’s operators and their +associativity with lowest precedence operators first, and highest +precedence last.

+ + ++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Operator precedences
OperatorAssociativity
==>right
\/right
/\right
== != === !==not associative
> < <= >= +<$ >$ <=$ >=$not associative
||right
^left
&&right
#right
>> << >>> <<< >>$left
+ -left
* / % /$ %$left
^^right
@ @@ ! !!left
(unary) - ~right
+
+
+

Built-in Type-level Operators

+

Cryptol includes a variety of operators that allow computations on +the numeric types used to specify the sizes of sequences.

+ + ++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Type-level operators
OperatorMeaning
+Addition
-Subtraction
*Multiplication
/Division
/^Ceiling division (/ rounded up)
%Modulus
%^Ceiling modulus (compute padding)
^^Exponentiation
lg2Ceiling logarithm (base 2)
widthBit width (equal to lg2(n+1))
maxMaximum
minMinimum
+
+
+

Numeric Literals

+

Numeric literals may be written in binary, octal, decimal, or +hexadecimal notation. The base of a literal is determined by its prefix: +0b for binary, 0o for octal, no special prefix for +decimal, and 0x for hexadecimal.

+
+
Examples of literals
+
254                 // Decimal literal
+0254                // Decimal literal
+0b11111110          // Binary literal
+0o376               // Octal literal
+0xFE                // Hexadecimal literal
+0xfe                // Hexadecimal literal
+
+
+
+

Numeric literals in binary, octal, or hexadecimal notation result in +bit sequences of a fixed length (i.e., they have type [n] for +some n). The length is determined by the base and the number +of digits in the literal. Decimal literals are overloaded, and so the +type is inferred from context in which the literal is used. Examples:

+
+
Literals and their types
+
0b1010              // : [4],   1 * number of digits
+0o1234              // : [12],  3 * number of digits
+0x1234              // : [16],  4 * number of digits
+
+10                  // : {a}. (Literal 10 a) => a
+                    // a = Integer or [n] where n >= width 10
+
+
+
+

Numeric literals may also be written as polynomials by writing a polynomial +expression in terms of x between an opening <| and a closing |>. +Numeric literals in polynomial notation result in bit sequences of length +one more than the degree of the polynomial. Examples:

+
+
Polynomial literals
+
<| x^^6 + x^^4 + x^^2 + x^^1 + 1 |>  // : [7], equal to 0b1010111
+<| x^^4 + x^^3 + x |>                // : [5], equal to 0b11010
+
+
+
+

Cryptol also supports fractional literals using binary (prefix 0b), +octal (prefix 0o), decimal (no prefix), and hexadecimal (prefix ox) +digits. A fractional literal must contain a . and may optionally +have an exponent. The base of the exponent for binary, octal, +and hexadecimal literals is 2 and the exponent is marked using the symbol p. +Decimal fractional literals use exponent base 10, and the symbol e. +Examples:

+
+
Fractional literals
+
10.2
+10.2e3            // 10.2 * 10^3
+0x30.1            // 3 * 64 + 1/16
+0x30.1p4          // (3 * 64 + 1/16) * 2^4
+
+
+
+

All fractional literals are overloaded and may be used with types that support +fractional numbers (e.g., Rational, and the Float family of types).

+

Some types (e.g. the Float family) cannot represent all fractional literals +precisely. Such literals are rejected statically when using binary, octal, +or hexadecimal notation. When using decimal notation, the literal is rounded +to the closest representable even number.

+

All numeric literals may also include _, which has no effect on the +literal value but may be used to improve readability. Here are some examples:

+
+
Using _
+
0b_0000_0010
+0x_FFFF_FFEA
+
+
+
+
+
+
+

Expressions

+

This section provides an overview of the Cryptol’s expression syntax.

+
+

Calling Functions

+
f 2             // call `f` with parameter `2`
+g x y           // call `g` with two parameters: `x` and `y`
+h (x,y)         // call `h` with one parameter,  the pair `(x,y)`
+
+
+
+
+

Prefix Operators

+
-2              // call unary `-` with parameter `2`
+- 2             // call unary `-` with parameter `2`
+f (-2)          // call `f` with one argument: `-2`,  parens are important
+-f 2            // call unary `-` with parameter `f 2`
+- f 2           // call unary `-` with parameter `f 2`
+
+
+
+
+

Infix Functions

+
2 + 3           // call `+` with two parameters: `2` and `3`
+2 + 3 * 5       // call `+` with two parameters: `2` and `3 * 5`
+(+) 2 3         // call `+` with two parameters: `2` and `3`
+f 2 + g 3       // call `+` with two parameters: `f 2` and `g 3`
+- 2 + - 3       // call `+` with two parameters: `-2` and `-3`
+- f 2 + - g 3
+
+
+
+
+

Type Annotations

+

Explicit type annotations may be added on expressions, patterns, and +in argument definitions.

+
x : Bit         // specify that `x` has type `Bit`
+f x : Bit       // specify that `f x` has type `Bit`
+- f x : [8]     // specify that `- f x` has type `[8]`
+2 + 3 : [8]     // specify that `2 + 3` has type `[8]`
+\x -> x : [8]   // type annotation is on `x`, not the function
+if x
+  then y
+  else z : Bit  // the type annotation is on `z`, not the whole `if`
+[1..9 : [8]]    // specify that elements in `[1..9]` have type `[8]`
+
+f (x : [8]) = x + 1   // type annotation on patterns
+
+
+
+

Todo

+

Patterns with type variables

+
+
+
+

Explicit Type Instantiation

+

If f is a polymorphic value with type:

+
f : { tyParam } tyParam
+f = zero
+
+
+

you can evaluate f, passing it a type parameter:

+
f `{ tyParam = 13 }
+
+
+
+
+

Local Declarations

+

Local declarations have the weakest precedence of all expressions.

+
2 + x : [T]
+  where
+  type T = 8
+  x      = 2          // `T` and `x` are in scope of `2 + x : `[T]`
+
+if x then 1 else 2
+  where x = 2         // `x` is in scope in the whole `if`
+
+\y -> x + y
+  where x = 2         // `y` is not in scope in the defintion of `x`
+
+
+
+

Block Arguments

+

When used as the last argument to a function call, +if and lambda expressions do not need parens:

+
f \x -> x       // call `f` with one argument `x -> x`
+2 + if x
+      then y
+      else z    // call `+` with two arguments: `2` and `if ...`
+
+
+
+
+

Conditionals

+

The if ... then ... else construct can be used with +multiple branches. For example:

+
x = if y % 2 == 0 then 22 else 33
+
+x = if y % 2 == 0 then 1
+     | y % 3 == 0 then 2
+     | y % 5 == 0 then 3
+     else 7
+
+
+
+
+

Demoting Numeric Types to Values

+

The value corresponding to a numeric type may be accessed using the +following notation:

+
`t
+
+
+

Here t should be a finite type expression with numeric kind. The resulting +expression will be of a numeric base type, which is sufficiently large +to accommodate the value of the type:

+
`t : {a} (Literal t a) => a
+
+
+

This backtick notation is syntax sugar for an application of the +number primtive, so the above may be written as:

+
number`{t} : {a} (Literal t a) => a
+
+
+

If a type cannot be inferred from context, a suitable type will be +automatically chosen if possible, usually Integer.

+
+
+
+
+

Basic Types

+
+

Bits

+

The type Bit has two inhabitants: True and False. These values +may be combined using various logical operators, or constructed as +results of comparisons.

+ + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Bit operations.
OperatorAssociativityDescription
==>rightShort-cut implication
\/rightShort-cut or
/\rightShort-cut and
!= ==noneNot equals, equals
> < <= >= +<$ >$ +<=$ >=$noneComparisons; +$ indicates signed
||rightLogical or
^leftExclusive-or
&&rightLogical and
~rightLogical negation
+
+
+

Tuples and Records

+

Tuples and records are used for packaging multiple values together. +Tuples are enclosed in parentheses, while records are enclosed in +curly braces. The components of both tuples and records are separated by +commas. The components of tuples are expressions, while the +components of records are a label and a value separated by an equal +sign. Examples:

+
(1,2,3)           // A tuple with 3 component
+()                // A tuple with no components
+
+{ x = 1, y = 2 }  // A record with two fields, `x` and `y`
+{}                // A record with no fields
+
+
+

The components of tuples are identified by position, while the +components of records are identified by their label, and so the +ordering of record components is not important for most purposes. +Examples:

+
           (1,2) == (1,2)               // True
+           (1,2) == (2,1)               // False
+
+{ x = 1, y = 2 } == { x = 1, y = 2 }    // True
+{ x = 1, y = 2 } == { y = 2, x = 1 }    // True
+
+
+

Ordering on tuples and records is defined lexicographically. Tuple +components are compared in the order they appear, whereas record +fields are compared in alphabetical order of field names.

+
+

Accessing Fields

+

The components of a record or a tuple may be accessed in two ways: via +pattern matching or by using explicit component selectors. Explicit +component selectors are written as follows:

+
(15, 20).0           == 15
+(15, 20).1           == 20
+
+{ x = 15, y = 20 }.x == 15
+
+
+

Explicit record selectors may be used only if the program contains +sufficient type information to determine the shape of the tuple or +record. For example:

+
type T = { sign : Bit, number : [15] }
+
+// Valid definition:
+// the type of the record is known.
+isPositive : T -> Bit
+isPositive x = x.sign
+
+// Invalid definition:
+// insufficient type information.
+badDef x = x.f
+
+
+

The components of a tuple or a record may also be accessed using +pattern matching. Patterns for tuples and records mirror the syntax +for constructing values: tuple patterns use parentheses, while record +patterns use braces. Examples:

+
getFst (x,_) = x
+
+distance2 { x = xPos, y = yPos } = xPos ^^ 2 + yPos ^^ 2
+
+f p = x + y where
+    (x, y) = p
+
+
+

Selectors are also lifted through sequence and function types, point-wise, +so that the following equations should hold:

+
xs.l == [ x.l | x <- xs ]     // sequences
+f.l  == \x -> (f x).l         // functions
+
+
+

Thus, if we have a sequence of tuples, xs, then we can quickly obtain a +sequence with only the tuples’ first components by writing xs.0.

+

Similarly, if we have a function, f, that computes a tuple of results, +then we can write f.0 to get a function that computes only the first +entry in the tuple.

+

This behavior is quite handy when examining complex data at the REPL.

+
+
+

Updating Fields

+

The components of a record or a tuple may be updated using the following +notation:

+
// Example values
+r = { x = 15, y = 20 }      // a record
+t = (True,True)             // a tuple
+n = { pt = r, size = 100 }  // nested record
+
+// Setting fields
+{ r | x = 30 }          == { x = 30, y = 20 }
+{ t | 0 = False }       == (False,True)
+
+// Update relative to the old value
+{ r | x -> x + 5 }      == { x = 20, y = 20 }
+
+// Update a nested field
+{ n | pt.x = 10 }       == { pt = { x = 10, y = 20 }, size = 100 }
+{ n | pt.x -> x + 10 }  == { pt = { x = 25, y = 20 }, size = 100 }
+
+
+
+
+
+

Sequences

+

A sequence is a fixed-length collection of elements of the same type. +The type of a finite sequence of length n, with elements of type a +is [n] a. Often, a finite sequence of bits, [n] Bit, is called a +word. We may abbreviate the type [n] Bit as [n]. An infinite +sequence with elements of type a has type [inf] a, and [inf] is +an infinite stream of bits.

+
[e1,e2,e3]            // A sequence with three elements
+
+[t1 .. t2]            // Enumeration
+[t1 .. <t2]           // Enumeration (exclusive bound)
+[t1 .. t2 by n]       // Enumeration (stride)
+[t1 .. <t2 by n]      // Enumeration (stride, ex. bound)
+[t1 .. t2 down by n]  // Enumeration (downward stride)
+[t1 .. >t2 down by n] // Enumeration (downward stride, ex. bound)
+[t1, t2 .. t3]        // Enumeration (step by t2 - t1)
+
+[e1 ...]              // Infinite sequence starting at e1
+[e1, e2 ...]          // Infinite sequence stepping by e2-e1
+
+[ e | p11 <- e11, p12 <- e12    // Sequence comprehensions
+    | p21 <- e21, p22 <- e22 ]
+
+x = generate (\i -> e)    // Sequence from generating function
+x @ i = e                 // Sequence with index binding
+arr @ i @ j = e           // Two-dimensional sequence
+
+
+

Note: the bounds in finite sequences (those with ..) are type +expressions, while the bounds in infinite sequences are value +expressions.

+ + ++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Sequence operations.
OperatorDescription
#Sequence concatenation
>> <<Shift (right, left)
>>> <<<Rotate (right, left)
>>$Arithmetic right shift (on bitvectors only)
@ !Access elements (front, back)
@@ !!Access sub-sequence (front, back)
update updateEndUpdate the value of a sequence at +a location +(front, back)
updates updatesEndUpdate multiple values of a sequence +(front, back)
+

There are also lifted pointwise operations.

+
[p1, p2, p3, p4]          // Sequence pattern
+p1 # p2                   // Split sequence pattern
+
+
+
+
+

Functions

+
\p1 p2 -> e              // Lambda expression
+f p1 p2 = e              // Function definition
+
+
+
+
+
+

Overloaded Operations

+
+

Equality

+
Eq
+  (==)        : {a}    (Eq a) => a -> a -> Bit
+  (!=)        : {a}    (Eq a) => a -> a -> Bit
+  (===)       : {a, b} (Eq b) => (a -> b) -> (a -> b) -> (a -> Bit)
+  (!==)       : {a, b} (Eq b) => (a -> b) -> (a -> b) -> (a -> Bit)
+
+
+
+
+

Comparisons

+
Cmp
+  (<)         : {a} (Cmp a) => a -> a -> Bit
+  (>)         : {a} (Cmp a) => a -> a -> Bit
+  (<=)        : {a} (Cmp a) => a -> a -> Bit
+  (>=)        : {a} (Cmp a) => a -> a -> Bit
+  min         : {a} (Cmp a) => a -> a -> a
+  max         : {a} (Cmp a) => a -> a -> a
+  abs         : {a} (Cmp a, Ring a) => a -> a
+
+
+
+
+

Signed Comparisons

+
SignedCmp
+  (<$)        : {a} (SignedCmp a) => a -> a -> Bit
+  (>$)        : {a} (SignedCmp a) => a -> a -> Bit
+  (<=$)       : {a} (SignedCmp a) => a -> a -> Bit
+  (>=$)       : {a} (SignedCmp a) => a -> a -> Bit
+
+
+
+
+

Zero

+
Zero
+  zero        : {a} (Zero a) => a
+
+
+
+
+

Logical Operations

+
Logic
+  (&&)        : {a} (Logic a) => a -> a -> a
+  (||)        : {a} (Logic a) => a -> a -> a
+  (^)         : {a} (Logic a) => a -> a -> a
+  complement  : {a} (Logic a) => a -> a
+
+
+
+
+

Basic Arithmetic

+
Ring
+  fromInteger : {a} (Ring a) => Integer -> a
+  (+)         : {a} (Ring a) => a -> a -> a
+  (-)         : {a} (Ring a) => a -> a -> a
+  (*)         : {a} (Ring a) => a -> a -> a
+  negate      : {a} (Ring a) => a -> a
+  (^^)        : {a, e} (Ring a, Integral e) => a -> e -> a
+
+
+
+
+

Integral Operations

+
Integral
+  (/)         : {a} (Integral a) => a -> a -> a
+  (%)         : {a} (Integral a) => a -> a -> a
+  (^^)        : {a, e} (Ring a, Integral e) => a -> e -> a
+  toInteger   : {a} (Integral a) => a -> Integer
+  infFrom     : {a} (Integral a) => a -> [inf]a
+  infFromThen : {a} (Integral a) => a -> a -> [inf]a
+
+
+
+
+

Division

+
Field
+  recip       : {a} (Field a) => a -> a
+  (/.)        : {a} (Field a) => a -> a -> a
+
+
+
+
+

Rounding

+
Round
+  ceiling     : {a} (Round a) => a -> Integer
+  floor       : {a} (Round a) => a -> Integer
+  trunc       : {a} (Round a) => a -> Integer
+  roundAway   : {a} (Round a) => a -> Integer
+  roundToEven : {a} (Round a) => a -> Integer
+
+
+
+
+
+

Type Declarations

+
+

Type Synonyms

+
type T a b = [a] b
+
+
+

A type declaration creates a synonym for a +pre-existing type expression, which may optionally have +arguments. A type synonym is transparently unfolded at +use sites and is treated as though the user had instead +written the body of the type synonym in line. +Type synonyms may mention other synonyms, but it is not +allowed to create a recursive collection of type synonyms.

+
+
+

Newtypes

+
newtype NewT a b = { seq : [a]b }
+
+
+

A newtype declaration declares a new named type which is defined by +a record body. Unlike type synonyms, each named newtype is treated +as a distinct type by the type checker, even if they have the same +bodies. Moreover, types created by a newtype declaration will not be +members of any typeclasses, even if the record defining their body +would be. For the purposes of typechecking, two newtypes are +considered equal only if all their arguments are equal, even if the +arguments do not appear in the body of the newtype, or are otherwise +irrelevant. Just like type synonyms, newtypes are not allowed to form +recursive groups.

+

Every newtype declaration brings into scope a new function with the +same name as the type which can be used to create values of the +newtype.

+
x : NewT 3 Integer
+x = NewT { seq = [1,2,3] }
+
+
+

Just as with records, field projections can be used directly on values +of newtypes to extract the values in the body of the type.

+
> sum x.seq
+6
+
+
+
+
+
+

Modules

+

A module is used to group some related definitions. Each file may +contain at most one top-level module.

+
module M where
+
+type T = [8]
+
+f : [8]
+f = 10
+
+
+
+

Hierarchical Module Names

+

Module may have either simple or hierarchical names. +Hierarchical names are constructed by gluing together ordinary +identifiers using the symbol ::.

+
module Hash::SHA256 where
+
+sha256 = ...
+
+
+

The structure in the name may be used to group together related +modules. Also, the Cryptol implementation uses the structure of the +name to locate the file containing the definition of the module. +For example, when searching for module Hash::SHA256, Cryptol +will look for a file named SHA256.cry in a directory called +Hash, contained in one of the directories specified by CRYPTOLPATH.

+
+
+

Module Imports

+

To use the definitions from one module in another module, we use +import declarations:

+
+
module M
+
// Provide some definitions
+module M where
+
+f : [8]
+f = 2
+
+
+
+
+
module N
+
// Uses definitions from `M`
+module N where
+
+import M  // import all definitions from `M`
+
+g = f   // `f` was imported from `M`
+
+
+
+
+

Import Lists

+

Sometimes, we may want to import only some of the definitions +from a module. To do so, we use an import declaration with +an import list.

+
module M where
+
+f = 0x02
+g = 0x03
+h = 0x04
+
+
+
module N where
+
+import M(f,g)  // Imports only `f` and `g`, but not `h`
+
+x = f + g
+
+
+

Using explicit import lists helps reduce name collisions. +It also tends to make code easier to understand, because +it makes it easy to see the source of definitions.

+
+
+

Hiding Imports

+

Sometimes a module may provide many definitions, and we want to use +most of them but with a few exceptions (e.g., because those would +result to a name clash). In such situations it is convenient +to use a hiding import:

+
+
module M
+
module M where
+
+f = 0x02
+g = 0x03
+h = 0x04
+
+
+
+
+
module N
+
module N where
+
+import M hiding (h) // Import everything but `h`
+
+x = f + g
+
+
+
+
+
+

Qualified Module Imports

+

Another way to avoid name collisions is by using a +qualified import.

+
+
module M
+
module M where
+
+f : [8]
+f = 2
+
+
+
+
+
module N
+
module N where
+
+import M as P
+
+g = P::f
+// `f` was imported from `M`
+// but when used it needs to be prefixed by the qualifier `P`
+
+
+
+

Qualified imports make it possible to work with definitions +that happen to have the same name but are defined in different modules.

+

Qualified imports may be combined with import lists or hiding clauses:

+
+
Example
+
import A as B (f)         // introduces B::f
+import X as Y hiding (f)  // introduces everything but `f` from X
+                          // using the prefix `X`
+
+
+
+

It is also possible to use the same qualifier prefix for imports +from different modules. For example:

+
+
Example
+
import A as B
+import X as B
+
+
+
+

Such declarations will introduces all definitions from A and X +but to use them, you would have to qualify using the prefix B::.

+
+
+
+

Private Blocks

+

In some cases, definitions in a module might use helper +functions that are not intended to be used outside the module. +It is good practice to place such declarations in private blocks:

+
+
Private blocks
+
module M where
+
+f : [8]
+f = 0x01 + helper1 + helper2
+
+private
+
+  helper1 : [8]
+  helper1 = 2
+
+  helper2 : [8]
+  helper2 = 3
+
+
+
+

The private block only needs to be indented if it might be followed by +additional public declarations. If all remaining declarations are to be +private then no additional indentation is needed as the private block will +extend to the end of the module.

+
+
Private blocks
+
module M where
+
+f : [8]
+f = 0x01 + helper1 + helper2
+
+private
+
+helper1 : [8]
+helper1 = 2
+
+helper2 : [8]
+helper2 = 3
+
+
+
+

The keyword private introduces a new layout scope, and all declarations +in the block are considered to be private to the module. A single module +may contain multiple private blocks. For example, the following module +is equivalent to the previous one:

+
+
Private blocks
+
module M where
+
+f : [8]
+f = 0x01 + helper1 + helper2
+
+private
+  helper1 : [8]
+  helper1 = 2
+
+private
+  helper2 : [8]
+  helper2 = 3
+
+
+
+
+
+

Parameterized Modules

+
+

Warning

+

This section documents the current design, but we are in the process of +redesigning some aspects of the parameterized modules mechanism.

+
+
module M where
+
+parameter
+  type n : #              // `n` is a numeric type parameter
+
+  type constraint (fin n, n >= 1)
+    // Assumptions about the parameter
+
+  x : [n]                 // A value parameter
+
+// This definition uses the parameters.
+f : [n]
+f = 1 + x
+
+
+
+

Named Module Instantiations

+

One way to use a parameterized module is through a named instantiation:

+
// A parameterized module
+module M where
+
+parameter
+  type n : #
+  x      : [n]
+  y      : [n]
+
+f : [n]
+f = x + y
+
+
+// A module instantiation
+module N = M where
+
+type n = 32
+x      = 11
+y      = helper
+
+helper = 12
+
+
+

The second module, N, is computed by instantiating the parameterized +module M. Module N will provide the exact same definitions as M, +except that the parameters will be replaced by the values in the body +of N. In this example, N provides just a single definition, f.

+

Note that the only purpose of the body of N (the declarations +after the where keyword) is to define the parameters for M.

+
+
+

Parameterized Instantiations

+

It is possible for a module instantiation to be itself parameterized. +This could be useful if we need to define some of a module’s parameters +but not others.

+
// A parameterized module
+module M where
+
+parameter
+  type n : #
+  x      : [n]
+  y      : [n]
+
+f : [n]
+f = x + y
+
+
+// A parameterized instantiation
+module N = M where
+
+parameter
+  x : [32]
+
+type n = 32
+y      = helper
+
+helper = 12
+
+
+

In this case N has a single parameter x. The result of instantiating +N would result in instantiating M using the value of x and 12 +for the value of y.

+
+
+

Importing Parameterized Modules

+

It is also possible to import a parameterized module without using +a module instantiation:

+
module M where
+
+parameter
+  x : [8]
+  y : [8]
+
+f : [8]
+f = x + y
+
+
+
module N where
+
+import `M
+
+g = f { x = 2, y = 3 }
+
+
+

A backtick at the start of the name of an imported module indicates +that we are importing a parameterized module. In this case, Cryptol +will import all definitions from the module as usual, however every +definition will have some additional parameters corresponding to +the parameters of a module. All value parameters are grouped in a record.

+

This is why in the example f is applied to a record of values, +even though its definition in M does not look like a function.

+
+
+
+
+ + +
+ +
+
+ +
+ +
+

+ © Copyright 2021, The Cryptol Team. + +

+
+ + + + Built with Sphinx using a + + theme + + provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + \ No newline at end of file diff --git a/docs/RefMan/_build/html/_sources/RefMan.rst.txt b/docs/RefMan/_build/html/_sources/RefMan.rst.txt new file mode 100644 index 00000000..dd9837d3 --- /dev/null +++ b/docs/RefMan/_build/html/_sources/RefMan.rst.txt @@ -0,0 +1,1248 @@ +######################## +Cryptol Reference Manual +######################## + + +.. toctree:: + :maxdepth: 3 + :caption: Contents: + + + +******************************************************************************** +Basic Syntax +******************************************************************************** + + +Declarations +============ + +.. code-block:: cryptol + + f x = x + y + z + + +Type Signatures +--------------- + +.. code-block:: cryptol + + f,g : {a,b} (fin a) => [a] b + + + +Layout +====== + +Groups of declarations are organized based on indentation. +Declarations with the same indentation belong to the same group. +Lines of text that are indented more than the beginning of a +declaration belong to that declaration, while lines of text that are +indented less terminate a group of declarations. Consider, for example, +the following Cryptol declarations: + +.. code-block:: cryptol + + f x = x + y + z + where + y = x * x + z = x + y + + g y = y + +This group has two declarations, one for `f` and one for `g`. All the +lines between `f` and `g` that are indented more than `f` belong to +`f`. The same principle applies to the declarations in the ``where`` block +of `f`, which defines two more local names, `y` and `z`. + + + +Comments +======== + +Cryptol supports block comments, which start with ``/*`` and end with +``*/``, and line comments, which start with ``//`` and terminate at the +end of the line. Block comments may be nested arbitrarily. + +.. code-block:: cryptol + + /* This is a block comment */ + // This is a line comment + /* This is a /* Nested */ block comment */ + +.. todo:: + Document ``/** */`` + + +Identifiers +=========== + +Cryptol identifiers consist of one or more characters. The first +character must be either an English letter or underscore (``_``). The +following characters may be an English letter, a decimal digit, +underscore (``_``), or a prime (``'``). Some identifiers have special +meaning in the language, so they may not be used in programmer-defined +names (see `Keywords and Built-in Operators`_). + +.. code-block:: cryptol + :caption: Examples of identifiers + + name name1 name' longer_name + Name Name2 Name'' longerName + + + +Keywords and Built-in Operators +=============================== + +The following identifiers have special meanings in Cryptol, and may +not be used for programmer defined names: + +.. The table below can be generated by running `chop.hs` on this list: + else + extern + if + private + include + module + newtype + pragma + property + then + type + where + let + import + as + hiding + infixl + infixr + infix + primitive + parameter + constraint + down + by +.. _Keywords: + +.. code-block:: none + :caption: Keywords + + else include property let infixl parameter + extern module then import infixr constraint + if newtype type as infix down + private pragma where hiding primitive by + + +The following table contains Cryptol's operators and their +associativity with lowest precedence operators first, and highest +precedence last. + +.. table:: Operator precedences + + +-----------------------------------------+-----------------+ + | Operator | Associativity | + +=========================================+=================+ + | ``==>`` | right | + +-----------------------------------------+-----------------+ + | ``\/`` | right | + +-----------------------------------------+-----------------+ + | ``/\`` | right | + +-----------------------------------------+-----------------+ + | ``==`` ``!=`` ``===`` ``!==`` | not associative | + +-----------------------------------------+-----------------+ + | ``>`` ``<`` ``<=`` ``>=`` | not associative | + | ``<$`` ``>$`` ``<=$`` ``>=$`` | | + +-----------------------------------------+-----------------+ + | ``||`` | right | + +-----------------------------------------+-----------------+ + | ``^`` | left | + +-----------------------------------------+-----------------+ + | ``&&`` | right | + +-----------------------------------------+-----------------+ + | ``#`` | right | + +-----------------------------------------+-----------------+ + | ``>>`` ``<<`` ``>>>`` ``<<<`` ``>>$`` | left | + +-----------------------------------------+-----------------+ + | ``+`` ``-`` | left | + +-----------------------------------------+-----------------+ + | ``*`` ``/`` ``%`` ``/$`` ``%$`` | left | + +-----------------------------------------+-----------------+ + | ``^^`` | right | + +-----------------------------------------+-----------------+ + | ``@`` ``@@`` ``!`` ``!!`` | left | + +-----------------------------------------+-----------------+ + | (unary) ``-`` ``~`` | right | + +-----------------------------------------+-----------------+ + + +Built-in Type-level Operators +============================= + +Cryptol includes a variety of operators that allow computations on +the numeric types used to specify the sizes of sequences. + +.. table:: Type-level operators + + +------------+----------------------------------------+ + | Operator | Meaning | + +============+========================================+ + | ``+`` | Addition | + +------------+----------------------------------------+ + | ``-`` | Subtraction | + +------------+----------------------------------------+ + | ``*`` | Multiplication | + +------------+----------------------------------------+ + | ``/`` | Division | + +------------+----------------------------------------+ + | ``/^`` | Ceiling division (``/`` rounded up) | + +------------+----------------------------------------+ + | ``%`` | Modulus | + +------------+----------------------------------------+ + | ``%^`` | Ceiling modulus (compute padding) | + +------------+----------------------------------------+ + | ``^^`` | Exponentiation | + +------------+----------------------------------------+ + | ``lg2`` | Ceiling logarithm (base 2) | + +------------+----------------------------------------+ + | ``width`` | Bit width (equal to ``lg2(n+1)``) | + +------------+----------------------------------------+ + | ``max`` | Maximum | + +------------+----------------------------------------+ + | ``min`` | Minimum | + +------------+----------------------------------------+ + +Numeric Literals +================ + +Numeric literals may be written in binary, octal, decimal, or +hexadecimal notation. The base of a literal is determined by its prefix: +``0b`` for binary, ``0o`` for octal, no special prefix for +decimal, and ``0x`` for hexadecimal. + +.. code-block:: cryptol + :caption: Examples of literals + + 254 // Decimal literal + 0254 // Decimal literal + 0b11111110 // Binary literal + 0o376 // Octal literal + 0xFE // Hexadecimal literal + 0xfe // Hexadecimal literal + +Numeric literals in binary, octal, or hexadecimal notation result in +bit sequences of a fixed length (i.e., they have type ``[n]`` for +some `n`). The length is determined by the base and the number +of digits in the literal. Decimal literals are overloaded, and so the +type is inferred from context in which the literal is used. Examples: + +.. code-block:: cryptol + :caption: Literals and their types + + 0b1010 // : [4], 1 * number of digits + 0o1234 // : [12], 3 * number of digits + 0x1234 // : [16], 4 * number of digits + + 10 // : {a}. (Literal 10 a) => a + // a = Integer or [n] where n >= width 10 + +Numeric literals may also be written as polynomials by writing a polynomial +expression in terms of `x` between an opening ``<|`` and a closing ``|>``. +Numeric literals in polynomial notation result in bit sequences of length +one more than the degree of the polynomial. Examples: + +.. code-block:: cryptol + :caption: Polynomial literals + + <| x^^6 + x^^4 + x^^2 + x^^1 + 1 |> // : [7], equal to 0b1010111 + <| x^^4 + x^^3 + x |> // : [5], equal to 0b11010 + +Cryptol also supports fractional literals using binary (prefix ``0b``), +octal (prefix ``0o``), decimal (no prefix), and hexadecimal (prefix ``ox``) +digits. A fractional literal must contain a ``.`` and may optionally +have an exponent. The base of the exponent for binary, octal, +and hexadecimal literals is 2 and the exponent is marked using the symbol ``p``. +Decimal fractional literals use exponent base 10, and the symbol ``e``. +Examples: + +.. code-block:: cryptol + :caption: Fractional literals + + 10.2 + 10.2e3 // 10.2 * 10^3 + 0x30.1 // 3 * 64 + 1/16 + 0x30.1p4 // (3 * 64 + 1/16) * 2^4 + +All fractional literals are overloaded and may be used with types that support +fractional numbers (e.g., ``Rational``, and the ``Float`` family of types). + +Some types (e.g. the ``Float`` family) cannot represent all fractional literals +precisely. Such literals are rejected statically when using binary, octal, +or hexadecimal notation. When using decimal notation, the literal is rounded +to the closest representable even number. + + +All numeric literals may also include ``_``, which has no effect on the +literal value but may be used to improve readability. Here are some examples: + +.. code-block:: cryptol + :caption: Using _ + + 0b_0000_0010 + 0x_FFFF_FFEA + + + +******************************************************************************** +Expressions +******************************************************************************** + +This section provides an overview of the Cryptol's expression syntax. + +Calling Functions +================= + +.. code-block:: cryptol + + f 2 // call `f` with parameter `2` + g x y // call `g` with two parameters: `x` and `y` + h (x,y) // call `h` with one parameter, the pair `(x,y)` + + +Prefix Operators +================ + + +.. code-block:: cryptol + + -2 // call unary `-` with parameter `2` + - 2 // call unary `-` with parameter `2` + f (-2) // call `f` with one argument: `-2`, parens are important + -f 2 // call unary `-` with parameter `f 2` + - f 2 // call unary `-` with parameter `f 2` + + +Infix Functions +=============== + + +.. code-block:: cryptol + + 2 + 3 // call `+` with two parameters: `2` and `3` + 2 + 3 * 5 // call `+` with two parameters: `2` and `3 * 5` + (+) 2 3 // call `+` with two parameters: `2` and `3` + f 2 + g 3 // call `+` with two parameters: `f 2` and `g 3` + - 2 + - 3 // call `+` with two parameters: `-2` and `-3` + - f 2 + - g 3 + +Type Annotations +================ + +Explicit type annotations may be added on expressions, patterns, and +in argument definitions. + +.. code-block:: cryptol + + x : Bit // specify that `x` has type `Bit` + f x : Bit // specify that `f x` has type `Bit` + - f x : [8] // specify that `- f x` has type `[8]` + 2 + 3 : [8] // specify that `2 + 3` has type `[8]` + \x -> x : [8] // type annotation is on `x`, not the function + if x + then y + else z : Bit // the type annotation is on `z`, not the whole `if` + [1..9 : [8]] // specify that elements in `[1..9]` have type `[8]` + + f (x : [8]) = x + 1 // type annotation on patterns + +.. todo:: + Patterns with type variables + + + +Explicit Type Instantiation +=========================== + +If ``f`` is a polymorphic value with type: + +.. code-block:: cryptol + + f : { tyParam } tyParam + f = zero + +you can evaluate ``f``, passing it a type parameter: + +.. code-block:: cryptol + + f `{ tyParam = 13 } + + + + +Local Declarations +================== + +Local declarations have the weakest precedence of all expressions. + +.. code-block:: cryptol + + 2 + x : [T] + where + type T = 8 + x = 2 // `T` and `x` are in scope of `2 + x : `[T]` + + if x then 1 else 2 + where x = 2 // `x` is in scope in the whole `if` + + \y -> x + y + where x = 2 // `y` is not in scope in the defintion of `x` + + +Block Arguments +--------------- + +When used as the last argument to a function call, +``if`` and lambda expressions do not need parens: + +.. code-block:: cryptol + + f \x -> x // call `f` with one argument `x -> x` + 2 + if x + then y + else z // call `+` with two arguments: `2` and `if ...` + + +Conditionals +------------ + +The ``if ... then ... else`` construct can be used with +multiple branches. For example: + +.. code-block:: cryptol + + x = if y % 2 == 0 then 22 else 33 + + x = if y % 2 == 0 then 1 + | y % 3 == 0 then 2 + | y % 5 == 0 then 3 + else 7 + + +Demoting Numeric Types to Values +-------------------------------- + +The value corresponding to a numeric type may be accessed using the +following notation: + +.. code-block:: cryptol + + `t + +Here `t` should be a finite type expression with numeric kind. The resulting +expression will be of a numeric base type, which is sufficiently large +to accommodate the value of the type: + +.. code-block:: cryptol + + `t : {a} (Literal t a) => a + +This backtick notation is syntax sugar for an application of the +`number` primtive, so the above may be written as: + +.. code-block:: cryptol + + number`{t} : {a} (Literal t a) => a + +If a type cannot be inferred from context, a suitable type will be +automatically chosen if possible, usually `Integer`. + + + +******************************************************************************** +Basic Types +******************************************************************************** + + +Bits +==== + +The type ``Bit`` has two inhabitants: ``True`` and ``False``. These values +may be combined using various logical operators, or constructed as +results of comparisons. + +.. table:: Bit operations. + + +--------------------------+---------------+------------------------+ + | Operator | Associativity | Description | + +--------------------------+---------------+------------------------+ + | ``==>`` | right | Short-cut implication | + +--------------------------+---------------+------------------------+ + | ``\/`` | right | Short-cut or | + +--------------------------+---------------+------------------------+ + | ``/\`` | right | Short-cut and | + +--------------------------+---------------+------------------------+ + | `!=` `==` | none | Not equals, equals | + +--------------------------+---------------+------------------------+ + | ``>`` ``<`` ``<=`` ``>=``| none | Comparisons; | + | ``<$`` ``>$`` | | $ indicates signed | + | ``<=$`` ``>=$`` | | | + +--------------------------+---------------+------------------------+ + | `||` | right | Logical or | + +--------------------------+---------------+------------------------+ + | `^` | left | Exclusive-or | + +--------------------------+---------------+------------------------+ + | `&&` | right | Logical and | + +--------------------------+---------------+------------------------+ + | `~` | right | Logical negation | + +--------------------------+---------------+------------------------+ + + +Tuples and Records +================== + +Tuples and records are used for packaging multiple values together. +Tuples are enclosed in parentheses, while records are enclosed in +curly braces. The components of both tuples and records are separated by +commas. The components of tuples are expressions, while the +components of records are a label and a value separated by an equal +sign. Examples: + +.. code-block:: cryptol + + (1,2,3) // A tuple with 3 component + () // A tuple with no components + + { x = 1, y = 2 } // A record with two fields, `x` and `y` + {} // A record with no fields + +The components of tuples are identified by position, while the +components of records are identified by their label, and so the +ordering of record components is not important for most purposes. +Examples: + +.. code-block:: cryptol + + (1,2) == (1,2) // True + (1,2) == (2,1) // False + + { x = 1, y = 2 } == { x = 1, y = 2 } // True + { x = 1, y = 2 } == { y = 2, x = 1 } // True + +Ordering on tuples and records is defined lexicographically. Tuple +components are compared in the order they appear, whereas record +fields are compared in alphabetical order of field names. + +Accessing Fields +---------------- + +The components of a record or a tuple may be accessed in two ways: via +pattern matching or by using explicit component selectors. Explicit +component selectors are written as follows: + +.. code-block:: cryptol + + (15, 20).0 == 15 + (15, 20).1 == 20 + + { x = 15, y = 20 }.x == 15 + +Explicit record selectors may be used only if the program contains +sufficient type information to determine the shape of the tuple or +record. For example: + +.. code-block:: cryptol + + type T = { sign : Bit, number : [15] } + + // Valid definition: + // the type of the record is known. + isPositive : T -> Bit + isPositive x = x.sign + + // Invalid definition: + // insufficient type information. + badDef x = x.f + +The components of a tuple or a record may also be accessed using +pattern matching. Patterns for tuples and records mirror the syntax +for constructing values: tuple patterns use parentheses, while record +patterns use braces. Examples: + +.. code-block:: cryptol + + getFst (x,_) = x + + distance2 { x = xPos, y = yPos } = xPos ^^ 2 + yPos ^^ 2 + + f p = x + y where + (x, y) = p + +Selectors are also lifted through sequence and function types, point-wise, +so that the following equations should hold: + +.. code-block:: cryptol + + xs.l == [ x.l | x <- xs ] // sequences + f.l == \x -> (f x).l // functions + +Thus, if we have a sequence of tuples, ``xs``, then we can quickly obtain a +sequence with only the tuples' first components by writing ``xs.0``. + +Similarly, if we have a function, ``f``, that computes a tuple of results, +then we can write ``f.0`` to get a function that computes only the first +entry in the tuple. + +This behavior is quite handy when examining complex data at the REPL. + + + + +Updating Fields +--------------- + +The components of a record or a tuple may be updated using the following +notation: + +.. code-block:: cryptol + + // Example values + r = { x = 15, y = 20 } // a record + t = (True,True) // a tuple + n = { pt = r, size = 100 } // nested record + + // Setting fields + { r | x = 30 } == { x = 30, y = 20 } + { t | 0 = False } == (False,True) + + // Update relative to the old value + { r | x -> x + 5 } == { x = 20, y = 20 } + + // Update a nested field + { n | pt.x = 10 } == { pt = { x = 10, y = 20 }, size = 100 } + { n | pt.x -> x + 10 } == { pt = { x = 25, y = 20 }, size = 100 } + + +Sequences +========= + +A sequence is a fixed-length collection of elements of the same type. +The type of a finite sequence of length `n`, with elements of type `a` +is ``[n] a``. Often, a finite sequence of bits, ``[n] Bit``, is called a +*word*. We may abbreviate the type ``[n] Bit`` as ``[n]``. An infinite +sequence with elements of type `a` has type ``[inf] a``, and ``[inf]`` is +an infinite stream of bits. + +.. code-block:: cryptol + + [e1,e2,e3] // A sequence with three elements + + [t1 .. t2] // Enumeration + [t1 .. t2 down by n] // Enumeration (downward stride, ex. bound) + [t1, t2 .. t3] // Enumeration (step by t2 - t1) + + [e1 ...] // Infinite sequence starting at e1 + [e1, e2 ...] // Infinite sequence stepping by e2-e1 + + [ e | p11 <- e11, p12 <- e12 // Sequence comprehensions + | p21 <- e21, p22 <- e22 ] + + x = generate (\i -> e) // Sequence from generating function + x @ i = e // Sequence with index binding + arr @ i @ j = e // Two-dimensional sequence + +Note: the bounds in finite sequences (those with `..`) are type +expressions, while the bounds in infinite sequences are value +expressions. + +.. table:: Sequence operations. + + +------------------------------+---------------------------------------------+ + | Operator | Description | + +==============================+=============================================+ + | ``#`` | Sequence concatenation | + +------------------------------+---------------------------------------------+ + | ``>>`` ``<<`` | Shift (right, left) | + +------------------------------+---------------------------------------------+ + | ``>>>`` ``<<<`` | Rotate (right, left) | + +------------------------------+---------------------------------------------+ + | ``>>$`` | Arithmetic right shift (on bitvectors only) | + +------------------------------+---------------------------------------------+ + | ``@`` ``!`` | Access elements (front, back) | + +------------------------------+---------------------------------------------+ + | ``@@`` ``!!`` | Access sub-sequence (front, back) | + +------------------------------+---------------------------------------------+ + | ``update`` ``updateEnd`` | Update the value of a sequence at | + | | a location | + | | (front, back) | + +------------------------------+---------------------------------------------+ + | ``updates`` ``updatesEnd`` | Update multiple values of a sequence | + | | (front, back) | + +------------------------------+---------------------------------------------+ + + +There are also lifted pointwise operations. + +.. code-block:: cryptol + + [p1, p2, p3, p4] // Sequence pattern + p1 # p2 // Split sequence pattern + + +Functions +========= + +.. code-block:: cryptol + + \p1 p2 -> e // Lambda expression + f p1 p2 = e // Function definition + + + +******************************************************************************** +Overloaded Operations +******************************************************************************** + +Equality +======== + +.. code-block:: cryptol + + Eq + (==) : {a} (Eq a) => a -> a -> Bit + (!=) : {a} (Eq a) => a -> a -> Bit + (===) : {a, b} (Eq b) => (a -> b) -> (a -> b) -> (a -> Bit) + (!==) : {a, b} (Eq b) => (a -> b) -> (a -> b) -> (a -> Bit) + +Comparisons +=========== + +.. code-block:: cryptol + + Cmp + (<) : {a} (Cmp a) => a -> a -> Bit + (>) : {a} (Cmp a) => a -> a -> Bit + (<=) : {a} (Cmp a) => a -> a -> Bit + (>=) : {a} (Cmp a) => a -> a -> Bit + min : {a} (Cmp a) => a -> a -> a + max : {a} (Cmp a) => a -> a -> a + abs : {a} (Cmp a, Ring a) => a -> a + + +Signed Comparisons +================== + +.. code-block:: cryptol + + SignedCmp + (<$) : {a} (SignedCmp a) => a -> a -> Bit + (>$) : {a} (SignedCmp a) => a -> a -> Bit + (<=$) : {a} (SignedCmp a) => a -> a -> Bit + (>=$) : {a} (SignedCmp a) => a -> a -> Bit + + +Zero +==== + +.. code-block:: cryptol + + Zero + zero : {a} (Zero a) => a + +Logical Operations +================== + +.. code-block:: cryptol + + Logic + (&&) : {a} (Logic a) => a -> a -> a + (||) : {a} (Logic a) => a -> a -> a + (^) : {a} (Logic a) => a -> a -> a + complement : {a} (Logic a) => a -> a + +Basic Arithmetic +================ + +.. code-block:: cryptol + + Ring + fromInteger : {a} (Ring a) => Integer -> a + (+) : {a} (Ring a) => a -> a -> a + (-) : {a} (Ring a) => a -> a -> a + (*) : {a} (Ring a) => a -> a -> a + negate : {a} (Ring a) => a -> a + (^^) : {a, e} (Ring a, Integral e) => a -> e -> a + +Integral Operations +=================== + +.. code-block:: cryptol + + Integral + (/) : {a} (Integral a) => a -> a -> a + (%) : {a} (Integral a) => a -> a -> a + (^^) : {a, e} (Ring a, Integral e) => a -> e -> a + toInteger : {a} (Integral a) => a -> Integer + infFrom : {a} (Integral a) => a -> [inf]a + infFromThen : {a} (Integral a) => a -> a -> [inf]a + + +Division +======== + +.. code-block:: cryptol + + Field + recip : {a} (Field a) => a -> a + (/.) : {a} (Field a) => a -> a -> a + +Rounding +======== + +.. code-block:: cryptol + + Round + ceiling : {a} (Round a) => a -> Integer + floor : {a} (Round a) => a -> Integer + trunc : {a} (Round a) => a -> Integer + roundAway : {a} (Round a) => a -> Integer + roundToEven : {a} (Round a) => a -> Integer + + + + +******************************************************************************** +Type Declarations +******************************************************************************** + +Type Synonyms +============= + +.. code-block:: cryptol + + type T a b = [a] b + +A ``type`` declaration creates a synonym for a +pre-existing type expression, which may optionally have +arguments. A type synonym is transparently unfolded at +use sites and is treated as though the user had instead +written the body of the type synonym in line. +Type synonyms may mention other synonyms, but it is not +allowed to create a recursive collection of type synonyms. + +Newtypes +======== + +.. code-block:: cryptol + + newtype NewT a b = { seq : [a]b } + +A ``newtype`` declaration declares a new named type which is defined by +a record body. Unlike type synonyms, each named ``newtype`` is treated +as a distinct type by the type checker, even if they have the same +bodies. Moreover, types created by a ``newtype`` declaration will not be +members of any typeclasses, even if the record defining their body +would be. For the purposes of typechecking, two newtypes are +considered equal only if all their arguments are equal, even if the +arguments do not appear in the body of the newtype, or are otherwise +irrelevant. Just like type synonyms, newtypes are not allowed to form +recursive groups. + +Every ``newtype`` declaration brings into scope a new function with the +same name as the type which can be used to create values of the +newtype. + +.. code-block:: cryptol + + x : NewT 3 Integer + x = NewT { seq = [1,2,3] } + +Just as with records, field projections can be used directly on values +of newtypes to extract the values in the body of the type. + +.. code-block:: none + + > sum x.seq + 6 + + +******************************************************************************** +Modules +******************************************************************************** + +A *module* is used to group some related definitions. Each file may +contain at most one top-level module. + +.. code-block:: cryptol + + module M where + + type T = [8] + + f : [8] + f = 10 + + +Hierarchical Module Names +========================= + +Module may have either simple or *hierarchical* names. +Hierarchical names are constructed by gluing together ordinary +identifiers using the symbol ``::``. + +.. code-block:: cryptol + + module Hash::SHA256 where + + sha256 = ... + +The structure in the name may be used to group together related +modules. Also, the Cryptol implementation uses the structure of the +name to locate the file containing the definition of the module. +For example, when searching for module ``Hash::SHA256``, Cryptol +will look for a file named ``SHA256.cry`` in a directory called +``Hash``, contained in one of the directories specified by ``CRYPTOLPATH``. + + +Module Imports +============== + +To use the definitions from one module in another module, we use +``import`` declarations: + + +.. code-block:: cryptol + :caption: module M + + // Provide some definitions + module M where + + f : [8] + f = 2 + + +.. code-block:: cryptol + :caption: module N + + // Uses definitions from `M` + module N where + + import M // import all definitions from `M` + + g = f // `f` was imported from `M` + + +Import Lists +------------ + +Sometimes, we may want to import only some of the definitions +from a module. To do so, we use an import declaration with +an *import list*. + +.. code-block:: cryptol + + module M where + + f = 0x02 + g = 0x03 + h = 0x04 + +.. code-block:: cryptol + + module N where + + import M(f,g) // Imports only `f` and `g`, but not `h` + + x = f + g + +Using explicit import lists helps reduce name collisions. +It also tends to make code easier to understand, because +it makes it easy to see the source of definitions. + + +Hiding Imports +-------------- + +Sometimes a module may provide many definitions, and we want to use +most of them but with a few exceptions (e.g., because those would +result to a name clash). In such situations it is convenient +to use a *hiding* import: + +.. code-block:: cryptol + :caption: module M + + module M where + + f = 0x02 + g = 0x03 + h = 0x04 + + +.. code-block:: cryptol + :caption: module N + + module N where + + import M hiding (h) // Import everything but `h` + + x = f + g + + + +Qualified Module Imports +------------------------ + +Another way to avoid name collisions is by using a +*qualified* import. + +.. code-block:: cryptol + :caption: module M + + module M where + + f : [8] + f = 2 + + +.. code-block:: cryptol + :caption: module N + + module N where + + import M as P + + g = P::f + // `f` was imported from `M` + // but when used it needs to be prefixed by the qualifier `P` + +Qualified imports make it possible to work with definitions +that happen to have the same name but are defined in different modules. + +Qualified imports may be combined with import lists or hiding clauses: + +.. code-block:: cryptol + :caption: Example + + import A as B (f) // introduces B::f + import X as Y hiding (f) // introduces everything but `f` from X + // using the prefix `X` + +It is also possible to use the same qualifier prefix for imports +from different modules. For example: + +.. code-block:: cryptol + :caption: Example + + import A as B + import X as B + +Such declarations will introduces all definitions from ``A`` and ``X`` +but to use them, you would have to qualify using the prefix ``B::``. + + +Private Blocks +============== + +In some cases, definitions in a module might use helper +functions that are not intended to be used outside the module. +It is good practice to place such declarations in *private blocks*: + +.. code-block:: cryptol + :caption: Private blocks + + module M where + + f : [8] + f = 0x01 + helper1 + helper2 + + private + + helper1 : [8] + helper1 = 2 + + helper2 : [8] + helper2 = 3 + +The private block only needs to be indented if it might be followed by +additional public declarations. If all remaining declarations are to be +private then no additional indentation is needed as the `private` block will +extend to the end of the module. + +.. code-block:: cryptol + :caption: Private blocks + + module M where + + f : [8] + f = 0x01 + helper1 + helper2 + + private + + helper1 : [8] + helper1 = 2 + + helper2 : [8] + helper2 = 3 + + +The keyword ``private`` introduces a new layout scope, and all declarations +in the block are considered to be private to the module. A single module +may contain multiple private blocks. For example, the following module +is equivalent to the previous one: + +.. code-block:: cryptol + :caption: Private blocks + + module M where + + f : [8] + f = 0x01 + helper1 + helper2 + + private + helper1 : [8] + helper1 = 2 + + private + helper2 : [8] + helper2 = 3 + + + +Parameterized Modules +===================== + +.. warning:: + This section documents the current design, but we are in the process of + redesigning some aspects of the parameterized modules mechanism. + + +.. code-block:: cryptol + + module M where + + parameter + type n : # // `n` is a numeric type parameter + + type constraint (fin n, n >= 1) + // Assumptions about the parameter + + x : [n] // A value parameter + + // This definition uses the parameters. + f : [n] + f = 1 + x + + +Named Module Instantiations +--------------------------- + +One way to use a parameterized module is through a named instantiation: + +.. code-block:: cryptol + + // A parameterized module + module M where + + parameter + type n : # + x : [n] + y : [n] + + f : [n] + f = x + y + + + // A module instantiation + module N = M where + + type n = 32 + x = 11 + y = helper + + helper = 12 + +The second module, ``N``, is computed by instantiating the parameterized +module ``M``. Module ``N`` will provide the exact same definitions as ``M``, +except that the parameters will be replaced by the values in the body +of ``N``. In this example, ``N`` provides just a single definition, ``f``. + +Note that the only purpose of the body of ``N`` (the declarations +after the ``where`` keyword) is to define the parameters for ``M``. + + +Parameterized Instantiations +---------------------------- + +It is possible for a module instantiation to be itself parameterized. +This could be useful if we need to define some of a module's parameters +but not others. + +.. code-block:: cryptol + + // A parameterized module + module M where + + parameter + type n : # + x : [n] + y : [n] + + f : [n] + f = x + y + + + // A parameterized instantiation + module N = M where + + parameter + x : [32] + + type n = 32 + y = helper + + helper = 12 + +In this case ``N`` has a single parameter ``x``. The result of instantiating +``N`` would result in instantiating ``M`` using the value of ``x`` and ``12`` +for the value of ``y``. + + +Importing Parameterized Modules +------------------------------- + +It is also possible to import a parameterized module without using +a module instantiation: + +.. code-block:: cryptol + + module M where + + parameter + x : [8] + y : [8] + + f : [8] + f = x + y + +.. code-block:: cryptol + + module N where + + import `M + + g = f { x = 2, y = 3 } + +A *backtick* at the start of the name of an imported module indicates +that we are importing a parameterized module. In this case, Cryptol +will import all definitions from the module as usual, however every +definition will have some additional parameters corresponding to +the parameters of a module. All value parameters are grouped in a record. + +This is why in the example ``f`` is applied to a record of values, +even though its definition in ``M`` does not look like a function. + + + diff --git a/docs/RefMan/_build/html/_static/basic.css b/docs/RefMan/_build/html/_static/basic.css new file mode 100644 index 00000000..0807176e --- /dev/null +++ b/docs/RefMan/_build/html/_static/basic.css @@ -0,0 +1,676 @@ +/* + * basic.css + * ~~~~~~~~~ + * + * Sphinx stylesheet -- basic theme. + * + * :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/* -- main layout ----------------------------------------------------------- */ + +div.clearer { + clear: both; +} + +/* -- relbar ---------------------------------------------------------------- */ + +div.related { + width: 100%; + font-size: 90%; +} + +div.related h3 { + display: none; +} + +div.related ul { + margin: 0; + padding: 0 0 0 10px; + list-style: none; +} + +div.related li { + display: inline; +} + +div.related li.right { + float: right; + margin-right: 5px; +} + +/* -- sidebar --------------------------------------------------------------- */ + +div.sphinxsidebarwrapper { + padding: 10px 5px 0 10px; +} + +div.sphinxsidebar { + float: left; + width: 230px; + margin-left: -100%; + font-size: 90%; + word-wrap: break-word; + overflow-wrap : break-word; +} + +div.sphinxsidebar ul { + list-style: none; +} + +div.sphinxsidebar ul ul, +div.sphinxsidebar ul.want-points { + margin-left: 20px; + list-style: square; +} + +div.sphinxsidebar ul ul { + margin-top: 0; + margin-bottom: 0; +} + +div.sphinxsidebar form { + margin-top: 10px; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + +div.sphinxsidebar #searchbox form.search { + overflow: hidden; +} + +div.sphinxsidebar #searchbox input[type="text"] { + float: left; + width: 80%; + padding: 0.25em; + box-sizing: border-box; +} + +div.sphinxsidebar #searchbox input[type="submit"] { + float: left; + width: 20%; + border-left: none; + padding: 0.25em; + box-sizing: border-box; +} + + +img { + border: 0; + max-width: 100%; +} + +/* -- search page ----------------------------------------------------------- */ + +ul.search { + margin: 10px 0 0 20px; + padding: 0; +} + +ul.search li { + padding: 5px 0 5px 20px; + background-image: url(file.png); + background-repeat: no-repeat; + background-position: 0 7px; +} + +ul.search li a { + font-weight: bold; +} + +ul.search li div.context { + color: #888; + margin: 2px 0 0 30px; + text-align: left; +} + +ul.keywordmatches li.goodmatch a { + font-weight: bold; +} + +/* -- index page ------------------------------------------------------------ */ + +table.contentstable { + width: 90%; + margin-left: auto; + margin-right: auto; +} + +table.contentstable p.biglink { + line-height: 150%; +} + +a.biglink { + font-size: 1.3em; +} + +span.linkdescr { + font-style: italic; + padding-top: 5px; + font-size: 90%; +} + +/* -- general index --------------------------------------------------------- */ + +table.indextable { + width: 100%; +} + +table.indextable td { + text-align: left; + vertical-align: top; +} + +table.indextable ul { + margin-top: 0; + margin-bottom: 0; + list-style-type: none; +} + +table.indextable > tbody > tr > td > ul { + padding-left: 0em; +} + +table.indextable tr.pcap { + height: 10px; +} + +table.indextable tr.cap { + margin-top: 10px; + background-color: #f2f2f2; +} + +img.toggler { + margin-right: 3px; + margin-top: 3px; + cursor: pointer; +} + +div.modindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +div.genindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +/* -- domain module index --------------------------------------------------- */ + +table.modindextable td { + padding: 2px; + border-collapse: collapse; +} + +/* -- general body styles --------------------------------------------------- */ + +div.body { + min-width: 450px; + max-width: 800px; +} + +div.body p, div.body dd, div.body li, div.body blockquote { + -moz-hyphens: auto; + -ms-hyphens: auto; + -webkit-hyphens: auto; + hyphens: auto; +} + +a.headerlink { + visibility: hidden; +} + +h1:hover > a.headerlink, +h2:hover > a.headerlink, +h3:hover > a.headerlink, +h4:hover > a.headerlink, +h5:hover > a.headerlink, +h6:hover > a.headerlink, +dt:hover > a.headerlink, +caption:hover > a.headerlink, +p.caption:hover > a.headerlink, +div.code-block-caption:hover > a.headerlink { + visibility: visible; +} + +div.body p.caption { + text-align: inherit; +} + +div.body td { + text-align: left; +} + +.first { + margin-top: 0 !important; +} + +p.rubric { + margin-top: 30px; + font-weight: bold; +} + +img.align-left, .figure.align-left, object.align-left { + clear: left; + float: left; + margin-right: 1em; +} + +img.align-right, .figure.align-right, object.align-right { + clear: right; + float: right; + margin-left: 1em; +} + +img.align-center, .figure.align-center, object.align-center { + display: block; + margin-left: auto; + margin-right: auto; +} + +.align-left { + text-align: left; +} + +.align-center { + text-align: center; +} + +.align-right { + text-align: right; +} + +/* -- sidebars -------------------------------------------------------------- */ + +div.sidebar { + margin: 0 0 0.5em 1em; + border: 1px solid #ddb; + padding: 7px 7px 0 7px; + background-color: #ffe; + width: 40%; + float: right; +} + +p.sidebar-title { + font-weight: bold; +} + +/* -- topics ---------------------------------------------------------------- */ + +div.topic { + border: 1px solid #ccc; + padding: 7px 7px 0 7px; + margin: 10px 0 10px 0; +} + +p.topic-title { + font-size: 1.1em; + font-weight: bold; + margin-top: 10px; +} + +/* -- admonitions ----------------------------------------------------------- */ + +div.admonition { + margin-top: 10px; + margin-bottom: 10px; + padding: 7px; +} + +div.admonition dt { + font-weight: bold; +} + +div.admonition dl { + margin-bottom: 0; +} + +p.admonition-title { + margin: 0px 10px 5px 0px; + font-weight: bold; +} + +div.body p.centered { + text-align: center; + margin-top: 25px; +} + +/* -- tables ---------------------------------------------------------------- */ + +table.docutils { + border: 0; + border-collapse: collapse; +} + +table.align-center { + margin-left: auto; + margin-right: auto; +} + +table caption span.caption-number { + font-style: italic; +} + +table caption span.caption-text { +} + +table.docutils td, table.docutils th { + padding: 1px 8px 1px 5px; + border-top: 0; + border-left: 0; + border-right: 0; + border-bottom: 1px solid #aaa; +} + +table.footnote td, table.footnote th { + border: 0 !important; +} + +th { + text-align: left; + padding-right: 5px; +} + +table.citation { + border-left: solid 1px gray; + margin-left: 1px; +} + +table.citation td { + border-bottom: none; +} + +/* -- figures --------------------------------------------------------------- */ + +div.figure { + margin: 0.5em; + padding: 0.5em; +} + +div.figure p.caption { + padding: 0.3em; +} + +div.figure p.caption span.caption-number { + font-style: italic; +} + +div.figure p.caption span.caption-text { +} + +/* -- field list styles ----------------------------------------------------- */ + +table.field-list td, table.field-list th { + border: 0 !important; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +.field-name { + -moz-hyphens: manual; + -ms-hyphens: manual; + -webkit-hyphens: manual; + hyphens: manual; +} + +/* -- hlist styles ---------------------------------------------------------- */ + +table.hlist td { + vertical-align: top; +} + + +/* -- other body styles ----------------------------------------------------- */ + +ol.arabic { + list-style: decimal; +} + +ol.loweralpha { + list-style: lower-alpha; +} + +ol.upperalpha { + list-style: upper-alpha; +} + +ol.lowerroman { + list-style: lower-roman; +} + +ol.upperroman { + list-style: upper-roman; +} + +dl { + margin-bottom: 15px; +} + +dd p { + margin-top: 0px; +} + +dd ul, dd table { + margin-bottom: 10px; +} + +dd { + margin-top: 3px; + margin-bottom: 10px; + margin-left: 30px; +} + +dt:target, span.highlighted { + background-color: #fbe54e; +} + +rect.highlighted { + fill: #fbe54e; +} + +dl.glossary dt { + font-weight: bold; + font-size: 1.1em; +} + +.optional { + font-size: 1.3em; +} + +.sig-paren { + font-size: larger; +} + +.versionmodified { + font-style: italic; +} + +.system-message { + background-color: #fda; + padding: 5px; + border: 3px solid red; +} + +.footnote:target { + background-color: #ffa; +} + +.line-block { + display: block; + margin-top: 1em; + margin-bottom: 1em; +} + +.line-block .line-block { + margin-top: 0; + margin-bottom: 0; + margin-left: 1.5em; +} + +.guilabel, .menuselection { + font-family: sans-serif; +} + +.accelerator { + text-decoration: underline; +} + +.classifier { + font-style: oblique; +} + +abbr, acronym { + border-bottom: dotted 1px; + cursor: help; +} + +/* -- code displays --------------------------------------------------------- */ + +pre { + overflow: auto; + overflow-y: hidden; /* fixes display issues on Chrome browsers */ +} + +span.pre { + -moz-hyphens: none; + -ms-hyphens: none; + -webkit-hyphens: none; + hyphens: none; +} + +td.linenos pre { + padding: 5px 0px; + border: 0; + background-color: transparent; + color: #aaa; +} + +table.highlighttable { + margin-left: 0.5em; +} + +table.highlighttable td { + padding: 0 0.5em 0 0.5em; +} + +div.code-block-caption { + padding: 2px 5px; + font-size: small; +} + +div.code-block-caption code { + background-color: transparent; +} + +div.code-block-caption + div > div.highlight > pre { + margin-top: 0; +} + +div.code-block-caption span.caption-number { + padding: 0.1em 0.3em; + font-style: italic; +} + +div.code-block-caption span.caption-text { +} + +div.literal-block-wrapper { + padding: 1em 1em 0; +} + +div.literal-block-wrapper div.highlight { + margin: 0; +} + +code.descname { + background-color: transparent; + font-weight: bold; + font-size: 1.2em; +} + +code.descclassname { + background-color: transparent; +} + +code.xref, a code { + background-color: transparent; + font-weight: bold; +} + +h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { + background-color: transparent; +} + +.viewcode-link { + float: right; +} + +.viewcode-back { + float: right; + font-family: sans-serif; +} + +div.viewcode-block:target { + margin: -1px -10px; + padding: 0 10px; +} + +/* -- math display ---------------------------------------------------------- */ + +img.math { + vertical-align: middle; +} + +div.body div.math p { + text-align: center; +} + +span.eqno { + float: right; +} + +span.eqno a.headerlink { + position: relative; + left: 0px; + z-index: 1; +} + +div.math:hover a.headerlink { + visibility: visible; +} + +/* -- printout stylesheet --------------------------------------------------- */ + +@media print { + div.document, + div.documentwrapper, + div.bodywrapper { + margin: 0 !important; + width: 100%; + } + + div.sphinxsidebar, + div.related, + div.footer, + #top-link { + display: none; + } +} \ No newline at end of file diff --git a/docs/RefMan/_build/html/_static/classic.css b/docs/RefMan/_build/html/_static/classic.css new file mode 100644 index 00000000..8c6dae44 --- /dev/null +++ b/docs/RefMan/_build/html/_static/classic.css @@ -0,0 +1,261 @@ +/* + * classic.css_t + * ~~~~~~~~~~~~~ + * + * Sphinx stylesheet -- classic theme. + * + * :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +@import url("basic.css"); + +/* -- page layout ----------------------------------------------------------- */ + +body { + font-family: sans-serif; + font-size: 100%; + background-color: #11303d; + color: #000; + margin: 0; + padding: 0; +} + +div.document { + background-color: #1c4e63; +} + +div.documentwrapper { + float: left; + width: 100%; +} + +div.bodywrapper { + margin: 0 0 0 230px; +} + +div.body { + background-color: #ffffff; + color: #000000; + padding: 0 20px 30px 20px; +} + +div.footer { + color: #ffffff; + width: 100%; + padding: 9px 0 9px 0; + text-align: center; + font-size: 75%; +} + +div.footer a { + color: #ffffff; + text-decoration: underline; +} + +div.related { + background-color: #133f52; + line-height: 30px; + color: #ffffff; +} + +div.related a { + color: #ffffff; +} + +div.sphinxsidebar { +} + +div.sphinxsidebar h3 { + font-family: 'Trebuchet MS', sans-serif; + color: #ffffff; + font-size: 1.4em; + font-weight: normal; + margin: 0; + padding: 0; +} + +div.sphinxsidebar h3 a { + color: #ffffff; +} + +div.sphinxsidebar h4 { + font-family: 'Trebuchet MS', sans-serif; + color: #ffffff; + font-size: 1.3em; + font-weight: normal; + margin: 5px 0 0 0; + padding: 0; +} + +div.sphinxsidebar p { + color: #ffffff; +} + +div.sphinxsidebar p.topless { + margin: 5px 10px 10px 10px; +} + +div.sphinxsidebar ul { + margin: 10px; + padding: 0; + color: #ffffff; +} + +div.sphinxsidebar a { + color: #98dbcc; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + + + +/* -- hyperlink styles ------------------------------------------------------ */ + +a { + color: #355f7c; + text-decoration: none; +} + +a:visited { + color: #355f7c; + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + + + +/* -- body styles ----------------------------------------------------------- */ + +div.body h1, +div.body h2, +div.body h3, +div.body h4, +div.body h5, +div.body h6 { + font-family: 'Trebuchet MS', sans-serif; + background-color: #f2f2f2; + font-weight: normal; + color: #20435c; + border-bottom: 1px solid #ccc; + margin: 20px -20px 10px -20px; + padding: 3px 0 3px 10px; +} + +div.body h1 { margin-top: 0; font-size: 200%; } +div.body h2 { font-size: 160%; } +div.body h3 { font-size: 140%; } +div.body h4 { font-size: 120%; } +div.body h5 { font-size: 110%; } +div.body h6 { font-size: 100%; } + +a.headerlink { + color: #c60f0f; + font-size: 0.8em; + padding: 0 4px 0 4px; + text-decoration: none; +} + +a.headerlink:hover { + background-color: #c60f0f; + color: white; +} + +div.body p, div.body dd, div.body li, div.body blockquote { + text-align: justify; + line-height: 130%; +} + +div.admonition p.admonition-title + p { + display: inline; +} + +div.admonition p { + margin-bottom: 5px; +} + +div.admonition pre { + margin-bottom: 5px; +} + +div.admonition ul, div.admonition ol { + margin-bottom: 5px; +} + +div.note { + background-color: #eee; + border: 1px solid #ccc; +} + +div.seealso { + background-color: #ffc; + border: 1px solid #ff6; +} + +div.topic { + background-color: #eee; +} + +div.warning { + background-color: #ffe4e4; + border: 1px solid #f66; +} + +p.admonition-title { + display: inline; +} + +p.admonition-title:after { + content: ":"; +} + +pre { + padding: 5px; + background-color: #eeffcc; + color: #333333; + line-height: 120%; + border: 1px solid #ac9; + border-left: none; + border-right: none; +} + +code { + background-color: #ecf0f3; + padding: 0 1px 0 1px; + font-size: 0.95em; +} + +th { + background-color: #ede; +} + +.warning code { + background: #efc2c2; +} + +.note code { + background: #d6d6d6; +} + +.viewcode-back { + font-family: sans-serif; +} + +div.viewcode-block:target { + background-color: #f4debf; + border-top: 1px solid #ac9; + border-bottom: 1px solid #ac9; +} + +div.code-block-caption { + color: #efefef; + background-color: #1c4e63; +} \ No newline at end of file diff --git a/docs/RefMan/_build/html/_static/css/badge_only.css b/docs/RefMan/_build/html/_static/css/badge_only.css new file mode 100644 index 00000000..e380325b --- /dev/null +++ b/docs/RefMan/_build/html/_static/css/badge_only.css @@ -0,0 +1 @@ +.fa:before{-webkit-font-smoothing:antialiased}.clearfix{*zoom:1}.clearfix:after,.clearfix:before{display:table;content:""}.clearfix:after{clear:both}@font-face{font-family:FontAwesome;font-style:normal;font-weight:400;src:url(fonts/fontawesome-webfont.eot?674f50d287a8c48dc19ba404d20fe713?#iefix) format("embedded-opentype"),url(fonts/fontawesome-webfont.woff2?af7ae505a9eed503f8b8e6982036873e) format("woff2"),url(fonts/fontawesome-webfont.woff?fee66e712a8a08eef5805a46892932ad) format("woff"),url(fonts/fontawesome-webfont.ttf?b06871f281fee6b241d60582ae9369b9) format("truetype"),url(fonts/fontawesome-webfont.svg?912ec66d7572ff821749319396470bde#FontAwesome) format("svg")}.fa:before{font-family:FontAwesome;font-style:normal;font-weight:400;line-height:1}.fa:before,a .fa{text-decoration:inherit}.fa:before,a .fa,li .fa{display:inline-block}li .fa-large:before{width:1.875em}ul.fas{list-style-type:none;margin-left:2em;text-indent:-.8em}ul.fas li .fa{width:.8em}ul.fas li .fa-large:before{vertical-align:baseline}.fa-book:before,.icon-book:before{content:"\f02d"}.fa-caret-down:before,.icon-caret-down:before{content:"\f0d7"}.fa-caret-up:before,.icon-caret-up:before{content:"\f0d8"}.fa-caret-left:before,.icon-caret-left:before{content:"\f0d9"}.fa-caret-right:before,.icon-caret-right:before{content:"\f0da"}.rst-versions{position:fixed;bottom:0;left:0;width:300px;color:#fcfcfc;background:#1f1d1d;font-family:Lato,proxima-nova,Helvetica Neue,Arial,sans-serif;z-index:400}.rst-versions a{color:#2980b9;text-decoration:none}.rst-versions .rst-badge-small{display:none}.rst-versions .rst-current-version{padding:12px;background-color:#272525;display:block;text-align:right;font-size:90%;cursor:pointer;color:#27ae60}.rst-versions .rst-current-version:after{clear:both;content:"";display:block}.rst-versions .rst-current-version .fa{color:#fcfcfc}.rst-versions .rst-current-version .fa-book,.rst-versions .rst-current-version .icon-book{float:left}.rst-versions .rst-current-version.rst-out-of-date{background-color:#e74c3c;color:#fff}.rst-versions .rst-current-version.rst-active-old-version{background-color:#f1c40f;color:#000}.rst-versions.shift-up{height:auto;max-height:100%;overflow-y:scroll}.rst-versions.shift-up .rst-other-versions{display:block}.rst-versions .rst-other-versions{font-size:90%;padding:12px;color:grey;display:none}.rst-versions .rst-other-versions hr{display:block;height:1px;border:0;margin:20px 0;padding:0;border-top:1px solid #413d3d}.rst-versions .rst-other-versions dd{display:inline-block;margin:0}.rst-versions .rst-other-versions dd a{display:inline-block;padding:6px;color:#fcfcfc}.rst-versions.rst-badge{width:auto;bottom:20px;right:20px;left:auto;border:none;max-width:300px;max-height:90%}.rst-versions.rst-badge .fa-book,.rst-versions.rst-badge .icon-book{float:none;line-height:30px}.rst-versions.rst-badge.shift-up .rst-current-version{text-align:right}.rst-versions.rst-badge.shift-up .rst-current-version .fa-book,.rst-versions.rst-badge.shift-up .rst-current-version .icon-book{float:left}.rst-versions.rst-badge>.rst-current-version{width:auto;height:30px;line-height:30px;padding:0 6px;display:block;text-align:center}@media screen and (max-width:768px){.rst-versions{width:85%;display:none}.rst-versions.shift{display:block}} \ No newline at end of file diff --git a/docs/RefMan/_build/html/_static/css/fonts/Roboto-Slab-Bold.woff b/docs/RefMan/_build/html/_static/css/fonts/Roboto-Slab-Bold.woff new file mode 100644 index 00000000..6cb60000 Binary files /dev/null and b/docs/RefMan/_build/html/_static/css/fonts/Roboto-Slab-Bold.woff differ diff --git a/docs/RefMan/_build/html/_static/css/fonts/Roboto-Slab-Bold.woff2 b/docs/RefMan/_build/html/_static/css/fonts/Roboto-Slab-Bold.woff2 new file mode 100644 index 00000000..7059e231 Binary files /dev/null and b/docs/RefMan/_build/html/_static/css/fonts/Roboto-Slab-Bold.woff2 differ diff --git a/docs/RefMan/_build/html/_static/css/fonts/Roboto-Slab-Regular.woff b/docs/RefMan/_build/html/_static/css/fonts/Roboto-Slab-Regular.woff new file mode 100644 index 00000000..f815f63f Binary files /dev/null and b/docs/RefMan/_build/html/_static/css/fonts/Roboto-Slab-Regular.woff differ diff --git a/docs/RefMan/_build/html/_static/css/fonts/Roboto-Slab-Regular.woff2 b/docs/RefMan/_build/html/_static/css/fonts/Roboto-Slab-Regular.woff2 new file mode 100644 index 00000000..f2c76e5b Binary files /dev/null and b/docs/RefMan/_build/html/_static/css/fonts/Roboto-Slab-Regular.woff2 differ diff --git a/docs/RefMan/_build/html/_static/css/fonts/fontawesome-webfont.eot b/docs/RefMan/_build/html/_static/css/fonts/fontawesome-webfont.eot new file mode 100644 index 00000000..e9f60ca9 Binary files /dev/null and b/docs/RefMan/_build/html/_static/css/fonts/fontawesome-webfont.eot differ diff --git a/docs/RefMan/_build/html/_static/css/fonts/fontawesome-webfont.svg b/docs/RefMan/_build/html/_static/css/fonts/fontawesome-webfont.svg new file mode 100644 index 00000000..855c845e --- /dev/null +++ b/docs/RefMan/_build/html/_static/css/fonts/fontawesome-webfont.svg @@ -0,0 +1,2671 @@ + + + + +Created by FontForge 20120731 at Mon Oct 24 17:37:40 2016 + By ,,, +Copyright Dave Gandy 2016. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/RefMan/_build/html/_static/css/fonts/fontawesome-webfont.ttf b/docs/RefMan/_build/html/_static/css/fonts/fontawesome-webfont.ttf new file mode 100644 index 00000000..35acda2f Binary files /dev/null and b/docs/RefMan/_build/html/_static/css/fonts/fontawesome-webfont.ttf differ diff --git a/docs/RefMan/_build/html/_static/css/fonts/fontawesome-webfont.woff b/docs/RefMan/_build/html/_static/css/fonts/fontawesome-webfont.woff new file mode 100644 index 00000000..400014a4 Binary files /dev/null and b/docs/RefMan/_build/html/_static/css/fonts/fontawesome-webfont.woff differ diff --git a/docs/RefMan/_build/html/_static/css/fonts/fontawesome-webfont.woff2 b/docs/RefMan/_build/html/_static/css/fonts/fontawesome-webfont.woff2 new file mode 100644 index 00000000..4d13fc60 Binary files /dev/null and b/docs/RefMan/_build/html/_static/css/fonts/fontawesome-webfont.woff2 differ diff --git a/docs/RefMan/_build/html/_static/css/fonts/lato-bold-italic.woff b/docs/RefMan/_build/html/_static/css/fonts/lato-bold-italic.woff new file mode 100644 index 00000000..88ad05b9 Binary files /dev/null and b/docs/RefMan/_build/html/_static/css/fonts/lato-bold-italic.woff differ diff --git a/docs/RefMan/_build/html/_static/css/fonts/lato-bold-italic.woff2 b/docs/RefMan/_build/html/_static/css/fonts/lato-bold-italic.woff2 new file mode 100644 index 00000000..c4e3d804 Binary files /dev/null and b/docs/RefMan/_build/html/_static/css/fonts/lato-bold-italic.woff2 differ diff --git a/docs/RefMan/_build/html/_static/css/fonts/lato-bold.woff b/docs/RefMan/_build/html/_static/css/fonts/lato-bold.woff new file mode 100644 index 00000000..c6dff51f Binary files /dev/null and b/docs/RefMan/_build/html/_static/css/fonts/lato-bold.woff differ diff --git a/docs/RefMan/_build/html/_static/css/fonts/lato-bold.woff2 b/docs/RefMan/_build/html/_static/css/fonts/lato-bold.woff2 new file mode 100644 index 00000000..bb195043 Binary files /dev/null and b/docs/RefMan/_build/html/_static/css/fonts/lato-bold.woff2 differ diff --git a/docs/RefMan/_build/html/_static/css/fonts/lato-normal-italic.woff b/docs/RefMan/_build/html/_static/css/fonts/lato-normal-italic.woff new file mode 100644 index 00000000..76114bc0 Binary files /dev/null and b/docs/RefMan/_build/html/_static/css/fonts/lato-normal-italic.woff differ diff --git a/docs/RefMan/_build/html/_static/css/fonts/lato-normal-italic.woff2 b/docs/RefMan/_build/html/_static/css/fonts/lato-normal-italic.woff2 new file mode 100644 index 00000000..3404f37e Binary files /dev/null and b/docs/RefMan/_build/html/_static/css/fonts/lato-normal-italic.woff2 differ diff --git a/docs/RefMan/_build/html/_static/css/fonts/lato-normal.woff b/docs/RefMan/_build/html/_static/css/fonts/lato-normal.woff new file mode 100644 index 00000000..ae1307ff Binary files /dev/null and b/docs/RefMan/_build/html/_static/css/fonts/lato-normal.woff differ diff --git a/docs/RefMan/_build/html/_static/css/fonts/lato-normal.woff2 b/docs/RefMan/_build/html/_static/css/fonts/lato-normal.woff2 new file mode 100644 index 00000000..3bf98433 Binary files /dev/null and b/docs/RefMan/_build/html/_static/css/fonts/lato-normal.woff2 differ diff --git a/docs/RefMan/_build/html/_static/css/theme.css b/docs/RefMan/_build/html/_static/css/theme.css new file mode 100644 index 00000000..8cd4f101 --- /dev/null +++ b/docs/RefMan/_build/html/_static/css/theme.css @@ -0,0 +1,4 @@ +html{box-sizing:border-box}*,:after,:before{box-sizing:inherit}article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio,canvas,video{display:inline-block;*display:inline;*zoom:1}[hidden],audio:not([controls]){display:none}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}blockquote{margin:0}dfn{font-style:italic}ins{background:#ff9;text-decoration:none}ins,mark{color:#000}mark{background:#ff0;font-style:italic;font-weight:700}.rst-content code,.rst-content tt,code,kbd,pre,samp{font-family:monospace,serif;_font-family:courier new,monospace;font-size:1em}pre{white-space:pre}q{quotes:none}q:after,q:before{content:"";content:none}small{font-size:85%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}dl,ol,ul{margin:0;padding:0;list-style:none;list-style-image:none}li{list-style:none}dd{margin:0}img{border:0;-ms-interpolation-mode:bicubic;vertical-align:middle;max-width:100%}svg:not(:root){overflow:hidden}figure,form{margin:0}label{cursor:pointer}button,input,select,textarea{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle}button,input{line-height:normal}button,input[type=button],input[type=reset],input[type=submit]{cursor:pointer;-webkit-appearance:button;*overflow:visible}button[disabled],input[disabled]{cursor:default}input[type=search]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}textarea{resize:vertical}table{border-collapse:collapse;border-spacing:0}td{vertical-align:top}.chromeframe{margin:.2em 0;background:#ccc;color:#000;padding:.2em 0}.ir{display:block;border:0;text-indent:-999em;overflow:hidden;background-color:transparent;background-repeat:no-repeat;text-align:left;direction:ltr;*line-height:0}.ir br{display:none}.hidden{display:none!important;visibility:hidden}.visuallyhidden{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.visuallyhidden.focusable:active,.visuallyhidden.focusable:focus{clip:auto;height:auto;margin:0;overflow:visible;position:static;width:auto}.invisible{visibility:hidden}.relative{position:relative}big,small{font-size:100%}@media print{body,html,section{background:none!important}*{box-shadow:none!important;text-shadow:none!important;filter:none!important;-ms-filter:none!important}a,a:visited{text-decoration:underline}.ir a:after,a[href^="#"]:after,a[href^="javascript:"]:after{content:""}blockquote,pre{page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}img{max-width:100%!important}@page{margin:.5cm}.rst-content .toctree-wrapper>p.caption,h2,h3,p{orphans:3;widows:3}.rst-content .toctree-wrapper>p.caption,h2,h3{page-break-after:avoid}}.btn,.fa:before,.icon:before,.rst-content .admonition,.rst-content .admonition-title:before,.rst-content .admonition-todo,.rst-content .attention,.rst-content .caution,.rst-content .code-block-caption .headerlink:before,.rst-content .danger,.rst-content .error,.rst-content .hint,.rst-content .important,.rst-content .note,.rst-content .seealso,.rst-content .tip,.rst-content .warning,.rst-content code.download span:first-child:before,.rst-content dl dt .headerlink:before,.rst-content h1 .headerlink:before,.rst-content h2 .headerlink:before,.rst-content h3 .headerlink:before,.rst-content h4 .headerlink:before,.rst-content h5 .headerlink:before,.rst-content h6 .headerlink:before,.rst-content p.caption .headerlink:before,.rst-content table>caption .headerlink:before,.rst-content tt.download span:first-child:before,.wy-alert,.wy-dropdown .caret:before,.wy-inline-validate.wy-inline-validate-danger .wy-input-context:before,.wy-inline-validate.wy-inline-validate-info .wy-input-context:before,.wy-inline-validate.wy-inline-validate-success .wy-input-context:before,.wy-inline-validate.wy-inline-validate-warning .wy-input-context:before,.wy-menu-vertical li.current>a,.wy-menu-vertical li.current>a span.toctree-expand:before,.wy-menu-vertical li.on a,.wy-menu-vertical li.on a span.toctree-expand:before,.wy-menu-vertical li span.toctree-expand:before,.wy-nav-top a,.wy-side-nav-search .wy-dropdown>a,.wy-side-nav-search>a,input[type=color],input[type=date],input[type=datetime-local],input[type=datetime],input[type=email],input[type=month],input[type=number],input[type=password],input[type=search],input[type=tel],input[type=text],input[type=time],input[type=url],input[type=week],select,textarea{-webkit-font-smoothing:antialiased}.clearfix{*zoom:1}.clearfix:after,.clearfix:before{display:table;content:""}.clearfix:after{clear:both}/*! + * Font Awesome 4.7.0 by @davegandy - http://fontawesome.io - @fontawesome + * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) + */@font-face{font-family:FontAwesome;src:url(fonts/fontawesome-webfont.eot?674f50d287a8c48dc19ba404d20fe713);src:url(fonts/fontawesome-webfont.eot?674f50d287a8c48dc19ba404d20fe713?#iefix&v=4.7.0) format("embedded-opentype"),url(fonts/fontawesome-webfont.woff2?af7ae505a9eed503f8b8e6982036873e) format("woff2"),url(fonts/fontawesome-webfont.woff?fee66e712a8a08eef5805a46892932ad) format("woff"),url(fonts/fontawesome-webfont.ttf?b06871f281fee6b241d60582ae9369b9) format("truetype"),url(fonts/fontawesome-webfont.svg?912ec66d7572ff821749319396470bde#fontawesomeregular) format("svg");font-weight:400;font-style:normal}.fa,.icon,.rst-content .admonition-title,.rst-content .code-block-caption .headerlink,.rst-content code.download span:first-child,.rst-content dl dt .headerlink,.rst-content h1 .headerlink,.rst-content h2 .headerlink,.rst-content h3 .headerlink,.rst-content h4 .headerlink,.rst-content h5 .headerlink,.rst-content h6 .headerlink,.rst-content p.caption .headerlink,.rst-content table>caption .headerlink,.rst-content tt.download span:first-child,.wy-menu-vertical li.current>a span.toctree-expand,.wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li span.toctree-expand{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.33333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.28571em;text-align:center}.fa-ul{padding-left:0;margin-left:2.14286em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.14286em;width:2.14286em;top:.14286em;text-align:center}.fa-li.fa-lg{left:-1.85714em}.fa-border{padding:.2em .25em .15em;border:.08em solid #eee;border-radius:.1em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa-pull-left.icon,.fa.fa-pull-left,.rst-content .code-block-caption .fa-pull-left.headerlink,.rst-content .fa-pull-left.admonition-title,.rst-content code.download span.fa-pull-left:first-child,.rst-content dl dt .fa-pull-left.headerlink,.rst-content h1 .fa-pull-left.headerlink,.rst-content h2 .fa-pull-left.headerlink,.rst-content h3 .fa-pull-left.headerlink,.rst-content h4 .fa-pull-left.headerlink,.rst-content h5 .fa-pull-left.headerlink,.rst-content h6 .fa-pull-left.headerlink,.rst-content p.caption .fa-pull-left.headerlink,.rst-content table>caption .fa-pull-left.headerlink,.rst-content tt.download span.fa-pull-left:first-child,.wy-menu-vertical li.current>a span.fa-pull-left.toctree-expand,.wy-menu-vertical li.on a span.fa-pull-left.toctree-expand,.wy-menu-vertical li span.fa-pull-left.toctree-expand{margin-right:.3em}.fa-pull-right.icon,.fa.fa-pull-right,.rst-content .code-block-caption .fa-pull-right.headerlink,.rst-content .fa-pull-right.admonition-title,.rst-content code.download span.fa-pull-right:first-child,.rst-content dl dt .fa-pull-right.headerlink,.rst-content h1 .fa-pull-right.headerlink,.rst-content h2 .fa-pull-right.headerlink,.rst-content h3 .fa-pull-right.headerlink,.rst-content h4 .fa-pull-right.headerlink,.rst-content h5 .fa-pull-right.headerlink,.rst-content h6 .fa-pull-right.headerlink,.rst-content p.caption .fa-pull-right.headerlink,.rst-content table>caption .fa-pull-right.headerlink,.rst-content tt.download span.fa-pull-right:first-child,.wy-menu-vertical li.current>a span.fa-pull-right.toctree-expand,.wy-menu-vertical li.on a span.fa-pull-right.toctree-expand,.wy-menu-vertical li span.fa-pull-right.toctree-expand{margin-left:.3em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left,.pull-left.icon,.rst-content .code-block-caption .pull-left.headerlink,.rst-content .pull-left.admonition-title,.rst-content code.download span.pull-left:first-child,.rst-content dl dt .pull-left.headerlink,.rst-content h1 .pull-left.headerlink,.rst-content h2 .pull-left.headerlink,.rst-content h3 .pull-left.headerlink,.rst-content h4 .pull-left.headerlink,.rst-content h5 .pull-left.headerlink,.rst-content h6 .pull-left.headerlink,.rst-content p.caption .pull-left.headerlink,.rst-content table>caption .pull-left.headerlink,.rst-content tt.download span.pull-left:first-child,.wy-menu-vertical li.current>a span.pull-left.toctree-expand,.wy-menu-vertical li.on a span.pull-left.toctree-expand,.wy-menu-vertical li span.pull-left.toctree-expand{margin-right:.3em}.fa.pull-right,.pull-right.icon,.rst-content .code-block-caption .pull-right.headerlink,.rst-content .pull-right.admonition-title,.rst-content code.download span.pull-right:first-child,.rst-content dl dt .pull-right.headerlink,.rst-content h1 .pull-right.headerlink,.rst-content h2 .pull-right.headerlink,.rst-content h3 .pull-right.headerlink,.rst-content h4 .pull-right.headerlink,.rst-content h5 .pull-right.headerlink,.rst-content h6 .pull-right.headerlink,.rst-content p.caption .pull-right.headerlink,.rst-content table>caption .pull-right.headerlink,.rst-content tt.download span.pull-right:first-child,.wy-menu-vertical li.current>a span.pull-right.toctree-expand,.wy-menu-vertical li.on a span.pull-right.toctree-expand,.wy-menu-vertical li span.pull-right.toctree-expand{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s linear infinite;animation:fa-spin 2s linear infinite}.fa-pulse{-webkit-animation:fa-spin 1s steps(8) infinite;animation:fa-spin 1s steps(8) infinite}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(359deg);transform:rotate(359deg)}}.fa-rotate-90{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";-webkit-transform:rotate(90deg);-ms-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";-webkit-transform:rotate(270deg);-ms-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)";-webkit-transform:scaleX(-1);-ms-transform:scaleX(-1);transform:scaleX(-1)}.fa-flip-vertical{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)";-webkit-transform:scaleY(-1);-ms-transform:scaleY(-1);transform:scaleY(-1)}:root .fa-flip-horizontal,:root .fa-flip-vertical,:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270{filter:none}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:""}.fa-music:before{content:""}.fa-search:before,.icon-search:before{content:""}.fa-envelope-o:before{content:""}.fa-heart:before{content:""}.fa-star:before{content:""}.fa-star-o:before{content:""}.fa-user:before{content:""}.fa-film:before{content:""}.fa-th-large:before{content:""}.fa-th:before{content:""}.fa-th-list:before{content:""}.fa-check:before{content:""}.fa-close:before,.fa-remove:before,.fa-times:before{content:""}.fa-search-plus:before{content:""}.fa-search-minus:before{content:""}.fa-power-off:before{content:""}.fa-signal:before{content:""}.fa-cog:before,.fa-gear:before{content:""}.fa-trash-o:before{content:""}.fa-home:before,.icon-home:before{content:""}.fa-file-o:before{content:""}.fa-clock-o:before{content:""}.fa-road:before{content:""}.fa-download:before,.rst-content code.download span:first-child:before,.rst-content tt.download span:first-child:before{content:""}.fa-arrow-circle-o-down:before{content:""}.fa-arrow-circle-o-up:before{content:""}.fa-inbox:before{content:""}.fa-play-circle-o:before{content:""}.fa-repeat:before,.fa-rotate-right:before{content:""}.fa-refresh:before{content:""}.fa-list-alt:before{content:""}.fa-lock:before{content:""}.fa-flag:before{content:""}.fa-headphones:before{content:""}.fa-volume-off:before{content:""}.fa-volume-down:before{content:""}.fa-volume-up:before{content:""}.fa-qrcode:before{content:""}.fa-barcode:before{content:""}.fa-tag:before{content:""}.fa-tags:before{content:""}.fa-book:before,.icon-book:before{content:""}.fa-bookmark:before{content:""}.fa-print:before{content:""}.fa-camera:before{content:""}.fa-font:before{content:""}.fa-bold:before{content:""}.fa-italic:before{content:""}.fa-text-height:before{content:""}.fa-text-width:before{content:""}.fa-align-left:before{content:""}.fa-align-center:before{content:""}.fa-align-right:before{content:""}.fa-align-justify:before{content:""}.fa-list:before{content:""}.fa-dedent:before,.fa-outdent:before{content:""}.fa-indent:before{content:""}.fa-video-camera:before{content:""}.fa-image:before,.fa-photo:before,.fa-picture-o:before{content:""}.fa-pencil:before{content:""}.fa-map-marker:before{content:""}.fa-adjust:before{content:""}.fa-tint:before{content:""}.fa-edit:before,.fa-pencil-square-o:before{content:""}.fa-share-square-o:before{content:""}.fa-check-square-o:before{content:""}.fa-arrows:before{content:""}.fa-step-backward:before{content:""}.fa-fast-backward:before{content:""}.fa-backward:before{content:""}.fa-play:before{content:""}.fa-pause:before{content:""}.fa-stop:before{content:""}.fa-forward:before{content:""}.fa-fast-forward:before{content:""}.fa-step-forward:before{content:""}.fa-eject:before{content:""}.fa-chevron-left:before{content:""}.fa-chevron-right:before{content:""}.fa-plus-circle:before{content:""}.fa-minus-circle:before{content:""}.fa-times-circle:before,.wy-inline-validate.wy-inline-validate-danger .wy-input-context:before{content:""}.fa-check-circle:before,.wy-inline-validate.wy-inline-validate-success .wy-input-context:before{content:""}.fa-question-circle:before{content:""}.fa-info-circle:before{content:""}.fa-crosshairs:before{content:""}.fa-times-circle-o:before{content:""}.fa-check-circle-o:before{content:""}.fa-ban:before{content:""}.fa-arrow-left:before{content:""}.fa-arrow-right:before{content:""}.fa-arrow-up:before{content:""}.fa-arrow-down:before{content:""}.fa-mail-forward:before,.fa-share:before{content:""}.fa-expand:before{content:""}.fa-compress:before{content:""}.fa-plus:before{content:""}.fa-minus:before{content:""}.fa-asterisk:before{content:""}.fa-exclamation-circle:before,.rst-content .admonition-title:before,.wy-inline-validate.wy-inline-validate-info .wy-input-context:before,.wy-inline-validate.wy-inline-validate-warning .wy-input-context:before{content:""}.fa-gift:before{content:""}.fa-leaf:before{content:""}.fa-fire:before,.icon-fire:before{content:""}.fa-eye:before{content:""}.fa-eye-slash:before{content:""}.fa-exclamation-triangle:before,.fa-warning:before{content:""}.fa-plane:before{content:""}.fa-calendar:before{content:""}.fa-random:before{content:""}.fa-comment:before{content:""}.fa-magnet:before{content:""}.fa-chevron-up:before{content:""}.fa-chevron-down:before{content:""}.fa-retweet:before{content:""}.fa-shopping-cart:before{content:""}.fa-folder:before{content:""}.fa-folder-open:before{content:""}.fa-arrows-v:before{content:""}.fa-arrows-h:before{content:""}.fa-bar-chart-o:before,.fa-bar-chart:before{content:""}.fa-twitter-square:before{content:""}.fa-facebook-square:before{content:""}.fa-camera-retro:before{content:""}.fa-key:before{content:""}.fa-cogs:before,.fa-gears:before{content:""}.fa-comments:before{content:""}.fa-thumbs-o-up:before{content:""}.fa-thumbs-o-down:before{content:""}.fa-star-half:before{content:""}.fa-heart-o:before{content:""}.fa-sign-out:before{content:""}.fa-linkedin-square:before{content:""}.fa-thumb-tack:before{content:""}.fa-external-link:before{content:""}.fa-sign-in:before{content:""}.fa-trophy:before{content:""}.fa-github-square:before{content:""}.fa-upload:before{content:""}.fa-lemon-o:before{content:""}.fa-phone:before{content:""}.fa-square-o:before{content:""}.fa-bookmark-o:before{content:""}.fa-phone-square:before{content:""}.fa-twitter:before{content:""}.fa-facebook-f:before,.fa-facebook:before{content:""}.fa-github:before,.icon-github:before{content:""}.fa-unlock:before{content:""}.fa-credit-card:before{content:""}.fa-feed:before,.fa-rss:before{content:""}.fa-hdd-o:before{content:""}.fa-bullhorn:before{content:""}.fa-bell:before{content:""}.fa-certificate:before{content:""}.fa-hand-o-right:before{content:""}.fa-hand-o-left:before{content:""}.fa-hand-o-up:before{content:""}.fa-hand-o-down:before{content:""}.fa-arrow-circle-left:before,.icon-circle-arrow-left:before{content:""}.fa-arrow-circle-right:before,.icon-circle-arrow-right:before{content:""}.fa-arrow-circle-up:before{content:""}.fa-arrow-circle-down:before{content:""}.fa-globe:before{content:""}.fa-wrench:before{content:""}.fa-tasks:before{content:""}.fa-filter:before{content:""}.fa-briefcase:before{content:""}.fa-arrows-alt:before{content:""}.fa-group:before,.fa-users:before{content:""}.fa-chain:before,.fa-link:before,.icon-link:before{content:""}.fa-cloud:before{content:""}.fa-flask:before{content:""}.fa-cut:before,.fa-scissors:before{content:""}.fa-copy:before,.fa-files-o:before{content:""}.fa-paperclip:before{content:""}.fa-floppy-o:before,.fa-save:before{content:""}.fa-square:before{content:""}.fa-bars:before,.fa-navicon:before,.fa-reorder:before{content:""}.fa-list-ul:before{content:""}.fa-list-ol:before{content:""}.fa-strikethrough:before{content:""}.fa-underline:before{content:""}.fa-table:before{content:""}.fa-magic:before{content:""}.fa-truck:before{content:""}.fa-pinterest:before{content:""}.fa-pinterest-square:before{content:""}.fa-google-plus-square:before{content:""}.fa-google-plus:before{content:""}.fa-money:before{content:""}.fa-caret-down:before,.icon-caret-down:before,.wy-dropdown .caret:before{content:""}.fa-caret-up:before{content:""}.fa-caret-left:before{content:""}.fa-caret-right:before{content:""}.fa-columns:before{content:""}.fa-sort:before,.fa-unsorted:before{content:""}.fa-sort-desc:before,.fa-sort-down:before{content:""}.fa-sort-asc:before,.fa-sort-up:before{content:""}.fa-envelope:before{content:""}.fa-linkedin:before{content:""}.fa-rotate-left:before,.fa-undo:before{content:""}.fa-gavel:before,.fa-legal:before{content:""}.fa-dashboard:before,.fa-tachometer:before{content:""}.fa-comment-o:before{content:""}.fa-comments-o:before{content:""}.fa-bolt:before,.fa-flash:before{content:""}.fa-sitemap:before{content:""}.fa-umbrella:before{content:""}.fa-clipboard:before,.fa-paste:before{content:""}.fa-lightbulb-o:before{content:""}.fa-exchange:before{content:""}.fa-cloud-download:before{content:""}.fa-cloud-upload:before{content:""}.fa-user-md:before{content:""}.fa-stethoscope:before{content:""}.fa-suitcase:before{content:""}.fa-bell-o:before{content:""}.fa-coffee:before{content:""}.fa-cutlery:before{content:""}.fa-file-text-o:before{content:""}.fa-building-o:before{content:""}.fa-hospital-o:before{content:""}.fa-ambulance:before{content:""}.fa-medkit:before{content:""}.fa-fighter-jet:before{content:""}.fa-beer:before{content:""}.fa-h-square:before{content:""}.fa-plus-square:before{content:""}.fa-angle-double-left:before{content:""}.fa-angle-double-right:before{content:""}.fa-angle-double-up:before{content:""}.fa-angle-double-down:before{content:""}.fa-angle-left:before{content:""}.fa-angle-right:before{content:""}.fa-angle-up:before{content:""}.fa-angle-down:before{content:""}.fa-desktop:before{content:""}.fa-laptop:before{content:""}.fa-tablet:before{content:""}.fa-mobile-phone:before,.fa-mobile:before{content:""}.fa-circle-o:before{content:""}.fa-quote-left:before{content:""}.fa-quote-right:before{content:""}.fa-spinner:before{content:""}.fa-circle:before{content:""}.fa-mail-reply:before,.fa-reply:before{content:""}.fa-github-alt:before{content:""}.fa-folder-o:before{content:""}.fa-folder-open-o:before{content:""}.fa-smile-o:before{content:""}.fa-frown-o:before{content:""}.fa-meh-o:before{content:""}.fa-gamepad:before{content:""}.fa-keyboard-o:before{content:""}.fa-flag-o:before{content:""}.fa-flag-checkered:before{content:""}.fa-terminal:before{content:""}.fa-code:before{content:""}.fa-mail-reply-all:before,.fa-reply-all:before{content:""}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:""}.fa-location-arrow:before{content:""}.fa-crop:before{content:""}.fa-code-fork:before{content:""}.fa-chain-broken:before,.fa-unlink:before{content:""}.fa-question:before{content:""}.fa-info:before{content:""}.fa-exclamation:before{content:""}.fa-superscript:before{content:""}.fa-subscript:before{content:""}.fa-eraser:before{content:""}.fa-puzzle-piece:before{content:""}.fa-microphone:before{content:""}.fa-microphone-slash:before{content:""}.fa-shield:before{content:""}.fa-calendar-o:before{content:""}.fa-fire-extinguisher:before{content:""}.fa-rocket:before{content:""}.fa-maxcdn:before{content:""}.fa-chevron-circle-left:before{content:""}.fa-chevron-circle-right:before{content:""}.fa-chevron-circle-up:before{content:""}.fa-chevron-circle-down:before{content:""}.fa-html5:before{content:""}.fa-css3:before{content:""}.fa-anchor:before{content:""}.fa-unlock-alt:before{content:""}.fa-bullseye:before{content:""}.fa-ellipsis-h:before{content:""}.fa-ellipsis-v:before{content:""}.fa-rss-square:before{content:""}.fa-play-circle:before{content:""}.fa-ticket:before{content:""}.fa-minus-square:before{content:""}.fa-minus-square-o:before,.wy-menu-vertical li.current>a span.toctree-expand:before,.wy-menu-vertical li.on a span.toctree-expand:before{content:""}.fa-level-up:before{content:""}.fa-level-down:before{content:""}.fa-check-square:before{content:""}.fa-pencil-square:before{content:""}.fa-external-link-square:before{content:""}.fa-share-square:before{content:""}.fa-compass:before{content:""}.fa-caret-square-o-down:before,.fa-toggle-down:before{content:""}.fa-caret-square-o-up:before,.fa-toggle-up:before{content:""}.fa-caret-square-o-right:before,.fa-toggle-right:before{content:""}.fa-eur:before,.fa-euro:before{content:""}.fa-gbp:before{content:""}.fa-dollar:before,.fa-usd:before{content:""}.fa-inr:before,.fa-rupee:before{content:""}.fa-cny:before,.fa-jpy:before,.fa-rmb:before,.fa-yen:before{content:""}.fa-rouble:before,.fa-rub:before,.fa-ruble:before{content:""}.fa-krw:before,.fa-won:before{content:""}.fa-bitcoin:before,.fa-btc:before{content:""}.fa-file:before{content:""}.fa-file-text:before{content:""}.fa-sort-alpha-asc:before{content:""}.fa-sort-alpha-desc:before{content:""}.fa-sort-amount-asc:before{content:""}.fa-sort-amount-desc:before{content:""}.fa-sort-numeric-asc:before{content:""}.fa-sort-numeric-desc:before{content:""}.fa-thumbs-up:before{content:""}.fa-thumbs-down:before{content:""}.fa-youtube-square:before{content:""}.fa-youtube:before{content:""}.fa-xing:before{content:""}.fa-xing-square:before{content:""}.fa-youtube-play:before{content:""}.fa-dropbox:before{content:""}.fa-stack-overflow:before{content:""}.fa-instagram:before{content:""}.fa-flickr:before{content:""}.fa-adn:before{content:""}.fa-bitbucket:before,.icon-bitbucket:before{content:""}.fa-bitbucket-square:before{content:""}.fa-tumblr:before{content:""}.fa-tumblr-square:before{content:""}.fa-long-arrow-down:before{content:""}.fa-long-arrow-up:before{content:""}.fa-long-arrow-left:before{content:""}.fa-long-arrow-right:before{content:""}.fa-apple:before{content:""}.fa-windows:before{content:""}.fa-android:before{content:""}.fa-linux:before{content:""}.fa-dribbble:before{content:""}.fa-skype:before{content:""}.fa-foursquare:before{content:""}.fa-trello:before{content:""}.fa-female:before{content:""}.fa-male:before{content:""}.fa-gittip:before,.fa-gratipay:before{content:""}.fa-sun-o:before{content:""}.fa-moon-o:before{content:""}.fa-archive:before{content:""}.fa-bug:before{content:""}.fa-vk:before{content:""}.fa-weibo:before{content:""}.fa-renren:before{content:""}.fa-pagelines:before{content:""}.fa-stack-exchange:before{content:""}.fa-arrow-circle-o-right:before{content:""}.fa-arrow-circle-o-left:before{content:""}.fa-caret-square-o-left:before,.fa-toggle-left:before{content:""}.fa-dot-circle-o:before{content:""}.fa-wheelchair:before{content:""}.fa-vimeo-square:before{content:""}.fa-try:before,.fa-turkish-lira:before{content:""}.fa-plus-square-o:before,.wy-menu-vertical li span.toctree-expand:before{content:""}.fa-space-shuttle:before{content:""}.fa-slack:before{content:""}.fa-envelope-square:before{content:""}.fa-wordpress:before{content:""}.fa-openid:before{content:""}.fa-bank:before,.fa-institution:before,.fa-university:before{content:""}.fa-graduation-cap:before,.fa-mortar-board:before{content:""}.fa-yahoo:before{content:""}.fa-google:before{content:""}.fa-reddit:before{content:""}.fa-reddit-square:before{content:""}.fa-stumbleupon-circle:before{content:""}.fa-stumbleupon:before{content:""}.fa-delicious:before{content:""}.fa-digg:before{content:""}.fa-pied-piper-pp:before{content:""}.fa-pied-piper-alt:before{content:""}.fa-drupal:before{content:""}.fa-joomla:before{content:""}.fa-language:before{content:""}.fa-fax:before{content:""}.fa-building:before{content:""}.fa-child:before{content:""}.fa-paw:before{content:""}.fa-spoon:before{content:""}.fa-cube:before{content:""}.fa-cubes:before{content:""}.fa-behance:before{content:""}.fa-behance-square:before{content:""}.fa-steam:before{content:""}.fa-steam-square:before{content:""}.fa-recycle:before{content:""}.fa-automobile:before,.fa-car:before{content:""}.fa-cab:before,.fa-taxi:before{content:""}.fa-tree:before{content:""}.fa-spotify:before{content:""}.fa-deviantart:before{content:""}.fa-soundcloud:before{content:""}.fa-database:before{content:""}.fa-file-pdf-o:before{content:""}.fa-file-word-o:before{content:""}.fa-file-excel-o:before{content:""}.fa-file-powerpoint-o:before{content:""}.fa-file-image-o:before,.fa-file-photo-o:before,.fa-file-picture-o:before{content:""}.fa-file-archive-o:before,.fa-file-zip-o:before{content:""}.fa-file-audio-o:before,.fa-file-sound-o:before{content:""}.fa-file-movie-o:before,.fa-file-video-o:before{content:""}.fa-file-code-o:before{content:""}.fa-vine:before{content:""}.fa-codepen:before{content:""}.fa-jsfiddle:before{content:""}.fa-life-bouy:before,.fa-life-buoy:before,.fa-life-ring:before,.fa-life-saver:before,.fa-support:before{content:""}.fa-circle-o-notch:before{content:""}.fa-ra:before,.fa-rebel:before,.fa-resistance:before{content:""}.fa-empire:before,.fa-ge:before{content:""}.fa-git-square:before{content:""}.fa-git:before{content:""}.fa-hacker-news:before,.fa-y-combinator-square:before,.fa-yc-square:before{content:""}.fa-tencent-weibo:before{content:""}.fa-qq:before{content:""}.fa-wechat:before,.fa-weixin:before{content:""}.fa-paper-plane:before,.fa-send:before{content:""}.fa-paper-plane-o:before,.fa-send-o:before{content:""}.fa-history:before{content:""}.fa-circle-thin:before{content:""}.fa-header:before{content:""}.fa-paragraph:before{content:""}.fa-sliders:before{content:""}.fa-share-alt:before{content:""}.fa-share-alt-square:before{content:""}.fa-bomb:before{content:""}.fa-futbol-o:before,.fa-soccer-ball-o:before{content:""}.fa-tty:before{content:""}.fa-binoculars:before{content:""}.fa-plug:before{content:""}.fa-slideshare:before{content:""}.fa-twitch:before{content:""}.fa-yelp:before{content:""}.fa-newspaper-o:before{content:""}.fa-wifi:before{content:""}.fa-calculator:before{content:""}.fa-paypal:before{content:""}.fa-google-wallet:before{content:""}.fa-cc-visa:before{content:""}.fa-cc-mastercard:before{content:""}.fa-cc-discover:before{content:""}.fa-cc-amex:before{content:""}.fa-cc-paypal:before{content:""}.fa-cc-stripe:before{content:""}.fa-bell-slash:before{content:""}.fa-bell-slash-o:before{content:""}.fa-trash:before{content:""}.fa-copyright:before{content:""}.fa-at:before{content:""}.fa-eyedropper:before{content:""}.fa-paint-brush:before{content:""}.fa-birthday-cake:before{content:""}.fa-area-chart:before{content:""}.fa-pie-chart:before{content:""}.fa-line-chart:before{content:""}.fa-lastfm:before{content:""}.fa-lastfm-square:before{content:""}.fa-toggle-off:before{content:""}.fa-toggle-on:before{content:""}.fa-bicycle:before{content:""}.fa-bus:before{content:""}.fa-ioxhost:before{content:""}.fa-angellist:before{content:""}.fa-cc:before{content:""}.fa-ils:before,.fa-shekel:before,.fa-sheqel:before{content:""}.fa-meanpath:before{content:""}.fa-buysellads:before{content:""}.fa-connectdevelop:before{content:""}.fa-dashcube:before{content:""}.fa-forumbee:before{content:""}.fa-leanpub:before{content:""}.fa-sellsy:before{content:""}.fa-shirtsinbulk:before{content:""}.fa-simplybuilt:before{content:""}.fa-skyatlas:before{content:""}.fa-cart-plus:before{content:""}.fa-cart-arrow-down:before{content:""}.fa-diamond:before{content:""}.fa-ship:before{content:""}.fa-user-secret:before{content:""}.fa-motorcycle:before{content:""}.fa-street-view:before{content:""}.fa-heartbeat:before{content:""}.fa-venus:before{content:""}.fa-mars:before{content:""}.fa-mercury:before{content:""}.fa-intersex:before,.fa-transgender:before{content:""}.fa-transgender-alt:before{content:""}.fa-venus-double:before{content:""}.fa-mars-double:before{content:""}.fa-venus-mars:before{content:""}.fa-mars-stroke:before{content:""}.fa-mars-stroke-v:before{content:""}.fa-mars-stroke-h:before{content:""}.fa-neuter:before{content:""}.fa-genderless:before{content:""}.fa-facebook-official:before{content:""}.fa-pinterest-p:before{content:""}.fa-whatsapp:before{content:""}.fa-server:before{content:""}.fa-user-plus:before{content:""}.fa-user-times:before{content:""}.fa-bed:before,.fa-hotel:before{content:""}.fa-viacoin:before{content:""}.fa-train:before{content:""}.fa-subway:before{content:""}.fa-medium:before{content:""}.fa-y-combinator:before,.fa-yc:before{content:""}.fa-optin-monster:before{content:""}.fa-opencart:before{content:""}.fa-expeditedssl:before{content:""}.fa-battery-4:before,.fa-battery-full:before,.fa-battery:before{content:""}.fa-battery-3:before,.fa-battery-three-quarters:before{content:""}.fa-battery-2:before,.fa-battery-half:before{content:""}.fa-battery-1:before,.fa-battery-quarter:before{content:""}.fa-battery-0:before,.fa-battery-empty:before{content:""}.fa-mouse-pointer:before{content:""}.fa-i-cursor:before{content:""}.fa-object-group:before{content:""}.fa-object-ungroup:before{content:""}.fa-sticky-note:before{content:""}.fa-sticky-note-o:before{content:""}.fa-cc-jcb:before{content:""}.fa-cc-diners-club:before{content:""}.fa-clone:before{content:""}.fa-balance-scale:before{content:""}.fa-hourglass-o:before{content:""}.fa-hourglass-1:before,.fa-hourglass-start:before{content:""}.fa-hourglass-2:before,.fa-hourglass-half:before{content:""}.fa-hourglass-3:before,.fa-hourglass-end:before{content:""}.fa-hourglass:before{content:""}.fa-hand-grab-o:before,.fa-hand-rock-o:before{content:""}.fa-hand-paper-o:before,.fa-hand-stop-o:before{content:""}.fa-hand-scissors-o:before{content:""}.fa-hand-lizard-o:before{content:""}.fa-hand-spock-o:before{content:""}.fa-hand-pointer-o:before{content:""}.fa-hand-peace-o:before{content:""}.fa-trademark:before{content:""}.fa-registered:before{content:""}.fa-creative-commons:before{content:""}.fa-gg:before{content:""}.fa-gg-circle:before{content:""}.fa-tripadvisor:before{content:""}.fa-odnoklassniki:before{content:""}.fa-odnoklassniki-square:before{content:""}.fa-get-pocket:before{content:""}.fa-wikipedia-w:before{content:""}.fa-safari:before{content:""}.fa-chrome:before{content:""}.fa-firefox:before{content:""}.fa-opera:before{content:""}.fa-internet-explorer:before{content:""}.fa-television:before,.fa-tv:before{content:""}.fa-contao:before{content:""}.fa-500px:before{content:""}.fa-amazon:before{content:""}.fa-calendar-plus-o:before{content:""}.fa-calendar-minus-o:before{content:""}.fa-calendar-times-o:before{content:""}.fa-calendar-check-o:before{content:""}.fa-industry:before{content:""}.fa-map-pin:before{content:""}.fa-map-signs:before{content:""}.fa-map-o:before{content:""}.fa-map:before{content:""}.fa-commenting:before{content:""}.fa-commenting-o:before{content:""}.fa-houzz:before{content:""}.fa-vimeo:before{content:""}.fa-black-tie:before{content:""}.fa-fonticons:before{content:""}.fa-reddit-alien:before{content:""}.fa-edge:before{content:""}.fa-credit-card-alt:before{content:""}.fa-codiepie:before{content:""}.fa-modx:before{content:""}.fa-fort-awesome:before{content:""}.fa-usb:before{content:""}.fa-product-hunt:before{content:""}.fa-mixcloud:before{content:""}.fa-scribd:before{content:""}.fa-pause-circle:before{content:""}.fa-pause-circle-o:before{content:""}.fa-stop-circle:before{content:""}.fa-stop-circle-o:before{content:""}.fa-shopping-bag:before{content:""}.fa-shopping-basket:before{content:""}.fa-hashtag:before{content:""}.fa-bluetooth:before{content:""}.fa-bluetooth-b:before{content:""}.fa-percent:before{content:""}.fa-gitlab:before,.icon-gitlab:before{content:""}.fa-wpbeginner:before{content:""}.fa-wpforms:before{content:""}.fa-envira:before{content:""}.fa-universal-access:before{content:""}.fa-wheelchair-alt:before{content:""}.fa-question-circle-o:before{content:""}.fa-blind:before{content:""}.fa-audio-description:before{content:""}.fa-volume-control-phone:before{content:""}.fa-braille:before{content:""}.fa-assistive-listening-systems:before{content:""}.fa-american-sign-language-interpreting:before,.fa-asl-interpreting:before{content:""}.fa-deaf:before,.fa-deafness:before,.fa-hard-of-hearing:before{content:""}.fa-glide:before{content:""}.fa-glide-g:before{content:""}.fa-sign-language:before,.fa-signing:before{content:""}.fa-low-vision:before{content:""}.fa-viadeo:before{content:""}.fa-viadeo-square:before{content:""}.fa-snapchat:before{content:""}.fa-snapchat-ghost:before{content:""}.fa-snapchat-square:before{content:""}.fa-pied-piper:before{content:""}.fa-first-order:before{content:""}.fa-yoast:before{content:""}.fa-themeisle:before{content:""}.fa-google-plus-circle:before,.fa-google-plus-official:before{content:""}.fa-fa:before,.fa-font-awesome:before{content:""}.fa-handshake-o:before{content:""}.fa-envelope-open:before{content:""}.fa-envelope-open-o:before{content:""}.fa-linode:before{content:""}.fa-address-book:before{content:""}.fa-address-book-o:before{content:""}.fa-address-card:before,.fa-vcard:before{content:""}.fa-address-card-o:before,.fa-vcard-o:before{content:""}.fa-user-circle:before{content:""}.fa-user-circle-o:before{content:""}.fa-user-o:before{content:""}.fa-id-badge:before{content:""}.fa-drivers-license:before,.fa-id-card:before{content:""}.fa-drivers-license-o:before,.fa-id-card-o:before{content:""}.fa-quora:before{content:""}.fa-free-code-camp:before{content:""}.fa-telegram:before{content:""}.fa-thermometer-4:before,.fa-thermometer-full:before,.fa-thermometer:before{content:""}.fa-thermometer-3:before,.fa-thermometer-three-quarters:before{content:""}.fa-thermometer-2:before,.fa-thermometer-half:before{content:""}.fa-thermometer-1:before,.fa-thermometer-quarter:before{content:""}.fa-thermometer-0:before,.fa-thermometer-empty:before{content:""}.fa-shower:before{content:""}.fa-bath:before,.fa-bathtub:before,.fa-s15:before{content:""}.fa-podcast:before{content:""}.fa-window-maximize:before{content:""}.fa-window-minimize:before{content:""}.fa-window-restore:before{content:""}.fa-times-rectangle:before,.fa-window-close:before{content:""}.fa-times-rectangle-o:before,.fa-window-close-o:before{content:""}.fa-bandcamp:before{content:""}.fa-grav:before{content:""}.fa-etsy:before{content:""}.fa-imdb:before{content:""}.fa-ravelry:before{content:""}.fa-eercast:before{content:""}.fa-microchip:before{content:""}.fa-snowflake-o:before{content:""}.fa-superpowers:before{content:""}.fa-wpexplorer:before{content:""}.fa-meetup:before{content:""}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}.fa,.icon,.rst-content .admonition-title,.rst-content .code-block-caption .headerlink,.rst-content code.download span:first-child,.rst-content dl dt .headerlink,.rst-content h1 .headerlink,.rst-content h2 .headerlink,.rst-content h3 .headerlink,.rst-content h4 .headerlink,.rst-content h5 .headerlink,.rst-content h6 .headerlink,.rst-content p.caption .headerlink,.rst-content table>caption .headerlink,.rst-content tt.download span:first-child,.wy-dropdown .caret,.wy-inline-validate.wy-inline-validate-danger .wy-input-context,.wy-inline-validate.wy-inline-validate-info .wy-input-context,.wy-inline-validate.wy-inline-validate-success .wy-input-context,.wy-inline-validate.wy-inline-validate-warning .wy-input-context,.wy-menu-vertical li.current>a span.toctree-expand,.wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li span.toctree-expand{font-family:inherit}.fa:before,.icon:before,.rst-content .admonition-title:before,.rst-content .code-block-caption .headerlink:before,.rst-content code.download span:first-child:before,.rst-content dl dt .headerlink:before,.rst-content h1 .headerlink:before,.rst-content h2 .headerlink:before,.rst-content h3 .headerlink:before,.rst-content h4 .headerlink:before,.rst-content h5 .headerlink:before,.rst-content h6 .headerlink:before,.rst-content p.caption .headerlink:before,.rst-content table>caption .headerlink:before,.rst-content tt.download span:first-child:before,.wy-dropdown .caret:before,.wy-inline-validate.wy-inline-validate-danger .wy-input-context:before,.wy-inline-validate.wy-inline-validate-info .wy-input-context:before,.wy-inline-validate.wy-inline-validate-success .wy-input-context:before,.wy-inline-validate.wy-inline-validate-warning .wy-input-context:before,.wy-menu-vertical li.current>a span.toctree-expand:before,.wy-menu-vertical li.on a span.toctree-expand:before,.wy-menu-vertical li span.toctree-expand:before{font-family:FontAwesome;display:inline-block;font-style:normal;font-weight:400;line-height:1;text-decoration:inherit}.rst-content .code-block-caption a .headerlink,.rst-content a .admonition-title,.rst-content code.download a span:first-child,.rst-content dl dt a .headerlink,.rst-content h1 a .headerlink,.rst-content h2 a .headerlink,.rst-content h3 a .headerlink,.rst-content h4 a .headerlink,.rst-content h5 a .headerlink,.rst-content h6 a .headerlink,.rst-content p.caption a .headerlink,.rst-content table>caption a .headerlink,.rst-content tt.download a span:first-child,.wy-menu-vertical li.current>a span.toctree-expand,.wy-menu-vertical li.on a span.toctree-expand,.wy-menu-vertical li a span.toctree-expand,a .fa,a .icon,a .rst-content .admonition-title,a .rst-content .code-block-caption .headerlink,a .rst-content code.download span:first-child,a .rst-content dl dt .headerlink,a .rst-content h1 .headerlink,a .rst-content h2 .headerlink,a .rst-content h3 .headerlink,a .rst-content h4 .headerlink,a .rst-content h5 .headerlink,a .rst-content h6 .headerlink,a .rst-content p.caption .headerlink,a .rst-content table>caption .headerlink,a .rst-content tt.download span:first-child,a .wy-menu-vertical li span.toctree-expand{display:inline-block;text-decoration:inherit}.btn .fa,.btn .icon,.btn .rst-content .admonition-title,.btn .rst-content .code-block-caption .headerlink,.btn .rst-content code.download span:first-child,.btn .rst-content dl dt .headerlink,.btn .rst-content h1 .headerlink,.btn .rst-content h2 .headerlink,.btn .rst-content h3 .headerlink,.btn .rst-content h4 .headerlink,.btn .rst-content h5 .headerlink,.btn .rst-content h6 .headerlink,.btn .rst-content p.caption .headerlink,.btn .rst-content table>caption .headerlink,.btn .rst-content tt.download span:first-child,.btn .wy-menu-vertical li.current>a span.toctree-expand,.btn .wy-menu-vertical li.on a span.toctree-expand,.btn .wy-menu-vertical li span.toctree-expand,.nav .fa,.nav .icon,.nav .rst-content .admonition-title,.nav .rst-content .code-block-caption .headerlink,.nav .rst-content code.download span:first-child,.nav .rst-content dl dt .headerlink,.nav .rst-content h1 .headerlink,.nav .rst-content h2 .headerlink,.nav .rst-content h3 .headerlink,.nav .rst-content h4 .headerlink,.nav .rst-content h5 .headerlink,.nav .rst-content h6 .headerlink,.nav .rst-content p.caption .headerlink,.nav .rst-content table>caption .headerlink,.nav .rst-content tt.download span:first-child,.nav .wy-menu-vertical li.current>a span.toctree-expand,.nav .wy-menu-vertical li.on a span.toctree-expand,.nav .wy-menu-vertical li span.toctree-expand,.rst-content .btn .admonition-title,.rst-content .code-block-caption .btn .headerlink,.rst-content .code-block-caption .nav .headerlink,.rst-content .nav .admonition-title,.rst-content code.download .btn span:first-child,.rst-content code.download .nav span:first-child,.rst-content dl dt .btn .headerlink,.rst-content dl dt .nav .headerlink,.rst-content h1 .btn .headerlink,.rst-content h1 .nav .headerlink,.rst-content h2 .btn .headerlink,.rst-content h2 .nav .headerlink,.rst-content h3 .btn .headerlink,.rst-content h3 .nav .headerlink,.rst-content h4 .btn .headerlink,.rst-content h4 .nav .headerlink,.rst-content h5 .btn .headerlink,.rst-content h5 .nav .headerlink,.rst-content h6 .btn .headerlink,.rst-content h6 .nav .headerlink,.rst-content p.caption .btn .headerlink,.rst-content p.caption .nav .headerlink,.rst-content table>caption .btn .headerlink,.rst-content table>caption .nav .headerlink,.rst-content tt.download .btn span:first-child,.rst-content tt.download .nav span:first-child,.wy-menu-vertical li .btn span.toctree-expand,.wy-menu-vertical li.current>a .btn span.toctree-expand,.wy-menu-vertical li.current>a .nav span.toctree-expand,.wy-menu-vertical li .nav span.toctree-expand,.wy-menu-vertical li.on a .btn span.toctree-expand,.wy-menu-vertical li.on a .nav span.toctree-expand{display:inline}.btn .fa-large.icon,.btn .fa.fa-large,.btn .rst-content .code-block-caption .fa-large.headerlink,.btn .rst-content .fa-large.admonition-title,.btn .rst-content code.download span.fa-large:first-child,.btn .rst-content dl dt .fa-large.headerlink,.btn .rst-content h1 .fa-large.headerlink,.btn .rst-content h2 .fa-large.headerlink,.btn .rst-content h3 .fa-large.headerlink,.btn .rst-content h4 .fa-large.headerlink,.btn .rst-content h5 .fa-large.headerlink,.btn .rst-content h6 .fa-large.headerlink,.btn .rst-content p.caption .fa-large.headerlink,.btn .rst-content table>caption .fa-large.headerlink,.btn .rst-content tt.download span.fa-large:first-child,.btn .wy-menu-vertical li span.fa-large.toctree-expand,.nav .fa-large.icon,.nav .fa.fa-large,.nav .rst-content .code-block-caption .fa-large.headerlink,.nav .rst-content .fa-large.admonition-title,.nav .rst-content code.download span.fa-large:first-child,.nav .rst-content dl dt .fa-large.headerlink,.nav .rst-content h1 .fa-large.headerlink,.nav .rst-content h2 .fa-large.headerlink,.nav .rst-content h3 .fa-large.headerlink,.nav .rst-content h4 .fa-large.headerlink,.nav .rst-content h5 .fa-large.headerlink,.nav .rst-content h6 .fa-large.headerlink,.nav .rst-content p.caption .fa-large.headerlink,.nav .rst-content table>caption .fa-large.headerlink,.nav .rst-content tt.download span.fa-large:first-child,.nav .wy-menu-vertical li span.fa-large.toctree-expand,.rst-content .btn .fa-large.admonition-title,.rst-content .code-block-caption .btn .fa-large.headerlink,.rst-content .code-block-caption .nav .fa-large.headerlink,.rst-content .nav .fa-large.admonition-title,.rst-content code.download .btn span.fa-large:first-child,.rst-content code.download .nav span.fa-large:first-child,.rst-content dl dt .btn .fa-large.headerlink,.rst-content dl dt .nav .fa-large.headerlink,.rst-content h1 .btn .fa-large.headerlink,.rst-content h1 .nav .fa-large.headerlink,.rst-content h2 .btn .fa-large.headerlink,.rst-content h2 .nav .fa-large.headerlink,.rst-content h3 .btn .fa-large.headerlink,.rst-content h3 .nav .fa-large.headerlink,.rst-content h4 .btn .fa-large.headerlink,.rst-content h4 .nav .fa-large.headerlink,.rst-content h5 .btn .fa-large.headerlink,.rst-content h5 .nav .fa-large.headerlink,.rst-content h6 .btn .fa-large.headerlink,.rst-content h6 .nav .fa-large.headerlink,.rst-content p.caption .btn .fa-large.headerlink,.rst-content p.caption .nav .fa-large.headerlink,.rst-content table>caption .btn .fa-large.headerlink,.rst-content table>caption .nav .fa-large.headerlink,.rst-content tt.download .btn span.fa-large:first-child,.rst-content tt.download .nav span.fa-large:first-child,.wy-menu-vertical li .btn span.fa-large.toctree-expand,.wy-menu-vertical li .nav span.fa-large.toctree-expand{line-height:.9em}.btn .fa-spin.icon,.btn .fa.fa-spin,.btn .rst-content .code-block-caption .fa-spin.headerlink,.btn .rst-content .fa-spin.admonition-title,.btn .rst-content code.download span.fa-spin:first-child,.btn .rst-content dl dt .fa-spin.headerlink,.btn .rst-content h1 .fa-spin.headerlink,.btn .rst-content h2 .fa-spin.headerlink,.btn .rst-content h3 .fa-spin.headerlink,.btn .rst-content h4 .fa-spin.headerlink,.btn .rst-content h5 .fa-spin.headerlink,.btn .rst-content h6 .fa-spin.headerlink,.btn .rst-content p.caption .fa-spin.headerlink,.btn .rst-content table>caption .fa-spin.headerlink,.btn .rst-content tt.download span.fa-spin:first-child,.btn .wy-menu-vertical li span.fa-spin.toctree-expand,.nav .fa-spin.icon,.nav .fa.fa-spin,.nav .rst-content .code-block-caption .fa-spin.headerlink,.nav .rst-content .fa-spin.admonition-title,.nav .rst-content code.download span.fa-spin:first-child,.nav .rst-content dl dt .fa-spin.headerlink,.nav .rst-content h1 .fa-spin.headerlink,.nav .rst-content h2 .fa-spin.headerlink,.nav .rst-content h3 .fa-spin.headerlink,.nav .rst-content h4 .fa-spin.headerlink,.nav .rst-content h5 .fa-spin.headerlink,.nav .rst-content h6 .fa-spin.headerlink,.nav .rst-content p.caption .fa-spin.headerlink,.nav .rst-content table>caption .fa-spin.headerlink,.nav .rst-content tt.download span.fa-spin:first-child,.nav .wy-menu-vertical li span.fa-spin.toctree-expand,.rst-content .btn .fa-spin.admonition-title,.rst-content .code-block-caption .btn .fa-spin.headerlink,.rst-content .code-block-caption .nav .fa-spin.headerlink,.rst-content .nav .fa-spin.admonition-title,.rst-content code.download .btn span.fa-spin:first-child,.rst-content code.download .nav span.fa-spin:first-child,.rst-content dl dt .btn .fa-spin.headerlink,.rst-content dl dt .nav .fa-spin.headerlink,.rst-content h1 .btn .fa-spin.headerlink,.rst-content h1 .nav .fa-spin.headerlink,.rst-content h2 .btn .fa-spin.headerlink,.rst-content h2 .nav .fa-spin.headerlink,.rst-content h3 .btn .fa-spin.headerlink,.rst-content h3 .nav .fa-spin.headerlink,.rst-content h4 .btn .fa-spin.headerlink,.rst-content h4 .nav .fa-spin.headerlink,.rst-content h5 .btn .fa-spin.headerlink,.rst-content h5 .nav .fa-spin.headerlink,.rst-content h6 .btn .fa-spin.headerlink,.rst-content h6 .nav .fa-spin.headerlink,.rst-content p.caption .btn .fa-spin.headerlink,.rst-content p.caption .nav .fa-spin.headerlink,.rst-content table>caption .btn .fa-spin.headerlink,.rst-content table>caption .nav .fa-spin.headerlink,.rst-content tt.download .btn span.fa-spin:first-child,.rst-content tt.download .nav span.fa-spin:first-child,.wy-menu-vertical li .btn span.fa-spin.toctree-expand,.wy-menu-vertical li .nav span.fa-spin.toctree-expand{display:inline-block}.btn.fa:before,.btn.icon:before,.rst-content .btn.admonition-title:before,.rst-content .code-block-caption .btn.headerlink:before,.rst-content code.download span.btn:first-child:before,.rst-content dl dt .btn.headerlink:before,.rst-content h1 .btn.headerlink:before,.rst-content h2 .btn.headerlink:before,.rst-content h3 .btn.headerlink:before,.rst-content h4 .btn.headerlink:before,.rst-content h5 .btn.headerlink:before,.rst-content h6 .btn.headerlink:before,.rst-content p.caption .btn.headerlink:before,.rst-content table>caption .btn.headerlink:before,.rst-content tt.download span.btn:first-child:before,.wy-menu-vertical li span.btn.toctree-expand:before{opacity:.5;-webkit-transition:opacity .05s ease-in;-moz-transition:opacity .05s ease-in;transition:opacity .05s ease-in}.btn.fa:hover:before,.btn.icon:hover:before,.rst-content .btn.admonition-title:hover:before,.rst-content .code-block-caption .btn.headerlink:hover:before,.rst-content code.download span.btn:first-child:hover:before,.rst-content dl dt .btn.headerlink:hover:before,.rst-content h1 .btn.headerlink:hover:before,.rst-content h2 .btn.headerlink:hover:before,.rst-content h3 .btn.headerlink:hover:before,.rst-content h4 .btn.headerlink:hover:before,.rst-content h5 .btn.headerlink:hover:before,.rst-content h6 .btn.headerlink:hover:before,.rst-content p.caption .btn.headerlink:hover:before,.rst-content table>caption .btn.headerlink:hover:before,.rst-content tt.download span.btn:first-child:hover:before,.wy-menu-vertical li span.btn.toctree-expand:hover:before{opacity:1}.btn-mini .fa:before,.btn-mini .icon:before,.btn-mini .rst-content .admonition-title:before,.btn-mini .rst-content .code-block-caption .headerlink:before,.btn-mini .rst-content code.download span:first-child:before,.btn-mini .rst-content dl dt .headerlink:before,.btn-mini .rst-content h1 .headerlink:before,.btn-mini .rst-content h2 .headerlink:before,.btn-mini .rst-content h3 .headerlink:before,.btn-mini .rst-content h4 .headerlink:before,.btn-mini .rst-content h5 .headerlink:before,.btn-mini .rst-content h6 .headerlink:before,.btn-mini .rst-content p.caption .headerlink:before,.btn-mini .rst-content table>caption .headerlink:before,.btn-mini .rst-content tt.download span:first-child:before,.btn-mini .wy-menu-vertical li span.toctree-expand:before,.rst-content .btn-mini .admonition-title:before,.rst-content .code-block-caption .btn-mini .headerlink:before,.rst-content code.download .btn-mini span:first-child:before,.rst-content dl dt .btn-mini .headerlink:before,.rst-content h1 .btn-mini .headerlink:before,.rst-content h2 .btn-mini .headerlink:before,.rst-content h3 .btn-mini .headerlink:before,.rst-content h4 .btn-mini .headerlink:before,.rst-content h5 .btn-mini .headerlink:before,.rst-content h6 .btn-mini .headerlink:before,.rst-content p.caption .btn-mini .headerlink:before,.rst-content table>caption .btn-mini .headerlink:before,.rst-content tt.download .btn-mini span:first-child:before,.wy-menu-vertical li .btn-mini span.toctree-expand:before{font-size:14px;vertical-align:-15%}.rst-content .admonition,.rst-content .admonition-todo,.rst-content .attention,.rst-content .caution,.rst-content .danger,.rst-content .error,.rst-content .hint,.rst-content .important,.rst-content .note,.rst-content .seealso,.rst-content .tip,.rst-content .warning,.wy-alert{padding:12px;line-height:24px;margin-bottom:24px;background:#e7f2fa}.rst-content .admonition-title,.wy-alert-title{font-weight:700;display:block;color:#fff;background:#6ab0de;padding:6px 12px;margin:-12px -12px 12px}.rst-content .danger,.rst-content .error,.rst-content .wy-alert-danger.admonition,.rst-content .wy-alert-danger.admonition-todo,.rst-content .wy-alert-danger.attention,.rst-content .wy-alert-danger.caution,.rst-content .wy-alert-danger.hint,.rst-content .wy-alert-danger.important,.rst-content .wy-alert-danger.note,.rst-content .wy-alert-danger.seealso,.rst-content .wy-alert-danger.tip,.rst-content .wy-alert-danger.warning,.wy-alert.wy-alert-danger{background:#fdf3f2}.rst-content .danger .admonition-title,.rst-content .danger .wy-alert-title,.rst-content .error .admonition-title,.rst-content .error .wy-alert-title,.rst-content .wy-alert-danger.admonition-todo .admonition-title,.rst-content .wy-alert-danger.admonition-todo .wy-alert-title,.rst-content .wy-alert-danger.admonition .admonition-title,.rst-content .wy-alert-danger.admonition .wy-alert-title,.rst-content .wy-alert-danger.attention .admonition-title,.rst-content .wy-alert-danger.attention .wy-alert-title,.rst-content .wy-alert-danger.caution .admonition-title,.rst-content .wy-alert-danger.caution .wy-alert-title,.rst-content .wy-alert-danger.hint .admonition-title,.rst-content .wy-alert-danger.hint .wy-alert-title,.rst-content .wy-alert-danger.important .admonition-title,.rst-content .wy-alert-danger.important .wy-alert-title,.rst-content .wy-alert-danger.note .admonition-title,.rst-content .wy-alert-danger.note .wy-alert-title,.rst-content .wy-alert-danger.seealso .admonition-title,.rst-content .wy-alert-danger.seealso .wy-alert-title,.rst-content .wy-alert-danger.tip .admonition-title,.rst-content .wy-alert-danger.tip .wy-alert-title,.rst-content .wy-alert-danger.warning .admonition-title,.rst-content .wy-alert-danger.warning .wy-alert-title,.rst-content .wy-alert.wy-alert-danger .admonition-title,.wy-alert.wy-alert-danger .rst-content .admonition-title,.wy-alert.wy-alert-danger .wy-alert-title{background:#f29f97}.rst-content .admonition-todo,.rst-content .attention,.rst-content .caution,.rst-content .warning,.rst-content .wy-alert-warning.admonition,.rst-content .wy-alert-warning.danger,.rst-content .wy-alert-warning.error,.rst-content .wy-alert-warning.hint,.rst-content .wy-alert-warning.important,.rst-content .wy-alert-warning.note,.rst-content .wy-alert-warning.seealso,.rst-content .wy-alert-warning.tip,.wy-alert.wy-alert-warning{background:#ffedcc}.rst-content .admonition-todo .admonition-title,.rst-content .admonition-todo .wy-alert-title,.rst-content .attention .admonition-title,.rst-content .attention .wy-alert-title,.rst-content .caution .admonition-title,.rst-content .caution .wy-alert-title,.rst-content .warning .admonition-title,.rst-content .warning .wy-alert-title,.rst-content .wy-alert-warning.admonition .admonition-title,.rst-content .wy-alert-warning.admonition .wy-alert-title,.rst-content .wy-alert-warning.danger .admonition-title,.rst-content .wy-alert-warning.danger .wy-alert-title,.rst-content .wy-alert-warning.error .admonition-title,.rst-content .wy-alert-warning.error .wy-alert-title,.rst-content .wy-alert-warning.hint .admonition-title,.rst-content .wy-alert-warning.hint .wy-alert-title,.rst-content .wy-alert-warning.important .admonition-title,.rst-content .wy-alert-warning.important .wy-alert-title,.rst-content .wy-alert-warning.note .admonition-title,.rst-content .wy-alert-warning.note .wy-alert-title,.rst-content .wy-alert-warning.seealso .admonition-title,.rst-content .wy-alert-warning.seealso .wy-alert-title,.rst-content .wy-alert-warning.tip .admonition-title,.rst-content .wy-alert-warning.tip .wy-alert-title,.rst-content .wy-alert.wy-alert-warning .admonition-title,.wy-alert.wy-alert-warning .rst-content .admonition-title,.wy-alert.wy-alert-warning .wy-alert-title{background:#f0b37e}.rst-content .note,.rst-content .seealso,.rst-content .wy-alert-info.admonition,.rst-content .wy-alert-info.admonition-todo,.rst-content .wy-alert-info.attention,.rst-content .wy-alert-info.caution,.rst-content .wy-alert-info.danger,.rst-content .wy-alert-info.error,.rst-content .wy-alert-info.hint,.rst-content .wy-alert-info.important,.rst-content .wy-alert-info.tip,.rst-content .wy-alert-info.warning,.wy-alert.wy-alert-info{background:#e7f2fa}.rst-content .note .admonition-title,.rst-content .note .wy-alert-title,.rst-content .seealso .admonition-title,.rst-content .seealso .wy-alert-title,.rst-content .wy-alert-info.admonition-todo .admonition-title,.rst-content .wy-alert-info.admonition-todo .wy-alert-title,.rst-content .wy-alert-info.admonition .admonition-title,.rst-content .wy-alert-info.admonition .wy-alert-title,.rst-content .wy-alert-info.attention .admonition-title,.rst-content .wy-alert-info.attention .wy-alert-title,.rst-content .wy-alert-info.caution .admonition-title,.rst-content .wy-alert-info.caution .wy-alert-title,.rst-content .wy-alert-info.danger .admonition-title,.rst-content .wy-alert-info.danger .wy-alert-title,.rst-content .wy-alert-info.error .admonition-title,.rst-content .wy-alert-info.error .wy-alert-title,.rst-content .wy-alert-info.hint .admonition-title,.rst-content .wy-alert-info.hint .wy-alert-title,.rst-content .wy-alert-info.important .admonition-title,.rst-content .wy-alert-info.important .wy-alert-title,.rst-content .wy-alert-info.tip .admonition-title,.rst-content .wy-alert-info.tip .wy-alert-title,.rst-content .wy-alert-info.warning .admonition-title,.rst-content .wy-alert-info.warning .wy-alert-title,.rst-content .wy-alert.wy-alert-info .admonition-title,.wy-alert.wy-alert-info .rst-content .admonition-title,.wy-alert.wy-alert-info .wy-alert-title{background:#6ab0de}.rst-content .hint,.rst-content .important,.rst-content .tip,.rst-content .wy-alert-success.admonition,.rst-content .wy-alert-success.admonition-todo,.rst-content .wy-alert-success.attention,.rst-content .wy-alert-success.caution,.rst-content .wy-alert-success.danger,.rst-content .wy-alert-success.error,.rst-content .wy-alert-success.note,.rst-content .wy-alert-success.seealso,.rst-content .wy-alert-success.warning,.wy-alert.wy-alert-success{background:#dbfaf4}.rst-content .hint .admonition-title,.rst-content .hint .wy-alert-title,.rst-content .important .admonition-title,.rst-content .important .wy-alert-title,.rst-content .tip .admonition-title,.rst-content .tip .wy-alert-title,.rst-content .wy-alert-success.admonition-todo .admonition-title,.rst-content .wy-alert-success.admonition-todo .wy-alert-title,.rst-content .wy-alert-success.admonition .admonition-title,.rst-content .wy-alert-success.admonition .wy-alert-title,.rst-content .wy-alert-success.attention .admonition-title,.rst-content .wy-alert-success.attention .wy-alert-title,.rst-content .wy-alert-success.caution .admonition-title,.rst-content .wy-alert-success.caution .wy-alert-title,.rst-content .wy-alert-success.danger .admonition-title,.rst-content .wy-alert-success.danger .wy-alert-title,.rst-content .wy-alert-success.error .admonition-title,.rst-content .wy-alert-success.error .wy-alert-title,.rst-content .wy-alert-success.note .admonition-title,.rst-content .wy-alert-success.note .wy-alert-title,.rst-content .wy-alert-success.seealso .admonition-title,.rst-content .wy-alert-success.seealso .wy-alert-title,.rst-content .wy-alert-success.warning .admonition-title,.rst-content .wy-alert-success.warning .wy-alert-title,.rst-content .wy-alert.wy-alert-success .admonition-title,.wy-alert.wy-alert-success .rst-content .admonition-title,.wy-alert.wy-alert-success .wy-alert-title{background:#1abc9c}.rst-content .wy-alert-neutral.admonition,.rst-content .wy-alert-neutral.admonition-todo,.rst-content .wy-alert-neutral.attention,.rst-content .wy-alert-neutral.caution,.rst-content .wy-alert-neutral.danger,.rst-content .wy-alert-neutral.error,.rst-content .wy-alert-neutral.hint,.rst-content .wy-alert-neutral.important,.rst-content .wy-alert-neutral.note,.rst-content .wy-alert-neutral.seealso,.rst-content .wy-alert-neutral.tip,.rst-content .wy-alert-neutral.warning,.wy-alert.wy-alert-neutral{background:#f3f6f6}.rst-content .wy-alert-neutral.admonition-todo .admonition-title,.rst-content .wy-alert-neutral.admonition-todo .wy-alert-title,.rst-content .wy-alert-neutral.admonition .admonition-title,.rst-content .wy-alert-neutral.admonition .wy-alert-title,.rst-content .wy-alert-neutral.attention .admonition-title,.rst-content .wy-alert-neutral.attention .wy-alert-title,.rst-content .wy-alert-neutral.caution .admonition-title,.rst-content .wy-alert-neutral.caution .wy-alert-title,.rst-content .wy-alert-neutral.danger .admonition-title,.rst-content .wy-alert-neutral.danger .wy-alert-title,.rst-content .wy-alert-neutral.error .admonition-title,.rst-content .wy-alert-neutral.error .wy-alert-title,.rst-content .wy-alert-neutral.hint .admonition-title,.rst-content .wy-alert-neutral.hint .wy-alert-title,.rst-content .wy-alert-neutral.important .admonition-title,.rst-content .wy-alert-neutral.important .wy-alert-title,.rst-content .wy-alert-neutral.note .admonition-title,.rst-content .wy-alert-neutral.note .wy-alert-title,.rst-content .wy-alert-neutral.seealso .admonition-title,.rst-content .wy-alert-neutral.seealso .wy-alert-title,.rst-content .wy-alert-neutral.tip .admonition-title,.rst-content .wy-alert-neutral.tip .wy-alert-title,.rst-content .wy-alert-neutral.warning .admonition-title,.rst-content .wy-alert-neutral.warning .wy-alert-title,.rst-content .wy-alert.wy-alert-neutral .admonition-title,.wy-alert.wy-alert-neutral .rst-content .admonition-title,.wy-alert.wy-alert-neutral .wy-alert-title{color:#404040;background:#e1e4e5}.rst-content .wy-alert-neutral.admonition-todo a,.rst-content .wy-alert-neutral.admonition a,.rst-content .wy-alert-neutral.attention a,.rst-content .wy-alert-neutral.caution a,.rst-content .wy-alert-neutral.danger a,.rst-content .wy-alert-neutral.error a,.rst-content .wy-alert-neutral.hint a,.rst-content .wy-alert-neutral.important a,.rst-content .wy-alert-neutral.note a,.rst-content .wy-alert-neutral.seealso a,.rst-content .wy-alert-neutral.tip a,.rst-content .wy-alert-neutral.warning a,.wy-alert.wy-alert-neutral a{color:#2980b9}.rst-content .admonition-todo p:last-child,.rst-content .admonition p:last-child,.rst-content .attention p:last-child,.rst-content .caution p:last-child,.rst-content .danger p:last-child,.rst-content .error p:last-child,.rst-content .hint p:last-child,.rst-content .important p:last-child,.rst-content .note p:last-child,.rst-content .seealso p:last-child,.rst-content .tip p:last-child,.rst-content .warning p:last-child,.wy-alert p:last-child{margin-bottom:0}.wy-tray-container{position:fixed;bottom:0;left:0;z-index:600}.wy-tray-container li{display:block;width:300px;background:transparent;color:#fff;text-align:center;box-shadow:0 5px 5px 0 rgba(0,0,0,.1);padding:0 24px;min-width:20%;opacity:0;height:0;line-height:56px;overflow:hidden;-webkit-transition:all .3s ease-in;-moz-transition:all .3s ease-in;transition:all .3s ease-in}.wy-tray-container li.wy-tray-item-success{background:#27ae60}.wy-tray-container li.wy-tray-item-info{background:#2980b9}.wy-tray-container li.wy-tray-item-warning{background:#e67e22}.wy-tray-container li.wy-tray-item-danger{background:#e74c3c}.wy-tray-container li.on{opacity:1;height:56px}@media screen and (max-width:768px){.wy-tray-container{bottom:auto;top:0;width:100%}.wy-tray-container li{width:100%}}button{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle;cursor:pointer;line-height:normal;-webkit-appearance:button;*overflow:visible}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}button[disabled]{cursor:default}.btn{display:inline-block;border-radius:2px;line-height:normal;white-space:nowrap;text-align:center;cursor:pointer;font-size:100%;padding:6px 12px 8px;color:#fff;border:1px solid rgba(0,0,0,.1);background-color:#27ae60;text-decoration:none;font-weight:400;font-family:Lato,proxima-nova,Helvetica Neue,Arial,sans-serif;box-shadow:inset 0 1px 2px -1px hsla(0,0%,100%,.5),inset 0 -2px 0 0 rgba(0,0,0,.1);outline-none:false;vertical-align:middle;*display:inline;zoom:1;-webkit-user-drag:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-transition:all .1s linear;-moz-transition:all .1s linear;transition:all .1s linear}.btn-hover{background:#2e8ece;color:#fff}.btn:hover{background:#2cc36b;color:#fff}.btn:focus{background:#2cc36b;outline:0}.btn:active{box-shadow:inset 0 -1px 0 0 rgba(0,0,0,.05),inset 0 2px 0 0 rgba(0,0,0,.1);padding:8px 12px 6px}.btn:visited{color:#fff}.btn-disabled,.btn-disabled:active,.btn-disabled:focus,.btn-disabled:hover,.btn:disabled{background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);filter:alpha(opacity=40);opacity:.4;cursor:not-allowed;box-shadow:none}.btn::-moz-focus-inner{padding:0;border:0}.btn-small{font-size:80%}.btn-info{background-color:#2980b9!important}.btn-info:hover{background-color:#2e8ece!important}.btn-neutral{background-color:#f3f6f6!important;color:#404040!important}.btn-neutral:hover{background-color:#e5ebeb!important;color:#404040}.btn-neutral:visited{color:#404040!important}.btn-success{background-color:#27ae60!important}.btn-success:hover{background-color:#295!important}.btn-danger{background-color:#e74c3c!important}.btn-danger:hover{background-color:#ea6153!important}.btn-warning{background-color:#e67e22!important}.btn-warning:hover{background-color:#e98b39!important}.btn-invert{background-color:#222}.btn-invert:hover{background-color:#2f2f2f!important}.btn-link{background-color:transparent!important;color:#2980b9;box-shadow:none;border-color:transparent!important}.btn-link:active,.btn-link:hover{background-color:transparent!important;color:#409ad5!important;box-shadow:none}.btn-link:visited{color:#9b59b6}.wy-btn-group .btn,.wy-control .btn{vertical-align:middle}.wy-btn-group{margin-bottom:24px;*zoom:1}.wy-btn-group:after,.wy-btn-group:before{display:table;content:""}.wy-btn-group:after{clear:both}.wy-dropdown{position:relative;display:inline-block}.wy-dropdown-active .wy-dropdown-menu{display:block}.wy-dropdown-menu{position:absolute;left:0;display:none;float:left;top:100%;min-width:100%;background:#fcfcfc;z-index:100;border:1px solid #cfd7dd;box-shadow:0 2px 2px 0 rgba(0,0,0,.1);padding:12px}.wy-dropdown-menu>dd>a{display:block;clear:both;color:#404040;white-space:nowrap;font-size:90%;padding:0 12px;cursor:pointer}.wy-dropdown-menu>dd>a:hover{background:#2980b9;color:#fff}.wy-dropdown-menu>dd.divider{border-top:1px solid #cfd7dd;margin:6px 0}.wy-dropdown-menu>dd.search{padding-bottom:12px}.wy-dropdown-menu>dd.search input[type=search]{width:100%}.wy-dropdown-menu>dd.call-to-action{background:#e3e3e3;text-transform:uppercase;font-weight:500;font-size:80%}.wy-dropdown-menu>dd.call-to-action:hover{background:#e3e3e3}.wy-dropdown-menu>dd.call-to-action .btn{color:#fff}.wy-dropdown.wy-dropdown-up .wy-dropdown-menu{bottom:100%;top:auto;left:auto;right:0}.wy-dropdown.wy-dropdown-bubble .wy-dropdown-menu{background:#fcfcfc;margin-top:2px}.wy-dropdown.wy-dropdown-bubble .wy-dropdown-menu a{padding:6px 12px}.wy-dropdown.wy-dropdown-bubble .wy-dropdown-menu a:hover{background:#2980b9;color:#fff}.wy-dropdown.wy-dropdown-left .wy-dropdown-menu{right:0;left:auto;text-align:right}.wy-dropdown-arrow:before{content:" ";border-bottom:5px solid #f5f5f5;border-left:5px solid transparent;border-right:5px solid transparent;position:absolute;display:block;top:-4px;left:50%;margin-left:-3px}.wy-dropdown-arrow.wy-dropdown-arrow-left:before{left:11px}.wy-form-stacked select{display:block}.wy-form-aligned .wy-help-inline,.wy-form-aligned input,.wy-form-aligned label,.wy-form-aligned select,.wy-form-aligned textarea{display:inline-block;*display:inline;*zoom:1;vertical-align:middle}.wy-form-aligned .wy-control-group>label{display:inline-block;vertical-align:middle;width:10em;margin:6px 12px 0 0;float:left}.wy-form-aligned .wy-control{float:left}.wy-form-aligned .wy-control label{display:block}.wy-form-aligned .wy-control select{margin-top:6px}fieldset{margin:0}fieldset,legend{border:0;padding:0}legend{width:100%;white-space:normal;margin-bottom:24px;font-size:150%;*margin-left:-7px}label,legend{display:block}label{margin:0 0 .3125em;color:#333;font-size:90%}input,select,textarea{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle}.wy-control-group{margin-bottom:24px;max-width:1200px;margin-left:auto;margin-right:auto;*zoom:1}.wy-control-group:after,.wy-control-group:before{display:table;content:""}.wy-control-group:after{clear:both}.wy-control-group.wy-control-group-required>label:after{content:" *";color:#e74c3c}.wy-control-group .wy-form-full,.wy-control-group .wy-form-halves,.wy-control-group .wy-form-thirds{padding-bottom:12px}.wy-control-group .wy-form-full input[type=color],.wy-control-group .wy-form-full input[type=date],.wy-control-group .wy-form-full input[type=datetime-local],.wy-control-group .wy-form-full input[type=datetime],.wy-control-group .wy-form-full input[type=email],.wy-control-group .wy-form-full input[type=month],.wy-control-group .wy-form-full input[type=number],.wy-control-group .wy-form-full input[type=password],.wy-control-group .wy-form-full input[type=search],.wy-control-group .wy-form-full input[type=tel],.wy-control-group .wy-form-full input[type=text],.wy-control-group .wy-form-full input[type=time],.wy-control-group .wy-form-full input[type=url],.wy-control-group .wy-form-full input[type=week],.wy-control-group .wy-form-full select,.wy-control-group .wy-form-halves input[type=color],.wy-control-group .wy-form-halves input[type=date],.wy-control-group .wy-form-halves input[type=datetime-local],.wy-control-group .wy-form-halves input[type=datetime],.wy-control-group .wy-form-halves input[type=email],.wy-control-group .wy-form-halves input[type=month],.wy-control-group .wy-form-halves input[type=number],.wy-control-group .wy-form-halves input[type=password],.wy-control-group .wy-form-halves input[type=search],.wy-control-group .wy-form-halves input[type=tel],.wy-control-group .wy-form-halves input[type=text],.wy-control-group .wy-form-halves input[type=time],.wy-control-group .wy-form-halves input[type=url],.wy-control-group .wy-form-halves input[type=week],.wy-control-group .wy-form-halves select,.wy-control-group .wy-form-thirds input[type=color],.wy-control-group .wy-form-thirds input[type=date],.wy-control-group .wy-form-thirds input[type=datetime-local],.wy-control-group .wy-form-thirds input[type=datetime],.wy-control-group .wy-form-thirds input[type=email],.wy-control-group .wy-form-thirds input[type=month],.wy-control-group .wy-form-thirds input[type=number],.wy-control-group .wy-form-thirds input[type=password],.wy-control-group .wy-form-thirds input[type=search],.wy-control-group .wy-form-thirds input[type=tel],.wy-control-group .wy-form-thirds input[type=text],.wy-control-group .wy-form-thirds input[type=time],.wy-control-group .wy-form-thirds input[type=url],.wy-control-group .wy-form-thirds input[type=week],.wy-control-group .wy-form-thirds select{width:100%}.wy-control-group .wy-form-full{float:left;display:block;width:100%;margin-right:0}.wy-control-group .wy-form-full:last-child{margin-right:0}.wy-control-group .wy-form-halves{float:left;display:block;margin-right:2.35765%;width:48.82117%}.wy-control-group .wy-form-halves:last-child,.wy-control-group .wy-form-halves:nth-of-type(2n){margin-right:0}.wy-control-group .wy-form-halves:nth-of-type(odd){clear:left}.wy-control-group .wy-form-thirds{float:left;display:block;margin-right:2.35765%;width:31.76157%}.wy-control-group .wy-form-thirds:last-child,.wy-control-group .wy-form-thirds:nth-of-type(3n){margin-right:0}.wy-control-group .wy-form-thirds:nth-of-type(3n+1){clear:left}.wy-control-group.wy-control-group-no-input .wy-control,.wy-control-no-input{margin:6px 0 0;font-size:90%}.wy-control-no-input{display:inline-block}.wy-control-group.fluid-input input[type=color],.wy-control-group.fluid-input input[type=date],.wy-control-group.fluid-input input[type=datetime-local],.wy-control-group.fluid-input input[type=datetime],.wy-control-group.fluid-input input[type=email],.wy-control-group.fluid-input input[type=month],.wy-control-group.fluid-input input[type=number],.wy-control-group.fluid-input input[type=password],.wy-control-group.fluid-input input[type=search],.wy-control-group.fluid-input input[type=tel],.wy-control-group.fluid-input input[type=text],.wy-control-group.fluid-input input[type=time],.wy-control-group.fluid-input input[type=url],.wy-control-group.fluid-input input[type=week]{width:100%}.wy-form-message-inline{padding-left:.3em;color:#666;font-size:90%}.wy-form-message{display:block;color:#999;font-size:70%;margin-top:.3125em;font-style:italic}.wy-form-message p{font-size:inherit;font-style:italic;margin-bottom:6px}.wy-form-message p:last-child{margin-bottom:0}input{line-height:normal}input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer;font-family:Lato,proxima-nova,Helvetica Neue,Arial,sans-serif;*overflow:visible}input[type=color],input[type=date],input[type=datetime-local],input[type=datetime],input[type=email],input[type=month],input[type=number],input[type=password],input[type=search],input[type=tel],input[type=text],input[type=time],input[type=url],input[type=week]{-webkit-appearance:none;padding:6px;display:inline-block;border:1px solid #ccc;font-size:80%;font-family:Lato,proxima-nova,Helvetica Neue,Arial,sans-serif;box-shadow:inset 0 1px 3px #ddd;border-radius:0;-webkit-transition:border .3s linear;-moz-transition:border .3s linear;transition:border .3s linear}input[type=datetime-local]{padding:.34375em .625em}input[disabled]{cursor:default}input[type=checkbox],input[type=radio]{padding:0;margin-right:.3125em;*height:13px;*width:13px}input[type=checkbox],input[type=radio],input[type=search]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}input[type=color]:focus,input[type=date]:focus,input[type=datetime-local]:focus,input[type=datetime]:focus,input[type=email]:focus,input[type=month]:focus,input[type=number]:focus,input[type=password]:focus,input[type=search]:focus,input[type=tel]:focus,input[type=text]:focus,input[type=time]:focus,input[type=url]:focus,input[type=week]:focus{outline:0;outline:thin dotted\9;border-color:#333}input.no-focus:focus{border-color:#ccc!important}input[type=checkbox]:focus,input[type=file]:focus,input[type=radio]:focus{outline:thin dotted #333;outline:1px auto #129fea}input[type=color][disabled],input[type=date][disabled],input[type=datetime-local][disabled],input[type=datetime][disabled],input[type=email][disabled],input[type=month][disabled],input[type=number][disabled],input[type=password][disabled],input[type=search][disabled],input[type=tel][disabled],input[type=text][disabled],input[type=time][disabled],input[type=url][disabled],input[type=week][disabled]{cursor:not-allowed;background-color:#fafafa}input:focus:invalid,select:focus:invalid,textarea:focus:invalid{color:#e74c3c;border:1px solid #e74c3c}input:focus:invalid:focus,select:focus:invalid:focus,textarea:focus:invalid:focus{border-color:#e74c3c}input[type=checkbox]:focus:invalid:focus,input[type=file]:focus:invalid:focus,input[type=radio]:focus:invalid:focus{outline-color:#e74c3c}input.wy-input-large{padding:12px;font-size:100%}textarea{overflow:auto;vertical-align:top;width:100%;font-family:Lato,proxima-nova,Helvetica Neue,Arial,sans-serif}select,textarea{padding:.5em .625em;display:inline-block;border:1px solid #ccc;font-size:80%;box-shadow:inset 0 1px 3px #ddd;-webkit-transition:border .3s linear;-moz-transition:border .3s linear;transition:border .3s linear}select{border:1px solid #ccc;background-color:#fff}select[multiple]{height:auto}select:focus,textarea:focus{outline:0}input[readonly],select[disabled],select[readonly],textarea[disabled],textarea[readonly]{cursor:not-allowed;background-color:#fafafa}input[type=checkbox][disabled],input[type=radio][disabled]{cursor:not-allowed}.wy-checkbox,.wy-radio{margin:6px 0;color:#404040;display:block}.wy-checkbox input,.wy-radio input{vertical-align:baseline}.wy-form-message-inline{display:inline-block;*display:inline;*zoom:1;vertical-align:middle}.wy-input-prefix,.wy-input-suffix{white-space:nowrap;padding:6px}.wy-input-prefix .wy-input-context,.wy-input-suffix .wy-input-context{line-height:27px;padding:0 8px;display:inline-block;font-size:80%;background-color:#f3f6f6;border:1px solid #ccc;color:#999}.wy-input-suffix .wy-input-context{border-left:0}.wy-input-prefix .wy-input-context{border-right:0}.wy-switch{position:relative;display:block;height:24px;margin-top:12px;cursor:pointer}.wy-switch:before{left:0;top:0;width:36px;height:12px;background:#ccc}.wy-switch:after,.wy-switch:before{position:absolute;content:"";display:block;border-radius:4px;-webkit-transition:all .2s ease-in-out;-moz-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.wy-switch:after{width:18px;height:18px;background:#999;left:-3px;top:-3px}.wy-switch span{position:absolute;left:48px;display:block;font-size:12px;color:#ccc;line-height:1}.wy-switch.active:before{background:#1e8449}.wy-switch.active:after{left:24px;background:#27ae60}.wy-switch.disabled{cursor:not-allowed;opacity:.8}.wy-control-group.wy-control-group-error .wy-form-message,.wy-control-group.wy-control-group-error>label{color:#e74c3c}.wy-control-group.wy-control-group-error input[type=color],.wy-control-group.wy-control-group-error input[type=date],.wy-control-group.wy-control-group-error input[type=datetime-local],.wy-control-group.wy-control-group-error input[type=datetime],.wy-control-group.wy-control-group-error input[type=email],.wy-control-group.wy-control-group-error input[type=month],.wy-control-group.wy-control-group-error input[type=number],.wy-control-group.wy-control-group-error input[type=password],.wy-control-group.wy-control-group-error input[type=search],.wy-control-group.wy-control-group-error input[type=tel],.wy-control-group.wy-control-group-error input[type=text],.wy-control-group.wy-control-group-error input[type=time],.wy-control-group.wy-control-group-error input[type=url],.wy-control-group.wy-control-group-error input[type=week],.wy-control-group.wy-control-group-error textarea{border:1px solid #e74c3c}.wy-inline-validate{white-space:nowrap}.wy-inline-validate .wy-input-context{padding:.5em .625em;display:inline-block;font-size:80%}.wy-inline-validate.wy-inline-validate-success .wy-input-context{color:#27ae60}.wy-inline-validate.wy-inline-validate-danger .wy-input-context{color:#e74c3c}.wy-inline-validate.wy-inline-validate-warning .wy-input-context{color:#e67e22}.wy-inline-validate.wy-inline-validate-info .wy-input-context{color:#2980b9}.rotate-90{-webkit-transform:rotate(90deg);-moz-transform:rotate(90deg);-ms-transform:rotate(90deg);-o-transform:rotate(90deg);transform:rotate(90deg)}.rotate-180{-webkit-transform:rotate(180deg);-moz-transform:rotate(180deg);-ms-transform:rotate(180deg);-o-transform:rotate(180deg);transform:rotate(180deg)}.rotate-270{-webkit-transform:rotate(270deg);-moz-transform:rotate(270deg);-ms-transform:rotate(270deg);-o-transform:rotate(270deg);transform:rotate(270deg)}.mirror{-webkit-transform:scaleX(-1);-moz-transform:scaleX(-1);-ms-transform:scaleX(-1);-o-transform:scaleX(-1);transform:scaleX(-1)}.mirror.rotate-90{-webkit-transform:scaleX(-1) rotate(90deg);-moz-transform:scaleX(-1) rotate(90deg);-ms-transform:scaleX(-1) rotate(90deg);-o-transform:scaleX(-1) rotate(90deg);transform:scaleX(-1) rotate(90deg)}.mirror.rotate-180{-webkit-transform:scaleX(-1) rotate(180deg);-moz-transform:scaleX(-1) rotate(180deg);-ms-transform:scaleX(-1) rotate(180deg);-o-transform:scaleX(-1) rotate(180deg);transform:scaleX(-1) rotate(180deg)}.mirror.rotate-270{-webkit-transform:scaleX(-1) rotate(270deg);-moz-transform:scaleX(-1) rotate(270deg);-ms-transform:scaleX(-1) rotate(270deg);-o-transform:scaleX(-1) rotate(270deg);transform:scaleX(-1) rotate(270deg)}@media only screen and (max-width:480px){.wy-form button[type=submit]{margin:.7em 0 0}.wy-form input[type=color],.wy-form input[type=date],.wy-form input[type=datetime-local],.wy-form input[type=datetime],.wy-form input[type=email],.wy-form input[type=month],.wy-form input[type=number],.wy-form input[type=password],.wy-form input[type=search],.wy-form input[type=tel],.wy-form input[type=text],.wy-form input[type=time],.wy-form input[type=url],.wy-form input[type=week],.wy-form label{margin-bottom:.3em;display:block}.wy-form input[type=color],.wy-form input[type=date],.wy-form input[type=datetime-local],.wy-form input[type=datetime],.wy-form input[type=email],.wy-form input[type=month],.wy-form input[type=number],.wy-form input[type=password],.wy-form input[type=search],.wy-form input[type=tel],.wy-form input[type=time],.wy-form input[type=url],.wy-form input[type=week]{margin-bottom:0}.wy-form-aligned .wy-control-group label{margin-bottom:.3em;text-align:left;display:block;width:100%}.wy-form-aligned .wy-control{margin:1.5em 0 0}.wy-form-message,.wy-form-message-inline,.wy-form .wy-help-inline{display:block;font-size:80%;padding:6px 0}}@media screen and (max-width:768px){.tablet-hide{display:none}}@media screen and (max-width:480px){.mobile-hide{display:none}}.float-left{float:left}.float-right{float:right}.full-width{width:100%}.rst-content table.docutils,.rst-content table.field-list,.wy-table{border-collapse:collapse;border-spacing:0;empty-cells:show;margin-bottom:24px}.rst-content table.docutils caption,.rst-content table.field-list caption,.wy-table caption{color:#000;font:italic 85%/1 arial,sans-serif;padding:1em 0;text-align:center}.rst-content table.docutils td,.rst-content table.docutils th,.rst-content table.field-list td,.rst-content table.field-list th,.wy-table td,.wy-table th{font-size:90%;margin:0;overflow:visible;padding:8px 16px}.rst-content table.docutils td:first-child,.rst-content table.docutils th:first-child,.rst-content table.field-list td:first-child,.rst-content table.field-list th:first-child,.wy-table td:first-child,.wy-table th:first-child{border-left-width:0}.rst-content table.docutils thead,.rst-content table.field-list thead,.wy-table thead{color:#000;text-align:left;vertical-align:bottom;white-space:nowrap}.rst-content table.docutils thead th,.rst-content table.field-list thead th,.wy-table thead th{font-weight:700;border-bottom:2px solid #e1e4e5}.rst-content table.docutils td,.rst-content table.field-list td,.wy-table td{background-color:transparent;vertical-align:middle}.rst-content table.docutils td p,.rst-content table.field-list td p,.wy-table td p{line-height:18px}.rst-content table.docutils td p:last-child,.rst-content table.field-list td p:last-child,.wy-table td p:last-child{margin-bottom:0}.rst-content table.docutils .wy-table-cell-min,.rst-content table.field-list .wy-table-cell-min,.wy-table .wy-table-cell-min{width:1%;padding-right:0}.rst-content table.docutils .wy-table-cell-min input[type=checkbox],.rst-content table.field-list .wy-table-cell-min input[type=checkbox],.wy-table .wy-table-cell-min input[type=checkbox]{margin:0}.wy-table-secondary{color:grey;font-size:90%}.wy-table-tertiary{color:grey;font-size:80%}.rst-content table.docutils:not(.field-list) tr:nth-child(2n-1) td,.wy-table-backed,.wy-table-odd td,.wy-table-striped tr:nth-child(2n-1) td{background-color:#f3f6f6}.rst-content table.docutils,.wy-table-bordered-all{border:1px solid #e1e4e5}.rst-content table.docutils td,.wy-table-bordered-all td{border-bottom:1px solid #e1e4e5;border-left:1px solid #e1e4e5}.rst-content table.docutils tbody>tr:last-child td,.wy-table-bordered-all tbody>tr:last-child td{border-bottom-width:0}.wy-table-bordered{border:1px solid #e1e4e5}.wy-table-bordered-rows td{border-bottom:1px solid #e1e4e5}.wy-table-bordered-rows tbody>tr:last-child td{border-bottom-width:0}.wy-table-horizontal td,.wy-table-horizontal th{border-width:0 0 1px;border-bottom:1px solid #e1e4e5}.wy-table-horizontal tbody>tr:last-child td{border-bottom-width:0}.wy-table-responsive{margin-bottom:24px;max-width:100%;overflow:auto}.wy-table-responsive table{margin-bottom:0!important}.wy-table-responsive table td,.wy-table-responsive table th{white-space:nowrap}a{color:#2980b9;text-decoration:none;cursor:pointer}a:hover{color:#3091d1}a:visited{color:#9b59b6}html{height:100%}body,html{overflow-x:hidden}body{font-family:Lato,proxima-nova,Helvetica Neue,Arial,sans-serif;font-weight:400;color:#404040;min-height:100%;background:#edf0f2}.wy-text-left{text-align:left}.wy-text-center{text-align:center}.wy-text-right{text-align:right}.wy-text-large{font-size:120%}.wy-text-normal{font-size:100%}.wy-text-small,small{font-size:80%}.wy-text-strike{text-decoration:line-through}.wy-text-warning{color:#e67e22!important}a.wy-text-warning:hover{color:#eb9950!important}.wy-text-info{color:#2980b9!important}a.wy-text-info:hover{color:#409ad5!important}.wy-text-success{color:#27ae60!important}a.wy-text-success:hover{color:#36d278!important}.wy-text-danger{color:#e74c3c!important}a.wy-text-danger:hover{color:#ed7669!important}.wy-text-neutral{color:#404040!important}a.wy-text-neutral:hover{color:#595959!important}.rst-content .toctree-wrapper>p.caption,h1,h2,h3,h4,h5,h6,legend{margin-top:0;font-weight:700;font-family:Roboto Slab,ff-tisa-web-pro,Georgia,Arial,sans-serif}p{line-height:24px;font-size:16px;margin:0 0 24px}h1{font-size:175%}.rst-content .toctree-wrapper>p.caption,h2{font-size:150%}h3{font-size:125%}h4{font-size:115%}h5{font-size:110%}h6{font-size:100%}hr{display:block;height:1px;border:0;border-top:1px solid #e1e4e5;margin:24px 0;padding:0}.rst-content code,.rst-content tt,code{white-space:nowrap;max-width:100%;background:#fff;border:1px solid #e1e4e5;font-size:75%;padding:0 5px;font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,Courier,monospace;color:#e74c3c;overflow-x:auto}.rst-content tt.code-large,code.code-large{font-size:90%}.rst-content .section ul,.rst-content .toctree-wrapper ul,.wy-plain-list-disc,article ul{list-style:disc;line-height:24px;margin-bottom:24px}.rst-content .section ul li,.rst-content .toctree-wrapper ul li,.wy-plain-list-disc li,article ul li{list-style:disc;margin-left:24px}.rst-content .section ul li p:last-child,.rst-content .section ul li ul,.rst-content .toctree-wrapper ul li p:last-child,.rst-content .toctree-wrapper ul li ul,.wy-plain-list-disc li p:last-child,.wy-plain-list-disc li ul,article ul li p:last-child,article ul li ul{margin-bottom:0}.rst-content .section ul li li,.rst-content .toctree-wrapper ul li li,.wy-plain-list-disc li li,article ul li li{list-style:circle}.rst-content .section ul li li li,.rst-content .toctree-wrapper ul li li li,.wy-plain-list-disc li li li,article ul li li li{list-style:square}.rst-content .section ul li ol li,.rst-content .toctree-wrapper ul li ol li,.wy-plain-list-disc li ol li,article ul li ol li{list-style:decimal}.rst-content .section ol,.rst-content ol.arabic,.wy-plain-list-decimal,article ol{list-style:decimal;line-height:24px;margin-bottom:24px}.rst-content .section ol li,.rst-content ol.arabic li,.wy-plain-list-decimal li,article ol li{list-style:decimal;margin-left:24px}.rst-content .section ol li p:last-child,.rst-content .section ol li ul,.rst-content ol.arabic li p:last-child,.rst-content ol.arabic li ul,.wy-plain-list-decimal li p:last-child,.wy-plain-list-decimal li ul,article ol li p:last-child,article ol li ul{margin-bottom:0}.rst-content .section ol li ul li,.rst-content ol.arabic li ul li,.wy-plain-list-decimal li ul li,article ol li ul li{list-style:disc}.wy-breadcrumbs{*zoom:1}.wy-breadcrumbs:after,.wy-breadcrumbs:before{display:table;content:""}.wy-breadcrumbs:after{clear:both}.wy-breadcrumbs li{display:inline-block}.wy-breadcrumbs li.wy-breadcrumbs-aside{float:right}.wy-breadcrumbs li a{display:inline-block;padding:5px}.wy-breadcrumbs li a:first-child{padding-left:0}.rst-content .wy-breadcrumbs li tt,.wy-breadcrumbs li .rst-content tt,.wy-breadcrumbs li code{padding:5px;border:none;background:none}.rst-content .wy-breadcrumbs li tt.literal,.wy-breadcrumbs li .rst-content tt.literal,.wy-breadcrumbs li code.literal{color:#404040}.wy-breadcrumbs-extra{margin-bottom:0;color:#b3b3b3;font-size:80%;display:inline-block}@media screen and (max-width:480px){.wy-breadcrumbs-extra,.wy-breadcrumbs li.wy-breadcrumbs-aside{display:none}}@media print{.wy-breadcrumbs li.wy-breadcrumbs-aside{display:none}}html{font-size:16px}.wy-affix{position:fixed;top:1.618em}.wy-menu a:hover{text-decoration:none}.wy-menu-horiz{*zoom:1}.wy-menu-horiz:after,.wy-menu-horiz:before{display:table;content:""}.wy-menu-horiz:after{clear:both}.wy-menu-horiz li,.wy-menu-horiz ul{display:inline-block}.wy-menu-horiz li:hover{background:hsla(0,0%,100%,.1)}.wy-menu-horiz li.divide-left{border-left:1px solid #404040}.wy-menu-horiz li.divide-right{border-right:1px solid #404040}.wy-menu-horiz a{height:32px;display:inline-block;line-height:32px;padding:0 16px}.wy-menu-vertical{width:300px}.wy-menu-vertical header,.wy-menu-vertical p.caption{color:#55a5d9;height:32px;line-height:32px;padding:0 1.618em;margin:12px 0 0;display:block;font-weight:700;text-transform:uppercase;font-size:85%;white-space:nowrap}.wy-menu-vertical ul{margin-bottom:0}.wy-menu-vertical li.divide-top{border-top:1px solid #404040}.wy-menu-vertical li.divide-bottom{border-bottom:1px solid #404040}.wy-menu-vertical li.current{background:#e3e3e3}.wy-menu-vertical li.current a{color:grey;border-right:1px solid #c9c9c9;padding:.4045em 2.427em}.wy-menu-vertical li.current a:hover{background:#d6d6d6}.rst-content .wy-menu-vertical li tt,.wy-menu-vertical li .rst-content tt,.wy-menu-vertical li code{border:none;background:inherit;color:inherit;padding-left:0;padding-right:0}.wy-menu-vertical li span.toctree-expand{display:block;float:left;margin-left:-1.2em;font-size:.8em;line-height:1.6em;color:#4d4d4d}.wy-menu-vertical li.current>a,.wy-menu-vertical li.on a{color:#404040;font-weight:700;position:relative;background:#fcfcfc;border:none;padding:.4045em 1.618em}.wy-menu-vertical li.current>a:hover,.wy-menu-vertical li.on a:hover{background:#fcfcfc}.wy-menu-vertical li.current>a:hover span.toctree-expand,.wy-menu-vertical li.on a:hover span.toctree-expand{color:grey}.wy-menu-vertical li.current>a span.toctree-expand,.wy-menu-vertical li.on a span.toctree-expand{display:block;font-size:.8em;line-height:1.6em;color:#333}.wy-menu-vertical li.toctree-l1.current>a{border-bottom:1px solid #c9c9c9;border-top:1px solid #c9c9c9}.wy-menu-vertical .toctree-l1.current .toctree-l2>ul,.wy-menu-vertical .toctree-l2.current .toctree-l3>ul,.wy-menu-vertical .toctree-l3.current .toctree-l4>ul,.wy-menu-vertical .toctree-l4.current .toctree-l5>ul,.wy-menu-vertical .toctree-l5.current .toctree-l6>ul,.wy-menu-vertical .toctree-l6.current .toctree-l7>ul,.wy-menu-vertical .toctree-l7.current .toctree-l8>ul,.wy-menu-vertical .toctree-l8.current .toctree-l9>ul,.wy-menu-vertical .toctree-l9.current .toctree-l10>ul,.wy-menu-vertical .toctree-l10.current .toctree-l11>ul{display:none}.wy-menu-vertical .toctree-l1.current .current.toctree-l2>ul,.wy-menu-vertical .toctree-l2.current .current.toctree-l3>ul,.wy-menu-vertical .toctree-l3.current .current.toctree-l4>ul,.wy-menu-vertical .toctree-l4.current .current.toctree-l5>ul,.wy-menu-vertical .toctree-l5.current .current.toctree-l6>ul,.wy-menu-vertical .toctree-l6.current .current.toctree-l7>ul,.wy-menu-vertical .toctree-l7.current .current.toctree-l8>ul,.wy-menu-vertical .toctree-l8.current .current.toctree-l9>ul,.wy-menu-vertical .toctree-l9.current .current.toctree-l10>ul,.wy-menu-vertical .toctree-l10.current .current.toctree-l11>ul{display:block}.wy-menu-vertical li.toctree-l3,.wy-menu-vertical li.toctree-l4{font-size:.9em}.wy-menu-vertical li.toctree-l2 a,.wy-menu-vertical li.toctree-l3 a,.wy-menu-vertical li.toctree-l4 a,.wy-menu-vertical li.toctree-l5 a,.wy-menu-vertical li.toctree-l6 a,.wy-menu-vertical li.toctree-l7 a,.wy-menu-vertical li.toctree-l8 a,.wy-menu-vertical li.toctree-l9 a,.wy-menu-vertical li.toctree-l10 a{color:#404040}.wy-menu-vertical li.toctree-l2 a:hover span.toctree-expand,.wy-menu-vertical li.toctree-l3 a:hover span.toctree-expand,.wy-menu-vertical li.toctree-l4 a:hover span.toctree-expand,.wy-menu-vertical li.toctree-l5 a:hover span.toctree-expand,.wy-menu-vertical li.toctree-l6 a:hover span.toctree-expand,.wy-menu-vertical li.toctree-l7 a:hover span.toctree-expand,.wy-menu-vertical li.toctree-l8 a:hover span.toctree-expand,.wy-menu-vertical li.toctree-l9 a:hover span.toctree-expand,.wy-menu-vertical li.toctree-l10 a:hover span.toctree-expand{color:grey}.wy-menu-vertical li.toctree-l2.current li.toctree-l3>a,.wy-menu-vertical li.toctree-l3.current li.toctree-l4>a,.wy-menu-vertical li.toctree-l4.current li.toctree-l5>a,.wy-menu-vertical li.toctree-l5.current li.toctree-l6>a,.wy-menu-vertical li.toctree-l6.current li.toctree-l7>a,.wy-menu-vertical li.toctree-l7.current li.toctree-l8>a,.wy-menu-vertical li.toctree-l8.current li.toctree-l9>a,.wy-menu-vertical li.toctree-l9.current li.toctree-l10>a,.wy-menu-vertical li.toctree-l10.current li.toctree-l11>a{display:block}.wy-menu-vertical li.toctree-l2.current>a{padding:.4045em 2.427em}.wy-menu-vertical li.toctree-l2.current li.toctree-l3>a,.wy-menu-vertical li.toctree-l3.current>a{padding:.4045em 4.045em}.wy-menu-vertical li.toctree-l3.current li.toctree-l4>a,.wy-menu-vertical li.toctree-l4.current>a{padding:.4045em 5.663em}.wy-menu-vertical li.toctree-l4.current li.toctree-l5>a,.wy-menu-vertical li.toctree-l5.current>a{padding:.4045em 7.281em}.wy-menu-vertical li.toctree-l5.current li.toctree-l6>a,.wy-menu-vertical li.toctree-l6.current>a{padding:.4045em 8.899em}.wy-menu-vertical li.toctree-l6.current li.toctree-l7>a,.wy-menu-vertical li.toctree-l7.current>a{padding:.4045em 10.517em}.wy-menu-vertical li.toctree-l7.current li.toctree-l8>a,.wy-menu-vertical li.toctree-l8.current>a{padding:.4045em 12.135em}.wy-menu-vertical li.toctree-l8.current li.toctree-l9>a,.wy-menu-vertical li.toctree-l9.current>a{padding:.4045em 13.753em}.wy-menu-vertical li.toctree-l9.current li.toctree-l10>a,.wy-menu-vertical li.toctree-l10.current>a{padding:.4045em 15.371em}.wy-menu-vertical li.toctree-l10.current li.toctree-l11>a{padding:.4045em 16.989em}.wy-menu-vertical li.toctree-l2.current>a,.wy-menu-vertical li.toctree-l2.current li.toctree-l3>a{background:#c9c9c9}.wy-menu-vertical li.toctree-l2 span.toctree-expand{color:#a3a3a3}.wy-menu-vertical li.toctree-l3.current>a,.wy-menu-vertical li.toctree-l3.current li.toctree-l4>a{background:#bdbdbd}.wy-menu-vertical li.toctree-l3 span.toctree-expand{color:#969696}.wy-menu-vertical li.current ul{display:block}.wy-menu-vertical li ul{margin-bottom:0;display:none}.wy-menu-vertical li ul li a{margin-bottom:0;color:#d9d9d9;font-weight:400}.wy-menu-vertical a{line-height:18px;padding:.4045em 1.618em;display:block;position:relative;font-size:90%;color:#d9d9d9}.wy-menu-vertical a:hover{background-color:#4e4a4a;cursor:pointer}.wy-menu-vertical a:hover span.toctree-expand{color:#d9d9d9}.wy-menu-vertical a:active{background-color:#2980b9;cursor:pointer;color:#fff}.wy-menu-vertical a:active span.toctree-expand{color:#fff}.wy-side-nav-search{display:block;width:300px;padding:.809em;margin-bottom:.809em;z-index:200;background-color:#2980b9;text-align:center;color:#fcfcfc}.wy-side-nav-search input[type=text]{width:100%;border-radius:50px;padding:6px 12px;border-color:#2472a4}.wy-side-nav-search img{display:block;margin:auto auto .809em;height:45px;width:45px;background-color:#2980b9;padding:5px;border-radius:100%}.wy-side-nav-search .wy-dropdown>a,.wy-side-nav-search>a{color:#fcfcfc;font-size:100%;font-weight:700;display:inline-block;padding:4px 6px;margin-bottom:.809em}.wy-side-nav-search .wy-dropdown>a:hover,.wy-side-nav-search>a:hover{background:hsla(0,0%,100%,.1)}.wy-side-nav-search .wy-dropdown>a img.logo,.wy-side-nav-search>a img.logo{display:block;margin:0 auto;height:auto;width:auto;border-radius:0;max-width:100%;background:transparent}.wy-side-nav-search .wy-dropdown>a.icon img.logo,.wy-side-nav-search>a.icon img.logo{margin-top:.85em}.wy-side-nav-search>div.version{margin-top:-.4045em;margin-bottom:.809em;font-weight:400;color:hsla(0,0%,100%,.3)}.wy-nav .wy-menu-vertical header{color:#2980b9}.wy-nav .wy-menu-vertical a{color:#b3b3b3}.wy-nav .wy-menu-vertical a:hover{background-color:#2980b9;color:#fff}[data-menu-wrap]{-webkit-transition:all .2s ease-in;-moz-transition:all .2s ease-in;transition:all .2s ease-in;position:absolute;opacity:1;width:100%;opacity:0}[data-menu-wrap].move-center{left:0;right:auto;opacity:1}[data-menu-wrap].move-left{right:auto;left:-100%;opacity:0}[data-menu-wrap].move-right{right:-100%;left:auto;opacity:0}.wy-body-for-nav{background:#fcfcfc}.wy-grid-for-nav{position:absolute;width:100%;height:100%}.wy-nav-side{position:fixed;top:0;bottom:0;left:0;padding-bottom:2em;width:300px;overflow-x:hidden;overflow-y:hidden;min-height:100%;color:#9b9b9b;background:#343131;z-index:200}.wy-side-scroll{width:320px;position:relative;overflow-x:hidden;overflow-y:scroll;height:100%}.wy-nav-top{display:none;background:#2980b9;color:#fff;padding:.4045em .809em;position:relative;line-height:50px;text-align:center;font-size:100%;*zoom:1}.wy-nav-top:after,.wy-nav-top:before{display:table;content:""}.wy-nav-top:after{clear:both}.wy-nav-top a{color:#fff;font-weight:700}.wy-nav-top img{margin-right:12px;height:45px;width:45px;background-color:#2980b9;padding:5px;border-radius:100%}.wy-nav-top i{font-size:30px;float:left;cursor:pointer;padding-top:inherit}.wy-nav-content-wrap{margin-left:300px;background:#fcfcfc;min-height:100%}.wy-nav-content{padding:1.618em 3.236em;height:100%;max-width:800px;margin:auto}.wy-body-mask{position:fixed;width:100%;height:100%;background:rgba(0,0,0,.2);display:none;z-index:499}.wy-body-mask.on{display:block}footer{color:grey}footer p{margin-bottom:12px}.rst-content footer span.commit tt,footer span.commit .rst-content tt,footer span.commit code{padding:0;font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,Courier,monospace;font-size:1em;background:none;border:none;color:grey}.rst-footer-buttons{*zoom:1}.rst-footer-buttons:after,.rst-footer-buttons:before{width:100%;display:table;content:""}.rst-footer-buttons:after{clear:both}.rst-breadcrumbs-buttons{margin-top:12px;*zoom:1}.rst-breadcrumbs-buttons:after,.rst-breadcrumbs-buttons:before{display:table;content:""}.rst-breadcrumbs-buttons:after{clear:both}#search-results .search li{margin-bottom:24px;border-bottom:1px solid #e1e4e5;padding-bottom:24px}#search-results .search li:first-child{border-top:1px solid #e1e4e5;padding-top:24px}#search-results .search li a{font-size:120%;margin-bottom:12px;display:inline-block}#search-results .context{color:grey;font-size:90%}.genindextable li>ul{margin-left:24px}@media screen and (max-width:768px){.wy-body-for-nav{background:#fcfcfc}.wy-nav-top{display:block}.wy-nav-side{left:-300px}.wy-nav-side.shift{width:85%;left:0}.wy-menu.wy-menu-vertical,.wy-side-nav-search,.wy-side-scroll{width:auto}.wy-nav-content-wrap{margin-left:0}.wy-nav-content-wrap .wy-nav-content{padding:1.618em}.wy-nav-content-wrap.shift{position:fixed;min-width:100%;left:85%;top:0;height:100%;overflow:hidden}}@media screen and (min-width:1100px){.wy-nav-content-wrap{background:rgba(0,0,0,.05)}.wy-nav-content{margin:0;background:#fcfcfc}}@media print{.rst-versions,.wy-nav-side,footer{display:none}.wy-nav-content-wrap{margin-left:0}}.rst-versions{position:fixed;bottom:0;left:0;width:300px;color:#fcfcfc;background:#1f1d1d;font-family:Lato,proxima-nova,Helvetica Neue,Arial,sans-serif;z-index:400}.rst-versions a{color:#2980b9;text-decoration:none}.rst-versions .rst-badge-small{display:none}.rst-versions .rst-current-version{padding:12px;background-color:#272525;display:block;text-align:right;font-size:90%;cursor:pointer;color:#27ae60;*zoom:1}.rst-versions .rst-current-version:after,.rst-versions .rst-current-version:before{display:table;content:""}.rst-versions .rst-current-version:after{clear:both}.rst-content .code-block-caption .rst-versions .rst-current-version .headerlink,.rst-content .rst-versions .rst-current-version .admonition-title,.rst-content code.download .rst-versions .rst-current-version span:first-child,.rst-content dl dt .rst-versions .rst-current-version .headerlink,.rst-content h1 .rst-versions .rst-current-version .headerlink,.rst-content h2 .rst-versions .rst-current-version .headerlink,.rst-content h3 .rst-versions .rst-current-version .headerlink,.rst-content h4 .rst-versions .rst-current-version .headerlink,.rst-content h5 .rst-versions .rst-current-version .headerlink,.rst-content h6 .rst-versions .rst-current-version .headerlink,.rst-content p.caption .rst-versions .rst-current-version .headerlink,.rst-content table>caption .rst-versions .rst-current-version .headerlink,.rst-content tt.download .rst-versions .rst-current-version span:first-child,.rst-versions .rst-current-version .fa,.rst-versions .rst-current-version .icon,.rst-versions .rst-current-version .rst-content .admonition-title,.rst-versions .rst-current-version .rst-content .code-block-caption .headerlink,.rst-versions .rst-current-version .rst-content code.download span:first-child,.rst-versions .rst-current-version .rst-content dl dt .headerlink,.rst-versions .rst-current-version .rst-content h1 .headerlink,.rst-versions .rst-current-version .rst-content h2 .headerlink,.rst-versions .rst-current-version .rst-content h3 .headerlink,.rst-versions .rst-current-version .rst-content h4 .headerlink,.rst-versions .rst-current-version .rst-content h5 .headerlink,.rst-versions .rst-current-version .rst-content h6 .headerlink,.rst-versions .rst-current-version .rst-content p.caption .headerlink,.rst-versions .rst-current-version .rst-content table>caption .headerlink,.rst-versions .rst-current-version .rst-content tt.download span:first-child,.rst-versions .rst-current-version .wy-menu-vertical li span.toctree-expand,.wy-menu-vertical li .rst-versions .rst-current-version span.toctree-expand{color:#fcfcfc}.rst-versions .rst-current-version .fa-book,.rst-versions .rst-current-version .icon-book{float:left}.rst-versions .rst-current-version.rst-out-of-date{background-color:#e74c3c;color:#fff}.rst-versions .rst-current-version.rst-active-old-version{background-color:#f1c40f;color:#000}.rst-versions.shift-up{height:auto;max-height:100%;overflow-y:scroll}.rst-versions.shift-up .rst-other-versions{display:block}.rst-versions .rst-other-versions{font-size:90%;padding:12px;color:grey;display:none}.rst-versions .rst-other-versions hr{display:block;height:1px;border:0;margin:20px 0;padding:0;border-top:1px solid #413d3d}.rst-versions .rst-other-versions dd{display:inline-block;margin:0}.rst-versions .rst-other-versions dd a{display:inline-block;padding:6px;color:#fcfcfc}.rst-versions.rst-badge{width:auto;bottom:20px;right:20px;left:auto;border:none;max-width:300px;max-height:90%}.rst-versions.rst-badge .fa-book,.rst-versions.rst-badge .icon-book{float:none;line-height:30px}.rst-versions.rst-badge.shift-up .rst-current-version{text-align:right}.rst-versions.rst-badge.shift-up .rst-current-version .fa-book,.rst-versions.rst-badge.shift-up .rst-current-version .icon-book{float:left}.rst-versions.rst-badge>.rst-current-version{width:auto;height:30px;line-height:30px;padding:0 6px;display:block;text-align:center}@media screen and (max-width:768px){.rst-versions{width:85%;display:none}.rst-versions.shift{display:block}}.rst-content img{max-width:100%;height:auto}.rst-content div.figure{margin-bottom:24px}.rst-content div.figure p.caption{font-style:italic}.rst-content div.figure p:last-child.caption{margin-bottom:0}.rst-content div.figure.align-center{text-align:center}.rst-content .section>a>img,.rst-content .section>img{margin-bottom:24px}.rst-content abbr[title]{text-decoration:none}.rst-content.style-external-links a.reference.external:after{font-family:FontAwesome;content:"\f08e";color:#b3b3b3;vertical-align:super;font-size:60%;margin:0 .2em}.rst-content blockquote{margin-left:24px;line-height:24px;margin-bottom:24px}.rst-content pre.literal-block{white-space:pre;margin:0;padding:12px;font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,Courier,monospace;display:block;overflow:auto}.rst-content div[class^=highlight],.rst-content pre.literal-block{border:1px solid #e1e4e5;overflow-x:auto;margin:1px 0 24px}.rst-content div[class^=highlight] div[class^=highlight],.rst-content pre.literal-block div[class^=highlight]{padding:0;border:none;margin:0}.rst-content div[class^=highlight] td.code{width:100%}.rst-content .linenodiv pre{border-right:1px solid #e6e9ea;margin:0;padding:12px;font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,Courier,monospace;user-select:none;pointer-events:none}.rst-content div[class^=highlight] pre{white-space:pre;margin:0;padding:12px;display:block;overflow:auto}.rst-content div[class^=highlight] pre .hll{display:block;margin:0 -12px;padding:0 12px}.rst-content .linenodiv pre,.rst-content div[class^=highlight] pre,.rst-content pre.literal-block{font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,Courier,monospace;font-size:12px;line-height:1.4}.rst-content div.highlight .gp{user-select:none;pointer-events:none}.rst-content .code-block-caption{font-style:italic;font-size:85%;line-height:1;padding:1em 0;text-align:center}@media print{.rst-content .codeblock,.rst-content div[class^=highlight],.rst-content div[class^=highlight] pre{white-space:pre-wrap}}.rst-content .admonition,.rst-content .admonition-todo,.rst-content .attention,.rst-content .caution,.rst-content .danger,.rst-content .error,.rst-content .hint,.rst-content .important,.rst-content .note,.rst-content .seealso,.rst-content .tip,.rst-content .warning{clear:both}.rst-content .admonition-todo .last,.rst-content .admonition-todo>:last-child,.rst-content .admonition .last,.rst-content .admonition>:last-child,.rst-content .attention .last,.rst-content .attention>:last-child,.rst-content .caution .last,.rst-content .caution>:last-child,.rst-content .danger .last,.rst-content .danger>:last-child,.rst-content .error .last,.rst-content .error>:last-child,.rst-content .hint .last,.rst-content .hint>:last-child,.rst-content .important .last,.rst-content .important>:last-child,.rst-content .note .last,.rst-content .note>:last-child,.rst-content .seealso .last,.rst-content .seealso>:last-child,.rst-content .tip .last,.rst-content .tip>:last-child,.rst-content .warning .last,.rst-content .warning>:last-child{margin-bottom:0}.rst-content .admonition-title:before{margin-right:4px}.rst-content .admonition table{border-color:rgba(0,0,0,.1)}.rst-content .admonition table td,.rst-content .admonition table th{background:transparent!important;border-color:rgba(0,0,0,.1)!important}.rst-content .section ol.loweralpha,.rst-content .section ol.loweralpha>li{list-style:lower-alpha}.rst-content .section ol.upperalpha,.rst-content .section ol.upperalpha>li{list-style:upper-alpha}.rst-content .section ol li>*,.rst-content .section ul li>*{margin-top:12px;margin-bottom:12px}.rst-content .section ol li>:first-child,.rst-content .section ul li>:first-child{margin-top:0}.rst-content .section ol li>p,.rst-content .section ol li>p:last-child,.rst-content .section ul li>p,.rst-content .section ul li>p:last-child{margin-bottom:12px}.rst-content .section ol li>p:only-child,.rst-content .section ol li>p:only-child:last-child,.rst-content .section ul li>p:only-child,.rst-content .section ul li>p:only-child:last-child{margin-bottom:0}.rst-content .section ol li>ol,.rst-content .section ol li>ul,.rst-content .section ul li>ol,.rst-content .section ul li>ul{margin-bottom:12px}.rst-content .section ol.simple li>*,.rst-content .section ol.simple li ol,.rst-content .section ol.simple li ul,.rst-content .section ul.simple li>*,.rst-content .section ul.simple li ol,.rst-content .section ul.simple li ul{margin-top:0;margin-bottom:0}.rst-content .line-block{margin-left:0;margin-bottom:24px;line-height:24px}.rst-content .line-block .line-block{margin-left:24px;margin-bottom:0}.rst-content .topic-title{font-weight:700;margin-bottom:12px}.rst-content .toc-backref{color:#404040}.rst-content .align-right{float:right;margin:0 0 24px 24px}.rst-content .align-left{float:left;margin:0 24px 24px 0}.rst-content .align-center{margin:auto}.rst-content .align-center:not(table){display:block}.rst-content .code-block-caption .headerlink,.rst-content .toctree-wrapper>p.caption .headerlink,.rst-content dl dt .headerlink,.rst-content h1 .headerlink,.rst-content h2 .headerlink,.rst-content h3 .headerlink,.rst-content h4 .headerlink,.rst-content h5 .headerlink,.rst-content h6 .headerlink,.rst-content p.caption .headerlink,.rst-content table>caption .headerlink{visibility:hidden;font-size:14px}.rst-content .code-block-caption .headerlink:after,.rst-content .toctree-wrapper>p.caption .headerlink:after,.rst-content dl dt .headerlink:after,.rst-content h1 .headerlink:after,.rst-content h2 .headerlink:after,.rst-content h3 .headerlink:after,.rst-content h4 .headerlink:after,.rst-content h5 .headerlink:after,.rst-content h6 .headerlink:after,.rst-content p.caption .headerlink:after,.rst-content table>caption .headerlink:after{content:"\f0c1";font-family:FontAwesome}.rst-content .code-block-caption:hover .headerlink:after,.rst-content .toctree-wrapper>p.caption:hover .headerlink:after,.rst-content dl dt:hover .headerlink:after,.rst-content h1:hover .headerlink:after,.rst-content h2:hover .headerlink:after,.rst-content h3:hover .headerlink:after,.rst-content h4:hover .headerlink:after,.rst-content h5:hover .headerlink:after,.rst-content h6:hover .headerlink:after,.rst-content p.caption:hover .headerlink:after,.rst-content table>caption:hover .headerlink:after{visibility:visible}.rst-content table>caption .headerlink:after{font-size:12px}.rst-content .centered{text-align:center}.rst-content .sidebar{float:right;width:40%;display:block;margin:0 0 24px 24px;padding:24px;background:#f3f6f6;border:1px solid #e1e4e5}.rst-content .sidebar dl,.rst-content .sidebar p,.rst-content .sidebar ul{font-size:90%}.rst-content .sidebar .last,.rst-content .sidebar>:last-child{margin-bottom:0}.rst-content .sidebar .sidebar-title{display:block;font-family:Roboto Slab,ff-tisa-web-pro,Georgia,Arial,sans-serif;font-weight:700;background:#e1e4e5;padding:6px 12px;margin:-24px -24px 24px;font-size:100%}.rst-content .highlighted{background:#f1c40f;box-shadow:0 0 0 2px #f1c40f;display:inline;font-weight:700}.rst-content .citation-reference,.rst-content .footnote-reference{vertical-align:baseline;position:relative;top:-.4em;line-height:0;font-size:90%}.rst-content .hlist{width:100%}html.writer-html4 .rst-content table.docutils.citation,html.writer-html4 .rst-content table.docutils.footnote{background:none;border:none}html.writer-html4 .rst-content table.docutils.citation td,html.writer-html4 .rst-content table.docutils.citation tr,html.writer-html4 .rst-content table.docutils.footnote td,html.writer-html4 .rst-content table.docutils.footnote tr{border:none;background-color:transparent!important;white-space:normal}html.writer-html4 .rst-content table.docutils.citation td.label,html.writer-html4 .rst-content table.docutils.footnote td.label{padding-left:0;padding-right:0;vertical-align:top}html.writer-html5 .rst-content dl dt span.classifier:before{content:" : "}html.writer-html5 .rst-content dl.field-list,html.writer-html5 .rst-content dl.footnote{display:grid;grid-template-columns:max-content auto}html.writer-html5 .rst-content dl.field-list>dt,html.writer-html5 .rst-content dl.footnote>dt{padding-left:1rem}html.writer-html5 .rst-content dl.field-list>dt:after,html.writer-html5 .rst-content dl.footnote>dt:after{content:":"}html.writer-html5 .rst-content dl.field-list>dd,html.writer-html5 .rst-content dl.field-list>dt,html.writer-html5 .rst-content dl.footnote>dd,html.writer-html5 .rst-content dl.footnote>dt{margin-bottom:0}html.writer-html5 .rst-content dl.footnote{font-size:.9rem}html.writer-html5 .rst-content dl.footnote>dt{margin:0 .5rem .5rem 0;line-height:1.2rem;word-break:break-all;font-weight:400}html.writer-html5 .rst-content dl.footnote>dt>span.brackets{margin-right:.5rem}html.writer-html5 .rst-content dl.footnote>dt>span.brackets:before{content:"["}html.writer-html5 .rst-content dl.footnote>dt>span.brackets:after{content:"]"}html.writer-html5 .rst-content dl.footnote>dt>span.fn-backref{font-style:italic}html.writer-html5 .rst-content dl.footnote>dd{margin:0 0 .5rem;line-height:1.2rem}html.writer-html5 .rst-content dl.footnote>dd p,html.writer-html5 .rst-content dl.option-list kbd{font-size:.9rem}.rst-content table.docutils.footnote,html.writer-html4 .rst-content table.docutils.citation,html.writer-html5 .rst-content dl.footnote{color:grey}.rst-content table.docutils.footnote code,.rst-content table.docutils.footnote tt,html.writer-html4 .rst-content table.docutils.citation code,html.writer-html4 .rst-content table.docutils.citation tt,html.writer-html5 .rst-content dl.footnote code,html.writer-html5 .rst-content dl.footnote tt{color:#555}.rst-content .wy-table-responsive.citation,.rst-content .wy-table-responsive.footnote{margin-bottom:0}.rst-content .wy-table-responsive.citation+:not(.citation),.rst-content .wy-table-responsive.footnote+:not(.footnote){margin-top:24px}.rst-content .wy-table-responsive.citation:last-child,.rst-content .wy-table-responsive.footnote:last-child{margin-bottom:24px}.rst-content table.docutils th{border-color:#e1e4e5}html.writer-html5 .rst-content table.docutils th{border:1px solid #e1e4e5}html.writer-html5 .rst-content table.docutils td>p,html.writer-html5 .rst-content table.docutils th>p{line-height:1rem;margin-bottom:0;font-size:.9rem}.rst-content table.docutils td .last,.rst-content table.docutils td .last>:last-child{margin-bottom:0}.rst-content table.field-list,.rst-content table.field-list td{border:none}.rst-content table.field-list td p{font-size:inherit;line-height:inherit}.rst-content table.field-list td>strong{display:inline-block}.rst-content table.field-list .field-name{padding-right:10px;text-align:left;white-space:nowrap}.rst-content table.field-list .field-body{text-align:left}.rst-content code,.rst-content tt{color:#000;font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,Courier,monospace;padding:2px 5px}.rst-content code big,.rst-content code em,.rst-content tt big,.rst-content tt em{font-size:100%!important;line-height:normal}.rst-content code.literal,.rst-content tt.literal{color:#e74c3c}.rst-content code.xref,.rst-content tt.xref,a .rst-content code,a .rst-content tt{font-weight:700;color:#404040}.rst-content kbd,.rst-content pre,.rst-content samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,Courier,monospace}.rst-content a code,.rst-content a tt{color:#2980b9}.rst-content dl{margin-bottom:24px}.rst-content dl dt{font-weight:700;margin-bottom:12px}.rst-content dl ol,.rst-content dl p,.rst-content dl table,.rst-content dl ul{margin-bottom:12px}.rst-content dl dd{margin:0 0 12px 24px;line-height:24px}html.writer-html4 .rst-content dl:not(.docutils),html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.glossary):not(.simple){margin-bottom:24px}html.writer-html4 .rst-content dl:not(.docutils)>dt,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.glossary):not(.simple)>dt{display:table;margin:6px 0;font-size:90%;line-height:normal;background:#e7f2fa;color:#2980b9;border-top:3px solid #6ab0de;padding:6px;position:relative}html.writer-html4 .rst-content dl:not(.docutils)>dt:before,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.glossary):not(.simple)>dt:before{color:#6ab0de}html.writer-html4 .rst-content dl:not(.docutils)>dt .headerlink,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.glossary):not(.simple)>dt .headerlink{color:#404040;font-size:100%!important}html.writer-html4 .rst-content dl:not(.docutils) dl:not(.field-list)>dt,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.glossary):not(.simple) dl:not(.field-list)>dt{margin-bottom:6px;border:none;border-left:3px solid #ccc;background:#f0f0f0;color:#555}html.writer-html4 .rst-content dl:not(.docutils) dl:not(.field-list)>dt .headerlink,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.glossary):not(.simple) dl:not(.field-list)>dt .headerlink{color:#404040;font-size:100%!important}html.writer-html4 .rst-content dl:not(.docutils)>dt:first-child,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.glossary):not(.simple)>dt:first-child{margin-top:0}html.writer-html4 .rst-content dl:not(.docutils) code,html.writer-html4 .rst-content dl:not(.docutils) tt,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.glossary):not(.simple) code,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.glossary):not(.simple) tt{font-weight:700}html.writer-html4 .rst-content dl:not(.docutils) code.descclassname,html.writer-html4 .rst-content dl:not(.docutils) code.descname,html.writer-html4 .rst-content dl:not(.docutils) tt.descclassname,html.writer-html4 .rst-content dl:not(.docutils) tt.descname,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.glossary):not(.simple) code.descclassname,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.glossary):not(.simple) code.descname,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.glossary):not(.simple) tt.descclassname,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.glossary):not(.simple) tt.descname{background-color:transparent;border:none;padding:0;font-size:100%!important}html.writer-html4 .rst-content dl:not(.docutils) code.descname,html.writer-html4 .rst-content dl:not(.docutils) tt.descname,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.glossary):not(.simple) code.descname,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.glossary):not(.simple) tt.descname{font-weight:700}html.writer-html4 .rst-content dl:not(.docutils) .optional,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.glossary):not(.simple) .optional{display:inline-block;padding:0 4px;color:#000;font-weight:700}html.writer-html4 .rst-content dl:not(.docutils) .property,html.writer-html5 .rst-content dl[class]:not(.option-list):not(.field-list):not(.footnote):not(.glossary):not(.simple) .property{display:inline-block;padding-right:8px}.rst-content .viewcode-back,.rst-content .viewcode-link{display:inline-block;color:#27ae60;font-size:80%;padding-left:24px}.rst-content .viewcode-back{display:block;float:right}.rst-content p.rubric{margin-bottom:12px;font-weight:700}.rst-content code.download,.rst-content tt.download{background:inherit;padding:inherit;font-weight:400;font-family:inherit;font-size:inherit;color:inherit;border:inherit;white-space:inherit}.rst-content code.download span:first-child,.rst-content tt.download span:first-child{-webkit-font-smoothing:subpixel-antialiased}.rst-content code.download span:first-child:before,.rst-content tt.download span:first-child:before{margin-right:4px}.rst-content .guilabel{border:1px solid #7fbbe3;background:#e7f2fa;font-size:80%;font-weight:700;border-radius:4px;padding:2.4px 6px;margin:auto 2px}.rst-content .versionmodified{font-style:italic}@media screen and (max-width:480px){.rst-content .sidebar{width:100%}}span[id*=MathJax-Span]{color:#404040}.math{text-align:center}@font-face{font-family:Lato;src:url(fonts/lato-normal.woff2?bd03a2cc277bbbc338d464e679fe9942) format("woff2"),url(fonts/lato-normal.woff?27bd77b9162d388cb8d4c4217c7c5e2a) format("woff");font-weight:400;font-style:normal;font-display:block}@font-face{font-family:Lato;src:url(fonts/lato-bold.woff2?cccb897485813c7c256901dbca54ecf2) format("woff2"),url(fonts/lato-bold.woff?d878b6c29b10beca227e9eef4246111b) format("woff");font-weight:700;font-style:normal;font-display:block}@font-face{font-family:Lato;src:url(fonts/lato-bold-italic.woff2?0b6bb6725576b072c5d0b02ecdd1900d) format("woff2"),url(fonts/lato-bold-italic.woff?9c7e4e9eb485b4a121c760e61bc3707c) format("woff");font-weight:700;font-style:italic;font-display:block}@font-face{font-family:Lato;src:url(fonts/lato-normal-italic.woff2?4eb103b4d12be57cb1d040ed5e162e9d) format("woff2"),url(fonts/lato-normal-italic.woff?f28f2d6482446544ef1ea1ccc6dd5892) format("woff");font-weight:400;font-style:italic;font-display:block}@font-face{font-family:Roboto Slab;font-style:normal;font-weight:400;src:url(fonts/Roboto-Slab-Regular.woff2?7abf5b8d04d26a2cafea937019bca958) format("woff2"),url(fonts/Roboto-Slab-Regular.woff?c1be9284088d487c5e3ff0a10a92e58c) format("woff");font-display:block}@font-face{font-family:Roboto Slab;font-style:normal;font-weight:700;src:url(fonts/Roboto-Slab-Bold.woff2?9984f4a9bda09be08e83f2506954adbe) format("woff2"),url(fonts/Roboto-Slab-Bold.woff?bed5564a116b05148e3b3bea6fb1162a) format("woff");font-display:block} \ No newline at end of file diff --git a/docs/RefMan/_build/html/_static/doctools.js b/docs/RefMan/_build/html/_static/doctools.js new file mode 100644 index 00000000..344db17d --- /dev/null +++ b/docs/RefMan/_build/html/_static/doctools.js @@ -0,0 +1,315 @@ +/* + * doctools.js + * ~~~~~~~~~~~ + * + * Sphinx JavaScript utilities for all documentation. + * + * :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/** + * select a different prefix for underscore + */ +$u = _.noConflict(); + +/** + * make the code below compatible with browsers without + * an installed firebug like debugger +if (!window.console || !console.firebug) { + var names = ["log", "debug", "info", "warn", "error", "assert", "dir", + "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", + "profile", "profileEnd"]; + window.console = {}; + for (var i = 0; i < names.length; ++i) + window.console[names[i]] = function() {}; +} + */ + +/** + * small helper function to urldecode strings + */ +jQuery.urldecode = function(x) { + return decodeURIComponent(x).replace(/\+/g, ' '); +}; + +/** + * small helper function to urlencode strings + */ +jQuery.urlencode = encodeURIComponent; + +/** + * This function returns the parsed url parameters of the + * current request. Multiple values per key are supported, + * it will always return arrays of strings for the value parts. + */ +jQuery.getQueryParameters = function(s) { + if (typeof s === 'undefined') + s = document.location.search; + var parts = s.substr(s.indexOf('?') + 1).split('&'); + var result = {}; + for (var i = 0; i < parts.length; i++) { + var tmp = parts[i].split('=', 2); + var key = jQuery.urldecode(tmp[0]); + var value = jQuery.urldecode(tmp[1]); + if (key in result) + result[key].push(value); + else + result[key] = [value]; + } + return result; +}; + +/** + * highlight a given string on a jquery object by wrapping it in + * span elements with the given class name. + */ +jQuery.fn.highlightText = function(text, className) { + function highlight(node, addItems) { + if (node.nodeType === 3) { + var val = node.nodeValue; + var pos = val.toLowerCase().indexOf(text); + if (pos >= 0 && + !jQuery(node.parentNode).hasClass(className) && + !jQuery(node.parentNode).hasClass("nohighlight")) { + var span; + var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg"); + if (isInSVG) { + span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); + } else { + span = document.createElement("span"); + span.className = className; + } + span.appendChild(document.createTextNode(val.substr(pos, text.length))); + node.parentNode.insertBefore(span, node.parentNode.insertBefore( + document.createTextNode(val.substr(pos + text.length)), + node.nextSibling)); + node.nodeValue = val.substr(0, pos); + if (isInSVG) { + var bbox = span.getBBox(); + var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); + rect.x.baseVal.value = bbox.x; + rect.y.baseVal.value = bbox.y; + rect.width.baseVal.value = bbox.width; + rect.height.baseVal.value = bbox.height; + rect.setAttribute('class', className); + var parentOfText = node.parentNode.parentNode; + addItems.push({ + "parent": node.parentNode, + "target": rect}); + } + } + } + else if (!jQuery(node).is("button, select, textarea")) { + jQuery.each(node.childNodes, function() { + highlight(this, addItems); + }); + } + } + var addItems = []; + var result = this.each(function() { + highlight(this, addItems); + }); + for (var i = 0; i < addItems.length; ++i) { + jQuery(addItems[i].parent).before(addItems[i].target); + } + return result; +}; + +/* + * backward compatibility for jQuery.browser + * This will be supported until firefox bug is fixed. + */ +if (!jQuery.browser) { + jQuery.uaMatch = function(ua) { + ua = ua.toLowerCase(); + + var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || + /(webkit)[ \/]([\w.]+)/.exec(ua) || + /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || + /(msie) ([\w.]+)/.exec(ua) || + ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || + []; + + return { + browser: match[ 1 ] || "", + version: match[ 2 ] || "0" + }; + }; + jQuery.browser = {}; + jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true; +} + +/** + * Small JavaScript module for the documentation. + */ +var Documentation = { + + init : function() { + this.fixFirefoxAnchorBug(); + this.highlightSearchWords(); + this.initIndexTable(); + if (DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) { + this.initOnKeyListeners(); + } + }, + + /** + * i18n support + */ + TRANSLATIONS : {}, + PLURAL_EXPR : function(n) { return n === 1 ? 0 : 1; }, + LOCALE : 'unknown', + + // gettext and ngettext don't access this so that the functions + // can safely bound to a different name (_ = Documentation.gettext) + gettext : function(string) { + var translated = Documentation.TRANSLATIONS[string]; + if (typeof translated === 'undefined') + return string; + return (typeof translated === 'string') ? translated : translated[0]; + }, + + ngettext : function(singular, plural, n) { + var translated = Documentation.TRANSLATIONS[singular]; + if (typeof translated === 'undefined') + return (n == 1) ? singular : plural; + return translated[Documentation.PLURALEXPR(n)]; + }, + + addTranslations : function(catalog) { + for (var key in catalog.messages) + this.TRANSLATIONS[key] = catalog.messages[key]; + this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')'); + this.LOCALE = catalog.locale; + }, + + /** + * add context elements like header anchor links + */ + addContextElements : function() { + $('div[id] > :header:first').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this headline')). + appendTo(this); + }); + $('dt[id]').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this definition')). + appendTo(this); + }); + }, + + /** + * workaround a firefox stupidity + * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075 + */ + fixFirefoxAnchorBug : function() { + if (document.location.hash && $.browser.mozilla) + window.setTimeout(function() { + document.location.href += ''; + }, 10); + }, + + /** + * highlight the search words provided in the url in the text + */ + highlightSearchWords : function() { + var params = $.getQueryParameters(); + var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; + if (terms.length) { + var body = $('div.body'); + if (!body.length) { + body = $('body'); + } + window.setTimeout(function() { + $.each(terms, function() { + body.highlightText(this.toLowerCase(), 'highlighted'); + }); + }, 10); + $('') + .appendTo($('#searchbox')); + } + }, + + /** + * init the domain index toggle buttons + */ + initIndexTable : function() { + var togglers = $('img.toggler').click(function() { + var src = $(this).attr('src'); + var idnum = $(this).attr('id').substr(7); + $('tr.cg-' + idnum).toggle(); + if (src.substr(-9) === 'minus.png') + $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); + else + $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); + }).css('display', ''); + if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) { + togglers.click(); + } + }, + + /** + * helper function to hide the search marks again + */ + hideSearchWords : function() { + $('#searchbox .highlight-link').fadeOut(300); + $('span.highlighted').removeClass('highlighted'); + }, + + /** + * make the url absolute + */ + makeURL : function(relativeURL) { + return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL; + }, + + /** + * get the current relative url + */ + getCurrentURL : function() { + var path = document.location.pathname; + var parts = path.split(/\//); + $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { + if (this === '..') + parts.pop(); + }); + var url = parts.join('/'); + return path.substring(url.lastIndexOf('/') + 1, path.length - 1); + }, + + initOnKeyListeners: function() { + $(document).keyup(function(event) { + var activeElementType = document.activeElement.tagName; + // don't navigate when in search box or textarea + if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT') { + switch (event.keyCode) { + case 37: // left + var prevHref = $('link[rel="prev"]').prop('href'); + if (prevHref) { + window.location.href = prevHref; + return false; + } + case 39: // right + var nextHref = $('link[rel="next"]').prop('href'); + if (nextHref) { + window.location.href = nextHref; + return false; + } + } + } + }); + } +}; + +// quick alias for translations +_ = Documentation.gettext; + +$(document).ready(function() { + Documentation.init(); +}); diff --git a/docs/RefMan/_build/html/_static/documentation_options.js b/docs/RefMan/_build/html/_static/documentation_options.js new file mode 100644 index 00000000..7d2f34c5 --- /dev/null +++ b/docs/RefMan/_build/html/_static/documentation_options.js @@ -0,0 +1,10 @@ +var DOCUMENTATION_OPTIONS = { + URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), + VERSION: '2.11.0', + LANGUAGE: 'None', + COLLAPSE_INDEX: false, + FILE_SUFFIX: '.html', + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt', + NAVIGATION_WITH_KEYS: false, +}; \ No newline at end of file diff --git a/docs/RefMan/_build/html/_static/file.png b/docs/RefMan/_build/html/_static/file.png new file mode 100644 index 00000000..a858a410 Binary files /dev/null and b/docs/RefMan/_build/html/_static/file.png differ diff --git a/docs/RefMan/_build/html/_static/fonts/Inconsolata-Bold.ttf b/docs/RefMan/_build/html/_static/fonts/Inconsolata-Bold.ttf new file mode 100644 index 00000000..809c1f58 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Inconsolata-Bold.ttf differ diff --git a/docs/RefMan/_build/html/_static/fonts/Inconsolata-Regular.ttf b/docs/RefMan/_build/html/_static/fonts/Inconsolata-Regular.ttf new file mode 100644 index 00000000..fc981ce7 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Inconsolata-Regular.ttf differ diff --git a/docs/RefMan/_build/html/_static/fonts/Inconsolata.ttf b/docs/RefMan/_build/html/_static/fonts/Inconsolata.ttf new file mode 100644 index 00000000..4b8a36d2 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Inconsolata.ttf differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato-Bold.ttf b/docs/RefMan/_build/html/_static/fonts/Lato-Bold.ttf new file mode 100644 index 00000000..1d23c706 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato-Bold.ttf differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato-Regular.ttf b/docs/RefMan/_build/html/_static/fonts/Lato-Regular.ttf new file mode 100644 index 00000000..0f3d0f83 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato-Regular.ttf differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato/lato-bold.eot b/docs/RefMan/_build/html/_static/fonts/Lato/lato-bold.eot new file mode 100644 index 00000000..3361183a Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato/lato-bold.eot differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato/lato-bold.ttf b/docs/RefMan/_build/html/_static/fonts/Lato/lato-bold.ttf new file mode 100644 index 00000000..29f691d5 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato/lato-bold.ttf differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato/lato-bold.woff b/docs/RefMan/_build/html/_static/fonts/Lato/lato-bold.woff new file mode 100644 index 00000000..c6dff51f Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato/lato-bold.woff differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato/lato-bold.woff2 b/docs/RefMan/_build/html/_static/fonts/Lato/lato-bold.woff2 new file mode 100644 index 00000000..bb195043 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato/lato-bold.woff2 differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato/lato-bolditalic.eot b/docs/RefMan/_build/html/_static/fonts/Lato/lato-bolditalic.eot new file mode 100644 index 00000000..3d415493 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato/lato-bolditalic.eot differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato/lato-bolditalic.ttf b/docs/RefMan/_build/html/_static/fonts/Lato/lato-bolditalic.ttf new file mode 100644 index 00000000..f402040b Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato/lato-bolditalic.ttf differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato/lato-bolditalic.woff b/docs/RefMan/_build/html/_static/fonts/Lato/lato-bolditalic.woff new file mode 100644 index 00000000..88ad05b9 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato/lato-bolditalic.woff differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato/lato-bolditalic.woff2 b/docs/RefMan/_build/html/_static/fonts/Lato/lato-bolditalic.woff2 new file mode 100644 index 00000000..c4e3d804 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato/lato-bolditalic.woff2 differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato/lato-italic.eot b/docs/RefMan/_build/html/_static/fonts/Lato/lato-italic.eot new file mode 100644 index 00000000..3f826421 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato/lato-italic.eot differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato/lato-italic.ttf b/docs/RefMan/_build/html/_static/fonts/Lato/lato-italic.ttf new file mode 100644 index 00000000..b4bfc9b2 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato/lato-italic.ttf differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato/lato-italic.woff b/docs/RefMan/_build/html/_static/fonts/Lato/lato-italic.woff new file mode 100644 index 00000000..76114bc0 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato/lato-italic.woff differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato/lato-italic.woff2 b/docs/RefMan/_build/html/_static/fonts/Lato/lato-italic.woff2 new file mode 100644 index 00000000..3404f37e Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato/lato-italic.woff2 differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato/lato-regular.eot b/docs/RefMan/_build/html/_static/fonts/Lato/lato-regular.eot new file mode 100644 index 00000000..11e3f2a5 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato/lato-regular.eot differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato/lato-regular.ttf b/docs/RefMan/_build/html/_static/fonts/Lato/lato-regular.ttf new file mode 100644 index 00000000..74decd9e Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato/lato-regular.ttf differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato/lato-regular.woff b/docs/RefMan/_build/html/_static/fonts/Lato/lato-regular.woff new file mode 100644 index 00000000..ae1307ff Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato/lato-regular.woff differ diff --git a/docs/RefMan/_build/html/_static/fonts/Lato/lato-regular.woff2 b/docs/RefMan/_build/html/_static/fonts/Lato/lato-regular.woff2 new file mode 100644 index 00000000..3bf98433 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/Lato/lato-regular.woff2 differ diff --git a/docs/RefMan/_build/html/_static/fonts/RobotoSlab-Bold.ttf b/docs/RefMan/_build/html/_static/fonts/RobotoSlab-Bold.ttf new file mode 100644 index 00000000..df5d1df2 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/RobotoSlab-Bold.ttf differ diff --git a/docs/RefMan/_build/html/_static/fonts/RobotoSlab-Regular.ttf b/docs/RefMan/_build/html/_static/fonts/RobotoSlab-Regular.ttf new file mode 100644 index 00000000..eb52a790 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/RobotoSlab-Regular.ttf differ diff --git a/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.eot b/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.eot new file mode 100644 index 00000000..79dc8efe Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.eot differ diff --git a/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.ttf b/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.ttf new file mode 100644 index 00000000..df5d1df2 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.ttf differ diff --git a/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.woff b/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.woff new file mode 100644 index 00000000..6cb60000 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.woff differ diff --git a/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.woff2 b/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.woff2 new file mode 100644 index 00000000..7059e231 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.woff2 differ diff --git a/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.eot b/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.eot new file mode 100644 index 00000000..2f7ca78a Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.eot differ diff --git a/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.ttf b/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.ttf new file mode 100644 index 00000000..eb52a790 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.ttf differ diff --git a/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.woff b/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.woff new file mode 100644 index 00000000..f815f63f Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.woff differ diff --git a/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.woff2 b/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.woff2 new file mode 100644 index 00000000..f2c76e5b Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.woff2 differ diff --git a/docs/RefMan/_build/html/_static/fonts/fontawesome-webfont.eot b/docs/RefMan/_build/html/_static/fonts/fontawesome-webfont.eot new file mode 100644 index 00000000..e9f60ca9 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/fontawesome-webfont.eot differ diff --git a/docs/RefMan/_build/html/_static/fonts/fontawesome-webfont.svg b/docs/RefMan/_build/html/_static/fonts/fontawesome-webfont.svg new file mode 100644 index 00000000..855c845e --- /dev/null +++ b/docs/RefMan/_build/html/_static/fonts/fontawesome-webfont.svg @@ -0,0 +1,2671 @@ + + + + +Created by FontForge 20120731 at Mon Oct 24 17:37:40 2016 + By ,,, +Copyright Dave Gandy 2016. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/RefMan/_build/html/_static/fonts/fontawesome-webfont.ttf b/docs/RefMan/_build/html/_static/fonts/fontawesome-webfont.ttf new file mode 100644 index 00000000..35acda2f Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/fontawesome-webfont.ttf differ diff --git a/docs/RefMan/_build/html/_static/fonts/fontawesome-webfont.woff b/docs/RefMan/_build/html/_static/fonts/fontawesome-webfont.woff new file mode 100644 index 00000000..400014a4 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/fontawesome-webfont.woff differ diff --git a/docs/RefMan/_build/html/_static/fonts/fontawesome-webfont.woff2 b/docs/RefMan/_build/html/_static/fonts/fontawesome-webfont.woff2 new file mode 100644 index 00000000..4d13fc60 Binary files /dev/null and b/docs/RefMan/_build/html/_static/fonts/fontawesome-webfont.woff2 differ diff --git a/docs/RefMan/_build/html/_static/jquery.js b/docs/RefMan/_build/html/_static/jquery.js new file mode 100644 index 00000000..7e329108 --- /dev/null +++ b/docs/RefMan/_build/html/_static/jquery.js @@ -0,0 +1,10365 @@ +/*! + * jQuery JavaScript Library v3.3.1-dfsg + * https://jquery.com/ + * + * Includes Sizzle.js + * https://sizzlejs.com/ + * + * Copyright JS Foundation and other contributors + * Released under the MIT license + * https://jquery.org/license + * + * Date: 2019-04-19T06:52Z + */ +( function( global, factory ) { + + "use strict"; + + if ( typeof module === "object" && typeof module.exports === "object" ) { + + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + // For environments that do not have a `window` with a `document` + // (such as Node.js), expose a factory as module.exports. + // This accentuates the need for the creation of a real `window`. + // e.g. var jQuery = require("jquery")(window); + // See ticket #14549 for more info. + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 +// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode +// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common +// enough that all such attempts are guarded in a try block. + + +var arr = []; + +var document = window.document; + +var getProto = Object.getPrototypeOf; + +var slice = arr.slice; + +var concat = arr.concat; + +var push = arr.push; + +var indexOf = arr.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var fnToString = hasOwn.toString; + +var ObjectFunctionString = fnToString.call( Object ); + +var support = {}; + +var isFunction = function isFunction( obj ) { + + // Support: Chrome <=57, Firefox <=52 + // In some browsers, typeof returns "function" for HTML elements + // (i.e., `typeof document.createElement( "object" ) === "function"`). + // We don't want to classify *any* DOM node as a function. + return typeof obj === "function" && typeof obj.nodeType !== "number"; + }; + + +var isWindow = function isWindow( obj ) { + return obj != null && obj === obj.window; + }; + + + + + var preservedScriptAttributes = { + type: true, + src: true, + noModule: true + }; + + function DOMEval( code, doc, node ) { + doc = doc || document; + + var i, + script = doc.createElement( "script" ); + + script.text = code; + if ( node ) { + for ( i in preservedScriptAttributes ) { + if ( node[ i ] ) { + script[ i ] = node[ i ]; + } + } + } + doc.head.appendChild( script ).parentNode.removeChild( script ); + } + + +function toType( obj ) { + if ( obj == null ) { + return obj + ""; + } + + // Support: Android <=2.3 only (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; +} +/* global Symbol */ +// Defining this global in .eslintrc.json would create a danger of using the global +// unguarded in another place, it seems safer to define global only for this module + + + +var + version = "3.3.1", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }, + + // Support: Android <=4.0 only + // Make sure we trim BOM and NBSP + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; + +jQuery.fn = jQuery.prototype = { + + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + + // Return all the elements in a clean array + if ( num == null ) { + return slice.call( this ); + } + + // Return just the one element from the set + return num < 0 ? this[ num + this.length ] : this[ num ]; + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + each: function( callback ) { + return jQuery.each( this, callback ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map( this, function( elem, i ) { + return callback.call( elem, i, elem ); + } ) ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: arr.sort, + splice: arr.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[ 0 ] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // Skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !isFunction( target ) ) { + target = {}; + } + + // Extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + + // Only deal with non-null/undefined values + if ( ( options = arguments[ i ] ) != null ) { + + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent Object.prototype pollution + // Prevent never-ending loop + if ( name === "__proto__" || target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = Array.isArray( copy ) ) ) ) { + + if ( copyIsArray ) { + copyIsArray = false; + clone = src && Array.isArray( src ) ? src : []; + + } else { + clone = src && jQuery.isPlainObject( src ) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend( { + + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + isPlainObject: function( obj ) { + var proto, Ctor; + + // Detect obvious negatives + // Use toString instead of jQuery.type to catch host objects + if ( !obj || toString.call( obj ) !== "[object Object]" ) { + return false; + } + + proto = getProto( obj ); + + // Objects with no prototype (e.g., `Object.create( null )`) are plain + if ( !proto ) { + return true; + } + + // Objects with prototype are plain iff they were constructed by a global Object function + Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; + return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; + }, + + isEmptyObject: function( obj ) { + + /* eslint-disable no-unused-vars */ + // See https://github.com/eslint/eslint/issues/6125 + var name; + + for ( name in obj ) { + return false; + } + return true; + }, + + // Evaluates a script in a global context + globalEval: function( code ) { + DOMEval( code ); + }, + + each: function( obj, callback ) { + var length, i = 0; + + if ( isArrayLike( obj ) ) { + length = obj.length; + for ( ; i < length; i++ ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } else { + for ( i in obj ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } + + return obj; + }, + + // Support: Android <=4.0 only + trim: function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArrayLike( Object( arr ) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + return arr == null ? -1 : indexOf.call( arr, elem, i ); + }, + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + for ( ; j < len; j++ ) { + first[ i++ ] = second[ j ]; + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var length, value, + i = 0, + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArrayLike( elems ) ) { + length = elems.length; + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +} ); + +if ( typeof Symbol === "function" ) { + jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; +} + +// Populate the class2type map +jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), +function( i, name ) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +} ); + +function isArrayLike( obj ) { + + // Support: real iOS 8.2 only (not reproducible in simulator) + // `in` check used to prevent JIT error (gh-2145) + // hasOwn isn't used here due to false negatives + // regarding Nodelist length in IE + var length = !!obj && "length" in obj && obj.length, + type = toType( obj ); + + if ( isFunction( obj ) || isWindow( obj ) ) { + return false; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v2.3.3 + * https://sizzlejs.com/ + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2016-08-08 + */ +(function( window ) { + +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + 1 * new Date(), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf as it's faster than native + // https://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { + var i = 0, + len = list.length; + for ( ; i < len; i++ ) { + if ( list[i] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + + // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + + "*\\]", + + pseudos = ":(" + identifier + ")(?:\\((" + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + identifier + ")" ), + "CLASS": new RegExp( "^\\.(" + identifier + ")" ), + "TAG": new RegExp( "^(" + identifier + "|[*])" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + + // CSS escapes + // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox<24 + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + high < 0 ? + // BMP codepoint + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // CSS string/identifier serialization + // https://drafts.csswg.org/cssom/#common-serializing-idioms + rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, + fcssescape = function( ch, asCodePoint ) { + if ( asCodePoint ) { + + // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER + if ( ch === "\0" ) { + return "\uFFFD"; + } + + // Control characters and (dependent upon position) numbers get escaped as code points + return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; + } + + // Other potentially-special ASCII characters get backslash-escaped + return "\\" + ch; + }, + + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); + }, + + disabledAncestor = addCombinator( + function( elem ) { + return elem.disabled === true && ("form" in elem || "label" in elem); + }, + { dir: "parentNode", next: "legend" } + ); + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var m, i, elem, nid, match, groups, newSelector, + newContext = context && context.ownerDocument, + + // nodeType defaults to 9, since context defaults to document + nodeType = context ? context.nodeType : 9; + + results = results || []; + + // Return early from calls with invalid selector or context + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + + return results; + } + + // Try to shortcut find operations (as opposed to filters) in HTML documents + if ( !seed ) { + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + context = context || document; + + if ( documentIsHTML ) { + + // If the selector is sufficiently simple, try using a "get*By*" DOM method + // (excepting DocumentFragment context, where the methods don't exist) + if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { + + // ID selector + if ( (m = match[1]) ) { + + // Document context + if ( nodeType === 9 ) { + if ( (elem = context.getElementById( m )) ) { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + + // Element context + } else { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( newContext && (elem = newContext.getElementById( m )) && + contains( context, elem ) && + elem.id === m ) { + + results.push( elem ); + return results; + } + } + + // Type selector + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Class selector + } else if ( (m = match[3]) && support.getElementsByClassName && + context.getElementsByClassName ) { + + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // Take advantage of querySelectorAll + if ( support.qsa && + !compilerCache[ selector + " " ] && + (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + + if ( nodeType !== 1 ) { + newContext = context; + newSelector = selector; + + // qSA looks outside Element context, which is not what we want + // Thanks to Andrew Dupont for this workaround technique + // Support: IE <=8 + // Exclude object elements + } else if ( context.nodeName.toLowerCase() !== "object" ) { + + // Capture the context ID, setting it first if necessary + if ( (nid = context.getAttribute( "id" )) ) { + nid = nid.replace( rcssescape, fcssescape ); + } else { + context.setAttribute( "id", (nid = expando) ); + } + + // Prefix every selector in the list + groups = tokenize( selector ); + i = groups.length; + while ( i-- ) { + groups[i] = "#" + nid + " " + toSelector( groups[i] ); + } + newSelector = groups.join( "," ); + + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || + context; + } + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + } finally { + if ( nid === expando ) { + context.removeAttribute( "id" ); + } + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {function(string, object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key + " " ] = value); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created element and returns a boolean result + */ +function assert( fn ) { + var el = document.createElement("fieldset"); + + try { + return !!fn( el ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( el.parentNode ) { + el.parentNode.removeChild( el ); + } + // release memory in IE + el = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = arr.length; + + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + a.sourceIndex - b.sourceIndex; + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for :enabled/:disabled + * @param {Boolean} disabled true for :disabled; false for :enabled + */ +function createDisabledPseudo( disabled ) { + + // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable + return function( elem ) { + + // Only certain elements can match :enabled or :disabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled + if ( "form" in elem ) { + + // Check for inherited disabledness on relevant non-disabled elements: + // * listed form-associated elements in a disabled fieldset + // https://html.spec.whatwg.org/multipage/forms.html#category-listed + // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled + // * option elements in a disabled optgroup + // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled + // All such elements have a "form" property. + if ( elem.parentNode && elem.disabled === false ) { + + // Option elements defer to a parent optgroup if present + if ( "label" in elem ) { + if ( "label" in elem.parentNode ) { + return elem.parentNode.disabled === disabled; + } else { + return elem.disabled === disabled; + } + } + + // Support: IE 6 - 11 + // Use the isDisabled shortcut property to check for disabled fieldset ancestors + return elem.isDisabled === disabled || + + // Where there is no isDisabled, check manually + /* jshint -W018 */ + elem.isDisabled !== !disabled && + disabledAncestor( elem ) === disabled; + } + + return elem.disabled === disabled; + + // Try to winnow out elements that can't be disabled before trusting the disabled property. + // Some victims get caught in our net (label, legend, menu, track), but it shouldn't + // even exist on them, let alone have a boolean value. + } else if ( "label" in elem ) { + return elem.disabled === disabled; + } + + // Remaining elements are neither :enabled nor :disabled + return false; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Checks a node for validity as a Sizzle context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== "undefined" && context; +} + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Detects XML nodes + * @param {Element|Object} elem An element or a document + * @returns {Boolean} True iff elem is a non-HTML XML node + */ +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var hasCompare, subWindow, + doc = node ? node.ownerDocument || node : preferredDoc; + + // Return early if doc is invalid or already selected + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Update global variables + document = doc; + docElem = document.documentElement; + documentIsHTML = !isXML( document ); + + // Support: IE 9-11, Edge + // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) + if ( preferredDoc !== document && + (subWindow = document.defaultView) && subWindow.top !== subWindow ) { + + // Support: IE 11, Edge + if ( subWindow.addEventListener ) { + subWindow.addEventListener( "unload", unloadHandler, false ); + + // Support: IE 9 - 10 only + } else if ( subWindow.attachEvent ) { + subWindow.attachEvent( "onunload", unloadHandler ); + } + } + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties + // (excepting IE8 booleans) + support.attributes = assert(function( el ) { + el.className = "i"; + return !el.getAttribute("className"); + }); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert(function( el ) { + el.appendChild( document.createComment("") ); + return !el.getElementsByTagName("*").length; + }); + + // Support: IE<9 + support.getElementsByClassName = rnative.test( document.getElementsByClassName ); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programmatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert(function( el ) { + docElem.appendChild( el ).id = expando; + return !document.getElementsByName || !document.getElementsByName( expando ).length; + }); + + // ID filter and find + if ( support.getById ) { + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var elem = context.getElementById( id ); + return elem ? [ elem ] : []; + } + }; + } else { + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== "undefined" && + elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; + + // Support: IE 6 - 7 only + // getElementById is not reliable as a find shortcut + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var node, i, elems, + elem = context.getElementById( id ); + + if ( elem ) { + + // Verify the id attribute + node = elem.getAttributeNode("id"); + if ( node && node.value === id ) { + return [ elem ]; + } + + // Fall back on getElementsByName + elems = context.getElementsByName( id ); + i = 0; + while ( (elem = elems[i++]) ) { + node = elem.getAttributeNode("id"); + if ( node && node.value === id ) { + return [ elem ]; + } + } + } + + return []; + } + }; + } + + // Tag + Expr.find["TAG"] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( tag ); + + // DocumentFragment nodes don't have gEBTN + } else if ( support.qsa ) { + return context.querySelectorAll( tag ); + } + } : + + function( tag, context ) { + var elem, + tmp = [], + i = 0, + // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See https://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( el ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // https://bugs.jquery.com/ticket/12359 + docElem.appendChild( el ).innerHTML = "" + + ""; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( el.querySelectorAll("[msallowcapture^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !el.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ + if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + rbuggyQSA.push("~="); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !el.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + + // Support: Safari 8+, iOS 8+ + // https://bugs.webkit.org/show_bug.cgi?id=136851 + // In-page `selector#id sibling-combinator selector` fails + if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { + rbuggyQSA.push(".#.+[+~]"); + } + }); + + assert(function( el ) { + el.innerHTML = "" + + ""; + + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = document.createElement("input"); + input.setAttribute( "type", "hidden" ); + el.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( el.querySelectorAll("[name=d]").length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( el.querySelectorAll(":enabled").length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Support: IE9-11+ + // IE's :disabled selector does not pick up the children of disabled fieldsets + docElem.appendChild( el ).disabled = true; + if ( el.querySelectorAll(":disabled").length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Opera 10-11 does not throw on post-comma invalid pseudos + el.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } + + if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { + + assert(function( el ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( el, "*" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( el, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); + + /* Contains + ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); + + // Element contains another + // Purposefully self-exclusive + // As in, an element does not contain itself + contains = hasCompare || rnative.test( docElem.contains ) ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = hasCompare ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { + return -1; + } + if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } : + function( a, b ) { + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Parentless nodes are either documents or disconnected + if ( !aup || !bup ) { + return a === document ? -1 : + b === document ? 1 : + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return document; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + if ( support.matchesSelector && documentIsHTML && + !compilerCache[ expr + " " ] && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch (e) {} + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + (val = elem.getAttributeNode(name)) && val.specified ? + val.value : + null; +}; + +Sizzle.escape = function( sel ) { + return (sel + "").replace( rcssescape, fcssescape ); +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + while ( (node = elem[i++]) ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (jQuery #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[6] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[3] ) { + match[2] = match[4] || match[5] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { return true; } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, uniqueCache, outerCache, node, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType, + diff = false; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) { + + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + + // Seek `elem` from a previously-cached index + + // ...in a gzip-friendly way + node = parent; + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex && cache[ 2 ]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + } else { + // Use previously-cached element index if available + if ( useCache ) { + // ...in a gzip-friendly way + node = elem; + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex; + } + + // xml :nth-child(...) + // or :nth-last-child(...) or :nth(-last)?-of-type(...) + if ( diff === false ) { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) && + ++diff ) { + + // Cache the index of each encountered element + if ( useCache ) { + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + uniqueCache[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + // Don't keep the element (issue #299) + input[0] = null; + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + text = text.replace( runescape, funescape ); + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": createDisabledPseudo( false ), + "disabled": createDisabledPseudo( true ), + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( (tokens = []) ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push({ + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + }); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push({ + value: matched, + type: type, + matches: match + }); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + skip = combinator.next, + key = skip || dir, + checkNonElements = base && key === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + return false; + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, uniqueCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); + + if ( skip && skip === elem.nodeName.toLowerCase() ) { + elem = elem[ dir ] || elem; + } else if ( (oldCache = uniqueCache[ key ]) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return (newCache[ 2 ] = oldCache[ 2 ]); + } else { + // Reuse newcache so results back-propagate to previous elements + uniqueCache[ key ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { + return true; + } + } + } + } + } + return false; + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + // Avoid hanging onto element (issue #299) + checkContext = null; + return ret; + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), + len = elems.length; + + if ( outermost ) { + outermostContext = context === document || context || outermost; + } + + // Add elements passing elementMatchers directly to results + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + for ( ; i !== len && (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + if ( !context && elem.ownerDocument !== document ) { + setDocument( elem ); + xml = !documentIsHTML; + } + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context || document, xml) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // `i` is now the count of elements visited above, and adding it to `matchedCount` + // makes the latter nonnegative. + matchedCount += i; + + // Apply set filters to unmatched elements + // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` + // equals `i`), unless we didn't visit _any_ elements in the above loop because we have + // no element matchers and no seed. + // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that + // case, which will result in a "00" `matchedCount` that differs from `i` but is also + // numerically zero. + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +}; + +/** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +select = Sizzle.select = function( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( (selector = compiled.selector || selector) ); + + results = results || []; + + // Try to minimize operations if there is only one selector in the list and no seed + // (the latter of which guarantees us context) + if ( match.length === 1 ) { + + // Reduce context if the leading compound selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + !context || rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +}; + +// One-time assignments + +// Sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + +// Support: Chrome 14-35+ +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = !!hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert(function( el ) { + // Should return 1, but returns 4 (following) + return el.compareDocumentPosition( document.createElement("fieldset") ) & 1; +}); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert(function( el ) { + el.innerHTML = ""; + return el.firstChild.getAttribute("href") === "#" ; +}) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + }); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert(function( el ) { + el.innerHTML = ""; + el.firstChild.setAttribute( "value", "" ); + return el.firstChild.getAttribute( "value" ) === ""; +}) ) { + addHandle( "value", function( elem, name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + }); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert(function( el ) { + return el.getAttribute("disabled") == null; +}) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return elem[ name ] === true ? name.toLowerCase() : + (val = elem.getAttributeNode( name )) && val.specified ? + val.value : + null; + } + }); +} + +return Sizzle; + +})( window ); + + + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; + +// Deprecated +jQuery.expr[ ":" ] = jQuery.expr.pseudos; +jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; +jQuery.escapeSelector = Sizzle.escape; + + + + +var dir = function( elem, dir, until ) { + var matched = [], + truncate = until !== undefined; + + while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { + if ( elem.nodeType === 1 ) { + if ( truncate && jQuery( elem ).is( until ) ) { + break; + } + matched.push( elem ); + } + } + return matched; +}; + + +var siblings = function( n, elem ) { + var matched = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + matched.push( n ); + } + } + + return matched; +}; + + +var rneedsContext = jQuery.expr.match.needsContext; + + + +function nodeName( elem, name ) { + + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + +}; +var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); + + + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + return !!qualifier.call( elem, i, elem ) !== not; + } ); + } + + // Single element + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + } ); + } + + // Arraylike of elements (jQuery, arguments, Array) + if ( typeof qualifier !== "string" ) { + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) > -1 ) !== not; + } ); + } + + // Filtered directly for both simple and complex selectors + return jQuery.filter( qualifier, elements, not ); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + if ( elems.length === 1 && elem.nodeType === 1 ) { + return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; + } + + return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + } ) ); +}; + +jQuery.fn.extend( { + find: function( selector ) { + var i, ret, + len = this.length, + self = this; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter( function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + } ) ); + } + + ret = this.pushStack( [] ); + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + return len > 1 ? jQuery.uniqueSort( ret ) : ret; + }, + filter: function( selector ) { + return this.pushStack( winnow( this, selector || [], false ) ); + }, + not: function( selector ) { + return this.pushStack( winnow( this, selector || [], true ) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +} ); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + // Shortcut simple #id case for speed + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, + + init = jQuery.fn.init = function( selector, context, root ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Method init() accepts an alternate rootjQuery + // so migrate can support jQuery.sub (gh-2101) + root = root || rootjQuery; + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector[ 0 ] === "<" && + selector[ selector.length - 1 ] === ">" && + selector.length >= 3 ) { + + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && ( match[ 1 ] || !context ) ) { + + // HANDLE: $(html) -> $(array) + if ( match[ 1 ] ) { + context = context instanceof jQuery ? context[ 0 ] : context; + + // Option to run scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[ 1 ], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + + // Properties of context are called as methods if possible + if ( isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[ 2 ] ); + + if ( elem ) { + + // Inject the element directly into the jQuery object + this[ 0 ] = elem; + this.length = 1; + } + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || root ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this[ 0 ] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( isFunction( selector ) ) { + return root.ready !== undefined ? + root.ready( selector ) : + + // Execute immediately if ready is not present + selector( jQuery ); + } + + return jQuery.makeArray( selector, this ); + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document ); + + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + + // Methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend( { + has: function( target ) { + var targets = jQuery( target, this ), + l = targets.length; + + return this.filter( function() { + var i = 0; + for ( ; i < l; i++ ) { + if ( jQuery.contains( this, targets[ i ] ) ) { + return true; + } + } + } ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + targets = typeof selectors !== "string" && jQuery( selectors ); + + // Positional selectors never match, since there's no _selection_ context + if ( !rneedsContext.test( selectors ) ) { + for ( ; i < l; i++ ) { + for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { + + // Always skip document fragments + if ( cur.nodeType < 11 && ( targets ? + targets.index( cur ) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector( cur, selectors ) ) ) { + + matched.push( cur ); + break; + } + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); + }, + + // Determine the position of an element within the set + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; + } + + // Index in selector + if ( typeof elem === "string" ) { + return indexOf.call( jQuery( elem ), this[ 0 ] ); + } + + // Locate the position of the desired element + return indexOf.call( this, + + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[ 0 ] : elem + ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.uniqueSort( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter( selector ) + ); + } +} ); + +function sibling( cur, dir ) { + while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} + return cur; +} + +jQuery.each( { + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return siblings( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return siblings( elem.firstChild ); + }, + contents: function( elem ) { + if ( nodeName( elem, "iframe" ) ) { + return elem.contentDocument; + } + + // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only + // Treat the template element as a regular one in browsers that + // don't support it. + if ( nodeName( elem, "template" ) ) { + elem = elem.content || elem; + } + + return jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var matched = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + matched = jQuery.filter( selector, matched ); + } + + if ( this.length > 1 ) { + + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + jQuery.uniqueSort( matched ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + matched.reverse(); + } + } + + return this.pushStack( matched ); + }; +} ); +var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); + + + +// Convert String-formatted options into Object-formatted ones +function createOptions( options ) { + var object = {}; + jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { + object[ flag ] = true; + } ); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + createOptions( options ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + + // Last fire value for non-forgettable lists + memory, + + // Flag to know if list was already fired + fired, + + // Flag to prevent firing + locked, + + // Actual callback list + list = [], + + // Queue of execution data for repeatable lists + queue = [], + + // Index of currently firing callback (modified by add/remove as needed) + firingIndex = -1, + + // Fire callbacks + fire = function() { + + // Enforce single-firing + locked = locked || options.once; + + // Execute callbacks for all pending executions, + // respecting firingIndex overrides and runtime changes + fired = firing = true; + for ( ; queue.length; firingIndex = -1 ) { + memory = queue.shift(); + while ( ++firingIndex < list.length ) { + + // Run callback and check for early termination + if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && + options.stopOnFalse ) { + + // Jump to end and forget the data so .add doesn't re-fire + firingIndex = list.length; + memory = false; + } + } + } + + // Forget the data if we're done with it + if ( !options.memory ) { + memory = false; + } + + firing = false; + + // Clean up if we're done firing for good + if ( locked ) { + + // Keep an empty list if we have data for future add calls + if ( memory ) { + list = []; + + // Otherwise, this object is spent + } else { + list = ""; + } + } + }, + + // Actual Callbacks object + self = { + + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + + // If we have memory from a past run, we should fire after adding + if ( memory && !firing ) { + firingIndex = list.length - 1; + queue.push( memory ); + } + + ( function add( args ) { + jQuery.each( args, function( _, arg ) { + if ( isFunction( arg ) ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && toType( arg ) !== "string" ) { + + // Inspect recursively + add( arg ); + } + } ); + } )( arguments ); + + if ( memory && !firing ) { + fire(); + } + } + return this; + }, + + // Remove a callback from the list + remove: function() { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + + // Handle firing indexes + if ( index <= firingIndex ) { + firingIndex--; + } + } + } ); + return this; + }, + + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? + jQuery.inArray( fn, list ) > -1 : + list.length > 0; + }, + + // Remove all callbacks from the list + empty: function() { + if ( list ) { + list = []; + } + return this; + }, + + // Disable .fire and .add + // Abort any current/pending executions + // Clear all callbacks and values + disable: function() { + locked = queue = []; + list = memory = ""; + return this; + }, + disabled: function() { + return !list; + }, + + // Disable .fire + // Also disable .add unless we have memory (since it would have no effect) + // Abort any pending executions + lock: function() { + locked = queue = []; + if ( !memory && !firing ) { + list = memory = ""; + } + return this; + }, + locked: function() { + return !!locked; + }, + + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( !locked ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + queue.push( args ); + if ( !firing ) { + fire(); + } + } + return this; + }, + + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + + +function Identity( v ) { + return v; +} +function Thrower( ex ) { + throw ex; +} + +function adoptValue( value, resolve, reject, noValue ) { + var method; + + try { + + // Check for promise aspect first to privilege synchronous behavior + if ( value && isFunction( ( method = value.promise ) ) ) { + method.call( value ).done( resolve ).fail( reject ); + + // Other thenables + } else if ( value && isFunction( ( method = value.then ) ) ) { + method.call( value, resolve, reject ); + + // Other non-thenables + } else { + + // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: + // * false: [ value ].slice( 0 ) => resolve( value ) + // * true: [ value ].slice( 1 ) => resolve() + resolve.apply( undefined, [ value ].slice( noValue ) ); + } + + // For Promises/A+, convert exceptions into rejections + // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in + // Deferred#then to conditionally suppress rejection. + } catch ( value ) { + + // Support: Android 4.0 only + // Strict mode functions invoked without .call/.apply get global-object context + reject.apply( undefined, [ value ] ); + } +} + +jQuery.extend( { + + Deferred: function( func ) { + var tuples = [ + + // action, add listener, callbacks, + // ... .then handlers, argument index, [final state] + [ "notify", "progress", jQuery.Callbacks( "memory" ), + jQuery.Callbacks( "memory" ), 2 ], + [ "resolve", "done", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 0, "resolved" ], + [ "reject", "fail", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 1, "rejected" ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + "catch": function( fn ) { + return promise.then( null, fn ); + }, + + // Keep pipe for back-compat + pipe: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + + return jQuery.Deferred( function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + + // Map tuples (progress, done, fail) to arguments (done, fail, progress) + var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; + + // deferred.progress(function() { bind to newDefer or newDefer.notify }) + // deferred.done(function() { bind to newDefer or newDefer.resolve }) + // deferred.fail(function() { bind to newDefer or newDefer.reject }) + deferred[ tuple[ 1 ] ]( function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && isFunction( returned.promise ) ) { + returned.promise() + .progress( newDefer.notify ) + .done( newDefer.resolve ) + .fail( newDefer.reject ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( + this, + fn ? [ returned ] : arguments + ); + } + } ); + } ); + fns = null; + } ).promise(); + }, + then: function( onFulfilled, onRejected, onProgress ) { + var maxDepth = 0; + function resolve( depth, deferred, handler, special ) { + return function() { + var that = this, + args = arguments, + mightThrow = function() { + var returned, then; + + // Support: Promises/A+ section 2.3.3.3.3 + // https://promisesaplus.com/#point-59 + // Ignore double-resolution attempts + if ( depth < maxDepth ) { + return; + } + + returned = handler.apply( that, args ); + + // Support: Promises/A+ section 2.3.1 + // https://promisesaplus.com/#point-48 + if ( returned === deferred.promise() ) { + throw new TypeError( "Thenable self-resolution" ); + } + + // Support: Promises/A+ sections 2.3.3.1, 3.5 + // https://promisesaplus.com/#point-54 + // https://promisesaplus.com/#point-75 + // Retrieve `then` only once + then = returned && + + // Support: Promises/A+ section 2.3.4 + // https://promisesaplus.com/#point-64 + // Only check objects and functions for thenability + ( typeof returned === "object" || + typeof returned === "function" ) && + returned.then; + + // Handle a returned thenable + if ( isFunction( then ) ) { + + // Special processors (notify) just wait for resolution + if ( special ) { + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ) + ); + + // Normal processors (resolve) also hook into progress + } else { + + // ...and disregard older resolution values + maxDepth++; + + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ), + resolve( maxDepth, deferred, Identity, + deferred.notifyWith ) + ); + } + + // Handle all other returned values + } else { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Identity ) { + that = undefined; + args = [ returned ]; + } + + // Process the value(s) + // Default process is resolve + ( special || deferred.resolveWith )( that, args ); + } + }, + + // Only normal processors (resolve) catch and reject exceptions + process = special ? + mightThrow : + function() { + try { + mightThrow(); + } catch ( e ) { + + if ( jQuery.Deferred.exceptionHook ) { + jQuery.Deferred.exceptionHook( e, + process.stackTrace ); + } + + // Support: Promises/A+ section 2.3.3.3.4.1 + // https://promisesaplus.com/#point-61 + // Ignore post-resolution exceptions + if ( depth + 1 >= maxDepth ) { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Thrower ) { + that = undefined; + args = [ e ]; + } + + deferred.rejectWith( that, args ); + } + } + }; + + // Support: Promises/A+ section 2.3.3.3.1 + // https://promisesaplus.com/#point-57 + // Re-resolve promises immediately to dodge false rejection from + // subsequent errors + if ( depth ) { + process(); + } else { + + // Call an optional hook to record the stack, in case of exception + // since it's otherwise lost when execution goes async + if ( jQuery.Deferred.getStackHook ) { + process.stackTrace = jQuery.Deferred.getStackHook(); + } + window.setTimeout( process ); + } + }; + } + + return jQuery.Deferred( function( newDefer ) { + + // progress_handlers.add( ... ) + tuples[ 0 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onProgress ) ? + onProgress : + Identity, + newDefer.notifyWith + ) + ); + + // fulfilled_handlers.add( ... ) + tuples[ 1 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onFulfilled ) ? + onFulfilled : + Identity + ) + ); + + // rejected_handlers.add( ... ) + tuples[ 2 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onRejected ) ? + onRejected : + Thrower + ) + ); + } ).promise(); + }, + + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 5 ]; + + // promise.progress = list.add + // promise.done = list.add + // promise.fail = list.add + promise[ tuple[ 1 ] ] = list.add; + + // Handle state + if ( stateString ) { + list.add( + function() { + + // state = "resolved" (i.e., fulfilled) + // state = "rejected" + state = stateString; + }, + + // rejected_callbacks.disable + // fulfilled_callbacks.disable + tuples[ 3 - i ][ 2 ].disable, + + // rejected_handlers.disable + // fulfilled_handlers.disable + tuples[ 3 - i ][ 3 ].disable, + + // progress_callbacks.lock + tuples[ 0 ][ 2 ].lock, + + // progress_handlers.lock + tuples[ 0 ][ 3 ].lock + ); + } + + // progress_handlers.fire + // fulfilled_handlers.fire + // rejected_handlers.fire + list.add( tuple[ 3 ].fire ); + + // deferred.notify = function() { deferred.notifyWith(...) } + // deferred.resolve = function() { deferred.resolveWith(...) } + // deferred.reject = function() { deferred.rejectWith(...) } + deferred[ tuple[ 0 ] ] = function() { + deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); + return this; + }; + + // deferred.notifyWith = list.fireWith + // deferred.resolveWith = list.fireWith + // deferred.rejectWith = list.fireWith + deferred[ tuple[ 0 ] + "With" ] = list.fireWith; + } ); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( singleValue ) { + var + + // count of uncompleted subordinates + remaining = arguments.length, + + // count of unprocessed arguments + i = remaining, + + // subordinate fulfillment data + resolveContexts = Array( i ), + resolveValues = slice.call( arguments ), + + // the master Deferred + master = jQuery.Deferred(), + + // subordinate callback factory + updateFunc = function( i ) { + return function( value ) { + resolveContexts[ i ] = this; + resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( !( --remaining ) ) { + master.resolveWith( resolveContexts, resolveValues ); + } + }; + }; + + // Single- and empty arguments are adopted like Promise.resolve + if ( remaining <= 1 ) { + adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, + !remaining ); + + // Use .then() to unwrap secondary thenables (cf. gh-3000) + if ( master.state() === "pending" || + isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { + + return master.then(); + } + } + + // Multiple arguments are aggregated like Promise.all array elements + while ( i-- ) { + adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); + } + + return master.promise(); + } +} ); + + +// These usually indicate a programmer mistake during development, +// warn about them ASAP rather than swallowing them by default. +var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; + +jQuery.Deferred.exceptionHook = function( error, stack ) { + + // Support: IE 8 - 9 only + // Console exists when dev tools are open, which can happen at any time + if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { + window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); + } +}; + + + + +jQuery.readyException = function( error ) { + window.setTimeout( function() { + throw error; + } ); +}; + + + + +// The deferred used on DOM ready +var readyList = jQuery.Deferred(); + +jQuery.fn.ready = function( fn ) { + + readyList + .then( fn ) + + // Wrap jQuery.readyException in a function so that the lookup + // happens at the time of error handling instead of callback + // registration. + .catch( function( error ) { + jQuery.readyException( error ); + } ); + + return this; +}; + +jQuery.extend( { + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + } +} ); + +jQuery.ready.then = readyList.then; + +// The ready event handler and self cleanup method +function completed() { + document.removeEventListener( "DOMContentLoaded", completed ); + window.removeEventListener( "load", completed ); + jQuery.ready(); +} + +// Catch cases where $(document).ready() is called +// after the browser event has already occurred. +// Support: IE <=9 - 10 only +// Older IE sometimes signals "interactive" too soon +if ( document.readyState === "complete" || + ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { + + // Handle it asynchronously to allow scripts the opportunity to delay ready + window.setTimeout( jQuery.ready ); + +} else { + + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed ); +} + + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + len = elems.length, + bulk = key == null; + + // Sets many values + if ( toType( key ) === "object" ) { + chainable = true; + for ( i in key ) { + access( elems, fn, i, key[ i ], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < len; i++ ) { + fn( + elems[ i ], key, raw ? + value : + value.call( elems[ i ], i, fn( elems[ i ], key ) ) + ); + } + } + } + + if ( chainable ) { + return elems; + } + + // Gets + if ( bulk ) { + return fn.call( elems ); + } + + return len ? fn( elems[ 0 ], key ) : emptyGet; +}; + + +// Matches dashed string for camelizing +var rmsPrefix = /^-ms-/, + rdashAlpha = /-([a-z])/g; + +// Used by camelCase as callback to replace() +function fcamelCase( all, letter ) { + return letter.toUpperCase(); +} + +// Convert dashed to camelCase; used by the css and data modules +// Support: IE <=9 - 11, Edge 12 - 15 +// Microsoft forgot to hump their vendor prefix (#9572) +function camelCase( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); +} +var acceptData = function( owner ) { + + // Accepts only: + // - Node + // - Node.ELEMENT_NODE + // - Node.DOCUMENT_NODE + // - Object + // - Any + return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); +}; + + + + +function Data() { + this.expando = jQuery.expando + Data.uid++; +} + +Data.uid = 1; + +Data.prototype = { + + cache: function( owner ) { + + // Check if the owner object already has a cache + var value = owner[ this.expando ]; + + // If not, create one + if ( !value ) { + value = {}; + + // We can accept data for non-element nodes in modern browsers, + // but we should not, see #8335. + // Always return an empty object. + if ( acceptData( owner ) ) { + + // If it is a node unlikely to be stringify-ed or looped over + // use plain assignment + if ( owner.nodeType ) { + owner[ this.expando ] = value; + + // Otherwise secure it in a non-enumerable property + // configurable must be true to allow the property to be + // deleted when data is removed + } else { + Object.defineProperty( owner, this.expando, { + value: value, + configurable: true + } ); + } + } + } + + return value; + }, + set: function( owner, data, value ) { + var prop, + cache = this.cache( owner ); + + // Handle: [ owner, key, value ] args + // Always use camelCase key (gh-2257) + if ( typeof data === "string" ) { + cache[ camelCase( data ) ] = value; + + // Handle: [ owner, { properties } ] args + } else { + + // Copy the properties one-by-one to the cache object + for ( prop in data ) { + cache[ camelCase( prop ) ] = data[ prop ]; + } + } + return cache; + }, + get: function( owner, key ) { + return key === undefined ? + this.cache( owner ) : + + // Always use camelCase key (gh-2257) + owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; + }, + access: function( owner, key, value ) { + + // In cases where either: + // + // 1. No key was specified + // 2. A string key was specified, but no value provided + // + // Take the "read" path and allow the get method to determine + // which value to return, respectively either: + // + // 1. The entire cache object + // 2. The data stored at the key + // + if ( key === undefined || + ( ( key && typeof key === "string" ) && value === undefined ) ) { + + return this.get( owner, key ); + } + + // When the key is not a string, or both a key and value + // are specified, set or extend (existing objects) with either: + // + // 1. An object of properties + // 2. A key and value + // + this.set( owner, key, value ); + + // Since the "set" path can have two possible entry points + // return the expected data based on which path was taken[*] + return value !== undefined ? value : key; + }, + remove: function( owner, key ) { + var i, + cache = owner[ this.expando ]; + + if ( cache === undefined ) { + return; + } + + if ( key !== undefined ) { + + // Support array or space separated string of keys + if ( Array.isArray( key ) ) { + + // If key is an array of keys... + // We always set camelCase keys, so remove that. + key = key.map( camelCase ); + } else { + key = camelCase( key ); + + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + key = key in cache ? + [ key ] : + ( key.match( rnothtmlwhite ) || [] ); + } + + i = key.length; + + while ( i-- ) { + delete cache[ key[ i ] ]; + } + } + + // Remove the expando if there's no more data + if ( key === undefined || jQuery.isEmptyObject( cache ) ) { + + // Support: Chrome <=35 - 45 + // Webkit & Blink performance suffers when deleting properties + // from DOM nodes, so set to undefined instead + // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) + if ( owner.nodeType ) { + owner[ this.expando ] = undefined; + } else { + delete owner[ this.expando ]; + } + } + }, + hasData: function( owner ) { + var cache = owner[ this.expando ]; + return cache !== undefined && !jQuery.isEmptyObject( cache ); + } +}; +var dataPriv = new Data(); + +var dataUser = new Data(); + + + +// Implementation Summary +// +// 1. Enforce API surface and semantic compatibility with 1.9.x branch +// 2. Improve the module's maintainability by reducing the storage +// paths to a single mechanism. +// 3. Use the same single mechanism to support "private" and "user" data. +// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) +// 5. Avoid exposing implementation details on user objects (eg. expando properties) +// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /[A-Z]/g; + +function getData( data ) { + if ( data === "true" ) { + return true; + } + + if ( data === "false" ) { + return false; + } + + if ( data === "null" ) { + return null; + } + + // Only convert to a number if it doesn't change the string + if ( data === +data + "" ) { + return +data; + } + + if ( rbrace.test( data ) ) { + return JSON.parse( data ); + } + + return data; +} + +function dataAttr( elem, key, data ) { + var name; + + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = getData( data ); + } catch ( e ) {} + + // Make sure we set the data so it isn't changed later + dataUser.set( elem, key, data ); + } else { + data = undefined; + } + } + return data; +} + +jQuery.extend( { + hasData: function( elem ) { + return dataUser.hasData( elem ) || dataPriv.hasData( elem ); + }, + + data: function( elem, name, data ) { + return dataUser.access( elem, name, data ); + }, + + removeData: function( elem, name ) { + dataUser.remove( elem, name ); + }, + + // TODO: Now that all calls to _data and _removeData have been replaced + // with direct calls to dataPriv methods, these can be deprecated. + _data: function( elem, name, data ) { + return dataPriv.access( elem, name, data ); + }, + + _removeData: function( elem, name ) { + dataPriv.remove( elem, name ); + } +} ); + +jQuery.fn.extend( { + data: function( key, value ) { + var i, name, data, + elem = this[ 0 ], + attrs = elem && elem.attributes; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = dataUser.get( elem ); + + if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE 11 only + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = camelCase( name.slice( 5 ) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + dataPriv.set( elem, "hasDataAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each( function() { + dataUser.set( this, key ); + } ); + } + + return access( this, function( value ) { + var data; + + // The calling jQuery object (element matches) is not empty + // (and therefore has an element appears at this[ 0 ]) and the + // `value` parameter was not undefined. An empty jQuery object + // will result in `undefined` for elem = this[ 0 ] which will + // throw an exception if an attempt to read a data cache is made. + if ( elem && value === undefined ) { + + // Attempt to get data from the cache + // The key will always be camelCased in Data + data = dataUser.get( elem, key ); + if ( data !== undefined ) { + return data; + } + + // Attempt to "discover" the data in + // HTML5 custom data-* attrs + data = dataAttr( elem, key ); + if ( data !== undefined ) { + return data; + } + + // We tried really hard, but the data doesn't exist. + return; + } + + // Set the data... + this.each( function() { + + // We always store the camelCased key + dataUser.set( this, key, value ); + } ); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each( function() { + dataUser.remove( this, key ); + } ); + } +} ); + + +jQuery.extend( { + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = dataPriv.get( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || Array.isArray( data ) ) { + queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // Clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // Not public - generate a queueHooks object, or return the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { + empty: jQuery.Callbacks( "once memory" ).add( function() { + dataPriv.remove( elem, [ type + "queue", key ] ); + } ) + } ); + } +} ); + +jQuery.fn.extend( { + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[ 0 ], type ); + } + + return data === undefined ? + this : + this.each( function() { + var queue = jQuery.queue( this, type, data ); + + // Ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + } ); + }, + dequeue: function( type ) { + return this.each( function() { + jQuery.dequeue( this, type ); + } ); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +} ); +var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; + +var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); + + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var isHiddenWithinTree = function( elem, el ) { + + // isHiddenWithinTree might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + + // Inline style trumps all + return elem.style.display === "none" || + elem.style.display === "" && + + // Otherwise, check computed style + // Support: Firefox <=43 - 45 + // Disconnected elements can have computed display: none, so first confirm that elem is + // in the document. + jQuery.contains( elem.ownerDocument, elem ) && + + jQuery.css( elem, "display" ) === "none"; + }; + +var swap = function( elem, options, callback, args ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.apply( elem, args || [] ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; +}; + + + + +function adjustCSS( elem, prop, valueParts, tween ) { + var adjusted, scale, + maxIterations = 20, + currentValue = tween ? + function() { + return tween.cur(); + } : + function() { + return jQuery.css( elem, prop, "" ); + }, + initial = currentValue(), + unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), + + // Starting value computation is required for potential unit mismatches + initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && + rcssNum.exec( jQuery.css( elem, prop ) ); + + if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { + + // Support: Firefox <=54 + // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) + initial = initial / 2; + + // Trust units reported by jQuery.css + unit = unit || initialInUnit[ 3 ]; + + // Iteratively approximate from a nonzero starting point + initialInUnit = +initial || 1; + + while ( maxIterations-- ) { + + // Evaluate and update our best guess (doubling guesses that zero out). + // Finish if the scale equals or crosses 1 (making the old*new product non-positive). + jQuery.style( elem, prop, initialInUnit + unit ); + if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { + maxIterations = 0; + } + initialInUnit = initialInUnit / scale; + + } + + initialInUnit = initialInUnit * 2; + jQuery.style( elem, prop, initialInUnit + unit ); + + // Make sure we update the tween properties later on + valueParts = valueParts || []; + } + + if ( valueParts ) { + initialInUnit = +initialInUnit || +initial || 0; + + // Apply relative offset (+=/-=) if specified + adjusted = valueParts[ 1 ] ? + initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : + +valueParts[ 2 ]; + if ( tween ) { + tween.unit = unit; + tween.start = initialInUnit; + tween.end = adjusted; + } + } + return adjusted; +} + + +var defaultDisplayMap = {}; + +function getDefaultDisplay( elem ) { + var temp, + doc = elem.ownerDocument, + nodeName = elem.nodeName, + display = defaultDisplayMap[ nodeName ]; + + if ( display ) { + return display; + } + + temp = doc.body.appendChild( doc.createElement( nodeName ) ); + display = jQuery.css( temp, "display" ); + + temp.parentNode.removeChild( temp ); + + if ( display === "none" ) { + display = "block"; + } + defaultDisplayMap[ nodeName ] = display; + + return display; +} + +function showHide( elements, show ) { + var display, elem, + values = [], + index = 0, + length = elements.length; + + // Determine new display value for elements that need to change + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + + display = elem.style.display; + if ( show ) { + + // Since we force visibility upon cascade-hidden elements, an immediate (and slow) + // check is required in this first loop unless we have a nonempty display value (either + // inline or about-to-be-restored) + if ( display === "none" ) { + values[ index ] = dataPriv.get( elem, "display" ) || null; + if ( !values[ index ] ) { + elem.style.display = ""; + } + } + if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { + values[ index ] = getDefaultDisplay( elem ); + } + } else { + if ( display !== "none" ) { + values[ index ] = "none"; + + // Remember what we're overwriting + dataPriv.set( elem, "display", display ); + } + } + } + + // Set the display of the elements in a second loop to avoid constant reflow + for ( index = 0; index < length; index++ ) { + if ( values[ index ] != null ) { + elements[ index ].style.display = values[ index ]; + } + } + + return elements; +} + +jQuery.fn.extend( { + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state ) { + if ( typeof state === "boolean" ) { + return state ? this.show() : this.hide(); + } + + return this.each( function() { + if ( isHiddenWithinTree( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + } ); + } +} ); +var rcheckableType = ( /^(?:checkbox|radio)$/i ); + +var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i ); + +var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); + + + +// We have to close these tags to support XHTML (#13200) +var wrapMap = { + + // Support: IE <=9 only + option: [ 1, "" ], + + // XHTML parsers do not magically insert elements in the + // same way that tag soup parsers do. So we cannot shorten + // this by omitting or other required elements. + thead: [ 1, "", "
" ], + col: [ 2, "", "
" ], + tr: [ 2, "", "
" ], + td: [ 3, "", "
" ], + + _default: [ 0, "", "" ] +}; + +// Support: IE <=9 only +wrapMap.optgroup = wrapMap.option; + +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + + +function getAll( context, tag ) { + + // Support: IE <=9 - 11 only + // Use typeof to avoid zero-argument method invocation on host objects (#15151) + var ret; + + if ( typeof context.getElementsByTagName !== "undefined" ) { + ret = context.getElementsByTagName( tag || "*" ); + + } else if ( typeof context.querySelectorAll !== "undefined" ) { + ret = context.querySelectorAll( tag || "*" ); + + } else { + ret = []; + } + + if ( tag === undefined || tag && nodeName( context, tag ) ) { + return jQuery.merge( [ context ], ret ); + } + + return ret; +} + + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + dataPriv.set( + elems[ i ], + "globalEval", + !refElements || dataPriv.get( refElements[ i ], "globalEval" ) + ); + } +} + + +var rhtml = /<|&#?\w+;/; + +function buildFragment( elems, context, scripts, selection, ignored ) { + var elem, tmp, tag, wrap, contains, j, + fragment = context.createDocumentFragment(), + nodes = [], + i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( toType( elem ) === "object" ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; + + // Descend through wrappers to the right content + j = wrap[ 0 ]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Ensure the created nodes are orphaned (#12392) + tmp.textContent = ""; + } + } + } + + // Remove wrapper from fragment + fragment.textContent = ""; + + i = 0; + while ( ( elem = nodes[ i++ ] ) ) { + + // Skip elements already in the context collection (trac-4087) + if ( selection && jQuery.inArray( elem, selection ) > -1 ) { + if ( ignored ) { + ignored.push( elem ); + } + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( ( elem = tmp[ j++ ] ) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + return fragment; +} + + +( function() { + var fragment = document.createDocumentFragment(), + div = fragment.appendChild( document.createElement( "div" ) ), + input = document.createElement( "input" ); + + // Support: Android 4.0 - 4.3 only + // Check state lost if the name is set (#11217) + // Support: Windows Web Apps (WWA) + // `name` and `type` must use .setAttribute for WWA (#14901) + input.setAttribute( "type", "radio" ); + input.setAttribute( "checked", "checked" ); + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + + // Support: Android <=4.1 only + // Older WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE <=11 only + // Make sure textarea (and checkbox) defaultValue is properly cloned + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; +} )(); +var documentElement = document.documentElement; + + + +var + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +// Support: IE <=9 only +// See #13393 for more info +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +function on( elem, types, selector, data, fn, one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + on( elem, type, selector, data, types[ type ], one ); + } + return elem; + } + + if ( data == null && fn == null ) { + + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return elem; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return elem.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + } ); +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + + var handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.get( elem ); + + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Ensure that invalid selectors throw exceptions at attach time + // Evaluate against documentElement in case elem is a non-element node (e.g., document) + if ( selector ) { + jQuery.find.matchesSelector( documentElement, selector ); + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !( events = elemData.events ) ) { + events = elemData.events = {}; + } + if ( !( eventHandle = elemData.handle ) ) { + eventHandle = elemData.handle = function( e ) { + + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? + jQuery.event.dispatch.apply( elem, arguments ) : undefined; + }; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend( { + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join( "." ) + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !( handlers = events[ type ] ) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener if the special events handler returns false + if ( !special.setup || + special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); + + if ( !elemData || !( events = elemData.events ) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[ 2 ] && + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || + selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || + special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove data and the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + dataPriv.remove( elem, "handle events" ); + } + }, + + dispatch: function( nativeEvent ) { + + // Make a writable jQuery.Event from the native event object + var event = jQuery.event.fix( nativeEvent ); + + var i, j, ret, matched, handleObj, handlerQueue, + args = new Array( arguments.length ), + handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[ 0 ] = event; + + for ( i = 1; i < arguments.length; i++ ) { + args[ i ] = arguments[ i ]; + } + + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( ( handleObj = matched.handlers[ j++ ] ) && + !event.isImmediatePropagationStopped() ) { + + // Triggered event must either 1) have no namespace, or 2) have namespace(s) + // a subset or equal to those in the bound event (both can have no namespace). + if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || + handleObj.handler ).apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( ( event.result = ret ) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, handleObj, sel, matchedHandlers, matchedSelectors, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + if ( delegateCount && + + // Support: IE <=9 + // Black-hole SVG instance trees (trac-13180) + cur.nodeType && + + // Support: Firefox <=42 + // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) + // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click + // Support: IE 11 only + // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) + !( event.type === "click" && event.button >= 1 ) ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { + matchedHandlers = []; + matchedSelectors = {}; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matchedSelectors[ sel ] === undefined ) { + matchedSelectors[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) > -1 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matchedSelectors[ sel ] ) { + matchedHandlers.push( handleObj ); + } + } + if ( matchedHandlers.length ) { + handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); + } + } + } + } + + // Add the remaining (directly-bound) handlers + cur = this; + if ( delegateCount < handlers.length ) { + handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); + } + + return handlerQueue; + }, + + addProp: function( name, hook ) { + Object.defineProperty( jQuery.Event.prototype, name, { + enumerable: true, + configurable: true, + + get: isFunction( hook ) ? + function() { + if ( this.originalEvent ) { + return hook( this.originalEvent ); + } + } : + function() { + if ( this.originalEvent ) { + return this.originalEvent[ name ]; + } + }, + + set: function( value ) { + Object.defineProperty( this, name, { + enumerable: true, + configurable: true, + writable: true, + value: value + } ); + } + } ); + }, + + fix: function( originalEvent ) { + return originalEvent[ jQuery.expando ] ? + originalEvent : + new jQuery.Event( originalEvent ); + }, + + special: { + load: { + + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + focus: { + + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + this.focus(); + return false; + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + click: { + + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) { + this.click(); + return false; + } + }, + + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return nodeName( event.target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + } +}; + +jQuery.removeEvent = function( elem, type, handle ) { + + // This "if" is needed for plain objects + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle ); + } +}; + +jQuery.Event = function( src, props ) { + + // Allow instantiation without the 'new' keyword + if ( !( this instanceof jQuery.Event ) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + + // Support: Android <=2.3 only + src.returnValue === false ? + returnTrue : + returnFalse; + + // Create target properties + // Support: Safari <=6 - 7 only + // Target should not be a text node (#504, #13143) + this.target = ( src.target && src.target.nodeType === 3 ) ? + src.target.parentNode : + src.target; + + this.currentTarget = src.currentTarget; + this.relatedTarget = src.relatedTarget; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || Date.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + constructor: jQuery.Event, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + isSimulated: false, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + + if ( e && !this.isSimulated ) { + e.preventDefault(); + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopPropagation(); + } + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Includes all common event props including KeyEvent and MouseEvent specific props +jQuery.each( { + altKey: true, + bubbles: true, + cancelable: true, + changedTouches: true, + ctrlKey: true, + detail: true, + eventPhase: true, + metaKey: true, + pageX: true, + pageY: true, + shiftKey: true, + view: true, + "char": true, + charCode: true, + key: true, + keyCode: true, + button: true, + buttons: true, + clientX: true, + clientY: true, + offsetX: true, + offsetY: true, + pointerId: true, + pointerType: true, + screenX: true, + screenY: true, + targetTouches: true, + toElement: true, + touches: true, + + which: function( event ) { + var button = event.button; + + // Add which for key events + if ( event.which == null && rkeyEvent.test( event.type ) ) { + return event.charCode != null ? event.charCode : event.keyCode; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { + if ( button & 1 ) { + return 1; + } + + if ( button & 2 ) { + return 3; + } + + if ( button & 4 ) { + return 2; + } + + return 0; + } + + return event.which; + } +}, jQuery.event.addProp ); + +// Create mouseenter/leave events using mouseover/out and event-time checks +// so that event delegation works in jQuery. +// Do the same for pointerenter/pointerleave and pointerover/pointerout +// +// Support: Safari 7 only +// Safari sends mouseenter too often; see: +// https://bugs.chromium.org/p/chromium/issues/detail?id=470258 +// for the description of the bug (it existed in older Chrome versions as well). +jQuery.each( { + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mouseenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +} ); + +jQuery.fn.extend( { + + on: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn ); + }, + one: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? + handleObj.origType + "." + handleObj.namespace : + handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each( function() { + jQuery.event.remove( this, types, fn, selector ); + } ); + } +} ); + + +var + + /* eslint-disable max-len */ + + // See https://github.com/eslint/eslint/issues/3229 + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi, + + /* eslint-enable */ + + // Support: IE <=10 - 11, Edge 12 - 13 only + // In IE/Edge using regex groups here causes severe slowdowns. + // See https://connect.microsoft.com/IE/feedback/details/1736512/ + rnoInnerhtml = /\s*$/g; + +// Prefer a tbody over its parent table for containing new rows +function manipulationTarget( elem, content ) { + if ( nodeName( elem, "table" ) && + nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { + + return jQuery( elem ).children( "tbody" )[ 0 ] || elem; + } + + return elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { + elem.type = elem.type.slice( 5 ); + } else { + elem.removeAttribute( "type" ); + } + + return elem; +} + +function cloneCopyEvent( src, dest ) { + var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; + + if ( dest.nodeType !== 1 ) { + return; + } + + // 1. Copy private data: events, handlers, etc. + if ( dataPriv.hasData( src ) ) { + pdataOld = dataPriv.access( src ); + pdataCur = dataPriv.set( dest, pdataOld ); + events = pdataOld.events; + + if ( events ) { + delete pdataCur.handle; + pdataCur.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + } + + // 2. Copy user data + if ( dataUser.hasData( src ) ) { + udataOld = dataUser.access( src ); + udataCur = jQuery.extend( {}, udataOld ); + + dataUser.set( dest, udataCur ); + } +} + +// Fix IE bugs, see support tests +function fixInput( src, dest ) { + var nodeName = dest.nodeName.toLowerCase(); + + // Fails to persist the checked state of a cloned checkbox or radio button. + if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + dest.checked = src.checked; + + // Fails to return the selected option to the default selected state when cloning options + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +function domManip( collection, args, callback, ignored ) { + + // Flatten any nested arrays + args = concat.apply( [], args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = collection.length, + iNoClone = l - 1, + value = args[ 0 ], + valueIsFunction = isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( valueIsFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return collection.each( function( index ) { + var self = collection.eq( index ); + if ( valueIsFunction ) { + args[ 0 ] = value.call( this, index, self.html() ); + } + domManip( self, args, callback, ignored ); + } ); + } + + if ( l ) { + fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + // Require either new content or an interest in ignored elements to invoke the callback + if ( first || ignored ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item + // instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( collection[ i ], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !dataPriv.access( node, "globalEval" ) && + jQuery.contains( doc, node ) ) { + + if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { + + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl ) { + jQuery._evalUrl( node.src ); + } + } else { + DOMEval( node.textContent.replace( rcleanScript, "" ), doc, node ); + } + } + } + } + } + } + + return collection; +} + +function remove( elem, selector, keepData ) { + var node, + nodes = selector ? jQuery.filter( selector, elem ) : elem, + i = 0; + + for ( ; ( node = nodes[ i ] ) != null; i++ ) { + if ( !keepData && node.nodeType === 1 ) { + jQuery.cleanData( getAll( node ) ); + } + + if ( node.parentNode ) { + if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { + setGlobalEval( getAll( node, "script" ) ); + } + node.parentNode.removeChild( node ); + } + } + + return elem; +} + +jQuery.extend( { + htmlPrefilter: function( html ) { + return html.replace( rxhtmlTag, "<$1>" ); + }, + + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var i, l, srcElements, destElements, + clone = elem.cloneNode( true ), + inPage = jQuery.contains( elem.ownerDocument, elem ); + + // Fix IE cloning issues + if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && + !jQuery.isXMLDoc( elem ) ) { + + // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + fixInput( srcElements[ i ], destElements[ i ] ); + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + cloneCopyEvent( srcElements[ i ], destElements[ i ] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + // Return the cloned set + return clone; + }, + + cleanData: function( elems ) { + var data, elem, type, + special = jQuery.event.special, + i = 0; + + for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { + if ( acceptData( elem ) ) { + if ( ( data = elem[ dataPriv.expando ] ) ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataPriv.expando ] = undefined; + } + if ( elem[ dataUser.expando ] ) { + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataUser.expando ] = undefined; + } + } + } + } +} ); + +jQuery.fn.extend( { + detach: function( selector ) { + return remove( this, selector, true ); + }, + + remove: function( selector ) { + return remove( this, selector ); + }, + + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().each( function() { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.textContent = value; + } + } ); + }, null, value, arguments.length ); + }, + + append: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + } ); + }, + + prepend: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + } ); + }, + + before: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + } ); + }, + + after: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + } ); + }, + + empty: function() { + var elem, + i = 0; + + for ( ; ( elem = this[ i ] ) != null; i++ ) { + if ( elem.nodeType === 1 ) { + + // Prevent memory leaks + jQuery.cleanData( getAll( elem, false ) ); + + // Remove any remaining nodes + elem.textContent = ""; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + } ); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined && elem.nodeType === 1 ) { + return elem.innerHTML; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { + + value = jQuery.htmlPrefilter( value ); + + try { + for ( ; i < l; i++ ) { + elem = this[ i ] || {}; + + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch ( e ) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var ignored = []; + + // Make the changes, replacing each non-ignored context element with the new content + return domManip( this, arguments, function( elem ) { + var parent = this.parentNode; + + if ( jQuery.inArray( this, ignored ) < 0 ) { + jQuery.cleanData( getAll( this ) ); + if ( parent ) { + parent.replaceChild( elem, this ); + } + } + + // Force callback invocation + }, ignored ); + } +} ); + +jQuery.each( { + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1, + i = 0; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone( true ); + jQuery( insert[ i ] )[ original ]( elems ); + + // Support: Android <=4.0 only, PhantomJS 1 only + // .get() because push.apply(_, arraylike) throws on ancient WebKit + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +} ); +var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); + +var getStyles = function( elem ) { + + // Support: IE <=11 only, Firefox <=30 (#15098, #14150) + // IE throws on elements created in popups + // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" + var view = elem.ownerDocument.defaultView; + + if ( !view || !view.opener ) { + view = window; + } + + return view.getComputedStyle( elem ); + }; + +var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); + + + +( function() { + + // Executing both pixelPosition & boxSizingReliable tests require only one layout + // so they're executed at the same time to save the second computation. + function computeStyleTests() { + + // This is a singleton, we need to execute it only once + if ( !div ) { + return; + } + + container.style.cssText = "position:absolute;left:-11111px;width:60px;" + + "margin-top:1px;padding:0;border:0"; + div.style.cssText = + "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + + "margin:auto;border:1px;padding:1px;" + + "width:60%;top:1%"; + documentElement.appendChild( container ).appendChild( div ); + + var divStyle = window.getComputedStyle( div ); + pixelPositionVal = divStyle.top !== "1%"; + + // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 + reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; + + // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 + // Some styles come back with percentage values, even though they shouldn't + div.style.right = "60%"; + pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; + + // Support: IE 9 - 11 only + // Detect misreporting of content dimensions for box-sizing:border-box elements + boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; + + // Support: IE 9 only + // Detect overflow:scroll screwiness (gh-3699) + div.style.position = "absolute"; + scrollboxSizeVal = div.offsetWidth === 36 || "absolute"; + + documentElement.removeChild( container ); + + // Nullify the div so it wouldn't be stored in the memory and + // it will also be a sign that checks already performed + div = null; + } + + function roundPixelMeasures( measure ) { + return Math.round( parseFloat( measure ) ); + } + + var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, + reliableMarginLeftVal, + container = document.createElement( "div" ), + div = document.createElement( "div" ); + + // Finish early in limited (non-browser) environments + if ( !div.style ) { + return; + } + + // Support: IE <=9 - 11 only + // Style of cloned element affects source element cloned (#8908) + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; + + jQuery.extend( support, { + boxSizingReliable: function() { + computeStyleTests(); + return boxSizingReliableVal; + }, + pixelBoxStyles: function() { + computeStyleTests(); + return pixelBoxStylesVal; + }, + pixelPosition: function() { + computeStyleTests(); + return pixelPositionVal; + }, + reliableMarginLeft: function() { + computeStyleTests(); + return reliableMarginLeftVal; + }, + scrollboxSize: function() { + computeStyleTests(); + return scrollboxSizeVal; + } + } ); +} )(); + + +function curCSS( elem, name, computed ) { + var width, minWidth, maxWidth, ret, + + // Support: Firefox 51+ + // Retrieving style before computed somehow + // fixes an issue with getting wrong values + // on detached elements + style = elem.style; + + computed = computed || getStyles( elem ); + + // getPropertyValue is needed for: + // .css('filter') (IE 9 only, #12537) + // .css('--customProperty) (#3144) + if ( computed ) { + ret = computed.getPropertyValue( name ) || computed[ name ]; + + if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Android Browser returns percentage for some values, + // but width seems to be reliably pixels. + // This is against the CSSOM draft spec: + // https://drafts.csswg.org/cssom/#resolved-values + if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { + + // Remember the original values + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + // Put in the new values to get a computed value out + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + // Revert the changed values + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret !== undefined ? + + // Support: IE <=9 - 11 only + // IE returns zIndex value as an integer. + ret + "" : + ret; +} + + +function addGetHookIf( conditionFn, hookFn ) { + + // Define the hook, we'll check on the first run if it's really needed. + return { + get: function() { + if ( conditionFn() ) { + + // Hook not needed (or it's not possible to use it due + // to missing dependency), remove it. + delete this.get; + return; + } + + // Hook needed; redefine it so that the support test is not executed again. + return ( this.get = hookFn ).apply( this, arguments ); + } + }; +} + + +var + + // Swappable if display is none or starts with table + // except "table", "table-cell", or "table-caption" + // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + rcustomProp = /^--/, + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: "0", + fontWeight: "400" + }, + + cssPrefixes = [ "Webkit", "Moz", "ms" ], + emptyStyle = document.createElement( "div" ).style; + +// Return a css property mapped to a potentially vendor prefixed property +function vendorPropName( name ) { + + // Shortcut for names that are not vendor prefixed + if ( name in emptyStyle ) { + return name; + } + + // Check for vendor prefixed names + var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in emptyStyle ) { + return name; + } + } +} + +// Return a property mapped along what jQuery.cssProps suggests or to +// a vendor prefixed property. +function finalPropName( name ) { + var ret = jQuery.cssProps[ name ]; + if ( !ret ) { + ret = jQuery.cssProps[ name ] = vendorPropName( name ) || name; + } + return ret; +} + +function setPositiveNumber( elem, value, subtract ) { + + // Any relative (+/-) values have already been + // normalized at this point + var matches = rcssNum.exec( value ); + return matches ? + + // Guard against undefined "subtract", e.g., when used as in cssHooks + Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : + value; +} + +function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { + var i = dimension === "width" ? 1 : 0, + extra = 0, + delta = 0; + + // Adjustment may not be necessary + if ( box === ( isBorderBox ? "border" : "content" ) ) { + return 0; + } + + for ( ; i < 4; i += 2 ) { + + // Both box models exclude margin + if ( box === "margin" ) { + delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); + } + + // If we get here with a content-box, we're seeking "padding" or "border" or "margin" + if ( !isBorderBox ) { + + // Add padding + delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // For "border" or "margin", add border + if ( box !== "padding" ) { + delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + + // But still keep track of it otherwise + } else { + extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + + // If we get here with a border-box (content + padding + border), we're seeking "content" or + // "padding" or "margin" + } else { + + // For "content", subtract padding + if ( box === "content" ) { + delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // For "content" or "padding", subtract border + if ( box !== "margin" ) { + delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + // Account for positive content-box scroll gutter when requested by providing computedVal + if ( !isBorderBox && computedVal >= 0 ) { + + // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border + // Assuming integer scroll gutter, subtract the rest and round down + delta += Math.max( 0, Math.ceil( + elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - + computedVal - + delta - + extra - + 0.5 + ) ); + } + + return delta; +} + +function getWidthOrHeight( elem, dimension, extra ) { + + // Start with computed style + var styles = getStyles( elem ), + val = curCSS( elem, dimension, styles ), + isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + valueIsBorderBox = isBorderBox; + + // Support: Firefox <=54 + // Return a confounding non-pixel value or feign ignorance, as appropriate. + if ( rnumnonpx.test( val ) ) { + if ( !extra ) { + return val; + } + val = "auto"; + } + + // Check for style in case a browser which returns unreliable values + // for getComputedStyle silently falls back to the reliable elem.style + valueIsBorderBox = valueIsBorderBox && + ( support.boxSizingReliable() || val === elem.style[ dimension ] ); + + // Fall back to offsetWidth/offsetHeight when value is "auto" + // This happens for inline elements with no explicit setting (gh-3571) + // Support: Android <=4.1 - 4.3 only + // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) + if ( val === "auto" || + !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) { + + val = elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ]; + + // offsetWidth/offsetHeight provide border-box values + valueIsBorderBox = true; + } + + // Normalize "" and auto + val = parseFloat( val ) || 0; + + // Adjust for the element's box model + return ( val + + boxModelAdjustment( + elem, + dimension, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles, + + // Provide the current computed size to request scroll gutter calculation (gh-3589) + val + ) + ) + "px"; +} + +jQuery.extend( { + + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + } + } + } + }, + + // Don't automatically add "px" to these possibly-unitless properties + cssNumber: { + "animationIterationCount": true, + "columnCount": true, + "fillOpacity": true, + "flexGrow": true, + "flexShrink": true, + "fontWeight": true, + "lineHeight": true, + "opacity": true, + "order": true, + "orphans": true, + "widows": true, + "zIndex": true, + "zoom": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: {}, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = camelCase( name ), + isCustomProp = rcustomProp.test( name ), + style = elem.style; + + // Make sure that we're working with the right name. We don't + // want to query the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Gets hook for the prefixed version, then unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // Convert "+=" or "-=" to relative numbers (#7345) + if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { + value = adjustCSS( elem, name, ret ); + + // Fixes bug #9237 + type = "number"; + } + + // Make sure that null and NaN values aren't set (#7116) + if ( value == null || value !== value ) { + return; + } + + // If a number was passed in, add the unit (except for certain CSS properties) + if ( type === "number" ) { + value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); + } + + // background-* props affect original clone's values + if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { + style[ name ] = "inherit"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !( "set" in hooks ) || + ( value = hooks.set( elem, value, extra ) ) !== undefined ) { + + if ( isCustomProp ) { + style.setProperty( name, value ); + } else { + style[ name ] = value; + } + } + + } else { + + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && + ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { + + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra, styles ) { + var val, num, hooks, + origName = camelCase( name ), + isCustomProp = rcustomProp.test( name ); + + // Make sure that we're working with the right name. We don't + // want to modify the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Try prefixed name followed by the unprefixed name + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name, styles ); + } + + // Convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Make numeric if forced or a qualifier was provided and val looks numeric + if ( extra === "" || extra ) { + num = parseFloat( val ); + return extra === true || isFinite( num ) ? num || 0 : val; + } + + return val; + } +} ); + +jQuery.each( [ "height", "width" ], function( i, dimension ) { + jQuery.cssHooks[ dimension ] = { + get: function( elem, computed, extra ) { + if ( computed ) { + + // Certain elements can have dimension info if we invisibly show them + // but it must have a current display style that would benefit + return rdisplayswap.test( jQuery.css( elem, "display" ) ) && + + // Support: Safari 8+ + // Table columns in Safari have non-zero offsetWidth & zero + // getBoundingClientRect().width unless display is changed. + // Support: IE <=11 only + // Running getBoundingClientRect on a disconnected node + // in IE throws an error. + ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? + swap( elem, cssShow, function() { + return getWidthOrHeight( elem, dimension, extra ); + } ) : + getWidthOrHeight( elem, dimension, extra ); + } + }, + + set: function( elem, value, extra ) { + var matches, + styles = getStyles( elem ), + isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + subtract = extra && boxModelAdjustment( + elem, + dimension, + extra, + isBorderBox, + styles + ); + + // Account for unreliable border-box dimensions by comparing offset* to computed and + // faking a content-box to get border and padding (gh-3699) + if ( isBorderBox && support.scrollboxSize() === styles.position ) { + subtract -= Math.ceil( + elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - + parseFloat( styles[ dimension ] ) - + boxModelAdjustment( elem, dimension, "border", false, styles ) - + 0.5 + ); + } + + // Convert to pixels if value adjustment is needed + if ( subtract && ( matches = rcssNum.exec( value ) ) && + ( matches[ 3 ] || "px" ) !== "px" ) { + + elem.style[ dimension ] = value; + value = jQuery.css( elem, dimension ); + } + + return setPositiveNumber( elem, value, subtract ); + } + }; +} ); + +jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, + function( elem, computed ) { + if ( computed ) { + return ( parseFloat( curCSS( elem, "marginLeft" ) ) || + elem.getBoundingClientRect().left - + swap( elem, { marginLeft: 0 }, function() { + return elem.getBoundingClientRect().left; + } ) + ) + "px"; + } + } +); + +// These hooks are used by animate to expand properties +jQuery.each( { + margin: "", + padding: "", + border: "Width" +}, function( prefix, suffix ) { + jQuery.cssHooks[ prefix + suffix ] = { + expand: function( value ) { + var i = 0, + expanded = {}, + + // Assumes a single number if not a string + parts = typeof value === "string" ? value.split( " " ) : [ value ]; + + for ( ; i < 4; i++ ) { + expanded[ prefix + cssExpand[ i ] + suffix ] = + parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; + } + + return expanded; + } + }; + + if ( prefix !== "margin" ) { + jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; + } +} ); + +jQuery.fn.extend( { + css: function( name, value ) { + return access( this, function( elem, name, value ) { + var styles, len, + map = {}, + i = 0; + + if ( Array.isArray( name ) ) { + styles = getStyles( elem ); + len = name.length; + + for ( ; i < len; i++ ) { + map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); + } + + return map; + } + + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + } +} ); + + +function Tween( elem, options, prop, end, easing ) { + return new Tween.prototype.init( elem, options, prop, end, easing ); +} +jQuery.Tween = Tween; + +Tween.prototype = { + constructor: Tween, + init: function( elem, options, prop, end, easing, unit ) { + this.elem = elem; + this.prop = prop; + this.easing = easing || jQuery.easing._default; + this.options = options; + this.start = this.now = this.cur(); + this.end = end; + this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); + }, + cur: function() { + var hooks = Tween.propHooks[ this.prop ]; + + return hooks && hooks.get ? + hooks.get( this ) : + Tween.propHooks._default.get( this ); + }, + run: function( percent ) { + var eased, + hooks = Tween.propHooks[ this.prop ]; + + if ( this.options.duration ) { + this.pos = eased = jQuery.easing[ this.easing ]( + percent, this.options.duration * percent, 0, 1, this.options.duration + ); + } else { + this.pos = eased = percent; + } + this.now = ( this.end - this.start ) * eased + this.start; + + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + if ( hooks && hooks.set ) { + hooks.set( this ); + } else { + Tween.propHooks._default.set( this ); + } + return this; + } +}; + +Tween.prototype.init.prototype = Tween.prototype; + +Tween.propHooks = { + _default: { + get: function( tween ) { + var result; + + // Use a property on the element directly when it is not a DOM element, + // or when there is no matching style property that exists. + if ( tween.elem.nodeType !== 1 || + tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { + return tween.elem[ tween.prop ]; + } + + // Passing an empty string as a 3rd parameter to .css will automatically + // attempt a parseFloat and fallback to a string if the parse fails. + // Simple values such as "10px" are parsed to Float; + // complex values such as "rotate(1rad)" are returned as-is. + result = jQuery.css( tween.elem, tween.prop, "" ); + + // Empty strings, null, undefined and "auto" are converted to 0. + return !result || result === "auto" ? 0 : result; + }, + set: function( tween ) { + + // Use step hook for back compat. + // Use cssHook if its there. + // Use .style if available and use plain properties where available. + if ( jQuery.fx.step[ tween.prop ] ) { + jQuery.fx.step[ tween.prop ]( tween ); + } else if ( tween.elem.nodeType === 1 && + ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || + jQuery.cssHooks[ tween.prop ] ) ) { + jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); + } else { + tween.elem[ tween.prop ] = tween.now; + } + } + } +}; + +// Support: IE <=9 only +// Panic based approach to setting things on disconnected nodes +Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { + set: function( tween ) { + if ( tween.elem.nodeType && tween.elem.parentNode ) { + tween.elem[ tween.prop ] = tween.now; + } + } +}; + +jQuery.easing = { + linear: function( p ) { + return p; + }, + swing: function( p ) { + return 0.5 - Math.cos( p * Math.PI ) / 2; + }, + _default: "swing" +}; + +jQuery.fx = Tween.prototype.init; + +// Back compat <1.8 extension point +jQuery.fx.step = {}; + + + + +var + fxNow, inProgress, + rfxtypes = /^(?:toggle|show|hide)$/, + rrun = /queueHooks$/; + +function schedule() { + if ( inProgress ) { + if ( document.hidden === false && window.requestAnimationFrame ) { + window.requestAnimationFrame( schedule ); + } else { + window.setTimeout( schedule, jQuery.fx.interval ); + } + + jQuery.fx.tick(); + } +} + +// Animations created synchronously will run synchronously +function createFxNow() { + window.setTimeout( function() { + fxNow = undefined; + } ); + return ( fxNow = Date.now() ); +} + +// Generate parameters to create a standard animation +function genFx( type, includeWidth ) { + var which, + i = 0, + attrs = { height: type }; + + // If we include width, step value is 1 to do all cssExpand values, + // otherwise step value is 2 to skip over Left and Right + includeWidth = includeWidth ? 1 : 0; + for ( ; i < 4; i += 2 - includeWidth ) { + which = cssExpand[ i ]; + attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; + } + + if ( includeWidth ) { + attrs.opacity = attrs.width = type; + } + + return attrs; +} + +function createTween( value, prop, animation ) { + var tween, + collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), + index = 0, + length = collection.length; + for ( ; index < length; index++ ) { + if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { + + // We're done with this property + return tween; + } + } +} + +function defaultPrefilter( elem, props, opts ) { + var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, + isBox = "width" in props || "height" in props, + anim = this, + orig = {}, + style = elem.style, + hidden = elem.nodeType && isHiddenWithinTree( elem ), + dataShow = dataPriv.get( elem, "fxshow" ); + + // Queue-skipping animations hijack the fx hooks + if ( !opts.queue ) { + hooks = jQuery._queueHooks( elem, "fx" ); + if ( hooks.unqueued == null ) { + hooks.unqueued = 0; + oldfire = hooks.empty.fire; + hooks.empty.fire = function() { + if ( !hooks.unqueued ) { + oldfire(); + } + }; + } + hooks.unqueued++; + + anim.always( function() { + + // Ensure the complete handler is called before this completes + anim.always( function() { + hooks.unqueued--; + if ( !jQuery.queue( elem, "fx" ).length ) { + hooks.empty.fire(); + } + } ); + } ); + } + + // Detect show/hide animations + for ( prop in props ) { + value = props[ prop ]; + if ( rfxtypes.test( value ) ) { + delete props[ prop ]; + toggle = toggle || value === "toggle"; + if ( value === ( hidden ? "hide" : "show" ) ) { + + // Pretend to be hidden if this is a "show" and + // there is still data from a stopped show/hide + if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { + hidden = true; + + // Ignore all other no-op show/hide data + } else { + continue; + } + } + orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); + } + } + + // Bail out if this is a no-op like .hide().hide() + propTween = !jQuery.isEmptyObject( props ); + if ( !propTween && jQuery.isEmptyObject( orig ) ) { + return; + } + + // Restrict "overflow" and "display" styles during box animations + if ( isBox && elem.nodeType === 1 ) { + + // Support: IE <=9 - 11, Edge 12 - 15 + // Record all 3 overflow attributes because IE does not infer the shorthand + // from identically-valued overflowX and overflowY and Edge just mirrors + // the overflowX value there. + opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; + + // Identify a display type, preferring old show/hide data over the CSS cascade + restoreDisplay = dataShow && dataShow.display; + if ( restoreDisplay == null ) { + restoreDisplay = dataPriv.get( elem, "display" ); + } + display = jQuery.css( elem, "display" ); + if ( display === "none" ) { + if ( restoreDisplay ) { + display = restoreDisplay; + } else { + + // Get nonempty value(s) by temporarily forcing visibility + showHide( [ elem ], true ); + restoreDisplay = elem.style.display || restoreDisplay; + display = jQuery.css( elem, "display" ); + showHide( [ elem ] ); + } + } + + // Animate inline elements as inline-block + if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { + if ( jQuery.css( elem, "float" ) === "none" ) { + + // Restore the original display value at the end of pure show/hide animations + if ( !propTween ) { + anim.done( function() { + style.display = restoreDisplay; + } ); + if ( restoreDisplay == null ) { + display = style.display; + restoreDisplay = display === "none" ? "" : display; + } + } + style.display = "inline-block"; + } + } + } + + if ( opts.overflow ) { + style.overflow = "hidden"; + anim.always( function() { + style.overflow = opts.overflow[ 0 ]; + style.overflowX = opts.overflow[ 1 ]; + style.overflowY = opts.overflow[ 2 ]; + } ); + } + + // Implement show/hide animations + propTween = false; + for ( prop in orig ) { + + // General show/hide setup for this element animation + if ( !propTween ) { + if ( dataShow ) { + if ( "hidden" in dataShow ) { + hidden = dataShow.hidden; + } + } else { + dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); + } + + // Store hidden/visible for toggle so `.stop().toggle()` "reverses" + if ( toggle ) { + dataShow.hidden = !hidden; + } + + // Show elements before animating them + if ( hidden ) { + showHide( [ elem ], true ); + } + + /* eslint-disable no-loop-func */ + + anim.done( function() { + + /* eslint-enable no-loop-func */ + + // The final step of a "hide" animation is actually hiding the element + if ( !hidden ) { + showHide( [ elem ] ); + } + dataPriv.remove( elem, "fxshow" ); + for ( prop in orig ) { + jQuery.style( elem, prop, orig[ prop ] ); + } + } ); + } + + // Per-property setup + propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); + if ( !( prop in dataShow ) ) { + dataShow[ prop ] = propTween.start; + if ( hidden ) { + propTween.end = propTween.start; + propTween.start = 0; + } + } + } +} + +function propFilter( props, specialEasing ) { + var index, name, easing, value, hooks; + + // camelCase, specialEasing and expand cssHook pass + for ( index in props ) { + name = camelCase( index ); + easing = specialEasing[ name ]; + value = props[ index ]; + if ( Array.isArray( value ) ) { + easing = value[ 1 ]; + value = props[ index ] = value[ 0 ]; + } + + if ( index !== name ) { + props[ name ] = value; + delete props[ index ]; + } + + hooks = jQuery.cssHooks[ name ]; + if ( hooks && "expand" in hooks ) { + value = hooks.expand( value ); + delete props[ name ]; + + // Not quite $.extend, this won't overwrite existing keys. + // Reusing 'index' because we have the correct "name" + for ( index in value ) { + if ( !( index in props ) ) { + props[ index ] = value[ index ]; + specialEasing[ index ] = easing; + } + } + } else { + specialEasing[ name ] = easing; + } + } +} + +function Animation( elem, properties, options ) { + var result, + stopped, + index = 0, + length = Animation.prefilters.length, + deferred = jQuery.Deferred().always( function() { + + // Don't match elem in the :animated selector + delete tick.elem; + } ), + tick = function() { + if ( stopped ) { + return false; + } + var currentTime = fxNow || createFxNow(), + remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), + + // Support: Android 2.3 only + // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) + temp = remaining / animation.duration || 0, + percent = 1 - temp, + index = 0, + length = animation.tweens.length; + + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( percent ); + } + + deferred.notifyWith( elem, [ animation, percent, remaining ] ); + + // If there's more to do, yield + if ( percent < 1 && length ) { + return remaining; + } + + // If this was an empty animation, synthesize a final progress notification + if ( !length ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + } + + // Resolve the animation and report its conclusion + deferred.resolveWith( elem, [ animation ] ); + return false; + }, + animation = deferred.promise( { + elem: elem, + props: jQuery.extend( {}, properties ), + opts: jQuery.extend( true, { + specialEasing: {}, + easing: jQuery.easing._default + }, options ), + originalProperties: properties, + originalOptions: options, + startTime: fxNow || createFxNow(), + duration: options.duration, + tweens: [], + createTween: function( prop, end ) { + var tween = jQuery.Tween( elem, animation.opts, prop, end, + animation.opts.specialEasing[ prop ] || animation.opts.easing ); + animation.tweens.push( tween ); + return tween; + }, + stop: function( gotoEnd ) { + var index = 0, + + // If we are going to the end, we want to run all the tweens + // otherwise we skip this part + length = gotoEnd ? animation.tweens.length : 0; + if ( stopped ) { + return this; + } + stopped = true; + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( 1 ); + } + + // Resolve when we played the last frame; otherwise, reject + if ( gotoEnd ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + deferred.resolveWith( elem, [ animation, gotoEnd ] ); + } else { + deferred.rejectWith( elem, [ animation, gotoEnd ] ); + } + return this; + } + } ), + props = animation.props; + + propFilter( props, animation.opts.specialEasing ); + + for ( ; index < length; index++ ) { + result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); + if ( result ) { + if ( isFunction( result.stop ) ) { + jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = + result.stop.bind( result ); + } + return result; + } + } + + jQuery.map( props, createTween, animation ); + + if ( isFunction( animation.opts.start ) ) { + animation.opts.start.call( elem, animation ); + } + + // Attach callbacks from options + animation + .progress( animation.opts.progress ) + .done( animation.opts.done, animation.opts.complete ) + .fail( animation.opts.fail ) + .always( animation.opts.always ); + + jQuery.fx.timer( + jQuery.extend( tick, { + elem: elem, + anim: animation, + queue: animation.opts.queue + } ) + ); + + return animation; +} + +jQuery.Animation = jQuery.extend( Animation, { + + tweeners: { + "*": [ function( prop, value ) { + var tween = this.createTween( prop, value ); + adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); + return tween; + } ] + }, + + tweener: function( props, callback ) { + if ( isFunction( props ) ) { + callback = props; + props = [ "*" ]; + } else { + props = props.match( rnothtmlwhite ); + } + + var prop, + index = 0, + length = props.length; + + for ( ; index < length; index++ ) { + prop = props[ index ]; + Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; + Animation.tweeners[ prop ].unshift( callback ); + } + }, + + prefilters: [ defaultPrefilter ], + + prefilter: function( callback, prepend ) { + if ( prepend ) { + Animation.prefilters.unshift( callback ); + } else { + Animation.prefilters.push( callback ); + } + } +} ); + +jQuery.speed = function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { + complete: fn || !fn && easing || + isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !isFunction( easing ) && easing + }; + + // Go to the end state if fx are off + if ( jQuery.fx.off ) { + opt.duration = 0; + + } else { + if ( typeof opt.duration !== "number" ) { + if ( opt.duration in jQuery.fx.speeds ) { + opt.duration = jQuery.fx.speeds[ opt.duration ]; + + } else { + opt.duration = jQuery.fx.speeds._default; + } + } + } + + // Normalize opt.queue - true/undefined/null -> "fx" + if ( opt.queue == null || opt.queue === true ) { + opt.queue = "fx"; + } + + // Queueing + opt.old = opt.complete; + + opt.complete = function() { + if ( isFunction( opt.old ) ) { + opt.old.call( this ); + } + + if ( opt.queue ) { + jQuery.dequeue( this, opt.queue ); + } + }; + + return opt; +}; + +jQuery.fn.extend( { + fadeTo: function( speed, to, easing, callback ) { + + // Show any hidden elements after setting opacity to 0 + return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() + + // Animate to the value specified + .end().animate( { opacity: to }, speed, easing, callback ); + }, + animate: function( prop, speed, easing, callback ) { + var empty = jQuery.isEmptyObject( prop ), + optall = jQuery.speed( speed, easing, callback ), + doAnimation = function() { + + // Operate on a copy of prop so per-property easing won't be lost + var anim = Animation( this, jQuery.extend( {}, prop ), optall ); + + // Empty animations, or finishing resolves immediately + if ( empty || dataPriv.get( this, "finish" ) ) { + anim.stop( true ); + } + }; + doAnimation.finish = doAnimation; + + return empty || optall.queue === false ? + this.each( doAnimation ) : + this.queue( optall.queue, doAnimation ); + }, + stop: function( type, clearQueue, gotoEnd ) { + var stopQueue = function( hooks ) { + var stop = hooks.stop; + delete hooks.stop; + stop( gotoEnd ); + }; + + if ( typeof type !== "string" ) { + gotoEnd = clearQueue; + clearQueue = type; + type = undefined; + } + if ( clearQueue && type !== false ) { + this.queue( type || "fx", [] ); + } + + return this.each( function() { + var dequeue = true, + index = type != null && type + "queueHooks", + timers = jQuery.timers, + data = dataPriv.get( this ); + + if ( index ) { + if ( data[ index ] && data[ index ].stop ) { + stopQueue( data[ index ] ); + } + } else { + for ( index in data ) { + if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { + stopQueue( data[ index ] ); + } + } + } + + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && + ( type == null || timers[ index ].queue === type ) ) { + + timers[ index ].anim.stop( gotoEnd ); + dequeue = false; + timers.splice( index, 1 ); + } + } + + // Start the next in the queue if the last step wasn't forced. + // Timers currently will call their complete callbacks, which + // will dequeue but only if they were gotoEnd. + if ( dequeue || !gotoEnd ) { + jQuery.dequeue( this, type ); + } + } ); + }, + finish: function( type ) { + if ( type !== false ) { + type = type || "fx"; + } + return this.each( function() { + var index, + data = dataPriv.get( this ), + queue = data[ type + "queue" ], + hooks = data[ type + "queueHooks" ], + timers = jQuery.timers, + length = queue ? queue.length : 0; + + // Enable finishing flag on private data + data.finish = true; + + // Empty the queue first + jQuery.queue( this, type, [] ); + + if ( hooks && hooks.stop ) { + hooks.stop.call( this, true ); + } + + // Look for any active animations, and finish them + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && timers[ index ].queue === type ) { + timers[ index ].anim.stop( true ); + timers.splice( index, 1 ); + } + } + + // Look for any animations in the old queue and finish them + for ( index = 0; index < length; index++ ) { + if ( queue[ index ] && queue[ index ].finish ) { + queue[ index ].finish.call( this ); + } + } + + // Turn off finishing flag + delete data.finish; + } ); + } +} ); + +jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) { + var cssFn = jQuery.fn[ name ]; + jQuery.fn[ name ] = function( speed, easing, callback ) { + return speed == null || typeof speed === "boolean" ? + cssFn.apply( this, arguments ) : + this.animate( genFx( name, true ), speed, easing, callback ); + }; +} ); + +// Generate shortcuts for custom animations +jQuery.each( { + slideDown: genFx( "show" ), + slideUp: genFx( "hide" ), + slideToggle: genFx( "toggle" ), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" }, + fadeToggle: { opacity: "toggle" } +}, function( name, props ) { + jQuery.fn[ name ] = function( speed, easing, callback ) { + return this.animate( props, speed, easing, callback ); + }; +} ); + +jQuery.timers = []; +jQuery.fx.tick = function() { + var timer, + i = 0, + timers = jQuery.timers; + + fxNow = Date.now(); + + for ( ; i < timers.length; i++ ) { + timer = timers[ i ]; + + // Run the timer and safely remove it when done (allowing for external removal) + if ( !timer() && timers[ i ] === timer ) { + timers.splice( i--, 1 ); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + fxNow = undefined; +}; + +jQuery.fx.timer = function( timer ) { + jQuery.timers.push( timer ); + jQuery.fx.start(); +}; + +jQuery.fx.interval = 13; +jQuery.fx.start = function() { + if ( inProgress ) { + return; + } + + inProgress = true; + schedule(); +}; + +jQuery.fx.stop = function() { + inProgress = null; +}; + +jQuery.fx.speeds = { + slow: 600, + fast: 200, + + // Default speed + _default: 400 +}; + + +// Based off of the plugin by Clint Helfers, with permission. +// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ +jQuery.fn.delay = function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = window.setTimeout( next, time ); + hooks.stop = function() { + window.clearTimeout( timeout ); + }; + } ); +}; + + +( function() { + var input = document.createElement( "input" ), + select = document.createElement( "select" ), + opt = select.appendChild( document.createElement( "option" ) ); + + input.type = "checkbox"; + + // Support: Android <=4.3 only + // Default value for a checkbox should be "on" + support.checkOn = input.value !== ""; + + // Support: IE <=11 only + // Must access selectedIndex to make default options select + support.optSelected = opt.selected; + + // Support: IE <=11 only + // An input loses its value after becoming a radio + input = document.createElement( "input" ); + input.value = "t"; + input.type = "radio"; + support.radioValue = input.value === "t"; +} )(); + + +var boolHook, + attrHandle = jQuery.expr.attrHandle; + +jQuery.fn.extend( { + attr: function( name, value ) { + return access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each( function() { + jQuery.removeAttr( this, name ); + } ); + } +} ); + +jQuery.extend( { + attr: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set attributes on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + // Attribute hooks are determined by the lowercase version + // Grab necessary hook if one is defined + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + hooks = jQuery.attrHooks[ name.toLowerCase() ] || + ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); + } + + if ( value !== undefined ) { + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + } + + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + elem.setAttribute( name, value + "" ); + return value; + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + ret = jQuery.find.attr( elem, name ); + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? undefined : ret; + }, + + attrHooks: { + type: { + set: function( elem, value ) { + if ( !support.radioValue && value === "radio" && + nodeName( elem, "input" ) ) { + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + } + }, + + removeAttr: function( elem, value ) { + var name, + i = 0, + + // Attribute names can contain non-HTML whitespace characters + // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 + attrNames = value && value.match( rnothtmlwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( ( name = attrNames[ i++ ] ) ) { + elem.removeAttribute( name ); + } + } + } +} ); + +// Hooks for boolean attributes +boolHook = { + set: function( elem, value, name ) { + if ( value === false ) { + + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + elem.setAttribute( name, name ); + } + return name; + } +}; + +jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { + var getter = attrHandle[ name ] || jQuery.find.attr; + + attrHandle[ name ] = function( elem, name, isXML ) { + var ret, handle, + lowercaseName = name.toLowerCase(); + + if ( !isXML ) { + + // Avoid an infinite loop by temporarily removing this function from the getter + handle = attrHandle[ lowercaseName ]; + attrHandle[ lowercaseName ] = ret; + ret = getter( elem, name, isXML ) != null ? + lowercaseName : + null; + attrHandle[ lowercaseName ] = handle; + } + return ret; + }; +} ); + + + + +var rfocusable = /^(?:input|select|textarea|button)$/i, + rclickable = /^(?:a|area)$/i; + +jQuery.fn.extend( { + prop: function( name, value ) { + return access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + return this.each( function() { + delete this[ jQuery.propFix[ name ] || name ]; + } ); + } +} ); + +jQuery.extend( { + prop: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set properties on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + return ( elem[ name ] = value ); + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + return elem[ name ]; + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + + // Support: IE <=9 - 11 only + // elem.tabIndex doesn't always return the + // correct value when it hasn't been explicitly set + // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + // Use proper attribute retrieval(#12072) + var tabindex = jQuery.find.attr( elem, "tabindex" ); + + if ( tabindex ) { + return parseInt( tabindex, 10 ); + } + + if ( + rfocusable.test( elem.nodeName ) || + rclickable.test( elem.nodeName ) && + elem.href + ) { + return 0; + } + + return -1; + } + } + }, + + propFix: { + "for": "htmlFor", + "class": "className" + } +} ); + +// Support: IE <=11 only +// Accessing the selectedIndex property +// forces the browser to respect setting selected +// on the option +// The getter ensures a default option is selected +// when in an optgroup +// eslint rule "no-unused-expressions" is disabled for this code +// since it considers such accessions noop +if ( !support.optSelected ) { + jQuery.propHooks.selected = { + get: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent && parent.parentNode ) { + parent.parentNode.selectedIndex; + } + return null; + }, + set: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent ) { + parent.selectedIndex; + + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + } + }; +} + +jQuery.each( [ + "tabIndex", + "readOnly", + "maxLength", + "cellSpacing", + "cellPadding", + "rowSpan", + "colSpan", + "useMap", + "frameBorder", + "contentEditable" +], function() { + jQuery.propFix[ this.toLowerCase() ] = this; +} ); + + + + + // Strip and collapse whitespace according to HTML spec + // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace + function stripAndCollapse( value ) { + var tokens = value.match( rnothtmlwhite ) || []; + return tokens.join( " " ); + } + + +function getClass( elem ) { + return elem.getAttribute && elem.getAttribute( "class" ) || ""; +} + +function classesToArray( value ) { + if ( Array.isArray( value ) ) { + return value; + } + if ( typeof value === "string" ) { + return value.match( rnothtmlwhite ) || []; + } + return []; +} + +jQuery.fn.extend( { + addClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + classes = classesToArray( value ); + + if ( classes.length ) { + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + if ( cur.indexOf( " " + clazz + " " ) < 0 ) { + cur += clazz + " "; + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + if ( !arguments.length ) { + return this.attr( "class", "" ); + } + + classes = classesToArray( value ); + + if ( classes.length ) { + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + + // This expression is here for better compressibility (see addClass) + cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + + // Remove *all* instances + while ( cur.indexOf( " " + clazz + " " ) > -1 ) { + cur = cur.replace( " " + clazz + " ", " " ); + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isValidValue = type === "string" || Array.isArray( value ); + + if ( typeof stateVal === "boolean" && isValidValue ) { + return stateVal ? this.addClass( value ) : this.removeClass( value ); + } + + if ( isFunction( value ) ) { + return this.each( function( i ) { + jQuery( this ).toggleClass( + value.call( this, i, getClass( this ), stateVal ), + stateVal + ); + } ); + } + + return this.each( function() { + var className, i, self, classNames; + + if ( isValidValue ) { + + // Toggle individual class names + i = 0; + self = jQuery( this ); + classNames = classesToArray( value ); + + while ( ( className = classNames[ i++ ] ) ) { + + // Check each className given, space separated list + if ( self.hasClass( className ) ) { + self.removeClass( className ); + } else { + self.addClass( className ); + } + } + + // Toggle whole class name + } else if ( value === undefined || type === "boolean" ) { + className = getClass( this ); + if ( className ) { + + // Store className if set + dataPriv.set( this, "__className__", className ); + } + + // If the element has a class name or if we're passed `false`, + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + if ( this.setAttribute ) { + this.setAttribute( "class", + className || value === false ? + "" : + dataPriv.get( this, "__className__" ) || "" + ); + } + } + } ); + }, + + hasClass: function( selector ) { + var className, elem, + i = 0; + + className = " " + selector + " "; + while ( ( elem = this[ i++ ] ) ) { + if ( elem.nodeType === 1 && + ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { + return true; + } + } + + return false; + } +} ); + + + + +var rreturn = /\r/g; + +jQuery.fn.extend( { + val: function( value ) { + var hooks, ret, valueIsFunction, + elem = this[ 0 ]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || + jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && + "get" in hooks && + ( ret = hooks.get( elem, "value" ) ) !== undefined + ) { + return ret; + } + + ret = elem.value; + + // Handle most common string cases + if ( typeof ret === "string" ) { + return ret.replace( rreturn, "" ); + } + + // Handle cases where value is null/undef or number + return ret == null ? "" : ret; + } + + return; + } + + valueIsFunction = isFunction( value ); + + return this.each( function( i ) { + var val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( valueIsFunction ) { + val = value.call( this, i, jQuery( this ).val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + + } else if ( typeof val === "number" ) { + val += ""; + + } else if ( Array.isArray( val ) ) { + val = jQuery.map( val, function( value ) { + return value == null ? "" : value + ""; + } ); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + } ); + } +} ); + +jQuery.extend( { + valHooks: { + option: { + get: function( elem ) { + + var val = jQuery.find.attr( elem, "value" ); + return val != null ? + val : + + // Support: IE <=10 - 11 only + // option.text throws exceptions (#14686, #14858) + // Strip and collapse whitespace + // https://html.spec.whatwg.org/#strip-and-collapse-whitespace + stripAndCollapse( jQuery.text( elem ) ); + } + }, + select: { + get: function( elem ) { + var value, option, i, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one", + values = one ? null : [], + max = one ? index + 1 : options.length; + + if ( index < 0 ) { + i = max; + + } else { + i = one ? index : 0; + } + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Support: IE <=9 only + // IE8-9 doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + + // Don't return options that are disabled or in a disabled optgroup + !option.disabled && + ( !option.parentNode.disabled || + !nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var optionSet, option, + options = elem.options, + values = jQuery.makeArray( value ), + i = options.length; + + while ( i-- ) { + option = options[ i ]; + + /* eslint-disable no-cond-assign */ + + if ( option.selected = + jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 + ) { + optionSet = true; + } + + /* eslint-enable no-cond-assign */ + } + + // Force browsers to behave consistently when non-matching value is set + if ( !optionSet ) { + elem.selectedIndex = -1; + } + return values; + } + } + } +} ); + +// Radios and checkboxes getter/setter +jQuery.each( [ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + set: function( elem, value ) { + if ( Array.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); + } + } + }; + if ( !support.checkOn ) { + jQuery.valHooks[ this ].get = function( elem ) { + return elem.getAttribute( "value" ) === null ? "on" : elem.value; + }; + } +} ); + + + + +// Return jQuery for attributes-only inclusion + + +support.focusin = "onfocusin" in window; + + +var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + stopPropagationCallback = function( e ) { + e.stopPropagation(); + }; + +jQuery.extend( jQuery.event, { + + trigger: function( event, data, elem, onlyHandlers ) { + + var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; + + cur = lastElement = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "." ) > -1 ) { + + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split( "." ); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf( ":" ) < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join( "." ); + event.rnamespace = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === ( elem.ownerDocument || document ) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { + lastElement = cur; + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] && + dataPriv.get( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( ( !special._default || + special._default.apply( eventPath.pop(), data ) === false ) && + acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name as the event. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + + if ( event.isPropagationStopped() ) { + lastElement.addEventListener( type, stopPropagationCallback ); + } + + elem[ type ](); + + if ( event.isPropagationStopped() ) { + lastElement.removeEventListener( type, stopPropagationCallback ); + } + + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + // Piggyback on a donor event to simulate a different one + // Used only for `focus(in | out)` events + simulate: function( type, elem, event ) { + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true + } + ); + + jQuery.event.trigger( e, null, elem ); + } + +} ); + +jQuery.fn.extend( { + + trigger: function( type, data ) { + return this.each( function() { + jQuery.event.trigger( type, data, this ); + } ); + }, + triggerHandler: function( type, data ) { + var elem = this[ 0 ]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +} ); + + +// Support: Firefox <=44 +// Firefox doesn't have focus(in | out) events +// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 +// +// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 +// focus(in | out) events fire after focus & blur events, +// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order +// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 +if ( !support.focusin ) { + jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler on the document while someone wants focusin/focusout + var handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + var doc = this.ownerDocument || this, + attaches = dataPriv.access( doc, fix ); + + if ( !attaches ) { + doc.addEventListener( orig, handler, true ); + } + dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this, + attaches = dataPriv.access( doc, fix ) - 1; + + if ( !attaches ) { + doc.removeEventListener( orig, handler, true ); + dataPriv.remove( doc, fix ); + + } else { + dataPriv.access( doc, fix, attaches ); + } + } + }; + } ); +} +var location = window.location; + +var nonce = Date.now(); + +var rquery = ( /\?/ ); + + + +// Cross-browser xml parsing +jQuery.parseXML = function( data ) { + var xml; + if ( !data || typeof data !== "string" ) { + return null; + } + + // Support: IE 9 - 11 only + // IE throws on parseFromString with invalid input. + try { + xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); + } catch ( e ) { + xml = undefined; + } + + if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; +}; + + +var + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, + rsubmittable = /^(?:input|select|textarea|keygen)/i; + +function buildParams( prefix, obj, traditional, add ) { + var name; + + if ( Array.isArray( obj ) ) { + + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || rbracket.test( prefix ) ) { + + // Treat each array item as a scalar. + add( prefix, v ); + + } else { + + // Item is non-scalar (array or object), encode its numeric index. + buildParams( + prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", + v, + traditional, + add + ); + } + } ); + + } else if ( !traditional && toType( obj ) === "object" ) { + + // Serialize object item. + for ( name in obj ) { + buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); + } + + } else { + + // Serialize scalar item. + add( prefix, obj ); + } +} + +// Serialize an array of form elements or a set of +// key/values into a query string +jQuery.param = function( a, traditional ) { + var prefix, + s = [], + add = function( key, valueOrFunction ) { + + // If value is a function, invoke it and use its return value + var value = isFunction( valueOrFunction ) ? + valueOrFunction() : + valueOrFunction; + + s[ s.length ] = encodeURIComponent( key ) + "=" + + encodeURIComponent( value == null ? "" : value ); + }; + + // If an array was passed in, assume that it is an array of form elements. + if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { + + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + } ); + + } else { + + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( prefix in a ) { + buildParams( prefix, a[ prefix ], traditional, add ); + } + } + + // Return the resulting serialization + return s.join( "&" ); +}; + +jQuery.fn.extend( { + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + serializeArray: function() { + return this.map( function() { + + // Can add propHook for "elements" to filter or add form elements + var elements = jQuery.prop( this, "elements" ); + return elements ? jQuery.makeArray( elements ) : this; + } ) + .filter( function() { + var type = this.type; + + // Use .is( ":disabled" ) so that fieldset[disabled] works + return this.name && !jQuery( this ).is( ":disabled" ) && + rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && + ( this.checked || !rcheckableType.test( type ) ); + } ) + .map( function( i, elem ) { + var val = jQuery( this ).val(); + + if ( val == null ) { + return null; + } + + if ( Array.isArray( val ) ) { + return jQuery.map( val, function( val ) { + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ); + } + + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ).get(); + } +} ); + + +var + r20 = /%20/g, + rhash = /#.*$/, + rantiCache = /([?&])_=[^&]*/, + rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, + + // #7653, #8125, #8152: local protocol detection + rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + + /* Prefilters + * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) + * 2) These are called: + * - BEFORE asking for a transport + * - AFTER param serialization (s.data is a string if s.processData is true) + * 3) key is the dataType + * 4) the catchall symbol "*" can be used + * 5) execution will start with transport dataType and THEN continue down to "*" if needed + */ + prefilters = {}, + + /* Transports bindings + * 1) key is the dataType + * 2) the catchall symbol "*" can be used + * 3) selection will start with transport dataType and THEN go to "*" if needed + */ + transports = {}, + + // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression + allTypes = "*/".concat( "*" ), + + // Anchor tag for parsing the document origin + originAnchor = document.createElement( "a" ); + originAnchor.href = location.href; + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport +function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + var dataType, + i = 0, + dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; + + if ( isFunction( func ) ) { + + // For each dataType in the dataTypeExpression + while ( ( dataType = dataTypes[ i++ ] ) ) { + + // Prepend if requested + if ( dataType[ 0 ] === "+" ) { + dataType = dataType.slice( 1 ) || "*"; + ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); + + // Otherwise append + } else { + ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); + } + } + } + }; +} + +// Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { + + var inspected = {}, + seekingTransport = ( structure === transports ); + + function inspect( dataType ) { + var selected; + inspected[ dataType ] = true; + jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { + var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); + if ( typeof dataTypeOrTransport === "string" && + !seekingTransport && !inspected[ dataTypeOrTransport ] ) { + + options.dataTypes.unshift( dataTypeOrTransport ); + inspect( dataTypeOrTransport ); + return false; + } else if ( seekingTransport ) { + return !( selected = dataTypeOrTransport ); + } + } ); + return selected; + } + + return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); +} + +// A special extend for ajax options +// that takes "flat" options (not to be deep extended) +// Fixes #9887 +function ajaxExtend( target, src ) { + var key, deep, + flatOptions = jQuery.ajaxSettings.flatOptions || {}; + + for ( key in src ) { + if ( src[ key ] !== undefined ) { + ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; + } + } + if ( deep ) { + jQuery.extend( true, target, deep ); + } + + return target; +} + +/* Handles responses to an ajax request: + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ +function ajaxHandleResponses( s, jqXHR, responses ) { + + var ct, type, finalDataType, firstDataType, + contents = s.contents, + dataTypes = s.dataTypes; + + // Remove auto dataType and get content-type in the process + while ( dataTypes[ 0 ] === "*" ) { + dataTypes.shift(); + if ( ct === undefined ) { + ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); + } + } + + // Check if we're dealing with a known content-type + if ( ct ) { + for ( type in contents ) { + if ( contents[ type ] && contents[ type ].test( ct ) ) { + dataTypes.unshift( type ); + break; + } + } + } + + // Check to see if we have a response for the expected dataType + if ( dataTypes[ 0 ] in responses ) { + finalDataType = dataTypes[ 0 ]; + } else { + + // Try convertible dataTypes + for ( type in responses ) { + if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { + finalDataType = type; + break; + } + if ( !firstDataType ) { + firstDataType = type; + } + } + + // Or just use first one + finalDataType = finalDataType || firstDataType; + } + + // If we found a dataType + // We add the dataType to the list if needed + // and return the corresponding response + if ( finalDataType ) { + if ( finalDataType !== dataTypes[ 0 ] ) { + dataTypes.unshift( finalDataType ); + } + return responses[ finalDataType ]; + } +} + +/* Chain conversions given the request and the original response + * Also sets the responseXXX fields on the jqXHR instance + */ +function ajaxConvert( s, response, jqXHR, isSuccess ) { + var conv2, current, conv, tmp, prev, + converters = {}, + + // Work with a copy of dataTypes in case we need to modify it for conversion + dataTypes = s.dataTypes.slice(); + + // Create converters map with lowercased keys + if ( dataTypes[ 1 ] ) { + for ( conv in s.converters ) { + converters[ conv.toLowerCase() ] = s.converters[ conv ]; + } + } + + current = dataTypes.shift(); + + // Convert to each sequential dataType + while ( current ) { + + if ( s.responseFields[ current ] ) { + jqXHR[ s.responseFields[ current ] ] = response; + } + + // Apply the dataFilter if provided + if ( !prev && isSuccess && s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + prev = current; + current = dataTypes.shift(); + + if ( current ) { + + // There's only work to do if current dataType is non-auto + if ( current === "*" ) { + + current = prev; + + // Convert response if prev dataType is non-auto and differs from current + } else if ( prev !== "*" && prev !== current ) { + + // Seek a direct converter + conv = converters[ prev + " " + current ] || converters[ "* " + current ]; + + // If none found, seek a pair + if ( !conv ) { + for ( conv2 in converters ) { + + // If conv2 outputs current + tmp = conv2.split( " " ); + if ( tmp[ 1 ] === current ) { + + // If prev can be converted to accepted input + conv = converters[ prev + " " + tmp[ 0 ] ] || + converters[ "* " + tmp[ 0 ] ]; + if ( conv ) { + + // Condense equivalence converters + if ( conv === true ) { + conv = converters[ conv2 ]; + + // Otherwise, insert the intermediate dataType + } else if ( converters[ conv2 ] !== true ) { + current = tmp[ 0 ]; + dataTypes.unshift( tmp[ 1 ] ); + } + break; + } + } + } + } + + // Apply converter (if not an equivalence) + if ( conv !== true ) { + + // Unless errors are allowed to bubble, catch and return them + if ( conv && s.throws ) { + response = conv( response ); + } else { + try { + response = conv( response ); + } catch ( e ) { + return { + state: "parsererror", + error: conv ? e : "No conversion from " + prev + " to " + current + }; + } + } + } + } + } + } + + return { state: "success", data: response }; +} + +jQuery.extend( { + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {}, + + ajaxSettings: { + url: location.href, + type: "GET", + isLocal: rlocalProtocol.test( location.protocol ), + global: true, + processData: true, + async: true, + contentType: "application/x-www-form-urlencoded; charset=UTF-8", + + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + throws: false, + traditional: false, + headers: {}, + */ + + accepts: { + "*": allTypes, + text: "text/plain", + html: "text/html", + xml: "application/xml, text/xml", + json: "application/json, text/javascript" + }, + + contents: { + xml: /\bxml\b/, + html: /\bhtml/, + json: /\bjson\b/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText", + json: "responseJSON" + }, + + // Data converters + // Keys separate source (or catchall "*") and destination types with a single space + converters: { + + // Convert anything to text + "* text": String, + + // Text to html (true = no transformation) + "text html": true, + + // Evaluate text as a json expression + "text json": JSON.parse, + + // Parse text as xml + "text xml": jQuery.parseXML + }, + + // For options that shouldn't be deep extended: + // you can add your own custom options here if + // and when you create one that shouldn't be + // deep extended (see ajaxExtend) + flatOptions: { + url: true, + context: true + } + }, + + // Creates a full fledged settings object into target + // with both ajaxSettings and settings fields. + // If target is omitted, writes into ajaxSettings. + ajaxSetup: function( target, settings ) { + return settings ? + + // Building a settings object + ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : + + // Extending ajaxSettings + ajaxExtend( jQuery.ajaxSettings, target ); + }, + + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), + + // Main method + ajax: function( url, options ) { + + // If url is an object, simulate pre-1.5 signature + if ( typeof url === "object" ) { + options = url; + url = undefined; + } + + // Force options to be an object + options = options || {}; + + var transport, + + // URL without anti-cache param + cacheURL, + + // Response headers + responseHeadersString, + responseHeaders, + + // timeout handle + timeoutTimer, + + // Url cleanup var + urlAnchor, + + // Request state (becomes false upon send and true upon completion) + completed, + + // To know if global events are to be dispatched + fireGlobals, + + // Loop variable + i, + + // uncached part of the url + uncached, + + // Create the final options object + s = jQuery.ajaxSetup( {}, options ), + + // Callbacks context + callbackContext = s.context || s, + + // Context for global events is callbackContext if it is a DOM node or jQuery collection + globalEventContext = s.context && + ( callbackContext.nodeType || callbackContext.jquery ) ? + jQuery( callbackContext ) : + jQuery.event, + + // Deferreds + deferred = jQuery.Deferred(), + completeDeferred = jQuery.Callbacks( "once memory" ), + + // Status-dependent callbacks + statusCode = s.statusCode || {}, + + // Headers (they are sent all at once) + requestHeaders = {}, + requestHeadersNames = {}, + + // Default abort message + strAbort = "canceled", + + // Fake xhr + jqXHR = { + readyState: 0, + + // Builds headers hashtable if needed + getResponseHeader: function( key ) { + var match; + if ( completed ) { + if ( !responseHeaders ) { + responseHeaders = {}; + while ( ( match = rheaders.exec( responseHeadersString ) ) ) { + responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ]; + } + } + match = responseHeaders[ key.toLowerCase() ]; + } + return match == null ? null : match; + }, + + // Raw string + getAllResponseHeaders: function() { + return completed ? responseHeadersString : null; + }, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( completed == null ) { + name = requestHeadersNames[ name.toLowerCase() ] = + requestHeadersNames[ name.toLowerCase() ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( completed == null ) { + s.mimeType = type; + } + return this; + }, + + // Status-dependent callbacks + statusCode: function( map ) { + var code; + if ( map ) { + if ( completed ) { + + // Execute the appropriate callbacks + jqXHR.always( map[ jqXHR.status ] ); + } else { + + // Lazy-add the new callbacks in a way that preserves old ones + for ( code in map ) { + statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; + } + } + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + var finalText = statusText || strAbort; + if ( transport ) { + transport.abort( finalText ); + } + done( 0, finalText ); + return this; + } + }; + + // Attach deferreds + deferred.promise( jqXHR ); + + // Add protocol if not provided (prefilters might expect it) + // Handle falsy url in the settings object (#10093: consistency with old signature) + // We also use the url parameter if available + s.url = ( ( url || s.url || location.href ) + "" ) + .replace( rprotocol, location.protocol + "//" ); + + // Alias method option to type as per ticket #12004 + s.type = options.method || options.type || s.method || s.type; + + // Extract dataTypes list + s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; + + // A cross-domain request is in order when the origin doesn't match the current origin. + if ( s.crossDomain == null ) { + urlAnchor = document.createElement( "a" ); + + // Support: IE <=8 - 11, Edge 12 - 15 + // IE throws exception on accessing the href property if url is malformed, + // e.g. http://example.com:80x/ + try { + urlAnchor.href = s.url; + + // Support: IE <=8 - 11 only + // Anchor's host property isn't correctly set when s.url is relative + urlAnchor.href = urlAnchor.href; + s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== + urlAnchor.protocol + "//" + urlAnchor.host; + } catch ( e ) { + + // If there is an error parsing the URL, assume it is crossDomain, + // it can be rejected by the transport if it is invalid + s.crossDomain = true; + } + } + + // Convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Apply prefilters + inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); + + // If request was aborted inside a prefilter, stop there + if ( completed ) { + return jqXHR; + } + + // We can fire global events as of now if asked to + // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) + fireGlobals = jQuery.event && s.global; + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Save the URL in case we're toying with the If-Modified-Since + // and/or If-None-Match header later on + // Remove hash to simplify url manipulation + cacheURL = s.url.replace( rhash, "" ); + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // Remember the hash so we can put it back + uncached = s.url.slice( cacheURL.length ); + + // If data is available and should be processed, append data to url + if ( s.data && ( s.processData || typeof s.data === "string" ) ) { + cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; + + // #9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Add or update anti-cache param if needed + if ( s.cache === false ) { + cacheURL = cacheURL.replace( rantiCache, "$1" ); + uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached; + } + + // Put hash and anti-cache on the URL that will be requested (gh-1732) + s.url = cacheURL + uncached; + + // Change '%20' to '+' if this is encoded form body content (gh-2658) + } else if ( s.data && s.processData && + ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { + s.data = s.data.replace( r20, "+" ); + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + if ( jQuery.lastModified[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); + } + if ( jQuery.etag[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); + } + } + + // Set the correct header, if data is being sent + if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { + jqXHR.setRequestHeader( "Content-Type", s.contentType ); + } + + // Set the Accepts header for the server, depending on the dataType + jqXHR.setRequestHeader( + "Accept", + s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? + s.accepts[ s.dataTypes[ 0 ] ] + + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : + s.accepts[ "*" ] + ); + + // Check for headers option + for ( i in s.headers ) { + jqXHR.setRequestHeader( i, s.headers[ i ] ); + } + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && + ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { + + // Abort if not done already and return + return jqXHR.abort(); + } + + // Aborting is no longer a cancellation + strAbort = "abort"; + + // Install callbacks on deferreds + completeDeferred.add( s.complete ); + jqXHR.done( s.success ); + jqXHR.fail( s.error ); + + // Get transport + transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); + + // If no transport, we auto-abort + if ( !transport ) { + done( -1, "No Transport" ); + } else { + jqXHR.readyState = 1; + + // Send global event + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); + } + + // If request was aborted inside ajaxSend, stop there + if ( completed ) { + return jqXHR; + } + + // Timeout + if ( s.async && s.timeout > 0 ) { + timeoutTimer = window.setTimeout( function() { + jqXHR.abort( "timeout" ); + }, s.timeout ); + } + + try { + completed = false; + transport.send( requestHeaders, done ); + } catch ( e ) { + + // Rethrow post-completion exceptions + if ( completed ) { + throw e; + } + + // Propagate others as results + done( -1, e ); + } + } + + // Callback for when everything is done + function done( status, nativeStatusText, responses, headers ) { + var isSuccess, success, error, response, modified, + statusText = nativeStatusText; + + // Ignore repeat invocations + if ( completed ) { + return; + } + + completed = true; + + // Clear timeout if it exists + if ( timeoutTimer ) { + window.clearTimeout( timeoutTimer ); + } + + // Dereference transport for early garbage collection + // (no matter how long the jqXHR object will be used) + transport = undefined; + + // Cache response headers + responseHeadersString = headers || ""; + + // Set readyState + jqXHR.readyState = status > 0 ? 4 : 0; + + // Determine if successful + isSuccess = status >= 200 && status < 300 || status === 304; + + // Get response data + if ( responses ) { + response = ajaxHandleResponses( s, jqXHR, responses ); + } + + // Convert no matter what (that way responseXXX fields are always set) + response = ajaxConvert( s, response, jqXHR, isSuccess ); + + // If successful, handle type chaining + if ( isSuccess ) { + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + modified = jqXHR.getResponseHeader( "Last-Modified" ); + if ( modified ) { + jQuery.lastModified[ cacheURL ] = modified; + } + modified = jqXHR.getResponseHeader( "etag" ); + if ( modified ) { + jQuery.etag[ cacheURL ] = modified; + } + } + + // if no content + if ( status === 204 || s.type === "HEAD" ) { + statusText = "nocontent"; + + // if not modified + } else if ( status === 304 ) { + statusText = "notmodified"; + + // If we have data, let's convert it + } else { + statusText = response.state; + success = response.data; + error = response.error; + isSuccess = !error; + } + } else { + + // Extract error from statusText and normalize for non-aborts + error = statusText; + if ( status || !statusText ) { + statusText = "error"; + if ( status < 0 ) { + status = 0; + } + } + } + + // Set data for the fake xhr object + jqXHR.status = status; + jqXHR.statusText = ( nativeStatusText || statusText ) + ""; + + // Success/Error + if ( isSuccess ) { + deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); + } else { + deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); + } + + // Status-dependent callbacks + jqXHR.statusCode( statusCode ); + statusCode = undefined; + + if ( fireGlobals ) { + globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", + [ jqXHR, s, isSuccess ? success : error ] ); + } + + // Complete + completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); + + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); + + // Handle the global AJAX counter + if ( !( --jQuery.active ) ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + } + + return jqXHR; + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + getScript: function( url, callback ) { + return jQuery.get( url, undefined, callback, "script" ); + } +} ); + +jQuery.each( [ "get", "post" ], function( i, method ) { + jQuery[ method ] = function( url, data, callback, type ) { + + // Shift arguments if data argument was omitted + if ( isFunction( data ) ) { + type = type || callback; + callback = data; + data = undefined; + } + + // The url can be an options object (which then must have .url) + return jQuery.ajax( jQuery.extend( { + url: url, + type: method, + dataType: type, + data: data, + success: callback + }, jQuery.isPlainObject( url ) && url ) ); + }; +} ); + + +jQuery._evalUrl = function( url ) { + return jQuery.ajax( { + url: url, + + // Make this explicit, since user can override this through ajaxSetup (#11264) + type: "GET", + dataType: "script", + cache: true, + async: false, + global: false, + "throws": true + } ); +}; + + +jQuery.fn.extend( { + wrapAll: function( html ) { + var wrap; + + if ( this[ 0 ] ) { + if ( isFunction( html ) ) { + html = html.call( this[ 0 ] ); + } + + // The elements to wrap the target around + wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); + + if ( this[ 0 ].parentNode ) { + wrap.insertBefore( this[ 0 ] ); + } + + wrap.map( function() { + var elem = this; + + while ( elem.firstElementChild ) { + elem = elem.firstElementChild; + } + + return elem; + } ).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( isFunction( html ) ) { + return this.each( function( i ) { + jQuery( this ).wrapInner( html.call( this, i ) ); + } ); + } + + return this.each( function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + } ); + }, + + wrap: function( html ) { + var htmlIsFunction = isFunction( html ); + + return this.each( function( i ) { + jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); + } ); + }, + + unwrap: function( selector ) { + this.parent( selector ).not( "body" ).each( function() { + jQuery( this ).replaceWith( this.childNodes ); + } ); + return this; + } +} ); + + +jQuery.expr.pseudos.hidden = function( elem ) { + return !jQuery.expr.pseudos.visible( elem ); +}; +jQuery.expr.pseudos.visible = function( elem ) { + return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); +}; + + + + +jQuery.ajaxSettings.xhr = function() { + try { + return new window.XMLHttpRequest(); + } catch ( e ) {} +}; + +var xhrSuccessStatus = { + + // File protocol always yields status code 0, assume 200 + 0: 200, + + // Support: IE <=9 only + // #1450: sometimes IE returns 1223 when it should be 204 + 1223: 204 + }, + xhrSupported = jQuery.ajaxSettings.xhr(); + +support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); +support.ajax = xhrSupported = !!xhrSupported; + +jQuery.ajaxTransport( function( options ) { + var callback, errorCallback; + + // Cross domain only allowed if supported through XMLHttpRequest + if ( support.cors || xhrSupported && !options.crossDomain ) { + return { + send: function( headers, complete ) { + var i, + xhr = options.xhr(); + + xhr.open( + options.type, + options.url, + options.async, + options.username, + options.password + ); + + // Apply custom fields if provided + if ( options.xhrFields ) { + for ( i in options.xhrFields ) { + xhr[ i ] = options.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( options.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( options.mimeType ); + } + + // X-Requested-With header + // For cross-domain requests, seeing as conditions for a preflight are + // akin to a jigsaw puzzle, we simply never set it to be sure. + // (it can always be set on a per-request basis or even using ajaxSetup) + // For same-domain requests, won't change header if already provided. + if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Set headers + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + + // Callback + callback = function( type ) { + return function() { + if ( callback ) { + callback = errorCallback = xhr.onload = + xhr.onerror = xhr.onabort = xhr.ontimeout = + xhr.onreadystatechange = null; + + if ( type === "abort" ) { + xhr.abort(); + } else if ( type === "error" ) { + + // Support: IE <=9 only + // On a manual native abort, IE9 throws + // errors on any property access that is not readyState + if ( typeof xhr.status !== "number" ) { + complete( 0, "error" ); + } else { + complete( + + // File: protocol always yields status 0; see #8605, #14207 + xhr.status, + xhr.statusText + ); + } + } else { + complete( + xhrSuccessStatus[ xhr.status ] || xhr.status, + xhr.statusText, + + // Support: IE <=9 only + // IE9 has no XHR2 but throws on binary (trac-11426) + // For XHR2 non-text, let the caller handle it (gh-2498) + ( xhr.responseType || "text" ) !== "text" || + typeof xhr.responseText !== "string" ? + { binary: xhr.response } : + { text: xhr.responseText }, + xhr.getAllResponseHeaders() + ); + } + } + }; + }; + + // Listen to events + xhr.onload = callback(); + errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" ); + + // Support: IE 9 only + // Use onreadystatechange to replace onabort + // to handle uncaught aborts + if ( xhr.onabort !== undefined ) { + xhr.onabort = errorCallback; + } else { + xhr.onreadystatechange = function() { + + // Check readyState before timeout as it changes + if ( xhr.readyState === 4 ) { + + // Allow onerror to be called first, + // but that will not handle a native abort + // Also, save errorCallback to a variable + // as xhr.onerror cannot be accessed + window.setTimeout( function() { + if ( callback ) { + errorCallback(); + } + } ); + } + }; + } + + // Create the abort callback + callback = callback( "abort" ); + + try { + + // Do send the request (this may raise an exception) + xhr.send( options.hasContent && options.data || null ); + } catch ( e ) { + + // #14683: Only rethrow if this hasn't been notified as an error yet + if ( callback ) { + throw e; + } + } + }, + + abort: function() { + if ( callback ) { + callback(); + } + } + }; + } +} ); + + + + +// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) +jQuery.ajaxPrefilter( function( s ) { + if ( s.crossDomain ) { + s.contents.script = false; + } +} ); + +// Install script dataType +jQuery.ajaxSetup( { + accepts: { + script: "text/javascript, application/javascript, " + + "application/ecmascript, application/x-ecmascript" + }, + contents: { + script: /\b(?:java|ecma)script\b/ + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } +} ); + +// Handle cache's special case and crossDomain +jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + if ( s.crossDomain ) { + s.type = "GET"; + } +} ); + +// Bind script tag hack transport +jQuery.ajaxTransport( "script", function( s ) { + + // This transport only deals with cross domain requests + if ( s.crossDomain ) { + var script, callback; + return { + send: function( _, complete ) { + script = jQuery( " + + + + + + + + + + + + + + + +
+ + + +
+ + + + + +
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
    + +
  • »
  • + +
  • Index
  • + + +
  • + + + +
  • + +
+ + +
+
+
+
+ + +

Index

+ +
+ +
+ + +
+ +
+
+ +
+ +
+

+ © Copyright 2021, The Cryptol Team. + +

+
+ + + + Built with Sphinx using a + + theme + + provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + \ No newline at end of file diff --git a/docs/RefMan/_build/html/objects.inv b/docs/RefMan/_build/html/objects.inv new file mode 100644 index 00000000..765ffffb --- /dev/null +++ b/docs/RefMan/_build/html/objects.inv @@ -0,0 +1,7 @@ +# Sphinx inventory version 2 +# Project: Cryptol +# Version: +# The remainder of this file is compressed using zlib. +xm +0DVՓHA؊ۤ$)4-X𶼙7^kK!򁝡jODv]셎> IfF-}X{E Y]hOTO͟'-Rev< +ڛnmVג_t  Sb \ No newline at end of file diff --git a/docs/RefMan/_build/html/search.html b/docs/RefMan/_build/html/search.html new file mode 100644 index 00000000..fdc903b9 --- /dev/null +++ b/docs/RefMan/_build/html/search.html @@ -0,0 +1,215 @@ + + + + + + + + + + Search — Cryptol 2.11.0 documentation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + + + +
+ +
+ + + + + + + + + + + + + + + + + + + +
+ +
    + +
  • »
  • + +
  • Search
  • + + +
  • + +
  • + +
+ + +
+
+
+
+ + + + +
+ +
+ +
+ +
+
+ +
+ +
+

+ © Copyright 2021, The Cryptol Team. + +

+
+ + + + Built with Sphinx using a + + theme + + provided by Read the Docs. + +
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docs/RefMan/_build/html/searchindex.js b/docs/RefMan/_build/html/searchindex.js new file mode 100644 index 00000000..999f2fcb --- /dev/null +++ b/docs/RefMan/_build/html/searchindex.js @@ -0,0 +1 @@ +Search.setIndex({docnames:["RefMan"],envversion:{"sphinx.domains.c":1,"sphinx.domains.changeset":1,"sphinx.domains.cpp":1,"sphinx.domains.javascript":1,"sphinx.domains.math":2,"sphinx.domains.python":1,"sphinx.domains.rst":1,"sphinx.domains.std":1,"sphinx.ext.todo":1,sphinx:55},filenames:["RefMan.rst"],objects:{},objnames:{},objtypes:{},terms:{"0b1010":0,"0b1010111":0,"0b11010":0,"0b11111110":0,"0b_0000_0010":0,"0o1234":0,"0o376":0,"0x01":0,"0x02":0,"0x03":0,"0x04":0,"0x1234":0,"0x30":0,"0x_ffff_ffea":0,"0xfe":0,"1p4":0,"2e3":0,"case":0,"float":0,"new":0,"public":0,"short":0,"static":0,"true":0,"while":0,For:0,Not:0,One:0,Such:0,The:0,There:0,These:0,Uses:0,Using:0,abbrevi:0,about:0,abov:0,abs:0,accommod:0,added:0,addit:0,after:0,all:0,allow:0,alphabet:0,also:0,ani:0,anoth:0,appear:0,appli:0,applic:0,arbitrarili:0,arithmet:[],arr:0,aspect:0,assert:[],associ:0,assumpt:0,automat:0,avoid:0,back:0,backtick:0,baddef:0,base:0,becaus:0,begin:0,behavior:0,belong:0,between:0,binari:0,bind:0,bitvector:0,bodi:0,both:0,bound:0,brace:0,branch:0,bring:0,can:0,cannot:0,ceil:0,charact:0,checker:0,chosen:0,clash:0,claus:0,close:0,closest:0,cmp:0,code:0,collect:0,collis:0,combin:0,comma:0,compar:0,comparison:[],complement:0,complex:0,compon:0,comprehens:0,comput:0,concaten:0,consid:0,consist:0,constraint:0,construct:0,contain:0,context:0,conveni:0,correspond:0,could:0,creat:0,cry:0,cryptolpath:0,curli:0,current:0,cut:0,data:0,decim:0,defin:0,definit:0,defint:0,degre:0,descript:0,design:0,determin:0,differ:0,digit:0,dimension:0,directli:0,directori:0,distance2:0,distinct:0,divis:[],document:0,doe:0,down:0,downward:0,e11:0,e12:0,e21:0,e22:0,each:0,easi:0,easier:0,effect:0,either:0,element:0,els:0,enclos:0,end:0,english:0,entri:0,enumer:0,equal:[],equat:0,equival:0,evalu:0,even:0,everi:0,everyth:0,exact:0,examin:0,exampl:0,except:0,exclus:0,exist:0,expon:0,exponenti:0,extend:0,extern:0,extract:0,fals:0,famili:0,few:0,file:0,fin:0,finit:0,first:0,fix:0,fliter:[],floor:0,follow:0,form:0,fraction:0,from:0,frominteg:0,front:0,gener:0,get:0,getfst:0,glu:0,good:0,group:0,had:0,handi:0,happen:0,has:0,hash:0,have:0,help:0,helper1:0,helper2:0,helper:0,here:0,hexadecim:0,highest:0,hold:0,howev:0,implement:0,implic:0,improv:0,includ:0,indent:0,index:0,indic:0,inf:0,infer:0,inffrom:0,inffromthen:0,infinit:0,infixl:0,infixr:0,inform:0,inhabit:0,instead:0,insuffici:0,integ:0,integr:[],intend:0,introduc:0,invalid:0,irrelev:0,isposit:0,its:0,itself:0,just:0,kind:0,known:0,label:0,lambda:0,languag:0,larg:0,last:0,left:0,length:0,less:0,let:0,letter:0,lexicograph:0,lg2:0,lift:0,like:0,line:0,literallessthan:[],locat:0,logarithm:0,logic:[],longer_nam:0,longernam:0,look:0,lowest:0,mai:0,make:0,mani:0,mark:0,match:0,max:0,maximum:0,mean:0,mechan:0,member:0,mention:0,might:0,min:0,minimum:0,mirror:0,modulu:0,more:0,moreov:0,most:0,multipl:0,must:0,name1:0,name2:0,need:0,negat:0,nest:0,newt:0,none:0,notat:0,note:0,number:0,obtain:0,octal:0,often:0,old:0,one:0,onli:0,open:0,option:0,order:0,ordinari:0,organ:0,other:0,otherwis:0,outsid:0,overload:[],overview:0,p11:0,p12:0,p21:0,p22:0,packag:0,pad:0,pair:0,paramet:0,paren:0,parenthes:0,pass:0,pattern:0,place:0,point:0,pointwis:0,polymorph:0,polynomi:0,posit:0,possibl:0,practic:0,pragma:0,pre:0,precis:0,previou:0,prime:0,primit:0,primtiv:0,principl:0,process:0,program:0,programm:0,project:0,properti:0,provid:0,purpos:0,quickli:0,quit:0,ration:0,readabl:0,recip:0,recurs:0,redesign:0,reduc:0,reject:0,rel:0,relat:0,remain:0,rep:[],repl:0,replac:0,repres:0,represent:0,result:0,right:0,ring:0,rotat:0,round:[],roundawai:0,roundtoeven:0,same:0,scope:0,search:0,second:0,section:0,see:0,selector:0,separ:0,seq:0,set:0,sha256:0,shape:0,shift:0,should:0,sign:[],signedcmp:0,similarli:0,simpl:0,singl:0,site:0,situat:0,size:0,some:0,sometim:0,sourc:0,special:0,specifi:0,split:0,start:0,step:0,stream:0,stride:0,structur:0,sub:0,subtract:0,suffici:0,sugar:0,suitabl:0,sum:0,support:0,symbol:0,tabl:0,tend:0,term:0,termin:0,text:0,than:0,thei:0,them:0,thi:0,those:0,though:0,three:0,through:0,thu:0,togeth:0,tointeg:0,top:0,transpar:0,treat:0,trunc:0,two:0,typaram:0,typecheck:0,typeclass:0,unari:0,underscor:0,understand:0,unfold:0,unlik:0,updateend:0,updatesend:0,use:0,used:0,useful:0,user:0,uses:0,using:0,usual:0,val:[],valid:0,variabl:0,varieti:0,variou:0,via:0,wai:0,want:0,weakest:0,when:0,where:0,wherea:0,which:0,whole:0,why:0,width:0,wise:0,without:0,word:0,work:0,would:0,write:0,written:0,xpo:0,you:0,ypo:0,zero:[]},titles:["Cryptol Reference Manual"],titleterms:{"function":0,"import":0,access:0,annot:0,argument:0,arithmet:0,basic:0,bit:0,block:0,built:0,call:0,comment:0,comparison:0,condit:0,cryptol:0,declar:0,demot:0,divis:0,equal:0,explicit:0,express:0,field:0,hide:0,hierarch:0,identifi:0,infix:0,instanti:0,integr:0,keyword:0,layout:0,level:0,list:0,liter:0,local:0,logic:0,manual:0,modul:0,name:0,newtyp:0,numer:0,oper:0,overload:0,parameter:0,preced:0,prefix:0,privat:0,qualifi:0,record:0,refer:0,round:0,sequenc:0,sign:0,signatur:0,synonym:0,syntax:0,todo:0,tupl:0,type:0,updat:0,valu:0,zero:0}}) \ No newline at end of file diff --git a/docs/RefMan/conf.py b/docs/RefMan/conf.py index b22b8a3e..7df55bf8 100644 --- a/docs/RefMan/conf.py +++ b/docs/RefMan/conf.py @@ -80,9 +80,11 @@ pygments_style = None # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -html_theme = 'classic' -# html_theme = 'sphinx_rtd_theme' +# html_theme = 'classic' +html_theme = 'sphinx_rtd_theme' # see: https://github.com/readthedocs/sphinx_rtd_theme +# the theme may be installed using: +# pip install sphinx-rtd-theme # Theme options are theme-specific and customize the look and feel of a theme diff --git a/docs/Semantics.pdf b/docs/Semantics.pdf index b898fad0..c27f9f65 100644 Binary files a/docs/Semantics.pdf and b/docs/Semantics.pdf differ diff --git a/docs/Syntax.md b/docs/Syntax.md index d1276015..2b1a7085 100644 --- a/docs/Syntax.md +++ b/docs/Syntax.md @@ -90,12 +90,14 @@ infix primitive parameter constraint +by +down ---> else include property let infixl parameter extern module then import infixr constraint - if newtype type as infix - private pragma where hiding primitive + if newtype type as infix by + private pragma where hiding primitive down The following table contains Cryptol's operators and their @@ -435,19 +437,25 @@ _word_. We may abbreviate the type `[n] Bit` as `[n]`. An infinite sequence with elements of type `a` has type `[inf] a`, and `[inf]` is an infinite stream of bits. - [e1,e2,e3] // A sequence with three elements + [e1,e2,e3] // A sequence with three elements - [t1 .. t3 ] // Sequence enumerations - [t1, t2 .. t3 ] // Step by t2 - t1 - [e1 ... ] // Infinite sequence starting at e1 - [e1, e2 ... ] // Infinite sequence stepping by e2-e1 + [t1 .. t2] // Enumeration + [t1 .. t2 down by n] // Enumeration (downward stride, ex. bound) + [t1, t2 .. t3] // Enumeration (step by t2 - t1) - [ e | p11 <- e11, p12 <- e12 // Sequence comprehensions + [e1 ...] // Infinite sequence starting at e1 + [e1, e2 ...] // Infinite sequence stepping by e2-e1 + + [ e | p11 <- e11, p12 <- e12 // Sequence comprehensions | p21 <- e21, p22 <- e22 ] - x = generate (\i -> e) // Sequence from generating function - x @ i = e // Sequence with index binding - arr @ i @ j = e // Two-dimensional sequence + x = generate (\i -> e) // Sequence from generating function + x @ i = e // Sequence with index binding + arr @ i @ j = e // Two-dimensional sequence Note: the bounds in finite sequences (those with `..`) are type @@ -508,11 +516,19 @@ following notation: `t -Here `t` should be a type expression with numeric kind. The resulting -expression is a finite word, which is sufficiently large to accommodate -the value of the type: +Here `t` should be a finite type expression with numeric kind. The resulting +expression will be of a numeric base type, which is sufficiently large +to accommodate the value of the type: - `t : {n} (fin n, n >= width t) => [n] + `t : {a} (Literal t a) => a + +This backtick notation is syntax sugar for an application of the +`number` primtive, so the above may be written as: + + number`{t} : {a} (Literal t a) => a + +If a type cannot be inferred from context, a suitable type will be +automatically chosen if possible, usually `Integer`. Explicit Type Annotations ========================= diff --git a/docs/Syntax.pdf b/docs/Syntax.pdf index ffe36508..6192ce4e 100644 Binary files a/docs/Syntax.pdf and b/docs/Syntax.pdf differ diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 00000000..e3a72b1b --- /dev/null +++ b/docs/index.html @@ -0,0 +1,10 @@ + + +Crytpol Documentation + + + +Crytpol Reference Manual + + diff --git a/lib/Array.cry b/lib/Array.cry index e178d7ff..d9aab610 100644 --- a/lib/Array.cry +++ b/lib/Array.cry @@ -11,3 +11,47 @@ primitive arrayConstant : {a, b} b -> (Array a b) primitive arrayLookup : {a, b} (Array a b) -> a -> b primitive arrayUpdate : {a, b} (Array a b) -> a -> b -> (Array a b) +/** + * Copy elements from the source array to the destination array. + * + * 'arrayCopy dest_arr dest_idx src_arr src_idx len' copies the + * elements from 'src_arr' at indices '[src_idx ..< (src_idx + len)]' into + * 'dest_arr' at indices '[dest_idx ..< (dest_idx + len)]'. + * + * The result is undefined if either 'dest_idx + len' or 'src_idx + len' + * wraps around. + */ +primitive arrayCopy : {n, a} (Array [n] a) -> [n] -> (Array [n] a) -> [n] -> [n] -> (Array [n] a) +/** + * Set elements of the given array. + * + * 'arraySet' arr idx val len' sets the elements of 'arr' at indices + * '[idx ..< (idx + len)]' to 'val'. + * + * The result is undefined if 'idx + len' wraps around. + */ +primitive arraySet : {n, a} (Array [n] a) -> [n] -> a -> [n] -> (Array [n] a) +/** + * Check whether the lhs array and rhs array are equal at a range of + * indices. + * + * 'arrayRangeEq sym lhs_arr lhs_idx rhs_arr rhs_idx len' checks whether + * the elements of 'lhs_arr' at indices '[lhs_idx ..< (lhs_idx + len)]' and + * the elements of 'rhs_arr' at indices '[rhs_idx ..< (rhs_idx + len)]' are + * equal. + * + * The result is undefined if either 'lhs_idx + len' or 'rhs_idx + len' + * wraps around. + */ +primitive arrayRangeEqual : {n, a} (Array [n] a) -> [n] -> (Array [n] a) -> [n] -> [n] -> Bool + +arrayRangeLookup : {a, b, n} (Integral a, fin n, LiteralLessThan n a) => (Array a b) -> a -> [n]b +arrayRangeLookup arr idx = res + where + res @ i = arrayLookup arr (idx + i) + +arrayRangeUpdate : {a, b, n} (Integral a, fin n, LiteralLessThan n a) => (Array a b) -> a -> [n]b -> (Array a b) +arrayRangeUpdate arr idx vals = arrs ! 0 + where + arrs = [arr] # [ arrayUpdate acc (idx + i) val | acc <- arrs | i <- [0 ..< n] | val <- vals ] + diff --git a/lib/Cryptol.cry b/lib/Cryptol.cry index a2b3c27c..ca99aad7 100644 --- a/lib/Cryptol.cry +++ b/lib/Cryptol.cry @@ -32,7 +32,7 @@ primitive type Integer : * /** * 'Z n' is the type of integers, modulo 'n'. * - * The values of 'Z n' may be thought of as equivalance + * The values of 'Z n' may be thought of as equivalence * classes of integers according to the equivalence * 'x ~ y' iff 'n' divides 'x - y'. 'Z n' naturally * forms a ring, but does not support integral division @@ -41,9 +41,9 @@ primitive type Integer : * * However, you may use the 'fromZ' operation * to project values in 'Z n' into the integers if such operations * are required. This will compute the reduced representative - * of the equivalance class. In other words, 'fromZ' computes + * of the equivalence class. In other words, 'fromZ' computes * the (unique) integer value 'i' where '0 <= i < n' and - * 'i' is in the given equivalance class. + * 'i' is in the given equivalence class. * * If the modulus 'n' is prime, 'Z n' also * supports computing inverses and forms a field. @@ -131,13 +131,13 @@ primitive type max : # -> # -> # /** Divide numeric types, rounding up. */ primitive type { m : #, n : # } - (fin m, fin n, n >= 1) => + (fin n, n >= 1) => m /^ n : # /** How much we need to add to make a proper multiple of the second argument. */ primitive type { m : #, n : # } - (fin m, fin n, n >= 1) => + (fin n, n >= 1) => m %^ n : # /** The length of an enumeration. */ @@ -195,26 +195,76 @@ length _ = `n /** * A finite sequence counting up from 'first' to 'last'. * - * '[a..b]' is syntactic sugar for 'fromTo`{first=a,last=b}'. + * '[x .. y]' is syntactic sugar for 'fromTo`{first=x,last=y}'. */ -primitive fromTo : {first, last, a} (fin last, last >= first, - Literal first a, Literal last a) => - [1 + (last - first)]a +primitive fromTo : {first, last, a} + (fin last, last >= first, Literal last a) => + [1 + (last - first)]a /** * A possibly infinite sequence counting up from 'first' up to (but not including) 'bound'. * - * Note that if 'first' = 'bound' then the sequence will be empty. + * '[ x ..< y ]' is syntactic sugar for 'fromToLessThan`{first=x,bound=y}'. + * + * Note that if 'first' = 'bound' then the sequence will be empty. If 'bound = inf' + * then the sequence will be infinite, and will eventually wrap around for bounded types. */ primitive fromToLessThan : - {first, bound, a} (fin first, bound >= first, LiteralLessThan bound a) => [bound - first]a + {first, bound, a} (fin first, bound >= first, LiteralLessThan bound a) => + [bound - first]a +/** + * A finite sequence counting up from 'first' to 'last' by 'stride'. + * Note that 'last' will only be an element of the enumeration if + * 'stride' divides 'last - first' evenly. + * + * '[x .. y by n]' is syntactic sugar for 'fromToBy`{first=x,last=y,stride=n}'. + */ +primitive fromToBy : {first, last, stride, a} + (fin last, fin stride, stride >= 1, last >= first, Literal last a) => + [1 + (last - first)/stride]a + +/** + * A finite sequence counting from 'first' up to (but not including) 'bound' + * by 'stride'. Note that if 'first = bound' then the sequence will + * be empty. If 'bound = inf' then the sequence will be infinite, and will + * eventually wrap around for bounded types. + * + * '[x ..< y by n]' is syntactic sugar for 'fromToByLessThan`{first=x,bound=y,stride=n}'. + */ +primitive fromToByLessThan : {first, bound, stride, a} + (fin first, fin stride, stride >= 1, bound >= first, LiteralLessThan bound a) => + [(bound - first)/^stride]a + +/** + * A finite sequence counting from 'first' down to 'last' by 'stride'. + * Note that 'last' will only be an element of the enumeration if + * 'stride' divides 'first - last' evenly. + * + * '[x .. y down by n]' is syntactic sugar for 'fromToDownBy`{first=x,last=y,stride=n}'. + */ +primitive fromToDownBy : {first, last, stride, a} + (fin first, fin stride, stride >= 1, first >= last, Literal first a) => + [1 + (first - last)/stride]a + +/** + * A finite sequence counting from 'first' down to (but not including) + * 'bound' by 'stride'. + * + * '[x ..> y down by n]' is syntactic sugar for + * 'fromToDownByGreaterThan`{first=x,bound=y,stride=n}'. + * + * Note that if 'first = bound' the sequence will be empty. + */ +primitive fromToDownByGreaterThan : {first, bound, stride, a} + (fin first, fin stride, stride >= 1, first >= bound, Literal first a) => + [(first - bound)/^stride]a /** * A finite arithmetic sequence starting with 'first' and 'next', * stopping when the values reach or would skip over 'last'. * - * '[a,b..c]' is syntactic sugar for 'fromThenTo`{first=a,next=b,last=c}'. + * '[x,y..z]' is syntactic sugar for 'fromThenTo`{first=x,next=y,last=z}'. */ primitive fromThenTo : {first, next, last, a, len} ( fin first, fin next, fin last @@ -224,12 +274,12 @@ primitive fromThenTo : {first, next, last, a, len} // Fractional Literals --------------------- -/** 'FLiteral m n r a' asserts that the type `a' contains the -fraction `m/n`. The flag `r` indicates if we should round (`r >= 1`) +/** 'FLiteral m n r a' asserts that the type 'a' contains the +fraction 'm/n'. The flag 'r' indicates if we should round ('r >= 1') or report an error if the number can't be represented exactly. */ primitive type FLiteral : # -> # -> # -> * -> Prop -/** A fractional literal corresponding to `m/n` */ +/** A fractional literal corresponding to 'm/n' */ primitive fraction : { m, n, r, a } FLiteral m n r a => a @@ -387,7 +437,7 @@ primitive infFromThen : {a} (Integral a) => a -> a -> [inf]a /** * Value types that correspond to a field; that is, - * a ring also posessing multiplicative inverses for + * a ring also possessing multiplicative inverses for * non-zero elements. * * Floating-point values are only approximately a field, @@ -684,6 +734,11 @@ primitive (>>$) : {n, ix} (fin n, n >= 1, Integral ix) => [n] -> ix -> [n] */ primitive lg2 : {n} (fin n) => [n] -> [n] +/** + * Convert a signed 2's complement bitvector to an integer. + */ +primitive toSignedInteger : {n} (fin n, n >= 1) => [n] -> Integer + // Rational specific operations ---------------------------------------------- @@ -860,14 +915,9 @@ primitive updateEnd : {n, a, ix} (fin n, Integral ix) => [n]a -> ix -> a -> [n]a * given update pairs. */ updates : {n, k, ix, a} (Integral ix, fin k) => [n]a -> [k]ix -> [k]a -> [n]a -updates xs0 idxs vals = xss!0 - where - xss = [ xs0 ] # - [ update xs i b - | xs <- xss - | i <- idxs - | b <- vals - ] +updates xs0 idxs vals = foldl upd xs0 (zip idxs vals) + where + upd xs (i,b) = update xs i b /** * Perform a series of updates to a sequence. The first argument is @@ -877,14 +927,9 @@ updates xs0 idxs vals = xss!0 * given update pairs. */ updatesEnd : {n, k, ix, a} (fin n, Integral ix, fin k) => [n]a -> [k]ix -> [k]a -> [n]a -updatesEnd xs0 idxs vals = xss!0 - where - xss = [ xs0 ] # - [ updateEnd xs i b - | xs <- xss - | i <- idxs - | b <- vals - ] +updatesEnd xs0 idxs vals = foldl upd xs0 (zip idxs vals) + where + upd xs (i,b) = updateEnd xs i b /** * Produce a sequence using a generating function. @@ -909,18 +954,16 @@ sort = sortBy (<=) * pair of elements that are equivalent according to the order relation. */ sortBy : {a, n} (fin n) => (a -> a -> Bit) -> [n]a -> [n]a -sortBy le vs = - if `n == (0 : Integer) then vs - else drop`{1 - min 1 n} (insertBy (vs@0) (sortBy le (drop`{min 1 n} vs))) +sortBy le ((xs : [n/2]a) # (ys : [n/^2]a)) = take zs.0 where - insertBy : {k} (fin k) => a -> [k]a -> [k+1]a - insertBy x0 ys = xys.0 # [last xs] - where - xs : [k+1]a - xs = [x0] # xys.1 - xys : [k](a, a) - xys = [ if le x y then (x, y) else (y, x) | x <- xs | y <- ys ] - + xs' = if `(n/2) == 1 then xs else sortBy le xs + ys' = if `(n/^2) == 1 then ys else sortBy le ys + zs = [ if i == `(n/2) then (ys'@j, i , j+1) + | j == `(n/^2) then (xs'@i, i+1, j ) + | le (xs'@i) (ys'@j) then (xs'@i, i+1, j ) + else (ys'@j, i , j+1) + | (_, i, j) <- [ (undefined, 0, 0) ] # zs + ] // GF_2^n polynomial computations ------------------------------------------- @@ -943,7 +986,7 @@ primitive pmod : {u, v} (fin u, fin v) => [u] -> [1 + v] -> [v] /** * Parallel map. The given function is applied to each element in the - * given finite seqeuence, and the results are computed in parallel. + * given finite sequence, and the results are computed in parallel. * The values in the resulting sequence are reduced to normal form, * as is done with the deepseq operation. * @@ -1104,27 +1147,22 @@ foldr' f acc xs = foldl' g acc (reverse xs) sum : {n, a} (fin n, Eq a, Ring a) => [n]a -> a sum xs = foldl' (+) (fromInteger 0) xs - /** * Compute the product of the values in the sequence. */ product : {n, a} (fin n, Eq a, Ring a) => [n]a -> a product xs = foldl' (*) (fromInteger 1) xs - /** * Scan left is like a foldl that also emits the intermediate values. */ -scanl : {n, b, a} (b -> a -> b) -> b -> [n]a -> [n+1]b -scanl f acc xs = ys - where ys = [acc] # [f a x | a <- ys | x <- xs] +primitive scanl : {n, a, b} (a -> b -> a) -> a -> [n]b -> [1+n]a /** * Scan right is like a foldr that also emits the intermediate values. */ -scanr : {n, a, b} (fin n) => (a -> b -> b) -> b -> [n]a -> [n+1]b -scanr f acc xs = reverse ys - where ys = [acc] # [f x a | a <- ys | x <- reverse xs] +scanr : {n, a, b} (fin n) => (a -> b -> b) -> b -> [n]a -> [1+n]b +scanr f acc xs = reverse (scanl (\a b -> f b a) acc (reverse xs)) /** * Repeat a value. @@ -1167,5 +1205,4 @@ curry f = \a b -> f (a, b) * list of successive function applications. */ iterate : {a} (a -> a) -> a -> [inf]a -iterate f x = xs - where xs = [x] # [ f v | v <- xs ] +iterate f z = scanl (\x _ -> f x) z (zero:[inf]()) diff --git a/lib/Cryptol/Reference.cry b/lib/Cryptol/Reference.cry index ece19a7a..46972b86 100644 --- a/lib/Cryptol/Reference.cry +++ b/lib/Cryptol/Reference.cry @@ -44,3 +44,33 @@ pmod x y = if y == 0 then 0/0 else last zs powers = [reduce 1] # [ reduce (p << 1) | p <- powers ] zs = [0] # [ z ^ (if xi then tail p else 0) | xi <- reverse x | p <- powers | z <- zs ] + +/** + * Functional left fold. + * + * foldl (+) 0 [1,2,3] = ((0 + 1) + 2) + 3 + * + * Reference implementation. + */ +foldl : {n, a, b} (fin n) => (a -> b -> a) -> a -> [n]b -> a +foldl f z bs = last (scanl f z bs) + +/** + * Scan left is like a foldl that also emits the intermediate values. + * + * Reference implementation. + */ +scanl : {n, a, b} (a -> b -> a) -> a -> [n]b -> [1+n]a +scanl f z bs = as + where + as = [z] # [ f a b | a <- as | b <- bs ] + +/** + * Map a function iteratively over a seed value, producing an infinite + * list of successive function applications. + * + * Reference implementation. + */ +iterate : {a} (a -> a) -> a -> [inf]a +iterate f z = xs + where xs = [z] # [ f x | x <- xs ] diff --git a/lib/CryptolTC.z3 b/lib/CryptolTC.z3 index 7d873694..f48923f1 100644 --- a/lib/CryptolTC.z3 +++ b/lib/CryptolTC.z3 @@ -293,15 +293,19 @@ ) (define-fun cryCeilDiv ((x InfNat) (y InfNat)) InfNat - (ite (or (isErr x) (isErr y) (not (isFin x)) (not (isFin y))) cryErr - (ite (= (value y) 0) cryErr (cryNat (- (div (- (value x)) (value y))))) - ) + (ite (or (isErr x) (isErr y) (not (isFin y))) cryErr + (ite (= (value y) 0) cryErr + (ite (not (isFin x)) cryInf + (cryNat (- (div (- (value x)) (value y)))) + ))) ) (define-fun cryCeilMod ((x InfNat) (y InfNat)) InfNat - (ite (or (isErr x) (isErr y) (not (isFin x)) (not (isFin y))) cryErr - (ite (= (value y) 0) cryErr (cryNat (mod (- (value x)) (value y)))) - ) + (ite (or (isErr x) (isErr y) (not (isFin y))) cryErr + (ite (= (value y) 0) cryErr + (ite (not (isFin x)) (cryNat 0) + (cryNat (mod (- (value x)) (value y))) + ))) ) (define-fun cryLenFromThenTo ((x InfNat) (y InfNat) (z InfNat)) InfNat diff --git a/src/Cryptol/Backend.hs b/src/Cryptol/Backend.hs index 5526b119..d132e5b6 100644 --- a/src/Cryptol/Backend.hs +++ b/src/Cryptol/Backend.hs @@ -614,6 +614,12 @@ class MonadIO (SEval sym) => Backend sym where SWord sym -> SEval sym (SInteger sym) + -- | Construct a signed integer value from the given packed word. + wordToSignedInt :: + sym -> + SWord sym -> + SEval sym (SInteger sym) + -- ==== Integer operations ==== -- | Addition of unbounded integers. diff --git a/src/Cryptol/Backend/Concrete.hs b/src/Cryptol/Backend/Concrete.hs index ab802761..466e51d6 100644 --- a/src/Cryptol/Backend/Concrete.hs +++ b/src/Cryptol/Backend/Concrete.hs @@ -116,7 +116,7 @@ ppBV opts (BV width i) prefix = case base of 2 -> text "0b" <.> padding 1 8 -> text "0o" <.> padding 3 - 10 -> empty + 10 -> mempty 16 -> text "0x" <.> padding 4 _ -> text "0" <.> char '<' <.> int base <.> char '>' @@ -187,6 +187,7 @@ instance Backend Concrete where integerAsLit _ = Just wordToInt _ (BV _ x) = pure x + wordToSignedInt _ (BV w x) = pure $! signedValue w x wordFromInt _ w x = pure $! mkBv w x packWord _ bits = pure $! BV (toInteger w) a diff --git a/src/Cryptol/Backend/SBV.hs b/src/Cryptol/Backend/SBV.hs index 87cc7b0a..90341b14 100644 --- a/src/Cryptol/Backend/SBV.hs +++ b/src/Cryptol/Backend/SBV.hs @@ -295,6 +295,7 @@ instance Backend SBV where wordLg2 _ a = sLg2 a wordToInt _ x = pure $! svToInteger x + wordToSignedInt _ x = pure $! svToInteger (svSign x) wordFromInt _ w i = pure $! svFromInteger w i intEq _ a b = pure $! svEqual a b diff --git a/src/Cryptol/Backend/What4.hs b/src/Cryptol/Backend/What4.hs index 3ff9c906..699fe1ab 100644 --- a/src/Cryptol/Backend/What4.hs +++ b/src/Cryptol/Backend/What4.hs @@ -364,6 +364,7 @@ instance W4.IsSymExprBuilder sym => Backend (What4 sym) where liftIO (SW.bvSRem (w4 sym) x y) wordToInt sym x = liftIO (SW.bvToInteger (w4 sym) x) + wordToSignedInt sym x = liftIO (SW.sbvToInteger (w4 sym) x) wordFromInt sym width i = liftIO (SW.integerToBV (w4 sym) i width) intPlus sym x y = liftIO $ W4.intAdd (w4 sym) x y diff --git a/src/Cryptol/Eval.hs b/src/Cryptol/Eval.hs index 937f097f..0c74be87 100644 --- a/src/Cryptol/Eval.hs +++ b/src/Cryptol/Eval.hs @@ -428,9 +428,11 @@ evalDecl sym renv env d = SEval Concrete (GenValue Concrete) #-} --- | Apply the the given "selector" form to the given value. This function pushes --- tuple and record selections pointwise down into other value constructs --- (e.g., streams and functions). +-- | Apply the the given "selector" form to the given value. Note that +-- selectors are expected to apply only to values of the right type, +-- e.g. tuple selectors expect only tuple values. The lifting of +-- tuple an record selectors over functions and sequences has already +-- been resolved earlier in the typechecker. evalSel :: Backend sym => sym -> diff --git a/src/Cryptol/Eval/Concrete.hs b/src/Cryptol/Eval/Concrete.hs index 6ef40641..d7fb80e4 100644 --- a/src/Cryptol/Eval/Concrete.hs +++ b/src/Cryptol/Eval/Concrete.hs @@ -126,7 +126,7 @@ toExpr prims t0 v0 = findOne (go t0 v0) panic "Cryptol.Eval.Concrete.toExpr" ["type mismatch:" , pretty (tValTy ty) - , render doc + , show doc ] floatToExpr :: PrimMap -> AST.Type -> AST.Type -> FP.BigFloat -> AST.Expr diff --git a/src/Cryptol/Eval/Generic.hs b/src/Cryptol/Eval/Generic.hs index 834a5c9a..cecf701e 100644 --- a/src/Cryptol/Eval/Generic.hs +++ b/src/Cryptol/Eval/Generic.hs @@ -35,7 +35,7 @@ import Data.Map(Map) import Data.Ratio ((%)) import Cryptol.TypeCheck.AST -import Cryptol.TypeCheck.Solver.InfNat (Nat'(..),nMul) +import Cryptol.TypeCheck.Solver.InfNat (Nat'(..),nMul,nAdd) import Cryptol.Backend import Cryptol.Backend.Concrete (Concrete(..)) import Cryptol.Backend.Monad( Eval, evalPanic, EvalError(..), Unsupported(..) ) @@ -716,6 +716,13 @@ smodV sym = PWordFun \y -> PPrim (VWord w . wordVal <$> wordSignedMod sym x y) +{-# SPECIALIZE toSignedIntegerV :: Concrete -> Prim Concrete #-} +toSignedIntegerV :: Backend sym => sym -> Prim sym +toSignedIntegerV sym = + PFinPoly \_w -> + PWordFun \x -> + PPrim (VInteger <$> wordToSignedInt sym x) + -- Cmp ------------------------------------------------------------------------- {-# SPECIALIZE cmpValue :: @@ -1437,7 +1444,6 @@ updatePrim sym updateWord updateSeq = (do vs <- fromSeq "updatePrim" =<< xs; updateSeq len eltTy vs idx' val) {-# INLINE fromToV #-} - -- @[ 0 .. 10 ]@ fromToV :: Backend sym => sym -> Prim sym fromToV sym = @@ -1452,23 +1458,7 @@ fromToV sym = in VSeq len $ indexSeqMap $ \i -> f (first' + i) _ -> evalPanic "fromToV" ["invalid arguments"] -{-# INLINE fromToLessThanV #-} - --- @[ 0 .. <10 ]@ -fromToLessThanV :: Backend sym => sym -> Prim sym -fromToLessThanV sym = - PFinPoly \first -> - PNumPoly \bound -> - PTyPoly \ty -> - PVal - let !f = mkLit sym ty - ss = indexSeqMap $ \i -> f (first + i) - in case bound of - Inf -> VStream ss - Nat bound' -> VSeq (bound' - first) ss - {-# INLINE fromThenToV #-} - -- @[ 0, 1 .. 10 ]@ fromThenToV :: Backend sym => sym -> Prim sym fromThenToV sym = @@ -1485,6 +1475,75 @@ fromThenToV sym = in VSeq len' $ indexSeqMap $ \i -> f (first' + i*diff) _ -> evalPanic "fromThenToV" ["invalid arguments"] +{-# INLINE fromToLessThanV #-} +-- @[ 0 .. <10 ]@ +fromToLessThanV :: Backend sym => sym -> Prim sym +fromToLessThanV sym = + PFinPoly \first -> + PNumPoly \bound -> + PTyPoly \ty -> + PVal + let !f = mkLit sym ty + ss = indexSeqMap $ \i -> f (first + i) + in case bound of + Inf -> VStream ss + Nat bound' -> VSeq (bound' - first) ss + +{-# INLINE fromToByV #-} +-- @[ 0 .. 10 by 2 ]@ +fromToByV :: Backend sym => sym -> Prim sym +fromToByV sym = + PFinPoly \first -> + PFinPoly \lst -> + PFinPoly \stride -> + PTyPoly \ty -> + PVal + let !f = mkLit sym ty + ss = indexSeqMap $ \i -> f (first + i*stride) + in VSeq (1 + ((lst - first) `div` stride)) ss + +{-# INLINE fromToByLessThanV #-} +-- @[ 0 .. <10 by 2 ]@ +fromToByLessThanV :: Backend sym => sym -> Prim sym +fromToByLessThanV sym = + PFinPoly \first -> + PNumPoly \bound -> + PFinPoly \stride -> + PTyPoly \ty -> + PVal + let !f = mkLit sym ty + ss = indexSeqMap $ \i -> f (first + i*stride) + in case bound of + Inf -> VStream ss + Nat bound' -> VSeq ((bound' - first + stride - 1) `div` stride) ss + + +{-# INLINE fromToDownByV #-} +-- @[ 10 .. 0 down by 2 ]@ +fromToDownByV :: Backend sym => sym -> Prim sym +fromToDownByV sym = + PFinPoly \first -> + PFinPoly \lst -> + PFinPoly \stride -> + PTyPoly \ty -> + PVal + let !f = mkLit sym ty + ss = indexSeqMap $ \i -> f (first - i*stride) + in VSeq (1 + ((first - lst) `div` stride)) ss + +{-# INLINE fromToDownByGreaterThanV #-} +-- @[ 10 .. >0 down by 2 ]@ +fromToDownByGreaterThanV :: Backend sym => sym -> Prim sym +fromToDownByGreaterThanV sym = + PFinPoly \first -> + PFinPoly \bound -> + PFinPoly \stride -> + PTyPoly \ty -> + PVal + let !f = mkLit sym ty + ss = indexSeqMap $ \i -> f (first - i*stride) + in VSeq ((first - bound + stride - 1) `div` stride) ss + {-# INLINE infFromV #-} infFromV :: Backend sym => sym -> Prim sym infFromV sym = @@ -1755,6 +1814,40 @@ foldl'V sym = go1 f a' bs +-- scanl : {n, a, b} (a -> b -> a) -> a -> [n]b -> [1+n]a +scanlV :: forall sym. Backend sym => sym -> Prim sym +scanlV sym = + PNumPoly \n -> + PTyPoly \a -> + PTyPoly \_b -> + PFun \f -> + PFun \z -> + PStrict \v -> + PPrim + do sm <- case v of + VSeq _ m -> scan n f z m + VWord _ wv -> scan n f z (VBit <$> asBitsMap sym wv) + VStream m -> scan n f z m + _ -> panic "Cryptol.Eval.Generic.scanlV" ["Expected sequence"] + mkSeq sym (nAdd (Nat 1) n) a sm + + where + scan :: Nat' -> + SEval sym (GenValue sym) -> + SEval sym (GenValue sym) -> + (SeqMap sym (GenValue sym)) -> + SEval sym (SeqMap sym (GenValue sym)) + scan n f z m = + do (result, fill) <- sDeclareHole sym "scanl" + fill $ memoMap sym (nAdd (Nat 1) n) $ indexSeqMap $ \i -> + if i == 0 then z + else + do r <- result + f' <- fromVFun sym <$> f + f'' <- fromVFun sym <$> f' (lookupSeqMap r (i-1)) + f'' (lookupSeqMap m (i-1)) + result + -- Random Values --------------------------------------------------------------- {-# SPECIALIZE randomV :: @@ -1979,6 +2072,9 @@ genericPrimTable sym getEOpts = unary (roundToEvenV sym)) -- Bitvector specific operations + , ("toSignedInteger" + , {-# SCC "Prelude::toSignedInteger" #-} + toSignedIntegerV sym) , ("/$" , {-# SCC "Prelude::(/$)" #-} sdivV sym) , ("%$" , {-# SCC "Prelude::(%$)" #-} @@ -2015,6 +2111,20 @@ genericPrimTable sym getEOpts = , {-# SCC "Prelude::fromToLessThan" #-} fromToLessThanV sym) + , ("fromToBy" , {-# SCC "Prelude::fromToBy" #-} + fromToByV sym) + + , ("fromToByLessThan", + {-# SCC "Prelude::fromToByLessThan" #-} + fromToByLessThanV sym) + + , ("fromToDownBy", {-# SCC "Prelude::fromToDownBy" #-} + fromToDownByV sym) + + , ("fromToDownByGreaterThan" + , {-# SCC "Prelude::fromToDownByGreaterThan" #-} + fromToDownByGreaterThanV sym) + -- Sequence manipulations , ("#" , {-# SCC "Prelude::(#)" #-} PFinPoly \front -> @@ -2124,6 +2234,9 @@ genericPrimTable sym getEOpts = , ("foldl'" , {-# SCC "Prelude::foldl'" #-} foldl'V sym) + , ("scanl" , {-# SCC "Prelude::scanl" #-} + scanlV sym) + , ("deepseq" , {-# SCC "Prelude::deepseq" #-} PTyPoly \_a -> PTyPoly \_b -> diff --git a/src/Cryptol/Eval/Reference.lhs b/src/Cryptol/Eval/Reference.lhs index 3d98be15..d5d91b77 100644 --- a/src/Cryptol/Eval/Reference.lhs +++ b/src/Cryptol/Eval/Reference.lhs @@ -543,7 +543,7 @@ To evaluate a primitive, we look up its implementation by name in a table. > evalPrim :: Name -> Value > evalPrim n > | Just i <- asPrim n, Just v <- Map.lookup i primTable = v -> | otherwise = evalPanic "evalPrim" ["Unimplemented primitive", show n] +> | otherwise = evalPanic "evalPrim" ["Unimplemented primitive", show (pp n)] Cryptol primitives fall into several groups, mostly delineated by corresponding type classes: @@ -568,7 +568,9 @@ by corresponding type classes: * Indexing: `@`, `@@`, `!`, `!!`, `update`, `updateEnd` -* Enumerations: `fromTo`, `fromThenTo`, `fromToLessThan`, `infFrom`, `infFromThen` +* Enumerations: `fromTo`, `fromThenTo`, `fromToLessThan`, `fromToBy`, + `fromToByLessThan`, `fromToDownBy`, `fromToDownByGreaterThan`, + `infFrom`, `infFromThen` * Polynomials: `pmult`, `pdiv`, `pmod` @@ -784,29 +786,71 @@ by corresponding type classes: > -- Enumerations > , "fromTo" ~> vFinPoly $ \first -> pure $ > vFinPoly $ \lst -> pure $ -> VPoly $ \ty -> -> let f i = literal i ty -> in pure (VList (Nat (1 + lst - first)) (map f [first .. lst])) +> VPoly $ \ty -> pure $ +> let f i = literal i ty in +> VList (Nat (1 + lst - first)) (map f [first .. lst]) +> +> , "fromToLessThan" ~> +> vFinPoly $ \first -> pure $ +> VNumPoly $ \bound -> pure $ +> VPoly $ \ty -> pure $ +> let f i = literal i ty in +> case bound of +> Inf -> VList Inf (map f [first ..]) +> Nat bound' -> +> let len = bound' - first in +> VList (Nat len) (map f (genericTake len [first ..])) +> +> , "fromToBy" ~> vFinPoly $ \first -> pure $ +> vFinPoly $ \lst -> pure $ +> vFinPoly $ \stride -> pure $ +> VPoly $ \ty -> pure $ +> let f i = literal i ty in +> let vs = [ f (first + i*stride) | i <- [0..] ] in +> let len = 1 + ((lst-first) `div` stride) in +> VList (Nat len) (genericTake len vs) +> +> , "fromToByLessThan" ~> +> vFinPoly $ \first -> pure $ +> VNumPoly $ \bound -> pure $ +> vFinPoly $ \stride -> pure $ +> VPoly $ \ty -> pure $ +> let f i = literal i ty in +> let vs = [ f (first + i*stride) | i <- [0..] ] in +> case bound of +> Inf -> VList Inf vs +> Nat bound' -> +> let len = (bound'-first+stride-1) `div` stride in +> VList (Nat len) (genericTake len vs) +> +> , "fromToDownBy" ~> +> vFinPoly $ \first -> pure $ +> vFinPoly $ \lst -> pure $ +> vFinPoly $ \stride -> pure $ +> VPoly $ \ty -> pure $ +> let f i = literal i ty in +> let vs = [ f (first - i*stride) | i <- [0..] ] in +> let len = 1 + ((first-lst) `div` stride) in +> VList (Nat len) (genericTake len vs) +> +> , "fromToDownByGreaterThan" ~> +> vFinPoly $ \first -> pure $ +> vFinPoly $ \lst -> pure $ +> vFinPoly $ \stride -> pure $ +> VPoly $ \ty -> pure $ +> let f i = literal i ty in +> let vs = [ f (first - i*stride) | i <- [0..] ] in +> let len = (first-lst+stride-1) `div` stride in +> VList (Nat len) (genericTake len vs) > > , "fromThenTo" ~> vFinPoly $ \first -> pure $ > vFinPoly $ \next -> pure $ > vFinPoly $ \_lst -> pure $ > VPoly $ \ty -> pure $ -> vFinPoly $ \len -> -> let f i = literal i ty -> in pure (VList (Nat len) -> (map f (genericTake len [first, next ..]))) -> -> , "fromToLessThan" ~> -> vFinPoly $ \first -> pure $ -> VNumPoly $ \bound -> pure $ -> VPoly $ \ty -> +> vFinPoly $ \len -> pure $ > let f i = literal i ty in -> case bound of -> Inf -> pure (VList Inf (map f [first ..])) -> Nat bound' -> -> let len = bound' - first in -> pure (VList (Nat len) (map f (genericTake len [first ..]))) +> VList (Nat len) +> (map f (genericTake len [first, next ..])) > > , "infFrom" ~> VPoly $ \ty -> pure $ > VFun $ \first -> @@ -1730,11 +1774,10 @@ Pretty Printing > case traverse isBit vs of > Just bs -> ppBV opts (mkBv n (bitsToInteger bs)) > Nothing -> ppList (map (ppEValue opts) vs) -> where ppList docs = brackets (fsep (punctuate comma docs)) -> isBit v = case v of Value (VBit b) -> Just b +> where isBit v = case v of Value (VBit b) -> Just b > _ -> Nothing -> VTuple vs -> parens (sep (punctuate comma (map (ppEValue opts) vs))) -> VRecord fs -> braces (sep (punctuate comma (map ppField fs))) +> VTuple vs -> ppTuple (map (ppEValue opts) vs) +> VRecord fs -> ppRecord (map ppField fs) > where ppField (f,r) = pp f <+> char '=' <+> ppEValue opts r > VFun _ -> text "" > VPoly _ -> text "" diff --git a/src/Cryptol/Eval/SBV.hs b/src/Cryptol/Eval/SBV.hs index e83ceea8..8ecf087e 100644 --- a/src/Cryptol/Eval/SBV.hs +++ b/src/Cryptol/Eval/SBV.hs @@ -29,7 +29,7 @@ import qualified Data.Text as T import Data.SBV.Dynamic as SBV import Cryptol.Backend -import Cryptol.Backend.Monad (Unsupported(..) ) +import Cryptol.Backend.Monad (Unsupported(..), EvalError(..) ) import Cryptol.Backend.SBV import Cryptol.Backend.SeqMap import Cryptol.Backend.WordValue @@ -81,25 +81,32 @@ indexFront sym mblen a xs _ix idx Just ws -> do z <- wordLit sym wlen 0 return $ VWord wlen $ wordVal $ SBV.svSelect ws z idx - Nothing -> folded + Nothing -> folded' + + | otherwise = folded' - | otherwise - = folded where k = SBV.kindOf idx - def = zeroV sym a - f n y = iteValue sym (SBV.svEqual idx (SBV.svInteger k n)) (lookupSeqMap xs n) y + + f n (Just y) = Just $ iteValue sym (SBV.svEqual idx (SBV.svInteger k n)) (lookupSeqMap xs n) y + f n Nothing = Just $ lookupSeqMap xs n + + folded' = + case folded of + Nothing -> raiseError sym (InvalidIndex Nothing) + Just m -> m + folded = case k of KBounded _ w -> case mblen of - Nat n | n < 2^w -> foldr f def [0 .. n-1] - _ -> foldr f def [0 .. 2^w - 1] + Nat n | n < 2^w -> foldr f Nothing [0 .. n-1] + _ -> foldr f Nothing [0 .. 2^w - 1] _ -> case mblen of - Nat n -> foldr f def [0 .. n-1] - Inf -> liftIO (X.throw (UnsupportedSymbolicOp "unbounded integer indexing")) + Nat n -> foldr f Nothing [0 .. n-1] + Inf -> Just (liftIO (X.throw (UnsupportedSymbolicOp "unbounded integer indexing"))) indexFront_segs :: SBV -> diff --git a/src/Cryptol/Eval/Value.hs b/src/Cryptol/Eval/Value.hs index 3666e75f..458d8802 100644 --- a/src/Cryptol/Eval/Value.hs +++ b/src/Cryptol/Eval/Value.hs @@ -165,11 +165,11 @@ ppValue x opts = loop loop :: GenValue sym -> SEval sym Doc loop val = case val of VRecord fs -> do fs' <- traverse (>>= loop) fs - return $ braces (sep (punctuate comma (map ppField (fields fs')))) + return $ ppRecord (map ppField (fields fs')) where ppField (f,r) = pp f <+> char '=' <+> r VTuple vals -> do vals' <- traverse (>>=loop) vals - return $ parens (sep (punctuate comma vals')) + return $ ppTuple vals' VBit b -> ppSBit x b VInteger i -> ppSInteger x i VRational q -> ppSRational x q @@ -177,10 +177,7 @@ ppValue x opts = loop VSeq sz vals -> ppWordSeq sz vals VWord _ wv -> ppWordVal wv VStream vals -> do vals' <- traverse (>>=loop) $ enumerateSeqMap (useInfLength opts) vals - return $ brackets $ fsep - $ punctuate comma - ( vals' ++ [text "..."] - ) + return $ ppList ( vals' ++ [text "..."] ) VFun{} -> return $ text "" VPoly{} -> return $ text "" VNumPoly{} -> return $ text "" @@ -204,9 +201,9 @@ ppValue x opts = loop case traverse (wordAsChar x) vs of Just str -> return $ text (show str) _ -> do vs' <- mapM (ppSWord x opts) vs - return $ brackets (fsep (punctuate comma vs')) + return $ ppList vs' _ -> do ws' <- traverse loop ws - return $ brackets (fsep (punctuate comma ws')) + return $ ppList ws' ppSBit :: Backend sym => sym -> SBit sym -> SEval sym Doc ppSBit sym b = @@ -273,7 +270,7 @@ ppSWord sym opts bv prefix len = case base of 2 -> text "0b" <.> padding 1 len 8 -> text "0o" <.> padding 3 len - 10 -> empty + 10 -> mempty 16 -> text "0x" <.> padding 4 len _ -> text "0" <.> char '<' <.> int base <.> char '>' diff --git a/src/Cryptol/Eval/What4.hs b/src/Cryptol/Eval/What4.hs index 2e53feb2..0e6bc98f 100644 --- a/src/Cryptol/Eval/What4.hs +++ b/src/Cryptol/Eval/What4.hs @@ -510,7 +510,9 @@ indexFront_int sym mblen _a xs ix idx = lookupSeqMap xs i | (lo, Just hi) <- bounds - = foldr f def [lo .. hi] + = case foldr f Nothing [lo .. hi] of + Nothing -> raiseError sym (InvalidIndex Nothing) + Just m -> m | otherwise = liftIO (X.throw (UnsupportedSymbolicOp "unbounded integer indexing")) @@ -518,11 +520,10 @@ indexFront_int sym mblen _a xs ix idx where w4sym = w4 sym - def = raiseError sym (InvalidIndex Nothing) - - f n y = + f n (Just y) = Just $ do p <- liftIO (W4.intEq w4sym idx =<< W4.intLit w4sym n) iteValue sym p (lookupSeqMap xs n) y + f n Nothing = Just $ lookupSeqMap xs n bounds = (case W4.rangeLowBound (W4.integerBounds idx) of @@ -559,17 +560,19 @@ indexFront_segs sym mblen _a xs _ix _idx_bits [WordIndexSegment idx] = lookupSeqMap xs i | otherwise - = foldr f def idxs + = case foldr f Nothing idxs of + Nothing -> raiseError sym (InvalidIndex Nothing) + Just m -> m where w4sym = w4 sym w = SW.bvWidth idx - def = raiseError sym (InvalidIndex Nothing) - f n y = + f n (Just y) = Just $ do p <- liftIO (SW.bvEq w4sym idx =<< SW.bvLit w4sym w n) iteValue sym p (lookupSeqMap xs n) y + f n Nothing = Just $ lookupSeqMap xs n -- maximum possible in-bounds index given the bitwidth -- of the index value and the length of the sequence diff --git a/src/Cryptol/ModuleSystem.hs b/src/Cryptol/ModuleSystem.hs index 36f6d76f..cf8986b1 100644 --- a/src/Cryptol/ModuleSystem.hs +++ b/src/Cryptol/ModuleSystem.hs @@ -33,6 +33,8 @@ module Cryptol.ModuleSystem ( , IfaceTySyn, IfaceDecl(..) ) where +import Data.Map (Map) + import qualified Cryptol.Eval.Concrete as Concrete import Cryptol.ModuleSystem.Env import Cryptol.ModuleSystem.Interface @@ -94,7 +96,7 @@ evalExpr :: T.Expr -> ModuleCmd Concrete.Value evalExpr e env = runModuleM env (interactive (Base.evalExpr e)) -- | Typecheck top-level declarations. -checkDecls :: [P.TopDecl PName] -> ModuleCmd (R.NamingEnv,[T.DeclGroup]) +checkDecls :: [P.TopDecl PName] -> ModuleCmd (R.NamingEnv,[T.DeclGroup], Map Name T.TySyn) checkDecls ds env = runModuleM env $ interactive $ Base.checkDecls ds diff --git a/src/Cryptol/ModuleSystem/Base.hs b/src/Cryptol/ModuleSystem/Base.hs index 1c896139..ea5da635 100644 --- a/src/Cryptol/ModuleSystem/Base.hs +++ b/src/Cryptol/ModuleSystem/Base.hs @@ -353,7 +353,7 @@ checkExpr e = do -- | Typecheck a group of declarations. -- -- INVARIANT: This assumes that NoPat has already been run on the declarations. -checkDecls :: [P.TopDecl PName] -> ModuleM (R.NamingEnv,[T.DeclGroup]) +checkDecls :: [P.TopDecl PName] -> ModuleM (R.NamingEnv,[T.DeclGroup], Map.Map Name T.TySyn) checkDecls ds = do fe <- getFocusedEnv let params = mctxParams fe @@ -365,8 +365,8 @@ checkDecls ds = do prims <- getPrimMap let act = TCAction { tcAction = T.tcDecls, tcLinter = declsLinter , tcPrims = prims } - ds' <- typecheck act rds params decls - return (declsEnv,ds') + (ds',tyMap) <- typecheck act rds params decls + return (declsEnv,ds',tyMap) -- | Generate the primitive map. If the prelude is currently being loaded, this -- should be generated directly from the naming environment given to the renamer @@ -482,11 +482,11 @@ exprLinter = TCLinter , lintModule = Nothing } -declsLinter :: TCLinter [ T.DeclGroup ] +declsLinter :: TCLinter ([ T.DeclGroup ], a) declsLinter = TCLinter - { lintCheck = \ds' i -> case TcSanity.tcDecls i ds' of - Left err -> Left err - Right os -> Right os + { lintCheck = \(ds',_) i -> case TcSanity.tcDecls i ds' of + Left err -> Left err + Right os -> Right os , lintModule = Nothing } diff --git a/src/Cryptol/ModuleSystem/Env.hs b/src/Cryptol/ModuleSystem/Env.hs index ae2c55f9..92fc0723 100644 --- a/src/Cryptol/ModuleSystem/Env.hs +++ b/src/Cryptol/ModuleSystem/Env.hs @@ -400,38 +400,43 @@ removeLoadedModule rm lm = data DynamicEnv = DEnv { deNames :: R.NamingEnv , deDecls :: [T.DeclGroup] + , deTySyns :: Map Name T.TySyn , deEnv :: EvalEnv } deriving Generic instance Semigroup DynamicEnv where de1 <> de2 = DEnv - { deNames = deNames de1 <> deNames de2 - , deDecls = deDecls de1 <> deDecls de2 - , deEnv = deEnv de1 <> deEnv de2 + { deNames = deNames de1 <> deNames de2 + , deDecls = deDecls de1 <> deDecls de2 + , deTySyns = deTySyns de1 <> deTySyns de2 + , deEnv = deEnv de1 <> deEnv de2 } instance Monoid DynamicEnv where mempty = DEnv - { deNames = mempty - , deDecls = mempty - , deEnv = mempty + { deNames = mempty + , deDecls = mempty + , deTySyns = mempty + , deEnv = mempty } mappend de1 de2 = de1 <> de2 -- | Build 'IfaceDecls' that correspond to all of the bindings in the -- dynamic environment. -- --- XXX: if we ever add type synonyms or newtypes at the REPL, revisit +-- XXX: if we add newtypes, etc. at the REPL, revisit -- this. deIfaceDecls :: DynamicEnv -> IfaceDecls -deIfaceDecls DEnv { deDecls = dgs } = - mconcat [ IfaceDecls - { ifTySyns = Map.empty - , ifNewtypes = Map.empty - , ifAbstractTypes = Map.empty - , ifDecls = Map.singleton (ifDeclName ifd) ifd - , ifModules = Map.empty - } - | decl <- concatMap T.groupDecls dgs - , let ifd = T.mkIfaceDecl decl - ] +deIfaceDecls DEnv { deDecls = dgs, deTySyns = tySyns } = + IfaceDecls { ifTySyns = tySyns + , ifNewtypes = Map.empty + , ifAbstractTypes = Map.empty + , ifDecls = decls + , ifModules = Map.empty + } + where + decls = mconcat + [ Map.singleton (ifDeclName ifd) ifd + | decl <- concatMap T.groupDecls dgs + , let ifd = T.mkIfaceDecl decl + ] diff --git a/src/Cryptol/ModuleSystem/Exports.hs b/src/Cryptol/ModuleSystem/Exports.hs index f510e1cb..a85d478a 100644 --- a/src/Cryptol/ModuleSystem/Exports.hs +++ b/src/Cryptol/ModuleSystem/Exports.hs @@ -15,23 +15,25 @@ import Cryptol.ModuleSystem.Name modExports :: Ord name => ModuleG mname name -> ExportSpec name modExports m = fold (concat [ exportedNames d | d <- mDecls m ]) - where - names by td = [ td { tlValue = thing n } | n <- fst (by (tlValue td)) ] - exportedNames (Decl td) = map exportBind (names namesD td) - ++ map exportType (names tnamesD td) - exportedNames (DPrimType t) = [ exportType (thing . primTName <$> t) ] - exportedNames (TDNewtype nt) = map exportType (names tnamesNT nt) - exportedNames (Include {}) = [] - exportedNames (DImport {}) = [] - exportedNames (DParameterFun {}) = [] - exportedNames (DParameterType {}) = [] - exportedNames (DParameterConstraint {}) = [] - exportedNames (DModule nested) = - case tlValue nested of - NestedModule x -> - [exportName NSModule nested { tlValue = thing (mName x) }] +exportedNames :: Ord name => TopDecl name -> [ExportSpec name] +exportedNames (Decl td) = map exportBind (names namesD td) + ++ map exportType (names tnamesD td) +exportedNames (DPrimType t) = [ exportType (thing . primTName <$> t) ] +exportedNames (TDNewtype nt) = map exportType (names tnamesNT nt) +exportedNames (Include {}) = [] +exportedNames (DImport {}) = [] +exportedNames (DParameterFun {}) = [] +exportedNames (DParameterType {}) = [] +exportedNames (DParameterConstraint {}) = [] +exportedNames (DModule nested) = + case tlValue nested of + NestedModule x -> + [exportName NSModule nested { tlValue = thing (mName x) }] + +names :: (a -> ([Located a'], b)) -> TopLevel a -> [TopLevel a'] +names by td = [ td { tlValue = thing n } | n <- fst (by (tlValue td)) ] newtype ExportSpec name = ExportSpec (Map Namespace (Set name)) @@ -78,6 +80,3 @@ isExportedBind = isExported NSValue -- | Check to see if a type synonym is exported. isExportedType :: Ord name => name -> ExportSpec name -> Bool isExportedType = isExported NSType - - - diff --git a/src/Cryptol/ModuleSystem/Monad.hs b/src/Cryptol/ModuleSystem/Monad.hs index 7a478603..e78bca04 100644 --- a/src/Cryptol/ModuleSystem/Monad.hs +++ b/src/Cryptol/ModuleSystem/Monad.hs @@ -202,7 +202,7 @@ instance PP ModuleError where FailedToParameterizeModDefs x xs -> hang (text "[error] Parameterized module" <+> pp x <+> text "has polymorphic parameters:") - 4 (hsep $ punctuate comma $ map pp xs) + 4 (commaSep (map pp xs)) NotAParameterizedModule x -> text "[error] Module" <+> pp x <+> text "does not have parameters." diff --git a/src/Cryptol/ModuleSystem/NamingEnv.hs b/src/Cryptol/ModuleSystem/NamingEnv.hs index 9ba085fb..d83506cf 100644 --- a/src/Cryptol/ModuleSystem/NamingEnv.hs +++ b/src/Cryptol/ModuleSystem/NamingEnv.hs @@ -110,7 +110,7 @@ merge xs ys | xs == ys = xs instance PP NamingEnv where ppPrec _ (NamingEnv mps) = vcat $ map ppNS $ Map.toList mps where ppNS (ns,xs) = pp ns $$ nest 2 (vcat (map ppNm (Map.toList xs))) - ppNm (x,as) = pp x <+> "->" <+> hsep (punctuate comma (map pp as)) + ppNm (x,as) = pp x <+> "->" <+> commaSep (map pp as) -- | Generate a mapping from 'PrimIdent' to 'Name' for a -- given naming environment. diff --git a/src/Cryptol/ModuleSystem/Renamer.hs b/src/Cryptol/ModuleSystem/Renamer.hs index a05c97ba..fdee5340 100644 --- a/src/Cryptol/ModuleSystem/Renamer.hs +++ b/src/Cryptol/ModuleSystem/Renamer.hs @@ -90,8 +90,12 @@ renameTopDecls m ds0 = setNestedModule (nestedModuleNames nested) do ds1 <- shadowNames' CheckOverlap env (renameTopDecls' (nested,mpath) ds) - pure (env,ds1) + -- record a use of top-level names to avoid + -- unused name warnings + let exports = concatMap exportedNames ds1 + mapM_ recordUse (foldMap (exported NSType) exports) + pure (env,ds1) -- | Returns declarations with additional imports and the public module names -- of this module and its children @@ -256,7 +260,12 @@ renameTopDecls' info ds = TDNewtype {} -> False DParameterType {} -> False DParameterConstraint {} -> False - DParameterFun {} -> False + + DParameterFun {} -> True + -- Here we may need the constraints to validate the type + -- (e.g., if the parameter is of type `Z a`) + + DModule tl -> any usesCtrs (mDecls m) where NestedModule m = tlValue tl DImport {} -> False @@ -465,6 +474,13 @@ instance Rename PrimType where depsOf (NamedThing (thing x)) do let (as,ps) = primTCts pt (_,cts) <- renameQual as ps $ \as' ps' -> pure (as',ps') + + -- Record an additional use for each parameter since we checked + -- earlier that all the parameters are used exactly once in the + -- body of the signature. This prevents incorret warnings + -- about unused names. + mapM_ (recordUse . tpName) (fst cts) + pure pt { primTCts = cts, primTName = x } instance Rename ParameterType where @@ -727,6 +743,18 @@ instance Rename Expr where <*> traverse rename n <*> rename e <*> traverse rename t + EFromToBy isStrict s e b t -> + EFromToBy isStrict + <$> rename s + <*> rename e + <*> rename b + <*> traverse rename t + EFromToDownBy isStrict s e b t -> + EFromToDownBy isStrict + <$> rename s + <*> rename e + <*> rename b + <*> traverse rename t EFromToLessThan s e t -> EFromToLessThan <$> rename s <*> rename e diff --git a/src/Cryptol/ModuleSystem/Renamer/Error.hs b/src/Cryptol/ModuleSystem/Renamer/Error.hs index bfe152e0..ebdbc49c 100644 --- a/src/Cryptol/ModuleSystem/Renamer/Error.hs +++ b/src/Cryptol/ModuleSystem/Renamer/Error.hs @@ -94,11 +94,10 @@ instance PP RenamerError where WrongNamespace expected actual lqn -> hang ("[error] at" <+> pp (srcRange lqn )) - 4 (fsep + 4 (fsep $ [ "Expected a", sayNS expected, "named", quotes (pp (thing lqn)) , "but found a", sayNS actual, "instead" - , suggestion - ]) + ] ++ suggestion) where sayNS ns = case ns of NSValue -> "value" @@ -106,30 +105,31 @@ instance PP RenamerError where NSModule -> "module" suggestion = case (expected,actual) of + (NSValue,NSType) -> - "Did you mean `(" <.> pp (thing lqn) <.> text")?" - _ -> empty + ["Did you mean `(" <.> pp (thing lqn) <.> text")?"] + _ -> [] FixityError o1 f1 o2 f2 -> hang (text "[error] at" <+> pp (srcRange o1) <+> text "and" <+> pp (srcRange o2)) - 4 (fsep [ text "The fixities of" - , nest 2 $ vcat + 4 (vsep [ text "The fixities of" + , indent 2 $ vcat [ "•" <+> pp (thing o1) <+> parens (pp f1) , "•" <+> pp (thing o2) <+> parens (pp f2) ] , text "are not compatible." , text "You may use explicit parentheses to disambiguate." ]) InvalidConstraint ty -> - hang (text "[error]" <+> maybe empty (\r -> text "at" <+> pp r) (getLoc ty)) + hang (hsep $ [text "[error]"] ++ maybe [] (\r -> [text "at" <+> pp r]) (getLoc ty)) 4 (fsep [ pp ty, text "is not a valid constraint" ]) MalformedBuiltin ty pn -> - hang (text "[error]" <+> maybe empty (\r -> text "at" <+> pp r) (getLoc ty)) + hang (hsep $ [text "[error]"] ++ maybe [] (\r -> [text "at" <+> pp r]) (getLoc ty)) 4 (fsep [ text "invalid use of built-in type", pp pn , text "in type", pp ty ]) BoundReservedType n loc src -> - hang (text "[error]" <+> maybe empty (\r -> text "at" <+> pp r) loc) + hang (hsep $ [text "[error]"] ++ maybe [] (\r -> [text "at" <+> pp r]) loc) 4 (fsep [ text "built-in type", quotes (pp n), text "shadowed in", src ]) OverlappingRecordUpdate xs ys -> @@ -139,9 +139,9 @@ instance PP RenamerError where ppLab as = ppNestedSels (thing as) <+> "at" <+> pp (srcRange as) InvalidDependency ds -> - "[error] Invalid recursive dependency:" - $$ nest 4 (vcat [ "•" <+> pp x <.> ", defined at" <+> ppR (depNameLoc x) - | x <- ds ]) + hang "[error] Invalid recursive dependency:" + 4 (vcat [ "•" <+> pp x <.> ", defined at" <+> ppR (depNameLoc x) + | x <- ds ]) where ppR r = pp (from r) <.> "--" <.> pp (to r) instance PP DepName where @@ -193,7 +193,7 @@ instance PP RenamerWarning where where plural | length os > 1 = char 's' - | otherwise = empty + | otherwise = mempty loc = pp (nameLoc x) diff --git a/src/Cryptol/Parser.y b/src/Cryptol/Parser.y index a9fb04d1..47c00d6e 100644 --- a/src/Cryptol/Parser.y +++ b/src/Cryptol/Parser.y @@ -85,6 +85,8 @@ import Paths_cryptol 'then' { Located $$ (Token (KW KW_then ) _)} 'else' { Located $$ (Token (KW KW_else ) _)} 'x' { Located $$ (Token (KW KW_x) _)} + 'down' { Located $$ (Token (KW KW_down) _)} + 'by' { Located $$ (Token (KW KW_by) _)} 'primitive' { Located $$ (Token (KW KW_primitive) _)} 'constraint'{ Located $$ (Token (KW KW_constraint) _)} @@ -96,8 +98,10 @@ import Paths_cryptol '..' { Located $$ (Token (Sym DotDot ) _)} '...' { Located $$ (Token (Sym DotDotDot) _)} '..<' { Located $$ (Token (Sym DotDotLt) _)} + '..>' { Located $$ (Token (Sym DotDotGt) _)} '|' { Located $$ (Token (Sym Bar ) _)} '<' { Located $$ (Token (Sym Lt ) _)} + '>' { Located $$ (Token (Sym Gt ) _)} '(' { Located $$ (Token (Sym ParenL ) _)} ')' { Located $$ (Token (Sym ParenR ) _)} @@ -334,9 +338,48 @@ decl :: { Decl PName } | 'infix' NUM ops {% mkFixity NonAssoc $2 (reverse $3) } | error {% expected "a declaration" } +let_decls :: { [Decl PName] } + : let_decl { [$1] } + | let_decl ';' { [$1] } + | let_decl ';' let_decls { ($1:$3) } + let_decl :: { Decl PName } - : 'let' ipat '=' expr { at ($2,$4) $ DPatBind $2 $4 } - | 'let' name apats_indices '=' expr { at ($2,$5) $ mkIndexedDecl $2 $3 $5 } + : 'let' ipat '=' expr { at ($2,$4) $ DPatBind $2 $4 } + | 'let' var apats_indices '=' expr { at ($2,$5) $ mkIndexedDecl $2 $3 $5 } + | 'let' '(' op ')' '=' expr { at ($2,$6) $ DPatBind (PVar $3) $6 } + | 'let' apat pat_op apat '=' expr + { at ($2,$6) $ + DBind $ Bind { bName = $3 + , bParams = [$2,$4] + , bDef = at $6 (Located emptyRange (DExpr $6)) + , bSignature = Nothing + , bPragmas = [] + , bMono = False + , bInfix = True + , bFixity = Nothing + , bDoc = Nothing + , bExport = Public + } } + + | 'let' vars_comma ':' schema { at (head $2,$4) $ DSignature (reverse $2) $4 } + + | 'type' name '=' type {% at ($1,$4) `fmap` mkTySyn $2 [] $4 } + | 'type' name tysyn_params '=' type + {% at ($1,$5) `fmap` mkTySyn $2 (reverse $3) $5 } + | 'type' tysyn_param op tysyn_param '=' type + {% at ($1,$6) `fmap` mkTySyn $3 [$2, $4] $6 } + + | 'type' 'constraint' name '=' type + {% at ($2,$5) `fmap` mkPropSyn $3 [] $5 } + | 'type' 'constraint' name tysyn_params '=' type + {% at ($2,$6) `fmap` mkPropSyn $3 (reverse $4) $6 } + | 'type' 'constraint' tysyn_param op tysyn_param '=' type + {% at ($2,$7) `fmap` mkPropSyn $4 [$3, $5] $7 } + + | 'infixl' NUM ops {% mkFixity LeftAssoc $2 (reverse $3) } + | 'infixr' NUM ops {% mkFixity RightAssoc $2 (reverse $3) } + | 'infix' NUM ops {% mkFixity NonAssoc $2 (reverse $3) } + newtype :: { Newtype PName } : 'newtype' qname '=' newtype_body @@ -391,7 +434,7 @@ decls_layout :: { [Decl PName] } repl :: { ReplInput PName } : expr { ExprInput $1 } - | let_decl { LetInput $1 } + | let_decls { LetInput $1 } | {- empty -} { EmptyInput } @@ -418,7 +461,7 @@ pat_op :: { LPName } | '~' { Located $1 $ mkUnqual $ mkInfix "~" } | '^^' { Located $1 $ mkUnqual $ mkInfix "^^" } | '<' { Located $1 $ mkUnqual $ mkInfix "<" } - + | '>' { Located $1 $ mkUnqual $ mkInfix ">" } other_op :: { LPName } : OP { let Token (Op (Other [] str)) _ = thing $1 @@ -587,6 +630,14 @@ list_expr :: { Expr PName } | expr '..' '<' expr {% eFromToLessThan $2 $1 $4 } | expr '..<' expr {% eFromToLessThan $2 $1 $3 } + | expr '..' expr 'by' expr {% eFromToBy $2 $1 $3 $5 False } + | expr '..' '<' expr 'by' expr {% eFromToBy $2 $1 $4 $6 True } + | expr '..<' expr 'by' expr {% eFromToBy $2 $1 $3 $5 True } + + | expr '..' expr 'down' 'by' expr {% eFromToDownBy $2 $1 $3 $6 False } + | expr '..' '>' expr 'down' 'by' expr {% eFromToDownBy $2 $1 $4 $7 True } + | expr '..>' expr 'down' 'by' expr {% eFromToDownBy $2 $1 $3 $6 True } + | expr '...' { EInfFrom $1 Nothing } | expr ',' expr '...' { EInfFrom $1 (Just $3) } @@ -732,7 +783,6 @@ ident :: { Located Ident } | 'as' { Located { srcRange = $1, thing = mkIdent "as" } } | 'hiding' { Located { srcRange = $1, thing = mkIdent "hiding" } } - name :: { LPName } : ident { fmap mkUnqual $1 } diff --git a/src/Cryptol/Parser/AST.hs b/src/Cryptol/Parser/AST.hs index 7c7e1fbd..41acb698 100644 --- a/src/Cryptol/Parser/AST.hs +++ b/src/Cryptol/Parser/AST.hs @@ -300,7 +300,7 @@ data PrimType name = PrimType { primTName :: Located name -- | Input at the REPL, which can be an expression, a @let@ -- statement, or empty (possibly a comment). data ReplInput name = ExprInput (Expr name) - | LetInput (Decl name) + | LetInput [Decl name] | EmptyInput deriving (Eq, Show) @@ -351,6 +351,11 @@ data Expr n = EVar n -- ^ @ x @ | EList [Expr n] -- ^ @ [1,2,3] @ | EFromTo (Type n) (Maybe (Type n)) (Type n) (Maybe (Type n)) -- ^ @ [1, 5 .. 117 : t] @ + | EFromToBy Bool (Type n) (Type n) (Type n) (Maybe (Type n)) + -- ^ @ [1 .. 10 by 2 : t ] @ + + | EFromToDownBy Bool (Type n) (Type n) (Type n) (Maybe (Type n)) + -- ^ @ [10 .. 1 down by 2 : t ] @ | EFromToLessThan (Type n) (Type n) (Maybe (Type n)) -- ^ @ [ 1 .. < 10 : t ] @ @@ -616,7 +621,7 @@ instance (Show name, PPName name) => PP (TopDecl name) where where prop = case map (pp . thing) d of [x] -> x [] -> "()" - xs -> parens (hsep (punctuate comma xs)) + xs -> nest 1 (parens (commaSepFill xs)) DModule d -> pp d DImport i -> pp (thing i) @@ -639,7 +644,7 @@ instance (Show name, PPName name) => PP (Decl name) where DSignature xs s -> commaSep (map ppL xs) <+> text ":" <+> pp s DPatBind p e -> pp p <+> text "=" <+> pp e DBind b -> ppPrec n b - DRec bs -> "recursive" $$ nest 2 (vcat (map (ppPrec n) bs)) + DRec bs -> nest 2 (vcat ("recursive" : map (ppPrec n) bs)) DFixity f ns -> ppFixity f ns DPragma xs p -> ppPragma xs p DType ts -> ppPrec n ts @@ -652,16 +657,16 @@ ppFixity (Fixity RightAssoc i) ns = text "infixr" <+> int i <+> commaSep (map pp ppFixity (Fixity NonAssoc i) ns = text "infix" <+> int i <+> commaSep (map pp ns) instance PPName name => PP (Newtype name) where - ppPrec _ nt = hsep - [ text "newtype", ppL (nName nt), hsep (map pp (nParams nt)), char '=' - , braces (commaSep (map (ppNamed' ":") (displayFields (nBody nt)))) ] + ppPrec _ nt = nest 2 $ sep + [ fsep $ [text "newtype", ppL (nName nt)] ++ map pp (nParams nt) ++ [char '='] + , ppRecord (map (ppNamed' ":") (displayFields (nBody nt))) + ] instance PP mname => PP (ImportG mname) where - ppPrec _ d = text "import" <+> sep [ pp (iModule d), mbAs, mbSpec ] + ppPrec _ d = text "import" <+> sep ([pp (iModule d)] ++ mbAs ++ mbSpec) where - mbAs = maybe empty (\ name -> text "as" <+> pp name ) (iAs d) - - mbSpec = maybe empty pp (iSpec d) + mbAs = maybe [] (\ name -> [text "as" <+> pp name]) (iAs d) + mbSpec = maybe [] (\x -> [pp x]) (iSpec d) instance PP name => PP (ImpName name) where ppPrec _ nm = @@ -689,16 +694,16 @@ ppPragma xs p = <+> text "*/" instance (Show name, PPName name) => PP (Bind name) where - ppPrec _ b = sig $$ vcat [ ppPragma [f] p | p <- bPragmas b ] $$ - hang (def <+> eq) 4 (pp (thing (bDef b))) + ppPrec _ b = vcat (sig ++ [ ppPragma [f] p | p <- bPragmas b ] ++ + [hang (def <+> eq) 4 (pp (thing (bDef b)))]) where def | bInfix b = lhsOp | otherwise = lhs f = bName b sig = case bSignature b of - Nothing -> empty - Just s -> pp (DSignature [f] s) + Nothing -> [] + Just s -> [pp (DSignature [f] s)] eq = if bMono b then text ":=" else text "=" - lhs = ppL f <+> fsep (map (ppPrec 3) (bParams b)) + lhs = fsep (ppL f : (map (ppPrec 3) (bParams b))) lhsOp = case bParams b of [x,y] -> pp x <+> ppL f <+> pp y @@ -713,13 +718,17 @@ instance (Show name, PPName name) => PP (BindDef name) where instance PPName name => PP (TySyn name) where ppPrec _ (TySyn x _ xs t) = - text "type" <+> ppL x <+> fsep (map (ppPrec 1) xs) - <+> text "=" <+> pp t + nest 2 $ sep $ + [ fsep $ [text "type", ppL x] ++ map (ppPrec 1) xs ++ [text "="] + , pp t + ] instance PPName name => PP (PropSyn name) where ppPrec _ (PropSyn x _ xs ps) = - text "constraint" <+> ppL x <+> fsep (map (ppPrec 1) xs) - <+> text "=" <+> parens (commaSep (map pp ps)) + nest 2 $ sep $ + [ fsep $ [text "constraint", ppL x] ++ map (ppPrec 1) xs ++ [text "="] + , parens (commaSep (map pp ps)) + ] instance PP Literal where ppPrec _ lit = @@ -776,7 +785,7 @@ ppNumLit n info = | otherwise = bits (Just p) (p : res) (p + 1) (num `shiftR` 1) wrap :: Int -> Int -> Doc -> Doc -wrap contextPrec myPrec doc = if myPrec < contextPrec then parens doc else doc +wrap contextPrec myPrec doc = optParens (myPrec < contextPrec) doc isEApp :: Expr n -> Maybe (Expr n, Expr n) isEApp (ELocated e _) = isEApp e @@ -815,15 +824,23 @@ instance (Show name, PPName name) => PP (Expr name) where ERecord fs -> braces (commaSep (map (ppNamed' "=") (displayFields fs))) EList es -> brackets (commaSep (map pp es)) EFromTo e1 e2 e3 t1 -> brackets (pp e1 <.> step <+> text ".." <+> end) - where step = maybe empty (\e -> comma <+> pp e) e2 + where step = maybe mempty (\e -> comma <+> pp e) e2 end = maybe (pp e3) (\t -> pp e3 <+> colon <+> pp t) t1 + EFromToBy isStrict e1 e2 e3 t1 -> brackets (pp e1 <+> dots <+> pp e2 <+> text "by" <+> end) + where end = maybe (pp e3) (\t -> pp e3 <+> colon <+> pp t) t1 + dots | isStrict = text ".. <" + | otherwise = text ".." + EFromToDownBy isStrict e1 e2 e3 t1 -> brackets (pp e1 <+> dots <+> pp e2 <+> text "down by" <+> end) + where end = maybe (pp e3) (\t -> pp e3 <+> colon <+> pp t) t1 + dots | isStrict = text ".. >" + | otherwise = text ".." EFromToLessThan e1 e2 t1 -> brackets (strt <+> text ".. <" <+> end) where strt = maybe (pp e1) (\t -> pp e1 <+> colon <+> pp t) t1 end = pp e2 EInfFrom e1 e2 -> brackets (pp e1 <.> step <+> text "...") - where step = maybe empty (\e -> comma <+> pp e) e2 - EComp e mss -> brackets (pp e <+> vcat (map arm mss)) - where arm ms = text "|" <+> commaSep (map pp ms) + where step = maybe mempty (\e -> comma <+> pp e) e2 + EComp e mss -> brackets (pp e <> align (vcat (map arm mss))) + where arm ms = text " |" <+> commaSep (map pp ms) EUpd mb fs -> braces (hd <+> "|" <+> commaSep (map pp fs)) where hd = maybe "_" pp mb @@ -841,10 +858,10 @@ instance (Show name, PPName name) => PP (Expr name) where ETyped e t -> wrap n 0 (ppPrec 2 e <+> text ":" <+> pp t) - EWhere e ds -> wrap n 0 (pp e - $$ text "where" - $$ nest 2 (vcat (map pp ds)) - $$ text "") + EWhere e ds -> wrap n 0 $ align $ vsep + [ pp e + , hang "where" 2 (vcat (map pp ds)) + ] -- infix applications _ | Just ifix <- isInfix expr -> @@ -880,9 +897,9 @@ instance PPName name => PP (Pattern name) where case pat of PVar x -> pp (thing x) PWild -> char '_' - PTuple ps -> parens (commaSep (map pp ps)) - PRecord fs -> braces (commaSep (map (ppNamed' "=") (displayFields fs))) - PList ps -> brackets (commaSep (map pp ps)) + PTuple ps -> ppTuple (map pp ps) + PRecord fs -> ppRecord (map (ppNamed' "=") (displayFields fs)) + PList ps -> ppList (map pp ps) PTyped p t -> wrap n 0 (ppPrec 1 p <+> text ":" <+> pp t) PSplit p1 p2 -> wrap n 1 (ppPrec 1 p1 <+> text "#" <+> ppPrec 1 p2) PLocated p _ -> ppPrec n p @@ -893,13 +910,13 @@ instance (Show name, PPName name) => PP (Match name) where instance PPName name => PP (Schema name) where - ppPrec _ (Forall xs ps t _) = sep [vars <+> preds, pp t] + ppPrec _ (Forall xs ps t _) = sep (vars ++ preds ++ [pp t]) where vars = case xs of - [] -> empty - _ -> braces (commaSep (map pp xs)) + [] -> [] + _ -> [nest 1 (braces (commaSepFill (map pp xs)))] preds = case ps of - [] -> empty - _ -> parens (commaSep (map pp ps)) <+> text "=>" + [] -> [] + _ -> [nest 1 (parens (commaSepFill (map pp ps))) <+> text "=>"] instance PP Kind where ppPrec _ KType = text "*" @@ -1074,6 +1091,10 @@ instance NoPos (Expr name) where EUpd x y -> EUpd (noPos x) (noPos y) EList x -> EList (noPos x) EFromTo x y z t -> EFromTo (noPos x) (noPos y) (noPos z) (noPos t) + EFromToBy isStrict x y z t + -> EFromToBy isStrict (noPos x) (noPos y) (noPos z) (noPos t) + EFromToDownBy isStrict x y z t + -> EFromToDownBy isStrict (noPos x) (noPos y) (noPos z) (noPos t) EFromToLessThan x y t -> EFromToLessThan (noPos x) (noPos y) (noPos t) EInfFrom x y -> EInfFrom (noPos x) (noPos y) EComp x y -> EComp (noPos x) (noPos y) diff --git a/src/Cryptol/Parser/Lexer.x b/src/Cryptol/Parser/Lexer.x index 74063ce0..0f76c62a 100644 --- a/src/Cryptol/Parser/Lexer.x +++ b/src/Cryptol/Parser/Lexer.x @@ -116,6 +116,8 @@ $white+ { emit $ White Space } "as" { emit $ KW KW_as } "hiding" { emit $ KW KW_hiding } "newtype" { emit $ KW KW_newtype } +"down" { emit $ KW KW_down } +"by" { emit $ KW KW_by } "infixl" { emit $ KW KW_infixl } "infixr" { emit $ KW KW_infixr } @@ -147,6 +149,7 @@ $white+ { emit $ White Space } ".." { emit $ Sym DotDot } "..." { emit $ Sym DotDotDot } "..<" { emit $ Sym DotDotLt } +"..>" { emit $ Sym DotDotGt } "|" { emit $ Sym Bar } "(" { emit $ Sym ParenL } ")" { emit $ Sym ParenR } @@ -169,6 +172,9 @@ $white+ { emit $ White Space } -- < can appear in the enumeration syntax `[ x .. < y ] "<" { emit $ Sym Lt } +-- > can appear in the enumeration syntax `[ x .. > y down by n ] +">" { emit $ Sym Gt } + -- hash is used as a kind, and as a pattern "#" { emit (Op Hash ) } diff --git a/src/Cryptol/Parser/Name.hs b/src/Cryptol/Parser/Name.hs index 04b05760..3c322dca 100644 --- a/src/Cryptol/Parser/Name.hs +++ b/src/Cryptol/Parser/Name.hs @@ -78,7 +78,7 @@ instance PPName PName where i = getIdent n pfx = case getModName n of Just ns -> pp ns <.> text "::" - Nothing -> empty + Nothing -> mempty ppInfixName n | isInfixIdent i = pfx <.> pp i @@ -87,4 +87,4 @@ instance PPName PName where i = getIdent n pfx = case getModName n of Just ns -> pp ns <.> text "::" - Nothing -> empty + Nothing -> mempty diff --git a/src/Cryptol/Parser/Names.hs b/src/Cryptol/Parser/Names.hs index d4ffb46b..06027391 100644 --- a/src/Cryptol/Parser/Names.hs +++ b/src/Cryptol/Parser/Names.hs @@ -82,6 +82,8 @@ namesE expr = in Set.unions (e : map namesUF fs) EList es -> Set.unions (map namesE es) EFromTo{} -> Set.empty + EFromToBy{} -> Set.empty + EFromToDownBy{} -> Set.empty EFromToLessThan{} -> Set.empty EInfFrom e e' -> Set.union (namesE e) (maybe Set.empty namesE e') EComp e arms -> let (dss,uss) = unzip (map namesArm arms) @@ -203,6 +205,8 @@ tnamesE expr = `Set.union` maybe Set.empty tnamesT b `Set.union` tnamesT c `Set.union` maybe Set.empty tnamesT t + EFromToBy _ a b c t -> Set.unions [ tnamesT a, tnamesT b, tnamesT c, maybe Set.empty tnamesT t ] + EFromToDownBy _ a b c t -> Set.unions [ tnamesT a, tnamesT b, tnamesT c, maybe Set.empty tnamesT t ] EFromToLessThan a b t -> tnamesT a `Set.union` tnamesT b `Set.union` maybe Set.empty tnamesT t EInfFrom e e' -> Set.union (tnamesE e) (maybe Set.empty tnamesE e') diff --git a/src/Cryptol/Parser/NoInclude.hs b/src/Cryptol/Parser/NoInclude.hs index fda369f7..336f2e26 100644 --- a/src/Cryptol/Parser/NoInclude.hs +++ b/src/Cryptol/Parser/NoInclude.hs @@ -34,7 +34,7 @@ import Cryptol.Parser.AST import Cryptol.Parser.LexerUtils (Config(..),defaultConfig) import Cryptol.Parser.ParserUtils import Cryptol.Parser.Unlit (guessPreProc) -import Cryptol.Utils.PP +import Cryptol.Utils.PP hiding (()) removeIncludesModule :: (FilePath -> IO ByteString) -> diff --git a/src/Cryptol/Parser/NoPat.hs b/src/Cryptol/Parser/NoPat.hs index 835a4fa4..c4f475e6 100644 --- a/src/Cryptol/Parser/NoPat.hs +++ b/src/Cryptol/Parser/NoPat.hs @@ -159,6 +159,8 @@ noPatE expr = EUpd mb fs -> EUpd <$> traverse noPatE mb <*> traverse noPatUF fs EList es -> EList <$> mapM noPatE es EFromTo {} -> return expr + EFromToBy {} -> return expr + EFromToDownBy {} -> return expr EFromToLessThan{} -> return expr EInfFrom e e' -> EInfFrom <$> noPatE e <*> traverse noPatE e' EComp e mss -> EComp <$> noPatE e <*> mapM noPatArm mss diff --git a/src/Cryptol/Parser/ParserUtils.hs b/src/Cryptol/Parser/ParserUtils.hs index f6431318..8fb94cc8 100644 --- a/src/Cryptol/Parser/ParserUtils.hs +++ b/src/Cryptol/Parser/ParserUtils.hs @@ -117,13 +117,13 @@ ppError (HappyError path ltok) | White DocStr <- tokenType tok = "Unexpected documentation (/**) comment at" <+> text path <.> char ':' <.> pp pos <.> colon $$ - nest 2 + indent 2 "Documentation comments need to be followed by something to document." | otherwise = text "Parse error at" <+> text path <.> char ':' <.> pp pos <.> comma $$ - nest 2 (text "unexpected:" <+> pp tok) + indent 2 (text "unexpected:" <+> pp tok) where pos = from (srcRange ltok) tok = thing ltok @@ -132,18 +132,18 @@ ppError (HappyOutOfTokens path pos) = text "Unexpected end of file at:" <+> text path <.> char ':' <.> pp pos -ppError (HappyErrorMsg p xs) = text "Parse error at" <+> pp p $$ nest 2 (vcat (map text xs)) +ppError (HappyErrorMsg p xs) = text "Parse error at" <+> pp p $$ indent 2 (vcat (map text xs)) ppError (HappyUnexpected path ltok e) = - text "Parse error at" <+> - text path <.> char ':' <.> pp pos <.> comma $$ - nest 2 unexp $$ - nest 2 ("expected:" <+> text e) + nest 2 $ vcat $ + [ text "Parse error at" <+> text path <.> char ':' <.> pp pos <.> comma ] + ++ unexp + ++ ["expected:" <+> text e] where (unexp,pos) = case ltok of - Nothing -> (empty,start) - Just t -> ( "unexpected:" <+> text (T.unpack (tokenText (thing t))) + Nothing -> ( [] ,start) + Just t -> ( ["unexpected:" <+> text (T.unpack (tokenText (thing t)))] , from (srcRange t) ) @@ -378,6 +378,43 @@ eFromTo r e1 e2 e3 = (Nothing, Nothing, Nothing) -> eFromToType r e1 e2 e3 Nothing _ -> errorMessage r ["A sequence enumeration may have at most one element type annotation."] +eFromToBy :: Range -> Expr PName -> Expr PName -> Expr PName -> Bool -> ParseM (Expr PName) +eFromToBy r e1 e2 e3 isStrictBound = + case (asETyped e1, asETyped e2, asETyped e3) of + (Just (e1', t), Nothing, Nothing) -> eFromToByTyped r e1' e2 e3 (Just t) isStrictBound + (Nothing, Just (e2', t), Nothing) -> eFromToByTyped r e1 e2' e3 (Just t) isStrictBound + (Nothing, Nothing, Just (e3', t)) -> eFromToByTyped r e1 e2 e3' (Just t) isStrictBound + (Nothing, Nothing, Nothing) -> eFromToByTyped r e1 e2 e3 Nothing isStrictBound + _ -> errorMessage r ["A sequence enumeration may have at most one element type annotation."] + +eFromToByTyped :: Range -> Expr PName -> Expr PName -> Expr PName -> Maybe (Type PName) -> Bool -> ParseM (Expr PName) +eFromToByTyped r e1 e2 e3 t isStrictBound = + EFromToBy isStrictBound + <$> exprToNumT r e1 + <*> exprToNumT r e2 + <*> exprToNumT r e3 + <*> pure t + +eFromToDownBy :: + Range -> Expr PName -> Expr PName -> Expr PName -> Bool -> ParseM (Expr PName) +eFromToDownBy r e1 e2 e3 isStrictBound = + case (asETyped e1, asETyped e2, asETyped e3) of + (Just (e1', t), Nothing, Nothing) -> eFromToDownByTyped r e1' e2 e3 (Just t) isStrictBound + (Nothing, Just (e2', t), Nothing) -> eFromToDownByTyped r e1 e2' e3 (Just t) isStrictBound + (Nothing, Nothing, Just (e3', t)) -> eFromToDownByTyped r e1 e2 e3' (Just t) isStrictBound + (Nothing, Nothing, Nothing) -> eFromToDownByTyped r e1 e2 e3 Nothing isStrictBound + _ -> errorMessage r ["A sequence enumeration may have at most one element type annotation."] + +eFromToDownByTyped :: + Range -> Expr PName -> Expr PName -> Expr PName -> Maybe (Type PName) -> Bool -> ParseM (Expr PName) +eFromToDownByTyped r e1 e2 e3 t isStrictBound = + EFromToDownBy isStrictBound + <$> exprToNumT r e1 + <*> exprToNumT r e2 + <*> exprToNumT r e3 + <*> pure t + + asETyped :: Expr n -> Maybe (Expr n, Type n) asETyped (ELocated e _) = asETyped e asETyped (ETyped e t) = Just (e, t) @@ -538,7 +575,8 @@ mkPoly rng terms -- NOTE: The list of patterns is reversed! mkProperty :: LPName -> [Pattern PName] -> Expr PName -> Decl PName -mkProperty f ps e = DBind Bind { bName = f +mkProperty f ps e = at (f,e) $ + DBind Bind { bName = f , bParams = reverse ps , bDef = at e (Located emptyRange (DExpr e)) , bSignature = Nothing diff --git a/src/Cryptol/Parser/Selector.hs b/src/Cryptol/Parser/Selector.hs index ed30f208..df443c0f 100644 --- a/src/Cryptol/Parser/Selector.hs +++ b/src/Cryptol/Parser/Selector.hs @@ -48,16 +48,16 @@ data Selector = TupleSel Int (Maybe Int) instance PP Selector where ppPrec _ sel = case sel of - TupleSel x sig -> int x <+> ppSig tupleSig sig - RecordSel x sig -> pp x <+> ppSig recordSig sig - ListSel x sig -> int x <+> ppSig listSig sig + TupleSel x sig -> sep (int x : ppSig tupleSig sig) + RecordSel x sig -> sep (pp x : ppSig recordSig sig) + ListSel x sig -> sep (int x : ppSig listSig sig) where tupleSig n = int n - recordSig xs = braces $ fsep $ punctuate comma $ map pp xs + recordSig xs = ppRecord $ map pp xs listSig n = int n - ppSig f = maybe empty (\x -> text "/* of" <+> f x <+> text "*/") + ppSig f = maybe [] (\x -> [text "/* of" <+> f x <+> text "*/"]) -- | Display the thing selected by the selector, nicely. diff --git a/src/Cryptol/Parser/Token.hs b/src/Cryptol/Parser/Token.hs index 280f8157..c1ec1690 100644 --- a/src/Cryptol/Parser/Token.hs +++ b/src/Cryptol/Parser/Token.hs @@ -51,6 +51,8 @@ data TokenKW = KW_else | KW_parameter | KW_constraint | KW_Prop + | KW_by + | KW_down deriving (Eq, Show, Generic, NFData) -- | The named operators are a special case for parsing types, and 'Other' is @@ -71,13 +73,14 @@ data TokenSym = Bar | DotDot | DotDotDot | DotDotLt + | DotDotGt | Colon | BackTick | ParenL | ParenR | BracketL | BracketR | CurlyL | CurlyR | TriL | TriR - | Lt + | Lt | Gt | Underscore deriving (Eq, Show, Generic, NFData) diff --git a/src/Cryptol/REPL/Browse.hs b/src/Cryptol/REPL/Browse.hs index 4722e578..b53f5fb9 100644 --- a/src/Cryptol/REPL/Browse.hs +++ b/src/Cryptol/REPL/Browse.hs @@ -6,7 +6,8 @@ import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe(mapMaybe) import Data.List(sortBy) -import qualified Text.PrettyPrint as PP +import Data.Void (Void) +import qualified Prettyprinter as PP import Cryptol.Parser.AST(Pragma(..)) import qualified Cryptol.TypeCheck.Type as T @@ -19,10 +20,10 @@ import Cryptol.ModuleSystem.Interface data BrowseHow = BrowseExported | BrowseInScope -browseModContext :: BrowseHow -> ModContext -> PP.Doc +browseModContext :: BrowseHow -> ModContext -> PP.Doc Void browseModContext how mc = runDoc (env disp) (vcat sections) where - sections = + sections = concat [ browseMParams (env disp) (mctxParams mc) , browseMods disp decls , browseTSyns disp decls @@ -43,15 +44,15 @@ data DispInfo = DispInfo { dispHow :: BrowseHow, env :: NameDisp } -------------------------------------------------------------------------------- -browseMParams :: NameDisp -> IfaceParams -> Doc +browseMParams :: NameDisp -> IfaceParams -> [Doc] browseMParams disp params = ppSectionHeading "Module Parameters" $ addEmpty $ map ppParamTy (sortByName disp (Map.toList (ifParamTypes params))) ++ map ppParamFu (sortByName disp (Map.toList (ifParamFuns params))) where - ppParamTy p = hang ("type" <+> pp (T.mtpName p) <+> ":") 2 (pp (T.mtpKind p)) - ppParamFu p = hang (pp (T.mvpName p) <+> ":") 2 (pp (T.mvpType p)) + ppParamTy p = nest 2 (sep ["type", pp (T.mtpName p) <+> ":", pp (T.mtpKind p)]) + ppParamFu p = nest 2 (sep [pp (T.mvpName p) <+> ":", pp (T.mvpType p)]) -- XXX: should we print the constraints somewhere too? addEmpty xs = case xs of @@ -59,7 +60,7 @@ browseMParams disp params = _ -> xs ++ [" "] -browseMods :: DispInfo -> IfaceDecls -> Doc +browseMods :: DispInfo -> IfaceDecls -> [Doc] browseMods disp decls = ppSection disp "Modules" ppM (ifModules decls) where @@ -70,38 +71,37 @@ browseMods disp decls = -browseTSyns :: DispInfo -> IfaceDecls -> Doc +browseTSyns :: DispInfo -> IfaceDecls -> [Doc] browseTSyns disp decls = ppSection disp "Type Synonyms" pp tss - $$ ppSection disp "Constraint Synonyms" pp cts + ++ ppSection disp "Constraint Synonyms" pp cts where (cts,tss) = Map.partition isCtrait (ifTySyns decls) isCtrait t = T.kindResult (T.kindOf (T.tsDef t)) == T.KProp -browsePrimTys :: DispInfo -> IfaceDecls -> Doc +browsePrimTys :: DispInfo -> IfaceDecls -> [Doc] browsePrimTys disp decls = ppSection disp "Primitive Types" ppA (ifAbstractTypes decls) where - ppA a = pp (T.atName a) <+> ":" <+> pp (T.atKind a) + ppA a = nest 2 (sep [pp (T.atName a) <+> ":", pp (T.atKind a)]) -browseNewtypes :: DispInfo -> IfaceDecls -> Doc +browseNewtypes :: DispInfo -> IfaceDecls -> [Doc] browseNewtypes disp decls = ppSection disp "Newtypes" T.ppNewtypeShort (ifNewtypes decls) -browseVars :: DispInfo -> IfaceDecls -> Doc +browseVars :: DispInfo -> IfaceDecls -> [Doc] browseVars disp decls = ppSection disp "Properties" ppVar props - $$ ppSection disp "Symbols" ppVar syms + ++ ppSection disp "Symbols" ppVar syms where isProp p = PragmaProperty `elem` ifDeclPragmas p (props,syms) = Map.partition isProp (ifDecls decls) - ppVar d = hang (pp (ifDeclName d) <+> char ':') 2 (pp (ifDeclSig d)) - + ppVar d = nest 2 (sep [pp (ifDeclName d) <+> ":", pp (ifDeclSig d)]) -------------------------------------------------------------------------------- -ppSection :: DispInfo -> String -> (a -> Doc) -> Map Name a -> Doc +ppSection :: DispInfo -> String -> (a -> Doc) -> Map Name a -> [Doc] ppSection disp heading ppThing mp = ppSectionHeading heading case dispHow disp of @@ -116,18 +116,18 @@ ppSection disp heading ppThing mp = [ "From" <+> pp nm , "-----" <.> text (map (const '-') (show (runDoc (env disp) (pp nm)))) , " " - , nest 2 (vcat (ppThings things)) + , indent 2 (vcat (ppThings things)) ] -ppSectionHeading :: String -> [Doc] -> Doc +ppSectionHeading :: String -> [Doc] -> [Doc] ppSectionHeading heading body - | null body = empty + | null body = [] | otherwise = - vcat [ text heading - , text (map (const '=') heading) - , " " - , nest 2 (vcat body) - ] + [ text heading + , text (map (const '=') heading) + , " " + , indent 2 (vcat body) + ] diff --git a/src/Cryptol/REPL/Command.hs b/src/Cryptol/REPL/Command.hs index 8f914364..c1c42265 100644 --- a/src/Cryptol/REPL/Command.hs +++ b/src/Cryptol/REPL/Command.hs @@ -85,7 +85,7 @@ import qualified Cryptol.TypeCheck.Parseable as T import qualified Cryptol.TypeCheck.Subst as T import Cryptol.TypeCheck.Solve(defaultReplExpr) import Cryptol.TypeCheck.PP (dump,ppWithNames,emptyNameMap) -import Cryptol.Utils.PP +import Cryptol.Utils.PP hiding (()) import Cryptol.Utils.Panic(panic) import Cryptol.Utils.RecordMap import qualified Cryptol.Parser.AST as P @@ -336,10 +336,10 @@ evalCmd str lineNum mbBatch = do -- $ return $!! show $ pp $ E.WithBase ppOpts val rPutStrLn (show valDoc) - P.LetInput decl -> do + P.LetInput ds -> do -- explicitly make this a top-level declaration, so that it will -- be generalized if mono-binds is enabled - replEvalDecl decl + replEvalDecls ds P.EmptyInput -> -- comment or empty input does nothing pure () @@ -348,16 +348,16 @@ printCounterexample :: CounterExampleType -> Doc -> [Concrete.Value] -> REPL () printCounterexample cexTy exprDoc vs = do ppOpts <- getPPValOpts docs <- mapM (rEval . E.ppValue Concrete ppOpts) vs - rPrint $ hang exprDoc 2 (sep docs) <+> - case cexTy of - SafetyViolation -> text "~> ERROR" - PredicateFalsified -> text "= False" + let cexRes = case cexTy of + SafetyViolation -> [text "~> ERROR"] + PredicateFalsified -> [text "= False"] + rPrint $ nest 2 (sep ([exprDoc] ++ docs ++ cexRes)) printSatisfyingModel :: Doc -> [Concrete.Value] -> REPL () printSatisfyingModel exprDoc vs = do ppOpts <- getPPValOpts docs <- mapM (rEval . E.ppValue Concrete ppOpts) vs - rPrint $ hang exprDoc 2 (sep docs) <+> text ("= True") + rPrint $ nest 2 (sep ([exprDoc] ++ docs ++ [text "= True"])) dumpTestsCmd :: FilePath -> String -> (Int,Int) -> Maybe FilePath -> REPL () @@ -785,6 +785,9 @@ proveSatExpr isSat rng exprDoc texpr schema = do ~(EnvBool yes) <- getUser "showExamples" when yes $ forM_ vss (printSatisfyingModel exprDoc) + let numModels = length tevss + when (numModels > 1) (rPutStrLn ("Models found: " ++ show numModels)) + case exprs of [e] -> void $ bindItVariable ty e _ -> bindItVariables ty exprs @@ -885,10 +888,10 @@ offlineProveSat proverName qtype expr schema mfile = do Just path -> io $ writeFile path smtlib Nothing -> rPutStr smtlib - Right w4Cfg -> + Right _w4Cfg -> do ~(EnvBool hashConsing) <- getUser "hashConsing" ~(EnvBool warnUninterp) <- getUser "warnUninterp" - result <- liftModuleCmd $ W4.satProveOffline w4Cfg hashConsing warnUninterp cmd $ \f -> + result <- liftModuleCmd $ W4.satProveOffline hashConsing warnUninterp cmd $ \f -> do displayMsg case mfile of Just path -> @@ -981,7 +984,8 @@ typeOfCmd str pos fnm = do whenDebug (rPutStrLn (dump def)) fDisp <- M.mctxNameDisp <$> getFocusedEnv -- type annotation ':' has precedence 2 - rPrint $ runDoc fDisp $ ppPrec 2 expr <+> text ":" <+> pp sig + rPrint $ runDoc fDisp $ group $ hang + (ppPrec 2 expr <+> text ":") 2 (pp sig) readFileCmd :: FilePath -> REPL () readFileCmd fp = do @@ -1278,9 +1282,9 @@ helpCmd cmd ns = T.addTNames vs emptyNameMap rs = [ "•" <+> ppWithNames ns c | c <- cs ] rPutStrLn "" - rPrint $ runDoc nameEnv $ nest 4 $ + rPrint $ runDoc nameEnv $ indent 4 $ backticks (ppWithNames ns example) <+> - "requires:" $$ nest 2 (vcat rs) + "requires:" $$ indent 2 (vcat rs) doShowFix (T.atFixitiy a) doShowDocString (T.atDoc a) @@ -1290,12 +1294,13 @@ helpCmd cmd let uses c = T.TVBound (T.mtpParam p) `Set.member` T.fvs c ctrs = filter uses (map P.thing (M.ifParamConstraints params)) ctrDoc = case ctrs of - [] -> empty - [x] -> pp x - xs -> parens $ hsep $ punctuate comma $ map pp xs - decl = text "parameter" <+> pp name <+> text ":" - <+> pp (T.mtpKind p) - $$ ctrDoc + [] -> [] + [x] -> [pp x] + xs -> [parens $ commaSep $ map pp xs] + decl = vcat $ + [ text "parameter" <+> pp name <+> text ":" + <+> pp (T.mtpKind p) ] + ++ ctrDoc return $ doShowTyHelp nameEnv decl (T.mtpDoc p) doShowTyHelp nameEnv decl doc = @@ -1325,15 +1330,14 @@ helpCmd cmd return $ do rPutStrLn "" - let property - | P.PragmaProperty `elem` ifDeclPragmas = text "property" - | otherwise = empty + let property + | P.PragmaProperty `elem` ifDeclPragmas = [text "property"] + | otherwise = [] rPrint $ runDoc nameEnv - $ nest 4 - $ property - <+> pp qname - <+> colon - <+> pp (ifDeclSig) + $ indent 4 + $ hsep + + $ property ++ [pp qname, colon, pp (ifDeclSig)] doShowFix $ ifDeclFixity `mplus` (guard ifDeclInfix >> return P.defaultFixity) @@ -1349,7 +1353,7 @@ helpCmd cmd return $ do rPutStrLn "" rPrint $ runDoc nameEnv - $ nest 4 + $ indent 4 $ text "parameter" <+> pp qname <+> colon <+> pp (T.mvpType p) @@ -1522,12 +1526,13 @@ replCheckDecls ds = do let mkTop d = P.Decl P.TopLevel { P.tlExport = P.Public , P.tlDoc = Nothing , P.tlValue = d } - (names,ds') <- liftModuleCmd (M.checkDecls (map mkTop npds)) + (names,ds',tyMap) <- liftModuleCmd (M.checkDecls (map mkTop npds)) - -- extend the naming env + -- extend the naming env and type synonym maps denv <- getDynEnv - setDynEnv denv { M.deNames = names `M.shadowing` M.deNames denv } - + setDynEnv denv { M.deNames = names `M.shadowing` M.deNames denv + , M.deTySyns = tyMap <> M.deTySyns denv + } return ds' replSpecExpr :: T.Expr -> REPL T.Expr @@ -1641,9 +1646,9 @@ bindItVariables ty exprs = void $ bindItVariable seqTy seqExpr seqTy = E.TVSeq (toInteger len) ty seqExpr = T.EList exprs (E.tValTy ty) -replEvalDecl :: P.Decl P.PName -> REPL () -replEvalDecl decl = do - dgs <- replCheckDecls [decl] +replEvalDecls :: [P.Decl P.PName] -> REPL () +replEvalDecls ds = do + dgs <- replCheckDecls ds validEvalContext dgs whenDebug (mapM_ (\dg -> (rPutStrLn (dump dg))) dgs) liftModuleCmd (M.evalDecls dgs) diff --git a/src/Cryptol/REPL/Monad.hs b/src/Cryptol/REPL/Monad.hs index 49892a76..1e4f2871 100644 --- a/src/Cryptol/REPL/Monad.hs +++ b/src/Cryptol/REPL/Monad.hs @@ -118,7 +118,7 @@ import Control.Monad.IO.Class import Control.Monad.Trans.Control import Data.Char (isSpace, toLower) import Data.IORef - (IORef,newIORef,readIORef,modifyIORef,atomicModifyIORef) + (IORef,newIORef,readIORef,atomicModifyIORef) import Data.List (intercalate, isPrefixOf, unfoldr, sortBy) import Data.Maybe (catMaybes) import Data.Ord (comparing) @@ -180,6 +180,12 @@ data RW = RW , eTCSolver :: Maybe SMT.Solver -- ^ Solver instance to be used for typechecking + + , eTCSolverRestarts :: !Int + -- ^ Counts how many times we've restarted the solver. + -- Used as a kind of id for the current solver, which helps avoid + -- a race condition where the callback of a dead solver runs after + -- a new one has been started. } @@ -202,6 +208,7 @@ defaultRW isBatch callStacks l = do , eProverConfig = Left SBV.defaultProver , eTCConfig = solverConfig , eTCSolver = Nothing + , eTCSolverRestarts = 0 } -- | Build up the prompt for the REPL. @@ -353,9 +360,9 @@ instance PP REPLException where $$ text "Type:" <+> pp s TypeNotTestable t -> text "The expression is not of a testable type." $$ text "Type:" <+> pp t - EvalInParamModule xs -> - text "Expression depends on definitions from a parameterized module:" - $$ nest 2 (vcat (map pp xs)) + EvalInParamModule xs -> nest 2 $ vsep $ + [ text "Expression depends on definitions from a parameterized module:" ] + ++ map pp xs SBVError s -> text "SBV error:" $$ text s SBVException e -> text "SBV exception:" $$ text (show e) SBVPortfolioException e -> text "SBV exception:" $$ text (show e) @@ -406,7 +413,7 @@ modifyRW :: (RW -> (RW,a)) -> REPL a modifyRW f = REPL (\ ref -> atomicModifyIORef ref f) modifyRW_ :: (RW -> RW) -> REPL () -modifyRW_ f = REPL (\ ref -> modifyIORef ref f) +modifyRW_ f = REPL (\ ref -> atomicModifyIORef ref (\x -> (f x, ()))) -- | Construct the prompt for the current environment. getPrompt :: REPL String @@ -415,16 +422,26 @@ getPrompt = mkPrompt `fmap` getRW getCallStacks :: REPL Bool getCallStacks = eCallStacks <$> getRW +-- This assumes that we are not starting solvers in parallel, otherwise +-- there are a bunch of race conditions here. getTCSolver :: REPL SMT.Solver getTCSolver = do rw <- getRW case eTCSolver rw of Just s -> return s Nothing -> - do s <- io (SMT.startSolver (eTCConfig rw)) - modifyRW_ (\rw' -> rw'{ eTCSolver = Just s }) + do ref <- REPL (\ref -> pure ref) + let now = eTCSolverRestarts rw + 1 + upd new = if eTCSolverRestarts new == now + then new { eTCSolver = Nothing } + else new + onExit = atomicModifyIORef ref (\s -> (upd s, ())) + s <- io (SMT.startSolver onExit (eTCConfig rw)) + modifyRW_ (\rw' -> rw'{ eTCSolver = Just s + , eTCSolverRestarts = now }) return s + resetTCSolver :: REPL () resetTCSolver = do mtc <- eTCSolver <$> getRW diff --git a/src/Cryptol/Symbolic.hs b/src/Cryptol/Symbolic.hs index 845b65ab..bc0a5127 100644 --- a/src/Cryptol/Symbolic.hs +++ b/src/Cryptol/Symbolic.hs @@ -38,6 +38,8 @@ module Cryptol.Symbolic , modelPred , varModelPred , varToExpr + , flattenShape + , flattenShapes ) where @@ -213,15 +215,33 @@ ppVarShape _sym (VarFloat _f) = text "" ppVarShape _sym (VarRational _n _d) = text "" ppVarShape sym (VarWord w) = text " integer (wordLen sym w) <> text ">" ppVarShape sym (VarFinSeq _ xs) = - brackets (fsep (punctuate comma (map (ppVarShape sym) xs))) + ppList (map (ppVarShape sym) xs) ppVarShape sym (VarTuple xs) = - parens (sep (punctuate comma (map (ppVarShape sym) xs))) + ppTuple (map (ppVarShape sym) xs) ppVarShape sym (VarRecord fs) = - braces (sep (punctuate comma (map ppField (displayFields fs)))) + ppRecord (map ppField (displayFields fs)) where ppField (f,v) = pp f <+> char '=' <+> ppVarShape sym v +-- | Flatten structured shapes (like tuples and sequences), leaving only +-- a sequence of variable shapes of base type. +flattenShapes :: [VarShape sym] -> [VarShape sym] -> [VarShape sym] +flattenShapes [] tl = tl +flattenShapes (x:xs) tl = flattenShape x (flattenShapes xs tl) + +flattenShape :: VarShape sym -> [VarShape sym] -> [VarShape sym] +flattenShape x tl = + case x of + VarBit{} -> x : tl + VarInteger{} -> x : tl + VarRational{} -> x : tl + VarWord{} -> x : tl + VarFloat{} -> x : tl + VarFinSeq _ vs -> flattenShapes vs tl + VarTuple vs -> flattenShapes vs tl + VarRecord fs -> flattenShapes (recordElements fs) tl + varShapeToValue :: Backend sym => sym -> VarShape sym -> GenValue sym varShapeToValue sym var = case var of diff --git a/src/Cryptol/Symbolic/What4.hs b/src/Cryptol/Symbolic/What4.hs index b4cdda49..d3ca83f8 100644 --- a/src/Cryptol/Symbolic/What4.hs +++ b/src/Cryptol/Symbolic/What4.hs @@ -8,8 +8,10 @@ {-# LANGUAGE BlockArguments #-} {-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE GADTs #-} {-# LANGUAGE ImplicitParams #-} {-# LANGUAGE LambdaCase #-} +{-# LANGUAGE ParallelListComp #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} @@ -33,13 +35,14 @@ import Control.Applicative import Control.Concurrent.Async import Control.Concurrent.MVar import Control.Monad.IO.Class -import Control.Monad (when, foldM, forM_) +import Control.Monad (when, foldM, forM_, void) import qualified Control.Exception as X import System.IO (Handle) import Data.Time import Data.IORef -import Data.List (intercalate) +import Data.List (intercalate, tails, inits) import Data.List.NonEmpty (NonEmpty(..)) +import Data.Proxy import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set @@ -60,7 +63,9 @@ import Cryptol.Backend.What4 import qualified Cryptol.Eval as Eval import qualified Cryptol.Eval.Concrete as Concrete import qualified Cryptol.Eval.Value as Eval +import Cryptol.Eval.Type (TValue) import Cryptol.Eval.What4 + import Cryptol.Parser.Position (emptyRange) import Cryptol.Symbolic import Cryptol.TypeCheck.AST @@ -75,7 +80,15 @@ import qualified What4.SatResult as W4 import qualified What4.SFloat as W4 import qualified What4.SWord as SW import What4.Solver +import qualified What4.Solver.Boolector as W4 +import qualified What4.Solver.CVC4 as W4 +import qualified What4.Solver.ExternalABC as W4 +import qualified What4.Solver.Yices as W4 +import qualified What4.Solver.Z3 as W4 import qualified What4.Solver.Adapter as W4 +import qualified What4.Protocol.Online as W4 +import qualified What4.Protocol.SMTLib2 as W4 +import qualified What4.ProblemFeatures as W4 import qualified Data.BitVector.Sized as BV import Data.Parameterized.Nonce @@ -130,32 +143,64 @@ doW4Eval sym m = W4Result p x -> pure (p,x) -data AnAdapter = AnAdapter (forall st. SolverAdapter st) +data AnAdapter + = AnAdapter (forall st. SolverAdapter st) + | forall s. W4.OnlineSolver s => + AnOnlineAdapter + String + W4.ProblemFeatures + [W4.ConfigDesc] + (Proxy s) data W4ProverConfig = W4ProverConfig AnAdapter + | W4OfflineConfig | W4Portfolio (NonEmpty AnAdapter) proverConfigs :: [(String, W4ProverConfig)] proverConfigs = - [ ("w4-cvc4" , W4ProverConfig (AnAdapter cvc4Adapter) ) - , ("w4-yices" , W4ProverConfig (AnAdapter yicesAdapter) ) - , ("w4-z3" , W4ProverConfig (AnAdapter z3Adapter) ) - , ("w4-boolector", W4ProverConfig (AnAdapter boolectorAdapter) ) - , ("w4-offline" , W4ProverConfig (AnAdapter z3Adapter) ) - , ("w4-any" , allSolvers) + [ ("w4-cvc4" , W4ProverConfig cvc4OnlineAdapter) + , ("w4-yices" , W4ProverConfig yicesOnlineAdapter) + , ("w4-z3" , W4ProverConfig z3OnlineAdapter) + , ("w4-boolector" , W4ProverConfig boolectorOnlineAdapter) + + , ("w4-abc" , W4ProverConfig (AnAdapter W4.externalABCAdapter)) + + , ("w4-offline" , W4OfflineConfig ) + , ("w4-any" , allSolvers) ] +z3OnlineAdapter :: AnAdapter +z3OnlineAdapter = + AnOnlineAdapter "Z3" W4.z3Features W4.z3Options + (Proxy :: Proxy (W4.Writer W4.Z3)) + +yicesOnlineAdapter :: AnAdapter +yicesOnlineAdapter = + AnOnlineAdapter "Yices" W4.yicesDefaultFeatures W4.yicesOptions + (Proxy :: Proxy W4.Connection) + +cvc4OnlineAdapter :: AnAdapter +cvc4OnlineAdapter = + AnOnlineAdapter "CVC4" W4.cvc4Features W4.cvc4Options + (Proxy :: Proxy (W4.Writer W4.CVC4)) + +boolectorOnlineAdapter :: AnAdapter +boolectorOnlineAdapter = + AnOnlineAdapter "Boolector" W4.boolectorFeatures W4.boolectorOptions + (Proxy :: Proxy (W4.Writer W4.Boolector)) + allSolvers :: W4ProverConfig allSolvers = W4Portfolio - $ AnAdapter z3Adapter :| - [ AnAdapter cvc4Adapter - , AnAdapter boolectorAdapter - , AnAdapter yicesAdapter + $ z3OnlineAdapter :| + [ cvc4OnlineAdapter + , boolectorOnlineAdapter + , yicesOnlineAdapter + , AnAdapter W4.externalABCAdapter ] defaultProver :: W4ProverConfig -defaultProver = W4ProverConfig (AnAdapter z3Adapter) +defaultProver = W4ProverConfig z3OnlineAdapter proverNames :: [String] proverNames = map fst proverConfigs @@ -178,12 +223,16 @@ setupProver nm = let msg = "What4 found the following solvers: " ++ show (adapterNames (p:ps')) in pure (Right ([msg], W4Portfolio (p:|ps'))) + Just W4OfflineConfig -> pure (Right ([], W4OfflineConfig)) + Nothing -> pure (Left ("unknown solver name: " ++ nm)) where adapterNames [] = [] adapterNames (AnAdapter adpt : ps) = solver_adapter_name adpt : adapterNames ps + adapterNames (AnOnlineAdapter n _ _ _ : ps) = + n : adapterNames ps filterAdapters [] = pure [] filterAdapters (p:ps) = @@ -191,12 +240,25 @@ setupProver nm = Just _err -> filterAdapters ps Nothing -> (p:) <$> filterAdapters ps + tryAdapter :: AnAdapter -> IO (Maybe X.SomeException) + tryAdapter (AnAdapter adpt) = do sym <- W4.newExprBuilder W4.FloatIEEERepr CryptolState globalNonceGenerator W4.extendConfig (W4.solver_adapter_config_options adpt) (W4.getConfiguration sym) W4.smokeTest sym adpt - + tryAdapter (AnOnlineAdapter _ fs opts (_ :: Proxy s)) = test `X.catch` (pure . Just) + where + test = + do sym <- W4.newExprBuilder W4.FloatIEEERepr CryptolState globalNonceGenerator + W4.extendConfig opts (W4.getConfiguration sym) + (proc :: W4.SolverProcess GlobalNonceGenerator s) <- W4.startSolverProcess fs Nothing sym + res <- W4.checkSatisfiable proc "smoke test" (W4.falsePred sym) + case res of + W4.Unsat () -> return () + _ -> fail "smoke test failed, expected UNSAT!" + void (W4.shutdownSolverProcess proc) + return Nothing proverError :: String -> M.ModuleCmd (Maybe String, ProverResult) proverError msg minp = @@ -211,11 +273,13 @@ setupAdapterOptions cfg sym = case cfg of W4ProverConfig p -> setupAnAdapter p W4Portfolio ps -> mapM_ setupAnAdapter ps + W4OfflineConfig -> return () where setupAnAdapter (AnAdapter adpt) = W4.extendConfig (W4.solver_adapter_config_options adpt) (W4.getConfiguration sym) - + setupAnAdapter (AnOnlineAdapter _n _fs opts _p) = + W4.extendConfig opts (W4.getConfiguration sym) what4FreshFns :: W4.IsSymExprBuilder sym => sym -> FreshVarFns (What4 sym) what4FreshFns sym = @@ -350,16 +414,13 @@ satProve solverCfg hashConsing warnUninterp ProverCommand {..} = Right (ts,args,safety,query) -> case pcQueryType of ProveQuery -> - singleQuery sym solverCfg primMap logData ts args - (Just safety) query + singleQuery sym solverCfg primMap logData ts args (Just safety) query SafetyQuery -> - singleQuery sym solverCfg primMap logData ts args - (Just safety) query + singleQuery sym solverCfg primMap logData ts args (Just safety) query SatQuery num -> - multiSATQuery sym solverCfg primMap logData ts args - query num + multiSATQuery sym solverCfg primMap logData ts args query num printUninterpWarn :: Logger -> Set Text -> IO () printUninterpWarn lg uninterpWarns = @@ -371,17 +432,14 @@ printUninterpWarn lg uninterpWarns = , " " ++ intercalate ", " (map Text.unpack xs) ] satProveOffline :: - W4ProverConfig -> Bool {- ^ hash consing -} -> Bool {- ^ warn on uninterpreted functions -} -> ProverCommand -> ((Handle -> IO ()) -> IO ()) -> M.ModuleCmd (Maybe String) -satProveOffline (W4Portfolio (p:|_)) hashConsing warnUninterp cmd outputContinuation = - satProveOffline (W4ProverConfig p) hashConsing warnUninterp cmd outputContinuation +satProveOffline hashConsing warnUninterp ProverCommand{ .. } outputContinuation = -satProveOffline (W4ProverConfig (AnAdapter adpt)) hashConsing warnUninterp ProverCommand {..} outputContinuation = protectStack onError \modIn -> M.runModuleM modIn do w4sym <- liftIO makeSym @@ -396,27 +454,26 @@ satProveOffline (W4ProverConfig (AnAdapter adpt)) hashConsing warnUninterp Prove case ok of Left msg -> return (Just msg) Right (_ts,_args,_safety,query) -> - do outputContinuation - (\hdl -> solver_adapter_write_smt2 adpt w4sym hdl [query]) + do outputContinuation (\hdl -> W4.writeZ3SMT2File w4sym hdl [query]) return Nothing where makeSym = - do sym <- W4.newExprBuilder W4.FloatIEEERepr CryptolState - globalNonceGenerator - W4.extendConfig (W4.solver_adapter_config_options adpt) - (W4.getConfiguration sym) + do sym <- W4.newExprBuilder W4.FloatIEEERepr CryptolState globalNonceGenerator + W4.extendConfig W4.z3Options (W4.getConfiguration sym) when hashConsing (W4.startCaching sym) pure sym onError msg minp = pure (Right (Just msg, M.minpModuleEnv minp), []) +{- decSatNum :: SatNum -> SatNum decSatNum (SomeSat n) | n > 0 = SomeSat (n-1) decSatNum n = n +-} -multiSATQuery :: +multiSATQuery :: forall sym t fm. sym ~ W4.ExprBuilder t CryptolState fm => What4 sym -> W4ProverConfig -> @@ -427,57 +484,144 @@ multiSATQuery :: W4.Pred sym -> SatNum -> IO (Maybe String, ProverResult) + multiSATQuery sym solverCfg primMap logData ts args query (SomeSat n) | n <= 1 = singleQuery sym solverCfg primMap logData ts args Nothing query +multiSATQuery _sym W4OfflineConfig _primMap _logData _ts _args _query _satNum = + fail "What4 offline solver cannot be used for multi-SAT queries" + multiSATQuery _sym (W4Portfolio _) _primMap _logData _ts _args _query _satNum = - fail "What4 portfolio solver cannot be used for multi SAT queries" + fail "What4 portfolio solver cannot be used for multi-SAT queries" -multiSATQuery sym (W4ProverConfig (AnAdapter adpt)) primMap logData ts args query satNum0 = - do pres <- W4.solver_adapter_check_sat adpt (w4 sym) logData [query] $ \res -> - case res of - W4.Unknown -> return (Left (ProverError "Solver returned UNKNOWN")) - W4.Unsat _ -> return (Left (ThmResult (map unFinType ts))) - W4.Sat (evalFn,_) -> - do xs <- mapM (varShapeToConcrete evalFn) args - let model = computeModel primMap ts xs - blockingPred <- computeBlockingPred sym args xs - return (Right (model, blockingPred)) +multiSATQuery _sym (W4ProverConfig (AnAdapter adpt)) _primMap _logData _ts _args _query _satNum = + fail ("Solver " ++ solver_adapter_name adpt ++ " does not support incremental solving and " ++ + "cannot be used for multi-SAT queries.") - case pres of - Left res -> pure (Just (solver_adapter_name adpt), res) - Right (mdl,block) -> - do mdls <- (mdl:) <$> computeMoreModels [block,query] (decSatNum satNum0) - return (Just (solver_adapter_name adpt), AllSatResult mdls) +multiSATQuery sym (W4ProverConfig (AnOnlineAdapter nm fs _opts (_ :: Proxy s))) + primMap _logData ts args query satNum0 = + X.bracket + (W4.startSolverProcess fs Nothing (w4 sym)) + (void . W4.shutdownSolverProcess) + (\ (proc :: W4.SolverProcess t s) -> + do W4.assume (W4.solverConn proc) query + res <- W4.checkAndGetModel proc "query" + case res of + W4.Unknown -> return (Just nm, ProverError "Solver returned UNKNOWN") + W4.Unsat _ -> return (Just nm, ThmResult (map unFinType ts)) + W4.Sat evalFn -> + do xs <- mapM (varShapeToConcrete evalFn) args + let mdl = computeModel primMap ts xs + -- NB, we flatten these shapes to make sure that we can split + -- our search across all of the atomic variables + let vs = flattenShapes args [] + let cs = flattenShapes xs [] + mdls <- runMultiSat satNum0 $ + do yield mdl + computeMoreModels proc vs cs + return (Just nm, AllSatResult mdls)) where + -- This search procedure uses incremental solving and push/pop to split on the concrete + -- values of variables, while also helping to prevent the accumulation of unhelpful + -- lemmas in the solver state. This algorithm is basically taken from: + -- http://theory.stanford.edu/%7Enikolaj/programmingz3.html#sec-blocking-evaluations + computeMoreModels :: + W4.SolverProcess t s -> + [VarShape (What4 sym)] -> + [VarShape Concrete.Concrete] -> + MultiSat () + computeMoreModels proc vs cs = + -- Enumerate all the ways to split up the current model + forM_ (computeSplits vs cs) $ \ (prefix, vi, ci, suffix) -> + do -- open a new solver frame + liftIO $ W4.push proc + -- force the selected pair to be different + liftIO $ W4.assume (W4.solverConn proc) =<< W4.notPred (w4 sym) =<< computeModelPred sym vi ci + -- force the prefix values to be the same + liftIO $ forM_ prefix $ \(v,c) -> + W4.assume (W4.solverConn proc) =<< computeModelPred sym v c + -- under these assumptions, find all the remaining models + findMoreModels proc (vi:suffix) + -- pop the current assumption frame + liftIO $ W4.pop proc - computeMoreModels _qs (SomeSat n) | n <= 0 = return [] -- should never happen... - computeMoreModels qs (SomeSat n) | n <= 1 = -- final model - W4.solver_adapter_check_sat adpt (w4 sym) logData qs $ \res -> - case res of - W4.Unknown -> return [] - W4.Unsat _ -> return [] - W4.Sat (evalFn,_) -> - do xs <- mapM (varShapeToConcrete evalFn) args - let model = computeModel primMap ts xs - return [model] + findMoreModels :: + W4.SolverProcess t s -> + [VarShape (What4 sym)] -> + MultiSat () + findMoreModels proc vs = + -- see if our current assumptions are consistent + do res <- liftIO (W4.checkAndGetModel proc "find model") + case res of + -- if the solver gets stuck, drop all the way out and stop search + W4.Unknown -> done + -- if our assumptions are already unsatisfiable, stop search and return + W4.Unsat _ -> return () + W4.Sat evalFn -> + -- We found a model. Record it and then use it to split the remaining + -- search variables some more. + do xs <- liftIO (mapM (varShapeToConcrete evalFn) args) + yield (computeModel primMap ts xs) + cs <- liftIO (mapM (varShapeToConcrete evalFn) vs) + computeMoreModels proc vs cs - computeMoreModels qs satNum = - do pres <- W4.solver_adapter_check_sat adpt (w4 sym) logData qs $ \res -> - case res of - W4.Unknown -> return Nothing - W4.Unsat _ -> return Nothing - W4.Sat (evalFn,_) -> - do xs <- mapM (varShapeToConcrete evalFn) args - let model = computeModel primMap ts xs - blockingPred <- computeBlockingPred sym args xs - return (Just (model, blockingPred)) +-- == Support operations for multi-SAT == +type Models = [[(TValue, Expr, Concrete.Value)]] - case pres of - Nothing -> return [] - Just (mdl, block) -> - (mdl:) <$> computeMoreModels (block:qs) (decSatNum satNum) +newtype MultiSat a = + MultiSat { unMultiSat :: Models -> SatNum -> (a -> Models -> SatNum -> IO Models) -> IO Models } + +instance Functor MultiSat where + fmap f m = MultiSat (\ms satNum k -> unMultiSat m ms satNum (k . f)) + +instance Applicative MultiSat where + pure x = MultiSat (\ms satNum k -> k x ms satNum) + mf <*> mx = mf >>= \f -> fmap f mx + +instance Monad MultiSat where + m >>= f = MultiSat (\ms satNum k -> unMultiSat m ms satNum (\x ms' satNum' -> unMultiSat (f x) ms' satNum' k)) + +instance MonadIO MultiSat where + liftIO m = MultiSat (\ms satNum k -> do x <- m; k x ms satNum) + +runMultiSat :: SatNum -> MultiSat a -> IO Models +runMultiSat satNum m = reverse <$> unMultiSat m [] satNum (\_ ms _ -> return ms) + +done :: MultiSat a +done = MultiSat (\ms _satNum _k -> return ms) + +yield :: [(TValue, Expr, Concrete.Value)] -> MultiSat () +yield mdl = MultiSat (\ms satNum k -> + case satNum of + SomeSat n + | n > 1 -> k () (mdl:ms) (SomeSat (n-1)) + | otherwise -> return (mdl:ms) + _ -> k () (mdl:ms) satNum) + +-- Compute all the ways to split a sequences of variables +-- and concrete values for those variables. Each element +-- of the list consists of a prefix of (varaible,value) +-- pairs whose values we will fix, a single (varaible,value) +-- pair that we will force to be different, and a list of +-- additional unconstrained variables. +computeSplits :: + [VarShape (What4 sym)] -> + [VarShape Concrete.Concrete] -> + [ ( [(VarShape (What4 sym), VarShape Concrete.Concrete)] + , VarShape (What4 sym) + , VarShape Concrete.Concrete + , [VarShape (What4 sym)] + ) + ] +computeSplits vs cs = reverse + [ (prefix, v, c, tl) + | prefix <- inits (zip vs cs) + | v <- vs + | c <- cs + | tl <- tail (tails vs) + ] +-- == END Support operations for multi-SAT == singleQuery :: sym ~ W4.ExprBuilder t CryptolState fm => @@ -491,6 +635,10 @@ singleQuery :: W4.Pred sym -> IO (Maybe String, ProverResult) +singleQuery _ W4OfflineConfig _primMap _logData _ts _args _msafe _query = + -- this shouldn't happen... + fail "What4 offline solver cannot be used for direct queries" + singleQuery sym (W4Portfolio ps) primMap logData ts args msafe query = do as <- mapM async [ singleQuery sym (W4ProverConfig p) primMap logData ts args msafe query | p <- NE.toList ps @@ -528,16 +676,37 @@ singleQuery sym (W4ProverConfig (AnAdapter adpt)) primMap logData ts args msafe return (Just (W4.solver_adapter_name adpt), pres) +singleQuery sym (W4ProverConfig (AnOnlineAdapter nm fs _opts (_ :: Proxy s))) + primMap _logData ts args msafe query = + X.bracket + (W4.startSolverProcess fs Nothing (w4 sym)) + (void . W4.shutdownSolverProcess) + (\ (proc :: W4.SolverProcess t s) -> + do W4.assume (W4.solverConn proc) query + res <- W4.checkAndGetModel proc "query" + case res of + W4.Unknown -> return (Just nm, ProverError "Solver returned UNKNOWN") + W4.Unsat _ -> return (Just nm, ThmResult (map unFinType ts)) + W4.Sat evalFn -> + do xs <- mapM (varShapeToConcrete evalFn) args + let model = computeModel primMap ts xs + case msafe of + Just s -> + do s' <- W4.groundEval evalFn s + let cexType = if s' then PredicateFalsified else SafetyViolation + return (Just nm, CounterExample cexType model) + Nothing -> return (Just nm, AllSatResult [ model ]) + ) -computeBlockingPred :: + +computeModelPred :: sym ~ W4.ExprBuilder t CryptolState fm => What4 sym -> - [VarShape (What4 sym)] -> - [VarShape Concrete.Concrete] -> + VarShape (What4 sym) -> + VarShape Concrete.Concrete -> IO (W4.Pred sym) -computeBlockingPred sym vs xs = - do res <- doW4Eval (w4 sym) (modelPred sym vs xs) - W4.notPred (w4 sym) (snd res) +computeModelPred sym v c = + snd <$> doW4Eval (w4 sym) (varModelPred sym (v, c)) varShapeToConcrete :: W4.GroundEvalFn t -> diff --git a/src/Cryptol/TypeCheck.hs b/src/Cryptol/TypeCheck.hs index 682690f8..ae541fa2 100644 --- a/src/Cryptol/TypeCheck.hs +++ b/src/Cryptol/TypeCheck.hs @@ -29,6 +29,7 @@ module Cryptol.TypeCheck ) where import Data.IORef(IORef,modifyIORef') +import Data.Map(Map) import Cryptol.ModuleSystem.Name (liftSupply,mkDeclared,NameSource(..),ModPath(..)) @@ -133,7 +134,7 @@ tcExpr e0 inp = runInferM inp : map show res ) -tcDecls :: [P.TopDecl Name] -> InferInput -> IO (InferOutput [DeclGroup]) +tcDecls :: [P.TopDecl Name] -> InferInput -> IO (InferOutput ([DeclGroup],Map Name TySyn)) tcDecls ds inp = runInferM inp $ do newLocalScope checkTopDecls ds @@ -141,18 +142,16 @@ tcDecls ds inp = runInferM inp $ endLocalScope ppWarning :: (Range,Warning) -> Doc -ppWarning (r,w) = text "[warning] at" <+> pp r <.> colon $$ nest 2 (pp w) +ppWarning (r,w) = nest 2 (text "[warning] at" <+> pp r <.> colon $$ pp w) ppError :: (Range,Error) -> Doc -ppError (r,w) = text "[error] at" <+> pp r <.> colon $$ nest 2 (pp w) - +ppError (r,w) = nest 2 (text "[error] at" <+> pp r <.> colon $$ pp w) ppNamedWarning :: NameMap -> (Range,Warning) -> Doc ppNamedWarning nm (r,w) = - text "[warning] at" <+> pp r <.> colon $$ nest 2 (pp (WithNames w nm)) + nest 2 (text "[warning] at" <+> pp r <.> colon $$ pp (WithNames w nm)) ppNamedError :: NameMap -> (Range,Error) -> Doc ppNamedError nm (r,e) = - text "[error] at" <+> pp r <.> colon $$ nest 2 (pp (WithNames e nm)) - + nest 2 (text "[error] at" <+> pp r <.> colon $$ pp (WithNames e nm)) diff --git a/src/Cryptol/TypeCheck/AST.hs b/src/Cryptol/TypeCheck/AST.hs index 08735128..a061630e 100644 --- a/src/Cryptol/TypeCheck/AST.hs +++ b/src/Cryptol/TypeCheck/AST.hs @@ -211,14 +211,14 @@ instance PP (WithNames Expr) where EList [] t -> optParens (prec > 0) $ text "[]" <+> colon <+> ppWP prec t - EList es _ -> brackets $ sep $ punctuate comma $ map ppW es + EList es _ -> ppList $ map ppW es - ETuple es -> parens $ sep $ punctuate comma $ map ppW es + ETuple es -> ppTuple $ map ppW es - ERec fs -> braces $ sep $ punctuate comma + ERec fs -> ppRecord [ pp f <+> text "=" <+> ppW e | (f,e) <- displayFields fs ] - ESel e sel -> ppWP 4 e <+> text "." <.> pp sel + ESel e sel -> ppWP 4 e <.> text "." <.> pp sel ESet _ty e sel v -> braces (pp e <+> "|" <+> pp sel <+> "=" <+> pp v) @@ -228,7 +228,7 @@ instance PP (WithNames Expr) where , text "else" <+> ppW e3 ] EComp _ _ e mss -> let arm ms = text "|" <+> commaSep (map ppW ms) - in brackets $ ppW e <+> vcat (map arm mss) + in brackets $ ppW e <+> (align (vcat (map arm mss))) EVar x -> ppPrefixName x @@ -261,28 +261,29 @@ instance PP (WithNames Expr) where ETApp e t -> optParens (prec > 3) $ ppWP 3 e <+> ppWP 5 t - EWhere e ds -> optParens (prec > 0) - ( ppW e $$ text "where" - $$ nest 2 (vcat (map ppW ds)) - $$ text "" ) + EWhere e ds -> optParens (prec > 0) $ align $ vsep $ + [ ppW e + , hang "where" 2 (vcat (map ppW ds)) + ] where ppW x = ppWithNames nm x ppWP x = ppWithNamesPrec nm x ppLam :: NameMap -> Int -> [TParam] -> [Prop] -> [(Name,Type)] -> Expr -> Doc -ppLam nm prec [] [] [] e = ppWithNamesPrec nm prec e +ppLam nm prec [] [] [] e = nest 2 (ppWithNamesPrec nm prec e) ppLam nm prec ts ps xs e = optParens (prec > 0) $ - sep [ text "\\" <.> tsD <+> psD <+> xsD <+> text "->" - , ppWithNames ns1 e - ] + nest 2 $ sep + [ text "\\" <.> hsep (tsD ++ psD ++ xsD ++ [text "->"]) + , ppWithNames ns1 e + ] where ns1 = addTNames ts nm - tsD = if null ts then empty else braces $ sep $ punctuate comma $ map ppT ts - psD = if null ps then empty else parens $ sep $ punctuate comma $ map ppP ps - xsD = if null xs then empty else sep $ map ppArg xs + tsD = if null ts then [] else [braces $ commaSep $ map ppT ts] + psD = if null ps then [] else [parens $ commaSep $ map ppP ps] + xsD = if null xs then [] else [sep $ map ppArg xs] ppT = ppWithNames ns1 ppP = ppWithNames ns1 @@ -359,12 +360,12 @@ instance PP DeclGroup where instance PP (WithNames Decl) where ppPrec _ (WithNames Decl { .. } nm) = - pp dName <+> text ":" <+> ppWithNames nm dSignature $$ - (if null dPragmas - then empty - else text "pragmas" <+> pp dName <+> sep (map pp dPragmas) - ) $$ - pp dName <+> text "=" <+> ppWithNames nm dDefinition + vcat $ + [ pp dName <+> text ":" <+> ppWithNames nm dSignature ] + ++ (if null dPragmas + then [] + else [text "pragmas" <+> pp dName <+> sep (map pp dPragmas)]) + ++ [ nest 2 (sep [pp dName <+> text "=", ppWithNames nm dDefinition]) ] instance PP (WithNames DeclDef) where ppPrec _ (WithNames DPrim _) = text "" diff --git a/src/Cryptol/TypeCheck/Error.hs b/src/Cryptol/TypeCheck/Error.hs index 5b030345..14d6f3f7 100644 --- a/src/Cryptol/TypeCheck/Error.hs +++ b/src/Cryptol/TypeCheck/Error.hs @@ -324,11 +324,11 @@ instance PP (WithNames Error) where KindMismatch mbsrc k1 k2 -> addTVarsDescsAfter names err $ nested "Incorrect type form." $ - vcat [ "Expected:" <+> cppKind k1 - , "Inferred:" <+> cppKind k2 - , kindMismatchHint k1 k2 - , maybe empty (\src -> "When checking" <+> pp src) mbsrc - ] + vcat $ + [ "Expected:" <+> cppKind k1 + , "Inferred:" <+> cppKind k2 + ] ++ kindMismatchHint k1 k2 + ++ maybe [] (\src -> ["When checking" <+> pp src]) mbsrc TooManyTypeParams extra k -> addTVarsDescsAfter names err $ @@ -355,16 +355,16 @@ instance PP (WithNames Error) where RecursiveTypeDecls ts -> addTVarsDescsAfter names err $ nested "Recursive type declarations:" - (fsep $ punctuate comma $ map nm ts) + (commaSep $ map nm ts) TypeMismatch src t1 t2 -> addTVarsDescsAfter names err $ nested "Type mismatch:" $ - vcat [ "Expected type:" <+> ppWithNames names t1 - , "Inferred type:" <+> ppWithNames names t2 - , mismatchHint t1 t2 - , "When checking" <+> pp src - ] + vcat $ + [ "Expected type:" <+> ppWithNames names t1 + , "Inferred type:" <+> ppWithNames names t2 + ] ++ mismatchHint t1 t2 + ++ ["When checking" <+> pp src] UnsolvableGoals gs -> explainUnsolvable names gs @@ -394,7 +394,7 @@ instance PP (WithNames Error) where nested ("The type" <+> ppWithNames names t <+> "is not sufficiently polymorphic.") $ vcat [ "It cannot depend on quantified variables:" <+> - sep (punctuate comma (map (ppWithNames names) xs)) + (commaSep (map (ppWithNames names) xs)) , "When checking" <+> pp src ] @@ -426,16 +426,17 @@ instance PP (WithNames Error) where $$ "See" <+> pp (srcRange x) RepeatedTypeParameter x rs -> - addTVarsDescsAfter names err $ - "Multiple definitions for type parameter `" <.> pp x <.> "`:" - $$ nest 2 (bullets (map pp rs)) + addTVarsDescsAfter names err $ nest 2 $ + "Multiple definitions for type parameter `" <.> pp x <.> "`:" + $$ bullets (map pp rs) AmbiguousSize x t -> let sizeMsg = case t of - Just t' -> "Must be at least:" <+> ppWithNames names t' - Nothing -> empty - in addTVarsDescsAfter names err ("Ambiguous numeric type:" <+> pp (tvarDesc x) $$ sizeMsg) + Just t' -> ["Must be at least:" <+> ppWithNames names t'] + Nothing -> [] + in addTVarsDescsAfter names err + (vcat (["Ambiguous numeric type:" <+> pp (tvarDesc x)] ++ sizeMsg)) BareTypeApp -> "Unexpected bare type application." $$ @@ -454,7 +455,7 @@ instance PP (WithNames Error) where where bullets xs = vcat [ "•" <+> d | d <- xs ] - nested x y = x $$ nest 2 y + nested x y = nest 2 (x $$ y) pl 1 x = text "1" <+> text x pl n x = text (show n) <+> text x <.> text "s" @@ -463,18 +464,18 @@ instance PP (WithNames Error) where kindMismatchHint k1 k2 = case (k1,k2) of - (KType,KProp) -> "Possibly due to a missing `=>`" - _ -> empty + (KType,KProp) -> [text "Possibly due to a missing `=>`"] + _ -> [] mismatchHint (TRec fs1) (TRec fs2) = - hint "Missing" missing $$ hint "Unexpected" extra + hint "Missing" missing ++ hint "Unexpected" extra where missing = displayOrder fs1 \\ displayOrder fs2 extra = displayOrder fs2 \\ displayOrder fs1 - hint _ [] = mempty - hint s [x] = text s <+> text "field" <+> pp x - hint s xs = text s <+> text "fields" <+> commaSep (map pp xs) - mismatchHint _ _ = mempty + hint _ [] = [] + hint s [x] = [text s <+> text "field" <+> pp x] + hint s xs = [text s <+> text "fields" <+> commaSep (map pp xs)] + mismatchHint _ _ = [] noUni = Set.null (Set.filter isFreeTV (fvs err)) @@ -490,18 +491,17 @@ explainUnsolvable names gs = explain g = - let useCtr = "Unsolvable constraint:" $$ - nest 2 (ppWithNames names g) + let useCtr = hang "Unsolvable constraint:" 2 (ppWithNames names g) in case tNoUser (goal g) of TCon (PC pc) ts -> let tys = [ backticks (ppWithNames names t) | t <- ts ] doc1 : _ = tys - custom msg = msg $$ - nest 2 (text "arising from" $$ - pp (goalSource g) $$ - text "at" <+> pp (goalRange g)) + custom msg = hang msg + 2 (text "arising from" $$ + pp (goalSource g) $$ + text "at" <+> pp (goalRange g)) in case pc of PEqual -> useCtr @@ -511,7 +511,7 @@ explainUnsolvable names gs = PPrime -> useCtr PHas sel -> - custom ("Type" <+> doc1 <+> "does not have field" <+> f + custom ("Type" <+> doc1 "does not have field" <+> f <+> "of type" <+> (tys !! 1)) where f = case sel of P.TupleSel n _ -> int n @@ -519,39 +519,39 @@ explainUnsolvable names gs = P.ListSel n _ -> int n PZero -> - custom ("Type" <+> doc1 <+> "does not have `zero`") + custom ("Type" <+> doc1 "does not have `zero`") PLogic -> - custom ("Type" <+> doc1 <+> "does not support logical operations.") + custom ("Type" <+> doc1 "does not support logical operations.") PRing -> - custom ("Type" <+> doc1 <+> "does not support ring operations.") + custom ("Type" <+> doc1 "does not support ring operations.") PIntegral -> - custom (doc1 <+> "is not an integral type.") + custom (doc1 "is not an integral type.") PField -> - custom ("Type" <+> doc1 <+> "does not support field operations.") + custom ("Type" <+> doc1 "does not support field operations.") PRound -> - custom ("Type" <+> doc1 <+> "does not support rounding operations.") + custom ("Type" <+> doc1 "does not support rounding operations.") PEq -> - custom ("Type" <+> doc1 <+> "does not support equality.") + custom ("Type" <+> doc1 "does not support equality.") PCmp -> - custom ("Type" <+> doc1 <+> "does not support comparisons.") + custom ("Type" <+> doc1 "does not support comparisons.") PSignedCmp -> - custom ("Type" <+> doc1 <+> "does not support signed comparisons.") + custom ("Type" <+> doc1 "does not support signed comparisons.") PLiteral -> let doc2 = tys !! 1 - in custom (doc1 <+> "is not a valid literal of type" <+> doc2) + in custom (doc1 "is not a valid literal of type" <+> doc2) PLiteralLessThan -> let doc2 = tys !! 1 - in custom ("Type" <+> doc2 <+> "does not contain all literals below" <+> (doc1 <> ".")) + in custom ("Type" <+> doc2 "does not contain all literals below" <+> (doc1 <> ".")) PFLiteral -> case ts of @@ -559,14 +559,14 @@ explainUnsolvable names gs = let frac = backticks (ppWithNamesPrec names 4 m <> "/" <> ppWithNamesPrec names 4 n) ty = tys !! 3 - in custom (frac <+> "is not a valid literal of type" <+> ty) + in custom (frac "is not a valid literal of type" ty) PValidFloat -> case ts of - ~[e,p] -> - custom ("Unsupported floating point parameters:" $$ - nest 2 ("exponent =" <+> ppWithNames names e $$ - "precision =" <+> ppWithNames names p)) + ~[e,p] -> + custom (hang "Unsupported floating point parameters:" + 2 ("exponent =" <+> ppWithNames names e $$ + "precision =" <+> ppWithNames names p)) PAnd -> useCtr diff --git a/src/Cryptol/TypeCheck/Infer.hs b/src/Cryptol/TypeCheck/Infer.hs index 95e201c6..f672a7a3 100644 --- a/src/Cryptol/TypeCheck/Infer.hs +++ b/src/Cryptol/TypeCheck/Infer.hs @@ -58,7 +58,7 @@ import Data.List(partition) import Data.Ratio(numerator,denominator) import Data.Traversable(forM) import Data.Function(on) -import Control.Monad(zipWithM,unless,foldM,forM_) +import Control.Monad(zipWithM,unless,foldM,forM_,mplus) @@ -164,6 +164,8 @@ appTys expr ts tGoal = P.ESel {} -> mono P.EList {} -> mono P.EFromTo {} -> mono + P.EFromToBy {} -> mono + P.EFromToDownBy {} -> mono P.EFromToLessThan {} -> mono P.EInfFrom {} -> mono P.EComp {} -> mono @@ -245,13 +247,14 @@ checkE expr tGoal = P.ETuple es -> do etys <- expectTuple (length es) tGoal - let mkTGoal n t = WithSource t (TypeOfTupleField n) - es' <- zipWithM checkE es (zipWith mkTGoal [1..] etys) + let mkTGoal n t e = WithSource t (TypeOfTupleField n) (getLoc e) + es' <- zipWithM checkE es (zipWith3 mkTGoal [1..] etys es) return (ETuple es') P.ERecord fs -> do es <- expectRec fs tGoal - let checkField f (e,t) = checkE e (WithSource t (TypeOfRecordField f)) + let checkField f (e,t) = + checkE e (WithSource t (TypeOfRecordField f) (getLoc e)) es' <- traverseRecordMap checkField es return (ERec es') @@ -260,22 +263,74 @@ checkE expr tGoal = P.ESel e l -> do let src = selSrc l t <- newType src KType - e' <- checkE e (WithSource t src) + e' <- checkE e (WithSource t src (getLoc expr)) f <- newHasGoal l t (twsType tGoal) return (hasDoSelect f e') P.EList [] -> do (len,a) <- expectSeq tGoal - expectFin 0 (WithSource len LenOfSeq) + expectFin 0 (WithSource len LenOfSeq (getLoc expr)) return (EList [] a) P.EList es -> do (len,a) <- expectSeq tGoal - expectFin (length es) (WithSource len LenOfSeq) - let checkElem e = checkE e (WithSource a TypeOfSeqElement) + expectFin (length es) (WithSource len LenOfSeq (getLoc expr)) + let checkElem e = checkE e (WithSource a TypeOfSeqElement (getLoc e)) es' <- mapM checkElem es return (EList es' a) + P.EFromToBy isStrict t1 t2 t3 mety + | isStrict -> + do l <- curRange + let fs = [("first",t1),("bound",t2),("stride",t3)] ++ + case mety of + Just ety -> [("a",ety)] + Nothing -> [] + prim <- mkPrim "fromToByLessThan" + let e' = P.EAppT prim + [ P.NamedInst P.Named{ name = Located l (packIdent x), value = y } + | (x,y) <- fs + ] + checkE e' tGoal + | otherwise -> + do l <- curRange + let fs = [("first",t1),("last",t2),("stride",t3)] ++ + case mety of + Just ety -> [("a",ety)] + Nothing -> [] + prim <- mkPrim "fromToBy" + let e' = P.EAppT prim + [ P.NamedInst P.Named{ name = Located l (packIdent x), value = y } + | (x,y) <- fs + ] + checkE e' tGoal + + P.EFromToDownBy isStrict t1 t2 t3 mety + | isStrict -> + do l <- curRange + let fs = [("first",t1),("bound",t2),("stride",t3)] ++ + case mety of + Just ety -> [("a",ety)] + Nothing -> [] + prim <- mkPrim "fromToDownByGreaterThan" + let e' = P.EAppT prim + [ P.NamedInst P.Named{ name = Located l (packIdent x), value = y } + | (x,y) <- fs + ] + checkE e' tGoal + | otherwise -> + do l <- curRange + let fs = [("first",t1),("last",t2),("stride",t3)] ++ + case mety of + Just ety -> [("a",ety)] + Nothing -> [] + prim <- mkPrim "fromToDownBy" + let e' = P.EAppT prim + [ P.NamedInst P.Named{ name = Located l (packIdent x), value = y } + | (x,y) <- fs + ] + checkE e' tGoal + P.EFromToLessThan t1 t2 mety -> do l <- curRange let fs0 = @@ -324,11 +379,12 @@ checkE expr tGoal = (len,a) <- expectSeq tGoal inferred <- smallest ts - ctrs <- unify (WithSource len LenOfSeq) inferred + ctrs <- unify (WithSource len LenOfSeq (getLoc expr)) inferred newGoals CtComprehension ctrs ds <- combineMaps dss - e' <- withMonoTypes ds (checkE e (WithSource a TypeOfSeqElement)) + e' <- withMonoTypes ds (checkE e + (WithSource a TypeOfSeqElement (getLoc e))) return (EComp len a e' mss') where -- the renamer should have made these checks already? @@ -353,12 +409,13 @@ checkE expr tGoal = P.EApp e1 e2 -> do let argSrc = TypeOfArg noArgDescr t1 <- newType argSrc KType - e1' <- checkE e1 (WithSource (tFun t1 (twsType tGoal)) FunApp) - e2' <- checkE e2 (WithSource t1 argSrc) + e1' <- checkE e1 + (WithSource (tFun t1 (twsType tGoal)) FunApp (getLoc e1)) + e2' <- checkE e2 (WithSource t1 argSrc (getLoc e2)) return (EApp e1' e2') P.EIf e1 e2 e3 -> - do e1' <- checkE e1 (WithSource tBit TypeOfIfCondExpr) + do e1' <- checkE e1 (WithSource tBit TypeOfIfCondExpr (getLoc e1)) e2' <- checkE e2 tGoal e3' <- checkE e3 tGoal return (EIf e1' e2' e3') @@ -369,7 +426,7 @@ checkE expr tGoal = P.ETyped e t -> do tSig <- checkTypeOfKind t KType - e' <- checkE e (WithSource tSig TypeFromUserAnnotation) + e' <- checkE e (WithSource tSig TypeFromUserAnnotation (getLoc expr)) checkHasType tSig tGoal return e' @@ -411,28 +468,28 @@ checkRecUpd mb fs tGoal = Just e -> do e1 <- checkE e tGoal - foldM doUpd e1 fs + fst <$> foldM doUpd (e1, getLoc e) fs where - doUpd e (P.UpdField how sels v) = + doUpd (e,eloc) (P.UpdField how sels v) = case sels of [l] -> case how of P.UpdSet -> do let src = selSrc s ft <- newType src KType - v1 <- checkE v (WithSource ft src) + v1 <- checkE v (WithSource ft src eloc) d <- newHasGoal s (twsType tGoal) ft - pure (hasDoSet d e v1) + pure (hasDoSet d e v1, eloc `rCombMaybe` getLoc v) P.UpdFun -> do let src = selSrc s ft <- newType src KType - v1 <- checkE v (WithSource (tFun ft ft) src) + v1 <- checkE v (WithSource (tFun ft ft) src eloc) -- XXX: ^ may be used a different src? d <- newHasGoal s (twsType tGoal) ft tmp <- newParamName NSValue (packIdent "rf") let e' = EVar tmp - pure $ hasDoSet d e' (EApp v1 (hasDoSelect d e')) + pure ( hasDoSet d e' (EApp v1 (hasDoSelect d e')) `EWhere` [ NonRecursive Decl { dName = tmp @@ -443,6 +500,7 @@ checkRecUpd mb fs tGoal = , dFixity = Nothing , dDoc = Nothing } ] + , eloc `rCombMaybe` getLoc v ) where s = thing l _ -> panic "checkRecUpd/doUpd" [ "Expected exactly 1 field label" @@ -451,11 +509,11 @@ checkRecUpd mb fs tGoal = expectSeq :: TypeWithSource -> InferM (Type,Type) -expectSeq tGoal@(WithSource ty src) = +expectSeq tGoal@(WithSource ty src rng) = case ty of TUser _ _ ty' -> - expectSeq (WithSource ty' src) + expectSeq (WithSource ty' src rng) TCon (TC TCSeq) [a,b] -> return (a,b) @@ -467,7 +525,7 @@ expectSeq tGoal@(WithSource ty src) = _ -> do tys@(a,b) <- genTys - recordError (TypeMismatch src ty (tSeq a b)) + recordErrorLoc rng (TypeMismatch src ty (tSeq a b)) return tys where genTys = @@ -477,11 +535,11 @@ expectSeq tGoal@(WithSource ty src) = expectTuple :: Int -> TypeWithSource -> InferM [Type] -expectTuple n tGoal@(WithSource ty src) = +expectTuple n tGoal@(WithSource ty src rng) = case ty of TUser _ _ ty' -> - expectTuple n (WithSource ty' src) + expectTuple n (WithSource ty' src rng) TCon (TC (TCTuple n')) tys | n == n' -> return tys @@ -493,7 +551,7 @@ expectTuple n tGoal@(WithSource ty src) = _ -> do tys <- genTys - recordError (TypeMismatch src ty (tTuple tys)) + recordErrorLoc rng (TypeMismatch src ty (tTuple tys)) return tys where @@ -504,11 +562,11 @@ expectRec :: RecordMap Ident (Range, a) -> TypeWithSource -> InferM (RecordMap Ident (a, Type)) -expectRec fs tGoal@(WithSource ty src) = +expectRec fs tGoal@(WithSource ty src rng) = case ty of TUser _ _ ty' -> - expectRec fs (WithSource ty' src) + expectRec fs (WithSource ty' src rng) TRec ls | Right r <- zipRecords (\_ (_rng,v) t -> (v,t)) fs ls -> pure r @@ -523,16 +581,16 @@ expectRec fs tGoal@(WithSource ty src) = case ty of TVar TVFree{} -> do ps <- unify tGoal (TRec tys) newGoals CtExactType ps - _ -> recordError (TypeMismatch src ty (TRec tys)) + _ -> recordErrorLoc rng (TypeMismatch src ty (TRec tys)) return res expectFin :: Int -> TypeWithSource -> InferM () -expectFin n tGoal@(WithSource ty src) = +expectFin n tGoal@(WithSource ty src rng) = case ty of TUser _ _ ty' -> - expectFin n (WithSource ty' src) + expectFin n (WithSource ty' src rng) TCon (TC (TCNum n')) [] | toInteger n == n' -> return () @@ -540,7 +598,7 @@ expectFin n tGoal@(WithSource ty src) = _ -> newGoals CtExactType =<< unify tGoal (tNum n) expectFun :: Maybe Name -> Int -> TypeWithSource -> InferM ([Type],Type) -expectFun mbN n (WithSource ty0 src) = go [] n ty0 +expectFun mbN n (WithSource ty0 src rng) = go [] n ty0 where go tys arity ty @@ -558,9 +616,10 @@ expectFun mbN n (WithSource ty0 src) = go [] n ty0 res <- newType TypeOfRes KType case ty of TVar TVFree{} -> - do ps <- unify (WithSource ty src) (foldr tFun res args) + do ps <- unify (WithSource ty src rng) (foldr tFun res args) newGoals CtExactType ps - _ -> recordError (TypeMismatch src ty (foldr tFun res args)) + _ -> recordErrorLoc rng + (TypeMismatch src ty (foldr tFun res args)) return (reverse tys ++ args, res) | otherwise = @@ -587,9 +646,11 @@ checkFun (P.FunDesc fun offset) ps e tGoal = do let descs = [ TypeOfArg (ArgDescr fun (Just n)) | n <- [ 1 + offset .. ] ] (tys,tRes) <- expectFun fun (length ps) tGoal - largs <- sequence (zipWith checkP ps (zipWith WithSource tys descs)) + let srcs = zipWith3 WithSource tys descs (map getLoc ps) + largs <- sequence (zipWith checkP ps srcs) let ds = Map.fromList [ (thing x, x { thing = t }) | (x,t) <- zip largs tys ] - e1 <- withMonoTypes ds (checkE e (WithSource tRes TypeOfRes)) + e1 <- withMonoTypes ds + (checkE e (WithSource tRes TypeOfRes (twsRange tGoal))) let args = [ (thing x, t) | (x,t) <- zip largs tys ] return (foldr (\(x,t) b -> EAbs x t b) e1 args) @@ -604,11 +665,12 @@ smallest ts = do a <- newType LenOfSeq KNum return a checkP :: P.Pattern Name -> TypeWithSource -> InferM (Located Name) -checkP p tGoal@(WithSource _ src) = +checkP p tGoal@(WithSource _ src rng0) = do (x, t) <- inferP p ps <- unify tGoal (thing t) - let rng = fromMaybe emptyRange (getLoc p) - let mkErr = recordError . UnsolvedGoals . (:[]) + let rngMb = getLoc p `mplus` rng0 + rng = fromMaybe emptyRange rngMb + let mkErr = recordErrorLoc rngMb . UnsolvedGoals . (:[]) . Goal (CtPattern src) rng mapM_ mkErr ps return (Located (srcRange t) x) @@ -625,7 +687,7 @@ inferP pat = P.PTyped p t -> do tSig <- checkTypeOfKind t KType - ln <- checkP p (WithSource tSig TypeFromUserAnnotation) + ln <- checkP p (WithSource tSig TypeFromUserAnnotation (getLoc t)) return (thing ln, ln { thing = tSig }) _ -> tcPanic "inferP" [ "Unexpected pattern:", show pat ] @@ -637,7 +699,8 @@ inferMatch :: P.Match Name -> InferM (Match, Name, Located Type, Type) inferMatch (P.Match p e) = do (x,t) <- inferP p n <- newType LenOfCompGen KNum - e' <- checkE e (WithSource (tSeq n (thing t)) GeneratorOfListComp) + e' <- checkE e (WithSource (tSeq n (thing t)) GeneratorOfListComp + (getLoc e)) return (From x n (thing t) e', x, t, n) inferMatch (P.MatchLet b) @@ -889,7 +952,7 @@ checkMonoB b t = P.DExpr e -> do let nm = thing (P.bName b) - let tGoal = WithSource t (DefinitionOf nm) + let tGoal = WithSource t (DefinitionOf nm) (getLoc b) e1 <- checkFun (P.FunDesc (Just nm) 0) (P.bParams b) e tGoal let f = thing (P.bName b) return Decl { dName = f @@ -921,7 +984,7 @@ checkSigB b (Forall as asmps0 t0, validSchema) = case thing (P.bDef b) of withTParams as $ do (e1,cs0) <- collectGoals $ do let nm = thing (P.bName b) - tGoal = WithSource t0 (DefinitionOf nm) + tGoal = WithSource t0 (DefinitionOf nm) (getLoc b) e1 <- checkFun (P.FunDesc (Just nm) 0) (P.bParams b) e0 tGoal addGoals validSchema () <- simplifyAllConstraints -- XXX: using `asmps` also? @@ -973,7 +1036,7 @@ checkLocalDecls ds0 k = do newLocalScope forM_ ds0 \d -> checkDecl False d Nothing a <- k - ds <- endLocalScope + (ds,_tySyns) <- endLocalScope pure (a,ds) diff --git a/src/Cryptol/TypeCheck/InferTypes.hs b/src/Cryptol/TypeCheck/InferTypes.hs index 9f8546c3..217a9c0d 100644 --- a/src/Cryptol/TypeCheck/InferTypes.hs +++ b/src/Cryptol/TypeCheck/InferTypes.hs @@ -315,24 +315,25 @@ cppKind ki = addTVarsDescsAfter :: FVS t => NameMap -> t -> Doc -> Doc addTVarsDescsAfter nm t d | Set.null vs = d +-- TODO? use `hang` here instead to indent things after "where" | otherwise = d $$ text "where" $$ vcat (map desc (Set.toList vs)) where vs = fvs t desc v = ppWithNames nm v <+> text "is" <+> pp (tvInfo v) addTVarsDescsBefore :: FVS t => NameMap -> t -> Doc -> Doc -addTVarsDescsBefore nm t d = frontMsg $$ d $$ backMsg +addTVarsDescsBefore nm t d = vcat (frontMsg ++ [d] ++ backMsg) where (vs1,vs2) = Set.partition isFreeTV (fvs t) - frontMsg | null vs1 = empty - | otherwise = "Failed to infer the following types:" - $$ nest 2 (vcat (map desc1 (Set.toList vs1))) + frontMsg | null vs1 = [] + | otherwise = [hang "Failed to infer the following types:" + 2 (vcat (map desc1 (Set.toList vs1)))] desc1 v = "•" <+> ppWithNames nm v <.> comma <+> pp (tvInfo v) - backMsg | null vs2 = empty - | otherwise = "where" - $$ nest 2 (vcat (map desc2 (Set.toList vs2))) + backMsg | null vs2 = [] + | otherwise = [hang "where" + 2 (vcat (map desc2 (Set.toList vs2)))] desc2 v = ppWithNames nm v <+> text "is" <+> pp (tvInfo v) @@ -363,7 +364,7 @@ ppUse expr = | prim == "infFromThen" -> "infinite enumeration (with step)" | prim == "fromTo" -> "finite enumeration" | prim == "fromThenTo" -> "finite enumeration" - _ -> "expression" <+> pp expr + _ -> "expression" <+> pp expr where isPrelPrim x = do PrimIdent p i <- asPrim x guard (p == preludeName) @@ -371,19 +372,21 @@ ppUse expr = instance PP (WithNames Goal) where ppPrec _ (WithNames g names) = - (ppWithNames names (goal g)) $$ - nest 2 (text "arising from" $$ - pp (goalSource g) $$ - text "at" <+> pp (goalRange g)) + hang (ppWithNames names (goal g)) + 2 (text "arising from" $$ + pp (goalSource g) $$ + text "at" <+> pp (goalRange g)) instance PP (WithNames DelayedCt) where ppPrec _ (WithNames d names) = - sig $$ "we need to show that" $$ - nest 2 (vcat [ vars, asmps, "the following constraints hold:" - , nest 2 $ vcat - $ bullets - $ map (ppWithNames ns1) - $ dctGoals d ]) + sig $$ + hang "we need to show that" + 2 (vcat ( vars ++ asmps ++ + [ hang "the following constraints hold:" + 2 (vcat + $ bullets + $ map (ppWithNames ns1) + $ dctGoals d )])) where bullets xs = [ "•" <+> x | x <- xs ] @@ -394,12 +397,11 @@ instance PP (WithNames DelayedCt) where name = dctSource d vars = case dctForall d of - [] -> empty - xs -> "for any type" <+> - fsep (punctuate comma (map (ppWithNames ns1 ) xs)) + [] -> [] + xs -> ["for any type" <+> commaSep (map (ppWithNames ns1) xs)] asmps = case dctAsmps d of - [] -> empty - xs -> "assuming" $$ - nest 2 (vcat (bullets (map (ppWithNames ns1) xs))) + [] -> [] + xs -> [hang "assuming" + 2 (vcat (bullets (map (ppWithNames ns1) xs)))] ns1 = addTNames (dctForall d) names diff --git a/src/Cryptol/TypeCheck/Instantiate.hs b/src/Cryptol/TypeCheck/Instantiate.hs index bd1b11d2..0a8b17bf 100644 --- a/src/Cryptol/TypeCheck/Instantiate.hs +++ b/src/Cryptol/TypeCheck/Instantiate.hs @@ -205,5 +205,6 @@ doInst su' e ps t = | Set.notMember tp bounds = return [] | otherwise = let a = tpVar tp src = tvarDesc (tvInfo a) - in unify (WithSource (TVar a) src) ty + rng = Just (tvarSource (tvInfo a)) + in unify (WithSource (TVar a) src rng) ty diff --git a/src/Cryptol/TypeCheck/Monad.hs b/src/Cryptol/TypeCheck/Monad.hs index af6127a3..16d7e4a0 100644 --- a/src/Cryptol/TypeCheck/Monad.hs +++ b/src/Cryptol/TypeCheck/Monad.hs @@ -331,12 +331,21 @@ curRange = IM $ asks iRange -- | Report an error. recordError :: Error -> InferM () -recordError e = - do r <- case e of - AmbiguousSize d _ -> return (tvarSource d) - _ -> curRange +recordError = recordErrorLoc Nothing + +-- | Report an error. +recordErrorLoc :: Maybe Range -> Error -> InferM () +recordErrorLoc rng e = + do r <- case rng of + Just r -> pure r + Nothing -> case e of + AmbiguousSize d _ -> return (tvarSource d) + _ -> curRange IM $ sets_ $ \s -> s { iErrors = (r,e) : iErrors s } + + + recordWarning :: Warning -> InferM () recordWarning w = unless ignore $ @@ -549,7 +558,7 @@ newType src k = TVar `fmap` newTVar src k -- | Record that the two types should be syntactically equal. unify :: TypeWithSource -> Type -> InferM [Prop] -unify (WithSource t1 src) t2 = +unify (WithSource t1 src rng) t2 = do t1' <- applySubst t1 t2' <- applySubst t2 let ((su1, ps), errs) = runResult (mgu t1' t2') @@ -565,7 +574,7 @@ unify (WithSource t1 src) t2 = UniNonPoly x t -> NotForAll src x t case errs of [] -> return ps - _ -> do mapM_ (recordError . toError) errs + _ -> do mapM_ (recordErrorLoc rng . toError) errs return [] -- | Apply the accumulated substitution to something with free type variables. @@ -804,13 +813,12 @@ updScope f = IM $ sets_ \rw -> rw { iScope = upd (iScope rw) } [] -> panic "updTopScope" [ "No top scope" ] s : more -> f s : more -endLocalScope :: InferM [DeclGroup] +endLocalScope :: InferM ([DeclGroup], Map Name TySyn) endLocalScope = IM $ sets \rw -> case iScope rw of x : xs | LocalScope <- mName x -> - (reverse (mDecls x), rw { iScope = xs }) - -- This ignores local type synonyms... Where should we put them? + ( (reverse (mDecls x), mTySyns x), rw { iScope = xs }) _ -> panic "endLocalScope" ["Missing local scope"] diff --git a/src/Cryptol/TypeCheck/Parseable.hs b/src/Cryptol/TypeCheck/Parseable.hs index 333aea41..86f72f06 100644 --- a/src/Cryptol/TypeCheck/Parseable.hs +++ b/src/Cryptol/TypeCheck/Parseable.hs @@ -17,18 +17,30 @@ module Cryptol.TypeCheck.Parseable , ShowParseable(..) ) where +import Data.Void +import Prettyprinter + import Cryptol.TypeCheck.AST import Cryptol.Utils.Ident (Ident,unpackIdent) import Cryptol.Utils.RecordMap (canonicalFields) import Cryptol.Parser.AST ( Located(..)) import Cryptol.ModuleSystem.Name -import Text.PrettyPrint hiding ((<>)) -import qualified Text.PrettyPrint as PP ((<>)) + + +infixl 5 $$ +($$) :: Doc a -> Doc a -> Doc a +($$) x y = sep [x, y] + +text :: String -> Doc a +text = pretty + +int :: Int -> Doc a +int = pretty -- ShowParseable prints out a cryptol program in a way that it's parseable by Coq (and likely other things) -- Used mainly for reasoning about the semantics of cryptol programs in Coq (https://github.com/GaloisInc/cryptol-semantics) class ShowParseable t where - showParseable :: t -> Doc + showParseable :: t -> Doc Void instance ShowParseable Expr where showParseable (ELocated _ e) = showParseable e -- TODO? emit range information @@ -53,7 +65,7 @@ instance ShowParseable Expr where showParseable (EProofApp e) = showParseable e --"(EProofApp " ++ showParseable e ++ ")" instance (ShowParseable a, ShowParseable b) => ShowParseable (a,b) where - showParseable (x,y) = parens (showParseable x PP.<> comma PP.<> showParseable y) + showParseable (x,y) = parens (showParseable x <> comma <> showParseable y) instance ShowParseable Int where showParseable i = int i @@ -105,11 +117,11 @@ instance (ShowParseable a) => ShowParseable (Located a) where showParseable l = showParseable (thing l) instance ShowParseable TParam where - showParseable tp = parens (text (show (tpUnique tp)) PP.<> comma PP.<> maybeNameDoc (tpName tp)) + showParseable tp = parens (text (show (tpUnique tp)) <> comma <> maybeNameDoc (tpName tp)) -maybeNameDoc :: Maybe Name -> Doc -maybeNameDoc Nothing = doubleQuotes empty +maybeNameDoc :: Maybe Name -> Doc Void +maybeNameDoc Nothing = dquotes mempty maybeNameDoc (Just n) = showParseable (nameIdent n) instance ShowParseable Name where - showParseable n = parens (text (show (nameUnique n)) PP.<> comma PP.<> showParseable (nameIdent n)) + showParseable n = parens (text (show (nameUnique n)) <> comma <> showParseable (nameIdent n)) diff --git a/src/Cryptol/TypeCheck/SimpType.hs b/src/Cryptol/TypeCheck/SimpType.hs index 96455091..c88bebf7 100644 --- a/src/Cryptol/TypeCheck/SimpType.hs +++ b/src/Cryptol/TypeCheck/SimpType.hs @@ -182,7 +182,6 @@ tMod x y tCeilDiv :: Type -> Type -> Type tCeilDiv x y | Just t <- tOp TCCeilDiv (op2 nCeilDiv) [x,y] = t - | tIsInf x = bad | tIsInf y = bad | Just 0 <- tIsNum y = bad | otherwise = tf2 TCCeilDiv x y @@ -191,7 +190,6 @@ tCeilDiv x y tCeilMod :: Type -> Type -> Type tCeilMod x y | Just t <- tOp TCCeilMod (op2 nCeilMod) [x,y] = t - | tIsInf x = bad | tIsInf y = bad | Just 0 <- tIsNum x = bad | otherwise = tf2 TCCeilMod x y @@ -264,6 +262,12 @@ tMax x y maxK (Nat 0) t = t maxK (Nat k) t + -- max 1 t ~> t, if t = a ^ b && a >= 1 + | k == 1 + , TCon (TF TCExp) [a,_] <- t' + , Just base <- tIsNat' a + , base >= Nat 1 = t + | TCon (TF TCAdd) [a,b] <- t' , Just n <- tIsNum a = if k <= n then t @@ -285,6 +289,13 @@ tMax x y tWidth :: Type -> Type tWidth x | Just t <- tOp TCWidth (total (op1 nWidth)) [x] = t + + -- width (2^n - 1) = n + | TCon (TF TCSub) [a,b] <- tNoUser x + , Just 1 <- tIsNum b + , TCon (TF TCExp) [p,q] <- tNoUser a + , Just 2 <- tIsNum p = q + | otherwise = tf1 TCWidth x tLenFromThenTo :: Type -> Type -> Type -> Type diff --git a/src/Cryptol/TypeCheck/SimpleSolver.hs b/src/Cryptol/TypeCheck/SimpleSolver.hs index fdbbc6c1..4f60e297 100644 --- a/src/Cryptol/TypeCheck/SimpleSolver.hs +++ b/src/Cryptol/TypeCheck/SimpleSolver.hs @@ -30,8 +30,7 @@ simplify ctxt p = SolvedIf ps -> dbg msg $ pAnd (map (simplify ctxt) ps) where msg = case ps of [] -> text "solved:" <+> pp p - _ -> pp p <+> text "~~~>" <+> - vcat (punctuate comma (map pp ps)) + _ -> pp p <+> text "~~~>" <+> commaSep (map pp ps) where dbg msg x diff --git a/src/Cryptol/TypeCheck/Solver/InfNat.hs b/src/Cryptol/TypeCheck/Solver/InfNat.hs index 893ab1dd..9072fbd4 100644 --- a/src/Cryptol/TypeCheck/Solver/InfNat.hs +++ b/src/Cryptol/TypeCheck/Solver/InfNat.hs @@ -122,23 +122,22 @@ nMod (Nat x) (Nat y) = Just (Nat (mod x y)) nMod (Nat x) Inf = Just (Nat x) -- inf * 0 + x = 0 + x -- | @nCeilDiv msgLen blockSize@ computes the least @n@ such that --- @msgLen <= blockSize * n@. It is undefined when @blockSize = 0@. --- It is also undefined when either input is infinite; perhaps this --- could be relaxed later. +-- @msgLen <= blockSize * n@. It is undefined when @blockSize = 0@, +-- or when @blockSize = inf@. @inf@ divided by any positive +-- finite value is @inf@. nCeilDiv :: Nat' -> Nat' -> Maybe Nat' +nCeilDiv _ Inf = Nothing nCeilDiv _ (Nat 0) = Nothing -nCeilDiv Inf _ = Nothing -nCeilDiv (Nat _) Inf = Nothing +nCeilDiv Inf (Nat _) = Just Inf nCeilDiv (Nat x) (Nat y) = Just (Nat (- div (- x) y)) -- | @nCeilMod msgLen blockSize@ computes the least @k@ such that --- @blockSize@ divides @msgLen + k@. It is undefined when @blockSize = 0@. --- It is also undefined when either input is infinite; perhaps this --- could be relaxed later. +-- @blockSize@ divides @msgLen + k@. It is undefined when @blockSize = 0@ +-- or @blockSize = inf@. @inf@ modulus any positive finite value is @0@. nCeilMod :: Nat' -> Nat' -> Maybe Nat' +nCeilMod _ Inf = Nothing nCeilMod _ (Nat 0) = Nothing -nCeilMod Inf _ = Nothing -nCeilMod (Nat _) Inf = Nothing +nCeilMod Inf (Nat _) = Just (Nat 0) nCeilMod (Nat x) (Nat y) = Just (Nat (mod (- x) y)) -- | Rounds up. diff --git a/src/Cryptol/TypeCheck/Solver/Numeric/Fin.hs b/src/Cryptol/TypeCheck/Solver/Numeric/Fin.hs index 4826bdcb..0355dbc8 100644 --- a/src/Cryptol/TypeCheck/Solver/Numeric/Fin.hs +++ b/src/Cryptol/TypeCheck/Solver/Numeric/Fin.hs @@ -56,7 +56,7 @@ cryIsFinType ctxt ty = i2 = typeInterval varInfo t2 - (TCDiv, [t1,_]) -> SolvedIf [ pFin t1 ] + (TCDiv, [_,_]) -> SolvedIf [] (TCMod, [_,_]) -> SolvedIf [] -- fin (x ^ y) @@ -85,7 +85,7 @@ cryIsFinType ctxt ty = (TCMax, [t1,t2]) -> SolvedIf [ pFin t1, pFin t2 ] (TCWidth, [t1]) -> SolvedIf [ pFin t1 ] - (TCCeilDiv, [_,_]) -> SolvedIf [] + (TCCeilDiv, [t1,_]) -> SolvedIf [ pFin t1 ] (TCCeilMod, [_,_]) -> SolvedIf [] (TCLenFromThenTo,[_,_,_]) -> SolvedIf [] diff --git a/src/Cryptol/TypeCheck/Solver/SMT.hs b/src/Cryptol/TypeCheck/Solver/SMT.hs index c2fae236..8da61e34 100644 --- a/src/Cryptol/TypeCheck/Solver/SMT.hs +++ b/src/Cryptol/TypeCheck/Solver/SMT.hs @@ -15,10 +15,12 @@ module Cryptol.TypeCheck.Solver.SMT ( -- * Setup Solver + , SolverConfig , withSolver , startSolver , stopSolver , isNumeric + , resetSolver -- * Debugging , debugBlock @@ -53,7 +55,7 @@ import Cryptol.TypeCheck.Solver.InfNat(Nat'(..)) import Cryptol.TypeCheck.TypePat hiding ((~>),(~~>)) import Cryptol.TypeCheck.Subst(Subst) import Cryptol.Utils.Panic -import Cryptol.Utils.PP -- ( Doc ) +import Cryptol.Utils.PP ( Doc, pp ) @@ -67,19 +69,22 @@ data Solver = Solver -- ^ For debugging } +setupSolver :: Solver -> SolverConfig -> IO () +setupSolver s cfg = do + _ <- SMT.setOptionMaybe (solver s) ":global-decls" "false" + loadTcPrelude s (solverPreludePath cfg) -- | Start a fresh solver instance -startSolver :: SolverConfig -> IO Solver -startSolver SolverConfig { .. } = - do logger <- if solverVerbose > 0 then SMT.newLogger 0 +startSolver :: IO () -> SolverConfig -> IO Solver +startSolver onExit sCfg = + do logger <- if (solverVerbose sCfg) > 0 then SMT.newLogger 0 else return quietLogger - let smtDbg = if solverVerbose > 1 then Just logger else Nothing - solver <- SMT.newSolver solverPath solverArgs smtDbg - _ <- SMT.setOptionMaybe solver ":global-decls" "false" - -- SMT.setLogic solver "QF_LIA" - let sol = Solver { .. } - loadTcPrelude sol solverPreludePath + let smtDbg = if (solverVerbose sCfg) > 1 then Just logger else Nothing + solver <- SMT.newSolverNotify + (solverPath sCfg) (solverArgs sCfg) smtDbg (Just (const onExit)) + let sol = Solver solver logger + setupSolver sol sCfg return sol where @@ -94,9 +99,14 @@ startSolver SolverConfig { .. } = stopSolver :: Solver -> IO () stopSolver s = void $ SMT.stop (solver s) +resetSolver :: Solver -> SolverConfig -> IO () +resetSolver s sCfg = do + _ <- SMT.simpleCommand (solver s) ["reset"] + setupSolver s sCfg + -- | Execute a computation with a fresh solver instance. -withSolver :: SolverConfig -> (Solver -> IO a) -> IO a -withSolver cfg = bracket (startSolver cfg) stopSolver +withSolver :: IO () -> SolverConfig -> (Solver -> IO a) -> IO a +withSolver onExit cfg = bracket (startSolver onExit cfg) stopSolver -- | Load the definitions used for type checking. loadTcPrelude :: Solver -> [FilePath] {- ^ Search in this paths -} -> IO () diff --git a/src/Cryptol/TypeCheck/Solver/Selector.hs b/src/Cryptol/TypeCheck/Solver/Selector.hs index 7b9492e9..f58f1507 100644 --- a/src/Cryptol/TypeCheck/Solver/Selector.hs +++ b/src/Cryptol/TypeCheck/Solver/Selector.hs @@ -8,6 +8,7 @@ {-# LANGUAGE PatternGuards, Safe #-} module Cryptol.TypeCheck.Solver.Selector (tryHasGoal) where +import Cryptol.Parser.Position(Range) import Cryptol.TypeCheck.AST import Cryptol.TypeCheck.InferTypes import Cryptol.TypeCheck.Monad( InferM, unify, newGoals @@ -41,8 +42,8 @@ listType n = return (tSeq (tNum n) elems) -improveSelector :: Selector -> Type -> InferM Bool -improveSelector sel outerT = +improveSelector :: Maybe Range -> Selector -> Type -> InferM Bool +improveSelector rng sel outerT = case sel of RecordSel _ mb -> cvt recordType mb TupleSel _ mb -> cvt tupleType mb @@ -50,7 +51,7 @@ improveSelector sel outerT = where cvt _ Nothing = return False cvt f (Just a) = do ty <- f a - ps <- unify (WithSource outerT (selSrc sel)) ty + ps <- unify (WithSource outerT (selSrc sel) rng) ty newGoals CtExactType ps newT <- applySubst outerT return (newT /= outerT) @@ -117,13 +118,15 @@ solveSelector sel outerT = tryHasGoal :: HasGoal -> InferM (Bool, Bool) -- ^ changes, solved tryHasGoal has | TCon (PC (PHas sel)) [ th, ft ] <- goal (hasGoal has) = - do imped <- improveSelector sel th + do let rng = Just (goalRange (hasGoal has)) + imped <- improveSelector rng sel th outerT <- tNoUser `fmap` applySubst th mbInnerT <- solveSelector sel outerT case mbInnerT of Nothing -> return (imped, False) Just innerT -> - do newGoals CtExactType =<< unify (WithSource innerT (selSrc sel)) ft + do newGoals CtExactType =<< + unify (WithSource innerT (selSrc sel) rng) ft oT <- applySubst outerT iT <- applySubst innerT sln <- mkSelSln sel oT iT diff --git a/src/Cryptol/TypeCheck/Subst.hs b/src/Cryptol/TypeCheck/Subst.hs index b3618bdd..474c537a 100644 --- a/src/Cryptol/TypeCheck/Subst.hs +++ b/src/Cryptol/TypeCheck/Subst.hs @@ -336,6 +336,14 @@ apSubstTypeMapKeys su = go (\_ x -> x) id (cons k) } +instance TVars a => TVars (Map.Map k a) where + -- NB, strict map + apSubst su m = Map.map (apSubst su) m + +instance TVars TySyn where + apSubst su (TySyn nm params props t doc) = + (\props' t' -> TySyn nm params props' t' doc) + !$ apSubst su props !$ apSubst su t {- | This instance does not need to worry about bound variable capture, because we rely on the 'Subst' datatype invariant to ensure diff --git a/src/Cryptol/TypeCheck/Type.hs b/src/Cryptol/TypeCheck/Type.hs index 6cd39654..754d88dd 100644 --- a/src/Cryptol/TypeCheck/Type.hs +++ b/src/Cryptol/TypeCheck/Type.hs @@ -231,6 +231,7 @@ tvSourceName tvs = data TypeWithSource = WithSource { twsType :: Type , twsSource :: TypeSource + , twsRange :: !(Maybe Range) } @@ -930,17 +931,17 @@ instance PP Schema where instance PP (WithNames Schema) where ppPrec _ (WithNames s ns) | null (sVars s) && null (sProps s) = body - | otherwise = hang (vars <+> props) 2 body + | otherwise = nest 2 (sep (vars ++ props ++ [body])) where body = ppWithNames ns1 (sType s) vars = case sVars s of - [] -> empty - vs -> braces $ commaSep $ map (ppWithNames ns1) vs + [] -> [] + vs -> [nest 1 (braces (commaSepFill (map (ppWithNames ns1) vs)))] props = case sProps s of - [] -> empty - ps -> parens (commaSep (map (ppWithNames ns1) ps)) <+> text "=>" + [] -> [] + ps -> [nest 1 (parens (commaSepFill (map (ppWithNames ns1) ps))) <+> text "=>"] ns1 = addTNames (sVars s) ns @@ -949,17 +950,20 @@ instance PP TySyn where instance PP (WithNames TySyn) where ppPrec _ (WithNames ts ns) = - text "type" <+> ctr <+> lhs <+> char '=' <+> ppWithNames ns1 (tsDef ts) + nest 2 $ sep + [ fsep ([text "type"] ++ ctr ++ lhs ++ [char '=']) + , ppWithNames ns1 (tsDef ts) + ] where ns1 = addTNames (tsParams ts) ns ctr = case kindResult (kindOf ts) of - KProp -> text "constraint" - _ -> empty + KProp -> [text "constraint"] + _ -> [] n = tsName ts lhs = case (nameFixity n, tsParams ts) of (Just _, [x, y]) -> - ppWithNames ns1 x <+> pp (nameIdent n) <+> ppWithNames ns1 y + [ppWithNames ns1 x, pp (nameIdent n), ppWithNames ns1 y] (_, ps) -> - pp n <+> sep (map (ppWithNames ns1) ps) + [pp n] ++ map (ppWithNames ns1) ps instance PP Newtype where ppPrec = ppWithNamesPrec IntMap.empty @@ -985,8 +989,8 @@ instance PP (WithNames Type) where ppPrec prec ty0@(WithNames ty nmMap) = case ty of TVar a -> ppWithNames nmMap a - TNewtype nt ts -> optParens (prec > 3) $ pp (ntName nt) <+> fsep (map (go 5) ts) - TRec fs -> braces $ fsep $ punctuate comma + TNewtype nt ts -> optParens (prec > 3) $ fsep (pp (ntName nt) : map (go 5) ts) + TRec fs -> ppRecord [ pp l <+> text ":" <+> go 0 t | (l,t) <- displayFields fs ] _ | Just tinf <- isTInfix ty0 -> optParens (prec > 2) @@ -1000,7 +1004,7 @@ instance PP (WithNames Type) where _ -> case ts of [] -> pp c - _ -> optParens (prec > 3) $ pp c <+> fsep (map (go 5) ts) + _ -> optParens (prec > 3) $ fsep (pp c : map (go 5) ts) TCon (TC tc) ts -> case (tc,ts) of @@ -1019,9 +1023,9 @@ instance PP (WithNames Type) where (TCFun, [t1,t2]) -> optParens (prec > 1) $ go 2 t1 <+> text "->" <+> go 1 t2 - (TCTuple _, fs) -> parens $ fsep $ punctuate comma $ map (go 0) fs + (TCTuple _, fs) -> ppTuple $ map (go 0) fs - (_, _) -> optParens (prec > 3) $ pp tc <+> fsep (map (go 5) ts) + (_, _) -> optParens (prec > 3) $ fsep (pp tc : (map (go 5) ts)) TCon (PC pc) ts -> case (pc,ts) of @@ -1032,7 +1036,7 @@ instance PP (WithNames Type) where (PPrime, [t1]) -> optParens (prec > 3) $ text "prime" <+> (go 5 t1) (PHas x, [t1,t2]) -> ppSelector x <+> text "of" <+> go 0 t1 <+> text "is" <+> go 0 t2 - (PAnd, [t1,t2]) -> parens (commaSep (map (go 0) (t1 : pSplitAnd t2))) + (PAnd, [t1,t2]) -> nest 1 (parens (commaSepFill (map (go 0) (t1 : pSplitAnd t2)))) (PRing, [t1]) -> pp pc <+> go 5 t1 (PField, [t1]) -> pp pc <+> go 5 t1 @@ -1044,10 +1048,9 @@ instance PP (WithNames Type) where (PLiteral, [t1,t2]) -> pp pc <+> go 5 t1 <+> go 5 t2 (PLiteralLessThan, [t1,t2]) -> pp pc <+> go 5 t1 <+> go 5 t2 - (_, _) -> optParens (prec > 3) $ pp pc <+> fsep (map (go 5) ts) + (_, _) -> optParens (prec > 3) $ fsep (pp pc : map (go 5) ts) - TCon f ts -> optParens (prec > 3) - $ pp f <+> fsep (map (go 5) ts) + TCon f ts -> optParens (prec > 3) $ fsep (pp f : map (go 5) ts) where go p t = ppWithNamesPrec nmMap p t @@ -1136,19 +1139,18 @@ instance PP Type where ppPrec n t = ppWithNamesPrec IntMap.empty n t instance PP TVarInfo where - ppPrec _ tvinfo = pp (tvarDesc tvinfo) <+> loc + ppPrec _ tvinfo = hsep $ [pp (tvarDesc tvinfo)] ++ loc where - loc = if rng == emptyRange then empty else "at" <+> pp rng + loc = if rng == emptyRange then [] else ["at" <+> pp rng] rng = tvarSource tvinfo instance PP ArgDescr where - ppPrec _ ad = which <+> "argument" <+> ofFun + ppPrec _ ad = hsep ([which, "argument"] ++ ofFun) where which = maybe "function" ordinal (argDescrNumber ad) ofFun = case argDescrFun ad of - Nothing -> empty - Just f -> "of" <+> pp f - + Nothing -> [] + Just f -> ["of" <+> pp f] instance PP TypeSource where diff --git a/src/Cryptol/TypeCheck/TypeOf.hs b/src/Cryptol/TypeCheck/TypeOf.hs index 7f458b24..b20748eb 100644 --- a/src/Cryptol/TypeCheck/TypeOf.hs +++ b/src/Cryptol/TypeCheck/TypeOf.hs @@ -54,8 +54,12 @@ fastTypeOf tyenv expr = polymorphic = case fastSchemaOf tyenv expr of Forall [] [] ty -> ty - _ -> panic "Cryptol.TypeCheck.TypeOf.fastTypeOf" - [ "unexpected polymorphic type" ] + s@Forall {} -> panic "Cryptol.TypeCheck.TypeOf.fastTypeOf" + [ "unexpected polymorphic type in expression:" + , pretty expr + , "with schema:" + , pretty s + ] fastSchemaOf :: Map Name Schema -> Expr -> Schema fastSchemaOf tyenv expr = @@ -124,13 +128,32 @@ plainSubst s ty = -- | Yields the return type of the selector on the given argument type. typeSelect :: Type -> Selector -> Type + +-- Selectors push inside the definition of type aliases typeSelect (TUser _ _ ty) sel = typeSelect ty sel + +-- Tuple selector applied to a tuple typeSelect (tIsTuple -> Just ts) (TupleSel i _) | i < length ts = ts !! i + +-- Record selector applied to a record typeSelect (TRec fields) (RecordSel n _) | Just ty <- lookupField n fields = ty + +-- Record selector applied to a newtype +typeSelect (TNewtype nt args) (RecordSel n _) + | Just ty <- lookupField n (ntFields nt) + = plainSubst (listParamSubst (zip (ntParams nt) args)) ty + +-- List selector applied to a sequence typeSelect (tIsSeq -> Just (_, a)) ListSel{} = a + +-- Tuple selectors and record selectors lift pointwise over sequences typeSelect (tIsSeq -> Just (n, a)) sel@TupleSel{} = tSeq n (typeSelect a sel) typeSelect (tIsSeq -> Just (n, a)) sel@RecordSel{} = tSeq n (typeSelect a sel) + +-- Selectors lift pointwise over functions +typeSelect (tIsFun -> Just (a, b)) sel = tFun a (typeSelect b sel) + typeSelect ty _ = panic "Cryptol.TypeCheck.TypeOf.typeSelect" - [ "cannot apply selector to value of type", render (pp ty) ] + [ "cannot apply selector to value of type", show (pp ty) ] diff --git a/src/Cryptol/Utils/PP.hs b/src/Cryptol/Utils/PP.hs index e91b3bcc..7c14a307 100644 --- a/src/Cryptol/Utils/PP.hs +++ b/src/Cryptol/Utils/PP.hs @@ -18,15 +18,12 @@ import Cryptol.Utils.Ident import Control.DeepSeq import Control.Monad (mplus) import Data.Maybe (fromMaybe) -import qualified Data.Semigroup as S import Data.String (IsString(..)) import qualified Data.Text as T +import Data.Void (Void) import GHC.Generics (Generic) -import qualified Text.PrettyPrint as PJ - -import Prelude () -import Prelude.Compat - +import qualified Prettyprinter as PP +import qualified Prettyprinter.Render.String as PP -- | How to pretty print things when evaluating data PPOpts = PPOpts @@ -76,7 +73,7 @@ data NameDisp = EmptyNameDisp instance Show NameDisp where show _ = "" -instance S.Semigroup NameDisp where +instance Semigroup NameDisp where NameDisp f <> NameDisp g = NameDisp (\n -> f n `mplus` g n) EmptyNameDisp <> EmptyNameDisp = EmptyNameDisp EmptyNameDisp <> x = x @@ -84,7 +81,7 @@ instance S.Semigroup NameDisp where instance Monoid NameDisp where mempty = EmptyNameDisp - mappend = (S.<>) + mappend = (<>) data NameFormat = UnQualified | Qualified !ModName @@ -122,29 +119,27 @@ fixNameDisp disp (Doc f) = Doc (\ _ -> f disp) -- Documents ------------------------------------------------------------------- -newtype Doc = Doc (NameDisp -> PJ.Doc) deriving (Generic, NFData) +newtype Doc = Doc (NameDisp -> PP.Doc Void) deriving (Generic, NFData) -instance S.Semigroup Doc where - (<>) = liftPJ2 (PJ.<>) +instance Semigroup Doc where + (<>) = liftPP2 (<>) instance Monoid Doc where - mempty = liftPJ PJ.empty - mappend = (S.<>) + mempty = liftPP mempty + mappend = (<>) -runDoc :: NameDisp -> Doc -> PJ.Doc +runDoc :: NameDisp -> Doc -> PP.Doc Void runDoc names (Doc f) = f names instance Show Doc where - show d = show (runDoc mempty d) + show d = PP.renderString (PP.layoutPretty opts (runDoc mempty d)) + where opts = PP.defaultLayoutOptions{ PP.layoutPageWidth = PP.AvailablePerLine 100 0.666 } instance IsString Doc where fromString = text -render :: Doc -> String -render d = PJ.render (runDoc mempty d) - renderOneLine :: Doc -> String -renderOneLine d = PJ.renderStyle (PJ.style { PJ.mode = PJ.OneLineMode }) (runDoc mempty d) +renderOneLine d = PP.renderString (PP.layoutCompact (runDoc mempty d)) class PP a where ppPrec :: Int -> a -> Doc @@ -171,7 +166,7 @@ pretty :: PP a => a -> String pretty = show . pp optParens :: Bool -> Doc -> Doc -optParens b body | b = parens body +optParens b body | b = nest 1 (parens body) | otherwise = body @@ -183,10 +178,6 @@ data Infix op thing = Infix , ieFixity :: Fixity -- ^ operator fixity } -commaSep :: [Doc] -> Doc -commaSep = fsep . punctuate comma - - -- | Pretty print an infix expression of some sort. ppInfix :: (PP thing, PP op) => Int -- ^ Non-infix leaves are printed with this precedence @@ -228,94 +219,123 @@ ordSuffix n0 = -- Wrapped Combinators --------------------------------------------------------- -liftPJ :: PJ.Doc -> Doc -liftPJ d = Doc (const d) +liftPP :: PP.Doc Void -> Doc +liftPP d = Doc (const d) -liftPJ1 :: (PJ.Doc -> PJ.Doc) -> Doc -> Doc -liftPJ1 f (Doc d) = Doc (\env -> f (d env)) +liftPP1 :: (PP.Doc Void -> PP.Doc Void) -> Doc -> Doc +liftPP1 f (Doc d) = Doc (\env -> f (d env)) -liftPJ2 :: (PJ.Doc -> PJ.Doc -> PJ.Doc) -> (Doc -> Doc -> Doc) -liftPJ2 f (Doc a) (Doc b) = Doc (\e -> f (a e) (b e)) +liftPP2 :: (PP.Doc Void -> PP.Doc Void -> PP.Doc Void) -> (Doc -> Doc -> Doc) +liftPP2 f (Doc a) (Doc b) = Doc (\e -> f (a e) (b e)) -liftSep :: ([PJ.Doc] -> PJ.Doc) -> ([Doc] -> Doc) +liftSep :: ([PP.Doc Void] -> PP.Doc Void) -> ([Doc] -> Doc) liftSep f ds = Doc (\e -> f [ d e | Doc d <- ds ]) -infixl 6 <.>, <+> +infixl 6 <.>, <+>, (<.>) :: Doc -> Doc -> Doc -(<.>) = liftPJ2 (PJ.<>) +(<.>) = liftPP2 (PP.<>) (<+>) :: Doc -> Doc -> Doc -(<+>) = liftPJ2 (PJ.<+>) +(<+>) = liftPP2 (PP.<+>) + +() :: Doc -> Doc -> Doc +Doc x Doc y = Doc (\e -> x e <> PP.softline <> y e) infixl 5 $$ ($$) :: Doc -> Doc -> Doc -($$) = liftPJ2 (PJ.$$) +($$) x y = vsep [x,y] sep :: [Doc] -> Doc -sep = liftSep PJ.sep +sep = liftSep PP.sep fsep :: [Doc] -> Doc -fsep = liftSep PJ.fsep +fsep = liftSep PP.fillSep hsep :: [Doc] -> Doc -hsep = liftSep PJ.hsep +hsep = liftSep PP.hsep hcat :: [Doc] -> Doc -hcat = liftSep PJ.hcat +hcat = liftSep PP.hcat vcat :: [Doc] -> Doc -vcat = liftSep PJ.vcat +vcat = liftSep PP.vcat +vsep :: [Doc] -> Doc +vsep = liftSep PP.vsep + +group :: Doc -> Doc +group = liftPP1 PP.group + +-- NB, this is the semantics of "hang" as defined +-- by the HugesPJ printer, not the "hang" from prettyprinter, +-- which is subtly different. hang :: Doc -> Int -> Doc -> Doc -hang (Doc p) i (Doc q) = Doc (\e -> PJ.hang (p e) i (q e)) +hang (Doc p) i (Doc q) = Doc (\e -> PP.hang i (PP.vsep [p e, q e])) nest :: Int -> Doc -> Doc -nest n = liftPJ1 (PJ.nest n) +nest n = liftPP1 (PP.nest n) + +indent :: Int -> Doc -> Doc +indent n = liftPP1 (PP.indent n) + +align :: Doc -> Doc +align = liftPP1 PP.align parens :: Doc -> Doc -parens = liftPJ1 PJ.parens +parens = liftPP1 PP.parens braces :: Doc -> Doc -braces = liftPJ1 PJ.braces +braces = liftPP1 PP.braces brackets :: Doc -> Doc -brackets = liftPJ1 PJ.brackets +brackets = liftPP1 PP.brackets quotes :: Doc -> Doc -quotes = liftPJ1 PJ.quotes +quotes = liftPP1 PP.squotes + +commaSep :: [Doc] -> Doc +commaSep xs = Doc (\e -> PP.sep (PP.punctuate PP.comma [ d e | Doc d <- xs ])) + +-- | Print a comma-separated list. Lay out each item on a single line +-- if it will fit. If an item requires multiple lines, then start it +-- on its own line. +commaSepFill :: [Doc] -> Doc +commaSepFill xs = Doc (\e -> fillSep (PP.punctuate PP.comma [ d e | Doc d <- xs ])) + where + fillSep [] = mempty + fillSep (d0 : ds) = foldl (\a d -> a <> PP.group (PP.line <> d)) d0 ds + +ppList :: [Doc] -> Doc +ppList xs = group (nest 1 (brackets (commaSepFill xs))) + +ppTuple :: [Doc] -> Doc +ppTuple xs = group (nest 1 (parens (commaSep xs))) + +ppRecord :: [Doc] -> Doc +ppRecord xs = group (nest 1 (braces (commaSep xs))) backticks :: Doc -> Doc backticks d = hcat [ "`", d, "`" ] -punctuate :: Doc -> [Doc] -> [Doc] -punctuate p = go - where - go (d:ds) | null ds = [d] - | otherwise = d <.> p : go ds - go [] = [] - text :: String -> Doc -text s = liftPJ (PJ.text s) +text s = liftPP (PP.pretty s) char :: Char -> Doc -char c = liftPJ (PJ.char c) +char c = liftPP (PP.pretty c) integer :: Integer -> Doc -integer i = liftPJ (PJ.integer i) +integer i = liftPP (PP.pretty i) int :: Int -> Doc -int i = liftPJ (PJ.int i) +int i = liftPP (PP.pretty i) comma :: Doc -comma = liftPJ PJ.comma - -empty :: Doc -empty = liftPJ PJ.empty +comma = liftPP PP.comma colon :: Doc -colon = liftPJ PJ.colon +colon = liftPP PP.colon instance PP T.Text where ppPrec _ str = text (T.unpack str) @@ -354,7 +374,7 @@ instance PP OrigName where case mo of TopModule m | m == exprModName -> x - | otherwise -> pp m <.> "::" <.> x + | otherwise -> pp m <.> "::" <.> x Nested m y -> ppQual m (pp y <.> "::" <.> x) instance PP Namespace where diff --git a/tests/examples/allexamples.icry.stdout b/tests/examples/allexamples.icry.stdout index c7df185d..3aa735d9 100644 --- a/tests/examples/allexamples.icry.stdout +++ b/tests/examples/allexamples.icry.stdout @@ -11,7 +11,8 @@ Loading module ChaCha20 [warning] at ChaChaPolyCryptolIETF.md:2062:20--2062:27 This binding for `AeadAAD` shadows the existing binding at ChaChaPolyCryptolIETF.md:1149:1--1149:8 -[warning] at ChaChaPolyCryptolIETF.md:340:32--340:33 Unused name: b +[warning] at ChaChaPolyCryptolIETF.md:340:32--340:33 + Unused name: b [warning] at ChaChaPolyCryptolIETF.md:2117:20--2117:21 Unused name: b Loading module Cryptol diff --git a/tests/issues/T146.icry.stdout b/tests/issues/T146.icry.stdout index 1ac3940f..03098f49 100644 --- a/tests/issues/T146.icry.stdout +++ b/tests/issues/T146.icry.stdout @@ -2,17 +2,17 @@ Loading module Cryptol Loading module Cryptol Loading module Main -[error] at T146.cry:1:18--6:10: - The type ?a is not sufficiently polymorphic. - It cannot depend on quantified variables: fv`812 - When checking type of field 'v0' - where - ?a is type argument 'fv' of 'Main::ec_v1' at T146.cry:4:19--4:24 - fv`812 is signature variable 'fv' at T146.cry:11:10--11:12 -[error] at T146.cry:5:19--5:24: +[error] at T146.cry:11:10--11:12: The type ?b is not sufficiently polymorphic. - It cannot depend on quantified variables: fv`812 + It cannot depend on quantified variables: fv`902 When checking signature variable 'fv' where ?b is type argument 'fv' of 'Main::ec_v2' at T146.cry:5:19--5:24 - fv`812 is signature variable 'fv' at T146.cry:11:10--11:12 + fv`902 is signature variable 'fv' at T146.cry:11:10--11:12 +[error] at T146.cry:12:11--12:21: + The type ?a is not sufficiently polymorphic. + It cannot depend on quantified variables: fv`902 + When checking type of field 'v0' + where + ?a is type argument 'fv' of 'Main::ec_v1' at T146.cry:4:19--4:24 + fv`902 is signature variable 'fv' at T146.cry:11:10--11:12 diff --git a/tests/issues/issue072.icry.stdout b/tests/issues/issue072.icry.stdout index 0c8e044f..e84e2b55 100644 --- a/tests/issues/issue072.icry.stdout +++ b/tests/issues/issue072.icry.stdout @@ -2,8 +2,10 @@ Loading module Cryptol Satisfiable it : {result : Bit, arg1 : [4]} Satisfiable +Models found: 11 it : [11]{result : Bit, arg1 : [4]} must be an integer > 0 or "all" must be an integer > 0 or "all" Satisfiable +Models found: 3 it : [3]{result : Bit, arg1 : [4]} diff --git a/tests/issues/issue1024.icry.stdout b/tests/issues/issue1024.icry.stdout index 8e21eec4..cacee831 100644 --- a/tests/issues/issue1024.icry.stdout +++ b/tests/issues/issue1024.icry.stdout @@ -1,27 +1,32 @@ Loading module Cryptol Loading module Cryptol Loading module Main -[warning] at issue1024a.cry:1:12--1:24 Unused name: f -[warning] at issue1024a.cry:2:14--2:24 Unused name: f -[warning] at issue1024a.cry:4:15--4:20 Unused name: i -[warning] at issue1024a.cry:4:22--4:32 Unused name: f -[warning] at issue1024a.cry:4:34--4:39 Unused name: g +[warning] at issue1024a.cry:1:12--1:24 + Unused name: f +[warning] at issue1024a.cry:2:14--2:24 + Unused name: f +[warning] at issue1024a.cry:4:15--4:20 + Unused name: i +[warning] at issue1024a.cry:4:22--4:32 + Unused name: f +[warning] at issue1024a.cry:4:34--4:39 + Unused name: g [error] at issue1024a.cry:1:6--1:11: - Illegal kind assigned to type variable: f`809 + Illegal kind assigned to type variable: f`899 Unexpected: # -> * where - f`809 is signature variable 'f' at issue1024a.cry:1:12--1:24 + f`899 is signature variable 'f' at issue1024a.cry:1:12--1:24 [error] at issue1024a.cry:2:6--2:13: - Illegal kind assigned to type variable: f`810 + Illegal kind assigned to type variable: f`900 Unexpected: Prop where - f`810 is signature variable 'f' at issue1024a.cry:2:14--2:24 + f`900 is signature variable 'f' at issue1024a.cry:2:14--2:24 [error] at issue1024a.cry:4:13--4:49: - Illegal kind assigned to type variable: f`812 + Illegal kind assigned to type variable: f`902 Unexpected: # -> * where - f`812 is signature variable 'f' at issue1024a.cry:4:22--4:32 + f`902 is signature variable 'f' at issue1024a.cry:4:22--4:32 Loading module Cryptol Loading module Main 0xffff diff --git a/tests/issues/issue103.icry.stdout b/tests/issues/issue103.icry.stdout index e003e802..3aa4b7dd 100644 --- a/tests/issues/issue103.icry.stdout +++ b/tests/issues/issue103.icry.stdout @@ -2,7 +2,7 @@ Loading module Cryptol Run-time error: undefined -- Backtrace -- -Cryptol::error called at Cryptol:990:13--990:18 +Cryptol::error called at Cryptol:1033:13--1033:18 Cryptol::undefined called at issue103.icry:1:9--1:18 Using exhaustive testing. Testing... ERROR for the following inputs: diff --git a/tests/issues/issue1240.cry b/tests/issues/issue1240.cry new file mode 100644 index 00000000..46191f4e --- /dev/null +++ b/tests/issues/issue1240.cry @@ -0,0 +1,8 @@ +module test where + +parameter + + type a : # + type constraint (fin a, a >= 1) + + b : Z a diff --git a/tests/issues/issue1240.icry b/tests/issues/issue1240.icry new file mode 100644 index 00000000..740955ca --- /dev/null +++ b/tests/issues/issue1240.icry @@ -0,0 +1 @@ +:load issue1240.cry diff --git a/tests/issues/issue1240.icry.stdout b/tests/issues/issue1240.icry.stdout new file mode 100644 index 00000000..eb41aed5 --- /dev/null +++ b/tests/issues/issue1240.icry.stdout @@ -0,0 +1,3 @@ +Loading module Cryptol +Loading module Cryptol +Loading module test diff --git a/tests/issues/issue138.cry b/tests/issues/issue138.cry index b28d8398..24a1a8c3 100644 --- a/tests/issues/issue138.cry +++ b/tests/issues/issue138.cry @@ -1,8 +1,8 @@ -down: [16][4] -down = [ 1+d | d <- tail down ] # [0] +dwn: [16][4] +dwn = [ 1+d | d <- tail dwn ] # [0] -down': [16][4] -down' = [ 1+(down' @ i) | i <- [1 .. 15] ] # [0] +dwn': [16][4] +dwn' = [ 1+(dwn' @ i) | i <- [1 .. 15] ] # [0] take_some: {n,k,t} (n>=k) => [n]t -> [k]t take_some xs = takes where takes = [ x | x <- xs | _ <- takes ] diff --git a/tests/issues/issue138.icry b/tests/issues/issue138.icry index 517399f0..71dbac5c 100644 --- a/tests/issues/issue138.icry +++ b/tests/issues/issue138.icry @@ -1,4 +1,4 @@ :l issue138.cry -down -down' +dwn +dwn' take_some`{4,3} "abcd" diff --git a/tests/issues/issue152.icry.stdout b/tests/issues/issue152.icry.stdout index 9724f8ef..ae1261b2 100644 --- a/tests/issues/issue152.icry.stdout +++ b/tests/issues/issue152.icry.stdout @@ -2,9 +2,9 @@ Loading module Cryptol 0x81db39d7 [0xdc6e05468ab90545, 0x3fd683aabbf9b928, 0x724f3408ce5a7745, 0xf5d53aa68de0ae45, 0xd8fc296263590e98, ...] -[[0x01, 0x83, 0x5f, 0x2e, 0xd1, 0x1a, 0x00, 0x1f, 0xfe, 0x55, 0xc8, - 0x96, 0xcd, 0xe5, 0x9e, 0xca, 0xd9, 0xaa, 0x8a, 0x89, 0x06, 0xbd, - 0x70, 0x40, 0xa7, 0x3b, 0xad, 0x8e, 0x8b, 0xe8, 0x6b, 0x5f], +[[0x01, 0x83, 0x5f, 0x2e, 0xd1, 0x1a, 0x00, 0x1f, 0xfe, 0x55, + 0xc8, 0x96, 0xcd, 0xe5, 0x9e, 0xca, 0xd9, 0xaa, 0x8a, 0x89, 0x06, + 0xbd, 0x70, 0x40, 0xa7, 0x3b, 0xad, 0x8e, 0x8b, 0xe8, 0x6b, 0x5f], [0xb1, 0xda, 0x11, 0x71, 0x9f, 0x42, 0x2e, 0x83, 0x42, 0xe3, 0x05, 0xab, 0xee, 0x00, 0x68, 0xdb, 0x82, 0x5e, 0xa5, 0xd7, 0x3c, 0x76, 0x99, 0xb9, 0xc2, 0xd9, 0xef, 0x44, 0x68, 0x95, 0x9b, 0x4d], diff --git a/tests/issues/issue226.icry.stdout b/tests/issues/issue226.icry.stdout index e49259c7..79e54a3b 100644 --- a/tests/issues/issue226.icry.stdout +++ b/tests/issues/issue226.icry.stdout @@ -90,9 +90,7 @@ Symbols (||) : {a} (Logic a) => a -> a -> a (^) : {a} (Logic a) => a -> a -> a (&&) : {a} (Logic a) => a -> a -> a - (#) : - {front, back, a} (fin front) => - [front]a -> [back]a -> [front + back]a + (#) : {front, back, a} (fin front) => [front]a -> [back]a -> [front + back]a (<<) : {n, ix, a} (Integral ix, Zero a) => [n]a -> ix -> [n]a (<<<) : {n, ix, a} (fin n, Integral ix) => [n]a -> ix -> [n]a (>>) : {n, ix, a} (Integral ix, Zero a) => [n]a -> ix -> [n]a @@ -133,29 +131,45 @@ Symbols fraction : {m, n, r, a} (FLiteral m n r a) => a fromInteger : {a} (Ring a) => Integer -> a fromThenTo : - {first, next, last, a, len} (fin first, fin next, fin last, - Literal first a, Literal next a, Literal last a, first != next, - lengthFromThenTo first next last == len) => + {first, next, last, a, len} + (fin first, fin next, fin last, Literal first a, Literal next a, + Literal last a, first != next, + lengthFromThenTo first next last == len) => [len]a fromTo : - {first, last, a} (fin last, last >= first, Literal first a, - Literal last a) => + {first, last, a} + (fin last, last >= first, Literal last a) => [1 + (last - first)]a + fromToBy : + {first, last, stride, a} + (fin last, fin stride, stride >= 1, last >= first, Literal last a) => + [1 + (last - first) / stride]a + fromToByLessThan : + {first, bound, stride, a} + (fin first, fin stride, stride >= 1, bound >= first, + LiteralLessThan bound a) => + [(bound - first) /^ stride]a + fromToDownBy : + {first, last, stride, a} + (fin first, fin stride, stride >= 1, first >= last, Literal first a) => + [1 + (first - last) / stride]a + fromToDownByGreaterThan : + {first, bound, stride, a} + (fin first, fin stride, stride >= 1, first >= bound, Literal first a) => + [(first - bound) /^ stride]a fromToLessThan : - {first, bound, a} (fin first, bound >= first, - LiteralLessThan bound a) => + {first, bound, a} + (fin first, bound >= first, LiteralLessThan bound a) => [bound - first]a fromZ : {n} (fin n, n >= 1) => Z n -> Integer generate : {n, a, ix} (Integral ix, LiteralLessThan n ix) => (ix -> a) -> [n]a - groupBy : - {each, parts, a} (fin each) => [each * parts]a -> [parts][each]a + groupBy : {each, parts, a} (fin each) => [each * parts]a -> [parts][each]a head : {n, a} [1 + n]a -> a infFrom : {a} (Integral a) => a -> [inf]a infFromThen : {a} (Integral a) => a -> a -> [inf]a iterate : {a} (a -> a) -> a -> [inf]a - join : - {parts, each, a} (fin each) => [parts][each]a -> [parts * each]a + join : {parts, each, a} (fin each) => [parts][each]a -> [parts * each]a last : {n, a} (fin n) => [1 + n]a -> a length : {n, a, b} (fin n, Literal n b) => [n]a -> b lg2 : {n} (fin n) => [n] -> [n] @@ -168,8 +182,7 @@ Symbols parmap : {a, b, n} (Eq b, fin n) => (a -> b) -> [n]a -> [n]b pdiv : {u, v} (fin u, fin v) => [u] -> [v] -> [u] pmod : {u, v} (fin u, fin v) => [u] -> [1 + v] -> [v] - pmult : - {u, v} (fin u, fin v) => [1 + u] -> [1 + v] -> [1 + (u + v)] + pmult : {u, v} (fin u, fin v) => [1 + u] -> [1 + v] -> [1 + (u + v)] product : {n, a} (fin n, Eq a, Ring a) => [n]a -> a random : {a} [256] -> a ratio : Integer -> Integer -> Rational @@ -180,22 +193,21 @@ Symbols roundAway : {a} (Round a) => a -> Integer roundToEven : {a} (Round a) => a -> Integer sborrow : {n} (fin n, n >= 1) => [n] -> [n] -> Bit - scanl : {n, b, a} (b -> a -> b) -> b -> [n]a -> [1 + n]b + scanl : {n, a, b} (a -> b -> a) -> a -> [n]b -> [1 + n]a scanr : {n, a, b} (fin n) => (a -> b -> b) -> b -> [n]a -> [1 + n]b scarry : {n} (fin n, n >= 1) => [n] -> [n] -> Bit sext : {m, n} (fin m, m >= n, n >= 1) => [n] -> [m] sort : {a, n} (Cmp a, fin n) => [n]a -> [n]a sortBy : {a, n} (fin n) => (a -> a -> Bit) -> [n]a -> [n]a - split : - {parts, each, a} (fin each) => [parts * each]a -> [parts][each]a + split : {parts, each, a} (fin each) => [parts * each]a -> [parts][each]a splitAt : - {front, back, a} (fin front) => - [front + back]a -> ([front]a, [back]a) + {front, back, a} (fin front) => [front + back]a -> ([front]a, [back]a) sum : {n, a} (fin n, Eq a, Ring a) => [n]a -> a True : Bit tail : {n, a} [1 + n]a -> [n]a take : {front, back, a} [front + back]a -> [front]a toInteger : {a} (Integral a) => a -> Integer + toSignedInteger : {n} (fin n, n >= 1) => [n] -> Integer trace : {n, a, b} (fin n) => String n -> a -> b -> b traceVal : {n, a} (fin n) => String n -> a -> a transpose : {rows, cols, a} [rows][cols]a -> [cols][rows]a @@ -203,13 +215,11 @@ Symbols uncurry : {a, b, c} (a -> b -> c) -> (a, b) -> c undefined : {a} a update : {n, a, ix} (Integral ix) => [n]a -> ix -> a -> [n]a - updateEnd : - {n, a, ix} (fin n, Integral ix) => [n]a -> ix -> a -> [n]a + updateEnd : {n, a, ix} (fin n, Integral ix) => [n]a -> ix -> a -> [n]a updates : {n, k, ix, a} (Integral ix, fin k) => [n]a -> [k]ix -> [k]a -> [n]a updatesEnd : - {n, k, ix, a} (fin n, Integral ix, fin k) => - [n]a -> [k]ix -> [k]a -> [n]a + {n, k, ix, a} (fin n, Integral ix, fin k) => [n]a -> [k]ix -> [k]a -> [n]a zero : {a} (Zero a) => a zext : {m, n} (fin m, m >= n) => [n] -> [m] zip : {n, a, b} [n]a -> [n]b -> [n](a, b) diff --git a/tests/issues/issue290v2.icry.stdout b/tests/issues/issue290v2.icry.stdout index 6f22bf30..7af830a7 100644 --- a/tests/issues/issue290v2.icry.stdout +++ b/tests/issues/issue290v2.icry.stdout @@ -3,10 +3,23 @@ Loading module Cryptol Loading module Main [error] at issue290v2.cry:2:1--2:19: + Failed to validate user-specified signature. + in the definition of 'Main::minMax', at issue290v2.cry:2:1--2:7, + we need to show that + for any type n, a + assuming + • fin n + • Cmp a + the following constraints hold: + • n == 1 + arising from + matching types + at issue290v2.cry:2:1--2:19 +[error] at issue290v2.cry:2:8--2:11: Unsolved constraints: - • n`809 == 1 + • n`899 == 1 arising from checking a pattern: type of 1st argument of Main::minMax at issue290v2.cry:2:8--2:11 where - n`809 is signature variable 'n' at issue290v2.cry:1:11--1:12 + n`899 is signature variable 'n' at issue290v2.cry:1:11--1:12 diff --git a/tests/issues/issue410.icry.stdout b/tests/issues/issue410.icry.stdout index 92824e55..513e2397 100644 --- a/tests/issues/issue410.icry.stdout +++ b/tests/issues/issue410.icry.stdout @@ -9,13 +9,9 @@ Loading module Cryptol (bs where bs = [~b | b <- [~x] # bs - | _ <- bs] - ) - ) : {n, a} (Logic a) => a -> [n]a + | _ <- bs])) : + {n, a} (Logic a) => a -> [n]a {n, a} n == n -(bs - where - bs = [b | b <- bs] - ) : {n, a} [n]a +(bs where bs = [b | b <- bs]) : {n, a} [n]a 1 == 1 [b | b <- [True]] : [1] diff --git a/tests/issues/issue494.icry.stdout b/tests/issues/issue494.icry.stdout index 8682dcaf..72698e61 100644 --- a/tests/issues/issue494.icry.stdout +++ b/tests/issues/issue494.icry.stdout @@ -1,5 +1,4 @@ Loading module Cryptol Loading module Cryptol Loading module Main -gt_words' : {n, m, a} (Cmp a, fin (min (1 + n) (1 + m))) => - [n]a -> [m]a -> Bit +gt_words' : {n, m, a} (Cmp a, fin (min (1 + n) (1 + m))) => [n]a -> [m]a -> Bit diff --git a/tests/issues/issue513.icry.stdout b/tests/issues/issue513.icry.stdout index 08fb3448..f178fe36 100644 --- a/tests/issues/issue513.icry.stdout +++ b/tests/issues/issue513.icry.stdout @@ -7,15 +7,16 @@ module Main import Cryptol /* Recursive */ Main::test : {a} [1 + a] -Main::test = \{a} -> - Main::$mono - where - /* Recursive */ - Main::$mono : [1 + a] - Main::$mono = (Cryptol::#) 1 a Bit <> [Cryptol::False] [y | i <- Cryptol::zero [a] <> - | y <- Main::$mono] - - +Main::test = + \{a} -> + Main::$mono + where + /* Recursive */ + Main::$mono : [1 + a] + Main::$mono = + (Cryptol::#) 1 a Bit <> [Cryptol::False] [y | i <- Cryptol::zero [a] <> + | y <- Main::$mono] + Main::test test : {a} [1 + a] diff --git a/tests/issues/issue582.icry.stdout b/tests/issues/issue582.icry.stdout index 72056447..07de82fc 100644 --- a/tests/issues/issue582.icry.stdout +++ b/tests/issues/issue582.icry.stdout @@ -6,13 +6,7 @@ Loading module Cryptol arising from use of partial type function (/^) at issue582.icry:1:1--1:18 - -[error] at issue582.icry:2:1--2:18: - • Unsolvable constraint: - fin inf - arising from - use of partial type function (/^) - at issue582.icry:2:1--2:18 +[False, False, False, False, False, ...] [error] at issue582.icry:3:1--3:16: • Unsolvable constraint: @@ -27,13 +21,7 @@ Loading module Cryptol arising from use of partial type function (%^) at issue582.icry:4:1--4:18 - -[error] at issue582.icry:5:1--5:18: - • Unsolvable constraint: - fin inf - arising from - use of partial type function (%^) - at issue582.icry:5:1--5:18 +0x0 [error] at issue582.icry:6:1--6:16: • Unsolvable constraint: @@ -54,10 +42,6 @@ Loading module Main arising from use of partial type function (/^) at issue582.cry:1:7--1:21 - • fin i - arising from - use of partial type function (/^) - at issue582.cry:1:7--1:21 • j >= 1 arising from use of partial type function (/^) @@ -72,10 +56,6 @@ Loading module Main arising from use of partial type function (%^) at issue582.cry:4:7--4:21 - • fin i - arising from - use of partial type function (%^) - at issue582.cry:4:7--4:21 • j >= 1 arising from use of partial type function (%^) diff --git a/tests/issues/issue702.icry.stdout b/tests/issues/issue702.icry.stdout index d360a39c..148fb479 100644 --- a/tests/issues/issue702.icry.stdout +++ b/tests/issues/issue702.icry.stdout @@ -1,7 +1,9 @@ Loading module Cryptol Satisfiable (\(x : {b : Bit, a : Bit}) -> x.a && x.b) - {b = True, a = True} = True + {b = True, a = True} + = True Satisfiable (\(x : {b : [8], a : Bit}) -> x.b == 0 /\ x.a) - {b = 0x00, a = True} = True + {b = 0x00, a = True} + = True diff --git a/tests/issues/issue723.icry.stdout b/tests/issues/issue723.icry.stdout index f954bf1d..bbf06f63 100644 --- a/tests/issues/issue723.icry.stdout +++ b/tests/issues/issue723.icry.stdout @@ -10,9 +10,9 @@ Loading module Main assuming • fin k the following constraints hold: - • k == n`809 + • k == n`899 arising from matching types at issue723.cry:7:17--7:19 where - n`809 is signature variable 'n' at issue723.cry:1:6--1:7 + n`899 is signature variable 'n' at issue723.cry:1:6--1:7 diff --git a/tests/issues/issue894.icry.stdout b/tests/issues/issue894.icry.stdout index 8d8cae5d..a8cd65d3 100644 --- a/tests/issues/issue894.icry.stdout +++ b/tests/issues/issue894.icry.stdout @@ -1,7 +1,8 @@ Loading module Cryptol Loading module Cryptol Loading module Main -[warning] at issue894.cry:1:10--1:11 Unused name: n +[warning] at issue894.cry:1:10--1:11 + Unused name: n [warning] at issue894.cry:1:6--1:9: Assuming n to have a numeric type foo 0x1 : Int 4 diff --git a/tests/modsys/T16.icry.stdout b/tests/modsys/T16.icry.stdout index 953033fd..72b79836 100644 --- a/tests/modsys/T16.icry.stdout +++ b/tests/modsys/T16.icry.stdout @@ -5,5 +5,5 @@ Loading module T16::B [error] at ./T16/B.cry:5:5--5:11 Multiple definitions for symbol: update - (at Cryptol:844:11--844:17, update) + (at Cryptol:899:11--899:17, update) (at ./T16/A.cry:3:1--3:7, T16::A::update) diff --git a/tests/modsys/T16.icry.stdout.mingw32 b/tests/modsys/T16.icry.stdout.mingw32 index 1ed7c0bc..0bffe31c 100644 --- a/tests/modsys/T16.icry.stdout.mingw32 +++ b/tests/modsys/T16.icry.stdout.mingw32 @@ -5,5 +5,5 @@ Loading module T16::B [error] at .\T16\B.cry:5:5--5:11 Multiple definitions for symbol: update - (at Cryptol:844:11--844:17, update) + (at Cryptol:899:11--899:17, update) (at .\T16\A.cry:3:1--3:7, T16::A::update) diff --git a/tests/modsys/nested/T1.icry.stdout b/tests/modsys/nested/T1.icry.stdout index 8b305832..706a4453 100644 --- a/tests/modsys/nested/T1.icry.stdout +++ b/tests/modsys/nested/T1.icry.stdout @@ -2,4 +2,5 @@ Loading module Cryptol Loading module Cryptol Loading module T1 -[error] at T1.cry:6:5--6:6 Value not in scope: x +[error] at T1.cry:6:5--6:6 + Value not in scope: x diff --git a/tests/modsys/nested/T2.icry.stdout b/tests/modsys/nested/T2.icry.stdout index 0c579d24..c07d2049 100644 --- a/tests/modsys/nested/T2.icry.stdout +++ b/tests/modsys/nested/T2.icry.stdout @@ -4,10 +4,14 @@ Parse error at T2.icry:1:1, unexpected: : expected: a declaration -[error] at T2.icry:2:4--2:5 Value not in scope: x +[error] at T2.icry:2:4--2:5 + Value not in scope: x -[error] at T2.icry:3:4--3:5 Value not in scope: y +[error] at T2.icry:3:4--3:5 + Value not in scope: y -[error] at T2.icry:4:1--4:2 Value not in scope: x +[error] at T2.icry:4:1--4:2 + Value not in scope: x -[error] at T2.icry:5:1--5:2 Value not in scope: y +[error] at T2.icry:5:1--5:2 + Value not in scope: y diff --git a/tests/mono-binds/test01.icry.stdout b/tests/mono-binds/test01.icry.stdout index adb0e36f..a165f4c6 100644 --- a/tests/mono-binds/test01.icry.stdout +++ b/tests/mono-binds/test01.icry.stdout @@ -5,14 +5,14 @@ module test01 import Cryptol /* Not recursive */ test01::a : {n, a} (fin n) => [n]a -> [2 * n]a -test01::a = \{n, a} (fin n) (x : [n]a) -> - f n x - where - /* Not recursive */ - f : {m} [m]a -> [n + m]a - f = \{m} (y : [m]a) -> (Cryptol::#) n m a <> x y - - +test01::a = + \{n, a} (fin n) (x : [n]a) -> + f n x + where + /* Not recursive */ + f : {m} [m]a -> [n + m]a + f = \{m} (y : [m]a) -> (Cryptol::#) n m a <> x y + Loading module Cryptol Loading module test01 @@ -20,12 +20,12 @@ module test01 import Cryptol /* Not recursive */ test01::a : {n, a} (fin n) => [n]a -> [2 * n]a -test01::a = \{n, a} (fin n) (x : [n]a) -> - f x - where - /* Not recursive */ - f : [n]a -> [2 * n]a - f = \ (y : [n]a) -> (Cryptol::#) n n a <> x y - - +test01::a = + \{n, a} (fin n) (x : [n]a) -> + f x + where + /* Not recursive */ + f : [n]a -> [2 * n]a + f = \(y : [n]a) -> (Cryptol::#) n n a <> x y + diff --git a/tests/mono-binds/test02.icry.stdout b/tests/mono-binds/test02.icry.stdout index ba8fc376..0c39c671 100644 --- a/tests/mono-binds/test02.icry.stdout +++ b/tests/mono-binds/test02.icry.stdout @@ -5,16 +5,16 @@ module test02 import Cryptol /* Not recursive */ test02::test : {a, b} a -> b -test02::test = \{a, b} (a : a) -> - f b a - where - /* Recursive */ - f : {c} a -> c - f = \{c} (x : a) -> g c a - g : {c} a -> c - g = \{c} (x : a) -> f c x - - +test02::test = + \{a, b} (a : a) -> + f b a + where + /* Recursive */ + f : {c} a -> c + f = \{c} (x : a) -> g c a + g : {c} a -> c + g = \{c} (x : a) -> f c x + Loading module Cryptol Loading module test02 @@ -22,14 +22,14 @@ module test02 import Cryptol /* Not recursive */ test02::test : {a, b} b -> a -test02::test = \{a, b} (a : b) -> - f a - where - /* Recursive */ - f : b -> a - f = \ (x : b) -> g a - g : b -> a - g = \ (x : b) -> f x - - +test02::test = + \{a, b} (a : b) -> + f a + where + /* Recursive */ + f : b -> a + f = \(x : b) -> g a + g : b -> a + g = \(x : b) -> f x + diff --git a/tests/mono-binds/test03.icry.stdout b/tests/mono-binds/test03.icry.stdout index e17ed8fd..53c98ad9 100644 --- a/tests/mono-binds/test03.icry.stdout +++ b/tests/mono-binds/test03.icry.stdout @@ -5,14 +5,14 @@ module test03 import Cryptol /* Not recursive */ test03::test : {a} (fin a, a >= width a) => [a] -test03::test = \{a} (fin a, a >= width a) -> - foo [a] <> - where - /* Not recursive */ - foo : {b} (Literal a b) => b - foo = \{b} (Literal a b) -> Cryptol::number a b <> - - +test03::test = + \{a} (fin a, a >= width a) -> + foo [a] <> + where + /* Not recursive */ + foo : {b} (Literal a b) => b + foo = \{b} (Literal a b) -> Cryptol::number a b <> + Loading module Cryptol Loading module test03 @@ -20,12 +20,12 @@ module test03 import Cryptol /* Not recursive */ test03::test : {a} (fin a, a >= width a) => [a] -test03::test = \{a} (fin a, a >= width a) -> - foo - where - /* Not recursive */ - foo : [a] - foo = Cryptol::number a [a] <> - - +test03::test = + \{a} (fin a, a >= width a) -> + foo + where + /* Not recursive */ + foo : [a] + foo = Cryptol::number a [a] <> + diff --git a/tests/mono-binds/test04.icry.stdout b/tests/mono-binds/test04.icry.stdout index 7f8758d8..ab707e1c 100644 --- a/tests/mono-binds/test04.icry.stdout +++ b/tests/mono-binds/test04.icry.stdout @@ -5,14 +5,14 @@ module test04 import Cryptol /* Not recursive */ test04::test : {a, b} (Literal 10 b) => a -> ((a, ()), (a, b)) -test04::test = \{a, b} (Literal 10 b) (a : a) -> - (f () (), f b (Cryptol::number 10 b <>)) - where - /* Not recursive */ - f : {c} c -> (a, c) - f = \{c} (x : c) -> (a, x) - - +test04::test = + \{a, b} (Literal 10 b) (a : a) -> + (f () (), f b (Cryptol::number 10 b <>)) + where + /* Not recursive */ + f : {c} c -> (a, c) + f = \{c} (x : c) -> (a, x) + Loading module Cryptol Loading module test04 diff --git a/tests/mono-binds/test05.icry.stdout b/tests/mono-binds/test05.icry.stdout index 03ebf46b..14b10073 100644 --- a/tests/mono-binds/test05.icry.stdout +++ b/tests/mono-binds/test05.icry.stdout @@ -15,30 +15,31 @@ test05::foo = Cryptol::number 10 [10] <> /* Not recursive */ test05::test : {n, a, b} (Zero b, Literal 10 a) => [n]b -> a -test05::test = \{n, a, b} (Zero b, Literal 10 a) (a : [n]b) -> - Cryptol::number 10 a <> - where - /* Not recursive */ - foo : [10] - foo = Cryptol::number 10 [10] <> - - /* Not recursive */ - f : {m} (fin m) => [n + m]b - f = \{m} (fin m) -> - bar m <> - where - /* Not recursive */ - foo : [n]b - foo = a - - /* Not recursive */ - bar : {i} (fin i) => [i + n]b - bar = \{i} (fin i) -> - (Cryptol::#) i n b <> (Cryptol::zero ([i]b) <>) foo - - - - +test05::test = + \{n, a, b} (Zero b, Literal 10 a) (a : [n]b) -> + Cryptol::number 10 a <> + where + /* Not recursive */ + foo : [10] + foo = Cryptol::number 10 [10] <> + + /* Not recursive */ + f : {m} (fin m) => [n + m]b + f = + \{m} (fin m) -> + bar m <> + where + /* Not recursive */ + foo : [n]b + foo = a + + /* Not recursive */ + bar : {i} (fin i) => [i + n]b + bar = + \{i} (fin i) -> + (Cryptol::#) i n b <> (Cryptol::zero ([i]b) <>) foo + + Loading module Cryptol Loading module test05 diff --git a/tests/mono-binds/test06.icry.stdout b/tests/mono-binds/test06.icry.stdout index 0555cc43..a579c368 100644 --- a/tests/mono-binds/test06.icry.stdout +++ b/tests/mono-binds/test06.icry.stdout @@ -5,18 +5,18 @@ module test06 import Cryptol /* Not recursive */ test06::test : {a} (Zero a) => a -> a -test06::test = \{a} (Zero a) (a : a) -> - bar - where - /* Not recursive */ - foo : a - foo = Cryptol::zero a <> - - /* Not recursive */ - bar : a - bar = foo - - +test06::test = + \{a} (Zero a) (a : a) -> + bar + where + /* Not recursive */ + foo : a + foo = Cryptol::zero a <> + + /* Not recursive */ + bar : a + bar = foo + Loading module Cryptol Loading module test06 @@ -24,16 +24,16 @@ module test06 import Cryptol /* Not recursive */ test06::test : {a} (Zero a) => a -> a -test06::test = \{a} (Zero a) (a : a) -> - bar - where - /* Not recursive */ - foo : a - foo = Cryptol::zero a <> - - /* Not recursive */ - bar : a - bar = foo - - +test06::test = + \{a} (Zero a) (a : a) -> + bar + where + /* Not recursive */ + foo : a + foo = Cryptol::zero a <> + + /* Not recursive */ + bar : a + bar = foo + diff --git a/tests/regression/allsat.cry b/tests/regression/allsat.cry new file mode 100644 index 00000000..1b56eeda --- /dev/null +++ b/tests/regression/allsat.cry @@ -0,0 +1,3 @@ +f : (Integer, Integer, Integer) -> Bit +f (x, y, z) = inRange x && inRange y && inRange z + where inRange v = (1 <= v) && (v <= 15) diff --git a/tests/regression/allsat.icry b/tests/regression/allsat.icry new file mode 100644 index 00000000..b920cac4 --- /dev/null +++ b/tests/regression/allsat.icry @@ -0,0 +1,9 @@ +:l allsat.cry + +:set satNum=all +:set showExamples=false +:set prover=sbv-z3 +:sat f + +:set prover=w4-z3 +:sat f diff --git a/tests/regression/allsat.icry.stdout b/tests/regression/allsat.icry.stdout new file mode 100644 index 00000000..12c5a4c0 --- /dev/null +++ b/tests/regression/allsat.icry.stdout @@ -0,0 +1,7 @@ +Loading module Cryptol +Loading module Cryptol +Loading module Main +Satisfiable +Models found: 3375 +Satisfiable +Models found: 3375 diff --git a/tests/regression/array.icry.stdout b/tests/regression/array.icry.stdout index cd311dc6..19b44e78 100644 --- a/tests/regression/array.icry.stdout +++ b/tests/regression/array.icry.stdout @@ -10,6 +10,17 @@ Symbols ======= arrayConstant : {a, b} b -> Array a b + arrayCopy : + {n, a} Array [n] a -> [n] -> Array [n] a -> [n] -> [n] -> Array [n] a arrayLookup : {a, b} Array a b -> a -> b + arrayRangeEqual : + {n, a} Array [n] a -> [n] -> Array [n] a -> [n] -> [n] -> Bool + arrayRangeLookup : + {a, b, n} (Integral a, fin n, LiteralLessThan n a) => Array a b -> a -> [n]b + arrayRangeUpdate : + {a, b, n} + (Integral a, fin n, LiteralLessThan n a) => + Array a b -> a -> [n]b -> Array a b + arraySet : {n, a} Array [n] a -> [n] -> a -> [n] -> Array [n] a arrayUpdate : {a, b} Array a b -> a -> b -> Array a b diff --git a/tests/regression/explicit-strides.icry b/tests/regression/explicit-strides.icry new file mode 100644 index 00000000..758dac51 --- /dev/null +++ b/tests/regression/explicit-strides.icry @@ -0,0 +1,12 @@ +[ 0:Integer .. 10 by 2] +[ 0 .. <10:Integer by 2] + +[ 0 .. 9 by 2] : [_]Integer +[ 0 .. <9 by 2:Integer] + +[ 10:Integer .. 0 down by 2 ] +[ 10 .. >0 down by 2 ] + +[ 2^^16-1 .. >50000 down by 100 ] : [_][16] + +[ 200 .. 100:Integer down by 9 ] diff --git a/tests/regression/explicit-strides.icry.stdout b/tests/regression/explicit-strides.icry.stdout new file mode 100644 index 00000000..2d5416b6 --- /dev/null +++ b/tests/regression/explicit-strides.icry.stdout @@ -0,0 +1,30 @@ +Loading module Cryptol +[0, 2, 4, 6, 8, 10] +[0, 2, 4, 6, 8] +[0, 2, 4, 6, 8] +[0, 2, 4, 6, 8] +[10, 8, 6, 4, 2, 0] +Showing a specific instance of polymorphic result: + * Using 'Integer' for type argument 'a' of 'Cryptol::fromToDownByGreaterThan' +[10, 8, 6, 4, 2] +[0xffff, 0xff9b, 0xff37, 0xfed3, 0xfe6f, 0xfe0b, 0xfda7, 0xfd43, + 0xfcdf, 0xfc7b, 0xfc17, 0xfbb3, 0xfb4f, 0xfaeb, 0xfa87, 0xfa23, + 0xf9bf, 0xf95b, 0xf8f7, 0xf893, 0xf82f, 0xf7cb, 0xf767, 0xf703, + 0xf69f, 0xf63b, 0xf5d7, 0xf573, 0xf50f, 0xf4ab, 0xf447, 0xf3e3, + 0xf37f, 0xf31b, 0xf2b7, 0xf253, 0xf1ef, 0xf18b, 0xf127, 0xf0c3, + 0xf05f, 0xeffb, 0xef97, 0xef33, 0xeecf, 0xee6b, 0xee07, 0xeda3, + 0xed3f, 0xecdb, 0xec77, 0xec13, 0xebaf, 0xeb4b, 0xeae7, 0xea83, + 0xea1f, 0xe9bb, 0xe957, 0xe8f3, 0xe88f, 0xe82b, 0xe7c7, 0xe763, + 0xe6ff, 0xe69b, 0xe637, 0xe5d3, 0xe56f, 0xe50b, 0xe4a7, 0xe443, + 0xe3df, 0xe37b, 0xe317, 0xe2b3, 0xe24f, 0xe1eb, 0xe187, 0xe123, + 0xe0bf, 0xe05b, 0xdff7, 0xdf93, 0xdf2f, 0xdecb, 0xde67, 0xde03, + 0xdd9f, 0xdd3b, 0xdcd7, 0xdc73, 0xdc0f, 0xdbab, 0xdb47, 0xdae3, + 0xda7f, 0xda1b, 0xd9b7, 0xd953, 0xd8ef, 0xd88b, 0xd827, 0xd7c3, + 0xd75f, 0xd6fb, 0xd697, 0xd633, 0xd5cf, 0xd56b, 0xd507, 0xd4a3, + 0xd43f, 0xd3db, 0xd377, 0xd313, 0xd2af, 0xd24b, 0xd1e7, 0xd183, + 0xd11f, 0xd0bb, 0xd057, 0xcff3, 0xcf8f, 0xcf2b, 0xcec7, 0xce63, + 0xcdff, 0xcd9b, 0xcd37, 0xccd3, 0xcc6f, 0xcc0b, 0xcba7, 0xcb43, + 0xcadf, 0xca7b, 0xca17, 0xc9b3, 0xc94f, 0xc8eb, 0xc887, 0xc823, + 0xc7bf, 0xc75b, 0xc6f7, 0xc693, 0xc62f, 0xc5cb, 0xc567, 0xc503, + 0xc49f, 0xc43b, 0xc3d7, 0xc373] +[200, 191, 182, 173, 164, 155, 146, 137, 128, 119, 110, 101] diff --git a/tests/regression/float.icry.stdout b/tests/regression/float.icry.stdout index c46120de..da5aaeac 100644 --- a/tests/regression/float.icry.stdout +++ b/tests/regression/float.icry.stdout @@ -36,7 +36,7 @@ Specifies the format to use when showing floating point numbers: 0x1.2p4 "-- Float Type-----------------------------------------------------------------" - primitive type Float : # -> # -> * +primitive type Float : # -> # -> * `Float exponent precision` requires: • ValidFloat exponent precision diff --git a/tests/regression/ignore-safe.icry b/tests/regression/ignore-safe.icry index 40f0057e..09add112 100644 --- a/tests/regression/ignore-safe.icry +++ b/tests/regression/ignore-safe.icry @@ -10,7 +10,6 @@ :prove (\ (x:[8]) y -> (y == 0) || (y*(x/y) + x%y == x)) :prove (\ (x:Integer) -> [0,0,0]@x == 0 ) -:prove (\ (x:Integer) -> []@x == 0 ) :prove (\ (x:[8]) -> [0,0,0]@x == 0 ) :set ignore-safety = on @@ -22,5 +21,4 @@ :prove (\ (x:[8]) y -> (y == 0) || (y*(x/y) + x%y == x)) :prove (\ (x:Integer) -> [0,0,0]@x == 0 ) -:prove (\ (x:Integer) -> []@x == 0 ) :prove (\ (x:[8]) -> [0,0,0]@x == 0 ) diff --git a/tests/regression/ignore-safe.icry.stdout b/tests/regression/ignore-safe.icry.stdout index cd1ae482..a2bf8388 100644 --- a/tests/regression/ignore-safe.icry.stdout +++ b/tests/regression/ignore-safe.icry.stdout @@ -11,5 +11,3 @@ Q.E.D. Q.E.D. Q.E.D. Q.E.D. -Q.E.D. -Q.E.D. diff --git a/tests/regression/instance.icry.stdout b/tests/regression/instance.icry.stdout index 2d499044..5128fa14 100644 --- a/tests/regression/instance.icry.stdout +++ b/tests/regression/instance.icry.stdout @@ -47,8 +47,8 @@ complement`{(_ -> _)} : {a, b} (Logic b) => (a -> b) -> a -> b complement`{()} : () -> () complement`{(_, _)} : {a, b} (Logic b, Logic a) => (a, b) -> (a, b) complement`{{}} : {} -> {} -complement`{{x : _, y : _}} : {a, b} (Logic b, Logic a) => - {x : a, y : b} -> {x : a, y : b} +complement`{{x : _, y : _}} : + {a, b} (Logic b, Logic a) => {x : a, y : b} -> {x : a, y : b} [error] at instance.icry:26:4--26:14: • Type `Float ?m ?n` does not support logical operations. @@ -81,10 +81,9 @@ negate`{(_ -> _)} : {a, b} (Ring b) => (a -> b) -> a -> b negate`{()} : () -> () negate`{(_, _)} : {a, b} (Ring b, Ring a) => (a, b) -> (a, b) negate`{{}} : {} -> {} -negate`{{x : _, y : _}} : {a, b} (Ring b, Ring a) => - {x : a, y : b} -> {x : a, y : b} -negate`{Float _ _} : {n, m} (ValidFloat n m) => - Float n m -> Float n m +negate`{{x : _, y : _}} : + {a, b} (Ring b, Ring a) => {x : a, y : b} -> {x : a, y : b} +negate`{Float _ _} : {n, m} (ValidFloat n m) => Float n m -> Float n m [error] at instance.icry:41:4--41:10: • Type `Box ?a` does not support ring operations. @@ -233,8 +232,7 @@ recip`{Z _} : {n} (prime n, n >= 1) => Z n -> Z n where ?a is type wildcard (_) at instance.icry:65:16--65:17 ?b is type wildcard (_) at instance.icry:65:23--65:24 -recip`{Float _ _} : {n, m} (ValidFloat n m) => - Float n m -> Float n m +recip`{Float _ _} : {n, m} (ValidFloat n m) => Float n m -> Float n m [error] at instance.icry:67:4--67:9: • Type `Box ?a` does not support field operations. @@ -338,10 +336,9 @@ floor`{Float _ _} : {n, m} (ValidFloat n m) => Float n m -> Integer (==)`{()} : () -> () -> Bit (==)`{(_, _)} : {a, b} (Eq b, Eq a) => (a, b) -> (a, b) -> Bit (==)`{{}} : {} -> {} -> Bit -(==)`{{x : _, y : _}} : {a, b} (Eq b, Eq a) => - {x : a, y : b} -> {x : a, y : b} -> Bit -(==)`{Float _ _} : {n, m} (ValidFloat n m) => - Float n m -> Float n m -> Bit +(==)`{{x : _, y : _}} : + {a, b} (Eq b, Eq a) => {x : a, y : b} -> {x : a, y : b} -> Bit +(==)`{Float _ _} : {n, m} (ValidFloat n m) => Float n m -> Float n m -> Bit [error] at instance.icry:93:4--93:8: • Type `Box ?a` does not support equality. @@ -374,10 +371,9 @@ floor`{Float _ _} : {n, m} (ValidFloat n m) => Float n m -> Integer (<)`{()} : () -> () -> Bit (<)`{(_, _)} : {a, b} (Cmp b, Cmp a) => (a, b) -> (a, b) -> Bit (<)`{{}} : {} -> {} -> Bit -(<)`{{x : _, y : _}} : {a, b} (Cmp b, Cmp a) => - {x : a, y : b} -> {x : a, y : b} -> Bit -(<)`{Float _ _} : {n, m} (ValidFloat n m) => - Float n m -> Float n m -> Bit +(<)`{{x : _, y : _}} : + {a, b} (Cmp b, Cmp a) => {x : a, y : b} -> {x : a, y : b} -> Bit +(<)`{Float _ _} : {n, m} (ValidFloat n m) => Float n m -> Float n m -> Bit [error] at instance.icry:106:4--106:7: • Type `Box ?a` does not support comparisons. @@ -423,11 +419,10 @@ floor`{Float _ _} : {n, m} (ValidFloat n m) => Float n m -> Integer ?a is type wildcard (_) at instance.icry:113:11--113:12 ?b is type wildcard (_) at instance.icry:113:16--113:17 (<$)`{()} : () -> () -> Bit -(<$)`{(_, _)} : {a, b} (SignedCmp b, SignedCmp a) => - (a, b) -> (a, b) -> Bit +(<$)`{(_, _)} : {a, b} (SignedCmp b, SignedCmp a) => (a, b) -> (a, b) -> Bit (<$)`{{}} : {} -> {} -> Bit -(<$)`{{x : _, y : _}} : {a, b} (SignedCmp b, SignedCmp a) => - {x : a, y : b} -> {x : a, y : b} -> Bit +(<$)`{{x : _, y : _}} : + {a, b} (SignedCmp b, SignedCmp a) => {x : a, y : b} -> {x : a, y : b} -> Bit [error] at instance.icry:118:4--118:8: • Type `Float ?m ?n` does not support signed comparisons. @@ -452,8 +447,7 @@ number`{rep = Bit} : {n} (1 >= n) => Bit [error] at instance.icry:123:4--123:10: Ambiguous numeric type: type argument 'val' of 'number' -number`{rep = Z _} : {n, m} (m >= 1 + n, m >= 1, fin m, fin n) => - Z m +number`{rep = Z _} : {n, m} (m >= 1 + n, m >= 1, fin m, fin n) => Z m number`{rep = [_]_} : {n, m} (m >= width n, fin m, fin n) => [m] [error] at instance.icry:126:4--126:10: @@ -501,9 +495,8 @@ number`{rep = [_]_} : {n, m} (m >= width n, fin m, fin n) => [m] ?m is type argument 'val' of 'number' at instance.icry:130:4--130:10 ?a is type wildcard (_) at instance.icry:130:23--130:24 ?b is type wildcard (_) at instance.icry:130:30--130:31 -number`{rep = Float _ _} : {n, m, i} (ValidFloat m i, - Literal n (Float m i)) => - Float m i +number`{rep = Float _ _} : + {n, m, i} (ValidFloat m i, Literal n (Float m i)) => Float m i [error] at instance.icry:132:4--132:10: • `?m` is not a valid literal of type `Box ?a` @@ -513,21 +506,17 @@ number`{rep = Float _ _} : {n, m, i} (ValidFloat m i, where ?m is type argument 'val' of 'number' at instance.icry:132:4--132:10 ?a is type wildcard (_) at instance.icry:132:22--132:23 -fromToLessThan`{a = Bit} : {n, m} (2 >= m, m >= n, fin n) => - [m - n] -fromToLessThan`{a = Integer} : {n, m} (m >= n, fin n) => - [m - n]Integer -fromToLessThan`{a = Rational} : {n, m} (m >= n, fin n) => - [m - n]Rational -fromToLessThan`{a = [_]} : {n, m, i} (i >= width (max 1 m - 1), - m >= n, fin i, fin m, fin n) => - [m - n][i] -fromToLessThan`{a = Z _} : {n, m, i} (i >= 1, i >= m, m >= n, - fin i, fin m, fin n) => - [m - n](Z i) -fromToLessThan`{a = [_]_} : {n, m, i, a} (LiteralLessThan m ([i]a), - m >= n, fin n) => - [m - n][i]a +fromToLessThan`{a = Bit} : {n, m} (2 >= m, m >= n, fin n) => [m - n] +fromToLessThan`{a = Integer} : {n, m} (m >= n, fin n) => [m - n]Integer +fromToLessThan`{a = Rational} : {n, m} (m >= n, fin n) => [m - n]Rational +fromToLessThan`{a = [_]} : + {n, m, i} + (i >= width (max 1 m - 1), m >= n, fin i, fin m, fin n) => + [m - n][i] +fromToLessThan`{a = Z _} : + {n, m, i} (i >= 1, i >= m, m >= n, fin i, fin m, fin n) => [m - n](Z i) +fromToLessThan`{a = [_]_} : + {n, m, i, a} (LiteralLessThan m ([i]a), m >= n, fin n) => [m - n][i]a [error] at instance.icry:140:4--140:18: • Type `?a -> ?b` does not contain all literals below `?m`. @@ -566,7 +555,8 @@ fromToLessThan`{a = [_]_} : {n, m, i, a} (LiteralLessThan m ([i]a), ?m is type argument 'bound' of 'fromToLessThan' at instance.icry:143:4--143:18 [error] at instance.icry:144:4--144:18: - • Type `{x : ?a, y : ?b}` does not contain all literals below `?m`. + • Type `{x : ?a, y : ?b}` + does not contain all literals below `?m`. arising from use of expression fromToLessThan at instance.icry:144:4--144:18 @@ -574,9 +564,10 @@ fromToLessThan`{a = [_]_} : {n, m, i, a} (LiteralLessThan m ([i]a), ?m is type argument 'bound' of 'fromToLessThan' at instance.icry:144:4--144:18 ?a is type wildcard (_) at instance.icry:144:27--144:28 ?b is type wildcard (_) at instance.icry:144:34--144:35 -fromToLessThan`{a = Float _ _} : {n, m, i, j} (ValidFloat i j, - LiteralLessThan m (Float i j), m >= n, fin n) => - [m - n](Float i j) +fromToLessThan`{a = Float _ _} : + {n, m, i, j} + (ValidFloat i j, LiteralLessThan m (Float i j), m >= n, fin n) => + [m - n](Float i j) [error] at instance.icry:146:4--146:18: • Type `Box ?a` does not contain all literals below `?m`. diff --git a/tests/regression/negshift.icry b/tests/regression/negshift.icry index 4c631a52..12bc6897 100644 --- a/tests/regression/negshift.icry +++ b/tests/regression/negshift.icry @@ -1,4 +1,4 @@ :l negshift.cry :set tests=1000 :check -:prove \ No newline at end of file +:prove diff --git a/tests/regression/rec-update.icry.stdout b/tests/regression/rec-update.icry.stdout index 48055616..6da94fc6 100644 --- a/tests/regression/rec-update.icry.stdout +++ b/tests/regression/rec-update.icry.stdout @@ -1,7 +1,7 @@ Loading module Cryptol Loading module Cryptol Loading module Main -[{x = 0x02, y = True}, {x = 0x03, y = True}, {x = 0x04, y = False}, - {x = 0x05, y = False}] -[{x = 0x07, y = True}, {x = 0x08, y = True}, {x = 0x09, y = False}, - {x = 0x0a, y = False}] +[{x = 0x02, y = True}, {x = 0x03, y = True}, + {x = 0x04, y = False}, {x = 0x05, y = False}] +[{x = 0x07, y = True}, {x = 0x08, y = True}, + {x = 0x09, y = False}, {x = 0x0a, y = False}] diff --git a/tests/regression/reference.cry b/tests/regression/reference.cry new file mode 100644 index 00000000..ec68e836 --- /dev/null +++ b/tests/regression/reference.cry @@ -0,0 +1,12 @@ +import Cryptol::Reference as Ref + +// NB, using subtraction here because is is not commutative or associative + +property foldl_eq (z:Integer) (xs:[10]Integer) = + foldl (-) z xs == Ref::foldl (-) z xs + +property scanl_eq (z:Integer) (xs:[10]Integer) = + scanl (-) z xs == Ref::scanl (-) z xs + +property iterate_eq (z:Integer) (i:[8]) = + (iterate (\x -> x + 1) z)@i == (Ref::iterate (\x -> x + 1) z)@i diff --git a/tests/regression/reference.icry b/tests/regression/reference.icry new file mode 100644 index 00000000..d04fa9c6 --- /dev/null +++ b/tests/regression/reference.icry @@ -0,0 +1,10 @@ +:l reference.cry + +:set tests=1000 +:check + +:set prover=sbv-z3 +:prove + +:set prover=w4-z3 +:prove diff --git a/tests/regression/reference.icry.stdout b/tests/regression/reference.icry.stdout new file mode 100644 index 00000000..35dfdba3 --- /dev/null +++ b/tests/regression/reference.icry.stdout @@ -0,0 +1,22 @@ +Loading module Cryptol +Loading module Cryptol +Loading module Cryptol::Reference +Loading module Main +property foldl_eq Using random testing. +Testing... Passed 1000 tests. +property scanl_eq Using random testing. +Testing... Passed 1000 tests. +property iterate_eq Using random testing. +Testing... Passed 1000 tests. +:prove foldl_eq + Q.E.D. +:prove scanl_eq + Q.E.D. +:prove iterate_eq + Q.E.D. +:prove foldl_eq + Q.E.D. +:prove scanl_eq + Q.E.D. +:prove iterate_eq + Q.E.D. diff --git a/tests/regression/repl-decls.icry b/tests/regression/repl-decls.icry new file mode 100644 index 00000000..ed0613d9 --- /dev/null +++ b/tests/regression/repl-decls.icry @@ -0,0 +1,42 @@ +let x -<- y = x - y; infixl 5 -<-; let (-<-) : Integer -> Integer -> Integer +let x ->- y = x - y; infixr 5 ->-; let (->-) : Integer -> Integer -> Integer + +42 -<- 10 -<- 100 +42 ->- 10 ->- 100 +42 ->- 10 -<- 100 + +let even x = if x == 0 then True else odd (x-1);\ +let odd x = if x == 0 then False else even (x-1) + +:t even +:t odd + +even 5 +even 4 + +odd 5 +odd 6 + +let even' : Integer -> Bool;\ +let even' x = if x == 0 then True else odd' (x-1);\ +let odd' x = if x == 0 then False else even' (x-1) + +:t even' +:t odd' + +even' 5 +even' 4 + +odd' 5 +odd' 6 + +type X n = [n]Integer +take [1...] : X 42 + +type constraint CS t = (Ring t, Logic t, Integral t) + +let f : {a} CS a => a -> Integer;\ +let f x = [1..100]@( (x + fromInteger 5) && fromInteger `0x1f) + +:t f +f 0x1234 diff --git a/tests/regression/repl-decls.icry.stdout b/tests/regression/repl-decls.icry.stdout new file mode 100644 index 00000000..c1e73a72 --- /dev/null +++ b/tests/regression/repl-decls.icry.stdout @@ -0,0 +1,27 @@ +Loading module Cryptol +-68 +132 + +[error] at repl-decls.icry:6:4--6:7 and repl-decls.icry:6:11--6:14 + The fixities of + • (->-) (precedence 5, right-associative) + • (-<-) (precedence 5, left-associative) + are not compatible. + You may use explicit parentheses to disambiguate. +even : {a} (Eq a, Ring a, Literal 1 a) => a -> Bit +odd : {a} (Eq a, Ring a, Literal 1 a) => a -> Bit +False +True +True +False +even' : Integer -> Bool +odd' : Integer -> Bit +False +True +True +False +[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, 33, 34, + 35, 36, 37, 38, 39, 40, 41, 42] +f : {a} (Ring a, Logic a, Integral a) => a -> Integer +26 diff --git a/tests/regression/safety.icry.stdout b/tests/regression/safety.icry.stdout index 796324d6..1805f17a 100644 --- a/tests/regression/safety.icry.stdout +++ b/tests/regression/safety.icry.stdout @@ -3,7 +3,7 @@ Counterexample (\x -> assert x "asdf" "asdf") False ~> ERROR Run-time error: asdf -- Backtrace -- -Cryptol::error called at Cryptol:998:41--998:46 +Cryptol::error called at Cryptol:1041:41--1041:46 Cryptol::assert called at safety.icry:3:14--3:20 ::it called at safety.icry:3:7--3:37 Counterexample diff --git a/tests/regression/sort.icry.stdout b/tests/regression/sort.icry.stdout index 56c3e216..ae5fb5ab 100644 --- a/tests/regression/sort.icry.stdout +++ b/tests/regression/sort.icry.stdout @@ -4,10 +4,10 @@ Loading module Cryptol (18, 8), (12, 9), (8, 10), (6, 11), (6, 12), (8, 13), (12, 14), (18, 15), (3, 16), (13, 17), (2, 18), (16, 19), (9, 20), (4, 21), (1, 22)] -[(0, 0), (1, 1), (1, 22), (2, 5), (2, 18), (3, 7), (3, 16), (4, 2), - (4, 21), (6, 11), (6, 12), (8, 10), (8, 13), (9, 3), (9, 20), - (12, 9), (12, 14), (13, 6), (13, 17), (16, 4), (16, 19), (18, 8), - (18, 15)] +[(0, 0), (1, 1), (1, 22), (2, 5), (2, 18), (3, 7), (3, 16), + (4, 2), (4, 21), (6, 11), (6, 12), (8, 10), (8, 13), (9, 3), + (9, 20), (12, 9), (12, 14), (13, 6), (13, 17), (16, 4), (16, 19), + (18, 8), (18, 15)] [(1, 22), (4, 21), (9, 20), (16, 19), (2, 18), (13, 17), (3, 16), (18, 15), (12, 14), (8, 13), (6, 12), (6, 11), (8, 10), (12, 9), (18, 8), (3, 7), (13, 6), (2, 5), (16, 4), (9, 3), (4, 2), (1, 1), diff --git a/tests/regression/specialize.icry.stdout b/tests/regression/specialize.icry.stdout index fea323d5..650807c7 100644 --- a/tests/regression/specialize.icry.stdout +++ b/tests/regression/specialize.icry.stdout @@ -10,32 +10,31 @@ specialize::top where /* Not recursive */ specialize::f : (Bit, Bit) -> (Bit, Bit) - specialize::f = \ (__p1 : (Bit, Bit)) -> - (x, y) - where - /* Not recursive */ - y : Bit - y = __p1 .1 /* of 2 */ - - /* Not recursive */ - x : Bit - x = __p1 .0 /* of 2 */ - - - + specialize::f = + \(__p1 : (Bit, Bit)) -> + (x, y) + where + /* Not recursive */ + y : Bit + y = __p1.1 /* of 2 */ + + /* Not recursive */ + x : Bit + x = __p1.0 /* of 2 */ + + /* Not recursive */ specialize::top : (Bit, Bit) -> (Bit, Bit) - specialize::top = \ (__p0 : (Bit, Bit)) -> - specialize::f (x, y) - where - /* Not recursive */ - y : Bit - y = __p0 .1 /* of 2 */ - - /* Not recursive */ - x : Bit - x = __p0 .0 /* of 2 */ - - - + specialize::top = + \(__p0 : (Bit, Bit)) -> + specialize::f (x, y) + where + /* Not recursive */ + y : Bit + y = __p0.1 /* of 2 */ + + /* Not recursive */ + x : Bit + x = __p0.0 /* of 2 */ + diff --git a/tests/regression/superclass.icry.stdout b/tests/regression/superclass.icry.stdout index d8ce8b3b..991ff7b3 100644 --- a/tests/regression/superclass.icry.stdout +++ b/tests/regression/superclass.icry.stdout @@ -18,8 +18,7 @@ Symbols (fromInteger 42 + zero) : {a} (Ring a) => a (trunc (recip (fromInteger 5))) : {a} (Round a) => Integer -(\x -> x < fromInteger (floor (recip x))) : {a} (Round a) => - a -> Bit +(\x -> x < fromInteger (floor (recip x))) : {a} (Round a) => a -> Bit (\x -> x == zero /. x) : {a} (Eq a, Field a) => a -> Bit (zero == ~zero) : {a} (Eq a, Logic a) => Bit (\x -> toInteger (x + zero)) : {a} (Integral a) => a -> Integer diff --git a/tests/regression/tc-errors.icry.stdout b/tests/regression/tc-errors.icry.stdout index c66ca812..03e4e534 100644 --- a/tests/regression/tc-errors.icry.stdout +++ b/tests/regression/tc-errors.icry.stdout @@ -81,21 +81,21 @@ Loading module Main Loading module Cryptol Loading module Main -[error] at tc-errors-5.cry:2:5--2:7: +[error] at tc-errors-5.cry:2:1--2:7: Inferred type is not sufficiently polymorphic. - Quantified variable: a`809 + Quantified variable: a`899 cannot match type: [0]?a When checking the type of 'Main::f' where ?a is type of sequence member at tc-errors-5.cry:2:5--2:7 - a`809 is signature variable 'a' at tc-errors-5.cry:1:6--1:7 + a`899 is signature variable 'a' at tc-errors-5.cry:1:6--1:7 Loading module Cryptol Loading module Main -[error] at tc-errors-6.cry:4:7--4:8: +[error] at tc-errors-6.cry:4:3--4:8: The type ?a is not sufficiently polymorphic. - It cannot depend on quantified variables: b`813 + It cannot depend on quantified variables: b`903 When checking the type of 'g' where ?a is the type of 'x' at tc-errors-6.cry:1:3--1:4 - b`813 is signature variable 'b' at tc-errors-6.cry:3:8--3:9 + b`903 is signature variable 'b' at tc-errors-6.cry:3:8--3:9