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.

emitter.py 4.3KB

KLL Compiler Re-Write This was many months of efforts in re-designing how the KLL compiler should work. The major problem with the original compiler was how difficult it was to extend language wise. This lead to many delays in KLL 0.4 and 0.5 being implemented. The new design is a multi-staged compiler, where even tokenization occurs over multiple stages. This allows individual parsing and token regexes to be expressed more simply without affect other expressions. Another area of change is the concept of Contexts. In the original KLL compiler the idea of a cache assigned was "hacked" on when I realized the language was "broken" (after nearly finishing the compiler). Since assignment order is generally considered not to matter for keymappings, I created a "cached" assignment where the whole file is read into a sub-datastructure, then apply to the master datastructure. Unfortunately, this wasn't really all that clear, so it was annoying to work with. To remedy this, I created KLL Contexts, which contain information about a group of expressions. Not only can these groups can be merged with other Contexts, they have historical data about how they were generated allowing for errors very late in processing to be pin-pointed back to the offending kll file. Backends work nearly the same as they did before. However, all call-backs for capability evaluations have been removed. This makes the interface much cleaner as Contexts can only be symbolically merged now. (Previously datastructures did evaluation merges where the ScanCode or Capability was looked up right before passing to the backend, but this required additional information from the backend). Many of the old parsing and tokenization rules have been reused, along with the hid_dict.py code. The new design takes advantage of processor pools to handle multithreading where it makes sense. For example, all specified files are loaded into ram simulatenously rather than sparingly reading from. The reason for this is so that each Context always has all the information it requires at all times. kll - Program entry point (previously kll.py) - Very small now, does some setting up of command-line args - Most command-line args are specified by the corresponding processing stage common/channel.py - Pixel Channel container classes common/context.py - Context container classes - As is usual with other files, blank classes inherit a base class - These blank classes are identified by the class name itself to handle special behaviour - And if/when necessary functions are re-implemented - MergeConext class facilitates merging of contexts while maintaining lineage common/expression.py - Expression container classes * Expression base class * AssignmentExpression * NameAssociationExpression * DataAssociationExpression * MapExpression - These classes are used to store expressions after they have finished parsing and tokenization common/file.py - Container class for files being read by the KLL compiler common/emitter.py - Base class for all KLL emitters - TextEmitter for dealing with text file templates common/hid_dict.py - Slightly modified version of kll_lib/hid_dict.py common/id.py - Identification container classes - Used to indentify different types of elements used within the KLL language common/modifier.py - Container classes for animation and pixel change functions common/organization.py - Data structure merging container classes - Contains all the sub-datastructure classes as well - The Organization class handles the merge orchestration and expression insertion common/parse.py - Parsing rules for funcparserlib - Much of this file was taken from the original kll.py - Many changes to support the multi-stage processing and support KLL 0.5 common/position.py - Container class dealing with physical positions common/schedule.py - Container class dealing with scheduling and timing events common/stage.py - Contains ControlStage and main Stage classes * CompilerConfigurationStage * FileImportStage * PreprocessorStage * OperationClassificationStage * OperationSpecificsStage * OperationOrganizationStage * DataOrganziationStage * DataFinalizationStage * DataAnalysisStage * CodeGenerationStage * ReportGenerationStage - Each of these classes controls the life-cycle of each stage - If multi-threading is desired, it must be handled within the class * The next stage will not start until the current stage is finished - Errors are handled such that as many errors as possible are recorded before forcing an exit * The exit is handled at the end of each stage if necessary - Command-line arguments for each stage can be defined if necessary (they are given their own grouping) - Each stage can pull variables and functions from other stages if necessary using a name lookup * This means you don't have to worry about over-arching datastructures emitters/emitters.py - Container class for KLL emitters - Handles emitter setup and selection emitters/kiibohd/kiibohd.py - kiibohd .h file KLL emitter - Re-uses some backend code from the original KLL compiler funcparserlib/parser.py - Added debug mode control examples/assignment.kll examples/defaultMapExample.kll examples/example.kll examples/hhkbpro2.kll examples/leds.kll examples/mapping.kll examples/simple1.kll examples/simple2.kll examples/simpleExample.kll examples/state_scheduling.kll - Updating/Adding rules for new compiler and KLL 0.4 + KLL 0.5 support
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. #!/usr/bin/env python3
  2. '''
  3. KLL Emitter Base Classes
  4. '''
  5. # Copyright (C) 2016 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 re
  21. import os
  22. import sys
  23. ### Decorators ###
  24. ## Print Decorator Variables
  25. ERROR = '\033[5;1;31mERROR\033[0m:'
  26. WARNING = '\033[5;1;33mWARNING\033[0m:'
  27. ### Classes ###
  28. class Emitter:
  29. '''
  30. KLL Emitter Base Class
  31. NOTE: Emitter should do as little as possible in the __init__ function.
  32. '''
  33. def __init__( self, control ):
  34. '''
  35. Emitter initialization
  36. @param control: ControlStage object, used to access data from other stages
  37. '''
  38. self.control = control
  39. self.color = False
  40. def command_line_args( self, args ):
  41. '''
  42. Group parser for command line arguments
  43. @param args: Name space of processed arguments
  44. '''
  45. print( "{0} '{1}' '{2}' has not been implemented yet"
  46. .format(
  47. WARNING,
  48. self.command_line_args.__name__,
  49. type( self ).__name__
  50. )
  51. )
  52. def command_line_flags( self, parser ):
  53. '''
  54. Group parser for command line options
  55. @param parser: argparse setup object
  56. '''
  57. print( "{0} '{1}' '{2}' has not been implemented yet"
  58. .format(
  59. WARNING,
  60. self.command_line_flags.__name__,
  61. type( self ).__name__
  62. )
  63. )
  64. def process( self ):
  65. '''
  66. Emitter Processing
  67. '''
  68. print( "{0} '{1}' '{2}' has not been implemented yet"
  69. .format(
  70. WARNING,
  71. self.process.__name__,
  72. type( self ).__name__
  73. )
  74. )
  75. def output( self ):
  76. '''
  77. Final Stage of Emitter
  78. Generate desired outputs
  79. '''
  80. print( "{0} '{1}' '{2}' has not been implemented yet"
  81. .format(
  82. WARNING,
  83. self.output.__name__,
  84. type( self ).__name__
  85. )
  86. )
  87. class TextEmitter:
  88. '''
  89. KLL Text Emitter Class
  90. Base class for any text emitter that wants to use the templating functionality
  91. If multiple files need to be generated, call load_template and generate multiple times.
  92. e.g.
  93. load_template('_myfile.h')
  94. generate('/tmp/myfile.h')
  95. load_template('_myfile2.h')
  96. generate('/tmp/myfile2.h')
  97. TODO
  98. - Generate list of unused tags
  99. '''
  100. def __init__( self ):
  101. '''
  102. TextEmitter Initialization
  103. '''
  104. # Dictionary used to do template replacements
  105. self.fill_dict = {}
  106. self.tag_list = []
  107. self.template = None
  108. def load_template( self, template ):
  109. '''
  110. Loads template file
  111. Looks for <|tags|> to replace in the template
  112. @param template: Path to template
  113. '''
  114. # Does template exist?
  115. if not os.path.isfile( template ):
  116. print ( "{0} '{1}' does not exist...".format( ERROR, template ) )
  117. sys.exit( 1 )
  118. self.template = template
  119. # Generate list of fill tags
  120. with open( template, 'r' ) as openFile:
  121. for line in openFile:
  122. match = re.findall( r'<\|([^|>]+)\|>', line )
  123. for item in match:
  124. self.tag_list.append( item )
  125. def generate( self, output_path ):
  126. '''
  127. Generates the output file from the template file
  128. @param output_path: Path to the generated file
  129. '''
  130. # Make sure we've called load_template at least once
  131. if self.template is None:
  132. print ( "{0} TextEmitter template (load_template) has not been called.".format( ERROR ) )
  133. sys.exit( 1 )
  134. # Process each line of the template, outputting to the target path
  135. with open( output_path, 'w' ) as outputFile:
  136. with open( self.template, 'r' ) as templateFile:
  137. for line in templateFile:
  138. # TODO Support multiple replacements per line
  139. # TODO Support replacement with other text inline
  140. match = re.findall( r'<\|([^|>]+)\|>', line )
  141. # If match, replace with processed variable
  142. if match:
  143. try:
  144. outputFile.write( self.fill_dict[ match[0] ] )
  145. except KeyError as err:
  146. print( "{0} '{1}' not found, skipping...".format(
  147. WARNING, match[0]
  148. ) )
  149. outputFile.write("\n")
  150. # Otherwise, just append template to output file
  151. else:
  152. outputFile.write( line )