@ai-ecoverse/py-pyparsing 3.3.3-1

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.
Files changed (43) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +3 -0
  3. package/lib/python3.14/site-packages/pyparsing/__init__.py +413 -0
  4. package/lib/python3.14/site-packages/pyparsing/__pycache__/__init__.cpython-314.pyc +0 -0
  5. package/lib/python3.14/site-packages/pyparsing/__pycache__/actions.cpython-314.pyc +0 -0
  6. package/lib/python3.14/site-packages/pyparsing/__pycache__/common.cpython-314.pyc +0 -0
  7. package/lib/python3.14/site-packages/pyparsing/__pycache__/core.cpython-314.pyc +0 -0
  8. package/lib/python3.14/site-packages/pyparsing/__pycache__/exceptions.cpython-314.pyc +0 -0
  9. package/lib/python3.14/site-packages/pyparsing/__pycache__/helpers.cpython-314.pyc +0 -0
  10. package/lib/python3.14/site-packages/pyparsing/__pycache__/results.cpython-314.pyc +0 -0
  11. package/lib/python3.14/site-packages/pyparsing/__pycache__/testing.cpython-314.pyc +0 -0
  12. package/lib/python3.14/site-packages/pyparsing/__pycache__/unicode.cpython-314.pyc +0 -0
  13. package/lib/python3.14/site-packages/pyparsing/__pycache__/util.cpython-314.pyc +0 -0
  14. package/lib/python3.14/site-packages/pyparsing/__pycache__/warnings.cpython-314.pyc +0 -0
  15. package/lib/python3.14/site-packages/pyparsing/actions.py +264 -0
  16. package/lib/python3.14/site-packages/pyparsing/ai/__init__.py +0 -0
  17. package/lib/python3.14/site-packages/pyparsing/ai/__pycache__/__init__.cpython-314.pyc +0 -0
  18. package/lib/python3.14/site-packages/pyparsing/ai/best_practices.md +75 -0
  19. package/lib/python3.14/site-packages/pyparsing/ai/show_best_practices/__init__.py +0 -0
  20. package/lib/python3.14/site-packages/pyparsing/ai/show_best_practices/__main__.py +2 -0
  21. package/lib/python3.14/site-packages/pyparsing/ai/show_best_practices/__pycache__/__init__.cpython-314.pyc +0 -0
  22. package/lib/python3.14/site-packages/pyparsing/ai/show_best_practices/__pycache__/__main__.cpython-314.pyc +0 -0
  23. package/lib/python3.14/site-packages/pyparsing/common.py +570 -0
  24. package/lib/python3.14/site-packages/pyparsing/core.py +6972 -0
  25. package/lib/python3.14/site-packages/pyparsing/diagram/__init__.py +761 -0
  26. package/lib/python3.14/site-packages/pyparsing/diagram/__pycache__/__init__.cpython-314.pyc +0 -0
  27. package/lib/python3.14/site-packages/pyparsing/exceptions.py +353 -0
  28. package/lib/python3.14/site-packages/pyparsing/helpers.py +1769 -0
  29. package/lib/python3.14/site-packages/pyparsing/py.typed +0 -0
  30. package/lib/python3.14/site-packages/pyparsing/results.py +928 -0
  31. package/lib/python3.14/site-packages/pyparsing/testing.py +398 -0
  32. package/lib/python3.14/site-packages/pyparsing/tools/__init__.py +0 -0
  33. package/lib/python3.14/site-packages/pyparsing/tools/__pycache__/__init__.cpython-314.pyc +0 -0
  34. package/lib/python3.14/site-packages/pyparsing/tools/__pycache__/cvt_pyparsing_pep8_names.cpython-314.pyc +0 -0
  35. package/lib/python3.14/site-packages/pyparsing/tools/cvt_pyparsing_pep8_names.py +142 -0
  36. package/lib/python3.14/site-packages/pyparsing/unicode.py +356 -0
  37. package/lib/python3.14/site-packages/pyparsing/util.py +514 -0
  38. package/lib/python3.14/site-packages/pyparsing/warnings.py +10 -0
  39. package/lib/python3.14/site-packages/pyparsing-3.3.3.dist-info/METADATA +147 -0
  40. package/lib/python3.14/site-packages/pyparsing-3.3.3.dist-info/RECORD +23 -0
  41. package/lib/python3.14/site-packages/pyparsing-3.3.3.dist-info/WHEEL +4 -0
  42. package/lib/python3.14/site-packages/pyparsing-3.3.3.dist-info/licenses/LICENSE +20 -0
  43. package/package.json +27 -0
@@ -0,0 +1,761 @@
1
+ # mypy: ignore-errors
2
+ from __future__ import annotations
3
+
4
+ import itertools
5
+ import railroad
6
+ import pyparsing
7
+ import dataclasses
8
+ import typing
9
+ from typing import (
10
+ Generic,
11
+ TypeVar,
12
+ Callable,
13
+ Iterable,
14
+ )
15
+ from jinja2 import Template
16
+ from io import StringIO
17
+ import inspect
18
+ import re
19
+
20
+
21
+ jinja2_template_source = """\
22
+ {% if not embed %}
23
+ <!DOCTYPE html>
24
+ <html>
25
+ <head>
26
+ {% endif %}
27
+ {% if not head %}
28
+ <style>
29
+ .railroad-heading {
30
+ font-family: monospace;
31
+ }
32
+ </style>
33
+ {% else %}
34
+ {{ head | safe }}
35
+ {% endif %}
36
+ {% if not embed %}
37
+ </head>
38
+ <body>
39
+ {% endif %}
40
+ <meta charset="UTF-8"/>
41
+ {{ body | safe }}
42
+ {% for diagram in diagrams %}
43
+ <div class="railroad-group">
44
+ <h1 class="railroad-heading" id="{{ diagram.bookmark }}">{{ diagram.title }}</h1>
45
+ <div class="railroad-description">{{ diagram.text }}</div>
46
+ <div class="railroad-svg">
47
+ {{ diagram.svg }}
48
+ </div>
49
+ </div>
50
+ {% endfor %}
51
+ {% if not embed %}
52
+ </body>
53
+ </html>
54
+ {% endif %}
55
+ """
56
+
57
+ template = Template(jinja2_template_source)
58
+
59
+
60
+ _bookmark_lookup = {}
61
+ _bookmark_ids = itertools.count(start=1)
62
+
63
+ def _make_bookmark(s: str) -> str:
64
+ """
65
+ Converts a string into a valid HTML bookmark (ID or anchor name).
66
+ """
67
+ if s in _bookmark_lookup:
68
+ return _bookmark_lookup[s]
69
+
70
+ # Replace invalid characters with hyphens and ensure only valid characters
71
+ bookmark = re.sub(r'[^a-zA-Z0-9-]+', '-', s)
72
+
73
+ # Ensure it starts with a letter by adding 'z' if necessary
74
+ if not bookmark[:1].isalpha():
75
+ bookmark = f"z{bookmark}"
76
+
77
+ # Convert to lowercase and strip hyphens
78
+ bookmark = bookmark.lower().strip('-')
79
+
80
+ _bookmark_lookup[s] = bookmark = f"{bookmark}-{next(_bookmark_ids):04d}"
81
+
82
+ return bookmark
83
+
84
+
85
+ def _collapse_verbose_regex(regex_str: str) -> str:
86
+ if "\n" not in regex_str:
87
+ return regex_str
88
+ collapsed = pyparsing.Regex(r"#.*$").suppress().transform_string(regex_str)
89
+ collapsed = re.sub(r"\s*\n\s*", "", collapsed)
90
+ return collapsed
91
+
92
+
93
+ @dataclasses.dataclass
94
+ class NamedDiagram:
95
+ """
96
+ A simple structure for associating a name with a railroad diagram
97
+ """
98
+
99
+ name: str
100
+ index: int
101
+ diagram: railroad.DiagramItem = None
102
+
103
+ @property
104
+ def bookmark(self):
105
+ bookmark = _make_bookmark(self.name)
106
+ return bookmark
107
+
108
+
109
+ T = TypeVar("T")
110
+
111
+
112
+ class EachItem(railroad.Group):
113
+ """
114
+ Custom railroad item to compose a:
115
+
116
+ - :class:`railroad.Group` containing a
117
+
118
+ - :class:`railroad.OneOrMore` containing a
119
+
120
+ - :class:`railroad.Choice` of the elements in the
121
+ :class:`railroad.Each`
122
+
123
+ with the group label indicating that all must be matched
124
+ """
125
+
126
+ all_label = "[ALL]"
127
+
128
+ def __init__(self, *items) -> None:
129
+ choice_item = railroad.Choice(len(items) - 1, *items)
130
+ one_or_more_item = railroad.OneOrMore(item=choice_item)
131
+ super().__init__(one_or_more_item, label=self.all_label)
132
+
133
+
134
+ class AnnotatedItem(railroad.Group):
135
+ """
136
+ Simple subclass of Group that creates an annotation label
137
+ """
138
+
139
+ def __init__(self, label: str, item) -> None:
140
+ super().__init__(item=item, label=f"[{label}]" if label else "")
141
+
142
+
143
+ class EditablePartial(Generic[T]):
144
+ """
145
+ Acts like a functools.partial, but can be edited. In other words, it represents a type that hasn't yet been
146
+ constructed.
147
+ """
148
+
149
+ # We need this here because the railroad constructors actually transform the data, so can't be called until the
150
+ # entire tree is assembled
151
+
152
+ def __init__(self, func: Callable[..., T], args: list, kwargs: dict) -> None:
153
+ self.func = func
154
+ self.args = args
155
+ self.kwargs = kwargs
156
+
157
+ @classmethod
158
+ def from_call(cls, func: Callable[..., T], *args, **kwargs) -> EditablePartial[T]:
159
+ """
160
+ If you call this function in the same way that you would call the constructor,
161
+ it will store the arguments as you expect. For example
162
+ ``EditablePartial.from_call(Fraction, 1, 3)() == Fraction(1, 3)``
163
+ """
164
+ return EditablePartial(func=func, args=list(args), kwargs=kwargs)
165
+
166
+ @property
167
+ def name(self):
168
+ return self.kwargs["name"]
169
+
170
+ def __call__(self) -> T:
171
+ """
172
+ Evaluate the partial and return the result
173
+ """
174
+ args = self.args.copy()
175
+ kwargs = self.kwargs.copy()
176
+
177
+ # This is a helpful hack to allow you to specify varargs parameters (e.g. *args) as keyword args (e.g.
178
+ # args=['list', 'of', 'things'])
179
+ arg_spec = inspect.getfullargspec(self.func)
180
+ if arg_spec.varargs in self.kwargs:
181
+ args += kwargs.pop(arg_spec.varargs)
182
+
183
+ return self.func(*args, **kwargs)
184
+
185
+
186
+ def railroad_to_html(diagrams: list[NamedDiagram], embed=False, **kwargs) -> str:
187
+ """
188
+ Given a list of :class:`NamedDiagram`, produce a single HTML string
189
+ that visualises those diagrams.
190
+
191
+ :params kwargs: kwargs to be passed in to the template
192
+ """
193
+ data = []
194
+ for diagram in diagrams:
195
+ if diagram.diagram is None:
196
+ continue
197
+ io = StringIO()
198
+ try:
199
+ css = kwargs.get("css")
200
+ diagram.diagram.writeStandalone(io.write, css=css)
201
+ except AttributeError:
202
+ diagram.diagram.writeSvg(io.write)
203
+ title = diagram.name
204
+ if diagram.index == 0:
205
+ title += " (root)"
206
+ data.append(
207
+ {
208
+ "title": title, "text": "", "svg": io.getvalue(), "bookmark": diagram.bookmark
209
+ }
210
+ )
211
+
212
+ return template.render(diagrams=data, embed=embed, **kwargs)
213
+
214
+
215
+ def resolve_partial(partial: EditablePartial[T]) -> T:
216
+ """
217
+ Recursively resolves a collection of Partials into whatever type they are
218
+ """
219
+ if isinstance(partial, EditablePartial):
220
+ partial.args = resolve_partial(partial.args)
221
+ partial.kwargs = resolve_partial(partial.kwargs)
222
+ return partial()
223
+ elif isinstance(partial, list):
224
+ return [resolve_partial(x) for x in partial]
225
+ elif isinstance(partial, dict):
226
+ return {key: resolve_partial(x) for key, x in partial.items()}
227
+ else:
228
+ return partial
229
+
230
+
231
+ def to_railroad(
232
+ element: pyparsing.ParserElement,
233
+ diagram_kwargs: typing.Optional[dict] = None,
234
+ vertical: int = 3,
235
+ show_results_names: bool = False,
236
+ show_groups: bool = False,
237
+ show_hidden: bool = False,
238
+ ) -> list[NamedDiagram]:
239
+ """
240
+ Convert a pyparsing element tree into a list of diagrams. This is the recommended entrypoint to diagram
241
+ creation if you want to access the Railroad tree before it is converted to HTML
242
+
243
+ :param element: base element of the parser being diagrammed
244
+
245
+ :param diagram_kwargs: kwargs to pass to the :meth:`Diagram` constructor
246
+
247
+ :param vertical: (optional) int - limit at which number of alternatives
248
+ should be shown vertically instead of horizontally
249
+
250
+ :param show_results_names: bool to indicate whether results name
251
+ annotations should be included in the diagram
252
+
253
+ :param show_groups: bool to indicate whether groups should be highlighted
254
+ with an unlabeled surrounding box
255
+
256
+ :param show_hidden: bool to indicate whether internal elements that are
257
+ typically hidden should be shown
258
+ """
259
+ # Convert the whole tree underneath the root
260
+ lookup = ConverterState(diagram_kwargs=diagram_kwargs or {})
261
+ _to_diagram_element(
262
+ element,
263
+ lookup=lookup,
264
+ parent=None,
265
+ vertical=vertical,
266
+ show_results_names=show_results_names,
267
+ show_groups=show_groups,
268
+ show_hidden=show_hidden,
269
+ )
270
+
271
+ root_id = id(element)
272
+ # Convert the root if it hasn't been already
273
+ if root_id in lookup:
274
+ if not element.customName:
275
+ lookup[root_id].name = ""
276
+ lookup[root_id].mark_for_extraction(root_id, lookup, force=True)
277
+
278
+ # Now that we're finished, we can convert from intermediate structures into Railroad elements
279
+ diags = list(lookup.diagrams.values())
280
+ if len(diags) > 1:
281
+ # collapse out duplicate diags with the same name
282
+ seen = set()
283
+ deduped_diags = []
284
+ for d in diags:
285
+ # don't extract SkipTo elements, they are uninformative as subdiagrams
286
+ if d.name == "...":
287
+ continue
288
+ if d.name is not None and d.name not in seen:
289
+ seen.add(d.name)
290
+ deduped_diags.append(d)
291
+ resolved = [resolve_partial(partial) for partial in deduped_diags]
292
+ else:
293
+ # special case - if just one diagram, always display it, even if
294
+ # it has no name
295
+ resolved = [resolve_partial(partial) for partial in diags]
296
+ return sorted(resolved, key=lambda diag: diag.index)
297
+
298
+
299
+ def _should_vertical(
300
+ specification: int, exprs: Iterable[pyparsing.ParserElement]
301
+ ) -> bool:
302
+ """
303
+ Returns true if we should return a vertical list of elements
304
+ """
305
+ if specification is None:
306
+ return False
307
+ else:
308
+ return len(_visible_exprs(exprs)) >= specification
309
+
310
+
311
+ @dataclasses.dataclass
312
+ class ElementState:
313
+ """
314
+ State recorded for an individual pyparsing Element
315
+ """
316
+
317
+ #: The pyparsing element that this represents
318
+ element: pyparsing.ParserElement
319
+ #: The output Railroad element in an unconverted state
320
+ converted: EditablePartial
321
+ #: The parent Railroad element, which we store so that we can extract this if it's duplicated
322
+ parent: EditablePartial
323
+ #: The order in which we found this element, used for sorting diagrams if this is extracted into a diagram
324
+ number: int
325
+ #: The name of the element
326
+ name: str = None
327
+ #: The index of this inside its parent
328
+ parent_index: typing.Optional[int] = None
329
+ #: If true, we should extract this out into a subdiagram
330
+ extract: bool = False
331
+ #: If true, all of this element's children have been filled out
332
+ complete: bool = False
333
+
334
+ def mark_for_extraction(
335
+ self, el_id: int, state: ConverterState, name: str = None, force: bool = False
336
+ ):
337
+ """
338
+ Called when this instance has been seen twice, and thus should eventually be extracted into a sub-diagram
339
+ :param el_id: id of the element
340
+ :param state: element/diagram state tracker
341
+ :param name: name to use for this element's text
342
+ :param force: If true, force extraction now, regardless of the state of this. Only useful for extracting the
343
+ root element when we know we're finished
344
+ """
345
+ self.extract = True
346
+
347
+ # Set the name
348
+ if not self.name:
349
+ if name:
350
+ # Allow forcing a custom name
351
+ self.name = name
352
+ elif self.element.customName:
353
+ self.name = self.element.customName
354
+ else:
355
+ self.name = ""
356
+
357
+ # Just because this is marked for extraction doesn't mean we can do it yet. We may have to wait for children
358
+ # to be added
359
+ # Also, if this is just a string literal etc, don't bother extracting it
360
+ if force or (self.complete and _worth_extracting(self.element)):
361
+ state.extract_into_diagram(el_id)
362
+
363
+
364
+ class ConverterState:
365
+ """
366
+ Stores some state that persists between recursions into the element tree
367
+ """
368
+ index_generator = itertools.count(start=1)
369
+
370
+ def __init__(self, diagram_kwargs: typing.Optional[dict] = None) -> None:
371
+ #: A dictionary mapping ParserElements to state relating to them
372
+ self._element_diagram_states: dict[int, ElementState] = {}
373
+ #: A dictionary mapping ParserElement IDs to subdiagrams generated from them
374
+ self.diagrams: dict[int, EditablePartial[NamedDiagram]] = {}
375
+ #: The index of the next element. This is used for sorting
376
+ self.index: int = 0
377
+ #: Shared kwargs that are used to customize the construction of diagrams
378
+ self.diagram_kwargs: dict = diagram_kwargs or {}
379
+ self.extracted_diagram_names: set[str] = set()
380
+
381
+ def __setitem__(self, key: int, value: ElementState):
382
+ self._element_diagram_states[key] = value
383
+
384
+ def __getitem__(self, key: int) -> ElementState:
385
+ return self._element_diagram_states[key]
386
+
387
+ def __delitem__(self, key: int):
388
+ del self._element_diagram_states[key]
389
+
390
+ def __contains__(self, key: int):
391
+ return key in self._element_diagram_states
392
+
393
+ def get(self, key, default=None):
394
+ try:
395
+ return self[key]
396
+ except KeyError:
397
+ return default
398
+
399
+ def generate_index(self) -> int:
400
+ """
401
+ Generate a number used to index a diagram
402
+ """
403
+ return next(self.index_generator)
404
+
405
+ def extract_into_diagram(self, el_id: int):
406
+ """
407
+ Used when we encounter the same token twice in the same tree. When this
408
+ happens, we replace all instances of that token with a terminal, and
409
+ create a new subdiagram for the token
410
+ """
411
+ position = self[el_id]
412
+
413
+ # Replace the original definition of this element with a regular block
414
+ if position.parent:
415
+ href = f"#{_make_bookmark(position.name)}"
416
+ ret = EditablePartial.from_call(railroad.NonTerminal, text=position.name, href=href)
417
+ if "item" in position.parent.kwargs:
418
+ position.parent.kwargs["item"] = ret
419
+ elif "items" in position.parent.kwargs:
420
+ position.parent.kwargs["items"][position.parent_index] = ret
421
+
422
+ # If the element we're extracting is a group, skip to its content but keep the title
423
+ if position.converted.func == railroad.Group:
424
+ content = position.converted.kwargs["item"]
425
+ else:
426
+ content = position.converted
427
+
428
+ self.diagrams[el_id] = EditablePartial.from_call(
429
+ NamedDiagram,
430
+ name=position.name,
431
+ diagram=EditablePartial.from_call(
432
+ railroad.Diagram, content, **self.diagram_kwargs
433
+ ),
434
+ index=position.number,
435
+ )
436
+
437
+ del self[el_id]
438
+
439
+
440
+ def _worth_extracting(element: pyparsing.ParserElement) -> bool:
441
+ """
442
+ Returns true if this element is worth having its own sub-diagram. Simply, if any of its children
443
+ themselves have children, then its complex enough to extract
444
+ """
445
+ children = element.recurse()
446
+ return any(child.recurse() for child in children)
447
+
448
+
449
+ def _apply_diagram_item_enhancements(fn):
450
+ """
451
+ decorator to ensure enhancements to a diagram item (such as results name annotations)
452
+ get applied on return from _to_diagram_element (we do this since there are several
453
+ returns in _to_diagram_element)
454
+ """
455
+
456
+ def _inner(
457
+ element: pyparsing.ParserElement,
458
+ parent: typing.Optional[EditablePartial],
459
+ lookup: ConverterState = None,
460
+ vertical: int = None,
461
+ index: int = 0,
462
+ name_hint: str = None,
463
+ show_results_names: bool = False,
464
+ show_groups: bool = False,
465
+ show_hidden: bool = False,
466
+ ) -> typing.Optional[EditablePartial]:
467
+ ret = fn(
468
+ element,
469
+ parent,
470
+ lookup,
471
+ vertical,
472
+ index,
473
+ name_hint,
474
+ show_results_names,
475
+ show_groups,
476
+ show_hidden,
477
+ )
478
+
479
+ # apply annotation for results name, if present
480
+ if show_results_names and ret is not None:
481
+ element_results_name = element.resultsName
482
+ if element_results_name:
483
+ # add "*" to indicate if this is a "list all results" name
484
+ modal_tag = "" if element.modalResults else "*"
485
+ ret = EditablePartial.from_call(
486
+ railroad.Group,
487
+ item=ret,
488
+ label=f"{repr(element_results_name)}{modal_tag}",
489
+ )
490
+
491
+ return ret
492
+
493
+ return _inner
494
+
495
+
496
+ def _visible_exprs(exprs: Iterable[pyparsing.ParserElement]):
497
+ non_diagramming_exprs = (
498
+ pyparsing.ParseElementEnhance,
499
+ pyparsing.PositionToken,
500
+ pyparsing.And._ErrorStop,
501
+ )
502
+ return [
503
+ e
504
+ for e in exprs
505
+ if not isinstance(e, non_diagramming_exprs)
506
+ ]
507
+
508
+
509
+ @_apply_diagram_item_enhancements
510
+ def _to_diagram_element(
511
+ element: pyparsing.ParserElement,
512
+ parent: typing.Optional[EditablePartial],
513
+ lookup: ConverterState = None,
514
+ vertical: int = None,
515
+ index: int = 0,
516
+ name_hint: str = None,
517
+ show_results_names: bool = False,
518
+ show_groups: bool = False,
519
+ show_hidden: bool = False,
520
+ ) -> typing.Optional[EditablePartial]:
521
+ """
522
+ Recursively converts a PyParsing Element to a railroad Element
523
+ :param lookup: The shared converter state that keeps track of useful things
524
+ :param index: The index of this element within the parent
525
+ :param parent: The parent of this element in the output tree
526
+ :param vertical: Controls at what point we make a list of elements vertical. If this is an integer (the default),
527
+ it sets the threshold of the number of items before we go vertical. If True, always go vertical, if False, never
528
+ do so
529
+ :param name_hint: If provided, this will override the generated name
530
+ :param show_results_names: bool flag indicating whether to add annotations for results names
531
+ :param show_groups: bool flag indicating whether to show groups using bounding box
532
+ :param show_hidden: bool flag indicating whether to show elements that are typically hidden
533
+ :returns: The converted version of the input element, but as a Partial that hasn't yet been constructed
534
+ """
535
+ exprs = element.recurse()
536
+ name = name_hint or element.customName or type(element).__name__
537
+
538
+ # Python's id() is used to provide a unique identifier for elements
539
+ el_id = id(element)
540
+
541
+ element_results_name = element.resultsName
542
+
543
+ # Here we basically bypass processing certain wrapper elements if they contribute nothing to the diagram
544
+ if not element.customName:
545
+ if isinstance(
546
+ element,
547
+ (
548
+ # pyparsing.TokenConverter,
549
+ pyparsing.Forward,
550
+ pyparsing.Located,
551
+ pyparsing.AtStringStart,
552
+ pyparsing.AtLineStart,
553
+ ),
554
+ ):
555
+ # However, if this element has a useful custom name, and its child does not, we can pass it on to the child
556
+ if exprs:
557
+ if not exprs[0].customName:
558
+ propagated_name = name
559
+ else:
560
+ propagated_name = None
561
+
562
+ return _to_diagram_element(
563
+ element.expr,
564
+ parent=parent,
565
+ lookup=lookup,
566
+ vertical=vertical,
567
+ index=index,
568
+ name_hint=propagated_name,
569
+ show_results_names=show_results_names,
570
+ show_groups=show_groups,
571
+ show_hidden=show_hidden,
572
+ )
573
+
574
+ # If the element isn't worth extracting, we always treat it as the first time we say it
575
+ if _worth_extracting(element):
576
+ looked_up = lookup.get(el_id)
577
+ if looked_up and looked_up.name is not None:
578
+ # If we've seen this element exactly once before, we are only just now finding out that it's a duplicate,
579
+ # so we have to extract it into a new diagram.
580
+ looked_up.mark_for_extraction(el_id, lookup, name=name_hint)
581
+ href = f"#{_make_bookmark(looked_up.name)}"
582
+ ret = EditablePartial.from_call(railroad.NonTerminal, text=looked_up.name, href=href)
583
+ return ret
584
+
585
+ elif el_id in lookup.diagrams:
586
+ # If we have seen the element at least twice before, and have already extracted it into a subdiagram, we
587
+ # just put in a marker element that refers to the sub-diagram
588
+ text = lookup.diagrams[el_id].kwargs["name"]
589
+ ret = EditablePartial.from_call(
590
+ railroad.NonTerminal, text=text, href=f"#{_make_bookmark(text)}"
591
+ )
592
+ return ret
593
+
594
+ # Recursively convert child elements
595
+ # Here we find the most relevant Railroad element for matching pyparsing Element
596
+ # We use ``items=[]`` here to hold the place for where the child elements will go once created
597
+
598
+ # see if this element is normally hidden, and whether hidden elements are desired
599
+ # if not, just return None
600
+ if not element.show_in_diagram and not show_hidden:
601
+ return None
602
+
603
+ if isinstance(element, pyparsing.And):
604
+ # detect And's created with ``expr*N`` notation - for these use a OneOrMore with a repeat
605
+ # (all will have the same name, and resultsName)
606
+ if not exprs:
607
+ return None
608
+ if len(set((e.name, e.resultsName) for e in exprs)) == 1 and len(exprs) > 2:
609
+ ret = EditablePartial.from_call(
610
+ railroad.OneOrMore, item="", repeat=str(len(exprs))
611
+ )
612
+ elif _should_vertical(vertical, exprs):
613
+ ret = EditablePartial.from_call(railroad.Stack, items=[])
614
+ else:
615
+ ret = EditablePartial.from_call(railroad.Sequence, items=[])
616
+ elif isinstance(element, (pyparsing.Or, pyparsing.MatchFirst)):
617
+ if not exprs:
618
+ return None
619
+ if _should_vertical(vertical, exprs):
620
+ ret = EditablePartial.from_call(railroad.Choice, 0, items=[])
621
+ else:
622
+ ret = EditablePartial.from_call(railroad.HorizontalChoice, items=[])
623
+ elif isinstance(element, pyparsing.Each):
624
+ if not exprs:
625
+ return None
626
+ ret = EditablePartial.from_call(EachItem, items=[])
627
+ elif isinstance(element, pyparsing.NotAny):
628
+ ret = EditablePartial.from_call(AnnotatedItem, label="NOT", item="")
629
+ elif isinstance(element, pyparsing.FollowedBy):
630
+ ret = EditablePartial.from_call(AnnotatedItem, label="LOOKAHEAD", item="")
631
+ elif isinstance(element, pyparsing.PrecededBy):
632
+ ret = EditablePartial.from_call(AnnotatedItem, label="LOOKBEHIND", item="")
633
+ elif isinstance(element, pyparsing.Group):
634
+ if show_groups:
635
+ ret = EditablePartial.from_call(AnnotatedItem, label="", item="")
636
+ else:
637
+ ret = EditablePartial.from_call(
638
+ railroad.Group, item=None, label=element_results_name
639
+ )
640
+ elif isinstance(element, pyparsing.TokenConverter):
641
+ label = type(element).__name__.lower()
642
+ if label == "tokenconverter":
643
+ ret = EditablePartial.from_call(railroad.Sequence, items=[])
644
+ else:
645
+ ret = EditablePartial.from_call(AnnotatedItem, label=label, item="")
646
+ elif isinstance(element, pyparsing.Opt):
647
+ ret = EditablePartial.from_call(railroad.Optional, item="")
648
+ elif isinstance(element, pyparsing.OneOrMore):
649
+ if element.not_ender is not None:
650
+ args = [
651
+ parent,
652
+ lookup,
653
+ vertical,
654
+ index,
655
+ name_hint,
656
+ show_results_names,
657
+ show_groups,
658
+ show_hidden,
659
+ ]
660
+ return _to_diagram_element(
661
+ (~element.not_ender.expr + element.expr)[1, ...].set_name(element.name),
662
+ *args,
663
+ )
664
+ ret = EditablePartial.from_call(railroad.OneOrMore, item=None)
665
+ elif isinstance(element, pyparsing.ZeroOrMore):
666
+ if element.not_ender is not None:
667
+ args = [
668
+ parent,
669
+ lookup,
670
+ vertical,
671
+ index,
672
+ name_hint,
673
+ show_results_names,
674
+ show_groups,
675
+ show_hidden,
676
+ ]
677
+ return _to_diagram_element(
678
+ (~element.not_ender.expr + element.expr)[...].set_name(element.name),
679
+ *args,
680
+ )
681
+ ret = EditablePartial.from_call(railroad.ZeroOrMore, item="")
682
+ elif isinstance(element, pyparsing.Empty) and not element.customName:
683
+ # Skip unnamed "Empty" elements
684
+ ret = None
685
+ elif isinstance(element, pyparsing.ParseElementEnhance):
686
+ ret = EditablePartial.from_call(railroad.Sequence, items=[])
687
+ elif len(exprs) > 0 and not element_results_name:
688
+ ret = EditablePartial.from_call(railroad.Group, item="", label=name)
689
+ elif isinstance(element, pyparsing.Regex):
690
+ collapsed_patt = _collapse_verbose_regex(element.pattern)
691
+ ret = EditablePartial.from_call(railroad.Terminal, collapsed_patt)
692
+ elif len(exprs) > 0:
693
+ ret = EditablePartial.from_call(railroad.Sequence, items=[])
694
+ else:
695
+ terminal = EditablePartial.from_call(railroad.Terminal, element.defaultName)
696
+ ret = terminal
697
+
698
+ if ret is None:
699
+ return
700
+
701
+ # Indicate this element's position in the tree so we can extract it if necessary
702
+ lookup[el_id] = ElementState(
703
+ element=element,
704
+ converted=ret,
705
+ parent=parent,
706
+ parent_index=index,
707
+ number=lookup.generate_index(),
708
+ )
709
+ if element.customName:
710
+ lookup[el_id].mark_for_extraction(el_id, lookup, element.customName)
711
+
712
+ i = 0
713
+ for expr in exprs:
714
+ # Add a placeholder index in case we have to extract the child before we even add it to the parent
715
+ if "items" in ret.kwargs:
716
+ ret.kwargs["items"].insert(i, None)
717
+
718
+ item = _to_diagram_element(
719
+ expr,
720
+ parent=ret,
721
+ lookup=lookup,
722
+ vertical=vertical,
723
+ index=i,
724
+ show_results_names=show_results_names,
725
+ show_groups=show_groups,
726
+ show_hidden=show_hidden,
727
+ )
728
+
729
+ # Some elements don't need to be shown in the diagram
730
+ if item is not None:
731
+ if "item" in ret.kwargs:
732
+ ret.kwargs["item"] = item
733
+ elif "items" in ret.kwargs:
734
+ # If we've already extracted the child, don't touch this index, since it's occupied by a nonterminal
735
+ ret.kwargs["items"][i] = item
736
+ i += 1
737
+ elif "items" in ret.kwargs:
738
+ # If we're supposed to skip this element, remove it from the parent
739
+ del ret.kwargs["items"][i]
740
+
741
+ # If all this items children are none, skip this item
742
+ if ret and (
743
+ ("items" in ret.kwargs and len(ret.kwargs["items"]) == 0)
744
+ or ("item" in ret.kwargs and ret.kwargs["item"] is None)
745
+ ):
746
+ ret = EditablePartial.from_call(railroad.Terminal, name)
747
+
748
+ # Mark this element as "complete", ie it has all of its children
749
+ if el_id in lookup:
750
+ lookup[el_id].complete = True
751
+
752
+ if el_id in lookup and lookup[el_id].extract and lookup[el_id].complete:
753
+ lookup.extract_into_diagram(el_id)
754
+ if ret is not None:
755
+ text = lookup.diagrams[el_id].kwargs["name"]
756
+ href = f"#{_make_bookmark(text)}"
757
+ ret = EditablePartial.from_call(
758
+ railroad.NonTerminal, text=text, href=href
759
+ )
760
+
761
+ return ret