lint_asn1.py 8.64 KB
Newer Older
canterburym's avatar
canterburym committed
1
2
3
4
5
6
7
8
9
10
import logging

from asn1tools import parse_files, compile_dict, ParseError, CompileError
from glob import glob
from pathlib import Path
import string

from pprint import pprint
import functools

canterburym's avatar
canterburym committed
11
12
import lintingexceptions

canterburym's avatar
canterburym committed
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

moduleLevelTests = []
typeLevelTests = []
fileLevelTests = []


def lintingTest (testName, testKind, testDescription):
    def decorate (func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            logging.debug (f"    Running test {testName}")
            errors = func(*args, **kwargs)
            for error in errors:
                error['testName'] = testName
                error['testKind'] = testKind
                error['testDescription'] = testDescription
            return errors
        if (testKind == "type"):
            typeLevelTests.append(wrapper)
        if (testKind == "module"):
            moduleLevelTests.append(wrapper)
        if (testKind == "file"):
            fileLevelTests.append(wrapper)
        return wrapper
    return decorate



def formatFailure(f):
42
    return f"{f['testName'] if f.get('testName') else 'Failure'}: {f['message']}"
canterburym's avatar
canterburym committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119


def appendFailure(failures, context, newFailure):
    combinedFailure = {**context, **newFailure}
    logging.info (f"Test Failure: {combinedFailure}")
    failures.append(combinedFailure)


#--------------------------------------------------------------------
# File level tests
#--------------------------------------------------------------------

@lintingTest(testName = "D.4.9", 
             testKind = "file", 
             testDescription = "Fields, tags, types and flags are space aligned")
def D41 (fileLines, context):
    errors = []
    for lineNumber, line in enumerate(fileLines):
        if '\t' in line:
            appendFailure(errors, context, { "line" : lineNumber,
                "message" : f"Line {lineNumber} contains tab characters"})
    return errors


@lintingTest(testName = "D.4.11", 
             testKind = "file", 
             testDescription = "Braces are given their own line")
def D41 (fileLines, context):
    errors = []
    for lineNumber, line in enumerate(fileLines):
        if ('{' in line and line.strip().replace(",","") != '{') or ('}' in line and line.strip().replace(",","") != '}'):
            if "itu-t(0)" in line: continue
            if "OBJECT IDENTIFIER" in line: continue
            if "RELATIVE-OID" in line: continue
            appendFailure(errors, context, { "line" : lineNumber + 1,
                "message" : f"Line {lineNumber + 1} contains a brace but also other characters ('{line}')"})
    return errors


#--------------------------------------------------------------------
# Module level tests
#--------------------------------------------------------------------

@lintingTest(testName = "D.4.1", 
             testKind = "module", 
             testDescription = "EXTENSIBILITY IMPLIED directive set")
def D41 (module, context):
    errors = []
    if (not ('extensibility-implied' in module.keys()) or (module['extensibility-implied'] == False)):
        appendFailure(errors, context, {"message" : "EXTENSIBILITY IMPLIED directive not set"})
    return errors


@lintingTest(testName = "D.4.2", 
             testKind = "module", 
             testDescription = "AUTOMATIC TAGS not used")
def D42(module, context):
    errors = []
    if (module['tags'] == 'AUTOMATIC'):
        appendFailure(errors, context, {"message" : "AUTOMATIC TAGS directive used"})
    return errors


#--------------------------------------------------------------------
# Type level tests
#--------------------------------------------------------------------

@lintingTest(testName = "D.3.4", 
             testKind = "type", 
             testDescription = "Field names only contain characters A-Z, a-z, 0-9")
def D34(t, context):
    if not 'members' in t.keys(): 
        logging.debug (f"      D34 ignoring {context['module']} '{context['type']}' as it has no members")
        return []
    errors = []
    for m in t['members']:
        logging.debug (f"      D34 checking member {m}")
120
121
122
        if not m:
            logging.debug ("       (appears to be None, ignoring)")
            continue
canterburym's avatar
canterburym committed
123
124
125
126
127
128
129
130
131
132
133
134
135
        badLetters = list(set([letter for letter in m['name'] if not ((letter in string.ascii_letters) or (letter in string.digits)) ]))
        if len(badLetters) > 0:
            appendFailure (errors, context, { "field" : m['name'],
                "message" : f"Field '{m['name']}' contains disallowed characters {badLetters!r}"})
    return errors


@lintingTest(testName = "D.4.3", 
             testKind = "type", 
             testDescription = "Tag numbers start at zero")
def D43 (t, context):
    errors = []
    if (t['type'] == 'SEQUENCE') or (t['type'] == 'CHOICE'):
136
137
        if not 'tag' in t['members'][0]:
            return errors
canterburym's avatar
canterburym committed
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
        if t['members'][0]['tag']['number'] != 1:
            appendFailure (errors, context, {"message" : f"Tag numbers for {context['type']} start at {t['members'][0]['tag']['number']}, not 1"})
    return errors


@lintingTest(testName = "D.4.4", 
             testKind = "type", 
             testDescription = "Enumerations start at zero")
def D44 (t, context):
    errors = []
    if t['type'] == 'ENUMERATED':
        if t['values'][0][1] != 1:
            appendFailure(errors, context, { "message" : f"Enumerations for {context['type']} start at {t['values'][0][1]}, not 1"})
    return errors


@lintingTest(testName = "D.4.5", 
             testKind = "type", 
             testDescription = "No anonymous types")
def checkD45 (t, context):
    if not 'members' in t: 
        logging.debug (f"      D45: No members in type {context['type']}, ignoring")
        return []
    errors = []
    for m in t['members']:
163
        if not m: continue
canterburym's avatar
canterburym committed
164
165
166
167
168
169
170
        if m['type'] in ['ENUMERATED','SEQUENCE','CHOICE', 'SET']:
            appendFailure(errors, context, { "field" : m['name'],
                "message" : f"Field '{m['name']}' in {context['type']} is an anonymous {m['type']}"})
    return errors


def lintASN1File (asnFile):
171
    print (f"File: {asnFile}")
canterburym's avatar
canterburym committed
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
    errors = []
    context = {'file' : asnFile}
    try:
        logging.info ("Checking file {0}...".format(asnFile))
        with open(asnFile) as f:
            s = f.read().splitlines()
        for test in fileLevelTests:
            errors += test(s, context)
        d = parse_files(asnFile)
        for moduleName, module in d.items():
            logging.info ("  Checking module {0}".format(moduleName))            
            for test in moduleLevelTests:
                context['module'] = moduleName
                errors += test(module, context)
            for typeName, typeDef in module['types'].items():
                context['type'] = typeName
                context['module'] = moduleName
                for test in typeLevelTests:
                    errors += test(typeDef, context)
    except ParseError as ex:
192
        appendFailure(errors, context, { "message" : "ParseError: {0}".format(ex)})
canterburym's avatar
canterburym committed
193
194
195
196
197
198
199
        logging.error("ParseError: {0}".format(ex))
    return errors


def lintASN1Files (fileList):
    if len(fileList) == 0:
        logging.warning ("No files specified")
canterburym's avatar
canterburym committed
200
        return {}
canterburym's avatar
canterburym committed
201
202
203
204

    errorMap = {}
    logging.info("Checking files...")
    for f in fileList:
205
        errorMap[str(f)] = lintASN1File(str(f))
canterburym's avatar
canterburym committed
206
207
208
    return errorMap


209
210
211
ignoreReleases = {'33108' : [f'r{i}' for i in range(5, 17)],
                  '33128' : [] }

canterburym's avatar
canterburym committed
212
def lintAllASN1FilesInPath (path):
213
214
215
216
217
218
219
220
221
    fileList = list(Path(path).rglob("*.asn1")) + list(Path(path).rglob("*.asn"))

    ignoredFiles = [file for file in fileList if file.parts[1] in ignoreReleases[file.parts[0]]]
    logging.info(f"Ignoring {len(ignoredFiles)} files")
    logging.debug(ignoredFiles)
    
    fileList = [file for file in fileList if file not in ignoredFiles]

    return lintASN1Files(fileList)    
canterburym's avatar
canterburym committed
222
223
224
225

if __name__ == '__main__':
    result = lintAllASN1FilesInPath("./")
    totalErrors = 0
canterburym's avatar
canterburym committed
226
    totalSuppressed = 0
canterburym's avatar
canterburym committed
227
228
    print ("Drafting rule checks:")
    print ("-----------------------------")
canterburym's avatar
canterburym committed
229
230
231
232
233
    for filename, results in result.items():
        errors = [r for r in results if not (formatFailure(r) in lintingexceptions.exceptedStrings)]
        suppressedErrors = [r for r in results if formatFailure(r) in lintingexceptions.exceptedStrings]
        print (f"{filename}: {'OK' if len(errors) == 0 else f'{len(errors)} errors detected'}")
        for error in errors:
canterburym's avatar
canterburym committed
234
            print("  " + formatFailure(error))
canterburym's avatar
canterburym committed
235
236
        for error in suppressedErrors:
            print(" (" + formatFailure(error) + " - suppressed)")
canterburym's avatar
canterburym committed
237
        totalErrors += len(errors)
canterburym's avatar
canterburym committed
238
        totalSuppressed += len(suppressedErrors)
canterburym's avatar
canterburym committed
239
240

    print ("-----------------------------")
canterburym's avatar
canterburym committed
241
    print (f"{totalErrors} non-compliances detected, {totalSuppressed} errors suppressed")
canterburym's avatar
canterburym committed
242
    exit(totalErrors)