Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/C/c.py
Original file line number Diff line number Diff line change
Expand Up @@ -1834,7 +1834,7 @@ def on_function_definition(self, target, option, names, values):
# -----------------------------------------


def main(*args):
def main():
"""
Unit-testing func
"""
Expand Down
91 changes: 70 additions & 21 deletions src/bison/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

from __future__ import absolute_import
from __future__ import print_function
import logging.config

import shutil
from os.path import dirname, join
Expand All @@ -37,6 +38,11 @@
from .node import BisonNode
from .convert import bisonToPython

import logging

LOGGER = logging.getLogger(__name__)


WIN_CHOCO_DIR = "C:\\ProgramData\\chocolatey\\lib\\winflexbison3\\tools\\"
WIN_FLEX = join( WIN_CHOCO_DIR, 'win_flex.exe')
WIN_BISON = join( WIN_CHOCO_DIR, 'win_bison.exe')
Expand Down Expand Up @@ -155,6 +161,37 @@ class BisonParser(object):

lasterror = None

logging_level: int = logging.WARNING
logging_config = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s] %(name)s (%(filename)s:%(lineno)d): %(message)s'
},
},
'handlers': {
'default': {
'level': 'DEBUG',
'formatter': 'standard',
'class': 'logging.StreamHandler',
'stream': 'ext://sys.stdout', # Default is stderr
},
},
'loggers': {
'bison': { # root logger
'handlers': ['default'],
'level': logging_level,
'propagate': True
},
'__main__': { # if __name__ == '__main__'
'handlers': ['default'],
'level': logging_level,
'propagate': False
},
}
}

def __init__(self, buildDirectory=None, **kw):
"""
Abstract representation of parser
Expand All @@ -172,7 +209,7 @@ def __init__(self, buildDirectory=None, **kw):
- defaultNodeClass - the class to use for creating parse nodes, default
is self.defaultNodeClass (in this base class, BisonNode)
"""
self.debug = kw.get('debug', 0)
self.debug = kw.get('debug', False)

if buildDirectory is not None:
self.buildDirectory = buildDirectory
Expand Down Expand Up @@ -209,6 +246,9 @@ def __init__(self, buildDirectory=None, **kw):
self.verbose = kw.get('verbose', False)
if self.verbose:
self.bisonCmd.append('--verbose')
self.logging_level = logging.INFO
if self.debug:
self.logging_level = logging.DEBUG

self.interactive = kw.get('interactive', False)
self.debugSymbols = kw.get('debugSymbols', False)
Expand All @@ -227,9 +267,18 @@ def __init__(self, buildDirectory=None, **kw):

self.BisonSyntaxError = BisonSyntaxError

# setup logging with dict config
self._set_logging_level()
logging.config.dictConfig(self.logging_config)

def __getitem__(self, idx):
return self.last[idx]

def _set_logging_level(self):
"""Sets logging level of all loggers with `logging_level`."""
for logger in self.logging_config["loggers"]:
self.logging_config["loggers"][logger]["level"] = self.logging_level

def _handle(self, targetname, option, names, values):
"""
Callback which receives a target from parser, as a targetname
Expand All @@ -247,7 +296,7 @@ def _handle(self, targetname, option, names, values):
except:
hdlrline = handler.__init__.__code__.co_firstlineno

print("BisonParser._handle: call handler at line {} with: {}".format(
LOGGER.info("BisonParser._handle: call handler at line {} with: {}".format(
hdlrline, str((targetname, option, names, values)))
)
try:
Expand All @@ -256,23 +305,26 @@ def _handle(self, targetname, option, names, values):
self.last = e
return e

# if self.verbose:
# print("handler for {} returned {}".format(targetname, repr(self.last)))
if self.verbose:
LOGGER.info("handler for {} returned {}".format(targetname, repr(self.last)))
else:
if self.verbose:
print("no handler for {}, using default".format(targetname))
LOGGER.info("no handler for {}, using default".format(targetname))

cls = self.default_node_class
self.last = cls(target=targetname, option=option, names=names,
values=values)

# assumedly the last thing parsed is at the top of the tree
# assumed the last thing parsed is at the top of the tree
return self.last

def handle_timeout(self, signum, frame):
raise TimeoutError("Computation exceeded timeout limit.")

def reset(self):
"""Reset engine."""
if self.verbose:
LOGGER.info("Reset engine '{}'.".format(self.bisonEngineLibName))
self.marker = 0
self.engine.reset()

Expand All @@ -295,7 +347,7 @@ def run(self, **kw):
- debug - enables garrulous parser debugging output, default 0
"""
if self.verbose:
print('Parser.run: calling engine')
LOGGER.info('Parser.run: calling engine')

filename = None
# grab keywords
Expand All @@ -317,9 +369,7 @@ def run(self, **kw):

read = kw.get('read', self.read)

debug = kw.get('debug', False)

# back up existing attribs
# back up existing attributes
oldfile = self.file
oldread = self.read

Expand All @@ -330,9 +380,9 @@ def run(self, **kw):
self.read = read

if self.verbose and self.marker:
print('Parser.run(): self.marker (', self.marker, ') is set')
LOGGER.info('Parser.run(): self.marker ({}) is set'.format(self.marker))
if self.verbose and self.file and self.file.closed:
print('Parser.run(): self.file', self.file, 'is closed')
LOGGER.info('Parser.run(): self.file {} is closed'.format(self.file))

error_count = 0
self.last = None
Expand All @@ -353,24 +403,24 @@ def run(self, **kw):
self.report_last_error(filename, e)

if self.verbose:
print('Parser.run: back from engine')
LOGGER.info('Parser.run: back from engine')

if hasattr(self, 'hook_run'):
self.last = self.hook_run(filename, self.last)

if self.verbose and not self.marker:
print('last:', self.last)
LOGGER.info('last:{}'.format(self.last))

if self.verbose:
print('last:', self.last)
LOGGER.info('last:{}'.format(self.last))

# restore old values
self.file = oldfile
self.read = oldread
self.marker = 0

if self.verbose:
print('------------------ result=', self.last)
LOGGER.info('------------------ result={}'.format(self.last))

# close the file if we opened one
if i_opened_a_file and fileobj:
Expand All @@ -391,14 +441,13 @@ def read(self, nbytes):
"""
# default to stdin
if self.verbose:
print('Parser.read: want %s bytes' % nbytes)
LOGGER.info('Parser.read: want %s bytes' % nbytes)

_bytes = self.file.readline(nbytes).replace(b'\r\n', b'\n').replace(b'\r', b'\n')

if self.verbose:
print('Parser.read: got %s bytes' % len(_bytes))
print(_bytes)

LOGGER.info('Parser.read: got %s bytes' % len(_bytes))
LOGGER.info(_bytes)
return _bytes

def report_last_error(self, filename, error):
Expand Down Expand Up @@ -438,7 +487,7 @@ def report_last_error(self, filename, error):
if self.verbose:
traceback.print_exc()

print('ERROR:', error)
LOGGER.error(error)

def report_syntax_error(self, msg, yytext, first_line, first_col, last_line, last_col):

Expand Down
Loading