diff --git a/deps/deep_merge/.fetch b/deps/deep_merge/.fetch new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/deps/deep_merge/.formatter.exs b/deps/deep_merge/.formatter.exs new file mode 100644 index 0000000000000000000000000000000000000000..1f9a976bd42595757e110935b2275d1177344d28 --- /dev/null +++ b/deps/deep_merge/.formatter.exs @@ -0,0 +1,9 @@ +[ + inputs: [ + "lib/**/*.{ex,exs}", + "test/**/*.{ex,exs}", + "mix/**/*.{ex,exs}", + "./mix.exs", + ] +] + diff --git a/deps/deep_merge/.hex b/deps/deep_merge/.hex new file mode 100644 index 0000000000000000000000000000000000000000..d46172236095a0ffe9651d2b361371459c7f4e93 Binary files /dev/null and b/deps/deep_merge/.hex differ diff --git a/deps/deep_merge/CHANGELOG.md b/deps/deep_merge/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..5202dcb4d0e04c06b51752052f27d23060f23ebf --- /dev/null +++ b/deps/deep_merge/CHANGELOG.md @@ -0,0 +1,16 @@ +## 1.0.0 (2019-03-26) + +* Added the possibility to `@derive [DeepMerge.Resolver]` if you want your custom structs to also easily be deep_mergeable +* added type specs +* Changed elixir support to ~> 1.6 + +Considered feature complete (tm) - unless you come with great feature ideas of course ;) + +## 0.2.0 (2018-07-27) + +* Remove compile warnings on elixir 1.7 +* Remove 1.2 from the build matrix (was getting big, should still work) + +## 0.1.1 (2016-11-29) + +* Remove warnings when run with elixir 1.4.0-rc.0 diff --git a/deps/deep_merge/LICENSE.md b/deps/deep_merge/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..c9ece1998ffac157bc6418b60286eda5e2909539 --- /dev/null +++ b/deps/deep_merge/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Tobias Pfeiffer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/deps/deep_merge/README.md b/deps/deep_merge/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a22458849ba922189a71e720c2aadb454c843724 --- /dev/null +++ b/deps/deep_merge/README.md @@ -0,0 +1,123 @@ +# DeepMerge [![Hex Version](https://img.shields.io/hexpm/v/deep_merge.svg)](https://hex.pm/packages/deep_merge) [![docs](https://img.shields.io/badge/docs-hexpm-blue.svg)](https://hexdocs.pm/deep_merge/) [![Build Status](https://travis-ci.org/PragTob/deep_merge.svg?branch=master)](https://travis-ci.org/PragTob/deep_merge) [![Coverage Status](https://coveralls.io/repos/github/PragTob/deep_merge/badge.svg?branch=master)](https://coveralls.io/github/PragTob/deep_merge?branch=master) [![Inline docs](http://inch-ci.org/github/PragTob/deep_merge.svg?branch=master)](http://inch-ci.org/github/PragTob/deep_merge) + +Provides functionality for "deep merging" maps and keyword lists in elixir, which is if during merging both values at the same key are maps/keyword lists merge them recursively. This is done via a protocol so can be extended for your own structs/data types if needbe. + +``` +iex> DeepMerge.deep_merge(%{a: 1, b: [x: 10, y: 9]}, %{b: [y: 20, z: 30], c: 4}) +%{a: 1, b: [x: 10, y: 20, z: 30], c: 4} +``` + +This functionality can be useful for instance when merging a default configuration with a user supplied custom configuration: + +```elixir +DeepMerge.deep_merge(default_config, custom_config) # => merged configuration +``` + +Further features include: + +* It handles both maps and keyword lists +* It does not merge structs or maps with structs… +* …but you can implement the simple DeepMerge.Resolver protocol for types/structs of your choice to also make them deep mergable (there is also a default implementation) +* a deep_merge/3 variant that gets a function similar to Map.merge/3 to modify the merging behavior, for instance in case you don't want keyword lists to be merged or you want all lists to be appended + +I wanted this to be a feature of Elixir itself, however the proposal [was rejected](https://github.com/elixir-lang/elixir/pull/5339) hence this library exists :) + +## Installation + +Add `deep_merge` to your list of dependencies in `mix.exs`: + + ```elixir + def deps do + [{:deep_merge, "~> 1.0"}] + end + ``` + +## General Usage - deep_merge/2 + +Using this library is quite simple (and you might also want to look at the [hexdocs](https://hexdocs.pm/deep_merge/api-reference.html)) - just pass two structures to be deep merged into `DeepMerge.deep_merge/2`: + +```elixir +iex> DeepMerge.deep_merge(%{a: 1, b: %{x: 10, y: 9}}, %{b: %{y: 20, z: 30}, c: 4}) +%{a: 1, b: %{x: 10, y: 20, z: 30}, c: 4} + +iex> DeepMerge.deep_merge([a: 1, b: [x: 10, y: 9]], [b: [y: 20, z: 30], c: 4]) +[a: 1, b: [x: 10, y: 20, z: 30], c: 4] +``` + +It is worth noting that structs are not deeply merged - not with each other and not with normal maps. This is because structs, while internally a map, are more like their own data types and therefore should not be deeply merged... unless you implement the protocol provided by this library for them. + +## Customization via protocols + +What is merged and how is defined by implementing the `DeepMerge.Resolver` protocol. This library implements it for `Map`, `List` and falls back to `Any` (where the right hand side value/override is taken). + +If you want your own struct to be deeply merged you can simply `@derive` the protocole: + +```elixir +defmodule Derived do + @derive [DeepMerge.Resolver] + defstruct [:attrs] +end +``` + + +If you want to change the deep merge for a custom struct you can do so. An example implementation might look like this if you want to deeply merge your struct but only against non `nil` values (because all keys are always there) if you merge against the same struct (but still merge with maps): + +```elixir +defimpl DeepMerge.Resolver, for: MyStruct do + def resolve(original, override = %MyStruct{}, resolver) do + cleaned_override = + override + |> Map.from_struct() + |> Enum.reject(fn {_key, value} -> is_nil(value) end) + |> Map.new() + + Map.merge(original, cleaned_override, resolver) + end + + def resolve(original, override, resolver) when is_map(override) do + Map.merge(original, override, resolver) + end +end +``` + +In this implementation, `MyStruct` structs are merged with other `MyStruct` structs, omitting nil values. The arguments passed to `resolve` are the original value (left hand side) and the override value (right hand side, which would normally replace the original). The third parameter is a `resolver` function which you can pass to `Map.merge/3`/`Keyword.merge/3` to continue the deep merge. + +## Customization via deep_merge/3 + +There is another deep merge variant that is a bit like `Map.merge/3` as it takes an additional function which you can use to alter the deep merge behavior: + +```elixir +iex> resolver = fn +...> (_, original, override) when is_list(original) and is_list(override) -> +...> override +...> (_, _original, _override) -> +...> DeepMerge.continue_deep_merge +...> end +iex> DeepMerge.deep_merge(%{a: %{b: 1}, c: [d: 1]}, +...> %{a: %{z: 5}, c: [x: 0]}, resolver) +%{a: %{b: 1, z: 5}, c: [x: 0]} +``` + +This function is called for a given merge conflict with the key where it occured and the two conflicting values. Whatever value is returned in this function is inserted at that point in the structure - unless `DeepMerge.continue_deep_merge` is returned in which case the deep merge continues as normal. + +When would you want to use this versus a protocol? The best use case I can think of is when you want to alter behavior for which a protocol is already implemented or if you care about specific keys. + +In the example above the behavior is changed so that keyword lists are not deep_merged (if they were the result would contain `c: [d: 1, x:0]`), but maps still are if that's what you are looking for. + +## Do I really need a library for this? + +Well not necessarily, no. There are [very simple implementations for maps that use Map.merge/3](http://stackoverflow.com/a/38865647). + +There are subtle things that can be missed there though (and I missed the first time around): + +* the most simple implementation also merges structs which is not always what you want +* For keyword lists on the other hand you gotta be careful that you don't accidentally merge keyword lists with lists as that's [currently possible](https://github.com/elixir-lang/elixir/issues/5395) +* you might want to further adopt the implementation, in [benchee](https://github.com/bencheeorg/benchee) we have 2 custom implementations of the protocol due to our needs + +This library takes care of those problems and will take care of further problems/edge cases should they appear so you can focus on your business logic. + +At the same time it offers extension mechanisms through protocols and a function in `deep_merge/3`. So, it should be adjustable to your use case and if not please open an issue :) + +## Considered feature-complete + +Unless you come with great feature ideas of course ;) So if you come here and there are no recent commits, don't worry - there are no known bugs or whatever. It's a small little library that does its job. \ No newline at end of file diff --git a/deps/deep_merge/hex_metadata.config b/deps/deep_merge/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..89b26501646b2ea54682e4a50ea97271f67f54f7 --- /dev/null +++ b/deps/deep_merge/hex_metadata.config @@ -0,0 +1,14 @@ +{<<"app">>,<<"deep_merge">>}. +{<<"build_tools">>,[<<"mix">>]}. +{<<"description">>, + <<"Deep (recursive) merging for maps, keyword lists and whatever else\nyou may want via implementing a simple protocol.">>}. +{<<"elixir">>,<<"~> 1.6">>}. +{<<"files">>, + [<<"lib">>,<<"lib/deep_merge.ex">>,<<"lib/deep_merge">>, + <<"lib/deep_merge/resolver.ex">>,<<".formatter.exs">>,<<"mix.exs">>, + <<"README.md">>,<<"LICENSE.md">>,<<"CHANGELOG.md">>]}. +{<<"licenses">>,[<<"MIT">>]}. +{<<"links">>,[{<<"github">>,<<"https://github.com/PragTob/deep_merge">>}]}. +{<<"name">>,<<"deep_merge">>}. +{<<"requirements">>,[]}. +{<<"version">>,<<"1.0.0">>}. diff --git a/deps/deep_merge/lib/deep_merge.ex b/deps/deep_merge/lib/deep_merge.ex new file mode 100644 index 0000000000000000000000000000000000000000..8bd76133bab30f2a86e31ef773b632c993eac0b7 --- /dev/null +++ b/deps/deep_merge/lib/deep_merge.ex @@ -0,0 +1,145 @@ +defmodule DeepMerge do + @moduledoc """ + Provides functionality for deeply/recursively merging structures (normally for + `Map` and `Keyword`). + + If you want to change the deep merge behavior of a custom struct, + please have a look at the `DeepMerge.Resolver` protocol. + """ + + alias DeepMerge.Resolver + @continue_symbol :__deep_merge_continue + + @doc """ + Deeply merges two maps or keyword list `original` and `override`. + + In more detail, if two conflicting values are maps or keyword lists themselves + then they will also be merged recursively. This is an extension in that sense + to what `Map.merge/2` and `Keyword.merge/2` do as it doesn't just override map + or keyword values but tries to merge them. + + It does not merge structs or structs with maps. If you want your structs to be + merged then please have a look at the `DeepMerge.Resolver` protocol and + consider implementing/deriving it. + + Also, while it says `Map` and `Keyword` here, it is really dependent on which + types implement the `DeepMerge.Resolver` protocol, which by default are `Map` + and `Keyword`. + + ## Examples + + iex> DeepMerge.deep_merge(%{a: 1, b: [x: 10, y: 9]}, %{b: [y: 20, z: 30], c: 4}) + %{a: 1, b: [x: 10, y: 20, z: 30], c: 4} + + iex> DeepMerge.deep_merge(%{a: 1, b: %{x: 10, y: 9}}, %{b: %{y: 20, z: 30}, c: 4}) + %{a: 1, b: %{x: 10, y: 20, z: 30}, c: 4} + + iex> DeepMerge.deep_merge(%{a: 1, b: %{x: 10, y: 9}}, %{b: %{y: 20, z: 30}, c: 4}) + %{a: 1, b: %{x: 10, y: 20, z: 30}, c: 4} + + iex> DeepMerge.deep_merge([a: 1, b: [x: 10, y: 9]], [b: [y: 20, z: 30], c: 4]) + [a: 1, b: [x: 10, y: 20, z: 30], c: 4] + + iex> DeepMerge.deep_merge(%{a: 1, b: 2}, %{b: 3, c: 4}) + %{a: 1, b: 3, c: 4} + + iex> DeepMerge.deep_merge(%{a: 1, b: %{x: 10, y: 9}}, %{b: 5, c: 4}) + %{a: 1, b: 5, c: 4} + + iex> DeepMerge.deep_merge([a: [b: [c: 1, d: 2], e: [24]]], [a: [b: [f: 3], e: [42, 100]]]) + [a: [b: [c: 1, d: 2, f: 3], e: [42, 100]]] + + iex> DeepMerge.deep_merge(%{a: 1, b: 5}, %{b: %{x: 10, y: 9}, c: 4}) + %{a: 1, b: %{x: 10, y: 9}, c: 4} + + iex> DeepMerge.deep_merge(%{a: [b: %{c: [d: "foo", e: 2]}]}, %{a: [b: %{c: [d: "bar"]}]}) + %{a: [b: %{c: [e: 2, d: "bar"]}]} + """ + @spec deep_merge(map() | keyword(), map | keyword()) :: map() | keyword() + def deep_merge(original, override) + when (is_map(original) or is_list(original)) and (is_map(override) or is_list(override)) do + standard_resolve(nil, original, override) + end + + @doc """ + A variant of `DeepMerge.deep_merge/2` that allows to modify the merge behavior + through the additional passed in function. + + This is similar to the relationship between `Map.merge/2` and `Map.merge/3` + and the structure of the function is exactly the same, e.g. the passed in + arguments are `key`, `original` and `override`. + + The function is called before a merge is performed. If it returns any value + that value is inserted at that point during the deep_merge. If the deep merge + should continue like normal you need to return the symbol returned by + `DeepMerge.continue_deep_merge/0`. + + If the merge conflict occurs at the top level then `key` is `nil`. + + The example shows how this can be used to modify `deep_merge` not to merge + keyword lists, in case you don't like that behavior. + + ## Examples + + iex> resolver = fn + ...> (_, original, override) when is_list(original) and is_list(override) -> + ...> override + ...> (_, _original, _override) -> + ...> DeepMerge.continue_deep_merge + ...> end + iex> DeepMerge.deep_merge(%{a: %{b: 1}, c: [d: 1]}, + ...> %{a: %{z: 5}, c: [x: 0]}, resolver) + %{a: %{b: 1, z: 5}, c: [x: 0]} + """ + @spec deep_merge(map() | keyword(), map() | keyword(), (any(), any() -> any())) :: + map() | keyword() + def deep_merge(original, override, resolve_function) + when (is_map(original) or is_list(original)) and (is_map(override) or is_list(override)) do + resolver = build_resolver(resolve_function) + resolver.(nil, original, override) + end + + @doc """ + The symbol to return in the function in `deep_merge/3` when deep merging + should continue as normal. + + ## Examples + + iex> DeepMerge.continue_deep_merge + :__deep_merge_continue + """ + @spec continue_deep_merge() :: :__deep_merge_continue + def continue_deep_merge, do: @continue_symbol + + @spec build_resolver((any(), any() -> any())) :: (any(), any(), any() -> any()) + defp build_resolver(resolve_function) do + my_resolver = fn key, base, override, fun -> + resolved_value = resolve_function.(key, base, override) + + case resolved_value do + @continue_symbol -> + continue_deep_merge(base, override, fun) + + _anything -> + resolved_value + end + end + + rebuild_resolver(my_resolver) + end + + defp rebuild_resolver(resolve_function) do + fn key, base, override -> + resolve_function.(key, base, override, resolve_function) + end + end + + defp continue_deep_merge(base, override, fun) do + resolver = rebuild_resolver(fun) + Resolver.resolve(base, override, resolver) + end + + defp standard_resolve(_key, original, override) do + Resolver.resolve(original, override, &standard_resolve/3) + end +end diff --git a/deps/deep_merge/lib/deep_merge/resolver.ex b/deps/deep_merge/lib/deep_merge/resolver.ex new file mode 100644 index 0000000000000000000000000000000000000000..b3864ec1479c779fabf0258ff9dc2db95a12443c --- /dev/null +++ b/deps/deep_merge/lib/deep_merge/resolver.ex @@ -0,0 +1,122 @@ +defprotocol DeepMerge.Resolver do + @moduledoc """ + Protocol defining how conflicts during deep_merge should be resolved. + + As part of the DeepMerge library this protocol is already implemented for + `Map` and `List` as well as a fallback to `Any` (which just always takes the + override). + + If you want your custom structs to also be deeply mergable and not just + override one another (default behaviour) you can derive the protocol: + + defmodule Derived do + @derive [DeepMerge.Resolver] + defstruct [:attrs] + end + + It will then automatically be deeply merged with structs of its own kind, not + with other structs or maps though. + """ + @fallback_to_any true + + @doc """ + Defines what happens when a merge conflict occurs on this struct during a + deep_merge. + + Can be implemented for additional data types to implement custom deep merging + behavior. + + The passed in values are: + * `original` - the value in the original data structure, usually left side + argument + * `override` - the value with which `original` would be overridden in a + normal `Map.merge/2` + * `resolver` - the function used by DeepMerge to resolve merge conflicts, + i.e. what you can pass to `Map.merge/3` and `Keyword.merge/3` to continue + deeply merging. + + An example implementation might look like this if you want to deeply merge + your struct but only against non `nil` values (because all keys are always there) + if you merge against the same struct (but still merge with maps): + + defimpl DeepMerge.Resolver, for: MyStruct do + def resolve(original, override = %MyStruct{}, resolver) do + cleaned_override = + override + |> Map.from_struct() + |> Enum.reject(fn {_key, value} -> is_nil(value) end) + |> Map.new() + + Map.merge(original, cleaned_override, resolver) + end + + def resolve(original, override, resolver) when is_map(override) do + Map.merge(original, override, resolver) + end + end + """ + def resolve(original, override, resolver) +end + +defimpl DeepMerge.Resolver, for: Map do + @doc """ + Resolve the merge between two maps by continuing to deeply merge them. + + Don't merge structs or if its any other type take the override value. + """ + def resolve(_original, override = %{__struct__: _}, _fun) do + override + end + + def resolve(original, override, resolver) when is_map(override) do + Map.merge(original, override, resolver) + end + + def resolve(_original, override, _fun), do: override +end + +defimpl DeepMerge.Resolver, for: List do + @doc """ + Deeply merge keyword lists but avoid overriding a keywords with an empty list. + """ + def resolve(original = [{_k, _v} | _], override = [{_, _} | _], resolver) do + Keyword.merge(original, override, resolver) + end + + def resolve(original = [{_k, _v} | _tail], _override = [], _fun) do + original + end + + def resolve(_original, override, _fun), do: override +end + +defimpl DeepMerge.Resolver, for: Any do + @doc """ + Fall back to always taking the override. + + Also the implementation for `@derive [DeppMerge.Resolver]` where structs of the same type that + implement the protocol are deeply merged. + """ + def resolve(original = %{__struct__: struct}, override = %{__struct__: struct}, resolver) do + implementors = get_implementors(DeepMerge.Resolver.__protocol__(:impls)) + + if Enum.member?(implementors, struct) do + Map.merge(original, override, resolver) + else + override + end + end + + def resolve(_original, override, _fun), do: override + + defp get_implementors({:consolidated, implementors}), do: implementors + + defp get_implementors(:not_consolidated) do + IO.warn( + "Protocols not consolidated and trying to merge two structs of the same type. Not supported!" + ) + + # let the code work with override semantics without being intrusive + [] + end +end diff --git a/deps/deep_merge/mix.exs b/deps/deep_merge/mix.exs new file mode 100644 index 0000000000000000000000000000000000000000..95ba7e8c0f3f7a9baa3ec988c4a2b9a5545f1486 --- /dev/null +++ b/deps/deep_merge/mix.exs @@ -0,0 +1,70 @@ +defmodule DeepMerge.Mixfile do + use Mix.Project + + @version "1.0.0" + + def project do + [ + app: :deep_merge, + version: @version, + elixir: "~> 1.6", + build_embedded: Mix.env() == :prod, + start_permanent: Mix.env() == :prod, + elixirc_paths: elixirc_paths(Mix.env()), + deps: deps(), + docs: [source_ref: @version], + test_coverage: [tool: ExCoveralls], + preferred_cli_env: [ + coveralls: :test, + "coveralls.detail": :test, + "coveralls.post": :test, + "coveralls.html": :test, + "coveralls.travis": :test + ], + package: package(), + name: "deep_merge", + source_url: "https://github.com/PragTob/deep_merge", + dialyzer: [ + flags: [:unmatched_returns, :error_handling, :race_conditions, :underspecs], + ignore_warnings: ".dialyzer_ignore.exs", + list_unused_filters: true + ], + description: """ + Deep (recursive) merging for maps, keyword lists and whatever else + you may want via implementing a simple protocol. + """ + ] + end + + # Specifies which paths to compile per environment. + defp elixirc_paths(:test), do: ["lib", "test/support"] + defp elixirc_paths(_), do: ["lib"] + + # Configuration for the OTP application + # + # Type "mix help compile.app" for more information + def application do + [] + end + + defp deps do + [ + {:credo, "~> 1.0", only: :dev}, + {:ex_doc, "~> 0.11", only: :dev}, + {:earmark, "~> 1.2", only: :dev}, + {:excoveralls, "~> 0.7", only: :test}, + {:inch_ex, "~> 0.5", only: :docs}, + {:dialyxir, "~> 1.0.0-rc.4", only: [:dev], runtime: false} + ] + end + + defp package do + [ + maintainers: ["Tobias Pfeiffer"], + licenses: ["MIT"], + links: %{ + "github" => "https://github.com/PragTob/deep_merge" + } + ] + end +end diff --git a/deps/eini/.hex b/deps/eini/.hex new file mode 100644 index 0000000000000000000000000000000000000000..fc45250151eb8363ad8ecc027e9e6ac30c0a8bed Binary files /dev/null and b/deps/eini/.hex differ diff --git a/deps/eini/LICENSE b/deps/eini/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/deps/eini/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/deps/eini/README.md b/deps/eini/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fa80edc9801e10d7453965582812f16b21285f9a --- /dev/null +++ b/deps/eini/README.md @@ -0,0 +1,37 @@ +eini-beam - An Erlang INI parser +================================ +This is just an INI parser. That's it. No state, no gen_servers, no ets tables, +just a parser that returns a map and does not convert strings into atoms. + +You're probably looking for the original: https://github.com/erlcloud/eini + +Example +------- + +Input file: +``` + [title1] + key = value + key2 = value2 + [title2] + key = value +``` + +Result form: +``` + #{ <<"title1">> => #{ <<"key">> => <<"value">>, + <<"key2">> => <<"value2">> }, + <<"title2">> => #{ <<"key">> => <<"value">> } + } +``` + +History +------- +This is a fork to decruft the parser of things it doesn't need (supervision, +ETS, gen_server) and make it use maps and not convert to atoms. We renamed +the repo in 2021 so we could publish it to hex. + +Copyright +--------- +Copyright 2011 by Accense Technology, Inc. +Copyright 2018 by Mark R. Allen diff --git a/deps/eini/_build/default/plugins/hex_core/CHANGELOG.md b/deps/eini/_build/default/plugins/hex_core/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..ac9078262cb0e03bf209175f9ba276d57b4f1e2b --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/CHANGELOG.md @@ -0,0 +1,222 @@ +# CHANGELOG + +## v0.12.2 (2026-02-27) + +* Exclude `src/safe_erl_term.erl` from package. + +## v0.12.1 (2026-02-27) + +* Fix unsafe deserialization of Erlang terms in API responses (CVE-2026-21619). + +## v0.12.0 (2025-10-26) + +* Add short URL API `hex_api_short_url:create/2`. +* Add OAuth API: + * `hex_api_oauth:device_authorization/3,4` + * `hex_api_oauth:poll_device_token/3` + * `hex_api_oauth:refresh_token/3` + * `hex_api_oauth:revoke_token/3` + * `hex_api_oauth:client_credentials_token/4,5` +* Support 2FA authentication, any API request can now return `{error, otp_required | invalid_totp}` + if 2FA is required. The config option `api_otp` can be used to provide the TOTP code. +* Differentiate between registry verification errors. `{error, unverified}` has been replaced with + `{error, bad_repo_name | bad_signature}`. +* Support nested maps in `extra` package metadata field. + +## v0.11.0 (2024-12-03) + +* Use secure SSL defaults for OTP 25+. +* Start inets and ssl applications. + +## v0.10.3 (2024-06-28) + +* Fix `hex_api_release:retirement_params/0` type spec. + +## v0.10.2 (2024-06-12) + +* Fix `hex_tarball:create_docs/1` type spec. + +## v0.10.1 (2024-06-11) + +* Drop support for OTP 20. +* Update `hex_licenses` module to reflect most recent list available from SPDX. + +## v0.10.0 (2023-05-09) + +* Drop support for old OTP and Rebar versions. `hex_core` now requires OTP20+ and Rebar 3.15.1+. + +* Add `hex_repo:get_docs/3` and `hex_repo:get_public_key/1`. + +## v0.9.0 (2022-11-03) + +* Change `hex_registry` functions to match protobuf fields + + Before: + + > hex_registry:unpack_names(Payload, <<"test">>, TestPublicKey) + {ok,[#{name => <<"package1">>, ...}, + #{name => <<"package2">>, ...}]} + + After: + + > hex_registry:unpack_names(Payload, <<"test">>, TestPublicKey) + {ok,#{packages => [#{name => <<"package1">>, ...}, + #{name => <<"package2">>, ...}], + repository: <<"test">>}} + +* Change `hex_repo` functions to match protobuf fields + + Before: + + > hex_repo:get_names(Config), + {ok,{200, ..., + [#{name => <<"pacakge2">>, ...}, + #{name => <<"pacakge2">>, ...}, + ...]}} + + After: + + > hex_repo:get_names(Config), + {ok,{200, ..., + #{packages => [#{name => <<"pacakge2">>, ...}, + #{name => <<"pacakge2">>, ...}, + ...], + repository => <<"test">>}}} + +## v0.8.4 (2021-12-20) + +* Add `@doc` to `hex_licenses` + +## v0.8.3 (2021-12-14) + +* Don't warn on non-https URLs +* Add `hex_licenses` module + +## v0.8.2 (2021-05-28) + +* Warn on unsafe httpc default SSL settings + +## v0.8.1 (2021-05-20) + +* Update gpb to 4.17.6 to avoid dialyzer warnings + +## v0.8.0 (2021-05-02) + +* Deprecate registry encode/decode API in favour of new high-level build/unpack API +* Add `updated_at` to repository names resource + +## v0.7.1 (2020-10-12) + +* Fix dialyzer warnings on OTP 23 + +## v0.7.0 (2020-10-20) + +* Fix compatibility with OTP 24 +* Change `hex_tarball:create/2` error value from `{error, too_big}` to `{tarball, {too_big_compressed | too_big_uncompressed, Size}}`. + +## v0.6.10 (2020-08-25) + +* Add configuration for max tarball size +* Do not create extraneous "memory" directory when unpacking + +## v0.6.9 (2020-05-24) + +* Add `hex_api_release:publish/3` + +## v0.6.8 (2020-02-04) + +* Fix tarball file extraction through symlinks + +## v0.6.7 (2020-02-03) + +* Fix compatibility with OTP 18 and 17 + +## v0.6.6 (2020-02-03) + +* Do not crash on empty tarballs +* Fix directory traversal vulnerability for symlinks in tarballs + +## v0.6.5 (2020-01-14) + +* Transition away from `http_uri` when using newer OTP releases +* Ensure `Role` is given as an atom in `hex_api_organization_member:add/3` +* Add `http_headers` to the `hex_core:config()` type +* Add default `http_headers` to `hex_core:default_config/0` +* Fix `hex_registry:decode_and_verify_signed/2` spec +* Fix `hex_tarball:files/0` type + +## v0.6.4 (2019-12-27) + +* Fix setting level and transfer options in organization api + +## v0.6.3 (2019-12-16) + +* Add organization API +* Add level and transfer params to add owner API +* Add `hex_tarball:unpack_docs/2` +* Add `hex_api_auth:test_key/3` + +## v0.6.2 (2019-11-11) + +* Gracefully handle HTTP errors + +## v0.6.1 (2019-07-30) + +* Fix bug when publishing with configuration that does not have `repo_organization` key set + +## v0.6.0 (2019-07-27) + +* **Backwards-incompatible**: Change successful return value of `hex_tarball:create/2` from + `{ok, {Tarball, Checksum}}` to `{ok, Map}`. Currently, `Map` has `tarball`, `inner_tarball`, + and `outer_tarball` keys +* Rename existing tarball checksum to inner checksum and deprecate it +* Add tarball outer checksum +* Do not allow comments in `safe_erl_term` +* Forward compatible tarball contents by not failing on unknown files + +## v0.5.1 (2019-07-30) + +* Fix bug when publishing with configuration that does not have `repo_organization` key set + +## v0.5.0 (2019-02-26) + +* Fetch package data from proper repository organization and don't verify origin if configured +* **Backwards-incompatible**: Make `hex_api` module private +* **Backwards-incompatible**: `organization` config key has been replaced with `api_organization` + and `api_repository` keys +* Add `repo_organization` config key +* `vendor.sh`: Add missing `hex_pb_*.erl` files +* `vendor.sh`: Fix replacing `hex_core` + +## v0.4.0 (2018-12-30) + +* Revert switch from proto2 to proto3 +* Verify authenticity of signed payload +* Add `repo_verify_origin` config option + +## v0.3.0 (2018-12-14) + +* Switch from proto2 to proto3 +* Fix `hex_http:body` type +* Fix `hex_http:request` spec + +## v0.2.1 (2018-12-13) + +* Always return the whole response tuple from requests +* Guess rebar3 as build tool over rebar +* Return compressed tarball from hex_tarball:create_docs/1 +* Add package identity to registry records + +## v0.2.0 (2018-09-01) + +* Accept `{filename(), filename()}` in files list for tarballs +* Support httpc profile through adapter configs +* Update generated protobuf files with OTP 21 compatibility + +## v0.1.1 (2018-08-11) + +* Use `hex_core` project name in user agent string + +## v0.1.0 (2018-08-08) + +* First release diff --git a/deps/eini/_build/default/plugins/hex_core/LICENSE b/deps/eini/_build/default/plugins/hex_core/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4c82636099ef694c991d528cc07c05a2923f3d50 --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/LICENSE @@ -0,0 +1,191 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2018, Six Colors AB + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/deps/eini/_build/default/plugins/hex_core/README.md b/deps/eini/_build/default/plugins/hex_core/README.md new file mode 100644 index 0000000000000000000000000000000000000000..99d366d13abcd33435c233c4aba0f30a425bc404 --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/README.md @@ -0,0 +1,244 @@ +# hex_core + +[![Build Status](https://github.com/hexpm/hex_core/actions/workflows/main.yml/badge.svg)](https://github.com/hexpm/hex_core/actions/workflows/main.yml) + +Reference implementation of Hex specifications: . + +## Usage + +Let's use default config for now. See "Configuration" section below for customization. + +```erlang +Config = hex_core:default_config(). +``` + +**WARNING** The built-in httpc-based HTTP client adapter has insecure default settings +and thus it is not recommended for usage, in particular for API write operations. +Use HTTP clients with secure defaults like [hackney](https://hex.pm/packages/hackney) and [Mint](https://hex.pm/packages/mint). +See "Configuration" and "Wrapper Module" sections for more information on customising your usage of `hex_core`. + +### Repository + +Get all package names: + +```erlang +> hex_repo:get_names(Config). +{ok,{200, ..., + #{packages => [ + #{name => <<"package1">>}, + #{name => <<"package2">>}, + ...]}}} +``` + +Get all package versions from repository: + +```erlang +> hex_repo:get_versions(Config). +{ok,{200, ..., + #{packages => [[ + #{name => <<"package1">>, retired => [], versions => [<<"1.0.0">>]}, + #{name => <<"package2">>, retired => [], versions => [<<"0.5.0">>]}, + ...]}}} +``` + +Get package releases from repository: + +```erlang +> hex_repo:get_package(Config, <<"package1">>). +{ok,{200, ..., + #{releases => [ + #{checksum => ..., version => <<"0.5.0">>, dependencies => []}], + #{checksum => ..., version => <<"1.0.0">>, dependencies => []}], + ...]}}} +``` + +### API + +For a full list of all parameters and returned objects for the API, check out the API docs: . + +Get package from HTTP API: + +```erlang +> hex_api_package:get(Config, <<"package1">>). +{ok, {200, ..., + #{ + <<"name">> => <<"package1">>, + <<"meta">> => #{ + <<"description">> => ..., + <<"licenses">> => ..., + <<"links">> => ..., + <<"maintainers">> => ..., + }, + ..., + <<"releases">> => [ + #{<<"url">> => ..., <<"version">> => <<"0.5.0">>}], + #{<<"url">> => ..., <<"version">> => <<"1.0.0">>}], + ... + ] + }}} +``` + +Get package tarball: + +```erlang +{ok, {200, _, Tarball}} = hex_repo:get_tarball(Config, <<"package1">>, <<"1.0.0">>). +``` + +Publish package tarball: + +```erlang +{ok, {200, _Headers, _Body} = hex_api_package:publish(Config, Tarball). +``` + +### Two-Factor Authentication + +When using OAuth tokens, two-factor authentication may be required. If required, the server will return `{error, otp_required}` and you should retry the request with the TOTP code via the `api_otp` configuration option. If the TOTP code is incorrect, the server will return `{error, invalid_totp}` and you should retry with the correct TOTP code. + +```erlang +%% First attempt without OTP +case hex_api_release:publish(Config, Tarball) of + {error, otp_required} -> + %% Retry with TOTP code + ConfigWithOTP = Config#{api_otp := <<"123456">>}, + hex_api_release:publish(ConfigWithOTP, Tarball); + {error, invalid_totp} -> + %% Retry with correct TOTP code + ConfigWithOTP = Config#{api_otp := <<"123456">>}, + hex_api_release:publish(ConfigWithOTP, Tarball); + Result -> + Result +end. +``` + +API keys don't require TOTP validation. + +### Package tarballs + +Unpack package tarball: + +```erlang +{ok, #{outer_checksum := Checksum, contents := Contents, metadata := Metadata}} = hex_tarball:unpack(Tarball, memory). +``` + +Remember to verify the outer tarball checksum against the registry checksum +returned from `hex_repo:get_package(Config, Package)`. + +Create package tarball: + +```erlang +{ok, #{tarball := Tarball, + inner_checksum := InnerChecksum, + outer_checksum := OuterChecksum}} = hex_tarball:create(Metadata, Contents). +``` + +## Configuration + +The default configuration, provided by `hex_core:default_config/0`, uses built-in httpc-based adapter and Hex.pm APIs: + and . + +HTTP client configuration can be overridden as follows: + +```erlang +Config = maps:merge(hex_core:default_config(), #{ + http_adapter => {my_hackney_adapter, my_hackney_adapter_config}, + http_user_agent_fragment => <<"(my_app/0.1.0) (hackney/1.12.1) ">> +}), +hex_repo:get_names(Config). + +%% my_hackney_adapter.erl +-module(my_hackney_adapter). +-behaviour(hex_http). +-exports([request/5]). + +request(Method, URI, ReqHeaders, Body, AdapterConfig) -> + %% ... +``` + +See the [`hex_core` module](src/hex_core.erl) for more information about the configuration. + +## Wrapper Module + +It's recommended to write a wrapper module because a lot of decisions are left to the user, e.g.: +where to get configuration from, how to handle caching, failures etc. + +For a sample, see: [`examples/myapp_hex.erl`](examples/myapp_hex.erl). Here's an excerpt: + +```erlang +-module(myapp_hex). +-export([ + get_api_package/1, + get_repo_tarball/2, + get_repo_versions/0 +]). + +%%==================================================================== +%% API functions +%%==================================================================== + +get_api_package(Name) -> + case hex_api_package:get(config(), Name) of + {ok, {200, _Headers, Payload}} -> + {ok, Payload}; + + Other -> + Other + end. + +get_repo_versions() -> + case hex_repo:get_versions(config()) of + {ok, {200, _Headers, Payload}} -> + {ok, maps:get(packages, Payload)}; + + Other -> + Other + end. + +%%==================================================================== +%% Internal functions +%%==================================================================== + +config() -> + Config1 = hex_core:default_config(), + Config2 = put_http_config(Config1), + Config3 = maybe_put_api_key(Config2), + Config3. + +put_http_config(Config) -> + maps:put(http_user_agent_fragment, <<"(myapp/1.0.0) (httpc)">>, Config). + +maybe_put_api_key(Config) -> + case os:getenv("HEX_API_KEY") of + false -> Config; + Key -> maps:put(api_key, Key, Config) + end. +``` + +## Installation + +### Rebar3 + +Add to `rebar.config`: + +```erlang +{deps, [ + {hex_core, "0.12.2"} +]} +``` + +### Mix + +Add to `mix.exs`: + +```elixir +defp deps do + [ + {:hex_core, "~> 0.12.2"} + ] +end +``` + +## Development + +* Run `rebar3 as dev compile` to re-generate protobuf files +* Run `rebar3 as test proper` for property-based tests +* Run `rebar3 ex_doc` to generate documentation diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_api.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api.beam new file mode 100644 index 0000000000000000000000000000000000000000..ed3c91c7a214af4fb993eb17cf19e984001d2bb8 Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_auth.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_auth.beam new file mode 100644 index 0000000000000000000000000000000000000000..6ebdb692c7202b926d56f7b91873570af64a05bf Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_auth.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_key.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_key.beam new file mode 100644 index 0000000000000000000000000000000000000000..33326094810c461c8c8453e02c2d2ae15d89c24e Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_key.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_oauth.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_oauth.beam new file mode 100644 index 0000000000000000000000000000000000000000..11e2a26f900d4816344e464e6938197e098d28e8 Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_oauth.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_organization.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_organization.beam new file mode 100644 index 0000000000000000000000000000000000000000..3c4291012b401517c46eaddc32cf5fa43cc98ffc Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_organization.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_organization_member.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_organization_member.beam new file mode 100644 index 0000000000000000000000000000000000000000..6a73d9369849ce061f395cbf3bf4273cba19cdba Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_organization_member.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_package.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_package.beam new file mode 100644 index 0000000000000000000000000000000000000000..d3abacc2401f85afc68fb2600a7dc7559d932768 Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_package.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_package_owner.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_package_owner.beam new file mode 100644 index 0000000000000000000000000000000000000000..a451c69bc96608f3111ffc79cc104622b29fd4f2 Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_package_owner.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_release.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_release.beam new file mode 100644 index 0000000000000000000000000000000000000000..427b82a08454daee2cfa92f1b9ec5cf0bb701468 Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_release.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_short_url.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_short_url.beam new file mode 100644 index 0000000000000000000000000000000000000000..8d47f8e3937ca8dc40451df9f55f2b1a358a7cd8 Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_short_url.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_user.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_user.beam new file mode 100644 index 0000000000000000000000000000000000000000..ee6b40b6221e6872bee8f3f77af33a5837f49537 Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_api_user.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_core.app b/deps/eini/_build/default/plugins/hex_core/ebin/hex_core.app new file mode 100644 index 0000000000000000000000000000000000000000..989d9432424d91140aef10b4200f625420be1c9a --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/ebin/hex_core.app @@ -0,0 +1,20 @@ +{application,hex_core, + [{description,"Reference implementation of Hex specifications"}, + {vsn,"0.12.2"}, + {registered,[]}, + {applications,[kernel,stdlib,inets,ssl]}, + {licenses,["Apache-2.0"]}, + {include_paths,["CHANGELOG.md"]}, + {exclude_paths,["src/safe_erl_term.erl"]}, + {links,[{"GitHub","https://github.com/hexpm/hex_core"}, + {"Hex specifications", + "https://github.com/hexpm/specifications"}]}, + {doc,"doc"}, + {modules,[hex_api,hex_api_auth,hex_api_key,hex_api_oauth, + hex_api_organization,hex_api_organization_member, + hex_api_package,hex_api_package_owner,hex_api_release, + hex_api_short_url,hex_api_user,hex_core,hex_erl_tar, + hex_filename,hex_http,hex_http_httpc,hex_licenses, + hex_pb_names,hex_pb_package,hex_pb_signed, + hex_pb_versions,hex_registry,hex_repo, + hex_safe_binary_to_term,hex_tarball,safe_erl_term]}]}. diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_core.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_core.beam new file mode 100644 index 0000000000000000000000000000000000000000..553932c32e458b15c9e78baebd0f0f317013a08d Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_core.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_erl_tar.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_erl_tar.beam new file mode 100644 index 0000000000000000000000000000000000000000..68055f2d63a8b4eaeb9e02e10b85393700a1e7c8 Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_erl_tar.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_filename.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_filename.beam new file mode 100644 index 0000000000000000000000000000000000000000..6f3a443a227b418c0e8625e8bf05e93077ddd804 Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_filename.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_http.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_http.beam new file mode 100644 index 0000000000000000000000000000000000000000..439aeca60c29a363b04e56187de6555c4bb65c69 Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_http.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_http_httpc.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_http_httpc.beam new file mode 100644 index 0000000000000000000000000000000000000000..b983fbd219368e9624b0be96af1a3e27aba16f65 Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_http_httpc.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_licenses.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_licenses.beam new file mode 100644 index 0000000000000000000000000000000000000000..d81d6c1e0107974a9bc466e828c0dfc9820e9436 Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_licenses.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_pb_names.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_pb_names.beam new file mode 100644 index 0000000000000000000000000000000000000000..00f3eb8bb46f2426c24de3ba9b0ac3f51322c097 Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_pb_names.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_pb_package.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_pb_package.beam new file mode 100644 index 0000000000000000000000000000000000000000..b276a33952fdb1a9af0d5482cbaea0c3e2d06087 Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_pb_package.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_pb_signed.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_pb_signed.beam new file mode 100644 index 0000000000000000000000000000000000000000..828a2a08f1fc6292a079eb4343da5c7cae4f3389 Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_pb_signed.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_pb_versions.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_pb_versions.beam new file mode 100644 index 0000000000000000000000000000000000000000..3fb709beed83318450b349bf81c5772c5864f57d Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_pb_versions.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_registry.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_registry.beam new file mode 100644 index 0000000000000000000000000000000000000000..b0f8f9bde426dab8fbf99a7eeb22330843091f8a Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_registry.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_repo.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_repo.beam new file mode 100644 index 0000000000000000000000000000000000000000..0f82818b87133c8e9fb8147aa341fb2187016c97 Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_repo.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_safe_binary_to_term.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_safe_binary_to_term.beam new file mode 100644 index 0000000000000000000000000000000000000000..b3904c14b3524f0f54ab66b1fbbf6ff07bf0a4cc Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_safe_binary_to_term.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/hex_tarball.beam b/deps/eini/_build/default/plugins/hex_core/ebin/hex_tarball.beam new file mode 100644 index 0000000000000000000000000000000000000000..1fbcba378e6ad20f1d7f25aade52f36a271edb73 Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/hex_tarball.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/ebin/safe_erl_term.beam b/deps/eini/_build/default/plugins/hex_core/ebin/safe_erl_term.beam new file mode 100644 index 0000000000000000000000000000000000000000..36bbf2dfb2907ea1b0ce65b0b567c2e79605169c Binary files /dev/null and b/deps/eini/_build/default/plugins/hex_core/ebin/safe_erl_term.beam differ diff --git a/deps/eini/_build/default/plugins/hex_core/hex_metadata.config b/deps/eini/_build/default/plugins/hex_core/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..514b2e2ab6bd6f042b2e43872ae7867ff74b62a2 --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/hex_metadata.config @@ -0,0 +1,27 @@ +{<<"app">>,<<"hex_core">>}. +{<<"build_tools">>,[<<"rebar3">>]}. +{<<"description">>,<<"Reference implementation of Hex specifications">>}. +{<<"files">>, + [<<"CHANGELOG.md">>,<<"LICENSE">>,<<"README.md">>,<<"rebar.config">>, + <<"rebar.config.script">>,<<"rebar.lock">>,<<"src">>,<<"src/hex_api.erl">>, + <<"src/hex_api_auth.erl">>,<<"src/hex_api_key.erl">>, + <<"src/hex_api_oauth.erl">>,<<"src/hex_api_organization.erl">>, + <<"src/hex_api_organization_member.erl">>,<<"src/hex_api_package.erl">>, + <<"src/hex_api_package_owner.erl">>,<<"src/hex_api_release.erl">>, + <<"src/hex_api_short_url.erl">>,<<"src/hex_api_user.erl">>, + <<"src/hex_core.app.src">>,<<"src/hex_core.erl">>,<<"src/hex_core.hrl">>, + <<"src/hex_erl_tar.erl">>,<<"src/hex_erl_tar.hrl">>, + <<"src/hex_filename.erl">>,<<"src/hex_http.erl">>, + <<"src/hex_http_httpc.erl">>,<<"src/hex_licenses.erl">>, + <<"src/hex_pb_names.erl">>,<<"src/hex_pb_package.erl">>, + <<"src/hex_pb_signed.erl">>,<<"src/hex_pb_versions.erl">>, + <<"src/hex_registry.erl">>,<<"src/hex_repo.erl">>, + <<"src/hex_safe_binary_to_term.erl">>,<<"src/hex_tarball.erl">>, + <<"src/safe_erl_term.xrl">>]}. +{<<"licenses">>,[<<"Apache-2.0">>]}. +{<<"links">>, + [{<<"GitHub">>,<<"https://github.com/hexpm/hex_core">>}, + {<<"Hex specifications">>,<<"https://github.com/hexpm/specifications">>}]}. +{<<"name">>,<<"hex_core">>}. +{<<"requirements">>,[]}. +{<<"version">>,<<"0.12.2">>}. diff --git a/deps/eini/_build/default/plugins/hex_core/rebar.config b/deps/eini/_build/default/plugins/hex_core/rebar.config new file mode 100644 index 0000000000000000000000000000000000000000..ae03520ecff7d2fb2abacf3f03347002cdf338b4 --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/rebar.config @@ -0,0 +1,67 @@ +{erl_opts, [ + debug_info +]}. + +{project_plugins, [rebar3_hex, rebar3_ex_doc, erlfmt]}. + +{gpb_opts, [ + {i, "proto"}, + {o_erl, "src"}, + {o_hrl, "src"}, + {verify, always}, + {strings_as_binaries, true}, + {maps, true}, + {maps_unset_optional, omitted}, + {report_warnings, true}, + {target_erlang_version, 17} +]}. + +{ex_doc, [ + {source_url, <<"https://github.com/hexpm/hex_core">>}, + {extras, [<<"README.md">>, <<"CHANGELOG.md">>]}, + {main, <<"readme">>} +]}. + +{hex, [{doc, #{provider => ex_doc}}]}. + +{erlfmt, [ + write, + {files, ["{src,test,examples}/*.{hrl,erl,app.src}", "rebar.config"]}, + {exclude_files, ["src/hex_pb_*.erl", "src/hex_erl_tar.{hrl,erl}"]} +]}. + +{profiles, [ + {dev, [ + {deps, [ + {gpb, "4.21.1"} + ]}, + {plugins, [ + {rebar3_gpb_plugin, "2.23.1"} + ]}, + {overrides, [ + {del, rebar3_gpb_plugin, [ + {deps, [gpb]} + ]} + ]}, + {provider_hooks, [ + {pre, [ + {compile, {protobuf, compile}}, + {clean, {protobuf, clean}} + ]} + ]} + ]}, + {test, [ + {erl_opts, [nowarn_export_all]}, + {ct_opts, [ + {create_priv_dir, auto_per_tc}, + {config, "test/ct.config"} + ]}, + {plugins, [ + rebar3_proper + ]}, + {deps, [ + {proper, "1.3.0"} + ]}, + {extra_src_dirs, ["test/support"]} + ]} +]}. diff --git a/deps/eini/_build/default/plugins/hex_core/rebar.config.script b/deps/eini/_build/default/plugins/hex_core/rebar.config.script new file mode 100644 index 0000000000000000000000000000000000000000..314f3b57c30e902964a26538bc1767b2bec04516 --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/rebar.config.script @@ -0,0 +1,9 @@ +case os:getenv("TARGET_ERLANG_VERSION") of + false -> CONFIG; + [] -> CONFIG; + TargetErlangVersionString -> + GpbOpts = proplists:get_value(gpb_opts, CONFIG), + TargetErlangVersion = {target_erlang_version, list_to_integer(TargetErlangVersionString)}, + NewGpbOpts = lists:keystore(target_erlang_version, 1, GpbOpts, TargetErlangVersion), + lists:keystore(gpb_opts, 1, CONFIG, {gpb_opts, NewGpbOpts}) +end. diff --git a/deps/eini/_build/default/plugins/hex_core/rebar.lock b/deps/eini/_build/default/plugins/hex_core/rebar.lock new file mode 100644 index 0000000000000000000000000000000000000000..57afcca04590ff2bbf2f83b8eac4f856df782c74 --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/rebar.lock @@ -0,0 +1 @@ +[]. diff --git a/deps/eini/_build/default/plugins/hex_core/src/hex_api.erl b/deps/eini/_build/default/plugins/hex_core/src/hex_api.erl new file mode 100644 index 0000000000000000000000000000000000000000..68734213dc38c3f356cbd1621725e39c6d06b193 --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/src/hex_api.erl @@ -0,0 +1,186 @@ +%% @doc +%% Hex HTTP API +-module(hex_api). + +-export([ + delete/2, + get/2, + post/3, + put/3, + encode_query_string/1, + build_repository_path/2, + build_organization_path/2, + join_path_segments/1 +]). +-define(ERL_CONTENT_TYPE, <<"application/vnd.hex+erlang">>). + +-export_type([response/0]). + +-type response() :: {ok, {hex_http:status(), hex_http:headers(), body() | nil}} | {error, term()}. +-type body() :: [body()] | #{binary() => body() | binary()}. + +%% @private +get(Config, Path) -> + request(Config, get, Path, undefined). + +%% @private +post(Config, Path, Body) -> + request(Config, post, Path, encode_body(Body)). + +%% @private +put(Config, Path, Body) -> + request(Config, put, Path, encode_body(Body)). + +%% @private +delete(Config, Path) -> + request(Config, delete, Path, undefined). + +%% @private +encode_query_string(List) -> + Pairs = lists:map(fun({K, V}) -> {to_list(K), to_list(V)} end, List), + list_to_binary(compose_query(Pairs)). + +%% OTP 21+ +%% @private +-ifdef(OTP_RELEASE). +compose_query(Pairs) -> + uri_string:compose_query(Pairs). +-else. +compose_query(Pairs) -> + String = join("&", lists:map(fun({K, V}) -> K ++ "=" ++ V end, Pairs)), + http_uri:encode(String). +-endif. + +%% @private +build_repository_path(#{api_repository := Repo}, Path) when is_binary(Repo) -> + ["repos", Repo | Path]; +build_repository_path(#{api_repository := undefined}, Path) -> + Path. + +%% @private +build_organization_path(#{api_organization := Org}, Path) when is_binary(Org) -> + ["orgs", Org | Path]; +build_organization_path(#{api_organization := undefined}, Path) -> + Path. + +%% @private +join_path_segments(Segments) -> + iolist_to_binary(recompose(Segments)). + +%% OTP 21+ +%% @private +-ifdef(OTP_RELEASE). +recompose(Segments) -> + Concatenated = join(<<"/">>, Segments), + %% uri_string:recompose/1 accepts path segments as a list, + %% both strings and binaries + uri_string:recompose(#{path => Concatenated}). +-else. +recompose(Segments) -> + join(<<"/">>, lists:map(fun encode_segment/1, Segments)). + +%% @private +encode_segment(Binary) when is_binary(Binary) -> + encode_segment(binary_to_list(Binary)); +encode_segment(String) when is_list(String) -> + http_uri:encode(String). +-endif. + +%%==================================================================== +%% Internal functions +%%==================================================================== + +request(Config, Method, PathSegments, Body) when is_list(PathSegments) -> + Path = join_path_segments(PathSegments), + request(Config, Method, Path, Body); +request(Config, Method, Path, Body) when is_binary(Path) and is_map(Config) -> + DefaultHeaders = make_headers(Config), + ReqHeaders = maps:merge(maps:get(http_headers, Config, #{}), DefaultHeaders), + ReqHeaders2 = put_new(<<"accept">>, ?ERL_CONTENT_TYPE, ReqHeaders), + + case hex_http:request(Config, Method, build_url(Path, Config), ReqHeaders2, Body) of + {ok, {Status, RespHeaders, RespBody}} -> + ContentType = maps:get(<<"content-type">>, RespHeaders, <<"">>), + Response = + case binary:match(ContentType, ?ERL_CONTENT_TYPE) of + {_, _} -> + case hex_safe_binary_to_term:safe_binary_to_term(RespBody) of + {ok, Term} -> + {ok, {Status, RespHeaders, Term}}; + {error, Reason} -> + {error, Reason} + end; + nomatch -> + {ok, {Status, RespHeaders, nil}} + end, + detect_otp_error(Response); + Other -> + Other + end. + +%% TODO: not needed after exdoc is fixed +%% @private +build_url(Path, #{api_url := URI}) -> + <>. + +%% TODO: not needed after exdoc is fixed +%% @private +encode_body({_ContentType, _Body} = Body) -> + Body; +encode_body(Body) -> + {binary_to_list(?ERL_CONTENT_TYPE), term_to_binary(Body)}. + +%% TODO: not needed after exdoc is fixed +%% @private +%% TODO: copy-pasted from hex_repo +make_headers(Config) -> + maps:fold(fun set_header/3, #{}, Config). + +%% TODO: not needed after exdoc is fixed +%% @private +set_header(api_key, Token, Headers) when is_binary(Token) -> + maps:put(<<"authorization">>, Token, Headers); +set_header(api_otp, OTP, Headers) when is_binary(OTP) -> + maps:put(<<"x-hex-otp">>, OTP, Headers); +set_header(_, _, Headers) -> + Headers. + +%% TODO: not needed after exdoc is fixed +%% @private +put_new(Key, Value, Map) -> + case maps:find(Key, Map) of + {ok, _} -> Map; + error -> maps:put(Key, Value, Map) + end. + +%% TODO: not needed after exdoc is fixed +%% @private +%% https://github.com/erlang/otp/blob/OTP-20.3/lib/stdlib/src/lists.erl#L1449:L1453 +join(_Sep, []) -> []; +join(Sep, [H | T]) -> [H | join_prepend(Sep, T)]. + +%% TODO: not needed after exdoc is fixed +%% @private +join_prepend(_Sep, []) -> []; +join_prepend(Sep, [H | T]) -> [Sep, H | join_prepend(Sep, T)]. + +%% TODO: not needed after exdoc is fixed +%% @private +to_list(A) when is_atom(A) -> atom_to_list(A); +to_list(B) when is_binary(B) -> unicode:characters_to_list(B); +to_list(I) when is_integer(I) -> integer_to_list(I); +to_list(Str) -> unicode:characters_to_list(Str). + +%% TODO: not needed after exdoc is fixed +%% @private +detect_otp_error({ok, {401, Headers, Body}}) -> + case maps:get(<<"www-authenticate">>, Headers, nil) of + <<"Bearer realm=\"hex\", error=\"totp_required\"", _/binary>> -> + {error, otp_required}; + <<"Bearer realm=\"hex\", error=\"invalid_totp\"", _/binary>> -> + {error, invalid_totp}; + _ -> + {ok, {401, Headers, Body}} + end; +detect_otp_error(Response) -> + Response. diff --git a/deps/eini/_build/default/plugins/hex_core/src/hex_api_oauth.erl b/deps/eini/_build/default/plugins/hex_core/src/hex_api_oauth.erl new file mode 100644 index 0000000000000000000000000000000000000000..e4d903f1685a4bc56d338592d0e516c3c9a03e55 --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/src/hex_api_oauth.erl @@ -0,0 +1,201 @@ +%% @doc +%% Hex HTTP API - OAuth. +-module(hex_api_oauth). +-export([ + device_authorization/3, + device_authorization/4, + poll_device_token/3, + refresh_token/3, + revoke_token/3, + client_credentials_token/4, + client_credentials_token/5 +]). + +%% @doc +%% Initiates the OAuth device authorization flow. +%% +%% @see device_authorization/4 +%% @end +-spec device_authorization(hex_core:config(), binary(), binary()) -> hex_api:response(). +device_authorization(Config, ClientId, Scope) -> + device_authorization(Config, ClientId, Scope, []). + +%% @doc +%% Initiates the OAuth device authorization flow with optional parameters. +%% +%% Returns device code, user code, and verification URIs for user authentication. +%% +%% Options: +%% * `name' - A name to identify the token (e.g., hostname of the device) +%% +%% Examples: +%% +%% ``` +%% 1> Config = hex_core:default_config(). +%% 2> hex_api_oauth:device_authorization(Config, <<"cli">>, <<"api:write">>). +%% {ok,{200, ..., #{ +%% <<"device_code">> => <<"...">>, +%% <<"user_code">> => <<"ABCD-1234">>, +%% <<"verification_uri">> => <<"https://hex.pm/oauth/device">>, +%% <<"verification_uri_complete">> => <<"https://hex.pm/oauth/device?user_code=ABCD-1234">>, +%% <<"expires_in">> => 600, +%% <<"interval">> => 5 +%% }}} +%% +%% 3> hex_api_oauth:device_authorization(Config, <<"cli">>, <<"api:write">>, [{name, <<"MyMachine">>}]). +%% ''' +%% @end +-spec device_authorization(hex_core:config(), binary(), binary(), proplists:proplist()) -> + hex_api:response(). +device_authorization(Config, ClientId, Scope, Opts) -> + Path = <<"oauth/device_authorization">>, + Params0 = #{ + <<"client_id">> => ClientId, + <<"scope">> => Scope + }, + Params = + case proplists:get_value(name, Opts) of + undefined -> Params0; + Name -> Params0#{<<"name">> => Name} + end, + hex_api:post(Config, Path, Params). + +%% @doc +%% Polls the OAuth token endpoint for device authorization completion. +%% +%% Returns: +%% - `{ok, {200, _, Token}}` - Authorization complete +%% - `{ok, {400, _, #{<<"error">> => <<"authorization_pending">>}}}` - Still waiting +%% - `{ok, {400, _, #{<<"error">> => <<"slow_down">>}}}` - Polling too fast +%% - `{ok, {400, _, #{<<"error">> => <<"expired_token">>}}}` - Code expired +%% - `{ok, {403, _, #{<<"error">> => <<"access_denied">>}}}` - User denied +%% +%% Examples: +%% +%% ``` +%% 1> Config = hex_core:default_config(). +%% 2> hex_api_oauth:poll_device_token(Config, <<"cli">>, DeviceCode). +%% {ok, {200, _, #{ +%% <<"access_token">> => <<"...">>, +%% <<"refresh_token">> => <<"...">>, +%% <<"token_type">> => <<"Bearer">>, +%% <<"expires_in">> => 3600 +%% }}} +%% ''' +%% @end +-spec poll_device_token(hex_core:config(), binary(), binary()) -> hex_api:response(). +poll_device_token(Config, ClientId, DeviceCode) -> + Path = <<"oauth/token">>, + Params = #{ + <<"grant_type">> => <<"urn:ietf:params:oauth:grant-type:device_code">>, + <<"device_code">> => DeviceCode, + <<"client_id">> => ClientId + }, + hex_api:post(Config, Path, Params). + +%% @doc +%% Refreshes an access token using a refresh token. +%% +%% Examples: +%% +%% ``` +%% 1> Config = hex_core:default_config(). +%% 2> hex_api_oauth:refresh_token(Config, <<"cli">>, RefreshToken). +%% {ok, {200, _, #{ +%% <<"access_token">> => <<"...">>, +%% <<"refresh_token">> => <<"...">>, +%% <<"token_type">> => <<"Bearer">>, +%% <<"expires_in">> => 3600 +%% }}} +%% ''' +%% @end +-spec refresh_token(hex_core:config(), binary(), binary()) -> hex_api:response(). +refresh_token(Config, ClientId, RefreshToken) -> + Path = <<"oauth/token">>, + Params = #{ + <<"grant_type">> => <<"refresh_token">>, + <<"refresh_token">> => RefreshToken, + <<"client_id">> => ClientId + }, + hex_api:post(Config, Path, Params). + +%% @doc +%% Exchanges an API key for an OAuth access token using the client credentials grant. +%% +%% @see client_credentials_token/5 +%% @end +-spec client_credentials_token(hex_core:config(), binary(), binary(), binary()) -> + hex_api:response(). +client_credentials_token(Config, ClientId, ApiKey, Scope) -> + client_credentials_token(Config, ClientId, ApiKey, Scope, []). + +%% @doc +%% Exchanges an API key for an OAuth access token using the client credentials grant with optional parameters. +%% +%% This grant type allows exchanging a long-lived API key for a short-lived OAuth access token. +%% The API key is sent as the client_secret parameter. +%% +%% Options: +%% * `name' - A name to identify the token (e.g., hostname of the client) +%% +%% Returns: +%% - `{ok, {200, _, Token}}` - Token exchange successful +%% - `{ok, {400, _, #{<<"error">> => ...}}}` - Invalid request or scope +%% - `{ok, {401, _, #{<<"error">> => ...}}}` - Invalid API key +%% +%% Examples: +%% +%% ``` +%% 1> Config = hex_core:default_config(). +%% 2> hex_api_oauth:client_credentials_token(Config, <<"cli">>, ApiKey, <<"api">>). +%% {ok, {200, _, #{ +%% <<"access_token">> => <<"...">>, +%% <<"token_type">> => <<"bearer">>, +%% <<"expires_in">> => 1800, +%% <<"scope">> => <<"api">> +%% }}} +%% +%% 3> hex_api_oauth:client_credentials_token(Config, <<"cli">>, ApiKey, <<"api">>, [{name, <<"MyMachine">>}]). +%% ''' +%% @end +-spec client_credentials_token( + hex_core:config(), binary(), binary(), binary(), proplists:proplist() +) -> hex_api:response(). +client_credentials_token(Config, ClientId, ApiKey, Scope, Opts) -> + Path = <<"oauth/token">>, + Params0 = #{ + <<"grant_type">> => <<"client_credentials">>, + <<"client_id">> => ClientId, + <<"client_secret">> => ApiKey, + <<"scope">> => Scope + }, + Params = + case proplists:get_value(name, Opts) of + undefined -> Params0; + Name -> Params0#{<<"name">> => Name} + end, + hex_api:post(Config, Path, Params). + +%% @doc +%% Revokes an OAuth token (RFC 7009). +%% +%% Can revoke either access tokens or refresh tokens. +%% Returns 200 OK regardless of whether the token was found, +%% following RFC 7009 security recommendations. +%% +%% Examples: +%% +%% ``` +%% 1> Config = hex_core:default_config(). +%% 2> hex_api_oauth:revoke_token(Config, <<"cli">>, Token). +%% {ok, {200, ..., nil}} +%% ''' +%% @end +-spec revoke_token(hex_core:config(), binary(), binary()) -> hex_api:response(). +revoke_token(Config, ClientId, Token) -> + Path = <<"oauth/revoke">>, + Params = #{ + <<"token">> => Token, + <<"client_id">> => ClientId + }, + hex_api:post(Config, Path, Params). diff --git a/deps/eini/_build/default/plugins/hex_core/src/hex_api_package_owner.erl b/deps/eini/_build/default/plugins/hex_core/src/hex_api_package_owner.erl new file mode 100644 index 0000000000000000000000000000000000000000..0250b652b5b3b601d7f658f5b7175765c8f52087 --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/src/hex_api_package_owner.erl @@ -0,0 +1,109 @@ +%% @doc +%% Hex HTTP API - Package Owners. +-module(hex_api_package_owner). +-export([ + add/5, + delete/3, + get/3, + list/2 +]). + +%% @doc +%% Lists the packages owners. +%% +%% Examples: +%% +%% ``` +%% > hex_api_package_owner:list(hex_core:default_config(), <<"package">>). +%% {ok, {200, ..., [#{ +%% <<"email">> => <<"user@example.com">>, +%% <<"full_name">> => <<"John Doe">>, +%% <<"handles">> => #{...}, +%% <<"inserted_at">> => <<"2014-04-21T17:20:12Z">>, +%% <<"level">> => <<"full">>, +%% <<"updated_at">> => <<"2019-08-04T19:28:05Z">>, +%% <<"url">> => <<"https://hex.pm/api/users/user">>, +%% <<"username">> => <<"user">> +%% }]}} +%% ''' +%% @end +-spec list(hex_core:config(), binary()) -> hex_api:response(). +list(Config, PackageName) when is_binary(PackageName) -> + Path = hex_api:build_repository_path(Config, ["packages", PackageName, "owners"]), + hex_api:get(Config, Path). + +%% @doc +%% Gets a packages owner. +%% +%% Examples: +%% +%% ``` +%% > hex_api_package_owner:get(hex_core:default_config(), <<"package">>, <<"user">>). +%% {ok, {200, ..., #{ +%% <<"email">> => <<"user@example.com">>, +%% <<"full_name">> => <<"John Doe">>, +%% <<"handles">> => #{...}, +%% <<"inserted_at">> => <<"2014-04-21T17:20:12Z">>, +%% <<"level">> => <<"full">>, +%% <<"updated_at">> => <<"2019-08-04T19:28:05Z">>, +%% <<"url">> => <<"https://hex.pm/api/users/user">>, +%% <<"username">> => <<"user">> +%% }}} +%% ''' +%% @end +-spec get(hex_core:config(), binary(), binary()) -> hex_api:response(). +get(Config, PackageName, UsernameOrEmail) when + is_map(Config) and is_binary(PackageName) and is_binary(UsernameOrEmail) +-> + Path = hex_api:build_repository_path(Config, [ + "packages", PackageName, "owners", UsernameOrEmail + ]), + hex_api:get(Config, Path). + +%% @doc +%% Adds a packages owner. +%% +%% Examples: +%% +%% ``` +%% > hex_api_package_owner:add(hex_core:default_config(), <<"package">>, <<"user">>, <<"full">>, false). +%% {ok, {200, ..., #{ +%% <<"email">> => <<"user@example.com">>, +%% <<"full_name">> => <<"John Doe">>, +%% <<"handles">> => #{...}, +%% <<"inserted_at">> => <<"2014-04-21T17:20:12Z">>, +%% <<"level">> => <<"full">>, +%% <<"updated_at">> => <<"2019-08-04T19:28:05Z">>, +%% <<"url">> => <<"https://hex.pm/api/users/user">>, +%% <<"username">> => <<"user">> +%% }}} +%% ''' +%% @end +-spec add(hex_core:config(), binary(), binary(), binary(), boolean()) -> hex_api:response(). +add(Config, PackageName, UsernameOrEmail, Level, Transfer) when + is_binary(PackageName) and is_binary(UsernameOrEmail) and is_map(Config) and is_binary(Level) and + is_boolean(Transfer) +-> + Path = hex_api:build_repository_path(Config, [ + "packages", PackageName, "owners", UsernameOrEmail + ]), + hex_api:put(Config, Path, #{<<"level">> => Level, <<"transfer">> => Transfer}). + +%% @doc +%% Deletes a packages owner. +%% +%% Examples: +%% +%% ``` +%% > hex_api_package_owner:delete(hex_core:default_config(), <<"package">>, <<"user">>). +%% {ok, {204, ..., nil}} +%% ''' +%% @end +-spec delete(hex_core:config(), binary(), binary()) -> hex_api:response(). +delete(Config, PackageName, UsernameOrEmail) when + is_map(Config) and is_binary(PackageName) and is_binary(UsernameOrEmail) +-> + Path = hex_api:build_repository_path(Config, [ + "packages", PackageName, "owners", UsernameOrEmail + ]), + hex_api:delete(Config, Path). diff --git a/deps/eini/_build/default/plugins/hex_core/src/hex_api_user.erl b/deps/eini/_build/default/plugins/hex_core/src/hex_api_user.erl new file mode 100644 index 0000000000000000000000000000000000000000..660bb59f8f2bc856d5dc3c6a63f92d22790becb9 --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/src/hex_api_user.erl @@ -0,0 +1,99 @@ +%% @doc +%% Hex HTTP API - Users. +-module(hex_api_user). +-export([ + create/4, + get/2, + me/1, + reset_password/2 +]). + +%% @doc +%% Gets the authenticated user. +%% +%% Examples: +%% +%% ``` +%% > hex_api_user:me(hex_core:default_config()). +%% {ok, {200, ..., #{ +%% <<"email">> => <<"user@example.com">>, +%% <<"full_name">> => <<"John Doe">>, +%% <<"handles">> => #{...}, +%% <<"inserted_at">> => <<"2014-04-21T17:20:12Z">>, +%% <<"level">> => <<"full">>, +%% <<"updated_at">> => <<"2019-08-04T19:28:05Z">>, +%% <<"url">> => <<"https://hex.pm/api/users/user">>, +%% <<"username">> => <<"user">> +%% }}} +%% ''' +%% @end +-spec me(hex_core:config()) -> hex_api:response(). +me(Config) when is_map(Config) -> + hex_api:get(Config, ["users", "me"]). + +%% @doc +%% Creates a new user account. +%% +%% Examples: +%% +%% ``` +%% > hex_api_user:create(hex_core:default_config(), <<"user">>, <<"hunter42">>, <<"user@example.com">>). +%% {ok, {201, ..., #{ +%% <<"email">> => <<"user@example.com">>, +%% <<"full_name">> => <<"John Doe">>, +%% <<"handles">> => #{...}, +%% <<"inserted_at">> => <<"2014-04-21T17:20:12Z">>, +%% <<"level">> => <<"full">>, +%% <<"updated_at">> => <<"2019-08-04T19:28:05Z">>, +%% <<"url">> => <<"https://hex.pm/api/users/user">>, +%% <<"username">> => <<"user">> +%% }}} +%% ''' +%% @end +-spec create(hex_core:config(), binary(), binary(), binary()) -> hex_api:response(). +create(Config, Username, Password, Email) when + is_map(Config) and is_binary(Username) and is_binary(Password) and is_binary(Email) +-> + Params = #{ + <<"username">> => Username, + <<"password">> => Password, + <<"email">> => Email + }, + hex_api:post(Config, ["users"], Params). + +%% @doc +%% Resets the user's password. +%% +%% Examples: +%% +%% ``` +%% > hex_api_user:reset_password(hex_core:default_config(), <<"user">>). +%% {ok, {204, ..., nil}} +%% ''' +%% @end +-spec reset_password(hex_core:config(), binary()) -> hex_api:response(). +reset_password(Config, Username) when is_map(Config) and is_binary(Username) -> + hex_api:post(Config, ["users", Username, "reset"], #{}). + +%% @doc +%% Gets a user. +%% +%% Examples: +%% +%% ``` +%% > hex_api_user:get(hex_core:default_config()). +%% {ok, {200, ..., #{ +%% <<"email">> => <<"user@example.com">>, +%% <<"full_name">> => <<"John Doe">>, +%% <<"handles">> => #{...}, +%% <<"inserted_at">> => <<"2014-04-21T17:20:12Z">>, +%% <<"level">> => <<"full">>, +%% <<"updated_at">> => <<"2019-08-04T19:28:05Z">>, +%% <<"url">> => <<"https://hex.pm/api/users/user">>, +%% <<"username">> => <<"user">> +%% }}} +%% ''' +%% @end +-spec get(hex_core:config(), binary()) -> hex_api:response(). +get(Config, Username) when is_map(Config) and is_binary(Username) -> + hex_api:get(Config, ["users", Username]). diff --git a/deps/eini/_build/default/plugins/hex_core/src/hex_core.erl b/deps/eini/_build/default/plugins/hex_core/src/hex_core.erl new file mode 100644 index 0000000000000000000000000000000000000000..1047fb04a525970d808632fec3c89efc424dd9fc --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/src/hex_core.erl @@ -0,0 +1,141 @@ +%% @doc +%% `hex_core' entrypoint module. +%% +%% === Config === +%% +%% Most functions in the `hex_core' API takes a configuration. The configuration sets things +%% like HTTP client to use, and API and repository URL. Some of these configuration options +%% will likely be static for your application and some may change depending on the function +%% you call. +%% +%% === Options === +%% +%% * `api_key' - Authentication key used when accessing the HTTP API. +%% +%% * `api_otp' - TOTP (Time-based One-Time Password) code for two-factor authentication. +%% When using OAuth tokens, write operations require 2FA if the user has it enabled. +%% If required, the server returns one of: +%% - `{error, otp_required}' - Retry the request with a 6-digit TOTP code in this option +%% - `{error, invalid_totp}' - The provided TOTP code was incorrect, retry with correct code +%% - `{ok, {403, _, #{<<"message">> => <<"Two-factor authentication must be enabled for API write access">>}}}' - User must enable 2FA first +%% - `{ok, {429, _, _}}' - Too many failed TOTP attempts, rate limited +%% API keys do not require TOTP validation. +%% +%% * `api_organization' - Name of the organization endpoint in the API, this should +%% for example be set when accessing key for a specific organization. +%% +%% * `api_repository' - Name of the repository endpoint in the API, this should +%% for example be set when accessing packages from a specific repository. +%% +%% * `api_url' - URL to the HTTP API (default: `https://hex.pm/api'). +%% +%% * `http_adapter' - A tuple of a callback module and its configuration used +%% for HTTP requests (default: `{hex_http_httpc, #{profile => default}}'). See +%% {@link hex_http} and {@link hex_http_httpc} for more information. +%% +%% * `http_etag' - Sets the `if-none-match' HTTP header with the given value to do a +%% conditional HTTP request. +%% +%% * `http_user_agent_fragment' - Will be appended to the `user-agent' HTTP header (default: `<<"(httpc)">>'). +%% +%% * `repo_key' - Authentication key used when accessing the repository. +%% +%% * `repo_name' - Name of the repository, used for verifying the repository signature +%% authenticity (default: `hexpm'). +%% +%% * `repo_public_key' - Public key used to verify the repository signature +%% (defaults to hexpm public key `https://hex.pm/docs/public_keys'). +%% +%% * `repo_url' - URL to the repository (default: `https://repo.hex.pm'). +%% +%% * `repo_organization' - Name of the organization repository, appends `/repos/:name' +%% to the repository URL and overrides the `repo_name' option. +%% +%% * `repo_verify' - If `true' will verify the repository signature (default: `true'). +%% +%% * `repo_verify_origin' - If `true' will verify the repository signature origin, +%% requires protobuf messages as of hex_core v0.4.0 (default: `true'). +%% +%% * `send_100_continue' - If `true' will send `Expect: 100-continue' header for +%% publish operations. This allows the server to validate authentication and +%% authorization before the client sends the request body (default: `true'). +%% +%% * `tarball_max_size' - Maximum size of package tarball, defaults to +%% `16_777_216' (16 MiB). Set to `infinity' to not enforce the limit. +%% +%% * `tarball_max_uncompressed_size' - Maximum size of uncompressed package tarball, defaults to +%% `134_217_728' (128 MiB). Set to `infinity' to not enforce the limit. +%% +%% * `docs_tarball_max_size' - Maximum size of docs tarball, defaults to +%% `16_777_216' (16 MiB). Set to `infinity' to not enforce the limit. +%% +%% * `docs_tarball_max_uncompressed_size' - Maximum size of uncompressed docs tarball, defaults to +%% `134_217_728' (128 MiB). Set to `infinity' to not enforce the limit. + +-module(hex_core). +-export([default_config/0]). + +-export_type([config/0]). + +%% https://hex.pm/docs/public_keys +-define(HEXPM_PUBLIC_KEY, << + "-----BEGIN PUBLIC KEY-----\n" + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApqREcFDt5vV21JVe2QNB\n" + "Edvzk6w36aNFhVGWN5toNJRjRJ6m4hIuG4KaXtDWVLjnvct6MYMfqhC79HAGwyF+\n" + "IqR6Q6a5bbFSsImgBJwz1oadoVKD6ZNetAuCIK84cjMrEFRkELtEIPNHblCzUkkM\n" + "3rS9+DPlnfG8hBvGi6tvQIuZmXGCxF/73hU0/MyGhbmEjIKRtG6b0sJYKelRLTPW\n" + "XgK7s5pESgiwf2YC/2MGDXjAJfpfCd0RpLdvd4eRiXtVlE9qO9bND94E7PgQ/xqZ\n" + "J1i2xWFndWa6nfFnRxZmCStCOZWYYPlaxr+FZceFbpMwzTNs4g3d4tLNUcbKAIH4\n" + "0wIDAQAB\n" + "-----END PUBLIC KEY-----" +>>). + +-type config() :: #{ + api_key => binary() | undefined, + api_otp => binary() | undefined, + api_organization => binary() | undefined, + api_repository => binary() | undefined, + api_url => binary(), + http_adapter => {module(), map()}, + http_etag => binary() | undefined, + http_headers => map(), + http_user_agent_fragment => binary(), + repo_key => binary() | undefined, + repo_name => binary(), + repo_public_key => binary(), + repo_url => binary(), + repo_organization => binary() | undefined, + repo_verify => boolean(), + repo_verify_origin => boolean(), + send_100_continue => boolean(), + tarball_max_size => pos_integer() | infinity, + tarball_max_uncompressed_size => pos_integer() | infinity, + docs_tarball_max_size => pos_integer() | infinity, + docs_tarball_max_uncompressed_size => pos_integer() | infinity +}. + +-spec default_config() -> config(). +default_config() -> + #{ + api_key => undefined, + api_otp => undefined, + api_organization => undefined, + api_repository => undefined, + api_url => <<"https://hex.pm/api">>, + http_adapter => {hex_http_httpc, #{profile => default}}, + http_etag => undefined, + http_headers => #{}, + http_user_agent_fragment => <<"(httpc)">>, + repo_key => undefined, + repo_name => <<"hexpm">>, + repo_public_key => ?HEXPM_PUBLIC_KEY, + repo_url => <<"https://repo.hex.pm">>, + repo_organization => undefined, + repo_verify => true, + repo_verify_origin => true, + send_100_continue => true, + tarball_max_size => 16 * 1024 * 1024, + tarball_max_uncompressed_size => 128 * 1024 * 1024, + docs_tarball_max_size => 16 * 1024 * 1024, + docs_tarball_max_uncompressed_size => 128 * 1024 * 1024 + }. diff --git a/deps/eini/_build/default/plugins/hex_core/src/hex_erl_tar.erl b/deps/eini/_build/default/plugins/hex_core/src/hex_erl_tar.erl new file mode 100644 index 0000000000000000000000000000000000000000..28ac0d290de1d7f0c5d5f7f3a31e1ca0def84230 --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/src/hex_erl_tar.erl @@ -0,0 +1,2014 @@ +%% @private +%% Copied from https://github.com/erlang/otp/blob/OTP-20.0.1/lib/stdlib/src/erl_tar.erl +%% with modifications: +%% - Change module name to `hex_erl_tar` +%% - Set tar mtimes to 0 and remove dependency on :os.system_time/1 +%% - Preserve modes when building tarball +%% - Do not crash if failing to write tar +%% - Allow setting file_info opts on :hex_erl_tar.add +%% - Add safe_relative_path_links/2 to check directory traversal vulnerability when extracting files, +%% it differs from OTP's current fix (2020-02-04) in that it checks regular files instead of +%% symlink targets. This allows creating symlinks with relative path targets such as `../tmp/log` +%% - Remove ram_file usage (backported from OTP master) + +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 1997-2017. All Rights Reserved. +%% +%% Licensed under the Apache License, Version 2.0 (the "License"); +%% you may not use this file except in compliance with the License. +%% You may obtain a copy of the License at +%% +%% http://www.apache.org/licenses/LICENSE-2.0 +%% +%% Unless required by applicable law or agreed to in writing, software +%% distributed under the License is distributed on an "AS IS" BASIS, +%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +%% See the License for the specific language governing permissions and +%% limitations under the License. +%% +%% %CopyrightEnd% +%% +%% This module implements extraction/creation of tar archives. +%% It supports reading most common tar formats, namely V7, STAR, +%% USTAR, GNU, BSD/libarchive, and PAX. It produces archives in USTAR +%% format, unless it must use PAX headers, in which case it produces PAX +%% format. +%% +%% The following references where used: +%% http://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5 +%% http://www.gnu.org/software/tar/manual/html_node/Standard.html +%% http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html +-module(hex_erl_tar). + +-export([init/3, + create/2, create/3, + extract/1, extract/2, + table/1, table/2, t/1, tt/1, + open/2, close/1, + add/3, add/4, add/5, + format_error/1]). + +-include_lib("kernel/include/file.hrl"). +-include_lib("hex_erl_tar.hrl"). + +%% Converts the short error reason to a descriptive string. +-spec format_error(term()) -> string(). +format_error(invalid_tar_checksum) -> + "Checksum failed"; +format_error(bad_header) -> + "Unrecognized tar header format"; +format_error({bad_header, Reason}) -> + lists:flatten(io_lib:format("Unrecognized tar header format: ~p", [Reason])); +format_error({invalid_header, negative_size}) -> + "Invalid header: negative size"; +format_error(invalid_sparse_header_size) -> + "Invalid sparse header: negative size"; +format_error(invalid_sparse_map_entry) -> + "Invalid sparse map entry"; +format_error({invalid_sparse_map_entry, Reason}) -> + lists:flatten(io_lib:format("Invalid sparse map entry: ~p", [Reason])); +format_error(invalid_end_of_archive) -> + "Invalid end of archive"; +format_error(eof) -> + "Unexpected end of file"; +format_error(integer_overflow) -> + "Failed to parse numeric: integer overflow"; +format_error({misaligned_read, Pos}) -> + lists:flatten(io_lib:format("Read a block which was misaligned: block_size=~p pos=~p", + [?BLOCK_SIZE, Pos])); +format_error(invalid_gnu_1_0_sparsemap) -> + "Invalid GNU sparse map (version 1.0)"; +format_error({invalid_gnu_0_1_sparsemap, Format}) -> + lists:flatten(io_lib:format("Invalid GNU sparse map (version ~s)", [Format])); +format_error(unsafe_path) -> + "The path points above the current working directory"; +format_error({Name,Reason}) -> + lists:flatten(io_lib:format("~ts: ~ts", [Name,format_error(Reason)])); +format_error(Atom) when is_atom(Atom) -> + file:format_error(Atom); +format_error(Term) -> + lists:flatten(io_lib:format("~tp", [Term])). + +%% Initializes a new reader given a custom file handle and I/O wrappers +-spec init(handle(), write | read, file_op()) -> {ok, reader()} | {error, badarg}. +init(Handle, AccessMode, Fun) when is_function(Fun, 2) -> + Reader = #reader{handle=Handle,access=AccessMode,func=Fun}, + {ok, Pos, Reader2} = do_position(Reader, {cur, 0}), + {ok, Reader2#reader{pos=Pos}}; +init(_Handle, _AccessMode, _Fun) -> + {error, badarg}. + +%%%================================================================ +%% Extracts all files from the tar file Name. +-spec extract(open_handle()) -> ok | {error, term()}. +extract(Name) -> + extract(Name, []). + +%% Extracts (all) files from the tar file Name. +%% Options accepted: +%% - cooked: Opens the tar file without mode `raw` +%% - compressed: Uncompresses the tar file when reading +%% - memory: Returns the tar contents as a list of tuples {Name, Bin} +%% - keep_old_files: Extracted files will not overwrite the destination +%% - {files, ListOfFilesToExtract}: Only extract ListOfFilesToExtract +%% - verbose: Prints verbose information about the extraction, +%% - {cwd, AbsoluteDir}: Sets the current working directory for the extraction +-spec extract(open_handle(), [extract_opt()]) -> + ok + | {ok, [{string(), binary()}]} + | {error, term()}. +extract({binary, Bin}, Opts) when is_list(Opts) -> + do_extract({binary, Bin}, Opts); +extract({file, Fd}, Opts) when is_list(Opts) -> + do_extract({file, Fd}, Opts); +extract(#reader{}=Reader, Opts) when is_list(Opts) -> + do_extract(Reader, Opts); +extract(Name, Opts) when is_list(Name); is_binary(Name), is_list(Opts) -> + do_extract(Name, Opts). + +do_extract(Handle, Opts) when is_list(Opts) -> + Opts2 = extract_opts(Opts), + Acc = if Opts2#read_opts.output =:= memory -> []; true -> ok end, + foldl_read(Handle, fun extract1/4, Acc, Opts2). + +extract1(eof, Reader, _, Acc) when is_list(Acc) -> + {ok, {ok, lists:reverse(Acc)}, Reader}; +extract1(eof, Reader, _, leading_slash) -> + error_logger:info_msg("erl_tar: removed leading '/' from member names\n"), + {ok, ok, Reader}; +extract1(eof, Reader, _, Acc) -> + {ok, Acc, Reader}; +extract1(#tar_header{name=Name,size=Size}=Header, Reader0, Opts, Acc0) -> + case check_extract(Name, Opts) of + true -> + case do_read(Reader0, Size) of + {ok, Bin, Reader1} -> + Acc = extract2(Header, Bin, Opts, Acc0), + {ok, Acc, Reader1}; + {error, _} = Err -> + throw(Err) + end; + false -> + {ok, Acc0, skip_file(Reader0)} + end. + +extract2(Header, Bin, Opts, Acc) -> + case write_extracted_element(Header, Bin, Opts) of + ok -> + case Header of + #tar_header{name="/"++_} -> + leading_slash; + #tar_header{} -> + Acc + end; + {ok, NameBin} when is_list(Acc) -> + [NameBin | Acc]; + {error, _} = Err -> + throw(Err) + end. + +%% Checks if the file Name should be extracted. +check_extract(_, #read_opts{files=all}) -> + true; +check_extract(Name, #read_opts{files=Files}) -> + ordsets:is_element(Name, Files). + +%%%================================================================ +%% The following table functions produce a list of information about +%% the files contained in the archive. +-type filename() :: string(). +-type typeflag() :: regular | link | symlink | + char | block | directory | + fifo | reserved | unknown. +-type mode() :: non_neg_integer(). +-type uid() :: non_neg_integer(). +-type gid() :: non_neg_integer(). + +-type tar_entry() :: {filename(), + typeflag(), + non_neg_integer(), + tar_time(), + mode(), + uid(), + gid()}. + +%% Returns a list of names of the files in the tar file Name. +-spec table(open_handle()) -> {ok, [string()]} | {error, term()}. +table(Name) -> + table(Name, []). + +%% Returns a list of names of the files in the tar file Name. +%% Options accepted: compressed, verbose, cooked. +-spec table(open_handle(), [compressed | verbose | cooked]) -> + {ok, [tar_entry()]} | {error, term()}. +table(Name, Opts) when is_list(Opts) -> + foldl_read(Name, fun table1/4, [], table_opts(Opts)). + +table1(eof, Reader, _, Result) -> + {ok, {ok, lists:reverse(Result)}, Reader}; +table1(#tar_header{}=Header, Reader, #read_opts{verbose=Verbose}, Result) -> + Attrs = table1_attrs(Header, Verbose), + Reader2 = skip_file(Reader), + {ok, [Attrs|Result], Reader2}. + +%% Extracts attributes relevant to table1's output +table1_attrs(#tar_header{typeflag=Typeflag,mode=Mode}=Header, true) -> + Type = typeflag(Typeflag), + Name = Header#tar_header.name, + Mtime = Header#tar_header.mtime, + Uid = Header#tar_header.uid, + Gid = Header#tar_header.gid, + Size = Header#tar_header.size, + {Name, Type, Size, Mtime, Mode, Uid, Gid}; +table1_attrs(#tar_header{name=Name}, _Verbose) -> + Name. + +typeflag(?TYPE_REGULAR) -> regular; +typeflag(?TYPE_REGULAR_A) -> regular; +typeflag(?TYPE_GNU_SPARSE) -> regular; +typeflag(?TYPE_CONT) -> regular; +typeflag(?TYPE_LINK) -> link; +typeflag(?TYPE_SYMLINK) -> symlink; +typeflag(?TYPE_CHAR) -> char; +typeflag(?TYPE_BLOCK) -> block; +typeflag(?TYPE_DIR) -> directory; +typeflag(?TYPE_FIFO) -> fifo; +typeflag(_) -> unknown. + +%%%================================================================ +%% Comments for printing the contents of a tape archive, +%% meant to be invoked from the shell. + +%% Prints each filename in the archive +-spec t(file:filename()) -> ok | {error, term()}. +t(Name) when is_list(Name); is_binary(Name) -> + case table(Name) of + {ok, List} -> + lists:foreach(fun(N) -> ok = io:format("~ts\n", [N]) end, List); + Error -> + Error + end. + +%% Prints verbose information about each file in the archive +-spec tt(open_handle()) -> ok | {error, term()}. +tt(Name) -> + case table(Name, [verbose]) of + {ok, List} -> + lists:foreach(fun print_header/1, List); + Error -> + Error + end. + +%% Used by tt/1 to print a tar_entry tuple +-spec print_header(tar_entry()) -> ok. +print_header({Name, Type, Size, Mtime, Mode, Uid, Gid}) -> + io:format("~s~s ~4w/~-4w ~7w ~s ~s\n", + [type_to_string(Type), mode_to_string(Mode), + Uid, Gid, Size, time_to_string(Mtime), Name]). + +type_to_string(regular) -> "-"; +type_to_string(directory) -> "d"; +type_to_string(link) -> "l"; +type_to_string(symlink) -> "s"; +type_to_string(char) -> "c"; +type_to_string(block) -> "b"; +type_to_string(fifo) -> "f"; +type_to_string(unknown) -> "?". + +%% Converts a numeric mode to its human-readable representation +mode_to_string(Mode) -> + mode_to_string(Mode, "xwrxwrxwr", []). +mode_to_string(Mode, [C|T], Acc) when Mode band 1 =:= 1 -> + mode_to_string(Mode bsr 1, T, [C|Acc]); +mode_to_string(Mode, [_|T], Acc) -> + mode_to_string(Mode bsr 1, T, [$-|Acc]); +mode_to_string(_, [], Acc) -> + Acc. + +%% Converts a tar_time() (POSIX time) to a readable string +time_to_string(Secs0) -> + Epoch = calendar:datetime_to_gregorian_seconds(?EPOCH), + Secs = Epoch + Secs0, + DateTime0 = calendar:gregorian_seconds_to_datetime(Secs), + DateTime = calendar:universal_time_to_local_time(DateTime0), + {{Y, Mon, Day}, {H, Min, _}} = DateTime, + io_lib:format("~s ~2w ~s:~s ~w", [month(Mon), Day, two_d(H), two_d(Min), Y]). + +two_d(N) -> + tl(integer_to_list(N + 100)). + +month(1) -> "Jan"; +month(2) -> "Feb"; +month(3) -> "Mar"; +month(4) -> "Apr"; +month(5) -> "May"; +month(6) -> "Jun"; +month(7) -> "Jul"; +month(8) -> "Aug"; +month(9) -> "Sep"; +month(10) -> "Oct"; +month(11) -> "Nov"; +month(12) -> "Dec". + +%%%================================================================ +%% The open function with friends is to keep the file and binary api of this module +-type open_handle() :: file:filename() + | {binary, binary()} + | {file, term()}. +-spec open(open_handle(), [write | compressed | cooked]) -> + {ok, reader()} | {error, term()}. +open({binary, Bin}, Mode) when is_binary(Bin) -> + do_open({binary, Bin}, Mode); +open({file, Fd}, Mode) -> + do_open({file, Fd}, Mode); +open(Name, Mode) when is_list(Name); is_binary(Name) -> + do_open(Name, Mode). + +do_open(Name, Mode) when is_list(Mode) -> + case open_mode(Mode) of + {ok, Access, Raw, Opts} -> + open1(Name, Access, Raw, Opts); + {error, Reason} -> + {error, {Name, Reason}} + end. + +open1({binary,Bin0}, read, _Raw, Opts) when is_binary(Bin0) -> + Bin = case lists:member(compressed, Opts) of + true -> + try + zlib:gunzip(Bin0) + catch + _:_ -> Bin0 + end; + false -> + Bin0 + end, + case file:open(Bin, [ram,binary,read]) of + {ok,File} -> + {ok, #reader{handle=File,access=read,func=fun file_op/2}}; + Error -> + Error + end; +open1({file, Fd}, read, _Raw, _Opts) -> + Reader = #reader{handle=Fd,access=read,func=fun file_op/2}, + case do_position(Reader, {cur, 0}) of + {ok, Pos, Reader2} -> + {ok, Reader2#reader{pos=Pos}}; + {error, _} = Err -> + Err + end; +open1(Name, Access, Raw, Opts) when is_list(Name) or is_binary(Name) -> + case file:open(Name, Raw ++ [binary, Access|Opts]) of + {ok, File} -> + {ok, #reader{handle=File,access=Access,func=fun file_op/2}}; + {error, Reason} -> + {error, {Name, Reason}} + end. + +open_mode(Mode) -> + open_mode(Mode, false, [raw], []). + +open_mode(read, _, Raw, _) -> + {ok, read, Raw, []}; +open_mode(write, _, Raw, _) -> + {ok, write, Raw, []}; +open_mode([read|Rest], false, Raw, Opts) -> + open_mode(Rest, read, Raw, Opts); +open_mode([write|Rest], false, Raw, Opts) -> + open_mode(Rest, write, Raw, Opts); +open_mode([compressed|Rest], Access, Raw, Opts) -> + open_mode(Rest, Access, Raw, [compressed|Opts]); +open_mode([cooked|Rest], Access, _Raw, Opts) -> + open_mode(Rest, Access, [], Opts); +open_mode([], Access, Raw, Opts) -> + {ok, Access, Raw, Opts}; +open_mode(_, _, _, _) -> + {error, einval}. + +file_op(write, {Fd, Data}) -> + file:write(Fd, Data); +file_op(position, {Fd, Pos}) -> + file:position(Fd, Pos); +file_op(read2, {Fd, Size}) -> + file:read(Fd, Size); +file_op(close, Fd) -> + file:close(Fd). + +%% Closes a tar archive. +-spec close(reader()) -> ok | {error, term()}. +close(#reader{access=read}=Reader) -> + ok = do_close(Reader); +close(#reader{access=write}=Reader) -> + {ok, Reader2} = pad_file(Reader), + ok = do_close(Reader2), + ok; +close(_) -> + {error, einval}. + +pad_file(#reader{pos=Pos}=Reader) -> + %% There must be at least two zero blocks at the end. + PadCurrent = skip_padding(Pos+?BLOCK_SIZE), + Padding = <<0:PadCurrent/unit:8>>, + do_write(Reader, [Padding, ?ZERO_BLOCK, ?ZERO_BLOCK]). + + +%%%================================================================ +%% Creation/modification of tar archives + +%% Creates a tar file Name containing the given files. +-spec create(file:filename(), filelist()) -> ok | {error, {string(), term()}}. +create(Name, FileList) when is_list(Name); is_binary(Name) -> + create(Name, FileList, []). + +%% Creates a tar archive Name containing the given files. +%% Accepted options: verbose, compressed, cooked +-spec create(file:filename(), filelist(), [create_opt()]) -> + ok | {error, term()} | {error, {string(), term()}}. +create(Name, FileList, Options) when is_list(Name); is_binary(Name) -> + Mode = lists:filter(fun(X) -> (X=:=compressed) or (X=:=cooked) + end, Options), + case open(Name, [write|Mode]) of + {ok, TarFile} -> + do_create(TarFile, FileList, Options); + {error, _} = Err -> + Err + end. + +do_create(TarFile, [], _Opts) -> + close(TarFile); +do_create(TarFile, [{NameInArchive, NameOrBin}|Rest], Opts) -> + case add(TarFile, NameOrBin, NameInArchive, Opts) of + ok -> + do_create(TarFile, Rest, Opts); + {error, _} = Err -> + _ = close(TarFile), + Err + end; +do_create(TarFile, [Name|Rest], Opts) -> + case add(TarFile, Name, Name, Opts) of + ok -> + do_create(TarFile, Rest, Opts); + {error, _} = Err -> + _ = close(TarFile), + Err + end. + +%% Adds a file to a tape archive. +-type add_type() :: string() + | {string(), string()} + | {string(), binary()}. +-spec add(reader(), add_type(), [add_opt()]) -> ok | {error, term()}. +add(Reader, {NameInArchive, Name}, Opts) + when is_list(NameInArchive), is_list(Name) -> + do_add(Reader, Name, NameInArchive, undefined, Opts); +add(Reader, {NameInArchive, Bin}, Opts) + when is_list(NameInArchive), is_binary(Bin) -> + do_add(Reader, Bin, NameInArchive, undefined, Opts); +add(Reader, {NameInArchive, Bin, Mode}, Opts) + when is_list(NameInArchive), is_binary(Bin), is_integer(Mode) -> + do_add(Reader, Bin, NameInArchive, Mode, Opts); +add(Reader, Name, Opts) when is_list(Name) -> + do_add(Reader, Name, Name, undefined, Opts). + + +-spec add(reader(), string() | binary(), string(), [add_opt()]) -> + ok | {error, term()}. +add(Reader, NameOrBin, NameInArchive, Options) + when is_list(NameOrBin); is_binary(NameOrBin), + is_list(NameInArchive), is_list(Options) -> + do_add(Reader, NameOrBin, NameInArchive, undefined, Options). + +-spec add(reader(), string() | binary(), string(), integer(), [add_opt()]) -> + ok | {error, term()}. +add(Reader, NameOrBin, NameInArchive, Mode, Options) + when is_list(NameOrBin); is_binary(NameOrBin), + is_list(NameInArchive), is_integer(Mode), is_list(Options) -> + do_add(Reader, NameOrBin, NameInArchive, Mode, Options). + +do_add(#reader{access=write}=Reader, Name, NameInArchive, Mode, Options) + when is_list(NameInArchive), is_list(Options) -> + RF = fun(F) -> apply_file_info_opts(Options, file:read_link_info(F, [{time, posix}])) end, + Opts = #add_opts{read_info=RF}, + add1(Reader, Name, NameInArchive, Mode, add_opts(Options, Options, Opts)); +do_add(#reader{access=read},_,_,_,_) -> + {error, eacces}; +do_add(Reader,_,_,_,_) -> + {error, {badarg, Reader}}. + +add_opts([dereference|T], AllOptions, Opts) -> + RF = fun(F) -> apply_file_info_opts(AllOptions, file:read_file_info(F, [{time, posix}])) end, + add_opts(T, AllOptions, Opts#add_opts{read_info=RF}); +add_opts([verbose|T], AllOptions, Opts) -> + add_opts(T, AllOptions, Opts#add_opts{verbose=true}); +add_opts([{chunks,N}|T], AllOptions, Opts) -> + add_opts(T, AllOptions, Opts#add_opts{chunk_size=N}); +add_opts([{atime,Value}|T], AllOptions, Opts) -> + add_opts(T, AllOptions, Opts#add_opts{atime=Value}); +add_opts([{mtime,Value}|T], AllOptions, Opts) -> + add_opts(T, AllOptions, Opts#add_opts{mtime=Value}); +add_opts([{ctime,Value}|T], AllOptions, Opts) -> + add_opts(T, AllOptions, Opts#add_opts{ctime=Value}); +add_opts([{uid,Value}|T], AllOptions, Opts) -> + add_opts(T, AllOptions, Opts#add_opts{uid=Value}); +add_opts([{gid,Value}|T], AllOptions, Opts) -> + add_opts(T, AllOptions, Opts#add_opts{gid=Value}); +add_opts([_|T], AllOptions, Opts) -> + add_opts(T, AllOptions, Opts); +add_opts([], _AllOptions, Opts) -> + Opts. + +apply_file_info_opts(Opts, {ok, FileInfo}) -> + {ok, do_apply_file_info_opts(Opts, FileInfo)}; +apply_file_info_opts(_Opts, Other) -> + Other. + +do_apply_file_info_opts([{atime,Value}|T], FileInfo) -> + do_apply_file_info_opts(T, FileInfo#file_info{atime=Value}); +do_apply_file_info_opts([{mtime,Value}|T], FileInfo) -> + do_apply_file_info_opts(T, FileInfo#file_info{mtime=Value}); +do_apply_file_info_opts([{ctime,Value}|T], FileInfo) -> + do_apply_file_info_opts(T, FileInfo#file_info{ctime=Value}); +do_apply_file_info_opts([{uid,Value}|T], FileInfo) -> + do_apply_file_info_opts(T, FileInfo#file_info{uid=Value}); +do_apply_file_info_opts([{gid,Value}|T], FileInfo) -> + do_apply_file_info_opts(T, FileInfo#file_info{gid=Value}); +do_apply_file_info_opts([_|T], FileInfo) -> + do_apply_file_info_opts(T, FileInfo); +do_apply_file_info_opts([], FileInfo) -> + FileInfo. + +add1(#reader{}=Reader, Name, NameInArchive, undefined, #add_opts{read_info=ReadInfo}=Opts) + when is_list(Name) -> + Res = case ReadInfo(Name) of + {error, Reason0} -> + {error, {Name, Reason0}}; + {ok, #file_info{type=symlink}=Fi} -> + add_verbose(Opts, "a ~ts~n", [NameInArchive]), + {ok, Linkname} = file:read_link(Name), + Header = fileinfo_to_header(NameInArchive, Fi, Linkname), + add_header(Reader, Header, Opts); + {ok, #file_info{type=regular}=Fi} -> + add_verbose(Opts, "a ~ts~n", [NameInArchive]), + Header = fileinfo_to_header(NameInArchive, Fi, false), + {ok, Reader2} = add_header(Reader, Header, Opts), + FileSize = Header#tar_header.size, + {ok, FileSize, Reader3} = do_copy(Reader2, Name, Opts), + Padding = skip_padding(FileSize), + Pad = <<0:Padding/unit:8>>, + do_write(Reader3, Pad); + {ok, #file_info{type=directory}=Fi} -> + add_directory(Reader, Name, NameInArchive, Fi, Opts); + {ok, #file_info{}=Fi} -> + add_verbose(Opts, "a ~ts~n", [NameInArchive]), + Header = fileinfo_to_header(NameInArchive, Fi, false), + add_header(Reader, Header, Opts) + end, + case Res of + ok -> ok; + {ok, _Reader} -> ok; + {error, _Reason} = Err -> Err + end; +add1(Reader, Bin, NameInArchive, Mode, Opts) when is_binary(Bin) -> + add_verbose(Opts, "a ~ts~n", [NameInArchive]), + Now = 0, + Header = #tar_header{ + name = NameInArchive, + size = byte_size(Bin), + typeflag = ?TYPE_REGULAR, + atime = add_opts_time(Opts#add_opts.atime, Now), + mtime = add_opts_time(Opts#add_opts.mtime, Now), + ctime = add_opts_time(Opts#add_opts.ctime, Now), + uid = Opts#add_opts.uid, + gid = Opts#add_opts.gid, + mode = default_mode(Mode, 8#100644)}, + {ok, Reader2} = add_header(Reader, Header, Opts), + Padding = skip_padding(byte_size(Bin)), + Data = [Bin, <<0:Padding/unit:8>>], + case do_write(Reader2, Data) of + {ok, _Reader3} -> ok; + {error, Reason} -> {error, {NameInArchive, Reason}} + end. + +add_opts_time(undefined, _Now) -> 0; +add_opts_time(Time, _Now) -> Time. + +default_mode(undefined, Mode) -> Mode; +default_mode(Mode, _) -> Mode. + +add_directory(Reader, DirName, NameInArchive, Info, Opts) -> + case file:list_dir(DirName) of + {ok, []} -> + add_verbose(Opts, "a ~ts~n", [NameInArchive]), + Header = fileinfo_to_header(NameInArchive, Info, false), + add_header(Reader, Header, Opts); + {ok, Files} -> + add_verbose(Opts, "a ~ts~n", [NameInArchive]), + try add_files(Reader, Files, DirName, NameInArchive, Opts) of + ok -> ok; + {error, _} = Err -> Err + catch + throw:{error, {_Name, _Reason}} = Err -> Err; + throw:{error, Reason} -> {error, {DirName, Reason}} + end; + {error, Reason} -> + {error, {DirName, Reason}} + end. + +add_files(_Reader, [], _Dir, _DirInArchive, _Opts) -> + ok; +add_files(Reader, [Name|Rest], Dir, DirInArchive, #add_opts{read_info=Info}=Opts) -> + FullName = filename:join(Dir, Name), + NameInArchive = filename:join(DirInArchive, Name), + Res = case Info(FullName) of + {error, Reason} -> + {error, {FullName, Reason}}; + {ok, #file_info{type=directory}=Fi} -> + add_directory(Reader, FullName, NameInArchive, Fi, Opts); + {ok, #file_info{type=symlink}=Fi} -> + add_verbose(Opts, "a ~ts~n", [NameInArchive]), + {ok, Linkname} = file:read_link(FullName), + Header = fileinfo_to_header(NameInArchive, Fi, Linkname), + add_header(Reader, Header, Opts); + {ok, #file_info{type=regular}=Fi} -> + add_verbose(Opts, "a ~ts~n", [NameInArchive]), + Header = fileinfo_to_header(NameInArchive, Fi, false), + {ok, Reader2} = add_header(Reader, Header, Opts), + FileSize = Header#tar_header.size, + {ok, FileSize, Reader3} = do_copy(Reader2, FullName, Opts), + Padding = skip_padding(FileSize), + Pad = <<0:Padding/unit:8>>, + do_write(Reader3, Pad); + {ok, #file_info{}=Fi} -> + add_verbose(Opts, "a ~ts~n", [NameInArchive]), + Header = fileinfo_to_header(NameInArchive, Fi, false), + add_header(Reader, Header, Opts) + end, + case Res of + ok -> add_files(Reader, Rest, Dir, DirInArchive, Opts); + {ok, ReaderNext} -> add_files(ReaderNext, Rest, Dir, DirInArchive, Opts); + {error, _} = Err -> Err + end. + +format_string(String, Size) when length(String) > Size -> + throw({error, {write_string, field_too_long}}); +format_string(String, Size) -> + Ascii = to_ascii(String), + if byte_size(Ascii) < Size -> + [Ascii, 0]; + true -> + Ascii + end. + +format_octal(Octal) -> + iolist_to_binary(io_lib:fwrite("~.8B", [Octal])). + +add_header(#reader{}=Reader, #tar_header{}=Header, Opts) -> + {ok, Iodata} = build_header(Header, Opts), + do_write(Reader, Iodata). + +write_to_block(Block, IoData, Start) when is_list(IoData) -> + write_to_block(Block, iolist_to_binary(IoData), Start); +write_to_block(Block, Bin, Start) when is_binary(Bin) -> + Size = byte_size(Bin), + <> = Block, + <>. + +build_header(#tar_header{}=Header, Opts) -> + #tar_header{ + name=Name, + mode=Mode, + uid=Uid, + gid=Gid, + size=Size, + typeflag=Type, + linkname=Linkname, + uname=Uname, + gname=Gname, + devmajor=Devmaj, + devminor=Devmin + } = Header, + Mtime = Header#tar_header.mtime, + + Block0 = ?ZERO_BLOCK, + {Block1, Pax0} = write_string(Block0, ?V7_NAME, ?V7_NAME_LEN, Name, ?PAX_PATH, #{}), + Block2 = write_octal(Block1, ?V7_MODE, ?V7_MODE_LEN, Mode), + {Block3, Pax1} = write_numeric(Block2, ?V7_UID, ?V7_UID_LEN, Uid, ?PAX_UID, Pax0), + {Block4, Pax2} = write_numeric(Block3, ?V7_GID, ?V7_GID_LEN, Gid, ?PAX_GID, Pax1), + {Block5, Pax3} = write_numeric(Block4, ?V7_SIZE, ?V7_SIZE_LEN, Size, ?PAX_SIZE, Pax2), + {Block6, Pax4} = write_numeric(Block5, ?V7_MTIME, ?V7_MTIME_LEN, Mtime, ?PAX_NONE, Pax3), + {Block7, Pax5} = write_string(Block6, ?V7_TYPE, ?V7_TYPE_LEN, <>, ?PAX_NONE, Pax4), + {Block8, Pax6} = write_string(Block7, ?V7_LINKNAME, ?V7_LINKNAME_LEN, + Linkname, ?PAX_LINKPATH, Pax5), + {Block9, Pax7} = write_string(Block8, ?USTAR_UNAME, ?USTAR_UNAME_LEN, + Uname, ?PAX_UNAME, Pax6), + {Block10, Pax8} = write_string(Block9, ?USTAR_GNAME, ?USTAR_GNAME_LEN, + Gname, ?PAX_GNAME, Pax7), + {Block11, Pax9} = write_numeric(Block10, ?USTAR_DEVMAJ, ?USTAR_DEVMAJ_LEN, + Devmaj, ?PAX_NONE, Pax8), + {Block12, Pax10} = write_numeric(Block11, ?USTAR_DEVMIN, ?USTAR_DEVMIN_LEN, + Devmin, ?PAX_NONE, Pax9), + {Block13, Pax11} = set_path(Block12, Pax10), + PaxEntry = case maps:size(Pax11) of + 0 -> []; + _ -> build_pax_entry(Header, Pax11, Opts) + end, + Block14 = set_format(Block13, ?FORMAT_USTAR), + Block15 = set_checksum(Block14), + {ok, [PaxEntry, Block15]}. + +set_path(Block0, Pax) -> + %% only use ustar header when name is too long + case maps:get(?PAX_PATH, Pax, nil) of + nil -> + {Block0, Pax}; + PaxPath -> + case split_ustar_path(PaxPath) of + {ok, UstarName, UstarPrefix} -> + {Block1, _} = write_string(Block0, ?V7_NAME, ?V7_NAME_LEN, + UstarName, ?PAX_NONE, #{}), + {Block2, _} = write_string(Block1, ?USTAR_PREFIX, ?USTAR_PREFIX_LEN, + UstarPrefix, ?PAX_NONE, #{}), + {Block2, maps:remove(?PAX_PATH, Pax)}; + false -> + {Block0, Pax} + end + end. + +set_format(Block0, Format) + when Format =:= ?FORMAT_USTAR; Format =:= ?FORMAT_PAX -> + Block1 = write_to_block(Block0, ?MAGIC_USTAR, ?USTAR_MAGIC), + write_to_block(Block1, ?VERSION_USTAR, ?USTAR_VERSION); +set_format(_Block, Format) -> + throw({error, {invalid_format, Format}}). + +set_checksum(Block) -> + Checksum = compute_checksum(Block), + write_octal(Block, ?V7_CHKSUM, ?V7_CHKSUM_LEN, Checksum). + +build_pax_entry(Header, PaxAttrs, Opts) -> + Path = Header#tar_header.name, + Filename = filename:basename(Path), + Dir = filename:dirname(Path), + Path2 = filename:join([Dir, "PaxHeaders.0", Filename]), + AsciiPath = to_ascii(Path2), + Path3 = if byte_size(AsciiPath) > ?V7_NAME_LEN -> + binary_part(AsciiPath, 0, ?V7_NAME_LEN - 1); + true -> + AsciiPath + end, + Keys = maps:keys(PaxAttrs), + SortedKeys = lists:sort(Keys), + PaxFile = build_pax_file(SortedKeys, PaxAttrs), + Size = byte_size(PaxFile), + Padding = (?BLOCK_SIZE - + (byte_size(PaxFile) rem ?BLOCK_SIZE)) rem ?BLOCK_SIZE, + Pad = <<0:Padding/unit:8>>, + PaxHeader = #tar_header{ + name=unicode:characters_to_list(Path3), + size=Size, + mtime=Header#tar_header.mtime, + atime=Header#tar_header.atime, + ctime=Header#tar_header.ctime, + typeflag=?TYPE_X_HEADER + }, + {ok, PaxHeaderData} = build_header(PaxHeader, Opts), + [PaxHeaderData, PaxFile, Pad]. + +build_pax_file(Keys, PaxAttrs) -> + build_pax_file(Keys, PaxAttrs, []). +build_pax_file([], _, Acc) -> + unicode:characters_to_binary(Acc); +build_pax_file([K|Rest], Attrs, Acc) -> + V = maps:get(K, Attrs), + Size = sizeof(K) + sizeof(V) + 3, + Size2 = sizeof(Size) + Size, + Key = to_string(K), + Value = to_string(V), + Record = unicode:characters_to_binary(io_lib:format("~B ~ts=~ts\n", [Size2, Key, Value])), + if byte_size(Record) =/= Size2 -> + Size3 = byte_size(Record), + Record2 = io_lib:format("~B ~ts=~ts\n", [Size3, Key, Value]), + build_pax_file(Rest, Attrs, [Acc, Record2]); + true -> + build_pax_file(Rest, Attrs, [Acc, Record]) + end. + +sizeof(Bin) when is_binary(Bin) -> + byte_size(Bin); +sizeof(List) when is_list(List) -> + length(List); +sizeof(N) when is_integer(N) -> + byte_size(integer_to_binary(N)); +sizeof(N) when is_float(N) -> + byte_size(float_to_binary(N)). + +to_string(Bin) when is_binary(Bin) -> + unicode:characters_to_list(Bin); +to_string(List) when is_list(List) -> + List; +to_string(N) when is_integer(N) -> + integer_to_list(N); +to_string(N) when is_float(N) -> + float_to_list(N). + +split_ustar_path(Path) -> + Len = length(Path), + NotAscii = not is_ascii(Path), + if Len =< ?V7_NAME_LEN; NotAscii -> + false; + true -> + PathBin = binary:list_to_bin(Path), + case binary:split(PathBin, [<<$/>>], [global, trim_all]) of + [Part] when byte_size(Part) >= ?V7_NAME_LEN -> + false; + Parts -> + case lists:last(Parts) of + Name when byte_size(Name) >= ?V7_NAME_LEN -> + false; + Name -> + Parts2 = lists:sublist(Parts, length(Parts) - 1), + join_split_ustar_path(Parts2, {ok, Name, nil}) + end + end + end. + +join_split_ustar_path([], Acc) -> + Acc; +join_split_ustar_path([Part|_], {ok, _, nil}) + when byte_size(Part) > ?USTAR_PREFIX_LEN -> + false; +join_split_ustar_path([Part|_], {ok, _Name, Acc}) + when (byte_size(Part)+byte_size(Acc)) > ?USTAR_PREFIX_LEN -> + false; +join_split_ustar_path([Part|Rest], {ok, Name, nil}) -> + join_split_ustar_path(Rest, {ok, Name, Part}); +join_split_ustar_path([Part|Rest], {ok, Name, Acc}) -> + join_split_ustar_path(Rest, {ok, Name, <>}). + +write_octal(Block, Pos, Size, X) -> + Octal = zero_pad(format_octal(X), Size-1), + if byte_size(Octal) < Size -> + write_to_block(Block, Octal, Pos); + true -> + throw({error, {write_failed, octal_field_too_long}}) + end. + +write_string(Block, Pos, Size, Str, PaxAttr, Pax0) -> + NotAscii = not is_ascii(Str), + if PaxAttr =/= ?PAX_NONE andalso (length(Str) > Size orelse NotAscii) -> + Pax1 = maps:put(PaxAttr, Str, Pax0), + {Block, Pax1}; + true -> + Formatted = format_string(Str, Size), + {write_to_block(Block, Formatted, Pos), Pax0} + end. +write_numeric(Block, Pos, Size, X, PaxAttr, Pax0) -> + %% attempt octal + Octal = zero_pad(format_octal(X), Size-1), + if byte_size(Octal) < Size -> + {write_to_block(Block, [Octal, 0], Pos), Pax0}; + PaxAttr =/= ?PAX_NONE -> + Pax1 = maps:put(PaxAttr, X, Pax0), + {Block, Pax1}; + true -> + throw({error, {write_failed, numeric_field_too_long}}) + end. + +zero_pad(Str, Size) when byte_size(Str) >= Size -> + Str; +zero_pad(Str, Size) -> + Padding = Size - byte_size(Str), + Pad = binary:copy(<<$0>>, Padding), + <>. + + +%%%================================================================ +%% Functions for creating or modifying tar archives + +read_block(Reader) -> + case do_read(Reader, ?BLOCK_SIZE) of + eof -> + throw({error, eof}); + %% Two zero blocks mark the end of the archive + {ok, ?ZERO_BLOCK, Reader1} -> + case do_read(Reader1, ?BLOCK_SIZE) of + eof -> + % This is technically a malformed end-of-archive marker, + % as two ZERO_BLOCKs are expected as the marker, + % but if we've already made it this far, we should just ignore it + eof; + {ok, ?ZERO_BLOCK, _Reader2} -> + eof; + {ok, _Block, _Reader2} -> + throw({error, invalid_end_of_archive}); + {error,_} = Err -> + throw(Err) + end; + {ok, Block, Reader1} when is_binary(Block) -> + {ok, Block, Reader1}; + {error, _} = Err -> + throw(Err) + end. + +get_header(#reader{}=Reader) -> + case read_block(Reader) of + eof -> + eof; + {ok, Block, Reader1} -> + convert_header(Block, Reader1) + end. + +%% Converts the tar header to a record. +to_v7(Bin) when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE -> + #header_v7{ + name=binary_part(Bin, ?V7_NAME, ?V7_NAME_LEN), + mode=binary_part(Bin, ?V7_MODE, ?V7_MODE_LEN), + uid=binary_part(Bin, ?V7_UID, ?V7_UID_LEN), + gid=binary_part(Bin, ?V7_GID, ?V7_GID_LEN), + size=binary_part(Bin, ?V7_SIZE, ?V7_SIZE_LEN), + mtime=binary_part(Bin, ?V7_MTIME, ?V7_MTIME_LEN), + checksum=binary_part(Bin, ?V7_CHKSUM, ?V7_CHKSUM_LEN), + typeflag=binary:at(Bin, ?V7_TYPE), + linkname=binary_part(Bin, ?V7_LINKNAME, ?V7_LINKNAME_LEN) + }; +to_v7(_) -> + {error, header_block_too_small}. + +to_gnu(#header_v7{}=V7, Bin) + when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE -> + #header_gnu{ + header_v7=V7, + magic=binary_part(Bin, ?GNU_MAGIC, ?GNU_MAGIC_LEN), + version=binary_part(Bin, ?GNU_VERSION, ?GNU_VERSION_LEN), + uname=binary_part(Bin, 265, 32), + gname=binary_part(Bin, 297, 32), + devmajor=binary_part(Bin, 329, 8), + devminor=binary_part(Bin, 337, 8), + atime=binary_part(Bin, 345, 12), + ctime=binary_part(Bin, 357, 12), + sparse=to_sparse_array(binary_part(Bin, 386, 24*4+1)), + real_size=binary_part(Bin, 483, 12) + }. + +to_star(#header_v7{}=V7, Bin) + when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE -> + #header_star{ + header_v7=V7, + magic=binary_part(Bin, ?USTAR_MAGIC, ?USTAR_MAGIC_LEN), + version=binary_part(Bin, ?USTAR_VERSION, ?USTAR_VERSION_LEN), + uname=binary_part(Bin, ?USTAR_UNAME, ?USTAR_UNAME_LEN), + gname=binary_part(Bin, ?USTAR_GNAME, ?USTAR_GNAME_LEN), + devmajor=binary_part(Bin, ?USTAR_DEVMAJ, ?USTAR_DEVMAJ_LEN), + devminor=binary_part(Bin, ?USTAR_DEVMIN, ?USTAR_DEVMIN_LEN), + prefix=binary_part(Bin, 345, 131), + atime=binary_part(Bin, 476, 12), + ctime=binary_part(Bin, 488, 12), + trailer=binary_part(Bin, ?STAR_TRAILER, ?STAR_TRAILER_LEN) + }. + +to_ustar(#header_v7{}=V7, Bin) + when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE -> + #header_ustar{ + header_v7=V7, + magic=binary_part(Bin, ?USTAR_MAGIC, ?USTAR_MAGIC_LEN), + version=binary_part(Bin, ?USTAR_VERSION, ?USTAR_VERSION_LEN), + uname=binary_part(Bin, ?USTAR_UNAME, ?USTAR_UNAME_LEN), + gname=binary_part(Bin, ?USTAR_GNAME, ?USTAR_GNAME_LEN), + devmajor=binary_part(Bin, ?USTAR_DEVMAJ, ?USTAR_DEVMAJ_LEN), + devminor=binary_part(Bin, ?USTAR_DEVMIN, ?USTAR_DEVMIN_LEN), + prefix=binary_part(Bin, 345, 155) + }. + +to_sparse_array(Bin) when is_binary(Bin) -> + MaxEntries = byte_size(Bin) div 24, + IsExtended = 1 =:= binary:at(Bin, 24*MaxEntries), + Entries = parse_sparse_entries(Bin, MaxEntries-1, []), + #sparse_array{ + entries=Entries, + max_entries=MaxEntries, + is_extended=IsExtended + }. + +parse_sparse_entries(<<>>, _, Acc) -> + Acc; +parse_sparse_entries(_, -1, Acc) -> + Acc; +parse_sparse_entries(Bin, N, Acc) -> + case to_sparse_entry(binary_part(Bin, N*24, 24)) of + nil -> + parse_sparse_entries(Bin, N-1, Acc); + Entry = #sparse_entry{} -> + parse_sparse_entries(Bin, N-1, [Entry|Acc]) + end. + +-define(EMPTY_ENTRY, <<0,0,0,0,0,0,0,0,0,0,0,0>>). +to_sparse_entry(Bin) when is_binary(Bin), byte_size(Bin) =:= 24 -> + OffsetBin = binary_part(Bin, 0, 12), + NumBytesBin = binary_part(Bin, 12, 12), + case {OffsetBin, NumBytesBin} of + {?EMPTY_ENTRY, ?EMPTY_ENTRY} -> + nil; + _ -> + #sparse_entry{ + offset=parse_numeric(OffsetBin), + num_bytes=parse_numeric(NumBytesBin)} + end. + +-spec get_format(binary()) -> {ok, pos_integer(), header_v7()} + | ?FORMAT_UNKNOWN + | {error, term()}. +get_format(Bin) when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE -> + do_get_format(to_v7(Bin), Bin). + +do_get_format({error, _} = Err, _Bin) -> + Err; +do_get_format(#header_v7{}=V7, Bin) + when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE -> + Checksum = parse_octal(V7#header_v7.checksum), + Chk1 = compute_checksum(Bin), + Chk2 = compute_signed_checksum(Bin), + if Checksum =/= Chk1 andalso Checksum =/= Chk2 -> + ?FORMAT_UNKNOWN; + true -> + %% guess magic + Ustar = to_ustar(V7, Bin), + Star = to_star(V7, Bin), + Magic = Ustar#header_ustar.magic, + Version = Ustar#header_ustar.version, + Trailer = Star#header_star.trailer, + Format = if + Magic =:= ?MAGIC_USTAR, Trailer =:= ?TRAILER_STAR -> + ?FORMAT_STAR; + Magic =:= ?MAGIC_USTAR -> + ?FORMAT_USTAR; + Magic =:= ?MAGIC_GNU, Version =:= ?VERSION_GNU -> + ?FORMAT_GNU; + true -> + ?FORMAT_V7 + end, + {ok, Format, V7} + end. + +unpack_format(Format, #header_v7{}=V7, Bin, Reader) + when is_binary(Bin), byte_size(Bin) =:= ?BLOCK_SIZE -> + Mtime = parse_numeric(V7#header_v7.mtime), + Header0 = #tar_header{ + name=parse_string(V7#header_v7.name), + mode=parse_numeric(V7#header_v7.mode), + uid=parse_numeric(V7#header_v7.uid), + gid=parse_numeric(V7#header_v7.gid), + size=parse_numeric(V7#header_v7.size), + mtime=Mtime, + atime=Mtime, + ctime=Mtime, + typeflag=V7#header_v7.typeflag, + linkname=parse_string(V7#header_v7.linkname) + }, + Typeflag = Header0#tar_header.typeflag, + Header1 = if Format > ?FORMAT_V7 -> + unpack_modern(Format, V7, Bin, Header0); + true -> + Name = Header0#tar_header.name, + Header0#tar_header{name=safe_join_path("", Name)} + end, + HeaderOnly = is_header_only_type(Typeflag), + Header2 = if HeaderOnly -> + Header1#tar_header{size=0}; + true -> + Header1 + end, + if Typeflag =:= ?TYPE_GNU_SPARSE -> + Gnu = to_gnu(V7, Bin), + RealSize = parse_numeric(Gnu#header_gnu.real_size), + {Sparsemap, Reader2} = parse_sparse_map(Gnu, Reader), + Header3 = Header2#tar_header{size=RealSize}, + {Header3, new_sparse_file_reader(Reader2, Sparsemap, RealSize)}; + true -> + FileReader = #reg_file_reader{ + handle=Reader, + num_bytes=Header2#tar_header.size, + size=Header2#tar_header.size, + pos = 0 + }, + {Header2, FileReader} + end. + +unpack_modern(Format, #header_v7{}=V7, Bin, #tar_header{}=Header0) + when is_binary(Bin) -> + Typeflag = Header0#tar_header.typeflag, + Ustar = to_ustar(V7, Bin), + H0 = Header0#tar_header{ + uname=parse_string(Ustar#header_ustar.uname), + gname=parse_string(Ustar#header_ustar.gname)}, + H1 = if Typeflag =:= ?TYPE_CHAR + orelse Typeflag =:= ?TYPE_BLOCK -> + Ma = parse_numeric(Ustar#header_ustar.devmajor), + Mi = parse_numeric(Ustar#header_ustar.devminor), + H0#tar_header{ + devmajor=Ma, + devminor=Mi + }; + true -> + H0 + end, + {Prefix, H2} = case Format of + ?FORMAT_USTAR -> + {parse_string(Ustar#header_ustar.prefix), H1}; + ?FORMAT_STAR -> + Star = to_star(V7, Bin), + Prefix0 = parse_string(Star#header_star.prefix), + Atime0 = Star#header_star.atime, + Atime = parse_numeric(Atime0), + Ctime0 = Star#header_star.ctime, + Ctime = parse_numeric(Ctime0), + {Prefix0, H1#tar_header{ + atime=Atime, + ctime=Ctime + }}; + _ -> + {"", H1} + end, + Name = H2#tar_header.name, + H2#tar_header{name=safe_join_path(Prefix, Name)}. + + +safe_join_path([], Name) -> + filename:join([Name]); +safe_join_path(Prefix, []) -> + filename:join([Prefix]); +safe_join_path(Prefix, Name) -> + filename:join(Prefix, Name). + +new_sparse_file_reader(Reader, Sparsemap, RealSize) -> + true = validate_sparse_entries(Sparsemap, RealSize), + #sparse_file_reader{ + handle = Reader, + num_bytes = RealSize, + pos = 0, + size = RealSize, + sparse_map = Sparsemap}. + +validate_sparse_entries(Entries, RealSize) -> + validate_sparse_entries(Entries, RealSize, 0, 0). +validate_sparse_entries([], _RealSize, _I, _LastOffset) -> + true; +validate_sparse_entries([#sparse_entry{}=Entry|Rest], RealSize, I, LastOffset) -> + Offset = Entry#sparse_entry.offset, + NumBytes = Entry#sparse_entry.num_bytes, + if + Offset > ?MAX_INT64-NumBytes -> + throw({error, {invalid_sparse_map_entry, offset_too_large}}); + Offset+NumBytes > RealSize -> + throw({error, {invalid_sparse_map_entry, offset_too_large}}); + I > 0 andalso LastOffset > Offset -> + throw({error, {invalid_sparse_map_entry, overlapping_offsets}}); + true -> + ok + end, + validate_sparse_entries(Rest, RealSize, I+1, Offset+NumBytes). + + +-spec parse_sparse_map(header_gnu(), reader_type()) -> + {[sparse_entry()], reader_type()}. +parse_sparse_map(#header_gnu{sparse=Sparse}, Reader) + when Sparse#sparse_array.is_extended -> + parse_sparse_map(Sparse, Reader, []); +parse_sparse_map(#header_gnu{sparse=Sparse}, Reader) -> + {Sparse#sparse_array.entries, Reader}. +parse_sparse_map(#sparse_array{is_extended=true,entries=Entries}, Reader, Acc) -> + case read_block(Reader) of + eof -> + throw({error, eof}); + {ok, Block, Reader2} -> + Sparse2 = to_sparse_array(Block), + parse_sparse_map(Sparse2, Reader2, Entries++Acc) + end; +parse_sparse_map(#sparse_array{entries=Entries}, Reader, Acc) -> + Sorted = lists:sort(fun (#sparse_entry{offset=A},#sparse_entry{offset=B}) -> + A =< B + end, Entries++Acc), + {Sorted, Reader}. + +%% Defined by taking the sum of the unsigned byte values of the +%% entire header record, treating the checksum bytes to as ASCII spaces +compute_checksum(<>) -> + C0 = checksum(H1) + (byte_size(H2) * $\s), + C1 = checksum(Rest), + C0 + C1. + +compute_signed_checksum(<>) -> + C0 = signed_checksum(H1) + (byte_size(H2) * $\s), + C1 = signed_checksum(Rest), + C0 + C1. + +%% Returns the checksum of a binary. +checksum(Bin) -> checksum(Bin, 0). +checksum(<>, Sum) -> + checksum(Rest, Sum+A); +checksum(<<>>, Sum) -> Sum. + +signed_checksum(Bin) -> signed_checksum(Bin, 0). +signed_checksum(<>, Sum) -> + signed_checksum(Rest, Sum+A); +signed_checksum(<<>>, Sum) -> Sum. + +-spec parse_numeric(binary()) -> non_neg_integer(). +parse_numeric(<<>>) -> + 0; +parse_numeric(<> = Bin) -> + %% check for base-256 format first + %% if the bit is set, then all following bits constitute a two's + %% complement encoded number in big-endian byte order + if + First band 16#80 =/= 0 -> + %% Handling negative numbers relies on the following identity: + %% -a-1 == ^a + %% If the number is negative, we use an inversion mask to invert + %% the data bytes and treat the value as an unsigned number + Inv = if First band 16#40 =/= 0 -> 16#00; true -> 16#FF end, + Bytes = binary:bin_to_list(Bin), + Reducer = fun (C, {I, X}) -> + C1 = C bxor Inv, + C2 = if I =:= 0 -> C1 band 16#7F; true -> C1 end, + if (X bsr 56) > 0 -> + throw({error,integer_overflow}); + true -> + {I+1, (X bsl 8) bor C2} + end + end, + {_, N} = lists:foldl(Reducer, {0,0}, Bytes), + if (N bsr 63) > 0 -> + throw({error, integer_overflow}); + true -> + if Inv =:= 16#FF -> + -1 bxor N; + true -> + N + end + end; + true -> + %% normal case is an octal number + parse_octal(Bin) + end. + +parse_octal(Bin) when is_binary(Bin) -> + %% skip leading/trailing zero bytes and spaces + do_parse_octal(Bin, <<>>). +do_parse_octal(<<>>, <<>>) -> + 0; +do_parse_octal(<<>>, Acc) -> + case io_lib:fread("~8u", binary:bin_to_list(Acc)) of + {error, _} -> throw({error, invalid_tar_checksum}); + {ok, [Octal], []} -> Octal; + {ok, _, _} -> throw({error, invalid_tar_checksum}) + end; +do_parse_octal(<<$\s,Rest/binary>>, Acc) -> + do_parse_octal(Rest, Acc); +do_parse_octal(<<0, Rest/binary>>, Acc) -> + do_parse_octal(Rest, Acc); +do_parse_octal(<>, Acc) -> + do_parse_octal(Rest, <>). + +parse_string(Bin) when is_binary(Bin) -> + do_parse_string(Bin, <<>>). +do_parse_string(<<>>, Acc) -> + case unicode:characters_to_list(Acc) of + Str when is_list(Str) -> + Str; + {incomplete, _Str, _Rest} -> + binary:bin_to_list(Acc); + {error, _Str, _Rest} -> + throw({error, {bad_header, invalid_string}}) + end; +do_parse_string(<<0, _/binary>>, Acc) -> + do_parse_string(<<>>, Acc); +do_parse_string(<>, Acc) -> + do_parse_string(Rest, <>). + +convert_header(Bin, #reader{pos=Pos}=Reader) + when byte_size(Bin) =:= ?BLOCK_SIZE, (Pos rem ?BLOCK_SIZE) =:= 0 -> + case get_format(Bin) of + ?FORMAT_UNKNOWN -> + throw({error, bad_header}); + {ok, Format, V7} -> + unpack_format(Format, V7, Bin, Reader); + {error, Reason} -> + throw({error, {bad_header, Reason}}) + end; +convert_header(Bin, #reader{pos=Pos}) when byte_size(Bin) =:= ?BLOCK_SIZE -> + throw({error, misaligned_read, Pos}); +convert_header(Bin, _Reader) when byte_size(Bin) =:= 0 -> + eof; +convert_header(_Bin, _Reader) -> + throw({error, eof}). + +%% Creates a partially-populated header record based +%% on the provided file_info record. If the file is +%% a symlink, then `link` is used as the link target. +%% If the file is a directory, a slash is appended to the name. +fileinfo_to_header(Name, #file_info{}=Fi, Link) when is_list(Name) -> + BaseHeader = #tar_header{name=Name, + mtime=0, + atime=0, + ctime=0, + mode=Fi#file_info.mode, + typeflag=?TYPE_REGULAR}, + do_fileinfo_to_header(BaseHeader, Fi, Link). + +do_fileinfo_to_header(Header, #file_info{size=Size,type=regular}, _Link) -> + Header#tar_header{size=Size,typeflag=?TYPE_REGULAR}; +do_fileinfo_to_header(#tar_header{name=Name}=Header, + #file_info{type=directory}, _Link) -> + Header#tar_header{name=Name++"/",typeflag=?TYPE_DIR}; +do_fileinfo_to_header(Header, #file_info{type=symlink}, Link) -> + Header#tar_header{typeflag=?TYPE_SYMLINK,linkname=Link}; +do_fileinfo_to_header(Header, #file_info{type=device,mode=Mode}=Fi, _Link) + when (Mode band ?S_IFMT) =:= ?S_IFCHR -> + Header#tar_header{typeflag=?TYPE_CHAR, + devmajor=Fi#file_info.major_device, + devminor=Fi#file_info.minor_device}; +do_fileinfo_to_header(Header, #file_info{type=device,mode=Mode}=Fi, _Link) + when (Mode band ?S_IFMT) =:= ?S_IFBLK -> + Header#tar_header{typeflag=?TYPE_BLOCK, + devmajor=Fi#file_info.major_device, + devminor=Fi#file_info.minor_device}; +do_fileinfo_to_header(Header, #file_info{type=other,mode=Mode}, _Link) + when (Mode band ?S_IFMT) =:= ?S_FIFO -> + Header#tar_header{typeflag=?TYPE_FIFO}; +do_fileinfo_to_header(Header, Fi, _Link) -> + {error, {invalid_file_type, Header#tar_header.name, Fi}}. + +is_ascii(Str) when is_list(Str) -> + not lists:any(fun (Char) -> Char >= 16#80 end, Str); +is_ascii(Bin) when is_binary(Bin) -> + is_ascii1(Bin). + +is_ascii1(<<>>) -> + true; +is_ascii1(<>) when C >= 16#80 -> + false; +is_ascii1(<<_, Rest/binary>>) -> + is_ascii1(Rest). + +to_ascii(Str) when is_list(Str) -> + case is_ascii(Str) of + true -> + unicode:characters_to_binary(Str); + false -> + Chars = lists:filter(fun (Char) -> Char < 16#80 end, Str), + unicode:characters_to_binary(Chars) + end; +to_ascii(Bin) when is_binary(Bin) -> + to_ascii(Bin, <<>>). +to_ascii(<<>>, Acc) -> + Acc; +to_ascii(<>, Acc) when C < 16#80 -> + to_ascii(Rest, <>); +to_ascii(<<_, Rest/binary>>, Acc) -> + to_ascii(Rest, Acc). + +is_header_only_type(?TYPE_SYMLINK) -> true; +is_header_only_type(?TYPE_LINK) -> true; +is_header_only_type(?TYPE_DIR) -> true; +is_header_only_type(_) -> false. + +foldl_read(#reader{access=read}=Reader, Fun, Accu, #read_opts{}=Opts) + when is_function(Fun,4) -> + case foldl_read0(Reader, Fun, Accu, Opts) of + {ok, Result, _Reader2} -> + Result; + {error, _} = Err -> + Err + end; +foldl_read(#reader{access=Access}, _Fun, _Accu, _Opts) -> + {error, {read_mode_expected, Access}}; +foldl_read(TarName, Fun, Accu, #read_opts{}=Opts) + when is_function(Fun,4) -> + try open(TarName, [read|Opts#read_opts.open_mode]) of + {ok, #reader{access=read}=Reader} -> + try + foldl_read(Reader, Fun, Accu, Opts) + after + _ = close(Reader) + end; + {error, _} = Err -> + Err + catch + throw:Err -> + Err + end. + +foldl_read0(Reader, Fun, Accu, Opts) -> + try foldl_read1(Fun, Accu, Reader, Opts, #{}) of + {ok,_,_} = Ok -> + Ok + catch + throw:{error, {Reason, Format, Args}} -> + read_verbose(Opts, Format, Args), + {error, Reason}; + throw:Err -> + Err + end. + +foldl_read1(Fun, Accu0, Reader0, Opts, ExtraHeaders) -> + {ok, Reader1} = skip_unread(Reader0), + case get_header(Reader1) of + eof -> + Fun(eof, Reader1, Opts, Accu0); + {Header, Reader2} -> + case Header#tar_header.typeflag of + ?TYPE_X_HEADER -> + {ExtraHeaders2, Reader3} = parse_pax(Reader2), + ExtraHeaders3 = maps:merge(ExtraHeaders, ExtraHeaders2), + foldl_read1(Fun, Accu0, Reader3, Opts, ExtraHeaders3); + ?TYPE_GNU_LONGNAME -> + {RealName, Reader3} = get_real_name(Reader2), + ExtraHeaders2 = maps:put(?PAX_PATH, + parse_string(RealName), ExtraHeaders), + foldl_read1(Fun, Accu0, Reader3, Opts, ExtraHeaders2); + ?TYPE_GNU_LONGLINK -> + {RealName, Reader3} = get_real_name(Reader2), + ExtraHeaders2 = maps:put(?PAX_LINKPATH, + parse_string(RealName), ExtraHeaders), + foldl_read1(Fun, Accu0, Reader3, Opts, ExtraHeaders2); + _ -> + Header1 = merge_pax(Header, ExtraHeaders), + {ok, NewAccu, Reader3} = Fun(Header1, Reader2, Opts, Accu0), + foldl_read1(Fun, NewAccu, Reader3, Opts, #{}) + end + end. + +%% Applies all known PAX attributes to the current tar header +-spec merge_pax(tar_header(), #{binary() => binary()}) -> tar_header(). +merge_pax(Header, ExtraHeaders) when is_map(ExtraHeaders) -> + do_merge_pax(Header, maps:to_list(ExtraHeaders)). + +do_merge_pax(Header, []) -> + Header; +do_merge_pax(Header, [{?PAX_PATH, Path}|Rest]) -> + do_merge_pax(Header#tar_header{name=unicode:characters_to_list(Path)}, Rest); +do_merge_pax(Header, [{?PAX_LINKPATH, LinkPath}|Rest]) -> + do_merge_pax(Header#tar_header{linkname=unicode:characters_to_list(LinkPath)}, Rest); +do_merge_pax(Header, [{?PAX_GNAME, Gname}|Rest]) -> + do_merge_pax(Header#tar_header{gname=unicode:characters_to_list(Gname)}, Rest); +do_merge_pax(Header, [{?PAX_UNAME, Uname}|Rest]) -> + do_merge_pax(Header#tar_header{uname=unicode:characters_to_list(Uname)}, Rest); +do_merge_pax(Header, [{?PAX_UID, Uid}|Rest]) -> + Uid2 = binary_to_integer(Uid), + do_merge_pax(Header#tar_header{uid=Uid2}, Rest); +do_merge_pax(Header, [{?PAX_GID, Gid}|Rest]) -> + Gid2 = binary_to_integer(Gid), + do_merge_pax(Header#tar_header{gid=Gid2}, Rest); +do_merge_pax(Header, [{?PAX_ATIME, Atime}|Rest]) -> + Atime2 = parse_pax_time(Atime), + do_merge_pax(Header#tar_header{atime=Atime2}, Rest); +do_merge_pax(Header, [{?PAX_MTIME, Mtime}|Rest]) -> + Mtime2 = parse_pax_time(Mtime), + do_merge_pax(Header#tar_header{mtime=Mtime2}, Rest); +do_merge_pax(Header, [{?PAX_CTIME, Ctime}|Rest]) -> + Ctime2 = parse_pax_time(Ctime), + do_merge_pax(Header#tar_header{ctime=Ctime2}, Rest); +do_merge_pax(Header, [{?PAX_SIZE, Size}|Rest]) -> + Size2 = binary_to_integer(Size), + do_merge_pax(Header#tar_header{size=Size2}, Rest); +do_merge_pax(Header, [{<>, _Value}|Rest]) -> + do_merge_pax(Header, Rest); +do_merge_pax(Header, [_Ignore|Rest]) -> + do_merge_pax(Header, Rest). + +%% Returns the time since UNIX epoch as a datetime +-spec parse_pax_time(binary()) -> tar_time(). +parse_pax_time(Bin) when is_binary(Bin) -> + TotalNano = case binary:split(Bin, [<<$.>>]) of + [SecondsStr, NanoStr0] -> + Seconds = binary_to_integer(SecondsStr), + if byte_size(NanoStr0) < ?MAX_NANO_INT_SIZE -> + %% right pad + PaddingN = ?MAX_NANO_INT_SIZE-byte_size(NanoStr0), + Padding = binary:copy(<<$0>>, PaddingN), + NanoStr1 = <>, + Nano = binary_to_integer(NanoStr1), + (Seconds*?BILLION)+Nano; + byte_size(NanoStr0) > ?MAX_NANO_INT_SIZE -> + %% right truncate + NanoStr1 = binary_part(NanoStr0, 0, ?MAX_NANO_INT_SIZE), + Nano = binary_to_integer(NanoStr1), + (Seconds*?BILLION)+Nano; + true -> + (Seconds*?BILLION)+binary_to_integer(NanoStr0) + end; + [SecondsStr] -> + binary_to_integer(SecondsStr)*?BILLION + end, + %% truncate to microseconds + Micro = TotalNano div 1000, + Mega = Micro div 1000000000000, + Secs = Micro div 1000000 - (Mega*1000000), + Secs. + +%% Given a regular file reader, reads the whole file and +%% parses all extended attributes it contains. +parse_pax(#reg_file_reader{handle=Handle,num_bytes=0}) -> + {#{}, Handle}; +parse_pax(#reg_file_reader{handle=Handle0,num_bytes=NumBytes}) -> + case do_read(Handle0, NumBytes) of + {ok, Bytes, Handle1} -> + do_parse_pax(Handle1, Bytes, #{}); + {error, _} = Err -> + throw(Err) + end. + +do_parse_pax(Reader, <<>>, Headers) -> + {Headers, Reader}; +do_parse_pax(Reader, Bin, Headers) -> + {Key, Value, Residual} = parse_pax_record(Bin), + NewHeaders = maps:put(Key, Value, Headers), + do_parse_pax(Reader, Residual, NewHeaders). + +%% Parse an extended attribute +parse_pax_record(Bin) when is_binary(Bin) -> + case binary:split(Bin, [<<$\n>>]) of + [Record, Residual] -> + case [X || X <- binary:split(Record, [<<$\s>>], [global]), X =/= <<>>] of + [_Len, Record1] -> + case [X || X <- binary:split(Record1, [<<$=>>], [global]), X =/= <<>>] of + [AttrName, AttrValue] -> + {AttrName, AttrValue, Residual}; + _Other -> + throw({error, malformed_pax_record}) + end; + _Other -> + throw({error, malformed_pax_record}) + end; + _Other -> + throw({error, malformed_pax_record}) + end. + +get_real_name(#reg_file_reader{handle=Handle,num_bytes=0}) -> + {"", Handle}; +get_real_name(#reg_file_reader{handle=Handle0,num_bytes=NumBytes}) -> + case do_read(Handle0, NumBytes) of + {ok, RealName, Handle1} -> + {RealName, Handle1}; + {error, _} = Err -> + throw(Err) + end; +get_real_name(#sparse_file_reader{num_bytes=NumBytes}=Reader0) -> + case do_read(Reader0, NumBytes) of + {ok, RealName, Reader1} -> + {RealName, Reader1}; + {error, _} = Err -> + throw(Err) + end. + +%% Skip the remaining bytes for the current file entry +skip_file(#reg_file_reader{handle=Handle0,pos=Pos,size=Size}=Reader) -> + Padding = skip_padding(Size), + AbsPos = Handle0#reader.pos + (Size-Pos) + Padding, + case do_position(Handle0, AbsPos) of + {ok, _, Handle1} -> + Reader#reg_file_reader{handle=Handle1,num_bytes=0,pos=Size}; + Err -> + throw(Err) + end; +skip_file(#sparse_file_reader{pos=Pos,size=Size}=Reader) -> + case do_read(Reader, Size-Pos) of + {ok, _, Reader2} -> + Reader2; + Err -> + throw(Err) + end. + +skip_padding(0) -> + 0; +skip_padding(Size) when (Size rem ?BLOCK_SIZE) =:= 0 -> + 0; +skip_padding(Size) when Size =< ?BLOCK_SIZE -> + ?BLOCK_SIZE - Size; +skip_padding(Size) -> + ?BLOCK_SIZE - (Size rem ?BLOCK_SIZE). + +skip_unread(#reader{pos=Pos}=Reader0) when (Pos rem ?BLOCK_SIZE) > 0 -> + Padding = skip_padding(Pos + ?BLOCK_SIZE), + AbsPos = Pos + Padding, + case do_position(Reader0, AbsPos) of + {ok, _, Reader1} -> + {ok, Reader1}; + Err -> + throw(Err) + end; +skip_unread(#reader{}=Reader) -> + {ok, Reader}; +skip_unread(#reg_file_reader{handle=Handle,num_bytes=0}) -> + skip_unread(Handle); +skip_unread(#reg_file_reader{}=Reader) -> + #reg_file_reader{handle=Handle} = skip_file(Reader), + {ok, Handle}; +skip_unread(#sparse_file_reader{handle=Handle,num_bytes=0}) -> + skip_unread(Handle); +skip_unread(#sparse_file_reader{}=Reader) -> + #sparse_file_reader{handle=Handle} = skip_file(Reader), + {ok, Handle}. + +write_extracted_element(#tar_header{name=Name,typeflag=Type}, + Bin, + #read_opts{output=memory}=Opts) -> + case typeflag(Type) of + regular -> + read_verbose(Opts, "x ~ts~n", [Name]), + {ok, {Name, Bin}}; + _ -> + ok + end; +write_extracted_element(#tar_header{name=Name0}=Header, Bin, Opts) -> + Name1 = make_safe_path(Name0, Opts), + Created = + case typeflag(Header#tar_header.typeflag) of + regular -> + create_regular(Name1, Name0, Bin, Opts); + directory -> + read_verbose(Opts, "x ~ts~n", [Name0]), + create_extracted_dir(Name1, Opts); + symlink -> + read_verbose(Opts, "x ~ts~n", [Name0]), + create_symlink(Name1, Header#tar_header.linkname, Opts); + Device when Device =:= char orelse Device =:= block -> + %% char/block devices will be created as empty files + %% and then have their major/minor device set later + create_regular(Name1, Name0, <<>>, Opts); + fifo -> + %% fifo devices will be created as empty files + create_regular(Name1, Name0, <<>>, Opts); + Other -> % Ignore. + read_verbose(Opts, "x ~ts - unsupported type ~p~n", + [Name0, Other]), + not_written + end, + case Created of + ok -> set_extracted_file_info(Name1, Header); + not_written -> ok + end. + +make_safe_path([$/|Path], Opts) -> + make_safe_path(Path, Opts); +make_safe_path(Path, #read_opts{cwd=Cwd}) -> + case safe_relative_path_links(Path, Cwd) of + unsafe -> + throw({error,{Path,unsafe_path}}); + SafePath -> + filename:absname(SafePath, Cwd) + end. + +safe_relative_path_links(Path, Cwd) -> + case filename:pathtype(Path) of + relative -> safe_relative_path_links(filename:split(Path), Cwd, [], ""); + _ -> unsafe + end. + +safe_relative_path_links([], _Cwd, _PrevLinks, Acc) -> + Acc; + +safe_relative_path_links([Segment | Segments], Cwd, PrevLinks, Acc) -> + AccSegment = join(Acc, Segment), + + case hex_filename:safe_relative_path(AccSegment) of + unsafe -> + unsafe; + + SafeAccSegment -> + case file:read_link(join(Cwd, SafeAccSegment)) of + {ok, LinkPath} -> + case lists:member(LinkPath, PrevLinks) of + true -> + unsafe; + false -> + case safe_relative_path_links(filename:split(LinkPath), Cwd, [LinkPath | PrevLinks], Acc) of + unsafe -> unsafe; + NewAcc -> safe_relative_path_links(Segments, Cwd, [], NewAcc) + end + end; + + {error, _} -> + safe_relative_path_links(Segments, Cwd, PrevLinks, SafeAccSegment) + end + end. + +join([], Path) -> Path; +join(Left, Right) -> filename:join(Left, Right). + +create_regular(Name, NameInArchive, Bin, Opts) -> + case write_extracted_file(Name, Bin, Opts) of + not_written -> + read_verbose(Opts, "x ~ts - exists, not created~n", [NameInArchive]), + not_written; + Ok -> + read_verbose(Opts, "x ~ts~n", [NameInArchive]), + Ok + end. + +create_extracted_dir(Name, _Opts) -> + case file:make_dir(Name) of + ok -> ok; + {error,enotsup} -> not_written; + {error,eexist} -> not_written; + {error,enoent} -> make_dirs(Name, dir); + {error,Reason} -> throw({error, Reason}) + end. + +create_symlink(Name, Linkname, Opts) -> + case file:make_symlink(Linkname, Name) of + ok -> ok; + {error,enoent} -> + ok = make_dirs(Name, file), + create_symlink(Name, Linkname, Opts); + {error,eexist} -> not_written; + {error,enotsup} -> + read_verbose(Opts, "x ~ts - symbolic links not supported~n", [Name]), + not_written; + {error,Reason} -> throw({error, Reason}) + end. + +write_extracted_file(Name, Bin, Opts) -> + Write = + case Opts#read_opts.keep_old_files of + true -> + case file:read_file_info(Name) of + {ok, _} -> false; + _ -> true + end; + false -> true + end, + case Write of + true -> write_file(Name, Bin); + false -> not_written + end. + +write_file(Name, Bin) -> + case file:write_file(Name, Bin) of + ok -> ok; + {error,enoent} -> + case make_dirs(Name, file) of + ok -> + write_file(Name, Bin); + {error,Reason} -> + throw({error, Reason}) + end; + {error,Reason} -> + throw({error, Reason}) + end. + +set_extracted_file_info(_, #tar_header{typeflag = ?TYPE_SYMLINK}) -> ok; +set_extracted_file_info(_, #tar_header{typeflag = ?TYPE_LINK}) -> ok; +set_extracted_file_info(Name, #tar_header{typeflag = ?TYPE_CHAR}=Header) -> + set_device_info(Name, Header); +set_extracted_file_info(Name, #tar_header{typeflag = ?TYPE_BLOCK}=Header) -> + set_device_info(Name, Header); +set_extracted_file_info(Name, #tar_header{mtime=Mtime,mode=Mode}) -> + Info = #file_info{mode=Mode, mtime=Mtime}, + file:write_file_info(Name, Info, [{time, posix}]). + +set_device_info(Name, #tar_header{}=Header) -> + Mtime = Header#tar_header.mtime, + Mode = Header#tar_header.mode, + Devmajor = Header#tar_header.devmajor, + Devminor = Header#tar_header.devminor, + Info = #file_info{ + mode=Mode, + mtime=Mtime, + major_device=Devmajor, + minor_device=Devminor + }, + file:write_file_info(Name, Info). + +%% Makes all directories leading up to the file. + +make_dirs(Name, file) -> + filelib:ensure_dir(Name); +make_dirs(Name, dir) -> + filelib:ensure_dir(filename:join(Name,"*")). + +%% Prints the message on if the verbose option is given (for reading). +read_verbose(#read_opts{verbose=true}, Format, Args) -> + io:format(Format, Args); +read_verbose(_, _, _) -> + ok. + +%% Prints the message on if the verbose option is given. +add_verbose(#add_opts{verbose=true}, Format, Args) -> + io:format(Format, Args); +add_verbose(_, _, _) -> + ok. + +%%%%%%%%%%%%%%%%%% +%% I/O primitives +%%%%%%%%%%%%%%%%%% + +do_write(#reader{handle=Handle,func=Fun}=Reader0, Data) + when is_function(Fun,2) -> + case Fun(write,{Handle,Data}) of + ok -> + {ok, Pos, Reader1} = do_position(Reader0, {cur,0}), + {ok, Reader1#reader{pos=Pos}}; + {error, _} = Err -> + Err + end. + +do_copy(#reader{func=Fun}=Reader, Source, #add_opts{chunk_size=0}=Opts) + when is_function(Fun, 2) -> + do_copy(Reader, Source, Opts#add_opts{chunk_size=65536}); +do_copy(#reader{func=Fun}=Reader, Source, #add_opts{chunk_size=ChunkSize}) + when is_function(Fun, 2) -> + case file:open(Source, [read, binary]) of + {ok, SourceFd} -> + case copy_chunked(Reader, SourceFd, ChunkSize, 0) of + {ok, _Copied, _Reader2} = Ok-> + _ = file:close(SourceFd), + Ok; + Err -> + _ = file:close(SourceFd), + throw(Err) + end; + Err -> + throw(Err) + end. + +copy_chunked(#reader{}=Reader, Source, ChunkSize, Copied) -> + case file:read(Source, ChunkSize) of + {ok, Bin} -> + {ok, Reader2} = do_write(Reader, Bin), + copy_chunked(Reader2, Source, ChunkSize, Copied+byte_size(Bin)); + eof -> + {ok, Copied, Reader}; + Other -> + Other + end. + + +do_position(#reader{handle=Handle,func=Fun}=Reader, Pos) + when is_function(Fun,2)-> + case Fun(position, {Handle,Pos}) of + {ok, NewPos} -> + %% since Pos may not always be an absolute seek, + %% make sure we update the reader with the new absolute position + {ok, AbsPos} = Fun(position, {Handle, {cur, 0}}), + {ok, NewPos, Reader#reader{pos=AbsPos}}; + Other -> + Other + end. + +do_read(#reg_file_reader{handle=Handle,pos=Pos,size=Size}=Reader, Len) -> + NumBytes = Size - Pos, + ActualLen = if NumBytes - Len < 0 -> NumBytes; true -> Len end, + case do_read(Handle, ActualLen) of + {ok, Bin, Handle2} -> + NewPos = Pos + ActualLen, + NumBytes2 = Size - NewPos, + Reader1 = Reader#reg_file_reader{ + handle=Handle2, + pos=NewPos, + num_bytes=NumBytes2}, + {ok, Bin, Reader1}; + Other -> + Other + end; +do_read(#sparse_file_reader{}=Reader, Len) -> + do_sparse_read(Reader, Len); +do_read(#reader{pos=Pos,handle=Handle,func=Fun}=Reader, Len) + when is_function(Fun,2)-> + %% Always convert to binary internally + case Fun(read2,{Handle,Len}) of + {ok, List} when is_list(List) -> + Bin = list_to_binary(List), + NewPos = Pos+byte_size(Bin), + {ok, Bin, Reader#reader{pos=NewPos}}; + {ok, Bin} when is_binary(Bin) -> + NewPos = Pos+byte_size(Bin), + {ok, Bin, Reader#reader{pos=NewPos}}; + Other -> + Other + end. + + +do_sparse_read(Reader, Len) -> + do_sparse_read(Reader, Len, <<>>). + +do_sparse_read(#sparse_file_reader{sparse_map=[#sparse_entry{num_bytes=0}|Entries] + }=Reader0, Len, Acc) -> + %% skip all empty fragments + Reader1 = Reader0#sparse_file_reader{sparse_map=Entries}, + do_sparse_read(Reader1, Len, Acc); +do_sparse_read(#sparse_file_reader{sparse_map=[], + pos=Pos,size=Size}=Reader0, Len, Acc) + when Pos < Size -> + %% if there are no more fragments, it is possible that there is one last sparse hole + %% this behaviour matches the BSD tar utility + %% however, GNU tar stops returning data even if we haven't reached the end + {ok, Bin, Reader1} = read_sparse_hole(Reader0, Size, Len), + do_sparse_read(Reader1, Len-byte_size(Bin), <>); +do_sparse_read(#sparse_file_reader{sparse_map=[]}=Reader, _Len, Acc) -> + {ok, Acc, Reader}; +do_sparse_read(#sparse_file_reader{}=Reader, 0, Acc) -> + {ok, Acc, Reader}; +do_sparse_read(#sparse_file_reader{sparse_map=[#sparse_entry{offset=Offset}|_], + pos=Pos}=Reader0, Len, Acc) + when Pos < Offset -> + {ok, Bin, Reader1} = read_sparse_hole(Reader0, Offset, Offset-Pos), + do_sparse_read(Reader1, Len-byte_size(Bin), <>); +do_sparse_read(#sparse_file_reader{sparse_map=[Entry|Entries], + pos=Pos}=Reader0, Len, Acc) -> + %% we're in a data fragment, so read from it + %% end offset of fragment + EndPos = Entry#sparse_entry.offset + Entry#sparse_entry.num_bytes, + %% bytes left in fragment + NumBytes = EndPos - Pos, + ActualLen = if Len > NumBytes -> NumBytes; true -> Len end, + case do_read(Reader0#sparse_file_reader.handle, ActualLen) of + {ok, Bin, Handle} -> + BytesRead = byte_size(Bin), + ActualEndPos = Pos+BytesRead, + Reader1 = if ActualEndPos =:= EndPos -> + Reader0#sparse_file_reader{sparse_map=Entries}; + true -> + Reader0 + end, + Size = Reader1#sparse_file_reader.size, + NumBytes2 = Size - ActualEndPos, + Reader2 = Reader1#sparse_file_reader{ + handle=Handle, + pos=ActualEndPos, + num_bytes=NumBytes2}, + do_sparse_read(Reader2, Len-byte_size(Bin), <>); + Other -> + Other + end. + +%% Reads a sparse hole ending at Offset +read_sparse_hole(#sparse_file_reader{pos=Pos}=Reader, Offset, Len) -> + N = Offset - Pos, + N2 = if N > Len -> + Len; + true -> + N + end, + Bin = <<0:N2/unit:8>>, + NumBytes = Reader#sparse_file_reader.size - (Pos+N2), + {ok, Bin, Reader#sparse_file_reader{ + num_bytes=NumBytes, + pos=Pos+N2}}. + +-spec do_close(reader()) -> ok | {error, term()}. +do_close(#reader{handle=Handle,func=Fun}) when is_function(Fun,2) -> + Fun(close,Handle). + +%%%%%%%%%%%%%%%%%% +%% Option parsing +%%%%%%%%%%%%%%%%%% + +extract_opts(List) -> + extract_opts(List, default_options()). + +table_opts(List) -> + read_opts(List, default_options()). + +default_options() -> + {ok, Cwd} = file:get_cwd(), + #read_opts{cwd=Cwd}. + +extract_opts([keep_old_files|Rest], Opts) -> + extract_opts(Rest, Opts#read_opts{keep_old_files=true}); +extract_opts([{cwd, Cwd}|Rest], Opts) -> + extract_opts(Rest, Opts#read_opts{cwd=Cwd}); +extract_opts([{files, Files}|Rest], Opts) -> + Set = ordsets:from_list(Files), + extract_opts(Rest, Opts#read_opts{files=Set}); +extract_opts([memory|Rest], Opts) -> + extract_opts(Rest, Opts#read_opts{output=memory}); +extract_opts([compressed|Rest], Opts=#read_opts{open_mode=OpenMode}) -> + extract_opts(Rest, Opts#read_opts{open_mode=[compressed|OpenMode]}); +extract_opts([cooked|Rest], Opts=#read_opts{open_mode=OpenMode}) -> + extract_opts(Rest, Opts#read_opts{open_mode=[cooked|OpenMode]}); +extract_opts([verbose|Rest], Opts) -> + extract_opts(Rest, Opts#read_opts{verbose=true}); +extract_opts([Other|Rest], Opts) -> + extract_opts(Rest, read_opts([Other], Opts)); +extract_opts([], Opts) -> + Opts. + +read_opts([compressed|Rest], Opts=#read_opts{open_mode=OpenMode}) -> + read_opts(Rest, Opts#read_opts{open_mode=[compressed|OpenMode]}); +read_opts([cooked|Rest], Opts=#read_opts{open_mode=OpenMode}) -> + read_opts(Rest, Opts#read_opts{open_mode=[cooked|OpenMode]}); +read_opts([verbose|Rest], Opts) -> + read_opts(Rest, Opts#read_opts{verbose=true}); +read_opts([_|Rest], Opts) -> + read_opts(Rest, Opts); +read_opts([], Opts) -> + Opts. diff --git a/deps/eini/_build/default/plugins/hex_core/src/hex_erl_tar.hrl b/deps/eini/_build/default/plugins/hex_core/src/hex_erl_tar.hrl new file mode 100644 index 0000000000000000000000000000000000000000..d142270f11ee1e36b900519929b9c3ccad5f9be4 --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/src/hex_erl_tar.hrl @@ -0,0 +1,409 @@ +% Copied from https://github.com/erlang/otp/blob/OTP-20.0.1/lib/stdlib/src/erl_tar.hrl + +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2017. All Rights Reserved. +%% +%% Licensed under the Apache License, Version 2.0 (the "License"); +%% you may not use this file except in compliance with the License. +%% You may obtain a copy of the License at +%% +%% http://www.apache.org/licenses/LICENSE-2.0 +%% +%% Unless required by applicable law or agreed to in writing, software +%% distributed under the License is distributed on an "AS IS" BASIS, +%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +%% See the License for the specific language governing permissions and +%% limitations under the License. +%% +%% %CopyrightEnd% + +%% Options used when adding files to a tar archive. +-record(add_opts, { + read_info, %% Fun to use for read file/link info. + chunk_size = 0 :: integer(), %% For file reading when sending to sftp. 0=do not chunk + verbose = false :: boolean(), %% Verbose on/off. + atime = undefined :: undefined | integer(), + mtime = undefined :: undefined | integer(), + ctime = undefined :: undefined | integer(), + uid = 0 :: integer(), + gid = 0 :: integer()}). +-type add_opts() :: #add_opts{}. + +%% Options used when reading a tar archive. +-record(read_opts, { + cwd :: string(), %% Current working directory. + keep_old_files = false :: boolean(), %% Owerwrite or not. + files = all, %% Set of files to extract (or all) + output = file :: 'file' | 'memory', + open_mode = [], %% Open mode options. + verbose = false :: boolean()}). %% Verbose on/off. +-type read_opts() :: #read_opts{}. + +-type add_opt() :: dereference + | verbose + | {chunks, pos_integer()} + | {atime, integer()} + | {mtime, integer()} + | {ctime, integer()} + | {uid, integer()} + | {gid, integer()}. + + +-type extract_opt() :: {cwd, string()} | + {files, [string()]} | + compressed | + cooked | + memory | + keep_old_files | + verbose. + +-type create_opt() :: compressed | + cooked | + dereference | + verbose. + +-type filelist() :: [file:filename() | + {string(), binary()} | + {string(), file:filename()}]. + +-type tar_time() :: non_neg_integer(). + +%% The tar header, once fully parsed. +-record(tar_header, { + name = "" :: string(), %% name of header file entry + mode = 8#100644 :: non_neg_integer(), %% permission and mode bits + uid = 0 :: non_neg_integer(), %% user id of owner + gid = 0 :: non_neg_integer(), %% group id of owner + size = 0 :: non_neg_integer(), %% length in bytes + mtime :: tar_time(), %% modified time + typeflag :: char(), %% type of header entry + linkname = "" :: string(), %% target name of link + uname = "" :: string(), %% user name of owner + gname = "" :: string(), %% group name of owner + devmajor = 0 :: non_neg_integer(), %% major number of character or block device + devminor = 0 :: non_neg_integer(), %% minor number of character or block device + atime :: tar_time(), %% access time + ctime :: tar_time() %% status change time + }). +-type tar_header() :: #tar_header{}. + +%% Metadata for a sparse file fragment +-record(sparse_entry, { + offset = 0 :: non_neg_integer(), + num_bytes = 0 :: non_neg_integer()}). +-type sparse_entry() :: #sparse_entry{}. +%% Contains metadata about fragments of a sparse file +-record(sparse_array, { + entries = [] :: [sparse_entry()], + is_extended = false :: boolean(), + max_entries = 0 :: non_neg_integer()}). +-type sparse_array() :: #sparse_array{}. +%% A subset of tar header fields common to all tar implementations +-record(header_v7, { + name :: binary(), + mode :: binary(), %% octal + uid :: binary(), %% integer + gid :: binary(), %% integer + size :: binary(), %% integer + mtime :: binary(), %% integer + checksum :: binary(), %% integer + typeflag :: byte(), %% char + linkname :: binary()}). +-type header_v7() :: #header_v7{}. +%% The set of fields specific to GNU tar formatted archives +-record(header_gnu, { + header_v7 :: header_v7(), + magic :: binary(), + version :: binary(), + uname :: binary(), + gname :: binary(), + devmajor :: binary(), %% integer + devminor :: binary(), %% integer + atime :: binary(), %% integer + ctime :: binary(), %% integer + sparse :: sparse_array(), + real_size :: binary()}). %% integer +-type header_gnu() :: #header_gnu{}. +%% The set of fields specific to STAR-formatted archives +-record(header_star, { + header_v7 :: header_v7(), + magic :: binary(), + version :: binary(), + uname :: binary(), + gname :: binary(), + devmajor :: binary(), %% integer + devminor :: binary(), %% integer + prefix :: binary(), + atime :: binary(), %% integer + ctime :: binary(), %% integer + trailer :: binary()}). +-type header_star() :: #header_star{}. +%% The set of fields specific to USTAR-formatted archives +-record(header_ustar, { + header_v7 :: header_v7(), + magic :: binary(), + version :: binary(), + uname :: binary(), + gname :: binary(), + devmajor :: binary(), %% integer + devminor :: binary(), %% integer + prefix :: binary()}). +-type header_ustar() :: #header_ustar{}. + +-type header_fields() :: header_v7() | + header_gnu() | + header_star() | + header_ustar(). + +%% The overall tar reader, it holds the low-level file handle, +%% its access, position, and the I/O primitives wrapper. +-record(reader, { + handle :: file:io_device() | term(), + access :: read | write | ram, + pos = 0 :: non_neg_integer(), + func :: file_op() + }). +-type reader() :: #reader{}. +%% A reader for a regular file within the tar archive, +%% It tracks its current state relative to that file. +-record(reg_file_reader, { + handle :: reader(), + num_bytes = 0, + pos = 0, + size = 0 + }). +-type reg_file_reader() :: #reg_file_reader{}. +%% A reader for a sparse file within the tar archive, +%% It tracks its current state relative to that file. +-record(sparse_file_reader, { + handle :: reader(), + num_bytes = 0, %% bytes remaining + pos = 0, %% pos + size = 0, %% total size of file + sparse_map = #sparse_array{} + }). +-type sparse_file_reader() :: #sparse_file_reader{}. + +%% Types for the readers +-type reader_type() :: reader() | reg_file_reader() | sparse_file_reader(). +-type handle() :: file:io_device() | term(). + +%% Type for the I/O primitive wrapper function +-type file_op() :: fun((write | close | read2 | position, + {handle(), iodata()} | handle() | {handle(), non_neg_integer()} + | {handle(), non_neg_integer()}) -> + ok | eof | {ok, string() | binary()} | {ok, non_neg_integer()} + | {error, term()}). + +%% These constants (except S_IFMT) are +%% used to determine what type of device +%% a file is. Namely, `S_IFMT band file_info.mode` +%% will equal one of these contants, and tells us +%% which type it is. The stdlib file_info record +%% does not differentiate between device types, and +%% will not allow us to differentiate between sockets +%% and named pipes. These constants are pulled from libc. +-define(S_IFMT, 61440). +-define(S_IFSOCK, 49152). %% socket +-define(S_FIFO, 4096). %% fifo/named pipe +-define(S_IFBLK, 24576). %% block device +-define(S_IFCHR, 8192). %% character device + +%% Typeflag constants for the tar header +-define(TYPE_REGULAR, $0). %% regular file +-define(TYPE_REGULAR_A, 0). %% regular file +-define(TYPE_LINK, $1). %% hard link +-define(TYPE_SYMLINK, $2). %% symbolic link +-define(TYPE_CHAR, $3). %% character device node +-define(TYPE_BLOCK, $4). %% block device node +-define(TYPE_DIR, $5). %% directory +-define(TYPE_FIFO, $6). %% fifo node +-define(TYPE_CONT, $7). %% reserved +-define(TYPE_X_HEADER, $x). %% extended header +-define(TYPE_X_GLOBAL_HEADER, $g). %% global extended header +-define(TYPE_GNU_LONGNAME, $L). %% next file has a long name +-define(TYPE_GNU_LONGLINK, $K). %% next file symlinks to a file with a long name +-define(TYPE_GNU_SPARSE, $S). %% sparse file + +%% Mode constants from tar spec +-define(MODE_ISUID, 4000). %% set uid +-define(MODE_ISGID, 2000). %% set gid +-define(MODE_ISVTX, 1000). %% save text (sticky bit) +-define(MODE_ISDIR, 40000). %% directory +-define(MODE_ISFIFO, 10000). %% fifo +-define(MODE_ISREG, 100000). %% regular file +-define(MODE_ISLNK, 120000). %% symbolic link +-define(MODE_ISBLK, 60000). %% block special file +-define(MODE_ISCHR, 20000). %% character special file +-define(MODE_ISSOCK, 140000). %% socket + +%% Keywords for PAX extended header +-define(PAX_ATIME, <<"atime">>). +-define(PAX_CHARSET, <<"charset">>). +-define(PAX_COMMENT, <<"comment">>). +-define(PAX_CTIME, <<"ctime">>). %% ctime is not a valid pax header +-define(PAX_GID, <<"gid">>). +-define(PAX_GNAME, <<"gname">>). +-define(PAX_LINKPATH, <<"linkpath">>). +-define(PAX_MTIME, <<"mtime">>). +-define(PAX_PATH, <<"path">>). +-define(PAX_SIZE, <<"size">>). +-define(PAX_UID, <<"uid">>). +-define(PAX_UNAME, <<"uname">>). +-define(PAX_XATTR, <<"SCHILY.xattr.">>). +-define(PAX_XATTR_STR, "SCHILY.xattr."). +-define(PAX_NONE, <<"">>). + +%% Tar format constants +%% Unknown format +-define(FORMAT_UNKNOWN, 0). +%% The format of the original Unix V7 tar tool prior to standardization +-define(FORMAT_V7, 1). +%% The old and new GNU formats, incompatible with USTAR. +%% This covers the old GNU sparse extension, but it does +%% not cover the GNU sparse extensions using PAX headers, +%% versions 0.0, 0.1, and 1.0; these fall under the PAX format. +-define(FORMAT_GNU, 2). +%% Schily's tar format, which is incompatible with USTAR. +%% This does not cover STAR extensions to the PAX format; these +%% fall under the PAX format. +-define(FORMAT_STAR, 3). +%% USTAR is the former standardization of tar defined in POSIX.1-1988, +%% it is incompatible with the GNU and STAR formats. +-define(FORMAT_USTAR, 4). +%% PAX is the latest standardization of tar defined in POSIX.1-2001. +%% This is an extension of USTAR and is "backwards compatible" with it. +%% +%% Some newer formats add their own extensions to PAX, such as GNU sparse +%% files and SCHILY extended attributes. Since they are backwards compatible +%% with PAX, they will be labelled as "PAX". +-define(FORMAT_PAX, 5). + +%% Magic constants +-define(MAGIC_GNU, <<"ustar ">>). +-define(VERSION_GNU, <<" \x00">>). +-define(MAGIC_USTAR, <<"ustar\x00">>). +-define(VERSION_USTAR, <<"00">>). +-define(TRAILER_STAR, <<"tar\x00">>). + +%% Size constants +-define(BLOCK_SIZE, 512). %% size of each block in a tar stream +-define(NAME_SIZE, 100). %% max length of the name field in USTAR format +-define(PREFIX_SIZE, 155). %% max length of the prefix field in USTAR format + +%% Maximum size of a nanosecond value as an integer +-define(MAX_NANO_INT_SIZE, 9). +%% Maximum size of a 64-bit signed integer +-define(MAX_INT64, (1 bsl 63 - 1)). + +-define(PAX_GNU_SPARSE_NUMBLOCKS, <<"GNU.sparse.numblocks">>). +-define(PAX_GNU_SPARSE_OFFSET, <<"GNU.sparse.offset">>). +-define(PAX_GNU_SPARSE_NUMBYTES, <<"GNU.sparse.numbytes">>). +-define(PAX_GNU_SPARSE_MAP, <<"GNU.sparse.map">>). +-define(PAX_GNU_SPARSE_NAME, <<"GNU.sparse.name">>). +-define(PAX_GNU_SPARSE_MAJOR, <<"GNU.sparse.major">>). +-define(PAX_GNU_SPARSE_MINOR, <<"GNU.sparse.minor">>). +-define(PAX_GNU_SPARSE_SIZE, <<"GNU.sparse.size">>). +-define(PAX_GNU_SPARSE_REALSIZE, <<"GNU.sparse.realsize">>). + +-define(V7_NAME, 0). +-define(V7_NAME_LEN, 100). +-define(V7_MODE, 100). +-define(V7_MODE_LEN, 8). +-define(V7_UID, 108). +-define(V7_UID_LEN, 8). +-define(V7_GID, 116). +-define(V7_GID_LEN, 8). +-define(V7_SIZE, 124). +-define(V7_SIZE_LEN, 12). +-define(V7_MTIME, 136). +-define(V7_MTIME_LEN, 12). +-define(V7_CHKSUM, 148). +-define(V7_CHKSUM_LEN, 8). +-define(V7_TYPE, 156). +-define(V7_TYPE_LEN, 1). +-define(V7_LINKNAME, 157). +-define(V7_LINKNAME_LEN, 100). + +-define(STAR_TRAILER, 508). +-define(STAR_TRAILER_LEN, 4). + +-define(USTAR_MAGIC, 257). +-define(USTAR_MAGIC_LEN, 6). +-define(USTAR_VERSION, 263). +-define(USTAR_VERSION_LEN, 2). +-define(USTAR_UNAME, 265). +-define(USTAR_UNAME_LEN, 32). +-define(USTAR_GNAME, 297). +-define(USTAR_GNAME_LEN, 32). +-define(USTAR_DEVMAJ, 329). +-define(USTAR_DEVMAJ_LEN, 8). +-define(USTAR_DEVMIN, 337). +-define(USTAR_DEVMIN_LEN, 8). +-define(USTAR_PREFIX, 345). +-define(USTAR_PREFIX_LEN, 155). + +-define(GNU_MAGIC, 257). +-define(GNU_MAGIC_LEN, 6). +-define(GNU_VERSION, 263). +-define(GNU_VERSION_LEN, 2). + +%% ?BLOCK_SIZE of zero-bytes. +%% Two of these in a row mark the end of an archive. +-define(ZERO_BLOCK, <<0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0>>). + +-define(BILLION, 1000000000). + +-define(EPOCH, {{1970,1,1}, {0,0,0}}). diff --git a/deps/eini/_build/default/plugins/hex_core/src/hex_http.erl b/deps/eini/_build/default/plugins/hex_core/src/hex_http.erl new file mode 100644 index 0000000000000000000000000000000000000000..c073481b88358e0de3e1ff172265ef6de8733f28 --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/src/hex_http.erl @@ -0,0 +1,60 @@ +%% @doc +%% HTTP contract. +-module(hex_http). +-export([request/5]). +-ifdef(TEST). +-export([user_agent/1]). +-endif. +-include_lib("hex_core.hrl"). + +-type method() :: get | post | put | patch | delete. +-type status() :: non_neg_integer(). +-export_type([status/0]). +-type headers() :: #{binary() => binary()}. +-export_type([headers/0]). +-type body() :: {ContentType :: binary(), Body :: binary()} | undefined. +-export_type([body/0]). +-type adapter_config() :: map(). +-export_type([adapter_config/0]). + +-callback request(method(), URI :: binary(), headers(), body(), adapter_config()) -> + {ok, {status(), headers(), binary()}} + | {error, term()}. + +-spec request(hex_core:config(), method(), URI :: binary(), headers(), body()) -> + {ok, {status(), headers(), binary()}} | {error, term()}. +request(Config, Method, URI, Headers, Body) when is_binary(URI) and is_map(Headers) -> + {Adapter, AdapterConfig} = + case maps:get(http_adapter, Config, {hex_http_httpc, #{}}) of + {Adapter0, AdapterConfig0} -> + {Adapter0, AdapterConfig0}; + %% TODO: remove in v0.9 + Adapter0 when is_atom(Adapter0) -> + AdapterConfig0 = maps:get(http_adapter_config, Config, #{}), + io:format( + "[hex_http] setting #{http_adapter => Module, http_adapter_config => Map} " + "is deprecated in favour of #{http_adapter => {Module, Map}}~n" + ), + {Adapter0, AdapterConfig0} + end, + UserAgentFragment = maps:get(http_user_agent_fragment, Config), + Headers2 = put_new(<<"user-agent">>, user_agent(UserAgentFragment), Headers), + Adapter:request(Method, URI, Headers2, Body, AdapterConfig). + +%% @private +user_agent(UserAgentFragment) -> + OTPRelease = erlang:system_info(otp_release), + ERTSVersion = erlang:system_info(version), + OTPString = " (OTP/" ++ OTPRelease ++ ") (erts/" ++ ERTSVersion ++ ")", + iolist_to_binary(["hex_core/", ?HEX_CORE_VERSION, " ", UserAgentFragment, OTPString]). + +%%==================================================================== +%% Internal functions +%%==================================================================== + +%% @private +put_new(Key, Value, Map) -> + case maps:find(Key, Map) of + {ok, _} -> Map; + error -> maps:put(Key, Value, Map) + end. diff --git a/deps/eini/_build/default/plugins/hex_core/src/hex_http_httpc.erl b/deps/eini/_build/default/plugins/hex_core/src/hex_http_httpc.erl new file mode 100644 index 0000000000000000000000000000000000000000..bb44e8104ee60f1bb63663cd0a95900008a3f720 --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/src/hex_http_httpc.erl @@ -0,0 +1,103 @@ +%% @doc +%% httpc-based implementation of {@link hex_http} contract. +%% +%% Configuration keys: +%% +%% * `profile' - the name of the profile, defaults to `default'. See +%% {@link httpc:set_options/2} for more information on setting +%% options on profiles. +%% +%% * `http_options' - a list of HTTP options, defaults to `[]'. See +%% {@link httpc:request/5} for a list of available HTTP options. + +-module(hex_http_httpc). +-behaviour(hex_http). +-export([request/5]). + +%%==================================================================== +%% API functions +%%==================================================================== + +request(Method, URI, ReqHeaders, Body, AdapterConfig) when is_binary(URI) -> + Profile = maps:get(profile, AdapterConfig, default), + HTTPOptions0 = maps:get(http_options, AdapterConfig, []), + + HTTPS = + case URI of + <<"https", _/binary>> -> true; + _ -> false + end, + SSLOpts0 = proplists:get_value(ssl, HTTPOptions0), + + HTTPOptions = + if + HTTPS == true andalso SSLOpts0 == undefined -> + %% Add safe defaults if possible. + try + [ + {ssl, [ + {verify, verify_peer}, + {cacerts, public_key:cacerts_get()}, + {depth, 3}, + {customize_hostname_check, [ + {match_fun, public_key:pkix_verify_hostname_match_fun(https)} + ]} + ]} + | HTTPOptions0 + ] + catch + _:_ -> + io:format( + "[hex_http_httpc] using default ssl options which are insecure.~n" + "Configure your adapter with: " + "{hex_http_httpc, #{http_options => [{ssl, SslOpts}]}}~n" + "or upgrade Erlang/OTP to OTP-25 or later.~n" + ), + HTTPOptions0 + end; + true -> + HTTPOptions0 + end, + + Request = build_request(URI, ReqHeaders, Body), + case httpc:request(Method, Request, HTTPOptions, [{body_format, binary}], Profile) of + {ok, {{_, StatusCode, _}, RespHeaders, RespBody}} -> + RespHeaders2 = load_headers(RespHeaders), + {ok, {StatusCode, RespHeaders2, RespBody}}; + {error, Reason} -> + {error, Reason} + end. + +%%==================================================================== +%% Internal functions +%%==================================================================== + +%% @private +build_request(URI, ReqHeaders, Body) -> + build_request2(binary_to_list(URI), dump_headers(ReqHeaders), Body). + +%% @private +build_request2(URI, ReqHeaders, undefined) -> + {URI, ReqHeaders}; +build_request2(URI, ReqHeaders, {ContentType, Body}) -> + {URI, ReqHeaders, ContentType, Body}. + +%% @private +dump_headers(Map) -> + maps:fold( + fun(K, V, Acc) -> + [{binary_to_list(K), binary_to_list(V)} | Acc] + end, + [], + Map + ). + +%% @private +load_headers(List) -> + lists:foldl( + fun({K, V}, Acc) -> + maps:put(list_to_binary(K), list_to_binary(V), Acc) + end, + #{}, + List + ). diff --git a/deps/eini/_build/default/plugins/hex_core/src/hex_pb_names.erl b/deps/eini/_build/default/plugins/hex_core/src/hex_pb_names.erl new file mode 100644 index 0000000000000000000000000000000000000000..a9891e0926510a3a9442b7b062994829d0bdb315 --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/src/hex_pb_names.erl @@ -0,0 +1,856 @@ +%% -*- coding: utf-8 -*- +%% % this file is @generated +%% @private +%% Automatically generated, do not edit +%% Generated by gpb_compile version 4.21.1 +%% Version source: file +-module(hex_pb_names). + +-export([encode_msg/2, encode_msg/3]). +-export([decode_msg/2, decode_msg/3]). +-export([merge_msgs/3, merge_msgs/4]). +-export([verify_msg/2, verify_msg/3]). +-export([get_msg_defs/0]). +-export([get_msg_names/0]). +-export([get_group_names/0]). +-export([get_msg_or_group_names/0]). +-export([get_enum_names/0]). +-export([find_msg_def/1, fetch_msg_def/1]). +-export([find_enum_def/1, fetch_enum_def/1]). +-export([enum_symbol_by_value/2, enum_value_by_symbol/2]). +-export([get_service_names/0]). +-export([get_service_def/1]). +-export([get_rpc_names/1]). +-export([find_rpc_def/2, fetch_rpc_def/2]). +-export([fqbin_to_service_name/1]). +-export([service_name_to_fqbin/1]). +-export([fqbins_to_service_and_rpc_name/2]). +-export([service_and_rpc_name_to_fqbins/2]). +-export([fqbin_to_msg_name/1]). +-export([msg_name_to_fqbin/1]). +-export([fqbin_to_enum_name/1]). +-export([enum_name_to_fqbin/1]). +-export([get_package_name/0]). +-export([uses_packages/0]). +-export([source_basename/0]). +-export([get_all_source_basenames/0]). +-export([get_all_proto_names/0]). +-export([get_msg_containment/1]). +-export([get_pkg_containment/1]). +-export([get_service_containment/1]). +-export([get_rpc_containment/1]). +-export([get_enum_containment/1]). +-export([get_proto_by_msg_name_as_fqbin/1]). +-export([get_proto_by_service_name_as_fqbin/1]). +-export([get_proto_by_enum_name_as_fqbin/1]). +-export([get_protos_by_pkg_name_as_fqbin/1]). +-export([gpb_version_as_string/0, gpb_version_as_list/0]). +-export([gpb_version_source/0]). + + +%% enumerated types + +-export_type([]). + +%% message types +-type 'Names'() :: + #{packages => ['Package'()], % = 1, repeated + repository => unicode:chardata() % = 2, required + }. + +-type 'Package'() :: + #{name => unicode:chardata(), % = 1, required + updated_at => 'Timestamp'() % = 3, optional + }. + +-type 'Timestamp'() :: + #{seconds => integer(), % = 1, required, 64 bits + nanos => integer() % = 2, required, 32 bits + }. + +-export_type(['Names'/0, 'Package'/0, 'Timestamp'/0]). +-type '$msg_name'() :: 'Names' | 'Package' | 'Timestamp'. +-type '$msg'() :: 'Names'() | 'Package'() | 'Timestamp'(). +-export_type(['$msg_name'/0, '$msg'/0]). + +-if(?OTP_RELEASE >= 24). +-dialyzer({no_underspecs, encode_msg/2}). +-endif. +-spec encode_msg('$msg'(), '$msg_name'()) -> binary(). +encode_msg(Msg, MsgName) when is_atom(MsgName) -> encode_msg(Msg, MsgName, []). + +-if(?OTP_RELEASE >= 24). +-dialyzer({no_underspecs, encode_msg/3}). +-endif. +-spec encode_msg('$msg'(), '$msg_name'(), list()) -> binary(). +encode_msg(Msg, MsgName, Opts) -> + verify_msg(Msg, MsgName, Opts), + TrUserData = proplists:get_value(user_data, Opts), + case MsgName of + 'Names' -> encode_msg_Names(id(Msg, TrUserData), TrUserData); + 'Package' -> encode_msg_Package(id(Msg, TrUserData), TrUserData); + 'Timestamp' -> encode_msg_Timestamp(id(Msg, TrUserData), TrUserData) + end. + + +encode_msg_Names(Msg, TrUserData) -> encode_msg_Names(Msg, <<>>, TrUserData). + + +encode_msg_Names(#{repository := F2} = M, Bin, TrUserData) -> + B1 = case M of + #{packages := F1} -> + TrF1 = id(F1, TrUserData), + if TrF1 == [] -> Bin; + true -> e_field_Names_packages(TrF1, Bin, TrUserData) + end; + _ -> Bin + end, + begin TrF2 = id(F2, TrUserData), e_type_string(TrF2, <>, TrUserData) end. + +encode_msg_Package(Msg, TrUserData) -> encode_msg_Package(Msg, <<>>, TrUserData). + + +encode_msg_Package(#{name := F1} = M, Bin, TrUserData) -> + B1 = begin TrF1 = id(F1, TrUserData), e_type_string(TrF1, <>, TrUserData) end, + case M of + #{updated_at := F2} -> begin TrF2 = id(F2, TrUserData), e_mfield_Package_updated_at(TrF2, <>, TrUserData) end; + _ -> B1 + end. + +encode_msg_Timestamp(Msg, TrUserData) -> encode_msg_Timestamp(Msg, <<>>, TrUserData). + + +encode_msg_Timestamp(#{seconds := F1, nanos := F2}, Bin, TrUserData) -> + B1 = begin TrF1 = id(F1, TrUserData), e_type_int64(TrF1, <>, TrUserData) end, + begin TrF2 = id(F2, TrUserData), e_type_int32(TrF2, <>, TrUserData) end. + +e_mfield_Names_packages(Msg, Bin, TrUserData) -> + SubBin = encode_msg_Package(Msg, <<>>, TrUserData), + Bin2 = e_varint(byte_size(SubBin), Bin), + <>. + +e_field_Names_packages([Elem | Rest], Bin, TrUserData) -> + Bin2 = <>, + Bin3 = e_mfield_Names_packages(id(Elem, TrUserData), Bin2, TrUserData), + e_field_Names_packages(Rest, Bin3, TrUserData); +e_field_Names_packages([], Bin, _TrUserData) -> Bin. + +e_mfield_Package_updated_at(Msg, Bin, TrUserData) -> + SubBin = encode_msg_Timestamp(Msg, <<>>, TrUserData), + Bin2 = e_varint(byte_size(SubBin), Bin), + <>. + +-compile({nowarn_unused_function,e_type_sint/3}). +e_type_sint(Value, Bin, _TrUserData) when Value >= 0 -> e_varint(Value * 2, Bin); +e_type_sint(Value, Bin, _TrUserData) -> e_varint(Value * -2 - 1, Bin). + +-compile({nowarn_unused_function,e_type_int32/3}). +e_type_int32(Value, Bin, _TrUserData) when 0 =< Value, Value =< 127 -> <>; +e_type_int32(Value, Bin, _TrUserData) -> + <> = <>, + e_varint(N, Bin). + +-compile({nowarn_unused_function,e_type_int64/3}). +e_type_int64(Value, Bin, _TrUserData) when 0 =< Value, Value =< 127 -> <>; +e_type_int64(Value, Bin, _TrUserData) -> + <> = <>, + e_varint(N, Bin). + +-compile({nowarn_unused_function,e_type_bool/3}). +e_type_bool(true, Bin, _TrUserData) -> <>; +e_type_bool(false, Bin, _TrUserData) -> <>; +e_type_bool(1, Bin, _TrUserData) -> <>; +e_type_bool(0, Bin, _TrUserData) -> <>. + +-compile({nowarn_unused_function,e_type_string/3}). +e_type_string(S, Bin, _TrUserData) -> + Utf8 = unicode:characters_to_binary(S), + Bin2 = e_varint(byte_size(Utf8), Bin), + <>. + +-compile({nowarn_unused_function,e_type_bytes/3}). +e_type_bytes(Bytes, Bin, _TrUserData) when is_binary(Bytes) -> + Bin2 = e_varint(byte_size(Bytes), Bin), + <>; +e_type_bytes(Bytes, Bin, _TrUserData) when is_list(Bytes) -> + BytesBin = iolist_to_binary(Bytes), + Bin2 = e_varint(byte_size(BytesBin), Bin), + <>. + +-compile({nowarn_unused_function,e_type_fixed32/3}). +e_type_fixed32(Value, Bin, _TrUserData) -> <>. + +-compile({nowarn_unused_function,e_type_sfixed32/3}). +e_type_sfixed32(Value, Bin, _TrUserData) -> <>. + +-compile({nowarn_unused_function,e_type_fixed64/3}). +e_type_fixed64(Value, Bin, _TrUserData) -> <>. + +-compile({nowarn_unused_function,e_type_sfixed64/3}). +e_type_sfixed64(Value, Bin, _TrUserData) -> <>. + +-compile({nowarn_unused_function,e_type_float/3}). +e_type_float(V, Bin, _) when is_number(V) -> <>; +e_type_float(infinity, Bin, _) -> <>; +e_type_float('-infinity', Bin, _) -> <>; +e_type_float(nan, Bin, _) -> <>. + +-compile({nowarn_unused_function,e_type_double/3}). +e_type_double(V, Bin, _) when is_number(V) -> <>; +e_type_double(infinity, Bin, _) -> <>; +e_type_double('-infinity', Bin, _) -> <>; +e_type_double(nan, Bin, _) -> <>. + +-compile({nowarn_unused_function,e_unknown_elems/2}). +e_unknown_elems([Elem | Rest], Bin) -> + BinR = case Elem of + {varint, FNum, N} -> + BinF = e_varint(FNum bsl 3, Bin), + e_varint(N, BinF); + {length_delimited, FNum, Data} -> + BinF = e_varint(FNum bsl 3 bor 2, Bin), + BinL = e_varint(byte_size(Data), BinF), + <>; + {group, FNum, GroupFields} -> + Bin1 = e_varint(FNum bsl 3 bor 3, Bin), + Bin2 = e_unknown_elems(GroupFields, Bin1), + e_varint(FNum bsl 3 bor 4, Bin2); + {fixed32, FNum, V} -> + BinF = e_varint(FNum bsl 3 bor 5, Bin), + <>; + {fixed64, FNum, V} -> + BinF = e_varint(FNum bsl 3 bor 1, Bin), + <> + end, + e_unknown_elems(Rest, BinR); +e_unknown_elems([], Bin) -> Bin. + +-compile({nowarn_unused_function,e_varint/3}). +e_varint(N, Bin, _TrUserData) -> e_varint(N, Bin). + +-compile({nowarn_unused_function,e_varint/2}). +e_varint(N, Bin) when N =< 127 -> <>; +e_varint(N, Bin) -> + Bin2 = <>, + e_varint(N bsr 7, Bin2). + + +decode_msg(Bin, MsgName) when is_binary(Bin) -> decode_msg(Bin, MsgName, []). + +decode_msg(Bin, MsgName, Opts) when is_binary(Bin) -> + TrUserData = proplists:get_value(user_data, Opts), + decode_msg_1_catch(Bin, MsgName, TrUserData). + +-ifdef('OTP_RELEASE'). +decode_msg_1_catch(Bin, MsgName, TrUserData) -> + try decode_msg_2_doit(MsgName, Bin, TrUserData) + catch + error:{gpb_error,_}=Reason:StackTrace -> + erlang:raise(error, Reason, StackTrace); + Class:Reason:StackTrace -> error({gpb_error,{decoding_failure, {Bin, MsgName, {Class, Reason, StackTrace}}}}) + end. +-else. +decode_msg_1_catch(Bin, MsgName, TrUserData) -> + try decode_msg_2_doit(MsgName, Bin, TrUserData) + catch + error:{gpb_error,_}=Reason -> + erlang:raise(error, Reason, + erlang:get_stacktrace()); + Class:Reason -> + StackTrace = erlang:get_stacktrace(), + error({gpb_error,{decoding_failure, {Bin, MsgName, {Class, Reason, StackTrace}}}}) + end. +-endif. + +decode_msg_2_doit('Names', Bin, TrUserData) -> id(decode_msg_Names(Bin, TrUserData), TrUserData); +decode_msg_2_doit('Package', Bin, TrUserData) -> id(decode_msg_Package(Bin, TrUserData), TrUserData); +decode_msg_2_doit('Timestamp', Bin, TrUserData) -> id(decode_msg_Timestamp(Bin, TrUserData), TrUserData). + + + +decode_msg_Names(Bin, TrUserData) -> dfp_read_field_def_Names(Bin, 0, 0, 0, id([], TrUserData), id('$undef', TrUserData), TrUserData). + +dfp_read_field_def_Names(<<10, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> d_field_Names_packages(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData); +dfp_read_field_def_Names(<<18, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> d_field_Names_repository(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData); +dfp_read_field_def_Names(<<>>, 0, 0, _, R1, F@_2, TrUserData) -> + S1 = #{repository => F@_2}, + if R1 == '$undef' -> S1; + true -> S1#{packages => lists_reverse(R1, TrUserData)} + end; +dfp_read_field_def_Names(Other, Z1, Z2, F, F@_1, F@_2, TrUserData) -> dg_read_field_def_Names(Other, Z1, Z2, F, F@_1, F@_2, TrUserData). + +dg_read_field_def_Names(<<1:1, X:7, Rest/binary>>, N, Acc, F, F@_1, F@_2, TrUserData) when N < 32 - 7 -> dg_read_field_def_Names(Rest, N + 7, X bsl N + Acc, F, F@_1, F@_2, TrUserData); +dg_read_field_def_Names(<<0:1, X:7, Rest/binary>>, N, Acc, _, F@_1, F@_2, TrUserData) -> + Key = X bsl N + Acc, + case Key of + 10 -> d_field_Names_packages(Rest, 0, 0, 0, F@_1, F@_2, TrUserData); + 18 -> d_field_Names_repository(Rest, 0, 0, 0, F@_1, F@_2, TrUserData); + _ -> + case Key band 7 of + 0 -> skip_varint_Names(Rest, 0, 0, Key bsr 3, F@_1, F@_2, TrUserData); + 1 -> skip_64_Names(Rest, 0, 0, Key bsr 3, F@_1, F@_2, TrUserData); + 2 -> skip_length_delimited_Names(Rest, 0, 0, Key bsr 3, F@_1, F@_2, TrUserData); + 3 -> skip_group_Names(Rest, 0, 0, Key bsr 3, F@_1, F@_2, TrUserData); + 5 -> skip_32_Names(Rest, 0, 0, Key bsr 3, F@_1, F@_2, TrUserData) + end + end; +dg_read_field_def_Names(<<>>, 0, 0, _, R1, F@_2, TrUserData) -> + S1 = #{repository => F@_2}, + if R1 == '$undef' -> S1; + true -> S1#{packages => lists_reverse(R1, TrUserData)} + end. + +d_field_Names_packages(<<1:1, X:7, Rest/binary>>, N, Acc, F, F@_1, F@_2, TrUserData) when N < 57 -> d_field_Names_packages(Rest, N + 7, X bsl N + Acc, F, F@_1, F@_2, TrUserData); +d_field_Names_packages(<<0:1, X:7, Rest/binary>>, N, Acc, F, Prev, F@_2, TrUserData) -> + {NewFValue, RestF} = begin Len = X bsl N + Acc, <> = Rest, {id(decode_msg_Package(Bs, TrUserData), TrUserData), Rest2} end, + dfp_read_field_def_Names(RestF, 0, 0, F, cons(NewFValue, Prev, TrUserData), F@_2, TrUserData). + +d_field_Names_repository(<<1:1, X:7, Rest/binary>>, N, Acc, F, F@_1, F@_2, TrUserData) when N < 57 -> d_field_Names_repository(Rest, N + 7, X bsl N + Acc, F, F@_1, F@_2, TrUserData); +d_field_Names_repository(<<0:1, X:7, Rest/binary>>, N, Acc, F, F@_1, _, TrUserData) -> + {NewFValue, RestF} = begin Len = X bsl N + Acc, <> = Rest, Bytes2 = binary:copy(Bytes), {id(Bytes2, TrUserData), Rest2} end, + dfp_read_field_def_Names(RestF, 0, 0, F, F@_1, NewFValue, TrUserData). + +skip_varint_Names(<<1:1, _:7, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> skip_varint_Names(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData); +skip_varint_Names(<<0:1, _:7, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> dfp_read_field_def_Names(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData). + +skip_length_delimited_Names(<<1:1, X:7, Rest/binary>>, N, Acc, F, F@_1, F@_2, TrUserData) when N < 57 -> skip_length_delimited_Names(Rest, N + 7, X bsl N + Acc, F, F@_1, F@_2, TrUserData); +skip_length_delimited_Names(<<0:1, X:7, Rest/binary>>, N, Acc, F, F@_1, F@_2, TrUserData) -> + Length = X bsl N + Acc, + <<_:Length/binary, Rest2/binary>> = Rest, + dfp_read_field_def_Names(Rest2, 0, 0, F, F@_1, F@_2, TrUserData). + +skip_group_Names(Bin, _, Z2, FNum, F@_1, F@_2, TrUserData) -> + {_, Rest} = read_group(Bin, FNum), + dfp_read_field_def_Names(Rest, 0, Z2, FNum, F@_1, F@_2, TrUserData). + +skip_32_Names(<<_:32, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> dfp_read_field_def_Names(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData). + +skip_64_Names(<<_:64, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> dfp_read_field_def_Names(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData). + +decode_msg_Package(Bin, TrUserData) -> dfp_read_field_def_Package(Bin, 0, 0, 0, id('$undef', TrUserData), id('$undef', TrUserData), TrUserData). + +dfp_read_field_def_Package(<<10, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> d_field_Package_name(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData); +dfp_read_field_def_Package(<<26, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> d_field_Package_updated_at(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData); +dfp_read_field_def_Package(<<>>, 0, 0, _, F@_1, F@_2, _) -> + S1 = #{name => F@_1}, + if F@_2 == '$undef' -> S1; + true -> S1#{updated_at => F@_2} + end; +dfp_read_field_def_Package(Other, Z1, Z2, F, F@_1, F@_2, TrUserData) -> dg_read_field_def_Package(Other, Z1, Z2, F, F@_1, F@_2, TrUserData). + +dg_read_field_def_Package(<<1:1, X:7, Rest/binary>>, N, Acc, F, F@_1, F@_2, TrUserData) when N < 32 - 7 -> dg_read_field_def_Package(Rest, N + 7, X bsl N + Acc, F, F@_1, F@_2, TrUserData); +dg_read_field_def_Package(<<0:1, X:7, Rest/binary>>, N, Acc, _, F@_1, F@_2, TrUserData) -> + Key = X bsl N + Acc, + case Key of + 10 -> d_field_Package_name(Rest, 0, 0, 0, F@_1, F@_2, TrUserData); + 26 -> d_field_Package_updated_at(Rest, 0, 0, 0, F@_1, F@_2, TrUserData); + _ -> + case Key band 7 of + 0 -> skip_varint_Package(Rest, 0, 0, Key bsr 3, F@_1, F@_2, TrUserData); + 1 -> skip_64_Package(Rest, 0, 0, Key bsr 3, F@_1, F@_2, TrUserData); + 2 -> skip_length_delimited_Package(Rest, 0, 0, Key bsr 3, F@_1, F@_2, TrUserData); + 3 -> skip_group_Package(Rest, 0, 0, Key bsr 3, F@_1, F@_2, TrUserData); + 5 -> skip_32_Package(Rest, 0, 0, Key bsr 3, F@_1, F@_2, TrUserData) + end + end; +dg_read_field_def_Package(<<>>, 0, 0, _, F@_1, F@_2, _) -> + S1 = #{name => F@_1}, + if F@_2 == '$undef' -> S1; + true -> S1#{updated_at => F@_2} + end. + +d_field_Package_name(<<1:1, X:7, Rest/binary>>, N, Acc, F, F@_1, F@_2, TrUserData) when N < 57 -> d_field_Package_name(Rest, N + 7, X bsl N + Acc, F, F@_1, F@_2, TrUserData); +d_field_Package_name(<<0:1, X:7, Rest/binary>>, N, Acc, F, _, F@_2, TrUserData) -> + {NewFValue, RestF} = begin Len = X bsl N + Acc, <> = Rest, Bytes2 = binary:copy(Bytes), {id(Bytes2, TrUserData), Rest2} end, + dfp_read_field_def_Package(RestF, 0, 0, F, NewFValue, F@_2, TrUserData). + +d_field_Package_updated_at(<<1:1, X:7, Rest/binary>>, N, Acc, F, F@_1, F@_2, TrUserData) when N < 57 -> d_field_Package_updated_at(Rest, N + 7, X bsl N + Acc, F, F@_1, F@_2, TrUserData); +d_field_Package_updated_at(<<0:1, X:7, Rest/binary>>, N, Acc, F, F@_1, Prev, TrUserData) -> + {NewFValue, RestF} = begin Len = X bsl N + Acc, <> = Rest, {id(decode_msg_Timestamp(Bs, TrUserData), TrUserData), Rest2} end, + dfp_read_field_def_Package(RestF, + 0, + 0, + F, + F@_1, + if Prev == '$undef' -> NewFValue; + true -> merge_msg_Timestamp(Prev, NewFValue, TrUserData) + end, + TrUserData). + +skip_varint_Package(<<1:1, _:7, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> skip_varint_Package(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData); +skip_varint_Package(<<0:1, _:7, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> dfp_read_field_def_Package(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData). + +skip_length_delimited_Package(<<1:1, X:7, Rest/binary>>, N, Acc, F, F@_1, F@_2, TrUserData) when N < 57 -> skip_length_delimited_Package(Rest, N + 7, X bsl N + Acc, F, F@_1, F@_2, TrUserData); +skip_length_delimited_Package(<<0:1, X:7, Rest/binary>>, N, Acc, F, F@_1, F@_2, TrUserData) -> + Length = X bsl N + Acc, + <<_:Length/binary, Rest2/binary>> = Rest, + dfp_read_field_def_Package(Rest2, 0, 0, F, F@_1, F@_2, TrUserData). + +skip_group_Package(Bin, _, Z2, FNum, F@_1, F@_2, TrUserData) -> + {_, Rest} = read_group(Bin, FNum), + dfp_read_field_def_Package(Rest, 0, Z2, FNum, F@_1, F@_2, TrUserData). + +skip_32_Package(<<_:32, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> dfp_read_field_def_Package(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData). + +skip_64_Package(<<_:64, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> dfp_read_field_def_Package(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData). + +decode_msg_Timestamp(Bin, TrUserData) -> dfp_read_field_def_Timestamp(Bin, 0, 0, 0, id('$undef', TrUserData), id('$undef', TrUserData), TrUserData). + +dfp_read_field_def_Timestamp(<<8, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> d_field_Timestamp_seconds(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData); +dfp_read_field_def_Timestamp(<<16, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> d_field_Timestamp_nanos(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData); +dfp_read_field_def_Timestamp(<<>>, 0, 0, _, F@_1, F@_2, _) -> #{seconds => F@_1, nanos => F@_2}; +dfp_read_field_def_Timestamp(Other, Z1, Z2, F, F@_1, F@_2, TrUserData) -> dg_read_field_def_Timestamp(Other, Z1, Z2, F, F@_1, F@_2, TrUserData). + +dg_read_field_def_Timestamp(<<1:1, X:7, Rest/binary>>, N, Acc, F, F@_1, F@_2, TrUserData) when N < 32 - 7 -> dg_read_field_def_Timestamp(Rest, N + 7, X bsl N + Acc, F, F@_1, F@_2, TrUserData); +dg_read_field_def_Timestamp(<<0:1, X:7, Rest/binary>>, N, Acc, _, F@_1, F@_2, TrUserData) -> + Key = X bsl N + Acc, + case Key of + 8 -> d_field_Timestamp_seconds(Rest, 0, 0, 0, F@_1, F@_2, TrUserData); + 16 -> d_field_Timestamp_nanos(Rest, 0, 0, 0, F@_1, F@_2, TrUserData); + _ -> + case Key band 7 of + 0 -> skip_varint_Timestamp(Rest, 0, 0, Key bsr 3, F@_1, F@_2, TrUserData); + 1 -> skip_64_Timestamp(Rest, 0, 0, Key bsr 3, F@_1, F@_2, TrUserData); + 2 -> skip_length_delimited_Timestamp(Rest, 0, 0, Key bsr 3, F@_1, F@_2, TrUserData); + 3 -> skip_group_Timestamp(Rest, 0, 0, Key bsr 3, F@_1, F@_2, TrUserData); + 5 -> skip_32_Timestamp(Rest, 0, 0, Key bsr 3, F@_1, F@_2, TrUserData) + end + end; +dg_read_field_def_Timestamp(<<>>, 0, 0, _, F@_1, F@_2, _) -> #{seconds => F@_1, nanos => F@_2}. + +d_field_Timestamp_seconds(<<1:1, X:7, Rest/binary>>, N, Acc, F, F@_1, F@_2, TrUserData) when N < 57 -> d_field_Timestamp_seconds(Rest, N + 7, X bsl N + Acc, F, F@_1, F@_2, TrUserData); +d_field_Timestamp_seconds(<<0:1, X:7, Rest/binary>>, N, Acc, F, _, F@_2, TrUserData) -> + {NewFValue, RestF} = {begin <> = <<(X bsl N + Acc):64/unsigned-native>>, id(Res, TrUserData) end, Rest}, + dfp_read_field_def_Timestamp(RestF, 0, 0, F, NewFValue, F@_2, TrUserData). + +d_field_Timestamp_nanos(<<1:1, X:7, Rest/binary>>, N, Acc, F, F@_1, F@_2, TrUserData) when N < 57 -> d_field_Timestamp_nanos(Rest, N + 7, X bsl N + Acc, F, F@_1, F@_2, TrUserData); +d_field_Timestamp_nanos(<<0:1, X:7, Rest/binary>>, N, Acc, F, F@_1, _, TrUserData) -> + {NewFValue, RestF} = {begin <> = <<(X bsl N + Acc):32/unsigned-native>>, id(Res, TrUserData) end, Rest}, + dfp_read_field_def_Timestamp(RestF, 0, 0, F, F@_1, NewFValue, TrUserData). + +skip_varint_Timestamp(<<1:1, _:7, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> skip_varint_Timestamp(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData); +skip_varint_Timestamp(<<0:1, _:7, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> dfp_read_field_def_Timestamp(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData). + +skip_length_delimited_Timestamp(<<1:1, X:7, Rest/binary>>, N, Acc, F, F@_1, F@_2, TrUserData) when N < 57 -> skip_length_delimited_Timestamp(Rest, N + 7, X bsl N + Acc, F, F@_1, F@_2, TrUserData); +skip_length_delimited_Timestamp(<<0:1, X:7, Rest/binary>>, N, Acc, F, F@_1, F@_2, TrUserData) -> + Length = X bsl N + Acc, + <<_:Length/binary, Rest2/binary>> = Rest, + dfp_read_field_def_Timestamp(Rest2, 0, 0, F, F@_1, F@_2, TrUserData). + +skip_group_Timestamp(Bin, _, Z2, FNum, F@_1, F@_2, TrUserData) -> + {_, Rest} = read_group(Bin, FNum), + dfp_read_field_def_Timestamp(Rest, 0, Z2, FNum, F@_1, F@_2, TrUserData). + +skip_32_Timestamp(<<_:32, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> dfp_read_field_def_Timestamp(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData). + +skip_64_Timestamp(<<_:64, Rest/binary>>, Z1, Z2, F, F@_1, F@_2, TrUserData) -> dfp_read_field_def_Timestamp(Rest, Z1, Z2, F, F@_1, F@_2, TrUserData). + +read_group(Bin, FieldNum) -> + {NumBytes, EndTagLen} = read_gr_b(Bin, 0, 0, 0, 0, FieldNum), + <> = Bin, + {Group, Rest}. + +%% Like skipping over fields, but record the total length, +%% Each field is <(FieldNum bsl 3) bor FieldType> ++ +%% Record the length because varints may be non-optimally encoded. +%% +%% Groups can be nested, but assume the same FieldNum cannot be nested +%% because group field numbers are shared with the rest of the fields +%% numbers. Thus we can search just for an group-end with the same +%% field number. +%% +%% (The only time the same group field number could occur would +%% be in a nested sub message, but then it would be inside a +%% length-delimited entry, which we skip-read by length.) +read_gr_b(<<1:1, X:7, Tl/binary>>, N, Acc, NumBytes, TagLen, FieldNum) + when N < (32-7) -> + read_gr_b(Tl, N+7, X bsl N + Acc, NumBytes, TagLen+1, FieldNum); +read_gr_b(<<0:1, X:7, Tl/binary>>, N, Acc, NumBytes, TagLen, + FieldNum) -> + Key = X bsl N + Acc, + TagLen1 = TagLen + 1, + case {Key bsr 3, Key band 7} of + {FieldNum, 4} -> % 4 = group_end + {NumBytes, TagLen1}; + {_, 0} -> % 0 = varint + read_gr_vi(Tl, 0, NumBytes + TagLen1, FieldNum); + {_, 1} -> % 1 = bits64 + <<_:64, Tl2/binary>> = Tl, + read_gr_b(Tl2, 0, 0, NumBytes + TagLen1 + 8, 0, FieldNum); + {_, 2} -> % 2 = length_delimited + read_gr_ld(Tl, 0, 0, NumBytes + TagLen1, FieldNum); + {_, 3} -> % 3 = group_start + read_gr_b(Tl, 0, 0, NumBytes + TagLen1, 0, FieldNum); + {_, 4} -> % 4 = group_end + read_gr_b(Tl, 0, 0, NumBytes + TagLen1, 0, FieldNum); + {_, 5} -> % 5 = bits32 + <<_:32, Tl2/binary>> = Tl, + read_gr_b(Tl2, 0, 0, NumBytes + TagLen1 + 4, 0, FieldNum) + end. + +read_gr_vi(<<1:1, _:7, Tl/binary>>, N, NumBytes, FieldNum) + when N < (64-7) -> + read_gr_vi(Tl, N+7, NumBytes+1, FieldNum); +read_gr_vi(<<0:1, _:7, Tl/binary>>, _, NumBytes, FieldNum) -> + read_gr_b(Tl, 0, 0, NumBytes+1, 0, FieldNum). + +read_gr_ld(<<1:1, X:7, Tl/binary>>, N, Acc, NumBytes, FieldNum) + when N < (64-7) -> + read_gr_ld(Tl, N+7, X bsl N + Acc, NumBytes+1, FieldNum); +read_gr_ld(<<0:1, X:7, Tl/binary>>, N, Acc, NumBytes, FieldNum) -> + Len = X bsl N + Acc, + NumBytes1 = NumBytes + 1, + <<_:Len/binary, Tl2/binary>> = Tl, + read_gr_b(Tl2, 0, 0, NumBytes1 + Len, 0, FieldNum). + +merge_msgs(Prev, New, MsgName) when is_atom(MsgName) -> merge_msgs(Prev, New, MsgName, []). + +merge_msgs(Prev, New, MsgName, Opts) -> + TrUserData = proplists:get_value(user_data, Opts), + case MsgName of + 'Names' -> merge_msg_Names(Prev, New, TrUserData); + 'Package' -> merge_msg_Package(Prev, New, TrUserData); + 'Timestamp' -> merge_msg_Timestamp(Prev, New, TrUserData) + end. + +-compile({nowarn_unused_function,merge_msg_Names/3}). +merge_msg_Names(#{} = PMsg, #{repository := NFrepository} = NMsg, TrUserData) -> + S1 = #{repository => NFrepository}, + case {PMsg, NMsg} of + {#{packages := PFpackages}, #{packages := NFpackages}} -> S1#{packages => 'erlang_++'(PFpackages, NFpackages, TrUserData)}; + {_, #{packages := NFpackages}} -> S1#{packages => NFpackages}; + {#{packages := PFpackages}, _} -> S1#{packages => PFpackages}; + {_, _} -> S1 + end. + +-compile({nowarn_unused_function,merge_msg_Package/3}). +merge_msg_Package(#{} = PMsg, #{name := NFname} = NMsg, TrUserData) -> + S1 = #{name => NFname}, + case {PMsg, NMsg} of + {#{updated_at := PFupdated_at}, #{updated_at := NFupdated_at}} -> S1#{updated_at => merge_msg_Timestamp(PFupdated_at, NFupdated_at, TrUserData)}; + {_, #{updated_at := NFupdated_at}} -> S1#{updated_at => NFupdated_at}; + {#{updated_at := PFupdated_at}, _} -> S1#{updated_at => PFupdated_at}; + {_, _} -> S1 + end. + +-compile({nowarn_unused_function,merge_msg_Timestamp/3}). +merge_msg_Timestamp(#{}, #{seconds := NFseconds, nanos := NFnanos}, _) -> #{seconds => NFseconds, nanos => NFnanos}. + + +verify_msg(Msg, MsgName) when is_atom(MsgName) -> verify_msg(Msg, MsgName, []). + +verify_msg(Msg, MsgName, Opts) -> + TrUserData = proplists:get_value(user_data, Opts), + case MsgName of + 'Names' -> v_msg_Names(Msg, [MsgName], TrUserData); + 'Package' -> v_msg_Package(Msg, [MsgName], TrUserData); + 'Timestamp' -> v_msg_Timestamp(Msg, [MsgName], TrUserData); + _ -> mk_type_error(not_a_known_message, Msg, []) + end. + + +-compile({nowarn_unused_function,v_msg_Names/3}). +-dialyzer({nowarn_function,v_msg_Names/3}). +v_msg_Names(#{repository := F2} = M, Path, TrUserData) -> + case M of + #{packages := F1} -> + if is_list(F1) -> + _ = [v_submsg_Package(Elem, [packages | Path], TrUserData) || Elem <- F1], + ok; + true -> mk_type_error({invalid_list_of, {msg, 'Package'}}, F1, [packages | Path]) + end; + _ -> ok + end, + v_type_string(F2, [repository | Path], TrUserData), + lists:foreach(fun (packages) -> ok; + (repository) -> ok; + (OtherKey) -> mk_type_error({extraneous_key, OtherKey}, M, Path) + end, + maps:keys(M)), + ok; +v_msg_Names(M, Path, _TrUserData) when is_map(M) -> mk_type_error({missing_fields, [repository] -- maps:keys(M), 'Names'}, M, Path); +v_msg_Names(X, Path, _TrUserData) -> mk_type_error({expected_msg, 'Names'}, X, Path). + +-compile({nowarn_unused_function,v_submsg_Package/3}). +-dialyzer({nowarn_function,v_submsg_Package/3}). +v_submsg_Package(Msg, Path, TrUserData) -> v_msg_Package(Msg, Path, TrUserData). + +-compile({nowarn_unused_function,v_msg_Package/3}). +-dialyzer({nowarn_function,v_msg_Package/3}). +v_msg_Package(#{name := F1} = M, Path, TrUserData) -> + v_type_string(F1, [name | Path], TrUserData), + case M of + #{updated_at := F2} -> v_submsg_Timestamp(F2, [updated_at | Path], TrUserData); + _ -> ok + end, + lists:foreach(fun (name) -> ok; + (updated_at) -> ok; + (OtherKey) -> mk_type_error({extraneous_key, OtherKey}, M, Path) + end, + maps:keys(M)), + ok; +v_msg_Package(M, Path, _TrUserData) when is_map(M) -> mk_type_error({missing_fields, [name] -- maps:keys(M), 'Package'}, M, Path); +v_msg_Package(X, Path, _TrUserData) -> mk_type_error({expected_msg, 'Package'}, X, Path). + +-compile({nowarn_unused_function,v_submsg_Timestamp/3}). +-dialyzer({nowarn_function,v_submsg_Timestamp/3}). +v_submsg_Timestamp(Msg, Path, TrUserData) -> v_msg_Timestamp(Msg, Path, TrUserData). + +-compile({nowarn_unused_function,v_msg_Timestamp/3}). +-dialyzer({nowarn_function,v_msg_Timestamp/3}). +v_msg_Timestamp(#{seconds := F1, nanos := F2} = M, Path, TrUserData) -> + v_type_int64(F1, [seconds | Path], TrUserData), + v_type_int32(F2, [nanos | Path], TrUserData), + lists:foreach(fun (seconds) -> ok; + (nanos) -> ok; + (OtherKey) -> mk_type_error({extraneous_key, OtherKey}, M, Path) + end, + maps:keys(M)), + ok; +v_msg_Timestamp(M, Path, _TrUserData) when is_map(M) -> mk_type_error({missing_fields, [seconds, nanos] -- maps:keys(M), 'Timestamp'}, M, Path); +v_msg_Timestamp(X, Path, _TrUserData) -> mk_type_error({expected_msg, 'Timestamp'}, X, Path). + +-compile({nowarn_unused_function,v_type_int32/3}). +-dialyzer({nowarn_function,v_type_int32/3}). +v_type_int32(N, _Path, _TrUserData) when is_integer(N), -2147483648 =< N, N =< 2147483647 -> ok; +v_type_int32(N, Path, _TrUserData) when is_integer(N) -> mk_type_error({value_out_of_range, int32, signed, 32}, N, Path); +v_type_int32(X, Path, _TrUserData) -> mk_type_error({bad_integer, int32, signed, 32}, X, Path). + +-compile({nowarn_unused_function,v_type_int64/3}). +-dialyzer({nowarn_function,v_type_int64/3}). +v_type_int64(N, _Path, _TrUserData) when is_integer(N), -9223372036854775808 =< N, N =< 9223372036854775807 -> ok; +v_type_int64(N, Path, _TrUserData) when is_integer(N) -> mk_type_error({value_out_of_range, int64, signed, 64}, N, Path); +v_type_int64(X, Path, _TrUserData) -> mk_type_error({bad_integer, int64, signed, 64}, X, Path). + +-compile({nowarn_unused_function,v_type_string/3}). +-dialyzer({nowarn_function,v_type_string/3}). +v_type_string(S, Path, _TrUserData) when is_list(S); is_binary(S) -> + try unicode:characters_to_binary(S) of + B when is_binary(B) -> ok; + {error, _, _} -> mk_type_error(bad_unicode_string, S, Path) + catch + error:badarg -> mk_type_error(bad_unicode_string, S, Path) + end; +v_type_string(X, Path, _TrUserData) -> mk_type_error(bad_unicode_string, X, Path). + +-compile({nowarn_unused_function,mk_type_error/3}). +-spec mk_type_error(_, _, list()) -> no_return(). +mk_type_error(Error, ValueSeen, Path) -> + Path2 = prettify_path(Path), + erlang:error({gpb_type_error, {Error, [{value, ValueSeen}, {path, Path2}]}}). + + +-compile({nowarn_unused_function,prettify_path/1}). +-dialyzer({nowarn_function,prettify_path/1}). +prettify_path([]) -> top_level; +prettify_path(PathR) -> lists:append(lists:join(".", lists:map(fun atom_to_list/1, lists:reverse(PathR)))). + + +-compile({nowarn_unused_function,id/2}). +-compile({inline,id/2}). +id(X, _TrUserData) -> X. + +-compile({nowarn_unused_function,v_ok/3}). +-compile({inline,v_ok/3}). +v_ok(_Value, _Path, _TrUserData) -> ok. + +-compile({nowarn_unused_function,m_overwrite/3}). +-compile({inline,m_overwrite/3}). +m_overwrite(_Prev, New, _TrUserData) -> New. + +-compile({nowarn_unused_function,cons/3}). +-compile({inline,cons/3}). +cons(Elem, Acc, _TrUserData) -> [Elem | Acc]. + +-compile({nowarn_unused_function,lists_reverse/2}). +-compile({inline,lists_reverse/2}). +'lists_reverse'(L, _TrUserData) -> lists:reverse(L). +-compile({nowarn_unused_function,'erlang_++'/3}). +-compile({inline,'erlang_++'/3}). +'erlang_++'(A, B, _TrUserData) -> A ++ B. + + +get_msg_defs() -> + [{{msg, 'Names'}, [#{name => packages, fnum => 1, rnum => 2, type => {msg, 'Package'}, occurrence => repeated, opts => []}, #{name => repository, fnum => 2, rnum => 3, type => string, occurrence => required, opts => []}]}, + {{msg, 'Package'}, [#{name => name, fnum => 1, rnum => 2, type => string, occurrence => required, opts => []}, #{name => updated_at, fnum => 3, rnum => 3, type => {msg, 'Timestamp'}, occurrence => optional, opts => []}]}, + {{msg, 'Timestamp'}, [#{name => seconds, fnum => 1, rnum => 2, type => int64, occurrence => required, opts => []}, #{name => nanos, fnum => 2, rnum => 3, type => int32, occurrence => required, opts => []}]}]. + + +get_msg_names() -> ['Names', 'Package', 'Timestamp']. + + +get_group_names() -> []. + + +get_msg_or_group_names() -> ['Names', 'Package', 'Timestamp']. + + +get_enum_names() -> []. + + +fetch_msg_def(MsgName) -> + case find_msg_def(MsgName) of + Fs when is_list(Fs) -> Fs; + error -> erlang:error({no_such_msg, MsgName}) + end. + + +-spec fetch_enum_def(_) -> no_return(). +fetch_enum_def(EnumName) -> erlang:error({no_such_enum, EnumName}). + + +find_msg_def('Names') -> [#{name => packages, fnum => 1, rnum => 2, type => {msg, 'Package'}, occurrence => repeated, opts => []}, #{name => repository, fnum => 2, rnum => 3, type => string, occurrence => required, opts => []}]; +find_msg_def('Package') -> [#{name => name, fnum => 1, rnum => 2, type => string, occurrence => required, opts => []}, #{name => updated_at, fnum => 3, rnum => 3, type => {msg, 'Timestamp'}, occurrence => optional, opts => []}]; +find_msg_def('Timestamp') -> [#{name => seconds, fnum => 1, rnum => 2, type => int64, occurrence => required, opts => []}, #{name => nanos, fnum => 2, rnum => 3, type => int32, occurrence => required, opts => []}]; +find_msg_def(_) -> error. + + +find_enum_def(_) -> error. + + +-spec enum_symbol_by_value(_, _) -> no_return(). +enum_symbol_by_value(E, V) -> erlang:error({no_enum_defs, E, V}). + + +-spec enum_value_by_symbol(_, _) -> no_return(). +enum_value_by_symbol(E, V) -> erlang:error({no_enum_defs, E, V}). + + + +get_service_names() -> []. + + +get_service_def(_) -> error. + + +get_rpc_names(_) -> error. + + +find_rpc_def(_, _) -> error. + + + +-spec fetch_rpc_def(_, _) -> no_return(). +fetch_rpc_def(ServiceName, RpcName) -> erlang:error({no_such_rpc, ServiceName, RpcName}). + + +%% Convert a a fully qualified (ie with package name) service name +%% as a binary to a service name as an atom. +-spec fqbin_to_service_name(_) -> no_return(). +fqbin_to_service_name(X) -> error({gpb_error, {badservice, X}}). + + +%% Convert a service name as an atom to a fully qualified +%% (ie with package name) name as a binary. +-spec service_name_to_fqbin(_) -> no_return(). +service_name_to_fqbin(X) -> error({gpb_error, {badservice, X}}). + + +%% Convert a a fully qualified (ie with package name) service name +%% and an rpc name, both as binaries to a service name and an rpc +%% name, as atoms. +-spec fqbins_to_service_and_rpc_name(_, _) -> no_return(). +fqbins_to_service_and_rpc_name(S, R) -> error({gpb_error, {badservice_or_rpc, {S, R}}}). + + +%% Convert a service name and an rpc name, both as atoms, +%% to a fully qualified (ie with package name) service name and +%% an rpc name as binaries. +-spec service_and_rpc_name_to_fqbins(_, _) -> no_return(). +service_and_rpc_name_to_fqbins(S, R) -> error({gpb_error, {badservice_or_rpc, {S, R}}}). + + +fqbin_to_msg_name(<<"Names">>) -> 'Names'; +fqbin_to_msg_name(<<"Package">>) -> 'Package'; +fqbin_to_msg_name(<<"Timestamp">>) -> 'Timestamp'; +fqbin_to_msg_name(E) -> error({gpb_error, {badmsg, E}}). + + +msg_name_to_fqbin('Names') -> <<"Names">>; +msg_name_to_fqbin('Package') -> <<"Package">>; +msg_name_to_fqbin('Timestamp') -> <<"Timestamp">>; +msg_name_to_fqbin(E) -> error({gpb_error, {badmsg, E}}). + + +-spec fqbin_to_enum_name(_) -> no_return(). +fqbin_to_enum_name(E) -> error({gpb_error, {badenum, E}}). + + +-spec enum_name_to_fqbin(_) -> no_return(). +enum_name_to_fqbin(E) -> error({gpb_error, {badenum, E}}). + + +get_package_name() -> undefined. + + +%% Whether or not the message names +%% are prepended with package name or not. +uses_packages() -> false. + + +source_basename() -> "hex_pb_names.proto". + + +%% Retrieve all proto file names, also imported ones. +%% The order is top-down. The first element is always the main +%% source file. The files are returned with extension, +%% see get_all_proto_names/0 for a version that returns +%% the basenames sans extension +get_all_source_basenames() -> ["hex_pb_names.proto"]. + + +%% Retrieve all proto file names, also imported ones. +%% The order is top-down. The first element is always the main +%% source file. The files are returned sans .proto extension, +%% to make it easier to use them with the various get_xyz_containment +%% functions. +get_all_proto_names() -> ["hex_pb_names"]. + + +get_msg_containment("hex_pb_names") -> ['Names', 'Package', 'Timestamp']; +get_msg_containment(P) -> error({gpb_error, {badproto, P}}). + + +get_pkg_containment("hex_pb_names") -> undefined; +get_pkg_containment(P) -> error({gpb_error, {badproto, P}}). + + +get_service_containment("hex_pb_names") -> []; +get_service_containment(P) -> error({gpb_error, {badproto, P}}). + + +get_rpc_containment("hex_pb_names") -> []; +get_rpc_containment(P) -> error({gpb_error, {badproto, P}}). + + +get_enum_containment("hex_pb_names") -> []; +get_enum_containment(P) -> error({gpb_error, {badproto, P}}). + + +get_proto_by_msg_name_as_fqbin(<<"Timestamp">>) -> "hex_pb_names"; +get_proto_by_msg_name_as_fqbin(<<"Names">>) -> "hex_pb_names"; +get_proto_by_msg_name_as_fqbin(<<"Package">>) -> "hex_pb_names"; +get_proto_by_msg_name_as_fqbin(E) -> error({gpb_error, {badmsg, E}}). + + +-spec get_proto_by_service_name_as_fqbin(_) -> no_return(). +get_proto_by_service_name_as_fqbin(E) -> error({gpb_error, {badservice, E}}). + + +-spec get_proto_by_enum_name_as_fqbin(_) -> no_return(). +get_proto_by_enum_name_as_fqbin(E) -> error({gpb_error, {badenum, E}}). + + +-spec get_protos_by_pkg_name_as_fqbin(_) -> no_return(). +get_protos_by_pkg_name_as_fqbin(E) -> error({gpb_error, {badpkg, E}}). + + + +gpb_version_as_string() -> + "4.21.1". + +gpb_version_as_list() -> + [4,21,1]. + +gpb_version_source() -> + "file". diff --git a/deps/eini/_build/default/plugins/hex_core/src/hex_repo.erl b/deps/eini/_build/default/plugins/hex_core/src/hex_repo.erl new file mode 100644 index 0000000000000000000000000000000000000000..08728b731f2c63f1e2225561e3081be753bdf5e8 --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/src/hex_repo.erl @@ -0,0 +1,260 @@ +%% @doc +%% Repo API. +-module(hex_repo). +-export([ + get_names/1, + get_versions/1, + get_package/2, + get_tarball/3, + get_docs/3, + get_public_key/1, + get_hex_installs/1 +]). + +%%==================================================================== +%% API functions +%%==================================================================== + +%% @doc +%% Gets names resource from the repository. +%% +%% Examples: +%% +%% ``` +%% > hex_repo:get_names(hex_core:default_config()). +%% {ok,{200, ..., +%% #{packages => [ +%% #{name => <<"package1">>}, +%% #{name => <<"package2">>}, +%% ...]}}} +%% ''' +%% @end +get_names(Config) when is_map(Config) -> + Decoder = fun(Data) -> + hex_registry:decode_names(Data, verify_repo(Config)) + end, + get_protobuf(Config, <<"names">>, Decoder). + +%% @doc +%% Gets versions resource from the repository. +%% +%% Examples: +%% +%% ``` +%% > hex_repo:get_versions(Config). +%% {ok, {200, ..., +%% #{packages => [ +%% #{name => <<"package1">>, retired => [], +%% versions => [<<"1.0.0">>]}, +%% #{name => <<"package2">>, retired => [<<"0.5.0>>"], +%% versions => [<<"0.5.0">>, <<"1.0.0">>]}, +%% ...]}}} +%% ''' +%% @end +get_versions(Config) when is_map(Config) -> + Decoder = fun(Data) -> + hex_registry:decode_versions(Data, verify_repo(Config)) + end, + get_protobuf(Config, <<"versions">>, Decoder). + +%% @doc +%% Gets package resource from the repository. +%% +%% Examples: +%% +%% ``` +%% > hex_repo:get_package(hex_core:default_config(), <<"package1">>). +%% {ok, {200, ..., +%% #{name => <<"package1">>, +%% releases => [ +%% #{checksum => ..., version => <<"0.5.0">>, dependencies => []}, +%% #{checksum => ..., version => <<"1.0.0">>, dependencies => [ +%% #{package => <<"package2">>, optional => true, requirement => <<"~> 0.1">>} +%% ]}, +%% ]}}} +%% ''' +%% @end +get_package(Config, Name) when is_binary(Name) and is_map(Config) -> + Verify = maps:get(repo_verify_origin, Config, true), + Decoder = fun(Data) -> + case Verify of + true -> hex_registry:decode_package(Data, repo_name(Config), Name); + false -> hex_registry:decode_package(Data, no_verify, no_verify) + end + end, + get_protobuf(Config, <<"packages/", Name/binary>>, Decoder). + +%% @doc +%% Gets tarball from the repository. +%% +%% Examples: +%% +%% ``` +%% > {ok, {200, _, Tarball}} = hex_repo:get_tarball(hex_core:default_config(), <<"package1">>, <<"1.0.0">>), +%% > {ok, #{metadata := Metadata}} = hex_tarball:unpack(Tarball, memory). +%% ''' +%% @end +get_tarball(Config, Name, Version) -> + ReqHeaders = make_headers(Config), + + case get(Config, tarball_url(Config, Name, Version), ReqHeaders) of + {ok, {200, RespHeaders, Tarball}} -> + {ok, {200, RespHeaders, Tarball}}; + Other -> + Other + end. + +%% @doc +%% Gets docs tarball from the repository. +%% +%% Examples: +%% +%% ``` +%% > {ok, {200, _, Docs}} = hex_repo:get_docs(hex_core:default_config(), <<"package1">>, <<"1.0.0">>), +%% > hex_tarball:unpack_docs(Docs, memory) +%% {ok, [{"index.html", <<"">>}, ...]} +%% ''' +get_docs(Config, Name, Version) -> + ReqHeaders = make_headers(Config), + + case get(Config, docs_url(Config, Name, Version), ReqHeaders) of + {ok, {200, RespHeaders, Docs}} -> + {ok, {200, RespHeaders, Docs}}; + Other -> + Other + end. + +%% @doc +%% Gets the public key from the repository. +%% +%% Examples: +%% +%% ``` +%% > hex_repo:get_public_key(hex_core:default_config()) +%% {ok, {200, _, PublicKey}} +%% ''' +get_public_key(Config) -> + ReqHeaders = make_headers(Config), + URI = build_url(Config, <<"public_key">>), + + case get(Config, URI, ReqHeaders) of + {ok, {200, RespHeaders, PublicKey}} -> + {ok, {200, RespHeaders, PublicKey}}; + Other -> + Other + end. + +%% @doc +%% Gets Hex installation versions CSV from repository. +%% +%% Examples: +%% +%% ``` +%% > hex_repo:get_hex_installs(hex_core:default_config()). +%% {ok, {200, ..., <<"1.0.0,abc123,1.13.0\n1.1.0,def456,1.14.0\n...">>}} +%% ''' +%% @end +get_hex_installs(Config) -> + ReqHeaders = make_headers(Config), + URI = build_url(Config, <<"installs/hex-1.x.csv">>), + + case get(Config, URI, ReqHeaders) of + {ok, {200, RespHeaders, CSV}} -> + {ok, {200, RespHeaders, CSV}}; + Other -> + Other + end. + +%%==================================================================== +%% Internal functions +%%==================================================================== + +%% @private +get(Config, URI, Headers) -> + hex_http:request(Config, get, URI, Headers, undefined). + +%% @private +get_protobuf(Config, Path, Decoder) -> + PublicKey = maps:get(repo_public_key, Config), + ReqHeaders = make_headers(Config), + + case get(Config, build_url(Config, Path), ReqHeaders) of + {ok, {200, RespHeaders, Compressed}} -> + Signed = zlib:gunzip(Compressed), + case decode(Signed, PublicKey, Decoder, Config) of + {ok, Decoded} -> + {ok, {200, RespHeaders, Decoded}}; + {error, _} = Error -> + Error + end; + Other -> + Other + end. + +%% @private +decode(Signed, PublicKey, Decoder, Config) -> + Verify = maps:get(repo_verify, Config, true), + + case Verify of + true -> + case hex_registry:decode_and_verify_signed(Signed, PublicKey) of + {ok, Payload} -> + Decoder(Payload); + Other -> + Other + end; + false -> + #{payload := Payload} = hex_registry:decode_signed(Signed), + Decoder(Payload) + end. + +%% @private +verify_repo(Config) -> + case maps:get(repo_verify_origin, Config, true) of + true -> repo_name(Config); + false -> no_verify + end. + +%% @private +repo_name(#{repo_organization := Name}) when is_binary(Name) -> Name; +repo_name(#{repo_name := Name}) when is_binary(Name) -> Name. + +%% @private +tarball_url(Config, Name, Version) -> + Filename = tarball_filename(Name, Version), + build_url(Config, <<"tarballs/", Filename/binary>>). + +%% @private +docs_url(Config, Name, Version) -> + Filename = docs_filename(Name, Version), + build_url(Config, <<"docs/", Filename/binary>>). + +%% @private +build_url(#{repo_url := URI, repo_organization := Org}, Path) when is_binary(Org) -> + <>; +build_url(#{repo_url := URI, repo_organization := undefined}, Path) -> + <>; +build_url(Config, Path) -> + build_url(Config#{repo_organization => undefined}, Path). + +%% @private +tarball_filename(Name, Version) -> + <>. + +%% @private +docs_filename(Name, Version) -> + <>. + +%% @private +make_headers(Config) -> + maps:fold(fun set_header/3, #{}, Config). + +%% @private +set_header(http_etag, ETag, Headers) when is_binary(ETag) -> + maps:put(<<"if-none-match">>, ETag, Headers); +set_header(repo_key, Token, Headers) when is_binary(Token) -> + maps:put(<<"authorization">>, Token, Headers); +set_header(api_otp, OTP, Headers) when is_binary(OTP) -> + maps:put(<<"x-hex-otp">>, OTP, Headers); +set_header(_, _, Headers) -> + Headers. diff --git a/deps/eini/_build/default/plugins/hex_core/src/safe_erl_term.erl b/deps/eini/_build/default/plugins/hex_core/src/safe_erl_term.erl new file mode 100644 index 0000000000000000000000000000000000000000..ed237d1d22932b5e7c3545b630f130fb38024f76 --- /dev/null +++ b/deps/eini/_build/default/plugins/hex_core/src/safe_erl_term.erl @@ -0,0 +1,758 @@ +-file("/home/saru/.local/share/mise/installs/erlang/28.4.1/lib/parsetools-2.7.1/include/leexinc.hrl", 0). +%% +%% %CopyrightBegin% +%% +%% SPDX-License-Identifier: BSD-2-Clause +%% +%% Copyright (c) 2008,2009 Robert Virding. All rights reserved. +%% Copyright Ericsson AB 2009-2025. All Rights Reserved. +%% +%% Redistribution and use in source and binary forms, with or without +%% modification, are permitted provided that the following conditions +%% are met: +%% +%% 1. Redistributions of source code must retain the above copyright +%% notice, this list of conditions and the following disclaimer. +%% 2. Redistributions in binary form must reproduce the above copyright +%% notice, this list of conditions and the following disclaimer in the +%% documentation and/or other materials provided with the distribution. +%% +%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +%% "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +%% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +%% FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +%% COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +%% INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +%% BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +%% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +%% CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +%% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +%% ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +%% POSSIBILITY OF SUCH DAMAGE. +%% +%% %CopyrightEnd% +%% + +%% The source of this file is part of leex distribution, as such it +%% has the same Copyright as the other files in the leex +%% distribution. However, the resultant scanner generated by leex is the +%% property of the creator of the scanner and is not covered by that +%% Copyright. + +-module(safe_erl_term). + +-export([string/1,string/2,token/2,token/3,tokens/2,tokens/3]). +-export([format_error/1]). + +%% User code. This is placed here to allow extra attributes. +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 24). + +-export([terms/1]). + +terms(Tokens) -> + terms(Tokens, []). + +terms([{dot, _} = H], Buffer) -> + [buffer_to_term([H|Buffer])]; +terms([{dot, _} = H|T], Buffer) -> + [buffer_to_term([H|Buffer])|terms(T, [])]; +terms([H|T], Buffer) -> + terms(T, [H|Buffer]). + +buffer_to_term(Buffer) -> + {ok, Term} = erl_parse:parse_term(lists:reverse(Buffer)), + Term. + +unquote(TokenChars, TokenLen) -> + lists:sublist(TokenChars, 2, TokenLen - 2). + +tokenize_atom(TokenChars, TokenLine) -> + try list_to_existing_atom(TokenChars) of + Atom -> {token, {atom, TokenLine, Atom}} + catch + error:badarg -> {error, "illegal atom " ++ TokenChars} + end. + +escape([$\\|Cs]) -> + do_escape(Cs); +escape([C|Cs]) -> + [C|escape(Cs)]; +escape([]) -> []. + +do_escape([O1,O2,O3|S]) when + O1 >= $0, O1 =< $7, O2 >= $0, O2 =< $7, O3 >= $0, O3 =< $7 -> + [(O1*8 + O2)*8 + O3 - 73*$0|escape(S)]; +do_escape([$^,C|Cs]) -> + [C band 31|escape(Cs)]; +do_escape([C|Cs]) when C >= $\000, C =< $\s -> + escape(Cs); +do_escape([C|Cs]) -> + [escape_char(C)|escape(Cs)]. + +escape_char($n) -> $\n; %\n = LF +escape_char($r) -> $\r; %\r = CR +escape_char($t) -> $\t; %\t = TAB +escape_char($v) -> $\v; %\v = VT +escape_char($b) -> $\b; %\b = BS +escape_char($f) -> $\f; %\f = FF +escape_char($e) -> $\e; %\e = ESC +escape_char($s) -> $\s; %\s = SPC +escape_char($d) -> $\d; %\d = DEL +escape_char(C) -> C. + +-file("/home/saru/.local/share/mise/installs/erlang/28.4.1/lib/parsetools-2.7.1/include/leexinc.hrl", 47). + +format_error({illegal,S}) -> ["illegal characters ",io_lib:write_string(S)]; +format_error({user,S}) -> S. + +%% string(InChars) -> +%% string(InChars, Loc) -> +%% {ok,Tokens,EndLoc} | {error,ErrorInfo,EndLoc}. +%% Loc is the starting location of the token, while EndLoc is the first not scanned +%% location. Location is either Line or {Line,Column}, depending on the "error_location" option. + +string(Ics) -> + string(Ics,1). +string(Ics,L0) -> + string(Ics, L0, 1, Ics, []). +string(Ics, L0, C0, Tcs, Ts) -> + case do_string(Ics, L0, C0, Tcs, Ts) of + {ok, T, {L,_}} -> {ok, T, L}; + {error, {{EL,_},M,D}, {L,_}} -> + EI = {EL,M,D}, + {error, EI, L} + end. + +do_string([], L, C, [], Ts) -> % No partial tokens! + {ok,yyrev(Ts),{L,C}}; +do_string(Ics0, L0, C0, Tcs, Ts) -> + case yystate(yystate(), Ics0, L0, C0, 0, reject, 0) of + {A,Alen,Ics1,L1,_C1} -> % Accepting end state + C2 = adjust_col(Tcs, Alen, C0), + string_cont(Ics1, L1, C2, yyaction(A, Alen, Tcs, L0, C0), Ts); + {A,Alen,Ics1,L1,_C1,_S1} -> % Accepting transition state + C2 = adjust_col(Tcs, Alen, C0), + string_cont(Ics1, L1, C2, yyaction(A, Alen, Tcs, L0, C0), Ts); + {reject,_Alen,Tlen,_Ics1,_L1,_C1,_S1} -> % After a non-accepting state + {error,{{L0, C0} ,?MODULE,{illegal,yypre(Tcs, Tlen+1)}},{L0, C0}}; + {A,Alen,Tlen,_Ics1,L1, C1,_S1}-> + Tcs1 = yysuf(Tcs, Alen), + L2 = adjust_line(Tlen, Alen, Tcs1, L1), + C2 = adjust_col(Tcs, Alen, C1), + string_cont(Tcs1, L2, C2, yyaction(A, Alen, Tcs, L0,C0), Ts) + end. + +%% string_cont(RestChars, Line, Col, Token, Tokens) +%% Test for and remove the end token wrapper. Push back characters +%% are prepended to RestChars. + +-dialyzer({nowarn_function, string_cont/5}). + +string_cont(Rest, Line, Col, {token,T}, Ts) -> + do_string(Rest, Line, Col, Rest, [T|Ts]); +string_cont(Rest, Line, Col, {token,T,Push}, Ts) -> + NewRest = Push ++ Rest, + do_string(NewRest, Line, Col, NewRest, [T|Ts]); +string_cont(Rest, Line, Col, {end_token,T}, Ts) -> + do_string(Rest, Line, Col, Rest, [T|Ts]); +string_cont(Rest, Line, Col, {end_token,T,Push}, Ts) -> + NewRest = Push ++ Rest, + do_string(NewRest, Line, Col, NewRest, [T|Ts]); +string_cont(Rest, Line, Col, skip_token, Ts) -> + do_string(Rest, Line, Col, Rest, Ts); +string_cont(Rest, Line, Col, {skip_token,Push}, Ts) -> + NewRest = Push ++ Rest, + do_string(NewRest, Line, Col, NewRest, Ts); +string_cont(_Rest, Line, Col, {error,S}, _Ts) -> + {error,{{Line, Col},?MODULE,{user,S}},{Line,Col}}. + +%% token(Continuation, Chars) -> +%% token(Continuation, Chars, Loc) -> +%% {more,Continuation} | {done,ReturnVal,RestChars}. +%% Must be careful when re-entering to append the latest characters to the +%% after characters in an accept. The continuation is: +%% {token,State,CurrLine,CurrCol,TokenChars,TokenLen,TokenLine,TokenCol,AccAction,AccLen} + +token(Cont,Chars) -> + token(Cont,Chars,1). +token(Cont, Chars, Line) -> + case do_token(Cont,Chars,Line,1) of + {more, _} = C -> C; + {done, Ret0, R} -> + Ret1 = case Ret0 of + {ok, T, {L,_}} -> {ok, T, L}; + {eof, {L,_}} -> {eof, L}; + {error, {{EL,_},M,D},{L,_}} -> {error, {EL,M,D},L} + end, + {done, Ret1, R} + end. + +do_token([], Chars, Line, Col) -> + token(yystate(), Chars, Line, Col, Chars, 0, Line, Col, reject, 0); +do_token({token,State,Line,Col,Tcs,Tlen,Tline,Tcol,Action,Alen}, Chars, _, _) -> + token(State, Chars, Line, Col, Tcs ++ Chars, Tlen, Tline, Tcol, Action, Alen). + +%% token(State, InChars, Line, Col, TokenChars, TokenLen, TokenLine, TokenCol +%% AcceptAction, AcceptLen) -> +%% {more,Continuation} | {done,ReturnVal,RestChars}. +%% The argument order is chosen to be more efficient. + +token(S0, Ics0, L0, C0, Tcs, Tlen0, Tline, Tcol, A0, Alen0) -> + case yystate(S0, Ics0, L0, C0, Tlen0, A0, Alen0) of + %% Accepting end state, we have a token. + {A1,Alen1,Ics1,L1,C1} -> + C2 = adjust_col(Tcs, Alen1, C1), + token_cont(Ics1, L1, C2, yyaction(A1, Alen1, Tcs, Tline,Tcol)); + %% Accepting transition state, can take more chars. + {A1,Alen1,[],L1,C1,S1} -> % Need more chars to check + {more,{token,S1,L1,C1,Tcs,Alen1,Tline,Tcol,A1,Alen1}}; + {A1,Alen1,Ics1,L1,C1,_S1} -> % Take what we got + C2 = adjust_col(Tcs, Alen1, C1), + token_cont(Ics1, L1, C2, yyaction(A1, Alen1, Tcs, Tline,Tcol)); + %% After a non-accepting state, maybe reach accept state later. + {A1,Alen1,Tlen1,[],L1,C1,S1} -> % Need more chars to check + {more,{token,S1,L1,C1,Tcs,Tlen1,Tline,Tcol,A1,Alen1}}; + {reject,_Alen1,Tlen1,eof,L1,C1,_S1} -> % No token match + %% Check for partial token which is error. + Ret = if Tlen1 > 0 -> {error,{{Tline,Tcol},?MODULE, + %% Skip eof tail in Tcs. + {illegal,yypre(Tcs, Tlen1)}},{L1,C1}}; + true -> {eof,{L1,C1}} + end, + {done,Ret,eof}; + {reject,_Alen1,Tlen1,Ics1,_L1,_C1,_S1} -> % No token match + Error = {{Tline,Tcol},?MODULE,{illegal,yypre(Tcs, Tlen1+1)}}, + {done,{error,Error,{Tline,Tcol}},Ics1}; + {A1,Alen1,Tlen1,_Ics1,L1,_C1,_S1} -> % Use last accept match + Tcs1 = yysuf(Tcs, Alen1), + L2 = adjust_line(Tlen1, Alen1, Tcs1, L1), + C2 = C0 + Alen1, + token_cont(Tcs1, L2, C2, yyaction(A1, Alen1, Tcs, Tline, Tcol)) + end. + +%% token_cont(RestChars, Line, Col, Token) +%% If we have a token or error then return done, else if we have a +%% skip_token then continue. + +-dialyzer({nowarn_function, token_cont/4}). + +token_cont(Rest, Line, Col, {token,T}) -> + {done,{ok,T,{Line,Col}},Rest}; +token_cont(Rest, Line, Col, {token,T,Push}) -> + NewRest = Push ++ Rest, + {done,{ok,T,{Line,Col}},NewRest}; +token_cont(Rest, Line, Col, {end_token,T}) -> + {done,{ok,T,{Line,Col}},Rest}; +token_cont(Rest, Line, Col, {end_token,T,Push}) -> + NewRest = Push ++ Rest, + {done,{ok,T,{Line,Col}},NewRest}; +token_cont(Rest, Line, Col, skip_token) -> + token(yystate(), Rest, Line, Col, Rest, 0, Line, Col, reject, 0); +token_cont(Rest, Line, Col, {skip_token,Push}) -> + NewRest = Push ++ Rest, + token(yystate(), NewRest, Line, Col, NewRest, 0, Line, Col, reject, 0); +token_cont(Rest, Line, Col, {error,S}) -> + {done,{error,{{Line, Col},?MODULE,{user,S}},{Line, Col}},Rest}. + +%% tokens(Continuation, Chars) -> +%% tokens(Continuation, Chars, Loc) -> +%% {more,Continuation} | {done,ReturnVal,RestChars}. +%% Must be careful when re-entering to append the latest characters to the +%% after characters in an accept. The continuation is: +%% {tokens,State,CurrLine,CurrCol,TokenChars,TokenLen,TokenLine,TokenCur,Tokens,AccAction,AccLen} +%% {skip_tokens,State,CurrLine,CurrCol,TokenChars,TokenLen,TokenLine,TokenCur,Error,AccAction,AccLen} + +tokens(Cont,Chars) -> + tokens(Cont,Chars,1). +tokens(Cont, Chars, Line) -> + case do_tokens(Cont,Chars,Line,1) of + {more, _} = C -> C; + {done, Ret0, R} -> + Ret1 = case Ret0 of + {ok, T, {L,_}} -> {ok, T, L}; + {eof, {L,_}} -> {eof, L}; + {error, {{EL,_},M,D},{L,_}} -> {error, {EL,M,D},L} + end, + {done, Ret1, R} + end. + +do_tokens([], Chars, Line, Col) -> + tokens(yystate(), Chars, Line, Col, Chars, 0, Line, Col, [], reject, 0); +do_tokens({tokens,State,Line,Col,Tcs,Tlen,Tline,Tcol,Ts,Action,Alen}, Chars, _,_) -> + tokens(State, Chars, Line, Col, Tcs ++ Chars, Tlen, Tline, Tcol, Ts, Action, Alen); +do_tokens({skip_tokens,State,Line, Col, Tcs,Tlen,Tline,Tcol,Error,Action,Alen}, Chars, _,_) -> + skip_tokens(State, Chars, Line, Col, Tcs ++ Chars, Tlen, Tline, Tcol, Error, Action, Alen). + +%% tokens(State, InChars, Line, Col, TokenChars, TokenLen, TokenLine, TokenCol,Tokens, +%% AcceptAction, AcceptLen) -> +%% {more,Continuation} | {done,ReturnVal,RestChars}. + +tokens(S0, Ics0, L0, C0, Tcs, Tlen0, Tline, Tcol, Ts, A0, Alen0) -> + case yystate(S0, Ics0, L0, C0, Tlen0, A0, Alen0) of + %% Accepting end state, we have a token. + {A1,Alen1,Ics1,L1,C1} -> + C2 = adjust_col(Tcs, Alen1, C1), + tokens_cont(Ics1, L1, C2, yyaction(A1, Alen1, Tcs, Tline, Tcol), Ts); + %% Accepting transition state, can take more chars. + {A1,Alen1,[],L1,C1,S1} -> % Need more chars to check + {more,{tokens,S1,L1,C1,Tcs,Alen1,Tline,Tcol,Ts,A1,Alen1}}; + {A1,Alen1,Ics1,L1,C1,_S1} -> % Take what we got + C2 = adjust_col(Tcs, Alen1, C1), + tokens_cont(Ics1, L1, C2, yyaction(A1, Alen1, Tcs, Tline,Tcol), Ts); + %% After a non-accepting state, maybe reach accept state later. + {A1,Alen1,Tlen1,[],L1,C1,S1} -> % Need more chars to check + {more,{tokens,S1,L1,C1,Tcs,Tlen1,Tline,Tcol,Ts,A1,Alen1}}; + {reject,_Alen1,Tlen1,eof,L1,C1,_S1} -> % No token match + %% Check for partial token which is error, no need to skip here. + Ret = if Tlen1 > 0 -> {error,{{Tline,Tcol},?MODULE, + %% Skip eof tail in Tcs. + {illegal,yypre(Tcs, Tlen1)}},{L1,C1}}; + Ts == [] -> {eof,{L1,C1}}; + true -> {ok,yyrev(Ts),{L1,C1}} + end, + {done,Ret,eof}; + {reject,_Alen1,Tlen1,_Ics1,L1,C1,_S1} -> + %% Skip rest of tokens. + Error = {{L1,C1},?MODULE,{illegal,yypre(Tcs, Tlen1+1)}}, + skip_tokens(yysuf(Tcs, Tlen1+1), L1, C1, Error); + {A1,Alen1,Tlen1,_Ics1,L1,_C1,_S1} -> + Token = yyaction(A1, Alen1, Tcs, Tline,Tcol), + Tcs1 = yysuf(Tcs, Alen1), + L2 = adjust_line(Tlen1, Alen1, Tcs1, L1), + C2 = C0 + Alen1, + tokens_cont(Tcs1, L2, C2, Token, Ts) + end. + +%% tokens_cont(RestChars, Line, Column, Token, Tokens) +%% If we have an end_token or error then return done, else if we have +%% a token then save it and continue, else if we have a skip_token +%% just continue. + +-dialyzer({nowarn_function, tokens_cont/5}). + +tokens_cont(Rest, Line, Col, {token,T}, Ts) -> + tokens(yystate(), Rest, Line, Col, Rest, 0, Line, Col, [T|Ts], reject, 0); +tokens_cont(Rest, Line, Col, {token,T,Push}, Ts) -> + NewRest = Push ++ Rest, + tokens(yystate(), NewRest, Line, Col, NewRest, 0, Line, Col, [T|Ts], reject, 0); +tokens_cont(Rest, Line, Col, {end_token,T}, Ts) -> + {done,{ok,yyrev(Ts, [T]),{Line,Col}},Rest}; +tokens_cont(Rest, Line, Col, {end_token,T,Push}, Ts) -> + NewRest = Push ++ Rest, + {done,{ok,yyrev(Ts, [T]),{Line, Col}},NewRest}; +tokens_cont(Rest, Line, Col, skip_token, Ts) -> + tokens(yystate(), Rest, Line, Col, Rest, 0, Line, Col, Ts, reject, 0); +tokens_cont(Rest, Line, Col, {skip_token,Push}, Ts) -> + NewRest = Push ++ Rest, + tokens(yystate(), NewRest, Line, Col, NewRest, 0, Line, Col, Ts, reject, 0); +tokens_cont(Rest, Line, Col, {error,S}, _Ts) -> + skip_tokens(Rest, Line, Col, {{Line,Col},?MODULE,{user,S}}). + +%% skip_tokens(InChars, Line, Col, Error) -> {done,{error,Error,{Line,Col}},Ics}. +%% Skip tokens until an end token, junk everything and return the error. + +skip_tokens(Ics, Line, Col, Error) -> + skip_tokens(yystate(), Ics, Line, Col, Ics, 0, Line, Col, Error, reject, 0). + +%% skip_tokens(State, InChars, Line, Col, TokenChars, TokenLen, TokenLine, TokenCol, Tokens, +%% AcceptAction, AcceptLen) -> +%% {more,Continuation} | {done,ReturnVal,RestChars}. + +skip_tokens(S0, Ics0, L0, C0, Tcs, Tlen0, Tline, Tcol, Error, A0, Alen0) -> + case yystate(S0, Ics0, L0, C0, Tlen0, A0, Alen0) of + {A1,Alen1,Ics1,L1, C1} -> % Accepting end state + skip_cont(Ics1, L1, C1, yyaction(A1, Alen1, Tcs, Tline, Tcol), Error); + {A1,Alen1,[],L1,C1, S1} -> % After an accepting state + {more,{skip_tokens,S1,L1,C1,Tcs,Alen1,Tline,Tcol,Error,A1,Alen1}}; + {A1,Alen1,Ics1,L1,C1,_S1} -> + skip_cont(Ics1, L1, C1, yyaction(A1, Alen1, Tcs, Tline, Tcol), Error); + {A1,Alen1,Tlen1,[],L1,C1,S1} -> % After a non-accepting state + {more,{skip_tokens,S1,L1,C1,Tcs,Tlen1,Tline,Tcol,Error,A1,Alen1}}; + {reject,_Alen1,_Tlen1,eof,L1,C1,_S1} -> + {done,{error,Error,{L1,C1}},eof}; + {reject,_Alen1,Tlen1,_Ics1,L1,C1,_S1} -> + skip_tokens(yysuf(Tcs, Tlen1+1), L1, C1,Error); + {A1,Alen1,Tlen1,_Ics1,L1,C1,_S1} -> + Token = yyaction(A1, Alen1, Tcs, Tline, Tcol), + Tcs1 = yysuf(Tcs, Alen1), + L2 = adjust_line(Tlen1, Alen1, Tcs1, L1), + skip_cont(Tcs1, L2, C1, Token, Error) + end. + +%% skip_cont(RestChars, Line, Col, Token, Error) +%% Skip tokens until we have an end_token or error then return done +%% with the original rror. + +-dialyzer({nowarn_function, skip_cont/5}). + +skip_cont(Rest, Line, Col, {token,_T}, Error) -> + skip_tokens(yystate(), Rest, Line, Col, Rest, 0, Line, Col, Error, reject, 0); +skip_cont(Rest, Line, Col, {token,_T,Push}, Error) -> + NewRest = Push ++ Rest, + skip_tokens(yystate(), NewRest, Line, Col, NewRest, 0, Line, Col, Error, reject, 0); +skip_cont(Rest, Line, Col, {end_token,_T}, Error) -> + {done,{error,Error,{Line,Col}},Rest}; +skip_cont(Rest, Line, Col, {end_token,_T,Push}, Error) -> + NewRest = Push ++ Rest, + {done,{error,Error,{Line,Col}},NewRest}; +skip_cont(Rest, Line, Col, skip_token, Error) -> + skip_tokens(yystate(), Rest, Line, Col, Rest, 0, Line, Col, Error, reject, 0); +skip_cont(Rest, Line, Col, {skip_token,Push}, Error) -> + NewRest = Push ++ Rest, + skip_tokens(yystate(), NewRest, Line, Col, NewRest, 0, Line, Col, Error, reject, 0); +skip_cont(Rest, Line, Col, {error,_S}, Error) -> + skip_tokens(yystate(), Rest, Line, Col, Rest, 0, Line, Col, Error, reject, 0). + +-compile({nowarn_unused_function, [yyrev/1, yyrev/2, yypre/2, yysuf/2]}). + +yyrev(List) -> lists:reverse(List). +yyrev(List, Tail) -> lists:reverse(List, Tail). +yypre(List, N) -> lists:sublist(List, N). +yysuf(List, N) -> lists:nthtail(N, List). + +%% adjust_line(TokenLength, AcceptLength, Chars, Line) -> NewLine +%% Make sure that newlines in Chars are not counted twice. +%% Line has been updated with respect to newlines in the prefix of +%% Chars consisting of (TokenLength - AcceptLength) characters. + +-compile({nowarn_unused_function, adjust_line/4}). + +adjust_line(N, N, _Cs, L) -> L; +adjust_line(T, A, [$\n|Cs], L) -> + adjust_line(T-1, A, Cs, L-1); +adjust_line(T, A, [_|Cs], L) -> + adjust_line(T-1, A, Cs, L). + +%% adjust_col(Chars, AcceptLength, Col) -> NewCol +%% Handle newlines, tabs and unicode chars. +adjust_col(_, 0, Col) -> + Col; +adjust_col([$\n | R], L, _) -> + adjust_col(R, L-1, 1); +adjust_col([$\t | R], L, Col) -> + adjust_col(R, L-1, tab_forward(Col)+1); +adjust_col([C | R], L, Col) when C>=0 andalso C=< 16#7F -> + adjust_col(R, L-1, Col+1); +adjust_col([C | R], L, Col) when C>= 16#80 andalso C=< 16#7FF -> + adjust_col(R, L-1, Col+2); +adjust_col([C | R], L, Col) when C>= 16#800 andalso C=< 16#FFFF -> + adjust_col(R, L-1, Col+3); +adjust_col([C | R], L, Col) when C>= 16#10000 andalso C=< 16#10FFFF -> + adjust_col(R, L-1, Col+4). + +tab_forward(C) -> + D = C rem tab_size(), + A = tab_size()-D, + C+A. + +tab_size() -> 8. + +%% yystate() -> InitialState. +%% yystate(State, InChars, Line, Col, CurrTokLen, AcceptAction, AcceptLen) -> +%% {Action, AcceptLen, RestChars, Line, Col} | +%% {Action, AcceptLen, RestChars, Line, Col, State} | +%% {reject, AcceptLen, CurrTokLen, RestChars, Line, Col, State} | +%% {Action, AcceptLen, CurrTokLen, RestChars, Line, Col, State}. +%% Generated state transition functions. The non-accepting end state +%% return signal either an unrecognised character or end of current +%% input. + +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/_build/default/plugins/hex_core/src/safe_erl_term.erl", 425). +yystate() -> 12. + +yystate(19, [92|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(15, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(19, [34|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(7, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(19, [10|Ics], Line, _, Tlen, Action, Alen) -> + yystate(8, Ics, Line+1, 1, Tlen+1, Action, Alen); +yystate(19, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 0, C =< 9 -> + yystate(8, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(19, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 11, C =< 33 -> + yystate(8, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(19, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 35, C =< 91 -> + yystate(8, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(19, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 93 -> + yystate(8, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(19, Ics, Line, Col, Tlen, Action, Alen) -> + {Action,Alen,Tlen,Ics,Line,Col,19}; +yystate(18, [92|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(14, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(18, [39|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(10, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(18, [10|Ics], Line, _, Tlen, Action, Alen) -> + yystate(5, Ics, Line+1, 1, Tlen+1, Action, Alen); +yystate(18, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 0, C =< 9 -> + yystate(5, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(18, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 11, C =< 38 -> + yystate(5, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(18, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 40, C =< 91 -> + yystate(5, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(18, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 93 -> + yystate(5, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(18, Ics, Line, Col, Tlen, Action, Alen) -> + {Action,Alen,Tlen,Ics,Line,Col,18}; +yystate(17, [60|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(11, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(17, Ics, Line, Col, Tlen, Action, Alen) -> + {Action,Alen,Tlen,Ics,Line,Col,17}; +yystate(16, [10|Ics], Line, _, Tlen, _, _) -> + yystate(16, Ics, Line+1, 1, Tlen+1, 8, Tlen); +yystate(16, [C|Ics], Line, Col, Tlen, _, _) when C >= 0, C =< 9 -> + yystate(16, Ics, Line, Col, Tlen+1, 8, Tlen); +yystate(16, [C|Ics], Line, Col, Tlen, _, _) when C >= 11, C =< 32 -> + yystate(16, Ics, Line, Col, Tlen+1, 8, Tlen); +yystate(16, Ics, Line, Col, Tlen, _, _) -> + {8,Tlen,Ics,Line,Col,16}; +yystate(15, [94|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(19, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(15, [93|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(8, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(15, [92|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(15, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(15, [34|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(7, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(15, [10|Ics], Line, _, Tlen, Action, Alen) -> + yystate(8, Ics, Line+1, 1, Tlen+1, Action, Alen); +yystate(15, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 0, C =< 9 -> + yystate(8, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(15, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 11, C =< 33 -> + yystate(8, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(15, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 35, C =< 91 -> + yystate(8, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(15, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 95 -> + yystate(8, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(15, Ics, Line, Col, Tlen, Action, Alen) -> + {Action,Alen,Tlen,Ics,Line,Col,15}; +yystate(14, [94|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(18, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(14, [93|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(5, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(14, [92|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(14, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(14, [39|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(10, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(14, [10|Ics], Line, _, Tlen, Action, Alen) -> + yystate(5, Ics, Line+1, 1, Tlen+1, Action, Alen); +yystate(14, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 0, C =< 9 -> + yystate(5, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(14, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 11, C =< 38 -> + yystate(5, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(14, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 40, C =< 91 -> + yystate(5, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(14, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 95 -> + yystate(5, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(14, Ics, Line, Col, Tlen, Action, Alen) -> + {Action,Alen,Tlen,Ics,Line,Col,14}; +yystate(13, Ics, Line, Col, Tlen, _, _) -> + {4,Tlen,Ics,Line,Col}; +yystate(12, [125|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(13, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(12, [123|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(13, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(12, [93|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(13, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(12, [91|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(13, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(12, [62|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(3, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(12, [61|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(3, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(12, [60|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(17, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(12, [47|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(1, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(12, [46|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(6, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(12, [39|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(5, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(12, [35|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(13, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(12, [34|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(8, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(12, [10|Ics], Line, _, Tlen, Action, Alen) -> + yystate(16, Ics, Line+1, 1, Tlen+1, Action, Alen); +yystate(12, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 0, C =< 9 -> + yystate(16, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(12, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 11, C =< 32 -> + yystate(16, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(12, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 43, C =< 45 -> + yystate(13, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(12, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 48, C =< 57 -> + yystate(9, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(12, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 97, C =< 122 -> + yystate(4, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(12, Ics, Line, Col, Tlen, Action, Alen) -> + {Action,Alen,Tlen,Ics,Line,Col,12}; +yystate(11, Ics, Line, Col, Tlen, _, _) -> + {5,Tlen,Ics,Line,Col}; +yystate(10, [92|Ics], Line, Col, Tlen, _, _) -> + yystate(14, Ics, Line, Col, Tlen+1, 1, Tlen); +yystate(10, [39|Ics], Line, Col, Tlen, _, _) -> + yystate(2, Ics, Line, Col, Tlen+1, 1, Tlen); +yystate(10, [10|Ics], Line, _, Tlen, _, _) -> + yystate(5, Ics, Line+1, 1, Tlen+1, 1, Tlen); +yystate(10, [C|Ics], Line, Col, Tlen, _, _) when C >= 0, C =< 9 -> + yystate(5, Ics, Line, Col, Tlen+1, 1, Tlen); +yystate(10, [C|Ics], Line, Col, Tlen, _, _) when C >= 11, C =< 38 -> + yystate(5, Ics, Line, Col, Tlen+1, 1, Tlen); +yystate(10, [C|Ics], Line, Col, Tlen, _, _) when C >= 40, C =< 91 -> + yystate(5, Ics, Line, Col, Tlen+1, 1, Tlen); +yystate(10, [C|Ics], Line, Col, Tlen, _, _) when C >= 93 -> + yystate(5, Ics, Line, Col, Tlen+1, 1, Tlen); +yystate(10, Ics, Line, Col, Tlen, _, _) -> + {1,Tlen,Ics,Line,Col,10}; +yystate(9, [C|Ics], Line, Col, Tlen, _, _) when C >= 48, C =< 57 -> + yystate(9, Ics, Line, Col, Tlen+1, 3, Tlen); +yystate(9, Ics, Line, Col, Tlen, _, _) -> + {3,Tlen,Ics,Line,Col,9}; +yystate(8, [92|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(15, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(8, [34|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(0, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(8, [10|Ics], Line, _, Tlen, Action, Alen) -> + yystate(8, Ics, Line+1, 1, Tlen+1, Action, Alen); +yystate(8, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 0, C =< 9 -> + yystate(8, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(8, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 11, C =< 33 -> + yystate(8, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(8, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 35, C =< 91 -> + yystate(8, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(8, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 93 -> + yystate(8, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(8, Ics, Line, Col, Tlen, Action, Alen) -> + {Action,Alen,Tlen,Ics,Line,Col,8}; +yystate(7, [92|Ics], Line, Col, Tlen, _, _) -> + yystate(15, Ics, Line, Col, Tlen+1, 2, Tlen); +yystate(7, [34|Ics], Line, Col, Tlen, _, _) -> + yystate(0, Ics, Line, Col, Tlen+1, 2, Tlen); +yystate(7, [10|Ics], Line, _, Tlen, _, _) -> + yystate(8, Ics, Line+1, 1, Tlen+1, 2, Tlen); +yystate(7, [C|Ics], Line, Col, Tlen, _, _) when C >= 0, C =< 9 -> + yystate(8, Ics, Line, Col, Tlen+1, 2, Tlen); +yystate(7, [C|Ics], Line, Col, Tlen, _, _) when C >= 11, C =< 33 -> + yystate(8, Ics, Line, Col, Tlen+1, 2, Tlen); +yystate(7, [C|Ics], Line, Col, Tlen, _, _) when C >= 35, C =< 91 -> + yystate(8, Ics, Line, Col, Tlen+1, 2, Tlen); +yystate(7, [C|Ics], Line, Col, Tlen, _, _) when C >= 93 -> + yystate(8, Ics, Line, Col, Tlen+1, 2, Tlen); +yystate(7, Ics, Line, Col, Tlen, _, _) -> + {2,Tlen,Ics,Line,Col,7}; +yystate(6, Ics, Line, Col, Tlen, _, _) -> + {6,Tlen,Ics,Line,Col}; +yystate(5, [92|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(14, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(5, [39|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(2, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(5, [10|Ics], Line, _, Tlen, Action, Alen) -> + yystate(5, Ics, Line+1, 1, Tlen+1, Action, Alen); +yystate(5, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 0, C =< 9 -> + yystate(5, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(5, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 11, C =< 38 -> + yystate(5, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(5, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 40, C =< 91 -> + yystate(5, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(5, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 93 -> + yystate(5, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(5, Ics, Line, Col, Tlen, Action, Alen) -> + {Action,Alen,Tlen,Ics,Line,Col,5}; +yystate(4, [95|Ics], Line, Col, Tlen, _, _) -> + yystate(4, Ics, Line, Col, Tlen+1, 0, Tlen); +yystate(4, [64|Ics], Line, Col, Tlen, _, _) -> + yystate(4, Ics, Line, Col, Tlen+1, 0, Tlen); +yystate(4, [C|Ics], Line, Col, Tlen, _, _) when C >= 48, C =< 57 -> + yystate(4, Ics, Line, Col, Tlen+1, 0, Tlen); +yystate(4, [C|Ics], Line, Col, Tlen, _, _) when C >= 65, C =< 90 -> + yystate(4, Ics, Line, Col, Tlen+1, 0, Tlen); +yystate(4, [C|Ics], Line, Col, Tlen, _, _) when C >= 97, C =< 122 -> + yystate(4, Ics, Line, Col, Tlen+1, 0, Tlen); +yystate(4, Ics, Line, Col, Tlen, _, _) -> + {0,Tlen,Ics,Line,Col,4}; +yystate(3, [62|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(11, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(3, Ics, Line, Col, Tlen, Action, Alen) -> + {Action,Alen,Tlen,Ics,Line,Col,3}; +yystate(2, Ics, Line, Col, Tlen, _, _) -> + {1,Tlen,Ics,Line,Col}; +yystate(1, Ics, Line, Col, Tlen, _, _) -> + {7,Tlen,Ics,Line,Col}; +yystate(0, Ics, Line, Col, Tlen, _, _) -> + {2,Tlen,Ics,Line,Col}; +yystate(S, Ics, Line, Col, Tlen, Action, Alen) -> + {Action,Alen,Tlen,Ics,Line,Col,S}. + +%% yyaction(Action, TokenLength, TokenChars, TokenLine, TokenCol) -> +%% {token,Token} | {end_token, Token} | skip_token | {error,String}. +%% Generated action function. + +yyaction(0, TokenLen, YYtcs, TokenLine, _) -> + TokenChars = yypre(YYtcs, TokenLen), + yyaction_0(TokenChars, TokenLine); +yyaction(1, TokenLen, YYtcs, TokenLine, _) -> + TokenChars = yypre(YYtcs, TokenLen), + yyaction_1(TokenChars, TokenLen, TokenLine); +yyaction(2, TokenLen, YYtcs, TokenLine, _) -> + TokenChars = yypre(YYtcs, TokenLen), + yyaction_2(TokenChars, TokenLen, TokenLine); +yyaction(3, TokenLen, YYtcs, TokenLine, _) -> + TokenChars = yypre(YYtcs, TokenLen), + yyaction_3(TokenChars, TokenLine); +yyaction(4, TokenLen, YYtcs, TokenLine, _) -> + TokenChars = yypre(YYtcs, TokenLen), + yyaction_4(TokenChars, TokenLine); +yyaction(5, TokenLen, YYtcs, TokenLine, _) -> + TokenChars = yypre(YYtcs, TokenLen), + yyaction_5(TokenChars, TokenLine); +yyaction(6, _, _, TokenLine, _) -> + yyaction_6(TokenLine); +yyaction(7, _, _, TokenLine, _) -> + yyaction_7(TokenLine); +yyaction(8, _, _, _, _) -> + yyaction_8(); +yyaction(_, _, _, _, _) -> error. + +-compile({inline,yyaction_0/2}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 12). +yyaction_0(TokenChars, TokenLine) -> + tokenize_atom (TokenChars, TokenLine) . + +-compile({inline,yyaction_1/3}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 13). +yyaction_1(TokenChars, TokenLen, TokenLine) -> + tokenize_atom (escape (unquote (TokenChars, TokenLen)), TokenLine) . + +-compile({inline,yyaction_2/3}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 14). +yyaction_2(TokenChars, TokenLen, TokenLine) -> + { token, { string, TokenLine, escape (unquote (TokenChars, TokenLen)) } } . + +-compile({inline,yyaction_3/2}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 15). +yyaction_3(TokenChars, TokenLine) -> + { token, { integer, TokenLine, list_to_integer (TokenChars) } } . + +-compile({inline,yyaction_4/2}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 16). +yyaction_4(TokenChars, TokenLine) -> + { token, { list_to_atom (TokenChars), TokenLine } } . + +-compile({inline,yyaction_5/2}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 17). +yyaction_5(TokenChars, TokenLine) -> + { token, { list_to_atom (TokenChars), TokenLine } } . + +-compile({inline,yyaction_6/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 18). +yyaction_6(TokenLine) -> + { token, { dot, TokenLine } } . + +-compile({inline,yyaction_7/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 19). +yyaction_7(TokenLine) -> + { token, { '/', TokenLine } } . + +-compile({inline,yyaction_8/0}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/_build/default/plugins/hex_core/src/safe_erl_term.xrl", 20). +yyaction_8() -> + skip_token . +-file("/home/saru/.local/share/mise/installs/erlang/28.4.1/lib/parsetools-2.7.1/include/leexinc.hrl", 377). diff --git a/deps/eini/_build/default/plugins/verl/LICENSE b/deps/eini/_build/default/plugins/verl/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..50e0a132cd0999ea3c5b308dffa2f432810ba102 --- /dev/null +++ b/deps/eini/_build/default/plugins/verl/LICENSE @@ -0,0 +1,191 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2019, Bryan Paxton . + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/deps/eini/_build/default/plugins/verl/README.md b/deps/eini/_build/default/plugins/verl/README.md new file mode 100644 index 0000000000000000000000000000000000000000..24468451d5c1b9d4e011639aa216f1165a16674e --- /dev/null +++ b/deps/eini/_build/default/plugins/verl/README.md @@ -0,0 +1,142 @@ +# verl +[![Hex Version](https://img.shields.io/hexpm/v/verl.svg)](https://hex.pm/packages/verl) [![GitHub Actions CI](https://github.com/jelly-beam/verl/workflows/build/badge.svg)](https://github.com/jelly-beam/verl +) [![codecov](https://codecov.io/gh/jelly-beam/verl/branch/main/graph/badge.svg)](https://codecov.io/gh/jelly-beam/verl) + +SemVer 2.0 version and requirements parsing, matching, and comparisons. + +All parsing of versions and requirements adhere to the [SemVer 2.0 schema](http://semver.org/) + + - [Build](#build) + - [Usage](#usage) + * [Comparisons](#comparisons) + * [Version, Requirements, and Matching](#version--requirements--and-matching) + - [Matching](#matching) + - [Compiled requirements for ludicious speed matching](#compiled-requirements-for-ludicious-speed-matching) + - [Version parsing](#version-parsing) + * [Requirements parsing](#requirements-parsing) + - [Credits](#credits) + + +## Build + +```bash +$ rebar3 compile +``` + +## Test + +```bash +$ rebar3 test +``` + +## Usage + +Add to you deps configuration in rebar.config for your project : + +```erlang +{deps, [{verl, "1.1.0"}]}. +``` + +### Comparisons + +```erlang +1> verl:compare(<<"1.0.0">>, <<"1.0.1">>). +lt +2> verl:compare(<<"1.0.0">>, <<"1.0.0">>). +eq +3> verl:compare(<<"2.0.0">>, <<"1.0.0">>). +gt +4> verl:compare(<<"1.0.0-pre">>, <<"1.0.0">>). +lt +5> verl:compare(<<"1.0.0">>, <<"1.0.0-pre">>). +gt +``` + +### Version, Requirements, and Matching + +#### Matching + +```erlang +1> verl:is_match(<<"1.0.0">>, <<"~> 1.0.0">>). +true +2> verl:is_match(<<"1.0.0">>, <<"~> 2.0.0">>). +false +3> verl:is_match(<<"3.2.0">>, <<"~> 3.0.0">>). +false +4> verl:is_match(<<"3.2.0">>, <<"~> 3.0">>). +true +``` + +#### Compiled requirements for ludicious speed matching + +```erlang +1> {ok, Req} = verl:parse_requirement(<<"~> 3.0">>). +{ok,#{compiled => false, + string => <<"~> 3.0">>, + matchspec => [{{'$1','$2','$3','$4','$5'}...}], + string => <<"~> 3.0">>}} +2> verl:is_match(<<"3.0.0-dev">>, Req). + false +3> verl:is_match(<<"1.2.3">>, Req). + false +4> verl:is_match(<<"3.1.0">>, Req). + true +``` + +#### Version parsing + +```erlang +1> verl:parse(<<"1.2.3">>). +#{build => undefined,major => 1,minor => 2,patch => 3, + pre => []} +2> verl:parse(<<"1.2.3+build">>). +#{build => <<"build">>,major => 1,minor => 2,patch => 3, + pre => []} +3> verl:parse(<<"1.2.3-pre+build">>). +#{build => <<"build">>,major => 1,minor => 2,patch => 3, + pre => [<<"pre">>]} +4> verl:parse(<<"1">>). +{error, invalid_version} +5> verl:parse(<<"2">>). +{error, invalid_version} +``` + +Don't want a map? Use the `verl_parser` module... + +```erlang +1> verl_parser:parse_version(<<"1.2.3">>). +{ok,{1,2,3,[],[]}} +2> verl_parser:parse_version(<<"1.2.3+build">>). +{ok,{1,2,3,[],[<<"build">>]}} +3> verl_parser:parse_version(<<"1.2.3-pre+build">>). +{ok,{1,2,3,[<<"pre">>],[<<"build">>]}} +4> verl_parser:parse_version(<<"1">>). +{error, invalid_version} +``` + +##### Requirements parsing + +```erlang +1> verl:parse_requirement(<<"~> 2.1.0-dev">>). +{ok,#{compiled => false, + string => <<"~> 2.1.0-dev">>, + matchspec => + [{{'$1','$2','$3','$4','$5'}...] }} +2> verl:parse_requirement(<<"~> 2.1.0-">>). +{error,invalid_requirement} +``` + +Don't want a map? User the `verl_parser` module... + +```erlang +1> verl_parser:parse_requirement(<<"~> 2.1.0-dev">>). +{ok, [{{'$1','$2','$3','$4','$5'}...]} +2> verl:parse_requirement(<<"~> 2.1.0-">>). +{error,invalid_requirement} +``` + +## Credits + +- All credit goes to the Elixir team and contributors to Version and +Version.Parser in the Elixir standard lib for the algorithm and original +implementation. diff --git a/deps/eini/_build/default/plugins/verl/ebin/verl.app b/deps/eini/_build/default/plugins/verl/ebin/verl.app new file mode 100644 index 0000000000000000000000000000000000000000..ce84a7f1f9d006663fdd2a99bfebd8ff91fe7e60 --- /dev/null +++ b/deps/eini/_build/default/plugins/verl/ebin/verl.app @@ -0,0 +1,11 @@ +{application,verl, + [{description,"SemVer2 version and requirements parsing, matching, and comparison"}, + {vsn,"1.1.1"}, + {organization,"jelly-beam"}, + {registered,[]}, + {applications,[kernel,stdlib]}, + {env,[]}, + {modules,[verl,verl_parser]}, + {extra,{maintainers,["Bryan Paxton"]}}, + {licenses,["Apache 2.0"]}, + {links,[{"Github","https://github.com/jelly-beam/verl"}]}]}. diff --git a/deps/eini/_build/default/plugins/verl/ebin/verl.beam b/deps/eini/_build/default/plugins/verl/ebin/verl.beam new file mode 100644 index 0000000000000000000000000000000000000000..0241845847897c87c1f6ad2d35fa2c497ac7c66b Binary files /dev/null and b/deps/eini/_build/default/plugins/verl/ebin/verl.beam differ diff --git a/deps/eini/_build/default/plugins/verl/ebin/verl_parser.beam b/deps/eini/_build/default/plugins/verl/ebin/verl_parser.beam new file mode 100644 index 0000000000000000000000000000000000000000..d6a54f7a32ade48c1ff77c17ab736b8f1af004cc Binary files /dev/null and b/deps/eini/_build/default/plugins/verl/ebin/verl_parser.beam differ diff --git a/deps/eini/_build/default/plugins/verl/hex_metadata.config b/deps/eini/_build/default/plugins/verl/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..398960df258c194226ca5252716e294543e759da --- /dev/null +++ b/deps/eini/_build/default/plugins/verl/hex_metadata.config @@ -0,0 +1,12 @@ +{<<"app">>,<<"verl">>}. +{<<"build_tools">>,[<<"rebar3">>]}. +{<<"description">>, + <<"SemVer2 version and requirements parsing, matching, and comparison">>}. +{<<"files">>, + [<<"LICENSE">>,<<"README.md">>,<<"rebar.config">>,<<"rebar.lock">>, + <<"src/verl.app.src">>,<<"src/verl.erl">>,<<"src/verl_parser.erl">>]}. +{<<"licenses">>,[<<"Apache 2.0">>]}. +{<<"links">>,[{<<"Github">>,<<"https://github.com/jelly-beam/verl">>}]}. +{<<"name">>,<<"verl">>}. +{<<"requirements">>,[]}. +{<<"version">>,<<"1.1.1">>}. diff --git a/deps/eini/_build/default/plugins/verl/rebar.config b/deps/eini/_build/default/plugins/verl/rebar.config new file mode 100644 index 0000000000000000000000000000000000000000..50e7a11c6f08965f39ca2bbfb9fd7db27da7adbf --- /dev/null +++ b/deps/eini/_build/default/plugins/verl/rebar.config @@ -0,0 +1,48 @@ +{erl_opts, [ + debug_info, + warn_missing_spec, + warnings_as_errors +]}. +{minimum_otp_vsn, "19.3"}. +{deps, []}. +{project_plugins, [erlfmt, rebar3_proper, rebar3_hex, covertool, rebar3_lint, rebar3_hank]}. +{profiles, [ + {test, [ + {deps, [{proper, "1.3.0"}]}, + {erl_opts, [nowarn_missing_spec, nowarn_export_all]}, + {dialyzer, [{plt_extra_apps, [proper]}]}, + {cover_enabled, true}, + {cover_opts, [verbose]} + ]} +]}. + +{erlfmt, [ + {files, "{src,include,test}/*.{hrl,erl}"} + ]}. + +{edoc_opts, [ + {doclet, edoc_doclet_chunks}, + {layout, edoc_layout_chunks}, + {preprocess, true}, + {dir, "_build/default/lib/verl/doc"}]}. + +{xref_ignores, [verl, {verl_parser, parse_version, 2}]}. + +{alias, [{quick_test, [{proper, "--cover --numtests=3"}, + {eunit, "--cover"}, + {cover, "-v"}]}, + {test, [{ct, "-c"}, {proper, "--cover"}, {eunit, "--cover"}, {cover, "-v"}]}, + {check, [{proper, "--cover --numtests=3"}, + {eunit, "--cover"}, + xref, dialyzer, cover]}]}. + +{xref_checks,[undefined_function_calls,locals_not_used, + deprecated_function_calls,exports_not_used]}. + +{dialyzer, [ + {warnings, [ + error_handling, + unknown, + unmatched_returns + ]} +]}. diff --git a/deps/eini/_build/default/plugins/verl/rebar.lock b/deps/eini/_build/default/plugins/verl/rebar.lock new file mode 100644 index 0000000000000000000000000000000000000000..57afcca04590ff2bbf2f83b8eac4f856df782c74 --- /dev/null +++ b/deps/eini/_build/default/plugins/verl/rebar.lock @@ -0,0 +1 @@ +[]. diff --git a/deps/eini/_build/default/plugins/verl/src/verl.app.src b/deps/eini/_build/default/plugins/verl/src/verl.app.src new file mode 100644 index 0000000000000000000000000000000000000000..144d36e636e16c0ba5561fa90c2823dd6086ae56 --- /dev/null +++ b/deps/eini/_build/default/plugins/verl/src/verl.app.src @@ -0,0 +1,11 @@ +{application,verl, + [{description,"SemVer2 version and requirements parsing, matching, and comparison"}, + {vsn,"1.1.1"}, + {organization,"jelly-beam"}, + {registered,[]}, + {applications,[kernel,stdlib]}, + {env,[]}, + {modules,[]}, + {extra,{maintainers,["Bryan Paxton"]}}, + {licenses,["Apache 2.0"]}, + {links,[{"Github","https://github.com/jelly-beam/verl"}]}]}. diff --git a/deps/eini/_build/default/plugins/verl/src/verl.erl b/deps/eini/_build/default/plugins/verl/src/verl.erl new file mode 100644 index 0000000000000000000000000000000000000000..f94f358cf29c08ecabfaa6a269cc9db9192d0454 --- /dev/null +++ b/deps/eini/_build/default/plugins/verl/src/verl.erl @@ -0,0 +1,332 @@ +-module(verl). + +%% Main API +-export([ + compare/2, + is_match/2, + is_match/3, + parse/1, + parse_requirement/1, + compile_requirement/1 +]). + +%% Helpers +-export([ + between/3, + eq/2, + gt/2, + gte/2, + lt/2, + lte/2 +]). + +-type version() :: binary(). +-type requirement() :: binary(). + +-type major() :: non_neg_integer(). +-type minor() :: non_neg_integer(). +-type patch() :: non_neg_integer(). +-type pre() :: [binary() | non_neg_integer()]. +-type build() :: binary() | undefined. +-type version_t() :: #{ + major => major(), + minor => minor(), + patch => patch(), + pre => pre(), + build => build() +}. + +-type requirement_t() :: #{ + string => requirement(), + matchspec => list(), + compiled => boolean() +}. + +-type compiled_requirement() :: #{ + compiled => true, + matchspec => ets:comp_match_spec(), + string => requirement() +}. + +-type match_opts() :: [allow_pre | {allow_pre, true}]. + +-export_type([ + version/0, + requirement/0, + major/0, + minor/0, + patch/0, + pre/0, + build/0, + version_t/0, + requirement_t/0, + compiled_requirement/0 +]). + +%%% Primary API + +%%% @doc +%%% Compares two versions, returning whether the first argument is greater, equal, or +%%% less than the second argument. +%%% @end +-spec compare(version(), version()) -> gt | eq | lt | {error, invalid_version}. +compare(Version1, Version2) -> + ver_cmp(to_matchable(Version1, true), to_matchable(Version2, true)). + +%%% @doc +%%% Parses a semantic version, returning {ok, version_t()} or {error, invalid_version} +%%% @end +-spec parse(version()) -> {ok, version_t()} | {error, invalid_version}. +parse(Str) -> + build_version(Str). + +%%% @doc +%%% Parses a semantic version requirement, returning {ok, requirement_t()} or +%%% {error, invalid_requirement} +%%% @end +-spec parse_requirement(requirement()) -> {ok, requirement_t()} | {error, invalid_requirement}. +parse_requirement(Str) -> + case verl_parser:parse_requirement(Str) of + {ok, Spec} -> + {ok, #{string => Str, matchspec => Spec, compiled => false}}; + {error, invalid_requirement} -> + {error, invalid_requirement} + end. + +%%% @doc +%%% Compiles a version requirement as returned by `parse_requirement' for faster +%%% matches. +%%% @end +-spec compile_requirement(requirement_t()) -> compiled_requirement(). +compile_requirement(Req) when is_map(Req) -> + Ms = ets:match_spec_compile(maps:get(matchspec, Req)), + maps:put(compiled, true, maps:put(matchspec, Ms, Req)). + +%%% @doc +%%% Returns `true' if the dependency is in range of the requirement, otherwise +%%% `false', or an error. +%%% @end +-spec is_match(version() | version_t(), requirement() | requirement_t()) -> + boolean() | {error, badarg | invalid_requirement | invalid_version}. +is_match(Version, Requirement) -> + is_match(Version, Requirement, []). + +%%% @doc +%%% Works like `is_match/2' but takes extra options as an argument. +%%% @end +-spec is_match(version() | version_t(), requirement() | requirement_t(), match_opts()) -> + boolean() | {error, badarg | invalid_requirement | invalid_version}. +is_match(Version, Requirement, Opts) when is_binary(Version) andalso is_binary(Requirement) -> + case build_version(Version) of + {ok, Ver} -> + case build_requirement(Requirement) of + {ok, Req} -> + is_match(Ver, Req, Opts); + {error, invalid_requirement} -> + {error, invalid_requirement} + end; + {error, invalid_version} -> + {error, invalid_version} + end; +is_match(Version, Requirement, Opts) when is_binary(Version) andalso is_map(Requirement) -> + case build_version(Version) of + {ok, Ver} -> + is_match(Ver, Requirement, Opts); + {error, invalid_version} -> + {error, invalid_version} + end; +is_match(Version, Requirement, Opts) when is_map(Version) andalso is_binary(Requirement) -> + case build_requirement(Requirement) of + {ok, Req} -> + is_match(Version, Req, Opts); + {error, invalid_requirement} -> + {error, invalid_requirement} + end; +is_match(Version, #{matchspec := Spec, compiled := false} = R, Opts) when is_map(R) -> + AllowPre = proplists:get_value(allow_pre, Opts, true), + {ok, Result} = ets:test_ms(to_matchable(Version, AllowPre), Spec), + Result /= false; +is_match(Version, #{matchspec := Spec, compiled := true} = R, Opts) when + is_map(Version) andalso is_map(R) +-> + AllowPre = proplists:get_value(allow_pre, Opts, true), + ets:match_spec_run([to_matchable(Version, AllowPre)], Spec) /= []. + +to_matchable(#{major := Major, minor := Minor, patch := Patch, pre := Pre}, AllowPre) -> + {Major, Minor, Patch, Pre, AllowPre}; +to_matchable(String, AllowPre) when is_binary(String) -> + case verl_parser:parse_version(String) of + {ok, {Major, Minor, Patch, Pre, _Build}} -> + {Major, Minor, Patch, Pre, AllowPre}; + {error, invalid_version} -> + {error, invalid_version} + end. + +%%% Helper functions + +%%% @doc +%%% Helper function that returns true if the first version is greater than the third version and +%%% also the second version is less than the the third version, otherwise returns false. +%%% See `compare/2' for more details. +%%% @end +-spec between(version(), version(), version()) -> boolean() | {error, invalid_version}. +between(Vsn1, Vsn2, VsnMatch) -> + case {gte(VsnMatch, Vsn1), lte(VsnMatch, Vsn2)} of + {true, true} -> + true; + {{error, _} = Err, _} -> + Err; + {_, {error, _} = Err} -> + Err; + _ -> + false + end. + +%%% @doc +%%% Helper function that returns true if two versions are equal, otherwise +%%% false. See `compare/2' for more details. +%%% @end +-spec eq(version(), version()) -> boolean() | {error, invalid_version}. +eq(Vsn1, Vsn2) -> + case compare(Vsn1, Vsn2) of + eq -> true; + {error, _} = Err -> Err; + _ -> false + end. + +%%% @doc +%%% Helper function that returns true the first version given is greater than +%%% the second, otherwise returns false. See `compare/2' for more details. +%%% @end +-spec gt(version(), version()) -> boolean() | {error, invalid_version}. +gt(Vsn1, Vsn2) -> + case compare(Vsn1, Vsn2) of + gt -> true; + {error, _} = Err -> Err; + _ -> false + end. + +%%% @doc +%%% Helper function that returns true the first version given is greater than +%%% or equal to the second, otherwise returns false. +%%% See `compare/2' for more details. +%%% @end +-spec gte(version(), version()) -> boolean() | {error, invalid_version}. +gte(Vsn1, Vsn2) -> + case compare(Vsn1, Vsn2) of + gt -> true; + eq -> true; + {error, _} = Err -> Err; + _ -> false + end. + +%%% @doc +%%% Helper function that returns true the first version given is less than the +%%% second, otherwise returns false. See `compare/2' for more details. +%%% @end +-spec lt(version(), version()) -> boolean() | {error, invalid_version}. +lt(Vsn1, Vsn2) -> + case compare(Vsn1, Vsn2) of + lt -> true; + {error, _} = Err -> Err; + _ -> false + end. + +%%% @doc +%%% Helper function that returns true the first version given is less than or +%%% equal to the second, otherwise returns false. +%%% See `compare/2' for more details. +%%% @end +-spec lte(version(), version()) -> boolean() | {error, invalid_version}. +lte(Vsn1, Vsn2) -> + case compare(Vsn1, Vsn2) of + lt -> true; + eq -> true; + {error, _} = Err -> Err; + _ -> false + end. + +%% private api +%% + +%% @private +build_version(Version) -> + case verl_parser:parse_version(Version) of + {ok, {Major, Minor, Patch, Pre, Build}} -> + {ok, #{ + major => Major, + minor => Minor, + patch => Patch, + pre => Pre, + build => build_string(Build) + }}; + {error, invalid_version} -> + {error, invalid_version} + end. + +%% @private +build_requirement(Str) -> + case verl_parser:parse_requirement(Str) of + {ok, Spec} -> + {ok, #{string => Str, matchspec => Spec, compiled => false}}; + {error, invalid_requirement} -> + {error, invalid_requirement} + end. + +%% @private +build_string(Build) -> + case Build of + [] -> undefined; + _ -> binary:list_to_bin(Build) + end. + +%% @private +ver_cmp({Maj1, Min1, Patch1, Pre1, _}, {Maj2, Min2, Patch2, Pre2, _}) -> + case {Maj1, Min1, Patch1} > {Maj2, Min2, Patch2} of + true -> + gt; + false -> + case {Maj1, Min1, Patch1} < {Maj2, Min2, Patch2} of + true -> + lt; + false -> + test_pre(Pre1, Pre2) + end + end; +ver_cmp(_, _) -> + {error, invalid_version}. + +%% @private +test_pre(Pre1, Pre2) -> + case pre_is_eq(Pre1, Pre2) of + true -> + gt; + false -> + case pre_is_eq(Pre2, Pre1) of + true -> + lt; + false -> + pre_cmp(Pre1, Pre2) + end + end. + +%% @private +pre_cmp(Pre1, Pre2) -> + case Pre1 > Pre2 of + true -> + gt; + false -> + case Pre1 < Pre2 of + true -> + lt; + false -> + eq + end + end. + +%% @private +pre_is_eq(Pre1, Pre2) -> + case Pre1 == [] of + false -> false; + true -> Pre2 /= [] + end. diff --git a/deps/eini/_build/default/plugins/verl/src/verl_parser.erl b/deps/eini/_build/default/plugins/verl/src/verl_parser.erl new file mode 100644 index 0000000000000000000000000000000000000000..614b5a190918596c27500b65174b87f2ffb0bf5a --- /dev/null +++ b/deps/eini/_build/default/plugins/verl/src/verl_parser.erl @@ -0,0 +1,456 @@ +-module(verl_parser). + +-export([parse_requirement/1, parse_version/1, parse_version/2]). + +-type operator() :: '!=' | '&&' | '<' | '<=' | '==' | '>' | '>=' | '||' | '~>' | bitstring(). + +-spec parse_version(verl:version()) -> + {ok, {verl:major(), verl:minor(), verl:patch(), verl:pre(), [verl:build()]}} + | {error, invalid_version}. +parse_version(Str) -> parse_version(Str, false). + +-spec parse_version(verl:version(), boolean()) -> + {ok, {verl:major(), verl:minor(), verl:patch(), verl:pre(), [verl:build()]}} + | {error, invalid_version}. +parse_version(Str, Approximate) when is_binary(Str) -> + try parse_and_convert(Str, Approximate) of + {ok, {_, _, undefined, _, _}} -> + {error, invalid_version}; + {ok, _} = V -> + V; + {error, invalid_version} -> + {error, invalid_version} + catch + error:{badmatch, {error, T}} when + T =:= invalid_version orelse + T =:= nan orelse + T =:= bad_part orelse + T =:= leading_zero + -> + {error, invalid_version} + end. + +-spec parse_requirement(verl:requirement()) -> + {ok, ets:match_spec()} | {error, invalid_requirement}. +parse_requirement(Source) -> + Lexed = lexer(Source, []), + to_matchspec(Lexed). + +%% @private +-spec lexer(binary(), [operator()]) -> [operator()]. +lexer(<<">=", Rest/binary>>, Acc) -> + lexer(Rest, ['>=' | Acc]); +lexer(<<"<=", Rest/binary>>, Acc) -> + lexer(Rest, ['<=' | Acc]); +lexer(<<"~>", Rest/binary>>, Acc) -> + lexer(Rest, ['~>' | Acc]); +lexer(<<">", Rest/binary>>, Acc) -> + lexer(Rest, ['>' | Acc]); +lexer(<<"<", Rest/binary>>, Acc) -> + lexer(Rest, ['<' | Acc]); +lexer(<<"==", Rest/binary>>, Acc) -> + lexer(Rest, ['==' | Acc]); +lexer(<<"!=", Rest/binary>>, Acc) -> + lexer(Rest, ['!=' | Acc]); +lexer(<<"!", Rest/binary>>, Acc) -> + lexer(Rest, ['!=' | Acc]); +lexer(<<" or ", Rest/binary>>, Acc) -> + lexer(Rest, ['||' | Acc]); +lexer(<<" and ", Rest/binary>>, Acc) -> + lexer(Rest, ['&&' | Acc]); +lexer(<<" ", Rest/binary>>, Acc) -> + lexer(Rest, Acc); +lexer(<>, []) -> + lexer(Rest, [<>, '==']); +lexer(<>, [Head | Acc]) -> + Acc1 = + case Head of + Head when is_binary(Head) -> + [<> | Acc]; + Head when Head =:= '&&' orelse Head =:= '||' -> + [<>, '==', Head | Acc]; + _Other -> + [<>, Head | Acc] + end, + lexer(Body, Acc1); +lexer(<<>>, Acc) -> + lists:reverse(Acc). + +%% @private +-spec parse_condition(verl:version()) -> + {integer(), integer(), 'undefined' | integer(), [binary() | integer()]}. +parse_condition(Version) -> parse_condition(Version, false). + +%% @private +-spec parse_condition(verl:version(), boolean()) -> + {integer(), integer(), 'undefined' | integer(), [binary() | integer()]}. +parse_condition(Version, Approximate) -> + try + case parse_and_convert(Version, Approximate) of + {ok, {Major, Minor, Patch, Pre, _Bld}} -> + {Major, Minor, Patch, Pre}; + _ -> + throw(invalid_matchspec) + end + catch + error:{badmatch, {error, T}} when + T =:= invalid_version orelse + T =:= nan orelse + T =:= bad_part orelse + T =:= leading_zero + -> + throw(invalid_matchspec) + end. + +%% @private +-spec approximate_upper({integer(), integer(), 'undefined' | integer(), [binary() | integer()]}) -> + {integer(), integer(), 0, [0, ...]}. +approximate_upper(Version) -> + case Version of + {Major, _Minor, undefined, _} -> + {Major + 1, 0, 0, [0]}; + {Major, Minor, _Patch, _Pre} -> + {Major, Minor + 1, 0, [0]} + end. + +%% @private +-spec matchable_to_string( + {integer(), integer(), 'undefined' | integer(), [binary() | integer()]} +) -> binary(). +matchable_to_string({Major, Minor, Patch, Pre}) -> + Patch1 = + case Patch of + P when P =:= undefined orelse P =:= false -> + <<"0">>; + _ -> + maybe_to_string(Patch) + end, + Pre1 = + case Pre == [] of + true -> + <<>>; + false -> + case Pre of + [0] -> + <<"-0">>; + _ -> + Pre0 = maybe_to_string(Pre), + <<<<"-">>/binary, Pre0/binary>> + end + end, + Major1 = maybe_to_string(Major), + Minor1 = maybe_to_string(Minor), + Patch2 = maybe_to_string(Patch1), + Joined = join_bins([Major1, Minor1, Patch2], <<".">>), + <>. + +%% @private +-spec pre_condition('<' | '>', [binary() | integer()]) -> tuple(). +pre_condition('>', Pre) -> + PreLength = length(Pre), + {'orelse', {'andalso', {'==', {length, '$4'}, 0}, {const, PreLength /= 0}}, + {'andalso', {const, PreLength /= 0}, + {'orelse', {'>', {length, '$4'}, PreLength}, + {'andalso', {'==', {length, '$4'}, PreLength}, {'>', '$4', {const, Pre}}}}}}; +pre_condition('<', Pre) -> + PreLength = length(Pre), + {'orelse', {'andalso', {'/=', {length, '$4'}, 0}, {const, PreLength == 0}}, + {'andalso', {'/=', {length, '$4'}, 0}, + {'orelse', {'<', {length, '$4'}, PreLength}, + {'andalso', {'==', {length, '$4'}, PreLength}, {'<', '$4', {const, Pre}}}}}}. + +%% @private +-spec no_pre_condition([binary() | integer()]) -> tuple(). +no_pre_condition([]) -> + {'orelse', '$5', {'==', {length, '$4'}, 0}}; +no_pre_condition(_) -> + {const, true}. + +%% @private +-spec to_matchspec([operator(), ...]) -> {error, invalid_requirement} | {ok, ets:match_spec()}. +to_matchspec(Lexed) -> + try + case is_valid_requirement(Lexed) of + true -> + First = to_condition(Lexed), + Rest = lists:nthtail(2, Lexed), + {ok, [{{'$1', '$2', '$3', '$4', '$5'}, [to_condition(First, Rest)], ['$_']}]}; + false -> + {error, invalid_requirement} + end + catch + invalid_matchspec -> {error, invalid_requirement} + end. + +%% @private +-spec to_condition([iodata(), ...]) -> tuple(). +to_condition(['==', Version | _]) -> + Matchable = parse_condition(Version), + main_condition('==', Matchable); +to_condition(['!=', Version | _]) -> + Matchable = parse_condition(Version), + main_condition('/=', Matchable); +to_condition(['~>', Version | _]) -> + From = parse_condition(Version, true), + To = approximate_upper(From), + {'andalso', to_condition(['>=', matchable_to_string(From)]), + to_condition(['<', matchable_to_string(To)])}; +to_condition(['>', Version | _]) -> + {Major, Minor, Patch, Pre} = + parse_condition(Version), + {'andalso', + {'orelse', main_condition('>', {Major, Minor, Patch}), + {'andalso', main_condition('==', {Major, Minor, Patch}), pre_condition('>', Pre)}}, + no_pre_condition(Pre)}; +to_condition(['>=', Version | _]) -> + Matchable = parse_condition(Version), + {'orelse', main_condition('==', Matchable), to_condition(['>', Version])}; +to_condition(['<', Version | _]) -> + {Major, Minor, Patch, Pre} = + parse_condition(Version), + {'orelse', main_condition('<', {Major, Minor, Patch}), + {'andalso', main_condition('==', {Major, Minor, Patch}), pre_condition('<', Pre)}}; +to_condition(['<=', Version | _]) -> + Matchable = parse_condition(Version), + {'orelse', main_condition('==', Matchable), to_condition(['<', Version])}. + +%% @private +-spec to_condition(tuple(), list()) -> tuple(). +to_condition(Current, []) -> + Current; +to_condition( + Current, + ['&&', Operator, Version | Rest] +) -> + to_condition( + {'andalso', Current, to_condition([Operator, Version])}, + Rest + ); +to_condition( + Current, + ['||', Operator, Version | Rest] +) -> + to_condition( + {'orelse', Current, to_condition([Operator, Version])}, + Rest + ). + +%% @private +-spec main_condition(any(), tuple()) -> tuple(). +main_condition(Op, Version) when tuple_size(Version) == 3 -> + {Op, {{'$1', '$2', '$3'}}, {const, Version}}; +main_condition(Op, Version) when tuple_size(Version) == 4 -> + {Op, {{'$1', '$2', '$3', '$4'}}, {const, Version}}. + +%% @private +-spec bisect(binary(), binary(), list()) -> [binary() | undefined, ...]. +bisect(Str, Delim, Opts) -> + [First | Rest] = binary:split(Str, [Delim], Opts), + Rest1 = + case Rest of + [] -> + undefined; + _ -> + join_bins(Rest, Delim) + end, + [First, Rest1]. + +%% @private +-spec has_leading_zero(error | undefined | binary() | [binary()]) -> boolean(). +has_leading_zero(<<48/integer, _/integer, _/binary>>) -> + true; +has_leading_zero(_) -> + false. + +%% @private +-spec is_valid_identifier(any()) -> boolean(). +is_valid_identifier(<>) when + is_integer(Char) andalso + Char >= 48 andalso Char =< 57; + is_integer(Char) andalso + Char >= 97 andalso Char =< 122; + is_integer(Char) andalso + Char >= 65 andalso Char =< 90; + Char == 45 +-> + is_valid_identifier(Rest); +is_valid_identifier(<<>>) -> + true; +is_valid_identifier(_) -> + false. + +%% @private +-spec join_bins([binary(), ...], binary()) -> binary(). +join_bins(List, Delim) -> + lists:foldl( + fun(Bin, Acc) -> + case bit_size(Acc) of + N when N > 0 -> + <>; + _ -> + Bin + end + end, + <<>>, + List + ). + +%% @private +-spec maybe_patch(undefined | binary() | integer(), boolean()) -> {ok, undefined | integer()}. +maybe_patch(undefined, true) -> + {ok, undefined}; +maybe_patch(Patch, _) -> + to_digits(Patch). + +%% @private +-spec parse_and_convert(verl:version(), boolean()) -> + {error, invalid_version} + | {ok, + { + integer(), + integer(), + 'undefined' + | integer(), + [ + binary() + | integer() + ], + [binary()] + }}. +parse_and_convert(Str, Approx) -> + [VerPre, Build] = bisect(Str, <<"+">>, [global]), + [Ver, Pre] = bisect(VerPre, <<"-">>, []), + [Maj1, Min1, Patch1, Other] = split_ver(Ver), + case Other of + undefined -> + {ok, Maj2} = to_digits(Maj1), + {ok, Min2} = to_digits(Min1), + {ok, Patch2} = maybe_patch(Patch1, Approx), + {ok, PreParts} = opt_dot_separated(Pre), + {ok, PreParts1} = parts_to_integers(PreParts, []), + {ok, Build2} = opt_dot_separated(Build), + {ok, {Maj2, Min2, Patch2, PreParts1, Build2}}; + _ -> + {error, invalid_version} + end. + +%% @private +-spec parse_digits('error' | 'undefined' | binary() | [binary()], bitstring()) -> + {'error', 'nan'} | {'ok', integer()}. +parse_digits(<>, Acc) when + is_integer(Char) andalso Char >= 48 andalso Char =< 57 +-> + parse_digits(Rest, <>); +parse_digits(<<>>, Acc) when byte_size(Acc) > 0 -> + {ok, binary_to_integer(Acc)}; +parse_digits(_, _) -> + {error, nan}. + +%% @private +-spec parts_to_integers([binary()], [binary() | integer()]) -> + {'error', 'nan'} | {'ok', [binary() | integer()]}. +parts_to_integers([Part | Rest], Acc) -> + case parse_digits(Part, <<>>) of + {ok, Int} -> + case has_leading_zero(Part) of + P when P =:= undefined orelse P =:= false -> + parts_to_integers(Rest, [Int | Acc]); + _ -> + {error, nan} + end; + {error, nan} -> + parts_to_integers(Rest, [Part | Acc]) + end; +parts_to_integers([], Acc) -> + {ok, lists:reverse(Acc)}. + +%% @private +-spec opt_dot_separated('undefined' | binary()) -> {'error', 'bad_part'} | {'ok', [binary()]}. +opt_dot_separated(undefined) -> + {ok, []}; +opt_dot_separated(Str) -> + Parts = binary:split(Str, <<".">>, [global]), + Fun = fun(P) -> + case P /= <<>> of + false -> false; + true -> is_valid_identifier(P) + end + end, + case lists:all(Fun, Parts) of + P when P =:= undefined orelse P =:= false -> + {error, bad_part}; + _ -> + {ok, Parts} + end. + +%% @private +-spec split_ver(binary()) -> ['error' | 'undefined' | binary() | [binary()], ...]. +split_ver(Str) -> + case binary:split(Str, [<<".">>], [global]) of + [Maj0, Min0] -> + [Maj0, Min0, undefined, undefined]; + [Maj, Min, P] -> + [Maj, Min, P, undefined]; + [Major, Minor, Patch | Rest] -> + [Major, Minor, Patch, Rest]; + _ -> + [error, error, error, error] + end. + +%% @private +-spec to_digits('error' | 'undefined' | binary() | [binary()]) -> + {'error', 'leading_zero' | 'nan'} | {'ok', integer()}. +to_digits(Str) -> + case has_leading_zero(Str) of + S when S =:= undefined orelse S =:= false -> + parse_digits(Str, <<>>); + true -> + {error, leading_zero} + end. + +%% @private +-spec maybe_to_string(binary() | [binary() | byte()] | integer()) -> binary(). +maybe_to_string(Part) -> + case Part of + Rewrite when is_binary(Rewrite) -> + Rewrite; + Int when is_integer(Int) -> + integer_to_binary(Int); + Rewrite when is_list(Rewrite) -> + list_to_binary(Rewrite) + end. + +%% @private +-spec is_valid_requirement([operator(), ...]) -> boolean(). +is_valid_requirement([]) -> false; +is_valid_requirement([A | Next]) -> is_valid_requirement(A, Next). + +%% @private +-spec is_valid_requirement(operator(), [operator()]) -> boolean(). +is_valid_requirement(A, []) when is_binary(A) -> + true; +is_valid_requirement(A, [B | Next]) when + (is_atom(A) andalso + is_atom(B)) andalso + (A =:= '&&' orelse A =:= '||') +-> + is_valid_requirement(B, Next); +is_valid_requirement(A, [B | Next]) when + (is_binary(A) andalso + is_atom(B)) andalso + (B =:= '&&' orelse B =:= '||') +-> + is_valid_requirement(B, Next); +is_valid_requirement(A, [B | Next]) when + (is_atom(A) andalso + is_binary(B)) andalso + (A =:= '&&' orelse A =:= '||') +-> + is_valid_requirement(B, Next); +is_valid_requirement(A, [B | Next]) when + is_atom(A) andalso + is_binary(B) +-> + is_valid_requirement(B, Next); +is_valid_requirement(_, _) -> + false. diff --git a/deps/eini/hex_metadata.config b/deps/eini/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..6be832c985f2090cd3d1332e2285e9865e920bd2 --- /dev/null +++ b/deps/eini/hex_metadata.config @@ -0,0 +1,12 @@ +{<<"app">>,<<"eini">>}. +{<<"build_tools">>,[<<"rebar3">>]}. +{<<"description">>,<<"An Erlang INI parser">>}. +{<<"files">>, + [<<"LICENSE">>,<<"README.md">>,<<"rebar.config">>,<<"rebar.lock">>,<<"src">>, + <<"src/eini.app.src">>,<<"src/eini.erl">>,<<"src/eini_lexer.xrl">>, + <<"src/eini_parser.yrl">>]}. +{<<"licenses">>,[<<"Apache-2.0">>]}. +{<<"links">>,[{<<"Github">>,<<"https://github.com/aws-beam/eini-beam">>}]}. +{<<"name">>,<<"eini_beam">>}. +{<<"requirements">>,[]}. +{<<"version">>,<<"2.2.5">>}. diff --git a/deps/eini/rebar.config b/deps/eini/rebar.config new file mode 100644 index 0000000000000000000000000000000000000000..52c1a8d72493f5f3577f786e935307ab05dc6856 --- /dev/null +++ b/deps/eini/rebar.config @@ -0,0 +1,6 @@ +%% -*- mode: erlang; -*- +{erl_opts, [debug_info]}. +{yrl_opts, [{verbose, true}]}. + +{deps, []}. +{plugins, [rebar3_hex]}. diff --git a/deps/eini/rebar.lock b/deps/eini/rebar.lock new file mode 100644 index 0000000000000000000000000000000000000000..57afcca04590ff2bbf2f83b8eac4f856df782c74 --- /dev/null +++ b/deps/eini/rebar.lock @@ -0,0 +1 @@ +[]. diff --git a/deps/eini/src/eini.app.src b/deps/eini/src/eini.app.src new file mode 100644 index 0000000000000000000000000000000000000000..b3f75c66daed47513cf14210bf99572779e42a7b --- /dev/null +++ b/deps/eini/src/eini.app.src @@ -0,0 +1,10 @@ +{application,eini, + [{description,"An Erlang INI parser"}, + {vsn,"2.2.5"}, + {applications,[kernel,stdlib]}, + {modules,[]}, + {registered,[]}, + {licenses,["Apache-2.0"]}, + {links,[{"Github","https://github.com/aws-beam/eini-beam"}]}, + {exclude_files,["src/eini_parser.erl","src/eini_lexer.erl"]}, + {pkg_name,"eini_beam"}]}. diff --git a/deps/eini/src/eini.erl b/deps/eini/src/eini.erl new file mode 100644 index 0000000000000000000000000000000000000000..c81084b0b1de30a2990beb3c28c17d3849ce8979 --- /dev/null +++ b/deps/eini/src/eini.erl @@ -0,0 +1,125 @@ +%% Licensed to the Apache Software Foundation (ASF) under one +%% or more contributor license agreements. See the NOTICE file +%% distributed with this work for additional information +%% regarding copyright ownership. The ASF licenses this file +%% to you under the Apache License, Version 2.0 (the +%% "License"); you may not use this file except in compliance +%% with the License. You may obtain a copy of the License at +%% +%% http://www.apache.org/licenses/LICENSE-2.0 +%% +%% Unless required by applicable law or agreed to in writing, +%% software distributed under the License is distributed on an +%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +%% KIND, either express or implied. See the License for the +%% specific language governing permissions and limitations +%% under the License. + +-module(eini). + +-export([parse/1]). + +%% for debug use +-export([lex/1, parse_tokens/1]). + +-type sections() :: [section()]. +-type section() :: {Title::binary(), [property()]}. +-type property() :: {Key::binary(), Value::binary()}. + +-type reason() :: {illegal_character, Line::integer(), Reason::string()} + | {syntax_error, Line::integer(), Reason::string()} + | {duplicate_title, Title::binary()} + | {duplicate_key, Title::binary(), Key::binary()}. + +-spec parse(Content:: string() | binary()) -> {ok, map()} + | {error, reason()}. +parse(Content) when is_binary(Content) -> + parse(binary_to_list(Content)); + +parse(Content) when is_list(Content) -> + case lex(Content) of + {ok, Tokens} -> + to_map(parse_and_validate(Tokens)); + {error, Reason} -> + {error, Reason} + end. + +parse_and_validate(Tokens) -> + case parse_tokens(Tokens) of + {ok, Parsed} -> + validate(Parsed); + {error, Reason} -> + {error, Reason} + end. + +-spec lex(string()) -> {ok, list(Token::tuple())} + | {error, {illegal_character, Line::integer(), Reason::string()}}. +lex(String) when is_list(String) -> + %% Add \n char at the end if does NOT end by \n + %% TOD(shino): more simple logic? + String2 = case String of + "" -> + "\n"; + _NotEmpty -> + case lists:last(String) of + $\n -> + String; + _ -> + String ++ "\n" + end + end, + case eini_lexer:string(String2) of + {ok, [{break, _Line}|RestTokens], _EndLine} -> + {ok, RestTokens}; + {ok, Tokens, _EndLine} -> + {ok, Tokens}; + {error, {ErrorLine, Mod, Reason}, _EndLine} -> + {error, {illegal_character, ErrorLine, Mod:format_error(Reason)}} + end. + +-spec parse_tokens(Token::tuple()) -> + {ok, sections()} + | {error, {syntax_error, Line::integer(), Reason::string()}}. +parse_tokens(Tokens) -> + case eini_parser:parse(Tokens) of + {ok, Res} -> + {ok, Res}; + {error, {Line, Mod, Reason}} -> + {error, {syntax_error, Line, Mod:format_error(Reason)}} + end. + +-spec validate(sections()) -> + {ok, sections()} + | {error, {duplicate_title, Title::binary()}} + | {error, {duplicate_key, Title::binary(), Key::binary()}}. +validate(Sections) -> + validate(Sections, [], []). + +validate([], _AccTitles, AccSections) -> + {ok, lists:reverse(AccSections)}; +validate([{Title, Properties} = Section | Sections], AccTitles, AccSections) -> + case lists:member(Title, AccTitles) of + true -> + {error, {duplicate_title, Title}}; + false -> + validate(Sections, [Title|AccTitles], [Section|AccSections], Properties, []) + end. + +validate(Sections, AccTitles, AccSections, [], _AccKeys) -> + validate(Sections, AccTitles, AccSections); +validate(Sections, AccTitles, AccSections, [{Key, _Value}|Properties], AccKeys) -> + case lists:member(Key, AccKeys) of + true -> + {error, {duplicate_key, hd(AccTitles), Key}}; + false -> + validate(Sections, AccTitles, AccSections, Properties, [Key|AccKeys]) + end. + +-spec to_map({ok, Sections :: sections()} | {error, Reason :: term()} ) -> {ok, map()} | {error, Reason :: term()}. +to_map({ok, Sections}) -> + {ok, lists:foldl(fun({Section, Properties}, Acc) -> + maps:put(Section, maps:from_list(Properties), Acc) + end, + #{}, + Sections)}; +to_map(Other) -> Other. diff --git a/deps/eini/src/eini_lexer.erl b/deps/eini/src/eini_lexer.erl new file mode 100644 index 0000000000000000000000000000000000000000..b68d3521955415f1fee6c282a846b15e5e82ac9b --- /dev/null +++ b/deps/eini/src/eini_lexer.erl @@ -0,0 +1,641 @@ +-file("/home/saru/.local/share/mise/installs/erlang/28.4.1/lib/parsetools-2.7.1/include/leexinc.hrl", 0). +%% +%% %CopyrightBegin% +%% +%% SPDX-License-Identifier: BSD-2-Clause +%% +%% Copyright (c) 2008,2009 Robert Virding. All rights reserved. +%% Copyright Ericsson AB 2009-2025. All Rights Reserved. +%% +%% Redistribution and use in source and binary forms, with or without +%% modification, are permitted provided that the following conditions +%% are met: +%% +%% 1. Redistributions of source code must retain the above copyright +%% notice, this list of conditions and the following disclaimer. +%% 2. Redistributions in binary form must reproduce the above copyright +%% notice, this list of conditions and the following disclaimer in the +%% documentation and/or other materials provided with the distribution. +%% +%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +%% "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +%% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +%% FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +%% COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +%% INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +%% BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +%% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +%% CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +%% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +%% ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +%% POSSIBILITY OF SUCH DAMAGE. +%% +%% %CopyrightEnd% +%% + +%% The source of this file is part of leex distribution, as such it +%% has the same Copyright as the other files in the leex +%% distribution. However, the resultant scanner generated by leex is the +%% property of the creator of the scanner and is not covered by that +%% Copyright. + +-module(eini_lexer). + +-export([string/1,string/2,token/2,token/3,tokens/2,tokens/3]). +-export([format_error/1]). + +%% User code. This is placed here to allow extra attributes. +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_lexer.xrl", 58). + +-file("/home/saru/.local/share/mise/installs/erlang/28.4.1/lib/parsetools-2.7.1/include/leexinc.hrl", 47). + +format_error({illegal,S}) -> ["illegal characters ",io_lib:write_string(S)]; +format_error({user,S}) -> S. + +%% string(InChars) -> +%% string(InChars, Loc) -> +%% {ok,Tokens,EndLoc} | {error,ErrorInfo,EndLoc}. +%% Loc is the starting location of the token, while EndLoc is the first not scanned +%% location. Location is either Line or {Line,Column}, depending on the "error_location" option. + +string(Ics) -> + string(Ics,1). +string(Ics,L0) -> + string(Ics, L0, 1, Ics, []). +string(Ics, L0, C0, Tcs, Ts) -> + case do_string(Ics, L0, C0, Tcs, Ts) of + {ok, T, {L,_}} -> {ok, T, L}; + {error, {{EL,_},M,D}, {L,_}} -> + EI = {EL,M,D}, + {error, EI, L} + end. + +do_string([], L, C, [], Ts) -> % No partial tokens! + {ok,yyrev(Ts),{L,C}}; +do_string(Ics0, L0, C0, Tcs, Ts) -> + case yystate(yystate(), Ics0, L0, C0, 0, reject, 0) of + {A,Alen,Ics1,L1,_C1} -> % Accepting end state + C2 = adjust_col(Tcs, Alen, C0), + string_cont(Ics1, L1, C2, yyaction(A, Alen, Tcs, L0, C0), Ts); + {A,Alen,Ics1,L1,_C1,_S1} -> % Accepting transition state + C2 = adjust_col(Tcs, Alen, C0), + string_cont(Ics1, L1, C2, yyaction(A, Alen, Tcs, L0, C0), Ts); + {reject,_Alen,Tlen,_Ics1,_L1,_C1,_S1} -> % After a non-accepting state + {error,{{L0, C0} ,?MODULE,{illegal,yypre(Tcs, Tlen+1)}},{L0, C0}}; + {A,Alen,Tlen,_Ics1,L1, C1,_S1}-> + Tcs1 = yysuf(Tcs, Alen), + L2 = adjust_line(Tlen, Alen, Tcs1, L1), + C2 = adjust_col(Tcs, Alen, C1), + string_cont(Tcs1, L2, C2, yyaction(A, Alen, Tcs, L0,C0), Ts) + end. + +%% string_cont(RestChars, Line, Col, Token, Tokens) +%% Test for and remove the end token wrapper. Push back characters +%% are prepended to RestChars. + +-dialyzer({nowarn_function, string_cont/5}). + +string_cont(Rest, Line, Col, {token,T}, Ts) -> + do_string(Rest, Line, Col, Rest, [T|Ts]); +string_cont(Rest, Line, Col, {token,T,Push}, Ts) -> + NewRest = Push ++ Rest, + do_string(NewRest, Line, Col, NewRest, [T|Ts]); +string_cont(Rest, Line, Col, {end_token,T}, Ts) -> + do_string(Rest, Line, Col, Rest, [T|Ts]); +string_cont(Rest, Line, Col, {end_token,T,Push}, Ts) -> + NewRest = Push ++ Rest, + do_string(NewRest, Line, Col, NewRest, [T|Ts]); +string_cont(Rest, Line, Col, skip_token, Ts) -> + do_string(Rest, Line, Col, Rest, Ts); +string_cont(Rest, Line, Col, {skip_token,Push}, Ts) -> + NewRest = Push ++ Rest, + do_string(NewRest, Line, Col, NewRest, Ts); +string_cont(_Rest, Line, Col, {error,S}, _Ts) -> + {error,{{Line, Col},?MODULE,{user,S}},{Line,Col}}. + +%% token(Continuation, Chars) -> +%% token(Continuation, Chars, Loc) -> +%% {more,Continuation} | {done,ReturnVal,RestChars}. +%% Must be careful when re-entering to append the latest characters to the +%% after characters in an accept. The continuation is: +%% {token,State,CurrLine,CurrCol,TokenChars,TokenLen,TokenLine,TokenCol,AccAction,AccLen} + +token(Cont,Chars) -> + token(Cont,Chars,1). +token(Cont, Chars, Line) -> + case do_token(Cont,Chars,Line,1) of + {more, _} = C -> C; + {done, Ret0, R} -> + Ret1 = case Ret0 of + {ok, T, {L,_}} -> {ok, T, L}; + {eof, {L,_}} -> {eof, L}; + {error, {{EL,_},M,D},{L,_}} -> {error, {EL,M,D},L} + end, + {done, Ret1, R} + end. + +do_token([], Chars, Line, Col) -> + token(yystate(), Chars, Line, Col, Chars, 0, Line, Col, reject, 0); +do_token({token,State,Line,Col,Tcs,Tlen,Tline,Tcol,Action,Alen}, Chars, _, _) -> + token(State, Chars, Line, Col, Tcs ++ Chars, Tlen, Tline, Tcol, Action, Alen). + +%% token(State, InChars, Line, Col, TokenChars, TokenLen, TokenLine, TokenCol +%% AcceptAction, AcceptLen) -> +%% {more,Continuation} | {done,ReturnVal,RestChars}. +%% The argument order is chosen to be more efficient. + +token(S0, Ics0, L0, C0, Tcs, Tlen0, Tline, Tcol, A0, Alen0) -> + case yystate(S0, Ics0, L0, C0, Tlen0, A0, Alen0) of + %% Accepting end state, we have a token. + {A1,Alen1,Ics1,L1,C1} -> + C2 = adjust_col(Tcs, Alen1, C1), + token_cont(Ics1, L1, C2, yyaction(A1, Alen1, Tcs, Tline,Tcol)); + %% Accepting transition state, can take more chars. + {A1,Alen1,[],L1,C1,S1} -> % Need more chars to check + {more,{token,S1,L1,C1,Tcs,Alen1,Tline,Tcol,A1,Alen1}}; + {A1,Alen1,Ics1,L1,C1,_S1} -> % Take what we got + C2 = adjust_col(Tcs, Alen1, C1), + token_cont(Ics1, L1, C2, yyaction(A1, Alen1, Tcs, Tline,Tcol)); + %% After a non-accepting state, maybe reach accept state later. + {A1,Alen1,Tlen1,[],L1,C1,S1} -> % Need more chars to check + {more,{token,S1,L1,C1,Tcs,Tlen1,Tline,Tcol,A1,Alen1}}; + {reject,_Alen1,Tlen1,eof,L1,C1,_S1} -> % No token match + %% Check for partial token which is error. + Ret = if Tlen1 > 0 -> {error,{{Tline,Tcol},?MODULE, + %% Skip eof tail in Tcs. + {illegal,yypre(Tcs, Tlen1)}},{L1,C1}}; + true -> {eof,{L1,C1}} + end, + {done,Ret,eof}; + {reject,_Alen1,Tlen1,Ics1,_L1,_C1,_S1} -> % No token match + Error = {{Tline,Tcol},?MODULE,{illegal,yypre(Tcs, Tlen1+1)}}, + {done,{error,Error,{Tline,Tcol}},Ics1}; + {A1,Alen1,Tlen1,_Ics1,L1,_C1,_S1} -> % Use last accept match + Tcs1 = yysuf(Tcs, Alen1), + L2 = adjust_line(Tlen1, Alen1, Tcs1, L1), + C2 = C0 + Alen1, + token_cont(Tcs1, L2, C2, yyaction(A1, Alen1, Tcs, Tline, Tcol)) + end. + +%% token_cont(RestChars, Line, Col, Token) +%% If we have a token or error then return done, else if we have a +%% skip_token then continue. + +-dialyzer({nowarn_function, token_cont/4}). + +token_cont(Rest, Line, Col, {token,T}) -> + {done,{ok,T,{Line,Col}},Rest}; +token_cont(Rest, Line, Col, {token,T,Push}) -> + NewRest = Push ++ Rest, + {done,{ok,T,{Line,Col}},NewRest}; +token_cont(Rest, Line, Col, {end_token,T}) -> + {done,{ok,T,{Line,Col}},Rest}; +token_cont(Rest, Line, Col, {end_token,T,Push}) -> + NewRest = Push ++ Rest, + {done,{ok,T,{Line,Col}},NewRest}; +token_cont(Rest, Line, Col, skip_token) -> + token(yystate(), Rest, Line, Col, Rest, 0, Line, Col, reject, 0); +token_cont(Rest, Line, Col, {skip_token,Push}) -> + NewRest = Push ++ Rest, + token(yystate(), NewRest, Line, Col, NewRest, 0, Line, Col, reject, 0); +token_cont(Rest, Line, Col, {error,S}) -> + {done,{error,{{Line, Col},?MODULE,{user,S}},{Line, Col}},Rest}. + +%% tokens(Continuation, Chars) -> +%% tokens(Continuation, Chars, Loc) -> +%% {more,Continuation} | {done,ReturnVal,RestChars}. +%% Must be careful when re-entering to append the latest characters to the +%% after characters in an accept. The continuation is: +%% {tokens,State,CurrLine,CurrCol,TokenChars,TokenLen,TokenLine,TokenCur,Tokens,AccAction,AccLen} +%% {skip_tokens,State,CurrLine,CurrCol,TokenChars,TokenLen,TokenLine,TokenCur,Error,AccAction,AccLen} + +tokens(Cont,Chars) -> + tokens(Cont,Chars,1). +tokens(Cont, Chars, Line) -> + case do_tokens(Cont,Chars,Line,1) of + {more, _} = C -> C; + {done, Ret0, R} -> + Ret1 = case Ret0 of + {ok, T, {L,_}} -> {ok, T, L}; + {eof, {L,_}} -> {eof, L}; + {error, {{EL,_},M,D},{L,_}} -> {error, {EL,M,D},L} + end, + {done, Ret1, R} + end. + +do_tokens([], Chars, Line, Col) -> + tokens(yystate(), Chars, Line, Col, Chars, 0, Line, Col, [], reject, 0); +do_tokens({tokens,State,Line,Col,Tcs,Tlen,Tline,Tcol,Ts,Action,Alen}, Chars, _,_) -> + tokens(State, Chars, Line, Col, Tcs ++ Chars, Tlen, Tline, Tcol, Ts, Action, Alen); +do_tokens({skip_tokens,State,Line, Col, Tcs,Tlen,Tline,Tcol,Error,Action,Alen}, Chars, _,_) -> + skip_tokens(State, Chars, Line, Col, Tcs ++ Chars, Tlen, Tline, Tcol, Error, Action, Alen). + +%% tokens(State, InChars, Line, Col, TokenChars, TokenLen, TokenLine, TokenCol,Tokens, +%% AcceptAction, AcceptLen) -> +%% {more,Continuation} | {done,ReturnVal,RestChars}. + +tokens(S0, Ics0, L0, C0, Tcs, Tlen0, Tline, Tcol, Ts, A0, Alen0) -> + case yystate(S0, Ics0, L0, C0, Tlen0, A0, Alen0) of + %% Accepting end state, we have a token. + {A1,Alen1,Ics1,L1,C1} -> + C2 = adjust_col(Tcs, Alen1, C1), + tokens_cont(Ics1, L1, C2, yyaction(A1, Alen1, Tcs, Tline, Tcol), Ts); + %% Accepting transition state, can take more chars. + {A1,Alen1,[],L1,C1,S1} -> % Need more chars to check + {more,{tokens,S1,L1,C1,Tcs,Alen1,Tline,Tcol,Ts,A1,Alen1}}; + {A1,Alen1,Ics1,L1,C1,_S1} -> % Take what we got + C2 = adjust_col(Tcs, Alen1, C1), + tokens_cont(Ics1, L1, C2, yyaction(A1, Alen1, Tcs, Tline,Tcol), Ts); + %% After a non-accepting state, maybe reach accept state later. + {A1,Alen1,Tlen1,[],L1,C1,S1} -> % Need more chars to check + {more,{tokens,S1,L1,C1,Tcs,Tlen1,Tline,Tcol,Ts,A1,Alen1}}; + {reject,_Alen1,Tlen1,eof,L1,C1,_S1} -> % No token match + %% Check for partial token which is error, no need to skip here. + Ret = if Tlen1 > 0 -> {error,{{Tline,Tcol},?MODULE, + %% Skip eof tail in Tcs. + {illegal,yypre(Tcs, Tlen1)}},{L1,C1}}; + Ts == [] -> {eof,{L1,C1}}; + true -> {ok,yyrev(Ts),{L1,C1}} + end, + {done,Ret,eof}; + {reject,_Alen1,Tlen1,_Ics1,L1,C1,_S1} -> + %% Skip rest of tokens. + Error = {{L1,C1},?MODULE,{illegal,yypre(Tcs, Tlen1+1)}}, + skip_tokens(yysuf(Tcs, Tlen1+1), L1, C1, Error); + {A1,Alen1,Tlen1,_Ics1,L1,_C1,_S1} -> + Token = yyaction(A1, Alen1, Tcs, Tline,Tcol), + Tcs1 = yysuf(Tcs, Alen1), + L2 = adjust_line(Tlen1, Alen1, Tcs1, L1), + C2 = C0 + Alen1, + tokens_cont(Tcs1, L2, C2, Token, Ts) + end. + +%% tokens_cont(RestChars, Line, Column, Token, Tokens) +%% If we have an end_token or error then return done, else if we have +%% a token then save it and continue, else if we have a skip_token +%% just continue. + +-dialyzer({nowarn_function, tokens_cont/5}). + +tokens_cont(Rest, Line, Col, {token,T}, Ts) -> + tokens(yystate(), Rest, Line, Col, Rest, 0, Line, Col, [T|Ts], reject, 0); +tokens_cont(Rest, Line, Col, {token,T,Push}, Ts) -> + NewRest = Push ++ Rest, + tokens(yystate(), NewRest, Line, Col, NewRest, 0, Line, Col, [T|Ts], reject, 0); +tokens_cont(Rest, Line, Col, {end_token,T}, Ts) -> + {done,{ok,yyrev(Ts, [T]),{Line,Col}},Rest}; +tokens_cont(Rest, Line, Col, {end_token,T,Push}, Ts) -> + NewRest = Push ++ Rest, + {done,{ok,yyrev(Ts, [T]),{Line, Col}},NewRest}; +tokens_cont(Rest, Line, Col, skip_token, Ts) -> + tokens(yystate(), Rest, Line, Col, Rest, 0, Line, Col, Ts, reject, 0); +tokens_cont(Rest, Line, Col, {skip_token,Push}, Ts) -> + NewRest = Push ++ Rest, + tokens(yystate(), NewRest, Line, Col, NewRest, 0, Line, Col, Ts, reject, 0); +tokens_cont(Rest, Line, Col, {error,S}, _Ts) -> + skip_tokens(Rest, Line, Col, {{Line,Col},?MODULE,{user,S}}). + +%% skip_tokens(InChars, Line, Col, Error) -> {done,{error,Error,{Line,Col}},Ics}. +%% Skip tokens until an end token, junk everything and return the error. + +skip_tokens(Ics, Line, Col, Error) -> + skip_tokens(yystate(), Ics, Line, Col, Ics, 0, Line, Col, Error, reject, 0). + +%% skip_tokens(State, InChars, Line, Col, TokenChars, TokenLen, TokenLine, TokenCol, Tokens, +%% AcceptAction, AcceptLen) -> +%% {more,Continuation} | {done,ReturnVal,RestChars}. + +skip_tokens(S0, Ics0, L0, C0, Tcs, Tlen0, Tline, Tcol, Error, A0, Alen0) -> + case yystate(S0, Ics0, L0, C0, Tlen0, A0, Alen0) of + {A1,Alen1,Ics1,L1, C1} -> % Accepting end state + skip_cont(Ics1, L1, C1, yyaction(A1, Alen1, Tcs, Tline, Tcol), Error); + {A1,Alen1,[],L1,C1, S1} -> % After an accepting state + {more,{skip_tokens,S1,L1,C1,Tcs,Alen1,Tline,Tcol,Error,A1,Alen1}}; + {A1,Alen1,Ics1,L1,C1,_S1} -> + skip_cont(Ics1, L1, C1, yyaction(A1, Alen1, Tcs, Tline, Tcol), Error); + {A1,Alen1,Tlen1,[],L1,C1,S1} -> % After a non-accepting state + {more,{skip_tokens,S1,L1,C1,Tcs,Tlen1,Tline,Tcol,Error,A1,Alen1}}; + {reject,_Alen1,_Tlen1,eof,L1,C1,_S1} -> + {done,{error,Error,{L1,C1}},eof}; + {reject,_Alen1,Tlen1,_Ics1,L1,C1,_S1} -> + skip_tokens(yysuf(Tcs, Tlen1+1), L1, C1,Error); + {A1,Alen1,Tlen1,_Ics1,L1,C1,_S1} -> + Token = yyaction(A1, Alen1, Tcs, Tline, Tcol), + Tcs1 = yysuf(Tcs, Alen1), + L2 = adjust_line(Tlen1, Alen1, Tcs1, L1), + skip_cont(Tcs1, L2, C1, Token, Error) + end. + +%% skip_cont(RestChars, Line, Col, Token, Error) +%% Skip tokens until we have an end_token or error then return done +%% with the original rror. + +-dialyzer({nowarn_function, skip_cont/5}). + +skip_cont(Rest, Line, Col, {token,_T}, Error) -> + skip_tokens(yystate(), Rest, Line, Col, Rest, 0, Line, Col, Error, reject, 0); +skip_cont(Rest, Line, Col, {token,_T,Push}, Error) -> + NewRest = Push ++ Rest, + skip_tokens(yystate(), NewRest, Line, Col, NewRest, 0, Line, Col, Error, reject, 0); +skip_cont(Rest, Line, Col, {end_token,_T}, Error) -> + {done,{error,Error,{Line,Col}},Rest}; +skip_cont(Rest, Line, Col, {end_token,_T,Push}, Error) -> + NewRest = Push ++ Rest, + {done,{error,Error,{Line,Col}},NewRest}; +skip_cont(Rest, Line, Col, skip_token, Error) -> + skip_tokens(yystate(), Rest, Line, Col, Rest, 0, Line, Col, Error, reject, 0); +skip_cont(Rest, Line, Col, {skip_token,Push}, Error) -> + NewRest = Push ++ Rest, + skip_tokens(yystate(), NewRest, Line, Col, NewRest, 0, Line, Col, Error, reject, 0); +skip_cont(Rest, Line, Col, {error,_S}, Error) -> + skip_tokens(yystate(), Rest, Line, Col, Rest, 0, Line, Col, Error, reject, 0). + +-compile({nowarn_unused_function, [yyrev/1, yyrev/2, yypre/2, yysuf/2]}). + +yyrev(List) -> lists:reverse(List). +yyrev(List, Tail) -> lists:reverse(List, Tail). +yypre(List, N) -> lists:sublist(List, N). +yysuf(List, N) -> lists:nthtail(N, List). + +%% adjust_line(TokenLength, AcceptLength, Chars, Line) -> NewLine +%% Make sure that newlines in Chars are not counted twice. +%% Line has been updated with respect to newlines in the prefix of +%% Chars consisting of (TokenLength - AcceptLength) characters. + +-compile({nowarn_unused_function, adjust_line/4}). + +adjust_line(N, N, _Cs, L) -> L; +adjust_line(T, A, [$\n|Cs], L) -> + adjust_line(T-1, A, Cs, L-1); +adjust_line(T, A, [_|Cs], L) -> + adjust_line(T-1, A, Cs, L). + +%% adjust_col(Chars, AcceptLength, Col) -> NewCol +%% Handle newlines, tabs and unicode chars. +adjust_col(_, 0, Col) -> + Col; +adjust_col([$\n | R], L, _) -> + adjust_col(R, L-1, 1); +adjust_col([$\t | R], L, Col) -> + adjust_col(R, L-1, tab_forward(Col)+1); +adjust_col([C | R], L, Col) when C>=0 andalso C=< 16#7F -> + adjust_col(R, L-1, Col+1); +adjust_col([C | R], L, Col) when C>= 16#80 andalso C=< 16#7FF -> + adjust_col(R, L-1, Col+2); +adjust_col([C | R], L, Col) when C>= 16#800 andalso C=< 16#FFFF -> + adjust_col(R, L-1, Col+3); +adjust_col([C | R], L, Col) when C>= 16#10000 andalso C=< 16#10FFFF -> + adjust_col(R, L-1, Col+4). + +tab_forward(C) -> + D = C rem tab_size(), + A = tab_size()-D, + C+A. + +tab_size() -> 8. + +%% yystate() -> InitialState. +%% yystate(State, InChars, Line, Col, CurrTokLen, AcceptAction, AcceptLen) -> +%% {Action, AcceptLen, RestChars, Line, Col} | +%% {Action, AcceptLen, RestChars, Line, Col, State} | +%% {reject, AcceptLen, CurrTokLen, RestChars, Line, Col, State} | +%% {Action, AcceptLen, CurrTokLen, RestChars, Line, Col, State}. +%% Generated state transition functions. The non-accepting end state +%% return signal either an unrecognised character or end of current +%% input. + +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_lexer.erl", 372). +yystate() -> 7. + +yystate(10, [96|Ics], Line, Col, Tlen, _, _) -> + yystate(9, Ics, Line, Col, Tlen+1, 6, Tlen); +yystate(10, [95|Ics], Line, Col, Tlen, _, _) -> + yystate(10, Ics, Line, Col, Tlen+1, 6, Tlen); +yystate(10, [94|Ics], Line, Col, Tlen, _, _) -> + yystate(9, Ics, Line, Col, Tlen+1, 6, Tlen); +yystate(10, [92|Ics], Line, Col, Tlen, _, _) -> + yystate(9, Ics, Line, Col, Tlen+1, 6, Tlen); +yystate(10, [62|Ics], Line, Col, Tlen, _, _) -> + yystate(9, Ics, Line, Col, Tlen+1, 6, Tlen); +yystate(10, [63|Ics], Line, Col, Tlen, _, _) -> + yystate(9, Ics, Line, Col, Tlen+1, 6, Tlen); +yystate(10, [60|Ics], Line, Col, Tlen, _, _) -> + yystate(9, Ics, Line, Col, Tlen+1, 6, Tlen); +yystate(10, [58|Ics], Line, Col, Tlen, _, _) -> + yystate(9, Ics, Line, Col, Tlen+1, 6, Tlen); +yystate(10, [11|Ics], Line, Col, Tlen, _, _) -> + yystate(9, Ics, Line, Col, Tlen+1, 6, Tlen); +yystate(10, [12|Ics], Line, Col, Tlen, _, _) -> + yystate(9, Ics, Line, Col, Tlen+1, 6, Tlen); +yystate(10, [C|Ics], Line, Col, Tlen, _, _) when C >= 0, C =< 8 -> + yystate(9, Ics, Line, Col, Tlen+1, 6, Tlen); +yystate(10, [C|Ics], Line, Col, Tlen, _, _) when C >= 14, C =< 31 -> + yystate(9, Ics, Line, Col, Tlen+1, 6, Tlen); +yystate(10, [C|Ics], Line, Col, Tlen, _, _) when C >= 33, C =< 44 -> + yystate(9, Ics, Line, Col, Tlen+1, 6, Tlen); +yystate(10, [C|Ics], Line, Col, Tlen, _, _) when C >= 45, C =< 57 -> + yystate(10, Ics, Line, Col, Tlen+1, 6, Tlen); +yystate(10, [C|Ics], Line, Col, Tlen, _, _) when C >= 64, C =< 90 -> + yystate(10, Ics, Line, Col, Tlen+1, 6, Tlen); +yystate(10, [C|Ics], Line, Col, Tlen, _, _) when C >= 97, C =< 122 -> + yystate(10, Ics, Line, Col, Tlen+1, 6, Tlen); +yystate(10, [C|Ics], Line, Col, Tlen, _, _) when C >= 123 -> + yystate(9, Ics, Line, Col, Tlen+1, 6, Tlen); +yystate(10, Ics, Line, Col, Tlen, _, _) -> + {6,Tlen,Ics,Line,Col,10}; +yystate(9, [92|Ics], Line, Col, Tlen, _, _) -> + yystate(9, Ics, Line, Col, Tlen+1, 7, Tlen); +yystate(9, [60|Ics], Line, Col, Tlen, _, _) -> + yystate(9, Ics, Line, Col, Tlen+1, 7, Tlen); +yystate(9, [11|Ics], Line, Col, Tlen, _, _) -> + yystate(9, Ics, Line, Col, Tlen+1, 7, Tlen); +yystate(9, [12|Ics], Line, Col, Tlen, _, _) -> + yystate(9, Ics, Line, Col, Tlen+1, 7, Tlen); +yystate(9, [C|Ics], Line, Col, Tlen, _, _) when C >= 0, C =< 8 -> + yystate(9, Ics, Line, Col, Tlen+1, 7, Tlen); +yystate(9, [C|Ics], Line, Col, Tlen, _, _) when C >= 14, C =< 31 -> + yystate(9, Ics, Line, Col, Tlen+1, 7, Tlen); +yystate(9, [C|Ics], Line, Col, Tlen, _, _) when C >= 33, C =< 58 -> + yystate(9, Ics, Line, Col, Tlen+1, 7, Tlen); +yystate(9, [C|Ics], Line, Col, Tlen, _, _) when C >= 62, C =< 90 -> + yystate(9, Ics, Line, Col, Tlen+1, 7, Tlen); +yystate(9, [C|Ics], Line, Col, Tlen, _, _) when C >= 94 -> + yystate(9, Ics, Line, Col, Tlen+1, 7, Tlen); +yystate(9, Ics, Line, Col, Tlen, _, _) -> + {7,Tlen,Ics,Line,Col,9}; +yystate(8, [C|Ics], Line, Col, Tlen, _, _) when C >= 0, C =< 9 -> + yystate(8, Ics, Line, Col, Tlen+1, 8, Tlen); +yystate(8, [C|Ics], Line, Col, Tlen, _, _) when C >= 11 -> + yystate(8, Ics, Line, Col, Tlen+1, 8, Tlen); +yystate(8, Ics, Line, Col, Tlen, _, _) -> + {8,Tlen,Ics,Line,Col,8}; +yystate(7, [96|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(9, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [95|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(10, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [94|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(9, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [93|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(3, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [92|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(9, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [91|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(0, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [62|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(9, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [63|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(9, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [61|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(4, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [60|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(9, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [59|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(8, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [58|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(9, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [32|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(5, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [13|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(6, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [11|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(9, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [12|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(9, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [10|Ics], Line, _, Tlen, Action, Alen) -> + yystate(6, Ics, Line+1, 1, Tlen+1, Action, Alen); +yystate(7, [9|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(5, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 0, C =< 8 -> + yystate(9, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 14, C =< 31 -> + yystate(9, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 33, C =< 44 -> + yystate(9, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 45, C =< 57 -> + yystate(10, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 64, C =< 90 -> + yystate(10, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 97, C =< 122 -> + yystate(10, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, [C|Ics], Line, Col, Tlen, Action, Alen) when C >= 123 -> + yystate(9, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(7, Ics, Line, Col, Tlen, Action, Alen) -> + {Action,Alen,Tlen,Ics,Line,Col,7}; +yystate(6, [32|Ics], Line, Col, Tlen, _, _) -> + yystate(1, Ics, Line, Col, Tlen+1, 1, Tlen); +yystate(6, [13|Ics], Line, Col, Tlen, _, _) -> + yystate(2, Ics, Line, Col, Tlen+1, 1, Tlen); +yystate(6, [10|Ics], Line, _, Tlen, _, _) -> + yystate(2, Ics, Line+1, 1, Tlen+1, 1, Tlen); +yystate(6, [9|Ics], Line, Col, Tlen, _, _) -> + yystate(1, Ics, Line, Col, Tlen+1, 1, Tlen); +yystate(6, Ics, Line, Col, Tlen, _, _) -> + {1,Tlen,Ics,Line,Col,6}; +yystate(5, [32|Ics], Line, Col, Tlen, _, _) -> + yystate(5, Ics, Line, Col, Tlen+1, 5, Tlen); +yystate(5, [9|Ics], Line, Col, Tlen, _, _) -> + yystate(5, Ics, Line, Col, Tlen+1, 5, Tlen); +yystate(5, Ics, Line, Col, Tlen, _, _) -> + {5,Tlen,Ics,Line,Col,5}; +yystate(4, Ics, Line, Col, Tlen, _, _) -> + {2,Tlen,Ics,Line,Col}; +yystate(3, Ics, Line, Col, Tlen, _, _) -> + {4,Tlen,Ics,Line,Col}; +yystate(2, [32|Ics], Line, Col, Tlen, _, _) -> + yystate(1, Ics, Line, Col, Tlen+1, 0, Tlen); +yystate(2, [13|Ics], Line, Col, Tlen, _, _) -> + yystate(2, Ics, Line, Col, Tlen+1, 0, Tlen); +yystate(2, [10|Ics], Line, _, Tlen, _, _) -> + yystate(2, Ics, Line+1, 1, Tlen+1, 0, Tlen); +yystate(2, [9|Ics], Line, Col, Tlen, _, _) -> + yystate(1, Ics, Line, Col, Tlen+1, 0, Tlen); +yystate(2, Ics, Line, Col, Tlen, _, _) -> + {0,Tlen,Ics,Line,Col,2}; +yystate(1, [32|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(1, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(1, [13|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(2, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(1, [10|Ics], Line, _, Tlen, Action, Alen) -> + yystate(2, Ics, Line+1, 1, Tlen+1, Action, Alen); +yystate(1, [9|Ics], Line, Col, Tlen, Action, Alen) -> + yystate(1, Ics, Line, Col, Tlen+1, Action, Alen); +yystate(1, Ics, Line, Col, Tlen, Action, Alen) -> + {Action,Alen,Tlen,Ics,Line,Col,1}; +yystate(0, Ics, Line, Col, Tlen, _, _) -> + {3,Tlen,Ics,Line,Col}; +yystate(S, Ics, Line, Col, Tlen, Action, Alen) -> + {Action,Alen,Tlen,Ics,Line,Col,S}. + +%% yyaction(Action, TokenLength, TokenChars, TokenLine, TokenCol) -> +%% {token,Token} | {end_token, Token} | skip_token | {error,String}. +%% Generated action function. + +yyaction(0, _, _, TokenLine, _) -> + yyaction_0(TokenLine); +yyaction(1, _, _, TokenLine, _) -> + yyaction_1(TokenLine); +yyaction(2, _, _, TokenLine, _) -> + yyaction_2(TokenLine); +yyaction(3, _, _, TokenLine, _) -> + yyaction_3(TokenLine); +yyaction(4, _, _, TokenLine, _) -> + yyaction_4(TokenLine); +yyaction(5, TokenLen, YYtcs, TokenLine, _) -> + TokenChars = yypre(YYtcs, TokenLen), + yyaction_5(TokenChars, TokenLine); +yyaction(6, TokenLen, YYtcs, TokenLine, _) -> + TokenChars = yypre(YYtcs, TokenLen), + yyaction_6(TokenChars, TokenLine); +yyaction(7, TokenLen, YYtcs, TokenLine, _) -> + TokenChars = yypre(YYtcs, TokenLen), + yyaction_7(TokenChars, TokenLine); +yyaction(8, TokenLen, YYtcs, TokenLine, _) -> + TokenChars = yypre(YYtcs, TokenLen), + yyaction_8(TokenChars, TokenLine); +yyaction(_, _, _, _, _) -> error. + +-compile({inline,yyaction_0/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_lexer.xrl", 38). +yyaction_0(TokenLine) -> + { token, { break, TokenLine } } . + +-compile({inline,yyaction_1/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_lexer.xrl", 41). +yyaction_1(TokenLine) -> + { token, { break, TokenLine } } . + +-compile({inline,yyaction_2/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_lexer.xrl", 44). +yyaction_2(TokenLine) -> + { token, { '=', TokenLine } } . + +-compile({inline,yyaction_3/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_lexer.xrl", 45). +yyaction_3(TokenLine) -> + { token, { '[', TokenLine } } . + +-compile({inline,yyaction_4/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_lexer.xrl", 46). +yyaction_4(TokenLine) -> + { token, { ']', TokenLine } } . + +-compile({inline,yyaction_5/2}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_lexer.xrl", 49). +yyaction_5(TokenChars, TokenLine) -> + { token, { blank, TokenLine, TokenChars } } . + +-compile({inline,yyaction_6/2}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_lexer.xrl", 50). +yyaction_6(TokenChars, TokenLine) -> + { token, { word, TokenLine, TokenChars } } . + +-compile({inline,yyaction_7/2}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_lexer.xrl", 51). +yyaction_7(TokenChars, TokenLine) -> + { token, { value, TokenLine, TokenChars } } . + +-compile({inline,yyaction_8/2}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_lexer.xrl", 54). +yyaction_8(TokenChars, TokenLine) -> + { token, { comment, TokenLine, TokenChars } } . +-file("/home/saru/.local/share/mise/installs/erlang/28.4.1/lib/parsetools-2.7.1/include/leexinc.hrl", 377). diff --git a/deps/eini/src/eini_lexer.xrl b/deps/eini/src/eini_lexer.xrl new file mode 100644 index 0000000000000000000000000000000000000000..cec9195045db695a6e212c9f705891e8cee8816d --- /dev/null +++ b/deps/eini/src/eini_lexer.xrl @@ -0,0 +1,58 @@ +%% Licensed to the Apache Software Foundation (ASF) under one +%% or more contributor license agreements. See the NOTICE file +%% distributed with this work for additional information +%% regarding copyright ownership. The ASF licenses this file +%% to you under the Apache License, Version 2.0 (the +%% "License"); you may not use this file except in compliance +%% with the License. You may obtain a copy of the License at +%% +%% http://www.apache.org/licenses/LICENSE-2.0 +%% +%% Unless required by applicable law or agreed to in writing, +%% software distributed under the License is distributed on an +%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +%% KIND, either express or implied. See the License for the +%% specific language governing permissions and limitations +%% under the License. + +%% @author: shino@accense.com + +Definitions. + +%% Characters for keys +K = [a-zA-Z0-9_\-\.@/]+ + + +%% \x3b : $; +%% \x3d : $= +%% \x5b : $[ +%% \x5d : $] +V = [^\x3b\x3d\x5b\x5d\x0d\x0a\s\t]+ + + +%% spaces and breaks +S = [\s\t] +B = [\n\r] + +Rules. + +%% skip empty or blank lines or lines with space/tab chars +{B}({S}*{B})+ : {token, {break, TokenLine}}. + +%% mark line break by token 'break' in order to use as delimiters +{B} : {token, {break, TokenLine}}. + +%% Just chars += : {token, {'=', TokenLine}}. +\[ : {token, {'[', TokenLine}}. +\] : {token, {']', TokenLine}}. + +%% word-like tokens +{S}+ : {token, {blank, TokenLine, TokenChars}}. +{K} : {token, {word, TokenLine, TokenChars}}. +{V} : {token, {value, TokenLine, TokenChars}}. + +%% comment-like token, but may be a part of value depending on the location +;.* : {token, {comment, TokenLine, TokenChars}}. + +Erlang code. diff --git a/deps/eini/src/eini_parser.erl b/deps/eini/src/eini_parser.erl new file mode 100644 index 0000000000000000000000000000000000000000..cdda6b00c4e28147efd56b4f64afdecb814294f4 --- /dev/null +++ b/deps/eini/src/eini_parser.erl @@ -0,0 +1,1299 @@ +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 0). +-module(eini_parser). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.erl", 3). +-export([parse/1, parse_and_scan/1, format_error/1]). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 109). + +-spec value_of({atom(), _Line, TokenChars::string()}) -> TokenChars::string(). +value_of(Token) -> + element(3, Token). + +-spec strip_values([TokenChars::string()]) -> Value::binary(). +strip_values(Values) -> + String = string:strip(string:strip(lists:flatten(Values), both, $\s), both, $\t), + list_to_binary(String). + +-file("/home/saru/.local/share/mise/installs/erlang/28.4.1/lib/parsetools-2.7.1/include/yeccpre.hrl", 0). +%% +%% %CopyrightBegin% +%% +%% SPDX-License-Identifier: Apache-2.0 +%% +%% Copyright Ericsson AB 1996-2025. All Rights Reserved. +%% +%% Licensed under the Apache License, Version 2.0 (the "License"); +%% you may not use this file except in compliance with the License. +%% You may obtain a copy of the License at +%% +%% http://www.apache.org/licenses/LICENSE-2.0 +%% +%% Unless required by applicable law or agreed to in writing, software +%% distributed under the License is distributed on an "AS IS" BASIS, +%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +%% See the License for the specific language governing permissions and +%% limitations under the License. +%% +%% %CopyrightEnd% +%% + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% The parser generator will insert appropriate declarations before this line.% + +-type yecc_ret() :: {'error', _} | {'ok', _}. + +-ifdef (YECC_PARSE_DOC). +-doc ?YECC_PARSE_DOC. +-endif. +-spec parse(Tokens :: list()) -> yecc_ret(). +parse(Tokens) -> + yeccpars0(Tokens, {no_func, no_location}, 0, [], []). + +-ifdef (YECC_PARSE_AND_SCAN_DOC). +-doc ?YECC_PARSE_AND_SCAN_DOC. +-endif. +-spec parse_and_scan({function() | {atom(), atom()}, [_]} + | {atom(), atom(), [_]}) -> yecc_ret(). +parse_and_scan({F, A}) -> + yeccpars0([], {{F, A}, no_location}, 0, [], []); +parse_and_scan({M, F, A}) -> + Arity = length(A), + yeccpars0([], {{fun M:F/Arity, A}, no_location}, 0, [], []). + +-ifdef (YECC_FORMAT_ERROR_DOC). +-doc ?YECC_FORMAT_ERROR_DOC. +-endif. +-spec format_error(any()) -> [char() | list()]. +format_error(Message) -> + case io_lib:deep_char_list(Message) of + true -> + Message; + _ -> + io_lib:write(Message) + end. + +%% To be used in grammar files to throw an error message to the parser +%% toplevel. Doesn't have to be exported! +-compile({nowarn_unused_function, return_error/2}). +-spec return_error(erl_anno:location(), any()) -> no_return(). +return_error(Location, Message) -> + throw({error, {Location, ?MODULE, Message}}). + +-define(CODE_VERSION, "1.4"). + +yeccpars0(Tokens, Tzr, State, States, Vstack) -> + try yeccpars1(Tokens, Tzr, State, States, Vstack) + catch + error: Error: Stacktrace -> + try yecc_error_type(Error, Stacktrace) of + Desc -> + erlang:raise(error, {yecc_bug, ?CODE_VERSION, Desc}, + Stacktrace) + catch _:_ -> erlang:raise(error, Error, Stacktrace) + end; + %% Probably thrown from return_error/2: + throw: {error, {_Location, ?MODULE, _M}} = Error -> + Error + end. + +yecc_error_type(function_clause, [{?MODULE,F,ArityOrArgs,_} | _]) -> + case atom_to_list(F) of + "yeccgoto_" ++ SymbolL -> + {ok,[{atom,_,Symbol}],_} = erl_scan:string(SymbolL), + State = case ArityOrArgs of + [S,_,_,_,_,_,_] -> S; + _ -> state_is_unknown + end, + {Symbol, State, missing_in_goto_table} + end. + +yeccpars1([Token | Tokens], Tzr, State, States, Vstack) -> + yeccpars2(State, element(1, Token), States, Vstack, Token, Tokens, Tzr); +yeccpars1([], {{F, A},_Location}, State, States, Vstack) -> + case apply(F, A) of + {ok, Tokens, EndLocation} -> + yeccpars1(Tokens, {{F, A}, EndLocation}, State, States, Vstack); + {eof, EndLocation} -> + yeccpars1([], {no_func, EndLocation}, State, States, Vstack); + {error, Descriptor, _EndLocation} -> + {error, Descriptor} + end; +yeccpars1([], {no_func, no_location}, State, States, Vstack) -> + Line = 999999, + yeccpars2(State, '$end', States, Vstack, yecc_end(Line), [], + {no_func, Line}); +yeccpars1([], {no_func, EndLocation}, State, States, Vstack) -> + yeccpars2(State, '$end', States, Vstack, yecc_end(EndLocation), [], + {no_func, EndLocation}). + +%% yeccpars1/7 is called from generated code. +%% +%% When using the {includefile, Includefile} option, make sure that +%% yeccpars1/7 can be found by parsing the file without following +%% include directives. yecc will otherwise assume that an old +%% yeccpre.hrl is included (one which defines yeccpars1/5). +yeccpars1(State1, State, States, Vstack, Token0, [Token | Tokens], Tzr) -> + yeccpars2(State, element(1, Token), [State1 | States], + [Token0 | Vstack], Token, Tokens, Tzr); +yeccpars1(State1, State, States, Vstack, Token0, [], {{_F,_A}, _Location}=Tzr) -> + yeccpars1([], Tzr, State, [State1 | States], [Token0 | Vstack]); +yeccpars1(State1, State, States, Vstack, Token0, [], {no_func, no_location}) -> + Location = yecctoken_end_location(Token0), + yeccpars2(State, '$end', [State1 | States], [Token0 | Vstack], + yecc_end(Location), [], {no_func, Location}); +yeccpars1(State1, State, States, Vstack, Token0, [], {no_func, Location}) -> + yeccpars2(State, '$end', [State1 | States], [Token0 | Vstack], + yecc_end(Location), [], {no_func, Location}). + +%% For internal use only. +yecc_end(Location) -> + {'$end', Location}. + +yecctoken_end_location(Token) -> + try erl_anno:end_location(element(2, Token)) of + undefined -> yecctoken_location(Token); + Loc -> Loc + catch _:_ -> yecctoken_location(Token) + end. + +-compile({nowarn_unused_function, yeccerror/1}). +yeccerror(Token) -> + Text = yecctoken_to_string(Token), + Location = yecctoken_location(Token), + {error, {Location, ?MODULE, ["syntax error before: ", Text]}}. + +-compile({nowarn_unused_function, yecctoken_to_string/1}). +yecctoken_to_string(Token) -> + try erl_scan:text(Token) of + undefined -> yecctoken2string(Token); + Txt -> Txt + catch _:_ -> yecctoken2string(Token) + end. + +yecctoken_location(Token) -> + try erl_scan:location(Token) + catch _:_ -> element(2, Token) + end. + +-compile({nowarn_unused_function, yecctoken2string/1}). +yecctoken2string(Token) -> + try + yecctoken2string1(Token) + catch + _:_ -> + io_lib:format("~tp", [Token]) + end. + +-compile({nowarn_unused_function, yecctoken2string1/1}). +yecctoken2string1({atom, _, A}) -> io_lib:write_atom(A); +yecctoken2string1({integer,_,N}) -> io_lib:write(N); +yecctoken2string1({float,_,F}) -> io_lib:write(F); +yecctoken2string1({char,_,C}) -> io_lib:write_char(C); +yecctoken2string1({var,_,V}) -> io_lib:format("~s", [V]); +yecctoken2string1({string,_,S}) -> io_lib:write_string(S); +yecctoken2string1({reserved_symbol, _, A}) -> io_lib:write(A); +yecctoken2string1({_Cat, _, Val}) -> io_lib:format("~tp", [Val]); +yecctoken2string1({dot, _}) -> "'.'"; +yecctoken2string1({'$end', _}) -> []; +yecctoken2string1({Other, _}) when is_atom(Other) -> + io_lib:write_atom(Other); +yecctoken2string1(Other) -> + io_lib:format("~tp", [Other]). + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + + +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.erl", 206). + +-dialyzer({nowarn_function, yeccpars2/7}). +-compile({nowarn_unused_function, yeccpars2/7}). +yeccpars2(0=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_0(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(1=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_1(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(2=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_2(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(3=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_3(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(4=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_4(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(5=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_5(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(6=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_6(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(7=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_7(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(8=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_8(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(9=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_9(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(10=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_10(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(11=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_11(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(12=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_12(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(13=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_13(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(14=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_14(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(15=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_15(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(16=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_16(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(17=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_17(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(18=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_18(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(19=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_19(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(20=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_20(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(21=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_21(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(22=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_22(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(23=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_23(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(24=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_24(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(25=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_25(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(26=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_26(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(27=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_27(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(28=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_28(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(29=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_29(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(30=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_30(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(31=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_31(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(32=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_32(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(33=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_33(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(34=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_34(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(35=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_35(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(36=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_36(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(37=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_37(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(38=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_38(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(39=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_39(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(40=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_40(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(41=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_41(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(42=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_42(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(43=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_43(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(44=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_44(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(45=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_45(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(46=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_46(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(47=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_47(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(48=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_48(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(49=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_49(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(50=S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_50(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(51=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_51(S, Cat, Ss, Stack, T, Ts, Tzr); +%% yeccpars2(52=S, Cat, Ss, Stack, T, Ts, Tzr) -> +%% yeccpars2_52(S, Cat, Ss, Stack, T, Ts, Tzr); +yeccpars2(Other, _, _, _, _, _, _) -> + erlang:error({yecc_bug,"1.4",{missing_state_in_action_table, Other}}). + +-dialyzer({nowarn_function, yeccpars2_0/7}). +-compile({nowarn_unused_function, yeccpars2_0/7}). +yeccpars2_0(S, '[', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 10, Ss, Stack, T, Ts, Tzr); +yeccpars2_0(S, 'blank', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 11, Ss, Stack, T, Ts, Tzr); +yeccpars2_0(S, 'comment', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 12, Ss, Stack, T, Ts, Tzr); +yeccpars2_0(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_0_(Stack), + yeccpars2_6(_S, Cat, [0 | Ss], NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_1/7}). +-compile({nowarn_unused_function, yeccpars2_1/7}). +yeccpars2_1(_S, '$end', _Ss, Stack, _T, _Ts, _Tzr) -> + {ok, hd(Stack)}; +yeccpars2_1(_, _, _, _, T, _, _) -> + yeccerror(T). + +-dialyzer({nowarn_function, yeccpars2_2/7}). +-compile({nowarn_unused_function, yeccpars2_2/7}). +yeccpars2_2(S, 'blank', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 34, Ss, Stack, T, Ts, Tzr); +yeccpars2_2(S, 'word', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 35, Ss, Stack, T, Ts, Tzr); +yeccpars2_2(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_2_(Stack), + yeccpars2_32(_S, Cat, [2 | Ss], NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_3/7}). +-compile({nowarn_unused_function, yeccpars2_3/7}). +yeccpars2_3(S, 'blank', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 25, Ss, Stack, T, Ts, Tzr); +yeccpars2_3(S, 'break', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 26, Ss, Stack, T, Ts, Tzr); +yeccpars2_3(_, _, _, _, T, _, _) -> + yeccerror(T). + +-dialyzer({nowarn_function, yeccpars2_4/7}). +-compile({nowarn_unused_function, yeccpars2_4/7}). +yeccpars2_4(S, '[', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 10, Ss, Stack, T, Ts, Tzr); +yeccpars2_4(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_4_(Stack), + yeccpars2_24(_S, Cat, [4 | Ss], NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_5/7}). +-compile({nowarn_unused_function, yeccpars2_5/7}). +yeccpars2_5(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_5_(Stack), + yeccgoto_whole(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_6/7}). +-compile({nowarn_unused_function, yeccpars2_6/7}). +yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_6_(Stack), + yeccgoto_sections_with_skip_lines(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_7/7}). +-compile({nowarn_unused_function, yeccpars2_7/7}). +yeccpars2_7(S, '[', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 10, Ss, Stack, T, Ts, Tzr); +yeccpars2_7(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_7_(Stack), + yeccpars2_23(_S, Cat, [7 | Ss], NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_8/7}). +-compile({nowarn_unused_function, yeccpars2_8/7}). +yeccpars2_8(S, 'comment', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 12, Ss, Stack, T, Ts, Tzr); +yeccpars2_8(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_8_(Stack), + yeccgoto_skip_lines(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_9/7}). +-compile({nowarn_unused_function, yeccpars2_9/7}). +yeccpars2_9(S, '[', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 10, Ss, Stack, T, Ts, Tzr); +yeccpars2_9(S, 'comment', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 12, Ss, Stack, T, Ts, Tzr); +yeccpars2_9(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_9_(Stack), + yeccpars2_6(_S, Cat, [9 | Ss], NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_10/7}). +-compile({nowarn_unused_function, yeccpars2_10/7}). +yeccpars2_10(S, 'blank', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 17, Ss, Stack, T, Ts, Tzr); +yeccpars2_10(S, 'word', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 18, Ss, Stack, T, Ts, Tzr); +yeccpars2_10(_, _, _, _, T, _, _) -> + yeccerror(T). + +-dialyzer({nowarn_function, yeccpars2_11/7}). +-compile({nowarn_unused_function, yeccpars2_11/7}). +yeccpars2_11(S, 'break', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 14, Ss, Stack, T, Ts, Tzr); +yeccpars2_11(_, _, _, _, T, _, _) -> + yeccerror(T). + +-dialyzer({nowarn_function, yeccpars2_12/7}). +-compile({nowarn_unused_function, yeccpars2_12/7}). +yeccpars2_12(S, 'break', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 13, Ss, Stack, T, Ts, Tzr); +yeccpars2_12(_, _, _, _, T, _, _) -> + yeccerror(T). + +-dialyzer({nowarn_function, yeccpars2_13/7}). +-compile({nowarn_unused_function, yeccpars2_13/7}). +yeccpars2_13(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_|Nss] = Ss, + NewStack = yeccpars2_13_(Stack), + yeccgoto_comment_line(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_14/7}). +-compile({nowarn_unused_function, yeccpars2_14/7}). +yeccpars2_14(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_|Nss] = Ss, + NewStack = yeccpars2_14_(Stack), + yeccgoto_blank_line(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_15/7}). +-compile({nowarn_unused_function, yeccpars2_15/7}). +yeccpars2_15(S, ']', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 20, Ss, Stack, T, Ts, Tzr); +yeccpars2_15(_, _, _, _, T, _, _) -> + yeccerror(T). + +-dialyzer({nowarn_function, yeccpars2_16/7}). +-compile({nowarn_unused_function, yeccpars2_16/7}). +yeccpars2_16(S, 'blank', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 17, Ss, Stack, T, Ts, Tzr); +yeccpars2_16(S, 'word', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 18, Ss, Stack, T, Ts, Tzr); +yeccpars2_16(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_16_(Stack), + yeccgoto_title_words(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_17/7}). +-compile({nowarn_unused_function, yeccpars2_17/7}). +yeccpars2_17(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_17_(Stack), + yeccgoto_title_word(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_18/7}). +-compile({nowarn_unused_function, yeccpars2_18/7}). +yeccpars2_18(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_18_(Stack), + yeccgoto_title_word(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_19/7}). +-compile({nowarn_unused_function, yeccpars2_19/7}). +yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_|Nss] = Ss, + NewStack = yeccpars2_19_(Stack), + yeccgoto_title_words(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_20/7}). +-compile({nowarn_unused_function, yeccpars2_20/7}). +yeccpars2_20(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_,_|Nss] = Ss, + NewStack = yeccpars2_20_(Stack), + yeccgoto_title(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_21/7}). +-compile({nowarn_unused_function, yeccpars2_21/7}). +yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_|Nss] = Ss, + NewStack = yeccpars2_21_(Stack), + yeccgoto_whole(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_22/7}). +-compile({nowarn_unused_function, yeccpars2_22/7}). +yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_|Nss] = Ss, + NewStack = yeccpars2_22_(Stack), + yeccgoto_skip_lines(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_23/7}). +-compile({nowarn_unused_function, yeccpars2_23/7}). +yeccpars2_23(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_|Nss] = Ss, + NewStack = yeccpars2_23_(Stack), + yeccgoto_sections(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_24/7}). +-compile({nowarn_unused_function, yeccpars2_24/7}). +yeccpars2_24(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_|Nss] = Ss, + NewStack = yeccpars2_24_(Stack), + yeccgoto_sections_with_skip_lines(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_25/7}). +-compile({nowarn_unused_function, yeccpars2_25/7}). +yeccpars2_25(S, 'break', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 28, Ss, Stack, T, Ts, Tzr); +yeccpars2_25(_, _, _, _, T, _, _) -> + yeccerror(T). + +-dialyzer({nowarn_function, yeccpars2_26/7}). +-compile({nowarn_unused_function, yeccpars2_26/7}). +yeccpars2_26(S, 'comment', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 12, Ss, Stack, T, Ts, Tzr); +yeccpars2_26(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_|Nss] = Ss, + NewStack = yeccpars2_26_(Stack), + yeccgoto_title_part(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_27/7}). +-compile({nowarn_unused_function, yeccpars2_27/7}). +yeccpars2_27(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_,_|Nss] = Ss, + NewStack = yeccpars2_27_(Stack), + yeccgoto_title_part(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_28/7}). +-compile({nowarn_unused_function, yeccpars2_28/7}). +yeccpars2_28(S, 'comment', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 12, Ss, Stack, T, Ts, Tzr); +yeccpars2_28(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_,_|Nss] = Ss, + NewStack = yeccpars2_28_(Stack), + yeccgoto_title_part(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_29/7}). +-compile({nowarn_unused_function, yeccpars2_29/7}). +yeccpars2_29(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_,_,_|Nss] = Ss, + NewStack = yeccpars2_29_(Stack), + yeccgoto_title_part(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_30/7}). +-compile({nowarn_unused_function, yeccpars2_30/7}). +yeccpars2_30(S, 'blank', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 34, Ss, Stack, T, Ts, Tzr); +yeccpars2_30(S, 'word', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 35, Ss, Stack, T, Ts, Tzr); +yeccpars2_30(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_30_(Stack), + yeccpars2_52(_S, Cat, [30 | Ss], NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_31/7}). +-compile({nowarn_unused_function, yeccpars2_31/7}). +yeccpars2_31(S, 'comment', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 12, Ss, Stack, T, Ts, Tzr); +yeccpars2_31(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_31_(Stack), + yeccgoto_property_with_skip_lines(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_32/7}). +-compile({nowarn_unused_function, yeccpars2_32/7}). +yeccpars2_32(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_|Nss] = Ss, + NewStack = yeccpars2_32_(Stack), + yeccgoto_section(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_33/7}). +-compile({nowarn_unused_function, yeccpars2_33/7}). +yeccpars2_33(S, '=', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 39, Ss, Stack, T, Ts, Tzr); +yeccpars2_33(_, _, _, _, T, _, _) -> + yeccerror(T). + +-dialyzer({nowarn_function, yeccpars2_34/7}). +-compile({nowarn_unused_function, yeccpars2_34/7}). +yeccpars2_34(S, 'word', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 37, Ss, Stack, T, Ts, Tzr); +yeccpars2_34(_, _, _, _, T, _, _) -> + yeccerror(T). + +-dialyzer({nowarn_function, yeccpars2_35/7}). +-compile({nowarn_unused_function, yeccpars2_35/7}). +yeccpars2_35(S, 'blank', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 36, Ss, Stack, T, Ts, Tzr); +yeccpars2_35(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_35_(Stack), + yeccgoto_key_part(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_36/7}). +-compile({nowarn_unused_function, yeccpars2_36/7}). +yeccpars2_36(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_|Nss] = Ss, + NewStack = yeccpars2_36_(Stack), + yeccgoto_key_part(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_37/7}). +-compile({nowarn_unused_function, yeccpars2_37/7}). +yeccpars2_37(S, 'blank', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 38, Ss, Stack, T, Ts, Tzr); +yeccpars2_37(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_|Nss] = Ss, + NewStack = yeccpars2_37_(Stack), + yeccgoto_key_part(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_38/7}). +-compile({nowarn_unused_function, yeccpars2_38/7}). +yeccpars2_38(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_,_|Nss] = Ss, + NewStack = yeccpars2_38_(Stack), + yeccgoto_key_part(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_39/7}). +-compile({nowarn_unused_function, yeccpars2_39/7}). +yeccpars2_39(S, '=', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 42, Ss, Stack, T, Ts, Tzr); +yeccpars2_39(S, '[', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 43, Ss, Stack, T, Ts, Tzr); +yeccpars2_39(S, ']', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 44, Ss, Stack, T, Ts, Tzr); +yeccpars2_39(S, 'blank', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 45, Ss, Stack, T, Ts, Tzr); +yeccpars2_39(S, 'comment', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 46, Ss, Stack, T, Ts, Tzr); +yeccpars2_39(S, 'value', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 47, Ss, Stack, T, Ts, Tzr); +yeccpars2_39(S, 'word', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 48, Ss, Stack, T, Ts, Tzr); +yeccpars2_39(_, _, _, _, T, _, _) -> + yeccerror(T). + +-dialyzer({nowarn_function, yeccpars2_40/7}). +-compile({nowarn_unused_function, yeccpars2_40/7}). +yeccpars2_40(S, 'break', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 50, Ss, Stack, T, Ts, Tzr); +yeccpars2_40(_, _, _, _, T, _, _) -> + yeccerror(T). + +-dialyzer({nowarn_function, yeccpars2_41/7}). +-compile({nowarn_unused_function, yeccpars2_41/7}). +yeccpars2_41(S, '=', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 42, Ss, Stack, T, Ts, Tzr); +yeccpars2_41(S, '[', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 43, Ss, Stack, T, Ts, Tzr); +yeccpars2_41(S, ']', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 44, Ss, Stack, T, Ts, Tzr); +yeccpars2_41(S, 'blank', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 45, Ss, Stack, T, Ts, Tzr); +yeccpars2_41(S, 'comment', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 46, Ss, Stack, T, Ts, Tzr); +yeccpars2_41(S, 'value', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 47, Ss, Stack, T, Ts, Tzr); +yeccpars2_41(S, 'word', Ss, Stack, T, Ts, Tzr) -> + yeccpars1(S, 48, Ss, Stack, T, Ts, Tzr); +yeccpars2_41(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_41_(Stack), + yeccgoto_values(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_42/7}). +-compile({nowarn_unused_function, yeccpars2_42/7}). +yeccpars2_42(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_42_(Stack), + yeccgoto_single_value(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_43/7}). +-compile({nowarn_unused_function, yeccpars2_43/7}). +yeccpars2_43(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_43_(Stack), + yeccgoto_single_value(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_44/7}). +-compile({nowarn_unused_function, yeccpars2_44/7}). +yeccpars2_44(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_44_(Stack), + yeccgoto_single_value(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_45/7}). +-compile({nowarn_unused_function, yeccpars2_45/7}). +yeccpars2_45(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_45_(Stack), + yeccgoto_single_value(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_46/7}). +-compile({nowarn_unused_function, yeccpars2_46/7}). +yeccpars2_46(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_46_(Stack), + yeccgoto_single_value(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_47/7}). +-compile({nowarn_unused_function, yeccpars2_47/7}). +yeccpars2_47(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_47_(Stack), + yeccgoto_single_value(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_48/7}). +-compile({nowarn_unused_function, yeccpars2_48/7}). +yeccpars2_48(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + NewStack = yeccpars2_48_(Stack), + yeccgoto_single_value(hd(Ss), Cat, Ss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_49/7}). +-compile({nowarn_unused_function, yeccpars2_49/7}). +yeccpars2_49(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_|Nss] = Ss, + NewStack = yeccpars2_49_(Stack), + yeccgoto_values(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_50/7}). +-compile({nowarn_unused_function, yeccpars2_50/7}). +yeccpars2_50(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_,_,_|Nss] = Ss, + NewStack = yeccpars2_50_(Stack), + yeccgoto_property(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_51/7}). +-compile({nowarn_unused_function, yeccpars2_51/7}). +yeccpars2_51(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_|Nss] = Ss, + NewStack = yeccpars2_51_(Stack), + yeccgoto_property_with_skip_lines(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccpars2_52/7}). +-compile({nowarn_unused_function, yeccpars2_52/7}). +yeccpars2_52(_S, Cat, Ss, Stack, T, Ts, Tzr) -> + [_|Nss] = Ss, + NewStack = yeccpars2_52_(Stack), + yeccgoto_properties(hd(Nss), Cat, Nss, NewStack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccgoto_blank_line/7}). +-compile({nowarn_unused_function, yeccgoto_blank_line/7}). +yeccgoto_blank_line(0, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_9(9, Cat, Ss, Stack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccgoto_comment_line/7}). +-compile({nowarn_unused_function, yeccgoto_comment_line/7}). +yeccgoto_comment_line(0, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_8(8, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_comment_line(8, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_8(8, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_comment_line(9, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_8(8, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_comment_line(26, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_8(8, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_comment_line(28, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_8(8, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_comment_line(31, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_8(8, Cat, Ss, Stack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccgoto_key_part/7}). +-compile({nowarn_unused_function, yeccgoto_key_part/7}). +yeccgoto_key_part(2, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_33(33, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_key_part(30, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_33(33, Cat, Ss, Stack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccgoto_properties/7}). +-compile({nowarn_unused_function, yeccgoto_properties/7}). +yeccgoto_properties(2=_S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_32(_S, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_properties(30=_S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_52(_S, Cat, Ss, Stack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccgoto_property/7}). +-compile({nowarn_unused_function, yeccgoto_property/7}). +yeccgoto_property(2, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_31(31, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_property(30, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_31(31, Cat, Ss, Stack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccgoto_property_with_skip_lines/7}). +-compile({nowarn_unused_function, yeccgoto_property_with_skip_lines/7}). +yeccgoto_property_with_skip_lines(2, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_30(30, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_property_with_skip_lines(30, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_30(30, Cat, Ss, Stack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccgoto_section/7}). +-compile({nowarn_unused_function, yeccgoto_section/7}). +yeccgoto_section(0, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_7(7, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_section(4, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_7(7, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_section(7, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_7(7, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_section(9, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_7(7, Cat, Ss, Stack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccgoto_sections/7}). +-compile({nowarn_unused_function, yeccgoto_sections/7}). +yeccgoto_sections(0=_S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_sections(4=_S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_24(_S, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_sections(7=_S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_23(_S, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_sections(9=_S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_6(_S, Cat, Ss, Stack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccgoto_sections_with_skip_lines/7}). +-compile({nowarn_unused_function, yeccgoto_sections_with_skip_lines/7}). +yeccgoto_sections_with_skip_lines(0=_S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_5(_S, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_sections_with_skip_lines(9=_S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_21(_S, Cat, Ss, Stack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccgoto_single_value/7}). +-compile({nowarn_unused_function, yeccgoto_single_value/7}). +yeccgoto_single_value(39, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_41(41, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_single_value(41, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_41(41, Cat, Ss, Stack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccgoto_skip_lines/7}). +-compile({nowarn_unused_function, yeccgoto_skip_lines/7}). +yeccgoto_skip_lines(0, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_skip_lines(8=_S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_22(_S, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_skip_lines(9, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_4(4, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_skip_lines(26=_S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_27(_S, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_skip_lines(28=_S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_29(_S, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_skip_lines(31=_S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_51(_S, Cat, Ss, Stack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccgoto_title/7}). +-compile({nowarn_unused_function, yeccgoto_title/7}). +yeccgoto_title(0, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_3(3, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_title(4, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_3(3, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_title(7, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_3(3, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_title(9, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_3(3, Cat, Ss, Stack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccgoto_title_part/7}). +-compile({nowarn_unused_function, yeccgoto_title_part/7}). +yeccgoto_title_part(0, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_2(2, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_title_part(4, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_2(2, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_title_part(7, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_2(2, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_title_part(9, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_2(2, Cat, Ss, Stack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccgoto_title_word/7}). +-compile({nowarn_unused_function, yeccgoto_title_word/7}). +yeccgoto_title_word(10, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_16(16, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_title_word(16, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_16(16, Cat, Ss, Stack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccgoto_title_words/7}). +-compile({nowarn_unused_function, yeccgoto_title_words/7}). +yeccgoto_title_words(10, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_15(15, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_title_words(16=_S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_19(_S, Cat, Ss, Stack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccgoto_values/7}). +-compile({nowarn_unused_function, yeccgoto_values/7}). +yeccgoto_values(39, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_40(40, Cat, Ss, Stack, T, Ts, Tzr); +yeccgoto_values(41=_S, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_49(_S, Cat, Ss, Stack, T, Ts, Tzr). + +-dialyzer({nowarn_function, yeccgoto_whole/7}). +-compile({nowarn_unused_function, yeccgoto_whole/7}). +yeccgoto_whole(0, Cat, Ss, Stack, T, Ts, Tzr) -> + yeccpars2_1(1, Cat, Ss, Stack, T, Ts, Tzr). + +-compile({inline,yeccpars2_0_/1}). +-dialyzer({nowarn_function, yeccpars2_0_/1}). +-compile({nowarn_unused_function, yeccpars2_0_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 61). +yeccpars2_0_(__Stack0) -> + [begin + [] + end | __Stack0]. + +-compile({inline,yeccpars2_2_/1}). +-dialyzer({nowarn_function, yeccpars2_2_/1}). +-compile({nowarn_unused_function, yeccpars2_2_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 79). +yeccpars2_2_(__Stack0) -> + [begin + [] + end | __Stack0]. + +-compile({inline,yeccpars2_4_/1}). +-dialyzer({nowarn_function, yeccpars2_4_/1}). +-compile({nowarn_unused_function, yeccpars2_4_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 61). +yeccpars2_4_(__Stack0) -> + [begin + [] + end | __Stack0]. + +-compile({inline,yeccpars2_5_/1}). +-dialyzer({nowarn_function, yeccpars2_5_/1}). +-compile({nowarn_unused_function, yeccpars2_5_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 44). +yeccpars2_5_(__Stack0) -> + [___1 | __Stack] = __Stack0, + [begin + ___1 + end | __Stack]. + +-compile({inline,yeccpars2_6_/1}). +-dialyzer({nowarn_function, yeccpars2_6_/1}). +-compile({nowarn_unused_function, yeccpars2_6_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 58). +yeccpars2_6_(__Stack0) -> + [___1 | __Stack] = __Stack0, + [begin + ___1 + end | __Stack]. + +-compile({inline,yeccpars2_7_/1}). +-dialyzer({nowarn_function, yeccpars2_7_/1}). +-compile({nowarn_unused_function, yeccpars2_7_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 61). +yeccpars2_7_(__Stack0) -> + [begin + [] + end | __Stack0]. + +-compile({inline,yeccpars2_8_/1}). +-dialyzer({nowarn_function, yeccpars2_8_/1}). +-compile({nowarn_unused_function, yeccpars2_8_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 53). +yeccpars2_8_(__Stack0) -> + [___1 | __Stack] = __Stack0, + [begin + [___1] + end | __Stack]. + +-compile({inline,yeccpars2_9_/1}). +-dialyzer({nowarn_function, yeccpars2_9_/1}). +-compile({nowarn_unused_function, yeccpars2_9_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 61). +yeccpars2_9_(__Stack0) -> + [begin + [] + end | __Stack0]. + +-compile({inline,yeccpars2_13_/1}). +-dialyzer({nowarn_function, yeccpars2_13_/1}). +-compile({nowarn_unused_function, yeccpars2_13_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 56). +yeccpars2_13_(__Stack0) -> + [___2,___1 | __Stack] = __Stack0, + [begin + ___1 + end | __Stack]. + +-compile({inline,yeccpars2_14_/1}). +-dialyzer({nowarn_function, yeccpars2_14_/1}). +-compile({nowarn_unused_function, yeccpars2_14_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 47). +yeccpars2_14_(__Stack0) -> + [___2,___1 | __Stack] = __Stack0, + [begin + ___1 + end | __Stack]. + +-compile({inline,yeccpars2_16_/1}). +-dialyzer({nowarn_function, yeccpars2_16_/1}). +-compile({nowarn_unused_function, yeccpars2_16_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 74). +yeccpars2_16_(__Stack0) -> + [___1 | __Stack] = __Stack0, + [begin + [___1] + end | __Stack]. + +-compile({inline,yeccpars2_17_/1}). +-dialyzer({nowarn_function, yeccpars2_17_/1}). +-compile({nowarn_unused_function, yeccpars2_17_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 72). +yeccpars2_17_(__Stack0) -> + [___1 | __Stack] = __Stack0, + [begin + value_of(___1) + end | __Stack]. + +-compile({inline,yeccpars2_18_/1}). +-dialyzer({nowarn_function, yeccpars2_18_/1}). +-compile({nowarn_unused_function, yeccpars2_18_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 71). +yeccpars2_18_(__Stack0) -> + [___1 | __Stack] = __Stack0, + [begin + value_of(___1) + end | __Stack]. + +-compile({inline,yeccpars2_19_/1}). +-dialyzer({nowarn_function, yeccpars2_19_/1}). +-compile({nowarn_unused_function, yeccpars2_19_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 75). +yeccpars2_19_(__Stack0) -> + [___2,___1 | __Stack] = __Stack0, + [begin + [___1 | ___2] + end | __Stack]. + +-compile({inline,yeccpars2_20_/1}). +-dialyzer({nowarn_function, yeccpars2_20_/1}). +-compile({nowarn_unused_function, yeccpars2_20_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 77). +yeccpars2_20_(__Stack0) -> + [___3,___2,___1 | __Stack] = __Stack0, + [begin + string:strip(lists:flatten(___2), both, $\s) + end | __Stack]. + +-compile({inline,yeccpars2_21_/1}). +-dialyzer({nowarn_function, yeccpars2_21_/1}). +-compile({nowarn_unused_function, yeccpars2_21_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 45). +yeccpars2_21_(__Stack0) -> + [___2,___1 | __Stack] = __Stack0, + [begin + ___2 + end | __Stack]. + +-compile({inline,yeccpars2_22_/1}). +-dialyzer({nowarn_function, yeccpars2_22_/1}). +-compile({nowarn_unused_function, yeccpars2_22_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 54). +yeccpars2_22_(__Stack0) -> + [___2,___1 | __Stack] = __Stack0, + [begin + [___1, ___2] + end | __Stack]. + +-compile({inline,yeccpars2_23_/1}). +-dialyzer({nowarn_function, yeccpars2_23_/1}). +-compile({nowarn_unused_function, yeccpars2_23_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 62). +yeccpars2_23_(__Stack0) -> + [___2,___1 | __Stack] = __Stack0, + [begin + [___1 | ___2] + end | __Stack]. + +-compile({inline,yeccpars2_24_/1}). +-dialyzer({nowarn_function, yeccpars2_24_/1}). +-compile({nowarn_unused_function, yeccpars2_24_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 59). +yeccpars2_24_(__Stack0) -> + [___2,___1 | __Stack] = __Stack0, + [begin + ___2 + end | __Stack]. + +-compile({inline,yeccpars2_26_/1}). +-dialyzer({nowarn_function, yeccpars2_26_/1}). +-compile({nowarn_unused_function, yeccpars2_26_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 66). +yeccpars2_26_(__Stack0) -> + [___2,___1 | __Stack] = __Stack0, + [begin + list_to_binary(___1) + end | __Stack]. + +-compile({inline,yeccpars2_27_/1}). +-dialyzer({nowarn_function, yeccpars2_27_/1}). +-compile({nowarn_unused_function, yeccpars2_27_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 68). +yeccpars2_27_(__Stack0) -> + [___3,___2,___1 | __Stack] = __Stack0, + [begin + list_to_binary(___1) + end | __Stack]. + +-compile({inline,yeccpars2_28_/1}). +-dialyzer({nowarn_function, yeccpars2_28_/1}). +-compile({nowarn_unused_function, yeccpars2_28_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 67). +yeccpars2_28_(__Stack0) -> + [___3,___2,___1 | __Stack] = __Stack0, + [begin + list_to_binary(___1) + end | __Stack]. + +-compile({inline,yeccpars2_29_/1}). +-dialyzer({nowarn_function, yeccpars2_29_/1}). +-compile({nowarn_unused_function, yeccpars2_29_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 69). +yeccpars2_29_(__Stack0) -> + [___4,___3,___2,___1 | __Stack] = __Stack0, + [begin + list_to_binary(___1) + end | __Stack]. + +-compile({inline,yeccpars2_30_/1}). +-dialyzer({nowarn_function, yeccpars2_30_/1}). +-compile({nowarn_unused_function, yeccpars2_30_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 79). +yeccpars2_30_(__Stack0) -> + [begin + [] + end | __Stack0]. + +-compile({inline,yeccpars2_31_/1}). +-dialyzer({nowarn_function, yeccpars2_31_/1}). +-compile({nowarn_unused_function, yeccpars2_31_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 82). +yeccpars2_31_(__Stack0) -> + [___1 | __Stack] = __Stack0, + [begin + ___1 + end | __Stack]. + +-compile({inline,yeccpars2_32_/1}). +-dialyzer({nowarn_function, yeccpars2_32_/1}). +-compile({nowarn_unused_function, yeccpars2_32_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 64). +yeccpars2_32_(__Stack0) -> + [___2,___1 | __Stack] = __Stack0, + [begin + {___1, ___2} + end | __Stack]. + +-compile({inline,yeccpars2_35_/1}). +-dialyzer({nowarn_function, yeccpars2_35_/1}). +-compile({nowarn_unused_function, yeccpars2_35_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 88). +yeccpars2_35_(__Stack0) -> + [___1 | __Stack] = __Stack0, + [begin + ___1 + end | __Stack]. + +-compile({inline,yeccpars2_36_/1}). +-dialyzer({nowarn_function, yeccpars2_36_/1}). +-compile({nowarn_unused_function, yeccpars2_36_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 89). +yeccpars2_36_(__Stack0) -> + [___2,___1 | __Stack] = __Stack0, + [begin + ___1 + end | __Stack]. + +-compile({inline,yeccpars2_37_/1}). +-dialyzer({nowarn_function, yeccpars2_37_/1}). +-compile({nowarn_unused_function, yeccpars2_37_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 90). +yeccpars2_37_(__Stack0) -> + [___2,___1 | __Stack] = __Stack0, + [begin + ___2 + end | __Stack]. + +-compile({inline,yeccpars2_38_/1}). +-dialyzer({nowarn_function, yeccpars2_38_/1}). +-compile({nowarn_unused_function, yeccpars2_38_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 91). +yeccpars2_38_(__Stack0) -> + [___3,___2,___1 | __Stack] = __Stack0, + [begin + ___2 + end | __Stack]. + +-compile({inline,yeccpars2_41_/1}). +-dialyzer({nowarn_function, yeccpars2_41_/1}). +-compile({nowarn_unused_function, yeccpars2_41_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 93). +yeccpars2_41_(__Stack0) -> + [___1 | __Stack] = __Stack0, + [begin + [___1] + end | __Stack]. + +-compile({inline,yeccpars2_42_/1}). +-dialyzer({nowarn_function, yeccpars2_42_/1}). +-compile({nowarn_unused_function, yeccpars2_42_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 102). +yeccpars2_42_(__Stack0) -> + [___1 | __Stack] = __Stack0, + [begin + "=" + end | __Stack]. + +-compile({inline,yeccpars2_43_/1}). +-dialyzer({nowarn_function, yeccpars2_43_/1}). +-compile({nowarn_unused_function, yeccpars2_43_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 101). +yeccpars2_43_(__Stack0) -> + [___1 | __Stack] = __Stack0, + [begin + "[" + end | __Stack]. + +-compile({inline,yeccpars2_44_/1}). +-dialyzer({nowarn_function, yeccpars2_44_/1}). +-compile({nowarn_unused_function, yeccpars2_44_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 103). +yeccpars2_44_(__Stack0) -> + [___1 | __Stack] = __Stack0, + [begin + "]" + end | __Stack]. + +-compile({inline,yeccpars2_45_/1}). +-dialyzer({nowarn_function, yeccpars2_45_/1}). +-compile({nowarn_unused_function, yeccpars2_45_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 99). +yeccpars2_45_(__Stack0) -> + [___1 | __Stack] = __Stack0, + [begin + value_of(___1) + end | __Stack]. + +-compile({inline,yeccpars2_46_/1}). +-dialyzer({nowarn_function, yeccpars2_46_/1}). +-compile({nowarn_unused_function, yeccpars2_46_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 100). +yeccpars2_46_(__Stack0) -> + [___1 | __Stack] = __Stack0, + [begin + value_of(___1) + end | __Stack]. + +-compile({inline,yeccpars2_47_/1}). +-dialyzer({nowarn_function, yeccpars2_47_/1}). +-compile({nowarn_unused_function, yeccpars2_47_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 98). +yeccpars2_47_(__Stack0) -> + [___1 | __Stack] = __Stack0, + [begin + value_of(___1) + end | __Stack]. + +-compile({inline,yeccpars2_48_/1}). +-dialyzer({nowarn_function, yeccpars2_48_/1}). +-compile({nowarn_unused_function, yeccpars2_48_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 97). +yeccpars2_48_(__Stack0) -> + [___1 | __Stack] = __Stack0, + [begin + value_of(___1) + end | __Stack]. + +-compile({inline,yeccpars2_49_/1}). +-dialyzer({nowarn_function, yeccpars2_49_/1}). +-compile({nowarn_unused_function, yeccpars2_49_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 94). +yeccpars2_49_(__Stack0) -> + [___2,___1 | __Stack] = __Stack0, + [begin + [___1 | ___2] + end | __Stack]. + +-compile({inline,yeccpars2_50_/1}). +-dialyzer({nowarn_function, yeccpars2_50_/1}). +-compile({nowarn_unused_function, yeccpars2_50_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 85). +yeccpars2_50_(__Stack0) -> + [___4,___3,___2,___1 | __Stack] = __Stack0, + [begin + + {list_to_binary(value_of(___1)), strip_values(___3)} + end | __Stack]. + +-compile({inline,yeccpars2_51_/1}). +-dialyzer({nowarn_function, yeccpars2_51_/1}). +-compile({nowarn_unused_function, yeccpars2_51_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 83). +yeccpars2_51_(__Stack0) -> + [___2,___1 | __Stack] = __Stack0, + [begin + ___1 + end | __Stack]. + +-compile({inline,yeccpars2_52_/1}). +-dialyzer({nowarn_function, yeccpars2_52_/1}). +-compile({nowarn_unused_function, yeccpars2_52_/1}). +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 80). +yeccpars2_52_(__Stack0) -> + [___2,___1 | __Stack] = __Stack0, + [begin + [___1 | ___2] + end | __Stack]. + + +-file("/home/saru/Documents/learning/books/ml_in_elixir/ml_elixir_learning/deps/eini/src/eini_parser.yrl", 119). diff --git a/deps/eini/src/eini_parser.yrl b/deps/eini/src/eini_parser.yrl new file mode 100644 index 0000000000000000000000000000000000000000..502b1538b2f4b2505a2de91542c1c370b25b2bfa --- /dev/null +++ b/deps/eini/src/eini_parser.yrl @@ -0,0 +1,118 @@ +%% Licensed to the Apache Software Foundation (ASF) under one +%% or more contributor license agreements. See the NOTICE file +%% distributed with this work for additional information +%% regarding copyright ownership. The ASF licenses this file +%% to you under the Apache License, Version 2.0 (the +%% "License"); you may not use this file except in compliance +%% with the License. You may obtain a copy of the License at +%% +%% http://www.apache.org/licenses/LICENSE-2.0 +%% +%% Unless required by applicable law or agreed to in writing, +%% software distributed under the License is distributed on an +%% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +%% KIND, either express or implied. See the License for the +%% specific language governing permissions and limitations +%% under the License. + +%% @author: shino@accense.com + +Nonterminals + whole + sections + sections_with_skip_lines + section + title_part + title_word + title_words + title + property_with_skip_lines + properties property + key_part + values single_value + skip_lines + comment_line + blank_line. + +Terminals + '[' ']' '=' + blank + word + value + comment + break. + +Rootsymbol whole. + +%% Leex smash out all blank lines, but at the beggining of file is NOT. +whole -> sections_with_skip_lines : '$1'. +whole -> blank_line sections_with_skip_lines : '$2'. + +blank_line -> blank break : '$1'. + +%% Comment lines are treated as: +%% 1. At the biggining of file are included into sections_with_skip_lines +%% 2. Other comment lines are included to title_part and property_with_skip_lines + +skip_lines -> comment_line : ['$1']. +skip_lines -> comment_line skip_lines : ['$1', '$2']. + +comment_line -> comment break : '$1'. + +sections_with_skip_lines -> sections : '$1'. +sections_with_skip_lines -> skip_lines sections : '$2'. + +sections -> '$empty' : []. +sections -> section sections : ['$1' | '$2']. + +section -> title_part properties : {'$1', '$2'}. + +title_part -> title break : list_to_binary('$1'). +title_part -> title blank break : list_to_binary('$1'). +title_part -> title break skip_lines : list_to_binary('$1'). +title_part -> title blank break skip_lines : list_to_binary('$1'). + +title_word -> word : value_of('$1'). +title_word -> blank : value_of('$1'). + +title_words -> title_word : ['$1']. +title_words -> title_word title_words : ['$1' | '$2']. + +title -> '[' title_words ']' : string:strip(lists:flatten('$2'), both, $\s). + +properties -> '$empty' : []. +properties -> property_with_skip_lines properties : ['$1' | '$2']. + +property_with_skip_lines -> property : '$1'. +property_with_skip_lines -> property skip_lines : '$1'. + +property -> key_part '=' values break : + {list_to_binary(value_of('$1')), strip_values('$3')}. + +key_part -> word : '$1'. +key_part -> word blank : '$1'. +key_part -> blank word : '$2'. +key_part -> blank word blank : '$2'. + +values -> single_value : ['$1']. +values -> single_value values : ['$1' | '$2']. + +%% At value position, any characters are accepted AS IS. +single_value -> word : value_of('$1'). +single_value -> value : value_of('$1'). +single_value -> blank : value_of('$1'). +single_value -> comment : value_of('$1'). +single_value -> '[' : "[". +single_value -> '=' : "=". +single_value -> ']' : "]". + +Erlang code. + +-spec value_of({atom(), _Line, TokenChars::string()}) -> TokenChars::string(). +value_of(Token) -> + element(3, Token). + +-spec strip_values([TokenChars::string()]) -> Value::binary(). +strip_values(Values) -> + String = string:strip(string:strip(lists:flatten(Values), both, $\s), both, $\t), + list_to_binary(String). diff --git a/deps/iso8601/.hex b/deps/iso8601/.hex new file mode 100644 index 0000000000000000000000000000000000000000..7caeffb812bfa3b6977a6cb6934df96a67006be6 Binary files /dev/null and b/deps/iso8601/.hex differ diff --git a/deps/iso8601/LICENSE b/deps/iso8601/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d4bfdbcc5f04663ddb61a39da84b67e87a7053c0 --- /dev/null +++ b/deps/iso8601/LICENSE @@ -0,0 +1,20 @@ +Copyright © 2011-2014, Sean Sawyer +Copyright © 2012, Tristan Sloughter +Copyright © 2016-2021, Erlang-Aided Enrichment Center + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/deps/iso8601/README.md b/deps/iso8601/README.md new file mode 100644 index 0000000000000000000000000000000000000000..94461e68d8cbb510bc12712d7b13274a34bfa614 --- /dev/null +++ b/deps/iso8601/README.md @@ -0,0 +1,141 @@ +# iso8601 +[![Build Status][gh-actions-badge]][gh-actions] +[![Tag][tag-badge]][tag] +[![Erlang Version][erl-badge]][erl] +[![Downloads][hex downloads]][hex package] + +*An ISO 8601 date formatting and parsing library for Erlang* + +[![iso8601 project logo][logo]][logo-large] + + +#### Contents + +* [About](#about-) +* [Usage](#usage-) +* [Known Deficiencies](#known-deficiencies-) +* [License](#license-) + + +## About [↟](#contents) + +The ``erlang_iso8601`` library was originally created by Sean Sawyer in 2011. In 2016, Sean handed off maintenance of the library to the [erlsci](https://github.com/erlsci) Github org at which point the project (and repo) was renamed to simply ``iso8601``, matching its Erlang app name: + +* ``git clone https://github.com/erlsci/iso8601.git`` + +Thanks to Github's forwarding for project renames and moves, the following still work: + +* ``git clone https://github.com/seansawyer/erlang_iso8601.git`` +* ``git clone https://github.com/erlsci/erlang_iso8601.git`` + + +## Usage [↟](#contents) + +Add it to your `rebar.config` deps: + +```erlang +{iso8601, {git, "https://github.com/erlsci/iso8601.git", {tag, "1.3.2"}}} +``` + +Format a timestamp or calendar datetime tuple: + +```erlang +1> iso8601:format(now()). +<<"2012-02-16T01:06:19Z">> +2> iso8601:format(calendar:universal_time()). +<<"2012-02-16T01:06:48Z">> +``` + +Parse a date string or binary: + +```erlang +3> iso8601:parse(<<"2012-02-16T01:06:48Z">>). +{{2012,2,16},{1,6,48}} +4> iso8601:parse("2012-02-16T01:06:48Z"). +{{2012,2,16},{1,6,48}} +``` + +Add 1 hour, 2 minutes and 3 seconds to a datetime tuple: + +```erlang +5> Datetime = iso8601:parse(<<"2012-02-16T01:06:48Z">>). +{{2012,2,16},{1,6,48}} +6> iso8601:add_time(Datetime, 1, 2, 3). +{{2012,2,16},{2,8,51}} +``` + +Subtract 1 hour, 2 minutes and 3 seconds from a datetime tuple: + +```erlang +5> Datetime = iso8601:parse(<<"2012-02-16T01:06:48Z">>). +{{2012,2,16},{1,6,48}} +6> iso8601:subtract_time(Datetime, 1, 2, 3). +{{2012,2,16},{0,4,45}} +``` + +Fractional times: + +```erlang +7> iso8601:parse("20120203T040506.50"). +{{2012,2,3},{4,5,7}} +8> iso8601:parse_exact("20120203T040506.50"). +{{2012,2,3},{4,5,6.50}} +``` + +Parse durations: + +```erlang +9> iso8601:parse_duration("+P6Y3M1DT1H1M1.1S"). +[{sign, "+"}, {years, 6}, {months, 3}, {days, 1}, {hours, 1}, {minutes, 1}, {seconds, 1}] +10> iso8601:parse_duration("PT6M"). +[{sign, []}, {years, 0}, {months, 0}, {days, 0},{hours, 0}, {minutes, 6}, {seconds, 0}] +``` + +## Known Deficiencies [↟](#contents) + +* Does not support expanded year representation. +* Does not support intervals. + +See the [open issues](https://github.com/erlsci/iso8601/issues) +for more info. + + +## Donating + +A donation account for supporting development on this project has been set up +on Liberapay here: + +* [https://liberapay.com/erlsci-iso8601/donate](https://liberapay.com/erlsci-iso8601/donate) + +You can learn more about Liberapay on its [Wikipedia entry][libera-wiki] or on the +service's ["About" page][libera-about]. + +[libera-wiki]: https://en.wikipedia.org/wiki/Liberapay +[libera-about]: https://liberapay.com/about/ + + +## License [↟](#contents) + +``` +The MIT License (MIT) + +Copyright © 2011-2014, Sean Sawyer +Copyright © 2012, Tristan Sloughter +Copyright © 2016-2021, Erlang-Aided Enrichment Center +``` + + +[//]: --Named-Links-- + +[gh-actions-badge]: https://github.com/erlsci/iso8601/workflows/ci/badge.svg +[gh-actions]: https://github.com/erlsci/iso8601/actions +[tag]: https://github.com/erlsci/iso8601/releases/latest +[tag-badge]: https://img.shields.io/github/tag/erlsci/iso8601.svg +[erl]: http://www.erlang.org/downloads +[erl-badge]: https://img.shields.io/badge/erlang-%E2%89%A5R15B03-blue.svg +[logo]: resources/images/logo.png +[logo-large]: resources/images/logo-large.png +[logo-source]: https://www.flickr.com/photos/theilr/2164085293 +[hex badge]: https://img.shields.io/hexpm/v/iso8601.svg?maxAge=259200 +[hex package]: https://hex.pm/packages/iso8601 +[hex downloads]: https://img.shields.io/hexpm/dt/iso8601.svg diff --git a/deps/iso8601/_build/prod/lib/.rebar3/rebar_compiler_erl/source.dag b/deps/iso8601/_build/prod/lib/.rebar3/rebar_compiler_erl/source.dag new file mode 100644 index 0000000000000000000000000000000000000000..29901ec365c0d3ec5f99ed217f980bc812cf35aa Binary files /dev/null and b/deps/iso8601/_build/prod/lib/.rebar3/rebar_compiler_erl/source.dag differ diff --git a/deps/iso8601/hex_metadata.config b/deps/iso8601/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..e3338c5d4d1f8d0a706ee818cc8a119c99e84688 --- /dev/null +++ b/deps/iso8601/hex_metadata.config @@ -0,0 +1,15 @@ +{<<"app">>,<<"iso8601">>}. +{<<"build_tools">>,[<<"rebar3">>]}. +{<<"description">>, + <<"An ISO 8601 date formatting and parsing library for Erlang">>}. +{<<"files">>, + [<<"LICENSE">>,<<"README.md">>,<<"rebar.config">>,<<"rebar.lock">>, + <<"src/iso8601.app.src">>,<<"src/iso8601.erl">>]}. +{<<"licenses">>,[<<"BSD">>]}. +{<<"links">>, + [{<<"GitHub">>,<<"https://github.com/erlsci/iso8601">>}, + {<<"Gitlab">>,<<"https://gitlab.com/erlsci/iso8601">>}, + {<<"Hex">>,<<"https://hex.pm/packages/iso8601">>}]}. +{<<"name">>,<<"iso8601">>}. +{<<"requirements">>,[]}. +{<<"version">>,<<"1.3.4">>}. diff --git a/deps/iso8601/rebar.config b/deps/iso8601/rebar.config new file mode 100644 index 0000000000000000000000000000000000000000..d79687e6c367639705bc0ec92fddd3ebca347681 --- /dev/null +++ b/deps/iso8601/rebar.config @@ -0,0 +1,51 @@ +{erl_opts, []}. + +{xref_checks, [ + undefined_function_calls, + undefined_functions, + %locals_not_used, + deprecated_function_calls, + deprecated_functions +]}. + +{dialyzer, [ + {warnings, [ + unknown, + unmatched_returns, + error_handling, + underspecs + ]} +]}. + +{profiles, [ + {test, [ + {deps, [ + {proper, "1.3.0"} + ]}, + {plugins, [ + {rebar3_proper, "0.12.1"} + ]}, + {eunit_opts, [verbose]}, + {erl_opts, [ + {src_dirs, ["src", "test"]} + ]} + ]} +]}. + +{alias, [ + {test, [ + compile, + eunit + ]}, + {coverage, [ + {proper, "-c"}, + {cover, "-v --min_coverage=0"} + ]}, + {check, [ + compile, + xref, + dialyzer, + eunit, + coverage + ]} +]}. \ No newline at end of file diff --git a/deps/iso8601/rebar.lock b/deps/iso8601/rebar.lock new file mode 100644 index 0000000000000000000000000000000000000000..57afcca04590ff2bbf2f83b8eac4f856df782c74 --- /dev/null +++ b/deps/iso8601/rebar.lock @@ -0,0 +1 @@ +[]. diff --git a/deps/iso8601/src/iso8601.app.src b/deps/iso8601/src/iso8601.app.src new file mode 100644 index 0000000000000000000000000000000000000000..b00d8e762dbbdd426dd339593d5a54bf4b4680fb --- /dev/null +++ b/deps/iso8601/src/iso8601.app.src @@ -0,0 +1,13 @@ +{application,iso8601, + [{description,"An ISO 8601 date formatting and parsing library for Erlang"}, + {vsn,"1.3.4"}, + {registered,[]}, + {modules,[iso8601]}, + {applications,[kernel,stdlib]}, + {env,[]}, + {pkg_name,iso8601}, + {licenses,["BSD"]}, + {maintainers,["Duncan McGreggor"]}, + {links,[{"GitHub","https://github.com/erlsci/iso8601"}, + {"Gitlab","https://gitlab.com/erlsci/iso8601"}, + {"Hex","https://hex.pm/packages/iso8601"}]}]}. diff --git a/deps/iso8601/src/iso8601.erl b/deps/iso8601/src/iso8601.erl new file mode 100644 index 0000000000000000000000000000000000000000..782479b34dcc8b970437cd29e70fca4480ed4eff --- /dev/null +++ b/deps/iso8601/src/iso8601.erl @@ -0,0 +1,441 @@ +-module(iso8601). + +-export([add_time/4, + add_days/2, + add_months/2, + add_years/2, + subtract_time/4, + format/1, + parse/1, + parse_exact/1, + parse_duration/1, + apply_duration/2]). + +-define(MIDNIGHT, {0,0,0}). +-define(NOON, {12,0,0}). +-define(TEATIME, {16,0,0}). +-define(V, proplists:get_value). + +%%---------------------------------------------------------------------- +%% Types +%%---------------------------------------------------------------------- + +-export_type([timestamp/0, year/0, month/0, day/0, hour/0, minute/0, second/0]). + +%% This group of types is from calendar.erl; we need to use some of them +%% for this lib, but thought it might be nice to provide the rest to users. +-type year() :: non_neg_integer(). +-type month() :: 1..12. +-type day() :: 1..31. +-type hour() :: 0..23. +-type minute() :: 0..59. +-type second() :: 0..59. + +-type datetime() :: {calendar:date(), {hour(), + minute(), + second() | float()}}. +-type datetime_plist() :: list({atom(), integer()}). +-type undefined_or(A) :: undefined | A. +-type timestamp() :: {MegaSecs::integer(), + Secs::integer(), + MicroSecs::integer() | float()}. + +%%---------------------------------------------------------------------- +%% API +%%---------------------------------------------------------------------- + +-spec add_time (calendar:datetime(), integer(), integer(), integer()) + -> calendar:datetime(). +%% @doc Add some time to the supplied `calendar:datetime()'. +add_time({_, _, _}=Timestamp, H, M, S) -> + add_time(calendar:now_to_datetime(Timestamp), H, M, S); +add_time(Datetime, H, M, S) -> + apply_offset(Datetime, H, M, S). + +-spec add_days (datetime() | timestamp(), integer()) -> datetime(). +%% @doc Add some days to the supplied `datetime()'. +add_days({_, _, _}=Timestamp, D) -> + add_days(calendar:now_to_datetime(Timestamp), D); +add_days(Datetime, D) -> + apply_days_offset(Datetime, D). + +-spec add_months (datetime() | timestamp(), integer()) -> datetime(). +%% @doc Add some months to the supplied `datetime()'. +add_months({_, _, _}=Timestamp, M) -> + add_months(calendar:now_to_datetime(Timestamp), M); +add_months(Datetime, M) -> + apply_months_offset(Datetime, M). + +-spec add_years (datetime() | timestamp(), integer()) -> datetime(). +%% @doc Add some years to the supplied `datetime()'. +add_years({_, _, _}=Timestamp, Y) -> + add_years(calendar:now_to_datetime(Timestamp), Y); +add_years(Datetime, Y) -> + apply_years_offset(Datetime, Y). + +-spec subtract_time (calendar:datetime(), integer(), integer(), integer()) + -> calendar:datetime(). +%% @doc Subtract some time from the supplied `calendar:datetime()'. +subtract_time(Datetime, H, M, S) -> + apply_offset(Datetime, -H, -M, -S). + +-spec format (datetime() | timestamp()) -> binary(). +%% @doc Convert a `util:timestamp()' or a calendar-style `{date(), time()}' +%% tuple to an ISO 8601 formatted string. Note that this function always +%% returns a string with no offset (i.e., ending in "Z"). +format({_,_,_}=Timestamp) -> + format(calendar:now_to_datetime(Timestamp)); +format({{Y,Mo,D}, {H,Mn,S}}) when is_float(S) -> + FmtStr = "~4.10.0B-~2.10.0B-~2.10.0BT~2.10.0B:~2.10.0B:~9.6.0fZ", + IsoStr = io_lib:format(FmtStr, [Y, Mo, D, H, Mn, S]), + list_to_binary(IsoStr); +format({{Y,Mo,D}, {H,Mn,S}}) -> + FmtStr = "~4.10.0B-~2.10.0B-~2.10.0BT~2.10.0B:~2.10.0B:~2.10.0BZ", + IsoStr = io_lib:format(FmtStr, [Y, Mo, D, H, Mn, S]), + list_to_binary(IsoStr). + +-spec parse (iodata()) -> calendar:datetime(). +%% @doc Convert an ISO 8601 formatted string to a `{date(), time()}' +parse(Bin) when is_binary(Bin) -> + parse(binary_to_list(Bin)); +parse(Str) -> + {{Date, {H, M, S}}, Subsecond} = year(Str, []), + {Date, {H, M, S + trunc(Subsecond)}}. + +-spec parse_exact (iodata()) -> calendar:datetime(). +%% @doc Convert an ISO 8601 formatted string to a `{date(), time()}' +%% tuple with seconds precision to 3 decimal places +parse_exact(Bin) when is_binary(Bin) -> + parse_exact(binary_to_list(Bin)); +parse_exact(Str) -> + {{Date, {H, M, S}}, SecondsDecimal} = year(Str, []), + {Date, {H, M, S + SecondsDecimal}}. + +-spec gi(string()) ->integer(). +%doc get string and return integer part or 0 on error +gi(DS)-> + {Int, _Rest} = string:to_integer(DS), + case Int of + error->0; + _->Int + end. + +-spec parse_duration(string()) ->datetime_plist(). +%% @doc Convert an ISO 8601 Durations string to a +parse_duration(Bin) when is_binary(Bin)-> %TODO extended format + parse_duration(binary_to_list(Bin)); +parse_duration(Str) -> + case re:run(Str, "^(?-|\\+)?P" + "(?:(?[0-9]+)Y)?" + "(?:(?[0-9]+)M)?" + "(?:(?[0-9]+)D)?" + "(T(?:(?[0-9]+)H)?" + "(?:(?[0-9]+)M)?" + "(?:(?[0-9]+(?:\\.[0-9]+)?)S)?)?$", + [{capture, [sign, years, months, days, hours, minutes, seconds], list}]) of + {match, [Sign, Years, Months, Days, Hours, Minutes, Seconds]} -> + [{sign, Sign}, {years, gi(Years)}, {months, gi(Months)}, + {days, gi(Days)}, {hours, gi(Hours)}, {minutes, gi(Minutes)}, + {seconds, gi(Seconds)}]; + nomatch -> error(badarg) + end. + +-spec apply_duration(datetime(), string()) -> datetime(). +%% @doc Return new datetime after apply duration. +apply_duration(Datetime, Duration) -> + [{sign, _S}, {years, Y}, {months, M}, {days, D}, {hours, H}, + {minutes, MM}, {seconds, SS}] = parse_duration(Duration), + D1 = apply_years_offset(Datetime, Y), + D2 = apply_months_offset(D1, M), + D3 = apply_days_offset(D2, D), + apply_offset(D3, H, MM, SS). + +%% Private functions + +year([Y1,Y2,Y3,Y4|Rest], Acc) -> + acc([Y1,Y2,Y3,Y4], Rest, year, Acc, fun month_or_week/2); +year(_, _) -> + error(badarg). + +month_or_week([], Acc) -> + datetime(Acc); +month_or_week([$-,$W,W1,W2|Rest], Acc) -> + acc([W1,W2], Rest, week, Acc, fun week_day/2); +month_or_week([$-,D1,D2,D3], Acc) -> + %% ordinal date, no time + io:format("Ordinal date, no time!~n"), + acc_ordinal_date(D1, D2, D3, [], Acc, fun hour/2); +month_or_week([$-,D1,D2,D3,$T|Rest], Acc) -> + %% ordinal date with time + io:format("Ordinal date, time is ~p!~n", [Rest]), + acc_ordinal_date(D1, D2, D3, [$T|Rest], Acc, fun hour/2); +month_or_week([$-,M1,M2|Rest], Acc) -> + acc([M1,M2], Rest, month, Acc, fun month_day/2); +month_or_week([$W,W1,W2|Rest], Acc) -> + acc([W1,W2], Rest, week, Acc, fun week_day_no_hyphen/2); +month_or_week([M1,M2|Rest], Acc) -> + acc([M1,M2], Rest, month, Acc, fun month_day_no_hyphen/2); +month_or_week(_, _) -> + error(badarg). + +week_day([], Acc) -> + datetime(Acc); +week_day([$-,D|Rest], Acc) -> + acc([D], Rest, week_day, Acc, fun hour/2); +week_day(_, _) -> + error(badarg). + +week_day_no_hyphen([], Acc) -> + datetime(Acc); +week_day_no_hyphen([D|Rest], Acc) -> + acc([D], Rest, week_day, Acc, fun hour/2); +week_day_no_hyphen(_, _) -> + error(badarg). + +month_day([], Acc) -> + datetime(Acc); +month_day([$-,D1,D2|Rest], Acc) -> + acc([D1,D2], Rest, month_day, Acc, fun hour/2); +month_day(_, _) -> + error(badarg). + +month_day_no_hyphen([], _) -> + error(badarg); % omission of day disallowed by spec in this case +month_day_no_hyphen([D1,D2|Rest], Acc) -> + acc([D1,D2], Rest, month_day, Acc, fun hour/2); +month_day_no_hyphen(_, _) -> + error(badarg). + +hour([], Acc) -> + datetime(Acc); +hour([$T,H1,H2,$.|Rest], Acc) -> + acc([H1,H2], Rest, hour, Acc, fun hour_decimal/2); +hour([$T,H1,H2,$,|Rest], Acc) -> + acc([H1,H2], Rest, hour, Acc, fun hour_decimal/2); +hour([$T,H1,H2|Rest], Acc) -> + acc([H1,H2], Rest, hour, Acc, fun minute/2); +hour(_, _) -> + error(badarg). + +hour_decimal(Str, Acc) -> + decimal(Str, Acc, hour_decimal). + +minute([], Acc) -> + datetime(Acc); +minute([$:,M1,M2,$.|Rest], Acc) -> + acc([M1,M2], Rest, minute, Acc, fun minute_decimal/2); +minute([$:,M1,M2,$,|Rest], Acc) -> + acc([M1,M2], Rest, minute, Acc, fun minute_decimal/2); +minute([$:,M1,M2|Rest], Acc) -> + acc([M1,M2], Rest, minute, Acc, fun second/2); +minute([M1,M2,$.|Rest], Acc) -> + acc([M1,M2], Rest, minute, Acc, fun minute_decimal/2); +minute([M1,M2,$,|Rest], Acc) -> + acc([M1,M2], Rest, minute, Acc, fun minute_decimal/2); +minute([M1,M2|Rest], Acc) -> + acc([M1,M2], Rest, minute, Acc, fun second_no_colon/2); +minute(_, _) -> + error(badarg). + +minute_decimal(Str, Acc) -> + decimal(Str, Acc, minute_decimal). + +second([], Acc) -> + datetime(Acc); +second([$:,S1,S2,$.|Rest], Acc) -> + acc([S1,S2], Rest, second, Acc, fun second_decimal/2); +second([$:,S1,S2,$,|Rest], Acc) -> + acc([S1,S2], Rest, second, Acc, fun second_decimal/2); +second([$:,S1,S2|Rest], Acc) -> + acc([S1,S2], Rest, second, Acc, fun offset_hour/2); +second(_, _) -> + error(badarg). + +second_no_colon([], Acc) -> + datetime(Acc); +second_no_colon([S1,S2,$.|Rest], Acc) -> + acc([S1,S2], Rest, second, Acc, fun second_decimal/2); +second_no_colon([S1,S2,$,|Rest], Acc) -> + acc([S1,S2], Rest, second, Acc, fun second_decimal/2); +second_no_colon([S1,S2|Rest], Acc) -> + acc([S1,S2], Rest, second, Acc, fun offset_hour/2); +second_no_colon(_, _) -> + error(badarg). + +second_decimal(Str, Acc) -> + decimal(Str, Acc, second_decimal). + +decimal([], _, _) -> + error(badarg); +decimal(Str, Acc, Key) -> + F = fun(X) when is_integer(X), X >= $0, X =< $9 -> + true; + (_) -> + false + end, + {Parts, Rest} = lists:splitwith(F, Str), + acc_float([$0,$.|Parts], Rest, Key, Acc, fun offset_hour/2). + +offset_hour([], Acc) -> + datetime(Acc); +offset_hour([$Z], Acc) -> + datetime(Acc); +offset_hour([$+,H1,H2|Rest], Acc) -> + acc([H1,H2], Rest, offset_hour, Acc, fun offset_minute/2); +offset_hour([$-,H1,H2|Rest], Acc) -> + acc([H1,H2], Rest, offset_hour, [{offset_sign, -1}|Acc], fun offset_minute/2); +offset_hour(_, _) -> + error(badarg). + +offset_minute([], Acc) -> + datetime(Acc); +offset_minute([$:,M1,M2], Acc) -> + acc([M1,M2], [], offset_minute, Acc, fun datetime/2); +offset_minute([M1,M2], Acc) -> + acc([M1,M2], [], offset_minute, Acc, fun datetime/2); +offset_minute(_, _) -> + error(badarg). + +acc(IntStr, Rest, Key, Acc, NextF) -> + Acc1 = [{Key, list_to_integer(IntStr)}|Acc], + NextF(Rest, Acc1). + +acc_float(FloatStr, Rest, Key, Acc, NextF) -> + Acc1 = [{Key, list_to_float(FloatStr)}|Acc], + NextF(Rest, Acc1). + +acc_ordinal_date(D1, D2, D3, Rest, Acc, NextF) -> + Days = list_to_integer([D1, D2, D3]), + Days > 0 orelse error(badarg), + Year = ?V(year, Acc), + Year =/= undefined orelse error(badarg), + DaysInMonths = days_in_months_for_year(Year), + { Month, Day } = unpack_ordinal_date(Days, DaysInMonths), + Acc1 = [{ month, Month }, { month_day, Day }|Acc], + NextF(Rest, Acc1). + +unpack_ordinal_date(Days, DaysInMonths) -> unpack_ordinal_date(1, Days, DaysInMonths). +unpack_ordinal_date(_Month, _Days, []) -> error(badarg), { 0, 0 }; +unpack_ordinal_date(_Month, Days, _DaysInMonths) when Days < 0 -> error(badarg), { 0, 0 }; +unpack_ordinal_date(Month, Days, [DaysThisMonth|DaysInMonths]) -> + case Days > DaysThisMonth of + true -> unpack_ordinal_date(Month + 1, Days - DaysThisMonth, DaysInMonths); + _ -> { Month, Days } + end. + +days_in_months_for_year(Year) -> + case is_leap_year(Year) of + true -> [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + false -> [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + end. + +is_leap_year(Year) -> + case Year rem 100 of + 0 -> Year rem 400 =:= 0; + _ -> Year rem 4 =:= 0 + end. + +add_decimal(Datetime, Plist) -> + HDecimal = ?V(hour_decimal, Plist, 0.0), + MDecimal = ?V(minute_decimal, Plist, 0.0), + apply_offset(Datetime, HDecimal, MDecimal, 0.0). + +datetime(Plist) -> + {Date, WeekOffsetH} = make_date(Plist), + Time = {?V(hour, Plist, 0), ?V(minute, Plist, 0), ?V(second, Plist, 0)}, + Datetime = add_decimal({Date, Time}, Plist), + OffsetSign = ?V(offset_sign, Plist, 1), + OffsetH = -1 * OffsetSign * ?V(offset_hour, Plist, 0), + OffsetM = -1 * OffsetSign * ?V(offset_minute, Plist, 0), + { apply_offset(Datetime, WeekOffsetH+OffsetH, OffsetM, 0), ?V(second_decimal, Plist, 0.0) }. + + +datetime(_, Plist) -> + datetime(Plist). + +-spec make_date (datetime_plist()) + -> {Date::calendar:date(), WeekOffsetH::non_neg_integer()}. +%% @doc Return a `tuple' containing a date and, if the date is in week format, +%% an offset in hours that can be applied to the date to adjust it to midnight +%% of the day specified. If month format is used, the offset will be zero. +make_date(Plist) -> + Year = ?V(year, Plist), + Year =/= undefined orelse error(badarg), + make_date(Year, ?V(month, Plist, 1), ?V(week, Plist), Plist). + +-spec make_date (non_neg_integer(), + undefined_or(pos_integer()), + undefined_or(pos_integer()), + datetime_plist()) + -> {calendar:date(), non_neg_integer()}. +%% @doc Return a `tuple' containing a date and - if the date is in week format +%% (i.e., `Month' is undefined, `Week' is not) - an offset in hours that can be +%% applied to the date to adjust it to midnight of the day specified. If month +%% format is used (i.e., `Week' is undefined, `Month' is not), the offset will +%% be zero. +make_date(Year, Month, undefined, Plist) -> + Date = {Year, Month, ?V(month_day, Plist, 1)}, + {Date, 0}; +make_date(Year, _, Week, Plist) -> + Weekday = ?V(week_day, Plist, 1), + OffsetH = ((Week-1)*7 + (Weekday-1))*24, % week/weekday offset in hours + {date_at_w01_1(Year), OffsetH}. + +-spec date_at_w01_1(pos_integer()) -> calendar:date(). +%% @doc Calculate the `calendar:date()' at ISO week 1, day 1 in the supplied +%% year. +date_at_w01_1(Year) -> + case calendar:day_of_the_week({Year,1,1}) of + 1 -> {Year, 1, 1}; + 2 -> {Year-1, 12, 31}; + 3 -> {Year-1, 12, 30}; + 4 -> {Year-1, 12, 29}; + 5 -> {Year, 1, 4}; + 6 -> {Year, 1, 3}; + 7 -> {Year, 1, 2} + end. + +-spec apply_offset (calendar:datetime(), number(), number(), number()) + -> calendar:datetime(). +%% @doc Add the specified number of hours, minutes and seconds to `Datetime'. +apply_offset(Datetime, H, M, S) -> + OffsetS = S + (60 * (M + (60 * H))), + Gs = round(OffsetS) + calendar:datetime_to_gregorian_seconds(Datetime), + calendar:gregorian_seconds_to_datetime(Gs). + +-spec apply_months_offset (datetime(), number()) -> datetime(). +%% @doc Add the specified number of months to `Datetime'. +apply_months_offset(Datetime, 0) -> + Datetime; +apply_months_offset(Datetime, AM) -> + {{Y, M, D}, {H, MM, S}} = Datetime, + AY = (Y*12)+M+AM, + Year = ((AY-1) div 12), + Month = + case (AY rem 12) of + 0 -> 12; + Result -> Result + end, + find_last_valid_date({{Year, Month, D}, {H, MM, S}}). + +-spec apply_days_offset (datetime(), number()) -> datetime(). +%% @doc Add the specified days to `Datetime'. +apply_days_offset(Datetime, AD) -> + {{Y, M, D}, {H, MM, S}} = Datetime, + DaysTotal=calendar:date_to_gregorian_days({Y, M, D})+AD, + {calendar:gregorian_days_to_date(DaysTotal), {H, MM, S}}. + +-spec apply_years_offset (datetime(), number()) -> datetime(). +%% @doc Add the specified years to `Datetime'. +apply_years_offset(Datetime, AY) -> + {{Y, M, D}, {H, MM, S}} = Datetime, + {{Y+AY, M, D}, {H, MM, S}}. + +-spec find_last_valid_date(datetime()) -> datetime(). +%% @doc Decrease days until found valid date'. +find_last_valid_date(Datetime)-> + {{Y, M, D}, {H, MM, S}} = Datetime, + case calendar:valid_date({Y, M, D}) of + true -> Datetime; + false -> find_last_valid_date({{Y, M, D-1}, {H, MM, S}}) + end. diff --git a/deps/nimble_parsec/.formatter.exs b/deps/nimble_parsec/.formatter.exs new file mode 100644 index 0000000000000000000000000000000000000000..1a415cedab6a5802e5a9d8a78be107a5f44da4fe --- /dev/null +++ b/deps/nimble_parsec/.formatter.exs @@ -0,0 +1,17 @@ +# Used by "mix format" +locals_without_parens = [ + defparsec: 2, + defparsec: 3, + defparsecp: 2, + defparsecp: 3, + defcombinator: 2, + defcombinator: 3, + defcombinatorp: 2, + defcombinatorp: 3 +] + +[ + inputs: ["mix.exs", "{examples,lib,test}/**/*.{ex,exs}"], + locals_without_parens: locals_without_parens, + export: [locals_without_parens: locals_without_parens] +] diff --git a/deps/nimble_parsec/.hex b/deps/nimble_parsec/.hex new file mode 100644 index 0000000000000000000000000000000000000000..a20cb620175ff3b070d36aa8a26b64c83c2213b2 Binary files /dev/null and b/deps/nimble_parsec/.hex differ diff --git a/deps/nimble_parsec/CHANGELOG.md b/deps/nimble_parsec/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..8463ad3bda9df7e1e2b1989d962dc928bc2cdfb1 --- /dev/null +++ b/deps/nimble_parsec/CHANGELOG.md @@ -0,0 +1,183 @@ +# Changelog for NimbleParsec + +## v1.4.2 (2025-01-21) + +### Enhancements + + * Remove more warnings on Elixir v1.18+ + +## v1.4.1 (2025-01-15) + +### Enhancements + + * Remove warnings on Elixir v1.18+ + +## v1.4.0 (2023-11-08) + +### Enhancements + + * Remove warnings and require Elixir v1.12 + +## v1.3.1 (2023-04-30) + +### Bug fixes + + * Make error messages consistent across Elixir versions + * Ensure `integer(max: ...)` also sets a minimum of 1 + * Do not lose context on `repeat_while` + +## v1.3.0 (2023-03-27) + +### Deprecations + + * Deprecate returning a `{acc, context}` from `quoted_post_traverse` and `quoted_pre_traverse`. Return `{rest, acc, context}` instead. + +### Bug fixes + + * Avoid compile warnings with negative lookahead + * Fix clause warning for integer combinator + +## v1.2.3 (2022-02-28) + +### Enhancements + + * Allow `:export_combinator` in `defparsec` + +## v1.2.2 (2022-02-12) + +### Enhancements + + * Allow `rest` to be returned from post_traverse/pre_traverse + +## v1.2.1 (2022-01-26) + +### Bug fixes + + * Improve typespecs + +## v1.2.0 (2021-11-07) + +### Enhancements + + * Add generator support to `NimbleParsec`: it now generates code that matches a combinator + +### Bug fixes + + * Fix using `eventually` with constructs that can accumulate + * Fix lookahead combinators running in reverse order + * Raise on invalid `min` for integer + +## v1.1.0 (2020-10-02) + +### Enhancements + + * Add `defcombinator` and support for remote `parsec`. This allows larger parsers to be broken over multiple modules to speed up compilation by leveraging parallelism. + +## v1.0.0 (2020-09-25) + +### Enhancements + + * Allow `byte_offset` to be given to `:line` + +## v0.6.0 (2020-05-25) + +NimbleParsec v0.6.0 requires Elixir v1.6+. + +### Bug fixes + + * Avoid unused variable warnings + +## v0.5.3 (2019-12-11) + +### Enhancements + + * Add `eventually/2` combinator + +## v0.5.2 (2019-11-10) + +### Enhancements + + * Optimize `repeat` with initial `lookahead` + * Add `@spec` to `parsec/2` + +## v0.5.1 (2019-08-04) + +### Enhancements + + * Remove dialyzer warnings from emitted code + * Optimize lookahead with choice + * Support min: 0 on utf8_string/ascii_string + * Remove compiler warnings in code generated by `mix nimble_parsec.compile` + * Add `@spec` to combinators + +## v0.5.0 (2018-12-12) + +### Enhancements + + * Introduce `pre_traverse/3` + * Introduce `lookahead/2` and `lookahead_not/2` which accepts combinators + * Introduce `eos/1` (end of string combinator) + +### Backwards incompatible changes + + * Deprecate `traverse/3` in favor of `post_traverse/3` + * `repeat_until/3` has been removed in favor of `repeat/2` with `lookahead_not/2` (see `repeat_while/3` docs for an example) + * `lookahead/2` with a call has been removed as it can be easily achieved with a `post_traverse/3` + +## v0.4.0 (2018-08-10) + +### Enhancements + + * Add `defcombinatorp` and clarify the role of `defparsecp` + +## v0.3.2 (2018-06-02) + +### Bug fixes + + * Fix compilation error for certain combinations of ascii_string/utf8_string + traverse + * Respect the `label` construct when wrapping a `choice` + +## v0.3.1 (2018-04-10) + +### Bug fixes + + * Avoid exponential compilation time when line break is unknown + +## v0.3.0 (2018-04-08) + +### Enhancements + + * Add `unwrap`, `tag` and `unwrap_and_tag` + * Add `nimble_parsec.compile` to compile parsers without a NimbleParsec dependency + +## v0.2.2 (2018-03-08) + +### Bug fix + + * Ensure multiple runtime traversals compose + +## v0.2.1 (2018-03-04) + +### Bug fix + + * Do not duplicate entries in integer/ascii_string/utf8_string + +## v0.2.0 (2018-03-04) + +### Enhancements + + * Support parser combinator contexts and return them in ok/error tuples + * Add `ascii_string/3` and `utf_string/3` combinators + * Add `lookahead/2` combinator + * Rename `literal/2` to `string/2` + * Add `line/2` and `byte_offset/2` combinators + * The MFA given to `repeat_while/3` now receives the accumulator, context, line, and byte_offset values and must return `{:cont, context} | {:halt, context}` + * The MFA given to `quoted_repeat_while/3` now receives the accumulator, context, line, and byte_offset values and must return `{:cont, context} | {:halt, context}` + * The MFA given to `traverse/3` now receives the rest, accumulator, context, line, and byte_offset values and must return `{acc, context} | {:error, reason}` + * The MFA given to `quoted_traverse/3` now receives the ASTs for the rest, accumulator, context, line, and byte_offset and must return `{acc, context} | {:error, reason}` + * Instead of `line` as a positive integer, we now track `{line, line_offset}` where `line` is the same as before and `line_offset` is the byte offset after the new line + * Instead of `column` as a positive integer, we now track `byte_offset` as a non-negative integer + +## v0.1.0 (2018-03-02) + + * First release. diff --git a/deps/nimble_parsec/README.md b/deps/nimble_parsec/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e005e35c5f9375c31c87c6843ac98af55050da24 --- /dev/null +++ b/deps/nimble_parsec/README.md @@ -0,0 +1,156 @@ +# NimbleParsec + +[![CI](https://github.com/dashbitco/nimble_parsec/actions/workflows/ci.yml/badge.svg)](https://github.com/dashbitco/nimble_parsec/actions/workflows/ci.yml) +[![Module Version](https://img.shields.io/hexpm/v/nimble_parsec.svg)](https://hex.pm/packages/nimble_parsec) +[![Hex Docs](https://img.shields.io/badge/hex-docs-lightgreen.svg)](https://hexdocs.pm/nimble_parsec) + + + +`NimbleParsec` is a simple and fast library for text-based parser +combinators. + +Combinators are composed programmatically and compiled into multiple +clauses with binary matching. This provides the following benefits: + + * Performance: since it compiles to binary matching, it leverages + many Erlang VM optimizations to generate a fast parser code with + low memory usage + + * Composable: this library does not rely on macros for building and + composing parsers, therefore they are fully composable. The only + macros are `defparsec/3` and `defparsecp/3` which emit the compiled + clauses with binary matching + + * No runtime dependency: after compilation, the generated parser + clauses have no runtime dependency on `NimbleParsec`. This opens up + the possibility to compile parsers and do not impose a dependency on + users of your library + + * No footprints: `NimbleParsec` only needs to be imported in your modules. + There is no need for `use NimbleParsec`, leaving no footprints on your + modules + +The goal of this library is to focus on a set of primitives for writing +efficient parser combinators. The composition aspect means you should be +able to use those primitives to implement higher level combinators. + +Note this library does not handle low-level binary parsing. In such cases, +we recommend using [Elixir's bitstring syntax](https://hexdocs.pm/elixir/Kernel.SpecialForms.html#%3C%3C%3E%3E/1). + +## Examples + +```elixir +defmodule MyParser do + import NimbleParsec + + date = + integer(4) + |> ignore(string("-")) + |> integer(2) + |> ignore(string("-")) + |> integer(2) + + time = + integer(2) + |> ignore(string(":")) + |> integer(2) + |> ignore(string(":")) + |> integer(2) + |> optional(string("Z")) + + defparsec :datetime, date |> ignore(string("T")) |> concat(time), debug: true +end + +MyParser.datetime("2010-04-17T14:12:34Z") +#=> {:ok, [2010, 4, 17, 14, 12, 34, "Z"], "", %{}, {1, 0}, 20} +``` + +If you add `debug: true` to `defparsec/3`, it will print the generated +clauses, which are shown below: + +```elixir +defp datetime__0(<>, + acc, stack, comb__context, comb__line, comb__column) + when x0 >= 48 and x0 <= 57 and (x1 >= 48 and x1 <= 57) and + (x2 >= 48 and x2 <= 57) and (x3 >= 48 and x3 <= 57) and + (x4 >= 48 and x4 <= 57) and (x5 >= 48 and x5 <= 57) and + (x6 >= 48 and x6 <= 57) and (x7 >= 48 and x7 <= 57) and + (x8 >= 48 and x8 <= 57) and (x9 >= 48 and x9 <= 57) and + (x10 >= 48 and x10 <= 57) and (x11 >= 48 and x11 <= 57) and + (x12 >= 48 and x12 <= 57) and (x13 >= 48 and x13 <= 57) do + datetime__1( + rest, + [(x13 - 48) * 1 + (x12 - 48) * 10, (x11 - 48) * 1 + (x10 - 48) * 10, + (x9 - 48) * 1 + (x8 - 48) * 10, (x7 - 48) * 1 + (x6 - 48) * 10, (x5 - 48) * 1 + (x4 - 48) * 10, + (x3 - 48) * 1 + (x2 - 48) * 10 + (x1 - 48) * 100 + (x0 - 48) * 1000] ++ acc, + stack, + comb__context, + comb__line, + comb__column + 19 + ) +end + +defp datetime__0(rest, acc, _stack, context, line, column) do + {:error, "...", rest, context, line, column} +end + +defp datetime__1(<<"Z", rest::binary>>, acc, stack, comb__context, comb__line, comb__column) do + datetime__2(rest, ["Z"] ++ acc, stack, comb__context, comb__line, comb__column + 1) +end + +defp datetime__1(rest, acc, stack, context, line, column) do + datetime__2(rest, acc, stack, context, line, column) +end + +defp datetime__2(rest, acc, _stack, context, line, column) do + {:ok, acc, rest, context, line, column} +end +``` + +As you can see, it generates highly inlined code, comparable to +hand-written parsers. This gives `NimbleParsec` an order of magnitude +performance gains compared to other parser combinators. Further performance +can be gained by giving the `inline: true` option to `defparsec/3`. + + + +## Installation + +Add `nimble_parsec` to your list of dependencies in `mix.exs`: + +```elixir +def deps do + [ + {:nimble_parsec, "~> 1.0"} + ] +end +``` + +## Nimble* + +All nimble libraries by Dashbit: + + * [NimbleCSV](https://github.com/dashbitco/nimble_csv) - simple and fast CSV parsing + * [NimbleOptions](https://github.com/dashbitco/nimble_options) - tiny library for validating and documenting high-level options + * [NimbleParsec](https://github.com/dashbitco/nimble_parsec) - simple and fast parser combinators + * [NimblePool](https://github.com/dashbitco/nimble_pool) - tiny resource-pool implementation + * [NimblePublisher](https://github.com/dashbitco/nimble_publisher) - a minimal filesystem-based publishing engine with Markdown support and code highlighting + * [NimbleTOTP](https://github.com/dashbitco/nimble_totp) - tiny library for generating time-based one time passwords (TOTP) + +## License + +Copyright 2018 Plataformatec \ +Copyright 2020 Dashbit + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/deps/nimble_parsec/hex_metadata.config b/deps/nimble_parsec/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..5dbdfd08b6769a4f0f34dcd6077c8c6870bfd3a8 --- /dev/null +++ b/deps/nimble_parsec/hex_metadata.config @@ -0,0 +1,16 @@ +{<<"links">>, + [{<<"GitHub">>,<<"https://github.com/dashbitco/nimble_parsec">>}]}. +{<<"name">>,<<"nimble_parsec">>}. +{<<"version">>,<<"1.4.2">>}. +{<<"description">>, + <<"A simple and fast library for text-based parser combinators">>}. +{<<"elixir">>,<<"~> 1.12">>}. +{<<"files">>, + [<<"lib">>,<<"lib/nimble_parsec">>,<<"lib/nimble_parsec/recorder.ex">>, + <<"lib/nimble_parsec/compiler.ex">>,<<"lib/mix">>,<<"lib/mix/tasks">>, + <<"lib/mix/tasks/nimble_parsec.compile.ex">>,<<"lib/nimble_parsec.ex">>, + <<".formatter.exs">>,<<"mix.exs">>,<<"README.md">>,<<"CHANGELOG.md">>]}. +{<<"app">>,<<"nimble_parsec">>}. +{<<"licenses">>,[<<"Apache-2.0">>]}. +{<<"requirements">>,[]}. +{<<"build_tools">>,[<<"mix">>]}. diff --git a/deps/nimble_parsec/lib/mix/tasks/nimble_parsec.compile.ex b/deps/nimble_parsec/lib/mix/tasks/nimble_parsec.compile.ex new file mode 100644 index 0000000000000000000000000000000000000000..a1eae25d213242ce04817f74ad76b106ad596f93 --- /dev/null +++ b/deps/nimble_parsec/lib/mix/tasks/nimble_parsec.compile.ex @@ -0,0 +1,118 @@ +defmodule Mix.Tasks.NimbleParsec.Compile do + @shortdoc "Compiles a parser and injects its content into the parser file" + + @moduledoc ~S""" + Compiles a parser from a template. + + $ mix nimble_parsec.compile template.ex.exs + + This task is useful to generate parsers that have no runtime dependency + on NimbleParsec. + + ## Examples + + Let's define a template file: + + # lib/my_parser.ex.exs + defmodule MyParser do + @moduledoc false + + # parsec:MyParser + import NimbleParsec + + date = + integer(4) + |> ignore(string("-")) + |> integer(2) + |> ignore(string("-")) + |> integer(2) + + time = + integer(2) + |> ignore(string(":")) + |> integer(2) + |> ignore(string(":")) + |> integer(2) + |> optional(string("Z")) + + defparsec :datetime, date |> ignore(string("T")) |> concat(time) + + # parsec:MyParser + end + + After running: + + $ mix nimble_parsec.compile lib/my_parser.ex.exs + + The following file will be generated: + + # lib/my_parser.ex + defmodule MyParser do + @moduledoc false + + def datetime(binary, opts \\ []) do + ... + end + + defp datetime__0(...) do + ... + end + + ... + end + + The file will be automatically formatted if using Elixir v1.6+. + + ## Options + + * `-o` - configures the output location. Defaults to the input + file without its last extension + + """ + + use Mix.Task + + @impl true + def run(args) do + Mix.Task.reenable("nimble_parsec.compile") + {opts, files} = OptionParser.parse!(args, strict: [output: :string], aliases: [o: :output]) + Mix.Task.run("compile") + + case files do + [file] -> compile(file, opts) + _ -> Mix.raise("Expected a single file to be given to nimble_parsec.compile") + end + end + + defp compile(input, opts) do + output = opts[:output] || Path.rootname(input) + Mix.shell().info("Generating #{output}") + + {:ok, _} = NimbleParsec.Recorder.start_link([]) + + try do + Code.compiler_options(ignore_module_conflict: true) + Code.require_file(input) + + input + |> File.read!() + |> NimbleParsec.Recorder.replay(input) + |> write_to_disk(input, output) + after + Code.compiler_options(ignore_module_conflict: false) + NimbleParsec.Recorder.stop() + end + end + + defp write_to_disk(contents, input, output) do + now = DateTime.utc_now() |> Map.put(:microsecond, {0, 0}) |> to_string + + prelude = """ + # Generated from #{input}, do not edit. + # Generated at #{now}. + + """ + + File.write!(output, [prelude | contents]) + end +end diff --git a/deps/nimble_parsec/lib/nimble_parsec.ex b/deps/nimble_parsec/lib/nimble_parsec.ex new file mode 100644 index 0000000000000000000000000000000000000000..766caa1fa486c4e1660343f73551ba535db77a0c --- /dev/null +++ b/deps/nimble_parsec/lib/nimble_parsec.ex @@ -0,0 +1,2126 @@ +defmodule NimbleParsec do + @moduledoc "README.md" + |> File.read!() + |> String.split("") + |> Enum.fetch!(1) + + defmacrop is_combinator(combinator) do + quote do + is_list(unquote(combinator)) + end + end + + @doc """ + Defines a parser (and a combinator) with the given `name` and `opts`. + + The parser is a function that receives two arguments, the binary + to be parsed and a set of options. You can consult the documentation + of the generated parser function for more information. + + This function will also define a combinator that can be used as + `parsec(name)` when building other parsers. See `parsec/2` for + more information on invoking compiled combinators. + + ## Beware! + + `defparsec/3` is executed during compilation. This means you can't + invoke a function defined in the same module. The following will error + because the `date` function has not yet been defined: + + defmodule MyParser do + import NimbleParsec + + def date do + integer(4) + |> ignore(string("-")) + |> integer(2) + |> ignore(string("-")) + |> integer(2) + end + + defparsec :date, date() + end + + This can be solved in different ways. You may simply + compose a long parser using variables. For example: + + defmodule MyParser do + import NimbleParsec + + date = + integer(4) + |> ignore(string("-")) + |> integer(2) + |> ignore(string("-")) + |> integer(2) + + defparsec :date, date + end + + Alternatively, you may define a `Helpers` module with many + convenience combinators, and then invoke them in your parser + module: + + defmodule MyParser.Helpers do + import NimbleParsec + + def date do + integer(4) + |> ignore(string("-")) + |> integer(2) + |> ignore(string("-")) + |> integer(2) + end + end + + defmodule MyParser do + import NimbleParsec + import MyParser.Helpers + + defparsec :date, date() + end + + The approach of using helper modules is the favorite way + of composing parsers in `NimbleParsec`. + + ## Options + + * `:inline` - when true, inlines clauses that work as redirection for + other clauses. Settings this may improve runtime performance at the + cost of increased compilation time and bytecode size + + * `:debug` - when true, writes generated clauses to `:stderr` for debugging + + * `:export_combinator` - make the underlying combinator function public + so it can be used as part of `parsec/1` from other modules + + * `:export_metadata` - export metadata necessary to use this parser + combinator to generate inputs + + """ + defmacro defparsec(name, combinator, opts \\ []) do + visibility = + quote do + if opts[:export_combinator], do: :def, else: :defp + end + + compile(:def, visibility, name, combinator, opts) + end + + @doc """ + Defines a private parser (and a combinator) with the given `name` and `opts`. + + The same as `defparsec/3` but the parsing function is private. + """ + defmacro defparsecp(name, combinator, opts \\ []) do + compile(:defp, :defp, name, combinator, opts) + end + + @doc """ + Defines a combinator with the given `name` and `opts`. + + It is similar to `defparsec/3` except it does not define + an entry-point parsing function, just the combinator function + to be used with `parsec/2`. + """ + defmacro defcombinator(name, combinator, opts \\ []) do + compile(nil, :def, name, combinator, opts) + end + + @doc """ + Defines a combinator with the given `name` and `opts`. + + It is similar to `defparsecp/3` except it does not define + an entry-point parsing function, just the combinator function + to be used with `parsec/2`. + """ + defmacro defcombinatorp(name, combinator, opts \\ []) do + compile(nil, :defp, name, combinator, opts) + end + + defp compile(parser_kind, combinator_kind, name, combinator, opts) do + prelude = + quote do + opts = unquote(opts) + combinator_kind = unquote(combinator_kind) + end + + combinator = + quote bind_quoted: [ + parser_kind: parser_kind, + name: name, + combinator: combinator + ] do + {defs, inline} = NimbleParsec.Compiler.compile(name, combinator, opts) + + NimbleParsec.Recorder.record( + __MODULE__, + parser_kind, + combinator_kind, + name, + defs, + inline, + opts + ) + + if opts[:export_metadata] do + def __nimble_parsec__(unquote(name)), + do: unquote(combinator |> Enum.reverse() |> Macro.escape()) + end + + if inline != [] do + @compile {:inline, inline} + end + + if combinator_kind == :def do + for {name, args, guards, body} <- defs do + def unquote(name)(unquote_splicing(args)) when unquote(guards), do: unquote(body) + end + else + for {name, args, guards, body} <- defs do + defp unquote(name)(unquote_splicing(args)) when unquote(guards), do: unquote(body) + end + end + end + + parser = compile_parser(name, parser_kind) + + quote do + unquote(prelude) + unquote(parser) + unquote(combinator) + end + end + + defp compile_parser(_name, nil) do + :ok + end + + defp compile_parser(name, :def) do + quote bind_quoted: [name: name] do + {doc, spec, {name, args, guards, body}} = NimbleParsec.Compiler.entry_point(name) + Module.get_attribute(__MODULE__, :doc) || @doc doc + @spec unquote(spec) + def unquote(name)(unquote_splicing(args)) when unquote(guards), do: unquote(body) + end + end + + defp compile_parser(name, :defp) do + quote bind_quoted: [name: name] do + {_doc, spec, {name, args, guards, body}} = NimbleParsec.Compiler.entry_point(name) + @spec unquote(spec) + defp unquote(name)(unquote_splicing(args)) when unquote(guards), do: unquote(body) + end + end + + @opaque t :: [combinator] + @type bin_modifier :: :integer | :utf8 | :utf16 | :utf32 + @type range :: inclusive_range | exclusive_range + @type inclusive_range :: Range.t() | char + @type exclusive_range :: {:not, Range.t()} | {:not, char} + @type min_and_max :: {:min, non_neg_integer} | {:max, pos_integer} + @type call :: mfargs | fargs | atom + @type mfargs :: {module, atom, args :: [term]} + @type fargs :: {atom, args :: [term]} + @type gen_times :: Range.t() | non_neg_integer | nil + @type gen_weights :: [pos_integer] | nil + @type opts :: Keyword.t() + + # Steps to add a new combinator: + # + # 1. Update the combinator type below + # 2. Update the compiler with combinator + # 3. Update the compiler with label step + # + @typep combinator :: bound_combinator | maybe_bound_combinator | unbound_combinator + + @typep bound_combinator :: + {:bin_segment, [inclusive_range], [exclusive_range], bin_modifier} + | {:string, binary} + | {:bytes, pos_integer} + | :eos + + @typep maybe_bound_combinator :: + {:label, t, binary} + | {:traverse, t, :pre | :post | :constant, [mfargs]} + + @typep unbound_combinator :: + {:choice, [t], gen_weights} + | {:eventually, t} + | {:lookahead, t, :positive | :negative} + | {:parsec, atom | {module, atom}} + | {:repeat, t, mfargs, gen_times} + | {:times, t, pos_integer} + + @doc ~S""" + Generate a random binary from the given parsec. + + Let's see an example: + + import NimbleParsec + generate(choice([string("foo"), string("bar")])) + + The command above will return either "foo" or "bar". `generate/1` + is often used with pre-defined parsecs. In this case, the + `:export_metadata` flag must be set: + + defmodule SomeModule do + import NimbleParsec + defparsec :parse, + choice([string("foo"), string("bar")]), + export_metadata: true + end + + # Reference the parsec and generate from it + NimbleParsec.parsec({SomeModule, :parse}) + |> NimbleParsec.generate() + |> IO.puts() + + `generate/1` can often run forever for recursive algorithms. + Read the notes below and make use of the `gen_weight` and `gen_times` + option to certain parsecs to control the recursion depth. + + ## Notes + + Overall, there is no guarantee over the generated output, except + that it will generate a binary that is parseable by the parsec + itself, but even this guarantee may be broken by parsers that have + custom validations. Keep in mind the following: + + * `generate/1` is not compatible with NimbleParsecs dumped via + `mix nimble_parsec.compile`; + + * `parsec/2` requires the referenced parsec to set `export_metadata: true` + on its definition; + + * `choice/2` will be generated evenly. You can pass `:gen_weights` + as a list of positive integer weights to balance your choices. + This is particularly important for recursive algorithms; + + * `repeat/2` and `repeat_while/3` will repeat between 0 and 3 times unless + a `:gen_times` option is given to these operations. `times/3` without a `:max` + will also additionally repeat between 0 and 3 times unless `:gen_times` is given. + The `:gen_times` option can either be an integer as the number of times to + repeat or a range where a random value in the range will be picked; + + * `eventually/2` always generates the eventually parsec immediately; + + * `lookahead/2` and `lookahead_not/2` are simply discarded; + + * Validations done in any of the traverse definitions are not taken into account + by the generator. Therefore, if a parsec does validations, the generator may + generate binaries invalid to said parsec; + + """ + def generate(parsecs) do + parsecs + |> Enum.reverse() + |> generate(nil, []) + |> IO.iodata_to_binary() + end + + defp generate([{:parsec, fun} | _parsecs], nil, _acc) when is_atom(fun) do + raise "cannot generate parsec(#{inspect(fun)}), use a remote parsec instead" + end + + defp generate([{:parsec, fun} | parsecs], mod, acc) when is_atom(fun) do + generate([{:parsec, {mod, fun}} | parsecs], mod, acc) + end + + defp generate([{:parsec, {mod, fun}} | outer_parsecs], outer_mod, acc) do + gen = generate(gen_export(mod, fun), mod, []) + generate(outer_parsecs, outer_mod, [gen | acc]) + end + + defp generate([{:string, string} | parsecs], mod, acc) do + generate(parsecs, mod, [string | acc]) + end + + defp generate([{:bin_segment, inclusive, exclusive, modifier} | parsecs], mod, acc) do + gen = gen_bin_segment(inclusive, exclusive) + + gen = + if modifier == :integer, + do: gen, + else: :unicode.characters_to_binary([gen], :unicode, modifier) + + generate(parsecs, mod, [gen | acc]) + end + + defp generate([:eos | parsecs], mod, acc) do + if parsecs == [] do + generate([], mod, acc) + else + raise ArgumentError, "found :eos not at the end of parsecs" + end + end + + defp generate([{:traverse, t, _, _} | parsecs], mod, acc) do + generate(t ++ parsecs, mod, acc) + end + + defp generate([{:label, t, _} | parsecs], mod, acc) do + generate(t ++ parsecs, mod, acc) + end + + defp generate([{:choice, choices, weights} | parsecs], mod, acc) do + pick = if weights, do: weighted_random(choices, weights), else: list_random(choices) + gen = generate(pick, mod, []) + generate(parsecs, mod, [gen | acc]) + end + + defp generate([{:lookahead, _, _} | parsecs], mod, acc) do + generate(parsecs, mod, acc) + end + + defp generate([{:repeat, t, _, gen} | parsecs], mod, acc) do + generate(parsecs, mod, gen_times(t, int_random(gen), mod, acc)) + end + + defp generate([{:times, t, max} | parsecs], mod, acc) do + generate(parsecs, mod, gen_times(t, Enum.random(0..max), mod, acc)) + end + + defp generate([{:bytes, count} | parsecs], mod, acc) do + bytes = bytes_random(count) + generate(parsecs, mod, [bytes | acc]) + end + + defp generate([], _mod, acc), do: Enum.reverse(acc) + + defp gen_export(mod, fun) do + unless Code.ensure_loaded?(mod) do + raise "cannot handle parsec(#{inspect({mod, fun})}) because #{inspect(mod)} is not available" + end + + try do + mod.__nimble_parsec__(fun) + rescue + _ -> + raise "cannot handle parsec(#{inspect({mod, fun})}) because #{inspect(mod)} " <> + "did not set :export_metadata when defining #{fun}" + end + end + + defp gen_times(_t, 0, _mod, acc), do: acc + + defp gen_times(t, n, mod, acc) do + gen = generate(t, mod, []) + gen_times(t, n - 1, mod, [gen | acc]) + end + + defp gen_bin_segment(inclusive, exclusive) do + gen = + if(inclusive == [], do: [0..255], else: inclusive) + |> list_random() + |> int_random() + + if Enum.any?(exclusive, &exclude_bin_segment?(&1, gen)) do + gen_bin_segment(inclusive, exclusive) + else + gen + end + end + + defp exclude_bin_segment?({:not, _.._//_ = range}, gen), do: gen in range + defp exclude_bin_segment?({:not, char}, gen) when is_integer(char), do: char == gen + + defp int_random(nil), do: Enum.random(0..3) + defp int_random(_.._//_ = range), do: Enum.random(range) + defp int_random(int) when is_integer(int), do: int + + # Enum.random uses reservoir sampling but our lists are short, so we use length + fetch! + defp list_random(list) when is_list(list), + do: Enum.fetch!(list, :rand.uniform(length(list)) - 1) + + defp weighted_random(list, weights) do + weighted_random(list, weights, :rand.uniform(Enum.sum(weights))) + end + + defp weighted_random([elem | _], [weight | _], chosen) when chosen <= weight, + do: elem + + defp weighted_random([_ | list], [weight | weights], chosen), + do: weighted_random(list, weights, chosen - weight) + + defp bytes_random(count) when is_integer(count) do + :crypto.strong_rand_bytes(count) + end + + @doc ~S""" + Returns an empty combinator. + + An empty combinator cannot be compiled on its own. + """ + @spec empty() :: t + def empty() do + [] + end + + @doc """ + Invokes an already compiled combinator with name `name` in the + same module. + + Every parser defined via `defparsec/3` or `defparsecp/3` can be + used as combinator. However, the `defparsec/3` and `defparsecp/3` + functions also define an entry-point parsing function, as implied + by their names. If you want to define a combinator with the sole + purpose of using it in combinator, use `defcombinatorp/3` instead. + + ## Use cases + + `parsec/2` is useful to implement recursive definitions. + + Note, while `parsec/2` can be used to compose smaller combinators, + the preferred mechanism for doing composition is via regular functions + and not via `parsec/2`. Let's see a practical example. Imagine + that you have this module: + + defmodule MyParser do + import NimbleParsec + + date = + integer(4) + |> ignore(string("-")) + |> integer(2) + |> ignore(string("-")) + |> integer(2) + + time = + integer(2) + |> ignore(string(":")) + |> integer(2) + |> ignore(string(":")) + |> integer(2) + |> optional(string("Z")) + + defparsec :datetime, date |> ignore(string("T")) |> concat(time), debug: true + end + + Now imagine that you want to break `date` and `time` apart + into helper functions, as you use them in other occasions. + Generally speaking, you should **NOT** do this: + + defmodule MyParser do + import NimbleParsec + + defcombinatorp :date, + integer(4) + |> ignore(string("-")) + |> integer(2) + |> ignore(string("-")) + |> integer(2) + + defcombinatorp :time, + integer(2) + |> ignore(string(":")) + |> integer(2) + |> ignore(string(":")) + |> integer(2) + |> optional(string("Z")) + + defparsec :datetime, + parsec(:date) |> ignore(string("T")) |> concat(parsec(:time)) + end + + The reason why the above is not recommended is because each + `parsec/2` combinator ends-up adding a stacktrace entry during + parsing, which affects the ability of `NimbleParsec` to optimize + code. If the goal is to compose combinators, you can do so + with modules and functions: + + defmodule MyParser.Helpers do + import NimbleParsec + + def date do + integer(4) + |> ignore(string("-")) + |> integer(2) + |> ignore(string("-")) + |> integer(2) + end + + def time do + integer(2) + |> ignore(string(":")) + |> integer(2) + |> ignore(string(":")) + |> integer(2) + |> optional(string("Z")) + end + end + + defmodule MyParser do + import NimbleParsec + import MyParser.Helpers + + defparsec :datetime, + date() |> ignore(string("T")) |> concat(time()) + end + + The implementation above will be able to compile to the most + efficient format as possible without forcing new stacktrace + entries. + + The only situation where you should use `parsec/2` for composition + is when a large parser is used over and over again in a way + compilation times are high. In this sense, you can use `parsec/2` + to improve compilation time at the cost of runtime performance. + By using `parsec/2`, the tree size built at compile time will be + reduced although runtime performance is degraded as `parsec` + introduces a stacktrace entry. + + ## Remote combinators + + You can also reference combinators in other modules by passing + a tuple with the module name and a function to `parsec/2` as follows: + + defmodule RemoteCombinatorModule do + defcombinator :upcase_unicode, utf8_char([...long, list, of, unicode, chars...]) + end + + defmodule LocalModule do + # Parsec that depends on `:upcase_A` + defparsec :parsec_name, + ... + |> ascii_char([?a..?Z]) + |> parsec({RemoteCombinatorModule, :upcase_unicode}) + end + + Remote combinators are useful when breaking the compilation of + large modules apart in order to use Elixir's ability to compile + modules in parallel. + + ## Examples + + A good example of using `parsec` is with recursive parsers. + A limited but recursive XML parser could be written as follows: + + defmodule SimpleXML do + import NimbleParsec + + tag = ascii_string([?a..?z, ?A..?Z], min: 1) + text = ascii_string([not: ?<], min: 1) + + opening_tag = + ignore(string("<")) + |> concat(tag) + |> ignore(string(">")) + + closing_tag = + ignore(string(" concat(tag) + |> ignore(string(">")) + + defparsec :xml, + opening_tag + |> repeat(lookahead_not(string(" choice([parsec(:xml), text])) + |> concat(closing_tag) + |> wrap() + end + + SimpleXML.xml("bar") + #=> {:ok, [["foo", "bar", "foo"]], "", %{}, {1, 0}, 14} + + In the example above, `defparsec/3` has defined the entry-point + parsing function as well as a combinator which we have invoked + with `parsec(:xml)`. + + In many cases, however, you want to define recursive combinators + without the entry-point parsing function. We can do this by + replacing `defparsec/3` by `defcombinatorp`: + + defcombinatorp :xml, + opening_tag + |> repeat(lookahead_not(string(" choice([parsec(:xml), text])) + |> concat(closing_tag) + |> wrap() + + When using `defcombinatorp`, you can no longer invoke + `SimpleXML.xml(xml)` as there is no associated parsing function. + You can only access the combinator above via `parsec/2`. + """ + @spec parsec(name :: atom) :: t + @spec parsec(t, name :: atom) :: t + @spec parsec({module, function_name :: atom}) :: t + @spec parsec(t, {module, function_name :: atom}) :: t + def parsec(combinator \\ empty(), name) + + def parsec(combinator, name) when is_combinator(combinator) and is_atom(name) do + [{:parsec, name} | combinator] + end + + def parsec(combinator, {module, function}) + when is_combinator(combinator) and is_atom(module) and is_atom(function) do + [{:parsec, {module, function}} | combinator] + end + + @doc ~S""" + Defines a single ASCII codepoint in the given ranges. + + `ranges` is a list containing one of: + + * a `min..max` range expressing supported codepoints + * a `codepoint` integer expressing a supported codepoint + * `{:not, min..max}` expressing not supported codepoints + * `{:not, codepoint}` expressing a not supported codepoint + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :digit_and_lowercase, + empty() + |> ascii_char([?0..?9]) + |> ascii_char([?a..?z]) + end + + MyParser.digit_and_lowercase("1a") + #=> {:ok, [?1, ?a], "", %{}, {1, 0}, 2} + + MyParser.digit_and_lowercase("a1") + #=> {:error, "expected ASCII character in the range '0' to '9', followed by ASCII character in the range 'a' to 'z'", "a1", %{}, {1, 0}, 0} + + """ + @spec ascii_char([range]) :: t + @spec ascii_char(t, [range]) :: t + def ascii_char(combinator \\ empty(), ranges) + when is_combinator(combinator) and is_list(ranges) do + {inclusive, exclusive} = split_ranges!(ranges, "ascii_char") + bin_segment(combinator, inclusive, exclusive, :integer) + end + + @doc ~S""" + Defines a single UTF-8 codepoint in the given ranges. + + `ranges` is a list containing one of: + + * a `min..max` range expressing supported codepoints + * a `codepoint` integer expressing a supported codepoint + * `{:not, min..max}` expressing not supported codepoints + * `{:not, codepoint}` expressing a not supported codepoint + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :digit_and_utf8, + empty() + |> utf8_char([?0..?9]) + |> utf8_char([]) + end + + MyParser.digit_and_utf8("1é") + #=> {:ok, [?1, ?é], "", %{}, {1, 0}, 2} + + MyParser.digit_and_utf8("a1") + #=> {:error, "expected utf8 codepoint in the range '0' to '9', followed by utf8 codepoint", "a1", %{}, {1, 0}, 0} + + """ + @spec utf8_char([range]) :: t + @spec utf8_char(t, [range]) :: t + def utf8_char(combinator \\ empty(), ranges) + when is_combinator(combinator) and is_list(ranges) do + {inclusive, exclusive} = split_ranges!(ranges, "utf8_char") + bin_segment(combinator, inclusive, exclusive, :utf8) + end + + @doc ~S""" + Adds a label to the combinator to be used in error reports. + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :digit_and_lowercase, + empty() + |> ascii_char([?0..?9]) + |> ascii_char([?a..?z]) + |> label("digit followed by lowercase letter") + end + + MyParser.digit_and_lowercase("1a") + #=> {:ok, [?1, ?a], "", %{}, {1, 0}, 2} + + MyParser.digit_and_lowercase("a1") + #=> {:error, "expected a digit followed by lowercase letter", "a1", %{}, {1, 0}, 0} + + """ + @spec label(t, String.t()) :: t + @spec label(t, t, String.t()) :: t + def label(combinator \\ empty(), to_label, label) + when is_combinator(combinator) and is_combinator(to_label) and is_binary(label) do + non_empty!(to_label, "label") + [{:label, Enum.reverse(to_label), label} | combinator] + end + + @doc ~S""" + Defines an integer combinator with exact length or `min` and `max` + length. + + If you want an integer of unknown size, use `integer(min: 1)`. + + This combinator does not parse the sign and is always on base 10. + + ## Examples + + With exact length: + + defmodule MyParser do + import NimbleParsec + + defparsec :two_digits_integer, integer(2) + end + + MyParser.two_digits_integer("123") + #=> {:ok, [12], "3", %{}, {1, 0}, 2} + + MyParser.two_digits_integer("1a3") + #=> {:error, "expected ASCII character in the range '0' to '9', followed by ASCII character in the range '0' to '9'", "1a3", %{}, {1, 0}, 0} + + With min and max: + + defmodule MyParser do + import NimbleParsec + + defparsec :two_digits_integer, integer(min: 2, max: 4) + end + + MyParser.two_digits_integer("123") + #=> {:ok, [123], "", %{}, {1, 0}, 2} + + MyParser.two_digits_integer("1a3") + #=> {:error, "expected ASCII character in the range '0' to '9', followed by ASCII character in the range '0' to '9'", "1a3", %{}, {1, 0}, 0} + + If the size of the integer has a min and max close to each other, such as + from 2 to 4 or from 1 to 2, using choice may emit more efficient code: + + choice([integer(4), integer(3), integer(2)]) + + Note you should start from bigger to smaller. + """ + @spec integer(pos_integer | [min_and_max]) :: t + @spec integer(t, pos_integer | [min_and_max]) :: t + def integer(combinator \\ empty(), count_or_opts) + + def integer(combinator, count) + when is_combinator(combinator) and is_integer(count) do + validate_min_and_max!(count, 1) + + min_max_compile_runtime_chars( + combinator, + ascii_char([?0..?9]), + count, + :__compile_integer__, + :__runtime_integer__, + [] + ) + end + + def integer(combinator, opts) + when is_combinator(combinator) and is_list(opts) do + # Read the minimum and maximum value to ensure the presence of at least one character + {min_val, max_val} = validate_min_and_max!(opts, 1) + opts = opts |> Keyword.put(:min, min_val) |> Keyword.put(:max, max_val) + + min_max_compile_runtime_chars( + combinator, + ascii_char([?0..?9]), + opts, + :__compile_integer__, + :__runtime_integer__, + [] + ) + end + + @doc ~S""" + Defines an ASCII string combinator with an exact length or `min` and `max` + length. + + The `ranges` specify the allowed characters in the ASCII string. + See `ascii_char/2` for more information. + + If you want a string of unknown size, use `ascii_string(ranges, min: 1)`. + If you want a literal string, use `string/2`. + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :two_lowercase_letters, ascii_string([?a..?z], 2) + end + + MyParser.two_lowercase_letters("abc") + #=> {:ok, ["ab"], "c", %{}, {1, 0}, 2} + + """ + @spec ascii_string([range], pos_integer | [min_and_max]) :: t + @spec ascii_string(t, [range], pos_integer | [min_and_max]) :: t + def ascii_string(combinator \\ empty(), range, count_or_opts) + when is_combinator(combinator) and is_list(range) and + (is_integer(count_or_opts) or is_list(count_or_opts)) do + min_max_compile_runtime_chars( + combinator, + ascii_char(range), + count_or_opts, + :__compile_string__, + :__runtime_string__, + [quote(do: integer)] + ) + end + + @doc ~S""" + Defines an UTF8 string combinator with of exact length or `min` and `max` + codepoint length. + + The `ranges` specify the allowed characters in the UTF8 string. + See `utf8_char/2` for more information. + + If you want a string of unknown size, use `utf8_string(ranges, min: 1)`. + If you want a literal string, use `string/2`. + + Note that the combinator matches on codepoints, not graphemes. Therefore + results may vary depending on whether the input is in `nfc` or `nfd` + normalized form. + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :two_letters, utf8_string([], 2) + end + + MyParser.two_letters("áé") + #=> {:ok, ["áé"], "", %{}, {1, 0}, 3} + + """ + @spec utf8_string([range], pos_integer | [min_and_max]) :: t + @spec utf8_string(t, [range], pos_integer | [min_and_max]) :: t + def utf8_string(combinator \\ empty(), range, count_or_opts) + when is_combinator(combinator) and is_list(range) and + (is_integer(count_or_opts) or is_list(count_or_opts)) do + min_max_compile_runtime_chars( + combinator, + utf8_char(range), + count_or_opts, + :__compile_string__, + :__runtime_string__, + [quote(do: utf8)] + ) + end + + @doc ~S""" + Defines an end of string combinator. + + The end of string does not produce a token and can be parsed multiple times. + This function is useful to avoid having to check for an empty remainder after + a successful parse. + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :letter_pairs, utf8_string([], 2) |> repeat() |> eos() + end + + MyParser.letter_pairs("hi") + #=> {:ok, ["hi"], "", %{}, {1, 0}, 2} + + MyParser.letter_pairs("hello") + #=> {:error, "expected end of string", "o", %{}, {1, 0}, 4} + """ + @spec eos :: t + @spec eos(t) :: t + def eos(combinator \\ empty()) do + [:eos | combinator] + end + + @doc ~S""" + Concatenates two combinators. + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :digit_upper_lower_plus, + concat( + concat(ascii_char([?0..?9]), ascii_char([?A..?Z])), + concat(ascii_char([?a..?z]), ascii_char([?+..?+])) + ) + end + + MyParser.digit_upper_lower_plus("1Az+") + #=> {:ok, [?1, ?A, ?z, ?+], "", %{}, {1, 0}, 4} + + """ + @spec concat(t, t) :: t + def concat(left, right) when is_combinator(left) and is_combinator(right) do + right ++ left + end + + @doc """ + Duplicates the combinator `to_duplicate` `n` times. + """ + @spec duplicate(t, non_neg_integer) :: t + @spec duplicate(t, t, non_neg_integer) :: t + def duplicate(combinator \\ empty(), to_duplicate, n) + + def duplicate(combinator, to_duplicate, 0) + when is_combinator(combinator) and is_combinator(to_duplicate) do + combinator + end + + def duplicate(combinator, to_duplicate, n) + when is_combinator(combinator) and is_combinator(to_duplicate) and is_integer(n) and n >= 1 do + Enum.reduce(1..n, combinator, fn _, acc -> to_duplicate ++ acc end) + end + + @doc """ + Puts the result of the given combinator as the first element + of a tuple with the `byte_offset` as second element. + + `byte_offset` is a non-negative integer. + """ + @spec byte_offset(t) :: t + @spec byte_offset(t, t) :: t + def byte_offset(combinator \\ empty(), to_wrap) + when is_combinator(combinator) and is_combinator(to_wrap) do + quoted_post_traverse(combinator, to_wrap, {__MODULE__, :__byte_offset__, []}) + end + + @doc """ + Puts the result of the given combinator as the first element + of a tuple with the `line` as second element. + + `line` is a tuple where the first element is the current line + and the second element is the byte offset immediately after + the newline. + """ + @spec line(t) :: t + @spec line(t, t) :: t + def line(combinator \\ empty(), to_wrap) + when is_combinator(combinator) and is_combinator(to_wrap) do + quoted_post_traverse(combinator, to_wrap, {__MODULE__, :__line__, []}) + end + + @doc ~S""" + Traverses the combinator results with the remote or local function `call`. + + `call` is either a `{module, function, args}` representing + a remote call, a `{function, args}` representing a local call + or an atom `function` representing `{function, []}`. + + The function given in `call` will receive 5 additional arguments. + The rest of the parsed binary, the parser results to be post_traversed, + the parser context, the current line and the current offset will + be prepended to the given `args`. The `args` will be injected at + the compile site and therefore must be escapable via `Macro.escape/1`. + + The line and offset will represent the location after the combinators. + To retrieve the position before the combinators, use `pre_traverse/3`. + + The `call` must return a tuple `{rest, acc, context}` with list of + results to be added to the accumulator as first argument and a context + as second argument. It may also return `{:error, reason}` to stop + processing. Notice the received results are in reverse order and + must be returned in reverse order too. + + The number of elements returned does not need to be + the same as the number of elements given. + + This is a low-level function for changing the parsed result. + On top of this function, other functions are built, such as + `map/3` if you want to map over each individual element and + not worry about ordering, `reduce/3` to reduce all elements + into a single one, `replace/3` if you want to replace the + parsed result by a single value and `ignore/2` if you want to + ignore the parsed result. + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :letters_to_chars, + ascii_char([?a..?z]) + |> ascii_char([?a..?z]) + |> ascii_char([?a..?z]) + |> post_traverse({:join_and_wrap, ["-"]}) + + defp join_and_wrap(rest, args, context, _line, _offset, joiner) do + {rest, args |> Enum.join(joiner) |> List.wrap(), context} + end + end + + MyParser.letters_to_chars("abc") + #=> {:ok, ["99-98-97"], "", %{}, {1, 0}, 3} + + """ + @spec post_traverse(t, call) :: t + @spec post_traverse(t, t, call) :: t + def post_traverse(combinator \\ empty(), to_post_traverse, call) + when is_combinator(combinator) and is_combinator(to_post_traverse) do + compile_call!([], call, "post_traverse") + quoted_post_traverse(combinator, to_post_traverse, {__MODULE__, :__post_traverse__, [call]}) + end + + @doc """ + The same as `post_traverse/3` but receives the line and offset + from before the wrapped combinators. + + `post_traverse/3` should be preferred as it keeps less stack + information. Use `pre_traverse/3` only if you have to access + the line and offset from before the given combinators. + """ + @spec pre_traverse(t, call) :: t + @spec pre_traverse(t, t, call) :: t + def pre_traverse(combinator \\ empty(), to_pre_traverse, call) + when is_combinator(combinator) and is_combinator(to_pre_traverse) do + compile_call!([], call, "pre_traverse") + quoted_pre_traverse(combinator, to_pre_traverse, {__MODULE__, :__pre_traverse__, [call]}) + end + + @doc ~S""" + Checks if a combinator is ahead. + + If it succeeds, it continues as usual, otherwise it aborts the + closest `choice/2`, `repeat/2`, etc. If there is no closest + operation to abort, then it errors. + + Note a lookahead never changes the accumulated output nor the + context. + + ## Examples + + For example, imagine you want to parse a language that has the + keywords "if" and "while" and identifiers made of any letters or + number, where keywords and identifiers can be separated by a + single white space: + + defmodule IfWhileLang do + import NimbleParsec + + keyword = + choice([ + string("if") |> replace(:if), + string("while") |> replace(:while) + ]) + + identifier = + ascii_string([?a..?z, ?A..?Z, ?0..?9], min: 1) + + defparsec :expr, repeat(choice([keyword, identifier]) |> optional(string(" "))) + end + + The issue with the implementation above is that the following + will parse: + + IfWhileLang.expr("iffy") + {:ok, [:if, "fy"], "", %{}, {1, 0}, 4} + + However, "iffy" should be treated as a full identifier. We could + solve this by inverting the order of `keyword` and `identifier` + in `:expr` but that means "if" itself will be considered an identifier + and not a keyword. To solve this, we need lookaheads. + + One option is to check that after the keyword we either have an + empty string OR the end of the string: + + keyword = + choice([ + string("if") |> replace(:if), + string("while") |> replace(:while) + ]) + |> lookahead(choice([string(" "), eos()])) + + However, in this case, a negative lookahead may be clearer, + and we can assert that we don't have any identifier character after + the keyword: + + keyword = + choice([ + string("if") |> replace(:if), + string("while") |> replace(:while) + ]) + |> lookahead_not(ascii_char([?a..?z, ?A..?Z, ?0..?9])) + + Now we get the desired result back: + + IfWhileLang.expr("iffy") + #=> {:ok, ["iffy"], "", %{}, {1, 0}, 4} + + IfWhileLang.expr("if fy") + #=> {:ok, [:if, " ", "fy"], "", %{}, {1, 0}, 5} + + """ + @spec lookahead(t) :: t + @spec lookahead(t, t) :: t + def lookahead(combinator \\ empty(), to_lookahead) + when is_combinator(combinator) and is_combinator(to_lookahead) do + [{:lookahead, Enum.reverse(to_lookahead), :positive} | combinator] + end + + @doc ~S""" + Checks if a combinator is not ahead. + + If it succeeds, it aborts the closest `choice/2`, `repeat/2`, etc. + Otherwise it continues as usual. If there is no closest operation + to abort, then it errors. + + Note a lookahead never changes the accumulated output nor the + context. + + For an example, see `lookahead/2`. + """ + @spec lookahead_not(t) :: t + @spec lookahead_not(t, t) :: t + def lookahead_not(combinator \\ empty(), to_lookahead) + when is_combinator(combinator) and is_combinator(to_lookahead) do + [{:lookahead, Enum.reverse(to_lookahead), :negative} | combinator] + end + + @doc """ + Invokes `call` to emit the AST that post traverses the `to_post_traverse` + combinator results. + + This is similar to `post_traverse/3`. In `post_traverse/3`, `call` is + invoked to process the combinator results. In here, it is invoked to + emit AST that in its turn will process the combinator results. + The invoked function must return the same types as `post_traverse/3`. + + `call` is a `{module, function, args}` and it will receive 5 + additional arguments. The AST representation of the rest of the + parsed binary, the parser results, context, line and offset will + be prepended to `args`. `call` is invoked at compile time and is + useful in combinators that avoid injecting runtime dependencies. + + The line and offset will represent the location after the combinators. + To retrieve the position before the combinators, use `quoted_pre_traverse/3`. + + This function must be used only when you want to emit code that + has no runtime dependencies in other modules. In most cases, + using `post_traverse/3` is better, since it doesn't work on ASTs + and instead works at runtime. + """ + @spec quoted_post_traverse(t, mfargs) :: t + @spec quoted_post_traverse(t, t, mfargs) :: t + def quoted_post_traverse(combinator \\ empty(), to_post_traverse, {_, _, _} = call) + when is_combinator(combinator) and is_combinator(to_post_traverse) do + quoted_traverse(combinator, to_post_traverse, :post, call) + end + + @doc """ + The same as `quoted_post_traverse/3` but receives the line and offset + from before the wrapped combinators. + + `quoted_post_traverse/3` should be preferred as it keeps less stack + information. Use `quoted_pre_traverse/3` only if you have to access + the line and offset from before the given combinators. + """ + @spec quoted_pre_traverse(t, mfargs) :: t + @spec quoted_pre_traverse(t, t, mfargs) :: t + def quoted_pre_traverse(combinator \\ empty(), to_pre_traverse, {_, _, _} = call) + when is_combinator(combinator) and is_combinator(to_pre_traverse) do + quoted_traverse(combinator, to_pre_traverse, :pre, call) + end + + @doc ~S""" + Maps over the combinator results with the remote or local function in `call`. + + `call` is either a `{module, function, args}` representing + a remote call, a `{function, args}` representing a local call + or an atom `function` representing `{function, []}`. + + Each parser result will be invoked individually for the `call`. + Each result be prepended to the given `args`. The `args` will + be injected at the compile site and therefore must be escapable + via `Macro.escape/1`. + + See `post_traverse/3` for a low level version of this function. + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :letters_to_string_chars, + ascii_char([?a..?z]) + |> ascii_char([?a..?z]) + |> ascii_char([?a..?z]) + |> map({Integer, :to_string, []}) + end + + MyParser.letters_to_string_chars("abc") + #=> {:ok, ["97", "98", "99"], "", %{}, {1, 0}, 3} + """ + @spec map(t, call) :: t + @spec map(t, t, call) :: t + def map(combinator \\ empty(), to_map, call) + when is_combinator(combinator) and is_combinator(to_map) do + var = Macro.var(:var, __MODULE__) + call = compile_call!([var], call, "map") + quoted_post_traverse(combinator, to_map, {__MODULE__, :__map__, [var, call]}) + end + + @doc ~S""" + Reduces over the combinator results with the remote or local function in `call`. + + `call` is either a `{module, function, args}` representing + a remote call, a `{function, args}` representing a local call + or an atom `function` representing `{function, []}`. + + The parser results to be reduced will be prepended to the + given `args`. The `args` will be injected at the compile site + and therefore must be escapable via `Macro.escape/1`. + + See `post_traverse/3` for a low level version of this function. + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :letters_to_reduced_chars, + ascii_char([?a..?z]) + |> ascii_char([?a..?z]) + |> ascii_char([?a..?z]) + |> reduce({Enum, :join, ["-"]}) + end + + MyParser.letters_to_reduced_chars("abc") + #=> {:ok, ["97-98-99"], "", %{}, {1, 0}, 3} + """ + @spec reduce(t, call) :: t + @spec reduce(t, t, call) :: t + def reduce(combinator \\ empty(), to_reduce, call) + when is_combinator(combinator) and is_combinator(to_reduce) do + compile_call!([], call, "reduce") + quoted_post_traverse(combinator, to_reduce, {__MODULE__, :__reduce__, [call]}) + end + + @doc """ + Wraps the results of the given combinator in `to_wrap` in a list. + """ + @spec wrap(t) :: t + @spec wrap(t, t) :: t + def wrap(combinator \\ empty(), to_wrap) + when is_combinator(combinator) and is_combinator(to_wrap) do + quoted_post_traverse(combinator, to_wrap, {__MODULE__, :__wrap__, []}) + end + + @doc """ + Tags the result of the given combinator in `to_tag` in a tuple with + `tag` as first element. + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :integer, integer(min: 1) |> tag(:integer) + end + + MyParser.integer("1234") + #=> {:ok, [integer: [1234]], "", %{}, {1, 0}, 4} + + Notice, however, that the integer result is wrapped in a list, because + the parser is expected to emit multiple tokens. When you are sure that + only a single token is emitted, you should use `unwrap_and_tag/3`. + """ + @spec tag(t, term) :: t + @spec tag(t, t, term) :: t + def tag(combinator \\ empty(), to_tag, tag) + when is_combinator(combinator) and is_combinator(to_tag) do + quoted_post_traverse(combinator, to_tag, {__MODULE__, :__tag__, [Macro.escape(tag)]}) + end + + @doc """ + Unwraps and tags the result of the given combinator in `to_tag` in a tuple with + `tag` as first element. + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :integer, integer(min: 1) |> unwrap_and_tag(:integer) + end + + MyParser.integer("1234") + #=> {:ok, [integer: 1234], "", %{}, {1, 0}, 4} + + + In case the combinator emits greater than one token, an error will be raised. + See `tag/3` for more information. + """ + @spec unwrap_and_tag(t, term) :: t + @spec unwrap_and_tag(t, t, term) :: t + def unwrap_and_tag(combinator \\ empty(), to_tag, tag) + when is_combinator(combinator) and is_combinator(to_tag) do + quoted_post_traverse( + combinator, + to_tag, + {__MODULE__, :__unwrap_and_tag__, [Macro.escape(tag)]} + ) + end + + @doc """ + Inspects the combinator state given to `to_debug` with the given `opts`. + """ + @spec debug(t) :: t + @spec debug(t, t) :: t + def debug(combinator \\ empty(), to_debug) + when is_combinator(combinator) and is_combinator(to_debug) do + quoted_pre_traverse(combinator, to_debug, {__MODULE__, :__debug__, []}) + end + + @doc ~S""" + Defines a string binary value. + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :string_t, string("T") + end + + MyParser.string_t("T") + #=> {:ok, ["T"], "", %{}, {1, 0}, 1} + + MyParser.string_t("not T") + #=> {:error, "expected a string \"T\"", "not T", %{}, {1, 0}, 0} + + """ + @spec string(binary) :: t + @spec string(t, binary) :: t + def string(combinator \\ empty(), binary) + when is_combinator(combinator) and is_binary(binary) do + [{:string, binary} | combinator] + end + + @doc """ + Ignores the output of combinator given in `to_ignore`. + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :ignorable, string("T") |> ignore() |> integer(2) + end + + MyParser.ignorable("T12") + #=> {:ok, [12], "", %{}, {1, 0}, 2} + + """ + @spec ignore(t) :: t + @spec ignore(t, t) :: t + def ignore(combinator \\ empty(), to_ignore) + when is_combinator(combinator) and is_combinator(to_ignore) do + if to_ignore == empty() do + to_ignore + else + quoted_constant_traverse(combinator, to_ignore, {__MODULE__, :__constant__, [[]]}) + end + end + + @doc """ + Replaces the output of combinator given in `to_replace` by a single value. + + The `value` will be injected at the compile site + and therefore must be escapable via `Macro.escape/1`. + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :replaceable, string("T") |> replace("OTHER") |> integer(2, 2) + end + + MyParser.replaceable("T12") + #=> {:ok, ["OTHER", 12], "", %{}, {1, 0}, 2} + + """ + @spec replace(t, term) :: t + @spec replace(t, t, term) :: t + def replace(combinator \\ empty(), to_replace, value) + when is_combinator(combinator) and is_combinator(to_replace) do + value = Macro.escape(value) + quoted_constant_traverse(combinator, to_replace, {__MODULE__, :__constant__, [[value]]}) + end + + @doc """ + Allows the combinator given on `to_repeat` to appear zero or more times. + + Beware! Since `repeat/2` allows zero entries, it cannot be used inside + `choice/2`, because it will always succeed and may lead to unused function + warnings since any further choice won't ever be attempted. For example, + because `repeat/2` always succeeds, the `string/2` combinator below it + won't ever run: + + choice([ + repeat(ascii_char([?a..?z])), + string("OK") + ]) + + Instead of `repeat/2`, you may want to use `times/3` with the flags `:min` + and `:max`. + + Also beware! If you attempt to repeat a combinator that can match nothing, + like `optional/2`, `repeat/2` will not terminate. For example, consider + this combinator: + + repeat(optional(utf8_char([?a]))) + + This combinator will never terminate because `repeat/2` chooses the empty + option of `optional/2` every time. Since the goal of the parser above is + to parse 0 or more `?a` characters, it can be represented by + `repeat(utf8_char([?a]))`, because `repeat/2` allows 0 or more matches. + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :repeat_lower, repeat(ascii_char([?a..?z])) + end + + MyParser.repeat_lower("abcd") + #=> {:ok, [?a, ?b, ?c, ?d], "", %{}, {1, 0}, 4} + + MyParser.repeat_lower("1234") + #=> {:ok, [], "1234", %{}, {1, 0}, 0} + + """ + @spec repeat(t) :: t + @spec repeat(t, t) :: t + @spec repeat(t, opts) :: t + @spec repeat(t, t, opts) :: t + def repeat(combinator \\ empty(), to_repeat, opts \\ []) + when is_combinator(combinator) and is_combinator(to_repeat) and is_list(opts) do + non_empty!(to_repeat, "repeat") + quoted_repeat_while(combinator, to_repeat, {__MODULE__, :__cont_context__, []}, opts) + end + + @doc """ + Marks the given combinator should appear eventually. + + Any other data before the combinator appears is discarded. + If the combinator never appears, then it is an error. + + **Note:** this can be potentially a very expensive operation + as it executes the given combinator byte by byte until finding + an eventual match or ultimately failing. For example, if you + are looking for an integer, it is preferable to discard + everything that is not an integer + + ignore(ascii_string([not: ?0..?9])) + + rather than eventually look for an integer + + eventually(ascii_string([?0..?9])) + + ## Examples + + defmodule MyParser do + import NimbleParsec + + hour = integer(min: 1, max: 2) + defparsec :extract_hour, eventually(hour) + end + + MyParser.extract_hour("let's meet at 12?") + #=> {:ok, [12], "?", %{}, {1, 0}, 16} + + """ + @spec eventually(t) :: t + @spec eventually(t, t) :: t + def eventually(combinator \\ empty(), eventually) + when is_combinator(combinator) and is_combinator(eventually) do + non_empty!(eventually, "eventually") + [{:eventually, Enum.reverse(eventually)} | combinator] + end + + @doc ~S""" + Repeats while the given remote or local function `while` returns + `{:cont, context}`. + + If the combinator `to_repeat` stops matching, then the whole repeat + loop stops successfully, hence it is important to assert the terminated + value after repeating. + + In case repetition should stop, `while` must return `{:halt, context}`. + + `while` is either a `{module, function, args}` representing + a remote call, a `{function, args}` representing a local call + or an atom `function` representing `{function, []}`. + + The function given in `while` will receive 4 additional arguments. + The `rest` of the binary to be parsed, the parser context, the + current line and the current offset will be prepended to the + given `args`. The `args` will be injected at the compile site + and therefore must be escapable via `Macro.escape/1`. + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :string_with_quotes, + ascii_char([?"]) + |> repeat_while( + choice([ + ~S(\") |> string() |> replace(?"), + utf8_char([]) + ]), + {:not_quote, []} + ) + |> ascii_char([?"]) + |> reduce({List, :to_string, []}) + + defp not_quote(<>, context, _, _), do: {:halt, context} + defp not_quote(_, context, _, _), do: {:cont, context} + end + + MyParser.string_with_quotes(~S("string with quotes \" inside")) + {:ok, ["\"string with quotes \" inside\""], "", %{}, {1, 0}, 30} + + Note you can use `lookahead/2` and `lookahead_not/2` with + `repeat/2` (instead of `repeat_while/3`) to write a combinator + that repeats while a combinator matches (or does not match). + For example, the same combinator above could be written as: + + defmodule MyParser do + import NimbleParsec + + defparsec :string_with_quotes, + ascii_char([?"]) + |> repeat( + lookahead_not(ascii_char([?"])) + |> choice([ + ~S(\") |> string() |> replace(?"), + utf8_char([]) + ]) + ) + |> ascii_char([?"]) + |> reduce({List, :to_string, []}) + end + + MyParser.string_with_quotes(~S("string with quotes \" inside")) + {:ok, ["\"string with quotes \" inside\""], "", %{}, {1, 0}, 30} + + However, `repeat_while` is still useful when the condition to + repeat comes from the context passed around. + """ + @spec repeat_while(t, call) :: t + @spec repeat_while(t, t, call) :: t + @spec repeat_while(t, t, call, opts) :: t + def repeat_while(combinator \\ empty(), to_repeat, while, opts \\ []) + when is_combinator(combinator) and is_combinator(to_repeat) and is_list(opts) do + non_empty!(to_repeat, "repeat_while") + compile_call!([], while, "repeat_while") + quoted_repeat_while(combinator, to_repeat, {__MODULE__, :__repeat_while__, [while]}, opts) + end + + @doc """ + Invokes `while` to emit the AST that will repeat `to_repeat` + while the AST code returns `{:cont, context}`. + + In case repetition should stop, `while` must return `{:halt, context}`. + + `while` is a `{module, function, args}` and it will receive 4 + additional arguments. The AST representations of the binary to be + parsed, context, line and offset will be prepended to `args`. `while` + is invoked at compile time and is useful in combinators that avoid + injecting runtime dependencies. + """ + @spec quoted_repeat_while(t, mfargs) :: t + @spec quoted_repeat_while(t, t, mfargs) :: t + @spec quoted_repeat_while(t, t, mfargs, opts) :: t + def quoted_repeat_while(combinator \\ empty(), to_repeat, {_, _, _} = while, opts \\ []) + when is_combinator(combinator) and is_combinator(to_repeat) and is_list(opts) do + non_empty!(to_repeat, "quoted_repeat_while") + [{:repeat, Enum.reverse(to_repeat), while, opts[:gen_times]} | combinator] + end + + @doc """ + Allow the combinator given on `to_repeat` to appear at least, at most + or exactly a given amount of times. + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :minimum_lower, times(ascii_char([?a..?z]), min: 2) + end + + MyParser.minimum_lower("abcd") + #=> {:ok, [?a, ?b, ?c, ?d], "", %{}, {1, 0}, 4} + + MyParser.minimum_lower("ab12") + #=> {:ok, [?a, ?b], "12", %{}, {1, 0}, 2} + + MyParser.minimum_lower("a123") + #=> {:ok, [], "a123", %{}, {1, 0}, 0} + + """ + @spec times(t, pos_integer | [min_and_max]) :: t + @spec times(t, t, pos_integer | [min_and_max]) :: t + def times(combinator \\ empty(), to_repeat, count_or_min_max) + + def times(combinator, to_repeat, n) + when is_combinator(combinator) and is_combinator(to_repeat) and is_integer(n) and n >= 1 do + non_empty!(to_repeat, "times") + duplicate(combinator, to_repeat, n) + end + + def times(combinator, to_repeat, opts) + when is_combinator(combinator) and is_combinator(to_repeat) and is_list(opts) do + {min, max} = validate_min_and_max!(opts) + non_empty!(to_repeat, "times") + + combinator = + if min > 0 do + duplicate(combinator, to_repeat, min) + else + combinator + end + + to_repeat = Enum.reverse(to_repeat) + + combinator = + if max do + [{:times, to_repeat, max - min} | combinator] + else + [{:repeat, to_repeat, {__MODULE__, :__cont_context__, []}, opts[:gen_times]} | combinator] + end + + combinator + end + + @doc """ + Chooses one of the given combinators. + + Expects at least two choices. + + ## Beware! Char combinators + + Note both `utf8_char/2` and `ascii_char/2` allow multiple ranges to + be given. Therefore, instead this: + + choice([ + ascii_char([?a..?z]), + ascii_char([?A..?Z]), + ]) + + One should simply prefer: + + ascii_char([?a..?z, ?A..?Z]) + + As the latter is compiled more efficiently by `NimbleParsec`. + + ## Beware! Always successful combinators + + If a combinator that always succeeds is given as a choice, that choice + will always succeed which may lead to unused function warnings since + any further choice won't ever be attempted. For example, because `repeat/2` + always succeeds, the `string/2` combinator below it won't ever run: + + choice([ + repeat(ascii_char([?0..?9])), + string("OK") + ]) + + Instead of `repeat/2`, you may want to use `times/3` with the flags `:min` + and `:max`. + + ## Beware! Overlapping choices + + In case choices overlap, there is no guarantee which error will be the one + effectively returned. For example, imagine this choice: + + choice([ + string("foo"), + string("") + ] + + Since both choices can be activated for an input starting with "abc", + NimbleParsec guarantees it will return the error from one of them, but + not which. + """ + @spec choice(nonempty_list(t)) :: t + @spec choice(t, nonempty_list(t)) :: t + @spec choice(t, nonempty_list(t), opts) :: t + def choice(combinator \\ empty(), [_, _ | _] = choices, opts \\ []) + when is_combinator(combinator) do + choices = Enum.map(choices, &Enum.reverse/1) + weights = opts[:gen_weights] + + if weights && length(weights) != length(choices) do + raise ArgumentError, ":gen_weights must be a list of the same size as choices" + end + + [{:choice, choices, weights} | combinator] + end + + @doc """ + Marks the given combinator as `optional`. + + It is equivalent to `choice([combinator, empty()])`. + """ + @spec optional(t) :: t + @spec optional(t, t) :: t + def optional(combinator \\ empty(), optional) do + choice(combinator, [optional, empty()]) + end + + @doc """ + Defines a combinator to consume the next `n` bytes from the input. + + ## Examples + + defmodule MyParser do + import NimbleParsec + + defparsec :three_bytes, bytes(3) + end + + MyParser.three_bytes("abc") + #=> {:ok, ["abc"], "", %{}, {1, 0}, 3} + + MyParser.three_bytes("ab") + #=> {:error, "expected 3 bytes", "ab", %{}, {1, 0}, 0} + """ + @spec bytes(pos_integer) :: t + @spec bytes(t, pos_integer) :: t + def bytes(combinator \\ empty(), count) + when is_combinator(combinator) and is_integer(count) and count > 0 do + [{:bytes, count} | combinator] + end + + ## Helpers + + defp validate_min_and_max!(count_or_opts, required_min \\ 0) + + defp validate_min_and_max!(count, required_min) + when is_integer(count) do + validate_min_and_max!([min: count], required_min) + end + + defp validate_min_and_max!(opts, required_min) do + min = opts[:min] + max = opts[:max] + + cond do + min && max -> + validate_min_or_max!(:min, min, required_min) + validate_min_or_max!(:max, max, 1) + + max <= min and + raise ArgumentError, + "expected :max to be strictly greater than :min, got: #{min} and #{max}" + + min -> + validate_min_or_max!(:min, min, required_min) + + max -> + validate_min_or_max!(:max, max, 1) + + true -> + raise ArgumentError, "expected :min or :max to be given" + end + + {min || required_min, max} + end + + defp validate_min_or_max!(kind, value, min) do + unless is_integer(value) and value >= min do + raise ArgumentError, + "expected #{kind} to be an integer greater than or equal to #{min}, " <> + "got: #{inspect(value)}" + end + end + + defp split_ranges!(ranges, context) do + Enum.split_with(ranges, &split_range!(&1, context)) + end + + defp split_range!(x, _context) when is_integer(x), do: true + defp split_range!(_.._//step, _context) when abs(step) == 1, do: true + defp split_range!({:not, x}, _context) when is_integer(x), do: false + defp split_range!({:not, _.._//step}, _context) when abs(step) == 1, do: false + + defp split_range!(range, context) do + raise ArgumentError, "unknown range #{inspect(range)} given to #{context}" + end + + defp compile_call!(extra, {module, function, args}, _context) + when is_atom(module) and is_atom(function) and is_list(args) do + quote do + unquote(module).unquote(function)( + unquote_splicing(extra), + unquote_splicing(Macro.escape(args)) + ) + end + end + + defp compile_call!(extra, {function, args}, _context) + when is_atom(function) and is_list(args) do + quote do + unquote(function)(unquote_splicing(extra), unquote_splicing(Macro.escape(args))) + end + end + + defp compile_call!(extra, function, _context) when is_atom(function) do + quote do + unquote(function)(unquote_splicing(extra)) + end + end + + defp compile_call!(_args, unknown, context) do + raise ArgumentError, "unknown call given to #{context}, got: #{inspect(unknown)}" + end + + defp non_empty!([], action) do + raise ArgumentError, "cannot call #{action} on empty combinator" + end + + defp non_empty!(combinator, action) do + if Enum.any?(combinator, &is_list/1) do + raise ArgumentError, + "invalid combinator given to #{action}, got a list of combinators instead" + end + end + + ## Inner combinators + + defp quoted_constant_traverse(combinator, to_traverse, call) do + case to_traverse do + [{:traverse, inner_traverse, :constant, inner_call}] -> + [{:traverse, inner_traverse, :constant, [call | inner_call]} | combinator] + + _ -> + [{:traverse, Enum.reverse(to_traverse), :constant, [call]} | combinator] + end + end + + defp quoted_traverse(combinator, to_traverse, pre_or_pos, call) do + [{:traverse, Enum.reverse(to_traverse), pre_or_pos, [call]} | combinator] + end + + defp bin_segment(combinator, inclusive, exclusive, modifier) do + [{:bin_segment, inclusive, exclusive, modifier} | combinator] + end + + ## Traverse callbacks + + @doc false + def __pre_traverse__(rest, acc, context, line, offset, call) do + compile_call!([rest, acc, context, line, offset], call, "pre_traverse") + end + + @doc false + def __post_traverse__(rest, acc, context, line, offset, call) do + compile_call!([rest, acc, context, line, offset], call, "post_traverse") + end + + @doc false + def __lookahead__(rest, _acc, context, line, offset, call) do + compile_call!([rest, context, line, offset], call, "lookahead") + end + + @doc false + def __wrap__(rest, acc, context, _line, _offset) do + {:{}, [], [rest, [reverse_now_or_later(acc)], context]} + end + + @doc false + def __tag__(rest, acc, context, _line, _offset, tag) do + {:{}, [], [rest, [{tag, reverse_now_or_later(acc)}], context]} + end + + @doc false + def __unwrap_and_tag__(rest, acc, context, _line, _offset, tag) when is_list(acc) do + case acc do + [one] -> {:{}, [], [rest, [{tag, one}], context]} + many -> raise "unwrap_and_tag/3 expected a single token, got: #{inspect(many)}" + end + end + + def __unwrap_and_tag__(rest, acc, context, _line, _offset, tag) do + quoted = + quote do + case :lists.reverse(unquote(acc)) do + [one] -> one + many -> raise "unwrap_and_tag/3 expected a single token, got: #{inspect(many)}" + end + end + + {:{}, [], [rest, [{tag, quoted}], context]} + end + + @doc false + def __debug__(rest, acc, context, line, offset) do + quote bind_quoted: [rest: rest, acc: acc, context: context, line: line, offset: offset] do + IO.puts(""" + == DEBUG == + Bin: #{inspect(rest)} + Acc: #{inspect(:lists.reverse(acc))} + Ctx: #{inspect(context)} + Lin: #{inspect(line)} + Off: #{inspect(offset)} + """) + + {rest, acc, context} + end + end + + @doc false + def __constant__(rest, _acc, context, _line, _offset, constant) do + {:{}, [], [rest, constant, context]} + end + + @doc false + def __line__(rest, acc, context, line, _offset) do + {:{}, [], [rest, [{reverse_now_or_later(acc), line}], context]} + end + + @doc false + def __byte_offset__(rest, acc, context, _line, offset) do + {:{}, [], [rest, [{reverse_now_or_later(acc), offset}], context]} + end + + @doc false + def __map__(rest, acc, context, _line, _offset, var, call) do + ast = + quote do + Enum.map(unquote(acc), fn unquote(var) -> unquote(call) end) + end + + {:{}, [], [rest, ast, context]} + end + + @doc false + def __reduce__(rest, acc, context, _line, _offset, call) do + {:{}, [], [rest, [compile_call!([reverse_now_or_later(acc)], call, "reduce")], context]} + end + + ## Repeat callbacks + + @doc false + def __cont_context__(_rest, context, _line, _offset) do + {:cont, context} + end + + @doc false + def __repeat_while__(quoted, context, line, offset, call) do + compile_call!([quoted, context, line, offset], call, "repeat_while") + end + + ## Chars callbacks + + defp min_max_compile_runtime_chars(combinator, to_repeat, count, compile, _runtime, args) + when is_integer(count) and count >= 0 do + chars = duplicate(to_repeat, count) + quoted_post_traverse(combinator, chars, {__MODULE__, compile, [count | args]}) + end + + defp min_max_compile_runtime_chars(combinator, to_repeat, opts, compile, runtime, args) + when is_list(opts) do + {min, max} = validate_min_and_max!(opts) + + chars = + if min > 0 do + min_max_compile_runtime_chars(empty(), to_repeat, min, compile, runtime, args) + else + empty() + end + + chars = + if max do + times(chars, to_repeat, max: max - min) + else + repeat(chars, to_repeat) + end + + quoted_post_traverse(combinator, chars, {__MODULE__, runtime, [min, max | args]}) + end + + @doc false + def __runtime_string__(rest, acc, context, _line, _offset, _min, _max, _type) do + ast = quote(do: List.to_string(unquote(reverse_now_or_later(acc)))) + {:{}, [], [rest, [ast], context]} + end + + @doc false + def __compile_string__(rest, acc, context, _line, _offset, _count, type) when is_list(acc) do + acc = + for entry <- :lists.reverse(acc) do + {:"::", [], [entry, type]} + end + + {:{}, [], [rest, [{:<<>>, [], acc}], context]} + end + + def __compile_string__(rest, acc, context, _line, _offset, _count, _type) do + ast = quote(do: List.to_string(unquote(reverse_now_or_later(acc)))) + {:{}, [], [rest, [ast], context]} + end + + @doc false + def __runtime_integer__(rest, acc, context, _line, _offset, min, _max) + when is_integer(min) and min > 0 do + ast = + quote do + [head | tail] = unquote(reverse_now_or_later(acc)) + [:lists.foldl(fn x, acc -> x - ?0 + acc * 10 end, head, tail)] + end + + {:{}, [], [rest, ast, context]} + end + + def __runtime_integer__(rest, acc, context, _line, _offset, _min, _max) do + ast = + quote do + [head | tail] = unquote(reverse_now_or_later(acc)) + [:lists.foldl(fn x, acc -> x - ?0 + acc * 10 end, head - ?0, tail)] + end + + {:{}, [], [rest, ast, context]} + end + + @doc false + def __compile_integer__(rest, acc, context, _line, _offset, _count) when is_list(acc) do + ast = + acc + |> quoted_ascii_to_integer(1) + |> Enum.reduce(&{:+, [], [&2, &1]}) + + {:{}, [], [rest, [ast], context]} + end + + defp reverse_now_or_later(list) when is_list(list), do: :lists.reverse(list) + defp reverse_now_or_later(expr), do: quote(do: :lists.reverse(unquote(expr))) + + defp quoted_ascii_to_integer([var | vars], 1) do + [quote(do: unquote(var) - ?0) | quoted_ascii_to_integer(vars, 10)] + end + + defp quoted_ascii_to_integer([var | vars], index) do + [quote(do: (unquote(var) - ?0) * unquote(index)) | quoted_ascii_to_integer(vars, index * 10)] + end + + defp quoted_ascii_to_integer([], _index) do + [] + end +end diff --git a/deps/nimble_parsec/lib/nimble_parsec/compiler.ex b/deps/nimble_parsec/lib/nimble_parsec/compiler.ex new file mode 100644 index 0000000000000000000000000000000000000000..9d0e4de532d2a995d76bd516424dc137f8d6222e --- /dev/null +++ b/deps/nimble_parsec/lib/nimble_parsec/compiler.ex @@ -0,0 +1,1187 @@ +defmodule NimbleParsec.Compiler do + @moduledoc false + @arity 6 + + @doc """ + Returns a parsec entrypoint named `name`. + """ + def entry_point(name) do + doc = """ + Parses the given `binary` as #{name}. + + Returns `{:ok, [token], rest, context, position, byte_offset}` or + `{:error, reason, rest, context, line, byte_offset}` where `position` + describes the location of the #{name} (start position) as `{line, offset_to_start_of_line}`. + + To column where the error occurred can be inferred from `byte_offset - offset_to_start_of_line`. + + ## Options + + * `:byte_offset` - the byte offset for the whole binary, defaults to 0 + * `:line` - the line and the byte offset into that line, defaults to `{1, byte_offset}` + * `:context` - the initial context value. It will be converted to a map + """ + + spec = + quote do + unquote(name)(binary, keyword) :: + {:ok, [term], rest, context, line, byte_offset} + | {:error, reason, rest, context, line, byte_offset} + when line: {pos_integer, byte_offset}, + byte_offset: non_neg_integer, + rest: binary, + reason: String.t(), + context: map + end + + args = quote(do: [binary, opts \\ []]) + guards = quote(do: is_binary(binary)) + + case = + quote generated: true do + case unquote(:"#{name}__0")(binary, [], [], context, line, byte_offset) do + {:ok, acc, rest, context, line, offset} -> + {:ok, :lists.reverse(acc), rest, context, line, offset} + + {:error, _, _, _, _, _} = error -> + error + end + end + + body = + quote do + context = Map.new(Keyword.get(opts, :context, [])) + byte_offset = Keyword.get(opts, :byte_offset, 0) + + line = + case Keyword.get(opts, :line, 1) do + {_, _} = line -> line + line -> {line, byte_offset} + end + + unquote(case) + end + + {doc, spec, {name, args, guards, body}} + end + + @doc """ + Compiles the given combinators into multiple definitions. + """ + def compile(name, [], _opts) do + raise ArgumentError, "cannot compile #{inspect(name)} with an empty parser combinator" + end + + def compile(name, combinators, opts) when is_list(combinators) do + inline? = Keyword.get(opts, :inline, false) + {defs, inline} = compile(name, combinators) + + if inline? do + {defs, inline} + else + {defs, []} + end + end + + defp compile(name, combinators) do + config = %{ + acc_depth: 0, + catch_all: nil, + labels: [], + name: name, + replace: false + } + + {next, step} = build_next(0, config) + + {defs, inline, last, _step} = + combinators + |> Enum.reverse() + |> compile([], [], next, step, config) + + {Enum.reverse([build_ok(last) | defs]), [{last, @arity} | inline]} + end + + defp compile([], defs, inline, current, step, _config) do + {defs, inline, current, step} + end + + defp compile([{:update, key, fun} | combinators], defs, inline, current, step, config) do + compile(combinators, defs, inline, current, step, Map.update!(config, key, fun)) + end + + defp compile(combinators, defs, inline, current, step, config) do + {next_combinators, used_combinators, {new_defs, new_inline, next, step, catch_all}} = + case take_bound_combinators(combinators) do + {[combinator | combinators], [], [], [], [], _metadata} -> + case combinator do + {:label, label_combinators, label} -> + pre_combinators = [{:update, :labels, &[label | &1]} | label_combinators] + pos_combinators = [{:update, :labels, &tl(&1)} | combinators] + + {pre_combinators ++ pos_combinators, [combinator], + {[], [], current, step, :catch_none}} + + _ -> + {combinators, [combinator], + compile_unbound_combinator(combinator, current, step, config)} + end + + {combinators, inputs, guards, outputs, acc, metadata} -> + {combinators, Enum.reverse(acc), + compile_bound_combinator(inputs, guards, outputs, metadata, current, step, config)} + end + + catch_all_defs = + case catch_all do + :catch_all -> [build_catch_all(:positive, current, used_combinators, config)] + :catch_none -> [] + end + + defs = catch_all_defs ++ Enum.reverse(new_defs) ++ defs + compile(next_combinators, defs, new_inline ++ inline, next, step, config) + end + + ## Unbound combinators + + defp compile_unbound_combinator({:parsec, parsec}, current, step, config) do + {next, step} = build_next(step, config) + head = quote(do: [rest, acc, stack, context, line, offset]) + + catch_all = + case config do + %{catch_all: nil} -> + quote(do: error) + + %{catch_all: catch_all, acc_depth: n} -> + {_, _, _, body} = build_proxy_to(current, catch_all, n) + body + end + + call = + case parsec do + {mod, fun} -> + quote do + unquote(mod).unquote(:"#{fun}__0")(rest, acc, [], context, line, offset) + end + + fun -> + quote do + unquote(:"#{fun}__0")(rest, acc, [], context, line, offset) + end + end + + body = + quote generated: true do + case unquote(call) do + {:ok, acc, rest, context, line, offset} -> + unquote(next)(rest, acc, stack, context, line, offset) + + {:error, _, _, _, _, _} = error -> + unquote(catch_all) + end + end + + def = {current, head, true, body} + {[def], [{current, @arity}], next, step, :catch_none} + end + + defp compile_unbound_combinator({:lookahead, combinators, kind}, current, step, config) do + choices = extract_choices_from_lookahead(combinators) + + if Enum.all?(choices, &all_bound_combinators?/1) do + {next, step} = build_next(step, config) + args = quote(do: [rest, acc, stack, context, line, offset]) + success_body = {next, [], args} + + {_, [_bin | negative_head], _, failure_body} = + build_catch_all(kind, current, combinators, config) + + {success_body, failure_body, head} = + if kind == :positive do + {success_body, failure_body, quote(do: [acc, stack, context, line, offset])} + else + {failure_body, success_body, negative_head} + end + + defs = + for choice <- choices do + {[], inputs, guards, _, _, metadata} = take_bound_combinators(choice) + {bin, _} = compile_bound_bin_pattern(inputs, metadata, quote(do: _)) + head = quote(do: [unquote(bin) = rest]) ++ quote(do: unquote(head)) + guards = guards_list_to_quoted(guards) + {current, head, guards, success_body} + end + + defs = if [] in choices, do: defs, else: defs ++ [{current, args, true, failure_body}] + {defs, [], next, step, :catch_none} + else + compile_unbound_lookahead(combinators, kind, current, step, config) + end + end + + defp compile_unbound_combinator( + {:traverse, combinators, kind, traversal}, + current, + step, + config + ) do + fun = &traverse(traversal, &1, &2, &3, &4, &5, &6, config) + config = if kind == :constant, do: put_in(config.replace, true), else: config + compile_unbound_traverse(combinators, kind, current, step, config, fun) + end + + defp compile_unbound_combinator({:times, combinators, count}, current, step, config) do + if all_no_context_combinators?(combinators) do + compile_bound_times(combinators, count, current, step, config) + else + compile_unbound_times(combinators, count, current, step, config) + end + end + + defp compile_unbound_combinator({:repeat, combinators, while, _gen}, current, step, config) do + {failure, step} = build_next(step, config) + config = %{config | catch_all: failure, acc_depth: 0} + + if all_no_context_combinators?(combinators) do + compile_bound_repeat(combinators, while, current, failure, step, config) + else + compile_unbound_repeat(combinators, while, current, failure, step, config) + end + end + + defp compile_unbound_combinator({:eventually, combinators}, current, step, config) do + compile_eventually(combinators, current, step, config) + end + + defp compile_unbound_combinator({:choice, choices, _} = combinator, current, step, config) do + config = + update_in(config.labels, fn + [] -> [label(combinator)] + other -> other + end) + + if Enum.all?(choices, &all_bound_combinators?/1) do + compile_bound_choice(choices, current, step, config) + else + compile_unbound_choice(choices, current, step, config) + end + end + + ## Lookahead + + defp extract_choices_from_lookahead([{:choice, choices, _}]), do: choices + defp extract_choices_from_lookahead(other), do: [other] + + defp compile_unbound_lookahead(combinators, kind, current, step, config) do + {_, _, _, catch_all} = build_catch_all(kind, current, combinators, config) + + {next, step} = build_next(step, config) + head = quote(do: [rest, acc, stack, context, line, offset]) + + args = + quote(do: [rest, [], [{rest, acc, context, line, offset} | stack], context, line, offset]) + + body = {next, [], args} + entry_point = {current, head, true, body} + + {failure, step} = build_next(step, config) + config = %{config | catch_all: failure, acc_depth: 0} + {defs, inline, success, step} = compile(combinators, [entry_point], [], next, step, config) + + {next, step} = build_next(step, config) + head = quote(do: [_, _, [{rest, acc, context, line, offset} | stack], _, _, _]) + args = quote(do: [rest, acc, stack, context, line, offset]) + body = {next, [], args} + + success_failure = + if kind == :positive do + [{success, head, true, body}, {failure, head, true, catch_all}] + else + [{failure, head, true, body}, {success, head, true, catch_all}] + end + + inline = [{current, @arity}, {success, @arity}, {failure, @arity} | inline] + {Enum.reverse(success_failure ++ defs), inline, next, step, :catch_none} + end + + ## Traverse + + defp compile_unbound_traverse([], _kind, current, step, config, fun) do + {next, step} = build_next(step, config) + head = quote(do: [rest, acc, stack, context, line, offset]) + [rest, _, _, context, line, offset] = head + + body = fun.(next, rest, [], context, line, offset) + def = {current, head, true, body} + {[def], [{current, @arity}], next, step, :catch_none} + end + + defp compile_unbound_traverse(combinators, kind, current, step, config, fun) do + {next, step} = build_next(step, config) + head = quote(do: [rest, acc, stack, context, line, offset]) + + args = + if kind == :pre do + quote(do: [rest, [], [{acc, line, offset} | stack], context, line, offset]) + else + quote(do: [rest, [], [acc | stack], context, line, offset]) + end + + body = {next, [], args} + entry_point = {current, head, true, body} + + config = update_in(config.acc_depth, &(&1 + 1)) + {defs, inline, last, step} = compile(combinators, [entry_point], [], next, step, config) + + # Now we need to traverse the accumulator with the user code and + # concatenate with the previous accumulator at the top of the stack. + {next, step} = build_next(step, config) + + {head, {traverse_line, traverse_offset}} = + if kind == :pre do + quote do + {[rest, user_acc, [{acc, stack_line, stack_offset} | stack], context, line, offset], + {stack_line, stack_offset}} + end + else + quote do + {[rest, user_acc, [acc | stack], context, line, offset], {line, offset}} + end + end + + [rest, user_acc, _, context | _] = head + body = fun.(next, rest, user_acc, context, traverse_line, traverse_offset) + last_def = {last, head, true, body} + + inline = [{current, @arity}, {last, @arity} | inline] + {Enum.reverse([last_def | defs]), inline, next, step, :catch_none} + end + + defp traverse(_traversal, next, _, user_acc, _, _, _, %{replace: true}) do + quote do + _ = unquote(user_acc) + unquote(next)(rest, acc, stack, context, line, offset) + end + end + + defp traverse(traversal, next, rest, user_acc, context, line, offset, _) do + case apply_traverse(traversal, rest, user_acc, context, line, offset) do + {:{}, _, [rest, expanded_acc, context]} -> + quote do + _ = unquote(user_acc) + + unquote(next)( + unquote(rest), + unquote(expanded_acc) ++ acc, + stack, + unquote(context), + line, + offset + ) + end + + {:error, reason} -> + quote do + {:error, unquote(reason), rest, context, line, offset} + end + + quoted -> + quote generated: true do + case unquote(quoted) do + {rest, user_acc, context} when is_list(user_acc) -> + unquote(next)(rest, user_acc ++ acc, stack, context, line, offset) + + {:error, reason} -> + {:error, reason, rest, context, line, offset} + end + end + end + end + + defp apply_traverse(mfargs, rest, acc, context, line, offset) do + apply_traverse(Enum.reverse(mfargs), {:{}, [], [rest, acc, context]}, line, offset) + end + + defp apply_traverse([mfargs | tail], {:{}, _, [rest, acc, context]}, line, offset) do + rest_acc_context = apply_traverse_mfa(mfargs, [rest, acc, context, line, offset], rest) + apply_traverse(tail, rest_acc_context, line, offset) + end + + defp apply_traverse([], rest_acc_context, _line, _offset) do + rest_acc_context + end + + defp apply_traverse(tail, rest_acc_context, line, offset) do + pattern = quote(do: {rest, acc, context}) + args = [quote(do: rest), quote(do: acc), quote(do: context), line, offset] + + entries = + Enum.map(tail, fn mfargs -> + quote(do: unquote(pattern) <- unquote(apply_traverse_mfa(mfargs, args, quote(do: rest)))) + end) + + quote do + with unquote(pattern) <- unquote(rest_acc_context), unquote_splicing(entries) do + {rest, acc, context} + end + end + end + + defp apply_traverse_mfa(mfargs, args, rest) do + case apply_mfa(mfargs, args) do + {:{}, _, [_, _, _]} = res -> + res + + {acc, context} when acc != :error -> + IO.warn( + "returning a two-element tuple {acc, context} in pre_traverse/post_traverse is deprecated, " <> + "please return {rest, acc, context} instead" + ) + + {:{}, [], [rest, acc, context]} + + {:error, context} -> + {:error, context} + + quoted -> + # TODO: Deprecate two element tuple return that is not error + quote generated: true do + case unquote(quoted) do + {_, _, _} = res -> + res + + {:error, reason} -> + {:error, reason} + + {acc, context} -> + IO.warn( + "returning a two-element tuple {acc, context} in pre_traverse/post_traverse is deprecated, " <> + "please return {rest, acc, context} instead" + ) + + {unquote(rest), acc, context} + end + end + end + end + + ## Eventually + + defp compile_eventually(combinators, current, step, config) do + # First add the initial accumulator to the stack + {entrypoint, step} = build_next(step, config) + head = quote(do: [rest, acc, stack, context, line, offset]) + args = quote(do: [rest, acc, [acc | stack], context, line, offset]) + body = {entrypoint, [], args} + current_def = {current, head, true, body} + + # Now define the failure point which will recur + {failure, step} = build_next(step, config) + failure_def = build_eventually_next_def(entrypoint, failure) + config = update_in(config.acc_depth, &(&1 + 1)) + catch_all_def = build_catch_all(:positive, failure, combinators, config) + + # And compile down the inner combinators + config = %{config | catch_all: failure, acc_depth: 0} + {defs, inline, success, step} = compile(combinators, [], [], entrypoint, step, config) + + # In the exit remove the accumulator from the stack + {exitpoint, step} = build_next(step, config) + head = quote(do: [rest, acc, [_ | stack], context, line, offset]) + args = quote(do: [rest, acc, stack, context, line, offset]) + body = {exitpoint, [], args} + success_def = {success, head, true, body} + + defs = Enum.reverse(defs, [success_def, current_def, failure_def, catch_all_def]) + inline = [{success, @arity}, {current, @arity}, {failure, @arity} | inline] + {defs, inline, exitpoint, step, :catch_none} + end + + defp build_eventually_next_def(entrypoint, failure) do + head = quote(do: [<>, _acc, [acc | _] = stack, context, line, offset]) + offset = add_offset(quote(do: offset), 1) + line = add_line(quote(do: line), offset, quote(do: byte)) + body = {entrypoint, [], quote(do: [rest, acc, stack, context]) ++ [line, offset]} + {failure, head, true, body} + end + + ## Repeat + + defp compile_bound_repeat(combinators, while, current, failure, step, config) do + {defs, recur, next, step} = + case apply_mfa(while, quote(do: [rest, context, line, offset])) do + {:cont, quote(do: context)} -> + {[], current, current, step} + + quoted -> + {next, step} = build_next(step, config) + head = args = quote(do: [rest, acc, stack, context, line, offset]) + body = repeat_while(quoted, next, args, failure, args) + {[{current, head, true, body}], current, next, step} + end + + {defs, inline, success, step} = compile(combinators, defs, [], next, step, config) + def = build_proxy_to(success, recur, 0) + {Enum.reverse([def | defs]), [{success, @arity} | inline], failure, step, :catch_none} + end + + defp compile_unbound_repeat(combinators, while, current, failure, step, config) do + {recur, step} = build_next(step, config) + {defs, inline, success, step} = compile(combinators, [], [], recur, step, config) + + {next, step} = build_next(step, config) + head = quote(do: [_, _, [{rest, acc, context, line, offset} | stack], _, _, _]) + args = quote(do: [rest, acc, stack, context, line, offset]) + body = {next, [], args} + failure_def = {failure, head, true, body} + + while = apply_mfa(while, quote(do: [rest, context, line, offset])) + cont = quote(do: {rest, acc, context, line, offset}) + + head = + quote do + [inner_rest, inner_acc, [unquote(cont) | stack], inner_context, inner_line, inner_offset] + end + + cont = quote(do: {inner_rest, inner_acc ++ acc, inner_context, inner_line, inner_offset}) + + true_args = + quote do + [inner_rest, [], [unquote(cont) | stack], inner_context, inner_line, inner_offset] + end + + false_args = quote(do: [rest, acc, stack, context, line, offset]) + + # We need to do this dance because of unused variables + body = + case compile_time_repeat_while(while) do + :cont -> + quote do + _ = {rest, acc, context, line, offset} + unquote({recur, [], true_args}) + end + + :halt -> + quote do + _ = {inner_rest, inner_acc, inner_context, inner_line, inner_offset} + unquote({next, [], false_args}) + end + + :none -> + repeat_while(while, recur, true_args, next, false_args) + end + + success_def = {success, head, true, body} + head = quote(do: [rest, acc, stack, context, line, offset]) + + true_args = + quote do + [rest, [], [{rest, acc, context, line, offset} | stack], context, line, offset] + end + + false_args = quote(do: [rest, acc, stack, context, line, offset]) + body = repeat_while(while, recur, true_args, next, false_args) + current_def = {current, head, true, body} + + defs = [current_def | Enum.reverse([success_def, failure_def | defs])] + inline = [{current, @arity}, {success, @arity}, {failure, @arity} | inline] + {defs, inline, next, step, :catch_none} + end + + defp compile_time_repeat_while({:cont, {:context, _, __MODULE__}}), do: :cont + defp compile_time_repeat_while({:halt, {:context, _, __MODULE__}}), do: :halt + defp compile_time_repeat_while(_), do: :none + + defp repeat_while(quoted, true_name, true_args, false_name, false_args) do + case compile_time_repeat_while(quoted) do + :cont -> + {true_name, [], true_args} + + :halt -> + {false_name, [], false_args} + + :none -> + quote do + case unquote(quoted) do + {:cont, unquote(Enum.at(true_args, 3))} -> unquote({true_name, [], true_args}) + {:halt, unquote(Enum.at(false_args, 3))} -> unquote({false_name, [], false_args}) + end + end + end + end + + ## Repeat up to + + defp compile_bound_times(combinators, count, current, step, config) do + {failure, step} = build_next(step, config) + {recur, step} = build_next(step, config) + + head = quote(do: [rest, acc, stack, context, line, offset]) + args = quote(do: [rest, acc, [unquote(count) | stack], context, line, offset]) + body = {recur, [], args} + current_def = {current, head, true, body} + + config = %{config | catch_all: failure, acc_depth: 0} + {defs, inline, success, step} = compile(combinators, [current_def], [], recur, step, config) + + {next, step} = build_next(step, config) + head = quote(do: [rest, acc, [1 | stack], context, line, offset]) + args = quote(do: [rest, acc, stack, context, line, offset]) + body = {next, [], args} + success_def0 = {success, head, true, body} + + head = quote(do: [rest, acc, [count | stack], context, line, offset]) + args = quote(do: [rest, acc, [count - 1 | stack], context, line, offset]) + body = {recur, [], args} + success_def1 = {success, head, true, body} + + head = quote(do: [rest, acc, [_ | stack], context, line, offset]) + args = quote(do: [rest, acc, stack, context, line, offset]) + body = {next, [], args} + failure_def = {failure, head, true, body} + + defs = Enum.reverse([success_def1, success_def0, failure_def | defs]) + inline = [{current, @arity}, {success, @arity}, {failure, @arity} | inline] + {defs, inline, next, step, :catch_none} + end + + defp compile_unbound_times(combinators, count, current, step, config) do + {failure, step} = build_next(step, config) + {recur, step} = build_next(step, config) + + head = quote(do: [rest, acc, stack, context, line, offset]) + cont = quote(do: {unquote(count), rest, acc, context, line, offset}) + args = quote(do: [rest, [], [unquote(cont) | stack], context, line, offset]) + body = {recur, [], args} + current_def = {current, head, true, body} + + config = %{config | catch_all: failure, acc_depth: 0} + {defs, inline, success, step} = compile(combinators, [current_def], [], recur, step, config) + + {next, step} = build_next(step, config) + head = quote(do: [rest, user_acc, [{1, _, acc, _, _, _} | stack], context, line, offset]) + args = quote(do: [rest, user_acc ++ acc, stack, context, line, offset]) + body = {next, [], args} + success_def0 = {success, head, true, body} + + head = quote(do: [rest, user_acc, [{count, _, acc, _, _, _} | stack], context, line, offset]) + cont = quote(do: {count - 1, rest, user_acc ++ acc, context, line, offset}) + args = quote(do: [rest, [], [unquote(cont) | stack], context, line, offset]) + body = {recur, [], args} + success_def1 = {success, head, true, body} + + head = quote(do: [_, _, [{_, rest, acc, context, line, offset} | stack], _, _, _]) + args = quote(do: [rest, acc, stack, context, line, offset]) + body = {next, [], args} + failure_def = {failure, head, true, body} + + defs = Enum.reverse([success_def1, success_def0, failure_def | defs]) + inline = [{current, @arity}, {success, @arity}, {failure, @arity} | inline] + {defs, inline, next, step, :catch_none} + end + + ## Choice + + defp compile_bound_choice(choices, current, step, config) do + {next_name, next_step} = build_next(step, config) + + defs = + for choice <- choices do + {[], inputs, guards, outputs, _, metadata} = take_bound_combinators(choice) + + {[def], [], ^next_name, ^next_step, _} = + compile_bound_combinator(inputs, guards, outputs, metadata, current, step, config) + + def + end + + catch_all = if [] in choices, do: :catch_none, else: :catch_all + {defs, [], next_name, next_step, catch_all} + end + + defp compile_unbound_choice(choices, current, step, config) do + {done, step} = build_next(step, config) + + # We process choices in reverse order. The last order does not + # have any fallback besides the requirement to drop the stack + # this allows us to compose with repeat and traverse. + config = update_in(config.acc_depth, &(&1 + 2)) + + {first, defs, inline, step} = + compile_unbound_choice(Enum.reverse(choices), [], [], :unused, step, done, config) + + head = quote(do: [rest, acc, stack, context, line, offset]) + cont = quote(do: {rest, context, line, offset}) + args = quote(do: [rest, [], [unquote(cont), acc | stack], context, line, offset]) + body = {first, [], args} + def = {current, head, true, body} + + {[def | Enum.reverse(defs)], [{current, @arity} | inline], done, step, :catch_none} + end + + defp compile_unbound_choice([], defs, inline, previous, step, _success, _config) do + # Discard the last failure definition that won't be used. + {previous, tl(defs), tl(inline), step - 1} + end + + defp compile_unbound_choice([choice | choices], defs, inline, _previous, step, done, config) do + {current, step} = build_next(step, config) + {defs, inline, success, step} = compile(choice, defs, inline, current, step, config) + + head = quote(do: [rest, acc, [_, previous_acc | stack], context, line, offset]) + args = quote(do: [rest, acc ++ previous_acc, stack, context, line, offset]) + body = {done, [], args} + success_def = {success, head, true, body} + + {failure, step} = build_next(step, config) + head = quote(do: [_, _, [{rest, context, line, offset} | _] = stack, _, _, _]) + args = quote(do: [rest, [], stack, context, line, offset]) + body = {current, [], args} + failure_def = {failure, head, true, body} + + defs = [failure_def, success_def | defs] + inline = [{failure, @arity}, {success, @arity} | inline] + config = %{config | catch_all: failure, acc_depth: 0} + compile_unbound_choice(choices, defs, inline, current, step, done, config) + end + + ## No context combinators + + # If a combinator does not need a context, i.e. it cannot abort + # in the middle, then we can compile to an optimized version of + # repeat and times. + # + # For example, a lookahead at the beginning doesn't need a context. + # A choice that is bound doesn't need one either. + defp all_no_context_combinators?([{:lookahead, look_combinators, _} | combinators]) do + all_bound_combinators?(look_combinators) and + all_no_context_combinators_next?(combinators) + end + + defp all_no_context_combinators?(combinators) do + all_no_context_combinators_next?(combinators) + end + + defp all_no_context_combinators_next?([{:choice, choice_combinators, _} | combinators]) do + all_bound_combinators?(choice_combinators) and + all_no_context_combinators_next?(combinators) + end + + defp all_no_context_combinators_next?(combinators) do + all_bound_combinators?(combinators) + end + + ## Bound combinators + + # A bound combinator is a combinator where the number of inputs, guards, + # outputs, line and offset shifts are known at compilation time. We inline + # those bound combinators into a single bitstring pattern for performance. + # Currently error reporting will accuse the beginning of the bound combinator + # in case of errors but such can be addressed if desired. + + defp compile_bound_combinator(inputs, guards, outputs, metadata, current, step, config) do + %{line: line, offset: offset} = metadata + {next, step} = build_next(step, config) + {bin, rest} = compile_bound_bin_pattern(inputs, metadata, quote(do: rest)) + + acc = if config.replace, do: quote(do: acc), else: quote(do: unquote(outputs) ++ acc) + + args = + quote(do: [unquote(rest), unquote(acc), stack, context, unquote(line), unquote(offset)]) + + head = quote(do: [unquote(bin), acc, stack, context, comb__line, comb__offset]) + body = {next, [], args} + + guards = guards_list_to_quoted(guards) + def = {current, head, guards, body} + {[def], [], next, step, :catch_all} + end + + defp compile_bound_bin_pattern(inputs, %{eos: eos?}, var) do + rest = if eos?, do: "", else: var + bin = {:<<>>, [], inputs ++ [quote(do: unquote(rest) :: binary)]} + {bin, rest} + end + + defp all_bound_combinators?(combinators) do + match?({[], _, _, _, _, _}, take_bound_combinators(combinators)) + end + + defp take_bound_combinators(combinators) do + {line, offset} = line_offset_pair() + metadata = %{eos: false, line: line, offset: offset, counter: 0} + take_bound_combinators(combinators, [], [], [], [], metadata) + end + + defp take_bound_combinators([:eos | combinators], inputs, guards, outputs, acc, metadata) do + combinators = Enum.drop_while(combinators, &(&1 == :eos)) + {combinators, inputs, guards, outputs, [:eos | acc], %{metadata | eos: true}} + end + + defp take_bound_combinators(combinators, inputs, guards, outputs, acc, metadata) do + with [combinator | combinators] <- combinators, + {:ok, new_inputs, new_guards, new_outputs, metadata} <- + bound_combinator(combinator, metadata) do + take_bound_combinators( + combinators, + inputs ++ new_inputs, + guards ++ new_guards, + merge_output(new_outputs, outputs), + [combinator | acc], + metadata + ) + else + _ -> + {combinators, inputs, guards, outputs, acc, metadata} + end + end + + defp merge_output(left, right) when is_list(left) and is_list(right), do: left ++ right + defp merge_output(left, right), do: quote(do: unquote(left) ++ unquote(right)) + + defp bound_combinator({:string, string}, %{line: line, offset: offset} = metadata) do + size = byte_size(string) + + line = + case String.split(string, "\n") do + [_] -> + line + + [_ | _] = many -> + last_size = many |> List.last() |> byte_size() + line_offset = add_offset(offset, size - last_size) + + quote do + {elem(unquote(line), 0) + unquote(length(many) - 1), unquote(line_offset)} + end + end + + offset = add_offset(offset, size) + {:ok, [string], [], [string], %{metadata | line: line, offset: offset}} + end + + defp bound_combinator({:bin_segment, inclusive, exclusive, modifier}, metadata) do + %{line: line, offset: offset, counter: counter} = metadata + + {var, counter} = build_var(counter) + input = apply_bin_modifier(var, modifier) + guards = compile_bin_ranges(var, inclusive, exclusive) + + offset = + if modifier == :integer do + add_offset(offset, 1) + else + add_offset(offset, quote(do: byte_size(<>))) + end + + line = + if newline_allowed?(inclusive) and not newline_forbidden?(exclusive) do + add_line(line, offset, var) + else + line + end + + metadata = %{metadata | line: line, offset: offset, counter: counter} + {:ok, [input], guards, [var], metadata} + end + + defp bound_combinator({:label, combinators, _labels}, metadata) do + case take_bound_combinators(combinators, [], [], [], [], metadata) do + {[], inputs, guards, outputs, _, metadata} -> + {:ok, inputs, guards, outputs, metadata} + + {_, _, _, _, _, _} -> + :error + end + end + + defp bound_combinator({:traverse, combinators, kind, mfargs}, pre_metadata) do + case take_bound_combinators(combinators, [], [], [], [], pre_metadata) do + {[], inputs, guards, outputs, _, post_metadata} -> + {rest, context} = quote(do: {rest, context}) + {traverse_line, traverse_offset} = pre_post_traverse(kind, pre_metadata, post_metadata) + + case apply_traverse(mfargs, rest, outputs, context, traverse_line, traverse_offset) do + {:{}, _, [^rest, outputs, ^context]} when outputs != :error -> + {:ok, inputs, guards, outputs, post_metadata} + + _ -> + :error + end + + {_, _, _, _, _, _} -> + :error + end + end + + defp bound_combinator({:bytes, count}, metadata) do + %{counter: counter, offset: offset} = metadata + {var, counter} = build_var(counter) + input = quote do: unquote(var) :: binary - size(unquote(count)) + offset = add_offset(offset, count) + metadata = %{metadata | counter: counter, offset: offset} + {:ok, [input], [], [var], metadata} + end + + defp bound_combinator(_, _) do + :error + end + + ## Line and offset handling + + # For pre traversal returns the AST before, otherwise the AST after + # for post. For constant, line/offset are never used. + defp pre_post_traverse(:pre, %{line: line, offset: offset}, _), do: {line, offset} + defp pre_post_traverse(_, _, %{line: line, offset: offset}), do: {line, offset} + + defp line_offset_pair() do + quote(do: {comb__line, comb__offset}) + end + + defp add_offset({:+, _, [var, current]}, extra) + when is_integer(current) and is_integer(extra) do + {:+, [], [var, current + extra]} + end + + defp add_offset(var, extra) do + {:+, [], [var, extra]} + end + + defp newline_allowed?([]), do: true + + defp newline_allowed?(ors) do + Enum.any?(ors, fn + _.._//_ = range -> ?\n in range + codepoint -> ?\n === codepoint + end) + end + + defp newline_forbidden?([]), do: false + + defp newline_forbidden?(ands) do + Enum.any?(ands, fn + {:not, _.._//_ = range} -> ?\n in range + {:not, codepoint} -> ?\n === codepoint + end) + end + + defp add_line(line, offset, var) do + quote do + line = unquote(line) + + case unquote(var) do + ?\n -> {elem(line, 0) + 1, unquote(offset)} + _ -> line + end + end + end + + ## Label + + defp labels([]) do + "nothing" + end + + defp labels(combinators) do + Enum.map_join(combinators, ", followed by ", &label/1) + end + + defp label({:string, binary}) do + "string #{inspect(binary)}" + end + + defp label({:label, _combinator, label}) do + label + end + + defp label({:bin_segment, inclusive, exclusive, modifier}) do + {inclusive, printable?} = Enum.map_reduce(inclusive, true, &inspect_bin_range(&1, &2)) + + {exclusive, printable?} = + Enum.map_reduce(exclusive, printable?, &inspect_bin_range(elem(&1, 1), &2)) + + prefix = + cond do + modifier == :integer and not printable? -> "byte" + modifier == :integer -> "ASCII character" + modifier == :utf8 -> "utf8 codepoint" + modifier == :utf16 -> "utf16 codepoint" + modifier == :utf32 -> "utf32 codepoint" + end + + prefix <> Enum.join([Enum.join(inclusive, " or") | exclusive], ", and not") + end + + defp label(:eos) do + "end of string" + end + + defp label({:lookahead, combinators, _}) do + labels(combinators) + end + + defp label({:repeat, combinators, _, _}) do + labels(combinators) + end + + defp label({:eventually, combinators}) do + labels(combinators) <> " eventually" + end + + defp label({:times, combinators, _}) do + labels(combinators) + end + + defp label({:choice, choices, _}) do + Enum.map_join(choices, " or ", &labels/1) + end + + defp label({:traverse, combinators, _, _}) do + labels(combinators) + end + + defp label({:parsec, {_module, function}}) do + Atom.to_string(function) + end + + defp label({:parsec, name}) do + Atom.to_string(name) + end + + defp label({:bytes, count}) do + "#{inspect(count)} bytes" + end + + ## Bin segments + + defp compile_bin_ranges(var, ors, ands) do + ands = Enum.map(ands, &bin_range_to_guard(var, &1)) + + if ors == [] do + ands + else + ors = + ors + |> Enum.map(&bin_range_to_guard(var, &1)) + |> Enum.reduce(&{:or, [], [&2, &1]}) + + [ors | ands] + end + end + + defp bin_range_to_guard(var, range) do + case range do + min..min//step when abs(step) == 1 -> + quote(do: unquote(var) === unquote(min)) + + min..max//1 -> + quote(do: unquote(var) >= unquote(min) and unquote(var) <= unquote(max)) + + min..max//-1 -> + quote(do: unquote(var) >= unquote(max) and unquote(var) <= unquote(min)) + + min when is_integer(min) -> + quote(do: unquote(var) === unquote(min)) + + {:not, min..min//step} when abs(step) == 1 -> + quote(do: unquote(var) !== unquote(min)) + + {:not, min..max//1} -> + quote(do: unquote(var) < unquote(min) or unquote(var) > unquote(max)) + + {:not, min..max//-1} -> + quote(do: unquote(var) < unquote(max) or unquote(var) > unquote(min)) + + {:not, min} when is_integer(min) -> + quote(do: unquote(var) !== unquote(min)) + end + end + + defp inspect_bin_range(min..max//_, printable?) do + {" in the range #{inspect_char(min)} to #{inspect_char(max)}", + printable? and printable?(min) and printable?(max)} + end + + defp inspect_bin_range(min, printable?) do + {" equal to #{inspect_char(min)}", printable? and printable?(min)} + end + + defp printable?(codepoint), do: List.ascii_printable?([codepoint]) + defp inspect_char(codepoint), do: inspect(<>) + + defp apply_bin_modifier(expr, :integer), do: expr + + defp apply_bin_modifier(expr, modifier) do + {:"::", [], [expr, Macro.var(modifier, __MODULE__)]} + end + + ## Helpers + + defp apply_mfa({mod, fun, args}, extra) do + apply(mod, fun, extra ++ args) + end + + defp guards_list_to_quoted([]), do: true + defp guards_list_to_quoted(guards), do: Enum.reduce(guards, &{:and, [], [&2, &1]}) + + defp build_var(counter) do + {{:"x#{counter}", [], __MODULE__}, counter + 1} + end + + defp build_next(step, %{name: name}) do + {:"#{name}__#{step}", step + 1} + end + + defp build_ok(current) do + head = quote(do: [rest, acc, _stack, context, line, offset]) + body = quote(do: {:ok, acc, rest, context, line, offset}) + {current, head, true, body} + end + + defp build_catch_all(kind, name, combinators, %{catch_all: nil, labels: labels}) do + reason = error_reason(combinators, labels) + reason = if kind == :positive, do: "expected " <> reason, else: "did not expect " <> reason + args = quote(do: [rest, _acc, _stack, context, line, offset]) + body = quote(do: {:error, unquote(reason), rest, context, line, offset}) + {name, args, true, body} + end + + defp build_catch_all(_kind, name, _combinators, %{catch_all: next, acc_depth: n}) do + build_proxy_to(name, next, n) + end + + defp build_acc_depth(1, acc, stack), do: [{:|, [], [acc, stack]}] + defp build_acc_depth(n, acc, stack), do: [quote(do: _) | build_acc_depth(n - 1, acc, stack)] + + defp build_proxy_to(name, next, 0) do + args = quote(do: [rest, acc, stack, context, line, offset]) + body = {next, [], args} + {name, args, true, body} + end + + defp build_proxy_to(name, next, n) do + args = quote(do: [rest, _acc, stack, context, line, offset]) + {acc, stack} = quote(do: {acc, stack}) + + body = + quote do + unquote(build_acc_depth(n, acc, stack)) = stack + unquote(next)(rest, acc, stack, context, line, offset) + end + + {name, args, true, body} + end + + defp error_reason(combinators, []) do + labels(combinators) + end + + defp error_reason(_combinators, [head]) do + head + end + + defp error_reason(_combinators, [head | tail]) do + "#{head} while processing #{Enum.join(tail, " inside ")}" + end +end diff --git a/deps/nimble_parsec/lib/nimble_parsec/recorder.ex b/deps/nimble_parsec/lib/nimble_parsec/recorder.ex new file mode 100644 index 0000000000000000000000000000000000000000..9b8fa778436298a435de5c5b87eec93c5bac7a0e --- /dev/null +++ b/deps/nimble_parsec/lib/nimble_parsec/recorder.ex @@ -0,0 +1,125 @@ +defmodule NimbleParsec.Recorder do + @moduledoc false + + @name __MODULE__ + + @doc """ + Starts the recorder server. + """ + def start_link(_opts) do + Agent.start_link(fn -> %{} end, name: @name) + end + + @doc """ + Stops the recorder server. + """ + def stop() do + Agent.stop(@name) + end + + @doc """ + Records the given call and potentially debugs it. + """ + def record(module, parser_kind, combinator_kind, name, combinators, inline, opts) do + inline? = Keyword.get(opts, :inline, false) + + if Keyword.get(opts, :debug, false) do + IO.puts(format_defs(combinator_kind, combinators, inline, inline?)) + end + + if Process.whereis(@name) do + Agent.update(@name, fn state -> + update_in( + state[module], + &[{parser_kind, combinator_kind, name, combinators, inline, inline?} | &1 || []] + ) + end) + end + + :ok + end + + defp format_parser_kind(nil, _name) do + [] + end + + defp format_parser_kind(:def, name) do + {doc, spec, def} = NimbleParsec.Compiler.entry_point(name) + + """ + @doc "\"" + #{doc} + "\"" + @spec #{Macro.to_string(spec)} + #{format_def(:def, def)} + """ + end + + defp format_parser_kind(:defp, name) do + {_doc, spec, def} = NimbleParsec.Compiler.entry_point(name) + + """ + @spec #{Macro.to_string(spec)} + #{format_def(:defp, def)} + """ + end + + defp format_defs(kind, defs, inline, inline?) do + functions = Enum.map(defs, &format_def(kind, &1)) + inline = if inline?, do: "@compile {:inline, #{inspect(inline)}}\n\n", else: "" + [inline | functions] + end + + defp format_def(kind, {name, args, guards, body}) do + signature = Macro.to_string(quote(do: unquote(name)(unquote_splicing(args)))) + + if guards == true do + """ + #{kind} #{signature} do + #{Macro.to_string(body)} + end + + """ + else + """ + #{kind} #{signature} when #{Macro.to_string(guards)} do + #{Macro.to_string(body)} + end + + """ + end + end + + @doc """ + Replays recorded parsers on the given content. + """ + def replay(contents, id) when is_binary(contents) do + code = inject_recorded(contents, id, Agent.get(@name, & &1)) + [Code.format_string!(code) | "\n"] + end + + defp inject_recorded(contents, id, recorded) do + Enum.reduce(recorded, contents, fn {module, entries}, acc -> + marker = "# parsec:#{inspect(module)}" + + case String.split(acc, marker) do + [pre, _middle, pos] -> + replacement = Enum.map(entries, &format_recorded/1) + IO.iodata_to_binary([pre, replacement, pos]) + + [_, _] -> + raise ArgumentError, "expected 2 markers #{inspect(marker)} on #{inspect(id)}, got 1" + + _ -> + raise ArgumentError, "could not find marker #{inspect(marker)} on #{inspect(id)}" + end + end) + end + + defp format_recorded({parser_kind, combinator_kind, name, combinators, inline, inline?}) do + [ + format_parser_kind(parser_kind, name) + | format_defs(combinator_kind, combinators, inline, inline?) + ] + end +end diff --git a/deps/nimble_parsec/mix.exs b/deps/nimble_parsec/mix.exs new file mode 100644 index 0000000000000000000000000000000000000000..42cef62565ecc5d8102b5e200ebc7ad29a29c33f --- /dev/null +++ b/deps/nimble_parsec/mix.exs @@ -0,0 +1,44 @@ +defmodule NimbleParsec.MixProject do + use Mix.Project + + @version "1.4.2" + @url "https://github.com/dashbitco/nimble_parsec" + + def project do + [ + app: :nimble_parsec, + version: @version, + elixir: "~> 1.12", + name: "NimbleParsec", + description: "A simple and fast library for text-based parser combinators", + aliases: [docs: &build_docs/1], + package: package() + ] + end + + def application do + [] + end + + defp package do + %{ + licenses: ["Apache-2.0"], + maintainers: ["José Valim"], + links: %{"GitHub" => @url} + } + end + + defp build_docs(_) do + Mix.Task.run("compile") + ex_doc = Path.join(Mix.path_for(:escripts), "ex_doc") + + unless File.exists?(ex_doc) do + raise "cannot build docs because escript for ex_doc is not installed, run \"mix escript.install hex ex_doc\"" + end + + args = ["NimbleParsec", @version, Mix.Project.compile_path()] + opts = ~w[--main NimbleParsec --source-ref v#{@version} --source-url #{@url}] + System.cmd(ex_doc, args ++ opts) + Mix.shell().info("Docs built successfully") + end +end diff --git a/deps/safetensors/lib/safetensors/file_tensor.ex b/deps/safetensors/lib/safetensors/file_tensor.ex new file mode 100644 index 0000000000000000000000000000000000000000..439425fffa95cd8821b1ae96389d2a050740fa8b --- /dev/null +++ b/deps/safetensors/lib/safetensors/file_tensor.ex @@ -0,0 +1,20 @@ +defmodule Safetensors.FileTensor do + @moduledoc false + + defstruct [:shape, :type, :path, :byte_offset, :byte_size] +end + +defimpl Nx.LazyContainer, for: Safetensors.FileTensor do + def traverse(lazy_tensor, acc, fun) do + template = Nx.template(lazy_tensor.shape, lazy_tensor.type) + + load = fn -> + File.open!(lazy_tensor.path, [:read, :raw], fn file -> + {:ok, binary} = :file.pread(file, lazy_tensor.byte_offset, lazy_tensor.byte_size) + Safetensors.Shared.build_tensor(binary, lazy_tensor.shape, lazy_tensor.type) + end) + end + + fun.(template, load, acc) + end +end diff --git a/deps/safetensors/lib/safetensors/shared.ex b/deps/safetensors/lib/safetensors/shared.ex new file mode 100644 index 0000000000000000000000000000000000000000..d98414106b2962efe083d94cf2222843c052182b --- /dev/null +++ b/deps/safetensors/lib/safetensors/shared.ex @@ -0,0 +1,36 @@ +defmodule Safetensors.Shared do + @moduledoc false + + @doc """ + Builds Nx tensor from the given safetensors binary. + """ + @spec build_tensor(binary(), tuple(), Nx.Type.t()) :: Nx.Tensor.t() + def build_tensor(binary, shape, type) do + {_, elem_size} = type + + binary + |> new_byte_order(elem_size, :little) + |> IO.iodata_to_binary() + |> Nx.from_binary(type) + |> Nx.reshape(shape) + end + + @doc """ + Changes endianness `binary` if `endianness` does not match system. + """ + @spec new_byte_order(binary(), pos_integer(), :little | :big) :: iodata() + def new_byte_order(binary, size, endianness) do + if System.endianness() == endianness do + binary + else + data = + for <> do + data + |> :binary.decode_unsigned() + |> :binary.encode_unsigned(endianness) + end + + IO.iodata_to_binary(data) + end + end +end