fast_xml-1.1.48/ 0000755 0002322 0002322 00000000000 14151146420 013766 5 ustar debalance debalance fast_xml-1.1.48/lib/ 0000755 0002322 0002322 00000000000 14151146420 014534 5 ustar debalance debalance fast_xml-1.1.48/lib/fast_xml.ex 0000644 0002322 0002322 00000002333 14151146420 016710 0 ustar debalance debalance defmodule FastXML do
require Record
@doc """
xml element record, composed of fields: name, attrs, children
"""
Record.defrecord :xmlel, Record.extract(:xmlel, from_lib: "fast_xml/include/fxml.hrl")
@type xmlel :: record(:xmlel, name: String.t, attrs: [attr], children: [content])
@type content :: xmlel | cdata
@type cdata :: {:xmlcdata, String.t}
@type attr :: {attribute::String.t, value::String.t}
Record.defrecord :xmlstreamstart, name: "", attrs: []
@type xmlstreamstart :: record(:xmlstreamstart, name: String.t, attrs: [attr])
Record.defrecord :xmlstreamend, name: ""
@type xmlstreamend :: record(:xmlstreamend, name: String.t)
Record.defrecord :xmlstreamerror, error: {0, ""}
@type xmlstreamerror ::record(:xmlstreamerror, error: error)
@type error :: {code::Integer, description::String.t}
def start, do: :application.start(:fast_xml)
def stop, do: :application.stop(:fast_xml)
end
# Elixir oriented data structures:
defmodule FastXML.El do
defstruct name: "", attrs: %{}, children: []
end
defmodule FastXML.StreamStart do
defstruct name: "", attrs: %{}
end
defmodule FastXML.StreamEnd do
defstruct name: ""
end
defmodule FastXML.StreamError do
defstruct code: 0, desc: ""
end
fast_xml-1.1.48/mix.lock 0000644 0002322 0002322 00000001325 14151146420 015436 0 ustar debalance debalance %{"earmark": {:hex, :earmark, "0.2.1", "ba6d26ceb16106d069b289df66751734802777a3cbb6787026dd800ffeb850f3", [:mix], [], "hexpm"},
"elixir_make": {:hex, :elixir_make, "0.4.0", "992f38fabe705bb45821a728f20914c554b276838433349d4f2341f7a687cddf", [:mix], [], "hexpm"},
"eqc_ex": {:hex, :eqc_ex, "1.4.2", "c89322cf8fbd4f9ddcb18141fb162a871afd357c55c8c0198441ce95ffe2e105", [:mix], [], "hexpm"},
"ex_doc": {:hex, :ex_doc, "0.12.0", "b774aabfede4af31c0301aece12371cbd25995a21bb3d71d66f5c2fe074c603f", [:mix], [{:earmark, "~> 0.2", [hex: :earmark, repo: "hexpm", optional: false]}], "hexpm"},
"p1_utils": {:hex, :p1_utils, "1.0.10", "a6d6927114bac79cf6468a10824125492034af7071adc6ed5ebc4ddb443845d4", [:rebar3], [], "hexpm"}}
fast_xml-1.1.48/LICENSE.txt 0000644 0002322 0002322 00000026136 14151146420 015621 0 ustar debalance debalance
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.
fast_xml-1.1.48/README.md 0000644 0002322 0002322 00000012004 14151146420 015242 0 ustar debalance debalance # Erlang and Elixir XML Parsing
[](https://github.com/processone/fast_xml/actions/workflows/ci.yml)
[](https://coveralls.io/github/processone/fast_xml?branch=master)
[](https://hex.pm/packages/fast_xml)
Fast Expat based Erlang XML parsing and manipulation library, with a
strong focus on XML stream parsing from network.
It supports:
- Full XML structure parsing: Suitable for small but complete XML chunks.
- XML stream parsing: Suitable for large XML document, or infinite
network XML stream like XMPP.
This module can parse files much faster than built-in module `xmerl`.
Depending on file complexity and size `fxml_stream:parse_element/1` can
be 8-18 times faster than calling `xmerl_scan:string/2`.
This application was previously called
[p1_xml](https://github.com/processone/xml) and was renamed after
major optimisations to put emphasis on the fact it is damn fast.
## Building
Erlang XML parser can be build as follow:
./configure && make
Erlang XML parser is a rebar-compatible OTP
application. Alternatively, you can build it with rebar:
rebar compile
## Dependencies
Erlang XML parser depends on Expat XML parser. You need development
headers for Expat library to build it.
You can use `configure` options to pass custom path to Expat libraries and headers:
--with-expat=[ARG] use Expat XML Parser from given prefix (ARG=path);
check standard prefixes (ARG=yes); disable (ARG=no)
--with-expat-inc=[DIR] path to Expat XML Parser headers
--with-expat-lib=[ARG] link options for Expat XML Parser libraries
## xmlel record and types
XML elements are provided as Erlang xmlel records.
Format of the record allows defining a simple tree-like
structure. xmlel record has the following fields:
- name :: binary()
- attrs :: [attr()]
- children :: [xmlel() | cdata()]
cdata type is a tuple of the form:
{xmlcdata, CData::binary()}
attr type if a tuple of the form:
{Name::binary(), Value::binary()}
## XML full structure parsing
You can definitely parse a complete XML structure with `fast_xml`:
```shell
$ erl -pa ebin
Erlang/OTP 17 [erts-6.3] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]
Eshell V6.3 (abort with ^G)
1> application:start(fast_xml).
ok
2> rr(fxml).
[xmlel]
3> fxml_stream:parse_element(<<"content cdata">>).
#xmlel{name = <<"test">>,attrs = [],
children = [{xmlcdata,<<"content cdata">>}]}
```
## XML Stream parsing example
You can also parse continuous stream. Our design allows decoupling
very easily the process receiving the raw XML to parse from the
process receiving the parsed content.
The workflow is as follow:
state = new(CallbackPID); parse(state, data); parse(state, moredata); ...
and the parsed XML fragments (stanzas) are send to CallbackPID.
With that approach you can be very flexible on how you architect your
own application.
Here is an example XML stream parsing:
```shell
$ erl -pa ebin
Erlang/OTP 17 [erts-6.3] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]
Eshell V6.3 (abort with ^G)
% Start the application:
1> application:start(fast_xml).
ok
% Create a new stream, using self PID to received XML parsing event:
2> S1 = fxml_stream:new(self()).
<<>>
% Start feeding content to the XML parser.
3> S2 = fxml_stream:parse(S1, <<"">>).
<<>>
% Receive Erlang message send to shell process:
4> flush().
Shell got {'$gen_event',{xmlstreamstart,<<"root">>,[]}}
ok
% Feed more content:
5> S3 = fxml_stream:parse(S2, <<"content cdata">>).
<<>>
% Receive more messages:
6> flush().
Shell got {'$gen_event',
{xmlstreamelement,
{xmlel,<<"xmlelement">>,[],
[{xmlcdata,<<"content cdata">>}]}}}
ok
% Feed more content:
7> S4 = fxml_stream:parse(S3, <<"">>).
<<>>
% Receive messages:
8> flush().
Shell got {'$gen_event',{xmlstreamend,<<"root">>}}
ok
9> fxml_stream:close(S4).
true
```
Note how the root element is important. We expect to have the root
element serve as boundary with stream start and stream end
event. Then, lower level tags are passed as sub stream elements.
## How does this module relate to exmpp ?
This module is a low level fast XML parser. It is not an XMPP client
library like [exmpp](https://processone.github.io/exmpp/).
## References
This module is use at large scale for parsing massive XML content in
[ejabberd](https://www.ejabberd.im) XMPP server project. It is used in
production in thousands of real life deployments.
## Development
### Test
#### Unit test
You can run eunit test with the command:
$ rebar eunit
#### Elixir / Quickcheck test
You can run test written with Elixir / Quickcheck thanks to the mix command:
MIX_EXS=test/elixir/mix.exs mix test
fast_xml-1.1.48/vars.config.in 0000644 0002322 0002322 00000000240 14151146420 016531 0 ustar debalance debalance {cflags, "@CFLAGS@"}.
{ldflags, "@LDFLAGS@ @LIBS@"}.
{with_gcov, "@gcov@"}.
%% Local Variables:
%% mode: erlang
%% End:
%% vim: set filetype=erlang tabstop=8:
fast_xml-1.1.48/rebar.config.script 0000644 0002322 0002322 00000012303 14151146420 017552 0 ustar debalance debalance %%%----------------------------------------------------------------------
%%% File : rebar.config.script
%%% Author : Evgeniy Khramtsov
%%% Purpose : Rebar build script. Compliant with rebar and rebar3.
%%% Created : 8 May 2013 by Evgeniy Khramtsov
%%%
%%% Copyright (C) 2002-2021 ProcessOne, SARL. 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.
%%%
%%%----------------------------------------------------------------------
Cfg = case file:consult(filename:join([filename:dirname(SCRIPT),"vars.config"])) of
{ok, Terms} ->
Terms;
_Err ->
[]
end ++ [{cflags, "-g -O2 -Wall"}, {ldflags, "-lexpat"}, {with_gcov, "false"}],
{cflags, CfgCFlags} = lists:keyfind(cflags, 1, Cfg),
{ldflags, CfgLDFlags} = lists:keyfind(ldflags, 1, Cfg),
{with_gcov, CfgWithGCov} = lists:keyfind(with_gcov, 1, Cfg),
IsRebar3 = case erlang:function_exported(rebar3, main, 1) of
true ->
true;
_ ->
lists:keymember(mix, 1, application:loaded_applications())
end,
ModCfg0 = fun(F, Cfg, [Key|Tail], Op, Default) ->
{OldVal,PartCfg} = case lists:keytake(Key, 1, Cfg) of
{value, {_, V1}, V2} -> {V1, V2};
false -> {if Tail == [] -> Default; true -> [] end, Cfg}
end,
case Tail of
[] ->
[{Key, Op(OldVal)} | PartCfg];
_ ->
[{Key, F(F, OldVal, Tail, Op, Default)} | PartCfg]
end
end,
ModCfg = fun(Cfg, Keys, Op, Default) -> ModCfg0(ModCfg0, Cfg, Keys, Op,
Default) end,
ModCfgS = fun(Cfg, Keys, Val) -> ModCfg0(ModCfg0, Cfg, Keys, fun(_V) ->
Val end, "") end,
FilterConfig = fun(F, Cfg, [{Path, true, ModFun, Default} | Tail]) ->
F(F, ModCfg0(ModCfg0, Cfg, Path, ModFun, Default), Tail);
(F, Cfg, [_ | Tail]) ->
F(F, Cfg, Tail);
(F, Cfg, []) ->
Cfg
end,
AppendStr = fun(Append) ->
fun("") ->
Append;
(Val) ->
Val ++ " " ++ Append
end
end,
AppendList = fun(Append) ->
fun(Val) ->
Val ++ Append
end
end,
Rebar3DepsFilter = fun(DepsList) ->
lists:map(fun({DepName,_, {git,_, {tag,Version}}}) ->
{DepName, Version};
(Dep) ->
Dep
end, DepsList)
end,
GlobalDepsFilter = fun(Deps) ->
DepNames = lists:map(fun({DepName, _, _}) -> DepName;
({DepName, _}) -> DepName
end, Deps),
lists:filtermap(fun(Dep) ->
case code:lib_dir(Dep) of
{error, _} ->
{true,"Unable to locate dep '"++atom_to_list(Dep)++"' in system deps."};
_ ->
false
end
end, DepNames)
end,
GithubConfig = case {os:getenv("GITHUB_ACTIONS"), os:getenv("GITHUB_TOKEN")} of
{"true", Token} when is_list(Token) ->
CONFIG1 = [{coveralls_repo_token, Token},
{coveralls_service_job_id, os:getenv("GITHUB_RUN_ID")},
{coveralls_commit_sha, os:getenv("GITHUB_SHA")},
{coveralls_service_number, os:getenv("GITHUB_RUN_NUMBER")}],
case os:getenv("GITHUB_EVENT_NAME") =:= "pull_request"
andalso string:tokens(os:getenv("GITHUB_REF"), "/") of
[_, "pull", PRNO, _] ->
[{coveralls_service_pull_request, PRNO} | CONFIG1];
_ ->
CONFIG1
end;
_ ->
[]
end,
Rules = [
{[port_env, "CFLAGS"], true,
AppendStr(CfgCFlags), "$CFLAGS"},
{[port_env, "LDFLAGS"], true,
AppendStr(CfgLDFlags), "$LDFLAGS"},
{[post_hooks], (not IsRebar3) and (CfgWithGCov == "true"),
AppendList([{eunit, "gcov -o c_src fxml fxml_stream"},
{eunit, "mv *.gcov .eunit/"}]), []},
{[post_hooks], IsRebar3 and (CfgWithGCov == "true"),
AppendList([{eunit, "gcov -o c_src fxml fxml_stream"},
{eunit, "mv *.gcov _build/test/cover/"}]), []},
{[port_env, "LDFLAGS"], CfgWithGCov == "true",
AppendStr("--coverage"), ""},
{[port_env, "CFLAGS"], CfgWithGCov == "true",
AppendStr("--coverage"), ""},
{[deps], IsRebar3,
Rebar3DepsFilter, []},
{[plugins], IsRebar3,
AppendList([pc]), []},
{[provider_hooks], IsRebar3,
AppendList([{pre, [
{compile, {pc, compile}},
{clean, {pc, clean}}
]}]), []},
{[plugins], os:getenv("COVERALLS") == "true",
AppendList([{coveralls, {git,
"https://github.com/processone/coveralls-erl.git",
{branch, "addjsonfile"}}} ]), []},
{[deps], os:getenv("USE_GLOBAL_DEPS") /= false,
GlobalDepsFilter, []}
],
Config = FilterConfig(FilterConfig, CONFIG, Rules) ++ GithubConfig,
%io:format("Rules:~n~p~n~nCONFIG:~n~p~n~nConfig:~n~p~n", [Rules, CONFIG, Config]),
Config.
%% Local Variables:
%% mode: erlang
%% End:
%% vim: set filetype=erlang tabstop=8:
fast_xml-1.1.48/CHANGELOG.md 0000644 0002322 0002322 00000012603 14151146420 015601 0 ustar debalance debalance # Version 1.1.48
* Generate documentation before publishing to hex
* Load the NIFs in the on_load callback, to support restart
* Add always_encode field to #attr{}
# Version 1.1.47
* Updating p1_utils to version 1.0.23.
* Switch from using Travis to Github Actions as CI
* Fix compatiblity with OTP24
# Version 1.1.46
* Updating p1_utils to version 1.0.22.
# Version 1.1.45
* Updating p1_utils to version 1.0.21.
# Version 1.1.44
* Get back compatibility with Erlang older than 20
* Add JSON encode/decode functions generation
* Update hex to compile ejabberd with rebar3
# Version 1.1.43
* Updating p1_utils to version 1.0.20.
# Version 1.1.42
* Fix compilation with Erlang/OTP 23.0
# Version 1.1.41
* Updating p1_utils to version 1.0.19.
# Version 1.1.40
* Fix issues with travis testing
# Version 1.1.39
* Updating p1_utils to version 1.0.18.
* Update copyright year
# Version 1.1.38
* Updating p1_utils to version 1.0.17.
# Version 1.1.37
* Updating p1_utils to version 1.0.16.
* Update XMLRPC codec
* Fail with 'badarg' on unknown records
# Version 1.1.36
* Updating p1_utils to version 1.0.15.
# Version 1.1.35
* Updating p1_utils to version 1.0.14.
* Add contribution guide
# Version 1.1.34
* Updating p1_utils to version 1.0.13.
# Version 1.1.33
* Updating p1_utils to version 6ff85e8.
* Fix incompatibility with OTP21
# Version 1.1.32
* Don't crash when trying to encode xmlcdata
# Version 1.1.31
* Updating p1_utils to version 1.0.12.
# Version 1.1.30
* Improve detection of rebar3
* Define p1\_utils as application dependency
# Version 1.1.29
* Updating p1_utils to version 1.0.11.
* Fix compilation with rebar3
* Get rid of $\_xmls label
# Version 1.1.28
* Include Makefile in package generated for hex
# Version 1.1.27
* Freeze dependencies in mix.lock file to be more friendly with hex.pm
* Fix ambiguous Elixir syntax in mix.exs
# Version 1.1.26
* Simplify pretty printer generation
* Generate get_els/1 and set_els/2
* The pretty printer should traverse elements recursively
* Extra test for too big input
# Version 1.1.25
* Invalidate sotred data when generating stanza-too-big-error
# Version 1.1.24
* Updating p1_utils to version 1.0.10.
* Make XML generator work on R19.3+
# Version 1.1.23
* depends on p1_utils-1.0.9
# Version 1.1.22
* Fix md5 sum calculation of modules for OTP17 (Evgeniy Khramtsov)
* Fix type spec for fxml_stream:parse_element/1 (Evgeniy Khramtsov)
# Version 1.1.21
* Add code for building on FreeBSD (Dave Cottlehuber)
# Version 1.1.20
* Make XML generator working on OTP 18 (Evgeniy Khramtsov)
# Version 1.1.19
* Add checks for empty string (Paweł Chmielowski)
* Remove unused code (Paweł Chmielowski)
* Load locally build .so file when performing tests (Paweł Chmielowski)
# Version 1.1.18
* Use p1_utils 1.0.6 (Paweł Chmielowski)
* fix xref with otp 17 (Paweł Chmielowski)
# Version 1.1.17
* Add 'undefined' type to some record fields type specs (Evgeniy Khramtsov)
# Version 1.1.16
* Improve XML generator (Evgeniy Khramtsov)
# Version 1.1.15
* Update to p1_utils 1.0.5 (Mickaël Rémond)
# Version 1.1.14
* Erlang OTP R19 compliance (Paweł Chmielowski)
* Fix compilation on rebar3 (Paweł Chmielowski)
# Version 1.1.13
* Use p1_utils 1.0.4 (Mickaël Rémond)
# Version 1.1.12
* Generator improvements (Evgeny Khramtsov)
# Version 1.1.11
* Now properly includes Elixir lib/ directory in hex.pm package (Mickaël Rémond)
# Version 1.1.10
* Split build in two steps to fix link step on Ubuntu (Paweł Chmielowski - Mickaël Rémond)
* Clean Makefile.mix to remove duplicated code (Paweł Chmielowski)
# Version 1.1.9
* Fix Linux build with Mix (Paweł Chmielowski)
# Version 1.1.8
* Package priv/lib structure to make sure everything is properly build by mix (Mickaël Rémond)
# Version 1.1.7
* Fix indent issue in Mix Makefile (Mickaël Rémond)
# Version 1.1.6
* Add missing Makefile.mix file in rebar hex.pm package description (Mickaël Rémond)
* Make sure priv dir is created when building with mix and included in package dir list (Mickaël Rémond)
# Version 1.1.4
This is an Elixir friendly update:
* Add ability to return maps instead of xmlel record (Paweł Chmielowski)
* Add ability to tell parser to return Elixir structs instead of records (Mickaël Rémond)
* Add Elixir tests (Mickaël Rémond)
# Version 1.1.3
* Memory optimizations (Paweł Chmielowski)
* Update to latest version of p1_utils (Mickaël Rémond)
* Erlang OTP R18 compliance (Evgeniy Khramtsov)
# Version 1.1.2
* Application is now called fast_xml (Mickaël Rémond)
# Version 1.1.1
* Support for both rebar and rebar3 (Mickaël Rémond)
* Huge performance and memory improvements (Paweł Chmielowski)
* Normalize namespace prefixed elements (Paweł Chmielowski)
* Document how to run tests (Mickaël Rémond)
* Architecture documentation in README.md (Mickaël Rémond)
* Introduce Elixir Quickcheck tests (Mickaël Rémond)
* Support C code coverage (Paweł Chmielowski)
* Better test case coverage (Evgeniy Khramtsov)
* Continuous integration with Travis CI and Coveralls (Paweł Chmielowski - Mickaël Rémond)
* Test refactoring (Evgeniy Khramtsov)
* Save cflags/ldflags passed to configure (Paweł Chmielowski)
* Move code for locating nif files to p1_utils package (Paweł Chmielowski)
* Improve code for locating .so part (Paweł Chmielowski)
* Do not check Expat presence via m4 macro (Evgeniy Khramtsov)
# Version 1.1.0
* Initial release on Hex.pm (Mickaël Rémond)
fast_xml-1.1.48/Makefile 0000644 0002322 0002322 00000001231 14151146420 015423 0 ustar debalance debalance REBAR ?= rebar
IS_REBAR3:=$(shell expr `$(REBAR) --version | awk -F '[ .]' '/rebar / {print $$2}'` '>=' 3)
ERL=erl
all: src
src:
$(REBAR) get-deps
$(REBAR) compile
clean:
$(REBAR) clean
ifeq "$(IS_REBAR3)" "1"
test:
$(REBAR) eunit -v
else
test: all
$(REBAR) -v skip_deps=true eunit
endif
spec:
$(ERL) -noinput +B -pa ebin -pa deps/*/ebin -eval 'case fxml_gen:compile("spec/fxmlrpc_codec.spec", [{erl_dir, "src"}, {hrl_dir, "include"}]) of ok -> halt(0); _ -> halt(1) end.'
# We assume Elixir and Quviq Quickcheck are installed
exunit:
MIX_EXS=test/elixir/mix.exs mix test
check-syntax:
gcc -o nul -S ${CHK_SOURCES}
.PHONY: clean src test all spec
fast_xml-1.1.48/spec/ 0000755 0002322 0002322 00000000000 14151146420 014720 5 ustar debalance debalance fast_xml-1.1.48/spec/README.md 0000644 0002322 0002322 00000000175 14151146420 016202 0 ustar debalance debalance This file is used to generate `src/fxmlrpc_codec.erl`.
From repository root, you can regenerate the file with:
$ make spec
fast_xml-1.1.48/spec/fxmlrpc_codec.spec 0000644 0002322 0002322 00000011033 14151146420 020402 0 ustar debalance debalance -xml(methodCall,
#elem{name = <<"methodCall">>,
xmlns = <<"xmlrpc">>,
result = {call, '$name', '$params'},
refs = [#ref{name = methodName,
label = '$name',
min = 1, max = 1},
#ref{name = params,
label = '$params',
default = [],
min = 0, max = 1}]}).
-xml(methodResponse,
#elem{name = <<"methodResponse">>,
xmlns = <<"xmlrpc">>,
result = {response, '$payload'},
refs = [#ref{name = fault, label = '$payload', default = [],
min = 0, max = 1},
#ref{name = params, label = '$payload', default = [],
min = 0, max = 1}]}).
-xml(fault,
#elem{name = <<"fault">>,
xmlns = <<"xmlrpc">>,
result = {fault, '$value'},
refs = [#ref{name = value, label = '$value', min = 1, max = 1}]}).
-xml(methodName,
#elem{name = <<"methodName">>,
xmlns = <<"xmlrpc">>,
result = '$cdata',
cdata = #cdata{required = true,
dec = {erlang, binary_to_atom, [utf8]},
enc = {erlang, atom_to_binary, [utf8]}}}).
-xml(params,
#elem{name = <<"params">>,
xmlns = <<"xmlrpc">>,
result = '$params',
refs = [#ref{name = param, label = '$params'}]}).
-xml(param,
#elem{name = <<"param">>,
xmlns = <<"xmlrpc">>,
result = '$value',
refs = [#ref{name = value, label = '$value',
min = 1, max = 1}]}).
-xml(value,
#elem{name = <<"value">>,
xmlns = <<"xmlrpc">>,
result = {'$val', '$cdata'},
refs = [#ref{name = i4, label = '$val', min = 0, max = 1},
#ref{name = int, label = '$val', min = 0, max = 1},
#ref{name = string, label = '$val', min = 0, max = 1},
#ref{name = double, label = '$val', min = 0, max = 1},
#ref{name = base64, label = '$val', min = 0, max = 1},
#ref{name = boolean, label = '$val', min = 0, max = 1},
#ref{name = array, label = '$val', min = 0, max = 1},
#ref{name = nil, label = '$val', min = 0, max = 1},
#ref{name = struct, label = '$val', min = 0, max = 1},
#ref{name = dateTime, label = '$val', min = 0, max = 1}],
cdata = #cdata{default = undefined}}).
-xml(i4,
#elem{name = <<"i4">>,
xmlns = <<"xmlrpc">>,
result = {i4, '$cdata'},
cdata = #cdata{required = true,
dec = {erlang, binary_to_integer, []},
enc = {erlang, integer_to_binary, []}}}).
-xml(int,
#elem{name = <<"int">>,
xmlns = <<"xmlrpc">>,
result = {int, '$cdata'},
cdata = #cdata{required = true,
dec = {erlang, binary_to_integer, []},
enc = {erlang, integer_to_binary, []}}}).
-xml(string,
#elem{name = <<"string">>,
xmlns = <<"xmlrpc">>,
cdata = #cdata{default = <<"">>},
result = {string, '$cdata'}}).
-xml(double,
#elem{name = <<"double">>,
xmlns = <<"xmlrpc">>,
result = {double, '$cdata'},
cdata = #cdata{required = true,
dec = {erlang, binary_to_float, []},
enc = {erlang, float_to_binary, []}}}).
-xml(base64,
#elem{name = <<"base64">>,
xmlns = <<"xmlrpc">>,
result = {base64, '$cdata'},
cdata = #cdata{required = true}}).
-xml(dateTime,
#elem{name = <<"dateTime.iso8601">>,
xmlns = <<"xmlrpc">>,
result = {date, '$cdata'},
cdata = #cdata{required = true}}).
-xml(boolean,
#elem{name = <<"boolean">>,
xmlns = <<"xmlrpc">>,
result = {boolean, '$cdata'},
cdata = #cdata{required = true,
dec = {dec_bool, []},
enc = {enc_bool, []}}}).
-xml(array,
#elem{name = <<"array">>,
xmlns = <<"xmlrpc">>,
result = {array, '$data'},
refs = [#ref{name = data, label = '$data', min = 1, max = 1}]}).
-xml(data,
#elem{name = <<"data">>,
xmlns = <<"xmlrpc">>,
result = '$v',
refs = [#ref{name = value, label = '$v'}]}).
-xml(nil,
#elem{name = <<"nil">>,
xmlns = <<"xmlrpc">>,
result = nil}).
-xml(struct,
#elem{name = <<"struct">>,
xmlns = <<"xmlrpc">>,
result = {struct, '$members'},
refs = [#ref{name = member, label = '$members'}]}).
-xml(member,
#elem{name = <<"member">>,
xmlns = <<"xmlrpc">>,
result = {'$name', '$value'},
refs = [#ref{name = name, label = '$name', min = 1, max = 1},
#ref{name = value, label = '$value', min = 1, max = 1}]}).
-xml(name,
#elem{name = <<"name">>,
xmlns = <<"xmlrpc">>,
result = '$cdata',
cdata = #cdata{required = true,
dec = {erlang, binary_to_atom, [utf8]},
enc = {erlang, atom_to_binary, [utf8]}}}).
dec_bool(<<"false">>) -> false;
dec_bool(<<"0">>) -> false;
dec_bool(<<"true">>) -> true;
dec_bool(<<"1">>) -> true.
enc_bool(false) -> <<"0">>;
enc_bool(true) -> <<"1">>.
%% Local Variables:
%% mode: erlang
%% End:
%% vim: set filetype=erlang tabstop=8:
fast_xml-1.1.48/c_src/ 0000755 0002322 0002322 00000000000 14151146420 015057 5 ustar debalance debalance fast_xml-1.1.48/c_src/fxml.c 0000644 0002322 0002322 00000016533 14151146420 016201 0 ustar debalance debalance /*
* Copyright (C) 2002-2021 ProcessOne, SARL. 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.
*
*/
#include
#include
#include
#define SSL40
#ifdef SSL40
#define ENIF_ALLOC(SIZE) enif_alloc(SIZE)
#define ENIF_FREE(PTR) enif_free(PTR)
#define ENIF_REALLOC(PTR, SIZE) enif_realloc(PTR, SIZE)
#define ENIF_ALLOC_BINARY(SIZE, BIN) enif_alloc_binary(SIZE, BIN)
#define ENIF_COMPARE(TERM1, TERM2) enif_compare(TERM1, TERM2)
#else
#define ENIF_ALLOC(SIZE) enif_alloc(env, SIZE)
#define ENIF_FREE(PTR) enif_free(env, PTR)
#define ENIF_REALLOC(PTR, SIZE) enif_realloc(env, PTR, SIZE)
#define ENIF_ALLOC_BINARY(SIZE, BIN) enif_alloc_binary(env, SIZE, BIN)
#define ENIF_COMPARE(TERM1, TERM2) enif_compare(env, TERM1, TERM2)
#endif
static ERL_NIF_TERM atom_xmlelement;
static ERL_NIF_TERM atom_xmlcdata;
struct buf {
int limit;
int len;
unsigned char *b;
};
static int make_element(ErlNifEnv* env, struct buf *rbuf, ERL_NIF_TERM el, int is_header);
static int load(ErlNifEnv* env, void** priv, ERL_NIF_TERM load_info)
{
atom_xmlelement = enif_make_atom(env, "xmlel");
atom_xmlcdata = enif_make_atom(env, "xmlcdata");
return 0;
}
static int upgrade(ErlNifEnv* env, void** priv, void** old_priv, ERL_NIF_TERM load_info)
{
return load(env, priv, load_info);
}
static struct buf *init_buf(ErlNifEnv* env)
{
struct buf *rbuf = ENIF_ALLOC(sizeof(struct buf));
rbuf->limit = 1024;
rbuf->len = 0;
rbuf->b = ENIF_ALLOC(rbuf->limit);
return rbuf;
}
static void destroy_buf(ErlNifEnv* env, struct buf *rbuf)
{
if (rbuf) {
if (rbuf->b) {
ENIF_FREE(rbuf->b);
};
ENIF_FREE(rbuf);
};
}
static void resize_buf(ErlNifEnv* env, struct buf *rbuf, int len_to_add)
{
int new_len = rbuf->len + len_to_add;
if (new_len > rbuf->limit) {
while (new_len > rbuf->limit)
rbuf->limit *= 2;
rbuf->b = ENIF_REALLOC(rbuf->b, rbuf->limit);
}
}
static void buf_add_char(ErlNifEnv* env, struct buf *rbuf, unsigned char c)
{
resize_buf(env, rbuf, 1);
(rbuf->b)[rbuf->len] = c;
rbuf->len += 1;
}
static void buf_add_str(ErlNifEnv* env, struct buf *rbuf, char *data, int len)
{
resize_buf(env, rbuf, len);
memcpy(rbuf->b + rbuf->len, data, len);
rbuf->len += len;
}
static void xml_encode(ErlNifEnv* env, struct buf *rbuf, unsigned char *data, int len)
{
int i;
for (i = 0; i < len; i++) {
switch (data[i]) {
case '&':
buf_add_str(env, rbuf, "&", 5);
break;
case '<':
buf_add_str(env, rbuf, "<", 4);
break;
case '>':
buf_add_str(env, rbuf, ">", 4);
break;
case '"':
buf_add_str(env, rbuf, """, 6);
break;
case '\'':
buf_add_str(env, rbuf, "'", 6);
break;
default:
buf_add_char(env, rbuf, data[i]);
break;
};
};
}
static void attr_encode(ErlNifEnv* env, struct buf *rbuf, unsigned char *data, int len)
{
int i;
for (i = 0; i < len; i++) {
switch (data[i]) {
case '&':
buf_add_str(env, rbuf, "&", 5);
break;
case '<':
buf_add_str(env, rbuf, "<", 4);
break;
case '"':
buf_add_str(env, rbuf, """, 6);
break;
case '\'':
buf_add_str(env, rbuf, "'", 6);
break;
case '\t':
buf_add_str(env, rbuf, " ", 5);
break;
case '\n':
buf_add_str(env, rbuf, "
", 5);
break;
case '\r':
buf_add_str(env, rbuf, "
", 5);
break;
default:
buf_add_char(env, rbuf, data[i]);
break;
};
};
}
static int make_elements(ErlNifEnv* env, struct buf *rbuf, ERL_NIF_TERM els)
{
ERL_NIF_TERM head, tail;
int ret = 0;
while (enif_get_list_cell(env, els, &head, &tail)) {
ret = make_element(env, rbuf, head, 0);
if (ret) {
els = tail;
} else {
break;
};
};
return ret;
}
static int make_attrs(ErlNifEnv* env, struct buf *rbuf, ERL_NIF_TERM attrs)
{
ErlNifBinary name, data;
ERL_NIF_TERM head, tail;
const ERL_NIF_TERM *tuple;
int arity, ret = 1;
while (enif_get_list_cell(env, attrs, &head, &tail)) {
if (enif_get_tuple(env, head, &arity, &tuple)) {
if (arity == 2) {
if (enif_inspect_iolist_as_binary(env, tuple[0], &name) &&
enif_inspect_iolist_as_binary(env, tuple[1], &data)) {
buf_add_char(env, rbuf, ' ');
buf_add_str(env, rbuf, (char *)name.data, name.size);
buf_add_str(env, rbuf, "='", 2);
attr_encode(env, rbuf, data.data, data.size);
buf_add_char(env, rbuf, '\'');
attrs = tail;
} else {
ret = 0;
break;
};
} else {
ret = 0;
break;
};
} else {
ret = 0;
break;
};
};
return ret;
}
static int make_element(ErlNifEnv* env, struct buf *rbuf, ERL_NIF_TERM el, int is_header)
{
ErlNifBinary cdata, name;
const ERL_NIF_TERM *tuple;
int arity, ret = 0;
if (enif_get_tuple(env, el, &arity, &tuple)) {
if (arity == 2 && !is_header) {
if (!ENIF_COMPARE(tuple[0], atom_xmlcdata)) {
if (enif_inspect_iolist_as_binary(env, tuple[1], &cdata)) {
xml_encode(env, rbuf, cdata.data, cdata.size);
ret = 1;
};
};
};
if (arity == 4) {
if (!ENIF_COMPARE(tuple[0], atom_xmlelement)) {
if (enif_inspect_iolist_as_binary(env, tuple[1], &name)) {
if (is_header)
buf_add_str(env, rbuf, "", 21);
buf_add_char(env, rbuf, '<');
buf_add_str(env, rbuf, (char *)name.data, name.size);
ret = make_attrs(env, rbuf, tuple[2]);
if (ret) {
if (is_header) {
buf_add_char(env, rbuf, '>');
} else if (enif_is_empty_list(env, tuple[3])) {
buf_add_str(env, rbuf, "/>", 2);
} else {
buf_add_char(env, rbuf, '>');
ret = make_elements(env, rbuf, tuple[3]);
if (ret) {
buf_add_str(env, rbuf, "", 2);
buf_add_str(env, rbuf, (char*)name.data, name.size);
buf_add_char(env, rbuf, '>');
};
};
};
};
};
};
};
return ret;
}
static ERL_NIF_TERM element_to(ErlNifEnv* env, int argc,
const ERL_NIF_TERM argv[],
int is_header)
{
ErlNifBinary output;
ERL_NIF_TERM result;
struct buf *rbuf;
if (argc == 1) {
rbuf = init_buf(env);
if (make_element(env, rbuf, argv[0], is_header)) {
if (ENIF_ALLOC_BINARY(rbuf->len, &output)) {
memcpy(output.data, rbuf->b, rbuf->len);
result = enif_make_binary(env, &output);
destroy_buf(env, rbuf);
return result;
};
};
destroy_buf(env, rbuf);
};
return enif_make_badarg(env);
}
static ERL_NIF_TERM element_to_binary(ErlNifEnv* env, int argc,
const ERL_NIF_TERM argv[])
{
return element_to(env, argc, argv, 0);
}
static ERL_NIF_TERM element_to_header(ErlNifEnv* env, int argc,
const ERL_NIF_TERM argv[])
{
return element_to(env, argc, argv, 1);
}
static ErlNifFunc nif_funcs[] =
{
{"element_to_binary", 1, element_to_binary},
{"element_to_header", 1, element_to_header}
};
ERL_NIF_INIT(fxml, nif_funcs, load, NULL, upgrade, NULL)
fast_xml-1.1.48/c_src/fxml_stream.c 0000644 0002322 0002322 00000074074 14151146420 017560 0 ustar debalance debalance /*
* Copyright (C) 2002-2021 ProcessOne, SARL. 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.
*
*/
#include
#include
#include
#include
#define PARSING_NOT_RESUMABLE XML_FALSE
#define ASSERT(x) if (!(x)) return 0
#define PARSER_ASSERT(X, E) do { if (!(X)) { state->error = (E); XML_StopParser(state->parser, PARSING_NOT_RESUMABLE); return; } } while(0)
#define PARSER_MEM_ASSERT(x) PARSER_ASSERT((x), "enomem")
typedef struct children_list_t {
union {
ERL_NIF_TERM term;
ErlNifBinary cdata;
};
struct children_list_t *next;
char is_cdata;
} children_list_t;
typedef struct attrs_list_t {
ErlNifBinary name;
ErlNifBinary value;
struct attrs_list_t *next;
} attrs_list_t;
typedef struct xmlel_stack_t {
ERL_NIF_TERM name;
ERL_NIF_TERM attrs;
children_list_t *children;
struct xmlel_stack_t *next;
char *namespace_str;
int redefined_top_prefix;
} xmlel_stack_t;
typedef struct {
ErlNifEnv *env;
ErlNifEnv *send_env;
ErlNifPid *pid;
size_t depth;
size_t size;
size_t max_size;
XML_Parser parser;
xmlel_stack_t *elements_stack;
attrs_list_t *xmlns_attrs;
attrs_list_t *top_xmlns_attrs;
const char *error;
char normalize_ns:1;
char gen_server:1;
char use_maps:1;
} state_t;
typedef enum xmlns_op {
OP_ERROR = 0,
OP_REMOVE_PREFIX,
OP_REMOVE_XMLNS,
OP_REPLACE_XMLNS,
OP_NOP
} xmlns_op;
static XML_Memory_Handling_Suite ms = {
.malloc_fcn = enif_alloc,
.realloc_fcn = enif_realloc,
.free_fcn = enif_free
};
static ErlNifResourceType *parser_state_t = NULL;
#define FAKE_BIN(STR) { sizeof(STR)-1, (unsigned char*)STR }
static attrs_list_t stream_stream_ns_attr = {
FAKE_BIN("stream:stream"),
FAKE_BIN("http://etherx.jabber.org/streams")
};
static int same_str_buf(const char *str, const char *buf, size_t buf_len)
{
if (strlen(str) != buf_len)
return 0;
if (!buf_len)
return 1;
return memcmp(str, buf, buf_len) == 0;
}
static char *dup_buf(const char *buf, size_t buf_len)
{
char *res = enif_alloc(buf_len+1);
if (!res)
return NULL;
if (buf_len)
memcpy(res, buf, buf_len);
res[buf_len] = '\0';
return res;
}
static int dup_to_bin(ErlNifBinary *bin, const char *buf, size_t buf_len)
{
if (!enif_alloc_binary(buf_len, bin))
return 0;
memcpy(bin->data, buf, buf_len);
return 1;
}
static ERL_NIF_TERM dup_to_term(ErlNifEnv *env, const char *buf, size_t buf_len)
{
ERL_NIF_TERM term;
unsigned char *str = enif_make_new_binary(env, buf_len, &term);
memcpy(str, buf, buf_len);
return term;
}
static int has_prefix_ns_from_list(attrs_list_t*list, const char *pfx, size_t pfx_len,
const char *ns, size_t ns_len)
{
while (pfx_len && list) {
if ((pfx == NULL ||
(list->name.size == pfx_len && memcmp(list->name.data, pfx, pfx_len) == 0)) &&
(ns == NULL ||
(list->value.size == ns_len && memcmp(list->value.data, ns, ns_len) == 0)))
{
return 1;
}
list = list->next;
}
return 0;
}
static int has_prefix_ns_from_top(state_t *state, const char *pfx, size_t pfx_len,
const char *ns, size_t ns_len)
{
if (state->elements_stack->redefined_top_prefix || !pfx_len)
return 0;
return has_prefix_ns_from_list(state->top_xmlns_attrs, pfx, pfx_len, ns, ns_len);
}
static xmlns_op encode_name(state_t *state, const char *xml_name, ErlNifBinary *buf,
char **ns_str, char **pfx_str, int top_element)
{
const char *parts[3];
int i, idx = 0;
for (i = 0; ; i++) {
if (!xml_name[i] || xml_name[i] == '\n') {
parts[idx++] = xml_name + i;
if (!xml_name[i])
break;
}
if (idx >= 3)
return OP_ERROR;
}
const char *ns = NULL, *name = NULL, *prefix = NULL;
size_t ns_len = 0, name_len = 0, prefix_len = 0;
if (idx == 1) {
name = xml_name;
name_len = parts[0] - xml_name;
} else {
ns = xml_name;
ns_len = parts[0] - xml_name;
name = parts[0] + 1;
name_len = parts[1] - parts[0] - 1;
if (idx == 3) {
prefix = parts[1] + 1;
prefix_len = parts[2] - parts[1] - 1;
}
}
int with_prefix = prefix_len && (top_element || !ns_str);
xmlns_op res = OP_REPLACE_XMLNS;
if (state->normalize_ns && !top_element) {
if (ns_str) {
if (!state->elements_stack->redefined_top_prefix && prefix_len &&
has_prefix_ns_from_top(state, prefix, prefix_len, ns, ns_len))
{
res = OP_REMOVE_PREFIX;
with_prefix = 1;
} else if (same_str_buf(state->elements_stack->namespace_str, ns, ns_len)) {
res = OP_REMOVE_XMLNS;
with_prefix = 0;
}
}
} else
res = OP_NOP;
if (with_prefix) {
ASSERT(enif_alloc_binary(name_len + prefix_len + 1, buf));
memcpy(buf->data, prefix, prefix_len);
buf->data[prefix_len] = ':';
memcpy(buf->data + prefix_len + 1, name, name_len);
} else {
ASSERT(dup_to_bin(buf, name, name_len));
}
if (ns_str) {
if (top_element && prefix_len > 0)
*ns_str = NULL;
else {
*ns_str = top_element ? dup_buf(ns, ns_len) :
res == OP_REMOVE_PREFIX ?
state->elements_stack->namespace_str :
dup_buf(ns, ns_len);
if (!*ns_str) {
enif_release_binary(buf);
return OP_ERROR;
}
}
if (pfx_str) {
if (res == OP_REMOVE_PREFIX) {
*pfx_str = dup_buf(prefix, prefix_len);
if (!*pfx_str) {
enif_release_binary(buf);
if (ns_str && *ns_str)
enif_free(*ns_str);
return OP_ERROR;
}
} else
*pfx_str = NULL;
}
}
return res;
}
static ERL_NIF_TERM str2bin(ErlNifEnv *env, const char *s)
{
return dup_to_term(env, s, strlen(s));
}
static void send_event(state_t *state, ERL_NIF_TERM el)
{
state->size = 0;
if (state->gen_server) {
enif_send(state->env, state->pid, state->send_env,
enif_make_tuple2(state->send_env,
enif_make_atom(state->send_env, "$gen_event"),
el));
} else {
enif_send(state->env, state->pid, state->send_env, el);
}
enif_clear_env(state->send_env);
}
static void send_all_state_event(state_t *state, ERL_NIF_TERM el)
{
state->size = 0;
if (state->gen_server) {
enif_send(state->env, state->pid, state->send_env,
enif_make_tuple2(state->send_env,
enif_make_atom(state->send_env, "$gen_all_state_event"),
el));
} else {
enif_send(state->env, state->pid, state->send_env, el);
}
enif_clear_env(state->send_env);
}
static ERL_NIF_TERM append_attr(state_t *state, ERL_NIF_TERM root, ERL_NIF_TERM name, ERL_NIF_TERM value) {
ErlNifEnv* env = state->send_env;
if (state->use_maps) {
ERL_NIF_TERM res;
enif_make_map_put(env, root, name, value, &res);
return res;
} else {
return enif_make_list_cell(env, enif_make_tuple2(env, name, value), root);
}
}
void erlXML_StartElementHandler(state_t *state,
const XML_Char *name,
const XML_Char **atts)
{
int i = 0;
ErlNifEnv* env = state->send_env;
ERL_NIF_TERM attrs_term;
ErlNifBinary name_bin;
if (state->use_maps) {
attrs_term = enif_make_new_map(env);
} else {
attrs_term = enif_make_list(env, 0);
}
if (state->error)
return;
state->depth++;
while (atts[i])
i += 2;
i -= 2;
while (i >= 0) {
ErlNifBinary attr_name;
ERL_NIF_TERM val;
unsigned char *val_str;
PARSER_MEM_ASSERT(encode_name(state, atts[i], &attr_name, NULL, NULL, 0));
size_t val_len = strlen(atts[i+1]);
val_str = enif_make_new_binary(env, val_len, &val);
PARSER_MEM_ASSERT(val_str);
memcpy(val_str, atts[i+1], val_len);
attrs_term = append_attr(state, attrs_term, enif_make_binary(env, &attr_name), val);
i -= 2;
}
char *ns = NULL, *pfx = NULL;
int redefined_top_prefix = state->depth > 1 ? state->elements_stack->redefined_top_prefix : 0;
int xmlns_op;
if (state->normalize_ns)
xmlns_op = encode_name(state, name, &name_bin, &ns, &pfx, state->depth == 1);
else
xmlns_op = encode_name(state, name, &name_bin, NULL, NULL, state->depth == 1);
PARSER_MEM_ASSERT(xmlns_op);
if (!state->normalize_ns)
xmlns_op = OP_NOP;
int non_xmpp_ns = -1;
int had_stream_stream = 0;
while (state->xmlns_attrs) {
ERL_NIF_TERM tuple = 0;
ERL_NIF_TERM tuple_name = 0, tuple_val = 0;
attrs_list_t *c = state->xmlns_attrs;
ErlNifBinary new_prefix, new_ns;
state->xmlns_attrs = c->next;
if (state->depth == 1 && state->normalize_ns && c->name.size > 6) {
if (non_xmpp_ns != 1 || !has_prefix_ns_from_list(&stream_stream_ns_attr,
(char*)c->name.data+6, c->name.size-6,
(char*)c->value.data, c->value.size))
{
if (had_stream_stream) {
PARSER_MEM_ASSERT(dup_to_bin(&new_prefix, (char*)stream_stream_ns_attr.name.data,
stream_stream_ns_attr.name.size));
PARSER_MEM_ASSERT(dup_to_bin(&new_ns, (char*)stream_stream_ns_attr.value.data,
stream_stream_ns_attr.value.size));
c->name = new_prefix;
c->value = new_ns;
c->next = state->top_xmlns_attrs;
state->top_xmlns_attrs = c;
had_stream_stream = 0;
}
non_xmpp_ns = 1;
PARSER_MEM_ASSERT(dup_to_bin(&new_prefix, (char*)c->name.data+6, c->name.size-6));
PARSER_MEM_ASSERT(dup_to_bin(&new_ns, (char*)c->value.data, c->value.size));
} else {
had_stream_stream = 1;
non_xmpp_ns = 0;
}
}
if (c->name.size == 5) { // xmlns
if (xmlns_op == OP_REMOVE_XMLNS) {
enif_release_binary(&c->name);
enif_release_binary(&c->value);
enif_free(c);
continue;
} else if (xmlns_op == OP_REPLACE_XMLNS) {
enif_release_binary(&c->value);
if (state->use_maps) {
tuple_name = enif_make_binary(env, &c->name);
tuple_val = dup_to_term(env, ns, strlen(ns));
} else {
tuple = enif_make_tuple2(env, enif_make_binary(env, &c->name),
dup_to_term(env, ns, strlen(ns)));
}
xmlns_op = OP_NOP;
}
if (!ns && state->normalize_ns)
PARSER_MEM_ASSERT(ns = dup_buf((char *) c->value.data, c->value.size));
} else if (xmlns_op == OP_REMOVE_PREFIX &&
same_str_buf(pfx, (char*)c->name.data + 6, c->name.size - 6)) {
enif_release_binary(&c->name);
enif_release_binary(&c->value);
enif_free(c);
continue;
} else if (!redefined_top_prefix && state->depth > 1 && c->name.size > 6 &&
has_prefix_ns_from_top(state, (char*)c->name.data + 6, c->name.size - 6, NULL, 0)) {
redefined_top_prefix = 1;
}
if (state->use_maps) {
if (!tuple_name) {
enif_make_map_update(env, attrs_term, enif_make_binary(env, &c->name),
enif_make_binary(env, &c->value), &attrs_term);
} else
enif_make_map_update(env, attrs_term, tuple_name, tuple_val, &attrs_term);
} else {
if (!tuple) {
tuple = enif_make_tuple2(env, enif_make_binary(env, &c->name),
enif_make_binary(env, &c->value));
}
attrs_term = enif_make_list_cell(env, tuple, attrs_term);
}
if (non_xmpp_ns && state->depth == 1 && state->normalize_ns && c->name.size > 6) {
c->name = new_prefix;
c->value = new_ns;
c->next = state->top_xmlns_attrs;
state->top_xmlns_attrs = c;
} else
enif_free(c);
}
if (!non_xmpp_ns && state->depth == 1 && state->normalize_ns) {
state->top_xmlns_attrs = &stream_stream_ns_attr;
}
if (xmlns_op == OP_REPLACE_XMLNS) {
attrs_term = append_attr(state, attrs_term, dup_to_term(env, "xmlns", 5),
dup_to_term(env, ns, strlen(ns)));
} else if (xmlns_op == OP_REMOVE_PREFIX) {
enif_free(pfx);
}
if (!ns && state->normalize_ns)
PARSER_MEM_ASSERT(ns = dup_buf("", 0));
xmlel_stack_t *xmlel = enif_alloc(sizeof(xmlel_stack_t));
PARSER_MEM_ASSERT(xmlel);
xmlel->next = state->elements_stack;
xmlel->attrs = attrs_term;
xmlel->namespace_str = ns;
xmlel->children = NULL;
xmlel->redefined_top_prefix = redefined_top_prefix;
state->elements_stack = xmlel;
if (state->pid && state->depth == 1) {
if (state->use_maps) {
ERL_NIF_TERM map = enif_make_new_map(env);
enif_make_map_put(env, map, enif_make_atom(env, "__struct__"),
enif_make_atom(env, "Elixir.FastXML.StreamStart"), &map);
enif_make_map_put(env, map, enif_make_atom(env, "name"),
enif_make_binary(env, &name_bin), &map);
enif_make_map_put(env, map, enif_make_atom(env, "attrs"),
attrs_term, &map);
send_event(state, map);
} else {
send_event(state,
enif_make_tuple3(env,
enif_make_atom(env, "xmlstreamstart"),
enif_make_binary(env, &name_bin),
attrs_term));
}
} else {
xmlel->name = enif_make_binary(env, &name_bin);
}
}
void erlXML_CharacterDataHandler(state_t *state, const XML_Char *s, int len)
{
ErlNifEnv *env = state->send_env;
if (state->error)
return;
if (state->depth == 0)
return;
if (state->pid && state->depth == 1) {
ErlNifBinary cdata;
PARSER_MEM_ASSERT(enif_alloc_binary(len, &cdata));
memcpy(cdata.data, s, len);
send_all_state_event(state,
enif_make_tuple2(env,
enif_make_atom(env, "xmlstreamcdata"),
enif_make_binary(env, &cdata)));
return;
}
children_list_t *children = state->elements_stack->children;
if (children && children->is_cdata) {
int old_size = children->cdata.size;
PARSER_MEM_ASSERT(enif_realloc_binary(&children->cdata, old_size + len));
memcpy(children->cdata.data+old_size, s, len);
} else {
children = enif_alloc(sizeof(children_list_t));
PARSER_MEM_ASSERT(children);
if (!enif_alloc_binary(len, &children->cdata)) {
enif_free(children);
PARSER_MEM_ASSERT(0);
}
children->is_cdata = 1;
memcpy(children->cdata.data, s, len);
children->next = state->elements_stack->children;
state->elements_stack->children = children;
}
return;
}
ERL_NIF_TERM
make_xmlel_children_list(state_t *state, children_list_t *list) {
ErlNifEnv *env = state->send_env;
ERL_NIF_TERM children_list = enif_make_list(env, 0);
while (list) {
if (list->is_cdata) {
ERL_NIF_TERM data;
if (state->use_maps) {
data = enif_make_binary(env, &list->cdata);
} else {
data = enif_make_tuple2(env,
enif_make_atom(env, "xmlcdata"),
enif_make_binary(env, &list->cdata));
}
children_list = enif_make_list_cell(env, data, children_list);
} else
children_list = enif_make_list_cell(env, list->term, children_list);
children_list_t *old_head = list;
list = list->next;
enif_free(old_head);
}
return children_list;
}
void erlXML_EndElementHandler(state_t *state, const XML_Char *name)
{
ErlNifEnv *env = state->send_env;
if (state->error)
return;
state->depth--;
if (state->pid && state->depth == 0) {
ErlNifBinary name_bin;
PARSER_MEM_ASSERT(encode_name(state, name, &name_bin, NULL, NULL, 0));
if (state->use_maps) {
ERL_NIF_TERM map = enif_make_new_map(env);
enif_make_map_put(env, map, enif_make_atom(env, "__struct__"),
enif_make_atom(env, "Elixir.FastXML.StreamEnd"), &map);
enif_make_map_put(env, map, enif_make_atom(env, "name"),
enif_make_binary(env, &name_bin), &map);
send_event(state, map);
} else {
send_event(state,
enif_make_tuple2(env,
enif_make_atom(env, "xmlstreamend"),
enif_make_binary(env, &name_bin)));
}
return;
}
ERL_NIF_TERM xmlel_term;
if (state->use_maps) {
xmlel_term = enif_make_new_map(env);
enif_make_map_put(env, xmlel_term, enif_make_atom(env, "__struct__"),
enif_make_atom(env, "Elixir.FastXML.El"), &xmlel_term);
enif_make_map_put(env, xmlel_term, enif_make_atom(env, "name"), state->elements_stack->name, &xmlel_term);
enif_make_map_put(env, xmlel_term, enif_make_atom(env, "attrs"), state->elements_stack->attrs, &xmlel_term);
enif_make_map_put(env, xmlel_term, enif_make_atom(env, "children"),
make_xmlel_children_list(state, state->elements_stack->children), &xmlel_term);
} else {
xmlel_term = enif_make_tuple4(env, enif_make_atom(env, "xmlel"),
state->elements_stack->name,
state->elements_stack->attrs,
make_xmlel_children_list(state, state->elements_stack->children));
}
if (!state->pid || state->depth > 1) {
children_list_t *el;
xmlel_stack_t *cur_el = state->elements_stack;
PARSER_MEM_ASSERT(el = enif_alloc(sizeof(children_list_t)));
state->elements_stack = state->elements_stack->next;
el->is_cdata = 0;
el->term = xmlel_term;
el->next = state->elements_stack->children;
state->elements_stack->children = el;
if (cur_el->namespace_str != state->elements_stack->namespace_str)
enif_free(cur_el->namespace_str);
enif_free(cur_el);
} else {
xmlel_stack_t *cur_el = state->elements_stack;
state->elements_stack = cur_el->next;
if (!state->elements_stack || cur_el->namespace_str != state->elements_stack->namespace_str)
enif_free(cur_el->namespace_str);
enif_free(cur_el);
if (state->use_maps) {
enif_make_map_put(env, xmlel_term, enif_make_atom(env, "__struct__"),
enif_make_atom(env, "Elixir.FastXML.El"), &xmlel_term);
send_event(state, xmlel_term);
} else {
send_event(state,
enif_make_tuple2(state->send_env,
enif_make_atom(state->send_env, "xmlstreamelement"),
xmlel_term));
}
}
return;
}
void erlXML_StartNamespaceDeclHandler(state_t *state,
const XML_Char *prefix,
const XML_Char *uri)
{
/* From the expat documentation:
"For a default namespace declaration (xmlns='...'),
the prefix will be null ...
... The URI will be null for the case where
the default namespace is being unset."
FIXME: I'm not quite sure what all that means */
if (uri == NULL)
return;
if (state->error)
return;
attrs_list_t *c = enif_alloc(sizeof(attrs_list_t));
PARSER_MEM_ASSERT(c);
if (prefix) {
size_t len = strlen(prefix);
if (!enif_alloc_binary(len + 6, &c->name)) {
enif_free(c);
PARSER_MEM_ASSERT(0);
}
memcpy(c->name.data, "xmlns:", 6);
memcpy(c->name.data + 6, prefix, len);
} else {
if (!enif_alloc_binary(5, &c->name)) {
enif_free(c);
PARSER_MEM_ASSERT(0);
}
memcpy(c->name.data, "xmlns", 5);
};
size_t len = strlen(uri);
if (!enif_alloc_binary(len, &c->value)) {
enif_release_binary(&c->name);
enif_free(c);
PARSER_MEM_ASSERT(0);
}
memcpy(c->value.data, uri, len);
c->next = state->xmlns_attrs;
state->xmlns_attrs = c;
return;
}
/*
* Prevent entity expansion attacks (CVE-2013-1664) by refusing
* to process any XML that contains a DTD.
*/
void erlXML_StartDoctypeDeclHandler(state_t *state,
const XML_Char *doctypeName,
const XML_Char *doctypeSysid,
const XML_Char *doctypePubid,
int hasInternalSubset)
{
XML_StopParser(state->parser, PARSING_NOT_RESUMABLE);
return;
}
/*
* Prevent entity expansion attacks (CVE-2013-1664) by having an explicit
* default handler. According to the documentation,
*
* "Setting the handler with this call has the side effect of turning off
* expansion of references to internally defined general entities. Instead
* these references are passed to the default handler."
*/
void erlXML_DefaultHandler(state_t *state, const XML_Char *s, int len)
{
return;
}
static void free_parser_allocated_structs(state_t *state) {
while (state->xmlns_attrs) {
attrs_list_t *c = state->xmlns_attrs;
state->xmlns_attrs = c->next;
enif_release_binary(&c->name);
enif_release_binary(&c->value);
enif_free(c);
}
while (state->elements_stack) {
xmlel_stack_t *c = state->elements_stack;
while (c->children) {
children_list_t *cc = c->children;
if (cc->is_cdata)
enif_release_binary(&cc->cdata);
c->children = cc->next;
enif_free(cc);
}
if (!c->next || c->namespace_str != c->next->namespace_str)
enif_free(c->namespace_str);
state->elements_stack = c->next;
enif_free(c);
}
if (state->top_xmlns_attrs != &stream_stream_ns_attr)
while (state->top_xmlns_attrs) {
attrs_list_t *c = state->top_xmlns_attrs;
state->top_xmlns_attrs = c->next;
enif_release_binary(&c->name);
enif_release_binary(&c->value);
enif_free(c);
}
}
static void destroy_parser_state(ErlNifEnv *env, void *data)
{
state_t *state = (state_t *) data;
if (state) {
if (state->parser) XML_ParserFree(state->parser);
if (state->pid) enif_free(state->pid);
if (state->send_env) enif_free_env(state->send_env);
free_parser_allocated_structs(state);
memset(state, 0, sizeof(state_t));
}
}
static void setup_parser(state_t *state)
{
XML_SetUserData(state->parser, state);
XML_SetStartElementHandler(state->parser,
(XML_StartElementHandler) erlXML_StartElementHandler);
XML_SetEndElementHandler(state->parser,
(XML_EndElementHandler) erlXML_EndElementHandler);
XML_SetCharacterDataHandler(state->parser,
(XML_CharacterDataHandler) erlXML_CharacterDataHandler);
XML_SetStartNamespaceDeclHandler(state->parser,
(XML_StartNamespaceDeclHandler)
erlXML_StartNamespaceDeclHandler);
XML_SetStartDoctypeDeclHandler(state->parser,
(XML_StartDoctypeDeclHandler)
erlXML_StartDoctypeDeclHandler);
XML_SetReturnNSTriplet(state->parser, 1);
XML_SetDefaultHandler(state->parser, (XML_DefaultHandler) erlXML_DefaultHandler);
}
static state_t *init_parser_state(ErlNifPid *pid)
{
state_t *state = enif_alloc_resource(parser_state_t, sizeof(state_t));
ASSERT(state);
memset(state, 0, sizeof(state_t));
if (pid) {
state->send_env = enif_alloc_env();
ASSERT(state->send_env);
state->pid = enif_alloc(sizeof(ErlNifPid));
ASSERT(state->pid);
memcpy(state->pid, pid, sizeof(ErlNifPid));
}
state->parser = XML_ParserCreate_MM("UTF-8", &ms, "\n");
setup_parser(state);
return state;
}
static int load(ErlNifEnv* env, void** priv, ERL_NIF_TERM load_info)
{
ErlNifResourceFlags flags = ERL_NIF_RT_CREATE | ERL_NIF_RT_TAKEOVER;
parser_state_t = enif_open_resource_type(env, NULL, "parser_state_t",
destroy_parser_state,
flags, NULL);
return 0;
}
static int upgrade(ErlNifEnv* env, void** priv, void** old_priv, ERL_NIF_TERM load_info)
{
return load(env, priv, load_info);
}
static ERL_NIF_TERM make_parse_error(ErlNifEnv *env, XML_Parser parser)
{
enum XML_Error errcode = XML_GetErrorCode(parser);
const char *errstring;
if (errcode == XML_ERROR_EXTERNAL_ENTITY_HANDLING)
errstring = "DTDs are not allowed";
else
errstring = XML_ErrorString(errcode);
return enif_make_tuple2(env, enif_make_uint(env, errcode),
str2bin(env, errstring));
}
static ERL_NIF_TERM reset_nif(ErlNifEnv* env, int argc,
const ERL_NIF_TERM argv[])
{
state_t *state = NULL;
if (argc != 1)
return enif_make_badarg(env);
if (!enif_get_resource(env, argv[0], parser_state_t, (void *) &state))
return enif_make_badarg(env);
ASSERT(XML_ParserReset(state->parser, "UTF-8"));
setup_parser(state);
free_parser_allocated_structs(state);
enif_clear_env(state->send_env);
state->size = 0;
state->depth = 0;
state->error = NULL;
return argv[0];
}
static ERL_NIF_TERM parse_element_nif(ErlNifEnv* env, int argc,
const ERL_NIF_TERM argv[])
{
ERL_NIF_TERM el;
ErlNifBinary bin;
if (argc != 1)
return enif_make_badarg(env);
if (!enif_inspect_binary(env, argv[0], &bin))
return enif_make_badarg(env);
state_t *state = init_parser_state(NULL);
if (!state)
return enif_make_badarg(env);
state->send_env = env;
xmlel_stack_t *xmlel = enif_alloc(sizeof(xmlel_stack_t));
if (!xmlel) {
enif_release_resource(state);
return enif_make_badarg(env);
}
memset(xmlel, 0, sizeof(xmlel_stack_t));
xmlel->next = state->elements_stack;
xmlel->children = NULL;
state->elements_stack = xmlel;
int res = XML_Parse(state->parser, (char *)bin.data, bin.size, 1);
if (res == XML_STATUS_OK && state->elements_stack->children &&
!state->elements_stack->children->is_cdata)
el = state->elements_stack->children->term;
else if (state->error)
el = enif_make_tuple2(env, enif_make_atom(env, "error"),
enif_make_atom(env, state->error));
else
el = enif_make_tuple2(env, enif_make_atom(env, "error"),
make_parse_error(env, state->parser));
state->send_env = NULL;
enif_release_resource(state);
return el;
}
static void send_error(state_t *state, ERL_NIF_TERM msg) {
ErlNifEnv *env = state->send_env;
if (state->use_maps) {
ERL_NIF_TERM map = enif_make_new_map(env);
enif_make_map_put(env, map, enif_make_atom(env, "__struct__"),
enif_make_atom(env, "Elixir.FastXML.StreamError"), &map);
enif_make_map_put(env, map, enif_make_atom(env, "desc"),
msg, &map);
send_event(state, map);
} else {
send_event(state,
enif_make_tuple2(env,
enif_make_atom(env, "xmlstreamerror"),
msg));
}
}
static ERL_NIF_TERM parse_nif(ErlNifEnv* env, int argc,
const ERL_NIF_TERM argv[])
{
state_t *state = NULL;
ErlNifBinary bin;
if (argc != 2)
return enif_make_badarg(env);
if (!enif_get_resource(env, argv[0], parser_state_t, (void *) &state))
return enif_make_badarg(env);
if (!enif_inspect_binary(env, argv[1], &bin))
return enif_make_badarg(env);
if (!state->parser || !state->pid || !state->send_env)
return enif_make_badarg(env);
state->size += bin.size;
state->env = env;
if (state->size >= state->max_size) {
size_t size = state->size;
send_error(state, str2bin(state->send_env, "XML stanza is too big"));
/* Don't let send_event() to set size to zero */
state->size = size;
} else {
int res = XML_Parse(state->parser, (char *)bin.data, bin.size, 0);
if (!res)
send_error(state, state->error ?
str2bin(state->send_env, state->error) :
make_parse_error(state->send_env, state->parser));
}
return argv[0];
}
static ERL_NIF_TERM change_callback_pid_nif(ErlNifEnv* env, int argc,
const ERL_NIF_TERM argv[])
{
state_t *state = NULL;
ErlNifPid pid;
if (argc != 2)
return enif_make_badarg(env);
if (!enif_get_resource(env, argv[0], parser_state_t, (void *) &state))
return enif_make_badarg(env);
if (!state->parser || !state->pid || !state->send_env)
return enif_make_badarg(env);
if (!enif_get_local_pid(env, argv[1], &pid))
return enif_make_badarg(env);
memcpy(state->pid, &pid, sizeof(ErlNifPid));
return enif_make_resource(env, state);
}
static ERL_NIF_TERM close_nif(ErlNifEnv* env, int argc,
const ERL_NIF_TERM argv[])
{
state_t *state = NULL;
if (argc != 1)
return enif_make_badarg(env);
if (!enif_get_resource(env, argv[0], parser_state_t, (void *) &state))
return enif_make_badarg(env);
if (!state->parser || !state->pid)
return enif_make_badarg(env);
destroy_parser_state(env, state);
return enif_make_atom(env, "true");
}
static ERL_NIF_TERM new_nif(ErlNifEnv* env, int argc,
const ERL_NIF_TERM argv[])
{
int gen_srv = 1;
int use_maps = 0;
if (argc != 2 && argc != 3)
return enif_make_badarg(env);
if (argc == 3) {
if (!enif_is_list(env, argv[2]))
return enif_make_badarg(env);
ERL_NIF_TERM head, tail = argv[2];
while (enif_get_list_cell(env, tail, &head, &tail)) {
char buf[16];
if (enif_get_atom(env, head, buf, sizeof(buf), ERL_NIF_LATIN1)) {
if (strcmp("no_gen_server", buf) == 0)
gen_srv = 0;
else if (strcmp("use_maps", buf) == 0)
use_maps = 1;
}
}
}
ErlNifPid pid;
if (!enif_get_local_pid(env, argv[0], &pid))
return enif_make_badarg(env);
state_t *state = init_parser_state(&pid);
if (!state)
return enif_make_badarg(env);
state->normalize_ns = 1;
state->use_maps = use_maps;
state->gen_server = gen_srv;
ERL_NIF_TERM result = enif_make_resource(env, state);
enif_release_resource(state);
ErlNifUInt64 max_size;
if (enif_get_uint64(env, argv[1], &max_size))
state->max_size = (size_t) max_size;
else if (!enif_compare(argv[1], enif_make_atom(env, "infinity")))
state->max_size = (size_t) - 1;
else
return enif_make_badarg(env);
return result;
}
static ErlNifFunc nif_funcs[] =
{
{"new", 2, new_nif},
{"new", 3, new_nif},
{"parse", 2, parse_nif},
{"parse_element", 1, parse_element_nif},
{"reset", 1, reset_nif},
{"close", 1, close_nif},
{"change_callback_pid", 2, change_callback_pid_nif}
};
ERL_NIF_INIT(fxml_stream, nif_funcs, load, NULL, upgrade, NULL)
fast_xml-1.1.48/configure.ac 0000644 0002322 0002322 00000002215 14151146420 016254 0 ustar debalance debalance # -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.
AC_PREREQ(2.53)
AC_PACKAGE_VERSION(1.1.21)
AC_INIT(fast_xml, 1.1.21, [], [])
# Checks for programs.
AC_PROG_CC
AC_PROG_MAKE_SET
if test "x$GCC" = "xyes"; then
CFLAGS="$CFLAGS -Wall"
fi
# Checks for typedefs, structures, and compiler characteristics.
AC_C_CONST
# Checks for library functions.
AC_FUNC_MALLOC
AC_HEADER_STDC
# Checks Erlang runtime and compiler
AC_ERLANG_NEED_ERL
AC_ERLANG_NEED_ERLC
# Checks and sets ERLANG_ROOT_DIR and ERLANG_LIB_DIR variable
# AC_ERLANG_SUBST_ROOT_DIR
# AC_ERLANG_SUBST_LIB_DIR
AC_CHECK_HEADERS([expat.h], [], [
AC_MSG_ERROR([libexpat header file expat.h was not found])])
AC_SEARCH_LIBS([XML_ParserCreate], [expat], [], [
AC_MSG_ERROR([libexpat library was not found])])
AC_ARG_ENABLE(gcov,
[AC_HELP_STRING([--enable-gcov], [compile with gcov enabled (default: no)])],
[case "${enableval}" in
yes) gcov=true ;;
no) gcov=false ;;
*) AC_MSG_ERROR(bad value ${enableval} for --enable-gcov) ;;
esac],[gcov=false])
AC_SUBST(gcov)
AC_CONFIG_FILES([vars.config])
AC_OUTPUT
fast_xml-1.1.48/priv/ 0000755 0002322 0002322 00000000000 14151146420 014746 5 ustar debalance debalance fast_xml-1.1.48/priv/lib/ 0000755 0002322 0002322 00000000000 14151146420 015514 5 ustar debalance debalance fast_xml-1.1.48/src/ 0000755 0002322 0002322 00000000000 14151146420 014555 5 ustar debalance debalance fast_xml-1.1.48/src/fxml_gen_pt.erl 0000644 0002322 0002322 00000003574 14151146420 017574 0 ustar debalance debalance %%%-------------------------------------------------------------------
%%% @author Evgeny Khramtsov
%%% @copyright (C) 2016-2021, Evgeny Khramtsov
%%% @doc
%%%
%%% @end
%%% Created : 27 May 2016 by Evgeny Khramtsov
%%%-------------------------------------------------------------------
-module(fxml_gen_pt).
%% API
-export([parse_transform/2]).
-include("fxml_gen.hrl").
%%%===================================================================
%%% API
%%%===================================================================
parse_transform(Forms, _Options) ->
Result = lists:map(
fun(Form) ->
try
Form2 = erl_syntax_lib:map(
fun(Node) ->
transform(Node)
end, Form),
Form3 = erl_syntax:revert(Form2),
%%io:format("~s~n", [erl_prettypr:format(Form3)]),
Form3
catch
throw:{error, Line, Error} ->
{error, {Line, erl_parse, Error}}
end
end, Forms),
Result.
%%%===================================================================
%%% Internal functions
%%%===================================================================
transform(Form) ->
case erl_syntax:type(Form) of
application ->
case erl_syntax_lib:analyze_application(Form) of
{?AST_MARK, 1} ->
[Tree] = erl_syntax:application_arguments(Form),
NewTree = erl_syntax_lib:map(
fun(Node) ->
transform_variable(Node)
end, erl_syntax:abstract(Tree)),
erl_syntax:revert(NewTree);
_ ->
Form
end;
_ ->
Form
end.
transform_variable(Form) ->
try
Term = erl_syntax:concrete(Form),
atom = erl_syntax:type(Term),
"?" ++ Var = erl_syntax:atom_name(Term),
{ok, Tokens, _} = erl_scan:string(Var ++ "."),
{ok, [NewForm]} = erl_parse:parse_exprs(Tokens),
NewForm
catch _:_ ->
Form
end.
fast_xml-1.1.48/src/fxml_sup.erl 0000644 0002322 0002322 00000004724 14151146420 017125 0 ustar debalance debalance %%%----------------------------------------------------------------------
%%% File : fxml_sup.erl
%%% Author : Evgeniy Khramtsov
%%% Purpose : XML supervisor
%%% Created : 1 May 2013 by Evgeniy Khramtsov
%%%
%%%
%%% Copyright (C) 2002-2021 ProcessOne, SARL. 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.
%%%
%%%----------------------------------------------------------------------
-module(fxml_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
-define(SERVER, ?MODULE).
%%%===================================================================
%%% API functions
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% Starts the supervisor
%%
%% @spec start_link() -> {ok, Pid} | ignore | {error, Error}
%% @end
%%--------------------------------------------------------------------
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
%%%===================================================================
%%% Supervisor callbacks
%%%===================================================================
%%--------------------------------------------------------------------
%% @private
%% @doc
%% Whenever a supervisor is started using supervisor:start_link/[2,3],
%% this function is called by the new process to find out about
%% restart strategy, maximum restart frequency and child
%% specifications.
%%
%% @spec init(Args) -> {ok, {SupFlags, [ChildSpec]}} |
%% ignore |
%% {error, Reason}
%% @end
%%--------------------------------------------------------------------
init([]) ->
{ok, {{one_for_one, 10, 1}, []}}.
%%%===================================================================
%%% Internal functions
%%%===================================================================
fast_xml-1.1.48/src/fxmlrpc_codec.erl 0000644 0002322 0002322 00000127762 14151146420 020110 0 ustar debalance debalance %% Created automatically by XML generator (fxml_gen.erl)
%% Source: fxmlrpc_codec.spec
-module(fxmlrpc_codec).
-compile(export_all).
decode(El) -> decode(El, <<>>, []).
decode(El, Opts) -> decode(El, <<>>, Opts).
decode({xmlel, Name, Attrs, _} = El, TopXMLNS, Opts) ->
XMLNS = get_attr(<<"xmlns">>, Attrs, TopXMLNS),
case get_mod(Name, XMLNS) of
undefined when XMLNS == <<>> ->
erlang:error({fxmlrpc_codec,
{missing_tag_xmlns, Name}});
undefined ->
erlang:error({fxmlrpc_codec,
{unknown_tag, Name, XMLNS}});
Mod -> Mod:do_decode(Name, XMLNS, El, Opts)
end.
encode(El) -> encode(El, <<>>).
encode({xmlel, _, _, _} = El, _) -> El;
encode({xmlcdata, _} = CData, _) -> CData;
encode(El, TopXMLNS) ->
Mod = get_mod(El), Mod:do_encode(El, TopXMLNS).
get_name(El) -> Mod = get_mod(El), Mod:do_get_name(El).
get_ns(El) -> Mod = get_mod(El), Mod:do_get_ns(El).
is_known_tag({xmlel, Name, Attrs, _}, TopXMLNS) ->
XMLNS = get_attr(<<"xmlns">>, Attrs, TopXMLNS),
get_mod(Name, XMLNS) /= undefined.
get_els(Term) -> Mod = get_mod(Term), Mod:get_els(Term).
set_els(Term, Els) ->
Mod = get_mod(Term), Mod:set_els(Term, Els).
do_decode(<<"name">>, <<"xmlrpc">>, El, Opts) ->
decode_name(<<"xmlrpc">>, Opts, El);
do_decode(<<"member">>, <<"xmlrpc">>, El, Opts) ->
decode_member(<<"xmlrpc">>, Opts, El);
do_decode(<<"struct">>, <<"xmlrpc">>, El, Opts) ->
decode_struct(<<"xmlrpc">>, Opts, El);
do_decode(<<"nil">>, <<"xmlrpc">>, El, Opts) ->
decode_nil(<<"xmlrpc">>, Opts, El);
do_decode(<<"data">>, <<"xmlrpc">>, El, Opts) ->
decode_data(<<"xmlrpc">>, Opts, El);
do_decode(<<"array">>, <<"xmlrpc">>, El, Opts) ->
decode_array(<<"xmlrpc">>, Opts, El);
do_decode(<<"boolean">>, <<"xmlrpc">>, El, Opts) ->
decode_boolean(<<"xmlrpc">>, Opts, El);
do_decode(<<"dateTime.iso8601">>, <<"xmlrpc">>, El,
Opts) ->
decode_dateTime(<<"xmlrpc">>, Opts, El);
do_decode(<<"base64">>, <<"xmlrpc">>, El, Opts) ->
decode_base64(<<"xmlrpc">>, Opts, El);
do_decode(<<"double">>, <<"xmlrpc">>, El, Opts) ->
decode_double(<<"xmlrpc">>, Opts, El);
do_decode(<<"string">>, <<"xmlrpc">>, El, Opts) ->
decode_string(<<"xmlrpc">>, Opts, El);
do_decode(<<"int">>, <<"xmlrpc">>, El, Opts) ->
decode_int(<<"xmlrpc">>, Opts, El);
do_decode(<<"i4">>, <<"xmlrpc">>, El, Opts) ->
decode_i4(<<"xmlrpc">>, Opts, El);
do_decode(<<"value">>, <<"xmlrpc">>, El, Opts) ->
decode_value(<<"xmlrpc">>, Opts, El);
do_decode(<<"param">>, <<"xmlrpc">>, El, Opts) ->
decode_param(<<"xmlrpc">>, Opts, El);
do_decode(<<"params">>, <<"xmlrpc">>, El, Opts) ->
decode_params(<<"xmlrpc">>, Opts, El);
do_decode(<<"methodName">>, <<"xmlrpc">>, El, Opts) ->
decode_methodName(<<"xmlrpc">>, Opts, El);
do_decode(<<"fault">>, <<"xmlrpc">>, El, Opts) ->
decode_fault(<<"xmlrpc">>, Opts, El);
do_decode(<<"methodResponse">>, <<"xmlrpc">>, El,
Opts) ->
decode_methodResponse(<<"xmlrpc">>, Opts, El);
do_decode(<<"methodCall">>, <<"xmlrpc">>, El, Opts) ->
decode_methodCall(<<"xmlrpc">>, Opts, El);
do_decode(Name, <<>>, _, _) ->
erlang:error({fxmlrpc_codec,
{missing_tag_xmlns, Name}});
do_decode(Name, XMLNS, _, _) ->
erlang:error({fxmlrpc_codec,
{unknown_tag, Name, XMLNS}}).
tags() ->
[{<<"name">>, <<"xmlrpc">>},
{<<"member">>, <<"xmlrpc">>},
{<<"struct">>, <<"xmlrpc">>}, {<<"nil">>, <<"xmlrpc">>},
{<<"data">>, <<"xmlrpc">>}, {<<"array">>, <<"xmlrpc">>},
{<<"boolean">>, <<"xmlrpc">>},
{<<"dateTime.iso8601">>, <<"xmlrpc">>},
{<<"base64">>, <<"xmlrpc">>},
{<<"double">>, <<"xmlrpc">>},
{<<"string">>, <<"xmlrpc">>}, {<<"int">>, <<"xmlrpc">>},
{<<"i4">>, <<"xmlrpc">>}, {<<"value">>, <<"xmlrpc">>},
{<<"param">>, <<"xmlrpc">>},
{<<"params">>, <<"xmlrpc">>},
{<<"methodName">>, <<"xmlrpc">>},
{<<"fault">>, <<"xmlrpc">>},
{<<"methodResponse">>, <<"xmlrpc">>},
{<<"methodCall">>, <<"xmlrpc">>}].
do_encode({call, _, _} = Methodcall, TopXMLNS) ->
encode_methodCall(Methodcall, TopXMLNS);
do_encode({response, _} = Methodresponse, TopXMLNS) ->
encode_methodResponse(Methodresponse, TopXMLNS);
do_encode({fault, _} = Fault, TopXMLNS) ->
encode_fault(Fault, TopXMLNS);
do_encode({i4, _} = I4, TopXMLNS) ->
encode_i4(I4, TopXMLNS);
do_encode({int, _} = Int, TopXMLNS) ->
encode_int(Int, TopXMLNS);
do_encode({string, _} = String, TopXMLNS) ->
encode_string(String, TopXMLNS);
do_encode({double, _} = Double, TopXMLNS) ->
encode_double(Double, TopXMLNS);
do_encode({base64, _} = Base64, TopXMLNS) ->
encode_base64(Base64, TopXMLNS);
do_encode({date, _} = Datetime_iso8601, TopXMLNS) ->
encode_dateTime(Datetime_iso8601, TopXMLNS);
do_encode({boolean, _} = Boolean, TopXMLNS) ->
encode_boolean(Boolean, TopXMLNS);
do_encode({array, _} = Array, TopXMLNS) ->
encode_array(Array, TopXMLNS);
do_encode({struct, _} = Struct, TopXMLNS) ->
encode_struct(Struct, TopXMLNS).
do_get_name({array, _}) -> <<"array">>;
do_get_name({base64, _}) -> <<"base64">>;
do_get_name({boolean, _}) -> <<"boolean">>;
do_get_name({call, _, _}) -> <<"methodCall">>;
do_get_name({date, _}) -> <<"dateTime.iso8601">>;
do_get_name({double, _}) -> <<"double">>;
do_get_name({fault, _}) -> <<"fault">>;
do_get_name({i4, _}) -> <<"i4">>;
do_get_name({int, _}) -> <<"int">>;
do_get_name({response, _}) -> <<"methodResponse">>;
do_get_name({string, _}) -> <<"string">>;
do_get_name({struct, _}) -> <<"struct">>.
do_get_ns({array, _}) -> <<"xmlrpc">>;
do_get_ns({base64, _}) -> <<"xmlrpc">>;
do_get_ns({boolean, _}) -> <<"xmlrpc">>;
do_get_ns({call, _, _}) -> <<"xmlrpc">>;
do_get_ns({date, _}) -> <<"xmlrpc">>;
do_get_ns({double, _}) -> <<"xmlrpc">>;
do_get_ns({fault, _}) -> <<"xmlrpc">>;
do_get_ns({i4, _}) -> <<"xmlrpc">>;
do_get_ns({int, _}) -> <<"xmlrpc">>;
do_get_ns({response, _}) -> <<"xmlrpc">>;
do_get_ns({string, _}) -> <<"xmlrpc">>;
do_get_ns({struct, _}) -> <<"xmlrpc">>.
register_module(Mod) ->
register_module(Mod, fxmlrpc_codec_external).
unregister_module(Mod) ->
unregister_module(Mod, fxmlrpc_codec_external).
format_error({bad_attr_value, Attr, Tag, XMLNS}) ->
<<"Bad value of attribute '", Attr/binary, "' in tag <",
Tag/binary, "/> qualified by namespace '", XMLNS/binary,
"'">>;
format_error({bad_cdata_value, <<>>, Tag, XMLNS}) ->
<<"Bad value of cdata in tag <", Tag/binary,
"/> qualified by namespace '", XMLNS/binary, "'">>;
format_error({missing_tag, Tag, XMLNS}) ->
<<"Missing tag <", Tag/binary,
"/> qualified by namespace '", XMLNS/binary, "'">>;
format_error({missing_attr, Attr, Tag, XMLNS}) ->
<<"Missing attribute '", Attr/binary, "' in tag <",
Tag/binary, "/> qualified by namespace '", XMLNS/binary,
"'">>;
format_error({missing_cdata, <<>>, Tag, XMLNS}) ->
<<"Missing cdata in tag <", Tag/binary,
"/> qualified by namespace '", XMLNS/binary, "'">>;
format_error({unknown_tag, Tag, XMLNS}) ->
<<"Unknown tag <", Tag/binary,
"/> qualified by namespace '", XMLNS/binary, "'">>;
format_error({missing_tag_xmlns, Tag}) ->
<<"Missing namespace for tag <", Tag/binary, "/>">>.
io_format_error({bad_attr_value, Attr, Tag, XMLNS}) ->
{<<"Bad value of attribute '~s' in tag <~s/> "
"qualified by namespace '~s'">>,
[Attr, Tag, XMLNS]};
io_format_error({bad_cdata_value, <<>>, Tag, XMLNS}) ->
{<<"Bad value of cdata in tag <~s/> qualified "
"by namespace '~s'">>,
[Tag, XMLNS]};
io_format_error({missing_tag, Tag, XMLNS}) ->
{<<"Missing tag <~s/> qualified by namespace "
"'~s'">>,
[Tag, XMLNS]};
io_format_error({missing_attr, Attr, Tag, XMLNS}) ->
{<<"Missing attribute '~s' in tag <~s/> "
"qualified by namespace '~s'">>,
[Attr, Tag, XMLNS]};
io_format_error({missing_cdata, <<>>, Tag, XMLNS}) ->
{<<"Missing cdata in tag <~s/> qualified "
"by namespace '~s'">>,
[Tag, XMLNS]};
io_format_error({unknown_tag, Tag, XMLNS}) ->
{<<"Unknown tag <~s/> qualified by namespace "
"'~s'">>,
[Tag, XMLNS]};
io_format_error({missing_tag_xmlns, Tag}) ->
{<<"Missing namespace for tag <~s/>">>, [Tag]}.
get_attr(Attr, Attrs, Default) ->
case lists:keyfind(Attr, 1, Attrs) of
{_, Val} -> Val;
false -> Default
end.
enc_xmlns_attrs(XMLNS, XMLNS) -> [];
enc_xmlns_attrs(XMLNS, _) -> [{<<"xmlns">>, XMLNS}].
choose_top_xmlns(<<>>, NSList, TopXMLNS) ->
case lists:member(TopXMLNS, NSList) of
true -> TopXMLNS;
false -> hd(NSList)
end;
choose_top_xmlns(XMLNS, _, _) -> XMLNS.
register_module(Mod, ResolverMod) ->
MD5Sum = try Mod:module_info(md5) of
Val -> Val
catch
error:badarg ->
{ok, {Mod, Val}} = beam_lib:md5(code:which(Mod)), Val
end,
case orddict:find(Mod, ResolverMod:modules()) of
{ok, MD5Sum} -> ok;
_ ->
Mods = orddict:store(Mod, MD5Sum,
ResolverMod:modules()),
recompile_resolver(Mods, ResolverMod)
end.
unregister_module(Mod, ResolverMod) ->
case orddict:find(Mod, ResolverMod:modules()) of
{ok, _} ->
Mods = orddict:erase(Mod, ResolverMod:modules()),
recompile_resolver(Mods, ResolverMod);
error -> ok
end.
recompile_resolver(Mods, ResolverMod) ->
Tags = lists:flatmap(fun (M) ->
[{Name, XMLNS, M} || {Name, XMLNS} <- M:tags()]
end,
orddict:fetch_keys(Mods)),
Records = lists:flatmap(fun (M) ->
[{RecName, RecSize, M}
|| {RecName, RecSize} <- M:records()]
end,
orddict:fetch_keys(Mods)),
Lookup1 = string:join(lists:map(fun ({RecName, RecSize,
M}) ->
io_lib:format("lookup({~s}) -> '~s'",
[string:join([io_lib:format("'~s'",
[RecName])
| ["_"
|| _
<- lists:seq(1,
RecSize)]],
","),
M])
end,
Records)
++
["lookup(Term) -> erlang:error(badarg, "
"[Term])."],
";" ++ io_lib:nl()),
Lookup2 = string:join(lists:map(fun ({Name, XMLNS,
M}) ->
io_lib:format("lookup(~w, ~w) -> '~s'",
[Name, XMLNS, M])
end,
Tags)
++ ["lookup(_, _) -> undefined."],
";" ++ io_lib:nl()),
Modules = io_lib:format("modules() -> [~s].",
[string:join([io_lib:format("{'~s', ~w}", [M, S])
|| {M, S} <- Mods],
",")]),
Module = io_lib:format("-module(~s).", [ResolverMod]),
Compile = "-compile(export_all).",
Forms = lists:map(fun (Expr) ->
{ok, Tokens, _} =
erl_scan:string(lists:flatten(Expr)),
{ok, Form} = erl_parse:parse_form(Tokens),
Form
end,
[Module, Compile, Modules, Lookup1, Lookup2]),
{ok, Code} = case compile:forms(Forms, []) of
{ok, ResolverMod, Bin} -> {ok, Bin};
{ok, ResolverMod, Bin, _Warnings} -> {ok, Bin};
Error -> Error
end,
{module, ResolverMod} = code:load_binary(ResolverMod,
"nofile", Code),
ok.
dec_bool(<<"false">>) -> false;
dec_bool(<<"0">>) -> false;
dec_bool(<<"true">>) -> true;
dec_bool(<<"1">>) -> true.
enc_bool(false) -> <<"0">>;
enc_bool(true) -> <<"1">>.
pp(call, 2) -> [name, params];
pp(response, 1) -> [payload];
pp(fault, 1) -> [value];
pp(i4, 1) -> [cdata];
pp(int, 1) -> [cdata];
pp(string, 1) -> [cdata];
pp(double, 1) -> [cdata];
pp(base64, 1) -> [cdata];
pp(date, 1) -> [cdata];
pp(boolean, 1) -> [cdata];
pp(array, 1) -> [data];
pp(struct, 1) -> [members];
pp(xmlel, 3) -> [name, attrs, children];
pp(Name, Arity) ->
try get_mod(erlang:make_tuple(Arity + 1, undefined,
[{1, Name}]))
of
Mod -> Mod:pp(Name, Arity)
catch
error:badarg -> no
end.
records() ->
[{call, 2}, {response, 1}, {fault, 1}, {i4, 1},
{int, 1}, {string, 1}, {double, 1}, {base64, 1},
{date, 1}, {boolean, 1}, {array, 1}, {struct, 1}].
get_mod(<<"int">>, <<"xmlrpc">>) -> fxmlrpc_codec;
get_mod(<<"array">>, <<"xmlrpc">>) -> fxmlrpc_codec;
get_mod(<<"dateTime.iso8601">>, <<"xmlrpc">>) ->
fxmlrpc_codec;
get_mod(<<"methodResponse">>, <<"xmlrpc">>) ->
fxmlrpc_codec;
get_mod(<<"nil">>, <<"xmlrpc">>) -> fxmlrpc_codec;
get_mod(<<"value">>, <<"xmlrpc">>) -> fxmlrpc_codec;
get_mod(<<"methodCall">>, <<"xmlrpc">>) ->
fxmlrpc_codec;
get_mod(<<"string">>, <<"xmlrpc">>) -> fxmlrpc_codec;
get_mod(<<"boolean">>, <<"xmlrpc">>) -> fxmlrpc_codec;
get_mod(<<"name">>, <<"xmlrpc">>) -> fxmlrpc_codec;
get_mod(<<"param">>, <<"xmlrpc">>) -> fxmlrpc_codec;
get_mod(<<"data">>, <<"xmlrpc">>) -> fxmlrpc_codec;
get_mod(<<"i4">>, <<"xmlrpc">>) -> fxmlrpc_codec;
get_mod(<<"base64">>, <<"xmlrpc">>) -> fxmlrpc_codec;
get_mod(<<"member">>, <<"xmlrpc">>) -> fxmlrpc_codec;
get_mod(<<"fault">>, <<"xmlrpc">>) -> fxmlrpc_codec;
get_mod(<<"methodName">>, <<"xmlrpc">>) ->
fxmlrpc_codec;
get_mod(<<"params">>, <<"xmlrpc">>) -> fxmlrpc_codec;
get_mod(<<"double">>, <<"xmlrpc">>) -> fxmlrpc_codec;
get_mod(<<"struct">>, <<"xmlrpc">>) -> fxmlrpc_codec;
get_mod(Name, XMLNS) ->
fxmlrpc_codec_external:lookup(Name, XMLNS).
get_mod({boolean, _}) -> fxmlrpc_codec;
get_mod({fault, _}) -> fxmlrpc_codec;
get_mod({i4, _}) -> fxmlrpc_codec;
get_mod({int, _}) -> fxmlrpc_codec;
get_mod({base64, _}) -> fxmlrpc_codec;
get_mod({struct, _}) -> fxmlrpc_codec;
get_mod({call, _, _}) -> fxmlrpc_codec;
get_mod({response, _}) -> fxmlrpc_codec;
get_mod({double, _}) -> fxmlrpc_codec;
get_mod({date, _}) -> fxmlrpc_codec;
get_mod({string, _}) -> fxmlrpc_codec;
get_mod({array, _}) -> fxmlrpc_codec;
get_mod(Record) ->
fxmlrpc_codec_external:lookup(Record).
decode_name(__TopXMLNS, __Opts,
{xmlel, <<"name">>, _attrs, _els}) ->
Cdata = decode_name_els(__TopXMLNS, __Opts, _els, <<>>),
Cdata.
decode_name_els(__TopXMLNS, __Opts, [], Cdata) ->
decode_name_cdata(__TopXMLNS, Cdata);
decode_name_els(__TopXMLNS, __Opts,
[{xmlcdata, _data} | _els], Cdata) ->
decode_name_els(__TopXMLNS, __Opts, _els,
<>);
decode_name_els(__TopXMLNS, __Opts, [_ | _els],
Cdata) ->
decode_name_els(__TopXMLNS, __Opts, _els, Cdata).
encode_name(Cdata, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = encode_name_cdata(Cdata, []),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"name">>, _attrs, _els}.
decode_name_cdata(__TopXMLNS, <<>>) ->
erlang:error({fxmlrpc_codec,
{missing_cdata, <<>>, <<"name">>, __TopXMLNS}});
decode_name_cdata(__TopXMLNS, _val) ->
case catch erlang:binary_to_atom(_val, utf8) of
{'EXIT', _} ->
erlang:error({fxmlrpc_codec,
{bad_cdata_value, <<>>, <<"name">>, __TopXMLNS}});
_res -> _res
end.
encode_name_cdata(_val, _acc) ->
[{xmlcdata, erlang:atom_to_binary(_val, utf8)} | _acc].
decode_member(__TopXMLNS, __Opts,
{xmlel, <<"member">>, _attrs, _els}) ->
{Value, Name} = decode_member_els(__TopXMLNS, __Opts,
_els, error, error),
{Name, Value}.
decode_member_els(__TopXMLNS, __Opts, [], Value,
Name) ->
{case Value of
error ->
erlang:error({fxmlrpc_codec,
{missing_tag, <<"value">>, __TopXMLNS}});
{value, Value1} -> Value1
end,
case Name of
error ->
erlang:error({fxmlrpc_codec,
{missing_tag, <<"name">>, __TopXMLNS}});
{value, Name1} -> Name1
end};
decode_member_els(__TopXMLNS, __Opts,
[{xmlel, <<"name">>, _attrs, _} = _el | _els], Value,
Name) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_member_els(__TopXMLNS, __Opts, _els, Value,
{value, decode_name(<<"xmlrpc">>, __Opts, _el)});
_ ->
decode_member_els(__TopXMLNS, __Opts, _els, Value, Name)
end;
decode_member_els(__TopXMLNS, __Opts,
[{xmlel, <<"value">>, _attrs, _} = _el | _els], Value,
Name) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_member_els(__TopXMLNS, __Opts, _els,
{value, decode_value(<<"xmlrpc">>, __Opts, _el)},
Name);
_ ->
decode_member_els(__TopXMLNS, __Opts, _els, Value, Name)
end;
decode_member_els(__TopXMLNS, __Opts, [_ | _els], Value,
Name) ->
decode_member_els(__TopXMLNS, __Opts, _els, Value,
Name).
encode_member({Name, Value}, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = lists:reverse('encode_member_$value'(Value,
__NewTopXMLNS,
'encode_member_$name'(Name,
__NewTopXMLNS,
[]))),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"member">>, _attrs, _els}.
'encode_member_$value'(Value, __TopXMLNS, _acc) ->
[encode_value(Value, __TopXMLNS) | _acc].
'encode_member_$name'(Name, __TopXMLNS, _acc) ->
[encode_name(Name, __TopXMLNS) | _acc].
decode_struct(__TopXMLNS, __Opts,
{xmlel, <<"struct">>, _attrs, _els}) ->
Members = decode_struct_els(__TopXMLNS, __Opts, _els,
[]),
{struct, Members}.
decode_struct_els(__TopXMLNS, __Opts, [], Members) ->
lists:reverse(Members);
decode_struct_els(__TopXMLNS, __Opts,
[{xmlel, <<"member">>, _attrs, _} = _el | _els],
Members) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_struct_els(__TopXMLNS, __Opts, _els,
[decode_member(<<"xmlrpc">>, __Opts, _el)
| Members]);
_ ->
decode_struct_els(__TopXMLNS, __Opts, _els, Members)
end;
decode_struct_els(__TopXMLNS, __Opts, [_ | _els],
Members) ->
decode_struct_els(__TopXMLNS, __Opts, _els, Members).
encode_struct({struct, Members}, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = lists:reverse('encode_struct_$members'(Members,
__NewTopXMLNS, [])),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"struct">>, _attrs, _els}.
'encode_struct_$members'([], __TopXMLNS, _acc) -> _acc;
'encode_struct_$members'([Members | _els], __TopXMLNS,
_acc) ->
'encode_struct_$members'(_els, __TopXMLNS,
[encode_member(Members, __TopXMLNS) | _acc]).
decode_nil(__TopXMLNS, __Opts,
{xmlel, <<"nil">>, _attrs, _els}) ->
nil.
encode_nil(nil, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = [],
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"nil">>, _attrs, _els}.
decode_data(__TopXMLNS, __Opts,
{xmlel, <<"data">>, _attrs, _els}) ->
V = decode_data_els(__TopXMLNS, __Opts, _els, []), V.
decode_data_els(__TopXMLNS, __Opts, [], V) ->
lists:reverse(V);
decode_data_els(__TopXMLNS, __Opts,
[{xmlel, <<"value">>, _attrs, _} = _el | _els], V) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_data_els(__TopXMLNS, __Opts, _els,
[decode_value(<<"xmlrpc">>, __Opts, _el) | V]);
_ -> decode_data_els(__TopXMLNS, __Opts, _els, V)
end;
decode_data_els(__TopXMLNS, __Opts, [_ | _els], V) ->
decode_data_els(__TopXMLNS, __Opts, _els, V).
encode_data(V, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = lists:reverse('encode_data_$v'(V, __NewTopXMLNS,
[])),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"data">>, _attrs, _els}.
'encode_data_$v'([], __TopXMLNS, _acc) -> _acc;
'encode_data_$v'([V | _els], __TopXMLNS, _acc) ->
'encode_data_$v'(_els, __TopXMLNS,
[encode_value(V, __TopXMLNS) | _acc]).
decode_array(__TopXMLNS, __Opts,
{xmlel, <<"array">>, _attrs, _els}) ->
Data = decode_array_els(__TopXMLNS, __Opts, _els,
error),
{array, Data}.
decode_array_els(__TopXMLNS, __Opts, [], Data) ->
case Data of
error ->
erlang:error({fxmlrpc_codec,
{missing_tag, <<"data">>, __TopXMLNS}});
{value, Data1} -> Data1
end;
decode_array_els(__TopXMLNS, __Opts,
[{xmlel, <<"data">>, _attrs, _} = _el | _els], Data) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_array_els(__TopXMLNS, __Opts, _els,
{value, decode_data(<<"xmlrpc">>, __Opts, _el)});
_ -> decode_array_els(__TopXMLNS, __Opts, _els, Data)
end;
decode_array_els(__TopXMLNS, __Opts, [_ | _els],
Data) ->
decode_array_els(__TopXMLNS, __Opts, _els, Data).
encode_array({array, Data}, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = lists:reverse('encode_array_$data'(Data,
__NewTopXMLNS, [])),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"array">>, _attrs, _els}.
'encode_array_$data'(Data, __TopXMLNS, _acc) ->
[encode_data(Data, __TopXMLNS) | _acc].
decode_boolean(__TopXMLNS, __Opts,
{xmlel, <<"boolean">>, _attrs, _els}) ->
Cdata = decode_boolean_els(__TopXMLNS, __Opts, _els,
<<>>),
{boolean, Cdata}.
decode_boolean_els(__TopXMLNS, __Opts, [], Cdata) ->
decode_boolean_cdata(__TopXMLNS, Cdata);
decode_boolean_els(__TopXMLNS, __Opts,
[{xmlcdata, _data} | _els], Cdata) ->
decode_boolean_els(__TopXMLNS, __Opts, _els,
<>);
decode_boolean_els(__TopXMLNS, __Opts, [_ | _els],
Cdata) ->
decode_boolean_els(__TopXMLNS, __Opts, _els, Cdata).
encode_boolean({boolean, Cdata}, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = encode_boolean_cdata(Cdata, []),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"boolean">>, _attrs, _els}.
decode_boolean_cdata(__TopXMLNS, <<>>) ->
erlang:error({fxmlrpc_codec,
{missing_cdata, <<>>, <<"boolean">>, __TopXMLNS}});
decode_boolean_cdata(__TopXMLNS, _val) ->
case catch dec_bool(_val) of
{'EXIT', _} ->
erlang:error({fxmlrpc_codec,
{bad_cdata_value, <<>>, <<"boolean">>, __TopXMLNS}});
_res -> _res
end.
encode_boolean_cdata(_val, _acc) ->
[{xmlcdata, enc_bool(_val)} | _acc].
decode_dateTime(__TopXMLNS, __Opts,
{xmlel, <<"dateTime.iso8601">>, _attrs, _els}) ->
Cdata = decode_dateTime_els(__TopXMLNS, __Opts, _els,
<<>>),
{date, Cdata}.
decode_dateTime_els(__TopXMLNS, __Opts, [], Cdata) ->
decode_dateTime_cdata(__TopXMLNS, Cdata);
decode_dateTime_els(__TopXMLNS, __Opts,
[{xmlcdata, _data} | _els], Cdata) ->
decode_dateTime_els(__TopXMLNS, __Opts, _els,
<>);
decode_dateTime_els(__TopXMLNS, __Opts, [_ | _els],
Cdata) ->
decode_dateTime_els(__TopXMLNS, __Opts, _els, Cdata).
encode_dateTime({date, Cdata}, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = encode_dateTime_cdata(Cdata, []),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"dateTime.iso8601">>, _attrs, _els}.
decode_dateTime_cdata(__TopXMLNS, <<>>) ->
erlang:error({fxmlrpc_codec,
{missing_cdata, <<>>, <<"dateTime.iso8601">>,
__TopXMLNS}});
decode_dateTime_cdata(__TopXMLNS, _val) -> _val.
encode_dateTime_cdata(_val, _acc) ->
[{xmlcdata, _val} | _acc].
decode_base64(__TopXMLNS, __Opts,
{xmlel, <<"base64">>, _attrs, _els}) ->
Cdata = decode_base64_els(__TopXMLNS, __Opts, _els,
<<>>),
{base64, Cdata}.
decode_base64_els(__TopXMLNS, __Opts, [], Cdata) ->
decode_base64_cdata(__TopXMLNS, Cdata);
decode_base64_els(__TopXMLNS, __Opts,
[{xmlcdata, _data} | _els], Cdata) ->
decode_base64_els(__TopXMLNS, __Opts, _els,
<>);
decode_base64_els(__TopXMLNS, __Opts, [_ | _els],
Cdata) ->
decode_base64_els(__TopXMLNS, __Opts, _els, Cdata).
encode_base64({base64, Cdata}, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = encode_base64_cdata(Cdata, []),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"base64">>, _attrs, _els}.
decode_base64_cdata(__TopXMLNS, <<>>) ->
erlang:error({fxmlrpc_codec,
{missing_cdata, <<>>, <<"base64">>, __TopXMLNS}});
decode_base64_cdata(__TopXMLNS, _val) -> _val.
encode_base64_cdata(_val, _acc) ->
[{xmlcdata, _val} | _acc].
decode_double(__TopXMLNS, __Opts,
{xmlel, <<"double">>, _attrs, _els}) ->
Cdata = decode_double_els(__TopXMLNS, __Opts, _els,
<<>>),
{double, Cdata}.
decode_double_els(__TopXMLNS, __Opts, [], Cdata) ->
decode_double_cdata(__TopXMLNS, Cdata);
decode_double_els(__TopXMLNS, __Opts,
[{xmlcdata, _data} | _els], Cdata) ->
decode_double_els(__TopXMLNS, __Opts, _els,
<>);
decode_double_els(__TopXMLNS, __Opts, [_ | _els],
Cdata) ->
decode_double_els(__TopXMLNS, __Opts, _els, Cdata).
encode_double({double, Cdata}, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = encode_double_cdata(Cdata, []),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"double">>, _attrs, _els}.
decode_double_cdata(__TopXMLNS, <<>>) ->
erlang:error({fxmlrpc_codec,
{missing_cdata, <<>>, <<"double">>, __TopXMLNS}});
decode_double_cdata(__TopXMLNS, _val) ->
case catch erlang:binary_to_float(_val) of
{'EXIT', _} ->
erlang:error({fxmlrpc_codec,
{bad_cdata_value, <<>>, <<"double">>, __TopXMLNS}});
_res -> _res
end.
encode_double_cdata(_val, _acc) ->
[{xmlcdata, erlang:float_to_binary(_val)} | _acc].
decode_string(__TopXMLNS, __Opts,
{xmlel, <<"string">>, _attrs, _els}) ->
Cdata = decode_string_els(__TopXMLNS, __Opts, _els,
<<>>),
{string, Cdata}.
decode_string_els(__TopXMLNS, __Opts, [], Cdata) ->
decode_string_cdata(__TopXMLNS, Cdata);
decode_string_els(__TopXMLNS, __Opts,
[{xmlcdata, _data} | _els], Cdata) ->
decode_string_els(__TopXMLNS, __Opts, _els,
<>);
decode_string_els(__TopXMLNS, __Opts, [_ | _els],
Cdata) ->
decode_string_els(__TopXMLNS, __Opts, _els, Cdata).
encode_string({string, Cdata}, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = encode_string_cdata(Cdata, []),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"string">>, _attrs, _els}.
decode_string_cdata(__TopXMLNS, <<>>) -> <<>>;
decode_string_cdata(__TopXMLNS, _val) -> _val.
encode_string_cdata(<<>>, _acc) -> _acc;
encode_string_cdata(_val, _acc) ->
[{xmlcdata, _val} | _acc].
decode_int(__TopXMLNS, __Opts,
{xmlel, <<"int">>, _attrs, _els}) ->
Cdata = decode_int_els(__TopXMLNS, __Opts, _els, <<>>),
{int, Cdata}.
decode_int_els(__TopXMLNS, __Opts, [], Cdata) ->
decode_int_cdata(__TopXMLNS, Cdata);
decode_int_els(__TopXMLNS, __Opts,
[{xmlcdata, _data} | _els], Cdata) ->
decode_int_els(__TopXMLNS, __Opts, _els,
<>);
decode_int_els(__TopXMLNS, __Opts, [_ | _els], Cdata) ->
decode_int_els(__TopXMLNS, __Opts, _els, Cdata).
encode_int({int, Cdata}, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = encode_int_cdata(Cdata, []),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"int">>, _attrs, _els}.
decode_int_cdata(__TopXMLNS, <<>>) ->
erlang:error({fxmlrpc_codec,
{missing_cdata, <<>>, <<"int">>, __TopXMLNS}});
decode_int_cdata(__TopXMLNS, _val) ->
case catch erlang:binary_to_integer(_val) of
{'EXIT', _} ->
erlang:error({fxmlrpc_codec,
{bad_cdata_value, <<>>, <<"int">>, __TopXMLNS}});
_res -> _res
end.
encode_int_cdata(_val, _acc) ->
[{xmlcdata, erlang:integer_to_binary(_val)} | _acc].
decode_i4(__TopXMLNS, __Opts,
{xmlel, <<"i4">>, _attrs, _els}) ->
Cdata = decode_i4_els(__TopXMLNS, __Opts, _els, <<>>),
{i4, Cdata}.
decode_i4_els(__TopXMLNS, __Opts, [], Cdata) ->
decode_i4_cdata(__TopXMLNS, Cdata);
decode_i4_els(__TopXMLNS, __Opts,
[{xmlcdata, _data} | _els], Cdata) ->
decode_i4_els(__TopXMLNS, __Opts, _els,
<>);
decode_i4_els(__TopXMLNS, __Opts, [_ | _els], Cdata) ->
decode_i4_els(__TopXMLNS, __Opts, _els, Cdata).
encode_i4({i4, Cdata}, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = encode_i4_cdata(Cdata, []),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"i4">>, _attrs, _els}.
decode_i4_cdata(__TopXMLNS, <<>>) ->
erlang:error({fxmlrpc_codec,
{missing_cdata, <<>>, <<"i4">>, __TopXMLNS}});
decode_i4_cdata(__TopXMLNS, _val) ->
case catch erlang:binary_to_integer(_val) of
{'EXIT', _} ->
erlang:error({fxmlrpc_codec,
{bad_cdata_value, <<>>, <<"i4">>, __TopXMLNS}});
_res -> _res
end.
encode_i4_cdata(_val, _acc) ->
[{xmlcdata, erlang:integer_to_binary(_val)} | _acc].
decode_value(__TopXMLNS, __Opts,
{xmlel, <<"value">>, _attrs, _els}) ->
{Cdata, Val} = decode_value_els(__TopXMLNS, __Opts,
_els, <<>>, undefined),
{Val, Cdata}.
decode_value_els(__TopXMLNS, __Opts, [], Cdata, Val) ->
{decode_value_cdata(__TopXMLNS, Cdata), Val};
decode_value_els(__TopXMLNS, __Opts,
[{xmlcdata, _data} | _els], Cdata, Val) ->
decode_value_els(__TopXMLNS, __Opts, _els,
<>, Val);
decode_value_els(__TopXMLNS, __Opts,
[{xmlel, <<"i4">>, _attrs, _} = _el | _els], Cdata,
Val) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata,
decode_i4(<<"xmlrpc">>, __Opts, _el));
_ ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata, Val)
end;
decode_value_els(__TopXMLNS, __Opts,
[{xmlel, <<"int">>, _attrs, _} = _el | _els], Cdata,
Val) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata,
decode_int(<<"xmlrpc">>, __Opts, _el));
_ ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata, Val)
end;
decode_value_els(__TopXMLNS, __Opts,
[{xmlel, <<"string">>, _attrs, _} = _el | _els], Cdata,
Val) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata,
decode_string(<<"xmlrpc">>, __Opts, _el));
_ ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata, Val)
end;
decode_value_els(__TopXMLNS, __Opts,
[{xmlel, <<"double">>, _attrs, _} = _el | _els], Cdata,
Val) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata,
decode_double(<<"xmlrpc">>, __Opts, _el));
_ ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata, Val)
end;
decode_value_els(__TopXMLNS, __Opts,
[{xmlel, <<"base64">>, _attrs, _} = _el | _els], Cdata,
Val) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata,
decode_base64(<<"xmlrpc">>, __Opts, _el));
_ ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata, Val)
end;
decode_value_els(__TopXMLNS, __Opts,
[{xmlel, <<"boolean">>, _attrs, _} = _el | _els], Cdata,
Val) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata,
decode_boolean(<<"xmlrpc">>, __Opts, _el));
_ ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata, Val)
end;
decode_value_els(__TopXMLNS, __Opts,
[{xmlel, <<"array">>, _attrs, _} = _el | _els], Cdata,
Val) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata,
decode_array(<<"xmlrpc">>, __Opts, _el));
_ ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata, Val)
end;
decode_value_els(__TopXMLNS, __Opts,
[{xmlel, <<"nil">>, _attrs, _} = _el | _els], Cdata,
Val) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata,
decode_nil(<<"xmlrpc">>, __Opts, _el));
_ ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata, Val)
end;
decode_value_els(__TopXMLNS, __Opts,
[{xmlel, <<"struct">>, _attrs, _} = _el | _els], Cdata,
Val) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata,
decode_struct(<<"xmlrpc">>, __Opts, _el));
_ ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata, Val)
end;
decode_value_els(__TopXMLNS, __Opts,
[{xmlel, <<"dateTime.iso8601">>, _attrs, _} = _el
| _els],
Cdata, Val) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata,
decode_dateTime(<<"xmlrpc">>, __Opts, _el));
_ ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata, Val)
end;
decode_value_els(__TopXMLNS, __Opts, [_ | _els], Cdata,
Val) ->
decode_value_els(__TopXMLNS, __Opts, _els, Cdata, Val).
encode_value({Val, Cdata}, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = lists:reverse(encode_value_cdata(Cdata,
'encode_value_$val'(Val,
__NewTopXMLNS,
[]))),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"value">>, _attrs, _els}.
'encode_value_$val'(undefined, __TopXMLNS, _acc) ->
_acc;
'encode_value_$val'({i4, _} = Val, __TopXMLNS, _acc) ->
[encode_i4(Val, __TopXMLNS) | _acc];
'encode_value_$val'({int, _} = Val, __TopXMLNS, _acc) ->
[encode_int(Val, __TopXMLNS) | _acc];
'encode_value_$val'({string, _} = Val, __TopXMLNS,
_acc) ->
[encode_string(Val, __TopXMLNS) | _acc];
'encode_value_$val'({double, _} = Val, __TopXMLNS,
_acc) ->
[encode_double(Val, __TopXMLNS) | _acc];
'encode_value_$val'({base64, _} = Val, __TopXMLNS,
_acc) ->
[encode_base64(Val, __TopXMLNS) | _acc];
'encode_value_$val'({boolean, _} = Val, __TopXMLNS,
_acc) ->
[encode_boolean(Val, __TopXMLNS) | _acc];
'encode_value_$val'({array, _} = Val, __TopXMLNS,
_acc) ->
[encode_array(Val, __TopXMLNS) | _acc];
'encode_value_$val'(nil = Val, __TopXMLNS, _acc) ->
[encode_nil(Val, __TopXMLNS) | _acc];
'encode_value_$val'({struct, _} = Val, __TopXMLNS,
_acc) ->
[encode_struct(Val, __TopXMLNS) | _acc];
'encode_value_$val'({date, _} = Val, __TopXMLNS,
_acc) ->
[encode_dateTime(Val, __TopXMLNS) | _acc].
decode_value_cdata(__TopXMLNS, <<>>) -> undefined;
decode_value_cdata(__TopXMLNS, _val) -> _val.
encode_value_cdata(undefined, _acc) -> _acc;
encode_value_cdata(_val, _acc) ->
[{xmlcdata, _val} | _acc].
decode_param(__TopXMLNS, __Opts,
{xmlel, <<"param">>, _attrs, _els}) ->
Value = decode_param_els(__TopXMLNS, __Opts, _els,
error),
Value.
decode_param_els(__TopXMLNS, __Opts, [], Value) ->
case Value of
error ->
erlang:error({fxmlrpc_codec,
{missing_tag, <<"value">>, __TopXMLNS}});
{value, Value1} -> Value1
end;
decode_param_els(__TopXMLNS, __Opts,
[{xmlel, <<"value">>, _attrs, _} = _el | _els],
Value) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_param_els(__TopXMLNS, __Opts, _els,
{value, decode_value(<<"xmlrpc">>, __Opts, _el)});
_ -> decode_param_els(__TopXMLNS, __Opts, _els, Value)
end;
decode_param_els(__TopXMLNS, __Opts, [_ | _els],
Value) ->
decode_param_els(__TopXMLNS, __Opts, _els, Value).
encode_param(Value, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = lists:reverse('encode_param_$value'(Value,
__NewTopXMLNS, [])),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"param">>, _attrs, _els}.
'encode_param_$value'(Value, __TopXMLNS, _acc) ->
[encode_value(Value, __TopXMLNS) | _acc].
decode_params(__TopXMLNS, __Opts,
{xmlel, <<"params">>, _attrs, _els}) ->
Params = decode_params_els(__TopXMLNS, __Opts, _els,
[]),
Params.
decode_params_els(__TopXMLNS, __Opts, [], Params) ->
lists:reverse(Params);
decode_params_els(__TopXMLNS, __Opts,
[{xmlel, <<"param">>, _attrs, _} = _el | _els],
Params) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_params_els(__TopXMLNS, __Opts, _els,
[decode_param(<<"xmlrpc">>, __Opts, _el) | Params]);
_ -> decode_params_els(__TopXMLNS, __Opts, _els, Params)
end;
decode_params_els(__TopXMLNS, __Opts, [_ | _els],
Params) ->
decode_params_els(__TopXMLNS, __Opts, _els, Params).
encode_params(Params, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = lists:reverse('encode_params_$params'(Params,
__NewTopXMLNS, [])),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"params">>, _attrs, _els}.
'encode_params_$params'([], __TopXMLNS, _acc) -> _acc;
'encode_params_$params'([Params | _els], __TopXMLNS,
_acc) ->
'encode_params_$params'(_els, __TopXMLNS,
[encode_param(Params, __TopXMLNS) | _acc]).
decode_methodName(__TopXMLNS, __Opts,
{xmlel, <<"methodName">>, _attrs, _els}) ->
Cdata = decode_methodName_els(__TopXMLNS, __Opts, _els,
<<>>),
Cdata.
decode_methodName_els(__TopXMLNS, __Opts, [], Cdata) ->
decode_methodName_cdata(__TopXMLNS, Cdata);
decode_methodName_els(__TopXMLNS, __Opts,
[{xmlcdata, _data} | _els], Cdata) ->
decode_methodName_els(__TopXMLNS, __Opts, _els,
<>);
decode_methodName_els(__TopXMLNS, __Opts, [_ | _els],
Cdata) ->
decode_methodName_els(__TopXMLNS, __Opts, _els, Cdata).
encode_methodName(Cdata, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = encode_methodName_cdata(Cdata, []),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"methodName">>, _attrs, _els}.
decode_methodName_cdata(__TopXMLNS, <<>>) ->
erlang:error({fxmlrpc_codec,
{missing_cdata, <<>>, <<"methodName">>, __TopXMLNS}});
decode_methodName_cdata(__TopXMLNS, _val) ->
case catch erlang:binary_to_atom(_val, utf8) of
{'EXIT', _} ->
erlang:error({fxmlrpc_codec,
{bad_cdata_value, <<>>, <<"methodName">>, __TopXMLNS}});
_res -> _res
end.
encode_methodName_cdata(_val, _acc) ->
[{xmlcdata, erlang:atom_to_binary(_val, utf8)} | _acc].
decode_fault(__TopXMLNS, __Opts,
{xmlel, <<"fault">>, _attrs, _els}) ->
Value = decode_fault_els(__TopXMLNS, __Opts, _els,
error),
{fault, Value}.
decode_fault_els(__TopXMLNS, __Opts, [], Value) ->
case Value of
error ->
erlang:error({fxmlrpc_codec,
{missing_tag, <<"value">>, __TopXMLNS}});
{value, Value1} -> Value1
end;
decode_fault_els(__TopXMLNS, __Opts,
[{xmlel, <<"value">>, _attrs, _} = _el | _els],
Value) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_fault_els(__TopXMLNS, __Opts, _els,
{value, decode_value(<<"xmlrpc">>, __Opts, _el)});
_ -> decode_fault_els(__TopXMLNS, __Opts, _els, Value)
end;
decode_fault_els(__TopXMLNS, __Opts, [_ | _els],
Value) ->
decode_fault_els(__TopXMLNS, __Opts, _els, Value).
encode_fault({fault, Value}, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = lists:reverse('encode_fault_$value'(Value,
__NewTopXMLNS, [])),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"fault">>, _attrs, _els}.
'encode_fault_$value'(Value, __TopXMLNS, _acc) ->
[encode_value(Value, __TopXMLNS) | _acc].
decode_methodResponse(__TopXMLNS, __Opts,
{xmlel, <<"methodResponse">>, _attrs, _els}) ->
Payload = decode_methodResponse_els(__TopXMLNS, __Opts,
_els, []),
{response, Payload}.
decode_methodResponse_els(__TopXMLNS, __Opts, [],
Payload) ->
Payload;
decode_methodResponse_els(__TopXMLNS, __Opts,
[{xmlel, <<"fault">>, _attrs, _} = _el | _els],
Payload) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_methodResponse_els(__TopXMLNS, __Opts, _els,
decode_fault(<<"xmlrpc">>, __Opts, _el));
_ ->
decode_methodResponse_els(__TopXMLNS, __Opts, _els,
Payload)
end;
decode_methodResponse_els(__TopXMLNS, __Opts,
[{xmlel, <<"params">>, _attrs, _} = _el | _els],
Payload) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_methodResponse_els(__TopXMLNS, __Opts, _els,
decode_params(<<"xmlrpc">>, __Opts, _el));
_ ->
decode_methodResponse_els(__TopXMLNS, __Opts, _els,
Payload)
end;
decode_methodResponse_els(__TopXMLNS, __Opts,
[_ | _els], Payload) ->
decode_methodResponse_els(__TopXMLNS, __Opts, _els,
Payload).
encode_methodResponse({response, Payload},
__TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els =
lists:reverse('encode_methodResponse_$payload'(Payload,
__NewTopXMLNS, [])),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"methodResponse">>, _attrs, _els}.
'encode_methodResponse_$payload'([], __TopXMLNS,
_acc) ->
_acc;
'encode_methodResponse_$payload'({fault, _} = Payload,
__TopXMLNS, _acc) ->
[encode_fault(Payload, __TopXMLNS) | _acc];
'encode_methodResponse_$payload'(_ = Payload,
__TopXMLNS, _acc) ->
[encode_params(Payload, __TopXMLNS) | _acc].
decode_methodCall(__TopXMLNS, __Opts,
{xmlel, <<"methodCall">>, _attrs, _els}) ->
{Params, Name} = decode_methodCall_els(__TopXMLNS,
__Opts, _els, [], error),
{call, Name, Params}.
decode_methodCall_els(__TopXMLNS, __Opts, [], Params,
Name) ->
{Params,
case Name of
error ->
erlang:error({fxmlrpc_codec,
{missing_tag, <<"methodName">>, __TopXMLNS}});
{value, Name1} -> Name1
end};
decode_methodCall_els(__TopXMLNS, __Opts,
[{xmlel, <<"methodName">>, _attrs, _} = _el | _els],
Params, Name) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_methodCall_els(__TopXMLNS, __Opts, _els, Params,
{value,
decode_methodName(<<"xmlrpc">>, __Opts, _el)});
_ ->
decode_methodCall_els(__TopXMLNS, __Opts, _els, Params,
Name)
end;
decode_methodCall_els(__TopXMLNS, __Opts,
[{xmlel, <<"params">>, _attrs, _} = _el | _els], Params,
Name) ->
case fxmlrpc_codec:get_attr(<<"xmlns">>, _attrs,
__TopXMLNS)
of
<<"xmlrpc">> ->
decode_methodCall_els(__TopXMLNS, __Opts, _els,
decode_params(<<"xmlrpc">>, __Opts, _el), Name);
_ ->
decode_methodCall_els(__TopXMLNS, __Opts, _els, Params,
Name)
end;
decode_methodCall_els(__TopXMLNS, __Opts, [_ | _els],
Params, Name) ->
decode_methodCall_els(__TopXMLNS, __Opts, _els, Params,
Name).
encode_methodCall({call, Name, Params}, __TopXMLNS) ->
__NewTopXMLNS =
fxmlrpc_codec:choose_top_xmlns(<<"xmlrpc">>, [],
__TopXMLNS),
_els = lists:reverse('encode_methodCall_$params'(Params,
__NewTopXMLNS,
'encode_methodCall_$name'(Name,
__NewTopXMLNS,
[]))),
_attrs = fxmlrpc_codec:enc_xmlns_attrs(__NewTopXMLNS,
__TopXMLNS),
{xmlel, <<"methodCall">>, _attrs, _els}.
'encode_methodCall_$params'([], __TopXMLNS, _acc) ->
_acc;
'encode_methodCall_$params'(Params, __TopXMLNS, _acc) ->
[encode_params(Params, __TopXMLNS) | _acc].
'encode_methodCall_$name'(Name, __TopXMLNS, _acc) ->
[encode_methodName(Name, __TopXMLNS) | _acc].
fast_xml-1.1.48/src/fxml_gen.erl 0000644 0002322 0002322 00000465146 14151146420 017100 0 ustar debalance debalance %%%----------------------------------------------------------------------
%%% File : xml_gen.erl
%%% Author : Evgeniy Khramtsov
%%% Purpose : XML code generator
%%% Created : 22 Jun 2009 by Evgeniy Khramtsov
%%%
%%%
%%% Copyright (C) 2002-2021 ProcessOne, SARL. 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.
%%%
%%%----------------------------------------------------------------------
-module(fxml_gen).
-compile(debug_info).
-compile({parse_transform, fxml_gen_pt}).
%% Generator API
-export([compile/1, compile/2]).
%% Runtime API
-export([format_error/1, io_format_error/1, get_attr/3]).
%% Runtime built-in decoders/encoders
-export([dec_int/1, dec_int/3, dec_enum/2, enc_int/1, enc_enum/1, not_empty/1,
enc_xmlns_attrs/2, choose_top_xmlns/3,
register_module/2, unregister_module/2, recompile_resolver/2]).
-include("fxml_gen.hrl").
-include("fxml.hrl").
-define(err(F, Args),
begin
io:format("** fxml_gen error: " ++ F ++ "~n", Args),
erlang:error(badarg)
end).
-define(info(F, Args), io:format("fxml_gen: " ++ F ++ "~n", Args)).
-define(warn(F, Args), io:format("* fxml_gen warning: " ++ F ++ "~n", Args)).
%%====================================================================
%% Compiler API
%%====================================================================
compile(Path) ->
compile(Path, []).
compile(Path, Opts) ->
case catch do_compile(Path, Opts) of
ok ->
ok;
Err ->
io:format("failed to compile ~p: ~p~n", [Path, Err]),
Err
end.
do_compile(Path, Opts) ->
case get_files_from_predefined_dir() of
{ok, Files} ->
case lists:foldr(
fun(_, {error, _} = Err) ->
Err;
(File, {AccTs, AccFs}) ->
case consult(File) of
{ok, Ts, Fs} ->
{Ts ++ AccTs, Fs ++ AccFs};
Err ->
Err
end
end, {[], []}, [Path|Files]) of
{error, Why} ->
{error, Why};
{Terms, Forms} ->
Elems = lists:flatmap(
fun({Tag, Elem}) when is_atom(Tag),
is_record(Elem, elem) ->
[{Tag, Elem}];
(_) ->
[]
end, Terms),
compile(Elems, Forms, Path, Opts)
end;
Err ->
Err
end.
get_files_from_predefined_dir() ->
case os:getenv("FXML_GEN_DIR") of
false ->
{ok, []};
Dir ->
case file:list_dir(Dir) of
{ok, Files} ->
{ok, lists:flatmap(
fun(File) ->
case filename:extension(File) of
".spec" ->
[filename:join(Dir, File)];
_ ->
[]
end
end, Files)};
{error, _} = Err ->
Err
end
end.
%%====================================================================
%% Runtime decoders/encoders
%%====================================================================
-spec dec_int(binary()) -> integer().
dec_int(Val) ->
dec_int(Val, infinity, infinity).
dec_int(Val, Min, Max) ->
case erlang:binary_to_integer(Val) of
Int when Int =< Max, Min == infinity ->
Int;
Int when Int =< Max, Int >= Min ->
Int
end.
-spec enc_int(integer()) -> binary().
enc_int(Int) ->
erlang:integer_to_binary(Int).
-spec dec_enum(binary(), [atom()]) -> atom().
dec_enum(Val, Enums) ->
AtomVal = erlang:binary_to_existing_atom(Val, utf8),
case lists:member(AtomVal, Enums) of
true ->
AtomVal
end.
-spec enc_enum(atom()) -> binary().
enc_enum(Atom) ->
erlang:atom_to_binary(Atom, utf8).
-spec not_empty(binary()) -> binary().
not_empty(<<_, _/binary>> = Val) ->
Val.
%%====================================================================
%% Runtime builtins
%%====================================================================
format_error({bad_attr_value, Attr, Tag, XMLNS}) ->
<<"Bad value of attribute '", Attr/binary,
"' in tag <", Tag/binary, "/> qualified by namespace '",
XMLNS/binary, "'">>;
format_error({bad_cdata_value, <<>>, Tag, XMLNS}) ->
<<"Bad value of cdata in tag <", Tag/binary,
"/> qualified by namespace '", XMLNS/binary, "'">>;
format_error({missing_tag, Tag, XMLNS}) ->
<<"Missing tag <", Tag/binary,
"/> qualified by namespace '", XMLNS/binary, "'">>;
format_error({missing_attr, Attr, Tag, XMLNS}) ->
<<"Missing attribute '", Attr/binary,
"' in tag <", Tag/binary,
"/> qualified by namespace '", XMLNS/binary, "'">>;
format_error({missing_cdata, <<>>, Tag, XMLNS}) ->
<<"Missing cdata in tag <", Tag/binary,
"/> qualified by namespace '", XMLNS/binary, "'">>;
format_error({unknown_tag, Tag, XMLNS}) ->
<<"Unknown tag <", Tag/binary,
"/> qualified by namespace '", XMLNS/binary, "'">>;
format_error({missing_tag_xmlns, Tag}) ->
<<"Missing namespace for tag <", Tag/binary, "/>">>.
io_format_error({bad_attr_value, Attr, Tag, XMLNS}) ->
{<<"Bad value of attribute '~s' in tag <~s/> qualified by namespace '~s'">>,
[Attr, Tag, XMLNS]};
io_format_error({bad_cdata_value, <<>>, Tag, XMLNS}) ->
{<<"Bad value of cdata in tag <~s/> qualified by namespace '~s'">>,
[Tag, XMLNS]};
io_format_error({missing_tag, Tag, XMLNS}) ->
{<<"Missing tag <~s/> qualified by namespace '~s'">>, [Tag, XMLNS]};
io_format_error({missing_attr, Attr, Tag, XMLNS}) ->
{<<"Missing attribute '~s' in tag <~s/> qualified by namespace '~s'">>,
[Attr, Tag, XMLNS]};
io_format_error({missing_cdata, <<>>, Tag, XMLNS}) ->
{<<"Missing cdata in tag <~s/> qualified by namespace '~s'">>,
[Tag, XMLNS]};
io_format_error({unknown_tag, Tag, XMLNS}) ->
{<<"Unknown tag <~s/> qualified by namespace '~s'">>, [Tag, XMLNS]};
io_format_error({missing_tag_xmlns, Tag}) ->
{<<"Missing namespace for tag <~s/>">>, [Tag]}.
get_attr(Attr, Attrs, Default) ->
case lists:keyfind(Attr, 1, Attrs) of
{_, Val} -> Val;
false -> Default
end.
enc_xmlns_attrs(XMLNS, XMLNS) -> [];
enc_xmlns_attrs(XMLNS, _) -> [{<<"xmlns">>, XMLNS}].
choose_top_xmlns(<<>>, NSList, TopXMLNS) ->
case lists:member(TopXMLNS, NSList) of
true -> TopXMLNS;
false -> hd(NSList)
end;
choose_top_xmlns(XMLNS, _, _) ->
XMLNS.
register_module(Mod, ResolverMod) ->
MD5Sum = try Mod:module_info(md5) of
Val -> Val
catch error:badarg ->
%% 'md5' attribute is relatively new,
%% calculate md5sum using beam_lib for
%% older OTP
{ok, {Mod, Val}} = beam_lib:md5(code:which(Mod)),
Val
end,
case orddict:find(Mod, ResolverMod:modules()) of
{ok, MD5Sum} ->
ok;
_ ->
Mods = orddict:store(Mod, MD5Sum, ResolverMod:modules()),
recompile_resolver(Mods, ResolverMod)
end.
unregister_module(Mod, ResolverMod) ->
case orddict:find(Mod, ResolverMod:modules()) of
{ok, _} ->
Mods = orddict:erase(Mod, ResolverMod:modules()),
recompile_resolver(Mods, ResolverMod);
error ->
ok
end.
%% We don't use erl_syntax here in order not to depend
%% on syntax_tools in runtime
recompile_resolver(Mods, ResolverMod) ->
Tags = lists:flatmap(
fun(M) ->
[{Name, XMLNS, M} || {Name, XMLNS} <- M:tags()]
end, orddict:fetch_keys(Mods)),
Records = lists:flatmap(
fun(M) ->
[{RecName, RecSize, M}
|| {RecName, RecSize} <- M:records()]
end, orddict:fetch_keys(Mods)),
Lookup1 = string:join(
lists:map(
fun({RecName, RecSize, M}) ->
io_lib:format(
"lookup({~s}) -> '~s'",
[string:join(
[io_lib:format("'~s'", [RecName]) |
["_" || _ <- lists:seq(1, RecSize)]],
","), M])
end, Records) ++ ["lookup(Term) -> erlang:error(badarg, [Term])."],
";" ++ io_lib:nl()),
Lookup2 = string:join(
lists:map(
fun({Name, XMLNS, M}) ->
io_lib:format("lookup(~w, ~w) -> '~s'",
[Name, XMLNS, M])
end, Tags) ++ ["lookup(_, _) -> undefined."],
";" ++ io_lib:nl()),
Modules = io_lib:format(
"modules() -> [~s].",
[string:join(
[io_lib:format(
"{'~s', ~w}", [M, S])
|| {M, S} <- Mods], ",")]),
Module = io_lib:format("-module(~s).", [ResolverMod]),
Compile = "-compile(export_all).",
Forms = lists:map(
fun(Expr) ->
{ok, Tokens, _} = erl_scan:string(lists:flatten(Expr)),
{ok, Form} = erl_parse:parse_form(Tokens),
Form
end, [Module, Compile, Modules, Lookup1, Lookup2]),
{ok, Code} = case compile:forms(Forms, []) of
{ok, ResolverMod, Bin} ->
{ok, Bin};
{ok, ResolverMod, Bin, _Warnings} ->
{ok, Bin};
Error ->
Error
end,
{module, ResolverMod} = code:load_binary(ResolverMod, "nofile", Code),
ok.
%%====================================================================
%% Internal functions
%%====================================================================
compile(TaggedElems0, Forms, Path, Opts) ->
FileName = filename:basename(Path),
ModName = list_to_atom(filename:rootname(FileName)),
ModNameHrl = filename:rootname(FileName) ++ ".hrl",
ModNameATD = filename:rootname(FileName) ++ ".atd",
DirName = filename:dirname(Path),
ErlDirName = proplists:get_value(erl_dir, Opts, DirName),
HrlDirName = proplists:get_value(hrl_dir, Opts, DirName),
{AttrForms, RestForms} = lists:partition(
fun(Form) ->
erl_syntax:type(Form) == attribute
end, Forms),
FunForms = lists:foldl(
fun(F, Acc) ->
case erl_syntax:type(F) of
function ->
[F|Acc];
_ ->
Acc
end
end, make_builtin_codec_funs(), RestForms),
KnownFuns = [erl_syntax_lib:analyze_function(F) || F <- FunForms],
FunSpecs = lists:foldl(
fun(Form, D) ->
case erl_syntax_lib:analyze_attribute(Form) of
{spec, _} ->
{Key, Value} = get_fun_spec(erl_syntax:revert(Form)),
dict:store(Key, Value, D);
_ ->
D
end
end, dict:new(), AttrForms),
TaggedElems = lists:map(
fun({Tag, Elem}) ->
{Tag, prepare_elem(Elem, KnownFuns, FunSpecs,
TaggedElems0, ModName, Opts)}
end, TaggedElems0),
Dups = get_dups([Tag || {Tag, _} <- TaggedElems]),
if Dups /= [] ->
bad_spec({duplicated_elem_specs, Dups});
true ->
ok
end,
Dups1 = get_dups([{Elem#elem.name, Elem#elem.xmlns}
|| {_, Elem} <- TaggedElems]),
if Dups1 /= [] ->
bad_spec({duplicated_elem_names, Dups1});
true ->
ok
end,
Types = get_types(TaggedElems, FunSpecs, Opts),
RawAttributes = lists:flatmap(
fun(Form) ->
case erl_syntax_lib:analyze_attribute(Form) of
{spec, _} ->
[];
_ ->
erl_syntax:get_ann(Form)
end
end, lists:reverse(AttrForms)),
PredefRecords = get_predefined_records(AttrForms),
ASTs = lists:foldl(
fun({Tag, Elem}, Acc) ->
dict:append_list(
Elem#elem.module,
elem_to_AST(Elem, Tag, TaggedElems, Types,
ModName, PredefRecords, FunSpecs, Opts),
Acc)
end, dict:from_list([{ModName, []}]), TaggedElems),
Records = make_records(Types, TaggedElems, PredefRecords, FunSpecs, Opts),
TypeSpecs = make_typespecs(ModName, Types, Opts),
Hdr = header(FileName),
FunDeps = build_fun_deps(FunForms),
case write_modules(ASTs, ModName, FunDeps, ErlDirName,
FileName, TaggedElems, PredefRecords, Opts) of
ok ->
case write_resolver(TaggedElems, ModName, ErlDirName, FileName) of
ok ->
io:format("Generating ~s~n", [ModNameHrl]),
file:write_file(
filename:join([HrlDirName, ModNameHrl]),
[erl_prettypr:format(Hdr),
RawAttributes,
io_lib:nl(),
string:join(Records, io_lib:nl() ++ io_lib:nl()),
io_lib:nl(),
io_lib:nl(),
TypeSpecs,
io_lib:nl()]),
case proplists:get_bool(json, Opts) of
true ->
io:format("Generating ~s~n", [ModNameATD]),
ATDRecords =
make_atd_records(Types, TaggedElems,
PredefRecords, FunSpecs),
file:write_file(
filename:join([HrlDirName, ModNameATD]),
[atd_header(FileName),
ATDRecords,
io_lib:nl()]);
false ->
ok
end;
Err ->
Err
end;
Err ->
Err
end.
write_modules(ASTs, ModName, FunDeps, ErlDirName,
FileName, TaggedElems, PredefRecords, Opts) ->
dict:fold(
fun(_, _, {error, _} = Err) ->
Err;
(Mod, AST, ok) ->
write_module(ModName, Mod, AST, FunDeps, ErlDirName,
FileName, TaggedElems, PredefRecords, Opts)
end, ok, ASTs).
write_module(ModName, ModName, AST, FunDeps, ErlDirName,
SpecFile, TaggedElems, PredefRecords, Opts) ->
ModNameErl = atom_to_list(ModName) ++ ".erl",
io:format("Generating ~s~n", [ModNameErl]),
Module = erl_syntax:attribute(
?AST(module),
[erl_syntax:atom(ModName)]),
TopDecoders = make_top_decoders(TaggedElems, ModName, Opts),
TopEncoders = make_top_encoders(TaggedElems, ModName, Opts),
Registrar = make_registrar(ModName),
Decoders = make_decoders(TaggedElems, PredefRecords, ModName, ModName, Opts),
Encoders = make_encoders(TaggedElems, ModName, Opts),
Printer = make_printer(TaggedElems, PredefRecords, ModName, ModName),
GettersSetters = make_getters_setters(TaggedElems, PredefRecords, ModName),
Resolver = make_resolver(TaggedElems, ModName),
AuxFuns = make_aux_funs(),
LocalFunForms = make_local_funs(FunDeps, TaggedElems, ModName),
NewAST = TopDecoders ++ TopEncoders ++ Decoders ++ Encoders ++
GettersSetters ++ Registrar ++ AuxFuns ++ LocalFunForms ++ Printer ++ Resolver ++ AST,
Compile = erl_syntax:attribute(?AST(compile), [?AST(export_all)]),
Hdr = header(SpecFile),
ResultAST = erl_syntax:form_list([Hdr, Module, Compile|NewAST]),
file:write_file(
filename:join([ErlDirName, ModNameErl]),
[erl_prettypr:format(ResultAST), io_lib:nl()]);
write_module(ParentMod, ModName, AST, FunDeps, ErlDirName,
SpecFile, TaggedElems, PredefRecords, Opts) ->
ModNameErl = atom_to_list(ModName) ++ ".erl",
io:format("Generating ~s~n", [ModNameErl]),
Hdr = header(SpecFile),
Module = erl_syntax:attribute(
?AST(module),
[erl_syntax:atom(ModName)]),
Decoders = make_decoders(TaggedElems, PredefRecords, ParentMod, ModName, Opts),
Encoders = make_encoders(TaggedElems, ModName, Opts),
Printer = make_printer(TaggedElems, PredefRecords, ModName, ParentMod),
GettersSetters = make_getters_setters(TaggedElems, PredefRecords, ModName),
Compile = erl_syntax:attribute(?AST(compile), [?AST(export_all)]),
LocalFunForms = make_local_funs(FunDeps, TaggedElems, ModName),
NewAST = Decoders ++ Encoders ++ GettersSetters ++ Printer ++ LocalFunForms ++ AST,
ResultAST = erl_syntax:form_list([Hdr, Module, Compile|NewAST]),
file:write_file(
filename:join([ErlDirName, ModNameErl]),
[erl_prettypr:format(ResultAST), io_lib:nl()]).
write_resolver(_TaggedElems, ParentMod, ErlDirName, SpecFile) ->
ModName = resolver_mod(ParentMod),
ModNameErl = atom_to_list(ModName) ++ ".erl",
io:format("Generating ~s~n", [ModNameErl]),
Hdr = header(SpecFile),
Module = erl_syntax:attribute(
?AST(module),
[erl_syntax:atom(ModName)]),
Compile = erl_syntax:attribute(?AST(compile), [?AST(export_all)]),
AST = [make_function(modules, [], [?AST([])]),
make_function(lookup, [?AST(_), ?AST(_)], [?AST(undefined)]),
make_function(lookup, [?AST(Term)], [?AST(erlang:error(badarg, [Term]))])],
ResultAST = erl_syntax:form_list([Hdr, Module, Compile|AST]),
file:write_file(
filename:join([ErlDirName, ModNameErl]),
[erl_prettypr:format(ResultAST), io_lib:nl()]).
get_fun_spec({attribute, _, spec, {MFA, Args}}) ->
Spec = case [Range || {type, _, 'fun', [_, Range]} <- Args] of
[] -> {type, 0, any, []};
[T] -> T;
Ts -> {type, 0, union, Ts}
end,
{MFA, Spec}.
get_predefined_records(AttrForms) ->
lists:foldl(
fun(F, Acc) ->
case erl_syntax_lib:analyze_attribute(F) of
{record, {RecName, RecAttrs}} ->
RecAttrs1 = lists:map(
fun({Attr, {Default, Type}}) ->
{Attr, Default, Type};
({Attr, Default}) ->
{Attr, Default, undefined}
end, RecAttrs),
dict:store(RecName, RecAttrs1, Acc);
_ ->
Acc
end
end, dict:new(), AttrForms).
make_aux_funs() ->
case get_abstract_code_from_myself() of
{ok, AbsCode} ->
lists:filter(
fun(T) ->
case catch erl_syntax_lib:analyze_function(T) of
{format_error, 1} -> true;
{io_format_error, 1} -> true;
{get_attr, 3} -> true;
{choose_top_xmlns, 3} -> true;
{enc_xmlns_attrs, 2} -> true;
{register_module, 2} -> true;
{unregister_module, 2} -> true;
{recompile_resolver, 2} -> true;
_ -> false
end
end, AbsCode);
error ->
erlang:error({no_abstract_code_found, ?MODULE})
end.
make_builtin_codec_funs() ->
case get_abstract_code_from_myself() of
{ok, AbsCode} ->
lists:filter(
fun(T) ->
case catch erl_syntax_lib:analyze_function(T) of
{dec_int, 3} -> true;
{dec_int, 1} -> true;
{dec_enum, 2} -> true;
{enc_int, 1} -> true;
{enc_enum, 1} -> true;
_ -> false
end
end, AbsCode);
error ->
erlang:error({no_abstract_code_found, ?MODULE})
end.
build_fun_deps(FunForms) ->
G = digraph:new([acyclic]),
lists:foreach(
fun(FunForm) ->
Fun = erl_syntax_lib:analyze_function(FunForm),
digraph:add_vertex(G, Fun, FunForm),
erl_syntax_lib:map(
fun(Form) ->
try erl_syntax_lib:analyze_application(Form) of
{_, Arity} = SubFun when is_integer(Arity) ->
case digraph:vertex(G, SubFun) of
false -> digraph:add_vertex(G, SubFun);
_ -> ok
end,
digraph:add_edge(G, Fun, SubFun);
_ ->
ok
catch _:_ ->
ok
end,
Form
end, FunForm)
end, FunForms),
G.
make_local_funs(FunDeps, TaggedElems, ModName) ->
CodecFuns = lists:flatmap(
fun({_, #elem{attrs = Attrs, cdata = CData, module = M}})
when M == ModName ->
[CData#cdata.enc, CData#cdata.dec|
lists:flatmap(
fun(#attr{enc = Enc, dec = Dec}) ->
[Enc,Dec]
end, Attrs)];
({_, _}) ->
[]
end, TaggedElems),
LocalFuns = lists:usort([{Name, length(Arity)+1} || {Name, Arity} <- CodecFuns]),
AllLocalFuns = lists:flatmap(
fun(LocalFun) ->
digraph_utils:reachable([LocalFun], FunDeps)
end, LocalFuns),
lists:flatmap(
fun(V) ->
case digraph:vertex(FunDeps, V) of
false ->
[];
{V, Form} when is_list(Form) ->
Form;
{V, Form} ->
case erl_syntax:is_form(Form) of
true -> [Form];
false -> []
end
end
end, lists:usort(AllLocalFuns)).
make_records({Tags, TypesDict, RecDict}, TaggedElems, PredefRecords, FunDict, Opts) ->
{Strings, _} =
lists:foldl(
fun(Tag, {Res, Seen}) ->
RefElem = get_elem_by_ref(Tag, TaggedElems),
Result = RefElem#elem.result,
case term_is_record(Result) of
true ->
RecName = element(1, Result),
case dict:is_key(RecName, PredefRecords) of
true ->
{Res, Seen};
false ->
case lists:member(RecName, Seen) of
false ->
{[record_to_string(
RefElem, RecDict,
TypesDict, FunDict, Opts)|Res],
[RecName|Seen]};
true ->
{Res, Seen}
end
end;
false ->
{Res, Seen}
end
end, {[], []}, Tags),
lists:reverse(Strings).
make_typespecs(_ModName, {_Tags, _TypesDict, RecDict}, Opts) ->
case proplists:get_value(add_type_specs, Opts) of
TypeName when is_atom(TypeName), TypeName /= undefined ->
case [[atom_to_string(R), "()"]
|| {record, R} <- lists:sort(dict_keys(RecDict))] of
[] ->
[];
Records ->
Prefix = "-type " ++ atom_to_string(TypeName) ++ "() :: ",
Sep = " |" ++ io_lib:nl()
++ lists:duplicate(length(Prefix), $ ),
[Prefix, string:join(Records, Sep), $.]
end;
_ ->
[]
end.
atom_to_string(Atom) ->
erl_syntax:atom_literal(abstract(Atom)).
-define(is_raw_type(T),
element(1, T) == type orelse
element(1, T) == remote_type).
record_to_string(#elem{result = Result} = Elem, RecDict, RecTypes, FunTypes, Opts) ->
[RecName|RecLabels] = tuple_to_list(Result),
Prefix = "-record(" ++ atom_to_string(RecName) ++ ", {",
Sep = "," ++ io_lib:nl() ++ lists:duplicate(length(Prefix), $ ),
Fs = lists:map(
fun(Label) ->
FName = label_to_record_field(Label),
case get_label_type(Label, Elem, RecTypes, FunTypes, Opts) of
{FType, undefined, true} when ?is_raw_type(FType) ->
[atom_to_string(FName), " :: ",
erl_types:t_form_to_string(FType)];
{FType, undefined, false} when ?is_raw_type(FType) ->
[atom_to_string(FName), " :: ",
"undefined | ", erl_types:t_form_to_string(FType)];
{FType, Default, _} when ?is_raw_type(FType) ->
[atom_to_string(FName), " = ",
io_lib:fwrite("~w", [Default]),
" :: ", erl_types:t_form_to_string(FType)];
{FType, undefined, true} ->
FType1 = erl_types:t_subtract(
FType, erl_types:t_atom(undefined)),
[atom_to_string(FName), " :: ",
erl_types:t_to_string(FType1, RecDict)];
{FType, undefined, false} ->
FType1 = erl_types:t_sup(
FType, erl_types:t_atom(undefined)),
[atom_to_string(FName), " :: ",
erl_types:t_to_string(FType1, RecDict)];
{FType, Default, _} ->
Type = erl_types:t_sup(
[erl_types:t_from_term(Default),
FType]),
[atom_to_string(FName), " = ",
io_lib:fwrite("~w", [Default]),
" :: ",
erl_types:t_to_string(Type, RecDict)]
end
end, RecLabels),
RecordStr = [Prefix, string:join(Fs, Sep), "})."],
case proplists:get_value(add_type_specs, Opts) of
TypeName when is_atom(TypeName), TypeName /= undefined ->
[RecordStr, io_lib:nl(),
"-type ", atom_to_string(RecName), "() :: ",
"#", atom_to_string(RecName), "{}."];
_ ->
RecordStr
end.
header(FileName) ->
erl_syntax:comment(
0,
["% Created automatically by XML generator (fxml_gen.erl)",
"% Source: " ++ FileName]).
make_atd_records({Tags, TypesDict, RecDict}, TaggedElems, PredefRecords, FunDict) ->
RecTypes =
lists:foldl(
fun(Tag, Types) ->
RefElem = get_elem_by_ref(Tag, TaggedElems),
Result = RefElem#elem.result,
case term_is_record(Result) of
true ->
{RecName, Ts} =
record_to_atd_types(
RefElem, TaggedElems,
TypesDict, FunDict),
case maps:find(RecName, Types) of
{ok, Ts2} ->
%% TODO
Ts3 = lists:zipwith(fun merge_json_types/2,
Ts, Ts2),
maps:put(RecName, Ts3, Types);
error ->
maps:put(RecName, Ts, Types)
end;
false ->
Types
end
end, maps:new(), Tags),
{Strings, _} =
lists:foldl(
fun(Tag, {Res, Seen}) ->
RefElem = get_elem_by_ref(Tag, TaggedElems),
Result = RefElem#elem.result,
case term_is_record(Result) of
true ->
RecName = element(1, Result),
case lists:member(RecName, Seen) of
false ->
Types = maps:get(RecName, RecTypes),
{[record_to_atd_string(
RefElem, Types, PredefRecords) | Res],
[RecName|Seen]};
true ->
{Res, Seen}
end;
false when is_atom(Result) ->
Label = Result,
Str =
case is_label(Label) of
true ->
JSONType = get_label_json_type(
Label, RefElem, TypesDict,
FunDict, TaggedElems),
T =
case JSONType of
{option, _Type, Default}
when is_atom(Default) ->
JSONType;
{option, Type, _Default} ->
Type;
_ ->
JSONType
end,
io_lib:format(
"type ~s = ~s",
[sanitize_for_atd(Tag),
json_type_to_atd(T)]);
false ->
io_lib:format(
"type ~s = ~s",
[sanitize_for_atd(Tag),
json_type_to_atd({atom, [Label]})])
end,
{[Str | Res], Seen};
false ->
{[tuple_to_atd_string(
RefElem, TaggedElems,
TypesDict, FunDict,
Tag) | Res],
Seen}
%{Res, Seen}
end
end, {[], []}, Tags),
lists:reverse(Strings),
ATDRecords = [io_lib:format(
" | ~s of ~s~n",
[to_atd_variant(R),
to_atd_var(R)])
|| {record, R} <- lists:sort(dict_keys(RecDict))],
[string:join(Strings, io_lib:nl() ++ io_lib:nl()), io_lib:nl(),
"type xmpp_element = [", io_lib:nl(),
" | XmlString of string", io_lib:nl(),
" | StreamEnd", io_lib:nl(),
ATDRecords,
"]"
].
record_to_atd_string(#elem{result = Result}, Types, PredefRecords) ->
[RecName | RecLabels] = tuple_to_list(Result),
Prefix = ["type ", to_atd_var(RecName), " = {", io_lib:nl(),
"\s\s"],
Sep = lists:flatten([";", io_lib:nl(), "\s\s"]),
{_, RevRecFields} =
lists:foldl(
fun(Label, {K, Fs}) ->
case is_label(Label) of
true when Label /= '$_' ->
{K + 1, [label_to_record_field(Label) | Fs]};
_ ->
{ok, RecFields} = dict:find(RecName, PredefRecords),
{FName, _, _} = lists:nth(K + 1, RecFields),
{K + 1, [FName | Fs]}
end
end, {0, []}, RecLabels),
RecFields = lists:reverse(RevRecFields),
case lists:zip(RecFields, Types) of
[{_FName, JSONType}] ->
["type ", to_atd_var(RecName), " = ",
json_type_to_atd(JSONType)];
RecFieldsTypes ->
Fs = lists:flatmap(
fun({FName, JSONType}) ->
case JSONType of
ignore -> [];
{option, Type, Default} ->
if
%is_atom(Default) ->
Default == undefined ->
[io_lib:format(
"?~s : ~s",
[to_atd_var(FName),
json_type_to_atd(JSONType)])];
true ->
[io_lib:format(
"~~~s : ~s",
[to_atd_var(FName),
atd_value_to_string(Default),
json_type_to_atd(Type)])]
end;
Type ->
UseDefault =
case Type of
{list, _} -> "~";
binary -> "~";
{binary, _, _} -> "~";
_ -> ""
end,
[io_lib:format("~s~s : ~s",
[UseDefault,
to_atd_var(FName),
json_type_to_atd(Type)])]
end
end, RecFieldsTypes),
case Fs of
[] ->
["type ", to_atd_var(RecName), " = unit"];
_ ->
RecordStr = [Prefix, string:join(Fs, Sep), io_lib:nl() ++ "}"],
[RecordStr, io_lib:nl()]
end
end.
tuple_to_atd_string(#elem{result = Result} = Elem, AllElems,
RecTypes, FunTypes, RecName) ->
RecLabels = tuple_to_list(Result),
Prefix = "type " ++ sanitize_for_atd(RecName) ++ " = (",
Sep = " * ",
Fs = lists:flatmap(
fun(Label) ->
JSONType = get_label_json_type(
Label, Elem, RecTypes,
FunTypes, AllElems),
case JSONType of
ignore -> [];
Type ->
[json_type_to_atd(Type)]
end
end, RecLabels),
RecordStr = [Prefix, string:join(Fs, Sep), ")"],
RecordStr.
record_to_atd_types(#elem{result = Result} = Elem, AllElems,
RecTypes, FunTypes) ->
[RecName | RecLabels] = tuple_to_list(Result),
{RecName,
lists:map(
fun(Label) ->
case is_label(Label) of
true ->
get_label_json_type(
Label, Elem, RecTypes,
FunTypes, AllElems);
false ->
{atom, [Label]}
end
end, RecLabels)}.
merge_json_types(T, T) ->
T;
merge_json_types(ignore, T) ->
merge_json_types(T, ignore);
merge_json_types(binary, ignore) ->
{option, binary, <<>>};
merge_json_types(jid, ignore) ->
{option, jid, undefined};
merge_json_types({atom, _} = T, ignore) ->
{option, T, undefined};
merge_json_types({option, _, _} = T, ignore) ->
T;
merge_json_types({atom, A1}, {atom, A2}) ->
{atom, A1 ++ A2};
merge_json_types({option, T1, Default}, {option, T2, Default}) ->
{option, merge_json_types(T1, T2), Default};
merge_json_types({external, T1, _, _} = T, {external, T1, _, _}) ->
T;
merge_json_types([T1], T2) ->
merge_json_types(T1, T2);
merge_json_types(T1, [T2]) ->
merge_json_types(T1, T2);
merge_json_types(_T1, _T2) ->
erlang:error({internal_error, ?MODULE}).
sanitize_for_atd(Atom) when is_atom(Atom) ->
sanitize_for_atd(atom_to_binary(Atom, utf8));
sanitize_for_atd(Str) ->
string_replace(Str, <<"-">>, <<"_">>, all).
to_atd_var(Atom) when is_atom(Atom) ->
to_atd_var(atom_to_binary(Atom, utf8));
to_atd_var(<<"type">>) -> <<"type_ ">>;
to_atd_var(<<"to">>) -> <<"to_ ">>;
to_atd_var(<<"end">>) -> <<"end_ ">>;
to_atd_var(<<"class">>) -> <<"class_ ">>;
to_atd_var(<<"private">>) -> <<"private_ ">>;
to_atd_var(<<"with">>) -> <<"with_ ">>;
to_atd_var(Str) ->
sanitize_for_atd(Str).
to_atd_variant(Atom) when is_atom(Atom) ->
to_atd_variant(atom_to_binary(Atom, utf8));
to_atd_variant(S) ->
[string_titlecase(sanitize_for_atd(S)),
" "].
-ifdef(OLD_STRING).
string_replace(Str, Search, Replace, all) ->
re:replace(Str, Search, Replace, [global, {return, binary}]).
string_titlecase(S) ->
<> = S,
<<(string:to_upper(Head)), Tail/binary>>.
-else.
string_replace(Str, Search, Replace, Where) ->
string:replace(Str, Search, Replace, Where).
string_titlecase(S) ->
string:titlecase(S).
-endif.
atd_header(FileName) ->
["(* Created automatically by XML generator (fxml_gen.erl) *)", io_lib:nl(),
"(* Source: ", FileName, " *)", io_lib:nl(),
io_lib:nl(),
"type jid = {user : string; server : string; resource : string; ",
"~luser : string; ~lserver : string; ~lresource : string}", io_lib:nl(),
io_lib:nl()].
atd_value_to_string(<<>>) -> "\\\"\\\"";
atd_value_to_string(true) -> "true";
atd_value_to_string(false) -> "false";
atd_value_to_string([]) -> "[| |]".
make_registrar(ModName) ->
ResolverMod = resolver_mod(ModName),
[make_function(register_module, [?AST(Mod)],
[?AST(register_module(Mod, '?a(ResolverMod)'))]),
make_function(unregister_module, [?AST(Mod)],
[?AST(unregister_module(Mod, '?a(ResolverMod)'))])].
make_resolver(TaggedSpecs, ModName) ->
ResolverMod = resolver_mod(ModName),
TagNSMods = lists:foldl(
fun({_, #elem{xmlns = XMLNS, name = Name, module = Mod}}, Acc)
when is_list(XMLNS) ->
lists:foldl(
fun(NS, D) ->
dict:store({Name, NS}, Mod, D)
end, Acc, XMLNS);
({_, #elem{xmlns = XMLNS, name = Name, module = Mod}}, Acc) ->
dict:store({Name, XMLNS}, Mod, Acc)
end, dict:new(), TaggedSpecs),
RecordMods = lists:foldl(
fun({_, #elem{result = Result, module = Mod}}, Acc) ->
case term_is_record(Result) of
true ->
Key = {element(1, Result), tuple_size(Result)},
dict:append(Key, Mod, Acc);
false ->
Acc
end
end, dict:new(), TaggedSpecs),
NilClause1 = erl_syntax:clause([?AST(Name), ?AST(XMLNS)], none,
[?AST('?a(ResolverMod)':lookup(Name, XMLNS))]),
Clauses1 = dict:fold(
fun({Name, NS}, Mod, Acc) ->
[erl_syntax:clause(
[?AST('?a(Name)'), ?AST('?a(NS)')],
none,
[?AST('?a(Mod)')])|Acc]
end, [NilClause1], TagNSMods),
NilClause2 = erl_syntax:clause([?AST(Record)], none,
[?AST('?a(ResolverMod)':lookup(Record))]),
Clauses2 = dict:fold(
fun({RecName, RecSize}, [Mod|_], Acc) ->
[erl_syntax:clause(
[erl_syntax:tuple(
[erl_syntax:atom(RecName)|
[?AST(_) || _ <- lists:seq(1, RecSize-1)]])],
none,
[erl_syntax:atom(Mod)])|Acc]
end, [NilClause2], RecordMods),
[erl_syntax:function(?AST(get_mod), Clauses1),
erl_syntax:function(?AST(get_mod), Clauses2)].
make_top_decoders(TaggedSpecs, ModName, Opts) ->
C0 = ?AST(XMLNS = get_attr(<<"xmlns">>, Attrs, TopXMLNS)),
C1 = erl_syntax:case_expr(
?AST(get_mod(Name, XMLNS)),
[erl_syntax:clause(
[?AST(undefined)],
?AST(XMLNS == <<>>),
[?AST(erlang:error(
{'?a(ModName)', {missing_tag_xmlns, Name}}))]),
erl_syntax:clause(
[?AST(undefined)],
none,
[?AST(erlang:error(
{'?a(ModName)', {unknown_tag, Name, XMLNS}}))]),
erl_syntax:clause(
[?AST(Mod)],
none,
[?AST(Mod:do_decode(Name, XMLNS, El, Opts))])]),
[make_function("decode", [?AST(El)], [?AST(decode(El, <<>>, []))]),
make_function("decode", [?AST(El), ?AST(Opts)], [?AST(decode(El, <<>>, Opts))]),
make_function(
"decode",
[?AST({xmlel, Name, Attrs, _} = El), ?AST(TopXMLNS), ?AST(Opts)],
[C0, C1])] ++
case proplists:get_bool(json, Opts) of
true ->
make_top_decoders_json(TaggedSpecs, ModName);
false ->
[]
end.
make_top_decoders_json(TaggedSpecs, _ModName) ->
RecordMods = lists:foldl(
fun({_, #elem{result = Result, module = Mod}}, Acc) ->
case term_is_record(Result) of
true ->
Key = {element(1, Result), tuple_size(Result)},
dict:append(Key, Mod, Acc);
false ->
Acc
end
end, dict:new(), TaggedSpecs),
Clauses = dict:fold(
fun({RecName, _RecSize}, [Mod | _], Acc) ->
BRecName = atom_to_binary(RecName, utf8),
[erl_syntax:clause(
[?AST(['?a(BRecName)', _] = El)],
none,
[?AST('?a(Mod)':do_decode_json(El))]) | Acc]
end, [], RecordMods),
[erl_syntax:function(?AST(decode_json), Clauses)].
make_decoders(TaggedSpecs1, PredefRecords, ParentMod, ModName, Opts) ->
TaggedSpecs = lists:flatmap(
fun({Tag, #elem{xmlns = XMLNSs, module = Mod} = E})
when Mod == ModName ->
if is_list(XMLNSs) ->
[{Tag, E#elem{xmlns = XMLNS}} || XMLNS <- XMLNSs];
true ->
[{Tag, E}]
end;
(_) ->
[]
end, TaggedSpecs1),
NilClause = [erl_syntax:clause(
[?AST(Name), ?AST(<<>>), ?AST(_), ?AST(_)],
none,
[?AST(erlang:error(
{'?a(ParentMod)', {missing_tag_xmlns, Name}}))]),
erl_syntax:clause(
[?AST(Name), ?AST(XMLNS), ?AST(_), ?AST(_)],
none,
[?AST(erlang:error(
{'?a(ParentMod)', {unknown_tag, Name, XMLNS}}))])],
Clauses = lists:map(
fun({Tag, #elem{xmlns = XMLNS, name = Name}}) ->
erl_syntax:clause(
[?AST('?a(Name)'), ?AST('?a(XMLNS)'), ?AST(El), ?AST(Opts)],
none,
[make_function_call(
make_dec_fun_name([Tag]),
[abstract(XMLNS),
?AST(Opts),
?AST(El)])])
end, TaggedSpecs),
[erl_syntax:function(erl_syntax:atom(do_decode), Clauses ++ NilClause),
make_function(tags, [],
[erl_syntax:list(
lists:map(
fun({_, #elem{name = Name, xmlns = NS}}) ->
?AST({'?a(Name)', '?a(NS)'})
end, TaggedSpecs))])] ++
case proplists:get_bool(json, Opts) of
true ->
make_decoders_json(TaggedSpecs1, PredefRecords,
ParentMod, ModName);
false ->
[]
end.
make_decoders_json(TaggedSpecs1, PredefRecords, ParentMod, ModName) ->
TaggedSpecs =
dict:to_list(
lists:foldl(
fun({Tag, #elem{module = Mod} = E}, Acc)
when Mod == ModName ->
Result = E#elem.result,
case term_is_record(Result) of
true ->
RecName = element(1, Result),
Append =
case dict:find(RecName, Acc) of
{ok, [{_, #elem{result = Result}}]} ->
case lists:keyfind(
<<"xmlns">>, #attr.name,
E#elem.attrs) of
#attr{} ->
true;
_ ->
false
end;
_ ->
true
end,
case Append of
false ->
Acc;
true ->
dict:append(RecName, {Tag, E}, Acc)
end;
false ->
Acc
end;
(_, Acc) ->
Acc
end, dict:new(), TaggedSpecs1)),
NilClause = [erl_syntax:clause(
[?AST([Name, _])],
none,
[?AST(erlang:error(
{'?a(ParentMod)', {unknown_tag, Name}}))])],
Clauses =
lists:map(
fun({RecName, [{Tag, #elem{}}]}) ->
BRecName = atom_to_binary(RecName, utf8),
erl_syntax:clause(
[?AST(['?a(BRecName)', El])],
none,
[make_function_call(
make_dec_fun_name([Tag, json]),
[?AST(El)])]);
({RecName, [{_, El1} | _] = TEs}) ->
BRecName = atom_to_binary(RecName, utf8),
XMLNSLabel = case lists:keyfind(<<"xmlns">>, #attr.name,
El1#elem.attrs) of
#attr{label = L, name = N} ->
prepare_label(L, N);
_ ->
undefined
end,
TagField =
case size(El1#elem.result) of
2 ->
?AST(El);
_ ->
case XMLNSLabel of
undefined ->
{ok, RecFields} =
dict:find(RecName, PredefRecords),
{FName, _, _} = lists:nth(1, RecFields),
FBName = atom_to_binary(FName, utf8),
?AST(proplists:get_value(
'?a(FBName)',
element(1, El)));
_ ->
BXMLNSLabel = atom_to_binary(
label_to_record_field(
XMLNSLabel), utf8),
?AST(proplists:get_value(
'?a(BXMLNSLabel)',
element(1, El)))
end
end,
Cs = lists:map(
fun({Tag, El}) when XMLNSLabel == undefined ->
Atom = element(2, El#elem.result),
false = is_label(Atom),
BAtom = atom_to_binary(Atom, utf8),
erl_syntax:clause(
[?AST('?a(BAtom)')],
none,
[make_function_call(
make_dec_fun_name([Tag, json]),
[?AST(El)])]);
({Tag, El}) ->
XMLNS = El#elem.xmlns,
erl_syntax:clause(
[?AST('?a(XMLNS)')],
none,
[make_function_call(
make_dec_fun_name([Tag, json]),
[?AST(El)])])
end, TEs),
erl_syntax:clause(
[?AST(['?a(BRecName)', El])],
none,
[erl_syntax:case_expr(TagField, Cs)])
end, TaggedSpecs),
[erl_syntax:function(erl_syntax:atom(do_decode_json),
Clauses ++ NilClause)].
make_top_encoders(_TaggedSpecs, _ModName, Opts) ->
Clause1 = erl_syntax:clause(
[?AST({xmlel, _, _, _} = El), ?AST(_)],
none,
[?AST(El)]),
Clause2 = erl_syntax:clause(
[?AST({xmlcdata, _} = CData), ?AST(_)],
none,
[?AST(CData)]),
GetNameCase = [?AST(Mod = get_mod(El)),
?AST(Mod:do_get_name(El))],
GetNSCase = [?AST(Mod = get_mod(El)),
?AST(Mod:do_get_ns(El))],
KnownTagCase = [?AST(XMLNS = get_attr(<<"xmlns">>, Attrs, TopXMLNS)),
?AST(get_mod(Name, XMLNS) /= undefined)],
Clause3 = erl_syntax:clause(
[?AST(El), ?AST(TopXMLNS)],
none,
[?AST(Mod = get_mod(El)),
?AST(Mod:do_encode(El, TopXMLNS))]),
JClause1 = erl_syntax:clause(
[?AST({xmlel, _, _, _} = El)],
none,
[?AST(try decode(El) of
JSON -> encode_json(JSON)
catch
_:_ ->
[<<"XmlString">>, fxml:element_to_binary(El)]
end)]),
JClause3 = erl_syntax:clause(
[?AST(El)],
none,
[?AST(Mod = get_mod(El)),
?AST(Mod:do_encode_json(El))]),
[make_function(encode, [?AST(El)], [?AST(encode(El, <<>>))]),
erl_syntax:function(?AST(encode), [Clause1, Clause2, Clause3]),
case proplists:get_bool(json, Opts) of
true ->
erl_syntax:function(?AST(encode_json), [JClause1, JClause3]);
false ->
erl_syntax:comment([])
end,
make_function(get_name, [?AST(El)], GetNameCase),
make_function(get_ns, [?AST(El)], GetNSCase),
make_function(is_known_tag,
[?AST({xmlel, Name, Attrs, _}), ?AST(TopXMLNS)],
KnownTagCase),
make_function(get_els, [?AST(Term)],
[?AST(Mod = get_mod(Term)),
?AST(Mod:get_els(Term))]),
make_function(set_els, [?AST(Term), ?AST(Els)],
[?AST(Mod = get_mod(Term)),
?AST(Mod:set_els(Term, Els))])].
make_encoders(TaggedSpecs, ModName, Opts) ->
{RecNames, ResNames} =
lists:foldl(
fun({Tag, #elem{result = Result, module = Mod}}, {RecAcc, ResAcc})
when Mod == ModName ->
try
[H|_]= tuple_to_list(Result),
true = is_atom(H),
false = is_label(H),
{dict:append(H, Tag, RecAcc),
dict:append(H, Result, ResAcc)}
catch _:_ ->
{RecAcc, ResAcc}
end;
(_, Acc) ->
Acc
end, {dict:new(), dict:new()}, TaggedSpecs),
JSONEnabled = proplists:get_bool(json, Opts),
{EncClauses, EncJSONClauses, NSClauses, TagClauses, _} =
lists:foldl(
fun({Tag, #elem{name = Name, xmlns = XMLNS, module = Mod,
result = Result, attrs = Attrs}},
{EncAcc, EncJSONAcc, NSAcc, TagAcc, Seen}) ->
XMLNSLabel = case lists:keyfind(<<"xmlns">>, #attr.name, Attrs) of
#attr{label = L, name = N} ->
prepare_label(L, N);
_ ->
undefined
end,
Var = label_to_var(prepare_label(undefined, Name)),
HasXMLNSAttr = XMLNSLabel /= undefined,
EncodeResult = if HasXMLNSAttr and not is_list(XMLNS) ->
labels_to_underscores(
Result, [], [{XMLNSLabel, XMLNS}]);
true ->
labels_to_underscores(Result)
end,
EncodeResultAux = labels_to_underscores(
Result, [], [{XMLNSLabel, <<>>}]),
NSResult = labels_to_underscores(Result, [XMLNSLabel]),
TagResult = labels_to_underscores(Result),
try
[H|_]= tuple_to_list(Result),
true = is_atom(H),
false = is_label(H),
Tags = dict:fetch(H, RecNames),
OtherResults = dict:fetch(H, ResNames) -- [Result],
true = lists:member(Tag, Tags),
IsDuplicated = lists:member(Result, OtherResults),
AlreadySeen = lists:member(Result, Seen),
{if AlreadySeen ->
EncAcc;
true ->
Call = [make_function_call(
make_enc_fun_name(ModName, Mod, [Tag]),
[Var, ?AST(TopXMLNS)])],
[erl_syntax:clause(
[?AST('?EncodeResult' = '?Var'), ?AST(TopXMLNS)],
none, Call)] ++
if HasXMLNSAttr and not is_list(XMLNS) ->
[erl_syntax:clause(
[?AST('?EncodeResultAux' = '?Var'),
?AST(TopXMLNS = '?a(XMLNS)')],
none, Call)];
true ->
[]
end ++ EncAcc
end,
if AlreadySeen or not JSONEnabled ->
EncJSONAcc;
true ->
Call = make_function_call(
make_enc_fun_name(ModName, Mod,
[Tag, json]),
[Var]),
BRecName = atom_to_binary(H, utf8),
ResJSON = ?AST(['?a(BRecName)', '?Call']),
[erl_syntax:clause(
[?AST('?EncodeResult' = '?Var')],
none,
[ResJSON])] ++ EncJSONAcc
end,
if IsDuplicated ->
NSAcc;
HasXMLNSAttr ->
[erl_syntax:clause(
[NSResult], none,
[label_to_var(XMLNSLabel)])|NSAcc];
is_list(XMLNS) ->
[erl_syntax:clause(
[NSResult], none,
[abstract(hd(XMLNS))])|NSAcc];
true ->
[erl_syntax:clause(
[NSResult], none,
[abstract(XMLNS)])|NSAcc]
end,
if AlreadySeen ->
TagAcc;
true ->
[erl_syntax:clause(
[TagResult], none,
[abstract(Name)])|TagAcc]
end,
[Result|Seen]}
catch _:_ ->
{EncAcc, EncJSONAcc, NSAcc, TagAcc, Seen}
end
end, {[], [], [], [], []}, TaggedSpecs),
if EncClauses /= [] ->
[erl_syntax:function(?AST(do_encode), EncClauses)];
true -> []
end ++
if EncJSONClauses /= [] ->
[erl_syntax:function(?AST(do_encode_json), EncJSONClauses)];
true -> []
end ++
if TagClauses /= [] ->
[erl_syntax:function(?AST(do_get_name), lists:usort(TagClauses))];
true -> []
end ++
if NSClauses /= [] ->
[erl_syntax:function(?AST(do_get_ns), lists:usort(NSClauses))];
true -> []
end.
make_printer(TaggedSpecs, PredefRecords, ModName, ParentMod) ->
PassClause1 =
if ModName == ParentMod ->
[erl_syntax:clause(
[?AST(xmlel), ?AST(3)],
none,
[?AST([name, attrs, children])]),
erl_syntax:clause(
[?AST(Name), ?AST(Arity)],
none,
[erl_syntax:try_expr(
[?AST(get_mod(
erlang:make_tuple(Arity+1, undefined, [{1, Name}])))],
[erl_syntax:clause(
[?AST(Mod)],
none,
[?AST(Mod:pp(Name, Arity))])],
[erl_syntax:clause(
[?AST(error:badarg)], none, [?AST(no)])])])];
true ->
[erl_syntax:clause([?AST(_), ?AST(_)], none, [?AST(no)])]
end,
%% Exclude tags with duplicated results
RecNames = lists:foldl(
fun({Tag, #elem{result = Result, module = Mod}}, Acc)
when Mod == ModName ->
try
[H|_]= tuple_to_list(Result),
true = is_atom(H),
false = is_label(H),
dict:append(H, Tag, Acc)
catch _:_ ->
Acc
end;
(_, Acc) ->
Acc
end, dict:new(), TaggedSpecs),
{Clauses1, Records} =
lists:foldl(
fun({Tag, #elem{result = Result}}, {Acc1, Acc2}) ->
try
[H|T]= tuple_to_list(Result),
true = is_atom(H),
false = is_label(H),
[Tag|_] = dict:fetch(H, RecNames),
Fields = case dict:find(H, PredefRecords) of
{ok, Fs} ->
[FName || {FName, _, _} <- Fs];
error ->
[label_to_record_field(F) || F <- T]
end,
{[erl_syntax:clause(
[erl_syntax:atom(H), abstract(length(T))],
none,
[erl_syntax:list(
[erl_syntax:atom(F) || F <- Fields])])
|Acc1],
[{H, length(T)}|Acc2]}
catch _:_ ->
{Acc1, Acc2}
end
end, {[], []}, TaggedSpecs),
[erl_syntax:function(?AST(pp), Clauses1 ++ PassClause1),
make_function(records, [],
[erl_syntax:list(
lists:map(
fun({RecName, RecSize}) ->
?AST({'?a(RecName)', '?a(RecSize)'})
end, Records))])].
make_getters_setters(TaggedSpecs, PredefRecords, ModName) ->
RecNames = lists:foldl(
fun({Tag, #elem{result = Result, module = Mod}}, Acc)
when Mod == ModName ->
try
[H|_]= tuple_to_list(Result),
true = is_atom(H),
false = is_label(H),
dict:append(H, Tag, Acc)
catch _:_ ->
Acc
end;
(_, Acc) ->
Acc
end, dict:new(), TaggedSpecs),
{Getters, Setters} =
lists:foldl(
fun({Tag, #elem{result = Result}}, {Acc1, Acc2}) ->
try
[H|T]= tuple_to_list(Result),
true = is_atom(H),
false = is_label(H),
[Tag|_] = dict:fetch(H, RecNames),
Fields = case dict:find(H, PredefRecords) of
{ok, Fs} ->
[FName || {FName, _, _} <- Fs];
error ->
[label_to_record_field(F) || F <- T]
end,
case lists:member(sub_els, Fields) of
false ->
{Acc1, Acc2};
true ->
{[erl_syntax:clause(
[record_fields_to_vars(H, Fields)],
none,
[?AST(_sub_els)])|Acc1],
[erl_syntax:clause(
[record_fields_to_vars(H, Fields, [{sub_els, ?AST(_)}]),
?AST(_sub_els)],
none,
[record_fields_to_vars(
H, Fields, [{sub_els, ?AST(_sub_els)}])])|Acc2]}
end
catch _:_ ->
{Acc1, Acc2}
end
end, {[], []}, TaggedSpecs),
case {Getters, Setters} of
{[], []} ->
[];
_ ->
[erl_syntax:function(?AST(get_els), Getters),
erl_syntax:function(?AST(set_els), Setters)]
end.
elem_to_AST(#elem{name = Name, xmlns = XMLNS, cdata = CData,
result = Result, attrs = Attrs, refs = _Refs} = Elem,
Tag, AllElems, Types, ModName, PredefRecords, FunSpecs, Opts) ->
AttrAST = lists:flatmap(
fun(#attr{name = AttrName,
required = Required,
dec = AttrDecF,
enc = AttrEncF,
always_encode = AlwaysEnc,
default = AttrDefault}) ->
make_decoding_MFA([AttrName,attr,Tag],
Name, XMLNS, AttrName,
Required, AttrDefault,
AttrDecF, Types, ModName) ++
make_encoding_MFA([AttrName,attr,Tag],
AttrName, Required, AttrDefault,
AttrEncF, AlwaysEnc)
end, Attrs),
#cdata{label = CDataLabl,
required = CDataRequired,
dec = CDataDecF,
enc = CDataEncF,
default = CDataDefault} = CData,
CDataAST =
case have_label(Result, CDataLabl) of
true ->
make_decoding_MFA([cdata,Tag], Name, XMLNS, <<>>,
CDataRequired, CDataDefault,
CDataDecF, Types, ModName) ++
make_encoding_MFA([cdata,Tag], <<>>,
CDataRequired, CDataDefault,
CDataEncF, false);
false ->
[]
end,
DecAST = make_elem_dec_fun(Elem, Tag, AllElems, Types,
ModName, PredefRecords, Opts),
DecJsonAST =
case proplists:get_bool(json, Opts) of
true ->
make_elem_dec_fun_json(Elem, Tag, AllElems, Types,
ModName, FunSpecs, PredefRecords);
false ->
[]
end,
EncAST = make_elem_enc_fun(Elem, Tag, AllElems, ModName),
EncJsonAST =
case proplists:get_bool(json, Opts) of
true ->
make_elem_enc_fun_json(Elem, Tag, AllElems, ModName,
Types, FunSpecs, PredefRecords);
false ->
[]
end,
DecAST ++ DecJsonAST ++ EncAST ++ EncJsonAST ++ AttrAST ++ CDataAST.
%% Replace in `Term' every label found in `Labels'
%% with the corresponding value.
subst_labels(Term) ->
subst_labels(Term, undefined).
subst_labels(Term, PredefRecords) ->
case have_label(Term, '$_') of
true when PredefRecords /= undefined ->
try
true = term_is_record(Term),
[H|Elems] = erl_syntax:tuple_elements(abstract(Term)),
RecName = erl_syntax:atom_value(H),
RecFields = dict:fetch(RecName, PredefRecords),
Vars = lists:map(
fun({T, {_, Default, _}}) ->
AbsDefault = if Default == none ->
?AST(undefined);
true ->
Default
end,
try
Label = erl_syntax:atom_value(T),
true = is_label(Label),
case Label of
'$_' -> AbsDefault;
_ -> label_to_var(Label)
end
catch _:_ ->
T
end
end, lists:zip(Elems, RecFields)),
erl_syntax:tuple([H|Vars])
catch error:{badmatch, false} ->
bad_spec({underscore_label_outside_record_tuple, Term});
_:_ ->
bad_spec({no_predefined_record_found, Term})
end;
_ ->
erl_syntax_lib:map(
fun(T) ->
try
Label = erl_syntax:atom_value(T),
true = is_label(Label),
label_to_var(Label)
catch _:_ ->
T
end
end, abstract(Term))
end.
get_elem_by_ref(RefName, TaggedElems) ->
{_, Elem} = lists:keyfind(RefName, 1, TaggedElems),
Elem.
get_spec_by_label('$_els', _Elem) ->
sub_els;
get_spec_by_label('$_', _Elem) ->
'_';
get_spec_by_label(Label, Elem) ->
[Spec|T] = lists:flatmap(
fun(#cdata{label = L} = CData) when Label == L ->
[CData];
(#attr{label = L, name = N} = Attr) ->
case prepare_label(L, N) of
Label ->
[Attr];
_ ->
[]
end;
(#ref{label = L, name = N} = Ref) ->
case prepare_label(L, N) of
Label ->
[Ref];
_ ->
[]
end;
(_) ->
[]
end, [Elem#elem.cdata|Elem#elem.attrs ++ Elem#elem.refs]),
if is_record(Spec, ref) ->
[Spec|T];
true ->
Spec
end.
group_refs(Refs) ->
dict:to_list(
lists:foldl(
fun(#ref{name = Name, label = Label} = Ref, G) ->
L = prepare_label(Label, Name),
dict:append_list(L, [Ref], G)
end, dict:new(), Refs)).
make_elem_dec_fun(#elem{name = Name, result = Result, refs = Refs, module = Mod,
cdata = CData, attrs = Attrs, xmlns = XMLNS,
ignore_els = IgnoreEls},
Tag, AllElems, Types, ModName, PredefRecords, Opts) ->
FunName = make_dec_fun_name([Tag]),
ResultWithVars = subst_labels(Result, PredefRecords),
AttrVars = lists:map(
fun(#attr{name = AttrName, label = AttrLabel}) ->
label_to_var(prepare_label(AttrLabel, AttrName))
end, Attrs),
HaveCData = have_label(Result, CData#cdata.label),
CDataVars = if HaveCData ->
[label_to_var(CData#cdata.label)];
true ->
[]
end,
SubElVars = case have_label(Result, '$_els') of
true ->
[label_to_var('$_els')];
false ->
[]
end,
ElemVars = lists:map(
fun({Label, _}) ->
label_to_var(Label)
end, group_refs(Refs)),
AttrMatch =
if AttrVars /= [] ->
AttrPattern = tuple_or_single_var(AttrVars),
AttrCall = make_function_call(
FunName ++ "_attrs",
[?AST(__TopXMLNS),
?AST(_attrs)|
lists:map(
fun(_) ->
?AST(undefined)
end, Attrs)]),
[erl_syntax:match_expr(AttrPattern, AttrCall)];
true ->
[]
end,
ElCDataMatch =
case CDataVars ++ ElemVars ++ SubElVars of
[] ->
[];
_ ->
[erl_syntax:match_expr(
tuple_or_single_var(CDataVars ++ ElemVars ++ SubElVars),
make_function_call(
FunName ++ "_els",
[?AST(__TopXMLNS),
?AST(__Opts),
?AST(_els)|
lists:flatmap(
fun({_, [#ref{min = 0, max = 1, default = Def}|_]}) ->
[abstract(Def)];
({_, [#ref{min = 1, max = 1}|_]}) ->
[?AST(error)];
(#cdata{}) when HaveCData ->
[?AST(<<>>)];
(#cdata{}) ->
[];
(_) ->
[?AST([])]
end, [CData|group_refs(Refs)] ++ SubElVars)]))]
end,
[make_function(
FunName,
[?AST(__TopXMLNS),
?AST(__Opts),
?AST({xmlel, '?a(Name)', _attrs, _els})],
ElCDataMatch ++ AttrMatch ++ [ResultWithVars])]
++ make_els_dec_fun(Mod, FunName ++ "_els", CData, HaveCData, SubElVars,
Refs, Tag, XMLNS, AllElems,
Result, Types, ModName, IgnoreEls, Opts)
++ make_attrs_dec_fun(FunName ++ "_attrs", Attrs, Tag).
make_els_dec_clause(ParentMod, ModName, FunName, CDataVars, Refs, _TopXMLNS,
AllElems, Result, {_SortedTags, Types, _RecDict}, _Opts) ->
SubElVars = case have_label(Result, '$_els') of
true ->
[label_to_var('$_els')];
false ->
[]
end,
lists:map(
fun(#ref{name = RefName, label = RefLabel}) ->
Label = prepare_label(RefLabel, RefName),
Var = label_to_var(Label),
RefElem = get_elem_by_ref(RefName, AllElems),
RefMod = RefElem#elem.module,
XMLNSs = lists:flatten([RefElem#elem.xmlns]),
ElemVars = lists:map(
fun({Labl, _}) ->
label_to_var(Labl)
end, group_refs(Refs)),
NewElemVars =
fun(NS) ->
lists:map(
fun({L, [#ref{min = Min, max = 1}|_]})
when L == Label ->
Call = make_function_call(
make_dec_fun_name(ModName, RefMod, [RefName]),
[NS,
?AST(__Opts),
?AST(_el)]),
if Min == 0 ->
Call;
Min == 1 ->
?AST({value, '?Call'})
end;
({L, [#ref{default = Def}]}) when L == Label ->
RefType = dict:fetch(RefName, Types),
case is_subtype(Def, RefType) of
true ->
erl_syntax:case_expr(
make_function_call(
make_dec_fun_name(ModName, RefMod, [RefName]),
[NS,
?AST(__Opts),
?AST(_el)]),
[erl_syntax:clause(
[abstract(Def)], none, [Var]),
erl_syntax:clause(
[?AST(_new_el)],
none,
[?AST([_new_el | '?Var'])])]);
false ->
erl_syntax:list(
[make_function_call(
make_dec_fun_name(ModName, RefMod, [RefName]),
[NS,
?AST(__Opts),
?AST(_el)])],
Var)
end;
({L, _}) ->
label_to_var(L)
end, group_refs(Refs))
end,
erl_syntax:clause(
[?AST(__TopXMLNS),
?AST(__Opts),
?AST([{xmlel, '?a(RefElem#elem.name)', _attrs, _} = _el | _els])|
CDataVars ++ ElemVars ++ SubElVars],
none,
[erl_syntax:case_expr(
?AST('?a(ParentMod)':get_attr(<<"xmlns">>, _attrs, __TopXMLNS)),
lists:map(
fun(NS) ->
erl_syntax:clause(
[abstract(NS)],
none,
[make_function_call(
FunName,
[?AST(__TopXMLNS),
?AST(__Opts),
?AST(_els)|CDataVars ++ NewElemVars(abstract(NS))
++ SubElVars])])
end, XMLNSs)
++
[erl_syntax:clause(
[?AST(_)], none,
[make_function_call(
FunName,
[?AST(__TopXMLNS),
?AST(__Opts),
?AST(_els)|CDataVars ++ ElemVars
++ case SubElVars of
[] -> [];
_ -> [erl_syntax:list(
[?AST(_el)],
label_to_var('$_els'))]
end])])])])
end, Refs).
make_els_dec_fun(_, _FunName, _CData, false, [], [], _Tag,
_TopXMLNS, _AllElems, _Result, _Types, _ModName,
_IgnoreEls, _Opts) ->
[];
make_els_dec_fun(Mod, FunName, CData, HaveCData, SubElVars, Refs, Tag,
TopXMLNS, AllElems, Result, Types, ModName, IgnoreEls, Opts) ->
CDataVars = if HaveCData ->
[label_to_var(CData#cdata.label)];
true ->
[]
end,
ElemVars = lists:map(
fun({Label, _}) ->
label_to_var(Label)
end, group_refs(Refs)),
ResultCData = if HaveCData ->
[erl_syntax:binary(
[erl_syntax:binary_field(
hd(CDataVars),
[?AST(binary)]),
erl_syntax:binary_field(
?AST(_data),
[?AST(binary)])])];
true ->
[]
end,
CDataClause = if HaveCData ->
[erl_syntax:clause(
[?AST(__TopXMLNS),
?AST(__Opts),
erl_syntax:list(
[?AST({xmlcdata, _data})],
?AST(_els))
|CDataVars ++ ElemVars ++ SubElVars],
none,
[make_function_call(
FunName,
[?AST(__TopXMLNS),
?AST(__Opts),
?AST(_els)|
ResultCData ++ ElemVars ++ SubElVars])])];
true ->
[]
end,
ElemClauses = make_els_dec_clause(ModName, Mod, FunName, CDataVars,
Refs, TopXMLNS, AllElems, Result,
Types, Opts),
ResultElems = lists:map(
fun({L, [#ref{min = 0, max = 1}|_]}) ->
label_to_var(L);
({L, [#ref{min = 1, max = 1, name = RefName}]}) ->
RefElem = get_elem_by_ref(RefName, AllElems),
L1 = list_to_atom(atom_to_list(L) ++ "1"),
erl_syntax:case_expr(
label_to_var(L),
[erl_syntax:clause(
[?AST(error)],
none,
[?AST(erlang:error(
{'?a(ModName)',
{missing_tag,
'?a(RefElem#elem.name)',
__TopXMLNS}}))]),
erl_syntax:clause(
[erl_syntax:tuple(
[?AST(value),
label_to_var(L1)])],
none,
[label_to_var(L1)])]);
({L, [#ref{min = 0, max = infinity}|_]}) ->
make_function_call(
{lists, reverse}, [label_to_var(L)])
end, group_refs(Refs)),
CDataCall = if HaveCData ->
[make_function_call(
make_dec_fun_name([cdata,Tag]),
[?AST(__TopXMLNS)|CDataVars])];
true ->
[]
end,
SubElResult = case have_label(Result, '$_els') of
true ->
[make_function_call(
{lists, reverse},
[label_to_var('$_els')])];
false ->
[]
end,
NilClause = erl_syntax:clause(
[?AST(__TopXMLNS),
?AST(__Opts),
?AST([])|
CDataVars ++
lists:map(
fun({L, _}) ->
label_to_var(L)
end, group_refs(Refs)) ++ SubElVars],
none,
[tuple_or_single_var(
CDataCall ++ ResultElems ++ SubElResult)]),
SubElPattern = [?AST(__TopXMLNS),
?AST(__Opts),
erl_syntax:list(
[?AST({xmlel, _name, _attrs, _} = _el)],
?AST(_els))
|CDataVars ++ ElemVars ++ SubElVars],
SubElClause =
case have_label(Result, '$_els') of
true when IgnoreEls ->
SubElBody = make_function_call(
FunName,
[?AST(__TopXMLNS),
?AST(__Opts),
?AST(_els)|CDataVars ++ ElemVars] ++
[erl_syntax:list(
[?AST(_el)],
label_to_var('$_els'))]),
[erl_syntax:clause(SubElPattern, none, [SubElBody])];
true ->
SubElBody = erl_syntax:case_expr(
?AST(proplists:get_bool(ignore_els, __Opts)),
[erl_syntax:clause(
[?AST(true)],
none,
[make_function_call(
FunName,
[?AST(__TopXMLNS),
?AST(__Opts),
?AST(_els)|CDataVars ++ ElemVars] ++
[erl_syntax:list(
[?AST(_el)],
label_to_var('$_els'))])]),
erl_syntax:clause(
[?AST(false)],
none,
[?AST(__XMLNS = '?a(ModName)':get_attr(
<<"xmlns">>, _attrs, __TopXMLNS)),
erl_syntax:case_expr(
?AST('?a(ModName)':get_mod(_name, __XMLNS)),
[erl_syntax:clause(
[?AST(undefined)],
none,
[make_function_call(
FunName,
[?AST(__TopXMLNS),
?AST(__Opts),
?AST(_els)|CDataVars ++ ElemVars] ++
[erl_syntax:list(
[?AST(_el)],
label_to_var('$_els'))])]),
erl_syntax:clause(
[?AST(Mod)],
none,
[make_function_call(
FunName,
[?AST(__TopXMLNS),
?AST(__Opts),
?AST(_els)|CDataVars ++ ElemVars] ++
[erl_syntax:list(
[?AST(Mod:do_decode(_name, __XMLNS, _el, __Opts))],
label_to_var('$_els'))])])])])]),
[erl_syntax:clause(SubElPattern, none, [SubElBody])];
false ->
[]
end,
PassClause = if SubElVars == []; CDataVars == [] ->
[erl_syntax:clause(
[?AST(__TopXMLNS),
?AST(__Opts),
?AST([_ | _els])|
CDataVars ++ ElemVars ++ SubElVars],
none,
[make_function_call(
FunName,
[?AST(__TopXMLNS),
?AST(__Opts), ?AST(_els)
|CDataVars ++ ElemVars ++ SubElVars])])];
true ->
[]
end,
[erl_syntax:function(
erl_syntax:atom(FunName),
[NilClause|CDataClause ++ ElemClauses ++ SubElClause ++ PassClause])].
make_attrs_dec_fun(FunName, Attrs, Tag) ->
AttrVars = lists:map(
fun(#attr{name = AttrName, label = AttrLabel}) ->
label_to_var(prepare_label(AttrLabel, AttrName))
end, Attrs),
Clauses =
lists:map(
fun(#attr{name = Name, label = Label}) ->
Var = label_to_var(prepare_label(Label, Name)),
Pattern = [?AST(__TopXMLNS),
?AST([{'?a(Name)', _val} | _attrs]) |
lists:map(
fun(V) when V == Var ->
VName = erl_syntax:variable_literal(V),
erl_syntax:variable("_" ++ VName);
(V) ->
V
end, AttrVars)],
Body = [make_function_call(
FunName,
[?AST(__TopXMLNS), ?AST(_attrs) |
lists:map(
fun(V) when V == Var ->
?AST(_val);
(V) ->
V
end, AttrVars)])],
erl_syntax:clause(Pattern, none, Body)
end, Attrs),
if Clauses /= [] ->
PassClause = erl_syntax:clause(
[?AST(__TopXMLNS), ?AST([_|_attrs])|AttrVars],
none,
[make_function_call(
FunName,
[?AST(__TopXMLNS), ?AST(_attrs)|AttrVars])]),
Result = lists:map(
fun(#attr{name = Name, label = Label}) ->
Var = label_to_var(prepare_label(Label, Name)),
make_function_call(
make_dec_fun_name([Name,attr,Tag]),
[?AST(__TopXMLNS), Var])
end, Attrs),
NilClause = erl_syntax:clause(
[?AST(__TopXMLNS), ?AST([])|AttrVars],
none,
[tuple_or_single_var(Result)]),
[erl_syntax:function(
erl_syntax:atom(FunName),
Clauses ++ [PassClause, NilClause])];
true ->
[]
end.
make_ref_enc_funs(Elem, Tag, AllElems) ->
ModName = Elem#elem.module,
lists:map(
fun({L, [#ref{min = Min, max = Max, default = Default}|_] = Refs}) ->
DefaultClause = if Min == 0, Max == 1 ->
[erl_syntax:clause(
[abstract(Default), ?AST(__TopXMLNS),
?AST(_acc)],
none, [?AST(_acc)])];
Min == 1, Max == 1 ->
[];
true ->
[erl_syntax:clause(
[?AST([]), ?AST(__TopXMLNS), ?AST(_acc)],
none, [?AST(_acc)])]
end,
Var = label_to_var(L),
Clauses =
lists:map(
fun(#ref{name = RefName, max = 1}) ->
RefElem = get_elem_by_ref(RefName, AllElems),
RefMod = RefElem#elem.module,
Pattern =
if length(Refs) > 1 ->
MatchVar = erl_syntax:match_expr(
labels_to_underscores(
RefElem#elem.result),
Var),
[MatchVar, ?AST(__TopXMLNS), ?AST(_acc)];
true ->
[Var, ?AST(__TopXMLNS), ?AST(_acc)]
end,
erl_syntax:clause(
Pattern,
none,
[erl_syntax:list(
[make_function_call(
make_enc_fun_name(ModName, RefMod, [RefName]),
[Var, ?AST(__TopXMLNS)])],
?AST(_acc))]);
(#ref{name = RefName}) ->
RefElem = get_elem_by_ref(RefName, AllElems),
RefMod = RefElem#elem.module,
Pattern =
if length(Refs) > 1 ->
erl_syntax:match_expr(
labels_to_underscores(
RefElem#elem.result),
Var);
true ->
Var
end,
erl_syntax:clause(
[?AST(['?Pattern' | _els]), ?AST(__TopXMLNS), ?AST(_acc)],
none,
[make_function_call(
make_enc_fun_name([L,Tag]),
[?AST(_els),
?AST(__TopXMLNS),
erl_syntax:list(
[make_function_call(
make_enc_fun_name(ModName, RefMod, [RefName]),
[Var, ?AST(__TopXMLNS)])],
?AST(_acc))])])
end, Refs),
erl_syntax:function(
erl_syntax:atom(make_enc_fun_name([L,Tag])),
DefaultClause ++ Clauses)
end, group_refs(Elem#elem.refs)).
make_elem_dec_fun_json(
#elem{result = Result} = Elem,
Tag, AllElems, Types, ModName, FunTypes, PredefRecords) ->
{_Tags, RecTypes, _RecDict} = Types,
case term_is_record(Result) of
true ->
ResultWithVars = subst_labels(Result, PredefRecords),
[RecName | RecLabels] = tuple_to_list(Result),
RecLabels2 =
lists:filter(
fun(Label) ->
case is_atom(Label) andalso is_label(Label) of
true ->
JSONType = get_label_json_type(
Label, Elem, RecTypes,
FunTypes, AllElems),
case JSONType of
ignore ->
false;
_ ->
true
end;
false ->
false
end
end, RecLabels),
case RecLabels of
[Label] ->
Res =
case is_label(Label) of
true ->
JSONType = get_label_json_type(
Label, Elem, RecTypes,
FunTypes, AllElems),
decode_json_field2(
JSONType, ?AST(_value),
Elem#elem.module, ModName);
false ->
BLabel = atom_to_binary(Label, utf8),
?AST('?a(BLabel)')
end,
[erl_syntax:function(
erl_syntax:atom(make_dec_fun_name([Tag, json])),
[erl_syntax:clause(
[?AST(_value)],
none,
[?AST({'?a(RecName)', '?Res'})]
)])];
_ ->
case RecLabels2 of
[] ->
[erl_syntax:function(
erl_syntax:atom(make_dec_fun_name([Tag, json])),
[erl_syntax:clause(
[?AST(_)],
none,
[ResultWithVars]
)])];
_ ->
DecCall = make_function_call(
make_dec_fun_name([fields, Tag, json]),
[?AST(_fields)|
lists:map(
fun(_) ->
?AST(undefined)
end, RecLabels2)]),
DecTuple =
tuple_or_single_var(
lists:map(fun label_to_var/1, RecLabels2)),
[erl_syntax:function(
erl_syntax:atom(make_dec_fun_name([Tag, json])),
[erl_syntax:clause(
[?AST({_fields})],
none,
[?AST('?DecTuple' = '?DecCall')] ++
[ResultWithVars]
)])]
++ make_json_fields_dec_fun(
make_dec_fun_name([fields, Tag, json]),
RecLabels2,
Elem, RecTypes, FunTypes, AllElems,
ModName)
end
end;
false when is_tuple(Result) ->
RecLabels = tuple_to_list(Result),
Res = lists:map(
fun(Label) ->
Var = label_to_var(Label),
JSONType = get_label_json_type(
Label, Elem, RecTypes,
FunTypes, AllElems),
decode_json_field(
JSONType, Var,
Elem#elem.module, ModName)
end, RecLabels),
[erl_syntax:function(
erl_syntax:atom(make_dec_fun_name([Tag, json])),
[erl_syntax:clause(
[erl_syntax:list(lists:map(fun label_to_var/1, RecLabels))],
none,
[erl_syntax:tuple(Res)]
)])];
false when is_atom(Result) ->
Label = Result,
Res =
case is_label(Label) of
true ->
JSONType = get_label_json_type(
Label, Elem, RecTypes,
FunTypes, AllElems),
decode_json_field2(
JSONType, ?AST(_val),
Elem#elem.module, ModName);
false ->
BLabel = atom_to_binary(Label, utf8),
?AST('?a(BLabel)')
end,
[erl_syntax:function(
erl_syntax:atom(make_dec_fun_name([Tag, json])),
[erl_syntax:clause(
[?AST(_val)],
none,
[Res]
)])];
false ->
[]
end.
make_json_fields_dec_fun(FunName, Attrs,
Elem, RecTypes, FunTypes, AllElems, ModName) ->
AttrVars = lists:map(fun label_to_var/1, Attrs),
Clauses =
lists:map(
fun(Label) ->
FName = label_to_record_field(Label),
FBName = atom_to_binary(FName, utf8),
Var = label_to_var(Label),
Pattern = [?AST([{'?a(FBName)', _val} | _fields]) |
lists:map(
fun(V) when V == Var ->
VName = erl_syntax:variable_literal(V),
erl_syntax:variable("_" ++ VName);
(V) ->
V
end, AttrVars)],
Body = [make_function_call(
FunName,
[?AST(_fields) |
lists:map(
fun(V) when V == Var ->
?AST(_val);
(V) ->
V
end, AttrVars)])],
erl_syntax:clause(Pattern, none, Body)
end, Attrs),
if Clauses /= [] ->
PassClause = erl_syntax:clause(
[?AST([_ | _fields]) | AttrVars],
none,
[make_function_call(
FunName,
[?AST(_fields) | AttrVars])]),
Result = lists:map(
fun(Label) ->
Var = label_to_var(Label),
JSONType = get_label_json_type(
Label, Elem, RecTypes,
FunTypes, AllElems),
decode_json_field(
JSONType, Var,
Elem#elem.module, ModName)
end, Attrs),
NilClause = erl_syntax:clause(
[?AST([]) | AttrVars],
none,
[tuple_or_single_var(Result)]),
[erl_syntax:function(
erl_syntax:atom(FunName),
Clauses ++ [PassClause, NilClause])];
true ->
[]
end.
make_elem_enc_fun(#elem{result = Result, attrs = Attrs,
name = ElemName, xmlns = XMLNS,
cdata = CData, refs = Refs} = Elem,
Tag, AllElems, ModName) ->
CDataLabel = CData#cdata.label,
HaveCData = have_label(Result, CDataLabel),
HaveRefs = Refs /= [],
HaveEls = have_label(Result, '$_els'),
NewTopXMLNSCall =
make_function_call(
{ModName, choose_top_xmlns},
case lists:keyfind(<<"xmlns">>, #attr.name, Attrs) of
#attr{label = L, name = N} ->
if is_list(XMLNS) ->
[label_to_var(prepare_label(L, N)),
erl_syntax:list([abstract(NS) || NS <- XMLNS])];
true ->
[label_to_var(prepare_label(L, N)),
erl_syntax:list([abstract(XMLNS)])]
end;
false when is_list(XMLNS) ->
[?AST(<<>>), erl_syntax:list([abstract(NS) || NS <- XMLNS])];
false ->
[abstract(XMLNS), ?AST([])]
end ++ [?AST(__TopXMLNS)]),
SubElGenerator = case have_label(Result, '$_els') of
true ->
erl_syntax:list_comp(
?AST('?a(ModName)':encode(_el, __NewTopXMLNS)),
[erl_syntax:generator(
?AST(_el),
label_to_var('$_els'))]);
false ->
?AST([])
end,
RefsFun = lists:foldr(
fun({Label, _}, Acc) ->
Var = label_to_var(Label),
make_function_call(
make_enc_fun_name([Label,Tag]),
[Var, ?AST(__NewTopXMLNS), Acc])
end, ?AST([]), group_refs(Refs)),
CDataFun = if HaveRefs and HaveCData ->
make_function_call(
{lists, reverse},
[make_function_call(make_enc_fun_name([cdata,Tag]),
[label_to_var(CDataLabel),
RefsFun])]);
HaveRefs and not HaveCData ->
?AST(lists:reverse('?RefsFun'));
HaveCData and not HaveRefs ->
make_function_call(make_enc_fun_name([cdata,Tag]),
[label_to_var(CDataLabel),
?AST([])]);
true ->
?AST([])
end,
ResFun = if (HaveCData or HaveRefs) and HaveEls ->
?AST('?SubElGenerator' ++ '?CDataFun');
HaveCData or HaveRefs ->
CDataFun;
HaveEls ->
SubElGenerator;
true ->
?AST([])
end,
AttrFun = lists:foldl(
fun(#attr{name = AttrName, label = AttrLabel}, Acc)
when AttrName /= <<"xmlns">> ->
Var = label_to_var(prepare_label(AttrLabel, AttrName)),
make_function_call(
make_enc_fun_name([AttrName,attr,Tag]),
[Var, Acc]);
(_, Acc) ->
Acc
end, ?AST('?a(ModName)':enc_xmlns_attrs(__NewTopXMLNS, __TopXMLNS)), Attrs),
[erl_syntax:function(
erl_syntax:atom(make_enc_fun_name([Tag])),
[erl_syntax:clause(
[subst_labels(Result), ?AST(__TopXMLNS)],
none,
[?AST(__NewTopXMLNS = '?NewTopXMLNSCall'),
?AST(_els = '?ResFun'),
?AST(_attrs = '?AttrFun'),
?AST({xmlel, '?a(ElemName)', _attrs, _els})
])])] ++ make_ref_enc_funs(Elem, Tag, AllElems).
make_elem_enc_fun_json(
#elem{result = Result} = Elem,
Tag, AllElems, ModName, Types, FunTypes, PredefRecords) ->
case term_is_record(Result) of
true ->
{_Tags, RecTypes, _RecDict} = Types,
[RecName | RecLabels] = tuple_to_list(Result),
ConvertLabelFun =
fun(Label, {K, ASTs}) ->
InVar = erl_syntax:variable(
"_fields" ++ integer_to_list(K)),
OutVar = erl_syntax:variable(
"_fields" ++ integer_to_list(K + 1)),
case is_label(Label) of
true ->
FName = label_to_record_field(Label),
FBName = atom_to_binary(FName, utf8),
JSONType = get_label_json_type(
Label, Elem, RecTypes,
FunTypes, AllElems),
Value =
encode_json_field(
JSONType, Label, InVar, FBName,
Elem#elem.module, ModName),
Assign = ?AST('?OutVar' = '?Value'),
%erl_syntax:tuple([?AST('?a(FBName)'), Value]),
{K + 1, [Assign | ASTs]};
false ->
{ok, RecFields} = dict:find(RecName, PredefRecords),
{FName, _, _} = lists:nth(K + 1, RecFields),
FBName = atom_to_binary(FName, utf8),
BLabel = atom_to_binary(Label, utf8),
Value = ?AST([{'?a(FBName)', '?a(BLabel)'} |
'?InVar']),
Assign = ?AST('?OutVar' = '?Value'),
{K + 1, [Assign | ASTs]}
end
end,
case RecLabels of
[] ->
[erl_syntax:function(
erl_syntax:atom(make_enc_fun_name([Tag, json])),
[erl_syntax:clause(
[?AST({'?a(RecName)'})],
none,
[?AST(null)]
)])];
[Label] ->
Res =
case is_label(Label) of
true ->
JSONType = get_label_json_type(
Label, Elem, RecTypes,
FunTypes, AllElems),
encode_json_field2(
JSONType, ?AST(_val),
Elem#elem.module, ModName);
false ->
BLabel = atom_to_binary(Label, utf8),
?AST('?a(BLabel)')
end,
[erl_syntax:function(
erl_syntax:atom(make_enc_fun_name([Tag, json])),
[erl_syntax:clause(
[?AST({'?a(RecName)', _val})],
none,
[Res]
)])];
_ ->
{K, MakeJSON} =
lists:foldl(ConvertLabelFun, {0, []}, RecLabels),
RecFieldsJSON = erl_syntax:variable("_fields" ++ integer_to_list(K)),
%RecFieldsJSON =
% erl_syntax:list(
% lists:map(ConvertLabelFun, RecLabels)),
RecJSON =
erl_syntax:tuple(
[RecFieldsJSON]),
[erl_syntax:function(
erl_syntax:atom(make_enc_fun_name([Tag, json])),
[erl_syntax:clause(
[subst_labels(Result)],
none,
[?AST(_fields0 = [])] ++
lists:reverse(MakeJSON) ++
[RecJSON]
)])]
end;
false when is_tuple(Result) ->
{_Tags, RecTypes, _RecDict} = Types,
RecLabels = tuple_to_list(Result),
ConvertLabelFun =
fun(Label, {K, ASTs}) ->
InVar = erl_syntax:variable(
"_fields" ++ integer_to_list(K)),
OutVar = erl_syntax:variable(
"_fields" ++ integer_to_list(K + 1)),
case is_label(Label) of
true ->
JSONType = get_label_json_type(
Label, Elem, RecTypes,
FunTypes, AllElems),
VLabel = label_to_var(Label),
Res = encode_json_field2(
JSONType, VLabel,
Elem#elem.module, ModName),
Value = ?AST(['?Res' | '?InVar']),
Assign = ?AST('?OutVar' = '?Value'),
{K + 1, [Assign | ASTs]};
false ->
BLabel = atom_to_binary(Label, utf8),
Value = ?AST(['?a(BLabel)' | '?InVar']),
Assign = ?AST('?OutVar' = '?Value'),
{K + 1, [Assign | ASTs]}
end
end,
{K, MakeJSON} =
lists:foldl(ConvertLabelFun, {0, []}, lists:reverse(RecLabels)),
RecFieldsJSON = erl_syntax:variable("_fields" ++ integer_to_list(K)),
%RecFieldsJSON =
% erl_syntax:list(
% lists:map(ConvertLabelFun, RecLabels)),
JSON = RecFieldsJSON,
[erl_syntax:function(
erl_syntax:atom(make_enc_fun_name([Tag, json])),
[erl_syntax:clause(
[subst_labels(Result)],
none,
[?AST(_fields0 = [])] ++
lists:reverse(MakeJSON) ++
[JSON]
)])];
false when is_atom(Result) ->
Label = Result,
{_Tags, RecTypes, _RecDict} = Types,
Res =
case is_label(Label) of
true ->
JSONType = get_label_json_type(
Label, Elem, RecTypes,
FunTypes, AllElems),
encode_json_field2(
JSONType, ?AST(_val),
Elem#elem.module, ModName);
false ->
BLabel = atom_to_binary(Label, utf8),
?AST('?a(BLabel)')
end,
[erl_syntax:function(
erl_syntax:atom(make_enc_fun_name([Tag, json])),
[erl_syntax:clause(
[?AST(_val)],
none,
[Res]
)])];
false ->
[]
end.
encode_json_field(Type, Label, InVar, FBName, ModName, TopModName) ->
VLabel = label_to_var(Label),
case Type of
ignore ->
InVar;
_ ->
{SubType, Default, UseDefault} =
case Type of
{option, SubT, Def} ->
{SubT, Def, true};
{list, _} ->
{Type, [], true};
binary ->
{Type, <<>>, true};
{binary, _, _} ->
{Type, <<>>, true};
_ ->
{Type, undefined, false}
end,
Res = encode_json_field2(SubType, VLabel, ModName, TopModName),
case UseDefault of
true ->
?AST(case '?VLabel' of
'?a(Default)' -> '?InVar';
_ -> [{'?a(FBName)', '?Res'} | '?InVar']
end
);
false ->
?AST([{'?a(FBName)', '?Res'} | '?InVar'])
end
end.
encode_json_field2(Type, InVar, ModName, TopModName) ->
case Type of
[T] ->
encode_json_field2(T, InVar, ModName, TopModName);
binary -> InVar;
integer -> InVar;
boolean -> InVar;
{binary, _DecFun, EncFun} ->
case EncFun of
{M, F, Args} ->
make_function_call(
{M, F},
[InVar |
[abstract(Arg) || Arg <- Args]]);
{F, Args} ->
make_function_call(
F,
[InVar |
[abstract(Arg) || Arg <- Args]]);
undefined ->
InVar
end;
{external, _, RefMod, RefTag} ->
make_function_call(
make_enc_fun_name(ModName, RefMod, [RefTag, json]),
[InVar]);
{list, T} ->
Res = encode_json_field2(T, ?AST(_X), ModName, TopModName),
?AST(lists:map(fun(_X) -> '?Res' end, '?InVar'));
{tuple, Args} ->
Pattern =
erl_syntax:tuple(
lists:map(
fun(I) ->
erl_syntax:variable("_X" ++ integer_to_list(I))
end, lists:seq(1, length(Args)))),
Tuple =
erl_syntax:list(
lists:map(
fun(I) ->
Var = erl_syntax:variable(
"_X" ++ integer_to_list(I)),
encode_json_field2(lists:nth(I, Args), Var,
ModName, TopModName)
end, lists:seq(1, length(Args)))),
?AST(fun('?Pattern') ->
'?Tuple'
end('?InVar'));
%timestamp ->
% ?AST(tuple_to_list('?InVar'));
ip_address ->
?AST(enc_ip('?InVar'));
jid ->
?AST(fun({jid, _U, _S, _R, _LU, _LS, _LR}) ->
{[{<<"user">>, _U},
{<<"server">>, _S},
{<<"resource">>, _R},
{<<"luser">>, _LU},
{<<"lserver">>, _LS},
{<<"lresource">>, _LR}
]}
end('?InVar'));
{atom, unknown} ->
erlang:error({internal_error, ?MODULE}),
InVar;
{atom, _} ->
encode_json_case([Type], InVar, ModName, TopModName);
Types when is_list(Types) ->
encode_json_case(Types, InVar, ModName, TopModName);
{option, SubType, Default} when is_atom(Default),
Default /= false ->
Res = encode_json_field2(SubType, InVar, ModName, TopModName),
?AST(case '?InVar' of
'?a(Default)' -> <<"None">>;
_ -> [<<"Some">>, '?Res']
end
);
{option, SubType, _Default} ->
encode_json_field2(SubType, InVar, ModName, TopModName);
xmpp_element ->
?AST('?a(TopModName)':encode_json('?InVar'));
_ ->
erlang:error({internal_error, ?MODULE})
end.
encode_json_case(Types, InVar, ModName, TopModName) ->
TMap =
lists:foldl(
fun({atom, Atoms}, Map) ->
lists:foldl(
fun(Atom, Acc) ->
case maps:find(Atom, Acc) of
{ok, atom} ->
Acc;
{ok, T} ->
erlang:error({conflicting_types,
{atom, Acc}, T});
error ->
maps:put(Atom, atom, Acc)
end
end, Map, Atoms);
({external, {record, Tag, _}, _, _} = Rec, Map) ->
case maps:find(Tag, Map) of
{ok, Rec} ->
Map;
{ok, T} ->
erlang:error({conflicting_types, Rec, T});
error ->
maps:put(Tag, Rec, Map)
end
end, maps:new(), Types),
Clauses =
lists:map(
fun({Atom, atom}) ->
BAtom = atom_to_binary(Atom, utf8),
erl_syntax:clause(
[?AST('?a(Atom)')],
none,
[?AST('?a(BAtom)')]);
({Tag, {external, {record, Tag, Arity}, _, _} = Rec}) ->
Pattern =
erl_syntax:tuple(
[erl_syntax:atom(Tag) |
lists:duplicate(Arity, erl_syntax:underscore())
]
),
Res = encode_json_field2(Rec, InVar, ModName, TopModName),
erl_syntax:clause(
[Pattern],
none,
[Res])
end, maps:to_list(TMap)),
erl_syntax:case_expr(InVar, Clauses).
decode_json_field(Type, InVar, ModName, TopModName) ->
case Type of
ignore ->
erlang:error({internal_error, ?MODULE});
_ ->
{SubType, Default, UseDefault} =
case Type of
{option, SubT, Def} ->
{SubT, ?AST('?a(Def)'), true};
{list, _} ->
{Type, ?AST([]), true};
binary ->
{Type, ?AST(<<>>), true};
{binary, _, _} ->
Dec = decode_json_field2(Type, ?AST(<<>>),
ModName, TopModName),
{Type, Dec, true};
_ ->
{Type, undefined, false}
end,
Res = decode_json_field2(SubType, InVar, ModName, TopModName),
case UseDefault of
true ->
?AST(case '?InVar' of
undefined -> '?Default';
_ -> '?Res'
end
);
false ->
Res
end
end.
decode_json_field2(Type, InVar, ModName, TopModName) ->
case Type of
[T] ->
decode_json_field2(T, InVar, ModName, TopModName);
binary -> InVar;
integer -> InVar;
boolean -> InVar;
{binary, DecFun, _EncFun} ->
case DecFun of
{M, F, Args} ->
make_function_call(
{M, F},
[InVar |
[abstract(Arg) || Arg <- Args]]);
{F, Args} ->
make_function_call(
F,
[InVar |
[abstract(Arg) || Arg <- Args]]);
undefined ->
InVar
end;
{external, _, RefMod, RefTag} ->
make_function_call(
make_dec_fun_name(ModName, RefMod, [RefTag, json]),
[InVar]);
{list, T} ->
Res = decode_json_field2(T, ?AST(_X), ModName, TopModName),
?AST(lists:map(fun(_X) -> '?Res' end, '?InVar'));
{tuple, Args} ->
Pattern =
erl_syntax:list(
lists:map(
fun(I) ->
erl_syntax:variable("_X" ++ integer_to_list(I))
end, lists:seq(1, length(Args)))),
Tuple =
erl_syntax:tuple(
lists:map(
fun(I) ->
Var = erl_syntax:variable(
"_X" ++ integer_to_list(I)),
decode_json_field2(lists:nth(I, Args), Var,
ModName, TopModName)
end, lists:seq(1, length(Args)))),
?AST(fun('?Pattern') ->
'?Tuple'
end('?InVar'));
ip_address ->
?AST(dec_ip('?InVar'));
jid ->
?AST(fun({_jid}) ->
case jid:make(proplists:get_value(<<"user">>, _jid, <<>>),
proplists:get_value(<<"server">>, _jid),
proplists:get_value(<<"resource">>, _jid, <<>>)) of
error -> erlang:error({bad_jid, _jid});
_JID -> _JID
end
end('?InVar'));
{atom, unknown} ->
erlang:error({internal_error, ?MODULE}),
InVar;
{atom, _} ->
decode_json_case([Type], InVar, ModName, TopModName);
Types when is_list(Types) ->
decode_json_case(Types, InVar, ModName, TopModName);
{option, SubType, Default} when is_atom(Default),
Default /= false ->
Res = decode_json_field2(SubType, ?AST(_val1), ModName, TopModName),
?AST(fun(<<"None">>) -> '?a(Default)';
([<<"Some">>, _val1]) -> '?Res'
end('?InVar')
);
{option, SubType, _Default} ->
decode_json_field2(SubType, InVar, ModName, TopModName);
xmpp_element ->
?AST('?a(TopModName)':decode_json('?InVar'));
_ ->
erlang:error({internal_error, ?MODULE})
end.
decode_json_case(Types, InVar, ModName, TopModName) ->
TMap =
lists:foldl(
fun({atom, Atoms}, Map) ->
lists:foldl(
fun(Atom, Acc) ->
case maps:find(Atom, Acc) of
{ok, atom} ->
Acc;
{ok, T} ->
erlang:error({conflicting_types,
{atom, Acc}, T});
error ->
maps:put(Atom, atom, Acc)
end
end, Map, Atoms);
({external, {record, Tag, _}, _, _} = Rec, Map) ->
case maps:find(Tag, Map) of
{ok, Rec} ->
Map;
{ok, T} ->
erlang:error({conflicting_types, Rec, T});
error ->
maps:put(Tag, Rec, Map)
end
end, maps:new(), Types),
Clauses =
lists:map(
fun({Atom, atom}) ->
BAtom = atom_to_binary(Atom, utf8),
erl_syntax:clause(
[?AST('?a(BAtom)')],
none,
[?AST('?a(Atom)')]);
({Tag, {external, {record, Tag, _Arity}, _, _} = Rec}) ->
BTag = atom_to_binary(Tag, utf8),
Pattern = ?AST(['?a(BTag)', _]),
Res = decode_json_field2(Rec, InVar, ModName, TopModName),
erl_syntax:clause(
[Pattern],
none,
[Res])
end, maps:to_list(TMap)),
erl_syntax:case_expr(InVar, Clauses).
get_label_json_type(Label, Elem, Dict, FunSpecs, AllElems) ->
case get_spec_by_label(Label, Elem) of
sub_els ->
{list, xmpp_element};
'_' ->
ignore;
#attr{dec = undefined, default = Default,
required = false} ->
{option, binary, Default};
#attr{dec = undefined, default = _Default, required = _IsRequired} ->
binary;
#attr{dec = DecFun, enc = EncFun, default = Default, required = IsRequired} ->
case json_use_enc_dec(DecFun) of
true ->
case {Default, IsRequired} of
{undefined, false} ->
{option, {binary, DecFun, EncFun}, Default};
_ ->
{binary, DecFun, EncFun}
end;
false ->
FType = get_fun_return_type(DecFun, FunSpecs),
get_json_type(FType, Default, IsRequired)
end;
#cdata{dec = undefined, default = Default,
required = false} ->
{option, binary, Default};
#cdata{dec = undefined, default = _Default, required = _IsRequired} ->
binary;
#cdata{dec = DecFun, enc = EncFun, default = Default, required = IsRequired} ->
case json_use_enc_dec(DecFun) of
true ->
case {Default, IsRequired} of
{undefined, false} ->
{option, {binary, DecFun, EncFun}, Default};
_ ->
{binary, DecFun, EncFun}
end;
false ->
FType = get_fun_return_type(DecFun, FunSpecs),
get_json_type(FType, Default, IsRequired)
end;
[#ref{min = Min, max = Max, default = Default}|_] = Refs ->
Types = lists:map(
fun(#ref{name = RefTag}) ->
case dict:find(RefTag, Dict) of
{ok, T} ->
case get_json_type2(T) of
%{record, _RecName, _RecSize} = Rec ->
% RefElem = get_elem_by_ref(RefTag, AllElems),
% RefMod = RefElem#elem.module,
% {external, Rec, RefMod, RefTag};
%{tuple, _} = Tuple ->
% RefElem = get_elem_by_ref(RefTag, AllElems),
% RefMod = RefElem#elem.module,
% {external, Tuple, RefMod, RefTag};
%RT -> RT
{atom, _} = RT -> RT;
RT ->
RefElem = get_elem_by_ref(RefTag, AllElems),
RefMod = RefElem#elem.module,
{external, RT, RefMod, RefTag}
end;
error ->
erlang:error({internal_error, ?MODULE})
end
end, Refs),
IsRequired = (Min == 1) and (Max == 1),
case {Default, IsRequired, Max} of
{false, false, 1} when Types == [{atom,[true]}] ->
{option, boolean, Default};
{_, false, 1} ->
{option, Types, Default};
{_, _, 1} ->
Types;
_ ->
{list, Types}
%{todo,
% erl_types:t_list(
% erl_types:t_subtract(
% Type, erl_types:t_from_term(Default))),
% [], false}
end
end.
get_json_type(FType, Default, IsRequired) ->
IsRaw = is_json_raw_type(FType),
case {Default, IsRequired, IsRaw} of
{undefined, false, {true, T}} ->
{option, T, Default};
{_Default, _, {true, T}} ->
T;
{undefined, true, _} ->
get_json_type2(FType);
{undefined, false, _} ->
{option, get_json_type2(FType), Default};
{_Default, _, _} ->
get_json_type2(FType)
end.
get_json_type2(FType) ->
case erl_types:t_is_tuple(FType) of
true ->
case erl_types:t_tuple_args(FType) of
[ATag] ->
case erl_types:t_is_atom(ATag) of
true ->
case erl_types:t_atom_vals(ATag) of
[Tag] ->
{record, Tag, erl_types:t_tuple_size(FType)};
_ ->
erlang:error({internal_error, ?MODULE})
end;
false ->
erlang:error({internal_error, ?MODULE})
end;
Args ->
{tuple, lists:map(fun get_json_type2/1, Args)}
end;
false ->
case erl_types:t_is_atom(FType) of
true ->
Atoms = erl_types:t_atom_vals(FType),
case lists:member(undefined, Atoms) of
false ->
{atom, Atoms};
true ->
{option, {atom, lists:delete(undefined, Atoms)},
undefined}
end;
false ->
case is_json_raw_type(FType) of
{true, T} -> T;
false ->
case erl_types:t_is_list(FType) of
true ->
{list, get_json_type2(erl_types:t_list_elements(FType))};
false ->
Undefined = erl_types:t_atom(undefined),
case catch erl_types:t_elements(FType) of
[Undefined, T] ->
{option, get_json_type2(T), undefined};
[_, _ | _] ->
{todo, FType};
_ ->
case erl_types:t_is_any(FType) of
true ->
{todo, FType};
false ->
case FType of
{type, _, list, [T]} ->
{list, get_json_type2(T)};
{remote_type, _,
[{atom, _, erlang},
{atom, _, timestamp}, []]} ->
{tuple,
[integer,
integer,
integer]};
{remote_type, _,
[{atom, _, inet},
{atom, _, ip_address}, []]} ->
ip_address;
{remote_type, _,
[{atom, _, jid},
{atom, _, jid}, []]} ->
jid;
{type, _, union, _} ->
{todo, FType};
_ ->
erlang:error({internal_error, ?MODULE})
end
end
end
end
end
end
end.
is_json_raw_type(Type) ->
case {erl_types:t_is_binary(Type),
erl_types:t_is_integer(Type),
erl_types:t_is_boolean(Type)} of
{true, _, _} -> {true, binary};
{_, true, _} -> {true, integer};
{_, _, true} -> {true, boolean};
_ -> false
end.
json_use_enc_dec({dec_ip, []}) -> true;
json_use_enc_dec({dec_host, []}) -> true;
json_use_enc_dec({dec_host_port, []}) -> true;
json_use_enc_dec({xmpp_lang, check, []}) -> true;
json_use_enc_dec({base64, mime_decode, []}) -> true;
json_use_enc_dec({base64, decode, []}) -> true;
json_use_enc_dec(_) -> false.
json_type_to_atd(Type) ->
case Type of
[T] ->
json_type_to_atd(T);
binary -> "string";
integer -> "int";
boolean -> "bool";
{binary, _DecFun, _EncFun} -> "string";
%{external, _, _RefMod, RefTag} -> atom_to_list(RefTag);
{external, {record, Tag, _}, _RefMod, _RefTag} ->
sanitize_for_atd(Tag);
{external, {list, {record, Tag, _}}, _RefMod, _RefTag} ->
[sanitize_for_atd(Tag), " list "];
{external, _, _RefMod, RefTag} ->
sanitize_for_atd(RefTag);
{list, T} ->
[json_type_to_atd(T), " list "];
{tuple, Args} ->
["(",
string:join(lists:map(fun json_type_to_atd/1, Args), " * "),
")"];
ip_address -> "string";
jid -> "jid";
{atom, unknown} ->
erlang:error({internal_error, ?MODULE});
{atom, _} ->
json_case_to_atd([Type]);
Types when is_list(Types) ->
json_case_to_atd(Types);
{option, SubType, Default} when is_atom(Default),
Default /= false ->
[json_type_to_atd(SubType), " option"];
{option, SubType, _Default} ->
json_type_to_atd(SubType);
xmpp_element -> "xmpp_element"
end.
json_case_to_atd(Types) ->
TMap =
lists:foldl(
fun({atom, Atoms}, Map) ->
lists:foldl(
fun(Atom, Acc) ->
case maps:find(Atom, Acc) of
{ok, atom} ->
Acc;
{ok, T} ->
erlang:error({conflicting_types,
{atom, Acc}, T});
error ->
maps:put(Atom, atom, Acc)
end
end, Map, Atoms);
({external, {record, Tag, _}, _, _} = Rec, Map) ->
case maps:find(Tag, Map) of
{ok, Rec} ->
Map;
{ok, T} ->
erlang:error({conflicting_types, Rec, T});
error ->
maps:put(Tag, Rec, Map)
end
end, maps:new(), Types),
Variants =
lists:map(
fun({Atom, atom}) ->
to_atd_variant(Atom);
({Tag, {external, {record, Tag, _Arity}, _, _}}) ->
RecName = sanitize_for_atd(Tag),
[to_atd_variant(Tag), " of ", RecName]
end, maps:to_list(TMap)),
["[",
string:join(Variants, " | "),
"]"].
make_decoding_MFA(Parents, TagName, _TagNS, AttrName,
IsRequired, Default, DecMFA, _Types, ModName) ->
FunName = make_dec_fun_name(Parents),
Type = case AttrName of
<<>> -> "cdata";
_ -> "attr"
end,
Clause1 = erl_syntax:clause(
[?AST(__TopXMLNS),
if Type == "attr" -> ?AST(undefined);
true -> ?AST(<<>>) end],
none,
[if IsRequired ->
MissingType = erl_syntax:atom("missing_" ++ Type),
?AST(erlang:error(
{'?a(ModName)', {'?MissingType', '?a(AttrName)',
'?a(TagName)', __TopXMLNS}}));
true ->
abstract(Default)
end]),
Body = case DecMFA of
{M, F, Args} ->
make_function_call(
{M, F},
[?AST(_val)|
[abstract(Arg) || Arg <- Args]]);
{F, Args} ->
make_function_call(
F,
[?AST(_val)|
[abstract(Arg) || Arg <- Args]]);
undefined ->
?AST(_val)
end,
Catch = case DecMFA of
undefined ->
Body;
_ ->
BadVal = erl_syntax:atom("bad_" ++ Type ++ "_value"),
erl_syntax:case_expr(
erl_syntax:catch_expr(Body),
[erl_syntax:clause(
[?AST({'EXIT', _})],
none,
[?AST(erlang:error(
{'?a(ModName)', {'?BadVal', '?a(AttrName)',
'?a(TagName)', __TopXMLNS}}))]),
erl_syntax:clause([?AST(_res)], none, [?AST(_res)])])
end,
Clause2 = erl_syntax:clause(
[?AST(__TopXMLNS),
?AST(_val)], none, [Catch]),
[erl_syntax:function(erl_syntax:atom(FunName), [Clause1, Clause2])].
make_encoding_MFA(_, <<"xmlns">>, _, _, _, _) ->
[];
make_encoding_MFA(Parents, AttrName, Required, AttrDefault, EncMFA, AlwaysEnc) ->
Clause1 = if Required orelse AlwaysEnc ->
[];
true ->
[erl_syntax:clause(
[abstract(AttrDefault),
?AST(_acc)],
none,
[?AST(_acc)])]
end,
Body = case EncMFA of
{M, F, Args} ->
make_function_call(
{M, F},
[?AST(_val)|
[abstract(Arg) || Arg <- Args]]);
{F, Args} ->
make_function_call(
F,
[?AST(_val)|
[abstract(Arg) || Arg <- Args]]);
undefined ->
?AST(_val)
end,
Clause2 = [erl_syntax:clause(
[?AST(_val),
?AST(_acc)],
none,
[erl_syntax:list(
[erl_syntax:tuple(
[if AttrName /= <<>> -> abstract(AttrName);
true -> ?AST(xmlcdata)
end, Body])],
?AST(_acc))])],
[erl_syntax:function(
erl_syntax:atom(make_enc_fun_name(Parents)),
Clause1 ++ Clause2)].
make_dec_fun_name(Vars) ->
make_dec_fun_name(undefined, undefined, Vars).
make_dec_fun_name(ParentMod, Mod, Vars) ->
NewVars = lists:foldl(
fun(Var, Acc) when is_binary(Var) ->
[binary_to_list(Var)|Acc];
(Var, Acc) when is_atom(Var) ->
[atom_to_list(Var)|Acc];
(Var, Acc) ->
[Var|Acc]
end, [], Vars),
Fun = "decode_" ++ string:join(NewVars, "_"),
if Mod == undefined -> Fun;
ParentMod == Mod -> Fun;
true -> {Mod, Fun}
end.
make_enc_fun_name(Vars) ->
make_enc_fun_name(undefined, undefined, Vars).
make_enc_fun_name(ParentMod, Mod, Vars) ->
NewVars = lists:foldl(
fun(Var, Acc) when is_binary(Var) ->
[binary_to_list(Var)|Acc];
(Var, Acc) when is_atom(Var) ->
[atom_to_list(Var)|Acc];
(Var, Acc) ->
[Var|Acc]
end, [], Vars),
Fun = "encode_" ++ string:join(NewVars, "_"),
if Mod == undefined -> Fun;
ParentMod == Mod -> Fun;
true -> {Mod, Fun}
end.
%% Fun(Args) -> Body.
make_function(Fun, Args, Body) ->
erl_syntax:function(
erl_syntax:atom(Fun),
[erl_syntax:clause(Args, none, Body)]).
make_function_call({Mod, Fun}, Args) ->
erl_syntax:application(
erl_syntax:atom(Mod),
erl_syntax:atom(Fun),
Args);
make_function_call(Fun, Args) ->
erl_syntax:application(
none,
erl_syntax:atom(Fun),
Args).
abstract(<<>>) ->
erl_syntax:abstract(<<>>);
abstract(Bin) when is_binary(Bin) ->
erl_syntax:binary(
[erl_syntax:abstract(
binary_to_list(Bin))]);
abstract(Term) ->
erl_syntax:abstract(Term).
a(Term) ->
abstract(Term).
label_to_var(Label) ->
case atom_to_list(Label) of
[$$,$_|[H|T]] ->
erl_syntax:variable(
replace_invalid_chars(
[$_, $_, string:to_upper(H)|T]));
[$$|[H|T]] when H /= $- ->
erl_syntax:variable(
replace_invalid_chars(
[string:to_upper(H)|T]))
end.
replace_invalid_chars([$-|T]) ->
[$_|replace_invalid_chars(T)];
replace_invalid_chars([$:|T]) ->
[$_|replace_invalid_chars(T)];
replace_invalid_chars([$.|T]) ->
[$_|replace_invalid_chars(T)];
replace_invalid_chars([H|T]) ->
[H|replace_invalid_chars(T)];
replace_invalid_chars([]) ->
[].
label_to_record_field(Label) ->
case atom_to_list(Label) of
"$_els" ->
sub_els;
[$$|T] ->
list_to_atom(T)
end.
record_fields_to_vars(Name, Fields) ->
record_fields_to_vars(Name, Fields, []).
record_fields_to_vars(Name, Fields, Replace) ->
FList = lists:map(
fun(Field) ->
case lists:keyfind(Field, 1, Replace) of
{_, AbstractVal} ->
AbstractVal;
false ->
erl_syntax:variable(
[$_|atom_to_list(Field)])
end
end, Fields),
erl_syntax:tuple([erl_syntax:atom(Name)|FList]).
prepare_label(Label, Name) when is_atom(Name) ->
prepare_label(Label, erlang:atom_to_binary(Name, utf8));
prepare_label(Label, Name) ->
if Label == undefined ->
list_to_atom(string:to_lower([$$|binary_to_list(Name)]));
is_atom(Label) ->
case atom_to_list(Label) of
[$$|_] ->
Label;
_ ->
?err("bad 'label': ~p", [Label])
end;
true ->
?err("bad 'label': ~p", [Label])
end.
tuple_or_single_var([Var]) ->
Var;
tuple_or_single_var([_|_] = Vars) ->
erl_syntax:tuple(Vars).
labels_to_underscores(Term) ->
labels_to_underscores(Term, []).
labels_to_underscores(Term, Except) ->
labels_to_underscores(Term, Except, []).
labels_to_underscores(Term, Except, Replace) ->
erl_syntax_lib:map(
fun(T) ->
try
Label = erl_syntax:atom_value(T),
true = is_label(Label),
case lists:member(Label, Except) of
true ->
label_to_var(Label);
false ->
case lists:keyfind(Label, 1, Replace) of
{_, Value} ->
abstract(Value);
false ->
?AST(_)
end
end
catch _:_ ->
T
end
end, abstract(Term)).
have_label(Term, Label) ->
erl_syntax_lib:fold(
fun(_, true) ->
true;
(T, false) ->
try
L = erl_syntax:atom_value(T),
true = is_label(L),
Label == L
catch _:_ ->
false
end
end, false, abstract(Term)).
get_fun_return_type(Fun, FunSpecs) ->
get_fun_return_type(Fun, FunSpecs, dict:new()).
get_fun_return_type({dec_enum, [Atoms]}, _, _) ->
%% TODO: erl_types:t_atoms restricts the number of atoms to 13, this is a
%% hack to allow any number of atoms
%erl_types:t_atoms(Atoms);
{c, atom, lists:usort(Atoms), unknown};
get_fun_return_type({dec_int, [Min, _]}, _, _) ->
if Min > 0 ->
erl_types:t_pos_integer();
Min == 0 ->
erl_types:t_non_neg_integer();
Min < 0 ->
erl_types:t_integer()
end;
get_fun_return_type({dec_int, []}, _, _) ->
erl_types:t_integer();
get_fun_return_type({F, Args}, FunSpecs, _) ->
case dict:find({F, length(Args) + 1}, FunSpecs) of
{ok, Spec} ->
Type = t_from_form(Spec),
case erl_types:t_is_any(Type) of
true -> Spec;
false -> Type
end;
_ ->
erl_types:t_any()
end;
get_fun_return_type({M, F, Args}, FunSpecs, _) ->
case dict:find({M, F, length(Args) + 1}, FunSpecs) of
{ok, Spec} ->
Type = t_from_form(Spec),
case erl_types:t_is_any(Type) of
true -> Spec;
false -> Type
end;
_ ->
erl_types:t_any()
end;
get_fun_return_type(undefined, _, _) ->
erl_types:t_binary().
term_is_record(Term) ->
try
[H|_T]= tuple_to_list(Term),
true = is_atom(H),
false == is_label(H)
catch _:_ ->
false
end.
%% This is a copy-paste from erl_types.erl and probably will
%% be broken from time to time in new OTP releases.
t_identifier(Elem) ->
{c, identifier, ordsets:from_list([Elem]), unknown}.
term_to_t([H|T], LabelTypes) ->
erl_types:t_cons(term_to_t(H, LabelTypes), term_to_t(T, LabelTypes));
term_to_t([], _LabelTypes) ->
erl_types:t_nil();
term_to_t(T, LabelTypes) when is_atom(T) ->
case is_label(T) of
true ->
{_, {Type, Default, IsRequired}} = lists:keyfind(T, 1, LabelTypes),
if IsRequired ->
Type;
?is_raw_type(Type) ->
Type;
true ->
erl_types:t_sup(Type, erl_types:t_from_term(Default))
end;
false ->
erl_types:t_atom(T)
end;
term_to_t(T, _LabelTypes) when is_bitstring(T) ->
erl_types:t_bitstr(0, erlang:bit_size(T));
term_to_t(T, _LabelTypes) when is_float(T) ->
erl_types:t_float();
term_to_t(T, _LabelTypes) when is_function(T) ->
{arity, Arity} = erlang:fun_info(T, arity),
erl_types:t_fun(Arity, erl_types:t_any());
term_to_t(T, _LabelTypes) when is_integer(T) ->
erl_types:t_integer(T);
term_to_t(T, _LabelTypes) when is_pid(T) ->
erl_types:t_pid();
term_to_t(T, _LabelTypes) when is_port(T) ->
erl_types:t_port();
term_to_t(T, _LabelTypes) when is_reference(T) ->
erl_types:t_reference();
term_to_t(T, LabelTypes) when is_tuple(T) ->
case term_is_record(T) of
true ->
RecName = element(1, T),
erl_types:t_tuple([term_to_t(RecName, LabelTypes)]);
false ->
erl_types:t_tuple(
[term_to_t(E, LabelTypes) || E <- tuple_to_list(T)])
end.
is_subtype(_Term, Type) when ?is_raw_type(Type) ->
false;
is_subtype(Term, Type) ->
erl_types:t_is_subtype(erl_types:t_from_term(Term), Type).
get_types(TaggedElems, FunSpecs, Opts) ->
G = build_ref_deps(TaggedElems),
SortedTags = digraph_utils:topsort(G),
TypesDict = lists:foldl(
fun(RefName, Dict) ->
RefElem = get_elem_by_ref(RefName, TaggedElems),
Result = RefElem#elem.result,
Labels = extract_labels_from_term(Result),
LabelTypes =
lists:map(
fun(Label) ->
{Label, get_label_type(Label, RefElem, Dict, FunSpecs, Opts)}
end, Labels),
Type = term_to_t(Result, LabelTypes),
dict:store(RefName, Type, Dict)
end, dict:new(), SortedTags),
RecDict = dict_from_list(
lists:flatmap(
fun({Tag, _T}) ->
RefElem = get_elem_by_ref(Tag, TaggedElems),
case term_is_record(RefElem#elem.result) of
true ->
RecName = element(1, RefElem#elem.result),
[{{record, RecName}, {0, [{0, []}]}}];
false ->
[]
end
end, dict:to_list(TypesDict))),
{digraph_utils:topsort(G), TypesDict, RecDict}.
extract_labels_from_term(Term) ->
erl_syntax_lib:fold(
fun(T, Acc) ->
try
Label = erl_syntax:atom_value(T),
true = is_label(Label),
[Label|Acc]
catch _:_ ->
Acc
end
end, [], abstract(Term)).
get_label_type(Label, Elem, Dict, FunSpecs, Opts) ->
XMLType = t_remote(fxml, xmlel),
case get_spec_by_label(Label, Elem) of
sub_els ->
T = case proplists:get_value(add_type_specs, Opts) of
SpecName when is_atom(SpecName), SpecName /= undefined ->
erl_types:t_sup([XMLType, t_identifier(SpecName)]);
_ ->
erl_types:t_any()
end,
{erl_types:t_list(T), [], false};
'_' ->
{erl_types:t_from_term(undefined), [], false};
#attr{dec = undefined, default = Default, required = IsRequired} ->
{erl_types:t_binary(), Default, IsRequired};
#attr{dec = DecFun, default = Default, required = IsRequired} ->
{get_fun_return_type(DecFun, FunSpecs), Default, IsRequired};
#cdata{dec = undefined, default = Default, required = IsRequired} ->
{erl_types:t_binary(), Default, IsRequired};
#cdata{dec = DecFun, default = Default, required = IsRequired} ->
{get_fun_return_type(DecFun, FunSpecs), Default, IsRequired};
[#ref{min = Min, max = Max, default = Default}|_] = Refs ->
Types = lists:flatmap(
fun(#ref{name = RefTag}) ->
case dict:find(RefTag, Dict) of
{ok, T} -> [T];
error -> []
end
end, Refs),
Type = erl_types:t_sup(Types),
IsRequired = (Min == 1) and (Max == 1),
if Max == 1 ->
{Type, Default, IsRequired};
?is_raw_type(Type) ->
{{type, element(2, Type), list, [Type]}, [], false};
true ->
{erl_types:t_list(
erl_types:t_subtract(
Type, erl_types:t_from_term(Default))),
[], false}
end
end.
build_ref_deps(TaggedElems) ->
G = digraph:new([acyclic]),
lists:foreach(
fun({Tag, Elem}) ->
digraph:add_vertex(G, Tag),
lists:foreach(
fun(#ref{name = RefTag}) ->
digraph:add_vertex(G, RefTag),
digraph:add_edge(G, RefTag, Tag)
end, Elem#elem.refs)
end, TaggedElems),
G.
get_abstract_code_from_myself() ->
{file, File} = code:is_loaded(?MODULE),
case beam_lib:chunks(File, [abstract_code]) of
{ok, {_, List}} ->
case lists:keyfind(abstract_code, 1, List) of
{abstract_code, {raw_abstract_v1, Abstr}} ->
{ok, Abstr};
_ ->
error
end;
_ ->
error
end.
%%====================================================================
%% Auxiliary functions
%%====================================================================
resolver_mod(Mod) ->
list_to_atom(atom_to_list(Mod) ++ "_external").
%% Checks
prepare_elem(#elem{name = Name}, _, _, _, _, _)
when not is_binary(Name) ->
bad_spec({wrong_name, Name});
prepare_elem(#elem{module = Mod}, _, _, _, _, _) when not is_atom(Mod) ->
bad_spec({wrong_module, Mod});
prepare_elem(#elem{name = Name, xmlns = XMLNS}, _, _, _, _, _)
when not is_binary(XMLNS), not is_list(XMLNS) ->
bad_spec({wrong_xmlns, XMLNS, Name});
prepare_elem(#elem{name = Name, refs = Refs}, _, _, _, _, _) when not is_list(Refs) ->
bad_spec({wrong_refs, Refs, Name});
prepare_elem(#elem{name = Name, attrs = Attrs}, _, _, _, _, _) when not is_list(Attrs) ->
bad_spec({wrong_attrs, Attrs, Name});
prepare_elem(#elem{name = Name, attrs = Attrs, xmlns = XMLNS,
cdata = CData, refs = Refs, module = Mod} = Elem,
KnownFunctions, FunSpecs, AllElems, ModName, _Opts) ->
if XMLNS == <<>> ->
bad_spec({empty_xmlns, Name});
true ->
ok
end,
NewAttrs = lists:map(
fun(Attr) ->
prepare_attr(Name, Attr, KnownFunctions, FunSpecs, ModName)
end, Attrs),
NewCData = prepare_cdata(Name, CData, KnownFunctions, FunSpecs, ModName),
NewRefs = lists:map(
fun(Ref) -> prepare_ref(Name, Ref, AllElems) end,
Refs),
check_labels(Elem),
NewMod = if Mod == undefined -> ModName;
true -> Mod
end,
Elem#elem{attrs = NewAttrs, cdata = NewCData, refs = NewRefs, module = NewMod}.
prepare_ref(Name, #ref{name = RefName}, _)
when not is_atom(RefName) ->
bad_spec({wrong_ref_name, RefName, Name});
prepare_ref(Name, #ref{name = RefName, min = Min}, _)
when not (Min == 0 orelse Min == 1) ->
bad_spec({wrong_ref_min, Min, RefName, Name});
prepare_ref(Name, #ref{name = RefName, max = Max}, _)
when not (Max == 1 orelse Max == infinity) ->
bad_spec({wrong_ref_max, Max, RefName, Name});
prepare_ref(Name, #ref{name = RefName, label = Label}, _)
when not is_atom(Label) ->
bad_spec({wrong_ref_label, Label, RefName, Name});
prepare_ref(Name, #ref{name = RefName, label = Label} = Ref, AllElems) ->
case (is_label(Label) or (Label == undefined)) of
false ->
bad_spec({wrong_ref_label_format, Label, RefName, Name});
true ->
case lists:keyfind(RefName, 1, AllElems) of
false ->
bad_spec({unresolved_ref, RefName, Name});
_ ->
Ref
end
end;
prepare_ref(Name, Junk, _) ->
bad_spec({not_ref_spec, Junk, Name}).
prepare_default('$unset', DecFun, _IsRequired, FunSpecs) ->
T = get_fun_return_type(DecFun, FunSpecs),
case erl_types:t_is_binary(T) of
true -> <<"">>;
_ -> undefined
end;
prepare_default(Default, _DecFun, false, _FunSpecs) ->
Default;
prepare_default(Default, _DecFun, true, _FunSpecs) ->
bad_spec({default_must_be_unset, Default}).
prepare_attr(Name, #attr{name = AName}, _, _, _)
when not is_binary(AName) ->
bad_spec({wrong_attr_name, AName, Name});
prepare_attr(Name, #attr{name = AName, label = Label}, _, _, _)
when not is_atom(Label) ->
bad_spec({wrong_attr_label, Label, AName, Name});
prepare_attr(Name, #attr{name = AName, required = Req}, _, _, _)
when not (Req == false orelse Req == true) ->
bad_spec({wrong_attr_required, Req, AName, Name});
prepare_attr(Name, #attr{name = AName, label = Label,
default = Default, required = IsRequired,
dec = DecF, enc = EncF} = Attr,
KnownFunctions, FunSpecs, ModName) ->
NewDefault = prepare_default(Default, DecF, IsRequired, FunSpecs),
NewDecFun = prep_dec_fun(DecF, KnownFunctions, ModName),
NewEncFun = prep_enc_fun(EncF, KnownFunctions, ModName),
case (is_label(Label) or (Label == undefined)) of
false ->
bad_spec({wrong_attr_label_format, Label, AName, Name});
true ->
Attr#attr{dec = NewDecFun, enc = NewEncFun, default = NewDefault}
end;
prepare_attr(Name, Junk, _, _, _) ->
bad_spec({not_attr_spec, Junk, Name}).
prepare_cdata(Name, #cdata{label = Label}, _, _, _)
when not is_atom(Label) ->
bad_spec({wrong_cdata_label, Label, Name});
prepare_cdata(Name, #cdata{required = Req}, _, _, _)
when not (Req == false orelse Req == true) ->
bad_spec({wrong_cdata_required, Req, Name});
prepare_cdata(Name, #cdata{label = Label, dec = DecF, enc = EncF,
default = Default, required = IsRequired} = CData,
KnownFunctions, FunSpecs, ModName) ->
NewDefault = prepare_default(Default, DecF, IsRequired, FunSpecs),
NewDecFun = prep_dec_fun(DecF, KnownFunctions, ModName),
NewEncFun = prep_enc_fun(EncF, KnownFunctions, ModName),
case (is_label(Label) or (Label == undefined)) of
false ->
bad_spec({wrong_cdata_label_format, Label, Name});
true ->
CData#cdata{enc = NewEncFun, dec = NewDecFun, default = NewDefault}
end;
prepare_cdata(Name, Junk, _, _, _) ->
bad_spec({not_cdata_spec, Junk, Name}).
get_dups(L) ->
get_dups(L, []).
get_dups([H|T], Acc) ->
case lists:member(H, T) of
true ->
get_dups(T, [H|Acc]);
false ->
get_dups(T, Acc)
end;
get_dups([], Acc) ->
lists:usort(Acc).
check_labels(#elem{result = Result, attrs = Attrs,
refs = Refs, cdata = CData}) ->
ResultLabels = erl_syntax_lib:fold(
fun(T, Acc) ->
try
Label = erl_syntax:atom_value(T),
true = is_label(Label),
[Label|Acc]
catch _:_ ->
Acc
end
end, [], abstract(Result)),
AttrLabels = lists:map(
fun(#attr{name = Name, label = Label}) ->
prepare_label(Label, Name)
end, Attrs),
CDataLabel = CData#cdata.label,
RefLabels = lists:map(
fun({L, Rs}) ->
check_group(L, Rs),
L
end, group_refs(Refs)),
AllLabels = AttrLabels ++ [CDataLabel] ++ RefLabels,
case get_dups(lists:filter(
fun('$_') -> false;
(_) -> true
end, ResultLabels)) of
Dups1 when Dups1 /= [] ->
bad_spec({duplicated_labels, Dups1});
_ ->
ok
end,
case get_dups(AllLabels) of
Dups2 when Dups2 /= [] ->
bad_spec({duplicated_labels, Dups2});
_ ->
ok
end,
ResultSet = sets:from_list(ResultLabels),
AllSet = sets:from_list(AllLabels),
UnresolvedLabels = sets:to_list(
sets:subtract(ResultSet, AllSet)) -- ['$_els', '$_'],
UnusedLabels = sets:to_list(sets:subtract(AllSet, ResultSet)) -- ['$cdata'],
if UnresolvedLabels /= [] ->
bad_spec({unresolved_labels, UnresolvedLabels});
UnusedLabels /= []->
bad_spec({unused_labels, UnusedLabels});
true ->
ok
end.
check_group(_Label, [_]) ->
ok;
check_group(Label, Refs) ->
#ref{default = Default} = hd(Refs),
case lists:all(
fun(#ref{default = D}) ->
D == Default
end, Refs) of
true ->
case lists:all(
fun(#ref{min = 0, max = 1}) ->
true;
(_) ->
false
end, Refs) of
true ->
ok;
false ->
case lists:all(
fun(#ref{min = 0, max = infinity}) ->
true;
(_) ->
false
end, Refs) of
true ->
ok;
false ->
bad_spec({wrong_min_max_in_group, Label})
end
end;
false ->
bad_spec({different_defaults_in_group, Label})
end.
prep_dec_fun({Mod, Fun, Args}, _, _)
when is_atom(Mod) andalso is_atom(Fun) andalso is_list(Args) ->
{Mod, Fun, Args};
prep_dec_fun({Fun, Args}, KnownFunctions, _ModName)
when is_atom(Fun) andalso is_list(Args) ->
Arity = length(Args) + 1,
case erlang:function_exported(?MODULE, Fun, Arity) of
true ->
{Fun, Args};
false ->
case lists:member({Fun, Arity}, KnownFunctions) of
true ->
{Fun, Args};
false ->
bad_spec({unknown_dec_fun, {Fun, Args}})
end
end;
prep_dec_fun(undefined, _, _) ->
undefined;
prep_dec_fun(Junk, _, _) ->
bad_spec({invalid_dec_fun, Junk}).
prep_enc_fun({Mod, Fun, Args}, _, _)
when is_atom(Mod) andalso is_atom(Fun) andalso is_list(Args) ->
{Mod, Fun, Args};
prep_enc_fun({Fun, Args}, KnownFunctions, _ModName)
when is_atom(Fun) andalso is_list(Args) ->
Arity = length(Args) + 1,
case erlang:function_exported(?MODULE, Fun, Arity) of
true ->
{Fun, Args};
false ->
case lists:member({Fun, Arity}, KnownFunctions) of
true ->
{Fun, Args};
false ->
bad_spec({unknown_enc_fun, {Fun, Args}})
end
end;
prep_enc_fun(undefined, _, _) ->
undefined;
prep_enc_fun(Junk, _, _) ->
bad_spec({invalid_enc_fun, Junk}).
is_label(Label) when not is_atom(Label) ->
false;
is_label(Label) ->
case atom_to_list(Label) of
"$_els" ->
true;
"$_" ->
true;
[$$,$_|_] ->
false;
[$$,$-|_] ->
false;
[$$,_|_] ->
true;
_ ->
false
end.
bad_spec(Err) ->
erlang:error({bad_spec, Err}).
%% @hidden
%% @doc Same as file:consult, but expands known records.
consult(Path) ->
case get_forms(Path) of
{ok, Forms} ->
{Terms, OtherForms} =
lists:foldl(
fun([Form], {Trms, Other}) ->
Trm =
erl_syntax_lib:map(
fun(T) ->
case erl_syntax:type(T) of
record_expr ->
record_to_tuple(T);
_ ->
T
end
end, erl_syntax:form_list([Form])),
{[Trm|Trms], Other};
(Form, {Trms, Other}) ->
{Trms, [Form|Other]}
end, {[], []}, Forms),
TmpFile = filename:join([filename:dirname(Path),
filename:basename(Path) ++ "~"]),
Str = lists:map(
fun(Tree) ->
AbsForm = erl_syntax:revert_forms(Tree),
case catch erl_eval:exprs(AbsForm, []) of
{'EXIT', _} ->
[];
{value, Term, _} ->
[io_lib:print(Term), $., io_lib:nl()]
end
end, Terms),
Res = case file:write_file(TmpFile, Str) of
ok ->
case file:consult(TmpFile) of
{ok, R} ->
{ok, R, OtherForms};
Err ->
Err
end;
Err ->
Err
end,
catch file:delete(TmpFile),
Res;
Err ->
Err
end.
record_to_tuple(R) ->
Name = erl_syntax:record_expr_type(R),
AtomName = list_to_atom(erl_syntax:atom_name(Name)),
case lists:member(AtomName, [attr, cdata, elem, ref]) of
true ->
record_to_tuple(R, tag_record(AtomName));
false ->
bad_spec({unknown_record, AtomName})
end.
tag_record(attr) ->
tag_record(#attr{}, record_info(fields, attr));
tag_record(cdata) ->
tag_record(#cdata{}, record_info(fields, cdata));
tag_record(ref) ->
tag_record(#ref{}, record_info(fields, ref));
tag_record(elem) ->
tag_record(#elem{}, record_info(fields, elem)).
tag_record(R, Fs) ->
[_|Vs] = tuple_to_list(R),
lists:zip(Fs, Vs).
record_to_tuple(R, TaggedRecord) ->
Name = erl_syntax:record_expr_type(R),
Fs = erl_syntax:record_expr_fields(R),
KeyVals = lists:map(
fun(F) ->
Key = list_to_atom(
erl_syntax:atom_name(
erl_syntax:record_field_name(F))),
Val = erl_syntax:record_field_value(F),
{Key, Val}
end, Fs),
case get_dups([K || {K, _} <- KeyVals]) of
Dups when Dups /= [] ->
bad_spec({duplicated_record_fields, Dups});
_ ->
ok
end,
case sets:to_list(sets:subtract(
sets:from_list([K || {K, _} <- KeyVals]),
sets:from_list([K || {K, _} <- TaggedRecord]))) of
Undef when Undef /= [] ->
bad_spec({undefined_record_fields, Undef});
_ ->
ok
end,
Vals = lists:map(
fun({K, Default}) ->
case lists:keyfind(K, 1, KeyVals) of
{_, Val} ->
Val;
false ->
erl_syntax:abstract(Default)
end
end, TaggedRecord),
erl_syntax:tuple([Name|Vals]).
get_forms(Path) ->
case file:open(Path, [read]) of
{ok, Fd} ->
parse(Fd, 1, []);
Err ->
Err
end.
parse(Fd, Line, Acc) ->
{ok, Pos} = file:position(Fd, cur),
case epp_dodger:parse_form(Fd, Line) of
{ok, Form, NewLine} ->
case erl_syntax:type(Form) of
attribute ->
{ok, NewPos} = file:position(Fd, cur),
{ok, RawForm} = file:pread(Fd, Pos, NewPos - Pos),
file:position(Fd, {bof, NewPos}),
AnnForm = erl_syntax:set_ann(Form, RawForm),
parse(Fd, NewLine, [AnnForm|Acc]);
_ ->
parse(Fd, NewLine, [Form|Acc])
end;
{eof, _} ->
{ok, lists:reverse(Acc)};
_Err ->
file:position(Fd, {bof, Pos}),
case io:scan_erl_exprs(Fd, "", Line) of
{ok, Toks, NewLine} ->
case transform_spec_to_form(Toks) of
{ok, Form} ->
parse(Fd, NewLine, [Form|Acc]);
not_spec ->
parse(Fd, NewLine, Acc);
Err ->
Err
end;
{eof, _} ->
{ok, lists:reverse(Acc)};
Err ->
Err
end
end.
transform_spec_to_form([{'-', L0}, {atom, _, 'xml'}, {'(', _}|T]) ->
case lists:reverse(T) of
[{dot, L3}, {')', L2}|T1] ->
T2 = lists:reverse([{dot, L3}, {'}', L2}|T1]),
case erl_parse:parse_exprs([{'{', L0}|T2]) of
{ok, Form} ->
{ok, Form};
Err ->
Err
end;
_ ->
not_spec
end;
transform_spec_to_form(_) ->
not_spec.
-ifdef(HAVE_REMOTE_TYPES).
-ifdef(HAVE_FROM_FORM0).
t_from_form(Spec) ->
erl_types:t_from_form(Spec).
-else.
-ifdef(OLD_DIALYZER_NO_FILENAMES).
t_from_form(Spec) ->
erl_types:t_from_form(Spec, sets:new(), {spec, foo}, dict:new()).
-else.
t_from_form(Spec) ->
erl_types:t_from_form(Spec, sets:new(), {spec, foo, "mod.erl"}, dict:new()).
-endif.
-endif.
t_remote(Mod, Type) ->
erl_types:t_remote(Mod, Type, []).
-else.
-ifdef(OLD_DIALYZER_NO_FILENAMES).
t_from_form(Spec) ->
{T, _} = erl_types:t_from_form(
Spec, sets:new(), {type, {mod, foo, 1}}, dict:new(),
erl_types:var_table__new(), erl_types:cache__new()),
T.
-else.
t_from_form(Spec) ->
{T, _} = erl_types:t_from_form(
Spec, sets:new(), {type, {mod, foo, 1}, "mod.erl"}, dict:new(),
erl_types:var_table__new(), erl_types:cache__new()),
T.
-endif.
t_remote(Mod, Type) ->
D = dict_from_list([{{opaque, Type, []},
{{Mod, 1, 2, []}, type}}]),
[T] = erl_types:t_opaque_from_records(D),
T.
-endif.
-ifdef(USE_DICT).
dict_from_list(L) ->
dict:from_list(L).
dict_keys(D) ->
dict:fetch_keys(D).
-else.
dict_from_list(L) ->
maps:from_list(L).
dict_keys(D) ->
maps:keys(D).
-endif.
fast_xml-1.1.48/src/fxmlrpc.erl 0000644 0002322 0002322 00000011130 14151146420 016730 0 ustar debalance debalance %%%-------------------------------------------------------------------
%%% File : fxmlrpc.erl
%%% Author : Evgeny Khramtsov
%%% Purpose : XMLRPC encoder/decoder
%%% Created : 3 Oct 2014 by Evgeny Khramtsov
%%%
%%%
%%% Copyright (C) 2002-2021 ProcessOne, SARL. 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.
%%%
%%%-------------------------------------------------------------------
-module(fxmlrpc).
%% API
-export([decode/1, encode/1]).
-include("fxml.hrl").
-define(NS_XMLRPC, <<"xmlrpc">>).
-type value() :: number() | binary() | boolean() | nil |
{base64, binary()} |
{date, binary()} |
{array, [{atom(), value()}]} |
{struct, [value()]}.
-type fault() :: {fault, integer(), binary()}.
-type call() :: {call, atom(), [value()]}.
-type response() :: {response, [value()] | fault()}.
%%%===================================================================
%%% API
%%%===================================================================
-spec decode(xmlel()) -> {ok, call()} | {ok, response()} | {error, any()}.
decode(El) ->
try fxmlrpc_codec:decode(El, ?NS_XMLRPC, []) of
{call, Name, Params} ->
{ok, {call, Name, [decode_param(Param) || Param <- Params]}};
{response, Params} when is_list(Params) ->
{ok, {response, [decode_param(Param) || Param <- Params]}};
{response, {fault, {{struct, Struct}, _}}} ->
case proplists:get_value(faultCode, Struct) of
{{Tag, Code}, _} when Tag == int; Tag == i4 ->
case proplists:get_value(faultString, Struct) of
{{string, String}, _} ->
{ok, {response, {fault, Code, String}}};
{undefined, undefined} ->
{ok, {response, {fault, Code, <<"">>}}};
{undefined, String} when is_binary(String) ->
{ok, {response, {fault, Code, String}}};
_ ->
{error, {bad_struct, Struct}}
end;
_ ->
{error, {bad_struct, Struct}}
end;
Other ->
{error, {unexpected_element, Other}}
catch error:{fxmlrpc_codec, Reason} ->
{error, Reason}
end.
-spec encode(call() | response()) -> xmlel().
encode({call, Name, Params}) ->
fxmlrpc_codec:encode(
{call, Name, [encode_param(Param) || Param <- Params]},
?NS_XMLRPC);
encode({response, Params}) when is_list(Params) ->
fxmlrpc_codec:encode(
{response, [encode_param(Param) || Param <- Params]},
?NS_XMLRPC);
encode({response, {fault, Code, String}}) ->
fxmlrpc_codec:encode(
{response, {fault, {{struct, [{faultCode, {{int, Code}, undefined}},
{faultString, {{string, String}, undefined}}]},
undefined}}},
?NS_XMLRPC).
%%%===================================================================
%%% Internal functions
%%%===================================================================
decode_param({undefined, B}) when is_binary(B) ->
B;
decode_param({undefined, undefined}) ->
<<"">>;
decode_param({{int, Int}, _}) ->
Int;
decode_param({{i4, Int}, _}) ->
Int;
decode_param({{boolean, Bool}, _}) ->
Bool;
decode_param({{string, S}, _}) ->
S;
decode_param({{double, D}, _}) ->
D;
decode_param({{array, L}, _}) ->
{array, [decode_param(E) || E <- L]};
decode_param({{struct, S}, _}) ->
{struct, [{Name, decode_param(Value)} || {Name, Value} <- S]};
decode_param({{base64, B64}, _}) ->
{base64, B64};
decode_param({{date, Date}, _}) ->
{date, Date};
decode_param({nil, _}) ->
nil.
encode_param(Int) when is_integer(Int) ->
{{int, Int}, undefined};
encode_param(B) when is_boolean(B) ->
{{boolean, B}, undefined};
encode_param(S) when is_binary(S) ->
{{string, S}, undefined};
encode_param(S) when is_list(S) ->
{{string, iolist_to_binary(S)}, undefined};
encode_param(D) when is_float(D) ->
{{double, D}, undefined};
encode_param({array, L}) ->
{{array, [encode_param(E) || E <- L]}, undefined};
encode_param({struct, S}) ->
{{struct, [{Name, encode_param(Value)} || {Name, Value} <- S]}, undefined};
encode_param({base64, B64}) ->
{{base64, B64}, undefined};
encode_param({date, Date}) ->
{{date, Date}, undefined};
encode_param(nil) ->
{nil, undefined}.
fast_xml-1.1.48/src/fxmlrpc_codec_external.erl 0000644 0002322 0002322 00000000355 14151146420 021776 0 ustar debalance debalance %% Created automatically by XML generator (fxml_gen.erl)
%% Source: fxmlrpc_codec.spec
-module(fxmlrpc_codec_external).
-compile(export_all).
modules() -> [].
lookup(_, _) -> undefined.
lookup(Term) -> erlang:error(badarg, [Term]).
fast_xml-1.1.48/src/fxml_stream.erl 0000644 0002322 0002322 00000006647 14151146420 017617 0 ustar debalance debalance %%%----------------------------------------------------------------------
%%% File : fxml_stream.erl
%%% Author : Alexey Shchepin
%%% Purpose : Parse XML streams
%%% Created : 17 Nov 2002 by Alexey Shchepin
%%%
%%%
%%% Copyright (C) 2002-2021 ProcessOne, SARL. 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.
%%%
%%%----------------------------------------------------------------------
-module(fxml_stream).
-author('alexey@process-one.net').
-compile(no_native).
-on_load(init/0).
-export([new/1, new/2, new/3, parse/2, close/1, reset/1,
change_callback_pid/2, parse_element/1]).
-export([load_nif/0, load_nif/1]).
-include("fxml.hrl").
-record(xml_stream_state,
{callback_pid = self() :: pid(),
port :: port(),
stack = [] :: stack(),
size = 0 :: non_neg_integer(),
maxsize = infinity :: non_neg_integer() | infinity}).
-type xml_stream_el() :: {xmlstreamraw, binary()} |
{xmlstreamcdata, binary()} |
{xmlstreamelement, xmlel()} |
{xmlstreamend, binary()} |
{xmlstreamstart, binary(), [attr()]} |
{xmlstreamerror, binary()}.
-type xml_stream_state() :: #xml_stream_state{}.
-type stack() :: [xmlel()].
-export_type([xml_stream_state/0, xml_stream_el/0]).
init() ->
ok = load_nif().
load_nif() ->
SOPath = p1_nif_utils:get_so_path(?MODULE, [fast_xml], "fxml_stream"),
load_nif(SOPath).
load_nif(SOPath) ->
case erlang:load_nif(SOPath, 0) of
ok ->
ok;
{error, {Reason, Txt}} ->
error_logger:error_msg("failed to load NIF ~s: ~s",
[SOPath, Txt]),
{error, Reason}
end.
-spec new(pid()) -> xml_stream_state().
new(CallbackPid) ->
new(CallbackPid, infinity).
-spec new(pid(), non_neg_integer() | infinity) -> xml_stream_state().
new(_CallbackPid, _MaxSize) ->
erlang:nif_error(nif_not_loaded).
-spec new(pid(), non_neg_integer() | infinity, list()) -> xml_stream_state().
new(_CallbackPid, _MaxSize, _Options) ->
erlang:nif_error(nif_not_loaded).
-spec reset(xml_stream_state()) -> xml_stream_state().
reset(_State) ->
erlang:nif_error(nif_not_loaded).
-spec change_callback_pid(xml_stream_state(), pid()) -> xml_stream_state().
change_callback_pid(_State, _CallbackPid) ->
erlang:nif_error(nif_not_loaded).
-spec parse(xml_stream_state(), binary()) -> xml_stream_state().
parse(_State, _Data) ->
erlang:nif_error(nif_not_loaded).
-spec close(xml_stream_state()) -> true.
close(_State) ->
erlang:nif_error(nif_not_loaded).
-spec parse_element(binary()) -> xmlel() |
{error, atom()} |
{error, {integer(), binary()}}.
parse_element(_Str) ->
erlang:nif_error(nif_not_loaded).
fast_xml-1.1.48/src/fxml.erl 0000644 0002322 0002322 00000022122 14151146420 016226 0 ustar debalance debalance %%%----------------------------------------------------------------------
%%% File : fxml.erl
%%% Author : Alexey Shchepin
%%% Purpose : XML utils for parsing, matching, processing XML
%%% Created : 20 Nov 2002 by Alexey Shchepin
%%%
%%%
%%% Copyright (C) 2002-2021 ProcessOne, SARL. 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.
%%%
%%%----------------------------------------------------------------------
-module(fxml).
-author('alexey@process-one.net').
-compile(no_native).
-on_load(init/0).
-export([element_to_binary/1, element_to_header/1,
crypt/1, remove_cdata/1,
remove_subtags/3, get_cdata/1, get_tag_cdata/1,
get_attr/2, get_attr_s/2, get_tag_attr/2,
get_tag_attr_s/2, get_subtag/2, get_subtags/2, get_subtag_cdata/2,
get_subtag_with_xmlns/3, get_subtags_with_xmlns/3,
append_subtags/2, get_path_s/2,
replace_tag_attr/3, replace_subtag/2, to_xmlel/1]).
-export([load_nif/0, load_nif/1]).
-include("fxml.hrl").
-export_type([xmlel/0]).
init() ->
ok = load_nif().
%% Replace element_to_binary/1 with NIF
load_nif() ->
SOPath = p1_nif_utils:get_so_path(?MODULE, [fast_xml], "fxml"),
load_nif(SOPath).
load_nif(SOPath) ->
case catch erlang:load_nif(SOPath, 0) of
ok -> ok;
Err -> error_logger:warning_msg("unable to load fxml NIF: ~p~n", [Err]),
{error, unable_to_load_nif}
end.
%%
-spec element_to_binary(El :: xmlel() | cdata()) -> binary().
element_to_binary(_El) ->
erlang:nif_error(nif_not_loaded).
-spec element_to_header(El :: xmlel()) -> binary().
element_to_header(_El) ->
erlang:nif_error(nif_not_loaded).
crypt(S) ->
<< <<(case C of
$& -> <<"&">>;
$< -> <<"<">>;
$> -> <<">">>;
$" -> <<""">>;
$' -> <<"'">>;
_ -> <>
end)/binary>>
|| <> <= S >>.
%%
-spec remove_cdata_p(El :: xmlel() | cdata()) -> boolean().
remove_cdata_p(#xmlel{}) -> true;
remove_cdata_p(_) -> false.
%%
-spec remove_cdata(L :: [xmlel() | cdata()]) -> [xmlel()].
remove_cdata(L) -> [E || E <- L, remove_cdata_p(E)].
%% This function is intended to remove subtags based on a name and an
%% attribute, usually an xmlns attribute for a specific XMPP
%% extension.
-spec remove_subtags(Xmlel :: xmlel(), Name :: binary(),
Attr :: attr()) -> Xmlel :: xmlel().
remove_subtags(#xmlel{name = TagName, attrs = TagAttrs, children = Els},
Name, Attr) ->
#xmlel{name = TagName, attrs = TagAttrs,
children = remove_subtags1(Els, [], Name, Attr)}.
%%
-spec remove_subtags1(Els :: [xmlel() | cdata()], NewEls :: [xmlel()],
Name :: binary(), Attr :: attr()) ->
NewEls :: [xmlel()].
remove_subtags1([], NewEls, _Name, _Attr) ->
lists:reverse(NewEls);
remove_subtags1([El | Els], NewEls, Name,
{AttrName, AttrValue} = Attr) ->
case El of
#xmlel{name = Name, attrs = Attrs} ->
case get_attr(AttrName, Attrs) of
false ->
remove_subtags1(Els, [El | NewEls], Name, Attr);
{value, AttrValue} ->
remove_subtags1(Els, NewEls, Name, Attr);
_ -> remove_subtags1(Els, [El | NewEls], Name, Attr)
end;
_ -> remove_subtags1(Els, [El | NewEls], Name, Attr)
end.
-spec get_cdata(L :: [xmlel() | cdata()]) -> binary().
get_cdata(L) ->
(iolist_to_binary(get_cdata(L, <<"">>))).
-spec get_cdata(L :: [xmlel() | cdata()],
S :: binary() | iolist()) ->
binary() | iolist().
get_cdata([{xmlcdata, CData} | L], S) ->
get_cdata(L, [S, CData]);
get_cdata([_ | L], S) -> get_cdata(L, S);
get_cdata([], S) -> S.
-spec get_tag_cdata(Xmlel :: xmlel()) -> binary().
get_tag_cdata(#xmlel{children = Els}) -> get_cdata(Els).
%%
-spec get_attr(AttrName :: binary(), Attrs :: [attr()]) ->
{value, binary()} | false.
get_attr(AttrName, Attrs) ->
case lists:keysearch(AttrName, 1, Attrs) of
{value, {_, Val}} -> {value, Val};
_ -> false
end.
%%
-spec get_attr_s(AttrName :: binary(), Attrs :: [attr()]) ->
Val :: binary().
get_attr_s(AttrName, Attrs) ->
case lists:keysearch(AttrName, 1, Attrs) of
{value, {_, Val}} -> Val;
_ -> <<"">>
end.
%%
-spec get_tag_attr(AttrName :: binary(), Xmlel :: xmlel()) ->
{value, binary()} | false.
get_tag_attr(AttrName, #xmlel{attrs = Attrs}) ->
get_attr(AttrName, Attrs).
%%
-spec get_tag_attr_s(AttrName :: binary(), Xmlel :: xmlel()) -> binary().
get_tag_attr_s(AttrName, #xmlel{attrs = Attrs}) ->
get_attr_s(AttrName, Attrs).
%%
-spec get_subtag(Xmlel :: xmlel(), Name :: binary()) -> xmlel() | false.
get_subtag(#xmlel{children = Els}, Name) ->
get_subtag1(Els, Name).
%%
-spec get_subtag1(Els :: [xmlel() | cdata()], Name :: binary()) ->
xmlel() | false.
get_subtag1( [El | Els], Name) ->
case El of
#xmlel{name = Name} -> El;
_ -> get_subtag1(Els, Name)
end;
get_subtag1([], _) -> false.
-spec get_subtags(Xmlel :: xmlel(), Name :: binary()) -> [xmlel()].
get_subtags(#xmlel{children = Els}, Name) ->
get_subtags1(Els, Name, []).
get_subtags1([], _Name, Acc) ->
lists:reverse(Acc);
get_subtags1([El | Els], Name, Acc) ->
case El of
#xmlel{name = Name} -> get_subtags1(Els, Name, [El|Acc]);
_ -> get_subtags1(Els, Name, Acc)
end.
%%
-spec get_subtag_with_xmlns(Xmlel :: xmlel(), Name :: binary(),
XMLNS :: binary()) -> xmlel() | false.
get_subtag_with_xmlns(#xmlel{children = Els}, Name, XMLNS) ->
get_subtag_with_xmlns1(Els, Name, XMLNS).
%%
-spec get_subtag_with_xmlns1(Els :: [xmlel() | cdata()], Name :: binary(),
XMLNS :: binary()) -> xmlel() | false.
get_subtag_with_xmlns1([El | Els], Name, XMLNS) ->
case El of
#xmlel{name = Name, attrs = Attrs} ->
case get_attr(<<"xmlns">>, Attrs) of
{value, XMLNS} ->
El;
_ ->
get_subtag_with_xmlns1(Els, Name, XMLNS)
end;
_ ->
get_subtag_with_xmlns1(Els, Name, XMLNS)
end;
get_subtag_with_xmlns1([], _, _) ->
false.
-spec get_subtags_with_xmlns(Xmlel :: xmlel(), Name :: binary(),
XMLNS :: binary()) -> [xmlel()].
get_subtags_with_xmlns(#xmlel{children = Els}, Name, XMLNS) ->
get_subtags_with_xmlns1(Els, Name, XMLNS, []).
get_subtags_with_xmlns1([], _Name, _XMLNS, Acc) ->
lists:reverse(Acc);
get_subtags_with_xmlns1([El | Els], Name, XMLNS, Acc) ->
case El of
#xmlel{name = Name, attrs = Attrs} ->
case get_attr(<<"xmlns">>, Attrs) of
{value, XMLNS} ->
get_subtags_with_xmlns1(Els, Name, XMLNS, [El|Acc]);
_ ->
get_subtags_with_xmlns1(Els, Name, XMLNS, Acc)
end;
_ ->
get_subtags_with_xmlns1(Els, Name, XMLNS, Acc)
end.
%%
-spec get_subtag_cdata(Tag :: xmlel(), Name :: binary()) -> binary().
get_subtag_cdata(Tag, Name) ->
case get_subtag(Tag, Name) of
false -> <<"">>;
Subtag -> get_tag_cdata(Subtag)
end.
%%
-spec append_subtags(Xmlel :: xmlel(), SubTags2 :: [xmlel() | cdata()]) ->
Xmlel :: xmlel().
append_subtags(#xmlel{name = Name, attrs = Attrs, children = SubTags1}, SubTags2) ->
#xmlel{name = Name, attrs = Attrs, children = SubTags1 ++ SubTags2}.
%%
-spec get_path_s(El :: xmlel(), Path :: [{elem, Name::binary()} |
{attr, Name::binary()} |cdata]) ->
xmlel() | binary().
get_path_s(El, []) -> El;
get_path_s(El, [{elem, Name} | Path]) ->
case get_subtag(El, Name) of
false -> <<"">>;
SubEl -> get_path_s(SubEl, Path)
end;
get_path_s(El, [{attr, Name}]) ->
get_tag_attr_s(Name, El);
get_path_s(El, [cdata]) -> get_tag_cdata(El).
%%
-spec replace_tag_attr(Name :: binary(), Value :: binary(),
Xmlel :: xmlel()) ->
Xmlel :: #xmlel{ name :: binary(),
attrs :: [attr(),...],
children :: [xmlel() | cdata()] }.
replace_tag_attr(Name, Value, Xmlel) ->
Xmlel#xmlel{
attrs = [{Name, Value} | lists:keydelete(Name, 1, Xmlel#xmlel.attrs)]
}.
-spec replace_subtag(Tag :: xmlel(), Xmlel :: xmlel()) ->
Xmlel :: #xmlel{ name :: binary(),
attrs :: [attr(),...],
children :: [xmlel() | cdata()] }.
replace_subtag(#xmlel{name = Name} = Tag, Xmlel) ->
Xmlel#xmlel{
children = [Tag | lists:keydelete(Name, #xmlel.name, Xmlel#xmlel.children)]
}.
to_xmlel({_, Name, Attrs, Els}) ->
#xmlel{name = iolist_to_binary(Name),
attrs = [{iolist_to_binary(K), iolist_to_binary(V)}
|| {K, V} <- Attrs],
children = [to_xmlel(El) || El <- Els]};
to_xmlel({xmlcdata, CData}) ->
{xmlcdata, iolist_to_binary(CData)}.
fast_xml-1.1.48/src/fast_xml.erl 0000644 0002322 0002322 00000005127 14151146420 017103 0 ustar debalance debalance %%%----------------------------------------------------------------------
%%% File : fxml_app.erl
%%% Author : Evgeniy Khramtsov
%%% Purpose : Fast XML application
%%% Created : 1 May 2013 by Evgeniy Khramtsov
%%%
%%%
%%% Copyright (C) 2002-2021 ProcessOne, SARL. 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.
%%%
%%%----------------------------------------------------------------------
-module(fast_xml).
-behaviour(application).
%% Application callbacks
-export([start/2, stop/1]).
%%%===================================================================
%%% Application callbacks
%%%===================================================================
%%--------------------------------------------------------------------
%% @private
%% @doc
%% This function is called whenever an application is started using
%% application:start/[1,2], and should start the processes of the
%% application. If the application is structured according to the OTP
%% design principles as a supervision tree, this means starting the
%% top supervisor of the tree.
%%
%% @spec start(StartType, StartArgs) -> {ok, Pid} |
%% {ok, Pid, State} |
%% {error, Reason}
%% StartType = normal | {takeover, Node} | {failover, Node}
%% StartArgs = term()
%% @end
%%--------------------------------------------------------------------
start(_StartType, _StartArgs) ->
fxml_sup:start_link().
%%--------------------------------------------------------------------
%% @private
%% @doc
%% This function is called whenever an application has stopped. It
%% is intended to be the opposite of Module:start/2 and should do
%% any necessary cleaning up. The return value is ignored.
%%
%% @spec stop(State) -> void()
%% @end
%%--------------------------------------------------------------------
stop(_State) ->
ok.
%%%===================================================================
%%% Internal functions
%%%===================================================================
fast_xml-1.1.48/src/fast_xml.app.src 0000644 0002322 0002322 00000003250 14151146420 017662 0 ustar debalance debalance %%%----------------------------------------------------------------------
%%% File : fast_xml.app.src
%%% Author : Evgeniy Khramtsov
%%% Purpose : Application package description
%%% Created : 4 Apr 2013 by Evgeniy Khramtsov
%%%
%%%
%%% Copyright (C) 2002-2021 ProcessOne, SARL. 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.
%%%
%%%----------------------------------------------------------------------
{application, fast_xml,
[{description, "Fast Expat-based Erlang / Elixir XML parsing library"},
{vsn, "1.1.48"},
{modules, []},
{registered, []},
{applications, [kernel, stdlib, p1_utils]},
{mod, {fast_xml,[]}},
%% hex.pm packaging:
{files, ["src/", "lib/", "c_src/fxml.c", "c_src/fxml_stream.c", "include/", "priv/lib/.keepme", "configure", "mix.exs", "mix.lock", "Makefile.mix", "rebar.config", "rebar.config.script", "vars.config.in", "README.md", "LICENSE.txt"]},
{licenses, ["Apache 2.0"]},
{links, [{"Github", "https://github.com/processone/fast_xml"}]}]}.
%% Local Variables:
%% mode: erlang
%% End:
%% vim: set filetype=erlang tabstop=8:
fast_xml-1.1.48/rebar.config 0000644 0002322 0002322 00000004474 14151146420 016261 0 ustar debalance debalance %%%----------------------------------------------------------------------
%%% File : rebar.config
%%% Author : Evgeniy Khramtsov
%%% Purpose : Rebar build script. Compliant with rebar and rebar3.
%%% Created : 8 May 2013 by Evgeniy Khramtsov
%%%
%%% Copyright (C) 2002-2021 ProcessOne, SARL. 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.
%%%
%%%----------------------------------------------------------------------
{erl_opts, [debug_info,
nowarn_export_all,
{platform_define, "^(1|20|21|22|23)", 'OLD_DIALYZER_NO_FILENAMES'},
{platform_define, "^(15|16|17|18)", 'HAVE_REMOTE_TYPES'},
{platform_define, "^(15|16|17)", 'HAVE_FROM_FORM0'},
{platform_define, "^(1)", 'OLD_STRING'},
{platform_define, "^(15|16|17|18|19\\.0|19\\.1|19\\.2)", 'USE_DICT'}]}.
{port_env, [{"CFLAGS", "$CFLAGS"}, {"LDFLAGS", "$LDFLAGS"},
{"ERL_LDFLAGS", " -L$ERL_EI_LIBDIR -lei"},
{"freebsd", "CFLAGS", "$CFLAGS -I/usr/local/include"},
{"freebsd","LDFLAGS", "$LDFLAGS -L/usr/local/lib"}]}.
{port_specs, [{"priv/lib/fxml.so", ["c_src/fxml.c"]},
{"priv/lib/fxml_stream.so", ["c_src/fxml_stream.c"]}]}.
{deps, [{p1_utils, ".*", {git, "https://github.com/processone/p1_utils", {tag, "1.0.23"}}}]}.
{clean_files, ["c_src/fxml.gcda", "c_src/fxml.gcno", "c_src/fxml_stream.gcda", "c_src/fxml_stream.gcno"]}.
{cover_enabled, true}.
{cover_export_enabled, true}.
{coveralls_coverdata , "_build/test/cover/eunit.coverdata"}.
{coveralls_service_name , "github"}.
{xref_checks, [undefined_function_calls, undefined_functions, deprecated_function_calls, deprecated_functions]}.
{plugins, []}.
%% Local Variables:
%% mode: erlang
%% End:
%% vim: set filetype=erlang tabstop=8:
fast_xml-1.1.48/CODE_OF_CONDUCT.md 0000644 0002322 0002322 00000006433 14151146420 016573 0 ustar debalance debalance # Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at contact@process-one.net. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
fast_xml-1.1.48/include/ 0000755 0002322 0002322 00000000000 14151146420 015411 5 ustar debalance debalance fast_xml-1.1.48/include/fxml_gen.hrl 0000644 0002322 0002322 00000003127 14151146420 017722 0 ustar debalance debalance %%%----------------------------------------------------------------------
%%% File : xml_gen.hrl
%%% Author : Evgeniy Khramtsov
%%% Purpose : XML utils
%%% Created : 1 May 2013 by Evgeniy Khramtsov
%%%
%%%
%%% Copyright (C) 2002-2021 ProcessOne, SARL. 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.
%%%
%%%----------------------------------------------------------------------
-define(AST_MARK, ast__mark_).
-define(AST(Code), ?AST_MARK(Code)).
-record(attr, {name,
label,
required = false,
default = '$unset',
always_encode = false,
dec,
enc}).
-record(cdata, {required = false,
label = '$cdata',
default = '$unset',
dec,
enc}).
-record(elem, {name,
module,
xmlns = <<"">>,
cdata = #cdata{},
ignore_els = false,
result,
attrs = [],
refs = []}).
-record(ref, {name,
label,
min = 0,
max = infinity,
default}).
fast_xml-1.1.48/include/fxml.hrl 0000644 0002322 0002322 00000002323 14151146420 017066 0 ustar debalance debalance %%%----------------------------------------------------------------------
%%% File : fxml.hrl
%%% Author : Evgeniy Khramtsov
%%% Purpose : XML utils
%%% Created : 1 May 2013 by Evgeniy Khramtsov
%%%
%%%
%%% Copyright (C) 2002-2021 ProcessOne, SARL. 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.
%%%
%%%----------------------------------------------------------------------
-record(xmlel,
{
name = <<"">> :: binary(),
attrs = [] :: [attr()],
children = [] :: [xmlel() | cdata()]
}).
-type(cdata() :: {xmlcdata, CData::binary()}).
-type(attr() :: {Name::binary(), Value::binary()}).
-type(xmlel() :: #xmlel{}).
fast_xml-1.1.48/mix.exs 0000644 0002322 0002322 00000003321 14151146420 015303 0 ustar debalance debalance # Copyright (C) 2002-2021 ProcessOne, SARL. 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.
defmodule FastXML.Mixfile do
use Mix.Project
def project do
[ app: :fast_xml,
description: "Fast Expat-based Erlang / Elixir XML parsing library",
version: "1.1.28",
elixir: "~> 1.4",
compilers: [:elixir_make | Mix.compilers],
make_makefile: "Makefile",
deps: deps(),
package: package()
]
end
def application do
[ mod: {:fast_xml, []},
applications: [:p1_utils]
]
end
defp package do
[# These are the default files included in the package
files: ["src", "lib", "c_src/*.c", "mix.exs", "rebar.config", "rebar.config.script", "Makefile", "Makefile.mix", "priv", "include", "README.md", "LICENSE.txt"],
maintainers: ["ProcessOne"],
licenses: ["Apache 2.0"],
links: %{"GitHub" => "https://github.com/processone/fast_xml",
"Docs" => "https://github.com/processone/fast_xml/blob/master/README.md"}]
end
def deps do
[{:p1_utils, "~> 1.0"},
{:elixir_make, "~> 0.4", runtime: false},
{:earmark, "~> 0.1", only: :dev},
{:ex_doc, "~> 0.11", only: :dev},
{:eqc_ex, "~> 1.2", only: :test}]
end
end
fast_xml-1.1.48/test/ 0000755 0002322 0002322 00000000000 14151146420 014745 5 ustar debalance debalance fast_xml-1.1.48/test/test_helper.exs 0000644 0002322 0002322 00000000104 14151146420 017777 0 ustar debalance debalance ExUnit.start()
# Mix is starting application fast_xml automatically
fast_xml-1.1.48/test/fxml_test.erl 0000644 0002322 0002322 00000107475 14151146420 017474 0 ustar debalance debalance %%%----------------------------------------------------------------------
%%% File : fxml_test.erl
%%% Author : Evgeniy Khramtsov
%%% Purpose : xml module testing
%%% Created : 17 Dec 2013 by Evgeny Khramtsov
%%%
%%%
%%% Copyright (C) 2002-2021 ProcessOne, SARL. 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.
%%%
%%%----------------------------------------------------------------------
-module(fxml_test).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").
-include("fxml.hrl").
new() ->
new(self()).
new(Pid) ->
new(Pid, infinity).
new(Pid, MaxSize) ->
fxml_stream:new(Pid, MaxSize).
close(State) ->
?assertEqual(true, fxml_stream:close(State)).
start_test() ->
?assertMatch({ok, _}, application:ensure_all_started(fast_xml)),
?assertMatch(ok, application:stop(fast_xml)),
?assertMatch({ok, _}, application:ensure_all_started(fast_xml)),
?assertMatch(ok, application:stop(fast_xml)).
tag_test() ->
?assertEqual(#xmlel{name = <<"root">>},
fxml_stream:parse_element(<<"">>)).
empty_tag_test() ->
?assertEqual(#xmlel{name = <<"root">>},
fxml_stream:parse_element(<<"">>)).
empty_tag_with_ns_test() ->
?assertEqual(#xmlel{name = <<"root">>, attrs = [{<<"xmlns">>, <<"ns">>}]},
fxml_stream:parse_element(<<"">>)).
tag_with_cdata_test() ->
?assertEqual(#xmlel{name = <<"root">>,
children = [{xmlcdata, <<"cdata">>}]},
fxml_stream:parse_element(<<"cdata">>)).
tag_with_attrs_test() ->
?assertEqual(#xmlel{name = <<"root">>,
attrs = [{<<"a">>, <<"1">>}, {<<"b">>, <<"2">>}]},
fxml_stream:parse_element(<<"">>)).
tag_with_empty_attr_test() ->
?assertEqual(#xmlel{name = <<"root">>, attrs = [{<<"a">>, <<>>}]},
fxml_stream:parse_element(<<"">>)).
tag_with_prefix_test() ->
?assertEqual(#xmlel{name = <<"prefix:root">>,
attrs = [{<<"xmlns:prefix">>, <<"ns">>}]},
fxml_stream:parse_element(<<"">>)).
tag_with_prefix_children1_test() ->
?assertEqual(#xmlel{name = <<"prefix:root">>,
attrs = [{<<"xmlns:prefix">>, <<"ns">>}],
children = [#xmlel{name = <<"prefix:a">>}]},
fxml_stream:parse_element(<<"">>)).
tag_with_prefix_children2_test() ->
?assertEqual(#xmlel{name = <<"prefix:root">>,
attrs = [{<<"xmlns:prefix">>, <<"ns">>}],
children = [#xmlel{name = <<"a">>, attrs=[{<<"xmlns">>, <<"ns2">>}]}]},
fxml_stream:parse_element(<<"">>)).
tag_with_prefix_children3_test() ->
?assertEqual(#xmlel{name = <<"prefix:root">>,
attrs = [{<<"xmlns:prefix">>, <<"ns">>}],
children = [#xmlel{name = <<"zed:a">>, attrs=[{<<"xmlns:zed">>, <<"ns2">>}]}]},
fxml_stream:parse_element(<<"">>)).
tag_with_prefix_children4_test() ->
?assertEqual(#xmlel{name = <<"prefix:root">>,
attrs = [{<<"xmlns:prefix">>, <<"ns">>}],
children = [#xmlel{name = <<"a">>, attrs=[{<<"xmlns">>, <<"ns">>}]}]},
fxml_stream:parse_element(<<"">>)).
tag_with_attr_with_prefix_test() ->
?assertEqual(#xmlel{name = <<"root">>,
attrs = [{<<"xmlns:prefix1">>, <<"ns1">>},
{<<"xmlns:prefix2">>, <<"ns2">>},
{<<"prefix1:a">>, <<"1">>},
{<<"prefix2:b">>, <<"2">>}]},
fxml_stream:parse_element(<<
"">>)).
tag_with_tags_test() ->
?assertEqual(#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"a">>},
{xmlcdata, <<"cdata1">>},
#xmlel{name = <<"b">>},
{xmlcdata, <<"cdata2">>}]},
fxml_stream:parse_element(<<"cdata1cdata2">>)).
receiver(Acc) ->
receive
{'$gen_event', Msg} ->
receiver([Msg|Acc]);
{get, Parent} ->
Parent ! lists:reverse(Acc),
receiver([]);
{close, Parent} ->
Parent ! closed
end.
collect_events(Pid) ->
Pid ! {get, self()},
receive
Events ->
Events
end.
close_collector(Pid) ->
Pid ! {close, self()},
receive
closed ->
closed
end.
parser_loop(TestData) ->
parser_loop(infinity, [], TestData).
parser_loop(MaxSize, Options, TestData) ->
CollectorPid = spawn_link(fun() -> receiver([]) end),
parser_loop_int(TestData, fxml_stream:new(CollectorPid, MaxSize, Options), CollectorPid).
parser_loop_int([reset | Tail], Handle, CollectorPid) ->
parser_loop_int(Tail, fxml_stream:reset(Handle), CollectorPid);
parser_loop_int([{Input, Output} | Tail], Handle, CollectorPid) ->
NHandle = fxml_stream:parse(Handle, Input),
?assertEqual(Output, collect_events(CollectorPid)),
parser_loop_int(Tail, NHandle, CollectorPid);
parser_loop_int([], Handle, CollectorPid) ->
close(Handle),
close_collector(CollectorPid).
stream_test() ->
CallbackPid = spawn_link(fun() -> receiver([]) end),
Stream0 = new(CallbackPid),
Data = [<<"">>,
<<"junk1">>, <<"">>, <<"junk2">>, <<"cdata">>,
<<"junk3">>, <<"">>],
StreamN = lists:foldl(
fun(Chunk, Stream) ->
fxml_stream:parse(Stream, Chunk)
end, Stream0, Data),
close(StreamN),
?assertEqual(
[{xmlstreamstart, <<"prefix:root">>, [{<<"xmlns:prefix">>, <<"ns">>},
{<<"prefix:r">>, <<"1">>}]},
{xmlstreamelement, #xmlel{name = <<"a">>}},
{xmlstreamelement, #xmlel{name = <<"b">>,
children = [{xmlcdata, <<"cdata">>}]}},
{xmlstreamend, <<"prefix:root">>}],
collect_events(CallbackPid)).
stream_normalized_ns_test() ->
CallbackPid = spawn_link(fun() -> receiver([]) end),
Stream0 = new(CallbackPid),
Data = [<<"">>,
<<"junk1">>, <<"">>,
<<"">>,
<<"">>, <<"">>,
<<"">>, <<"">>,
<<"">>, <<"">>,
<<"">>,
<<"junk2">>, <<"cdata">>,
<<"junk3">>, <<"">>],
StreamN = lists:foldl(
fun(Chunk, Stream) ->
fxml_stream:parse(Stream, Chunk)
end, Stream0, Data),
close(StreamN),
?assertEqual(
[{xmlstreamstart, <<"prefix:root">>, [{<<"xmlns">>, <<"ns0">>},
{<<"xmlns:t">>, <<"ns1">>},
{<<"xmlns:prefix">>, <<"ns">>},
{<<"prefix:r">>, <<"1">>}]},
{xmlstreamelement, #xmlel{name = <<"a">>}},
{xmlstreamelement, #xmlel{name = <<"t:a">>,
children=[#xmlel{name = <<"b">>,
attrs=[{<<"xmlns">>, <<"ns2">>}, {<<"xmlns:s">>, <<"ns2">>}],
children=[#xmlel{name = <<"c">>,
attrs=[{<<"xmlns">>, <<"ns0">>}]}]}]}},
{xmlstreamelement, #xmlel{name = <<"prefix:n1">>}},
{xmlstreamelement, #xmlel{name = <<"prefix:n1">>}},
{xmlstreamelement, #xmlel{name = <<"a">>, attrs=[{<<"xmlns">>, <<"ns5">>}],
children=[#xmlel{name = <<"b">>}, #xmlel{name = <<"t:c">>}]}},
{xmlstreamelement, #xmlel{name = <<"n2">>, attrs=[{<<"xmlns">>, <<"2">>}]}},
{xmlstreamelement, #xmlel{name = <<"t:n3">>}},
{xmlstreamelement, #xmlel{name = <<"n4">>, attrs=[{<<"xmlns">>, <<"3">>}, {<<"xmlns:v">>, <<"3">>}]}},
{xmlstreamelement, #xmlel{name = <<"n5">>, attrs=[{<<"xmlns">>, <<"n4">>}, {<<"xmlns:prefix">>, <<"n4">>}],
children=[#xmlel{name = <<"e1">>, attrs=[{<<"xmlns">>, <<"ns0">>}]},
#xmlel{name = <<"e2">>}]}},
{xmlstreamelement, #xmlel{name = <<"b">>,
children = [{xmlcdata, <<"cdata">>}]}},
{xmlstreamend, <<"prefix:root">>}],
collect_events(CallbackPid)).
stream_reset_test() ->
parser_loop([{<<"">>,
[{xmlstreamstart, <<"a">>, [{<<"xmlns">>, <<"ns1">>}]},
{xmlstreamelement, #xmlel{name = <<"b">>}}]},
reset,
{<<"">>,
[{xmlstreamstart, <<"a">>, []},
{xmlstreamelement, #xmlel{name = <<"b">>}},
{xmlstreamend, <<"a">>}]}
]).
stream_error_test() ->
CallbackPid = spawn_link(fun() -> receiver([]) end),
S0 = new(CallbackPid),
S1 = fxml_stream:parse(S0, <<"a">>),
close(S1),
?assertEqual(
[{xmlstreamstart, <<"a">>, []},
{xmlstreamerror, {7, <<"mismatched tag">>}}],
collect_events(CallbackPid)).
stream_with_joined_cdata_test() ->
CallbackPid = spawn_link(fun() -> receiver([]) end),
Stream0 = new(CallbackPid),
Data = [<<"">>, <<"">>, <<"1">>, <<"2">>, <<"3">>,
<<"">>, <<"">>],
StreamN = lists:foldl(
fun(Chunk, Stream) ->
fxml_stream:parse(Stream, Chunk)
end, Stream0, Data),
close(StreamN),
?assertEqual(
[{xmlstreamstart, <<"root">>, []},
{xmlstreamelement, #xmlel{name = <<"a">>,
children = [{xmlcdata, <<"123">>}]}},
{xmlstreamend, <<"root">>}],
collect_events(CallbackPid)).
splitted_stream_test() ->
CallbackPid = spawn_link(fun() -> receiver([]) end),
Stream0 = new(CallbackPid),
Stream1 = fxml_stream:parse(Stream0, <<">),
?assertEqual([], collect_events(CallbackPid)),
Stream2 = fxml_stream:parse(Stream1, <<">">>),
?assertEqual([{xmlstreamstart, <<"root">>, []}],
collect_events(CallbackPid)),
Stream3 = fxml_stream:parse(Stream2, <<">}},
{xmlstreamelement, #xmlel{name = <<"b">>}}],
collect_events(CallbackPid)),
Stream4 = fxml_stream:parse(Stream3, <<"'1'>">>),
?assertEqual([{xmlstreamelement, #xmlel{name = <<"c">>,
attrs = [{<<"attr">>, <<"1">>}]}}],
collect_events(CallbackPid)),
Stream5 = fxml_stream:parse(Stream4, <<"">>),
?assertEqual([], collect_events(CallbackPid)),
Stream6 = fxml_stream:parse(Stream5, <<"">>),
?assertEqual([{xmlstreamend, <<"root">>}], collect_events(CallbackPid)),
close(Stream6).
map_stream_test() ->
parser_loop(infinity, [use_maps], [
{<<"">>,
[#{'__struct__' => 'Elixir.FastXML.StreamStart',
attrs => #{},
name => <<"a">>},
#{'__struct__' => 'Elixir.FastXML.El',
attrs => #{},
children => [],
name => <<"b">>}]},
reset,
{<<"">>,
[#{'__struct__' => 'Elixir.FastXML.StreamStart',
attrs => #{},
name => <<"a">>},
#{'__struct__' => 'Elixir.FastXML.El',
attrs => #{<<"c">> => <<"1">>},
children => [],
name => <<"b">>},
#{'__struct__' => 'Elixir.FastXML.StreamEnd',
name => <<"a">>}]}
]).
streaming_mismatched_tags_error_test() ->
parser_loop([{<<">, []},
{<<">">>, [{xmlstreamstart, <<"root">>, []}]},
{<<">}},
{xmlstreamelement, #xmlel{name = <<"b">>}}]},
{<<"'1'>">>,
[{xmlstreamelement, #xmlel{name = <<"c">>,
attrs = [{<<"attr">>, <<"1">>}]}}]},
{<<"">>,
[{xmlstreamerror,{7,<<"mismatched tag">>}}]}
]).
streaming_invalid_attribute_error_test() ->
parser_loop([{<<">, []},
{<<">">>, [{xmlstreamstart, <<"root">>, []}]},
{<<">}},
{xmlstreamelement, #xmlel{name = <<"b">>}}]},
{<<"'1>">>,
[{xmlstreamerror,{4,<<"not well-formed (invalid token)">>}}]}
]).
xmpp_stream_test() ->
parser_loop([{<<"",
"">>,
[{xmlstreamstart,<<"stream:stream">>,
[{<<"xmlns:stream">>,<<"http://etherx.jabber.org/streams">>},
{<<"to">>,<<"server.com">>},
{<<"version">>,<<"1.0">>},
{<<"xml:lang">>, <<"pl">>}]}]},
{<<"",
"",
"">>,
[{xmlstreamelement,
{xmlel,<<"stream:features">>,
[],
[{xmlel,<<"register">>,
[{<<"xmlns">>,<<"http://jabber.org/features/iq-register">>}],
[]}]}}]},
{<<"">>,
[{xmlstreamelement,
{xmlel,<<"a">>,
[{<<"xmlns">>,<<"b">>}, {<<"xmlns:a">>,<<"b">>}],
[{xmlel,<<"c">>,[], []}]}}]},
reset,
{<<"",
"">>,
[{xmlstreamstart,<<"stream:stream">>,
[{<<"xmlns">>,<<"jabber:client">>},
{<<"xmlns:stream">>,<<"http://etherx.jabber.org/streams">>},
{<<"to">>,<<"server.com">>},
{<<"version">>,<<"1.0">>},
{<<"xml:lang">>, <<"pl">>}]}]},
reset,
{<<"",
"">>,
[{xmlstreamstart, <<"stream:stream">>,
[{<<"xmlns:stream">>, <<"http://etherx.jabber.org/streams">>},
{<<"xmlns">>, <<"jabber:client">>},
{<<"to">>, <<"server.com">>},
{<<"version">>, <<"1.0">>},
{<<"xml:lang">>, <<"pl">>}]}]}
]).
too_big_test() ->
CallbackPid = spawn_link(fun() -> receiver([]) end),
Stream0 = new(CallbackPid, 5),
Stream1 = fxml_stream:parse(Stream0, <<"">>),
Stream2 = fxml_stream:parse(Stream1, <<"">>),
Stream3 = fxml_stream:parse(Stream2, <<"">>),
Stream4 = fxml_stream:parse(Stream3, <<"">>),
?assertEqual([{xmlstreamstart, <<"a">>, []},
{xmlstreamelement, #xmlel{name = <<"b">>}},
{xmlstreamelement, #xmlel{name = <<"c">>}},
{xmlstreamerror, <<"XML stanza is too big">>}],
collect_events(CallbackPid)),
close(Stream4).
too_big_with_data_after_test() ->
parser_loop(30, [],
[{
<<"">>,
[{xmlstreamstart, <<"start">>, []}]
},
{
<<">,
[]
},
{
<<"<1234567890123456790123456789012345678901234567890/>">>,
[{xmlstreamerror, <<"XML stanza is too big">>}]
},
{
<<"z='1'/>">>,
[{xmlstreamerror, <<"XML stanza is too big">>}]
},
{
<<"">>,
[{xmlstreamerror, <<"XML stanza is too big">>}]
}]).
close_close_test() ->
Stream = new(),
close(Stream),
?assertError(badarg, fxml_stream:close(Stream)).
close_parse_test() ->
Stream = new(),
close(Stream),
?assertError(badarg, fxml_stream:parse(Stream, <<"junk">>)).
close_change_callback_pid_test() ->
Stream = new(),
close(Stream),
?assertError(badarg, fxml_stream:change_callback_pid(Stream, self())).
change_callback_pid_test() ->
Pid1 = spawn_link(fun() -> receiver([]) end),
Pid2 = spawn_link(fun() -> receiver([]) end),
Stream0 = new(Pid1),
Stream1 = fxml_stream:parse(Stream0, <<"">>),
?assertEqual([{xmlstreamstart, <<"root">>, []}],
collect_events(Pid1)),
Stream2 = fxml_stream:change_callback_pid(Stream1, Pid2),
Stream3 = fxml_stream:parse(Stream2, <<"">>),
?assertEqual([{xmlstreamend, <<"root">>}],
collect_events(Pid2)),
close(Stream3).
badarg_new_test() ->
?assertError(badarg, fxml_stream:new(1)),
?assertError(badarg, fxml_stream:new(self(), unlimited)),
?assertError(badarg, fxml_stream:new(foo, fun() -> ok end)).
badarg_parse_test() ->
Stream = new(),
?assertError(badarg, fxml_stream:parse(1, <<"">>)),
?assertError(badarg, fxml_stream:parse(<<>>, "")),
?assertError(badarg, fxml_stream:parse(Stream, blah)),
?assertError(badarg, fxml_stream:parse(foo, fun() -> ok end)),
close(Stream).
badarg_change_callback_pid_test() ->
Stream = new(),
?assertError(badarg, fxml_stream:change_callback_pid(1, self())),
?assertError(badarg, fxml_stream:change_callback_pid(<<>>, self())),
?assertError(badarg, fxml_stream:change_callback_pid(Stream, foo)),
?assertError(badarg, fxml_stream:change_callback_pid(foo, fun() -> ok end)),
close(Stream).
badarg_close_test() ->
Stream = new(),
?assertError(badarg, fxml_stream:close(1)),
?assertError(badarg, fxml_stream:close(<<>>)),
close(Stream).
badarg_parse_element_test() ->
?assertError(badarg, fxml_stream:parse_element(1)).
parse_error_test() ->
L = ["<", "<>", ">", ">", "/>",
"", "x/>", "junk",
"", "", "",
"", ""],
lists:foreach(
fun(S) ->
?assertMatch({error, _}, fxml_stream:parse_element(list_to_binary(S)))
end, L).
dead_pid_test() ->
CallbackPid = spawn(fun() -> receiver([]) end),
?assertEqual(true, exit(CallbackPid, kill)),
?assertEqual(false, is_process_alive(CallbackPid)),
Stream0 = new(CallbackPid),
Stream1 = fxml_stream:parse(Stream0, <<"">>),
close(Stream1).
huge_element_test_() ->
{timeout, 60,
fun() ->
Tags = [list_to_binary(["a", integer_to_list(I)])
|| I <- lists:seq(1, 100000)],
Data = ["", [[$<, Tag, "/>"] || Tag <- Tags], ""],
Els = #xmlel{name = <<"root">>,
children = [#xmlel{name = Tag} || Tag <- Tags]},
?assertEqual(Els, fxml_stream:parse_element(iolist_to_binary(Data)))
end}.
many_stream_elements_test_() ->
{timeout, 60,
fun() ->
CallbackPid = spawn(fun() -> receiver([]) end),
Stream0 = new(CallbackPid),
Stream1 = fxml_stream:parse(Stream0, <<"">>),
?assertEqual([{xmlstreamstart, <<"root">>, []}],
collect_events(CallbackPid)),
Stream2 = lists:foldl(
fun(I, Stream) ->
Tag = list_to_binary(["a", integer_to_list(I)]),
NewStream = fxml_stream:parse(Stream, iolist_to_binary([$<, Tag, "/>"])),
?assertEqual([{xmlstreamelement, #xmlel{name = Tag}}],
collect_events(CallbackPid)),
NewStream
end, Stream1, lists:seq(1, 100000)),
close(Stream2)
end}.
billionlaughs_test() ->
Data = <<
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
"] >\n">>,
CallbackPid = spawn_link(fun() -> receiver([]) end),
Stream0 = new(CallbackPid),
Stream1 = fxml_stream:parse(Stream0, Data),
close(Stream1),
?assertMatch([{xmlstreamerror, _}], collect_events(CallbackPid)).
element_to_binary_entities_test() ->
S = <<"a<>&"'b">>,
E = #xmlel{name = <<"a">>,
attrs = [{<<"b">>, <<"a\t\n\r<>&\"'b">>}],
children = [{xmlcdata, <<"a<>&\"'b">>}]},
R = fxml:element_to_binary(E),
?assertEqual(S, R),
?assertEqual(E, fxml_stream:parse_element(R)).
element_to_binary_resize_test() ->
A = #xmlel{
name = <<"a">>,
children = [{xmlcdata, <<"1234567890123456790123456789012345678901234567890">>}]
},
?assertEqual(
<<"",
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
"1234567890123456790123456789012345678901234567890"
""
>>,
fxml:element_to_binary(
#xmlel{name = <<"t">>,
children = [A, A, A, A, A,
A, A, A, A, A,
A, A, A, A, A,
A, A, A, A, A]
})).
element_to_binary_test() ->
?assertEqual(
<<""
"">>,
fxml:element_to_binary(
#xmlel{name = <<"iq">>,
attrs = [{<<"from">>,<<"hag66@shakespeare.lit/pda">>},
{<<"id">>,<<"ik3vs715">>},
{<<"to">>,<<"coven@chat.shakespeare.lit">>},
{<<"type">>,<<"get">>}],
children = [#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>,
<<"http://jabber.org/protocol/disco#info">>}],
children = []}]})).
element_to_header_test() ->
?assertEqual(
<<"">>,
fxml:element_to_header(
#xmlel{name = <<"stream:stream">>,
attrs = [{<<"xmlns:stream">>,<<"http://etherx.jabber.org/streams">>},
{<<"xmlns">>,<<"jabber:server">>},
{<<"xmlns:db">>,<<"jabber:server:dialback">>},
{<<"id">>,<<"4774242664715222330">>},
{<<"version">>,<<"1.0">>}]})).
element_to_header_xmlcdata_test() ->
?assertError(badarg, fxml:element_to_header({xmlcdata, <<"">>})).
crypt_test() ->
?assertEqual(
<<"a&b<c>d"e'f">>,
fxml:crypt(<<"a&bd\"e\'f">>)).
remove_cdata_test() ->
?assertEqual(
[#xmlel{name = <<"b">>}],
fxml:remove_cdata(
[{xmlcdata, <<"x">>},
{xmlcdata, <<"y">>},
#xmlel{name = <<"b">>},
{xmlcdata, <<"z">>}])).
remove_subtags_test() ->
?assertMatch(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"2">>,
attrs = [{<<"n1">>, <<"v1">>}]},
#xmlel{name = <<"1">>,
attrs = [{<<"n1">>, <<"v2">>}]},
#xmlel{name = <<"1">>,
attrs = [{<<"n2">>, <<"v1">>}]},
#xmlel{name = <<"3">>}]},
fxml:remove_subtags(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"1">>,
attrs = [{<<"n1">>, <<"v1">>}]},
#xmlel{name = <<"2">>,
attrs = [{<<"n1">>, <<"v1">>}]},
#xmlel{name = <<"1">>,
attrs = [{<<"n1">>, <<"v2">>}]},
#xmlel{name = <<"1">>,
attrs = [{<<"n2">>, <<"v1">>}]},
#xmlel{name = <<"1">>,
attrs = [{<<"n1">>, <<"v1">>}]},
#xmlel{name = <<"3">>}]},
<<"1">>, {<<"n1">>, <<"v1">>})).
get_cdata_test() ->
?assertEqual(
<<"xyz">>,
fxml:get_cdata(
[{xmlcdata, <<"x">>},
{xmlcdata, <<"y">>},
#xmlel{name = <<"b">>},
{xmlcdata, <<"z">>}])).
get_tag_cdata_test() ->
?assertEqual(
<<"xyz">>,
fxml:get_tag_cdata(
#xmlel{name = <<"a">>,
children = [{xmlcdata, <<"x">>},
{xmlcdata, <<"y">>},
#xmlel{name = <<"b">>},
{xmlcdata, <<"z">>}]})).
get_attr_test() ->
?assertEqual(
{value, <<"2">>},
fxml:get_attr(
<<"y">>,
[{<<"x">>, <<"1">>},
{<<"y">>, <<"2">>},
{<<"z">>, <<"3">>}])).
get_attr_empty_test() ->
?assertEqual(
false,
fxml:get_attr(
<<"a">>,
[{<<"x">>, <<"1">>},
{<<"y">>, <<"2">>},
{<<"z">>, <<"3">>}])).
get_attr_s_test() ->
?assertEqual(
<<"2">>,
fxml:get_attr_s(
<<"y">>,
[{<<"x">>, <<"1">>},
{<<"y">>, <<"2">>},
{<<"z">>, <<"3">>}])).
get_attr_s_empty_test() ->
?assertEqual(
<<"">>,
fxml:get_attr_s(
<<"a">>,
[{<<"x">>, <<"1">>},
{<<"y">>, <<"2">>},
{<<"z">>, <<"3">>}])).
get_tag_attr_test() ->
?assertEqual(
{value, <<"2">>},
fxml:get_tag_attr(
<<"y">>,
#xmlel{name = <<"foo">>,
attrs = [{<<"x">>, <<"1">>},
{<<"y">>, <<"2">>},
{<<"z">>, <<"3">>}]})).
get_tag_attr_empty_test() ->
?assertEqual(
false,
fxml:get_tag_attr(
<<"a">>,
#xmlel{name = <<"foo">>,
attrs = [{<<"x">>, <<"1">>},
{<<"y">>, <<"2">>},
{<<"z">>, <<"3">>}]})).
get_tag_attr_s_test() ->
?assertEqual(
<<"2">>,
fxml:get_tag_attr_s(
<<"y">>,
#xmlel{name = <<"foo">>,
attrs = [{<<"x">>, <<"1">>},
{<<"y">>, <<"2">>},
{<<"z">>, <<"3">>}]})).
get_tag_attr_s_empty_test() ->
?assertEqual(
<<"">>,
fxml:get_tag_attr_s(
<<"a">>,
#xmlel{name = <<"foo">>,
attrs = [{<<"x">>, <<"1">>},
{<<"y">>, <<"2">>},
{<<"z">>, <<"3">>}]})).
get_subtag_test() ->
?assertMatch(
#xmlel{name = <<"2">>},
fxml:get_subtag(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"1">>},
#xmlel{name = <<"2">>},
#xmlel{name = <<"3">>}]},
<<"2">>)).
get_subtag_false_test() ->
?assertMatch(
false,
fxml:get_subtag(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"1">>},
#xmlel{name = <<"2">>},
#xmlel{name = <<"3">>}]},
<<"4">>)).
get_subtags_test() ->
?assertMatch(
[#xmlel{name = <<"1">>, attrs = [{<<"a">>, <<"b">>}]},
#xmlel{name = <<"1">>, attrs = [{<<"x">>, <<"y">>}]}],
fxml:get_subtags(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"1">>,
attrs = [{<<"a">>, <<"b">>}]},
#xmlel{name = <<"2">>},
#xmlel{name = <<"3">>},
#xmlel{name = <<"1">>,
attrs = [{<<"x">>, <<"y">>}]}]},
<<"1">>)).
get_subtags_empty_test() ->
?assertEqual(
[],
fxml:get_subtags(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"1">>},
#xmlel{name = <<"2">>},
#xmlel{name = <<"3">>}]},
<<"4">>)).
get_subtag_with_xmlns_test() ->
?assertMatch(
#xmlel{name = <<"2">>,
attrs = [{<<"xmlns">>, <<"ns1">>}]},
fxml:get_subtag_with_xmlns(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"1">>,
attrs = [{<<"xmlns">>, <<"ns1">>}]},
#xmlel{name = <<"2">>,
attrs = [{<<"xmlns">>, <<"ns2">>}]},
#xmlel{name = <<"2">>,
attrs = [{<<"xmlns">>, <<"ns1">>}]},
#xmlel{name = <<"3">>,
attrs = [{<<"xmlns">>, <<"ns2">>}]}]},
<<"2">>, <<"ns1">>)).
get_subtag_with_xmlns_empty_test() ->
?assertMatch(
false,
fxml:get_subtag_with_xmlns(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"1">>,
attrs = [{<<"xmlns">>, <<"ns1">>}]},
#xmlel{name = <<"2">>,
attrs = [{<<"xmlns">>, <<"ns2">>}]},
#xmlel{name = <<"2">>,
attrs = [{<<"xmlns">>, <<"ns1">>}]},
#xmlel{name = <<"3">>,
attrs = [{<<"xmlns">>, <<"ns2">>}]}]},
<<"4">>, <<"ns2">>)).
get_subtags_with_xmlns_test() ->
?assertMatch(
[#xmlel{name = <<"2">>,
attrs = [{<<"xmlns">>, <<"ns1">>}],
children = [{xmlcdata, <<"foo">>}]},
#xmlel{name = <<"2">>,
attrs = [{<<"xmlns">>, <<"ns1">>}],
children = [{xmlcdata, <<"bar">>}]}],
fxml:get_subtags_with_xmlns(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"1">>,
attrs = [{<<"xmlns">>, <<"ns1">>}]},
#xmlel{name = <<"2">>,
children = [{xmlcdata, <<"foo">>}],
attrs = [{<<"xmlns">>, <<"ns1">>}]},
#xmlel{name = <<"2">>,
attrs = [{<<"xmlns">>, <<"ns2">>}]},
#xmlel{name = <<"2">>,
children = [{xmlcdata, <<"bar">>}],
attrs = [{<<"xmlns">>, <<"ns1">>}]},
#xmlel{name = <<"3">>,
attrs = [{<<"xmlns">>, <<"ns2">>}]}]},
<<"2">>, <<"ns1">>)).
get_subtag_cdata_test() ->
?assertEqual(
<<"ab">>,
fxml:get_subtag_cdata(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"1">>,
children = [{xmlcdata, <<"a">>},
#xmlel{name = <<"3">>},
{xmlcdata, <<"b">>}]},
#xmlel{name = <<"2">>}]},
<<"1">>)).
get_subtag_cdata_empty_test() ->
?assertEqual(
<<"">>,
fxml:get_subtag_cdata(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"2">>}]},
<<"1">>)).
append_subtags_test() ->
?assertMatch(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"1">>},
#xmlel{name = <<"2">>},
#xmlel{name = <<"3">>}]},
fxml:append_subtags(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"1">>}]},
[#xmlel{name = <<"2">>}, #xmlel{name = <<"3">>}])).
get_path_s_tag_test() ->
?assertMatch(
#xmlel{name = <<"2">>},
fxml:get_path_s(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"1">>},
#xmlel{name = <<"2">>}]},
[{elem, <<"2">>}])).
get_path_s_empty_tag_test() ->
?assertEqual(
<<"">>,
fxml:get_path_s(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"1">>},
#xmlel{name = <<"2">>}]},
[{elem, <<"3">>}])).
get_path_s_attr_test() ->
?assertEqual(
<<"v1">>,
fxml:get_path_s(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"a">>,
children =
[#xmlel{name = <<"a1">>,
attrs = [{<<"x">>, <<"y">>},
{<<"n1">>, <<"v1">>}]},
#xmlel{name = <<"b">>}]},
#xmlel{name = <<"b">>}]},
[{elem, <<"a">>}, {elem, <<"a1">>}, {attr, <<"n1">>}])).
get_path_s_cdata_test() ->
?assertEqual(
<<"d1">>,
fxml:get_path_s(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"a">>,
children = [#xmlel{name = <<"a1">>},
{xmlcdata, <<"d1">>}]},
#xmlel{name = <<"b">>}]},
[{elem, <<"a">>}, cdata])).
replace_tag_attr_test() ->
?assertMatch(
#xmlel{name = <<"foo">>,
attrs = [{<<"2">>, <<"d">>},
{<<"1">>, <<"a">>},
{<<"2">>, <<"c">>}]},
fxml:replace_tag_attr(
<<"2">>, <<"d">>,
#xmlel{name = <<"foo">>,
attrs = [{<<"1">>, <<"a">>},
{<<"2">>, <<"b">>},
{<<"2">>, <<"c">>}]})).
replace_subtag_test() ->
?assertMatch(
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"2">>, children = []},
#xmlel{name = <<"1">>},
#xmlel{name = <<"2">>,
children = [{xmlcdata, <<"b">>}]}]},
fxml:replace_subtag(
#xmlel{name = <<"2">>},
#xmlel{name = <<"root">>,
children = [#xmlel{name = <<"1">>},
#xmlel{name = <<"2">>,
children = [{xmlcdata, <<"a">>}]},
#xmlel{name = <<"2">>,
children =[{xmlcdata, <<"b">>}]}]})).
to_xmlel_test() ->
?assertEqual(
#xmlel{name = <<"foo">>,
attrs = [{<<"a">>, <<"b">>}],
children = [{xmlcdata, <<"xyz">>}]},
fxml:to_xmlel({xmlelement, "foo", [{"a", "b"}], [{xmlcdata, "xyz"}]})).
rpc_fault_test() ->
Fault = {xmlel,<<"methodResponse">>,[],
[{xmlel,<<"fault">>,[],
[{xmlel,<<"value">>,[],
[{xmlel,<<"struct">>,[],
[{xmlel,<<"member">>,[],
[{xmlel,<<"name">>,[],[{xmlcdata,<<"faultCode">>}]},
{xmlel,<<"value">>,[],
[{xmlel,<<"int">>,[],[{xmlcdata,<<"4">>}]}]}]},
{xmlel,<<"member">>,[],
[{xmlel,<<"name">>,[],[{xmlcdata,<<"faultString">>}]},
{xmlel,<<"value">>,[],
[{xmlel,<<"string">>,[],
[{xmlcdata,<<"Too many parameters.">>}]}]}]}]}]}]}]},
Result = {response, {fault, 4, <<"Too many parameters.">>}},
?assertEqual({ok, Result}, fxmlrpc:decode(Fault)),
?assertEqual(Fault, fxmlrpc:encode(Result)).
rpc_call_test() ->
Call = {xmlel,<<"methodCall">>,[],
[{xmlel,<<"methodName">>,[],[{xmlcdata,<<"examples.getStateName">>}]},
{xmlel,<<"params">>,[],
[{xmlel,<<"param">>,[],
[{xmlel,<<"value">>,[],
[{xmlel,<<"int">>,[],[{xmlcdata,<<"40">>}]}]}]},
{xmlel,<<"param">>,[],
[{xmlel,<<"value">>,[],
[{xmlel,<<"int">>,[],[{xmlcdata,<<"30">>}]}]}]},
{xmlel,<<"param">>,[],
[{xmlel,<<"value">>,[],
[{xmlel,<<"boolean">>,[],[{xmlcdata,<<"0">>}]}]}]},
{xmlel,<<"param">>,[],
[{xmlel,<<"value">>,[],
[{xmlel,<<"base64">>,[],
[{xmlcdata,<<"eW91IGNhbid0IHJlYWQgdGhpcyE=">>}]}]}]},
{xmlel,<<"param">>,[],
[{xmlel,<<"value">>,[],
[{xmlel,<<"dateTime.iso8601">>,[],
[{xmlcdata,<<"19980717T14:08:55">>}]}]}]},
{xmlel,<<"param">>,[],
[{xmlel,<<"value">>,[],
[{xmlel,<<"string">>,[],
[{xmlcdata,<<"Hello world!">>}]}]}]},
{xmlel,<<"param">>,[],
[{xmlel,<<"value">>,[],[{xmlel,<<"nil">>,[],[]}]}]},
{xmlel,<<"param">>,[],
[{xmlel,<<"value">>,[],
[{xmlel,<<"array">>,[],
[{xmlel,<<"data">>,[],
[{xmlel,<<"value">>,[],
[{xmlel,<<"int">>,[],
[{xmlcdata,<<"1404">>}]}]},
{xmlel,<<"value">>,[],
[{xmlel,<<"string">>,[],
[{xmlcdata,<<"Something here">>}]}]},
{xmlel,<<"value">>,[],
[{xmlel,<<"int">>,[],
[{xmlcdata,<<"1">>}]}]}]}]}]}]},
{xmlel,<<"param">>,[],
[{xmlel,<<"value">>,[],
[{xmlel,<<"struct">>,[],
[{xmlel,<<"member">>,[],
[{xmlel,<<"name">>,[],[{xmlcdata,<<"foo">>}]},
{xmlel,<<"value">>,[],
[{xmlel,<<"int">>,[],
[{xmlcdata,<<"1">>}]}]}]},
{xmlel,<<"member">>,[],
[{xmlel,<<"name">>,[],[{xmlcdata,<<"bar">>}]},
{xmlel,<<"value">>,[],
[{xmlel,<<"int">>,[],
[{xmlcdata,<<"2">>}]}]}]}]}]}]}]}]},
Result = {call,'examples.getStateName',
[40,30,false,
{base64,<<"eW91IGNhbid0IHJlYWQgdGhpcyE=">>},
{date,<<"19980717T14:08:55">>},
<<"Hello world!">>,nil,
{array,[1404,<<"Something here">>,1]},
{struct,[{foo,1},{bar,2}]}]},
?assertEqual({ok, Result}, fxmlrpc:decode(Call)),
?assertEqual(Call, fxmlrpc:encode(Result)).
response_test() ->
Response = {xmlel,<<"methodResponse">>, [],
[{xmlel,<<"params">>,[],
[{xmlel,<<"param">>,[],
[{xmlel,<<"value">>,[],
[{xmlel,<<"string">>,[],
[{xmlcdata,<<"South Dakota">>}]}]}]}]}]},
Result = {response,[<<"South Dakota">>]},
?assertEqual({ok, Result}, fxmlrpc:decode(Response)),
?assertEqual(Response, fxmlrpc:encode(Result)).
rpc_empty_call_test() ->
Call = {xmlel,<<"methodCall">>,[],
[{xmlel,<<"methodName">>,[],
[{xmlcdata,<<"some_method">>}]}]},
Result = {call, some_method, []},
?assertEqual({ok, Result}, fxmlrpc:decode(Call)),
?assertEqual(Call, fxmlrpc:encode(Result)).
rpc_empty_response_test() ->
Response = {xmlel,<<"methodResponse">>, [], []},
Result = {response, []},
?assertEqual({ok, Result}, fxmlrpc:decode(Response)),
?assertEqual(Response, fxmlrpc:encode(Result)).
fast_xml-1.1.48/test/elixir/ 0000755 0002322 0002322 00000000000 14151146420 016241 5 ustar debalance debalance fast_xml-1.1.48/test/elixir/fxml_test.exs 0000644 0002322 0002322 00000004764 14151146420 021002 0 ustar debalance debalance #
# Test XML module with Quviq Quickcheck
#
# Copyright (C) 2002-2021 ProcessOne, SARL. 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.
import :erlang, only: [list_to_binary: 1]
defmodule XmlTest do
use ExUnit.Case
use EQC.ExUnit
require Record
Record.defrecord :xmlel, Record.extract(:xmlel, from: "include/fxml.hrl")
property "Can serialize arbitrary XML packets" do
forall xml_chunk <- xml_el do
is_binary(:fxml.element_to_binary(xml_chunk))
end
end
property "Serialize and parse same XML packet" do
forall xml_chunk <- xml_el do
:fxml_stream.parse_element(:fxml.element_to_binary(xml_chunk)) == xml_chunk
end
end
# Generators
# ==========
#
# Random small XML packets generator
# ----------------------------------
# TODO: We need to weight lowercase char much more that the rest
# An XML name cannot start with number of punctuation char
def xml_name do
[letter|list(letter_figure)]
end
def letter do
oneof([choose(?A, ?Z), choose(?a, ?z)])
end
def letter_figure do
oneof([choose(?A, ?Z),choose(?a, ?z), choose(?0, ?9)])
end
def xml_attr do
let {key, val} <- {xml_name, xml_name} do
{list_to_binary(key), list_to_binary(val)}
end
end
def xml_children(0) do
[]
end
def xml_children(size) do
let name <- xml_name do
oneof([xml_children(0),
oneof([[{:xmlcdata, list_to_binary(name)}],
list(xml_child(div size, 3))])])
end
end
def xml_child(size) do
let {name, attrs} <- {xml_name, list(xml_attr)} do
xmlel(name: list_to_binary(name),
attrs: :lists.ukeysort(1, attrs),
children: xml_children(size))
end
end
def xml_el do
sized size do
let {tagname, attrs} <- {xml_name, list(xml_attr)} do
xmlel(name: list_to_binary(tagname),
attrs: :lists.ukeysort(1, attrs),
children: xml_children(size))
end
end
end
end
fast_xml-1.1.48/test/elixir/fast_xml_test.exs 0000644 0002322 0002322 00000004535 14151146420 021645 0 ustar debalance debalance # Copyright (C) 2002-2021 ProcessOne, SARL. 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.
defmodule FastXMLTest do
use ExUnit.Case
# TODO: we should be able to pass :use_maps option to :fxml_stream.parse_element/2
test "Stream parser can return Elixir structs" do
s1 = :fxml_stream.new(self, :infinity, [:no_gen_server, :use_maps])
s2 = :fxml_stream.parse(s1, "")
assert receive_stanza == %FastXML.StreamStart{name: "root"}
s3 = :fxml_stream.parse(s2, "content cdata")
assert receive_stanza == %FastXML.El{name: "xmlelement", children: ["content cdata"]}
s4 = :fxml_stream.parse(s3, "content cdata")
assert receive_stanza == %FastXML.El{name: "xmlelement", children: ["content cdata"]}
s5 = :fxml_stream.parse(s4, "")
assert receive_stanza == %FastXML.StreamEnd{name: "root"}
:fxml_stream.close(s5)
end
test "Size of parsed stanza can be limited" do
:todo
end
# TODO This test is failing at the moment
# test "Stream parser can support arbitrary root element attributes" do
# s1 = :fxml_stream.new(self, :infinity, [:no_gen_server, :use_maps])
# s2 = :fxml_stream.parse(s1, "")
# assert receive_result == %FastXML.StreamStart{name: "root", attrs: %{"xmlns": "myns"}}
# :fxml_stream.close(s2)
# end
# TODO to test, unbound prefix error:
# code: receive_result == %FastXML.StreamStart{name: "stream:stream", attrs: %{xmlns: "jabber:client"}}
# lhs: %{__struct__: FastXML.StreamError, desc: {27, "unbound prefix"}}
# rhs: %FastXML.StreamStart{attrs: %{xmlns: "jabber:client"}, name: "stream:stream"}
# TODO test mismatched tags
defp receive_stanza do
receive do
result ->
result
after 2000 ->
nil
end
end
end
fast_xml-1.1.48/Makefile.mix 0000644 0002322 0002322 00000002316 14151146420 016224 0 ustar debalance debalance # This file is used to compile C NIF module in Elixir buildchain
MIX = mix
CFLAGS = -g -O2 -Wall
#CFLAGS = -g -O3 -ansi -pedantic -Wall -Wextra -Wno-unused-parameter
ERLANG_PATH = $(shell erl -eval 'io:format("~s", [lists:concat([code:root_dir(), "/erts-", erlang:system_info(version), "/include"])])' -s init stop -noshell)
ERL_INTERFACE_PATH = $(shell erl -eval 'io:format("~s", [code:lib_dir(erl_interface, lib)])' -s init stop -noshell)
CFLAGS += -I$(ERLANG_PATH)
LDFLAGS += -lexpat
ifneq ($(OS),Windows_NT)
CFLAGS += -fPIC
ifeq ($(shell uname),Darwin)
LDFLAGS += -dynamiclib -undefined dynamic_lookup
endif
ifeq ($(shell uname),FreeBSD)
CFLAGS += -I/usr/local/include
LDFLAGS += -L/usr/local/lib
endif
ifeq ($(shell uname),Linux)
LDFLAGS += -shared -L$(ERL_INTERFACE_PATH) -lerl_interface -lei
endif
endif
.PHONY: all fast_xml clean
all: fast_xml
fast_xml:
$(MIX) compile
c_src/%.o: c_src/%.c
$(CC) -c $(CFLAGS) -o $@ $<
priv/lib/%.so:
@mkdir -p priv/lib
$(CC) $< $(LDFLAGS) -o $@
priv/lib/fxml_stream.so: c_src/fxml_stream.o
priv/lib/fxml.so: c_src/fxml.o
clean:
$(RM) priv/lib/fxml_stream.so
$(RM) priv/lib/fxml.so
# Local Variables:
# mode: makefile
# End:
# vim: set filetype=makefile
fast_xml-1.1.48/CONTRIBUTING.md 0000644 0002322 0002322 00000013615 14151146420 016225 0 ustar debalance debalance # Contributing
We'd love for you to contribute to our source code and to make our project even better than it is
today! Here are the guidelines we'd like you to follow:
* [Code of Conduct](#coc)
* [Questions and Problems](#question)
* [Issues and Bugs](#issue)
* [Feature Requests](#feature)
* [Issue Submission Guidelines](#submit)
* [Pull Request Submission Guidelines](#submit-pr)
* [Signing the CLA](#cla)
## Code of Conduct
Help us keep our community open-minded and inclusive. Please read and follow our [Code of Conduct][coc].
## Questions, Bugs, Features
### Got a Question or Problem?
Do not open issues for general support questions as we want to keep GitHub issues for bug reports
and feature requests. You've got much better chances of getting your question answered on dedicated
support platforms, the best being [Stack Overflow][stackoverflow].
Stack Overflow is a much better place to ask questions since:
- there are thousands of people willing to help on Stack Overflow
- questions and answers stay available for public viewing so your question / answer might help
someone else
- Stack Overflow's voting system assures that the best answers are prominently visible.
To save your and our time, we will systematically close all issues that are requests for general
support and redirect people to the section you are reading right now.
### Found an Issue or Bug?
If you find a bug in the source code, you can help us by submitting an issue to our
[GitHub Repository][github]. Even better, you can submit a Pull Request with a fix.
### Missing a Feature?
You can request a new feature by submitting an issue to our [GitHub Repository][github-issues].
If you would like to implement a new feature then consider what kind of change it is:
* **Major Changes** that you wish to contribute to the project should be discussed first in an
[GitHub issue][github-issues] that clearly outlines the changes and benefits of the feature.
* **Small Changes** can directly be crafted and submitted to the [GitHub Repository][github]
as a Pull Request. See the section about [Pull Request Submission Guidelines](#submit-pr).
## Issue Submission Guidelines
Before you submit your issue search the archive, maybe your question was already answered.
If your issue appears to be a bug, and hasn't been reported, open a new issue. Help us to maximize
the effort we can spend fixing issues and adding new features, by not reporting duplicate issues.
The "[new issue][github-new-issue]" form contains a number of prompts that you should fill out to
make it easier to understand and categorize the issue.
## Pull Request Submission Guidelines
By submitting a pull request for a code or doc contribution, you need to have the right
to grant your contribution's copyright license to ProcessOne. Please check [ProcessOne CLA][cla]
for details.
Before you submit your pull request consider the following guidelines:
* Search [GitHub][github-pr] for an open or closed Pull Request
that relates to your submission. You don't want to duplicate effort.
* Make your changes in a new git branch:
```shell
git checkout -b my-fix-branch master
```
* Test your changes and, if relevant, expand the automated test suite.
* Create your patch commit, including appropriate test cases.
* If the changes affect public APIs, change or add relevant documentation.
* Commit your changes using a descriptive commit message.
```shell
git commit -a
```
Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files.
* Push your branch to GitHub:
```shell
git push origin my-fix-branch
```
* In GitHub, send a pull request to `master` branch. This will trigger the continuous integration and run the test.
We will also notify you if you have not yet signed the [contribution agreement][cla].
* If you find that the continunous integration has failed, look into the logs to find out
if your changes caused test failures, the commit message was malformed etc. If you find that the
tests failed or times out for unrelated reasons, you can ping a team member so that the build can be
restarted.
* If we suggest changes, then:
* Make the required updates.
* Test your changes and test cases.
* Commit your changes to your branch (e.g. `my-fix-branch`).
* Push the changes to your GitHub repository (this will update your Pull Request).
You can also amend the initial commits and force push them to the branch.
```shell
git rebase master -i
git push origin my-fix-branch -f
```
This is generally easier to follow, but separate commits are useful if the Pull Request contains
iterations that might be interesting to see side-by-side.
That's it! Thank you for your contribution!
## Signing the Contributor License Agreement (CLA)
Upon submitting a Pull Request, we will ask you to sign our CLA if you haven't done
so before. It's a quick process, we promise, and you will be able to do it all online
You can read [ProcessOne Contribution License Agreement][cla] in PDF.
This is part of the legal framework of the open-source ecosystem that adds some red tape,
but protects both the contributor and the company / foundation behind the project. It also
gives us the option to relicense the code with a more permissive license in the future.
[coc]: https://github.com/processone/fast_xml/blob/master/CODE_OF_CONDUCT.md
[stackoverflow]: https://stackoverflow.com/
[github]: https://github.com/processone/fast_xml
[github-issues]: https://github.com/processone/fast_xml/issues
[github-new-issue]: https://github.com/processone/fast_xml/issues/new
[github-pr]: https://github.com/processone/fast_xml/pulls
[cla]: https://www.process-one.net/resources/ejabberd-cla.pdf
[license]: https://github.com/processone/fast_xml/blob/master/LICENSE.txt
fast_xml-1.1.48/configure 0000755 0002322 0002322 00000431762 14151146420 015712 0 ustar debalance debalance #! /bin/sh
# Guess values for system-dependent variables and create Makefiles.
# Generated by GNU Autoconf 2.69 for fast_xml 1.1.21.
#
#
# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
#
#
# This configure script is free software; the Free Software Foundation
# gives unlimited permission to copy, distribute and modify it.
## -------------------- ##
## M4sh Initialization. ##
## -------------------- ##
# Be more Bourne compatible
DUALCASE=1; export DUALCASE # for MKS sh
if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
emulate sh
NULLCMD=:
# Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
# is contrary to our usage. Disable this feature.
alias -g '${1+"$@"}'='"$@"'
setopt NO_GLOB_SUBST
else
case `(set -o) 2>/dev/null` in #(
*posix*) :
set -o posix ;; #(
*) :
;;
esac
fi
as_nl='
'
export as_nl
# Printing a long string crashes Solaris 7 /usr/bin/printf.
as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
# Prefer a ksh shell builtin over an external printf program on Solaris,
# but without wasting forks for bash or zsh.
if test -z "$BASH_VERSION$ZSH_VERSION" \
&& (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
as_echo='print -r --'
as_echo_n='print -rn --'
elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
as_echo='printf %s\n'
as_echo_n='printf %s'
else
if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
as_echo_n='/usr/ucb/echo -n'
else
as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
as_echo_n_body='eval
arg=$1;
case $arg in #(
*"$as_nl"*)
expr "X$arg" : "X\\(.*\\)$as_nl";
arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
esac;
expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
'
export as_echo_n_body
as_echo_n='sh -c $as_echo_n_body as_echo'
fi
export as_echo_body
as_echo='sh -c $as_echo_body as_echo'
fi
# The user is always right.
if test "${PATH_SEPARATOR+set}" != set; then
PATH_SEPARATOR=:
(PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
(PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
PATH_SEPARATOR=';'
}
fi
# IFS
# We need space, tab and new line, in precisely that order. Quoting is
# there to prevent editors from complaining about space-tab.
# (If _AS_PATH_WALK were called with IFS unset, it would disable word
# splitting by setting IFS to empty value.)
IFS=" "" $as_nl"
# Find who we are. Look in the path if we contain no directory separator.
as_myself=
case $0 in #((
*[\\/]* ) as_myself=$0 ;;
*) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
for as_dir in $PATH
do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
done
IFS=$as_save_IFS
;;
esac
# We did not find ourselves, most probably we were run as `sh COMMAND'
# in which case we are not to be found in the path.
if test "x$as_myself" = x; then
as_myself=$0
fi
if test ! -f "$as_myself"; then
$as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
exit 1
fi
# Unset variables that we do not need and which cause bugs (e.g. in
# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1"
# suppresses any "Segmentation fault" message there. '((' could
# trigger a bug in pdksh 5.2.14.
for as_var in BASH_ENV ENV MAIL MAILPATH
do eval test x\${$as_var+set} = xset \
&& ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
done
PS1='$ '
PS2='> '
PS4='+ '
# NLS nuisances.
LC_ALL=C
export LC_ALL
LANGUAGE=C
export LANGUAGE
# CDPATH.
(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
# Use a proper internal environment variable to ensure we don't fall
# into an infinite loop, continuously re-executing ourselves.
if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then
_as_can_reexec=no; export _as_can_reexec;
# We cannot yet assume a decent shell, so we have to provide a
# neutralization value for shells without unset; and this also
# works around shells that cannot unset nonexistent variables.
# Preserve -v and -x to the replacement shell.
BASH_ENV=/dev/null
ENV=/dev/null
(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
case $- in # ((((
*v*x* | *x*v* ) as_opts=-vx ;;
*v* ) as_opts=-v ;;
*x* ) as_opts=-x ;;
* ) as_opts= ;;
esac
exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
# Admittedly, this is quite paranoid, since all the known shells bail
# out after a failed `exec'.
$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
as_fn_exit 255
fi
# We don't want this to propagate to other subprocesses.
{ _as_can_reexec=; unset _as_can_reexec;}
if test "x$CONFIG_SHELL" = x; then
as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :
emulate sh
NULLCMD=:
# Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which
# is contrary to our usage. Disable this feature.
alias -g '\${1+\"\$@\"}'='\"\$@\"'
setopt NO_GLOB_SUBST
else
case \`(set -o) 2>/dev/null\` in #(
*posix*) :
set -o posix ;; #(
*) :
;;
esac
fi
"
as_required="as_fn_return () { (exit \$1); }
as_fn_success () { as_fn_return 0; }
as_fn_failure () { as_fn_return 1; }
as_fn_ret_success () { return 0; }
as_fn_ret_failure () { return 1; }
exitcode=0
as_fn_success || { exitcode=1; echo as_fn_success failed.; }
as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; }
as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; }
as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; }
if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then :
else
exitcode=1; echo positional parameters were not saved.
fi
test x\$exitcode = x0 || exit 1
test -x / || exit 1"
as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO
as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO
eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" &&
test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1
test \$(( 1 + 1 )) = 2 || exit 1"
if (eval "$as_required") 2>/dev/null; then :
as_have_required=yes
else
as_have_required=no
fi
if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then :
else
as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
as_found=false
for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
as_found=:
case $as_dir in #(
/*)
for as_base in sh bash ksh sh5; do
# Try only shells that exist, to save several forks.
as_shell=$as_dir/$as_base
if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
{ $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then :
CONFIG_SHELL=$as_shell as_have_required=yes
if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then :
break 2
fi
fi
done;;
esac
as_found=false
done
$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } &&
{ $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then :
CONFIG_SHELL=$SHELL as_have_required=yes
fi; }
IFS=$as_save_IFS
if test "x$CONFIG_SHELL" != x; then :
export CONFIG_SHELL
# We cannot yet assume a decent shell, so we have to provide a
# neutralization value for shells without unset; and this also
# works around shells that cannot unset nonexistent variables.
# Preserve -v and -x to the replacement shell.
BASH_ENV=/dev/null
ENV=/dev/null
(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
case $- in # ((((
*v*x* | *x*v* ) as_opts=-vx ;;
*v* ) as_opts=-v ;;
*x* ) as_opts=-x ;;
* ) as_opts= ;;
esac
exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
# Admittedly, this is quite paranoid, since all the known shells bail
# out after a failed `exec'.
$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
exit 255
fi
if test x$as_have_required = xno; then :
$as_echo "$0: This script requires a shell more modern than all"
$as_echo "$0: the shells that I found on your system."
if test x${ZSH_VERSION+set} = xset ; then
$as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should"
$as_echo "$0: be upgraded to zsh 4.3.4 or later."
else
$as_echo "$0: Please tell bug-autoconf@gnu.org about your system,
$0: including any error possibly output before this
$0: message. Then install a modern shell, or manually run
$0: the script under such a shell if you do have one."
fi
exit 1
fi
fi
fi
SHELL=${CONFIG_SHELL-/bin/sh}
export SHELL
# Unset more variables known to interfere with behavior of common tools.
CLICOLOR_FORCE= GREP_OPTIONS=
unset CLICOLOR_FORCE GREP_OPTIONS
## --------------------- ##
## M4sh Shell Functions. ##
## --------------------- ##
# as_fn_unset VAR
# ---------------
# Portably unset VAR.
as_fn_unset ()
{
{ eval $1=; unset $1;}
}
as_unset=as_fn_unset
# as_fn_set_status STATUS
# -----------------------
# Set $? to STATUS, without forking.
as_fn_set_status ()
{
return $1
} # as_fn_set_status
# as_fn_exit STATUS
# -----------------
# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
as_fn_exit ()
{
set +e
as_fn_set_status $1
exit $1
} # as_fn_exit
# as_fn_mkdir_p
# -------------
# Create "$as_dir" as a directory, including parents if necessary.
as_fn_mkdir_p ()
{
case $as_dir in #(
-*) as_dir=./$as_dir;;
esac
test -d "$as_dir" || eval $as_mkdir_p || {
as_dirs=
while :; do
case $as_dir in #(
*\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
*) as_qdir=$as_dir;;
esac
as_dirs="'$as_qdir' $as_dirs"
as_dir=`$as_dirname -- "$as_dir" ||
$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
X"$as_dir" : 'X\(//\)[^/]' \| \
X"$as_dir" : 'X\(//\)$' \| \
X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
$as_echo X"$as_dir" |
sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
s//\1/
q
}
/^X\(\/\/\)[^/].*/{
s//\1/
q
}
/^X\(\/\/\)$/{
s//\1/
q
}
/^X\(\/\).*/{
s//\1/
q
}
s/.*/./; q'`
test -d "$as_dir" && break
done
test -z "$as_dirs" || eval "mkdir $as_dirs"
} || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
} # as_fn_mkdir_p
# as_fn_executable_p FILE
# -----------------------
# Test if FILE is an executable regular file.
as_fn_executable_p ()
{
test -f "$1" && test -x "$1"
} # as_fn_executable_p
# as_fn_append VAR VALUE
# ----------------------
# Append the text in VALUE to the end of the definition contained in VAR. Take
# advantage of any shell optimizations that allow amortized linear growth over
# repeated appends, instead of the typical quadratic growth present in naive
# implementations.
if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
eval 'as_fn_append ()
{
eval $1+=\$2
}'
else
as_fn_append ()
{
eval $1=\$$1\$2
}
fi # as_fn_append
# as_fn_arith ARG...
# ------------------
# Perform arithmetic evaluation on the ARGs, and store the result in the
# global $as_val. Take advantage of shells that can avoid forks. The arguments
# must be portable across $(()) and expr.
if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
eval 'as_fn_arith ()
{
as_val=$(( $* ))
}'
else
as_fn_arith ()
{
as_val=`expr "$@" || test $? -eq 1`
}
fi # as_fn_arith
# as_fn_error STATUS ERROR [LINENO LOG_FD]
# ----------------------------------------
# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
# script with STATUS, using 1 if that was 0.
as_fn_error ()
{
as_status=$1; test $as_status -eq 0 && as_status=1
if test "$4"; then
as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
$as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
fi
$as_echo "$as_me: error: $2" >&2
as_fn_exit $as_status
} # as_fn_error
if expr a : '\(a\)' >/dev/null 2>&1 &&
test "X`expr 00001 : '.*\(...\)'`" = X001; then
as_expr=expr
else
as_expr=false
fi
if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
as_basename=basename
else
as_basename=false
fi
if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
as_dirname=dirname
else
as_dirname=false
fi
as_me=`$as_basename -- "$0" ||
$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
X"$0" : 'X\(//\)$' \| \
X"$0" : 'X\(/\)' \| . 2>/dev/null ||
$as_echo X/"$0" |
sed '/^.*\/\([^/][^/]*\)\/*$/{
s//\1/
q
}
/^X\/\(\/\/\)$/{
s//\1/
q
}
/^X\/\(\/\).*/{
s//\1/
q
}
s/.*/./; q'`
# Avoid depending upon Character Ranges.
as_cr_letters='abcdefghijklmnopqrstuvwxyz'
as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
as_cr_Letters=$as_cr_letters$as_cr_LETTERS
as_cr_digits='0123456789'
as_cr_alnum=$as_cr_Letters$as_cr_digits
as_lineno_1=$LINENO as_lineno_1a=$LINENO
as_lineno_2=$LINENO as_lineno_2a=$LINENO
eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" &&
test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || {
# Blame Lee E. McMahon (1931-1989) for sed's syntax. :-)
sed -n '
p
/[$]LINENO/=
' <$as_myself |
sed '
s/[$]LINENO.*/&-/
t lineno
b
:lineno
N
:loop
s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
t loop
s/-\n.*//
' >$as_me.lineno &&
chmod +x "$as_me.lineno" ||
{ $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; }
# If we had to re-execute with $CONFIG_SHELL, we're ensured to have
# already done that, so ensure we don't try to do so again and fall
# in an infinite loop. This has already happened in practice.
_as_can_reexec=no; export _as_can_reexec
# Don't try to exec as it changes $[0], causing all sort of problems
# (the dirname of $[0] is not the place where we might find the
# original and so on. Autoconf is especially sensitive to this).
. "./$as_me.lineno"
# Exit status is that of the last command.
exit
}
ECHO_C= ECHO_N= ECHO_T=
case `echo -n x` in #(((((
-n*)
case `echo 'xy\c'` in
*c*) ECHO_T=' ';; # ECHO_T is single tab character.
xy) ECHO_C='\c';;
*) echo `echo ksh88 bug on AIX 6.1` > /dev/null
ECHO_T=' ';;
esac;;
*)
ECHO_N='-n';;
esac
rm -f conf$$ conf$$.exe conf$$.file
if test -d conf$$.dir; then
rm -f conf$$.dir/conf$$.file
else
rm -f conf$$.dir
mkdir conf$$.dir 2>/dev/null
fi
if (echo >conf$$.file) 2>/dev/null; then
if ln -s conf$$.file conf$$ 2>/dev/null; then
as_ln_s='ln -s'
# ... but there are two gotchas:
# 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
# 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
# In both cases, we have to default to `cp -pR'.
ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
as_ln_s='cp -pR'
elif ln conf$$.file conf$$ 2>/dev/null; then
as_ln_s=ln
else
as_ln_s='cp -pR'
fi
else
as_ln_s='cp -pR'
fi
rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
rmdir conf$$.dir 2>/dev/null
if mkdir -p . 2>/dev/null; then
as_mkdir_p='mkdir -p "$as_dir"'
else
test -d ./-p && rmdir ./-p
as_mkdir_p=false
fi
as_test_x='test -x'
as_executable_p=as_fn_executable_p
# Sed expression to map a string onto a valid CPP name.
as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
# Sed expression to map a string onto a valid variable name.
as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
test -n "$DJDIR" || exec 7<&0 &1
# Name of the host.
# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status,
# so uname gets run too.
ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
#
# Initializations.
#
ac_default_prefix=/usr/local
ac_clean_files=
ac_config_libobj_dir=.
LIBOBJS=
cross_compiling=no
subdirs=
MFLAGS=
MAKEFLAGS=
# Identity of this package.
PACKAGE_NAME='fast_xml'
PACKAGE_TARNAME='fast_xml'
PACKAGE_VERSION='1.1.21'
PACKAGE_STRING='fast_xml 1.1.21'
PACKAGE_BUGREPORT=''
PACKAGE_URL=''
# Factoring default headers for most tests.
ac_includes_default="\
#include
#ifdef HAVE_SYS_TYPES_H
# include
#endif
#ifdef HAVE_SYS_STAT_H
# include
#endif
#ifdef STDC_HEADERS
# include
# include
#else
# ifdef HAVE_STDLIB_H
# include
# endif
#endif
#ifdef HAVE_STRING_H
# if !defined STDC_HEADERS && defined HAVE_MEMORY_H
# include
# endif
# include
#endif
#ifdef HAVE_STRINGS_H
# include
#endif
#ifdef HAVE_INTTYPES_H
# include
#endif
#ifdef HAVE_STDINT_H
# include
#endif
#ifdef HAVE_UNISTD_H
# include
#endif"
ac_subst_vars='LTLIBOBJS
gcov
ERLCFLAGS
ERLC
ERL
LIBOBJS
EGREP
GREP
CPP
SET_MAKE
OBJEXT
EXEEXT
ac_ct_CC
CPPFLAGS
LDFLAGS
CFLAGS
CC
target_alias
host_alias
build_alias
LIBS
ECHO_T
ECHO_N
ECHO_C
DEFS
mandir
localedir
libdir
psdir
pdfdir
dvidir
htmldir
infodir
docdir
oldincludedir
includedir
runstatedir
localstatedir
sharedstatedir
sysconfdir
datadir
datarootdir
libexecdir
sbindir
bindir
program_transform_name
prefix
exec_prefix
PACKAGE_URL
PACKAGE_BUGREPORT
PACKAGE_STRING
PACKAGE_VERSION
PACKAGE_TARNAME
PACKAGE_NAME
PATH_SEPARATOR
SHELL'
ac_subst_files=''
ac_user_opts='
enable_option_checking
enable_gcov
'
ac_precious_vars='build_alias
host_alias
target_alias
CC
CFLAGS
LDFLAGS
LIBS
CPPFLAGS
CPP
ERL
ERLC
ERLCFLAGS'
# Initialize some variables set by options.
ac_init_help=
ac_init_version=false
ac_unrecognized_opts=
ac_unrecognized_sep=
# The variables have the same names as the options, with
# dashes changed to underlines.
cache_file=/dev/null
exec_prefix=NONE
no_create=
no_recursion=
prefix=NONE
program_prefix=NONE
program_suffix=NONE
program_transform_name=s,x,x,
silent=
site=
srcdir=
verbose=
x_includes=NONE
x_libraries=NONE
# Installation directory options.
# These are left unexpanded so users can "make install exec_prefix=/foo"
# and all the variables that are supposed to be based on exec_prefix
# by default will actually change.
# Use braces instead of parens because sh, perl, etc. also accept them.
# (The list follows the same order as the GNU Coding Standards.)
bindir='${exec_prefix}/bin'
sbindir='${exec_prefix}/sbin'
libexecdir='${exec_prefix}/libexec'
datarootdir='${prefix}/share'
datadir='${datarootdir}'
sysconfdir='${prefix}/etc'
sharedstatedir='${prefix}/com'
localstatedir='${prefix}/var'
runstatedir='${localstatedir}/run'
includedir='${prefix}/include'
oldincludedir='/usr/include'
docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
infodir='${datarootdir}/info'
htmldir='${docdir}'
dvidir='${docdir}'
pdfdir='${docdir}'
psdir='${docdir}'
libdir='${exec_prefix}/lib'
localedir='${datarootdir}/locale'
mandir='${datarootdir}/man'
ac_prev=
ac_dashdash=
for ac_option
do
# If the previous option needs an argument, assign it.
if test -n "$ac_prev"; then
eval $ac_prev=\$ac_option
ac_prev=
continue
fi
case $ac_option in
*=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
*=) ac_optarg= ;;
*) ac_optarg=yes ;;
esac
# Accept the important Cygnus configure options, so we can diagnose typos.
case $ac_dashdash$ac_option in
--)
ac_dashdash=yes ;;
-bindir | --bindir | --bindi | --bind | --bin | --bi)
ac_prev=bindir ;;
-bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
bindir=$ac_optarg ;;
-build | --build | --buil | --bui | --bu)
ac_prev=build_alias ;;
-build=* | --build=* | --buil=* | --bui=* | --bu=*)
build_alias=$ac_optarg ;;
-cache-file | --cache-file | --cache-fil | --cache-fi \
| --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
ac_prev=cache_file ;;
-cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
| --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
cache_file=$ac_optarg ;;
--config-cache | -C)
cache_file=config.cache ;;
-datadir | --datadir | --datadi | --datad)
ac_prev=datadir ;;
-datadir=* | --datadir=* | --datadi=* | --datad=*)
datadir=$ac_optarg ;;
-datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
| --dataroo | --dataro | --datar)
ac_prev=datarootdir ;;
-datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
| --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
datarootdir=$ac_optarg ;;
-disable-* | --disable-*)
ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
# Reject names that are not valid shell variable names.
expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
as_fn_error $? "invalid feature name: $ac_useropt"
ac_useropt_orig=$ac_useropt
ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
case $ac_user_opts in
*"
"enable_$ac_useropt"
"*) ;;
*) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig"
ac_unrecognized_sep=', ';;
esac
eval enable_$ac_useropt=no ;;
-docdir | --docdir | --docdi | --doc | --do)
ac_prev=docdir ;;
-docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
docdir=$ac_optarg ;;
-dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
ac_prev=dvidir ;;
-dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
dvidir=$ac_optarg ;;
-enable-* | --enable-*)
ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
# Reject names that are not valid shell variable names.
expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
as_fn_error $? "invalid feature name: $ac_useropt"
ac_useropt_orig=$ac_useropt
ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
case $ac_user_opts in
*"
"enable_$ac_useropt"
"*) ;;
*) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig"
ac_unrecognized_sep=', ';;
esac
eval enable_$ac_useropt=\$ac_optarg ;;
-exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
| --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
| --exec | --exe | --ex)
ac_prev=exec_prefix ;;
-exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
| --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
| --exec=* | --exe=* | --ex=*)
exec_prefix=$ac_optarg ;;
-gas | --gas | --ga | --g)
# Obsolete; use --with-gas.
with_gas=yes ;;
-help | --help | --hel | --he | -h)
ac_init_help=long ;;
-help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
ac_init_help=recursive ;;
-help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
ac_init_help=short ;;
-host | --host | --hos | --ho)
ac_prev=host_alias ;;
-host=* | --host=* | --hos=* | --ho=*)
host_alias=$ac_optarg ;;
-htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
ac_prev=htmldir ;;
-htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
| --ht=*)
htmldir=$ac_optarg ;;
-includedir | --includedir | --includedi | --included | --include \
| --includ | --inclu | --incl | --inc)
ac_prev=includedir ;;
-includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
| --includ=* | --inclu=* | --incl=* | --inc=*)
includedir=$ac_optarg ;;
-infodir | --infodir | --infodi | --infod | --info | --inf)
ac_prev=infodir ;;
-infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
infodir=$ac_optarg ;;
-libdir | --libdir | --libdi | --libd)
ac_prev=libdir ;;
-libdir=* | --libdir=* | --libdi=* | --libd=*)
libdir=$ac_optarg ;;
-libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
| --libexe | --libex | --libe)
ac_prev=libexecdir ;;
-libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
| --libexe=* | --libex=* | --libe=*)
libexecdir=$ac_optarg ;;
-localedir | --localedir | --localedi | --localed | --locale)
ac_prev=localedir ;;
-localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
localedir=$ac_optarg ;;
-localstatedir | --localstatedir | --localstatedi | --localstated \
| --localstate | --localstat | --localsta | --localst | --locals)
ac_prev=localstatedir ;;
-localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
| --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
localstatedir=$ac_optarg ;;
-mandir | --mandir | --mandi | --mand | --man | --ma | --m)
ac_prev=mandir ;;
-mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
mandir=$ac_optarg ;;
-nfp | --nfp | --nf)
# Obsolete; use --without-fp.
with_fp=no ;;
-no-create | --no-create | --no-creat | --no-crea | --no-cre \
| --no-cr | --no-c | -n)
no_create=yes ;;
-no-recursion | --no-recursion | --no-recursio | --no-recursi \
| --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
no_recursion=yes ;;
-oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
| --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
| --oldin | --oldi | --old | --ol | --o)
ac_prev=oldincludedir ;;
-oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
| --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
| --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
oldincludedir=$ac_optarg ;;
-prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
ac_prev=prefix ;;
-prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
prefix=$ac_optarg ;;
-program-prefix | --program-prefix | --program-prefi | --program-pref \
| --program-pre | --program-pr | --program-p)
ac_prev=program_prefix ;;
-program-prefix=* | --program-prefix=* | --program-prefi=* \
| --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
program_prefix=$ac_optarg ;;
-program-suffix | --program-suffix | --program-suffi | --program-suff \
| --program-suf | --program-su | --program-s)
ac_prev=program_suffix ;;
-program-suffix=* | --program-suffix=* | --program-suffi=* \
| --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
program_suffix=$ac_optarg ;;
-program-transform-name | --program-transform-name \
| --program-transform-nam | --program-transform-na \
| --program-transform-n | --program-transform- \
| --program-transform | --program-transfor \
| --program-transfo | --program-transf \
| --program-trans | --program-tran \
| --progr-tra | --program-tr | --program-t)
ac_prev=program_transform_name ;;
-program-transform-name=* | --program-transform-name=* \
| --program-transform-nam=* | --program-transform-na=* \
| --program-transform-n=* | --program-transform-=* \
| --program-transform=* | --program-transfor=* \
| --program-transfo=* | --program-transf=* \
| --program-trans=* | --program-tran=* \
| --progr-tra=* | --program-tr=* | --program-t=*)
program_transform_name=$ac_optarg ;;
-pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
ac_prev=pdfdir ;;
-pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
pdfdir=$ac_optarg ;;
-psdir | --psdir | --psdi | --psd | --ps)
ac_prev=psdir ;;
-psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
psdir=$ac_optarg ;;
-q | -quiet | --quiet | --quie | --qui | --qu | --q \
| -silent | --silent | --silen | --sile | --sil)
silent=yes ;;
-runstatedir | --runstatedir | --runstatedi | --runstated \
| --runstate | --runstat | --runsta | --runst | --runs \
| --run | --ru | --r)
ac_prev=runstatedir ;;
-runstatedir=* | --runstatedir=* | --runstatedi=* | --runstated=* \
| --runstate=* | --runstat=* | --runsta=* | --runst=* | --runs=* \
| --run=* | --ru=* | --r=*)
runstatedir=$ac_optarg ;;
-sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
ac_prev=sbindir ;;
-sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
| --sbi=* | --sb=*)
sbindir=$ac_optarg ;;
-sharedstatedir | --sharedstatedir | --sharedstatedi \
| --sharedstated | --sharedstate | --sharedstat | --sharedsta \
| --sharedst | --shareds | --shared | --share | --shar \
| --sha | --sh)
ac_prev=sharedstatedir ;;
-sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
| --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
| --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
| --sha=* | --sh=*)
sharedstatedir=$ac_optarg ;;
-site | --site | --sit)
ac_prev=site ;;
-site=* | --site=* | --sit=*)
site=$ac_optarg ;;
-srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
ac_prev=srcdir ;;
-srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
srcdir=$ac_optarg ;;
-sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
| --syscon | --sysco | --sysc | --sys | --sy)
ac_prev=sysconfdir ;;
-sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
| --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
sysconfdir=$ac_optarg ;;
-target | --target | --targe | --targ | --tar | --ta | --t)
ac_prev=target_alias ;;
-target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
target_alias=$ac_optarg ;;
-v | -verbose | --verbose | --verbos | --verbo | --verb)
verbose=yes ;;
-version | --version | --versio | --versi | --vers | -V)
ac_init_version=: ;;
-with-* | --with-*)
ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
# Reject names that are not valid shell variable names.
expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
as_fn_error $? "invalid package name: $ac_useropt"
ac_useropt_orig=$ac_useropt
ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
case $ac_user_opts in
*"
"with_$ac_useropt"
"*) ;;
*) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig"
ac_unrecognized_sep=', ';;
esac
eval with_$ac_useropt=\$ac_optarg ;;
-without-* | --without-*)
ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'`
# Reject names that are not valid shell variable names.
expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
as_fn_error $? "invalid package name: $ac_useropt"
ac_useropt_orig=$ac_useropt
ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
case $ac_user_opts in
*"
"with_$ac_useropt"
"*) ;;
*) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig"
ac_unrecognized_sep=', ';;
esac
eval with_$ac_useropt=no ;;
--x)
# Obsolete; use --with-x.
with_x=yes ;;
-x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
| --x-incl | --x-inc | --x-in | --x-i)
ac_prev=x_includes ;;
-x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
| --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
x_includes=$ac_optarg ;;
-x-libraries | --x-libraries | --x-librarie | --x-librari \
| --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
ac_prev=x_libraries ;;
-x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
| --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
x_libraries=$ac_optarg ;;
-*) as_fn_error $? "unrecognized option: \`$ac_option'
Try \`$0 --help' for more information"
;;
*=*)
ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
# Reject names that are not valid shell variable names.
case $ac_envvar in #(
'' | [0-9]* | *[!_$as_cr_alnum]* )
as_fn_error $? "invalid variable name: \`$ac_envvar'" ;;
esac
eval $ac_envvar=\$ac_optarg
export $ac_envvar ;;
*)
# FIXME: should be removed in autoconf 3.0.
$as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2
expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
$as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
: "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}"
;;
esac
done
if test -n "$ac_prev"; then
ac_option=--`echo $ac_prev | sed 's/_/-/g'`
as_fn_error $? "missing argument to $ac_option"
fi
if test -n "$ac_unrecognized_opts"; then
case $enable_option_checking in
no) ;;
fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;;
*) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;;
esac
fi
# Check all directory arguments for consistency.
for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \
datadir sysconfdir sharedstatedir localstatedir includedir \
oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
libdir localedir mandir runstatedir
do
eval ac_val=\$$ac_var
# Remove trailing slashes.
case $ac_val in
*/ )
ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'`
eval $ac_var=\$ac_val;;
esac
# Be sure to have absolute directory names.
case $ac_val in
[\\/$]* | ?:[\\/]* ) continue;;
NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
esac
as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val"
done
# There might be people who depend on the old broken behavior: `$host'
# used to hold the argument of --host etc.
# FIXME: To remove some day.
build=$build_alias
host=$host_alias
target=$target_alias
# FIXME: To remove some day.
if test "x$host_alias" != x; then
if test "x$build_alias" = x; then
cross_compiling=maybe
elif test "x$build_alias" != "x$host_alias"; then
cross_compiling=yes
fi
fi
ac_tool_prefix=
test -n "$host_alias" && ac_tool_prefix=$host_alias-
test "$silent" = yes && exec 6>/dev/null
ac_pwd=`pwd` && test -n "$ac_pwd" &&
ac_ls_di=`ls -di .` &&
ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
as_fn_error $? "working directory cannot be determined"
test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
as_fn_error $? "pwd does not report name of working directory"
# Find the source files, if location was not specified.
if test -z "$srcdir"; then
ac_srcdir_defaulted=yes
# Try the directory containing this script, then the parent directory.
ac_confdir=`$as_dirname -- "$as_myself" ||
$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
X"$as_myself" : 'X\(//\)[^/]' \| \
X"$as_myself" : 'X\(//\)$' \| \
X"$as_myself" : 'X\(/\)' \| . 2>/dev/null ||
$as_echo X"$as_myself" |
sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
s//\1/
q
}
/^X\(\/\/\)[^/].*/{
s//\1/
q
}
/^X\(\/\/\)$/{
s//\1/
q
}
/^X\(\/\).*/{
s//\1/
q
}
s/.*/./; q'`
srcdir=$ac_confdir
if test ! -r "$srcdir/$ac_unique_file"; then
srcdir=..
fi
else
ac_srcdir_defaulted=no
fi
if test ! -r "$srcdir/$ac_unique_file"; then
test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir"
fi
ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
ac_abs_confdir=`(
cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg"
pwd)`
# When building in place, set srcdir=.
if test "$ac_abs_confdir" = "$ac_pwd"; then
srcdir=.
fi
# Remove unnecessary trailing slashes from srcdir.
# Double slashes in file names in object file debugging info
# mess up M-x gdb in Emacs.
case $srcdir in
*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
esac
for ac_var in $ac_precious_vars; do
eval ac_env_${ac_var}_set=\${${ac_var}+set}
eval ac_env_${ac_var}_value=\$${ac_var}
eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
eval ac_cv_env_${ac_var}_value=\$${ac_var}
done
#
# Report the --help message.
#
if test "$ac_init_help" = "long"; then
# Omit some internal or obsolete options to make the list less imposing.
# This message is too long to be a string in the A/UX 3.1 sh.
cat <<_ACEOF
\`configure' configures fast_xml 1.1.21 to adapt to many kinds of systems.
Usage: $0 [OPTION]... [VAR=VALUE]...
To assign environment variables (e.g., CC, CFLAGS...), specify them as
VAR=VALUE. See below for descriptions of some of the useful variables.
Defaults for the options are specified in brackets.
Configuration:
-h, --help display this help and exit
--help=short display options specific to this package
--help=recursive display the short help of all the included packages
-V, --version display version information and exit
-q, --quiet, --silent do not print \`checking ...' messages
--cache-file=FILE cache test results in FILE [disabled]
-C, --config-cache alias for \`--cache-file=config.cache'
-n, --no-create do not create output files
--srcdir=DIR find the sources in DIR [configure dir or \`..']
Installation directories:
--prefix=PREFIX install architecture-independent files in PREFIX
[$ac_default_prefix]
--exec-prefix=EPREFIX install architecture-dependent files in EPREFIX
[PREFIX]
By default, \`make install' will install all the files in
\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify
an installation prefix other than \`$ac_default_prefix' using \`--prefix',
for instance \`--prefix=\$HOME'.
For better control, use the options below.
Fine tuning of the installation directories:
--bindir=DIR user executables [EPREFIX/bin]
--sbindir=DIR system admin executables [EPREFIX/sbin]
--libexecdir=DIR program executables [EPREFIX/libexec]
--sysconfdir=DIR read-only single-machine data [PREFIX/etc]
--sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com]
--localstatedir=DIR modifiable single-machine data [PREFIX/var]
--runstatedir=DIR modifiable per-process data [LOCALSTATEDIR/run]
--libdir=DIR object code libraries [EPREFIX/lib]
--includedir=DIR C header files [PREFIX/include]
--oldincludedir=DIR C header files for non-gcc [/usr/include]
--datarootdir=DIR read-only arch.-independent data root [PREFIX/share]
--datadir=DIR read-only architecture-independent data [DATAROOTDIR]
--infodir=DIR info documentation [DATAROOTDIR/info]
--localedir=DIR locale-dependent data [DATAROOTDIR/locale]
--mandir=DIR man documentation [DATAROOTDIR/man]
--docdir=DIR documentation root [DATAROOTDIR/doc/fast_xml]
--htmldir=DIR html documentation [DOCDIR]
--dvidir=DIR dvi documentation [DOCDIR]
--pdfdir=DIR pdf documentation [DOCDIR]
--psdir=DIR ps documentation [DOCDIR]
_ACEOF
cat <<\_ACEOF
_ACEOF
fi
if test -n "$ac_init_help"; then
case $ac_init_help in
short | recursive ) echo "Configuration of fast_xml 1.1.21:";;
esac
cat <<\_ACEOF
Optional Features:
--disable-option-checking ignore unrecognized --enable/--with options
--disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no)
--enable-FEATURE[=ARG] include FEATURE [ARG=yes]
--enable-gcov compile with gcov enabled (default: no)
Some influential environment variables:
CC C compiler command
CFLAGS C compiler flags
LDFLAGS linker flags, e.g. -L if you have libraries in a
nonstandard directory
LIBS libraries to pass to the linker, e.g. -l
CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if
you have headers in a nonstandard directory
CPP C preprocessor
ERL Erlang/OTP interpreter command [autodetected]
ERLC Erlang/OTP compiler command [autodetected]
ERLCFLAGS Erlang/OTP compiler flags [none]
Use these variables to override the choices made by `configure' or to help
it to find libraries and programs with nonstandard names/locations.
Report bugs to the package provider.
_ACEOF
ac_status=$?
fi
if test "$ac_init_help" = "recursive"; then
# If there are subdirs, report their specific --help.
for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
test -d "$ac_dir" ||
{ cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } ||
continue
ac_builddir=.
case "$ac_dir" in
.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
*)
ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
# A ".." for each directory in $ac_dir_suffix.
ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
case $ac_top_builddir_sub in
"") ac_top_builddir_sub=. ac_top_build_prefix= ;;
*) ac_top_build_prefix=$ac_top_builddir_sub/ ;;
esac ;;
esac
ac_abs_top_builddir=$ac_pwd
ac_abs_builddir=$ac_pwd$ac_dir_suffix
# for backward compatibility:
ac_top_builddir=$ac_top_build_prefix
case $srcdir in
.) # We are building in place.
ac_srcdir=.
ac_top_srcdir=$ac_top_builddir_sub
ac_abs_top_srcdir=$ac_pwd ;;
[\\/]* | ?:[\\/]* ) # Absolute name.
ac_srcdir=$srcdir$ac_dir_suffix;
ac_top_srcdir=$srcdir
ac_abs_top_srcdir=$srcdir ;;
*) # Relative name.
ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
ac_top_srcdir=$ac_top_build_prefix$srcdir
ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
esac
ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
cd "$ac_dir" || { ac_status=$?; continue; }
# Check for guested configure.
if test -f "$ac_srcdir/configure.gnu"; then
echo &&
$SHELL "$ac_srcdir/configure.gnu" --help=recursive
elif test -f "$ac_srcdir/configure"; then
echo &&
$SHELL "$ac_srcdir/configure" --help=recursive
else
$as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
fi || ac_status=$?
cd "$ac_pwd" || { ac_status=$?; break; }
done
fi
test -n "$ac_init_help" && exit $ac_status
if $ac_init_version; then
cat <<\_ACEOF
fast_xml configure 1.1.21
generated by GNU Autoconf 2.69
Copyright (C) 2012 Free Software Foundation, Inc.
This configure script is free software; the Free Software Foundation
gives unlimited permission to copy, distribute and modify it.
_ACEOF
exit
fi
## ------------------------ ##
## Autoconf initialization. ##
## ------------------------ ##
# ac_fn_c_try_compile LINENO
# --------------------------
# Try to compile conftest.$ac_ext, and return whether this succeeded.
ac_fn_c_try_compile ()
{
as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
rm -f conftest.$ac_objext
if { { ac_try="$ac_compile"
case "(($ac_try" in
*\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
*) ac_try_echo=$ac_try;;
esac
eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
$as_echo "$ac_try_echo"; } >&5
(eval "$ac_compile") 2>conftest.err
ac_status=$?
if test -s conftest.err; then
grep -v '^ *+' conftest.err >conftest.er1
cat conftest.er1 >&5
mv -f conftest.er1 conftest.err
fi
$as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
test $ac_status = 0; } && {
test -z "$ac_c_werror_flag" ||
test ! -s conftest.err
} && test -s conftest.$ac_objext; then :
ac_retval=0
else
$as_echo "$as_me: failed program was:" >&5
sed 's/^/| /' conftest.$ac_ext >&5
ac_retval=1
fi
eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
as_fn_set_status $ac_retval
} # ac_fn_c_try_compile
# ac_fn_c_try_cpp LINENO
# ----------------------
# Try to preprocess conftest.$ac_ext, and return whether this succeeded.
ac_fn_c_try_cpp ()
{
as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
if { { ac_try="$ac_cpp conftest.$ac_ext"
case "(($ac_try" in
*\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
*) ac_try_echo=$ac_try;;
esac
eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
$as_echo "$ac_try_echo"; } >&5
(eval "$ac_cpp conftest.$ac_ext") 2>conftest.err
ac_status=$?
if test -s conftest.err; then
grep -v '^ *+' conftest.err >conftest.er1
cat conftest.er1 >&5
mv -f conftest.er1 conftest.err
fi
$as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
test $ac_status = 0; } > conftest.i && {
test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
test ! -s conftest.err
}; then :
ac_retval=0
else
$as_echo "$as_me: failed program was:" >&5
sed 's/^/| /' conftest.$ac_ext >&5
ac_retval=1
fi
eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
as_fn_set_status $ac_retval
} # ac_fn_c_try_cpp
# ac_fn_c_try_run LINENO
# ----------------------
# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
# that executables *can* be run.
ac_fn_c_try_run ()
{
as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
if { { ac_try="$ac_link"
case "(($ac_try" in
*\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
*) ac_try_echo=$ac_try;;
esac
eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
$as_echo "$ac_try_echo"; } >&5
(eval "$ac_link") 2>&5
ac_status=$?
$as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
test $ac_status = 0; } && { ac_try='./conftest$ac_exeext'
{ { case "(($ac_try" in
*\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
*) ac_try_echo=$ac_try;;
esac
eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
$as_echo "$ac_try_echo"; } >&5
(eval "$ac_try") 2>&5
ac_status=$?
$as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
test $ac_status = 0; }; }; then :
ac_retval=0
else
$as_echo "$as_me: program exited with status $ac_status" >&5
$as_echo "$as_me: failed program was:" >&5
sed 's/^/| /' conftest.$ac_ext >&5
ac_retval=$ac_status
fi
rm -rf conftest.dSYM conftest_ipa8_conftest.oo
eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
as_fn_set_status $ac_retval
} # ac_fn_c_try_run
# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES
# -------------------------------------------------------
# Tests whether HEADER exists, giving a warning if it cannot be compiled using
# the include files in INCLUDES and setting the cache variable VAR
# accordingly.
ac_fn_c_check_header_mongrel ()
{
as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
if eval \${$3+:} false; then :
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
$as_echo_n "checking for $2... " >&6; }
if eval \${$3+:} false; then :
$as_echo_n "(cached) " >&6
fi
eval ac_res=\$$3
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
$as_echo "$ac_res" >&6; }
else
# Is the header compilable?
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5
$as_echo_n "checking $2 usability... " >&6; }
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
$4
#include <$2>
_ACEOF
if ac_fn_c_try_compile "$LINENO"; then :
ac_header_compiler=yes
else
ac_header_compiler=no
fi
rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5
$as_echo "$ac_header_compiler" >&6; }
# Is the header present?
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5
$as_echo_n "checking $2 presence... " >&6; }
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
#include <$2>
_ACEOF
if ac_fn_c_try_cpp "$LINENO"; then :
ac_header_preproc=yes
else
ac_header_preproc=no
fi
rm -f conftest.err conftest.i conftest.$ac_ext
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5
$as_echo "$ac_header_preproc" >&6; }
# So? What about this header?
case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #((
yes:no: )
{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5
$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;}
{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
;;
no:yes:* )
{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5
$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;}
{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5
$as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;}
{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5
$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;}
{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5
$as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;}
{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
;;
esac
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
$as_echo_n "checking for $2... " >&6; }
if eval \${$3+:} false; then :
$as_echo_n "(cached) " >&6
else
eval "$3=\$ac_header_compiler"
fi
eval ac_res=\$$3
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
$as_echo "$ac_res" >&6; }
fi
eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
} # ac_fn_c_check_header_mongrel
# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES
# -------------------------------------------------------
# Tests whether HEADER exists and can be compiled using the include files in
# INCLUDES, setting the cache variable VAR accordingly.
ac_fn_c_check_header_compile ()
{
as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
$as_echo_n "checking for $2... " >&6; }
if eval \${$3+:} false; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
$4
#include <$2>
_ACEOF
if ac_fn_c_try_compile "$LINENO"; then :
eval "$3=yes"
else
eval "$3=no"
fi
rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
fi
eval ac_res=\$$3
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
$as_echo "$ac_res" >&6; }
eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
} # ac_fn_c_check_header_compile
# ac_fn_c_try_link LINENO
# -----------------------
# Try to link conftest.$ac_ext, and return whether this succeeded.
ac_fn_c_try_link ()
{
as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
rm -f conftest.$ac_objext conftest$ac_exeext
if { { ac_try="$ac_link"
case "(($ac_try" in
*\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
*) ac_try_echo=$ac_try;;
esac
eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
$as_echo "$ac_try_echo"; } >&5
(eval "$ac_link") 2>conftest.err
ac_status=$?
if test -s conftest.err; then
grep -v '^ *+' conftest.err >conftest.er1
cat conftest.er1 >&5
mv -f conftest.er1 conftest.err
fi
$as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
test $ac_status = 0; } && {
test -z "$ac_c_werror_flag" ||
test ! -s conftest.err
} && test -s conftest$ac_exeext && {
test "$cross_compiling" = yes ||
test -x conftest$ac_exeext
}; then :
ac_retval=0
else
$as_echo "$as_me: failed program was:" >&5
sed 's/^/| /' conftest.$ac_ext >&5
ac_retval=1
fi
# Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information
# created by the PGI compiler (conftest_ipa8_conftest.oo), as it would
# interfere with the next link command; also delete a directory that is
# left behind by Apple's compiler. We do this before executing the actions.
rm -rf conftest.dSYM conftest_ipa8_conftest.oo
eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
as_fn_set_status $ac_retval
} # ac_fn_c_try_link
cat >config.log <<_ACEOF
This file contains any messages produced by compilers while
running configure, to aid debugging if configure makes a mistake.
It was created by fast_xml $as_me 1.1.21, which was
generated by GNU Autoconf 2.69. Invocation command line was
$ $0 $@
_ACEOF
exec 5>>config.log
{
cat <<_ASUNAME
## --------- ##
## Platform. ##
## --------- ##
hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
uname -m = `(uname -m) 2>/dev/null || echo unknown`
uname -r = `(uname -r) 2>/dev/null || echo unknown`
uname -s = `(uname -s) 2>/dev/null || echo unknown`
uname -v = `(uname -v) 2>/dev/null || echo unknown`
/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown`
/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown`
/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown`
/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown`
/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown`
/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown`
/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown`
_ASUNAME
as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
for as_dir in $PATH
do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
$as_echo "PATH: $as_dir"
done
IFS=$as_save_IFS
} >&5
cat >&5 <<_ACEOF
## ----------- ##
## Core tests. ##
## ----------- ##
_ACEOF
# Keep a trace of the command line.
# Strip out --no-create and --no-recursion so they do not pile up.
# Strip out --silent because we don't want to record it for future runs.
# Also quote any args containing shell meta-characters.
# Make two passes to allow for proper duplicate-argument suppression.
ac_configure_args=
ac_configure_args0=
ac_configure_args1=
ac_must_keep_next=false
for ac_pass in 1 2
do
for ac_arg
do
case $ac_arg in
-no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
-q | -quiet | --quiet | --quie | --qui | --qu | --q \
| -silent | --silent | --silen | --sile | --sil)
continue ;;
*\'*)
ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
esac
case $ac_pass in
1) as_fn_append ac_configure_args0 " '$ac_arg'" ;;
2)
as_fn_append ac_configure_args1 " '$ac_arg'"
if test $ac_must_keep_next = true; then
ac_must_keep_next=false # Got value, back to normal.
else
case $ac_arg in
*=* | --config-cache | -C | -disable-* | --disable-* \
| -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
| -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
| -with-* | --with-* | -without-* | --without-* | --x)
case "$ac_configure_args0 " in
"$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
esac
;;
-* ) ac_must_keep_next=true ;;
esac
fi
as_fn_append ac_configure_args " '$ac_arg'"
;;
esac
done
done
{ ac_configure_args0=; unset ac_configure_args0;}
{ ac_configure_args1=; unset ac_configure_args1;}
# When interrupted or exit'd, cleanup temporary files, and complete
# config.log. We remove comments because anyway the quotes in there
# would cause problems or look ugly.
# WARNING: Use '\'' to represent an apostrophe within the trap.
# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
trap 'exit_status=$?
# Save into config.log some information that might help in debugging.
{
echo
$as_echo "## ---------------- ##
## Cache variables. ##
## ---------------- ##"
echo
# The following way of writing the cache mishandles newlines in values,
(
for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
eval ac_val=\$$ac_var
case $ac_val in #(
*${as_nl}*)
case $ac_var in #(
*_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
esac
case $ac_var in #(
_ | IFS | as_nl) ;; #(
BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
*) { eval $ac_var=; unset $ac_var;} ;;
esac ;;
esac
done
(set) 2>&1 |
case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
*${as_nl}ac_space=\ *)
sed -n \
"s/'\''/'\''\\\\'\'''\''/g;
s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
;; #(
*)
sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
;;
esac |
sort
)
echo
$as_echo "## ----------------- ##
## Output variables. ##
## ----------------- ##"
echo
for ac_var in $ac_subst_vars
do
eval ac_val=\$$ac_var
case $ac_val in
*\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
esac
$as_echo "$ac_var='\''$ac_val'\''"
done | sort
echo
if test -n "$ac_subst_files"; then
$as_echo "## ------------------- ##
## File substitutions. ##
## ------------------- ##"
echo
for ac_var in $ac_subst_files
do
eval ac_val=\$$ac_var
case $ac_val in
*\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
esac
$as_echo "$ac_var='\''$ac_val'\''"
done | sort
echo
fi
if test -s confdefs.h; then
$as_echo "## ----------- ##
## confdefs.h. ##
## ----------- ##"
echo
cat confdefs.h
echo
fi
test "$ac_signal" != 0 &&
$as_echo "$as_me: caught signal $ac_signal"
$as_echo "$as_me: exit $exit_status"
} >&5
rm -f core *.core core.conftest.* &&
rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
exit $exit_status
' 0
for ac_signal in 1 2 13 15; do
trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal
done
ac_signal=0
# confdefs.h avoids OS command line length limits that DEFS can exceed.
rm -f -r conftest* confdefs.h
$as_echo "/* confdefs.h */" > confdefs.h
# Predefined preprocessor variables.
cat >>confdefs.h <<_ACEOF
#define PACKAGE_NAME "$PACKAGE_NAME"
_ACEOF
cat >>confdefs.h <<_ACEOF
#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
_ACEOF
cat >>confdefs.h <<_ACEOF
#define PACKAGE_VERSION "$PACKAGE_VERSION"
_ACEOF
cat >>confdefs.h <<_ACEOF
#define PACKAGE_STRING "$PACKAGE_STRING"
_ACEOF
cat >>confdefs.h <<_ACEOF
#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
_ACEOF
cat >>confdefs.h <<_ACEOF
#define PACKAGE_URL "$PACKAGE_URL"
_ACEOF
# Let the site file select an alternate cache file if it wants to.
# Prefer an explicitly selected file to automatically selected ones.
ac_site_file1=NONE
ac_site_file2=NONE
if test -n "$CONFIG_SITE"; then
# We do not want a PATH search for config.site.
case $CONFIG_SITE in #((
-*) ac_site_file1=./$CONFIG_SITE;;
*/*) ac_site_file1=$CONFIG_SITE;;
*) ac_site_file1=./$CONFIG_SITE;;
esac
elif test "x$prefix" != xNONE; then
ac_site_file1=$prefix/share/config.site
ac_site_file2=$prefix/etc/config.site
else
ac_site_file1=$ac_default_prefix/share/config.site
ac_site_file2=$ac_default_prefix/etc/config.site
fi
for ac_site_file in "$ac_site_file1" "$ac_site_file2"
do
test "x$ac_site_file" = xNONE && continue
if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5
$as_echo "$as_me: loading site script $ac_site_file" >&6;}
sed 's/^/| /' "$ac_site_file" >&5
. "$ac_site_file" \
|| { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error $? "failed to load site script $ac_site_file
See \`config.log' for more details" "$LINENO" 5; }
fi
done
if test -r "$cache_file"; then
# Some versions of bash will fail to source /dev/null (special files
# actually), so we avoid doing that. DJGPP emulates it as a regular file.
if test /dev/null != "$cache_file" && test -f "$cache_file"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5
$as_echo "$as_me: loading cache $cache_file" >&6;}
case $cache_file in
[\\/]* | ?:[\\/]* ) . "$cache_file";;
*) . "./$cache_file";;
esac
fi
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5
$as_echo "$as_me: creating cache $cache_file" >&6;}
>$cache_file
fi
# Check that the precious variables saved in the cache have kept the same
# value.
ac_cache_corrupted=false
for ac_var in $ac_precious_vars; do
eval ac_old_set=\$ac_cv_env_${ac_var}_set
eval ac_new_set=\$ac_env_${ac_var}_set
eval ac_old_val=\$ac_cv_env_${ac_var}_value
eval ac_new_val=\$ac_env_${ac_var}_value
case $ac_old_set,$ac_new_set in
set,)
{ $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
ac_cache_corrupted=: ;;
,set)
{ $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5
$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
ac_cache_corrupted=: ;;
,);;
*)
if test "x$ac_old_val" != "x$ac_new_val"; then
# differences in whitespace do not lead to failure.
ac_old_val_w=`echo x $ac_old_val`
ac_new_val_w=`echo x $ac_new_val`
if test "$ac_old_val_w" != "$ac_new_val_w"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5
$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
ac_cache_corrupted=:
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5
$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;}
eval $ac_var=\$ac_old_val
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5
$as_echo "$as_me: former value: \`$ac_old_val'" >&2;}
{ $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5
$as_echo "$as_me: current value: \`$ac_new_val'" >&2;}
fi;;
esac
# Pass precious variables to config.status.
if test "$ac_new_set" = set; then
case $ac_new_val in
*\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
*) ac_arg=$ac_var=$ac_new_val ;;
esac
case " $ac_configure_args " in
*" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy.
*) as_fn_append ac_configure_args " '$ac_arg'" ;;
esac
fi
done
if $ac_cache_corrupted; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
{ $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5
$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;}
as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5
fi
## -------------------- ##
## Main body of script. ##
## -------------------- ##
ac_ext=c
ac_cpp='$CPP $CPPFLAGS'
ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
ac_compiler_gnu=$ac_cv_c_compiler_gnu
# Checks for programs.
ac_ext=c
ac_cpp='$CPP $CPPFLAGS'
ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
ac_compiler_gnu=$ac_cv_c_compiler_gnu
if test -n "$ac_tool_prefix"; then
# Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
set dummy ${ac_tool_prefix}gcc; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
if ${ac_cv_prog_CC+:} false; then :
$as_echo_n "(cached) " >&6
else
if test -n "$CC"; then
ac_cv_prog_CC="$CC" # Let the user override the test.
else
as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
for as_dir in $PATH
do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
ac_cv_prog_CC="${ac_tool_prefix}gcc"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
fi
done
done
IFS=$as_save_IFS
fi
fi
CC=$ac_cv_prog_CC
if test -n "$CC"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
$as_echo "$CC" >&6; }
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
$as_echo "no" >&6; }
fi
fi
if test -z "$ac_cv_prog_CC"; then
ac_ct_CC=$CC
# Extract the first word of "gcc", so it can be a program name with args.
set dummy gcc; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
if ${ac_cv_prog_ac_ct_CC+:} false; then :
$as_echo_n "(cached) " >&6
else
if test -n "$ac_ct_CC"; then
ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
else
as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
for as_dir in $PATH
do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
ac_cv_prog_ac_ct_CC="gcc"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
fi
done
done
IFS=$as_save_IFS
fi
fi
ac_ct_CC=$ac_cv_prog_ac_ct_CC
if test -n "$ac_ct_CC"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
$as_echo "$ac_ct_CC" >&6; }
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
$as_echo "no" >&6; }
fi
if test "x$ac_ct_CC" = x; then
CC=""
else
case $cross_compiling:$ac_tool_warned in
yes:)
{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
ac_tool_warned=yes ;;
esac
CC=$ac_ct_CC
fi
else
CC="$ac_cv_prog_CC"
fi
if test -z "$CC"; then
if test -n "$ac_tool_prefix"; then
# Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
set dummy ${ac_tool_prefix}cc; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
if ${ac_cv_prog_CC+:} false; then :
$as_echo_n "(cached) " >&6
else
if test -n "$CC"; then
ac_cv_prog_CC="$CC" # Let the user override the test.
else
as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
for as_dir in $PATH
do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
ac_cv_prog_CC="${ac_tool_prefix}cc"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
fi
done
done
IFS=$as_save_IFS
fi
fi
CC=$ac_cv_prog_CC
if test -n "$CC"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
$as_echo "$CC" >&6; }
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
$as_echo "no" >&6; }
fi
fi
fi
if test -z "$CC"; then
# Extract the first word of "cc", so it can be a program name with args.
set dummy cc; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
if ${ac_cv_prog_CC+:} false; then :
$as_echo_n "(cached) " >&6
else
if test -n "$CC"; then
ac_cv_prog_CC="$CC" # Let the user override the test.
else
ac_prog_rejected=no
as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
for as_dir in $PATH
do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
ac_prog_rejected=yes
continue
fi
ac_cv_prog_CC="cc"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
fi
done
done
IFS=$as_save_IFS
if test $ac_prog_rejected = yes; then
# We found a bogon in the path, so make sure we never use it.
set dummy $ac_cv_prog_CC
shift
if test $# != 0; then
# We chose a different compiler from the bogus one.
# However, it has the same basename, so the bogon will be chosen
# first if we set CC to just the basename; use the full file name.
shift
ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"
fi
fi
fi
fi
CC=$ac_cv_prog_CC
if test -n "$CC"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
$as_echo "$CC" >&6; }
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
$as_echo "no" >&6; }
fi
fi
if test -z "$CC"; then
if test -n "$ac_tool_prefix"; then
for ac_prog in cl.exe
do
# Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
set dummy $ac_tool_prefix$ac_prog; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
if ${ac_cv_prog_CC+:} false; then :
$as_echo_n "(cached) " >&6
else
if test -n "$CC"; then
ac_cv_prog_CC="$CC" # Let the user override the test.
else
as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
for as_dir in $PATH
do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
fi
done
done
IFS=$as_save_IFS
fi
fi
CC=$ac_cv_prog_CC
if test -n "$CC"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
$as_echo "$CC" >&6; }
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
$as_echo "no" >&6; }
fi
test -n "$CC" && break
done
fi
if test -z "$CC"; then
ac_ct_CC=$CC
for ac_prog in cl.exe
do
# Extract the first word of "$ac_prog", so it can be a program name with args.
set dummy $ac_prog; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
if ${ac_cv_prog_ac_ct_CC+:} false; then :
$as_echo_n "(cached) " >&6
else
if test -n "$ac_ct_CC"; then
ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
else
as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
for as_dir in $PATH
do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
ac_cv_prog_ac_ct_CC="$ac_prog"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
fi
done
done
IFS=$as_save_IFS
fi
fi
ac_ct_CC=$ac_cv_prog_ac_ct_CC
if test -n "$ac_ct_CC"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
$as_echo "$ac_ct_CC" >&6; }
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
$as_echo "no" >&6; }
fi
test -n "$ac_ct_CC" && break
done
if test "x$ac_ct_CC" = x; then
CC=""
else
case $cross_compiling:$ac_tool_warned in
yes:)
{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
ac_tool_warned=yes ;;
esac
CC=$ac_ct_CC
fi
fi
fi
test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error $? "no acceptable C compiler found in \$PATH
See \`config.log' for more details" "$LINENO" 5; }
# Provide some information about the compiler.
$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
set X $ac_compile
ac_compiler=$2
for ac_option in --version -v -V -qversion; do
{ { ac_try="$ac_compiler $ac_option >&5"
case "(($ac_try" in
*\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
*) ac_try_echo=$ac_try;;
esac
eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
$as_echo "$ac_try_echo"; } >&5
(eval "$ac_compiler $ac_option >&5") 2>conftest.err
ac_status=$?
if test -s conftest.err; then
sed '10a\
... rest of stderr output deleted ...
10q' conftest.err >conftest.er1
cat conftest.er1 >&5
fi
rm -f conftest.er1 conftest.err
$as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
test $ac_status = 0; }
done
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
int
main ()
{
;
return 0;
}
_ACEOF
ac_clean_files_save=$ac_clean_files
ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out"
# Try to create an executable without -o first, disregard a.out.
# It will help us diagnose broken compilers, and finding out an intuition
# of exeext.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5
$as_echo_n "checking whether the C compiler works... " >&6; }
ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
# The possible output files:
ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*"
ac_rmfiles=
for ac_file in $ac_files
do
case $ac_file in
*.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
* ) ac_rmfiles="$ac_rmfiles $ac_file";;
esac
done
rm -f $ac_rmfiles
if { { ac_try="$ac_link_default"
case "(($ac_try" in
*\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
*) ac_try_echo=$ac_try;;
esac
eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
$as_echo "$ac_try_echo"; } >&5
(eval "$ac_link_default") 2>&5
ac_status=$?
$as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
test $ac_status = 0; }; then :
# Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
# So ignore a value of `no', otherwise this would lead to `EXEEXT = no'
# in a Makefile. We should not override ac_cv_exeext if it was cached,
# so that the user can short-circuit this test for compilers unknown to
# Autoconf.
for ac_file in $ac_files ''
do
test -f "$ac_file" || continue
case $ac_file in
*.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj )
;;
[ab].out )
# We found the default executable, but exeext='' is most
# certainly right.
break;;
*.* )
if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;
then :; else
ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
fi
# We set ac_cv_exeext here because the later test for it is not
# safe: cross compilers may not add the suffix if given an `-o'
# argument, so we may need to know it at that point already.
# Even if this section looks crufty: it has the advantage of
# actually working.
break;;
* )
break;;
esac
done
test "$ac_cv_exeext" = no && ac_cv_exeext=
else
ac_file=''
fi
if test -z "$ac_file"; then :
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
$as_echo "no" >&6; }
$as_echo "$as_me: failed program was:" >&5
sed 's/^/| /' conftest.$ac_ext >&5
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error 77 "C compiler cannot create executables
See \`config.log' for more details" "$LINENO" 5; }
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
$as_echo "yes" >&6; }
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5
$as_echo_n "checking for C compiler default output file name... " >&6; }
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5
$as_echo "$ac_file" >&6; }
ac_exeext=$ac_cv_exeext
rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out
ac_clean_files=$ac_clean_files_save
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5
$as_echo_n "checking for suffix of executables... " >&6; }
if { { ac_try="$ac_link"
case "(($ac_try" in
*\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
*) ac_try_echo=$ac_try;;
esac
eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
$as_echo "$ac_try_echo"; } >&5
(eval "$ac_link") 2>&5
ac_status=$?
$as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
test $ac_status = 0; }; then :
# If both `conftest.exe' and `conftest' are `present' (well, observable)
# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will
# work properly (i.e., refer to `conftest.exe'), while it won't with
# `rm'.
for ac_file in conftest.exe conftest conftest.*; do
test -f "$ac_file" || continue
case $ac_file in
*.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
*.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
break;;
* ) break;;
esac
done
else
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error $? "cannot compute suffix of executables: cannot compile and link
See \`config.log' for more details" "$LINENO" 5; }
fi
rm -f conftest conftest$ac_cv_exeext
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
$as_echo "$ac_cv_exeext" >&6; }
rm -f conftest.$ac_ext
EXEEXT=$ac_cv_exeext
ac_exeext=$EXEEXT
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
#include
int
main ()
{
FILE *f = fopen ("conftest.out", "w");
return ferror (f) || fclose (f) != 0;
;
return 0;
}
_ACEOF
ac_clean_files="$ac_clean_files conftest.out"
# Check that the compiler produces executables we can run. If not, either
# the compiler is broken, or we cross compile.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5
$as_echo_n "checking whether we are cross compiling... " >&6; }
if test "$cross_compiling" != yes; then
{ { ac_try="$ac_link"
case "(($ac_try" in
*\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
*) ac_try_echo=$ac_try;;
esac
eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
$as_echo "$ac_try_echo"; } >&5
(eval "$ac_link") 2>&5
ac_status=$?
$as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
test $ac_status = 0; }
if { ac_try='./conftest$ac_cv_exeext'
{ { case "(($ac_try" in
*\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
*) ac_try_echo=$ac_try;;
esac
eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
$as_echo "$ac_try_echo"; } >&5
(eval "$ac_try") 2>&5
ac_status=$?
$as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
test $ac_status = 0; }; }; then
cross_compiling=no
else
if test "$cross_compiling" = maybe; then
cross_compiling=yes
else
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error $? "cannot run C compiled programs.
If you meant to cross compile, use \`--host'.
See \`config.log' for more details" "$LINENO" 5; }
fi
fi
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5
$as_echo "$cross_compiling" >&6; }
rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out
ac_clean_files=$ac_clean_files_save
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
$as_echo_n "checking for suffix of object files... " >&6; }
if ${ac_cv_objext+:} false; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
int
main ()
{
;
return 0;
}
_ACEOF
rm -f conftest.o conftest.obj
if { { ac_try="$ac_compile"
case "(($ac_try" in
*\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
*) ac_try_echo=$ac_try;;
esac
eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
$as_echo "$ac_try_echo"; } >&5
(eval "$ac_compile") 2>&5
ac_status=$?
$as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
test $ac_status = 0; }; then :
for ac_file in conftest.o conftest.obj conftest.*; do
test -f "$ac_file" || continue;
case $ac_file in
*.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;;
*) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
break;;
esac
done
else
$as_echo "$as_me: failed program was:" >&5
sed 's/^/| /' conftest.$ac_ext >&5
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error $? "cannot compute suffix of object files: cannot compile
See \`config.log' for more details" "$LINENO" 5; }
fi
rm -f conftest.$ac_cv_objext conftest.$ac_ext
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5
$as_echo "$ac_cv_objext" >&6; }
OBJEXT=$ac_cv_objext
ac_objext=$OBJEXT
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
if ${ac_cv_c_compiler_gnu+:} false; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
int
main ()
{
#ifndef __GNUC__
choke me
#endif
;
return 0;
}
_ACEOF
if ac_fn_c_try_compile "$LINENO"; then :
ac_compiler_gnu=yes
else
ac_compiler_gnu=no
fi
rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
ac_cv_c_compiler_gnu=$ac_compiler_gnu
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
$as_echo "$ac_cv_c_compiler_gnu" >&6; }
if test $ac_compiler_gnu = yes; then
GCC=yes
else
GCC=
fi
ac_test_CFLAGS=${CFLAGS+set}
ac_save_CFLAGS=$CFLAGS
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
$as_echo_n "checking whether $CC accepts -g... " >&6; }
if ${ac_cv_prog_cc_g+:} false; then :
$as_echo_n "(cached) " >&6
else
ac_save_c_werror_flag=$ac_c_werror_flag
ac_c_werror_flag=yes
ac_cv_prog_cc_g=no
CFLAGS="-g"
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
int
main ()
{
;
return 0;
}
_ACEOF
if ac_fn_c_try_compile "$LINENO"; then :
ac_cv_prog_cc_g=yes
else
CFLAGS=""
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
int
main ()
{
;
return 0;
}
_ACEOF
if ac_fn_c_try_compile "$LINENO"; then :
else
ac_c_werror_flag=$ac_save_c_werror_flag
CFLAGS="-g"
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
int
main ()
{
;
return 0;
}
_ACEOF
if ac_fn_c_try_compile "$LINENO"; then :
ac_cv_prog_cc_g=yes
fi
rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
fi
rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
fi
rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
ac_c_werror_flag=$ac_save_c_werror_flag
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
$as_echo "$ac_cv_prog_cc_g" >&6; }
if test "$ac_test_CFLAGS" = set; then
CFLAGS=$ac_save_CFLAGS
elif test $ac_cv_prog_cc_g = yes; then
if test "$GCC" = yes; then
CFLAGS="-g -O2"
else
CFLAGS="-g"
fi
else
if test "$GCC" = yes; then
CFLAGS="-O2"
else
CFLAGS=
fi
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
if ${ac_cv_prog_cc_c89+:} false; then :
$as_echo_n "(cached) " >&6
else
ac_cv_prog_cc_c89=no
ac_save_CC=$CC
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
#include
#include
struct stat;
/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */
struct buf { int x; };
FILE * (*rcsopen) (struct buf *, struct stat *, int);
static char *e (p, i)
char **p;
int i;
{
return p[i];
}
static char *f (char * (*g) (char **, int), char **p, ...)
{
char *s;
va_list v;
va_start (v,p);
s = g (p, va_arg (v,int));
va_end (v);
return s;
}
/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has
function prototypes and stuff, but not '\xHH' hex character constants.
These don't provoke an error unfortunately, instead are silently treated
as 'x'. The following induces an error, until -std is added to get
proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an
array size at least. It's necessary to write '\x00'==0 to get something
that's true only with -std. */
int osf4_cc_array ['\x00' == 0 ? 1 : -1];
/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
inside strings and character constants. */
#define FOO(x) 'x'
int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
int test (int i, double x);
struct s1 {int (*f) (int a);};
struct s2 {int (*f) (double a);};
int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
int argc;
char **argv;
int
main ()
{
return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1];
;
return 0;
}
_ACEOF
for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
-Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
do
CC="$ac_save_CC $ac_arg"
if ac_fn_c_try_compile "$LINENO"; then :
ac_cv_prog_cc_c89=$ac_arg
fi
rm -f core conftest.err conftest.$ac_objext
test "x$ac_cv_prog_cc_c89" != "xno" && break
done
rm -f conftest.$ac_ext
CC=$ac_save_CC
fi
# AC_CACHE_VAL
case "x$ac_cv_prog_cc_c89" in
x)
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
$as_echo "none needed" >&6; } ;;
xno)
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
$as_echo "unsupported" >&6; } ;;
*)
CC="$CC $ac_cv_prog_cc_c89"
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;
esac
if test "x$ac_cv_prog_cc_c89" != xno; then :
fi
ac_ext=c
ac_cpp='$CPP $CPPFLAGS'
ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
ac_compiler_gnu=$ac_cv_c_compiler_gnu
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5
$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; }
set x ${MAKE-make}
ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'`
if eval \${ac_cv_prog_make_${ac_make}_set+:} false; then :
$as_echo_n "(cached) " >&6
else
cat >conftest.make <<\_ACEOF
SHELL = /bin/sh
all:
@echo '@@@%%%=$(MAKE)=@@@%%%'
_ACEOF
# GNU make sometimes prints "make[1]: Entering ...", which would confuse us.
case `${MAKE-make} -f conftest.make 2>/dev/null` in
*@@@%%%=?*=@@@%%%*)
eval ac_cv_prog_make_${ac_make}_set=yes;;
*)
eval ac_cv_prog_make_${ac_make}_set=no;;
esac
rm -f conftest.make
fi
if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
$as_echo "yes" >&6; }
SET_MAKE=
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
$as_echo "no" >&6; }
SET_MAKE="MAKE=${MAKE-make}"
fi
if test "x$GCC" = "xyes"; then
CFLAGS="$CFLAGS -Wall"
fi
# Checks for typedefs, structures, and compiler characteristics.
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5
$as_echo_n "checking for an ANSI C-conforming const... " >&6; }
if ${ac_cv_c_const+:} false; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
int
main ()
{
#ifndef __cplusplus
/* Ultrix mips cc rejects this sort of thing. */
typedef int charset[2];
const charset cs = { 0, 0 };
/* SunOS 4.1.1 cc rejects this. */
char const *const *pcpcc;
char **ppc;
/* NEC SVR4.0.2 mips cc rejects this. */
struct point {int x, y;};
static struct point const zero = {0,0};
/* AIX XL C 1.02.0.0 rejects this.
It does not let you subtract one const X* pointer from another in
an arm of an if-expression whose if-part is not a constant
expression */
const char *g = "string";
pcpcc = &g + (g ? g-g : 0);
/* HPUX 7.0 cc rejects these. */
++pcpcc;
ppc = (char**) pcpcc;
pcpcc = (char const *const *) ppc;
{ /* SCO 3.2v4 cc rejects this sort of thing. */
char tx;
char *t = &tx;
char const *s = 0 ? (char *) 0 : (char const *) 0;
*t++ = 0;
if (s) return 0;
}
{ /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */
int x[] = {25, 17};
const int *foo = &x[0];
++foo;
}
{ /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */
typedef const int *iptr;
iptr p = 0;
++p;
}
{ /* AIX XL C 1.02.0.0 rejects this sort of thing, saying
"k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */
struct s { int j; const int *ap[3]; } bx;
struct s *b = &bx; b->j = 5;
}
{ /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */
const int foo = 10;
if (!foo) return 0;
}
return !cs[0] && !zero.x;
#endif
;
return 0;
}
_ACEOF
if ac_fn_c_try_compile "$LINENO"; then :
ac_cv_c_const=yes
else
ac_cv_c_const=no
fi
rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5
$as_echo "$ac_cv_c_const" >&6; }
if test $ac_cv_c_const = no; then
$as_echo "#define const /**/" >>confdefs.h
fi
# Checks for library functions.
ac_ext=c
ac_cpp='$CPP $CPPFLAGS'
ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
ac_compiler_gnu=$ac_cv_c_compiler_gnu
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5
$as_echo_n "checking how to run the C preprocessor... " >&6; }
# On Suns, sometimes $CPP names a directory.
if test -n "$CPP" && test -d "$CPP"; then
CPP=
fi
if test -z "$CPP"; then
if ${ac_cv_prog_CPP+:} false; then :
$as_echo_n "(cached) " >&6
else
# Double quotes because CPP needs to be expanded
for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
do
ac_preproc_ok=false
for ac_c_preproc_warn_flag in '' yes
do
# Use a header file that comes with gcc, so configuring glibc
# with a fresh cross-compiler works.
# Prefer to if __STDC__ is defined, since
# exists even on freestanding compilers.
# On the NeXT, cc -E runs the code through the compiler's parser,
# not just through cpp. "Syntax error" is here to catch this case.
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
#ifdef __STDC__
# include
#else
# include
#endif
Syntax error
_ACEOF
if ac_fn_c_try_cpp "$LINENO"; then :
else
# Broken: fails on valid input.
continue
fi
rm -f conftest.err conftest.i conftest.$ac_ext
# OK, works on sane cases. Now check whether nonexistent headers
# can be detected and how.
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
#include
_ACEOF
if ac_fn_c_try_cpp "$LINENO"; then :
# Broken: success on invalid input.
continue
else
# Passes both tests.
ac_preproc_ok=:
break
fi
rm -f conftest.err conftest.i conftest.$ac_ext
done
# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
rm -f conftest.i conftest.err conftest.$ac_ext
if $ac_preproc_ok; then :
break
fi
done
ac_cv_prog_CPP=$CPP
fi
CPP=$ac_cv_prog_CPP
else
ac_cv_prog_CPP=$CPP
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5
$as_echo "$CPP" >&6; }
ac_preproc_ok=false
for ac_c_preproc_warn_flag in '' yes
do
# Use a header file that comes with gcc, so configuring glibc
# with a fresh cross-compiler works.
# Prefer to if __STDC__ is defined, since
# exists even on freestanding compilers.
# On the NeXT, cc -E runs the code through the compiler's parser,
# not just through cpp. "Syntax error" is here to catch this case.
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
#ifdef __STDC__
# include
#else
# include
#endif
Syntax error
_ACEOF
if ac_fn_c_try_cpp "$LINENO"; then :
else
# Broken: fails on valid input.
continue
fi
rm -f conftest.err conftest.i conftest.$ac_ext
# OK, works on sane cases. Now check whether nonexistent headers
# can be detected and how.
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
#include
_ACEOF
if ac_fn_c_try_cpp "$LINENO"; then :
# Broken: success on invalid input.
continue
else
# Passes both tests.
ac_preproc_ok=:
break
fi
rm -f conftest.err conftest.i conftest.$ac_ext
done
# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
rm -f conftest.i conftest.err conftest.$ac_ext
if $ac_preproc_ok; then :
else
{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
See \`config.log' for more details" "$LINENO" 5; }
fi
ac_ext=c
ac_cpp='$CPP $CPPFLAGS'
ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
ac_compiler_gnu=$ac_cv_c_compiler_gnu
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5
$as_echo_n "checking for grep that handles long lines and -e... " >&6; }
if ${ac_cv_path_GREP+:} false; then :
$as_echo_n "(cached) " >&6
else
if test -z "$GREP"; then
ac_path_GREP_found=false
# Loop through the user's path and test for each of PROGNAME-LIST
as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_prog in grep ggrep; do
for ac_exec_ext in '' $ac_executable_extensions; do
ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext"
as_fn_executable_p "$ac_path_GREP" || continue
# Check for GNU ac_path_GREP and select it if it is found.
# Check for GNU $ac_path_GREP
case `"$ac_path_GREP" --version 2>&1` in
*GNU*)
ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;;
*)
ac_count=0
$as_echo_n 0123456789 >"conftest.in"
while :
do
cat "conftest.in" "conftest.in" >"conftest.tmp"
mv "conftest.tmp" "conftest.in"
cp "conftest.in" "conftest.nl"
$as_echo 'GREP' >> "conftest.nl"
"$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break
diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
as_fn_arith $ac_count + 1 && ac_count=$as_val
if test $ac_count -gt ${ac_path_GREP_max-0}; then
# Best one so far, save it but keep looking for a better one
ac_cv_path_GREP="$ac_path_GREP"
ac_path_GREP_max=$ac_count
fi
# 10*(2^10) chars as input seems more than enough
test $ac_count -gt 10 && break
done
rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
esac
$ac_path_GREP_found && break 3
done
done
done
IFS=$as_save_IFS
if test -z "$ac_cv_path_GREP"; then
as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
fi
else
ac_cv_path_GREP=$GREP
fi
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5
$as_echo "$ac_cv_path_GREP" >&6; }
GREP="$ac_cv_path_GREP"
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5
$as_echo_n "checking for egrep... " >&6; }
if ${ac_cv_path_EGREP+:} false; then :
$as_echo_n "(cached) " >&6
else
if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
then ac_cv_path_EGREP="$GREP -E"
else
if test -z "$EGREP"; then
ac_path_EGREP_found=false
# Loop through the user's path and test for each of PROGNAME-LIST
as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_prog in egrep; do
for ac_exec_ext in '' $ac_executable_extensions; do
ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext"
as_fn_executable_p "$ac_path_EGREP" || continue
# Check for GNU ac_path_EGREP and select it if it is found.
# Check for GNU $ac_path_EGREP
case `"$ac_path_EGREP" --version 2>&1` in
*GNU*)
ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;;
*)
ac_count=0
$as_echo_n 0123456789 >"conftest.in"
while :
do
cat "conftest.in" "conftest.in" >"conftest.tmp"
mv "conftest.tmp" "conftest.in"
cp "conftest.in" "conftest.nl"
$as_echo 'EGREP' >> "conftest.nl"
"$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break
diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
as_fn_arith $ac_count + 1 && ac_count=$as_val
if test $ac_count -gt ${ac_path_EGREP_max-0}; then
# Best one so far, save it but keep looking for a better one
ac_cv_path_EGREP="$ac_path_EGREP"
ac_path_EGREP_max=$ac_count
fi
# 10*(2^10) chars as input seems more than enough
test $ac_count -gt 10 && break
done
rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
esac
$ac_path_EGREP_found && break 3
done
done
done
IFS=$as_save_IFS
if test -z "$ac_cv_path_EGREP"; then
as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
fi
else
ac_cv_path_EGREP=$EGREP
fi
fi
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5
$as_echo "$ac_cv_path_EGREP" >&6; }
EGREP="$ac_cv_path_EGREP"
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
$as_echo_n "checking for ANSI C header files... " >&6; }
if ${ac_cv_header_stdc+:} false; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
#include
#include
#include
#include
int
main ()
{
;
return 0;
}
_ACEOF
if ac_fn_c_try_compile "$LINENO"; then :
ac_cv_header_stdc=yes
else
ac_cv_header_stdc=no
fi
rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
if test $ac_cv_header_stdc = yes; then
# SunOS 4.x string.h does not declare mem*, contrary to ANSI.
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
#include
_ACEOF
if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
$EGREP "memchr" >/dev/null 2>&1; then :
else
ac_cv_header_stdc=no
fi
rm -f conftest*
fi
if test $ac_cv_header_stdc = yes; then
# ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
#include
_ACEOF
if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
$EGREP "free" >/dev/null 2>&1; then :
else
ac_cv_header_stdc=no
fi
rm -f conftest*
fi
if test $ac_cv_header_stdc = yes; then
# /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
if test "$cross_compiling" = yes; then :
:
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
#include
#include
#if ((' ' & 0x0FF) == 0x020)
# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
#else
# define ISLOWER(c) \
(('a' <= (c) && (c) <= 'i') \
|| ('j' <= (c) && (c) <= 'r') \
|| ('s' <= (c) && (c) <= 'z'))
# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
#endif
#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
int
main ()
{
int i;
for (i = 0; i < 256; i++)
if (XOR (islower (i), ISLOWER (i))
|| toupper (i) != TOUPPER (i))
return 2;
return 0;
}
_ACEOF
if ac_fn_c_try_run "$LINENO"; then :
else
ac_cv_header_stdc=no
fi
rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
conftest.$ac_objext conftest.beam conftest.$ac_ext
fi
fi
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
$as_echo "$ac_cv_header_stdc" >&6; }
if test $ac_cv_header_stdc = yes; then
$as_echo "#define STDC_HEADERS 1" >>confdefs.h
fi
# On IRIX 5.3, sys/types and inttypes.h are conflicting.
for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \
inttypes.h stdint.h unistd.h
do :
as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default
"
if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
cat >>confdefs.h <<_ACEOF
#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
_ACEOF
fi
done
for ac_header in stdlib.h
do :
ac_fn_c_check_header_mongrel "$LINENO" "stdlib.h" "ac_cv_header_stdlib_h" "$ac_includes_default"
if test "x$ac_cv_header_stdlib_h" = xyes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_STDLIB_H 1
_ACEOF
fi
done
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU libc compatible malloc" >&5
$as_echo_n "checking for GNU libc compatible malloc... " >&6; }
if ${ac_cv_func_malloc_0_nonnull+:} false; then :
$as_echo_n "(cached) " >&6
else
if test "$cross_compiling" = yes; then :
ac_cv_func_malloc_0_nonnull=no
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
#if defined STDC_HEADERS || defined HAVE_STDLIB_H
# include
#else
char *malloc ();
#endif
int
main ()
{
return ! malloc (0);
;
return 0;
}
_ACEOF
if ac_fn_c_try_run "$LINENO"; then :
ac_cv_func_malloc_0_nonnull=yes
else
ac_cv_func_malloc_0_nonnull=no
fi
rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
conftest.$ac_objext conftest.beam conftest.$ac_ext
fi
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_malloc_0_nonnull" >&5
$as_echo "$ac_cv_func_malloc_0_nonnull" >&6; }
if test $ac_cv_func_malloc_0_nonnull = yes; then :
$as_echo "#define HAVE_MALLOC 1" >>confdefs.h
else
$as_echo "#define HAVE_MALLOC 0" >>confdefs.h
case " $LIBOBJS " in
*" malloc.$ac_objext "* ) ;;
*) LIBOBJS="$LIBOBJS malloc.$ac_objext"
;;
esac
$as_echo "#define malloc rpl_malloc" >>confdefs.h
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
$as_echo_n "checking for ANSI C header files... " >&6; }
if ${ac_cv_header_stdc+:} false; then :
$as_echo_n "(cached) " >&6
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
#include
#include
#include
#include
int
main ()
{
;
return 0;
}
_ACEOF
if ac_fn_c_try_compile "$LINENO"; then :
ac_cv_header_stdc=yes
else
ac_cv_header_stdc=no
fi
rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
if test $ac_cv_header_stdc = yes; then
# SunOS 4.x string.h does not declare mem*, contrary to ANSI.
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
#include
_ACEOF
if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
$EGREP "memchr" >/dev/null 2>&1; then :
else
ac_cv_header_stdc=no
fi
rm -f conftest*
fi
if test $ac_cv_header_stdc = yes; then
# ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
#include
_ACEOF
if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
$EGREP "free" >/dev/null 2>&1; then :
else
ac_cv_header_stdc=no
fi
rm -f conftest*
fi
if test $ac_cv_header_stdc = yes; then
# /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
if test "$cross_compiling" = yes; then :
:
else
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
#include
#include
#if ((' ' & 0x0FF) == 0x020)
# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
#else
# define ISLOWER(c) \
(('a' <= (c) && (c) <= 'i') \
|| ('j' <= (c) && (c) <= 'r') \
|| ('s' <= (c) && (c) <= 'z'))
# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
#endif
#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
int
main ()
{
int i;
for (i = 0; i < 256; i++)
if (XOR (islower (i), ISLOWER (i))
|| toupper (i) != TOUPPER (i))
return 2;
return 0;
}
_ACEOF
if ac_fn_c_try_run "$LINENO"; then :
else
ac_cv_header_stdc=no
fi
rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
conftest.$ac_objext conftest.beam conftest.$ac_ext
fi
fi
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
$as_echo "$ac_cv_header_stdc" >&6; }
if test $ac_cv_header_stdc = yes; then
$as_echo "#define STDC_HEADERS 1" >>confdefs.h
fi
# Checks Erlang runtime and compiler
if test -n "$ERL"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for erl" >&5
$as_echo_n "checking for erl... " >&6; }
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ERL" >&5
$as_echo "$ERL" >&6; }
else
if test -n "$ac_tool_prefix"; then
# Extract the first word of "${ac_tool_prefix}erl", so it can be a program name with args.
set dummy ${ac_tool_prefix}erl; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
if ${ac_cv_path_ERL+:} false; then :
$as_echo_n "(cached) " >&6
else
case $ERL in
[\\/]* | ?:[\\/]*)
ac_cv_path_ERL="$ERL" # Let the user override the test with a path.
;;
*)
as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
for as_dir in $PATH
do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
ac_cv_path_ERL="$as_dir/$ac_word$ac_exec_ext"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
fi
done
done
IFS=$as_save_IFS
;;
esac
fi
ERL=$ac_cv_path_ERL
if test -n "$ERL"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ERL" >&5
$as_echo "$ERL" >&6; }
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
$as_echo "no" >&6; }
fi
fi
if test -z "$ac_cv_path_ERL"; then
ac_pt_ERL=$ERL
# Extract the first word of "erl", so it can be a program name with args.
set dummy erl; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
if ${ac_cv_path_ac_pt_ERL+:} false; then :
$as_echo_n "(cached) " >&6
else
case $ac_pt_ERL in
[\\/]* | ?:[\\/]*)
ac_cv_path_ac_pt_ERL="$ac_pt_ERL" # Let the user override the test with a path.
;;
*)
as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
for as_dir in $PATH
do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
ac_cv_path_ac_pt_ERL="$as_dir/$ac_word$ac_exec_ext"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
fi
done
done
IFS=$as_save_IFS
;;
esac
fi
ac_pt_ERL=$ac_cv_path_ac_pt_ERL
if test -n "$ac_pt_ERL"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_ERL" >&5
$as_echo "$ac_pt_ERL" >&6; }
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
$as_echo "no" >&6; }
fi
if test "x$ac_pt_ERL" = x; then
ERL="not found"
else
case $cross_compiling:$ac_tool_warned in
yes:)
{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
ac_tool_warned=yes ;;
esac
ERL=$ac_pt_ERL
fi
else
ERL="$ac_cv_path_ERL"
fi
fi
if test "$ERL" = "not found"; then
as_fn_error $? "Erlang/OTP interpreter (erl) not found but required" "$LINENO" 5
fi
if test -n "$ERLC"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for erlc" >&5
$as_echo_n "checking for erlc... " >&6; }
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ERLC" >&5
$as_echo "$ERLC" >&6; }
else
if test -n "$ac_tool_prefix"; then
# Extract the first word of "${ac_tool_prefix}erlc", so it can be a program name with args.
set dummy ${ac_tool_prefix}erlc; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
if ${ac_cv_path_ERLC+:} false; then :
$as_echo_n "(cached) " >&6
else
case $ERLC in
[\\/]* | ?:[\\/]*)
ac_cv_path_ERLC="$ERLC" # Let the user override the test with a path.
;;
*)
as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
for as_dir in $PATH
do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
ac_cv_path_ERLC="$as_dir/$ac_word$ac_exec_ext"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
fi
done
done
IFS=$as_save_IFS
;;
esac
fi
ERLC=$ac_cv_path_ERLC
if test -n "$ERLC"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ERLC" >&5
$as_echo "$ERLC" >&6; }
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
$as_echo "no" >&6; }
fi
fi
if test -z "$ac_cv_path_ERLC"; then
ac_pt_ERLC=$ERLC
# Extract the first word of "erlc", so it can be a program name with args.
set dummy erlc; ac_word=$2
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
$as_echo_n "checking for $ac_word... " >&6; }
if ${ac_cv_path_ac_pt_ERLC+:} false; then :
$as_echo_n "(cached) " >&6
else
case $ac_pt_ERLC in
[\\/]* | ?:[\\/]*)
ac_cv_path_ac_pt_ERLC="$ac_pt_ERLC" # Let the user override the test with a path.
;;
*)
as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
for as_dir in $PATH
do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
ac_cv_path_ac_pt_ERLC="$as_dir/$ac_word$ac_exec_ext"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
fi
done
done
IFS=$as_save_IFS
;;
esac
fi
ac_pt_ERLC=$ac_cv_path_ac_pt_ERLC
if test -n "$ac_pt_ERLC"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_ERLC" >&5
$as_echo "$ac_pt_ERLC" >&6; }
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
$as_echo "no" >&6; }
fi
if test "x$ac_pt_ERLC" = x; then
ERLC="not found"
else
case $cross_compiling:$ac_tool_warned in
yes:)
{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
ac_tool_warned=yes ;;
esac
ERLC=$ac_pt_ERLC
fi
else
ERLC="$ac_cv_path_ERLC"
fi
fi
if test "$ERLC" = "not found"; then
as_fn_error $? "Erlang/OTP compiler (erlc) not found but required" "$LINENO" 5
fi
# Checks and sets ERLANG_ROOT_DIR and ERLANG_LIB_DIR variable
# AC_ERLANG_SUBST_ROOT_DIR
# AC_ERLANG_SUBST_LIB_DIR
for ac_header in expat.h
do :
ac_fn_c_check_header_mongrel "$LINENO" "expat.h" "ac_cv_header_expat_h" "$ac_includes_default"
if test "x$ac_cv_header_expat_h" = xyes; then :
cat >>confdefs.h <<_ACEOF
#define HAVE_EXPAT_H 1
_ACEOF
else
as_fn_error $? "libexpat header file expat.h was not found" "$LINENO" 5
fi
done
{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing XML_ParserCreate" >&5
$as_echo_n "checking for library containing XML_ParserCreate... " >&6; }
if ${ac_cv_search_XML_ParserCreate+:} false; then :
$as_echo_n "(cached) " >&6
else
ac_func_search_save_LIBS=$LIBS
cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
/* Override any GCC internal prototype to avoid an error.
Use char because int might match the return type of a GCC
builtin and then its argument prototype would still apply. */
#ifdef __cplusplus
extern "C"
#endif
char XML_ParserCreate ();
int
main ()
{
return XML_ParserCreate ();
;
return 0;
}
_ACEOF
for ac_lib in '' expat; do
if test -z "$ac_lib"; then
ac_res="none required"
else
ac_res=-l$ac_lib
LIBS="-l$ac_lib $ac_func_search_save_LIBS"
fi
if ac_fn_c_try_link "$LINENO"; then :
ac_cv_search_XML_ParserCreate=$ac_res
fi
rm -f core conftest.err conftest.$ac_objext \
conftest$ac_exeext
if ${ac_cv_search_XML_ParserCreate+:} false; then :
break
fi
done
if ${ac_cv_search_XML_ParserCreate+:} false; then :
else
ac_cv_search_XML_ParserCreate=no
fi
rm conftest.$ac_ext
LIBS=$ac_func_search_save_LIBS
fi
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_XML_ParserCreate" >&5
$as_echo "$ac_cv_search_XML_ParserCreate" >&6; }
ac_res=$ac_cv_search_XML_ParserCreate
if test "$ac_res" != no; then :
test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
else
as_fn_error $? "libexpat library was not found" "$LINENO" 5
fi
# Check whether --enable-gcov was given.
if test "${enable_gcov+set}" = set; then :
enableval=$enable_gcov; case "${enableval}" in
yes) gcov=true ;;
no) gcov=false ;;
*) as_fn_error $? "bad value ${enableval} for --enable-gcov" "$LINENO" 5 ;;
esac
else
gcov=false
fi
ac_config_files="$ac_config_files vars.config"
cat >confcache <<\_ACEOF
# This file is a shell script that caches the results of configure
# tests run on this system so they can be shared between configure
# scripts and configure runs, see configure's option --config-cache.
# It is not useful on other systems. If it contains results you don't
# want to keep, you may remove or edit it.
#
# config.status only pays attention to the cache file if you give it
# the --recheck option to rerun configure.
#
# `ac_cv_env_foo' variables (set or unset) will be overridden when
# loading this file, other *unset* `ac_cv_foo' will be assigned the
# following values.
_ACEOF
# The following way of writing the cache mishandles newlines in values,
# but we know of no workaround that is simple, portable, and efficient.
# So, we kill variables containing newlines.
# Ultrix sh set writes to stderr and can't be redirected directly,
# and sets the high bit in the cache file unless we assign to the vars.
(
for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
eval ac_val=\$$ac_var
case $ac_val in #(
*${as_nl}*)
case $ac_var in #(
*_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
esac
case $ac_var in #(
_ | IFS | as_nl) ;; #(
BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
*) { eval $ac_var=; unset $ac_var;} ;;
esac ;;
esac
done
(set) 2>&1 |
case $as_nl`(ac_space=' '; set) 2>&1` in #(
*${as_nl}ac_space=\ *)
# `set' does not quote correctly, so add quotes: double-quote
# substitution turns \\\\ into \\, and sed turns \\ into \.
sed -n \
"s/'/'\\\\''/g;
s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
;; #(
*)
# `set' quotes correctly as required by POSIX, so do not add quotes.
sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
;;
esac |
sort
) |
sed '
/^ac_cv_env_/b end
t clear
:clear
s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
t end
s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
:end' >>confcache
if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
if test -w "$cache_file"; then
if test "x$cache_file" != "x/dev/null"; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
$as_echo "$as_me: updating cache $cache_file" >&6;}
if test ! -f "$cache_file" || test -h "$cache_file"; then
cat confcache >"$cache_file"
else
case $cache_file in #(
*/* | ?:*)
mv -f confcache "$cache_file"$$ &&
mv -f "$cache_file"$$ "$cache_file" ;; #(
*)
mv -f confcache "$cache_file" ;;
esac
fi
fi
else
{ $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
fi
fi
rm -f confcache
test "x$prefix" = xNONE && prefix=$ac_default_prefix
# Let make expand exec_prefix.
test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
# Transform confdefs.h into DEFS.
# Protect against shell expansion while executing Makefile rules.
# Protect against Makefile macro expansion.
#
# If the first sed substitution is executed (which looks for macros that
# take arguments), then branch to the quote section. Otherwise,
# look for a macro that doesn't take arguments.
ac_script='
:mline
/\\$/{
N
s,\\\n,,
b mline
}
t clear
:clear
s/^[ ]*#[ ]*define[ ][ ]*\([^ (][^ (]*([^)]*)\)[ ]*\(.*\)/-D\1=\2/g
t quote
s/^[ ]*#[ ]*define[ ][ ]*\([^ ][^ ]*\)[ ]*\(.*\)/-D\1=\2/g
t quote
b any
:quote
s/[ `~#$^&*(){}\\|;'\''"<>?]/\\&/g
s/\[/\\&/g
s/\]/\\&/g
s/\$/$$/g
H
:any
${
g
s/^\n//
s/\n/ /g
p
}
'
DEFS=`sed -n "$ac_script" confdefs.h`
ac_libobjs=
ac_ltlibobjs=
U=
for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
# 1. Remove the extension, and $U if already installed.
ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
ac_i=`$as_echo "$ac_i" | sed "$ac_script"`
# 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR
# will be set to the directory where LIBOBJS objects are built.
as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext"
as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo'
done
LIBOBJS=$ac_libobjs
LTLIBOBJS=$ac_ltlibobjs
: "${CONFIG_STATUS=./config.status}"
ac_write_fail=0
ac_clean_files_save=$ac_clean_files
ac_clean_files="$ac_clean_files $CONFIG_STATUS"
{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5
$as_echo "$as_me: creating $CONFIG_STATUS" >&6;}
as_write_fail=0
cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1
#! $SHELL
# Generated by $as_me.
# Run this file to recreate the current configuration.
# Compiler output produced by configure, useful for debugging
# configure, is in config.log if it exists.
debug=false
ac_cs_recheck=false
ac_cs_silent=false
SHELL=\${CONFIG_SHELL-$SHELL}
export SHELL
_ASEOF
cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1
## -------------------- ##
## M4sh Initialization. ##
## -------------------- ##
# Be more Bourne compatible
DUALCASE=1; export DUALCASE # for MKS sh
if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
emulate sh
NULLCMD=:
# Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
# is contrary to our usage. Disable this feature.
alias -g '${1+"$@"}'='"$@"'
setopt NO_GLOB_SUBST
else
case `(set -o) 2>/dev/null` in #(
*posix*) :
set -o posix ;; #(
*) :
;;
esac
fi
as_nl='
'
export as_nl
# Printing a long string crashes Solaris 7 /usr/bin/printf.
as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
# Prefer a ksh shell builtin over an external printf program on Solaris,
# but without wasting forks for bash or zsh.
if test -z "$BASH_VERSION$ZSH_VERSION" \
&& (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
as_echo='print -r --'
as_echo_n='print -rn --'
elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
as_echo='printf %s\n'
as_echo_n='printf %s'
else
if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
as_echo_n='/usr/ucb/echo -n'
else
as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
as_echo_n_body='eval
arg=$1;
case $arg in #(
*"$as_nl"*)
expr "X$arg" : "X\\(.*\\)$as_nl";
arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
esac;
expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
'
export as_echo_n_body
as_echo_n='sh -c $as_echo_n_body as_echo'
fi
export as_echo_body
as_echo='sh -c $as_echo_body as_echo'
fi
# The user is always right.
if test "${PATH_SEPARATOR+set}" != set; then
PATH_SEPARATOR=:
(PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
(PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
PATH_SEPARATOR=';'
}
fi
# IFS
# We need space, tab and new line, in precisely that order. Quoting is
# there to prevent editors from complaining about space-tab.
# (If _AS_PATH_WALK were called with IFS unset, it would disable word
# splitting by setting IFS to empty value.)
IFS=" "" $as_nl"
# Find who we are. Look in the path if we contain no directory separator.
as_myself=
case $0 in #((
*[\\/]* ) as_myself=$0 ;;
*) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
for as_dir in $PATH
do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
done
IFS=$as_save_IFS
;;
esac
# We did not find ourselves, most probably we were run as `sh COMMAND'
# in which case we are not to be found in the path.
if test "x$as_myself" = x; then
as_myself=$0
fi
if test ! -f "$as_myself"; then
$as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
exit 1
fi
# Unset variables that we do not need and which cause bugs (e.g. in
# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1"
# suppresses any "Segmentation fault" message there. '((' could
# trigger a bug in pdksh 5.2.14.
for as_var in BASH_ENV ENV MAIL MAILPATH
do eval test x\${$as_var+set} = xset \
&& ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
done
PS1='$ '
PS2='> '
PS4='+ '
# NLS nuisances.
LC_ALL=C
export LC_ALL
LANGUAGE=C
export LANGUAGE
# CDPATH.
(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
# as_fn_error STATUS ERROR [LINENO LOG_FD]
# ----------------------------------------
# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
# script with STATUS, using 1 if that was 0.
as_fn_error ()
{
as_status=$1; test $as_status -eq 0 && as_status=1
if test "$4"; then
as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
$as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
fi
$as_echo "$as_me: error: $2" >&2
as_fn_exit $as_status
} # as_fn_error
# as_fn_set_status STATUS
# -----------------------
# Set $? to STATUS, without forking.
as_fn_set_status ()
{
return $1
} # as_fn_set_status
# as_fn_exit STATUS
# -----------------
# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
as_fn_exit ()
{
set +e
as_fn_set_status $1
exit $1
} # as_fn_exit
# as_fn_unset VAR
# ---------------
# Portably unset VAR.
as_fn_unset ()
{
{ eval $1=; unset $1;}
}
as_unset=as_fn_unset
# as_fn_append VAR VALUE
# ----------------------
# Append the text in VALUE to the end of the definition contained in VAR. Take
# advantage of any shell optimizations that allow amortized linear growth over
# repeated appends, instead of the typical quadratic growth present in naive
# implementations.
if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
eval 'as_fn_append ()
{
eval $1+=\$2
}'
else
as_fn_append ()
{
eval $1=\$$1\$2
}
fi # as_fn_append
# as_fn_arith ARG...
# ------------------
# Perform arithmetic evaluation on the ARGs, and store the result in the
# global $as_val. Take advantage of shells that can avoid forks. The arguments
# must be portable across $(()) and expr.
if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
eval 'as_fn_arith ()
{
as_val=$(( $* ))
}'
else
as_fn_arith ()
{
as_val=`expr "$@" || test $? -eq 1`
}
fi # as_fn_arith
if expr a : '\(a\)' >/dev/null 2>&1 &&
test "X`expr 00001 : '.*\(...\)'`" = X001; then
as_expr=expr
else
as_expr=false
fi
if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
as_basename=basename
else
as_basename=false
fi
if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
as_dirname=dirname
else
as_dirname=false
fi
as_me=`$as_basename -- "$0" ||
$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
X"$0" : 'X\(//\)$' \| \
X"$0" : 'X\(/\)' \| . 2>/dev/null ||
$as_echo X/"$0" |
sed '/^.*\/\([^/][^/]*\)\/*$/{
s//\1/
q
}
/^X\/\(\/\/\)$/{
s//\1/
q
}
/^X\/\(\/\).*/{
s//\1/
q
}
s/.*/./; q'`
# Avoid depending upon Character Ranges.
as_cr_letters='abcdefghijklmnopqrstuvwxyz'
as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
as_cr_Letters=$as_cr_letters$as_cr_LETTERS
as_cr_digits='0123456789'
as_cr_alnum=$as_cr_Letters$as_cr_digits
ECHO_C= ECHO_N= ECHO_T=
case `echo -n x` in #(((((
-n*)
case `echo 'xy\c'` in
*c*) ECHO_T=' ';; # ECHO_T is single tab character.
xy) ECHO_C='\c';;
*) echo `echo ksh88 bug on AIX 6.1` > /dev/null
ECHO_T=' ';;
esac;;
*)
ECHO_N='-n';;
esac
rm -f conf$$ conf$$.exe conf$$.file
if test -d conf$$.dir; then
rm -f conf$$.dir/conf$$.file
else
rm -f conf$$.dir
mkdir conf$$.dir 2>/dev/null
fi
if (echo >conf$$.file) 2>/dev/null; then
if ln -s conf$$.file conf$$ 2>/dev/null; then
as_ln_s='ln -s'
# ... but there are two gotchas:
# 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
# 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
# In both cases, we have to default to `cp -pR'.
ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
as_ln_s='cp -pR'
elif ln conf$$.file conf$$ 2>/dev/null; then
as_ln_s=ln
else
as_ln_s='cp -pR'
fi
else
as_ln_s='cp -pR'
fi
rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
rmdir conf$$.dir 2>/dev/null
# as_fn_mkdir_p
# -------------
# Create "$as_dir" as a directory, including parents if necessary.
as_fn_mkdir_p ()
{
case $as_dir in #(
-*) as_dir=./$as_dir;;
esac
test -d "$as_dir" || eval $as_mkdir_p || {
as_dirs=
while :; do
case $as_dir in #(
*\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
*) as_qdir=$as_dir;;
esac
as_dirs="'$as_qdir' $as_dirs"
as_dir=`$as_dirname -- "$as_dir" ||
$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
X"$as_dir" : 'X\(//\)[^/]' \| \
X"$as_dir" : 'X\(//\)$' \| \
X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
$as_echo X"$as_dir" |
sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
s//\1/
q
}
/^X\(\/\/\)[^/].*/{
s//\1/
q
}
/^X\(\/\/\)$/{
s//\1/
q
}
/^X\(\/\).*/{
s//\1/
q
}
s/.*/./; q'`
test -d "$as_dir" && break
done
test -z "$as_dirs" || eval "mkdir $as_dirs"
} || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
} # as_fn_mkdir_p
if mkdir -p . 2>/dev/null; then
as_mkdir_p='mkdir -p "$as_dir"'
else
test -d ./-p && rmdir ./-p
as_mkdir_p=false
fi
# as_fn_executable_p FILE
# -----------------------
# Test if FILE is an executable regular file.
as_fn_executable_p ()
{
test -f "$1" && test -x "$1"
} # as_fn_executable_p
as_test_x='test -x'
as_executable_p=as_fn_executable_p
# Sed expression to map a string onto a valid CPP name.
as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
# Sed expression to map a string onto a valid variable name.
as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
exec 6>&1
## ----------------------------------- ##
## Main body of $CONFIG_STATUS script. ##
## ----------------------------------- ##
_ASEOF
test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1
cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
# Save the log message, to keep $0 and so on meaningful, and to
# report actual input values of CONFIG_FILES etc. instead of their
# values after options handling.
ac_log="
This file was extended by fast_xml $as_me 1.1.21, which was
generated by GNU Autoconf 2.69. Invocation command line was
CONFIG_FILES = $CONFIG_FILES
CONFIG_HEADERS = $CONFIG_HEADERS
CONFIG_LINKS = $CONFIG_LINKS
CONFIG_COMMANDS = $CONFIG_COMMANDS
$ $0 $@
on `(hostname || uname -n) 2>/dev/null | sed 1q`
"
_ACEOF
case $ac_config_files in *"
"*) set x $ac_config_files; shift; ac_config_files=$*;;
esac
cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
# Files that config.status was made for.
config_files="$ac_config_files"
_ACEOF
cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
ac_cs_usage="\
\`$as_me' instantiates files and other configuration actions
from templates according to the current configuration. Unless the files
and actions are specified as TAGs, all are instantiated by default.
Usage: $0 [OPTION]... [TAG]...
-h, --help print this help, then exit
-V, --version print version number and configuration settings, then exit
--config print configuration, then exit
-q, --quiet, --silent
do not print progress messages
-d, --debug don't remove temporary files
--recheck update $as_me by reconfiguring in the same conditions
--file=FILE[:TEMPLATE]
instantiate the configuration file FILE
Configuration files:
$config_files
Report bugs to the package provider."
_ACEOF
cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
ac_cs_version="\\
fast_xml config.status 1.1.21
configured by $0, generated by GNU Autoconf 2.69,
with options \\"\$ac_cs_config\\"
Copyright (C) 2012 Free Software Foundation, Inc.
This config.status script is free software; the Free Software Foundation
gives unlimited permission to copy, distribute and modify it."
ac_pwd='$ac_pwd'
srcdir='$srcdir'
test -n "\$AWK" || AWK=awk
_ACEOF
cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
# The default lists apply if the user does not specify any file.
ac_need_defaults=:
while test $# != 0
do
case $1 in
--*=?*)
ac_option=`expr "X$1" : 'X\([^=]*\)='`
ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
ac_shift=:
;;
--*=)
ac_option=`expr "X$1" : 'X\([^=]*\)='`
ac_optarg=
ac_shift=:
;;
*)
ac_option=$1
ac_optarg=$2
ac_shift=shift
;;
esac
case $ac_option in
# Handling of the options.
-recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
ac_cs_recheck=: ;;
--version | --versio | --versi | --vers | --ver | --ve | --v | -V )
$as_echo "$ac_cs_version"; exit ;;
--config | --confi | --conf | --con | --co | --c )
$as_echo "$ac_cs_config"; exit ;;
--debug | --debu | --deb | --de | --d | -d )
debug=: ;;
--file | --fil | --fi | --f )
$ac_shift
case $ac_optarg in
*\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
'') as_fn_error $? "missing file argument" ;;
esac
as_fn_append CONFIG_FILES " '$ac_optarg'"
ac_need_defaults=false;;
--he | --h | --help | --hel | -h )
$as_echo "$ac_cs_usage"; exit ;;
-q | -quiet | --quiet | --quie | --qui | --qu | --q \
| -silent | --silent | --silen | --sile | --sil | --si | --s)
ac_cs_silent=: ;;
# This is an error.
-*) as_fn_error $? "unrecognized option: \`$1'
Try \`$0 --help' for more information." ;;
*) as_fn_append ac_config_targets " $1"
ac_need_defaults=false ;;
esac
shift
done
ac_configure_extra_args=
if $ac_cs_silent; then
exec 6>/dev/null
ac_configure_extra_args="$ac_configure_extra_args --silent"
fi
_ACEOF
cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
if \$ac_cs_recheck; then
set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
shift
\$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6
CONFIG_SHELL='$SHELL'
export CONFIG_SHELL
exec "\$@"
fi
_ACEOF
cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
exec 5>>config.log
{
echo
sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
## Running $as_me. ##
_ASBOX
$as_echo "$ac_log"
} >&5
_ACEOF
cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
_ACEOF
cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
# Handling of arguments.
for ac_config_target in $ac_config_targets
do
case $ac_config_target in
"vars.config") CONFIG_FILES="$CONFIG_FILES vars.config" ;;
*) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
esac
done
# If the user did not use the arguments to specify the items to instantiate,
# then the envvar interface is used. Set only those that are not.
# We use the long form for the default assignment because of an extremely
# bizarre bug on SunOS 4.1.3.
if $ac_need_defaults; then
test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
fi
# Have a temporary directory for convenience. Make it in the build tree
# simply because there is no reason against having it here, and in addition,
# creating and moving files from /tmp can sometimes cause problems.
# Hook for its removal unless debugging.
# Note that there is a small window in which the directory will not be cleaned:
# after its creation but before its name has been assigned to `$tmp'.
$debug ||
{
tmp= ac_tmp=
trap 'exit_status=$?
: "${ac_tmp:=$tmp}"
{ test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status
' 0
trap 'as_fn_exit 1' 1 2 13 15
}
# Create a (secure) tmp directory for tmp files.
{
tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
test -d "$tmp"
} ||
{
tmp=./conf$$-$RANDOM
(umask 077 && mkdir "$tmp")
} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5
ac_tmp=$tmp
# Set up the scripts for CONFIG_FILES section.
# No need to generate them if there are no CONFIG_FILES.
# This happens for instance with `./config.status config.h'.
if test -n "$CONFIG_FILES"; then
ac_cr=`echo X | tr X '\015'`
# On cygwin, bash can eat \r inside `` if the user requested igncr.
# But we know of no other shell where ac_cr would be empty at this
# point, so we can use a bashism as a fallback.
if test "x$ac_cr" = x; then
eval ac_cr=\$\'\\r\'
fi
ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null`
if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then
ac_cs_awk_cr='\\r'
else
ac_cs_awk_cr=$ac_cr
fi
echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&
_ACEOF
{
echo "cat >conf$$subs.awk <<_ACEOF" &&
echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' &&
echo "_ACEOF"
} >conf$$subs.sh ||
as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'`
ac_delim='%!_!# '
for ac_last_try in false false false false false :; do
. ./conf$$subs.sh ||
as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X`
if test $ac_delim_n = $ac_delim_num; then
break
elif $ac_last_try; then
as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
else
ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
fi
done
rm -f conf$$subs.sh
cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK &&
_ACEOF
sed -n '
h
s/^/S["/; s/!.*/"]=/
p
g
s/^[^!]*!//
:repl
t repl
s/'"$ac_delim"'$//
t delim
:nl
h
s/\(.\{148\}\)..*/\1/
t more1
s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/
p
n
b repl
:more1
s/["\\]/\\&/g; s/^/"/; s/$/"\\/
p
g
s/.\{148\}//
t nl
:delim
h
s/\(.\{148\}\)..*/\1/
t more2
s/["\\]/\\&/g; s/^/"/; s/$/"/
p
b
:more2
s/["\\]/\\&/g; s/^/"/; s/$/"\\/
p
g
s/.\{148\}//
t delim
' >$CONFIG_STATUS || ac_write_fail=1
rm -f conf$$subs.awk
cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
_ACAWK
cat >>"\$ac_tmp/subs1.awk" <<_ACAWK &&
for (key in S) S_is_set[key] = 1
FS = ""
}
{
line = $ 0
nfields = split(line, field, "@")
substed = 0
len = length(field[1])
for (i = 2; i < nfields; i++) {
key = field[i]
keylen = length(key)
if (S_is_set[key]) {
value = S[key]
line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3)
len += length(value) + length(field[++i])
substed = 1
} else
len += 1 + keylen
}
print line
}
_ACAWK
_ACEOF
cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then
sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
else
cat
fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \
|| as_fn_error $? "could not setup config files machinery" "$LINENO" 5
_ACEOF
# VPATH may cause trouble with some makes, so we remove sole $(srcdir),
# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and
# trailing colons and then remove the whole line if VPATH becomes empty
# (actually we leave an empty line to preserve line numbers).
if test "x$srcdir" = x.; then
ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{
h
s///
s/^/:/
s/[ ]*$/:/
s/:\$(srcdir):/:/g
s/:\${srcdir}:/:/g
s/:@srcdir@:/:/g
s/^:*//
s/:*$//
x
s/\(=[ ]*\).*/\1/
G
s/\n//
s/^[^=]*=[ ]*$//
}'
fi
cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
fi # test -n "$CONFIG_FILES"
eval set X " :F $CONFIG_FILES "
shift
for ac_tag
do
case $ac_tag in
:[FHLC]) ac_mode=$ac_tag; continue;;
esac
case $ac_mode$ac_tag in
:[FHL]*:*);;
:L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;
:[FH]-) ac_tag=-:-;;
:[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
esac
ac_save_IFS=$IFS
IFS=:
set x $ac_tag
IFS=$ac_save_IFS
shift
ac_file=$1
shift
case $ac_mode in
:L) ac_source=$1;;
:[FH])
ac_file_inputs=
for ac_f
do
case $ac_f in
-) ac_f="$ac_tmp/stdin";;
*) # Look for the file first in the build tree, then in the source tree
# (if the path is not absolute). The absolute path cannot be DOS-style,
# because $ac_f cannot contain `:'.
test -f "$ac_f" ||
case $ac_f in
[\\/$]*) false;;
*) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
esac ||
as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
esac
case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
as_fn_append ac_file_inputs " '$ac_f'"
done
# Let's still pretend it is `configure' which instantiates (i.e., don't
# use $as_me), people would be surprised to read:
# /* config.h. Generated by config.status. */
configure_input='Generated from '`
$as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'
`' by configure.'
if test x"$ac_file" != x-; then
configure_input="$ac_file. $configure_input"
{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5
$as_echo "$as_me: creating $ac_file" >&6;}
fi
# Neutralize special characters interpreted by sed in replacement strings.
case $configure_input in #(
*\&* | *\|* | *\\* )
ac_sed_conf_input=`$as_echo "$configure_input" |
sed 's/[\\\\&|]/\\\\&/g'`;; #(
*) ac_sed_conf_input=$configure_input;;
esac
case $ac_tag in
*:-:* | *:-) cat >"$ac_tmp/stdin" \
|| as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
esac
;;
esac
ac_dir=`$as_dirname -- "$ac_file" ||
$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
X"$ac_file" : 'X\(//\)[^/]' \| \
X"$ac_file" : 'X\(//\)$' \| \
X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
$as_echo X"$ac_file" |
sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
s//\1/
q
}
/^X\(\/\/\)[^/].*/{
s//\1/
q
}
/^X\(\/\/\)$/{
s//\1/
q
}
/^X\(\/\).*/{
s//\1/
q
}
s/.*/./; q'`
as_dir="$ac_dir"; as_fn_mkdir_p
ac_builddir=.
case "$ac_dir" in
.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
*)
ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
# A ".." for each directory in $ac_dir_suffix.
ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
case $ac_top_builddir_sub in
"") ac_top_builddir_sub=. ac_top_build_prefix= ;;
*) ac_top_build_prefix=$ac_top_builddir_sub/ ;;
esac ;;
esac
ac_abs_top_builddir=$ac_pwd
ac_abs_builddir=$ac_pwd$ac_dir_suffix
# for backward compatibility:
ac_top_builddir=$ac_top_build_prefix
case $srcdir in
.) # We are building in place.
ac_srcdir=.
ac_top_srcdir=$ac_top_builddir_sub
ac_abs_top_srcdir=$ac_pwd ;;
[\\/]* | ?:[\\/]* ) # Absolute name.
ac_srcdir=$srcdir$ac_dir_suffix;
ac_top_srcdir=$srcdir
ac_abs_top_srcdir=$srcdir ;;
*) # Relative name.
ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
ac_top_srcdir=$ac_top_build_prefix$srcdir
ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
esac
ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
case $ac_mode in
:F)
#
# CONFIG_FILE
#
_ACEOF
cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
# If the template does not know about datarootdir, expand it.
# FIXME: This hack should be removed a few years after 2.60.
ac_datarootdir_hack=; ac_datarootdir_seen=
ac_sed_dataroot='
/datarootdir/ {
p
q
}
/@datadir@/p
/@docdir@/p
/@infodir@/p
/@localedir@/p
/@mandir@/p'
case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in
*datarootdir*) ac_datarootdir_seen=yes;;
*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
_ACEOF
cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
ac_datarootdir_hack='
s&@datadir@&$datadir&g
s&@docdir@&$docdir&g
s&@infodir@&$infodir&g
s&@localedir@&$localedir&g
s&@mandir@&$mandir&g
s&\\\${datarootdir}&$datarootdir&g' ;;
esac
_ACEOF
# Neutralize VPATH when `$srcdir' = `.'.
# Shell code in configure.ac might set extrasub.
# FIXME: do we really want to maintain this feature?
cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
ac_sed_extra="$ac_vpsub
$extrasub
_ACEOF
cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
:t
/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
s|@configure_input@|$ac_sed_conf_input|;t t
s&@top_builddir@&$ac_top_builddir_sub&;t t
s&@top_build_prefix@&$ac_top_build_prefix&;t t
s&@srcdir@&$ac_srcdir&;t t
s&@abs_srcdir@&$ac_abs_srcdir&;t t
s&@top_srcdir@&$ac_top_srcdir&;t t
s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
s&@builddir@&$ac_builddir&;t t
s&@abs_builddir@&$ac_abs_builddir&;t t
s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
$ac_datarootdir_hack
"
eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \
>$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5
test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
{ ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
{ ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \
"$ac_tmp/out"`; test -z "$ac_out"; } &&
{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
which seems to be undefined. Please make sure it is defined" >&5
$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
which seems to be undefined. Please make sure it is defined" >&2;}
rm -f "$ac_tmp/stdin"
case $ac_file in
-) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;
*) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;
esac \
|| as_fn_error $? "could not create $ac_file" "$LINENO" 5
;;
esac
done # for ac_tag
as_fn_exit 0
_ACEOF
ac_clean_files=$ac_clean_files_save
test $ac_write_fail = 0 ||
as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5
# configure is writing to config.log, and then calls config.status.
# config.status does its own redirection, appending to config.log.
# Unfortunately, on DOS this fails, as config.log is still kept open
# by configure, so config.status won't be able to write to it; its
# output is simply discarded. So we exec the FD to /dev/null,
# effectively closing config.log, so it can be properly (re)opened and
# appended to by config.status. When coming back to configure, we
# need to make the FD available again.
if test "$no_create" != yes; then
ac_cs_success=:
ac_config_status_args=
test "$silent" = yes &&
ac_config_status_args="$ac_config_status_args --quiet"
exec 5>/dev/null
$SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
exec 5>>config.log
# Use ||, not &&, to avoid exiting from the if with $? = 1, which
# would make configure fail if this is the last instruction.
$ac_cs_success || as_fn_exit 1
fi
if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5
$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}
fi