id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
162,890 | import os
import sys
import enum
import textwrap
import importlib
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Type,
Tuple,
Union,
Generic,
TypeVar,
ClassVar,
Iterable,
Iterator,
NoReturn,
Optional,
cast,
)
from keyword import iskeyword
from pathlib import Path
from importlib import util as importlib_util, machinery
from itertools import chain
from contextvars import ContextVar
from importlib.abc import InspectLoader
from typing_extensions import Annotated, override
import click
import pydantic
from pydantic.fields import PrivateAttr
from .. import config
from .utils import Faker, Sampler, clean_multiline
from ..utils import DEBUG_GENERATOR, assert_never
from ..errors import UnsupportedListTypeError
from .._compat import (
PYDANTIC_V2,
Field as FieldInfo,
BaseConfig,
ConfigDict,
BaseSettings,
GenericModel,
PlainSerializer,
BaseSettingsConfig,
model_dict,
model_parse,
model_rebuild,
root_validator,
cached_property,
field_validator,
)
from .._constants import QUERY_BUILDER_ALIASES
from ._dsl_parser import parse_schema_dsl
data_ctx: ContextVar['AnyData'] = ContextVar('data_ctx')
from .errors import (
TemplateError,
PartialTypeGeneratorError,
)
from .schema import Schema, ClientTypes
def sql_param(num: int = 1) -> str:
# TODO: add case for sqlserver
active_provider = data_ctx.get().datasources[0].active_provider
if active_provider == 'postgresql':
return f'${num}'
# TODO: test
if active_provider == 'mongodb': # pragma: no cover
raise RuntimeError('no-op')
# SQLite and MySQL use this style so just default to it
return '?' | null |
162,891 | import os
import sys
import enum
import textwrap
import importlib
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Type,
Tuple,
Union,
Generic,
TypeVar,
ClassVar,
Iterable,
Iterator,
NoReturn,
Optional,
cast,
)
from keyword import iskeyword
from pathlib import Path
from importlib import util as importlib_util, machinery
from itertools import chain
from contextvars import ContextVar
from importlib.abc import InspectLoader
from typing_extensions import Annotated, override
import click
import pydantic
from pydantic.fields import PrivateAttr
from .. import config
from .utils import Faker, Sampler, clean_multiline
from ..utils import DEBUG_GENERATOR, assert_never
from ..errors import UnsupportedListTypeError
from .._compat import (
PYDANTIC_V2,
Field as FieldInfo,
BaseConfig,
ConfigDict,
BaseSettings,
GenericModel,
PlainSerializer,
BaseSettingsConfig,
model_dict,
model_parse,
model_rebuild,
root_validator,
cached_property,
field_validator,
)
from .._constants import QUERY_BUILDER_ALIASES
from ._dsl_parser import parse_schema_dsl
from .errors import (
TemplateError,
PartialTypeGeneratorError,
)
from .schema import Schema, ClientTypes
class TemplateError(PrismaError):
pass
def raise_err(msg: str) -> NoReturn:
raise TemplateError(msg) | null |
162,892 | import os
import sys
import enum
import textwrap
import importlib
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Type,
Tuple,
Union,
Generic,
TypeVar,
ClassVar,
Iterable,
Iterator,
NoReturn,
Optional,
cast,
)
from keyword import iskeyword
from pathlib import Path
from importlib import util as importlib_util, machinery
from itertools import chain
from contextvars import ContextVar
from importlib.abc import InspectLoader
from typing_extensions import Annotated, override
import click
import pydantic
from pydantic.fields import PrivateAttr
from .. import config
from .utils import Faker, Sampler, clean_multiline
from ..utils import DEBUG_GENERATOR, assert_never
from ..errors import UnsupportedListTypeError
from .._compat import (
PYDANTIC_V2,
Field as FieldInfo,
BaseConfig,
ConfigDict,
BaseSettings,
GenericModel,
PlainSerializer,
BaseSettingsConfig,
model_dict,
model_parse,
model_rebuild,
root_validator,
cached_property,
field_validator,
)
from .._constants import QUERY_BUILDER_ALIASES
from ._dsl_parser import parse_schema_dsl
from .errors import (
TemplateError,
PartialTypeGeneratorError,
)
from .schema import Schema, ClientTypes
The provided code snippet includes necessary dependencies for implementing the `type_as_string` function. Write a Python function `def type_as_string(typ: str) -> str` to solve the following problem:
Ensure a type string is wrapped with a string, e.g. enums.Role -> 'enums.Role'
Here is the function:
def type_as_string(typ: str) -> str:
"""Ensure a type string is wrapped with a string, e.g.
enums.Role -> 'enums.Role'
"""
# TODO: use this function internally in this module
if not typ.startswith("'") and not typ.startswith('"'):
return f"'{typ}'"
return typ | Ensure a type string is wrapped with a string, e.g. enums.Role -> 'enums.Role' |
162,893 | import os
import sys
import enum
import textwrap
import importlib
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Type,
Tuple,
Union,
Generic,
TypeVar,
ClassVar,
Iterable,
Iterator,
NoReturn,
Optional,
cast,
)
from keyword import iskeyword
from pathlib import Path
from importlib import util as importlib_util, machinery
from itertools import chain
from contextvars import ContextVar
from importlib.abc import InspectLoader
from typing_extensions import Annotated, override
import click
import pydantic
from pydantic.fields import PrivateAttr
from .. import config
from .utils import Faker, Sampler, clean_multiline
from ..utils import DEBUG_GENERATOR, assert_never
from ..errors import UnsupportedListTypeError
from .._compat import (
PYDANTIC_V2,
Field as FieldInfo,
BaseConfig,
ConfigDict,
BaseSettings,
GenericModel,
PlainSerializer,
BaseSettingsConfig,
model_dict,
model_parse,
model_rebuild,
root_validator,
cached_property,
field_validator,
)
from .._constants import QUERY_BUILDER_ALIASES
from ._dsl_parser import parse_schema_dsl
from .errors import (
TemplateError,
PartialTypeGeneratorError,
)
from .schema import Schema, ClientTypes
The provided code snippet includes necessary dependencies for implementing the `format_documentation` function. Write a Python function `def format_documentation(doc: str, indent: int = 4) -> str` to solve the following problem:
Format a schema comment by indenting nested lines, e.g. '''Foo Bar''' Becomes '''Foo Bar '''
Here is the function:
def format_documentation(doc: str, indent: int = 4) -> str:
"""Format a schema comment by indenting nested lines, e.g.
'''Foo
Bar'''
Becomes
'''Foo
Bar
'''
"""
if not doc:
# empty string, nothing to do
return doc
prefix = ' ' * indent
first, *rest = doc.splitlines()
return '\n'.join(
[
first,
*[textwrap.indent(line, prefix) for line in rest],
prefix,
]
) | Format a schema comment by indenting nested lines, e.g. '''Foo Bar''' Becomes '''Foo Bar ''' |
162,894 | import os
import sys
import enum
import textwrap
import importlib
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Type,
Tuple,
Union,
Generic,
TypeVar,
ClassVar,
Iterable,
Iterator,
NoReturn,
Optional,
cast,
)
from keyword import iskeyword
from pathlib import Path
from importlib import util as importlib_util, machinery
from itertools import chain
from contextvars import ContextVar
from importlib.abc import InspectLoader
from typing_extensions import Annotated, override
import click
import pydantic
from pydantic.fields import PrivateAttr
from .. import config
from .utils import Faker, Sampler, clean_multiline
from ..utils import DEBUG_GENERATOR, assert_never
from ..errors import UnsupportedListTypeError
from .._compat import (
PYDANTIC_V2,
Field as FieldInfo,
BaseConfig,
ConfigDict,
BaseSettings,
GenericModel,
PlainSerializer,
BaseSettingsConfig,
model_dict,
model_parse,
model_rebuild,
root_validator,
cached_property,
field_validator,
)
from .._constants import QUERY_BUILDER_ALIASES
from ._dsl_parser import parse_schema_dsl
from .errors import (
TemplateError,
PartialTypeGeneratorError,
)
from .schema import Schema, ClientTypes
def _module_spec_serializer(spec: machinery.ModuleSpec) -> str:
assert spec.origin is not None, 'Cannot serialize module with no origin'
return spec.origin | null |
162,895 | import os
import sys
import enum
import textwrap
import importlib
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Type,
Tuple,
Union,
Generic,
TypeVar,
ClassVar,
Iterable,
Iterator,
NoReturn,
Optional,
cast,
)
from keyword import iskeyword
from pathlib import Path
from importlib import util as importlib_util, machinery
from itertools import chain
from contextvars import ContextVar
from importlib.abc import InspectLoader
from typing_extensions import Annotated, override
import click
import pydantic
from pydantic.fields import PrivateAttr
from .. import config
from .utils import Faker, Sampler, clean_multiline
from ..utils import DEBUG_GENERATOR, assert_never
from ..errors import UnsupportedListTypeError
from .._compat import (
PYDANTIC_V2,
Field as FieldInfo,
BaseConfig,
ConfigDict,
BaseSettings,
GenericModel,
PlainSerializer,
BaseSettingsConfig,
model_dict,
model_parse,
model_rebuild,
root_validator,
cached_property,
field_validator,
)
from .._constants import QUERY_BUILDER_ALIASES
from ._dsl_parser import parse_schema_dsl
from .errors import (
TemplateError,
PartialTypeGeneratorError,
)
from .schema import Schema, ClientTypes
def _pathlib_serializer(path: Path) -> str:
return str(path.absolute()) | null |
162,896 | import os
import sys
import enum
import textwrap
import importlib
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Type,
Tuple,
Union,
Generic,
TypeVar,
ClassVar,
Iterable,
Iterator,
NoReturn,
Optional,
cast,
)
from keyword import iskeyword
from pathlib import Path
from importlib import util as importlib_util, machinery
from itertools import chain
from contextvars import ContextVar
from importlib.abc import InspectLoader
from typing_extensions import Annotated, override
import click
import pydantic
from pydantic.fields import PrivateAttr
from .. import config
from .utils import Faker, Sampler, clean_multiline
from ..utils import DEBUG_GENERATOR, assert_never
from ..errors import UnsupportedListTypeError
from .._compat import (
PYDANTIC_V2,
Field as FieldInfo,
BaseConfig,
ConfigDict,
BaseSettings,
GenericModel,
PlainSerializer,
BaseSettingsConfig,
model_dict,
model_parse,
model_rebuild,
root_validator,
cached_property,
field_validator,
)
from .._constants import QUERY_BUILDER_ALIASES
from ._dsl_parser import parse_schema_dsl
RECURSIVE_TYPE_DEPTH_WARNING = """Some types are disabled by default due to being incompatible with Mypy, it is highly recommended
to use Pyright instead and configure Prisma Python to use recursive types. To re-enable certain types:"""
RECURSIVE_TYPE_DEPTH_WARNING_DESC = """
generator client {
provider = "prisma-client-py"
recursive_type_depth = -1
}
If you need to use Mypy, you can also disable this message by explicitly setting the default value:
generator client {
provider = "prisma-client-py"
recursive_type_depth = 5
}
For more information see: https://prisma-client-py.readthedocs.io/en/stable/reference/limitations/#default-type-limitations
"""
from .errors import (
TemplateError,
PartialTypeGeneratorError,
)
from .schema import Schema, ClientTypes
def _recursive_type_depth_factory() -> int:
click.echo(
click.style(
f'\n{RECURSIVE_TYPE_DEPTH_WARNING}',
fg='yellow',
)
)
click.echo(f'{RECURSIVE_TYPE_DEPTH_WARNING_DESC}\n')
return 5 | null |
162,897 |
The provided code snippet includes necessary dependencies for implementing the `quote` function. Write a Python function `def quote(string: str) -> str` to solve the following problem:
Surround the given string with single quotes. e.g. foo -> 'foo' This does not do any form of escaping, the input is expected to not contain any single quotes.
Here is the function:
def quote(string: str) -> str:
"""Surround the given string with single quotes. e.g.
foo -> 'foo'
This does not do any form of escaping, the input is expected to not contain any single quotes.
"""
return "'" + string + "'" | Surround the given string with single quotes. e.g. foo -> 'foo' This does not do any form of escaping, the input is expected to not contain any single quotes. |
162,898 | import os
import sys
import json
import shutil
import logging
import traceback
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Type, Generic, Optional, cast
from pathlib import Path
from contextvars import ContextVar
from typing_extensions import override
from jinja2 import Environment, StrictUndefined, FileSystemLoader
from pydantic import BaseModel, ValidationError
from . import jsonrpc
from .. import __version__
from .types import PartialModel
from .utils import (
copy_tree,
is_same_path,
resolve_template_path,
)
from ..utils import DEBUG, DEBUG_GENERATOR
from .errors import PartialTypeGeneratorError
from .models import PythonData, DefaultData
from .._types import BaseModelT, InheritsGeneric, get_args
from .filters import quote
from .jsonrpc import Manifest
from .._compat import model_json, model_parse, cached_property
log: logging.Logger = logging.getLogger(__name__)
DEFAULT_ENV = Environment(
trim_blocks=True,
lstrip_blocks=True,
loader=FileSystemLoader(Path(__file__).parent / 'templates'),
undefined=StrictUndefined,
)
DEFAULT_ENV.filters['quote'] = quote
def resolve_template_path(rootdir: Path, name: Union[str, Path]) -> Path:
return rootdir.joinpath(remove_suffix(name, '.jinja'))
def render_template(
rootdir: Path,
name: str,
params: Dict[str, Any],
*,
env: Optional[Environment] = None,
) -> None:
if env is None:
env = DEFAULT_ENV
template = env.get_template(name)
output = template.render(**params)
file = resolve_template_path(rootdir=rootdir, name=name)
if not file.parent.exists():
file.parent.mkdir(parents=True, exist_ok=True)
file.write_bytes(output.encode(sys.getdefaultencoding()))
log.debug('Rendered template to %s', file.absolute()) | null |
162,899 | import os
import sys
import json
import shutil
import logging
import traceback
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Type, Generic, Optional, cast
from pathlib import Path
from contextvars import ContextVar
from typing_extensions import override
from jinja2 import Environment, StrictUndefined, FileSystemLoader
from pydantic import BaseModel, ValidationError
from . import jsonrpc
from .. import __version__
from .types import PartialModel
from .utils import (
copy_tree,
is_same_path,
resolve_template_path,
)
from ..utils import DEBUG, DEBUG_GENERATOR
from .errors import PartialTypeGeneratorError
from .models import PythonData, DefaultData
from .._types import BaseModelT, InheritsGeneric, get_args
from .filters import quote
from .jsonrpc import Manifest
from .._compat import model_json, model_parse, cached_property
log: logging.Logger = logging.getLogger(__name__)
def _write_debug_data(name: str, output: str) -> None:
path = Path(__file__).parent.joinpath(f'debug-{name}.json')
with path.open('w') as file:
file.write(output)
log.debug('Wrote generator %s to %s', name, path.absolute()) | null |
162,900 | from enum import Enum
from typing import Any, Dict, List, Type, Tuple, Union, Optional
from typing_extensions import ClassVar
from pydantic import BaseModel
from .utils import to_constant_case
from .models import Model as ModelInfo, AnyData, PrimaryKey, DMMFEnumType
from .._compat import (
PYDANTIC_V2,
ConfigDict,
model_rebuild,
root_validator,
cached_property,
)
class PrismaEnum(PrismaType):
kind: Kind = Kind.enum
members: List[Tuple[str, str]]
def to_constant_case(input_str: str) -> str:
"""Converts to snake case + uppercase, examples:
foo_bar -> FOO_BAR
fooBar -> FOO_BAR
"""
return to_snake_case(input_str).upper()
def construct_enum_type(dmmf_enum_types: List[DMMFEnumType], *, name: str) -> Optional[PrismaEnum]:
enum_type = next((t for t in dmmf_enum_types if t.name == name), None)
if not enum_type:
return None
return PrismaEnum(
name=name,
members=[(to_constant_case(str(value)), str(value)) for value in enum_type.values],
) | null |
162,901 | from __future__ import annotations
from typing import Union
from typing_extensions import Literal, TypedDict
from .transformer import TransformResult, DefinitionTransformer
from ..._vendor.lark_schema_parser import Lark_StandAlone as LarkParser, UnexpectedInput
from ..._vendor.lark_schema_scan_parser import Lark_StandAlone as LarkScanner
schema_extension_parser = LarkParser()
transformer = DefinitionTransformer()
def scan_for_declarations(text: str) -> list[tuple[int, int]]:
"""Returns a list of (start, end) of parts of the text that
look like `@Python(...)`.
Note: this is just needed until Lark provides a more complete
way to scan for a grammar and also provide syntax errors.
https://github.com/lark-parser/lark/discussions/1390#discussioncomment-8354420
"""
return [indices for indices, _ in scanner.scan(text)]
ParseResult = Union[ParseResultOk, ParseResultInvalid, ParseResultNotApplicable]
The provided code snippet includes necessary dependencies for implementing the `parse_schema_dsl` function. Write a Python function `def parse_schema_dsl(text: str) -> ParseResult` to solve the following problem:
Given a string like `@Python(foo: bar)` returns `{ 'type': 'ok', 'value': { 'arguments': { 'foo': 'bar' } } }`. If the string is not valid syntax, then `{'type': 'invalid', 'error': 'msg'}` is returned. If the string is not actually even attempting to represent the `@Python` DSL, then `{'type': 'not_applicable'}` is returned. Note, currently `not_applicable` will be returned if there are no arguments given to `@Python`, e.g. `@Python()`. This currently doesn't matter, but it may be changed in the future.
Here is the function:
def parse_schema_dsl(text: str) -> ParseResult:
"""Given a string like `@Python(foo: bar)`
returns `{ 'type': 'ok', 'value': { 'arguments': { 'foo': 'bar' } } }`.
If the string is not valid syntax, then `{'type': 'invalid', 'error': 'msg'}`
is returned.
If the string is not actually even attempting to represent the `@Python`
DSL, then `{'type': 'not_applicable'}` is returned.
Note, currently `not_applicable` will be returned if there are no arguments given
to `@Python`, e.g. `@Python()`. This currently doesn't matter, but it may be changed
in the future.
"""
parts = scan_for_declarations(text)
if not parts:
return {'type': 'not_applicable'}
if len(parts) > 1:
# TODO: include context in error message
return {'type': 'invalid', 'error': f'Encountered multiple `@Python` declarations'}
start, end = parts[0]
snippet = text[start:end]
try:
parsed = schema_extension_parser.parse(snippet)
except UnexpectedInput as exc:
return {'type': 'invalid', 'error': str(exc) + exc.get_context(snippet)}
transformed = transformer.transform(parsed)
return {'type': 'ok', 'value': transformed} | Given a string like `@Python(foo: bar)` returns `{ 'type': 'ok', 'value': { 'arguments': { 'foo': 'bar' } } }`. If the string is not valid syntax, then `{'type': 'invalid', 'error': 'msg'}` is returned. If the string is not actually even attempting to represent the `@Python` DSL, then `{'type': 'not_applicable'}` is returned. Note, currently `not_applicable` will be returned if there are no arguments given to `@Python`, e.g. `@Python()`. This currently doesn't matter, but it may be changed in the future. |
162,902 | from __future__ import annotations
import sys
import json
import logging
from typing import Any, Dict, List, Type, Union, Optional
from pathlib import Path
from typing_extensions import Literal, TypedDict
from pydantic import Field
from .models import BaseModel
from .._compat import model_json
log: logging.Logger = logging.getLogger(__name__)
def readline() -> Optional[str]:
try:
line = input()
except EOFError:
log.debug('Ignoring EOFError')
return None
return line | null |
162,903 | from __future__ import annotations
import sys
import json
import logging
from typing import Any, Dict, List, Type, Union, Optional
from pathlib import Path
from typing_extensions import Literal, TypedDict
from pydantic import Field
from .models import BaseModel
from .._compat import model_json
class Request(BaseModel):
# JSON RPC protocol version
jsonrpc: str = '2.0'
# identifies a request
id: int
# request intention
method: str
# request payload
params: Optional[Dict[str, Any]] = None
method_mapping: Dict[str, Type[Request]] = {
'getManifest': Request,
'generate': Request,
}
def parse(line: str) -> Request:
data = json.loads(line)
try:
method = data['method']
except (KeyError, TypeError):
# TODO
raise
else:
request_type = method_mapping.get(method)
if request_type is None:
raise RuntimeError(f'Unknown method: {method}')
return request_type(**data) | null |
162,904 | from __future__ import annotations
import sys
import json
import logging
from typing import Any, Dict, List, Type, Union, Optional
from pathlib import Path
from typing_extensions import Literal, TypedDict
from pydantic import Field
from .models import BaseModel
from .._compat import model_json
log: logging.Logger = logging.getLogger(__name__)
Response = Union[SuccessResponse, ErrorResponse]
def model_json(
model: BaseModel,
*,
indent: int | None = None,
exclude: set[str] | None = None,
) -> str:
if PYDANTIC_V2:
return model.model_dump_json(indent=indent, exclude=exclude)
return model.json( # pyright: ignore[reportDeprecated]
indent=indent,
exclude=exclude,
)
def reply(response: Response) -> None:
dumped = model_json(response) + '\n'
print(dumped, file=sys.stderr, flush=True) # noqa: T201
log.debug('Replied with %s', dumped) | null |
162,905 | import click
from .utils import PrismaCLI
The provided code snippet includes necessary dependencies for implementing the `cli` function. Write a Python function `def cli() -> None` to solve the following problem:
Custom command line arguments specifically for Prisma Client Python. For other prisma commands, see prisma --help
Here is the function:
def cli() -> None:
"""Custom command line arguments specifically for
Prisma Client Python.
For other prisma commands, see prisma --help
""" | Custom command line arguments specifically for Prisma Client Python. For other prisma commands, see prisma --help |
162,906 | import json
from typing import List
from pathlib import Path
from importlib import import_module
import click
from ... import config, __version__
from ..utils import pretty_info
from ...binaries.platform import binary_platform
__version__ = '0.12.0'
def pretty_info(mapping: Mapping[str, Any]) -> str:
"""Pretty print a mapping
e.g {'foo': 'bar', 'hello': 1}
foo : bar
hello : 1
"""
pad = max(len(k) for k in mapping.keys())
return '\n'.join(f'{k.ljust(pad)} : {v}' for k, v in mapping.items())
def binary_platform() -> str:
platform = name()
if platform != 'linux':
return platform
distro = linux_distro()
if distro == 'alpine':
return 'linux-musl'
ssl = get_openssl()
return f'{distro}-openssl-{ssl}'
The provided code snippet includes necessary dependencies for implementing the `cli` function. Write a Python function `def cli(output_json: bool) -> None` to solve the following problem:
Display Prisma Client Python version information.
Here is the function:
def cli(output_json: bool) -> None:
"""Display Prisma Client Python version information."""
extras = {
'dev': 'nox',
'docs': 'mkdocs',
}
installed: List[str] = []
for extra, module in extras.items():
try:
import_module(module)
except ImportError:
continue
else:
installed.append(extra)
info = {
'prisma': config.prisma_version,
'prisma client python': __version__,
'platform': binary_platform(),
'expected engine version': config.expected_engine_version,
'installed extras': installed,
'install path': str(Path(__file__).resolve().parent.parent.parent),
'binary cache dir': str(config.binary_cache_dir),
}
if output_json:
click.echo(json.dumps({k.replace(' ', '-'): v for k, v in info.items()}, indent=2))
else:
click.echo(pretty_info(info)) | Display Prisma Client Python version information. |
162,907 | import shutil
import click
from ... import config
from ...cli.prisma import ensure_cached
def ensure_cached() -> CLICache:
cache_dir = config.binary_cache_dir
entrypoint = cache_dir / 'node_modules' / 'prisma' / 'build' / 'index.js'
if not cache_dir.exists():
cache_dir.mkdir(parents=True)
# We need to create a dummy `package.json` file so that `npm` doesn't try
# and search for it elsewhere.
#
# If it finds a different `package.json` file then the `prisma` package
# will be installed there instead of our cache directory.
package = cache_dir / 'package.json'
if not package.exists():
package.write_text(json.dumps(DEFAULT_PACKAGE_JSON))
if not entrypoint.exists():
click.echo('Installing Prisma CLI')
try:
proc = npm.run(
'install',
f'prisma@{config.prisma_version}',
cwd=config.binary_cache_dir,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
if proc.returncode != 0:
click.echo(
f'An error ocurred while installing the Prisma CLI; npm install log: {proc.stdout.decode("utf-8")}'
)
proc.check_returncode()
except Exception:
# as we use the entrypoint existing to check whether or not we should run `npm install`
# we need to make sure it doesn't exist if running `npm install` fails as it will otherwise
# lead to a broken state, https://github.com/RobertCraigie/prisma-client-py/issues/705
if entrypoint.exists():
try:
entrypoint.unlink()
except Exception:
pass
raise
if not entrypoint.exists():
raise PrismaError(
f'CLI installation appeared to complete but the expected entrypoint ({entrypoint}) could not be found.'
)
return CLICache(cache_dir=cache_dir, entrypoint=entrypoint)
The provided code snippet includes necessary dependencies for implementing the `cli` function. Write a Python function `def cli(force: bool) -> None` to solve the following problem:
Ensures all required binaries are available.
Here is the function:
def cli(force: bool) -> None:
"""Ensures all required binaries are available."""
if force:
shutil.rmtree(config.binary_cache_dir)
directory = ensure_cached().cache_dir
click.echo(f'Downloaded binaries to {click.style(str(directory), fg="green")}') | Ensures all required binaries are available. |
162,908 | from typing import Any, Optional, cast
import click
from .. import options
from ..utils import error, generate_client
from ...utils import module_exists, maybe_async_run, temp_env_update
The provided code snippet includes necessary dependencies for implementing the `_cli` function. Write a Python function `def _cli() -> None` to solve the following problem:
Commands for developing Prisma Client Python
Here is the function:
def _cli() -> None:
"""Commands for developing Prisma Client Python""" | Commands for developing Prisma Client Python |
162,909 | from typing import Any, Optional, cast
import click
from .. import options
from ..utils import error, generate_client
from ...utils import module_exists, maybe_async_run, temp_env_update
def generate_client(schema: Optional[str] = None, *, reload: bool = False) -> None:
"""Run `prisma generate` and update sys.modules"""
args = ['generate']
if schema is not None:
args.append(f'--schema={schema}')
maybe_exit(prisma.run(args))
if reload:
for name in sys.modules.copy():
if 'prisma' in name and 'generator' not in name:
sys.modules.pop(name, None)
def error(message: str) -> NoReturn:
...
def error(message: str, exit_: Literal[True]) -> NoReturn:
...
def error(message: str, exit_: Literal[False]) -> None:
...
def error(message: str, exit_: bool = True) -> Union[None, NoReturn]:
click.echo(click.style(message, fg='bright_red', bold=True), err=True)
if exit_:
sys.exit(1)
else:
return None
def maybe_async_run(
func: Union[FuncType, CoroType],
*args: Any,
**kwargs: Any,
) -> object:
if is_coroutine(func):
return async_run(func(*args, **kwargs))
return func(*args, **kwargs)
def module_exists(name: str) -> bool:
return find_spec(name) is not None
def temp_env_update(env: Dict[str, str]) -> Iterator[None]:
old = os.environ.copy()
try:
os.environ.update(env)
yield
finally:
for key in env:
os.environ.pop(key, None)
os.environ.update(old)
The provided code snippet includes necessary dependencies for implementing the `playground` function. Write a Python function `def playground(schema: Optional[str], skip_generate: bool) -> None` to solve the following problem:
Run the GraphQL playground
Here is the function:
def playground(schema: Optional[str], skip_generate: bool) -> None:
"""Run the GraphQL playground"""
if skip_generate and not module_exists('prisma.client'):
error('Prisma Client Python has not been generated yet.')
else:
generate_client(schema=schema, reload=True)
# TODO: this assumes we are generating to the same location that we are being invoked from
from ... import Prisma
from ...engine import QueryEngine
client = Prisma()
engine_class = client._engine_class
if engine_class.__name__ == 'QueryEngine':
with temp_env_update({'__PRISMA_PY_PLAYGROUND': '1'}):
maybe_async_run(client.connect)
# TODO: this is the result of a badly designed class
engine = cast(QueryEngine, client._engine)
assert engine.process is not None, 'Engine process unavailable for some reason'
engine.process.wait()
else: # pragma: no cover
error(f'Unsupported engine type: "{engine_class}"') | Run the GraphQL playground |
162,910 | import sys
import logging
from typing import Any, Dict, Tuple, Optional
from pathlib import Path
import click
import pydantic
from .. import prisma, options
from ..utils import EnumChoice, PathlibPath, warning
from ..._compat import PYDANTIC_V2
from ...generator.models import InterfaceChoices
ARG_TO_CONFIG_KEY = {
'partials': 'partial_type_generator',
'type_depth': 'recursive_type_depth',
}
log: logging.Logger = logging.getLogger(__name__)
def serialize(key: str, obj: Any) -> str:
if not PYDANTIC_V2:
if key == 'partials':
# partials has to be JSON serializable
return f'"{obj}"'
return str(obj)
def warning(message: str) -> None:
click.echo(click.style('WARNING: ', fg='bright_yellow') + click.style(message, bold=True))
The provided code snippet includes necessary dependencies for implementing the `cli` function. Write a Python function `def cli(schema: Optional[Path], watch: bool, generator: Tuple[str], **kwargs: Any) -> None` to solve the following problem:
Generate prisma artifacts with modified config options
Here is the function:
def cli(schema: Optional[Path], watch: bool, generator: Tuple[str], **kwargs: Any) -> None:
"""Generate prisma artifacts with modified config options"""
# context https://github.com/microsoft/pyright/issues/6099
if pydantic.VERSION.split('.') < ['1', '8']: # pyright: ignore
warning(
'Unsupported version of pydantic installed, this command may not work as intended\n'
'Please update pydantic to 1.8 or greater.\n'
)
args = ['generate']
if schema is not None:
args.append(f'--schema={schema}')
if watch:
args.append('--watch')
if generator:
for name in generator:
args.append(f'--generator={name}')
env: Dict[str, str] = {}
prefix = 'PRISMA_PY_CONFIG_'
for key, value in kwargs.items():
if value is None:
continue
env[prefix + ARG_TO_CONFIG_KEY.get(key, key).upper()] = serialize(key, value)
log.debug('Running generate with env: %s', env)
sys.exit(prisma.run(args, env=env)) | Generate prisma artifacts with modified config options |
162,911 | import os
import sys
import logging
import contextlib
from typing import List, Iterator, NoReturn, Optional
import click
from . import prisma
from .. import _sync_http as http
from .utils import error
from ..utils import DEBUG
from .custom import cli
from ..generator import Generator
log: logging.Logger = logging.getLogger(__name__)
DEBUG = _env_bool('PRISMA_PY_DEBUG')
def setup_logging(use_handler: bool = True) -> Iterator[None]:
handler = None
logger = logging.getLogger()
try:
if DEBUG:
logger.setLevel(logging.DEBUG)
# the prisma CLI binary uses the DEBUG environment variable
if os.environ.get('DEBUG') is None:
os.environ['DEBUG'] = 'prisma:GeneratorProcess'
else:
log.debug('Not overriding the DEBUG environment variable.')
else:
logger.setLevel(logging.INFO)
if use_handler:
fmt = logging.Formatter(
'[{levelname:<7}] {name}: {message}',
style='{',
)
handler = logging.StreamHandler()
handler.setFormatter(fmt)
logger.addHandler(handler)
yield
finally:
if use_handler and handler is not None:
handler.close()
logger.removeHandler(handler) | null |
162,912 | import os
import sys
import logging
import contextlib
from typing import List, Iterator, NoReturn, Optional
import click
from . import prisma
from .. import _sync_http as http
from .utils import error
from ..utils import DEBUG
from .custom import cli
from ..generator import Generator
def cleanup(do_cleanup: bool = True) -> Iterator[None]:
try:
yield
finally:
if do_cleanup:
http.client.close() | null |
162,913 | from __future__ import annotations
import os
import sys
import logging
from enum import Enum
from typing import (
Any,
List,
Type,
Union,
Mapping,
NoReturn,
Optional,
overload,
)
from pathlib import Path
from typing_extensions import override
import click
from . import prisma
from ..utils import module_exists
from .._types import Literal
def is_module(path: Path) -> bool:
return path.is_dir() and path.joinpath('__init__.py').exists() | null |
162,914 | from __future__ import annotations
import os
import re
import sys
import shutil
import logging
import subprocess
from abc import ABC, abstractmethod
from typing import IO, Any, Union, Mapping, cast
from pathlib import Path
from typing_extensions import Literal, override
from .. import config
from .._proxy import LazyProxy
from ..errors import PrismaError
from .._compat import nodejs, get_args
from ..binaries import platform
log: logging.Logger = logging.getLogger(__name__)
Target = Literal['node', 'npm']
class UnknownTargetError(PrismaError):
def __init__(self, *, target: str) -> None:
super().__init__(f'Unknown target: {target}; Valid choices are: {", ".join(get_args(cast(type, Target)))}')
class NodeBinaryStrategy(Strategy):
target: Target
resolver: Literal['global', 'nodeenv']
def __init__(
self,
*,
path: Path,
target: Target,
resolver: Literal['global', 'nodeenv'],
) -> None:
self.path = path
self.target = target
self.resolver = resolver
def target_bin(self) -> Path:
return self.path.parent
def __run__(
self,
*args: str,
check: bool = False,
cwd: Path | None = None,
stdout: File | None = None,
stderr: File | None = None,
env: Mapping[str, str] | None = None,
) -> subprocess.CompletedProcess[bytes]:
path = str(self.path.absolute())
log.debug('Executing binary at %s with args: %s', path, args)
return subprocess.run(
[path, *args],
check=check,
cwd=cwd,
env=env,
stdout=stdout,
stderr=stderr,
)
def resolve(cls, target: Target) -> NodeBinaryStrategy:
path = None
if config.use_global_node:
path = _get_global_binary(target)
if path is not None:
return NodeBinaryStrategy(
path=path,
target=target,
resolver='global',
)
return NodeBinaryStrategy.from_nodeenv(target)
def from_nodeenv(cls, target: Target) -> NodeBinaryStrategy:
cache_dir = config.nodeenv_cache_dir.absolute()
if cache_dir.exists():
log.debug(
'Skipping nodeenv installation as it already exists at %s',
cache_dir,
)
else:
log.debug('Installing nodeenv to %s', cache_dir)
try:
subprocess.run(
[
sys.executable,
'-m',
'nodeenv',
str(cache_dir),
*config.nodeenv_extra_args,
],
check=True,
stdout=sys.stdout,
stderr=sys.stderr,
)
except Exception as exc:
print( # noqa: T201
'nodeenv installation failed; You may want to try installing `nodejs-bin` as it is more reliable.',
file=sys.stderr,
)
raise exc
if not cache_dir.exists():
raise RuntimeError(
'Could not install nodeenv to the expected directory; See the output above for more details.'
)
# TODO: what hapens on cygwin?
if platform.name() == 'windows':
bin_dir = cache_dir / 'Scripts'
if target == 'node':
path = bin_dir / 'node.exe'
else:
path = bin_dir / f'{target}.cmd'
else:
path = cache_dir / 'bin' / target
if target == 'npm':
return cls(path=path, resolver='nodeenv', target=target)
elif target == 'node':
return cls(path=path, resolver='nodeenv', target=target)
else:
raise UnknownTargetError(target=target)
class NodeJSPythonStrategy(Strategy):
target: Target
resolver: Literal['nodejs-bin']
def __init__(self, *, target: Target) -> None:
self.target = target
self.resolver = 'nodejs-bin'
def __run__(
self,
*args: str,
check: bool = False,
cwd: Path | None = None,
stdout: File | None = None,
stderr: File | None = None,
env: Mapping[str, str] | None = None,
) -> subprocess.CompletedProcess[bytes]:
if nodejs is None:
raise MissingNodejsBinError()
func = None
if self.target == 'node':
func = nodejs.node.run
elif self.target == 'npm':
func = nodejs.npm.run
else:
raise UnknownTargetError(target=self.target)
return cast(
'subprocess.CompletedProcess[bytes]',
func(
args,
check=check,
cwd=cwd,
env=env,
stdout=stdout,
stderr=stderr,
),
)
def node_path(self) -> Path:
"""Returns the path to the `node` binary"""
if nodejs is None:
raise MissingNodejsBinError()
return Path(nodejs.node.path)
def target_bin(self) -> Path:
return Path(self.node_path).parent
Node = Union[NodeJSPythonStrategy, NodeBinaryStrategy]
def resolve(target: Target) -> Node:
if target not in {'node', 'npm'}:
raise UnknownTargetError(target=target)
if config.use_nodejs_bin:
log.debug('Checking if nodejs-bin is installed')
if nodejs is not None:
log.debug('Using nodejs-bin with version: %s', nodejs.node_version)
return NodeJSPythonStrategy(target=target)
return NodeBinaryStrategy.resolve(target) | null |
162,915 | from __future__ import annotations
import os
import re
import sys
import shutil
import logging
import subprocess
from abc import ABC, abstractmethod
from typing import IO, Any, Union, Mapping, cast
from pathlib import Path
from typing_extensions import Literal, override
from .. import config
from .._proxy import LazyProxy
from ..errors import PrismaError
from .._compat import nodejs, get_args
from ..binaries import platform
log: logging.Logger = logging.getLogger(__name__)
The provided code snippet includes necessary dependencies for implementing the `_update_path_env` function. Write a Python function `def _update_path_env( *, env: Mapping[str, str] | None, target_bin: Path, sep: str = os.pathsep, ) -> dict[str, str]` to solve the following problem:
Returns a modified version of `os.environ` with the `PATH` environment variable updated to include the location of the downloaded Node binaries.
Here is the function:
def _update_path_env(
*,
env: Mapping[str, str] | None,
target_bin: Path,
sep: str = os.pathsep,
) -> dict[str, str]:
"""Returns a modified version of `os.environ` with the `PATH` environment variable updated
to include the location of the downloaded Node binaries.
"""
if env is None:
env = dict(os.environ)
log.debug('Attempting to preprend %s to the PATH', target_bin)
assert target_bin.exists(), 'Target `bin` directory does not exist'
path = env.get('PATH', '') or os.environ.get('PATH', '')
if path:
# handle the case where the PATH already starts with the separator (this probably shouldn't happen)
if path.startswith(sep):
path = f'{target_bin.absolute()}{path}'
else:
path = f'{target_bin.absolute()}{sep}{path}'
else:
# handle the case where there is no PATH set (unlikely / impossible to actually happen?)
path = str(target_bin.absolute())
log.debug('Using PATH environment variable: %s', path)
return {**env, 'PATH': path} | Returns a modified version of `os.environ` with the `PATH` environment variable updated to include the location of the downloaded Node binaries. |
162,916 | from __future__ import annotations
import os
import re
import sys
import shutil
import logging
import subprocess
from abc import ABC, abstractmethod
from typing import IO, Any, Union, Mapping, cast
from pathlib import Path
from typing_extensions import Literal, override
from .. import config
from .._proxy import LazyProxy
from ..errors import PrismaError
from .._compat import nodejs, get_args
from ..binaries import platform
log: logging.Logger = logging.getLogger(__name__)
Target = Literal['node', 'npm']
def _should_use_binary(target: Target, path: Path) -> bool:
"""Call the binary at `path` with a `--version` flag to check if it matches our minimum version requirements.
This only applies to the global node installation as:
- the minimum version of `nodejs-bin` is higher than our requirement
- `nodeenv` defaults to the latest stable version of node
"""
if target == 'node':
min_version = MIN_NODE_VERSION
elif target == 'npm':
min_version = MIN_NPM_VERSION
else:
raise UnknownTargetError(target=target)
version = _get_binary_version(target, path)
if version is None:
log.debug(
'Could not resolve %s version, ignoring global %s installation',
target,
target,
)
return False
if version < min_version:
log.debug(
'Global %s version (%s) is lower than the minimum required version (%s), ignoring',
target,
version,
min_version,
)
return False
return True
The provided code snippet includes necessary dependencies for implementing the `_get_global_binary` function. Write a Python function `def _get_global_binary(target: Target) -> Path | None` to solve the following problem:
Returns the path to a globally installed binary. This also ensures that the binary is of the right version.
Here is the function:
def _get_global_binary(target: Target) -> Path | None:
"""Returns the path to a globally installed binary.
This also ensures that the binary is of the right version.
"""
log.debug('Checking for global target binary: %s', target)
which = shutil.which(target)
if which is None:
log.debug('Global target binary: %s not found', target)
return None
log.debug('Found global binary at: %s', which)
path = Path(which)
if not path.exists():
log.debug('Global binary does not exist at: %s', which)
return None
if not _should_use_binary(target=target, path=path):
return None
log.debug('Using global %s binary at %s', target, path)
return path | Returns the path to a globally installed binary. This also ensures that the binary is of the right version. |
162,917 | from __future__ import annotations
import json
from typing import (
Any,
Callable,
overload,
)
from ._types import BaseModelT
from ._compat import model_parse
def deserialize_raw_results(raw_list: list[dict[str, Any]]) -> list[dict[str, Any]]:
... | null |
162,918 | from __future__ import annotations
import json
from typing import (
Any,
Callable,
overload,
)
from ._types import BaseModelT
from ._compat import model_parse
BaseModelT = TypeVar('BaseModelT', bound=BaseModel)
def deserialize_raw_results(
raw_list: list[dict[str, object]],
model: type[BaseModelT],
) -> list[BaseModelT]:
... | null |
162,919 | from __future__ import annotations
import json
from typing import (
Any,
Callable,
overload,
)
from ._types import BaseModelT
from ._compat import model_parse
def _deserialize_prisma_object(
raw_obj: dict[str, Any],
*,
for_model: bool,
) -> dict[str, Any]:
...
def _deserialize_prisma_object(
raw_obj: dict[str, object],
*,
for_model: bool,
model: type[BaseModelT],
) -> BaseModelT:
...
def _deserialize_prisma_object(
raw_obj: dict[Any, Any],
*,
for_model: bool,
model: type[BaseModelT] | None = None,
) -> BaseModelT | dict[str, Any]:
# create a local reference to avoid performance penalty of global
# lookups on some python versions
_deserializers = DESERIALIZERS
new_obj = {}
for key, raw_value in raw_obj.items():
value = raw_value['prisma__value']
prisma_type = raw_value['prisma__type']
new_obj[key] = _deserializers[prisma_type](value, for_model) if prisma_type in _deserializers else value
if model is not None:
return model_parse(model, new_obj)
return new_obj
BaseModelT = TypeVar('BaseModelT', bound=BaseModel)
The provided code snippet includes necessary dependencies for implementing the `deserialize_raw_results` function. Write a Python function `def deserialize_raw_results( raw_list: list[dict[str, Any]], model: type[BaseModelT] | None = None, ) -> list[BaseModelT] | list[dict[str, Any]]` to solve the following problem:
Deserialize a list of raw query results into their rich Python types. If `model` is given, convert each result into the corresponding model. Otherwise results are returned as a dictionary
Here is the function:
def deserialize_raw_results(
raw_list: list[dict[str, Any]],
model: type[BaseModelT] | None = None,
) -> list[BaseModelT] | list[dict[str, Any]]:
"""Deserialize a list of raw query results into their rich Python types.
If `model` is given, convert each result into the corresponding model.
Otherwise results are returned as a dictionary
"""
if model is not None:
return [_deserialize_prisma_object(obj, model=model, for_model=True) for obj in raw_list]
return [_deserialize_prisma_object(obj, for_model=False) for obj in raw_list] | Deserialize a list of raw query results into their rich Python types. If `model` is given, convert each result into the corresponding model. Otherwise results are returned as a dictionary |
162,920 | from __future__ import annotations
import json
from typing import (
Any,
Callable,
overload,
)
from ._types import BaseModelT
from ._compat import model_parse
def _deserialize_bigint(value: str, _for_model: bool) -> int:
return int(value) | null |
162,921 | from __future__ import annotations
import json
from typing import (
Any,
Callable,
overload,
)
from ._types import BaseModelT
from ._compat import model_parse
def _deserialize_decimal(value: str, _for_model: bool) -> float:
return float(value) | null |
162,922 | from __future__ import annotations
import json
from typing import (
Any,
Callable,
overload,
)
from ._types import BaseModelT
from ._compat import model_parse
DESERIALIZERS: dict[str, Callable[[Any, bool], object]] = {
'bigint': _deserialize_bigint,
'decimal': _deserialize_decimal,
'array': _deserialize_array,
'json': _deserialize_json,
}
def _deserialize_array(value: list[Any], for_model: bool) -> list[Any]:
# create a local reference to avoid performance penalty of global
# lookups on some python versions
_deserializers = DESERIALIZERS
arr = []
for entry in value:
prisma_type = entry['prisma__type']
prisma_value = entry['prisma__value']
arr.append(
(_deserializers[prisma_type](prisma_value, for_model) if prisma_type in _deserializers else prisma_value)
)
return arr | null |
162,923 | from __future__ import annotations
import json
from typing import (
Any,
Callable,
overload,
)
from ._types import BaseModelT
from ._compat import model_parse
def _deserialize_json(value: object, for_model: bool) -> object:
# TODO: this may break if someone inserts just a string into the database
if not isinstance(value, str) and for_model:
# TODO: this is very bad
#
# Pydantic expects Json fields to be a `str`, we should implement
# an actual workaround for this validation instead of wasting compute
# on re-serializing the data.
return json.dumps(value)
# This may or may not have already been deserialized by the database
return value | null |
162,924 | from __future__ import annotations
import os
import sys
import time
import socket
import logging
import subprocess
from typing import Any, Dict, Type, NoReturn
from pathlib import Path
from . import errors
from .. import config, errors as prisma_errors
from ..utils import DEBUG_GENERATOR, time_since
from ..binaries import platform
from ..http_abstract import AbstractResponse
log: logging.Logger = logging.getLogger(__name__)
def query_engine_name() -> str:
def _resolve_from_binary_paths(binary_paths: dict[str, str]) -> Path | None:
from ..errors import PrismaError
DEBUG_GENERATOR = _env_bool('PRISMA_PY_DEBUG_GENERATOR')
def time_since(start: float, precision: int = 4) -> str:
def ensure(binary_paths: dict[str, str]) -> Path:
start_time = time.monotonic()
file = None
force_version = not DEBUG_GENERATOR
name = query_engine_name()
local_path = Path.cwd().joinpath(name)
global_path = config.binary_cache_dir.joinpath(name)
file_from_paths = _resolve_from_binary_paths(binary_paths)
log.debug('Expecting local query engine %s', local_path)
log.debug('Expecting global query engine %s', global_path)
binary = os.environ.get('PRISMA_QUERY_ENGINE_BINARY')
if binary:
log.debug('PRISMA_QUERY_ENGINE_BINARY is defined, using %s', binary)
if not Path(binary).exists():
raise errors.BinaryNotFoundError(
'PRISMA_QUERY_ENGINE_BINARY was provided, ' f'but no query engine was found at {binary}'
)
file = Path(binary)
force_version = False
elif local_path.exists():
file = local_path
log.debug('Query engine found in the working directory')
elif file_from_paths is not None and file_from_paths.exists():
file = file_from_paths
log.debug(
'Query engine found from the Prisma CLI generated path: %s',
file_from_paths,
)
elif global_path.exists():
file = global_path
log.debug('Query engine found in the global path')
if not file:
if file_from_paths is not None:
expected = f'{local_path}, {global_path} or {file_from_paths} to exist but none'
else:
expected = f'{local_path} or {global_path} to exist but neither'
raise errors.BinaryNotFoundError(
f'Expected {expected} were found or could not be executed.\n' + 'Try running prisma py fetch'
)
log.debug('Using Query Engine binary at %s', file)
start_version = time.monotonic()
process = subprocess.run([str(file.absolute()), '--version'], stdout=subprocess.PIPE, check=True)
log.debug('Version check took %s', time_since(start_version))
version = str(process.stdout, sys.getdefaultencoding()).replace('query-engine', '').strip()
log.debug('Using query engine version %s', version)
if force_version and version != config.expected_engine_version:
raise errors.MismatchedVersionsError(expected=config.expected_engine_version, got=version)
log.debug('Using query engine at %s', file)
log.debug('Ensuring query engine took: %s', time_since(start_time))
return file | null |
162,925 | from __future__ import annotations
import os
import sys
import time
import socket
import logging
import subprocess
from typing import Any, Dict, Type, NoReturn
from pathlib import Path
from . import errors
from .. import config, errors as prisma_errors
from ..utils import DEBUG_GENERATOR, time_since
from ..binaries import platform
from ..http_abstract import AbstractResponse
def get_open_port() -> int:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 0))
port = sock.getsockname()[1]
sock.close()
return int(port) | null |
162,926 | from __future__ import annotations
import os
import sys
import time
import socket
import logging
import subprocess
from typing import Any, Dict, Type, NoReturn
from pathlib import Path
from . import errors
from .. import config, errors as prisma_errors
from ..utils import DEBUG_GENERATOR, time_since
from ..binaries import platform
from ..http_abstract import AbstractResponse
log: logging.Logger = logging.getLogger(__name__)
ERROR_MAPPING: Dict[str, Type[Exception]] = {
'P2002': prisma_errors.UniqueViolationError,
'P2003': prisma_errors.ForeignKeyViolationError,
'P2009': prisma_errors.FieldNotFoundError,
'P2010': prisma_errors.RawQueryError,
'P2012': prisma_errors.MissingRequiredValueError,
'P2019': prisma_errors.InputError,
'P2021': prisma_errors.TableNotFoundError,
'P2025': prisma_errors.RecordNotFoundError,
}
META_ERROR_MAPPING: dict[str, type[Exception]] = {
'UnknownArgument': prisma_errors.FieldNotFoundError,
'UnknownInputField': prisma_errors.FieldNotFoundError,
'UnknownSelectionField': prisma_errors.FieldNotFoundError,
}
from ..errors import PrismaError
class AbstractResponse(ABC, Generic[Response]):
original: Response
__slots__ = ('original',)
def __init__(self, original: Response) -> None:
self.original = original
def status(self) -> int:
...
def headers(self) -> Headers:
...
def json(self) -> MaybeCoroutine[Any]:
...
def text(self) -> MaybeCoroutine[str]:
...
def __repr__(self) -> str:
return str(self)
def __str__(self) -> str:
return f'<Response wrapped={self.original} >'
def handle_response_errors(resp: AbstractResponse[Any], data: Any) -> NoReturn:
for error in data:
try:
base_error_message = error.get('error', '')
user_facing = error.get('user_facing_error', {})
code = user_facing.get('error_code')
if code is None:
continue
# TODO: the order of these if statements is important because
# the P2009 code can be returned for both: missing a required value
# and an unknown field error. As we want to explicitly handle
# the missing a required value error then we need to check for that first.
# As we can only check for this error by searching the message then this
# comes with performance concerns.
message = user_facing.get('message', '')
if code == 'P2028':
if base_error_message.startswith('Transaction already closed'):
raise prisma_errors.TransactionExpiredError(base_error_message)
raise prisma_errors.TransactionError(message)
if 'A value is required but not set' in message:
raise prisma_errors.MissingRequiredValueError(error)
exc: type[Exception] | None = None
kind = user_facing.get('meta', {}).get('kind')
if kind is not None:
exc = META_ERROR_MAPPING.get(kind)
if exc is None:
exc = ERROR_MAPPING.get(code)
if exc is not None:
raise exc(error)
except (KeyError, TypeError) as err:
log.debug('Ignoring error while constructing specialized error %s', err)
continue
try:
raise prisma_errors.DataError(data[0])
except (IndexError, TypeError):
pass
raise errors.EngineRequestError(resp, f'Could not process erroneous response: {data}') | null |
162,927 | import re
import copy
import logging
import builtins
import operator
from typing import (
Any,
Dict,
Type as TypingType,
Union,
Callable,
Optional,
cast,
)
from configparser import ConfigParser
from typing_extensions import override
from mypy.nodes import (
Var,
Node,
Context,
IntExpr,
StrExpr,
CallExpr,
DictExpr,
NameExpr,
TypeInfo,
BytesExpr,
Expression,
SymbolTable,
SymbolTableNode,
)
from mypy.types import (
Type,
Instance,
NoneType,
UnionType,
)
from mypy.plugin import Plugin, MethodContext, CheckerPluginInterface
from mypy.options import Options
from mypy.errorcodes import ErrorCode
class PrismaPlugin(Plugin):
config: PrismaPluginConfig
def __init__(self, options: Options) -> None:
self.config = PrismaPluginConfig(options)
super().__init__(options)
def get_method_hook(self, fullname: str) -> Optional[Callable[[MethodContext], Type]]:
match = CLIENT_ACTION_CHILD.match(fullname)
if not match:
return None
if match.group('name') in ACTIONS:
return self.handle_action_invocation
return None
def handle_action_invocation(self, ctx: MethodContext) -> Type:
# TODO: if an error occurs, log it so that we don't cause mypy to
# exit prematurely.
return self._handle_include(ctx)
def _handle_include(self, ctx: MethodContext) -> Type:
"""Recursively remove Optional from a relational field of a model
if it was explicitly included.
An argument could be made that this is over-engineered
and while I do agree to an extent, the benefit of this
method over just setting the default value to an empty list
is that access to a relational field without explicitly
including it will raise an error when type checking, e.g
user = await client.user.find_unique(where={'id': user_id})
print('\n'.join(p.title for p in user.posts))
"""
include_expr = self.get_arg_named('include', ctx)
if include_expr is None:
return ctx.default_return_type
if not isinstance(ctx.default_return_type, Instance):
# TODO: resolve this?
return ctx.default_return_type
is_coroutine = self.is_coroutine_type(ctx.default_return_type)
if is_coroutine:
actual_ret = ctx.default_return_type.args[2]
else:
actual_ret = ctx.default_return_type
is_optional = self.is_optional_type(actual_ret)
if is_optional:
actual_ret = cast(UnionType, actual_ret)
model_type = actual_ret.items[0]
else:
model_type = actual_ret
if not isinstance(model_type, Instance):
return ctx.default_return_type
try:
include = self.parse_expression_to_dict(include_expr)
new_model = self.modify_model_from_include(model_type, include)
except Exception as exc:
log.debug(
'Ignoring %s exception while parsing include: %s',
type(exc).__name__,
exc,
)
# TODO: test this, pytest-mypy-plugins does not bode well with multiple line output
if self.config.warn_parsing_errors:
# TODO: add more details
# e.g. "include" to "find_unique" of "UserActions"
if isinstance(exc, UnparsedExpression):
err_ctx = exc.context
else:
err_ctx = include_expr
error_unable_to_parse(
ctx.api,
err_ctx,
'the "include" argument',
)
return ctx.default_return_type
if is_optional:
actual_ret = cast(UnionType, actual_ret)
modified_ret = self.copy_modified_optional_type(actual_ret, new_model)
else:
modified_ret = new_model # type: ignore
if is_coroutine:
arg1, arg2, _ = ctx.default_return_type.args
return ctx.default_return_type.copy_modified(args=[arg1, arg2, modified_ret])
return modified_ret
def modify_model_from_include(self, model: Instance, data: Dict[Any, Any]) -> Instance:
names = model.type.names.copy()
for key, node in model.type.names.items():
names[key] = self.maybe_modify_included_field(key, node, data)
return self.copy_modified_instance(model, names)
def maybe_modify_included_field(
self,
key: Union[str, Expression, Node],
node: SymbolTableNode,
data: Dict[Any, Any],
) -> SymbolTableNode:
value = data.get(key)
if value is False or value is None:
return node
if isinstance(value, (Expression, Node)):
raise UnparsedExpression(value)
# we do not want to remove the Optional from a field that is not a list
# as the Optional indicates that the field is optional on a database level
if (
not isinstance(node.node, Var)
or node.node.type is None
or not isinstance(node.node.type, UnionType)
or not self.is_optional_union_type(node.node.type)
or not self.is_list_type(node.node.type.items[0])
):
log.debug(
'Not modifying included field: %s',
key,
)
return node
# this whole mess with copying is so that the modified field is not leaked
new = node.copy()
new.node = copy.copy(new.node)
assert isinstance(new.node, Var)
new.node.type = node.node.type.items[0]
if (
isinstance(value, dict)
and 'include' in value
and isinstance(new.node.type, Instance)
and isinstance(new.node.type.args[0], Instance)
):
model = self.modify_model_from_include(new.node.type.args[0], value['include'])
new.node.type.args = (model, *new.node.type.args)
return new
def get_arg_named(self, name: str, ctx: MethodContext) -> Optional[Expression]:
"""Return the expression for an argument."""
# keyword arguments
for i, names in enumerate(ctx.arg_names):
for j, arg_name in enumerate(names):
if arg_name == name:
return ctx.args[i][j]
# positional arguments
for i, arg_name in enumerate(ctx.callee_arg_names):
if arg_name == name and ctx.args[i]:
return ctx.args[i][0]
return None
def is_optional_type(self, typ: Type) -> bool:
return isinstance(typ, UnionType) and self.is_optional_union_type(typ)
def is_optional_union_type(self, typ: UnionType) -> bool:
return len(typ.items) == 2 and isinstance(typ.items[1], NoneType)
# TODO: why is fullname Any?
def is_coroutine_type(self, typ: Instance) -> bool:
return bool(typ.type.fullname == 'typing.Coroutine')
def is_list_type(self, typ: Type) -> bool:
return isinstance(typ, Instance) and typ.type.fullname == 'builtins.list'
def is_dict_call_type(self, expr: NameExpr) -> bool:
# statically wise, TypedDicts do not inherit from dict
# so we cannot check that, just checking if the expression
# inherits from a class that ends with dict is good enough
# for our use case
return bool(expr.fullname == 'builtins.dict') or bool(
isinstance(expr.node, TypeInfo)
and expr.node.bases
and expr.node.bases[0].type.fullname.lower().endswith('dict')
)
def copy_modified_instance(self, instance: Instance, names: SymbolTable) -> Instance:
new = copy.copy(instance)
new.type = TypeInfo(names, new.type.defn, new.type.module_name)
new.type.mro = [new.type, *instance.type.mro]
new.type.bases = instance.type.bases
new.type.metaclass_type = instance.type.metaclass_type
return new
def copy_modified_optional_type(self, original: UnionType, typ: Type) -> UnionType:
new = copy.copy(original)
new.items = new.items.copy()
new.items[0] = typ
return new
def parse_expression_to_dict(self, expression: Expression) -> Dict[Any, Any]:
if isinstance(expression, DictExpr):
return self._dictexpr_to_dict(expression)
if isinstance(expression, CallExpr):
return self._callexpr_to_dict(expression)
raise TypeError(f'Cannot parse expression of type={type(expression).__name__} to a dictionary.')
def _dictexpr_to_dict(self, expr: DictExpr) -> Dict[Any, Any]:
parsed = {}
for key_expr, value_expr in expr.items:
if key_expr is None:
# TODO: what causes this?
continue
key = self._resolve_expression(key_expr)
value = self._resolve_expression(value_expr)
parsed[key] = value
return parsed
def _callexpr_to_dict(self, expr: CallExpr, strict: bool = True) -> Dict[str, Any]:
if not isinstance(expr.callee, NameExpr):
raise TypeError(f'Expected CallExpr.callee to be a NameExpr but got {type(expr.callee)} instead.')
if strict and not self.is_dict_call_type(expr.callee):
raise TypeError(f'Expected builtins.dict to be called but got {expr.callee.fullname} instead')
parsed = {}
for arg_name, value_expr in zip(expr.arg_names, expr.args):
if arg_name is None:
continue
value = self._resolve_expression(value_expr)
parsed[arg_name] = value
return parsed
def _resolve_expression(self, expression: Expression) -> Any:
if isinstance(expression, (StrExpr, BytesExpr, IntExpr)):
return expression.value
if isinstance(expression, NameExpr):
return self._resolve_name_expression(expression)
if isinstance(expression, DictExpr):
return self._dictexpr_to_dict(expression)
if isinstance(expression, CallExpr):
return self._callexpr_to_dict(expression)
return expression
def _resolve_name_expression(self, expression: NameExpr) -> Any:
if isinstance(expression.node, Var):
return self._resolve_var_node(expression.node)
return expression
def _resolve_var_node(self, node: Var) -> Any:
if node.is_final:
return node.final_value
if node.fullname.startswith('builtins.'):
return self._resolve_builtin(node.fullname)
return node
def _resolve_builtin(self, fullname: str) -> Any:
return operator.attrgetter(*fullname.split('.')[1:])(builtins)
def plugin(version: str) -> TypingType[Plugin]: # noqa: ARG001
return PrismaPlugin | null |
162,928 | import re
import copy
import logging
import builtins
import operator
from typing import (
Any,
Dict,
Type as TypingType,
Union,
Callable,
Optional,
cast,
)
from configparser import ConfigParser
from typing_extensions import override
from mypy.nodes import (
Var,
Node,
Context,
IntExpr,
StrExpr,
CallExpr,
DictExpr,
NameExpr,
TypeInfo,
BytesExpr,
Expression,
SymbolTable,
SymbolTableNode,
)
from mypy.types import (
Type,
Instance,
NoneType,
UnionType,
)
from mypy.plugin import Plugin, MethodContext, CheckerPluginInterface
from mypy.options import Options
from mypy.errorcodes import ErrorCode
ERROR_PARSING = ErrorCode('prisma-parsing', 'Unable to parse', 'Prisma')
def error_unable_to_parse(api: CheckerPluginInterface, context: Context, detail: str) -> None:
link = 'https://github.com/RobertCraigie/prisma-client-py/issues/new/choose'
full_message = f'The prisma mypy plugin was unable to parse: {detail}\n'
full_message += f'Please consider reporting this bug at {link} so we can try to fix it!'
api.fail(full_message, context, code=ERROR_PARSING) | null |
162,929 | from __future__ import annotations
from typing import TYPE_CHECKING, Union, Callable
from .errors import ClientNotRegisteredError, ClientAlreadyRegisteredError
RegisteredClient = Union['Prisma', Callable[[], 'Prisma']]
_registered_client: RegisteredClient | None = None
class ClientAlreadyRegisteredError(PrismaError):
def __init__(self) -> None:
super().__init__('A client has already been registered.')
The provided code snippet includes necessary dependencies for implementing the `register` function. Write a Python function `def register(client: RegisteredClient) -> None` to solve the following problem:
Register a client instance to be retrieved by `get_client()` This function _must_ only be called once, preferrably as soon as possible to avoid any potentially confusing errors with threads or processes.
Here is the function:
def register(client: RegisteredClient) -> None:
"""Register a client instance to be retrieved by `get_client()`
This function _must_ only be called once, preferrably as soon as possible
to avoid any potentially confusing errors with threads or processes.
"""
from .client import Prisma # noqa: TID251
global _registered_client
if _registered_client is not None:
raise ClientAlreadyRegisteredError()
if not isinstance(client, Prisma) and not callable(client):
raise TypeError(
f'Expected either a {Prisma} instance or a function that returns a {Prisma} but got {client} instead.'
)
_registered_client = client | Register a client instance to be retrieved by `get_client()` This function _must_ only be called once, preferrably as soon as possible to avoid any potentially confusing errors with threads or processes. |
162,930 | from __future__ import annotations
from typing import TYPE_CHECKING, Union, Callable
from .errors import ClientNotRegisteredError, ClientAlreadyRegisteredError
_registered_client: RegisteredClient | None = None
class ClientNotRegisteredError(PrismaError):
def __init__(self) -> None:
super().__init__('No client instance registered; You must call prisma.register(prisma.Prisma())')
The provided code snippet includes necessary dependencies for implementing the `get_client` function. Write a Python function `def get_client() -> Prisma` to solve the following problem:
Get the registered client instance Raises errors.ClientNotRegisteredError() if no client instance has been registered.
Here is the function:
def get_client() -> Prisma:
"""Get the registered client instance
Raises errors.ClientNotRegisteredError() if no client instance has been registered.
"""
from .client import Prisma # noqa: TID251
registered = _registered_client
if registered is None:
raise ClientNotRegisteredError() from None
if isinstance(registered, Prisma):
return registered
client = registered()
if not isinstance(client, Prisma): # pyright: ignore[reportUnnecessaryIsInstance]
raise TypeError(f'Registered function returned {client} instead of a {Prisma} instance.')
return client | Get the registered client instance Raises errors.ClientNotRegisteredError() if no client instance has been registered. |
162,931 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
from functools import partial, wraps
from itertools import product
import pickle, zlib, base64
def _deserialize(data: Any, namespace: Dict[str, Any], memo: Dict) -> Any:
if isinstance(data, dict):
if '__type__' in data: ##
class_ = namespace[data['__type__']]
return class_.deserialize(data, memo)
elif '@' in data:
return memo[data['@']]
return {key:_deserialize(value, namespace, memo) for key, value in data.items()}
elif isinstance(data, list):
return [_deserialize(value, namespace, memo) for value in data]
return data | null |
162,932 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
try:
import regex
_has_regex = True
except ImportError:
_has_regex = False
categ_pattern = re.compile(r'\\p{[A-Za-z_]+}')
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
from functools import partial, wraps
from itertools import product
import pickle, zlib, base64
def get_regexp_width(expr: str) -> Union[Tuple[int, int], List[int]]:
if _has_regex:
##
##
##
regexp_final = re.sub(categ_pattern, 'A', expr)
else:
if re.search(categ_pattern, expr):
raise ImportError('`regex` module must be installed in order to use Unicode categories.', expr)
regexp_final = expr
try:
##
return [int(x) for x in sre_parse.parse(regexp_final).getwidth()] ##
except sre_constants.error:
if not _has_regex:
raise ValueError(expr)
else:
##
##
c = regex.compile(regexp_final)
if c.match('') is None:
##
return 1, int(sre_constants.MAXREPEAT)
else:
return 0, int(sre_constants.MAXREPEAT) | null |
162,933 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
class Transformer(_Decoratable, ABC, Generic[_Leaf_T, _Return_T]):
#--
__visit_tokens__ = True ##
def __init__(self, visit_tokens: bool=True) -> None:
self.__visit_tokens__ = visit_tokens
def _call_userfunc(self, tree, new_children=None):
##
children = new_children if new_children is not None else tree.children
try:
f = getattr(self, tree.data)
except AttributeError:
return self.__default__(tree.data, children, tree.meta)
else:
try:
wrapper = getattr(f, 'visit_wrapper', None)
if wrapper is not None:
return f.visit_wrapper(f, tree.data, children, tree.meta)
else:
return f(children)
except GrammarError:
raise
except Exception as e:
raise VisitError(tree.data, tree, e)
def _call_userfunc_token(self, token):
try:
f = getattr(self, token.type)
except AttributeError:
return self.__default_token__(token)
else:
try:
return f(token)
except GrammarError:
raise
except Exception as e:
raise VisitError(token.type, token, e)
def _transform_children(self, children):
for c in children:
if isinstance(c, Tree):
res = self._transform_tree(c)
elif self.__visit_tokens__ and isinstance(c, Token):
res = self._call_userfunc_token(c)
else:
res = c
if res is not Discard:
yield res
def _transform_tree(self, tree):
children = list(self._transform_children(tree.children))
return self._call_userfunc(tree, children)
def transform(self, tree: Tree[_Leaf_T]) -> _Return_T:
#--
return self._transform_tree(tree)
def __mul__(
self: 'Transformer[_Leaf_T, Tree[_Leaf_U]]',
other: 'Union[Transformer[_Leaf_U, _Return_V], TransformerChain[_Leaf_U, _Return_V,]]'
) -> 'TransformerChain[_Leaf_T, _Return_V]':
#--
return TransformerChain(self, other)
def __default__(self, data, children, meta):
#--
return Tree(data, children, meta)
def __default_token__(self, token):
#--
return token
from copy import copy
from functools import partial, wraps
from itertools import product
import pickle, zlib, base64
def merge_transformers(base_transformer=None, **transformers_to_merge):
#--
if base_transformer is None:
base_transformer = Transformer()
for prefix, transformer in transformers_to_merge.items():
for method_name in dir(transformer):
method = getattr(transformer, method_name)
if not callable(method):
continue
if method_name.startswith("_") or method_name == "transform":
continue
prefixed_method = prefix + "__" + method_name
if hasattr(base_transformer, prefixed_method):
raise AttributeError("Cannot merge: method '%s' appears more than once" % prefixed_method)
setattr(base_transformer, prefixed_method, method)
return base_transformer | null |
162,934 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
_InterMethod = Callable[[Type[Interpreter], _Return_T], _R]
from copy import copy
from functools import partial, wraps
from itertools import product
import pickle, zlib, base64
def visit_children_decor(func: _InterMethod) -> _InterMethod:
#--
@wraps(func)
def inner(cls, tree):
values = cls.visit_children(tree)
return func(cls, values)
return inner | null |
162,935 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
_DECORATED = Union[_FUNC, type]
def _apply_v_args(obj, visit_wrapper):
try:
_apply = obj._apply_v_args
except AttributeError:
return _VArgsWrapper(obj, visit_wrapper)
else:
return _apply(visit_wrapper)
def _vargs_inline(f, _data, children, _meta):
return f(*children)
def _vargs_meta_inline(f, _data, children, meta):
return f(meta, *children)
def _vargs_meta(f, _data, children, meta):
return f(meta, children)
def _vargs_tree(f, data, children, meta):
return f(Tree(data, children, meta))
from copy import copy
from functools import partial, wraps
from itertools import product
import pickle, zlib, base64
def v_args(inline: bool = False, meta: bool = False, tree: bool = False, wrapper: Optional[Callable] = None) -> Callable[[_DECORATED], _DECORATED]:
#--
if tree and (meta or inline):
raise ValueError("Visitor functions cannot combine 'tree' with 'meta' or 'inline'.")
func = None
if meta:
if inline:
func = _vargs_meta_inline
else:
func = _vargs_meta
elif inline:
func = _vargs_inline
elif tree:
func = _vargs_tree
if wrapper is not None:
if func is not None:
raise ValueError("Cannot use 'wrapper' along with 'tree', 'meta' or 'inline'.")
func = wrapper
def _visitor_args_dec(obj):
return _apply_v_args(obj, func)
return _visitor_args_dec | null |
162,936 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
def classify(seq: Iterable, key: Optional[Callable] = None, value: Optional[Callable] = None) -> Dict:
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
class PatternStr(Pattern):
def to_regexp(self) -> str:
def min_width(self) -> int:
def max_width(self) -> int:
class PatternRE(Pattern):
def to_regexp(self) -> str:
def _get_width(self):
def min_width(self) -> int:
def max_width(self) -> int:
class UnlessCallback:
def __init__(self, scanner):
def __call__(self, t):
def _get_match(re_, regexp, s, flags):
class Scanner:
def __init__(self, terminals, g_regex_flags, re_, use_bytes, match_whole=False):
def _build_mres(self, terminals, max_size):
def match(self, text, pos):
def search(self, text, pos):
from functools import partial, wraps
from itertools import product
import pickle, zlib, base64
def _create_unless(terminals, g_regex_flags, re_, use_bytes):
tokens_by_type = classify(terminals, lambda t: type(t.pattern))
assert len(tokens_by_type) <= 2, tokens_by_type.keys()
embedded_strs = set()
callback = {}
for retok in tokens_by_type.get(PatternRE, []):
unless = []
for strtok in tokens_by_type.get(PatternStr, []):
if strtok.priority != retok.priority:
continue
s = strtok.pattern.value
if s == _get_match(re_, retok.pattern.to_regexp(), s, g_regex_flags):
unless.append(strtok)
if strtok.pattern.flags <= retok.pattern.flags:
embedded_strs.add(strtok)
if unless:
callback[retok.name] = UnlessCallback(Scanner(unless, g_regex_flags, re_, match_whole=True, use_bytes=use_bytes))
new_terminals = [t for t in terminals if t not in embedded_strs]
return new_terminals, callback | null |
162,937 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
from functools import partial, wraps
from itertools import product
import pickle, zlib, base64
def _regexp_has_newline(r: str):
#--
return '\n' in r or '\\n' in r or '\\s' in r or '[^' in r or ('(?s' in r and '.' in r) | null |
162,938 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
class LexError(LarkError):
pass
import sys, re
import logging
logger: logging.Logger = logging.getLogger("lark")
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.CRITICAL)
def classify(seq: Iterable, key: Optional[Callable] = None, value: Optional[Callable] = None) -> Dict:
d: Dict[Any, Any] = {}
for item in seq:
k = key(item) if (key is not None) else item
v = value(item) if (value is not None) else item
try:
d[k].append(v)
except KeyError:
d[k] = [v]
return d
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
class TerminalDef(Serialize):
#--
__serialize_fields__ = 'name', 'pattern', 'priority'
__serialize_namespace__ = PatternStr, PatternRE
name: str
pattern: Pattern
priority: int
def __init__(self, name: str, pattern: Pattern, priority: int = TOKEN_DEFAULT_PRIORITY) -> None:
assert isinstance(pattern, Pattern), pattern
self.name = name
self.pattern = pattern
self.priority = priority
def __repr__(self):
return '%s(%r, %r)' % (type(self).__name__, self.name, self.pattern)
def user_repr(self) -> str:
if self.name.startswith('__'): ##
return self.pattern.raw or self.name
else:
return self.name
from functools import partial, wraps
from itertools import product
import pickle, zlib, base64
def _check_regex_collisions(terminal_to_regexp: Dict[TerminalDef, str], comparator, strict_mode, max_collisions_to_show=8):
if not comparator:
comparator = interegular.Comparator.from_regexes(terminal_to_regexp)
##
##
max_time = 2 if strict_mode else 0.2
##
if comparator.count_marked_pairs() >= max_collisions_to_show:
return
for group in classify(terminal_to_regexp, lambda t: t.priority).values():
for a, b in comparator.check(group, skip_marked=True):
assert a.priority == b.priority
##
comparator.mark(a, b)
##
message = f"Collision between Terminals {a.name} and {b.name}. "
try:
example = comparator.get_example_overlap(a, b, max_time).format_multiline()
except ValueError:
##
example = "No example could be found fast enough. However, the collision does still exists"
if strict_mode:
raise LexError(f"{message}\n{example}")
logger.warning("%s The lexer will choose between them arbitrarily.\n%s", message, example)
if comparator.count_marked_pairs() >= max_collisions_to_show:
logger.warning("Found 8 regex collisions, will not check for more.")
return | null |
162,939 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
class ConfigurationError(LarkError, ValueError):
pass
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
from functools import partial, wraps
from itertools import product
class PropagatePositions:
def __init__(self, node_builder, node_filter=None):
self.node_builder = node_builder
self.node_filter = node_filter
def __call__(self, children):
res = self.node_builder(children)
if isinstance(res, Tree):
##
##
##
##
res_meta = res.meta
first_meta = self._pp_get_meta(children)
if first_meta is not None:
if not hasattr(res_meta, 'line'):
##
res_meta.line = getattr(first_meta, 'container_line', first_meta.line)
res_meta.column = getattr(first_meta, 'container_column', first_meta.column)
res_meta.start_pos = getattr(first_meta, 'container_start_pos', first_meta.start_pos)
res_meta.empty = False
res_meta.container_line = getattr(first_meta, 'container_line', first_meta.line)
res_meta.container_column = getattr(first_meta, 'container_column', first_meta.column)
res_meta.container_start_pos = getattr(first_meta, 'container_start_pos', first_meta.start_pos)
last_meta = self._pp_get_meta(reversed(children))
if last_meta is not None:
if not hasattr(res_meta, 'end_line'):
res_meta.end_line = getattr(last_meta, 'container_end_line', last_meta.end_line)
res_meta.end_column = getattr(last_meta, 'container_end_column', last_meta.end_column)
res_meta.end_pos = getattr(last_meta, 'container_end_pos', last_meta.end_pos)
res_meta.empty = False
res_meta.container_end_line = getattr(last_meta, 'container_end_line', last_meta.end_line)
res_meta.container_end_column = getattr(last_meta, 'container_end_column', last_meta.end_column)
res_meta.container_end_pos = getattr(last_meta, 'container_end_pos', last_meta.end_pos)
return res
def _pp_get_meta(self, children):
for c in children:
if self.node_filter is not None and not self.node_filter(c):
continue
if isinstance(c, Tree):
if not c.meta.empty:
return c.meta
elif isinstance(c, Token):
return c
elif hasattr(c, '__lark_meta__'):
return c.__lark_meta__()
import pickle, zlib, base64
def make_propagate_positions(option):
if callable(option):
return partial(PropagatePositions, node_filter=option)
elif option is True:
return PropagatePositions
elif option is False:
return None
raise ConfigurationError('Invalid option for propagate_positions: %r' % option) | null |
162,940 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
from functools import partial, wraps
from itertools import product
class ChildFilter:
def __init__(self, to_include, append_none, node_builder):
self.node_builder = node_builder
self.to_include = to_include
self.append_none = append_none
def __call__(self, children):
filtered = []
for i, to_expand, add_none in self.to_include:
if add_none:
filtered += [None] * add_none
if to_expand:
filtered += children[i].children
else:
filtered.append(children[i])
if self.append_none:
filtered += [None] * self.append_none
return self.node_builder(filtered)
class ChildFilterLALR(ChildFilter):
#--
def __call__(self, children):
filtered = []
for i, to_expand, add_none in self.to_include:
if add_none:
filtered += [None] * add_none
if to_expand:
if filtered:
filtered += children[i].children
else: ##
filtered = children[i].children
else:
filtered.append(children[i])
if self.append_none:
filtered += [None] * self.append_none
return self.node_builder(filtered)
class ChildFilterLALR_NoPlaceholders(ChildFilter):
#--
def __init__(self, to_include, node_builder):
self.node_builder = node_builder
self.to_include = to_include
def __call__(self, children):
filtered = []
for i, to_expand in self.to_include:
if to_expand:
if filtered:
filtered += children[i].children
else: ##
filtered = children[i].children
else:
filtered.append(children[i])
return self.node_builder(filtered)
def _should_expand(sym):
return not sym.is_term and sym.name.startswith('_')
import pickle, zlib, base64
def maybe_create_child_filter(expansion, keep_all_tokens, ambiguous, _empty_indices: List[bool]):
##
if _empty_indices:
assert _empty_indices.count(False) == len(expansion)
s = ''.join(str(int(b)) for b in _empty_indices)
empty_indices = [len(ones) for ones in s.split('0')]
assert len(empty_indices) == len(expansion)+1, (empty_indices, len(expansion))
else:
empty_indices = [0] * (len(expansion)+1)
to_include = []
nones_to_add = 0
for i, sym in enumerate(expansion):
nones_to_add += empty_indices[i]
if keep_all_tokens or not (sym.is_term and sym.filter_out):
to_include.append((i, _should_expand(sym), nones_to_add))
nones_to_add = 0
nones_to_add += empty_indices[len(expansion)]
if _empty_indices or len(to_include) < len(expansion) or any(to_expand for i, to_expand,_ in to_include):
if _empty_indices or ambiguous:
return partial(ChildFilter if ambiguous else ChildFilterLALR, to_include, nones_to_add)
else:
##
return partial(ChildFilterLALR_NoPlaceholders, [(i, x) for i,x,_ in to_include]) | null |
162,941 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
from functools import partial, wraps
from itertools import product
def _should_expand(sym):
return not sym.is_term and sym.name.startswith('_')
class AmbiguousExpander:
#--
def __init__(self, to_expand, tree_class, node_builder):
self.node_builder = node_builder
self.tree_class = tree_class
self.to_expand = to_expand
def __call__(self, children):
def _is_ambig_tree(t):
return hasattr(t, 'data') and t.data == '_ambig'
##
##
##
##
ambiguous = []
for i, child in enumerate(children):
if _is_ambig_tree(child):
if i in self.to_expand:
ambiguous.append(i)
child.expand_kids_by_data('_ambig')
if not ambiguous:
return self.node_builder(children)
expand = [child.children if i in ambiguous else (child,) for i, child in enumerate(children)]
return self.tree_class('_ambig', [self.node_builder(list(f)) for f in product(*expand)])
import pickle, zlib, base64
def maybe_create_ambiguous_expander(tree_class, expansion, keep_all_tokens):
to_expand = [i for i, sym in enumerate(expansion)
if keep_all_tokens or ((not (sym.is_term and sym.filter_out)) and _should_expand(sym))]
if to_expand:
return partial(AmbiguousExpander, to_expand, tree_class) | null |
162,942 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
class Tree(Generic[_Leaf_T]):
#--
data: str
children: 'List[Branch[_Leaf_T]]'
def __init__(self, data: str, children: 'List[Branch[_Leaf_T]]', meta: Optional[Meta]=None) -> None:
self.data = data
self.children = children
self._meta = meta
def meta(self) -> Meta:
if self._meta is None:
self._meta = Meta()
return self._meta
def __repr__(self):
return 'Tree(%r, %r)' % (self.data, self.children)
def _pretty_label(self):
return self.data
def _pretty(self, level, indent_str):
yield f'{indent_str*level}{self._pretty_label()}'
if len(self.children) == 1 and not isinstance(self.children[0], Tree):
yield f'\t{self.children[0]}\n'
else:
yield '\n'
for n in self.children:
if isinstance(n, Tree):
yield from n._pretty(level+1, indent_str)
else:
yield f'{indent_str*(level+1)}{n}\n'
def pretty(self, indent_str: str=' ') -> str:
#--
return ''.join(self._pretty(0, indent_str))
def __rich__(self, parent:Optional['rich.tree.Tree']=None) -> 'rich.tree.Tree':
#--
return self._rich(parent)
def _rich(self, parent):
if parent:
tree = parent.add(f'[bold]{self.data}[/bold]')
else:
import rich.tree
tree = rich.tree.Tree(self.data)
for c in self.children:
if isinstance(c, Tree):
c._rich(tree)
else:
tree.add(f'[green]{c}[/green]')
return tree
def __eq__(self, other):
try:
return self.data == other.data and self.children == other.children
except AttributeError:
return False
def __ne__(self, other):
return not (self == other)
def __hash__(self) -> int:
return hash((self.data, tuple(self.children)))
def iter_subtrees(self) -> 'Iterator[Tree[_Leaf_T]]':
#--
queue = [self]
subtrees = OrderedDict()
for subtree in queue:
subtrees[id(subtree)] = subtree
##
queue += [c for c in reversed(subtree.children) ##
if isinstance(c, Tree) and id(c) not in subtrees]
del queue
return reversed(list(subtrees.values()))
def iter_subtrees_topdown(self):
#--
stack = [self]
stack_append = stack.append
stack_pop = stack.pop
while stack:
node = stack_pop()
if not isinstance(node, Tree):
continue
yield node
for child in reversed(node.children):
stack_append(child)
def find_pred(self, pred: 'Callable[[Tree[_Leaf_T]], bool]') -> 'Iterator[Tree[_Leaf_T]]':
#--
return filter(pred, self.iter_subtrees())
def find_data(self, data: str) -> 'Iterator[Tree[_Leaf_T]]':
#--
return self.find_pred(lambda t: t.data == data)
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
from functools import partial, wraps
from itertools import product
import pickle, zlib, base64
def inplace_transformer(func):
@wraps(func)
def f(children):
##
tree = Tree(func.__name__, children)
return func(tree)
return f | null |
162,943 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
def _vargs_meta_inline(f, _data, children, meta):
return f(meta, *children)
def _vargs_meta(f, _data, children, meta):
return f(meta, children)
from copy import copy
from functools import partial, wraps
from itertools import product
import pickle, zlib, base64
def apply_visit_wrapper(func, name, wrapper):
if wrapper is _vargs_meta or wrapper is _vargs_meta_inline:
raise NotImplementedError("Meta args not supported for internal transformer")
@wraps(func)
def f(children):
return wrapper(func, name, children, None)
return f | null |
162,944 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
class Lexer(ABC):
#--
def lex(self, lexer_state: LexerState, parser_state: Any) -> Iterator[Token]:
return NotImplemented
def make_lexer_state(self, text):
#--
return LexerState(text)
from functools import partial, wraps
from itertools import product
import pickle, zlib, base64
def _wrap_lexer(lexer_class):
future_interface = getattr(lexer_class, '__future_interface__', False)
if future_interface:
return lexer_class
else:
class CustomLexerWrapper(Lexer):
def __init__(self, lexer_conf):
self.lexer = lexer_class(lexer_conf)
def lex(self, lexer_state, parser_state):
return self.lexer.lex(lexer_state.text)
return CustomLexerWrapper | null |
162,945 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
class ParserConf(Serialize):
__serialize_fields__ = 'rules', 'start', 'parser_type'
rules: List['Rule']
callbacks: ParserCallbacks
start: List[str]
parser_type: _ParserArgType
def __init__(self, rules: List['Rule'], callbacks: ParserCallbacks, start: List[str]):
assert isinstance(start, list)
self.rules = rules
self.callbacks = callbacks
self.start = start
from functools import partial, wraps
from itertools import product
class LALR_Parser(Serialize):
def __init__(self, parser_conf: ParserConf, debug: bool=False, strict: bool=False):
analysis = LALR_Analyzer(parser_conf, debug=debug, strict=strict)
analysis.compute_lalr()
callbacks = parser_conf.callbacks
self._parse_table = analysis.parse_table
self.parser_conf = parser_conf
self.parser = _Parser(analysis.parse_table, callbacks, debug)
def deserialize(cls, data, memo, callbacks, debug=False):
inst = cls.__new__(cls)
inst._parse_table = IntParseTable.deserialize(data, memo)
inst.parser = _Parser(inst._parse_table, callbacks, debug)
return inst
def serialize(self, memo: Any = None) -> Dict[str, Any]:
return self._parse_table.serialize(memo)
def parse_interactive(self, lexer: LexerThread, start: str):
return self.parser.parse(lexer, start, start_interactive=True)
def parse(self, lexer, start, on_error=None):
try:
return self.parser.parse(lexer, start)
except UnexpectedInput as e:
if on_error is None:
raise
while True:
if isinstance(e, UnexpectedCharacters):
s = e.interactive_parser.lexer_thread.state
p = s.line_ctr.char_pos
if not on_error(e):
raise e
if isinstance(e, UnexpectedCharacters):
##
if p == s.line_ctr.char_pos:
s.line_ctr.feed(s.text[p:p+1])
try:
return e.interactive_parser.resume_parse()
except UnexpectedToken as e2:
if (isinstance(e, UnexpectedToken)
and e.token.type == e2.token.type == '$END'
and e.interactive_parser == e2.interactive_parser):
##
raise e2
e = e2
except UnexpectedCharacters as e2:
e = e2
class ParsingFrontend(Serialize):
__serialize_fields__ = 'lexer_conf', 'parser_conf', 'parser'
lexer_conf: LexerConf
parser_conf: ParserConf
options: Any
def __init__(self, lexer_conf: LexerConf, parser_conf: ParserConf, options, parser=None):
self.parser_conf = parser_conf
self.lexer_conf = lexer_conf
self.options = options
##
if parser: ##
self.parser = parser
else:
create_parser = _parser_creators.get(parser_conf.parser_type)
assert create_parser is not None, "{} is not supported in standalone mode".format(
parser_conf.parser_type
)
self.parser = create_parser(lexer_conf, parser_conf, options)
##
lexer_type = lexer_conf.lexer_type
self.skip_lexer = False
if lexer_type in ('dynamic', 'dynamic_complete'):
assert lexer_conf.postlex is None
self.skip_lexer = True
return
if isinstance(lexer_type, type):
assert issubclass(lexer_type, Lexer)
self.lexer = _wrap_lexer(lexer_type)(lexer_conf)
elif isinstance(lexer_type, str):
create_lexer = {
'basic': create_basic_lexer,
'contextual': create_contextual_lexer,
}[lexer_type]
self.lexer = create_lexer(lexer_conf, self.parser, lexer_conf.postlex, options)
else:
raise TypeError("Bad value for lexer_type: {lexer_type}")
if lexer_conf.postlex:
self.lexer = PostLexConnector(self.lexer, lexer_conf.postlex)
def _verify_start(self, start=None):
if start is None:
start_decls = self.parser_conf.start
if len(start_decls) > 1:
raise ConfigurationError("Lark initialized with more than 1 possible start rule. Must specify which start rule to parse", start_decls)
start ,= start_decls
elif start not in self.parser_conf.start:
raise ConfigurationError("Unknown start rule %s. Must be one of %r" % (start, self.parser_conf.start))
return start
def _make_lexer_thread(self, text: str) -> Union[str, LexerThread]:
cls = (self.options and self.options._plugins.get('LexerThread')) or LexerThread
return text if self.skip_lexer else cls.from_text(self.lexer, text)
def parse(self, text: str, start=None, on_error=None):
chosen_start = self._verify_start(start)
kw = {} if on_error is None else {'on_error': on_error}
stream = self._make_lexer_thread(text)
return self.parser.parse(stream, chosen_start, **kw)
def parse_interactive(self, text: Optional[str]=None, start=None):
##
##
chosen_start = self._verify_start(start)
if self.parser_conf.parser_type != 'lalr':
raise ConfigurationError("parse_interactive() currently only works with parser='lalr' ")
stream = self._make_lexer_thread(text) ##
return self.parser.parse_interactive(stream, chosen_start)
import pickle, zlib, base64
def _deserialize_parsing_frontend(data, memo, lexer_conf, callbacks, options):
parser_conf = ParserConf.deserialize(data['parser_conf'], memo)
cls = (options and options._plugins.get('LALR_Parser')) or LALR_Parser
parser = cls.deserialize(data['parser'], memo, callbacks, options.debug)
parser_conf.callbacks = callbacks
return ParsingFrontend(lexer_conf, parser_conf, options, parser=parser) | null |
162,946 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
def assert_config(value, options: Collection, msg='Got %r, expected one of %s'):
if value not in options:
raise ConfigurationError(msg % (value, options))
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
from functools import partial, wraps
from itertools import product
import pickle, zlib, base64
def _validate_frontend_args(parser, lexer) -> None:
assert_config(parser, ('lalr', 'earley', 'cyk'))
if not isinstance(lexer, type): ##
expected = {
'lalr': ('basic', 'contextual'),
'earley': ('basic', 'dynamic', 'dynamic_complete'),
'cyk': ('basic', ),
}[parser]
assert_config(lexer, expected, 'Parser %r does not support lexer %%r, expected one of %%s' % parser) | null |
162,947 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
from functools import partial, wraps
from itertools import product
import pickle, zlib, base64
def _get_lexer_callbacks(transformer, terminals):
result = {}
for terminal in terminals:
callback = getattr(transformer, terminal.name, None)
if callback is not None:
result[terminal.name] = callback
return result | null |
162,948 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
class BasicLexer(AbstractBasicLexer):
terminals: Collection[TerminalDef]
ignore_types: FrozenSet[str]
newline_types: FrozenSet[str]
user_callbacks: Dict[str, _Callback]
callback: Dict[str, _Callback]
re: ModuleType
def __init__(self, conf: 'LexerConf', comparator=None) -> None:
terminals = list(conf.terminals)
assert all(isinstance(t, TerminalDef) for t in terminals), terminals
self.re = conf.re_module
if not conf.skip_validation:
##
terminal_to_regexp = {}
for t in terminals:
regexp = t.pattern.to_regexp()
try:
self.re.compile(regexp, conf.g_regex_flags)
except self.re.error:
raise LexError("Cannot compile token %s: %s" % (t.name, t.pattern))
if t.pattern.min_width == 0:
raise LexError("Lexer does not allow zero-width terminals. (%s: %s)" % (t.name, t.pattern))
if t.pattern.type == "re":
terminal_to_regexp[t] = regexp
if not (set(conf.ignore) <= {t.name for t in terminals}):
raise LexError("Ignore terminals are not defined: %s" % (set(conf.ignore) - {t.name for t in terminals}))
if has_interegular:
_check_regex_collisions(terminal_to_regexp, comparator, conf.strict)
elif conf.strict:
raise LexError("interegular must be installed for strict mode. Use `pip install 'lark[interegular]'`.")
##
self.newline_types = frozenset(t.name for t in terminals if _regexp_has_newline(t.pattern.to_regexp()))
self.ignore_types = frozenset(conf.ignore)
terminals.sort(key=lambda x: (-x.priority, -x.pattern.max_width, -len(x.pattern.value), x.name))
self.terminals = terminals
self.user_callbacks = conf.callbacks
self.g_regex_flags = conf.g_regex_flags
self.use_bytes = conf.use_bytes
self.terminals_by_name = conf.terminals_by_name
self._scanner = None
def _build_scanner(self):
terminals, self.callback = _create_unless(self.terminals, self.g_regex_flags, self.re, self.use_bytes)
assert all(self.callback.values())
for type_, f in self.user_callbacks.items():
if type_ in self.callback:
##
self.callback[type_] = CallChain(self.callback[type_], f, lambda t: t.type == type_)
else:
self.callback[type_] = f
self._scanner = Scanner(terminals, self.g_regex_flags, self.re, self.use_bytes)
def scanner(self):
if self._scanner is None:
self._build_scanner()
return self._scanner
def match(self, text, pos):
return self.scanner.match(text, pos)
def next_token(self, lex_state: LexerState, parser_state: Any = None) -> Token:
line_ctr = lex_state.line_ctr
while line_ctr.char_pos < len(lex_state.text):
res = self.match(lex_state.text, line_ctr.char_pos)
if not res:
allowed = self.scanner.allowed_types - self.ignore_types
if not allowed:
allowed = {"<END-OF-FILE>"}
raise UnexpectedCharacters(lex_state.text, line_ctr.char_pos, line_ctr.line, line_ctr.column,
allowed=allowed, token_history=lex_state.last_token and [lex_state.last_token],
state=parser_state, terminals_by_name=self.terminals_by_name)
value, type_ = res
ignored = type_ in self.ignore_types
t = None
if not ignored or type_ in self.callback:
t = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
line_ctr.feed(value, type_ in self.newline_types)
if t is not None:
t.end_line = line_ctr.line
t.end_column = line_ctr.column
t.end_pos = line_ctr.char_pos
if t.type in self.callback:
t = self.callback[t.type](t)
if not ignored:
if not isinstance(t, Token):
raise LexError("Callbacks must return a token (returned %r)" % t)
lex_state.last_token = t
return t
##
raise EOFError(self)
from functools import partial, wraps
from itertools import product
import pickle, zlib, base64
def create_basic_lexer(lexer_conf, parser, postlex, options) -> BasicLexer:
cls = (options and options._plugins.get('BasicLexer')) or BasicLexer
return cls(lexer_conf) | null |
162,949 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
class ContextualLexer(Lexer):
def __init__(self, conf: 'LexerConf', states: Dict[int, Collection[str]], always_accept: Collection[str]=()) -> None:
def lex(self, lexer_state: LexerState, parser_state: 'ParserState') -> Iterator[Token]:
class LexerConf(Serialize):
def __init__(self, terminals: Collection[TerminalDef], re_module: ModuleType, ignore: Collection[str]=(), postlex: 'Optional[PostLex]'=None,
callbacks: Optional[Dict[str, _LexerCallback]]=None, g_regex_flags: int=0, skip_validation: bool=False, use_bytes: bool=False, strict: bool=False):
def _deserialize(self):
def __deepcopy__(self, memo=None):
from functools import partial, wraps
from itertools import product
class ParseTableBase(Generic[StateT]):
def __init__(self, states, start_states, end_states):
def serialize(self, memo):
def deserialize(cls, data, memo):
import pickle, zlib, base64
def create_contextual_lexer(lexer_conf: LexerConf, parser, postlex, options) -> ContextualLexer:
cls = (options and options._plugins.get('ContextualLexer')) or ContextualLexer
parse_table: ParseTableBase[int] = parser._parse_table
states: Dict[int, Collection[str]] = {idx:list(t.keys()) for idx, t in parse_table.states.items()}
always_accept: Collection[str] = postlex.always_accept if postlex else ()
return cls(lexer_conf, states, always_accept=always_accept) | null |
162,950 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
class LexerConf(Serialize):
__serialize_fields__ = 'terminals', 'ignore', 'g_regex_flags', 'use_bytes', 'lexer_type'
__serialize_namespace__ = TerminalDef,
terminals: Collection[TerminalDef]
re_module: ModuleType
ignore: Collection[str]
postlex: 'Optional[PostLex]'
callbacks: Dict[str, _LexerCallback]
g_regex_flags: int
skip_validation: bool
use_bytes: bool
lexer_type: Optional[_LexerArgType]
strict: bool
def __init__(self, terminals: Collection[TerminalDef], re_module: ModuleType, ignore: Collection[str]=(), postlex: 'Optional[PostLex]'=None,
callbacks: Optional[Dict[str, _LexerCallback]]=None, g_regex_flags: int=0, skip_validation: bool=False, use_bytes: bool=False, strict: bool=False):
self.terminals = terminals
self.terminals_by_name = {t.name: t for t in self.terminals}
assert len(self.terminals) == len(self.terminals_by_name)
self.ignore = ignore
self.postlex = postlex
self.callbacks = callbacks or {}
self.g_regex_flags = g_regex_flags
self.re_module = re_module
self.skip_validation = skip_validation
self.use_bytes = use_bytes
self.strict = strict
self.lexer_type = None
def _deserialize(self):
self.terminals_by_name = {t.name: t for t in self.terminals}
def __deepcopy__(self, memo=None):
return type(self)(
deepcopy(self.terminals, memo),
self.re_module,
deepcopy(self.ignore, memo),
deepcopy(self.postlex, memo),
deepcopy(self.callbacks, memo),
deepcopy(self.g_regex_flags, memo),
deepcopy(self.skip_validation, memo),
deepcopy(self.use_bytes, memo),
)
class ParserConf(Serialize):
__serialize_fields__ = 'rules', 'start', 'parser_type'
rules: List['Rule']
callbacks: ParserCallbacks
start: List[str]
parser_type: _ParserArgType
def __init__(self, rules: List['Rule'], callbacks: ParserCallbacks, start: List[str]):
assert isinstance(start, list)
self.rules = rules
self.callbacks = callbacks
self.start = start
from functools import partial, wraps
from itertools import product
class LALR_Parser(Serialize):
def __init__(self, parser_conf: ParserConf, debug: bool=False, strict: bool=False):
analysis = LALR_Analyzer(parser_conf, debug=debug, strict=strict)
analysis.compute_lalr()
callbacks = parser_conf.callbacks
self._parse_table = analysis.parse_table
self.parser_conf = parser_conf
self.parser = _Parser(analysis.parse_table, callbacks, debug)
def deserialize(cls, data, memo, callbacks, debug=False):
inst = cls.__new__(cls)
inst._parse_table = IntParseTable.deserialize(data, memo)
inst.parser = _Parser(inst._parse_table, callbacks, debug)
return inst
def serialize(self, memo: Any = None) -> Dict[str, Any]:
return self._parse_table.serialize(memo)
def parse_interactive(self, lexer: LexerThread, start: str):
return self.parser.parse(lexer, start, start_interactive=True)
def parse(self, lexer, start, on_error=None):
try:
return self.parser.parse(lexer, start)
except UnexpectedInput as e:
if on_error is None:
raise
while True:
if isinstance(e, UnexpectedCharacters):
s = e.interactive_parser.lexer_thread.state
p = s.line_ctr.char_pos
if not on_error(e):
raise e
if isinstance(e, UnexpectedCharacters):
##
if p == s.line_ctr.char_pos:
s.line_ctr.feed(s.text[p:p+1])
try:
return e.interactive_parser.resume_parse()
except UnexpectedToken as e2:
if (isinstance(e, UnexpectedToken)
and e.token.type == e2.token.type == '$END'
and e.interactive_parser == e2.interactive_parser):
##
raise e2
e = e2
except UnexpectedCharacters as e2:
e = e2
import pickle, zlib, base64
def create_lalr_parser(lexer_conf: LexerConf, parser_conf: ParserConf, options=None) -> LALR_Parser:
debug = options.debug if options else False
strict = options.strict if options else False
cls = (options and options._plugins.get('LALR_Parser')) or LALR_Parser
return cls(parser_conf, debug=debug, strict=strict) | null |
162,951 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
from functools import partial, wraps
from itertools import product
class Lark(Serialize):
#--
source_path: str
source_grammar: str
grammar: 'Grammar'
options: LarkOptions
lexer: Lexer
parser: 'ParsingFrontend'
terminals: Collection[TerminalDef]
def __init__(self, grammar: 'Union[Grammar, str, IO[str]]', **options) -> None:
self.options = LarkOptions(options)
re_module: types.ModuleType
##
use_regex = self.options.regex
if use_regex:
if _has_regex:
re_module = regex
else:
raise ImportError('`regex` module must be installed if calling `Lark(regex=True)`.')
else:
re_module = re
##
if self.options.source_path is None:
try:
self.source_path = grammar.name ##
except AttributeError:
self.source_path = '<string>'
else:
self.source_path = self.options.source_path
##
try:
read = grammar.read ##
except AttributeError:
pass
else:
grammar = read()
cache_fn = None
cache_sha256 = None
if isinstance(grammar, str):
self.source_grammar = grammar
if self.options.use_bytes:
if not isascii(grammar):
raise ConfigurationError("Grammar must be ascii only, when use_bytes=True")
if self.options.cache:
if self.options.parser != 'lalr':
raise ConfigurationError("cache only works with parser='lalr' for now")
unhashable = ('transformer', 'postlex', 'lexer_callbacks', 'edit_terminals', '_plugins')
options_str = ''.join(k+str(v) for k, v in options.items() if k not in unhashable)
from . import __version__
s = grammar + options_str + __version__ + str(sys.version_info[:2])
cache_sha256 = sha256_digest(s)
if isinstance(self.options.cache, str):
cache_fn = self.options.cache
else:
if self.options.cache is not True:
raise ConfigurationError("cache argument must be bool or str")
try:
username = getpass.getuser()
except Exception:
##
##
##
username = "unknown"
cache_fn = tempfile.gettempdir() + "/.lark_cache_%s_%s_%s_%s.tmp" % (username, cache_sha256, *sys.version_info[:2])
old_options = self.options
try:
with FS.open(cache_fn, 'rb') as f:
logger.debug('Loading grammar from cache: %s', cache_fn)
##
for name in (set(options) - _LOAD_ALLOWED_OPTIONS):
del options[name]
file_sha256 = f.readline().rstrip(b'\n')
cached_used_files = pickle.load(f)
if file_sha256 == cache_sha256.encode('utf8') and verify_used_files(cached_used_files):
cached_parser_data = pickle.load(f)
self._load(cached_parser_data, **options)
return
except FileNotFoundError:
##
pass
except Exception: ##
logger.exception("Failed to load Lark from cache: %r. We will try to carry on.", cache_fn)
##
##
self.options = old_options
##
self.grammar, used_files = load_grammar(grammar, self.source_path, self.options.import_paths, self.options.keep_all_tokens)
else:
assert isinstance(grammar, Grammar)
self.grammar = grammar
if self.options.lexer == 'auto':
if self.options.parser == 'lalr':
self.options.lexer = 'contextual'
elif self.options.parser == 'earley':
if self.options.postlex is not None:
logger.info("postlex can't be used with the dynamic lexer, so we use 'basic' instead. "
"Consider using lalr with contextual instead of earley")
self.options.lexer = 'basic'
else:
self.options.lexer = 'dynamic'
elif self.options.parser == 'cyk':
self.options.lexer = 'basic'
else:
assert False, self.options.parser
lexer = self.options.lexer
if isinstance(lexer, type):
assert issubclass(lexer, Lexer) ##
else:
assert_config(lexer, ('basic', 'contextual', 'dynamic', 'dynamic_complete'))
if self.options.postlex is not None and 'dynamic' in lexer:
raise ConfigurationError("Can't use postlex with a dynamic lexer. Use basic or contextual instead")
if self.options.ambiguity == 'auto':
if self.options.parser == 'earley':
self.options.ambiguity = 'resolve'
else:
assert_config(self.options.parser, ('earley', 'cyk'), "%r doesn't support disambiguation. Use one of these parsers instead: %s")
if self.options.priority == 'auto':
self.options.priority = 'normal'
if self.options.priority not in _VALID_PRIORITY_OPTIONS:
raise ConfigurationError("invalid priority option: %r. Must be one of %r" % (self.options.priority, _VALID_PRIORITY_OPTIONS))
if self.options.ambiguity not in _VALID_AMBIGUITY_OPTIONS:
raise ConfigurationError("invalid ambiguity option: %r. Must be one of %r" % (self.options.ambiguity, _VALID_AMBIGUITY_OPTIONS))
if self.options.parser is None:
terminals_to_keep = '*'
elif self.options.postlex is not None:
terminals_to_keep = set(self.options.postlex.always_accept)
else:
terminals_to_keep = set()
##
self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start, terminals_to_keep)
if self.options.edit_terminals:
for t in self.terminals:
self.options.edit_terminals(t)
self._terminals_dict = {t.name: t for t in self.terminals}
##
if self.options.priority == 'invert':
for rule in self.rules:
if rule.options.priority is not None:
rule.options.priority = -rule.options.priority
for term in self.terminals:
term.priority = -term.priority
##
##
##
elif self.options.priority is None:
for rule in self.rules:
if rule.options.priority is not None:
rule.options.priority = None
for term in self.terminals:
term.priority = 0
##
self.lexer_conf = LexerConf(
self.terminals, re_module, self.ignore_tokens, self.options.postlex,
self.options.lexer_callbacks, self.options.g_regex_flags, use_bytes=self.options.use_bytes, strict=self.options.strict
)
if self.options.parser:
self.parser = self._build_parser()
elif lexer:
self.lexer = self._build_lexer()
if cache_fn:
logger.debug('Saving grammar to cache: %s', cache_fn)
try:
with FS.open(cache_fn, 'wb') as f:
assert cache_sha256 is not None
f.write(cache_sha256.encode('utf8') + b'\n')
pickle.dump(used_files, f)
self.save(f, _LOAD_ALLOWED_OPTIONS)
except IOError as e:
logger.exception("Failed to save Lark to cache: %r.", cache_fn, e)
if __doc__:
__doc__ += "\n\n" + LarkOptions.OPTIONS_DOC
__serialize_fields__ = 'parser', 'rules', 'options'
def _build_lexer(self, dont_ignore: bool=False) -> BasicLexer:
lexer_conf = self.lexer_conf
if dont_ignore:
from copy import copy
lexer_conf = copy(lexer_conf)
lexer_conf.ignore = ()
return BasicLexer(lexer_conf)
def _prepare_callbacks(self) -> None:
self._callbacks = {}
##
if self.options.ambiguity != 'forest':
self._parse_tree_builder = ParseTreeBuilder(
self.rules,
self.options.tree_class or Tree,
self.options.propagate_positions,
self.options.parser != 'lalr' and self.options.ambiguity == 'explicit',
self.options.maybe_placeholders
)
self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer)
self._callbacks.update(_get_lexer_callbacks(self.options.transformer, self.terminals))
def _build_parser(self) -> "ParsingFrontend":
self._prepare_callbacks()
_validate_frontend_args(self.options.parser, self.options.lexer)
parser_conf = ParserConf(self.rules, self._callbacks, self.options.start)
return _construct_parsing_frontend(
self.options.parser,
self.options.lexer,
self.lexer_conf,
parser_conf,
options=self.options
)
def save(self, f, exclude_options: Collection[str] = ()) -> None:
#--
if self.options.parser != 'lalr':
raise NotImplementedError("Lark.save() is only implemented for the LALR(1) parser.")
data, m = self.memo_serialize([TerminalDef, Rule])
if exclude_options:
data["options"] = {n: v for n, v in data["options"].items() if n not in exclude_options}
pickle.dump({'data': data, 'memo': m}, f, protocol=pickle.HIGHEST_PROTOCOL)
def load(cls: Type[_T], f) -> _T:
#--
inst = cls.__new__(cls)
return inst._load(f)
def _deserialize_lexer_conf(self, data: Dict[str, Any], memo: Dict[int, Union[TerminalDef, Rule]], options: LarkOptions) -> LexerConf:
lexer_conf = LexerConf.deserialize(data['lexer_conf'], memo)
lexer_conf.callbacks = options.lexer_callbacks or {}
lexer_conf.re_module = regex if options.regex else re
lexer_conf.use_bytes = options.use_bytes
lexer_conf.g_regex_flags = options.g_regex_flags
lexer_conf.skip_validation = True
lexer_conf.postlex = options.postlex
return lexer_conf
def _load(self: _T, f: Any, **kwargs) -> _T:
if isinstance(f, dict):
d = f
else:
d = pickle.load(f)
memo_json = d['memo']
data = d['data']
assert memo_json
memo = SerializeMemoizer.deserialize(memo_json, {'Rule': Rule, 'TerminalDef': TerminalDef}, {})
options = dict(data['options'])
if (set(kwargs) - _LOAD_ALLOWED_OPTIONS) & set(LarkOptions._defaults):
raise ConfigurationError("Some options are not allowed when loading a Parser: {}"
.format(set(kwargs) - _LOAD_ALLOWED_OPTIONS))
options.update(kwargs)
self.options = LarkOptions.deserialize(options, memo)
self.rules = [Rule.deserialize(r, memo) for r in data['rules']]
self.source_path = '<deserialized>'
_validate_frontend_args(self.options.parser, self.options.lexer)
self.lexer_conf = self._deserialize_lexer_conf(data['parser'], memo, self.options)
self.terminals = self.lexer_conf.terminals
self._prepare_callbacks()
self._terminals_dict = {t.name: t for t in self.terminals}
self.parser = _deserialize_parsing_frontend(
data['parser'],
memo,
self.lexer_conf,
self._callbacks,
self.options, ##
)
return self
def _load_from_dict(cls, data, memo, **kwargs):
inst = cls.__new__(cls)
return inst._load({'data': data, 'memo': memo}, **kwargs)
def open(cls: Type[_T], grammar_filename: str, rel_to: Optional[str]=None, **options) -> _T:
#--
if rel_to:
basepath = os.path.dirname(rel_to)
grammar_filename = os.path.join(basepath, grammar_filename)
with open(grammar_filename, encoding='utf8') as f:
return cls(f, **options)
def open_from_package(cls: Type[_T], package: str, grammar_path: str, search_paths: 'Sequence[str]'=[""], **options) -> _T:
#--
package_loader = FromPackageLoader(package, search_paths)
full_path, text = package_loader(None, grammar_path)
options.setdefault('source_path', full_path)
options.setdefault('import_paths', [])
options['import_paths'].append(package_loader)
return cls(text, **options)
def __repr__(self):
return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source_path, self.options.parser, self.options.lexer)
def lex(self, text: str, dont_ignore: bool=False) -> Iterator[Token]:
#--
lexer: Lexer
if not hasattr(self, 'lexer') or dont_ignore:
lexer = self._build_lexer(dont_ignore)
else:
lexer = self.lexer
lexer_thread = LexerThread.from_text(lexer, text)
stream = lexer_thread.lex(None)
if self.options.postlex:
return self.options.postlex.process(stream)
return stream
def get_terminal(self, name: str) -> TerminalDef:
#--
return self._terminals_dict[name]
def parse_interactive(self, text: Optional[str]=None, start: Optional[str]=None) -> 'InteractiveParser':
#--
return self.parser.parse_interactive(text, start=start)
def parse(self, text: str, start: Optional[str]=None, on_error: 'Optional[Callable[[UnexpectedInput], bool]]'=None) -> 'ParseTree':
#--
return self.parser.parse(text, start=start, on_error=on_error)
def scan(self, text: str, start: Optional[str]=None) -> Iterator[Tuple[Tuple[int, int], 'ParseTree']]:
#--
if self.options.parser != 'lalr' or self.options.lexer != 'contextual':
raise ValueError("scan requires parser='lalr' and lexer='contextual'")
start_states = self.parser.parser._parse_table.start_states
if start is None:
if len(start_states) != 1:
raise ValueError("Need to specify start")
start, = start_states
start_state = start_states[start]
start_lex: BasicLexer = self.parser.lexer.lexers[start_state]
pos = 0
while True:
start_pos = start_lex.scanner.search(text, pos)
if start_pos is None:
break
valid_end = []
ip = self.parse_interactive(text[start_pos:], start=start)
tokens = ip.lexer_thread.lex(ip.parser_state)
while True:
try:
token = next(tokens)
ip.feed_token(token)
except (UnexpectedInput, StopIteration):
break
if '$END' in ip.choices():
valid_end.append((token, ip.copy()))
for (last, pot) in valid_end[::-1]:
try:
res = pot.feed_eof(last)
except UnexpectedInput:
continue
else:
yield ((start_pos, start_pos + last.end_pos), res)
pos = start_pos + last.end_pos
break
else:
pos = start_pos + 1
import pickle, zlib, base64
DATA = (
{'parser': {'lexer_conf': {'terminals': [{'@': 0}, {'@': 1}, {'@': 2}, {'@': 3}, {'@': 4}, {'@': 5}, {'@': 6}, {'@': 7}, {'@': 8}], 'ignore': ['WS'], 'g_regex_flags': 0, 'use_bytes': False, 'lexer_type': 'contextual', '__type__': 'LexerConf'}, 'parser_conf': {'rules': [{'@': 9}, {'@': 10}, {'@': 11}, {'@': 12}, {'@': 13}, {'@': 14}, {'@': 15}, {'@': 16}, {'@': 17}, {'@': 18}, {'@': 19}, {'@': 20}], 'start': ['start'], 'parser_type': 'lalr', '__type__': 'ParserConf'}, 'parser': {'tokens': {0: '__argument_list_star_0', 1: 'COMMA', 2: 'RPAR', 3: 'argument', 4: 'key', 5: 'CNAME', 6: 'COLON', 7: 'PYTHON', 8: 'ident', 9: 'AT', 10: 'start', 11: 'ESCAPED_STRING', 12: 'value', 13: 'LPAR', 14: '$END', 15: 'argument_list'}, 'states': {0: {0: (0, 4), 1: (0, 1), 2: (1, {'@': 14})}, 1: {3: (0, 18), 4: (0, 3), 5: (0, 13), 2: (1, {'@': 13})}, 2: {}, 3: {6: (0, 11)}, 4: {1: (0, 6), 2: (1, {'@': 12})}, 5: {2: (1, {'@': 20}), 1: (1, {'@': 20})}, 6: {4: (0, 3), 3: (0, 5), 5: (0, 13), 2: (1, {'@': 11})}, 7: {2: (0, 14)}, 8: {7: (0, 17), 8: (0, 12)}, 9: {9: (0, 8), 10: (0, 2)}, 10: {2: (1, {'@': 16}), 1: (1, {'@': 16})}, 11: {11: (0, 15), 12: (0, 10)}, 12: {13: (0, 16)}, 13: {6: (1, {'@': 17})}, 14: {14: (1, {'@': 9})}, 15: {2: (1, {'@': 18}), 1: (1, {'@': 18})}, 16: {3: (0, 0), 4: (0, 3), 5: (0, 13), 15: (0, 7), 2: (1, {'@': 15})}, 17: {13: (1, {'@': 10})}, 18: {2: (1, {'@': 19}), 1: (1, {'@': 19})}}, 'start_states': {'start': 9}, 'end_states': {'start': 2}}, '__type__': 'ParsingFrontend'}, 'rules': [{'@': 9}, {'@': 10}, {'@': 11}, {'@': 12}, {'@': 13}, {'@': 14}, {'@': 15}, {'@': 16}, {'@': 17}, {'@': 18}, {'@': 19}, {'@': 20}], 'options': {'debug': False, 'strict': False, 'keep_all_tokens': False, 'tree_class': None, 'cache': False, 'postlex': None, 'parser': 'lalr', 'lexer': 'contextual', 'transformer': None, 'start': ['start'], 'priority': 'normal', 'ambiguity': 'auto', 'regex': False, 'propagate_positions': False, 'lexer_callbacks': {}, 'maybe_placeholders': False, 'edit_terminals': None, 'g_regex_flags': 0, 'use_bytes': False, 'ordered_sets': True, 'import_paths': [], 'source_path': None, '_plugins': {}}, '__type__': 'Lark'}
)
MEMO = (
{0: {'name': 'ESCAPED_STRING', 'pattern': {'value': '(?:\'.*?(?<!\\\\)(\\\\\\\\)*?\'|".*?(?<!\\\\)(\\\\\\\\)*?")', 'flags': [], 'raw': None, '_width': [2, 4294967295], '__type__': 'PatternRE'}, 'priority': 0, '__type__': 'TerminalDef'}, 1: {'name': 'WS', 'pattern': {'value': '(?:[ \t\x0c\r\n])+', 'flags': [], 'raw': None, '_width': [1, 4294967295], '__type__': 'PatternRE'}, 'priority': 0, '__type__': 'TerminalDef'}, 2: {'name': 'CNAME', 'pattern': {'value': '[A-Za-z_][A-Za-z0-9_]*', 'flags': [], 'raw': '/[A-Za-z_][A-Za-z0-9_]*/', '_width': [1, 4294967295], '__type__': 'PatternRE'}, 'priority': 0, '__type__': 'TerminalDef'}, 3: {'name': 'AT', 'pattern': {'value': '@', 'flags': [], 'raw': '"@"', '__type__': 'PatternStr'}, 'priority': 0, '__type__': 'TerminalDef'}, 4: {'name': 'LPAR', 'pattern': {'value': '(', 'flags': [], 'raw': '"("', '__type__': 'PatternStr'}, 'priority': 0, '__type__': 'TerminalDef'}, 5: {'name': 'RPAR', 'pattern': {'value': ')', 'flags': [], 'raw': '")"', '__type__': 'PatternStr'}, 'priority': 0, '__type__': 'TerminalDef'}, 6: {'name': 'PYTHON', 'pattern': {'value': 'Python', 'flags': [], 'raw': '"Python"', '__type__': 'PatternStr'}, 'priority': 0, '__type__': 'TerminalDef'}, 7: {'name': 'COMMA', 'pattern': {'value': ',', 'flags': [], 'raw': '","', '__type__': 'PatternStr'}, 'priority': 0, '__type__': 'TerminalDef'}, 8: {'name': 'COLON', 'pattern': {'value': ':', 'flags': [], 'raw': '":"', '__type__': 'PatternStr'}, 'priority': 0, '__type__': 'TerminalDef'}, 9: {'origin': {'name': Token('RULE', 'start'), '__type__': 'NonTerminal'}, 'expansion': [{'name': 'AT', 'filter_out': True, '__type__': 'Terminal'}, {'name': 'ident', '__type__': 'NonTerminal'}, {'name': 'LPAR', 'filter_out': True, '__type__': 'Terminal'}, {'name': 'argument_list', '__type__': 'NonTerminal'}, {'name': 'RPAR', 'filter_out': True, '__type__': 'Terminal'}], 'order': 0, 'alias': None, 'options': {'keep_all_tokens': False, 'expand1': False, 'priority': None, 'template_source': None, 'empty_indices': (), '__type__': 'RuleOptions'}, '__type__': 'Rule'}, 10: {'origin': {'name': Token('RULE', 'ident'), '__type__': 'NonTerminal'}, 'expansion': [{'name': 'PYTHON', 'filter_out': True, '__type__': 'Terminal'}], 'order': 0, 'alias': None, 'options': {'keep_all_tokens': False, 'expand1': True, 'priority': None, 'template_source': None, 'empty_indices': (), '__type__': 'RuleOptions'}, '__type__': 'Rule'}, 11: {'origin': {'name': Token('RULE', 'argument_list'), '__type__': 'NonTerminal'}, 'expansion': [{'name': 'argument', '__type__': 'NonTerminal'}, {'name': '__argument_list_star_0', '__type__': 'NonTerminal'}, {'name': 'COMMA', 'filter_out': True, '__type__': 'Terminal'}], 'order': 0, 'alias': None, 'options': {'keep_all_tokens': False, 'expand1': False, 'priority': None, 'template_source': None, 'empty_indices': (), '__type__': 'RuleOptions'}, '__type__': 'Rule'}, 12: {'origin': {'name': Token('RULE', 'argument_list'), '__type__': 'NonTerminal'}, 'expansion': [{'name': 'argument', '__type__': 'NonTerminal'}, {'name': '__argument_list_star_0', '__type__': 'NonTerminal'}], 'order': 1, 'alias': None, 'options': {'keep_all_tokens': False, 'expand1': False, 'priority': None, 'template_source': None, 'empty_indices': (), '__type__': 'RuleOptions'}, '__type__': 'Rule'}, 13: {'origin': {'name': Token('RULE', 'argument_list'), '__type__': 'NonTerminal'}, 'expansion': [{'name': 'argument', '__type__': 'NonTerminal'}, {'name': 'COMMA', 'filter_out': True, '__type__': 'Terminal'}], 'order': 2, 'alias': None, 'options': {'keep_all_tokens': False, 'expand1': False, 'priority': None, 'template_source': None, 'empty_indices': (), '__type__': 'RuleOptions'}, '__type__': 'Rule'}, 14: {'origin': {'name': Token('RULE', 'argument_list'), '__type__': 'NonTerminal'}, 'expansion': [{'name': 'argument', '__type__': 'NonTerminal'}], 'order': 3, 'alias': None, 'options': {'keep_all_tokens': False, 'expand1': False, 'priority': None, 'template_source': None, 'empty_indices': (), '__type__': 'RuleOptions'}, '__type__': 'Rule'}, 15: {'origin': {'name': Token('RULE', 'argument_list'), '__type__': 'NonTerminal'}, 'expansion': [], 'order': 4, 'alias': None, 'options': {'keep_all_tokens': False, 'expand1': False, 'priority': None, 'template_source': None, 'empty_indices': (True,), '__type__': 'RuleOptions'}, '__type__': 'Rule'}, 16: {'origin': {'name': Token('RULE', 'argument'), '__type__': 'NonTerminal'}, 'expansion': [{'name': 'key', '__type__': 'NonTerminal'}, {'name': 'COLON', 'filter_out': True, '__type__': 'Terminal'}, {'name': 'value', '__type__': 'NonTerminal'}], 'order': 0, 'alias': None, 'options': {'keep_all_tokens': False, 'expand1': False, 'priority': None, 'template_source': None, 'empty_indices': (), '__type__': 'RuleOptions'}, '__type__': 'Rule'}, 17: {'origin': {'name': Token('RULE', 'key'), '__type__': 'NonTerminal'}, 'expansion': [{'name': 'CNAME', 'filter_out': False, '__type__': 'Terminal'}], 'order': 0, 'alias': None, 'options': {'keep_all_tokens': False, 'expand1': False, 'priority': None, 'template_source': None, 'empty_indices': (), '__type__': 'RuleOptions'}, '__type__': 'Rule'}, 18: {'origin': {'name': Token('RULE', 'value'), '__type__': 'NonTerminal'}, 'expansion': [{'name': 'ESCAPED_STRING', 'filter_out': False, '__type__': 'Terminal'}], 'order': 0, 'alias': None, 'options': {'keep_all_tokens': False, 'expand1': False, 'priority': None, 'template_source': None, 'empty_indices': (), '__type__': 'RuleOptions'}, '__type__': 'Rule'}, 19: {'origin': {'name': '__argument_list_star_0', '__type__': 'NonTerminal'}, 'expansion': [{'name': 'COMMA', 'filter_out': True, '__type__': 'Terminal'}, {'name': 'argument', '__type__': 'NonTerminal'}], 'order': 0, 'alias': None, 'options': {'keep_all_tokens': False, 'expand1': False, 'priority': None, 'template_source': None, 'empty_indices': (), '__type__': 'RuleOptions'}, '__type__': 'Rule'}, 20: {'origin': {'name': '__argument_list_star_0', '__type__': 'NonTerminal'}, 'expansion': [{'name': '__argument_list_star_0', '__type__': 'NonTerminal'}, {'name': 'COMMA', 'filter_out': True, '__type__': 'Terminal'}, {'name': 'argument', '__type__': 'NonTerminal'}], 'order': 1, 'alias': None, 'options': {'keep_all_tokens': False, 'expand1': False, 'priority': None, 'template_source': None, 'empty_indices': (), '__type__': 'RuleOptions'}, '__type__': 'Rule'}}
)
def Lark_StandAlone(**kwargs):
return Lark._load_from_dict(DATA, MEMO, **kwargs) | null |
162,957 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
def classify(seq: Iterable, key: Optional[Callable] = None, value: Optional[Callable] = None) -> Dict:
d: Dict[Any, Any] = {}
for item in seq:
k = key(item) if (key is not None) else item
v = value(item) if (value is not None) else item
try:
d[k].append(v)
except KeyError:
d[k] = [v]
return d
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
class PatternStr(Pattern):
__serialize_fields__ = 'value', 'flags', 'raw'
type: ClassVar[str] = "str"
def to_regexp(self) -> str:
return self._get_flags(re.escape(self.value))
def min_width(self) -> int:
return len(self.value)
def max_width(self) -> int:
return len(self.value)
class PatternRE(Pattern):
__serialize_fields__ = 'value', 'flags', 'raw', '_width'
type: ClassVar[str] = "re"
def to_regexp(self) -> str:
return self._get_flags(self.value)
_width = None
def _get_width(self):
if self._width is None:
self._width = get_regexp_width(self.to_regexp())
return self._width
def min_width(self) -> int:
return self._get_width()[0]
def max_width(self) -> int:
return self._get_width()[1]
class UnlessCallback:
def __init__(self, scanner):
self.scanner = scanner
def __call__(self, t):
res = self.scanner.match(t.value, 0)
if res:
_value, t.type = res
return t
def _get_match(re_, regexp, s, flags):
m = re_.match(regexp, s, flags)
if m:
return m.group(0)
class Scanner:
def __init__(self, terminals, g_regex_flags, re_, use_bytes, match_whole=False):
self.terminals = terminals
self.g_regex_flags = g_regex_flags
self.re_ = re_
self.use_bytes = use_bytes
self.match_whole = match_whole
self.allowed_types = {t.name for t in self.terminals}
self._mres = self._build_mres(terminals, len(terminals))
def _build_mres(self, terminals, max_size):
##
##
##
postfix = '$' if self.match_whole else ''
mres = []
while terminals:
pattern = u'|'.join(u'(?P<%s>%s)' % (t.name, t.pattern.to_regexp() + postfix) for t in terminals[:max_size])
if self.use_bytes:
pattern = pattern.encode('latin-1')
try:
mre = self.re_.compile(pattern, self.g_regex_flags)
except AssertionError: ##
return self._build_mres(terminals, max_size // 2)
mres.append(mre)
terminals = terminals[max_size:]
return mres
def match(self, text, pos):
for mre in self._mres:
m = mre.match(text, pos)
if m:
return m.group(0), m.lastgroup
def search(self, text, pos):
best = None, float("inf")
for mre in self._mres:
mre: re.Pattern
m = mre.search(text, pos)
if m:
if m.start() < best[1]:
best = (m.group(0), m.lastgroup), m.start()
if best[0] is None:
return None
else:
return best[1]
from functools import partial, wraps
from itertools import product
import pickle, zlib, base64
def _create_unless(terminals, g_regex_flags, re_, use_bytes):
tokens_by_type = classify(terminals, lambda t: type(t.pattern))
assert len(tokens_by_type) <= 2, tokens_by_type.keys()
embedded_strs = set()
callback = {}
for retok in tokens_by_type.get(PatternRE, []):
unless = []
for strtok in tokens_by_type.get(PatternStr, []):
if strtok.priority != retok.priority:
continue
s = strtok.pattern.value
if s == _get_match(re_, retok.pattern.to_regexp(), s, g_regex_flags):
unless.append(strtok)
if strtok.pattern.flags <= retok.pattern.flags:
embedded_strs.add(strtok)
if unless:
callback[retok.name] = UnlessCallback(Scanner(unless, g_regex_flags, re_, match_whole=True, use_bytes=use_bytes))
new_terminals = [t for t in terminals if t not in embedded_strs]
return new_terminals, callback | null |
162,963 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
class Tree(Generic[_Leaf_T]):
def __init__(self, data: str, children: 'List[Branch[_Leaf_T]]', meta: Optional[Meta]=None) -> None:
def meta(self) -> Meta:
def __repr__(self):
def _pretty_label(self):
def _pretty(self, level, indent_str):
def pretty(self, indent_str: str=' ') -> str:
def __rich__(self, parent:Optional['rich.tree.Tree']=None) -> 'rich.tree.Tree':
def _rich(self, parent):
def __eq__(self, other):
def __ne__(self, other):
def __hash__(self) -> int:
def iter_subtrees(self) -> 'Iterator[Tree[_Leaf_T]]':
def iter_subtrees_topdown(self):
def find_pred(self, pred: 'Callable[[Tree[_Leaf_T]], bool]') -> 'Iterator[Tree[_Leaf_T]]':
def find_data(self, data: str) -> 'Iterator[Tree[_Leaf_T]]':
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
from functools import partial, wraps
from itertools import product
import pickle, zlib, base64
def inplace_transformer(func):
@wraps(func)
def f(children):
##
tree = Tree(func.__name__, children)
return func(tree)
return f | null |
162,966 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
class ParserConf(Serialize):
def __init__(self, rules: List['Rule'], callbacks: ParserCallbacks, start: List[str]):
from functools import partial, wraps
from itertools import product
class LALR_Parser(Serialize):
def __init__(self, parser_conf: ParserConf, debug: bool=False, strict: bool=False):
def deserialize(cls, data, memo, callbacks, debug=False):
def serialize(self, memo: Any = None) -> Dict[str, Any]:
def parse_interactive(self, lexer: LexerThread, start: str):
def parse(self, lexer, start, on_error=None):
class ParsingFrontend(Serialize):
def __init__(self, lexer_conf: LexerConf, parser_conf: ParserConf, options, parser=None):
def _verify_start(self, start=None):
def _make_lexer_thread(self, text: str) -> Union[str, LexerThread]:
def parse(self, text: str, start=None, on_error=None):
def parse_interactive(self, text: Optional[str]=None, start=None):
import pickle, zlib, base64
def _deserialize_parsing_frontend(data, memo, lexer_conf, callbacks, options):
parser_conf = ParserConf.deserialize(data['parser_conf'], memo)
cls = (options and options._plugins.get('LALR_Parser')) or LALR_Parser
parser = cls.deserialize(data['parser'], memo, callbacks, options.debug)
parser_conf.callbacks = callbacks
return ParsingFrontend(lexer_conf, parser_conf, options, parser=parser) | null |
162,970 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
class ContextualLexer(Lexer):
lexers: Dict[int, AbstractBasicLexer]
root_lexer: AbstractBasicLexer
BasicLexer: Type[AbstractBasicLexer] = BasicLexer
def __init__(self, conf: 'LexerConf', states: Dict[int, Collection[str]], always_accept: Collection[str]=()) -> None:
terminals = list(conf.terminals)
terminals_by_name = conf.terminals_by_name
trad_conf = copy(conf)
trad_conf.terminals = terminals
if has_interegular and not conf.skip_validation:
comparator = interegular.Comparator.from_regexes({t: t.pattern.to_regexp() for t in terminals})
else:
comparator = None
lexer_by_tokens: Dict[FrozenSet[str], AbstractBasicLexer] = {}
self.lexers = {}
for state, accepts in states.items():
key = frozenset(accepts)
try:
lexer = lexer_by_tokens[key]
except KeyError:
accepts = set(accepts) | set(conf.ignore) | set(always_accept)
lexer_conf = copy(trad_conf)
lexer_conf.terminals = [terminals_by_name[n] for n in accepts if n in terminals_by_name]
lexer = self.BasicLexer(lexer_conf, comparator)
lexer_by_tokens[key] = lexer
self.lexers[state] = lexer
assert trad_conf.terminals is terminals
trad_conf.skip_validation = True ##
self.root_lexer = self.BasicLexer(trad_conf, comparator)
def lex(self, lexer_state: LexerState, parser_state: 'ParserState') -> Iterator[Token]:
try:
while True:
lexer = self.lexers[parser_state.position]
yield lexer.next_token(lexer_state, parser_state)
except EOFError:
pass
except UnexpectedCharacters as e:
##
##
try:
last_token = lexer_state.last_token ##
token = self.root_lexer.next_token(lexer_state, parser_state)
raise UnexpectedToken(token, e.allowed, state=parser_state, token_history=[last_token], terminals_by_name=self.root_lexer.terminals_by_name)
except UnexpectedCharacters:
raise e ##
class LexerConf(Serialize):
__serialize_fields__ = 'terminals', 'ignore', 'g_regex_flags', 'use_bytes', 'lexer_type'
__serialize_namespace__ = TerminalDef,
terminals: Collection[TerminalDef]
re_module: ModuleType
ignore: Collection[str]
postlex: 'Optional[PostLex]'
callbacks: Dict[str, _LexerCallback]
g_regex_flags: int
skip_validation: bool
use_bytes: bool
lexer_type: Optional[_LexerArgType]
strict: bool
def __init__(self, terminals: Collection[TerminalDef], re_module: ModuleType, ignore: Collection[str]=(), postlex: 'Optional[PostLex]'=None,
callbacks: Optional[Dict[str, _LexerCallback]]=None, g_regex_flags: int=0, skip_validation: bool=False, use_bytes: bool=False, strict: bool=False):
self.terminals = terminals
self.terminals_by_name = {t.name: t for t in self.terminals}
assert len(self.terminals) == len(self.terminals_by_name)
self.ignore = ignore
self.postlex = postlex
self.callbacks = callbacks or {}
self.g_regex_flags = g_regex_flags
self.re_module = re_module
self.skip_validation = skip_validation
self.use_bytes = use_bytes
self.strict = strict
self.lexer_type = None
def _deserialize(self):
self.terminals_by_name = {t.name: t for t in self.terminals}
def __deepcopy__(self, memo=None):
return type(self)(
deepcopy(self.terminals, memo),
self.re_module,
deepcopy(self.ignore, memo),
deepcopy(self.postlex, memo),
deepcopy(self.callbacks, memo),
deepcopy(self.g_regex_flags, memo),
deepcopy(self.skip_validation, memo),
deepcopy(self.use_bytes, memo),
)
from functools import partial, wraps
from itertools import product
class ParseTableBase(Generic[StateT]):
states: Dict[StateT, Dict[str, Tuple]]
start_states: Dict[str, StateT]
end_states: Dict[str, StateT]
def __init__(self, states, start_states, end_states):
self.states = states
self.start_states = start_states
self.end_states = end_states
def serialize(self, memo):
tokens = Enumerator()
states = {
state: {tokens.get(token): ((1, arg.serialize(memo)) if action is Reduce else (0, arg))
for token, (action, arg) in actions.items()}
for state, actions in self.states.items()
}
return {
'tokens': tokens.reversed(),
'states': states,
'start_states': self.start_states,
'end_states': self.end_states,
}
def deserialize(cls, data, memo):
tokens = data['tokens']
states = {
state: {tokens[token]: ((Reduce, Rule.deserialize(arg, memo)) if action==1 else (Shift, arg))
for token, (action, arg) in actions.items()}
for state, actions in data['states'].items()
}
return cls(states, data['start_states'], data['end_states'])
import pickle, zlib, base64
def create_contextual_lexer(lexer_conf: LexerConf, parser, postlex, options) -> ContextualLexer:
cls = (options and options._plugins.get('ContextualLexer')) or ContextualLexer
parse_table: ParseTableBase[int] = parser._parse_table
states: Dict[int, Collection[str]] = {idx:list(t.keys()) for idx, t in parse_table.states.items()}
always_accept: Collection[str] = postlex.always_accept if postlex else ()
return cls(lexer_conf, states, always_accept=always_accept) | null |
162,972 | from copy import deepcopy
from abc import ABC, abstractmethod
from types import ModuleType
from typing import (
TypeVar, Generic, Type, Tuple, List, Dict, Iterator, Collection, Callable, Optional, FrozenSet, Any,
Union, Iterable, IO, TYPE_CHECKING, overload, Sequence,
Pattern as REPattern, ClassVar, Set, Mapping
)
import sys, re
import logging
from collections import OrderedDict
from functools import wraps, update_wrapper
from inspect import getmembers, getmro
from copy import copy
from functools import partial, wraps
from itertools import product
class Lark(Serialize):
#--
source_path: str
source_grammar: str
grammar: 'Grammar'
options: LarkOptions
lexer: Lexer
parser: 'ParsingFrontend'
terminals: Collection[TerminalDef]
def __init__(self, grammar: 'Union[Grammar, str, IO[str]]', **options) -> None:
self.options = LarkOptions(options)
re_module: types.ModuleType
##
use_regex = self.options.regex
if use_regex:
if _has_regex:
re_module = regex
else:
raise ImportError('`regex` module must be installed if calling `Lark(regex=True)`.')
else:
re_module = re
##
if self.options.source_path is None:
try:
self.source_path = grammar.name ##
except AttributeError:
self.source_path = '<string>'
else:
self.source_path = self.options.source_path
##
try:
read = grammar.read ##
except AttributeError:
pass
else:
grammar = read()
cache_fn = None
cache_sha256 = None
if isinstance(grammar, str):
self.source_grammar = grammar
if self.options.use_bytes:
if not isascii(grammar):
raise ConfigurationError("Grammar must be ascii only, when use_bytes=True")
if self.options.cache:
if self.options.parser != 'lalr':
raise ConfigurationError("cache only works with parser='lalr' for now")
unhashable = ('transformer', 'postlex', 'lexer_callbacks', 'edit_terminals', '_plugins')
options_str = ''.join(k+str(v) for k, v in options.items() if k not in unhashable)
from . import __version__
s = grammar + options_str + __version__ + str(sys.version_info[:2])
cache_sha256 = sha256_digest(s)
if isinstance(self.options.cache, str):
cache_fn = self.options.cache
else:
if self.options.cache is not True:
raise ConfigurationError("cache argument must be bool or str")
try:
username = getpass.getuser()
except Exception:
##
##
##
username = "unknown"
cache_fn = tempfile.gettempdir() + "/.lark_cache_%s_%s_%s_%s.tmp" % (username, cache_sha256, *sys.version_info[:2])
old_options = self.options
try:
with FS.open(cache_fn, 'rb') as f:
logger.debug('Loading grammar from cache: %s', cache_fn)
##
for name in (set(options) - _LOAD_ALLOWED_OPTIONS):
del options[name]
file_sha256 = f.readline().rstrip(b'\n')
cached_used_files = pickle.load(f)
if file_sha256 == cache_sha256.encode('utf8') and verify_used_files(cached_used_files):
cached_parser_data = pickle.load(f)
self._load(cached_parser_data, **options)
return
except FileNotFoundError:
##
pass
except Exception: ##
logger.exception("Failed to load Lark from cache: %r. We will try to carry on.", cache_fn)
##
##
self.options = old_options
##
self.grammar, used_files = load_grammar(grammar, self.source_path, self.options.import_paths, self.options.keep_all_tokens)
else:
assert isinstance(grammar, Grammar)
self.grammar = grammar
if self.options.lexer == 'auto':
if self.options.parser == 'lalr':
self.options.lexer = 'contextual'
elif self.options.parser == 'earley':
if self.options.postlex is not None:
logger.info("postlex can't be used with the dynamic lexer, so we use 'basic' instead. "
"Consider using lalr with contextual instead of earley")
self.options.lexer = 'basic'
else:
self.options.lexer = 'dynamic'
elif self.options.parser == 'cyk':
self.options.lexer = 'basic'
else:
assert False, self.options.parser
lexer = self.options.lexer
if isinstance(lexer, type):
assert issubclass(lexer, Lexer) ##
else:
assert_config(lexer, ('basic', 'contextual', 'dynamic', 'dynamic_complete'))
if self.options.postlex is not None and 'dynamic' in lexer:
raise ConfigurationError("Can't use postlex with a dynamic lexer. Use basic or contextual instead")
if self.options.ambiguity == 'auto':
if self.options.parser == 'earley':
self.options.ambiguity = 'resolve'
else:
assert_config(self.options.parser, ('earley', 'cyk'), "%r doesn't support disambiguation. Use one of these parsers instead: %s")
if self.options.priority == 'auto':
self.options.priority = 'normal'
if self.options.priority not in _VALID_PRIORITY_OPTIONS:
raise ConfigurationError("invalid priority option: %r. Must be one of %r" % (self.options.priority, _VALID_PRIORITY_OPTIONS))
if self.options.ambiguity not in _VALID_AMBIGUITY_OPTIONS:
raise ConfigurationError("invalid ambiguity option: %r. Must be one of %r" % (self.options.ambiguity, _VALID_AMBIGUITY_OPTIONS))
if self.options.parser is None:
terminals_to_keep = '*'
elif self.options.postlex is not None:
terminals_to_keep = set(self.options.postlex.always_accept)
else:
terminals_to_keep = set()
##
self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start, terminals_to_keep)
if self.options.edit_terminals:
for t in self.terminals:
self.options.edit_terminals(t)
self._terminals_dict = {t.name: t for t in self.terminals}
##
if self.options.priority == 'invert':
for rule in self.rules:
if rule.options.priority is not None:
rule.options.priority = -rule.options.priority
for term in self.terminals:
term.priority = -term.priority
##
##
##
elif self.options.priority is None:
for rule in self.rules:
if rule.options.priority is not None:
rule.options.priority = None
for term in self.terminals:
term.priority = 0
##
self.lexer_conf = LexerConf(
self.terminals, re_module, self.ignore_tokens, self.options.postlex,
self.options.lexer_callbacks, self.options.g_regex_flags, use_bytes=self.options.use_bytes, strict=self.options.strict
)
if self.options.parser:
self.parser = self._build_parser()
elif lexer:
self.lexer = self._build_lexer()
if cache_fn:
logger.debug('Saving grammar to cache: %s', cache_fn)
try:
with FS.open(cache_fn, 'wb') as f:
assert cache_sha256 is not None
f.write(cache_sha256.encode('utf8') + b'\n')
pickle.dump(used_files, f)
self.save(f, _LOAD_ALLOWED_OPTIONS)
except IOError as e:
logger.exception("Failed to save Lark to cache: %r.", cache_fn, e)
if __doc__:
__doc__ += "\n\n" + LarkOptions.OPTIONS_DOC
__serialize_fields__ = 'parser', 'rules', 'options'
def _build_lexer(self, dont_ignore: bool=False) -> BasicLexer:
lexer_conf = self.lexer_conf
if dont_ignore:
from copy import copy
lexer_conf = copy(lexer_conf)
lexer_conf.ignore = ()
return BasicLexer(lexer_conf)
def _prepare_callbacks(self) -> None:
self._callbacks = {}
##
if self.options.ambiguity != 'forest':
self._parse_tree_builder = ParseTreeBuilder(
self.rules,
self.options.tree_class or Tree,
self.options.propagate_positions,
self.options.parser != 'lalr' and self.options.ambiguity == 'explicit',
self.options.maybe_placeholders
)
self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer)
self._callbacks.update(_get_lexer_callbacks(self.options.transformer, self.terminals))
def _build_parser(self) -> "ParsingFrontend":
self._prepare_callbacks()
_validate_frontend_args(self.options.parser, self.options.lexer)
parser_conf = ParserConf(self.rules, self._callbacks, self.options.start)
return _construct_parsing_frontend(
self.options.parser,
self.options.lexer,
self.lexer_conf,
parser_conf,
options=self.options
)
def save(self, f, exclude_options: Collection[str] = ()) -> None:
#--
if self.options.parser != 'lalr':
raise NotImplementedError("Lark.save() is only implemented for the LALR(1) parser.")
data, m = self.memo_serialize([TerminalDef, Rule])
if exclude_options:
data["options"] = {n: v for n, v in data["options"].items() if n not in exclude_options}
pickle.dump({'data': data, 'memo': m}, f, protocol=pickle.HIGHEST_PROTOCOL)
def load(cls: Type[_T], f) -> _T:
#--
inst = cls.__new__(cls)
return inst._load(f)
def _deserialize_lexer_conf(self, data: Dict[str, Any], memo: Dict[int, Union[TerminalDef, Rule]], options: LarkOptions) -> LexerConf:
lexer_conf = LexerConf.deserialize(data['lexer_conf'], memo)
lexer_conf.callbacks = options.lexer_callbacks or {}
lexer_conf.re_module = regex if options.regex else re
lexer_conf.use_bytes = options.use_bytes
lexer_conf.g_regex_flags = options.g_regex_flags
lexer_conf.skip_validation = True
lexer_conf.postlex = options.postlex
return lexer_conf
def _load(self: _T, f: Any, **kwargs) -> _T:
if isinstance(f, dict):
d = f
else:
d = pickle.load(f)
memo_json = d['memo']
data = d['data']
assert memo_json
memo = SerializeMemoizer.deserialize(memo_json, {'Rule': Rule, 'TerminalDef': TerminalDef}, {})
options = dict(data['options'])
if (set(kwargs) - _LOAD_ALLOWED_OPTIONS) & set(LarkOptions._defaults):
raise ConfigurationError("Some options are not allowed when loading a Parser: {}"
.format(set(kwargs) - _LOAD_ALLOWED_OPTIONS))
options.update(kwargs)
self.options = LarkOptions.deserialize(options, memo)
self.rules = [Rule.deserialize(r, memo) for r in data['rules']]
self.source_path = '<deserialized>'
_validate_frontend_args(self.options.parser, self.options.lexer)
self.lexer_conf = self._deserialize_lexer_conf(data['parser'], memo, self.options)
self.terminals = self.lexer_conf.terminals
self._prepare_callbacks()
self._terminals_dict = {t.name: t for t in self.terminals}
self.parser = _deserialize_parsing_frontend(
data['parser'],
memo,
self.lexer_conf,
self._callbacks,
self.options, ##
)
return self
def _load_from_dict(cls, data, memo, **kwargs):
inst = cls.__new__(cls)
return inst._load({'data': data, 'memo': memo}, **kwargs)
def open(cls: Type[_T], grammar_filename: str, rel_to: Optional[str]=None, **options) -> _T:
#--
if rel_to:
basepath = os.path.dirname(rel_to)
grammar_filename = os.path.join(basepath, grammar_filename)
with open(grammar_filename, encoding='utf8') as f:
return cls(f, **options)
def open_from_package(cls: Type[_T], package: str, grammar_path: str, search_paths: 'Sequence[str]'=[""], **options) -> _T:
#--
package_loader = FromPackageLoader(package, search_paths)
full_path, text = package_loader(None, grammar_path)
options.setdefault('source_path', full_path)
options.setdefault('import_paths', [])
options['import_paths'].append(package_loader)
return cls(text, **options)
def __repr__(self):
return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source_path, self.options.parser, self.options.lexer)
def lex(self, text: str, dont_ignore: bool=False) -> Iterator[Token]:
#--
lexer: Lexer
if not hasattr(self, 'lexer') or dont_ignore:
lexer = self._build_lexer(dont_ignore)
else:
lexer = self.lexer
lexer_thread = LexerThread.from_text(lexer, text)
stream = lexer_thread.lex(None)
if self.options.postlex:
return self.options.postlex.process(stream)
return stream
def get_terminal(self, name: str) -> TerminalDef:
#--
return self._terminals_dict[name]
def parse_interactive(self, text: Optional[str]=None, start: Optional[str]=None) -> 'InteractiveParser':
#--
return self.parser.parse_interactive(text, start=start)
def parse(self, text: str, start: Optional[str]=None, on_error: 'Optional[Callable[[UnexpectedInput], bool]]'=None) -> 'ParseTree':
#--
return self.parser.parse(text, start=start, on_error=on_error)
def scan(self, text: str, start: Optional[str]=None) -> Iterator[Tuple[Tuple[int, int], 'ParseTree']]:
#--
if self.options.parser != 'lalr' or self.options.lexer != 'contextual':
raise ValueError("scan requires parser='lalr' and lexer='contextual'")
start_states = self.parser.parser._parse_table.start_states
if start is None:
if len(start_states) != 1:
raise ValueError("Need to specify start")
start, = start_states
start_state = start_states[start]
start_lex: BasicLexer = self.parser.lexer.lexers[start_state]
pos = 0
while True:
start_pos = start_lex.scanner.search(text, pos)
if start_pos is None:
break
valid_end = []
ip = self.parse_interactive(text[start_pos:], start=start)
tokens = ip.lexer_thread.lex(ip.parser_state)
while True:
try:
token = next(tokens)
ip.feed_token(token)
except (UnexpectedInput, StopIteration):
break
if '$END' in ip.choices():
valid_end.append((token, ip.copy()))
for (last, pot) in valid_end[::-1]:
try:
res = pot.feed_eof(last)
except UnexpectedInput:
continue
else:
yield ((start_pos, start_pos + last.end_pos), res)
pos = start_pos + last.end_pos
break
else:
pos = start_pos + 1
import pickle, zlib, base64
DATA = (
{'parser': {'lexer_conf': {'terminals': [{'@': 0}, {'@': 1}, {'@': 2}], 'ignore': [], 'g_regex_flags': 0, 'use_bytes': False, 'lexer_type': 'contextual', '__type__': 'LexerConf'}, 'parser_conf': {'rules': [{'@': 3}], 'start': ['start'], 'parser_type': 'lalr', '__type__': 'ParserConf'}, 'parser': {'tokens': {0: 'start', 1: '__ANON_0', 2: '$END', 3: 'RPAR', 4: 'ANYTHING_EXCEPT_PAREN'}, 'states': {0: {0: (0, 3), 1: (0, 4)}, 1: {2: (1, {'@': 3})}, 2: {3: (0, 1)}, 3: {}, 4: {4: (0, 2)}}, 'start_states': {'start': 0}, 'end_states': {'start': 3}}, '__type__': 'ParsingFrontend'}, 'rules': [{'@': 3}], 'options': {'debug': False, 'strict': False, 'keep_all_tokens': False, 'tree_class': None, 'cache': False, 'postlex': None, 'parser': 'lalr', 'lexer': 'contextual', 'transformer': None, 'start': ['start'], 'priority': 'normal', 'ambiguity': 'auto', 'regex': False, 'propagate_positions': False, 'lexer_callbacks': {}, 'maybe_placeholders': False, 'edit_terminals': None, 'g_regex_flags': 0, 'use_bytes': False, 'ordered_sets': True, 'import_paths': [], 'source_path': None, '_plugins': {}}, '__type__': 'Lark'}
)
MEMO = (
{0: {'name': 'ANYTHING_EXCEPT_PAREN', 'pattern': {'value': '[^)]+', 'flags': [], 'raw': '/[^)]+/', '_width': [1, 4294967295], '__type__': 'PatternRE'}, 'priority': 0, '__type__': 'TerminalDef'}, 1: {'name': '__ANON_0', 'pattern': {'value': '@Python(', 'flags': [], 'raw': '"@Python("', '__type__': 'PatternStr'}, 'priority': 0, '__type__': 'TerminalDef'}, 2: {'name': 'RPAR', 'pattern': {'value': ')', 'flags': [], 'raw': '")"', '__type__': 'PatternStr'}, 'priority': 0, '__type__': 'TerminalDef'}, 3: {'origin': {'name': Token('RULE', 'start'), '__type__': 'NonTerminal'}, 'expansion': [{'name': '__ANON_0', 'filter_out': True, '__type__': 'Terminal'}, {'name': 'ANYTHING_EXCEPT_PAREN', 'filter_out': False, '__type__': 'Terminal'}, {'name': 'RPAR', 'filter_out': True, '__type__': 'Terminal'}], 'order': 0, 'alias': None, 'options': {'keep_all_tokens': False, 'expand1': False, 'priority': None, 'template_source': None, 'empty_indices': (), '__type__': 'RuleOptions'}, '__type__': 'Rule'}}
)
def Lark_StandAlone(**kwargs):
return Lark._load_from_dict(DATA, MEMO, **kwargs) | null |
162,973 | from __future__ import annotations
import json
import decimal
import inspect
import logging
import datetime
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Union, Mapping, Iterable, ForwardRef, cast
from datetime import timezone
from textwrap import indent
from functools import singledispatch
from typing_extensions import Literal, TypeGuard, override
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from . import fields
from ._types import PrismaMethod
from .errors import InvalidModelError, UnknownModelError, UnknownRelationalFieldError
from ._compat import get_args, is_union, get_origin, model_fields, model_field_type
from ._typing import is_list_type
from ._constants import QUERY_BUILDER_ALIASES
def _prisma_model_for_field(
field: FieldInfo,
*,
name: str,
parent: type[BaseModel],
) -> type[PrismaModel] | None:
cls_name = parent.__name__
type_ = model_field_type(field)
if type_ is None:
raise RuntimeError(f'Unexpected field type is None for {cls_name}.{name}')
types: Iterable[type]
if is_union(get_origin(type_)):
types = get_args(type_)
else:
types = [type_]
for type_ in types:
if isinstance(type_, ForwardRef):
raise RuntimeError(
f'Encountered forward reference for {cls_name}.{name}; Forward references must be evaluated using {cls_name}.update_forward_refs()'
)
if is_list_type(type_) and type_ is not None:
type_ = get_args(type_)[0]
if hasattr(type_, '__prisma_model__'):
return type_
return None
The provided code snippet includes necessary dependencies for implementing the `_field_is_prisma_model` function. Write a Python function `def _field_is_prisma_model(field: FieldInfo, *, name: str, parent: type[BaseModel]) -> bool` to solve the following problem:
Whether or not the given field info represents a model at the database level. This will return `True` for cases where the field represents a list of models or a single model.
Here is the function:
def _field_is_prisma_model(field: FieldInfo, *, name: str, parent: type[BaseModel]) -> bool:
"""Whether or not the given field info represents a model at the database level.
This will return `True` for cases where the field represents a list of models or a single model.
"""
return _prisma_model_for_field(field, name=name, parent=parent) is not None | Whether or not the given field info represents a model at the database level. This will return `True` for cases where the field represents a list of models or a single model. |
162,974 | from __future__ import annotations
import json
import decimal
import inspect
import logging
import datetime
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Union, Mapping, Iterable, ForwardRef, cast
from datetime import timezone
from textwrap import indent
from functools import singledispatch
from typing_extensions import Literal, TypeGuard, override
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from . import fields
from ._types import PrismaMethod
from .errors import InvalidModelError, UnknownModelError, UnknownRelationalFieldError
from ._compat import get_args, is_union, get_origin, model_fields, model_field_type
from ._typing import is_list_type
from ._constants import QUERY_BUILDER_ALIASES
def _is_prisma_model_type(type_: type[BaseModel]) -> TypeGuard[type[PrismaModel]]:
from .bases import _PrismaModel # noqa: TID251
return issubclass(type_, _PrismaModel) | null |
162,975 | from __future__ import annotations
import json
import decimal
import inspect
import logging
import datetime
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Union, Mapping, Iterable, ForwardRef, cast
from datetime import timezone
from textwrap import indent
from functools import singledispatch
from typing_extensions import Literal, TypeGuard, override
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from . import fields
from ._types import PrismaMethod
from .errors import InvalidModelError, UnknownModelError, UnknownRelationalFieldError
from ._compat import get_args, is_union, get_origin, model_fields, model_field_type
from ._typing import is_list_type
from ._constants import QUERY_BUILDER_ALIASES
The provided code snippet includes necessary dependencies for implementing the `serialize_datetime` function. Write a Python function `def serialize_datetime(dt: datetime.datetime) -> str` to solve the following problem:
Format a datetime object to an ISO8601 string with a timezone. This assumes naive datetime objects are in UTC.
Here is the function:
def serialize_datetime(dt: datetime.datetime) -> str:
"""Format a datetime object to an ISO8601 string with a timezone.
This assumes naive datetime objects are in UTC.
"""
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
elif dt.tzinfo != timezone.utc:
dt = dt.astimezone(timezone.utc)
# truncate microseconds to 3 decimal places
# https://github.com/RobertCraigie/prisma-client-py/issues/129
dt = dt.replace(microsecond=int(dt.microsecond / 1000) * 1000)
return dt.isoformat() | Format a datetime object to an ISO8601 string with a timezone. This assumes naive datetime objects are in UTC. |
162,976 | from __future__ import annotations
import json
import decimal
import inspect
import logging
import datetime
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Union, Mapping, Iterable, ForwardRef, cast
from datetime import timezone
from textwrap import indent
from functools import singledispatch
from typing_extensions import Literal, TypeGuard, override
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from . import fields
from ._types import PrismaMethod
from .errors import InvalidModelError, UnknownModelError, UnknownRelationalFieldError
from ._compat import get_args, is_union, get_origin, model_fields, model_field_type
from ._typing import is_list_type
from ._constants import QUERY_BUILDER_ALIASES
def dumps(obj: Any, **kwargs: Any) -> str:
kwargs.setdefault('default', serializer)
kwargs.setdefault('ensure_ascii', False)
return json.dumps(obj, **kwargs)
The provided code snippet includes necessary dependencies for implementing the `serialize_json` function. Write a Python function `def serialize_json(obj: fields.Json) -> str` to solve the following problem:
Serialize a Json wrapper to a json string. This is used as a hook to override our default behaviour when building queries which would treat data like {'hello': 'world'} as a Data node when we instead want it to be rendered as a raw json string. This should only be used for fields that are of the `Json` type.
Here is the function:
def serialize_json(obj: fields.Json) -> str:
"""Serialize a Json wrapper to a json string.
This is used as a hook to override our default behaviour when building
queries which would treat data like {'hello': 'world'} as a Data node
when we instead want it to be rendered as a raw json string.
This should only be used for fields that are of the `Json` type.
"""
return dumps(obj.data) | Serialize a Json wrapper to a json string. This is used as a hook to override our default behaviour when building queries which would treat data like {'hello': 'world'} as a Data node when we instead want it to be rendered as a raw json string. This should only be used for fields that are of the `Json` type. |
162,977 | from __future__ import annotations
import json
import decimal
import inspect
import logging
import datetime
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Union, Mapping, Iterable, ForwardRef, cast
from datetime import timezone
from textwrap import indent
from functools import singledispatch
from typing_extensions import Literal, TypeGuard, override
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from . import fields
from ._types import PrismaMethod
from .errors import InvalidModelError, UnknownModelError, UnknownRelationalFieldError
from ._compat import get_args, is_union, get_origin, model_fields, model_field_type
from ._typing import is_list_type
from ._constants import QUERY_BUILDER_ALIASES
The provided code snippet includes necessary dependencies for implementing the `serialize_base64` function. Write a Python function `def serialize_base64(obj: fields.Base64) -> str` to solve the following problem:
Serialize a Base64 wrapper object to raw binary data
Here is the function:
def serialize_base64(obj: fields.Base64) -> str:
"""Serialize a Base64 wrapper object to raw binary data"""
return str(obj) | Serialize a Base64 wrapper object to raw binary data |
162,978 | from __future__ import annotations
import json
import decimal
import inspect
import logging
import datetime
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Union, Mapping, Iterable, ForwardRef, cast
from datetime import timezone
from textwrap import indent
from functools import singledispatch
from typing_extensions import Literal, TypeGuard, override
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from . import fields
from ._types import PrismaMethod
from .errors import InvalidModelError, UnknownModelError, UnknownRelationalFieldError
from ._compat import get_args, is_union, get_origin, model_fields, model_field_type
from ._typing import is_list_type
from ._constants import QUERY_BUILDER_ALIASES
The provided code snippet includes necessary dependencies for implementing the `serialize_decimal` function. Write a Python function `def serialize_decimal(obj: decimal.Decimal) -> str` to solve the following problem:
Serialize a Decimal object to a string
Here is the function:
def serialize_decimal(obj: decimal.Decimal) -> str:
"""Serialize a Decimal object to a string"""
return str(obj) | Serialize a Decimal object to a string |
162,979 | import sys
from pathlib import Path
from importlib.util import find_spec
from typing_extensions import Protocol, runtime_checkable
PRISMA_INIT_CONTENTS = "__title__ = 'prisma'"
class SourceLoader(Protocol):
def get_filename(self) -> str:
...
def cleanup_templates(rootdir: Path, *, env: Optional[Environment] = None) -> None:
"""Revert module to pre-generation state"""
if env is None:
env = DEFAULT_ENV
for name in env.list_templates():
file = resolve_template_path(rootdir=rootdir, name=name)
if file.exists():
log.debug('Removing rendered template at %s', file)
file.unlink()
The provided code snippet includes necessary dependencies for implementing the `cleanup` function. Write a Python function `def cleanup(pkg_name: str = 'prisma') -> None` to solve the following problem:
Remove python files that are auto-generated by Prisma Client Python
Here is the function:
def cleanup(pkg_name: str = 'prisma') -> None:
"""Remove python files that are auto-generated by Prisma Client Python"""
spec = find_spec(pkg_name)
if spec is None:
raise RuntimeError(f'Could not resolve package: {pkg_name}')
loader = spec.loader
if loader is None:
raise RuntimeError(f'No loader defined for: {pkg_name}')
if not isinstance(loader, SourceLoader):
raise RuntimeError(f'Received unresolvable import loader: {loader}')
# ensure the package we've been given is actually a Prisma Client Python package
# we don't want to make it easy for users to accidentaly delete files from
# a non Prisma Client Python package
pkg_path = Path(loader.get_filename())
if PRISMA_INIT_CONTENTS not in pkg_path.read_text():
raise RuntimeError('The given package does not appear to be a Prisma Client Python package.')
# as we rely on prisma to cleanup the templates for us
# we have to make sure that prisma is importable and
# if any template rendered incorrect syntax or any other
# kind of error that wasn't automatically cleaned up,
# prisma will raise an error when imported,
# removing prisma/client.py fixes this as it is
# the only default entrypoint to generated code.
file = pkg_path.parent / 'client.py'
if file.exists():
file.unlink()
# the `prisma` package will always exist even when using a custom output
# location so it is safe to use here
from prisma.generator.generator import cleanup_templates
cleanup_templates(rootdir=pkg_path.parent)
print(f'Successfully removed all auto-generated files from {pkg_path}') # noqa: T201 | Remove python files that are auto-generated by Prisma Client Python |
162,980 | import os
import logging
import contextlib
from typing import Iterator
from prisma.utils import async_run
from bot import bot
def setup_logging() -> Iterator[None]:
logger = logging.getLogger('discord')
logger.setLevel(logging.INFO)
fmt = logging.Formatter(
'[{levelname:<7}] {name}: {message}',
style='{',
)
handler = logging.StreamHandler()
handler.setFormatter(fmt)
logger.addHandler(handler)
try:
yield
finally:
handler.close()
logger.removeHandler(handler)
def async_run(coro: Coroutine[Any, Any, _T]) -> _T:
"""Execute the coroutine and return the result."""
return get_or_create_event_loop().run_until_complete(coro)
bot = Bot()
def launch() -> None:
with setup_logging():
async_run(bot.prisma.connect())
bot.run(os.environ['BOT_TOKEN']) | null |
162,981 | from typing import TYPE_CHECKING, Optional
import discord
from discord.ext import commands
from prisma import Prisma
class Context(commands.Context):
bot = Bot()
async def total(ctx: Context, channel: Optional[discord.TextChannel] = None) -> None:
if channel is None:
if isinstance(ctx.channel, discord.TextChannel):
channel = ctx.channel
else:
await ctx.send('Could not resolve channel, this should never happen')
return
record = await ctx.bot.prisma.channel.find_unique(
where={
'id': channel.id,
},
)
if record is None:
await ctx.send(f"No messages have been sent in {channel.mention} since I've been here!")
else:
await ctx.send(f"{record.total} messages have been sent in {channel.mention} since I've been here!") | null |
162,982 | from typing import Optional
from prisma import Prisma, register, get_client
from prisma.models import Url
from hashids import Hashids
from flask import Flask, render_template, request, flash, redirect, url_for, g
def get_db() -> Prisma:
try:
return g.db
except AttributeError:
g.db = db = Prisma()
db.connect()
return db | null |
162,983 | from typing import Optional
from prisma import Prisma, register, get_client
from prisma.models import Url
from hashids import Hashids
from flask import Flask, render_template, request, flash, redirect, url_for, g
def close_db(exc: Optional[Exception] = None) -> None: # noqa: ARG001
client = get_client()
if client.is_connected():
client.disconnect() | null |
162,984 | from typing import Optional
from prisma import Prisma, register, get_client
from prisma.models import Url
from hashids import Hashids
from flask import Flask, render_template, request, flash, redirect, url_for, g
def index():
return render_template('index.html') | null |
162,985 | from typing import Optional
from prisma import Prisma, register, get_client
from prisma.models import Url
from hashids import Hashids
from flask import Flask, render_template, request, flash, redirect, url_for, g
hashids = Hashids(min_length=4, salt=app.config['SECRET_KEY'])
def create_shortened():
original: str = request.form['url']
if not original:
flash('The URL is required!')
return redirect(url_for('index'))
url = Url.prisma().create(
{
'original': original,
}
)
hashid = hashids.encode(url.id)
short_url = request.host_url + hashid
return render_template('index.html', short_url=short_url) | null |
162,986 | from typing import Optional
from prisma import Prisma, register, get_client
from prisma.models import Url
from hashids import Hashids
from flask import Flask, render_template, request, flash, redirect, url_for, g
hashids = Hashids(min_length=4, salt=app.config['SECRET_KEY'])
def url_redirect(id: str):
decoded = hashids.decode(id)
if decoded:
original_id = decoded[0]
url = Url.prisma().update(
where={
'id': original_id,
},
data={
'clicks': {
'increment': 1,
},
},
)
if url is None:
flash('URL not found')
return redirect(url_for('index'))
return redirect(url.original)
else:
flash('Invalid URL')
return redirect(url_for('index')) | null |
162,987 | from typing import Optional
from prisma import Prisma, register, get_client
from prisma.models import Url
from hashids import Hashids
from flask import Flask, render_template, request, flash, redirect, url_for, g
hashids = Hashids(min_length=4, salt=app.config['SECRET_KEY'])
def stats():
urls = Url.prisma().find_many(
order={
'clicks': 'desc',
}
)
short_urls = {url.id: request.host_url + hashids.encode(url.id) for url in urls}
return render_template('stats.html', urls=urls, short_urls=short_urls) | null |
162,988 | from typing import Optional, List
from fastapi import FastAPI
from prisma import Prisma
from prisma.models import User, Post
from prisma.types import UserUpdateInput
from prisma.partials import UserWithoutRelations, PostWithoutRelations
prisma = Prisma(auto_register=True)
async def startup() -> None:
await prisma.connect() | null |
162,989 | from typing import Optional, List
from fastapi import FastAPI
from prisma import Prisma
from prisma.models import User, Post
from prisma.types import UserUpdateInput
from prisma.partials import UserWithoutRelations, PostWithoutRelations
prisma = Prisma(auto_register=True)
async def shutdown() -> None:
if prisma.is_connected():
await prisma.disconnect() | null |
162,990 | from typing import Optional, List
from fastapi import FastAPI
from prisma import Prisma
from prisma.models import User, Post
from prisma.types import UserUpdateInput
from prisma.partials import UserWithoutRelations, PostWithoutRelations
prisma = Prisma(auto_register=True)
async def list_users(take: int = 10) -> List[User]:
return await User.prisma().find_many(take=take) | null |
162,991 | from typing import Optional, List
from fastapi import FastAPI
from prisma import Prisma
from prisma.models import User, Post
from prisma.types import UserUpdateInput
from prisma.partials import UserWithoutRelations, PostWithoutRelations
prisma = Prisma(auto_register=True)
async def create_user(name: str, email: Optional[str] = None) -> User:
return await User.prisma().create({'name': name, 'email': email}) | null |
162,992 | from typing import Optional, List
from fastapi import FastAPI
from prisma import Prisma
from prisma.models import User, Post
from prisma.types import UserUpdateInput
from prisma.partials import UserWithoutRelations, PostWithoutRelations
prisma = Prisma(auto_register=True)
async def update_user(
user_id: str,
name: Optional[str] = None,
email: Optional[str] = None,
) -> Optional[User]:
data: UserUpdateInput = {}
if name is not None:
data['name'] = name
if email is not None:
data['email'] = email
return await User.prisma().update(
where={
'id': user_id,
},
data=data,
) | null |
162,993 | from typing import Optional, List
from fastapi import FastAPI
from prisma import Prisma
from prisma.models import User, Post
from prisma.types import UserUpdateInput
from prisma.partials import UserWithoutRelations, PostWithoutRelations
prisma = Prisma(auto_register=True)
async def delete_user(user_id: str) -> Optional[User]:
return await User.prisma().delete(
where={
'id': user_id,
},
include={
'posts': True,
},
) | null |
162,994 | from typing import Optional, List
from fastapi import FastAPI
from prisma import Prisma
from prisma.models import User, Post
from prisma.types import UserUpdateInput
from prisma.partials import UserWithoutRelations, PostWithoutRelations
prisma = Prisma(auto_register=True)
async def get_user(user_id: str) -> Optional[User]:
return await User.prisma().find_unique(
where={
'id': user_id,
},
) | null |
162,995 | from typing import Optional, List
from fastapi import FastAPI
from prisma import Prisma
from prisma.models import User, Post
from prisma.types import UserUpdateInput
from prisma.partials import UserWithoutRelations, PostWithoutRelations
prisma = Prisma(auto_register=True)
async def get_user_posts(user_id: str) -> List[Post]:
user = await User.prisma().find_unique(
where={
'id': user_id,
},
include={
'posts': True,
},
)
if user is not None:
# we are including the posts, so they will never be None
assert user.posts is not None
return user.posts
return [] | null |
162,996 | from typing import Optional, List
from fastapi import FastAPI
from prisma import Prisma
from prisma.models import User, Post
from prisma.types import UserUpdateInput
from prisma.partials import UserWithoutRelations, PostWithoutRelations
prisma = Prisma(auto_register=True)
async def create_post(user_id: str, title: str, published: bool) -> Post:
return await Post.prisma().create(
data={
'title': title,
'published': published,
'author': {
'connect': {
'id': user_id,
},
},
}
) | null |
162,997 | from typing import Optional, List
from fastapi import FastAPI
from prisma import Prisma
from prisma.models import User, Post
from prisma.types import UserUpdateInput
from prisma.partials import UserWithoutRelations, PostWithoutRelations
prisma = Prisma(auto_register=True)
async def list_posts(take: int = 10) -> List[Post]:
return await Post.prisma().find_many(take=take) | null |
162,998 | from typing import Optional, List
from fastapi import FastAPI
from prisma import Prisma
from prisma.models import User, Post
from prisma.types import UserUpdateInput
from prisma.partials import UserWithoutRelations, PostWithoutRelations
prisma = Prisma(auto_register=True)
async def get_post(post_id: str) -> Optional[Post]:
return await Post.prisma().find_unique(
where={
'id': post_id,
},
include={
'author': True,
},
) | null |
162,999 | from typing import Optional, List
from fastapi import FastAPI
from prisma import Prisma
from prisma.models import User, Post
from prisma.types import UserUpdateInput
from prisma.partials import UserWithoutRelations, PostWithoutRelations
prisma = Prisma(auto_register=True)
async def delete_post(post_id: str) -> Optional[Post]:
return await Post.prisma().delete(
where={
'id': post_id,
},
include={
'author': True,
},
) | null |
163,000 | from __future__ import annotations
from typing import TypeVar
from pathlib import Path
T = TypeVar('T')
def flatten(arr: list[list[T]]) -> list[T]:
return [item for sublist in arr for item in sublist] | null |
163,001 | from __future__ import annotations
from typing import TypeVar
from pathlib import Path
def escape_path(path: str | Path) -> str:
if isinstance(path, Path): # pragma: no branch
path = str(path.absolute())
return path.replace('\\', '\\\\') | null |
163,002 | from __future__ import annotations
from typing import TypeVar
from pathlib import Path
The provided code snippet includes necessary dependencies for implementing the `maybe_decode` function. Write a Python function `def maybe_decode(data: str | bytes) -> str` to solve the following problem:
Helper for decoding `bytes`. - Given a `bytes` object, return it decoded using utf8. - Given a `str` object, return it as is.
Here is the function:
def maybe_decode(data: str | bytes) -> str:
"""Helper for decoding `bytes`.
- Given a `bytes` object, return it decoded using utf8.
- Given a `str` object, return it as is.
"""
if isinstance(data, bytes):
return data.decode('utf8')
return data | Helper for decoding `bytes`. - Given a `bytes` object, return it decoded using utf8. - Given a `str` object, return it as is. |
163,003 | import tempfile
from pathlib import Path
import nox
import distro
def get_pkg_location(session: nox.Session, pkg: str) -> str:
location = session.run(
'python',
'-c',
f'import {pkg}; print({pkg}.__file__)',
silent=True,
)
assert isinstance(location, str)
return str(Path(location).parent) | null |
163,004 | import tempfile
from pathlib import Path
import nox
import distro
def setup_coverage(session: nox.Session, identifier: str) -> None:
if identifier:
identifier = f'.{identifier}'
coverage_file = f'.coverage.{session.name}{identifier}'
session.env['COVERAGE_FILE'] = str(CACHE_DIR / coverage_file)
def setup_env(session: nox.Session) -> None:
setup_coverage(
session,
identifier=session.python if isinstance(session.python, str) else '',
)
session.env['PRISMA_PY_DEBUG'] = '1'
session.env['PYTEST_ADDOPTS'] = ' '.join(
[
f'"{opt}"'
for opt in [
'-W error',
# httpx deprecation warnings
"-W ignore:'cgi' is deprecated and slated for removal in Python 3.13:DeprecationWarning",
'-W ignore:path is deprecated:DeprecationWarning',
]
]
) | null |
163,005 | import tempfile
from pathlib import Path
import nox
import distro
PIPELINES_DIR = Path(__file__).parent.parent
def maybe_install_nodejs_bin(session: nox.Session) -> bool:
# nodejs-bin is not available on alpine yet, we need to wait until this fix is released:
# https://github.com/samwillis/nodejs-pypi/issues/11
if distro.id() == 'alpine':
return False
session.install('-r', str(PIPELINES_DIR / 'requirements/node.txt'))
return True | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.