2014-09-02 17:03:50 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
# Copyright (c) 2008/2013 Andrey Vlasovskikh
|
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
2016-09-02 06:48:13 +00:00
|
|
|
# Modifications by Jacob Alexander 2014, 2016
|
2014-09-02 17:03:50 +00:00
|
|
|
#
|
|
|
|
# Permission is hereby granted, free of charge, to any person obtaining
|
|
|
|
# a copy of this software and associated documentation files (the
|
|
|
|
# "Software"), to deal in the Software without restriction, including
|
|
|
|
# without limitation the rights to use, copy, modify, merge, publish,
|
|
|
|
# distribute, sublicense, and/or sell copies of the Software, and to
|
|
|
|
# permit persons to whom the Software is furnished to do so, subject to
|
|
|
|
# the following conditions:
|
|
|
|
#
|
|
|
|
# The above copyright notice and this permission notice shall be included
|
|
|
|
# in all copies or substantial portions of the Software.
|
|
|
|
#
|
|
|
|
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
|
|
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
|
|
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
|
|
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
|
|
|
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
|
|
|
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
|
|
|
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
|
|
|
|
|
|
"""A recurisve descent parser library based on functional combinators.
|
|
|
|
|
|
|
|
Basic combinators are taken from Harrison's book ["Introduction to Functional
|
|
|
|
Programming"][1] and translated from ML into Python. See also [a Russian
|
|
|
|
translation of the book][2].
|
|
|
|
|
|
|
|
[1]: http://www.cl.cam.ac.uk/teaching/Lectures/funprog-jrh-1996/
|
|
|
|
[2]: http://code.google.com/p/funprog-ru/
|
|
|
|
|
|
|
|
A parser `p` is represented by a function of type:
|
|
|
|
|
|
|
|
p :: Sequence(a), State -> (b, State)
|
|
|
|
|
|
|
|
that takes as its input a sequence of tokens of arbitrary type `a` and a
|
|
|
|
current parsing state and return a pair of a parsed token of arbitrary type
|
|
|
|
`b` and the new parsing state.
|
|
|
|
|
|
|
|
The parsing state includes the current position in the sequence being parsed and
|
|
|
|
the position of the rightmost token that has been consumed while parsing.
|
|
|
|
|
|
|
|
Parser functions are wrapped into an object of the class `Parser`. This class
|
|
|
|
implements custom operators `+` for sequential composition of parsers, `|` for
|
|
|
|
choice composition, `>>` for transforming the result of parsing. The method
|
|
|
|
`Parser.parse` provides an easier way for invoking a parser hiding details
|
|
|
|
related to a parser state:
|
|
|
|
|
|
|
|
Parser.parse :: Parser(a, b), Sequence(a) -> b
|
|
|
|
|
|
|
|
Altough this module is able to deal with a sequences of any kind of objects, the
|
|
|
|
recommended way of using it is applying a parser to a `Sequence(Token)`.
|
|
|
|
`Token` objects are produced by a regexp-based tokenizer defined in
|
|
|
|
`funcparserlib.lexer`. By using it this way you get more readable parsing error
|
|
|
|
messages (as `Token` objects contain their position in the source file) and good
|
|
|
|
separation of lexical and syntactic levels of the grammar. See examples for more
|
|
|
|
info.
|
|
|
|
|
|
|
|
Debug messages are emitted via a `logging.Logger` object named
|
|
|
|
`"funcparserlib"`.
|
|
|
|
"""
|
|
|
|
|
|
|
|
__all__ = [
|
|
|
|
'some', 'a', 'many', 'pure', 'finished', 'maybe', 'skip', 'oneplus',
|
|
|
|
'forward_decl', 'NoParseError',
|
|
|
|
]
|
|
|
|
|
|
|
|
import logging
|
|
|
|
|
|
|
|
|
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
2016-09-02 06:48:13 +00:00
|
|
|
log = logging.getLogger('funcparserlib')
|
2014-09-02 17:03:50 +00:00
|
|
|
debug = False
|
|
|
|
|
|
|
|
|
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
2016-09-02 06:48:13 +00:00
|
|
|
def Parser_debug(enable, stream=None):
|
|
|
|
'''
|
|
|
|
Enables/Disables debug logger for parser.py
|
|
|
|
|
|
|
|
NOTE: This is not really multi-thread friendly
|
|
|
|
|
|
|
|
@param stream: StringIO stream to use
|
|
|
|
@param enable: Enable/disable debug stream
|
|
|
|
'''
|
|
|
|
global debug
|
|
|
|
debug = enable
|
|
|
|
|
|
|
|
if enable:
|
|
|
|
logging.raiseExceptions = False
|
|
|
|
log.setLevel(logging.DEBUG)
|
|
|
|
ch = logging.StreamHandler(stream)
|
|
|
|
log.addHandler(ch)
|
|
|
|
|
|
|
|
|
2014-09-02 17:03:50 +00:00
|
|
|
class Parser(object):
|
|
|
|
"""A wrapper around a parser function that defines some operators for parser
|
|
|
|
composition.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, p):
|
|
|
|
"""Wraps a parser function p into an object."""
|
|
|
|
self.define(p)
|
|
|
|
|
|
|
|
def named(self, name):
|
|
|
|
"""Specifies the name of the parser for more readable parsing log."""
|
|
|
|
self.name = name
|
|
|
|
return self
|
|
|
|
|
|
|
|
def define(self, p):
|
|
|
|
"""Defines a parser wrapped into this object."""
|
|
|
|
f = getattr(p, 'run', p)
|
|
|
|
if debug:
|
|
|
|
setattr(self, '_run', f)
|
|
|
|
else:
|
|
|
|
setattr(self, 'run', f)
|
|
|
|
self.named(getattr(p, 'name', p.__doc__))
|
|
|
|
|
|
|
|
def run(self, tokens, s):
|
|
|
|
"""Sequence(a), State -> (b, State)
|
|
|
|
|
|
|
|
Runs a parser wrapped into this object.
|
|
|
|
"""
|
|
|
|
if debug:
|
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
2016-09-02 06:48:13 +00:00
|
|
|
# Truncate at 500 characters
|
|
|
|
# Any longer isn't that useful and makes the output hard to read
|
|
|
|
output = 'trying %s' % self.name
|
|
|
|
if len( output ) > 500:
|
|
|
|
output = output[:250] + ' ... [truncated] ... ' + output[-250:]
|
|
|
|
log.debug(output)
|
2014-09-02 17:03:50 +00:00
|
|
|
return self._run(tokens, s)
|
|
|
|
|
|
|
|
def _run(self, tokens, s):
|
2014-09-16 00:32:07 +00:00
|
|
|
raise NotImplementedError('you must define() a parser')
|
2014-09-02 17:03:50 +00:00
|
|
|
|
|
|
|
def parse(self, tokens):
|
|
|
|
"""Sequence(a) -> b
|
|
|
|
|
|
|
|
Applies the parser to a sequence of tokens producing a parsing result.
|
|
|
|
|
|
|
|
It provides a way to invoke a parser hiding details related to the
|
|
|
|
parser state. Also it makes error messages more readable by specifying
|
|
|
|
the position of the rightmost token that has been reached.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
(tree, _) = self.run(tokens, State())
|
|
|
|
return tree
|
|
|
|
except NoParseError as e:
|
|
|
|
max = e.state.max
|
|
|
|
if len(tokens) > max:
|
|
|
|
tok = tokens[max]
|
|
|
|
else:
|
2014-09-16 00:32:07 +00:00
|
|
|
tok = '<EOF>'
|
2016-10-10 05:00:30 +00:00
|
|
|
raise NoParseError('%s: %s' % (e.msg, tok), e.state, tok)
|
2014-09-02 17:03:50 +00:00
|
|
|
|
|
|
|
def __add__(self, other):
|
|
|
|
"""Parser(a, b), Parser(a, c) -> Parser(a, _Tuple(b, c))
|
|
|
|
|
|
|
|
A sequential composition of parsers.
|
|
|
|
|
|
|
|
NOTE: The real type of the parsed value isn't always such as specified.
|
|
|
|
Here we use dynamic typing for ignoring the tokens that are of no
|
|
|
|
interest to the user. Also we merge parsing results into a single _Tuple
|
|
|
|
unless the user explicitely prevents it. See also skip and >>
|
|
|
|
combinators.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def magic(v1, v2):
|
|
|
|
vs = [v for v in [v1, v2] if not isinstance(v, _Ignored)]
|
|
|
|
if len(vs) == 1:
|
|
|
|
return vs[0]
|
|
|
|
elif len(vs) == 2:
|
|
|
|
if isinstance(vs[0], _Tuple):
|
|
|
|
return _Tuple(v1 + (v2,))
|
|
|
|
else:
|
|
|
|
return _Tuple(vs)
|
|
|
|
else:
|
|
|
|
return _Ignored(())
|
|
|
|
|
|
|
|
@Parser
|
|
|
|
def _add(tokens, s):
|
|
|
|
(v1, s2) = self.run(tokens, s)
|
|
|
|
(v2, s3) = other.run(tokens, s2)
|
|
|
|
return magic(v1, v2), s3
|
|
|
|
|
|
|
|
# or in terms of bind and pure:
|
|
|
|
# _add = self.bind(lambda x: other.bind(lambda y: pure(magic(x, y))))
|
2014-09-16 00:32:07 +00:00
|
|
|
_add.name = '(%s , %s)' % (self.name, other.name)
|
2014-09-02 17:03:50 +00:00
|
|
|
return _add
|
|
|
|
|
|
|
|
def __or__(self, other):
|
|
|
|
"""Parser(a, b), Parser(a, c) -> Parser(a, b or c)
|
|
|
|
|
|
|
|
A choice composition of two parsers.
|
|
|
|
|
|
|
|
NOTE: Here we are not providing the exact type of the result. In a
|
|
|
|
statically typed langage something like Either b c could be used. See
|
|
|
|
also + combinator.
|
|
|
|
"""
|
|
|
|
|
|
|
|
@Parser
|
|
|
|
def _or(tokens, s):
|
|
|
|
try:
|
|
|
|
return self.run(tokens, s)
|
|
|
|
except NoParseError as e:
|
|
|
|
return other.run(tokens, State(s.pos, e.state.max))
|
|
|
|
|
2014-09-16 00:32:07 +00:00
|
|
|
_or.name = '(%s | %s)' % (self.name, other.name)
|
2014-09-02 17:03:50 +00:00
|
|
|
return _or
|
|
|
|
|
|
|
|
def __rshift__(self, f):
|
|
|
|
"""Parser(a, b), (b -> c) -> Parser(a, c)
|
|
|
|
|
|
|
|
Given a function from b to c, transforms a parser of b into a parser of
|
|
|
|
c. It is useful for transorming a parser value into another value for
|
|
|
|
making it a part of a parse tree or an AST.
|
|
|
|
|
|
|
|
This combinator may be thought of as a functor from b -> c to Parser(a,
|
|
|
|
b) -> Parser(a, c).
|
|
|
|
"""
|
|
|
|
|
|
|
|
@Parser
|
|
|
|
def _shift(tokens, s):
|
|
|
|
(v, s2) = self.run(tokens, s)
|
|
|
|
return f(v), s2
|
|
|
|
|
|
|
|
# or in terms of bind and pure:
|
|
|
|
# _shift = self.bind(lambda x: pure(f(x)))
|
2014-09-16 00:32:07 +00:00
|
|
|
_shift.name = '(%s)' % (self.name,)
|
2014-09-02 17:03:50 +00:00
|
|
|
return _shift
|
|
|
|
|
|
|
|
def bind(self, f):
|
|
|
|
"""Parser(a, b), (b -> Parser(a, c)) -> Parser(a, c)
|
|
|
|
|
|
|
|
NOTE: A monadic bind function. It is used internally to implement other
|
|
|
|
combinators. Functions bind and pure make the Parser a Monad.
|
|
|
|
"""
|
|
|
|
|
|
|
|
@Parser
|
|
|
|
def _bind(tokens, s):
|
|
|
|
(v, s2) = self.run(tokens, s)
|
|
|
|
return f(v).run(tokens, s2)
|
|
|
|
|
2014-09-16 00:32:07 +00:00
|
|
|
_bind.name = '(%s >>=)' % (self.name,)
|
2014-09-02 17:03:50 +00:00
|
|
|
return _bind
|
|
|
|
|
|
|
|
|
|
|
|
class State(object):
|
|
|
|
"""A parsing state that is maintained basically for error reporting.
|
|
|
|
|
|
|
|
It consists of the current position pos in the sequence being parsed and
|
|
|
|
the position max of the rightmost token that has been consumed while
|
|
|
|
parsing.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, pos=0, max=0):
|
|
|
|
self.pos = pos
|
|
|
|
self.max = max
|
|
|
|
|
|
|
|
def __str__(self):
|
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
2016-09-02 06:48:13 +00:00
|
|
|
return str((self.pos, self.max))
|
2014-09-02 17:03:50 +00:00
|
|
|
|
|
|
|
def __repr__(self):
|
2014-09-16 00:32:07 +00:00
|
|
|
return 'State(%r, %r)' % (self.pos, self.max)
|
2014-09-02 17:03:50 +00:00
|
|
|
|
|
|
|
|
|
|
|
class NoParseError(Exception):
|
2016-10-10 05:00:30 +00:00
|
|
|
def __init__(self, msg='', state=None, token=None):
|
2014-09-02 17:03:50 +00:00
|
|
|
self.msg = msg
|
|
|
|
self.state = state
|
2016-10-10 05:00:30 +00:00
|
|
|
self.token = token # Next token
|
2014-09-02 17:03:50 +00:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.msg
|
|
|
|
|
|
|
|
|
|
|
|
class _Tuple(tuple):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class _Ignored(object):
|
|
|
|
def __init__(self, value):
|
|
|
|
self.value = value
|
|
|
|
|
|
|
|
def __repr__(self):
|
2014-09-16 00:32:07 +00:00
|
|
|
return '_Ignored(%s)' % repr(self.value)
|
2014-09-02 17:03:50 +00:00
|
|
|
|
|
|
|
|
|
|
|
@Parser
|
|
|
|
def finished(tokens, s):
|
|
|
|
"""Parser(a, None)
|
|
|
|
|
|
|
|
Throws an exception if any tokens are left in the input unparsed.
|
|
|
|
"""
|
|
|
|
if s.pos >= len(tokens):
|
|
|
|
return None, s
|
|
|
|
else:
|
2016-10-10 05:00:30 +00:00
|
|
|
raise NoParseError('should have reached <EOF>', s, tokens[s.pos])
|
2014-09-02 17:03:50 +00:00
|
|
|
|
|
|
|
|
2014-09-16 00:32:07 +00:00
|
|
|
finished.name = 'finished'
|
2014-09-02 17:03:50 +00:00
|
|
|
|
|
|
|
|
|
|
|
def many(p):
|
|
|
|
"""Parser(a, b) -> Parser(a, [b])
|
|
|
|
|
|
|
|
Returns a parser that infinitely applies the parser p to the input sequence
|
|
|
|
of tokens while it successfully parsers them. The resulting parser returns a
|
|
|
|
list of parsed values.
|
|
|
|
"""
|
|
|
|
|
|
|
|
@Parser
|
|
|
|
def _many(tokens, s):
|
|
|
|
"""Iterative implementation preventing the stack overflow."""
|
|
|
|
res = []
|
|
|
|
try:
|
|
|
|
while True:
|
|
|
|
(v, s) = p.run(tokens, s)
|
|
|
|
res.append(v)
|
|
|
|
except NoParseError as e:
|
|
|
|
return res, State(s.pos, e.state.max)
|
|
|
|
|
2014-09-16 00:32:07 +00:00
|
|
|
_many.name = '{ %s }' % p.name
|
2014-09-02 17:03:50 +00:00
|
|
|
return _many
|
|
|
|
|
|
|
|
|
|
|
|
def some(pred):
|
|
|
|
"""(a -> bool) -> Parser(a, a)
|
|
|
|
|
|
|
|
Returns a parser that parses a token if it satisfies a predicate pred.
|
|
|
|
"""
|
|
|
|
|
|
|
|
@Parser
|
|
|
|
def _some(tokens, s):
|
|
|
|
if s.pos >= len(tokens):
|
2014-09-16 00:32:07 +00:00
|
|
|
raise NoParseError('no tokens left in the stream', s)
|
2014-09-02 17:03:50 +00:00
|
|
|
else:
|
|
|
|
t = tokens[s.pos]
|
|
|
|
if pred(t):
|
|
|
|
pos = s.pos + 1
|
|
|
|
s2 = State(pos, max(pos, s.max))
|
|
|
|
if debug:
|
2014-09-16 00:32:07 +00:00
|
|
|
log.debug('*matched* "%s", new state = %s' % (t, s2))
|
2014-09-02 17:03:50 +00:00
|
|
|
return t, s2
|
|
|
|
else:
|
|
|
|
if debug:
|
2014-09-16 00:32:07 +00:00
|
|
|
log.debug('failed "%s", state = %s' % (t, s))
|
2016-10-10 05:00:30 +00:00
|
|
|
raise NoParseError('got unexpected token', s, t)
|
2014-09-02 17:03:50 +00:00
|
|
|
|
2014-09-16 00:32:07 +00:00
|
|
|
_some.name = '(some)'
|
2014-09-02 17:03:50 +00:00
|
|
|
return _some
|
|
|
|
|
|
|
|
|
|
|
|
def a(value):
|
|
|
|
"""Eq(a) -> Parser(a, a)
|
|
|
|
|
|
|
|
Returns a parser that parses a token that is equal to the value value.
|
|
|
|
"""
|
|
|
|
name = getattr(value, 'name', value)
|
2014-09-16 00:32:07 +00:00
|
|
|
return some(lambda t: t == value).named('(a "%s")' % (name,))
|
2014-09-02 17:03:50 +00:00
|
|
|
|
|
|
|
|
|
|
|
def pure(x):
|
|
|
|
@Parser
|
|
|
|
def _pure(_, s):
|
|
|
|
return x, s
|
|
|
|
|
2014-09-16 00:32:07 +00:00
|
|
|
_pure.name = '(pure %r)' % (x,)
|
2014-09-02 17:03:50 +00:00
|
|
|
return _pure
|
|
|
|
|
|
|
|
|
|
|
|
def maybe(p):
|
|
|
|
"""Parser(a, b) -> Parser(a, b or None)
|
|
|
|
|
|
|
|
Returns a parser that retuns None if parsing fails.
|
|
|
|
|
|
|
|
NOTE: In a statically typed language, the type Maybe b could be more
|
|
|
|
approprieate.
|
|
|
|
"""
|
2014-09-16 00:32:07 +00:00
|
|
|
return (p | pure(None)).named('[ %s ]' % (p.name,))
|
2014-09-02 17:03:50 +00:00
|
|
|
|
|
|
|
|
|
|
|
def skip(p):
|
|
|
|
"""Parser(a, b) -> Parser(a, _Ignored(b))
|
|
|
|
|
|
|
|
Returns a parser which results are ignored by the combinator +. It is useful
|
|
|
|
for throwing away elements of concrete syntax (e. g. ",", ";").
|
|
|
|
"""
|
|
|
|
return p >> _Ignored
|
|
|
|
|
|
|
|
|
|
|
|
def oneplus(p):
|
|
|
|
"""Parser(a, b) -> Parser(a, [b])
|
|
|
|
|
|
|
|
Returns a parser that applies the parser p one or more times.
|
|
|
|
"""
|
|
|
|
q = p + many(p) >> (lambda x: [x[0]] + x[1])
|
2014-09-16 00:32:07 +00:00
|
|
|
return q.named('(%s , { %s })' % (p.name, p.name))
|
2014-09-02 17:03:50 +00:00
|
|
|
|
|
|
|
|
|
|
|
def with_forward_decls(suspension):
|
|
|
|
"""(None -> Parser(a, b)) -> Parser(a, b)
|
|
|
|
|
|
|
|
Returns a parser that computes itself lazily as a result of the suspension
|
|
|
|
provided. It is needed when some parsers contain forward references to
|
|
|
|
parsers defined later and such references are cyclic. See examples for more
|
|
|
|
details.
|
|
|
|
"""
|
|
|
|
|
|
|
|
@Parser
|
|
|
|
def f(tokens, s):
|
|
|
|
return suspension().run(tokens, s)
|
|
|
|
|
|
|
|
return f
|
|
|
|
|
|
|
|
|
|
|
|
def forward_decl():
|
|
|
|
"""None -> Parser(?, ?)
|
|
|
|
|
|
|
|
Returns an undefined parser that can be used as a forward declaration. You
|
|
|
|
will be able to define() it when all the parsers it depends on are
|
|
|
|
available.
|
|
|
|
"""
|
|
|
|
|
|
|
|
@Parser
|
|
|
|
def f(tokens, s):
|
2014-09-16 00:32:07 +00:00
|
|
|
raise NotImplementedError('you must define() a forward_decl somewhere')
|
2014-09-02 17:03:50 +00:00
|
|
|
|
|
|
|
return f
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
import doctest
|
|
|
|
doctest.testmod()
|