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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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="templateKeymap.h",
  68. help="Specify template used to generate the keymap.\n"
  69. "Default: templateKeymap.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. ( 'Comma', ( r',', ) ),
  108. ( 'Dash', ( r'-', ) ),
  109. ( 'Plus', ( r'\+', ) ),
  110. ( 'Operator', ( 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. scanCode_map = [ None ] * 0xFF # Define 8 bit address width
  124. usbCode_map = [ None ] * 0xFF # Define 8 bit address width
  125. variable_dict = dict()
  126. capabilities_dict = Capabilities()
  127. ## Parsing Functions
  128. def make_scanCode( token ):
  129. scanCode = int( token[1:], 0 )
  130. # Check size, to make sure it's valid
  131. if scanCode > 0xFF:
  132. print ( "{0} ScanCode value {1} is larger than 255".format( ERROR, scanCode ) )
  133. raise
  134. return scanCode
  135. def make_usbCode( token ):
  136. # If first character is a U, strip
  137. if token[0] == "U":
  138. token = token[1:]
  139. # If using string representation of USB Code, do lookup, case-insensitive
  140. if '"' in token:
  141. try:
  142. usbCode = kll_hid_lookup_dictionary[ token[1:-1].upper() ]
  143. except LookupError as err:
  144. print ( "{0} {1} is an invalid USB Code Lookup...".format( ERROR, err ) )
  145. raise
  146. else:
  147. usbCode = int( token, 0 )
  148. # Check size, to make sure it's valid
  149. if usbCode > 0xFF:
  150. print ( "{0} USBCode value {1} is larger than 255".format( ERROR, usbCode ) )
  151. raise
  152. return usbCode
  153. def make_seqString( token ):
  154. # Shifted Characters, and amount to move by to get non-shifted version
  155. # US ANSI
  156. shiftCharacters = (
  157. ( "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 0x20 ),
  158. ( "+", 0x12 ),
  159. ( "&(", 0x11 ),
  160. ( "!#$%<>", 0x10 ),
  161. ( "*", 0x0E ),
  162. ( ")", 0x07 ),
  163. ( '"', 0x05 ),
  164. ( ":", 0x01 ),
  165. ( "^", -0x10 ),
  166. ( "_", -0x18 ),
  167. ( "{}|", -0x1E ),
  168. ( "~", -0x20 ),
  169. ( "@", -0x32 ),
  170. ( "?", -0x38 ),
  171. )
  172. listOfLists = []
  173. shiftKey = kll_hid_lookup_dictionary["SHIFT"]
  174. # Creates a list of USB codes from the string: sequence (list) of combos (lists)
  175. for char in token[1:-1]:
  176. processedChar = char
  177. # Whether or not to create a combo for this sequence with a shift
  178. shiftCombo = False
  179. # Depending on the ASCII character, convert to single character or Shift + character
  180. for pair in shiftCharacters:
  181. if char in pair[0]:
  182. shiftCombo = True
  183. processedChar = chr( ord( char ) + pair[1] )
  184. break
  185. # Do KLL HID Lookup on non-shifted character
  186. # NOTE: Case-insensitive, which is why the shift must be pre-computed
  187. usbCode = kll_hid_lookup_dictionary[ processedChar.upper() ]
  188. # Create Combo for this character, add shift key if shifted
  189. charCombo = []
  190. if shiftCombo:
  191. charCombo = [ [ shiftKey ] ]
  192. charCombo.append( [ usbCode ] )
  193. # Add to list of lists
  194. listOfLists.append( charCombo )
  195. return listOfLists
  196. def make_string( token ):
  197. return token[1:-1]
  198. def make_number( token ):
  199. return int( token, 0 )
  200. # Range can go from high to low or low to high
  201. def make_scanCode_range( rangeVals ):
  202. start = rangeVals[0]
  203. end = rangeVals[1]
  204. # Swap start, end if start is greater than end
  205. if start > end:
  206. start, end = end, start
  207. # Iterate from start to end, and generate the range
  208. return list( range( start, end + 1 ) )
  209. # Range can go from high to low or low to high
  210. # Warn on 0-9 (as this does not do what one would expect) TODO
  211. # Lookup USB HID tags and convert to a number
  212. def make_usbCode_range( rangeVals ):
  213. # Check if already integers
  214. if isinstance( rangeVals[0], int ):
  215. start = rangeVals[0]
  216. else:
  217. start = make_usbCode( rangeVals[0] )
  218. if isinstance( rangeVals[1], int ):
  219. end = rangeVals[1]
  220. else:
  221. end = make_usbCode( rangeVals[1] )
  222. # Swap start, end if start is greater than end
  223. if start > end:
  224. start, end = end, start
  225. # Iterate from start to end, and generate the range
  226. return list( range( start, end + 1 ) )
  227. pass
  228. ## Base Rules
  229. const = lambda x: lambda _: x
  230. unarg = lambda f: lambda x: f(*x)
  231. flatten = lambda list: sum( list, [] )
  232. tokenValue = lambda x: x.value
  233. tokenType = lambda t: some( lambda x: x.type == t ) >> tokenValue
  234. operator = lambda s: a( Token( 'Operator', s ) ) >> tokenValue
  235. parenthesis = lambda s: a( Token( 'Parenthesis', s ) ) >> tokenValue
  236. eol = a( Token( 'EndOfLine', ';' ) )
  237. def listElem( item ):
  238. return [ item ]
  239. # Flatten only the top layer (list of lists of ...)
  240. def oneLayerFlatten( items ):
  241. mainList = []
  242. for sublist in items:
  243. for item in sublist:
  244. mainList.append( item )
  245. return mainList
  246. # Expand ranges of values in the 3rd dimension of the list, to a list of 2nd lists
  247. # i.e. [ sequence, [ combo, [ range ] ] ] --> [ [ sequence, [ combo ] ], <option 2>, <option 3> ]
  248. def optionExpansion( sequences ):
  249. expandedSequences = []
  250. # Total number of combinations of the sequence of combos that needs to be generated
  251. totalCombinations = 1
  252. # List of leaf lists, with number of leaves
  253. maxLeafList = []
  254. # Traverse to the leaf nodes, and count the items in each leaf list
  255. for sequence in sequences:
  256. for combo in sequence:
  257. rangeLen = len( combo )
  258. totalCombinations *= rangeLen
  259. maxLeafList.append( rangeLen )
  260. # Counter list to keep track of which combination is being generated
  261. curLeafList = [0] * len( maxLeafList )
  262. # Generate a list of permuations of the sequence of combos
  263. for count in range( 0, totalCombinations ):
  264. expandedSequences.append( [] ) # Prepare list for adding the new combination
  265. position = 0
  266. # Traverse sequence of combos to generate permuation
  267. for sequence in sequences:
  268. expandedSequences[ -1 ].append( [] )
  269. for combo in sequence:
  270. expandedSequences[ -1 ][ -1 ].append( combo[ curLeafList[ position ] ] )
  271. position += 1
  272. # Increment combination tracker
  273. for leaf in range( 0, len( curLeafList ) ):
  274. curLeafList[ leaf ] += 1
  275. # Reset this position, increment next position (if it exists), then stop
  276. if curLeafList[ leaf ] >= maxLeafList[ leaf ]:
  277. curLeafList[ leaf ] = 0
  278. if leaf + 1 < len( curLeafList ):
  279. curLeafList[ leaf + 1 ] += 1
  280. break
  281. return expandedSequences
  282. ## Evaluation Rules
  283. def eval_scanCode( trigger, result ):
  284. # Convert to lists of lists of lists to tuples of tuples of tuples
  285. trigger = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in trigger )
  286. result = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in result )
  287. # Add to the base scanCode map, overwrite if already defined
  288. # if scanCode_map[ trigger ] != None:
  289. # print ( "ScanCodeMap - Replacing '{0}' with '{1}' -> {2}".format( scanCode_map[ trigger ], result, trigger ) )
  290. # scanCode_map[ trigger ] = result
  291. def eval_usbCode( trigger, result ):
  292. # Check if trigger is list
  293. # Add to the base usbCode map, overwrite if already defined
  294. if usbCode_map[ trigger ] != None:
  295. print ( "USBCodeMap - Replacing '{0}' with '{1}' -> {2}".format( usbCode_map[ trigger ], result, trigger ) )
  296. usbCode_map[ trigger ] = result
  297. print ( trigger )
  298. def eval_variable( name, content ):
  299. # Content might be a concatenation of multiple data types, convert everything into a single string
  300. assigned_content = ""
  301. for item in content:
  302. assigned_content += str( item )
  303. variable_dict[ name ] = assigned_content
  304. def eval_capability( name, function, args ):
  305. capabilities_dict[ name ] = [ function, args ]
  306. map_scanCode = unarg( eval_scanCode )
  307. map_usbCode = unarg( eval_usbCode )
  308. set_variable = unarg( eval_variable )
  309. set_capability = unarg( eval_capability )
  310. ## Sub Rules
  311. usbCode = tokenType('USBCode') >> make_usbCode
  312. scanCode = tokenType('ScanCode') >> make_scanCode
  313. name = tokenType('Name')
  314. number = tokenType('Number') >> make_number
  315. comma = tokenType('Comma')
  316. dash = tokenType('Dash')
  317. plus = tokenType('Plus')
  318. content = tokenType('VariableContents')
  319. string = tokenType('String') >> make_string
  320. unString = tokenType('String') # When the double quotes are still needed for internal processing
  321. seqString = tokenType('SequenceString') >> make_seqString
  322. # Code variants
  323. code_end = tokenType('CodeEnd')
  324. # Scan Codes
  325. scanCode_start = tokenType('ScanCodeStart')
  326. scanCode_range = number + skip( dash ) + number >> make_scanCode_range
  327. scanCode_listElem = number >> listElem
  328. scanCode_innerList = oneplus( ( scanCode_range | scanCode_listElem ) + skip( maybe( comma ) ) ) >> flatten
  329. scanCode_expanded = skip( scanCode_start ) + scanCode_innerList + skip( code_end )
  330. scanCode_elem = scanCode >> listElem
  331. scanCode_combo = oneplus( ( scanCode_expanded | scanCode_elem ) + skip( maybe( plus ) ) )
  332. scanCode_sequence = oneplus( scanCode_combo + skip( maybe( comma ) ) )
  333. # USB Codes
  334. usbCode_start = tokenType('USBCodeStart')
  335. usbCode_range = ( number | unString ) + skip( dash ) + ( number | unString ) >> make_usbCode_range
  336. usbCode_listElemTag = unString >> make_usbCode
  337. usbCode_listElem = ( number | usbCode_listElemTag ) >> listElem
  338. usbCode_innerList = oneplus( ( usbCode_range | usbCode_listElem ) + skip( maybe( comma ) ) ) >> flatten
  339. usbCode_expanded = skip( usbCode_start ) + usbCode_innerList + skip( code_end )
  340. usbCode_elem = usbCode >> listElem
  341. usbCode_combo = oneplus( ( usbCode_expanded | usbCode_elem ) + skip( maybe( plus ) ) ) >> listElem
  342. usbCode_sequence = oneplus( ( usbCode_combo | seqString ) + skip( maybe( comma ) ) ) >> oneLayerFlatten
  343. # Capabilities
  344. capFunc_arguments = number + skip( maybe( comma ) )
  345. capFunc_elem = name + skip( parenthesis('(') ) + many( capFunc_arguments ) + skip( parenthesis(')') ) >> listElem
  346. capFunc_combo = oneplus( ( usbCode_expanded | usbCode_elem | capFunc_elem ) + skip( maybe( plus ) ) ) >> listElem
  347. capFunc_sequence = oneplus( ( capFunc_combo | seqString ) + skip( maybe( comma ) ) ) >> oneLayerFlatten
  348. # Trigger / Result Codes
  349. triggerCode_outerList = scanCode_sequence >> optionExpansion
  350. triggerUSBCode_outerList = usbCode_sequence >> optionExpansion
  351. resultCode_outerList = capFunc_sequence >> optionExpansion
  352. ## Main Rules
  353. #| <variable> = <variable contents>;
  354. variable_contents = name | content | string | number | comma | dash
  355. variable_expression = name + skip( operator('=') ) + oneplus( variable_contents ) + skip( eol ) >> set_variable
  356. #| <capability name> => <c function>;
  357. capability_arguments = name + skip( operator(':') ) + number + skip( maybe( comma ) )
  358. capability_expression = name + skip( operator('=>') ) + name + skip( parenthesis('(') ) + many( capability_arguments ) + skip( parenthesis(')') ) + skip( eol ) >> set_capability
  359. #| <trigger> : <result>;
  360. scanCode_expression = triggerCode_outerList + skip( operator(':') ) + resultCode_outerList + skip( eol ) >> map_scanCode
  361. usbCode_expression = triggerUSBCode_outerList + skip( operator(':') ) + resultCode_outerList + skip( eol ) #>> map_usbCode
  362. def parse( tokenSequence ):
  363. """Sequence(Token) -> object"""
  364. # Top-level Parser
  365. expression = scanCode_expression | usbCode_expression | variable_expression | capability_expression
  366. kll_text = many( expression )
  367. kll_file = maybe( kll_text ) + skip( finished )
  368. return kll_file.parse( tokenSequence )
  369. ### Main Entry Point ###
  370. if __name__ == '__main__':
  371. (defaultFiles, partialFileSets, backend_name, template, output) = processCommandLineArgs()
  372. # Load backend module
  373. global backend
  374. backend_import = importlib.import_module( "backends.{0}".format( backend_name ) )
  375. backend = backend_import.Backend( template )
  376. #TODO Move elsewhere
  377. for filename in defaultFiles:
  378. with open( filename ) as file:
  379. data = file.read()
  380. tokenSequence = tokenize( data )
  381. print ( pformat( tokenSequence ) )
  382. tree = parse( tokenSequence )
  383. #print ( tree )
  384. #print ( scanCode_map )
  385. #print ( usbCode_map )
  386. print ( variable_dict )
  387. print ( capabilities_dict )
  388. # TODO Move
  389. backend.process( capabilities_dict )
  390. # Successful Execution
  391. sys.exit( 0 )