1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
|
"""
pint.delegates.txt_defparser.plain
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Definitions for parsing:
- Equality
- CommentDefinition
- PrefixDefinition
- UnitDefinition
- DimensionDefinition
- DerivedDimensionDefinition
- AliasDefinition
Notices that some of the checks are done within the
format agnostic parent definition class.
See each one for a slighly longer description of the
syntax.
:copyright: 2022 by Pint Authors, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import annotations
from dataclasses import dataclass
import flexparser as fp
from ...converters import Converter
from ...facets.plain import definitions
from ...util import UnitsContainer
from ..base_defparser import ParserConfig, PintParsedStatement
from . import common
@dataclass(frozen=True)
class Equality(PintParsedStatement, definitions.Equality):
"""An equality statement contains a left and right hand separated
lhs and rhs should be space stripped.
"""
@classmethod
def from_string(cls, s: str) -> fp.NullableParsedResult[Equality]:
if "=" not in s:
return None
parts = [p.strip() for p in s.split("=")]
if len(parts) != 2:
return common.DefinitionSyntaxError(
f"Exactly two terms expected, not {len(parts)} (`{s}`)"
)
return cls(*parts)
@dataclass(frozen=True)
class CommentDefinition(PintParsedStatement, definitions.CommentDefinition):
"""Comments start with a # character.
# This is a comment.
## This is also a comment.
Captured value does not include the leading # character and space stripped.
"""
@classmethod
def from_string(cls, s: str) -> fp.NullableParsedResult[CommentDefinition]:
if not s.startswith("#"):
return None
return cls(s[1:].strip())
@dataclass(frozen=True)
class PrefixDefinition(PintParsedStatement, definitions.PrefixDefinition):
"""Definition of a prefix::
<prefix>- = <value> [= <symbol>] [= <alias>] [ = <alias> ] [...]
Example::
deca- = 1e+1 = da- = deka-
"""
@classmethod
def from_string_and_config(
cls, s: str, config: ParserConfig
) -> fp.NullableParsedResult[PrefixDefinition]:
if "=" not in s:
return None
name, value, *aliases = s.split("=")
name = name.strip()
if not name.endswith("-"):
return None
name = name.rstrip("-")
aliases = tuple(alias.strip().rstrip("-") for alias in aliases)
defined_symbol = None
if aliases:
if aliases[0] == "_":
aliases = aliases[1:]
else:
defined_symbol, *aliases = aliases
aliases = tuple(alias for alias in aliases if alias not in ("", "_"))
try:
value = config.to_number(value)
except definitions.NotNumeric as ex:
return common.DefinitionSyntaxError(
f"Prefix definition ('{name}') must contain only numbers, not {ex.value}"
)
try:
return cls(name, value, defined_symbol, aliases)
except Exception as exc:
return common.DefinitionSyntaxError(str(exc))
@dataclass(frozen=True)
class UnitDefinition(PintParsedStatement, definitions.UnitDefinition):
"""Definition of a unit::
<canonical name> = <relation to another unit or dimension> [= <symbol>] [= <alias>] [ = <alias> ] [...]
Example::
millennium = 1e3 * year = _ = millennia
Parameters
----------
reference : UnitsContainer
Reference units.
is_base : bool
Indicates if it is a base unit.
"""
@classmethod
def from_string_and_config(
cls, s: str, config: ParserConfig
) -> fp.NullableParsedResult[UnitDefinition]:
if "=" not in s:
return None
name, value, *aliases = (p.strip() for p in s.split("="))
defined_symbol = None
if aliases:
if aliases[0] == "_":
aliases = aliases[1:]
else:
defined_symbol, *aliases = aliases
aliases = tuple(alias for alias in aliases if alias not in ("", "_"))
if ";" in value:
[converter, modifiers] = value.split(";", 1)
try:
modifiers = {
key.strip(): config.to_number(value)
for key, value in (part.split(":") for part in modifiers.split(";"))
}
except definitions.NotNumeric as ex:
return common.DefinitionSyntaxError(
f"Unit definition ('{name}') must contain only numbers in modifier, not {ex.value}"
)
else:
converter = value
modifiers = {}
converter = config.to_scaled_units_container(converter)
try:
reference = UnitsContainer(converter)
# reference = converter.to_units_container()
except common.DefinitionSyntaxError as ex:
return common.DefinitionSyntaxError(f"While defining {name}: {ex}")
try:
converter = Converter.from_arguments(scale=converter.scale, **modifiers)
except Exception as ex:
return common.DefinitionSyntaxError(
f"Unable to assign a converter to the unit {ex}"
)
try:
return cls(name, defined_symbol, tuple(aliases), converter, reference)
except Exception as ex:
return common.DefinitionSyntaxError(str(ex))
@dataclass(frozen=True)
class DimensionDefinition(PintParsedStatement, definitions.DimensionDefinition):
"""Definition of a root dimension::
[dimension name]
Example::
[volume]
"""
@classmethod
def from_string(cls, s: str) -> fp.NullableParsedResult[DimensionDefinition]:
s = s.strip()
if not (s.startswith("[") and "=" not in s):
return None
return cls(s)
@dataclass(frozen=True)
class DerivedDimensionDefinition(
PintParsedStatement, definitions.DerivedDimensionDefinition
):
"""Definition of a derived dimension::
[dimension name] = <relation to other dimensions>
Example::
[density] = [mass] / [volume]
"""
@classmethod
def from_string_and_config(
cls, s: str, config: ParserConfig
) -> fp.NullableParsedResult[DerivedDimensionDefinition]:
if not (s.startswith("[") and "=" in s):
return None
name, value, *aliases = s.split("=")
if aliases:
return common.DefinitionSyntaxError(
"Derived dimensions cannot have aliases."
)
try:
reference = config.to_dimension_container(value)
except common.DefinitionSyntaxError as exc:
return common.DefinitionSyntaxError(
f"In {name} derived dimensions must only be referenced "
f"to dimensions. {exc}"
)
try:
return cls(name.strip(), reference)
except Exception as exc:
return common.DefinitionSyntaxError(str(exc))
@dataclass(frozen=True)
class AliasDefinition(PintParsedStatement, definitions.AliasDefinition):
"""Additional alias(es) for an already existing unit::
@alias <canonical name or previous alias> = <alias> [ = <alias> ] [...]
Example::
@alias meter = my_meter
"""
@classmethod
def from_string(cls, s: str) -> fp.NullableParsedResult[AliasDefinition]:
if not s.startswith("@alias "):
return None
name, *aliases = s[len("@alias ") :].split("=")
try:
return cls(name.strip(), tuple(alias.strip() for alias in aliases))
except Exception as exc:
return common.DefinitionSyntaxError(str(exc))
|