gleplot 6.0.0__py3-none-any.whl
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.
- gleplot/__init__.py +772 -0
- gleplot/_warn.py +45 -0
- gleplot/axes.py +10714 -0
- gleplot/cairo_support.py +232 -0
- gleplot/colors.py +721 -0
- gleplot/compiler.py +863 -0
- gleplot/config.py +491 -0
- gleplot/dataio.py +1403 -0
- gleplot/figure.py +5789 -0
- gleplot/guides.py +172 -0
- gleplot/markers.py +424 -0
- gleplot/mathtext.py +679 -0
- gleplot/palettes.py +243 -0
- gleplot/parser/__init__.py +83 -0
- gleplot/parser/expr.py +196 -0
- gleplot/parser/lexer.py +289 -0
- gleplot/parser/metadata.py +374 -0
- gleplot/parser/recognizer.py +12654 -0
- gleplot/parser/report.py +74 -0
- gleplot/parser/syntax.py +756 -0
- gleplot/parser/tables.py +484 -0
- gleplot/parser/units.py +196 -0
- gleplot/py.typed +0 -0
- gleplot/series.py +1609 -0
- gleplot/sources.py +623 -0
- gleplot/writer.py +7215 -0
- gleplot-6.0.0.dist-info/METADATA +138 -0
- gleplot-6.0.0.dist-info/RECORD +31 -0
- gleplot-6.0.0.dist-info/WHEEL +5 -0
- gleplot-6.0.0.dist-info/licenses/LICENSE +25 -0
- gleplot-6.0.0.dist-info/top_level.txt +1 -0
gleplot/parser/lexer.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
"""Tokenizer for a single physical line of GLE source.
|
|
2
|
+
|
|
3
|
+
This is a *tolerant* lexer: it never raises on malformed input. When it
|
|
4
|
+
encounters something it cannot classify cleanly (for example an unterminated
|
|
5
|
+
double-quoted string), it emits a best-effort token and records the situation
|
|
6
|
+
via the token type / an ``error`` flag rather than aborting. The point of the
|
|
7
|
+
whole parser stack is byte-exact round-tripping of arbitrary ``.gle`` text, so
|
|
8
|
+
the lexer must degrade gracefully on anything a human might have typed.
|
|
9
|
+
|
|
10
|
+
Lexical contract (verified against GLE 4.3.10 ``token.cpp`` / ``pass.cpp``):
|
|
11
|
+
|
|
12
|
+
* ``!`` begins a comment that runs to end of line, *except* inside a
|
|
13
|
+
double-quoted string. The comment text (including the ``!``) is preserved
|
|
14
|
+
verbatim as a ``COMMENT`` token.
|
|
15
|
+
* Strings are double-quoted. GLE 4.3.10 embeds a quote by doubling it
|
|
16
|
+
(a label 5" is written with the quote character twice); a backslash is
|
|
17
|
+
an ordinary character, so ``"a\\"`` is a whole string. Single-quoted
|
|
18
|
+
strings are tolerated on input (kept verbatim, quote char recorded) but this
|
|
19
|
+
layer never rewrites them.
|
|
20
|
+
* Whitespace is insignificant to structure but every token carries a span into
|
|
21
|
+
the original line so the raw text is always reconstructable.
|
|
22
|
+
* Numbers follow ``float()`` semantics: ``1``, ``1.5``, ``.5``, ``5.``,
|
|
23
|
+
``1e-3``, with an optional leading sign -- but only when the numeric
|
|
24
|
+
literal is immediately followed by a terminator or end-of-line. A digit
|
|
25
|
+
run glued directly to further word characters (no terminator in between)
|
|
26
|
+
is a bareword, not a number followed by a word: ``20_main.dat`` is a
|
|
27
|
+
single ``WORD`` token (not ``NUMBER '20'`` + ``WORD '_main.dat'``),
|
|
28
|
+
``5.dat`` is ``WORD '5.dat'``, ``1e5abc`` is ``WORD '1e5abc'``. This
|
|
29
|
+
matters for unquoted data filenames, which are the only place valid GLE
|
|
30
|
+
glues digits directly onto identifier characters. ``20,30`` still lexes
|
|
31
|
+
as ``NUMBER OP NUMBER``, ``20!c`` as ``NUMBER COMMENT``, ``2(x)`` as
|
|
32
|
+
``NUMBER OP ...``, ``20"s"`` as ``NUMBER STRING``, and ``10%`` as
|
|
33
|
+
``NUMBER WORD('%')`` -- ``,``, ``!``, ``(``, and ``"`` are ordinary word
|
|
34
|
+
terminators, and ``%`` additionally stops the digit-merge (without being a
|
|
35
|
+
general bareword terminator), so those cases are unaffected. This keeps a
|
|
36
|
+
percentage error like ``err 10%`` lexing with a standalone ``'%'`` token,
|
|
37
|
+
which the recognizer's error-value parsing looks for by value.
|
|
38
|
+
* Operators recognised as ``OP``: ``= , ( ) * / + - ^``.
|
|
39
|
+
|
|
40
|
+
The lexer does **not** split on ``;`` -- statement splitting is the concern of
|
|
41
|
+
:mod:`gleplot.parser.syntax`, which needs quote-aware splitting and does it
|
|
42
|
+
itself. The lexer treats ``;`` as an ``OP`` token so a caller tokenising a full
|
|
43
|
+
line still sees it.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
from __future__ import annotations
|
|
47
|
+
|
|
48
|
+
from dataclasses import dataclass
|
|
49
|
+
from enum import Enum
|
|
50
|
+
from typing import List, Optional
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class TokenType(Enum):
|
|
54
|
+
"""Kinds of lexical token produced by :func:`tokenize_line`."""
|
|
55
|
+
|
|
56
|
+
WORD = "WORD" # bareword / identifier / keyword (case preserved)
|
|
57
|
+
NUMBER = "NUMBER" # numeric literal (float() parseable)
|
|
58
|
+
STRING = "STRING" # quoted string literal (quotes included in value)
|
|
59
|
+
OP = "OP" # one of = , ( ) * / + - ^ ;
|
|
60
|
+
COMMENT = "COMMENT" # ! ... to end of line (! included)
|
|
61
|
+
UNKNOWN = "UNKNOWN" # anything the lexer could not classify
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# Single-character operators. ``;`` is included so a full-line tokenisation
|
|
65
|
+
# still surfaces statement separators; the structural splitter handles them.
|
|
66
|
+
_OPERATOR_CHARS = frozenset("=,()*/+-^;")
|
|
67
|
+
|
|
68
|
+
# Characters that terminate a bareword.
|
|
69
|
+
_WORD_TERMINATORS = frozenset("=,()*/+-^;!\"' \t")
|
|
70
|
+
|
|
71
|
+
# Additional characters that stop the "digit glued to word" merge (see
|
|
72
|
+
# tokenize_line) without being general bareword terminators. '%' is the only
|
|
73
|
+
# member: a percentage literal like 'err 10%' must keep lexing as NUMBER '10'
|
|
74
|
+
# + WORD '%' (the recognizer's error-value parsing looks for a standalone
|
|
75
|
+
# '%' token), but a bare '%' elsewhere still reads as an ordinary WORD
|
|
76
|
+
# character rather than becoming its own terminator-triggered token.
|
|
77
|
+
_NUMBER_MERGE_STOPPERS = _WORD_TERMINATORS | frozenset("%")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class Token:
|
|
82
|
+
"""A single lexical token.
|
|
83
|
+
|
|
84
|
+
Attributes
|
|
85
|
+
----------
|
|
86
|
+
type:
|
|
87
|
+
The :class:`TokenType`.
|
|
88
|
+
value:
|
|
89
|
+
The exact source text of the token, verbatim. For ``STRING`` tokens
|
|
90
|
+
this *includes* the surrounding quote characters, so ``value`` sliced
|
|
91
|
+
from the source line is always ``line[span[0]:span[1]]``.
|
|
92
|
+
span:
|
|
93
|
+
``(start, end)`` half-open character offsets into the source line.
|
|
94
|
+
error:
|
|
95
|
+
Set for tolerated-but-malformed tokens (currently: unterminated
|
|
96
|
+
string). Downstream code may surface this as a warning; it never
|
|
97
|
+
affects round-tripping because ``value`` is still the raw text.
|
|
98
|
+
quote:
|
|
99
|
+
For ``STRING`` tokens, the quote character that opened it (``"`` or
|
|
100
|
+
``'``). ``None`` otherwise.
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
type: TokenType
|
|
104
|
+
value: str
|
|
105
|
+
span: tuple
|
|
106
|
+
error: Optional[str] = None
|
|
107
|
+
quote: Optional[str] = None
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def start(self) -> int:
|
|
111
|
+
return self.span[0]
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def end(self) -> int:
|
|
115
|
+
return self.span[1]
|
|
116
|
+
|
|
117
|
+
def lower(self) -> str:
|
|
118
|
+
"""Case-folded token value (for case-insensitive keyword matching)."""
|
|
119
|
+
return self.value.lower()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def tokenize_line(text: str) -> List[Token]:
|
|
123
|
+
"""Tokenise a single physical line of GLE source.
|
|
124
|
+
|
|
125
|
+
The input should be one line *without* its trailing newline (the caller in
|
|
126
|
+
:mod:`~gleplot.parser.syntax` strips line endings and preserves them
|
|
127
|
+
separately). Passing a string that contains newlines is tolerated -- the
|
|
128
|
+
newline is treated as ordinary whitespace -- but spans then refer to the
|
|
129
|
+
combined string.
|
|
130
|
+
|
|
131
|
+
Never raises. Returns tokens in source order; whitespace produces no token
|
|
132
|
+
but is fully recoverable from the gaps between token spans.
|
|
133
|
+
"""
|
|
134
|
+
tokens: List[Token] = []
|
|
135
|
+
i = 0
|
|
136
|
+
n = len(text)
|
|
137
|
+
|
|
138
|
+
while i < n:
|
|
139
|
+
ch = text[i]
|
|
140
|
+
|
|
141
|
+
# Whitespace: skip (recoverable via spans).
|
|
142
|
+
if ch in " \t\r\n":
|
|
143
|
+
i += 1
|
|
144
|
+
continue
|
|
145
|
+
|
|
146
|
+
# Comment: '!' to end of line, verbatim.
|
|
147
|
+
if ch == "!":
|
|
148
|
+
tokens.append(Token(TokenType.COMMENT, text[i:], (i, n)))
|
|
149
|
+
break
|
|
150
|
+
|
|
151
|
+
# Quoted string (double or tolerated single).
|
|
152
|
+
if ch == '"' or ch == "'":
|
|
153
|
+
tok = _read_string(text, i, n, ch)
|
|
154
|
+
tokens.append(tok)
|
|
155
|
+
i = tok.end
|
|
156
|
+
continue
|
|
157
|
+
|
|
158
|
+
# Number literal (including a leading sign only when it is clearly a
|
|
159
|
+
# numeric literal rather than an operator between operands). We take
|
|
160
|
+
# the tolerant route: a '+'/'-' immediately followed by a digit or a
|
|
161
|
+
# dot+digit, and NOT preceded by something that could be an operand,
|
|
162
|
+
# is treated as an operator here -- expression evaluation handles unary
|
|
163
|
+
# signs itself. So the lexer emits '+'/'-' as OP and lets expr.py
|
|
164
|
+
# interpret unary vs binary. Bare numbers still parse here.
|
|
165
|
+
if ch.isdigit() or (ch == "." and i + 1 < n and text[i + 1].isdigit()):
|
|
166
|
+
number = _read_number(text, i, n)
|
|
167
|
+
if number is not None:
|
|
168
|
+
tok = number
|
|
169
|
+
if tok.end < n and text[tok.end] not in _NUMBER_MERGE_STOPPERS:
|
|
170
|
+
# The digit run is glued directly to more word
|
|
171
|
+
# characters with no terminator between them -- e.g.
|
|
172
|
+
# '20_main.dat', '1e5abc', '5.dat'. That is only ever a
|
|
173
|
+
# bareword (typically an unquoted filename) in valid
|
|
174
|
+
# GLE, so re-read the whole run as a single WORD rather
|
|
175
|
+
# than splitting off a NUMBER prefix.
|
|
176
|
+
tok = _read_word(text, i, n)
|
|
177
|
+
tokens.append(tok)
|
|
178
|
+
i = tok.end
|
|
179
|
+
continue
|
|
180
|
+
|
|
181
|
+
# Operators.
|
|
182
|
+
if ch in _OPERATOR_CHARS:
|
|
183
|
+
tokens.append(Token(TokenType.OP, ch, (i, i + 1)))
|
|
184
|
+
i += 1
|
|
185
|
+
continue
|
|
186
|
+
|
|
187
|
+
# Bareword / identifier / keyword.
|
|
188
|
+
tok = _read_word(text, i, n)
|
|
189
|
+
tokens.append(tok)
|
|
190
|
+
i = tok.end
|
|
191
|
+
|
|
192
|
+
return tokens
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _read_string(text: str, start: int, n: int, quote: str) -> Token:
|
|
196
|
+
"""Read a quoted string beginning at ``start`` (the opening quote).
|
|
197
|
+
|
|
198
|
+
As in GLE's ``Tokenizer::copy_string``, a backslash is an ordinary
|
|
199
|
+
character, and a quote doubled in place is the embedded quote: both
|
|
200
|
+
characters stay in the token and the string continues. An unterminated
|
|
201
|
+
string is tolerated: the token spans to end of line and is flagged with
|
|
202
|
+
``error='unterminated-string'``.
|
|
203
|
+
"""
|
|
204
|
+
i = start + 1
|
|
205
|
+
while i < n:
|
|
206
|
+
c = text[i]
|
|
207
|
+
if c == quote:
|
|
208
|
+
if i + 1 < n and text[i + 1] == quote:
|
|
209
|
+
i += 2
|
|
210
|
+
continue
|
|
211
|
+
end = i + 1
|
|
212
|
+
return Token(
|
|
213
|
+
TokenType.STRING,
|
|
214
|
+
text[start:end],
|
|
215
|
+
(start, end),
|
|
216
|
+
quote=quote,
|
|
217
|
+
)
|
|
218
|
+
i += 1
|
|
219
|
+
# Ran off the end without a closing quote: tolerate, flag it.
|
|
220
|
+
return Token(
|
|
221
|
+
TokenType.STRING,
|
|
222
|
+
text[start:n],
|
|
223
|
+
(start, n),
|
|
224
|
+
error="unterminated-string",
|
|
225
|
+
quote=quote,
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _read_number(text: str, start: int, n: int) -> Optional[Token]:
|
|
230
|
+
"""Read a numeric literal beginning at ``start``.
|
|
231
|
+
|
|
232
|
+
Uses ``float()`` semantics for the longest prefix that parses. Returns
|
|
233
|
+
``None`` if no numeric literal can be formed (caller then falls back to
|
|
234
|
+
word/operator handling).
|
|
235
|
+
"""
|
|
236
|
+
i = start
|
|
237
|
+
seen_digit = False
|
|
238
|
+
seen_dot = False
|
|
239
|
+
seen_exp = False
|
|
240
|
+
|
|
241
|
+
while i < n:
|
|
242
|
+
c = text[i]
|
|
243
|
+
if c.isdigit():
|
|
244
|
+
seen_digit = True
|
|
245
|
+
i += 1
|
|
246
|
+
elif c == "." and not seen_dot and not seen_exp:
|
|
247
|
+
seen_dot = True
|
|
248
|
+
i += 1
|
|
249
|
+
elif (c == "e" or c == "E") and seen_digit and not seen_exp:
|
|
250
|
+
# Exponent: optional sign then digits.
|
|
251
|
+
j = i + 1
|
|
252
|
+
if j < n and text[j] in "+-":
|
|
253
|
+
j += 1
|
|
254
|
+
if j < n and text[j].isdigit():
|
|
255
|
+
seen_exp = True
|
|
256
|
+
i = j
|
|
257
|
+
else:
|
|
258
|
+
break # 'e' not part of a valid exponent -> stop number here
|
|
259
|
+
else:
|
|
260
|
+
break
|
|
261
|
+
|
|
262
|
+
if not seen_digit:
|
|
263
|
+
return None
|
|
264
|
+
|
|
265
|
+
literal = text[start:i]
|
|
266
|
+
# Defensive: confirm it really parses (it always should given the scan).
|
|
267
|
+
try:
|
|
268
|
+
float(literal)
|
|
269
|
+
except ValueError: # pragma: no cover - scan guarantees validity
|
|
270
|
+
return None
|
|
271
|
+
return Token(TokenType.NUMBER, literal, (start, i))
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _read_word(text: str, start: int, n: int) -> Token:
|
|
275
|
+
"""Read a bareword up to the next terminator.
|
|
276
|
+
|
|
277
|
+
A bareword is any run of characters not in :data:`_WORD_TERMINATORS`. This
|
|
278
|
+
deliberately includes ``.`` (so filenames like ``data.dat`` and dataset
|
|
279
|
+
refs like ``d1=c1,c2`` -- well, the ``=`` splits -- stay intact where
|
|
280
|
+
sensible) and ``_`` and digits mid-word.
|
|
281
|
+
"""
|
|
282
|
+
i = start
|
|
283
|
+
while i < n and text[i] not in _WORD_TERMINATORS:
|
|
284
|
+
i += 1
|
|
285
|
+
if i == start:
|
|
286
|
+
# Shouldn't happen (caller guarantees a non-terminator start), but be
|
|
287
|
+
# safe: emit a single-char UNKNOWN token to guarantee progress.
|
|
288
|
+
return Token(TokenType.UNKNOWN, text[start : start + 1], (start, start + 1))
|
|
289
|
+
return Token(TokenType.WORD, text[start:i], (start, i))
|
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
"""The ``! gleplot:`` metadata comment block: emit and parse (pure module).
|
|
2
|
+
|
|
3
|
+
``.gle`` has no native concept of a few gleplot-specific, non-GLE-semantic
|
|
4
|
+
settings (canvas DPI, whether subplots share axes, the marker-size scale
|
|
5
|
+
factor, the style's default line width and colours, and which series were plotted from an *imported* copy of an external
|
|
6
|
+
data file vs. a live *reference* to it). These are persisted as a small,
|
|
7
|
+
versioned block of GLE comment lines so a ``.gle`` file round-trips through
|
|
8
|
+
gleplot without losing them, while remaining perfectly valid (and harmless)
|
|
9
|
+
GLE source to any other tool that opens it.
|
|
10
|
+
|
|
11
|
+
Format (fixed, versioned)::
|
|
12
|
+
|
|
13
|
+
! gleplot-meta-begin v2
|
|
14
|
+
! gleplot: dpi = 100
|
|
15
|
+
! gleplot: sharex = false
|
|
16
|
+
! gleplot: sharey = false
|
|
17
|
+
! gleplot: msize_scale = 1.0
|
|
18
|
+
! gleplot: default_linewidth = 1.5
|
|
19
|
+
! gleplot: default_color = BLUE
|
|
20
|
+
! gleplot: default_marker_color = BLUE
|
|
21
|
+
! gleplot: import-data = data_0.dat, data_1.dat
|
|
22
|
+
! gleplot: insets = 3
|
|
23
|
+
! gleplot-meta-end
|
|
24
|
+
|
|
25
|
+
``insets`` lists, by 1-based graph block number, the axes placed outside the
|
|
26
|
+
subplot grid by :meth:`gleplot.Figure.add_axes`. It is written only when the
|
|
27
|
+
figure has such an axes.
|
|
28
|
+
|
|
29
|
+
This module is intentionally standalone: it does not import the writer, and
|
|
30
|
+
nothing wires it into ``GLEWriter`` yet (that is a later phase). It only
|
|
31
|
+
defines the ``emit_metadata`` / ``parse_metadata`` pair plus the shared
|
|
32
|
+
default/type knowledge they both use so the two can never drift apart.
|
|
33
|
+
|
|
34
|
+
Versions
|
|
35
|
+
--------
|
|
36
|
+
The version marker does **not** describe the ``key = value`` lines. It
|
|
37
|
+
records the *page geometry* of the file the block sits in: since ``v2`` every
|
|
38
|
+
graph block carries an explicit frame rectangle (``amove x y``, ``size w h``
|
|
39
|
+
and ``scale 1 1``, SPEC 3.3), which the recognizer reads back into
|
|
40
|
+
:attr:`gleplot.Axes.placement`.
|
|
41
|
+
|
|
42
|
+
:func:`emit_metadata` always writes :data:`VERSION`. :func:`parse_metadata`
|
|
43
|
+
reads a ``v2`` block, or one with no version. A block of an older version is
|
|
44
|
+
not read: the file loads as hand-written GLE, and saving it writes a ``v2``
|
|
45
|
+
block. A newer or unparseable marker is reported and its lines are read
|
|
46
|
+
anyway.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
from __future__ import annotations
|
|
50
|
+
|
|
51
|
+
import re
|
|
52
|
+
from typing import Any, Dict, List, Tuple
|
|
53
|
+
|
|
54
|
+
__all__ = [
|
|
55
|
+
"BEGIN_MARKER",
|
|
56
|
+
"END_MARKER",
|
|
57
|
+
"LINE_PREFIX",
|
|
58
|
+
"DEFAULTS",
|
|
59
|
+
"ALWAYS_EMIT",
|
|
60
|
+
"VERSION",
|
|
61
|
+
"emit_metadata",
|
|
62
|
+
"parse_metadata",
|
|
63
|
+
]
|
|
64
|
+
|
|
65
|
+
# -- Format constants ---------------------------------------------------
|
|
66
|
+
|
|
67
|
+
#: Version written by :func:`emit_metadata`, and the only one
|
|
68
|
+
#: :func:`parse_metadata` reads (see the module docstring).
|
|
69
|
+
VERSION = 2
|
|
70
|
+
|
|
71
|
+
BEGIN_MARKER = f"! gleplot-meta-begin v{VERSION}"
|
|
72
|
+
END_MARKER = "! gleplot-meta-end"
|
|
73
|
+
LINE_PREFIX = "! gleplot:"
|
|
74
|
+
|
|
75
|
+
#: Known keys and their default values (used to decide what counts as
|
|
76
|
+
#: "non-default" for emission). ``import-data`` has no meaningful scalar
|
|
77
|
+
#: default -- it is handled separately (see :data:`ALWAYS_EMIT`).
|
|
78
|
+
DEFAULTS: Dict[str, Any] = {
|
|
79
|
+
"dpi": 100,
|
|
80
|
+
"sharex": False,
|
|
81
|
+
"sharey": False,
|
|
82
|
+
"msize_scale": 1.0,
|
|
83
|
+
"default_linewidth": 1.5,
|
|
84
|
+
# None: the colour cycle (see GLEStyleConfig).
|
|
85
|
+
"default_color": None,
|
|
86
|
+
"default_marker_color": None,
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
#: Keys that are always emitted regardless of whether they equal their
|
|
90
|
+
#: default, per the spec: "Only NON-DEFAULT values need emitting except dpi
|
|
91
|
+
#: and the import-data list".
|
|
92
|
+
ALWAYS_EMIT = frozenset({"dpi", "import-data"})
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _format_scalar(value: Any) -> str:
|
|
96
|
+
"""Render a single metadata value as it appears after ``key = ``."""
|
|
97
|
+
if isinstance(value, bool):
|
|
98
|
+
return "true" if value else "false"
|
|
99
|
+
if isinstance(value, float):
|
|
100
|
+
# Keep an explicit decimal point (e.g. "1.0" not "1") so re-parsing
|
|
101
|
+
# infers float, not int, matching the documented example.
|
|
102
|
+
if value.is_integer():
|
|
103
|
+
return f"{value:.1f}"
|
|
104
|
+
return repr(value)
|
|
105
|
+
if isinstance(value, int):
|
|
106
|
+
return str(value)
|
|
107
|
+
return str(value)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _quote_list_item(name: str) -> str:
|
|
111
|
+
"""Quote a list entry when a bare comma-join would corrupt it.
|
|
112
|
+
|
|
113
|
+
Entries containing a comma, a double quote, or leading/trailing
|
|
114
|
+
whitespace are wrapped in double quotes, with embedded quotes escaped
|
|
115
|
+
as ``\\"``, so they survive emit -> parse unchanged.
|
|
116
|
+
"""
|
|
117
|
+
if any(ch in name for ch in ',"') or name != name.strip():
|
|
118
|
+
return '"' + name.replace('"', '\\"') + '"'
|
|
119
|
+
return name
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _split_list(raw: str) -> List[str]:
|
|
123
|
+
"""Split a comma-list, honoring the quoting from :func:`_quote_list_item`."""
|
|
124
|
+
items: List[str] = []
|
|
125
|
+
i, n = 0, len(raw)
|
|
126
|
+
while i < n:
|
|
127
|
+
while i < n and raw[i] in " \t":
|
|
128
|
+
i += 1
|
|
129
|
+
if i >= n:
|
|
130
|
+
break
|
|
131
|
+
if raw[i] == '"':
|
|
132
|
+
i += 1
|
|
133
|
+
buf: List[str] = []
|
|
134
|
+
while i < n:
|
|
135
|
+
ch = raw[i]
|
|
136
|
+
if ch == "\\" and i + 1 < n and raw[i + 1] == '"':
|
|
137
|
+
buf.append('"')
|
|
138
|
+
i += 2
|
|
139
|
+
continue
|
|
140
|
+
if ch == '"':
|
|
141
|
+
i += 1
|
|
142
|
+
break
|
|
143
|
+
buf.append(ch)
|
|
144
|
+
i += 1
|
|
145
|
+
items.append("".join(buf))
|
|
146
|
+
while i < n and raw[i] != ",":
|
|
147
|
+
i += 1
|
|
148
|
+
i += 1
|
|
149
|
+
else:
|
|
150
|
+
j = raw.find(",", i)
|
|
151
|
+
if j == -1:
|
|
152
|
+
j = n
|
|
153
|
+
item = raw[i:j].strip()
|
|
154
|
+
if item:
|
|
155
|
+
items.append(item)
|
|
156
|
+
i = j + 1
|
|
157
|
+
return items
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _format_value(key: str, value: Any) -> str:
|
|
161
|
+
if key == "insets":
|
|
162
|
+
return ", ".join(str(int(n)) for n in value)
|
|
163
|
+
if key == "import-data":
|
|
164
|
+
names = value or []
|
|
165
|
+
return ", ".join(_quote_list_item(str(n)) for n in names)
|
|
166
|
+
return _format_scalar(value)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def emit_metadata(data: Dict[str, Any]) -> List[str]:
|
|
170
|
+
"""Build the ``! gleplot:`` comment block lines for ``data``.
|
|
171
|
+
|
|
172
|
+
Parameters
|
|
173
|
+
----------
|
|
174
|
+
data : dict
|
|
175
|
+
Metadata values to persist. Recognized keys: ``dpi`` (int),
|
|
176
|
+
``sharex`` / ``sharey`` (bool, or 'row'/'col'), ``msize_scale`` and
|
|
177
|
+
``default_linewidth`` (float), ``default_color`` and
|
|
178
|
+
``default_marker_color`` (GLE colour tokens),
|
|
179
|
+
``import-data`` (list of str filenames), ``insets`` (list of int
|
|
180
|
+
graph numbers, emitted only when present). Unknown keys are emitted
|
|
181
|
+
verbatim (as strings) so callers can round-trip forward-compatible
|
|
182
|
+
extra fields; a bare list/tuple value is rendered as a comma-list,
|
|
183
|
+
anything else via ``str()``.
|
|
184
|
+
|
|
185
|
+
Returns
|
|
186
|
+
-------
|
|
187
|
+
list of str
|
|
188
|
+
The full block, from ``! gleplot-meta-begin v1`` through
|
|
189
|
+
``! gleplot-meta-end`` inclusive. Returns an empty list only if
|
|
190
|
+
``data`` is falsy (no block at all is emitted for an empty figure).
|
|
191
|
+
|
|
192
|
+
Notes
|
|
193
|
+
-----
|
|
194
|
+
Only non-default values are emitted, except ``dpi`` and ``import-data``
|
|
195
|
+
which are always emitted (``dpi`` because "no dpi line" is ambiguous
|
|
196
|
+
with "dpi omitted", and ``import-data`` because an empty list is itself
|
|
197
|
+
meaningful: it says no series are in import mode). A key is considered
|
|
198
|
+
"default" only when it is a *known* key (present in :data:`DEFAULTS`)
|
|
199
|
+
and its value equals that default; unknown keys are always emitted since
|
|
200
|
+
they have no known default to compare against.
|
|
201
|
+
"""
|
|
202
|
+
if not data:
|
|
203
|
+
return []
|
|
204
|
+
|
|
205
|
+
lines = [BEGIN_MARKER]
|
|
206
|
+
|
|
207
|
+
# Emit known keys in the documented, stable order first.
|
|
208
|
+
known_order = (
|
|
209
|
+
"dpi",
|
|
210
|
+
"sharex",
|
|
211
|
+
"sharey",
|
|
212
|
+
"msize_scale",
|
|
213
|
+
"default_linewidth",
|
|
214
|
+
"default_color",
|
|
215
|
+
"default_marker_color",
|
|
216
|
+
)
|
|
217
|
+
seen = set()
|
|
218
|
+
for key in known_order:
|
|
219
|
+
seen.add(key)
|
|
220
|
+
if key not in data:
|
|
221
|
+
continue
|
|
222
|
+
value = data[key]
|
|
223
|
+
if key not in ALWAYS_EMIT and key in DEFAULTS and value == DEFAULTS[key]:
|
|
224
|
+
continue
|
|
225
|
+
lines.append(f"{LINE_PREFIX} {key} = {_format_value(key, value)}")
|
|
226
|
+
|
|
227
|
+
# import-data always emitted if the key is present at all (even empty).
|
|
228
|
+
if "import-data" in data:
|
|
229
|
+
seen.add("import-data")
|
|
230
|
+
lines.append(
|
|
231
|
+
f"{LINE_PREFIX} import-data = {_format_value('import-data', data['import-data'])}"
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
# Any remaining (unknown / forward-compat) keys, in insertion order.
|
|
235
|
+
for key, value in data.items():
|
|
236
|
+
if key in seen:
|
|
237
|
+
continue
|
|
238
|
+
lines.append(f"{LINE_PREFIX} {key} = {_format_value(key, value)}")
|
|
239
|
+
|
|
240
|
+
lines.append(END_MARKER)
|
|
241
|
+
return lines
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _older_version(marker: str) -> bool:
|
|
245
|
+
"""True if ``marker`` (after ``! gleplot-meta-begin``) is ``vN``, N < VERSION."""
|
|
246
|
+
match = re.fullmatch(r"v([0-9]+)", marker)
|
|
247
|
+
return match is not None and int(match.group(1)) < VERSION
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _version_warnings(marker: str) -> List[str]:
|
|
251
|
+
"""Warnings for a ``! gleplot-meta-begin`` marker's version suffix.
|
|
252
|
+
|
|
253
|
+
``marker`` is everything after ``! gleplot-meta-begin`` (e.g. ``"v2"``),
|
|
254
|
+
already stripped; an empty string means the marker carried no version.
|
|
255
|
+
The current :data:`VERSION`, or no suffix at all, is silent.
|
|
256
|
+
"""
|
|
257
|
+
if not marker or marker == f"v{VERSION}":
|
|
258
|
+
return []
|
|
259
|
+
if _older_version(marker):
|
|
260
|
+
return [
|
|
261
|
+
f"file uses gleplot metadata {marker}, which gleplot no longer "
|
|
262
|
+
f"reads; it loads as hand-written GLE, and saving writes a "
|
|
263
|
+
f"v{VERSION} block."
|
|
264
|
+
]
|
|
265
|
+
return [
|
|
266
|
+
f"Unrecognized gleplot metadata version marker {marker!r}; "
|
|
267
|
+
f"expected 'v{VERSION}'. Parsing line contents anyway."
|
|
268
|
+
]
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _parse_scalar(raw: str) -> Any:
|
|
272
|
+
"""Parse a single scalar value token: bool, int, float, else string."""
|
|
273
|
+
lowered = raw.lower()
|
|
274
|
+
if lowered == "true":
|
|
275
|
+
return True
|
|
276
|
+
if lowered == "false":
|
|
277
|
+
return False
|
|
278
|
+
try:
|
|
279
|
+
return int(raw)
|
|
280
|
+
except ValueError:
|
|
281
|
+
pass
|
|
282
|
+
try:
|
|
283
|
+
return float(raw)
|
|
284
|
+
except ValueError:
|
|
285
|
+
pass
|
|
286
|
+
return raw
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _parse_value(key: str, raw: str) -> Any:
|
|
290
|
+
raw = raw.strip()
|
|
291
|
+
if key == "insets":
|
|
292
|
+
return [int(n) for n in _split_list(raw)]
|
|
293
|
+
if key == "import-data":
|
|
294
|
+
if not raw:
|
|
295
|
+
return []
|
|
296
|
+
return _split_list(raw)
|
|
297
|
+
return _parse_scalar(raw)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def parse_metadata(lines: List[str]) -> Tuple[Dict[str, Any], List[str]]:
|
|
301
|
+
"""Parse a ``! gleplot:`` metadata block out of a list of source lines.
|
|
302
|
+
|
|
303
|
+
Parameters
|
|
304
|
+
----------
|
|
305
|
+
lines : list of str
|
|
306
|
+
Source lines to scan (typically the whole ``.gle`` file, or just the
|
|
307
|
+
preamble). Only the content between a ``! gleplot-meta-begin vN``
|
|
308
|
+
line and the next ``! gleplot-meta-end`` line is considered; lines
|
|
309
|
+
outside a block are ignored. If multiple blocks are present, only
|
|
310
|
+
the first is parsed.
|
|
311
|
+
|
|
312
|
+
Returns
|
|
313
|
+
-------
|
|
314
|
+
(dict, list of str)
|
|
315
|
+
A tuple of ``(data, warnings)``. ``data`` maps each recognized key to
|
|
316
|
+
its typed value (``int``/``float``/``bool``/``str``/``list[str]``);
|
|
317
|
+
unknown keys are preserved with their parsed scalar value so callers
|
|
318
|
+
can round-trip forward-compatible fields. If no metadata block is
|
|
319
|
+
found at all, returns ``({}, [])``. Malformed lines inside a found
|
|
320
|
+
block (missing ``=``, blank key) are skipped and recorded in
|
|
321
|
+
``warnings`` rather than raising.
|
|
322
|
+
|
|
323
|
+
Notes
|
|
324
|
+
-----
|
|
325
|
+
A block of a version older than :data:`VERSION` is not read: it yields
|
|
326
|
+
no data and one warning saying the file loads as hand-written GLE. A
|
|
327
|
+
newer or unparseable version yields the "unrecognized version" warning
|
|
328
|
+
and its lines are read anyway. Neither raises. See the module docstring.
|
|
329
|
+
"""
|
|
330
|
+
data: Dict[str, Any] = {}
|
|
331
|
+
warnings: List[str] = []
|
|
332
|
+
|
|
333
|
+
in_block = False
|
|
334
|
+
found_block = False
|
|
335
|
+
for line in lines:
|
|
336
|
+
stripped = line.strip()
|
|
337
|
+
|
|
338
|
+
if not in_block:
|
|
339
|
+
if stripped.startswith("! gleplot-meta-begin"):
|
|
340
|
+
in_block = True
|
|
341
|
+
found_block = True
|
|
342
|
+
rest = stripped[len("! gleplot-meta-begin") :].strip()
|
|
343
|
+
warnings.extend(_version_warnings(rest))
|
|
344
|
+
if _older_version(rest):
|
|
345
|
+
return {}, warnings
|
|
346
|
+
continue
|
|
347
|
+
|
|
348
|
+
if stripped == END_MARKER:
|
|
349
|
+
break
|
|
350
|
+
|
|
351
|
+
if not stripped.startswith(LINE_PREFIX):
|
|
352
|
+
warnings.append(f"Skipping malformed metadata line: {line!r}")
|
|
353
|
+
continue
|
|
354
|
+
|
|
355
|
+
payload = stripped[len(LINE_PREFIX) :].strip()
|
|
356
|
+
if "=" not in payload:
|
|
357
|
+
warnings.append(f"Skipping malformed metadata line (no '='): {line!r}")
|
|
358
|
+
continue
|
|
359
|
+
|
|
360
|
+
key, _, raw_value = payload.partition("=")
|
|
361
|
+
key = key.strip()
|
|
362
|
+
if not key:
|
|
363
|
+
warnings.append(f"Skipping malformed metadata line (empty key): {line!r}")
|
|
364
|
+
continue
|
|
365
|
+
|
|
366
|
+
try:
|
|
367
|
+
data[key] = _parse_value(key, raw_value)
|
|
368
|
+
except ValueError:
|
|
369
|
+
warnings.append(f"Skipping malformed metadata line (bad value): {line!r}")
|
|
370
|
+
|
|
371
|
+
if not found_block:
|
|
372
|
+
return {}, []
|
|
373
|
+
|
|
374
|
+
return data, warnings
|