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