How to use the pyparsing.ParseException function in pyparsing

To help you get started, we’ve selected a few pyparsing examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github seporaitis / mysqlparse / tests / grammar / test_data_type.py View on Github external
def test_varbinary(self):
        with self.assertRaises(pyparsing.ParseException):
            data_type_syntax.parseString("VARBINARY").data_type

        self.assertEquals(data_type_syntax.parseString("VARBINARY(8)").length[0], '8')
github stfc / PSyclone / src / psyclone / parse / kernel.py View on Github external
except AttributeError:
        raise ParseError(
            "In kernel metadata '{0}': '{1}' variable must be an array.".
            format(name, var_name))
    if len(descs.shape) != 1:
        raise ParseError(
            "In kernel metadata '{0}': '{1}' variable must be a 1 dimensional "
            "array.".format(name, var_name))
    if descs.init.find("[") != -1 and descs.init.find("]") != -1:
        # there is a bug in fparser1
        raise ParseError(
            "Parser does not currently support '[...]' initialisation for "
            "'{0}', please use '(/.../)' instead.".format(var_name))
    try:
        inits = expr.FORT_EXPRESSION.parseString(descs.init)[0]
    except ParseException:
        raise ParseError("Kernel metadata has an invalid format {0}.".
                         format(descs.init))
    nargs = int(descs.shape[0])
    if len(inits) != nargs:
        raise ParseError(
            "In the '{0}' metadata, the number of items in the array "
            "constructor ({1}) does not match the extent of the "
            "array ({2}).".format(var_name, len(inits), nargs))
    if var_type:
        # Check that each element in the list is of the correct type
        if not all([init.name == var_type for init in inits]):
            raise ParseError(
                "The '{0}' metadata must consist of an array of structure"
                " constructors, all of type '{1}' but found: {2}.".format(
                    var_name, var_type, [str(init.name) for init in inits]))
    return inits
github Cigna / ibis / ibis / inventor / dsl_parser.py View on Github external
def parse_file(self, path):
        """parses DSL file and validates it
        Args:
            path: DSL file path
        Returns:
            action_data: list of action names from config file
        """
        with open(path, 'rb') as file_h:
            lines = file_h.readlines()
        lines = Utilities.clean_lines(lines)
        action_data = []
        for index, line in enumerate(lines):
            try:
                result = self.pattern.parseString(line)
                action_data.append(result['action_body']['action_id'])
            except pp.ParseException as parse_ex:
                err_msg = "Line {lineno}, column {err.col}:\n"
                err_msg += "Fix this line: '{err.line}'"
                err_msg = err_msg.format(err=parse_ex, lineno=index + 1)
                err_msg = Utilities.print_box_msg(err_msg, border_char='x')
                raise ValueError(err_msg)
        return action_data
github linkedin / sensei / clients / python / sensei / bql_parser.py View on Github external
def contains_all_predicate_action(self, s, loc, tok):
    field = tok[0]
    ok, msg = self._verify_field_data_type(field, tok.value_list)
    if not ok:
      raise ParseSyntaxException(ParseException(s, loc, msg))
    ok, msg = self._verify_field_data_type(field, tok.except_values)
    if not ok:
      raise ParseSyntaxException(ParseException(s, loc, msg))

    return {"terms":
              {field:
                 {JSON_PARAM_VALUES: (tok.value_list[:] or []),
                  JSON_PARAM_EXCLUDES: (tok.except_values[:] or []),
                  JSON_PARAM_OPERATOR: PARAM_SELECT_OP_AND,
                  # XXX Need to check this based on facet info
                  JSON_PARAM_NO_OPTIMIZE: False
                  }
github pyparsing / pyparsing / examples / pgn.py View on Github external
def parsePGN(pgn, bnf=pgnGrammar, fn=None):
    try:
        return bnf.parseString(pgn)
    except ParseException as err:
        print(err.line)
        print(" " * (err.column - 1) + "^")
        print(err)
github inveniosoftware / invenio / modules / bibfield / lib / bibfield_config_engine.py View on Github external
def check_sub_indent(str, location, tokens):
        cur_col = col(location, str)
        if cur_col > indent_stack[-1]:
            indent_stack.append(cur_col)
        else:
            raise ParseException(str, location, "not a subentry")
github hgomersall / PicoPy / picopy / logic.py View on Github external
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#

import pyparsing
import qm
import sys

ParseError = pyparsing.ParseException

class BoolOperand(object):
    def __init__(self,t):
        self.args = t[0][0::2]

    def __unicode__(self):
        sep = u' %s ' % self.symbol
        return u'(' + sep.join([unicode(arg) for arg in self.args]) + u')'

    def __str__(self):
        return unicode(self).encode(
                sys.stdout.encoding or DEFAULT_ENCODING, 'replace')


class BoolAnd(BoolOperand):
    symbol = u'.'
github martinblech / pyfpm / pyfpm / parser.py View on Github external
def get_type(type_name):
        try:
            t = eval(type_name, context)
        except NameError:
            raise ParseException('unknown type: %s' % type_name)
        if not isinstance(t, type):
            raise ParseException('not a type: %s' % type_name)
        return t
github betodealmeida / gsheets-db-api / gsheetsdb / query.py View on Github external
def execute(query, headers=0, credentials=None):
    try:
        parsed_query = parse_sql(query)
    except pyparsing.ParseException as e:
        raise ProgrammingError(format_moz_error(query, e))

    # fetch aliases, since they will be removed by the translator
    original_aliases = extract_column_aliases(parsed_query)

    # extract URL from the `FROM` clause
    from_ = extract_url(query)
    baseurl = get_url(from_, headers)

    # verify that URL is actually a Google spreadsheet
    parsed = parse.urlparse(baseurl)
    if not parsed.netloc == 'docs.google.com':
        raise InterfaceError('Invalid URL, must be a docs.google.com URL!')

    # map between labels and ids, eg, `{ 'country': 'A' }`
    column_map = get_column_map(baseurl, credentials)
github pybel / pybel / src / pybel / io / line_utils.py View on Github external
:param bel_parser: A BEL parser
    :param use_tqdm: Use :mod:`tqdm` to show a progress bar? Requires reading whole file to memory.
    :param tqdm_kwargs: Keywords to pass to ``tqdm``
    """
    parse_statements_start_time = time.time()

    if use_tqdm:
        _tqdm_kwargs = dict(desc='Statements')
        if tqdm_kwargs:
            _tqdm_kwargs.update(tqdm_kwargs)
        enumerated_lines = tqdm(list(enumerated_lines), **_tqdm_kwargs)

    for line_number, line in enumerated_lines:
        try:
            bel_parser.parseString(line, line_number=line_number)
        except ParseException as e:
            exc = BELSyntaxError(line_number, line, e.loc)
            _log_parse_exception(graph, exc)
            graph.add_warning(exc, bel_parser.get_annotations())
        except PlaceholderAminoAcidWarning as exc:
            exc.line_number = line_number
            _log_parse_exception(graph, exc)
            graph.add_warning(exc, bel_parser.get_annotations())
        except BELParserWarning as exc:
            _log_parse_exception(graph, exc)
            graph.add_warning(exc, bel_parser.get_annotations())
        except Exception:
            parser_logger.exception(LOG_FMT, line_number, 0, 'General Failure', line)
            raise

    logger.info(
        'Parsed statements section in %.02f seconds with %d warnings',