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

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