KLL Compiler
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

kll.py 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. #!/usr/bin/env python3
  2. # KLL Compiler
  3. # Keyboard Layout Langauge
  4. #
  5. # Copyright (C) 2014 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. ### Imports ###
  20. import argparse
  21. import io
  22. import os
  23. import re
  24. import sys
  25. import token
  26. import importlib
  27. from tokenize import generate_tokens
  28. from re import VERBOSE
  29. from pprint import pformat
  30. from kll_lib.hid_dict import *
  31. from kll_lib.containers import *
  32. from funcparserlib.lexer import make_tokenizer, Token, LexerError
  33. from funcparserlib.parser import (some, a, many, oneplus, skip, finished, maybe, skip, forward_decl, NoParseError)
  34. ### Decorators ###
  35. ## Print Decorator Variables
  36. ERROR = '\033[5;1;31mERROR\033[0m:'
  37. ## Python Text Formatting Fixer...
  38. ## Because the creators of Python are averse to proper capitalization.
  39. textFormatter_lookup = {
  40. "usage: " : "Usage: ",
  41. "optional arguments" : "Optional Arguments",
  42. }
  43. def textFormatter_gettext( s ):
  44. return textFormatter_lookup.get( s, s )
  45. argparse._ = textFormatter_gettext
  46. ### Argument Parsing ###
  47. def checkFileExists( filename ):
  48. if not os.path.isfile( filename ):
  49. print ( "{0} {1} does not exist...".format( ERROR, filename ) )
  50. sys.exit( 1 )
  51. def processCommandLineArgs():
  52. # Setup argument processor
  53. pArgs = argparse.ArgumentParser(
  54. usage="%(prog)s [options] <file1>...",
  55. description="Generates .h file state tables and pointer indices from KLL .kll files.",
  56. epilog="Example: {0} mykeyboard.kll -d colemak.kll -p hhkbpro2.kll -p symbols.kll".format( os.path.basename( sys.argv[0] ) ),
  57. formatter_class=argparse.RawTextHelpFormatter,
  58. add_help=False,
  59. )
  60. # Positional Arguments
  61. pArgs.add_argument( 'files', type=str, nargs='+',
  62. help=argparse.SUPPRESS ) # Suppressed help output, because Python output is verbosely ugly
  63. # Optional Arguments
  64. pArgs.add_argument( '-b', '--backend', type=str, default="kiibohd",
  65. help="Specify target backend for the KLL compiler.\n"
  66. "Default: kiibohd" )
  67. pArgs.add_argument( '-d', '--default', type=str, nargs='+',
  68. help="Specify .kll files to layer on top of the default map to create a combined map." )
  69. pArgs.add_argument( '-p', '--partial', type=str, nargs='+', action='append',
  70. help="Specify .kll files to generate partial map, multiple files per flag.\n"
  71. "Each -p defines another partial map.\n"
  72. "Base .kll files (that define the scan code maps) must be defined for each partial map." )
  73. pArgs.add_argument( '-t', '--template', type=str, default="templates/kiibohdKeymap.h",
  74. help="Specify template used to generate the keymap.\n"
  75. "Default: templates/kiibohdKeymap.h" )
  76. pArgs.add_argument( '--defines-template', type=str, default="templates/kiibohdDefs.h",
  77. help="Specify template used to generate kll_defs.h.\n"
  78. "Default: templates/kiibohdDefs.h" )
  79. pArgs.add_argument( '-o', '--output', type=str, default="generatedKeymap.h",
  80. help="Specify output file. Writes to current working directory by default.\n"
  81. "Default: generatedKeymap.h" )
  82. pArgs.add_argument( '--defines-output', type=str, default="kll_defs.h",
  83. help="Specify output path for kll_defs.h. Writes to current working directory by default.\n"
  84. "Default: kll_defs.h" )
  85. pArgs.add_argument( '-h', '--help', action="help",
  86. help="This message." )
  87. # Process Arguments
  88. args = pArgs.parse_args()
  89. # Parameters
  90. baseFiles = args.files
  91. defaultFiles = args.default
  92. partialFileSets = args.partial
  93. if defaultFiles is None:
  94. defaultFiles = []
  95. if partialFileSets is None:
  96. partialFileSets = [[]]
  97. # Check file existance
  98. for filename in baseFiles:
  99. checkFileExists( filename )
  100. for filename in defaultFiles:
  101. checkFileExists( filename )
  102. for partial in partialFileSets:
  103. for filename in partial:
  104. checkFileExists( filename )
  105. return (baseFiles, defaultFiles, partialFileSets, args.backend, args.template, args.defines_template, args.output, args.defines_output)
  106. ### Tokenizer ###
  107. def tokenize( string ):
  108. """str -> Sequence(Token)"""
  109. # Basic Tokens Spec
  110. specs = [
  111. ( 'Comment', ( r' *#.*', ) ),
  112. ( 'Space', ( r'[ \t\r\n]+', ) ),
  113. ( 'USBCode', ( r'U(("[^"]+")|(0x[0-9a-fA-F]+)|([0-9]+))', ) ),
  114. ( 'USBCodeStart', ( r'U\[', ) ),
  115. ( 'ScanCode', ( r'S((0x[0-9a-fA-F]+)|([0-9]+))', ) ),
  116. ( 'ScanCodeStart', ( r'S\[', ) ),
  117. ( 'CodeEnd', ( r'\]', ) ),
  118. ( 'String', ( r'"[^"]*"', VERBOSE ) ),
  119. ( 'SequenceString', ( r"'[^']*'", ) ),
  120. ( 'Operator', ( r'=>|:\+|:-|:|=', ) ),
  121. ( 'Comma', ( r',', ) ),
  122. ( 'Dash', ( r'-', ) ),
  123. ( 'Plus', ( r'\+', ) ),
  124. ( 'Parenthesis', ( r'\(|\)', ) ),
  125. ( 'Number', ( r'-?(0x[0-9a-fA-F]+)|(0|([1-9][0-9]*))', VERBOSE ) ),
  126. ( 'Name', ( r'[A-Za-z_][A-Za-z_0-9]*', ) ),
  127. ( 'VariableContents', ( r'''[^"' ;:=>()]+''', ) ),
  128. ( 'EndOfLine', ( r';', ) ),
  129. ]
  130. # Tokens to filter out of the token stream
  131. useless = ['Space', 'Comment']
  132. tokens = make_tokenizer( specs )
  133. return [x for x in tokens( string ) if x.type not in useless]
  134. ### Parsing ###
  135. ## Map Arrays
  136. macros_map = Macros()
  137. variables_dict = Variables()
  138. capabilities_dict = Capabilities()
  139. ## Parsing Functions
  140. def make_scanCode( token ):
  141. scanCode = int( token[1:], 0 )
  142. # Check size, to make sure it's valid
  143. if scanCode > 0xFF:
  144. print ( "{0} ScanCode value {1} is larger than 255".format( ERROR, scanCode ) )
  145. raise
  146. return scanCode
  147. def make_usbCode( token ):
  148. # If first character is a U, strip
  149. if token[0] == "U":
  150. token = token[1:]
  151. # If using string representation of USB Code, do lookup, case-insensitive
  152. if '"' in token:
  153. try:
  154. usbCode = kll_hid_lookup_dictionary[ token[1:-1].upper() ]
  155. except LookupError as err:
  156. print ( "{0} {1} is an invalid USB Code Lookup...".format( ERROR, err ) )
  157. raise
  158. else:
  159. usbCode = int( token, 0 )
  160. # Check size, to make sure it's valid
  161. if usbCode > 0xFF:
  162. print ( "{0} USBCode value {1} is larger than 255".format( ERROR, usbCode ) )
  163. raise
  164. return usbCode
  165. def make_seqString( token ):
  166. # Shifted Characters, and amount to move by to get non-shifted version
  167. # US ANSI
  168. shiftCharacters = (
  169. ( "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 0x20 ),
  170. ( "+", 0x12 ),
  171. ( "&(", 0x11 ),
  172. ( "!#$%<>", 0x10 ),
  173. ( "*", 0x0E ),
  174. ( ")", 0x07 ),
  175. ( '"', 0x05 ),
  176. ( ":", 0x01 ),
  177. ( "^", -0x10 ),
  178. ( "_", -0x18 ),
  179. ( "{}|", -0x1E ),
  180. ( "~", -0x20 ),
  181. ( "@", -0x32 ),
  182. ( "?", -0x38 ),
  183. )
  184. listOfLists = []
  185. shiftKey = kll_hid_lookup_dictionary["SHIFT"]
  186. # Creates a list of USB codes from the string: sequence (list) of combos (lists)
  187. for char in token[1:-1]:
  188. processedChar = char
  189. # Whether or not to create a combo for this sequence with a shift
  190. shiftCombo = False
  191. # Depending on the ASCII character, convert to single character or Shift + character
  192. for pair in shiftCharacters:
  193. if char in pair[0]:
  194. shiftCombo = True
  195. processedChar = chr( ord( char ) + pair[1] )
  196. break
  197. # Do KLL HID Lookup on non-shifted character
  198. # NOTE: Case-insensitive, which is why the shift must be pre-computed
  199. usbCode = kll_hid_lookup_dictionary[ processedChar.upper() ]
  200. # Create Combo for this character, add shift key if shifted
  201. charCombo = []
  202. if shiftCombo:
  203. charCombo = [ [ shiftKey ] ]
  204. charCombo.append( [ usbCode ] )
  205. # Add to list of lists
  206. listOfLists.append( charCombo )
  207. return listOfLists
  208. def make_string( token ):
  209. return token[1:-1]
  210. def make_unseqString( token ):
  211. return token[1:-1]
  212. def make_number( token ):
  213. return int( token, 0 )
  214. # Range can go from high to low or low to high
  215. def make_scanCode_range( rangeVals ):
  216. start = rangeVals[0]
  217. end = rangeVals[1]
  218. # Swap start, end if start is greater than end
  219. if start > end:
  220. start, end = end, start
  221. # Iterate from start to end, and generate the range
  222. return list( range( start, end + 1 ) )
  223. # Range can go from high to low or low to high
  224. # Warn on 0-9 (as this does not do what one would expect) TODO
  225. # Lookup USB HID tags and convert to a number
  226. def make_usbCode_range( rangeVals ):
  227. # Check if already integers
  228. if isinstance( rangeVals[0], int ):
  229. start = rangeVals[0]
  230. else:
  231. start = make_usbCode( rangeVals[0] )
  232. if isinstance( rangeVals[1], int ):
  233. end = rangeVals[1]
  234. else:
  235. end = make_usbCode( rangeVals[1] )
  236. # Swap start, end if start is greater than end
  237. if start > end:
  238. start, end = end, start
  239. # Iterate from start to end, and generate the range
  240. return list( range( start, end + 1 ) )
  241. pass
  242. ## Base Rules
  243. const = lambda x: lambda _: x
  244. unarg = lambda f: lambda x: f(*x)
  245. flatten = lambda list: sum( list, [] )
  246. tokenValue = lambda x: x.value
  247. tokenType = lambda t: some( lambda x: x.type == t ) >> tokenValue
  248. operator = lambda s: a( Token( 'Operator', s ) ) >> tokenValue
  249. parenthesis = lambda s: a( Token( 'Parenthesis', s ) ) >> tokenValue
  250. eol = a( Token( 'EndOfLine', ';' ) )
  251. def listElem( item ):
  252. return [ item ]
  253. def listToTuple( items ):
  254. return tuple( items )
  255. # Flatten only the top layer (list of lists of ...)
  256. def oneLayerFlatten( items ):
  257. mainList = []
  258. for sublist in items:
  259. for item in sublist:
  260. mainList.append( item )
  261. return mainList
  262. # Capability arguments may need to be expanded (e.g. 1 16 bit argument needs to be 2 8 bit arguments for the state machine)
  263. def capArgExpander( items ):
  264. newArgs = []
  265. # For each defined argument in the capability definition
  266. for arg in range( 0, len( capabilities_dict[ items[0] ][1] ) ):
  267. argLen = capabilities_dict[ items[0] ][1][ arg ][1]
  268. num = items[1][ arg ]
  269. byteForm = num.to_bytes( argLen, byteorder='little' ) # XXX Yes, little endian from how the uC structs work
  270. # For each sub-argument, split into byte-sized chunks
  271. for byte in range( 0, argLen ):
  272. newArgs.append( byteForm[ byte ] )
  273. return tuple( [ items[0], tuple( newArgs ) ] )
  274. # Expand ranges of values in the 3rd dimension of the list, to a list of 2nd lists
  275. # i.e. [ sequence, [ combo, [ range ] ] ] --> [ [ sequence, [ combo ] ], <option 2>, <option 3> ]
  276. def optionExpansion( sequences ):
  277. expandedSequences = []
  278. # Total number of combinations of the sequence of combos that needs to be generated
  279. totalCombinations = 1
  280. # List of leaf lists, with number of leaves
  281. maxLeafList = []
  282. # Traverse to the leaf nodes, and count the items in each leaf list
  283. for sequence in sequences:
  284. for combo in sequence:
  285. rangeLen = len( combo )
  286. totalCombinations *= rangeLen
  287. maxLeafList.append( rangeLen )
  288. # Counter list to keep track of which combination is being generated
  289. curLeafList = [0] * len( maxLeafList )
  290. # Generate a list of permuations of the sequence of combos
  291. for count in range( 0, totalCombinations ):
  292. expandedSequences.append( [] ) # Prepare list for adding the new combination
  293. position = 0
  294. # Traverse sequence of combos to generate permuation
  295. for sequence in sequences:
  296. expandedSequences[ -1 ].append( [] )
  297. for combo in sequence:
  298. expandedSequences[ -1 ][ -1 ].append( combo[ curLeafList[ position ] ] )
  299. position += 1
  300. # Increment combination tracker
  301. for leaf in range( 0, len( curLeafList ) ):
  302. curLeafList[ leaf ] += 1
  303. # Reset this position, increment next position (if it exists), then stop
  304. if curLeafList[ leaf ] >= maxLeafList[ leaf ]:
  305. curLeafList[ leaf ] = 0
  306. if leaf + 1 < len( curLeafList ):
  307. curLeafList[ leaf + 1 ] += 1
  308. return expandedSequences
  309. # Converts USB Codes into Capabilities
  310. def usbCodeToCapability( items ):
  311. # Items already converted to variants using optionExpansion
  312. for variant in range( 0, len( items ) ):
  313. # Sequence of Combos
  314. for sequence in range( 0, len( items[ variant ] ) ):
  315. for combo in range( 0, len( items[ variant ][ sequence ] ) ):
  316. # Only convert if an integer, otherwise USB Code doesn't need converting
  317. if isinstance( items[ variant ][ sequence ][ combo ], int ):
  318. # Use backend capability name and a single argument
  319. items[ variant ][ sequence ][ combo ] = tuple( [ backend.usbCodeCapability(), tuple( [ items[ variant ][ sequence ][ combo ] ] ) ] )
  320. return items
  321. ## Evaluation Rules
  322. def eval_scanCode( triggers, operator, results ):
  323. # Convert to lists of lists of lists to tuples of tuples of tuples
  324. # Tuples are non-mutable, and can be used has index items
  325. triggers = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in triggers )
  326. results = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in results )
  327. # Iterate over all combinations of triggers and results
  328. for trigger in triggers:
  329. for result in results:
  330. # Append Case
  331. if operator == ":+":
  332. macros_map.appendScanCode( trigger, result )
  333. # Remove Case
  334. elif operator == ":-":
  335. macros_map.removeScanCode( trigger, result )
  336. # Replace Case
  337. elif operator == ":":
  338. macros_map.replaceScanCode( trigger, result )
  339. def eval_usbCode( triggers, operator, results ):
  340. # Convert to lists of lists of lists to tuples of tuples of tuples
  341. # Tuples are non-mutable, and can be used has index items
  342. triggers = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in triggers )
  343. results = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in results )
  344. # Iterate over all combinations of triggers and results
  345. for trigger in triggers:
  346. scanCodes = macros_map.lookupUSBCodes( trigger )
  347. for scanCode in scanCodes:
  348. for result in results:
  349. # Cache assignment until file finishes processing
  350. macros_map.cacheAssignment( operator, scanCode, result )
  351. def eval_variable( name, content ):
  352. # Content might be a concatenation of multiple data types, convert everything into a single string
  353. assigned_content = ""
  354. for item in content:
  355. assigned_content += str( item )
  356. variables_dict.assignVariable( name, assigned_content )
  357. def eval_capability( name, function, args ):
  358. capabilities_dict[ name ] = [ function, args ]
  359. def eval_define( name, cdefine_name ):
  360. variables_dict.defines[ name ] = cdefine_name
  361. map_scanCode = unarg( eval_scanCode )
  362. map_usbCode = unarg( eval_usbCode )
  363. set_variable = unarg( eval_variable )
  364. set_capability = unarg( eval_capability )
  365. set_define = unarg( eval_define )
  366. ## Sub Rules
  367. usbCode = tokenType('USBCode') >> make_usbCode
  368. scanCode = tokenType('ScanCode') >> make_scanCode
  369. name = tokenType('Name')
  370. number = tokenType('Number') >> make_number
  371. comma = tokenType('Comma')
  372. dash = tokenType('Dash')
  373. plus = tokenType('Plus')
  374. content = tokenType('VariableContents')
  375. string = tokenType('String') >> make_string
  376. unString = tokenType('String') # When the double quotes are still needed for internal processing
  377. seqString = tokenType('SequenceString') >> make_seqString
  378. unseqString = tokenType('SequenceString') >> make_unseqString # For use with variables
  379. # Code variants
  380. code_end = tokenType('CodeEnd')
  381. # Scan Codes
  382. scanCode_start = tokenType('ScanCodeStart')
  383. scanCode_range = number + skip( dash ) + number >> make_scanCode_range
  384. scanCode_listElem = number >> listElem
  385. scanCode_innerList = oneplus( ( scanCode_range | scanCode_listElem ) + skip( maybe( comma ) ) ) >> flatten
  386. scanCode_expanded = skip( scanCode_start ) + scanCode_innerList + skip( code_end )
  387. scanCode_elem = scanCode >> listElem
  388. scanCode_combo = oneplus( ( scanCode_expanded | scanCode_elem ) + skip( maybe( plus ) ) )
  389. scanCode_sequence = oneplus( scanCode_combo + skip( maybe( comma ) ) )
  390. # USB Codes
  391. usbCode_start = tokenType('USBCodeStart')
  392. usbCode_range = ( number | unString ) + skip( dash ) + ( number | unString ) >> make_usbCode_range
  393. usbCode_listElemTag = unString >> make_usbCode
  394. usbCode_listElem = ( number | usbCode_listElemTag ) >> listElem
  395. usbCode_innerList = oneplus( ( usbCode_range | usbCode_listElem ) + skip( maybe( comma ) ) ) >> flatten
  396. usbCode_expanded = skip( usbCode_start ) + usbCode_innerList + skip( code_end )
  397. usbCode_elem = usbCode >> listElem
  398. usbCode_combo = oneplus( ( usbCode_expanded | usbCode_elem ) + skip( maybe( plus ) ) ) >> listElem
  399. usbCode_sequence = oneplus( ( usbCode_combo | seqString ) + skip( maybe( comma ) ) ) >> oneLayerFlatten
  400. # Capabilities
  401. capFunc_arguments = many( number + skip( maybe( comma ) ) ) >> listToTuple
  402. capFunc_elem = name + skip( parenthesis('(') ) + capFunc_arguments + skip( parenthesis(')') ) >> capArgExpander >> listElem
  403. capFunc_combo = oneplus( ( usbCode_expanded | usbCode_elem | capFunc_elem ) + skip( maybe( plus ) ) ) >> listElem
  404. capFunc_sequence = oneplus( ( capFunc_combo | seqString ) + skip( maybe( comma ) ) ) >> oneLayerFlatten
  405. # Trigger / Result Codes
  406. triggerCode_outerList = scanCode_sequence >> optionExpansion
  407. triggerUSBCode_outerList = usbCode_sequence >> optionExpansion >> usbCodeToCapability
  408. resultCode_outerList = capFunc_sequence >> optionExpansion >> usbCodeToCapability
  409. ## Main Rules
  410. #| <variable> = <variable contents>;
  411. variable_contents = name | content | string | number | comma | dash | unseqString
  412. variable_expression = name + skip( operator('=') ) + oneplus( variable_contents ) + skip( eol ) >> set_variable
  413. #| <capability name> => <c function>;
  414. capability_arguments = name + skip( operator(':') ) + number + skip( maybe( comma ) )
  415. capability_expression = name + skip( operator('=>') ) + name + skip( parenthesis('(') ) + many( capability_arguments ) + skip( parenthesis(')') ) + skip( eol ) >> set_capability
  416. #| <define name> => <c define>;
  417. define_expression = name + skip( operator('=>') ) + name + skip( eol ) >> set_define
  418. #| <trigger> : <result>;
  419. operatorTriggerResult = operator(':') | operator(':+') | operator(':-')
  420. scanCode_expression = triggerCode_outerList + operatorTriggerResult + resultCode_outerList + skip( eol ) >> map_scanCode
  421. usbCode_expression = triggerUSBCode_outerList + operatorTriggerResult + resultCode_outerList + skip( eol ) >> map_usbCode
  422. def parse( tokenSequence ):
  423. """Sequence(Token) -> object"""
  424. # Top-level Parser
  425. expression = scanCode_expression | usbCode_expression | variable_expression | capability_expression | define_expression
  426. kll_text = many( expression )
  427. kll_file = maybe( kll_text ) + skip( finished )
  428. return kll_file.parse( tokenSequence )
  429. def processKLLFile( filename ):
  430. with open( filename ) as file:
  431. data = file.read()
  432. tokenSequence = tokenize( data )
  433. #print ( pformat( tokenSequence ) ) # Display tokenization
  434. tree = parse( tokenSequence )
  435. ### Main Entry Point ###
  436. if __name__ == '__main__':
  437. (baseFiles, defaultFiles, partialFileSets, backend_name, template, defines_template, output, defines_output) = processCommandLineArgs()
  438. # Load backend module
  439. global backend
  440. backend_import = importlib.import_module( "backends.{0}".format( backend_name ) )
  441. backend = backend_import.Backend( template, defines_template )
  442. # Process base layout files
  443. for filename in baseFiles:
  444. variables_dict.setCurrentFile( filename )
  445. processKLLFile( filename )
  446. macros_map.completeBaseLayout() # Indicates to macros_map that the base layout is complete
  447. variables_dict.baseLayoutFinished()
  448. # Default combined layer
  449. for filename in defaultFiles:
  450. variables_dict.setCurrentFile( filename )
  451. processKLLFile( filename )
  452. # Apply assignment cache, see 5.1.2 USB Codes for why this is necessary
  453. macros_map.replayCachedAssignments()
  454. # Iterate through additional layers
  455. for partial in partialFileSets:
  456. # Increment layer for each -p option
  457. macros_map.addLayer()
  458. variables_dict.incrementLayer() # DefaultLayer is layer 0
  459. # Iterate and process each of the file in the layer
  460. for filename in partial:
  461. variables_dict.setCurrentFile( filename )
  462. processKLLFile( filename )
  463. # Apply assignment cache, see 5.1.2 USB Codes for why this is necessary
  464. macros_map.replayCachedAssignments()
  465. # Remove un-marked keys to complete the partial layer
  466. macros_map.removeUnmarked()
  467. # Do macro correlation and transformation
  468. macros_map.generate()
  469. # Process needed templating variables using backend
  470. backend.process( capabilities_dict, macros_map, variables_dict )
  471. # Generate output file using template and backend
  472. backend.generate( output, defines_output )
  473. # Successful Execution
  474. sys.exit( 0 )