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 21KB

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