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

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