├── .gitignore ├── .gitmodules ├── COPYRIGHT ├── LICENSE-APACHE ├── LICENSE-MIT ├── MANIFEST.in ├── Makefile ├── README.md ├── benchmarks ├── results-cpython2 ├── results-cpython3 ├── results-pypy └── run.py ├── html5ever ├── __init__.py ├── _build_ffi.py └── elementtree.py ├── rust-glue ├── Cargo.lock ├── Cargo.toml ├── examples │ └── time_parse_stdin.rs └── lib.rs ├── setup.py ├── setuptools_ext.py ├── tests ├── api.py └── tree_construction.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | *.so 2 | *.egg-info 3 | *.egg 4 | *.pyc 5 | __pycache__/ 6 | .tox/ 7 | html5ever/_ffi.py 8 | target/ 9 | .cache/ 10 | .eggs/ 11 | profile 12 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "tests/html5lib-tests"] 2 | path = tests/html5lib-tests 3 | url = https://github.com/html5lib/html5lib-tests 4 | -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | This project is copyright 2015, The html5ever-python Project Developers 2 | (as shown by `git shortlog -se`). 3 | 4 | Licensed under the Apache License, Version 2.0 or the MIT license , at your option. Files in the project 7 | may not be copied, modified, or distributed except according to those terms. 8 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 The html5ever Project Developers 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include rust-glue/Cargo.toml 2 | include rust-glue/Cargo.lock 3 | include rust-glue/lib.rs 4 | include setuptools_ext.py 5 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | VENV = ~/.virtualenvs/html5ever 2 | 3 | test: 4 | @${VENV}/bin/python setup.py -q develop 5 | @${VENV}/bin/py.test -q 6 | 7 | bench: 8 | @${VENV}/bin/python benchmarks/run.py | tee benchmarks/results-cpython3 9 | @${VENV}-py2/bin/python benchmarks/run.py | tee benchmarks/results-cpython2 10 | @${VENV}-pypy/bin/python benchmarks/run.py | tee benchmarks/results-pypy 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | html5ever-python 2 | ================ 3 | 4 | Python bindings for [html5ever](https://github.com/servo/html5ever), 5 | using [CFFI](http://cffi.readthedocs.org/en/latest/). 6 | 7 | [![No Maintenance Intended](http://unmaintained.tech/badge.svg)](http://unmaintained.tech/) 8 | -------------------------------------------------------------------------------- /benchmarks/results-cpython2: -------------------------------------------------------------------------------- 1 | Python 2.7.10 (default, Sep 7 2015, 13:51:49) [GCC 5.2.0] 2 | rustc rustc 1.5.0-nightly (f0666b45d 2015-09-24) 3 | html5ever 0.2.5 4 | lxml (3, 4, 4, 0) 5 | libxml (2, 9, 2) 6 | htmllib 0.9999999 7 | 8 | HTML source SHA1: 6a2963fa1f15fe99884acdad8a895af4df8e8c01 9 | Best time of 3, parsing 5,598,887 bytes of HTML: 10 | 11 | html5ever to Rust RcDom: 16.612 MiB/s 12 | lxml.html: 25.601 MiB/s 13 | html5ever-python: 2.923 MiB/s 14 | html5ever-python to ElementTree: 2.607 MiB/s 15 | html5lib to ElementTree: 0.688 MiB/s 16 | html5lib to lxml: 0.446 MiB/s 17 | 18 | -------------------------------------------------------------------------------- /benchmarks/results-cpython3: -------------------------------------------------------------------------------- 1 | Python 3.4.3 (default, Sep 7 2015, 15:40:35) [GCC 5.2.0] 2 | rustc rustc 1.5.0-nightly (f0666b45d 2015-09-24) 3 | html5ever 0.2.5 4 | lxml (3, 4, 4, 0) 5 | libxml (2, 9, 2) 6 | htmllib 0.9999999 7 | 8 | HTML source SHA1: 6a2963fa1f15fe99884acdad8a895af4df8e8c01 9 | Best time of 3, parsing 5,598,887 bytes of HTML: 10 | 11 | html5ever to Rust RcDom: 16.801 MiB/s 12 | lxml.html: 25.107 MiB/s 13 | html5ever-python: 2.957 MiB/s 14 | html5ever-python to ElementTree: 2.839 MiB/s 15 | html5lib to ElementTree: 0.695 MiB/s 16 | html5lib to lxml: 0.462 MiB/s 17 | 18 | -------------------------------------------------------------------------------- /benchmarks/results-pypy: -------------------------------------------------------------------------------- 1 | Python 2.7.10 (f3ad1e1e1d62, Sep 07 2015, 21:46:51) [PyPy 2.6.1 with GCC 5.2.0] 2 | rustc rustc 1.5.0-nightly (f0666b45d 2015-09-24) 3 | html5ever 0.2.5 4 | lxml (3, 4, 4, 0) 5 | libxml (2, 9, 2) 6 | htmllib 0.9999999 7 | 8 | HTML source SHA1: 6a2963fa1f15fe99884acdad8a895af4df8e8c01 9 | Best time of 3, parsing 5,598,887 bytes of HTML: 10 | 11 | html5ever to Rust RcDom: 16.822 MiB/s 12 | lxml.html: 24.181 MiB/s 13 | html5ever-python: 8.832 MiB/s 14 | html5ever-python to ElementTree: 7.825 MiB/s 15 | html5lib to ElementTree: 1.888 MiB/s 16 | html5lib to lxml: 0.249 MiB/s 17 | 18 | -------------------------------------------------------------------------------- /benchmarks/run.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import html5ever.elementtree 3 | import html5lib 4 | import lxml.html 5 | import os.path 6 | import re 7 | import subprocess 8 | import sys 9 | import timeit 10 | try: 11 | from urllib.request import urlopen # Python 3.x 12 | except ImportError: 13 | from urllib import urlopen 14 | 15 | 16 | def run(url, quick=False): 17 | html = urlopen(url).read() 18 | bytes = len(html) 19 | root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 20 | print('Python {}'.format(sys.version.replace('\n', ' '))) 21 | if not quick: 22 | print('rustc {}'.format(rustc_version())) 23 | print('html5ever {}'.format(html5ever_version(root))) 24 | print('lxml {}'.format(lxml.etree.LXML_VERSION)) 25 | print('libxml {}'.format(lxml.etree.LIBXML_COMPILED_VERSION)) 26 | print('htmllib {}'.format(html5lib.__version__)) 27 | print('') 28 | print('HTML source SHA1: {}'.format(hashlib.sha1(html).hexdigest())) 29 | print('Best time of 3, parsing {:,} bytes of HTML:'.format(bytes)) 30 | print('') 31 | sys.stdout.flush() 32 | bench_rust(bytes, root, html) 33 | bench_python(bytes, 'lxml.html', lambda: lxml.html.fromstring(html)) 34 | bench_python(bytes, 'html5ever-python', lambda: html5ever.parse(html)) 35 | bench_python(bytes, 'html5ever-python to ElementTree', 36 | lambda: html5ever.parse(html, tree_builder=html5ever.elementtree.TreeBuilder)) 37 | if not quick: 38 | bench_python(bytes, 'html5lib to ElementTree', lambda: html5lib.parse(html)) 39 | bench_python(bytes, 'html5lib to lxml', lambda: html5lib.parse(html, treebuilder='lxml')) 40 | print('') 41 | 42 | 43 | def rustc_version(): 44 | stdout, stderr = subprocess.Popen(['rustc', '--version'], stdout=subprocess.PIPE).communicate() 45 | return stdout.strip().decode('utf8') 46 | 47 | 48 | def html5ever_version(root): 49 | with open(os.path.join(root, 'rust-glue', 'Cargo.lock'), 'rb') as fd: 50 | return re.search(b'html5ever ([\d.]+)', fd.read()).group(1).decode('utf8') 51 | 52 | 53 | def bench_rust(bytes, root, html): 54 | subprocess.check_call([ 55 | 'cargo', 'test', '--no-run', '--release', '--manifest-path', 56 | os.path.join(root, 'rust-glue', 'Cargo.toml'), 57 | ]) 58 | stdout, _stderr = subprocess.Popen( 59 | [os.path.join(root, 'rust-glue', 'target', 'release', 'examples', 'time_parse_stdin')], 60 | stdin=subprocess.PIPE, 61 | stdout=subprocess.PIPE, 62 | ).communicate(html) 63 | bench(bytes, 'html5ever to Rust RcDom', float(stdout)) 64 | 65 | 66 | def bench_python(bytes, name, func): 67 | bench(bytes, name, min(timeit.repeat(func, number=1, repeat=3))) 68 | 69 | 70 | def bench(bytes, name, seconds): 71 | print('{}: {:.3f} MiB/s'.format(name, bytes / seconds / (1024. ** 2))) 72 | sys.stdout.flush() 73 | 74 | 75 | if __name__ == '__main__': 76 | quick = '--quick' in sys.argv 77 | if quick: 78 | sys.argv.remove('--quick') 79 | if len(sys.argv) > 1: 80 | url = sys.argv[1] 81 | else: 82 | url = 'https://raw.githubusercontent.com/whatwg/html/d8717d8831c276ca65d2d44bbf2ce4ce673997b9/source' 83 | run(url, quick) 84 | -------------------------------------------------------------------------------- /html5ever/__init__.py: -------------------------------------------------------------------------------- 1 | import os.path 2 | import sys 3 | import threading 4 | from ._ffi import ffi 5 | 6 | 7 | capi = ffi.dlopen(os.path.join(os.path.dirname(__file__), 'libhtml5ever_capi.so')) 8 | 9 | 10 | class DefaultTreeBuilder(object): 11 | def new_document(self): 12 | return Document() 13 | 14 | def new_element(self, namespace_url, local_name): 15 | return Element(namespace_url, local_name) 16 | 17 | def element_add_template_contents(self, element): 18 | element.template_contents = DocumentFragment() 19 | return element.template_contents 20 | 21 | def element_add_attribute_if_missing(self, element, namespace_url, local_name, value): 22 | element.attributes.setdefault((namespace_url, local_name), value) 23 | 24 | def new_comment(self, data): 25 | return Comment(data) 26 | 27 | def append_doctype_to_document(self, document, name, public_id, system_id): 28 | document.children.append(Doctype(name, public_id, system_id)) 29 | 30 | def append_node(self, parent, new_child): 31 | parent.children.append(new_child) 32 | new_child.parent = parent 33 | 34 | def append_text(self, parent, data): 35 | if parent.children and isinstance(parent.children[-1], Text): 36 | parent.children[-1].data += data 37 | else: 38 | child = Text(data) 39 | child.parent = parent 40 | parent.children.append(child) 41 | 42 | def insert_node_before_sibling(self, sibling, new_sibling): 43 | parent = sibling.parent 44 | if parent is None: 45 | return False 46 | position = parent.children.index(sibling) 47 | parent.children.insert(position, new_sibling) 48 | return True 49 | 50 | def insert_text_before_sibling(self, sibling, data): 51 | parent = sibling.parent 52 | if parent is None: 53 | return False 54 | position = parent.children.index(sibling) 55 | if position > 0 and isinstance(parent.children[position - 1], Text): 56 | parent.children[position - 1].data += data 57 | else: 58 | child = Text(data) 59 | child.parent = parent 60 | parent.children.insert(position, child) 61 | return True 62 | 63 | def reparent_children(self, parent, new_parent): 64 | for child in parent.children: 65 | child.parent = new_parent 66 | new_parent.children.extend(parent.children) 67 | parent.children = [] 68 | 69 | def remove_from_parent(self, node): 70 | if node.parent is not None: 71 | node.parent.children.remove(node) 72 | node.parent = None 73 | 74 | 75 | def parse(bytes, tree_builder=DefaultTreeBuilder): 76 | parser = Parser(tree_builder=tree_builder) 77 | parser.feed(bytes) 78 | return parser.end() 79 | 80 | def compose(func1, func2): 81 | def composed(arg): 82 | return func2(func1(arg)) 83 | return composed 84 | 85 | 86 | class Parser(object): 87 | def __init__(self, tree_builder=DefaultTreeBuilder): 88 | self.tree_builder = tree_builder() 89 | self._keep_alive_handles = [] 90 | self._template_contents_keep_alive_handles = {} 91 | self._document = self.tree_builder.new_document() 92 | self._ptr = ffi.gc( 93 | check_null(capi.new_parser( 94 | CALLBACKS, self._keep_alive(self), self._keep_alive(self._document))), 95 | compose(capi.destroy_parser, check_int)) 96 | 97 | def feed(self, bytes_chunk): 98 | data = ffi.new('char[]', bytes_chunk) 99 | slice_ = ffi.new('BytesSlice*', (data, len(bytes_chunk))) 100 | check_int(capi.feed_parser(self._ptr, slice_[0])) 101 | 102 | def end(self): 103 | check_int(capi.end_parser(self._ptr)) 104 | self._keep_alive_handles = None 105 | self._template_contents_keep_alive_handles = None 106 | self._ptr = None 107 | return self._document 108 | 109 | def _keep_alive(self, obj): 110 | ''' 111 | Keep the given object alive at least as long as the parser, 112 | and return a handle that can go through C / Rust as a `void *` pointer. 113 | 114 | For nodes, we could use a reference counting scheme here with the `clone_node_ref` 115 | and `destroy_node_ref` callbacks, but that would only help with nodes 116 | created by the parser that don't end up in the tree (to free them early), 117 | which is probably rare if it happens at all. 118 | ''' 119 | handle = ffi.new_handle(obj) 120 | self._keep_alive_handles.append(handle) 121 | return handle 122 | 123 | 124 | class Node(object): 125 | '''Abstract base class for all nodes in the tree.''' 126 | def __init__(self): 127 | self.parent = None 128 | self.children = [] 129 | 130 | 131 | class Document(Node): 132 | '''A document node, the root of the tree.''' 133 | 134 | 135 | class DocumentFragment(Node): 136 | '''A document fragement node.''' 137 | 138 | 139 | HTML_NAMESPACE = b'http://www.w3.org/1999/xhtml' 140 | MATHML_NAMESPACE = b'http://www.w3.org/1998/Math/MathML' 141 | SVG_NAMESPACE = b'http://www.w3.org/2000/svg' 142 | XLINK_NAMESPACE = b'http://www.w3.org/1999/xlink' 143 | XML_NAMESPACE = b'http://www.w3.org/XML/1998/namespace' 144 | XMLNS_NAMESPACE = b'http://www.w3.org/2000/xmlns/' 145 | 146 | 147 | class Element(Node): 148 | '''An element node.''' 149 | def __init__(self, namespace_url, local_name): 150 | self.parent = None 151 | self.children = [] 152 | self.name = (namespace_url, local_name) 153 | self.attributes = {} 154 | self.template_contents = None 155 | 156 | 157 | class Text(Node): 158 | '''A text node.''' 159 | def __init__(self, data): 160 | self.parent = None 161 | self.data = data 162 | 163 | 164 | class Comment(Node): 165 | '''A comment node.''' 166 | def __init__(self, data): 167 | self.parent = None 168 | self.data = data 169 | 170 | 171 | class Doctype(Node): 172 | '''A doctype node.''' 173 | def __init__(self, name, public_id, system_id): 174 | self.parent = None 175 | self.name = name 176 | self.public_id = public_id 177 | self.system_id = system_id 178 | 179 | 180 | def str_from_slice(slice_): 181 | return ffi.buffer(slice_.ptr, slice_.len)[:] 182 | 183 | 184 | CALLBACK_EXCPTION = threading.local() 185 | CALLBACK_EXCPTION.exception_data = None 186 | 187 | 188 | def onerror(exception, exc_value, traceback): 189 | CALLBACK_EXCPTION.exception_data = (exception, exc_value, traceback) 190 | 191 | 192 | if sys.version_info[0] >= 3: 193 | def raise_(exception, exc_value, traceback): 194 | if exc_value is not None: 195 | exception = exception(exc_value) 196 | if exception.__traceback__ is traceback: 197 | raise exception 198 | raise exception.with_traceback(traceback) 199 | else: 200 | exec(''' 201 | def raise_(exception, exc_value, traceback): 202 | raise exception, exc_value, traceback 203 | '''.strip()) 204 | 205 | 206 | # Keyword arguments in case this is called during interpreter shutdown when globals are gone. 207 | def check_callback_exception(CALLBACK_EXCPTION=CALLBACK_EXCPTION, raise_=raise_): 208 | exception_data = CALLBACK_EXCPTION.exception_data 209 | if exception_data is not None: 210 | CALLBACK_EXCPTION.exception_data = None 211 | raise_(*exception_data) 212 | 213 | 214 | @ffi.callback('Node*(ParserUserData*, Utf8Slice, Utf8Slice)', onerror=onerror) 215 | def create_element(parser, namespace_url, local_name): 216 | parser = ffi.from_handle(ffi.cast('void*', parser)) 217 | namespace_url = str_from_slice(namespace_url) 218 | local_name = str_from_slice(local_name) 219 | element = parser.tree_builder.new_element(namespace_url, local_name) 220 | if local_name == b'template' and namespace_url == HTML_NAMESPACE: 221 | parser._template_contents_keep_alive_handles[element] = \ 222 | ffi.new_handle(parser.tree_builder.element_add_template_contents(element)) 223 | return parser._keep_alive(element) 224 | 225 | 226 | @ffi.callback('Node*(ParserUserData*, Node*)', onerror=onerror) 227 | def get_template_contents(parser, element): 228 | parser = ffi.from_handle(ffi.cast('void*', parser)) 229 | element = ffi.from_handle(ffi.cast('void*', element)) 230 | return parser._template_contents_keep_alive_handles[element] 231 | 232 | 233 | @ffi.callback('int(ParserUserData*, Node*, Utf8Slice, Utf8Slice, Utf8Slice)', 234 | error=-1, onerror=onerror) 235 | def add_attribute_if_missing(parser, element, namespace_url, local_name, value): 236 | parser = ffi.from_handle(ffi.cast('void*', parser)) 237 | element = ffi.from_handle(ffi.cast('void*', element)) 238 | parser.tree_builder.element_add_attribute_if_missing( 239 | element, 240 | str_from_slice(namespace_url), 241 | str_from_slice(local_name), 242 | str_from_slice(value)) 243 | return 0 244 | 245 | 246 | @ffi.callback('Node*(ParserUserData*, Utf8Slice)', onerror=onerror) 247 | def create_comment(parser, data): 248 | parser = ffi.from_handle(ffi.cast('void*', parser)) 249 | return parser._keep_alive(parser.tree_builder.new_comment(str_from_slice(data))) 250 | 251 | 252 | @ffi.callback('int(ParserUserData*, uintptr_t, Utf8Slice, Utf8Slice, Utf8Slice)', 253 | error=-1, onerror=onerror) 254 | def append_doctype_to_document(parser, _dummy, name, public_id, system_id): 255 | parser = ffi.from_handle(ffi.cast('void*', parser)) 256 | parser.tree_builder.append_doctype_to_document( 257 | parser._document, 258 | str_from_slice(name), 259 | str_from_slice(public_id), 260 | str_from_slice(system_id)) 261 | return 0 262 | 263 | 264 | @ffi.callback('int(ParserUserData*, Node*, Node*)', error=-1, onerror=onerror) 265 | def append_node(parser, parent, child): 266 | parser = ffi.from_handle(ffi.cast('void*', parser)) 267 | parent = ffi.from_handle(ffi.cast('void*', parent)) 268 | child = ffi.from_handle(ffi.cast('void*', child)) 269 | parser.tree_builder.append_node(parent, child) 270 | return 0 271 | 272 | 273 | @ffi.callback('int(ParserUserData*, Node*, Utf8Slice)', error=-1, onerror=onerror) 274 | def append_text(parser, parent, data): 275 | parser = ffi.from_handle(ffi.cast('void*', parser)) 276 | parent = ffi.from_handle(ffi.cast('void*', parent)) 277 | parser.tree_builder.append_text(parent, str_from_slice(data)) 278 | return 0 279 | 280 | 281 | @ffi.callback('int(ParserUserData*, Node*, Node*)', error=-1, onerror=onerror) 282 | def insert_node_before_sibling(parser, sibling, new_sibling): 283 | parser = ffi.from_handle(ffi.cast('void*', parser)) 284 | sibling = ffi.from_handle(ffi.cast('void*', sibling)) 285 | new_sibling = ffi.from_handle(ffi.cast('void*', new_sibling)) 286 | return parser.tree_builder.insert_node_before_sibling(sibling, new_sibling) 287 | 288 | 289 | @ffi.callback('int(ParserUserData*, Node*, Utf8Slice)', error=-1, onerror=onerror) 290 | def insert_text_before_sibling(parser, sibling, data): 291 | parser = ffi.from_handle(ffi.cast('void*', parser)) 292 | sibling = ffi.from_handle(ffi.cast('void*', sibling)) 293 | return parser.tree_builder.insert_text_before_sibling(sibling, str_from_slice(data)) 294 | 295 | 296 | @ffi.callback('int(ParserUserData*, Node*, Node*)', error=-1, onerror=onerror) 297 | def reparent_children(parser, parent, new_parent): 298 | parser = ffi.from_handle(ffi.cast('void*', parser)) 299 | parent = ffi.from_handle(ffi.cast('void*', parent)) 300 | new_parent = ffi.from_handle(ffi.cast('void*', new_parent)) 301 | parser.tree_builder.reparent_children(parent, new_parent) 302 | return 0 303 | 304 | 305 | @ffi.callback('int(ParserUserData*, Node*)', error=-1, onerror=onerror) 306 | def remove_from_parent(parser, node): 307 | parser = ffi.from_handle(ffi.cast('void*', parser)) 308 | node = ffi.from_handle(ffi.cast('void*', node)) 309 | parser.tree_builder.remove_from_parent(node) 310 | return 0 311 | 312 | 313 | class RustPanic(Exception): 314 | '''Some Rust code panicked. This is a bug.''' 315 | 316 | 317 | # Keyword arguments in case this is called during interpreter shutdown when globals are gone. 318 | def check_null(pointer, check_callback_exception=check_callback_exception, RustPanic=RustPanic): 319 | check_callback_exception() 320 | if pointer == ffi.NULL: 321 | raise RustPanic() 322 | else: 323 | return pointer 324 | 325 | # Keyword arguments in case this is called during interpreter shutdown when globals are gone. 326 | def check_int(value, check_callback_exception=check_callback_exception, RustPanic=RustPanic): 327 | check_callback_exception() 328 | if value < 0: 329 | raise RustPanic() 330 | else: 331 | return value 332 | 333 | 334 | CALLBACKS = check_null(capi.declare_callbacks( 335 | ffi.NULL, ffi.NULL, ffi.NULL, ffi.NULL, 336 | create_element, get_template_contents, add_attribute_if_missing, 337 | create_comment, append_doctype_to_document, 338 | append_node, append_text, insert_node_before_sibling, insert_text_before_sibling, 339 | reparent_children, remove_from_parent)) 340 | -------------------------------------------------------------------------------- /html5ever/_build_ffi.py: -------------------------------------------------------------------------------- 1 | from cffi import FFI 2 | 3 | ffi = FFI() 4 | ffi.set_source('html5ever._ffi', None) 5 | ffi.cdef(''' 6 | 7 | typedef ... Callbacks; 8 | typedef ... ParserUserData; 9 | typedef ... Node; 10 | typedef ... Parser; 11 | 12 | typedef struct { 13 | uint8_t* ptr; 14 | uintptr_t len; 15 | } BytesSlice; 16 | 17 | typedef BytesSlice Utf8Slice; 18 | 19 | Callbacks* declare_callbacks( 20 | Node* (*clone_node_ref)(ParserUserData*, Node*), 21 | int (*destroy_node_ref)(ParserUserData*, Node*), 22 | int (*same_node)(ParserUserData*, Node*, Node*), 23 | int (*parse_error)(ParserUserData*, Utf8Slice), 24 | 25 | Node* (*create_element)(ParserUserData*, Utf8Slice, Utf8Slice), 26 | Node* (*get_template_contents)(ParserUserData*, Node*), 27 | int (*add_attribute_if_missing)(ParserUserData*, Node*, Utf8Slice, Utf8Slice, Utf8Slice), 28 | Node* (*create_comment)(ParserUserData*, Utf8Slice), 29 | int (*append_doctype_to_document)(ParserUserData*, uintptr_t, Utf8Slice, Utf8Slice, Utf8Slice), 30 | 31 | int (*append_node)(ParserUserData*, Node*, Node*), 32 | int (*append_text)(ParserUserData*, Node*, Utf8Slice), 33 | int (*insert_node_before_sibling)(ParserUserData*, Node*, Node*), 34 | int (*insert_text_before_sibling)(ParserUserData*, Node*, Utf8Slice), 35 | int (*reparent_children)(ParserUserData*, Node*, Node*), 36 | int (*remove_from_parent)(ParserUserData*, Node*) 37 | ); 38 | 39 | Parser* new_parser(Callbacks*, ParserUserData*, Node*); 40 | int destroy_parser(Parser*); 41 | int feed_parser(Parser*, BytesSlice); 42 | int end_parser(Parser*); 43 | 44 | ''') 45 | 46 | if __name__ == '__main__': 47 | ffi.compile() 48 | -------------------------------------------------------------------------------- /html5ever/elementtree.py: -------------------------------------------------------------------------------- 1 | import xml.etree.ElementTree as ET 2 | 3 | 4 | def qname(namespace_url, local_name): 5 | return '{%s}%s' % (namespace_url, local_name) if namespace_url else local_name 6 | 7 | 8 | class TreeBuilder(object): 9 | def __init__(self): 10 | self.parent_map = {} 11 | 12 | def new_document(self): 13 | return ET.ElementTree() 14 | 15 | def new_element(self, namespace_url, local_name): 16 | return ET.Element(qname(namespace_url, local_name)) 17 | 18 | def element_add_template_contents(self, element): 19 | # Store the template contents as children of the