KLL Compiler
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

kll.py 21KB

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