]> git.donarmstrong.com Git - kiibohd-kll.git/blob - kll.py
ae96b2db5acbd39db9248bf8927921f5abfeb012
[kiibohd-kll.git] / kll.py
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
20 ### Imports ###
21
22 import argparse
23 import io
24 import os
25 import re
26 import sys
27 import token
28 import importlib
29
30 from tokenize import generate_tokens
31 from re       import VERBOSE
32 from pprint   import pformat
33
34 from kll_lib.hid_dict   import *
35 from kll_lib.containers import *
36
37 from funcparserlib.lexer  import make_tokenizer, Token, LexerError
38 from funcparserlib.parser import (some, a, many, oneplus, skip, finished, maybe, skip, forward_decl, NoParseError)
39
40
41
42 ### Decorators ###
43
44  ## Print Decorator Variables
45 ERROR = '\033[5;1;31mERROR\033[0m:'
46
47
48  ## Python Text Formatting Fixer...
49  ##  Because the creators of Python are averse to proper capitalization.
50 textFormatter_lookup = {
51         "usage: "            : "Usage: ",
52         "optional arguments" : "Optional Arguments",
53 }
54
55 def textFormatter_gettext( s ):
56         return textFormatter_lookup.get( s, s )
57
58 argparse._ = textFormatter_gettext
59
60
61
62 ### Argument Parsing ###
63
64 def processCommandLineArgs():
65         # Setup argument processor
66         pArgs = argparse.ArgumentParser(
67                 usage="%(prog)s [options] <file1>...",
68                 description="Generates .h file state tables and pointer indices from KLL .kll files.",
69                 epilog="Example: {0} TODO".format( os.path.basename( sys.argv[0] ) ),
70                 formatter_class=argparse.RawTextHelpFormatter,
71                 add_help=False,
72 )
73
74         # Positional Arguments
75         pArgs.add_argument( 'files', type=str, nargs='+',
76                 help=argparse.SUPPRESS ) # Suppressed help output, because Python output is verbosely ugly
77
78         # Optional Arguments
79         pArgs.add_argument( '-b', '--backend', type=str, default="kiibohd",
80                 help="Specify target backend for the KLL compiler.\n"
81                 "Default: kiibohd" )
82         pArgs.add_argument( '-p', '--partial', type=str, nargs='+', action='append',
83                 help="Specify .kll files to generate partial map, multiple files per flag.\n"
84                 "Each -p defines another partial map.\n"
85                 "Base .kll files (that define the scan code maps) must be defined for each partial map." )
86         pArgs.add_argument( '-t', '--template', type=str, default="templates/kiibohdKeymap.h",
87                 help="Specify template used to generate the keymap.\n"
88                 "Default: templates/kiibohdKeymap.h" )
89         pArgs.add_argument( '-o', '--output', type=str, default="templateKeymap.h",
90                 help="Specify output file. Writes to current working directory by default.\n"
91                 "Default: generatedKeymap.h" )
92         pArgs.add_argument( '-h', '--help', action="help",
93                 help="This message." )
94
95         # Process Arguments
96         args = pArgs.parse_args()
97
98         # Parameters
99         defaultFiles = args.files
100         partialFileSets = args.partial
101         if partialFileSets is None:
102                 partialFileSets = [[]]
103
104         # Check file existance
105         for filename in defaultFiles:
106                 if not os.path.isfile( filename ):
107                         print ( "{0} {1} does not exist...".format( ERROR, filename ) )
108                         sys.exit( 1 )
109
110         for partial in partialFileSets:
111                 for filename in partial:
112                         if not os.path.isfile( filename ):
113                                 print ( "{0} {1} does not exist...".format( ERROR, filename ) )
114                                 sys.exit( 1 )
115
116         return (defaultFiles, partialFileSets, args.backend, args.template, args.output)
117
118
119
120 ### Tokenizer ###
121
122 def tokenize( string ):
123         """str -> Sequence(Token)"""
124
125         # Basic Tokens Spec
126         specs = [
127                 ( 'Comment',          ( r' *#.*', ) ),
128                 ( 'Space',            ( r'[ \t\r\n]+', ) ),
129                 ( 'USBCode',          ( r'U(("[^"]+")|(0x[0-9a-fA-F]+)|([0-9]+))', ) ),
130                 ( 'USBCodeStart',     ( r'U\[', ) ),
131                 ( 'ScanCode',         ( r'S((0x[0-9a-fA-F]+)|([0-9]+))', ) ),
132                 ( 'ScanCodeStart',    ( r'S\[', ) ),
133                 ( 'CodeEnd',          ( r'\]', ) ),
134                 ( 'String',           ( r'"[^"]*"', VERBOSE ) ),
135                 ( 'SequenceString',   ( r"'[^']*'", ) ),
136                 ( 'Operator',         ( r'=>|:\+|:-|:|=', ) ),
137                 ( 'Comma',            ( r',', ) ),
138                 ( 'Dash',             ( r'-', ) ),
139                 ( 'Plus',             ( r'\+', ) ),
140                 ( 'Parenthesis',      ( r'\(|\)', ) ),
141                 ( 'Number',           ( r'-?(0x[0-9a-fA-F]+)|(0|([1-9][0-9]*))', VERBOSE ) ),
142                 ( 'Name',             ( r'[A-Za-z_][A-Za-z_0-9]*', ) ),
143                 ( 'VariableContents', ( r'''[^"' ;:=>()]+''', ) ),
144                 ( 'EndOfLine',        ( r';', ) ),
145         ]
146
147         # Tokens to filter out of the token stream
148         useless = ['Space', 'Comment']
149
150         tokens = make_tokenizer( specs )
151         return [x for x in tokens( string ) if x.type not in useless]
152
153
154
155 ### Parsing ###
156
157  ## Map Arrays
158 macros_map        = Macros()
159 variable_dict     = dict()
160 capabilities_dict = Capabilities()
161
162
163  ## Parsing Functions
164
165 def make_scanCode( token ):
166         scanCode = int( token[1:], 0 )
167         # Check size, to make sure it's valid
168         if scanCode > 0xFF:
169                 print ( "{0} ScanCode value {1} is larger than 255".format( ERROR, scanCode ) )
170                 raise
171         return scanCode
172
173 def make_usbCode( token ):
174         # If first character is a U, strip
175         if token[0] == "U":
176                 token = token[1:]
177
178         # If using string representation of USB Code, do lookup, case-insensitive
179         if '"' in token:
180                 try:
181                         usbCode = kll_hid_lookup_dictionary[ token[1:-1].upper() ]
182                 except LookupError as err:
183                         print ( "{0} {1} is an invalid USB Code Lookup...".format( ERROR, err ) )
184                         raise
185         else:
186                 usbCode = int( token, 0 )
187
188         # Check size, to make sure it's valid
189         if usbCode > 0xFF:
190                 print ( "{0} USBCode value {1} is larger than 255".format( ERROR, usbCode ) )
191                 raise
192         return usbCode
193
194 def make_seqString( token ):
195         # Shifted Characters, and amount to move by to get non-shifted version
196         # US ANSI
197         shiftCharacters = (
198                 ( "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 0x20 ),
199                 ( "+",       0x12 ),
200                 ( "&(",      0x11 ),
201                 ( "!#$%<>",  0x10 ),
202                 ( "*",       0x0E ),
203                 ( ")",       0x07 ),
204                 ( '"',       0x05 ),
205                 ( ":",       0x01 ),
206                 ( "^",      -0x10 ),
207                 ( "_",      -0x18 ),
208                 ( "{}|",    -0x1E ),
209                 ( "~",      -0x20 ),
210                 ( "@",      -0x32 ),
211                 ( "?",      -0x38 ),
212         )
213
214         listOfLists = []
215         shiftKey = kll_hid_lookup_dictionary["SHIFT"]
216
217         # Creates a list of USB codes from the string: sequence (list) of combos (lists)
218         for char in token[1:-1]:
219                 processedChar = char
220
221                 # Whether or not to create a combo for this sequence with a shift
222                 shiftCombo = False
223
224                 # Depending on the ASCII character, convert to single character or Shift + character
225                 for pair in shiftCharacters:
226                         if char in pair[0]:
227                                 shiftCombo = True
228                                 processedChar = chr( ord( char ) + pair[1] )
229                                 break
230
231                 # Do KLL HID Lookup on non-shifted character
232                 # NOTE: Case-insensitive, which is why the shift must be pre-computed
233                 usbCode = kll_hid_lookup_dictionary[ processedChar.upper() ]
234
235                 # Create Combo for this character, add shift key if shifted
236                 charCombo = []
237                 if shiftCombo:
238                         charCombo = [ [ shiftKey ] ]
239                 charCombo.append( [ usbCode ] )
240
241                 # Add to list of lists
242                 listOfLists.append( charCombo )
243
244         return listOfLists
245
246 def make_string( token ):
247         return token[1:-1]
248
249 def make_number( token ):
250         return int( token, 0 )
251
252   # Range can go from high to low or low to high
253 def make_scanCode_range( rangeVals ):
254         start = rangeVals[0]
255         end   = rangeVals[1]
256
257         # Swap start, end if start is greater than end
258         if start > end:
259                 start, end = end, start
260
261         # Iterate from start to end, and generate the range
262         return list( range( start, end + 1 ) )
263
264   # Range can go from high to low or low to high
265   # Warn on 0-9 (as this does not do what one would expect) TODO
266   # Lookup USB HID tags and convert to a number
267 def make_usbCode_range( rangeVals ):
268         # Check if already integers
269         if isinstance( rangeVals[0], int ):
270                 start = rangeVals[0]
271         else:
272                 start = make_usbCode( rangeVals[0] )
273
274         if isinstance( rangeVals[1], int ):
275                 end = rangeVals[1]
276         else:
277                 end = make_usbCode( rangeVals[1] )
278
279         # Swap start, end if start is greater than end
280         if start > end:
281                 start, end = end, start
282
283         # Iterate from start to end, and generate the range
284         return list( range( start, end + 1 ) )
285         pass
286
287
288  ## Base Rules
289
290 const       = lambda x: lambda _: x
291 unarg       = lambda f: lambda x: f(*x)
292 flatten     = lambda list: sum( list, [] )
293
294 tokenValue  = lambda x: x.value
295 tokenType   = lambda t: some( lambda x: x.type == t ) >> tokenValue
296 operator    = lambda s: a( Token( 'Operator', s ) ) >> tokenValue
297 parenthesis = lambda s: a( Token( 'Parenthesis', s ) ) >> tokenValue
298 eol         = a( Token( 'EndOfLine', ';' ) )
299
300 def listElem( item ):
301         return [ item ]
302
303 def listToTuple( items ):
304         return tuple( items )
305
306   # Flatten only the top layer (list of lists of ...)
307 def oneLayerFlatten( items ):
308         mainList = []
309         for sublist in items:
310                 for item in sublist:
311                         mainList.append( item )
312
313         return mainList
314
315   # Expand ranges of values in the 3rd dimension of the list, to a list of 2nd lists
316   # i.e. [ sequence, [ combo, [ range ] ] ] --> [ [ sequence, [ combo ] ], <option 2>, <option 3> ]
317 def optionExpansion( sequences ):
318         expandedSequences = []
319
320         # Total number of combinations of the sequence of combos that needs to be generated
321         totalCombinations = 1
322
323         # List of leaf lists, with number of leaves
324         maxLeafList = []
325
326         # Traverse to the leaf nodes, and count the items in each leaf list
327         for sequence in sequences:
328                 for combo in sequence:
329                         rangeLen = len( combo )
330                         totalCombinations *= rangeLen
331                         maxLeafList.append( rangeLen )
332
333         # Counter list to keep track of which combination is being generated
334         curLeafList = [0] * len( maxLeafList )
335
336         # Generate a list of permuations of the sequence of combos
337         for count in range( 0, totalCombinations ):
338                 expandedSequences.append( [] ) # Prepare list for adding the new combination
339                 position = 0
340
341                 # Traverse sequence of combos to generate permuation
342                 for sequence in sequences:
343                         expandedSequences[ -1 ].append( [] )
344                         for combo in sequence:
345                                 expandedSequences[ -1 ][ -1 ].append( combo[ curLeafList[ position ] ] )
346                                 position += 1
347
348                 # Increment combination tracker
349                 for leaf in range( 0, len( curLeafList ) ):
350                         curLeafList[ leaf ] += 1
351
352                         # Reset this position, increment next position (if it exists), then stop
353                         if curLeafList[ leaf ] >= maxLeafList[ leaf ]:
354                                 curLeafList[ leaf ] = 0
355                                 if leaf + 1 < len( curLeafList ):
356                                         curLeafList[ leaf + 1 ] += 1
357                                 break
358
359         return expandedSequences
360
361
362 # Converts USB Codes into Capabilities
363 def usbCodeToCapability( items ):
364         # Items already converted to variants using optionExpansion
365         for variant in range( 0, len( items ) ):
366                 # Sequence of Combos
367                 for sequence in range( 0, len( items[ variant ] ) ):
368                         for combo in range( 0, len( items[ variant ][ sequence ] ) ):
369                                 # Only convert if an integer, otherwise USB Code doesn't need converting
370                                 if isinstance( items[ variant ][ sequence ][ combo ], int ):
371                                         # Use backend capability name and a single argument
372                                         items[ variant ][ sequence ][ combo ] = tuple( [ backend.usbCodeCapability(), tuple( [ items[ variant ][ sequence ][ combo ] ] ) ] )
373
374         return items
375
376
377  ## Evaluation Rules
378
379 def eval_scanCode( triggers, operator, results ):
380         # Convert to lists of lists of lists to tuples of tuples of tuples
381         # Tuples are non-mutable, and can be used has index items
382         triggers = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in triggers )
383         results  = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in results )
384
385         # Iterate over all combinations of triggers and results
386         for trigger in triggers:
387                 for result in results:
388                         # Append Case
389                         if operator == ":+":
390                                 macros_map.appendScanCode( trigger, result )
391
392                         # Remove Case
393                         elif operator == ":-":
394                                 macros_map.removeScanCode( trigger, result )
395
396                         # Replace Case
397                         elif operator == ":":
398                                 macros_map.replaceScanCode( trigger, result )
399
400 def eval_usbCode( triggers, operator, results ):
401         # Convert to lists of lists of lists to tuples of tuples of tuples
402         # Tuples are non-mutable, and can be used has index items
403         triggers = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in triggers )
404         results  = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in results )
405
406         # Iterate over all combinations of triggers and results
407         for trigger in triggers:
408                 scanCodes = macros_map.lookupUSBCodes( trigger )
409                 for scanCode in scanCodes:
410                         for result in results:
411                                 # Cache assignment until file finishes processing
412                                 macros_map.cacheAssignment( operator, scanCode, result )
413
414 def eval_variable( name, content ):
415         # Content might be a concatenation of multiple data types, convert everything into a single string
416         assigned_content = ""
417         for item in content:
418                 assigned_content += str( item )
419
420         variable_dict[ name ] = assigned_content
421
422 def eval_capability( name, function, args ):
423         capabilities_dict[ name ] = [ function, args ]
424
425 map_scanCode   = unarg( eval_scanCode )
426 map_usbCode    = unarg( eval_usbCode )
427
428 set_variable   = unarg( eval_variable )
429 set_capability = unarg( eval_capability )
430
431
432  ## Sub Rules
433
434 usbCode   = tokenType('USBCode') >> make_usbCode
435 scanCode  = tokenType('ScanCode') >> make_scanCode
436 name      = tokenType('Name')
437 number    = tokenType('Number') >> make_number
438 comma     = tokenType('Comma')
439 dash      = tokenType('Dash')
440 plus      = tokenType('Plus')
441 content   = tokenType('VariableContents')
442 string    = tokenType('String') >> make_string
443 unString  = tokenType('String') # When the double quotes are still needed for internal processing
444 seqString = tokenType('SequenceString') >> make_seqString
445
446   # Code variants
447 code_end = tokenType('CodeEnd')
448
449   # Scan Codes
450 scanCode_start     = tokenType('ScanCodeStart')
451 scanCode_range     = number + skip( dash ) + number >> make_scanCode_range
452 scanCode_listElem  = number >> listElem
453 scanCode_innerList = oneplus( ( scanCode_range | scanCode_listElem ) + skip( maybe( comma ) ) ) >> flatten
454 scanCode_expanded  = skip( scanCode_start ) + scanCode_innerList + skip( code_end )
455 scanCode_elem      = scanCode >> listElem
456 scanCode_combo     = oneplus( ( scanCode_expanded | scanCode_elem ) + skip( maybe( plus ) ) )
457 scanCode_sequence  = oneplus( scanCode_combo + skip( maybe( comma ) ) )
458
459   # USB Codes
460 usbCode_start       = tokenType('USBCodeStart')
461 usbCode_range       = ( number | unString ) + skip( dash ) + ( number | unString ) >> make_usbCode_range
462 usbCode_listElemTag = unString >> make_usbCode
463 usbCode_listElem    = ( number | usbCode_listElemTag ) >> listElem
464 usbCode_innerList   = oneplus( ( usbCode_range | usbCode_listElem ) + skip( maybe( comma ) ) ) >> flatten
465 usbCode_expanded    = skip( usbCode_start ) + usbCode_innerList + skip( code_end )
466 usbCode_elem        = usbCode >> listElem
467 usbCode_combo       = oneplus( ( usbCode_expanded | usbCode_elem ) + skip( maybe( plus ) ) ) >> listElem
468 usbCode_sequence    = oneplus( ( usbCode_combo | seqString ) + skip( maybe( comma ) ) ) >> oneLayerFlatten
469
470   # Capabilities
471 capFunc_arguments = many( number + skip( maybe( comma ) ) ) >> listToTuple
472 capFunc_elem      = name + skip( parenthesis('(') ) + capFunc_arguments + skip( parenthesis(')') ) >> listElem
473 capFunc_combo     = oneplus( ( usbCode_expanded | usbCode_elem | capFunc_elem ) + skip( maybe( plus ) ) ) >> listElem
474 capFunc_sequence  = oneplus( ( capFunc_combo | seqString ) + skip( maybe( comma ) ) ) >> oneLayerFlatten
475
476   # Trigger / Result Codes
477 triggerCode_outerList    = scanCode_sequence >> optionExpansion
478 triggerUSBCode_outerList = usbCode_sequence >> optionExpansion >> usbCodeToCapability
479 resultCode_outerList     = capFunc_sequence >> optionExpansion >> usbCodeToCapability
480
481
482  ## Main Rules
483
484 #| <variable> = <variable contents>;
485 variable_contents   = name | content | string | number | comma | dash
486 variable_expression = name + skip( operator('=') ) + oneplus( variable_contents ) + skip( eol ) >> set_variable
487
488 #| <capability name> => <c function>;
489 capability_arguments  = name + skip( operator(':') ) + number + skip( maybe( comma ) )
490 capability_expression = name + skip( operator('=>') ) + name + skip( parenthesis('(') ) + many( capability_arguments ) + skip( parenthesis(')') ) + skip( eol ) >> set_capability
491
492 #| <trigger> : <result>;
493 operatorTriggerResult = operator(':') | operator(':+') | operator(':-')
494 scanCode_expression   = triggerCode_outerList + operatorTriggerResult + resultCode_outerList + skip( eol ) >> map_scanCode
495 usbCode_expression    = triggerUSBCode_outerList + operatorTriggerResult + resultCode_outerList + skip( eol ) >> map_usbCode
496
497 def parse( tokenSequence ):
498         """Sequence(Token) -> object"""
499
500         # Top-level Parser
501         expression = scanCode_expression | usbCode_expression | variable_expression | capability_expression
502
503         kll_text = many( expression )
504         kll_file = maybe( kll_text ) + skip( finished )
505
506         return kll_file.parse( tokenSequence )
507
508
509
510 def processKLLFile( filename ):
511         with open( filename ) as file:
512                 data = file.read()
513                 tokenSequence = tokenize( data )
514                 #print ( pformat( tokenSequence ) ) # Display tokenization
515                 tree = parse( tokenSequence )
516
517         # Apply assignment cache, see 5.1.2 USB Codes for why this is necessary
518         macros_map.replayCachedAssignments()
519
520
521
522 ### Main Entry Point ###
523
524 if __name__ == '__main__':
525         (defaultFiles, partialFileSets, backend_name, template, output) = processCommandLineArgs()
526
527         # Load backend module
528         global backend
529         backend_import = importlib.import_module( "backends.{0}".format( backend_name ) )
530         backend = backend_import.Backend( template )
531
532         # Default combined layer
533         for filename in defaultFiles:
534                 processKLLFile( filename )
535
536         # Iterate through additional layers
537         for partial in partialFileSets:
538                 # Increment layer for each -p option
539                 macros_map.addLayer()
540
541                 # Iterate and process each of the file in the layer
542                 for filename in partial:
543                         processKLLFile( filename )
544
545         # Do macro correlation and transformation
546         macros_map.generate()
547
548         # Process needed templating variables using backend
549         backend.process( capabilities_dict, macros_map )
550
551         # Generate output file using template and backend
552         backend.generate( output )
553
554         # Successful Execution
555         sys.exit( 0 )
556