asnkit-gen-python 1.0.1__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.
@@ -0,0 +1,13 @@
1
+ # Copyright (c) 2025 BoxTheta
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """Makes Python code with data classes from a compiled ASN.1
6
+ specification, for `asnkit`.
7
+
8
+ """
9
+
10
+ from .generate import GenerateError, generate
11
+ from .version import __version__
12
+
13
+ __all__ = ["GenerateError", "generate", "__version__"]
@@ -0,0 +1,7 @@
1
+ # Copyright (c) 2025 BoxTheta
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from .cli import main
6
+
7
+ main()
@@ -0,0 +1,102 @@
1
+ # Copyright (c) 2025 BoxTheta
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """The plugin ``asnkit-gen-python``, as ``asnkitcc generate`` runs it:
6
+
7
+ .. code-block:: text
8
+
9
+ asnkit-gen-python --asni FILE --asnst FILE --out FOLDER [--opt KEY=VALUE ...]
10
+
11
+ It writes one Python module to the folder. The options are ``name``,
12
+ which is the name of the module without ``.py`` (default: that of
13
+ the first file the specification is from), and ``codec``, which is
14
+ what the module encodes and decodes with if not told otherwise
15
+ (default: ``ber``).
16
+
17
+ """
18
+
19
+ import argparse
20
+ import os
21
+ import sys
22
+
23
+ from asnkitrt import syntax
24
+ from asnkitrt.errors import Error
25
+
26
+ from .generate import DEFAULT_CODEC, GenerateError, generate
27
+ from .version import __version__
28
+
29
+ OPTIONS = {"name", "codec"}
30
+
31
+
32
+ def read_options(items: list[str]) -> dict[str, str]:
33
+ options = {}
34
+
35
+ for item in items:
36
+ key, separator, value = item.partition("=")
37
+
38
+ if not separator or key not in OPTIONS:
39
+ raise GenerateError(
40
+ "Expected the option {} as KEY=VALUE with a KEY of {}.".format(
41
+ item, ", ".join(sorted(OPTIONS))
42
+ )
43
+ )
44
+
45
+ options[key] = value
46
+
47
+ return options
48
+
49
+
50
+ def run(args: argparse.Namespace) -> str:
51
+ options = read_options(args.opt)
52
+
53
+ with open(args.asni, "rb") as fin:
54
+ asni = fin.read()
55
+
56
+ # The names of the files it was made from are in the .asnst file.
57
+ sources: list[str] = []
58
+
59
+ if args.asnst is not None:
60
+ with open(args.asnst, "rb") as fin:
61
+ header = syntax.read_header(fin.read())
62
+
63
+ if header.metadata is not None:
64
+ sources = [source.name for source in header.metadata.sources if source.name]
65
+
66
+ name = options.get("name")
67
+
68
+ if name is None:
69
+ name = os.path.splitext(sources[0])[0] if sources else "specification"
70
+
71
+ if not name.isidentifier():
72
+ raise GenerateError("Expected a name of a module, but got '{}'.".format(name))
73
+
74
+ text = generate(asni, sources, options.get("codec", DEFAULT_CODEC))
75
+ os.makedirs(args.out, exist_ok=True)
76
+ path = os.path.join(args.out, name + ".py")
77
+
78
+ with open(path, "w", encoding="utf-8") as fout:
79
+ fout.write(text)
80
+
81
+ return path
82
+
83
+
84
+ def main() -> None:
85
+ parser = argparse.ArgumentParser(
86
+ prog="asnkit-gen-python",
87
+ description="Makes Python code with data classes from a compiled ASN.1 "
88
+ "specification. Run by `asnkitcc generate`.",
89
+ )
90
+ parser.add_argument("--version", action="version", version=__version__)
91
+ parser.add_argument("--asni", required=True, help="The compiled specification.")
92
+ parser.add_argument("--asnst", help="The syntax tree of the specification.")
93
+ parser.add_argument("--out", required=True, help="The folder to write to.")
94
+ parser.add_argument(
95
+ "--opt", action="append", default=[], help="An option, as KEY=VALUE."
96
+ )
97
+ args = parser.parse_args()
98
+
99
+ try:
100
+ run(args)
101
+ except (GenerateError, Error, OSError) as error:
102
+ sys.exit("error: {}".format(error))
@@ -0,0 +1,790 @@
1
+ # Copyright (c) 2025 BoxTheta
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """Makes the text of a Python module from a compiled ASN.1 specification.
6
+
7
+ The module imports asnkit, has the ``.asni`` file in it as bytes and has
8
+ a data class for each SEQUENCE and SET, an enumeration for each
9
+ ENUMERATED and a class for each alternative of a CHOICE, with methods
10
+ to encode and decode them and to turn them into and from what asnkitrt
11
+ encodes and decodes.
12
+
13
+ """
14
+
15
+ import keyword
16
+ import re
17
+ from typing import Any
18
+
19
+ from asnkitrt import syntax
20
+
21
+ DEFAULT_CODEC = "ber"
22
+
23
+ # What asnkitrt encodes and decodes a type as, by the name of the type.
24
+ # Everything else is a SEQUENCE, a SET, a SEQUENCE OF, a SET OF, a CHOICE,
25
+ # an ENUMERATED or the name of a type.
26
+ PLAIN_TYPES = {
27
+ "BOOLEAN": "bool",
28
+ "INTEGER": "int",
29
+ "REAL": "float",
30
+ "OCTET STRING": "bytes",
31
+ "BIT STRING": "tuple[bytes, int]",
32
+ "NULL": "None",
33
+ "OBJECT IDENTIFIER": "str",
34
+ "RELATIVE-OID": "str",
35
+ "ObjectDescriptor": "str",
36
+ "TeletexString": "str",
37
+ "VideotexString": "str",
38
+ "NumericString": "str",
39
+ "PrintableString": "str",
40
+ "IA5String": "str",
41
+ "VisibleString": "str",
42
+ "GeneralString": "str",
43
+ "UTF8String": "str",
44
+ "BMPString": "str",
45
+ "GraphicString": "str",
46
+ "UniversalString": "str",
47
+ "UTCTime": "datetime.datetime",
48
+ "GeneralizedTime": "datetime.datetime",
49
+ "DATE-TIME": "datetime.datetime",
50
+ "DATE": "datetime.date",
51
+ "TIME-OF-DAY": "datetime.time",
52
+ "DURATION": "str",
53
+ "ANY": "Any",
54
+ "ANY DEFINED BY": "Any",
55
+ "OpenType": "Any",
56
+ "EXTERNAL": "Any",
57
+ }
58
+
59
+ # What the generated code uses, which a type is not called.
60
+ TAKEN = {
61
+ "Any",
62
+ "ClassVar",
63
+ "CodecType",
64
+ "DEFAULT_CODEC",
65
+ "TypeAlias",
66
+ "asnkit",
67
+ "dataclasses",
68
+ "datetime",
69
+ "enum",
70
+ "functools",
71
+ "spec",
72
+ }
73
+
74
+ # Names of what the methods of the classes are called, which a member
75
+ # can not be called.
76
+ RESERVED = {"encode", "decode", "to_value", "from_value"}
77
+
78
+
79
+ class GenerateError(Exception):
80
+ pass
81
+
82
+
83
+ def camel(name: str) -> str:
84
+ """``foo-bar`` and ``foo_bar`` are ``FooBar``."""
85
+
86
+ parts = [part for part in re.split(r"[-_]", name) if part]
87
+ result = "".join(part[0].upper() + part[1:] for part in parts)
88
+
89
+ if not result or result[0].isdigit():
90
+ result = "T" + result
91
+
92
+ return result
93
+
94
+
95
+ def snake(name: str) -> str:
96
+ """``fooBar`` and ``foo-bar`` are ``foo_bar``."""
97
+
98
+ name = name.replace("-", "_")
99
+ name = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", name)
100
+ name = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", name)
101
+ name = name.lower()
102
+
103
+ if not name or name[0].isdigit():
104
+ name = "n" + name
105
+
106
+ return name
107
+
108
+
109
+ def field_name(name: str) -> str:
110
+ result = snake(name)
111
+
112
+ if keyword.iskeyword(result) or result in RESERVED or result.startswith("_"):
113
+ result += "_"
114
+
115
+ return result
116
+
117
+
118
+ HEADER = '''\
119
+ # Generated by asnkit-gen-python {version} from {sources}. Do not edit.
120
+ #
121
+ # This file is made from the specification it names, and needs the asnkitrt
122
+ # package (MIT) to run. It may be used under terms of your choice: the code
123
+ # that asnkit-gen-python copies into it is not under the Apache License of
124
+ # the plugin.
125
+
126
+ from __future__ import annotations
127
+
128
+ import dataclasses
129
+ import datetime
130
+ import enum
131
+ import functools
132
+ from typing import Any, ClassVar, TypeAlias
133
+
134
+ import asnkitrt
135
+ from asnkitrt.runtime import CodecType
136
+
137
+ DEFAULT_CODEC: CodecType = "{codec}"
138
+
139
+ # The compiled specification, as the contents of an .asni file.
140
+ _ASNI = (
141
+ {asni}
142
+ )
143
+
144
+
145
+ @functools.cache
146
+ def spec(codec: CodecType = DEFAULT_CODEC) -> asnkitrt.Specification:
147
+ """The specification, loaded for the given codec."""
148
+
149
+ return asnkitrt.load_asni(_ASNI, codec)
150
+
151
+
152
+ def _type(codec: CodecType, asn1_type: tuple[str, str]) -> Any:
153
+ if not asn1_type[1]:
154
+ raise TypeError(
155
+ "This type is a part of another type, and is not encoded on its own."
156
+ )
157
+
158
+ return spec(codec).modules[asn1_type[0]][asn1_type[1]]
159
+
160
+
161
+ def _to_value(shape: Any, obj: Any) -> Any:
162
+ """What asnkitrt encodes, for an object of given shape."""
163
+
164
+ if shape is None:
165
+ return obj
166
+
167
+ if isinstance(shape, type):
168
+ shape = getattr(shape, "_shape")
169
+
170
+ kind = shape[0]
171
+
172
+ if kind == "seq":
173
+ values: dict[str, Any] = {{}}
174
+
175
+ for attribute, name, member_shape, how in shape[2]:
176
+ member = getattr(obj, attribute)
177
+
178
+ if how == "null":
179
+ # An optional NULL is there if it is True.
180
+ if member:
181
+ values[name] = None
182
+ elif how == "required_null":
183
+ values[name] = None
184
+ elif member is not None:
185
+ values[name] = _to_value(member_shape, member)
186
+
187
+ return values
188
+
189
+ if kind == "list":
190
+ return [_to_value(shape[1], item) for item in obj]
191
+
192
+ if kind == "choice":
193
+ return (obj._alternative, _to_value(shape[1][obj._alternative][1], obj.value))
194
+
195
+ if kind == "enum":
196
+ return obj.value if isinstance(obj, enum.Enum) else obj
197
+
198
+ raise TypeError(shape)
199
+
200
+
201
+ def _from_value(shape: Any, value: Any) -> Any:
202
+ """The object of given shape for what asnkitrt decoded."""
203
+
204
+ if shape is None:
205
+ return value
206
+
207
+ if isinstance(shape, type):
208
+ shape = getattr(shape, "_shape")
209
+
210
+ kind = shape[0]
211
+
212
+ if kind == "seq":
213
+ arguments: dict[str, Any] = {{}}
214
+
215
+ for attribute, name, member_shape, how in shape[2]:
216
+ if how == "null":
217
+ arguments[attribute] = name in value
218
+ elif name in value:
219
+ arguments[attribute] = _from_value(member_shape, value[name])
220
+ elif how == "required_null":
221
+ arguments[attribute] = None
222
+
223
+ return shape[1](**arguments)
224
+
225
+ if kind == "list":
226
+ return [_from_value(shape[1], item) for item in value]
227
+
228
+ if kind == "choice":
229
+ alternative, shape_of_value = shape[1][value[0]]
230
+
231
+ return alternative(_from_value(shape_of_value, value[1]))
232
+
233
+ if kind == "enum":
234
+ # An extensible enumeration is None for what it does not know of.
235
+ if value is None:
236
+ return None
237
+
238
+ try:
239
+ return shape[1](value)
240
+ except ValueError:
241
+ return value
242
+
243
+ raise TypeError(shape)
244
+
245
+
246
+ def _alternatives(table: dict[str, Any]) -> dict[str, Any]:
247
+ # The alternatives of a choice, which are not of one type.
248
+ return table
249
+
250
+
251
+ def _encode(
252
+ asn1_type: tuple[str, str],
253
+ shape: Any,
254
+ obj: Any,
255
+ codec: CodecType,
256
+ check_types: bool,
257
+ check_constraints: bool,
258
+ ) -> bytes:
259
+ type_ = _type(codec, asn1_type)
260
+ value = _to_value(shape, obj)
261
+
262
+ if check_types:
263
+ type_.check_types(value)
264
+
265
+ if check_constraints:
266
+ type_.check_constraints(value)
267
+
268
+ return bytes(type_.encode(value))
269
+
270
+
271
+ def _decode(
272
+ asn1_type: tuple[str, str],
273
+ shape: Any,
274
+ data: bytes | bytearray,
275
+ codec: CodecType,
276
+ check_constraints: bool,
277
+ ) -> Any:
278
+ type_ = _type(codec, asn1_type)
279
+ value = type_.decode(data)
280
+
281
+ if check_constraints:
282
+ type_.check_constraints(value)
283
+
284
+ return _from_value(shape, value)
285
+
286
+
287
+ class _Methods:
288
+ """What the classes made from ASN.1 types can do."""
289
+
290
+ _asn1_type: ClassVar[tuple[str, str]]
291
+ _shape: ClassVar[Any]
292
+
293
+ def to_value(self) -> Any:
294
+ """What asnkitrt encodes for this object."""
295
+
296
+ return _to_value(type(self)._shape, self)
297
+
298
+ @classmethod
299
+ def from_value(cls, value: Any) -> Any:
300
+ """The object for what asnkitrt decoded."""
301
+
302
+ return _from_value(cls._shape, value)
303
+
304
+ def encode(
305
+ self,
306
+ codec: CodecType = DEFAULT_CODEC,
307
+ check_types: bool = True,
308
+ check_constraints: bool = False,
309
+ ) -> bytes:
310
+ """This object encoded with given codec."""
311
+
312
+ return _encode(
313
+ type(self)._asn1_type,
314
+ type(self)._shape,
315
+ self,
316
+ codec,
317
+ check_types,
318
+ check_constraints,
319
+ )
320
+
321
+ @classmethod
322
+ def decode(
323
+ cls,
324
+ data: bytes | bytearray,
325
+ codec: CodecType = DEFAULT_CODEC,
326
+ check_constraints: bool = False,
327
+ ) -> Any:
328
+ """The object that given data is when decoded with given codec."""
329
+
330
+ return _decode(cls._asn1_type, cls._shape, data, codec, check_constraints)
331
+ '''
332
+
333
+
334
+ class Generator:
335
+ def __init__(
336
+ self,
337
+ compiled: syntax.CompiledSpecification,
338
+ asni: bytes,
339
+ sources: list[str],
340
+ codec: str,
341
+ ) -> None:
342
+ from asnkitrt.version import __version__ as asnkit_version # noqa: F401
343
+
344
+ from .version import __version__
345
+
346
+ self.version = __version__
347
+ self.asni = asni
348
+ self.sources = sources
349
+ self.codec = codec
350
+ self.modules: dict[str, Any] = syntax.compiled_to_dict(compiled)
351
+ self.blocks: list[str] = []
352
+ self.registrations: list[str] = []
353
+ self.functions: list[str] = []
354
+ self.exported: list[str] = ["DEFAULT_CODEC", "spec"]
355
+ self.taken: dict[str, str] = {name: "the code of the module" for name in TAKEN}
356
+ self.names: dict[tuple[str, str], str] = {}
357
+ self.aliases: dict[tuple[str, str], tuple[str, str]] = {}
358
+ self.alias_blocks: list[str] = []
359
+
360
+ # Names.
361
+
362
+ def take(self, name: str, what: str) -> str:
363
+ if name in self.taken:
364
+ raise GenerateError(
365
+ "Both {} and {} are called {} in Python.".format(
366
+ self.taken[name], what, name
367
+ )
368
+ )
369
+
370
+ self.taken[name] = what
371
+
372
+ return name
373
+
374
+ def name_the_types(self) -> None:
375
+ count: dict[str, int] = {}
376
+
377
+ for module in self.modules.values():
378
+ for type_name in module["types"]:
379
+ count[camel(type_name)] = count.get(camel(type_name), 0) + 1
380
+
381
+ for module_name, module in self.modules.items():
382
+ for type_name in module["types"]:
383
+ name = camel(type_name)
384
+
385
+ if count[name] > 1:
386
+ # The same name in more than one module.
387
+ name = camel(module_name) + name
388
+
389
+ if name in TAKEN:
390
+ name += "_"
391
+
392
+ self.names[(module_name, type_name)] = self.take(
393
+ name, "the type {} of {}".format(type_name, module_name)
394
+ )
395
+
396
+ # Types.
397
+
398
+ def lookup(self, module_name: str, type_name: str) -> Any:
399
+ try:
400
+ return self.modules[module_name]["types"][type_name]
401
+ except KeyError:
402
+ raise GenerateError(
403
+ "The type {} of {} is not in the specification.".format(
404
+ type_name, module_name
405
+ )
406
+ )
407
+
408
+ def kind_of(self, descriptor: dict[str, Any]) -> str:
409
+ type_name = descriptor["type"]
410
+
411
+ if type_name in ("SEQUENCE", "SET"):
412
+ return "sequence"
413
+
414
+ if type_name == "CHOICE":
415
+ return "choice"
416
+
417
+ if type_name == "ENUMERATED":
418
+ return "enumerated"
419
+
420
+ return "other"
421
+
422
+ def resolves_to_null(self, descriptor: dict[str, Any], module_name: str) -> bool:
423
+ seen = set()
424
+
425
+ while True:
426
+ type_name = descriptor["type"]
427
+ module_name = descriptor.get("module-name", module_name)
428
+
429
+ if type_name == "NULL":
430
+ return True
431
+
432
+ if (
433
+ type_name in PLAIN_TYPES
434
+ or type_name in ("SEQUENCE", "SET", "CHOICE", "ENUMERATED")
435
+ or type_name.endswith(" OF")
436
+ or "&" in type_name
437
+ or (module_name, type_name) in seen
438
+ or type_name not in self.modules.get(module_name, {}).get("types", {})
439
+ ):
440
+ return False
441
+
442
+ seen.add((module_name, type_name))
443
+ descriptor = self.lookup(module_name, type_name)
444
+
445
+ def annotate(
446
+ self, descriptor: dict[str, Any], module_name: str, context: str
447
+ ) -> tuple[str, str]:
448
+ """Returns the Python type of given type and its shape, and makes
449
+ the classes it needs, named after the context if it has no name.
450
+
451
+ """
452
+
453
+ type_name = descriptor["type"]
454
+ module_name = descriptor.get("module-name", module_name)
455
+
456
+ if type_name in PLAIN_TYPES:
457
+ return PLAIN_TYPES[type_name], "None"
458
+
459
+ if "&" in type_name:
460
+ # A field of an object class.
461
+ return "Any", "None"
462
+
463
+ if type_name in ("SEQUENCE", "SET"):
464
+ name = self.take(camel(context), "the type in " + context)
465
+ self.sequence(name, descriptor, module_name, None)
466
+
467
+ return name, name
468
+
469
+ if type_name == "CHOICE":
470
+ name = self.take(camel(context), "the type in " + context)
471
+ self.choice(name, descriptor, module_name, None)
472
+
473
+ return name, name
474
+
475
+ if type_name == "ENUMERATED":
476
+ name = self.take(camel(context), "the type in " + context)
477
+ self.enumerated(name, descriptor, module_name, None)
478
+
479
+ return name, name
480
+
481
+ if type_name in ("SEQUENCE OF", "SET OF"):
482
+ element, shape = self.annotate(
483
+ descriptor["element"], module_name, context + "-element"
484
+ )
485
+
486
+ return "list[{}]".format(element), '("list", {})'.format(shape)
487
+
488
+ # The name of a type.
489
+ key = (module_name, type_name)
490
+ target = self.lookup(module_name, type_name)
491
+
492
+ if self.kind_of(target) != "other":
493
+ return self.names[key], self.names[key]
494
+
495
+ return self.names[key], self.alias(key, target)[1]
496
+
497
+ def alias(
498
+ self, key: tuple[str, str], descriptor: dict[str, Any]
499
+ ) -> tuple[str, str]:
500
+ """The Python type and the shape of a type that is not a class of
501
+ its own, which is made once.
502
+
503
+ """
504
+
505
+ if key not in self.aliases:
506
+ # Not recursive, as only a class can refer to itself.
507
+ self.aliases[key] = self.annotate(descriptor, key[0], self.names[key])
508
+
509
+ return self.aliases[key]
510
+
511
+ # Classes.
512
+
513
+ def register(self, name: str, module_name: str, type_name: str, shape: str) -> None:
514
+ self.registrations.append(
515
+ "_register({}, ({!r}, {!r}), {})".format(
516
+ name, module_name, type_name, shape
517
+ )
518
+ )
519
+
520
+ def members(self, descriptor: dict[str, Any]) -> list[tuple[dict[str, Any], bool]]:
521
+ """The members, with whether each is in an extension."""
522
+
523
+ members: list[tuple[dict[str, Any], bool]] = []
524
+ in_extension = False
525
+
526
+ for member in descriptor["members"]:
527
+ if member is None:
528
+ in_extension = not in_extension
529
+ elif isinstance(member, list):
530
+ members.extend((item, True) for item in member)
531
+ else:
532
+ members.append((member, in_extension))
533
+
534
+ return members
535
+
536
+ def sequence(
537
+ self,
538
+ name: str,
539
+ descriptor: dict[str, Any],
540
+ module_name: str,
541
+ type_name: str | None,
542
+ ) -> None:
543
+ lines = [
544
+ "@dataclasses.dataclass(kw_only=True)",
545
+ "class {}(_Methods):".format(name),
546
+ ]
547
+ fields = []
548
+ attributes: dict[str, str] = {}
549
+
550
+ scope = descriptor.get("module-name", module_name)
551
+
552
+ for member, in_extension in self.members(descriptor):
553
+ asn1_name = member["name"]
554
+ attribute = field_name(asn1_name)
555
+
556
+ if attribute in attributes:
557
+ raise GenerateError(
558
+ "Both {} and {} of {} are called {} in Python.".format(
559
+ attributes[attribute], asn1_name, name, attribute
560
+ )
561
+ )
562
+
563
+ attributes[attribute] = asn1_name
564
+ annotation, shape = self.annotate(member, scope, name + "-" + asn1_name)
565
+ optional = in_extension or member.get("optional") or "default" in member
566
+ null = self.resolves_to_null(member, scope)
567
+
568
+ if optional and null:
569
+ lines.append(" {}: bool = False".format(attribute))
570
+ how = "null"
571
+ elif null:
572
+ lines.append(" {}: None = None".format(attribute))
573
+ how = "required_null"
574
+ elif optional:
575
+ lines.append(" {}: {} | None = None".format(attribute, annotation))
576
+ how = "optional"
577
+ else:
578
+ lines.append(" {}: {}".format(attribute, annotation))
579
+ how = "required"
580
+
581
+ fields.append(
582
+ "({!r}, {!r}, {}, {!r})".format(attribute, asn1_name, shape, how)
583
+ )
584
+
585
+ if not attributes:
586
+ lines.append(" pass")
587
+
588
+ self.blocks.append("\n".join(lines))
589
+ self.exported.append(name)
590
+ shape = '("seq", {}, ({}))'.format(name, "".join(f + ", " for f in fields))
591
+ self.register(name, module_name, type_name or "", shape)
592
+
593
+ def choice(
594
+ self,
595
+ name: str,
596
+ descriptor: dict[str, Any],
597
+ module_name: str,
598
+ type_name: str | None,
599
+ ) -> None:
600
+ self.blocks.append(
601
+ "class {}(_Methods):\n _alternative: ClassVar[str]".format(name)
602
+ )
603
+ self.exported.append(name)
604
+ alternatives = []
605
+ attributes: dict[str, str] = {}
606
+
607
+ scope = descriptor.get("module-name", module_name)
608
+
609
+ for member, _ in self.members(descriptor):
610
+ asn1_name = member["name"]
611
+ alternative = self.take(
612
+ name + camel(asn1_name),
613
+ "the alternative {} of {}".format(asn1_name, name),
614
+ )
615
+ annotation, shape = self.annotate(
616
+ member, scope, name + "-" + asn1_name + "-value"
617
+ )
618
+ attributes[asn1_name] = alternative
619
+
620
+ self.blocks.append(
621
+ "@dataclasses.dataclass\n"
622
+ "class {}({}):\n"
623
+ " value: {}\n"
624
+ " _alternative: ClassVar[str] = {!r}".format(
625
+ alternative, name, annotation, asn1_name
626
+ )
627
+ )
628
+ self.exported.append(alternative)
629
+ alternatives.append("{!r}: ({}, {}),".format(asn1_name, alternative, shape))
630
+
631
+ shape = '("choice", _alternatives({{{}}}))'.format(" ".join(alternatives))
632
+ self.register(name, module_name, type_name or "", shape)
633
+
634
+ def enumerated(
635
+ self,
636
+ name: str,
637
+ descriptor: dict[str, Any],
638
+ module_name: str,
639
+ type_name: str | None,
640
+ ) -> None:
641
+ lines = ["class {}(_Methods, enum.Enum):".format(name)]
642
+ members: dict[str, str] = {}
643
+
644
+ for value in descriptor["values"]:
645
+ if value is None:
646
+ continue
647
+
648
+ asn1_name = value[0]
649
+ member = snake(asn1_name).upper()
650
+
651
+ if member in members:
652
+ raise GenerateError(
653
+ "Both {} and {} of {} are called {} in Python.".format(
654
+ members[member], asn1_name, name, member
655
+ )
656
+ )
657
+
658
+ members[member] = asn1_name
659
+ lines.append(" {} = {!r}".format(member, asn1_name))
660
+
661
+ if not members:
662
+ lines.append(" pass")
663
+
664
+ self.blocks.append("\n".join(lines))
665
+ self.exported.append(name)
666
+ self.register(name, module_name, type_name or "", '("enum", {})'.format(name))
667
+
668
+ # The whole module.
669
+
670
+ def type_assignment(
671
+ self, module_name: str, type_name: str, descriptor: dict[str, Any]
672
+ ) -> None:
673
+ name = self.names[(module_name, type_name)]
674
+ kind = self.kind_of(descriptor)
675
+
676
+ if kind == "sequence":
677
+ self.sequence(name, descriptor, module_name, type_name)
678
+ elif kind == "choice":
679
+ self.choice(name, descriptor, module_name, type_name)
680
+ elif kind == "enumerated":
681
+ self.enumerated(name, descriptor, module_name, type_name)
682
+ else:
683
+ annotation, shape = self.alias((module_name, type_name), descriptor)
684
+ function = snake(name)
685
+ self.alias_blocks.append('{}: TypeAlias = "{}"'.format(name, annotation))
686
+ self.exported.extend([name, "encode_" + function, "decode_" + function])
687
+ self.functions.append(
688
+ "def encode_{function}(\n"
689
+ " value: {name},\n"
690
+ " codec: CodecType = DEFAULT_CODEC,\n"
691
+ " check_types: bool = True,\n"
692
+ " check_constraints: bool = False,\n"
693
+ ") -> bytes:\n"
694
+ " return _encode(\n"
695
+ " ({module!r}, {type!r}),\n"
696
+ " {shape},\n"
697
+ " value,\n"
698
+ " codec,\n"
699
+ " check_types,\n"
700
+ " check_constraints,\n"
701
+ " )\n\n\n"
702
+ "def decode_{function}(\n"
703
+ " data: bytes | bytearray,\n"
704
+ " codec: CodecType = DEFAULT_CODEC,\n"
705
+ " check_constraints: bool = False,\n"
706
+ ") -> {name}:\n"
707
+ " return _decode(\n"
708
+ " ({module!r}, {type!r}), {shape}, data, codec, check_constraints\n"
709
+ " )".format(
710
+ function=function,
711
+ name=name,
712
+ module=module_name,
713
+ type=type_name,
714
+ shape=shape,
715
+ )
716
+ )
717
+
718
+ def run(self) -> str:
719
+ self.name_the_types()
720
+
721
+ for module_name, module in self.modules.items():
722
+ for type_name, descriptor in module["types"].items():
723
+ self.type_assignment(module_name, type_name, descriptor)
724
+
725
+ # The classes made for types inside others have no name of their
726
+ # own in the specification.
727
+ header = HEADER.format(
728
+ version=self.version,
729
+ sources=", ".join(self.sources) or "a specification",
730
+ codec=self.codec,
731
+ asni=format_bytes(self.asni),
732
+ )
733
+ parts = [
734
+ header,
735
+ "\n\n" + REGISTER,
736
+ "\n\n\n".join(self.blocks),
737
+ "\n".join(self.registrations),
738
+ "\n".join(self.alias_blocks),
739
+ "\n\n\n".join(self.functions),
740
+ "__all__ = [\n{}]".format(
741
+ "".join(" {!r},\n".format(name) for name in self.exported)
742
+ ),
743
+ ]
744
+
745
+ return "\n\n\n".join(part.strip("\n") for part in parts if part.strip()) + "\n"
746
+
747
+
748
+ REGISTER = """\
749
+ def _register(
750
+ class_: Any, asn1_type: tuple[str, str], shape: Any
751
+ ) -> None:
752
+ class_._asn1_type = asn1_type
753
+ class_._shape = shape"""
754
+
755
+
756
+ def format_bytes(data: bytes) -> str:
757
+ lines = []
758
+
759
+ for offset in range(0, len(data), 24):
760
+ chunk = data[offset : offset + 24]
761
+ lines.append(
762
+ ' b"{}"'.format("".join("\\x{:02x}".format(byte) for byte in chunk))
763
+ )
764
+
765
+ return "\n".join(lines) if lines else ' b""'
766
+
767
+
768
+ def generate(
769
+ asni: bytes,
770
+ sources: list[str] | None = None,
771
+ codec: str = DEFAULT_CODEC,
772
+ ) -> str:
773
+ """Returns the text of a Python module for given contents of an
774
+ ``.asni`` file, which must not be signed, encrypted, bound to
775
+ something or have a nonce to check, as it is embedded in the module
776
+ and loaded without any of those. `sources` are the names of the
777
+ files it was made from, and `codec` is what the module encodes and
778
+ decodes with if not told otherwise.
779
+
780
+ """
781
+
782
+ try:
783
+ compiled = syntax.from_asni(asni)
784
+ except Exception as error:
785
+ raise GenerateError(
786
+ "Expected a compiled specification that is not signed, encrypted, "
787
+ "bound to something or has a nonce, but: {}".format(error)
788
+ )
789
+
790
+ return Generator(compiled, asni, sources or [], codec).run()
File without changes
@@ -0,0 +1,5 @@
1
+ # Copyright (c) 2025 BoxTheta
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ __version__ = "1.0.1"
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.4
2
+ Name: asnkit-gen-python
3
+ Version: 1.0.1
4
+ Summary: asnkit plugin that makes Python code with data classes from ASN.1
5
+ Author: xadaemon
6
+ Author-email: xadaemon <mxavier@boxtheta.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE-COMPILER
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Code Generators
13
+ Requires-Dist: asnkitrt==1.0.1
14
+ Requires-Python: >=3.13
15
+ Project-URL: source, https://github.com/boxtheta/asnkit
16
+ Description-Content-Type: text/x-rst
17
+
18
+ asnkit-gen-python
19
+ =================
20
+
21
+ A plugin for `asnkitcc`_ that generates Python code from ASN.1. The
22
+ generated module imports `asnkitrt`_ and embeds the compiled
23
+ specification as bytes. It has a data class for each ``SEQUENCE`` and
24
+ ``SET``, an enumeration for each ``ENUMERATED`` and a class for each
25
+ alternative of a ``CHOICE``, all with methods to encode and decode.
26
+
27
+ .. code-block:: text
28
+
29
+ $ pip install asnkit-gen-python
30
+ $ asnkitcc generate --plugin python -o out foo.asn # Writes out/foo.py.
31
+
32
+ .. code-block:: python
33
+
34
+ >>> from foo import Question
35
+ >>> encoded = Question(id=1, question='Is 1+1=3?').encode('uper')
36
+ >>> Question.decode(encoded, 'uper')
37
+ Question(id=1, question='Is 1+1=3?')
38
+
39
+ Options, given with ``--plugin-opt KEY=VALUE``:
40
+
41
+ ``name``
42
+ The name of the module, without ``.py``. Default: the name of the
43
+ first ASN.1 file.
44
+
45
+ ``codec``
46
+ The codec used when none is given. Default: ``ber``.
47
+
48
+ Names are converted to Python style: ``fooBar`` becomes ``foo_bar`` and
49
+ a type ``Foo-Bar`` becomes ``FooBar``. If two names end up the same in
50
+ Python, generation fails with an error.
51
+
52
+ .. _asnkitcc: https://crates.io/crates/asnkitcc
53
+
54
+ .. _asnkitrt: https://pypi.org/project/asnkitrt/
55
+
56
+ License
57
+ -------
58
+
59
+ Apache License 2.0 (``LICENSE-COMPILER``). The generated code, with the
60
+ helper code copied into it, is yours to use under terms of your choice,
61
+ as the header of each file it writes says. The generated code depends on
62
+ ``asnkitrt``,
63
+ which is MIT licensed.
@@ -0,0 +1,11 @@
1
+ asnkit_gen_python/__init__.py,sha256=-hHOTKkPIWhYCsTSi8u1o9NkFOZPzb9KqjkziUQ-OhE,302
2
+ asnkit_gen_python/__main__.py,sha256=xiAucIWkcJ2FDPkyYE9H9ERf7FH31VBl3actIbDTxfo,101
3
+ asnkit_gen_python/cli.py,sha256=Tgl2yb74CsihoF8GiY9mq32_XMjP9PtcLANQyhJpY0M,3044
4
+ asnkit_gen_python/generate.py,sha256=FuS8ZStFC3h7Fe4ILUv_J86JRtxPytE5RVYVyoRF4E0,23856
5
+ asnkit_gen_python/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ asnkit_gen_python/version.py,sha256=d8hfbFYDJ0fCZqkABAtCBI1bcRIm-zHO3ToQ5quUyUU,93
7
+ asnkit_gen_python-1.0.1.dist-info/licenses/LICENSE-COMPILER,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
8
+ asnkit_gen_python-1.0.1.dist-info/WHEEL,sha256=9IUYslYuG_asT4WlWvfk_K76nveuLvSTKDoLeL0cV-Q,80
9
+ asnkit_gen_python-1.0.1.dist-info/entry_points.txt,sha256=4tq6qQZh-ExXQSRBx6f8hEMdkjAGEMLs2xCeeMCPDXA,66
10
+ asnkit_gen_python-1.0.1.dist-info/METADATA,sha256=v1zqfLaBczpou1Bg5WKyGlpR_QK9L0nQzm5fQ4lhCVI,2105
11
+ asnkit_gen_python-1.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ asnkit-gen-python = asnkit_gen_python.cli:main
3
+
@@ -0,0 +1,201 @@
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.