]> git.donarmstrong.com Git - kiibohd-kll.git/blob - kll.py
Adding a few more symbolic names.
[kiibohd-kll.git] / kll.py
1 #!/usr/bin/env python3
2 # KLL Compiler
3 # Keyboard Layout Langauge
4 #
5 # Copyright (C) 2014-2015 by Jacob Alexander
6 #
7 # This file is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This file is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this file.  If not, see <http://www.gnu.org/licenses/>.
19
20 ### Imports ###
21
22 import argparse
23 import io
24 import os
25 import re
26 import sys
27 import token
28 import importlib
29
30 from tokenize import generate_tokens
31 from re       import VERBOSE
32 from pprint   import pformat
33
34 from kll_lib.hid_dict   import *
35 from kll_lib.containers import *
36
37 from funcparserlib.lexer  import make_tokenizer, Token, LexerError
38 from funcparserlib.parser import (some, a, many, oneplus, skip, finished, maybe, skip, forward_decl, NoParseError)
39
40
41
42 ### Decorators ###
43
44  ## Print Decorator Variables
45 ERROR = '\033[5;1;31mERROR\033[0m:'
46
47
48  ## Python Text Formatting Fixer...
49  ##  Because the creators of Python are averse to proper capitalization.
50 textFormatter_lookup = {
51         "usage: "            : "Usage: ",
52         "optional arguments" : "Optional Arguments",
53 }
54
55 def textFormatter_gettext( s ):
56         return textFormatter_lookup.get( s, s )
57
58 argparse._ = textFormatter_gettext
59
60
61
62 ### Argument Parsing ###
63
64 def checkFileExists( filename ):
65         if not os.path.isfile( filename ):
66                 print ( "{0} {1} does not exist...".format( ERROR, filename ) )
67                 sys.exit( 1 )
68
69 def processCommandLineArgs():
70         # Setup argument processor
71         pArgs = argparse.ArgumentParser(
72                 usage="%(prog)s [options] <file1>...",
73                 description="Generates .h file state tables and pointer indices from KLL .kll files.",
74                 epilog="Example: {0} mykeyboard.kll -d colemak.kll -p hhkbpro2.kll -p symbols.kll".format( os.path.basename( sys.argv[0] ) ),
75                 formatter_class=argparse.RawTextHelpFormatter,
76                 add_help=False,
77 )
78
79         # Positional Arguments
80         pArgs.add_argument( 'files', type=str, nargs='+',
81                 help=argparse.SUPPRESS ) # Suppressed help output, because Python output is verbosely ugly
82
83         # Optional Arguments
84         pArgs.add_argument( '-b', '--backend', type=str, default="kiibohd",
85                 help="Specify target backend for the KLL compiler.\n"
86                 "Default: kiibohd\n"
87                 "Options: kiibohd, json" )
88         pArgs.add_argument( '-d', '--default', type=str, nargs='+',
89                 help="Specify .kll files to layer on top of the default map to create a combined map." )
90         pArgs.add_argument( '-p', '--partial', type=str, nargs='+', action='append',
91                 help="Specify .kll files to generate partial map, multiple files per flag.\n"
92                 "Each -p defines another partial map.\n"
93                 "Base .kll files (that define the scan code maps) must be defined for each partial map." )
94         pArgs.add_argument( '-t', '--templates', type=str, nargs='+',
95                 help="Specify template used to generate the keymap.\n"
96                 "Default: <backend specific>" )
97         pArgs.add_argument( '-o', '--outputs', type=str, nargs='+',
98                 help="Specify output file. Writes to current working directory by default.\n"
99                 "Default: <backend specific>" )
100         pArgs.add_argument( '-h', '--help', action="help",
101                 help="This message." )
102
103         # Process Arguments
104         args = pArgs.parse_args()
105
106         # Parameters
107         baseFiles = args.files
108         defaultFiles = args.default
109         partialFileSets = args.partial
110         if defaultFiles is None:
111                 defaultFiles = []
112         if partialFileSets is None:
113                 partialFileSets = [[]]
114
115         # Check file existance
116         for filename in baseFiles:
117                 checkFileExists( filename )
118
119         for filename in defaultFiles:
120                 checkFileExists( filename )
121
122         for partial in partialFileSets:
123                 for filename in partial:
124                         checkFileExists( filename )
125
126         return (baseFiles, defaultFiles, partialFileSets, args.backend, args.templates, args.outputs)
127
128
129
130 ### Tokenizer ###
131
132 def tokenize( string ):
133         """str -> Sequence(Token)"""
134
135         # Basic Tokens Spec
136         specs = [
137                 ( 'Comment',          ( r' *#.*', ) ),
138                 ( 'Space',            ( r'[ \t\r\n]+', ) ),
139                 ( 'USBCode',          ( r'U(("[^"]+")|(0x[0-9a-fA-F]+)|([0-9]+))', ) ),
140                 ( 'USBCodeStart',     ( r'U\[', ) ),
141                 ( 'ScanCode',         ( r'S((0x[0-9a-fA-F]+)|([0-9]+))', ) ),
142                 ( 'ScanCodeStart',    ( r'S\[', ) ),
143                 ( 'CodeEnd',          ( r'\]', ) ),
144                 ( 'String',           ( r'"[^"]*"', VERBOSE ) ),
145                 ( 'SequenceString',   ( r"'[^']*'", ) ),
146                 ( 'Operator',         ( r'=>|:\+|:-|:|=', ) ),
147                 ( 'Comma',            ( r',', ) ),
148                 ( 'Dash',             ( r'-', ) ),
149                 ( 'Plus',             ( r'\+', ) ),
150                 ( 'Parenthesis',      ( r'\(|\)', ) ),
151                 ( 'Number',           ( r'-?(0x[0-9a-fA-F]+)|(0|([1-9][0-9]*))', VERBOSE ) ),
152                 ( 'Name',             ( r'[A-Za-z_][A-Za-z_0-9]*', ) ),
153                 ( 'VariableContents', ( r'''[^"' ;:=>()]+''', ) ),
154                 ( 'EndOfLine',        ( r';', ) ),
155         ]
156
157         # Tokens to filter out of the token stream
158         useless = ['Space', 'Comment']
159
160         tokens = make_tokenizer( specs )
161         return [x for x in tokens( string ) if x.type not in useless]
162
163
164
165 ### Parsing ###
166
167  ## Map Arrays
168 macros_map        = Macros()
169 variables_dict    = Variables()
170 capabilities_dict = Capabilities()
171
172
173  ## Parsing Functions
174
175 def make_scanCode( token ):
176         scanCode = int( token[1:], 0 )
177         # Check size, to make sure it's valid
178         if scanCode > 0xFF:
179                 print ( "{0} ScanCode value {1} is larger than 255".format( ERROR, scanCode ) )
180                 raise
181         return scanCode
182
183 def make_usbCode( token ):
184         # If first character is a U, strip
185         if token[0] == "U":
186                 token = token[1:]
187
188         # If using string representation of USB Code, do lookup, case-insensitive
189         if '"' in token:
190                 try:
191                         usbCode = kll_hid_lookup_dictionary[ token[1:-1].upper() ]
192                 except LookupError as err:
193                         print ( "{0} {1} is an invalid USB Code Lookup...".format( ERROR, err ) )
194                         raise
195         else:
196                 usbCode = int( token, 0 )
197
198         # Check size, to make sure it's valid
199         if usbCode > 0xFF:
200                 print ( "{0} USBCode value {1} is larger than 255".format( ERROR, usbCode ) )
201                 raise
202         return usbCode
203
204 def make_seqString( token ):
205         # Shifted Characters, and amount to move by to get non-shifted version
206         # US ANSI
207         shiftCharacters = (
208                 ( "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 0x20 ),
209                 ( "+",       0x12 ),
210                 ( "&(",      0x11 ),
211                 ( "!#$%<>",  0x10 ),
212                 ( "*",       0x0E ),
213                 ( ")",       0x07 ),
214                 ( '"',       0x05 ),
215                 ( ":",       0x01 ),
216                 ( "^",      -0x10 ),
217                 ( "_",      -0x18 ),
218                 ( "{}|",    -0x1E ),
219                 ( "~",      -0x20 ),
220                 ( "@",      -0x32 ),
221                 ( "?",      -0x38 ),
222         )
223
224         listOfLists = []
225         shiftKey = kll_hid_lookup_dictionary["SHIFT"]
226
227         # Creates a list of USB codes from the string: sequence (list) of combos (lists)
228         for char in token[1:-1]:
229                 processedChar = char
230
231                 # Whether or not to create a combo for this sequence with a shift
232                 shiftCombo = False
233
234                 # Depending on the ASCII character, convert to single character or Shift + character
235                 for pair in shiftCharacters:
236                         if char in pair[0]:
237                                 shiftCombo = True
238                                 processedChar = chr( ord( char ) + pair[1] )
239                                 break
240
241                 # Do KLL HID Lookup on non-shifted character
242                 # NOTE: Case-insensitive, which is why the shift must be pre-computed
243                 usbCode = kll_hid_lookup_dictionary[ processedChar.upper() ]
244
245                 # Create Combo for this character, add shift key if shifted
246                 charCombo = []
247                 if shiftCombo:
248                         charCombo = [ [ shiftKey ] ]
249                 charCombo.append( [ usbCode ] )
250
251                 # Add to list of lists
252                 listOfLists.append( charCombo )
253
254         return listOfLists
255
256 def make_string( token ):
257         return token[1:-1]
258
259 def make_unseqString( token ):
260         return token[1:-1]
261
262 def make_number( token ):
263         return int( token, 0 )
264
265   # Range can go from high to low or low to high
266 def make_scanCode_range( rangeVals ):
267         start = rangeVals[0]
268         end   = rangeVals[1]
269
270         # Swap start, end if start is greater than end
271         if start > end:
272                 start, end = end, start
273
274         # Iterate from start to end, and generate the range
275         return list( range( start, end + 1 ) )
276
277   # Range can go from high to low or low to high
278   # Warn on 0-9 (as this does not do what one would expect) TODO
279   # Lookup USB HID tags and convert to a number
280 def make_usbCode_range( rangeVals ):
281         # Check if already integers
282         if isinstance( rangeVals[0], int ):
283                 start = rangeVals[0]
284         else:
285                 start = make_usbCode( rangeVals[0] )
286
287         if isinstance( rangeVals[1], int ):
288                 end = rangeVals[1]
289         else:
290                 end = make_usbCode( rangeVals[1] )
291
292         # Swap start, end if start is greater than end
293         if start > end:
294                 start, end = end, start
295
296         # Iterate from start to end, and generate the range
297         return list( range( start, end + 1 ) )
298         pass
299
300
301  ## Base Rules
302
303 const       = lambda x: lambda _: x
304 unarg       = lambda f: lambda x: f(*x)
305 flatten     = lambda list: sum( list, [] )
306
307 tokenValue  = lambda x: x.value
308 tokenType   = lambda t: some( lambda x: x.type == t ) >> tokenValue
309 operator    = lambda s: a( Token( 'Operator', s ) ) >> tokenValue
310 parenthesis = lambda s: a( Token( 'Parenthesis', s ) ) >> tokenValue
311 eol         = a( Token( 'EndOfLine', ';' ) )
312
313 def listElem( item ):
314         return [ item ]
315
316 def listToTuple( items ):
317         return tuple( items )
318
319   # Flatten only the top layer (list of lists of ...)
320 def oneLayerFlatten( items ):
321         mainList = []
322         for sublist in items:
323                 for item in sublist:
324                         mainList.append( item )
325
326         return mainList
327
328   # Capability arguments may need to be expanded (e.g. 1 16 bit argument needs to be 2 8 bit arguments for the state machine)
329 def capArgExpander( items ):
330         newArgs = []
331         # For each defined argument in the capability definition
332         for arg in range( 0, len( capabilities_dict[ items[0] ][1] ) ):
333                 argLen = capabilities_dict[ items[0] ][1][ arg ][1]
334                 num = items[1][ arg ]
335                 byteForm = num.to_bytes( argLen, byteorder='little' ) # XXX Yes, little endian from how the uC structs work
336
337                 # For each sub-argument, split into byte-sized chunks
338                 for byte in range( 0, argLen ):
339                         newArgs.append( byteForm[ byte ] )
340
341         return tuple( [ items[0], tuple( newArgs ) ] )
342
343   # Expand ranges of values in the 3rd dimension of the list, to a list of 2nd lists
344   # i.e. [ sequence, [ combo, [ range ] ] ] --> [ [ sequence, [ combo ] ], <option 2>, <option 3> ]
345 def optionExpansion( sequences ):
346         expandedSequences = []
347
348         # Total number of combinations of the sequence of combos that needs to be generated
349         totalCombinations = 1
350
351         # List of leaf lists, with number of leaves
352         maxLeafList = []
353
354         # Traverse to the leaf nodes, and count the items in each leaf list
355         for sequence in sequences:
356                 for combo in sequence:
357                         rangeLen = len( combo )
358                         totalCombinations *= rangeLen
359                         maxLeafList.append( rangeLen )
360
361         # Counter list to keep track of which combination is being generated
362         curLeafList = [0] * len( maxLeafList )
363
364         # Generate a list of permuations of the sequence of combos
365         for count in range( 0, totalCombinations ):
366                 expandedSequences.append( [] ) # Prepare list for adding the new combination
367                 position = 0
368
369                 # Traverse sequence of combos to generate permuation
370                 for sequence in sequences:
371                         expandedSequences[ -1 ].append( [] )
372                         for combo in sequence:
373                                 expandedSequences[ -1 ][ -1 ].append( combo[ curLeafList[ position ] ] )
374                                 position += 1
375
376                 # Increment combination tracker
377                 for leaf in range( 0, len( curLeafList ) ):
378                         curLeafList[ leaf ] += 1
379
380                         # Reset this position, increment next position (if it exists), then stop
381                         if curLeafList[ leaf ] >= maxLeafList[ leaf ]:
382                                 curLeafList[ leaf ] = 0
383                                 if leaf + 1 < len( curLeafList ):
384                                         curLeafList[ leaf + 1 ] += 1
385
386         return expandedSequences
387
388
389 # Converts USB Codes into Capabilities
390 def usbCodeToCapability( items ):
391         # Items already converted to variants using optionExpansion
392         for variant in range( 0, len( items ) ):
393                 # Sequence of Combos
394                 for sequence in range( 0, len( items[ variant ] ) ):
395                         for combo in range( 0, len( items[ variant ][ sequence ] ) ):
396                                 # Only convert if an integer, otherwise USB Code doesn't need converting
397                                 if isinstance( items[ variant ][ sequence ][ combo ], int ):
398                                         # Use backend capability name and a single argument
399                                         items[ variant ][ sequence ][ combo ] = tuple( [ backend.usbCodeCapability(), tuple( [ hid_lookup_dictionary[ items[ variant ][ sequence ][ combo ] ] ] ) ] )
400
401         return items
402
403
404  ## Evaluation Rules
405
406 def eval_scanCode( triggers, operator, results ):
407         # Convert to lists of lists of lists to tuples of tuples of tuples
408         # Tuples are non-mutable, and can be used has index items
409         triggers = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in triggers )
410         results  = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in results )
411
412         # Iterate over all combinations of triggers and results
413         for trigger in triggers:
414                 for result in results:
415                         # Append Case
416                         if operator == ":+":
417                                 macros_map.appendScanCode( trigger, result )
418
419                         # Remove Case
420                         elif operator == ":-":
421                                 macros_map.removeScanCode( trigger, result )
422
423                         # Replace Case
424                         elif operator == ":":
425                                 macros_map.replaceScanCode( trigger, result )
426
427 def eval_usbCode( triggers, operator, results ):
428         # Convert to lists of lists of lists to tuples of tuples of tuples
429         # Tuples are non-mutable, and can be used has index items
430         triggers = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in triggers )
431         results  = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in results )
432
433         # Iterate over all combinations of triggers and results
434         for trigger in triggers:
435                 scanCodes = macros_map.lookupUSBCodes( trigger )
436                 for scanCode in scanCodes:
437                         for result in results:
438                                 # Cache assignment until file finishes processing
439                                 macros_map.cacheAssignment( operator, scanCode, result )
440
441 def eval_variable( name, content ):
442         # Content might be a concatenation of multiple data types, convert everything into a single string
443         assigned_content = ""
444         for item in content:
445                 assigned_content += str( item )
446
447         variables_dict.assignVariable( name, assigned_content )
448
449 def eval_capability( name, function, args ):
450         capabilities_dict[ name ] = [ function, args ]
451
452 def eval_define( name, cdefine_name ):
453         variables_dict.defines[ name ] = cdefine_name
454
455 map_scanCode   = unarg( eval_scanCode )
456 map_usbCode    = unarg( eval_usbCode )
457
458 set_variable   = unarg( eval_variable )
459 set_capability = unarg( eval_capability )
460 set_define     = unarg( eval_define )
461
462
463  ## Sub Rules
464
465 usbCode     = tokenType('USBCode') >> make_usbCode
466 scanCode    = tokenType('ScanCode') >> make_scanCode
467 name        = tokenType('Name')
468 number      = tokenType('Number') >> make_number
469 comma       = tokenType('Comma')
470 dash        = tokenType('Dash')
471 plus        = tokenType('Plus')
472 content     = tokenType('VariableContents')
473 string      = tokenType('String') >> make_string
474 unString    = tokenType('String') # When the double quotes are still needed for internal processing
475 seqString   = tokenType('SequenceString') >> make_seqString
476 unseqString = tokenType('SequenceString') >> make_unseqString # For use with variables
477
478   # Code variants
479 code_end = tokenType('CodeEnd')
480
481   # Scan Codes
482 scanCode_start     = tokenType('ScanCodeStart')
483 scanCode_range     = number + skip( dash ) + number >> make_scanCode_range
484 scanCode_listElem  = number >> listElem
485 scanCode_innerList = oneplus( ( scanCode_range | scanCode_listElem ) + skip( maybe( comma ) ) ) >> flatten
486 scanCode_expanded  = skip( scanCode_start ) + scanCode_innerList + skip( code_end )
487 scanCode_elem      = scanCode >> listElem
488 scanCode_combo     = oneplus( ( scanCode_expanded | scanCode_elem ) + skip( maybe( plus ) ) )
489 scanCode_sequence  = oneplus( scanCode_combo + skip( maybe( comma ) ) )
490
491   # USB Codes
492 usbCode_start       = tokenType('USBCodeStart')
493 usbCode_range       = ( number | unString ) + skip( dash ) + ( number | unString ) >> make_usbCode_range
494 usbCode_listElemTag = unString >> make_usbCode
495 usbCode_listElem    = ( number | usbCode_listElemTag ) >> listElem
496 usbCode_innerList   = oneplus( ( usbCode_range | usbCode_listElem ) + skip( maybe( comma ) ) ) >> flatten
497 usbCode_expanded    = skip( usbCode_start ) + usbCode_innerList + skip( code_end )
498 usbCode_elem        = usbCode >> listElem
499 usbCode_combo       = oneplus( ( usbCode_expanded | usbCode_elem ) + skip( maybe( plus ) ) ) >> listElem
500 usbCode_sequence    = oneplus( ( usbCode_combo | seqString ) + skip( maybe( comma ) ) ) >> oneLayerFlatten
501
502   # Capabilities
503 capFunc_arguments = many( number + skip( maybe( comma ) ) ) >> listToTuple
504 capFunc_elem      = name + skip( parenthesis('(') ) + capFunc_arguments + skip( parenthesis(')') ) >> capArgExpander >> listElem
505 capFunc_combo     = oneplus( ( usbCode_expanded | usbCode_elem | capFunc_elem ) + skip( maybe( plus ) ) ) >> listElem
506 capFunc_sequence  = oneplus( ( capFunc_combo | seqString ) + skip( maybe( comma ) ) ) >> oneLayerFlatten
507
508   # Trigger / Result Codes
509 triggerCode_outerList    = scanCode_sequence >> optionExpansion
510 triggerUSBCode_outerList = usbCode_sequence >> optionExpansion >> usbCodeToCapability
511 resultCode_outerList     = capFunc_sequence >> optionExpansion >> usbCodeToCapability
512
513
514  ## Main Rules
515
516 #| <variable> = <variable contents>;
517 variable_contents   = name | content | string | number | comma | dash | unseqString
518 variable_expression = name + skip( operator('=') ) + oneplus( variable_contents ) + skip( eol ) >> set_variable
519
520 #| <capability name> => <c function>;
521 capability_arguments  = name + skip( operator(':') ) + number + skip( maybe( comma ) )
522 capability_expression = name + skip( operator('=>') ) + name + skip( parenthesis('(') ) + many( capability_arguments ) + skip( parenthesis(')') ) + skip( eol ) >> set_capability
523
524 #| <define name> => <c define>;
525 define_expression = name + skip( operator('=>') ) + name + skip( eol ) >> set_define
526
527 #| <trigger> : <result>;
528 operatorTriggerResult = operator(':') | operator(':+') | operator(':-')
529 scanCode_expression   = triggerCode_outerList + operatorTriggerResult + resultCode_outerList + skip( eol ) >> map_scanCode
530 usbCode_expression    = triggerUSBCode_outerList + operatorTriggerResult + resultCode_outerList + skip( eol ) >> map_usbCode
531
532 def parse( tokenSequence ):
533         """Sequence(Token) -> object"""
534
535         # Top-level Parser
536         expression = scanCode_expression | usbCode_expression | variable_expression | capability_expression | define_expression
537
538         kll_text = many( expression )
539         kll_file = maybe( kll_text ) + skip( finished )
540
541         return kll_file.parse( tokenSequence )
542
543
544
545 def processKLLFile( filename ):
546         with open( filename ) as file:
547                 data = file.read()
548                 tokenSequence = tokenize( data )
549                 #print ( pformat( tokenSequence ) ) # Display tokenization
550                 try:
551                         tree = parse( tokenSequence )
552                 except NoParseError as e:
553                         print("Error parsing %s. %s" % (filename, e.msg), file=sys.stderr)
554                         sys.exit(1)
555
556
557 ### Misc Utility Functions ###
558
559 def gitRevision( kllPath ):
560         import subprocess
561
562         # Change the path to where kll.py is
563         origPath = os.getcwd()
564         os.chdir( kllPath )
565
566         # Just in case git can't be found
567         try:
568                 # Get hash of the latest git commit
569                 revision = subprocess.check_output( ['git', 'rev-parse', 'HEAD'] ).decode()[:-1]
570
571                 # Get list of files that have changed since the commit
572                 changed = subprocess.check_output( ['git', 'diff-index', '--name-only', 'HEAD', '--'] ).decode().splitlines()
573         except:
574                 revision = "<no git>"
575                 changed = []
576
577         # Change back to the old working directory
578         os.chdir( origPath )
579
580         return revision, changed
581
582
583 ### Main Entry Point ###
584
585 if __name__ == '__main__':
586         (baseFiles, defaultFiles, partialFileSets, backend_name, templates, outputs) = processCommandLineArgs()
587
588         # Look up git information on the compiler
589         gitRev, gitChanges = gitRevision( os.path.dirname( os.path.realpath( __file__ ) ) )
590
591         # Load backend module
592         global backend
593         backend_import = importlib.import_module( "backends.{0}".format( backend_name ) )
594         backend = backend_import.Backend( templates )
595
596         # Process base layout files
597         for filename in baseFiles:
598                 variables_dict.setCurrentFile( filename )
599                 processKLLFile( filename )
600         macros_map.completeBaseLayout() # Indicates to macros_map that the base layout is complete
601         variables_dict.baseLayoutFinished()
602
603         # Default combined layer
604         for filename in defaultFiles:
605                 variables_dict.setCurrentFile( filename )
606                 processKLLFile( filename )
607                 # Apply assignment cache, see 5.1.2 USB Codes for why this is necessary
608                 macros_map.replayCachedAssignments()
609
610         # Iterate through additional layers
611         for partial in partialFileSets:
612                 # Increment layer for each -p option
613                 macros_map.addLayer()
614                 variables_dict.incrementLayer() # DefaultLayer is layer 0
615
616                 # Iterate and process each of the file in the layer
617                 for filename in partial:
618                         variables_dict.setCurrentFile( filename )
619                         processKLLFile( filename )
620
621                 # Apply assignment cache, see 5.1.2 USB Codes for why this is necessary
622                 macros_map.replayCachedAssignments()
623                 # Remove un-marked keys to complete the partial layer
624                 macros_map.removeUnmarked()
625
626         # Do macro correlation and transformation
627         macros_map.generate()
628
629         # Process needed templating variables using backend
630         backend.process(
631                 capabilities_dict,
632                 macros_map,
633                 variables_dict,
634                 gitRev,
635                 gitChanges
636         )
637
638         # Generate output file using template and backend
639         backend.generate( outputs )
640
641         # Successful Execution
642         sys.exit( 0 )
643