learn_CHOICE_enums.py 1.56 KB
Newer Older
1
2
3
#!/usr/bin/env python2
import os
import sys
4
choices = []
5
enums = []
6
7
8
9
10
11
12
13
14
bEnum = False

''' Parse the ASN.1-generated header file and extract the constants used for
CHOICE determinants (#define det..._PRESENT) and ENUMERATED values
Emit strings that are appended to DV.py from Makefile.python
There is no name clash thanks to the rename policy of the ASN.1 compiler
(a constant cannot be defined twice)
'''

15
16
for line in open(sys.argv[1] + '.h', 'r'):
    if '_PRESENT' in line and not line.startswith('#define'):
17
        choices.append(line.strip().replace(",", ""))
18
        bEnum = False
19
20
21
22
    elif line.strip().startswith('typedef enum {'):
        bEnum = True
    elif line.strip().startswith('}') and bEnum:
        bEnum = False
23
24
    elif '_NONE' in line or '_PRESENT' in line:
        bEnum = False
25
26
27
    elif bEnum:
        enums.append(line.strip().replace(",", "").split("="))

28
enums_dump = "\n    ".join(
29
    'printf("%s = %%d\\n", %s);' % (e, e)
30
31
32
33
34
35
    for e in choices
)

enums_dump += "\n    ".join(
    'printf("%s = %d\\n");' % (name.strip(), int(val))
    for name, val in enums
36
37
)
uniq = os.getpid()
38
extractor_filename = "/tmp/enums_%d" % uniq
39
40
41
42
43
44
45
46
f = open(extractor_filename + ".c", 'w')
f.write("""
#include <stdio.h>
#include "%(base)s.h"

void main()
{
%(enums_dump)s
47
}""" % {"enums_dump": enums_dump, "base": sys.argv[1]})
48
f.close()
49
50
cmd = "gcc -o %s -I. %s.c" % (extractor_filename, extractor_filename)
if os.system(cmd) != 0:
51
    print("Failed to extract CHOICE enum values...")
52
53
54
55
    sys.exit(1)
os.system(extractor_filename)
os.unlink(extractor_filename + ".c")
os.unlink(extractor_filename)