pygments-sparql-generate 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pygments_sparql_generate-0.1.0/PKG-INFO +17 -0
- pygments_sparql_generate-0.1.0/pygments_sparql_generate/__init__.py +11 -0
- pygments_sparql_generate-0.1.0/pygments_sparql_generate/_lexicon.py +167 -0
- pygments_sparql_generate-0.1.0/pygments_sparql_generate/lexer.py +132 -0
- pygments_sparql_generate-0.1.0/pygments_sparql_generate.egg-info/PKG-INFO +17 -0
- pygments_sparql_generate-0.1.0/pygments_sparql_generate.egg-info/SOURCES.txt +11 -0
- pygments_sparql_generate-0.1.0/pygments_sparql_generate.egg-info/dependency_links.txt +1 -0
- pygments_sparql_generate-0.1.0/pygments_sparql_generate.egg-info/entry_points.txt +2 -0
- pygments_sparql_generate-0.1.0/pygments_sparql_generate.egg-info/requires.txt +4 -0
- pygments_sparql_generate-0.1.0/pygments_sparql_generate.egg-info/top_level.txt +1 -0
- pygments_sparql_generate-0.1.0/pyproject.toml +34 -0
- pygments_sparql_generate-0.1.0/setup.cfg +4 -0
- pygments_sparql_generate-0.1.0/tests/test_lexer.py +174 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pygments-sparql-generate
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Pygments lexer for SPARQL-Generate (.rqg): SPARQL 1.1 plus templates, iterators and sources.
|
|
5
|
+
Author: Maxime Lefrançois
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/sparql-generate/highlight-sparql-generate
|
|
8
|
+
Project-URL: Language, https://ci.mines-stetienne.fr/sparql-generate/
|
|
9
|
+
Keywords: pygments,lexer,sparql,sparql-generate,rdf,minted,syntax-highlighting
|
|
10
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Topic :: Text Processing :: Filters
|
|
13
|
+
Requires-Python: >=3.8
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
Requires-Dist: Pygments>=2.12
|
|
16
|
+
Provides-Extra: test
|
|
17
|
+
Requires-Dist: pytest; extra == "test"
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Pygments lexer for SPARQL-Generate (``.rqg``).
|
|
2
|
+
|
|
3
|
+
Installed, it registers the alias ``sparql-generate`` with Pygments (entry
|
|
4
|
+
point ``pygments.lexers``), so ``pygmentize -l sparql-generate``, LaTeX
|
|
5
|
+
minted, MkDocs and Sphinx find it by name.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .lexer import SparqlGenerateLexer
|
|
9
|
+
|
|
10
|
+
__all__ = ["SparqlGenerateLexer"]
|
|
11
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""The SPARQL-Generate lexicon, for the Pygments lexer.
|
|
2
|
+
|
|
3
|
+
GENERATED by `npm run generate` from src/lexicon.js of
|
|
4
|
+
highlight-sparql-generate. Do not edit: edit src/lexicon.js and regenerate.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
SPARQL_KEYWORDS = [
|
|
8
|
+
"base",
|
|
9
|
+
"prefix",
|
|
10
|
+
"select",
|
|
11
|
+
"distinct",
|
|
12
|
+
"reduced",
|
|
13
|
+
"construct",
|
|
14
|
+
"describe",
|
|
15
|
+
"ask",
|
|
16
|
+
"from",
|
|
17
|
+
"named",
|
|
18
|
+
"where",
|
|
19
|
+
"order",
|
|
20
|
+
"by",
|
|
21
|
+
"asc",
|
|
22
|
+
"desc",
|
|
23
|
+
"limit",
|
|
24
|
+
"offset",
|
|
25
|
+
"values",
|
|
26
|
+
"undef",
|
|
27
|
+
"graph",
|
|
28
|
+
"optional",
|
|
29
|
+
"union",
|
|
30
|
+
"minus",
|
|
31
|
+
"bind",
|
|
32
|
+
"service",
|
|
33
|
+
"silent",
|
|
34
|
+
"filter",
|
|
35
|
+
"exists",
|
|
36
|
+
"not",
|
|
37
|
+
"in",
|
|
38
|
+
"as",
|
|
39
|
+
"group",
|
|
40
|
+
"having",
|
|
41
|
+
"separator",
|
|
42
|
+
"load",
|
|
43
|
+
"clear",
|
|
44
|
+
"drop",
|
|
45
|
+
"create",
|
|
46
|
+
"add",
|
|
47
|
+
"move",
|
|
48
|
+
"copy",
|
|
49
|
+
"insert",
|
|
50
|
+
"delete",
|
|
51
|
+
"data",
|
|
52
|
+
"with",
|
|
53
|
+
"using",
|
|
54
|
+
"into",
|
|
55
|
+
"to",
|
|
56
|
+
"default",
|
|
57
|
+
"all",
|
|
58
|
+
]
|
|
59
|
+
|
|
60
|
+
SPARQL_BUILTINS = [
|
|
61
|
+
"str",
|
|
62
|
+
"lang",
|
|
63
|
+
"langmatches",
|
|
64
|
+
"datatype",
|
|
65
|
+
"bound",
|
|
66
|
+
"iri",
|
|
67
|
+
"uri",
|
|
68
|
+
"bnode",
|
|
69
|
+
"rand",
|
|
70
|
+
"abs",
|
|
71
|
+
"ceil",
|
|
72
|
+
"floor",
|
|
73
|
+
"round",
|
|
74
|
+
"concat",
|
|
75
|
+
"strlen",
|
|
76
|
+
"ucase",
|
|
77
|
+
"lcase",
|
|
78
|
+
"encode_for_uri",
|
|
79
|
+
"contains",
|
|
80
|
+
"strstarts",
|
|
81
|
+
"strends",
|
|
82
|
+
"strbefore",
|
|
83
|
+
"strafter",
|
|
84
|
+
"year",
|
|
85
|
+
"month",
|
|
86
|
+
"day",
|
|
87
|
+
"hours",
|
|
88
|
+
"minutes",
|
|
89
|
+
"seconds",
|
|
90
|
+
"timezone",
|
|
91
|
+
"tz",
|
|
92
|
+
"now",
|
|
93
|
+
"uuid",
|
|
94
|
+
"struuid",
|
|
95
|
+
"md5",
|
|
96
|
+
"sha1",
|
|
97
|
+
"sha224",
|
|
98
|
+
"sha256",
|
|
99
|
+
"sha384",
|
|
100
|
+
"sha512",
|
|
101
|
+
"coalesce",
|
|
102
|
+
"if",
|
|
103
|
+
"strlang",
|
|
104
|
+
"strdt",
|
|
105
|
+
"sameterm",
|
|
106
|
+
"isiri",
|
|
107
|
+
"isuri",
|
|
108
|
+
"isblank",
|
|
109
|
+
"isliteral",
|
|
110
|
+
"isnumeric",
|
|
111
|
+
"regex",
|
|
112
|
+
"substr",
|
|
113
|
+
"replace",
|
|
114
|
+
"count",
|
|
115
|
+
"sum",
|
|
116
|
+
"min",
|
|
117
|
+
"max",
|
|
118
|
+
"avg",
|
|
119
|
+
"sample",
|
|
120
|
+
"group_concat",
|
|
121
|
+
]
|
|
122
|
+
|
|
123
|
+
GENERATE_KEYWORDS = [
|
|
124
|
+
"generate",
|
|
125
|
+
"template",
|
|
126
|
+
"perform",
|
|
127
|
+
"function",
|
|
128
|
+
"iterator",
|
|
129
|
+
"source",
|
|
130
|
+
"accept",
|
|
131
|
+
"box",
|
|
132
|
+
"format",
|
|
133
|
+
"before",
|
|
134
|
+
"after",
|
|
135
|
+
"list",
|
|
136
|
+
"expressions",
|
|
137
|
+
"pragma",
|
|
138
|
+
]
|
|
139
|
+
|
|
140
|
+
REUSED_KEYWORDS = [
|
|
141
|
+
"group",
|
|
142
|
+
]
|
|
143
|
+
|
|
144
|
+
LIBRARY_PREFIXES = [
|
|
145
|
+
"fun",
|
|
146
|
+
"iter",
|
|
147
|
+
]
|
|
148
|
+
|
|
149
|
+
# Final regular-expression sources (Python `re` syntax).
|
|
150
|
+
P = {
|
|
151
|
+
"generateKeywords": "(?<![\\w?$:.\\-])(?:generate|template|perform|function|iterator|source|accept|box|format|before|after|list|expressions|pragma)(?![\\w\\-:])",
|
|
152
|
+
"reusedKeywords": "(?<![\\w?$:.\\-])(?:group)(?![\\w\\-:])",
|
|
153
|
+
"libraryName": "(?<![\\w?$:.\\-])(?:fun|iter):[A-Za-z_](?:[\\w.\\-]*[\\w\\-])?",
|
|
154
|
+
"xexprOpen": "[?$]\\{",
|
|
155
|
+
"iriChar": "[^<>\"{}|^`\\\\\\x00-\\x20]",
|
|
156
|
+
"xiriStart": "<(?=[^<>\"{}|^`\\\\\\x00-\\x20]*\\{)",
|
|
157
|
+
"echar": "\\\\[tbnrf\"'\\\\{}]",
|
|
158
|
+
"interpFlat": "\\{(?:[^{}\"'\\n]|\"(?:[^\"\\\\\\n]|\\\\.)*\"|'(?:[^'\\\\\\n]|\\\\.)*'|\\{(?:[^{}\"'\\n]|\"(?:[^\"\\\\\\n]|\\\\.)*\"|'(?:[^'\\\\\\n]|\\\\.)*')*\\})*\\}",
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
ROLES = {
|
|
162
|
+
"keyword.generate": "a SPARQL-Generate keyword",
|
|
163
|
+
"function.library": "a fun: or iter: function name",
|
|
164
|
+
"interp.punct": "the braces of an embedded expression, and ?{ / ${",
|
|
165
|
+
"string": "the literal part of a string with embedded expressions",
|
|
166
|
+
"iri": "the literal part of an IRI with embedded expressions",
|
|
167
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Pygments lexer for SPARQL-Generate.
|
|
2
|
+
|
|
3
|
+
SPARQL-Generate is SPARQL 1.1 plus a closed set of additions. This lexer is
|
|
4
|
+
Pygments' own ``SparqlLexer`` with only those additions layered on top, so a
|
|
5
|
+
plain SPARQL 1.1 query gets exactly the tokens ``SparqlLexer`` gives it (the
|
|
6
|
+
parity test of ``tests/test_lexer.py``), except for the one known defect of
|
|
7
|
+
the base lexer listed there.
|
|
8
|
+
|
|
9
|
+
The additions come from ``_lexicon.py``, generated from ``src/lexicon.js`` of
|
|
10
|
+
the highlight-sparql-generate repository: the lexicon is written once, for
|
|
11
|
+
every engine.
|
|
12
|
+
|
|
13
|
+
- the keywords of SPARQL-Generate (``GENERATE``, ``TEMPLATE``, ``ITERATOR``,
|
|
14
|
+
``SOURCE`` ... ``ACCEPT``, ``BOX``, ``FORMAT`` ...), and ``GROUP`` alone (a
|
|
15
|
+
template group), which SPARQL only knows in ``GROUP BY``;
|
|
16
|
+
- expression nodes ``?{ expr }`` and ``${ expr }``;
|
|
17
|
+
- expressions embedded in IRIs (``<http://ex/{?id}>``) and in string
|
|
18
|
+
literals (``"Hello {?name}"``), in all four quote styles. ``\\{`` and
|
|
19
|
+
``\\}`` keep a literal brace;
|
|
20
|
+
- the library functions and iterators, by their conventional prefixes
|
|
21
|
+
``fun:`` and ``iter:``.
|
|
22
|
+
|
|
23
|
+
Usage::
|
|
24
|
+
|
|
25
|
+
pygmentize -l sparql-generate query.rqg
|
|
26
|
+
\\begin{minted}{sparql-generate} ... \\end{minted} % LaTeX
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
import copy
|
|
30
|
+
import re
|
|
31
|
+
|
|
32
|
+
from pygments.lexer import default, include
|
|
33
|
+
from pygments.lexers.rdf import SparqlLexer
|
|
34
|
+
from pygments.token import Keyword, Name, Punctuation, String
|
|
35
|
+
|
|
36
|
+
from . import _lexicon as L
|
|
37
|
+
|
|
38
|
+
__all__ = ["SparqlGenerateLexer"]
|
|
39
|
+
|
|
40
|
+
# The interpolation delimiters: `{` `}` inside an IRI or a string, and the
|
|
41
|
+
# `?{` / `${` ... `}` of an expression node.
|
|
42
|
+
INTERPOL = String.Interpol
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _ci(source):
|
|
46
|
+
"""A case-insensitive pattern, the Pygments way (a leading flag)."""
|
|
47
|
+
return "(?i)" + source
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _string_states(base):
|
|
51
|
+
"""The four string states of SparqlLexer, taught to stop at ``{``.
|
|
52
|
+
|
|
53
|
+
Short strings: the content rule of the base, with ``{`` added to its
|
|
54
|
+
negated class, and an interpolation rule in front. Long strings: the base
|
|
55
|
+
content rule ``[^\\\\]+`` runs past the closing quotes to the end of the
|
|
56
|
+
input (a defect of SparqlLexer, see the parity test), so the content rule
|
|
57
|
+
is rewritten to stop at the closing quotes as well as at ``{``.
|
|
58
|
+
"""
|
|
59
|
+
long_content = {
|
|
60
|
+
"triple-double-quoted-string": r'(?:[^\\"{]|"(?!""))+',
|
|
61
|
+
"triple-single-quoted-string": r"(?:[^\\'{]|'(?!''))+",
|
|
62
|
+
}
|
|
63
|
+
states = {}
|
|
64
|
+
for name in ("single-double-quoted-string", "single-single-quoted-string",
|
|
65
|
+
"triple-double-quoted-string", "triple-single-quoted-string"):
|
|
66
|
+
rules = []
|
|
67
|
+
for rule in base[name]:
|
|
68
|
+
regex = rule[0]
|
|
69
|
+
if name in long_content and regex == r"[^\\]+":
|
|
70
|
+
rule = (long_content[name],) + tuple(rule[1:])
|
|
71
|
+
elif isinstance(regex, str) and regex.startswith("[^") and regex.endswith("]+"):
|
|
72
|
+
rule = ("[^{" + regex[2:],) + tuple(rule[1:])
|
|
73
|
+
rules.append(rule)
|
|
74
|
+
states[name] = [(r"\{", INTERPOL, "sg-expression")] + rules
|
|
75
|
+
return states
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _tokens():
|
|
79
|
+
base = copy.deepcopy(SparqlLexer.tokens)
|
|
80
|
+
root = base["root"]
|
|
81
|
+
# Insert the additions just after the base keyword rule (index 1, after
|
|
82
|
+
# whitespace): the base keeps the words it knows (`group\s+by` stays one
|
|
83
|
+
# SPARQL token), ours only ever match where the base has no rule.
|
|
84
|
+
head, tail = root[:2], root[2:]
|
|
85
|
+
additions = [
|
|
86
|
+
(_ci(L.P["generateKeywords"]), Keyword),
|
|
87
|
+
(_ci(L.P["reusedKeywords"]), Keyword),
|
|
88
|
+
(L.P["libraryName"], Name.Function),
|
|
89
|
+
(L.P["xexprOpen"], INTERPOL, "sg-expression"),
|
|
90
|
+
(L.P["xiriStart"], Name.Label, "sg-iri"),
|
|
91
|
+
]
|
|
92
|
+
base["root"] = head + additions + tail
|
|
93
|
+
base.update(_string_states(base))
|
|
94
|
+
base["sg-expression"] = [
|
|
95
|
+
(r"\}", INTERPOL, "#pop"),
|
|
96
|
+
(r"\{", Punctuation, "sg-group"),
|
|
97
|
+
include("root"),
|
|
98
|
+
]
|
|
99
|
+
# A group inside an expression: `{ IF(EXISTS { ?s ?p ?o }, 1, 0) }`.
|
|
100
|
+
base["sg-group"] = [
|
|
101
|
+
(r"\}", Punctuation, "#pop"),
|
|
102
|
+
(r"\{", Punctuation, "#push"),
|
|
103
|
+
include("root"),
|
|
104
|
+
]
|
|
105
|
+
base["sg-iri"] = [
|
|
106
|
+
(L.P["iriChar"] + "+", Name.Label),
|
|
107
|
+
(r"\{", INTERPOL, "sg-expression"),
|
|
108
|
+
(r">", Name.Label, "#pop"),
|
|
109
|
+
default("#pop"),
|
|
110
|
+
]
|
|
111
|
+
return base
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class SparqlGenerateLexer(SparqlLexer):
|
|
115
|
+
"""Lexer for SPARQL-Generate queries (``.rqg``)."""
|
|
116
|
+
|
|
117
|
+
name = "SPARQL-Generate"
|
|
118
|
+
aliases = ["sparql-generate", "sparqlgenerate", "rqg"]
|
|
119
|
+
filenames = ["*.rqg"]
|
|
120
|
+
mimetypes = ["application/vnd.sparql-generate"]
|
|
121
|
+
url = "https://ci.mines-stetienne.fr/sparql-generate/"
|
|
122
|
+
version_added = ""
|
|
123
|
+
|
|
124
|
+
tokens = _tokens()
|
|
125
|
+
|
|
126
|
+
def analyse_text(text):
|
|
127
|
+
"""A query that uses a SPARQL-Generate form is ours, not SPARQL's."""
|
|
128
|
+
if re.search(r"(?im)^\s*(GENERATE|TEMPLATE|PERFORM|FUNCTION)\b", text):
|
|
129
|
+
return 0.6
|
|
130
|
+
if re.search(r"(?i)\b(ITERATOR|SOURCE)\s+[?$<\w]", text):
|
|
131
|
+
return 0.4
|
|
132
|
+
return 0.0
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pygments-sparql-generate
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Pygments lexer for SPARQL-Generate (.rqg): SPARQL 1.1 plus templates, iterators and sources.
|
|
5
|
+
Author: Maxime Lefrançois
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/sparql-generate/highlight-sparql-generate
|
|
8
|
+
Project-URL: Language, https://ci.mines-stetienne.fr/sparql-generate/
|
|
9
|
+
Keywords: pygments,lexer,sparql,sparql-generate,rdf,minted,syntax-highlighting
|
|
10
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Topic :: Text Processing :: Filters
|
|
13
|
+
Requires-Python: >=3.8
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
Requires-Dist: Pygments>=2.12
|
|
16
|
+
Provides-Extra: test
|
|
17
|
+
Requires-Dist: pytest; extra == "test"
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
pyproject.toml
|
|
2
|
+
pygments_sparql_generate/__init__.py
|
|
3
|
+
pygments_sparql_generate/_lexicon.py
|
|
4
|
+
pygments_sparql_generate/lexer.py
|
|
5
|
+
pygments_sparql_generate.egg-info/PKG-INFO
|
|
6
|
+
pygments_sparql_generate.egg-info/SOURCES.txt
|
|
7
|
+
pygments_sparql_generate.egg-info/dependency_links.txt
|
|
8
|
+
pygments_sparql_generate.egg-info/entry_points.txt
|
|
9
|
+
pygments_sparql_generate.egg-info/requires.txt
|
|
10
|
+
pygments_sparql_generate.egg-info/top_level.txt
|
|
11
|
+
tests/test_lexer.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pygments_sparql_generate
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pygments-sparql-generate"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Pygments lexer for SPARQL-Generate (.rqg): SPARQL 1.1 plus templates, iterators and sources."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "Apache-2.0" }
|
|
11
|
+
authors = [{ name = "Maxime Lefrançois" }]
|
|
12
|
+
requires-python = ">=3.8"
|
|
13
|
+
dependencies = ["Pygments>=2.12"]
|
|
14
|
+
keywords = ["pygments", "lexer", "sparql", "sparql-generate", "rdf", "minted", "syntax-highlighting"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"License :: OSI Approved :: Apache Software License",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Topic :: Text Processing :: Filters",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://github.com/sparql-generate/highlight-sparql-generate"
|
|
23
|
+
Language = "https://ci.mines-stetienne.fr/sparql-generate/"
|
|
24
|
+
|
|
25
|
+
# `pygmentize -l sparql-generate`, minted's \begin{minted}{sparql-generate},
|
|
26
|
+
# MkDocs (pymdownx.highlight) and Sphinx all find the lexer through this.
|
|
27
|
+
[project.entry-points."pygments.lexers"]
|
|
28
|
+
sparql-generate = "pygments_sparql_generate.lexer:SparqlGenerateLexer"
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
test = ["pytest"]
|
|
32
|
+
|
|
33
|
+
[tool.setuptools]
|
|
34
|
+
packages = ["pygments_sparql_generate"]
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Tests of the Pygments lexer for SPARQL-Generate (``pytest``).
|
|
2
|
+
|
|
3
|
+
1. DRIFT — ``_lexicon.py`` is the output of ``npm run generate`` (skipped
|
|
4
|
+
when Node.js is not installed).
|
|
5
|
+
2. PARITY — a plain SPARQL 1.1 query gets exactly the tokens of Pygments'
|
|
6
|
+
own ``SparqlLexer``, character for character, apart from the named
|
|
7
|
+
divergences below, each of which must still be observed.
|
|
8
|
+
3. GOLDEN — the tokens of every SPARQL-Generate fixture, frozen
|
|
9
|
+
(``UPDATE_GOLDEN=1 pytest`` regenerates them).
|
|
10
|
+
4. NO ERROR TOKEN on any fixture: every construct is recognised.
|
|
11
|
+
5. REGISTRATION — ``sparql-generate`` and ``*.rqg`` reach the lexer through
|
|
12
|
+
the Pygments plugin entry point (needs the package installed).
|
|
13
|
+
6. PATTERNS — every pattern of the lexicon compiles under Python `re`.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import pathlib
|
|
18
|
+
import re
|
|
19
|
+
import shutil
|
|
20
|
+
import subprocess
|
|
21
|
+
|
|
22
|
+
import pytest
|
|
23
|
+
from pygments.lexers import SparqlLexer
|
|
24
|
+
from pygments.token import Error
|
|
25
|
+
|
|
26
|
+
from pygments_sparql_generate import SparqlGenerateLexer
|
|
27
|
+
|
|
28
|
+
HERE = pathlib.Path(__file__).resolve().parent
|
|
29
|
+
REPO = HERE.parent.parent
|
|
30
|
+
FIX = REPO / "test" / "fixtures"
|
|
31
|
+
GOLDEN = REPO / "test" / "golden"
|
|
32
|
+
PURE = sorted((FIX / "pure").glob("*.rq"))
|
|
33
|
+
CONSTRUCTS = sorted(FIX.glob("*.rqg"))
|
|
34
|
+
|
|
35
|
+
# Known divergences from SparqlLexer on plain SPARQL, by fixture: a regular
|
|
36
|
+
# expression whose first match starts the exempt region (to the end of the
|
|
37
|
+
# file). Each must be OBSERVED — if SparqlLexer is fixed, the test says so,
|
|
38
|
+
# so that the exemption is removed.
|
|
39
|
+
DIVERGENCES = {
|
|
40
|
+
# SparqlLexer's triple-quoted strings use `[^\\]+` as content rule: the
|
|
41
|
+
# first long string runs to the next backslash or to the end of the
|
|
42
|
+
# input, closing quotes included. This lexer stops at the closing quotes.
|
|
43
|
+
"long-strings.rq": r'"""|\'\'\'',
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def char_types(lexer, text):
|
|
48
|
+
out = []
|
|
49
|
+
for ttype, value in lexer.get_tokens(text):
|
|
50
|
+
out.extend([ttype] * len(value))
|
|
51
|
+
return out
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def read(path):
|
|
55
|
+
# Pygments appends a final newline when the input lacks one; the
|
|
56
|
+
# fixtures all end with one, so offsets match the file.
|
|
57
|
+
text = path.read_text(encoding="utf-8")
|
|
58
|
+
assert text.endswith("\n"), f"{path.name} must end with a newline"
|
|
59
|
+
return text
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def golden_text(name, text, types):
|
|
63
|
+
lines = [f"# {name}"]
|
|
64
|
+
prev = None
|
|
65
|
+
for i, (ch, t) in enumerate(zip(text, types)):
|
|
66
|
+
label = str(t).replace("Token.", "") if t is not None else "-"
|
|
67
|
+
if label != prev:
|
|
68
|
+
lines.append(f"{i} {_json_char(ch)} {label}")
|
|
69
|
+
prev = label
|
|
70
|
+
return "\n".join(lines) + "\n"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def golden_name(path):
|
|
74
|
+
"""`pure/select.rq` -> `pure.select.rq`: the same name as in test/run.js."""
|
|
75
|
+
return ".".join(path.relative_to(FIX).parts)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _json_char(ch):
|
|
79
|
+
# The same quoting as JSON.stringify in the JavaScript goldens.
|
|
80
|
+
import json
|
|
81
|
+
return json.dumps(ch, ensure_ascii=False)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
# ------------------------------------------------------------------ 1. drift
|
|
85
|
+
|
|
86
|
+
def test_lexicon_is_generated():
|
|
87
|
+
node = shutil.which("node")
|
|
88
|
+
if not node:
|
|
89
|
+
pytest.skip("Node.js not found: cannot regenerate _lexicon.py")
|
|
90
|
+
script = ("process.stdout.write(require('./src/python-lexicon')"
|
|
91
|
+
".pythonLexicon())")
|
|
92
|
+
fresh = subprocess.run([node, "-e", script], cwd=REPO, check=True,
|
|
93
|
+
capture_output=True, text=True).stdout
|
|
94
|
+
current = (REPO / "pygments-sparql-generate" / "pygments_sparql_generate"
|
|
95
|
+
/ "_lexicon.py").read_text(encoding="utf-8")
|
|
96
|
+
assert current == fresh, "_lexicon.py is stale: run `npm run generate`"
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# ----------------------------------------------------------------- 2. parity
|
|
100
|
+
|
|
101
|
+
@pytest.mark.parametrize("path", PURE, ids=lambda p: p.name)
|
|
102
|
+
def test_parity_with_sparql_lexer(path):
|
|
103
|
+
text = read(path)
|
|
104
|
+
base = char_types(SparqlLexer(), text)
|
|
105
|
+
ours = char_types(SparqlGenerateLexer(), text)
|
|
106
|
+
assert len(base) == len(ours) == len(text)
|
|
107
|
+
limit = len(text)
|
|
108
|
+
if path.name in DIVERGENCES:
|
|
109
|
+
m = re.search(DIVERGENCES[path.name], text)
|
|
110
|
+
assert m, f"{path.name}: the divergence pattern no longer matches"
|
|
111
|
+
limit = m.start()
|
|
112
|
+
assert base[limit:] != ours[limit:], (
|
|
113
|
+
f"{path.name}: SparqlLexer no longer diverges here — "
|
|
114
|
+
"remove the exemption from DIVERGENCES")
|
|
115
|
+
for i in range(limit):
|
|
116
|
+
if base[i] != ours[i]:
|
|
117
|
+
line = text.count("\n", 0, i) + 1
|
|
118
|
+
pytest.fail(f"{path.name}, line {line}: {text[i:i + 16]!r} "
|
|
119
|
+
f"sparql={base[i]} sparql-generate={ours[i]}")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# ----------------------------------------------------------------- 3. golden
|
|
123
|
+
|
|
124
|
+
@pytest.mark.parametrize("path", CONSTRUCTS + PURE, ids=lambda p: p.name)
|
|
125
|
+
def test_golden(path):
|
|
126
|
+
text = read(path)
|
|
127
|
+
fresh = golden_text("Pygments", text, char_types(SparqlGenerateLexer(), text))
|
|
128
|
+
golden = GOLDEN / (golden_name(path) + ".pygments.txt")
|
|
129
|
+
if os.environ.get("UPDATE_GOLDEN"):
|
|
130
|
+
golden.write_text(fresh, encoding="utf-8")
|
|
131
|
+
return
|
|
132
|
+
assert golden.exists(), f"{golden.name} missing: UPDATE_GOLDEN=1 pytest"
|
|
133
|
+
old = golden.read_text(encoding="utf-8")
|
|
134
|
+
if old != fresh:
|
|
135
|
+
a, b = old.split("\n"), fresh.split("\n")
|
|
136
|
+
i = next(n for n in range(min(len(a), len(b))) if a[n] != b[n])
|
|
137
|
+
pytest.fail(f"golden {golden.name}, first difference:\n"
|
|
138
|
+
f" expected: {a[i]}\n got: {b[i]}")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
# ---------------------------------------------------------- 4. no Error token
|
|
142
|
+
|
|
143
|
+
@pytest.mark.parametrize("path", CONSTRUCTS + PURE, ids=lambda p: p.name)
|
|
144
|
+
def test_no_error_token(path):
|
|
145
|
+
text = read(path)
|
|
146
|
+
for ttype, value in SparqlGenerateLexer().get_tokens(text):
|
|
147
|
+
assert ttype is not Error and ttype not in Error, (
|
|
148
|
+
f"{path.name}: Error token {value!r}")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
# ----------------------------------------------------------- 5. registration
|
|
152
|
+
|
|
153
|
+
def test_registered_with_pygments():
|
|
154
|
+
from pygments.lexers import get_lexer_by_name, get_lexer_for_filename
|
|
155
|
+
from pygments.util import ClassNotFound
|
|
156
|
+
try:
|
|
157
|
+
by_name = get_lexer_by_name("sparql-generate")
|
|
158
|
+
except ClassNotFound:
|
|
159
|
+
pytest.skip("package not installed (pip install -e pygments-sparql-generate)")
|
|
160
|
+
assert isinstance(by_name, SparqlGenerateLexer)
|
|
161
|
+
assert isinstance(get_lexer_for_filename("query.rqg"), SparqlGenerateLexer)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def test_guess_prefers_sparql_generate():
|
|
165
|
+
from pygments.lexers import guess_lexer
|
|
166
|
+
text = read(FIX / "generate.rqg")
|
|
167
|
+
assert isinstance(guess_lexer(text), SparqlGenerateLexer)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def test_patterns_compile_under_python_re():
|
|
171
|
+
from pygments_sparql_generate import _lexicon as L
|
|
172
|
+
for name, source in L.P.items():
|
|
173
|
+
re.compile(source)
|
|
174
|
+
re.compile("(?i)" + source)
|