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