pax_global_header00006660000000000000000000000064152463312160014515gustar00rootroot0000000000000052 comment=0cc48eb5eb74f682020121225bc38344ea9052f2 ocp-indent-1.10.0/000077500000000000000000000000001524633121600136345ustar00rootroot00000000000000ocp-indent-1.10.0/.git-blame-ignore-revs000066400000000000000000000001541524633121600177340ustar00rootroot00000000000000# Initial formatting commit following the @fmt rules introduction 3b9490d31931ad11a53188324bbb791a7561cf8f ocp-indent-1.10.0/.github/000077500000000000000000000000001524633121600151745ustar00rootroot00000000000000ocp-indent-1.10.0/.github/workflows/000077500000000000000000000000001524633121600172315ustar00rootroot00000000000000ocp-indent-1.10.0/.github/workflows/main.yml000066400000000000000000000022051524633121600206770ustar00rootroot00000000000000name: ocp-indent on: pull_request: push: jobs: build: strategy: fail-fast: false matrix: include: - os: windows-latest ocaml-compiler: 4.14.x - os: ubuntu-latest ocaml-compiler: 4.11.x - os: ubuntu-latest ocaml-compiler: 4.14.x - os: ubuntu-latest ocaml-compiler: 5.0.x - os: ubuntu-latest ocaml-compiler: 5.1.x - os: ubuntu-latest ocaml-compiler: 5.2.x - os: ubuntu-latest ocaml-compiler: 5.3.x runs-on: ${{ matrix.os }} steps: - name: Checkout code uses: actions/checkout@v3 - name: Use OCaml ${{ matrix.ocaml-compiler }} uses: ocaml/setup-ocaml@v3 with: ocaml-compiler: ${{ matrix.ocaml-compiler }} - run: opam install . --deps-only - run: opam exec -- dune build @install - run: opam install . --deps-only -t - run: opam exec -- dune runtest - run: opam exec -- dune build @fmt - run: opam config report - run: opam install . - run: opam exec ocp-indent --help ocp-indent-1.10.0/.gitignore000066400000000000000000000004271524633121600156270ustar00rootroot00000000000000.hgignore.in Makefile.config jbuild-ignore ocp-build.root* _obuild config.log config.status src/indentVersion.ml *~ version.ocp autom4te.cache aclocal.m4 man/man1/ src/.hgignore.in src/Makefile.extracted-from-jenga src/buildable_targets.list **/.fe.sexp _build .merlin *.install ocp-indent-1.10.0/.ocp-indent000066400000000000000000000077501524633121600157060ustar00rootroot00000000000000# -*- conf -*- # This is an example configuration file for ocp-indent # # Copy to the root of your project with name ".ocp-indent", customise, and # transparently get consistent indentation on all your ocaml source files. # Starting the configuration file with a preset ensures you won't fallback to # definitions from "~/.ocp/ocp-indent.conf". # These are `normal`, `apprentice` and `JaneStreet` and set different defaults. normal # # INDENTATION VALUES # # Number of spaces used in all base cases, for example: # let foo = # ^^bar base = 2 # Indent for type definitions: # type t = # ^^int type = 2 # Indent after `let in` (unless followed by another `let`): # let foo = () in # ^^bar in = 0 # Indent after `match/try with` or `function`: # match foo with # ^^| _ -> bar with = 0 # Indent for clauses inside a pattern-match (after the arrow): # match foo with # | _ -> # ^^^^bar # the default is 2, which aligns the pattern and the expression match_clause = 4 # this is non-default # Indentation for items inside extension nodes: # [%% id.id # ^^^^contents ] # [@@id # ^^^^foo # ] ppx_stritem_ext = 2 # When nesting expressions on the same line, their indentation are in # some cases stacked, so that it remains correct if you close them one # at a line. This may lead to large indents in complex code though, so # this parameter can be used to set a maximum value. Note that it only # affects indentation after function arrows and opening parens at end # of line. # # for example (left: `none`; right: `4`) # let f = g (h (i (fun x -> # let f = g (h (i (fun x -> # x) # x) # ) # ) # ) # ) max_indent = 4 # # INDENTATION TOGGLES # # Wether the `with` parameter should be applied even when in a sub-block. # Can be `always`, `never` or `auto`. # if `always`, there are no exceptions # if `auto`, the `with` parameter is superseded when seen fit (most of the time, # but not after `begin match` for example) # if `never`, `with` is only applied if the match block starts a line. # # For example, the following is not indented if set to `always`: # let f = function # ^^| Foo -> bar strict_with = never # Controls indentation after the `else` keyword. `always` indents after the # `else` keyword normally, like after `then`. # If set to `never', the `else` keyword won't indent when followed by a newline. # `auto` indents after `else` unless in a few "unclosable" cases (`let in`, # `match`...). # # For example, with `strict_else=never`: # if cond then # foo # else # bar; # baz # `never` is discouraged if you may encounter code like this example, # because it hides the scoping error (`baz` is always executed) strict_else = always # Ocp-indent will normally try to preserve your in-comment indentation, as long # as it respects the left-margin or starts with `(*\n`. Setting this to `true` # forces alignment within comments. strict_comments = false # Toggles preference of column-alignment over line indentation for most # of the common operators and after mid-line opening parentheses. # # for example (left: `false'; right: `true') # let f x = x # let f x = x # + y # + y align_ops = true # Function parameters are normally indented one level from the line containing # the function. This option can be used to have them align relative to the # column of the function body instead. # if set to `always`, always align below the function # if `auto`, only do that when seen fit (mainly, after arrows) # if `never`, no alignment whatsoever # # for example (left: `never`; right: `always or `auto) # match foo with # match foo with # | _ -> some_fun # | _ -> some_fun # ^^parameter # ^^parameter align_params = auto # # SYNTAX EXTENSIONS # # You can also add syntax extensions (as per the --syntax command-line option): # syntax = mll lwt ocp-indent-1.10.0/CHANGELOG.md000066400000000000000000000155231524633121600154530ustar00rootroot00000000000000## 1.10.0 + Bump OCaml lower bound to 4.11 (#343, @NathanReb) + Add explicit support for effect syntax (#342, @NathanReb) + Remove support for legacy camlp4 extensions that was causing misidentation of code using some predefined identifiers (`TEST`, `BENCH`, `IFDEF`) (#345, @NathanReb) + Add support for starred style comments (#347, @NathanReb) + Add explicit support for labeled tuples syntax (#349, @NathanReb) + Fix `strict_with` so it applies to extensible variant types in the same way it applies to variant types (#350, @NathanReb) + Fix a bug where `-` would be rejected as `ocp-indent` input argument instead of being interpreted as `stdin` (#351, @NathanReb) + Update to cmdliner 2 and install completion scripts for common shells (#351, @NathanReb) + Add explicit support for external types (#353, @NathanReb) + Add explicit support for new 5.5 let in constructs: `let type`, `let external`, `let class` (#354, @NathanReb) + Add `--strict` flag to make warnings fatal and parsing stricter (#356, @NathanReb) + Add `--check` flag and corresponding check mode which does not print indented version but instead succeed if the input is already correctly indented and fails otherwise. (#357, @NathanReb) + Add `?filename` argument to `Nstream` functions to allow properly setting the filename for parsing errors. (#357, @NathanReb) ## 1.9.0 + Fix detection of let vs letin after a struct (#324, @Julow) + Treat `|>` as a monadic operator (#322, @nberth) + Prevent Args out of range error in ocp-indent-buffer (#327, @bcc32) + Fix "Missing ‘lexical-binding’ cookie" warning in Emacs (#329, @nojb) + Fix a bug where ocp-indent translate LF to CRLF when run on Windows instead of preserving the input's newlines. (#334, @nojb) + Add `ocp-indent-gen-rules` to support `dune fmt` like workflow with ocp-indent (#333, @NathanReb) ## 1.8.1 * tiny API change to help with the detection of top-level phrase boundaries * fixed a bug with end of comment detection in some cases (esp. related to cinaps) * tweaks for better indentation within cinaps comments * lowered priority of algebraic attributes in expressions (`[@...]`) to better match the actual meaning. ## 1.8.0 * compatibility with OCaml 4.08.0 (new attributes, monadic lets...) * lots of smaller indentation fixes (module types, empty variants...) * more reliable "inplace" mode (preserving symlinks and permissions) * XDG compatibility (e.g. config file below `~/.config`) * support for "cinaps" comments (indent as code comments that start with `(*$`) * API: `IndentBlock.is_at_top` now returns true for top-level expressions ## 1.7.0 * lots of small fixes * better handling of attributes and extension points * better handling of GADT definitions * fixed a stack-overflow on extremely large files * indent the same (1 step) after `let f = fun x ->` and `let f =\n fun x ->` * build using dune ## 1.6.1 * fixes related to ppx extensions * fixed regression on indentation within record types ## 1.6.0 * fixes some cases of comments * supports new cases of ppx * fixed cases of unstable indentation within records * supports local exceptions * fixed handling of polymorphic methods * uses cmdliner 1.0.0 ## 1.5.3 * fixes on nested try-with and some cases of comments * better alignment of stand-alone semicolons in records * improved emacs and vim scripts * better indentation within extension blocks ## 1.5.2 * small emacs binding fix * compatibility with cmdliner 0.9.8 ## 1.5.1 * generic handling of ppx keywords * much improved vim binding * changed installation location of vim bindings (to share/ocp-indent/vim/indent) for easier autoload * don't increase indentation level for sequences of try..with * support for '[@' * restore back-alignment of '&&', '||' after 'if' and 'when' * support for extensible variant types ## 1.5 * new vim binding * support for ppx lwt keywords * fixed indentation at BOF and EOF in some cases * back-alignment of '&&' and '||' disabled * tweaks to functor, struct and module indentation * support for ppx attributes * lots of fixes and tweaks ## 1.4.1 * OCaml 4.01.0 warnings fix * fixed indent of lwt try/finally * sort Jane Street tests by priority * added support for BENCH syntax * added support for the new {xx| |xx} quotation syntax * emacs mode: cleaner loading * emacs mode: fixed the 'syntax' option * emacs mode: workaround an auto-complete.el display bug * emacs and vim modes: install in editor-specific directories * refactored build system. Install through opam-installer, register libs as ocamlfind sub-packages ## 1.4.0 * license change: lessening the GPL to make ocp-indent easier to use as a library * removed indent by default after most common operators (when align_ops is set) * removed extra-indent in some pattern-matching cases * fixed a few bugs related to records, lazy as pattern, "module with" * added support for the cstruct syntax extension * fixed Makefile to properly install all cmi files, working around an ocp-build bug ## 1.3.2 * bug-fix release: object types, module type of, first line, etc. ## 1.3.1 * optimised functional operators on OCaml 4.00 * fixed a bug in phrase boundary detection ## 1.3.0 * Large API rewrite, offering much more flexibility and functionality * Still some bug fixes (comments at end, nested ocamldoc tags, etc.) * Man-page fixes (thanks to Kaustuv Chaudhuri) * Temporarily disabled the non-functional state-marshalling function * Emacs mode: auto-disabling indent-tabs-mode by default, it's not compatible anyways. ## 1.2.2 * Fixed critical bug with the parsing of the --syntax option * a few indent fixes (functor sigs, comments in expressions) ## 1.2.1 * Fixed bugs with GADTs, comments at end of modules * Fixed compilation with OCaml trunk (warnings as errors) * New vim script, contributed by Jonathan Derque * New option "strict_else" to allow unindenting after else ## 1.2.0 * Lots of fixes * Switched most operators and constructs with parentheses to column aligned by default (can be disabled with option align_ops) * Better handling of records * Some code cleanup (record fields with meaningful names) * Documentation and manpage (now relying on cmdliner) * Added an option (max_indent) to limit over-indent in the most annoying cases * Syntax extensions can now be enabled from the configuration files ## 1.1.0 * Small fixes, stabilised ocamldoc indentation * Support for configuration files, either user or project-wide ## 1.0.2 * Supporting indentation of ocamldoc. In particular, code within ocamldoc blocks {[...]} should be automatically indented * Fixed the emacs mode not to set the mark * A few new configuration options (strict_with, strict_comments, align_params) * A few tweaks and improvements (better empty line indent, etc.) * Bugfixes (#43, #47) ## 1.0.1 * Indentation of comments now follows ocamldoc conventions properly * Partial indent adapts more closely to manual indentation * Various small fixes (indent on empty lines, freeform comments...) ocp-indent-1.10.0/CONTRIBUTING.md000066400000000000000000000054771524633121600161020ustar00rootroot00000000000000# Contributing to `ocp-indent` ## Setting up your dev environment You can quickly setup your `ocp-indent` dev environement by running: ``` git clone git@github.com:OCamlPro/ocp-indent.git cd ocp-indent opam switch create ./ --deps-only -t ``` This will clone the project and create a local opam switch with all of the project's dependencies required to build it and run the tests. ## Building `ocp-indent` The project uses dune so you can build it using the usual: ``` dune build ``` ## Project layout All our source code leaves in `src/`: - `ocp-indent-lib` contains the core ocp-indent logic - `ocp-indent-lexer` contains our simplified OCaml lexer - `ocp-indent` is the CLI wrapper around the lib and parser - `ocp-indent-utils` contains small helpers and stdlib extensions - `ocp-indent-dynlink` is the plugin loading lib for `--load-pkgs` and `--load-mods` - `ocp-indent-gen-rules` is a small executable used to generate dune formatting rules with `ocp-indent` The two most important modules are `IndentBlock` and `IndentPrinter`. `IndentPrinter` runs through the lexer token stream and calculates the indentation for each new line that appears. This is done by asking `indentBlock` to calculate a structured "path" to the current token. This path reflect the OCaml structure of the code and is used to calculate the indentation level of the current token if it sits at the begining of a line. Most changes usually go in either of those modules which makes for the core of the tool's logic. ## Tests You can run the full test suite with: ``` dune runtest ``` All of our tests are dune cram tests (you can learn more [here](https://dune.readthedocs.io/en/stable/reference/cram.html)). The main executable tests are separated between three folders: - `tests/passing`: for regular tests, running on all platforms - `tests/unix-only`: for tests that cannot be run on Windows - `tests/failing`: for tests that document known bugs. Those have their own [README](tests/failing/README.md) if you ever need to know more. `ocp-indent-gen-rules` has its own test folder in `tests/ocp-indent-gen-rules`. ## Formatting The code is indented using, well, ocp-indent. Dune files are formatted as well. Formatting is checked by our CI so remember to run: ``` dune build @fmt ``` to ensure your patches are correctly formatted. If the command reports a diff, you can run `dune promote` to update the relevant files. ## Submitting contributions We expect the usual github workflow for external contributions. Feel free to open a PR directly for simple bug fixes, typos and other consensual changes. When submitting a bug fix, please try to add a regression tests alongside it if it's reasonably easy to write. For more involved changes/features, we suggest that you start by opening an issue so you can discuss with the maintainers team the best way to proceed. ocp-indent-1.10.0/LICENSE000066400000000000000000000645711524633121600146560ustar00rootroot00000000000000Ocp-Indent is distributed under the terms of the GNU Lesser General Public License (LGPL) version 2.1 (included below). As a special exception to the GNU Lesser General Public License, you may link, statically or dynamically, a "work that uses ocp-indent" with a publicly distributed version of ocp-indent to produce an executable file containing portions of ocp-indent, and distribute that executable file under terms of your choice, without any of the additional requirements listed in clause 6 of the GNU Lesser General Public License. By "a publicly distributed version of ocp-indent", we mean either the unmodified ocp-indent as distributed by OCamlPro, or a modified version of the ocp-indent that is distributed under the conditions defined in clause 2 of the GNU Lesser General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU Lesser General Public License. ---------------------------------------------------------------------- GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. one line to give the library's name and an idea of what it does. Copyright (C) year name of author This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. signature of Ty Coon, 1 April 1990 Ty Coon, President of Vice That's all there is to it! -------------------------------------------------- ocp-indent-1.10.0/README.md000066400000000000000000000124071524633121600151170ustar00rootroot00000000000000A simple tool and library to indent OCaml programs, developed and maintained by OCamlPro (Louis Gesbert). License: LGPL 2.1 with linking exception ## Installation ### Using OPAM You can install `ocp-indent` using [OPAM](https://opam.ocaml.org/): ```bash opam install ocp-indent ``` ## Usage The above installation step copies elisp scripts to `/share/emacs/site-lisp/` and vim scripts to `/share/ocp-indent/vim/`. You then need to load them in the editor of your choice to automatically use ocp-indent. Installing OPAM package [`user-setup`](https://opam.ocaml.org/packages/user-setup/) will trigger automatic configuration for popular editors (emacs and vim currently, but more are in the works). If you prefer to handle your configuration manually, read on. ### Emacs Run the following command to setup tuareg-mode or caml-mode to use `ocp-indent` for indentation: ```bash echo '(load-file "'"$(opam config var share)"'/emacs/site-lisp/ocp-indent.el")' >>~/.emacs ``` The `tab` key should now reindent the current line using ocp-indent. ### Vim Use the following command to tell Vim to use `ocp-indent` to indent OCaml code: ```bash echo 'set rtp^="'"$(opam config var ocp-indent:share)"'/vim"' >>~/.vimrc ``` Automatic indentation as you type should take place, depending on your configuration. Use `==` to reindent the current line, and `=G` to reindent until the end of buffer. ### NeoVim Use the following command to tell NeoVim to `ocp-indent` to indent OCaml code: ```bash echo 'vim.opt.rtp:prepend("'"$(opam var ocp-indent:share)"'/vim")' >> ~/.config/nvim/init.lua ``` Automatic indentation as you type should take place, depending on your configuration. Use `==` to reindent the current line, and `=G` to reindent until the end of buffer. ### Other editors As `ocp-indent` is a command-line tool, you can easily integrate it with other editors. ```bash ocp-indent > ``` You can also tell it to indent only subsets of lines, and to output only the indentation level: ```bash ocp-indent --lines - --numeric ``` ## Configuration options By default, `ocp-indent` comes with sensible default parameters. However, you can customize some of the indentation options using command-line arguments. For more details, see: ```bash ocp-indent --help ``` ### Configuration file The same parameters can be defined in a configuration file, allowing for user defaults and per-project parameters. The latter is particularly convenient to transparently ensure consistency in projects with many contributors, without requiring them to change their settings in any way (except that, obviously, they need to use ocp-indent !). If a `.ocp-indent` file is found in the current directory or its ancestors, it overrides definitions from `$XDG_CONFIG_HOME/ocp/ocp-indent.conf`, `~/.ocp/ocp-indent.conf` and the built-in default. The command-line can of course still be used to override parameters defined in the files. Have a look at ocp-indent's own [`.ocp-indent`](.ocp-indent) file for an example. ### In-file configuration There is no built-in support for in-file configuration directives. Yet, some editors already provide these features, and with emacs, starting your file with a line like: ``` (* -*- ocp-indent-config: in=2 -*- *) ``` will enable you to have the indentation after `in` setup to 2 locally on this file. ## Autoformat files with ocp-indent in dune `dune fmt` or `dune build @fmt` can be used to format dune and OCaml files with `ocamlformat`. This can prove a convenient workflow for new projects so we made it available to `ocp-indent` users as well. First you need to disable the default formatting rules for OCaml source files by adding the following to your `dune-project`: ```dune (formatting (enabled_for dune)) ``` `dune fmt` won't try to format your OCaml files with `ocamlformat` from there. The `ocp-indent` formatting rules need to be enabled on a per-directory basis by adding the following dune rules to the `dune` file: ```dune ;; Auto indent files with `dune build @fmt` (subdir run (dynamic_include ../rules/dune.ocp-indent)) (subdir rules (rule (deps (glob_files ../*.{ml,mli})) (target dune.ocp-indent) (action (run ocp-indent-gen-rules -o %{target})))) ``` `ocp-indent-gen-rules` will generate promotion based formatting rules for each `.ml` and `.mli` files in this folder. You can simply use the same `dune build @fmt`/`dune promote` workflow as with ocamlformat. ## How does it compare to tuareg ? We've run some benchmarks on real code-bases and the result is quite conclusive. Keep in mind that most of existing source files are either indented manually or following tuareg standards. You can see the results [here](http://htmlpreview.github.com/?https://github.com/AltGr/ocp-indent-tests/blob/master/status.html). Moreover, as `ocp-indent` has a deep understanding of the OCaml syntax it shines on specific cases. See for instance the collection of unit-tests [here](https://github.com/OCamlPro/ocp-indent/tree/master/tests/passing). The currently failing tests can be seen [here](http://htmlpreview.github.com/?https://github.com/OCamlPro/ocp-indent/blob/master/tests/failing.html). ## Contributing If you'd like to contribute to `ocp-indent`, please head over our [contributing guide](CONTRIBUTING.md). ocp-indent-1.10.0/VERSION000066400000000000000000000000061524633121600147000ustar00rootroot000000000000001.8.1 ocp-indent-1.10.0/doc/000077500000000000000000000000001524633121600144015ustar00rootroot00000000000000ocp-indent-1.10.0/doc/dune000066400000000000000000000002421524633121600152550ustar00rootroot00000000000000(rule (targets ocp-indent.1) (action (with-stdout-to %{targets} (run %{bin:ocp-indent} --help=groff)))) (install (section man) (files ocp-indent.1)) ocp-indent-1.10.0/doc/ocp-indent.md000066400000000000000000000121131524633121600167610ustar00rootroot00000000000000# ocp-indent A simple tool to indent OCaml programs Authors: Louis Gesbert (OCamlPro), Thomas Gazagnaire (OCamlPro), Jun Furuse License: LGPL 2.1 with linking exception ## Installation ### Using OPAM The simplest way to install `ocp-indent` is using [OPAM](http://opam.ocamlpro.com): ```bash opam install ocp-indent ``` ### By hand You can also compile and install `ocp-indent` from sources. You'll need `ocaml (>= 3.12.1)` and `ocp-build (>= 1.99.6-beta)`: ```bash ./configure make make install ``` If you use opam and want it installed alongside ocaml, you may want to use `./configure --prefix $(opam config var prefix)`. ## Usage The above installation step copies elisp scripts to `/share/emacs/site-lisp/` and vim scripts to `/share/ocp-indent/vim/`. You then need to load them in the editor of your choice to automatically use ocp-indent. Installing OPAM package [`user-setup`](https://opam.ocaml.org/packages/user-setup/user-setup.0.3/) will trigger automatic configuration for popular editors (emacs and vim currently, but more are in the works). If you prefer to handle your configuration manually, read on. ### Emacs Run the following command to setup tuareg-mode or caml-mode to use `ocp-indent` for indentation: ```bash echo '(load-file "'"$(opam config var share)"'/emacs/site-lisp/ocp-indent.el")' >>~/.emacs ``` The `tab` key should now reindent the current line using ocp-indent. ### Vim Use the following command to tell Vim to use `ocp-indent` to indent OCaml code: ```bash echo 'set rtp^="'"$(opam config var ocp-indent:share)"'/vim"' >>~/.vimrc ``` Automatic indentation as you type should take place, depending on your configuration. Use `==` to reindent the current line, and `=G` to reindent until the end of buffer. ### Other editors As `ocp-indent` is a command-line tool, you can easily integrate it with other editors. ```bash ocp-indent > ``` You can also tell it to indent only subsets of lines, and to output only the indentation level: ```bash ocp-indent --lines - --numeric ``` ## Configuration options By default, `ocp-indent` comes with sensible default parameters. However, you can customize some of the indentation options using command-line arguments. For more details, see: ```bash ocp-indent --help ``` ### Configuration file The same parameters can be defined in a configuration file, allowing for user defaults and per-project parameters. The latter is particularly convenient to transparently ensure consistency in projects with many contributors, without requiring them to change their settings in any way (except that, obviously, they need to use ocp-indent !). If a `.ocp-indent` file is found in the current directory or its ancestors, it overrides definitions from `$XDG_CONFIG_HOME/ocp/ocp-indent.conf`, `~/.ocp/ocp-indent.conf` and the built-in default. The command-line can of course still be used to override parameters defined in the files. Have a look at ocp-indent's own [`.ocp-indent`](.ocp-indent) file for an example. ### In-file configuration There is no built-in support for in-file configuration directives. Yet, some editors already provide these features, and with emacs, starting your file with a line like: ``` (* -*- ocp-indent-config: in=2 -*- *) ``` will enable you to have the indentation after `in` setup to 2 locally on this file. ## How does it compare to tuareg ? We've run some benchmarks on real code-bases and the result is quite conclusive. Keep in mind that most of existing source files are either indented manually or following tuareg standards. You can see the results [here](http://htmlpreview.github.com/?https://github.com/AltGr/ocp-indent-tests/blob/master/status.html). Moreover, as `ocp-indent` has a deep understanding of the OCaml syntax it shines on specific cases. See for instance the collection of unit-tests [here](https://github.com/OCamlPro/ocp-indent/tree/master/tests/passing). The currently failing tests can be seen [here](http://htmlpreview.github.com/?https://github.com/OCamlPro/ocp-indent/blob/master/tests/failing.html). ## Testing It's hard to deliver a great indenter without tests. We've built `ocp-indent` based on a growing collection of unit-tests. If you find an indentation bug, feel free to send us a code snippet that we will incorporate into our test suite. The tests are organized as follows: * `tests/passing` contains tests that are properly indented and should be left unchanged by ocp-indent. * `tests/failing` contains tests for which ocp-indent currently returns the results in `tests/failing-output`, hence `meld tests/failing{,-output}` should give an overview of currently known bugs (also available online [here](http://htmlpreview.github.com/?https://github.com/OCamlPro/ocp-indent/blob/master/tests/failing.html)). * `tests/test.sh` checks the current state against the reference state (checked into git). * `tests/test.sh --[git-]update` updates the current reference state. * See `tests/test.sh --help` for more Please make sure to run `make && tests/test.sh --git-update` before any commit, so that the repo always reflects the state of the program. ocp-indent-1.10.0/dune-project000066400000000000000000000001261524633121600161550ustar00rootroot00000000000000(lang dune 3.20) (name ocp-indent) (version 1.10.0) (formatting (enabled_for dune)) ocp-indent-1.10.0/ocp-indent.opam000066400000000000000000000036011524633121600165520ustar00rootroot00000000000000opam-version: "2.0" maintainer: "contact@ocamlpro.com" synopsis: "A simple tool to indent OCaml programs" description: """ Ocp-indent is based on an approximate, tolerant OCaml parser and a simple stack machine ; this is much faster and more reliable than using regexps. Presets and configuration options available, with the possibility to set them project-wide. Supports most common syntax extensions, and extensible for others. Includes: - An indentor program, callable from the command-line or from within editors - Bindings for popular editors - A library that can be directly used by editor writers, or just for fault-tolerant/approximate parsing. """ authors: [ "Louis Gesbert " "Thomas Gazagnaire " "Jun Furuse" ] homepage: "http://www.typerex.org/ocp-indent.html" bug-reports: "https://github.com/OCamlPro/ocp-indent/issues" license: "LGPL-2.1-only WITH OCaml-LGPL-linking-exception" tags: ["org:ocamlpro" "org:typerex"] dev-repo: "git+https://github.com/OCamlPro/ocp-indent.git" build: [ [ "dune" "build" "-p" name "-j" jobs "@install" "@runtest" {with-test} "@doc" {with-doc} ] [ "cmdliner" "install" "tool-completion" "--update-opam-install=ocp-indent.install" "ocp-indent" {os-family != "windows"} "ocp-indent.exe" {os-family = "windows"} "_build/" ] ] run-test: [ ["dune" "runtest" "-p" name "-j" jobs] ] depends: [ "ocaml" {>= "4.11"} "dune" {>= "3.20"} "cmdliner" {>= "2.0.0"} "ocamlfind" ] post-messages: [ "This package requires additional configuration for use in editors. Install package 'user-setup', or manually: * for Emacs, add these lines to ~/.emacs: (add-to-list 'load-path \"%{share}%/emacs/site-lisp\") (require 'ocp-indent) * for Vim, add this line to ~/.vimrc: set rtp^=\"%{share}%/ocp-indent/vim\" " {success & !user-setup:installed} ] ocp-indent-1.10.0/src/000077500000000000000000000000001524633121600144235ustar00rootroot00000000000000ocp-indent-1.10.0/src/ocp-indent-dynlink/000077500000000000000000000000001524633121600201315ustar00rootroot00000000000000ocp-indent-1.10.0/src/ocp-indent-dynlink/dune000066400000000000000000000006201524633121600210050ustar00rootroot00000000000000(library (name ocp_indent_dynlink) (public_name ocp-indent.dynlink) (wrapped false) (libraries findlib dynlink ocp-indent.lexer ocp-indent.utils)) ;; Auto indent files with `dune build @fmt` (subdir run (dynamic_include ../rules/dune.ocp-indent)) (subdir rules (rule (deps (glob_files ../*.{ml,mli})) (target dune.ocp-indent) (action (run ocp-indent-gen-rules -o %{target})))) ocp-indent-1.10.0/src/ocp-indent-dynlink/indentLoader.ml000066400000000000000000000042661524633121600231030ustar00rootroot00000000000000(**************************************************************************) (* *) (* All rights reserved. This file is distributed under the terms of the *) (* GNU Lesser General Public License version 2.1 with linking *) (* exception. *) (* *) (* TypeRex is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* Lesser GNU General Public License for more details. *) (* *) (**************************************************************************) module SS = Set.Make(String) let loaded = ref SS.empty let predicates = if Dynlink.is_native then [ "plugin" ; "native" ] else [ "plugin" ; "byte" ] let dynlink debug s = if debug then Format.eprintf "loading archive %s..@." s; try Dynlink.loadfile s with exc -> Format.eprintf "Error while linking %s : %s@." s (Printexc.to_string exc); raise exc let load_pkg debug pkg = if not (SS.mem pkg !loaded) then begin let d = Findlib.package_directory pkg in let archive = try Findlib.package_property predicates pkg "archive" with Not_found -> "" in let archives = Util.string_split ' ' archive in List.iter (fun arch -> if arch <> "" then let arch' = Findlib.resolve_path ~base:d arch in dynlink debug arch') archives; loaded:=SS.add pkg !loaded end let rec partition mods pkgs = function | [] -> List.rev pkgs, List.rev mods | `Mod m :: rest -> partition (m::mods) pkgs rest | `Pkg p :: rest -> partition mods (p::pkgs) rest let load ?(debug=false) l = let pkglist,mods = partition [] [] l in List.iter (dynlink debug) mods; let eff_pkglist = Findlib.package_deep_ancestors predicates pkglist in List.iter (load_pkg debug) eff_pkglist ocp-indent-1.10.0/src/ocp-indent-dynlink/indentLoader.mli000066400000000000000000000020261524633121600232440ustar00rootroot00000000000000(**************************************************************************) (* *) (* All rights reserved. This file is distributed under the terms of the *) (* GNU Lesser General Public License version 2.1 with linking *) (* exception. *) (* *) (* TypeRex is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* Lesser GNU General Public License for more details. *) (* *) (**************************************************************************) (** Dynlink of modules and finlib packages *) val load : ?debug:bool -> [`Mod of string | `Pkg of string ] list -> unit ocp-indent-1.10.0/src/ocp-indent-gen-rules/000077500000000000000000000000001524633121600203625ustar00rootroot00000000000000ocp-indent-1.10.0/src/ocp-indent-gen-rules/dune000066400000000000000000000006411524633121600212410ustar00rootroot00000000000000(rule (with-stdout-to version.ml (echo "let v = \"%{version:ocp-indent}\""))) (executable (name main) (public_name ocp-indent-gen-rules) (libraries cmdliner)) ;; Auto indent files with `dune build @fmt` (subdir run (dynamic_include ../rules/dune.ocp-indent)) (subdir rules (rule (deps (glob_files ../*.{ml,mli})) (target dune.ocp-indent) (action (run ocp-indent-gen-rules -o %{target})))) ocp-indent-1.10.0/src/ocp-indent-gen-rules/main.ml000066400000000000000000000044301524633121600216410ustar00rootroot00000000000000let exe_name = "ocp-indent-gen-rules" let named f = Cmdliner.Term.(app (const f)) let ignore = let open Cmdliner.Arg in let doc = "Comma separated list of files that should not be indented" in named (fun x -> `Ignore x) (value & opt (list string) [] & info ~doc ["ignore"]) let alias = let open Cmdliner.Arg in let doc = "The alias for the ocp-indent rules, default is fmt" in named (fun x -> `Alias x) (value & opt string "fmt" & info ~doc ["alias"]) let static = let open Cmdliner.Arg in let doc = "Generate rules for a regular include stanza rather than a dynamic_include" in named (fun x -> `Static x) (value & flag & info ~doc ["static"]) let output = let open Cmdliner.Arg in let docv = "OUTFILE" in let doc = "Writes rules to $(docv). When absent, writes rules to stdout." in named (fun x -> `Output x) (value & opt (some string) None & info ~doc ~docv ["o"]) let print_rules ~ignore ~alias ~static oc file = let source_file = if static then file else "../" ^ file in if List.mem file ignore then () else match Filename.extension file with | ".ml" | ".mli" -> let formatted_ext = "fmtd" in let pf fmt = Printf.fprintf oc (fmt ^^ "\n") in pf "(rule"; pf " (target %s.%s)" file formatted_ext; pf " (action (run ocp-indent %%{dep:%s} -o %%{target})))" source_file; pf ""; pf "(rule"; pf " (alias %s)" alias; pf " (action (diff %s %s.%s)))" source_file file formatted_ext; pf "" | _ -> () let with_output ~f output = match output with | None -> f stdout | Some file -> let oc = open_out file in f oc; close_out oc let run (`Ignore ignore) (`Alias alias) (`Static static) (`Output output) = let src_dir = if static then Sys.getcwd () else ".." in let files = Sys.readdir src_dir in with_output output ~f:(fun oc -> Array.sort String.compare files; Array.iter (print_rules ~ignore ~alias ~static oc) files) let term = let open Cmdliner.Term in const run $ ignore $ alias $ static $ output let info = let open Cmdliner in Cmd.info exe_name ~version:Version.v ~exits:Cmd.Exit.defaults ~doc:"Generate ocp-indent dune rules" let () = exit (Cmdliner.Cmd.eval (Cmdliner.Cmd.v info term)) ocp-indent-1.10.0/src/ocp-indent-lexer/000077500000000000000000000000001524633121600176005ustar00rootroot00000000000000ocp-indent-1.10.0/src/ocp-indent-lexer/approx_lexer.mll000066400000000000000000000613511524633121600230240ustar00rootroot00000000000000(**************************************************************************) (* *) (* TypeRex OCaml Studio *) (* Thomas Gazagnaire, Fabrice Le Fessant, Louis Gesbert *) (* *) (* OCaml *) (* Xavier Leroy, projet Cristal, INRIA Rocquencourt *) (* *) (* Copyright 2011-2013 OCamlPro *) (* Copyright 1996-2011 INRIA. *) (* All rights reserved. This file is distributed under the terms of *) (* the Q Public License version 1.0. *) (* *) (**************************************************************************) { open Lexing include Approx_tokens type error = | Illegal_escape of string | Keyword_as_label of string let error_msg = function | Illegal_escape s -> Printf.sprintf "Illegal character escape: %s" s | Keyword_as_label s -> Printf.sprintf "Invalid tuple or argument label: %s" s exception Error of { error: error ; start_pos: Lexing.position ; end_pos : Lexing.position } let list_last l = List.hd (List.rev l) let strict = ref false let set_strict_mode bool = strict := bool let lines_starts = ref [] (* The table of keywords *) let keywords = [ "and", AND; "as", AS; "assert", ASSERT; "begin", BEGIN; "class", CLASS; "constraint", CONSTRAINT; "do", DO; "done", DONE; "downto", DOWNTO; "else", ELSE; "end", END; "exception", EXCEPTION; "external", EXTERNAL; "false", FALSE; "for", FOR; "fun", FUN; "function", FUNCTION; "functor", FUNCTOR; "if", IF; "in", IN; "include", INCLUDE; "inherit", INHERIT; "initializer", INITIALIZER; "lazy", LAZY; "let", LET; "match", MATCH; "method", METHOD; "module", MODULE; "mutable", MUTABLE; "new", NEW; "object", OBJECT; "of", OF; "open", OPEN; "or", OR; "private", PRIVATE; "rec", REC; "sig", SIG; "struct", STRUCT; "then", THEN; "to", TO; "true", TRUE; "try", TRY; "type", TYPE; "val", VAL; "virtual", VIRTUAL; "when", WHEN; "while", WHILE; "with", WITH; "mod", INFIXOP3("mod"); "land", INFIXOP3("land"); "lor", INFIXOP3("lor"); "lxor", INFIXOP3("lxor"); "lsl", INFIXOP4("lsl"); "lsr", INFIXOP4("lsr"); "asr", INFIXOP4("asr"); ] let keyword_table = let t = Hashtbl.create 149 in List.iter (fun (x,y) -> Hashtbl.add t x y) keywords; t let lexer_extensions : (Lexing.lexbuf -> Approx_tokens.token) list ref = ref [] let enable_extension name = let t = IndentExtend.find name in List.iter (fun (x,y) -> Hashtbl.add keyword_table x y) t.IndentExtend.keywords; match t.IndentExtend.lexer with | None -> () | Some f -> lexer_extensions := f :: !lexer_extensions let disable_extensions () = Hashtbl.clear keyword_table; lexer_extensions := []; List.iter (fun (x,y) -> Hashtbl.add keyword_table x y) keywords (* To buffer string literals *) let initial_string_buffer = Bytes.create 256 let string_buff = ref initial_string_buffer let string_index = ref 0 let reset_string_buffer () = string_buff := initial_string_buffer; string_index := 0 let store_string_char c = if !string_index >= Bytes.length (!string_buff) then begin let new_buff = Bytes.create (Bytes.length (!string_buff) * 2) in Bytes.blit (!string_buff) 0 new_buff 0 (Bytes.length (!string_buff)); string_buff := new_buff end; Bytes.unsafe_set (!string_buff) (!string_index) c; incr string_index let get_stored_string () = let s = Bytes.sub (!string_buff) 0 (!string_index) in string_buff := initial_string_buffer; Bytes.to_string s (* To store the position of the beginning of a string and comment *) let string_start_loc = ref (-1);; let quotation_start_loc = ref (-1);; let quotation_kind = ref (`Camlp4 "<:<": [ `Camlp4 of string | `Ppx of string ]);; type in_comment = Comment | Code | Cinaps (* Like code, but started / ended with "(*$" / "$*)" rather than "{[" / "]}" *) | Verbatim | CommentCont let comment_stack : in_comment list ref = ref [] ;; let entering_inline_code_block = ref false;; let rec close_comment () = match !comment_stack with | Comment :: r -> comment_stack := r; COMMENT | CommentCont :: r -> comment_stack := r; COMMENTCONT | (Code | Cinaps | Verbatim) :: r -> comment_stack := r; ignore (close_comment ()); COMMENTCONT | [] -> assert false ;; let in_comment () = match !comment_stack with | (Comment | CommentCont | Verbatim) :: _ -> true | (Code | Cinaps) :: _ | [] -> false ;; let in_verbatim () = List.mem Verbatim !comment_stack ;; let rewind lexbuf n = lexbuf.lex_curr_pos <- lexbuf.lex_curr_pos - n; let curpos = lexbuf.lex_curr_p in lexbuf.lex_curr_p <- { curpos with pos_cnum = curpos.pos_cnum - n } ;; let check_commentclose lexbuf f = let s = Lexing.lexeme lexbuf in let len = String.length s in if s.[len - 1] <> ')' then f s else let rollback = if len >= 2 && !comment_stack <> [] && s.[len - 2] = '*' then 2 (* this is a comment end, unparse it *) else 1 (* only unparse the closing paren *) in let op = String.sub s 0 (len - rollback) in rewind lexbuf rollback; f op ;; let init () = lines_starts := []; (* disable_extensions(); *) reset_string_buffer(); string_start_loc := -1; quotation_start_loc := -1; quotation_kind := `Camlp4 "<:<"; comment_stack := []; entering_inline_code_block := false ;; (* To translate escape sequences *) let char_for_backslash = function | 'n' -> '\010' | 'r' -> '\013' | 'b' -> '\008' | 't' -> '\009' | c -> c let can_overflow f lexbuf = let s = Lexing.lexeme lexbuf in try InRange (f s) with Failure _ -> Overflow s let char_for_decimal_code i s = let c = 100 * (Char.code(s.[i]) - 48) + 10 * (Char.code(s.[i+1]) - 48) + (Char.code(s.[i+2]) - 48) in if (c < 0 || c > 255) then failwith "Bad escaped decimal char" else Char.chr c let char_for_hexadecimal_code lexbuf i = let d1 = Char.code (Lexing.lexeme_char lexbuf i) in let val1 = if d1 >= 97 then d1 - 87 else if d1 >= 65 then d1 - 55 else d1 - 48 in let d2 = Char.code (Lexing.lexeme_char lexbuf (i+1)) in let val2 = if d2 >= 97 then d2 - 87 else if d2 >= 65 then d2 - 55 else d2 - 48 in Char.chr (val1 * 16 + val2) (* To convert integer literals, allowing max_int + 1 (PR#4210) *) let cvt_int_literal s = - int_of_string ("-" ^ s) let cvt_int32_literal s = Int32.neg (Int32.of_string ("-" ^ String.sub s 0 (String.length s - 1))) let cvt_int64_literal s = Int64.neg (Int64.of_string ("-" ^ String.sub s 0 (String.length s - 1))) let cvt_nativeint_literal s = Nativeint.neg (Nativeint.of_string ("-" ^ String.sub s 0 (String.length s - 1))) (* Remove underscores from float literals *) let remove_underscores s = let s = Bytes.of_string s in let l = Bytes.length s in let rec remove src dst = if src >= l then if dst >= l then s else Bytes.sub s 0 dst else match Bytes.get s src with '_' -> remove (src + 1) dst | c -> Bytes.set s dst c; remove (src + 1) (dst + 1) in Bytes.to_string (remove 0 0) (* Update the current location with file name and line number. *) let update_loc lexbuf file line absolute chars = let pos = lexbuf.lex_curr_p in let new_file = match file with | None -> pos.pos_fname | Some s -> s in lexbuf.lex_curr_p <- { pos with pos_fname = new_file; pos_lnum = if absolute then line else pos.pos_lnum + line; pos_bol = pos.pos_cnum - chars; }; lines_starts := (lexbuf.lex_curr_p.pos_lnum, lexbuf.lex_curr_p.pos_bol) :: !lines_starts; ;; } let newline = ('\010' | '\013' | "\013\010") let blank = [' ' '\009' '\012'] let lowercase = ['a'-'z' '\223'-'\246' '\248'-'\255' '_' '\''] let uppercase = ['A'-'Z' '\192'-'\214' '\216'-'\222' '`'] let identchar = ['A'-'Z' 'a'-'z' '_' '\192'-'\214' '\216'-'\246' '\248'-'\255' '\'' '0'-'9'] let symbolchar = ['!' '$' '%' '&' '*' '+' '-' '.' '/' ':' '<' '=' '>' '?' '@' '^' '|' '~'] let bindingopchar = ['$' '&' '*' '+' '-' '/' '<' '=' '>' '@' '^' '|'] let decimal_literal = (['0'-'9'] ['0'-'9' '_']*) let hex_literal = ('0' ['x' 'X'] ['0'-'9' 'A'-'F' 'a'-'f']['0'-'9' 'A'-'F' 'a'-'f' '_']*) let oct_literal = ('0' ['o' 'O'] ['0'-'7'] ['0'-'7' '_']*) let bin_literal = ('0' ['b' 'B'] ['0'-'1'] ['0'-'1' '_']*) let int_literal = (decimal_literal | hex_literal | oct_literal | bin_literal) let float_literal = ['0'-'9'] ['0'-'9' '_']* ('.' ['0'-'9' '_']* )? (['e' 'E'] ['+' '-']? ['0'-'9'] ['0'-'9' '_']*)? rule parse_token = parse | newline { update_loc lexbuf None 1 false 0; EOL } | blank + { SPACES } | "_" { UNDERSCORE } | "~" { TILDE } | "~" lowercase identchar * ':' { let s = Lexing.lexeme lexbuf in let name = String.sub s 1 (String.length s - 2) in if !strict && Hashtbl.mem keyword_table name then raise (Error { error = Keyword_as_label name ; start_pos = Lexing.lexeme_start_p lexbuf ; end_pos = Lexing.lexeme_end_p lexbuf }); LABEL name } | "?" { QUESTION } | "??" { QUESTIONQUESTION } | "?" lowercase identchar * ':' { let s = Lexing.lexeme lexbuf in let name = String.sub s 1 (String.length s - 2) in if !strict && Hashtbl.mem keyword_table name then raise (Error { error = Keyword_as_label name ; start_pos = Lexing.lexeme_start_p lexbuf ; end_pos = Lexing.lexeme_end_p lexbuf }); OPTLABEL name } | lowercase identchar * ( '%' identchar + ('.' identchar +) * ) ? { let s = Lexing.lexeme lexbuf in try let i = String.index_from s 1 '%' in let kw = String.sub s 0 i in try Hashtbl.find keyword_table kw with Not_found -> rewind lexbuf (String.length s - i); LIDENT s with Not_found -> try Hashtbl.find keyword_table s with Not_found -> LIDENT s } | uppercase identchar * { UIDENT(Lexing.lexeme lexbuf) } (* No capitalized keywords *) | int_literal { INT (can_overflow cvt_int_literal lexbuf) } | float_literal { FLOAT (remove_underscores(Lexing.lexeme lexbuf)) } | int_literal "l" { INT32 (can_overflow cvt_int32_literal lexbuf) } | int_literal "L" { INT64 (can_overflow cvt_int64_literal lexbuf) } | int_literal "n" { NATIVEINT (can_overflow cvt_nativeint_literal lexbuf) } | "\"" { reset_string_buffer(); let string_start = lexbuf.lex_start_p in string_start_loc := Lexing.lexeme_start lexbuf; let token = string lexbuf in lexbuf.lex_start_p <- string_start; token } | "'" newline "'" { update_loc lexbuf None 1 false 1; CHAR (InRange (Lexing.lexeme_char lexbuf 1)) } | "'" [^ '\\' '\'' '\010' '\013'] "'" { CHAR( InRange (Lexing.lexeme_char lexbuf 1)) } | "'\\" ['\\' '\'' '"' 'n' 't' 'b' 'r' ' '] "'" { CHAR( InRange (char_for_backslash (Lexing.lexeme_char lexbuf 2))) } | "'\\" ['0'-'9'] ['0'-'9'] ['0'-'9'] "'" { CHAR(can_overflow (char_for_decimal_code 2) lexbuf) } | "'\\" 'x' ['0'-'9' 'a'-'f' 'A'-'F'] ['0'-'9' 'a'-'f' 'A'-'F'] "'" { CHAR( InRange (char_for_hexadecimal_code lexbuf 3)) } | "'\\" _ { let l = Lexing.lexeme lexbuf in CHAR ( Overflow l ) } | "(*$" { entering_inline_code_block := true; comment_stack := Comment :: !comment_stack; rewind lexbuf 1; COMMENT } | "(*" { let comment_start = lexbuf.lex_start_p in comment_stack := Comment :: !comment_stack; let token = comment lexbuf in lexbuf.lex_start_p <- comment_start; token } | "*)" { match !comment_stack with | _ :: _ -> close_comment () | [] -> rewind lexbuf 1; STAR } | '{' [ '[' 'v' ] { if !entering_inline_code_block then begin entering_inline_code_block := false; match !comment_stack with | Code :: _ -> OCAMLDOC_CODE | Verbatim :: _ -> let verb_start = lexbuf.lex_start_p in let token = verbatim lexbuf in lexbuf.lex_start_p <- verb_start; token | _ -> assert false end else begin rewind lexbuf 1; LBRACE end } | [ ']' 'v' ] '}' { match !comment_stack with | (Code|Verbatim)::r -> comment_stack := r; let comment_start = lexbuf.lex_start_p in let token = comment lexbuf in lexbuf.lex_start_p <- comment_start; token | _ -> rewind lexbuf 1; match Bytes.get lexbuf.lex_buffer (lexbuf.lex_curr_pos - 1) with | ']' -> RBRACKET | 'v' -> LIDENT "v" | _ -> assert false } | "]}" { match !comment_stack with | Code::r -> comment_stack := r; let comment_start = lexbuf.lex_start_p in let token = comment lexbuf in lexbuf.lex_start_p <- comment_start; token | _ -> rewind lexbuf 1; RBRACKET } | "v}" { match !comment_stack with | Verbatim::r -> comment_stack := r; let comment_start = lexbuf.lex_start_p in let token = comment lexbuf in lexbuf.lex_start_p <- comment_start; token | _ -> rewind lexbuf 1; LIDENT "v" } | "<:" identchar * "<" { let start = lexbuf.lex_start_p in quotation_start_loc := Lexing.lexeme_start lexbuf; let s = Lexing.lexeme lexbuf in let tag = String.sub s 2 (String.length s - 3) in quotation_kind := `Camlp4 tag; let token = quotation lexbuf in lexbuf.lex_start_p <- start; token } | "{" identchar * "|" { let start = lexbuf.lex_start_p in quotation_start_loc := Lexing.lexeme_start lexbuf; let s = Lexing.lexeme lexbuf in let delim = String.sub s 1 (String.length s - 2) in quotation_kind := `Ppx delim; let token = quotation lexbuf in lexbuf.lex_start_p <- start; token } | "#" [' ' '\t']* (['0'-'9']+ as _num) [' ' '\t']* ("\"" ([^ '\010' '\013' '"' ] * as _name) "\"")? [^ '\010' '\013'] * newline { update_loc lexbuf None 1 false 0; LINE_DIRECTIVE } | "#" { SHARP } | "&" { AMPERSAND } | "&&" { AMPERAMPER } | "`" { BACKQUOTE } | "'" { QUOTE } | "(" { LPAREN } | ")" { RPAREN } | "*" { STAR } | "," { COMMA } | "->" { MINUSGREATER } | "." { DOT } | ".." { DOTDOT } | ":" { COLON } | "::" { COLONCOLON } | ":=" { COLONEQUAL } | ":>" { COLONGREATER } | ";" ( '%' identchar + ('.' identchar +) * ) ? { SEMI } | ";;" { SEMISEMI } | "<" { LESS } | "<-" { LESSMINUS } | "=" { EQUAL } | "[" { LBRACKET } | "[|" { LBRACKETBAR } | "[<" { LBRACKETLESS } | "[>" { LBRACKETGREATER } | "]" { RBRACKET } | "{" { LBRACE } | "{<" { LBRACELESS } | "|" { BAR } | "||" { BARBAR } | "|]" { BARRBRACKET } | ">" { GREATER } | ">]" { GREATERRBRACKET } | "}" { RBRACE } | ">}" { GREATERRBRACE } | "[%" { LBRACKETPERCENT } | "[%%" { LBRACKETPERCENTPERCENT } | "[@" { LBRACKETAT } | "[@@" { LBRACKETATAT } | "[@@@" { LBRACKETATATAT } | "!" { BANG } | "!=" { INFIXOP0 "!=" } | "+" { PLUS } | "+." { PLUSDOT } | "-" { MINUS } | "-." { MINUSDOT } | "!" symbolchar + ')'? { check_commentclose lexbuf (fun s -> PREFIXOP s) } | ['~' '?'] symbolchar + ')'? { check_commentclose lexbuf (fun s -> PREFIXOP s) } | '$' symbolchar * ')'? { if !entering_inline_code_block then begin entering_inline_code_block := false; comment_stack := Cinaps :: !comment_stack; rewind lexbuf (Lexing.lexeme_end lexbuf - Lexing.lexeme_start lexbuf - 1); OCAMLDOC_CODE end else check_commentclose lexbuf (fun s -> INFIXOP0 s) } | ['=' '<' '>' '|' '&'] symbolchar * ')'? { check_commentclose lexbuf (fun s -> INFIXOP0 s) } | ['@' '^'] symbolchar * ')'? { check_commentclose lexbuf (fun s -> INFIXOP1 s) } | ['+' '-'] symbolchar * ')'? { check_commentclose lexbuf (fun s -> INFIXOP2 s) } | "**" symbolchar * ')'? { check_commentclose lexbuf (fun s -> INFIXOP4 s) } | ['*' '/' '%'] symbolchar * ')'? { check_commentclose lexbuf (fun s -> INFIXOP3 s) } | "let" bindingopchar symbolchar* ')'? { check_commentclose lexbuf (fun _ -> LET) } | "and" bindingopchar symbolchar* ')'? { check_commentclose lexbuf (fun _ -> AND) } | eof { EOF } | _ { ILLEGAL_CHAR (Lexing.lexeme_char lexbuf 0) } and quotation = parse ">>" { match !quotation_kind with | `Camlp4 tag -> QUOTATION ("<:"^tag^"<") | `Ppx _ -> quotation lexbuf } | "|" identchar * "}" { match !quotation_kind with | `Ppx delim -> let s = Lexing.lexeme lexbuf in let ndelim = String.sub s 1 (String.length s - 2) in if ndelim = delim then QUOTATION ("{"^delim^"|") else quotation lexbuf | `Camlp4 _ -> quotation lexbuf } | newline { update_loc lexbuf None 1 false 0; quotation lexbuf } | eof { match !quotation_kind with | `Camlp4 tag -> QUOTATION ("<:"^tag^"<") | `Ppx delim -> QUOTATION ("{"^delim^"|") } | _ { quotation lexbuf } and comment = parse | "(*" { comment_stack := Comment :: !comment_stack; comment lexbuf } | "*)" | eof { let tok = close_comment () in if in_verbatim () then verbatim lexbuf else match !comment_stack with | (Comment | CommentCont) :: _ -> comment lexbuf | _ -> tok } | (newline blank*)? '{' [ '[' 'v' ] { if in_verbatim() then comment lexbuf else let tok = match !comment_stack with | CommentCont::_ -> COMMENTCONT | Comment::r -> comment_stack := CommentCont::r; COMMENT | _s -> assert false in let block = match Bytes.get lexbuf.lex_buffer (lexbuf.lex_curr_pos - 1) with | '[' -> Code | 'v' -> Verbatim | _ -> assert false in comment_stack := block :: !comment_stack; entering_inline_code_block := true; (* unparse the token, to be parsed again as code *) lexbuf.Lexing.lex_curr_p <- lexbuf.Lexing.lex_start_p; lexbuf.Lexing.lex_curr_pos <- lexbuf.Lexing.lex_start_pos; tok } | '"' { reset_string_buffer(); string_start_loc := Lexing.lexeme_start lexbuf; ignore (string lexbuf); reset_string_buffer (); comment lexbuf } | "{" identchar * "|" { quotation_start_loc := Lexing.lexeme_start lexbuf; let s = Lexing.lexeme lexbuf in let delim = String.sub s 1 (String.length s - 2) in quotation_kind := `Ppx delim; ignore (quotation lexbuf); comment lexbuf } | "''" { comment lexbuf } | "'" newline "'" { update_loc lexbuf None 1 false 1; comment lexbuf } | "'" [^ '\\' '\'' '\010' '\013' ] "'" { comment lexbuf } | "'\\" ['\\' '"' '\'' 'n' 't' 'b' 'r' ' '] "'" { comment lexbuf } | "'\\" ['0'-'9'] ['0'-'9'] ['0'-'9'] "'" { comment lexbuf } | "'\\" 'x' ['0'-'9' 'a'-'f' 'A'-'F'] ['0'-'9' 'a'-'f' 'A'-'F'] "'" { comment lexbuf } | newline { update_loc lexbuf None 1 false 0; comment lexbuf } | _ { comment lexbuf } (* Ocamldoc verbatim, inside comments ; mostly the same as the comment rule *) and verbatim = parse | "(*" { comment_stack := Comment :: !comment_stack; comment lexbuf } | "*)" { (* leave the verbatim block and unparse the token *) comment_stack := (match !comment_stack with | Verbatim :: s -> s | _ -> assert false); lexbuf.Lexing.lex_curr_p <- lexbuf.Lexing.lex_start_p; lexbuf.Lexing.lex_curr_pos <- lexbuf.Lexing.lex_start_pos; (* let the surrounding comments close themselves *) match !comment_stack with | Comment :: _ -> comment lexbuf | CommentCont :: r -> comment_stack := Comment :: r; comment lexbuf | _ -> OCAMLDOC_VERB } | "v}" { (* Unparse the token but leave the comment stack. The token rule will reparse, detect it, pop the verbatim and return to the comment rule. *) rewind lexbuf 2; OCAMLDOC_VERB } | "\"" { reset_string_buffer(); string_start_loc := Lexing.lexeme_start lexbuf; ignore (string lexbuf); reset_string_buffer (); verbatim lexbuf } | "''" { verbatim lexbuf } | "'" newline "'" { update_loc lexbuf None 1 false 1; verbatim lexbuf } | "'" [^ '\\' '\'' '\010' '\013' ] "'" { verbatim lexbuf } | "'\\" ['\\' '"' '\'' 'n' 't' 'b' 'r' ' '] "'" { verbatim lexbuf } | "'\\" ['0'-'9'] ['0'-'9'] ['0'-'9'] "'" { verbatim lexbuf } | "'\\" 'x' ['0'-'9' 'a'-'f' 'A'-'F'] ['0'-'9' 'a'-'f' 'A'-'F'] "'" { verbatim lexbuf } | newline { update_loc lexbuf None 1 false 0; verbatim lexbuf } | eof { OCAMLDOC_VERB } | _ { verbatim lexbuf } and string = parse '"' | eof { STRING (get_stored_string ()) } | '\\' newline ([' ' '\t'] * as space) { update_loc lexbuf None 1 false (String.length space); string lexbuf } | '\\' ['\\' '\'' '"' 'n' 't' 'b' 'r' ' '] { store_string_char(char_for_backslash(Lexing.lexeme_char lexbuf 1)); string lexbuf } | '\\' ['0'-'9'] ['0'-'9'] ['0'-'9'] { (match can_overflow (char_for_decimal_code 1) lexbuf with | Overflow _ -> let s = Lexing.lexeme lexbuf in for i = 0 to String.length s - 1 do store_string_char s.[i] done | InRange c -> store_string_char c); string lexbuf } | '\\' 'x' ['0'-'9' 'a'-'f' 'A'-'F'] ['0'-'9' 'a'-'f' 'A'-'F'] { store_string_char(char_for_hexadecimal_code lexbuf 2); string lexbuf } | '\\' _ { if in_comment () then string lexbuf else begin if !strict then raise (Error { error = Illegal_escape (Lexing.lexeme lexbuf) ; start_pos = Lexing.lexeme_start_p lexbuf ; end_pos = Lexing.lexeme_end_p lexbuf }); store_string_char (Lexing.lexeme_char lexbuf 0); store_string_char (Lexing.lexeme_char lexbuf 1); string lexbuf end } | newline { update_loc lexbuf None 1 false 0; let s = Lexing.lexeme lexbuf in for i = 0 to String.length s - 1 do store_string_char s.[i]; done; string lexbuf } | _ { store_string_char(Lexing.lexeme_char lexbuf 0); string lexbuf } { let token = let rec tok lexbuf = function | [] -> parse_token lexbuf | x::xs -> begin try x lexbuf with | _ -> tok lexbuf xs end in fun lexbuf -> tok lexbuf !lexer_extensions let rec token_locs lexbuf = match token lexbuf with COMMENT -> token_locs lexbuf | token -> token, ( lexbuf.lex_start_p, lexbuf.lex_curr_p) let rec token_pos lexbuf = match token lexbuf with COMMENT -> token_pos lexbuf | token -> token, ( lexbuf.lex_start_p.pos_cnum, lexbuf.lex_curr_p.pos_cnum) let token_locs_and_comments lexbuf = let token = token lexbuf in token, ( lexbuf.lex_start_p, lexbuf.lex_curr_p) let get_token = token let token_with_comments = get_token let rec token lexbuf = match get_token lexbuf with COMMENT -> token lexbuf | tok -> tok let tokens_of_file filename = let ic = open_in filename in try init (); let lexbuf = Lexing.from_channel ic in let rec iter tokens = let token = token_pos lexbuf in match token with (EOF, _) -> List.rev tokens | _ -> iter (token :: tokens) in let tokens = iter [] in close_in ic; tokens with e -> close_in ic; raise e let tokens_with_loc_of_string s = init (); let lexbuf = Lexing.from_string s in let rec iter tokens = let token = token_pos lexbuf in match token with (EOF, _) -> List.rev tokens | _ -> iter (token :: tokens) in let tokens = iter [] in tokens let tokens_of_string s = init (); let lexbuf = Lexing.from_string s in let rec iter tokens = let token = token lexbuf in match token with (EOF) -> List.rev tokens | _ -> iter (token :: tokens) in let tokens = iter [] in tokens let lines () = List.rev ( !lines_starts ) } ocp-indent-1.10.0/src/ocp-indent-lexer/approx_tokens.ml000066400000000000000000000147561524633121600230430ustar00rootroot00000000000000(**************************************************************************) (* *) (* TypeRex OCaml Studio *) (* Thomas Gazagnaire, Fabrice Le Fessant, Louis Gesbert *) (* *) (* OCaml *) (* Xavier Leroy, projet Cristal, INRIA Rocquencourt *) (* *) (* Copyright 2011-2013 OCamlPro *) (* Copyright 1996-2011 INRIA. *) (* All rights reserved. This file is distributed under the terms of *) (* the Q Public License version 1.0. *) (* *) (**************************************************************************) (* ADMIN: fabrice *) (* Instead of raising an error when a CHAR, INT, INT32, INT64 or NATIVEINT overflows, we just changed the returned value to take that into account. *) type 'a overflow = | InRange of 'a | Overflow of string type token = | AMPERAMPER | AMPERSAND | AND | AS | ASSERT | BACKQUOTE | BANG | BAR | BARBAR | BARRBRACKET | BEGIN | CHAR of (char overflow) | CLASS | COLON | COLONCOLON | COLONEQUAL | COLONGREATER | COMMA (* Start of comment from code *) | COMMENT (* Start of inline code section within comment: "{[" *) | OCAMLDOC_CODE (* Start of verbatim section within comment: "{v" *) | OCAMLDOC_VERB (* Continuation of comment after a closed ocamldoc code or verb section *) | COMMENTCONT | CONSTRAINT | DO | DONE | DOT | DOTDOT | DOWNTO | ELSE | END | EOF | EQUAL | EXCEPTION | EXTERNAL | FALSE | FLOAT of (string) | FOR | FUN | FUNCTION | FUNCTOR | GREATER | GREATERRBRACE | GREATERRBRACKET | IF | ILLEGAL_CHAR of (char) | IN | INCLUDE | INFIXOP0 of (string) | INFIXOP1 of (string) | INFIXOP2 of (string) | INFIXOP3 of (string) | INFIXOP4 of (string) | INHERIT | INITIALIZER | INT of (int overflow) | INT32 of (int32 overflow) | INT64 of (int64 overflow) | LABEL of (string) | LAZY | LBRACE | LBRACELESS | LBRACKET | LBRACKETBAR | LBRACKETLESS | LBRACKETGREATER | LBRACKETPERCENT | LBRACKETPERCENTPERCENT | LBRACKETAT | LBRACKETATAT | LBRACKETATATAT | LESS | LESSMINUS | LET | LIDENT of (string) | LINE_DIRECTIVE | LPAREN | MATCH | METHOD | MINUS | MINUSDOT | MINUSGREATER | MODULE | MUTABLE | NATIVEINT of (nativeint overflow) | NEW | OBJECT | OF | OPEN | OPTLABEL of (string) | OR | PLUS | PLUSDOT | PREFIXOP of (string) | PRIVATE | QUESTION | QUESTIONQUESTION | QUOTATION of (string) | QUOTE | RBRACE | RBRACKET | REC | RPAREN | SEMI | SEMISEMI | SHARP | SIG | STAR | STRING of (string) | STRUCT | THEN | TILDE | TO | TRUE | TRY | TYPE | UIDENT of (string) | UNDERSCORE | VAL | VIRTUAL | WHEN | WHILE | WITH | EOL | SPACES let to_string = function | AMPERAMPER -> "AMPERAMPER" | AMPERSAND -> "AMPERSAND" | AND -> "AND" | AS -> "AS" | ASSERT -> "ASSERT" | BACKQUOTE -> "BACKQUOTE" | BANG -> "BANG" | BAR -> "BAR" | BARBAR -> "BARBAR" | BARRBRACKET -> "BARRBRACKET" | BEGIN -> "BEGIN" | CHAR _ -> "CHAR" | CLASS -> "CLASS" | COLON -> "COLON" | COLONCOLON -> "COLONCOLON" | COLONEQUAL -> "COLONEQUAL" | COLONGREATER -> "COLONGREATER" | COMMA -> "COMMA" (* Start of comment from code *) | COMMENT -> "COMMENT" (* Start of inline code section within comment: "{[" *) | OCAMLDOC_CODE -> "OCAMLDOC_CODE" (* Start of verbatim section within comment: "{v" *) | OCAMLDOC_VERB -> "OCAMLDOC_VERB" (* Continuation of comment after a closed ocamldoc code or verb section *) | COMMENTCONT -> "COMMENTCONT" | CONSTRAINT -> "CONSTRAINT" | DO -> "DO" | DONE -> "DONE" | DOT -> "DOT" | DOTDOT -> "DOTDOT" | DOWNTO -> "DOWNTO" | ELSE -> "ELSE" | END -> "END" | EOF -> "EOF" | EQUAL -> "EQUAL" | EXCEPTION -> "EXCEPTION" | EXTERNAL -> "EXTERNAL" | FALSE -> "FALSE" | FLOAT _ -> "FLOAT" | FOR -> "FOR" | FUN -> "FUN" | FUNCTION -> "FUNCTION" | FUNCTOR -> "FUNCTOR" | GREATER -> "GREATER" | GREATERRBRACE -> "GREATERRBRACE" | GREATERRBRACKET -> "GREATERRBRACKET" | IF -> "IF" | ILLEGAL_CHAR _ -> "ILLEGAL_CHAR" | IN -> "IN" | INCLUDE -> "INCLUDE" | INFIXOP0 _ -> "INFIXOP0" | INFIXOP1 _ -> "INFIXOP1" | INFIXOP2 _ -> "INFIXOP2" | INFIXOP3 _ -> "INFIXOP3" | INFIXOP4 _ -> "INFIXOP4" | INHERIT -> "INHERIT" | INITIALIZER -> "INITIALIZER" | INT _ -> "INT" | INT32 _ -> "INT32" | INT64 _ -> "INT64" | LABEL _ -> "LABEL" | LAZY -> "LAZY" | LBRACE -> "LBRACE" | LBRACELESS -> "LBRACELESS" | LBRACKET -> "LBRACKET" | LBRACKETBAR -> "LBRACKETBAR" | LBRACKETLESS -> "LBRACKETLESS" | LBRACKETGREATER -> "LBRACKETGREATER" | LBRACKETPERCENT -> "LBRACKETPERCENT" | LBRACKETPERCENTPERCENT -> "LBRACKETPERCENTPERCENT" | LBRACKETAT -> "LBRACKETAT" | LBRACKETATAT -> "LBRACKETATAT" | LBRACKETATATAT -> "LBRACKETATATAT" | LESS -> "LESS" | LESSMINUS -> "LESSMINUS" | LET -> "LET" | LIDENT _ -> "LIDENT" | LINE_DIRECTIVE -> "LINE_DIRECTIVE" | LPAREN -> "LPAREN" | MATCH -> "MATCH" | METHOD -> "METHOD" | MINUS -> "MINUS" | MINUSDOT -> "MINUSDOT" | MINUSGREATER -> "MINUSGREATER" | MODULE -> "MODULE" | MUTABLE -> "MUTABLE" | NATIVEINT _ -> "NATIVEINT" | NEW -> "NEW" | OBJECT -> "OBJECT" | OF -> "OF" | OPEN -> "OPEN" | OPTLABEL _ -> "OPTLABEL" | OR -> "OR" | PLUS -> "PLUS" | PLUSDOT -> "PLUSDOT" | PREFIXOP _ -> "PREFIXOP" | PRIVATE -> "PRIVATE" | QUESTION -> "QUESTION" | QUESTIONQUESTION -> "QUESTIONQUESTION" | QUOTATION _ -> "QUOTATION" | QUOTE -> "QUOTE" | RBRACE -> "RBRACE" | RBRACKET -> "RBRACKET" | REC -> "REC" | RPAREN -> "RPAREN" | SEMI -> "SEMI" | SEMISEMI -> "SEMISEMI" | SHARP -> "SHARP" | SIG -> "SIG" | STAR -> "STAR" | STRING _ -> "STRING" | STRUCT -> "STRUCT" | THEN -> "THEN" | TILDE -> "TILDE" | TO -> "TO" | TRUE -> "TRUE" | TRY -> "TRY" | TYPE -> "TYPE" | UIDENT _ -> "UIDENT" | UNDERSCORE -> "UNDERSCORE" | VAL -> "VAL" | VIRTUAL -> "VIRTUAL" | WHEN -> "WHEN" | WHILE -> "WHILE" | WITH -> "WITH" | EOL -> "EOL" | SPACES -> "SPACES" ocp-indent-1.10.0/src/ocp-indent-lexer/dune000066400000000000000000000005771524633121600204670ustar00rootroot00000000000000(ocamllex approx_lexer) (library (name ocp_indent_lexer) (public_name ocp-indent.lexer) (wrapped false)) ;; Auto indent files with `dune build @fmt` (subdir run (dynamic_include ../rules/dune.ocp-indent)) (subdir rules (rule (deps (glob_files ../*.{ml,mli})) (target dune.ocp-indent) (action (run ocp-indent-gen-rules --ignore approx_lexer.ml -o %{target})))) ocp-indent-1.10.0/src/ocp-indent-lexer/indentExtend.ml000066400000000000000000000036431524633121600225710ustar00rootroot00000000000000(**************************************************************************) (* *) (* All rights reserved. This file is distributed under the terms of the *) (* GNU Lesser General Public License version 2.1 with linking *) (* exception. *) (* *) (* TypeRex is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* Lesser GNU General Public License for more details. *) (* *) (**************************************************************************) exception Syntax_not_found of string type t = { keywords : (string * Approx_tokens.token) list; lexer : (Lexing.lexbuf -> Approx_tokens.token) option } let extensions = Hashtbl.create 17 let register name ?(keywords=[]) ?lexer () = Hashtbl.add extensions name {keywords;lexer} let available () = Hashtbl.fold (fun name _ acc -> name::acc) extensions [] let find (name : string) = try Hashtbl.find extensions name with Not_found -> raise (Syntax_not_found name) (* predefined extensions *) open Approx_tokens let _ = register "lwt" ~keywords:[ "for_lwt", FOR; "lwt", LET; "match_lwt", MATCH; "try_lwt", TRY; "while_lwt", WHILE; "finally", WITH; (* -- no equivalence for this one, this is a hack ! *) ] (); register "mll" ~keywords:[ "rule", LET; "parse", FUNCTION; ] (); register "stream" ~keywords:[ "parser", FUNCTION; ] (); register "cstruct" ~keywords:[ "cstruct", TYPE; ] (); register "bitstring" ~keywords:[ "bitmatch", MATCH; ] (); ocp-indent-1.10.0/src/ocp-indent-lexer/indentExtend.mli000066400000000000000000000025541524633121600227420ustar00rootroot00000000000000(**************************************************************************) (* *) (* All rights reserved. This file is distributed under the terms of the *) (* GNU Lesser General Public License version 2.1 with linking *) (* exception. *) (* *) (* TypeRex is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* Lesser GNU General Public License for more details. *) (* *) (**************************************************************************) exception Syntax_not_found of string type t = { keywords : (string * Approx_tokens.token) list; lexer : (Lexing.lexbuf -> Approx_tokens.token) option } (** Register lexer extension.*) val register : string -> ?keywords:(string * Approx_tokens.token) list -> ?lexer:(Lexing.lexbuf -> Approx_tokens.token) -> unit -> unit (** Get available extensions *) val available : unit -> string list (** Find an extension by its name *) val find : string -> t ocp-indent-1.10.0/src/ocp-indent-lib/000077500000000000000000000000001524633121600172275ustar00rootroot00000000000000ocp-indent-1.10.0/src/ocp-indent-lib/dune000066400000000000000000000006201524633121600201030ustar00rootroot00000000000000(library (name ocp_indent_lib) (wrapped false) (public_name ocp-indent.lib) (libraries ocp-indent.utils) (flags :standard -w -9 -warn-error -57)) ;; Auto indent files with `dune build @fmt` (subdir run (dynamic_include ../rules/dune.ocp-indent)) (subdir rules (rule (deps (glob_files ../*.{ml,mli})) (target dune.ocp-indent) (action (run ocp-indent-gen-rules -o %{target})))) ocp-indent-1.10.0/src/ocp-indent-lib/indentBlock.ml000066400000000000000000002052211524633121600220170ustar00rootroot00000000000000(**************************************************************************) (* *) (* Copyright 2011 Jun Furuse *) (* Copyright 2012,2015 OCamlPro *) (* *) (* All rights reserved. This file is distributed under the terms of the *) (* GNU Lesser General Public License version 2.1 with linking *) (* exception. *) (* *) (* TypeRex is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* Lesser GNU General Public License for more details. *) (* *) (**************************************************************************) open Pos open Nstream open Approx_lexer open Util module Node = struct type extension_kind = ExtNode | Attr (* Node kind *) type kind = | KParen | KBrace | KBracket | KBracketBar | KLet | KClass | KAnd of kind | KLetIn | KIn | KExpr of int (* actually handles also patterns / types / ... *) (* Parameter:Priority - next expression is deindented if the op has lower priority *) | KBody of kind | KArrow of kind | KColon | KType | KConstraint | KException | KOpen | KInclude | KVal | KBar of kind (* Stores the original token and line offset for alignment of comment continuations *) | KComment of Nstream.token * int (* ocamldoc verbatim block *) | KVerbatim of Nstream.token * int | KUnknown | KStruct | KSig | KModule | KBegin | KObject | KMatch | KTry | KWith of kind | KLoop | KIf | KThen | KElse | KDo | KFun | KWhen | KExternal | KCodeInComment | KEffect | KExtendedExpr of string list * extension_kind | KExtendedItem of string list * extension_kind | KAttrId of string list * bool (* Priority of open expression constructs (see below for operators) *) let prio = function | KIn | KArrow _ -> 0 | KThen | KElse -> 10 | KExpr i -> i | _ -> -10 let prio_max = 200 let prio_dot = 160 let prio_apply = 140 let expr_atom = KExpr prio_max let expr_apply = KExpr 140 let prio_lbracketat = 30 (* Special colon prio used to correctly indent labeled tuples *) let prio_star = 100 let prio_colon_tuple = prio_star (* Special operators that should break arrow indentation have this prio (eg monad operators, >>=) *) let prio_flatop = 59 let prio_colon = 35 let prio_arrow = 32 let prio_semi = 5 let rec follow = function | KAnd k | KBody k | KWith k -> follow k | k -> k let rec string_of_kind = function | KExpr i -> Printf.sprintf "KExpr(%d)" i | KParen -> "KParen" | KBrace -> "KBrace" | KBracket -> "KBracket" | KBracketBar -> "KBracketBar" (* | KField -> "KField" *) | KLet -> "KLet" | KClass -> "KClass" | KIn -> "KIn" | KAnd k -> aux "KAnd" k | KLetIn -> "KLetIn" | KBody k -> aux "KBody" k | KArrow k -> aux "KArrow" k | KColon -> "KColon" | KVal -> "KVal" | KBar k -> aux "KBar" k | KOpen -> "KOpen" | KInclude -> "KInclude" | KComment _ -> "KComment" | KVerbatim _ -> "KVerbatim" | KUnknown -> "KUnknown" | KType -> "Ktype" | KConstraint -> "KConstraint" | KException -> "KException" | KStruct -> "KStruct" | KSig -> "KSig" | KModule -> "KModule" | KBegin -> "KBegin" | KObject -> "KObject" | KMatch -> "KMatch" | KTry -> "KTry" | KWith k -> aux "KWith" k | KLoop -> "KLoop" | KIf -> "KIf" | KThen -> "Kthen" | KElse -> "KElse" | KDo -> "KDo" | KFun -> "KFun" | KWhen -> "KWhen" | KExternal -> "KExternal" | KCodeInComment -> "KCodeInComment" | KEffect -> "KEffect" | KExtendedExpr (name, kind) -> Printf.sprintf "KExtendedExpr(%s,%s)" (String.concat "." (List.rev name)) (match kind with ExtNode -> "node" | Attr -> "attr") | KExtendedItem (name, kind) -> Printf.sprintf "KExtendedItem(%s,%s)" (String.concat "." (List.rev name)) (match kind with ExtNode -> "node" | Attr -> "attr") | KAttrId(name, dotted) -> Printf.sprintf "KAttrId(%s,%B)" (String.concat "." (List.rev name)) dotted and aux str k = Printf.sprintf "%s(%s)" str (string_of_kind k) (* A node: - has a kind - has the current line offset [indent] - has the current token offset [column] - has a inner padding [pad] - has a line count [count] XXX XXX XXX [ XXX ] XXX XXX XXX [ XXX ] <----------x--------> <-pad-> <-pad-> *) type t = { kind: kind; indent: int; (* expression starting column *) column: int; (* starting column of the token*) pad: int; (* padding: how much children should be indented from current line *) line_indent: int; (* starting column of the current line *) line: int; (* starting line of the expression *) } let to_string i t = Printf.sprintf "%s%s %d|%d-%d-%d(%d)" (String.make i ' ') (string_of_kind t.kind) t.line t.line_indent t.indent t.column t.pad let default = { kind = KUnknown; indent = 0; column = 0; pad = 0; line = 0; line_indent = 0; } let shift node n = let n = max n (- node.indent) in { node with indent = node.indent + n; column = node.column + n } end module Path = struct open Node type t = Node.t list let to_string t = String.concat " \027[35m/\027[m " (List.map (fun n -> Node.to_string 0 n) (List.rev t)) let top = function | [] -> Node.default | t :: _ -> t let indent = function | [] -> 0 | t :: _ -> t.indent let pad = function | [] -> 0 | t :: _ -> t.pad let maptop f = function | [] | {kind=KCodeInComment}::_ as l -> l | t::l -> f t :: l let shift path n = maptop (fun t -> Node.shift t n) path end open Node (* A block is: - a node path to go to this block - the last token of this block (when a comment, it is stacked to keep the last meaningful token) - the last token offset - the original starting column for this block *) type t = { path: Path.t; last: Nstream.token list; toff: int; orig: int; } let shift t n = { t with path = Path.shift t.path n } let to_string t = Path.to_string t.path (* Printf.sprintf "%s\n%d %b" (Path.to_string t.path) t.toff *) let empty = { path = []; last = []; toff = 0; orig = 0; } (* (* Does the token close a top LET construct ? *) (* NB: we do this with another way below, but this one might be more robust *) let rec close_top_let = function | None -> true | Some t -> match t.token with | COMMENT _ -> assert false (* COMMENT must be skipped *) (* Tokens that allow a let-in after them *) | AMPERSAND | AMPERAMPER | BARBAR | BEGIN | COLONCOLON | COLONEQUAL | COMMA | DO | DOWNTO | ELSE | EQUAL | GREATER | IF | IN | INFIXOP0 _ | INFIXOP1 _ | INFIXOP2 _ | INFIXOP3 _ | INFIXOP4 _ | LBRACE | LBRACELESS | LBRACKET | LBRACKETBAR | LBRACKETLESS | LBRACKETGREATER | LESS | LESSMINUS | LPAREN | MATCH | MINUS | MINUSDOT | MINUSGREATER | OR | PLUS | PLUSDOT | QUESTION | QUESTIONQUESTION | SEMI | STAR | THEN | TO | TRY | WHEN | WHILE | TILDE -> false | _ -> true *) (* Go back to the node path path until [f] holds *) let rec unwind f path = match path with | { kind } :: _ when f kind -> path | { kind=KCodeInComment } :: _ -> path | _ :: path -> unwind f path | [] -> [] (* Unwinds the path while [f] holds, returning the last step for which it does *) let unwind_while f path = let rec aux acc = function | { kind=KCodeInComment } :: _ as p -> acc :: p | { kind } as h :: p when f kind -> aux h p | p -> acc :: p in match path with | { kind=KCodeInComment } :: _ -> None | { kind } as h :: p when f kind -> Some (aux h p) | _ -> None let top_kind = function | KStruct|KSig|KParen|KBegin|KObject|KExtendedItem _|KAttrId _|KExtendedExpr _ -> true | _ -> false let stritem_kind = function | KModule|KVal|KLet|KExternal|KType|KException|KOpen|KInclude -> true | _ -> false (* Unwind the struct/sig top *) let unwind_top = unwind top_kind (* Get the parent node *) let parent = function | [] | {kind=KCodeInComment}::_ as t -> t | _ :: t -> t (* Get the next token, skipping comments (and in-comment tokens) *) let next_token_full = let rec skip depth stream = match Nstream.next stream with | None -> None | Some (tok,stream) -> match tok.token with | COMMENT -> skip depth stream | OCAMLDOC_VERB | OCAMLDOC_CODE -> skip (depth + 1) stream | COMMENTCONT -> if depth = 0 then None else skip (depth-1) stream | _ when depth = 0 -> Some (tok,stream) | _ -> skip depth stream in skip 0 let next_token stream = match next_token_full stream with | None -> None | Some (t,_) -> Some t.token let next_2_tokens stream = match next_token_full stream with | None -> None | Some (t1,s) -> match next_token s with | None -> None | Some t2 -> Some (t1.token, t2) let last_token t = let rec aux = function | [] -> None | {token = COMMENT | COMMENTCONT} :: r -> aux r | t :: _ -> Some t.token in aux t.last (* Returns whether there's an arrow coming up. Used to correctly indent labeled tuples VS labeled arguments. We stop looking after a predefined distance as in some, presumably extremely rare, corner case we could end up looking up quite far ahead. *) let in_arrow_type stream = let max_distance = 30 in let rec aux ~distance ~depth stream = match next_token_full stream with | None -> false (* distance acts as a failsafe *) | Some _ when distance >= max_distance -> false | Some (tok, stream) -> let distance = distance + 1 in match tok, depth with | {token = EOF}, _ -> false | {token = MINUSGREATER; _}, 0 -> true | {token = (* End of phrase *) ( SEMISEMI (* Begining of next item *) | LBRACKETATAT | LBRACKETPERCENTPERCENT | LINE_DIRECTIVE | MATCH | METHOD | CLASS | AND | BEGIN | MODULE | VAL | LET | DO | WHILE | FOR (* End of current core type *) | EQUAL | RPAREN | RBRACKET | RBRACE | GREATER | SEMI | COMMA | BAR | IN | DONE | WHEN | ELSE | THEN ) ; _}, 0 -> false | {token = ( LBRACKET | LBRACKETLESS | LBRACKETGREATER | LBRACKETAT | LBRACKETPERCENT | LPAREN | LESS ) ; _}, depth -> aux ~distance ~depth:(depth + 1) stream | {token = RPAREN | GREATER | RBRACKET; _}, _ -> (* Only reached when [depth > 0]. Does not track which is opened, undefined behaviour on incorrect code. *) aux ~distance ~depth:(depth - 1) stream | _ -> aux ~distance ~depth stream in aux ~distance:0 ~depth:0 stream (* a more efficient way to do this would be to store a "context-type" in the stack *) let rec is_inside_type path = match unwind (function | KParen | KBegin | KBracket | KBrace | KBracketBar | KVal | KLet | KLetIn | KBody (KVal | KLet | KLetIn) | KBody(KType|KExternal) | KColon | KStruct | KSig | KObject -> true | _ -> false) path with | {kind=KBody(KVal|KType|KExternal) | KColon}::_ -> true | {kind=KParen | KBegin | KBracket | KBrace}::p -> is_inside_type p | _ -> false (* Returns None if the current token ends a line, the offset of the next token otherwise *) let next_offset tok stream = match next_token_full stream with | None -> None | Some (next,_) -> if Region.end_line tok.region < Region.start_line next.region then None else Some next.offset let reset_padding ?(pad=0) path = Path.maptop (fun n -> {n with pad}) path let reset_line_indent config current_line path = let limit_overindent = match config.IndentConfig.i_max_indent with | Some m -> let m = max 0 (m - config.IndentConfig.i_base) in fun i -> min i m | None -> fun i -> i in let rec aux acc = function | {line} as t :: r when line = current_line -> aux (t::acc) r | p -> let p, acc, extra = match acc with | {kind = KParen|KBracket|KBrace|KBracketBar} as acc1 :: acc when acc1.line_indent = acc1.column -> (* ignore those if at start of line *) acc1 :: p, acc, acc1.pad | _ -> p, acc, 0 in List.fold_left (fun p t -> {t with indent = t.line_indent + limit_overindent (t.indent - t.line_indent) + extra} ::p) p acc in aux [] path let dump t = Printf.eprintf "\027[35m# \027[32m%8s\027[m %s\n%!" (match t.last with tok::_ -> shorten_string 30 (Lazy.force tok.substr) | _ -> "") (to_string t) (* different kinds of position: [T]: token aligned: the child is aligned with the token position [L]: line aligned: the child is aligned with the begining of line [A]: absolute position *) type pos = L | T | A of int (* position *) (* indent configuration of the infix operators *) let op_prio_align_indent config = let open IndentConfig in let align, indent = match config.i_align_ops with | true -> T, 0 | false -> L, config.i_base in let is_monadop s = match String.sub s 0 (min 2 (String.length s)) with | ">>" | ">|" | "@@" | "@>" | "|>" -> true | _ -> false in let is_monadop s = is_monadop s (* "*>>=", "+>>>", "/>>|", etc. *) || (String.length s > 3 && is_monadop (String.sub s 1 2)) in function (* anything else : -10 *) (* in -> : 0 *) | SEMI -> prio_semi,L,-2 (* special negative indent is only honored at beginning of line *) (* then else : 10 *) | BAR -> 10,T,-2 | OF -> 20,L,2 | LESSMINUS | COLONEQUAL -> 20,L,config.i_base | COMMA -> 30,align,-2 | MINUSGREATER -> prio_arrow,L,0 (* is an operator only in types *) | COLON -> prio_colon,T,config.i_base | COLONGREATER -> prio_colon,L,config.i_base | OR | BARBAR -> 40,T,0 | AMPERSAND | AMPERAMPER -> 50,T,0 | (INFIXOP0 s | INFIXOP1 s | INFIXOP2 s | INFIXOP3 s | INFIXOP4 s) (* these should deindent fun -> *) when is_monadop s -> prio_flatop,L,0 | INFIXOP0 s -> (match String.sub s 0 (min 2 (String.length s)) with | "|!" | "|>" -> prio_flatop,T,0 | _ -> 60,align,indent) | EQUAL | LESS | GREATER -> 60,align,0 | INFIXOP1 _ -> 70,align,indent | LBRACKETAT -> prio_lbracketat,align,indent | COLONCOLON -> 80,align,indent | INFIXOP2 _ | PLUSDOT | PLUS | MINUSDOT | MINUS -> 90,align,indent | INFIXOP3 _ | STAR -> prio_star,align,indent | INFIXOP4 _ -> 110,align,indent (* apply: 140 *) | AS -> prio_apply,L,0 | TILDE | QUESTION -> prio_apply,L,config.i_base | LABEL _ | OPTLABEL _ -> if config.i_align_params = Always then 145,T,config.i_base else 145,L,config.i_base | SHARP -> 150,align,config.i_base | DOT -> prio_dot,align,config.i_base | _ -> assert false let handle_dotted block tok = let starts_line = tok.newlines > 0 in let current_line = Region.start_line tok.region in let is_attr_id = function | { kind = KAttrId (_, dotted) } :: _ -> not dotted | _ -> false in let make_dotted_attr_id = function | { kind = KAttrId (names, _) } as node :: ({ kind = (KExtendedItem ([],_) | KExtendedExpr ([],_))} :: _ as path) -> { node with kind = KAttrId (names, true) } :: path | _ -> assert false in let is_dotted_attr_id = function | { kind = KExtendedExpr ([],_) } :: _ -> true | { kind = KExtendedItem ([],_) } :: _ -> true | { kind = KAttrId (_, dotted) } :: _ -> dotted | _ -> false in let make_attr_id name = function | ({ kind = (KExtendedItem ([],_) | KExtendedExpr ([],_)); indent; pad; } :: _ as path) -> let indent = if starts_line then indent + pad else indent + pad + String.length (Lazy.force tok.between) - 1 in let column = if starts_line then indent else block.toff + tok.offset in { kind = (KAttrId ([name], false)); indent; line_indent = indent; column; line = current_line; pad = 0 } :: path | ({ kind = KAttrId (names, _)} as node) :: path -> { node with kind = KAttrId (name :: names, false); } :: path | _ -> assert false in if is_dotted_attr_id block.path then match tok.token with | LIDENT s | UIDENT s -> Some (make_attr_id s block.path) | AND | AS | ASSERT | BEGIN | CLASS | CONSTRAINT | DO | DONE | DOWNTO | ELSE | END | EXCEPTION | EXTERNAL | FALSE | FOR | FUN | FUNCTION | FUNCTOR | IF | IN | INCLUDE | INHERIT | INITIALIZER | LAZY | LET | MATCH | METHOD | MODULE | MUTABLE | NEW | OBJECT | OF | OPEN | OR | PRIVATE | REC | SIG | STRUCT | THEN | TO | TRUE | TRY | TYPE | VAL | VIRTUAL | WHEN | WHILE | WITH -> Some (make_attr_id (Lazy.force tok.substr) block.path) | _ -> None else if is_attr_id block.path then match tok.token with | DOT -> Some (make_dotted_attr_id block.path) | _ -> None else None let ext_kind = function | LBRACKETPERCENT | LBRACKETPERCENTPERCENT -> ExtNode | LBRACKETAT | LBRACKETATAT | LBRACKETATATAT -> Attr | _ -> invalid_arg "ext_kind" (* Take a block, a token stream and a token. Return the new block stack. *) let rec update_path config block stream tok = let open IndentConfig in let starts_line = tok.newlines > 0 in let current_line = Region.start_line tok.region in let node replace kind pos pad path = let parent = Path.top path in if starts_line then let indent = match pos with | A p -> p | L -> parent.indent + if replace then 0 else parent.pad | T -> parent.column + if replace then 0 else parent.pad in { kind; indent; line_indent=indent; column=indent; pad; line = current_line } else let column = block.toff + tok.offset in { kind; indent = parent.indent; line_indent=parent.line_indent; column; pad; line = current_line } in (* Add a new child block *) let append kind pos ?(pad=config.i_base) = function | {kind = KAttrId (names, _)} :: ({kind = KExtendedItem ([],_) | KExtendedExpr ([],_) } as n) :: path -> let n = { n with kind = match n.kind with | KExtendedItem ([],k) -> KExtendedItem (List.rev names,k) | KExtendedExpr ([],k) -> KExtendedExpr (List.rev names,k) | _ -> assert false } in let path = {n with pad = config.i_ppx_stritem_ext } :: path in node false kind pos pad path :: path | path -> node false kind pos pad path :: path in (* replace the current block with a new one *) let replace kind pos ?(pad=config.i_base) path = match path with | [] | {kind=KCodeInComment} :: _ -> node true kind pos pad path :: path | _::t -> node true kind pos pad path :: t in (* Used when expressions are merged together (for example in "3 +" the "+" extends the lower-priority expression "3") *) let extend kind pos ?(pad=config.i_base) = function | [] | {kind=KCodeInComment} :: _ as path -> node true kind pos pad path :: path | h::p -> let negative_indent () = (* Special negative indent: relative, only at beginning of line, and when prio is changed or there is a paren to back-align to *) if pad >= 0 || not starts_line then None else match p with | {kind=KParen|KBracket|KBracketBar |KBrace|KBar _|KWith KBrace|KBody _} as paren :: _ when paren.line = h.line -> let paren_len = match paren.kind with | KParen | KBracket | KBrace | KBar _ | KBody _ -> 1 | KBracketBar -> 2 | KWith KBrace -> 4 | _ -> assert false in let indent = paren.column + paren_len + 1 (* usually 1 space *) + pad in Some ({ h with kind; indent; column=indent; line_indent = indent-pad; pad = max h.pad (h.indent-indent)} :: p) | _ -> match kind,h.kind with | KExpr pk, KExpr ph when ph = pk -> (* respect the indent of the above same-priority term, we assume it was already back-indented *) Some ({ h with kind; indent=h.column; column=h.column; line_indent = h.column; pad = h.pad } :: p) | _ -> let indent = h.column + pad in if indent < 0 then None else Some ({ h with kind; indent; column=indent; line_indent = indent-pad; pad = -pad } :: p) in match negative_indent () with | Some p -> p | None -> (* normal case *) (* change indent to set the starting column of the expression *) let pad = max 0 pad in let indent,pad = if pos = T then h.column, pad else (* set indent of the whole expr accoring to its parent *) Path.indent p + Path.pad p, pad in let line_indent = if starts_line then indent else h.line_indent in { h with kind; indent; line_indent; pad } :: p in (* use before appending a new expr_atom: checks if that may cause an apply and folds parent exprs accordingly *) let fold_expr path = match path with | {kind=KExpr _} as e :: ({kind=KFun} as fn) :: p -> {fn with line_indent = e.line_indent} :: p | {kind=KExpr i} as e :: _ when i = prio_max -> (* we are appending two expr_atom next to each other: this is an apply. *) (* this "folds" the left-side of the apply *) let p = match unwind_while (fun kind -> prio kind >= prio_apply) path with | Some({kind=KExpr i} as e1 :: p) when i = prio_apply -> {e1 with line_indent = e.line_indent} :: p | Some({kind=KExpr _; line} :: {kind=KModule|KInclude|KOpen|KBody KModule} :: _ as p) -> (* ignore align_params for functor application *) extend (KExpr prio_apply) L (reset_line_indent config line p) | Some({kind=KExpr _; line} :: {kind=KArrow (KMatch|KTry) | KTry | KMatch; line=arrow_line}::_ as p) when config.i_align_params = Auto && line = arrow_line -> (* Special case: switch to token-aligned (see test js-args) *) extend (KExpr prio_apply) T p | Some p -> extend (KExpr prio_apply) (if config.i_align_params = Always then T else L) p | None -> assert false in p | _ -> path in let before_append_atom = function | {kind=KWith(KTry|KMatch as m)}::parent as path -> (* Special case: 'match with' and no bar for the 1st case: we append a virtual bar for alignment *) let path = match parent with | {kind = KExpr i} :: _ when i = prio_flatop -> reset_padding path | _ -> path in let p = append (KBar m) L ~pad:2 path in if not starts_line then let column = max 0 (block.toff + tok.offset - 2) in Path.maptop (fun h -> {h with column}) p else p | path -> fold_expr path in let atom path = let path = before_append_atom path in let pad = match path with {kind=KExpr _; pad}::_ -> pad | _ -> config.i_base in append expr_atom L ~pad path in let open_paren kind path = let path = before_append_atom path in let path = if config.i_align_params = Never || next_offset tok stream = None then reset_line_indent config current_line path else path in let p = append kind L path in let p = match p with (* Special case: paren after arrow has extra indent (see test js-begin) *) | {kind=KParen|KBegin|KBracket|KBracketBar|KBrace} :: {kind=KArrow _} :: _ when not starts_line -> Path.shift p config.i_base | p -> p in match p with | [] -> [] | h::p as path -> if config.i_align_params = Never then path else match kind with | KBegin -> path | KParen when if not config.i_align_ops then not starts_line else match next_token_full stream with | Some({token = SIG|STRUCT|OBJECT}, _) -> true | Some({token = MODULE}, stream) when next_token stream = Some STRUCT -> true | _ -> false -> path | _ -> (* set alignment for next lines relative to [ *) (match next_offset tok stream with | Some pad -> let indent = if starts_line then h.indent else block.toff + tok.offset in { h with indent; column=indent; pad } :: p | None -> if starts_line then path else {h with column = h.indent + h.pad} :: p) in let close f path = (* Remove the padding for the closing brace/bracket/paren/etc. *) Path.maptop (fun h -> {h with kind=expr_atom; pad=0}) (unwind f path) in let make_infix tok path = let op_prio, align, indent = op_prio_align_indent config tok.token in let in_delim_block () = match unwind_while (fun kind -> prio kind >= op_prio) path with | Some ({ kind = KExpr _; line } :: { kind = (KBrace|KParen|KBracket|KBracketBar); line = bline } :: _) -> line = bline | _ -> false in (* special cases *) let indent = (* don't back-indent operators when alone on their line (except BAR because that would disrupt typing) *) if indent < 0 && tok.token <> BAR && not (tok.token = SEMI && in_delim_block ()) && next_offset tok stream = None then 0 else indent in match path with | {kind=KExpr prio}::_ when prio >= op_prio && prio < prio_max -> (* we are just after another operator (should be an atom). handle as unary (eg. x + -y) : indented but no effect on following expressions *) (* append KUnknown L path *) append (KExpr prio) L ~pad:(max 0 indent) path | _ -> match unwind_while (fun kind -> prio kind >= op_prio) path with | Some p -> extend (KExpr op_prio) align ~pad:indent p | None -> (* used as prefix ? Don't apply T indent *) append (KExpr op_prio) L ~pad:(max 0 indent) path in (* KComment/KUnknown nodes correspond to comments or top-level stuff, they shouldn't be taken into account when indenting the next token *) let block0 = block in let block = match block.path with | {kind=KComment _|KVerbatim _|KUnknown}::path -> {block with path} | _ -> block in (* Handles labels [:] in type expressions, trying to determine whether the label belongs to a tuple or an upcoming arrow type. *) let tuple_or_argument_label () = let after_star = match block.path with | {kind = KExpr 200; _} :: {kind = KExpr 100; _} :: _ -> (* Our [:] is after `*