| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import numbers |
| 4 |
import typing as ty |
| 5 |
from dataclasses import dataclass |
| 6 |
|
| 7 |
from flexparser import flexparser as fp |
| 8 |
|
| 9 |
from . import errors |
| 10 |
from .pintimports import ParserHelper, UnitsContainer |
| 11 |
|
| 12 |
|
| 13 |
@dataclass(frozen=True) |
| 14 |
class Config: |
| 15 |
"""Configuration used by the parser.""" |
| 16 |
|
| 17 |
|
| 18 |
non_int_type: ty.Type[numbers.Number] = float |
| 19 |
|
| 20 |
def to_scaled_units_container(self, s: str): |
| 21 |
return ParserHelper.from_string(s, self.non_int_type) |
| 22 |
|
| 23 |
def to_units_container(self, s: str): |
| 24 |
v = self.to_scaled_units_container(s) |
| 25 |
if v.scale != 1: |
| 26 |
raise errors.UnexpectedScaleInContainer(str(v.scale)) |
| 27 |
return UnitsContainer(v) |
| 28 |
|
| 29 |
def to_dimension_container(self, s: str): |
| 30 |
v = self.to_units_container(s) |
| 31 |
_ = [check_dim(el) for el in v.keys()] |
| 32 |
return v |
| 33 |
|
| 34 |
def to_number(self, s: str) -> numbers.Number: |
| 35 |
"""Try parse a string into a number (without using eval). |
| 36 |
|
| 37 |
The string can contain a number or a simple equation (3 + 4) |
| 38 |
|
| 39 |
Raises |
| 40 |
------ |
| 41 |
_NotNumeric |
| 42 |
If the string cannot be parsed as a number. |
| 43 |
""" |
| 44 |
val = self.to_scaled_units_container(s) |
| 45 |
if len(val): |
| 46 |
raise NotNumeric(s) |
| 47 |
return val.scale |
| 48 |
|
| 49 |
|
| 50 |
@dataclass(frozen=True) |
| 51 |
class Equality(fp.ParsedStatement): |
| 52 |
"""An equality statement contains a left and right hand separated |
| 53 |
by and equal (=) sign. |
| 54 |
|
| 55 |
lhs = rhs |
| 56 |
|
| 57 |
lhs and rhs are space stripped. |
| 58 |
""" |
| 59 |
|
| 60 |
lhs: str |
| 61 |
rhs: str |
| 62 |
|
| 63 |
@classmethod |
| 64 |
def from_string(cls, s: str) -> fp.NullableParsedResult[Equality]: |
| 65 |
if "=" not in s: |
| 66 |
return None |
| 67 |
parts = [p.strip() for p in s.split("=")] |
| 68 |
if len(parts) != 2: |
| 69 |
return errors.DefinitionSyntaxError( |
| 70 |
f"Exactly two terms expected, not {len(parts)} (`{s}`)" |
| 71 |
) |
| 72 |
return cls(*parts) |
| 73 |
|
| 74 |
|
| 75 |
@dataclass(frozen=True) |
| 76 |
class Comment(fp.ParsedStatement): |
| 77 |
"""Comments start with a # character. |
| 78 |
|
| 79 |
# This is a comment. |
| 80 |
## This is also a comment. |
| 81 |
|
| 82 |
Captured value does not include the leading # character and space stripped. |
| 83 |
""" |
| 84 |
|
| 85 |
comment: str |
| 86 |
|
| 87 |
@classmethod |
| 88 |
def from_string(cls, s: str) -> fp.NullableParsedResult[fp.ParsedStatement]: |
| 89 |
if not s.startswith("#"): |
| 90 |
return None |
| 91 |
return cls(s[1:].strip()) |
| 92 |
|
| 93 |
|
| 94 |
@dataclass(frozen=True) |
| 95 |
class EndDirectiveBlock(fp.ParsedStatement): |
| 96 |
"""An EndDirectiveBlock is simply an "@end" statement.""" |
| 97 |
|
| 98 |
@classmethod |
| 99 |
def from_string(cls, s: str) -> fp.NullableParsedResult[EndDirectiveBlock]: |
| 100 |
if s == "@end": |
| 101 |
return cls() |
| 102 |
return None |
| 103 |
|
| 104 |
|
| 105 |
@dataclass(frozen=True) |
| 106 |
class DirectiveBlock(fp.Block): |
| 107 |
"""Directive blocks have beginning statement starting with a @ character. |
| 108 |
and ending with a "@end" (captured using a EndDirectiveBlock). |
| 109 |
|
| 110 |
Subclass this class for convenience. |
| 111 |
""" |
| 112 |
|
| 113 |
closing: EndDirectiveBlock |
| 114 |
|
| 115 |
|
| 116 |
class NotNumeric(Exception): |
| 117 |
"""Internal exception. Do not expose outside Pint""" |
| 118 |
|
| 119 |
def __init__(self, value): |
| 120 |
self.value = value |
| 121 |
|
| 122 |
|
| 123 |
def is_dim(name: str) -> bool: |
| 124 |
return name[0] == "[" and name[-1] == "]" |
| 125 |
|
| 126 |
|
| 127 |
def check_dim(name: str) -> ty.Union[errors.DefinitionSyntaxError, str]: |
| 128 |
name = name.strip() |
| 129 |
if not is_dim(name): |
| 130 |
raise errors.DefinitionSyntaxError( |
| 131 |
f"Dimension definition `{name}` must be enclosed by []." |
| 132 |
) |
| 133 |
|
| 134 |
if not str.isidentifier(name[1:-1]): |
| 135 |
raise errors.DefinitionSyntaxError( |
| 136 |
f"`{name[1:-1]}` is not a valid dimension name (must follow Python identifier rules)." |
| 137 |
) |
| 138 |
|
| 139 |
return name |