file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
pyngo/__init__.py
Python
"""Pydantic Package for Adding Models into a Django or Django Rest Framework Project""" __version__ = "2.4.1" from .errors import drf_error_details from .openapi import ParameterDict, openapi_params from .querydict import QueryDictModel, querydict_to_dict __all__ = ( "ParameterDict", "QueryDictModel", "querydict_to_dict", "drf_error_details", "openapi_params", )
yezz123/pyngo
89
Pydantic model support for Django & Django-Rest-Framework ✨
Python
yezz123
Yasser Tahiri
Yezz LLC.
pyngo/errors.py
Python
from collections.abc import Sequence from typing import Any from pydantic import ValidationError def drf_error_details(exception: ValidationError) -> dict[str, Any]: """ Convert a pydantic ValidationError into a DRF-style error response. Args: exception (ValidationError): The exception to convert. Returns: dict[str, Any]: The error response. """ drf_data: dict[str, Any] = {} for error in exception.errors(): set_nested(drf_data, error["loc"], [error["msg"]]) return drf_data def set_nested(data: dict[str, Any], keys: Sequence[int | str], value: Any) -> None: """ Set a value in a nested dictionary. Args: data (dict[str, Any]): The dictionary to set the value in. keys (tuple[int | str, ...]): The keys to set the value at. value (Any): The value to set. Returns: None """ for key in keys[:-1]: data = data.setdefault(str(key), {}) data[str(keys[-1])] = value def get_nested(data: dict[str, Any], keys: Sequence[str]) -> Any: """ Get a value from a nested dictionary. Args: data (Dict[str, Any]): The dictionary to get the value from. keys (Sequence[str]): The keys to get the value at. Returns: Any: The value. """ for key in keys[:-1]: data = data[key] return data[keys[-1]]
yezz123/pyngo
89
Pydantic model support for Django & Django-Rest-Framework ✨
Python
yezz123
Yasser Tahiri
Yezz LLC.
pyngo/openapi.py
Python
import types from typing import Literal, Optional, Type, TypedDict, Union, cast, get_args, get_origin from pydantic import BaseModel from pydantic.fields import FieldInfo _In = Literal["query", "header", "path", "cookie"] ParameterDict = TypedDict( "ParameterDict", { "name": str, "in": _In, "description": str, "required": bool, "deprecated": bool, "allowEmptyValue": bool, }, total=False, ) _VALID_LOCATIONS = ("query", "header", "path", "cookie") def is_simple_type(field: FieldInfo) -> bool: """ Returns True if the given field has simple type. Args: field (FieldInfo): The field to check. Returns: bool: True if the given field has simple type. """ args = get_args(field.annotation) if args == (): return True origin = get_origin(field.annotation) if origin in [Optional, Union]: match args: case (klass, types.NoneType) if get_args(klass) == (): return True case (types.NoneType, klass) if get_args(klass) == (): return True case _: return False return False def openapi_params( model_class: Type[BaseModel], ) -> list[ParameterDict]: """ Returns a list of parameters for the given model class. Args: model_class (Type[BaseModel]): The model class to get parameters for. Raises: ValueError: If the model class is not a pydantic model. ValueError: If the model class has a field with an invalid location. ValueError: If the model class has a field with allowEmptyValue set for a location other than 'query'. ValueError: If the model class has a field with required set to False for a path parameter. Returns: list[ParameterDict]: A list of parameters for the given model class. """ parameters: list[ParameterDict] = [] for name, field in model_class.model_fields.items(): if not is_simple_type(field): raise ValueError("Only simple types allowed") parameters.append(_pydantic_field_to_parameter(name, field)) return parameters def _pydantic_field_to_parameter(name: str, field: FieldInfo) -> ParameterDict: """ Converts a pydantic field to an OpenAPI parameter. Args: field (FieldInfo): The field to convert. Raises: ValueError: If the field has an invalid location. ValueError: If the field has allowEmptyValue set for a location other than 'query'. ValueError: If the field has required set to False for a path parameter. Returns: ParameterDict: The converted field. """ field_extra = (None if callable(field.json_schema_extra) else field.json_schema_extra) or {} location = field_extra.get("location", "query") if location not in _VALID_LOCATIONS: raise ValueError(f"location must be one of: {', '.join(_VALID_LOCATIONS)}") required = field.is_required() if location == "path" and not required: raise ValueError("Path parameters must be required") deprecated = field_extra.get("deprecated", False) args = { "name": name, "in": location, "description": field.description or "", "required": required, "deprecated": deprecated, } allow_empty_value = field_extra.get("allowEmptyValue") if allow_empty_value is not None and location != "query": raise ValueError("allowEmptyValue only permitted for 'query' values") elif location == "query": if allow_empty_value is not None: args["allowEmptyValue"] = allow_empty_value else: args["allowEmptyValue"] = False return cast(ParameterDict, args)
yezz123/pyngo
89
Pydantic model support for Django & Django-Rest-Framework ✨
Python
yezz123
Yasser Tahiri
Yezz LLC.
pyngo/querydict.py
Python
from collections import deque from types import NoneType, UnionType from typing import Any, Type, get_args, get_origin from django.http import QueryDict from pydantic import BaseModel from pydantic.fields import FieldInfo from typing_extensions import Self class QueryDictModel(BaseModel): """ A model that can be initialized from a QueryDict. This is a base class for models that can be initialized from a QueryDict. The QueryDictModel class is a base class for models that can be initialized from a QueryDict. """ @classmethod def model_validate( cls, obj: Any, *, strict: bool | None = None, from_attributes: bool | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None, ) -> Self: """ Parse a QueryDict into a model. Returns: A model that was initialized from the QueryDict. """ if isinstance(obj, QueryDict): obj = querydict_to_dict(obj, cls) return super().model_validate(obj, strict=strict, from_attributes=from_attributes, context=context) def querydict_to_dict( query_dict: QueryDict, model_class: Type[BaseModel], ) -> dict[str, Any]: """ Convert a QueryDict into a dictionary. Args: query_dict (QueryDict): The QueryDict to convert. model_class (Type[BaseModel]): The model class to use for the conversion. Returns: Dict[str, Any]: The converted dictionary. """ to_dict: dict[str, Any] = {} model_fields = model_class.model_fields for key, orig_value in query_dict.items(): # Get field name (as defined in Pydantic model, not necessary the key in data dict, because of aliasing) field_key = next( (name for (name, inf) in model_fields.items() if inf.alias == key or inf.validation_alias == key), key ) if field_key not in model_fields: to_dict[key] = orig_value continue field = model_fields[field_key] # Discard field if its value is empty string and we don't expect string in model if orig_value in ("", b"") and not _is_string_like_field(field): continue if _is_sequence_field(field): to_dict[key] = query_dict.getlist(key) else: to_dict[key] = query_dict.get(key) return to_dict def _is_string_like_field(field: FieldInfo) -> bool: """ Check if a field is a string-like field (str, bytes, bytearray, StrEnum). Args: field (FieldInfo): The field to check. Returns: bool: True if the field is a string-like field, False otherwise. """ if not field.annotation: return False try: return issubclass(field.annotation, (str, bytes, bytearray)) except TypeError: return False def _is_sequence_field(field: FieldInfo) -> bool: """ Check if a field is a sequence field. Args: field (FieldInfo): The field to check. Returns: bool: True if the field is a list field, False otherwise. """ SEQUENCE_TYPES = (list, tuple, deque, set, frozenset) origin_type = get_origin(field.annotation) if origin_type in SEQUENCE_TYPES: return True # Hanlde the case of list[int] | None if origin_type is UnionType: union_arg_types = get_args(field.annotation) first_member_type, second_member_type = union_arg_types[:2] return (second_member_type is NoneType and get_origin(first_member_type) in SEQUENCE_TYPES) or ( first_member_type is NoneType and get_origin(second_member_type) in SEQUENCE_TYPES ) return False
yezz123/pyngo
89
Pydantic model support for Django & Django-Rest-Framework ✨
Python
yezz123
Yasser Tahiri
Yezz LLC.
tests/errors_test.py
Python
from typing import List, Optional import pytest from pydantic import BaseModel, ValidationError, field_validator from pyngo import drf_error_details from pyngo.errors import get_nested class NestedModel(BaseModel): str_field: str @field_validator("str_field") @classmethod def must_be_bar(cls, value: str) -> str: special_name = "bar" if value != special_name: raise ValueError(f"Name must be: '{special_name}'!") else: return value class MyModel(BaseModel): int_field: Optional[int] = None nested_field: Optional[NestedModel] = None nested_list: Optional[List[NestedModel]] = None @field_validator("int_field") @classmethod def must_be_special_value(cls, value: int) -> int: magic_number = 42 if value != magic_number: raise ValueError("Must be the magic number!") else: return value class TestToDRFError: def test_with_single_flat_field(self) -> None: with pytest.raises(ValidationError) as e: MyModel(int_field=2) assert drf_error_details(e.value) == {"int_field": ["Value error, Must be the magic number!"]} def test_with_nested_field(self) -> None: with pytest.raises(ValidationError) as e: MyModel(nested_field={"str_field": "foo"}) assert drf_error_details(e.value) == {"nested_field": {"str_field": ["Value error, Name must be: 'bar'!"]}} def test_with_nested_list(self) -> None: try: MyModel.model_validate({"nested_list": [{"str_field": "bar"}, {"str_field": "foo"}]}) except ValidationError as e: assert drf_error_details(e) == {"nested_list": {"1": {"str_field": ["Value error, Name must be: 'bar'!"]}}} class TestGetNested: def test_get_nested_with_valid_data(self): result = self.data("bar") # Assert the result assert result == "bar" def test_get_nested_with_invalid_data(self): result = self.data("not_bar") with pytest.raises(ValueError, match="Name must be: 'bar'!"): NestedModel(str_field=result).model_dump() def data(self, arg): nested_data = {"first": {"second": {"third": {"str_field": arg}}}} keys = ["first", "second", "third", "str_field"] return get_nested(nested_data, keys) def test_must_be_bar_validator_with_valid_value(self): # Create a valid NestedModel instance valid_model = NestedModel(str_field="bar") # Assert that validation does not raise an error valid_model.model_dump() def test_must_be_bar_validator_with_invalid_value(self): # Create an invalid NestedModel instance with pytest.raises(ValidationError, match="Name must be: 'bar'!"): NestedModel(str_field="not_bar") class TestMyModel: def test_must_be_special_value_validator_with_invalid_value(self): with pytest.raises(ValidationError, match="Must be the magic number!"): MyModel(int_field=10) def test_valid_model_creation(self): valid_model = MyModel(int_field=42, nested_field=NestedModel(str_field="bar")) assert valid_model.int_field == 42 assert valid_model.nested_field.str_field == "bar"
yezz123/pyngo
89
Pydantic model support for Django & Django-Rest-Framework ✨
Python
yezz123
Yasser Tahiri
Yezz LLC.
tests/openapi_test.py
Python
from typing import Dict, Optional import pytest from pydantic import BaseModel, Field from pyngo import ParameterDict, openapi_params class TestPydanticModelToOpenapiParameters: def test_only_primitive_types_allowed(self) -> None: class Model(BaseModel): non_primitive: Dict[str, str] with pytest.raises(ValueError) as exc: openapi_params(Model) assert str(exc.value) == "Only simple types allowed" def test_prohibits_unknown_location(self) -> None: class Model(BaseModel): path_param: int = Field(json_schema_extra={"location": "foo"}) with pytest.raises(ValueError) as exc: openapi_params(Model) assert str(exc.value) == "location must be one of: query, header, path, cookie" def test_prohibits_optional_path_params(self) -> None: class Model(BaseModel): path_param: Optional[int] = Field(default=0, json_schema_extra={"location": "path"}) with pytest.raises(ValueError) as exc: openapi_params(Model) assert str(exc.value) == "Path parameters must be required" def test_defaults_path_params_to_be_required(self) -> None: class Model(BaseModel): path_param: int = Field(json_schema_extra={"location": "path"}) params = openapi_params(Model) assert len(params) == 1 assert params[0]["required"] @pytest.mark.parametrize("param_loc", ("header", "path", "cookie")) def test_prohibits_allow_empty_outside_of_query(self, param_loc: str) -> None: class Model(BaseModel): param: int = Field(json_schema_extra={"location": param_loc, "allowEmptyValue": True}) with pytest.raises(ValueError) as exc: openapi_params(Model) assert str(exc.value) == "allowEmptyValue only permitted for 'query' values" def test_allow_empty_excluded_for_non_query_params(self) -> None: class Model(BaseModel): param: int = Field(json_schema_extra={"location": "header"}) params = openapi_params(Model) assert len(params) == 1 assert "allowEmptyValue" not in params[0] def test_allow_empty_value_defaults_to_true_for_query_params(self) -> None: class Model(BaseModel): param: int = Field() self.openapi_param(Model, "allowEmptyValue") def test_deprecated_defaults_to_false(self) -> None: class Model(BaseModel): param: int = Field() self.openapi_param(Model, "deprecated") def test_optional_fields_are_not_required(self) -> None: class Model(BaseModel): param: Optional[int] = Field(default=0) self.openapi_param(Model, "required") def openapi_param(self, Model, arg): params = openapi_params(Model) assert len(params) == 1 assert not params[0][arg] def test_reading_query_params(self) -> None: class PathParams(BaseModel): document_id: int = Field( description="The document id", json_schema_extra={ "location": "query", "deprecated": True, "allowEmptyValue": True, }, ) expected_parameters = [ ParameterDict( { "in": "query", "name": "document_id", "description": "The document id", "required": True, "deprecated": True, "allowEmptyValue": True, } ) ] assert openapi_params(PathParams) == expected_parameters
yezz123/pyngo
89
Pydantic model support for Django & Django-Rest-Framework ✨
Python
yezz123
Yasser Tahiri
Yezz LLC.
tests/querydict_test.py
Python
import os from collections import deque from typing import Annotated, Any, Deque, Dict, FrozenSet, List, Optional, Tuple, Union import pytest from django.http import QueryDict from pydantic import ConfigDict, Field from pyngo import QueryDictModel os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings" class Model(QueryDictModel): model_config = ConfigDict(populate_by_name=True) foo: int bar: List[int] sub_id: Optional[int] = None key: str = "key" wings: Tuple[int, ...] = Field(default_factory=tuple) queue: Deque[int] = Field(default_factory=deque) basket: FrozenSet[int] = Field(default_factory=frozenset) alias_list: List[int] = Field(alias="alias[list]", default_factory=list) nodes: Annotated[list[int] | None, Field(validation_alias="node")] = None author: int | str = 0 @pytest.mark.parametrize( ("data", "expected"), ( ( QueryDict("foo=12&bar=12"), Model(foo=12, bar=[12], key="key", wings=(), queue=deque(), basket=frozenset(), author=0), ), ({"foo": 44, "bar": [0, 4], "author": 5}, Model(foo=44, bar=[0, 4], key="key", author=5)), ( QueryDict("foo=10&bar=12&sub_id=&key="), Model(foo=10, bar=[12], sub_id=None, key=""), ), ( QueryDict("foo=10&bar=12&key=abc&extra=something"), Model(foo=10, bar=[12], key="abc"), ), ( QueryDict("foo=8&bar=9&wings=1&wings=2&queue=3&queue=4"), Model(foo=8, bar=[9], wings=(1, 2), queue=deque((3, 4))), ), ( QueryDict("foo=8&bar=9&basket=5&basket=6"), Model(foo=8, bar=[9], basket=frozenset((5, 6))), ), ( QueryDict("foo=8&bar=9&basket=5&basket=6&alias[list]=5&alias[list]=3"), # This has to be a dictionary due to the invalid characters in alias[list] # Which has to be set because that's what the model is looking for via the Field alias Model( **{ "foo": 8, "bar": [9], "basket": frozenset((5, 6)), "alias[list]": [5, 3], } ), ), ( QueryDict("foo=1&bar=2&node=9&node=10"), Model(foo=1, bar=[2], nodes=[9, 10]), ), ( QueryDict("foo=1&bar=2&author=user@example.com"), Model(foo=1, bar=[2], author="user@example.com"), ), ), ) def test_parsing_objects(data: Union[QueryDict, Dict[str, Any]], expected: Model) -> None: got = Model.model_validate(data) assert got == expected assert got.foo == expected.foo assert got.bar == expected.bar assert got.sub_id == expected.sub_id assert got.key == expected.key assert got.wings == expected.wings assert got.queue == expected.queue assert got.basket == expected.basket assert got.alias_list == expected.alias_list
yezz123/pyngo
89
Pydantic model support for Django & Django-Rest-Framework ✨
Python
yezz123
Yasser Tahiri
Yezz LLC.
tests/settings.py
Python
# Empty settings file just so we can pass Django
yezz123/pyngo
89
Pydantic model support for Django & Django-Rest-Framework ✨
Python
yezz123
Yasser Tahiri
Yezz LLC.
__tests__/input.test.ts
TypeScript
import { getInputs, getVenvInput, getVersionInput, getCacheInput, isCacheAllowed } from '../src/inputs' import * as core from '@actions/core' jest.mock('@actions/core') const mockedCore = core as jest.Mocked<typeof core> const TEST_ENV_VARS = { INPUT_MISSING: '', INPUT_FALSY: 'false', INPUT_TRUTHY: 'true', INPUT_VERSION_UNSUPPORTED: '0.0.3', INPUT_VERSION_SUPPORTED: '0.1.2', INPUT_VERSION_CACHE_SUPPORTED: '0.3.0', INPUT_VERSION_LATEST: 'latest', 'INPUT_UV-VERSION': '0.1.2', 'INPUT_UV-VENV': 'my_venv', 'INPUT_UV-CACHE': 'true' } describe('options', () => { beforeEach(() => { jest.resetAllMocks() for (const key in TEST_ENV_VARS) { process.env[key] = TEST_ENV_VARS[key as keyof typeof TEST_ENV_VARS] } }) afterEach(() => { for (const key in TEST_ENV_VARS) { delete process.env[key] } }) it('getVersionInput returns null if input is missing', () => { mockedCore.getInput.mockReturnValue('') expect(getVersionInput('missing')).toBeNull() expect(mockedCore.notice).toHaveBeenCalledWith('Using latest uv version') }) it('getVersionInput returns null if input is "latest"', () => { mockedCore.getInput.mockReturnValue('latest') expect(getVersionInput('version_latest')).toBeNull() expect(mockedCore.notice).toHaveBeenCalledWith('Using latest uv version') }) it('getVersionInput throws if input is not valid', () => { mockedCore.getInput.mockReturnValue('false') expect(() => getVersionInput('falsy')).toThrow( "Passed uv version 'false' is not valid" ) }) it('getVersionInput warns if version is unsupported', () => { mockedCore.getInput.mockReturnValue('0.2.9') expect(getVersionInput('version_unsupported')).toBe('0.2.9') expect(mockedCore.warning).toHaveBeenCalledWith( "Passed uv version '0.2.9' is less than 0.3.0. Caching will be disabled." ) expect(mockedCore.warning).toHaveBeenCalledWith( 'Using uv version 0.2.9. This may not be the latest version.' ) }) it('getVersionInput warns for supported version', () => { mockedCore.getInput.mockReturnValue('0.3.0') expect(getVersionInput('version_supported')).toBe('0.3.0') expect(mockedCore.warning).toHaveBeenCalledWith( 'Using uv version 0.3.0. This may not be the latest version.' ) }) it('getVenvInput returns venv name if input is valid', () => { mockedCore.getInput.mockReturnValue('my_venv') expect(getVenvInput('uv-venv')).toBe('my_venv') }) it('getVenvInput returns null if input is not provided', () => { mockedCore.getInput.mockReturnValue('') expect(getVenvInput('SOMETHING')).toBeNull() }) it('getInputs returns inputs including cache', () => { mockedCore.getInput.mockImplementation(name => { if (name === 'uv-version') { return '0.3.0' } if (name === 'uv-venv') { return 'my_venv' } if (name === 'uv-cache') { return 'true' } return '' }) expect(getInputs()).toStrictEqual({ version: '0.3.0', venv: 'my_venv', cache: true }) expect(mockedCore.warning).toHaveBeenCalledWith( 'Using uv version 0.3.0. This may not be the latest version.' ) }) it('getCacheInput returns true if input is true and version is supported', () => { mockedCore.getInput.mockReturnValue('true') expect(getCacheInput('uv-cache', '0.3.0')).toBe(true) }) it('getCacheInput returns false if input is true but version is not supported', () => { mockedCore.getInput.mockReturnValue('true') expect(getCacheInput('uv-cache', '0.2.9')).toBe(false) expect(mockedCore.warning).toHaveBeenCalledWith( 'Cache requested but uv version is less than 0.3.0. Caching will be disabled.' ) }) it('getCacheInput returns false if input is false', () => { mockedCore.getInput.mockReturnValue('false') expect(getCacheInput('uv-cache', '0.3.0')).toBe(false) }) it('getCacheInput returns true if input is true and version is null (latest)', () => { mockedCore.getInput.mockReturnValue('true') expect(getCacheInput('uv-cache', null)).toBe(true) }) it('isCacheAllowed returns true for supported versions', () => { expect(isCacheAllowed('0.3.0')).toBe(true) expect(isCacheAllowed('0.4.0')).toBe(true) expect(isCacheAllowed(null)).toBe(true) // null represents latest version }) it('isCacheAllowed returns false for unsupported versions', () => { expect(isCacheAllowed('0.2.9')).toBe(false) expect(isCacheAllowed('0.1.0')).toBe(false) }) it('getCacheInput returns false if cache is not requested, even if version is supported', () => { mockedCore.getInput.mockReturnValue('false') expect(getCacheInput('uv-cache', '0.3.0')).toBe(false) }) it('getInputs returns cache as false when cache is not requested, even if version is supported', () => { mockedCore.getInput.mockImplementation(name => { if (name === 'uv-version') { return '0.3.0' } if (name === 'uv-venv') { return 'my_venv' } if (name === 'uv-cache') { return 'false' } return '' }) expect(getInputs()).toStrictEqual({ version: '0.3.0', venv: 'my_venv', cache: false }) expect(mockedCore.warning).toHaveBeenCalledWith( 'Using uv version 0.3.0. This may not be the latest version.' ) }) })
yezz123/setup-uv
43
Set up your GitHub Actions workflow with a specific version of uv
TypeScript
yezz123
Yasser Tahiri
Yezz LLC.
src/cache.ts
TypeScript
import * as core from '@actions/core' import * as cache from '@actions/cache' import * as exec from '@actions/exec' import * as io from '@actions/io' import * as fs from 'fs' import * as crypto from 'crypto' import * as path from 'path' import * as os from 'os' const UV_CACHE_DIR = process.env.UV_CACHE_DIR || path.join(os.tmpdir(), '.uv-cache') export async function setupCache(): Promise<void> { core.info(`Setting up uv cache directory: ${UV_CACHE_DIR}`) await io.mkdirP(UV_CACHE_DIR) core.exportVariable('UV_CACHE_DIR', UV_CACHE_DIR) } export async function restoreCache(): Promise<void> { const lockFile = 'uv.lock' if (!fs.existsSync(lockFile)) { core.info('No uv.lock file found. Skipping cache restore.') return } const hash = await getFileHash(lockFile) const cacheKey = `uv-${process.platform}-${hash}` core.info(`Attempting to restore uv cache with key: ${cacheKey}`) const cacheHit = await cache.restoreCache([UV_CACHE_DIR], cacheKey, [ `uv-${process.platform}-` ]) if (cacheHit) { core.info('Cache restored successfully') } else { core.info('No cache found. A new cache will be created after installation.') } } export async function saveCache(): Promise<void> { const lockFile = 'uv.lock' if (!fs.existsSync(lockFile)) { core.info('No uv.lock file found. Skipping cache save.') return } const hash = await getFileHash(lockFile) const cacheKey = `uv-${process.platform}-${hash}` core.info(`Saving uv cache with key: ${cacheKey}`) try { await cache.saveCache([UV_CACHE_DIR], cacheKey) core.info('Cache saved successfully') } catch (error) { core.warning(`Failed to save cache: ${error}`) } } export async function minimizeCache(): Promise<void> { core.info('Minimizing uv cache') await exec.exec('uv', ['cache', 'prune', '--ci']) } async function getFileHash(filePath: string): Promise<string> { return new Promise((resolve, reject) => { const hash = crypto.createHash('sha256') const stream = fs.createReadStream(filePath) stream.on('error', err => reject(err)) stream.on('data', chunk => hash.update(chunk)) stream.on('end', () => resolve(hash.digest('hex'))) }) }
yezz123/setup-uv
43
Set up your GitHub Actions workflow with a specific version of uv
TypeScript
yezz123
Yasser Tahiri
Yezz LLC.
src/find.ts
TypeScript
import { addPath } from '@actions/core' import { exec } from '@actions/exec' import { mv } from '@actions/io' import { downloadTool } from '@actions/tool-cache' import os from 'os' import path from 'path' const UV_UNIX_LATEST_URL = 'https://astral.sh/uv/install.sh' const UV_WIN_LATEST_URL = 'https://astral.sh/uv/install.ps1' export async function findUv(version: string | null): Promise<void> { const installScriptUrl = getInstallScriptUrl(version) const uvInstallPath = await downloadTool(installScriptUrl) await installUv(os.platform(), uvInstallPath) // Add uv executable to the PATH const uvPath = path.join(os.homedir(), ...getUvPathArgs()) addPath(uvPath) } function getInstallScriptUrl(version: string | null): string { let installScript: string if (os.platform() === 'win32') { installScript = version == null ? UV_WIN_LATEST_URL : `https://github.com/astral-sh/uv/releases/download/${version}/uv-installer.ps1` } else { installScript = version == null ? UV_UNIX_LATEST_URL : `https://github.com/astral-sh/uv/releases/download/${version}/uv-installer.sh` } return installScript } async function installUv( platform: string, uvInstallPath: string ): Promise<number> { if (platform === 'win32') { await mv(uvInstallPath, uvInstallPath + '.ps1') return await exec('powershell', ['-File', `${uvInstallPath}.ps1`]) } else { return await exec('sh', [uvInstallPath]) } } function getUvPathArgs(): string[] { if (os.platform() === 'win32') { return ['AppData', 'Roaming', 'uv'] } return ['.local', 'bin'] }
yezz123/setup-uv
43
Set up your GitHub Actions workflow with a specific version of uv
TypeScript
yezz123
Yasser Tahiri
Yezz LLC.
src/inputs.ts
TypeScript
import { getInput, notice, warning } from '@actions/core' import semver from 'semver' export interface Inputs { version: string | null venv: string | null cache: boolean } export function getInputs(): Inputs { const version = getVersionInput('uv-version') return { version, venv: getVenvInput('uv-venv'), cache: getCacheInput('uv-cache', version) } } export function getVersionInput(name: string): string | null { const version = getInput(name) if (!version || version.toLowerCase() === 'latest') { notice('Using latest uv version') return null } const coerced = semver.coerce(version) if (!coerced) { throw new Error(`Passed uv version '${version}' is not valid`) } else if (!semver.satisfies(coerced, '>=0.3.0')) { warning( `Passed uv version '${coerced}' is less than 0.3.0. Caching will be disabled.` ) } warning(`Using uv version ${version}. This may not be the latest version.`) return version.trim() } export function getVenvInput(name: string): string | null { const venv = getInput(name) if (!venv) { return null } return venv.trim() } export function getCacheInput(name: string, version: string | null): boolean { const cache = getInput(name) const cacheRequested = cache.toLowerCase() === 'true' if (cacheRequested && version) { const coerced = semver.coerce(version) if (coerced && semver.satisfies(coerced, '>=0.3.0')) { return true } else { warning( 'Cache requested but uv version is less than 0.3.0. Caching will be disabled.' ) return false } } return cacheRequested && version === null // Allow caching for 'latest' version } export function isCacheAllowed(version: string | null): boolean { if (!version) { return true } const coerced = semver.coerce(version) return coerced ? semver.satisfies(coerced, '>=0.3.0') : false }
yezz123/setup-uv
43
Set up your GitHub Actions workflow with a specific version of uv
TypeScript
yezz123
Yasser Tahiri
Yezz LLC.
src/main.ts
TypeScript
import { setFailed, getInput, warning } from '@actions/core' import { findUv } from './find' import { getInputs, isCacheAllowed } from './inputs' import { activateVenv, createVenv } from './venv' import { setupCache, restoreCache, saveCache, minimizeCache } from './cache' async function run(): Promise<void> { try { const inputs = getInputs() const cacheDir = getInput('uv-cache-dir') if (cacheDir) { process.env.UV_CACHE_DIR = cacheDir } const shouldCache = inputs.cache && isCacheAllowed(inputs.version) if (shouldCache) { await setupCache() await restoreCache() } else if (inputs.cache && !isCacheAllowed(inputs.version)) { warning( 'Caching is not supported for uv versions below 0.3.0. Skipping cache operations.' ) } await findUv(inputs.version) if (inputs.venv) { await createVenv(inputs.venv) await activateVenv(inputs.venv) } if (shouldCache) { await saveCache() await minimizeCache() } } catch (error) { setFailed(errorAsMessage(error)) } } function errorAsMessage(error: unknown) { if (error instanceof Error) { return error.message } return String(error) } run()
yezz123/setup-uv
43
Set up your GitHub Actions workflow with a specific version of uv
TypeScript
yezz123
Yasser Tahiri
Yezz LLC.
src/venv.ts
TypeScript
import { exec } from '@actions/exec' import { exportVariable, addPath } from '@actions/core' import os from 'os' import path from 'path' const uvBinPath = path.join(os.homedir(), '.local', 'bin') export async function createVenv(venv: string) { if (os.platform() === 'win32') { await exec('powershell', [ '-Command', `$env:Path = "${uvBinPath};$env:Path"` ]) } addPath(uvBinPath) await exec('uv', ['venv', venv]) } export async function activateVenv(venv: string) { if (os.platform() === 'win32') { await exec('powershell', [`${venv}\\Scripts\\activate.ps1`]) addPath(`${venv}/Scripts`) } else { await exec('/bin/bash', ['-c', `source ${venv}/bin/activate`]) addPath(`${venv}/bin`) } exportVariable('VIRTUAL_ENV', venv) }
yezz123/setup-uv
43
Set up your GitHub Actions workflow with a specific version of uv
TypeScript
yezz123
Yasser Tahiri
Yezz LLC.
app/__init__.py
Python
__version__ = "0.0.1"
yezz123/stripe-template
14
Template for integrating stripe into your FastAPI application 💸
Python
yezz123
Yasser Tahiri
Yezz LLC.
app/main.py
Python
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from app.router.includes import app as router from app.settings.config import Settings config = Settings() app = FastAPI( description=config.API_DESCRIPTION, title=config.API_TITLE, version=config.API_VERSION, docs_url=config.API_DOC_URL, openapi_url=config.API_OPENAPI_URL, redoc_url=config.API_REDOC_URL, debug=config.DEBUG, ) app.include_router(router) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
yezz123/stripe-template
14
Template for integrating stripe into your FastAPI application 💸
Python
yezz123
Yasser Tahiri
Yezz LLC.
app/router/includes.py
Python
from fastapi import APIRouter from app.router.v1 import health, payment app = APIRouter() app.include_router(payment.app, tags=["Payment"]) app.include_router(health.router, tags=["Health"])
yezz123/stripe-template
14
Template for integrating stripe into your FastAPI application 💸
Python
yezz123
Yasser Tahiri
Yezz LLC.
app/router/v1/health.py
Python
from fastapi import APIRouter router = APIRouter() @router.get("/health") async def health_check() -> str: return "Pong!"
yezz123/stripe-template
14
Template for integrating stripe into your FastAPI application 💸
Python
yezz123
Yasser Tahiri
Yezz LLC.
app/router/v1/payment.py
Python
import stripe from decouple import config from fastapi import APIRouter, HTTPException, Request from fastapi.responses import RedirectResponse from pydantic import EmailStr, constr from stripe import Customer, checkout, error from app.settings.config import Settings setting = Settings() app = APIRouter() stripe.api_key = constr(regex=r"sk_.*")(config("STRIPE_API_KEY")) @app.get("/success") def success() -> str: """Redirect page on success""" return "Payment method registered with success ✅" @app.get("/cancel") def cancel() -> str: """Redirect page on cancel""" return "Operation canceled ❌" def session_url(customer_id: str, request: dict) -> str: """ Create a new checkout session for the customer to setup a new payment method More details on https://stripe.com/docs/api/checkout/sessions/create and on: https://stripe.com/docs/payments/sepa-debit/set-up-payment?platform=checkout """ success_url = f"{request['url']['scheme']}://{request['url']['netloc']}/success" cancel_url = f"{request['url']['scheme']}://{request['url']['netloc']}/cancel" checkout_session = checkout.Session.create( payment_method_types=setting.PAYMENT_METHOD_TYPES, mode="setup", customer=customer_id, success_url=success_url, cancel_url=cancel_url, ) return checkout_session.id @app.get("/email/{email}", summary="Setup a new payment method by email") def setup_new_method_by_email(email: EmailStr, request: Request): """ Retrieve a customer by email and redirect to the checkout session More details on https://stripe.com/docs/api/customers/list """ customer = Customer.list(email=email) if not customer: raise HTTPException( status_code=404, detail=f"No customer with this email: {email}" ) if len(customer.data) > 1: raise HTTPException( status_code=404, detail="More than one customer with this email, use the id instead", ) return RedirectResponse(session_url(customer.data[0].id, request), status_code=303) # TODO: Bypassing Ruff for now customer = constr(regex=r"cus_.*") @app.get("/id/{customer_id}", summary="Setup a new payment method by user id") def setup_new_method_by_id(customer_id: customer, request: Request): try: customer = Customer.retrieve(customer_id) except error.InvalidRequestError as exc: raise HTTPException(status_code=404, detail=exc.error.message) from exc return RedirectResponse(session_url(customer.id, request), status_code=303)
yezz123/stripe-template
14
Template for integrating stripe into your FastAPI application 💸
Python
yezz123
Yasser Tahiri
Yezz LLC.
app/settings/config.py
Python
from typing import List from pydantic import BaseSettings, HttpUrl class Settings(BaseSettings): HOST: HttpUrl = "http://127.0.0.1:8000" PAYMENT_METHOD_TYPES: List[str] = ["sepa_debit", "card"] API_DOC_URL: str = "/docs" API_OPENAPI_URL: str = "/openapi.json" API_REDOC_URL: str = "/redoc" API_TITLE: str = "Stripe Template" API_VERSION: str = "0.0.1" API_DESCRIPTION: str = ( "Template for integrating stripe into your FastAPI application" ) DEBUG: bool = False class Config: env_file = ".env" env_file_encoding = "utf-8"
yezz123/stripe-template
14
Template for integrating stripe into your FastAPI application 💸
Python
yezz123
Yasser Tahiri
Yezz LLC.
scripts/clean.sh
Shell
#!/bin/sh -e rm -f `find . -type f -name '*.py[co]' ` rm -f `find . -type f -name '*~' ` rm -f `find . -type f -name '.*~' ` rm -f `find . -type f -name .coverage` rm -f `find . -type f -name ".coverage.*"` rm -rf `find . -name __pycache__` rm -rf `find . -type d -name '*.egg-info' ` rm -rf `find . -type d -name 'pip-wheel-metadata' ` rm -rf `find . -type d -name .pytest_cache` rm -rf `find . -type d -name .ruff_cache` rm -rf `find . -type d -name .cache` rm -rf `find . -type d -name .mypy_cache` rm -rf `find . -type d -name htmlcov` rm -rf `find . -type d -name "*.egg-info"` rm -rf `find . -type d -name build` rm -rf `find . -type d -name dist`
yezz123/stripe-template
14
Template for integrating stripe into your FastAPI application 💸
Python
yezz123
Yasser Tahiri
Yezz LLC.
scripts/format.sh
Shell
#!/usr/bin/env bash set -e set -x pre-commit run --all-files --verbose --show-diff-on-failure
yezz123/stripe-template
14
Template for integrating stripe into your FastAPI application 💸
Python
yezz123
Yasser Tahiri
Yezz LLC.
scripts/test.sh
Shell
#!/usr/bin/env bash set -e set -x echo "ENV=${ENV}" export PYTHONPATH=. pytest --cov=app --cov=tests --cov-report=term-missing --cov-fail-under=80
yezz123/stripe-template
14
Template for integrating stripe into your FastAPI application 💸
Python
yezz123
Yasser Tahiri
Yezz LLC.
tests/test_health.py
Python
from fastapi.testclient import TestClient from app.main import app client = TestClient(app) def test_health() -> None: response = client.get("/health") assert response.status_code == 200 assert response.json() == "Pong!"
yezz123/stripe-template
14
Template for integrating stripe into your FastAPI application 💸
Python
yezz123
Yasser Tahiri
Yezz LLC.
tests/test_payment.py
Python
from unittest.mock import Mock, patch import pytest import stripe from fastapi.testclient import TestClient from app.main import app from app.router.v1.payment import session_url from app.settings.config import Settings config = Settings() client = TestClient(app) # Mock the stripe checkout session @pytest.fixture def mock_checkout_session(mocker): session = mocker.Mock() session.url = "https://checkout.stripe.com/session" session_create = mocker.Mock(return_value=session) mocker.patch.object(stripe.checkout.Session, "create", session_create) @pytest.fixture def mock_session_url(mocker): mocker.patch("app.router.v1.payment.session_url") # Test for the success page def test_success_page() -> None: response = client.get("/success") assert response.status_code == 200 assert response.text == '"Payment method registered with success ✅"' # Test for the cancel page def test_cancel_page() -> None: response = client.get("/cancel") assert response.status_code == 200 assert response.text == '"Operation canceled ❌"' # Test the session_url function def test_session_url(mock_checkout_session): customer_id = "cus_123456" request = {"url": {"scheme": "http", "netloc": "localhost:8000"}} url = session_url(customer_id, request) # noqa: F841 stripe.checkout.Session.create.assert_called_with( payment_method_types=config.PAYMENT_METHOD_TYPES, mode="setup", customer=customer_id, success_url="http://localhost:8000/success", cancel_url="http://localhost:8000/cancel", ) # Test the setup_new_method_by_email function @patch("app.router.v1.payment.setup_new_method_by_email") def test_setup_new_method_by_email(mock_setup_new_method_by_email: Mock) -> None: email = "test@example.com" mock_response = Mock() mock_response.status_code = 302 mock_response.email = email mock_setup_new_method_by_email.return_value = mock_response response = client.get(f"/email/{email}") # TODO: I notice that the status code is 404 # if you didn't create already a customer with the email assert response.status_code == 404 # Test the setup_new_method_by_id function @patch("app.router.v1.payment.setup_new_method_by_id") def test_setup_new_method_by_id(mock_setup_new_method_by_id: Mock) -> None: customer_id = "cus_123456" mock_response = Mock() mock_response.status_code = 302 mock_response.customer_id = customer_id mock_setup_new_method_by_id.return_value = mock_response response = client.get(f"/id/{customer_id}") # TODO: I notice that the status code is 404 # if you didn't create already a customer with the id assert response.status_code == 404
yezz123/stripe-template
14
Template for integrating stripe into your FastAPI application 💸
Python
yezz123
Yasser Tahiri
Yezz LLC.
tests/test_version.py
Python
import app def test_version() -> None: assert app.__version__ == "0.0.1"
yezz123/stripe-template
14
Template for integrating stripe into your FastAPI application 💸
Python
yezz123
Yasser Tahiri
Yezz LLC.
jsonlib.h
C/C++ Header
// // jsonlib.h // // Copyright (c) 2021 Yuji Hirose. All rights reserved. // MIT License // #pragma once #include <rapidjson/reader.h> #include <functional> #include <string> namespace jsonlib { using namespace rapidjson; struct Handlers { std::function<void()> Null; std::function<void(bool b)> Bool; std::function<void(int i)> Int; std::function<void(unsigned u)> Uint; std::function<void(int64_t i)> Int64; std::function<void(uint64_t i)> Uint64; std::function<void(double i)> Double; std::function<void(const char* str, SizeType length)> String; std::function<void()> StartObject; std::function<void(const char* str, SizeType length)> Key; std::function<void(SizeType memberCount)> EndObject; std::function<void()> StartArray; std::function<void(SizeType elementCount)> EndArray; }; inline bool parse(const char* json, const Handlers& functions) { struct ReaderHandler : public BaseReaderHandler<UTF8<>, ReaderHandler> { ReaderHandler(const Handlers& functions) : functions_(functions) {} bool Null() { if (functions_.Null) { functions_.Null(); } return true; } bool Bool(bool b) { if (functions_.Bool) { functions_.Bool(b); } return true; } bool Int(int i) { if (functions_.Int) { functions_.Int(i); } return true; } bool Uint(unsigned u) { if (functions_.Uint) { functions_.Uint(u); } return true; } bool Int64(int i) { if (functions_.Int64) { functions_.Int64(i); } return true; } bool Uint64(unsigned u) { if (functions_.Uint64) { functions_.Uint64(u); } return true; } bool Double(double d) { if (functions_.Double) { functions_.Double(d); } return true; } bool String(const char* str, SizeType length, bool /*copy*/) { if (functions_.String) { functions_.String(str, length); } return true; } bool StartObject() { if (functions_.StartObject) { functions_.StartObject(); } return true; } bool Key(const char* str, SizeType length, bool /*copy*/) { if (functions_.Key) { functions_.Key(str, length); } return true; } bool EndObject(SizeType memberCount) { if (functions_.EndObject) { functions_.EndObject(memberCount); } return true; } bool StartArray() { if (functions_.StartArray) { functions_.StartArray(); } return true; } bool EndArray(SizeType elementCount) { if (functions_.EndArray) { functions_.EndArray(elementCount); } return true; } const Handlers& functions_; std::string key_; }; StringStream ss(json); ReaderHandler handler(functions); Reader reader; return reader.Parse(ss, handler); } inline bool parse(const std::string& json, const Handlers& functions) { return parse(json.data(), functions); } }; // namespace jsonlib
yhirose/cpp-jsonlib
7
A C++17 single-file header-only library to wrap RapidJSON SAX interface
C++
yhirose
mmaplib.h
C/C++ Header
// // mmaplib.h // // Copyright (c) 2021 Yuji Hirose. All rights reserved. // MIT License // #ifndef _CPPMMAPLIB_MMAPLIB_H_ #define _CPPMMAPLIB_MMAPLIB_H_ #if defined(_WIN32) #include <windows.h> #else #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #endif #include <stdexcept> namespace mmaplib { class mmap { public: mmap(); mmap(const char *path); ~mmap(); bool open(const char *path); void close(); bool is_open() const; size_t size() const; const char *data() const; private: #if defined(_WIN32) HANDLE hFile_; HANDLE hMapping_; #else int fd_; #endif size_t size_; void *addr_; }; #if defined(_WIN32) #define MAP_FAILED NULL #endif inline mmap::mmap() #if defined(_WIN32) : hFile_(NULL), hMapping_(NULL) #else : fd_(-1) #endif , size_(0), addr_(MAP_FAILED) { } inline mmap::mmap(const char *path) #if defined(_WIN32) : hFile_(NULL), hMapping_(NULL) #else : fd_(-1) #endif , size_(0), addr_(MAP_FAILED) { open(path); } inline mmap::~mmap() { close(); } inline bool mmap::open(const char *path) { close(); #if defined(_WIN32) hFile_ = ::CreateFileA(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile_ == INVALID_HANDLE_VALUE) { return false; } size_ = ::GetFileSize(hFile_, NULL); hMapping_ = ::CreateFileMapping(hFile_, NULL, PAGE_READONLY, 0, 0, NULL); if (hMapping_ == NULL) { close(); return false; } addr_ = ::MapViewOfFile(hMapping_, FILE_MAP_READ, 0, 0, 0); #else fd_ = ::open(path, O_RDONLY); if (fd_ == -1) { return false; } struct stat sb; if (fstat(fd_, &sb) == -1) { close(); return false; } size_ = sb.st_size; addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0); #endif if (addr_ == MAP_FAILED) { close(); return false; } return true; } inline bool mmap::is_open() const { return addr_ != MAP_FAILED; } inline size_t mmap::size() const { return size_; } inline const char *mmap::data() const { return (const char *)addr_; } inline void mmap::close() { #if defined(_WIN32) if (addr_) { ::UnmapViewOfFile(addr_); addr_ = MAP_FAILED; } if (hMapping_) { ::CloseHandle(hMapping_); hMapping_ = NULL; } if (hFile_ != INVALID_HANDLE_VALUE) { ::CloseHandle(hFile_); hFile_ = INVALID_HANDLE_VALUE; } #else if (addr_ != MAP_FAILED) { munmap(addr_, size_); addr_ = MAP_FAILED; } if (fd_ != -1) { ::close(fd_); fd_ = -1; } #endif size_ = 0; } } // namespace mmaplib #endif
yhirose/cpp-mmaplib
72
A single file C++11 header-only memory mapped file library.
C++
yhirose
include/searchlib.h
C/C++ Header
// // searchlib.h // // Copyright (c) 2021 Yuji Hirose. All rights reserved. // MIT License // #pragma once #include <algorithm> #include <functional> #include <map> #include <optional> #include <string> #include <string_view> #include <unordered_map> #include <vector> namespace searchlib { //----------------------------------------------------------------------------- // Interface //----------------------------------------------------------------------------- class IPostings { public: virtual ~IPostings() = 0; virtual size_t size() const = 0; virtual size_t document_id(size_t index) const = 0; virtual size_t search_hit_count(size_t index) const = 0; virtual size_t term_position(size_t index, size_t search_hit_index) const = 0; virtual size_t term_length(size_t index, size_t search_hit_index) const = 0; virtual bool is_term_position(size_t index, size_t term_pos) const = 0; }; class IInvertedIndex { public: virtual ~IInvertedIndex() = 0; virtual size_t document_count() const = 0; virtual size_t document_term_count(size_t document_id) const = 0; virtual double average_document_term_count() const = 0; virtual bool term_exists(const std::u32string &str) const = 0; virtual size_t term_count(const std::u32string &str) const = 0; virtual size_t term_count(const std::u32string &str, size_t document_id) const = 0; virtual size_t df(const std::u32string &str) const = 0; virtual double tf(const std::u32string &str, size_t document_id) const = 0; virtual const IPostings &postings(const std::u32string &str) const = 0; }; using Normalizer = std::function<std::u32string(const std::u32string &str)>; template <typename T> using TextRangeList = std::unordered_map<size_t /*document_id*/, std::vector<T>>; template <typename T> using Tokenizer = std::function<void(Normalizer normalizer, std::function<void(const std::u32string &str, size_t term_pos, T text_range)> callback)>; template <typename T> class ITextRange { public: virtual ~ITextRange(){}; virtual T text_range(const IPostings &positions, size_t index, size_t search_hit_index) const = 0; }; template <typename T> class IInvertedIndexWithTextRange : public IInvertedIndex, ITextRange<T> { public: virtual ~IInvertedIndexWithTextRange(){}; }; //----------------------------------------------------------------------------- // Search //----------------------------------------------------------------------------- enum class Operation { Term, And, Adjacent, Or, Near }; struct Expression { Operation operation; std::u32string term_str; size_t near_operation_distance; std::vector<Expression> nodes; }; std::optional<Expression> parse_query(const IInvertedIndex &invidx, Normalizer normalizer, std::string_view query); std::shared_ptr<IPostings> perform_search(const IInvertedIndex &invidx, const Expression &expr); size_t term_count_score(const IInvertedIndex &invidx, const Expression &expr, const IPostings &postings, size_t index); double tf_idf_score(const IInvertedIndex &invidx, const Expression &expr, const IPostings &postings, size_t index); double bm25_score(const IInvertedIndex &invidx, const Expression &expr, const IPostings &postings, size_t index, double k1 = 1.2, double b = 0.75); //----------------------------------------------------------------------------- // Indexers //----------------------------------------------------------------------------- template <typename T> class IIndexer { public: virtual ~IIndexer(){}; virtual void index_document(size_t document_id, Tokenizer<T> tokenizer) = 0; }; template <typename T> inline std::shared_ptr<IInvertedIndexWithTextRange<T>> make_in_memory_index(Normalizer normalizer, std::function<void(IIndexer<T> &indexer)> callback); //----------------------------------------------------------------------------- // Text Ranges //----------------------------------------------------------------------------- struct TextRange { size_t position; size_t length; }; //----------------------------------------------------------------------------- // Tokenizers //----------------------------------------------------------------------------- class UTF8PlainTextTokenizer { public: explicit UTF8PlainTextTokenizer(std::string_view text); void operator()(Normalizer normalizer, std::function<void(const std::u32string &str, size_t term_pos, TextRange text_range)> callback); private: std::string_view text_; }; //----------------------------------------------------------------------------- TextRange text_range(const TextRangeList<TextRange> &text_range_list, const IPostings &positions, size_t index, size_t search_hit_index); class InMemoryInvertedIndexBase : public IInvertedIndex { public: size_t document_count() const override; size_t document_term_count(size_t document_id) const override; double average_document_term_count() const override; bool term_exists(const std::u32string &str) const override; size_t term_count(const std::u32string &str) const override; size_t term_count(const std::u32string &str, size_t document_id) const override; size_t df(const std::u32string &str) const override; double tf(const std::u32string &str, size_t document_id) const override; const IPostings &postings(const std::u32string &str) const override; class Postings : public IPostings { public: size_t size() const override; size_t document_id(size_t index) const override; size_t search_hit_count(size_t index) const override; size_t term_position(size_t index, size_t search_hit_index) const override; size_t term_length(size_t index, size_t search_hit_index) const override; bool is_term_position(size_t index, size_t term_pos) const override; void add_term_position(size_t document_id, size_t term_pos); private: using PositionsMap = std::map<size_t /*document_id*/, std::vector<size_t /*position*/>>; PositionsMap::const_iterator find_positions_map(size_t index) const; PositionsMap positions_map_; }; struct Document { size_t term_count; }; struct Term { std::u32string str; size_t term_count; Postings postings; }; std::unordered_map<size_t /*document_id*/, Document> documents_; std::unordered_map<std::u32string /*str*/, Term> term_dictionary_; }; template <typename T> class InMemoryInvertedIndex : public IInvertedIndexWithTextRange<T> { public: size_t document_count() const override { return base_.document_count(); } size_t document_term_count(size_t document_id) const override { return base_.document_term_count(document_id); } double average_document_term_count() const override { return base_.average_document_term_count(); } bool term_exists(const std::u32string &str) const override { return base_.term_exists(str); } size_t term_count(const std::u32string &str) const override { return base_.term_count(str); } size_t term_count(const std::u32string &str, size_t document_id) const override { return base_.term_count(str, document_id); } size_t df(const std::u32string &str) const override { return base_.df(str); } double tf(const std::u32string &str, size_t document_id) const override { return base_.tf(str, document_id); } const IPostings &postings(const std::u32string &str) const override { return base_.postings(str); } T text_range(const IPostings &positions, size_t index, size_t search_hit_index) const override { return searchlib::text_range(text_range_list_, positions, index, search_hit_index); } private: template <typename> friend class InMemoryIndexer; InMemoryInvertedIndexBase base_; TextRangeList<T> text_range_list_; }; template <typename T> class InMemoryIndexer : public IIndexer<T> { public: InMemoryIndexer(InMemoryInvertedIndex<T> &invidx, Normalizer normalizer) : invidx_(invidx), normalizer_(normalizer) {} void index_document(size_t document_id, Tokenizer<T> tokenizer) override { size_t term_count = 0; tokenizer(normalizer_, [&](const auto &str, auto term_pos, auto text_range) { if (invidx_.base_.term_dictionary_.find(str) == invidx_.base_.term_dictionary_.end()) { invidx_.base_.term_dictionary_[str] = {str, 0}; } auto &term = invidx_.base_.term_dictionary_.at(str); term.term_count++; term.postings.add_term_position(document_id, term_pos); invidx_.text_range_list_[document_id].push_back(std::move(text_range)); term_count++; }); invidx_.base_.documents_[document_id] = {term_count}; } private: InMemoryInvertedIndex<T> &invidx_; Normalizer normalizer_; }; template <typename T> inline std::shared_ptr<IInvertedIndexWithTextRange<T>> make_in_memory_index( Normalizer normalizer, std::function<void(IIndexer<T> &indexer)> callback) { auto invidx = new InMemoryInvertedIndex<T>(); InMemoryIndexer<T> indexer(*invidx, normalizer); callback(indexer); return std::shared_ptr<IInvertedIndexWithTextRange<T>>(invidx); } } // namespace searchlib
yhirose/cpp-searchlib
33
A C++17 full-text search engine library
C++
yhirose
scope/lib/flags.h
C/C++ Header
#ifndef FLAGS_H_ #define FLAGS_H_ #include <algorithm> #include <array> #include <optional> #include <sstream> #include <string> #include <string_view> #include <unordered_map> #include <vector> namespace flags { namespace detail { using argument_map = std::unordered_map<std::string_view, std::optional<std::string_view>>; // Non-destructively parses the argv tokens. // * If the token begins with a -, it will be considered an option. // * If the token does not begin with a -, it will be considered a value for the // previous option. If there was no previous option, it will be considered a // positional argument. struct parser { parser(const int argc, char** argv) { for (int i = 1; i < argc; ++i) { churn(argv[i]); } // If the last token was an option, it needs to be drained. flush(); } parser& operator=(const parser&) = delete; const argument_map& options() const { return options_; } const std::vector<std::string_view>& positional_arguments() const { return positional_arguments_; } private: // Advance the state machine for the current token. void churn(const std::string_view& item) { item.at(0) == '-' ? on_option(item) : on_value(item); } // Consumes the current option if there is one. void flush() { if (current_option_) on_value(); } void on_option(const std::string_view& option) { // Consume the current_option and reassign it to the new option while // removing all leading dashes. flush(); current_option_ = option; current_option_->remove_prefix(current_option_->find_first_not_of('-')); // Handle a packed argument (--arg_name=value). if (const auto delimiter = current_option_->find_first_of('='); delimiter != std::string_view::npos) { auto value = *current_option_; value.remove_prefix(delimiter + 1 /* skip '=' */); current_option_->remove_suffix(current_option_->size() - delimiter); on_value(value); } } void on_value(const std::optional<std::string_view>& value = std::nullopt) { // If there's not an option preceding the value, it's a positional argument. if (!current_option_) { if (value) positional_arguments_.emplace_back(*value); return; } // Consume the preceding option and assign its value. options_.emplace(*current_option_, value); current_option_.reset(); } std::optional<std::string_view> current_option_; argument_map options_; std::vector<std::string_view> positional_arguments_; }; // If a key exists, return an optional populated with its value. inline std::optional<std::string_view> get_value( const argument_map& options, const std::string_view& option) { if (const auto it = options.find(option); it != options.end()) { return it->second; } return std::nullopt; } // Coerces the string value of the given option into <T>. // If the value cannot be properly parsed or the key does not exist, returns // nullopt. template <class T> std::optional<T> get(const argument_map& options, const std::string_view& option) { if (const auto view = get_value(options, option)) { if (T value; std::istringstream(std::string(*view)) >> value) return value; } return std::nullopt; } // Since the values are already stored as strings, there's no need to use `>>`. template <> inline std::optional<std::string_view> get(const argument_map& options, const std::string_view& option) { return get_value(options, option); } template <> inline std::optional<std::string> get(const argument_map& options, const std::string_view& option) { if (const auto view = get<std::string_view>(options, option)) { return std::string(*view); } return std::nullopt; } // Special case for booleans: if the value is any of the below, the option will // be considered falsy. Otherwise, it will be considered truthy just for being // present. constexpr std::array<const char*, 5> falsities{{"0", "n", "no", "f", "false"}}; template <> inline std::optional<bool> get(const argument_map& options, const std::string_view& option) { if (const auto value = get_value(options, option)) { return std::none_of(falsities.begin(), falsities.end(), [&value](auto falsity) { return *value == falsity; }); } if (options.find(option) != options.end()) return true; return std::nullopt; } // Coerces the string value of the given positional index into <T>. // If the value cannot be properly parsed or the key does not exist, returns // nullopt. template <class T> std::optional<T> get(const std::vector<std::string_view>& positional_arguments, size_t positional_index) { if (positional_index < positional_arguments.size()) { if (T value; std::istringstream( std::string(positional_arguments[positional_index])) >> value) return value; } return std::nullopt; } // Since the values are already stored as strings, there's no need to use `>>`. template <> inline std::optional<std::string_view> get( const std::vector<std::string_view>& positional_arguments, size_t positional_index) { if (positional_index < positional_arguments.size()) { return positional_arguments[positional_index]; } return std::nullopt; } template <> inline std::optional<std::string> get( const std::vector<std::string_view>& positional_arguments, size_t positional_index) { if (positional_index < positional_arguments.size()) { return std::string(positional_arguments[positional_index]); } return std::nullopt; } } // namespace detail struct args { args(const int argc, char** argv) : parser_(argc, argv) {} template <class T> std::optional<T> get(const std::string_view& option) const { return detail::get<T>(parser_.options(), option); } template <class T> T get(const std::string_view& option, T&& default_value) const { return get<T>(option).value_or(default_value); } template <class T> std::optional<T> get(size_t positional_index) const { return detail::get<T>(parser_.positional_arguments(), positional_index); } template <class T> T get(size_t positional_index, T&& default_value) const { return get<T>(positional_index).value_or(default_value); } const std::vector<std::string_view>& positional() const { return parser_.positional_arguments(); } private: const detail::parser parser_; }; } // namespace flags #endif // FLAGS_H_
yhirose/cpp-searchlib
33
A C++17 full-text search engine library
C++
yhirose
scope/main.cpp
C++
#include <iostream> #include "lib/flags.h" void usage() { std::cout << R"(usage: scope [options] <command> [<args>] commends: index source INDEX_PATH - index documents search INDEX_PATH [query] - search in documents options: -v verbose output )"; } int error(int code) { usage(); return code; } int main(int argc, char **argv) { const flags::args args(argc, argv); if (args.positional().size() < 2) { return error(1); } auto opt_verbose = args.get<bool>("v", false); auto cmd = args.positional().at(0); const std::string index_path{args.positional().at(1)}; if (cmd == "index") { } else if (cmd == "search") { } else { return error(1); } return 0; }
yhirose/cpp-searchlib
33
A C++17 full-text search engine library
C++
yhirose
src/invertedindex.cpp
C++
// // invertedindex.cpp // // Copyright (c) 2021 Yuji Hirose. All rights reserved. // MIT License // #include "searchlib.h" #include "utils.h" namespace searchlib { IPostings::~IPostings() = default; IInvertedIndex::~IInvertedIndex() = default; //----------------------------------------------------------------------------- size_t InMemoryInvertedIndexBase::Postings::size() const { return positions_map_.size(); } size_t InMemoryInvertedIndexBase::Postings::document_id(size_t index) const { return find_positions_map(index)->first; } size_t InMemoryInvertedIndexBase::Postings::search_hit_count(size_t index) const { return find_positions_map(index)->second.size(); } size_t InMemoryInvertedIndexBase::Postings::term_position( size_t index, size_t search_hit_index) const { return find_positions_map(index)->second[search_hit_index]; } size_t InMemoryInvertedIndexBase::Postings::term_length( size_t index, size_t search_hit_index) const { return 1; } bool InMemoryInvertedIndexBase::Postings::is_term_position( size_t index, size_t term_pos) const { const auto &positions = find_positions_map(index)->second; return std::binary_search(positions.begin(), positions.end(), term_pos); } void InMemoryInvertedIndexBase::Postings::add_term_position(size_t document_id, size_t term_pos) { return positions_map_[document_id].push_back(term_pos); } InMemoryInvertedIndexBase::Postings::PositionsMap::const_iterator InMemoryInvertedIndexBase::Postings::find_positions_map(size_t index) const { assert(index < positions_map_.size()); // TODO: performance improvement with caching the last access value auto it = positions_map_.begin(); std::advance(it, index); return it; } //----------------------------------------------------------------------------- size_t find_postings_index_for_document_id_(const IPostings &p, size_t document_id) { // TODO: use binary search and cache... for (size_t i = 0; i < p.size(); i++) { if (p.document_id(i) == document_id) { return i; } } return p.size(); } size_t InMemoryInvertedIndexBase::document_count() const { return documents_.size(); } size_t InMemoryInvertedIndexBase::document_term_count(size_t document_id) const { return documents_.at(document_id).term_count; } double InMemoryInvertedIndexBase::average_document_term_count() const { auto buffs = std::vector<std::pair<size_t, size_t>>{{0.0, 0}}; for (const auto &[_, document] : documents_) { if (document.term_count < std::numeric_limits<size_t>::max() - buffs.back().first) { buffs.back().first += document.term_count; buffs.back().second += 1; } else { buffs.emplace_back(std::pair(document.term_count, 1)); } } double avg = 0.0; for (const auto [term_count, document_count] : buffs) { avg += static_cast<double>(term_count) / static_cast<double>(document_count); } return avg; } bool InMemoryInvertedIndexBase::term_exists(const std::u32string &str) const { return term_dictionary_.find(str) != term_dictionary_.end(); } size_t InMemoryInvertedIndexBase::term_count(const std::u32string &str) const { return term_dictionary_.at(str).term_count; } size_t InMemoryInvertedIndexBase::term_count(const std::u32string &str, size_t document_id) const { const auto &p = postings(str); auto i = find_postings_index_for_document_id_(p, document_id); if (i < p.size()) { return p.search_hit_count(i); } return 0; } size_t InMemoryInvertedIndexBase::df(const std::u32string &str) const { return postings(str).size(); } double InMemoryInvertedIndexBase::tf(const std::u32string &str, size_t document_id) const { const auto &p = postings(str); auto i = find_postings_index_for_document_id_(p, document_id); if (i < p.size()) { return static_cast<double>(p.search_hit_count(i)) / static_cast<double>(document_term_count(document_id)); } return 0.0; } const IPostings & InMemoryInvertedIndexBase::postings(const std::u32string &str) const { return term_dictionary_.at(str).postings; } } // namespace searchlib
yhirose/cpp-searchlib
33
A C++17 full-text search engine library
C++
yhirose
src/lib/peglib.h
C/C++ Header
// // peglib.h // // Copyright (c) 2020 Yuji Hirose. All rights reserved. // MIT License // #pragma once #include <algorithm> #include <any> #include <cassert> #include <cctype> #if __has_include(<charconv>) #include <charconv> #endif #include <cstring> #include <functional> #include <initializer_list> #include <iostream> #include <limits> #include <list> #include <map> #include <memory> #include <mutex> #include <set> #include <sstream> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #if !defined(__cplusplus) || __cplusplus < 201703L #error "Requires complete C++17 support" #endif namespace peg { /*----------------------------------------------------------------------------- * scope_exit *---------------------------------------------------------------------------*/ // This is based on // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189". template <typename EF> struct scope_exit { explicit scope_exit(EF &&f) : exit_function(std::move(f)), execute_on_destruction{true} {} scope_exit(scope_exit &&rhs) : exit_function(std::move(rhs.exit_function)), execute_on_destruction{rhs.execute_on_destruction} { rhs.release(); } ~scope_exit() { if (execute_on_destruction) { this->exit_function(); } } void release() { this->execute_on_destruction = false; } private: scope_exit(const scope_exit &) = delete; void operator=(const scope_exit &) = delete; scope_exit &operator=(scope_exit &&) = delete; EF exit_function; bool execute_on_destruction; }; /*----------------------------------------------------------------------------- * UTF8 functions *---------------------------------------------------------------------------*/ inline size_t codepoint_length(const char *s8, size_t l) { if (l) { auto b = static_cast<uint8_t>(s8[0]); if ((b & 0x80) == 0) { return 1; } else if ((b & 0xE0) == 0xC0 && l >= 2) { return 2; } else if ((b & 0xF0) == 0xE0 && l >= 3) { return 3; } else if ((b & 0xF8) == 0xF0 && l >= 4) { return 4; } } return 0; } inline size_t codepoint_count(const char *s8, size_t l) { size_t count = 0; for (size_t i = 0; i < l; i += codepoint_length(s8 + i, l - i)) { count++; } return count; } inline size_t encode_codepoint(char32_t cp, char *buff) { if (cp < 0x0080) { buff[0] = static_cast<char>(cp & 0x7F); return 1; } else if (cp < 0x0800) { buff[0] = static_cast<char>(0xC0 | ((cp >> 6) & 0x1F)); buff[1] = static_cast<char>(0x80 | (cp & 0x3F)); return 2; } else if (cp < 0xD800) { buff[0] = static_cast<char>(0xE0 | ((cp >> 12) & 0xF)); buff[1] = static_cast<char>(0x80 | ((cp >> 6) & 0x3F)); buff[2] = static_cast<char>(0x80 | (cp & 0x3F)); return 3; } else if (cp < 0xE000) { // D800 - DFFF is invalid... return 0; } else if (cp < 0x10000) { buff[0] = static_cast<char>(0xE0 | ((cp >> 12) & 0xF)); buff[1] = static_cast<char>(0x80 | ((cp >> 6) & 0x3F)); buff[2] = static_cast<char>(0x80 | (cp & 0x3F)); return 3; } else if (cp < 0x110000) { buff[0] = static_cast<char>(0xF0 | ((cp >> 18) & 0x7)); buff[1] = static_cast<char>(0x80 | ((cp >> 12) & 0x3F)); buff[2] = static_cast<char>(0x80 | ((cp >> 6) & 0x3F)); buff[3] = static_cast<char>(0x80 | (cp & 0x3F)); return 4; } return 0; } inline std::string encode_codepoint(char32_t cp) { char buff[4]; auto l = encode_codepoint(cp, buff); return std::string(buff, l); } inline bool decode_codepoint(const char *s8, size_t l, size_t &bytes, char32_t &cp) { if (l) { auto b = static_cast<uint8_t>(s8[0]); if ((b & 0x80) == 0) { bytes = 1; cp = b; return true; } else if ((b & 0xE0) == 0xC0) { if (l >= 2) { bytes = 2; cp = ((static_cast<char32_t>(s8[0] & 0x1F)) << 6) | (static_cast<char32_t>(s8[1] & 0x3F)); return true; } } else if ((b & 0xF0) == 0xE0) { if (l >= 3) { bytes = 3; cp = ((static_cast<char32_t>(s8[0] & 0x0F)) << 12) | ((static_cast<char32_t>(s8[1] & 0x3F)) << 6) | (static_cast<char32_t>(s8[2] & 0x3F)); return true; } } else if ((b & 0xF8) == 0xF0) { if (l >= 4) { bytes = 4; cp = ((static_cast<char32_t>(s8[0] & 0x07)) << 18) | ((static_cast<char32_t>(s8[1] & 0x3F)) << 12) | ((static_cast<char32_t>(s8[2] & 0x3F)) << 6) | (static_cast<char32_t>(s8[3] & 0x3F)); return true; } } } return false; } inline size_t decode_codepoint(const char *s8, size_t l, char32_t &cp) { size_t bytes; if (decode_codepoint(s8, l, bytes, cp)) { return bytes; } return 0; } inline char32_t decode_codepoint(const char *s8, size_t l) { char32_t cp = 0; decode_codepoint(s8, l, cp); return cp; } inline std::u32string decode(const char *s8, size_t l) { std::u32string out; size_t i = 0; while (i < l) { auto beg = i++; while (i < l && (s8[i] & 0xc0) == 0x80) { i++; } out += decode_codepoint(&s8[beg], (i - beg)); } return out; } template <typename T> const char *u8(const T *s) { return reinterpret_cast<const char *>(s); } /*----------------------------------------------------------------------------- * escape_characters *---------------------------------------------------------------------------*/ inline std::string escape_characters(const char *s, size_t n) { std::string str; for (size_t i = 0; i < n; i++) { auto c = s[i]; switch (c) { case '\n': str += "\\n"; break; case '\r': str += "\\r"; break; case '\t': str += "\\t"; break; default: str += c; break; } } return str; } inline std::string escape_characters(std::string_view sv) { return escape_characters(sv.data(), sv.size()); } /*----------------------------------------------------------------------------- * resolve_escape_sequence *---------------------------------------------------------------------------*/ inline bool is_hex(char c, int &v) { if ('0' <= c && c <= '9') { v = c - '0'; return true; } else if ('a' <= c && c <= 'f') { v = c - 'a' + 10; return true; } else if ('A' <= c && c <= 'F') { v = c - 'A' + 10; return true; } return false; } inline bool is_digit(char c, int &v) { if ('0' <= c && c <= '9') { v = c - '0'; return true; } return false; } inline std::pair<int, size_t> parse_hex_number(const char *s, size_t n, size_t i) { int ret = 0; int val; while (i < n && is_hex(s[i], val)) { ret = static_cast<int>(ret * 16 + val); i++; } return std::pair(ret, i); } inline std::pair<int, size_t> parse_octal_number(const char *s, size_t n, size_t i) { int ret = 0; int val; while (i < n && is_digit(s[i], val)) { ret = static_cast<int>(ret * 8 + val); i++; } return std::pair(ret, i); } inline std::string resolve_escape_sequence(const char *s, size_t n) { std::string r; r.reserve(n); size_t i = 0; while (i < n) { auto ch = s[i]; if (ch == '\\') { i++; if (i == n) { throw std::runtime_error("Invalid escape sequence..."); } switch (s[i]) { case 'n': r += '\n'; i++; break; case 'r': r += '\r'; i++; break; case 't': r += '\t'; i++; break; case '\'': r += '\''; i++; break; case '"': r += '"'; i++; break; case '[': r += '['; i++; break; case ']': r += ']'; i++; break; case '\\': r += '\\'; i++; break; case 'x': case 'u': { char32_t cp; std::tie(cp, i) = parse_hex_number(s, n, i + 1); r += encode_codepoint(cp); break; } default: { char32_t cp; std::tie(cp, i) = parse_octal_number(s, n, i); r += encode_codepoint(cp); break; } } } else { r += ch; i++; } } return r; } /*----------------------------------------------------------------------------- * token_to_number_ - This function should be removed eventually *---------------------------------------------------------------------------*/ template <typename T> T token_to_number_(std::string_view sv) { T n = 0; #if __has_include(<charconv>) if constexpr (!std::is_floating_point<T>::value) { std::from_chars(sv.data(), sv.data() + sv.size(), n); #else if constexpr (false) { #endif } else { auto s = std::string(sv); std::istringstream ss(s); ss >> n; } return n; } /*----------------------------------------------------------------------------- * Trie *---------------------------------------------------------------------------*/ class Trie { public: Trie() = default; Trie(const Trie &) = default; Trie(const std::vector<std::string> &items) { for (const auto &item : items) { for (size_t len = 1; len <= item.size(); len++) { auto last = len == item.size(); std::string_view sv(item.data(), len); auto it = dic_.find(sv); if (it == dic_.end()) { dic_.emplace(sv, Info{last, last}); } else if (last) { it->second.match = true; } else { it->second.done = false; } } } } size_t match(const char *text, size_t text_len) const { size_t match_len = 0; auto done = false; size_t len = 1; while (!done && len <= text_len) { std::string_view sv(text, len); auto it = dic_.find(sv); if (it == dic_.end()) { done = true; } else { if (it->second.match) { match_len = len; } if (it->second.done) { done = true; } } len += 1; } return match_len; } private: struct Info { bool done; bool match; }; // TODO: Use unordered_map when heterogeneous lookup is supported in C++20 // std::unordered_map<std::string, Info> dic_; std::map<std::string, Info, std::less<>> dic_; }; /*----------------------------------------------------------------------------- * PEG *---------------------------------------------------------------------------*/ /* * Line information utility function */ inline std::pair<size_t, size_t> line_info(const char *start, const char *cur) { auto p = start; auto col_ptr = p; auto no = 1; while (p < cur) { if (*p == '\n') { no++; col_ptr = p + 1; } p++; } auto col = codepoint_count(col_ptr, p - col_ptr) + 1; return std::pair(no, col); } /* * String tag */ inline constexpr unsigned int str2tag_core(const char *s, size_t l, unsigned int h) { return (l == 0) ? h : str2tag_core(s + 1, l - 1, (h * 33) ^ static_cast<unsigned char>(*s)); } inline constexpr unsigned int str2tag(std::string_view sv) { return str2tag_core(sv.data(), sv.size(), 0); } namespace udl { inline constexpr unsigned int operator"" _(const char *s, size_t l) { return str2tag_core(s, l, 0); } } // namespace udl /* * Semantic values */ struct SemanticValues : protected std::vector<std::any> { // Input text const char *path = nullptr; const char *ss = nullptr; std::function<const std::vector<size_t> &()> source_line_index; // Matched string std::string_view sv() const { return sv_; } // Definition name const std::string &name() const { return name_; } std::vector<unsigned int> tags; // Line number and column at which the matched string is std::pair<size_t, size_t> line_info() const { auto &idx = source_line_index(); auto cur = static_cast<size_t>(std::distance(ss, sv_.data())); auto it = std::lower_bound( idx.begin(), idx.end(), cur, [](size_t element, size_t value) { return element < value; }); auto id = static_cast<size_t>(std::distance(idx.begin(), it)); auto off = cur - (id == 0 ? 0 : idx[id - 1] + 1); return std::pair(id + 1, off + 1); } // Choice count size_t choice_count() const { return choice_count_; } // Choice number (0 based index) size_t choice() const { return choice_; } // Tokens std::vector<std::string_view> tokens; std::string_view token(size_t id = 0) const { if (tokens.empty()) { return sv_; } assert(id < tokens.size()); return tokens[id]; } // Token conversion std::string token_to_string(size_t id = 0) const { return std::string(token(id)); } template <typename T> T token_to_number() const { return token_to_number_<T>(token()); } // Transform the semantic value vector to another vector template <typename T> std::vector<T> transform(size_t beg = 0, size_t end = static_cast<size_t>(-1)) const { std::vector<T> r; end = (std::min)(end, size()); for (size_t i = beg; i < end; i++) { r.emplace_back(std::any_cast<T>((*this)[i])); } return r; } using std::vector<std::any>::iterator; using std::vector<std::any>::const_iterator; using std::vector<std::any>::size; using std::vector<std::any>::empty; using std::vector<std::any>::assign; using std::vector<std::any>::begin; using std::vector<std::any>::end; using std::vector<std::any>::rbegin; using std::vector<std::any>::rend; using std::vector<std::any>::operator[]; using std::vector<std::any>::at; using std::vector<std::any>::resize; using std::vector<std::any>::front; using std::vector<std::any>::back; using std::vector<std::any>::push_back; using std::vector<std::any>::pop_back; using std::vector<std::any>::insert; using std::vector<std::any>::erase; using std::vector<std::any>::clear; using std::vector<std::any>::swap; using std::vector<std::any>::emplace; using std::vector<std::any>::emplace_back; private: friend class Context; friend class Sequence; friend class PrioritizedChoice; friend class Holder; friend class PrecedenceClimbing; std::string_view sv_; size_t choice_count_ = 0; size_t choice_ = 0; std::string name_; }; /* * Semantic action */ template <typename F, typename... Args> std::any call(F fn, Args &&... args) { using R = decltype(fn(std::forward<Args>(args)...)); if constexpr (std::is_void<R>::value) { fn(std::forward<Args>(args)...); return std::any(); } else if constexpr (std::is_same<typename std::remove_cv<R>::type, std::any>::value) { return fn(std::forward<Args>(args)...); } else { return std::any(fn(std::forward<Args>(args)...)); } } template <typename T> struct argument_count : argument_count<decltype(&T::operator())> {}; template <typename R, typename... Args> struct argument_count<R (*)(Args...)> : std::integral_constant<unsigned, sizeof...(Args)> {}; template <typename R, typename C, typename... Args> struct argument_count<R (C::*)(Args...)> : std::integral_constant<unsigned, sizeof...(Args)> {}; template <typename R, typename C, typename... Args> struct argument_count<R (C::*)(Args...) const> : std::integral_constant<unsigned, sizeof...(Args)> {}; class Action { public: Action() = default; Action(Action &&rhs) = default; template <typename F> Action(F fn) : fn_(make_adaptor(fn)) {} template <typename F> void operator=(F fn) { fn_ = make_adaptor(fn); } Action &operator=(const Action &rhs) = default; operator bool() const { return bool(fn_); } std::any operator()(SemanticValues &vs, std::any &dt) const { return fn_(vs, dt); } private: using Fty = std::function<std::any(SemanticValues &vs, std::any &dt)>; template <typename F> Fty make_adaptor(F fn) { if constexpr (argument_count<F>::value == 1) { return [fn](auto &vs, auto & /*dt*/) { return call(fn, vs); }; } else { return [fn](auto &vs, auto &dt) { return call(fn, vs, dt); }; } } Fty fn_; }; /* * Semantic predicate */ // Note: 'parse_error' exception class should be be used in sematic action // handlers to reject the rule. class parse_error : public std::runtime_error { public: parse_error(const char *what_arg) : std::runtime_error(what_arg) {} }; /* * Parse result helper */ inline bool success(size_t len) { return len != static_cast<size_t>(-1); } inline bool fail(size_t len) { return len == static_cast<size_t>(-1); } /* * Log */ using Log = std::function<void(size_t, size_t, const std::string &)>; /* * ErrorInfo */ struct ErrorInfo { const char *error_pos = nullptr; std::vector<std::pair<const char *, bool>> expected_tokens; const char *message_pos = nullptr; std::string message; mutable const char *last_output_pos = nullptr; void clear() { error_pos = nullptr; expected_tokens.clear(); message_pos = nullptr; message.clear(); } void add(const char *token, bool is_literal) { for (const auto &[t, l] : expected_tokens) { if (t == token && l == is_literal) { return; } } expected_tokens.push_back(std::make_pair(token, is_literal)); } void output_log(const Log &log, const char *s, size_t n) const { if (message_pos) { if (message_pos > last_output_pos) { last_output_pos = message_pos; auto line = line_info(s, message_pos); std::string msg; if (auto unexpected_token = heuristic_error_token(s, n, message_pos); !unexpected_token.empty()) { msg = replace_all(message, "%t", unexpected_token); auto unexpected_char = unexpected_token.substr( 0, codepoint_length(unexpected_token.data(), unexpected_token.size())); msg = replace_all(msg, "%c", unexpected_char); } else { msg = message; } log(line.first, line.second, msg); } } else if (error_pos) { if (error_pos > last_output_pos) { last_output_pos = error_pos; auto line = line_info(s, error_pos); std::string msg; if (expected_tokens.empty()) { msg = "syntax error."; } else { msg = "syntax error"; // unexpected token if (auto unexpected_token = heuristic_error_token(s, n, error_pos); !unexpected_token.empty()) { msg += ", unexpected '"; msg += unexpected_token; msg += "'"; } auto first_item = true; size_t i = 0; while (i < expected_tokens.size()) { auto [token, is_literal] = expected_tokens[expected_tokens.size() - i - 1]; // Skip rules start with '_' if (!is_literal && token[0] != '_') { msg += (first_item ? ", expecting " : ", "); if (is_literal) { msg += "'"; msg += token; msg += "'"; } else { msg += "<"; msg += token; msg += ">"; } first_item = false; } i++; } msg += "."; } log(line.first, line.second, msg); } } } private: int cast_char(char c) const { return static_cast<unsigned char>(c); } std::string heuristic_error_token(const char *s, size_t n, const char *pos) const { auto len = n - std::distance(s, pos); if (len) { size_t i = 0; auto c = cast_char(pos[i++]); if (!std::ispunct(c) && !std::isspace(c)) { while (i < len && !std::ispunct(cast_char(pos[i])) && !std::isspace(cast_char(pos[i]))) { i++; } } size_t count = 8; size_t j = 0; while (count > 0 && j < i) { j += codepoint_length(&pos[j], i - j); count--; } return escape_characters(pos, j); } return std::string(); } std::string replace_all(std::string str, const std::string &from, const std::string &to) const { size_t pos = 0; while ((pos = str.find(from, pos)) != std::string::npos) { str.replace(pos, from.length(), to); pos += to.length(); } return str; } }; /* * Context */ class Context; class Ope; class Definition; using TracerEnter = std::function<void(const Ope &name, const char *s, size_t n, const SemanticValues &vs, const Context &c, const std::any &dt)>; using TracerLeave = std::function<void( const Ope &ope, const char *s, size_t n, const SemanticValues &vs, const Context &c, const std::any &dt, size_t)>; class Context { public: const char *path; const char *s; const size_t l; std::vector<size_t> source_line_index; ErrorInfo error_info; bool recovered = false; std::vector<std::shared_ptr<SemanticValues>> value_stack; size_t value_stack_size = 0; std::vector<Definition *> rule_stack; std::vector<std::vector<std::shared_ptr<Ope>>> args_stack; size_t in_token_boundary_count = 0; std::shared_ptr<Ope> whitespaceOpe; bool in_whitespace = false; std::shared_ptr<Ope> wordOpe; std::vector<std::map<std::string_view, std::string>> capture_scope_stack; size_t capture_scope_stack_size = 0; std::vector<bool> cut_stack; const size_t def_count; const bool enablePackratParsing; std::vector<bool> cache_registered; std::vector<bool> cache_success; std::map<std::pair<size_t, size_t>, std::tuple<size_t, std::any>> cache_values; TracerEnter tracer_enter; TracerLeave tracer_leave; Log log; Context(const char *path, const char *s, size_t l, size_t def_count, std::shared_ptr<Ope> whitespaceOpe, std::shared_ptr<Ope> wordOpe, bool enablePackratParsing, TracerEnter tracer_enter, TracerLeave tracer_leave, Log log) : path(path), s(s), l(l), whitespaceOpe(whitespaceOpe), wordOpe(wordOpe), def_count(def_count), enablePackratParsing(enablePackratParsing), cache_registered(enablePackratParsing ? def_count * (l + 1) : 0), cache_success(enablePackratParsing ? def_count * (l + 1) : 0), tracer_enter(tracer_enter), tracer_leave(tracer_leave), log(log) { args_stack.resize(1); push_capture_scope(); } ~Context() { assert(!value_stack_size); } Context(const Context &) = delete; Context(Context &&) = delete; Context operator=(const Context &) = delete; template <typename T> void packrat(const char *a_s, size_t def_id, size_t &len, std::any &val, T fn) { if (!enablePackratParsing) { fn(val); return; } auto col = a_s - s; auto idx = def_count * static_cast<size_t>(col) + def_id; if (cache_registered[idx]) { if (cache_success[idx]) { auto key = std::pair(col, def_id); std::tie(len, val) = cache_values[key]; return; } else { len = static_cast<size_t>(-1); return; } } else { fn(val); cache_registered[idx] = true; cache_success[idx] = success(len); if (success(len)) { auto key = std::pair(col, def_id); cache_values[key] = std::pair(len, val); } return; } } SemanticValues &push() { assert(value_stack_size <= value_stack.size()); if (value_stack_size == value_stack.size()) { value_stack.emplace_back(std::make_shared<SemanticValues>()); } else { auto &vs = *value_stack[value_stack_size]; if (!vs.empty()) { vs.clear(); if (!vs.tags.empty()) { vs.tags.clear(); } } vs.sv_ = std::string_view(); vs.choice_count_ = 0; vs.choice_ = 0; if (!vs.tokens.empty()) { vs.tokens.clear(); } } auto &vs = *value_stack[value_stack_size++]; vs.path = path; vs.ss = s; vs.source_line_index = [&]() -> const std::vector<size_t> & { if (source_line_index.empty()) { for (size_t pos = 0; pos < l; pos++) { if (s[pos] == '\n') { source_line_index.push_back(pos); } } source_line_index.push_back(l); } return source_line_index; }; return vs; } void pop() { value_stack_size--; } void push_args(std::vector<std::shared_ptr<Ope>> &&args) { args_stack.emplace_back(args); } void pop_args() { args_stack.pop_back(); } const std::vector<std::shared_ptr<Ope>> &top_args() const { return args_stack[args_stack.size() - 1]; } void push_capture_scope() { assert(capture_scope_stack_size <= capture_scope_stack.size()); if (capture_scope_stack_size == capture_scope_stack.size()) { capture_scope_stack.emplace_back( std::map<std::string_view, std::string>()); } else { auto &cs = capture_scope_stack[capture_scope_stack_size]; if (!cs.empty()) { cs.clear(); } } capture_scope_stack_size++; } void pop_capture_scope() { capture_scope_stack_size--; } void shift_capture_values() { assert(capture_scope_stack.size() >= 2); auto curr = &capture_scope_stack[capture_scope_stack_size - 1]; auto prev = curr - 1; for (const auto &[k, v] : *curr) { (*prev)[k] = v; } } void set_error_pos(const char *a_s, const char *literal = nullptr); // void trace_enter(const char *name, const char *a_s, size_t n, void trace_enter(const Ope &ope, const char *a_s, size_t n, SemanticValues &vs, std::any &dt) const; // void trace_leave(const char *name, const char *a_s, size_t n, void trace_leave(const Ope &ope, const char *a_s, size_t n, SemanticValues &vs, std::any &dt, size_t len) const; bool is_traceable(const Ope &ope) const; mutable size_t next_trace_id = 0; mutable std::list<size_t> trace_ids; }; /* * Parser operators */ class Ope { public: struct Visitor; virtual ~Ope() = default; size_t parse(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const; virtual size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const = 0; virtual void accept(Visitor &v) = 0; }; class Sequence : public Ope { public: template <typename... Args> Sequence(const Args &... args) : opes_{static_cast<std::shared_ptr<Ope>>(args)...} {} Sequence(const std::vector<std::shared_ptr<Ope>> &opes) : opes_(opes) {} Sequence(std::vector<std::shared_ptr<Ope>> &&opes) : opes_(opes) {} size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const override { auto &chldsv = c.push(); auto pop_se = scope_exit([&]() { c.pop(); }); size_t i = 0; for (const auto &ope : opes_) { const auto &rule = *ope; auto len = rule.parse(s + i, n - i, chldsv, c, dt); if (fail(len)) { return len; } i += len; } if (!chldsv.empty()) { for (size_t j = 0; j < chldsv.size(); j++) { vs.emplace_back(std::move(chldsv[j])); } } if (!chldsv.tags.empty()) { for (size_t j = 0; j < chldsv.tags.size(); j++) { vs.tags.emplace_back(std::move(chldsv.tags[j])); } } vs.sv_ = chldsv.sv_; if (!chldsv.tokens.empty()) { for (size_t j = 0; j < chldsv.tokens.size(); j++) { vs.tokens.emplace_back(std::move(chldsv.tokens[j])); } } return i; } void accept(Visitor &v) override; std::vector<std::shared_ptr<Ope>> opes_; }; class PrioritizedChoice : public Ope { public: template <typename... Args> PrioritizedChoice(bool for_label, const Args &... args) : opes_{static_cast<std::shared_ptr<Ope>>(args)...}, for_label_(for_label) {} PrioritizedChoice(const std::vector<std::shared_ptr<Ope>> &opes) : opes_(opes) {} PrioritizedChoice(std::vector<std::shared_ptr<Ope>> &&opes) : opes_(opes) {} size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const override { size_t len = static_cast<size_t>(-1); if (!for_label_) { c.cut_stack.push_back(false); } size_t id = 0; for (const auto &ope : opes_) { if (!c.cut_stack.empty()) { c.cut_stack.back() = false; } auto &chldsv = c.push(); c.push_capture_scope(); auto se = scope_exit([&]() { c.pop(); c.pop_capture_scope(); }); len = ope->parse(s, n, chldsv, c, dt); if (success(len)) { if (!chldsv.empty()) { for (size_t i = 0; i < chldsv.size(); i++) { vs.emplace_back(std::move(chldsv[i])); } } if (!chldsv.tags.empty()) { for (size_t i = 0; i < chldsv.tags.size(); i++) { vs.tags.emplace_back(std::move(chldsv.tags[i])); } } vs.sv_ = chldsv.sv_; vs.choice_count_ = opes_.size(); vs.choice_ = id; if (!chldsv.tokens.empty()) { for (size_t i = 0; i < chldsv.tokens.size(); i++) { vs.tokens.emplace_back(std::move(chldsv.tokens[i])); } } c.shift_capture_values(); break; } else if (!c.cut_stack.empty() && c.cut_stack.back()) { break; } id++; } if (!for_label_) { c.cut_stack.pop_back(); } return len; } void accept(Visitor &v) override; size_t size() const { return opes_.size(); } std::vector<std::shared_ptr<Ope>> opes_; bool for_label_ = false; }; class Repetition : public Ope { public: Repetition(const std::shared_ptr<Ope> &ope, size_t min, size_t max) : ope_(ope), min_(min), max_(max) {} size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const override { size_t count = 0; size_t i = 0; while (count < min_) { c.push_capture_scope(); auto se = scope_exit([&]() { c.pop_capture_scope(); }); const auto &rule = *ope_; auto len = rule.parse(s + i, n - i, vs, c, dt); if (success(len)) { c.shift_capture_values(); } else { return len; } i += len; count++; } while (n - i > 0 && count < max_) { c.push_capture_scope(); auto se = scope_exit([&]() { c.pop_capture_scope(); }); auto save_sv_size = vs.size(); auto save_tok_size = vs.tokens.size(); const auto &rule = *ope_; auto len = rule.parse(s + i, n - i, vs, c, dt); if (success(len)) { c.shift_capture_values(); } else { if (vs.size() != save_sv_size) { vs.erase(vs.begin() + static_cast<std::ptrdiff_t>(save_sv_size)); vs.tags.erase(vs.tags.begin() + static_cast<std::ptrdiff_t>(save_sv_size)); } if (vs.tokens.size() != save_tok_size) { vs.tokens.erase(vs.tokens.begin() + static_cast<std::ptrdiff_t>(save_tok_size)); } break; } i += len; count++; } return i; } void accept(Visitor &v) override; bool is_zom() const { return min_ == 0 && max_ == std::numeric_limits<size_t>::max(); } static std::shared_ptr<Repetition> zom(const std::shared_ptr<Ope> &ope) { return std::make_shared<Repetition>(ope, 0, std::numeric_limits<size_t>::max()); } static std::shared_ptr<Repetition> oom(const std::shared_ptr<Ope> &ope) { return std::make_shared<Repetition>(ope, 1, std::numeric_limits<size_t>::max()); } static std::shared_ptr<Repetition> opt(const std::shared_ptr<Ope> &ope) { return std::make_shared<Repetition>(ope, 0, 1); } std::shared_ptr<Ope> ope_; size_t min_; size_t max_; }; class AndPredicate : public Ope { public: AndPredicate(const std::shared_ptr<Ope> &ope) : ope_(ope) {} size_t parse_core(const char *s, size_t n, SemanticValues & /*vs*/, Context &c, std::any &dt) const override { auto &chldsv = c.push(); c.push_capture_scope(); auto se = scope_exit([&]() { c.pop(); c.pop_capture_scope(); }); const auto &rule = *ope_; auto len = rule.parse(s, n, chldsv, c, dt); if (success(len)) { return 0; } else { return len; } } void accept(Visitor &v) override; std::shared_ptr<Ope> ope_; }; class NotPredicate : public Ope { public: NotPredicate(const std::shared_ptr<Ope> &ope) : ope_(ope) {} size_t parse_core(const char *s, size_t n, SemanticValues & /*vs*/, Context &c, std::any &dt) const override { auto &chldsv = c.push(); c.push_capture_scope(); auto se = scope_exit([&]() { c.pop(); c.pop_capture_scope(); }); auto len = ope_->parse(s, n, chldsv, c, dt); if (success(len)) { c.set_error_pos(s); return static_cast<size_t>(-1); } else { return 0; } } void accept(Visitor &v) override; std::shared_ptr<Ope> ope_; }; class Dictionary : public Ope, public std::enable_shared_from_this<Dictionary> { public: Dictionary(const std::vector<std::string> &v) : trie_(v) {} size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const override; void accept(Visitor &v) override; Trie trie_; }; class LiteralString : public Ope, public std::enable_shared_from_this<LiteralString> { public: LiteralString(std::string &&s, bool ignore_case) : lit_(s), ignore_case_(ignore_case), is_word_(false) {} LiteralString(const std::string &s, bool ignore_case) : lit_(s), ignore_case_(ignore_case), is_word_(false) {} size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const override; void accept(Visitor &v) override; std::string lit_; bool ignore_case_; mutable std::once_flag init_is_word_; mutable bool is_word_; }; class CharacterClass : public Ope, public std::enable_shared_from_this<CharacterClass> { public: CharacterClass(const std::string &s, bool negated) : negated_(negated) { auto chars = decode(s.data(), s.length()); auto i = 0u; while (i < chars.size()) { if (i + 2 < chars.size() && chars[i + 1] == '-') { auto cp1 = chars[i]; auto cp2 = chars[i + 2]; ranges_.emplace_back(std::pair(cp1, cp2)); i += 3; } else { auto cp = chars[i]; ranges_.emplace_back(std::pair(cp, cp)); i += 1; } } assert(!ranges_.empty()); } CharacterClass(const std::vector<std::pair<char32_t, char32_t>> &ranges, bool negated) : ranges_(ranges), negated_(negated) { assert(!ranges_.empty()); } size_t parse_core(const char *s, size_t n, SemanticValues & /*vs*/, Context &c, std::any & /*dt*/) const override { if (n < 1) { c.set_error_pos(s); return static_cast<size_t>(-1); } char32_t cp = 0; auto len = decode_codepoint(s, n, cp); for (const auto &range : ranges_) { if (range.first <= cp && cp <= range.second) { if (negated_) { c.set_error_pos(s); return static_cast<size_t>(-1); } else { return len; } } } if (negated_) { return len; } else { c.set_error_pos(s); return static_cast<size_t>(-1); } } void accept(Visitor &v) override; std::vector<std::pair<char32_t, char32_t>> ranges_; bool negated_; }; class Character : public Ope, public std::enable_shared_from_this<Character> { public: Character(char ch) : ch_(ch) {} size_t parse_core(const char *s, size_t n, SemanticValues & /*vs*/, Context &c, std::any & /*dt*/) const override { if (n < 1 || s[0] != ch_) { c.set_error_pos(s); return static_cast<size_t>(-1); } return 1; } void accept(Visitor &v) override; char ch_; }; class AnyCharacter : public Ope, public std::enable_shared_from_this<AnyCharacter> { public: size_t parse_core(const char *s, size_t n, SemanticValues & /*vs*/, Context &c, std::any & /*dt*/) const override { auto len = codepoint_length(s, n); if (len < 1) { c.set_error_pos(s); return static_cast<size_t>(-1); } return len; } void accept(Visitor &v) override; }; class CaptureScope : public Ope { public: CaptureScope(const std::shared_ptr<Ope> &ope) : ope_(ope) {} size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const override { c.push_capture_scope(); auto se = scope_exit([&]() { c.pop_capture_scope(); }); const auto &rule = *ope_; auto len = rule.parse(s, n, vs, c, dt); return len; } void accept(Visitor &v) override; std::shared_ptr<Ope> ope_; }; class Capture : public Ope { public: using MatchAction = std::function<void(const char *s, size_t n, Context &c)>; Capture(const std::shared_ptr<Ope> &ope, MatchAction ma) : ope_(ope), match_action_(ma) {} size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const override { const auto &rule = *ope_; auto len = rule.parse(s, n, vs, c, dt); if (success(len) && match_action_) { match_action_(s, len, c); } return len; } void accept(Visitor &v) override; std::shared_ptr<Ope> ope_; MatchAction match_action_; }; class TokenBoundary : public Ope { public: TokenBoundary(const std::shared_ptr<Ope> &ope) : ope_(ope) {} size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const override; void accept(Visitor &v) override; std::shared_ptr<Ope> ope_; }; class Ignore : public Ope { public: Ignore(const std::shared_ptr<Ope> &ope) : ope_(ope) {} size_t parse_core(const char *s, size_t n, SemanticValues & /*vs*/, Context &c, std::any &dt) const override { const auto &rule = *ope_; auto &chldsv = c.push(); auto se = scope_exit([&]() { c.pop(); }); return rule.parse(s, n, chldsv, c, dt); } void accept(Visitor &v) override; std::shared_ptr<Ope> ope_; }; using Parser = std::function<size_t(const char *s, size_t n, SemanticValues &vs, std::any &dt)>; class User : public Ope { public: User(Parser fn) : fn_(fn) {} size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context & /*c*/, std::any &dt) const override { assert(fn_); return fn_(s, n, vs, dt); } void accept(Visitor &v) override; std::function<size_t(const char *s, size_t n, SemanticValues &vs, std::any &dt)> fn_; }; class WeakHolder : public Ope { public: WeakHolder(const std::shared_ptr<Ope> &ope) : weak_(ope) {} size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const override { auto ope = weak_.lock(); assert(ope); const auto &rule = *ope; return rule.parse(s, n, vs, c, dt); } void accept(Visitor &v) override; std::weak_ptr<Ope> weak_; }; class Holder : public Ope { public: Holder(Definition *outer) : outer_(outer) {} size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const override; void accept(Visitor &v) override; std::any reduce(SemanticValues &vs, std::any &dt) const; const char *trace_name() const; std::shared_ptr<Ope> ope_; Definition *outer_; mutable std::string trace_name_; friend class Definition; }; using Grammar = std::unordered_map<std::string, Definition>; class Reference : public Ope, public std::enable_shared_from_this<Reference> { public: Reference(const Grammar &grammar, const std::string &name, const char *s, bool is_macro, const std::vector<std::shared_ptr<Ope>> &args) : grammar_(grammar), name_(name), s_(s), is_macro_(is_macro), args_(args), rule_(nullptr), iarg_(0) {} size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const override; void accept(Visitor &v) override; std::shared_ptr<Ope> get_core_operator() const; const Grammar &grammar_; const std::string name_; const char *s_; const bool is_macro_; const std::vector<std::shared_ptr<Ope>> args_; Definition *rule_; size_t iarg_; }; class Whitespace : public Ope { public: Whitespace(const std::shared_ptr<Ope> &ope) : ope_(ope) {} size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const override { if (c.in_whitespace) { return 0; } c.in_whitespace = true; auto se = scope_exit([&]() { c.in_whitespace = false; }); const auto &rule = *ope_; return rule.parse(s, n, vs, c, dt); } void accept(Visitor &v) override; std::shared_ptr<Ope> ope_; }; class BackReference : public Ope { public: BackReference(std::string &&name) : name_(name) {} BackReference(const std::string &name) : name_(name) {} size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const override; void accept(Visitor &v) override; std::string name_; }; class PrecedenceClimbing : public Ope { public: using BinOpeInfo = std::map<std::string_view, std::pair<size_t, char>>; PrecedenceClimbing(const std::shared_ptr<Ope> &atom, const std::shared_ptr<Ope> &binop, const BinOpeInfo &info, const Definition &rule) : atom_(atom), binop_(binop), info_(info), rule_(rule) {} size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const override { return parse_expression(s, n, vs, c, dt, 0); } void accept(Visitor &v) override; std::shared_ptr<Ope> atom_; std::shared_ptr<Ope> binop_; BinOpeInfo info_; const Definition &rule_; private: size_t parse_expression(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt, size_t min_prec) const; Definition &get_reference_for_binop(Context &c) const; }; class Recovery : public Ope { public: Recovery(const std::shared_ptr<Ope> &ope) : ope_(ope) {} size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const override; void accept(Visitor &v) override; std::shared_ptr<Ope> ope_; }; class Cut : public Ope, public std::enable_shared_from_this<Cut> { public: size_t parse_core(const char * /*s*/, size_t /*n*/, SemanticValues & /*vs*/, Context &c, std::any & /*dt*/) const override { c.cut_stack.back() = true; return 0; } void accept(Visitor &v) override; }; /* * Factories */ template <typename... Args> std::shared_ptr<Ope> seq(Args &&... args) { return std::make_shared<Sequence>(static_cast<std::shared_ptr<Ope>>(args)...); } template <typename... Args> std::shared_ptr<Ope> cho(Args &&... args) { return std::make_shared<PrioritizedChoice>( false, static_cast<std::shared_ptr<Ope>>(args)...); } template <typename... Args> std::shared_ptr<Ope> cho4label_(Args &&... args) { return std::make_shared<PrioritizedChoice>( true, static_cast<std::shared_ptr<Ope>>(args)...); } inline std::shared_ptr<Ope> zom(const std::shared_ptr<Ope> &ope) { return Repetition::zom(ope); } inline std::shared_ptr<Ope> oom(const std::shared_ptr<Ope> &ope) { return Repetition::oom(ope); } inline std::shared_ptr<Ope> opt(const std::shared_ptr<Ope> &ope) { return Repetition::opt(ope); } inline std::shared_ptr<Ope> rep(const std::shared_ptr<Ope> &ope, size_t min, size_t max) { return std::make_shared<Repetition>(ope, min, max); } inline std::shared_ptr<Ope> apd(const std::shared_ptr<Ope> &ope) { return std::make_shared<AndPredicate>(ope); } inline std::shared_ptr<Ope> npd(const std::shared_ptr<Ope> &ope) { return std::make_shared<NotPredicate>(ope); } inline std::shared_ptr<Ope> dic(const std::vector<std::string> &v) { return std::make_shared<Dictionary>(v); } inline std::shared_ptr<Ope> lit(std::string &&s) { return std::make_shared<LiteralString>(s, false); } inline std::shared_ptr<Ope> liti(std::string &&s) { return std::make_shared<LiteralString>(s, true); } inline std::shared_ptr<Ope> cls(const std::string &s) { return std::make_shared<CharacterClass>(s, false); } inline std::shared_ptr<Ope> cls(const std::vector<std::pair<char32_t, char32_t>> &ranges) { return std::make_shared<CharacterClass>(ranges, false); } inline std::shared_ptr<Ope> ncls(const std::string &s) { return std::make_shared<CharacterClass>(s, true); } inline std::shared_ptr<Ope> ncls(const std::vector<std::pair<char32_t, char32_t>> &ranges) { return std::make_shared<CharacterClass>(ranges, true); } inline std::shared_ptr<Ope> chr(char dt) { return std::make_shared<Character>(dt); } inline std::shared_ptr<Ope> dot() { return std::make_shared<AnyCharacter>(); } inline std::shared_ptr<Ope> csc(const std::shared_ptr<Ope> &ope) { return std::make_shared<CaptureScope>(ope); } inline std::shared_ptr<Ope> cap(const std::shared_ptr<Ope> &ope, Capture::MatchAction ma) { return std::make_shared<Capture>(ope, ma); } inline std::shared_ptr<Ope> tok(const std::shared_ptr<Ope> &ope) { return std::make_shared<TokenBoundary>(ope); } inline std::shared_ptr<Ope> ign(const std::shared_ptr<Ope> &ope) { return std::make_shared<Ignore>(ope); } inline std::shared_ptr<Ope> usr(std::function<size_t(const char *s, size_t n, SemanticValues &vs, std::any &dt)> fn) { return std::make_shared<User>(fn); } inline std::shared_ptr<Ope> ref(const Grammar &grammar, const std::string &name, const char *s, bool is_macro, const std::vector<std::shared_ptr<Ope>> &args) { return std::make_shared<Reference>(grammar, name, s, is_macro, args); } inline std::shared_ptr<Ope> wsp(const std::shared_ptr<Ope> &ope) { return std::make_shared<Whitespace>(std::make_shared<Ignore>(ope)); } inline std::shared_ptr<Ope> bkr(std::string &&name) { return std::make_shared<BackReference>(name); } inline std::shared_ptr<Ope> pre(const std::shared_ptr<Ope> &atom, const std::shared_ptr<Ope> &binop, const PrecedenceClimbing::BinOpeInfo &info, const Definition &rule) { return std::make_shared<PrecedenceClimbing>(atom, binop, info, rule); } inline std::shared_ptr<Ope> rec(const std::shared_ptr<Ope> &ope) { return std::make_shared<Recovery>(ope); } inline std::shared_ptr<Ope> cut() { return std::make_shared<Cut>(); } /* * Visitor */ struct Ope::Visitor { virtual ~Visitor() {} virtual void visit(Sequence &) {} virtual void visit(PrioritizedChoice &) {} virtual void visit(Repetition &) {} virtual void visit(AndPredicate &) {} virtual void visit(NotPredicate &) {} virtual void visit(Dictionary &) {} virtual void visit(LiteralString &) {} virtual void visit(CharacterClass &) {} virtual void visit(Character &) {} virtual void visit(AnyCharacter &) {} virtual void visit(CaptureScope &) {} virtual void visit(Capture &) {} virtual void visit(TokenBoundary &) {} virtual void visit(Ignore &) {} virtual void visit(User &) {} virtual void visit(WeakHolder &) {} virtual void visit(Holder &) {} virtual void visit(Reference &) {} virtual void visit(Whitespace &) {} virtual void visit(BackReference &) {} virtual void visit(PrecedenceClimbing &) {} virtual void visit(Recovery &) {} virtual void visit(Cut &) {} }; struct IsReference : public Ope::Visitor { void visit(Reference &) override { is_reference_ = true; } static bool check(Ope &ope) { IsReference vis; ope.accept(vis); return vis.is_reference_; } private: bool is_reference_ = false; }; struct TraceOpeName : public Ope::Visitor { void visit(Sequence &) override { name_ = "Sequence"; } void visit(PrioritizedChoice &) override { name_ = "PrioritizedChoice"; } void visit(Repetition &) override { name_ = "Repetition"; } void visit(AndPredicate &) override { name_ = "AndPredicate"; } void visit(NotPredicate &) override { name_ = "NotPredicate"; } void visit(Dictionary &) override { name_ = "Dictionary"; } void visit(LiteralString &) override { name_ = "LiteralString"; } void visit(CharacterClass &) override { name_ = "CharacterClass"; } void visit(Character &) override { name_ = "Character"; } void visit(AnyCharacter &) override { name_ = "AnyCharacter"; } void visit(CaptureScope &) override { name_ = "CaptureScope"; } void visit(Capture &) override { name_ = "Capture"; } void visit(TokenBoundary &) override { name_ = "TokenBoundary"; } void visit(Ignore &) override { name_ = "Ignore"; } void visit(User &) override { name_ = "User"; } void visit(WeakHolder &) override { name_ = "WeakHolder"; } void visit(Holder &ope) override { name_ = ope.trace_name(); } void visit(Reference &) override { name_ = "Reference"; } void visit(Whitespace &) override { name_ = "Whitespace"; } void visit(BackReference &) override { name_ = "BackReference"; } void visit(PrecedenceClimbing &) override { name_ = "PrecedenceClimbing"; } void visit(Recovery &) override { name_ = "Recovery"; } void visit(Cut &) override { name_ = "Cut"; } static std::string get(Ope &ope) { TraceOpeName vis; ope.accept(vis); return vis.name_; } private: const char *name_ = nullptr; }; struct AssignIDToDefinition : public Ope::Visitor { void visit(Sequence &ope) override { for (auto op : ope.opes_) { op->accept(*this); } } void visit(PrioritizedChoice &ope) override { for (auto op : ope.opes_) { op->accept(*this); } } void visit(Repetition &ope) override { ope.ope_->accept(*this); } void visit(AndPredicate &ope) override { ope.ope_->accept(*this); } void visit(NotPredicate &ope) override { ope.ope_->accept(*this); } void visit(CaptureScope &ope) override { ope.ope_->accept(*this); } void visit(Capture &ope) override { ope.ope_->accept(*this); } void visit(TokenBoundary &ope) override { ope.ope_->accept(*this); } void visit(Ignore &ope) override { ope.ope_->accept(*this); } void visit(WeakHolder &ope) override { ope.weak_.lock()->accept(*this); } void visit(Holder &ope) override; void visit(Reference &ope) override; void visit(Whitespace &ope) override { ope.ope_->accept(*this); } void visit(PrecedenceClimbing &ope) override; void visit(Recovery &ope) override { ope.ope_->accept(*this); } std::unordered_map<void *, size_t> ids; }; struct IsLiteralToken : public Ope::Visitor { void visit(PrioritizedChoice &ope) override { for (auto op : ope.opes_) { if (!IsLiteralToken::check(*op)) { return; } } result_ = true; } void visit(Dictionary &) override { result_ = true; } void visit(LiteralString &) override { result_ = true; } static bool check(Ope &ope) { IsLiteralToken vis; ope.accept(vis); return vis.result_; } private: bool result_ = false; }; struct TokenChecker : public Ope::Visitor { void visit(Sequence &ope) override { for (auto op : ope.opes_) { op->accept(*this); } } void visit(PrioritizedChoice &ope) override { for (auto op : ope.opes_) { op->accept(*this); } } void visit(Repetition &ope) override { ope.ope_->accept(*this); } void visit(CaptureScope &ope) override { ope.ope_->accept(*this); } void visit(Capture &ope) override { ope.ope_->accept(*this); } void visit(TokenBoundary &) override { has_token_boundary_ = true; } void visit(Ignore &ope) override { ope.ope_->accept(*this); } void visit(WeakHolder &) override { has_rule_ = true; } void visit(Holder &ope) override { ope.ope_->accept(*this); } void visit(Reference &ope) override; void visit(Whitespace &ope) override { ope.ope_->accept(*this); } void visit(PrecedenceClimbing &ope) override { ope.atom_->accept(*this); } void visit(Recovery &ope) override { ope.ope_->accept(*this); } static bool is_token(Ope &ope) { if (IsLiteralToken::check(ope)) { return true; } TokenChecker vis; ope.accept(vis); return vis.has_token_boundary_ || !vis.has_rule_; } private: bool has_token_boundary_ = false; bool has_rule_ = false; }; struct FindLiteralToken : public Ope::Visitor { void visit(LiteralString &ope) override { token_ = ope.lit_.c_str(); } void visit(TokenBoundary &ope) override { ope.ope_->accept(*this); } void visit(Ignore &ope) override { ope.ope_->accept(*this); } void visit(Reference &ope) override; void visit(Recovery &ope) override { ope.ope_->accept(*this); } static const char *token(Ope &ope) { FindLiteralToken vis; ope.accept(vis); return vis.token_; } private: const char *token_ = nullptr; }; struct DetectLeftRecursion : public Ope::Visitor { DetectLeftRecursion(const std::string &name) : name_(name) {} void visit(Sequence &ope) override { for (auto op : ope.opes_) { op->accept(*this); if (done_) { break; } else if (error_s) { done_ = true; break; } } } void visit(PrioritizedChoice &ope) override { for (auto op : ope.opes_) { op->accept(*this); if (error_s) { done_ = true; break; } } } void visit(Repetition &ope) override { ope.ope_->accept(*this); done_ = ope.min_ > 0; } void visit(AndPredicate &ope) override { ope.ope_->accept(*this); done_ = false; } void visit(NotPredicate &ope) override { ope.ope_->accept(*this); done_ = false; } void visit(Dictionary &) override { done_ = true; } void visit(LiteralString &ope) override { done_ = !ope.lit_.empty(); } void visit(CharacterClass &) override { done_ = true; } void visit(Character &) override { done_ = true; } void visit(AnyCharacter &) override { done_ = true; } void visit(CaptureScope &ope) override { ope.ope_->accept(*this); } void visit(Capture &ope) override { ope.ope_->accept(*this); } void visit(TokenBoundary &ope) override { ope.ope_->accept(*this); } void visit(Ignore &ope) override { ope.ope_->accept(*this); } void visit(User &) override { done_ = true; } void visit(WeakHolder &ope) override { ope.weak_.lock()->accept(*this); } void visit(Holder &ope) override { ope.ope_->accept(*this); } void visit(Reference &ope) override; void visit(Whitespace &ope) override { ope.ope_->accept(*this); } void visit(BackReference &) override { done_ = true; } void visit(PrecedenceClimbing &ope) override { ope.atom_->accept(*this); } void visit(Recovery &ope) override { ope.ope_->accept(*this); } void visit(Cut &) override { done_ = true; } const char *error_s = nullptr; private: std::string name_; std::set<std::string> refs_; bool done_ = false; }; struct HasEmptyElement : public Ope::Visitor { HasEmptyElement(std::list<std::pair<const char *, std::string>> &refs) : refs_(refs) {} void visit(Sequence &ope) override { auto save_is_empty = false; const char *save_error_s = nullptr; std::string save_error_name; for (auto op : ope.opes_) { op->accept(*this); if (!is_empty) { return; } save_is_empty = is_empty; save_error_s = error_s; save_error_name = error_name; is_empty = false; error_name.clear(); } is_empty = save_is_empty; error_s = save_error_s; error_name = save_error_name; } void visit(PrioritizedChoice &ope) override { for (auto op : ope.opes_) { op->accept(*this); if (is_empty) { return; } } } void visit(Repetition &ope) override { if (ope.min_ == 0) { set_error(); } else { ope.ope_->accept(*this); } } void visit(AndPredicate &) override { set_error(); } void visit(NotPredicate &) override { set_error(); } void visit(LiteralString &ope) override { if (ope.lit_.empty()) { set_error(); } } void visit(CaptureScope &ope) override { ope.ope_->accept(*this); } void visit(Capture &ope) override { ope.ope_->accept(*this); } void visit(TokenBoundary &ope) override { ope.ope_->accept(*this); } void visit(Ignore &ope) override { ope.ope_->accept(*this); } void visit(WeakHolder &ope) override { ope.weak_.lock()->accept(*this); } void visit(Holder &ope) override { ope.ope_->accept(*this); } void visit(Reference &ope) override; void visit(Whitespace &ope) override { ope.ope_->accept(*this); } void visit(PrecedenceClimbing &ope) override { ope.atom_->accept(*this); } void visit(Recovery &ope) override { ope.ope_->accept(*this); } bool is_empty = false; const char *error_s = nullptr; std::string error_name; private: void set_error() { is_empty = true; tie(error_s, error_name) = refs_.back(); } std::list<std::pair<const char *, std::string>> &refs_; }; struct DetectInfiniteLoop : public Ope::Visitor { DetectInfiniteLoop(const char *s, const std::string &name) { refs_.emplace_back(s, name); } void visit(Sequence &ope) override { for (auto op : ope.opes_) { op->accept(*this); if (has_error) { return; } } } void visit(PrioritizedChoice &ope) override { for (auto op : ope.opes_) { op->accept(*this); if (has_error) { return; } } } void visit(Repetition &ope) override { if (ope.max_ == std::numeric_limits<size_t>::max()) { HasEmptyElement vis(refs_); ope.ope_->accept(vis); if (vis.is_empty) { has_error = true; error_s = vis.error_s; error_name = vis.error_name; } } else { ope.ope_->accept(*this); } } void visit(AndPredicate &ope) override { ope.ope_->accept(*this); } void visit(NotPredicate &ope) override { ope.ope_->accept(*this); } void visit(CaptureScope &ope) override { ope.ope_->accept(*this); } void visit(Capture &ope) override { ope.ope_->accept(*this); } void visit(TokenBoundary &ope) override { ope.ope_->accept(*this); } void visit(Ignore &ope) override { ope.ope_->accept(*this); } void visit(WeakHolder &ope) override { ope.weak_.lock()->accept(*this); } void visit(Holder &ope) override { ope.ope_->accept(*this); } void visit(Reference &ope) override; void visit(Whitespace &ope) override { ope.ope_->accept(*this); } void visit(PrecedenceClimbing &ope) override { ope.atom_->accept(*this); } void visit(Recovery &ope) override { ope.ope_->accept(*this); } bool has_error = false; const char *error_s = nullptr; std::string error_name; private: std::list<std::pair<const char *, std::string>> refs_; }; struct ReferenceChecker : public Ope::Visitor { ReferenceChecker(const Grammar &grammar, const std::vector<std::string> &params) : grammar_(grammar), params_(params) {} void visit(Sequence &ope) override { for (auto op : ope.opes_) { op->accept(*this); } } void visit(PrioritizedChoice &ope) override { for (auto op : ope.opes_) { op->accept(*this); } } void visit(Repetition &ope) override { ope.ope_->accept(*this); } void visit(AndPredicate &ope) override { ope.ope_->accept(*this); } void visit(NotPredicate &ope) override { ope.ope_->accept(*this); } void visit(CaptureScope &ope) override { ope.ope_->accept(*this); } void visit(Capture &ope) override { ope.ope_->accept(*this); } void visit(TokenBoundary &ope) override { ope.ope_->accept(*this); } void visit(Ignore &ope) override { ope.ope_->accept(*this); } void visit(WeakHolder &ope) override { ope.weak_.lock()->accept(*this); } void visit(Holder &ope) override { ope.ope_->accept(*this); } void visit(Reference &ope) override; void visit(Whitespace &ope) override { ope.ope_->accept(*this); } void visit(PrecedenceClimbing &ope) override { ope.atom_->accept(*this); } void visit(Recovery &ope) override { ope.ope_->accept(*this); } std::unordered_map<std::string, const char *> error_s; std::unordered_map<std::string, std::string> error_message; std::unordered_set<std::string> referenced; private: const Grammar &grammar_; const std::vector<std::string> &params_; }; struct LinkReferences : public Ope::Visitor { LinkReferences(Grammar &grammar, const std::vector<std::string> &params) : grammar_(grammar), params_(params) {} void visit(Sequence &ope) override { for (auto op : ope.opes_) { op->accept(*this); } } void visit(PrioritizedChoice &ope) override { for (auto op : ope.opes_) { op->accept(*this); } } void visit(Repetition &ope) override { ope.ope_->accept(*this); } void visit(AndPredicate &ope) override { ope.ope_->accept(*this); } void visit(NotPredicate &ope) override { ope.ope_->accept(*this); } void visit(CaptureScope &ope) override { ope.ope_->accept(*this); } void visit(Capture &ope) override { ope.ope_->accept(*this); } void visit(TokenBoundary &ope) override { ope.ope_->accept(*this); } void visit(Ignore &ope) override { ope.ope_->accept(*this); } void visit(WeakHolder &ope) override { ope.weak_.lock()->accept(*this); } void visit(Holder &ope) override { ope.ope_->accept(*this); } void visit(Reference &ope) override; void visit(Whitespace &ope) override { ope.ope_->accept(*this); } void visit(PrecedenceClimbing &ope) override { ope.atom_->accept(*this); } void visit(Recovery &ope) override { ope.ope_->accept(*this); } private: Grammar &grammar_; const std::vector<std::string> &params_; }; struct FindReference : public Ope::Visitor { FindReference(const std::vector<std::shared_ptr<Ope>> &args, const std::vector<std::string> &params) : args_(args), params_(params) {} void visit(Sequence &ope) override { std::vector<std::shared_ptr<Ope>> opes; for (auto o : ope.opes_) { o->accept(*this); opes.push_back(found_ope); } found_ope = std::make_shared<Sequence>(opes); } void visit(PrioritizedChoice &ope) override { std::vector<std::shared_ptr<Ope>> opes; for (auto o : ope.opes_) { o->accept(*this); opes.push_back(found_ope); } found_ope = std::make_shared<PrioritizedChoice>(opes); } void visit(Repetition &ope) override { ope.ope_->accept(*this); found_ope = rep(found_ope, ope.min_, ope.max_); } void visit(AndPredicate &ope) override { ope.ope_->accept(*this); found_ope = apd(found_ope); } void visit(NotPredicate &ope) override { ope.ope_->accept(*this); found_ope = npd(found_ope); } void visit(Dictionary &ope) override { found_ope = ope.shared_from_this(); } void visit(LiteralString &ope) override { found_ope = ope.shared_from_this(); } void visit(CharacterClass &ope) override { found_ope = ope.shared_from_this(); } void visit(Character &ope) override { found_ope = ope.shared_from_this(); } void visit(AnyCharacter &ope) override { found_ope = ope.shared_from_this(); } void visit(CaptureScope &ope) override { ope.ope_->accept(*this); found_ope = csc(found_ope); } void visit(Capture &ope) override { ope.ope_->accept(*this); found_ope = cap(found_ope, ope.match_action_); } void visit(TokenBoundary &ope) override { ope.ope_->accept(*this); found_ope = tok(found_ope); } void visit(Ignore &ope) override { ope.ope_->accept(*this); found_ope = ign(found_ope); } void visit(WeakHolder &ope) override { ope.weak_.lock()->accept(*this); } void visit(Holder &ope) override { ope.ope_->accept(*this); } void visit(Reference &ope) override; void visit(Whitespace &ope) override { ope.ope_->accept(*this); found_ope = wsp(found_ope); } void visit(PrecedenceClimbing &ope) override { ope.atom_->accept(*this); found_ope = csc(found_ope); } void visit(Recovery &ope) override { ope.ope_->accept(*this); found_ope = rec(found_ope); } void visit(Cut &ope) override { found_ope = ope.shared_from_this(); } std::shared_ptr<Ope> found_ope; private: const std::vector<std::shared_ptr<Ope>> &args_; const std::vector<std::string> &params_; }; struct IsPrioritizedChoice : public Ope::Visitor { void visit(PrioritizedChoice &) override { result_ = true; } static bool check(Ope &ope) { IsPrioritizedChoice vis; ope.accept(vis); return vis.result_; } private: bool result_ = false; }; /* * Keywords */ static const char *WHITESPACE_DEFINITION_NAME = "%whitespace"; static const char *WORD_DEFINITION_NAME = "%word"; static const char *RECOVER_DEFINITION_NAME = "%recover"; /* * Definition */ class Definition { public: struct Result { bool ret; bool recovered; size_t len; ErrorInfo error_info; }; Definition() : holder_(std::make_shared<Holder>(this)) {} Definition(const Definition &rhs) : name(rhs.name), holder_(rhs.holder_) { holder_->outer_ = this; } Definition(const std::shared_ptr<Ope> &ope) : holder_(std::make_shared<Holder>(this)) { *this <= ope; } operator std::shared_ptr<Ope>() { return std::make_shared<WeakHolder>(holder_); } Definition &operator<=(const std::shared_ptr<Ope> &ope) { holder_->ope_ = ope; return *this; } Result parse(const char *s, size_t n, const char *path = nullptr, Log log = nullptr) const { SemanticValues vs; std::any dt; return parse_core(s, n, vs, dt, path, log); } Result parse(const char *s, const char *path = nullptr, Log log = nullptr) const { auto n = strlen(s); return parse(s, n, path, log); } Result parse(const char *s, size_t n, std::any &dt, const char *path = nullptr, Log log = nullptr) const { SemanticValues vs; return parse_core(s, n, vs, dt, path, log); } Result parse(const char *s, std::any &dt, const char *path = nullptr, Log log = nullptr) const { auto n = strlen(s); return parse(s, n, dt, path, log); } template <typename T> Result parse_and_get_value(const char *s, size_t n, T &val, const char *path = nullptr, Log log = nullptr) const { SemanticValues vs; std::any dt; auto r = parse_core(s, n, vs, dt, path, log); if (r.ret && !vs.empty() && vs.front().has_value()) { val = std::any_cast<T>(vs[0]); } return r; } template <typename T> Result parse_and_get_value(const char *s, T &val, const char *path = nullptr, Log log = nullptr) const { auto n = strlen(s); return parse_and_get_value(s, n, val, path, log); } template <typename T> Result parse_and_get_value(const char *s, size_t n, std::any &dt, T &val, const char *path = nullptr, Log log = nullptr) const { SemanticValues vs; auto r = parse_core(s, n, vs, dt, path, log); if (r.ret && !vs.empty() && vs.front().has_value()) { val = std::any_cast<T>(vs[0]); } return r; } template <typename T> Result parse_and_get_value(const char *s, std::any &dt, T &val, const char *path = nullptr, Log log = nullptr) const { auto n = strlen(s); return parse_and_get_value(s, n, dt, val, path, log); } void operator=(Action a) { action = a; } template <typename T> Definition &operator,(T fn) { operator=(fn); return *this; } Definition &operator~() { ignoreSemanticValue = true; return *this; } void accept(Ope::Visitor &v) { holder_->accept(v); } std::shared_ptr<Ope> get_core_operator() const { return holder_->ope_; } bool is_token() const { std::call_once(is_token_init_, [this]() { is_token_ = TokenChecker::is_token(*get_core_operator()); }); return is_token_; } std::string name; const char *s_ = nullptr; size_t id = 0; Action action; std::function<void(const char *s, size_t n, std::any &dt)> enter; std::function<void(const char *s, size_t n, size_t matchlen, std::any &value, std::any &dt)> leave; bool ignoreSemanticValue = false; std::shared_ptr<Ope> whitespaceOpe; std::shared_ptr<Ope> wordOpe; bool enablePackratParsing = false; bool is_macro = false; std::vector<std::string> params; TracerEnter tracer_enter; TracerLeave tracer_leave; bool disable_action = false; std::string error_message; bool no_ast_opt = false; private: friend class Reference; friend class ParserGenerator; Definition &operator=(const Definition &rhs); Definition &operator=(Definition &&rhs); void initialize_definition_ids() const { std::call_once(definition_ids_init_, [&]() { AssignIDToDefinition vis; holder_->accept(vis); if (whitespaceOpe) { whitespaceOpe->accept(vis); } if (wordOpe) { wordOpe->accept(vis); } definition_ids_.swap(vis.ids); }); } Result parse_core(const char *s, size_t n, SemanticValues &vs, std::any &dt, const char *path, Log log) const { initialize_definition_ids(); std::shared_ptr<Ope> ope = holder_; if (whitespaceOpe) { ope = std::make_shared<Sequence>(whitespaceOpe, ope); } Context cxt(path, s, n, definition_ids_.size(), whitespaceOpe, wordOpe, enablePackratParsing, tracer_enter, tracer_leave, log); auto len = ope->parse(s, n, vs, cxt, dt); return Result{success(len), cxt.recovered, len, cxt.error_info}; } std::shared_ptr<Holder> holder_; mutable std::once_flag is_token_init_; mutable bool is_token_ = false; mutable std::once_flag assign_id_to_definition_init_; mutable std::once_flag definition_ids_init_; mutable std::unordered_map<void *, size_t> definition_ids_; }; /* * Implementations */ inline size_t parse_literal(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt, const std::string &lit, std::once_flag &init_is_word, bool &is_word, bool ignore_case) { size_t i = 0; for (; i < lit.size(); i++) { if (i >= n || (ignore_case ? (std::tolower(s[i]) != std::tolower(lit[i])) : (s[i] != lit[i]))) { c.set_error_pos(s, lit.c_str()); return static_cast<size_t>(-1); } } // Word check if (c.wordOpe) { std::call_once(init_is_word, [&]() { SemanticValues dummy_vs; Context dummy_c(nullptr, c.s, c.l, 0, nullptr, nullptr, false, nullptr, nullptr, nullptr); std::any dummy_dt; auto len = c.wordOpe->parse(lit.data(), lit.size(), dummy_vs, dummy_c, dummy_dt); is_word = success(len); }); if (is_word) { SemanticValues dummy_vs; Context dummy_c(nullptr, c.s, c.l, 0, nullptr, nullptr, false, nullptr, nullptr, nullptr); std::any dummy_dt; NotPredicate ope(c.wordOpe); auto len = ope.parse(s + i, n - i, dummy_vs, dummy_c, dummy_dt); if (fail(len)) { return len; } i += len; } } // Skip whiltespace if (!c.in_token_boundary_count) { if (c.whitespaceOpe) { auto len = c.whitespaceOpe->parse(s + i, n - i, vs, c, dt); if (fail(len)) { return len; } i += len; } } return i; } inline void Context::set_error_pos(const char *a_s, const char *literal) { if (log) { if (error_info.error_pos <= a_s) { if (error_info.error_pos < a_s) { error_info.error_pos = a_s; error_info.expected_tokens.clear(); } if (literal) { error_info.add(literal, true); } else if (!rule_stack.empty()) { auto rule = rule_stack.back(); auto ope = rule->get_core_operator(); if (auto token = FindLiteralToken::token(*ope); token && token[0] != '\0') { error_info.add(token, true); } else { error_info.add(rule->name.c_str(), false); } } } } } inline void Context::trace_enter(const Ope &ope, const char *a_s, size_t n, SemanticValues &vs, std::any &dt) const { trace_ids.push_back(next_trace_id++); tracer_enter(ope, a_s, n, vs, *this, dt); } inline void Context::trace_leave(const Ope &ope, const char *a_s, size_t n, SemanticValues &vs, std::any &dt, size_t len) const { tracer_leave(ope, a_s, n, vs, *this, dt, len); trace_ids.pop_back(); } inline bool Context::is_traceable(const Ope &ope) const { if (tracer_enter && tracer_leave) { return !IsReference::check(const_cast<Ope &>(ope)); } return false; } inline size_t Ope::parse(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const { if (c.is_traceable(*this)) { c.trace_enter(*this, s, n, vs, dt); auto len = parse_core(s, n, vs, c, dt); c.trace_leave(*this, s, n, vs, dt, len); return len; } return parse_core(s, n, vs, c, dt); } inline size_t Dictionary::parse_core(const char *s, size_t n, SemanticValues & /*vs*/, Context &c, std::any & /*dt*/) const { auto len = trie_.match(s, n); if (len > 0) { return len; } c.set_error_pos(s); return static_cast<size_t>(-1); } inline size_t LiteralString::parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const { return parse_literal(s, n, vs, c, dt, lit_, init_is_word_, is_word_, ignore_case_); } inline size_t TokenBoundary::parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const { size_t len; { c.in_token_boundary_count++; auto se = scope_exit([&]() { c.in_token_boundary_count--; }); len = ope_->parse(s, n, vs, c, dt); } if (success(len)) { vs.tokens.emplace_back(std::string_view(s, len)); if (!c.in_token_boundary_count) { if (c.whitespaceOpe) { auto l = c.whitespaceOpe->parse(s + len, n - len, vs, c, dt); if (fail(l)) { return l; } len += l; } } } return len; } inline size_t Holder::parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const { if (!ope_) { throw std::logic_error("Uninitialized definition ope was used..."); } // Macro reference if (outer_->is_macro) { c.rule_stack.push_back(outer_); auto len = ope_->parse(s, n, vs, c, dt); c.rule_stack.pop_back(); return len; } size_t len; std::any val; c.packrat(s, outer_->id, len, val, [&](std::any &a_val) { if (outer_->enter) { outer_->enter(s, n, dt); } auto se2 = scope_exit([&]() { c.pop(); if (outer_->leave) { outer_->leave(s, n, len, a_val, dt); } }); auto &chldsv = c.push(); c.rule_stack.push_back(outer_); len = ope_->parse(s, n, chldsv, c, dt); c.rule_stack.pop_back(); // Invoke action if (success(len)) { chldsv.sv_ = std::string_view(s, len); chldsv.name_ = outer_->name; if (!IsPrioritizedChoice::check(*ope_)) { chldsv.choice_count_ = 0; chldsv.choice_ = 0; } try { a_val = reduce(chldsv, dt); } catch (const parse_error &e) { if (c.log) { if (e.what()) { if (c.error_info.message_pos < s) { c.error_info.message_pos = s; c.error_info.message = e.what(); } } } len = static_cast<size_t>(-1); } } }); if (success(len)) { if (!outer_->ignoreSemanticValue) { vs.emplace_back(std::move(val)); vs.tags.emplace_back(str2tag(outer_->name)); } } return len; } inline std::any Holder::reduce(SemanticValues &vs, std::any &dt) const { if (outer_->action && !outer_->disable_action) { return outer_->action(vs, dt); } else if (vs.empty()) { return std::any(); } else { return std::move(vs.front()); } } inline const char *Holder::trace_name() const { if (trace_name_.empty()) { trace_name_ = "[" + outer_->name + "]"; } return trace_name_.data(); } inline size_t Reference::parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const { if (rule_) { // Reference rule if (rule_->is_macro) { // Macro FindReference vis(c.top_args(), c.rule_stack.back()->params); // Collect arguments std::vector<std::shared_ptr<Ope>> args; for (auto arg : args_) { arg->accept(vis); args.emplace_back(std::move(vis.found_ope)); } c.push_args(std::move(args)); auto se = scope_exit([&]() { c.pop_args(); }); auto ope = get_core_operator(); return ope->parse(s, n, vs, c, dt); } else { // Definition c.push_args(std::vector<std::shared_ptr<Ope>>()); auto se = scope_exit([&]() { c.pop_args(); }); auto ope = get_core_operator(); return ope->parse(s, n, vs, c, dt); } } else { // Reference parameter in macro const auto &args = c.top_args(); return args[iarg_]->parse(s, n, vs, c, dt); } } inline std::shared_ptr<Ope> Reference::get_core_operator() const { return rule_->holder_; } inline size_t BackReference::parse_core(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt) const { auto size = static_cast<int>(c.capture_scope_stack_size); for (auto i = size - 1; i >= 0; i--) { auto index = static_cast<size_t>(i); const auto &cs = c.capture_scope_stack[index]; if (cs.find(name_) != cs.end()) { const auto &lit = cs.at(name_); std::once_flag init_is_word; auto is_word = false; return parse_literal(s, n, vs, c, dt, lit, init_is_word, is_word, false); } } throw std::runtime_error("Invalid back reference..."); } inline Definition & PrecedenceClimbing::get_reference_for_binop(Context &c) const { if (rule_.is_macro) { // Reference parameter in macro const auto &args = c.top_args(); auto iarg = dynamic_cast<Reference &>(*binop_).iarg_; auto arg = args[iarg]; return *dynamic_cast<Reference &>(*arg).rule_; } return *dynamic_cast<Reference &>(*binop_).rule_; } inline size_t PrecedenceClimbing::parse_expression(const char *s, size_t n, SemanticValues &vs, Context &c, std::any &dt, size_t min_prec) const { auto len = atom_->parse(s, n, vs, c, dt); if (fail(len)) { return len; } std::string tok; auto &rule = get_reference_for_binop(c); auto action = std::move(rule.action); rule.action = [&](SemanticValues &vs2, std::any &dt2) { tok = vs2.token(); if (action) { return action(vs2, dt2); } else if (!vs2.empty()) { return vs2[0]; } return std::any(); }; auto action_se = scope_exit([&]() { rule.action = std::move(action); }); auto i = len; while (i < n) { std::vector<std::any> save_values(vs.begin(), vs.end()); auto save_tokens = vs.tokens; auto chv = c.push(); auto chl = binop_->parse(s + i, n - i, chv, c, dt); c.pop(); if (fail(chl)) { break; } auto it = info_.find(tok); if (it == info_.end()) { break; } auto level = std::get<0>(it->second); auto assoc = std::get<1>(it->second); if (level < min_prec) { break; } vs.emplace_back(std::move(chv[0])); i += chl; auto next_min_prec = level; if (assoc == 'L') { next_min_prec = level + 1; } chv = c.push(); chl = parse_expression(s + i, n - i, chv, c, dt, next_min_prec); c.pop(); if (fail(chl)) { vs.assign(save_values.begin(), save_values.end()); vs.tokens = save_tokens; i = chl; break; } vs.emplace_back(std::move(chv[0])); i += chl; std::any val; if (rule_.action) { vs.sv_ = std::string_view(s, i); val = rule_.action(vs, dt); } else if (!vs.empty()) { val = vs[0]; } vs.clear(); vs.emplace_back(std::move(val)); } return i; } inline size_t Recovery::parse_core(const char *s, size_t n, SemanticValues & /*vs*/, Context &c, std::any & /*dt*/) const { const auto &rule = dynamic_cast<Reference &>(*ope_); // Custom error message if (c.log) { auto label = dynamic_cast<Reference *>(rule.args_[0].get()); if (label) { if (!label->rule_->error_message.empty()) { c.error_info.message_pos = s; c.error_info.message = label->rule_->error_message; } } } // Recovery size_t len = static_cast<size_t>(-1); { auto save_log = c.log; c.log = nullptr; auto se = scope_exit([&]() { c.log = save_log; }); SemanticValues dummy_vs; std::any dummy_dt; len = rule.parse(s, n, dummy_vs, c, dummy_dt); } if (success(len)) { c.recovered = true; if (c.log) { c.error_info.output_log(c.log, c.s, c.l); c.error_info.clear(); } } // Cut if (!c.cut_stack.empty()) { c.cut_stack.back() = true; if (c.cut_stack.size() == 1) { // TODO: Remove unneeded entries in packrat memoise table } } return len; } inline void Sequence::accept(Visitor &v) { v.visit(*this); } inline void PrioritizedChoice::accept(Visitor &v) { v.visit(*this); } inline void Repetition::accept(Visitor &v) { v.visit(*this); } inline void AndPredicate::accept(Visitor &v) { v.visit(*this); } inline void NotPredicate::accept(Visitor &v) { v.visit(*this); } inline void Dictionary::accept(Visitor &v) { v.visit(*this); } inline void LiteralString::accept(Visitor &v) { v.visit(*this); } inline void CharacterClass::accept(Visitor &v) { v.visit(*this); } inline void Character::accept(Visitor &v) { v.visit(*this); } inline void AnyCharacter::accept(Visitor &v) { v.visit(*this); } inline void CaptureScope::accept(Visitor &v) { v.visit(*this); } inline void Capture::accept(Visitor &v) { v.visit(*this); } inline void TokenBoundary::accept(Visitor &v) { v.visit(*this); } inline void Ignore::accept(Visitor &v) { v.visit(*this); } inline void User::accept(Visitor &v) { v.visit(*this); } inline void WeakHolder::accept(Visitor &v) { v.visit(*this); } inline void Holder::accept(Visitor &v) { v.visit(*this); } inline void Reference::accept(Visitor &v) { v.visit(*this); } inline void Whitespace::accept(Visitor &v) { v.visit(*this); } inline void BackReference::accept(Visitor &v) { v.visit(*this); } inline void PrecedenceClimbing::accept(Visitor &v) { v.visit(*this); } inline void Recovery::accept(Visitor &v) { v.visit(*this); } inline void Cut::accept(Visitor &v) { v.visit(*this); } inline void AssignIDToDefinition::visit(Holder &ope) { auto p = static_cast<void *>(ope.outer_); if (ids.count(p)) { return; } auto id = ids.size(); ids[p] = id; ope.outer_->id = id; ope.ope_->accept(*this); } inline void AssignIDToDefinition::visit(Reference &ope) { if (ope.rule_) { for (auto arg : ope.args_) { arg->accept(*this); } ope.rule_->accept(*this); } } inline void AssignIDToDefinition::visit(PrecedenceClimbing &ope) { ope.atom_->accept(*this); ope.binop_->accept(*this); } inline void TokenChecker::visit(Reference &ope) { if (ope.is_macro_) { for (auto arg : ope.args_) { arg->accept(*this); } } else { has_rule_ = true; } } inline void FindLiteralToken::visit(Reference &ope) { if (ope.is_macro_) { ope.rule_->accept(*this); for (auto arg : ope.args_) { arg->accept(*this); } } } inline void DetectLeftRecursion::visit(Reference &ope) { if (ope.name_ == name_) { error_s = ope.s_; } else if (!refs_.count(ope.name_)) { refs_.insert(ope.name_); if (ope.rule_) { ope.rule_->accept(*this); if (done_ == false) { return; } } } done_ = true; } inline void HasEmptyElement::visit(Reference &ope) { auto it = std::find_if(refs_.begin(), refs_.end(), [&](const std::pair<const char *, std::string> &ref) { return ope.name_ == ref.second; }); if (it != refs_.end()) { return; } if (ope.rule_) { refs_.emplace_back(ope.s_, ope.name_); ope.rule_->accept(*this); refs_.pop_back(); } } inline void DetectInfiniteLoop::visit(Reference &ope) { auto it = std::find_if(refs_.begin(), refs_.end(), [&](const std::pair<const char *, std::string> &ref) { return ope.name_ == ref.second; }); if (it != refs_.end()) { return; } if (ope.rule_) { refs_.emplace_back(ope.s_, ope.name_); ope.rule_->accept(*this); refs_.pop_back(); } if (ope.is_macro_) { for (auto arg : ope.args_) { arg->accept(*this); } } } inline void ReferenceChecker::visit(Reference &ope) { auto it = std::find(params_.begin(), params_.end(), ope.name_); if (it != params_.end()) { return; } if (!grammar_.count(ope.name_)) { error_s[ope.name_] = ope.s_; error_message[ope.name_] = "'" + ope.name_ + "' is not defined."; } else { if (!referenced.count(ope.name_)) { referenced.insert(ope.name_); } const auto &rule = grammar_.at(ope.name_); if (rule.is_macro) { if (!ope.is_macro_ || ope.args_.size() != rule.params.size()) { error_s[ope.name_] = ope.s_; error_message[ope.name_] = "incorrect number of arguments."; } } else if (ope.is_macro_) { error_s[ope.name_] = ope.s_; error_message[ope.name_] = "'" + ope.name_ + "' is not macro."; } for (auto arg : ope.args_) { arg->accept(*this); } } } inline void LinkReferences::visit(Reference &ope) { // Check if the reference is a macro parameter auto found_param = false; for (size_t i = 0; i < params_.size(); i++) { const auto &param = params_[i]; if (param == ope.name_) { ope.iarg_ = i; found_param = true; break; } } // Check if the reference is a definition rule if (!found_param && grammar_.count(ope.name_)) { auto &rule = grammar_.at(ope.name_); ope.rule_ = &rule; } for (auto arg : ope.args_) { arg->accept(*this); } } inline void FindReference::visit(Reference &ope) { for (size_t i = 0; i < args_.size(); i++) { const auto &name = params_[i]; if (name == ope.name_) { found_ope = args_[i]; return; } } found_ope = ope.shared_from_this(); } /*----------------------------------------------------------------------------- * PEG parser generator *---------------------------------------------------------------------------*/ using Rules = std::unordered_map<std::string, std::shared_ptr<Ope>>; class ParserGenerator { public: static std::shared_ptr<Grammar> parse(const char *s, size_t n, const Rules &rules, std::string &start, bool &enablePackratParsing, Log log) { return get_instance().perform_core(s, n, rules, start, enablePackratParsing, log); } static std::shared_ptr<Grammar> parse(const char *s, size_t n, std::string &start, bool &enablePackratParsing, Log log) { Rules dummy; return parse(s, n, dummy, start, enablePackratParsing, log); } // For debuging purpose static Grammar &grammar() { return get_instance().g; } private: static ParserGenerator &get_instance() { static ParserGenerator instance; return instance; } ParserGenerator() { make_grammar(); setup_actions(); } struct Instruction { std::string type; std::any data; }; struct Data { std::shared_ptr<Grammar> grammar; std::string start; const char *start_pos = nullptr; std::vector<std::pair<std::string, const char *>> duplicates; std::map<std::string, Instruction> instructions; std::set<std::string_view> captures; bool enablePackratParsing = true; Data() : grammar(std::make_shared<Grammar>()) {} }; void make_grammar() { // Setup PEG syntax parser g["Grammar"] <= seq(g["Spacing"], oom(g["Definition"]), g["EndOfFile"]); g["Definition"] <= cho(seq(g["Ignore"], g["IdentCont"], g["Parameters"], g["LEFTARROW"], g["Expression"], opt(g["Instruction"])), seq(g["Ignore"], g["Identifier"], g["LEFTARROW"], g["Expression"], opt(g["Instruction"]))); g["Expression"] <= seq(g["Sequence"], zom(seq(g["SLASH"], g["Sequence"]))); g["Sequence"] <= zom(cho(g["CUT"], g["Prefix"])); g["Prefix"] <= seq(opt(cho(g["AND"], g["NOT"])), g["SuffixWithLabel"]); g["SuffixWithLabel"] <= seq(g["Suffix"], opt(seq(g["LABEL"], g["Identifier"]))); g["Suffix"] <= seq(g["Primary"], opt(g["Loop"])); g["Loop"] <= cho(g["QUESTION"], g["STAR"], g["PLUS"], g["Repetition"]); g["Primary"] <= cho(seq(g["Ignore"], g["IdentCont"], g["Arguments"], npd(g["LEFTARROW"])), seq(g["Ignore"], g["Identifier"], npd(seq(opt(g["Parameters"]), g["LEFTARROW"]))), seq(g["OPEN"], g["Expression"], g["CLOSE"]), seq(g["BeginTok"], g["Expression"], g["EndTok"]), seq(g["BeginCapScope"], g["Expression"], g["EndCapScope"]), seq(g["BeginCap"], g["Expression"], g["EndCap"]), g["BackRef"], g["LiteralI"], g["Dictionary"], g["Literal"], g["NegatedClass"], g["Class"], g["DOT"]); g["Identifier"] <= seq(g["IdentCont"], g["Spacing"]); g["IdentCont"] <= seq(g["IdentStart"], zom(g["IdentRest"])); const static std::vector<std::pair<char32_t, char32_t>> range = { {0x0080, 0xFFFF}}; g["IdentStart"] <= seq(npd(lit(u8(u8"↑"))), npd(lit(u8(u8"⇑"))), cho(cls("a-zA-Z_%"), cls(range))); g["IdentRest"] <= cho(g["IdentStart"], cls("0-9")); g["Dictionary"] <= seq(g["LiteralD"], oom(seq(g["PIPE"], g["LiteralD"]))); auto lit_ope = cho(seq(cls("'"), tok(zom(seq(npd(cls("'")), g["Char"]))), cls("'"), g["Spacing"]), seq(cls("\""), tok(zom(seq(npd(cls("\"")), g["Char"]))), cls("\""), g["Spacing"])); g["Literal"] <= lit_ope; g["LiteralD"] <= lit_ope; g["LiteralI"] <= cho(seq(cls("'"), tok(zom(seq(npd(cls("'")), g["Char"]))), lit("'i"), g["Spacing"]), seq(cls("\""), tok(zom(seq(npd(cls("\"")), g["Char"]))), lit("\"i"), g["Spacing"])); // NOTE: The original Brian Ford's paper uses 'zom' instead of 'oom'. g["Class"] <= seq(chr('['), npd(chr('^')), tok(oom(seq(npd(chr(']')), g["Range"]))), chr(']'), g["Spacing"]); g["NegatedClass"] <= seq(lit("[^"), tok(oom(seq(npd(chr(']')), g["Range"]))), chr(']'), g["Spacing"]); g["Range"] <= cho(seq(g["Char"], chr('-'), g["Char"]), g["Char"]); g["Char"] <= cho(seq(chr('\\'), cls("nrt'\"[]\\^")), seq(chr('\\'), cls("0-3"), cls("0-7"), cls("0-7")), seq(chr('\\'), cls("0-7"), opt(cls("0-7"))), seq(lit("\\x"), cls("0-9a-fA-F"), opt(cls("0-9a-fA-F"))), seq(lit("\\u"), cho(seq(cho(seq(chr('0'), cls("0-9a-fA-F")), lit("10")), rep(cls("0-9a-fA-F"), 4, 4)), rep(cls("0-9a-fA-F"), 4, 5))), seq(npd(chr('\\')), dot())); g["Repetition"] <= seq(g["BeginBlacket"], g["RepetitionRange"], g["EndBlacket"]); g["RepetitionRange"] <= cho(seq(g["Number"], g["COMMA"], g["Number"]), seq(g["Number"], g["COMMA"]), g["Number"], seq(g["COMMA"], g["Number"])); g["Number"] <= seq(oom(cls("0-9")), g["Spacing"]); g["LEFTARROW"] <= seq(cho(lit("<-"), lit(u8(u8"←"))), g["Spacing"]); ~g["SLASH"] <= seq(chr('/'), g["Spacing"]); ~g["PIPE"] <= seq(chr('|'), g["Spacing"]); g["AND"] <= seq(chr('&'), g["Spacing"]); g["NOT"] <= seq(chr('!'), g["Spacing"]); g["QUESTION"] <= seq(chr('?'), g["Spacing"]); g["STAR"] <= seq(chr('*'), g["Spacing"]); g["PLUS"] <= seq(chr('+'), g["Spacing"]); ~g["OPEN"] <= seq(chr('('), g["Spacing"]); ~g["CLOSE"] <= seq(chr(')'), g["Spacing"]); g["DOT"] <= seq(chr('.'), g["Spacing"]); g["CUT"] <= seq(lit(u8(u8"↑")), g["Spacing"]); ~g["LABEL"] <= seq(cho(chr('^'), lit(u8(u8"⇑"))), g["Spacing"]); ~g["Spacing"] <= zom(cho(g["Space"], g["Comment"])); g["Comment"] <= seq(chr('#'), zom(seq(npd(g["EndOfLine"]), dot())), g["EndOfLine"]); g["Space"] <= cho(chr(' '), chr('\t'), g["EndOfLine"]); g["EndOfLine"] <= cho(lit("\r\n"), chr('\n'), chr('\r')); g["EndOfFile"] <= npd(dot()); ~g["BeginTok"] <= seq(chr('<'), g["Spacing"]); ~g["EndTok"] <= seq(chr('>'), g["Spacing"]); ~g["BeginCapScope"] <= seq(chr('$'), chr('('), g["Spacing"]); ~g["EndCapScope"] <= seq(chr(')'), g["Spacing"]); g["BeginCap"] <= seq(chr('$'), tok(g["IdentCont"]), chr('<'), g["Spacing"]); ~g["EndCap"] <= seq(chr('>'), g["Spacing"]); g["BackRef"] <= seq(chr('$'), tok(g["IdentCont"]), g["Spacing"]); g["IGNORE"] <= chr('~'); g["Ignore"] <= opt(g["IGNORE"]); g["Parameters"] <= seq(g["OPEN"], g["Identifier"], zom(seq(g["COMMA"], g["Identifier"])), g["CLOSE"]); g["Arguments"] <= seq(g["OPEN"], g["Expression"], zom(seq(g["COMMA"], g["Expression"])), g["CLOSE"]); ~g["COMMA"] <= seq(chr(','), g["Spacing"]); // Instruction grammars g["Instruction"] <= seq(g["BeginBlacket"], cho(cho(g["PrecedenceClimbing"]), cho(g["ErrorMessage"]), cho(g["NoAstOpt"])), g["EndBlacket"]); ~g["SpacesZom"] <= zom(g["Space"]); ~g["SpacesOom"] <= oom(g["Space"]); ~g["BeginBlacket"] <= seq(chr('{'), g["Spacing"]); ~g["EndBlacket"] <= seq(chr('}'), g["Spacing"]); // PrecedenceClimbing instruction g["PrecedenceClimbing"] <= seq(lit("precedence"), g["SpacesOom"], g["PrecedenceInfo"], zom(seq(g["SpacesOom"], g["PrecedenceInfo"])), g["SpacesZom"]); g["PrecedenceInfo"] <= seq(g["PrecedenceAssoc"], oom(seq(ign(g["SpacesOom"]), g["PrecedenceOpe"]))); g["PrecedenceOpe"] <= cho(seq(cls("'"), tok(zom(seq(npd(cho(g["Space"], cls("'"))), g["Char"]))), cls("'")), seq(cls("\""), tok(zom(seq(npd(cho(g["Space"], cls("\""))), g["Char"]))), cls("\"")), tok(oom(seq(npd(cho(g["PrecedenceAssoc"], g["Space"], chr('}'))), dot())))); g["PrecedenceAssoc"] <= cls("LR"); // Error message instruction g["ErrorMessage"] <= seq(lit("message"), g["SpacesOom"], g["LiteralD"], g["SpacesZom"]); // No Ast node optimazation instruction g["NoAstOpt"] <= seq(lit("no_ast_opt"), g["SpacesZom"]); // Set definition names for (auto &x : g) { x.second.name = x.first; } } void setup_actions() { g["Definition"] = [&](const SemanticValues &vs, std::any &dt) { auto &data = *std::any_cast<Data *>(dt); auto is_macro = vs.choice() == 0; auto ignore = std::any_cast<bool>(vs[0]); auto name = std::any_cast<std::string>(vs[1]); std::vector<std::string> params; std::shared_ptr<Ope> ope; if (is_macro) { params = std::any_cast<std::vector<std::string>>(vs[2]); ope = std::any_cast<std::shared_ptr<Ope>>(vs[4]); if (vs.size() == 6) { data.instructions[name] = std::any_cast<Instruction>(vs[5]); } } else { ope = std::any_cast<std::shared_ptr<Ope>>(vs[3]); if (vs.size() == 5) { data.instructions[name] = std::any_cast<Instruction>(vs[4]); } } auto &grammar = *data.grammar; if (!grammar.count(name)) { auto &rule = grammar[name]; rule <= ope; rule.name = name; rule.s_ = vs.sv().data(); rule.ignoreSemanticValue = ignore; rule.is_macro = is_macro; rule.params = params; if (data.start.empty()) { data.start = name; data.start_pos = vs.sv().data(); } } else { data.duplicates.emplace_back(name, vs.sv().data()); } }; g["Definition"].enter = [](const char * /*s*/, size_t /*n*/, std::any &dt) { auto &data = *std::any_cast<Data *>(dt); data.captures.clear(); }; g["Expression"] = [&](const SemanticValues &vs) { if (vs.size() == 1) { return std::any_cast<std::shared_ptr<Ope>>(vs[0]); } else { std::vector<std::shared_ptr<Ope>> opes; for (auto i = 0u; i < vs.size(); i++) { opes.emplace_back(std::any_cast<std::shared_ptr<Ope>>(vs[i])); } const std::shared_ptr<Ope> ope = std::make_shared<PrioritizedChoice>(opes); return ope; } }; g["Sequence"] = [&](const SemanticValues &vs) { if (vs.empty()) { return npd(lit("")); } else if (vs.size() == 1) { return std::any_cast<std::shared_ptr<Ope>>(vs[0]); } else { std::vector<std::shared_ptr<Ope>> opes; for (const auto &x : vs) { opes.emplace_back(std::any_cast<std::shared_ptr<Ope>>(x)); } const std::shared_ptr<Ope> ope = std::make_shared<Sequence>(opes); return ope; } }; g["Prefix"] = [&](const SemanticValues &vs) { std::shared_ptr<Ope> ope; if (vs.size() == 1) { ope = std::any_cast<std::shared_ptr<Ope>>(vs[0]); } else { assert(vs.size() == 2); auto tok = std::any_cast<char>(vs[0]); ope = std::any_cast<std::shared_ptr<Ope>>(vs[1]); if (tok == '&') { ope = apd(ope); } else { // '!' ope = npd(ope); } } return ope; }; g["SuffixWithLabel"] = [&](const SemanticValues &vs, std::any &dt) { auto ope = std::any_cast<std::shared_ptr<Ope>>(vs[0]); if (vs.size() == 1) { return ope; } else { assert(vs.size() == 2); auto &data = *std::any_cast<Data *>(dt); const auto &ident = std::any_cast<std::string>(vs[1]); auto label = ref(*data.grammar, ident, vs.sv().data(), false, {}); auto recovery = rec(ref(*data.grammar, RECOVER_DEFINITION_NAME, vs.sv().data(), true, {label})); return cho4label_(ope, recovery); } }; struct Loop { enum class Type { opt = 0, zom, oom, rep }; Type type; std::pair<size_t, size_t> range; }; g["Suffix"] = [&](const SemanticValues &vs) { auto ope = std::any_cast<std::shared_ptr<Ope>>(vs[0]); if (vs.size() == 1) { return ope; } else { assert(vs.size() == 2); auto loop = std::any_cast<Loop>(vs[1]); switch (loop.type) { case Loop::Type::opt: return opt(ope); case Loop::Type::zom: return zom(ope); case Loop::Type::oom: return oom(ope); default: // Regex-like repetition return rep(ope, loop.range.first, loop.range.second); } } }; g["Loop"] = [&](const SemanticValues &vs) { switch (vs.choice()) { case 0: // Option return Loop{Loop::Type::opt, std::pair<size_t, size_t>()}; case 1: // Zero or More return Loop{Loop::Type::zom, std::pair<size_t, size_t>()}; case 2: // One or More return Loop{Loop::Type::oom, std::pair<size_t, size_t>()}; default: // Regex-like repetition return Loop{Loop::Type::rep, std::any_cast<std::pair<size_t, size_t>>(vs[0])}; } }; g["RepetitionRange"] = [&](const SemanticValues &vs) { switch (vs.choice()) { case 0: { // Number COMMA Number auto min = std::any_cast<size_t>(vs[0]); auto max = std::any_cast<size_t>(vs[1]); return std::pair(min, max); } case 1: // Number COMMA return std::pair(std::any_cast<size_t>(vs[0]), std::numeric_limits<size_t>::max()); case 2: { // Number auto n = std::any_cast<size_t>(vs[0]); return std::pair(n, n); } default: // COMMA Number return std::pair(std::numeric_limits<size_t>::min(), std::any_cast<size_t>(vs[0])); } }; g["Number"] = [&](const SemanticValues &vs) { return vs.token_to_number<size_t>(); }; g["Primary"] = [&](const SemanticValues &vs, std::any &dt) { auto &data = *std::any_cast<Data *>(dt); switch (vs.choice()) { case 0: // Macro Reference case 1: { // Reference auto is_macro = vs.choice() == 0; auto ignore = std::any_cast<bool>(vs[0]); const auto &ident = std::any_cast<std::string>(vs[1]); std::vector<std::shared_ptr<Ope>> args; if (is_macro) { args = std::any_cast<std::vector<std::shared_ptr<Ope>>>(vs[2]); } auto ope = ref(*data.grammar, ident, vs.sv().data(), is_macro, args); if (ident == RECOVER_DEFINITION_NAME) { ope = rec(ope); } if (ignore) { return ign(ope); } else { return ope; } } case 2: { // (Expression) return std::any_cast<std::shared_ptr<Ope>>(vs[0]); } case 3: { // TokenBoundary return tok(std::any_cast<std::shared_ptr<Ope>>(vs[0])); } case 4: { // CaptureScope return csc(std::any_cast<std::shared_ptr<Ope>>(vs[0])); } case 5: { // Capture const auto &name = std::any_cast<std::string_view>(vs[0]); auto ope = std::any_cast<std::shared_ptr<Ope>>(vs[1]); data.captures.insert(name); return cap(ope, [name](const char *a_s, size_t a_n, Context &c) { auto &cs = c.capture_scope_stack[c.capture_scope_stack_size - 1]; cs[name] = std::string(a_s, a_n); }); } default: { return std::any_cast<std::shared_ptr<Ope>>(vs[0]); } } }; g["IdentCont"] = [](const SemanticValues &vs) { return std::string(vs.sv().data(), vs.sv().length()); }; g["Dictionary"] = [](const SemanticValues &vs) { auto items = vs.transform<std::string>(); return dic(items); }; g["Literal"] = [](const SemanticValues &vs) { const auto &tok = vs.tokens.front(); return lit(resolve_escape_sequence(tok.data(), tok.size())); }; g["LiteralI"] = [](const SemanticValues &vs) { const auto &tok = vs.tokens.front(); return liti(resolve_escape_sequence(tok.data(), tok.size())); }; g["LiteralD"] = [](const SemanticValues &vs) { auto &tok = vs.tokens.front(); return resolve_escape_sequence(tok.data(), tok.size()); }; g["Class"] = [](const SemanticValues &vs) { auto ranges = vs.transform<std::pair<char32_t, char32_t>>(); return cls(ranges); }; g["NegatedClass"] = [](const SemanticValues &vs) { auto ranges = vs.transform<std::pair<char32_t, char32_t>>(); return ncls(ranges); }; g["Range"] = [](const SemanticValues &vs) { switch (vs.choice()) { case 0: { auto s1 = std::any_cast<std::string>(vs[0]); auto s2 = std::any_cast<std::string>(vs[1]); auto cp1 = decode_codepoint(s1.data(), s1.length()); auto cp2 = decode_codepoint(s2.data(), s2.length()); return std::pair(cp1, cp2); } case 1: { auto s = std::any_cast<std::string>(vs[0]); auto cp = decode_codepoint(s.data(), s.length()); return std::pair(cp, cp); } } return std::pair<char32_t, char32_t>(0, 0); }; g["Char"] = [](const SemanticValues &vs) { return resolve_escape_sequence(vs.sv().data(), vs.sv().length()); }; g["AND"] = [](const SemanticValues &vs) { return *vs.sv().data(); }; g["NOT"] = [](const SemanticValues &vs) { return *vs.sv().data(); }; g["QUESTION"] = [](const SemanticValues &vs) { return *vs.sv().data(); }; g["STAR"] = [](const SemanticValues &vs) { return *vs.sv().data(); }; g["PLUS"] = [](const SemanticValues &vs) { return *vs.sv().data(); }; g["DOT"] = [](const SemanticValues & /*vs*/) { return dot(); }; g["CUT"] = [](const SemanticValues & /*vs*/) { return cut(); }; g["BeginCap"] = [](const SemanticValues &vs) { return vs.token(); }; g["BackRef"] = [&](const SemanticValues &vs, std::any &dt) { auto &data = *std::any_cast<Data *>(dt); if (data.captures.find(vs.token()) == data.captures.end()) { data.enablePackratParsing = false; } return bkr(vs.token_to_string()); }; g["Ignore"] = [](const SemanticValues &vs) { return vs.size() > 0; }; g["Parameters"] = [](const SemanticValues &vs) { return vs.transform<std::string>(); }; g["Arguments"] = [](const SemanticValues &vs) { return vs.transform<std::shared_ptr<Ope>>(); }; g["PrecedenceClimbing"] = [](const SemanticValues &vs) { PrecedenceClimbing::BinOpeInfo binOpeInfo; size_t level = 1; for (auto v : vs) { auto tokens = std::any_cast<std::vector<std::string_view>>(v); auto assoc = tokens[0][0]; for (size_t i = 1; i < tokens.size(); i++) { binOpeInfo[tokens[i]] = std::pair(level, assoc); } level++; } Instruction instruction; instruction.type = "precedence"; instruction.data = binOpeInfo; return instruction; }; g["PrecedenceInfo"] = [](const SemanticValues &vs) { return vs.transform<std::string_view>(); }; g["PrecedenceOpe"] = [](const SemanticValues &vs) { return vs.token(); }; g["PrecedenceAssoc"] = [](const SemanticValues &vs) { return vs.token(); }; g["ErrorMessage"] = [](const SemanticValues &vs) { Instruction instruction; instruction.type = "message"; instruction.data = std::any_cast<std::string>(vs[0]); return instruction; }; g["NoAstOpt"] = [](const SemanticValues & /*vs*/) { Instruction instruction; instruction.type = "no_ast_opt"; return instruction; }; } bool apply_precedence_instruction(Definition &rule, const PrecedenceClimbing::BinOpeInfo &info, const char *s, Log log) { try { auto &seq = dynamic_cast<Sequence &>(*rule.get_core_operator()); auto atom = seq.opes_[0]; auto &rep = dynamic_cast<Repetition &>(*seq.opes_[1]); auto &seq1 = dynamic_cast<Sequence &>(*rep.ope_); auto binop = seq1.opes_[0]; auto atom1 = seq1.opes_[1]; auto atom_name = dynamic_cast<Reference &>(*atom).name_; auto binop_name = dynamic_cast<Reference &>(*binop).name_; auto atom1_name = dynamic_cast<Reference &>(*atom1).name_; if (!rep.is_zom() || atom_name != atom1_name || atom_name == binop_name) { if (log) { auto line = line_info(s, rule.s_); log(line.first, line.second, "'precedence' instruction cannot be applied to '" + rule.name + "'."); } return false; } rule.holder_->ope_ = pre(atom, binop, info, rule); rule.disable_action = true; } catch (...) { if (log) { auto line = line_info(s, rule.s_); log(line.first, line.second, "'precedence' instruction cannot be applied to '" + rule.name + "'."); } return false; } return true; } std::shared_ptr<Grammar> perform_core(const char *s, size_t n, const Rules &rules, std::string &start, bool &enablePackratParsing, Log log) { Data data; auto &grammar = *data.grammar; // Built-in macros { // `%recover` { auto &rule = grammar[RECOVER_DEFINITION_NAME]; rule <= ref(grammar, "x", "", false, {}); rule.name = RECOVER_DEFINITION_NAME; rule.s_ = "[native]"; rule.ignoreSemanticValue = true; rule.is_macro = true; rule.params = {"x"}; } } std::any dt = &data; auto r = g["Grammar"].parse(s, n, dt, nullptr, log); if (!r.ret) { if (log) { if (r.error_info.message_pos) { auto line = line_info(s, r.error_info.message_pos); log(line.first, line.second, r.error_info.message); } else { auto line = line_info(s, r.error_info.error_pos); log(line.first, line.second, "syntax error"); } } return nullptr; } // User provided rules for (auto [user_name, user_rule] : rules) { auto name = user_name; auto ignore = false; if (!name.empty() && name[0] == '~') { ignore = true; name.erase(0, 1); } if (!name.empty()) { auto &rule = grammar[name]; rule <= user_rule; rule.name = name; rule.ignoreSemanticValue = ignore; } } // Check duplicated definitions auto ret = data.duplicates.empty(); for (const auto &[name, ptr] : data.duplicates) { if (log) { auto line = line_info(s, ptr); log(line.first, line.second, "'" + name + "' is already defined."); } } // Set root definition auto &start_rule = grammar[data.start]; // Check if the start rule has ignore operator { if (start_rule.ignoreSemanticValue) { if (log) { auto line = line_info(s, start_rule.s_); log(line.first, line.second, "Ignore operator cannot be applied to '" + start_rule.name + "'."); } ret = false; } } if (!ret) { return nullptr; } // Check missing definitions auto referenced = std::unordered_set<std::string>{ WHITESPACE_DEFINITION_NAME, WORD_DEFINITION_NAME, RECOVER_DEFINITION_NAME, start_rule.name, }; for (auto &[_, rule] : grammar) { ReferenceChecker vis(grammar, rule.params); rule.accept(vis); referenced.insert(vis.referenced.begin(), vis.referenced.end()); for (const auto &[name, ptr] : vis.error_s) { if (log) { auto line = line_info(s, ptr); log(line.first, line.second, vis.error_message[name]); } ret = false; } } for (auto &[name, rule] : grammar) { if (!referenced.count(name)) { if (log) { auto line = line_info(s, rule.s_); auto msg = "'" + name + "' is not referenced."; log(line.first, line.second, msg); } } } if (!ret) { return nullptr; } // Link references for (auto &x : grammar) { auto &rule = x.second; LinkReferences vis(grammar, rule.params); rule.accept(vis); } // Check left recursion ret = true; for (auto &[name, rule] : grammar) { DetectLeftRecursion vis(name); rule.accept(vis); if (vis.error_s) { if (log) { auto line = line_info(s, vis.error_s); log(line.first, line.second, "'" + name + "' is left recursive."); } ret = false; } } if (!ret) { return nullptr; } // Check infinite loop { DetectInfiniteLoop vis(data.start_pos, data.start); start_rule.accept(vis); if (vis.has_error) { if (log) { auto line = line_info(s, vis.error_s); log(line.first, line.second, "infinite loop is detected in '" + vis.error_name + "'."); } return nullptr; } } // Automatic whitespace skipping if (grammar.count(WHITESPACE_DEFINITION_NAME)) { for (auto &x : grammar) { auto &rule = x.second; auto ope = rule.get_core_operator(); if (IsLiteralToken::check(*ope)) { rule <= tok(ope); } } start_rule.whitespaceOpe = wsp(grammar[WHITESPACE_DEFINITION_NAME].get_core_operator()); } // Word expression if (grammar.count(WORD_DEFINITION_NAME)) { start_rule.wordOpe = grammar[WORD_DEFINITION_NAME].get_core_operator(); } // Apply instructions for (const auto &[name, instruction] : data.instructions) { auto &rule = grammar[name]; if (instruction.type == "precedence") { const auto &info = std::any_cast<PrecedenceClimbing::BinOpeInfo>(instruction.data); if (!apply_precedence_instruction(rule, info, s, log)) { return nullptr; } } else if (instruction.type == "message") { rule.error_message = std::any_cast<std::string>(instruction.data); } else if (instruction.type == "no_ast_opt") { rule.no_ast_opt = true; } } // Set root definition start = data.start; enablePackratParsing = data.enablePackratParsing; return data.grammar; } Grammar g; }; /*----------------------------------------------------------------------------- * AST *---------------------------------------------------------------------------*/ template <typename Annotation> struct AstBase : public Annotation { AstBase(const char *path, size_t line, size_t column, const char *name, const std::vector<std::shared_ptr<AstBase>> &nodes, size_t position = 0, size_t length = 0, size_t choice_count = 0, size_t choice = 0) : path(path ? path : ""), line(line), column(column), name(name), position(position), length(length), choice_count(choice_count), choice(choice), original_name(name), original_choice_count(choice_count), original_choice(choice), tag(str2tag(name)), original_tag(tag), is_token(false), nodes(nodes) {} AstBase(const char *path, size_t line, size_t column, const char *name, const std::string_view &token, size_t position = 0, size_t length = 0, size_t choice_count = 0, size_t choice = 0) : path(path ? path : ""), line(line), column(column), name(name), position(position), length(length), choice_count(choice_count), choice(choice), original_name(name), original_choice_count(choice_count), original_choice(choice), tag(str2tag(name)), original_tag(tag), is_token(true), token(token) {} AstBase(const AstBase &ast, const char *original_name, size_t position = 0, size_t length = 0, size_t original_choice_count = 0, size_t original_choise = 0) : path(ast.path), line(ast.line), column(ast.column), name(ast.name), position(position), length(length), choice_count(ast.choice_count), choice(ast.choice), original_name(original_name), original_choice_count(original_choice_count), original_choice(original_choise), tag(ast.tag), original_tag(str2tag(original_name)), is_token(ast.is_token), token(ast.token), nodes(ast.nodes), parent(ast.parent) {} const std::string path; const size_t line = 1; const size_t column = 1; const std::string name; size_t position; size_t length; const size_t choice_count; const size_t choice; const std::string original_name; const size_t original_choice_count; const size_t original_choice; const unsigned int tag; const unsigned int original_tag; const bool is_token; const std::string_view token; std::vector<std::shared_ptr<AstBase<Annotation>>> nodes; std::weak_ptr<AstBase<Annotation>> parent; std::string token_to_string() const { assert(is_token); return std::string(token); } template <typename T> T token_to_number() const { return token_to_number_<T>(token); } }; template <typename T> void ast_to_s_core(const std::shared_ptr<T> &ptr, std::string &s, int level, std::function<std::string(const T &ast, int level)> fn) { const auto &ast = *ptr; for (auto i = 0; i < level; i++) { s += " "; } auto name = ast.original_name; if (ast.original_choice_count > 0) { name += "/" + std::to_string(ast.original_choice); } if (ast.name != ast.original_name) { name += "[" + ast.name + "]"; } if (ast.is_token) { s += "- " + name + " ("; s += ast.token; s += ")\n"; } else { s += "+ " + name + "\n"; } if (fn) { s += fn(ast, level + 1); } for (auto node : ast.nodes) { ast_to_s_core(node, s, level + 1, fn); } } template <typename T> std::string ast_to_s(const std::shared_ptr<T> &ptr, std::function<std::string(const T &ast, int level)> fn = nullptr) { std::string s; ast_to_s_core(ptr, s, 0, fn); return s; } struct AstOptimizer { AstOptimizer(bool mode, const std::vector<std::string> &rules = {}) : mode_(mode), rules_(rules) {} template <typename T> std::shared_ptr<T> optimize(std::shared_ptr<T> original, std::shared_ptr<T> parent = nullptr) { auto found = std::find(rules_.begin(), rules_.end(), original->name) != rules_.end(); bool opt = mode_ ? !found : found; if (opt && original->nodes.size() == 1) { auto child = optimize(original->nodes[0], parent); return std::make_shared<T>(*child, original->name.data(), original->choice_count, original->position, original->length, original->choice); } auto ast = std::make_shared<T>(*original); ast->parent = parent; ast->nodes.clear(); for (auto node : original->nodes) { auto child = optimize(node, ast); ast->nodes.push_back(child); } return ast; } private: const bool mode_; const std::vector<std::string> rules_; }; struct EmptyType {}; using Ast = AstBase<EmptyType>; template <typename T = Ast> void add_ast_action(Definition &rule) { rule.action = [&](const SemanticValues &vs) { auto line = vs.line_info(); if (rule.is_token()) { return std::make_shared<T>( vs.path, line.first, line.second, rule.name.data(), vs.token(), std::distance(vs.ss, vs.sv().data()), vs.sv().length(), vs.choice_count(), vs.choice()); } auto ast = std::make_shared<T>(vs.path, line.first, line.second, rule.name.data(), vs.transform<std::shared_ptr<T>>(), std::distance(vs.ss, vs.sv().data()), vs.sv().length(), vs.choice_count(), vs.choice()); for (auto node : ast->nodes) { node->parent = ast; } return ast; }; } #define PEG_EXPAND(...) __VA_ARGS__ #define PEG_CONCAT(a, b) a##b #define PEG_CONCAT2(a, b) PEG_CONCAT(a, b) #define PEG_PICK( \ a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, \ a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, \ a32, a33, a34, a35, a36, a37, a38, a39, a40, a41, a42, a43, a44, a45, a46, \ a47, a48, a49, a50, a51, a52, a53, a54, a55, a56, a57, a58, a59, a60, a61, \ a62, a63, a64, a65, a66, a67, a68, a69, a70, a71, a72, a73, a74, a75, a76, \ a77, a78, a79, a80, a81, a82, a83, a84, a85, a86, a87, a88, a89, a90, a91, \ a92, a93, a94, a95, a96, a97, a98, a99, a100, ...) \ a100 #define PEG_COUNT(...) \ PEG_EXPAND(PEG_PICK( \ __VA_ARGS__, 100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, \ 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, \ 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, \ 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, \ 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, \ 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)) #define PEG_DEF_1(r) \ peg::Definition r; \ r.name = #r; \ peg::add_ast_action(r); #define PEG_DEF_2(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_1(__VA_ARGS__)) #define PEG_DEF_3(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_2(__VA_ARGS__)) #define PEG_DEF_4(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_3(__VA_ARGS__)) #define PEG_DEF_5(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_4(__VA_ARGS__)) #define PEG_DEF_6(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_5(__VA_ARGS__)) #define PEG_DEF_7(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_6(__VA_ARGS__)) #define PEG_DEF_8(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_7(__VA_ARGS__)) #define PEG_DEF_9(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_8(__VA_ARGS__)) #define PEG_DEF_10(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_9(__VA_ARGS__)) #define PEG_DEF_11(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_10(__VA_ARGS__)) #define PEG_DEF_12(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_11(__VA_ARGS__)) #define PEG_DEF_13(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_12(__VA_ARGS__)) #define PEG_DEF_14(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_13(__VA_ARGS__)) #define PEG_DEF_15(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_14(__VA_ARGS__)) #define PEG_DEF_16(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_15(__VA_ARGS__)) #define PEG_DEF_17(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_16(__VA_ARGS__)) #define PEG_DEF_18(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_17(__VA_ARGS__)) #define PEG_DEF_19(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_18(__VA_ARGS__)) #define PEG_DEF_20(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_19(__VA_ARGS__)) #define PEG_DEF_21(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_20(__VA_ARGS__)) #define PEG_DEF_22(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_21(__VA_ARGS__)) #define PEG_DEF_23(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_22(__VA_ARGS__)) #define PEG_DEF_24(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_23(__VA_ARGS__)) #define PEG_DEF_25(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_24(__VA_ARGS__)) #define PEG_DEF_26(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_25(__VA_ARGS__)) #define PEG_DEF_27(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_26(__VA_ARGS__)) #define PEG_DEF_28(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_27(__VA_ARGS__)) #define PEG_DEF_29(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_28(__VA_ARGS__)) #define PEG_DEF_30(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_29(__VA_ARGS__)) #define PEG_DEF_31(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_30(__VA_ARGS__)) #define PEG_DEF_32(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_31(__VA_ARGS__)) #define PEG_DEF_33(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_32(__VA_ARGS__)) #define PEG_DEF_34(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_33(__VA_ARGS__)) #define PEG_DEF_35(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_34(__VA_ARGS__)) #define PEG_DEF_36(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_35(__VA_ARGS__)) #define PEG_DEF_37(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_36(__VA_ARGS__)) #define PEG_DEF_38(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_37(__VA_ARGS__)) #define PEG_DEF_39(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_38(__VA_ARGS__)) #define PEG_DEF_40(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_39(__VA_ARGS__)) #define PEG_DEF_41(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_40(__VA_ARGS__)) #define PEG_DEF_42(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_41(__VA_ARGS__)) #define PEG_DEF_43(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_42(__VA_ARGS__)) #define PEG_DEF_44(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_43(__VA_ARGS__)) #define PEG_DEF_45(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_44(__VA_ARGS__)) #define PEG_DEF_46(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_45(__VA_ARGS__)) #define PEG_DEF_47(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_46(__VA_ARGS__)) #define PEG_DEF_48(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_47(__VA_ARGS__)) #define PEG_DEF_49(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_48(__VA_ARGS__)) #define PEG_DEF_50(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_49(__VA_ARGS__)) #define PEG_DEF_51(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_50(__VA_ARGS__)) #define PEG_DEF_52(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_51(__VA_ARGS__)) #define PEG_DEF_53(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_52(__VA_ARGS__)) #define PEG_DEF_54(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_53(__VA_ARGS__)) #define PEG_DEF_55(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_54(__VA_ARGS__)) #define PEG_DEF_56(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_55(__VA_ARGS__)) #define PEG_DEF_57(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_56(__VA_ARGS__)) #define PEG_DEF_58(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_57(__VA_ARGS__)) #define PEG_DEF_59(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_58(__VA_ARGS__)) #define PEG_DEF_60(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_59(__VA_ARGS__)) #define PEG_DEF_61(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_60(__VA_ARGS__)) #define PEG_DEF_62(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_61(__VA_ARGS__)) #define PEG_DEF_63(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_62(__VA_ARGS__)) #define PEG_DEF_64(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_63(__VA_ARGS__)) #define PEG_DEF_65(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_64(__VA_ARGS__)) #define PEG_DEF_66(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_65(__VA_ARGS__)) #define PEG_DEF_67(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_66(__VA_ARGS__)) #define PEG_DEF_68(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_67(__VA_ARGS__)) #define PEG_DEF_69(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_68(__VA_ARGS__)) #define PEG_DEF_70(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_69(__VA_ARGS__)) #define PEG_DEF_71(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_70(__VA_ARGS__)) #define PEG_DEF_72(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_71(__VA_ARGS__)) #define PEG_DEF_73(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_72(__VA_ARGS__)) #define PEG_DEF_74(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_73(__VA_ARGS__)) #define PEG_DEF_75(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_74(__VA_ARGS__)) #define PEG_DEF_76(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_75(__VA_ARGS__)) #define PEG_DEF_77(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_76(__VA_ARGS__)) #define PEG_DEF_78(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_77(__VA_ARGS__)) #define PEG_DEF_79(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_78(__VA_ARGS__)) #define PEG_DEF_80(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_79(__VA_ARGS__)) #define PEG_DEF_81(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_80(__VA_ARGS__)) #define PEG_DEF_82(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_81(__VA_ARGS__)) #define PEG_DEF_83(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_82(__VA_ARGS__)) #define PEG_DEF_84(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_83(__VA_ARGS__)) #define PEG_DEF_85(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_84(__VA_ARGS__)) #define PEG_DEF_86(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_85(__VA_ARGS__)) #define PEG_DEF_87(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_86(__VA_ARGS__)) #define PEG_DEF_88(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_87(__VA_ARGS__)) #define PEG_DEF_89(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_88(__VA_ARGS__)) #define PEG_DEF_90(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_89(__VA_ARGS__)) #define PEG_DEF_91(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_90(__VA_ARGS__)) #define PEG_DEF_92(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_91(__VA_ARGS__)) #define PEG_DEF_93(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_92(__VA_ARGS__)) #define PEG_DEF_94(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_93(__VA_ARGS__)) #define PEG_DEF_95(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_94(__VA_ARGS__)) #define PEG_DEF_96(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_95(__VA_ARGS__)) #define PEG_DEF_97(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_96(__VA_ARGS__)) #define PEG_DEF_98(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_97(__VA_ARGS__)) #define PEG_DEF_99(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_98(__VA_ARGS__)) #define PEG_DEF_100(r1, ...) PEG_EXPAND(PEG_DEF_1(r1) PEG_DEF_99(__VA_ARGS__)) #define AST_DEFINITIONS(...) \ PEG_EXPAND(PEG_CONCAT2(PEG_DEF_, PEG_COUNT(__VA_ARGS__))(__VA_ARGS__)) /*----------------------------------------------------------------------------- * parser *---------------------------------------------------------------------------*/ class parser { public: parser() = default; parser(const char *s, size_t n, const Rules &rules) { load_grammar(s, n, rules); } parser(std::string_view sv, const Rules &rules) : parser(sv.data(), sv.size(), rules) {} parser(const char *s, size_t n) : parser(s, n, Rules()) {} parser(std::string_view sv) : parser(sv.data(), sv.size(), Rules()) {} operator bool() { return grammar_ != nullptr; } bool load_grammar(const char *s, size_t n, const Rules &rules) { grammar_ = ParserGenerator::parse(s, n, rules, start_, enablePackratParsing_, log); return grammar_ != nullptr; } bool load_grammar(const char *s, size_t n) { return load_grammar(s, n, Rules()); } bool load_grammar(std::string_view sv, const Rules &rules) { return load_grammar(sv.data(), sv.size(), rules); } bool load_grammar(std::string_view sv) { return load_grammar(sv.data(), sv.size()); } bool parse_n(const char *s, size_t n, const char *path = nullptr) const { if (grammar_ != nullptr) { const auto &rule = (*grammar_)[start_]; return post_process(s, n, rule.parse(s, n, path, log)); } return false; } bool parse(std::string_view sv, const char *path = nullptr) const { return parse_n(sv.data(), sv.size(), path); } bool parse_n(const char *s, size_t n, std::any &dt, const char *path = nullptr) const { if (grammar_ != nullptr) { const auto &rule = (*grammar_)[start_]; return post_process(s, n, rule.parse(s, n, dt, path, log)); } return false; } bool parse(std::string_view sv, std::any &dt, const char *path = nullptr) const { return parse_n(sv.data(), sv.size(), dt, path); } template <typename T> bool parse_n(const char *s, size_t n, T &val, const char *path = nullptr) const { if (grammar_ != nullptr) { const auto &rule = (*grammar_)[start_]; return post_process(s, n, rule.parse_and_get_value(s, n, val, path, log)); } return false; } template <typename T> bool parse(std::string_view sv, T &val, const char *path = nullptr) const { return parse_n(sv.data(), sv.size(), val, path); } template <typename T> bool parse_n(const char *s, size_t n, std::any &dt, T &val, const char *path = nullptr) const { if (grammar_ != nullptr) { const auto &rule = (*grammar_)[start_]; return post_process(s, n, rule.parse_and_get_value(s, n, dt, val, path, log)); } return false; } template <typename T> bool parse(const char *s, std::any &dt, T &val, const char *path = nullptr) const { auto n = strlen(s); return parse_n(s, n, dt, val, path); } Definition &operator[](const char *s) { return (*grammar_)[s]; } const Definition &operator[](const char *s) const { return (*grammar_)[s]; } std::vector<std::string> get_rule_names() const { std::vector<std::string> rules; for (auto &[name, _] : *grammar_) { rules.push_back(name); } return rules; } void enable_packrat_parsing() { if (grammar_ != nullptr) { auto &rule = (*grammar_)[start_]; rule.enablePackratParsing = enablePackratParsing_ && true; } } void enable_trace(TracerEnter tracer_enter, TracerLeave tracer_leave) { if (grammar_ != nullptr) { auto &rule = (*grammar_)[start_]; rule.tracer_enter = tracer_enter; rule.tracer_leave = tracer_leave; } } template <typename T = Ast> parser &enable_ast() { for (auto &[_, rule] : *grammar_) { if (!rule.action) { add_ast_action<T>(rule); } } return *this; } template <typename T> std::shared_ptr<T> optimize_ast(std::shared_ptr<T> ast, bool opt_mode = true) const { return AstOptimizer(opt_mode, get_no_ast_opt_rules()).optimize(ast); } Log log; private: bool post_process(const char *s, size_t n, const Definition::Result &r) const { auto ret = r.ret && r.len == n; if (log && !ret) { r.error_info.output_log(log, s, n); } return ret && !r.recovered; } std::vector<std::string> get_no_ast_opt_rules() const { std::vector<std::string> rules; for (auto &[name, rule] : *grammar_) { if (rule.no_ast_opt) { rules.push_back(name); } } return rules; } std::shared_ptr<Grammar> grammar_; std::string start_; bool enablePackratParsing_ = false; }; } // namespace peg
yhirose/cpp-searchlib
33
A C++17 full-text search engine library
C++
yhirose
src/lib/unicodelib_encodings.h
C/C++ Header
// // unicodelib_encodings.h // // Copyright (c) 2020 Yuji Hirose. All rights reserved. // MIT License // #pragma once #include <cstdlib> #include <string> #if !defined(__cplusplus) || __cplusplus < 201703L #error "Requires complete C++17 support" #endif /* namespace utf8 { size_t codepoint_length(char32_t cp); size_t codepoint_length(const char *s8, size_t l); size_t codepoint_count(const char *s8, size_t l); size_t encode_codepoint(char32_t cp, std::string &out); void encode(const char32_t *s32, size_t l, std::string &out); size_t decode_codepoint(const char *s8, size_t l, char32_t &out); void decode(const char *s8, size_t l, std::u32string &out); } // namespace utf8 namespace utf16 { size_t codepoint_length(char32_t cp); size_t codepoint_length(const char16_t *s16, size_t l); size_t codepoint_count(const char16_t *s16, size_t l); size_t encode_codepoint(char32_t cp, std::u16string &out); void encode(const char32_t *s32, size_t l, std::u16string &out); size_t decode_codepoint(const char16_t *s16, size_t l, char32_t &out); void decode(const char16_t *s16, size_t l, std::u32string &out); } // namespace utf16 std::string to_utf8(const char16_t *s16, size_t l); std::u16string to_utf16(const char *s8, size_t l); std::wstring to_wstring(const char *s8, size_t l); std::wstring to_wstring(const char16_t *s16, size_t l); std::wstring to_wstring(const char32_t *s32, size_t l); std::string to_utf8(const wchar_t *sw, size_t l); std::u16string to_utf16(const wchar_t *sw, size_t l); std::u32string to_utf32(const wchar_t *sw, size_t l); */ namespace unicode { //----------------------------------------------------------------------------- // UTF8 encoding //----------------------------------------------------------------------------- namespace utf8 { inline size_t codepoint_length(char32_t cp) { if (cp < 0x0080) { return 1; } else if (cp < 0x0800) { return 2; } else if (cp < 0xD800) { return 3; } else if (cp < 0xe000) { // D800 - DFFF is invalid... return 0; } else if (cp < 0x10000) { return 3; } else if (cp < 0x110000) { return 4; } return 0; } inline size_t codepoint_length(const char *s8, size_t l) { if (l) { uint8_t b = s8[0]; if ((b & 0x80) == 0) { return 1; } else if ((b & 0xE0) == 0xC0) { return 2; } else if ((b & 0xF0) == 0xE0) { return 3; } else if ((b & 0xF8) == 0xF0) { return 4; } } return 0; } inline size_t codepoint_count(const char *s8, size_t l) { size_t count = 0; for (size_t i = 0; i < l; i += codepoint_length(s8 + i, l - i)) { count++; } return count; } inline size_t encode_codepoint(char32_t cp, char *buff) { if (cp < 0x0080) { buff[0] = static_cast<uint8_t>(cp & 0x7F); return 1; } else if (cp < 0x0800) { buff[0] = static_cast<uint8_t>(0xC0 | ((cp >> 6) & 0x1F)); buff[1] = static_cast<uint8_t>(0x80 | (cp & 0x3F)); return 2; } else if (cp < 0xD800) { buff[0] = static_cast<uint8_t>(0xE0 | ((cp >> 12) & 0xF)); buff[1] = static_cast<uint8_t>(0x80 | ((cp >> 6) & 0x3F)); buff[2] = static_cast<uint8_t>(0x80 | (cp & 0x3F)); return 3; } else if (cp < 0xE000) { // D800 - DFFF is invalid... return 0; } else if (cp < 0x10000) { buff[0] = static_cast<uint8_t>(0xE0 | ((cp >> 12) & 0xF)); buff[1] = static_cast<uint8_t>(0x80 | ((cp >> 6) & 0x3F)); buff[2] = static_cast<uint8_t>(0x80 | (cp & 0x3F)); return 3; } else if (cp < 0x110000) { buff[0] = static_cast<uint8_t>(0xF0 | ((cp >> 18) & 0x7)); buff[1] = static_cast<uint8_t>(0x80 | ((cp >> 12) & 0x3F)); buff[2] = static_cast<uint8_t>(0x80 | ((cp >> 6) & 0x3F)); buff[3] = static_cast<uint8_t>(0x80 | (cp & 0x3F)); return 4; } return 0; } inline size_t encode_codepoint(char32_t cp, std::string &out) { char buff[4]; auto l = encode_codepoint(cp, buff); out.append(buff, l); return l; } inline void encode(const char32_t *s32, size_t l, std::string &out) { for (size_t i = 0; i < l; i++) { encode_codepoint(s32[i], out); } } inline bool decode_codepoint(const char *s8, size_t l, size_t &bytes, char32_t &cp) { if (l) { uint8_t b = s8[0]; if ((b & 0x80) == 0) { bytes = 1; cp = b; return true; } else if ((b & 0xE0) == 0xC0) { if (l >= 2) { bytes = 2; cp = ((static_cast<char32_t>(s8[0] & 0x1F)) << 6) | (static_cast<char32_t>(s8[1] & 0x3F)); return true; } } else if ((b & 0xF0) == 0xE0) { if (l >= 3) { bytes = 3; cp = ((static_cast<char32_t>(s8[0] & 0x0F)) << 12) | ((static_cast<char32_t>(s8[1] & 0x3F)) << 6) | (static_cast<char32_t>(s8[2] & 0x3F)); return true; } } else if ((b & 0xF8) == 0xF0) { if (l >= 4) { bytes = 4; cp = ((static_cast<char32_t>(s8[0] & 0x07)) << 18) | ((static_cast<char32_t>(s8[1] & 0x3F)) << 12) | ((static_cast<char32_t>(s8[2] & 0x3F)) << 6) | (static_cast<char32_t>(s8[3] & 0x3F)); return true; } } } return false; } inline size_t decode_codepoint(const char *s8, size_t l, char32_t &out) { size_t bytes; if (decode_codepoint(s8, l, bytes, out)) { return bytes; } return 0; } template <typename T> inline void for_each(const char *s8, size_t l, T callback) { size_t id = 0; size_t i = 0; while (i < l) { auto beg = i++; while (i < l && (s8[i] & 0xc0) == 0x80) { i++; } callback(s8, l, beg, i, id++); } } inline void decode(const char *s8, size_t l, std::u32string &out) { for_each(s8, l, [&](const char *s, size_t /*l*/, size_t beg, size_t end, size_t /*i*/) { size_t bytes; char32_t cp; decode_codepoint(&s[beg], (end - beg), bytes, cp); out += cp; }); } } // namespace utf8 //----------------------------------------------------------------------------- // UTF16 encoding //----------------------------------------------------------------------------- namespace utf16 { inline bool is_surrogate_pair(const char16_t *s16, size_t l) { if (l > 0) { auto first = s16[0]; if (0xD800 <= first && first < 0xDC00) { auto second = s16[1]; if (0xDC00 <= second && second < 0xE000) { return true; } } } return false; } inline size_t codepoint_length(char32_t cp) { return cp <= 0xFFFF ? 1 : 2; } inline size_t codepoint_length(const char16_t *s16, size_t l) { if (l > 0) { if (is_surrogate_pair(s16, l)) { return 2; } return 1; } return 0; } inline size_t codepoint_count(const char16_t *s16, size_t l) { size_t count = 0; for (size_t i = 0; i < l; i += codepoint_length(s16 + i, l - i)) { count++; } return count; } inline size_t encode_codepoint(char32_t cp, char16_t *buff) { if (cp < 0xD800) { buff[0] = static_cast<char16_t>(cp); return 1; } else if (cp < 0xE000) { // D800 - DFFF is invalid... return 0; } else if (cp < 0x10000) { buff[0] = static_cast<char16_t>(cp); return 1; } else if (cp < 0x110000) { // high surrogate buff[0] = static_cast<char16_t>(0xD800 + (((cp - 0x10000) >> 10) & 0x3FF)); // low surrogate buff[1] = static_cast<char16_t>(0xDC00 + ((cp - 0x10000) & 0x3FF)); return 2; } return 0; } inline size_t encode_codepoint(char32_t cp, std::u16string &out) { char16_t buff[2]; auto l = encode_codepoint(cp, buff); out.append(buff, l); return l; } inline void encode(const char32_t *s32, size_t l, std::u16string &out) { for (size_t i = 0; i < l; i++) { encode_codepoint(s32[i], out); } } inline bool decode_codepoint(const char16_t *s16, size_t l, size_t &length, char32_t &cp) { if (l) { // Surrogate auto first = s16[0]; if (0xD800 <= first && first < 0xDC00) { if (l >= 2) { auto second = s16[1]; if (0xDC00 <= second && second < 0xE000) { cp = (((first - 0xD800) << 10) | (second - 0xDC00)) + 0x10000; length = 2; return true; } } } // Non surrogate else { cp = first; length = 1; return true; } } return false; } inline size_t decode_codepoint(const char16_t *s16, size_t l, char32_t &out) { size_t length; if (decode_codepoint(s16, l, length, out)) { return length; } return 0; } template <typename T> inline void for_each(const char16_t *s16, size_t l, T callback) { size_t id = 0; size_t i = 0; while (i < l) { auto beg = i++; if (is_surrogate_pair(&s16[beg], l - beg)) { i++; } callback(s16, l, beg, i, id++); } } inline void decode(const char16_t *s16, size_t l, std::u32string &out) { for_each(s16, l, [&](const char16_t *s, size_t /*l*/, size_t beg, size_t end, size_t /*i*/) { size_t length; char32_t cp; decode_codepoint(&s[beg], (end - beg), length, cp); out += cp; }); } } // namespace utf16 //----------------------------------------------------------------------------- // Inline Wrapper functions //----------------------------------------------------------------------------- namespace utf8 { inline size_t codepoint_length(std::string_view s8) { return codepoint_length(s8.data(), s8.length()); } inline size_t codepoint_count(std::string_view s8) { return codepoint_count(s8.data(), s8.length()); } inline std::string encode_codepoint(char32_t cp) { std::string out; encode_codepoint(cp, out); return out; } inline void encode(std::u32string_view s32, std::string &out) { encode(s32.data(), s32.length(), out); } inline std::string encode(const char32_t *s32, size_t l) { std::string out; encode(s32, l, out); return out; } inline std::string encode(std::u32string_view s32) { return encode(s32.data(), s32.length()); } inline size_t decode_codepoint(std::string_view s8, char32_t &cp) { return decode_codepoint(s8.data(), s8.length(), cp); } inline char32_t decode_codepoint(const char *s8, size_t l) { char32_t out = 0; decode_codepoint(s8, l, out); return out; } inline char32_t decode_codepoint(std::string_view s8) { return decode_codepoint(s8.data(), s8.length()); } inline void decode(std::string_view s8, std::u32string &out) { decode(s8.data(), s8.length(), out); } inline std::u32string decode(const char *s8, size_t l) { std::u32string out; decode(s8, l, out); return out; } inline std::u32string decode(std::string_view s8) { return decode(s8.data(), s8.length()); } } // namespace utf8 namespace utf16 { inline size_t codepoint_length(std::u16string_view s16) { return codepoint_length(s16.data(), s16.length()); } inline size_t codepoint_count(std::u16string_view s16) { return codepoint_count(s16.data(), s16.length()); } inline std::u16string encode_codepoint(char32_t cp) { std::u16string out; encode_codepoint(cp, out); return out; } inline void encode(std::u32string_view s32, std::u16string &out) { encode(s32.data(), s32.length(), out); } inline std::u16string encode(const char32_t *s32, size_t l) { std::u16string out; encode(s32, l, out); return out; } inline std::u16string encode(std::u32string_view s32) { return encode(s32.data(), s32.length()); } inline size_t decode_codepoint(std::u16string_view s16, char32_t &cp) { return decode_codepoint(s16.data(), s16.length(), cp); } inline char32_t decode_codepoint(const char16_t *s16, size_t l) { char32_t out = 0; decode_codepoint(s16, l, out); return out; } inline char32_t decode_codepoint(std::u16string_view s16) { return decode_codepoint(s16.data(), s16.length()); } inline void decode(std::u16string_view s16, std::u32string &out) { decode(s16.data(), s16.length(), out); } inline std::u32string decode(const char16_t *s16, size_t l) { std::u32string out; decode(s16, l, out); return out; } inline std::u32string decode(std::u16string_view s16) { return decode(s16.data(), s16.length()); } } // namespace utf16 //----------------------------------------------------------------------------- // utf8/utf16 conversion //----------------------------------------------------------------------------- inline std::string to_utf8(const char16_t *s16, size_t l) { return utf8::encode(utf16::decode(s16, l)); } inline std::string to_utf8(std::u16string_view s16) { return to_utf8(s16.data(), s16.length()); } inline std::u16string to_utf16(const char *s8, size_t l) { return utf16::encode(utf8::decode(s8, l)); } inline std::u16string to_utf16(std::string_view s8) { return to_utf16(s8.data(), s8.length()); } //----------------------------------------------------------------------------- // std::wstring conversion //----------------------------------------------------------------------------- namespace detail { inline std::wstring to_wstring_core(const char *s8, size_t l) { if constexpr (sizeof(wchar_t) == 2) { auto s16 = utf16::encode(utf8::decode(s8, l)); return std::wstring(reinterpret_cast<const wchar_t *>(s16.data()), s16.length()); } else if constexpr (sizeof(wchar_t) == 4) { auto s32 = utf8::decode(s8, l); return std::wstring(reinterpret_cast<const wchar_t *>(s32.data()), s32.length()); } } inline std::wstring to_wstring_core(const char16_t *s16, size_t l) { if constexpr (sizeof(wchar_t) == 2) { return std::wstring(reinterpret_cast<const wchar_t *>(s16), l); } else if constexpr (sizeof(wchar_t) == 4) { auto s32 = utf16::decode(s16, l); return std::wstring(reinterpret_cast<const wchar_t *>(s32.data()), s32.length()); } } inline std::wstring to_wstring_core(const char32_t *s32, size_t l) { if constexpr (sizeof(wchar_t) == 2) { auto s16 = utf16::encode(s32, l); return std::wstring(reinterpret_cast<const wchar_t *>(s16.data()), s16.length()); } else if constexpr (sizeof(wchar_t) == 4) { return std::wstring(reinterpret_cast<const wchar_t *>(s32), l); } } inline std::string to_utf8_core(const wchar_t *sw, size_t l) { if constexpr (sizeof(wchar_t) == 2) { return utf8::encode( utf16::decode(reinterpret_cast<const char16_t *>(sw), l)); } else if constexpr (sizeof(wchar_t) == 4) { return utf8::encode(reinterpret_cast<const char32_t *>(sw), l); } } inline std::u16string to_utf16_core(const wchar_t *sw, size_t l) { if constexpr (sizeof(wchar_t) == 2) { return std::u16string(reinterpret_cast<const char16_t *>(sw), l); } else if constexpr (sizeof(wchar_t) == 4) { return utf16::encode(reinterpret_cast<const char32_t *>(sw), l); } } inline std::u32string to_utf32_core(const wchar_t *sw, size_t l) { if constexpr (sizeof(wchar_t) == 2) { return utf16::decode(reinterpret_cast<const char16_t *>(sw), l); } else if constexpr (sizeof(wchar_t) == 4) { return std::u32string(reinterpret_cast<const char32_t *>(sw), l); } } } // namespace detail inline std::wstring to_wstring(const char *s8, size_t l) { return detail::to_wstring_core(s8, l); } inline std::wstring to_wstring(std::string_view s8) { return to_wstring(s8.data(), s8.length()); } inline std::wstring to_wstring(const char16_t *s16, size_t l) { return detail::to_wstring_core(s16, l); } inline std::wstring to_wstring(std::u16string_view s16) { return to_wstring(s16.data(), s16.length()); } inline std::wstring to_wstring(const char32_t *s32, size_t l) { return detail::to_wstring_core(s32, l); } inline std::wstring to_wstring(std::u32string_view s32) { return to_wstring(s32.data(), s32.length()); } inline std::string to_utf8(const wchar_t *sw, size_t l) { return detail::to_utf8_core(sw, l); } inline std::string to_utf8(std::wstring_view sw) { return to_utf8(sw.data(), sw.length()); } inline std::u16string to_utf16(const wchar_t *sw, size_t l) { return detail::to_utf16_core(sw, l); } inline std::u16string to_utf16(std::wstring_view sw) { return to_utf16(sw.data(), sw.length()); } inline std::u32string to_utf32(const wchar_t *sw, size_t l) { return detail::to_utf32_core(sw, l); } inline std::u32string to_utf32(std::wstring_view sw) { return to_utf32(sw.data(), sw.length()); } } // namespace unicode // vim: et ts=2 sw=2 cin cino=\:0 ff=unix
yhirose/cpp-searchlib
33
A C++17 full-text search engine library
C++
yhirose
src/query.cpp
C++
// // query.cpp // // Copyright (c) 2021 Yuji Hirose. All rights reserved. // MIT License // #include "lib/peglib.h" #include "searchlib.h" #include "utils.h" namespace searchlib { std::optional<Expression> parse_query(const IInvertedIndex &inverted_index, Normalizer normalizer, std::string_view query) { static peg::parser parser(R"( ROOT <- OR? OR <- AND ('|' AND)* AND <- NEAR+ NEAR <- PRIMARY ('~' PRIMARY)* PRIMARY <- PHRASE / TERM / '(' OR ')' PHRASE <- '"' TERM+ '"' TERM <- < [a-zA-Z0-9-]+ > %whitespace <- [ \t]* )"); parser["ROOT"] = [&](const peg::SemanticValues &vs) -> std::optional<Expression> { if (!vs.empty()) { return std::any_cast<Expression>(vs[0]); } return std::nullopt; }; size_t DEFAULT_NEAR_SIZE = 4; auto list_handler = [&](Operation operation) { return [=](const peg::SemanticValues &vs) { if (vs.size() == 1) { return std::any_cast<Expression>(vs[0]); } return Expression{operation, std::u32string(), DEFAULT_NEAR_SIZE, vs.transform<Expression>()}; }; }; parser["OR"] = list_handler(Operation::Or); parser["AND"] = list_handler(Operation::And); parser["NEAR"] = list_handler(Operation::Near); parser["PHRASE"] = list_handler(Operation::Adjacent); parser["TERM"] = [&](const peg::SemanticValues &vs) { auto term = normalizer(u32(vs.token())); if (!inverted_index.term_exists(term)) { std::string msg = "invalid term '" + vs.token_to_string() + "'."; throw peg::parse_error(msg.c_str()); } return Expression{Operation::Term, term}; }; // parser.log = [](size_t line, size_t col, const std::string& msg) { // std::cerr << line << ":" << col << ": " << msg << "\n"; // }; std::optional<Expression> expr; if (!parser.parse(query, expr)) { return std::nullopt; } return *expr; } } // namespace searchlib
yhirose/cpp-searchlib
33
A C++17 full-text search engine library
C++
yhirose
src/search.cpp
C++
// // search.cpp // // Copyright (c) 2021 Yuji Hirose. All rights reserved. // MIT License // #include <array> #include <cassert> #include <iostream> #include <numeric> #include "./utils.h" #include "searchlib.h" namespace searchlib { class TermSearchResult : public IPostings { public: TermSearchResult(const IInvertedIndex &inverted_index, const std::u32string &str) : postings_(inverted_index.postings(str)) {} ~TermSearchResult() override = default; size_t size() const override { return postings_.size(); } size_t document_id(size_t index) const override { return postings_.document_id(index); } size_t search_hit_count(size_t index) const override { return postings_.search_hit_count(index); } size_t term_position(size_t index, size_t search_hit_index) const override { return postings_.term_position(index, search_hit_index); } size_t term_length(size_t index, size_t search_hit_index) const override { return 1; } bool is_term_position(size_t index, size_t term_pos) const override { return postings_.is_term_position(index, term_pos); } private: const IPostings &postings_; }; //----------------------------------------------------------------------------- class Position { public: Position(size_t document_id, std::vector<size_t> &&term_positions, std::vector<size_t> &&term_lengths) : document_id_(document_id), term_positions_(term_positions), term_lengths(term_lengths) {} ~Position() = default; size_t document_id() const { return document_id_; } size_t search_hit_count() const { return term_positions_.size(); } size_t term_position(size_t search_hit_index) const { return term_positions_[search_hit_index]; } size_t term_length(size_t search_hit_index) const { return term_lengths[search_hit_index]; } bool is_term_position(size_t term_pos) const { return std::binary_search(term_positions_.begin(), term_positions_.end(), term_pos); } private: size_t document_id_; std::vector<size_t> term_positions_; std::vector<size_t> term_lengths; }; class SearchResult : public IPostings { public: ~SearchResult() override = default; size_t size() const override { return positions_.size(); } size_t document_id(size_t index) const override { return positions_[index]->document_id(); } size_t search_hit_count(size_t index) const override { return positions_[index]->search_hit_count(); } size_t term_position(size_t index, size_t search_hit_index) const override { return positions_[index]->term_position(search_hit_index); } size_t term_length(size_t index, size_t search_hit_index) const override { return positions_[index]->term_length(search_hit_index); } bool is_term_position(size_t index, size_t term_pos) const override { return positions_[index]->is_term_position(term_pos); } void push_back(std::shared_ptr<Position> info) { positions_.push_back(std::move(info)); } private: std::vector<std::shared_ptr<Position>> positions_; }; //----------------------------------------------------------------------------- static auto positings_list(const IInvertedIndex &inverted_index, const std::vector<Expression> &nodes) { std::vector<std::shared_ptr<IPostings>> positings_list; for (const auto &expr : nodes) { positings_list.push_back(perform_search(inverted_index, expr)); } return positings_list; } static std::vector<size_t /*slot*/> min_slots(const std::vector<std::shared_ptr<IPostings>> &positings_list, const std::vector<size_t> &cursors) { std::vector<size_t> slots = {0}; for (size_t slot = 1; slot < positings_list.size(); slot++) { auto prev = positings_list[slots[0]]->document_id(cursors[slots[0]]); auto curr = positings_list[slot]->document_id(cursors[slot]); if (curr < prev) { slots.clear(); slots.push_back(slot); } else if (curr == prev) { slots.push_back(slot); } } return slots; } static std::pair<size_t /*min*/, size_t /*max*/> min_max_slots(const std::vector<std::shared_ptr<IPostings>> &positings_list, const std::vector<size_t> &cursors) { auto min = positings_list[0]->document_id(cursors[0]); auto max = min; for (size_t slot = 1; slot < positings_list.size(); slot++) { auto id = positings_list[slot]->document_id(cursors[slot]); if (id < min) { min = id; } else if (id > max) { max = id; } } return std::make_pair(min, max); } static bool skip_cursors(const std::vector<std::shared_ptr<IPostings>> &positings_list, std::vector<size_t> &cursors, size_t document_id) { for (size_t slot = 0; slot < positings_list.size(); slot++) { // TODO: skip list support while (cursors[slot] < positings_list[slot]->size()) { if (positings_list[slot]->document_id(cursors[slot]) >= document_id) { break; } cursors[slot]++; } if (cursors[slot] == positings_list[slot]->size()) { return true; } } return false; } static bool increment_all_cursors( const std::vector<std::shared_ptr<IPostings>> &positings_list, std::vector<size_t> &cursors) { for (size_t slot = 0; slot < positings_list.size(); slot++) { cursors[slot]++; if (cursors[slot] == positings_list[slot]->size()) { return true; } } return false; } static void increment_cursors(std::vector<std::shared_ptr<IPostings>> &positings_list, std::vector<size_t> &cursors, const std::vector<size_t> &slots) { for (int i = slots.size() - 1; i >= 0; i--) { auto slot = slots[i]; cursors[slot]++; if (cursors[slot] == positings_list[slot]->size()) { cursors.erase(cursors.begin() + slot); positings_list.erase(positings_list.begin() + slot); } } } static size_t shortest_slot(const std::vector<std::shared_ptr<IPostings>> &positings_list, const std::vector<size_t> &cursors) { size_t shortest_slot = 0; auto shortest_count = positings_list[shortest_slot]->search_hit_count(cursors[shortest_slot]); for (size_t slot = 1; slot < positings_list.size(); slot++) { auto count = positings_list[slot]->search_hit_count(cursors[slot]); if (count < shortest_count) { shortest_slot = slot; shortest_count = count; } } return shortest_slot; } static bool is_adjacent(const std::vector<std::shared_ptr<IPostings>> &positings_list, const std::vector<size_t> &cursors, size_t target_slot, size_t term_pos) { auto ret = true; for (size_t slot = 0; ret && slot < positings_list.size(); slot++) { if (slot == target_slot) { continue; } auto delta = slot - target_slot; auto next_term_pos = term_pos + delta; ret = positings_list[slot]->is_term_position(cursors[slot], next_term_pos); } return ret; } template <typename T> static std::shared_ptr<IPostings> intersect_postings( const std::vector<std::shared_ptr<IPostings>> &positings_list, T make_positions) { auto result = std::make_shared<SearchResult>(); std::vector<size_t> cursors(positings_list.size(), 0); auto done = false; while (!done) { auto [min, max] = min_max_slots(positings_list, cursors); if (min == max) { auto positions = make_positions(positings_list, cursors); if (positions) { result->push_back(positions); } done = increment_all_cursors(positings_list, cursors); } else { done = skip_cursors(positings_list, cursors, max); } } return result; } static void merge_term_positions( const std::vector<std::shared_ptr<IPostings>> &positings_list, const std::vector<size_t> &cursors, const std::vector<size_t> &slots, std::vector<size_t> &term_positions, std::vector<size_t> &term_lengths) { std::vector<size_t> search_hit_cursors(positings_list.size(), 0); while (true) { size_t min_slot = -1; size_t min_term_pos = -1; size_t min_term_length = -1; // TODO: improve performance by reducing slots for (auto slot : slots) { auto index = cursors[slot]; auto p = positings_list[slot]; auto hit_index = search_hit_cursors[slot]; if (hit_index < p->search_hit_count(index)) { auto term_pos = p->term_position(index, hit_index); auto term_length = p->term_length(index, hit_index); if (term_pos < min_term_pos) { min_slot = slot; min_term_pos = term_pos; min_term_length = term_length; } } } if (min_slot == -1) { break; } term_positions.push_back(min_term_pos); term_lengths.push_back(min_term_length); search_hit_cursors[min_slot]++; } } static std::shared_ptr<IPostings> union_postings(std::vector<std::shared_ptr<IPostings>> &&positings_list) { auto result = std::make_shared<SearchResult>(); std::vector<size_t> cursors(positings_list.size(), 0); while (!positings_list.empty()) { auto slots = min_slots(positings_list, cursors); std::vector<size_t> term_positions; std::vector<size_t> term_lengths; merge_term_positions(positings_list, cursors, slots, term_positions, term_lengths); result->push_back(std::make_shared<Position>( positings_list[slots[0]]->document_id(cursors[slots[0]]), std::move(term_positions), std::move(term_lengths))); increment_cursors(positings_list, cursors, slots); assert(positings_list.size() == cursors.size()); } return result; } //----------------------------------------------------------------------------- static std::shared_ptr<IPostings> perform_term_operation(const IInvertedIndex &inverted_index, const Expression &expr) { return std::make_shared<TermSearchResult>(inverted_index, expr.term_str); } static std::shared_ptr<IPostings> perform_and_operation(const IInvertedIndex &inverted_index, const Expression &expr) { return intersect_postings( positings_list(inverted_index, expr.nodes), [](const auto &positings_list, const auto &cursors) { std::vector<size_t> slots(positings_list.size(), 0); std::iota(slots.begin(), slots.end(), 0); std::vector<size_t> term_positions; std::vector<size_t> term_lengths; merge_term_positions(positings_list, cursors, slots, term_positions, term_lengths); return std::make_shared<Position>( positings_list[0]->document_id(cursors[0]), std::move(term_positions), std::move(term_lengths)); }); } static std::shared_ptr<IPostings> perform_adjacent_operation(const IInvertedIndex &inverted_index, const Expression &expr) { return intersect_postings( positings_list(inverted_index, expr.nodes), [](const auto &positings_list, const auto &cursors) { std::vector<size_t> term_positions; std::vector<size_t> term_lengths; auto target_slot = shortest_slot(positings_list, cursors); auto count = positings_list[target_slot]->search_hit_count(cursors[target_slot]); for (size_t i = 0; i < count; i++) { auto term_pos = positings_list[target_slot]->term_position( cursors[target_slot], i); if (is_adjacent(positings_list, cursors, target_slot, term_pos)) { auto start_term_pos = term_pos - target_slot; term_positions.push_back(start_term_pos); term_lengths.push_back(positings_list.size()); } } if (term_positions.empty()) { return std::shared_ptr<Position>(); } else { return std::make_shared<Position>( positings_list[0]->document_id(cursors[0]), std::move(term_positions), std::move(term_lengths)); } }); } static std::shared_ptr<IPostings> perform_or_operation(const IInvertedIndex &inverted_index, const Expression &expr) { return union_postings(positings_list(inverted_index, expr.nodes)); } static std::shared_ptr<IPostings> perform_near_operation(const IInvertedIndex &inverted_index, const Expression &expr) { return intersect_postings( positings_list(inverted_index, expr.nodes), [&](const auto &positings_list, const auto &cursors) { std::vector<size_t> term_positions; std::vector<size_t> term_lengths; std::vector<size_t> search_hit_cursors(positings_list.size(), 0); auto done = false; while (!done) { // TODO: performance improvement by reusing values as many as // possible std::map<size_t /*term_pos*/, std::pair<size_t /*slot*/, size_t /*term_length*/>> slots_by_term_pos; { auto slot = 0; for (const auto &p : positings_list) { auto index = cursors[slot]; auto hit_index = search_hit_cursors[slot]; auto term_pos = p->term_position(index, hit_index); auto term_length = p->term_length(index, hit_index); slots_by_term_pos[term_pos] = std::pair(slot, term_length); slot++; } } auto near = true; { auto it = slots_by_term_pos.begin(); auto it_prev = it; ++it; while (it != slots_by_term_pos.end()) { auto [prev_term_pos, prev_item] = *it_prev; auto [prev_slot, prev_term_count] = prev_item; auto [term_pos, item] = *it; auto delta = term_pos - (prev_term_pos + prev_term_count - 1); if (delta > expr.near_operation_distance) { near = false; break; } it_prev = it; ++it; } } if (near) { // Skip all search hit cursors for (auto [term_pos, item] : slots_by_term_pos) { auto [slot, term_length] = item; term_positions.push_back(term_pos); term_lengths.push_back(term_length); search_hit_cursors[slot]++; if (search_hit_cursors[slot] == positings_list[slot]->search_hit_count(cursors[slot])) { done = true; } } } else { // Skip search hit cursor for the smallest slot auto slot = slots_by_term_pos.begin()->second.first; search_hit_cursors[slot]++; if (search_hit_cursors[slot] == positings_list[slot]->search_hit_count(cursors[slot])) { done = true; } } } if (term_positions.empty()) { return std::shared_ptr<Position>(); } else { return std::make_shared<Position>( positings_list[0]->document_id(cursors[0]), std::move(term_positions), std::move(term_lengths)); } }); } //----------------------------------------------------------------------------- std::shared_ptr<IPostings> perform_search(const IInvertedIndex &inverted_index, const Expression &expr) { switch (expr.operation) { case Operation::Term: return perform_term_operation(inverted_index, expr); case Operation::And: return perform_and_operation(inverted_index, expr); case Operation::Adjacent: return perform_adjacent_operation(inverted_index, expr); case Operation::Or: return perform_or_operation(inverted_index, expr); case Operation::Near: return perform_near_operation(inverted_index, expr); default: return nullptr; } } template <typename T> void enumerate_terms(const Expression &expr, T fn) { if (expr.operation == Operation::Term) { fn(expr.term_str); } else { for (const auto &node : expr.nodes) { enumerate_terms(node, fn); } } } size_t term_count_score(const IInvertedIndex &invidx, const Expression &expr, const IPostings &postings, size_t index) { auto document_id = postings.document_id(index); size_t score = 0; enumerate_terms(expr, [&](const auto &term) { score += invidx.term_count(term, document_id); }); return score; } double tf_idf_score(const IInvertedIndex &invidx, const Expression &expr, const IPostings &postings, size_t index) { auto document_id = postings.document_id(index); auto N = static_cast<double>(invidx.document_count()); double score = 0.0; enumerate_terms(expr, [&](const auto &term) { auto n = static_cast<double>(invidx.df(term)); auto idf = std::log2((N + 0.001) / (n + 0.001)); score += invidx.tf(term, document_id) * idf; }); return score; } double bm25_score(const IInvertedIndex &invidx, const Expression &expr, const IPostings &postings, size_t index, double k1, double b) { auto document_id = postings.document_id(index); auto N = static_cast<double>(invidx.document_count()); auto dl = static_cast<double>(invidx.document_term_count(document_id)); auto avgdl = static_cast<double>(invidx.average_document_term_count()); double score = 0.0; enumerate_terms(expr, [&](const auto &term) { auto n = static_cast<double>(invidx.df(term)); auto idf = std::log2((N - n + 0.5) / (n + 0.5)); auto tf = invidx.tf(term, document_id); score += idf * ((tf * (k1 + 1.0)) / (tf + k1 * (1.0 - b + b * (dl / avgdl)))); }); return score; } } // namespace searchlib
yhirose/cpp-searchlib
33
A C++17 full-text search engine library
C++
yhirose
src/tokenizer.cpp
C++
// // tokenizer.cpp // // Copyright (c) 2021 Yuji Hirose. All rights reserved. // MIT License // #include "lib/unicodelib.h" #include "lib/unicodelib_encodings.h" #include "searchlib.h" using namespace unicode; namespace searchlib { TextRange text_range(const TextRangeList<TextRange> &text_range_list, const IPostings &positions, size_t index, size_t search_hit_index) { auto document_id = positions.document_id(index); auto term_pos = positions.term_position(index, search_hit_index); auto term_length = positions.term_length(index, search_hit_index); if (term_length == 1) { return text_range_list.at(document_id)[term_pos]; } else { auto beg = text_range_list.at(document_id)[term_pos]; auto end = text_range_list.at(document_id)[term_pos + term_length - 1]; auto length = end.position + end.length - beg.position; return TextRange{beg.position, length}; } } //----------------------------------------------------------------------------- UTF8PlainTextTokenizer::UTF8PlainTextTokenizer(std::string_view text) : text_(text) {} void UTF8PlainTextTokenizer::operator()( Normalizer normalizer, std::function<void(const std::u32string &str, size_t term_pos, TextRange text_range)> callback) { size_t pos = 0; size_t term_pos = 0; while (pos < text_.size()) { // Skip while (pos < text_.size()) { char32_t cp; auto len = utf8::decode_codepoint(&text_[pos], text_.size() - pos, cp); if (is_letter(cp)) { break; } pos += len; } // Term auto beg = pos; std::u32string str; while (pos < text_.size()) { char32_t cp; auto len = utf8::decode_codepoint(&text_[pos], text_.size() - pos, cp); if (!is_letter(cp)) { break; } str += cp; pos += len; } if (!str.empty()) { callback((normalizer ? normalizer(str) : str), term_pos, {beg, pos - beg}); term_pos++; } } } } // namespace searchlib
yhirose/cpp-searchlib
33
A C++17 full-text search engine library
C++
yhirose
src/utils.cpp
C++
// // utils.cpp // // Copyright (c) 2021 Yuji Hirose. All rights reserved. // MIT License // #include "utils.h" #include "lib/unicodelib_encodings.h" namespace searchlib { std::string u8(std::u32string_view u32) { return unicode::utf8::encode(u32); } std::u32string u32(std::string_view u8) { return unicode::utf8::decode(u8); } } // namespace searchlib
yhirose/cpp-searchlib
33
A C++17 full-text search engine library
C++
yhirose
src/utils.h
C/C++ Header
// // utils.h // // Copyright (c) 2021 Yuji Hirose. All rights reserved. // MIT License // #pragma once #include <string> namespace searchlib { std::string u8(std::u32string_view u32); std::u32string u32(std::string_view u8); } // namespace searchlib
yhirose/cpp-searchlib
33
A C++17 full-text search engine library
C++
yhirose
test/split_to_chapters.py
Python
import sys from itertools import groupby lines = [line.rstrip().split('\t') for line in sys.stdin.readlines()] for key, group in groupby(lines, key=lambda x: [int(x[1]), int(x[2])]): book, chap = key text = '\\n'.join([x[4] for x in group]) print('{:d}{:02d}\t{}'.format(book, chap, text))
yhirose/cpp-searchlib
33
A C++17 full-text search engine library
C++
yhirose
test/test.cc
C++
#include <gtest/gtest.h> #include <searchlib.h> #include "test_utils.h" using namespace searchlib; std::vector<std::string> sample_documents = { "This is the first document.", "This is the second document.", "This is the third document. This is the second sentence in the third.", "Fourth document", "Hello World!", }; auto normalizer = [](auto sv) { return unicode::to_lowercase(sv); }; auto sample_index() { InMemoryInvertedIndex<TextRange> invidx; InMemoryIndexer indexer(invidx, normalizer); size_t document_id = 0; for (const auto &doc : sample_documents) { indexer.index_document(document_id, UTF8PlainTextTokenizer(doc)); document_id++; } EXPECT_EQ(sample_documents.size(), invidx.document_count()); auto term = U"the"; EXPECT_EQ(5, invidx.term_count(term)); return invidx; } TEST(TokenizerTest, UTF8PlainTextTokenizer) { std::vector<std::vector<std::string>> expected = { {"this", "is", "the", "first", "document"}, {"this", "is", "the", "second", "document"}, {"this", "is", "the", "third", "document", "this", "is", "the", "second", "sentence", "in", "the", "third"}, {"fourth", "document"}, {"hello", "world"}, }; size_t document_id = 0; for (const auto &doc : sample_documents) { UTF8PlainTextTokenizer tokenizer(doc); std::vector<std::string> actual; tokenizer([](auto sv) { return unicode::to_lowercase(sv); }, [&](auto &str, auto, auto) { actual.emplace_back(u8(str)); }); EXPECT_EQ(expected[document_id], actual); document_id++; } } TEST(QueryTest, ParsingQuery) { const auto &invidx = sample_index(); { auto expr = parse_query(invidx, normalizer, " The "); EXPECT_NE(std::nullopt, expr); EXPECT_EQ(Operation::Term, (*expr).operation); EXPECT_EQ(U"the", (*expr).term_str); } { auto expr = parse_query(invidx, normalizer, " nothing "); EXPECT_EQ(std::nullopt, expr); } } TEST(TermTest, TermSearch) { const auto &invidx = sample_index(); { auto expr = parse_query(invidx, normalizer, " The "); auto postings = perform_search(invidx, *expr); EXPECT_EQ(3, postings->size()); { auto index = 0; EXPECT_EQ(0, postings->document_id(index)); EXPECT_EQ(1, postings->search_hit_count(index)); EXPECT_EQ(2, postings->term_position(index, 0)); EXPECT_EQ(1, postings->term_length(index, 0)); auto rng = invidx.text_range(*postings, index, 0); EXPECT_EQ(8, rng.position); EXPECT_EQ(3, rng.length); } { auto index = 2; EXPECT_EQ(2, postings->document_id(index)); EXPECT_EQ(3, postings->search_hit_count(index)); EXPECT_EQ(2, postings->term_position(index, 0)); EXPECT_EQ(1, postings->term_length(index, 0)); EXPECT_EQ(7, postings->term_position(index, 1)); EXPECT_EQ(1, postings->term_length(index, 1)); EXPECT_EQ(11, postings->term_position(index, 2)); EXPECT_EQ(1, postings->term_length(index, 2)); auto rng = invidx.text_range(*postings, index, 2); EXPECT_EQ(59, rng.position); EXPECT_EQ(3, rng.length); } } { auto expr = parse_query(invidx, normalizer, " second "); auto postings = perform_search(invidx, *expr); EXPECT_EQ(2, postings->size()); { auto index = 0; EXPECT_EQ(1, postings->document_id(index)); EXPECT_EQ(1, postings->search_hit_count(index)); EXPECT_EQ(3, postings->term_position(index, 0)); EXPECT_EQ(1, postings->term_length(index, 0)); auto rng = invidx.text_range(*postings, index, 0); EXPECT_EQ(12, rng.position); EXPECT_EQ(6, rng.length); } { auto index = 1; EXPECT_EQ(2, postings->document_id(index)); EXPECT_EQ(1, postings->search_hit_count(index)); EXPECT_EQ(8, postings->term_position(index, 0)); EXPECT_EQ(1, postings->term_length(index, 0)); auto rng = invidx.text_range(*postings, index, 0); EXPECT_EQ(40, rng.position); EXPECT_EQ(6, rng.length); } } } TEST(AndTest, AndSearch) { const auto &invidx = sample_index(); { auto expr = parse_query(invidx, normalizer, " the second third "); EXPECT_EQ(Operation::And, expr->operation); EXPECT_EQ(3, expr->nodes.size()); auto postings = perform_search(invidx, *expr); EXPECT_EQ(1, postings->size()); { auto index = 0; EXPECT_EQ(2, postings->document_id(index)); EXPECT_EQ(6, postings->search_hit_count(index)); { auto hit_index = 1; EXPECT_EQ(3, postings->term_position(index, hit_index)); EXPECT_EQ(1, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(12, rng.position); EXPECT_EQ(5, rng.length); } { auto hit_index = 3; EXPECT_EQ(8, postings->term_position(index, hit_index)); EXPECT_EQ(1, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(40, rng.position); EXPECT_EQ(6, rng.length); } { auto hit_index = 5; EXPECT_EQ(12, postings->term_position(index, hit_index)); EXPECT_EQ(1, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(63, rng.position); EXPECT_EQ(5, rng.length); } } } } TEST(OrTest, OrSearch) { const auto &invidx = sample_index(); { auto expr = parse_query(invidx, normalizer, " third | HELLO | second "); EXPECT_EQ(Operation::Or, expr->operation); EXPECT_EQ(3, expr->nodes.size()); auto postings = perform_search(invidx, *expr); EXPECT_EQ(3, postings->size()); { auto index = 0; EXPECT_EQ(1, postings->document_id(index)); EXPECT_EQ(1, postings->search_hit_count(index)); { auto hit_index = 0; EXPECT_EQ(3, postings->term_position(index, hit_index)); EXPECT_EQ(1, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(12, rng.position); EXPECT_EQ(6, rng.length); } } { auto index = 1; EXPECT_EQ(2, postings->document_id(index)); EXPECT_EQ(3, postings->search_hit_count(index)); { auto hit_index = 0; EXPECT_EQ(3, postings->term_position(index, hit_index)); EXPECT_EQ(1, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(12, rng.position); EXPECT_EQ(5, rng.length); } { auto hit_index = 1; EXPECT_EQ(8, postings->term_position(index, hit_index)); EXPECT_EQ(1, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(40, rng.position); EXPECT_EQ(6, rng.length); } { auto hit_index = 2; EXPECT_EQ(12, postings->term_position(index, hit_index)); EXPECT_EQ(1, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(63, rng.position); EXPECT_EQ(5, rng.length); } } { auto index = 2; EXPECT_EQ(4, postings->document_id(index)); EXPECT_EQ(1, postings->search_hit_count(index)); { auto hit_index = 0; EXPECT_EQ(0, postings->term_position(index, hit_index)); EXPECT_EQ(1, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(0, rng.position); EXPECT_EQ(5, rng.length); } } } } TEST(AdjacentTest, AdjacentSearch) { const auto &invidx = sample_index(); { auto expr = parse_query(invidx, normalizer, R"( "is the" )"); EXPECT_EQ(Operation::Adjacent, expr->operation); EXPECT_EQ(2, expr->nodes.size()); auto postings = perform_search(invidx, *expr); EXPECT_EQ(3, postings->size()); { auto index = 0; EXPECT_EQ(0, postings->document_id(index)); EXPECT_EQ(1, postings->search_hit_count(index)); { auto hit_index = 0; EXPECT_EQ(1, postings->term_position(index, hit_index)); EXPECT_EQ(2, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(5, rng.position); EXPECT_EQ(6, rng.length); } } { auto index = 1; EXPECT_EQ(1, postings->document_id(index)); EXPECT_EQ(1, postings->search_hit_count(index)); { auto hit_index = 0; EXPECT_EQ(1, postings->term_position(index, hit_index)); EXPECT_EQ(2, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(5, rng.position); EXPECT_EQ(6, rng.length); } } { auto index = 2; EXPECT_EQ(2, postings->document_id(index)); EXPECT_EQ(2, postings->search_hit_count(index)); { auto hit_index = 0; EXPECT_EQ(1, postings->term_position(index, hit_index)); EXPECT_EQ(2, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(5, rng.position); EXPECT_EQ(6, rng.length); } { auto hit_index = 1; EXPECT_EQ(6, postings->term_position(index, hit_index)); EXPECT_EQ(2, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(33, rng.position); EXPECT_EQ(6, rng.length); } } } } TEST(AdjacentTest, AdjacentSearchWith3Words) { const auto &invidx = sample_index(); { auto expr = parse_query(invidx, normalizer, R"( "the second sentence" )"); EXPECT_EQ(Operation::Adjacent, expr->operation); EXPECT_EQ(3, expr->nodes.size()); auto postings = perform_search(invidx, *expr); EXPECT_EQ(1, postings->size()); { auto index = 0; EXPECT_EQ(2, postings->document_id(index)); EXPECT_EQ(1, postings->search_hit_count(index)); { auto hit_index = 0; EXPECT_EQ(7, postings->term_position(index, hit_index)); EXPECT_EQ(3, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(36, rng.position); EXPECT_EQ(19, rng.length); } } } } TEST(NearTest, NearSearch) { const auto &invidx = sample_index(); { auto expr = parse_query(invidx, normalizer, R"( second ~ document )"); EXPECT_EQ(Operation::Near, expr->operation); EXPECT_EQ(2, expr->nodes.size()); auto postings = perform_search(invidx, *expr); EXPECT_EQ(2, postings->size()); { auto index = 0; EXPECT_EQ(1, postings->document_id(index)); EXPECT_EQ(2, postings->search_hit_count(index)); { auto hit_index = 0; EXPECT_EQ(3, postings->term_position(index, hit_index)); EXPECT_EQ(1, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(12, rng.position); EXPECT_EQ(6, rng.length); } { auto hit_index = 1; EXPECT_EQ(4, postings->term_position(index, hit_index)); EXPECT_EQ(1, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(19, rng.position); EXPECT_EQ(8, rng.length); } } { auto index = 1; EXPECT_EQ(2, postings->document_id(index)); EXPECT_EQ(2, postings->search_hit_count(index)); { auto hit_index = 0; EXPECT_EQ(4, postings->term_position(index, hit_index)); EXPECT_EQ(1, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(18, rng.position); EXPECT_EQ(8, rng.length); } { auto hit_index = 1; EXPECT_EQ(8, postings->term_position(index, hit_index)); EXPECT_EQ(1, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(40, rng.position); EXPECT_EQ(6, rng.length); } } } } TEST(NearTest, NearSearchWithPhrase) { const auto &invidx = sample_index(); { auto expr = parse_query(invidx, normalizer, R"( sentence ~ "is the" )"); EXPECT_EQ(Operation::Near, expr->operation); EXPECT_EQ(2, expr->nodes.size()); auto postings = perform_search(invidx, *expr); EXPECT_EQ(1, postings->size()); { auto index = 0; EXPECT_EQ(2, postings->document_id(index)); EXPECT_EQ(2, postings->search_hit_count(index)); { auto hit_index = 0; EXPECT_EQ(6, postings->term_position(index, hit_index)); EXPECT_EQ(2, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(33, rng.position); EXPECT_EQ(6, rng.length); } { auto hit_index = 1; EXPECT_EQ(9, postings->term_position(index, hit_index)); EXPECT_EQ(1, postings->term_length(index, hit_index)); auto rng = invidx.text_range(*postings, index, hit_index); EXPECT_EQ(47, rng.position); EXPECT_EQ(8, rng.length); } } } } TEST(TF_IDF_Test, TF_IDF) { const std::vector<std::string> documents = { "apple orange orange banana", "banana orange strawberry strawberry grape", }; InMemoryInvertedIndex<TextRange> invidx; { InMemoryIndexer indexer(invidx, normalizer); size_t document_id = 0; for (const auto &doc : documents) { UTF8PlainTextTokenizer tokenizer(doc); indexer.index_document(document_id, tokenizer); document_id++; } } { auto term = U"apple"; EXPECT_EQ(1, invidx.df(term)); EXPECT_EQ(0.25, invidx.tf(term, 0)); EXPECT_EQ(0, invidx.tf(term, 1)); } { auto term = U"orange"; EXPECT_EQ(2, invidx.df(term)); EXPECT_EQ(0.5, invidx.tf(term, 0)); EXPECT_EQ(0.2, invidx.tf(term, 1)); } { auto term = U"banana"; EXPECT_EQ(2, invidx.df(term)); EXPECT_EQ(0.25, invidx.tf(term, 0)); EXPECT_EQ(0.2, invidx.tf(term, 1)); } { auto term = U"strawberry"; EXPECT_EQ(1, invidx.df(term)); EXPECT_EQ(0, invidx.tf(term, 0)); EXPECT_EQ(0.4, invidx.tf(term, 1)); } { auto term = U"grape"; EXPECT_EQ(1, invidx.df(term)); EXPECT_EQ(0, invidx.tf(term, 0)); EXPECT_EQ(0.2, invidx.tf(term, 1)); } }
yhirose/cpp-searchlib
33
A C++17 full-text search engine library
C++
yhirose
test/test_kjv.cc
C++
#include <gtest/gtest.h> #include <searchlib.h> #include <filesystem> #include <fstream> #include "test_utils.h" using namespace searchlib; const auto KJV_PATH = "../../test/t_kjv.tsv"; auto normalizer = [](auto sv) { return unicode::to_lowercase(sv); }; static auto kjv_index() { InMemoryInvertedIndex<TextRange> invidx; InMemoryIndexer indexer(invidx, normalizer); std::ifstream fs(KJV_PATH); if (fs) { std::string line; while (std::getline(fs, line)) { auto fields = split(line, '\t'); auto document_id = std::stoi(fields[0]); const auto &s = fields[4]; indexer.index_document(document_id, UTF8PlainTextTokenizer(s)); } } return invidx; } TEST(KJVTest, SimpleTest) { const auto &invidx = kjv_index(); { auto expr = parse_query(invidx, normalizer, R"( apple )"); ASSERT_TRUE(expr); auto postings = perform_search(invidx, *expr); ASSERT_TRUE(postings); ASSERT_EQ(8, postings->size()); auto term = U"apple"; EXPECT_EQ(8, invidx.df(term)); EXPECT_AP(0.411, tf_idf_score(invidx, *expr, *postings, 0)); EXPECT_AP(0.745, tf_idf_score(invidx, *expr, *postings, 1)); EXPECT_AP(0.852, tf_idf_score(invidx, *expr, *postings, 2)); EXPECT_AP(0.351, tf_idf_score(invidx, *expr, *postings, 3)); EXPECT_AP(0.341, tf_idf_score(invidx, *expr, *postings, 4)); EXPECT_AP(0.341, tf_idf_score(invidx, *expr, *postings, 5)); EXPECT_AP(0.298, tf_idf_score(invidx, *expr, *postings, 6)); EXPECT_AP(0.385, tf_idf_score(invidx, *expr, *postings, 7)); EXPECT_AP(0.660, bm25_score(invidx, *expr, *postings, 0)); EXPECT_AP(1.753, bm25_score(invidx, *expr, *postings, 1)); EXPECT_AP(2.146, bm25_score(invidx, *expr, *postings, 2)); EXPECT_AP(0.500, bm25_score(invidx, *expr, *postings, 3)); EXPECT_AP(0.475, bm25_score(invidx, *expr, *postings, 4)); EXPECT_AP(0.475, bm25_score(invidx, *expr, *postings, 5)); EXPECT_AP(0.374, bm25_score(invidx, *expr, *postings, 6)); EXPECT_AP(0.588, bm25_score(invidx, *expr, *postings, 7)); } { auto expr = parse_query(invidx, normalizer, R"( "apple tree" )"); ASSERT_TRUE(expr); auto postings = perform_search(invidx, *expr); ASSERT_TRUE(postings); ASSERT_EQ(3, postings->size()); EXPECT_EQ(1, postings->search_hit_count(0)); EXPECT_EQ(1, postings->search_hit_count(1)); EXPECT_EQ(1, postings->search_hit_count(2)); EXPECT_EQ(2, term_count_score(invidx, *expr, *postings, 0)); EXPECT_EQ(2, term_count_score(invidx, *expr, *postings, 1)); EXPECT_EQ(5, term_count_score(invidx, *expr, *postings, 2)); EXPECT_AP(0.572, tf_idf_score(invidx, *expr, *postings, 0)); EXPECT_AP(0.556, tf_idf_score(invidx, *expr, *postings, 1)); EXPECT_AP(1.051, tf_idf_score(invidx, *expr, *postings, 2)); EXPECT_AP(0.817, bm25_score(invidx, *expr, *postings, 0)); EXPECT_AP(0.776, bm25_score(invidx, *expr, *postings, 1)); EXPECT_AP(1.285, bm25_score(invidx, *expr, *postings, 2)); } } TEST(KJVTest, UTF8DecodePerformance) { // auto normalizer = [](const auto &str) { // return unicode::to_lowercase(str); // }; auto normalizer = to_lowercase; std::ifstream fs(KJV_PATH); std::string s; while (std::getline(fs, s)) { UTF8PlainTextTokenizer tokenizer(s); tokenizer(normalizer, [&](auto &str, auto, auto) {}); } }
yhirose/cpp-searchlib
33
A C++17 full-text search engine library
C++
yhirose
test/test_kjv_chapters.cc
C++
#include <gtest/gtest.h> #include <searchlib.h> #include <filesystem> #include <fstream> #include "test_utils.h" using namespace searchlib; const auto KJV_PATH = "../../test/t_kjv_chapters.tsv"; auto normalizer = [](auto sv) { return unicode::to_lowercase(sv); }; static auto kjv_index() { return make_in_memory_index<TextRange>(normalizer, [&](auto &indexer) { std::ifstream fs(KJV_PATH); if (fs) { std::string line; while (std::getline(fs, line)) { auto fields = split(line, '\t'); auto document_id = std::stoi(fields[0]); const auto &s = fields[1]; indexer.index_document(document_id, UTF8PlainTextTokenizer(s)); } } }); } TEST(KJVChapterTest, SimpleTest) { auto p = kjv_index(); const auto &invidx = *p; { auto expr = parse_query(invidx, normalizer, R"( apple )"); ASSERT_TRUE(expr); auto postings = perform_search(invidx, *expr); ASSERT_TRUE(postings); ASSERT_EQ(8, postings->size()); auto term = U"apple"; EXPECT_EQ(8, invidx.df(term)); EXPECT_EQ(532, postings->document_id(0)); EXPECT_EQ(1917, postings->document_id(1)); EXPECT_EQ(2007, postings->document_id(2)); EXPECT_EQ(2202, postings->document_id(3)); EXPECT_EQ(2208, postings->document_id(4)); EXPECT_EQ(2502, postings->document_id(5)); EXPECT_EQ(2901, postings->document_id(6)); EXPECT_EQ(3802, postings->document_id(7)); EXPECT_EQ(1, postings->search_hit_count(0)); EXPECT_EQ(1, postings->search_hit_count(1)); EXPECT_EQ(1, postings->search_hit_count(2)); EXPECT_EQ(1, postings->search_hit_count(3)); EXPECT_EQ(1, postings->search_hit_count(4)); EXPECT_EQ(1, postings->search_hit_count(5)); EXPECT_EQ(1, postings->search_hit_count(6)); EXPECT_EQ(1, postings->search_hit_count(7)); EXPECT_AP(0.00549139, tf_idf_score(invidx, *expr, *postings, 0)); EXPECT_AP(0.0230779, tf_idf_score(invidx, *expr, *postings, 1)); EXPECT_AP(0.0174205, tf_idf_score(invidx, *expr, *postings, 2)); EXPECT_AP(0.020448, tf_idf_score(invidx, *expr, *postings, 3)); EXPECT_AP(0.0198816, tf_idf_score(invidx, *expr, *postings, 4)); EXPECT_AP(0.00811905, tf_idf_score(invidx, *expr, *postings, 5)); EXPECT_AP(0.0141007, tf_idf_score(invidx, *expr, *postings, 6)); EXPECT_AP(0.0226411, tf_idf_score(invidx, *expr, *postings, 7)); EXPECT_AP(0.00583253, bm25_score(invidx, *expr, *postings, 0)); EXPECT_AP(0.0697716, bm25_score(invidx, *expr, *postings, 1)); EXPECT_AP(0.0443892, bm25_score(invidx, *expr, *postings, 2)); EXPECT_AP(0.0575726, bm25_score(invidx, *expr, *postings, 3)); EXPECT_AP(0.0550316, bm25_score(invidx, *expr, *postings, 4)); EXPECT_AP(0.011908, bm25_score(invidx, *expr, *postings, 5)); EXPECT_AP(0.0312082, bm25_score(invidx, *expr, *postings, 6)); EXPECT_AP(0.0677023, bm25_score(invidx, *expr, *postings, 7)); } { auto expr = parse_query(invidx, normalizer, R"( apple tree )"); ASSERT_TRUE(expr); auto postings = perform_search(invidx, *expr); ASSERT_TRUE(postings); ASSERT_EQ(3, postings->size()); EXPECT_EQ(2202, postings->document_id(0)); EXPECT_EQ(2208, postings->document_id(1)); EXPECT_EQ(2901, postings->document_id(2)); EXPECT_EQ(3, postings->search_hit_count(0)); EXPECT_EQ(2, postings->search_hit_count(1)); EXPECT_EQ(6, postings->search_hit_count(2)); EXPECT_AP(0.0391522, tf_idf_score(invidx, *expr, *postings, 0)); EXPECT_AP(0.0289746, tf_idf_score(invidx, *expr, *postings, 1)); EXPECT_AP(0.0463462, tf_idf_score(invidx, *expr, *postings, 2)); EXPECT_AP(0.108137, bm25_score(invidx, *expr, *postings, 0)); EXPECT_AP(0.079287, bm25_score(invidx, *expr, *postings, 1)); EXPECT_AP(0.0994374, bm25_score(invidx, *expr, *postings, 2)); } { auto expr = parse_query(invidx, normalizer, R"( Joshua Jericho )"); ASSERT_TRUE(expr); auto postings = perform_search(invidx, *expr); ASSERT_TRUE(postings); ASSERT_EQ(18, postings->size()); { size_t i = 0; for (auto expected : {426, 434, 534, 602, 603, 604, 605, 606, 607, 608, 609, 610, 612, 613, 618, 620, 624, 1116}) { EXPECT_EQ(expected, postings->document_id(i)); i++; } } { size_t i = 0; for (auto expected : {3, 2, 3, 6, 7, 13, 12, 15, 13, 19, 10, 31, 3, 2, 7, 2, 15, 2}) { EXPECT_EQ(expected, postings->search_hit_count(i)); i++; } } { size_t i = 0; for (auto expected : {0.00982997, 0.0149824, 0.0444499, 0.0367272, 0.057788, 0.0860655, 0.10183, 0.077544, 0.0654762, 0.0724664, 0.0583369, 0.103775, 0.0289974, 0.0114411, 0.0426484, 0.0306458, 0.0671168, 0.00910212}) { EXPECT_AP(expected, tf_idf_score(invidx, *expr, *postings, i)); i++; } } { size_t i = 0; for (auto expected : {0.00955058, 0.0284355, 0.131614, 0.059746, 0.117627, 0.148535, 0.209976, 0.110549, 0.0916737, 0.0807503, 0.091753, 0.103232, 0.066022, 0.017691, 0.0693532, 0.0930067, 0.0853508, 0.0117135}) { EXPECT_AP(expected, bm25_score(invidx, *expr, *postings, i)); i++; } } } }
yhirose/cpp-searchlib
33
A C++17 full-text search engine library
C++
yhirose
test/test_utils.h
C/C++ Header
#include <sstream> #include "lib/unicodelib.h" #include "utils.h" inline bool close_enough(double expect, double actual) { auto tolerance = 0.001; return (expect - tolerance) <= actual && actual <= (expect + tolerance); } #define EXPECT_AP(a, b) EXPECT_TRUE(close_enough(a, b)) inline std::u32string to_lowercase(std::u32string str) { std::transform(str.begin(), str.end(), str.begin(), [](auto c) { return std::tolower(c); }); return str; } inline std::vector<std::string> split(const std::string &input, char delimiter) { std::istringstream ss(input); std::string field; std::vector<std::string> result; while (std::getline(ss, field, delimiter)) { result.push_back(field); } return result; }
yhirose/cpp-searchlib
33
A C++17 full-text search engine library
C++
yhirose
test.cc
C++
#include <iostream> #include <strstream> #include <unistd.h> #include "threadpool.h" using namespace std; int main(void) { threadpool::pool pool; pool.start(4); thread t = thread([&] { size_t id = 0; while (id < 20) { pool.enqueue([=] { sleep(1); strstream ss; ss << "[job " << id << "] is done" << endl; cout << ss.str(); }); id++; } sleep(3); cout << "shutdown begin" << endl; pool.shutdown(); cout << "shutdown end" << endl; }); t.join(); return 0; }
yhirose/cpp-threadpool
19
C++11 header-only thread pool library
C++
yhirose
threadpool.h
C/C++ Header
// // threadpool.h // // Copyright (c) 2019 Yuji Hirose. All rights reserved. // MIT License // #ifndef CPPHTTPLIB_THREADPOOL_H #define CPPHTTPLIB_THREADPOOL_H #include <condition_variable> #include <functional> #include <list> #include <mutex> #include <thread> #include <vector> namespace threadpool { class pool { public: pool() : shutdown_(false) {} pool(const pool &) = delete; ~pool() {} void start(size_t n) { while (n) { auto t = std::make_shared<std::thread>(worker(*this)); threads_.push_back(t); n--; } } void shutdown() { // Stop all worker threads... { std::unique_lock<std::mutex> lock(mutex_); shutdown_ = true; } cond_.notify_all(); // Join... for (auto t : threads_) { t->join(); } } void enqueue(std::function<void()> fn) { std::unique_lock<std::mutex> lock(mutex_); jobs_.push_back(fn); cond_.notify_one(); } private: struct worker { worker(pool &pool) : pool_(pool) {} void operator()() { for (;;) { std::function<void()> fn; { std::unique_lock<std::mutex> lock(pool_.mutex_); pool_.cond_.wait( lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; }); if (pool_.shutdown_ && pool_.jobs_.empty()) { break; } fn = pool_.jobs_.front(); pool_.jobs_.pop_front(); } assert(true == (bool)fn); fn(); } } pool &pool_; }; friend struct worker; std::vector<std::shared_ptr<std::thread>> threads_; std::list<std::function<void()>> jobs_; bool shutdown_; std::condition_variable cond_; std::mutex mutex_; }; }; // namespace threadpool #endif // CPPHTTPLIB_THREADPOOL_H
yhirose/cpp-threadpool
19
C++11 header-only thread pool library
C++
yhirose
scripts/gen_property_values.py
Python
import sys import re MaxCode = 0x0010FFFF r = re.compile(r"^[0-9A-F]+(?:\.\.[0-9A-F]+)?\s*;\s*(.+?)\s*(?:#.+)?$") names = [] for line in sys.stdin.readlines(): m = r.match(line) if m: name = ''.join([x.title() if x.islower() else x for x in re.split(r"[ -]", m.group(1))]) if not name in names: names.append(name) print(" Unassigned,") for name in names: print(' %s,' % name)
yhirose/cpp-unicodelib
122
A C++17 header-only Unicode library. (Unicode 17.0.0)
C++
yhirose
scripts/gen_tables.py
Python
import sys import re #------------------------------------------------------------------------------ # Constants #------------------------------------------------------------------------------ MaxCopePoint = 0x0010FFFF #------------------------------------------------------------------------------ # Utilities #------------------------------------------------------------------------------ def to_unicode_literal(str): if len(str): return 'U"%s"' % ''.join([('\\U%08X' % x) for x in str]) return '0' #------------------------------------------------------------------------------ # generateTable #------------------------------------------------------------------------------ def findDataSize(values, blockSize): result = [] for i in range(0, len(values), blockSize): items = values[i:i+blockSize] result.append(all([x == items[0] for x in items])) itemSize = 8 return (result.count(True) * itemSize + result.count(False) * blockSize * itemSize) / 1024 def findBestBlockSize(values): originalSize = findDataSize(values, 1) smallestSize = originalSize blockSize = 1 for bs in [16, 32, 64, 128, 256, 512, 1024]: sz = findDataSize(values, bs) if sz < smallestSize: smallestSize = sz blockSize = bs return blockSize def isPremitiveType(type): return type == 'int' or type == 'uint32_t' or type == 'uint64_t' or type == 'NormalizationProperties' def generateTable(name, type, defval, out, values): def formatValue(val): if isPremitiveType(type): return "{},".format(val) else: return "D," if val == defval else "T::{},".format(val) if isPremitiveType(type): out.write("""namespace {0} {{ """.format(name)) else: out.write("""namespace {0} {{ using T = {1}; const auto D = {1}::{2}; """.format(name, type, defval)) blockSize = findBestBlockSize(values) out.write("static const size_t _block_size = {};\n".format(blockSize)) blockValues = [] for i in range(0, len(values), blockSize): items = values[i:i+blockSize] if all([x == items[0] for x in items]): blockValues.append(items[0]) else: blockValues.append(None) iblock = i // blockSize out.write("static const {} _{}[] = {{ ".format(type, iblock)) for val in items: out.write(formatValue(val)) out.write(" };\n") out.write("static const {} *_blocks[] = {{\n".format(type)) for iblock, blockValue in enumerate(blockValues): if iblock % 8 == 0: if iblock == 0: out.write(" ") else: out.write("\n ") if blockValue != None: out.write("0,") else: out.write("_{},".format(iblock)) out.write("\n};\n") out.write("static const {} _block_values[] = {{\n".format(type)) for iblock, blockValue in enumerate(blockValues): if iblock % 8 == 0: if iblock == 0: out.write(" ") else: out.write("\n ") if blockValue != None: out.write(formatValue(blockValue)) else: out.write(formatValue(defval)) out.write("\n};\n") out.write("""inline {} get_value(char32_t cp) {{ auto i = cp / _block_size; auto bl = _blocks[i]; if (bl) {{ auto off = cp % _block_size; return bl[off]; }} return _block_values[i]; }} }} """.format(type)) #------------------------------------------------------------------------------ # genGeneralCategoryPropertyTable #------------------------------------------------------------------------------ def genGeneralCategoryPropertyTable(ucd): fin = open(ucd + '/UnicodeData.txt') defval = 'Cn' data = [x.rstrip().split(';') for x in fin] def items(): codePointPrev = -1 i = 0 while i < len(data): flds = data[i] codePoint = int(flds[0], 16) value = flds[2] for cp in range(codePointPrev + 1, codePoint): yield cp, defval if flds[1].endswith('First>'): fldsLast = data[i + 1] codePointLast = int(fldsLast[0], 16) categoryLast = fldsLast[2] for cp in range(codePoint, codePointLast + 1): yield cp, categoryLast codePointPrev = codePointLast i += 2 else: yield codePoint, value codePointPrev = codePoint i += 1 for cp in range(codePointPrev + 1, MaxCopePoint + 1): yield cp, defval values = [val for cp, val in items()] generateTable('_general_category_properties', 'GeneralCategory', defval, sys.stdout, values) #------------------------------------------------------------------------------ # genPropertyTable #------------------------------------------------------------------------------ def genPropertyTable(ucd): fin = open(ucd + '/PropList.txt') values = [0] * (MaxCopePoint + 1) names = {} r = re.compile(r"([0-9A-F]+)(?:\.\.([0-9A-F]+))?\s*;\s*(\w+)\s*#.*") for line in fin: m = r.match(line) if m: codePoint = int(m.group(1), 16) name = m.group(3) if not name in names: names[name] = len(names) val = names[name] if m.group(2): codePointLast = int(m.group(2), 16) for cp in range(codePoint, codePointLast + 1): values[cp] += (1 << val) else: values[codePoint] += (1 << val) generateTable('_properties', "uint64_t", 0, sys.stdout, values) #------------------------------------------------------------------------------ # genDerivedCorePropertyTable #------------------------------------------------------------------------------ def genDerivedCorePropertyTable(ucd): fin = open(ucd + '/DerivedCoreProperties.txt') values = [0] * (MaxCopePoint + 1) names = {} r = re.compile(r"([0-9A-F]+)(?:\.\.([0-9A-F]+))?\s*;\s*(\w+)(?:;\s*(\w+))?\s*#.*") for line in fin: m = r.match(line) if m: codePoint = int(m.group(1), 16) name = m.group(3) prop_val = m.group(4) if prop_val: name = name + "_" + prop_val if not name in names: names[name] = len(names) val = names[name] if m.group(2): codePointLast = int(m.group(2), 16) for cp in range(codePoint, codePointLast + 1): values[cp] += (1 << val) else: values[codePoint] += (1 << val) generateTable('_derived_core_properties', "uint32_t", 0, sys.stdout, values) #------------------------------------------------------------------------------ # genSimpleCaseMappingTable #------------------------------------------------------------------------------ def genSimpleCaseMappingTable(ucd): fin = open(ucd + '/UnicodeData.txt') data = [x.rstrip().split(';') for x in fin] r = re.compile(r"(?:<(\w+)> )?(.+)") def items(): codePointPrev = -1 i = 0 while i < len(data): flds = data[i] codePoint = int(flds[0], 16) upper = flds[12] lower = flds[13] title = flds[14] if flds[1].endswith('First>'): fldsLast = data[i + 1] codePointLast = int(fldsLast[0], 16) codePointPrev = codePointLast i += 2 else: if len(upper) or len(lower) or len(title): if len(upper) == 0: upper = flds[0] if len(lower) == 0: lower = flds[0] if len(title) == 0: title = flds[0] yield codePoint, int(upper, 16), int(lower, 16), int(title, 16) codePointPrev = codePoint i += 1 print("const std::unordered_map<char32_t, const char32_t*> _simple_case_mappings = {") for cp, upper, lower, title in items(): print('{ 0x%08X, U"\\U%08X\\U%08X\\U%08X" },' % (cp, upper, lower, title)) print("};") #------------------------------------------------------------------------------ # genSpecialCaseMappingTable #------------------------------------------------------------------------------ def genSpecialCaseMappingTable(ucd): r = re.compile(r"(?!#)(.+?); #") def to_array(str): if len(str): return str.split(' ') return [] def is_language(str): return str in ('lt', 'tr', 'az') def items(): fin = open(ucd + '/SpecialCasing.txt') for line in fin: m = r.match(line) if m: flds = m.group(1).split('; ') cp = int(flds[0], 16) lower = [int(x, 16) for x in to_array(flds[1])] title = [int(x, 16) for x in to_array(flds[2])] upper = [int(x, 16) for x in to_array(flds[3])] hasContext = False language = '0' context = 'Unassigned' if len(flds) == 5: hasContext = True for x in to_array(flds[4]): if is_language(x): language = '"%s"' % x else: context = x yield cp, lower, title, upper, language, context, hasContext # Regular print("const std::unordered_multimap<char32_t, SpecialCasing> _special_case_mappings = {") for cp, lower, title, upper, language, context, hasContext in items(): if hasContext == True: print('{ 0x%08X, { %s, %s, %s, %s, SpecialCasingContext::%s } },' % (cp, to_unicode_literal(lower), to_unicode_literal(title), to_unicode_literal(upper), language, context)) print("};") # Default print("const std::unordered_multimap<char32_t, SpecialCasing> _special_case_mappings_default = {") for cp, lower, title, upper, language, context, hasContext in items(): if hasContext == False: print('{ 0x%08X, { %s, %s, %s, %s, SpecialCasingContext::%s } },' % (cp, to_unicode_literal(lower), to_unicode_literal(title), to_unicode_literal(upper), language, context)) print("};") #------------------------------------------------------------------------------ # genCaseFoldingTable #------------------------------------------------------------------------------ def genCaseFoldingTable(ucd): fin = open(ucd + '/CaseFolding.txt') r = re.compile(r"(.+?); ([CFST]); (.+?); #.*") dic = {} for line in fin: m = r.match(line) if m: cp = int(m.group(1), 16) status = m.group(2) codes = [int(x, 16) for x in m.group(3).split(' ')] if not cp in dic: dic[cp] = [0, 0, [], 0] if status == 'C': dic[cp][0] = codes[0] elif status == 'S': dic[cp][1] = codes[0] elif status == 'F': dic[cp][2] = codes elif status == 'T': dic[cp][3] = codes[0] print("const std::unordered_map<char32_t, CaseFolding> _case_foldings = {") for cp in dic: cf = dic[cp] f = to_unicode_literal(cf[2]) print('{ 0x%08X, { 0x%08X, 0x%08X, %s, 0x%08X } },' % (cp, cf[0], cf[1], f, cf[3])) print("};") #------------------------------------------------------------------------------ # genBlockPropertyTable #------------------------------------------------------------------------------ def genBlockPropertyTable(ucd): fin = open(ucd + '/Blocks.txt') defval = 'Unassigned' values = [defval] * (MaxCopePoint + 1) r = re.compile(r"([0-9A-F]+)\.\.([0-9A-F]+)\s*;\s+(.+)") for line in fin: m = r.match(line) if m: codePointFirst = int(m.group(1), 16) codePointLast = int(m.group(2), 16) block = "{}".format(''.join([x.title() if x.islower() else x for x in re.split(r"[ -]", m.group(3))])) for cp in range(codePointFirst, codePointLast + 1): values[cp] = block generateTable('_block_properties', 'Block', defval, sys.stdout, values) #------------------------------------------------------------------------------ # genScriptPropertyTable #------------------------------------------------------------------------------ def genScriptPropertyTable(ucd): fin = open(ucd + '/Scripts.txt') defval = 'Unassigned' values = [defval] * (MaxCopePoint + 1) r = re.compile(r"([0-9A-F]+)(?:\.\.([0-9A-F]+))?\s+;\s+(\w+)\s+#.*") for line in fin: m = r.match(line) if m: codePoint = int(m.group(1), 16) value = m.group(3) if m.group(2): codePointLast = int(m.group(2), 16) for cp in range(codePoint, codePointLast + 1): values[cp] = value else: values[codePoint] = value generateTable('_script_properties', 'Script', defval, sys.stdout, values) #------------------------------------------------------------------------------ # genScriptExtensionTable #------------------------------------------------------------------------------ def genScriptExtensionTable(ucd): # This list is from 'PropertyValueAliases.txt' in Unicode database. dic = { 'Adlm': 'Adlam', 'Aghb': 'Caucasian_Albanian', 'Ahom': 'Ahom', 'Arab': 'Arabic', 'Armi': 'Imperial_Aramaic', 'Armn': 'Armenian', 'Avst': 'Avestan', 'Bali': 'Balinese', 'Bamu': 'Bamum', 'Bass': 'Bassa_Vah', 'Batk': 'Batak', 'Beng': 'Bengali', 'Bhks': 'Bhaiksuki', 'Bopo': 'Bopomofo', 'Brah': 'Brahmi', 'Brai': 'Braille', 'Bugi': 'Buginese', 'Buhd': 'Buhid', 'Cakm': 'Chakma', 'Cans': 'Canadian_Aboriginal', 'Cari': 'Carian', 'Cham': 'Cham', 'Cher': 'Cherokee', 'Chrs': 'Chorasmian', 'Copt': 'Coptic', 'Cpmn': 'Cypro_Minoan', 'Cprt': 'Cypriot', 'Cyrl': 'Cyrillic', 'Deva': 'Devanagari', 'Diak': 'Dives_Akuru', 'Dogr': 'Dogra', 'Dsrt': 'Deseret', 'Dupl': 'Duployan', 'Egyp': 'Egyptian_Hieroglyphs', 'Elba': 'Elbasan', 'Elym': 'Elymaic', 'Ethi': 'Ethiopic', 'Gara': 'Garay', 'Geor': 'Georgian', 'Glag': 'Glagolitic', 'Gong': 'Gunjala_Gondi', 'Gonm': 'Masaram_Gondi', 'Goth': 'Gothic', 'Gran': 'Grantha', 'Grek': 'Greek', 'Gujr': 'Gujarati', 'Gukh': 'Gurung_Khema', 'Guru': 'Gurmukhi', 'Hang': 'Hangul', 'Hani': 'Han', 'Hano': 'Hanunoo', 'Hatr': 'Hatran', 'Hebr': 'Hebrew', 'Hira': 'Hiragana', 'Hluw': 'Anatolian_Hieroglyphs', 'Hmng': 'Pahawh_Hmong', 'Hmnp': 'Nyiakeng_Puachue_Hmong', 'Hrkt': 'Katakana_Or_Hiragana', 'Hung': 'Old_Hungarian', 'Ital': 'Old_Italic', 'Java': 'Javanese', 'Kali': 'Kayah_Li', 'Kana': 'Katakana', 'Kawi': 'Kawi', 'Khar': 'Kharoshthi', 'Khmr': 'Khmer', 'Khoj': 'Khojki', 'Kits': 'Khitan_Small_Script', 'Knda': 'Kannada', 'Krai': 'Kirat_Rai', 'Kthi': 'Kaithi', 'Lana': 'Tai_Tham', 'Laoo': 'Lao', 'Latn': 'Latin', 'Lepc': 'Lepcha', 'Limb': 'Limbu', 'Lina': 'Linear_A', 'Linb': 'Linear_B', 'Lisu': 'Lisu', 'Lyci': 'Lycian', 'Lydi': 'Lydian', 'Mahj': 'Mahajani', 'Maka': 'Makasar', 'Mand': 'Mandaic', 'Mani': 'Manichaean', 'Marc': 'Marchen', 'Medf': 'Medefaidrin', 'Mend': 'Mende_Kikakui', 'Merc': 'Meroitic_Cursive', 'Mero': 'Meroitic_Hieroglyphs', 'Mlym': 'Malayalam', 'Modi': 'Modi', 'Mong': 'Mongolian', 'Mroo': 'Mro', 'Mtei': 'Meetei_Mayek', 'Mult': 'Multani', 'Mymr': 'Myanmar', 'Nagm': 'Nag_Mundari', 'Nand': 'Nandinagari', 'Narb': 'Old_North_Arabian', 'Nbat': 'Nabataean', 'Newa': 'Newa', 'Nkoo': 'Nko', 'Nshu': 'Nushu', 'Ogam': 'Ogham', 'Olck': 'Ol_Chiki', 'Onao': 'Ol_Onal', 'Orkh': 'Old_Turkic', 'Orya': 'Oriya', 'Osge': 'Osage', 'Osma': 'Osmanya', 'Ougr': 'Old_Uyghur', 'Palm': 'Palmyrene', 'Pauc': 'Pau_Cin_Hau', 'Perm': 'Old_Permic', 'Phag': 'Phags_Pa', 'Phli': 'Inscriptional_Pahlavi', 'Phlp': 'Psalter_Pahlavi', 'Phnx': 'Phoenician', 'Plrd': 'Miao', 'Prti': 'Inscriptional_Parthian', 'Rjng': 'Rejang', 'Rohg': 'Hanifi_Rohingya', 'Runr': 'Runic', 'Samr': 'Samaritan', 'Sarb': 'Old_South_Arabian', 'Saur': 'Saurashtra', 'Sgnw': 'SignWriting', 'Shaw': 'Shavian', 'Shrd': 'Sharada', 'Sidd': 'Siddham', 'Sind': 'Khudawadi', 'Sinh': 'Sinhala', 'Sogd': 'Sogdian', 'Sogo': 'Old_Sogdian', 'Sora': 'Sora_Sompeng', 'Soyo': 'Soyombo', 'Sund': 'Sundanese', 'Sunu': 'Sunuwar', 'Sylo': 'Syloti_Nagri', 'Syrc': 'Syriac', 'Tagb': 'Tagbanwa', 'Takr': 'Takri', 'Tale': 'Tai_Le', 'Talu': 'New_Tai_Lue', 'Taml': 'Tamil', 'Tang': 'Tangut', 'Tavt': 'Tai_Viet', 'Telu': 'Telugu', 'Tfng': 'Tifinagh', 'Tglg': 'Tagalog', 'Thaa': 'Thaana', 'Thai': 'Thai', 'Tibt': 'Tibetan', 'Tirh': 'Tirhuta', 'Tnsa': 'Tangsa', 'Todr': 'Todhri', 'Toto': 'Toto', 'Tutg': 'Tulu_Tigalari', 'Ugar': 'Ugaritic', 'Vaii': 'Vai', 'Vith': 'Vithkuqi', 'Wara': 'Warang_Citi', 'Wcho': 'Wancho', 'Xpeo': 'Old_Persian', 'Xsux': 'Cuneiform', 'Yezi': 'Yezidi', 'Yiii': 'Yi', 'Zanb': 'Zanabazar_Square', 'Zinh': 'Inherited', 'Zyyy': 'Common', 'Zzzz': 'Unknown', } fin = open(ucd + '/ScriptExtensions.txt') values = [-1] * (MaxCopePoint + 1) r = re.compile(r"([0-9A-F]+)(?:\.\.([0-9A-F]+))?\s*;\s*(.*?)\s*#.*") ids = {} print("const std::vector<std::vector<Script>> _script_extension_properties_for_id = {") for line in fin: m = r.match(line) if m: firstCode = int(m.group(1), 16) if m.group(2): lastCode = int(m.group(2), 16) + 1 else: lastCode = firstCode + 1 scripts = m.group(3) if scripts in ids: id = ids[scripts] else: id = len(ids) ids[scripts] = id print('{') for sc in [dic[x] for x in scripts.split(' ')]: print(' Script::%s, ' % sc) print('},') for cp in range(firstCode, lastCode): values[cp] = id print("};") generateTable('_script_extension_ids', "int", 0, sys.stdout, values) #------------------------------------------------------------------------------ # genNomalizationPropertyTable #------------------------------------------------------------------------------ def genNomalizationPropertyTable(ucd): fin = open(ucd + '/UnicodeData.txt') data = [x.rstrip().split(';') for x in fin] r = re.compile(r"(?:<(\w+)> )?(.+)") def items(): codePointPrev = -1 i = 0 while i < len(data): flds = data[i] codePoint = int(flds[0], 16) combiningClass = int(flds[3]) codes = flds[5] for cp in range(codePointPrev + 1, codePoint): yield cp, combiningClass, None, [] if flds[1].endswith('First>'): fldsLast = data[i + 1] codePointLast = int(fldsLast[0], 16) for cp in range(codePoint, codePointLast + 1): yield cp, combiningClass, None, [] codePointPrev = codePointLast i += 2 else: m = r.match(codes) if m: compat = m.group(1) codes = [int(x, 16) for x in m.group(2).split(' ')] yield codePoint, combiningClass, compat, codes else: yield codePoint, combiningClass, None, [] codePointPrev = codePoint i += 1 for cp in range(codePointPrev + 1, MaxCopePoint + 1): yield cp, combiningClass, None, [] values = [] for cp, cls, compat, codes in items(): if compat: compat = '"%s"' % compat else: compat = '0' if codes: codes = 'U"%s"' % ''.join(["\\U%08X" % x for x in codes]) else: codes = '0' values.append("{{{},{},{}}}".format(cls, compat, codes)) generateTable('_normalization_properties', 'NormalizationProperties', "{0,0,0}", sys.stdout, values) #------------------------------------------------------------------------------ # genNomalizationCompositionTable #------------------------------------------------------------------------------ def genNomalizationCompositionTable(ucd): fin = open(ucd + '/UnicodeData.txt') finExclusions = open(ucd + '/CompositionExclusions.txt') data = [x.rstrip().split(';') for x in fin] r = re.compile(r"(?:<(\w+)> )?(.+)") def items(): codePointPrev = -1 i = 0 while i < len(data): flds = data[i] codePoint = int(flds[0], 16) combiningClass = int(flds[3]) codes = flds[5] if flds[1].endswith('First>'): fldsLast = data[i + 1] codePointLast = int(fldsLast[0], 16) codePointPrev = codePointLast i += 2 else: m = r.match(codes) if m: compat = m.group(1) codes = [int(x, 16) for x in m.group(2).split(' ')] if len(codes) == 2 and not compat and combiningClass == 0: yield codePoint, codes codePointPrev = codePoint i += 1 exclusions = set() rRange = re.compile(r"(?:# )?([0-9A-F]{4,})(?:\.\.([0-9A-F]+))?.*") for line in finExclusions: m = rRange.match(line) if m: first = int(m.group(1), 16) if m.group(2): last = int(m.group(2), 16) for i in range(first, last + 1): exclusions.add(i) else: exclusions.add(first) print("const std::unordered_map<std::u32string, char32_t> _normalization_composition = {") for cp, codes in items(): if not cp in exclusions: print('{ U"\\U%08X\\U%08X", 0x%08X },' % (codes[0], codes[1], cp)) print("};") #------------------------------------------------------------------------------ # genGraphemeBreakPropertyTable #------------------------------------------------------------------------------ def genGraphemeBreakPropertyTable(ucd): fin = open(ucd + '/auxiliary/GraphemeBreakProperty.txt') defval = 'Unassigned' values = [defval] * (MaxCopePoint + 1) r = re.compile(r"([0-9A-F]+)(?:\.\.([0-9A-F]+))?\s*;\s*(\w+)\s*#.*") for line in fin: m = r.match(line) if m: codePoint = int(m.group(1), 16) value = m.group(3) if m.group(2): codePointLast = int(m.group(2), 16) for cp in range(codePoint, codePointLast + 1): values[cp] = value else: values[codePoint] = value generateTable('_grapheme_break_properties', 'GraphemeBreak', defval, sys.stdout, values) #------------------------------------------------------------------------------ # genWordBreakPropertyTable #------------------------------------------------------------------------------ def genWordBreakPropertyTable(ucd): fin = open(ucd + '/auxiliary/WordBreakProperty.txt') defval = 'Unassigned' values = [defval] * (MaxCopePoint + 1) r = re.compile(r"([0-9A-F]+)(?:\.\.([0-9A-F]+))?\s*;\s*(\w+)\s*#.*") for line in fin: m = r.match(line) if m: codePoint = int(m.group(1), 16) value = m.group(3) if m.group(2): codePointLast = int(m.group(2), 16) for cp in range(codePoint, codePointLast + 1): values[cp] = value else: values[codePoint] = value generateTable('_word_break_properties', 'WordBreak', defval, sys.stdout, values) #------------------------------------------------------------------------------ # genSentenceBreakPropertyTable #------------------------------------------------------------------------------ def genSentenceBreakPropertyTable(ucd): fin = open(ucd + '/auxiliary/SentenceBreakProperty.txt') defval = 'Unassigned' values = [defval] * (MaxCopePoint + 1) r = re.compile(r"([0-9A-F]+)(?:\.\.([0-9A-F]+))?\s*;\s*(\w+)\s*#.*") for line in fin: m = r.match(line) if m: codePoint = int(m.group(1), 16) value = m.group(3) if m.group(2): codePointLast = int(m.group(2), 16) for cp in range(codePoint, codePointLast + 1): values[cp] = value else: values[codePoint] = value generateTable('_sentence_break_properties', 'SentenceBreak', defval, sys.stdout, values) #------------------------------------------------------------------------------ # genEmojiPropertyTable #------------------------------------------------------------------------------ def genEmojiPropertyTable(ucd): fin = open(ucd + '/emoji/emoji-data.txt') defval = 'Unassigned' values = [defval] * (MaxCopePoint + 1) r = re.compile(r"([0-9A-F]+)(?:\.\.([0-9A-F]+))?\s*;\s*(\w+)\s*#.*") for line in fin: m = r.match(line) if m: codePoint = int(m.group(1), 16) value = m.group(3) if m.group(2): codePointLast = int(m.group(2), 16) for cp in range(codePoint, codePointLast + 1): values[cp] = value else: values[codePoint] = value generateTable('_emoji_properties', 'Emoji', defval, sys.stdout, values) #------------------------------------------------------------------------------ # Main #------------------------------------------------------------------------------ if (len(sys.argv) < 2): print('usage: python gen_tables.py UCD_DIR') else: ucd = sys.argv[1] genGeneralCategoryPropertyTable(ucd) genPropertyTable(ucd) genDerivedCorePropertyTable(ucd) genSimpleCaseMappingTable(ucd) genSpecialCaseMappingTable(ucd) genCaseFoldingTable(ucd) genBlockPropertyTable(ucd) genScriptPropertyTable(ucd) genScriptExtensionTable(ucd) genNomalizationPropertyTable(ucd) genNomalizationCompositionTable(ucd) genGraphemeBreakPropertyTable(ucd) genWordBreakPropertyTable(ucd) genSentenceBreakPropertyTable(ucd) genEmojiPropertyTable(ucd)
yhirose/cpp-unicodelib
122
A C++17 header-only Unicode library. (Unicode 17.0.0)
C++
yhirose
scripts/gen_unicode_names.py
Python
import sys import re def getNameAliases(ucd): dict = {} fin = open(ucd + '/NameAliases.txt') for line in fin: line = line.rstrip() if len(line) > 0 and line[0] != '#': flds = line.split(';') cp = int(flds[0], 16) if not cp in dict: dict[cp] = flds[1] return dict def genUnicodeSymbols(ucd): fin = open(ucd + '/UnicodeData.txt') data = [x.rstrip().split(';') for x in fin] def items(): i = 0 while i < len(data): flds = data[i] codePoint = int(flds[0], 16) name = flds[1] yield codePoint, name, len(flds[0]) if flds[1].endswith('First>'): fldsLast = data[i + 1] codePointLast = int(fldsLast[0], 16) nameLast = fldsLast[1] yield codePointLast, nameLast, len(fldsLast[0]) i += 2 else: i += 1 aliases = getNameAliases(ucd) print(''' #pragma once #include <cstdlib> namespace unicode { ''') for cp, name, nameLen in items(): if cp != 0: name = re.sub(r'[<>,]', '', name) if name == 'control': name = aliases[cp] symbol = '_'.join([x.upper() for x in re.split(r"[ -]", name)]) if nameLen > 4: print("const char32_t %s = 0x%08X;" % (symbol, cp)) else: print("const char32_t %s = 0x%04X;" % (symbol, cp)) print(''' } // namespace unicode ''') if (len(sys.argv) < 2): print('usage: python gen_unicode_symbols.py UCD_DIR') else: ucd = sys.argv[1] genUnicodeSymbols(ucd)
yhirose/cpp-unicodelib
122
A C++17 header-only Unicode library. (Unicode 17.0.0)
C++
yhirose
scripts/update.py
Python
#!/usr/bin/env python3 """ Update unicodelib.h with UCD. This script processes unicodelib.h and updates all generated blocks by executing the commands specified in COMMAND: lines. """ import re import subprocess import sys import os def find_generated_blocks(content): """ Find all generated blocks in the content. Returns a list of tuples: (command, start_pos, end_pos) where start_pos is the position after BEGIN marker and end_pos is the position before END marker. """ blocks = [] # Pattern to match COMMAND line followed by BEGIN/END markers command_pattern = re.compile(r'// COMMAND: `([^`]+)`') begin_marker = '// -------- [BEGIN GENERATED BLOCK] --------' end_marker = '// -------- [END GENERATED BLOCK] --------' pos = 0 while True: # Find the next COMMAND line match = command_pattern.search(content, pos) if not match: break command = match.group(1) command_end = match.end() # Find the BEGIN marker after the command begin_pos = content.find(begin_marker, command_end) if begin_pos == -1: print(f"Warning: BEGIN marker not found after command: {command}", file=sys.stderr) pos = command_end continue # The content starts after the BEGIN marker line (including newline) content_start = content.find('\n', begin_pos) + 1 # Find the END marker end_pos = content.find(end_marker, content_start) if end_pos == -1: print(f"Warning: END marker not found after command: {command}", file=sys.stderr) pos = content_start continue blocks.append((command, content_start, end_pos)) pos = end_pos + len(end_marker) return blocks def execute_command(command, working_dir): """ Execute a shell command and return its stdout. """ try: result = subprocess.run( command, shell=True, cwd=working_dir, capture_output=True, text=True, check=True ) return result.stdout except subprocess.CalledProcessError as e: print(f"Error executing command: {command}", file=sys.stderr) print(f"stderr: {e.stderr}", file=sys.stderr) raise def update_file(filepath): """ Update the generated blocks in the specified file. """ # Get the project root directory (parent of scripts directory) script_dir = os.path.dirname(os.path.abspath(__file__)) project_root = os.path.dirname(script_dir) # Read the file content with open(filepath, 'r', encoding='utf-8') as f: content = f.read() # Find all generated blocks blocks = find_generated_blocks(content) if not blocks: print("No generated blocks found.") return print(f"Found {len(blocks)} generated block(s).") # Process blocks in reverse order to preserve positions for command, start_pos, end_pos in reversed(blocks): print(f"Processing: {command}") # Execute the command new_content = execute_command(command, project_root) # Replace the content content = content[:start_pos] + new_content + content[end_pos:] # Write the updated content back with open(filepath, 'w', encoding='utf-8') as f: f.write(content) print("Update complete.") def main(): # Default to unicodelib.h in the project root script_dir = os.path.dirname(os.path.abspath(__file__)) project_root = os.path.dirname(script_dir) if len(sys.argv) > 1: filepath = sys.argv[1] else: filepath = os.path.join(project_root, 'unicodelib.h') if not os.path.exists(filepath): print(f"Error: File not found: {filepath}", file=sys.stderr) sys.exit(1) update_file(filepath) if __name__ == '__main__': main()
yhirose/cpp-unicodelib
122
A C++17 header-only Unicode library. (Unicode 17.0.0)
C++
yhirose
scripts/update.sh
Shell
#!/bin/bash cd "$(dirname "$0")/.." set -e uv run scripts/update.py uv run scripts/gen_unicode_names.py UCD > unicodelib_names.h
yhirose/cpp-unicodelib
122
A C++17 header-only Unicode library. (Unicode 17.0.0)
C++
yhirose
test/test.cpp
C++
#include <unicodelib.h> #include <unicodelib_encodings.h> #include <catch2/catch_test_macros.hpp> #include <fstream> #include <sstream> using namespace std; using namespace unicode; template <class Fn> void split(const char *b, const char *e, char d, Fn fn) { int i = 0; int beg = 0; while (e ? (b + i != e) : (b[i] != '\0')) { if (b[i] == d) { fn(&b[beg], &b[i]); beg = i + 1; } i++; } if (i) { fn(&b[beg], &b[i]); } } //----------------------------------------------------------------------------- // General Category //----------------------------------------------------------------------------- TEST_CASE("General category", "[general category]") { REQUIRE(general_category(0x0000) == GeneralCategory::Cc); REQUIRE(general_category(0x0370) == GeneralCategory::Lu); REQUIRE(general_category(0x0371) == GeneralCategory::Ll); REQUIRE(general_category(0x0483) == GeneralCategory::Mn); REQUIRE(general_category(0x10FFFF) == GeneralCategory::Unassigned); } TEST_CASE("General category predicate functions", "[general category]") { REQUIRE(is_letter(U'a') == true); REQUIRE(is_cased_letter(U'A') == true); REQUIRE(is_letter(U'あ') == true); REQUIRE(is_mark(0x0303) == true); REQUIRE(is_number(U'1') == true); REQUIRE(is_number(U'¼') == true); REQUIRE(is_punctuation(U'-') == true); REQUIRE(is_separator(0x2028) == true); REQUIRE(is_symbol(U'€') == true); REQUIRE(is_other(0x0000) == true); REQUIRE(is_other(0x00AD) == true); // Soft hyphen REQUIRE(is_other(0xD800) == true); // Surrogate REQUIRE(is_other(0xE000) == true); // Private Use REQUIRE(is_other(0x0378) == true); // Unassigned } //----------------------------------------------------------------------------- // Property //----------------------------------------------------------------------------- TEST_CASE("Property", "[property]") { REQUIRE(is_white_space(U'a') == false); REQUIRE(is_white_space(U' ') == true); } //----------------------------------------------------------------------------- // Derived Property //----------------------------------------------------------------------------- TEST_CASE("Derived property", "[derived property]") { REQUIRE(is_math(U'a') == false); REQUIRE(is_math(U' ') == false); REQUIRE(is_math(U'+') == true); REQUIRE(is_alphabetic(U'a') == true); REQUIRE(is_alphabetic(U' ') == false); REQUIRE(is_alphabetic(U'+') == false); } //----------------------------------------------------------------------------- // Case //----------------------------------------------------------------------------- TEST_CASE("Case property", "[case]") { REQUIRE(general_category(U'h') == GeneralCategory::Ll); REQUIRE(is_lowercase(U'h') == true); REQUIRE(is_uppercase(U'h') == false); REQUIRE(general_category(U'H') == GeneralCategory::Lu); REQUIRE(is_lowercase(U'H') == false); REQUIRE(is_uppercase(U'H') == true); REQUIRE(general_category(0x24D7) == GeneralCategory::So); REQUIRE(is_lowercase(0x24D7) == true); REQUIRE(is_uppercase(0x24D7) == false); REQUIRE(general_category(0x24BD) == GeneralCategory::So); REQUIRE(is_lowercase(0x24BD) == false); REQUIRE(is_uppercase(0x24BD) == true); REQUIRE(general_category(0x02B0) == GeneralCategory::Lm); REQUIRE(is_lowercase(0x02B0) == true); REQUIRE(is_uppercase(0x02B0) == false); REQUIRE(general_category(0x1D34) == GeneralCategory::Lm); REQUIRE(is_lowercase(0x1D34) == true); REQUIRE(is_uppercase(0x1D34) == false); REQUIRE(general_category(0x02BD) == GeneralCategory::Lm); REQUIRE(is_lowercase(0x02BD) == false); REQUIRE(is_uppercase(0x02BD) == false); } TEST_CASE("Simple case mapping", "[case]") { REQUIRE(simple_lowercase_mapping(U'A') == U'a'); REQUIRE(simple_lowercase_mapping(U'a') == U'a'); REQUIRE(simple_lowercase_mapping(U'あ') == U'あ'); REQUIRE(simple_lowercase_mapping(U',') == U','); REQUIRE(simple_lowercase_mapping(0x118DF) == 0x118DF); REQUIRE(simple_lowercase_mapping(0x118BF) == 0x118DF); REQUIRE(simple_uppercase_mapping(U'A') == U'A'); REQUIRE(simple_uppercase_mapping(U'a') == U'A'); REQUIRE(simple_uppercase_mapping(U'あ') == U'あ'); REQUIRE(simple_uppercase_mapping(U',') == U','); REQUIRE(simple_uppercase_mapping(0x118DF) == 0x118BF); REQUIRE(simple_uppercase_mapping(0x118BF) == 0x118BF); REQUIRE(simple_lowercase_mapping(U'DZ') == U'dz'); REQUIRE(simple_lowercase_mapping(U'Dz') == U'dz'); REQUIRE(simple_lowercase_mapping(U'dz') == U'dz'); REQUIRE(simple_uppercase_mapping(U'DZ') == U'DZ'); REQUIRE(simple_uppercase_mapping(U'Dz') == U'DZ'); REQUIRE(simple_uppercase_mapping(U'dz') == U'DZ'); REQUIRE(simple_titlecase_mapping(U'DZ') == U'Dz'); REQUIRE(simple_titlecase_mapping(U'Dz') == U'Dz'); REQUIRE(simple_titlecase_mapping(U'dz') == U'Dz'); } TEST_CASE("Simple case folding", "[case]") { REQUIRE(simple_case_folding(U'A') == U'a'); REQUIRE(simple_case_folding(U'a') == U'a'); REQUIRE(simple_case_folding(U'あ') == U'あ'); REQUIRE(simple_case_folding(U',') == U','); REQUIRE(simple_case_folding(0x118DF) == 0x118DF); REQUIRE(simple_case_folding(0x118BF) == 0x118DF); REQUIRE(simple_case_folding(U'DZ') == U'dz'); REQUIRE(simple_case_folding(U'Dz') == U'dz'); REQUIRE(simple_case_folding(U'dz') == U'dz'); } TEST_CASE("Full case mapping", "[case]") { // Sigma REQUIRE(to_lowercase(U"Σ") == U"σ"); REQUIRE(to_lowercase(U"ΧΑΟΣ") == U"χαος"); REQUIRE(to_lowercase(U"ΧΑΟΣΣ") == U"χαοσς"); REQUIRE(to_lowercase(U"ΧΑΟΣ Σ") == U"χαος σ"); REQUIRE(to_uppercase(U"σ") == U"Σ"); REQUIRE(to_uppercase(U"χαος") == U"ΧΑΟΣ"); REQUIRE(to_uppercase(U"χαοσς") == U"ΧΑΟΣΣ"); REQUIRE(to_uppercase(U"χαος σ") == U"ΧΑΟΣ Σ"); // German REQUIRE(to_uppercase(U"Maße") == U"MASSE"); // Title case REQUIRE(to_titlecase(U"hello WORLD. A, a.") == U"Hello World. A, A."); REQUIRE(to_titlecase(U"ΧΑΟΣ χαος Σ σ") == U"Χαος Χαος Σ Σ"); REQUIRE(to_titlecase(U"DZabc dzabc Dzabc") == U"Dzabc Dzabc Dzabc"); // Dutch IJ titlecasing REQUIRE(to_titlecase(U"ijsje", "nl") == U"IJsje"); REQUIRE(to_titlecase(U"IJssel", "nl") == U"IJssel"); REQUIRE(to_titlecase(U"ik hou van ijsje", "nl") == U"Ik Hou Van IJsje"); REQUIRE(to_titlecase(U"ijmuiden", "nl") == U"IJmuiden"); REQUIRE(to_titlecase(U"IJMUIDEN", "nl") == U"IJmuiden"); // Without Dutch locale, IJ should not be special-cased REQUIRE(to_titlecase(U"ijsje") == U"Ijsje"); REQUIRE(to_titlecase(U"ijsje", "en") == U"Ijsje"); } TEST_CASE("Full case folding", "[case]") { REQUIRE(to_case_fold(U"heiss") == to_case_fold(U"heiß")); } TEST_CASE("Casless match", "[case]") { REQUIRE(caseless_match(U"résumé", U"RéSUMé") == true); // German REQUIRE(caseless_match(U"MASSE", U"Maße") == true); REQUIRE(caseless_match(U"Dürst", U"DüRST") == true); // Turkish dot I REQUIRE(caseless_match(U"Istanbul", U"ıstanbul") == false); REQUIRE(caseless_match(U"İstanbul", U"istanbul") == false); REQUIRE(caseless_match(U"İstanbul", U"ıstanbul") == false); REQUIRE(caseless_match(U"İstanbul", U"Istanbul") == false); REQUIRE(caseless_match(U"Istanbul", U"istanbul") == true); REQUIRE(caseless_match(U"Istanbul", U"ıstanbul", true) == true); REQUIRE(caseless_match(U"İstanbul", U"istanbul", true) == true); REQUIRE(caseless_match(U"İstanbul", U"ıstanbul", true) == false); REQUIRE(caseless_match(U"İstanbul", U"Istanbul", true) == false); REQUIRE(caseless_match(U"Istanbul", U"istanbul", true) == false); // Sigma REQUIRE(caseless_match(U"όσος", U"ΌΣΟΣ") == true); // French (ignore diacritics) // REQUIRE(caseless_match(U"côte", U"côté") == true); } TEST_CASE("case detection", "[case]") { REQUIRE(is_uppercase(U"ΌΣΟΣ HELLO") == true); REQUIRE(is_uppercase(U"όσος hello") == false); REQUIRE(is_lowercase(U"ΌΣΟΣ HELLO") == false); REQUIRE(is_lowercase(U"όσος hello") == true); REQUIRE(is_titlecase(U"ΌΣΟΣ HELLO") == false); REQUIRE(is_titlecase(U"όσος hello") == false); REQUIRE(is_titlecase(U"Όσος Hello") == true); REQUIRE(is_case_fold(U"heiss") == true); REQUIRE(is_case_fold(U"heiß") == false); } //----------------------------------------------------------------------------- // Text Segmentation //----------------------------------------------------------------------------- TEST_CASE("Combining character sequence", "[segmentation]") { REQUIRE(is_graphic_character(U'あ')); REQUIRE(is_graphic_character(0x0001) == false); REQUIRE(is_base_character(U'A')); REQUIRE(is_base_character(0x0300) == false); REQUIRE(is_combining_character(U'A') == false); REQUIRE(is_combining_character(0x0300)); std::u32string base = U"\u0061\u0062"; REQUIRE(combining_character_sequence_length(base.data(), base.length()) == 1); std::u32string valid = U"\u0061\u0301\u0302\u0062"; REQUIRE(combining_character_sequence_length(valid.data(), valid.length()) == 3); std::u32string invalid = U"\u0301\u0302\u0062"; REQUIRE(combining_character_sequence_length(invalid.data(), invalid.length()) == 2); std::u32string zwj = U"\u0061\u200D\u0062"; // TODO: Need better examples REQUIRE(combining_character_sequence_length(zwj.data(), zwj.length()) == 2); std::u32string zwnj = U"\u0061\u200C\u0062"; // TODO: Need better examples REQUIRE(combining_character_sequence_length(zwnj.data(), zwnj.length()) == 2); std::u32string count = U"\u0061\u0301\u0302\u0062\u0301\u0063"; REQUIRE(combining_character_sequence_count(count.data(), count.length()) == 3); std::u32string korean = U"\uD4DB\u1111\u1171\u11B6"; REQUIRE(combining_character_sequence_count(korean.data(), korean.length()) == 4); REQUIRE(extended_combining_character_sequence_count(korean.data(), korean.length()) == 2); // D56: The sequence <0030, FE00, 20E3> represents a variant form of the digit // zero, followed by an enclosing keycap. std::u32string enclosing_keycap = U"\u0030\uFE00\u20E3\u0030\uFE00\u20E3"; REQUIRE(combining_character_sequence_length(enclosing_keycap.data(), enclosing_keycap.length()) == 3); REQUIRE(combining_character_sequence_count(enclosing_keycap.data(), enclosing_keycap.length()) == 2); } template <typename T> void read_text_segmentation_test_file(const char *path, T callback) { ifstream fs(path); REQUIRE(fs); size_t ln = 0; std::string line; while (std::getline(fs, line)) { ln++; if (line.empty() || line[0] == '#') { continue; } line.erase(line.find('\t')); std::u32string s32; std::vector<bool> boundary; size_t expected_count = 0; stringstream ss(line); string ope; char32_t ope_cp; ss >> ope; utf8::decode_codepoint(ope.data(), ope.length(), ope_cp); boundary.push_back(ope_cp == U'÷'); while (!ss.eof()) { int val; ss >> hex >> val; s32 += static_cast<char32_t>(val); ss >> ope; utf8::decode_codepoint(ope.data(), ope.length(), ope_cp); auto is_boundary = (ope_cp == U'÷'); boundary.push_back(is_boundary); expected_count += (is_boundary ? 1 : 0); } callback(s32, boundary, expected_count, ln); } } TEST_CASE("Grapheme cluster segmentation", "[segmentation]") { auto path = "../UCD/auxiliary/GraphemeBreakTest.txt"; read_text_segmentation_test_file( path, [](const auto &s32, const auto &boundary, auto expected_count, auto /*ln*/) { for (auto i = 0u; i < boundary.size(); i++) { auto actual = is_grapheme_boundary(s32.data(), s32.length(), i); CHECK(boundary[i] == actual); } CHECK(expected_count == grapheme_count(s32)); }); } TEST_CASE("Word segmentation", "[segmentation]") { auto path = "../UCD/auxiliary/WordBreakTest.txt"; read_text_segmentation_test_file( path, [](const auto &s32, const auto &boundary, auto /*expected_count*/, auto /*ln*/) { for (auto i = 0u; i < boundary.size(); i++) { auto actual = is_word_boundary(s32.data(), s32.length(), i); CHECK(boundary[i] == actual); } }); } TEST_CASE("Sentence segmentation", "[segmentation]") { auto path = "../UCD/auxiliary/SentenceBreakTest.txt"; read_text_segmentation_test_file( path, [](const auto &s32, const auto &boundary, auto /*expected_count*/, auto /*ln*/) { for (auto i = 0u; i < boundary.size(); i++) { auto actual = is_sentence_boundary(s32.data(), s32.length(), i); CHECK(boundary[i] == actual); } }); } //----------------------------------------------------------------------------- // Block //----------------------------------------------------------------------------- TEST_CASE("Block", "[block]") { REQUIRE(block(U'a') == Block::BasicLatin); REQUIRE(block(U'あ') == Block::Hiragana); } //----------------------------------------------------------------------------- // Script //----------------------------------------------------------------------------- TEST_CASE("Script", "[script]") { REQUIRE(script(U'a') == Script::Latin); REQUIRE(script(U'あ') == Script::Hiragana); REQUIRE(script(U'ー') == Script::Common); } TEST_CASE("Script extension", "[script]") { REQUIRE(is_script(Script::Hiragana, U'ー')); REQUIRE(is_script(Script::Katakana, U'ー')); REQUIRE(is_script(Script::Latin, U'ー') == false); } //----------------------------------------------------------------------------- // Normalization //----------------------------------------------------------------------------- TEST_CASE("Normalization", "[normalization]") { ifstream fs("../UCD/NormalizationTest.txt"); REQUIRE(fs); std::string line; while (std::getline(fs, line)) { if (line.empty() || line[0] == '#' || line[0] == '@') { continue; } line.erase(line.find("; #")); vector<u32string> fields; split(line.data(), line.data() + line.length(), ';', [&](auto b, auto e) { u32string codes; split(b, e, ' ', [&](auto b, auto e) { char32_t cp = stoi(string(b, e), nullptr, 16); codes += cp; }); fields.push_back(codes); }); const auto &c1 = fields[0]; const auto &c2 = fields[1]; const auto &c3 = fields[2]; const auto &c4 = fields[3]; const auto &c5 = fields[4]; // NFC // c2 == toNFC(c1) == toNFC(c2) == toNFC(c3) // c4 == toNFC(c4) == toNFC(c5) REQUIRE(c2 == to_nfc(c1)); REQUIRE(c2 == to_nfc(c2)); REQUIRE(c2 == to_nfc(c3)); REQUIRE(c4 == to_nfc(c4)); REQUIRE(c4 == to_nfc(c5)); // NFD // c3 == toNFD(c1) == toNFD(c2) == toNFD(c3) // c5 == toNFD(c4) == toNFD(c5) REQUIRE(c3 == to_nfd(c1)); REQUIRE(c3 == to_nfd(c2)); REQUIRE(c3 == to_nfd(c3)); REQUIRE(c5 == to_nfd(c4)); REQUIRE(c5 == to_nfd(c5)); // NFKC // c4 == toNFKC(c1) == toNFKC(c2) == toNFKC(c3) == toNFKC(c4) == // toNFKC(c5) REQUIRE(c4 == to_nfkc(c1)); REQUIRE(c4 == to_nfkc(c2)); REQUIRE(c4 == to_nfkc(c3)); REQUIRE(c4 == to_nfkc(c4)); REQUIRE(c4 == to_nfkc(c5)); // NFKD // c5 == toNFKD(c1) == toNFKD(c2) == toNFKD(c3) == toNFKD(c4) == // toNFKD(c5) REQUIRE(c5 == to_nfkd(c1)); REQUIRE(c5 == to_nfkd(c2)); REQUIRE(c5 == to_nfkd(c3)); REQUIRE(c5 == to_nfkd(c4)); REQUIRE(c5 == to_nfkd(c5)); } } //----------------------------------------------------------------------------- // UTF8 encoding //----------------------------------------------------------------------------- namespace test_utf8 { std::string u8text = u8"日本語もOKです。"; std::u32string u32text = U"日本語もOKです。"; std::string str1(u8"a"); std::string str2(u8"À"); std::string str3(u8"あ"); std::string str4(u8"𠀋"); TEST_CASE("codepoint length in char32_t", "[utf8]") { REQUIRE(utf8::codepoint_length(U'a') == 1); REQUIRE(utf8::codepoint_length(U'À') == 2); REQUIRE(utf8::codepoint_length(U'あ') == 3); REQUIRE(utf8::codepoint_length(U'𠀋') == 4); } TEST_CASE("encode 1", "[utf8]") { std::string out1, out2, out3, out4; REQUIRE(utf8::encode_codepoint(U'a', out1) == 1); REQUIRE(utf8::encode_codepoint(U'À', out2) == 2); REQUIRE(utf8::encode_codepoint(U'あ', out3) == 3); REQUIRE(utf8::encode_codepoint(U'𠀋', out4) == 4); REQUIRE(out1 == u8"a"); REQUIRE(out2 == u8"À"); REQUIRE(out3 == u8"あ"); REQUIRE(out4 == u8"𠀋"); } TEST_CASE("encode 2", "[utf8]") { std::string out; utf8::encode(u32text, out); REQUIRE(out == u8"日本語もOKです。"); } TEST_CASE("encode 3", "[utf8]") { REQUIRE(utf8::encode(u32text) == u8"日本語もOKです。"); } TEST_CASE("codepoint length in utf8", "[utf8]") { REQUIRE(utf8::codepoint_length(str1) == 1); REQUIRE(utf8::codepoint_length(str2) == 2); REQUIRE(utf8::codepoint_length(str3) == 3); REQUIRE(utf8::codepoint_length(str4) == 4); } TEST_CASE("codepoint_count", "[utf8]") { REQUIRE(utf8::codepoint_count(u8text) == 9); } TEST_CASE("decode 1", "[utf8]") { char32_t out1, out2, out3, out4; REQUIRE(utf8::decode_codepoint(str1, out1) == 1); REQUIRE(utf8::decode_codepoint(str2, out2) == 2); REQUIRE(utf8::decode_codepoint(str3, out3) == 3); REQUIRE(utf8::decode_codepoint(str4, out4) == 4); REQUIRE(utf8::decode_codepoint(str1) == 0x0061); REQUIRE(utf8::decode_codepoint(str2) == 0x00C0); REQUIRE(utf8::decode_codepoint(str3) == 0x3042); REQUIRE(utf8::decode_codepoint(str4) == 0x2000B); } TEST_CASE("decode 2", "[utf8]") { std::u32string out1; utf8::decode(u8text, out1); REQUIRE(out1 == u32text); std::u32string out2; utf8::decode(u8text, out2); REQUIRE(out2 == u32text); } TEST_CASE("decode 3", "[utf8]") { REQUIRE(utf8::decode(u8text) == u32text); REQUIRE(utf8::decode(u8text) == u32text); } } // namespace test_utf8 //----------------------------------------------------------------------------- // UTF16 encoding //----------------------------------------------------------------------------- namespace test_utf16 { std::u16string u16text = u"日本語もOKです。"; std::u32string u32text = U"日本語もOKです。"; std::u16string str1(u"a"); std::u16string str2(u"À"); std::u16string str3(u"あ"); std::u16string str4(u"𠀋"); TEST_CASE("utf16 codepoint length in char32_t", "[utf16]") { REQUIRE(utf16::codepoint_length(U'a') == 1); REQUIRE(utf16::codepoint_length(U'À') == 1); REQUIRE(utf16::codepoint_length(U'あ') == 1); REQUIRE(utf16::codepoint_length(U'𠀋') == 2); } TEST_CASE("utf16 encode 1", "[utf16]") { std::u16string out1, out2, out3, out4; REQUIRE(utf16::encode_codepoint(U'a', out1) == 1); REQUIRE(utf16::encode_codepoint(U'À', out2) == 1); REQUIRE(utf16::encode_codepoint(U'あ', out3) == 1); REQUIRE(utf16::encode_codepoint(U'𠀋', out4) == 2); REQUIRE(out1 == u"a"); REQUIRE(out2 == u"À"); REQUIRE(out3 == u"あ"); REQUIRE(out4 == u"𠀋"); } TEST_CASE("utf16 encode 2", "[utf16]") { std::u16string out; utf16::encode(u32text, out); REQUIRE(out == u"日本語もOKです。"); } TEST_CASE("utf16 encode 3", "[utf16]") { REQUIRE(utf16::encode(u32text) == u"日本語もOKです。"); } TEST_CASE("codepoint length in utf16", "[utf16]") { REQUIRE(utf16::codepoint_length(str1) == 1); REQUIRE(utf16::codepoint_length(str2) == 1); REQUIRE(utf16::codepoint_length(str3) == 1); REQUIRE(utf16::codepoint_length(str4) == 2); } TEST_CASE("utf16 codepoint_count", "[utf16]") { REQUIRE(utf16::codepoint_count(u16text) == 9); } TEST_CASE("utf16 decode 1", "[utf16]") { char32_t out1, out2, out3, out4; REQUIRE(utf16::decode_codepoint(str1, out1) == 1); REQUIRE(utf16::decode_codepoint(str2, out2) == 1); REQUIRE(utf16::decode_codepoint(str3, out3) == 1); REQUIRE(utf16::decode_codepoint(str4, out4) == 2); REQUIRE(utf16::decode_codepoint(str1) == 0x0061); REQUIRE(utf16::decode_codepoint(str2) == 0x00C0); REQUIRE(utf16::decode_codepoint(str3) == 0x3042); REQUIRE(utf16::decode_codepoint(str4) == 0x2000B); } TEST_CASE("utf16 decode 2", "[utf16]") { std::u32string out1; utf16::decode(u16text, out1); REQUIRE(out1 == u32text); std::u32string out2; utf16::decode(u16text, out2); REQUIRE(out2 == u32text); } TEST_CASE("utf16 decode 3", "[utf16]") { REQUIRE(utf16::decode(u16text) == u32text); REQUIRE(utf16::decode(u16text) == u32text); } } // namespace test_utf16 //----------------------------------------------------------------------------- // Conversion between encodings //----------------------------------------------------------------------------- namespace test_encodeings { TEST_CASE("Conversion text", "[encodings]") { std::string u8text = u8"日本語もOKです。"; std::u16string u16text = u"日本語もOKです。"; std::u32string u32text = U"日本語もOKです。"; std::wstring wtext = L"日本語もOKです。"; REQUIRE(to_utf16(u8text) == u16text); REQUIRE(to_utf8(u16text) == u8text); REQUIRE(to_wstring(u8text) == wtext); REQUIRE(to_wstring(u16text) == wtext); REQUIRE(to_wstring(u32text) == wtext); REQUIRE(to_utf8(wtext) == u8text); REQUIRE(to_utf16(wtext) == u16text); REQUIRE(to_utf32(wtext) == u32text); } } // namespace test_encodeings // vim: et ts=2 sw=2 cin cino=\:0 ff=unix
yhirose/cpp-unicodelib
122
A C++17 header-only Unicode library. (Unicode 17.0.0)
C++
yhirose
test/test2.cpp
C++
// This file is to check duplicate symbols #include <catch2/catch_test_macros.hpp> #include <unicodelib.h> TEST_CASE("Duplicate Check", "[duplicate]") { REQUIRE(unicode::is_white_space(U'a') == false); }
yhirose/cpp-unicodelib
122
A C++17 header-only Unicode library. (Unicode 17.0.0)
C++
yhirose
unicodelib_encodings.h
C/C++ Header
// // unicodelib_encodings.h // // Copyright (c) 2025 Yuji Hirose. All rights reserved. // MIT License // #pragma once #include <cstdint> #include <cstdlib> #include <string> #if !defined(__cplusplus) || __cplusplus < 201703L #error "Requires complete C++17 support" #endif /* namespace utf8 { size_t codepoint_length(char32_t cp); size_t codepoint_length(const char *s8, size_t l); size_t codepoint_count(const char *s8, size_t l); size_t encode_codepoint(char32_t cp, std::string &out); void encode(const char32_t *s32, size_t l, std::string &out); size_t decode_codepoint(const char *s8, size_t l, char32_t &out); void decode(const char *s8, size_t l, std::u32string &out); } // namespace utf8 namespace utf16 { size_t codepoint_length(char32_t cp); size_t codepoint_length(const char16_t *s16, size_t l); size_t codepoint_count(const char16_t *s16, size_t l); size_t encode_codepoint(char32_t cp, std::u16string &out); void encode(const char32_t *s32, size_t l, std::u16string &out); size_t decode_codepoint(const char16_t *s16, size_t l, char32_t &out); void decode(const char16_t *s16, size_t l, std::u32string &out); } // namespace utf16 std::string to_utf8(const char16_t *s16, size_t l); std::u16string to_utf16(const char *s8, size_t l); std::wstring to_wstring(const char *s8, size_t l); std::wstring to_wstring(const char16_t *s16, size_t l); std::wstring to_wstring(const char32_t *s32, size_t l); std::string to_utf8(const wchar_t *sw, size_t l); std::u16string to_utf16(const wchar_t *sw, size_t l); std::u32string to_utf32(const wchar_t *sw, size_t l); */ namespace unicode { //----------------------------------------------------------------------------- // UTF8 encoding //----------------------------------------------------------------------------- namespace utf8 { inline size_t codepoint_length(char32_t cp) { if (cp < 0x0080) { return 1; } else if (cp < 0x0800) { return 2; } else if (cp < 0xD800) { return 3; } else if (cp < 0xe000) { // D800 - DFFF is invalid... return 0; } else if (cp < 0x10000) { return 3; } else if (cp < 0x110000) { return 4; } return 0; } inline size_t codepoint_length(const char *s8, size_t l) { if (l) { uint8_t b = s8[0]; if ((b & 0x80) == 0) { return 1; } else if ((b & 0xE0) == 0xC0) { return 2; } else if ((b & 0xF0) == 0xE0) { return 3; } else if ((b & 0xF8) == 0xF0) { return 4; } } return 0; } inline size_t codepoint_count(const char *s8, size_t l) { size_t count = 0; for (size_t i = 0; i < l; i += codepoint_length(s8 + i, l - i)) { count++; } return count; } inline size_t encode_codepoint(char32_t cp, char *buff) { if (cp < 0x0080) { buff[0] = static_cast<uint8_t>(cp & 0x7F); return 1; } else if (cp < 0x0800) { buff[0] = static_cast<uint8_t>(0xC0 | ((cp >> 6) & 0x1F)); buff[1] = static_cast<uint8_t>(0x80 | (cp & 0x3F)); return 2; } else if (cp < 0xD800) { buff[0] = static_cast<uint8_t>(0xE0 | ((cp >> 12) & 0xF)); buff[1] = static_cast<uint8_t>(0x80 | ((cp >> 6) & 0x3F)); buff[2] = static_cast<uint8_t>(0x80 | (cp & 0x3F)); return 3; } else if (cp < 0xE000) { // D800 - DFFF is invalid... return 0; } else if (cp < 0x10000) { buff[0] = static_cast<uint8_t>(0xE0 | ((cp >> 12) & 0xF)); buff[1] = static_cast<uint8_t>(0x80 | ((cp >> 6) & 0x3F)); buff[2] = static_cast<uint8_t>(0x80 | (cp & 0x3F)); return 3; } else if (cp < 0x110000) { buff[0] = static_cast<uint8_t>(0xF0 | ((cp >> 18) & 0x7)); buff[1] = static_cast<uint8_t>(0x80 | ((cp >> 12) & 0x3F)); buff[2] = static_cast<uint8_t>(0x80 | ((cp >> 6) & 0x3F)); buff[3] = static_cast<uint8_t>(0x80 | (cp & 0x3F)); return 4; } return 0; } inline size_t encode_codepoint(char32_t cp, std::string &out) { char buff[4]; auto l = encode_codepoint(cp, buff); out.append(buff, l); return l; } inline void encode(const char32_t *s32, size_t l, std::string &out) { for (size_t i = 0; i < l; i++) { encode_codepoint(s32[i], out); } } inline bool decode_codepoint(const char *s8, size_t l, size_t &bytes, char32_t &cp) { if (l) { uint8_t b = s8[0]; if ((b & 0x80) == 0) { bytes = 1; cp = b; return true; } else if ((b & 0xE0) == 0xC0) { if (l >= 2) { bytes = 2; cp = ((static_cast<char32_t>(s8[0] & 0x1F)) << 6) | (static_cast<char32_t>(s8[1] & 0x3F)); return true; } } else if ((b & 0xF0) == 0xE0) { if (l >= 3) { bytes = 3; cp = ((static_cast<char32_t>(s8[0] & 0x0F)) << 12) | ((static_cast<char32_t>(s8[1] & 0x3F)) << 6) | (static_cast<char32_t>(s8[2] & 0x3F)); return true; } } else if ((b & 0xF8) == 0xF0) { if (l >= 4) { bytes = 4; cp = ((static_cast<char32_t>(s8[0] & 0x07)) << 18) | ((static_cast<char32_t>(s8[1] & 0x3F)) << 12) | ((static_cast<char32_t>(s8[2] & 0x3F)) << 6) | (static_cast<char32_t>(s8[3] & 0x3F)); return true; } } } return false; } inline size_t decode_codepoint(const char *s8, size_t l, char32_t &out) { size_t bytes; if (decode_codepoint(s8, l, bytes, out)) { return bytes; } return 0; } template <typename T> inline void for_each(const char *s8, size_t l, T callback) { size_t id = 0; size_t i = 0; while (i < l) { auto beg = i++; while (i < l && (s8[i] & 0xc0) == 0x80) { i++; } callback(s8, l, beg, i, id++); } } inline void decode(const char *s8, size_t l, std::u32string &out) { for_each( s8, l, [&](const char *s, size_t /*l*/, size_t beg, size_t end, size_t /*i*/) { size_t bytes; char32_t cp; if (decode_codepoint(&s[beg], (end - beg), bytes, cp)) { out += cp; } }); } } // namespace utf8 //----------------------------------------------------------------------------- // UTF16 encoding //----------------------------------------------------------------------------- namespace utf16 { inline bool is_surrogate_pair(const char16_t *s16, size_t l) { if (l > 0) { auto first = s16[0]; if (0xD800 <= first && first < 0xDC00) { auto second = s16[1]; if (0xDC00 <= second && second < 0xE000) { return true; } } } return false; } inline size_t codepoint_length(char32_t cp) { return cp <= 0xFFFF ? 1 : 2; } inline size_t codepoint_length(const char16_t *s16, size_t l) { if (l > 0) { if (is_surrogate_pair(s16, l)) { return 2; } return 1; } return 0; } inline size_t codepoint_count(const char16_t *s16, size_t l) { size_t count = 0; for (size_t i = 0; i < l; i += codepoint_length(s16 + i, l - i)) { count++; } return count; } inline size_t encode_codepoint(char32_t cp, char16_t *buff) { if (cp < 0xD800) { buff[0] = static_cast<char16_t>(cp); return 1; } else if (cp < 0xE000) { // D800 - DFFF is invalid... return 0; } else if (cp < 0x10000) { buff[0] = static_cast<char16_t>(cp); return 1; } else if (cp < 0x110000) { // high surrogate buff[0] = static_cast<char16_t>(0xD800 + (((cp - 0x10000) >> 10) & 0x3FF)); // low surrogate buff[1] = static_cast<char16_t>(0xDC00 + ((cp - 0x10000) & 0x3FF)); return 2; } return 0; } inline size_t encode_codepoint(char32_t cp, std::u16string &out) { char16_t buff[2]; auto l = encode_codepoint(cp, buff); out.append(buff, l); return l; } inline void encode(const char32_t *s32, size_t l, std::u16string &out) { for (size_t i = 0; i < l; i++) { encode_codepoint(s32[i], out); } } inline bool decode_codepoint(const char16_t *s16, size_t l, size_t &length, char32_t &cp) { if (l) { // Surrogate auto first = s16[0]; if (0xD800 <= first && first < 0xDC00) { if (l >= 2) { auto second = s16[1]; if (0xDC00 <= second && second < 0xE000) { cp = (((first - 0xD800) << 10) | (second - 0xDC00)) + 0x10000; length = 2; return true; } } } // Non surrogate else { cp = first; length = 1; return true; } } return false; } inline size_t decode_codepoint(const char16_t *s16, size_t l, char32_t &out) { size_t length; if (decode_codepoint(s16, l, length, out)) { return length; } return 0; } template <typename T> inline void for_each(const char16_t *s16, size_t l, T callback) { size_t id = 0; size_t i = 0; while (i < l) { auto beg = i++; if (is_surrogate_pair(&s16[beg], l - beg)) { i++; } callback(s16, l, beg, i, id++); } } inline void decode(const char16_t *s16, size_t l, std::u32string &out) { for_each(s16, l, [&](const char16_t *s, size_t /*l*/, size_t beg, size_t end, size_t /*i*/) { size_t length; char32_t cp; if (decode_codepoint(&s[beg], (end - beg), length, cp)) { out += cp; } }); } } // namespace utf16 //----------------------------------------------------------------------------- // Inline Wrapper functions //----------------------------------------------------------------------------- namespace utf8 { inline size_t codepoint_length(std::string_view s8) { return codepoint_length(s8.data(), s8.length()); } inline size_t codepoint_count(std::string_view s8) { return codepoint_count(s8.data(), s8.length()); } inline std::string encode_codepoint(char32_t cp) { std::string out; encode_codepoint(cp, out); return out; } inline void encode(std::u32string_view s32, std::string &out) { encode(s32.data(), s32.length(), out); } inline std::string encode(const char32_t *s32, size_t l) { std::string out; encode(s32, l, out); return out; } inline std::string encode(std::u32string_view s32) { return encode(s32.data(), s32.length()); } inline size_t decode_codepoint(std::string_view s8, char32_t &cp) { return decode_codepoint(s8.data(), s8.length(), cp); } inline char32_t decode_codepoint(const char *s8, size_t l) { char32_t out = 0; decode_codepoint(s8, l, out); return out; } inline char32_t decode_codepoint(std::string_view s8) { return decode_codepoint(s8.data(), s8.length()); } inline void decode(std::string_view s8, std::u32string &out) { decode(s8.data(), s8.length(), out); } inline std::u32string decode(const char *s8, size_t l) { std::u32string out; decode(s8, l, out); return out; } inline std::u32string decode(std::string_view s8) { return decode(s8.data(), s8.length()); } } // namespace utf8 namespace utf16 { inline size_t codepoint_length(std::u16string_view s16) { return codepoint_length(s16.data(), s16.length()); } inline size_t codepoint_count(std::u16string_view s16) { return codepoint_count(s16.data(), s16.length()); } inline std::u16string encode_codepoint(char32_t cp) { std::u16string out; encode_codepoint(cp, out); return out; } inline void encode(std::u32string_view s32, std::u16string &out) { encode(s32.data(), s32.length(), out); } inline std::u16string encode(const char32_t *s32, size_t l) { std::u16string out; encode(s32, l, out); return out; } inline std::u16string encode(std::u32string_view s32) { return encode(s32.data(), s32.length()); } inline size_t decode_codepoint(std::u16string_view s16, char32_t &cp) { return decode_codepoint(s16.data(), s16.length(), cp); } inline char32_t decode_codepoint(const char16_t *s16, size_t l) { char32_t out = 0; decode_codepoint(s16, l, out); return out; } inline char32_t decode_codepoint(std::u16string_view s16) { return decode_codepoint(s16.data(), s16.length()); } inline void decode(std::u16string_view s16, std::u32string &out) { decode(s16.data(), s16.length(), out); } inline std::u32string decode(const char16_t *s16, size_t l) { std::u32string out; decode(s16, l, out); return out; } inline std::u32string decode(std::u16string_view s16) { return decode(s16.data(), s16.length()); } } // namespace utf16 //----------------------------------------------------------------------------- // utf8/utf16 conversion //----------------------------------------------------------------------------- inline std::string to_utf8(const char16_t *s16, size_t l) { return utf8::encode(utf16::decode(s16, l)); } inline std::string to_utf8(std::u16string_view s16) { return to_utf8(s16.data(), s16.length()); } inline std::u16string to_utf16(const char *s8, size_t l) { return utf16::encode(utf8::decode(s8, l)); } inline std::u16string to_utf16(std::string_view s8) { return to_utf16(s8.data(), s8.length()); } //----------------------------------------------------------------------------- // std::wstring conversion //----------------------------------------------------------------------------- namespace detail { inline std::wstring to_wstring_core(const char *s8, size_t l) { if constexpr (sizeof(wchar_t) == 2) { auto s16 = utf16::encode(utf8::decode(s8, l)); return std::wstring(s16.begin(), s16.end()); } else if constexpr (sizeof(wchar_t) == 4) { auto s32 = utf8::decode(s8, l); return std::wstring(s32.begin(), s32.end()); } } inline std::wstring to_wstring_core(const char16_t *s16, size_t l) { if constexpr (sizeof(wchar_t) == 2) { return std::wstring(s16, s16 + l); } else if constexpr (sizeof(wchar_t) == 4) { auto s32 = utf16::decode(s16, l); return std::wstring(s32.begin(), s32.end()); } } inline std::wstring to_wstring_core(const char32_t *s32, size_t l) { if constexpr (sizeof(wchar_t) == 2) { auto s16 = utf16::encode(s32, l); return std::wstring(s16.begin(), s16.end()); } else if constexpr (sizeof(wchar_t) == 4) { return std::wstring(s32, s32 + l); } } inline std::string to_utf8_core(const wchar_t *sw, size_t l) { if constexpr (sizeof(wchar_t) == 2) { std::u16string buf(sw, sw + l); return utf8::encode(utf16::decode(buf.data(), l)); } else if constexpr (sizeof(wchar_t) == 4) { std::u32string buf(sw, sw + l); return utf8::encode(buf.data(), l); } } inline std::u16string to_utf16_core(const wchar_t *sw, size_t l) { if constexpr (sizeof(wchar_t) == 2) { return std::u16string(sw, sw + l); } else if constexpr (sizeof(wchar_t) == 4) { std::u32string buf(sw, sw + l); return utf16::encode(buf.data(), l); } } inline std::u32string to_utf32_core(const wchar_t *sw, size_t l) { if constexpr (sizeof(wchar_t) == 2) { std::u16string buf(sw, sw + l); return utf16::decode(buf.data(), l); } else if constexpr (sizeof(wchar_t) == 4) { return std::u32string(sw, sw + l); } } } // namespace detail inline std::wstring to_wstring(const char *s8, size_t l) { return detail::to_wstring_core(s8, l); } inline std::wstring to_wstring(std::string_view s8) { return to_wstring(s8.data(), s8.length()); } inline std::wstring to_wstring(const char16_t *s16, size_t l) { return detail::to_wstring_core(s16, l); } inline std::wstring to_wstring(std::u16string_view s16) { return to_wstring(s16.data(), s16.length()); } inline std::wstring to_wstring(const char32_t *s32, size_t l) { return detail::to_wstring_core(s32, l); } inline std::wstring to_wstring(std::u32string_view s32) { return to_wstring(s32.data(), s32.length()); } inline std::string to_utf8(const wchar_t *sw, size_t l) { return detail::to_utf8_core(sw, l); } inline std::string to_utf8(std::wstring_view sw) { return to_utf8(sw.data(), sw.length()); } inline std::u16string to_utf16(const wchar_t *sw, size_t l) { return detail::to_utf16_core(sw, l); } inline std::u16string to_utf16(std::wstring_view sw) { return to_utf16(sw.data(), sw.length()); } inline std::u32string to_utf32(const wchar_t *sw, size_t l) { return detail::to_utf32_core(sw, l); } inline std::u32string to_utf32(std::wstring_view sw) { return to_utf32(sw.data(), sw.length()); } } // namespace unicode // vim: et ts=2 sw=2 cin cino=\:0 ff=unix
yhirose/cpp-unicodelib
122
A C++17 header-only Unicode library. (Unicode 17.0.0)
C++
yhirose
example/example.cpp
C++
#include <filesystem> #include <iostream> #include "zipper.h" namespace fs = std::filesystem; int main() { { zipper::Zip zip("test_copy.zip"); zipper::enumerate("test.zip", [&zip](auto &unzip) { if (unzip.is_dir()) { zip.add_dir(unzip.file_path()); } else { std::string buf; if (unzip.read(buf)) { zip.add_file(unzip.file_path(), buf); } } }); } { zipper::UnZip zip0("test.zip"); zipper::UnZip zip1("test_copy.zip"); do { assert(zip0.is_dir() == zip1.is_dir()); assert(zip0.is_file() == zip1.is_file()); assert(zip0.file_path() == zip1.file_path()); assert(zip0.file_size() == zip1.file_size()); if (zip0.is_file()) { std::string buf0, buf1; assert(zip0.read(buf0) == zip1.read(buf1)); assert(buf0 == buf1); } } while (zip0.next() && zip1.next()); } return 0; }
yhirose/cpp-zipper
29
A single file C++ header-only minizip wrapper library
C++
yhirose
zipper.h
C/C++ Header
// // zipper.h // // This code is based on 'Making MiniZip Easier to Use' by John Schember. // https://nachtimwald.com/2019/09/08/making-minizip-easier-to-use/ // // Copyright (c) 2021 Yuji Hirose. All rights reserved. // MIT License // #pragma once #include <minizip/unzip.h> #include <minizip/zip.h> #include <cassert> #include <fstream> #include <functional> #include <string> #include <vector> #define ZIPPER_BUF_SIZE 8192 #define ZIPPER_MAX_NAMELEN 256 namespace zipper { using read_cb_t = std::function<void(const char *data, size_t len)>; class Zip { public: Zip() = default; Zip(const std::string &zipname) { open(zipname); } ~Zip() { close(); } bool open(const std::string &zipname) { zfile_ = zipOpen64(zipname.data(), 0); return is_open(); } bool is_open() const { return zfile_ != nullptr; } void close() { if (zfile_ != nullptr) { zipClose(zfile_, nullptr); zfile_ = nullptr; } } bool add_dir(std::string dirname) { assert(zfile_ && !dirname.empty()); if (dirname.back() != '/') { dirname += '/'; } auto ret = zipOpenNewFileInZip64(zfile_, dirname.data(), nullptr, nullptr, 0, nullptr, 0, nullptr, 0, 0, 0); if (ret != ZIP_OK) { return false; } zipCloseFileInZip(zfile_); return ret == ZIP_OK ? true : false; } bool add_file(const std::string &path, const char *data, size_t len) { assert(zfile_ && data && len > 0); auto ret = zipOpenNewFileInZip64( zfile_, path.data(), nullptr, nullptr, 0, nullptr, 0, nullptr, Z_DEFLATED, Z_DEFAULT_COMPRESSION, (len > 0xffffffff) ? 1 : 0); if (ret != ZIP_OK) { return false; } ret = zipWriteInFileInZip(zfile_, data, static_cast<unsigned int>(len)); zipCloseFileInZip(zfile_); return ret == ZIP_OK ? true : false; } bool add_file(const std::string &path, const std::string &data) { return add_file(path, data.data(), data.size()); } operator zipFile() { return zfile_; } private: zipFile zfile_ = nullptr; }; class UnZip { public: UnZip() = default; UnZip(const std::string &zipname) { open(zipname); } ~UnZip() { close(); } bool open(const std::string &zipname) { uzfile_ = unzOpen64(zipname.data()); return is_open(); } bool is_open() const { return uzfile_ != nullptr; } void close() { if (uzfile_ != nullptr) { unzClose(uzfile_); uzfile_ = nullptr; } } bool read(read_cb_t cb) const { assert(uzfile_); auto ret = unzOpenCurrentFile(uzfile_); if (ret != UNZ_OK) { return false; } char buf[ZIPPER_BUF_SIZE]; int red; while ((red = unzReadCurrentFile(uzfile_, buf, sizeof(buf))) > 0) { cb(buf, red); } unzCloseCurrentFile(uzfile_); return red >= 0; } bool read(std::string &buf) const { return read([&](const char *data, size_t len) { buf.append(data, len); }); } std::string file_path() const { assert(uzfile_); char name[ZIPPER_MAX_NAMELEN]; unz_file_info64 finfo; auto ret = unzGetCurrentFileInfo64(uzfile_, &finfo, name, sizeof(name), nullptr, 0, nullptr, 0); if (ret != UNZ_OK) { return std::string(); } return name; } bool is_dir() const { assert(uzfile_); char name[ZIPPER_MAX_NAMELEN]; unz_file_info64 finfo; auto ret = unzGetCurrentFileInfo64(uzfile_, &finfo, name, sizeof(name), nullptr, 0, nullptr, 0); if (ret != UNZ_OK) { return false; } auto len = strlen(name); return finfo.uncompressed_size == 0 && len > 0 && name[len - 1] == '/'; } bool is_file() const { return !is_dir(); } bool next() const { assert(uzfile_); return unzGoToNextFile(uzfile_) == UNZ_OK; } uint64_t file_size() const { assert(uzfile_); unz_file_info64 finfo; auto ret = unzGetCurrentFileInfo64(uzfile_, &finfo, nullptr, 0, nullptr, 0, nullptr, 0); if (ret != UNZ_OK) { return 0; } return finfo.uncompressed_size; } template <typename T> void enumerate(T callback) { if (!file_path().empty()) { do { callback(*this); } while (next()); } } operator unzFile() { return uzfile_; } private: unzFile uzfile_ = nullptr; }; template <typename T> inline bool enumerate(const std::string &zipname, T callback) { UnZip unzip; if (unzip.open(zipname)) { unzip.enumerate(callback); return true; } return false; } }; // namespace zipper
yhirose/cpp-zipper
29
A single file C++ header-only minizip wrapper library
C++
yhirose
fzbz.cc
C++
// // FizzBuzzLang // A Programming Language just for writing Fizz Buzz program. :) // // Copyright (c) 2021 Yuji Hirose. All rights reserved. // MIT License // #include <fstream> #include <variant> #include "peglib.h" using namespace std; using namespace peg; using namespace peg::udl; //----------------------------------------------------------------------------- // Parser //----------------------------------------------------------------------------- shared_ptr<Ast> parse(const string& source, ostream& out) { parser parser(R"( # Syntax Rules EXPRESSION ← TERNARY TERNARY ← CONDITION ('?' EXPRESSION ':' EXPRESSION)? CONDITION ← MULTIPLICATIVE (ConditionOperator MULTIPLICATIVE)? MULTIPLICATIVE ← CALL (MultiplicativeOperator CALL)* CALL ← PRIMARY (EXPRESSION)? PRIMARY ← FOR / Identifier / '(' EXPRESSION ')' / String / Number FOR ← 'for' Identifier 'from' Number 'to' Number EXPRESSION # Token Rules ConditionOperator ← '==' MultiplicativeOperator ← '%' Identifier ← !Keyword < [a-zA-Z][a-zA-Z0-9_]* > String ← "'" < ([^'] .)* > "'" Number ← < [0-9]+ > Keyword ← ('for' / 'from' / 'to') ![a-zA-Z] %whitespace ← [ \t\r\n]* )"); parser.enable_ast(); parser.set_logger([&](size_t ln, size_t col, const auto& msg) { out << ln << ":" << col << ": " << msg << endl; }); shared_ptr<Ast> ast; if (parser.parse_n(source.data(), source.size(), ast)) { return parser.optimize_ast(ast); } return nullptr; } //----------------------------------------------------------------------------- // Value //----------------------------------------------------------------------------- struct Value; using Function = function<Value(const Value&)>; struct Value { variant<nullptr_t, bool, long, string_view, Function> v; Value() : v(nullptr) {} explicit Value(bool b) : v(b) {} explicit Value(long l) : v(l) {} explicit Value(string_view s) : v(s) {} explicit Value(Function f) : v(move(f)) {} template <typename T> T get() const { try { return std::get<T>(v); } catch (bad_variant_access&) { throw runtime_error("type error."); } } bool operator==(const Value& rhs) const { switch (v.index()) { case 0: return get<nullptr_t>() == rhs.get<nullptr_t>(); case 1: return get<bool>() == rhs.get<bool>(); case 2: return get<long>() == rhs.get<long>(); case 3: return get<string_view>() == rhs.get<string_view>(); } } string str() const { switch (v.index()) { case 0: return "nil"; case 1: return get<bool>() ? "true" : "false"; case 2: return to_string(get<long>()); case 3: return string(get<string_view>()); } } }; //----------------------------------------------------------------------------- // Environment //----------------------------------------------------------------------------- struct Environment { shared_ptr<Environment> outer; map<string_view, Value> values; Environment(shared_ptr<Environment> outer = nullptr) : outer(outer) {} const Value& get_value(string_view s) const { if (auto it = values.find(s); it != values.end()) { return it->second; } else if (outer) { return outer->get_value(s); } throw runtime_error("undefined variable '" + string(s) + "'..."); } void set_value(string_view s, const Value& val) { values[s] = val; } }; //----------------------------------------------------------------------------- // Interpreter //----------------------------------------------------------------------------- Value eval(const Ast& ast, shared_ptr<Environment> env); Value eval_ternary(const Ast& ast, shared_ptr<Environment> env) { auto cond = eval(*ast.nodes[0], env).get<bool>(); auto val1 = eval(*ast.nodes[1], env); auto val2 = eval(*ast.nodes[2], env); return cond ? val1 : val2; } Value eval_condition(const Ast& ast, shared_ptr<Environment> env) { auto lhs = eval(*ast.nodes[0], env); auto rhs = eval(*ast.nodes[2], env); return Value(lhs == rhs); } Value eval_multiplicative(const Ast& ast, shared_ptr<Environment> env) { auto l = eval(*ast.nodes[0], env).get<long>(); for (size_t i = 1; i < ast.nodes.size(); i += 2) { auto r = eval(*ast.nodes[i + 1], env).get<long>(); l = l % r; } return Value(l); } Value eval_call(const Ast& ast, shared_ptr<Environment> env) { auto fn = env->get_value(ast.nodes[0]->token).get<Function>(); auto val = eval(*ast.nodes[1], env); return fn(val); } Value eval_for(const Ast& ast, shared_ptr<Environment> env) { auto ident = ast.nodes[0]->token; auto from = eval(*ast.nodes[1], env).get<long>(); auto to = eval(*ast.nodes[2], env).get<long>(); auto& expr = *ast.nodes[3]; for (auto i = from; i <= to; i++) { auto call_env = make_shared<Environment>(env); call_env->set_value(ident, Value(i)); eval(expr, call_env); } return Value(); } Value eval(const Ast& ast, shared_ptr<Environment> env) { switch (ast.tag) { case "TERNARY"_: return eval_ternary(ast, env); case "CONDITION"_: return eval_condition(ast, env); case "MULTIPLICATIVE"_: return eval_multiplicative(ast, env); case "CALL"_: return eval_call(ast, env); case "FOR"_: return eval_for(ast, env); case "Identifier"_: return Value(env->get_value(ast.token)); case "String"_: return Value(ast.token); case "Number"_: return Value(ast.token_to_number<long>()); default: return Value(); } } Value interpret(const Ast& ast) { auto env = make_shared<Environment>(); env->set_value("puts", Value(Function([](auto& val) { cout << val.str() << endl; return Value(); }))); return eval(ast, env); } //----------------------------------------------------------------------------- // main //----------------------------------------------------------------------------- int main(int argc, const char** argv) { if (argc < 2) { cerr << "usage: fzbz [source file path]" << endl; return 1; } ifstream file{argv[1]}; if (!file) { cerr << "can't open the source file." << endl; return 2; } auto source = string(istreambuf_iterator<char>(file), istreambuf_iterator<char>()); auto ast = parse(source, cerr); if (!ast) { return 3; } try { interpret(*ast); } catch (const exception& e) { cerr << e.what() << endl; return 4; } return 0; }
yhirose/fizzbuzzlang
6
A Programming Language just for writing Fizz Buzz program. :)
C++
yhirose
include/array.h
C/C++ Header
#pragma once #include <metal.h> #include <concepts> #include <iostream> #include <iterator> #include <limits> #include <ranges> namespace mtl { using shape_type = std::vector<size_t>; using strides_type = shape_type; //------------------------------------------------------------------------------ template <value_type T> class array { public: array() = default; array(array &&rhs) = default; array(const array &rhs) = default; array &operator=(const array &rhs) = default; array(const shape_type &shape, T val); array(const shape_type &shape, std::input_iterator auto it); array(const shape_type &shape, std::ranges::input_range auto &&r); array(std::ranges::input_range auto &&r); array(T val); array(nested_initializer_list<T, 1> l); array(nested_initializer_list<T, 2> l); array(nested_initializer_list<T, 3> l); array(nested_initializer_list<T, 4> l); //---------------------------------------------------------------------------- template <value_type U = T> array<U> clone() const; //---------------------------------------------------------------------------- array<bool> operator==(const array &rhs) const; array<bool> operator!=(const array &rhs) const; array<bool> operator>(const array &rhs) const; array<bool> operator<(const array &rhs) const; array<bool> operator>=(const array &rhs) const; array<bool> operator<=(const array &rhs) const; //---------------------------------------------------------------------------- size_t buffer_element_count() const; size_t buffer_bytes() const; T *buffer_data(); const T *buffer_data() const; //---------------------------------------------------------------------------- size_t element_count() const; size_t length() const; size_t dimension() const; const shape_type &shape() const; const strides_type &strides() const; void reshape(const shape_type &shape); // TODO: can return a reference for performance? const auto broadcast(const shape_type &target_shape) const; array transpose() const; //---------------------------------------------------------------------------- T at() const; T &at(); T at(size_t i) const; T &at(size_t i); T at(size_t x, size_t y) const; T &at(size_t x, size_t y); T at(size_t x, size_t y, size_t z) const; T &at(size_t x, size_t y, size_t z); T at(const std::vector<size_t> &position) const; T &at(const std::vector<size_t> &position); template <size_t I> auto take() const; //---------------------------------------------------------------------------- array operator[](size_t row) const; //---------------------------------------------------------------------------- auto element_begin(); auto element_end(); auto element_cbegin() const; auto element_cend() const; auto elements(); auto elements() const; //---------------------------------------------------------------------------- auto begin(); auto end(); auto begin() const; auto end() const; auto cbegin() const; auto cend() const; template <size_t N = 0> auto rows(); template <size_t N = 0> auto rows() const; //---------------------------------------------------------------------------- void set(std::input_iterator auto it); void set(std::initializer_list<T> l); //---------------------------------------------------------------------------- void constants(T val); void zeros(); void ones(); void random(); //---------------------------------------------------------------------------- array operator+(const array &rhs) const; array operator-(const array &rhs) const; array operator*(const array &rhs) const; array operator/(const array &rhs) const; array pow(const array &rhs) const; void operator+=(const array &rhs); void operator-=(const array &rhs); void operator*=(const array &rhs); void operator/=(const array &rhs); //---------------------------------------------------------------------------- array dot(const array &rhs) const; array linear(const array& W, const array& b) const; //---------------------------------------------------------------------------- array<float> sigmoid() const; //---------------------------------------------------------------------------- T sum() const; array sum(size_t axis) const; float mean() const; array<float> mean(size_t axis) const; T min() const; T max() const; size_t count() const; bool all(arithmetic auto val) const; template <typename U> bool all(U fn) const; array<float> softmax() const; auto argmax() const; float mean_square_error(const array &rhs) const; //---------------------------------------------------------------------------- std::string print_shape_type(const shape_type &shape) const; std::string print_shape() const; std::string print_strides() const; std::string print_data_type() const; std::string print_info() const; std::string print_array() const; private: shape_type shape_; strides_type strides_; metal::storage storage_; //---------------------------------------------------------------------------- void allocate_buffer_(); //---------------------------------------------------------------------------- void copy_initializer_list_(const auto &l); //---------------------------------------------------------------------------- void bounds_check_(size_t i) const; void bounds_check_(size_t x, size_t y) const; void bounds_check_(size_t x, size_t y, size_t z) const; //---------------------------------------------------------------------------- template <typename U> void enumerate_position_(size_t shape_index, std::vector<size_t> &position, U fn) const; template <typename U> void enumerate_position_(U fn) const; //---------------------------------------------------------------------------- static auto broadcast_(const array &lhs, const array &rhs, auto cb); template <value_type U = T> array<U> apply_binary_operation_(const array &rhs, auto ope) const; //---------------------------------------------------------------------------- enum class ArithmeticOperation { Add = 0, Sub, Mul, Div, Pow, }; static auto gpu_arithmetic_operation_(const array &lhs, const array &rhs, ArithmeticOperation ope); static auto cpu_arithmetic_operation_(const array &lhs, const array &rhs, ArithmeticOperation ope); static auto arithmetic_operation_(const array &lhs, const array &rhs, ArithmeticOperation ope); //---------------------------------------------------------------------------- static array cpu_dot_operation_(const array &lhs, const array &rhs); static array gpu_dot_operation_(const array &lhs, const array &rhs); template <typename U> array dot_operation_(const array &rhs, U fn) const; }; //---------------------------------------------------------------------------- template <value_type T> std::ostream &operator<<(std::ostream &os, const array<T> &arr); //---------------------------------------------------------------------------- template <value_type T> array<T> operator+(auto lhs, const array<T> &rhs); template <value_type T> array<T> operator-(auto lhs, const array<T> &rhs); template <value_type T> array<T> operator*(auto lhs, const array<T> &rhs); template <value_type T> array<T> operator/(auto lhs, const array<T> &rhs); //---------------------------------------------------------------------------- template <value_type T, value_type U> array<T> where(const array<U> &cond, T x, T y); //---------------------------------------------------------------------------- template <value_type T> bool array_equal(const array<T> &a, const array<T> &b); template <std::floating_point T, std::floating_point U> bool is_close(T a, U b, float tolerance = 1e-3); template <std::integral T, std::integral U> bool is_close(T a, U b); template <value_type T> bool allclose(const array<T> &a, const array<T> &b, float tolerance = 1e-3); //---------------------------------------------------------------------------- template <value_type T> auto empty(const shape_type &shape); template <value_type T> auto zeros(const shape_type &shape); template <value_type T> auto ones(const shape_type &shape); auto random(const shape_type &shape); //----------------------------------------------------------------------------- // Implementation //----------------------------------------------------------------------------- template <value_type T> inline array<T>::array(const shape_type &shape, T val) { reshape(shape); allocate_buffer_(); constants(val); } template <value_type T> inline array<T>::array(const shape_type &shape, std::input_iterator auto it) { reshape(shape); allocate_buffer_(); set(it); } template <value_type T> inline array<T>::array(const shape_type &shape, std::ranges::input_range auto &&r) { reshape(shape); allocate_buffer_(); set(r.begin()); } template <value_type T> inline array<T>::array(std::ranges::input_range auto &&r) { size_t element_count = std::ranges::distance(r); reshape({element_count}); allocate_buffer_(); set(r.begin()); } template <value_type T> inline array<T>::array(T val) : array(shape_type({}), T{}) { *buffer_data() = val; } template <typename T> struct depth_ { static constexpr size_t value = 0; }; template <typename T> struct depth_<std::initializer_list<T>> { static constexpr size_t value = 1 + depth_<T>::value; }; template <size_t I> struct shape_value_ { template <typename T> static constexpr size_t value(T l) { return l.size() == 0 ? 0 : shape_value_<I - 1>::value(*l.begin()); } }; template <> struct shape_value_<0> { template <typename T> static constexpr size_t value(T l) { return l.size(); } }; template <typename T, size_t... I> constexpr shape_type shape_(T l, std::index_sequence<I...>) { return {shape_type::value_type(shape_value_<I>::value(l))...}; } template <typename T> constexpr size_t nested_initializer_list_dimension_() { return depth_<T>::value; }; template <typename T> constexpr shape_type nested_initializer_list_shape_(T l) { return shape_<T>( l, std::make_index_sequence<nested_initializer_list_dimension_<T>()>()); } template <value_type T> inline array<T>::array(nested_initializer_list<T, 1> l) : array(nested_initializer_list_shape_(l), T{}) { copy_initializer_list_(l); } template <value_type T> inline array<T>::array(nested_initializer_list<T, 2> l) : array(nested_initializer_list_shape_(l), T{}) { copy_initializer_list_(l); } template <value_type T> inline array<T>::array(nested_initializer_list<T, 3> l) : array(nested_initializer_list_shape_(l), T{}) { copy_initializer_list_(l); } template <value_type T> inline array<T>::array(nested_initializer_list<T, 4> l) : array(nested_initializer_list_shape_(l), T{}) { copy_initializer_list_(l); } //---------------------------------------------------------------------------- template <value_type T> template <value_type U> inline array<U> array<T>::clone() const { auto tmp = array<U>(shape_, U{}); for (size_t i = 0; i < element_count(); i++) { tmp.at(i) = static_cast<U>(at(i)); } return tmp; } //---------------------------------------------------------------------------- template <value_type T> inline array<bool> array<T>::operator==(const array &rhs) const { return apply_binary_operation_<bool>( rhs, [](auto lhs, auto rhs) { return lhs == rhs; }); } template <value_type T> inline array<bool> array<T>::operator!=(const array &rhs) const { return apply_binary_operation_<bool>( rhs, [](auto lhs, auto rhs) { return lhs != rhs; }); } template <value_type T> inline array<bool> array<T>::operator>(const array &rhs) const { return apply_binary_operation_<bool>( rhs, [](auto lhs, auto rhs) { return lhs > rhs; }); } template <value_type T> inline array<bool> array<T>::operator>=(const array &rhs) const { return apply_binary_operation_<bool>( rhs, [](auto lhs, auto rhs) { return lhs >= rhs; }); } template <value_type T> inline array<bool> array<T>::operator<(const array &rhs) const { return apply_binary_operation_<bool>( rhs, [](auto lhs, auto rhs) { return lhs < rhs; }); } template <value_type T> inline array<bool> array<T>::operator<=(const array &rhs) const { return apply_binary_operation_<bool>( rhs, [](auto lhs, auto rhs) { return lhs <= rhs; }); } //---------------------------------------------------------------------------- template <value_type T> inline size_t array<T>::buffer_element_count() const { return storage_.len; } template <value_type T> inline size_t array<T>::buffer_bytes() const { return storage_.len * sizeof(T); } template <value_type T> inline T *array<T>::buffer_data() { return static_cast<T *>(storage_.buf->contents()) + storage_.off; } template <value_type T> inline const T *array<T>::buffer_data() const { return static_cast<const T *>(storage_.buf->contents()) + storage_.off; } //---------------------------------------------------------------------------- template <value_type T> inline size_t array<T>::element_count() const { // TODO: cache size_t count = 1; for (auto n : shape_) { count *= n; } return count; } template <value_type T> inline size_t array<T>::length() const { if (shape_.empty()) { throw std::runtime_error("array: cannot call with a scalar value."); } return shape_[0]; } template <value_type T> inline size_t array<T>::dimension() const { return shape_.size(); } template <value_type T> inline const shape_type &array<T>::shape() const { return shape_; } template <value_type T> inline const strides_type &array<T>::strides() const { return strides_; } template <value_type T> inline void array<T>::reshape(const shape_type &shape) { // TODO: check the shape shape_ = shape; // strides strides_.clear(); strides_.push_back(1); if (!strides_.empty()) { for (int i = shape.size() - 1; i > 0; i--) { auto n = strides_.front() * shape[i]; strides_.insert(strides_.begin(), n); } } } template <value_type T> inline const auto array<T>::broadcast(const shape_type &target_shape) const { if (target_shape.size() < dimension()) { throw std::runtime_error("array: invalid shape for broadcast."); } else if (target_shape.size() == dimension()) { return *this; } auto diff = target_shape.size() - dimension(); for (size_t i = 0; i < dimension(); i++) { if (shape_[i] != target_shape[i + diff]) { throw std::runtime_error("array: invalid shape for broadcast."); } } array tmp = *this; tmp.shape_ = target_shape; // strides tmp.strides_.clear(); tmp.strides_.push_back(1); if (!strides_.empty()) { for (int i = target_shape.size() - 1; i > 0; i--) { auto n = i <= diff ? 0 : tmp.strides_.front() * target_shape[i]; tmp.strides_.insert(tmp.strides_.begin(), n); } } return tmp; } template <value_type T> inline array<T> array<T>::transpose() const { if (dimension() == 1) { auto tmp = clone(); tmp.reshape({1, element_count()}); auto it = element_cbegin(); for (size_t col = 0; col < element_count(); col++) { tmp.at(0, col) = *it; ++it; } return tmp; } if (dimension() == 2) { if (shape_[0] == 1) { auto tmp = clone(); tmp.reshape({element_count()}); auto it = element_cbegin(); for (size_t row = 0; row < element_count(); row++) { tmp.at(row) = *it; ++it; } return tmp; } else { auto shape = shape_; std::ranges::reverse(shape); auto tmp = clone(); tmp.reshape(shape); auto it = element_cbegin(); for (size_t col = 0; col < shape[1]; col++) { for (size_t row = 0; row < shape[0]; row++) { tmp.at(row, col) = *it; ++it; } } return tmp; } } if (dimension() == 3) { auto shape = shape_; std::ranges::reverse(shape); auto tmp = clone(); tmp.reshape(shape); auto it = element_cbegin(); for (size_t z = 0; z < shape[2]; z++) { for (size_t y = 0; y < shape[1]; y++) { for (size_t x = 0; x < shape[0]; x++) { tmp.at(x, y, z) = *it; ++it; } } } return tmp; } throw std::runtime_error("array: can't do `transpose` operation."); } //---------------------------------------------------------------------------- template <value_type T> inline T array<T>::at() const { return *buffer_data(); } template <value_type T> inline T &array<T>::at() { return *buffer_data(); } template <value_type T> inline T array<T>::at(size_t i) const { bounds_check_(i); return buffer_data()[i % buffer_element_count()]; } template <value_type T> inline T &array<T>::at(size_t i) { bounds_check_(i); return buffer_data()[i % buffer_element_count()]; } template <value_type T> inline T array<T>::at(size_t x, size_t y) const { bounds_check_(x, y); return buffer_data()[strides_[0] * x + y]; } template <value_type T> inline T &array<T>::at(size_t x, size_t y) { bounds_check_(x, y); return buffer_data()[strides_[0] * x + y]; } template <value_type T> inline T array<T>::at(size_t x, size_t y, size_t z) const { bounds_check_(x, y, z); return buffer_data()[(strides_[0] * x) + (strides_[1] * y) + z]; } template <value_type T> inline T &array<T>::at(size_t x, size_t y, size_t z) { bounds_check_(x, y, z); return buffer_data()[(strides_[0] * x) + (strides_[1] * y) + z]; } template <value_type T> inline T array<T>::at(const std::vector<size_t> &position) const { // TODO: bounds_check_(position); size_t buffer_index = 0; for (size_t i = 0; i < position.size(); i++) { buffer_index += strides_[i] * position[i]; } return buffer_data()[buffer_index]; } template <value_type T> inline T &array<T>::at(const std::vector<size_t> &position) { // TODO: bounds_check_(position); size_t buffer_index = 0; for (size_t i = 0; i < position.size(); i++) { buffer_index += strides_[i] * position[i]; } return buffer_data()[buffer_index]; } template <value_type T> template <size_t I> inline auto array<T>::take() const { if constexpr (I == 0) { return std::tuple<>(); } else { auto t = take<I - 1>(); return std::tuple_cat(t, std::tuple<T>(at(I - 1))); } } //---------------------------------------------------------------------------- template <value_type T> inline array<T> array<T>::operator[](size_t row) const { if (dimension() == 0 || row >= shape_[0]) { throw std::runtime_error("array: row is out of bounds."); } array tmp(*this); auto s = shape(); s.erase(s.begin()); tmp.reshape(s); auto stride = strides_[0]; tmp.storage_.off = storage_.off + stride * row; tmp.storage_.len = stride; return tmp; } //---------------------------------------------------------------------------- template <value_type T> class element_iterator { public: using difference_type = std::ptrdiff_t; using reference = T &; using iterator_concept = std::forward_iterator_tag; element_iterator(array<T> *arr, size_t i) : arr_(arr), i_(i) {} element_iterator &operator++() { ++i_; return *this; } element_iterator operator++(int) { auto tmp = *this; ++(*this); return tmp; } reference &operator*() { return arr_->at(i_); } friend bool operator==(const element_iterator &a, const element_iterator &b) { return a.i_ == b.i_; }; private: array<T> *arr_ = nullptr; size_t i_ = 0; }; template <value_type T> class const_element_iterator { public: using difference_type = std::ptrdiff_t; using value_type = T; using iterator_concept = std::forward_iterator_tag; const_element_iterator(const array<T> *arr, size_t i) : arr_(arr), i_(i) {} const_element_iterator &operator++() { ++i_; return *this; } const_element_iterator operator++(int) { auto tmp = *this; ++(*this); return tmp; } value_type operator*() const { return arr_->at(i_); } friend bool operator==(const const_element_iterator &a, const const_element_iterator &b) { return a.i_ == b.i_; }; private: const array<T> *arr_ = nullptr; size_t i_ = 0; }; template <value_type T> struct element_range { element_range(array<T> *arr) : arr_(arr) {} auto begin() { return element_iterator(arr_, 0); } auto end() { return element_iterator(arr_, arr_->element_count()); } array<T> *arr_ = nullptr; }; template <value_type T> struct const_element_range { const_element_range(const array<T> *arr) : arr_(arr) {} auto begin() { return const_element_iterator(arr_, 0); } auto end() { return const_element_iterator(arr_, arr_->element_count()); } auto cbegin() const { return const_element_iterator(arr_, 0); } auto cend() const { return const_element_iterator(arr_, arr_->element_count()); } const array<T> *arr_ = nullptr; }; template <value_type T> inline auto array<T>::element_begin() { return element_iterator(this, 0); } template <value_type T> inline auto array<T>::element_end() { return element_iterator(this, element_count()); } template <value_type T> inline auto array<T>::element_cbegin() const { return const_element_iterator(this, 0); } template <value_type T> inline auto array<T>::element_cend() const { return const_element_iterator(this, element_count()); } template <value_type T> inline auto array<T>::elements() { return element_range(this); } template <value_type T> inline auto array<T>::elements() const { return const_element_range(this); } //---------------------------------------------------------------------------- template <value_type T> class row_iterator { public: using difference_type = std::ptrdiff_t; using value_type = array<T>; using iterator_concept = std::forward_iterator_tag; row_iterator(array<T> *arr, size_t i) : arr_(arr), i_(i) {} row_iterator &operator++() { ++i_; return *this; } row_iterator operator++(int) { auto tmp = *this; ++(*this); return tmp; } value_type operator*() { return (*arr_)[i_]; } friend bool operator==(const row_iterator &a, const row_iterator &b) { return a.i_ == b.i_; }; private: array<T> *arr_ = nullptr; size_t i_ = 0; }; template <value_type T> class const_row_iterator { public: using difference_type = std::ptrdiff_t; using value_type = array<T>; using iterator_concept = std::forward_iterator_tag; const_row_iterator(const array<T> *arr, size_t i) : arr_(arr), i_(i) {} const_row_iterator &operator++() { ++i_; return *this; } const_row_iterator operator++(int) { auto tmp = *this; ++(*this); return tmp; } value_type operator*() const { return (*arr_)[i_]; } friend bool operator==(const const_row_iterator &a, const const_row_iterator &b) { return a.i_ == b.i_; }; private: const array<T> *arr_ = nullptr; size_t i_ = 0; }; template <value_type T, size_t N> class row_tuple_iterator { public: using difference_type = std::ptrdiff_t; using reference = array<T> &; using iterator_concept = std::forward_iterator_tag; row_tuple_iterator(array<T> *arr, size_t i) : arr_(arr), i_(i) {} row_tuple_iterator &operator++() { ++i_; return *this; } row_tuple_iterator operator++(int) { auto tmp = *this; ++(*this); return tmp; } auto operator*() const { return (*arr_)[i_].template take<N>(); } friend bool operator==(const row_tuple_iterator &a, const row_tuple_iterator &b) { return a.i_ == b.i_; }; private: array<T> *arr_ = nullptr; size_t i_ = 0; }; template <value_type T, size_t N> class const_row_tuple_iterator { public: using difference_type = std::ptrdiff_t; using iterator_concept = std::forward_iterator_tag; const_row_tuple_iterator(const array<T> *arr, size_t i) : arr_(arr), i_(i) {} const_row_tuple_iterator &operator++() { ++i_; return *this; } const_row_tuple_iterator operator++(int) { auto tmp = *this; ++(*this); return tmp; } auto operator*() const { return (*arr_)(i_).template take<N>(); } friend bool operator==(const const_row_tuple_iterator &a, const const_row_tuple_iterator &b) { return a.i_ == b.i_; }; private: const array<T> *arr_ = nullptr; size_t i_ = 0; }; template <value_type T> struct row_range { row_range(array<T> *arr) : arr_(arr) {} auto begin() { return row_iterator(arr_, 0); } auto end() { return row_iterator(arr_, arr_->shape()[0]); } array<T> *arr_ = nullptr; }; template <value_type T> struct const_row_range { const_row_range(const array<T> *arr) : arr_(arr) {} auto begin() const { return const_row_iterator(arr_, 0); } auto end() const { return const_row_iterator(arr_, arr_->shape()[0]); } auto cbegin() const { return const_row_iterator(arr_, 0); } auto cend() const { return const_row_iterator(arr_, arr_->shape()[0]); } const array<T> *arr_ = nullptr; }; template <value_type T, size_t N> struct row_tuple_range { row_tuple_range(array<T> *arr) : arr_(arr) {} auto begin() { return row_tuple_iterator<T, N>(arr_, 0); } auto end() { return row_tuple_iterator<T, N>(arr_, arr_->shape()[0]); } array<T> *arr_ = nullptr; }; template <value_type T, size_t N> struct const_row_tuple_range { const_row_tuple_range(array<T> *arr) : arr_(arr) {} auto cbegin() const { return const_row_tuple_iterator<T, N>(arr_, 0); } auto cend() const { return const_row_tuple_iterator<T, N>(arr_, arr_->shape()[0]); } const array<T> *arr_ = nullptr; }; template <value_type T> inline auto array<T>::begin() { return row_iterator(this, 0); } template <value_type T> inline auto array<T>::end() { return row_iterator(this, shape_[0]); } template <value_type T> inline auto array<T>::begin() const { return const_row_iterator(this, 0); } template <value_type T> inline auto array<T>::end() const { return const_row_iterator(this, shape_[0]); } template <value_type T> inline auto array<T>::cbegin() const { return const_row_iterator(this, 0); } template <value_type T> inline auto array<T>::cend() const { return const_row_iterator(this, shape_[0]); } template <value_type T> template <size_t N> inline auto array<T>::rows() { if constexpr (N == 0) { return row_range(this); } else { return row_tuple_range<T, N>(this); } } template <value_type T> template <size_t N> inline auto array<T>::rows() const { if constexpr (N == 0) { return const_row_range(this); } else { return const_row_tuple_range<T, N>(this); } } //---------------------------------------------------------------------------- template <value_type T> inline void array<T>::set(std::input_iterator auto it) { // TODO: parallel operation on GPU for (size_t i = 0; i < element_count(); i++) { at(i) = *it++; } } template <value_type T> inline void array<T>::set(std::initializer_list<T> l) { std::ranges::copy(l, element_begin()); } //---------------------------------------------------------------------------- template <value_type T> inline void array<T>::constants(T val) { std::fill(buffer_data(), buffer_data() + buffer_element_count(), val); } template <value_type T> inline void array<T>::zeros() { constants(0); }; template <value_type T> inline void array<T>::ones() { constants(1); }; template <value_type T> inline void array<T>::random() { std::generate(buffer_data(), buffer_data() + buffer_element_count(), []() { return static_cast<float>(static_cast<double>(rand()) / RAND_MAX); }); } //---------------------------------------------------------------------------- template <value_type T> inline array<T> array<T>::operator+(const array &rhs) const { return arithmetic_operation_(*this, rhs, ArithmeticOperation::Add); } template <value_type T> inline array<T> array<T>::operator-(const array &rhs) const { return arithmetic_operation_(*this, rhs, ArithmeticOperation::Sub); } template <value_type T> inline array<T> array<T>::operator*(const array &rhs) const { return arithmetic_operation_(*this, rhs, ArithmeticOperation::Mul); } template <value_type T> inline array<T> array<T>::operator/(const array &rhs) const { return arithmetic_operation_(*this, rhs, ArithmeticOperation::Div); } template <value_type T> inline array<T> array<T>::pow(const array &rhs) const { return arithmetic_operation_(*this, rhs, ArithmeticOperation::Pow); } template <value_type T> inline void array<T>::operator+=(const array &rhs) { // TODO: in-place *this = arithmetic_operation_(*this, rhs, ArithmeticOperation::Add); } template <value_type T> inline void array<T>::operator-=(const array &rhs) { // TODO: in-place *this = arithmetic_operation_(*this, rhs, ArithmeticOperation::Sub); } template <value_type T> inline void array<T>::operator*=(const array &rhs) { // TODO: in-place *this = arithmetic_operation_(*this, rhs, ArithmeticOperation::Mul); } template <value_type T> inline void array<T>::operator/=(const array &rhs) { // TODO: in-place *this = arithmetic_operation_(*this, rhs, ArithmeticOperation::Div); } //---------------------------------------------------------------------------- template <value_type T> inline array<T> array<T>::dot(const array &rhs) const { switch (device_) { case Device::GPU: return dot_operation_(rhs, gpu_dot_operation_); case Device::CPU: return dot_operation_(rhs, cpu_dot_operation_); } } template <value_type T> inline array<T> array<T>::linear(const array& W, const array& b) const { return dot(W) + b; } //---------------------------------------------------------------------------- template <value_type T> inline array<float> array<T>::sigmoid() const { // TODO: parallel operation on GPU auto tmp = array<float>(shape_, 0.0); for (size_t i = 0; i < element_count(); i++) { tmp.at(i) = 1.0 / (1.0 + std::exp(-static_cast<float>(at(i)))); } return tmp; } //---------------------------------------------------------------------------- template <value_type T> inline T array<T>::sum() const { return std::accumulate(element_cbegin(), element_cend(), T{}); } template <value_type T> inline array<T> array<T>::sum(size_t axis) const { auto s = shape_; s.erase(s.begin() + axis); auto tmp = array(s, T{}); enumerate_position_([&](const auto &pos) { auto p = pos; p.erase(p.begin() + axis); tmp.at(p) += at(pos); }); return tmp; } template <value_type T> inline float array<T>::mean() const { return sum() / static_cast<float>(element_count()); } template <value_type T> inline array<float> array<T>::mean(size_t axis) const { auto t = sum(axis); if constexpr (std::is_same_v<T, float>) { return t / shape_[axis]; } else { return t.template clone<float>() / shape_[axis]; } } template <value_type T> inline T array<T>::min() const { T min_val = std::numeric_limits<T>::max(); for (size_t i = 0; i < buffer_element_count(); i++) { auto val = buffer_data()[i]; if (val < min_val) { min_val = val; } } return min_val; } template <value_type T> inline T array<T>::max() const { T max_val = std::numeric_limits<T>::min(); for (size_t i = 0; i < buffer_element_count(); i++) { auto val = buffer_data()[i]; if (val > max_val) { max_val = val; } } return max_val; } template <value_type T> inline size_t array<T>::count() const { size_t cnt = 0; for (size_t i = 0; i < element_count(); i++) { if (at(i)) { cnt++; } } return cnt; } template <value_type T> inline bool array<T>::all(arithmetic auto val) const { for (size_t i = 0; i < buffer_element_count(); i++) { if (buffer_data()[i] != val) { return false; } } return true; } template <value_type T> template <typename U> inline bool array<T>::all(U fn) const { for (size_t i = 0; i < buffer_element_count(); i++) { if (!fn(buffer_data()[i])) { return false; } } return true; } template <value_type T> inline array<float> array<T>::softmax() const { if (dimension() == 1) { auto c = min(); auto tmp = array<float>(shape_, 0.0); for (size_t i = 0; i < element_count(); i++) { tmp.at(i) = std::exp(at(i) - c); } return tmp / tmp.sum(); } else if (dimension() == 2) { auto tmp = array<float>(shape_, 0.0); for (size_t i = 0; i < shape_[0]; i++) { const auto row = (*this)[i]; auto c = row.min(); for (size_t j = 0; j < row.element_count(); j++) { tmp[i].at(j) = std::exp(row.at(j) - c); } auto smax = tmp[i] / tmp[i].sum(); for (size_t j = 0; j < row.element_count(); j++) { tmp[i].at(j) = smax.at(j); } } return tmp; } throw std::runtime_error( "array: softmax is available only for 1 or 2 dimension array."); } template <value_type T> inline auto array<T>::argmax() const { if (dimension() == 2) { auto row_count = shape_[0]; auto tmp = array<int>({row_count}, 0); for (size_t i = 0; i < row_count; i++) { const auto row = (*this)[i]; size_t max_index = 0; { T max_val = std::numeric_limits<T>::min(); for (size_t j = 0; j < row.buffer_element_count(); j++) { auto val = row.buffer_data()[j]; if (val > max_val) { max_val = val; max_index = j; } } } tmp.at(i) = max_index; } return tmp; } throw std::runtime_error("array: argmax is available for 2 dimension array."); } template <value_type T> inline float array<T>::mean_square_error(const array &rhs) const { return (*this - rhs).pow(2).mean(); } //---------------------------------------------------------------------------- template <value_type T> inline std::string array<T>::print_shape_type(const shape_type &shape) const { std::stringstream ss; ss << "{"; for (size_t i = 0; i < shape.size(); i++) { if (i != 0) { ss << ", "; } ss << shape[i]; } ss << "}"; return ss.str(); } template <value_type T> inline std::string array<T>::print_shape() const { return print_shape_type(shape_); } template <value_type T> inline std::string array<T>::print_strides() const { return print_shape_type(strides_); } template <value_type T> inline std::string array<T>::print_data_type() const { if constexpr (std::is_same_v<T, float>) { return "float"; } else { return "int"; } } template <value_type T> inline std::string array<T>::print_info() const { std::stringstream ss; ss << "dtype: " << print_data_type() << ", dim: " << dimension() << ", shape: " << print_shape() << ", strides: " << print_strides(); return ss.str(); } template <value_type T> inline std::string array<T>::print_array() const { auto loop = [&](auto self, auto &os, auto dim, auto arr_index) { auto n = shape_[dim]; if (dim + 1 == dimension()) { for (size_t i = 0; i < n; i++, arr_index++) { if (i > 0) { os << ", "; } if constexpr (std::is_same_v<T, bool>) { os << (at(arr_index) ? "true" : "false"); } else { os << at(arr_index); } } return arr_index; } for (size_t i = 0; i < n; i++) { if (dim < dimension() && i > 0) { os << ",\n"; if (dimension() >= 3 && dim == 0 && i > 0) { os << "\n"; } for (size_t j = 0; j <= dim; j++) { os << " "; } } os << '{'; arr_index = self(self, os, dim + 1, arr_index); os << '}'; } return arr_index; }; std::stringstream ss; if (dimension() == 0) { ss << at(); } else { ss << '{'; loop(loop, ss, 0, 0); ss << '}'; } return ss.str(); } //---------------------------------------------------------------------------- template <value_type T> inline void array<T>::allocate_buffer_() { storage_.off = 0; storage_.len = element_count(); storage_.buf = metal::default_device().make_buffer(storage_.len * sizeof(T)); } //---------------------------------------------------------------------------- template <typename T> constexpr size_t nested_initializer_item_count_(const T &l) { return 1; } template <typename T> constexpr size_t nested_initializer_item_count_(std::initializer_list<T> l) { size_t count = 0; for (auto it = l.begin(); it != l.end(); ++it) { count += nested_initializer_item_count_(*it); } return count; } template <typename T> constexpr void nested_initializer_copy_(T &&dst, const auto &src) { *dst++ = src; } template <typename T, typename U> constexpr void nested_initializer_copy_(T &&dst, std::initializer_list<U> src) { for (auto it = src.begin(); it != src.end(); ++it) { nested_initializer_copy_(std::forward<T>(dst), *it); } } template <value_type T> inline void array<T>::copy_initializer_list_(const auto &l) { if (nested_initializer_item_count_(l) != element_count()) { throw std::runtime_error("array: invalid initializer list."); } nested_initializer_copy_(buffer_data(), l); } //---------------------------------------------------------------------------- template <value_type T> inline void array<T>::bounds_check_(size_t i) const { if (strides_.empty() || i >= element_count()) { throw std::runtime_error("array: index is out of bounds."); } } template <value_type T> inline void array<T>::bounds_check_(size_t x, size_t y) const { if (dimension() != 2 || x >= shape_[0] || y >= shape_[1]) { throw std::runtime_error("array: (x, y) is out of bounds."); } } template <value_type T> inline void array<T>::bounds_check_(size_t x, size_t y, size_t z) const { if (dimension() != 3 || x >= shape_[0] || y >= shape_[1] || z >= shape_[2]) { throw std::runtime_error("array: (x, y, z) is out of bounds."); } } //---------------------------------------------------------------------------- template <value_type T> template <typename U> inline void array<T>::enumerate_position_(size_t shape_index, std::vector<size_t> &position, U fn) const { if (shape_index == shape_.size()) { fn(position); return; } for (size_t i = 0; i < shape_[shape_index]; i++) { position[shape_index] = i; enumerate_position_(shape_index + 1, position, fn); } } template <value_type T> template <typename U> inline void array<T>::enumerate_position_(U fn) const { std::vector<size_t> position(shape_.size()); for (size_t i = 0; i < shape_[0]; i++) { position[0] = i; enumerate_position_(1, position, fn); } } //---------------------------------------------------------------------------- template <value_type T> inline auto array<T>::broadcast_(const array &lhs, const array &rhs, auto cb) { if (lhs.shape() == rhs.shape()) { return cb(lhs, rhs); } else if (lhs.dimension() < rhs.dimension()) { return cb(lhs.broadcast(rhs.shape()), rhs); } else if (lhs.dimension() > rhs.dimension()) { return cb(lhs, rhs.broadcast(lhs.shape())); } throw std::runtime_error("array: invalid operation."); } template <value_type T> template <value_type U> inline array<U> array<T>::apply_binary_operation_(const array &rhs, auto ope) const { return broadcast_(*this, rhs, [ope](const auto &lhs, const auto &rhs) { // TODO: parallel operation on GPU auto tmp = array<U>(lhs.shape(), U{}); for (size_t i = 0; i < lhs.element_count(); i++) { tmp.at(i) = ope(lhs.at(i), rhs.at(i)); } return tmp; }); } //---------------------------------------------------------------------------- template <value_type T> inline auto array<T>::gpu_arithmetic_operation_(const array &lhs, const array &rhs, ArithmeticOperation ope) { return broadcast_(lhs, rhs, [ope](const auto &lhs, const auto &rhs) { auto tmp = array(lhs.shape(), T{}); switch (ope) { case ArithmeticOperation::Add: metal::default_device().add<T>(lhs.storage_, rhs.storage_, tmp.storage_); break; case ArithmeticOperation::Sub: metal::default_device().sub<T>(lhs.storage_, rhs.storage_, tmp.storage_); break; case ArithmeticOperation::Mul: metal::default_device().mul<T>(lhs.storage_, rhs.storage_, tmp.storage_); break; case ArithmeticOperation::Div: metal::default_device().div<T>(lhs.storage_, rhs.storage_, tmp.storage_); break; case ArithmeticOperation::Pow: metal::default_device().pow<T>(lhs.storage_, rhs.storage_, tmp.storage_); break; default: assert(false); break; } return tmp; }); } template <value_type T> inline auto array<T>::cpu_arithmetic_operation_(const array &lhs, const array &rhs, ArithmeticOperation ope) { switch (ope) { case ArithmeticOperation::Add: return lhs.apply_binary_operation_( rhs, [](auto lhs, auto rhs) { return lhs + rhs; }); break; case ArithmeticOperation::Sub: return lhs.apply_binary_operation_( rhs, [](auto lhs, auto rhs) { return lhs - rhs; }); break; case ArithmeticOperation::Mul: return lhs.apply_binary_operation_( rhs, [](auto lhs, auto rhs) { return lhs * rhs; }); break; case ArithmeticOperation::Div: return lhs.apply_binary_operation_( rhs, [](auto lhs, auto rhs) { return lhs / rhs; }); break; case ArithmeticOperation::Pow: return lhs.apply_binary_operation_( rhs, [](auto lhs, auto rhs) { return std::pow(lhs, rhs); }); break; default: assert(false); break; } } template <value_type T> inline auto array<T>::arithmetic_operation_(const array &lhs, const array &rhs, ArithmeticOperation ope) { switch (device_) { case Device::GPU: return gpu_arithmetic_operation_(lhs, rhs, ope); case Device::CPU: return cpu_arithmetic_operation_(lhs, rhs, ope); } } //---------------------------------------------------------------------------- template <value_type T> inline array<T> array<T>::cpu_dot_operation_(const array &lhs, const array &rhs) { auto rows = lhs.shape_[0]; auto cols = rhs.shape_[1]; auto m = lhs.shape_[1]; auto tmp = array({rows, cols}, T{}); for (size_t row = 0; row < rows; row++) { for (size_t col = 0; col < cols; col++) { T val{}; for (size_t i = 0; i < m; i++) { val += lhs.at(row, i) * rhs.at(i, col); } tmp.at(row, col) = val; } } return tmp; } template <value_type T> inline array<T> array<T>::gpu_dot_operation_(const array &lhs, const array &rhs) { auto tmp = array({lhs.shape_[0], rhs.shape_[1]}, T{}); metal::default_device().dot<T>(lhs.storage_, rhs.storage_, tmp.storage_, lhs.shape_[1], lhs.shape_[0], rhs.shape_[1]); return tmp; } template <value_type T> template <typename U> inline array<T> array<T>::dot_operation_(const array &rhs, U fn) const { if (dimension() == 2 && rhs.dimension() == 2 && shape_[1] == rhs.shape_[0]) { return fn(*this, rhs); } if (dimension() == 1 && rhs.dimension() == 2 && shape_[0] == rhs.shape_[0]) { auto lhs2 = *this; lhs2.reshape({1, shape_[0]}); auto tmp = fn(lhs2, rhs); tmp.reshape({rhs.shape_[1]}); return tmp; } if (dimension() == 2 && rhs.dimension() == 1 && shape_[1] == rhs.shape_[0]) { auto rhs2 = rhs; rhs2.reshape({rhs.shape_[0], 1}); auto tmp = fn(*this, rhs2); tmp.reshape({shape_[0]}); return tmp; } if (dimension() == 1 && rhs.dimension() == 1 && shape_[0] == rhs.shape_[0]) { auto lhs2 = *this; lhs2.reshape({1, shape_[0]}); auto rhs2 = rhs; rhs2.reshape({rhs.shape_[0], 1}); auto tmp = fn(lhs2, rhs2); tmp.reshape({}); return tmp; } throw std::runtime_error("array: can't do `dot` operation."); } //---------------------------------------------------------------------------- template <value_type T> inline std::ostream &operator<<(std::ostream &os, const array<T> &arr) { os << arr.print_array(); return os; } //---------------------------------------------------------------------------- template <value_type T> inline array<T> operator+(auto lhs, const array<T> &rhs) { return array<T>(static_cast<T>(lhs)) + rhs; } template <value_type T> inline array<T> operator-(auto lhs, const array<T> &rhs) { return array<T>(static_cast<T>(lhs)) - rhs; } template <value_type T> inline array<T> operator*(auto lhs, const array<T> &rhs) { return array<T>(static_cast<T>(lhs)) * rhs; } template <value_type T> inline array<T> operator/(auto lhs, const array<T> &rhs) { return array<T>(static_cast<T>(lhs)) / rhs; } //---------------------------------------------------------------------------- template <value_type T, value_type U> inline array<T> where(const array<U> &cond, T x, T y) { // TODO: parallel operation on GPU auto tmp = array<T>(cond.shape(), T{}); for (size_t i = 0; i < cond.element_count(); i++) { tmp.at(i) = cond.at(i) ? x : y; } return tmp; } //---------------------------------------------------------------------------- template <value_type T> inline bool array_equal(const array<T> &a, const array<T> &b) { if (&a != &b) { if (a.shape() != b.shape()) { return false; } for (size_t i = 0; i < a.element_count(); i++) { if (a.at(i) != b.at(i)) { return false; } } } return true; } template <std::floating_point T, std::floating_point U> inline bool is_close(T a, U b, float tolerance) { return std::abs(static_cast<float>(a) - static_cast<float>(b)) <= tolerance; } template <std::integral T, std::integral U> inline bool is_close(T a, U b) { return a == b; } template <value_type T> inline bool allclose(const array<T> &a, const array<T> &b, float tolerance) { if (&a != &b) { if (a.shape() != b.shape()) { return false; } for (size_t i = 0; i < a.element_count(); i++) { if constexpr (std::is_same_v<T, float>) { if (std::abs(a.at(i) - b.at(i)) > tolerance) { return false; } } else { if (a.at(i) != b.at(i)) { return false; } } } } return true; } //---------------------------------------------------------------------------- template <value_type T> inline auto empty(const shape_type &shape) { return array<T>(shape, T{}); } template <value_type T> inline auto zeros(const shape_type &shape) { return array<T>(shape, 0); } template <value_type T> inline auto ones(const shape_type &shape) { return array<T>(shape, 1); } inline auto random(const shape_type &shape) { auto tmp = array<float>(shape, 0.0); tmp.random(); return tmp; } }; // namespace mtl
yhirose/mtlcpp
16
Utilities for Metal-cpp
C++
yhirose
include/metal.h
C/C++ Header
#pragma once #include <Metal/Metal.hpp> #include <numeric> #include <sstream> namespace mtl { template <typename T> concept value_type = std::same_as<T, float> || std::same_as<T, int> || std::same_as<T, bool>; template <typename T> concept arithmetic = std::is_arithmetic_v<T>; //----------------------------------------------------------------------------- template <typename T> struct releaser { void operator()(T* p) { if (p != nullptr) { p->release(); } else { throw std::runtime_error( "metal: This managed resource object has already been released..."); } } }; template <typename T> inline auto managed(T* p) { return std::shared_ptr<T>(p, releaser<T>()); } template <typename T> using managed_ptr = std::shared_ptr<T>; //----------------------------------------------------------------------------- template <value_type T, size_t I> struct nested_initializer_list_ { using nested_type = nested_initializer_list_<T, I - 1>::type; using type = std::initializer_list<nested_type>; }; template <value_type T> struct nested_initializer_list_<T, 0> { using type = T; }; template <value_type T, size_t I> using nested_initializer_list = nested_initializer_list_<T, I>::type; //----------------------------------------------------------------------------- enum class Device { GPU = 0, CPU, }; static Device device_ = Device::GPU; inline void use_cpu() { device_ = Device::CPU; } inline void use_gpu() { device_ = Device::GPU; } //----------------------------------------------------------------------------- class metal { public: struct storage { managed_ptr<MTL::Buffer> buf; size_t off = 0; size_t len = 0; }; metal(managed_ptr<MTL::Device> device); managed_ptr<MTL::Buffer> make_buffer(NS::UInteger length); template <value_type T> void add(const storage& A, const storage& B, storage& OUT); template <value_type T> void sub(const storage& A, const storage& B, storage& OUT); template <value_type T> void mul(const storage& A, const storage& B, storage& OUT); template <value_type T> void div(const storage& A, const storage& B, storage& OUT); template <value_type T> void pow(const storage& A, const storage& B, storage& OUT); template <value_type T> void dot(const storage& A, const storage& B, storage& OUT, uint32_t A_cols, uint32_t OUT_rows, uint32_t OUT_cols); static metal& default_device() { static auto metal_ = metal(managed(MTL::CreateSystemDefaultDevice())); return metal_; } private: enum class DataType { Float = 0, Integer, }; managed_ptr<MTL::Device> device_; managed_ptr<MTL::ComputePipelineState> pso_add_; managed_ptr<MTL::ComputePipelineState> pso_sub_; managed_ptr<MTL::ComputePipelineState> pso_mul_; managed_ptr<MTL::ComputePipelineState> pso_div_; managed_ptr<MTL::ComputePipelineState> pso_pow_; managed_ptr<MTL::ComputePipelineState> pso_dot_; managed_ptr<MTL::CommandQueue> queue_; template <value_type T> void arithmetic_operation_(const storage& A, const storage& B, storage& OUT, managed_ptr<MTL::ComputePipelineState> pso); managed_ptr<MTL::ComputePipelineState> create_compute_pipeline_state_object_( managed_ptr<MTL::Device> device, managed_ptr<MTL::Library> library, const char* name); }; //----------------------------------------------------------------------------- // Implementation //----------------------------------------------------------------------------- static const char* msl_source_ = R"( #include <metal_stdlib> using namespace metal; template <typename Ope, typename T> void arithmetic_operation_( device const void* A, device const void* B, device void* OUT, constant uint32_t& A_length, constant uint32_t& B_length, uint gid) { auto A_arr = static_cast<device const T*>(A); auto B_arr = static_cast<device const T*>(B); auto OUT_arr = reinterpret_cast<device T*>(OUT); // broadcast offset auto A_index = gid % A_length; auto B_index = gid % B_length; OUT_arr[gid] = Ope()(A_arr[A_index], B_arr[B_index]); } template <typename T> struct add_ { T operator()(T a, T b) { return a + b; } }; template <typename T> struct sub_ { T operator()(T a, T b) { return a - b; } }; template <typename T> struct mul_ { T operator()(T a, T b) { return a * b; } }; template <typename T> struct div_ { T operator()(T a, T b) { return a / b; } }; struct powf_ { float operator()(float a, float b) { return pow(a, b); } }; struct powi_ { int operator()(int a, int b) { return round(pow(static_cast<float>(a), static_cast<float>(b))); } }; template <typename T> void dot_operatoin( device const void* A, device const void* B, device void* OUT, constant uint32_t& A_cols, constant uint32_t& OUT_raws, constant uint32_t& OUT_cols, uint2 gid) { auto A_arr = static_cast<device const T*>(A); auto B_arr = static_cast<device const T*>(B); auto OUT_arr = reinterpret_cast<device T*>(OUT); auto irow = gid.y; auto icol = gid.x; T val{}; for (uint32_t i = 0; i < A_cols; i++) { auto aval = A_arr[A_cols * irow + i]; auto bval = B_arr[OUT_cols * i + icol]; val += aval * bval; } OUT_arr[OUT_cols * irow + icol] = val; } constant uint32_t Float = 0; kernel void add( device const void* A, device const void* B, device void* OUT, constant uint32_t& A_length, constant uint32_t& B_length, constant uint32_t& dtype, uint gid [[thread_position_in_grid]]) { if (dtype == Float) { arithmetic_operation_<add_<float>, float>(A, B, OUT, A_length, B_length, gid); } else { arithmetic_operation_<add_<int>, int>(A, B, OUT, A_length, B_length, gid); } } kernel void sub( device const void* A, device const void* B, device void* OUT, constant uint32_t& A_length, constant uint32_t& B_length, constant uint32_t& dtype, uint gid [[thread_position_in_grid]]) { if (dtype == Float) { arithmetic_operation_<sub_<float>, float>(A, B, OUT, A_length, B_length, gid); } else { arithmetic_operation_<sub_<int>, int>(A, B, OUT, A_length, B_length, gid); } } kernel void mul( device const void* A, device const void* B, device void* OUT, constant uint32_t& A_length, constant uint32_t& B_length, constant uint32_t& dtype, uint gid [[thread_position_in_grid]]) { if (dtype == Float) { arithmetic_operation_<mul_<float>, float>(A, B, OUT, A_length, B_length, gid); } else { arithmetic_operation_<mul_<int>, int>(A, B, OUT, A_length, B_length, gid); } } kernel void div( device const void* A, device const void* B, device void* OUT, constant uint32_t& A_length, constant uint32_t& B_length, constant uint32_t& dtype, uint gid [[thread_position_in_grid]]) { if (dtype == Float) { arithmetic_operation_<div_<float>, float>(A, B, OUT, A_length, B_length, gid); } else { arithmetic_operation_<div_<int>, int>(A, B, OUT, A_length, B_length, gid); } } kernel void pow( device const void* A, device const void* B, device void* OUT, constant uint32_t& A_length, constant uint32_t& B_length, constant uint32_t& dtype, uint gid [[thread_position_in_grid]]) { if (dtype == Float) { arithmetic_operation_<powf_, float>(A, B, OUT, A_length, B_length, gid); } else { arithmetic_operation_<powi_, int>(A, B, OUT, A_length, B_length, gid); } } kernel void dot( device const void* A, device const void* B, device void* OUT, constant uint32_t& A_cols, constant uint32_t& OUT_raws, constant uint32_t& OUT_cols, constant uint32_t& dtype, uint2 gid [[thread_position_in_grid]]) { if (dtype == Float) { dot_operatoin<float>(A, B, OUT, A_cols, OUT_raws, OUT_cols, gid); } else { dot_operatoin<int>(A, B, OUT, A_cols, OUT_raws, OUT_cols, gid); } } )"; //----------------------------------------------------------------------------- inline metal::metal(managed_ptr<MTL::Device> device) : device_(device) { if (device == nullptr) { throw std::runtime_error("metal: Failed to create the default library."); } // Compile a Metal library auto src = NS::String::string(msl_source_, NS::ASCIIStringEncoding); NS::Error* error = nullptr; auto lib = managed(device->newLibrary(src, nullptr, &error)); if (lib == nullptr) { std::stringstream ss; ss << "metal: Failed to compile the Metal library, error " << error << "."; throw std::runtime_error(ss.str()); } // Create pipeline state objects pso_add_ = create_compute_pipeline_state_object_(device, lib, "add"); pso_sub_ = create_compute_pipeline_state_object_(device, lib, "sub"); pso_mul_ = create_compute_pipeline_state_object_(device, lib, "mul"); pso_div_ = create_compute_pipeline_state_object_(device, lib, "div"); pso_pow_ = create_compute_pipeline_state_object_(device, lib, "pow"); pso_dot_ = create_compute_pipeline_state_object_(device, lib, "dot"); // Create a command queue queue_ = managed(device->newCommandQueue()); if (queue_ == nullptr) { throw std::runtime_error("metal: Failed to find the command queue."); } } inline managed_ptr<MTL::Buffer> metal::make_buffer(NS::UInteger length) { return managed(device_->newBuffer(length, MTL::ResourceStorageModeShared)); } template <value_type T> inline void metal::add(const storage& A, const storage& B, storage& OUT) { arithmetic_operation_<T>(A, B, OUT, pso_add_); } template <value_type T> inline void metal::sub(const storage& A, const storage& B, storage& OUT) { arithmetic_operation_<T>(A, B, OUT, pso_sub_); } template <value_type T> inline void metal::mul(const storage& A, const storage& B, storage& OUT) { arithmetic_operation_<T>(A, B, OUT, pso_mul_); } template <value_type T> inline void metal::div(const storage& A, const storage& B, storage& OUT) { arithmetic_operation_<T>(A, B, OUT, pso_div_); } template <value_type T> inline void metal::pow(const storage& A, const storage& B, storage& OUT) { arithmetic_operation_<T>(A, B, OUT, pso_pow_); } template <value_type T> inline void metal::dot(const storage& A, const storage& B, storage& OUT, uint32_t A_cols, uint32_t OUT_rows, uint32_t OUT_cols) { auto pso = pso_dot_; auto dtype = std::is_same_v<T, float> ? static_cast<uint32_t>(DataType::Float) : static_cast<uint32_t>(DataType::Integer); auto commandBuffer = queue_->commandBuffer(); auto computeEncoder = commandBuffer->computeCommandEncoder(); computeEncoder->setComputePipelineState(pso.get()); computeEncoder->setBuffer(A.buf.get(), A.off * sizeof(T), 0); computeEncoder->setBuffer(B.buf.get(), B.off * sizeof(T), 1); computeEncoder->setBuffer(OUT.buf.get(), OUT.off * sizeof(T), 2); computeEncoder->setBytes(&A_cols, sizeof(uint32_t), 3); computeEncoder->setBytes(&OUT_rows, sizeof(uint32_t), 4); computeEncoder->setBytes(&OUT_cols, sizeof(uint32_t), 5); computeEncoder->setBytes(&dtype, sizeof(uint32_t), 6); auto grid_size = MTL::Size::Make(OUT_cols, OUT_rows, 1); auto w = pso->threadExecutionWidth(); auto h = pso->maxTotalThreadsPerThreadgroup() / w; auto threads_size = MTL::Size::Make(w, h, 1); computeEncoder->dispatchThreads(grid_size, threads_size); computeEncoder->endEncoding(); commandBuffer->commit(); commandBuffer->waitUntilCompleted(); } template <value_type T> inline void metal::arithmetic_operation_( const storage& A, const storage& B, storage& OUT, managed_ptr<MTL::ComputePipelineState> pso) { auto dtype = std::is_same_v<T, float> ? static_cast<uint32_t>(DataType::Float) : static_cast<uint32_t>(DataType::Integer); auto commandBuffer = queue_->commandBuffer(); auto computeEncoder = commandBuffer->computeCommandEncoder(); computeEncoder->setComputePipelineState(pso.get()); computeEncoder->setBuffer(A.buf.get(), A.off * sizeof(T), 0); computeEncoder->setBuffer(B.buf.get(), B.off * sizeof(T), 1); computeEncoder->setBuffer(OUT.buf.get(), OUT.off * sizeof(T), 2); computeEncoder->setBytes(&A.len, sizeof(uint32_t), 3); computeEncoder->setBytes(&B.len, sizeof(uint32_t), 4); computeEncoder->setBytes(&dtype, sizeof(uint32_t), 5); auto grid_size = MTL::Size::Make(OUT.len, 1, 1); auto w = pso->threadExecutionWidth(); auto h = pso->maxTotalThreadsPerThreadgroup() / w; auto threads_size = MTL::Size::Make(w, h, 1); computeEncoder->dispatchThreads(grid_size, threads_size); computeEncoder->endEncoding(); commandBuffer->commit(); commandBuffer->waitUntilCompleted(); } inline managed_ptr<MTL::ComputePipelineState> metal::create_compute_pipeline_state_object_(managed_ptr<MTL::Device> device, managed_ptr<MTL::Library> library, const char* name) { auto str = NS::String::string(name, NS::ASCIIStringEncoding); auto fn = managed(library->newFunction(str)); if (fn == nullptr) { std::stringstream ss; ss << "metal: Failed to find the " << name << " function."; throw std::runtime_error(ss.str()); } NS::Error* error = nullptr; auto pso = managed(device->newComputePipelineState(fn.get(), &error)); if (pso == nullptr) { std::stringstream ss; ss << "metal: Failed to created pipeline state object, error " << error << "."; throw std::runtime_error(ss.str()); } return pso; } }; // namespace mtl
yhirose/mtlcpp
16
Utilities for Metal-cpp
C++
yhirose
include/mtlcpp.h
C/C++ Header
#pragma once #include "./metal.h" #include "./array.h"
yhirose/mtlcpp
16
Utilities for Metal-cpp
C++
yhirose
metal-cpp_macOS14.2_iOS17.2/Metal/Metal.hpp
C++ Header
// // Metal.hpp // // Autogenerated on February 11, 2024. // // Copyright 2020-2023 Apple Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma once #define _NS_WEAK_IMPORT __attribute__((weak_import)) #ifdef METALCPP_SYMBOL_VISIBILITY_HIDDEN #define _NS_EXPORT __attribute__((visibility("hidden"))) #else #define _NS_EXPORT __attribute__((visibility("default"))) #endif // METALCPP_SYMBOL_VISIBILITY_HIDDEN #define _NS_EXTERN extern "C" _NS_EXPORT #define _NS_INLINE inline __attribute__((always_inline)) #define _NS_PACKED __attribute__((packed)) #define _NS_CONST(type, name) _NS_EXTERN type const name #define _NS_ENUM(type, name) enum name : type #define _NS_OPTIONS(type, name) \ using name = type; \ enum : name #define _NS_CAST_TO_UINT(value) static_cast<NS::UInteger>(value) #define _NS_VALIDATE_SIZE(ns, name) static_assert(sizeof(ns::name) == sizeof(ns##name), "size mismatch " #ns "::" #name) #define _NS_VALIDATE_ENUM(ns, name) static_assert(_NS_CAST_TO_UINT(ns::name) == _NS_CAST_TO_UINT(ns##name), "value mismatch " #ns "::" #name) #include <objc/runtime.h> #define _NS_PRIVATE_CLS(symbol) (Private::Class::s_k##symbol) #define _NS_PRIVATE_SEL(accessor) (Private::Selector::s_k##accessor) #if defined(NS_PRIVATE_IMPLEMENTATION) #ifdef METALCPP_SYMBOL_VISIBILITY_HIDDEN #define _NS_PRIVATE_VISIBILITY __attribute__((visibility("hidden"))) #else #define _NS_PRIVATE_VISIBILITY __attribute__((visibility("default"))) #endif // METALCPP_SYMBOL_VISIBILITY_HIDDEN #define _NS_PRIVATE_IMPORT __attribute__((weak_import)) #ifdef __OBJC__ #define _NS_PRIVATE_OBJC_LOOKUP_CLASS(symbol) ((__bridge void*)objc_lookUpClass(#symbol)) #define _NS_PRIVATE_OBJC_GET_PROTOCOL(symbol) ((__bridge void*)objc_getProtocol(#symbol)) #else #define _NS_PRIVATE_OBJC_LOOKUP_CLASS(symbol) objc_lookUpClass(#symbol) #define _NS_PRIVATE_OBJC_GET_PROTOCOL(symbol) objc_getProtocol(#symbol) #endif // __OBJC__ #define _NS_PRIVATE_DEF_CLS(symbol) void* s_k##symbol _NS_PRIVATE_VISIBILITY = _NS_PRIVATE_OBJC_LOOKUP_CLASS(symbol) #define _NS_PRIVATE_DEF_PRO(symbol) void* s_k##symbol _NS_PRIVATE_VISIBILITY = _NS_PRIVATE_OBJC_GET_PROTOCOL(symbol) #define _NS_PRIVATE_DEF_SEL(accessor, symbol) SEL s_k##accessor _NS_PRIVATE_VISIBILITY = sel_registerName(symbol) #define _NS_PRIVATE_DEF_CONST(type, symbol) \ _NS_EXTERN type const NS##symbol _NS_PRIVATE_IMPORT; \ type const NS::symbol = (nullptr != &NS##symbol) ? NS##symbol : nullptr #else #define _NS_PRIVATE_DEF_CLS(symbol) extern void* s_k##symbol #define _NS_PRIVATE_DEF_PRO(symbol) extern void* s_k##symbol #define _NS_PRIVATE_DEF_SEL(accessor, symbol) extern SEL s_k##accessor #define _NS_PRIVATE_DEF_CONST(type, symbol) extern type const NS::symbol #endif // NS_PRIVATE_IMPLEMENTATION namespace NS { namespace Private { namespace Class { _NS_PRIVATE_DEF_CLS(NSArray); _NS_PRIVATE_DEF_CLS(NSAutoreleasePool); _NS_PRIVATE_DEF_CLS(NSBundle); _NS_PRIVATE_DEF_CLS(NSCondition); _NS_PRIVATE_DEF_CLS(NSDate); _NS_PRIVATE_DEF_CLS(NSDictionary); _NS_PRIVATE_DEF_CLS(NSError); _NS_PRIVATE_DEF_CLS(NSNotificationCenter); _NS_PRIVATE_DEF_CLS(NSNumber); _NS_PRIVATE_DEF_CLS(NSObject); _NS_PRIVATE_DEF_CLS(NSProcessInfo); _NS_PRIVATE_DEF_CLS(NSSet); _NS_PRIVATE_DEF_CLS(NSString); _NS_PRIVATE_DEF_CLS(NSURL); _NS_PRIVATE_DEF_CLS(NSValue); } // Class } // Private } // MTL namespace NS { namespace Private { namespace Protocol { } // Protocol } // Private } // NS namespace NS { namespace Private { namespace Selector { _NS_PRIVATE_DEF_SEL(addObject_, "addObject:"); _NS_PRIVATE_DEF_SEL(addObserverName_object_queue_block_, "addObserverForName:object:queue:usingBlock:"); _NS_PRIVATE_DEF_SEL(activeProcessorCount, "activeProcessorCount"); _NS_PRIVATE_DEF_SEL(allBundles, "allBundles"); _NS_PRIVATE_DEF_SEL(allFrameworks, "allFrameworks"); _NS_PRIVATE_DEF_SEL(allObjects, "allObjects"); _NS_PRIVATE_DEF_SEL(alloc, "alloc"); _NS_PRIVATE_DEF_SEL(appStoreReceiptURL, "appStoreReceiptURL"); _NS_PRIVATE_DEF_SEL(arguments, "arguments"); _NS_PRIVATE_DEF_SEL(array, "array"); _NS_PRIVATE_DEF_SEL(arrayWithObject_, "arrayWithObject:"); _NS_PRIVATE_DEF_SEL(arrayWithObjects_count_, "arrayWithObjects:count:"); _NS_PRIVATE_DEF_SEL(automaticTerminationSupportEnabled, "automaticTerminationSupportEnabled"); _NS_PRIVATE_DEF_SEL(autorelease, "autorelease"); _NS_PRIVATE_DEF_SEL(beginActivityWithOptions_reason_, "beginActivityWithOptions:reason:"); _NS_PRIVATE_DEF_SEL(boolValue, "boolValue"); _NS_PRIVATE_DEF_SEL(broadcast, "broadcast"); _NS_PRIVATE_DEF_SEL(builtInPlugInsPath, "builtInPlugInsPath"); _NS_PRIVATE_DEF_SEL(builtInPlugInsURL, "builtInPlugInsURL"); _NS_PRIVATE_DEF_SEL(bundleIdentifier, "bundleIdentifier"); _NS_PRIVATE_DEF_SEL(bundlePath, "bundlePath"); _NS_PRIVATE_DEF_SEL(bundleURL, "bundleURL"); _NS_PRIVATE_DEF_SEL(bundleWithPath_, "bundleWithPath:"); _NS_PRIVATE_DEF_SEL(bundleWithURL_, "bundleWithURL:"); _NS_PRIVATE_DEF_SEL(caseInsensitiveCompare_, "caseInsensitiveCompare:"); _NS_PRIVATE_DEF_SEL(characterAtIndex_, "characterAtIndex:"); _NS_PRIVATE_DEF_SEL(charValue, "charValue"); _NS_PRIVATE_DEF_SEL(countByEnumeratingWithState_objects_count_, "countByEnumeratingWithState:objects:count:"); _NS_PRIVATE_DEF_SEL(cStringUsingEncoding_, "cStringUsingEncoding:"); _NS_PRIVATE_DEF_SEL(code, "code"); _NS_PRIVATE_DEF_SEL(compare_, "compare:"); _NS_PRIVATE_DEF_SEL(copy, "copy"); _NS_PRIVATE_DEF_SEL(count, "count"); _NS_PRIVATE_DEF_SEL(dateWithTimeIntervalSinceNow_, "dateWithTimeIntervalSinceNow:"); _NS_PRIVATE_DEF_SEL(defaultCenter, "defaultCenter"); _NS_PRIVATE_DEF_SEL(descriptionWithLocale_, "descriptionWithLocale:"); _NS_PRIVATE_DEF_SEL(disableAutomaticTermination_, "disableAutomaticTermination:"); _NS_PRIVATE_DEF_SEL(disableSuddenTermination, "disableSuddenTermination"); _NS_PRIVATE_DEF_SEL(debugDescription, "debugDescription"); _NS_PRIVATE_DEF_SEL(description, "description"); _NS_PRIVATE_DEF_SEL(dictionary, "dictionary"); _NS_PRIVATE_DEF_SEL(dictionaryWithObject_forKey_, "dictionaryWithObject:forKey:"); _NS_PRIVATE_DEF_SEL(dictionaryWithObjects_forKeys_count_, "dictionaryWithObjects:forKeys:count:"); _NS_PRIVATE_DEF_SEL(domain, "domain"); _NS_PRIVATE_DEF_SEL(doubleValue, "doubleValue"); _NS_PRIVATE_DEF_SEL(drain, "drain"); _NS_PRIVATE_DEF_SEL(enableAutomaticTermination_, "enableAutomaticTermination:"); _NS_PRIVATE_DEF_SEL(enableSuddenTermination, "enableSuddenTermination"); _NS_PRIVATE_DEF_SEL(endActivity_, "endActivity:"); _NS_PRIVATE_DEF_SEL(environment, "environment"); _NS_PRIVATE_DEF_SEL(errorWithDomain_code_userInfo_, "errorWithDomain:code:userInfo:"); _NS_PRIVATE_DEF_SEL(executablePath, "executablePath"); _NS_PRIVATE_DEF_SEL(executableURL, "executableURL"); _NS_PRIVATE_DEF_SEL(fileSystemRepresentation, "fileSystemRepresentation"); _NS_PRIVATE_DEF_SEL(fileURLWithPath_, "fileURLWithPath:"); _NS_PRIVATE_DEF_SEL(floatValue, "floatValue"); _NS_PRIVATE_DEF_SEL(fullUserName, "fullUserName"); _NS_PRIVATE_DEF_SEL(getValue_size_, "getValue:size:"); _NS_PRIVATE_DEF_SEL(globallyUniqueString, "globallyUniqueString"); _NS_PRIVATE_DEF_SEL(hash, "hash"); _NS_PRIVATE_DEF_SEL(hostName, "hostName"); _NS_PRIVATE_DEF_SEL(infoDictionary, "infoDictionary"); _NS_PRIVATE_DEF_SEL(init, "init"); _NS_PRIVATE_DEF_SEL(initFileURLWithPath_, "initFileURLWithPath:"); _NS_PRIVATE_DEF_SEL(initWithBool_, "initWithBool:"); _NS_PRIVATE_DEF_SEL(initWithBytes_objCType_, "initWithBytes:objCType:"); _NS_PRIVATE_DEF_SEL(initWithBytesNoCopy_length_encoding_freeWhenDone_, "initWithBytesNoCopy:length:encoding:freeWhenDone:"); _NS_PRIVATE_DEF_SEL(initWithChar_, "initWithChar:"); _NS_PRIVATE_DEF_SEL(initWithCoder_, "initWithCoder:"); _NS_PRIVATE_DEF_SEL(initWithCString_encoding_, "initWithCString:encoding:"); _NS_PRIVATE_DEF_SEL(initWithDomain_code_userInfo_, "initWithDomain:code:userInfo:"); _NS_PRIVATE_DEF_SEL(initWithDouble_, "initWithDouble:"); _NS_PRIVATE_DEF_SEL(initWithFloat_, "initWithFloat:"); _NS_PRIVATE_DEF_SEL(initWithInt_, "initWithInt:"); _NS_PRIVATE_DEF_SEL(initWithLong_, "initWithLong:"); _NS_PRIVATE_DEF_SEL(initWithLongLong_, "initWithLongLong:"); _NS_PRIVATE_DEF_SEL(initWithObjects_count_, "initWithObjects:count:"); _NS_PRIVATE_DEF_SEL(initWithObjects_forKeys_count_, "initWithObjects:forKeys:count:"); _NS_PRIVATE_DEF_SEL(initWithPath_, "initWithPath:"); _NS_PRIVATE_DEF_SEL(initWithShort_, "initWithShort:"); _NS_PRIVATE_DEF_SEL(initWithString_, "initWithString:"); _NS_PRIVATE_DEF_SEL(initWithUnsignedChar_, "initWithUnsignedChar:"); _NS_PRIVATE_DEF_SEL(initWithUnsignedInt_, "initWithUnsignedInt:"); _NS_PRIVATE_DEF_SEL(initWithUnsignedLong_, "initWithUnsignedLong:"); _NS_PRIVATE_DEF_SEL(initWithUnsignedLongLong_, "initWithUnsignedLongLong:"); _NS_PRIVATE_DEF_SEL(initWithUnsignedShort_, "initWithUnsignedShort:"); _NS_PRIVATE_DEF_SEL(initWithURL_, "initWithURL:"); _NS_PRIVATE_DEF_SEL(integerValue, "integerValue"); _NS_PRIVATE_DEF_SEL(intValue, "intValue"); _NS_PRIVATE_DEF_SEL(isEqual_, "isEqual:"); _NS_PRIVATE_DEF_SEL(isEqualToNumber_, "isEqualToNumber:"); _NS_PRIVATE_DEF_SEL(isEqualToString_, "isEqualToString:"); _NS_PRIVATE_DEF_SEL(isEqualToValue_, "isEqualToValue:"); _NS_PRIVATE_DEF_SEL(isiOSAppOnMac, "isiOSAppOnMac"); _NS_PRIVATE_DEF_SEL(isLoaded, "isLoaded"); _NS_PRIVATE_DEF_SEL(isLowPowerModeEnabled, "isLowPowerModeEnabled"); _NS_PRIVATE_DEF_SEL(isMacCatalystApp, "isMacCatalystApp"); _NS_PRIVATE_DEF_SEL(isOperatingSystemAtLeastVersion_, "isOperatingSystemAtLeastVersion:"); _NS_PRIVATE_DEF_SEL(keyEnumerator, "keyEnumerator"); _NS_PRIVATE_DEF_SEL(length, "length"); _NS_PRIVATE_DEF_SEL(lengthOfBytesUsingEncoding_, "lengthOfBytesUsingEncoding:"); _NS_PRIVATE_DEF_SEL(load, "load"); _NS_PRIVATE_DEF_SEL(loadAndReturnError_, "loadAndReturnError:"); _NS_PRIVATE_DEF_SEL(localizedDescription, "localizedDescription"); _NS_PRIVATE_DEF_SEL(localizedFailureReason, "localizedFailureReason"); _NS_PRIVATE_DEF_SEL(localizedInfoDictionary, "localizedInfoDictionary"); _NS_PRIVATE_DEF_SEL(localizedRecoveryOptions, "localizedRecoveryOptions"); _NS_PRIVATE_DEF_SEL(localizedRecoverySuggestion, "localizedRecoverySuggestion"); _NS_PRIVATE_DEF_SEL(localizedStringForKey_value_table_, "localizedStringForKey:value:table:"); _NS_PRIVATE_DEF_SEL(lock, "lock"); _NS_PRIVATE_DEF_SEL(longValue, "longValue"); _NS_PRIVATE_DEF_SEL(longLongValue, "longLongValue"); _NS_PRIVATE_DEF_SEL(mainBundle, "mainBundle"); _NS_PRIVATE_DEF_SEL(maximumLengthOfBytesUsingEncoding_, "maximumLengthOfBytesUsingEncoding:"); _NS_PRIVATE_DEF_SEL(methodSignatureForSelector_, "methodSignatureForSelector:"); _NS_PRIVATE_DEF_SEL(mutableBytes, "mutableBytes"); _NS_PRIVATE_DEF_SEL(name, "name"); _NS_PRIVATE_DEF_SEL(nextObject, "nextObject"); _NS_PRIVATE_DEF_SEL(numberWithBool_, "numberWithBool:"); _NS_PRIVATE_DEF_SEL(numberWithChar_, "numberWithChar:"); _NS_PRIVATE_DEF_SEL(numberWithDouble_, "numberWithDouble:"); _NS_PRIVATE_DEF_SEL(numberWithFloat_, "numberWithFloat:"); _NS_PRIVATE_DEF_SEL(numberWithInt_, "numberWithInt:"); _NS_PRIVATE_DEF_SEL(numberWithLong_, "numberWithLong:"); _NS_PRIVATE_DEF_SEL(numberWithLongLong_, "numberWithLongLong:"); _NS_PRIVATE_DEF_SEL(numberWithShort_, "numberWithShort:"); _NS_PRIVATE_DEF_SEL(numberWithUnsignedChar_, "numberWithUnsignedChar:"); _NS_PRIVATE_DEF_SEL(numberWithUnsignedInt_, "numberWithUnsignedInt:"); _NS_PRIVATE_DEF_SEL(numberWithUnsignedLong_, "numberWithUnsignedLong:"); _NS_PRIVATE_DEF_SEL(numberWithUnsignedLongLong_, "numberWithUnsignedLongLong:"); _NS_PRIVATE_DEF_SEL(numberWithUnsignedShort_, "numberWithUnsignedShort:"); _NS_PRIVATE_DEF_SEL(objCType, "objCType"); _NS_PRIVATE_DEF_SEL(object, "object"); _NS_PRIVATE_DEF_SEL(objectAtIndex_, "objectAtIndex:"); _NS_PRIVATE_DEF_SEL(objectEnumerator, "objectEnumerator"); _NS_PRIVATE_DEF_SEL(objectForInfoDictionaryKey_, "objectForInfoDictionaryKey:"); _NS_PRIVATE_DEF_SEL(objectForKey_, "objectForKey:"); _NS_PRIVATE_DEF_SEL(operatingSystem, "operatingSystem"); _NS_PRIVATE_DEF_SEL(operatingSystemVersion, "operatingSystemVersion"); _NS_PRIVATE_DEF_SEL(operatingSystemVersionString, "operatingSystemVersionString"); _NS_PRIVATE_DEF_SEL(pathForAuxiliaryExecutable_, "pathForAuxiliaryExecutable:"); _NS_PRIVATE_DEF_SEL(performActivityWithOptions_reason_usingBlock_, "performActivityWithOptions:reason:usingBlock:"); _NS_PRIVATE_DEF_SEL(performExpiringActivityWithReason_usingBlock_, "performExpiringActivityWithReason:usingBlock:"); _NS_PRIVATE_DEF_SEL(physicalMemory, "physicalMemory"); _NS_PRIVATE_DEF_SEL(pointerValue, "pointerValue"); _NS_PRIVATE_DEF_SEL(preflightAndReturnError_, "preflightAndReturnError:"); _NS_PRIVATE_DEF_SEL(privateFrameworksPath, "privateFrameworksPath"); _NS_PRIVATE_DEF_SEL(privateFrameworksURL, "privateFrameworksURL"); _NS_PRIVATE_DEF_SEL(processIdentifier, "processIdentifier"); _NS_PRIVATE_DEF_SEL(processInfo, "processInfo"); _NS_PRIVATE_DEF_SEL(processName, "processName"); _NS_PRIVATE_DEF_SEL(processorCount, "processorCount"); _NS_PRIVATE_DEF_SEL(rangeOfString_options_, "rangeOfString:options:"); _NS_PRIVATE_DEF_SEL(release, "release"); _NS_PRIVATE_DEF_SEL(removeObserver_, "removeObserver:"); _NS_PRIVATE_DEF_SEL(resourcePath, "resourcePath"); _NS_PRIVATE_DEF_SEL(resourceURL, "resourceURL"); _NS_PRIVATE_DEF_SEL(respondsToSelector_, "respondsToSelector:"); _NS_PRIVATE_DEF_SEL(retain, "retain"); _NS_PRIVATE_DEF_SEL(retainCount, "retainCount"); _NS_PRIVATE_DEF_SEL(setAutomaticTerminationSupportEnabled_, "setAutomaticTerminationSupportEnabled:"); _NS_PRIVATE_DEF_SEL(setProcessName_, "setProcessName:"); _NS_PRIVATE_DEF_SEL(sharedFrameworksPath, "sharedFrameworksPath"); _NS_PRIVATE_DEF_SEL(sharedFrameworksURL, "sharedFrameworksURL"); _NS_PRIVATE_DEF_SEL(sharedSupportPath, "sharedSupportPath"); _NS_PRIVATE_DEF_SEL(sharedSupportURL, "sharedSupportURL"); _NS_PRIVATE_DEF_SEL(shortValue, "shortValue"); _NS_PRIVATE_DEF_SEL(showPools, "showPools"); _NS_PRIVATE_DEF_SEL(signal, "signal"); _NS_PRIVATE_DEF_SEL(string, "string"); _NS_PRIVATE_DEF_SEL(stringValue, "stringValue"); _NS_PRIVATE_DEF_SEL(stringWithString_, "stringWithString:"); _NS_PRIVATE_DEF_SEL(stringWithCString_encoding_, "stringWithCString:encoding:"); _NS_PRIVATE_DEF_SEL(stringByAppendingString_, "stringByAppendingString:"); _NS_PRIVATE_DEF_SEL(systemUptime, "systemUptime"); _NS_PRIVATE_DEF_SEL(thermalState, "thermalState"); _NS_PRIVATE_DEF_SEL(unload, "unload"); _NS_PRIVATE_DEF_SEL(unlock, "unlock"); _NS_PRIVATE_DEF_SEL(unsignedCharValue, "unsignedCharValue"); _NS_PRIVATE_DEF_SEL(unsignedIntegerValue, "unsignedIntegerValue"); _NS_PRIVATE_DEF_SEL(unsignedIntValue, "unsignedIntValue"); _NS_PRIVATE_DEF_SEL(unsignedLongValue, "unsignedLongValue"); _NS_PRIVATE_DEF_SEL(unsignedLongLongValue, "unsignedLongLongValue"); _NS_PRIVATE_DEF_SEL(unsignedShortValue, "unsignedShortValue"); _NS_PRIVATE_DEF_SEL(URLForAuxiliaryExecutable_, "URLForAuxiliaryExecutable:"); _NS_PRIVATE_DEF_SEL(userInfo, "userInfo"); _NS_PRIVATE_DEF_SEL(userName, "userName"); _NS_PRIVATE_DEF_SEL(UTF8String, "UTF8String"); _NS_PRIVATE_DEF_SEL(valueWithBytes_objCType_, "valueWithBytes:objCType:"); _NS_PRIVATE_DEF_SEL(valueWithPointer_, "valueWithPointer:"); _NS_PRIVATE_DEF_SEL(wait, "wait"); _NS_PRIVATE_DEF_SEL(waitUntilDate_, "waitUntilDate:"); } // Class } // Private } // MTL #include <CoreFoundation/CoreFoundation.h> #include <cstdint> namespace NS { using TimeInterval = double; using Integer = std::intptr_t; using UInteger = std::uintptr_t; const Integer IntegerMax = INTPTR_MAX; const Integer IntegerMin = INTPTR_MIN; const UInteger UIntegerMax = UINTPTR_MAX; struct OperatingSystemVersion { Integer majorVersion; Integer minorVersion; Integer patchVersion; } _NS_PACKED; } #include <objc/message.h> #include <objc/runtime.h> #include <type_traits> namespace NS { template <class _Class, class _Base = class Object> class _NS_EXPORT Referencing : public _Base { public: _Class* retain(); void release(); _Class* autorelease(); UInteger retainCount() const; }; template <class _Class, class _Base = class Object> class Copying : public Referencing<_Class, _Base> { public: _Class* copy() const; }; template <class _Class, class _Base = class Object> class SecureCoding : public Referencing<_Class, _Base> { }; class Object : public Referencing<Object, objc_object> { public: UInteger hash() const; bool isEqual(const Object* pObject) const; class String* description() const; class String* debugDescription() const; protected: friend class Referencing<Object, objc_object>; template <class _Class> static _Class* alloc(const char* pClassName); template <class _Class> static _Class* alloc(const void* pClass); template <class _Class> _Class* init(); template <class _Dst> static _Dst bridgingCast(const void* pObj); static class MethodSignature* methodSignatureForSelector(const void* pObj, SEL selector); static bool respondsToSelector(const void* pObj, SEL selector); template <typename _Type> static constexpr bool doesRequireMsgSendStret(); template <typename _Ret, typename... _Args> static _Ret sendMessage(const void* pObj, SEL selector, _Args... args); template <typename _Ret, typename... _Args> static _Ret sendMessageSafe(const void* pObj, SEL selector, _Args... args); private: Object() = delete; Object(const Object&) = delete; ~Object() = delete; Object& operator=(const Object&) = delete; }; } template <class _Class, class _Base /* = Object */> _NS_INLINE _Class* NS::Referencing<_Class, _Base>::retain() { return Object::sendMessage<_Class*>(this, _NS_PRIVATE_SEL(retain)); } template <class _Class, class _Base /* = Object */> _NS_INLINE void NS::Referencing<_Class, _Base>::release() { Object::sendMessage<void>(this, _NS_PRIVATE_SEL(release)); } template <class _Class, class _Base /* = Object */> _NS_INLINE _Class* NS::Referencing<_Class, _Base>::autorelease() { return Object::sendMessage<_Class*>(this, _NS_PRIVATE_SEL(autorelease)); } template <class _Class, class _Base /* = Object */> _NS_INLINE NS::UInteger NS::Referencing<_Class, _Base>::retainCount() const { return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(retainCount)); } template <class _Class, class _Base /* = Object */> _NS_INLINE _Class* NS::Copying<_Class, _Base>::copy() const { return Object::sendMessage<_Class*>(this, _NS_PRIVATE_SEL(copy)); } template <class _Dst> _NS_INLINE _Dst NS::Object::bridgingCast(const void* pObj) { #ifdef __OBJC__ return (__bridge _Dst)pObj; #else return (_Dst)pObj; #endif // __OBJC__ } template <typename _Type> _NS_INLINE constexpr bool NS::Object::doesRequireMsgSendStret() { #if (defined(__i386__) || defined(__x86_64__)) constexpr size_t kStructLimit = (sizeof(std::uintptr_t) << 1); return sizeof(_Type) > kStructLimit; #elif defined(__arm64__) return false; #elif defined(__arm__) constexpr size_t kStructLimit = sizeof(std::uintptr_t); return std::is_class(_Type) && (sizeof(_Type) > kStructLimit); #else #error "Unsupported architecture!" #endif } template <> _NS_INLINE constexpr bool NS::Object::doesRequireMsgSendStret<void>() { return false; } template <typename _Ret, typename... _Args> _NS_INLINE _Ret NS::Object::sendMessage(const void* pObj, SEL selector, _Args... args) { #if (defined(__i386__) || defined(__x86_64__)) if constexpr (std::is_floating_point<_Ret>()) { using SendMessageProcFpret = _Ret (*)(const void*, SEL, _Args...); const SendMessageProcFpret pProc = reinterpret_cast<SendMessageProcFpret>(&objc_msgSend_fpret); return (*pProc)(pObj, selector, args...); } else #endif // ( defined( __i386__ ) || defined( __x86_64__ ) ) #if !defined(__arm64__) if constexpr (doesRequireMsgSendStret<_Ret>()) { using SendMessageProcStret = void (*)(_Ret*, const void*, SEL, _Args...); const SendMessageProcStret pProc = reinterpret_cast<SendMessageProcStret>(&objc_msgSend_stret); _Ret ret; (*pProc)(&ret, pObj, selector, args...); return ret; } else #endif // !defined( __arm64__ ) { using SendMessageProc = _Ret (*)(const void*, SEL, _Args...); const SendMessageProc pProc = reinterpret_cast<SendMessageProc>(&objc_msgSend); return (*pProc)(pObj, selector, args...); } } _NS_INLINE NS::MethodSignature* NS::Object::methodSignatureForSelector(const void* pObj, SEL selector) { return sendMessage<MethodSignature*>(pObj, _NS_PRIVATE_SEL(methodSignatureForSelector_), selector); } _NS_INLINE bool NS::Object::respondsToSelector(const void* pObj, SEL selector) { return sendMessage<bool>(pObj, _NS_PRIVATE_SEL(respondsToSelector_), selector); } template <typename _Ret, typename... _Args> _NS_INLINE _Ret NS::Object::sendMessageSafe(const void* pObj, SEL selector, _Args... args) { if ((respondsToSelector(pObj, selector)) || (nullptr != methodSignatureForSelector(pObj, selector))) { return sendMessage<_Ret>(pObj, selector, args...); } if constexpr (!std::is_void<_Ret>::value) { return _Ret(0); } } template <class _Class> _NS_INLINE _Class* NS::Object::alloc(const char* pClassName) { return sendMessage<_Class*>(objc_lookUpClass(pClassName), _NS_PRIVATE_SEL(alloc)); } template <class _Class> _NS_INLINE _Class* NS::Object::alloc(const void* pClass) { return sendMessage<_Class*>(pClass, _NS_PRIVATE_SEL(alloc)); } template <class _Class> _NS_INLINE _Class* NS::Object::init() { return sendMessage<_Class*>(this, _NS_PRIVATE_SEL(init)); } _NS_INLINE NS::UInteger NS::Object::hash() const { return sendMessage<UInteger>(this, _NS_PRIVATE_SEL(hash)); } _NS_INLINE bool NS::Object::isEqual(const Object* pObject) const { return sendMessage<bool>(this, _NS_PRIVATE_SEL(isEqual_), pObject); } _NS_INLINE NS::String* NS::Object::description() const { return sendMessage<String*>(this, _NS_PRIVATE_SEL(description)); } _NS_INLINE NS::String* NS::Object::debugDescription() const { return sendMessageSafe<String*>(this, _NS_PRIVATE_SEL(debugDescription)); } namespace NS { class Array : public Copying<Array> { public: static Array* array(); static Array* array(const Object* pObject); static Array* array(const Object* const* pObjects, UInteger count); static Array* alloc(); Array* init(); Array* init(const Object* const* pObjects, UInteger count); Array* init(const class Coder* pCoder); template <class _Object = Object> _Object* object(UInteger index) const; UInteger count() const; }; } _NS_INLINE NS::Array* NS::Array::array() { return Object::sendMessage<Array*>(_NS_PRIVATE_CLS(NSArray), _NS_PRIVATE_SEL(array)); } _NS_INLINE NS::Array* NS::Array::array(const Object* pObject) { return Object::sendMessage<Array*>(_NS_PRIVATE_CLS(NSArray), _NS_PRIVATE_SEL(arrayWithObject_), pObject); } _NS_INLINE NS::Array* NS::Array::array(const Object* const* pObjects, UInteger count) { return Object::sendMessage<Array*>(_NS_PRIVATE_CLS(NSArray), _NS_PRIVATE_SEL(arrayWithObjects_count_), pObjects, count); } _NS_INLINE NS::Array* NS::Array::alloc() { return NS::Object::alloc<Array>(_NS_PRIVATE_CLS(NSArray)); } _NS_INLINE NS::Array* NS::Array::init() { return NS::Object::init<Array>(); } _NS_INLINE NS::Array* NS::Array::init(const Object* const* pObjects, UInteger count) { return Object::sendMessage<Array*>(this, _NS_PRIVATE_SEL(initWithObjects_count_), pObjects, count); } _NS_INLINE NS::Array* NS::Array::init(const class Coder* pCoder) { return Object::sendMessage<Array*>(this, _NS_PRIVATE_SEL(initWithCoder_), pCoder); } _NS_INLINE NS::UInteger NS::Array::count() const { return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(count)); } template <class _Object> _NS_INLINE _Object* NS::Array::object(UInteger index) const { return Object::sendMessage<_Object*>(this, _NS_PRIVATE_SEL(objectAtIndex_), index); } namespace NS { class AutoreleasePool : public Object { public: static AutoreleasePool* alloc(); AutoreleasePool* init(); void drain(); void addObject(Object* pObject); static void showPools(); }; } _NS_INLINE NS::AutoreleasePool* NS::AutoreleasePool::alloc() { return NS::Object::alloc<AutoreleasePool>(_NS_PRIVATE_CLS(NSAutoreleasePool)); } _NS_INLINE NS::AutoreleasePool* NS::AutoreleasePool::init() { return NS::Object::init<AutoreleasePool>(); } _NS_INLINE void NS::AutoreleasePool::drain() { Object::sendMessage<void>(this, _NS_PRIVATE_SEL(drain)); } _NS_INLINE void NS::AutoreleasePool::addObject(Object* pObject) { Object::sendMessage<void>(this, _NS_PRIVATE_SEL(addObject_), pObject); } _NS_INLINE void NS::AutoreleasePool::showPools() { Object::sendMessage<void>(_NS_PRIVATE_CLS(NSAutoreleasePool), _NS_PRIVATE_SEL(showPools)); } namespace NS { struct FastEnumerationState { unsigned long state; Object** itemsPtr; unsigned long* mutationsPtr; unsigned long extra[5]; } _NS_PACKED; class FastEnumeration : public Referencing<FastEnumeration> { public: NS::UInteger countByEnumerating(FastEnumerationState* pState, Object** pBuffer, NS::UInteger len); }; template <class _ObjectType> class Enumerator : public Referencing<Enumerator<_ObjectType>, FastEnumeration> { public: _ObjectType* nextObject(); class Array* allObjects(); }; } _NS_INLINE NS::UInteger NS::FastEnumeration::countByEnumerating(FastEnumerationState* pState, Object** pBuffer, NS::UInteger len) { return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(countByEnumeratingWithState_objects_count_), pState, pBuffer, len); } template <class _ObjectType> _NS_INLINE _ObjectType* NS::Enumerator<_ObjectType>::nextObject() { return Object::sendMessage<_ObjectType*>(this, _NS_PRIVATE_SEL(nextObject)); } template <class _ObjectType> _NS_INLINE NS::Array* NS::Enumerator<_ObjectType>::allObjects() { return Object::sendMessage<Array*>(this, _NS_PRIVATE_SEL(allObjects)); } namespace NS { class Dictionary : public NS::Copying<Dictionary> { public: static Dictionary* dictionary(); static Dictionary* dictionary(const Object* pObject, const Object* pKey); static Dictionary* dictionary(const Object* const* pObjects, const Object* const* pKeys, UInteger count); static Dictionary* alloc(); Dictionary* init(); Dictionary* init(const Object* const* pObjects, const Object* const* pKeys, UInteger count); Dictionary* init(const class Coder* pCoder); template <class _KeyType = Object> Enumerator<_KeyType>* keyEnumerator() const; template <class _Object = Object> _Object* object(const Object* pKey) const; UInteger count() const; }; } _NS_INLINE NS::Dictionary* NS::Dictionary::dictionary() { return Object::sendMessage<Dictionary*>(_NS_PRIVATE_CLS(NSDictionary), _NS_PRIVATE_SEL(dictionary)); } _NS_INLINE NS::Dictionary* NS::Dictionary::dictionary(const Object* pObject, const Object* pKey) { return Object::sendMessage<Dictionary*>(_NS_PRIVATE_CLS(NSDictionary), _NS_PRIVATE_SEL(dictionaryWithObject_forKey_), pObject, pKey); } _NS_INLINE NS::Dictionary* NS::Dictionary::dictionary(const Object* const* pObjects, const Object* const* pKeys, UInteger count) { return Object::sendMessage<Dictionary*>(_NS_PRIVATE_CLS(NSDictionary), _NS_PRIVATE_SEL(dictionaryWithObjects_forKeys_count_), pObjects, pKeys, count); } _NS_INLINE NS::Dictionary* NS::Dictionary::alloc() { return NS::Object::alloc<Dictionary>(_NS_PRIVATE_CLS(NSDictionary)); } _NS_INLINE NS::Dictionary* NS::Dictionary::init() { return NS::Object::init<Dictionary>(); } _NS_INLINE NS::Dictionary* NS::Dictionary::init(const Object* const* pObjects, const Object* const* pKeys, UInteger count) { return Object::sendMessage<Dictionary*>(this, _NS_PRIVATE_SEL(initWithObjects_forKeys_count_), pObjects, pKeys, count); } _NS_INLINE NS::Dictionary* NS::Dictionary::init(const class Coder* pCoder) { return Object::sendMessage<Dictionary*>(this, _NS_PRIVATE_SEL(initWithCoder_), pCoder); } template <class _KeyType> _NS_INLINE NS::Enumerator<_KeyType>* NS::Dictionary::keyEnumerator() const { return Object::sendMessage<Enumerator<_KeyType>*>(this, _NS_PRIVATE_SEL(keyEnumerator)); } template <class _Object> _NS_INLINE _Object* NS::Dictionary::object(const Object* pKey) const { return Object::sendMessage<_Object*>(this, _NS_PRIVATE_SEL(objectForKey_), pKey); } _NS_INLINE NS::UInteger NS::Dictionary::count() const { return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(count)); } namespace NS { _NS_ENUM(Integer, ComparisonResult) { OrderedAscending = -1L, OrderedSame, OrderedDescending }; const Integer NotFound = IntegerMax; } namespace NS { struct Range { static Range Make(UInteger loc, UInteger len); Range(UInteger loc, UInteger len); bool Equal(const Range& range) const; bool LocationInRange(UInteger loc) const; UInteger Max() const; UInteger location; UInteger length; } _NS_PACKED; } _NS_INLINE NS::Range::Range(UInteger loc, UInteger len) : location(loc) , length(len) { } _NS_INLINE NS::Range NS::Range::Make(UInteger loc, UInteger len) { return Range(loc, len); } _NS_INLINE bool NS::Range::Equal(const Range& range) const { return (location == range.location) && (length == range.length); } _NS_INLINE bool NS::Range::LocationInRange(UInteger loc) const { return (!(loc < location)) && ((loc - location) < length); } _NS_INLINE NS::UInteger NS::Range::Max() const { return location + length; } namespace NS { _NS_ENUM(NS::UInteger, StringEncoding) { ASCIIStringEncoding = 1, NEXTSTEPStringEncoding = 2, JapaneseEUCStringEncoding = 3, UTF8StringEncoding = 4, ISOLatin1StringEncoding = 5, SymbolStringEncoding = 6, NonLossyASCIIStringEncoding = 7, ShiftJISStringEncoding = 8, ISOLatin2StringEncoding = 9, UnicodeStringEncoding = 10, WindowsCP1251StringEncoding = 11, WindowsCP1252StringEncoding = 12, WindowsCP1253StringEncoding = 13, WindowsCP1254StringEncoding = 14, WindowsCP1250StringEncoding = 15, ISO2022JPStringEncoding = 21, MacOSRomanStringEncoding = 30, UTF16StringEncoding = UnicodeStringEncoding, UTF16BigEndianStringEncoding = 0x90000100, UTF16LittleEndianStringEncoding = 0x94000100, UTF32StringEncoding = 0x8c000100, UTF32BigEndianStringEncoding = 0x98000100, UTF32LittleEndianStringEncoding = 0x9c000100 }; _NS_OPTIONS(NS::UInteger, StringCompareOptions) { CaseInsensitiveSearch = 1, LiteralSearch = 2, BackwardsSearch = 4, AnchoredSearch = 8, NumericSearch = 64, DiacriticInsensitiveSearch = 128, WidthInsensitiveSearch = 256, ForcedOrderingSearch = 512, RegularExpressionSearch = 1024 }; using unichar = unsigned short; class String : public Copying<String> { public: static String* string(); static String* string(const String* pString); static String* string(const char* pString, StringEncoding encoding); static String* alloc(); String* init(); String* init(const String* pString); String* init(const char* pString, StringEncoding encoding); String* init(void* pBytes, UInteger len, StringEncoding encoding, bool freeBuffer); unichar character(UInteger index) const; UInteger length() const; const char* cString(StringEncoding encoding) const; const char* utf8String() const; UInteger maximumLengthOfBytes(StringEncoding encoding) const; UInteger lengthOfBytes(StringEncoding encoding) const; bool isEqualToString(const String* pString) const; Range rangeOfString(const String* pString, StringCompareOptions options) const; const char* fileSystemRepresentation() const; String* stringByAppendingString(const String* pString) const; ComparisonResult caseInsensitiveCompare(const String* pString) const; }; #define MTLSTR(literal) (NS::String*)__builtin___CFStringMakeConstantString("" literal "") template <std::size_t _StringLen> [[deprecated("please use MTLSTR(str)")]] constexpr const String* MakeConstantString(const char (&str)[_StringLen]) { return reinterpret_cast<const String*>(__CFStringMakeConstantString(str)); } } _NS_INLINE NS::String* NS::String::string() { return Object::sendMessage<String*>(_NS_PRIVATE_CLS(NSString), _NS_PRIVATE_SEL(string)); } _NS_INLINE NS::String* NS::String::string(const String* pString) { return Object::sendMessage<String*>(_NS_PRIVATE_CLS(NSString), _NS_PRIVATE_SEL(stringWithString_), pString); } _NS_INLINE NS::String* NS::String::string(const char* pString, StringEncoding encoding) { return Object::sendMessage<String*>(_NS_PRIVATE_CLS(NSString), _NS_PRIVATE_SEL(stringWithCString_encoding_), pString, encoding); } _NS_INLINE NS::String* NS::String::alloc() { return Object::alloc<String>(_NS_PRIVATE_CLS(NSString)); } _NS_INLINE NS::String* NS::String::init() { return Object::init<String>(); } _NS_INLINE NS::String* NS::String::init(const String* pString) { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(initWithString_), pString); } _NS_INLINE NS::String* NS::String::init(const char* pString, StringEncoding encoding) { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(initWithCString_encoding_), pString, encoding); } _NS_INLINE NS::String* NS::String::init(void* pBytes, UInteger len, StringEncoding encoding, bool freeBuffer) { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(initWithBytesNoCopy_length_encoding_freeWhenDone_), pBytes, len, encoding, freeBuffer); } _NS_INLINE NS::unichar NS::String::character(UInteger index) const { return Object::sendMessage<unichar>(this, _NS_PRIVATE_SEL(characterAtIndex_), index); } _NS_INLINE NS::UInteger NS::String::length() const { return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(length)); } _NS_INLINE const char* NS::String::cString(StringEncoding encoding) const { return Object::sendMessage<const char*>(this, _NS_PRIVATE_SEL(cStringUsingEncoding_), encoding); } _NS_INLINE const char* NS::String::utf8String() const { return Object::sendMessage<const char*>(this, _NS_PRIVATE_SEL(UTF8String)); } _NS_INLINE NS::UInteger NS::String::maximumLengthOfBytes(StringEncoding encoding) const { return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(maximumLengthOfBytesUsingEncoding_), encoding); } _NS_INLINE NS::UInteger NS::String::lengthOfBytes(StringEncoding encoding) const { return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(lengthOfBytesUsingEncoding_), encoding); } _NS_INLINE bool NS::String::isEqualToString(const NS::String* pString) const { return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(isEqualToString_), pString); } _NS_INLINE NS::Range NS::String::rangeOfString(const NS::String* pString, NS::StringCompareOptions options) const { return Object::sendMessage<Range>(this, _NS_PRIVATE_SEL(rangeOfString_options_), pString, options); } _NS_INLINE const char* NS::String::fileSystemRepresentation() const { return Object::sendMessage<const char*>(this, _NS_PRIVATE_SEL(fileSystemRepresentation)); } _NS_INLINE NS::String* NS::String::stringByAppendingString(const String* pString) const { return Object::sendMessage<NS::String*>(this, _NS_PRIVATE_SEL(stringByAppendingString_), pString); } _NS_INLINE NS::ComparisonResult NS::String::caseInsensitiveCompare(const String* pString) const { return Object::sendMessage<NS::ComparisonResult>(this, _NS_PRIVATE_SEL(caseInsensitiveCompare_), pString); } #include <functional> namespace NS { using NotificationName = class String*; class Notification : public NS::Referencing<Notification> { public: NS::String* name() const; NS::Object* object() const; NS::Dictionary* userInfo() const; }; using ObserverBlock = void(^)(Notification*); using ObserverFunction = std::function<void(Notification*)>; class NotificationCenter : public NS::Referencing<NotificationCenter> { public: static class NotificationCenter* defaultCenter(); Object* addObserver(NotificationName name, Object* pObj, void* pQueue, ObserverBlock block); Object* addObserver(NotificationName name, Object* pObj, void* pQueue, ObserverFunction &handler); void removeObserver(Object* pObserver); }; } _NS_INLINE NS::String* NS::Notification::name() const { return Object::sendMessage<NS::String*>(this, _NS_PRIVATE_SEL(name)); } _NS_INLINE NS::Object* NS::Notification::object() const { return Object::sendMessage<NS::Object*>(this, _NS_PRIVATE_SEL(object)); } _NS_INLINE NS::Dictionary* NS::Notification::userInfo() const { return Object::sendMessage<NS::Dictionary*>(this, _NS_PRIVATE_SEL(userInfo)); } _NS_INLINE NS::NotificationCenter* NS::NotificationCenter::defaultCenter() { return NS::Object::sendMessage<NS::NotificationCenter*>(_NS_PRIVATE_CLS(NSNotificationCenter), _NS_PRIVATE_SEL(defaultCenter)); } _NS_INLINE NS::Object* NS::NotificationCenter::addObserver(NS::NotificationName name, Object* pObj, void* pQueue, NS::ObserverBlock block) { return NS::Object::sendMessage<Object*>(this, _NS_PRIVATE_SEL(addObserverName_object_queue_block_), name, pObj, pQueue, block); } _NS_INLINE NS::Object* NS::NotificationCenter::addObserver(NS::NotificationName name, Object* pObj, void* pQueue, NS::ObserverFunction &handler) { __block ObserverFunction blockFunction = handler; return addObserver(name, pObj, pQueue, ^(NS::Notification* pNotif) {blockFunction(pNotif);}); } _NS_INLINE void NS::NotificationCenter::removeObserver(Object* pObserver) { return NS::Object::sendMessage<void>(this, _NS_PRIVATE_SEL(removeObserver_), pObserver); } namespace NS { _NS_CONST(NotificationName, BundleDidLoadNotification); _NS_CONST(NotificationName, BundleResourceRequestLowDiskSpaceNotification); class String* LocalizedString(const String* pKey, const String*); class String* LocalizedStringFromTable(const String* pKey, const String* pTbl, const String*); class String* LocalizedStringFromTableInBundle(const String* pKey, const String* pTbl, const class Bundle* pBdle, const String*); class String* LocalizedStringWithDefaultValue(const String* pKey, const String* pTbl, const class Bundle* pBdle, const String* pVal, const String*); class Bundle : public Referencing<Bundle> { public: static Bundle* mainBundle(); static Bundle* bundle(const class String* pPath); static Bundle* bundle(const class URL* pURL); static Bundle* alloc(); Bundle* init(const class String* pPath); Bundle* init(const class URL* pURL); class Array* allBundles() const; class Array* allFrameworks() const; bool load(); bool unload(); bool isLoaded() const; bool preflightAndReturnError(class Error** pError) const; bool loadAndReturnError(class Error** pError); class URL* bundleURL() const; class URL* resourceURL() const; class URL* executableURL() const; class URL* URLForAuxiliaryExecutable(const class String* pExecutableName) const; class URL* privateFrameworksURL() const; class URL* sharedFrameworksURL() const; class URL* sharedSupportURL() const; class URL* builtInPlugInsURL() const; class URL* appStoreReceiptURL() const; class String* bundlePath() const; class String* resourcePath() const; class String* executablePath() const; class String* pathForAuxiliaryExecutable(const class String* pExecutableName) const; class String* privateFrameworksPath() const; class String* sharedFrameworksPath() const; class String* sharedSupportPath() const; class String* builtInPlugInsPath() const; class String* bundleIdentifier() const; class Dictionary* infoDictionary() const; class Dictionary* localizedInfoDictionary() const; class Object* objectForInfoDictionaryKey(const class String* pKey); class String* localizedString(const class String* pKey, const class String* pValue = nullptr, const class String* pTableName = nullptr) const; }; } _NS_PRIVATE_DEF_CONST(NS::NotificationName, BundleDidLoadNotification); _NS_PRIVATE_DEF_CONST(NS::NotificationName, BundleResourceRequestLowDiskSpaceNotification); _NS_INLINE NS::String* NS::LocalizedString(const String* pKey, const String*) { return Bundle::mainBundle()->localizedString(pKey, nullptr, nullptr); } _NS_INLINE NS::String* NS::LocalizedStringFromTable(const String* pKey, const String* pTbl, const String*) { return Bundle::mainBundle()->localizedString(pKey, nullptr, pTbl); } _NS_INLINE NS::String* NS::LocalizedStringFromTableInBundle(const String* pKey, const String* pTbl, const Bundle* pBdl, const String*) { return pBdl->localizedString(pKey, nullptr, pTbl); } _NS_INLINE NS::String* NS::LocalizedStringWithDefaultValue(const String* pKey, const String* pTbl, const Bundle* pBdl, const String* pVal, const String*) { return pBdl->localizedString(pKey, pVal, pTbl); } _NS_INLINE NS::Bundle* NS::Bundle::mainBundle() { return Object::sendMessage<Bundle*>(_NS_PRIVATE_CLS(NSBundle), _NS_PRIVATE_SEL(mainBundle)); } _NS_INLINE NS::Bundle* NS::Bundle::bundle(const class String* pPath) { return Object::sendMessage<Bundle*>(_NS_PRIVATE_CLS(NSBundle), _NS_PRIVATE_SEL(bundleWithPath_), pPath); } _NS_INLINE NS::Bundle* NS::Bundle::bundle(const class URL* pURL) { return Object::sendMessage<Bundle*>(_NS_PRIVATE_CLS(NSBundle), _NS_PRIVATE_SEL(bundleWithURL_), pURL); } _NS_INLINE NS::Bundle* NS::Bundle::alloc() { return Object::sendMessage<Bundle*>(_NS_PRIVATE_CLS(NSBundle), _NS_PRIVATE_SEL(alloc)); } _NS_INLINE NS::Bundle* NS::Bundle::init(const String* pPath) { return Object::sendMessage<Bundle*>(this, _NS_PRIVATE_SEL(initWithPath_), pPath); } _NS_INLINE NS::Bundle* NS::Bundle::init(const URL* pURL) { return Object::sendMessage<Bundle*>(this, _NS_PRIVATE_SEL(initWithURL_), pURL); } _NS_INLINE NS::Array* NS::Bundle::allBundles() const { return Object::sendMessage<Array*>(this, _NS_PRIVATE_SEL(allBundles)); } _NS_INLINE NS::Array* NS::Bundle::allFrameworks() const { return Object::sendMessage<Array*>(this, _NS_PRIVATE_SEL(allFrameworks)); } _NS_INLINE bool NS::Bundle::load() { return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(load)); } _NS_INLINE bool NS::Bundle::unload() { return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(unload)); } _NS_INLINE bool NS::Bundle::isLoaded() const { return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(isLoaded)); } _NS_INLINE bool NS::Bundle::preflightAndReturnError(Error** pError) const { return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(preflightAndReturnError_), pError); } _NS_INLINE bool NS::Bundle::loadAndReturnError(Error** pError) { return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(loadAndReturnError_), pError); } _NS_INLINE NS::URL* NS::Bundle::bundleURL() const { return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(bundleURL)); } _NS_INLINE NS::URL* NS::Bundle::resourceURL() const { return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(resourceURL)); } _NS_INLINE NS::URL* NS::Bundle::executableURL() const { return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(executableURL)); } _NS_INLINE NS::URL* NS::Bundle::URLForAuxiliaryExecutable(const String* pExecutableName) const { return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(URLForAuxiliaryExecutable_), pExecutableName); } _NS_INLINE NS::URL* NS::Bundle::privateFrameworksURL() const { return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(privateFrameworksURL)); } _NS_INLINE NS::URL* NS::Bundle::sharedFrameworksURL() const { return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(sharedFrameworksURL)); } _NS_INLINE NS::URL* NS::Bundle::sharedSupportURL() const { return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(sharedSupportURL)); } _NS_INLINE NS::URL* NS::Bundle::builtInPlugInsURL() const { return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(builtInPlugInsURL)); } _NS_INLINE NS::URL* NS::Bundle::appStoreReceiptURL() const { return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(appStoreReceiptURL)); } _NS_INLINE NS::String* NS::Bundle::bundlePath() const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(bundlePath)); } _NS_INLINE NS::String* NS::Bundle::resourcePath() const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(resourcePath)); } _NS_INLINE NS::String* NS::Bundle::executablePath() const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(executablePath)); } _NS_INLINE NS::String* NS::Bundle::pathForAuxiliaryExecutable(const String* pExecutableName) const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(pathForAuxiliaryExecutable_), pExecutableName); } _NS_INLINE NS::String* NS::Bundle::privateFrameworksPath() const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(privateFrameworksPath)); } _NS_INLINE NS::String* NS::Bundle::sharedFrameworksPath() const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(sharedFrameworksPath)); } _NS_INLINE NS::String* NS::Bundle::sharedSupportPath() const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(sharedSupportPath)); } _NS_INLINE NS::String* NS::Bundle::builtInPlugInsPath() const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(builtInPlugInsPath)); } _NS_INLINE NS::String* NS::Bundle::bundleIdentifier() const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(bundleIdentifier)); } _NS_INLINE NS::Dictionary* NS::Bundle::infoDictionary() const { return Object::sendMessage<Dictionary*>(this, _NS_PRIVATE_SEL(infoDictionary)); } _NS_INLINE NS::Dictionary* NS::Bundle::localizedInfoDictionary() const { return Object::sendMessage<Dictionary*>(this, _NS_PRIVATE_SEL(localizedInfoDictionary)); } _NS_INLINE NS::Object* NS::Bundle::objectForInfoDictionaryKey(const String* pKey) { return Object::sendMessage<Object*>(this, _NS_PRIVATE_SEL(objectForInfoDictionaryKey_), pKey); } _NS_INLINE NS::String* NS::Bundle::localizedString(const String* pKey, const String* pValue /* = nullptr */, const String* pTableName /* = nullptr */) const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(localizedStringForKey_value_table_), pKey, pValue, pTableName); } namespace NS { class Data : public Copying<Data> { public: void* mutableBytes() const; UInteger length() const; }; } _NS_INLINE void* NS::Data::mutableBytes() const { return Object::sendMessage<void*>(this, _NS_PRIVATE_SEL(mutableBytes)); } _NS_INLINE NS::UInteger NS::Data::length() const { return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(length)); } namespace NS { using TimeInterval = double; class Date : public Copying<Date> { public: static Date* dateWithTimeIntervalSinceNow(TimeInterval secs); }; } // NS _NS_INLINE NS::Date* NS::Date::dateWithTimeIntervalSinceNow(NS::TimeInterval secs) { return NS::Object::sendMessage<NS::Date*>(_NS_PRIVATE_CLS(NSDate), _NS_PRIVATE_SEL(dateWithTimeIntervalSinceNow_), secs); } //------------------------------------------------------------------------------------------------------------------------------------------------------------- namespace NS { using ErrorDomain = class String*; _NS_CONST(ErrorDomain, CocoaErrorDomain); _NS_CONST(ErrorDomain, POSIXErrorDomain); _NS_CONST(ErrorDomain, OSStatusErrorDomain); _NS_CONST(ErrorDomain, MachErrorDomain); using ErrorUserInfoKey = class String*; _NS_CONST(ErrorUserInfoKey, UnderlyingErrorKey); _NS_CONST(ErrorUserInfoKey, LocalizedDescriptionKey); _NS_CONST(ErrorUserInfoKey, LocalizedFailureReasonErrorKey); _NS_CONST(ErrorUserInfoKey, LocalizedRecoverySuggestionErrorKey); _NS_CONST(ErrorUserInfoKey, LocalizedRecoveryOptionsErrorKey); _NS_CONST(ErrorUserInfoKey, RecoveryAttempterErrorKey); _NS_CONST(ErrorUserInfoKey, HelpAnchorErrorKey); _NS_CONST(ErrorUserInfoKey, DebugDescriptionErrorKey); _NS_CONST(ErrorUserInfoKey, LocalizedFailureErrorKey); _NS_CONST(ErrorUserInfoKey, StringEncodingErrorKey); _NS_CONST(ErrorUserInfoKey, URLErrorKey); _NS_CONST(ErrorUserInfoKey, FilePathErrorKey); class Error : public Copying<Error> { public: static Error* error(ErrorDomain domain, Integer code, class Dictionary* pDictionary); static Error* alloc(); Error* init(); Error* init(ErrorDomain domain, Integer code, class Dictionary* pDictionary); Integer code() const; ErrorDomain domain() const; class Dictionary* userInfo() const; class String* localizedDescription() const; class Array* localizedRecoveryOptions() const; class String* localizedRecoverySuggestion() const; class String* localizedFailureReason() const; }; } _NS_PRIVATE_DEF_CONST(NS::ErrorDomain, CocoaErrorDomain); _NS_PRIVATE_DEF_CONST(NS::ErrorDomain, POSIXErrorDomain); _NS_PRIVATE_DEF_CONST(NS::ErrorDomain, OSStatusErrorDomain); _NS_PRIVATE_DEF_CONST(NS::ErrorDomain, MachErrorDomain); _NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, UnderlyingErrorKey); _NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, LocalizedDescriptionKey); _NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, LocalizedFailureReasonErrorKey); _NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, LocalizedRecoverySuggestionErrorKey); _NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, LocalizedRecoveryOptionsErrorKey); _NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, RecoveryAttempterErrorKey); _NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, HelpAnchorErrorKey); _NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, DebugDescriptionErrorKey); _NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, LocalizedFailureErrorKey); _NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, StringEncodingErrorKey); _NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, URLErrorKey); _NS_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, FilePathErrorKey); _NS_INLINE NS::Error* NS::Error::error(ErrorDomain domain, Integer code, class Dictionary* pDictionary) { return Object::sendMessage<Error*>(_NS_PRIVATE_CLS(NSError), _NS_PRIVATE_SEL(errorWithDomain_code_userInfo_), domain, code, pDictionary); } _NS_INLINE NS::Error* NS::Error::alloc() { return Object::alloc<Error>(_NS_PRIVATE_CLS(NSError)); } _NS_INLINE NS::Error* NS::Error::init() { return Object::init<Error>(); } _NS_INLINE NS::Error* NS::Error::init(ErrorDomain domain, Integer code, class Dictionary* pDictionary) { return Object::sendMessage<Error*>(this, _NS_PRIVATE_SEL(initWithDomain_code_userInfo_), domain, code, pDictionary); } _NS_INLINE NS::Integer NS::Error::code() const { return Object::sendMessage<Integer>(this, _NS_PRIVATE_SEL(code)); } _NS_INLINE NS::ErrorDomain NS::Error::domain() const { return Object::sendMessage<ErrorDomain>(this, _NS_PRIVATE_SEL(domain)); } _NS_INLINE NS::Dictionary* NS::Error::userInfo() const { return Object::sendMessage<Dictionary*>(this, _NS_PRIVATE_SEL(userInfo)); } _NS_INLINE NS::String* NS::Error::localizedDescription() const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(localizedDescription)); } _NS_INLINE NS::Array* NS::Error::localizedRecoveryOptions() const { return Object::sendMessage<Array*>(this, _NS_PRIVATE_SEL(localizedRecoveryOptions)); } _NS_INLINE NS::String* NS::Error::localizedRecoverySuggestion() const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(localizedRecoverySuggestion)); } _NS_INLINE NS::String* NS::Error::localizedFailureReason() const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(localizedFailureReason)); } namespace NS { template <class _Class, class _Base = class Object> class Locking : public _Base { public: void lock(); void unlock(); }; class Condition : public Locking<Condition> { public: static Condition* alloc(); Condition* init(); void wait(); bool waitUntilDate(Date* pLimit); void signal(); void broadcast(); }; } // NS template<class _Class, class _Base /* = NS::Object */> _NS_INLINE void NS::Locking<_Class, _Base>::lock() { NS::Object::sendMessage<void>(this, _NS_PRIVATE_SEL(lock)); } template<class _Class, class _Base /* = NS::Object */> _NS_INLINE void NS::Locking<_Class, _Base>::unlock() { NS::Object::sendMessage<void>(this, _NS_PRIVATE_SEL(unlock)); } _NS_INLINE NS::Condition* NS::Condition::alloc() { return NS::Object::alloc<NS::Condition>(_NS_PRIVATE_CLS(NSCondition)); } _NS_INLINE NS::Condition* NS::Condition::init() { return NS::Object::init<NS::Condition>(); } _NS_INLINE void NS::Condition::wait() { NS::Object::sendMessage<void>(this, _NS_PRIVATE_SEL(wait)); } _NS_INLINE bool NS::Condition::waitUntilDate(NS::Date* pLimit) { return NS::Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(waitUntilDate_), pLimit); } _NS_INLINE void NS::Condition::signal() { NS::Object::sendMessage<void>(this, _NS_PRIVATE_SEL(signal)); } _NS_INLINE void NS::Condition::broadcast() { NS::Object::sendMessage<void>(this, _NS_PRIVATE_SEL(broadcast)); } //------------------------------------------------------------------------------------------------------------------------------------------------------------- namespace NS { class Value : public Copying<Value> { public: static Value* value(const void* pValue, const char* pType); static Value* value(const void* pPointer); static Value* alloc(); Value* init(const void* pValue, const char* pType); Value* init(const class Coder* pCoder); void getValue(void* pValue, UInteger size) const; const char* objCType() const; bool isEqualToValue(Value* pValue) const; void* pointerValue() const; }; class Number : public Copying<Number, Value> { public: static Number* number(char value); static Number* number(unsigned char value); static Number* number(short value); static Number* number(unsigned short value); static Number* number(int value); static Number* number(unsigned int value); static Number* number(long value); static Number* number(unsigned long value); static Number* number(long long value); static Number* number(unsigned long long value); static Number* number(float value); static Number* number(double value); static Number* number(bool value); static Number* alloc(); Number* init(const class Coder* pCoder); Number* init(char value); Number* init(unsigned char value); Number* init(short value); Number* init(unsigned short value); Number* init(int value); Number* init(unsigned int value); Number* init(long value); Number* init(unsigned long value); Number* init(long long value); Number* init(unsigned long long value); Number* init(float value); Number* init(double value); Number* init(bool value); char charValue() const; unsigned char unsignedCharValue() const; short shortValue() const; unsigned short unsignedShortValue() const; int intValue() const; unsigned int unsignedIntValue() const; long longValue() const; unsigned long unsignedLongValue() const; long long longLongValue() const; unsigned long long unsignedLongLongValue() const; float floatValue() const; double doubleValue() const; bool boolValue() const; Integer integerValue() const; UInteger unsignedIntegerValue() const; class String* stringValue() const; ComparisonResult compare(const Number* pOtherNumber) const; bool isEqualToNumber(const Number* pNumber) const; class String* descriptionWithLocale(const Object* pLocale) const; }; } _NS_INLINE NS::Value* NS::Value::value(const void* pValue, const char* pType) { return Object::sendMessage<Value*>(_NS_PRIVATE_CLS(NSValue), _NS_PRIVATE_SEL(valueWithBytes_objCType_), pValue, pType); } _NS_INLINE NS::Value* NS::Value::value(const void* pPointer) { return Object::sendMessage<Value*>(_NS_PRIVATE_CLS(NSValue), _NS_PRIVATE_SEL(valueWithPointer_), pPointer); } _NS_INLINE NS::Value* NS::Value::alloc() { return NS::Object::alloc<Value>(_NS_PRIVATE_CLS(NSValue)); } _NS_INLINE NS::Value* NS::Value::init(const void* pValue, const char* pType) { return Object::sendMessage<Value*>(this, _NS_PRIVATE_SEL(initWithBytes_objCType_), pValue, pType); } _NS_INLINE NS::Value* NS::Value::init(const class Coder* pCoder) { return Object::sendMessage<Value*>(this, _NS_PRIVATE_SEL(initWithCoder_), pCoder); } _NS_INLINE void NS::Value::getValue(void* pValue, UInteger size) const { Object::sendMessage<void>(this, _NS_PRIVATE_SEL(getValue_size_), pValue, size); } _NS_INLINE const char* NS::Value::objCType() const { return Object::sendMessage<const char*>(this, _NS_PRIVATE_SEL(objCType)); } _NS_INLINE bool NS::Value::isEqualToValue(Value* pValue) const { return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(isEqualToValue_), pValue); } _NS_INLINE void* NS::Value::pointerValue() const { return Object::sendMessage<void*>(this, _NS_PRIVATE_SEL(pointerValue)); } _NS_INLINE NS::Number* NS::Number::number(char value) { return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithChar_), value); } _NS_INLINE NS::Number* NS::Number::number(unsigned char value) { return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithUnsignedChar_), value); } _NS_INLINE NS::Number* NS::Number::number(short value) { return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithShort_), value); } _NS_INLINE NS::Number* NS::Number::number(unsigned short value) { return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithUnsignedShort_), value); } _NS_INLINE NS::Number* NS::Number::number(int value) { return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithInt_), value); } _NS_INLINE NS::Number* NS::Number::number(unsigned int value) { return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithUnsignedInt_), value); } _NS_INLINE NS::Number* NS::Number::number(long value) { return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithLong_), value); } _NS_INLINE NS::Number* NS::Number::number(unsigned long value) { return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithUnsignedLong_), value); } _NS_INLINE NS::Number* NS::Number::number(long long value) { return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithLongLong_), value); } _NS_INLINE NS::Number* NS::Number::number(unsigned long long value) { return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithUnsignedLongLong_), value); } _NS_INLINE NS::Number* NS::Number::number(float value) { return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithFloat_), value); } _NS_INLINE NS::Number* NS::Number::number(double value) { return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithDouble_), value); } _NS_INLINE NS::Number* NS::Number::number(bool value) { return Object::sendMessage<Number*>(_NS_PRIVATE_CLS(NSNumber), _NS_PRIVATE_SEL(numberWithBool_), value); } _NS_INLINE NS::Number* NS::Number::alloc() { return NS::Object::alloc<Number>(_NS_PRIVATE_CLS(NSNumber)); } _NS_INLINE NS::Number* NS::Number::init(const Coder* pCoder) { return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithCoder_), pCoder); } _NS_INLINE NS::Number* NS::Number::init(char value) { return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithChar_), value); } _NS_INLINE NS::Number* NS::Number::init(unsigned char value) { return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithUnsignedChar_), value); } _NS_INLINE NS::Number* NS::Number::init(short value) { return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithShort_), value); } _NS_INLINE NS::Number* NS::Number::init(unsigned short value) { return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithUnsignedShort_), value); } _NS_INLINE NS::Number* NS::Number::init(int value) { return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithInt_), value); } _NS_INLINE NS::Number* NS::Number::init(unsigned int value) { return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithUnsignedInt_), value); } _NS_INLINE NS::Number* NS::Number::init(long value) { return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithLong_), value); } _NS_INLINE NS::Number* NS::Number::init(unsigned long value) { return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithUnsignedLong_), value); } _NS_INLINE NS::Number* NS::Number::init(long long value) { return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithLongLong_), value); } _NS_INLINE NS::Number* NS::Number::init(unsigned long long value) { return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithUnsignedLongLong_), value); } _NS_INLINE NS::Number* NS::Number::init(float value) { return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithFloat_), value); } _NS_INLINE NS::Number* NS::Number::init(double value) { return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithDouble_), value); } _NS_INLINE NS::Number* NS::Number::init(bool value) { return Object::sendMessage<Number*>(this, _NS_PRIVATE_SEL(initWithBool_), value); } _NS_INLINE char NS::Number::charValue() const { return Object::sendMessage<char>(this, _NS_PRIVATE_SEL(charValue)); } _NS_INLINE unsigned char NS::Number::unsignedCharValue() const { return Object::sendMessage<unsigned char>(this, _NS_PRIVATE_SEL(unsignedCharValue)); } _NS_INLINE short NS::Number::shortValue() const { return Object::sendMessage<short>(this, _NS_PRIVATE_SEL(shortValue)); } _NS_INLINE unsigned short NS::Number::unsignedShortValue() const { return Object::sendMessage<unsigned short>(this, _NS_PRIVATE_SEL(unsignedShortValue)); } _NS_INLINE int NS::Number::intValue() const { return Object::sendMessage<int>(this, _NS_PRIVATE_SEL(intValue)); } _NS_INLINE unsigned int NS::Number::unsignedIntValue() const { return Object::sendMessage<unsigned int>(this, _NS_PRIVATE_SEL(unsignedIntValue)); } _NS_INLINE long NS::Number::longValue() const { return Object::sendMessage<long>(this, _NS_PRIVATE_SEL(longValue)); } _NS_INLINE unsigned long NS::Number::unsignedLongValue() const { return Object::sendMessage<unsigned long>(this, _NS_PRIVATE_SEL(unsignedLongValue)); } _NS_INLINE long long NS::Number::longLongValue() const { return Object::sendMessage<long long>(this, _NS_PRIVATE_SEL(longLongValue)); } _NS_INLINE unsigned long long NS::Number::unsignedLongLongValue() const { return Object::sendMessage<unsigned long long>(this, _NS_PRIVATE_SEL(unsignedLongLongValue)); } _NS_INLINE float NS::Number::floatValue() const { return Object::sendMessage<float>(this, _NS_PRIVATE_SEL(floatValue)); } _NS_INLINE double NS::Number::doubleValue() const { return Object::sendMessage<double>(this, _NS_PRIVATE_SEL(doubleValue)); } _NS_INLINE bool NS::Number::boolValue() const { return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(boolValue)); } _NS_INLINE NS::Integer NS::Number::integerValue() const { return Object::sendMessage<Integer>(this, _NS_PRIVATE_SEL(integerValue)); } _NS_INLINE NS::UInteger NS::Number::unsignedIntegerValue() const { return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(unsignedIntegerValue)); } _NS_INLINE NS::String* NS::Number::stringValue() const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(stringValue)); } _NS_INLINE NS::ComparisonResult NS::Number::compare(const Number* pOtherNumber) const { return Object::sendMessage<ComparisonResult>(this, _NS_PRIVATE_SEL(compare_), pOtherNumber); } _NS_INLINE bool NS::Number::isEqualToNumber(const Number* pNumber) const { return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(isEqualToNumber_), pNumber); } _NS_INLINE NS::String* NS::Number::descriptionWithLocale(const Object* pLocale) const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(descriptionWithLocale_), pLocale); } #include <functional> namespace NS { _NS_CONST(NotificationName, ProcessInfoThermalStateDidChangeNotification); _NS_CONST(NotificationName, ProcessInfoPowerStateDidChangeNotification); _NS_ENUM(NS::Integer, ProcessInfoThermalState) { ProcessInfoThermalStateNominal = 0, ProcessInfoThermalStateFair = 1, ProcessInfoThermalStateSerious = 2, ProcessInfoThermalStateCritical = 3 }; _NS_OPTIONS(std::uint64_t, ActivityOptions) { ActivityIdleDisplaySleepDisabled = (1ULL << 40), ActivityIdleSystemSleepDisabled = (1ULL << 20), ActivitySuddenTerminationDisabled = (1ULL << 14), ActivityAutomaticTerminationDisabled = (1ULL << 15), ActivityUserInitiated = (0x00FFFFFFULL | ActivityIdleSystemSleepDisabled), ActivityUserInitiatedAllowingIdleSystemSleep = (ActivityUserInitiated & ~ActivityIdleSystemSleepDisabled), ActivityBackground = 0x000000FFULL, ActivityLatencyCritical = 0xFF00000000ULL, }; class ProcessInfo : public Referencing<ProcessInfo> { public: static ProcessInfo* processInfo(); class Array* arguments() const; class Dictionary* environment() const; class String* hostName() const; class String* processName() const; void setProcessName(const String* pString); int processIdentifier() const; class String* globallyUniqueString() const; class String* userName() const; class String* fullUserName() const; UInteger operatingSystem() const; OperatingSystemVersion operatingSystemVersion() const; class String* operatingSystemVersionString() const; bool isOperatingSystemAtLeastVersion(OperatingSystemVersion version) const; UInteger processorCount() const; UInteger activeProcessorCount() const; unsigned long long physicalMemory() const; TimeInterval systemUptime() const; void disableSuddenTermination(); void enableSuddenTermination(); void disableAutomaticTermination(const class String* pReason); void enableAutomaticTermination(const class String* pReason); bool automaticTerminationSupportEnabled() const; void setAutomaticTerminationSupportEnabled(bool enabled); class Object* beginActivity(ActivityOptions options, const class String* pReason); void endActivity(class Object* pActivity); void performActivity(ActivityOptions options, const class String* pReason, void (^block)(void)); void performActivity(ActivityOptions options, const class String* pReason, const std::function<void()>& func); void performExpiringActivity(const class String* pReason, void (^block)(bool expired)); void performExpiringActivity(const class String* pReason, const std::function<void(bool expired)>& func); ProcessInfoThermalState thermalState() const; bool isLowPowerModeEnabled() const; bool isiOSAppOnMac() const; bool isMacCatalystApp() const; }; } _NS_PRIVATE_DEF_CONST(NS::NotificationName, ProcessInfoThermalStateDidChangeNotification); _NS_PRIVATE_DEF_CONST(NS::NotificationName, ProcessInfoPowerStateDidChangeNotification); _NS_INLINE NS::ProcessInfo* NS::ProcessInfo::processInfo() { return Object::sendMessage<ProcessInfo*>(_NS_PRIVATE_CLS(NSProcessInfo), _NS_PRIVATE_SEL(processInfo)); } _NS_INLINE NS::Array* NS::ProcessInfo::arguments() const { return Object::sendMessage<Array*>(this, _NS_PRIVATE_SEL(arguments)); } _NS_INLINE NS::Dictionary* NS::ProcessInfo::environment() const { return Object::sendMessage<Dictionary*>(this, _NS_PRIVATE_SEL(environment)); } _NS_INLINE NS::String* NS::ProcessInfo::hostName() const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(hostName)); } _NS_INLINE NS::String* NS::ProcessInfo::processName() const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(processName)); } _NS_INLINE void NS::ProcessInfo::setProcessName(const String* pString) { Object::sendMessage<void>(this, _NS_PRIVATE_SEL(setProcessName_), pString); } _NS_INLINE int NS::ProcessInfo::processIdentifier() const { return Object::sendMessage<int>(this, _NS_PRIVATE_SEL(processIdentifier)); } _NS_INLINE NS::String* NS::ProcessInfo::globallyUniqueString() const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(globallyUniqueString)); } _NS_INLINE NS::String* NS::ProcessInfo::userName() const { return Object::sendMessageSafe<String*>(this, _NS_PRIVATE_SEL(userName)); } _NS_INLINE NS::String* NS::ProcessInfo::fullUserName() const { return Object::sendMessageSafe<String*>(this, _NS_PRIVATE_SEL(fullUserName)); } _NS_INLINE NS::UInteger NS::ProcessInfo::operatingSystem() const { return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(operatingSystem)); } _NS_INLINE NS::OperatingSystemVersion NS::ProcessInfo::operatingSystemVersion() const { return Object::sendMessage<OperatingSystemVersion>(this, _NS_PRIVATE_SEL(operatingSystemVersion)); } _NS_INLINE NS::String* NS::ProcessInfo::operatingSystemVersionString() const { return Object::sendMessage<String*>(this, _NS_PRIVATE_SEL(operatingSystemVersionString)); } _NS_INLINE bool NS::ProcessInfo::isOperatingSystemAtLeastVersion(OperatingSystemVersion version) const { return Object::sendMessage<bool>(this, _NS_PRIVATE_SEL(isOperatingSystemAtLeastVersion_), version); } _NS_INLINE NS::UInteger NS::ProcessInfo::processorCount() const { return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(processorCount)); } _NS_INLINE NS::UInteger NS::ProcessInfo::activeProcessorCount() const { return Object::sendMessage<UInteger>(this, _NS_PRIVATE_SEL(activeProcessorCount)); } _NS_INLINE unsigned long long NS::ProcessInfo::physicalMemory() const { return Object::sendMessage<unsigned long long>(this, _NS_PRIVATE_SEL(physicalMemory)); } _NS_INLINE NS::TimeInterval NS::ProcessInfo::systemUptime() const { return Object::sendMessage<TimeInterval>(this, _NS_PRIVATE_SEL(systemUptime)); } _NS_INLINE void NS::ProcessInfo::disableSuddenTermination() { Object::sendMessageSafe<void>(this, _NS_PRIVATE_SEL(disableSuddenTermination)); } _NS_INLINE void NS::ProcessInfo::enableSuddenTermination() { Object::sendMessageSafe<void>(this, _NS_PRIVATE_SEL(enableSuddenTermination)); } _NS_INLINE void NS::ProcessInfo::disableAutomaticTermination(const String* pReason) { Object::sendMessageSafe<void>(this, _NS_PRIVATE_SEL(disableAutomaticTermination_), pReason); } _NS_INLINE void NS::ProcessInfo::enableAutomaticTermination(const String* pReason) { Object::sendMessageSafe<void>(this, _NS_PRIVATE_SEL(enableAutomaticTermination_), pReason); } _NS_INLINE bool NS::ProcessInfo::automaticTerminationSupportEnabled() const { return Object::sendMessageSafe<bool>(this, _NS_PRIVATE_SEL(automaticTerminationSupportEnabled)); } _NS_INLINE void NS::ProcessInfo::setAutomaticTerminationSupportEnabled(bool enabled) { Object::sendMessageSafe<void>(this, _NS_PRIVATE_SEL(setAutomaticTerminationSupportEnabled_), enabled); } _NS_INLINE NS::Object* NS::ProcessInfo::beginActivity(ActivityOptions options, const String* pReason) { return Object::sendMessage<Object*>(this, _NS_PRIVATE_SEL(beginActivityWithOptions_reason_), options, pReason); } _NS_INLINE void NS::ProcessInfo::endActivity(Object* pActivity) { Object::sendMessage<void>(this, _NS_PRIVATE_SEL(endActivity_), pActivity); } _NS_INLINE void NS::ProcessInfo::performActivity(ActivityOptions options, const String* pReason, void (^block)(void)) { Object::sendMessage<void>(this, _NS_PRIVATE_SEL(performActivityWithOptions_reason_usingBlock_), options, pReason, block); } _NS_INLINE void NS::ProcessInfo::performActivity(ActivityOptions options, const String* pReason, const std::function<void()>& function) { __block std::function<void()> blockFunction = function; performActivity(options, pReason, ^() { blockFunction(); }); } _NS_INLINE void NS::ProcessInfo::performExpiringActivity(const String* pReason, void (^block)(bool expired)) { Object::sendMessageSafe<void>(this, _NS_PRIVATE_SEL(performExpiringActivityWithReason_usingBlock_), pReason, block); } _NS_INLINE void NS::ProcessInfo::performExpiringActivity(const String* pReason, const std::function<void(bool expired)>& function) { __block std::function<void(bool expired)> blockFunction = function; performExpiringActivity(pReason, ^(bool expired) { blockFunction(expired); }); } _NS_INLINE NS::ProcessInfoThermalState NS::ProcessInfo::thermalState() const { return Object::sendMessage<ProcessInfoThermalState>(this, _NS_PRIVATE_SEL(thermalState)); } _NS_INLINE bool NS::ProcessInfo::isLowPowerModeEnabled() const { return Object::sendMessageSafe<bool>(this, _NS_PRIVATE_SEL(isLowPowerModeEnabled)); } _NS_INLINE bool NS::ProcessInfo::isiOSAppOnMac() const { return Object::sendMessageSafe<bool>(this, _NS_PRIVATE_SEL(isiOSAppOnMac)); } _NS_INLINE bool NS::ProcessInfo::isMacCatalystApp() const { return Object::sendMessageSafe<bool>(this, _NS_PRIVATE_SEL(isMacCatalystApp)); } /*****Immutable Set*******/ namespace NS { class Set : public NS::Copying <Set> { public: UInteger count() const; Enumerator<Object>* objectEnumerator() const; static Set* alloc(); Set* init(); Set* init(const Object* const* pObjects, UInteger count); Set* init(const class Coder* pCoder); }; } _NS_INLINE NS::UInteger NS::Set::count() const { return NS::Object::sendMessage<NS::UInteger>(this, _NS_PRIVATE_SEL(count)); } _NS_INLINE NS::Enumerator<NS::Object>* NS::Set::objectEnumerator() const { return NS::Object::sendMessage<Enumerator<NS::Object>*>(this, _NS_PRIVATE_SEL(objectEnumerator)); } _NS_INLINE NS::Set* NS::Set::alloc() { return NS::Object::alloc<Set>(_NS_PRIVATE_CLS(NSSet)); } _NS_INLINE NS::Set* NS::Set::init() { return NS::Object::init<Set>(); } _NS_INLINE NS::Set* NS::Set::init(const Object* const* pObjects, NS::UInteger count) { return NS::Object::sendMessage<Set*>(this, _NS_PRIVATE_SEL(initWithObjects_count_), pObjects, count); } _NS_INLINE NS::Set* NS::Set::init(const class Coder* pCoder) { return Object::sendMessage<Set*>(this, _NS_PRIVATE_SEL(initWithCoder_), pCoder); } #pragma once namespace NS { template <class _Class> class SharedPtr { public: /** * Create a new null pointer. */ SharedPtr(); /** * Destroy this SharedPtr, decreasing the reference count. */ ~SharedPtr(); /** * SharedPtr copy constructor. */ SharedPtr(const SharedPtr<_Class>& other) noexcept; /** * Construction from another pointee type. */ template <class _OtherClass> SharedPtr(const SharedPtr<_OtherClass>& other, typename std::enable_if_t<std::is_convertible_v<_OtherClass *, _Class *>> * = nullptr) noexcept; /** * SharedPtr move constructor. */ SharedPtr(SharedPtr<_Class>&& other) noexcept; /** * Move from another pointee type. */ template <class _OtherClass> SharedPtr(SharedPtr<_OtherClass>&& other, typename std::enable_if_t<std::is_convertible_v<_OtherClass *, _Class *>> * = nullptr) noexcept; /** * Copy assignment operator. * Copying increases reference count. Only releases previous pointee if objects are different. */ SharedPtr& operator=(const SharedPtr<_Class>& other); /** * Copy-assignment from different pointee. * Copying increases reference count. Only releases previous pointee if objects are different. */ template <class _OtherClass> typename std::enable_if_t<std::is_convertible_v<_OtherClass *, _Class *>, SharedPtr &> operator=(const SharedPtr<_OtherClass>& other); /** * Move assignment operator. * Move without affecting reference counts, unless pointees are equal. Moved-from object is reset to nullptr. */ SharedPtr& operator=(SharedPtr<_Class>&& other); /** * Move-asignment from different pointee. * Move without affecting reference counts, unless pointees are equal. Moved-from object is reset to nullptr. */ template <class _OtherClass> typename std::enable_if_t<std::is_convertible_v<_OtherClass *, _Class *>, SharedPtr &> operator=(SharedPtr<_OtherClass>&& other); /** * Access raw pointee. * @warning Avoid wrapping the returned value again, as it may lead double frees unless this object becomes detached. */ _Class* get() const; /** * Call operations directly on the pointee. */ _Class* operator->() const; /** * Implicit cast to bool. */ explicit operator bool() const; /** * Reset this SharedPtr to null, decreasing the reference count. */ void reset(); /** * Detach the SharedPtr from the pointee, without decreasing the reference count. */ void detach(); template <class _OtherClass> friend SharedPtr<_OtherClass> RetainPtr(_OtherClass* ptr); template <class _OtherClass> friend SharedPtr<_OtherClass> TransferPtr(_OtherClass* ptr); private: _Class* m_pObject; }; /** * Create a SharedPtr by retaining an existing raw pointer. * Increases the reference count of the passed-in object. * If the passed-in object was in an AutoreleasePool, it will be removed from it. */ template <class _Class> _NS_INLINE NS::SharedPtr<_Class> RetainPtr(_Class* pObject) { NS::SharedPtr<_Class> ret; ret.m_pObject = pObject->retain(); return ret; } /* * Create a SharedPtr by transfering the ownership of an existing raw pointer to SharedPtr. * Does not increase the reference count of the passed-in pointer, it is assumed to be >= 1. * This method does not remove objects from an AutoreleasePool. */ template <class _Class> _NS_INLINE NS::SharedPtr<_Class> TransferPtr(_Class* pObject) { NS::SharedPtr<_Class> ret; ret.m_pObject = pObject; return ret; } } template <class _Class> _NS_INLINE NS::SharedPtr<_Class>::SharedPtr() : m_pObject(nullptr) { } template <class _Class> _NS_INLINE NS::SharedPtr<_Class>::~SharedPtr<_Class>() { if (m_pObject) { m_pObject->release(); } } template <class _Class> _NS_INLINE NS::SharedPtr<_Class>::SharedPtr(const NS::SharedPtr<_Class>& other) noexcept : m_pObject(other.m_pObject->retain()) { } template <class _Class> template <class _OtherClass> _NS_INLINE NS::SharedPtr<_Class>::SharedPtr(const NS::SharedPtr<_OtherClass>& other, typename std::enable_if_t<std::is_convertible_v<_OtherClass *, _Class *>> *) noexcept : m_pObject(reinterpret_cast<_Class*>(other.get()->retain())) { } template <class _Class> _NS_INLINE NS::SharedPtr<_Class>::SharedPtr(NS::SharedPtr<_Class>&& other) noexcept : m_pObject(other.m_pObject) { other.m_pObject = nullptr; } template <class _Class> template <class _OtherClass> _NS_INLINE NS::SharedPtr<_Class>::SharedPtr(NS::SharedPtr<_OtherClass>&& other, typename std::enable_if_t<std::is_convertible_v<_OtherClass *, _Class *>> *) noexcept : m_pObject(reinterpret_cast<_Class*>(other.get())) { other.detach(); } template <class _Class> _NS_INLINE _Class* NS::SharedPtr<_Class>::get() const { return m_pObject; } template <class _Class> _NS_INLINE _Class* NS::SharedPtr<_Class>::operator->() const { return m_pObject; } template <class _Class> _NS_INLINE NS::SharedPtr<_Class>::operator bool() const { return nullptr != m_pObject; } template <class _Class> _NS_INLINE void NS::SharedPtr<_Class>::reset() { m_pObject->release(); m_pObject = nullptr; } template <class _Class> _NS_INLINE void NS::SharedPtr<_Class>::detach() { m_pObject = nullptr; } template <class _Class> _NS_INLINE NS::SharedPtr<_Class>& NS::SharedPtr<_Class>::operator=(const SharedPtr<_Class>& other) { if (m_pObject != other.m_pObject) { if (m_pObject) { m_pObject->release(); } m_pObject = other.m_pObject->retain(); } return *this; } template <class _Class> template <class _OtherClass> typename std::enable_if_t<std::is_convertible_v<_OtherClass *, _Class *>, NS::SharedPtr<_Class> &> _NS_INLINE NS::SharedPtr<_Class>::operator=(const SharedPtr<_OtherClass>& other) { if (m_pObject != other.get()) { if (m_pObject) { m_pObject->release(); } m_pObject = reinterpret_cast<_Class*>(other.get()->retain()); } return *this; } template <class _Class> _NS_INLINE NS::SharedPtr<_Class>& NS::SharedPtr<_Class>::operator=(SharedPtr<_Class>&& other) { if (m_pObject != other.m_pObject) { if (m_pObject) { m_pObject->release(); } m_pObject = other.m_pObject; } else { m_pObject = other.m_pObject; other.m_pObject->release(); } other.m_pObject = nullptr; return *this; } template <class _Class> template <class _OtherClass> typename std::enable_if_t<std::is_convertible_v<_OtherClass *, _Class *>, NS::SharedPtr<_Class> &> _NS_INLINE NS::SharedPtr<_Class>::operator=(SharedPtr<_OtherClass>&& other) { if (m_pObject != other.get()) { if (m_pObject) { m_pObject->release(); } m_pObject = reinterpret_cast<_Class*>(other.get()); other.detach(); } else { m_pObject = other.get(); other.reset(); } return *this; } template <class _ClassLhs, class _ClassRhs> _NS_INLINE bool operator==(const NS::SharedPtr<_ClassLhs>& lhs, const NS::SharedPtr<_ClassRhs>& rhs) { return lhs.get() == rhs.get(); } template <class _ClassLhs, class _ClassRhs> _NS_INLINE bool operator!=(const NS::SharedPtr<_ClassLhs>& lhs, const NS::SharedPtr<_ClassRhs>& rhs) { return lhs.get() != rhs.get(); } namespace NS { class URL : public Copying<URL> { public: static URL* fileURLWithPath(const class String* pPath); static URL* alloc(); URL* init(); URL* init(const class String* pString); URL* initFileURLWithPath(const class String* pPath); const char* fileSystemRepresentation() const; }; } _NS_INLINE NS::URL* NS::URL::fileURLWithPath(const String* pPath) { return Object::sendMessage<URL*>(_NS_PRIVATE_CLS(NSURL), _NS_PRIVATE_SEL(fileURLWithPath_), pPath); } _NS_INLINE NS::URL* NS::URL::alloc() { return Object::alloc<URL>(_NS_PRIVATE_CLS(NSURL)); } _NS_INLINE NS::URL* NS::URL::init() { return Object::init<URL>(); } _NS_INLINE NS::URL* NS::URL::init(const String* pString) { return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(initWithString_), pString); } _NS_INLINE NS::URL* NS::URL::initFileURLWithPath(const String* pPath) { return Object::sendMessage<URL*>(this, _NS_PRIVATE_SEL(initFileURLWithPath_), pPath); } _NS_INLINE const char* NS::URL::fileSystemRepresentation() const { return Object::sendMessage<const char*>(this, _NS_PRIVATE_SEL(fileSystemRepresentation)); } #pragma once #define _MTL_EXPORT _NS_EXPORT #define _MTL_EXTERN _NS_EXTERN #define _MTL_INLINE _NS_INLINE #define _MTL_PACKED _NS_PACKED #define _MTL_CONST(type, name) _NS_CONST(type, name) #define _MTL_ENUM(type, name) _NS_ENUM(type, name) #define _MTL_OPTIONS(type, name) _NS_OPTIONS(type, name) #define _MTL_VALIDATE_SIZE(ns, name) _NS_VALIDATE_SIZE(ns, name) #define _MTL_VALIDATE_ENUM(ns, name) _NS_VALIDATE_ENUM(ns, name) #pragma once #include <objc/runtime.h> #define _MTL_PRIVATE_CLS(symbol) (Private::Class::s_k##symbol) #define _MTL_PRIVATE_SEL(accessor) (Private::Selector::s_k##accessor) #if defined(MTL_PRIVATE_IMPLEMENTATION) #ifdef METALCPP_SYMBOL_VISIBILITY_HIDDEN #define _MTL_PRIVATE_VISIBILITY __attribute__((visibility("hidden"))) #else #define _MTL_PRIVATE_VISIBILITY __attribute__((visibility("default"))) #endif // METALCPP_SYMBOL_VISIBILITY_HIDDEN #define _MTL_PRIVATE_IMPORT __attribute__((weak_import)) #ifdef __OBJC__ #define _MTL_PRIVATE_OBJC_LOOKUP_CLASS(symbol) ((__bridge void*)objc_lookUpClass(#symbol)) #define _MTL_PRIVATE_OBJC_GET_PROTOCOL(symbol) ((__bridge void*)objc_getProtocol(#symbol)) #else #define _MTL_PRIVATE_OBJC_LOOKUP_CLASS(symbol) objc_lookUpClass(#symbol) #define _MTL_PRIVATE_OBJC_GET_PROTOCOL(symbol) objc_getProtocol(#symbol) #endif // __OBJC__ #define _MTL_PRIVATE_DEF_CLS(symbol) void* s_k##symbol _MTL_PRIVATE_VISIBILITY = _MTL_PRIVATE_OBJC_LOOKUP_CLASS(symbol) #define _MTL_PRIVATE_DEF_PRO(symbol) void* s_k##symbol _MTL_PRIVATE_VISIBILITY = _MTL_PRIVATE_OBJC_GET_PROTOCOL(symbol) #define _MTL_PRIVATE_DEF_SEL(accessor, symbol) SEL s_k##accessor _MTL_PRIVATE_VISIBILITY = sel_registerName(symbol) #include <dlfcn.h> #define MTL_DEF_FUNC( name, signature ) \ using Fn##name = signature; \ Fn##name name = reinterpret_cast< Fn##name >( dlsym( RTLD_DEFAULT, #name ) ) namespace MTL::Private { template <typename _Type> inline _Type const LoadSymbol(const char* pSymbol) { const _Type* pAddress = static_cast<_Type*>(dlsym(RTLD_DEFAULT, pSymbol)); return pAddress ? *pAddress : nullptr; } } // MTL::Private #if defined(__MAC_10_16) || defined(__MAC_11_0) || defined(__MAC_12_0) || defined(__MAC_13_0) || defined(__MAC_14_0) || defined(__IPHONE_14_0) || defined(__IPHONE_15_0) || defined(__IPHONE_16_0) || defined(__IPHONE_17_0) || defined(__TVOS_14_0) || defined(__TVOS_15_0) || defined(__TVOS_16_0) || defined(__TVOS_17_0) #define _MTL_PRIVATE_DEF_STR(type, symbol) \ _MTL_EXTERN type const MTL##symbol _MTL_PRIVATE_IMPORT; \ type const MTL::symbol = (nullptr != &MTL##symbol) ? MTL##symbol : nullptr #define _MTL_PRIVATE_DEF_CONST(type, symbol) \ _MTL_EXTERN type const MTL##symbol _MTL_PRIVATE_IMPORT; \ type const MTL::symbol = (nullptr != &MTL##symbol) ? MTL##symbol : nullptr #define _MTL_PRIVATE_DEF_WEAK_CONST(type, symbol) \ _MTL_EXTERN type const MTL##symbol; \ type const MTL::symbol = Private::LoadSymbol<type>("MTL" #symbol) #else #define _MTL_PRIVATE_DEF_STR(type, symbol) \ _MTL_EXTERN type const MTL##symbol; \ type const MTL::symbol = Private::LoadSymbol<type>("MTL" #symbol) #define _MTL_PRIVATE_DEF_CONST(type, symbol) \ _MTL_EXTERN type const MTL##symbol; \ type const MTL::symbol = Private::LoadSymbol<type>("MTL" #symbol) #define _MTL_PRIVATE_DEF_WEAK_CONST(type, symbol) _MTL_PRIVATE_DEF_CONST(type, symbol) #endif // defined(__MAC_10_16) || defined(__MAC_11_0) || defined(__MAC_12_0) || defined(__MAC_13_0) || defined(__MAC_14_0) || defined(__IPHONE_14_0) || defined(__IPHONE_15_0) || defined(__IPHONE_16_0) || defined(__IPHONE_17_0) || defined(__TVOS_14_0) || defined(__TVOS_15_0) || defined(__TVOS_16_0) || defined(__TVOS_17_0) #else #define _MTL_PRIVATE_DEF_CLS(symbol) extern void* s_k##symbol #define _MTL_PRIVATE_DEF_PRO(symbol) extern void* s_k##symbol #define _MTL_PRIVATE_DEF_SEL(accessor, symbol) extern SEL s_k##accessor #define _MTL_PRIVATE_DEF_STR(type, symbol) extern type const MTL::symbol #define _MTL_PRIVATE_DEF_CONST(type, symbol) extern type const MTL::symbol #define _MTL_PRIVATE_DEF_WEAK_CONST(type, symbol) extern type const MTL::symbol #endif // MTL_PRIVATE_IMPLEMENTATION namespace MTL { namespace Private { namespace Class { } // Class } // Private } // MTL namespace MTL { namespace Private { namespace Protocol { } // Protocol } // Private } // MTL namespace MTL { namespace Private { namespace Selector { _MTL_PRIVATE_DEF_SEL(beginScope, "beginScope"); _MTL_PRIVATE_DEF_SEL(endScope, "endScope"); } // Class } // Private } // MTL namespace MTL::Private::Class { _MTL_PRIVATE_DEF_CLS(MTLAccelerationStructureBoundingBoxGeometryDescriptor); _MTL_PRIVATE_DEF_CLS(MTLAccelerationStructureCurveGeometryDescriptor); _MTL_PRIVATE_DEF_CLS(MTLAccelerationStructureDescriptor); _MTL_PRIVATE_DEF_CLS(MTLAccelerationStructureGeometryDescriptor); _MTL_PRIVATE_DEF_CLS(MTLAccelerationStructureMotionBoundingBoxGeometryDescriptor); _MTL_PRIVATE_DEF_CLS(MTLAccelerationStructureMotionCurveGeometryDescriptor); _MTL_PRIVATE_DEF_CLS(MTLAccelerationStructureMotionTriangleGeometryDescriptor); _MTL_PRIVATE_DEF_CLS(MTLAccelerationStructurePassDescriptor); _MTL_PRIVATE_DEF_CLS(MTLAccelerationStructurePassSampleBufferAttachmentDescriptor); _MTL_PRIVATE_DEF_CLS(MTLAccelerationStructurePassSampleBufferAttachmentDescriptorArray); _MTL_PRIVATE_DEF_CLS(MTLAccelerationStructureTriangleGeometryDescriptor); _MTL_PRIVATE_DEF_CLS(MTLArchitecture); _MTL_PRIVATE_DEF_CLS(MTLArgument); _MTL_PRIVATE_DEF_CLS(MTLArgumentDescriptor); _MTL_PRIVATE_DEF_CLS(MTLArrayType); _MTL_PRIVATE_DEF_CLS(MTLAttribute); _MTL_PRIVATE_DEF_CLS(MTLAttributeDescriptor); _MTL_PRIVATE_DEF_CLS(MTLAttributeDescriptorArray); _MTL_PRIVATE_DEF_CLS(MTLBinaryArchiveDescriptor); _MTL_PRIVATE_DEF_CLS(MTLBlitPassDescriptor); _MTL_PRIVATE_DEF_CLS(MTLBlitPassSampleBufferAttachmentDescriptor); _MTL_PRIVATE_DEF_CLS(MTLBlitPassSampleBufferAttachmentDescriptorArray); _MTL_PRIVATE_DEF_CLS(MTLBufferLayoutDescriptor); _MTL_PRIVATE_DEF_CLS(MTLBufferLayoutDescriptorArray); _MTL_PRIVATE_DEF_CLS(MTLCaptureDescriptor); _MTL_PRIVATE_DEF_CLS(MTLCaptureManager); _MTL_PRIVATE_DEF_CLS(MTLCommandBufferDescriptor); _MTL_PRIVATE_DEF_CLS(MTLCompileOptions); _MTL_PRIVATE_DEF_CLS(MTLComputePassDescriptor); _MTL_PRIVATE_DEF_CLS(MTLComputePassSampleBufferAttachmentDescriptor); _MTL_PRIVATE_DEF_CLS(MTLComputePassSampleBufferAttachmentDescriptorArray); _MTL_PRIVATE_DEF_CLS(MTLComputePipelineDescriptor); _MTL_PRIVATE_DEF_CLS(MTLComputePipelineReflection); _MTL_PRIVATE_DEF_CLS(MTLCounterSampleBufferDescriptor); _MTL_PRIVATE_DEF_CLS(MTLDepthStencilDescriptor); _MTL_PRIVATE_DEF_CLS(MTLFunctionConstant); _MTL_PRIVATE_DEF_CLS(MTLFunctionConstantValues); _MTL_PRIVATE_DEF_CLS(MTLFunctionDescriptor); _MTL_PRIVATE_DEF_CLS(MTLFunctionStitchingAttributeAlwaysInline); _MTL_PRIVATE_DEF_CLS(MTLFunctionStitchingFunctionNode); _MTL_PRIVATE_DEF_CLS(MTLFunctionStitchingGraph); _MTL_PRIVATE_DEF_CLS(MTLFunctionStitchingInputNode); _MTL_PRIVATE_DEF_CLS(MTLHeapDescriptor); _MTL_PRIVATE_DEF_CLS(MTLIOCommandQueueDescriptor); _MTL_PRIVATE_DEF_CLS(MTLIndirectCommandBufferDescriptor); _MTL_PRIVATE_DEF_CLS(MTLIndirectInstanceAccelerationStructureDescriptor); _MTL_PRIVATE_DEF_CLS(MTLInstanceAccelerationStructureDescriptor); _MTL_PRIVATE_DEF_CLS(MTLIntersectionFunctionDescriptor); _MTL_PRIVATE_DEF_CLS(MTLIntersectionFunctionTableDescriptor); _MTL_PRIVATE_DEF_CLS(MTLLinkedFunctions); _MTL_PRIVATE_DEF_CLS(MTLMeshRenderPipelineDescriptor); _MTL_PRIVATE_DEF_CLS(MTLMotionKeyframeData); _MTL_PRIVATE_DEF_CLS(MTLPipelineBufferDescriptor); _MTL_PRIVATE_DEF_CLS(MTLPipelineBufferDescriptorArray); _MTL_PRIVATE_DEF_CLS(MTLPointerType); _MTL_PRIVATE_DEF_CLS(MTLPrimitiveAccelerationStructureDescriptor); _MTL_PRIVATE_DEF_CLS(MTLRasterizationRateLayerArray); _MTL_PRIVATE_DEF_CLS(MTLRasterizationRateLayerDescriptor); _MTL_PRIVATE_DEF_CLS(MTLRasterizationRateMapDescriptor); _MTL_PRIVATE_DEF_CLS(MTLRasterizationRateSampleArray); _MTL_PRIVATE_DEF_CLS(MTLRenderPassAttachmentDescriptor); _MTL_PRIVATE_DEF_CLS(MTLRenderPassColorAttachmentDescriptor); _MTL_PRIVATE_DEF_CLS(MTLRenderPassColorAttachmentDescriptorArray); _MTL_PRIVATE_DEF_CLS(MTLRenderPassDepthAttachmentDescriptor); _MTL_PRIVATE_DEF_CLS(MTLRenderPassDescriptor); _MTL_PRIVATE_DEF_CLS(MTLRenderPassSampleBufferAttachmentDescriptor); _MTL_PRIVATE_DEF_CLS(MTLRenderPassSampleBufferAttachmentDescriptorArray); _MTL_PRIVATE_DEF_CLS(MTLRenderPassStencilAttachmentDescriptor); _MTL_PRIVATE_DEF_CLS(MTLRenderPipelineColorAttachmentDescriptor); _MTL_PRIVATE_DEF_CLS(MTLRenderPipelineColorAttachmentDescriptorArray); _MTL_PRIVATE_DEF_CLS(MTLRenderPipelineDescriptor); _MTL_PRIVATE_DEF_CLS(MTLRenderPipelineFunctionsDescriptor); _MTL_PRIVATE_DEF_CLS(MTLRenderPipelineReflection); _MTL_PRIVATE_DEF_CLS(MTLResourceStatePassDescriptor); _MTL_PRIVATE_DEF_CLS(MTLResourceStatePassSampleBufferAttachmentDescriptor); _MTL_PRIVATE_DEF_CLS(MTLResourceStatePassSampleBufferAttachmentDescriptorArray); _MTL_PRIVATE_DEF_CLS(MTLSamplerDescriptor); _MTL_PRIVATE_DEF_CLS(MTLSharedEventHandle); _MTL_PRIVATE_DEF_CLS(MTLSharedEventListener); _MTL_PRIVATE_DEF_CLS(MTLSharedTextureHandle); _MTL_PRIVATE_DEF_CLS(MTLStageInputOutputDescriptor); _MTL_PRIVATE_DEF_CLS(MTLStencilDescriptor); _MTL_PRIVATE_DEF_CLS(MTLStitchedLibraryDescriptor); _MTL_PRIVATE_DEF_CLS(MTLStructMember); _MTL_PRIVATE_DEF_CLS(MTLStructType); _MTL_PRIVATE_DEF_CLS(MTLTextureDescriptor); _MTL_PRIVATE_DEF_CLS(MTLTextureReferenceType); _MTL_PRIVATE_DEF_CLS(MTLTileRenderPipelineColorAttachmentDescriptor); _MTL_PRIVATE_DEF_CLS(MTLTileRenderPipelineColorAttachmentDescriptorArray); _MTL_PRIVATE_DEF_CLS(MTLTileRenderPipelineDescriptor); _MTL_PRIVATE_DEF_CLS(MTLType); _MTL_PRIVATE_DEF_CLS(MTLVertexAttribute); _MTL_PRIVATE_DEF_CLS(MTLVertexAttributeDescriptor); _MTL_PRIVATE_DEF_CLS(MTLVertexAttributeDescriptorArray); _MTL_PRIVATE_DEF_CLS(MTLVertexBufferLayoutDescriptor); _MTL_PRIVATE_DEF_CLS(MTLVertexBufferLayoutDescriptorArray); _MTL_PRIVATE_DEF_CLS(MTLVertexDescriptor); _MTL_PRIVATE_DEF_CLS(MTLVisibleFunctionTableDescriptor); } namespace MTL::Private::Protocol { _MTL_PRIVATE_DEF_PRO(MTLAccelerationStructure); _MTL_PRIVATE_DEF_PRO(MTLAccelerationStructureCommandEncoder); _MTL_PRIVATE_DEF_PRO(MTLArgumentEncoder); _MTL_PRIVATE_DEF_PRO(MTLBinaryArchive); _MTL_PRIVATE_DEF_PRO(MTLBinding); _MTL_PRIVATE_DEF_PRO(MTLBlitCommandEncoder); _MTL_PRIVATE_DEF_PRO(MTLBuffer); _MTL_PRIVATE_DEF_PRO(MTLBufferBinding); _MTL_PRIVATE_DEF_PRO(MTLCommandBuffer); _MTL_PRIVATE_DEF_PRO(MTLCommandBufferEncoderInfo); _MTL_PRIVATE_DEF_PRO(MTLCommandEncoder); _MTL_PRIVATE_DEF_PRO(MTLCommandQueue); _MTL_PRIVATE_DEF_PRO(MTLComputeCommandEncoder); _MTL_PRIVATE_DEF_PRO(MTLComputePipelineState); _MTL_PRIVATE_DEF_PRO(MTLCounter); _MTL_PRIVATE_DEF_PRO(MTLCounterSampleBuffer); _MTL_PRIVATE_DEF_PRO(MTLCounterSet); _MTL_PRIVATE_DEF_PRO(MTLDepthStencilState); _MTL_PRIVATE_DEF_PRO(MTLDevice); _MTL_PRIVATE_DEF_PRO(MTLDrawable); _MTL_PRIVATE_DEF_PRO(MTLDynamicLibrary); _MTL_PRIVATE_DEF_PRO(MTLEvent); _MTL_PRIVATE_DEF_PRO(MTLFence); _MTL_PRIVATE_DEF_PRO(MTLFunction); _MTL_PRIVATE_DEF_PRO(MTLFunctionHandle); _MTL_PRIVATE_DEF_PRO(MTLFunctionLog); _MTL_PRIVATE_DEF_PRO(MTLFunctionLogDebugLocation); _MTL_PRIVATE_DEF_PRO(MTLFunctionStitchingAttribute); _MTL_PRIVATE_DEF_PRO(MTLFunctionStitchingNode); _MTL_PRIVATE_DEF_PRO(MTLHeap); _MTL_PRIVATE_DEF_PRO(MTLIOCommandBuffer); _MTL_PRIVATE_DEF_PRO(MTLIOCommandQueue); _MTL_PRIVATE_DEF_PRO(MTLIOFileHandle); _MTL_PRIVATE_DEF_PRO(MTLIOScratchBuffer); _MTL_PRIVATE_DEF_PRO(MTLIOScratchBufferAllocator); _MTL_PRIVATE_DEF_PRO(MTLIndirectCommandBuffer); _MTL_PRIVATE_DEF_PRO(MTLIndirectComputeCommand); _MTL_PRIVATE_DEF_PRO(MTLIndirectRenderCommand); _MTL_PRIVATE_DEF_PRO(MTLIntersectionFunctionTable); _MTL_PRIVATE_DEF_PRO(MTLLibrary); _MTL_PRIVATE_DEF_PRO(MTLLogContainer); _MTL_PRIVATE_DEF_PRO(MTLObjectPayloadBinding); _MTL_PRIVATE_DEF_PRO(MTLParallelRenderCommandEncoder); _MTL_PRIVATE_DEF_PRO(MTLRasterizationRateMap); _MTL_PRIVATE_DEF_PRO(MTLRenderCommandEncoder); _MTL_PRIVATE_DEF_PRO(MTLRenderPipelineState); _MTL_PRIVATE_DEF_PRO(MTLResource); _MTL_PRIVATE_DEF_PRO(MTLResourceStateCommandEncoder); _MTL_PRIVATE_DEF_PRO(MTLSamplerState); _MTL_PRIVATE_DEF_PRO(MTLSharedEvent); _MTL_PRIVATE_DEF_PRO(MTLTexture); _MTL_PRIVATE_DEF_PRO(MTLTextureBinding); _MTL_PRIVATE_DEF_PRO(MTLThreadgroupBinding); _MTL_PRIVATE_DEF_PRO(MTLVisibleFunctionTable); } namespace MTL::Private::Selector { _MTL_PRIVATE_DEF_SEL(GPUEndTime, "GPUEndTime"); _MTL_PRIVATE_DEF_SEL(GPUStartTime, "GPUStartTime"); _MTL_PRIVATE_DEF_SEL(URL, "URL"); _MTL_PRIVATE_DEF_SEL(accelerationStructureCommandEncoder, "accelerationStructureCommandEncoder"); _MTL_PRIVATE_DEF_SEL(accelerationStructureCommandEncoderWithDescriptor_, "accelerationStructureCommandEncoderWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(accelerationStructurePassDescriptor, "accelerationStructurePassDescriptor"); _MTL_PRIVATE_DEF_SEL(accelerationStructureSizesWithDescriptor_, "accelerationStructureSizesWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(access, "access"); _MTL_PRIVATE_DEF_SEL(addBarrier, "addBarrier"); _MTL_PRIVATE_DEF_SEL(addCompletedHandler_, "addCompletedHandler:"); _MTL_PRIVATE_DEF_SEL(addComputePipelineFunctionsWithDescriptor_error_, "addComputePipelineFunctionsWithDescriptor:error:"); _MTL_PRIVATE_DEF_SEL(addDebugMarker_range_, "addDebugMarker:range:"); _MTL_PRIVATE_DEF_SEL(addFunctionWithDescriptor_library_error_, "addFunctionWithDescriptor:library:error:"); _MTL_PRIVATE_DEF_SEL(addPresentedHandler_, "addPresentedHandler:"); _MTL_PRIVATE_DEF_SEL(addRenderPipelineFunctionsWithDescriptor_error_, "addRenderPipelineFunctionsWithDescriptor:error:"); _MTL_PRIVATE_DEF_SEL(addScheduledHandler_, "addScheduledHandler:"); _MTL_PRIVATE_DEF_SEL(addTileRenderPipelineFunctionsWithDescriptor_error_, "addTileRenderPipelineFunctionsWithDescriptor:error:"); _MTL_PRIVATE_DEF_SEL(alignment, "alignment"); _MTL_PRIVATE_DEF_SEL(allocatedSize, "allocatedSize"); _MTL_PRIVATE_DEF_SEL(allowDuplicateIntersectionFunctionInvocation, "allowDuplicateIntersectionFunctionInvocation"); _MTL_PRIVATE_DEF_SEL(allowGPUOptimizedContents, "allowGPUOptimizedContents"); _MTL_PRIVATE_DEF_SEL(allowReferencingUndefinedSymbols, "allowReferencingUndefinedSymbols"); _MTL_PRIVATE_DEF_SEL(alphaBlendOperation, "alphaBlendOperation"); _MTL_PRIVATE_DEF_SEL(architecture, "architecture"); _MTL_PRIVATE_DEF_SEL(areBarycentricCoordsSupported, "areBarycentricCoordsSupported"); _MTL_PRIVATE_DEF_SEL(areProgrammableSamplePositionsSupported, "areProgrammableSamplePositionsSupported"); _MTL_PRIVATE_DEF_SEL(areRasterOrderGroupsSupported, "areRasterOrderGroupsSupported"); _MTL_PRIVATE_DEF_SEL(argumentBuffersSupport, "argumentBuffersSupport"); _MTL_PRIVATE_DEF_SEL(argumentDescriptor, "argumentDescriptor"); _MTL_PRIVATE_DEF_SEL(argumentIndex, "argumentIndex"); _MTL_PRIVATE_DEF_SEL(argumentIndexStride, "argumentIndexStride"); _MTL_PRIVATE_DEF_SEL(arguments, "arguments"); _MTL_PRIVATE_DEF_SEL(arrayLength, "arrayLength"); _MTL_PRIVATE_DEF_SEL(arrayType, "arrayType"); _MTL_PRIVATE_DEF_SEL(attributeIndex, "attributeIndex"); _MTL_PRIVATE_DEF_SEL(attributeType, "attributeType"); _MTL_PRIVATE_DEF_SEL(attributes, "attributes"); _MTL_PRIVATE_DEF_SEL(backFaceStencil, "backFaceStencil"); _MTL_PRIVATE_DEF_SEL(binaryArchives, "binaryArchives"); _MTL_PRIVATE_DEF_SEL(binaryFunctions, "binaryFunctions"); _MTL_PRIVATE_DEF_SEL(bindings, "bindings"); _MTL_PRIVATE_DEF_SEL(blitCommandEncoder, "blitCommandEncoder"); _MTL_PRIVATE_DEF_SEL(blitCommandEncoderWithDescriptor_, "blitCommandEncoderWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(blitPassDescriptor, "blitPassDescriptor"); _MTL_PRIVATE_DEF_SEL(borderColor, "borderColor"); _MTL_PRIVATE_DEF_SEL(boundingBoxBuffer, "boundingBoxBuffer"); _MTL_PRIVATE_DEF_SEL(boundingBoxBufferOffset, "boundingBoxBufferOffset"); _MTL_PRIVATE_DEF_SEL(boundingBoxBuffers, "boundingBoxBuffers"); _MTL_PRIVATE_DEF_SEL(boundingBoxCount, "boundingBoxCount"); _MTL_PRIVATE_DEF_SEL(boundingBoxStride, "boundingBoxStride"); _MTL_PRIVATE_DEF_SEL(buffer, "buffer"); _MTL_PRIVATE_DEF_SEL(bufferAlignment, "bufferAlignment"); _MTL_PRIVATE_DEF_SEL(bufferBytesPerRow, "bufferBytesPerRow"); _MTL_PRIVATE_DEF_SEL(bufferDataSize, "bufferDataSize"); _MTL_PRIVATE_DEF_SEL(bufferDataType, "bufferDataType"); _MTL_PRIVATE_DEF_SEL(bufferIndex, "bufferIndex"); _MTL_PRIVATE_DEF_SEL(bufferOffset, "bufferOffset"); _MTL_PRIVATE_DEF_SEL(bufferPointerType, "bufferPointerType"); _MTL_PRIVATE_DEF_SEL(bufferStructType, "bufferStructType"); _MTL_PRIVATE_DEF_SEL(buffers, "buffers"); _MTL_PRIVATE_DEF_SEL(buildAccelerationStructure_descriptor_scratchBuffer_scratchBufferOffset_, "buildAccelerationStructure:descriptor:scratchBuffer:scratchBufferOffset:"); _MTL_PRIVATE_DEF_SEL(captureObject, "captureObject"); _MTL_PRIVATE_DEF_SEL(clearBarrier, "clearBarrier"); _MTL_PRIVATE_DEF_SEL(clearColor, "clearColor"); _MTL_PRIVATE_DEF_SEL(clearDepth, "clearDepth"); _MTL_PRIVATE_DEF_SEL(clearStencil, "clearStencil"); _MTL_PRIVATE_DEF_SEL(colorAttachments, "colorAttachments"); _MTL_PRIVATE_DEF_SEL(column, "column"); _MTL_PRIVATE_DEF_SEL(commandBuffer, "commandBuffer"); _MTL_PRIVATE_DEF_SEL(commandBufferWithDescriptor_, "commandBufferWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(commandBufferWithUnretainedReferences, "commandBufferWithUnretainedReferences"); _MTL_PRIVATE_DEF_SEL(commandQueue, "commandQueue"); _MTL_PRIVATE_DEF_SEL(commandTypes, "commandTypes"); _MTL_PRIVATE_DEF_SEL(commit, "commit"); _MTL_PRIVATE_DEF_SEL(compareFunction, "compareFunction"); _MTL_PRIVATE_DEF_SEL(compileSymbolVisibility, "compileSymbolVisibility"); _MTL_PRIVATE_DEF_SEL(compressionType, "compressionType"); _MTL_PRIVATE_DEF_SEL(computeCommandEncoder, "computeCommandEncoder"); _MTL_PRIVATE_DEF_SEL(computeCommandEncoderWithDescriptor_, "computeCommandEncoderWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(computeCommandEncoderWithDispatchType_, "computeCommandEncoderWithDispatchType:"); _MTL_PRIVATE_DEF_SEL(computeFunction, "computeFunction"); _MTL_PRIVATE_DEF_SEL(computePassDescriptor, "computePassDescriptor"); _MTL_PRIVATE_DEF_SEL(concurrentDispatchThreadgroups_threadsPerThreadgroup_, "concurrentDispatchThreadgroups:threadsPerThreadgroup:"); _MTL_PRIVATE_DEF_SEL(concurrentDispatchThreads_threadsPerThreadgroup_, "concurrentDispatchThreads:threadsPerThreadgroup:"); _MTL_PRIVATE_DEF_SEL(constantBlockAlignment, "constantBlockAlignment"); _MTL_PRIVATE_DEF_SEL(constantDataAtIndex_, "constantDataAtIndex:"); _MTL_PRIVATE_DEF_SEL(constantValues, "constantValues"); _MTL_PRIVATE_DEF_SEL(contents, "contents"); _MTL_PRIVATE_DEF_SEL(controlDependencies, "controlDependencies"); _MTL_PRIVATE_DEF_SEL(controlPointBuffer, "controlPointBuffer"); _MTL_PRIVATE_DEF_SEL(controlPointBufferOffset, "controlPointBufferOffset"); _MTL_PRIVATE_DEF_SEL(controlPointBuffers, "controlPointBuffers"); _MTL_PRIVATE_DEF_SEL(controlPointCount, "controlPointCount"); _MTL_PRIVATE_DEF_SEL(controlPointFormat, "controlPointFormat"); _MTL_PRIVATE_DEF_SEL(controlPointStride, "controlPointStride"); _MTL_PRIVATE_DEF_SEL(convertSparsePixelRegions_toTileRegions_withTileSize_alignmentMode_numRegions_, "convertSparsePixelRegions:toTileRegions:withTileSize:alignmentMode:numRegions:"); _MTL_PRIVATE_DEF_SEL(convertSparseTileRegions_toPixelRegions_withTileSize_numRegions_, "convertSparseTileRegions:toPixelRegions:withTileSize:numRegions:"); _MTL_PRIVATE_DEF_SEL(copyAccelerationStructure_toAccelerationStructure_, "copyAccelerationStructure:toAccelerationStructure:"); _MTL_PRIVATE_DEF_SEL(copyAndCompactAccelerationStructure_toAccelerationStructure_, "copyAndCompactAccelerationStructure:toAccelerationStructure:"); _MTL_PRIVATE_DEF_SEL(copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin_, "copyFromBuffer:sourceOffset:sourceBytesPerRow:sourceBytesPerImage:sourceSize:toTexture:destinationSlice:destinationLevel:destinationOrigin:"); _MTL_PRIVATE_DEF_SEL(copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin_options_, "copyFromBuffer:sourceOffset:sourceBytesPerRow:sourceBytesPerImage:sourceSize:toTexture:destinationSlice:destinationLevel:destinationOrigin:options:"); _MTL_PRIVATE_DEF_SEL(copyFromBuffer_sourceOffset_toBuffer_destinationOffset_size_, "copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:"); _MTL_PRIVATE_DEF_SEL(copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage_, "copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toBuffer:destinationOffset:destinationBytesPerRow:destinationBytesPerImage:"); _MTL_PRIVATE_DEF_SEL(copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage_options_, "copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toBuffer:destinationOffset:destinationBytesPerRow:destinationBytesPerImage:options:"); _MTL_PRIVATE_DEF_SEL(copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin_, "copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toTexture:destinationSlice:destinationLevel:destinationOrigin:"); _MTL_PRIVATE_DEF_SEL(copyFromTexture_sourceSlice_sourceLevel_toTexture_destinationSlice_destinationLevel_sliceCount_levelCount_, "copyFromTexture:sourceSlice:sourceLevel:toTexture:destinationSlice:destinationLevel:sliceCount:levelCount:"); _MTL_PRIVATE_DEF_SEL(copyFromTexture_toTexture_, "copyFromTexture:toTexture:"); _MTL_PRIVATE_DEF_SEL(copyIndirectCommandBuffer_sourceRange_destination_destinationIndex_, "copyIndirectCommandBuffer:sourceRange:destination:destinationIndex:"); _MTL_PRIVATE_DEF_SEL(copyParameterDataToBuffer_offset_, "copyParameterDataToBuffer:offset:"); _MTL_PRIVATE_DEF_SEL(copyStatusToBuffer_offset_, "copyStatusToBuffer:offset:"); _MTL_PRIVATE_DEF_SEL(counterSet, "counterSet"); _MTL_PRIVATE_DEF_SEL(counterSets, "counterSets"); _MTL_PRIVATE_DEF_SEL(counters, "counters"); _MTL_PRIVATE_DEF_SEL(cpuCacheMode, "cpuCacheMode"); _MTL_PRIVATE_DEF_SEL(currentAllocatedSize, "currentAllocatedSize"); _MTL_PRIVATE_DEF_SEL(curveBasis, "curveBasis"); _MTL_PRIVATE_DEF_SEL(curveEndCaps, "curveEndCaps"); _MTL_PRIVATE_DEF_SEL(curveType, "curveType"); _MTL_PRIVATE_DEF_SEL(data, "data"); _MTL_PRIVATE_DEF_SEL(dataSize, "dataSize"); _MTL_PRIVATE_DEF_SEL(dataType, "dataType"); _MTL_PRIVATE_DEF_SEL(dealloc, "dealloc"); _MTL_PRIVATE_DEF_SEL(debugLocation, "debugLocation"); _MTL_PRIVATE_DEF_SEL(debugSignposts, "debugSignposts"); _MTL_PRIVATE_DEF_SEL(defaultCaptureScope, "defaultCaptureScope"); _MTL_PRIVATE_DEF_SEL(defaultRasterSampleCount, "defaultRasterSampleCount"); _MTL_PRIVATE_DEF_SEL(depth, "depth"); _MTL_PRIVATE_DEF_SEL(depthAttachment, "depthAttachment"); _MTL_PRIVATE_DEF_SEL(depthAttachmentPixelFormat, "depthAttachmentPixelFormat"); _MTL_PRIVATE_DEF_SEL(depthCompareFunction, "depthCompareFunction"); _MTL_PRIVATE_DEF_SEL(depthFailureOperation, "depthFailureOperation"); _MTL_PRIVATE_DEF_SEL(depthPlane, "depthPlane"); _MTL_PRIVATE_DEF_SEL(depthResolveFilter, "depthResolveFilter"); _MTL_PRIVATE_DEF_SEL(depthStencilPassOperation, "depthStencilPassOperation"); _MTL_PRIVATE_DEF_SEL(descriptor, "descriptor"); _MTL_PRIVATE_DEF_SEL(destination, "destination"); _MTL_PRIVATE_DEF_SEL(destinationAlphaBlendFactor, "destinationAlphaBlendFactor"); _MTL_PRIVATE_DEF_SEL(destinationRGBBlendFactor, "destinationRGBBlendFactor"); _MTL_PRIVATE_DEF_SEL(device, "device"); _MTL_PRIVATE_DEF_SEL(didModifyRange_, "didModifyRange:"); _MTL_PRIVATE_DEF_SEL(dispatchQueue, "dispatchQueue"); _MTL_PRIVATE_DEF_SEL(dispatchThreadgroups_threadsPerThreadgroup_, "dispatchThreadgroups:threadsPerThreadgroup:"); _MTL_PRIVATE_DEF_SEL(dispatchThreadgroupsWithIndirectBuffer_indirectBufferOffset_threadsPerThreadgroup_, "dispatchThreadgroupsWithIndirectBuffer:indirectBufferOffset:threadsPerThreadgroup:"); _MTL_PRIVATE_DEF_SEL(dispatchThreads_threadsPerThreadgroup_, "dispatchThreads:threadsPerThreadgroup:"); _MTL_PRIVATE_DEF_SEL(dispatchThreadsPerTile_, "dispatchThreadsPerTile:"); _MTL_PRIVATE_DEF_SEL(dispatchType, "dispatchType"); _MTL_PRIVATE_DEF_SEL(drawIndexedPatches_patchIndexBuffer_patchIndexBufferOffset_controlPointIndexBuffer_controlPointIndexBufferOffset_indirectBuffer_indirectBufferOffset_, "drawIndexedPatches:patchIndexBuffer:patchIndexBufferOffset:controlPointIndexBuffer:controlPointIndexBufferOffset:indirectBuffer:indirectBufferOffset:"); _MTL_PRIVATE_DEF_SEL(drawIndexedPatches_patchStart_patchCount_patchIndexBuffer_patchIndexBufferOffset_controlPointIndexBuffer_controlPointIndexBufferOffset_instanceCount_baseInstance_, "drawIndexedPatches:patchStart:patchCount:patchIndexBuffer:patchIndexBufferOffset:controlPointIndexBuffer:controlPointIndexBufferOffset:instanceCount:baseInstance:"); _MTL_PRIVATE_DEF_SEL(drawIndexedPatches_patchStart_patchCount_patchIndexBuffer_patchIndexBufferOffset_controlPointIndexBuffer_controlPointIndexBufferOffset_instanceCount_baseInstance_tessellationFactorBuffer_tessellationFactorBufferOffset_tessellationFactorBufferInstanceStride_, "drawIndexedPatches:patchStart:patchCount:patchIndexBuffer:patchIndexBufferOffset:controlPointIndexBuffer:controlPointIndexBufferOffset:instanceCount:baseInstance:tessellationFactorBuffer:tessellationFactorBufferOffset:tessellationFactorBufferInstanceStride:"); _MTL_PRIVATE_DEF_SEL(drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_, "drawIndexedPrimitives:indexCount:indexType:indexBuffer:indexBufferOffset:"); _MTL_PRIVATE_DEF_SEL(drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_instanceCount_, "drawIndexedPrimitives:indexCount:indexType:indexBuffer:indexBufferOffset:instanceCount:"); _MTL_PRIVATE_DEF_SEL(drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_instanceCount_baseVertex_baseInstance_, "drawIndexedPrimitives:indexCount:indexType:indexBuffer:indexBufferOffset:instanceCount:baseVertex:baseInstance:"); _MTL_PRIVATE_DEF_SEL(drawIndexedPrimitives_indexType_indexBuffer_indexBufferOffset_indirectBuffer_indirectBufferOffset_, "drawIndexedPrimitives:indexType:indexBuffer:indexBufferOffset:indirectBuffer:indirectBufferOffset:"); _MTL_PRIVATE_DEF_SEL(drawMeshThreadgroups_threadsPerObjectThreadgroup_threadsPerMeshThreadgroup_, "drawMeshThreadgroups:threadsPerObjectThreadgroup:threadsPerMeshThreadgroup:"); _MTL_PRIVATE_DEF_SEL(drawMeshThreadgroupsWithIndirectBuffer_indirectBufferOffset_threadsPerObjectThreadgroup_threadsPerMeshThreadgroup_, "drawMeshThreadgroupsWithIndirectBuffer:indirectBufferOffset:threadsPerObjectThreadgroup:threadsPerMeshThreadgroup:"); _MTL_PRIVATE_DEF_SEL(drawMeshThreads_threadsPerObjectThreadgroup_threadsPerMeshThreadgroup_, "drawMeshThreads:threadsPerObjectThreadgroup:threadsPerMeshThreadgroup:"); _MTL_PRIVATE_DEF_SEL(drawPatches_patchIndexBuffer_patchIndexBufferOffset_indirectBuffer_indirectBufferOffset_, "drawPatches:patchIndexBuffer:patchIndexBufferOffset:indirectBuffer:indirectBufferOffset:"); _MTL_PRIVATE_DEF_SEL(drawPatches_patchStart_patchCount_patchIndexBuffer_patchIndexBufferOffset_instanceCount_baseInstance_, "drawPatches:patchStart:patchCount:patchIndexBuffer:patchIndexBufferOffset:instanceCount:baseInstance:"); _MTL_PRIVATE_DEF_SEL(drawPatches_patchStart_patchCount_patchIndexBuffer_patchIndexBufferOffset_instanceCount_baseInstance_tessellationFactorBuffer_tessellationFactorBufferOffset_tessellationFactorBufferInstanceStride_, "drawPatches:patchStart:patchCount:patchIndexBuffer:patchIndexBufferOffset:instanceCount:baseInstance:tessellationFactorBuffer:tessellationFactorBufferOffset:tessellationFactorBufferInstanceStride:"); _MTL_PRIVATE_DEF_SEL(drawPrimitives_indirectBuffer_indirectBufferOffset_, "drawPrimitives:indirectBuffer:indirectBufferOffset:"); _MTL_PRIVATE_DEF_SEL(drawPrimitives_vertexStart_vertexCount_, "drawPrimitives:vertexStart:vertexCount:"); _MTL_PRIVATE_DEF_SEL(drawPrimitives_vertexStart_vertexCount_instanceCount_, "drawPrimitives:vertexStart:vertexCount:instanceCount:"); _MTL_PRIVATE_DEF_SEL(drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance_, "drawPrimitives:vertexStart:vertexCount:instanceCount:baseInstance:"); _MTL_PRIVATE_DEF_SEL(drawableID, "drawableID"); _MTL_PRIVATE_DEF_SEL(elementArrayType, "elementArrayType"); _MTL_PRIVATE_DEF_SEL(elementIsArgumentBuffer, "elementIsArgumentBuffer"); _MTL_PRIVATE_DEF_SEL(elementPointerType, "elementPointerType"); _MTL_PRIVATE_DEF_SEL(elementStructType, "elementStructType"); _MTL_PRIVATE_DEF_SEL(elementTextureReferenceType, "elementTextureReferenceType"); _MTL_PRIVATE_DEF_SEL(elementType, "elementType"); _MTL_PRIVATE_DEF_SEL(encodeSignalEvent_value_, "encodeSignalEvent:value:"); _MTL_PRIVATE_DEF_SEL(encodeWaitForEvent_value_, "encodeWaitForEvent:value:"); _MTL_PRIVATE_DEF_SEL(encodedLength, "encodedLength"); _MTL_PRIVATE_DEF_SEL(encoderLabel, "encoderLabel"); _MTL_PRIVATE_DEF_SEL(endEncoding, "endEncoding"); _MTL_PRIVATE_DEF_SEL(endOfEncoderSampleIndex, "endOfEncoderSampleIndex"); _MTL_PRIVATE_DEF_SEL(endOfFragmentSampleIndex, "endOfFragmentSampleIndex"); _MTL_PRIVATE_DEF_SEL(endOfVertexSampleIndex, "endOfVertexSampleIndex"); _MTL_PRIVATE_DEF_SEL(enqueue, "enqueue"); _MTL_PRIVATE_DEF_SEL(enqueueBarrier, "enqueueBarrier"); _MTL_PRIVATE_DEF_SEL(error, "error"); _MTL_PRIVATE_DEF_SEL(errorOptions, "errorOptions"); _MTL_PRIVATE_DEF_SEL(errorState, "errorState"); _MTL_PRIVATE_DEF_SEL(executeCommandsInBuffer_indirectBuffer_indirectBufferOffset_, "executeCommandsInBuffer:indirectBuffer:indirectBufferOffset:"); _MTL_PRIVATE_DEF_SEL(executeCommandsInBuffer_withRange_, "executeCommandsInBuffer:withRange:"); _MTL_PRIVATE_DEF_SEL(fastMathEnabled, "fastMathEnabled"); _MTL_PRIVATE_DEF_SEL(fillBuffer_range_value_, "fillBuffer:range:value:"); _MTL_PRIVATE_DEF_SEL(firstMipmapInTail, "firstMipmapInTail"); _MTL_PRIVATE_DEF_SEL(format, "format"); _MTL_PRIVATE_DEF_SEL(fragmentAdditionalBinaryFunctions, "fragmentAdditionalBinaryFunctions"); _MTL_PRIVATE_DEF_SEL(fragmentArguments, "fragmentArguments"); _MTL_PRIVATE_DEF_SEL(fragmentBindings, "fragmentBindings"); _MTL_PRIVATE_DEF_SEL(fragmentBuffers, "fragmentBuffers"); _MTL_PRIVATE_DEF_SEL(fragmentFunction, "fragmentFunction"); _MTL_PRIVATE_DEF_SEL(fragmentLinkedFunctions, "fragmentLinkedFunctions"); _MTL_PRIVATE_DEF_SEL(fragmentPreloadedLibraries, "fragmentPreloadedLibraries"); _MTL_PRIVATE_DEF_SEL(frontFaceStencil, "frontFaceStencil"); _MTL_PRIVATE_DEF_SEL(function, "function"); _MTL_PRIVATE_DEF_SEL(functionConstantsDictionary, "functionConstantsDictionary"); _MTL_PRIVATE_DEF_SEL(functionCount, "functionCount"); _MTL_PRIVATE_DEF_SEL(functionDescriptor, "functionDescriptor"); _MTL_PRIVATE_DEF_SEL(functionGraphs, "functionGraphs"); _MTL_PRIVATE_DEF_SEL(functionHandleWithFunction_, "functionHandleWithFunction:"); _MTL_PRIVATE_DEF_SEL(functionHandleWithFunction_stage_, "functionHandleWithFunction:stage:"); _MTL_PRIVATE_DEF_SEL(functionName, "functionName"); _MTL_PRIVATE_DEF_SEL(functionNames, "functionNames"); _MTL_PRIVATE_DEF_SEL(functionType, "functionType"); _MTL_PRIVATE_DEF_SEL(functions, "functions"); _MTL_PRIVATE_DEF_SEL(generateMipmapsForTexture_, "generateMipmapsForTexture:"); _MTL_PRIVATE_DEF_SEL(geometryDescriptors, "geometryDescriptors"); _MTL_PRIVATE_DEF_SEL(getBytes_bytesPerRow_bytesPerImage_fromRegion_mipmapLevel_slice_, "getBytes:bytesPerRow:bytesPerImage:fromRegion:mipmapLevel:slice:"); _MTL_PRIVATE_DEF_SEL(getBytes_bytesPerRow_fromRegion_mipmapLevel_, "getBytes:bytesPerRow:fromRegion:mipmapLevel:"); _MTL_PRIVATE_DEF_SEL(getDefaultSamplePositions_count_, "getDefaultSamplePositions:count:"); _MTL_PRIVATE_DEF_SEL(getSamplePositions_count_, "getSamplePositions:count:"); _MTL_PRIVATE_DEF_SEL(getTextureAccessCounters_region_mipLevel_slice_resetCounters_countersBuffer_countersBufferOffset_, "getTextureAccessCounters:region:mipLevel:slice:resetCounters:countersBuffer:countersBufferOffset:"); _MTL_PRIVATE_DEF_SEL(gpuAddress, "gpuAddress"); _MTL_PRIVATE_DEF_SEL(gpuResourceID, "gpuResourceID"); _MTL_PRIVATE_DEF_SEL(groups, "groups"); _MTL_PRIVATE_DEF_SEL(hasUnifiedMemory, "hasUnifiedMemory"); _MTL_PRIVATE_DEF_SEL(hazardTrackingMode, "hazardTrackingMode"); _MTL_PRIVATE_DEF_SEL(heap, "heap"); _MTL_PRIVATE_DEF_SEL(heapAccelerationStructureSizeAndAlignWithDescriptor_, "heapAccelerationStructureSizeAndAlignWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(heapAccelerationStructureSizeAndAlignWithSize_, "heapAccelerationStructureSizeAndAlignWithSize:"); _MTL_PRIVATE_DEF_SEL(heapBufferSizeAndAlignWithLength_options_, "heapBufferSizeAndAlignWithLength:options:"); _MTL_PRIVATE_DEF_SEL(heapOffset, "heapOffset"); _MTL_PRIVATE_DEF_SEL(heapTextureSizeAndAlignWithDescriptor_, "heapTextureSizeAndAlignWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(height, "height"); _MTL_PRIVATE_DEF_SEL(horizontal, "horizontal"); _MTL_PRIVATE_DEF_SEL(horizontalSampleStorage, "horizontalSampleStorage"); _MTL_PRIVATE_DEF_SEL(imageblockMemoryLengthForDimensions_, "imageblockMemoryLengthForDimensions:"); _MTL_PRIVATE_DEF_SEL(imageblockSampleLength, "imageblockSampleLength"); _MTL_PRIVATE_DEF_SEL(index, "index"); _MTL_PRIVATE_DEF_SEL(indexBuffer, "indexBuffer"); _MTL_PRIVATE_DEF_SEL(indexBufferIndex, "indexBufferIndex"); _MTL_PRIVATE_DEF_SEL(indexBufferOffset, "indexBufferOffset"); _MTL_PRIVATE_DEF_SEL(indexType, "indexType"); _MTL_PRIVATE_DEF_SEL(indirectComputeCommandAtIndex_, "indirectComputeCommandAtIndex:"); _MTL_PRIVATE_DEF_SEL(indirectRenderCommandAtIndex_, "indirectRenderCommandAtIndex:"); _MTL_PRIVATE_DEF_SEL(inheritBuffers, "inheritBuffers"); _MTL_PRIVATE_DEF_SEL(inheritPipelineState, "inheritPipelineState"); _MTL_PRIVATE_DEF_SEL(init, "init"); _MTL_PRIVATE_DEF_SEL(initWithArgumentIndex_, "initWithArgumentIndex:"); _MTL_PRIVATE_DEF_SEL(initWithDispatchQueue_, "initWithDispatchQueue:"); _MTL_PRIVATE_DEF_SEL(initWithFunctionName_nodes_outputNode_attributes_, "initWithFunctionName:nodes:outputNode:attributes:"); _MTL_PRIVATE_DEF_SEL(initWithName_arguments_controlDependencies_, "initWithName:arguments:controlDependencies:"); _MTL_PRIVATE_DEF_SEL(initWithSampleCount_, "initWithSampleCount:"); _MTL_PRIVATE_DEF_SEL(initWithSampleCount_horizontal_vertical_, "initWithSampleCount:horizontal:vertical:"); _MTL_PRIVATE_DEF_SEL(inputPrimitiveTopology, "inputPrimitiveTopology"); _MTL_PRIVATE_DEF_SEL(insertDebugCaptureBoundary, "insertDebugCaptureBoundary"); _MTL_PRIVATE_DEF_SEL(insertDebugSignpost_, "insertDebugSignpost:"); _MTL_PRIVATE_DEF_SEL(insertLibraries, "insertLibraries"); _MTL_PRIVATE_DEF_SEL(installName, "installName"); _MTL_PRIVATE_DEF_SEL(instanceCount, "instanceCount"); _MTL_PRIVATE_DEF_SEL(instanceCountBuffer, "instanceCountBuffer"); _MTL_PRIVATE_DEF_SEL(instanceCountBufferOffset, "instanceCountBufferOffset"); _MTL_PRIVATE_DEF_SEL(instanceDescriptorBuffer, "instanceDescriptorBuffer"); _MTL_PRIVATE_DEF_SEL(instanceDescriptorBufferOffset, "instanceDescriptorBufferOffset"); _MTL_PRIVATE_DEF_SEL(instanceDescriptorStride, "instanceDescriptorStride"); _MTL_PRIVATE_DEF_SEL(instanceDescriptorType, "instanceDescriptorType"); _MTL_PRIVATE_DEF_SEL(instancedAccelerationStructures, "instancedAccelerationStructures"); _MTL_PRIVATE_DEF_SEL(intersectionFunctionTableDescriptor, "intersectionFunctionTableDescriptor"); _MTL_PRIVATE_DEF_SEL(intersectionFunctionTableOffset, "intersectionFunctionTableOffset"); _MTL_PRIVATE_DEF_SEL(iosurface, "iosurface"); _MTL_PRIVATE_DEF_SEL(iosurfacePlane, "iosurfacePlane"); _MTL_PRIVATE_DEF_SEL(isActive, "isActive"); _MTL_PRIVATE_DEF_SEL(isAliasable, "isAliasable"); _MTL_PRIVATE_DEF_SEL(isAlphaToCoverageEnabled, "isAlphaToCoverageEnabled"); _MTL_PRIVATE_DEF_SEL(isAlphaToOneEnabled, "isAlphaToOneEnabled"); _MTL_PRIVATE_DEF_SEL(isArgument, "isArgument"); _MTL_PRIVATE_DEF_SEL(isBlendingEnabled, "isBlendingEnabled"); _MTL_PRIVATE_DEF_SEL(isCapturing, "isCapturing"); _MTL_PRIVATE_DEF_SEL(isDepth24Stencil8PixelFormatSupported, "isDepth24Stencil8PixelFormatSupported"); _MTL_PRIVATE_DEF_SEL(isDepthTexture, "isDepthTexture"); _MTL_PRIVATE_DEF_SEL(isDepthWriteEnabled, "isDepthWriteEnabled"); _MTL_PRIVATE_DEF_SEL(isFramebufferOnly, "isFramebufferOnly"); _MTL_PRIVATE_DEF_SEL(isHeadless, "isHeadless"); _MTL_PRIVATE_DEF_SEL(isLowPower, "isLowPower"); _MTL_PRIVATE_DEF_SEL(isPatchControlPointData, "isPatchControlPointData"); _MTL_PRIVATE_DEF_SEL(isPatchData, "isPatchData"); _MTL_PRIVATE_DEF_SEL(isRasterizationEnabled, "isRasterizationEnabled"); _MTL_PRIVATE_DEF_SEL(isRemovable, "isRemovable"); _MTL_PRIVATE_DEF_SEL(isShareable, "isShareable"); _MTL_PRIVATE_DEF_SEL(isSparse, "isSparse"); _MTL_PRIVATE_DEF_SEL(isTessellationFactorScaleEnabled, "isTessellationFactorScaleEnabled"); _MTL_PRIVATE_DEF_SEL(isUsed, "isUsed"); _MTL_PRIVATE_DEF_SEL(kernelEndTime, "kernelEndTime"); _MTL_PRIVATE_DEF_SEL(kernelStartTime, "kernelStartTime"); _MTL_PRIVATE_DEF_SEL(label, "label"); _MTL_PRIVATE_DEF_SEL(languageVersion, "languageVersion"); _MTL_PRIVATE_DEF_SEL(layerAtIndex_, "layerAtIndex:"); _MTL_PRIVATE_DEF_SEL(layerCount, "layerCount"); _MTL_PRIVATE_DEF_SEL(layers, "layers"); _MTL_PRIVATE_DEF_SEL(layouts, "layouts"); _MTL_PRIVATE_DEF_SEL(length, "length"); _MTL_PRIVATE_DEF_SEL(level, "level"); _MTL_PRIVATE_DEF_SEL(libraries, "libraries"); _MTL_PRIVATE_DEF_SEL(libraryType, "libraryType"); _MTL_PRIVATE_DEF_SEL(line, "line"); _MTL_PRIVATE_DEF_SEL(linkedFunctions, "linkedFunctions"); _MTL_PRIVATE_DEF_SEL(loadAction, "loadAction"); _MTL_PRIVATE_DEF_SEL(loadBuffer_offset_size_sourceHandle_sourceHandleOffset_, "loadBuffer:offset:size:sourceHandle:sourceHandleOffset:"); _MTL_PRIVATE_DEF_SEL(loadBytes_size_sourceHandle_sourceHandleOffset_, "loadBytes:size:sourceHandle:sourceHandleOffset:"); _MTL_PRIVATE_DEF_SEL(loadTexture_slice_level_size_sourceBytesPerRow_sourceBytesPerImage_destinationOrigin_sourceHandle_sourceHandleOffset_, "loadTexture:slice:level:size:sourceBytesPerRow:sourceBytesPerImage:destinationOrigin:sourceHandle:sourceHandleOffset:"); _MTL_PRIVATE_DEF_SEL(location, "location"); _MTL_PRIVATE_DEF_SEL(locationNumber, "locationNumber"); _MTL_PRIVATE_DEF_SEL(lodAverage, "lodAverage"); _MTL_PRIVATE_DEF_SEL(lodMaxClamp, "lodMaxClamp"); _MTL_PRIVATE_DEF_SEL(lodMinClamp, "lodMinClamp"); _MTL_PRIVATE_DEF_SEL(logs, "logs"); _MTL_PRIVATE_DEF_SEL(magFilter, "magFilter"); _MTL_PRIVATE_DEF_SEL(makeAliasable, "makeAliasable"); _MTL_PRIVATE_DEF_SEL(mapPhysicalToScreenCoordinates_forLayer_, "mapPhysicalToScreenCoordinates:forLayer:"); _MTL_PRIVATE_DEF_SEL(mapScreenToPhysicalCoordinates_forLayer_, "mapScreenToPhysicalCoordinates:forLayer:"); _MTL_PRIVATE_DEF_SEL(maxAnisotropy, "maxAnisotropy"); _MTL_PRIVATE_DEF_SEL(maxArgumentBufferSamplerCount, "maxArgumentBufferSamplerCount"); _MTL_PRIVATE_DEF_SEL(maxAvailableSizeWithAlignment_, "maxAvailableSizeWithAlignment:"); _MTL_PRIVATE_DEF_SEL(maxBufferLength, "maxBufferLength"); _MTL_PRIVATE_DEF_SEL(maxCallStackDepth, "maxCallStackDepth"); _MTL_PRIVATE_DEF_SEL(maxCommandBufferCount, "maxCommandBufferCount"); _MTL_PRIVATE_DEF_SEL(maxCommandsInFlight, "maxCommandsInFlight"); _MTL_PRIVATE_DEF_SEL(maxFragmentBufferBindCount, "maxFragmentBufferBindCount"); _MTL_PRIVATE_DEF_SEL(maxFragmentCallStackDepth, "maxFragmentCallStackDepth"); _MTL_PRIVATE_DEF_SEL(maxInstanceCount, "maxInstanceCount"); _MTL_PRIVATE_DEF_SEL(maxKernelBufferBindCount, "maxKernelBufferBindCount"); _MTL_PRIVATE_DEF_SEL(maxKernelThreadgroupMemoryBindCount, "maxKernelThreadgroupMemoryBindCount"); _MTL_PRIVATE_DEF_SEL(maxMeshBufferBindCount, "maxMeshBufferBindCount"); _MTL_PRIVATE_DEF_SEL(maxMotionTransformCount, "maxMotionTransformCount"); _MTL_PRIVATE_DEF_SEL(maxObjectBufferBindCount, "maxObjectBufferBindCount"); _MTL_PRIVATE_DEF_SEL(maxObjectThreadgroupMemoryBindCount, "maxObjectThreadgroupMemoryBindCount"); _MTL_PRIVATE_DEF_SEL(maxSampleCount, "maxSampleCount"); _MTL_PRIVATE_DEF_SEL(maxTessellationFactor, "maxTessellationFactor"); _MTL_PRIVATE_DEF_SEL(maxThreadgroupMemoryLength, "maxThreadgroupMemoryLength"); _MTL_PRIVATE_DEF_SEL(maxThreadsPerThreadgroup, "maxThreadsPerThreadgroup"); _MTL_PRIVATE_DEF_SEL(maxTotalThreadgroupsPerMeshGrid, "maxTotalThreadgroupsPerMeshGrid"); _MTL_PRIVATE_DEF_SEL(maxTotalThreadsPerMeshThreadgroup, "maxTotalThreadsPerMeshThreadgroup"); _MTL_PRIVATE_DEF_SEL(maxTotalThreadsPerObjectThreadgroup, "maxTotalThreadsPerObjectThreadgroup"); _MTL_PRIVATE_DEF_SEL(maxTotalThreadsPerThreadgroup, "maxTotalThreadsPerThreadgroup"); _MTL_PRIVATE_DEF_SEL(maxTransferRate, "maxTransferRate"); _MTL_PRIVATE_DEF_SEL(maxVertexAmplificationCount, "maxVertexAmplificationCount"); _MTL_PRIVATE_DEF_SEL(maxVertexBufferBindCount, "maxVertexBufferBindCount"); _MTL_PRIVATE_DEF_SEL(maxVertexCallStackDepth, "maxVertexCallStackDepth"); _MTL_PRIVATE_DEF_SEL(maximumConcurrentCompilationTaskCount, "maximumConcurrentCompilationTaskCount"); _MTL_PRIVATE_DEF_SEL(memberByName_, "memberByName:"); _MTL_PRIVATE_DEF_SEL(members, "members"); _MTL_PRIVATE_DEF_SEL(memoryBarrierWithResources_count_, "memoryBarrierWithResources:count:"); _MTL_PRIVATE_DEF_SEL(memoryBarrierWithResources_count_afterStages_beforeStages_, "memoryBarrierWithResources:count:afterStages:beforeStages:"); _MTL_PRIVATE_DEF_SEL(memoryBarrierWithScope_, "memoryBarrierWithScope:"); _MTL_PRIVATE_DEF_SEL(memoryBarrierWithScope_afterStages_beforeStages_, "memoryBarrierWithScope:afterStages:beforeStages:"); _MTL_PRIVATE_DEF_SEL(meshBindings, "meshBindings"); _MTL_PRIVATE_DEF_SEL(meshBuffers, "meshBuffers"); _MTL_PRIVATE_DEF_SEL(meshFunction, "meshFunction"); _MTL_PRIVATE_DEF_SEL(meshLinkedFunctions, "meshLinkedFunctions"); _MTL_PRIVATE_DEF_SEL(meshThreadExecutionWidth, "meshThreadExecutionWidth"); _MTL_PRIVATE_DEF_SEL(meshThreadgroupSizeIsMultipleOfThreadExecutionWidth, "meshThreadgroupSizeIsMultipleOfThreadExecutionWidth"); _MTL_PRIVATE_DEF_SEL(minFilter, "minFilter"); _MTL_PRIVATE_DEF_SEL(minimumLinearTextureAlignmentForPixelFormat_, "minimumLinearTextureAlignmentForPixelFormat:"); _MTL_PRIVATE_DEF_SEL(minimumTextureBufferAlignmentForPixelFormat_, "minimumTextureBufferAlignmentForPixelFormat:"); _MTL_PRIVATE_DEF_SEL(mipFilter, "mipFilter"); _MTL_PRIVATE_DEF_SEL(mipmapLevelCount, "mipmapLevelCount"); _MTL_PRIVATE_DEF_SEL(motionEndBorderMode, "motionEndBorderMode"); _MTL_PRIVATE_DEF_SEL(motionEndTime, "motionEndTime"); _MTL_PRIVATE_DEF_SEL(motionKeyframeCount, "motionKeyframeCount"); _MTL_PRIVATE_DEF_SEL(motionStartBorderMode, "motionStartBorderMode"); _MTL_PRIVATE_DEF_SEL(motionStartTime, "motionStartTime"); _MTL_PRIVATE_DEF_SEL(motionTransformBuffer, "motionTransformBuffer"); _MTL_PRIVATE_DEF_SEL(motionTransformBufferOffset, "motionTransformBufferOffset"); _MTL_PRIVATE_DEF_SEL(motionTransformCount, "motionTransformCount"); _MTL_PRIVATE_DEF_SEL(motionTransformCountBuffer, "motionTransformCountBuffer"); _MTL_PRIVATE_DEF_SEL(motionTransformCountBufferOffset, "motionTransformCountBufferOffset"); _MTL_PRIVATE_DEF_SEL(moveTextureMappingsFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin_, "moveTextureMappingsFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toTexture:destinationSlice:destinationLevel:destinationOrigin:"); _MTL_PRIVATE_DEF_SEL(mutability, "mutability"); _MTL_PRIVATE_DEF_SEL(name, "name"); _MTL_PRIVATE_DEF_SEL(newAccelerationStructureWithDescriptor_, "newAccelerationStructureWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(newAccelerationStructureWithDescriptor_offset_, "newAccelerationStructureWithDescriptor:offset:"); _MTL_PRIVATE_DEF_SEL(newAccelerationStructureWithSize_, "newAccelerationStructureWithSize:"); _MTL_PRIVATE_DEF_SEL(newAccelerationStructureWithSize_offset_, "newAccelerationStructureWithSize:offset:"); _MTL_PRIVATE_DEF_SEL(newArgumentEncoderForBufferAtIndex_, "newArgumentEncoderForBufferAtIndex:"); _MTL_PRIVATE_DEF_SEL(newArgumentEncoderWithArguments_, "newArgumentEncoderWithArguments:"); _MTL_PRIVATE_DEF_SEL(newArgumentEncoderWithBufferBinding_, "newArgumentEncoderWithBufferBinding:"); _MTL_PRIVATE_DEF_SEL(newArgumentEncoderWithBufferIndex_, "newArgumentEncoderWithBufferIndex:"); _MTL_PRIVATE_DEF_SEL(newArgumentEncoderWithBufferIndex_reflection_, "newArgumentEncoderWithBufferIndex:reflection:"); _MTL_PRIVATE_DEF_SEL(newBinaryArchiveWithDescriptor_error_, "newBinaryArchiveWithDescriptor:error:"); _MTL_PRIVATE_DEF_SEL(newBufferWithBytes_length_options_, "newBufferWithBytes:length:options:"); _MTL_PRIVATE_DEF_SEL(newBufferWithBytesNoCopy_length_options_deallocator_, "newBufferWithBytesNoCopy:length:options:deallocator:"); _MTL_PRIVATE_DEF_SEL(newBufferWithLength_options_, "newBufferWithLength:options:"); _MTL_PRIVATE_DEF_SEL(newBufferWithLength_options_offset_, "newBufferWithLength:options:offset:"); _MTL_PRIVATE_DEF_SEL(newCaptureScopeWithCommandQueue_, "newCaptureScopeWithCommandQueue:"); _MTL_PRIVATE_DEF_SEL(newCaptureScopeWithDevice_, "newCaptureScopeWithDevice:"); _MTL_PRIVATE_DEF_SEL(newCommandQueue, "newCommandQueue"); _MTL_PRIVATE_DEF_SEL(newCommandQueueWithMaxCommandBufferCount_, "newCommandQueueWithMaxCommandBufferCount:"); _MTL_PRIVATE_DEF_SEL(newComputePipelineStateWithAdditionalBinaryFunctions_error_, "newComputePipelineStateWithAdditionalBinaryFunctions:error:"); _MTL_PRIVATE_DEF_SEL(newComputePipelineStateWithDescriptor_options_completionHandler_, "newComputePipelineStateWithDescriptor:options:completionHandler:"); _MTL_PRIVATE_DEF_SEL(newComputePipelineStateWithDescriptor_options_reflection_error_, "newComputePipelineStateWithDescriptor:options:reflection:error:"); _MTL_PRIVATE_DEF_SEL(newComputePipelineStateWithFunction_completionHandler_, "newComputePipelineStateWithFunction:completionHandler:"); _MTL_PRIVATE_DEF_SEL(newComputePipelineStateWithFunction_error_, "newComputePipelineStateWithFunction:error:"); _MTL_PRIVATE_DEF_SEL(newComputePipelineStateWithFunction_options_completionHandler_, "newComputePipelineStateWithFunction:options:completionHandler:"); _MTL_PRIVATE_DEF_SEL(newComputePipelineStateWithFunction_options_reflection_error_, "newComputePipelineStateWithFunction:options:reflection:error:"); _MTL_PRIVATE_DEF_SEL(newCounterSampleBufferWithDescriptor_error_, "newCounterSampleBufferWithDescriptor:error:"); _MTL_PRIVATE_DEF_SEL(newDefaultLibrary, "newDefaultLibrary"); _MTL_PRIVATE_DEF_SEL(newDefaultLibraryWithBundle_error_, "newDefaultLibraryWithBundle:error:"); _MTL_PRIVATE_DEF_SEL(newDepthStencilStateWithDescriptor_, "newDepthStencilStateWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(newDynamicLibrary_error_, "newDynamicLibrary:error:"); _MTL_PRIVATE_DEF_SEL(newDynamicLibraryWithURL_error_, "newDynamicLibraryWithURL:error:"); _MTL_PRIVATE_DEF_SEL(newEvent, "newEvent"); _MTL_PRIVATE_DEF_SEL(newFence, "newFence"); _MTL_PRIVATE_DEF_SEL(newFunctionWithDescriptor_completionHandler_, "newFunctionWithDescriptor:completionHandler:"); _MTL_PRIVATE_DEF_SEL(newFunctionWithDescriptor_error_, "newFunctionWithDescriptor:error:"); _MTL_PRIVATE_DEF_SEL(newFunctionWithName_, "newFunctionWithName:"); _MTL_PRIVATE_DEF_SEL(newFunctionWithName_constantValues_completionHandler_, "newFunctionWithName:constantValues:completionHandler:"); _MTL_PRIVATE_DEF_SEL(newFunctionWithName_constantValues_error_, "newFunctionWithName:constantValues:error:"); _MTL_PRIVATE_DEF_SEL(newHeapWithDescriptor_, "newHeapWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(newIOCommandQueueWithDescriptor_error_, "newIOCommandQueueWithDescriptor:error:"); _MTL_PRIVATE_DEF_SEL(newIOFileHandleWithURL_compressionMethod_error_, "newIOFileHandleWithURL:compressionMethod:error:"); _MTL_PRIVATE_DEF_SEL(newIOFileHandleWithURL_error_, "newIOFileHandleWithURL:error:"); _MTL_PRIVATE_DEF_SEL(newIOHandleWithURL_compressionMethod_error_, "newIOHandleWithURL:compressionMethod:error:"); _MTL_PRIVATE_DEF_SEL(newIOHandleWithURL_error_, "newIOHandleWithURL:error:"); _MTL_PRIVATE_DEF_SEL(newIndirectCommandBufferWithDescriptor_maxCommandCount_options_, "newIndirectCommandBufferWithDescriptor:maxCommandCount:options:"); _MTL_PRIVATE_DEF_SEL(newIntersectionFunctionTableWithDescriptor_, "newIntersectionFunctionTableWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(newIntersectionFunctionTableWithDescriptor_stage_, "newIntersectionFunctionTableWithDescriptor:stage:"); _MTL_PRIVATE_DEF_SEL(newIntersectionFunctionWithDescriptor_completionHandler_, "newIntersectionFunctionWithDescriptor:completionHandler:"); _MTL_PRIVATE_DEF_SEL(newIntersectionFunctionWithDescriptor_error_, "newIntersectionFunctionWithDescriptor:error:"); _MTL_PRIVATE_DEF_SEL(newLibraryWithData_error_, "newLibraryWithData:error:"); _MTL_PRIVATE_DEF_SEL(newLibraryWithFile_error_, "newLibraryWithFile:error:"); _MTL_PRIVATE_DEF_SEL(newLibraryWithSource_options_completionHandler_, "newLibraryWithSource:options:completionHandler:"); _MTL_PRIVATE_DEF_SEL(newLibraryWithSource_options_error_, "newLibraryWithSource:options:error:"); _MTL_PRIVATE_DEF_SEL(newLibraryWithStitchedDescriptor_completionHandler_, "newLibraryWithStitchedDescriptor:completionHandler:"); _MTL_PRIVATE_DEF_SEL(newLibraryWithStitchedDescriptor_error_, "newLibraryWithStitchedDescriptor:error:"); _MTL_PRIVATE_DEF_SEL(newLibraryWithURL_error_, "newLibraryWithURL:error:"); _MTL_PRIVATE_DEF_SEL(newRasterizationRateMapWithDescriptor_, "newRasterizationRateMapWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(newRemoteBufferViewForDevice_, "newRemoteBufferViewForDevice:"); _MTL_PRIVATE_DEF_SEL(newRemoteTextureViewForDevice_, "newRemoteTextureViewForDevice:"); _MTL_PRIVATE_DEF_SEL(newRenderPipelineStateWithAdditionalBinaryFunctions_error_, "newRenderPipelineStateWithAdditionalBinaryFunctions:error:"); _MTL_PRIVATE_DEF_SEL(newRenderPipelineStateWithDescriptor_completionHandler_, "newRenderPipelineStateWithDescriptor:completionHandler:"); _MTL_PRIVATE_DEF_SEL(newRenderPipelineStateWithDescriptor_error_, "newRenderPipelineStateWithDescriptor:error:"); _MTL_PRIVATE_DEF_SEL(newRenderPipelineStateWithDescriptor_options_completionHandler_, "newRenderPipelineStateWithDescriptor:options:completionHandler:"); _MTL_PRIVATE_DEF_SEL(newRenderPipelineStateWithDescriptor_options_reflection_error_, "newRenderPipelineStateWithDescriptor:options:reflection:error:"); _MTL_PRIVATE_DEF_SEL(newRenderPipelineStateWithMeshDescriptor_options_completionHandler_, "newRenderPipelineStateWithMeshDescriptor:options:completionHandler:"); _MTL_PRIVATE_DEF_SEL(newRenderPipelineStateWithMeshDescriptor_options_reflection_error_, "newRenderPipelineStateWithMeshDescriptor:options:reflection:error:"); _MTL_PRIVATE_DEF_SEL(newRenderPipelineStateWithTileDescriptor_options_completionHandler_, "newRenderPipelineStateWithTileDescriptor:options:completionHandler:"); _MTL_PRIVATE_DEF_SEL(newRenderPipelineStateWithTileDescriptor_options_reflection_error_, "newRenderPipelineStateWithTileDescriptor:options:reflection:error:"); _MTL_PRIVATE_DEF_SEL(newSamplerStateWithDescriptor_, "newSamplerStateWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(newScratchBufferWithMinimumSize_, "newScratchBufferWithMinimumSize:"); _MTL_PRIVATE_DEF_SEL(newSharedEvent, "newSharedEvent"); _MTL_PRIVATE_DEF_SEL(newSharedEventHandle, "newSharedEventHandle"); _MTL_PRIVATE_DEF_SEL(newSharedEventWithHandle_, "newSharedEventWithHandle:"); _MTL_PRIVATE_DEF_SEL(newSharedTextureHandle, "newSharedTextureHandle"); _MTL_PRIVATE_DEF_SEL(newSharedTextureWithDescriptor_, "newSharedTextureWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(newSharedTextureWithHandle_, "newSharedTextureWithHandle:"); _MTL_PRIVATE_DEF_SEL(newTextureViewWithPixelFormat_, "newTextureViewWithPixelFormat:"); _MTL_PRIVATE_DEF_SEL(newTextureViewWithPixelFormat_textureType_levels_slices_, "newTextureViewWithPixelFormat:textureType:levels:slices:"); _MTL_PRIVATE_DEF_SEL(newTextureViewWithPixelFormat_textureType_levels_slices_swizzle_, "newTextureViewWithPixelFormat:textureType:levels:slices:swizzle:"); _MTL_PRIVATE_DEF_SEL(newTextureWithDescriptor_, "newTextureWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(newTextureWithDescriptor_iosurface_plane_, "newTextureWithDescriptor:iosurface:plane:"); _MTL_PRIVATE_DEF_SEL(newTextureWithDescriptor_offset_, "newTextureWithDescriptor:offset:"); _MTL_PRIVATE_DEF_SEL(newTextureWithDescriptor_offset_bytesPerRow_, "newTextureWithDescriptor:offset:bytesPerRow:"); _MTL_PRIVATE_DEF_SEL(newVisibleFunctionTableWithDescriptor_, "newVisibleFunctionTableWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(newVisibleFunctionTableWithDescriptor_stage_, "newVisibleFunctionTableWithDescriptor:stage:"); _MTL_PRIVATE_DEF_SEL(nodes, "nodes"); _MTL_PRIVATE_DEF_SEL(normalizedCoordinates, "normalizedCoordinates"); _MTL_PRIVATE_DEF_SEL(notifyListener_atValue_block_, "notifyListener:atValue:block:"); _MTL_PRIVATE_DEF_SEL(objectAtIndexedSubscript_, "objectAtIndexedSubscript:"); _MTL_PRIVATE_DEF_SEL(objectBindings, "objectBindings"); _MTL_PRIVATE_DEF_SEL(objectBuffers, "objectBuffers"); _MTL_PRIVATE_DEF_SEL(objectFunction, "objectFunction"); _MTL_PRIVATE_DEF_SEL(objectLinkedFunctions, "objectLinkedFunctions"); _MTL_PRIVATE_DEF_SEL(objectPayloadAlignment, "objectPayloadAlignment"); _MTL_PRIVATE_DEF_SEL(objectPayloadDataSize, "objectPayloadDataSize"); _MTL_PRIVATE_DEF_SEL(objectThreadExecutionWidth, "objectThreadExecutionWidth"); _MTL_PRIVATE_DEF_SEL(objectThreadgroupSizeIsMultipleOfThreadExecutionWidth, "objectThreadgroupSizeIsMultipleOfThreadExecutionWidth"); _MTL_PRIVATE_DEF_SEL(offset, "offset"); _MTL_PRIVATE_DEF_SEL(opaque, "opaque"); _MTL_PRIVATE_DEF_SEL(optimizationLevel, "optimizationLevel"); _MTL_PRIVATE_DEF_SEL(optimizeContentsForCPUAccess_, "optimizeContentsForCPUAccess:"); _MTL_PRIVATE_DEF_SEL(optimizeContentsForCPUAccess_slice_level_, "optimizeContentsForCPUAccess:slice:level:"); _MTL_PRIVATE_DEF_SEL(optimizeContentsForGPUAccess_, "optimizeContentsForGPUAccess:"); _MTL_PRIVATE_DEF_SEL(optimizeContentsForGPUAccess_slice_level_, "optimizeContentsForGPUAccess:slice:level:"); _MTL_PRIVATE_DEF_SEL(optimizeIndirectCommandBuffer_withRange_, "optimizeIndirectCommandBuffer:withRange:"); _MTL_PRIVATE_DEF_SEL(options, "options"); _MTL_PRIVATE_DEF_SEL(outputNode, "outputNode"); _MTL_PRIVATE_DEF_SEL(outputURL, "outputURL"); _MTL_PRIVATE_DEF_SEL(parallelRenderCommandEncoderWithDescriptor_, "parallelRenderCommandEncoderWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(parameterBufferSizeAndAlign, "parameterBufferSizeAndAlign"); _MTL_PRIVATE_DEF_SEL(parentRelativeLevel, "parentRelativeLevel"); _MTL_PRIVATE_DEF_SEL(parentRelativeSlice, "parentRelativeSlice"); _MTL_PRIVATE_DEF_SEL(parentTexture, "parentTexture"); _MTL_PRIVATE_DEF_SEL(patchControlPointCount, "patchControlPointCount"); _MTL_PRIVATE_DEF_SEL(patchType, "patchType"); _MTL_PRIVATE_DEF_SEL(payloadMemoryLength, "payloadMemoryLength"); _MTL_PRIVATE_DEF_SEL(peerCount, "peerCount"); _MTL_PRIVATE_DEF_SEL(peerGroupID, "peerGroupID"); _MTL_PRIVATE_DEF_SEL(peerIndex, "peerIndex"); _MTL_PRIVATE_DEF_SEL(physicalGranularity, "physicalGranularity"); _MTL_PRIVATE_DEF_SEL(physicalSizeForLayer_, "physicalSizeForLayer:"); _MTL_PRIVATE_DEF_SEL(pixelFormat, "pixelFormat"); _MTL_PRIVATE_DEF_SEL(pointerType, "pointerType"); _MTL_PRIVATE_DEF_SEL(popDebugGroup, "popDebugGroup"); _MTL_PRIVATE_DEF_SEL(preloadedLibraries, "preloadedLibraries"); _MTL_PRIVATE_DEF_SEL(preprocessorMacros, "preprocessorMacros"); _MTL_PRIVATE_DEF_SEL(present, "present"); _MTL_PRIVATE_DEF_SEL(presentAfterMinimumDuration_, "presentAfterMinimumDuration:"); _MTL_PRIVATE_DEF_SEL(presentAtTime_, "presentAtTime:"); _MTL_PRIVATE_DEF_SEL(presentDrawable_, "presentDrawable:"); _MTL_PRIVATE_DEF_SEL(presentDrawable_afterMinimumDuration_, "presentDrawable:afterMinimumDuration:"); _MTL_PRIVATE_DEF_SEL(presentDrawable_atTime_, "presentDrawable:atTime:"); _MTL_PRIVATE_DEF_SEL(presentedTime, "presentedTime"); _MTL_PRIVATE_DEF_SEL(preserveInvariance, "preserveInvariance"); _MTL_PRIVATE_DEF_SEL(primitiveDataBuffer, "primitiveDataBuffer"); _MTL_PRIVATE_DEF_SEL(primitiveDataBufferOffset, "primitiveDataBufferOffset"); _MTL_PRIVATE_DEF_SEL(primitiveDataElementSize, "primitiveDataElementSize"); _MTL_PRIVATE_DEF_SEL(primitiveDataStride, "primitiveDataStride"); _MTL_PRIVATE_DEF_SEL(priority, "priority"); _MTL_PRIVATE_DEF_SEL(privateFunctions, "privateFunctions"); _MTL_PRIVATE_DEF_SEL(pushDebugGroup_, "pushDebugGroup:"); _MTL_PRIVATE_DEF_SEL(rAddressMode, "rAddressMode"); _MTL_PRIVATE_DEF_SEL(radiusBuffer, "radiusBuffer"); _MTL_PRIVATE_DEF_SEL(radiusBufferOffset, "radiusBufferOffset"); _MTL_PRIVATE_DEF_SEL(radiusBuffers, "radiusBuffers"); _MTL_PRIVATE_DEF_SEL(radiusFormat, "radiusFormat"); _MTL_PRIVATE_DEF_SEL(radiusStride, "radiusStride"); _MTL_PRIVATE_DEF_SEL(rasterSampleCount, "rasterSampleCount"); _MTL_PRIVATE_DEF_SEL(rasterizationRateMap, "rasterizationRateMap"); _MTL_PRIVATE_DEF_SEL(rasterizationRateMapDescriptorWithScreenSize_, "rasterizationRateMapDescriptorWithScreenSize:"); _MTL_PRIVATE_DEF_SEL(rasterizationRateMapDescriptorWithScreenSize_layer_, "rasterizationRateMapDescriptorWithScreenSize:layer:"); _MTL_PRIVATE_DEF_SEL(rasterizationRateMapDescriptorWithScreenSize_layerCount_layers_, "rasterizationRateMapDescriptorWithScreenSize:layerCount:layers:"); _MTL_PRIVATE_DEF_SEL(readMask, "readMask"); _MTL_PRIVATE_DEF_SEL(readWriteTextureSupport, "readWriteTextureSupport"); _MTL_PRIVATE_DEF_SEL(recommendedMaxWorkingSetSize, "recommendedMaxWorkingSetSize"); _MTL_PRIVATE_DEF_SEL(refitAccelerationStructure_descriptor_destination_scratchBuffer_scratchBufferOffset_, "refitAccelerationStructure:descriptor:destination:scratchBuffer:scratchBufferOffset:"); _MTL_PRIVATE_DEF_SEL(refitAccelerationStructure_descriptor_destination_scratchBuffer_scratchBufferOffset_options_, "refitAccelerationStructure:descriptor:destination:scratchBuffer:scratchBufferOffset:options:"); _MTL_PRIVATE_DEF_SEL(registryID, "registryID"); _MTL_PRIVATE_DEF_SEL(remoteStorageBuffer, "remoteStorageBuffer"); _MTL_PRIVATE_DEF_SEL(remoteStorageTexture, "remoteStorageTexture"); _MTL_PRIVATE_DEF_SEL(removeAllDebugMarkers, "removeAllDebugMarkers"); _MTL_PRIVATE_DEF_SEL(renderCommandEncoder, "renderCommandEncoder"); _MTL_PRIVATE_DEF_SEL(renderCommandEncoderWithDescriptor_, "renderCommandEncoderWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(renderPassDescriptor, "renderPassDescriptor"); _MTL_PRIVATE_DEF_SEL(renderTargetArrayLength, "renderTargetArrayLength"); _MTL_PRIVATE_DEF_SEL(renderTargetHeight, "renderTargetHeight"); _MTL_PRIVATE_DEF_SEL(renderTargetWidth, "renderTargetWidth"); _MTL_PRIVATE_DEF_SEL(replaceRegion_mipmapLevel_slice_withBytes_bytesPerRow_bytesPerImage_, "replaceRegion:mipmapLevel:slice:withBytes:bytesPerRow:bytesPerImage:"); _MTL_PRIVATE_DEF_SEL(replaceRegion_mipmapLevel_withBytes_bytesPerRow_, "replaceRegion:mipmapLevel:withBytes:bytesPerRow:"); _MTL_PRIVATE_DEF_SEL(required, "required"); _MTL_PRIVATE_DEF_SEL(reset, "reset"); _MTL_PRIVATE_DEF_SEL(resetCommandsInBuffer_withRange_, "resetCommandsInBuffer:withRange:"); _MTL_PRIVATE_DEF_SEL(resetTextureAccessCounters_region_mipLevel_slice_, "resetTextureAccessCounters:region:mipLevel:slice:"); _MTL_PRIVATE_DEF_SEL(resetWithRange_, "resetWithRange:"); _MTL_PRIVATE_DEF_SEL(resolveCounterRange_, "resolveCounterRange:"); _MTL_PRIVATE_DEF_SEL(resolveCounters_inRange_destinationBuffer_destinationOffset_, "resolveCounters:inRange:destinationBuffer:destinationOffset:"); _MTL_PRIVATE_DEF_SEL(resolveDepthPlane, "resolveDepthPlane"); _MTL_PRIVATE_DEF_SEL(resolveLevel, "resolveLevel"); _MTL_PRIVATE_DEF_SEL(resolveSlice, "resolveSlice"); _MTL_PRIVATE_DEF_SEL(resolveTexture, "resolveTexture"); _MTL_PRIVATE_DEF_SEL(resourceOptions, "resourceOptions"); _MTL_PRIVATE_DEF_SEL(resourceStateCommandEncoder, "resourceStateCommandEncoder"); _MTL_PRIVATE_DEF_SEL(resourceStateCommandEncoderWithDescriptor_, "resourceStateCommandEncoderWithDescriptor:"); _MTL_PRIVATE_DEF_SEL(resourceStatePassDescriptor, "resourceStatePassDescriptor"); _MTL_PRIVATE_DEF_SEL(retainedReferences, "retainedReferences"); _MTL_PRIVATE_DEF_SEL(rgbBlendOperation, "rgbBlendOperation"); _MTL_PRIVATE_DEF_SEL(rootResource, "rootResource"); _MTL_PRIVATE_DEF_SEL(sAddressMode, "sAddressMode"); _MTL_PRIVATE_DEF_SEL(sampleBuffer, "sampleBuffer"); _MTL_PRIVATE_DEF_SEL(sampleBufferAttachments, "sampleBufferAttachments"); _MTL_PRIVATE_DEF_SEL(sampleCount, "sampleCount"); _MTL_PRIVATE_DEF_SEL(sampleCountersInBuffer_atSampleIndex_withBarrier_, "sampleCountersInBuffer:atSampleIndex:withBarrier:"); _MTL_PRIVATE_DEF_SEL(sampleTimestamps_gpuTimestamp_, "sampleTimestamps:gpuTimestamp:"); _MTL_PRIVATE_DEF_SEL(scratchBufferAllocator, "scratchBufferAllocator"); _MTL_PRIVATE_DEF_SEL(screenSize, "screenSize"); _MTL_PRIVATE_DEF_SEL(segmentControlPointCount, "segmentControlPointCount"); _MTL_PRIVATE_DEF_SEL(segmentCount, "segmentCount"); _MTL_PRIVATE_DEF_SEL(serializeToURL_error_, "serializeToURL:error:"); _MTL_PRIVATE_DEF_SEL(setAccelerationStructure_atBufferIndex_, "setAccelerationStructure:atBufferIndex:"); _MTL_PRIVATE_DEF_SEL(setAccelerationStructure_atIndex_, "setAccelerationStructure:atIndex:"); _MTL_PRIVATE_DEF_SEL(setAccess_, "setAccess:"); _MTL_PRIVATE_DEF_SEL(setAllowDuplicateIntersectionFunctionInvocation_, "setAllowDuplicateIntersectionFunctionInvocation:"); _MTL_PRIVATE_DEF_SEL(setAllowGPUOptimizedContents_, "setAllowGPUOptimizedContents:"); _MTL_PRIVATE_DEF_SEL(setAllowReferencingUndefinedSymbols_, "setAllowReferencingUndefinedSymbols:"); _MTL_PRIVATE_DEF_SEL(setAlphaBlendOperation_, "setAlphaBlendOperation:"); _MTL_PRIVATE_DEF_SEL(setAlphaToCoverageEnabled_, "setAlphaToCoverageEnabled:"); _MTL_PRIVATE_DEF_SEL(setAlphaToOneEnabled_, "setAlphaToOneEnabled:"); _MTL_PRIVATE_DEF_SEL(setArgumentBuffer_offset_, "setArgumentBuffer:offset:"); _MTL_PRIVATE_DEF_SEL(setArgumentBuffer_startOffset_arrayElement_, "setArgumentBuffer:startOffset:arrayElement:"); _MTL_PRIVATE_DEF_SEL(setArgumentIndex_, "setArgumentIndex:"); _MTL_PRIVATE_DEF_SEL(setArguments_, "setArguments:"); _MTL_PRIVATE_DEF_SEL(setArrayLength_, "setArrayLength:"); _MTL_PRIVATE_DEF_SEL(setAttributes_, "setAttributes:"); _MTL_PRIVATE_DEF_SEL(setBackFaceStencil_, "setBackFaceStencil:"); _MTL_PRIVATE_DEF_SEL(setBarrier, "setBarrier"); _MTL_PRIVATE_DEF_SEL(setBinaryArchives_, "setBinaryArchives:"); _MTL_PRIVATE_DEF_SEL(setBinaryFunctions_, "setBinaryFunctions:"); _MTL_PRIVATE_DEF_SEL(setBlendColorRed_green_blue_alpha_, "setBlendColorRed:green:blue:alpha:"); _MTL_PRIVATE_DEF_SEL(setBlendingEnabled_, "setBlendingEnabled:"); _MTL_PRIVATE_DEF_SEL(setBorderColor_, "setBorderColor:"); _MTL_PRIVATE_DEF_SEL(setBoundingBoxBuffer_, "setBoundingBoxBuffer:"); _MTL_PRIVATE_DEF_SEL(setBoundingBoxBufferOffset_, "setBoundingBoxBufferOffset:"); _MTL_PRIVATE_DEF_SEL(setBoundingBoxBuffers_, "setBoundingBoxBuffers:"); _MTL_PRIVATE_DEF_SEL(setBoundingBoxCount_, "setBoundingBoxCount:"); _MTL_PRIVATE_DEF_SEL(setBoundingBoxStride_, "setBoundingBoxStride:"); _MTL_PRIVATE_DEF_SEL(setBuffer_, "setBuffer:"); _MTL_PRIVATE_DEF_SEL(setBuffer_offset_atIndex_, "setBuffer:offset:atIndex:"); _MTL_PRIVATE_DEF_SEL(setBuffer_offset_attributeStride_atIndex_, "setBuffer:offset:attributeStride:atIndex:"); _MTL_PRIVATE_DEF_SEL(setBufferIndex_, "setBufferIndex:"); _MTL_PRIVATE_DEF_SEL(setBufferOffset_atIndex_, "setBufferOffset:atIndex:"); _MTL_PRIVATE_DEF_SEL(setBufferOffset_attributeStride_atIndex_, "setBufferOffset:attributeStride:atIndex:"); _MTL_PRIVATE_DEF_SEL(setBuffers_offsets_attributeStrides_withRange_, "setBuffers:offsets:attributeStrides:withRange:"); _MTL_PRIVATE_DEF_SEL(setBuffers_offsets_withRange_, "setBuffers:offsets:withRange:"); _MTL_PRIVATE_DEF_SEL(setBytes_length_atIndex_, "setBytes:length:atIndex:"); _MTL_PRIVATE_DEF_SEL(setBytes_length_attributeStride_atIndex_, "setBytes:length:attributeStride:atIndex:"); _MTL_PRIVATE_DEF_SEL(setCaptureObject_, "setCaptureObject:"); _MTL_PRIVATE_DEF_SEL(setClearColor_, "setClearColor:"); _MTL_PRIVATE_DEF_SEL(setClearDepth_, "setClearDepth:"); _MTL_PRIVATE_DEF_SEL(setClearStencil_, "setClearStencil:"); _MTL_PRIVATE_DEF_SEL(setColorStoreAction_atIndex_, "setColorStoreAction:atIndex:"); _MTL_PRIVATE_DEF_SEL(setColorStoreActionOptions_atIndex_, "setColorStoreActionOptions:atIndex:"); _MTL_PRIVATE_DEF_SEL(setCommandTypes_, "setCommandTypes:"); _MTL_PRIVATE_DEF_SEL(setCompareFunction_, "setCompareFunction:"); _MTL_PRIVATE_DEF_SEL(setCompileSymbolVisibility_, "setCompileSymbolVisibility:"); _MTL_PRIVATE_DEF_SEL(setCompressionType_, "setCompressionType:"); _MTL_PRIVATE_DEF_SEL(setComputeFunction_, "setComputeFunction:"); _MTL_PRIVATE_DEF_SEL(setComputePipelineState_, "setComputePipelineState:"); _MTL_PRIVATE_DEF_SEL(setComputePipelineState_atIndex_, "setComputePipelineState:atIndex:"); _MTL_PRIVATE_DEF_SEL(setComputePipelineStates_withRange_, "setComputePipelineStates:withRange:"); _MTL_PRIVATE_DEF_SEL(setConstantBlockAlignment_, "setConstantBlockAlignment:"); _MTL_PRIVATE_DEF_SEL(setConstantValue_type_atIndex_, "setConstantValue:type:atIndex:"); _MTL_PRIVATE_DEF_SEL(setConstantValue_type_withName_, "setConstantValue:type:withName:"); _MTL_PRIVATE_DEF_SEL(setConstantValues_, "setConstantValues:"); _MTL_PRIVATE_DEF_SEL(setConstantValues_type_withRange_, "setConstantValues:type:withRange:"); _MTL_PRIVATE_DEF_SEL(setControlDependencies_, "setControlDependencies:"); _MTL_PRIVATE_DEF_SEL(setControlPointBuffer_, "setControlPointBuffer:"); _MTL_PRIVATE_DEF_SEL(setControlPointBufferOffset_, "setControlPointBufferOffset:"); _MTL_PRIVATE_DEF_SEL(setControlPointBuffers_, "setControlPointBuffers:"); _MTL_PRIVATE_DEF_SEL(setControlPointCount_, "setControlPointCount:"); _MTL_PRIVATE_DEF_SEL(setControlPointFormat_, "setControlPointFormat:"); _MTL_PRIVATE_DEF_SEL(setControlPointStride_, "setControlPointStride:"); _MTL_PRIVATE_DEF_SEL(setCounterSet_, "setCounterSet:"); _MTL_PRIVATE_DEF_SEL(setCpuCacheMode_, "setCpuCacheMode:"); _MTL_PRIVATE_DEF_SEL(setCullMode_, "setCullMode:"); _MTL_PRIVATE_DEF_SEL(setCurveBasis_, "setCurveBasis:"); _MTL_PRIVATE_DEF_SEL(setCurveEndCaps_, "setCurveEndCaps:"); _MTL_PRIVATE_DEF_SEL(setCurveType_, "setCurveType:"); _MTL_PRIVATE_DEF_SEL(setDataType_, "setDataType:"); _MTL_PRIVATE_DEF_SEL(setDefaultCaptureScope_, "setDefaultCaptureScope:"); _MTL_PRIVATE_DEF_SEL(setDefaultRasterSampleCount_, "setDefaultRasterSampleCount:"); _MTL_PRIVATE_DEF_SEL(setDepth_, "setDepth:"); _MTL_PRIVATE_DEF_SEL(setDepthAttachment_, "setDepthAttachment:"); _MTL_PRIVATE_DEF_SEL(setDepthAttachmentPixelFormat_, "setDepthAttachmentPixelFormat:"); _MTL_PRIVATE_DEF_SEL(setDepthBias_slopeScale_clamp_, "setDepthBias:slopeScale:clamp:"); _MTL_PRIVATE_DEF_SEL(setDepthClipMode_, "setDepthClipMode:"); _MTL_PRIVATE_DEF_SEL(setDepthCompareFunction_, "setDepthCompareFunction:"); _MTL_PRIVATE_DEF_SEL(setDepthFailureOperation_, "setDepthFailureOperation:"); _MTL_PRIVATE_DEF_SEL(setDepthPlane_, "setDepthPlane:"); _MTL_PRIVATE_DEF_SEL(setDepthResolveFilter_, "setDepthResolveFilter:"); _MTL_PRIVATE_DEF_SEL(setDepthStencilPassOperation_, "setDepthStencilPassOperation:"); _MTL_PRIVATE_DEF_SEL(setDepthStencilState_, "setDepthStencilState:"); _MTL_PRIVATE_DEF_SEL(setDepthStoreAction_, "setDepthStoreAction:"); _MTL_PRIVATE_DEF_SEL(setDepthStoreActionOptions_, "setDepthStoreActionOptions:"); _MTL_PRIVATE_DEF_SEL(setDepthWriteEnabled_, "setDepthWriteEnabled:"); _MTL_PRIVATE_DEF_SEL(setDestination_, "setDestination:"); _MTL_PRIVATE_DEF_SEL(setDestinationAlphaBlendFactor_, "setDestinationAlphaBlendFactor:"); _MTL_PRIVATE_DEF_SEL(setDestinationRGBBlendFactor_, "setDestinationRGBBlendFactor:"); _MTL_PRIVATE_DEF_SEL(setDispatchType_, "setDispatchType:"); _MTL_PRIVATE_DEF_SEL(setEndOfEncoderSampleIndex_, "setEndOfEncoderSampleIndex:"); _MTL_PRIVATE_DEF_SEL(setEndOfFragmentSampleIndex_, "setEndOfFragmentSampleIndex:"); _MTL_PRIVATE_DEF_SEL(setEndOfVertexSampleIndex_, "setEndOfVertexSampleIndex:"); _MTL_PRIVATE_DEF_SEL(setErrorOptions_, "setErrorOptions:"); _MTL_PRIVATE_DEF_SEL(setFastMathEnabled_, "setFastMathEnabled:"); _MTL_PRIVATE_DEF_SEL(setFormat_, "setFormat:"); _MTL_PRIVATE_DEF_SEL(setFragmentAccelerationStructure_atBufferIndex_, "setFragmentAccelerationStructure:atBufferIndex:"); _MTL_PRIVATE_DEF_SEL(setFragmentAdditionalBinaryFunctions_, "setFragmentAdditionalBinaryFunctions:"); _MTL_PRIVATE_DEF_SEL(setFragmentBuffer_offset_atIndex_, "setFragmentBuffer:offset:atIndex:"); _MTL_PRIVATE_DEF_SEL(setFragmentBufferOffset_atIndex_, "setFragmentBufferOffset:atIndex:"); _MTL_PRIVATE_DEF_SEL(setFragmentBuffers_offsets_withRange_, "setFragmentBuffers:offsets:withRange:"); _MTL_PRIVATE_DEF_SEL(setFragmentBytes_length_atIndex_, "setFragmentBytes:length:atIndex:"); _MTL_PRIVATE_DEF_SEL(setFragmentFunction_, "setFragmentFunction:"); _MTL_PRIVATE_DEF_SEL(setFragmentIntersectionFunctionTable_atBufferIndex_, "setFragmentIntersectionFunctionTable:atBufferIndex:"); _MTL_PRIVATE_DEF_SEL(setFragmentIntersectionFunctionTables_withBufferRange_, "setFragmentIntersectionFunctionTables:withBufferRange:"); _MTL_PRIVATE_DEF_SEL(setFragmentLinkedFunctions_, "setFragmentLinkedFunctions:"); _MTL_PRIVATE_DEF_SEL(setFragmentPreloadedLibraries_, "setFragmentPreloadedLibraries:"); _MTL_PRIVATE_DEF_SEL(setFragmentSamplerState_atIndex_, "setFragmentSamplerState:atIndex:"); _MTL_PRIVATE_DEF_SEL(setFragmentSamplerState_lodMinClamp_lodMaxClamp_atIndex_, "setFragmentSamplerState:lodMinClamp:lodMaxClamp:atIndex:"); _MTL_PRIVATE_DEF_SEL(setFragmentSamplerStates_lodMinClamps_lodMaxClamps_withRange_, "setFragmentSamplerStates:lodMinClamps:lodMaxClamps:withRange:"); _MTL_PRIVATE_DEF_SEL(setFragmentSamplerStates_withRange_, "setFragmentSamplerStates:withRange:"); _MTL_PRIVATE_DEF_SEL(setFragmentTexture_atIndex_, "setFragmentTexture:atIndex:"); _MTL_PRIVATE_DEF_SEL(setFragmentTextures_withRange_, "setFragmentTextures:withRange:"); _MTL_PRIVATE_DEF_SEL(setFragmentVisibleFunctionTable_atBufferIndex_, "setFragmentVisibleFunctionTable:atBufferIndex:"); _MTL_PRIVATE_DEF_SEL(setFragmentVisibleFunctionTables_withBufferRange_, "setFragmentVisibleFunctionTables:withBufferRange:"); _MTL_PRIVATE_DEF_SEL(setFrontFaceStencil_, "setFrontFaceStencil:"); _MTL_PRIVATE_DEF_SEL(setFrontFacingWinding_, "setFrontFacingWinding:"); _MTL_PRIVATE_DEF_SEL(setFunction_atIndex_, "setFunction:atIndex:"); _MTL_PRIVATE_DEF_SEL(setFunctionCount_, "setFunctionCount:"); _MTL_PRIVATE_DEF_SEL(setFunctionGraphs_, "setFunctionGraphs:"); _MTL_PRIVATE_DEF_SEL(setFunctionName_, "setFunctionName:"); _MTL_PRIVATE_DEF_SEL(setFunctions_, "setFunctions:"); _MTL_PRIVATE_DEF_SEL(setFunctions_withRange_, "setFunctions:withRange:"); _MTL_PRIVATE_DEF_SEL(setGeometryDescriptors_, "setGeometryDescriptors:"); _MTL_PRIVATE_DEF_SEL(setGroups_, "setGroups:"); _MTL_PRIVATE_DEF_SEL(setHazardTrackingMode_, "setHazardTrackingMode:"); _MTL_PRIVATE_DEF_SEL(setHeight_, "setHeight:"); _MTL_PRIVATE_DEF_SEL(setImageblockSampleLength_, "setImageblockSampleLength:"); _MTL_PRIVATE_DEF_SEL(setImageblockWidth_height_, "setImageblockWidth:height:"); _MTL_PRIVATE_DEF_SEL(setIndex_, "setIndex:"); _MTL_PRIVATE_DEF_SEL(setIndexBuffer_, "setIndexBuffer:"); _MTL_PRIVATE_DEF_SEL(setIndexBufferIndex_, "setIndexBufferIndex:"); _MTL_PRIVATE_DEF_SEL(setIndexBufferOffset_, "setIndexBufferOffset:"); _MTL_PRIVATE_DEF_SEL(setIndexType_, "setIndexType:"); _MTL_PRIVATE_DEF_SEL(setIndirectCommandBuffer_atIndex_, "setIndirectCommandBuffer:atIndex:"); _MTL_PRIVATE_DEF_SEL(setIndirectCommandBuffers_withRange_, "setIndirectCommandBuffers:withRange:"); _MTL_PRIVATE_DEF_SEL(setInheritBuffers_, "setInheritBuffers:"); _MTL_PRIVATE_DEF_SEL(setInheritPipelineState_, "setInheritPipelineState:"); _MTL_PRIVATE_DEF_SEL(setInputPrimitiveTopology_, "setInputPrimitiveTopology:"); _MTL_PRIVATE_DEF_SEL(setInsertLibraries_, "setInsertLibraries:"); _MTL_PRIVATE_DEF_SEL(setInstallName_, "setInstallName:"); _MTL_PRIVATE_DEF_SEL(setInstanceCount_, "setInstanceCount:"); _MTL_PRIVATE_DEF_SEL(setInstanceCountBuffer_, "setInstanceCountBuffer:"); _MTL_PRIVATE_DEF_SEL(setInstanceCountBufferOffset_, "setInstanceCountBufferOffset:"); _MTL_PRIVATE_DEF_SEL(setInstanceDescriptorBuffer_, "setInstanceDescriptorBuffer:"); _MTL_PRIVATE_DEF_SEL(setInstanceDescriptorBufferOffset_, "setInstanceDescriptorBufferOffset:"); _MTL_PRIVATE_DEF_SEL(setInstanceDescriptorStride_, "setInstanceDescriptorStride:"); _MTL_PRIVATE_DEF_SEL(setInstanceDescriptorType_, "setInstanceDescriptorType:"); _MTL_PRIVATE_DEF_SEL(setInstancedAccelerationStructures_, "setInstancedAccelerationStructures:"); _MTL_PRIVATE_DEF_SEL(setIntersectionFunctionTable_atBufferIndex_, "setIntersectionFunctionTable:atBufferIndex:"); _MTL_PRIVATE_DEF_SEL(setIntersectionFunctionTable_atIndex_, "setIntersectionFunctionTable:atIndex:"); _MTL_PRIVATE_DEF_SEL(setIntersectionFunctionTableOffset_, "setIntersectionFunctionTableOffset:"); _MTL_PRIVATE_DEF_SEL(setIntersectionFunctionTables_withBufferRange_, "setIntersectionFunctionTables:withBufferRange:"); _MTL_PRIVATE_DEF_SEL(setIntersectionFunctionTables_withRange_, "setIntersectionFunctionTables:withRange:"); _MTL_PRIVATE_DEF_SEL(setKernelBuffer_offset_atIndex_, "setKernelBuffer:offset:atIndex:"); _MTL_PRIVATE_DEF_SEL(setKernelBuffer_offset_attributeStride_atIndex_, "setKernelBuffer:offset:attributeStride:atIndex:"); _MTL_PRIVATE_DEF_SEL(setLabel_, "setLabel:"); _MTL_PRIVATE_DEF_SEL(setLanguageVersion_, "setLanguageVersion:"); _MTL_PRIVATE_DEF_SEL(setLayer_atIndex_, "setLayer:atIndex:"); _MTL_PRIVATE_DEF_SEL(setLevel_, "setLevel:"); _MTL_PRIVATE_DEF_SEL(setLibraries_, "setLibraries:"); _MTL_PRIVATE_DEF_SEL(setLibraryType_, "setLibraryType:"); _MTL_PRIVATE_DEF_SEL(setLinkedFunctions_, "setLinkedFunctions:"); _MTL_PRIVATE_DEF_SEL(setLoadAction_, "setLoadAction:"); _MTL_PRIVATE_DEF_SEL(setLodAverage_, "setLodAverage:"); _MTL_PRIVATE_DEF_SEL(setLodMaxClamp_, "setLodMaxClamp:"); _MTL_PRIVATE_DEF_SEL(setLodMinClamp_, "setLodMinClamp:"); _MTL_PRIVATE_DEF_SEL(setMagFilter_, "setMagFilter:"); _MTL_PRIVATE_DEF_SEL(setMaxAnisotropy_, "setMaxAnisotropy:"); _MTL_PRIVATE_DEF_SEL(setMaxCallStackDepth_, "setMaxCallStackDepth:"); _MTL_PRIVATE_DEF_SEL(setMaxCommandBufferCount_, "setMaxCommandBufferCount:"); _MTL_PRIVATE_DEF_SEL(setMaxCommandsInFlight_, "setMaxCommandsInFlight:"); _MTL_PRIVATE_DEF_SEL(setMaxFragmentBufferBindCount_, "setMaxFragmentBufferBindCount:"); _MTL_PRIVATE_DEF_SEL(setMaxFragmentCallStackDepth_, "setMaxFragmentCallStackDepth:"); _MTL_PRIVATE_DEF_SEL(setMaxInstanceCount_, "setMaxInstanceCount:"); _MTL_PRIVATE_DEF_SEL(setMaxKernelBufferBindCount_, "setMaxKernelBufferBindCount:"); _MTL_PRIVATE_DEF_SEL(setMaxKernelThreadgroupMemoryBindCount_, "setMaxKernelThreadgroupMemoryBindCount:"); _MTL_PRIVATE_DEF_SEL(setMaxMeshBufferBindCount_, "setMaxMeshBufferBindCount:"); _MTL_PRIVATE_DEF_SEL(setMaxMotionTransformCount_, "setMaxMotionTransformCount:"); _MTL_PRIVATE_DEF_SEL(setMaxObjectBufferBindCount_, "setMaxObjectBufferBindCount:"); _MTL_PRIVATE_DEF_SEL(setMaxObjectThreadgroupMemoryBindCount_, "setMaxObjectThreadgroupMemoryBindCount:"); _MTL_PRIVATE_DEF_SEL(setMaxTessellationFactor_, "setMaxTessellationFactor:"); _MTL_PRIVATE_DEF_SEL(setMaxTotalThreadgroupsPerMeshGrid_, "setMaxTotalThreadgroupsPerMeshGrid:"); _MTL_PRIVATE_DEF_SEL(setMaxTotalThreadsPerMeshThreadgroup_, "setMaxTotalThreadsPerMeshThreadgroup:"); _MTL_PRIVATE_DEF_SEL(setMaxTotalThreadsPerObjectThreadgroup_, "setMaxTotalThreadsPerObjectThreadgroup:"); _MTL_PRIVATE_DEF_SEL(setMaxTotalThreadsPerThreadgroup_, "setMaxTotalThreadsPerThreadgroup:"); _MTL_PRIVATE_DEF_SEL(setMaxVertexAmplificationCount_, "setMaxVertexAmplificationCount:"); _MTL_PRIVATE_DEF_SEL(setMaxVertexBufferBindCount_, "setMaxVertexBufferBindCount:"); _MTL_PRIVATE_DEF_SEL(setMaxVertexCallStackDepth_, "setMaxVertexCallStackDepth:"); _MTL_PRIVATE_DEF_SEL(setMeshBuffer_offset_atIndex_, "setMeshBuffer:offset:atIndex:"); _MTL_PRIVATE_DEF_SEL(setMeshBufferOffset_atIndex_, "setMeshBufferOffset:atIndex:"); _MTL_PRIVATE_DEF_SEL(setMeshBuffers_offsets_withRange_, "setMeshBuffers:offsets:withRange:"); _MTL_PRIVATE_DEF_SEL(setMeshBytes_length_atIndex_, "setMeshBytes:length:atIndex:"); _MTL_PRIVATE_DEF_SEL(setMeshFunction_, "setMeshFunction:"); _MTL_PRIVATE_DEF_SEL(setMeshLinkedFunctions_, "setMeshLinkedFunctions:"); _MTL_PRIVATE_DEF_SEL(setMeshSamplerState_atIndex_, "setMeshSamplerState:atIndex:"); _MTL_PRIVATE_DEF_SEL(setMeshSamplerState_lodMinClamp_lodMaxClamp_atIndex_, "setMeshSamplerState:lodMinClamp:lodMaxClamp:atIndex:"); _MTL_PRIVATE_DEF_SEL(setMeshSamplerStates_lodMinClamps_lodMaxClamps_withRange_, "setMeshSamplerStates:lodMinClamps:lodMaxClamps:withRange:"); _MTL_PRIVATE_DEF_SEL(setMeshSamplerStates_withRange_, "setMeshSamplerStates:withRange:"); _MTL_PRIVATE_DEF_SEL(setMeshTexture_atIndex_, "setMeshTexture:atIndex:"); _MTL_PRIVATE_DEF_SEL(setMeshTextures_withRange_, "setMeshTextures:withRange:"); _MTL_PRIVATE_DEF_SEL(setMeshThreadgroupSizeIsMultipleOfThreadExecutionWidth_, "setMeshThreadgroupSizeIsMultipleOfThreadExecutionWidth:"); _MTL_PRIVATE_DEF_SEL(setMinFilter_, "setMinFilter:"); _MTL_PRIVATE_DEF_SEL(setMipFilter_, "setMipFilter:"); _MTL_PRIVATE_DEF_SEL(setMipmapLevelCount_, "setMipmapLevelCount:"); _MTL_PRIVATE_DEF_SEL(setMotionEndBorderMode_, "setMotionEndBorderMode:"); _MTL_PRIVATE_DEF_SEL(setMotionEndTime_, "setMotionEndTime:"); _MTL_PRIVATE_DEF_SEL(setMotionKeyframeCount_, "setMotionKeyframeCount:"); _MTL_PRIVATE_DEF_SEL(setMotionStartBorderMode_, "setMotionStartBorderMode:"); _MTL_PRIVATE_DEF_SEL(setMotionStartTime_, "setMotionStartTime:"); _MTL_PRIVATE_DEF_SEL(setMotionTransformBuffer_, "setMotionTransformBuffer:"); _MTL_PRIVATE_DEF_SEL(setMotionTransformBufferOffset_, "setMotionTransformBufferOffset:"); _MTL_PRIVATE_DEF_SEL(setMotionTransformCount_, "setMotionTransformCount:"); _MTL_PRIVATE_DEF_SEL(setMotionTransformCountBuffer_, "setMotionTransformCountBuffer:"); _MTL_PRIVATE_DEF_SEL(setMotionTransformCountBufferOffset_, "setMotionTransformCountBufferOffset:"); _MTL_PRIVATE_DEF_SEL(setMutability_, "setMutability:"); _MTL_PRIVATE_DEF_SEL(setName_, "setName:"); _MTL_PRIVATE_DEF_SEL(setNodes_, "setNodes:"); _MTL_PRIVATE_DEF_SEL(setNormalizedCoordinates_, "setNormalizedCoordinates:"); _MTL_PRIVATE_DEF_SEL(setObject_atIndexedSubscript_, "setObject:atIndexedSubscript:"); _MTL_PRIVATE_DEF_SEL(setObjectBuffer_offset_atIndex_, "setObjectBuffer:offset:atIndex:"); _MTL_PRIVATE_DEF_SEL(setObjectBufferOffset_atIndex_, "setObjectBufferOffset:atIndex:"); _MTL_PRIVATE_DEF_SEL(setObjectBuffers_offsets_withRange_, "setObjectBuffers:offsets:withRange:"); _MTL_PRIVATE_DEF_SEL(setObjectBytes_length_atIndex_, "setObjectBytes:length:atIndex:"); _MTL_PRIVATE_DEF_SEL(setObjectFunction_, "setObjectFunction:"); _MTL_PRIVATE_DEF_SEL(setObjectLinkedFunctions_, "setObjectLinkedFunctions:"); _MTL_PRIVATE_DEF_SEL(setObjectSamplerState_atIndex_, "setObjectSamplerState:atIndex:"); _MTL_PRIVATE_DEF_SEL(setObjectSamplerState_lodMinClamp_lodMaxClamp_atIndex_, "setObjectSamplerState:lodMinClamp:lodMaxClamp:atIndex:"); _MTL_PRIVATE_DEF_SEL(setObjectSamplerStates_lodMinClamps_lodMaxClamps_withRange_, "setObjectSamplerStates:lodMinClamps:lodMaxClamps:withRange:"); _MTL_PRIVATE_DEF_SEL(setObjectSamplerStates_withRange_, "setObjectSamplerStates:withRange:"); _MTL_PRIVATE_DEF_SEL(setObjectTexture_atIndex_, "setObjectTexture:atIndex:"); _MTL_PRIVATE_DEF_SEL(setObjectTextures_withRange_, "setObjectTextures:withRange:"); _MTL_PRIVATE_DEF_SEL(setObjectThreadgroupMemoryLength_atIndex_, "setObjectThreadgroupMemoryLength:atIndex:"); _MTL_PRIVATE_DEF_SEL(setObjectThreadgroupSizeIsMultipleOfThreadExecutionWidth_, "setObjectThreadgroupSizeIsMultipleOfThreadExecutionWidth:"); _MTL_PRIVATE_DEF_SEL(setOffset_, "setOffset:"); _MTL_PRIVATE_DEF_SEL(setOpaque_, "setOpaque:"); _MTL_PRIVATE_DEF_SEL(setOpaqueCurveIntersectionFunctionWithSignature_atIndex_, "setOpaqueCurveIntersectionFunctionWithSignature:atIndex:"); _MTL_PRIVATE_DEF_SEL(setOpaqueCurveIntersectionFunctionWithSignature_withRange_, "setOpaqueCurveIntersectionFunctionWithSignature:withRange:"); _MTL_PRIVATE_DEF_SEL(setOpaqueTriangleIntersectionFunctionWithSignature_atIndex_, "setOpaqueTriangleIntersectionFunctionWithSignature:atIndex:"); _MTL_PRIVATE_DEF_SEL(setOpaqueTriangleIntersectionFunctionWithSignature_withRange_, "setOpaqueTriangleIntersectionFunctionWithSignature:withRange:"); _MTL_PRIVATE_DEF_SEL(setOptimizationLevel_, "setOptimizationLevel:"); _MTL_PRIVATE_DEF_SEL(setOptions_, "setOptions:"); _MTL_PRIVATE_DEF_SEL(setOutputNode_, "setOutputNode:"); _MTL_PRIVATE_DEF_SEL(setOutputURL_, "setOutputURL:"); _MTL_PRIVATE_DEF_SEL(setPayloadMemoryLength_, "setPayloadMemoryLength:"); _MTL_PRIVATE_DEF_SEL(setPixelFormat_, "setPixelFormat:"); _MTL_PRIVATE_DEF_SEL(setPreloadedLibraries_, "setPreloadedLibraries:"); _MTL_PRIVATE_DEF_SEL(setPreprocessorMacros_, "setPreprocessorMacros:"); _MTL_PRIVATE_DEF_SEL(setPreserveInvariance_, "setPreserveInvariance:"); _MTL_PRIVATE_DEF_SEL(setPrimitiveDataBuffer_, "setPrimitiveDataBuffer:"); _MTL_PRIVATE_DEF_SEL(setPrimitiveDataBufferOffset_, "setPrimitiveDataBufferOffset:"); _MTL_PRIVATE_DEF_SEL(setPrimitiveDataElementSize_, "setPrimitiveDataElementSize:"); _MTL_PRIVATE_DEF_SEL(setPrimitiveDataStride_, "setPrimitiveDataStride:"); _MTL_PRIVATE_DEF_SEL(setPriority_, "setPriority:"); _MTL_PRIVATE_DEF_SEL(setPrivateFunctions_, "setPrivateFunctions:"); _MTL_PRIVATE_DEF_SEL(setPurgeableState_, "setPurgeableState:"); _MTL_PRIVATE_DEF_SEL(setRAddressMode_, "setRAddressMode:"); _MTL_PRIVATE_DEF_SEL(setRadiusBuffer_, "setRadiusBuffer:"); _MTL_PRIVATE_DEF_SEL(setRadiusBufferOffset_, "setRadiusBufferOffset:"); _MTL_PRIVATE_DEF_SEL(setRadiusBuffers_, "setRadiusBuffers:"); _MTL_PRIVATE_DEF_SEL(setRadiusFormat_, "setRadiusFormat:"); _MTL_PRIVATE_DEF_SEL(setRadiusStride_, "setRadiusStride:"); _MTL_PRIVATE_DEF_SEL(setRasterSampleCount_, "setRasterSampleCount:"); _MTL_PRIVATE_DEF_SEL(setRasterizationEnabled_, "setRasterizationEnabled:"); _MTL_PRIVATE_DEF_SEL(setRasterizationRateMap_, "setRasterizationRateMap:"); _MTL_PRIVATE_DEF_SEL(setReadMask_, "setReadMask:"); _MTL_PRIVATE_DEF_SEL(setRenderPipelineState_, "setRenderPipelineState:"); _MTL_PRIVATE_DEF_SEL(setRenderPipelineState_atIndex_, "setRenderPipelineState:atIndex:"); _MTL_PRIVATE_DEF_SEL(setRenderPipelineStates_withRange_, "setRenderPipelineStates:withRange:"); _MTL_PRIVATE_DEF_SEL(setRenderTargetArrayLength_, "setRenderTargetArrayLength:"); _MTL_PRIVATE_DEF_SEL(setRenderTargetHeight_, "setRenderTargetHeight:"); _MTL_PRIVATE_DEF_SEL(setRenderTargetWidth_, "setRenderTargetWidth:"); _MTL_PRIVATE_DEF_SEL(setResolveDepthPlane_, "setResolveDepthPlane:"); _MTL_PRIVATE_DEF_SEL(setResolveLevel_, "setResolveLevel:"); _MTL_PRIVATE_DEF_SEL(setResolveSlice_, "setResolveSlice:"); _MTL_PRIVATE_DEF_SEL(setResolveTexture_, "setResolveTexture:"); _MTL_PRIVATE_DEF_SEL(setResourceOptions_, "setResourceOptions:"); _MTL_PRIVATE_DEF_SEL(setRetainedReferences_, "setRetainedReferences:"); _MTL_PRIVATE_DEF_SEL(setRgbBlendOperation_, "setRgbBlendOperation:"); _MTL_PRIVATE_DEF_SEL(setSAddressMode_, "setSAddressMode:"); _MTL_PRIVATE_DEF_SEL(setSampleBuffer_, "setSampleBuffer:"); _MTL_PRIVATE_DEF_SEL(setSampleCount_, "setSampleCount:"); _MTL_PRIVATE_DEF_SEL(setSamplePositions_count_, "setSamplePositions:count:"); _MTL_PRIVATE_DEF_SEL(setSamplerState_atIndex_, "setSamplerState:atIndex:"); _MTL_PRIVATE_DEF_SEL(setSamplerState_lodMinClamp_lodMaxClamp_atIndex_, "setSamplerState:lodMinClamp:lodMaxClamp:atIndex:"); _MTL_PRIVATE_DEF_SEL(setSamplerStates_lodMinClamps_lodMaxClamps_withRange_, "setSamplerStates:lodMinClamps:lodMaxClamps:withRange:"); _MTL_PRIVATE_DEF_SEL(setSamplerStates_withRange_, "setSamplerStates:withRange:"); _MTL_PRIVATE_DEF_SEL(setScissorRect_, "setScissorRect:"); _MTL_PRIVATE_DEF_SEL(setScissorRects_count_, "setScissorRects:count:"); _MTL_PRIVATE_DEF_SEL(setScratchBufferAllocator_, "setScratchBufferAllocator:"); _MTL_PRIVATE_DEF_SEL(setScreenSize_, "setScreenSize:"); _MTL_PRIVATE_DEF_SEL(setSegmentControlPointCount_, "setSegmentControlPointCount:"); _MTL_PRIVATE_DEF_SEL(setSegmentCount_, "setSegmentCount:"); _MTL_PRIVATE_DEF_SEL(setShouldMaximizeConcurrentCompilation_, "setShouldMaximizeConcurrentCompilation:"); _MTL_PRIVATE_DEF_SEL(setSignaledValue_, "setSignaledValue:"); _MTL_PRIVATE_DEF_SEL(setSize_, "setSize:"); _MTL_PRIVATE_DEF_SEL(setSlice_, "setSlice:"); _MTL_PRIVATE_DEF_SEL(setSourceAlphaBlendFactor_, "setSourceAlphaBlendFactor:"); _MTL_PRIVATE_DEF_SEL(setSourceRGBBlendFactor_, "setSourceRGBBlendFactor:"); _MTL_PRIVATE_DEF_SEL(setSparsePageSize_, "setSparsePageSize:"); _MTL_PRIVATE_DEF_SEL(setSpecializedName_, "setSpecializedName:"); _MTL_PRIVATE_DEF_SEL(setStageInRegion_, "setStageInRegion:"); _MTL_PRIVATE_DEF_SEL(setStageInRegionWithIndirectBuffer_indirectBufferOffset_, "setStageInRegionWithIndirectBuffer:indirectBufferOffset:"); _MTL_PRIVATE_DEF_SEL(setStageInputDescriptor_, "setStageInputDescriptor:"); _MTL_PRIVATE_DEF_SEL(setStartOfEncoderSampleIndex_, "setStartOfEncoderSampleIndex:"); _MTL_PRIVATE_DEF_SEL(setStartOfFragmentSampleIndex_, "setStartOfFragmentSampleIndex:"); _MTL_PRIVATE_DEF_SEL(setStartOfVertexSampleIndex_, "setStartOfVertexSampleIndex:"); _MTL_PRIVATE_DEF_SEL(setStencilAttachment_, "setStencilAttachment:"); _MTL_PRIVATE_DEF_SEL(setStencilAttachmentPixelFormat_, "setStencilAttachmentPixelFormat:"); _MTL_PRIVATE_DEF_SEL(setStencilCompareFunction_, "setStencilCompareFunction:"); _MTL_PRIVATE_DEF_SEL(setStencilFailureOperation_, "setStencilFailureOperation:"); _MTL_PRIVATE_DEF_SEL(setStencilFrontReferenceValue_backReferenceValue_, "setStencilFrontReferenceValue:backReferenceValue:"); _MTL_PRIVATE_DEF_SEL(setStencilReferenceValue_, "setStencilReferenceValue:"); _MTL_PRIVATE_DEF_SEL(setStencilResolveFilter_, "setStencilResolveFilter:"); _MTL_PRIVATE_DEF_SEL(setStencilStoreAction_, "setStencilStoreAction:"); _MTL_PRIVATE_DEF_SEL(setStencilStoreActionOptions_, "setStencilStoreActionOptions:"); _MTL_PRIVATE_DEF_SEL(setStepFunction_, "setStepFunction:"); _MTL_PRIVATE_DEF_SEL(setStepRate_, "setStepRate:"); _MTL_PRIVATE_DEF_SEL(setStorageMode_, "setStorageMode:"); _MTL_PRIVATE_DEF_SEL(setStoreAction_, "setStoreAction:"); _MTL_PRIVATE_DEF_SEL(setStoreActionOptions_, "setStoreActionOptions:"); _MTL_PRIVATE_DEF_SEL(setStride_, "setStride:"); _MTL_PRIVATE_DEF_SEL(setSupportAddingBinaryFunctions_, "setSupportAddingBinaryFunctions:"); _MTL_PRIVATE_DEF_SEL(setSupportAddingFragmentBinaryFunctions_, "setSupportAddingFragmentBinaryFunctions:"); _MTL_PRIVATE_DEF_SEL(setSupportAddingVertexBinaryFunctions_, "setSupportAddingVertexBinaryFunctions:"); _MTL_PRIVATE_DEF_SEL(setSupportArgumentBuffers_, "setSupportArgumentBuffers:"); _MTL_PRIVATE_DEF_SEL(setSupportDynamicAttributeStride_, "setSupportDynamicAttributeStride:"); _MTL_PRIVATE_DEF_SEL(setSupportIndirectCommandBuffers_, "setSupportIndirectCommandBuffers:"); _MTL_PRIVATE_DEF_SEL(setSupportRayTracing_, "setSupportRayTracing:"); _MTL_PRIVATE_DEF_SEL(setSwizzle_, "setSwizzle:"); _MTL_PRIVATE_DEF_SEL(setTAddressMode_, "setTAddressMode:"); _MTL_PRIVATE_DEF_SEL(setTessellationControlPointIndexType_, "setTessellationControlPointIndexType:"); _MTL_PRIVATE_DEF_SEL(setTessellationFactorBuffer_offset_instanceStride_, "setTessellationFactorBuffer:offset:instanceStride:"); _MTL_PRIVATE_DEF_SEL(setTessellationFactorFormat_, "setTessellationFactorFormat:"); _MTL_PRIVATE_DEF_SEL(setTessellationFactorScale_, "setTessellationFactorScale:"); _MTL_PRIVATE_DEF_SEL(setTessellationFactorScaleEnabled_, "setTessellationFactorScaleEnabled:"); _MTL_PRIVATE_DEF_SEL(setTessellationFactorStepFunction_, "setTessellationFactorStepFunction:"); _MTL_PRIVATE_DEF_SEL(setTessellationOutputWindingOrder_, "setTessellationOutputWindingOrder:"); _MTL_PRIVATE_DEF_SEL(setTessellationPartitionMode_, "setTessellationPartitionMode:"); _MTL_PRIVATE_DEF_SEL(setTexture_, "setTexture:"); _MTL_PRIVATE_DEF_SEL(setTexture_atIndex_, "setTexture:atIndex:"); _MTL_PRIVATE_DEF_SEL(setTextureType_, "setTextureType:"); _MTL_PRIVATE_DEF_SEL(setTextures_withRange_, "setTextures:withRange:"); _MTL_PRIVATE_DEF_SEL(setThreadGroupSizeIsMultipleOfThreadExecutionWidth_, "setThreadGroupSizeIsMultipleOfThreadExecutionWidth:"); _MTL_PRIVATE_DEF_SEL(setThreadgroupMemoryLength_, "setThreadgroupMemoryLength:"); _MTL_PRIVATE_DEF_SEL(setThreadgroupMemoryLength_atIndex_, "setThreadgroupMemoryLength:atIndex:"); _MTL_PRIVATE_DEF_SEL(setThreadgroupMemoryLength_offset_atIndex_, "setThreadgroupMemoryLength:offset:atIndex:"); _MTL_PRIVATE_DEF_SEL(setThreadgroupSizeMatchesTileSize_, "setThreadgroupSizeMatchesTileSize:"); _MTL_PRIVATE_DEF_SEL(setTileAccelerationStructure_atBufferIndex_, "setTileAccelerationStructure:atBufferIndex:"); _MTL_PRIVATE_DEF_SEL(setTileAdditionalBinaryFunctions_, "setTileAdditionalBinaryFunctions:"); _MTL_PRIVATE_DEF_SEL(setTileBuffer_offset_atIndex_, "setTileBuffer:offset:atIndex:"); _MTL_PRIVATE_DEF_SEL(setTileBufferOffset_atIndex_, "setTileBufferOffset:atIndex:"); _MTL_PRIVATE_DEF_SEL(setTileBuffers_offsets_withRange_, "setTileBuffers:offsets:withRange:"); _MTL_PRIVATE_DEF_SEL(setTileBytes_length_atIndex_, "setTileBytes:length:atIndex:"); _MTL_PRIVATE_DEF_SEL(setTileFunction_, "setTileFunction:"); _MTL_PRIVATE_DEF_SEL(setTileHeight_, "setTileHeight:"); _MTL_PRIVATE_DEF_SEL(setTileIntersectionFunctionTable_atBufferIndex_, "setTileIntersectionFunctionTable:atBufferIndex:"); _MTL_PRIVATE_DEF_SEL(setTileIntersectionFunctionTables_withBufferRange_, "setTileIntersectionFunctionTables:withBufferRange:"); _MTL_PRIVATE_DEF_SEL(setTileSamplerState_atIndex_, "setTileSamplerState:atIndex:"); _MTL_PRIVATE_DEF_SEL(setTileSamplerState_lodMinClamp_lodMaxClamp_atIndex_, "setTileSamplerState:lodMinClamp:lodMaxClamp:atIndex:"); _MTL_PRIVATE_DEF_SEL(setTileSamplerStates_lodMinClamps_lodMaxClamps_withRange_, "setTileSamplerStates:lodMinClamps:lodMaxClamps:withRange:"); _MTL_PRIVATE_DEF_SEL(setTileSamplerStates_withRange_, "setTileSamplerStates:withRange:"); _MTL_PRIVATE_DEF_SEL(setTileTexture_atIndex_, "setTileTexture:atIndex:"); _MTL_PRIVATE_DEF_SEL(setTileTextures_withRange_, "setTileTextures:withRange:"); _MTL_PRIVATE_DEF_SEL(setTileVisibleFunctionTable_atBufferIndex_, "setTileVisibleFunctionTable:atBufferIndex:"); _MTL_PRIVATE_DEF_SEL(setTileVisibleFunctionTables_withBufferRange_, "setTileVisibleFunctionTables:withBufferRange:"); _MTL_PRIVATE_DEF_SEL(setTileWidth_, "setTileWidth:"); _MTL_PRIVATE_DEF_SEL(setTransformationMatrixBuffer_, "setTransformationMatrixBuffer:"); _MTL_PRIVATE_DEF_SEL(setTransformationMatrixBufferOffset_, "setTransformationMatrixBufferOffset:"); _MTL_PRIVATE_DEF_SEL(setTriangleCount_, "setTriangleCount:"); _MTL_PRIVATE_DEF_SEL(setTriangleFillMode_, "setTriangleFillMode:"); _MTL_PRIVATE_DEF_SEL(setType_, "setType:"); _MTL_PRIVATE_DEF_SEL(setUrl_, "setUrl:"); _MTL_PRIVATE_DEF_SEL(setUsage_, "setUsage:"); _MTL_PRIVATE_DEF_SEL(setVertexAccelerationStructure_atBufferIndex_, "setVertexAccelerationStructure:atBufferIndex:"); _MTL_PRIVATE_DEF_SEL(setVertexAdditionalBinaryFunctions_, "setVertexAdditionalBinaryFunctions:"); _MTL_PRIVATE_DEF_SEL(setVertexAmplificationCount_viewMappings_, "setVertexAmplificationCount:viewMappings:"); _MTL_PRIVATE_DEF_SEL(setVertexBuffer_, "setVertexBuffer:"); _MTL_PRIVATE_DEF_SEL(setVertexBuffer_offset_atIndex_, "setVertexBuffer:offset:atIndex:"); _MTL_PRIVATE_DEF_SEL(setVertexBuffer_offset_attributeStride_atIndex_, "setVertexBuffer:offset:attributeStride:atIndex:"); _MTL_PRIVATE_DEF_SEL(setVertexBufferOffset_, "setVertexBufferOffset:"); _MTL_PRIVATE_DEF_SEL(setVertexBufferOffset_atIndex_, "setVertexBufferOffset:atIndex:"); _MTL_PRIVATE_DEF_SEL(setVertexBufferOffset_attributeStride_atIndex_, "setVertexBufferOffset:attributeStride:atIndex:"); _MTL_PRIVATE_DEF_SEL(setVertexBuffers_, "setVertexBuffers:"); _MTL_PRIVATE_DEF_SEL(setVertexBuffers_offsets_attributeStrides_withRange_, "setVertexBuffers:offsets:attributeStrides:withRange:"); _MTL_PRIVATE_DEF_SEL(setVertexBuffers_offsets_withRange_, "setVertexBuffers:offsets:withRange:"); _MTL_PRIVATE_DEF_SEL(setVertexBytes_length_atIndex_, "setVertexBytes:length:atIndex:"); _MTL_PRIVATE_DEF_SEL(setVertexBytes_length_attributeStride_atIndex_, "setVertexBytes:length:attributeStride:atIndex:"); _MTL_PRIVATE_DEF_SEL(setVertexDescriptor_, "setVertexDescriptor:"); _MTL_PRIVATE_DEF_SEL(setVertexFormat_, "setVertexFormat:"); _MTL_PRIVATE_DEF_SEL(setVertexFunction_, "setVertexFunction:"); _MTL_PRIVATE_DEF_SEL(setVertexIntersectionFunctionTable_atBufferIndex_, "setVertexIntersectionFunctionTable:atBufferIndex:"); _MTL_PRIVATE_DEF_SEL(setVertexIntersectionFunctionTables_withBufferRange_, "setVertexIntersectionFunctionTables:withBufferRange:"); _MTL_PRIVATE_DEF_SEL(setVertexLinkedFunctions_, "setVertexLinkedFunctions:"); _MTL_PRIVATE_DEF_SEL(setVertexPreloadedLibraries_, "setVertexPreloadedLibraries:"); _MTL_PRIVATE_DEF_SEL(setVertexSamplerState_atIndex_, "setVertexSamplerState:atIndex:"); _MTL_PRIVATE_DEF_SEL(setVertexSamplerState_lodMinClamp_lodMaxClamp_atIndex_, "setVertexSamplerState:lodMinClamp:lodMaxClamp:atIndex:"); _MTL_PRIVATE_DEF_SEL(setVertexSamplerStates_lodMinClamps_lodMaxClamps_withRange_, "setVertexSamplerStates:lodMinClamps:lodMaxClamps:withRange:"); _MTL_PRIVATE_DEF_SEL(setVertexSamplerStates_withRange_, "setVertexSamplerStates:withRange:"); _MTL_PRIVATE_DEF_SEL(setVertexStride_, "setVertexStride:"); _MTL_PRIVATE_DEF_SEL(setVertexTexture_atIndex_, "setVertexTexture:atIndex:"); _MTL_PRIVATE_DEF_SEL(setVertexTextures_withRange_, "setVertexTextures:withRange:"); _MTL_PRIVATE_DEF_SEL(setVertexVisibleFunctionTable_atBufferIndex_, "setVertexVisibleFunctionTable:atBufferIndex:"); _MTL_PRIVATE_DEF_SEL(setVertexVisibleFunctionTables_withBufferRange_, "setVertexVisibleFunctionTables:withBufferRange:"); _MTL_PRIVATE_DEF_SEL(setViewport_, "setViewport:"); _MTL_PRIVATE_DEF_SEL(setViewports_count_, "setViewports:count:"); _MTL_PRIVATE_DEF_SEL(setVisibilityResultBuffer_, "setVisibilityResultBuffer:"); _MTL_PRIVATE_DEF_SEL(setVisibilityResultMode_offset_, "setVisibilityResultMode:offset:"); _MTL_PRIVATE_DEF_SEL(setVisibleFunctionTable_atBufferIndex_, "setVisibleFunctionTable:atBufferIndex:"); _MTL_PRIVATE_DEF_SEL(setVisibleFunctionTable_atIndex_, "setVisibleFunctionTable:atIndex:"); _MTL_PRIVATE_DEF_SEL(setVisibleFunctionTables_withBufferRange_, "setVisibleFunctionTables:withBufferRange:"); _MTL_PRIVATE_DEF_SEL(setVisibleFunctionTables_withRange_, "setVisibleFunctionTables:withRange:"); _MTL_PRIVATE_DEF_SEL(setWidth_, "setWidth:"); _MTL_PRIVATE_DEF_SEL(setWriteMask_, "setWriteMask:"); _MTL_PRIVATE_DEF_SEL(sharedCaptureManager, "sharedCaptureManager"); _MTL_PRIVATE_DEF_SEL(shouldMaximizeConcurrentCompilation, "shouldMaximizeConcurrentCompilation"); _MTL_PRIVATE_DEF_SEL(signalEvent_value_, "signalEvent:value:"); _MTL_PRIVATE_DEF_SEL(signaledValue, "signaledValue"); _MTL_PRIVATE_DEF_SEL(size, "size"); _MTL_PRIVATE_DEF_SEL(slice, "slice"); _MTL_PRIVATE_DEF_SEL(sourceAlphaBlendFactor, "sourceAlphaBlendFactor"); _MTL_PRIVATE_DEF_SEL(sourceRGBBlendFactor, "sourceRGBBlendFactor"); _MTL_PRIVATE_DEF_SEL(sparsePageSize, "sparsePageSize"); _MTL_PRIVATE_DEF_SEL(sparseTileSizeInBytes, "sparseTileSizeInBytes"); _MTL_PRIVATE_DEF_SEL(sparseTileSizeInBytesForSparsePageSize_, "sparseTileSizeInBytesForSparsePageSize:"); _MTL_PRIVATE_DEF_SEL(sparseTileSizeWithTextureType_pixelFormat_sampleCount_, "sparseTileSizeWithTextureType:pixelFormat:sampleCount:"); _MTL_PRIVATE_DEF_SEL(sparseTileSizeWithTextureType_pixelFormat_sampleCount_sparsePageSize_, "sparseTileSizeWithTextureType:pixelFormat:sampleCount:sparsePageSize:"); _MTL_PRIVATE_DEF_SEL(specializedName, "specializedName"); _MTL_PRIVATE_DEF_SEL(stageInputAttributes, "stageInputAttributes"); _MTL_PRIVATE_DEF_SEL(stageInputDescriptor, "stageInputDescriptor"); _MTL_PRIVATE_DEF_SEL(stageInputOutputDescriptor, "stageInputOutputDescriptor"); _MTL_PRIVATE_DEF_SEL(startCaptureWithCommandQueue_, "startCaptureWithCommandQueue:"); _MTL_PRIVATE_DEF_SEL(startCaptureWithDescriptor_error_, "startCaptureWithDescriptor:error:"); _MTL_PRIVATE_DEF_SEL(startCaptureWithDevice_, "startCaptureWithDevice:"); _MTL_PRIVATE_DEF_SEL(startCaptureWithScope_, "startCaptureWithScope:"); _MTL_PRIVATE_DEF_SEL(startOfEncoderSampleIndex, "startOfEncoderSampleIndex"); _MTL_PRIVATE_DEF_SEL(startOfFragmentSampleIndex, "startOfFragmentSampleIndex"); _MTL_PRIVATE_DEF_SEL(startOfVertexSampleIndex, "startOfVertexSampleIndex"); _MTL_PRIVATE_DEF_SEL(staticThreadgroupMemoryLength, "staticThreadgroupMemoryLength"); _MTL_PRIVATE_DEF_SEL(status, "status"); _MTL_PRIVATE_DEF_SEL(stencilAttachment, "stencilAttachment"); _MTL_PRIVATE_DEF_SEL(stencilAttachmentPixelFormat, "stencilAttachmentPixelFormat"); _MTL_PRIVATE_DEF_SEL(stencilCompareFunction, "stencilCompareFunction"); _MTL_PRIVATE_DEF_SEL(stencilFailureOperation, "stencilFailureOperation"); _MTL_PRIVATE_DEF_SEL(stencilResolveFilter, "stencilResolveFilter"); _MTL_PRIVATE_DEF_SEL(stepFunction, "stepFunction"); _MTL_PRIVATE_DEF_SEL(stepRate, "stepRate"); _MTL_PRIVATE_DEF_SEL(stopCapture, "stopCapture"); _MTL_PRIVATE_DEF_SEL(storageMode, "storageMode"); _MTL_PRIVATE_DEF_SEL(storeAction, "storeAction"); _MTL_PRIVATE_DEF_SEL(storeActionOptions, "storeActionOptions"); _MTL_PRIVATE_DEF_SEL(stride, "stride"); _MTL_PRIVATE_DEF_SEL(structType, "structType"); _MTL_PRIVATE_DEF_SEL(supportAddingBinaryFunctions, "supportAddingBinaryFunctions"); _MTL_PRIVATE_DEF_SEL(supportAddingFragmentBinaryFunctions, "supportAddingFragmentBinaryFunctions"); _MTL_PRIVATE_DEF_SEL(supportAddingVertexBinaryFunctions, "supportAddingVertexBinaryFunctions"); _MTL_PRIVATE_DEF_SEL(supportArgumentBuffers, "supportArgumentBuffers"); _MTL_PRIVATE_DEF_SEL(supportDynamicAttributeStride, "supportDynamicAttributeStride"); _MTL_PRIVATE_DEF_SEL(supportIndirectCommandBuffers, "supportIndirectCommandBuffers"); _MTL_PRIVATE_DEF_SEL(supportRayTracing, "supportRayTracing"); _MTL_PRIVATE_DEF_SEL(supports32BitFloatFiltering, "supports32BitFloatFiltering"); _MTL_PRIVATE_DEF_SEL(supports32BitMSAA, "supports32BitMSAA"); _MTL_PRIVATE_DEF_SEL(supportsBCTextureCompression, "supportsBCTextureCompression"); _MTL_PRIVATE_DEF_SEL(supportsCounterSampling_, "supportsCounterSampling:"); _MTL_PRIVATE_DEF_SEL(supportsDestination_, "supportsDestination:"); _MTL_PRIVATE_DEF_SEL(supportsDynamicLibraries, "supportsDynamicLibraries"); _MTL_PRIVATE_DEF_SEL(supportsFamily_, "supportsFamily:"); _MTL_PRIVATE_DEF_SEL(supportsFeatureSet_, "supportsFeatureSet:"); _MTL_PRIVATE_DEF_SEL(supportsFunctionPointers, "supportsFunctionPointers"); _MTL_PRIVATE_DEF_SEL(supportsFunctionPointersFromRender, "supportsFunctionPointersFromRender"); _MTL_PRIVATE_DEF_SEL(supportsPrimitiveMotionBlur, "supportsPrimitiveMotionBlur"); _MTL_PRIVATE_DEF_SEL(supportsPullModelInterpolation, "supportsPullModelInterpolation"); _MTL_PRIVATE_DEF_SEL(supportsQueryTextureLOD, "supportsQueryTextureLOD"); _MTL_PRIVATE_DEF_SEL(supportsRasterizationRateMapWithLayerCount_, "supportsRasterizationRateMapWithLayerCount:"); _MTL_PRIVATE_DEF_SEL(supportsRaytracing, "supportsRaytracing"); _MTL_PRIVATE_DEF_SEL(supportsRaytracingFromRender, "supportsRaytracingFromRender"); _MTL_PRIVATE_DEF_SEL(supportsRenderDynamicLibraries, "supportsRenderDynamicLibraries"); _MTL_PRIVATE_DEF_SEL(supportsShaderBarycentricCoordinates, "supportsShaderBarycentricCoordinates"); _MTL_PRIVATE_DEF_SEL(supportsTextureSampleCount_, "supportsTextureSampleCount:"); _MTL_PRIVATE_DEF_SEL(supportsVertexAmplificationCount_, "supportsVertexAmplificationCount:"); _MTL_PRIVATE_DEF_SEL(swizzle, "swizzle"); _MTL_PRIVATE_DEF_SEL(synchronizeResource_, "synchronizeResource:"); _MTL_PRIVATE_DEF_SEL(synchronizeTexture_slice_level_, "synchronizeTexture:slice:level:"); _MTL_PRIVATE_DEF_SEL(tAddressMode, "tAddressMode"); _MTL_PRIVATE_DEF_SEL(tailSizeInBytes, "tailSizeInBytes"); _MTL_PRIVATE_DEF_SEL(tessellationControlPointIndexType, "tessellationControlPointIndexType"); _MTL_PRIVATE_DEF_SEL(tessellationFactorFormat, "tessellationFactorFormat"); _MTL_PRIVATE_DEF_SEL(tessellationFactorStepFunction, "tessellationFactorStepFunction"); _MTL_PRIVATE_DEF_SEL(tessellationOutputWindingOrder, "tessellationOutputWindingOrder"); _MTL_PRIVATE_DEF_SEL(tessellationPartitionMode, "tessellationPartitionMode"); _MTL_PRIVATE_DEF_SEL(texture, "texture"); _MTL_PRIVATE_DEF_SEL(texture2DDescriptorWithPixelFormat_width_height_mipmapped_, "texture2DDescriptorWithPixelFormat:width:height:mipmapped:"); _MTL_PRIVATE_DEF_SEL(textureBarrier, "textureBarrier"); _MTL_PRIVATE_DEF_SEL(textureBufferDescriptorWithPixelFormat_width_resourceOptions_usage_, "textureBufferDescriptorWithPixelFormat:width:resourceOptions:usage:"); _MTL_PRIVATE_DEF_SEL(textureCubeDescriptorWithPixelFormat_size_mipmapped_, "textureCubeDescriptorWithPixelFormat:size:mipmapped:"); _MTL_PRIVATE_DEF_SEL(textureDataType, "textureDataType"); _MTL_PRIVATE_DEF_SEL(textureReferenceType, "textureReferenceType"); _MTL_PRIVATE_DEF_SEL(textureType, "textureType"); _MTL_PRIVATE_DEF_SEL(threadExecutionWidth, "threadExecutionWidth"); _MTL_PRIVATE_DEF_SEL(threadGroupSizeIsMultipleOfThreadExecutionWidth, "threadGroupSizeIsMultipleOfThreadExecutionWidth"); _MTL_PRIVATE_DEF_SEL(threadgroupMemoryAlignment, "threadgroupMemoryAlignment"); _MTL_PRIVATE_DEF_SEL(threadgroupMemoryDataSize, "threadgroupMemoryDataSize"); _MTL_PRIVATE_DEF_SEL(threadgroupMemoryLength, "threadgroupMemoryLength"); _MTL_PRIVATE_DEF_SEL(threadgroupSizeMatchesTileSize, "threadgroupSizeMatchesTileSize"); _MTL_PRIVATE_DEF_SEL(tileAdditionalBinaryFunctions, "tileAdditionalBinaryFunctions"); _MTL_PRIVATE_DEF_SEL(tileArguments, "tileArguments"); _MTL_PRIVATE_DEF_SEL(tileBindings, "tileBindings"); _MTL_PRIVATE_DEF_SEL(tileBuffers, "tileBuffers"); _MTL_PRIVATE_DEF_SEL(tileFunction, "tileFunction"); _MTL_PRIVATE_DEF_SEL(tileHeight, "tileHeight"); _MTL_PRIVATE_DEF_SEL(tileWidth, "tileWidth"); _MTL_PRIVATE_DEF_SEL(transformationMatrixBuffer, "transformationMatrixBuffer"); _MTL_PRIVATE_DEF_SEL(transformationMatrixBufferOffset, "transformationMatrixBufferOffset"); _MTL_PRIVATE_DEF_SEL(triangleCount, "triangleCount"); _MTL_PRIVATE_DEF_SEL(tryCancel, "tryCancel"); _MTL_PRIVATE_DEF_SEL(type, "type"); _MTL_PRIVATE_DEF_SEL(updateFence_, "updateFence:"); _MTL_PRIVATE_DEF_SEL(updateFence_afterStages_, "updateFence:afterStages:"); _MTL_PRIVATE_DEF_SEL(updateTextureMapping_mode_indirectBuffer_indirectBufferOffset_, "updateTextureMapping:mode:indirectBuffer:indirectBufferOffset:"); _MTL_PRIVATE_DEF_SEL(updateTextureMapping_mode_region_mipLevel_slice_, "updateTextureMapping:mode:region:mipLevel:slice:"); _MTL_PRIVATE_DEF_SEL(updateTextureMappings_mode_regions_mipLevels_slices_numRegions_, "updateTextureMappings:mode:regions:mipLevels:slices:numRegions:"); _MTL_PRIVATE_DEF_SEL(url, "url"); _MTL_PRIVATE_DEF_SEL(usage, "usage"); _MTL_PRIVATE_DEF_SEL(useHeap_, "useHeap:"); _MTL_PRIVATE_DEF_SEL(useHeap_stages_, "useHeap:stages:"); _MTL_PRIVATE_DEF_SEL(useHeaps_count_, "useHeaps:count:"); _MTL_PRIVATE_DEF_SEL(useHeaps_count_stages_, "useHeaps:count:stages:"); _MTL_PRIVATE_DEF_SEL(useResource_usage_, "useResource:usage:"); _MTL_PRIVATE_DEF_SEL(useResource_usage_stages_, "useResource:usage:stages:"); _MTL_PRIVATE_DEF_SEL(useResources_count_usage_, "useResources:count:usage:"); _MTL_PRIVATE_DEF_SEL(useResources_count_usage_stages_, "useResources:count:usage:stages:"); _MTL_PRIVATE_DEF_SEL(usedSize, "usedSize"); _MTL_PRIVATE_DEF_SEL(vertexAdditionalBinaryFunctions, "vertexAdditionalBinaryFunctions"); _MTL_PRIVATE_DEF_SEL(vertexArguments, "vertexArguments"); _MTL_PRIVATE_DEF_SEL(vertexAttributes, "vertexAttributes"); _MTL_PRIVATE_DEF_SEL(vertexBindings, "vertexBindings"); _MTL_PRIVATE_DEF_SEL(vertexBuffer, "vertexBuffer"); _MTL_PRIVATE_DEF_SEL(vertexBufferOffset, "vertexBufferOffset"); _MTL_PRIVATE_DEF_SEL(vertexBuffers, "vertexBuffers"); _MTL_PRIVATE_DEF_SEL(vertexDescriptor, "vertexDescriptor"); _MTL_PRIVATE_DEF_SEL(vertexFormat, "vertexFormat"); _MTL_PRIVATE_DEF_SEL(vertexFunction, "vertexFunction"); _MTL_PRIVATE_DEF_SEL(vertexLinkedFunctions, "vertexLinkedFunctions"); _MTL_PRIVATE_DEF_SEL(vertexPreloadedLibraries, "vertexPreloadedLibraries"); _MTL_PRIVATE_DEF_SEL(vertexStride, "vertexStride"); _MTL_PRIVATE_DEF_SEL(vertical, "vertical"); _MTL_PRIVATE_DEF_SEL(verticalSampleStorage, "verticalSampleStorage"); _MTL_PRIVATE_DEF_SEL(visibilityResultBuffer, "visibilityResultBuffer"); _MTL_PRIVATE_DEF_SEL(visibleFunctionTableDescriptor, "visibleFunctionTableDescriptor"); _MTL_PRIVATE_DEF_SEL(waitForEvent_value_, "waitForEvent:value:"); _MTL_PRIVATE_DEF_SEL(waitForFence_, "waitForFence:"); _MTL_PRIVATE_DEF_SEL(waitForFence_beforeStages_, "waitForFence:beforeStages:"); _MTL_PRIVATE_DEF_SEL(waitUntilCompleted, "waitUntilCompleted"); _MTL_PRIVATE_DEF_SEL(waitUntilScheduled, "waitUntilScheduled"); _MTL_PRIVATE_DEF_SEL(width, "width"); _MTL_PRIVATE_DEF_SEL(writeCompactedAccelerationStructureSize_toBuffer_offset_, "writeCompactedAccelerationStructureSize:toBuffer:offset:"); _MTL_PRIVATE_DEF_SEL(writeCompactedAccelerationStructureSize_toBuffer_offset_sizeDataType_, "writeCompactedAccelerationStructureSize:toBuffer:offset:sizeDataType:"); _MTL_PRIVATE_DEF_SEL(writeMask, "writeMask"); } #include <CoreFoundation/CoreFoundation.h> #include <functional> namespace MTL { using DrawablePresentedHandler = void (^)(class Drawable*); using DrawablePresentedHandlerFunction = std::function<void(class Drawable*)>; class Drawable : public NS::Referencing<Drawable> { public: void addPresentedHandler(const MTL::DrawablePresentedHandlerFunction& function); void present(); void presentAtTime(CFTimeInterval presentationTime); void presentAfterMinimumDuration(CFTimeInterval duration); void addPresentedHandler(const MTL::DrawablePresentedHandler block); CFTimeInterval presentedTime() const; NS::UInteger drawableID() const; }; } _MTL_INLINE void MTL::Drawable::addPresentedHandler(const MTL::DrawablePresentedHandlerFunction& function) { __block DrawablePresentedHandlerFunction blockFunction = function; addPresentedHandler(^(Drawable* pDrawable) { blockFunction(pDrawable); }); } _MTL_INLINE void MTL::Drawable::present() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(present)); } _MTL_INLINE void MTL::Drawable::presentAtTime(CFTimeInterval presentationTime) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(presentAtTime_), presentationTime); } _MTL_INLINE void MTL::Drawable::presentAfterMinimumDuration(CFTimeInterval duration) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(presentAfterMinimumDuration_), duration); } _MTL_INLINE void MTL::Drawable::addPresentedHandler(const MTL::DrawablePresentedHandler block) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(addPresentedHandler_), block); } _MTL_INLINE CFTimeInterval MTL::Drawable::presentedTime() const { return Object::sendMessage<CFTimeInterval>(this, _MTL_PRIVATE_SEL(presentedTime)); } _MTL_INLINE NS::UInteger MTL::Drawable::drawableID() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(drawableID)); } #pragma once #pragma once namespace MTL { _MTL_ENUM(NS::UInteger, PixelFormat) { PixelFormatInvalid = 0, PixelFormatA8Unorm = 1, PixelFormatR8Unorm = 10, PixelFormatR8Unorm_sRGB = 11, PixelFormatR8Snorm = 12, PixelFormatR8Uint = 13, PixelFormatR8Sint = 14, PixelFormatR16Unorm = 20, PixelFormatR16Snorm = 22, PixelFormatR16Uint = 23, PixelFormatR16Sint = 24, PixelFormatR16Float = 25, PixelFormatRG8Unorm = 30, PixelFormatRG8Unorm_sRGB = 31, PixelFormatRG8Snorm = 32, PixelFormatRG8Uint = 33, PixelFormatRG8Sint = 34, PixelFormatB5G6R5Unorm = 40, PixelFormatA1BGR5Unorm = 41, PixelFormatABGR4Unorm = 42, PixelFormatBGR5A1Unorm = 43, PixelFormatR32Uint = 53, PixelFormatR32Sint = 54, PixelFormatR32Float = 55, PixelFormatRG16Unorm = 60, PixelFormatRG16Snorm = 62, PixelFormatRG16Uint = 63, PixelFormatRG16Sint = 64, PixelFormatRG16Float = 65, PixelFormatRGBA8Unorm = 70, PixelFormatRGBA8Unorm_sRGB = 71, PixelFormatRGBA8Snorm = 72, PixelFormatRGBA8Uint = 73, PixelFormatRGBA8Sint = 74, PixelFormatBGRA8Unorm = 80, PixelFormatBGRA8Unorm_sRGB = 81, PixelFormatRGB10A2Unorm = 90, PixelFormatRGB10A2Uint = 91, PixelFormatRG11B10Float = 92, PixelFormatRGB9E5Float = 93, PixelFormatBGR10A2Unorm = 94, PixelFormatBGR10_XR = 554, PixelFormatBGR10_XR_sRGB = 555, PixelFormatRG32Uint = 103, PixelFormatRG32Sint = 104, PixelFormatRG32Float = 105, PixelFormatRGBA16Unorm = 110, PixelFormatRGBA16Snorm = 112, PixelFormatRGBA16Uint = 113, PixelFormatRGBA16Sint = 114, PixelFormatRGBA16Float = 115, PixelFormatBGRA10_XR = 552, PixelFormatBGRA10_XR_sRGB = 553, PixelFormatRGBA32Uint = 123, PixelFormatRGBA32Sint = 124, PixelFormatRGBA32Float = 125, PixelFormatBC1_RGBA = 130, PixelFormatBC1_RGBA_sRGB = 131, PixelFormatBC2_RGBA = 132, PixelFormatBC2_RGBA_sRGB = 133, PixelFormatBC3_RGBA = 134, PixelFormatBC3_RGBA_sRGB = 135, PixelFormatBC4_RUnorm = 140, PixelFormatBC4_RSnorm = 141, PixelFormatBC5_RGUnorm = 142, PixelFormatBC5_RGSnorm = 143, PixelFormatBC6H_RGBFloat = 150, PixelFormatBC6H_RGBUfloat = 151, PixelFormatBC7_RGBAUnorm = 152, PixelFormatBC7_RGBAUnorm_sRGB = 153, PixelFormatPVRTC_RGB_2BPP = 160, PixelFormatPVRTC_RGB_2BPP_sRGB = 161, PixelFormatPVRTC_RGB_4BPP = 162, PixelFormatPVRTC_RGB_4BPP_sRGB = 163, PixelFormatPVRTC_RGBA_2BPP = 164, PixelFormatPVRTC_RGBA_2BPP_sRGB = 165, PixelFormatPVRTC_RGBA_4BPP = 166, PixelFormatPVRTC_RGBA_4BPP_sRGB = 167, PixelFormatEAC_R11Unorm = 170, PixelFormatEAC_R11Snorm = 172, PixelFormatEAC_RG11Unorm = 174, PixelFormatEAC_RG11Snorm = 176, PixelFormatEAC_RGBA8 = 178, PixelFormatEAC_RGBA8_sRGB = 179, PixelFormatETC2_RGB8 = 180, PixelFormatETC2_RGB8_sRGB = 181, PixelFormatETC2_RGB8A1 = 182, PixelFormatETC2_RGB8A1_sRGB = 183, PixelFormatASTC_4x4_sRGB = 186, PixelFormatASTC_5x4_sRGB = 187, PixelFormatASTC_5x5_sRGB = 188, PixelFormatASTC_6x5_sRGB = 189, PixelFormatASTC_6x6_sRGB = 190, PixelFormatASTC_8x5_sRGB = 192, PixelFormatASTC_8x6_sRGB = 193, PixelFormatASTC_8x8_sRGB = 194, PixelFormatASTC_10x5_sRGB = 195, PixelFormatASTC_10x6_sRGB = 196, PixelFormatASTC_10x8_sRGB = 197, PixelFormatASTC_10x10_sRGB = 198, PixelFormatASTC_12x10_sRGB = 199, PixelFormatASTC_12x12_sRGB = 200, PixelFormatASTC_4x4_LDR = 204, PixelFormatASTC_5x4_LDR = 205, PixelFormatASTC_5x5_LDR = 206, PixelFormatASTC_6x5_LDR = 207, PixelFormatASTC_6x6_LDR = 208, PixelFormatASTC_8x5_LDR = 210, PixelFormatASTC_8x6_LDR = 211, PixelFormatASTC_8x8_LDR = 212, PixelFormatASTC_10x5_LDR = 213, PixelFormatASTC_10x6_LDR = 214, PixelFormatASTC_10x8_LDR = 215, PixelFormatASTC_10x10_LDR = 216, PixelFormatASTC_12x10_LDR = 217, PixelFormatASTC_12x12_LDR = 218, PixelFormatASTC_4x4_HDR = 222, PixelFormatASTC_5x4_HDR = 223, PixelFormatASTC_5x5_HDR = 224, PixelFormatASTC_6x5_HDR = 225, PixelFormatASTC_6x6_HDR = 226, PixelFormatASTC_8x5_HDR = 228, PixelFormatASTC_8x6_HDR = 229, PixelFormatASTC_8x8_HDR = 230, PixelFormatASTC_10x5_HDR = 231, PixelFormatASTC_10x6_HDR = 232, PixelFormatASTC_10x8_HDR = 233, PixelFormatASTC_10x10_HDR = 234, PixelFormatASTC_12x10_HDR = 235, PixelFormatASTC_12x12_HDR = 236, PixelFormatGBGR422 = 240, PixelFormatBGRG422 = 241, PixelFormatDepth16Unorm = 250, PixelFormatDepth32Float = 252, PixelFormatStencil8 = 253, PixelFormatDepth24Unorm_Stencil8 = 255, PixelFormatDepth32Float_Stencil8 = 260, PixelFormatX32_Stencil8 = 261, PixelFormatX24_Stencil8 = 262, }; } #pragma once namespace MTL { _MTL_ENUM(NS::UInteger, PurgeableState) { PurgeableStateKeepCurrent = 1, PurgeableStateNonVolatile = 2, PurgeableStateVolatile = 3, PurgeableStateEmpty = 4, }; _MTL_ENUM(NS::UInteger, CPUCacheMode) { CPUCacheModeDefaultCache = 0, CPUCacheModeWriteCombined = 1, }; _MTL_ENUM(NS::UInteger, StorageMode) { StorageModeShared = 0, StorageModeManaged = 1, StorageModePrivate = 2, StorageModeMemoryless = 3, }; _MTL_ENUM(NS::UInteger, HazardTrackingMode) { HazardTrackingModeDefault = 0, HazardTrackingModeUntracked = 1, HazardTrackingModeTracked = 2, }; _MTL_OPTIONS(NS::UInteger, ResourceOptions) { ResourceCPUCacheModeDefaultCache = 0, ResourceCPUCacheModeWriteCombined = 1, ResourceStorageModeShared = 0, ResourceStorageModeManaged = 16, ResourceStorageModePrivate = 32, ResourceStorageModeMemoryless = 48, ResourceHazardTrackingModeDefault = 0, ResourceHazardTrackingModeUntracked = 256, ResourceHazardTrackingModeTracked = 512, ResourceOptionCPUCacheModeDefault = 0, ResourceOptionCPUCacheModeWriteCombined = 1, }; class Resource : public NS::Referencing<Resource> { public: NS::String* label() const; void setLabel(const NS::String* label); class Device* device() const; MTL::CPUCacheMode cpuCacheMode() const; MTL::StorageMode storageMode() const; MTL::HazardTrackingMode hazardTrackingMode() const; MTL::ResourceOptions resourceOptions() const; MTL::PurgeableState setPurgeableState(MTL::PurgeableState state); class Heap* heap() const; NS::UInteger heapOffset() const; NS::UInteger allocatedSize() const; void makeAliasable(); bool isAliasable(); }; } _MTL_INLINE NS::String* MTL::Resource::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::Resource::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE MTL::Device* MTL::Resource::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE MTL::CPUCacheMode MTL::Resource::cpuCacheMode() const { return Object::sendMessage<MTL::CPUCacheMode>(this, _MTL_PRIVATE_SEL(cpuCacheMode)); } _MTL_INLINE MTL::StorageMode MTL::Resource::storageMode() const { return Object::sendMessage<MTL::StorageMode>(this, _MTL_PRIVATE_SEL(storageMode)); } _MTL_INLINE MTL::HazardTrackingMode MTL::Resource::hazardTrackingMode() const { return Object::sendMessage<MTL::HazardTrackingMode>(this, _MTL_PRIVATE_SEL(hazardTrackingMode)); } _MTL_INLINE MTL::ResourceOptions MTL::Resource::resourceOptions() const { return Object::sendMessage<MTL::ResourceOptions>(this, _MTL_PRIVATE_SEL(resourceOptions)); } _MTL_INLINE MTL::PurgeableState MTL::Resource::setPurgeableState(MTL::PurgeableState state) { return Object::sendMessage<MTL::PurgeableState>(this, _MTL_PRIVATE_SEL(setPurgeableState_), state); } _MTL_INLINE MTL::Heap* MTL::Resource::heap() const { return Object::sendMessage<MTL::Heap*>(this, _MTL_PRIVATE_SEL(heap)); } _MTL_INLINE NS::UInteger MTL::Resource::heapOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(heapOffset)); } _MTL_INLINE NS::UInteger MTL::Resource::allocatedSize() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(allocatedSize)); } _MTL_INLINE void MTL::Resource::makeAliasable() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(makeAliasable)); } _MTL_INLINE bool MTL::Resource::isAliasable() { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isAliasable)); } #pragma once namespace MTL { struct Origin { Origin() = default; Origin(NS::UInteger x, NS::UInteger y, NS::UInteger z); static Origin Make(NS::UInteger x, NS::UInteger y, NS::UInteger z); NS::UInteger x; NS::UInteger y; NS::UInteger z; } _MTL_PACKED; struct Size { Size() = default; Size(NS::UInteger width, NS::UInteger height, NS::UInteger depth); static Size Make(NS::UInteger width, NS::UInteger height, NS::UInteger depth); NS::UInteger width; NS::UInteger height; NS::UInteger depth; } _MTL_PACKED; struct Region { Region() = default; Region(NS::UInteger x, NS::UInteger width); Region(NS::UInteger x, NS::UInteger y, NS::UInteger width, NS::UInteger height); Region(NS::UInteger x, NS::UInteger y, NS::UInteger z, NS::UInteger width, NS::UInteger height, NS::UInteger depth); static Region Make1D(NS::UInteger x, NS::UInteger width); static Region Make2D(NS::UInteger x, NS::UInteger y, NS::UInteger width, NS::UInteger height); static Region Make3D(NS::UInteger x, NS::UInteger y, NS::UInteger z, NS::UInteger width, NS::UInteger height, NS::UInteger depth); MTL::Origin origin; MTL::Size size; } _MTL_PACKED; struct SamplePosition; using Coordinate2D = SamplePosition; struct SamplePosition { SamplePosition() = default; SamplePosition(float _x, float _y); static SamplePosition Make(float x, float y); float x; float y; } _MTL_PACKED; struct ResourceID { uint64_t _impl; } _MTL_PACKED; } _MTL_INLINE MTL::Origin::Origin(NS::UInteger _x, NS::UInteger _y, NS::UInteger _z) : x(_x) , y(_y) , z(_z) { } _MTL_INLINE MTL::Origin MTL::Origin::Make(NS::UInteger x, NS::UInteger y, NS::UInteger z) { return Origin(x, y, z); } _MTL_INLINE MTL::Size::Size(NS::UInteger _width, NS::UInteger _height, NS::UInteger _depth) : width(_width) , height(_height) , depth(_depth) { } _MTL_INLINE MTL::Size MTL::Size::Make(NS::UInteger width, NS::UInteger height, NS::UInteger depth) { return Size(width, height, depth); } _MTL_INLINE MTL::Region::Region(NS::UInteger x, NS::UInteger width) : origin(x, 0, 0) , size(width, 1, 1) { } _MTL_INLINE MTL::Region::Region(NS::UInteger x, NS::UInteger y, NS::UInteger width, NS::UInteger height) : origin(x, y, 0) , size(width, height, 1) { } _MTL_INLINE MTL::Region::Region(NS::UInteger x, NS::UInteger y, NS::UInteger z, NS::UInteger width, NS::UInteger height, NS::UInteger depth) : origin(x, y, z) , size(width, height, depth) { } _MTL_INLINE MTL::Region MTL::Region::Make1D(NS::UInteger x, NS::UInteger width) { return Region(x, width); } _MTL_INLINE MTL::Region MTL::Region::Make2D(NS::UInteger x, NS::UInteger y, NS::UInteger width, NS::UInteger height) { return Region(x, y, width, height); } _MTL_INLINE MTL::Region MTL::Region::Make3D(NS::UInteger x, NS::UInteger y, NS::UInteger z, NS::UInteger width, NS::UInteger height, NS::UInteger depth) { return Region(x, y, z, width, height, depth); } _MTL_INLINE MTL::SamplePosition::SamplePosition(float _x, float _y) : x(_x) , y(_y) { } _MTL_INLINE MTL::SamplePosition MTL::SamplePosition::Make(float x, float y) { return SamplePosition(x, y); } #include <IOSurface/IOSurfaceRef.h> namespace MTL { _MTL_ENUM(NS::UInteger, TextureType) { TextureType1D = 0, TextureType1DArray = 1, TextureType2D = 2, TextureType2DArray = 3, TextureType2DMultisample = 4, TextureTypeCube = 5, TextureTypeCubeArray = 6, TextureType3D = 7, TextureType2DMultisampleArray = 8, TextureTypeTextureBuffer = 9, }; _MTL_ENUM(uint8_t, TextureSwizzle) { TextureSwizzleZero = 0, TextureSwizzleOne = 1, TextureSwizzleRed = 2, TextureSwizzleGreen = 3, TextureSwizzleBlue = 4, TextureSwizzleAlpha = 5, }; struct TextureSwizzleChannels { MTL::TextureSwizzle red; MTL::TextureSwizzle green; MTL::TextureSwizzle blue; MTL::TextureSwizzle alpha; } _MTL_PACKED; class SharedTextureHandle : public NS::SecureCoding<SharedTextureHandle> { public: static class SharedTextureHandle* alloc(); class SharedTextureHandle* init(); class Device* device() const; NS::String* label() const; }; _MTL_OPTIONS(NS::UInteger, TextureUsage) { TextureUsageUnknown = 0, TextureUsageShaderRead = 1, TextureUsageShaderWrite = 2, TextureUsageRenderTarget = 4, TextureUsagePixelFormatView = 16, TextureUsageShaderAtomic = 32, }; _MTL_ENUM(NS::Integer, TextureCompressionType) { TextureCompressionTypeLossless = 0, TextureCompressionTypeLossy = 1, }; class TextureDescriptor : public NS::Copying<TextureDescriptor> { public: static class TextureDescriptor* alloc(); class TextureDescriptor* init(); static class TextureDescriptor* texture2DDescriptor(MTL::PixelFormat pixelFormat, NS::UInteger width, NS::UInteger height, bool mipmapped); static class TextureDescriptor* textureCubeDescriptor(MTL::PixelFormat pixelFormat, NS::UInteger size, bool mipmapped); static class TextureDescriptor* textureBufferDescriptor(MTL::PixelFormat pixelFormat, NS::UInteger width, MTL::ResourceOptions resourceOptions, MTL::TextureUsage usage); MTL::TextureType textureType() const; void setTextureType(MTL::TextureType textureType); MTL::PixelFormat pixelFormat() const; void setPixelFormat(MTL::PixelFormat pixelFormat); NS::UInteger width() const; void setWidth(NS::UInteger width); NS::UInteger height() const; void setHeight(NS::UInteger height); NS::UInteger depth() const; void setDepth(NS::UInteger depth); NS::UInteger mipmapLevelCount() const; void setMipmapLevelCount(NS::UInteger mipmapLevelCount); NS::UInteger sampleCount() const; void setSampleCount(NS::UInteger sampleCount); NS::UInteger arrayLength() const; void setArrayLength(NS::UInteger arrayLength); MTL::ResourceOptions resourceOptions() const; void setResourceOptions(MTL::ResourceOptions resourceOptions); MTL::CPUCacheMode cpuCacheMode() const; void setCpuCacheMode(MTL::CPUCacheMode cpuCacheMode); MTL::StorageMode storageMode() const; void setStorageMode(MTL::StorageMode storageMode); MTL::HazardTrackingMode hazardTrackingMode() const; void setHazardTrackingMode(MTL::HazardTrackingMode hazardTrackingMode); MTL::TextureUsage usage() const; void setUsage(MTL::TextureUsage usage); bool allowGPUOptimizedContents() const; void setAllowGPUOptimizedContents(bool allowGPUOptimizedContents); MTL::TextureCompressionType compressionType() const; void setCompressionType(MTL::TextureCompressionType compressionType); MTL::TextureSwizzleChannels swizzle() const; void setSwizzle(MTL::TextureSwizzleChannels swizzle); }; class Texture : public NS::Referencing<Texture, Resource> { public: class Resource* rootResource() const; class Texture* parentTexture() const; NS::UInteger parentRelativeLevel() const; NS::UInteger parentRelativeSlice() const; class Buffer* buffer() const; NS::UInteger bufferOffset() const; NS::UInteger bufferBytesPerRow() const; IOSurfaceRef iosurface() const; NS::UInteger iosurfacePlane() const; MTL::TextureType textureType() const; MTL::PixelFormat pixelFormat() const; NS::UInteger width() const; NS::UInteger height() const; NS::UInteger depth() const; NS::UInteger mipmapLevelCount() const; NS::UInteger sampleCount() const; NS::UInteger arrayLength() const; MTL::TextureUsage usage() const; bool shareable() const; bool framebufferOnly() const; NS::UInteger firstMipmapInTail() const; NS::UInteger tailSizeInBytes() const; bool isSparse() const; bool allowGPUOptimizedContents() const; MTL::TextureCompressionType compressionType() const; MTL::ResourceID gpuResourceID() const; void getBytes(const void* pixelBytes, NS::UInteger bytesPerRow, NS::UInteger bytesPerImage, MTL::Region region, NS::UInteger level, NS::UInteger slice); void replaceRegion(MTL::Region region, NS::UInteger level, NS::UInteger slice, const void* pixelBytes, NS::UInteger bytesPerRow, NS::UInteger bytesPerImage); void getBytes(const void* pixelBytes, NS::UInteger bytesPerRow, MTL::Region region, NS::UInteger level); void replaceRegion(MTL::Region region, NS::UInteger level, const void* pixelBytes, NS::UInteger bytesPerRow); class Texture* newTextureView(MTL::PixelFormat pixelFormat); class Texture* newTextureView(MTL::PixelFormat pixelFormat, MTL::TextureType textureType, NS::Range levelRange, NS::Range sliceRange); class SharedTextureHandle* newSharedTextureHandle(); class Texture* remoteStorageTexture() const; class Texture* newRemoteTextureViewForDevice(const class Device* device); MTL::TextureSwizzleChannels swizzle() const; class Texture* newTextureView(MTL::PixelFormat pixelFormat, MTL::TextureType textureType, NS::Range levelRange, NS::Range sliceRange, MTL::TextureSwizzleChannels swizzle); }; } _MTL_INLINE MTL::SharedTextureHandle* MTL::SharedTextureHandle::alloc() { return NS::Object::alloc<MTL::SharedTextureHandle>(_MTL_PRIVATE_CLS(MTLSharedTextureHandle)); } _MTL_INLINE MTL::SharedTextureHandle* MTL::SharedTextureHandle::init() { return NS::Object::init<MTL::SharedTextureHandle>(); } _MTL_INLINE MTL::Device* MTL::SharedTextureHandle::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE NS::String* MTL::SharedTextureHandle::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE MTL::TextureDescriptor* MTL::TextureDescriptor::alloc() { return NS::Object::alloc<MTL::TextureDescriptor>(_MTL_PRIVATE_CLS(MTLTextureDescriptor)); } _MTL_INLINE MTL::TextureDescriptor* MTL::TextureDescriptor::init() { return NS::Object::init<MTL::TextureDescriptor>(); } _MTL_INLINE MTL::TextureDescriptor* MTL::TextureDescriptor::texture2DDescriptor(MTL::PixelFormat pixelFormat, NS::UInteger width, NS::UInteger height, bool mipmapped) { return Object::sendMessage<MTL::TextureDescriptor*>(_MTL_PRIVATE_CLS(MTLTextureDescriptor), _MTL_PRIVATE_SEL(texture2DDescriptorWithPixelFormat_width_height_mipmapped_), pixelFormat, width, height, mipmapped); } _MTL_INLINE MTL::TextureDescriptor* MTL::TextureDescriptor::textureCubeDescriptor(MTL::PixelFormat pixelFormat, NS::UInteger size, bool mipmapped) { return Object::sendMessage<MTL::TextureDescriptor*>(_MTL_PRIVATE_CLS(MTLTextureDescriptor), _MTL_PRIVATE_SEL(textureCubeDescriptorWithPixelFormat_size_mipmapped_), pixelFormat, size, mipmapped); } _MTL_INLINE MTL::TextureDescriptor* MTL::TextureDescriptor::textureBufferDescriptor(MTL::PixelFormat pixelFormat, NS::UInteger width, MTL::ResourceOptions resourceOptions, MTL::TextureUsage usage) { return Object::sendMessage<MTL::TextureDescriptor*>(_MTL_PRIVATE_CLS(MTLTextureDescriptor), _MTL_PRIVATE_SEL(textureBufferDescriptorWithPixelFormat_width_resourceOptions_usage_), pixelFormat, width, resourceOptions, usage); } _MTL_INLINE MTL::TextureType MTL::TextureDescriptor::textureType() const { return Object::sendMessage<MTL::TextureType>(this, _MTL_PRIVATE_SEL(textureType)); } _MTL_INLINE void MTL::TextureDescriptor::setTextureType(MTL::TextureType textureType) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTextureType_), textureType); } _MTL_INLINE MTL::PixelFormat MTL::TextureDescriptor::pixelFormat() const { return Object::sendMessage<MTL::PixelFormat>(this, _MTL_PRIVATE_SEL(pixelFormat)); } _MTL_INLINE void MTL::TextureDescriptor::setPixelFormat(MTL::PixelFormat pixelFormat) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPixelFormat_), pixelFormat); } _MTL_INLINE NS::UInteger MTL::TextureDescriptor::width() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(width)); } _MTL_INLINE void MTL::TextureDescriptor::setWidth(NS::UInteger width) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setWidth_), width); } _MTL_INLINE NS::UInteger MTL::TextureDescriptor::height() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(height)); } _MTL_INLINE void MTL::TextureDescriptor::setHeight(NS::UInteger height) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setHeight_), height); } _MTL_INLINE NS::UInteger MTL::TextureDescriptor::depth() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(depth)); } _MTL_INLINE void MTL::TextureDescriptor::setDepth(NS::UInteger depth) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepth_), depth); } _MTL_INLINE NS::UInteger MTL::TextureDescriptor::mipmapLevelCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(mipmapLevelCount)); } _MTL_INLINE void MTL::TextureDescriptor::setMipmapLevelCount(NS::UInteger mipmapLevelCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMipmapLevelCount_), mipmapLevelCount); } _MTL_INLINE NS::UInteger MTL::TextureDescriptor::sampleCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(sampleCount)); } _MTL_INLINE void MTL::TextureDescriptor::setSampleCount(NS::UInteger sampleCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSampleCount_), sampleCount); } _MTL_INLINE NS::UInteger MTL::TextureDescriptor::arrayLength() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(arrayLength)); } _MTL_INLINE void MTL::TextureDescriptor::setArrayLength(NS::UInteger arrayLength) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setArrayLength_), arrayLength); } _MTL_INLINE MTL::ResourceOptions MTL::TextureDescriptor::resourceOptions() const { return Object::sendMessage<MTL::ResourceOptions>(this, _MTL_PRIVATE_SEL(resourceOptions)); } _MTL_INLINE void MTL::TextureDescriptor::setResourceOptions(MTL::ResourceOptions resourceOptions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setResourceOptions_), resourceOptions); } _MTL_INLINE MTL::CPUCacheMode MTL::TextureDescriptor::cpuCacheMode() const { return Object::sendMessage<MTL::CPUCacheMode>(this, _MTL_PRIVATE_SEL(cpuCacheMode)); } _MTL_INLINE void MTL::TextureDescriptor::setCpuCacheMode(MTL::CPUCacheMode cpuCacheMode) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCpuCacheMode_), cpuCacheMode); } _MTL_INLINE MTL::StorageMode MTL::TextureDescriptor::storageMode() const { return Object::sendMessage<MTL::StorageMode>(this, _MTL_PRIVATE_SEL(storageMode)); } _MTL_INLINE void MTL::TextureDescriptor::setStorageMode(MTL::StorageMode storageMode) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStorageMode_), storageMode); } _MTL_INLINE MTL::HazardTrackingMode MTL::TextureDescriptor::hazardTrackingMode() const { return Object::sendMessage<MTL::HazardTrackingMode>(this, _MTL_PRIVATE_SEL(hazardTrackingMode)); } _MTL_INLINE void MTL::TextureDescriptor::setHazardTrackingMode(MTL::HazardTrackingMode hazardTrackingMode) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setHazardTrackingMode_), hazardTrackingMode); } _MTL_INLINE MTL::TextureUsage MTL::TextureDescriptor::usage() const { return Object::sendMessage<MTL::TextureUsage>(this, _MTL_PRIVATE_SEL(usage)); } _MTL_INLINE void MTL::TextureDescriptor::setUsage(MTL::TextureUsage usage) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setUsage_), usage); } _MTL_INLINE bool MTL::TextureDescriptor::allowGPUOptimizedContents() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(allowGPUOptimizedContents)); } _MTL_INLINE void MTL::TextureDescriptor::setAllowGPUOptimizedContents(bool allowGPUOptimizedContents) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAllowGPUOptimizedContents_), allowGPUOptimizedContents); } _MTL_INLINE MTL::TextureCompressionType MTL::TextureDescriptor::compressionType() const { return Object::sendMessage<MTL::TextureCompressionType>(this, _MTL_PRIVATE_SEL(compressionType)); } _MTL_INLINE void MTL::TextureDescriptor::setCompressionType(MTL::TextureCompressionType compressionType) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCompressionType_), compressionType); } _MTL_INLINE MTL::TextureSwizzleChannels MTL::TextureDescriptor::swizzle() const { return Object::sendMessage<MTL::TextureSwizzleChannels>(this, _MTL_PRIVATE_SEL(swizzle)); } _MTL_INLINE void MTL::TextureDescriptor::setSwizzle(MTL::TextureSwizzleChannels swizzle) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSwizzle_), swizzle); } _MTL_INLINE MTL::Resource* MTL::Texture::rootResource() const { return Object::sendMessage<MTL::Resource*>(this, _MTL_PRIVATE_SEL(rootResource)); } _MTL_INLINE MTL::Texture* MTL::Texture::parentTexture() const { return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(parentTexture)); } _MTL_INLINE NS::UInteger MTL::Texture::parentRelativeLevel() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(parentRelativeLevel)); } _MTL_INLINE NS::UInteger MTL::Texture::parentRelativeSlice() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(parentRelativeSlice)); } _MTL_INLINE MTL::Buffer* MTL::Texture::buffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(buffer)); } _MTL_INLINE NS::UInteger MTL::Texture::bufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(bufferOffset)); } _MTL_INLINE NS::UInteger MTL::Texture::bufferBytesPerRow() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(bufferBytesPerRow)); } _MTL_INLINE IOSurfaceRef MTL::Texture::iosurface() const { return Object::sendMessage<IOSurfaceRef>(this, _MTL_PRIVATE_SEL(iosurface)); } _MTL_INLINE NS::UInteger MTL::Texture::iosurfacePlane() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(iosurfacePlane)); } _MTL_INLINE MTL::TextureType MTL::Texture::textureType() const { return Object::sendMessage<MTL::TextureType>(this, _MTL_PRIVATE_SEL(textureType)); } _MTL_INLINE MTL::PixelFormat MTL::Texture::pixelFormat() const { return Object::sendMessage<MTL::PixelFormat>(this, _MTL_PRIVATE_SEL(pixelFormat)); } _MTL_INLINE NS::UInteger MTL::Texture::width() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(width)); } _MTL_INLINE NS::UInteger MTL::Texture::height() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(height)); } _MTL_INLINE NS::UInteger MTL::Texture::depth() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(depth)); } _MTL_INLINE NS::UInteger MTL::Texture::mipmapLevelCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(mipmapLevelCount)); } _MTL_INLINE NS::UInteger MTL::Texture::sampleCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(sampleCount)); } _MTL_INLINE NS::UInteger MTL::Texture::arrayLength() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(arrayLength)); } _MTL_INLINE MTL::TextureUsage MTL::Texture::usage() const { return Object::sendMessage<MTL::TextureUsage>(this, _MTL_PRIVATE_SEL(usage)); } _MTL_INLINE bool MTL::Texture::shareable() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isShareable)); } _MTL_INLINE bool MTL::Texture::framebufferOnly() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isFramebufferOnly)); } _MTL_INLINE NS::UInteger MTL::Texture::firstMipmapInTail() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(firstMipmapInTail)); } _MTL_INLINE NS::UInteger MTL::Texture::tailSizeInBytes() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(tailSizeInBytes)); } _MTL_INLINE bool MTL::Texture::isSparse() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isSparse)); } _MTL_INLINE bool MTL::Texture::allowGPUOptimizedContents() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(allowGPUOptimizedContents)); } _MTL_INLINE MTL::TextureCompressionType MTL::Texture::compressionType() const { return Object::sendMessage<MTL::TextureCompressionType>(this, _MTL_PRIVATE_SEL(compressionType)); } _MTL_INLINE MTL::ResourceID MTL::Texture::gpuResourceID() const { return Object::sendMessage<MTL::ResourceID>(this, _MTL_PRIVATE_SEL(gpuResourceID)); } _MTL_INLINE void MTL::Texture::getBytes(const void* pixelBytes, NS::UInteger bytesPerRow, NS::UInteger bytesPerImage, MTL::Region region, NS::UInteger level, NS::UInteger slice) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(getBytes_bytesPerRow_bytesPerImage_fromRegion_mipmapLevel_slice_), pixelBytes, bytesPerRow, bytesPerImage, region, level, slice); } _MTL_INLINE void MTL::Texture::replaceRegion(MTL::Region region, NS::UInteger level, NS::UInteger slice, const void* pixelBytes, NS::UInteger bytesPerRow, NS::UInteger bytesPerImage) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(replaceRegion_mipmapLevel_slice_withBytes_bytesPerRow_bytesPerImage_), region, level, slice, pixelBytes, bytesPerRow, bytesPerImage); } _MTL_INLINE void MTL::Texture::getBytes(const void* pixelBytes, NS::UInteger bytesPerRow, MTL::Region region, NS::UInteger level) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(getBytes_bytesPerRow_fromRegion_mipmapLevel_), pixelBytes, bytesPerRow, region, level); } _MTL_INLINE void MTL::Texture::replaceRegion(MTL::Region region, NS::UInteger level, const void* pixelBytes, NS::UInteger bytesPerRow) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(replaceRegion_mipmapLevel_withBytes_bytesPerRow_), region, level, pixelBytes, bytesPerRow); } _MTL_INLINE MTL::Texture* MTL::Texture::newTextureView(MTL::PixelFormat pixelFormat) { return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newTextureViewWithPixelFormat_), pixelFormat); } _MTL_INLINE MTL::Texture* MTL::Texture::newTextureView(MTL::PixelFormat pixelFormat, MTL::TextureType textureType, NS::Range levelRange, NS::Range sliceRange) { return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newTextureViewWithPixelFormat_textureType_levels_slices_), pixelFormat, textureType, levelRange, sliceRange); } _MTL_INLINE MTL::SharedTextureHandle* MTL::Texture::newSharedTextureHandle() { return Object::sendMessage<MTL::SharedTextureHandle*>(this, _MTL_PRIVATE_SEL(newSharedTextureHandle)); } _MTL_INLINE MTL::Texture* MTL::Texture::remoteStorageTexture() const { return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(remoteStorageTexture)); } _MTL_INLINE MTL::Texture* MTL::Texture::newRemoteTextureViewForDevice(const MTL::Device* device) { return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newRemoteTextureViewForDevice_), device); } _MTL_INLINE MTL::TextureSwizzleChannels MTL::Texture::swizzle() const { return Object::sendMessage<MTL::TextureSwizzleChannels>(this, _MTL_PRIVATE_SEL(swizzle)); } _MTL_INLINE MTL::Texture* MTL::Texture::newTextureView(MTL::PixelFormat pixelFormat, MTL::TextureType textureType, NS::Range levelRange, NS::Range sliceRange, MTL::TextureSwizzleChannels swizzle) { return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newTextureViewWithPixelFormat_textureType_levels_slices_swizzle_), pixelFormat, textureType, levelRange, sliceRange, swizzle); } #define _CA_EXPORT _NS_EXPORT #define _CA_EXTERN _NS_EXTERN #define _CA_INLINE _NS_INLINE #define _CA_PACKED _NS_PACKED #define _CA_CONST(type, name) _NS_CONST(type, name) #define _CA_ENUM(type, name) _NS_ENUM(type, name) #define _CA_OPTIONS(type, name) _NS_OPTIONS(type, name) #define _CA_VALIDATE_SIZE(ns, name) _NS_VALIDATE_SIZE(ns, name) #define _CA_VALIDATE_ENUM(ns, name) _NS_VALIDATE_ENUM(ns, name) #include <objc/runtime.h> #define _CA_PRIVATE_CLS(symbol) (Private::Class::s_k##symbol) #define _CA_PRIVATE_SEL(accessor) (Private::Selector::s_k##accessor) #if defined(CA_PRIVATE_IMPLEMENTATION) #ifdef METALCPP_SYMBOL_VISIBILITY_HIDDEN #define _CA_PRIVATE_VISIBILITY __attribute__((visibility("hidden"))) #else #define _CA_PRIVATE_VISIBILITY __attribute__((visibility("default"))) #endif // METALCPP_SYMBOL_VISIBILITY_HIDDEN #define _CA_PRIVATE_IMPORT __attribute__((weak_import)) #ifdef __OBJC__ #define _CA_PRIVATE_OBJC_LOOKUP_CLASS(symbol) ((__bridge void*)objc_lookUpClass(#symbol)) #define _CA_PRIVATE_OBJC_GET_PROTOCOL(symbol) ((__bridge void*)objc_getProtocol(#symbol)) #else #define _CA_PRIVATE_OBJC_LOOKUP_CLASS(symbol) objc_lookUpClass(#symbol) #define _CA_PRIVATE_OBJC_GET_PROTOCOL(symbol) objc_getProtocol(#symbol) #endif // __OBJC__ #define _CA_PRIVATE_DEF_CLS(symbol) void* s_k##symbol _CA_PRIVATE_VISIBILITY = _CA_PRIVATE_OBJC_LOOKUP_CLASS(symbol) #define _CA_PRIVATE_DEF_PRO(symbol) void* s_k##symbol _CA_PRIVATE_VISIBILITY = _CA_PRIVATE_OBJC_GET_PROTOCOL(symbol) #define _CA_PRIVATE_DEF_SEL(accessor, symbol) SEL s_k##accessor _CA_PRIVATE_VISIBILITY = sel_registerName(symbol) #define _CA_PRIVATE_DEF_STR(type, symbol) \ _CA_EXTERN type const CA##symbol _CA_PRIVATE_IMPORT; \ type const CA::symbol = (nullptr != &CA##symbol) ? CA##symbol : nullptr #else #define _CA_PRIVATE_DEF_CLS(symbol) extern void* s_k##symbol #define _CA_PRIVATE_DEF_PRO(symbol) extern void* s_k##symbol #define _CA_PRIVATE_DEF_SEL(accessor, symbol) extern SEL s_k##accessor #define _CA_PRIVATE_DEF_STR(type, symbol) extern type const CA::symbol #endif // CA_PRIVATE_IMPLEMENTATION namespace CA { namespace Private { namespace Class { _CA_PRIVATE_DEF_CLS(CAMetalLayer); } // Class } // Private } // CA namespace CA { namespace Private { namespace Protocol { _CA_PRIVATE_DEF_PRO(CAMetalDrawable); } // Protocol } // Private } // CA namespace CA { namespace Private { namespace Selector { _CA_PRIVATE_DEF_SEL(device, "device"); _CA_PRIVATE_DEF_SEL(drawableSize, "drawableSize"); _CA_PRIVATE_DEF_SEL(framebufferOnly, "framebufferOnly"); _CA_PRIVATE_DEF_SEL(layer, "layer"); _CA_PRIVATE_DEF_SEL(nextDrawable, "nextDrawable"); _CA_PRIVATE_DEF_SEL(pixelFormat, "pixelFormat"); _CA_PRIVATE_DEF_SEL(setDevice_, "setDevice:"); _CA_PRIVATE_DEF_SEL(setDrawableSize_, "setDrawableSize:"); _CA_PRIVATE_DEF_SEL(setFramebufferOnly_, "setFramebufferOnly:"); _CA_PRIVATE_DEF_SEL(setPixelFormat_, "setPixelFormat:"); _CA_PRIVATE_DEF_SEL(texture, "texture"); } // Class } // Private } // CA namespace CA { class MetalDrawable : public NS::Referencing<MetalDrawable, MTL::Drawable> { public: class MetalLayer* layer() const; MTL::Texture* texture() const; }; } _CA_INLINE CA::MetalLayer* CA::MetalDrawable::layer() const { return Object::sendMessage<MetalLayer*>(this, _CA_PRIVATE_SEL(layer)); } _CA_INLINE MTL::Texture* CA::MetalDrawable::texture() const { return Object::sendMessage<MTL::Texture*>(this, _CA_PRIVATE_SEL(texture)); } #include <CoreGraphics/CGGeometry.h> namespace CA { class MetalLayer : public NS::Referencing<MetalLayer> { public: static class MetalLayer* layer(); MTL::Device* device() const; void setDevice(MTL::Device* device); MTL::PixelFormat pixelFormat() const; void setPixelFormat(MTL::PixelFormat pixelFormat); bool framebufferOnly() const; void setFramebufferOnly(bool framebufferOnly); CGSize drawableSize() const; void setDrawableSize(CGSize drawableSize); class MetalDrawable* nextDrawable(); }; } // namespace CA _CA_INLINE CA::MetalLayer* CA::MetalLayer::layer() { return Object::sendMessage<CA::MetalLayer*>(_CA_PRIVATE_CLS(CAMetalLayer), _CA_PRIVATE_SEL(layer)); } _CA_INLINE MTL::Device* CA::MetalLayer::device() const { return Object::sendMessage<MTL::Device*>(this, _CA_PRIVATE_SEL(device)); } _CA_INLINE void CA::MetalLayer::setDevice(MTL::Device* device) { return Object::sendMessage<void>(this, _CA_PRIVATE_SEL(setDevice_), device); } _CA_INLINE MTL::PixelFormat CA::MetalLayer::pixelFormat() const { return Object::sendMessage<MTL::PixelFormat>(this, _CA_PRIVATE_SEL(pixelFormat)); } _CA_INLINE void CA::MetalLayer::setPixelFormat(MTL::PixelFormat pixelFormat) { return Object::sendMessage<void>(this, _CA_PRIVATE_SEL(setPixelFormat_), pixelFormat); } _CA_INLINE bool CA::MetalLayer::framebufferOnly() const { return Object::sendMessage<bool>(this, _CA_PRIVATE_SEL(framebufferOnly)); } _CA_INLINE void CA::MetalLayer::setFramebufferOnly(bool framebufferOnly) { return Object::sendMessage<void>(this, _CA_PRIVATE_SEL(setFramebufferOnly_), framebufferOnly); } _CA_INLINE CGSize CA::MetalLayer::drawableSize() const { return Object::sendMessage<CGSize>(this, _CA_PRIVATE_SEL(drawableSize)); } _CA_INLINE void CA::MetalLayer::setDrawableSize(CGSize drawableSize) { return Object::sendMessage<void>(this, _CA_PRIVATE_SEL(setDrawableSize_), drawableSize); } _CA_INLINE CA::MetalDrawable* CA::MetalLayer::nextDrawable() { return Object::sendMessage<MetalDrawable*>(this, _CA_PRIVATE_SEL(nextDrawable)); } #pragma once #pragma once namespace MTL { _MTL_ENUM(NS::UInteger, AttributeFormat) { AttributeFormatInvalid = 0, AttributeFormatUChar2 = 1, AttributeFormatUChar3 = 2, AttributeFormatUChar4 = 3, AttributeFormatChar2 = 4, AttributeFormatChar3 = 5, AttributeFormatChar4 = 6, AttributeFormatUChar2Normalized = 7, AttributeFormatUChar3Normalized = 8, AttributeFormatUChar4Normalized = 9, AttributeFormatChar2Normalized = 10, AttributeFormatChar3Normalized = 11, AttributeFormatChar4Normalized = 12, AttributeFormatUShort2 = 13, AttributeFormatUShort3 = 14, AttributeFormatUShort4 = 15, AttributeFormatShort2 = 16, AttributeFormatShort3 = 17, AttributeFormatShort4 = 18, AttributeFormatUShort2Normalized = 19, AttributeFormatUShort3Normalized = 20, AttributeFormatUShort4Normalized = 21, AttributeFormatShort2Normalized = 22, AttributeFormatShort3Normalized = 23, AttributeFormatShort4Normalized = 24, AttributeFormatHalf2 = 25, AttributeFormatHalf3 = 26, AttributeFormatHalf4 = 27, AttributeFormatFloat = 28, AttributeFormatFloat2 = 29, AttributeFormatFloat3 = 30, AttributeFormatFloat4 = 31, AttributeFormatInt = 32, AttributeFormatInt2 = 33, AttributeFormatInt3 = 34, AttributeFormatInt4 = 35, AttributeFormatUInt = 36, AttributeFormatUInt2 = 37, AttributeFormatUInt3 = 38, AttributeFormatUInt4 = 39, AttributeFormatInt1010102Normalized = 40, AttributeFormatUInt1010102Normalized = 41, AttributeFormatUChar4Normalized_BGRA = 42, AttributeFormatUChar = 45, AttributeFormatChar = 46, AttributeFormatUCharNormalized = 47, AttributeFormatCharNormalized = 48, AttributeFormatUShort = 49, AttributeFormatShort = 50, AttributeFormatUShortNormalized = 51, AttributeFormatShortNormalized = 52, AttributeFormatHalf = 53, AttributeFormatFloatRG11B10 = 54, AttributeFormatFloatRGB9E5 = 55, }; _MTL_ENUM(NS::UInteger, IndexType) { IndexTypeUInt16 = 0, IndexTypeUInt32 = 1, }; _MTL_ENUM(NS::UInteger, StepFunction) { StepFunctionConstant = 0, StepFunctionPerVertex = 1, StepFunctionPerInstance = 2, StepFunctionPerPatch = 3, StepFunctionPerPatchControlPoint = 4, StepFunctionThreadPositionInGridX = 5, StepFunctionThreadPositionInGridY = 6, StepFunctionThreadPositionInGridXIndexed = 7, StepFunctionThreadPositionInGridYIndexed = 8, }; class BufferLayoutDescriptor : public NS::Copying<BufferLayoutDescriptor> { public: static class BufferLayoutDescriptor* alloc(); class BufferLayoutDescriptor* init(); NS::UInteger stride() const; void setStride(NS::UInteger stride); MTL::StepFunction stepFunction() const; void setStepFunction(MTL::StepFunction stepFunction); NS::UInteger stepRate() const; void setStepRate(NS::UInteger stepRate); }; class BufferLayoutDescriptorArray : public NS::Referencing<BufferLayoutDescriptorArray> { public: static class BufferLayoutDescriptorArray* alloc(); class BufferLayoutDescriptorArray* init(); class BufferLayoutDescriptor* object(NS::UInteger index); void setObject(const class BufferLayoutDescriptor* bufferDesc, NS::UInteger index); }; class AttributeDescriptor : public NS::Copying<AttributeDescriptor> { public: static class AttributeDescriptor* alloc(); class AttributeDescriptor* init(); MTL::AttributeFormat format() const; void setFormat(MTL::AttributeFormat format); NS::UInteger offset() const; void setOffset(NS::UInteger offset); NS::UInteger bufferIndex() const; void setBufferIndex(NS::UInteger bufferIndex); }; class AttributeDescriptorArray : public NS::Referencing<AttributeDescriptorArray> { public: static class AttributeDescriptorArray* alloc(); class AttributeDescriptorArray* init(); class AttributeDescriptor* object(NS::UInteger index); void setObject(const class AttributeDescriptor* attributeDesc, NS::UInteger index); }; class StageInputOutputDescriptor : public NS::Copying<StageInputOutputDescriptor> { public: static class StageInputOutputDescriptor* alloc(); class StageInputOutputDescriptor* init(); static class StageInputOutputDescriptor* stageInputOutputDescriptor(); class BufferLayoutDescriptorArray* layouts() const; class AttributeDescriptorArray* attributes() const; MTL::IndexType indexType() const; void setIndexType(MTL::IndexType indexType); NS::UInteger indexBufferIndex() const; void setIndexBufferIndex(NS::UInteger indexBufferIndex); void reset(); }; } _MTL_INLINE MTL::BufferLayoutDescriptor* MTL::BufferLayoutDescriptor::alloc() { return NS::Object::alloc<MTL::BufferLayoutDescriptor>(_MTL_PRIVATE_CLS(MTLBufferLayoutDescriptor)); } _MTL_INLINE MTL::BufferLayoutDescriptor* MTL::BufferLayoutDescriptor::init() { return NS::Object::init<MTL::BufferLayoutDescriptor>(); } _MTL_INLINE NS::UInteger MTL::BufferLayoutDescriptor::stride() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(stride)); } _MTL_INLINE void MTL::BufferLayoutDescriptor::setStride(NS::UInteger stride) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStride_), stride); } _MTL_INLINE MTL::StepFunction MTL::BufferLayoutDescriptor::stepFunction() const { return Object::sendMessage<MTL::StepFunction>(this, _MTL_PRIVATE_SEL(stepFunction)); } _MTL_INLINE void MTL::BufferLayoutDescriptor::setStepFunction(MTL::StepFunction stepFunction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStepFunction_), stepFunction); } _MTL_INLINE NS::UInteger MTL::BufferLayoutDescriptor::stepRate() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(stepRate)); } _MTL_INLINE void MTL::BufferLayoutDescriptor::setStepRate(NS::UInteger stepRate) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStepRate_), stepRate); } _MTL_INLINE MTL::BufferLayoutDescriptorArray* MTL::BufferLayoutDescriptorArray::alloc() { return NS::Object::alloc<MTL::BufferLayoutDescriptorArray>(_MTL_PRIVATE_CLS(MTLBufferLayoutDescriptorArray)); } _MTL_INLINE MTL::BufferLayoutDescriptorArray* MTL::BufferLayoutDescriptorArray::init() { return NS::Object::init<MTL::BufferLayoutDescriptorArray>(); } _MTL_INLINE MTL::BufferLayoutDescriptor* MTL::BufferLayoutDescriptorArray::object(NS::UInteger index) { return Object::sendMessage<MTL::BufferLayoutDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), index); } _MTL_INLINE void MTL::BufferLayoutDescriptorArray::setObject(const MTL::BufferLayoutDescriptor* bufferDesc, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), bufferDesc, index); } _MTL_INLINE MTL::AttributeDescriptor* MTL::AttributeDescriptor::alloc() { return NS::Object::alloc<MTL::AttributeDescriptor>(_MTL_PRIVATE_CLS(MTLAttributeDescriptor)); } _MTL_INLINE MTL::AttributeDescriptor* MTL::AttributeDescriptor::init() { return NS::Object::init<MTL::AttributeDescriptor>(); } _MTL_INLINE MTL::AttributeFormat MTL::AttributeDescriptor::format() const { return Object::sendMessage<MTL::AttributeFormat>(this, _MTL_PRIVATE_SEL(format)); } _MTL_INLINE void MTL::AttributeDescriptor::setFormat(MTL::AttributeFormat format) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFormat_), format); } _MTL_INLINE NS::UInteger MTL::AttributeDescriptor::offset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(offset)); } _MTL_INLINE void MTL::AttributeDescriptor::setOffset(NS::UInteger offset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOffset_), offset); } _MTL_INLINE NS::UInteger MTL::AttributeDescriptor::bufferIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(bufferIndex)); } _MTL_INLINE void MTL::AttributeDescriptor::setBufferIndex(NS::UInteger bufferIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBufferIndex_), bufferIndex); } _MTL_INLINE MTL::AttributeDescriptorArray* MTL::AttributeDescriptorArray::alloc() { return NS::Object::alloc<MTL::AttributeDescriptorArray>(_MTL_PRIVATE_CLS(MTLAttributeDescriptorArray)); } _MTL_INLINE MTL::AttributeDescriptorArray* MTL::AttributeDescriptorArray::init() { return NS::Object::init<MTL::AttributeDescriptorArray>(); } _MTL_INLINE MTL::AttributeDescriptor* MTL::AttributeDescriptorArray::object(NS::UInteger index) { return Object::sendMessage<MTL::AttributeDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), index); } _MTL_INLINE void MTL::AttributeDescriptorArray::setObject(const MTL::AttributeDescriptor* attributeDesc, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attributeDesc, index); } _MTL_INLINE MTL::StageInputOutputDescriptor* MTL::StageInputOutputDescriptor::alloc() { return NS::Object::alloc<MTL::StageInputOutputDescriptor>(_MTL_PRIVATE_CLS(MTLStageInputOutputDescriptor)); } _MTL_INLINE MTL::StageInputOutputDescriptor* MTL::StageInputOutputDescriptor::init() { return NS::Object::init<MTL::StageInputOutputDescriptor>(); } _MTL_INLINE MTL::StageInputOutputDescriptor* MTL::StageInputOutputDescriptor::stageInputOutputDescriptor() { return Object::sendMessage<MTL::StageInputOutputDescriptor*>(_MTL_PRIVATE_CLS(MTLStageInputOutputDescriptor), _MTL_PRIVATE_SEL(stageInputOutputDescriptor)); } _MTL_INLINE MTL::BufferLayoutDescriptorArray* MTL::StageInputOutputDescriptor::layouts() const { return Object::sendMessage<MTL::BufferLayoutDescriptorArray*>(this, _MTL_PRIVATE_SEL(layouts)); } _MTL_INLINE MTL::AttributeDescriptorArray* MTL::StageInputOutputDescriptor::attributes() const { return Object::sendMessage<MTL::AttributeDescriptorArray*>(this, _MTL_PRIVATE_SEL(attributes)); } _MTL_INLINE MTL::IndexType MTL::StageInputOutputDescriptor::indexType() const { return Object::sendMessage<MTL::IndexType>(this, _MTL_PRIVATE_SEL(indexType)); } _MTL_INLINE void MTL::StageInputOutputDescriptor::setIndexType(MTL::IndexType indexType) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexType_), indexType); } _MTL_INLINE NS::UInteger MTL::StageInputOutputDescriptor::indexBufferIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(indexBufferIndex)); } _MTL_INLINE void MTL::StageInputOutputDescriptor::setIndexBufferIndex(NS::UInteger indexBufferIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexBufferIndex_), indexBufferIndex); } _MTL_INLINE void MTL::StageInputOutputDescriptor::reset() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(reset)); } namespace MTL { struct PackedFloat3 { PackedFloat3(); PackedFloat3(float x, float y, float z); float& operator[](int idx); float operator[](int idx) const; union { struct { float x; float y; float z; }; float elements[3]; }; } _MTL_PACKED; struct PackedFloat4x3 { PackedFloat4x3(); PackedFloat4x3(const PackedFloat3& col0, const PackedFloat3& col1, const PackedFloat3& col2, const PackedFloat3& col3); PackedFloat3& operator[](int idx); const PackedFloat3& operator[](int idx) const; PackedFloat3 columns[4]; } _MTL_PACKED; struct AxisAlignedBoundingBox { AxisAlignedBoundingBox(); AxisAlignedBoundingBox(PackedFloat3 p); AxisAlignedBoundingBox(PackedFloat3 min, PackedFloat3 max); PackedFloat3 min; PackedFloat3 max; } _MTL_PACKED; } _MTL_INLINE MTL::PackedFloat3::PackedFloat3() : x(0.0f) , y(0.0f) , z(0.0f) { } _MTL_INLINE MTL::PackedFloat3::PackedFloat3(float _x, float _y, float _z) : x(_x) , y(_y) , z(_z) { } _MTL_INLINE float& MTL::PackedFloat3::operator[](int idx) { return elements[idx]; } _MTL_INLINE float MTL::PackedFloat3::operator[](int idx) const { return elements[idx]; } _MTL_INLINE MTL::PackedFloat4x3::PackedFloat4x3() { columns[0] = PackedFloat3(0.0f, 0.0f, 0.0f); columns[1] = PackedFloat3(0.0f, 0.0f, 0.0f); columns[2] = PackedFloat3(0.0f, 0.0f, 0.0f); columns[3] = PackedFloat3(0.0f, 0.0f, 0.0f); } _MTL_INLINE MTL::PackedFloat4x3::PackedFloat4x3(const PackedFloat3& col0, const PackedFloat3& col1, const PackedFloat3& col2, const PackedFloat3& col3) { columns[0] = col0; columns[1] = col1; columns[2] = col2; columns[3] = col3; } _MTL_INLINE MTL::PackedFloat3& MTL::PackedFloat4x3::operator[](int idx) { return columns[idx]; } _MTL_INLINE const MTL::PackedFloat3& MTL::PackedFloat4x3::operator[](int idx) const { return columns[idx]; } _MTL_INLINE MTL::AxisAlignedBoundingBox::AxisAlignedBoundingBox() : min(INFINITY, INFINITY, INFINITY) , max(-INFINITY, -INFINITY, -INFINITY) { } _MTL_INLINE MTL::AxisAlignedBoundingBox::AxisAlignedBoundingBox(PackedFloat3 p) : min(p) , max(p) { } _MTL_INLINE MTL::AxisAlignedBoundingBox::AxisAlignedBoundingBox(PackedFloat3 _min, PackedFloat3 _max) : min(_min) , max(_max) { } namespace MTL { _MTL_OPTIONS(NS::UInteger, AccelerationStructureUsage) { AccelerationStructureUsageNone = 0, AccelerationStructureUsageRefit = 1, AccelerationStructureUsagePreferFastBuild = 2, AccelerationStructureUsageExtendedLimits = 4, }; _MTL_OPTIONS(uint32_t, AccelerationStructureInstanceOptions) { AccelerationStructureInstanceOptionNone = 0, AccelerationStructureInstanceOptionDisableTriangleCulling = 1, AccelerationStructureInstanceOptionTriangleFrontFacingWindingCounterClockwise = 2, AccelerationStructureInstanceOptionOpaque = 4, AccelerationStructureInstanceOptionNonOpaque = 8, }; class AccelerationStructureDescriptor : public NS::Copying<AccelerationStructureDescriptor> { public: static class AccelerationStructureDescriptor* alloc(); class AccelerationStructureDescriptor* init(); MTL::AccelerationStructureUsage usage() const; void setUsage(MTL::AccelerationStructureUsage usage); }; class AccelerationStructureGeometryDescriptor : public NS::Copying<AccelerationStructureGeometryDescriptor> { public: static class AccelerationStructureGeometryDescriptor* alloc(); class AccelerationStructureGeometryDescriptor* init(); NS::UInteger intersectionFunctionTableOffset() const; void setIntersectionFunctionTableOffset(NS::UInteger intersectionFunctionTableOffset); bool opaque() const; void setOpaque(bool opaque); bool allowDuplicateIntersectionFunctionInvocation() const; void setAllowDuplicateIntersectionFunctionInvocation(bool allowDuplicateIntersectionFunctionInvocation); NS::String* label() const; void setLabel(const NS::String* label); class Buffer* primitiveDataBuffer() const; void setPrimitiveDataBuffer(const class Buffer* primitiveDataBuffer); NS::UInteger primitiveDataBufferOffset() const; void setPrimitiveDataBufferOffset(NS::UInteger primitiveDataBufferOffset); NS::UInteger primitiveDataStride() const; void setPrimitiveDataStride(NS::UInteger primitiveDataStride); NS::UInteger primitiveDataElementSize() const; void setPrimitiveDataElementSize(NS::UInteger primitiveDataElementSize); }; _MTL_ENUM(uint32_t, MotionBorderMode) { MotionBorderModeClamp = 0, MotionBorderModeVanish = 1, }; class PrimitiveAccelerationStructureDescriptor : public NS::Copying<PrimitiveAccelerationStructureDescriptor, MTL::AccelerationStructureDescriptor> { public: static class PrimitiveAccelerationStructureDescriptor* alloc(); class PrimitiveAccelerationStructureDescriptor* init(); NS::Array* geometryDescriptors() const; void setGeometryDescriptors(const NS::Array* geometryDescriptors); MTL::MotionBorderMode motionStartBorderMode() const; void setMotionStartBorderMode(MTL::MotionBorderMode motionStartBorderMode); MTL::MotionBorderMode motionEndBorderMode() const; void setMotionEndBorderMode(MTL::MotionBorderMode motionEndBorderMode); float motionStartTime() const; void setMotionStartTime(float motionStartTime); float motionEndTime() const; void setMotionEndTime(float motionEndTime); NS::UInteger motionKeyframeCount() const; void setMotionKeyframeCount(NS::UInteger motionKeyframeCount); static MTL::PrimitiveAccelerationStructureDescriptor* descriptor(); }; class AccelerationStructureTriangleGeometryDescriptor : public NS::Copying<AccelerationStructureTriangleGeometryDescriptor, MTL::AccelerationStructureGeometryDescriptor> { public: static class AccelerationStructureTriangleGeometryDescriptor* alloc(); class AccelerationStructureTriangleGeometryDescriptor* init(); class Buffer* vertexBuffer() const; void setVertexBuffer(const class Buffer* vertexBuffer); NS::UInteger vertexBufferOffset() const; void setVertexBufferOffset(NS::UInteger vertexBufferOffset); MTL::AttributeFormat vertexFormat() const; void setVertexFormat(MTL::AttributeFormat vertexFormat); NS::UInteger vertexStride() const; void setVertexStride(NS::UInteger vertexStride); class Buffer* indexBuffer() const; void setIndexBuffer(const class Buffer* indexBuffer); NS::UInteger indexBufferOffset() const; void setIndexBufferOffset(NS::UInteger indexBufferOffset); MTL::IndexType indexType() const; void setIndexType(MTL::IndexType indexType); NS::UInteger triangleCount() const; void setTriangleCount(NS::UInteger triangleCount); class Buffer* transformationMatrixBuffer() const; void setTransformationMatrixBuffer(const class Buffer* transformationMatrixBuffer); NS::UInteger transformationMatrixBufferOffset() const; void setTransformationMatrixBufferOffset(NS::UInteger transformationMatrixBufferOffset); static MTL::AccelerationStructureTriangleGeometryDescriptor* descriptor(); }; class AccelerationStructureBoundingBoxGeometryDescriptor : public NS::Copying<AccelerationStructureBoundingBoxGeometryDescriptor, MTL::AccelerationStructureGeometryDescriptor> { public: static class AccelerationStructureBoundingBoxGeometryDescriptor* alloc(); class AccelerationStructureBoundingBoxGeometryDescriptor* init(); class Buffer* boundingBoxBuffer() const; void setBoundingBoxBuffer(const class Buffer* boundingBoxBuffer); NS::UInteger boundingBoxBufferOffset() const; void setBoundingBoxBufferOffset(NS::UInteger boundingBoxBufferOffset); NS::UInteger boundingBoxStride() const; void setBoundingBoxStride(NS::UInteger boundingBoxStride); NS::UInteger boundingBoxCount() const; void setBoundingBoxCount(NS::UInteger boundingBoxCount); static MTL::AccelerationStructureBoundingBoxGeometryDescriptor* descriptor(); }; class MotionKeyframeData : public NS::Referencing<MotionKeyframeData> { public: static class MotionKeyframeData* alloc(); class MotionKeyframeData* init(); class Buffer* buffer() const; void setBuffer(const class Buffer* buffer); NS::UInteger offset() const; void setOffset(NS::UInteger offset); static MTL::MotionKeyframeData* data(); }; class AccelerationStructureMotionTriangleGeometryDescriptor : public NS::Copying<AccelerationStructureMotionTriangleGeometryDescriptor, MTL::AccelerationStructureGeometryDescriptor> { public: static class AccelerationStructureMotionTriangleGeometryDescriptor* alloc(); class AccelerationStructureMotionTriangleGeometryDescriptor* init(); NS::Array* vertexBuffers() const; void setVertexBuffers(const NS::Array* vertexBuffers); MTL::AttributeFormat vertexFormat() const; void setVertexFormat(MTL::AttributeFormat vertexFormat); NS::UInteger vertexStride() const; void setVertexStride(NS::UInteger vertexStride); class Buffer* indexBuffer() const; void setIndexBuffer(const class Buffer* indexBuffer); NS::UInteger indexBufferOffset() const; void setIndexBufferOffset(NS::UInteger indexBufferOffset); MTL::IndexType indexType() const; void setIndexType(MTL::IndexType indexType); NS::UInteger triangleCount() const; void setTriangleCount(NS::UInteger triangleCount); class Buffer* transformationMatrixBuffer() const; void setTransformationMatrixBuffer(const class Buffer* transformationMatrixBuffer); NS::UInteger transformationMatrixBufferOffset() const; void setTransformationMatrixBufferOffset(NS::UInteger transformationMatrixBufferOffset); static MTL::AccelerationStructureMotionTriangleGeometryDescriptor* descriptor(); }; class AccelerationStructureMotionBoundingBoxGeometryDescriptor : public NS::Copying<AccelerationStructureMotionBoundingBoxGeometryDescriptor, MTL::AccelerationStructureGeometryDescriptor> { public: static class AccelerationStructureMotionBoundingBoxGeometryDescriptor* alloc(); class AccelerationStructureMotionBoundingBoxGeometryDescriptor* init(); NS::Array* boundingBoxBuffers() const; void setBoundingBoxBuffers(const NS::Array* boundingBoxBuffers); NS::UInteger boundingBoxStride() const; void setBoundingBoxStride(NS::UInteger boundingBoxStride); NS::UInteger boundingBoxCount() const; void setBoundingBoxCount(NS::UInteger boundingBoxCount); static MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor* descriptor(); }; _MTL_ENUM(NS::Integer, CurveType) { CurveTypeRound = 0, CurveTypeFlat = 1, }; _MTL_ENUM(NS::Integer, CurveBasis) { CurveBasisBSpline = 0, CurveBasisCatmullRom = 1, CurveBasisLinear = 2, CurveBasisBezier = 3, }; _MTL_ENUM(NS::Integer, CurveEndCaps) { CurveEndCapsNone = 0, CurveEndCapsDisk = 1, CurveEndCapsSphere = 2, }; class AccelerationStructureCurveGeometryDescriptor : public NS::Copying<AccelerationStructureCurveGeometryDescriptor, MTL::AccelerationStructureGeometryDescriptor> { public: static class AccelerationStructureCurveGeometryDescriptor* alloc(); class AccelerationStructureCurveGeometryDescriptor* init(); class Buffer* controlPointBuffer() const; void setControlPointBuffer(const class Buffer* controlPointBuffer); NS::UInteger controlPointBufferOffset() const; void setControlPointBufferOffset(NS::UInteger controlPointBufferOffset); NS::UInteger controlPointCount() const; void setControlPointCount(NS::UInteger controlPointCount); NS::UInteger controlPointStride() const; void setControlPointStride(NS::UInteger controlPointStride); MTL::AttributeFormat controlPointFormat() const; void setControlPointFormat(MTL::AttributeFormat controlPointFormat); class Buffer* radiusBuffer() const; void setRadiusBuffer(const class Buffer* radiusBuffer); NS::UInteger radiusBufferOffset() const; void setRadiusBufferOffset(NS::UInteger radiusBufferOffset); MTL::AttributeFormat radiusFormat() const; void setRadiusFormat(MTL::AttributeFormat radiusFormat); NS::UInteger radiusStride() const; void setRadiusStride(NS::UInteger radiusStride); class Buffer* indexBuffer() const; void setIndexBuffer(const class Buffer* indexBuffer); NS::UInteger indexBufferOffset() const; void setIndexBufferOffset(NS::UInteger indexBufferOffset); MTL::IndexType indexType() const; void setIndexType(MTL::IndexType indexType); NS::UInteger segmentCount() const; void setSegmentCount(NS::UInteger segmentCount); NS::UInteger segmentControlPointCount() const; void setSegmentControlPointCount(NS::UInteger segmentControlPointCount); MTL::CurveType curveType() const; void setCurveType(MTL::CurveType curveType); MTL::CurveBasis curveBasis() const; void setCurveBasis(MTL::CurveBasis curveBasis); MTL::CurveEndCaps curveEndCaps() const; void setCurveEndCaps(MTL::CurveEndCaps curveEndCaps); static MTL::AccelerationStructureCurveGeometryDescriptor* descriptor(); }; class AccelerationStructureMotionCurveGeometryDescriptor : public NS::Copying<AccelerationStructureMotionCurveGeometryDescriptor, MTL::AccelerationStructureGeometryDescriptor> { public: static class AccelerationStructureMotionCurveGeometryDescriptor* alloc(); class AccelerationStructureMotionCurveGeometryDescriptor* init(); NS::Array* controlPointBuffers() const; void setControlPointBuffers(const NS::Array* controlPointBuffers); NS::UInteger controlPointCount() const; void setControlPointCount(NS::UInteger controlPointCount); NS::UInteger controlPointStride() const; void setControlPointStride(NS::UInteger controlPointStride); MTL::AttributeFormat controlPointFormat() const; void setControlPointFormat(MTL::AttributeFormat controlPointFormat); NS::Array* radiusBuffers() const; void setRadiusBuffers(const NS::Array* radiusBuffers); MTL::AttributeFormat radiusFormat() const; void setRadiusFormat(MTL::AttributeFormat radiusFormat); NS::UInteger radiusStride() const; void setRadiusStride(NS::UInteger radiusStride); class Buffer* indexBuffer() const; void setIndexBuffer(const class Buffer* indexBuffer); NS::UInteger indexBufferOffset() const; void setIndexBufferOffset(NS::UInteger indexBufferOffset); MTL::IndexType indexType() const; void setIndexType(MTL::IndexType indexType); NS::UInteger segmentCount() const; void setSegmentCount(NS::UInteger segmentCount); NS::UInteger segmentControlPointCount() const; void setSegmentControlPointCount(NS::UInteger segmentControlPointCount); MTL::CurveType curveType() const; void setCurveType(MTL::CurveType curveType); MTL::CurveBasis curveBasis() const; void setCurveBasis(MTL::CurveBasis curveBasis); MTL::CurveEndCaps curveEndCaps() const; void setCurveEndCaps(MTL::CurveEndCaps curveEndCaps); static MTL::AccelerationStructureMotionCurveGeometryDescriptor* descriptor(); }; struct AccelerationStructureInstanceDescriptor { MTL::PackedFloat4x3 transformationMatrix; MTL::AccelerationStructureInstanceOptions options; uint32_t mask; uint32_t intersectionFunctionTableOffset; uint32_t accelerationStructureIndex; } _MTL_PACKED; struct AccelerationStructureUserIDInstanceDescriptor { MTL::PackedFloat4x3 transformationMatrix; MTL::AccelerationStructureInstanceOptions options; uint32_t mask; uint32_t intersectionFunctionTableOffset; uint32_t accelerationStructureIndex; uint32_t userID; } _MTL_PACKED; _MTL_ENUM(NS::UInteger, AccelerationStructureInstanceDescriptorType) { AccelerationStructureInstanceDescriptorTypeDefault = 0, AccelerationStructureInstanceDescriptorTypeUserID = 1, AccelerationStructureInstanceDescriptorTypeMotion = 2, AccelerationStructureInstanceDescriptorTypeIndirect = 3, AccelerationStructureInstanceDescriptorTypeIndirectMotion = 4, }; struct AccelerationStructureMotionInstanceDescriptor { MTL::AccelerationStructureInstanceOptions options; uint32_t mask; uint32_t intersectionFunctionTableOffset; uint32_t accelerationStructureIndex; uint32_t userID; uint32_t motionTransformsStartIndex; uint32_t motionTransformsCount; MTL::MotionBorderMode motionStartBorderMode; MTL::MotionBorderMode motionEndBorderMode; float motionStartTime; float motionEndTime; } _MTL_PACKED; struct IndirectAccelerationStructureInstanceDescriptor { MTL::PackedFloat4x3 transformationMatrix; MTL::AccelerationStructureInstanceOptions options; uint32_t mask; uint32_t intersectionFunctionTableOffset; uint32_t userID; MTL::ResourceID accelerationStructureID; } _MTL_PACKED; struct IndirectAccelerationStructureMotionInstanceDescriptor { MTL::AccelerationStructureInstanceOptions options; uint32_t mask; uint32_t intersectionFunctionTableOffset; uint32_t userID; MTL::ResourceID accelerationStructureID; uint32_t motionTransformsStartIndex; uint32_t motionTransformsCount; MTL::MotionBorderMode motionStartBorderMode; MTL::MotionBorderMode motionEndBorderMode; float motionStartTime; float motionEndTime; } _MTL_PACKED; class InstanceAccelerationStructureDescriptor : public NS::Copying<InstanceAccelerationStructureDescriptor, MTL::AccelerationStructureDescriptor> { public: static class InstanceAccelerationStructureDescriptor* alloc(); class InstanceAccelerationStructureDescriptor* init(); class Buffer* instanceDescriptorBuffer() const; void setInstanceDescriptorBuffer(const class Buffer* instanceDescriptorBuffer); NS::UInteger instanceDescriptorBufferOffset() const; void setInstanceDescriptorBufferOffset(NS::UInteger instanceDescriptorBufferOffset); NS::UInteger instanceDescriptorStride() const; void setInstanceDescriptorStride(NS::UInteger instanceDescriptorStride); NS::UInteger instanceCount() const; void setInstanceCount(NS::UInteger instanceCount); NS::Array* instancedAccelerationStructures() const; void setInstancedAccelerationStructures(const NS::Array* instancedAccelerationStructures); MTL::AccelerationStructureInstanceDescriptorType instanceDescriptorType() const; void setInstanceDescriptorType(MTL::AccelerationStructureInstanceDescriptorType instanceDescriptorType); class Buffer* motionTransformBuffer() const; void setMotionTransformBuffer(const class Buffer* motionTransformBuffer); NS::UInteger motionTransformBufferOffset() const; void setMotionTransformBufferOffset(NS::UInteger motionTransformBufferOffset); NS::UInteger motionTransformCount() const; void setMotionTransformCount(NS::UInteger motionTransformCount); static MTL::InstanceAccelerationStructureDescriptor* descriptor(); }; class IndirectInstanceAccelerationStructureDescriptor : public NS::Copying<IndirectInstanceAccelerationStructureDescriptor, MTL::AccelerationStructureDescriptor> { public: static class IndirectInstanceAccelerationStructureDescriptor* alloc(); class IndirectInstanceAccelerationStructureDescriptor* init(); class Buffer* instanceDescriptorBuffer() const; void setInstanceDescriptorBuffer(const class Buffer* instanceDescriptorBuffer); NS::UInteger instanceDescriptorBufferOffset() const; void setInstanceDescriptorBufferOffset(NS::UInteger instanceDescriptorBufferOffset); NS::UInteger instanceDescriptorStride() const; void setInstanceDescriptorStride(NS::UInteger instanceDescriptorStride); NS::UInteger maxInstanceCount() const; void setMaxInstanceCount(NS::UInteger maxInstanceCount); class Buffer* instanceCountBuffer() const; void setInstanceCountBuffer(const class Buffer* instanceCountBuffer); NS::UInteger instanceCountBufferOffset() const; void setInstanceCountBufferOffset(NS::UInteger instanceCountBufferOffset); MTL::AccelerationStructureInstanceDescriptorType instanceDescriptorType() const; void setInstanceDescriptorType(MTL::AccelerationStructureInstanceDescriptorType instanceDescriptorType); class Buffer* motionTransformBuffer() const; void setMotionTransformBuffer(const class Buffer* motionTransformBuffer); NS::UInteger motionTransformBufferOffset() const; void setMotionTransformBufferOffset(NS::UInteger motionTransformBufferOffset); NS::UInteger maxMotionTransformCount() const; void setMaxMotionTransformCount(NS::UInteger maxMotionTransformCount); class Buffer* motionTransformCountBuffer() const; void setMotionTransformCountBuffer(const class Buffer* motionTransformCountBuffer); NS::UInteger motionTransformCountBufferOffset() const; void setMotionTransformCountBufferOffset(NS::UInteger motionTransformCountBufferOffset); static MTL::IndirectInstanceAccelerationStructureDescriptor* descriptor(); }; class AccelerationStructure : public NS::Referencing<AccelerationStructure, Resource> { public: NS::UInteger size() const; MTL::ResourceID gpuResourceID() const; }; } _MTL_INLINE MTL::AccelerationStructureDescriptor* MTL::AccelerationStructureDescriptor::alloc() { return NS::Object::alloc<MTL::AccelerationStructureDescriptor>(_MTL_PRIVATE_CLS(MTLAccelerationStructureDescriptor)); } _MTL_INLINE MTL::AccelerationStructureDescriptor* MTL::AccelerationStructureDescriptor::init() { return NS::Object::init<MTL::AccelerationStructureDescriptor>(); } _MTL_INLINE MTL::AccelerationStructureUsage MTL::AccelerationStructureDescriptor::usage() const { return Object::sendMessage<MTL::AccelerationStructureUsage>(this, _MTL_PRIVATE_SEL(usage)); } _MTL_INLINE void MTL::AccelerationStructureDescriptor::setUsage(MTL::AccelerationStructureUsage usage) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setUsage_), usage); } _MTL_INLINE MTL::AccelerationStructureGeometryDescriptor* MTL::AccelerationStructureGeometryDescriptor::alloc() { return NS::Object::alloc<MTL::AccelerationStructureGeometryDescriptor>(_MTL_PRIVATE_CLS(MTLAccelerationStructureGeometryDescriptor)); } _MTL_INLINE MTL::AccelerationStructureGeometryDescriptor* MTL::AccelerationStructureGeometryDescriptor::init() { return NS::Object::init<MTL::AccelerationStructureGeometryDescriptor>(); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureGeometryDescriptor::intersectionFunctionTableOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(intersectionFunctionTableOffset)); } _MTL_INLINE void MTL::AccelerationStructureGeometryDescriptor::setIntersectionFunctionTableOffset(NS::UInteger intersectionFunctionTableOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIntersectionFunctionTableOffset_), intersectionFunctionTableOffset); } _MTL_INLINE bool MTL::AccelerationStructureGeometryDescriptor::opaque() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(opaque)); } _MTL_INLINE void MTL::AccelerationStructureGeometryDescriptor::setOpaque(bool opaque) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOpaque_), opaque); } _MTL_INLINE bool MTL::AccelerationStructureGeometryDescriptor::allowDuplicateIntersectionFunctionInvocation() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(allowDuplicateIntersectionFunctionInvocation)); } _MTL_INLINE void MTL::AccelerationStructureGeometryDescriptor::setAllowDuplicateIntersectionFunctionInvocation(bool allowDuplicateIntersectionFunctionInvocation) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAllowDuplicateIntersectionFunctionInvocation_), allowDuplicateIntersectionFunctionInvocation); } _MTL_INLINE NS::String* MTL::AccelerationStructureGeometryDescriptor::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::AccelerationStructureGeometryDescriptor::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE MTL::Buffer* MTL::AccelerationStructureGeometryDescriptor::primitiveDataBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(primitiveDataBuffer)); } _MTL_INLINE void MTL::AccelerationStructureGeometryDescriptor::setPrimitiveDataBuffer(const MTL::Buffer* primitiveDataBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPrimitiveDataBuffer_), primitiveDataBuffer); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureGeometryDescriptor::primitiveDataBufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(primitiveDataBufferOffset)); } _MTL_INLINE void MTL::AccelerationStructureGeometryDescriptor::setPrimitiveDataBufferOffset(NS::UInteger primitiveDataBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPrimitiveDataBufferOffset_), primitiveDataBufferOffset); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureGeometryDescriptor::primitiveDataStride() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(primitiveDataStride)); } _MTL_INLINE void MTL::AccelerationStructureGeometryDescriptor::setPrimitiveDataStride(NS::UInteger primitiveDataStride) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPrimitiveDataStride_), primitiveDataStride); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureGeometryDescriptor::primitiveDataElementSize() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(primitiveDataElementSize)); } _MTL_INLINE void MTL::AccelerationStructureGeometryDescriptor::setPrimitiveDataElementSize(NS::UInteger primitiveDataElementSize) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPrimitiveDataElementSize_), primitiveDataElementSize); } _MTL_INLINE MTL::PrimitiveAccelerationStructureDescriptor* MTL::PrimitiveAccelerationStructureDescriptor::alloc() { return NS::Object::alloc<MTL::PrimitiveAccelerationStructureDescriptor>(_MTL_PRIVATE_CLS(MTLPrimitiveAccelerationStructureDescriptor)); } _MTL_INLINE MTL::PrimitiveAccelerationStructureDescriptor* MTL::PrimitiveAccelerationStructureDescriptor::init() { return NS::Object::init<MTL::PrimitiveAccelerationStructureDescriptor>(); } _MTL_INLINE NS::Array* MTL::PrimitiveAccelerationStructureDescriptor::geometryDescriptors() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(geometryDescriptors)); } _MTL_INLINE void MTL::PrimitiveAccelerationStructureDescriptor::setGeometryDescriptors(const NS::Array* geometryDescriptors) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setGeometryDescriptors_), geometryDescriptors); } _MTL_INLINE MTL::MotionBorderMode MTL::PrimitiveAccelerationStructureDescriptor::motionStartBorderMode() const { return Object::sendMessage<MTL::MotionBorderMode>(this, _MTL_PRIVATE_SEL(motionStartBorderMode)); } _MTL_INLINE void MTL::PrimitiveAccelerationStructureDescriptor::setMotionStartBorderMode(MTL::MotionBorderMode motionStartBorderMode) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionStartBorderMode_), motionStartBorderMode); } _MTL_INLINE MTL::MotionBorderMode MTL::PrimitiveAccelerationStructureDescriptor::motionEndBorderMode() const { return Object::sendMessage<MTL::MotionBorderMode>(this, _MTL_PRIVATE_SEL(motionEndBorderMode)); } _MTL_INLINE void MTL::PrimitiveAccelerationStructureDescriptor::setMotionEndBorderMode(MTL::MotionBorderMode motionEndBorderMode) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionEndBorderMode_), motionEndBorderMode); } _MTL_INLINE float MTL::PrimitiveAccelerationStructureDescriptor::motionStartTime() const { return Object::sendMessage<float>(this, _MTL_PRIVATE_SEL(motionStartTime)); } _MTL_INLINE void MTL::PrimitiveAccelerationStructureDescriptor::setMotionStartTime(float motionStartTime) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionStartTime_), motionStartTime); } _MTL_INLINE float MTL::PrimitiveAccelerationStructureDescriptor::motionEndTime() const { return Object::sendMessage<float>(this, _MTL_PRIVATE_SEL(motionEndTime)); } _MTL_INLINE void MTL::PrimitiveAccelerationStructureDescriptor::setMotionEndTime(float motionEndTime) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionEndTime_), motionEndTime); } _MTL_INLINE NS::UInteger MTL::PrimitiveAccelerationStructureDescriptor::motionKeyframeCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(motionKeyframeCount)); } _MTL_INLINE void MTL::PrimitiveAccelerationStructureDescriptor::setMotionKeyframeCount(NS::UInteger motionKeyframeCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionKeyframeCount_), motionKeyframeCount); } _MTL_INLINE MTL::PrimitiveAccelerationStructureDescriptor* MTL::PrimitiveAccelerationStructureDescriptor::descriptor() { return Object::sendMessage<MTL::PrimitiveAccelerationStructureDescriptor*>(_MTL_PRIVATE_CLS(MTLPrimitiveAccelerationStructureDescriptor), _MTL_PRIVATE_SEL(descriptor)); } _MTL_INLINE MTL::AccelerationStructureTriangleGeometryDescriptor* MTL::AccelerationStructureTriangleGeometryDescriptor::alloc() { return NS::Object::alloc<MTL::AccelerationStructureTriangleGeometryDescriptor>(_MTL_PRIVATE_CLS(MTLAccelerationStructureTriangleGeometryDescriptor)); } _MTL_INLINE MTL::AccelerationStructureTriangleGeometryDescriptor* MTL::AccelerationStructureTriangleGeometryDescriptor::init() { return NS::Object::init<MTL::AccelerationStructureTriangleGeometryDescriptor>(); } _MTL_INLINE MTL::Buffer* MTL::AccelerationStructureTriangleGeometryDescriptor::vertexBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(vertexBuffer)); } _MTL_INLINE void MTL::AccelerationStructureTriangleGeometryDescriptor::setVertexBuffer(const MTL::Buffer* vertexBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBuffer_), vertexBuffer); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureTriangleGeometryDescriptor::vertexBufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(vertexBufferOffset)); } _MTL_INLINE void MTL::AccelerationStructureTriangleGeometryDescriptor::setVertexBufferOffset(NS::UInteger vertexBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBufferOffset_), vertexBufferOffset); } _MTL_INLINE MTL::AttributeFormat MTL::AccelerationStructureTriangleGeometryDescriptor::vertexFormat() const { return Object::sendMessage<MTL::AttributeFormat>(this, _MTL_PRIVATE_SEL(vertexFormat)); } _MTL_INLINE void MTL::AccelerationStructureTriangleGeometryDescriptor::setVertexFormat(MTL::AttributeFormat vertexFormat) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexFormat_), vertexFormat); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureTriangleGeometryDescriptor::vertexStride() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(vertexStride)); } _MTL_INLINE void MTL::AccelerationStructureTriangleGeometryDescriptor::setVertexStride(NS::UInteger vertexStride) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexStride_), vertexStride); } _MTL_INLINE MTL::Buffer* MTL::AccelerationStructureTriangleGeometryDescriptor::indexBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(indexBuffer)); } _MTL_INLINE void MTL::AccelerationStructureTriangleGeometryDescriptor::setIndexBuffer(const MTL::Buffer* indexBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexBuffer_), indexBuffer); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureTriangleGeometryDescriptor::indexBufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(indexBufferOffset)); } _MTL_INLINE void MTL::AccelerationStructureTriangleGeometryDescriptor::setIndexBufferOffset(NS::UInteger indexBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexBufferOffset_), indexBufferOffset); } _MTL_INLINE MTL::IndexType MTL::AccelerationStructureTriangleGeometryDescriptor::indexType() const { return Object::sendMessage<MTL::IndexType>(this, _MTL_PRIVATE_SEL(indexType)); } _MTL_INLINE void MTL::AccelerationStructureTriangleGeometryDescriptor::setIndexType(MTL::IndexType indexType) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexType_), indexType); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureTriangleGeometryDescriptor::triangleCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(triangleCount)); } _MTL_INLINE void MTL::AccelerationStructureTriangleGeometryDescriptor::setTriangleCount(NS::UInteger triangleCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTriangleCount_), triangleCount); } _MTL_INLINE MTL::Buffer* MTL::AccelerationStructureTriangleGeometryDescriptor::transformationMatrixBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(transformationMatrixBuffer)); } _MTL_INLINE void MTL::AccelerationStructureTriangleGeometryDescriptor::setTransformationMatrixBuffer(const MTL::Buffer* transformationMatrixBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTransformationMatrixBuffer_), transformationMatrixBuffer); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureTriangleGeometryDescriptor::transformationMatrixBufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(transformationMatrixBufferOffset)); } _MTL_INLINE void MTL::AccelerationStructureTriangleGeometryDescriptor::setTransformationMatrixBufferOffset(NS::UInteger transformationMatrixBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTransformationMatrixBufferOffset_), transformationMatrixBufferOffset); } _MTL_INLINE MTL::AccelerationStructureTriangleGeometryDescriptor* MTL::AccelerationStructureTriangleGeometryDescriptor::descriptor() { return Object::sendMessage<MTL::AccelerationStructureTriangleGeometryDescriptor*>(_MTL_PRIVATE_CLS(MTLAccelerationStructureTriangleGeometryDescriptor), _MTL_PRIVATE_SEL(descriptor)); } _MTL_INLINE MTL::AccelerationStructureBoundingBoxGeometryDescriptor* MTL::AccelerationStructureBoundingBoxGeometryDescriptor::alloc() { return NS::Object::alloc<MTL::AccelerationStructureBoundingBoxGeometryDescriptor>(_MTL_PRIVATE_CLS(MTLAccelerationStructureBoundingBoxGeometryDescriptor)); } _MTL_INLINE MTL::AccelerationStructureBoundingBoxGeometryDescriptor* MTL::AccelerationStructureBoundingBoxGeometryDescriptor::init() { return NS::Object::init<MTL::AccelerationStructureBoundingBoxGeometryDescriptor>(); } _MTL_INLINE MTL::Buffer* MTL::AccelerationStructureBoundingBoxGeometryDescriptor::boundingBoxBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(boundingBoxBuffer)); } _MTL_INLINE void MTL::AccelerationStructureBoundingBoxGeometryDescriptor::setBoundingBoxBuffer(const MTL::Buffer* boundingBoxBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBoundingBoxBuffer_), boundingBoxBuffer); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureBoundingBoxGeometryDescriptor::boundingBoxBufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(boundingBoxBufferOffset)); } _MTL_INLINE void MTL::AccelerationStructureBoundingBoxGeometryDescriptor::setBoundingBoxBufferOffset(NS::UInteger boundingBoxBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBoundingBoxBufferOffset_), boundingBoxBufferOffset); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureBoundingBoxGeometryDescriptor::boundingBoxStride() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(boundingBoxStride)); } _MTL_INLINE void MTL::AccelerationStructureBoundingBoxGeometryDescriptor::setBoundingBoxStride(NS::UInteger boundingBoxStride) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBoundingBoxStride_), boundingBoxStride); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureBoundingBoxGeometryDescriptor::boundingBoxCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(boundingBoxCount)); } _MTL_INLINE void MTL::AccelerationStructureBoundingBoxGeometryDescriptor::setBoundingBoxCount(NS::UInteger boundingBoxCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBoundingBoxCount_), boundingBoxCount); } _MTL_INLINE MTL::AccelerationStructureBoundingBoxGeometryDescriptor* MTL::AccelerationStructureBoundingBoxGeometryDescriptor::descriptor() { return Object::sendMessage<MTL::AccelerationStructureBoundingBoxGeometryDescriptor*>(_MTL_PRIVATE_CLS(MTLAccelerationStructureBoundingBoxGeometryDescriptor), _MTL_PRIVATE_SEL(descriptor)); } _MTL_INLINE MTL::MotionKeyframeData* MTL::MotionKeyframeData::alloc() { return NS::Object::alloc<MTL::MotionKeyframeData>(_MTL_PRIVATE_CLS(MTLMotionKeyframeData)); } _MTL_INLINE MTL::MotionKeyframeData* MTL::MotionKeyframeData::init() { return NS::Object::init<MTL::MotionKeyframeData>(); } _MTL_INLINE MTL::Buffer* MTL::MotionKeyframeData::buffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(buffer)); } _MTL_INLINE void MTL::MotionKeyframeData::setBuffer(const MTL::Buffer* buffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBuffer_), buffer); } _MTL_INLINE NS::UInteger MTL::MotionKeyframeData::offset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(offset)); } _MTL_INLINE void MTL::MotionKeyframeData::setOffset(NS::UInteger offset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOffset_), offset); } _MTL_INLINE MTL::MotionKeyframeData* MTL::MotionKeyframeData::data() { return Object::sendMessage<MTL::MotionKeyframeData*>(_MTL_PRIVATE_CLS(MTLMotionKeyframeData), _MTL_PRIVATE_SEL(data)); } _MTL_INLINE MTL::AccelerationStructureMotionTriangleGeometryDescriptor* MTL::AccelerationStructureMotionTriangleGeometryDescriptor::alloc() { return NS::Object::alloc<MTL::AccelerationStructureMotionTriangleGeometryDescriptor>(_MTL_PRIVATE_CLS(MTLAccelerationStructureMotionTriangleGeometryDescriptor)); } _MTL_INLINE MTL::AccelerationStructureMotionTriangleGeometryDescriptor* MTL::AccelerationStructureMotionTriangleGeometryDescriptor::init() { return NS::Object::init<MTL::AccelerationStructureMotionTriangleGeometryDescriptor>(); } _MTL_INLINE NS::Array* MTL::AccelerationStructureMotionTriangleGeometryDescriptor::vertexBuffers() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(vertexBuffers)); } _MTL_INLINE void MTL::AccelerationStructureMotionTriangleGeometryDescriptor::setVertexBuffers(const NS::Array* vertexBuffers) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBuffers_), vertexBuffers); } _MTL_INLINE MTL::AttributeFormat MTL::AccelerationStructureMotionTriangleGeometryDescriptor::vertexFormat() const { return Object::sendMessage<MTL::AttributeFormat>(this, _MTL_PRIVATE_SEL(vertexFormat)); } _MTL_INLINE void MTL::AccelerationStructureMotionTriangleGeometryDescriptor::setVertexFormat(MTL::AttributeFormat vertexFormat) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexFormat_), vertexFormat); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureMotionTriangleGeometryDescriptor::vertexStride() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(vertexStride)); } _MTL_INLINE void MTL::AccelerationStructureMotionTriangleGeometryDescriptor::setVertexStride(NS::UInteger vertexStride) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexStride_), vertexStride); } _MTL_INLINE MTL::Buffer* MTL::AccelerationStructureMotionTriangleGeometryDescriptor::indexBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(indexBuffer)); } _MTL_INLINE void MTL::AccelerationStructureMotionTriangleGeometryDescriptor::setIndexBuffer(const MTL::Buffer* indexBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexBuffer_), indexBuffer); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureMotionTriangleGeometryDescriptor::indexBufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(indexBufferOffset)); } _MTL_INLINE void MTL::AccelerationStructureMotionTriangleGeometryDescriptor::setIndexBufferOffset(NS::UInteger indexBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexBufferOffset_), indexBufferOffset); } _MTL_INLINE MTL::IndexType MTL::AccelerationStructureMotionTriangleGeometryDescriptor::indexType() const { return Object::sendMessage<MTL::IndexType>(this, _MTL_PRIVATE_SEL(indexType)); } _MTL_INLINE void MTL::AccelerationStructureMotionTriangleGeometryDescriptor::setIndexType(MTL::IndexType indexType) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexType_), indexType); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureMotionTriangleGeometryDescriptor::triangleCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(triangleCount)); } _MTL_INLINE void MTL::AccelerationStructureMotionTriangleGeometryDescriptor::setTriangleCount(NS::UInteger triangleCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTriangleCount_), triangleCount); } _MTL_INLINE MTL::Buffer* MTL::AccelerationStructureMotionTriangleGeometryDescriptor::transformationMatrixBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(transformationMatrixBuffer)); } _MTL_INLINE void MTL::AccelerationStructureMotionTriangleGeometryDescriptor::setTransformationMatrixBuffer(const MTL::Buffer* transformationMatrixBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTransformationMatrixBuffer_), transformationMatrixBuffer); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureMotionTriangleGeometryDescriptor::transformationMatrixBufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(transformationMatrixBufferOffset)); } _MTL_INLINE void MTL::AccelerationStructureMotionTriangleGeometryDescriptor::setTransformationMatrixBufferOffset(NS::UInteger transformationMatrixBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTransformationMatrixBufferOffset_), transformationMatrixBufferOffset); } _MTL_INLINE MTL::AccelerationStructureMotionTriangleGeometryDescriptor* MTL::AccelerationStructureMotionTriangleGeometryDescriptor::descriptor() { return Object::sendMessage<MTL::AccelerationStructureMotionTriangleGeometryDescriptor*>(_MTL_PRIVATE_CLS(MTLAccelerationStructureMotionTriangleGeometryDescriptor), _MTL_PRIVATE_SEL(descriptor)); } _MTL_INLINE MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor* MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::alloc() { return NS::Object::alloc<MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor>(_MTL_PRIVATE_CLS(MTLAccelerationStructureMotionBoundingBoxGeometryDescriptor)); } _MTL_INLINE MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor* MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::init() { return NS::Object::init<MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor>(); } _MTL_INLINE NS::Array* MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::boundingBoxBuffers() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(boundingBoxBuffers)); } _MTL_INLINE void MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::setBoundingBoxBuffers(const NS::Array* boundingBoxBuffers) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBoundingBoxBuffers_), boundingBoxBuffers); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::boundingBoxStride() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(boundingBoxStride)); } _MTL_INLINE void MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::setBoundingBoxStride(NS::UInteger boundingBoxStride) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBoundingBoxStride_), boundingBoxStride); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::boundingBoxCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(boundingBoxCount)); } _MTL_INLINE void MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::setBoundingBoxCount(NS::UInteger boundingBoxCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBoundingBoxCount_), boundingBoxCount); } _MTL_INLINE MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor* MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor::descriptor() { return Object::sendMessage<MTL::AccelerationStructureMotionBoundingBoxGeometryDescriptor*>(_MTL_PRIVATE_CLS(MTLAccelerationStructureMotionBoundingBoxGeometryDescriptor), _MTL_PRIVATE_SEL(descriptor)); } _MTL_INLINE MTL::AccelerationStructureCurveGeometryDescriptor* MTL::AccelerationStructureCurveGeometryDescriptor::alloc() { return NS::Object::alloc<MTL::AccelerationStructureCurveGeometryDescriptor>(_MTL_PRIVATE_CLS(MTLAccelerationStructureCurveGeometryDescriptor)); } _MTL_INLINE MTL::AccelerationStructureCurveGeometryDescriptor* MTL::AccelerationStructureCurveGeometryDescriptor::init() { return NS::Object::init<MTL::AccelerationStructureCurveGeometryDescriptor>(); } _MTL_INLINE MTL::Buffer* MTL::AccelerationStructureCurveGeometryDescriptor::controlPointBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(controlPointBuffer)); } _MTL_INLINE void MTL::AccelerationStructureCurveGeometryDescriptor::setControlPointBuffer(const MTL::Buffer* controlPointBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setControlPointBuffer_), controlPointBuffer); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureCurveGeometryDescriptor::controlPointBufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(controlPointBufferOffset)); } _MTL_INLINE void MTL::AccelerationStructureCurveGeometryDescriptor::setControlPointBufferOffset(NS::UInteger controlPointBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setControlPointBufferOffset_), controlPointBufferOffset); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureCurveGeometryDescriptor::controlPointCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(controlPointCount)); } _MTL_INLINE void MTL::AccelerationStructureCurveGeometryDescriptor::setControlPointCount(NS::UInteger controlPointCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setControlPointCount_), controlPointCount); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureCurveGeometryDescriptor::controlPointStride() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(controlPointStride)); } _MTL_INLINE void MTL::AccelerationStructureCurveGeometryDescriptor::setControlPointStride(NS::UInteger controlPointStride) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setControlPointStride_), controlPointStride); } _MTL_INLINE MTL::AttributeFormat MTL::AccelerationStructureCurveGeometryDescriptor::controlPointFormat() const { return Object::sendMessage<MTL::AttributeFormat>(this, _MTL_PRIVATE_SEL(controlPointFormat)); } _MTL_INLINE void MTL::AccelerationStructureCurveGeometryDescriptor::setControlPointFormat(MTL::AttributeFormat controlPointFormat) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setControlPointFormat_), controlPointFormat); } _MTL_INLINE MTL::Buffer* MTL::AccelerationStructureCurveGeometryDescriptor::radiusBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(radiusBuffer)); } _MTL_INLINE void MTL::AccelerationStructureCurveGeometryDescriptor::setRadiusBuffer(const MTL::Buffer* radiusBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRadiusBuffer_), radiusBuffer); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureCurveGeometryDescriptor::radiusBufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(radiusBufferOffset)); } _MTL_INLINE void MTL::AccelerationStructureCurveGeometryDescriptor::setRadiusBufferOffset(NS::UInteger radiusBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRadiusBufferOffset_), radiusBufferOffset); } _MTL_INLINE MTL::AttributeFormat MTL::AccelerationStructureCurveGeometryDescriptor::radiusFormat() const { return Object::sendMessage<MTL::AttributeFormat>(this, _MTL_PRIVATE_SEL(radiusFormat)); } _MTL_INLINE void MTL::AccelerationStructureCurveGeometryDescriptor::setRadiusFormat(MTL::AttributeFormat radiusFormat) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRadiusFormat_), radiusFormat); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureCurveGeometryDescriptor::radiusStride() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(radiusStride)); } _MTL_INLINE void MTL::AccelerationStructureCurveGeometryDescriptor::setRadiusStride(NS::UInteger radiusStride) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRadiusStride_), radiusStride); } _MTL_INLINE MTL::Buffer* MTL::AccelerationStructureCurveGeometryDescriptor::indexBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(indexBuffer)); } _MTL_INLINE void MTL::AccelerationStructureCurveGeometryDescriptor::setIndexBuffer(const MTL::Buffer* indexBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexBuffer_), indexBuffer); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureCurveGeometryDescriptor::indexBufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(indexBufferOffset)); } _MTL_INLINE void MTL::AccelerationStructureCurveGeometryDescriptor::setIndexBufferOffset(NS::UInteger indexBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexBufferOffset_), indexBufferOffset); } _MTL_INLINE MTL::IndexType MTL::AccelerationStructureCurveGeometryDescriptor::indexType() const { return Object::sendMessage<MTL::IndexType>(this, _MTL_PRIVATE_SEL(indexType)); } _MTL_INLINE void MTL::AccelerationStructureCurveGeometryDescriptor::setIndexType(MTL::IndexType indexType) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexType_), indexType); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureCurveGeometryDescriptor::segmentCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(segmentCount)); } _MTL_INLINE void MTL::AccelerationStructureCurveGeometryDescriptor::setSegmentCount(NS::UInteger segmentCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSegmentCount_), segmentCount); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureCurveGeometryDescriptor::segmentControlPointCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(segmentControlPointCount)); } _MTL_INLINE void MTL::AccelerationStructureCurveGeometryDescriptor::setSegmentControlPointCount(NS::UInteger segmentControlPointCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSegmentControlPointCount_), segmentControlPointCount); } _MTL_INLINE MTL::CurveType MTL::AccelerationStructureCurveGeometryDescriptor::curveType() const { return Object::sendMessage<MTL::CurveType>(this, _MTL_PRIVATE_SEL(curveType)); } _MTL_INLINE void MTL::AccelerationStructureCurveGeometryDescriptor::setCurveType(MTL::CurveType curveType) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCurveType_), curveType); } _MTL_INLINE MTL::CurveBasis MTL::AccelerationStructureCurveGeometryDescriptor::curveBasis() const { return Object::sendMessage<MTL::CurveBasis>(this, _MTL_PRIVATE_SEL(curveBasis)); } _MTL_INLINE void MTL::AccelerationStructureCurveGeometryDescriptor::setCurveBasis(MTL::CurveBasis curveBasis) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCurveBasis_), curveBasis); } _MTL_INLINE MTL::CurveEndCaps MTL::AccelerationStructureCurveGeometryDescriptor::curveEndCaps() const { return Object::sendMessage<MTL::CurveEndCaps>(this, _MTL_PRIVATE_SEL(curveEndCaps)); } _MTL_INLINE void MTL::AccelerationStructureCurveGeometryDescriptor::setCurveEndCaps(MTL::CurveEndCaps curveEndCaps) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCurveEndCaps_), curveEndCaps); } _MTL_INLINE MTL::AccelerationStructureCurveGeometryDescriptor* MTL::AccelerationStructureCurveGeometryDescriptor::descriptor() { return Object::sendMessage<MTL::AccelerationStructureCurveGeometryDescriptor*>(_MTL_PRIVATE_CLS(MTLAccelerationStructureCurveGeometryDescriptor), _MTL_PRIVATE_SEL(descriptor)); } _MTL_INLINE MTL::AccelerationStructureMotionCurveGeometryDescriptor* MTL::AccelerationStructureMotionCurveGeometryDescriptor::alloc() { return NS::Object::alloc<MTL::AccelerationStructureMotionCurveGeometryDescriptor>(_MTL_PRIVATE_CLS(MTLAccelerationStructureMotionCurveGeometryDescriptor)); } _MTL_INLINE MTL::AccelerationStructureMotionCurveGeometryDescriptor* MTL::AccelerationStructureMotionCurveGeometryDescriptor::init() { return NS::Object::init<MTL::AccelerationStructureMotionCurveGeometryDescriptor>(); } _MTL_INLINE NS::Array* MTL::AccelerationStructureMotionCurveGeometryDescriptor::controlPointBuffers() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(controlPointBuffers)); } _MTL_INLINE void MTL::AccelerationStructureMotionCurveGeometryDescriptor::setControlPointBuffers(const NS::Array* controlPointBuffers) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setControlPointBuffers_), controlPointBuffers); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureMotionCurveGeometryDescriptor::controlPointCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(controlPointCount)); } _MTL_INLINE void MTL::AccelerationStructureMotionCurveGeometryDescriptor::setControlPointCount(NS::UInteger controlPointCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setControlPointCount_), controlPointCount); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureMotionCurveGeometryDescriptor::controlPointStride() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(controlPointStride)); } _MTL_INLINE void MTL::AccelerationStructureMotionCurveGeometryDescriptor::setControlPointStride(NS::UInteger controlPointStride) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setControlPointStride_), controlPointStride); } _MTL_INLINE MTL::AttributeFormat MTL::AccelerationStructureMotionCurveGeometryDescriptor::controlPointFormat() const { return Object::sendMessage<MTL::AttributeFormat>(this, _MTL_PRIVATE_SEL(controlPointFormat)); } _MTL_INLINE void MTL::AccelerationStructureMotionCurveGeometryDescriptor::setControlPointFormat(MTL::AttributeFormat controlPointFormat) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setControlPointFormat_), controlPointFormat); } _MTL_INLINE NS::Array* MTL::AccelerationStructureMotionCurveGeometryDescriptor::radiusBuffers() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(radiusBuffers)); } _MTL_INLINE void MTL::AccelerationStructureMotionCurveGeometryDescriptor::setRadiusBuffers(const NS::Array* radiusBuffers) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRadiusBuffers_), radiusBuffers); } _MTL_INLINE MTL::AttributeFormat MTL::AccelerationStructureMotionCurveGeometryDescriptor::radiusFormat() const { return Object::sendMessage<MTL::AttributeFormat>(this, _MTL_PRIVATE_SEL(radiusFormat)); } _MTL_INLINE void MTL::AccelerationStructureMotionCurveGeometryDescriptor::setRadiusFormat(MTL::AttributeFormat radiusFormat) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRadiusFormat_), radiusFormat); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureMotionCurveGeometryDescriptor::radiusStride() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(radiusStride)); } _MTL_INLINE void MTL::AccelerationStructureMotionCurveGeometryDescriptor::setRadiusStride(NS::UInteger radiusStride) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRadiusStride_), radiusStride); } _MTL_INLINE MTL::Buffer* MTL::AccelerationStructureMotionCurveGeometryDescriptor::indexBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(indexBuffer)); } _MTL_INLINE void MTL::AccelerationStructureMotionCurveGeometryDescriptor::setIndexBuffer(const MTL::Buffer* indexBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexBuffer_), indexBuffer); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureMotionCurveGeometryDescriptor::indexBufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(indexBufferOffset)); } _MTL_INLINE void MTL::AccelerationStructureMotionCurveGeometryDescriptor::setIndexBufferOffset(NS::UInteger indexBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexBufferOffset_), indexBufferOffset); } _MTL_INLINE MTL::IndexType MTL::AccelerationStructureMotionCurveGeometryDescriptor::indexType() const { return Object::sendMessage<MTL::IndexType>(this, _MTL_PRIVATE_SEL(indexType)); } _MTL_INLINE void MTL::AccelerationStructureMotionCurveGeometryDescriptor::setIndexType(MTL::IndexType indexType) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndexType_), indexType); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureMotionCurveGeometryDescriptor::segmentCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(segmentCount)); } _MTL_INLINE void MTL::AccelerationStructureMotionCurveGeometryDescriptor::setSegmentCount(NS::UInteger segmentCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSegmentCount_), segmentCount); } _MTL_INLINE NS::UInteger MTL::AccelerationStructureMotionCurveGeometryDescriptor::segmentControlPointCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(segmentControlPointCount)); } _MTL_INLINE void MTL::AccelerationStructureMotionCurveGeometryDescriptor::setSegmentControlPointCount(NS::UInteger segmentControlPointCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSegmentControlPointCount_), segmentControlPointCount); } _MTL_INLINE MTL::CurveType MTL::AccelerationStructureMotionCurveGeometryDescriptor::curveType() const { return Object::sendMessage<MTL::CurveType>(this, _MTL_PRIVATE_SEL(curveType)); } _MTL_INLINE void MTL::AccelerationStructureMotionCurveGeometryDescriptor::setCurveType(MTL::CurveType curveType) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCurveType_), curveType); } _MTL_INLINE MTL::CurveBasis MTL::AccelerationStructureMotionCurveGeometryDescriptor::curveBasis() const { return Object::sendMessage<MTL::CurveBasis>(this, _MTL_PRIVATE_SEL(curveBasis)); } _MTL_INLINE void MTL::AccelerationStructureMotionCurveGeometryDescriptor::setCurveBasis(MTL::CurveBasis curveBasis) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCurveBasis_), curveBasis); } _MTL_INLINE MTL::CurveEndCaps MTL::AccelerationStructureMotionCurveGeometryDescriptor::curveEndCaps() const { return Object::sendMessage<MTL::CurveEndCaps>(this, _MTL_PRIVATE_SEL(curveEndCaps)); } _MTL_INLINE void MTL::AccelerationStructureMotionCurveGeometryDescriptor::setCurveEndCaps(MTL::CurveEndCaps curveEndCaps) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCurveEndCaps_), curveEndCaps); } _MTL_INLINE MTL::AccelerationStructureMotionCurveGeometryDescriptor* MTL::AccelerationStructureMotionCurveGeometryDescriptor::descriptor() { return Object::sendMessage<MTL::AccelerationStructureMotionCurveGeometryDescriptor*>(_MTL_PRIVATE_CLS(MTLAccelerationStructureMotionCurveGeometryDescriptor), _MTL_PRIVATE_SEL(descriptor)); } _MTL_INLINE MTL::InstanceAccelerationStructureDescriptor* MTL::InstanceAccelerationStructureDescriptor::alloc() { return NS::Object::alloc<MTL::InstanceAccelerationStructureDescriptor>(_MTL_PRIVATE_CLS(MTLInstanceAccelerationStructureDescriptor)); } _MTL_INLINE MTL::InstanceAccelerationStructureDescriptor* MTL::InstanceAccelerationStructureDescriptor::init() { return NS::Object::init<MTL::InstanceAccelerationStructureDescriptor>(); } _MTL_INLINE MTL::Buffer* MTL::InstanceAccelerationStructureDescriptor::instanceDescriptorBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(instanceDescriptorBuffer)); } _MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setInstanceDescriptorBuffer(const MTL::Buffer* instanceDescriptorBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstanceDescriptorBuffer_), instanceDescriptorBuffer); } _MTL_INLINE NS::UInteger MTL::InstanceAccelerationStructureDescriptor::instanceDescriptorBufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(instanceDescriptorBufferOffset)); } _MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setInstanceDescriptorBufferOffset(NS::UInteger instanceDescriptorBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstanceDescriptorBufferOffset_), instanceDescriptorBufferOffset); } _MTL_INLINE NS::UInteger MTL::InstanceAccelerationStructureDescriptor::instanceDescriptorStride() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(instanceDescriptorStride)); } _MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setInstanceDescriptorStride(NS::UInteger instanceDescriptorStride) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstanceDescriptorStride_), instanceDescriptorStride); } _MTL_INLINE NS::UInteger MTL::InstanceAccelerationStructureDescriptor::instanceCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(instanceCount)); } _MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setInstanceCount(NS::UInteger instanceCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstanceCount_), instanceCount); } _MTL_INLINE NS::Array* MTL::InstanceAccelerationStructureDescriptor::instancedAccelerationStructures() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(instancedAccelerationStructures)); } _MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setInstancedAccelerationStructures(const NS::Array* instancedAccelerationStructures) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstancedAccelerationStructures_), instancedAccelerationStructures); } _MTL_INLINE MTL::AccelerationStructureInstanceDescriptorType MTL::InstanceAccelerationStructureDescriptor::instanceDescriptorType() const { return Object::sendMessage<MTL::AccelerationStructureInstanceDescriptorType>(this, _MTL_PRIVATE_SEL(instanceDescriptorType)); } _MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setInstanceDescriptorType(MTL::AccelerationStructureInstanceDescriptorType instanceDescriptorType) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstanceDescriptorType_), instanceDescriptorType); } _MTL_INLINE MTL::Buffer* MTL::InstanceAccelerationStructureDescriptor::motionTransformBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(motionTransformBuffer)); } _MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setMotionTransformBuffer(const MTL::Buffer* motionTransformBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionTransformBuffer_), motionTransformBuffer); } _MTL_INLINE NS::UInteger MTL::InstanceAccelerationStructureDescriptor::motionTransformBufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(motionTransformBufferOffset)); } _MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setMotionTransformBufferOffset(NS::UInteger motionTransformBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionTransformBufferOffset_), motionTransformBufferOffset); } _MTL_INLINE NS::UInteger MTL::InstanceAccelerationStructureDescriptor::motionTransformCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(motionTransformCount)); } _MTL_INLINE void MTL::InstanceAccelerationStructureDescriptor::setMotionTransformCount(NS::UInteger motionTransformCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionTransformCount_), motionTransformCount); } _MTL_INLINE MTL::InstanceAccelerationStructureDescriptor* MTL::InstanceAccelerationStructureDescriptor::descriptor() { return Object::sendMessage<MTL::InstanceAccelerationStructureDescriptor*>(_MTL_PRIVATE_CLS(MTLInstanceAccelerationStructureDescriptor), _MTL_PRIVATE_SEL(descriptor)); } _MTL_INLINE MTL::IndirectInstanceAccelerationStructureDescriptor* MTL::IndirectInstanceAccelerationStructureDescriptor::alloc() { return NS::Object::alloc<MTL::IndirectInstanceAccelerationStructureDescriptor>(_MTL_PRIVATE_CLS(MTLIndirectInstanceAccelerationStructureDescriptor)); } _MTL_INLINE MTL::IndirectInstanceAccelerationStructureDescriptor* MTL::IndirectInstanceAccelerationStructureDescriptor::init() { return NS::Object::init<MTL::IndirectInstanceAccelerationStructureDescriptor>(); } _MTL_INLINE MTL::Buffer* MTL::IndirectInstanceAccelerationStructureDescriptor::instanceDescriptorBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(instanceDescriptorBuffer)); } _MTL_INLINE void MTL::IndirectInstanceAccelerationStructureDescriptor::setInstanceDescriptorBuffer(const MTL::Buffer* instanceDescriptorBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstanceDescriptorBuffer_), instanceDescriptorBuffer); } _MTL_INLINE NS::UInteger MTL::IndirectInstanceAccelerationStructureDescriptor::instanceDescriptorBufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(instanceDescriptorBufferOffset)); } _MTL_INLINE void MTL::IndirectInstanceAccelerationStructureDescriptor::setInstanceDescriptorBufferOffset(NS::UInteger instanceDescriptorBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstanceDescriptorBufferOffset_), instanceDescriptorBufferOffset); } _MTL_INLINE NS::UInteger MTL::IndirectInstanceAccelerationStructureDescriptor::instanceDescriptorStride() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(instanceDescriptorStride)); } _MTL_INLINE void MTL::IndirectInstanceAccelerationStructureDescriptor::setInstanceDescriptorStride(NS::UInteger instanceDescriptorStride) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstanceDescriptorStride_), instanceDescriptorStride); } _MTL_INLINE NS::UInteger MTL::IndirectInstanceAccelerationStructureDescriptor::maxInstanceCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxInstanceCount)); } _MTL_INLINE void MTL::IndirectInstanceAccelerationStructureDescriptor::setMaxInstanceCount(NS::UInteger maxInstanceCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxInstanceCount_), maxInstanceCount); } _MTL_INLINE MTL::Buffer* MTL::IndirectInstanceAccelerationStructureDescriptor::instanceCountBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(instanceCountBuffer)); } _MTL_INLINE void MTL::IndirectInstanceAccelerationStructureDescriptor::setInstanceCountBuffer(const MTL::Buffer* instanceCountBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstanceCountBuffer_), instanceCountBuffer); } _MTL_INLINE NS::UInteger MTL::IndirectInstanceAccelerationStructureDescriptor::instanceCountBufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(instanceCountBufferOffset)); } _MTL_INLINE void MTL::IndirectInstanceAccelerationStructureDescriptor::setInstanceCountBufferOffset(NS::UInteger instanceCountBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstanceCountBufferOffset_), instanceCountBufferOffset); } _MTL_INLINE MTL::AccelerationStructureInstanceDescriptorType MTL::IndirectInstanceAccelerationStructureDescriptor::instanceDescriptorType() const { return Object::sendMessage<MTL::AccelerationStructureInstanceDescriptorType>(this, _MTL_PRIVATE_SEL(instanceDescriptorType)); } _MTL_INLINE void MTL::IndirectInstanceAccelerationStructureDescriptor::setInstanceDescriptorType(MTL::AccelerationStructureInstanceDescriptorType instanceDescriptorType) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstanceDescriptorType_), instanceDescriptorType); } _MTL_INLINE MTL::Buffer* MTL::IndirectInstanceAccelerationStructureDescriptor::motionTransformBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(motionTransformBuffer)); } _MTL_INLINE void MTL::IndirectInstanceAccelerationStructureDescriptor::setMotionTransformBuffer(const MTL::Buffer* motionTransformBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionTransformBuffer_), motionTransformBuffer); } _MTL_INLINE NS::UInteger MTL::IndirectInstanceAccelerationStructureDescriptor::motionTransformBufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(motionTransformBufferOffset)); } _MTL_INLINE void MTL::IndirectInstanceAccelerationStructureDescriptor::setMotionTransformBufferOffset(NS::UInteger motionTransformBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionTransformBufferOffset_), motionTransformBufferOffset); } _MTL_INLINE NS::UInteger MTL::IndirectInstanceAccelerationStructureDescriptor::maxMotionTransformCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxMotionTransformCount)); } _MTL_INLINE void MTL::IndirectInstanceAccelerationStructureDescriptor::setMaxMotionTransformCount(NS::UInteger maxMotionTransformCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxMotionTransformCount_), maxMotionTransformCount); } _MTL_INLINE MTL::Buffer* MTL::IndirectInstanceAccelerationStructureDescriptor::motionTransformCountBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(motionTransformCountBuffer)); } _MTL_INLINE void MTL::IndirectInstanceAccelerationStructureDescriptor::setMotionTransformCountBuffer(const MTL::Buffer* motionTransformCountBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionTransformCountBuffer_), motionTransformCountBuffer); } _MTL_INLINE NS::UInteger MTL::IndirectInstanceAccelerationStructureDescriptor::motionTransformCountBufferOffset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(motionTransformCountBufferOffset)); } _MTL_INLINE void MTL::IndirectInstanceAccelerationStructureDescriptor::setMotionTransformCountBufferOffset(NS::UInteger motionTransformCountBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMotionTransformCountBufferOffset_), motionTransformCountBufferOffset); } _MTL_INLINE MTL::IndirectInstanceAccelerationStructureDescriptor* MTL::IndirectInstanceAccelerationStructureDescriptor::descriptor() { return Object::sendMessage<MTL::IndirectInstanceAccelerationStructureDescriptor*>(_MTL_PRIVATE_CLS(MTLIndirectInstanceAccelerationStructureDescriptor), _MTL_PRIVATE_SEL(descriptor)); } _MTL_INLINE NS::UInteger MTL::AccelerationStructure::size() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(size)); } _MTL_INLINE MTL::ResourceID MTL::AccelerationStructure::gpuResourceID() const { return Object::sendMessage<MTL::ResourceID>(this, _MTL_PRIVATE_SEL(gpuResourceID)); } #pragma once #pragma once namespace MTL { _MTL_ENUM(NS::UInteger, DataType) { DataTypeNone = 0, DataTypeStruct = 1, DataTypeArray = 2, DataTypeFloat = 3, DataTypeFloat2 = 4, DataTypeFloat3 = 5, DataTypeFloat4 = 6, DataTypeFloat2x2 = 7, DataTypeFloat2x3 = 8, DataTypeFloat2x4 = 9, DataTypeFloat3x2 = 10, DataTypeFloat3x3 = 11, DataTypeFloat3x4 = 12, DataTypeFloat4x2 = 13, DataTypeFloat4x3 = 14, DataTypeFloat4x4 = 15, DataTypeHalf = 16, DataTypeHalf2 = 17, DataTypeHalf3 = 18, DataTypeHalf4 = 19, DataTypeHalf2x2 = 20, DataTypeHalf2x3 = 21, DataTypeHalf2x4 = 22, DataTypeHalf3x2 = 23, DataTypeHalf3x3 = 24, DataTypeHalf3x4 = 25, DataTypeHalf4x2 = 26, DataTypeHalf4x3 = 27, DataTypeHalf4x4 = 28, DataTypeInt = 29, DataTypeInt2 = 30, DataTypeInt3 = 31, DataTypeInt4 = 32, DataTypeUInt = 33, DataTypeUInt2 = 34, DataTypeUInt3 = 35, DataTypeUInt4 = 36, DataTypeShort = 37, DataTypeShort2 = 38, DataTypeShort3 = 39, DataTypeShort4 = 40, DataTypeUShort = 41, DataTypeUShort2 = 42, DataTypeUShort3 = 43, DataTypeUShort4 = 44, DataTypeChar = 45, DataTypeChar2 = 46, DataTypeChar3 = 47, DataTypeChar4 = 48, DataTypeUChar = 49, DataTypeUChar2 = 50, DataTypeUChar3 = 51, DataTypeUChar4 = 52, DataTypeBool = 53, DataTypeBool2 = 54, DataTypeBool3 = 55, DataTypeBool4 = 56, DataTypeTexture = 58, DataTypeSampler = 59, DataTypePointer = 60, DataTypeR8Unorm = 62, DataTypeR8Snorm = 63, DataTypeR16Unorm = 64, DataTypeR16Snorm = 65, DataTypeRG8Unorm = 66, DataTypeRG8Snorm = 67, DataTypeRG16Unorm = 68, DataTypeRG16Snorm = 69, DataTypeRGBA8Unorm = 70, DataTypeRGBA8Unorm_sRGB = 71, DataTypeRGBA8Snorm = 72, DataTypeRGBA16Unorm = 73, DataTypeRGBA16Snorm = 74, DataTypeRGB10A2Unorm = 75, DataTypeRG11B10Float = 76, DataTypeRGB9E5Float = 77, DataTypeRenderPipeline = 78, DataTypeComputePipeline = 79, DataTypeIndirectCommandBuffer = 80, DataTypeLong = 81, DataTypeLong2 = 82, DataTypeLong3 = 83, DataTypeLong4 = 84, DataTypeULong = 85, DataTypeULong2 = 86, DataTypeULong3 = 87, DataTypeULong4 = 88, DataTypeVisibleFunctionTable = 115, DataTypeIntersectionFunctionTable = 116, DataTypePrimitiveAccelerationStructure = 117, DataTypeInstanceAccelerationStructure = 118, DataTypeBFloat = 121, DataTypeBFloat2 = 122, DataTypeBFloat3 = 123, DataTypeBFloat4 = 124, }; _MTL_ENUM(NS::Integer, BindingType) { BindingTypeBuffer = 0, BindingTypeThreadgroupMemory = 1, BindingTypeTexture = 2, BindingTypeSampler = 3, BindingTypeImageblockData = 16, BindingTypeImageblock = 17, BindingTypeVisibleFunctionTable = 24, BindingTypePrimitiveAccelerationStructure = 25, BindingTypeInstanceAccelerationStructure = 26, BindingTypeIntersectionFunctionTable = 27, BindingTypeObjectPayload = 34, }; _MTL_ENUM(NS::UInteger, ArgumentType) { ArgumentTypeBuffer = 0, ArgumentTypeThreadgroupMemory = 1, ArgumentTypeTexture = 2, ArgumentTypeSampler = 3, ArgumentTypeImageblockData = 16, ArgumentTypeImageblock = 17, ArgumentTypeVisibleFunctionTable = 24, ArgumentTypePrimitiveAccelerationStructure = 25, ArgumentTypeInstanceAccelerationStructure = 26, ArgumentTypeIntersectionFunctionTable = 27, }; _MTL_ENUM(NS::UInteger, BindingAccess) { BindingAccessReadOnly = 0, BindingAccessReadWrite = 1, BindingAccessWriteOnly = 2, ArgumentAccessReadOnly = 0, ArgumentAccessReadWrite = 1, ArgumentAccessWriteOnly = 2, }; class Type : public NS::Referencing<Type> { public: static class Type* alloc(); class Type* init(); MTL::DataType dataType() const; }; class StructMember : public NS::Referencing<StructMember> { public: static class StructMember* alloc(); class StructMember* init(); NS::String* name() const; NS::UInteger offset() const; MTL::DataType dataType() const; class StructType* structType(); class ArrayType* arrayType(); class TextureReferenceType* textureReferenceType(); class PointerType* pointerType(); NS::UInteger argumentIndex() const; }; class StructType : public NS::Referencing<StructType, Type> { public: static class StructType* alloc(); class StructType* init(); NS::Array* members() const; class StructMember* memberByName(const NS::String* name); }; class ArrayType : public NS::Referencing<ArrayType, Type> { public: static class ArrayType* alloc(); class ArrayType* init(); MTL::DataType elementType() const; NS::UInteger arrayLength() const; NS::UInteger stride() const; NS::UInteger argumentIndexStride() const; class StructType* elementStructType(); class ArrayType* elementArrayType(); class TextureReferenceType* elementTextureReferenceType(); class PointerType* elementPointerType(); }; class PointerType : public NS::Referencing<PointerType, Type> { public: static class PointerType* alloc(); class PointerType* init(); MTL::DataType elementType() const; MTL::BindingAccess access() const; NS::UInteger alignment() const; NS::UInteger dataSize() const; bool elementIsArgumentBuffer() const; class StructType* elementStructType(); class ArrayType* elementArrayType(); }; class TextureReferenceType : public NS::Referencing<TextureReferenceType, Type> { public: static class TextureReferenceType* alloc(); class TextureReferenceType* init(); MTL::DataType textureDataType() const; MTL::TextureType textureType() const; MTL::BindingAccess access() const; bool isDepthTexture() const; }; class Argument : public NS::Referencing<Argument> { public: static class Argument* alloc(); class Argument* init(); NS::String* name() const; MTL::ArgumentType type() const; MTL::BindingAccess access() const; NS::UInteger index() const; bool active() const; NS::UInteger bufferAlignment() const; NS::UInteger bufferDataSize() const; MTL::DataType bufferDataType() const; class StructType* bufferStructType() const; class PointerType* bufferPointerType() const; NS::UInteger threadgroupMemoryAlignment() const; NS::UInteger threadgroupMemoryDataSize() const; MTL::TextureType textureType() const; MTL::DataType textureDataType() const; bool isDepthTexture() const; NS::UInteger arrayLength() const; }; class Binding : public NS::Referencing<Binding> { public: NS::String* name() const; MTL::BindingType type() const; MTL::BindingAccess access() const; NS::UInteger index() const; bool used() const; bool argument() const; }; class BufferBinding : public NS::Referencing<BufferBinding, Binding> { public: NS::UInteger bufferAlignment() const; NS::UInteger bufferDataSize() const; MTL::DataType bufferDataType() const; class StructType* bufferStructType() const; class PointerType* bufferPointerType() const; }; class ThreadgroupBinding : public NS::Referencing<ThreadgroupBinding, Binding> { public: NS::UInteger threadgroupMemoryAlignment() const; NS::UInteger threadgroupMemoryDataSize() const; }; class TextureBinding : public NS::Referencing<TextureBinding, Binding> { public: MTL::TextureType textureType() const; MTL::DataType textureDataType() const; bool depthTexture() const; NS::UInteger arrayLength() const; }; class ObjectPayloadBinding : public NS::Referencing<ObjectPayloadBinding, Binding> { public: NS::UInteger objectPayloadAlignment() const; NS::UInteger objectPayloadDataSize() const; }; } _MTL_INLINE MTL::Type* MTL::Type::alloc() { return NS::Object::alloc<MTL::Type>(_MTL_PRIVATE_CLS(MTLType)); } _MTL_INLINE MTL::Type* MTL::Type::init() { return NS::Object::init<MTL::Type>(); } _MTL_INLINE MTL::DataType MTL::Type::dataType() const { return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(dataType)); } _MTL_INLINE MTL::StructMember* MTL::StructMember::alloc() { return NS::Object::alloc<MTL::StructMember>(_MTL_PRIVATE_CLS(MTLStructMember)); } _MTL_INLINE MTL::StructMember* MTL::StructMember::init() { return NS::Object::init<MTL::StructMember>(); } _MTL_INLINE NS::String* MTL::StructMember::name() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name)); } _MTL_INLINE NS::UInteger MTL::StructMember::offset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(offset)); } _MTL_INLINE MTL::DataType MTL::StructMember::dataType() const { return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(dataType)); } _MTL_INLINE MTL::StructType* MTL::StructMember::structType() { return Object::sendMessage<MTL::StructType*>(this, _MTL_PRIVATE_SEL(structType)); } _MTL_INLINE MTL::ArrayType* MTL::StructMember::arrayType() { return Object::sendMessage<MTL::ArrayType*>(this, _MTL_PRIVATE_SEL(arrayType)); } _MTL_INLINE MTL::TextureReferenceType* MTL::StructMember::textureReferenceType() { return Object::sendMessage<MTL::TextureReferenceType*>(this, _MTL_PRIVATE_SEL(textureReferenceType)); } _MTL_INLINE MTL::PointerType* MTL::StructMember::pointerType() { return Object::sendMessage<MTL::PointerType*>(this, _MTL_PRIVATE_SEL(pointerType)); } _MTL_INLINE NS::UInteger MTL::StructMember::argumentIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(argumentIndex)); } _MTL_INLINE MTL::StructType* MTL::StructType::alloc() { return NS::Object::alloc<MTL::StructType>(_MTL_PRIVATE_CLS(MTLStructType)); } _MTL_INLINE MTL::StructType* MTL::StructType::init() { return NS::Object::init<MTL::StructType>(); } _MTL_INLINE NS::Array* MTL::StructType::members() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(members)); } _MTL_INLINE MTL::StructMember* MTL::StructType::memberByName(const NS::String* name) { return Object::sendMessage<MTL::StructMember*>(this, _MTL_PRIVATE_SEL(memberByName_), name); } _MTL_INLINE MTL::ArrayType* MTL::ArrayType::alloc() { return NS::Object::alloc<MTL::ArrayType>(_MTL_PRIVATE_CLS(MTLArrayType)); } _MTL_INLINE MTL::ArrayType* MTL::ArrayType::init() { return NS::Object::init<MTL::ArrayType>(); } _MTL_INLINE MTL::DataType MTL::ArrayType::elementType() const { return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(elementType)); } _MTL_INLINE NS::UInteger MTL::ArrayType::arrayLength() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(arrayLength)); } _MTL_INLINE NS::UInteger MTL::ArrayType::stride() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(stride)); } _MTL_INLINE NS::UInteger MTL::ArrayType::argumentIndexStride() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(argumentIndexStride)); } _MTL_INLINE MTL::StructType* MTL::ArrayType::elementStructType() { return Object::sendMessage<MTL::StructType*>(this, _MTL_PRIVATE_SEL(elementStructType)); } _MTL_INLINE MTL::ArrayType* MTL::ArrayType::elementArrayType() { return Object::sendMessage<MTL::ArrayType*>(this, _MTL_PRIVATE_SEL(elementArrayType)); } _MTL_INLINE MTL::TextureReferenceType* MTL::ArrayType::elementTextureReferenceType() { return Object::sendMessage<MTL::TextureReferenceType*>(this, _MTL_PRIVATE_SEL(elementTextureReferenceType)); } _MTL_INLINE MTL::PointerType* MTL::ArrayType::elementPointerType() { return Object::sendMessage<MTL::PointerType*>(this, _MTL_PRIVATE_SEL(elementPointerType)); } _MTL_INLINE MTL::PointerType* MTL::PointerType::alloc() { return NS::Object::alloc<MTL::PointerType>(_MTL_PRIVATE_CLS(MTLPointerType)); } _MTL_INLINE MTL::PointerType* MTL::PointerType::init() { return NS::Object::init<MTL::PointerType>(); } _MTL_INLINE MTL::DataType MTL::PointerType::elementType() const { return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(elementType)); } _MTL_INLINE MTL::BindingAccess MTL::PointerType::access() const { return Object::sendMessage<MTL::BindingAccess>(this, _MTL_PRIVATE_SEL(access)); } _MTL_INLINE NS::UInteger MTL::PointerType::alignment() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(alignment)); } _MTL_INLINE NS::UInteger MTL::PointerType::dataSize() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(dataSize)); } _MTL_INLINE bool MTL::PointerType::elementIsArgumentBuffer() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(elementIsArgumentBuffer)); } _MTL_INLINE MTL::StructType* MTL::PointerType::elementStructType() { return Object::sendMessage<MTL::StructType*>(this, _MTL_PRIVATE_SEL(elementStructType)); } _MTL_INLINE MTL::ArrayType* MTL::PointerType::elementArrayType() { return Object::sendMessage<MTL::ArrayType*>(this, _MTL_PRIVATE_SEL(elementArrayType)); } _MTL_INLINE MTL::TextureReferenceType* MTL::TextureReferenceType::alloc() { return NS::Object::alloc<MTL::TextureReferenceType>(_MTL_PRIVATE_CLS(MTLTextureReferenceType)); } _MTL_INLINE MTL::TextureReferenceType* MTL::TextureReferenceType::init() { return NS::Object::init<MTL::TextureReferenceType>(); } _MTL_INLINE MTL::DataType MTL::TextureReferenceType::textureDataType() const { return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(textureDataType)); } _MTL_INLINE MTL::TextureType MTL::TextureReferenceType::textureType() const { return Object::sendMessage<MTL::TextureType>(this, _MTL_PRIVATE_SEL(textureType)); } _MTL_INLINE MTL::BindingAccess MTL::TextureReferenceType::access() const { return Object::sendMessage<MTL::BindingAccess>(this, _MTL_PRIVATE_SEL(access)); } _MTL_INLINE bool MTL::TextureReferenceType::isDepthTexture() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isDepthTexture)); } _MTL_INLINE MTL::Argument* MTL::Argument::alloc() { return NS::Object::alloc<MTL::Argument>(_MTL_PRIVATE_CLS(MTLArgument)); } _MTL_INLINE MTL::Argument* MTL::Argument::init() { return NS::Object::init<MTL::Argument>(); } _MTL_INLINE NS::String* MTL::Argument::name() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name)); } _MTL_INLINE MTL::ArgumentType MTL::Argument::type() const { return Object::sendMessage<MTL::ArgumentType>(this, _MTL_PRIVATE_SEL(type)); } _MTL_INLINE MTL::BindingAccess MTL::Argument::access() const { return Object::sendMessage<MTL::BindingAccess>(this, _MTL_PRIVATE_SEL(access)); } _MTL_INLINE NS::UInteger MTL::Argument::index() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(index)); } _MTL_INLINE bool MTL::Argument::active() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isActive)); } _MTL_INLINE NS::UInteger MTL::Argument::bufferAlignment() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(bufferAlignment)); } _MTL_INLINE NS::UInteger MTL::Argument::bufferDataSize() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(bufferDataSize)); } _MTL_INLINE MTL::DataType MTL::Argument::bufferDataType() const { return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(bufferDataType)); } _MTL_INLINE MTL::StructType* MTL::Argument::bufferStructType() const { return Object::sendMessage<MTL::StructType*>(this, _MTL_PRIVATE_SEL(bufferStructType)); } _MTL_INLINE MTL::PointerType* MTL::Argument::bufferPointerType() const { return Object::sendMessage<MTL::PointerType*>(this, _MTL_PRIVATE_SEL(bufferPointerType)); } _MTL_INLINE NS::UInteger MTL::Argument::threadgroupMemoryAlignment() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(threadgroupMemoryAlignment)); } _MTL_INLINE NS::UInteger MTL::Argument::threadgroupMemoryDataSize() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(threadgroupMemoryDataSize)); } _MTL_INLINE MTL::TextureType MTL::Argument::textureType() const { return Object::sendMessage<MTL::TextureType>(this, _MTL_PRIVATE_SEL(textureType)); } _MTL_INLINE MTL::DataType MTL::Argument::textureDataType() const { return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(textureDataType)); } _MTL_INLINE bool MTL::Argument::isDepthTexture() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isDepthTexture)); } _MTL_INLINE NS::UInteger MTL::Argument::arrayLength() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(arrayLength)); } _MTL_INLINE NS::String* MTL::Binding::name() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name)); } _MTL_INLINE MTL::BindingType MTL::Binding::type() const { return Object::sendMessage<MTL::BindingType>(this, _MTL_PRIVATE_SEL(type)); } _MTL_INLINE MTL::BindingAccess MTL::Binding::access() const { return Object::sendMessage<MTL::BindingAccess>(this, _MTL_PRIVATE_SEL(access)); } _MTL_INLINE NS::UInteger MTL::Binding::index() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(index)); } _MTL_INLINE bool MTL::Binding::used() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isUsed)); } _MTL_INLINE bool MTL::Binding::argument() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isArgument)); } _MTL_INLINE NS::UInteger MTL::BufferBinding::bufferAlignment() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(bufferAlignment)); } _MTL_INLINE NS::UInteger MTL::BufferBinding::bufferDataSize() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(bufferDataSize)); } _MTL_INLINE MTL::DataType MTL::BufferBinding::bufferDataType() const { return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(bufferDataType)); } _MTL_INLINE MTL::StructType* MTL::BufferBinding::bufferStructType() const { return Object::sendMessage<MTL::StructType*>(this, _MTL_PRIVATE_SEL(bufferStructType)); } _MTL_INLINE MTL::PointerType* MTL::BufferBinding::bufferPointerType() const { return Object::sendMessage<MTL::PointerType*>(this, _MTL_PRIVATE_SEL(bufferPointerType)); } _MTL_INLINE NS::UInteger MTL::ThreadgroupBinding::threadgroupMemoryAlignment() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(threadgroupMemoryAlignment)); } _MTL_INLINE NS::UInteger MTL::ThreadgroupBinding::threadgroupMemoryDataSize() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(threadgroupMemoryDataSize)); } _MTL_INLINE MTL::TextureType MTL::TextureBinding::textureType() const { return Object::sendMessage<MTL::TextureType>(this, _MTL_PRIVATE_SEL(textureType)); } _MTL_INLINE MTL::DataType MTL::TextureBinding::textureDataType() const { return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(textureDataType)); } _MTL_INLINE bool MTL::TextureBinding::depthTexture() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isDepthTexture)); } _MTL_INLINE NS::UInteger MTL::TextureBinding::arrayLength() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(arrayLength)); } _MTL_INLINE NS::UInteger MTL::ObjectPayloadBinding::objectPayloadAlignment() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(objectPayloadAlignment)); } _MTL_INLINE NS::UInteger MTL::ObjectPayloadBinding::objectPayloadDataSize() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(objectPayloadDataSize)); } #pragma once namespace MTL { _MTL_OPTIONS(NS::UInteger, ResourceUsage) { ResourceUsageRead = 1, ResourceUsageWrite = 2, ResourceUsageSample = 4, }; _MTL_OPTIONS(NS::UInteger, BarrierScope) { BarrierScopeBuffers = 1, BarrierScopeTextures = 2, BarrierScopeRenderTargets = 4, }; class CommandEncoder : public NS::Referencing<CommandEncoder> { public: class Device* device() const; NS::String* label() const; void setLabel(const NS::String* label); void endEncoding(); void insertDebugSignpost(const NS::String* string); void pushDebugGroup(const NS::String* string); void popDebugGroup(); }; } _MTL_INLINE MTL::Device* MTL::CommandEncoder::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE NS::String* MTL::CommandEncoder::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::CommandEncoder::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE void MTL::CommandEncoder::endEncoding() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(endEncoding)); } _MTL_INLINE void MTL::CommandEncoder::insertDebugSignpost(const NS::String* string) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(insertDebugSignpost_), string); } _MTL_INLINE void MTL::CommandEncoder::pushDebugGroup(const NS::String* string) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(pushDebugGroup_), string); } _MTL_INLINE void MTL::CommandEncoder::popDebugGroup() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(popDebugGroup)); } namespace MTL { _MTL_OPTIONS(NS::UInteger, AccelerationStructureRefitOptions) { AccelerationStructureRefitOptionVertexData = 1, AccelerationStructureRefitOptionPerPrimitiveData = 2, }; class AccelerationStructureCommandEncoder : public NS::Referencing<AccelerationStructureCommandEncoder, CommandEncoder> { public: void buildAccelerationStructure(const class AccelerationStructure* accelerationStructure, const class AccelerationStructureDescriptor* descriptor, const class Buffer* scratchBuffer, NS::UInteger scratchBufferOffset); void refitAccelerationStructure(const class AccelerationStructure* sourceAccelerationStructure, const class AccelerationStructureDescriptor* descriptor, const class AccelerationStructure* destinationAccelerationStructure, const class Buffer* scratchBuffer, NS::UInteger scratchBufferOffset); void refitAccelerationStructure(const class AccelerationStructure* sourceAccelerationStructure, const class AccelerationStructureDescriptor* descriptor, const class AccelerationStructure* destinationAccelerationStructure, const class Buffer* scratchBuffer, NS::UInteger scratchBufferOffset, MTL::AccelerationStructureRefitOptions options); void copyAccelerationStructure(const class AccelerationStructure* sourceAccelerationStructure, const class AccelerationStructure* destinationAccelerationStructure); void writeCompactedAccelerationStructureSize(const class AccelerationStructure* accelerationStructure, const class Buffer* buffer, NS::UInteger offset); void writeCompactedAccelerationStructureSize(const class AccelerationStructure* accelerationStructure, const class Buffer* buffer, NS::UInteger offset, MTL::DataType sizeDataType); void copyAndCompactAccelerationStructure(const class AccelerationStructure* sourceAccelerationStructure, const class AccelerationStructure* destinationAccelerationStructure); void updateFence(const class Fence* fence); void waitForFence(const class Fence* fence); void useResource(const class Resource* resource, MTL::ResourceUsage usage); void useResources(const class Resource* const resources[], NS::UInteger count, MTL::ResourceUsage usage); void useHeap(const class Heap* heap); void useHeaps(const class Heap* const heaps[], NS::UInteger count); void sampleCountersInBuffer(const class CounterSampleBuffer* sampleBuffer, NS::UInteger sampleIndex, bool barrier); }; class AccelerationStructurePassSampleBufferAttachmentDescriptor : public NS::Copying<AccelerationStructurePassSampleBufferAttachmentDescriptor> { public: static class AccelerationStructurePassSampleBufferAttachmentDescriptor* alloc(); class AccelerationStructurePassSampleBufferAttachmentDescriptor* init(); class CounterSampleBuffer* sampleBuffer() const; void setSampleBuffer(const class CounterSampleBuffer* sampleBuffer); NS::UInteger startOfEncoderSampleIndex() const; void setStartOfEncoderSampleIndex(NS::UInteger startOfEncoderSampleIndex); NS::UInteger endOfEncoderSampleIndex() const; void setEndOfEncoderSampleIndex(NS::UInteger endOfEncoderSampleIndex); }; class AccelerationStructurePassSampleBufferAttachmentDescriptorArray : public NS::Referencing<AccelerationStructurePassSampleBufferAttachmentDescriptorArray> { public: static class AccelerationStructurePassSampleBufferAttachmentDescriptorArray* alloc(); class AccelerationStructurePassSampleBufferAttachmentDescriptorArray* init(); class AccelerationStructurePassSampleBufferAttachmentDescriptor* object(NS::UInteger attachmentIndex); void setObject(const class AccelerationStructurePassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex); }; class AccelerationStructurePassDescriptor : public NS::Copying<AccelerationStructurePassDescriptor> { public: static class AccelerationStructurePassDescriptor* alloc(); class AccelerationStructurePassDescriptor* init(); static class AccelerationStructurePassDescriptor* accelerationStructurePassDescriptor(); class AccelerationStructurePassSampleBufferAttachmentDescriptorArray* sampleBufferAttachments() const; }; } _MTL_INLINE void MTL::AccelerationStructureCommandEncoder::buildAccelerationStructure(const MTL::AccelerationStructure* accelerationStructure, const MTL::AccelerationStructureDescriptor* descriptor, const MTL::Buffer* scratchBuffer, NS::UInteger scratchBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(buildAccelerationStructure_descriptor_scratchBuffer_scratchBufferOffset_), accelerationStructure, descriptor, scratchBuffer, scratchBufferOffset); } _MTL_INLINE void MTL::AccelerationStructureCommandEncoder::refitAccelerationStructure(const MTL::AccelerationStructure* sourceAccelerationStructure, const MTL::AccelerationStructureDescriptor* descriptor, const MTL::AccelerationStructure* destinationAccelerationStructure, const MTL::Buffer* scratchBuffer, NS::UInteger scratchBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(refitAccelerationStructure_descriptor_destination_scratchBuffer_scratchBufferOffset_), sourceAccelerationStructure, descriptor, destinationAccelerationStructure, scratchBuffer, scratchBufferOffset); } _MTL_INLINE void MTL::AccelerationStructureCommandEncoder::refitAccelerationStructure(const MTL::AccelerationStructure* sourceAccelerationStructure, const MTL::AccelerationStructureDescriptor* descriptor, const MTL::AccelerationStructure* destinationAccelerationStructure, const MTL::Buffer* scratchBuffer, NS::UInteger scratchBufferOffset, MTL::AccelerationStructureRefitOptions options) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(refitAccelerationStructure_descriptor_destination_scratchBuffer_scratchBufferOffset_options_), sourceAccelerationStructure, descriptor, destinationAccelerationStructure, scratchBuffer, scratchBufferOffset, options); } _MTL_INLINE void MTL::AccelerationStructureCommandEncoder::copyAccelerationStructure(const MTL::AccelerationStructure* sourceAccelerationStructure, const MTL::AccelerationStructure* destinationAccelerationStructure) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyAccelerationStructure_toAccelerationStructure_), sourceAccelerationStructure, destinationAccelerationStructure); } _MTL_INLINE void MTL::AccelerationStructureCommandEncoder::writeCompactedAccelerationStructureSize(const MTL::AccelerationStructure* accelerationStructure, const MTL::Buffer* buffer, NS::UInteger offset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(writeCompactedAccelerationStructureSize_toBuffer_offset_), accelerationStructure, buffer, offset); } _MTL_INLINE void MTL::AccelerationStructureCommandEncoder::writeCompactedAccelerationStructureSize(const MTL::AccelerationStructure* accelerationStructure, const MTL::Buffer* buffer, NS::UInteger offset, MTL::DataType sizeDataType) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(writeCompactedAccelerationStructureSize_toBuffer_offset_sizeDataType_), accelerationStructure, buffer, offset, sizeDataType); } _MTL_INLINE void MTL::AccelerationStructureCommandEncoder::copyAndCompactAccelerationStructure(const MTL::AccelerationStructure* sourceAccelerationStructure, const MTL::AccelerationStructure* destinationAccelerationStructure) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyAndCompactAccelerationStructure_toAccelerationStructure_), sourceAccelerationStructure, destinationAccelerationStructure); } _MTL_INLINE void MTL::AccelerationStructureCommandEncoder::updateFence(const MTL::Fence* fence) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(updateFence_), fence); } _MTL_INLINE void MTL::AccelerationStructureCommandEncoder::waitForFence(const MTL::Fence* fence) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(waitForFence_), fence); } _MTL_INLINE void MTL::AccelerationStructureCommandEncoder::useResource(const MTL::Resource* resource, MTL::ResourceUsage usage) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useResource_usage_), resource, usage); } _MTL_INLINE void MTL::AccelerationStructureCommandEncoder::useResources(const MTL::Resource* const resources[], NS::UInteger count, MTL::ResourceUsage usage) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useResources_count_usage_), resources, count, usage); } _MTL_INLINE void MTL::AccelerationStructureCommandEncoder::useHeap(const MTL::Heap* heap) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useHeap_), heap); } _MTL_INLINE void MTL::AccelerationStructureCommandEncoder::useHeaps(const MTL::Heap* const heaps[], NS::UInteger count) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useHeaps_count_), heaps, count); } _MTL_INLINE void MTL::AccelerationStructureCommandEncoder::sampleCountersInBuffer(const MTL::CounterSampleBuffer* sampleBuffer, NS::UInteger sampleIndex, bool barrier) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(sampleCountersInBuffer_atSampleIndex_withBarrier_), sampleBuffer, sampleIndex, barrier); } _MTL_INLINE MTL::AccelerationStructurePassSampleBufferAttachmentDescriptor* MTL::AccelerationStructurePassSampleBufferAttachmentDescriptor::alloc() { return NS::Object::alloc<MTL::AccelerationStructurePassSampleBufferAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLAccelerationStructurePassSampleBufferAttachmentDescriptor)); } _MTL_INLINE MTL::AccelerationStructurePassSampleBufferAttachmentDescriptor* MTL::AccelerationStructurePassSampleBufferAttachmentDescriptor::init() { return NS::Object::init<MTL::AccelerationStructurePassSampleBufferAttachmentDescriptor>(); } _MTL_INLINE MTL::CounterSampleBuffer* MTL::AccelerationStructurePassSampleBufferAttachmentDescriptor::sampleBuffer() const { return Object::sendMessage<MTL::CounterSampleBuffer*>(this, _MTL_PRIVATE_SEL(sampleBuffer)); } _MTL_INLINE void MTL::AccelerationStructurePassSampleBufferAttachmentDescriptor::setSampleBuffer(const MTL::CounterSampleBuffer* sampleBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSampleBuffer_), sampleBuffer); } _MTL_INLINE NS::UInteger MTL::AccelerationStructurePassSampleBufferAttachmentDescriptor::startOfEncoderSampleIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(startOfEncoderSampleIndex)); } _MTL_INLINE void MTL::AccelerationStructurePassSampleBufferAttachmentDescriptor::setStartOfEncoderSampleIndex(NS::UInteger startOfEncoderSampleIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStartOfEncoderSampleIndex_), startOfEncoderSampleIndex); } _MTL_INLINE NS::UInteger MTL::AccelerationStructurePassSampleBufferAttachmentDescriptor::endOfEncoderSampleIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(endOfEncoderSampleIndex)); } _MTL_INLINE void MTL::AccelerationStructurePassSampleBufferAttachmentDescriptor::setEndOfEncoderSampleIndex(NS::UInteger endOfEncoderSampleIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setEndOfEncoderSampleIndex_), endOfEncoderSampleIndex); } _MTL_INLINE MTL::AccelerationStructurePassSampleBufferAttachmentDescriptorArray* MTL::AccelerationStructurePassSampleBufferAttachmentDescriptorArray::alloc() { return NS::Object::alloc<MTL::AccelerationStructurePassSampleBufferAttachmentDescriptorArray>(_MTL_PRIVATE_CLS(MTLAccelerationStructurePassSampleBufferAttachmentDescriptorArray)); } _MTL_INLINE MTL::AccelerationStructurePassSampleBufferAttachmentDescriptorArray* MTL::AccelerationStructurePassSampleBufferAttachmentDescriptorArray::init() { return NS::Object::init<MTL::AccelerationStructurePassSampleBufferAttachmentDescriptorArray>(); } _MTL_INLINE MTL::AccelerationStructurePassSampleBufferAttachmentDescriptor* MTL::AccelerationStructurePassSampleBufferAttachmentDescriptorArray::object(NS::UInteger attachmentIndex) { return Object::sendMessage<MTL::AccelerationStructurePassSampleBufferAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), attachmentIndex); } _MTL_INLINE void MTL::AccelerationStructurePassSampleBufferAttachmentDescriptorArray::setObject(const MTL::AccelerationStructurePassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attachment, attachmentIndex); } _MTL_INLINE MTL::AccelerationStructurePassDescriptor* MTL::AccelerationStructurePassDescriptor::alloc() { return NS::Object::alloc<MTL::AccelerationStructurePassDescriptor>(_MTL_PRIVATE_CLS(MTLAccelerationStructurePassDescriptor)); } _MTL_INLINE MTL::AccelerationStructurePassDescriptor* MTL::AccelerationStructurePassDescriptor::init() { return NS::Object::init<MTL::AccelerationStructurePassDescriptor>(); } _MTL_INLINE MTL::AccelerationStructurePassDescriptor* MTL::AccelerationStructurePassDescriptor::accelerationStructurePassDescriptor() { return Object::sendMessage<MTL::AccelerationStructurePassDescriptor*>(_MTL_PRIVATE_CLS(MTLAccelerationStructurePassDescriptor), _MTL_PRIVATE_SEL(accelerationStructurePassDescriptor)); } _MTL_INLINE MTL::AccelerationStructurePassSampleBufferAttachmentDescriptorArray* MTL::AccelerationStructurePassDescriptor::sampleBufferAttachments() const { return Object::sendMessage<MTL::AccelerationStructurePassSampleBufferAttachmentDescriptorArray*>(this, _MTL_PRIVATE_SEL(sampleBufferAttachments)); } #pragma once namespace MTL { static const NS::UInteger AttributeStrideStatic = NS::UIntegerMax; class ArgumentEncoder : public NS::Referencing<ArgumentEncoder> { public: class Device* device() const; NS::String* label() const; void setLabel(const NS::String* label); NS::UInteger encodedLength() const; NS::UInteger alignment() const; void setArgumentBuffer(const class Buffer* argumentBuffer, NS::UInteger offset); void setArgumentBuffer(const class Buffer* argumentBuffer, NS::UInteger startOffset, NS::UInteger arrayElement); void setBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index); void setBuffers(const class Buffer* const buffers[], const NS::UInteger offsets[], NS::Range range); void setTexture(const class Texture* texture, NS::UInteger index); void setTextures(const class Texture* const textures[], NS::Range range); void setSamplerState(const class SamplerState* sampler, NS::UInteger index); void setSamplerStates(const class SamplerState* const samplers[], NS::Range range); void* constantData(NS::UInteger index); void setRenderPipelineState(const class RenderPipelineState* pipeline, NS::UInteger index); void setRenderPipelineStates(const class RenderPipelineState* const pipelines[], NS::Range range); void setComputePipelineState(const class ComputePipelineState* pipeline, NS::UInteger index); void setComputePipelineStates(const class ComputePipelineState* const pipelines[], NS::Range range); void setIndirectCommandBuffer(const class IndirectCommandBuffer* indirectCommandBuffer, NS::UInteger index); void setIndirectCommandBuffers(const class IndirectCommandBuffer* const buffers[], NS::Range range); void setAccelerationStructure(const class AccelerationStructure* accelerationStructure, NS::UInteger index); class ArgumentEncoder* newArgumentEncoder(NS::UInteger index); void setVisibleFunctionTable(const class VisibleFunctionTable* visibleFunctionTable, NS::UInteger index); void setVisibleFunctionTables(const class VisibleFunctionTable* const visibleFunctionTables[], NS::Range range); void setIntersectionFunctionTable(const class IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger index); void setIntersectionFunctionTables(const class IntersectionFunctionTable* const intersectionFunctionTables[], NS::Range range); }; } _MTL_INLINE MTL::Device* MTL::ArgumentEncoder::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE NS::String* MTL::ArgumentEncoder::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::ArgumentEncoder::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE NS::UInteger MTL::ArgumentEncoder::encodedLength() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(encodedLength)); } _MTL_INLINE NS::UInteger MTL::ArgumentEncoder::alignment() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(alignment)); } _MTL_INLINE void MTL::ArgumentEncoder::setArgumentBuffer(const MTL::Buffer* argumentBuffer, NS::UInteger offset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setArgumentBuffer_offset_), argumentBuffer, offset); } _MTL_INLINE void MTL::ArgumentEncoder::setArgumentBuffer(const MTL::Buffer* argumentBuffer, NS::UInteger startOffset, NS::UInteger arrayElement) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setArgumentBuffer_startOffset_arrayElement_), argumentBuffer, startOffset, arrayElement); } _MTL_INLINE void MTL::ArgumentEncoder::setBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBuffer_offset_atIndex_), buffer, offset, index); } _MTL_INLINE void MTL::ArgumentEncoder::setBuffers(const MTL::Buffer* const buffers[], const NS::UInteger offsets[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBuffers_offsets_withRange_), buffers, offsets, range); } _MTL_INLINE void MTL::ArgumentEncoder::setTexture(const MTL::Texture* texture, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTexture_atIndex_), texture, index); } _MTL_INLINE void MTL::ArgumentEncoder::setTextures(const MTL::Texture* const textures[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTextures_withRange_), textures, range); } _MTL_INLINE void MTL::ArgumentEncoder::setSamplerState(const MTL::SamplerState* sampler, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSamplerState_atIndex_), sampler, index); } _MTL_INLINE void MTL::ArgumentEncoder::setSamplerStates(const MTL::SamplerState* const samplers[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSamplerStates_withRange_), samplers, range); } _MTL_INLINE void* MTL::ArgumentEncoder::constantData(NS::UInteger index) { return Object::sendMessage<void*>(this, _MTL_PRIVATE_SEL(constantDataAtIndex_), index); } _MTL_INLINE void MTL::ArgumentEncoder::setRenderPipelineState(const MTL::RenderPipelineState* pipeline, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRenderPipelineState_atIndex_), pipeline, index); } _MTL_INLINE void MTL::ArgumentEncoder::setRenderPipelineStates(const MTL::RenderPipelineState* const pipelines[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRenderPipelineStates_withRange_), pipelines, range); } _MTL_INLINE void MTL::ArgumentEncoder::setComputePipelineState(const MTL::ComputePipelineState* pipeline, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setComputePipelineState_atIndex_), pipeline, index); } _MTL_INLINE void MTL::ArgumentEncoder::setComputePipelineStates(const MTL::ComputePipelineState* const pipelines[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setComputePipelineStates_withRange_), pipelines, range); } _MTL_INLINE void MTL::ArgumentEncoder::setIndirectCommandBuffer(const MTL::IndirectCommandBuffer* indirectCommandBuffer, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndirectCommandBuffer_atIndex_), indirectCommandBuffer, index); } _MTL_INLINE void MTL::ArgumentEncoder::setIndirectCommandBuffers(const MTL::IndirectCommandBuffer* const buffers[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndirectCommandBuffers_withRange_), buffers, range); } _MTL_INLINE void MTL::ArgumentEncoder::setAccelerationStructure(const MTL::AccelerationStructure* accelerationStructure, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAccelerationStructure_atIndex_), accelerationStructure, index); } _MTL_INLINE MTL::ArgumentEncoder* MTL::ArgumentEncoder::newArgumentEncoder(NS::UInteger index) { return Object::sendMessage<MTL::ArgumentEncoder*>(this, _MTL_PRIVATE_SEL(newArgumentEncoderForBufferAtIndex_), index); } _MTL_INLINE void MTL::ArgumentEncoder::setVisibleFunctionTable(const MTL::VisibleFunctionTable* visibleFunctionTable, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVisibleFunctionTable_atIndex_), visibleFunctionTable, index); } _MTL_INLINE void MTL::ArgumentEncoder::setVisibleFunctionTables(const MTL::VisibleFunctionTable* const visibleFunctionTables[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVisibleFunctionTables_withRange_), visibleFunctionTables, range); } _MTL_INLINE void MTL::ArgumentEncoder::setIntersectionFunctionTable(const MTL::IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIntersectionFunctionTable_atIndex_), intersectionFunctionTable, index); } _MTL_INLINE void MTL::ArgumentEncoder::setIntersectionFunctionTables(const MTL::IntersectionFunctionTable* const intersectionFunctionTables[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIntersectionFunctionTables_withRange_), intersectionFunctionTables, range); } #pragma once namespace MTL { _MTL_ENUM(NS::UInteger, BinaryArchiveError) { BinaryArchiveErrorNone = 0, BinaryArchiveErrorInvalidFile = 1, BinaryArchiveErrorUnexpectedElement = 2, BinaryArchiveErrorCompilationFailure = 3, BinaryArchiveErrorInternalError = 4, }; class BinaryArchiveDescriptor : public NS::Copying<BinaryArchiveDescriptor> { public: static class BinaryArchiveDescriptor* alloc(); class BinaryArchiveDescriptor* init(); NS::URL* url() const; void setUrl(const NS::URL* url); }; class BinaryArchive : public NS::Referencing<BinaryArchive> { public: NS::String* label() const; void setLabel(const NS::String* label); class Device* device() const; bool addComputePipelineFunctions(const class ComputePipelineDescriptor* descriptor, NS::Error** error); bool addRenderPipelineFunctions(const class RenderPipelineDescriptor* descriptor, NS::Error** error); bool addTileRenderPipelineFunctions(const class TileRenderPipelineDescriptor* descriptor, NS::Error** error); bool serializeToURL(const NS::URL* url, NS::Error** error); bool addFunction(const class FunctionDescriptor* descriptor, const class Library* library, NS::Error** error); }; } _MTL_INLINE MTL::BinaryArchiveDescriptor* MTL::BinaryArchiveDescriptor::alloc() { return NS::Object::alloc<MTL::BinaryArchiveDescriptor>(_MTL_PRIVATE_CLS(MTLBinaryArchiveDescriptor)); } _MTL_INLINE MTL::BinaryArchiveDescriptor* MTL::BinaryArchiveDescriptor::init() { return NS::Object::init<MTL::BinaryArchiveDescriptor>(); } _MTL_INLINE NS::URL* MTL::BinaryArchiveDescriptor::url() const { return Object::sendMessage<NS::URL*>(this, _MTL_PRIVATE_SEL(url)); } _MTL_INLINE void MTL::BinaryArchiveDescriptor::setUrl(const NS::URL* url) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setUrl_), url); } _MTL_INLINE NS::String* MTL::BinaryArchive::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::BinaryArchive::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE MTL::Device* MTL::BinaryArchive::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE bool MTL::BinaryArchive::addComputePipelineFunctions(const MTL::ComputePipelineDescriptor* descriptor, NS::Error** error) { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(addComputePipelineFunctionsWithDescriptor_error_), descriptor, error); } _MTL_INLINE bool MTL::BinaryArchive::addRenderPipelineFunctions(const MTL::RenderPipelineDescriptor* descriptor, NS::Error** error) { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(addRenderPipelineFunctionsWithDescriptor_error_), descriptor, error); } _MTL_INLINE bool MTL::BinaryArchive::addTileRenderPipelineFunctions(const MTL::TileRenderPipelineDescriptor* descriptor, NS::Error** error) { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(addTileRenderPipelineFunctionsWithDescriptor_error_), descriptor, error); } _MTL_INLINE bool MTL::BinaryArchive::serializeToURL(const NS::URL* url, NS::Error** error) { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(serializeToURL_error_), url, error); } _MTL_INLINE bool MTL::BinaryArchive::addFunction(const MTL::FunctionDescriptor* descriptor, const MTL::Library* library, NS::Error** error) { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(addFunctionWithDescriptor_library_error_), descriptor, library, error); } #pragma once namespace MTL { _MTL_OPTIONS(NS::UInteger, BlitOption) { BlitOptionNone = 0, BlitOptionDepthFromDepthStencil = 1, BlitOptionStencilFromDepthStencil = 2, BlitOptionRowLinearPVRTC = 4, }; class BlitCommandEncoder : public NS::Referencing<BlitCommandEncoder, CommandEncoder> { public: void synchronizeResource(const class Resource* resource); void synchronizeTexture(const class Texture* texture, NS::UInteger slice, NS::UInteger level); void copyFromTexture(const class Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, MTL::Origin sourceOrigin, MTL::Size sourceSize, const class Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, MTL::Origin destinationOrigin); void copyFromBuffer(const class Buffer* sourceBuffer, NS::UInteger sourceOffset, NS::UInteger sourceBytesPerRow, NS::UInteger sourceBytesPerImage, MTL::Size sourceSize, const class Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, MTL::Origin destinationOrigin); void copyFromBuffer(const class Buffer* sourceBuffer, NS::UInteger sourceOffset, NS::UInteger sourceBytesPerRow, NS::UInteger sourceBytesPerImage, MTL::Size sourceSize, const class Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, MTL::Origin destinationOrigin, MTL::BlitOption options); void copyFromTexture(const class Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, MTL::Origin sourceOrigin, MTL::Size sourceSize, const class Buffer* destinationBuffer, NS::UInteger destinationOffset, NS::UInteger destinationBytesPerRow, NS::UInteger destinationBytesPerImage); void copyFromTexture(const class Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, MTL::Origin sourceOrigin, MTL::Size sourceSize, const class Buffer* destinationBuffer, NS::UInteger destinationOffset, NS::UInteger destinationBytesPerRow, NS::UInteger destinationBytesPerImage, MTL::BlitOption options); void generateMipmaps(const class Texture* texture); void fillBuffer(const class Buffer* buffer, NS::Range range, uint8_t value); void copyFromTexture(const class Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, const class Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, NS::UInteger sliceCount, NS::UInteger levelCount); void copyFromTexture(const class Texture* sourceTexture, const class Texture* destinationTexture); void copyFromBuffer(const class Buffer* sourceBuffer, NS::UInteger sourceOffset, const class Buffer* destinationBuffer, NS::UInteger destinationOffset, NS::UInteger size); void updateFence(const class Fence* fence); void waitForFence(const class Fence* fence); void getTextureAccessCounters(const class Texture* texture, MTL::Region region, NS::UInteger mipLevel, NS::UInteger slice, bool resetCounters, const class Buffer* countersBuffer, NS::UInteger countersBufferOffset); void resetTextureAccessCounters(const class Texture* texture, MTL::Region region, NS::UInteger mipLevel, NS::UInteger slice); void optimizeContentsForGPUAccess(const class Texture* texture); void optimizeContentsForGPUAccess(const class Texture* texture, NS::UInteger slice, NS::UInteger level); void optimizeContentsForCPUAccess(const class Texture* texture); void optimizeContentsForCPUAccess(const class Texture* texture, NS::UInteger slice, NS::UInteger level); void resetCommandsInBuffer(const class IndirectCommandBuffer* buffer, NS::Range range); void copyIndirectCommandBuffer(const class IndirectCommandBuffer* source, NS::Range sourceRange, const class IndirectCommandBuffer* destination, NS::UInteger destinationIndex); void optimizeIndirectCommandBuffer(const class IndirectCommandBuffer* indirectCommandBuffer, NS::Range range); void sampleCountersInBuffer(const class CounterSampleBuffer* sampleBuffer, NS::UInteger sampleIndex, bool barrier); void resolveCounters(const class CounterSampleBuffer* sampleBuffer, NS::Range range, const class Buffer* destinationBuffer, NS::UInteger destinationOffset); }; } _MTL_INLINE void MTL::BlitCommandEncoder::synchronizeResource(const MTL::Resource* resource) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(synchronizeResource_), resource); } _MTL_INLINE void MTL::BlitCommandEncoder::synchronizeTexture(const MTL::Texture* texture, NS::UInteger slice, NS::UInteger level) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(synchronizeTexture_slice_level_), texture, slice, level); } _MTL_INLINE void MTL::BlitCommandEncoder::copyFromTexture(const MTL::Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, MTL::Origin sourceOrigin, MTL::Size sourceSize, const MTL::Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, MTL::Origin destinationOrigin) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin_), sourceTexture, sourceSlice, sourceLevel, sourceOrigin, sourceSize, destinationTexture, destinationSlice, destinationLevel, destinationOrigin); } _MTL_INLINE void MTL::BlitCommandEncoder::copyFromBuffer(const MTL::Buffer* sourceBuffer, NS::UInteger sourceOffset, NS::UInteger sourceBytesPerRow, NS::UInteger sourceBytesPerImage, MTL::Size sourceSize, const MTL::Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, MTL::Origin destinationOrigin) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin_), sourceBuffer, sourceOffset, sourceBytesPerRow, sourceBytesPerImage, sourceSize, destinationTexture, destinationSlice, destinationLevel, destinationOrigin); } _MTL_INLINE void MTL::BlitCommandEncoder::copyFromBuffer(const MTL::Buffer* sourceBuffer, NS::UInteger sourceOffset, NS::UInteger sourceBytesPerRow, NS::UInteger sourceBytesPerImage, MTL::Size sourceSize, const MTL::Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, MTL::Origin destinationOrigin, MTL::BlitOption options) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin_options_), sourceBuffer, sourceOffset, sourceBytesPerRow, sourceBytesPerImage, sourceSize, destinationTexture, destinationSlice, destinationLevel, destinationOrigin, options); } _MTL_INLINE void MTL::BlitCommandEncoder::copyFromTexture(const MTL::Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, MTL::Origin sourceOrigin, MTL::Size sourceSize, const MTL::Buffer* destinationBuffer, NS::UInteger destinationOffset, NS::UInteger destinationBytesPerRow, NS::UInteger destinationBytesPerImage) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage_), sourceTexture, sourceSlice, sourceLevel, sourceOrigin, sourceSize, destinationBuffer, destinationOffset, destinationBytesPerRow, destinationBytesPerImage); } _MTL_INLINE void MTL::BlitCommandEncoder::copyFromTexture(const MTL::Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, MTL::Origin sourceOrigin, MTL::Size sourceSize, const MTL::Buffer* destinationBuffer, NS::UInteger destinationOffset, NS::UInteger destinationBytesPerRow, NS::UInteger destinationBytesPerImage, MTL::BlitOption options) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage_options_), sourceTexture, sourceSlice, sourceLevel, sourceOrigin, sourceSize, destinationBuffer, destinationOffset, destinationBytesPerRow, destinationBytesPerImage, options); } _MTL_INLINE void MTL::BlitCommandEncoder::generateMipmaps(const MTL::Texture* texture) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(generateMipmapsForTexture_), texture); } _MTL_INLINE void MTL::BlitCommandEncoder::fillBuffer(const MTL::Buffer* buffer, NS::Range range, uint8_t value) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(fillBuffer_range_value_), buffer, range, value); } _MTL_INLINE void MTL::BlitCommandEncoder::copyFromTexture(const MTL::Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, const MTL::Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, NS::UInteger sliceCount, NS::UInteger levelCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyFromTexture_sourceSlice_sourceLevel_toTexture_destinationSlice_destinationLevel_sliceCount_levelCount_), sourceTexture, sourceSlice, sourceLevel, destinationTexture, destinationSlice, destinationLevel, sliceCount, levelCount); } _MTL_INLINE void MTL::BlitCommandEncoder::copyFromTexture(const MTL::Texture* sourceTexture, const MTL::Texture* destinationTexture) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyFromTexture_toTexture_), sourceTexture, destinationTexture); } _MTL_INLINE void MTL::BlitCommandEncoder::copyFromBuffer(const MTL::Buffer* sourceBuffer, NS::UInteger sourceOffset, const MTL::Buffer* destinationBuffer, NS::UInteger destinationOffset, NS::UInteger size) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyFromBuffer_sourceOffset_toBuffer_destinationOffset_size_), sourceBuffer, sourceOffset, destinationBuffer, destinationOffset, size); } _MTL_INLINE void MTL::BlitCommandEncoder::updateFence(const MTL::Fence* fence) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(updateFence_), fence); } _MTL_INLINE void MTL::BlitCommandEncoder::waitForFence(const MTL::Fence* fence) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(waitForFence_), fence); } _MTL_INLINE void MTL::BlitCommandEncoder::getTextureAccessCounters(const MTL::Texture* texture, MTL::Region region, NS::UInteger mipLevel, NS::UInteger slice, bool resetCounters, const MTL::Buffer* countersBuffer, NS::UInteger countersBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(getTextureAccessCounters_region_mipLevel_slice_resetCounters_countersBuffer_countersBufferOffset_), texture, region, mipLevel, slice, resetCounters, countersBuffer, countersBufferOffset); } _MTL_INLINE void MTL::BlitCommandEncoder::resetTextureAccessCounters(const MTL::Texture* texture, MTL::Region region, NS::UInteger mipLevel, NS::UInteger slice) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(resetTextureAccessCounters_region_mipLevel_slice_), texture, region, mipLevel, slice); } _MTL_INLINE void MTL::BlitCommandEncoder::optimizeContentsForGPUAccess(const MTL::Texture* texture) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(optimizeContentsForGPUAccess_), texture); } _MTL_INLINE void MTL::BlitCommandEncoder::optimizeContentsForGPUAccess(const MTL::Texture* texture, NS::UInteger slice, NS::UInteger level) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(optimizeContentsForGPUAccess_slice_level_), texture, slice, level); } _MTL_INLINE void MTL::BlitCommandEncoder::optimizeContentsForCPUAccess(const MTL::Texture* texture) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(optimizeContentsForCPUAccess_), texture); } _MTL_INLINE void MTL::BlitCommandEncoder::optimizeContentsForCPUAccess(const MTL::Texture* texture, NS::UInteger slice, NS::UInteger level) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(optimizeContentsForCPUAccess_slice_level_), texture, slice, level); } _MTL_INLINE void MTL::BlitCommandEncoder::resetCommandsInBuffer(const MTL::IndirectCommandBuffer* buffer, NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(resetCommandsInBuffer_withRange_), buffer, range); } _MTL_INLINE void MTL::BlitCommandEncoder::copyIndirectCommandBuffer(const MTL::IndirectCommandBuffer* source, NS::Range sourceRange, const MTL::IndirectCommandBuffer* destination, NS::UInteger destinationIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyIndirectCommandBuffer_sourceRange_destination_destinationIndex_), source, sourceRange, destination, destinationIndex); } _MTL_INLINE void MTL::BlitCommandEncoder::optimizeIndirectCommandBuffer(const MTL::IndirectCommandBuffer* indirectCommandBuffer, NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(optimizeIndirectCommandBuffer_withRange_), indirectCommandBuffer, range); } _MTL_INLINE void MTL::BlitCommandEncoder::sampleCountersInBuffer(const MTL::CounterSampleBuffer* sampleBuffer, NS::UInteger sampleIndex, bool barrier) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(sampleCountersInBuffer_atSampleIndex_withBarrier_), sampleBuffer, sampleIndex, barrier); } _MTL_INLINE void MTL::BlitCommandEncoder::resolveCounters(const MTL::CounterSampleBuffer* sampleBuffer, NS::Range range, const MTL::Buffer* destinationBuffer, NS::UInteger destinationOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(resolveCounters_inRange_destinationBuffer_destinationOffset_), sampleBuffer, range, destinationBuffer, destinationOffset); } #pragma once namespace MTL { class BlitPassSampleBufferAttachmentDescriptor : public NS::Copying<BlitPassSampleBufferAttachmentDescriptor> { public: static class BlitPassSampleBufferAttachmentDescriptor* alloc(); class BlitPassSampleBufferAttachmentDescriptor* init(); class CounterSampleBuffer* sampleBuffer() const; void setSampleBuffer(const class CounterSampleBuffer* sampleBuffer); NS::UInteger startOfEncoderSampleIndex() const; void setStartOfEncoderSampleIndex(NS::UInteger startOfEncoderSampleIndex); NS::UInteger endOfEncoderSampleIndex() const; void setEndOfEncoderSampleIndex(NS::UInteger endOfEncoderSampleIndex); }; class BlitPassSampleBufferAttachmentDescriptorArray : public NS::Referencing<BlitPassSampleBufferAttachmentDescriptorArray> { public: static class BlitPassSampleBufferAttachmentDescriptorArray* alloc(); class BlitPassSampleBufferAttachmentDescriptorArray* init(); class BlitPassSampleBufferAttachmentDescriptor* object(NS::UInteger attachmentIndex); void setObject(const class BlitPassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex); }; class BlitPassDescriptor : public NS::Copying<BlitPassDescriptor> { public: static class BlitPassDescriptor* alloc(); class BlitPassDescriptor* init(); static class BlitPassDescriptor* blitPassDescriptor(); class BlitPassSampleBufferAttachmentDescriptorArray* sampleBufferAttachments() const; }; } _MTL_INLINE MTL::BlitPassSampleBufferAttachmentDescriptor* MTL::BlitPassSampleBufferAttachmentDescriptor::alloc() { return NS::Object::alloc<MTL::BlitPassSampleBufferAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLBlitPassSampleBufferAttachmentDescriptor)); } _MTL_INLINE MTL::BlitPassSampleBufferAttachmentDescriptor* MTL::BlitPassSampleBufferAttachmentDescriptor::init() { return NS::Object::init<MTL::BlitPassSampleBufferAttachmentDescriptor>(); } _MTL_INLINE MTL::CounterSampleBuffer* MTL::BlitPassSampleBufferAttachmentDescriptor::sampleBuffer() const { return Object::sendMessage<MTL::CounterSampleBuffer*>(this, _MTL_PRIVATE_SEL(sampleBuffer)); } _MTL_INLINE void MTL::BlitPassSampleBufferAttachmentDescriptor::setSampleBuffer(const MTL::CounterSampleBuffer* sampleBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSampleBuffer_), sampleBuffer); } _MTL_INLINE NS::UInteger MTL::BlitPassSampleBufferAttachmentDescriptor::startOfEncoderSampleIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(startOfEncoderSampleIndex)); } _MTL_INLINE void MTL::BlitPassSampleBufferAttachmentDescriptor::setStartOfEncoderSampleIndex(NS::UInteger startOfEncoderSampleIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStartOfEncoderSampleIndex_), startOfEncoderSampleIndex); } _MTL_INLINE NS::UInteger MTL::BlitPassSampleBufferAttachmentDescriptor::endOfEncoderSampleIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(endOfEncoderSampleIndex)); } _MTL_INLINE void MTL::BlitPassSampleBufferAttachmentDescriptor::setEndOfEncoderSampleIndex(NS::UInteger endOfEncoderSampleIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setEndOfEncoderSampleIndex_), endOfEncoderSampleIndex); } _MTL_INLINE MTL::BlitPassSampleBufferAttachmentDescriptorArray* MTL::BlitPassSampleBufferAttachmentDescriptorArray::alloc() { return NS::Object::alloc<MTL::BlitPassSampleBufferAttachmentDescriptorArray>(_MTL_PRIVATE_CLS(MTLBlitPassSampleBufferAttachmentDescriptorArray)); } _MTL_INLINE MTL::BlitPassSampleBufferAttachmentDescriptorArray* MTL::BlitPassSampleBufferAttachmentDescriptorArray::init() { return NS::Object::init<MTL::BlitPassSampleBufferAttachmentDescriptorArray>(); } _MTL_INLINE MTL::BlitPassSampleBufferAttachmentDescriptor* MTL::BlitPassSampleBufferAttachmentDescriptorArray::object(NS::UInteger attachmentIndex) { return Object::sendMessage<MTL::BlitPassSampleBufferAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), attachmentIndex); } _MTL_INLINE void MTL::BlitPassSampleBufferAttachmentDescriptorArray::setObject(const MTL::BlitPassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attachment, attachmentIndex); } _MTL_INLINE MTL::BlitPassDescriptor* MTL::BlitPassDescriptor::alloc() { return NS::Object::alloc<MTL::BlitPassDescriptor>(_MTL_PRIVATE_CLS(MTLBlitPassDescriptor)); } _MTL_INLINE MTL::BlitPassDescriptor* MTL::BlitPassDescriptor::init() { return NS::Object::init<MTL::BlitPassDescriptor>(); } _MTL_INLINE MTL::BlitPassDescriptor* MTL::BlitPassDescriptor::blitPassDescriptor() { return Object::sendMessage<MTL::BlitPassDescriptor*>(_MTL_PRIVATE_CLS(MTLBlitPassDescriptor), _MTL_PRIVATE_SEL(blitPassDescriptor)); } _MTL_INLINE MTL::BlitPassSampleBufferAttachmentDescriptorArray* MTL::BlitPassDescriptor::sampleBufferAttachments() const { return Object::sendMessage<MTL::BlitPassSampleBufferAttachmentDescriptorArray*>(this, _MTL_PRIVATE_SEL(sampleBufferAttachments)); } #pragma once namespace MTL { class Buffer : public NS::Referencing<Buffer, Resource> { public: NS::UInteger length() const; void* contents(); void didModifyRange(NS::Range range); class Texture* newTexture(const class TextureDescriptor* descriptor, NS::UInteger offset, NS::UInteger bytesPerRow); void addDebugMarker(const NS::String* marker, NS::Range range); void removeAllDebugMarkers(); class Buffer* remoteStorageBuffer() const; class Buffer* newRemoteBufferViewForDevice(const class Device* device); uint64_t gpuAddress() const; }; } _MTL_INLINE NS::UInteger MTL::Buffer::length() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(length)); } _MTL_INLINE void* MTL::Buffer::contents() { return Object::sendMessage<void*>(this, _MTL_PRIVATE_SEL(contents)); } _MTL_INLINE void MTL::Buffer::didModifyRange(NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(didModifyRange_), range); } _MTL_INLINE MTL::Texture* MTL::Buffer::newTexture(const MTL::TextureDescriptor* descriptor, NS::UInteger offset, NS::UInteger bytesPerRow) { return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newTextureWithDescriptor_offset_bytesPerRow_), descriptor, offset, bytesPerRow); } _MTL_INLINE void MTL::Buffer::addDebugMarker(const NS::String* marker, NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(addDebugMarker_range_), marker, range); } _MTL_INLINE void MTL::Buffer::removeAllDebugMarkers() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(removeAllDebugMarkers)); } _MTL_INLINE MTL::Buffer* MTL::Buffer::remoteStorageBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(remoteStorageBuffer)); } _MTL_INLINE MTL::Buffer* MTL::Buffer::newRemoteBufferViewForDevice(const MTL::Device* device) { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(newRemoteBufferViewForDevice_), device); } _MTL_INLINE uint64_t MTL::Buffer::gpuAddress() const { return Object::sendMessage<uint64_t>(this, _MTL_PRIVATE_SEL(gpuAddress)); } #pragma once namespace MTL { _MTL_ENUM(NS::Integer, CaptureError) { CaptureErrorNotSupported = 1, CaptureErrorAlreadyCapturing = 2, CaptureErrorInvalidDescriptor = 3, }; _MTL_ENUM(NS::Integer, CaptureDestination) { CaptureDestinationDeveloperTools = 1, CaptureDestinationGPUTraceDocument = 2, }; class CaptureDescriptor : public NS::Copying<CaptureDescriptor> { public: static class CaptureDescriptor* alloc(); class CaptureDescriptor* init(); id captureObject() const; void setCaptureObject(id captureObject); MTL::CaptureDestination destination() const; void setDestination(MTL::CaptureDestination destination); NS::URL* outputURL() const; void setOutputURL(const NS::URL* outputURL); }; class CaptureManager : public NS::Referencing<CaptureManager> { public: static class CaptureManager* alloc(); static class CaptureManager* sharedCaptureManager(); MTL::CaptureManager* init(); class CaptureScope* newCaptureScope(const class Device* device); class CaptureScope* newCaptureScope(const class CommandQueue* commandQueue); bool supportsDestination(MTL::CaptureDestination destination); bool startCapture(const class CaptureDescriptor* descriptor, NS::Error** error); void startCapture(const class Device* device); void startCapture(const class CommandQueue* commandQueue); void startCapture(const class CaptureScope* captureScope); void stopCapture(); class CaptureScope* defaultCaptureScope() const; void setDefaultCaptureScope(const class CaptureScope* defaultCaptureScope); bool isCapturing() const; }; } _MTL_INLINE MTL::CaptureDescriptor* MTL::CaptureDescriptor::alloc() { return NS::Object::alloc<MTL::CaptureDescriptor>(_MTL_PRIVATE_CLS(MTLCaptureDescriptor)); } _MTL_INLINE MTL::CaptureDescriptor* MTL::CaptureDescriptor::init() { return NS::Object::init<MTL::CaptureDescriptor>(); } _MTL_INLINE id MTL::CaptureDescriptor::captureObject() const { return Object::sendMessage<id>(this, _MTL_PRIVATE_SEL(captureObject)); } _MTL_INLINE void MTL::CaptureDescriptor::setCaptureObject(id captureObject) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCaptureObject_), captureObject); } _MTL_INLINE MTL::CaptureDestination MTL::CaptureDescriptor::destination() const { return Object::sendMessage<MTL::CaptureDestination>(this, _MTL_PRIVATE_SEL(destination)); } _MTL_INLINE void MTL::CaptureDescriptor::setDestination(MTL::CaptureDestination destination) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDestination_), destination); } _MTL_INLINE NS::URL* MTL::CaptureDescriptor::outputURL() const { return Object::sendMessage<NS::URL*>(this, _MTL_PRIVATE_SEL(outputURL)); } _MTL_INLINE void MTL::CaptureDescriptor::setOutputURL(const NS::URL* outputURL) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOutputURL_), outputURL); } _MTL_INLINE MTL::CaptureManager* MTL::CaptureManager::alloc() { return NS::Object::alloc<MTL::CaptureManager>(_MTL_PRIVATE_CLS(MTLCaptureManager)); } _MTL_INLINE MTL::CaptureManager* MTL::CaptureManager::sharedCaptureManager() { return Object::sendMessage<MTL::CaptureManager*>(_MTL_PRIVATE_CLS(MTLCaptureManager), _MTL_PRIVATE_SEL(sharedCaptureManager)); } _MTL_INLINE MTL::CaptureManager* MTL::CaptureManager::init() { return NS::Object::init<MTL::CaptureManager>(); } _MTL_INLINE MTL::CaptureScope* MTL::CaptureManager::newCaptureScope(const MTL::Device* device) { return Object::sendMessage<MTL::CaptureScope*>(this, _MTL_PRIVATE_SEL(newCaptureScopeWithDevice_), device); } _MTL_INLINE MTL::CaptureScope* MTL::CaptureManager::newCaptureScope(const MTL::CommandQueue* commandQueue) { return Object::sendMessage<MTL::CaptureScope*>(this, _MTL_PRIVATE_SEL(newCaptureScopeWithCommandQueue_), commandQueue); } _MTL_INLINE bool MTL::CaptureManager::supportsDestination(MTL::CaptureDestination destination) { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsDestination_), destination); } _MTL_INLINE bool MTL::CaptureManager::startCapture(const MTL::CaptureDescriptor* descriptor, NS::Error** error) { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(startCaptureWithDescriptor_error_), descriptor, error); } _MTL_INLINE void MTL::CaptureManager::startCapture(const MTL::Device* device) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(startCaptureWithDevice_), device); } _MTL_INLINE void MTL::CaptureManager::startCapture(const MTL::CommandQueue* commandQueue) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(startCaptureWithCommandQueue_), commandQueue); } _MTL_INLINE void MTL::CaptureManager::startCapture(const MTL::CaptureScope* captureScope) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(startCaptureWithScope_), captureScope); } _MTL_INLINE void MTL::CaptureManager::stopCapture() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(stopCapture)); } _MTL_INLINE MTL::CaptureScope* MTL::CaptureManager::defaultCaptureScope() const { return Object::sendMessage<MTL::CaptureScope*>(this, _MTL_PRIVATE_SEL(defaultCaptureScope)); } _MTL_INLINE void MTL::CaptureManager::setDefaultCaptureScope(const MTL::CaptureScope* defaultCaptureScope) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDefaultCaptureScope_), defaultCaptureScope); } _MTL_INLINE bool MTL::CaptureManager::isCapturing() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isCapturing)); } namespace MTL { class CaptureScope : public NS::Referencing<CaptureScope> { public: class Device* device() const; NS::String* label() const; void setLabel(const NS::String* pLabel); class CommandQueue* commandQueue() const; void beginScope(); void endScope(); }; } _MTL_INLINE MTL::Device* MTL::CaptureScope::device() const { return Object::sendMessage<Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE NS::String* MTL::CaptureScope::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::CaptureScope::setLabel(const NS::String* pLabel) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), pLabel); } _MTL_INLINE MTL::CommandQueue* MTL::CaptureScope::commandQueue() const { return Object::sendMessage<CommandQueue*>(this, _MTL_PRIVATE_SEL(commandQueue)); } _MTL_INLINE void MTL::CaptureScope::beginScope() { return Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(beginScope)); } _MTL_INLINE void MTL::CaptureScope::endScope() { return Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(endScope)); } #pragma once #include <functional> namespace MTL { _MTL_ENUM(NS::UInteger, CommandBufferStatus) { CommandBufferStatusNotEnqueued = 0, CommandBufferStatusEnqueued = 1, CommandBufferStatusCommitted = 2, CommandBufferStatusScheduled = 3, CommandBufferStatusCompleted = 4, CommandBufferStatusError = 5, }; _MTL_ENUM(NS::UInteger, CommandBufferError) { CommandBufferErrorNone = 0, CommandBufferErrorInternal = 1, CommandBufferErrorTimeout = 2, CommandBufferErrorPageFault = 3, CommandBufferErrorBlacklisted = 4, CommandBufferErrorAccessRevoked = 4, CommandBufferErrorNotPermitted = 7, CommandBufferErrorOutOfMemory = 8, CommandBufferErrorInvalidResource = 9, CommandBufferErrorMemoryless = 10, CommandBufferErrorDeviceRemoved = 11, CommandBufferErrorStackOverflow = 12, }; _MTL_OPTIONS(NS::UInteger, CommandBufferErrorOption) { CommandBufferErrorOptionNone = 0, CommandBufferErrorOptionEncoderExecutionStatus = 1, }; _MTL_ENUM(NS::Integer, CommandEncoderErrorState) { CommandEncoderErrorStateUnknown = 0, CommandEncoderErrorStateCompleted = 1, CommandEncoderErrorStateAffected = 2, CommandEncoderErrorStatePending = 3, CommandEncoderErrorStateFaulted = 4, }; class CommandBufferDescriptor : public NS::Copying<CommandBufferDescriptor> { public: static class CommandBufferDescriptor* alloc(); class CommandBufferDescriptor* init(); bool retainedReferences() const; void setRetainedReferences(bool retainedReferences); MTL::CommandBufferErrorOption errorOptions() const; void setErrorOptions(MTL::CommandBufferErrorOption errorOptions); }; class CommandBufferEncoderInfo : public NS::Referencing<CommandBufferEncoderInfo> { public: NS::String* label() const; NS::Array* debugSignposts() const; MTL::CommandEncoderErrorState errorState() const; }; _MTL_ENUM(NS::UInteger, DispatchType) { DispatchTypeSerial = 0, DispatchTypeConcurrent = 1, }; class CommandBuffer; using CommandBufferHandler = void (^)(CommandBuffer*); using HandlerFunction = std::function<void(CommandBuffer*)>; class CommandBuffer : public NS::Referencing<CommandBuffer> { public: void addScheduledHandler(const HandlerFunction& function); void addCompletedHandler(const HandlerFunction& function); class Device* device() const; class CommandQueue* commandQueue() const; bool retainedReferences() const; MTL::CommandBufferErrorOption errorOptions() const; NS::String* label() const; void setLabel(const NS::String* label); CFTimeInterval kernelStartTime() const; CFTimeInterval kernelEndTime() const; class LogContainer* logs() const; CFTimeInterval GPUStartTime() const; CFTimeInterval GPUEndTime() const; void enqueue(); void commit(); void addScheduledHandler(const MTL::CommandBufferHandler block); void presentDrawable(const class Drawable* drawable); void presentDrawableAtTime(const class Drawable* drawable, CFTimeInterval presentationTime); void presentDrawableAfterMinimumDuration(const class Drawable* drawable, CFTimeInterval duration); void waitUntilScheduled(); void addCompletedHandler(const MTL::CommandBufferHandler block); void waitUntilCompleted(); MTL::CommandBufferStatus status() const; NS::Error* error() const; class BlitCommandEncoder* blitCommandEncoder(); class RenderCommandEncoder* renderCommandEncoder(const class RenderPassDescriptor* renderPassDescriptor); class ComputeCommandEncoder* computeCommandEncoder(const class ComputePassDescriptor* computePassDescriptor); class BlitCommandEncoder* blitCommandEncoder(const class BlitPassDescriptor* blitPassDescriptor); class ComputeCommandEncoder* computeCommandEncoder(); class ComputeCommandEncoder* computeCommandEncoder(MTL::DispatchType dispatchType); void encodeWait(const class Event* event, uint64_t value); void encodeSignalEvent(const class Event* event, uint64_t value); class ParallelRenderCommandEncoder* parallelRenderCommandEncoder(const class RenderPassDescriptor* renderPassDescriptor); class ResourceStateCommandEncoder* resourceStateCommandEncoder(); class ResourceStateCommandEncoder* resourceStateCommandEncoder(const class ResourceStatePassDescriptor* resourceStatePassDescriptor); class AccelerationStructureCommandEncoder* accelerationStructureCommandEncoder(); class AccelerationStructureCommandEncoder* accelerationStructureCommandEncoder(const class AccelerationStructurePassDescriptor* descriptor); void pushDebugGroup(const NS::String* string); void popDebugGroup(); }; } _MTL_INLINE MTL::CommandBufferDescriptor* MTL::CommandBufferDescriptor::alloc() { return NS::Object::alloc<MTL::CommandBufferDescriptor>(_MTL_PRIVATE_CLS(MTLCommandBufferDescriptor)); } _MTL_INLINE MTL::CommandBufferDescriptor* MTL::CommandBufferDescriptor::init() { return NS::Object::init<MTL::CommandBufferDescriptor>(); } _MTL_INLINE bool MTL::CommandBufferDescriptor::retainedReferences() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(retainedReferences)); } _MTL_INLINE void MTL::CommandBufferDescriptor::setRetainedReferences(bool retainedReferences) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRetainedReferences_), retainedReferences); } _MTL_INLINE MTL::CommandBufferErrorOption MTL::CommandBufferDescriptor::errorOptions() const { return Object::sendMessage<MTL::CommandBufferErrorOption>(this, _MTL_PRIVATE_SEL(errorOptions)); } _MTL_INLINE void MTL::CommandBufferDescriptor::setErrorOptions(MTL::CommandBufferErrorOption errorOptions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setErrorOptions_), errorOptions); } _MTL_INLINE NS::String* MTL::CommandBufferEncoderInfo::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE NS::Array* MTL::CommandBufferEncoderInfo::debugSignposts() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(debugSignposts)); } _MTL_INLINE MTL::CommandEncoderErrorState MTL::CommandBufferEncoderInfo::errorState() const { return Object::sendMessage<MTL::CommandEncoderErrorState>(this, _MTL_PRIVATE_SEL(errorState)); } _MTL_INLINE void MTL::CommandBuffer::addScheduledHandler(const HandlerFunction& function) { __block HandlerFunction blockFunction = function; addScheduledHandler(^(MTL::CommandBuffer* pCommandBuffer) { blockFunction(pCommandBuffer); }); } _MTL_INLINE void MTL::CommandBuffer::addCompletedHandler(const HandlerFunction& function) { __block HandlerFunction blockFunction = function; addCompletedHandler(^(MTL::CommandBuffer* pCommandBuffer) { blockFunction(pCommandBuffer); }); } _MTL_INLINE MTL::Device* MTL::CommandBuffer::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE MTL::CommandQueue* MTL::CommandBuffer::commandQueue() const { return Object::sendMessage<MTL::CommandQueue*>(this, _MTL_PRIVATE_SEL(commandQueue)); } _MTL_INLINE bool MTL::CommandBuffer::retainedReferences() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(retainedReferences)); } _MTL_INLINE MTL::CommandBufferErrorOption MTL::CommandBuffer::errorOptions() const { return Object::sendMessage<MTL::CommandBufferErrorOption>(this, _MTL_PRIVATE_SEL(errorOptions)); } _MTL_INLINE NS::String* MTL::CommandBuffer::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::CommandBuffer::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE CFTimeInterval MTL::CommandBuffer::kernelStartTime() const { return Object::sendMessage<CFTimeInterval>(this, _MTL_PRIVATE_SEL(kernelStartTime)); } _MTL_INLINE CFTimeInterval MTL::CommandBuffer::kernelEndTime() const { return Object::sendMessage<CFTimeInterval>(this, _MTL_PRIVATE_SEL(kernelEndTime)); } _MTL_INLINE MTL::LogContainer* MTL::CommandBuffer::logs() const { return Object::sendMessage<MTL::LogContainer*>(this, _MTL_PRIVATE_SEL(logs)); } _MTL_INLINE CFTimeInterval MTL::CommandBuffer::GPUStartTime() const { return Object::sendMessage<CFTimeInterval>(this, _MTL_PRIVATE_SEL(GPUStartTime)); } _MTL_INLINE CFTimeInterval MTL::CommandBuffer::GPUEndTime() const { return Object::sendMessage<CFTimeInterval>(this, _MTL_PRIVATE_SEL(GPUEndTime)); } _MTL_INLINE void MTL::CommandBuffer::enqueue() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(enqueue)); } _MTL_INLINE void MTL::CommandBuffer::commit() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(commit)); } _MTL_INLINE void MTL::CommandBuffer::addScheduledHandler(const MTL::CommandBufferHandler block) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(addScheduledHandler_), block); } _MTL_INLINE void MTL::CommandBuffer::presentDrawable(const MTL::Drawable* drawable) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(presentDrawable_), drawable); } _MTL_INLINE void MTL::CommandBuffer::presentDrawableAtTime(const MTL::Drawable* drawable, CFTimeInterval presentationTime) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(presentDrawable_atTime_), drawable, presentationTime); } _MTL_INLINE void MTL::CommandBuffer::presentDrawableAfterMinimumDuration(const MTL::Drawable* drawable, CFTimeInterval duration) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(presentDrawable_afterMinimumDuration_), drawable, duration); } _MTL_INLINE void MTL::CommandBuffer::waitUntilScheduled() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(waitUntilScheduled)); } _MTL_INLINE void MTL::CommandBuffer::addCompletedHandler(const MTL::CommandBufferHandler block) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(addCompletedHandler_), block); } _MTL_INLINE void MTL::CommandBuffer::waitUntilCompleted() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(waitUntilCompleted)); } _MTL_INLINE MTL::CommandBufferStatus MTL::CommandBuffer::status() const { return Object::sendMessage<MTL::CommandBufferStatus>(this, _MTL_PRIVATE_SEL(status)); } _MTL_INLINE NS::Error* MTL::CommandBuffer::error() const { return Object::sendMessage<NS::Error*>(this, _MTL_PRIVATE_SEL(error)); } _MTL_INLINE MTL::BlitCommandEncoder* MTL::CommandBuffer::blitCommandEncoder() { return Object::sendMessage<MTL::BlitCommandEncoder*>(this, _MTL_PRIVATE_SEL(blitCommandEncoder)); } _MTL_INLINE MTL::RenderCommandEncoder* MTL::CommandBuffer::renderCommandEncoder(const MTL::RenderPassDescriptor* renderPassDescriptor) { return Object::sendMessage<MTL::RenderCommandEncoder*>(this, _MTL_PRIVATE_SEL(renderCommandEncoderWithDescriptor_), renderPassDescriptor); } _MTL_INLINE MTL::ComputeCommandEncoder* MTL::CommandBuffer::computeCommandEncoder(const MTL::ComputePassDescriptor* computePassDescriptor) { return Object::sendMessage<MTL::ComputeCommandEncoder*>(this, _MTL_PRIVATE_SEL(computeCommandEncoderWithDescriptor_), computePassDescriptor); } _MTL_INLINE MTL::BlitCommandEncoder* MTL::CommandBuffer::blitCommandEncoder(const MTL::BlitPassDescriptor* blitPassDescriptor) { return Object::sendMessage<MTL::BlitCommandEncoder*>(this, _MTL_PRIVATE_SEL(blitCommandEncoderWithDescriptor_), blitPassDescriptor); } _MTL_INLINE MTL::ComputeCommandEncoder* MTL::CommandBuffer::computeCommandEncoder() { return Object::sendMessage<MTL::ComputeCommandEncoder*>(this, _MTL_PRIVATE_SEL(computeCommandEncoder)); } _MTL_INLINE MTL::ComputeCommandEncoder* MTL::CommandBuffer::computeCommandEncoder(MTL::DispatchType dispatchType) { return Object::sendMessage<MTL::ComputeCommandEncoder*>(this, _MTL_PRIVATE_SEL(computeCommandEncoderWithDispatchType_), dispatchType); } _MTL_INLINE void MTL::CommandBuffer::encodeWait(const MTL::Event* event, uint64_t value) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(encodeWaitForEvent_value_), event, value); } _MTL_INLINE void MTL::CommandBuffer::encodeSignalEvent(const MTL::Event* event, uint64_t value) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(encodeSignalEvent_value_), event, value); } _MTL_INLINE MTL::ParallelRenderCommandEncoder* MTL::CommandBuffer::parallelRenderCommandEncoder(const MTL::RenderPassDescriptor* renderPassDescriptor) { return Object::sendMessage<MTL::ParallelRenderCommandEncoder*>(this, _MTL_PRIVATE_SEL(parallelRenderCommandEncoderWithDescriptor_), renderPassDescriptor); } _MTL_INLINE MTL::ResourceStateCommandEncoder* MTL::CommandBuffer::resourceStateCommandEncoder() { return Object::sendMessage<MTL::ResourceStateCommandEncoder*>(this, _MTL_PRIVATE_SEL(resourceStateCommandEncoder)); } _MTL_INLINE MTL::ResourceStateCommandEncoder* MTL::CommandBuffer::resourceStateCommandEncoder(const MTL::ResourceStatePassDescriptor* resourceStatePassDescriptor) { return Object::sendMessage<MTL::ResourceStateCommandEncoder*>(this, _MTL_PRIVATE_SEL(resourceStateCommandEncoderWithDescriptor_), resourceStatePassDescriptor); } _MTL_INLINE MTL::AccelerationStructureCommandEncoder* MTL::CommandBuffer::accelerationStructureCommandEncoder() { return Object::sendMessage<MTL::AccelerationStructureCommandEncoder*>(this, _MTL_PRIVATE_SEL(accelerationStructureCommandEncoder)); } _MTL_INLINE MTL::AccelerationStructureCommandEncoder* MTL::CommandBuffer::accelerationStructureCommandEncoder(const MTL::AccelerationStructurePassDescriptor* descriptor) { return Object::sendMessage<MTL::AccelerationStructureCommandEncoder*>(this, _MTL_PRIVATE_SEL(accelerationStructureCommandEncoderWithDescriptor_), descriptor); } _MTL_INLINE void MTL::CommandBuffer::pushDebugGroup(const NS::String* string) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(pushDebugGroup_), string); } _MTL_INLINE void MTL::CommandBuffer::popDebugGroup() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(popDebugGroup)); } #pragma once namespace MTL { class CommandQueue : public NS::Referencing<CommandQueue> { public: NS::String* label() const; void setLabel(const NS::String* label); class Device* device() const; class CommandBuffer* commandBuffer(); class CommandBuffer* commandBuffer(const class CommandBufferDescriptor* descriptor); class CommandBuffer* commandBufferWithUnretainedReferences(); void insertDebugCaptureBoundary(); }; } _MTL_INLINE NS::String* MTL::CommandQueue::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::CommandQueue::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE MTL::Device* MTL::CommandQueue::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE MTL::CommandBuffer* MTL::CommandQueue::commandBuffer() { return Object::sendMessage<MTL::CommandBuffer*>(this, _MTL_PRIVATE_SEL(commandBuffer)); } _MTL_INLINE MTL::CommandBuffer* MTL::CommandQueue::commandBuffer(const MTL::CommandBufferDescriptor* descriptor) { return Object::sendMessage<MTL::CommandBuffer*>(this, _MTL_PRIVATE_SEL(commandBufferWithDescriptor_), descriptor); } _MTL_INLINE MTL::CommandBuffer* MTL::CommandQueue::commandBufferWithUnretainedReferences() { return Object::sendMessage<MTL::CommandBuffer*>(this, _MTL_PRIVATE_SEL(commandBufferWithUnretainedReferences)); } _MTL_INLINE void MTL::CommandQueue::insertDebugCaptureBoundary() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(insertDebugCaptureBoundary)); } #pragma once namespace MTL { struct DispatchThreadgroupsIndirectArguments { uint32_t threadgroupsPerGrid[3]; } _MTL_PACKED; struct StageInRegionIndirectArguments { uint32_t stageInOrigin[3]; uint32_t stageInSize[3]; } _MTL_PACKED; class ComputeCommandEncoder : public NS::Referencing<ComputeCommandEncoder, CommandEncoder> { public: MTL::DispatchType dispatchType() const; void setComputePipelineState(const class ComputePipelineState* state); void setBytes(const void* bytes, NS::UInteger length, NS::UInteger index); void setBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index); void setBufferOffset(NS::UInteger offset, NS::UInteger index); void setBuffers(const class Buffer* const buffers[], const NS::UInteger offsets[], NS::Range range); void setBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger stride, NS::UInteger index); void setBuffers(const class Buffer* const buffers[], const NS::UInteger* offsets, const NS::UInteger* strides, NS::Range range); void setBufferOffset(NS::UInteger offset, NS::UInteger stride, NS::UInteger index); void setBytes(const void* bytes, NS::UInteger length, NS::UInteger stride, NS::UInteger index); void setVisibleFunctionTable(const class VisibleFunctionTable* visibleFunctionTable, NS::UInteger bufferIndex); void setVisibleFunctionTables(const class VisibleFunctionTable* const visibleFunctionTables[], NS::Range range); void setIntersectionFunctionTable(const class IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger bufferIndex); void setIntersectionFunctionTables(const class IntersectionFunctionTable* const intersectionFunctionTables[], NS::Range range); void setAccelerationStructure(const class AccelerationStructure* accelerationStructure, NS::UInteger bufferIndex); void setTexture(const class Texture* texture, NS::UInteger index); void setTextures(const class Texture* const textures[], NS::Range range); void setSamplerState(const class SamplerState* sampler, NS::UInteger index); void setSamplerStates(const class SamplerState* const samplers[], NS::Range range); void setSamplerState(const class SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index); void setSamplerStates(const class SamplerState* const samplers[], const float lodMinClamps[], const float lodMaxClamps[], NS::Range range); void setThreadgroupMemoryLength(NS::UInteger length, NS::UInteger index); void setImageblockWidth(NS::UInteger width, NS::UInteger height); void setStageInRegion(MTL::Region region); void setStageInRegion(const class Buffer* indirectBuffer, NS::UInteger indirectBufferOffset); void dispatchThreadgroups(MTL::Size threadgroupsPerGrid, MTL::Size threadsPerThreadgroup); void dispatchThreadgroups(const class Buffer* indirectBuffer, NS::UInteger indirectBufferOffset, MTL::Size threadsPerThreadgroup); void dispatchThreads(MTL::Size threadsPerGrid, MTL::Size threadsPerThreadgroup); void updateFence(const class Fence* fence); void waitForFence(const class Fence* fence); void useResource(const class Resource* resource, MTL::ResourceUsage usage); void useResources(const class Resource* const resources[], NS::UInteger count, MTL::ResourceUsage usage); void useHeap(const class Heap* heap); void useHeaps(const class Heap* const heaps[], NS::UInteger count); void executeCommandsInBuffer(const class IndirectCommandBuffer* indirectCommandBuffer, NS::Range executionRange); void executeCommandsInBuffer(const class IndirectCommandBuffer* indirectCommandbuffer, const class Buffer* indirectRangeBuffer, NS::UInteger indirectBufferOffset); void memoryBarrier(MTL::BarrierScope scope); void memoryBarrier(const class Resource* const resources[], NS::UInteger count); void sampleCountersInBuffer(const class CounterSampleBuffer* sampleBuffer, NS::UInteger sampleIndex, bool barrier); }; } _MTL_INLINE MTL::DispatchType MTL::ComputeCommandEncoder::dispatchType() const { return Object::sendMessage<MTL::DispatchType>(this, _MTL_PRIVATE_SEL(dispatchType)); } _MTL_INLINE void MTL::ComputeCommandEncoder::setComputePipelineState(const MTL::ComputePipelineState* state) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setComputePipelineState_), state); } _MTL_INLINE void MTL::ComputeCommandEncoder::setBytes(const void* bytes, NS::UInteger length, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBytes_length_atIndex_), bytes, length, index); } _MTL_INLINE void MTL::ComputeCommandEncoder::setBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBuffer_offset_atIndex_), buffer, offset, index); } _MTL_INLINE void MTL::ComputeCommandEncoder::setBufferOffset(NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBufferOffset_atIndex_), offset, index); } _MTL_INLINE void MTL::ComputeCommandEncoder::setBuffers(const MTL::Buffer* const buffers[], const NS::UInteger offsets[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBuffers_offsets_withRange_), buffers, offsets, range); } _MTL_INLINE void MTL::ComputeCommandEncoder::setBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger stride, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBuffer_offset_attributeStride_atIndex_), buffer, offset, stride, index); } _MTL_INLINE void MTL::ComputeCommandEncoder::setBuffers(const MTL::Buffer* const buffers[], const NS::UInteger* offsets, const NS::UInteger* strides, NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBuffers_offsets_attributeStrides_withRange_), buffers, offsets, strides, range); } _MTL_INLINE void MTL::ComputeCommandEncoder::setBufferOffset(NS::UInteger offset, NS::UInteger stride, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBufferOffset_attributeStride_atIndex_), offset, stride, index); } _MTL_INLINE void MTL::ComputeCommandEncoder::setBytes(const void* bytes, NS::UInteger length, NS::UInteger stride, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBytes_length_attributeStride_atIndex_), bytes, length, stride, index); } _MTL_INLINE void MTL::ComputeCommandEncoder::setVisibleFunctionTable(const MTL::VisibleFunctionTable* visibleFunctionTable, NS::UInteger bufferIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVisibleFunctionTable_atBufferIndex_), visibleFunctionTable, bufferIndex); } _MTL_INLINE void MTL::ComputeCommandEncoder::setVisibleFunctionTables(const MTL::VisibleFunctionTable* const visibleFunctionTables[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVisibleFunctionTables_withBufferRange_), visibleFunctionTables, range); } _MTL_INLINE void MTL::ComputeCommandEncoder::setIntersectionFunctionTable(const MTL::IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger bufferIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIntersectionFunctionTable_atBufferIndex_), intersectionFunctionTable, bufferIndex); } _MTL_INLINE void MTL::ComputeCommandEncoder::setIntersectionFunctionTables(const MTL::IntersectionFunctionTable* const intersectionFunctionTables[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIntersectionFunctionTables_withBufferRange_), intersectionFunctionTables, range); } _MTL_INLINE void MTL::ComputeCommandEncoder::setAccelerationStructure(const MTL::AccelerationStructure* accelerationStructure, NS::UInteger bufferIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAccelerationStructure_atBufferIndex_), accelerationStructure, bufferIndex); } _MTL_INLINE void MTL::ComputeCommandEncoder::setTexture(const MTL::Texture* texture, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTexture_atIndex_), texture, index); } _MTL_INLINE void MTL::ComputeCommandEncoder::setTextures(const MTL::Texture* const textures[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTextures_withRange_), textures, range); } _MTL_INLINE void MTL::ComputeCommandEncoder::setSamplerState(const MTL::SamplerState* sampler, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSamplerState_atIndex_), sampler, index); } _MTL_INLINE void MTL::ComputeCommandEncoder::setSamplerStates(const MTL::SamplerState* const samplers[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSamplerStates_withRange_), samplers, range); } _MTL_INLINE void MTL::ComputeCommandEncoder::setSamplerState(const MTL::SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSamplerState_lodMinClamp_lodMaxClamp_atIndex_), sampler, lodMinClamp, lodMaxClamp, index); } _MTL_INLINE void MTL::ComputeCommandEncoder::setSamplerStates(const MTL::SamplerState* const samplers[], const float lodMinClamps[], const float lodMaxClamps[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSamplerStates_lodMinClamps_lodMaxClamps_withRange_), samplers, lodMinClamps, lodMaxClamps, range); } _MTL_INLINE void MTL::ComputeCommandEncoder::setThreadgroupMemoryLength(NS::UInteger length, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setThreadgroupMemoryLength_atIndex_), length, index); } _MTL_INLINE void MTL::ComputeCommandEncoder::setImageblockWidth(NS::UInteger width, NS::UInteger height) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setImageblockWidth_height_), width, height); } _MTL_INLINE void MTL::ComputeCommandEncoder::setStageInRegion(MTL::Region region) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStageInRegion_), region); } _MTL_INLINE void MTL::ComputeCommandEncoder::setStageInRegion(const MTL::Buffer* indirectBuffer, NS::UInteger indirectBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStageInRegionWithIndirectBuffer_indirectBufferOffset_), indirectBuffer, indirectBufferOffset); } _MTL_INLINE void MTL::ComputeCommandEncoder::dispatchThreadgroups(MTL::Size threadgroupsPerGrid, MTL::Size threadsPerThreadgroup) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(dispatchThreadgroups_threadsPerThreadgroup_), threadgroupsPerGrid, threadsPerThreadgroup); } _MTL_INLINE void MTL::ComputeCommandEncoder::dispatchThreadgroups(const MTL::Buffer* indirectBuffer, NS::UInteger indirectBufferOffset, MTL::Size threadsPerThreadgroup) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(dispatchThreadgroupsWithIndirectBuffer_indirectBufferOffset_threadsPerThreadgroup_), indirectBuffer, indirectBufferOffset, threadsPerThreadgroup); } _MTL_INLINE void MTL::ComputeCommandEncoder::dispatchThreads(MTL::Size threadsPerGrid, MTL::Size threadsPerThreadgroup) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(dispatchThreads_threadsPerThreadgroup_), threadsPerGrid, threadsPerThreadgroup); } _MTL_INLINE void MTL::ComputeCommandEncoder::updateFence(const MTL::Fence* fence) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(updateFence_), fence); } _MTL_INLINE void MTL::ComputeCommandEncoder::waitForFence(const MTL::Fence* fence) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(waitForFence_), fence); } _MTL_INLINE void MTL::ComputeCommandEncoder::useResource(const MTL::Resource* resource, MTL::ResourceUsage usage) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useResource_usage_), resource, usage); } _MTL_INLINE void MTL::ComputeCommandEncoder::useResources(const MTL::Resource* const resources[], NS::UInteger count, MTL::ResourceUsage usage) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useResources_count_usage_), resources, count, usage); } _MTL_INLINE void MTL::ComputeCommandEncoder::useHeap(const MTL::Heap* heap) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useHeap_), heap); } _MTL_INLINE void MTL::ComputeCommandEncoder::useHeaps(const MTL::Heap* const heaps[], NS::UInteger count) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useHeaps_count_), heaps, count); } _MTL_INLINE void MTL::ComputeCommandEncoder::executeCommandsInBuffer(const MTL::IndirectCommandBuffer* indirectCommandBuffer, NS::Range executionRange) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(executeCommandsInBuffer_withRange_), indirectCommandBuffer, executionRange); } _MTL_INLINE void MTL::ComputeCommandEncoder::executeCommandsInBuffer(const MTL::IndirectCommandBuffer* indirectCommandbuffer, const MTL::Buffer* indirectRangeBuffer, NS::UInteger indirectBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(executeCommandsInBuffer_indirectBuffer_indirectBufferOffset_), indirectCommandbuffer, indirectRangeBuffer, indirectBufferOffset); } _MTL_INLINE void MTL::ComputeCommandEncoder::memoryBarrier(MTL::BarrierScope scope) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(memoryBarrierWithScope_), scope); } _MTL_INLINE void MTL::ComputeCommandEncoder::memoryBarrier(const MTL::Resource* const resources[], NS::UInteger count) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(memoryBarrierWithResources_count_), resources, count); } _MTL_INLINE void MTL::ComputeCommandEncoder::sampleCountersInBuffer(const MTL::CounterSampleBuffer* sampleBuffer, NS::UInteger sampleIndex, bool barrier) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(sampleCountersInBuffer_atSampleIndex_withBarrier_), sampleBuffer, sampleIndex, barrier); } #pragma once namespace MTL { class ComputePassSampleBufferAttachmentDescriptor : public NS::Copying<ComputePassSampleBufferAttachmentDescriptor> { public: static class ComputePassSampleBufferAttachmentDescriptor* alloc(); class ComputePassSampleBufferAttachmentDescriptor* init(); class CounterSampleBuffer* sampleBuffer() const; void setSampleBuffer(const class CounterSampleBuffer* sampleBuffer); NS::UInteger startOfEncoderSampleIndex() const; void setStartOfEncoderSampleIndex(NS::UInteger startOfEncoderSampleIndex); NS::UInteger endOfEncoderSampleIndex() const; void setEndOfEncoderSampleIndex(NS::UInteger endOfEncoderSampleIndex); }; class ComputePassSampleBufferAttachmentDescriptorArray : public NS::Referencing<ComputePassSampleBufferAttachmentDescriptorArray> { public: static class ComputePassSampleBufferAttachmentDescriptorArray* alloc(); class ComputePassSampleBufferAttachmentDescriptorArray* init(); class ComputePassSampleBufferAttachmentDescriptor* object(NS::UInteger attachmentIndex); void setObject(const class ComputePassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex); }; class ComputePassDescriptor : public NS::Copying<ComputePassDescriptor> { public: static class ComputePassDescriptor* alloc(); class ComputePassDescriptor* init(); static class ComputePassDescriptor* computePassDescriptor(); MTL::DispatchType dispatchType() const; void setDispatchType(MTL::DispatchType dispatchType); class ComputePassSampleBufferAttachmentDescriptorArray* sampleBufferAttachments() const; }; } _MTL_INLINE MTL::ComputePassSampleBufferAttachmentDescriptor* MTL::ComputePassSampleBufferAttachmentDescriptor::alloc() { return NS::Object::alloc<MTL::ComputePassSampleBufferAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLComputePassSampleBufferAttachmentDescriptor)); } _MTL_INLINE MTL::ComputePassSampleBufferAttachmentDescriptor* MTL::ComputePassSampleBufferAttachmentDescriptor::init() { return NS::Object::init<MTL::ComputePassSampleBufferAttachmentDescriptor>(); } _MTL_INLINE MTL::CounterSampleBuffer* MTL::ComputePassSampleBufferAttachmentDescriptor::sampleBuffer() const { return Object::sendMessage<MTL::CounterSampleBuffer*>(this, _MTL_PRIVATE_SEL(sampleBuffer)); } _MTL_INLINE void MTL::ComputePassSampleBufferAttachmentDescriptor::setSampleBuffer(const MTL::CounterSampleBuffer* sampleBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSampleBuffer_), sampleBuffer); } _MTL_INLINE NS::UInteger MTL::ComputePassSampleBufferAttachmentDescriptor::startOfEncoderSampleIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(startOfEncoderSampleIndex)); } _MTL_INLINE void MTL::ComputePassSampleBufferAttachmentDescriptor::setStartOfEncoderSampleIndex(NS::UInteger startOfEncoderSampleIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStartOfEncoderSampleIndex_), startOfEncoderSampleIndex); } _MTL_INLINE NS::UInteger MTL::ComputePassSampleBufferAttachmentDescriptor::endOfEncoderSampleIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(endOfEncoderSampleIndex)); } _MTL_INLINE void MTL::ComputePassSampleBufferAttachmentDescriptor::setEndOfEncoderSampleIndex(NS::UInteger endOfEncoderSampleIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setEndOfEncoderSampleIndex_), endOfEncoderSampleIndex); } _MTL_INLINE MTL::ComputePassSampleBufferAttachmentDescriptorArray* MTL::ComputePassSampleBufferAttachmentDescriptorArray::alloc() { return NS::Object::alloc<MTL::ComputePassSampleBufferAttachmentDescriptorArray>(_MTL_PRIVATE_CLS(MTLComputePassSampleBufferAttachmentDescriptorArray)); } _MTL_INLINE MTL::ComputePassSampleBufferAttachmentDescriptorArray* MTL::ComputePassSampleBufferAttachmentDescriptorArray::init() { return NS::Object::init<MTL::ComputePassSampleBufferAttachmentDescriptorArray>(); } _MTL_INLINE MTL::ComputePassSampleBufferAttachmentDescriptor* MTL::ComputePassSampleBufferAttachmentDescriptorArray::object(NS::UInteger attachmentIndex) { return Object::sendMessage<MTL::ComputePassSampleBufferAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), attachmentIndex); } _MTL_INLINE void MTL::ComputePassSampleBufferAttachmentDescriptorArray::setObject(const MTL::ComputePassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attachment, attachmentIndex); } _MTL_INLINE MTL::ComputePassDescriptor* MTL::ComputePassDescriptor::alloc() { return NS::Object::alloc<MTL::ComputePassDescriptor>(_MTL_PRIVATE_CLS(MTLComputePassDescriptor)); } _MTL_INLINE MTL::ComputePassDescriptor* MTL::ComputePassDescriptor::init() { return NS::Object::init<MTL::ComputePassDescriptor>(); } _MTL_INLINE MTL::ComputePassDescriptor* MTL::ComputePassDescriptor::computePassDescriptor() { return Object::sendMessage<MTL::ComputePassDescriptor*>(_MTL_PRIVATE_CLS(MTLComputePassDescriptor), _MTL_PRIVATE_SEL(computePassDescriptor)); } _MTL_INLINE MTL::DispatchType MTL::ComputePassDescriptor::dispatchType() const { return Object::sendMessage<MTL::DispatchType>(this, _MTL_PRIVATE_SEL(dispatchType)); } _MTL_INLINE void MTL::ComputePassDescriptor::setDispatchType(MTL::DispatchType dispatchType) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDispatchType_), dispatchType); } _MTL_INLINE MTL::ComputePassSampleBufferAttachmentDescriptorArray* MTL::ComputePassDescriptor::sampleBufferAttachments() const { return Object::sendMessage<MTL::ComputePassSampleBufferAttachmentDescriptorArray*>(this, _MTL_PRIVATE_SEL(sampleBufferAttachments)); } #pragma once namespace MTL { class ComputePipelineReflection : public NS::Referencing<ComputePipelineReflection> { public: static class ComputePipelineReflection* alloc(); class ComputePipelineReflection* init(); NS::Array* bindings() const; NS::Array* arguments() const; }; class ComputePipelineDescriptor : public NS::Copying<ComputePipelineDescriptor> { public: static class ComputePipelineDescriptor* alloc(); class ComputePipelineDescriptor* init(); NS::String* label() const; void setLabel(const NS::String* label); class Function* computeFunction() const; void setComputeFunction(const class Function* computeFunction); bool threadGroupSizeIsMultipleOfThreadExecutionWidth() const; void setThreadGroupSizeIsMultipleOfThreadExecutionWidth(bool threadGroupSizeIsMultipleOfThreadExecutionWidth); NS::UInteger maxTotalThreadsPerThreadgroup() const; void setMaxTotalThreadsPerThreadgroup(NS::UInteger maxTotalThreadsPerThreadgroup); class StageInputOutputDescriptor* stageInputDescriptor() const; void setStageInputDescriptor(const class StageInputOutputDescriptor* stageInputDescriptor); class PipelineBufferDescriptorArray* buffers() const; bool supportIndirectCommandBuffers() const; void setSupportIndirectCommandBuffers(bool supportIndirectCommandBuffers); NS::Array* insertLibraries() const; void setInsertLibraries(const NS::Array* insertLibraries); NS::Array* preloadedLibraries() const; void setPreloadedLibraries(const NS::Array* preloadedLibraries); NS::Array* binaryArchives() const; void setBinaryArchives(const NS::Array* binaryArchives); void reset(); class LinkedFunctions* linkedFunctions() const; void setLinkedFunctions(const class LinkedFunctions* linkedFunctions); bool supportAddingBinaryFunctions() const; void setSupportAddingBinaryFunctions(bool supportAddingBinaryFunctions); NS::UInteger maxCallStackDepth() const; void setMaxCallStackDepth(NS::UInteger maxCallStackDepth); }; class ComputePipelineState : public NS::Referencing<ComputePipelineState> { public: NS::String* label() const; class Device* device() const; NS::UInteger maxTotalThreadsPerThreadgroup() const; NS::UInteger threadExecutionWidth() const; NS::UInteger staticThreadgroupMemoryLength() const; NS::UInteger imageblockMemoryLength(MTL::Size imageblockDimensions); bool supportIndirectCommandBuffers() const; MTL::ResourceID gpuResourceID() const; class FunctionHandle* functionHandle(const class Function* function); class ComputePipelineState* newComputePipelineState(const NS::Array* functions, NS::Error** error); class VisibleFunctionTable* newVisibleFunctionTable(const class VisibleFunctionTableDescriptor* descriptor); class IntersectionFunctionTable* newIntersectionFunctionTable(const class IntersectionFunctionTableDescriptor* descriptor); }; } _MTL_INLINE MTL::ComputePipelineReflection* MTL::ComputePipelineReflection::alloc() { return NS::Object::alloc<MTL::ComputePipelineReflection>(_MTL_PRIVATE_CLS(MTLComputePipelineReflection)); } _MTL_INLINE MTL::ComputePipelineReflection* MTL::ComputePipelineReflection::init() { return NS::Object::init<MTL::ComputePipelineReflection>(); } _MTL_INLINE NS::Array* MTL::ComputePipelineReflection::bindings() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(bindings)); } _MTL_INLINE NS::Array* MTL::ComputePipelineReflection::arguments() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(arguments)); } _MTL_INLINE MTL::ComputePipelineDescriptor* MTL::ComputePipelineDescriptor::alloc() { return NS::Object::alloc<MTL::ComputePipelineDescriptor>(_MTL_PRIVATE_CLS(MTLComputePipelineDescriptor)); } _MTL_INLINE MTL::ComputePipelineDescriptor* MTL::ComputePipelineDescriptor::init() { return NS::Object::init<MTL::ComputePipelineDescriptor>(); } _MTL_INLINE NS::String* MTL::ComputePipelineDescriptor::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::ComputePipelineDescriptor::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE MTL::Function* MTL::ComputePipelineDescriptor::computeFunction() const { return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(computeFunction)); } _MTL_INLINE void MTL::ComputePipelineDescriptor::setComputeFunction(const MTL::Function* computeFunction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setComputeFunction_), computeFunction); } _MTL_INLINE bool MTL::ComputePipelineDescriptor::threadGroupSizeIsMultipleOfThreadExecutionWidth() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(threadGroupSizeIsMultipleOfThreadExecutionWidth)); } _MTL_INLINE void MTL::ComputePipelineDescriptor::setThreadGroupSizeIsMultipleOfThreadExecutionWidth(bool threadGroupSizeIsMultipleOfThreadExecutionWidth) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setThreadGroupSizeIsMultipleOfThreadExecutionWidth_), threadGroupSizeIsMultipleOfThreadExecutionWidth); } _MTL_INLINE NS::UInteger MTL::ComputePipelineDescriptor::maxTotalThreadsPerThreadgroup() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxTotalThreadsPerThreadgroup)); } _MTL_INLINE void MTL::ComputePipelineDescriptor::setMaxTotalThreadsPerThreadgroup(NS::UInteger maxTotalThreadsPerThreadgroup) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxTotalThreadsPerThreadgroup_), maxTotalThreadsPerThreadgroup); } _MTL_INLINE MTL::StageInputOutputDescriptor* MTL::ComputePipelineDescriptor::stageInputDescriptor() const { return Object::sendMessage<MTL::StageInputOutputDescriptor*>(this, _MTL_PRIVATE_SEL(stageInputDescriptor)); } _MTL_INLINE void MTL::ComputePipelineDescriptor::setStageInputDescriptor(const MTL::StageInputOutputDescriptor* stageInputDescriptor) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStageInputDescriptor_), stageInputDescriptor); } _MTL_INLINE MTL::PipelineBufferDescriptorArray* MTL::ComputePipelineDescriptor::buffers() const { return Object::sendMessage<MTL::PipelineBufferDescriptorArray*>(this, _MTL_PRIVATE_SEL(buffers)); } _MTL_INLINE bool MTL::ComputePipelineDescriptor::supportIndirectCommandBuffers() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportIndirectCommandBuffers)); } _MTL_INLINE void MTL::ComputePipelineDescriptor::setSupportIndirectCommandBuffers(bool supportIndirectCommandBuffers) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSupportIndirectCommandBuffers_), supportIndirectCommandBuffers); } _MTL_INLINE NS::Array* MTL::ComputePipelineDescriptor::insertLibraries() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(insertLibraries)); } _MTL_INLINE void MTL::ComputePipelineDescriptor::setInsertLibraries(const NS::Array* insertLibraries) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInsertLibraries_), insertLibraries); } _MTL_INLINE NS::Array* MTL::ComputePipelineDescriptor::preloadedLibraries() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(preloadedLibraries)); } _MTL_INLINE void MTL::ComputePipelineDescriptor::setPreloadedLibraries(const NS::Array* preloadedLibraries) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPreloadedLibraries_), preloadedLibraries); } _MTL_INLINE NS::Array* MTL::ComputePipelineDescriptor::binaryArchives() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(binaryArchives)); } _MTL_INLINE void MTL::ComputePipelineDescriptor::setBinaryArchives(const NS::Array* binaryArchives) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBinaryArchives_), binaryArchives); } _MTL_INLINE void MTL::ComputePipelineDescriptor::reset() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(reset)); } _MTL_INLINE MTL::LinkedFunctions* MTL::ComputePipelineDescriptor::linkedFunctions() const { return Object::sendMessage<MTL::LinkedFunctions*>(this, _MTL_PRIVATE_SEL(linkedFunctions)); } _MTL_INLINE void MTL::ComputePipelineDescriptor::setLinkedFunctions(const MTL::LinkedFunctions* linkedFunctions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLinkedFunctions_), linkedFunctions); } _MTL_INLINE bool MTL::ComputePipelineDescriptor::supportAddingBinaryFunctions() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportAddingBinaryFunctions)); } _MTL_INLINE void MTL::ComputePipelineDescriptor::setSupportAddingBinaryFunctions(bool supportAddingBinaryFunctions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSupportAddingBinaryFunctions_), supportAddingBinaryFunctions); } _MTL_INLINE NS::UInteger MTL::ComputePipelineDescriptor::maxCallStackDepth() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxCallStackDepth)); } _MTL_INLINE void MTL::ComputePipelineDescriptor::setMaxCallStackDepth(NS::UInteger maxCallStackDepth) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxCallStackDepth_), maxCallStackDepth); } _MTL_INLINE NS::String* MTL::ComputePipelineState::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE MTL::Device* MTL::ComputePipelineState::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE NS::UInteger MTL::ComputePipelineState::maxTotalThreadsPerThreadgroup() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxTotalThreadsPerThreadgroup)); } _MTL_INLINE NS::UInteger MTL::ComputePipelineState::threadExecutionWidth() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(threadExecutionWidth)); } _MTL_INLINE NS::UInteger MTL::ComputePipelineState::staticThreadgroupMemoryLength() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(staticThreadgroupMemoryLength)); } _MTL_INLINE NS::UInteger MTL::ComputePipelineState::imageblockMemoryLength(MTL::Size imageblockDimensions) { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(imageblockMemoryLengthForDimensions_), imageblockDimensions); } _MTL_INLINE bool MTL::ComputePipelineState::supportIndirectCommandBuffers() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportIndirectCommandBuffers)); } _MTL_INLINE MTL::ResourceID MTL::ComputePipelineState::gpuResourceID() const { return Object::sendMessage<MTL::ResourceID>(this, _MTL_PRIVATE_SEL(gpuResourceID)); } _MTL_INLINE MTL::FunctionHandle* MTL::ComputePipelineState::functionHandle(const MTL::Function* function) { return Object::sendMessage<MTL::FunctionHandle*>(this, _MTL_PRIVATE_SEL(functionHandleWithFunction_), function); } _MTL_INLINE MTL::ComputePipelineState* MTL::ComputePipelineState::newComputePipelineState(const NS::Array* functions, NS::Error** error) { return Object::sendMessage<MTL::ComputePipelineState*>(this, _MTL_PRIVATE_SEL(newComputePipelineStateWithAdditionalBinaryFunctions_error_), functions, error); } _MTL_INLINE MTL::VisibleFunctionTable* MTL::ComputePipelineState::newVisibleFunctionTable(const MTL::VisibleFunctionTableDescriptor* descriptor) { return Object::sendMessage<MTL::VisibleFunctionTable*>(this, _MTL_PRIVATE_SEL(newVisibleFunctionTableWithDescriptor_), descriptor); } _MTL_INLINE MTL::IntersectionFunctionTable* MTL::ComputePipelineState::newIntersectionFunctionTable(const MTL::IntersectionFunctionTableDescriptor* descriptor) { return Object::sendMessage<MTL::IntersectionFunctionTable*>(this, _MTL_PRIVATE_SEL(newIntersectionFunctionTableWithDescriptor_), descriptor); } #pragma once namespace MTL { struct CounterResultTimestamp { uint64_t timestamp; } _MTL_PACKED; struct CounterResultStageUtilization { uint64_t totalCycles; uint64_t vertexCycles; uint64_t tessellationCycles; uint64_t postTessellationVertexCycles; uint64_t fragmentCycles; uint64_t renderTargetCycles; } _MTL_PACKED; struct CounterResultStatistic { uint64_t tessellationInputPatches; uint64_t vertexInvocations; uint64_t postTessellationVertexInvocations; uint64_t clipperInvocations; uint64_t clipperPrimitivesOut; uint64_t fragmentInvocations; uint64_t fragmentsPassed; uint64_t computeKernelInvocations; } _MTL_PACKED; _MTL_CONST(NS::ErrorDomain, CounterErrorDomain); using CommonCounter = NS::String*; _MTL_CONST(CommonCounter, CommonCounterTimestamp); _MTL_CONST(CommonCounter, CommonCounterTessellationInputPatches); _MTL_CONST(CommonCounter, CommonCounterVertexInvocations); _MTL_CONST(CommonCounter, CommonCounterPostTessellationVertexInvocations); _MTL_CONST(CommonCounter, CommonCounterClipperInvocations); _MTL_CONST(CommonCounter, CommonCounterClipperPrimitivesOut); _MTL_CONST(CommonCounter, CommonCounterFragmentInvocations); _MTL_CONST(CommonCounter, CommonCounterFragmentsPassed); _MTL_CONST(CommonCounter, CommonCounterComputeKernelInvocations); _MTL_CONST(CommonCounter, CommonCounterTotalCycles); _MTL_CONST(CommonCounter, CommonCounterVertexCycles); _MTL_CONST(CommonCounter, CommonCounterTessellationCycles); _MTL_CONST(CommonCounter, CommonCounterPostTessellationVertexCycles); _MTL_CONST(CommonCounter, CommonCounterFragmentCycles); _MTL_CONST(CommonCounter, CommonCounterRenderTargetWriteCycles); using CommonCounterSet = NS::String*; _MTL_CONST(CommonCounterSet, CommonCounterSetTimestamp); _MTL_CONST(CommonCounterSet, CommonCounterSetStageUtilization); _MTL_CONST(CommonCounterSet, CommonCounterSetStatistic); class Counter : public NS::Referencing<Counter> { public: NS::String* name() const; }; class CounterSet : public NS::Referencing<CounterSet> { public: NS::String* name() const; NS::Array* counters() const; }; class CounterSampleBufferDescriptor : public NS::Copying<CounterSampleBufferDescriptor> { public: static class CounterSampleBufferDescriptor* alloc(); class CounterSampleBufferDescriptor* init(); class CounterSet* counterSet() const; void setCounterSet(const class CounterSet* counterSet); NS::String* label() const; void setLabel(const NS::String* label); MTL::StorageMode storageMode() const; void setStorageMode(MTL::StorageMode storageMode); NS::UInteger sampleCount() const; void setSampleCount(NS::UInteger sampleCount); }; class CounterSampleBuffer : public NS::Referencing<CounterSampleBuffer> { public: class Device* device() const; NS::String* label() const; NS::UInteger sampleCount() const; NS::Data* resolveCounterRange(NS::Range range); }; _MTL_ENUM(NS::Integer, CounterSampleBufferError) { CounterSampleBufferErrorOutOfMemory = 0, CounterSampleBufferErrorInvalid = 1, CounterSampleBufferErrorInternal = 2, }; } _MTL_PRIVATE_DEF_STR(NS::ErrorDomain, CounterErrorDomain); _MTL_PRIVATE_DEF_STR(MTL::CommonCounter, CommonCounterTimestamp); _MTL_PRIVATE_DEF_STR(MTL::CommonCounter, CommonCounterTessellationInputPatches); _MTL_PRIVATE_DEF_STR(MTL::CommonCounter, CommonCounterVertexInvocations); _MTL_PRIVATE_DEF_STR(MTL::CommonCounter, CommonCounterPostTessellationVertexInvocations); _MTL_PRIVATE_DEF_STR(MTL::CommonCounter, CommonCounterClipperInvocations); _MTL_PRIVATE_DEF_STR(MTL::CommonCounter, CommonCounterClipperPrimitivesOut); _MTL_PRIVATE_DEF_STR(MTL::CommonCounter, CommonCounterFragmentInvocations); _MTL_PRIVATE_DEF_STR(MTL::CommonCounter, CommonCounterFragmentsPassed); _MTL_PRIVATE_DEF_STR(MTL::CommonCounter, CommonCounterComputeKernelInvocations); _MTL_PRIVATE_DEF_STR(MTL::CommonCounter, CommonCounterTotalCycles); _MTL_PRIVATE_DEF_STR(MTL::CommonCounter, CommonCounterVertexCycles); _MTL_PRIVATE_DEF_STR(MTL::CommonCounter, CommonCounterTessellationCycles); _MTL_PRIVATE_DEF_STR(MTL::CommonCounter, CommonCounterPostTessellationVertexCycles); _MTL_PRIVATE_DEF_STR(MTL::CommonCounter, CommonCounterFragmentCycles); _MTL_PRIVATE_DEF_STR(MTL::CommonCounter, CommonCounterRenderTargetWriteCycles); _MTL_PRIVATE_DEF_STR(MTL::CommonCounterSet, CommonCounterSetTimestamp); _MTL_PRIVATE_DEF_STR(MTL::CommonCounterSet, CommonCounterSetStageUtilization); _MTL_PRIVATE_DEF_STR(MTL::CommonCounterSet, CommonCounterSetStatistic); _MTL_INLINE NS::String* MTL::Counter::name() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name)); } _MTL_INLINE NS::String* MTL::CounterSet::name() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name)); } _MTL_INLINE NS::Array* MTL::CounterSet::counters() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(counters)); } _MTL_INLINE MTL::CounterSampleBufferDescriptor* MTL::CounterSampleBufferDescriptor::alloc() { return NS::Object::alloc<MTL::CounterSampleBufferDescriptor>(_MTL_PRIVATE_CLS(MTLCounterSampleBufferDescriptor)); } _MTL_INLINE MTL::CounterSampleBufferDescriptor* MTL::CounterSampleBufferDescriptor::init() { return NS::Object::init<MTL::CounterSampleBufferDescriptor>(); } _MTL_INLINE MTL::CounterSet* MTL::CounterSampleBufferDescriptor::counterSet() const { return Object::sendMessage<MTL::CounterSet*>(this, _MTL_PRIVATE_SEL(counterSet)); } _MTL_INLINE void MTL::CounterSampleBufferDescriptor::setCounterSet(const MTL::CounterSet* counterSet) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCounterSet_), counterSet); } _MTL_INLINE NS::String* MTL::CounterSampleBufferDescriptor::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::CounterSampleBufferDescriptor::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE MTL::StorageMode MTL::CounterSampleBufferDescriptor::storageMode() const { return Object::sendMessage<MTL::StorageMode>(this, _MTL_PRIVATE_SEL(storageMode)); } _MTL_INLINE void MTL::CounterSampleBufferDescriptor::setStorageMode(MTL::StorageMode storageMode) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStorageMode_), storageMode); } _MTL_INLINE NS::UInteger MTL::CounterSampleBufferDescriptor::sampleCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(sampleCount)); } _MTL_INLINE void MTL::CounterSampleBufferDescriptor::setSampleCount(NS::UInteger sampleCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSampleCount_), sampleCount); } _MTL_INLINE MTL::Device* MTL::CounterSampleBuffer::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE NS::String* MTL::CounterSampleBuffer::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE NS::UInteger MTL::CounterSampleBuffer::sampleCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(sampleCount)); } _MTL_INLINE NS::Data* MTL::CounterSampleBuffer::resolveCounterRange(NS::Range range) { return Object::sendMessage<NS::Data*>(this, _MTL_PRIVATE_SEL(resolveCounterRange_), range); } #pragma once namespace MTL { _MTL_ENUM(NS::UInteger, CompareFunction) { CompareFunctionNever = 0, CompareFunctionLess = 1, CompareFunctionEqual = 2, CompareFunctionLessEqual = 3, CompareFunctionGreater = 4, CompareFunctionNotEqual = 5, CompareFunctionGreaterEqual = 6, CompareFunctionAlways = 7, }; _MTL_ENUM(NS::UInteger, StencilOperation) { StencilOperationKeep = 0, StencilOperationZero = 1, StencilOperationReplace = 2, StencilOperationIncrementClamp = 3, StencilOperationDecrementClamp = 4, StencilOperationInvert = 5, StencilOperationIncrementWrap = 6, StencilOperationDecrementWrap = 7, }; class StencilDescriptor : public NS::Copying<StencilDescriptor> { public: static class StencilDescriptor* alloc(); class StencilDescriptor* init(); MTL::CompareFunction stencilCompareFunction() const; void setStencilCompareFunction(MTL::CompareFunction stencilCompareFunction); MTL::StencilOperation stencilFailureOperation() const; void setStencilFailureOperation(MTL::StencilOperation stencilFailureOperation); MTL::StencilOperation depthFailureOperation() const; void setDepthFailureOperation(MTL::StencilOperation depthFailureOperation); MTL::StencilOperation depthStencilPassOperation() const; void setDepthStencilPassOperation(MTL::StencilOperation depthStencilPassOperation); uint32_t readMask() const; void setReadMask(uint32_t readMask); uint32_t writeMask() const; void setWriteMask(uint32_t writeMask); }; class DepthStencilDescriptor : public NS::Copying<DepthStencilDescriptor> { public: static class DepthStencilDescriptor* alloc(); class DepthStencilDescriptor* init(); MTL::CompareFunction depthCompareFunction() const; void setDepthCompareFunction(MTL::CompareFunction depthCompareFunction); bool depthWriteEnabled() const; void setDepthWriteEnabled(bool depthWriteEnabled); class StencilDescriptor* frontFaceStencil() const; void setFrontFaceStencil(const class StencilDescriptor* frontFaceStencil); class StencilDescriptor* backFaceStencil() const; void setBackFaceStencil(const class StencilDescriptor* backFaceStencil); NS::String* label() const; void setLabel(const NS::String* label); }; class DepthStencilState : public NS::Referencing<DepthStencilState> { public: NS::String* label() const; class Device* device() const; }; } _MTL_INLINE MTL::StencilDescriptor* MTL::StencilDescriptor::alloc() { return NS::Object::alloc<MTL::StencilDescriptor>(_MTL_PRIVATE_CLS(MTLStencilDescriptor)); } _MTL_INLINE MTL::StencilDescriptor* MTL::StencilDescriptor::init() { return NS::Object::init<MTL::StencilDescriptor>(); } _MTL_INLINE MTL::CompareFunction MTL::StencilDescriptor::stencilCompareFunction() const { return Object::sendMessage<MTL::CompareFunction>(this, _MTL_PRIVATE_SEL(stencilCompareFunction)); } _MTL_INLINE void MTL::StencilDescriptor::setStencilCompareFunction(MTL::CompareFunction stencilCompareFunction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilCompareFunction_), stencilCompareFunction); } _MTL_INLINE MTL::StencilOperation MTL::StencilDescriptor::stencilFailureOperation() const { return Object::sendMessage<MTL::StencilOperation>(this, _MTL_PRIVATE_SEL(stencilFailureOperation)); } _MTL_INLINE void MTL::StencilDescriptor::setStencilFailureOperation(MTL::StencilOperation stencilFailureOperation) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilFailureOperation_), stencilFailureOperation); } _MTL_INLINE MTL::StencilOperation MTL::StencilDescriptor::depthFailureOperation() const { return Object::sendMessage<MTL::StencilOperation>(this, _MTL_PRIVATE_SEL(depthFailureOperation)); } _MTL_INLINE void MTL::StencilDescriptor::setDepthFailureOperation(MTL::StencilOperation depthFailureOperation) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthFailureOperation_), depthFailureOperation); } _MTL_INLINE MTL::StencilOperation MTL::StencilDescriptor::depthStencilPassOperation() const { return Object::sendMessage<MTL::StencilOperation>(this, _MTL_PRIVATE_SEL(depthStencilPassOperation)); } _MTL_INLINE void MTL::StencilDescriptor::setDepthStencilPassOperation(MTL::StencilOperation depthStencilPassOperation) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthStencilPassOperation_), depthStencilPassOperation); } _MTL_INLINE uint32_t MTL::StencilDescriptor::readMask() const { return Object::sendMessage<uint32_t>(this, _MTL_PRIVATE_SEL(readMask)); } _MTL_INLINE void MTL::StencilDescriptor::setReadMask(uint32_t readMask) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setReadMask_), readMask); } _MTL_INLINE uint32_t MTL::StencilDescriptor::writeMask() const { return Object::sendMessage<uint32_t>(this, _MTL_PRIVATE_SEL(writeMask)); } _MTL_INLINE void MTL::StencilDescriptor::setWriteMask(uint32_t writeMask) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setWriteMask_), writeMask); } _MTL_INLINE MTL::DepthStencilDescriptor* MTL::DepthStencilDescriptor::alloc() { return NS::Object::alloc<MTL::DepthStencilDescriptor>(_MTL_PRIVATE_CLS(MTLDepthStencilDescriptor)); } _MTL_INLINE MTL::DepthStencilDescriptor* MTL::DepthStencilDescriptor::init() { return NS::Object::init<MTL::DepthStencilDescriptor>(); } _MTL_INLINE MTL::CompareFunction MTL::DepthStencilDescriptor::depthCompareFunction() const { return Object::sendMessage<MTL::CompareFunction>(this, _MTL_PRIVATE_SEL(depthCompareFunction)); } _MTL_INLINE void MTL::DepthStencilDescriptor::setDepthCompareFunction(MTL::CompareFunction depthCompareFunction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthCompareFunction_), depthCompareFunction); } _MTL_INLINE bool MTL::DepthStencilDescriptor::depthWriteEnabled() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isDepthWriteEnabled)); } _MTL_INLINE void MTL::DepthStencilDescriptor::setDepthWriteEnabled(bool depthWriteEnabled) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthWriteEnabled_), depthWriteEnabled); } _MTL_INLINE MTL::StencilDescriptor* MTL::DepthStencilDescriptor::frontFaceStencil() const { return Object::sendMessage<MTL::StencilDescriptor*>(this, _MTL_PRIVATE_SEL(frontFaceStencil)); } _MTL_INLINE void MTL::DepthStencilDescriptor::setFrontFaceStencil(const MTL::StencilDescriptor* frontFaceStencil) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFrontFaceStencil_), frontFaceStencil); } _MTL_INLINE MTL::StencilDescriptor* MTL::DepthStencilDescriptor::backFaceStencil() const { return Object::sendMessage<MTL::StencilDescriptor*>(this, _MTL_PRIVATE_SEL(backFaceStencil)); } _MTL_INLINE void MTL::DepthStencilDescriptor::setBackFaceStencil(const MTL::StencilDescriptor* backFaceStencil) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBackFaceStencil_), backFaceStencil); } _MTL_INLINE NS::String* MTL::DepthStencilDescriptor::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::DepthStencilDescriptor::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE NS::String* MTL::DepthStencilState::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE MTL::Device* MTL::DepthStencilState::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } #pragma once #include <IOSurface/IOSurfaceRef.h> #include <functional> namespace MTL { _MTL_ENUM(NS::Integer, IOCompressionMethod) { IOCompressionMethodZlib = 0, IOCompressionMethodLZFSE = 1, IOCompressionMethodLZ4 = 2, IOCompressionMethodLZMA = 3, IOCompressionMethodLZBitmap = 4, }; _MTL_ENUM(NS::UInteger, FeatureSet) { FeatureSet_iOS_GPUFamily1_v1 = 0, FeatureSet_iOS_GPUFamily2_v1 = 1, FeatureSet_iOS_GPUFamily1_v2 = 2, FeatureSet_iOS_GPUFamily2_v2 = 3, FeatureSet_iOS_GPUFamily3_v1 = 4, FeatureSet_iOS_GPUFamily1_v3 = 5, FeatureSet_iOS_GPUFamily2_v3 = 6, FeatureSet_iOS_GPUFamily3_v2 = 7, FeatureSet_iOS_GPUFamily1_v4 = 8, FeatureSet_iOS_GPUFamily2_v4 = 9, FeatureSet_iOS_GPUFamily3_v3 = 10, FeatureSet_iOS_GPUFamily4_v1 = 11, FeatureSet_iOS_GPUFamily1_v5 = 12, FeatureSet_iOS_GPUFamily2_v5 = 13, FeatureSet_iOS_GPUFamily3_v4 = 14, FeatureSet_iOS_GPUFamily4_v2 = 15, FeatureSet_iOS_GPUFamily5_v1 = 16, FeatureSet_macOS_GPUFamily1_v1 = 10000, FeatureSet_OSX_GPUFamily1_v1 = 10000, FeatureSet_macOS_GPUFamily1_v2 = 10001, FeatureSet_OSX_GPUFamily1_v2 = 10001, FeatureSet_macOS_ReadWriteTextureTier2 = 10002, FeatureSet_OSX_ReadWriteTextureTier2 = 10002, FeatureSet_macOS_GPUFamily1_v3 = 10003, FeatureSet_macOS_GPUFamily1_v4 = 10004, FeatureSet_macOS_GPUFamily2_v1 = 10005, FeatureSet_watchOS_GPUFamily1_v1 = 20000, FeatureSet_WatchOS_GPUFamily1_v1 = 20000, FeatureSet_watchOS_GPUFamily2_v1 = 20001, FeatureSet_WatchOS_GPUFamily2_v1 = 20001, FeatureSet_tvOS_GPUFamily1_v1 = 30000, FeatureSet_TVOS_GPUFamily1_v1 = 30000, FeatureSet_tvOS_GPUFamily1_v2 = 30001, FeatureSet_tvOS_GPUFamily1_v3 = 30002, FeatureSet_tvOS_GPUFamily2_v1 = 30003, FeatureSet_tvOS_GPUFamily1_v4 = 30004, FeatureSet_tvOS_GPUFamily2_v2 = 30005, }; _MTL_ENUM(NS::Integer, GPUFamily) { GPUFamilyApple1 = 1001, GPUFamilyApple2 = 1002, GPUFamilyApple3 = 1003, GPUFamilyApple4 = 1004, GPUFamilyApple5 = 1005, GPUFamilyApple6 = 1006, GPUFamilyApple7 = 1007, GPUFamilyApple8 = 1008, GPUFamilyApple9 = 1009, GPUFamilyMac1 = 2001, GPUFamilyMac2 = 2002, GPUFamilyCommon1 = 3001, GPUFamilyCommon2 = 3002, GPUFamilyCommon3 = 3003, GPUFamilyMacCatalyst1 = 4001, GPUFamilyMacCatalyst2 = 4002, GPUFamilyMetal3 = 5001, }; _MTL_ENUM(NS::UInteger, DeviceLocation) { DeviceLocationBuiltIn = 0, DeviceLocationSlot = 1, DeviceLocationExternal = 2, DeviceLocationUnspecified = NS::UIntegerMax, }; _MTL_OPTIONS(NS::UInteger, PipelineOption) { PipelineOptionNone = 0, PipelineOptionArgumentInfo = 1, PipelineOptionBufferTypeInfo = 2, PipelineOptionFailOnBinaryArchiveMiss = 4, }; _MTL_ENUM(NS::UInteger, ReadWriteTextureTier) { ReadWriteTextureTierNone = 0, ReadWriteTextureTier1 = 1, ReadWriteTextureTier2 = 2, }; _MTL_ENUM(NS::UInteger, ArgumentBuffersTier) { ArgumentBuffersTier1 = 0, ArgumentBuffersTier2 = 1, }; _MTL_ENUM(NS::UInteger, SparseTextureRegionAlignmentMode) { SparseTextureRegionAlignmentModeOutward = 0, SparseTextureRegionAlignmentModeInward = 1, }; _MTL_ENUM(NS::Integer, SparsePageSize) { SparsePageSize16 = 101, SparsePageSize64 = 102, SparsePageSize256 = 103, }; struct AccelerationStructureSizes { NS::UInteger accelerationStructureSize; NS::UInteger buildScratchBufferSize; NS::UInteger refitScratchBufferSize; } _MTL_PACKED; _MTL_ENUM(NS::UInteger, CounterSamplingPoint) { CounterSamplingPointAtStageBoundary = 0, CounterSamplingPointAtDrawBoundary = 1, CounterSamplingPointAtDispatchBoundary = 2, CounterSamplingPointAtTileDispatchBoundary = 3, CounterSamplingPointAtBlitBoundary = 4, }; struct SizeAndAlign { NS::UInteger size; NS::UInteger align; } _MTL_PACKED; class ArgumentDescriptor : public NS::Copying<ArgumentDescriptor> { public: static class ArgumentDescriptor* alloc(); class ArgumentDescriptor* init(); static class ArgumentDescriptor* argumentDescriptor(); MTL::DataType dataType() const; void setDataType(MTL::DataType dataType); NS::UInteger index() const; void setIndex(NS::UInteger index); NS::UInteger arrayLength() const; void setArrayLength(NS::UInteger arrayLength); MTL::BindingAccess access() const; void setAccess(MTL::BindingAccess access); MTL::TextureType textureType() const; void setTextureType(MTL::TextureType textureType); NS::UInteger constantBlockAlignment() const; void setConstantBlockAlignment(NS::UInteger constantBlockAlignment); }; class Architecture : public NS::Copying<Architecture> { public: static class Architecture* alloc(); class Architecture* init(); NS::String* name() const; }; using DeviceNotificationName = NS::String*; _MTL_CONST(DeviceNotificationName, DeviceWasAddedNotification); _MTL_CONST(DeviceNotificationName, DeviceRemovalRequestedNotification); _MTL_CONST(DeviceNotificationName, DeviceWasRemovedNotification); _MTL_CONST(NS::ErrorUserInfoKey, CommandBufferEncoderInfoErrorKey); using DeviceNotificationHandlerBlock = void (^)(class Device* pDevice, DeviceNotificationName notifyName); using DeviceNotificationHandlerFunction = std::function<void(class Device* pDevice, DeviceNotificationName notifyName)>; using AutoreleasedComputePipelineReflection = class ComputePipelineReflection*; using AutoreleasedRenderPipelineReflection = class RenderPipelineReflection*; using NewLibraryCompletionHandler = void (^)(class Library*, NS::Error*); using NewLibraryCompletionHandlerFunction = std::function<void(class Library*, NS::Error*)>; using NewRenderPipelineStateCompletionHandler = void (^)(class RenderPipelineState*, NS::Error*); using NewRenderPipelineStateCompletionHandlerFunction = std::function<void(class RenderPipelineState*, NS::Error*)>; using NewRenderPipelineStateWithReflectionCompletionHandler = void (^)(class RenderPipelineState*, class RenderPipelineReflection*, NS::Error*); using NewRenderPipelineStateWithReflectionCompletionHandlerFunction = std::function<void(class RenderPipelineState*, class RenderPipelineReflection*, NS::Error*)>; using NewComputePipelineStateCompletionHandler = void (^)(class ComputePipelineState*, NS::Error*); using NewComputePipelineStateCompletionHandlerFunction = std::function<void(class ComputePipelineState*, NS::Error*)>; using NewComputePipelineStateWithReflectionCompletionHandler = void (^)(class ComputePipelineState*, class ComputePipelineReflection*, NS::Error*); using NewComputePipelineStateWithReflectionCompletionHandlerFunction = std::function<void(class ComputePipelineState*, class ComputePipelineReflection*, NS::Error*)>; using Timestamp = std::uint64_t; MTL::Device* CreateSystemDefaultDevice(); NS::Array* CopyAllDevices(); NS::Array* CopyAllDevicesWithObserver(NS::Object** pOutObserver, DeviceNotificationHandlerBlock handler); NS::Array* CopyAllDevicesWithObserver(NS::Object** pOutObserver, const DeviceNotificationHandlerFunction& handler); void RemoveDeviceObserver(const NS::Object* pObserver); class Device : public NS::Referencing<Device> { public: void newLibrary(const NS::String* pSource, const class CompileOptions* pOptions, const NewLibraryCompletionHandlerFunction& completionHandler); void newLibrary(const class StitchedLibraryDescriptor* pDescriptor, const MTL::NewLibraryCompletionHandlerFunction& completionHandler); void newRenderPipelineState(const class RenderPipelineDescriptor* pDescriptor, const NewRenderPipelineStateCompletionHandlerFunction& completionHandler); void newRenderPipelineState(const class RenderPipelineDescriptor* pDescriptor, PipelineOption options, const NewRenderPipelineStateWithReflectionCompletionHandlerFunction& completionHandler); void newRenderPipelineState(const class TileRenderPipelineDescriptor* pDescriptor, PipelineOption options, const NewRenderPipelineStateWithReflectionCompletionHandlerFunction& completionHandler); void newComputePipelineState(const class Function* pFunction, const NewComputePipelineStateCompletionHandlerFunction& completionHandler); void newComputePipelineState(const class Function* pFunction, PipelineOption options, const NewComputePipelineStateWithReflectionCompletionHandlerFunction& completionHandler); void newComputePipelineState(const class ComputePipelineDescriptor* pDescriptor, PipelineOption options, const NewComputePipelineStateWithReflectionCompletionHandlerFunction& completionHandler); bool isHeadless() const; NS::String* name() const; uint64_t registryID() const; class Architecture* architecture() const; MTL::Size maxThreadsPerThreadgroup() const; bool lowPower() const; bool headless() const; bool removable() const; bool hasUnifiedMemory() const; uint64_t recommendedMaxWorkingSetSize() const; MTL::DeviceLocation location() const; NS::UInteger locationNumber() const; uint64_t maxTransferRate() const; bool depth24Stencil8PixelFormatSupported() const; MTL::ReadWriteTextureTier readWriteTextureSupport() const; MTL::ArgumentBuffersTier argumentBuffersSupport() const; bool rasterOrderGroupsSupported() const; bool supports32BitFloatFiltering() const; bool supports32BitMSAA() const; bool supportsQueryTextureLOD() const; bool supportsBCTextureCompression() const; bool supportsPullModelInterpolation() const; bool barycentricCoordsSupported() const; bool supportsShaderBarycentricCoordinates() const; NS::UInteger currentAllocatedSize() const; class CommandQueue* newCommandQueue(); class CommandQueue* newCommandQueue(NS::UInteger maxCommandBufferCount); MTL::SizeAndAlign heapTextureSizeAndAlign(const class TextureDescriptor* desc); MTL::SizeAndAlign heapBufferSizeAndAlign(NS::UInteger length, MTL::ResourceOptions options); class Heap* newHeap(const class HeapDescriptor* descriptor); class Buffer* newBuffer(NS::UInteger length, MTL::ResourceOptions options); class Buffer* newBuffer(const void* pointer, NS::UInteger length, MTL::ResourceOptions options); class Buffer* newBuffer(const void* pointer, NS::UInteger length, MTL::ResourceOptions options, void (^deallocator)(void*, NS::UInteger)); class DepthStencilState* newDepthStencilState(const class DepthStencilDescriptor* descriptor); class Texture* newTexture(const class TextureDescriptor* descriptor); class Texture* newTexture(const class TextureDescriptor* descriptor, const IOSurfaceRef iosurface, NS::UInteger plane); class Texture* newSharedTexture(const class TextureDescriptor* descriptor); class Texture* newSharedTexture(const class SharedTextureHandle* sharedHandle); class SamplerState* newSamplerState(const class SamplerDescriptor* descriptor); class Library* newDefaultLibrary(); class Library* newDefaultLibrary(const NS::Bundle* bundle, NS::Error** error); class Library* newLibrary(const NS::String* filepath, NS::Error** error); class Library* newLibrary(const NS::URL* url, NS::Error** error); class Library* newLibrary(const dispatch_data_t data, NS::Error** error); class Library* newLibrary(const NS::String* source, const class CompileOptions* options, NS::Error** error); void newLibrary(const NS::String* source, const class CompileOptions* options, const MTL::NewLibraryCompletionHandler completionHandler); class Library* newLibrary(const class StitchedLibraryDescriptor* descriptor, NS::Error** error); void newLibrary(const class StitchedLibraryDescriptor* descriptor, const MTL::NewLibraryCompletionHandler completionHandler); class RenderPipelineState* newRenderPipelineState(const class RenderPipelineDescriptor* descriptor, NS::Error** error); class RenderPipelineState* newRenderPipelineState(const class RenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::AutoreleasedRenderPipelineReflection* reflection, NS::Error** error); void newRenderPipelineState(const class RenderPipelineDescriptor* descriptor, const MTL::NewRenderPipelineStateCompletionHandler completionHandler); void newRenderPipelineState(const class RenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::NewRenderPipelineStateWithReflectionCompletionHandler completionHandler); class ComputePipelineState* newComputePipelineState(const class Function* computeFunction, NS::Error** error); class ComputePipelineState* newComputePipelineState(const class Function* computeFunction, MTL::PipelineOption options, const MTL::AutoreleasedComputePipelineReflection* reflection, NS::Error** error); void newComputePipelineState(const class Function* computeFunction, const MTL::NewComputePipelineStateCompletionHandler completionHandler); void newComputePipelineState(const class Function* computeFunction, MTL::PipelineOption options, const MTL::NewComputePipelineStateWithReflectionCompletionHandler completionHandler); class ComputePipelineState* newComputePipelineState(const class ComputePipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::AutoreleasedComputePipelineReflection* reflection, NS::Error** error); void newComputePipelineState(const class ComputePipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::NewComputePipelineStateWithReflectionCompletionHandler completionHandler); class Fence* newFence(); bool supportsFeatureSet(MTL::FeatureSet featureSet); bool supportsFamily(MTL::GPUFamily gpuFamily); bool supportsTextureSampleCount(NS::UInteger sampleCount); NS::UInteger minimumLinearTextureAlignmentForPixelFormat(MTL::PixelFormat format); NS::UInteger minimumTextureBufferAlignmentForPixelFormat(MTL::PixelFormat format); class RenderPipelineState* newRenderPipelineState(const class TileRenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::AutoreleasedRenderPipelineReflection* reflection, NS::Error** error); void newRenderPipelineState(const class TileRenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::NewRenderPipelineStateWithReflectionCompletionHandler completionHandler); class RenderPipelineState* newRenderPipelineState(const class MeshRenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::AutoreleasedRenderPipelineReflection* reflection, NS::Error** error); void newRenderPipelineState(const class MeshRenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::NewRenderPipelineStateWithReflectionCompletionHandler completionHandler); NS::UInteger maxThreadgroupMemoryLength() const; NS::UInteger maxArgumentBufferSamplerCount() const; bool programmableSamplePositionsSupported() const; void getDefaultSamplePositions(MTL::SamplePosition* positions, NS::UInteger count); class ArgumentEncoder* newArgumentEncoder(const NS::Array* arguments); bool supportsRasterizationRateMap(NS::UInteger layerCount); class RasterizationRateMap* newRasterizationRateMap(const class RasterizationRateMapDescriptor* descriptor); class IndirectCommandBuffer* newIndirectCommandBuffer(const class IndirectCommandBufferDescriptor* descriptor, NS::UInteger maxCount, MTL::ResourceOptions options); class Event* newEvent(); class SharedEvent* newSharedEvent(); class SharedEvent* newSharedEvent(const class SharedEventHandle* sharedEventHandle); uint64_t peerGroupID() const; uint32_t peerIndex() const; uint32_t peerCount() const; class IOFileHandle* newIOHandle(const NS::URL* url, NS::Error** error); class IOCommandQueue* newIOCommandQueue(const class IOCommandQueueDescriptor* descriptor, NS::Error** error); class IOFileHandle* newIOHandle(const NS::URL* url, MTL::IOCompressionMethod compressionMethod, NS::Error** error); class IOFileHandle* newIOFileHandle(const NS::URL* url, NS::Error** error); class IOFileHandle* newIOFileHandle(const NS::URL* url, MTL::IOCompressionMethod compressionMethod, NS::Error** error); MTL::Size sparseTileSize(MTL::TextureType textureType, MTL::PixelFormat pixelFormat, NS::UInteger sampleCount); NS::UInteger sparseTileSizeInBytes() const; void convertSparsePixelRegions(const MTL::Region* pixelRegions, MTL::Region* tileRegions, MTL::Size tileSize, MTL::SparseTextureRegionAlignmentMode mode, NS::UInteger numRegions); void convertSparseTileRegions(const MTL::Region* tileRegions, MTL::Region* pixelRegions, MTL::Size tileSize, NS::UInteger numRegions); NS::UInteger sparseTileSizeInBytes(MTL::SparsePageSize sparsePageSize); MTL::Size sparseTileSize(MTL::TextureType textureType, MTL::PixelFormat pixelFormat, NS::UInteger sampleCount, MTL::SparsePageSize sparsePageSize); NS::UInteger maxBufferLength() const; NS::Array* counterSets() const; class CounterSampleBuffer* newCounterSampleBuffer(const class CounterSampleBufferDescriptor* descriptor, NS::Error** error); void sampleTimestamps(MTL::Timestamp* cpuTimestamp, MTL::Timestamp* gpuTimestamp); class ArgumentEncoder* newArgumentEncoder(const class BufferBinding* bufferBinding); bool supportsCounterSampling(MTL::CounterSamplingPoint samplingPoint); bool supportsVertexAmplificationCount(NS::UInteger count); bool supportsDynamicLibraries() const; bool supportsRenderDynamicLibraries() const; class DynamicLibrary* newDynamicLibrary(const class Library* library, NS::Error** error); class DynamicLibrary* newDynamicLibrary(const NS::URL* url, NS::Error** error); class BinaryArchive* newBinaryArchive(const class BinaryArchiveDescriptor* descriptor, NS::Error** error); bool supportsRaytracing() const; MTL::AccelerationStructureSizes accelerationStructureSizes(const class AccelerationStructureDescriptor* descriptor); class AccelerationStructure* newAccelerationStructure(NS::UInteger size); class AccelerationStructure* newAccelerationStructure(const class AccelerationStructureDescriptor* descriptor); MTL::SizeAndAlign heapAccelerationStructureSizeAndAlign(NS::UInteger size); MTL::SizeAndAlign heapAccelerationStructureSizeAndAlign(const class AccelerationStructureDescriptor* descriptor); bool supportsFunctionPointers() const; bool supportsFunctionPointersFromRender() const; bool supportsRaytracingFromRender() const; bool supportsPrimitiveMotionBlur() const; bool shouldMaximizeConcurrentCompilation() const; void setShouldMaximizeConcurrentCompilation(bool shouldMaximizeConcurrentCompilation); NS::UInteger maximumConcurrentCompilationTaskCount() const; }; } _MTL_INLINE MTL::ArgumentDescriptor* MTL::ArgumentDescriptor::alloc() { return NS::Object::alloc<MTL::ArgumentDescriptor>(_MTL_PRIVATE_CLS(MTLArgumentDescriptor)); } _MTL_INLINE MTL::ArgumentDescriptor* MTL::ArgumentDescriptor::init() { return NS::Object::init<MTL::ArgumentDescriptor>(); } _MTL_INLINE MTL::ArgumentDescriptor* MTL::ArgumentDescriptor::argumentDescriptor() { return Object::sendMessage<MTL::ArgumentDescriptor*>(_MTL_PRIVATE_CLS(MTLArgumentDescriptor), _MTL_PRIVATE_SEL(argumentDescriptor)); } _MTL_INLINE MTL::DataType MTL::ArgumentDescriptor::dataType() const { return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(dataType)); } _MTL_INLINE void MTL::ArgumentDescriptor::setDataType(MTL::DataType dataType) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDataType_), dataType); } _MTL_INLINE NS::UInteger MTL::ArgumentDescriptor::index() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(index)); } _MTL_INLINE void MTL::ArgumentDescriptor::setIndex(NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setIndex_), index); } _MTL_INLINE NS::UInteger MTL::ArgumentDescriptor::arrayLength() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(arrayLength)); } _MTL_INLINE void MTL::ArgumentDescriptor::setArrayLength(NS::UInteger arrayLength) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setArrayLength_), arrayLength); } _MTL_INLINE MTL::BindingAccess MTL::ArgumentDescriptor::access() const { return Object::sendMessage<MTL::BindingAccess>(this, _MTL_PRIVATE_SEL(access)); } _MTL_INLINE void MTL::ArgumentDescriptor::setAccess(MTL::BindingAccess access) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAccess_), access); } _MTL_INLINE MTL::TextureType MTL::ArgumentDescriptor::textureType() const { return Object::sendMessage<MTL::TextureType>(this, _MTL_PRIVATE_SEL(textureType)); } _MTL_INLINE void MTL::ArgumentDescriptor::setTextureType(MTL::TextureType textureType) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTextureType_), textureType); } _MTL_INLINE NS::UInteger MTL::ArgumentDescriptor::constantBlockAlignment() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(constantBlockAlignment)); } _MTL_INLINE void MTL::ArgumentDescriptor::setConstantBlockAlignment(NS::UInteger constantBlockAlignment) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setConstantBlockAlignment_), constantBlockAlignment); } _MTL_INLINE MTL::Architecture* MTL::Architecture::alloc() { return NS::Object::alloc<MTL::Architecture>(_MTL_PRIVATE_CLS(MTLArchitecture)); } _MTL_INLINE MTL::Architecture* MTL::Architecture::init() { return NS::Object::init<MTL::Architecture>(); } _MTL_INLINE NS::String* MTL::Architecture::name() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name)); } _MTL_PRIVATE_DEF_WEAK_CONST(MTL::DeviceNotificationName, DeviceWasAddedNotification); _MTL_PRIVATE_DEF_WEAK_CONST(MTL::DeviceNotificationName, DeviceRemovalRequestedNotification); _MTL_PRIVATE_DEF_WEAK_CONST(MTL::DeviceNotificationName, DeviceWasRemovedNotification); _MTL_PRIVATE_DEF_CONST(NS::ErrorUserInfoKey, CommandBufferEncoderInfoErrorKey); #if defined(MTL_PRIVATE_IMPLEMENTATION) extern "C" MTL::Device* MTLCreateSystemDefaultDevice(); extern "C" NS::Array* MTLCopyAllDevices(); extern "C" NS::Array* MTLCopyAllDevicesWithObserver(NS::Object**, MTL::DeviceNotificationHandlerBlock); extern "C" void MTLRemoveDeviceObserver(const NS::Object*); #include <TargetConditionals.h> _NS_EXPORT MTL::Device* MTL::CreateSystemDefaultDevice() { return ::MTLCreateSystemDefaultDevice(); } _NS_EXPORT NS::Array* MTL::CopyAllDevices() { #if TARGET_OS_OSX return ::MTLCopyAllDevices(); #else return nullptr; #endif // TARGET_OS_OSX } _NS_EXPORT NS::Array* MTL::CopyAllDevicesWithObserver(NS::Object** pOutObserver, DeviceNotificationHandlerBlock handler) { #if TARGET_OS_OSX return ::MTLCopyAllDevicesWithObserver(pOutObserver, handler); #else (void)pOutObserver; (void)handler; return nullptr; #endif // TARGET_OS_OSX } _NS_EXPORT NS::Array* MTL::CopyAllDevicesWithObserver(NS::Object** pOutObserver, const DeviceNotificationHandlerFunction& handler) { __block DeviceNotificationHandlerFunction function = handler; return CopyAllDevicesWithObserver(pOutObserver, ^(Device* pDevice, DeviceNotificationName pNotificationName) { function(pDevice, pNotificationName); }); } _NS_EXPORT void MTL::RemoveDeviceObserver(const NS::Object* pObserver) { #if TARGET_OS_OSX ::MTLRemoveDeviceObserver(pObserver); #endif // TARGET_OS_OSX } #endif // MTL_PRIVATE_IMPLEMENTATION _MTL_INLINE void MTL::Device::newLibrary(const NS::String* pSource, const CompileOptions* pOptions, const NewLibraryCompletionHandlerFunction& completionHandler) { __block NewLibraryCompletionHandlerFunction blockCompletionHandler = completionHandler; newLibrary(pSource, pOptions, ^(Library* pLibrary, NS::Error* pError) { blockCompletionHandler(pLibrary, pError); }); } _MTL_INLINE void MTL::Device::newLibrary(const class StitchedLibraryDescriptor* pDescriptor, const MTL::NewLibraryCompletionHandlerFunction& completionHandler) { __block NewLibraryCompletionHandlerFunction blockCompletionHandler = completionHandler; newLibrary(pDescriptor, ^(Library* pLibrary, NS::Error* pError) { blockCompletionHandler(pLibrary, pError); }); } _MTL_INLINE void MTL::Device::newRenderPipelineState(const RenderPipelineDescriptor* pDescriptor, const NewRenderPipelineStateCompletionHandlerFunction& completionHandler) { __block NewRenderPipelineStateCompletionHandlerFunction blockCompletionHandler = completionHandler; newRenderPipelineState(pDescriptor, ^(RenderPipelineState* pPipelineState, NS::Error* pError) { blockCompletionHandler(pPipelineState, pError); }); } _MTL_INLINE void MTL::Device::newRenderPipelineState(const RenderPipelineDescriptor* pDescriptor, PipelineOption options, const NewRenderPipelineStateWithReflectionCompletionHandlerFunction& completionHandler) { __block NewRenderPipelineStateWithReflectionCompletionHandlerFunction blockCompletionHandler = completionHandler; newRenderPipelineState(pDescriptor, options, ^(RenderPipelineState* pPipelineState, class RenderPipelineReflection* pReflection, NS::Error* pError) { blockCompletionHandler(pPipelineState, pReflection, pError); }); } _MTL_INLINE void MTL::Device::newRenderPipelineState(const TileRenderPipelineDescriptor* pDescriptor, PipelineOption options, const NewRenderPipelineStateWithReflectionCompletionHandlerFunction& completionHandler) { __block NewRenderPipelineStateWithReflectionCompletionHandlerFunction blockCompletionHandler = completionHandler; newRenderPipelineState(pDescriptor, options, ^(RenderPipelineState* pPipelineState, class RenderPipelineReflection* pReflection, NS::Error* pError) { blockCompletionHandler(pPipelineState, pReflection, pError); }); } _MTL_INLINE void MTL::Device::newComputePipelineState(const class Function* pFunction, const NewComputePipelineStateCompletionHandlerFunction& completionHandler) { __block NewComputePipelineStateCompletionHandlerFunction blockCompletionHandler = completionHandler; newComputePipelineState(pFunction, ^(ComputePipelineState* pPipelineState, NS::Error* pError) { blockCompletionHandler(pPipelineState, pError); }); } _MTL_INLINE void MTL::Device::newComputePipelineState(const Function* pFunction, PipelineOption options, const NewComputePipelineStateWithReflectionCompletionHandlerFunction& completionHandler) { __block NewComputePipelineStateWithReflectionCompletionHandlerFunction blockCompletionHandler = completionHandler; newComputePipelineState(pFunction, options, ^(ComputePipelineState* pPipelineState, ComputePipelineReflection* pReflection, NS::Error* pError) { blockCompletionHandler(pPipelineState, pReflection, pError); }); } _MTL_INLINE void MTL::Device::newComputePipelineState(const ComputePipelineDescriptor* pDescriptor, PipelineOption options, const NewComputePipelineStateWithReflectionCompletionHandlerFunction& completionHandler) { __block NewComputePipelineStateWithReflectionCompletionHandlerFunction blockCompletionHandler = completionHandler; newComputePipelineState(pDescriptor, options, ^(ComputePipelineState* pPipelineState, ComputePipelineReflection* pReflection, NS::Error* pError) { blockCompletionHandler(pPipelineState, pReflection, pError); }); } _MTL_INLINE bool MTL::Device::isHeadless() const { return headless(); } _MTL_INLINE NS::String* MTL::Device::name() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name)); } _MTL_INLINE uint64_t MTL::Device::registryID() const { return Object::sendMessage<uint64_t>(this, _MTL_PRIVATE_SEL(registryID)); } _MTL_INLINE MTL::Architecture* MTL::Device::architecture() const { return Object::sendMessage<MTL::Architecture*>(this, _MTL_PRIVATE_SEL(architecture)); } _MTL_INLINE MTL::Size MTL::Device::maxThreadsPerThreadgroup() const { return Object::sendMessage<MTL::Size>(this, _MTL_PRIVATE_SEL(maxThreadsPerThreadgroup)); } _MTL_INLINE bool MTL::Device::lowPower() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isLowPower)); } _MTL_INLINE bool MTL::Device::headless() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isHeadless)); } _MTL_INLINE bool MTL::Device::removable() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isRemovable)); } _MTL_INLINE bool MTL::Device::hasUnifiedMemory() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(hasUnifiedMemory)); } _MTL_INLINE uint64_t MTL::Device::recommendedMaxWorkingSetSize() const { return Object::sendMessage<uint64_t>(this, _MTL_PRIVATE_SEL(recommendedMaxWorkingSetSize)); } _MTL_INLINE MTL::DeviceLocation MTL::Device::location() const { return Object::sendMessage<MTL::DeviceLocation>(this, _MTL_PRIVATE_SEL(location)); } _MTL_INLINE NS::UInteger MTL::Device::locationNumber() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(locationNumber)); } _MTL_INLINE uint64_t MTL::Device::maxTransferRate() const { return Object::sendMessage<uint64_t>(this, _MTL_PRIVATE_SEL(maxTransferRate)); } _MTL_INLINE bool MTL::Device::depth24Stencil8PixelFormatSupported() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(isDepth24Stencil8PixelFormatSupported)); } _MTL_INLINE MTL::ReadWriteTextureTier MTL::Device::readWriteTextureSupport() const { return Object::sendMessage<MTL::ReadWriteTextureTier>(this, _MTL_PRIVATE_SEL(readWriteTextureSupport)); } _MTL_INLINE MTL::ArgumentBuffersTier MTL::Device::argumentBuffersSupport() const { return Object::sendMessage<MTL::ArgumentBuffersTier>(this, _MTL_PRIVATE_SEL(argumentBuffersSupport)); } _MTL_INLINE bool MTL::Device::rasterOrderGroupsSupported() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(areRasterOrderGroupsSupported)); } _MTL_INLINE bool MTL::Device::supports32BitFloatFiltering() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supports32BitFloatFiltering)); } _MTL_INLINE bool MTL::Device::supports32BitMSAA() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supports32BitMSAA)); } _MTL_INLINE bool MTL::Device::supportsQueryTextureLOD() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsQueryTextureLOD)); } _MTL_INLINE bool MTL::Device::supportsBCTextureCompression() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsBCTextureCompression)); } _MTL_INLINE bool MTL::Device::supportsPullModelInterpolation() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsPullModelInterpolation)); } _MTL_INLINE bool MTL::Device::barycentricCoordsSupported() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(areBarycentricCoordsSupported)); } _MTL_INLINE bool MTL::Device::supportsShaderBarycentricCoordinates() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsShaderBarycentricCoordinates)); } _MTL_INLINE NS::UInteger MTL::Device::currentAllocatedSize() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(currentAllocatedSize)); } _MTL_INLINE MTL::CommandQueue* MTL::Device::newCommandQueue() { return Object::sendMessage<MTL::CommandQueue*>(this, _MTL_PRIVATE_SEL(newCommandQueue)); } _MTL_INLINE MTL::CommandQueue* MTL::Device::newCommandQueue(NS::UInteger maxCommandBufferCount) { return Object::sendMessage<MTL::CommandQueue*>(this, _MTL_PRIVATE_SEL(newCommandQueueWithMaxCommandBufferCount_), maxCommandBufferCount); } _MTL_INLINE MTL::SizeAndAlign MTL::Device::heapTextureSizeAndAlign(const MTL::TextureDescriptor* desc) { return Object::sendMessage<MTL::SizeAndAlign>(this, _MTL_PRIVATE_SEL(heapTextureSizeAndAlignWithDescriptor_), desc); } _MTL_INLINE MTL::SizeAndAlign MTL::Device::heapBufferSizeAndAlign(NS::UInteger length, MTL::ResourceOptions options) { return Object::sendMessage<MTL::SizeAndAlign>(this, _MTL_PRIVATE_SEL(heapBufferSizeAndAlignWithLength_options_), length, options); } _MTL_INLINE MTL::Heap* MTL::Device::newHeap(const MTL::HeapDescriptor* descriptor) { return Object::sendMessage<MTL::Heap*>(this, _MTL_PRIVATE_SEL(newHeapWithDescriptor_), descriptor); } _MTL_INLINE MTL::Buffer* MTL::Device::newBuffer(NS::UInteger length, MTL::ResourceOptions options) { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(newBufferWithLength_options_), length, options); } _MTL_INLINE MTL::Buffer* MTL::Device::newBuffer(const void* pointer, NS::UInteger length, MTL::ResourceOptions options) { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(newBufferWithBytes_length_options_), pointer, length, options); } _MTL_INLINE MTL::Buffer* MTL::Device::newBuffer(const void* pointer, NS::UInteger length, MTL::ResourceOptions options, void (^deallocator)(void*, NS::UInteger)) { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(newBufferWithBytesNoCopy_length_options_deallocator_), pointer, length, options, deallocator); } _MTL_INLINE MTL::DepthStencilState* MTL::Device::newDepthStencilState(const MTL::DepthStencilDescriptor* descriptor) { return Object::sendMessage<MTL::DepthStencilState*>(this, _MTL_PRIVATE_SEL(newDepthStencilStateWithDescriptor_), descriptor); } _MTL_INLINE MTL::Texture* MTL::Device::newTexture(const MTL::TextureDescriptor* descriptor) { return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newTextureWithDescriptor_), descriptor); } _MTL_INLINE MTL::Texture* MTL::Device::newTexture(const MTL::TextureDescriptor* descriptor, const IOSurfaceRef iosurface, NS::UInteger plane) { return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newTextureWithDescriptor_iosurface_plane_), descriptor, iosurface, plane); } _MTL_INLINE MTL::Texture* MTL::Device::newSharedTexture(const MTL::TextureDescriptor* descriptor) { return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newSharedTextureWithDescriptor_), descriptor); } _MTL_INLINE MTL::Texture* MTL::Device::newSharedTexture(const MTL::SharedTextureHandle* sharedHandle) { return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newSharedTextureWithHandle_), sharedHandle); } _MTL_INLINE MTL::SamplerState* MTL::Device::newSamplerState(const MTL::SamplerDescriptor* descriptor) { return Object::sendMessage<MTL::SamplerState*>(this, _MTL_PRIVATE_SEL(newSamplerStateWithDescriptor_), descriptor); } _MTL_INLINE MTL::Library* MTL::Device::newDefaultLibrary() { return Object::sendMessage<MTL::Library*>(this, _MTL_PRIVATE_SEL(newDefaultLibrary)); } _MTL_INLINE MTL::Library* MTL::Device::newDefaultLibrary(const NS::Bundle* bundle, NS::Error** error) { return Object::sendMessage<MTL::Library*>(this, _MTL_PRIVATE_SEL(newDefaultLibraryWithBundle_error_), bundle, error); } _MTL_INLINE MTL::Library* MTL::Device::newLibrary(const NS::String* filepath, NS::Error** error) { return Object::sendMessage<MTL::Library*>(this, _MTL_PRIVATE_SEL(newLibraryWithFile_error_), filepath, error); } _MTL_INLINE MTL::Library* MTL::Device::newLibrary(const NS::URL* url, NS::Error** error) { return Object::sendMessage<MTL::Library*>(this, _MTL_PRIVATE_SEL(newLibraryWithURL_error_), url, error); } _MTL_INLINE MTL::Library* MTL::Device::newLibrary(const dispatch_data_t data, NS::Error** error) { return Object::sendMessage<MTL::Library*>(this, _MTL_PRIVATE_SEL(newLibraryWithData_error_), data, error); } _MTL_INLINE MTL::Library* MTL::Device::newLibrary(const NS::String* source, const MTL::CompileOptions* options, NS::Error** error) { return Object::sendMessage<MTL::Library*>(this, _MTL_PRIVATE_SEL(newLibraryWithSource_options_error_), source, options, error); } _MTL_INLINE void MTL::Device::newLibrary(const NS::String* source, const MTL::CompileOptions* options, const MTL::NewLibraryCompletionHandler completionHandler) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newLibraryWithSource_options_completionHandler_), source, options, completionHandler); } _MTL_INLINE MTL::Library* MTL::Device::newLibrary(const MTL::StitchedLibraryDescriptor* descriptor, NS::Error** error) { return Object::sendMessage<MTL::Library*>(this, _MTL_PRIVATE_SEL(newLibraryWithStitchedDescriptor_error_), descriptor, error); } _MTL_INLINE void MTL::Device::newLibrary(const MTL::StitchedLibraryDescriptor* descriptor, const MTL::NewLibraryCompletionHandler completionHandler) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newLibraryWithStitchedDescriptor_completionHandler_), descriptor, completionHandler); } _MTL_INLINE MTL::RenderPipelineState* MTL::Device::newRenderPipelineState(const MTL::RenderPipelineDescriptor* descriptor, NS::Error** error) { return Object::sendMessage<MTL::RenderPipelineState*>(this, _MTL_PRIVATE_SEL(newRenderPipelineStateWithDescriptor_error_), descriptor, error); } _MTL_INLINE MTL::RenderPipelineState* MTL::Device::newRenderPipelineState(const MTL::RenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::AutoreleasedRenderPipelineReflection* reflection, NS::Error** error) { return Object::sendMessage<MTL::RenderPipelineState*>(this, _MTL_PRIVATE_SEL(newRenderPipelineStateWithDescriptor_options_reflection_error_), descriptor, options, reflection, error); } _MTL_INLINE void MTL::Device::newRenderPipelineState(const MTL::RenderPipelineDescriptor* descriptor, const MTL::NewRenderPipelineStateCompletionHandler completionHandler) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newRenderPipelineStateWithDescriptor_completionHandler_), descriptor, completionHandler); } _MTL_INLINE void MTL::Device::newRenderPipelineState(const MTL::RenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::NewRenderPipelineStateWithReflectionCompletionHandler completionHandler) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newRenderPipelineStateWithDescriptor_options_completionHandler_), descriptor, options, completionHandler); } _MTL_INLINE MTL::ComputePipelineState* MTL::Device::newComputePipelineState(const MTL::Function* computeFunction, NS::Error** error) { return Object::sendMessage<MTL::ComputePipelineState*>(this, _MTL_PRIVATE_SEL(newComputePipelineStateWithFunction_error_), computeFunction, error); } _MTL_INLINE MTL::ComputePipelineState* MTL::Device::newComputePipelineState(const MTL::Function* computeFunction, MTL::PipelineOption options, const MTL::AutoreleasedComputePipelineReflection* reflection, NS::Error** error) { return Object::sendMessage<MTL::ComputePipelineState*>(this, _MTL_PRIVATE_SEL(newComputePipelineStateWithFunction_options_reflection_error_), computeFunction, options, reflection, error); } _MTL_INLINE void MTL::Device::newComputePipelineState(const MTL::Function* computeFunction, const MTL::NewComputePipelineStateCompletionHandler completionHandler) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newComputePipelineStateWithFunction_completionHandler_), computeFunction, completionHandler); } _MTL_INLINE void MTL::Device::newComputePipelineState(const MTL::Function* computeFunction, MTL::PipelineOption options, const MTL::NewComputePipelineStateWithReflectionCompletionHandler completionHandler) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newComputePipelineStateWithFunction_options_completionHandler_), computeFunction, options, completionHandler); } _MTL_INLINE MTL::ComputePipelineState* MTL::Device::newComputePipelineState(const MTL::ComputePipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::AutoreleasedComputePipelineReflection* reflection, NS::Error** error) { return Object::sendMessage<MTL::ComputePipelineState*>(this, _MTL_PRIVATE_SEL(newComputePipelineStateWithDescriptor_options_reflection_error_), descriptor, options, reflection, error); } _MTL_INLINE void MTL::Device::newComputePipelineState(const MTL::ComputePipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::NewComputePipelineStateWithReflectionCompletionHandler completionHandler) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newComputePipelineStateWithDescriptor_options_completionHandler_), descriptor, options, completionHandler); } _MTL_INLINE MTL::Fence* MTL::Device::newFence() { return Object::sendMessage<MTL::Fence*>(this, _MTL_PRIVATE_SEL(newFence)); } _MTL_INLINE bool MTL::Device::supportsFeatureSet(MTL::FeatureSet featureSet) { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsFeatureSet_), featureSet); } _MTL_INLINE bool MTL::Device::supportsFamily(MTL::GPUFamily gpuFamily) { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsFamily_), gpuFamily); } _MTL_INLINE bool MTL::Device::supportsTextureSampleCount(NS::UInteger sampleCount) { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsTextureSampleCount_), sampleCount); } _MTL_INLINE NS::UInteger MTL::Device::minimumLinearTextureAlignmentForPixelFormat(MTL::PixelFormat format) { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(minimumLinearTextureAlignmentForPixelFormat_), format); } _MTL_INLINE NS::UInteger MTL::Device::minimumTextureBufferAlignmentForPixelFormat(MTL::PixelFormat format) { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(minimumTextureBufferAlignmentForPixelFormat_), format); } _MTL_INLINE MTL::RenderPipelineState* MTL::Device::newRenderPipelineState(const MTL::TileRenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::AutoreleasedRenderPipelineReflection* reflection, NS::Error** error) { return Object::sendMessage<MTL::RenderPipelineState*>(this, _MTL_PRIVATE_SEL(newRenderPipelineStateWithTileDescriptor_options_reflection_error_), descriptor, options, reflection, error); } _MTL_INLINE void MTL::Device::newRenderPipelineState(const MTL::TileRenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::NewRenderPipelineStateWithReflectionCompletionHandler completionHandler) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newRenderPipelineStateWithTileDescriptor_options_completionHandler_), descriptor, options, completionHandler); } _MTL_INLINE MTL::RenderPipelineState* MTL::Device::newRenderPipelineState(const MTL::MeshRenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::AutoreleasedRenderPipelineReflection* reflection, NS::Error** error) { return Object::sendMessage<MTL::RenderPipelineState*>(this, _MTL_PRIVATE_SEL(newRenderPipelineStateWithMeshDescriptor_options_reflection_error_), descriptor, options, reflection, error); } _MTL_INLINE void MTL::Device::newRenderPipelineState(const MTL::MeshRenderPipelineDescriptor* descriptor, MTL::PipelineOption options, const MTL::NewRenderPipelineStateWithReflectionCompletionHandler completionHandler) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newRenderPipelineStateWithMeshDescriptor_options_completionHandler_), descriptor, options, completionHandler); } _MTL_INLINE NS::UInteger MTL::Device::maxThreadgroupMemoryLength() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxThreadgroupMemoryLength)); } _MTL_INLINE NS::UInteger MTL::Device::maxArgumentBufferSamplerCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxArgumentBufferSamplerCount)); } _MTL_INLINE bool MTL::Device::programmableSamplePositionsSupported() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(areProgrammableSamplePositionsSupported)); } _MTL_INLINE void MTL::Device::getDefaultSamplePositions(MTL::SamplePosition* positions, NS::UInteger count) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(getDefaultSamplePositions_count_), positions, count); } _MTL_INLINE MTL::ArgumentEncoder* MTL::Device::newArgumentEncoder(const NS::Array* arguments) { return Object::sendMessage<MTL::ArgumentEncoder*>(this, _MTL_PRIVATE_SEL(newArgumentEncoderWithArguments_), arguments); } _MTL_INLINE bool MTL::Device::supportsRasterizationRateMap(NS::UInteger layerCount) { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsRasterizationRateMapWithLayerCount_), layerCount); } _MTL_INLINE MTL::RasterizationRateMap* MTL::Device::newRasterizationRateMap(const MTL::RasterizationRateMapDescriptor* descriptor) { return Object::sendMessage<MTL::RasterizationRateMap*>(this, _MTL_PRIVATE_SEL(newRasterizationRateMapWithDescriptor_), descriptor); } _MTL_INLINE MTL::IndirectCommandBuffer* MTL::Device::newIndirectCommandBuffer(const MTL::IndirectCommandBufferDescriptor* descriptor, NS::UInteger maxCount, MTL::ResourceOptions options) { return Object::sendMessage<MTL::IndirectCommandBuffer*>(this, _MTL_PRIVATE_SEL(newIndirectCommandBufferWithDescriptor_maxCommandCount_options_), descriptor, maxCount, options); } _MTL_INLINE MTL::Event* MTL::Device::newEvent() { return Object::sendMessage<MTL::Event*>(this, _MTL_PRIVATE_SEL(newEvent)); } _MTL_INLINE MTL::SharedEvent* MTL::Device::newSharedEvent() { return Object::sendMessage<MTL::SharedEvent*>(this, _MTL_PRIVATE_SEL(newSharedEvent)); } _MTL_INLINE MTL::SharedEvent* MTL::Device::newSharedEvent(const MTL::SharedEventHandle* sharedEventHandle) { return Object::sendMessage<MTL::SharedEvent*>(this, _MTL_PRIVATE_SEL(newSharedEventWithHandle_), sharedEventHandle); } _MTL_INLINE uint64_t MTL::Device::peerGroupID() const { return Object::sendMessage<uint64_t>(this, _MTL_PRIVATE_SEL(peerGroupID)); } _MTL_INLINE uint32_t MTL::Device::peerIndex() const { return Object::sendMessage<uint32_t>(this, _MTL_PRIVATE_SEL(peerIndex)); } _MTL_INLINE uint32_t MTL::Device::peerCount() const { return Object::sendMessage<uint32_t>(this, _MTL_PRIVATE_SEL(peerCount)); } _MTL_INLINE MTL::IOFileHandle* MTL::Device::newIOHandle(const NS::URL* url, NS::Error** error) { return Object::sendMessage<MTL::IOFileHandle*>(this, _MTL_PRIVATE_SEL(newIOHandleWithURL_error_), url, error); } _MTL_INLINE MTL::IOCommandQueue* MTL::Device::newIOCommandQueue(const MTL::IOCommandQueueDescriptor* descriptor, NS::Error** error) { return Object::sendMessage<MTL::IOCommandQueue*>(this, _MTL_PRIVATE_SEL(newIOCommandQueueWithDescriptor_error_), descriptor, error); } _MTL_INLINE MTL::IOFileHandle* MTL::Device::newIOHandle(const NS::URL* url, MTL::IOCompressionMethod compressionMethod, NS::Error** error) { return Object::sendMessage<MTL::IOFileHandle*>(this, _MTL_PRIVATE_SEL(newIOHandleWithURL_compressionMethod_error_), url, compressionMethod, error); } _MTL_INLINE MTL::IOFileHandle* MTL::Device::newIOFileHandle(const NS::URL* url, NS::Error** error) { return Object::sendMessage<MTL::IOFileHandle*>(this, _MTL_PRIVATE_SEL(newIOFileHandleWithURL_error_), url, error); } _MTL_INLINE MTL::IOFileHandle* MTL::Device::newIOFileHandle(const NS::URL* url, MTL::IOCompressionMethod compressionMethod, NS::Error** error) { return Object::sendMessage<MTL::IOFileHandle*>(this, _MTL_PRIVATE_SEL(newIOFileHandleWithURL_compressionMethod_error_), url, compressionMethod, error); } _MTL_INLINE MTL::Size MTL::Device::sparseTileSize(MTL::TextureType textureType, MTL::PixelFormat pixelFormat, NS::UInteger sampleCount) { return Object::sendMessage<MTL::Size>(this, _MTL_PRIVATE_SEL(sparseTileSizeWithTextureType_pixelFormat_sampleCount_), textureType, pixelFormat, sampleCount); } _MTL_INLINE NS::UInteger MTL::Device::sparseTileSizeInBytes() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(sparseTileSizeInBytes)); } _MTL_INLINE void MTL::Device::convertSparsePixelRegions(const MTL::Region* pixelRegions, MTL::Region* tileRegions, MTL::Size tileSize, MTL::SparseTextureRegionAlignmentMode mode, NS::UInteger numRegions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(convertSparsePixelRegions_toTileRegions_withTileSize_alignmentMode_numRegions_), pixelRegions, tileRegions, tileSize, mode, numRegions); } _MTL_INLINE void MTL::Device::convertSparseTileRegions(const MTL::Region* tileRegions, MTL::Region* pixelRegions, MTL::Size tileSize, NS::UInteger numRegions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(convertSparseTileRegions_toPixelRegions_withTileSize_numRegions_), tileRegions, pixelRegions, tileSize, numRegions); } _MTL_INLINE NS::UInteger MTL::Device::sparseTileSizeInBytes(MTL::SparsePageSize sparsePageSize) { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(sparseTileSizeInBytesForSparsePageSize_), sparsePageSize); } _MTL_INLINE MTL::Size MTL::Device::sparseTileSize(MTL::TextureType textureType, MTL::PixelFormat pixelFormat, NS::UInteger sampleCount, MTL::SparsePageSize sparsePageSize) { return Object::sendMessage<MTL::Size>(this, _MTL_PRIVATE_SEL(sparseTileSizeWithTextureType_pixelFormat_sampleCount_sparsePageSize_), textureType, pixelFormat, sampleCount, sparsePageSize); } _MTL_INLINE NS::UInteger MTL::Device::maxBufferLength() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxBufferLength)); } _MTL_INLINE NS::Array* MTL::Device::counterSets() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(counterSets)); } _MTL_INLINE MTL::CounterSampleBuffer* MTL::Device::newCounterSampleBuffer(const MTL::CounterSampleBufferDescriptor* descriptor, NS::Error** error) { return Object::sendMessage<MTL::CounterSampleBuffer*>(this, _MTL_PRIVATE_SEL(newCounterSampleBufferWithDescriptor_error_), descriptor, error); } _MTL_INLINE void MTL::Device::sampleTimestamps(MTL::Timestamp* cpuTimestamp, MTL::Timestamp* gpuTimestamp) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(sampleTimestamps_gpuTimestamp_), cpuTimestamp, gpuTimestamp); } _MTL_INLINE MTL::ArgumentEncoder* MTL::Device::newArgumentEncoder(const MTL::BufferBinding* bufferBinding) { return Object::sendMessage<MTL::ArgumentEncoder*>(this, _MTL_PRIVATE_SEL(newArgumentEncoderWithBufferBinding_), bufferBinding); } _MTL_INLINE bool MTL::Device::supportsCounterSampling(MTL::CounterSamplingPoint samplingPoint) { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsCounterSampling_), samplingPoint); } _MTL_INLINE bool MTL::Device::supportsVertexAmplificationCount(NS::UInteger count) { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsVertexAmplificationCount_), count); } _MTL_INLINE bool MTL::Device::supportsDynamicLibraries() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsDynamicLibraries)); } _MTL_INLINE bool MTL::Device::supportsRenderDynamicLibraries() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsRenderDynamicLibraries)); } _MTL_INLINE MTL::DynamicLibrary* MTL::Device::newDynamicLibrary(const MTL::Library* library, NS::Error** error) { return Object::sendMessage<MTL::DynamicLibrary*>(this, _MTL_PRIVATE_SEL(newDynamicLibrary_error_), library, error); } _MTL_INLINE MTL::DynamicLibrary* MTL::Device::newDynamicLibrary(const NS::URL* url, NS::Error** error) { return Object::sendMessage<MTL::DynamicLibrary*>(this, _MTL_PRIVATE_SEL(newDynamicLibraryWithURL_error_), url, error); } _MTL_INLINE MTL::BinaryArchive* MTL::Device::newBinaryArchive(const MTL::BinaryArchiveDescriptor* descriptor, NS::Error** error) { return Object::sendMessage<MTL::BinaryArchive*>(this, _MTL_PRIVATE_SEL(newBinaryArchiveWithDescriptor_error_), descriptor, error); } _MTL_INLINE bool MTL::Device::supportsRaytracing() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsRaytracing)); } _MTL_INLINE MTL::AccelerationStructureSizes MTL::Device::accelerationStructureSizes(const MTL::AccelerationStructureDescriptor* descriptor) { return Object::sendMessage<MTL::AccelerationStructureSizes>(this, _MTL_PRIVATE_SEL(accelerationStructureSizesWithDescriptor_), descriptor); } _MTL_INLINE MTL::AccelerationStructure* MTL::Device::newAccelerationStructure(NS::UInteger size) { return Object::sendMessage<MTL::AccelerationStructure*>(this, _MTL_PRIVATE_SEL(newAccelerationStructureWithSize_), size); } _MTL_INLINE MTL::AccelerationStructure* MTL::Device::newAccelerationStructure(const MTL::AccelerationStructureDescriptor* descriptor) { return Object::sendMessage<MTL::AccelerationStructure*>(this, _MTL_PRIVATE_SEL(newAccelerationStructureWithDescriptor_), descriptor); } _MTL_INLINE MTL::SizeAndAlign MTL::Device::heapAccelerationStructureSizeAndAlign(NS::UInteger size) { return Object::sendMessage<MTL::SizeAndAlign>(this, _MTL_PRIVATE_SEL(heapAccelerationStructureSizeAndAlignWithSize_), size); } _MTL_INLINE MTL::SizeAndAlign MTL::Device::heapAccelerationStructureSizeAndAlign(const MTL::AccelerationStructureDescriptor* descriptor) { return Object::sendMessage<MTL::SizeAndAlign>(this, _MTL_PRIVATE_SEL(heapAccelerationStructureSizeAndAlignWithDescriptor_), descriptor); } _MTL_INLINE bool MTL::Device::supportsFunctionPointers() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsFunctionPointers)); } _MTL_INLINE bool MTL::Device::supportsFunctionPointersFromRender() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsFunctionPointersFromRender)); } _MTL_INLINE bool MTL::Device::supportsRaytracingFromRender() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsRaytracingFromRender)); } _MTL_INLINE bool MTL::Device::supportsPrimitiveMotionBlur() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportsPrimitiveMotionBlur)); } _MTL_INLINE bool MTL::Device::shouldMaximizeConcurrentCompilation() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(shouldMaximizeConcurrentCompilation)); } _MTL_INLINE void MTL::Device::setShouldMaximizeConcurrentCompilation(bool shouldMaximizeConcurrentCompilation) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setShouldMaximizeConcurrentCompilation_), shouldMaximizeConcurrentCompilation); } _MTL_INLINE NS::UInteger MTL::Device::maximumConcurrentCompilationTaskCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maximumConcurrentCompilationTaskCount)); } #pragma once namespace MTL { _MTL_ENUM(NS::UInteger, DynamicLibraryError) { DynamicLibraryErrorNone = 0, DynamicLibraryErrorInvalidFile = 1, DynamicLibraryErrorCompilationFailure = 2, DynamicLibraryErrorUnresolvedInstallName = 3, DynamicLibraryErrorDependencyLoadFailure = 4, DynamicLibraryErrorUnsupported = 5, }; class DynamicLibrary : public NS::Referencing<DynamicLibrary> { public: NS::String* label() const; void setLabel(const NS::String* label); class Device* device() const; NS::String* installName() const; bool serializeToURL(const NS::URL* url, NS::Error** error); }; } _MTL_INLINE NS::String* MTL::DynamicLibrary::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::DynamicLibrary::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE MTL::Device* MTL::DynamicLibrary::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE NS::String* MTL::DynamicLibrary::installName() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(installName)); } _MTL_INLINE bool MTL::DynamicLibrary::serializeToURL(const NS::URL* url, NS::Error** error) { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(serializeToURL_error_), url, error); } #pragma once namespace MTL { class Event : public NS::Referencing<Event> { public: class Device* device() const; NS::String* label() const; void setLabel(const NS::String* label); }; class SharedEventListener : public NS::Referencing<SharedEventListener> { public: static class SharedEventListener* alloc(); MTL::SharedEventListener* init(); MTL::SharedEventListener* init(const dispatch_queue_t dispatchQueue); dispatch_queue_t dispatchQueue() const; }; using SharedEventNotificationBlock = void (^)(SharedEvent* pEvent, std::uint64_t value); class SharedEvent : public NS::Referencing<SharedEvent, Event> { public: void notifyListener(const class SharedEventListener* listener, uint64_t value, const MTL::SharedEventNotificationBlock block); class SharedEventHandle* newSharedEventHandle(); uint64_t signaledValue() const; void setSignaledValue(uint64_t signaledValue); }; class SharedEventHandle : public NS::SecureCoding<SharedEventHandle> { public: static class SharedEventHandle* alloc(); class SharedEventHandle* init(); NS::String* label() const; }; } _MTL_INLINE MTL::Device* MTL::Event::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE NS::String* MTL::Event::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::Event::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE MTL::SharedEventListener* MTL::SharedEventListener::alloc() { return NS::Object::alloc<MTL::SharedEventListener>(_MTL_PRIVATE_CLS(MTLSharedEventListener)); } _MTL_INLINE MTL::SharedEventListener* MTL::SharedEventListener::init() { return NS::Object::init<MTL::SharedEventListener>(); } _MTL_INLINE MTL::SharedEventListener* MTL::SharedEventListener::init(const dispatch_queue_t dispatchQueue) { return Object::sendMessage<MTL::SharedEventListener*>(this, _MTL_PRIVATE_SEL(initWithDispatchQueue_), dispatchQueue); } _MTL_INLINE dispatch_queue_t MTL::SharedEventListener::dispatchQueue() const { return Object::sendMessage<dispatch_queue_t>(this, _MTL_PRIVATE_SEL(dispatchQueue)); } _MTL_INLINE void MTL::SharedEvent::notifyListener(const MTL::SharedEventListener* listener, uint64_t value, const MTL::SharedEventNotificationBlock block) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(notifyListener_atValue_block_), listener, value, block); } _MTL_INLINE MTL::SharedEventHandle* MTL::SharedEvent::newSharedEventHandle() { return Object::sendMessage<MTL::SharedEventHandle*>(this, _MTL_PRIVATE_SEL(newSharedEventHandle)); } _MTL_INLINE uint64_t MTL::SharedEvent::signaledValue() const { return Object::sendMessage<uint64_t>(this, _MTL_PRIVATE_SEL(signaledValue)); } _MTL_INLINE void MTL::SharedEvent::setSignaledValue(uint64_t signaledValue) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSignaledValue_), signaledValue); } _MTL_INLINE MTL::SharedEventHandle* MTL::SharedEventHandle::alloc() { return NS::Object::alloc<MTL::SharedEventHandle>(_MTL_PRIVATE_CLS(MTLSharedEventHandle)); } _MTL_INLINE MTL::SharedEventHandle* MTL::SharedEventHandle::init() { return NS::Object::init<MTL::SharedEventHandle>(); } _MTL_INLINE NS::String* MTL::SharedEventHandle::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } #pragma once namespace MTL { class Fence : public NS::Referencing<Fence> { public: class Device* device() const; NS::String* label() const; void setLabel(const NS::String* label); }; } _MTL_INLINE MTL::Device* MTL::Fence::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE NS::String* MTL::Fence::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::Fence::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } #pragma once namespace MTL { class FunctionConstantValues : public NS::Copying<FunctionConstantValues> { public: static class FunctionConstantValues* alloc(); class FunctionConstantValues* init(); void setConstantValue(const void* value, MTL::DataType type, NS::UInteger index); void setConstantValues(const void* values, MTL::DataType type, NS::Range range); void setConstantValue(const void* value, MTL::DataType type, const NS::String* name); void reset(); }; } _MTL_INLINE MTL::FunctionConstantValues* MTL::FunctionConstantValues::alloc() { return NS::Object::alloc<MTL::FunctionConstantValues>(_MTL_PRIVATE_CLS(MTLFunctionConstantValues)); } _MTL_INLINE MTL::FunctionConstantValues* MTL::FunctionConstantValues::init() { return NS::Object::init<MTL::FunctionConstantValues>(); } _MTL_INLINE void MTL::FunctionConstantValues::setConstantValue(const void* value, MTL::DataType type, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setConstantValue_type_atIndex_), value, type, index); } _MTL_INLINE void MTL::FunctionConstantValues::setConstantValues(const void* values, MTL::DataType type, NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setConstantValues_type_withRange_), values, type, range); } _MTL_INLINE void MTL::FunctionConstantValues::setConstantValue(const void* value, MTL::DataType type, const NS::String* name) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setConstantValue_type_withName_), value, type, name); } _MTL_INLINE void MTL::FunctionConstantValues::reset() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(reset)); } #pragma once namespace MTL { _MTL_OPTIONS(NS::UInteger, FunctionOptions) { FunctionOptionNone = 0, FunctionOptionCompileToBinary = 1, FunctionOptionStoreFunctionInMetalScript = 2, }; class FunctionDescriptor : public NS::Copying<FunctionDescriptor> { public: static class FunctionDescriptor* alloc(); class FunctionDescriptor* init(); static class FunctionDescriptor* functionDescriptor(); NS::String* name() const; void setName(const NS::String* name); NS::String* specializedName() const; void setSpecializedName(const NS::String* specializedName); class FunctionConstantValues* constantValues() const; void setConstantValues(const class FunctionConstantValues* constantValues); MTL::FunctionOptions options() const; void setOptions(MTL::FunctionOptions options); NS::Array* binaryArchives() const; void setBinaryArchives(const NS::Array* binaryArchives); }; class IntersectionFunctionDescriptor : public NS::Copying<IntersectionFunctionDescriptor, MTL::FunctionDescriptor> { public: static class IntersectionFunctionDescriptor* alloc(); class IntersectionFunctionDescriptor* init(); }; } _MTL_INLINE MTL::FunctionDescriptor* MTL::FunctionDescriptor::alloc() { return NS::Object::alloc<MTL::FunctionDescriptor>(_MTL_PRIVATE_CLS(MTLFunctionDescriptor)); } _MTL_INLINE MTL::FunctionDescriptor* MTL::FunctionDescriptor::init() { return NS::Object::init<MTL::FunctionDescriptor>(); } _MTL_INLINE MTL::FunctionDescriptor* MTL::FunctionDescriptor::functionDescriptor() { return Object::sendMessage<MTL::FunctionDescriptor*>(_MTL_PRIVATE_CLS(MTLFunctionDescriptor), _MTL_PRIVATE_SEL(functionDescriptor)); } _MTL_INLINE NS::String* MTL::FunctionDescriptor::name() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name)); } _MTL_INLINE void MTL::FunctionDescriptor::setName(const NS::String* name) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setName_), name); } _MTL_INLINE NS::String* MTL::FunctionDescriptor::specializedName() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(specializedName)); } _MTL_INLINE void MTL::FunctionDescriptor::setSpecializedName(const NS::String* specializedName) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSpecializedName_), specializedName); } _MTL_INLINE MTL::FunctionConstantValues* MTL::FunctionDescriptor::constantValues() const { return Object::sendMessage<MTL::FunctionConstantValues*>(this, _MTL_PRIVATE_SEL(constantValues)); } _MTL_INLINE void MTL::FunctionDescriptor::setConstantValues(const MTL::FunctionConstantValues* constantValues) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setConstantValues_), constantValues); } _MTL_INLINE MTL::FunctionOptions MTL::FunctionDescriptor::options() const { return Object::sendMessage<MTL::FunctionOptions>(this, _MTL_PRIVATE_SEL(options)); } _MTL_INLINE void MTL::FunctionDescriptor::setOptions(MTL::FunctionOptions options) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOptions_), options); } _MTL_INLINE NS::Array* MTL::FunctionDescriptor::binaryArchives() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(binaryArchives)); } _MTL_INLINE void MTL::FunctionDescriptor::setBinaryArchives(const NS::Array* binaryArchives) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBinaryArchives_), binaryArchives); } _MTL_INLINE MTL::IntersectionFunctionDescriptor* MTL::IntersectionFunctionDescriptor::alloc() { return NS::Object::alloc<MTL::IntersectionFunctionDescriptor>(_MTL_PRIVATE_CLS(MTLIntersectionFunctionDescriptor)); } _MTL_INLINE MTL::IntersectionFunctionDescriptor* MTL::IntersectionFunctionDescriptor::init() { return NS::Object::init<MTL::IntersectionFunctionDescriptor>(); } #pragma once #pragma once #include <functional> namespace MTL { _MTL_ENUM(NS::UInteger, PatchType) { PatchTypeNone = 0, PatchTypeTriangle = 1, PatchTypeQuad = 2, }; class VertexAttribute : public NS::Referencing<VertexAttribute> { public: static class VertexAttribute* alloc(); class VertexAttribute* init(); NS::String* name() const; NS::UInteger attributeIndex() const; MTL::DataType attributeType() const; bool active() const; bool patchData() const; bool patchControlPointData() const; }; class Attribute : public NS::Referencing<Attribute> { public: static class Attribute* alloc(); class Attribute* init(); NS::String* name() const; NS::UInteger attributeIndex() const; MTL::DataType attributeType() const; bool active() const; bool patchData() const; bool patchControlPointData() const; }; _MTL_ENUM(NS::UInteger, FunctionType) { FunctionTypeVertex = 1, FunctionTypeFragment = 2, FunctionTypeKernel = 3, FunctionTypeVisible = 5, FunctionTypeIntersection = 6, FunctionTypeMesh = 7, FunctionTypeObject = 8, }; class FunctionConstant : public NS::Referencing<FunctionConstant> { public: static class FunctionConstant* alloc(); class FunctionConstant* init(); NS::String* name() const; MTL::DataType type() const; NS::UInteger index() const; bool required() const; }; using AutoreleasedArgument = class Argument*; class Function : public NS::Referencing<Function> { public: NS::String* label() const; void setLabel(const NS::String* label); class Device* device() const; MTL::FunctionType functionType() const; MTL::PatchType patchType() const; NS::Integer patchControlPointCount() const; NS::Array* vertexAttributes() const; NS::Array* stageInputAttributes() const; NS::String* name() const; NS::Dictionary* functionConstantsDictionary() const; class ArgumentEncoder* newArgumentEncoder(NS::UInteger bufferIndex); class ArgumentEncoder* newArgumentEncoder(NS::UInteger bufferIndex, const MTL::AutoreleasedArgument* reflection); MTL::FunctionOptions options() const; }; _MTL_ENUM(NS::UInteger, LanguageVersion) { LanguageVersion1_0 = 65536, LanguageVersion1_1 = 65537, LanguageVersion1_2 = 65538, LanguageVersion2_0 = 131072, LanguageVersion2_1 = 131073, LanguageVersion2_2 = 131074, LanguageVersion2_3 = 131075, LanguageVersion2_4 = 131076, LanguageVersion3_0 = 196608, LanguageVersion3_1 = 196609, }; _MTL_ENUM(NS::Integer, LibraryType) { LibraryTypeExecutable = 0, LibraryTypeDynamic = 1, }; _MTL_ENUM(NS::Integer, LibraryOptimizationLevel) { LibraryOptimizationLevelDefault = 0, LibraryOptimizationLevelSize = 1, }; _MTL_ENUM(NS::Integer, CompileSymbolVisibility) { CompileSymbolVisibilityDefault = 0, CompileSymbolVisibilityHidden = 1, }; class CompileOptions : public NS::Copying<CompileOptions> { public: static class CompileOptions* alloc(); class CompileOptions* init(); NS::Dictionary* preprocessorMacros() const; void setPreprocessorMacros(const NS::Dictionary* preprocessorMacros); bool fastMathEnabled() const; void setFastMathEnabled(bool fastMathEnabled); MTL::LanguageVersion languageVersion() const; void setLanguageVersion(MTL::LanguageVersion languageVersion); MTL::LibraryType libraryType() const; void setLibraryType(MTL::LibraryType libraryType); NS::String* installName() const; void setInstallName(const NS::String* installName); NS::Array* libraries() const; void setLibraries(const NS::Array* libraries); bool preserveInvariance() const; void setPreserveInvariance(bool preserveInvariance); MTL::LibraryOptimizationLevel optimizationLevel() const; void setOptimizationLevel(MTL::LibraryOptimizationLevel optimizationLevel); MTL::CompileSymbolVisibility compileSymbolVisibility() const; void setCompileSymbolVisibility(MTL::CompileSymbolVisibility compileSymbolVisibility); bool allowReferencingUndefinedSymbols() const; void setAllowReferencingUndefinedSymbols(bool allowReferencingUndefinedSymbols); NS::UInteger maxTotalThreadsPerThreadgroup() const; void setMaxTotalThreadsPerThreadgroup(NS::UInteger maxTotalThreadsPerThreadgroup); }; _MTL_ENUM(NS::UInteger, LibraryError) { LibraryErrorUnsupported = 1, LibraryErrorInternal = 2, LibraryErrorCompileFailure = 3, LibraryErrorCompileWarning = 4, LibraryErrorFunctionNotFound = 5, LibraryErrorFileNotFound = 6, }; class Library : public NS::Referencing<Library> { public: void newFunction(const NS::String* pFunctionName, const class FunctionConstantValues* pConstantValues, const std::function<void(Function* pFunction, NS::Error* pError)>& completionHandler); void newFunction(const class FunctionDescriptor* pDescriptor, const std::function<void(Function* pFunction, NS::Error* pError)>& completionHandler); void newIntersectionFunction(const class IntersectionFunctionDescriptor* pDescriptor, const std::function<void(Function* pFunction, NS::Error* pError)>& completionHandler); NS::String* label() const; void setLabel(const NS::String* label); class Device* device() const; class Function* newFunction(const NS::String* functionName); class Function* newFunction(const NS::String* name, const class FunctionConstantValues* constantValues, NS::Error** error); void newFunction(const NS::String* name, const class FunctionConstantValues* constantValues, void (^completionHandler)(MTL::Function*, NS::Error*)); void newFunction(const class FunctionDescriptor* descriptor, void (^completionHandler)(MTL::Function*, NS::Error*)); class Function* newFunction(const class FunctionDescriptor* descriptor, NS::Error** error); void newIntersectionFunction(const class IntersectionFunctionDescriptor* descriptor, void (^completionHandler)(MTL::Function*, NS::Error*)); class Function* newIntersectionFunction(const class IntersectionFunctionDescriptor* descriptor, NS::Error** error); NS::Array* functionNames() const; MTL::LibraryType type() const; NS::String* installName() const; }; } _MTL_INLINE MTL::VertexAttribute* MTL::VertexAttribute::alloc() { return NS::Object::alloc<MTL::VertexAttribute>(_MTL_PRIVATE_CLS(MTLVertexAttribute)); } _MTL_INLINE MTL::VertexAttribute* MTL::VertexAttribute::init() { return NS::Object::init<MTL::VertexAttribute>(); } _MTL_INLINE NS::String* MTL::VertexAttribute::name() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name)); } _MTL_INLINE NS::UInteger MTL::VertexAttribute::attributeIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(attributeIndex)); } _MTL_INLINE MTL::DataType MTL::VertexAttribute::attributeType() const { return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(attributeType)); } _MTL_INLINE bool MTL::VertexAttribute::active() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isActive)); } _MTL_INLINE bool MTL::VertexAttribute::patchData() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isPatchData)); } _MTL_INLINE bool MTL::VertexAttribute::patchControlPointData() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isPatchControlPointData)); } _MTL_INLINE MTL::Attribute* MTL::Attribute::alloc() { return NS::Object::alloc<MTL::Attribute>(_MTL_PRIVATE_CLS(MTLAttribute)); } _MTL_INLINE MTL::Attribute* MTL::Attribute::init() { return NS::Object::init<MTL::Attribute>(); } _MTL_INLINE NS::String* MTL::Attribute::name() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name)); } _MTL_INLINE NS::UInteger MTL::Attribute::attributeIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(attributeIndex)); } _MTL_INLINE MTL::DataType MTL::Attribute::attributeType() const { return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(attributeType)); } _MTL_INLINE bool MTL::Attribute::active() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isActive)); } _MTL_INLINE bool MTL::Attribute::patchData() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isPatchData)); } _MTL_INLINE bool MTL::Attribute::patchControlPointData() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isPatchControlPointData)); } _MTL_INLINE MTL::FunctionConstant* MTL::FunctionConstant::alloc() { return NS::Object::alloc<MTL::FunctionConstant>(_MTL_PRIVATE_CLS(MTLFunctionConstant)); } _MTL_INLINE MTL::FunctionConstant* MTL::FunctionConstant::init() { return NS::Object::init<MTL::FunctionConstant>(); } _MTL_INLINE NS::String* MTL::FunctionConstant::name() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name)); } _MTL_INLINE MTL::DataType MTL::FunctionConstant::type() const { return Object::sendMessage<MTL::DataType>(this, _MTL_PRIVATE_SEL(type)); } _MTL_INLINE NS::UInteger MTL::FunctionConstant::index() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(index)); } _MTL_INLINE bool MTL::FunctionConstant::required() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(required)); } _MTL_INLINE NS::String* MTL::Function::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::Function::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE MTL::Device* MTL::Function::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE MTL::FunctionType MTL::Function::functionType() const { return Object::sendMessage<MTL::FunctionType>(this, _MTL_PRIVATE_SEL(functionType)); } _MTL_INLINE MTL::PatchType MTL::Function::patchType() const { return Object::sendMessage<MTL::PatchType>(this, _MTL_PRIVATE_SEL(patchType)); } _MTL_INLINE NS::Integer MTL::Function::patchControlPointCount() const { return Object::sendMessage<NS::Integer>(this, _MTL_PRIVATE_SEL(patchControlPointCount)); } _MTL_INLINE NS::Array* MTL::Function::vertexAttributes() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(vertexAttributes)); } _MTL_INLINE NS::Array* MTL::Function::stageInputAttributes() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(stageInputAttributes)); } _MTL_INLINE NS::String* MTL::Function::name() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name)); } _MTL_INLINE NS::Dictionary* MTL::Function::functionConstantsDictionary() const { return Object::sendMessage<NS::Dictionary*>(this, _MTL_PRIVATE_SEL(functionConstantsDictionary)); } _MTL_INLINE MTL::ArgumentEncoder* MTL::Function::newArgumentEncoder(NS::UInteger bufferIndex) { return Object::sendMessage<MTL::ArgumentEncoder*>(this, _MTL_PRIVATE_SEL(newArgumentEncoderWithBufferIndex_), bufferIndex); } _MTL_INLINE MTL::ArgumentEncoder* MTL::Function::newArgumentEncoder(NS::UInteger bufferIndex, const MTL::AutoreleasedArgument* reflection) { return Object::sendMessage<MTL::ArgumentEncoder*>(this, _MTL_PRIVATE_SEL(newArgumentEncoderWithBufferIndex_reflection_), bufferIndex, reflection); } _MTL_INLINE MTL::FunctionOptions MTL::Function::options() const { return Object::sendMessage<MTL::FunctionOptions>(this, _MTL_PRIVATE_SEL(options)); } _MTL_INLINE MTL::CompileOptions* MTL::CompileOptions::alloc() { return NS::Object::alloc<MTL::CompileOptions>(_MTL_PRIVATE_CLS(MTLCompileOptions)); } _MTL_INLINE MTL::CompileOptions* MTL::CompileOptions::init() { return NS::Object::init<MTL::CompileOptions>(); } _MTL_INLINE NS::Dictionary* MTL::CompileOptions::preprocessorMacros() const { return Object::sendMessage<NS::Dictionary*>(this, _MTL_PRIVATE_SEL(preprocessorMacros)); } _MTL_INLINE void MTL::CompileOptions::setPreprocessorMacros(const NS::Dictionary* preprocessorMacros) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPreprocessorMacros_), preprocessorMacros); } _MTL_INLINE bool MTL::CompileOptions::fastMathEnabled() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(fastMathEnabled)); } _MTL_INLINE void MTL::CompileOptions::setFastMathEnabled(bool fastMathEnabled) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFastMathEnabled_), fastMathEnabled); } _MTL_INLINE MTL::LanguageVersion MTL::CompileOptions::languageVersion() const { return Object::sendMessage<MTL::LanguageVersion>(this, _MTL_PRIVATE_SEL(languageVersion)); } _MTL_INLINE void MTL::CompileOptions::setLanguageVersion(MTL::LanguageVersion languageVersion) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLanguageVersion_), languageVersion); } _MTL_INLINE MTL::LibraryType MTL::CompileOptions::libraryType() const { return Object::sendMessage<MTL::LibraryType>(this, _MTL_PRIVATE_SEL(libraryType)); } _MTL_INLINE void MTL::CompileOptions::setLibraryType(MTL::LibraryType libraryType) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLibraryType_), libraryType); } _MTL_INLINE NS::String* MTL::CompileOptions::installName() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(installName)); } _MTL_INLINE void MTL::CompileOptions::setInstallName(const NS::String* installName) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInstallName_), installName); } _MTL_INLINE NS::Array* MTL::CompileOptions::libraries() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(libraries)); } _MTL_INLINE void MTL::CompileOptions::setLibraries(const NS::Array* libraries) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLibraries_), libraries); } _MTL_INLINE bool MTL::CompileOptions::preserveInvariance() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(preserveInvariance)); } _MTL_INLINE void MTL::CompileOptions::setPreserveInvariance(bool preserveInvariance) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPreserveInvariance_), preserveInvariance); } _MTL_INLINE MTL::LibraryOptimizationLevel MTL::CompileOptions::optimizationLevel() const { return Object::sendMessage<MTL::LibraryOptimizationLevel>(this, _MTL_PRIVATE_SEL(optimizationLevel)); } _MTL_INLINE void MTL::CompileOptions::setOptimizationLevel(MTL::LibraryOptimizationLevel optimizationLevel) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOptimizationLevel_), optimizationLevel); } _MTL_INLINE MTL::CompileSymbolVisibility MTL::CompileOptions::compileSymbolVisibility() const { return Object::sendMessage<MTL::CompileSymbolVisibility>(this, _MTL_PRIVATE_SEL(compileSymbolVisibility)); } _MTL_INLINE void MTL::CompileOptions::setCompileSymbolVisibility(MTL::CompileSymbolVisibility compileSymbolVisibility) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCompileSymbolVisibility_), compileSymbolVisibility); } _MTL_INLINE bool MTL::CompileOptions::allowReferencingUndefinedSymbols() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(allowReferencingUndefinedSymbols)); } _MTL_INLINE void MTL::CompileOptions::setAllowReferencingUndefinedSymbols(bool allowReferencingUndefinedSymbols) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAllowReferencingUndefinedSymbols_), allowReferencingUndefinedSymbols); } _MTL_INLINE NS::UInteger MTL::CompileOptions::maxTotalThreadsPerThreadgroup() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxTotalThreadsPerThreadgroup)); } _MTL_INLINE void MTL::CompileOptions::setMaxTotalThreadsPerThreadgroup(NS::UInteger maxTotalThreadsPerThreadgroup) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxTotalThreadsPerThreadgroup_), maxTotalThreadsPerThreadgroup); } _MTL_INLINE void MTL::Library::newFunction(const NS::String* pFunctionName, const FunctionConstantValues* pConstantValues, const std::function<void(Function* pFunction, NS::Error* pError)>& completionHandler) { __block std::function<void(Function * pFunction, NS::Error * pError)> blockCompletionHandler = completionHandler; newFunction(pFunctionName, pConstantValues, ^(Function* pFunction, NS::Error* pError) { blockCompletionHandler(pFunction, pError); }); } _MTL_INLINE void MTL::Library::newFunction(const FunctionDescriptor* pDescriptor, const std::function<void(Function* pFunction, NS::Error* pError)>& completionHandler) { __block std::function<void(Function * pFunction, NS::Error * pError)> blockCompletionHandler = completionHandler; newFunction(pDescriptor, ^(Function* pFunction, NS::Error* pError) { blockCompletionHandler(pFunction, pError); }); } _MTL_INLINE void MTL::Library::newIntersectionFunction(const IntersectionFunctionDescriptor* pDescriptor, const std::function<void(Function* pFunction, NS::Error* pError)>& completionHandler) { __block std::function<void(Function * pFunction, NS::Error * pError)> blockCompletionHandler = completionHandler; newIntersectionFunction(pDescriptor, ^(Function* pFunction, NS::Error* pError) { blockCompletionHandler(pFunction, pError); }); } _MTL_INLINE NS::String* MTL::Library::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::Library::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE MTL::Device* MTL::Library::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE MTL::Function* MTL::Library::newFunction(const NS::String* functionName) { return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(newFunctionWithName_), functionName); } _MTL_INLINE MTL::Function* MTL::Library::newFunction(const NS::String* name, const MTL::FunctionConstantValues* constantValues, NS::Error** error) { return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(newFunctionWithName_constantValues_error_), name, constantValues, error); } _MTL_INLINE void MTL::Library::newFunction(const NS::String* name, const MTL::FunctionConstantValues* constantValues, void (^completionHandler)(MTL::Function*, NS::Error*)) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newFunctionWithName_constantValues_completionHandler_), name, constantValues, completionHandler); } _MTL_INLINE void MTL::Library::newFunction(const MTL::FunctionDescriptor* descriptor, void (^completionHandler)(MTL::Function*, NS::Error*)) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newFunctionWithDescriptor_completionHandler_), descriptor, completionHandler); } _MTL_INLINE MTL::Function* MTL::Library::newFunction(const MTL::FunctionDescriptor* descriptor, NS::Error** error) { return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(newFunctionWithDescriptor_error_), descriptor, error); } _MTL_INLINE void MTL::Library::newIntersectionFunction(const MTL::IntersectionFunctionDescriptor* descriptor, void (^completionHandler)(MTL::Function*, NS::Error*)) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(newIntersectionFunctionWithDescriptor_completionHandler_), descriptor, completionHandler); } _MTL_INLINE MTL::Function* MTL::Library::newIntersectionFunction(const MTL::IntersectionFunctionDescriptor* descriptor, NS::Error** error) { return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(newIntersectionFunctionWithDescriptor_error_), descriptor, error); } _MTL_INLINE NS::Array* MTL::Library::functionNames() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(functionNames)); } _MTL_INLINE MTL::LibraryType MTL::Library::type() const { return Object::sendMessage<MTL::LibraryType>(this, _MTL_PRIVATE_SEL(type)); } _MTL_INLINE NS::String* MTL::Library::installName() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(installName)); } namespace MTL { class FunctionHandle : public NS::Referencing<FunctionHandle> { public: MTL::FunctionType functionType() const; NS::String* name() const; class Device* device() const; }; } _MTL_INLINE MTL::FunctionType MTL::FunctionHandle::functionType() const { return Object::sendMessage<MTL::FunctionType>(this, _MTL_PRIVATE_SEL(functionType)); } _MTL_INLINE NS::String* MTL::FunctionHandle::name() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name)); } _MTL_INLINE MTL::Device* MTL::FunctionHandle::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } #pragma once namespace MTL { _MTL_ENUM(NS::UInteger, FunctionLogType) { FunctionLogTypeValidation = 0, }; class LogContainer : public NS::Referencing<LogContainer, NS::FastEnumeration> { public: }; class FunctionLogDebugLocation : public NS::Referencing<FunctionLogDebugLocation> { public: NS::String* functionName() const; NS::URL* URL() const; NS::UInteger line() const; NS::UInteger column() const; }; class FunctionLog : public NS::Referencing<FunctionLog> { public: MTL::FunctionLogType type() const; NS::String* encoderLabel() const; class Function* function() const; class FunctionLogDebugLocation* debugLocation() const; }; } _MTL_INLINE NS::String* MTL::FunctionLogDebugLocation::functionName() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(functionName)); } _MTL_INLINE NS::URL* MTL::FunctionLogDebugLocation::URL() const { return Object::sendMessage<NS::URL*>(this, _MTL_PRIVATE_SEL(URL)); } _MTL_INLINE NS::UInteger MTL::FunctionLogDebugLocation::line() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(line)); } _MTL_INLINE NS::UInteger MTL::FunctionLogDebugLocation::column() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(column)); } _MTL_INLINE MTL::FunctionLogType MTL::FunctionLog::type() const { return Object::sendMessage<MTL::FunctionLogType>(this, _MTL_PRIVATE_SEL(type)); } _MTL_INLINE NS::String* MTL::FunctionLog::encoderLabel() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(encoderLabel)); } _MTL_INLINE MTL::Function* MTL::FunctionLog::function() const { return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(function)); } _MTL_INLINE MTL::FunctionLogDebugLocation* MTL::FunctionLog::debugLocation() const { return Object::sendMessage<MTL::FunctionLogDebugLocation*>(this, _MTL_PRIVATE_SEL(debugLocation)); } #pragma once namespace MTL { class FunctionStitchingAttribute : public NS::Referencing<FunctionStitchingAttribute> { public: }; class FunctionStitchingAttributeAlwaysInline : public NS::Referencing<FunctionStitchingAttributeAlwaysInline, FunctionStitchingAttribute> { public: static class FunctionStitchingAttributeAlwaysInline* alloc(); class FunctionStitchingAttributeAlwaysInline* init(); }; class FunctionStitchingNode : public NS::Copying<FunctionStitchingNode> { public: }; class FunctionStitchingInputNode : public NS::Referencing<FunctionStitchingInputNode, FunctionStitchingNode> { public: static class FunctionStitchingInputNode* alloc(); class FunctionStitchingInputNode* init(); NS::UInteger argumentIndex() const; void setArgumentIndex(NS::UInteger argumentIndex); MTL::FunctionStitchingInputNode* init(NS::UInteger argument); }; class FunctionStitchingFunctionNode : public NS::Referencing<FunctionStitchingFunctionNode, FunctionStitchingNode> { public: static class FunctionStitchingFunctionNode* alloc(); class FunctionStitchingFunctionNode* init(); NS::String* name() const; void setName(const NS::String* name); NS::Array* arguments() const; void setArguments(const NS::Array* arguments); NS::Array* controlDependencies() const; void setControlDependencies(const NS::Array* controlDependencies); MTL::FunctionStitchingFunctionNode* init(const NS::String* name, const NS::Array* arguments, const NS::Array* controlDependencies); }; class FunctionStitchingGraph : public NS::Copying<FunctionStitchingGraph> { public: static class FunctionStitchingGraph* alloc(); class FunctionStitchingGraph* init(); NS::String* functionName() const; void setFunctionName(const NS::String* functionName); NS::Array* nodes() const; void setNodes(const NS::Array* nodes); class FunctionStitchingFunctionNode* outputNode() const; void setOutputNode(const class FunctionStitchingFunctionNode* outputNode); NS::Array* attributes() const; void setAttributes(const NS::Array* attributes); MTL::FunctionStitchingGraph* init(const NS::String* functionName, const NS::Array* nodes, const class FunctionStitchingFunctionNode* outputNode, const NS::Array* attributes); }; class StitchedLibraryDescriptor : public NS::Copying<StitchedLibraryDescriptor> { public: static class StitchedLibraryDescriptor* alloc(); class StitchedLibraryDescriptor* init(); NS::Array* functionGraphs() const; void setFunctionGraphs(const NS::Array* functionGraphs); NS::Array* functions() const; void setFunctions(const NS::Array* functions); }; } _MTL_INLINE MTL::FunctionStitchingAttributeAlwaysInline* MTL::FunctionStitchingAttributeAlwaysInline::alloc() { return NS::Object::alloc<MTL::FunctionStitchingAttributeAlwaysInline>(_MTL_PRIVATE_CLS(MTLFunctionStitchingAttributeAlwaysInline)); } _MTL_INLINE MTL::FunctionStitchingAttributeAlwaysInline* MTL::FunctionStitchingAttributeAlwaysInline::init() { return NS::Object::init<MTL::FunctionStitchingAttributeAlwaysInline>(); } _MTL_INLINE MTL::FunctionStitchingInputNode* MTL::FunctionStitchingInputNode::alloc() { return NS::Object::alloc<MTL::FunctionStitchingInputNode>(_MTL_PRIVATE_CLS(MTLFunctionStitchingInputNode)); } _MTL_INLINE MTL::FunctionStitchingInputNode* MTL::FunctionStitchingInputNode::init() { return NS::Object::init<MTL::FunctionStitchingInputNode>(); } _MTL_INLINE NS::UInteger MTL::FunctionStitchingInputNode::argumentIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(argumentIndex)); } _MTL_INLINE void MTL::FunctionStitchingInputNode::setArgumentIndex(NS::UInteger argumentIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setArgumentIndex_), argumentIndex); } _MTL_INLINE MTL::FunctionStitchingInputNode* MTL::FunctionStitchingInputNode::init(NS::UInteger argument) { return Object::sendMessage<MTL::FunctionStitchingInputNode*>(this, _MTL_PRIVATE_SEL(initWithArgumentIndex_), argument); } _MTL_INLINE MTL::FunctionStitchingFunctionNode* MTL::FunctionStitchingFunctionNode::alloc() { return NS::Object::alloc<MTL::FunctionStitchingFunctionNode>(_MTL_PRIVATE_CLS(MTLFunctionStitchingFunctionNode)); } _MTL_INLINE MTL::FunctionStitchingFunctionNode* MTL::FunctionStitchingFunctionNode::init() { return NS::Object::init<MTL::FunctionStitchingFunctionNode>(); } _MTL_INLINE NS::String* MTL::FunctionStitchingFunctionNode::name() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(name)); } _MTL_INLINE void MTL::FunctionStitchingFunctionNode::setName(const NS::String* name) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setName_), name); } _MTL_INLINE NS::Array* MTL::FunctionStitchingFunctionNode::arguments() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(arguments)); } _MTL_INLINE void MTL::FunctionStitchingFunctionNode::setArguments(const NS::Array* arguments) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setArguments_), arguments); } _MTL_INLINE NS::Array* MTL::FunctionStitchingFunctionNode::controlDependencies() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(controlDependencies)); } _MTL_INLINE void MTL::FunctionStitchingFunctionNode::setControlDependencies(const NS::Array* controlDependencies) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setControlDependencies_), controlDependencies); } _MTL_INLINE MTL::FunctionStitchingFunctionNode* MTL::FunctionStitchingFunctionNode::init(const NS::String* name, const NS::Array* arguments, const NS::Array* controlDependencies) { return Object::sendMessage<MTL::FunctionStitchingFunctionNode*>(this, _MTL_PRIVATE_SEL(initWithName_arguments_controlDependencies_), name, arguments, controlDependencies); } _MTL_INLINE MTL::FunctionStitchingGraph* MTL::FunctionStitchingGraph::alloc() { return NS::Object::alloc<MTL::FunctionStitchingGraph>(_MTL_PRIVATE_CLS(MTLFunctionStitchingGraph)); } _MTL_INLINE MTL::FunctionStitchingGraph* MTL::FunctionStitchingGraph::init() { return NS::Object::init<MTL::FunctionStitchingGraph>(); } _MTL_INLINE NS::String* MTL::FunctionStitchingGraph::functionName() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(functionName)); } _MTL_INLINE void MTL::FunctionStitchingGraph::setFunctionName(const NS::String* functionName) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunctionName_), functionName); } _MTL_INLINE NS::Array* MTL::FunctionStitchingGraph::nodes() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(nodes)); } _MTL_INLINE void MTL::FunctionStitchingGraph::setNodes(const NS::Array* nodes) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setNodes_), nodes); } _MTL_INLINE MTL::FunctionStitchingFunctionNode* MTL::FunctionStitchingGraph::outputNode() const { return Object::sendMessage<MTL::FunctionStitchingFunctionNode*>(this, _MTL_PRIVATE_SEL(outputNode)); } _MTL_INLINE void MTL::FunctionStitchingGraph::setOutputNode(const MTL::FunctionStitchingFunctionNode* outputNode) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOutputNode_), outputNode); } _MTL_INLINE NS::Array* MTL::FunctionStitchingGraph::attributes() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(attributes)); } _MTL_INLINE void MTL::FunctionStitchingGraph::setAttributes(const NS::Array* attributes) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAttributes_), attributes); } _MTL_INLINE MTL::FunctionStitchingGraph* MTL::FunctionStitchingGraph::init(const NS::String* functionName, const NS::Array* nodes, const MTL::FunctionStitchingFunctionNode* outputNode, const NS::Array* attributes) { return Object::sendMessage<MTL::FunctionStitchingGraph*>(this, _MTL_PRIVATE_SEL(initWithFunctionName_nodes_outputNode_attributes_), functionName, nodes, outputNode, attributes); } _MTL_INLINE MTL::StitchedLibraryDescriptor* MTL::StitchedLibraryDescriptor::alloc() { return NS::Object::alloc<MTL::StitchedLibraryDescriptor>(_MTL_PRIVATE_CLS(MTLStitchedLibraryDescriptor)); } _MTL_INLINE MTL::StitchedLibraryDescriptor* MTL::StitchedLibraryDescriptor::init() { return NS::Object::init<MTL::StitchedLibraryDescriptor>(); } _MTL_INLINE NS::Array* MTL::StitchedLibraryDescriptor::functionGraphs() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(functionGraphs)); } _MTL_INLINE void MTL::StitchedLibraryDescriptor::setFunctionGraphs(const NS::Array* functionGraphs) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunctionGraphs_), functionGraphs); } _MTL_INLINE NS::Array* MTL::StitchedLibraryDescriptor::functions() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(functions)); } _MTL_INLINE void MTL::StitchedLibraryDescriptor::setFunctions(const NS::Array* functions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunctions_), functions); } #pragma once namespace MTL { _MTL_ENUM(NS::Integer, HeapType) { HeapTypeAutomatic = 0, HeapTypePlacement = 1, HeapTypeSparse = 2, }; class HeapDescriptor : public NS::Copying<HeapDescriptor> { public: static class HeapDescriptor* alloc(); class HeapDescriptor* init(); NS::UInteger size() const; void setSize(NS::UInteger size); MTL::StorageMode storageMode() const; void setStorageMode(MTL::StorageMode storageMode); MTL::CPUCacheMode cpuCacheMode() const; void setCpuCacheMode(MTL::CPUCacheMode cpuCacheMode); MTL::SparsePageSize sparsePageSize() const; void setSparsePageSize(MTL::SparsePageSize sparsePageSize); MTL::HazardTrackingMode hazardTrackingMode() const; void setHazardTrackingMode(MTL::HazardTrackingMode hazardTrackingMode); MTL::ResourceOptions resourceOptions() const; void setResourceOptions(MTL::ResourceOptions resourceOptions); MTL::HeapType type() const; void setType(MTL::HeapType type); }; class Heap : public NS::Referencing<Heap> { public: NS::String* label() const; void setLabel(const NS::String* label); class Device* device() const; MTL::StorageMode storageMode() const; MTL::CPUCacheMode cpuCacheMode() const; MTL::HazardTrackingMode hazardTrackingMode() const; MTL::ResourceOptions resourceOptions() const; NS::UInteger size() const; NS::UInteger usedSize() const; NS::UInteger currentAllocatedSize() const; NS::UInteger maxAvailableSize(NS::UInteger alignment); class Buffer* newBuffer(NS::UInteger length, MTL::ResourceOptions options); class Texture* newTexture(const class TextureDescriptor* descriptor); MTL::PurgeableState setPurgeableState(MTL::PurgeableState state); MTL::HeapType type() const; class Buffer* newBuffer(NS::UInteger length, MTL::ResourceOptions options, NS::UInteger offset); class Texture* newTexture(const class TextureDescriptor* descriptor, NS::UInteger offset); class AccelerationStructure* newAccelerationStructure(NS::UInteger size); class AccelerationStructure* newAccelerationStructure(const class AccelerationStructureDescriptor* descriptor); class AccelerationStructure* newAccelerationStructure(NS::UInteger size, NS::UInteger offset); class AccelerationStructure* newAccelerationStructure(const class AccelerationStructureDescriptor* descriptor, NS::UInteger offset); }; } _MTL_INLINE MTL::HeapDescriptor* MTL::HeapDescriptor::alloc() { return NS::Object::alloc<MTL::HeapDescriptor>(_MTL_PRIVATE_CLS(MTLHeapDescriptor)); } _MTL_INLINE MTL::HeapDescriptor* MTL::HeapDescriptor::init() { return NS::Object::init<MTL::HeapDescriptor>(); } _MTL_INLINE NS::UInteger MTL::HeapDescriptor::size() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(size)); } _MTL_INLINE void MTL::HeapDescriptor::setSize(NS::UInteger size) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSize_), size); } _MTL_INLINE MTL::StorageMode MTL::HeapDescriptor::storageMode() const { return Object::sendMessage<MTL::StorageMode>(this, _MTL_PRIVATE_SEL(storageMode)); } _MTL_INLINE void MTL::HeapDescriptor::setStorageMode(MTL::StorageMode storageMode) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStorageMode_), storageMode); } _MTL_INLINE MTL::CPUCacheMode MTL::HeapDescriptor::cpuCacheMode() const { return Object::sendMessage<MTL::CPUCacheMode>(this, _MTL_PRIVATE_SEL(cpuCacheMode)); } _MTL_INLINE void MTL::HeapDescriptor::setCpuCacheMode(MTL::CPUCacheMode cpuCacheMode) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCpuCacheMode_), cpuCacheMode); } _MTL_INLINE MTL::SparsePageSize MTL::HeapDescriptor::sparsePageSize() const { return Object::sendMessage<MTL::SparsePageSize>(this, _MTL_PRIVATE_SEL(sparsePageSize)); } _MTL_INLINE void MTL::HeapDescriptor::setSparsePageSize(MTL::SparsePageSize sparsePageSize) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSparsePageSize_), sparsePageSize); } _MTL_INLINE MTL::HazardTrackingMode MTL::HeapDescriptor::hazardTrackingMode() const { return Object::sendMessage<MTL::HazardTrackingMode>(this, _MTL_PRIVATE_SEL(hazardTrackingMode)); } _MTL_INLINE void MTL::HeapDescriptor::setHazardTrackingMode(MTL::HazardTrackingMode hazardTrackingMode) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setHazardTrackingMode_), hazardTrackingMode); } _MTL_INLINE MTL::ResourceOptions MTL::HeapDescriptor::resourceOptions() const { return Object::sendMessage<MTL::ResourceOptions>(this, _MTL_PRIVATE_SEL(resourceOptions)); } _MTL_INLINE void MTL::HeapDescriptor::setResourceOptions(MTL::ResourceOptions resourceOptions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setResourceOptions_), resourceOptions); } _MTL_INLINE MTL::HeapType MTL::HeapDescriptor::type() const { return Object::sendMessage<MTL::HeapType>(this, _MTL_PRIVATE_SEL(type)); } _MTL_INLINE void MTL::HeapDescriptor::setType(MTL::HeapType type) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setType_), type); } _MTL_INLINE NS::String* MTL::Heap::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::Heap::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE MTL::Device* MTL::Heap::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE MTL::StorageMode MTL::Heap::storageMode() const { return Object::sendMessage<MTL::StorageMode>(this, _MTL_PRIVATE_SEL(storageMode)); } _MTL_INLINE MTL::CPUCacheMode MTL::Heap::cpuCacheMode() const { return Object::sendMessage<MTL::CPUCacheMode>(this, _MTL_PRIVATE_SEL(cpuCacheMode)); } _MTL_INLINE MTL::HazardTrackingMode MTL::Heap::hazardTrackingMode() const { return Object::sendMessage<MTL::HazardTrackingMode>(this, _MTL_PRIVATE_SEL(hazardTrackingMode)); } _MTL_INLINE MTL::ResourceOptions MTL::Heap::resourceOptions() const { return Object::sendMessage<MTL::ResourceOptions>(this, _MTL_PRIVATE_SEL(resourceOptions)); } _MTL_INLINE NS::UInteger MTL::Heap::size() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(size)); } _MTL_INLINE NS::UInteger MTL::Heap::usedSize() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(usedSize)); } _MTL_INLINE NS::UInteger MTL::Heap::currentAllocatedSize() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(currentAllocatedSize)); } _MTL_INLINE NS::UInteger MTL::Heap::maxAvailableSize(NS::UInteger alignment) { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxAvailableSizeWithAlignment_), alignment); } _MTL_INLINE MTL::Buffer* MTL::Heap::newBuffer(NS::UInteger length, MTL::ResourceOptions options) { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(newBufferWithLength_options_), length, options); } _MTL_INLINE MTL::Texture* MTL::Heap::newTexture(const MTL::TextureDescriptor* descriptor) { return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newTextureWithDescriptor_), descriptor); } _MTL_INLINE MTL::PurgeableState MTL::Heap::setPurgeableState(MTL::PurgeableState state) { return Object::sendMessage<MTL::PurgeableState>(this, _MTL_PRIVATE_SEL(setPurgeableState_), state); } _MTL_INLINE MTL::HeapType MTL::Heap::type() const { return Object::sendMessage<MTL::HeapType>(this, _MTL_PRIVATE_SEL(type)); } _MTL_INLINE MTL::Buffer* MTL::Heap::newBuffer(NS::UInteger length, MTL::ResourceOptions options, NS::UInteger offset) { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(newBufferWithLength_options_offset_), length, options, offset); } _MTL_INLINE MTL::Texture* MTL::Heap::newTexture(const MTL::TextureDescriptor* descriptor, NS::UInteger offset) { return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(newTextureWithDescriptor_offset_), descriptor, offset); } _MTL_INLINE MTL::AccelerationStructure* MTL::Heap::newAccelerationStructure(NS::UInteger size) { return Object::sendMessage<MTL::AccelerationStructure*>(this, _MTL_PRIVATE_SEL(newAccelerationStructureWithSize_), size); } _MTL_INLINE MTL::AccelerationStructure* MTL::Heap::newAccelerationStructure(const MTL::AccelerationStructureDescriptor* descriptor) { return Object::sendMessage<MTL::AccelerationStructure*>(this, _MTL_PRIVATE_SEL(newAccelerationStructureWithDescriptor_), descriptor); } _MTL_INLINE MTL::AccelerationStructure* MTL::Heap::newAccelerationStructure(NS::UInteger size, NS::UInteger offset) { return Object::sendMessage<MTL::AccelerationStructure*>(this, _MTL_PRIVATE_SEL(newAccelerationStructureWithSize_offset_), size, offset); } _MTL_INLINE MTL::AccelerationStructure* MTL::Heap::newAccelerationStructure(const MTL::AccelerationStructureDescriptor* descriptor, NS::UInteger offset) { return Object::sendMessage<MTL::AccelerationStructure*>(this, _MTL_PRIVATE_SEL(newAccelerationStructureWithDescriptor_offset_), descriptor, offset); } #pragma once namespace MTL { _MTL_OPTIONS(NS::UInteger, IndirectCommandType) { IndirectCommandTypeDraw = 1, IndirectCommandTypeDrawIndexed = 2, IndirectCommandTypeDrawPatches = 4, IndirectCommandTypeDrawIndexedPatches = 8, IndirectCommandTypeConcurrentDispatch = 32, IndirectCommandTypeConcurrentDispatchThreads = 64, IndirectCommandTypeDrawMeshThreadgroups = 128, IndirectCommandTypeDrawMeshThreads = 256, }; struct IndirectCommandBufferExecutionRange { uint32_t location; uint32_t length; } _MTL_PACKED; class IndirectCommandBufferDescriptor : public NS::Copying<IndirectCommandBufferDescriptor> { public: static class IndirectCommandBufferDescriptor* alloc(); class IndirectCommandBufferDescriptor* init(); MTL::IndirectCommandType commandTypes() const; void setCommandTypes(MTL::IndirectCommandType commandTypes); bool inheritPipelineState() const; void setInheritPipelineState(bool inheritPipelineState); bool inheritBuffers() const; void setInheritBuffers(bool inheritBuffers); NS::UInteger maxVertexBufferBindCount() const; void setMaxVertexBufferBindCount(NS::UInteger maxVertexBufferBindCount); NS::UInteger maxFragmentBufferBindCount() const; void setMaxFragmentBufferBindCount(NS::UInteger maxFragmentBufferBindCount); NS::UInteger maxKernelBufferBindCount() const; void setMaxKernelBufferBindCount(NS::UInteger maxKernelBufferBindCount); NS::UInteger maxKernelThreadgroupMemoryBindCount() const; void setMaxKernelThreadgroupMemoryBindCount(NS::UInteger maxKernelThreadgroupMemoryBindCount); NS::UInteger maxObjectBufferBindCount() const; void setMaxObjectBufferBindCount(NS::UInteger maxObjectBufferBindCount); NS::UInteger maxMeshBufferBindCount() const; void setMaxMeshBufferBindCount(NS::UInteger maxMeshBufferBindCount); NS::UInteger maxObjectThreadgroupMemoryBindCount() const; void setMaxObjectThreadgroupMemoryBindCount(NS::UInteger maxObjectThreadgroupMemoryBindCount); bool supportRayTracing() const; void setSupportRayTracing(bool supportRayTracing); bool supportDynamicAttributeStride() const; void setSupportDynamicAttributeStride(bool supportDynamicAttributeStride); }; class IndirectCommandBuffer : public NS::Referencing<IndirectCommandBuffer, Resource> { public: NS::UInteger size() const; MTL::ResourceID gpuResourceID() const; void reset(NS::Range range); class IndirectRenderCommand* indirectRenderCommand(NS::UInteger commandIndex); class IndirectComputeCommand* indirectComputeCommand(NS::UInteger commandIndex); }; } _MTL_INLINE MTL::IndirectCommandBufferDescriptor* MTL::IndirectCommandBufferDescriptor::alloc() { return NS::Object::alloc<MTL::IndirectCommandBufferDescriptor>(_MTL_PRIVATE_CLS(MTLIndirectCommandBufferDescriptor)); } _MTL_INLINE MTL::IndirectCommandBufferDescriptor* MTL::IndirectCommandBufferDescriptor::init() { return NS::Object::init<MTL::IndirectCommandBufferDescriptor>(); } _MTL_INLINE MTL::IndirectCommandType MTL::IndirectCommandBufferDescriptor::commandTypes() const { return Object::sendMessage<MTL::IndirectCommandType>(this, _MTL_PRIVATE_SEL(commandTypes)); } _MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setCommandTypes(MTL::IndirectCommandType commandTypes) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCommandTypes_), commandTypes); } _MTL_INLINE bool MTL::IndirectCommandBufferDescriptor::inheritPipelineState() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(inheritPipelineState)); } _MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setInheritPipelineState(bool inheritPipelineState) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInheritPipelineState_), inheritPipelineState); } _MTL_INLINE bool MTL::IndirectCommandBufferDescriptor::inheritBuffers() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(inheritBuffers)); } _MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setInheritBuffers(bool inheritBuffers) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInheritBuffers_), inheritBuffers); } _MTL_INLINE NS::UInteger MTL::IndirectCommandBufferDescriptor::maxVertexBufferBindCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxVertexBufferBindCount)); } _MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setMaxVertexBufferBindCount(NS::UInteger maxVertexBufferBindCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxVertexBufferBindCount_), maxVertexBufferBindCount); } _MTL_INLINE NS::UInteger MTL::IndirectCommandBufferDescriptor::maxFragmentBufferBindCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxFragmentBufferBindCount)); } _MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setMaxFragmentBufferBindCount(NS::UInteger maxFragmentBufferBindCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxFragmentBufferBindCount_), maxFragmentBufferBindCount); } _MTL_INLINE NS::UInteger MTL::IndirectCommandBufferDescriptor::maxKernelBufferBindCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxKernelBufferBindCount)); } _MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setMaxKernelBufferBindCount(NS::UInteger maxKernelBufferBindCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxKernelBufferBindCount_), maxKernelBufferBindCount); } _MTL_INLINE NS::UInteger MTL::IndirectCommandBufferDescriptor::maxKernelThreadgroupMemoryBindCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxKernelThreadgroupMemoryBindCount)); } _MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setMaxKernelThreadgroupMemoryBindCount(NS::UInteger maxKernelThreadgroupMemoryBindCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxKernelThreadgroupMemoryBindCount_), maxKernelThreadgroupMemoryBindCount); } _MTL_INLINE NS::UInteger MTL::IndirectCommandBufferDescriptor::maxObjectBufferBindCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxObjectBufferBindCount)); } _MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setMaxObjectBufferBindCount(NS::UInteger maxObjectBufferBindCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxObjectBufferBindCount_), maxObjectBufferBindCount); } _MTL_INLINE NS::UInteger MTL::IndirectCommandBufferDescriptor::maxMeshBufferBindCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxMeshBufferBindCount)); } _MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setMaxMeshBufferBindCount(NS::UInteger maxMeshBufferBindCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxMeshBufferBindCount_), maxMeshBufferBindCount); } _MTL_INLINE NS::UInteger MTL::IndirectCommandBufferDescriptor::maxObjectThreadgroupMemoryBindCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxObjectThreadgroupMemoryBindCount)); } _MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setMaxObjectThreadgroupMemoryBindCount(NS::UInteger maxObjectThreadgroupMemoryBindCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxObjectThreadgroupMemoryBindCount_), maxObjectThreadgroupMemoryBindCount); } _MTL_INLINE bool MTL::IndirectCommandBufferDescriptor::supportRayTracing() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportRayTracing)); } _MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setSupportRayTracing(bool supportRayTracing) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSupportRayTracing_), supportRayTracing); } _MTL_INLINE bool MTL::IndirectCommandBufferDescriptor::supportDynamicAttributeStride() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportDynamicAttributeStride)); } _MTL_INLINE void MTL::IndirectCommandBufferDescriptor::setSupportDynamicAttributeStride(bool supportDynamicAttributeStride) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSupportDynamicAttributeStride_), supportDynamicAttributeStride); } _MTL_INLINE NS::UInteger MTL::IndirectCommandBuffer::size() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(size)); } _MTL_INLINE MTL::ResourceID MTL::IndirectCommandBuffer::gpuResourceID() const { return Object::sendMessage<MTL::ResourceID>(this, _MTL_PRIVATE_SEL(gpuResourceID)); } _MTL_INLINE void MTL::IndirectCommandBuffer::reset(NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(resetWithRange_), range); } _MTL_INLINE MTL::IndirectRenderCommand* MTL::IndirectCommandBuffer::indirectRenderCommand(NS::UInteger commandIndex) { return Object::sendMessage<MTL::IndirectRenderCommand*>(this, _MTL_PRIVATE_SEL(indirectRenderCommandAtIndex_), commandIndex); } _MTL_INLINE MTL::IndirectComputeCommand* MTL::IndirectCommandBuffer::indirectComputeCommand(NS::UInteger commandIndex) { return Object::sendMessage<MTL::IndirectComputeCommand*>(this, _MTL_PRIVATE_SEL(indirectComputeCommandAtIndex_), commandIndex); } #pragma once #pragma once #pragma once namespace MTL { struct ClearColor { static ClearColor Make(double red, double green, double blue, double alpha); ClearColor() = default; ClearColor(double red, double green, double blue, double alpha); double red; double green; double blue; double alpha; } _MTL_PACKED; _MTL_ENUM(NS::UInteger, LoadAction) { LoadActionDontCare = 0, LoadActionLoad = 1, LoadActionClear = 2, }; _MTL_ENUM(NS::UInteger, StoreAction) { StoreActionDontCare = 0, StoreActionStore = 1, StoreActionMultisampleResolve = 2, StoreActionStoreAndMultisampleResolve = 3, StoreActionUnknown = 4, StoreActionCustomSampleDepthStore = 5, }; _MTL_OPTIONS(NS::UInteger, StoreActionOptions) { StoreActionOptionNone = 0, StoreActionOptionCustomSamplePositions = 1, StoreActionOptionValidMask = 1, }; class RenderPassAttachmentDescriptor : public NS::Copying<RenderPassAttachmentDescriptor> { public: static class RenderPassAttachmentDescriptor* alloc(); class RenderPassAttachmentDescriptor* init(); class Texture* texture() const; void setTexture(const class Texture* texture); NS::UInteger level() const; void setLevel(NS::UInteger level); NS::UInteger slice() const; void setSlice(NS::UInteger slice); NS::UInteger depthPlane() const; void setDepthPlane(NS::UInteger depthPlane); class Texture* resolveTexture() const; void setResolveTexture(const class Texture* resolveTexture); NS::UInteger resolveLevel() const; void setResolveLevel(NS::UInteger resolveLevel); NS::UInteger resolveSlice() const; void setResolveSlice(NS::UInteger resolveSlice); NS::UInteger resolveDepthPlane() const; void setResolveDepthPlane(NS::UInteger resolveDepthPlane); MTL::LoadAction loadAction() const; void setLoadAction(MTL::LoadAction loadAction); MTL::StoreAction storeAction() const; void setStoreAction(MTL::StoreAction storeAction); MTL::StoreActionOptions storeActionOptions() const; void setStoreActionOptions(MTL::StoreActionOptions storeActionOptions); }; class RenderPassColorAttachmentDescriptor : public NS::Copying<RenderPassColorAttachmentDescriptor, MTL::RenderPassAttachmentDescriptor> { public: static class RenderPassColorAttachmentDescriptor* alloc(); class RenderPassColorAttachmentDescriptor* init(); MTL::ClearColor clearColor() const; void setClearColor(MTL::ClearColor clearColor); }; _MTL_ENUM(NS::UInteger, MultisampleDepthResolveFilter) { MultisampleDepthResolveFilterSample0 = 0, MultisampleDepthResolveFilterMin = 1, MultisampleDepthResolveFilterMax = 2, }; class RenderPassDepthAttachmentDescriptor : public NS::Copying<RenderPassDepthAttachmentDescriptor, MTL::RenderPassAttachmentDescriptor> { public: static class RenderPassDepthAttachmentDescriptor* alloc(); class RenderPassDepthAttachmentDescriptor* init(); double clearDepth() const; void setClearDepth(double clearDepth); MTL::MultisampleDepthResolveFilter depthResolveFilter() const; void setDepthResolveFilter(MTL::MultisampleDepthResolveFilter depthResolveFilter); }; _MTL_ENUM(NS::UInteger, MultisampleStencilResolveFilter) { MultisampleStencilResolveFilterSample0 = 0, MultisampleStencilResolveFilterDepthResolvedSample = 1, }; class RenderPassStencilAttachmentDescriptor : public NS::Copying<RenderPassStencilAttachmentDescriptor, MTL::RenderPassAttachmentDescriptor> { public: static class RenderPassStencilAttachmentDescriptor* alloc(); class RenderPassStencilAttachmentDescriptor* init(); uint32_t clearStencil() const; void setClearStencil(uint32_t clearStencil); MTL::MultisampleStencilResolveFilter stencilResolveFilter() const; void setStencilResolveFilter(MTL::MultisampleStencilResolveFilter stencilResolveFilter); }; class RenderPassColorAttachmentDescriptorArray : public NS::Referencing<RenderPassColorAttachmentDescriptorArray> { public: static class RenderPassColorAttachmentDescriptorArray* alloc(); class RenderPassColorAttachmentDescriptorArray* init(); class RenderPassColorAttachmentDescriptor* object(NS::UInteger attachmentIndex); void setObject(const class RenderPassColorAttachmentDescriptor* attachment, NS::UInteger attachmentIndex); }; class RenderPassSampleBufferAttachmentDescriptor : public NS::Copying<RenderPassSampleBufferAttachmentDescriptor> { public: static class RenderPassSampleBufferAttachmentDescriptor* alloc(); class RenderPassSampleBufferAttachmentDescriptor* init(); class CounterSampleBuffer* sampleBuffer() const; void setSampleBuffer(const class CounterSampleBuffer* sampleBuffer); NS::UInteger startOfVertexSampleIndex() const; void setStartOfVertexSampleIndex(NS::UInteger startOfVertexSampleIndex); NS::UInteger endOfVertexSampleIndex() const; void setEndOfVertexSampleIndex(NS::UInteger endOfVertexSampleIndex); NS::UInteger startOfFragmentSampleIndex() const; void setStartOfFragmentSampleIndex(NS::UInteger startOfFragmentSampleIndex); NS::UInteger endOfFragmentSampleIndex() const; void setEndOfFragmentSampleIndex(NS::UInteger endOfFragmentSampleIndex); }; class RenderPassSampleBufferAttachmentDescriptorArray : public NS::Referencing<RenderPassSampleBufferAttachmentDescriptorArray> { public: static class RenderPassSampleBufferAttachmentDescriptorArray* alloc(); class RenderPassSampleBufferAttachmentDescriptorArray* init(); class RenderPassSampleBufferAttachmentDescriptor* object(NS::UInteger attachmentIndex); void setObject(const class RenderPassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex); }; class RenderPassDescriptor : public NS::Copying<RenderPassDescriptor> { public: static class RenderPassDescriptor* alloc(); class RenderPassDescriptor* init(); static class RenderPassDescriptor* renderPassDescriptor(); class RenderPassColorAttachmentDescriptorArray* colorAttachments() const; class RenderPassDepthAttachmentDescriptor* depthAttachment() const; void setDepthAttachment(const class RenderPassDepthAttachmentDescriptor* depthAttachment); class RenderPassStencilAttachmentDescriptor* stencilAttachment() const; void setStencilAttachment(const class RenderPassStencilAttachmentDescriptor* stencilAttachment); class Buffer* visibilityResultBuffer() const; void setVisibilityResultBuffer(const class Buffer* visibilityResultBuffer); NS::UInteger renderTargetArrayLength() const; void setRenderTargetArrayLength(NS::UInteger renderTargetArrayLength); NS::UInteger imageblockSampleLength() const; void setImageblockSampleLength(NS::UInteger imageblockSampleLength); NS::UInteger threadgroupMemoryLength() const; void setThreadgroupMemoryLength(NS::UInteger threadgroupMemoryLength); NS::UInteger tileWidth() const; void setTileWidth(NS::UInteger tileWidth); NS::UInteger tileHeight() const; void setTileHeight(NS::UInteger tileHeight); NS::UInteger defaultRasterSampleCount() const; void setDefaultRasterSampleCount(NS::UInteger defaultRasterSampleCount); NS::UInteger renderTargetWidth() const; void setRenderTargetWidth(NS::UInteger renderTargetWidth); NS::UInteger renderTargetHeight() const; void setRenderTargetHeight(NS::UInteger renderTargetHeight); void setSamplePositions(const MTL::SamplePosition* positions, NS::UInteger count); NS::UInteger getSamplePositions(MTL::SamplePosition* positions, NS::UInteger count); class RasterizationRateMap* rasterizationRateMap() const; void setRasterizationRateMap(const class RasterizationRateMap* rasterizationRateMap); class RenderPassSampleBufferAttachmentDescriptorArray* sampleBufferAttachments() const; }; } _MTL_INLINE MTL::ClearColor MTL::ClearColor::Make(double red, double green, double blue, double alpha) { return ClearColor(red, green, blue, alpha); } _MTL_INLINE MTL::ClearColor::ClearColor(double _red, double _green, double _blue, double _alpha) : red(_red) , green(_green) , blue(_blue) , alpha(_alpha) { } _MTL_INLINE MTL::RenderPassAttachmentDescriptor* MTL::RenderPassAttachmentDescriptor::alloc() { return NS::Object::alloc<MTL::RenderPassAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPassAttachmentDescriptor)); } _MTL_INLINE MTL::RenderPassAttachmentDescriptor* MTL::RenderPassAttachmentDescriptor::init() { return NS::Object::init<MTL::RenderPassAttachmentDescriptor>(); } _MTL_INLINE MTL::Texture* MTL::RenderPassAttachmentDescriptor::texture() const { return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(texture)); } _MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setTexture(const MTL::Texture* texture) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTexture_), texture); } _MTL_INLINE NS::UInteger MTL::RenderPassAttachmentDescriptor::level() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(level)); } _MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setLevel(NS::UInteger level) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLevel_), level); } _MTL_INLINE NS::UInteger MTL::RenderPassAttachmentDescriptor::slice() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(slice)); } _MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setSlice(NS::UInteger slice) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSlice_), slice); } _MTL_INLINE NS::UInteger MTL::RenderPassAttachmentDescriptor::depthPlane() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(depthPlane)); } _MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setDepthPlane(NS::UInteger depthPlane) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthPlane_), depthPlane); } _MTL_INLINE MTL::Texture* MTL::RenderPassAttachmentDescriptor::resolveTexture() const { return Object::sendMessage<MTL::Texture*>(this, _MTL_PRIVATE_SEL(resolveTexture)); } _MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setResolveTexture(const MTL::Texture* resolveTexture) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setResolveTexture_), resolveTexture); } _MTL_INLINE NS::UInteger MTL::RenderPassAttachmentDescriptor::resolveLevel() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(resolveLevel)); } _MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setResolveLevel(NS::UInteger resolveLevel) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setResolveLevel_), resolveLevel); } _MTL_INLINE NS::UInteger MTL::RenderPassAttachmentDescriptor::resolveSlice() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(resolveSlice)); } _MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setResolveSlice(NS::UInteger resolveSlice) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setResolveSlice_), resolveSlice); } _MTL_INLINE NS::UInteger MTL::RenderPassAttachmentDescriptor::resolveDepthPlane() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(resolveDepthPlane)); } _MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setResolveDepthPlane(NS::UInteger resolveDepthPlane) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setResolveDepthPlane_), resolveDepthPlane); } _MTL_INLINE MTL::LoadAction MTL::RenderPassAttachmentDescriptor::loadAction() const { return Object::sendMessage<MTL::LoadAction>(this, _MTL_PRIVATE_SEL(loadAction)); } _MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setLoadAction(MTL::LoadAction loadAction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLoadAction_), loadAction); } _MTL_INLINE MTL::StoreAction MTL::RenderPassAttachmentDescriptor::storeAction() const { return Object::sendMessage<MTL::StoreAction>(this, _MTL_PRIVATE_SEL(storeAction)); } _MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setStoreAction(MTL::StoreAction storeAction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStoreAction_), storeAction); } _MTL_INLINE MTL::StoreActionOptions MTL::RenderPassAttachmentDescriptor::storeActionOptions() const { return Object::sendMessage<MTL::StoreActionOptions>(this, _MTL_PRIVATE_SEL(storeActionOptions)); } _MTL_INLINE void MTL::RenderPassAttachmentDescriptor::setStoreActionOptions(MTL::StoreActionOptions storeActionOptions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStoreActionOptions_), storeActionOptions); } _MTL_INLINE MTL::RenderPassColorAttachmentDescriptor* MTL::RenderPassColorAttachmentDescriptor::alloc() { return NS::Object::alloc<MTL::RenderPassColorAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPassColorAttachmentDescriptor)); } _MTL_INLINE MTL::RenderPassColorAttachmentDescriptor* MTL::RenderPassColorAttachmentDescriptor::init() { return NS::Object::init<MTL::RenderPassColorAttachmentDescriptor>(); } _MTL_INLINE MTL::ClearColor MTL::RenderPassColorAttachmentDescriptor::clearColor() const { return Object::sendMessage<MTL::ClearColor>(this, _MTL_PRIVATE_SEL(clearColor)); } _MTL_INLINE void MTL::RenderPassColorAttachmentDescriptor::setClearColor(MTL::ClearColor clearColor) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setClearColor_), clearColor); } _MTL_INLINE MTL::RenderPassDepthAttachmentDescriptor* MTL::RenderPassDepthAttachmentDescriptor::alloc() { return NS::Object::alloc<MTL::RenderPassDepthAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPassDepthAttachmentDescriptor)); } _MTL_INLINE MTL::RenderPassDepthAttachmentDescriptor* MTL::RenderPassDepthAttachmentDescriptor::init() { return NS::Object::init<MTL::RenderPassDepthAttachmentDescriptor>(); } _MTL_INLINE double MTL::RenderPassDepthAttachmentDescriptor::clearDepth() const { return Object::sendMessage<double>(this, _MTL_PRIVATE_SEL(clearDepth)); } _MTL_INLINE void MTL::RenderPassDepthAttachmentDescriptor::setClearDepth(double clearDepth) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setClearDepth_), clearDepth); } _MTL_INLINE MTL::MultisampleDepthResolveFilter MTL::RenderPassDepthAttachmentDescriptor::depthResolveFilter() const { return Object::sendMessage<MTL::MultisampleDepthResolveFilter>(this, _MTL_PRIVATE_SEL(depthResolveFilter)); } _MTL_INLINE void MTL::RenderPassDepthAttachmentDescriptor::setDepthResolveFilter(MTL::MultisampleDepthResolveFilter depthResolveFilter) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthResolveFilter_), depthResolveFilter); } _MTL_INLINE MTL::RenderPassStencilAttachmentDescriptor* MTL::RenderPassStencilAttachmentDescriptor::alloc() { return NS::Object::alloc<MTL::RenderPassStencilAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPassStencilAttachmentDescriptor)); } _MTL_INLINE MTL::RenderPassStencilAttachmentDescriptor* MTL::RenderPassStencilAttachmentDescriptor::init() { return NS::Object::init<MTL::RenderPassStencilAttachmentDescriptor>(); } _MTL_INLINE uint32_t MTL::RenderPassStencilAttachmentDescriptor::clearStencil() const { return Object::sendMessage<uint32_t>(this, _MTL_PRIVATE_SEL(clearStencil)); } _MTL_INLINE void MTL::RenderPassStencilAttachmentDescriptor::setClearStencil(uint32_t clearStencil) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setClearStencil_), clearStencil); } _MTL_INLINE MTL::MultisampleStencilResolveFilter MTL::RenderPassStencilAttachmentDescriptor::stencilResolveFilter() const { return Object::sendMessage<MTL::MultisampleStencilResolveFilter>(this, _MTL_PRIVATE_SEL(stencilResolveFilter)); } _MTL_INLINE void MTL::RenderPassStencilAttachmentDescriptor::setStencilResolveFilter(MTL::MultisampleStencilResolveFilter stencilResolveFilter) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilResolveFilter_), stencilResolveFilter); } _MTL_INLINE MTL::RenderPassColorAttachmentDescriptorArray* MTL::RenderPassColorAttachmentDescriptorArray::alloc() { return NS::Object::alloc<MTL::RenderPassColorAttachmentDescriptorArray>(_MTL_PRIVATE_CLS(MTLRenderPassColorAttachmentDescriptorArray)); } _MTL_INLINE MTL::RenderPassColorAttachmentDescriptorArray* MTL::RenderPassColorAttachmentDescriptorArray::init() { return NS::Object::init<MTL::RenderPassColorAttachmentDescriptorArray>(); } _MTL_INLINE MTL::RenderPassColorAttachmentDescriptor* MTL::RenderPassColorAttachmentDescriptorArray::object(NS::UInteger attachmentIndex) { return Object::sendMessage<MTL::RenderPassColorAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), attachmentIndex); } _MTL_INLINE void MTL::RenderPassColorAttachmentDescriptorArray::setObject(const MTL::RenderPassColorAttachmentDescriptor* attachment, NS::UInteger attachmentIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attachment, attachmentIndex); } _MTL_INLINE MTL::RenderPassSampleBufferAttachmentDescriptor* MTL::RenderPassSampleBufferAttachmentDescriptor::alloc() { return NS::Object::alloc<MTL::RenderPassSampleBufferAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPassSampleBufferAttachmentDescriptor)); } _MTL_INLINE MTL::RenderPassSampleBufferAttachmentDescriptor* MTL::RenderPassSampleBufferAttachmentDescriptor::init() { return NS::Object::init<MTL::RenderPassSampleBufferAttachmentDescriptor>(); } _MTL_INLINE MTL::CounterSampleBuffer* MTL::RenderPassSampleBufferAttachmentDescriptor::sampleBuffer() const { return Object::sendMessage<MTL::CounterSampleBuffer*>(this, _MTL_PRIVATE_SEL(sampleBuffer)); } _MTL_INLINE void MTL::RenderPassSampleBufferAttachmentDescriptor::setSampleBuffer(const MTL::CounterSampleBuffer* sampleBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSampleBuffer_), sampleBuffer); } _MTL_INLINE NS::UInteger MTL::RenderPassSampleBufferAttachmentDescriptor::startOfVertexSampleIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(startOfVertexSampleIndex)); } _MTL_INLINE void MTL::RenderPassSampleBufferAttachmentDescriptor::setStartOfVertexSampleIndex(NS::UInteger startOfVertexSampleIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStartOfVertexSampleIndex_), startOfVertexSampleIndex); } _MTL_INLINE NS::UInteger MTL::RenderPassSampleBufferAttachmentDescriptor::endOfVertexSampleIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(endOfVertexSampleIndex)); } _MTL_INLINE void MTL::RenderPassSampleBufferAttachmentDescriptor::setEndOfVertexSampleIndex(NS::UInteger endOfVertexSampleIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setEndOfVertexSampleIndex_), endOfVertexSampleIndex); } _MTL_INLINE NS::UInteger MTL::RenderPassSampleBufferAttachmentDescriptor::startOfFragmentSampleIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(startOfFragmentSampleIndex)); } _MTL_INLINE void MTL::RenderPassSampleBufferAttachmentDescriptor::setStartOfFragmentSampleIndex(NS::UInteger startOfFragmentSampleIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStartOfFragmentSampleIndex_), startOfFragmentSampleIndex); } _MTL_INLINE NS::UInteger MTL::RenderPassSampleBufferAttachmentDescriptor::endOfFragmentSampleIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(endOfFragmentSampleIndex)); } _MTL_INLINE void MTL::RenderPassSampleBufferAttachmentDescriptor::setEndOfFragmentSampleIndex(NS::UInteger endOfFragmentSampleIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setEndOfFragmentSampleIndex_), endOfFragmentSampleIndex); } _MTL_INLINE MTL::RenderPassSampleBufferAttachmentDescriptorArray* MTL::RenderPassSampleBufferAttachmentDescriptorArray::alloc() { return NS::Object::alloc<MTL::RenderPassSampleBufferAttachmentDescriptorArray>(_MTL_PRIVATE_CLS(MTLRenderPassSampleBufferAttachmentDescriptorArray)); } _MTL_INLINE MTL::RenderPassSampleBufferAttachmentDescriptorArray* MTL::RenderPassSampleBufferAttachmentDescriptorArray::init() { return NS::Object::init<MTL::RenderPassSampleBufferAttachmentDescriptorArray>(); } _MTL_INLINE MTL::RenderPassSampleBufferAttachmentDescriptor* MTL::RenderPassSampleBufferAttachmentDescriptorArray::object(NS::UInteger attachmentIndex) { return Object::sendMessage<MTL::RenderPassSampleBufferAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), attachmentIndex); } _MTL_INLINE void MTL::RenderPassSampleBufferAttachmentDescriptorArray::setObject(const MTL::RenderPassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attachment, attachmentIndex); } _MTL_INLINE MTL::RenderPassDescriptor* MTL::RenderPassDescriptor::alloc() { return NS::Object::alloc<MTL::RenderPassDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPassDescriptor)); } _MTL_INLINE MTL::RenderPassDescriptor* MTL::RenderPassDescriptor::init() { return NS::Object::init<MTL::RenderPassDescriptor>(); } _MTL_INLINE MTL::RenderPassDescriptor* MTL::RenderPassDescriptor::renderPassDescriptor() { return Object::sendMessage<MTL::RenderPassDescriptor*>(_MTL_PRIVATE_CLS(MTLRenderPassDescriptor), _MTL_PRIVATE_SEL(renderPassDescriptor)); } _MTL_INLINE MTL::RenderPassColorAttachmentDescriptorArray* MTL::RenderPassDescriptor::colorAttachments() const { return Object::sendMessage<MTL::RenderPassColorAttachmentDescriptorArray*>(this, _MTL_PRIVATE_SEL(colorAttachments)); } _MTL_INLINE MTL::RenderPassDepthAttachmentDescriptor* MTL::RenderPassDescriptor::depthAttachment() const { return Object::sendMessage<MTL::RenderPassDepthAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(depthAttachment)); } _MTL_INLINE void MTL::RenderPassDescriptor::setDepthAttachment(const MTL::RenderPassDepthAttachmentDescriptor* depthAttachment) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthAttachment_), depthAttachment); } _MTL_INLINE MTL::RenderPassStencilAttachmentDescriptor* MTL::RenderPassDescriptor::stencilAttachment() const { return Object::sendMessage<MTL::RenderPassStencilAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(stencilAttachment)); } _MTL_INLINE void MTL::RenderPassDescriptor::setStencilAttachment(const MTL::RenderPassStencilAttachmentDescriptor* stencilAttachment) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilAttachment_), stencilAttachment); } _MTL_INLINE MTL::Buffer* MTL::RenderPassDescriptor::visibilityResultBuffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(visibilityResultBuffer)); } _MTL_INLINE void MTL::RenderPassDescriptor::setVisibilityResultBuffer(const MTL::Buffer* visibilityResultBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVisibilityResultBuffer_), visibilityResultBuffer); } _MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::renderTargetArrayLength() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(renderTargetArrayLength)); } _MTL_INLINE void MTL::RenderPassDescriptor::setRenderTargetArrayLength(NS::UInteger renderTargetArrayLength) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRenderTargetArrayLength_), renderTargetArrayLength); } _MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::imageblockSampleLength() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(imageblockSampleLength)); } _MTL_INLINE void MTL::RenderPassDescriptor::setImageblockSampleLength(NS::UInteger imageblockSampleLength) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setImageblockSampleLength_), imageblockSampleLength); } _MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::threadgroupMemoryLength() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(threadgroupMemoryLength)); } _MTL_INLINE void MTL::RenderPassDescriptor::setThreadgroupMemoryLength(NS::UInteger threadgroupMemoryLength) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setThreadgroupMemoryLength_), threadgroupMemoryLength); } _MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::tileWidth() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(tileWidth)); } _MTL_INLINE void MTL::RenderPassDescriptor::setTileWidth(NS::UInteger tileWidth) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileWidth_), tileWidth); } _MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::tileHeight() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(tileHeight)); } _MTL_INLINE void MTL::RenderPassDescriptor::setTileHeight(NS::UInteger tileHeight) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileHeight_), tileHeight); } _MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::defaultRasterSampleCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(defaultRasterSampleCount)); } _MTL_INLINE void MTL::RenderPassDescriptor::setDefaultRasterSampleCount(NS::UInteger defaultRasterSampleCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDefaultRasterSampleCount_), defaultRasterSampleCount); } _MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::renderTargetWidth() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(renderTargetWidth)); } _MTL_INLINE void MTL::RenderPassDescriptor::setRenderTargetWidth(NS::UInteger renderTargetWidth) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRenderTargetWidth_), renderTargetWidth); } _MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::renderTargetHeight() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(renderTargetHeight)); } _MTL_INLINE void MTL::RenderPassDescriptor::setRenderTargetHeight(NS::UInteger renderTargetHeight) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRenderTargetHeight_), renderTargetHeight); } _MTL_INLINE void MTL::RenderPassDescriptor::setSamplePositions(const MTL::SamplePosition* positions, NS::UInteger count) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSamplePositions_count_), positions, count); } _MTL_INLINE NS::UInteger MTL::RenderPassDescriptor::getSamplePositions(MTL::SamplePosition* positions, NS::UInteger count) { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(getSamplePositions_count_), positions, count); } _MTL_INLINE MTL::RasterizationRateMap* MTL::RenderPassDescriptor::rasterizationRateMap() const { return Object::sendMessage<MTL::RasterizationRateMap*>(this, _MTL_PRIVATE_SEL(rasterizationRateMap)); } _MTL_INLINE void MTL::RenderPassDescriptor::setRasterizationRateMap(const MTL::RasterizationRateMap* rasterizationRateMap) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRasterizationRateMap_), rasterizationRateMap); } _MTL_INLINE MTL::RenderPassSampleBufferAttachmentDescriptorArray* MTL::RenderPassDescriptor::sampleBufferAttachments() const { return Object::sendMessage<MTL::RenderPassSampleBufferAttachmentDescriptorArray*>(this, _MTL_PRIVATE_SEL(sampleBufferAttachments)); } namespace MTL { _MTL_ENUM(NS::UInteger, PrimitiveType) { PrimitiveTypePoint = 0, PrimitiveTypeLine = 1, PrimitiveTypeLineStrip = 2, PrimitiveTypeTriangle = 3, PrimitiveTypeTriangleStrip = 4, }; _MTL_ENUM(NS::UInteger, VisibilityResultMode) { VisibilityResultModeDisabled = 0, VisibilityResultModeBoolean = 1, VisibilityResultModeCounting = 2, }; struct ScissorRect { NS::UInteger x; NS::UInteger y; NS::UInteger width; NS::UInteger height; } _MTL_PACKED; struct Viewport { double originX; double originY; double width; double height; double znear; double zfar; } _MTL_PACKED; _MTL_ENUM(NS::UInteger, CullMode) { CullModeNone = 0, CullModeFront = 1, CullModeBack = 2, }; _MTL_ENUM(NS::UInteger, Winding) { WindingClockwise = 0, WindingCounterClockwise = 1, }; _MTL_ENUM(NS::UInteger, DepthClipMode) { DepthClipModeClip = 0, DepthClipModeClamp = 1, }; _MTL_ENUM(NS::UInteger, TriangleFillMode) { TriangleFillModeFill = 0, TriangleFillModeLines = 1, }; struct DrawPrimitivesIndirectArguments { uint32_t vertexCount; uint32_t instanceCount; uint32_t vertexStart; uint32_t baseInstance; } _MTL_PACKED; struct DrawIndexedPrimitivesIndirectArguments { uint32_t indexCount; uint32_t instanceCount; uint32_t indexStart; int32_t baseVertex; uint32_t baseInstance; } _MTL_PACKED; struct VertexAmplificationViewMapping { uint32_t viewportArrayIndexOffset; uint32_t renderTargetArrayIndexOffset; } _MTL_PACKED; struct DrawPatchIndirectArguments { uint32_t patchCount; uint32_t instanceCount; uint32_t patchStart; uint32_t baseInstance; } _MTL_PACKED; struct QuadTessellationFactorsHalf { uint16_t edgeTessellationFactor[4]; uint16_t insideTessellationFactor[2]; } _MTL_PACKED; struct TriangleTessellationFactorsHalf { uint16_t edgeTessellationFactor[3]; uint16_t insideTessellationFactor; } _MTL_PACKED; _MTL_OPTIONS(NS::UInteger, RenderStages) { RenderStageVertex = 1, RenderStageFragment = 2, RenderStageTile = 4, RenderStageObject = 8, RenderStageMesh = 16, }; class RenderCommandEncoder : public NS::Referencing<RenderCommandEncoder, CommandEncoder> { public: void setRenderPipelineState(const class RenderPipelineState* pipelineState); void setVertexBytes(const void* bytes, NS::UInteger length, NS::UInteger index); void setVertexBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index); void setVertexBufferOffset(NS::UInteger offset, NS::UInteger index); void setVertexBuffers(const class Buffer* const buffers[], const NS::UInteger offsets[], NS::Range range); void setVertexBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger stride, NS::UInteger index); void setVertexBuffers(const class Buffer* const buffers[], const NS::UInteger* offsets, const NS::UInteger* strides, NS::Range range); void setVertexBufferOffset(NS::UInteger offset, NS::UInteger stride, NS::UInteger index); void setVertexBytes(const void* bytes, NS::UInteger length, NS::UInteger stride, NS::UInteger index); void setVertexTexture(const class Texture* texture, NS::UInteger index); void setVertexTextures(const class Texture* const textures[], NS::Range range); void setVertexSamplerState(const class SamplerState* sampler, NS::UInteger index); void setVertexSamplerStates(const class SamplerState* const samplers[], NS::Range range); void setVertexSamplerState(const class SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index); void setVertexSamplerStates(const class SamplerState* const samplers[], const float lodMinClamps[], const float lodMaxClamps[], NS::Range range); void setVertexVisibleFunctionTable(const class VisibleFunctionTable* functionTable, NS::UInteger bufferIndex); void setVertexVisibleFunctionTables(const class VisibleFunctionTable* const functionTables[], NS::Range range); void setVertexIntersectionFunctionTable(const class IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger bufferIndex); void setVertexIntersectionFunctionTables(const class IntersectionFunctionTable* const intersectionFunctionTables[], NS::Range range); void setVertexAccelerationStructure(const class AccelerationStructure* accelerationStructure, NS::UInteger bufferIndex); void setViewport(MTL::Viewport viewport); void setViewports(const MTL::Viewport* viewports, NS::UInteger count); void setFrontFacingWinding(MTL::Winding frontFacingWinding); void setVertexAmplificationCount(NS::UInteger count, const MTL::VertexAmplificationViewMapping* viewMappings); void setCullMode(MTL::CullMode cullMode); void setDepthClipMode(MTL::DepthClipMode depthClipMode); void setDepthBias(float depthBias, float slopeScale, float clamp); void setScissorRect(MTL::ScissorRect rect); void setScissorRects(const MTL::ScissorRect* scissorRects, NS::UInteger count); void setTriangleFillMode(MTL::TriangleFillMode fillMode); void setFragmentBytes(const void* bytes, NS::UInteger length, NS::UInteger index); void setFragmentBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index); void setFragmentBufferOffset(NS::UInteger offset, NS::UInteger index); void setFragmentBuffers(const class Buffer* const buffers[], const NS::UInteger offsets[], NS::Range range); void setFragmentTexture(const class Texture* texture, NS::UInteger index); void setFragmentTextures(const class Texture* const textures[], NS::Range range); void setFragmentSamplerState(const class SamplerState* sampler, NS::UInteger index); void setFragmentSamplerStates(const class SamplerState* const samplers[], NS::Range range); void setFragmentSamplerState(const class SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index); void setFragmentSamplerStates(const class SamplerState* const samplers[], const float lodMinClamps[], const float lodMaxClamps[], NS::Range range); void setFragmentVisibleFunctionTable(const class VisibleFunctionTable* functionTable, NS::UInteger bufferIndex); void setFragmentVisibleFunctionTables(const class VisibleFunctionTable* const functionTables[], NS::Range range); void setFragmentIntersectionFunctionTable(const class IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger bufferIndex); void setFragmentIntersectionFunctionTables(const class IntersectionFunctionTable* const intersectionFunctionTables[], NS::Range range); void setFragmentAccelerationStructure(const class AccelerationStructure* accelerationStructure, NS::UInteger bufferIndex); void setBlendColor(float red, float green, float blue, float alpha); void setDepthStencilState(const class DepthStencilState* depthStencilState); void setStencilReferenceValue(uint32_t referenceValue); void setStencilReferenceValues(uint32_t frontReferenceValue, uint32_t backReferenceValue); void setVisibilityResultMode(MTL::VisibilityResultMode mode, NS::UInteger offset); void setColorStoreAction(MTL::StoreAction storeAction, NS::UInteger colorAttachmentIndex); void setDepthStoreAction(MTL::StoreAction storeAction); void setStencilStoreAction(MTL::StoreAction storeAction); void setColorStoreActionOptions(MTL::StoreActionOptions storeActionOptions, NS::UInteger colorAttachmentIndex); void setDepthStoreActionOptions(MTL::StoreActionOptions storeActionOptions); void setStencilStoreActionOptions(MTL::StoreActionOptions storeActionOptions); void setObjectBytes(const void* bytes, NS::UInteger length, NS::UInteger index); void setObjectBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index); void setObjectBufferOffset(NS::UInteger offset, NS::UInteger index); void setObjectBuffers(const class Buffer* const buffers[], const NS::UInteger* offsets, NS::Range range); void setObjectTexture(const class Texture* texture, NS::UInteger index); void setObjectTextures(const class Texture* const textures[], NS::Range range); void setObjectSamplerState(const class SamplerState* sampler, NS::UInteger index); void setObjectSamplerStates(const class SamplerState* const samplers[], NS::Range range); void setObjectSamplerState(const class SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index); void setObjectSamplerStates(const class SamplerState* const samplers[], const float* lodMinClamps, const float* lodMaxClamps, NS::Range range); void setObjectThreadgroupMemoryLength(NS::UInteger length, NS::UInteger index); void setMeshBytes(const void* bytes, NS::UInteger length, NS::UInteger index); void setMeshBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index); void setMeshBufferOffset(NS::UInteger offset, NS::UInteger index); void setMeshBuffers(const class Buffer* const buffers[], const NS::UInteger* offsets, NS::Range range); void setMeshTexture(const class Texture* texture, NS::UInteger index); void setMeshTextures(const class Texture* const textures[], NS::Range range); void setMeshSamplerState(const class SamplerState* sampler, NS::UInteger index); void setMeshSamplerStates(const class SamplerState* const samplers[], NS::Range range); void setMeshSamplerState(const class SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index); void setMeshSamplerStates(const class SamplerState* const samplers[], const float* lodMinClamps, const float* lodMaxClamps, NS::Range range); void drawMeshThreadgroups(MTL::Size threadgroupsPerGrid, MTL::Size threadsPerObjectThreadgroup, MTL::Size threadsPerMeshThreadgroup); void drawMeshThreads(MTL::Size threadsPerGrid, MTL::Size threadsPerObjectThreadgroup, MTL::Size threadsPerMeshThreadgroup); void drawMeshThreadgroups(const class Buffer* indirectBuffer, NS::UInteger indirectBufferOffset, MTL::Size threadsPerObjectThreadgroup, MTL::Size threadsPerMeshThreadgroup); void drawPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger vertexStart, NS::UInteger vertexCount, NS::UInteger instanceCount); void drawPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger vertexStart, NS::UInteger vertexCount); void drawIndexedPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger indexCount, MTL::IndexType indexType, const class Buffer* indexBuffer, NS::UInteger indexBufferOffset, NS::UInteger instanceCount); void drawIndexedPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger indexCount, MTL::IndexType indexType, const class Buffer* indexBuffer, NS::UInteger indexBufferOffset); void drawPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger vertexStart, NS::UInteger vertexCount, NS::UInteger instanceCount, NS::UInteger baseInstance); void drawIndexedPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger indexCount, MTL::IndexType indexType, const class Buffer* indexBuffer, NS::UInteger indexBufferOffset, NS::UInteger instanceCount, NS::Integer baseVertex, NS::UInteger baseInstance); void drawPrimitives(MTL::PrimitiveType primitiveType, const class Buffer* indirectBuffer, NS::UInteger indirectBufferOffset); void drawIndexedPrimitives(MTL::PrimitiveType primitiveType, MTL::IndexType indexType, const class Buffer* indexBuffer, NS::UInteger indexBufferOffset, const class Buffer* indirectBuffer, NS::UInteger indirectBufferOffset); void textureBarrier(); void updateFence(const class Fence* fence, MTL::RenderStages stages); void waitForFence(const class Fence* fence, MTL::RenderStages stages); void setTessellationFactorBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger instanceStride); void setTessellationFactorScale(float scale); void drawPatches(NS::UInteger numberOfPatchControlPoints, NS::UInteger patchStart, NS::UInteger patchCount, const class Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, NS::UInteger instanceCount, NS::UInteger baseInstance); void drawPatches(NS::UInteger numberOfPatchControlPoints, const class Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, const class Buffer* indirectBuffer, NS::UInteger indirectBufferOffset); void drawIndexedPatches(NS::UInteger numberOfPatchControlPoints, NS::UInteger patchStart, NS::UInteger patchCount, const class Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, const class Buffer* controlPointIndexBuffer, NS::UInteger controlPointIndexBufferOffset, NS::UInteger instanceCount, NS::UInteger baseInstance); void drawIndexedPatches(NS::UInteger numberOfPatchControlPoints, const class Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, const class Buffer* controlPointIndexBuffer, NS::UInteger controlPointIndexBufferOffset, const class Buffer* indirectBuffer, NS::UInteger indirectBufferOffset); NS::UInteger tileWidth() const; NS::UInteger tileHeight() const; void setTileBytes(const void* bytes, NS::UInteger length, NS::UInteger index); void setTileBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index); void setTileBufferOffset(NS::UInteger offset, NS::UInteger index); void setTileBuffers(const class Buffer* const buffers[], const NS::UInteger* offsets, NS::Range range); void setTileTexture(const class Texture* texture, NS::UInteger index); void setTileTextures(const class Texture* const textures[], NS::Range range); void setTileSamplerState(const class SamplerState* sampler, NS::UInteger index); void setTileSamplerStates(const class SamplerState* const samplers[], NS::Range range); void setTileSamplerState(const class SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index); void setTileSamplerStates(const class SamplerState* const samplers[], const float lodMinClamps[], const float lodMaxClamps[], NS::Range range); void setTileVisibleFunctionTable(const class VisibleFunctionTable* functionTable, NS::UInteger bufferIndex); void setTileVisibleFunctionTables(const class VisibleFunctionTable* const functionTables[], NS::Range range); void setTileIntersectionFunctionTable(const class IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger bufferIndex); void setTileIntersectionFunctionTables(const class IntersectionFunctionTable* const intersectionFunctionTables[], NS::Range range); void setTileAccelerationStructure(const class AccelerationStructure* accelerationStructure, NS::UInteger bufferIndex); void dispatchThreadsPerTile(MTL::Size threadsPerTile); void setThreadgroupMemoryLength(NS::UInteger length, NS::UInteger offset, NS::UInteger index); void useResource(const class Resource* resource, MTL::ResourceUsage usage); void useResources(const class Resource* const resources[], NS::UInteger count, MTL::ResourceUsage usage); void useResource(const class Resource* resource, MTL::ResourceUsage usage, MTL::RenderStages stages); void useResources(const class Resource* const resources[], NS::UInteger count, MTL::ResourceUsage usage, MTL::RenderStages stages); void useHeap(const class Heap* heap); void useHeaps(const class Heap* const heaps[], NS::UInteger count); void useHeap(const class Heap* heap, MTL::RenderStages stages); void useHeaps(const class Heap* const heaps[], NS::UInteger count, MTL::RenderStages stages); void executeCommandsInBuffer(const class IndirectCommandBuffer* indirectCommandBuffer, NS::Range executionRange); void executeCommandsInBuffer(const class IndirectCommandBuffer* indirectCommandbuffer, const class Buffer* indirectRangeBuffer, NS::UInteger indirectBufferOffset); void memoryBarrier(MTL::BarrierScope scope, MTL::RenderStages after, MTL::RenderStages before); void memoryBarrier(const class Resource* const resources[], NS::UInteger count, MTL::RenderStages after, MTL::RenderStages before); void sampleCountersInBuffer(const class CounterSampleBuffer* sampleBuffer, NS::UInteger sampleIndex, bool barrier); }; } _MTL_INLINE void MTL::RenderCommandEncoder::setRenderPipelineState(const MTL::RenderPipelineState* pipelineState) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRenderPipelineState_), pipelineState); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexBytes(const void* bytes, NS::UInteger length, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBytes_length_atIndex_), bytes, length, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBuffer_offset_atIndex_), buffer, offset, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexBufferOffset(NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBufferOffset_atIndex_), offset, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexBuffers(const MTL::Buffer* const buffers[], const NS::UInteger offsets[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBuffers_offsets_withRange_), buffers, offsets, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger stride, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBuffer_offset_attributeStride_atIndex_), buffer, offset, stride, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexBuffers(const MTL::Buffer* const buffers[], const NS::UInteger* offsets, const NS::UInteger* strides, NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBuffers_offsets_attributeStrides_withRange_), buffers, offsets, strides, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexBufferOffset(NS::UInteger offset, NS::UInteger stride, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBufferOffset_attributeStride_atIndex_), offset, stride, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexBytes(const void* bytes, NS::UInteger length, NS::UInteger stride, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBytes_length_attributeStride_atIndex_), bytes, length, stride, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexTexture(const MTL::Texture* texture, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexTexture_atIndex_), texture, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexTextures(const MTL::Texture* const textures[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexTextures_withRange_), textures, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexSamplerState(const MTL::SamplerState* sampler, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexSamplerState_atIndex_), sampler, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexSamplerStates(const MTL::SamplerState* const samplers[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexSamplerStates_withRange_), samplers, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexSamplerState(const MTL::SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexSamplerState_lodMinClamp_lodMaxClamp_atIndex_), sampler, lodMinClamp, lodMaxClamp, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexSamplerStates(const MTL::SamplerState* const samplers[], const float lodMinClamps[], const float lodMaxClamps[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexSamplerStates_lodMinClamps_lodMaxClamps_withRange_), samplers, lodMinClamps, lodMaxClamps, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexVisibleFunctionTable(const MTL::VisibleFunctionTable* functionTable, NS::UInteger bufferIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexVisibleFunctionTable_atBufferIndex_), functionTable, bufferIndex); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexVisibleFunctionTables(const MTL::VisibleFunctionTable* const functionTables[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexVisibleFunctionTables_withBufferRange_), functionTables, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexIntersectionFunctionTable(const MTL::IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger bufferIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexIntersectionFunctionTable_atBufferIndex_), intersectionFunctionTable, bufferIndex); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexIntersectionFunctionTables(const MTL::IntersectionFunctionTable* const intersectionFunctionTables[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexIntersectionFunctionTables_withBufferRange_), intersectionFunctionTables, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexAccelerationStructure(const MTL::AccelerationStructure* accelerationStructure, NS::UInteger bufferIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexAccelerationStructure_atBufferIndex_), accelerationStructure, bufferIndex); } _MTL_INLINE void MTL::RenderCommandEncoder::setViewport(MTL::Viewport viewport) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setViewport_), viewport); } _MTL_INLINE void MTL::RenderCommandEncoder::setViewports(const MTL::Viewport* viewports, NS::UInteger count) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setViewports_count_), viewports, count); } _MTL_INLINE void MTL::RenderCommandEncoder::setFrontFacingWinding(MTL::Winding frontFacingWinding) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFrontFacingWinding_), frontFacingWinding); } _MTL_INLINE void MTL::RenderCommandEncoder::setVertexAmplificationCount(NS::UInteger count, const MTL::VertexAmplificationViewMapping* viewMappings) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexAmplificationCount_viewMappings_), count, viewMappings); } _MTL_INLINE void MTL::RenderCommandEncoder::setCullMode(MTL::CullMode cullMode) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCullMode_), cullMode); } _MTL_INLINE void MTL::RenderCommandEncoder::setDepthClipMode(MTL::DepthClipMode depthClipMode) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthClipMode_), depthClipMode); } _MTL_INLINE void MTL::RenderCommandEncoder::setDepthBias(float depthBias, float slopeScale, float clamp) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthBias_slopeScale_clamp_), depthBias, slopeScale, clamp); } _MTL_INLINE void MTL::RenderCommandEncoder::setScissorRect(MTL::ScissorRect rect) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setScissorRect_), rect); } _MTL_INLINE void MTL::RenderCommandEncoder::setScissorRects(const MTL::ScissorRect* scissorRects, NS::UInteger count) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setScissorRects_count_), scissorRects, count); } _MTL_INLINE void MTL::RenderCommandEncoder::setTriangleFillMode(MTL::TriangleFillMode fillMode) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTriangleFillMode_), fillMode); } _MTL_INLINE void MTL::RenderCommandEncoder::setFragmentBytes(const void* bytes, NS::UInteger length, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentBytes_length_atIndex_), bytes, length, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setFragmentBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentBuffer_offset_atIndex_), buffer, offset, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setFragmentBufferOffset(NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentBufferOffset_atIndex_), offset, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setFragmentBuffers(const MTL::Buffer* const buffers[], const NS::UInteger offsets[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentBuffers_offsets_withRange_), buffers, offsets, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setFragmentTexture(const MTL::Texture* texture, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentTexture_atIndex_), texture, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setFragmentTextures(const MTL::Texture* const textures[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentTextures_withRange_), textures, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setFragmentSamplerState(const MTL::SamplerState* sampler, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentSamplerState_atIndex_), sampler, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setFragmentSamplerStates(const MTL::SamplerState* const samplers[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentSamplerStates_withRange_), samplers, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setFragmentSamplerState(const MTL::SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentSamplerState_lodMinClamp_lodMaxClamp_atIndex_), sampler, lodMinClamp, lodMaxClamp, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setFragmentSamplerStates(const MTL::SamplerState* const samplers[], const float lodMinClamps[], const float lodMaxClamps[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentSamplerStates_lodMinClamps_lodMaxClamps_withRange_), samplers, lodMinClamps, lodMaxClamps, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setFragmentVisibleFunctionTable(const MTL::VisibleFunctionTable* functionTable, NS::UInteger bufferIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentVisibleFunctionTable_atBufferIndex_), functionTable, bufferIndex); } _MTL_INLINE void MTL::RenderCommandEncoder::setFragmentVisibleFunctionTables(const MTL::VisibleFunctionTable* const functionTables[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentVisibleFunctionTables_withBufferRange_), functionTables, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setFragmentIntersectionFunctionTable(const MTL::IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger bufferIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentIntersectionFunctionTable_atBufferIndex_), intersectionFunctionTable, bufferIndex); } _MTL_INLINE void MTL::RenderCommandEncoder::setFragmentIntersectionFunctionTables(const MTL::IntersectionFunctionTable* const intersectionFunctionTables[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentIntersectionFunctionTables_withBufferRange_), intersectionFunctionTables, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setFragmentAccelerationStructure(const MTL::AccelerationStructure* accelerationStructure, NS::UInteger bufferIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentAccelerationStructure_atBufferIndex_), accelerationStructure, bufferIndex); } _MTL_INLINE void MTL::RenderCommandEncoder::setBlendColor(float red, float green, float blue, float alpha) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBlendColorRed_green_blue_alpha_), red, green, blue, alpha); } _MTL_INLINE void MTL::RenderCommandEncoder::setDepthStencilState(const MTL::DepthStencilState* depthStencilState) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthStencilState_), depthStencilState); } _MTL_INLINE void MTL::RenderCommandEncoder::setStencilReferenceValue(uint32_t referenceValue) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilReferenceValue_), referenceValue); } _MTL_INLINE void MTL::RenderCommandEncoder::setStencilReferenceValues(uint32_t frontReferenceValue, uint32_t backReferenceValue) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilFrontReferenceValue_backReferenceValue_), frontReferenceValue, backReferenceValue); } _MTL_INLINE void MTL::RenderCommandEncoder::setVisibilityResultMode(MTL::VisibilityResultMode mode, NS::UInteger offset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVisibilityResultMode_offset_), mode, offset); } _MTL_INLINE void MTL::RenderCommandEncoder::setColorStoreAction(MTL::StoreAction storeAction, NS::UInteger colorAttachmentIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setColorStoreAction_atIndex_), storeAction, colorAttachmentIndex); } _MTL_INLINE void MTL::RenderCommandEncoder::setDepthStoreAction(MTL::StoreAction storeAction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthStoreAction_), storeAction); } _MTL_INLINE void MTL::RenderCommandEncoder::setStencilStoreAction(MTL::StoreAction storeAction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilStoreAction_), storeAction); } _MTL_INLINE void MTL::RenderCommandEncoder::setColorStoreActionOptions(MTL::StoreActionOptions storeActionOptions, NS::UInteger colorAttachmentIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setColorStoreActionOptions_atIndex_), storeActionOptions, colorAttachmentIndex); } _MTL_INLINE void MTL::RenderCommandEncoder::setDepthStoreActionOptions(MTL::StoreActionOptions storeActionOptions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthStoreActionOptions_), storeActionOptions); } _MTL_INLINE void MTL::RenderCommandEncoder::setStencilStoreActionOptions(MTL::StoreActionOptions storeActionOptions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilStoreActionOptions_), storeActionOptions); } _MTL_INLINE void MTL::RenderCommandEncoder::setObjectBytes(const void* bytes, NS::UInteger length, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObjectBytes_length_atIndex_), bytes, length, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setObjectBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObjectBuffer_offset_atIndex_), buffer, offset, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setObjectBufferOffset(NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObjectBufferOffset_atIndex_), offset, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setObjectBuffers(const MTL::Buffer* const buffers[], const NS::UInteger* offsets, NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObjectBuffers_offsets_withRange_), buffers, offsets, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setObjectTexture(const MTL::Texture* texture, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObjectTexture_atIndex_), texture, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setObjectTextures(const MTL::Texture* const textures[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObjectTextures_withRange_), textures, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setObjectSamplerState(const MTL::SamplerState* sampler, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObjectSamplerState_atIndex_), sampler, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setObjectSamplerStates(const MTL::SamplerState* const samplers[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObjectSamplerStates_withRange_), samplers, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setObjectSamplerState(const MTL::SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObjectSamplerState_lodMinClamp_lodMaxClamp_atIndex_), sampler, lodMinClamp, lodMaxClamp, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setObjectSamplerStates(const MTL::SamplerState* const samplers[], const float* lodMinClamps, const float* lodMaxClamps, NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObjectSamplerStates_lodMinClamps_lodMaxClamps_withRange_), samplers, lodMinClamps, lodMaxClamps, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setObjectThreadgroupMemoryLength(NS::UInteger length, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObjectThreadgroupMemoryLength_atIndex_), length, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setMeshBytes(const void* bytes, NS::UInteger length, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMeshBytes_length_atIndex_), bytes, length, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setMeshBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMeshBuffer_offset_atIndex_), buffer, offset, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setMeshBufferOffset(NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMeshBufferOffset_atIndex_), offset, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setMeshBuffers(const MTL::Buffer* const buffers[], const NS::UInteger* offsets, NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMeshBuffers_offsets_withRange_), buffers, offsets, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setMeshTexture(const MTL::Texture* texture, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMeshTexture_atIndex_), texture, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setMeshTextures(const MTL::Texture* const textures[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMeshTextures_withRange_), textures, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setMeshSamplerState(const MTL::SamplerState* sampler, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMeshSamplerState_atIndex_), sampler, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setMeshSamplerStates(const MTL::SamplerState* const samplers[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMeshSamplerStates_withRange_), samplers, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setMeshSamplerState(const MTL::SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMeshSamplerState_lodMinClamp_lodMaxClamp_atIndex_), sampler, lodMinClamp, lodMaxClamp, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setMeshSamplerStates(const MTL::SamplerState* const samplers[], const float* lodMinClamps, const float* lodMaxClamps, NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMeshSamplerStates_lodMinClamps_lodMaxClamps_withRange_), samplers, lodMinClamps, lodMaxClamps, range); } _MTL_INLINE void MTL::RenderCommandEncoder::drawMeshThreadgroups(MTL::Size threadgroupsPerGrid, MTL::Size threadsPerObjectThreadgroup, MTL::Size threadsPerMeshThreadgroup) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawMeshThreadgroups_threadsPerObjectThreadgroup_threadsPerMeshThreadgroup_), threadgroupsPerGrid, threadsPerObjectThreadgroup, threadsPerMeshThreadgroup); } _MTL_INLINE void MTL::RenderCommandEncoder::drawMeshThreads(MTL::Size threadsPerGrid, MTL::Size threadsPerObjectThreadgroup, MTL::Size threadsPerMeshThreadgroup) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawMeshThreads_threadsPerObjectThreadgroup_threadsPerMeshThreadgroup_), threadsPerGrid, threadsPerObjectThreadgroup, threadsPerMeshThreadgroup); } _MTL_INLINE void MTL::RenderCommandEncoder::drawMeshThreadgroups(const MTL::Buffer* indirectBuffer, NS::UInteger indirectBufferOffset, MTL::Size threadsPerObjectThreadgroup, MTL::Size threadsPerMeshThreadgroup) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawMeshThreadgroupsWithIndirectBuffer_indirectBufferOffset_threadsPerObjectThreadgroup_threadsPerMeshThreadgroup_), indirectBuffer, indirectBufferOffset, threadsPerObjectThreadgroup, threadsPerMeshThreadgroup); } _MTL_INLINE void MTL::RenderCommandEncoder::drawPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger vertexStart, NS::UInteger vertexCount, NS::UInteger instanceCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawPrimitives_vertexStart_vertexCount_instanceCount_), primitiveType, vertexStart, vertexCount, instanceCount); } _MTL_INLINE void MTL::RenderCommandEncoder::drawPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger vertexStart, NS::UInteger vertexCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawPrimitives_vertexStart_vertexCount_), primitiveType, vertexStart, vertexCount); } _MTL_INLINE void MTL::RenderCommandEncoder::drawIndexedPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger indexCount, MTL::IndexType indexType, const MTL::Buffer* indexBuffer, NS::UInteger indexBufferOffset, NS::UInteger instanceCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_instanceCount_), primitiveType, indexCount, indexType, indexBuffer, indexBufferOffset, instanceCount); } _MTL_INLINE void MTL::RenderCommandEncoder::drawIndexedPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger indexCount, MTL::IndexType indexType, const MTL::Buffer* indexBuffer, NS::UInteger indexBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_), primitiveType, indexCount, indexType, indexBuffer, indexBufferOffset); } _MTL_INLINE void MTL::RenderCommandEncoder::drawPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger vertexStart, NS::UInteger vertexCount, NS::UInteger instanceCount, NS::UInteger baseInstance) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance_), primitiveType, vertexStart, vertexCount, instanceCount, baseInstance); } _MTL_INLINE void MTL::RenderCommandEncoder::drawIndexedPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger indexCount, MTL::IndexType indexType, const MTL::Buffer* indexBuffer, NS::UInteger indexBufferOffset, NS::UInteger instanceCount, NS::Integer baseVertex, NS::UInteger baseInstance) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_instanceCount_baseVertex_baseInstance_), primitiveType, indexCount, indexType, indexBuffer, indexBufferOffset, instanceCount, baseVertex, baseInstance); } _MTL_INLINE void MTL::RenderCommandEncoder::drawPrimitives(MTL::PrimitiveType primitiveType, const MTL::Buffer* indirectBuffer, NS::UInteger indirectBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawPrimitives_indirectBuffer_indirectBufferOffset_), primitiveType, indirectBuffer, indirectBufferOffset); } _MTL_INLINE void MTL::RenderCommandEncoder::drawIndexedPrimitives(MTL::PrimitiveType primitiveType, MTL::IndexType indexType, const MTL::Buffer* indexBuffer, NS::UInteger indexBufferOffset, const MTL::Buffer* indirectBuffer, NS::UInteger indirectBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawIndexedPrimitives_indexType_indexBuffer_indexBufferOffset_indirectBuffer_indirectBufferOffset_), primitiveType, indexType, indexBuffer, indexBufferOffset, indirectBuffer, indirectBufferOffset); } _MTL_INLINE void MTL::RenderCommandEncoder::textureBarrier() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(textureBarrier)); } _MTL_INLINE void MTL::RenderCommandEncoder::updateFence(const MTL::Fence* fence, MTL::RenderStages stages) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(updateFence_afterStages_), fence, stages); } _MTL_INLINE void MTL::RenderCommandEncoder::waitForFence(const MTL::Fence* fence, MTL::RenderStages stages) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(waitForFence_beforeStages_), fence, stages); } _MTL_INLINE void MTL::RenderCommandEncoder::setTessellationFactorBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger instanceStride) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTessellationFactorBuffer_offset_instanceStride_), buffer, offset, instanceStride); } _MTL_INLINE void MTL::RenderCommandEncoder::setTessellationFactorScale(float scale) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTessellationFactorScale_), scale); } _MTL_INLINE void MTL::RenderCommandEncoder::drawPatches(NS::UInteger numberOfPatchControlPoints, NS::UInteger patchStart, NS::UInteger patchCount, const MTL::Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, NS::UInteger instanceCount, NS::UInteger baseInstance) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawPatches_patchStart_patchCount_patchIndexBuffer_patchIndexBufferOffset_instanceCount_baseInstance_), numberOfPatchControlPoints, patchStart, patchCount, patchIndexBuffer, patchIndexBufferOffset, instanceCount, baseInstance); } _MTL_INLINE void MTL::RenderCommandEncoder::drawPatches(NS::UInteger numberOfPatchControlPoints, const MTL::Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, const MTL::Buffer* indirectBuffer, NS::UInteger indirectBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawPatches_patchIndexBuffer_patchIndexBufferOffset_indirectBuffer_indirectBufferOffset_), numberOfPatchControlPoints, patchIndexBuffer, patchIndexBufferOffset, indirectBuffer, indirectBufferOffset); } _MTL_INLINE void MTL::RenderCommandEncoder::drawIndexedPatches(NS::UInteger numberOfPatchControlPoints, NS::UInteger patchStart, NS::UInteger patchCount, const MTL::Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, const MTL::Buffer* controlPointIndexBuffer, NS::UInteger controlPointIndexBufferOffset, NS::UInteger instanceCount, NS::UInteger baseInstance) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawIndexedPatches_patchStart_patchCount_patchIndexBuffer_patchIndexBufferOffset_controlPointIndexBuffer_controlPointIndexBufferOffset_instanceCount_baseInstance_), numberOfPatchControlPoints, patchStart, patchCount, patchIndexBuffer, patchIndexBufferOffset, controlPointIndexBuffer, controlPointIndexBufferOffset, instanceCount, baseInstance); } _MTL_INLINE void MTL::RenderCommandEncoder::drawIndexedPatches(NS::UInteger numberOfPatchControlPoints, const MTL::Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, const MTL::Buffer* controlPointIndexBuffer, NS::UInteger controlPointIndexBufferOffset, const MTL::Buffer* indirectBuffer, NS::UInteger indirectBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawIndexedPatches_patchIndexBuffer_patchIndexBufferOffset_controlPointIndexBuffer_controlPointIndexBufferOffset_indirectBuffer_indirectBufferOffset_), numberOfPatchControlPoints, patchIndexBuffer, patchIndexBufferOffset, controlPointIndexBuffer, controlPointIndexBufferOffset, indirectBuffer, indirectBufferOffset); } _MTL_INLINE NS::UInteger MTL::RenderCommandEncoder::tileWidth() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(tileWidth)); } _MTL_INLINE NS::UInteger MTL::RenderCommandEncoder::tileHeight() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(tileHeight)); } _MTL_INLINE void MTL::RenderCommandEncoder::setTileBytes(const void* bytes, NS::UInteger length, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileBytes_length_atIndex_), bytes, length, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setTileBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileBuffer_offset_atIndex_), buffer, offset, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setTileBufferOffset(NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileBufferOffset_atIndex_), offset, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setTileBuffers(const MTL::Buffer* const buffers[], const NS::UInteger* offsets, NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileBuffers_offsets_withRange_), buffers, offsets, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setTileTexture(const MTL::Texture* texture, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileTexture_atIndex_), texture, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setTileTextures(const MTL::Texture* const textures[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileTextures_withRange_), textures, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setTileSamplerState(const MTL::SamplerState* sampler, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileSamplerState_atIndex_), sampler, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setTileSamplerStates(const MTL::SamplerState* const samplers[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileSamplerStates_withRange_), samplers, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setTileSamplerState(const MTL::SamplerState* sampler, float lodMinClamp, float lodMaxClamp, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileSamplerState_lodMinClamp_lodMaxClamp_atIndex_), sampler, lodMinClamp, lodMaxClamp, index); } _MTL_INLINE void MTL::RenderCommandEncoder::setTileSamplerStates(const MTL::SamplerState* const samplers[], const float lodMinClamps[], const float lodMaxClamps[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileSamplerStates_lodMinClamps_lodMaxClamps_withRange_), samplers, lodMinClamps, lodMaxClamps, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setTileVisibleFunctionTable(const MTL::VisibleFunctionTable* functionTable, NS::UInteger bufferIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileVisibleFunctionTable_atBufferIndex_), functionTable, bufferIndex); } _MTL_INLINE void MTL::RenderCommandEncoder::setTileVisibleFunctionTables(const MTL::VisibleFunctionTable* const functionTables[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileVisibleFunctionTables_withBufferRange_), functionTables, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setTileIntersectionFunctionTable(const MTL::IntersectionFunctionTable* intersectionFunctionTable, NS::UInteger bufferIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileIntersectionFunctionTable_atBufferIndex_), intersectionFunctionTable, bufferIndex); } _MTL_INLINE void MTL::RenderCommandEncoder::setTileIntersectionFunctionTables(const MTL::IntersectionFunctionTable* const intersectionFunctionTables[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileIntersectionFunctionTables_withBufferRange_), intersectionFunctionTables, range); } _MTL_INLINE void MTL::RenderCommandEncoder::setTileAccelerationStructure(const MTL::AccelerationStructure* accelerationStructure, NS::UInteger bufferIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileAccelerationStructure_atBufferIndex_), accelerationStructure, bufferIndex); } _MTL_INLINE void MTL::RenderCommandEncoder::dispatchThreadsPerTile(MTL::Size threadsPerTile) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(dispatchThreadsPerTile_), threadsPerTile); } _MTL_INLINE void MTL::RenderCommandEncoder::setThreadgroupMemoryLength(NS::UInteger length, NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setThreadgroupMemoryLength_offset_atIndex_), length, offset, index); } _MTL_INLINE void MTL::RenderCommandEncoder::useResource(const MTL::Resource* resource, MTL::ResourceUsage usage) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useResource_usage_), resource, usage); } _MTL_INLINE void MTL::RenderCommandEncoder::useResources(const MTL::Resource* const resources[], NS::UInteger count, MTL::ResourceUsage usage) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useResources_count_usage_), resources, count, usage); } _MTL_INLINE void MTL::RenderCommandEncoder::useResource(const MTL::Resource* resource, MTL::ResourceUsage usage, MTL::RenderStages stages) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useResource_usage_stages_), resource, usage, stages); } _MTL_INLINE void MTL::RenderCommandEncoder::useResources(const MTL::Resource* const resources[], NS::UInteger count, MTL::ResourceUsage usage, MTL::RenderStages stages) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useResources_count_usage_stages_), resources, count, usage, stages); } _MTL_INLINE void MTL::RenderCommandEncoder::useHeap(const MTL::Heap* heap) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useHeap_), heap); } _MTL_INLINE void MTL::RenderCommandEncoder::useHeaps(const MTL::Heap* const heaps[], NS::UInteger count) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useHeaps_count_), heaps, count); } _MTL_INLINE void MTL::RenderCommandEncoder::useHeap(const MTL::Heap* heap, MTL::RenderStages stages) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useHeap_stages_), heap, stages); } _MTL_INLINE void MTL::RenderCommandEncoder::useHeaps(const MTL::Heap* const heaps[], NS::UInteger count, MTL::RenderStages stages) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(useHeaps_count_stages_), heaps, count, stages); } _MTL_INLINE void MTL::RenderCommandEncoder::executeCommandsInBuffer(const MTL::IndirectCommandBuffer* indirectCommandBuffer, NS::Range executionRange) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(executeCommandsInBuffer_withRange_), indirectCommandBuffer, executionRange); } _MTL_INLINE void MTL::RenderCommandEncoder::executeCommandsInBuffer(const MTL::IndirectCommandBuffer* indirectCommandbuffer, const MTL::Buffer* indirectRangeBuffer, NS::UInteger indirectBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(executeCommandsInBuffer_indirectBuffer_indirectBufferOffset_), indirectCommandbuffer, indirectRangeBuffer, indirectBufferOffset); } _MTL_INLINE void MTL::RenderCommandEncoder::memoryBarrier(MTL::BarrierScope scope, MTL::RenderStages after, MTL::RenderStages before) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(memoryBarrierWithScope_afterStages_beforeStages_), scope, after, before); } _MTL_INLINE void MTL::RenderCommandEncoder::memoryBarrier(const MTL::Resource* const resources[], NS::UInteger count, MTL::RenderStages after, MTL::RenderStages before) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(memoryBarrierWithResources_count_afterStages_beforeStages_), resources, count, after, before); } _MTL_INLINE void MTL::RenderCommandEncoder::sampleCountersInBuffer(const MTL::CounterSampleBuffer* sampleBuffer, NS::UInteger sampleIndex, bool barrier) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(sampleCountersInBuffer_atSampleIndex_withBarrier_), sampleBuffer, sampleIndex, barrier); } namespace MTL { class IndirectRenderCommand : public NS::Referencing<IndirectRenderCommand> { public: void setRenderPipelineState(const class RenderPipelineState* pipelineState); void setVertexBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index); void setFragmentBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index); void setVertexBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger stride, NS::UInteger index); void drawPatches(NS::UInteger numberOfPatchControlPoints, NS::UInteger patchStart, NS::UInteger patchCount, const class Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, NS::UInteger instanceCount, NS::UInteger baseInstance, const class Buffer* buffer, NS::UInteger offset, NS::UInteger instanceStride); void drawIndexedPatches(NS::UInteger numberOfPatchControlPoints, NS::UInteger patchStart, NS::UInteger patchCount, const class Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, const class Buffer* controlPointIndexBuffer, NS::UInteger controlPointIndexBufferOffset, NS::UInteger instanceCount, NS::UInteger baseInstance, const class Buffer* buffer, NS::UInteger offset, NS::UInteger instanceStride); void drawPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger vertexStart, NS::UInteger vertexCount, NS::UInteger instanceCount, NS::UInteger baseInstance); void drawIndexedPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger indexCount, MTL::IndexType indexType, const class Buffer* indexBuffer, NS::UInteger indexBufferOffset, NS::UInteger instanceCount, NS::Integer baseVertex, NS::UInteger baseInstance); void setObjectThreadgroupMemoryLength(NS::UInteger length, NS::UInteger index); void setObjectBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index); void setMeshBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index); void drawMeshThreadgroups(MTL::Size threadgroupsPerGrid, MTL::Size threadsPerObjectThreadgroup, MTL::Size threadsPerMeshThreadgroup); void drawMeshThreads(MTL::Size threadsPerGrid, MTL::Size threadsPerObjectThreadgroup, MTL::Size threadsPerMeshThreadgroup); void setBarrier(); void clearBarrier(); void reset(); }; class IndirectComputeCommand : public NS::Referencing<IndirectComputeCommand> { public: void setComputePipelineState(const class ComputePipelineState* pipelineState); void setKernelBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index); void setKernelBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger stride, NS::UInteger index); void concurrentDispatchThreadgroups(MTL::Size threadgroupsPerGrid, MTL::Size threadsPerThreadgroup); void concurrentDispatchThreads(MTL::Size threadsPerGrid, MTL::Size threadsPerThreadgroup); void setBarrier(); void clearBarrier(); void setImageblockWidth(NS::UInteger width, NS::UInteger height); void reset(); void setThreadgroupMemoryLength(NS::UInteger length, NS::UInteger index); void setStageInRegion(MTL::Region region); }; } _MTL_INLINE void MTL::IndirectRenderCommand::setRenderPipelineState(const MTL::RenderPipelineState* pipelineState) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRenderPipelineState_), pipelineState); } _MTL_INLINE void MTL::IndirectRenderCommand::setVertexBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBuffer_offset_atIndex_), buffer, offset, index); } _MTL_INLINE void MTL::IndirectRenderCommand::setFragmentBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentBuffer_offset_atIndex_), buffer, offset, index); } _MTL_INLINE void MTL::IndirectRenderCommand::setVertexBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger stride, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexBuffer_offset_attributeStride_atIndex_), buffer, offset, stride, index); } _MTL_INLINE void MTL::IndirectRenderCommand::drawPatches(NS::UInteger numberOfPatchControlPoints, NS::UInteger patchStart, NS::UInteger patchCount, const MTL::Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, NS::UInteger instanceCount, NS::UInteger baseInstance, const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger instanceStride) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawPatches_patchStart_patchCount_patchIndexBuffer_patchIndexBufferOffset_instanceCount_baseInstance_tessellationFactorBuffer_tessellationFactorBufferOffset_tessellationFactorBufferInstanceStride_), numberOfPatchControlPoints, patchStart, patchCount, patchIndexBuffer, patchIndexBufferOffset, instanceCount, baseInstance, buffer, offset, instanceStride); } _MTL_INLINE void MTL::IndirectRenderCommand::drawIndexedPatches(NS::UInteger numberOfPatchControlPoints, NS::UInteger patchStart, NS::UInteger patchCount, const MTL::Buffer* patchIndexBuffer, NS::UInteger patchIndexBufferOffset, const MTL::Buffer* controlPointIndexBuffer, NS::UInteger controlPointIndexBufferOffset, NS::UInteger instanceCount, NS::UInteger baseInstance, const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger instanceStride) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawIndexedPatches_patchStart_patchCount_patchIndexBuffer_patchIndexBufferOffset_controlPointIndexBuffer_controlPointIndexBufferOffset_instanceCount_baseInstance_tessellationFactorBuffer_tessellationFactorBufferOffset_tessellationFactorBufferInstanceStride_), numberOfPatchControlPoints, patchStart, patchCount, patchIndexBuffer, patchIndexBufferOffset, controlPointIndexBuffer, controlPointIndexBufferOffset, instanceCount, baseInstance, buffer, offset, instanceStride); } _MTL_INLINE void MTL::IndirectRenderCommand::drawPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger vertexStart, NS::UInteger vertexCount, NS::UInteger instanceCount, NS::UInteger baseInstance) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance_), primitiveType, vertexStart, vertexCount, instanceCount, baseInstance); } _MTL_INLINE void MTL::IndirectRenderCommand::drawIndexedPrimitives(MTL::PrimitiveType primitiveType, NS::UInteger indexCount, MTL::IndexType indexType, const MTL::Buffer* indexBuffer, NS::UInteger indexBufferOffset, NS::UInteger instanceCount, NS::Integer baseVertex, NS::UInteger baseInstance) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_instanceCount_baseVertex_baseInstance_), primitiveType, indexCount, indexType, indexBuffer, indexBufferOffset, instanceCount, baseVertex, baseInstance); } _MTL_INLINE void MTL::IndirectRenderCommand::setObjectThreadgroupMemoryLength(NS::UInteger length, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObjectThreadgroupMemoryLength_atIndex_), length, index); } _MTL_INLINE void MTL::IndirectRenderCommand::setObjectBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObjectBuffer_offset_atIndex_), buffer, offset, index); } _MTL_INLINE void MTL::IndirectRenderCommand::setMeshBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMeshBuffer_offset_atIndex_), buffer, offset, index); } _MTL_INLINE void MTL::IndirectRenderCommand::drawMeshThreadgroups(MTL::Size threadgroupsPerGrid, MTL::Size threadsPerObjectThreadgroup, MTL::Size threadsPerMeshThreadgroup) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawMeshThreadgroups_threadsPerObjectThreadgroup_threadsPerMeshThreadgroup_), threadgroupsPerGrid, threadsPerObjectThreadgroup, threadsPerMeshThreadgroup); } _MTL_INLINE void MTL::IndirectRenderCommand::drawMeshThreads(MTL::Size threadsPerGrid, MTL::Size threadsPerObjectThreadgroup, MTL::Size threadsPerMeshThreadgroup) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(drawMeshThreads_threadsPerObjectThreadgroup_threadsPerMeshThreadgroup_), threadsPerGrid, threadsPerObjectThreadgroup, threadsPerMeshThreadgroup); } _MTL_INLINE void MTL::IndirectRenderCommand::setBarrier() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBarrier)); } _MTL_INLINE void MTL::IndirectRenderCommand::clearBarrier() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(clearBarrier)); } _MTL_INLINE void MTL::IndirectRenderCommand::reset() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(reset)); } _MTL_INLINE void MTL::IndirectComputeCommand::setComputePipelineState(const MTL::ComputePipelineState* pipelineState) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setComputePipelineState_), pipelineState); } _MTL_INLINE void MTL::IndirectComputeCommand::setKernelBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setKernelBuffer_offset_atIndex_), buffer, offset, index); } _MTL_INLINE void MTL::IndirectComputeCommand::setKernelBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger stride, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setKernelBuffer_offset_attributeStride_atIndex_), buffer, offset, stride, index); } _MTL_INLINE void MTL::IndirectComputeCommand::concurrentDispatchThreadgroups(MTL::Size threadgroupsPerGrid, MTL::Size threadsPerThreadgroup) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(concurrentDispatchThreadgroups_threadsPerThreadgroup_), threadgroupsPerGrid, threadsPerThreadgroup); } _MTL_INLINE void MTL::IndirectComputeCommand::concurrentDispatchThreads(MTL::Size threadsPerGrid, MTL::Size threadsPerThreadgroup) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(concurrentDispatchThreads_threadsPerThreadgroup_), threadsPerGrid, threadsPerThreadgroup); } _MTL_INLINE void MTL::IndirectComputeCommand::setBarrier() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBarrier)); } _MTL_INLINE void MTL::IndirectComputeCommand::clearBarrier() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(clearBarrier)); } _MTL_INLINE void MTL::IndirectComputeCommand::setImageblockWidth(NS::UInteger width, NS::UInteger height) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setImageblockWidth_height_), width, height); } _MTL_INLINE void MTL::IndirectComputeCommand::reset() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(reset)); } _MTL_INLINE void MTL::IndirectComputeCommand::setThreadgroupMemoryLength(NS::UInteger length, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setThreadgroupMemoryLength_atIndex_), length, index); } _MTL_INLINE void MTL::IndirectComputeCommand::setStageInRegion(MTL::Region region) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStageInRegion_), region); } #pragma once namespace MTL { _MTL_OPTIONS(NS::UInteger, IntersectionFunctionSignature) { IntersectionFunctionSignatureNone = 0, IntersectionFunctionSignatureInstancing = 1, IntersectionFunctionSignatureTriangleData = 2, IntersectionFunctionSignatureWorldSpaceData = 4, IntersectionFunctionSignatureInstanceMotion = 8, IntersectionFunctionSignaturePrimitiveMotion = 16, IntersectionFunctionSignatureExtendedLimits = 32, IntersectionFunctionSignatureMaxLevels = 64, IntersectionFunctionSignatureCurveData = 128, }; class IntersectionFunctionTableDescriptor : public NS::Copying<IntersectionFunctionTableDescriptor> { public: static class IntersectionFunctionTableDescriptor* alloc(); class IntersectionFunctionTableDescriptor* init(); static class IntersectionFunctionTableDescriptor* intersectionFunctionTableDescriptor(); NS::UInteger functionCount() const; void setFunctionCount(NS::UInteger functionCount); }; class IntersectionFunctionTable : public NS::Referencing<IntersectionFunctionTable, Resource> { public: void setBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger index); void setBuffers(const class Buffer* const buffers[], const NS::UInteger offsets[], NS::Range range); MTL::ResourceID gpuResourceID() const; void setFunction(const class FunctionHandle* function, NS::UInteger index); void setFunctions(const class FunctionHandle* const functions[], NS::Range range); void setOpaqueTriangleIntersectionFunction(MTL::IntersectionFunctionSignature signature, NS::UInteger index); void setOpaqueTriangleIntersectionFunction(MTL::IntersectionFunctionSignature signature, NS::Range range); void setOpaqueCurveIntersectionFunction(MTL::IntersectionFunctionSignature signature, NS::UInteger index); void setOpaqueCurveIntersectionFunction(MTL::IntersectionFunctionSignature signature, NS::Range range); void setVisibleFunctionTable(const class VisibleFunctionTable* functionTable, NS::UInteger bufferIndex); void setVisibleFunctionTables(const class VisibleFunctionTable* const functionTables[], NS::Range bufferRange); }; } _MTL_INLINE MTL::IntersectionFunctionTableDescriptor* MTL::IntersectionFunctionTableDescriptor::alloc() { return NS::Object::alloc<MTL::IntersectionFunctionTableDescriptor>(_MTL_PRIVATE_CLS(MTLIntersectionFunctionTableDescriptor)); } _MTL_INLINE MTL::IntersectionFunctionTableDescriptor* MTL::IntersectionFunctionTableDescriptor::init() { return NS::Object::init<MTL::IntersectionFunctionTableDescriptor>(); } _MTL_INLINE MTL::IntersectionFunctionTableDescriptor* MTL::IntersectionFunctionTableDescriptor::intersectionFunctionTableDescriptor() { return Object::sendMessage<MTL::IntersectionFunctionTableDescriptor*>(_MTL_PRIVATE_CLS(MTLIntersectionFunctionTableDescriptor), _MTL_PRIVATE_SEL(intersectionFunctionTableDescriptor)); } _MTL_INLINE NS::UInteger MTL::IntersectionFunctionTableDescriptor::functionCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(functionCount)); } _MTL_INLINE void MTL::IntersectionFunctionTableDescriptor::setFunctionCount(NS::UInteger functionCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunctionCount_), functionCount); } _MTL_INLINE void MTL::IntersectionFunctionTable::setBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBuffer_offset_atIndex_), buffer, offset, index); } _MTL_INLINE void MTL::IntersectionFunctionTable::setBuffers(const MTL::Buffer* const buffers[], const NS::UInteger offsets[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBuffers_offsets_withRange_), buffers, offsets, range); } _MTL_INLINE MTL::ResourceID MTL::IntersectionFunctionTable::gpuResourceID() const { return Object::sendMessage<MTL::ResourceID>(this, _MTL_PRIVATE_SEL(gpuResourceID)); } _MTL_INLINE void MTL::IntersectionFunctionTable::setFunction(const MTL::FunctionHandle* function, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunction_atIndex_), function, index); } _MTL_INLINE void MTL::IntersectionFunctionTable::setFunctions(const MTL::FunctionHandle* const functions[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunctions_withRange_), functions, range); } _MTL_INLINE void MTL::IntersectionFunctionTable::setOpaqueTriangleIntersectionFunction(MTL::IntersectionFunctionSignature signature, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOpaqueTriangleIntersectionFunctionWithSignature_atIndex_), signature, index); } _MTL_INLINE void MTL::IntersectionFunctionTable::setOpaqueTriangleIntersectionFunction(MTL::IntersectionFunctionSignature signature, NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOpaqueTriangleIntersectionFunctionWithSignature_withRange_), signature, range); } _MTL_INLINE void MTL::IntersectionFunctionTable::setOpaqueCurveIntersectionFunction(MTL::IntersectionFunctionSignature signature, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOpaqueCurveIntersectionFunctionWithSignature_atIndex_), signature, index); } _MTL_INLINE void MTL::IntersectionFunctionTable::setOpaqueCurveIntersectionFunction(MTL::IntersectionFunctionSignature signature, NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOpaqueCurveIntersectionFunctionWithSignature_withRange_), signature, range); } _MTL_INLINE void MTL::IntersectionFunctionTable::setVisibleFunctionTable(const MTL::VisibleFunctionTable* functionTable, NS::UInteger bufferIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVisibleFunctionTable_atBufferIndex_), functionTable, bufferIndex); } _MTL_INLINE void MTL::IntersectionFunctionTable::setVisibleFunctionTables(const MTL::VisibleFunctionTable* const functionTables[], NS::Range bufferRange) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVisibleFunctionTables_withBufferRange_), functionTables, bufferRange); } #pragma once namespace MTL { _MTL_ENUM(NS::Integer, IOStatus) { IOStatusPending = 0, IOStatusCancelled = 1, IOStatusError = 2, IOStatusComplete = 3, }; using IOCommandBufferHandler = void (^)(class IOCommandBuffer*); using IOCommandBufferHandlerFunction = std::function<void(class IOCommandBuffer*)>; class IOCommandBuffer : public NS::Referencing<IOCommandBuffer> { public: void addCompletedHandler(const MTL::IOCommandBufferHandlerFunction& function); void addCompletedHandler(const MTL::IOCommandBufferHandler block); void loadBytes(const void* pointer, NS::UInteger size, const class IOFileHandle* sourceHandle, NS::UInteger sourceHandleOffset); void loadBuffer(const class Buffer* buffer, NS::UInteger offset, NS::UInteger size, const class IOFileHandle* sourceHandle, NS::UInteger sourceHandleOffset); void loadTexture(const class Texture* texture, NS::UInteger slice, NS::UInteger level, MTL::Size size, NS::UInteger sourceBytesPerRow, NS::UInteger sourceBytesPerImage, MTL::Origin destinationOrigin, const class IOFileHandle* sourceHandle, NS::UInteger sourceHandleOffset); void copyStatusToBuffer(const class Buffer* buffer, NS::UInteger offset); void commit(); void waitUntilCompleted(); void tryCancel(); void addBarrier(); void pushDebugGroup(const NS::String* string); void popDebugGroup(); void enqueue(); void wait(const class SharedEvent* event, uint64_t value); void signalEvent(const class SharedEvent* event, uint64_t value); NS::String* label() const; void setLabel(const NS::String* label); MTL::IOStatus status() const; NS::Error* error() const; }; } _MTL_INLINE void MTL::IOCommandBuffer::addCompletedHandler(const MTL::IOCommandBufferHandlerFunction& function) { __block IOCommandBufferHandlerFunction blockFunction = function; addCompletedHandler(^(IOCommandBuffer* pCommandBuffer) { blockFunction(pCommandBuffer); }); } _MTL_INLINE void MTL::IOCommandBuffer::addCompletedHandler(const MTL::IOCommandBufferHandler block) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(addCompletedHandler_), block); } _MTL_INLINE void MTL::IOCommandBuffer::loadBytes(const void* pointer, NS::UInteger size, const MTL::IOFileHandle* sourceHandle, NS::UInteger sourceHandleOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(loadBytes_size_sourceHandle_sourceHandleOffset_), pointer, size, sourceHandle, sourceHandleOffset); } _MTL_INLINE void MTL::IOCommandBuffer::loadBuffer(const MTL::Buffer* buffer, NS::UInteger offset, NS::UInteger size, const MTL::IOFileHandle* sourceHandle, NS::UInteger sourceHandleOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(loadBuffer_offset_size_sourceHandle_sourceHandleOffset_), buffer, offset, size, sourceHandle, sourceHandleOffset); } _MTL_INLINE void MTL::IOCommandBuffer::loadTexture(const MTL::Texture* texture, NS::UInteger slice, NS::UInteger level, MTL::Size size, NS::UInteger sourceBytesPerRow, NS::UInteger sourceBytesPerImage, MTL::Origin destinationOrigin, const MTL::IOFileHandle* sourceHandle, NS::UInteger sourceHandleOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(loadTexture_slice_level_size_sourceBytesPerRow_sourceBytesPerImage_destinationOrigin_sourceHandle_sourceHandleOffset_), texture, slice, level, size, sourceBytesPerRow, sourceBytesPerImage, destinationOrigin, sourceHandle, sourceHandleOffset); } _MTL_INLINE void MTL::IOCommandBuffer::copyStatusToBuffer(const MTL::Buffer* buffer, NS::UInteger offset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyStatusToBuffer_offset_), buffer, offset); } _MTL_INLINE void MTL::IOCommandBuffer::commit() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(commit)); } _MTL_INLINE void MTL::IOCommandBuffer::waitUntilCompleted() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(waitUntilCompleted)); } _MTL_INLINE void MTL::IOCommandBuffer::tryCancel() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(tryCancel)); } _MTL_INLINE void MTL::IOCommandBuffer::addBarrier() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(addBarrier)); } _MTL_INLINE void MTL::IOCommandBuffer::pushDebugGroup(const NS::String* string) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(pushDebugGroup_), string); } _MTL_INLINE void MTL::IOCommandBuffer::popDebugGroup() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(popDebugGroup)); } _MTL_INLINE void MTL::IOCommandBuffer::enqueue() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(enqueue)); } _MTL_INLINE void MTL::IOCommandBuffer::wait(const MTL::SharedEvent* event, uint64_t value) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(waitForEvent_value_), event, value); } _MTL_INLINE void MTL::IOCommandBuffer::signalEvent(const MTL::SharedEvent* event, uint64_t value) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(signalEvent_value_), event, value); } _MTL_INLINE NS::String* MTL::IOCommandBuffer::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::IOCommandBuffer::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE MTL::IOStatus MTL::IOCommandBuffer::status() const { return Object::sendMessage<MTL::IOStatus>(this, _MTL_PRIVATE_SEL(status)); } _MTL_INLINE NS::Error* MTL::IOCommandBuffer::error() const { return Object::sendMessage<NS::Error*>(this, _MTL_PRIVATE_SEL(error)); } #pragma once namespace MTL { _MTL_ENUM(NS::Integer, IOPriority) { IOPriorityHigh = 0, IOPriorityNormal = 1, IOPriorityLow = 2, }; _MTL_ENUM(NS::Integer, IOCommandQueueType) { IOCommandQueueTypeConcurrent = 0, IOCommandQueueTypeSerial = 1, }; _MTL_CONST(NS::ErrorDomain, IOErrorDomain); _MTL_ENUM(NS::Integer, IOError) { IOErrorURLInvalid = 1, IOErrorInternal = 2, }; class IOCommandQueue : public NS::Referencing<IOCommandQueue> { public: void enqueueBarrier(); class IOCommandBuffer* commandBuffer(); class IOCommandBuffer* commandBufferWithUnretainedReferences(); NS::String* label() const; void setLabel(const NS::String* label); }; class IOScratchBuffer : public NS::Referencing<IOScratchBuffer> { public: class Buffer* buffer() const; }; class IOScratchBufferAllocator : public NS::Referencing<IOScratchBufferAllocator> { public: class IOScratchBuffer* newScratchBuffer(NS::UInteger minimumSize); }; class IOCommandQueueDescriptor : public NS::Copying<IOCommandQueueDescriptor> { public: static class IOCommandQueueDescriptor* alloc(); class IOCommandQueueDescriptor* init(); NS::UInteger maxCommandBufferCount() const; void setMaxCommandBufferCount(NS::UInteger maxCommandBufferCount); MTL::IOPriority priority() const; void setPriority(MTL::IOPriority priority); MTL::IOCommandQueueType type() const; void setType(MTL::IOCommandQueueType type); NS::UInteger maxCommandsInFlight() const; void setMaxCommandsInFlight(NS::UInteger maxCommandsInFlight); class IOScratchBufferAllocator* scratchBufferAllocator() const; void setScratchBufferAllocator(const class IOScratchBufferAllocator* scratchBufferAllocator); }; class IOFileHandle : public NS::Referencing<IOFileHandle> { public: NS::String* label() const; void setLabel(const NS::String* label); }; } _MTL_INLINE void MTL::IOCommandQueue::enqueueBarrier() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(enqueueBarrier)); } _MTL_INLINE MTL::IOCommandBuffer* MTL::IOCommandQueue::commandBuffer() { return Object::sendMessage<MTL::IOCommandBuffer*>(this, _MTL_PRIVATE_SEL(commandBuffer)); } _MTL_INLINE MTL::IOCommandBuffer* MTL::IOCommandQueue::commandBufferWithUnretainedReferences() { return Object::sendMessage<MTL::IOCommandBuffer*>(this, _MTL_PRIVATE_SEL(commandBufferWithUnretainedReferences)); } _MTL_INLINE NS::String* MTL::IOCommandQueue::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::IOCommandQueue::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE MTL::Buffer* MTL::IOScratchBuffer::buffer() const { return Object::sendMessage<MTL::Buffer*>(this, _MTL_PRIVATE_SEL(buffer)); } _MTL_INLINE MTL::IOScratchBuffer* MTL::IOScratchBufferAllocator::newScratchBuffer(NS::UInteger minimumSize) { return Object::sendMessage<MTL::IOScratchBuffer*>(this, _MTL_PRIVATE_SEL(newScratchBufferWithMinimumSize_), minimumSize); } _MTL_INLINE MTL::IOCommandQueueDescriptor* MTL::IOCommandQueueDescriptor::alloc() { return NS::Object::alloc<MTL::IOCommandQueueDescriptor>(_MTL_PRIVATE_CLS(MTLIOCommandQueueDescriptor)); } _MTL_INLINE MTL::IOCommandQueueDescriptor* MTL::IOCommandQueueDescriptor::init() { return NS::Object::init<MTL::IOCommandQueueDescriptor>(); } _MTL_INLINE NS::UInteger MTL::IOCommandQueueDescriptor::maxCommandBufferCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxCommandBufferCount)); } _MTL_INLINE void MTL::IOCommandQueueDescriptor::setMaxCommandBufferCount(NS::UInteger maxCommandBufferCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxCommandBufferCount_), maxCommandBufferCount); } _MTL_INLINE MTL::IOPriority MTL::IOCommandQueueDescriptor::priority() const { return Object::sendMessage<MTL::IOPriority>(this, _MTL_PRIVATE_SEL(priority)); } _MTL_INLINE void MTL::IOCommandQueueDescriptor::setPriority(MTL::IOPriority priority) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPriority_), priority); } _MTL_INLINE MTL::IOCommandQueueType MTL::IOCommandQueueDescriptor::type() const { return Object::sendMessage<MTL::IOCommandQueueType>(this, _MTL_PRIVATE_SEL(type)); } _MTL_INLINE void MTL::IOCommandQueueDescriptor::setType(MTL::IOCommandQueueType type) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setType_), type); } _MTL_INLINE NS::UInteger MTL::IOCommandQueueDescriptor::maxCommandsInFlight() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxCommandsInFlight)); } _MTL_INLINE void MTL::IOCommandQueueDescriptor::setMaxCommandsInFlight(NS::UInteger maxCommandsInFlight) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxCommandsInFlight_), maxCommandsInFlight); } _MTL_INLINE MTL::IOScratchBufferAllocator* MTL::IOCommandQueueDescriptor::scratchBufferAllocator() const { return Object::sendMessage<MTL::IOScratchBufferAllocator*>(this, _MTL_PRIVATE_SEL(scratchBufferAllocator)); } _MTL_INLINE void MTL::IOCommandQueueDescriptor::setScratchBufferAllocator(const MTL::IOScratchBufferAllocator* scratchBufferAllocator) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setScratchBufferAllocator_), scratchBufferAllocator); } _MTL_INLINE NS::String* MTL::IOFileHandle::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::IOFileHandle::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } #pragma once namespace MTL { using IOCompresionContext=void*; _MTL_ENUM(NS::Integer, IOCompressionStatus) { IOCompressionStatusComplete = 0, IOCompressionStatusError = 1, }; size_t IOCompressionContextDefaultChunkSize(); IOCompresionContext IOCreateCompressionContext(const char* path, IOCompressionMethod type, size_t chunkSize); void IOCompressionContextAppendData(IOCompresionContext context, const void* data, size_t size); IOCompressionStatus IOFlushAndDestroyCompressionContext(IOCompresionContext context); } #if defined(MTL_PRIVATE_IMPLEMENTATION) namespace MTL::Private { MTL_DEF_FUNC(MTLIOCompressionContextDefaultChunkSize, size_t (*)(void)); MTL_DEF_FUNC( MTLIOCreateCompressionContext, void* (*)(const char*, MTL::IOCompressionMethod, size_t) ); MTL_DEF_FUNC( MTLIOCompressionContextAppendData, void (*)(void*, const void*, size_t) ); MTL_DEF_FUNC( MTLIOFlushAndDestroyCompressionContext, MTL::IOCompressionStatus (*)(void*) ); } _NS_EXPORT size_t MTL::IOCompressionContextDefaultChunkSize() { return MTL::Private::MTLIOCompressionContextDefaultChunkSize(); } _NS_EXPORT void* MTL::IOCreateCompressionContext(const char* path, IOCompressionMethod type, size_t chunkSize) { if ( MTL::Private::MTLIOCreateCompressionContext ) { return MTL::Private::MTLIOCreateCompressionContext( path, type, chunkSize ); } return nullptr; } _NS_EXPORT void MTL::IOCompressionContextAppendData(void* context, const void* data, size_t size) { if ( MTL::Private::MTLIOCompressionContextAppendData ) { MTL::Private::MTLIOCompressionContextAppendData( context, data, size ); } } _NS_EXPORT MTL::IOCompressionStatus MTL::IOFlushAndDestroyCompressionContext(void* context) { if ( MTL::Private::MTLIOFlushAndDestroyCompressionContext ) { return MTL::Private::MTLIOFlushAndDestroyCompressionContext( context ); } return MTL::IOCompressionStatusError; } #endif #pragma once namespace MTL { class LinkedFunctions : public NS::Copying<LinkedFunctions> { public: static class LinkedFunctions* alloc(); class LinkedFunctions* init(); static class LinkedFunctions* linkedFunctions(); NS::Array* functions() const; void setFunctions(const NS::Array* functions); NS::Array* binaryFunctions() const; void setBinaryFunctions(const NS::Array* binaryFunctions); NS::Dictionary* groups() const; void setGroups(const NS::Dictionary* groups); NS::Array* privateFunctions() const; void setPrivateFunctions(const NS::Array* privateFunctions); }; } _MTL_INLINE MTL::LinkedFunctions* MTL::LinkedFunctions::alloc() { return NS::Object::alloc<MTL::LinkedFunctions>(_MTL_PRIVATE_CLS(MTLLinkedFunctions)); } _MTL_INLINE MTL::LinkedFunctions* MTL::LinkedFunctions::init() { return NS::Object::init<MTL::LinkedFunctions>(); } _MTL_INLINE MTL::LinkedFunctions* MTL::LinkedFunctions::linkedFunctions() { return Object::sendMessage<MTL::LinkedFunctions*>(_MTL_PRIVATE_CLS(MTLLinkedFunctions), _MTL_PRIVATE_SEL(linkedFunctions)); } _MTL_INLINE NS::Array* MTL::LinkedFunctions::functions() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(functions)); } _MTL_INLINE void MTL::LinkedFunctions::setFunctions(const NS::Array* functions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunctions_), functions); } _MTL_INLINE NS::Array* MTL::LinkedFunctions::binaryFunctions() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(binaryFunctions)); } _MTL_INLINE void MTL::LinkedFunctions::setBinaryFunctions(const NS::Array* binaryFunctions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBinaryFunctions_), binaryFunctions); } _MTL_INLINE NS::Dictionary* MTL::LinkedFunctions::groups() const { return Object::sendMessage<NS::Dictionary*>(this, _MTL_PRIVATE_SEL(groups)); } _MTL_INLINE void MTL::LinkedFunctions::setGroups(const NS::Dictionary* groups) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setGroups_), groups); } _MTL_INLINE NS::Array* MTL::LinkedFunctions::privateFunctions() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(privateFunctions)); } _MTL_INLINE void MTL::LinkedFunctions::setPrivateFunctions(const NS::Array* privateFunctions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPrivateFunctions_), privateFunctions); } #pragma once namespace MTL { class ParallelRenderCommandEncoder : public NS::Referencing<ParallelRenderCommandEncoder, CommandEncoder> { public: class RenderCommandEncoder* renderCommandEncoder(); void setColorStoreAction(MTL::StoreAction storeAction, NS::UInteger colorAttachmentIndex); void setDepthStoreAction(MTL::StoreAction storeAction); void setStencilStoreAction(MTL::StoreAction storeAction); void setColorStoreActionOptions(MTL::StoreActionOptions storeActionOptions, NS::UInteger colorAttachmentIndex); void setDepthStoreActionOptions(MTL::StoreActionOptions storeActionOptions); void setStencilStoreActionOptions(MTL::StoreActionOptions storeActionOptions); }; } _MTL_INLINE MTL::RenderCommandEncoder* MTL::ParallelRenderCommandEncoder::renderCommandEncoder() { return Object::sendMessage<MTL::RenderCommandEncoder*>(this, _MTL_PRIVATE_SEL(renderCommandEncoder)); } _MTL_INLINE void MTL::ParallelRenderCommandEncoder::setColorStoreAction(MTL::StoreAction storeAction, NS::UInteger colorAttachmentIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setColorStoreAction_atIndex_), storeAction, colorAttachmentIndex); } _MTL_INLINE void MTL::ParallelRenderCommandEncoder::setDepthStoreAction(MTL::StoreAction storeAction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthStoreAction_), storeAction); } _MTL_INLINE void MTL::ParallelRenderCommandEncoder::setStencilStoreAction(MTL::StoreAction storeAction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilStoreAction_), storeAction); } _MTL_INLINE void MTL::ParallelRenderCommandEncoder::setColorStoreActionOptions(MTL::StoreActionOptions storeActionOptions, NS::UInteger colorAttachmentIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setColorStoreActionOptions_atIndex_), storeActionOptions, colorAttachmentIndex); } _MTL_INLINE void MTL::ParallelRenderCommandEncoder::setDepthStoreActionOptions(MTL::StoreActionOptions storeActionOptions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthStoreActionOptions_), storeActionOptions); } _MTL_INLINE void MTL::ParallelRenderCommandEncoder::setStencilStoreActionOptions(MTL::StoreActionOptions storeActionOptions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilStoreActionOptions_), storeActionOptions); } #pragma once namespace MTL { _MTL_ENUM(NS::UInteger, Mutability) { MutabilityDefault = 0, MutabilityMutable = 1, MutabilityImmutable = 2, }; class PipelineBufferDescriptor : public NS::Copying<PipelineBufferDescriptor> { public: static class PipelineBufferDescriptor* alloc(); class PipelineBufferDescriptor* init(); MTL::Mutability mutability() const; void setMutability(MTL::Mutability mutability); }; class PipelineBufferDescriptorArray : public NS::Referencing<PipelineBufferDescriptorArray> { public: static class PipelineBufferDescriptorArray* alloc(); class PipelineBufferDescriptorArray* init(); class PipelineBufferDescriptor* object(NS::UInteger bufferIndex); void setObject(const class PipelineBufferDescriptor* buffer, NS::UInteger bufferIndex); }; } _MTL_INLINE MTL::PipelineBufferDescriptor* MTL::PipelineBufferDescriptor::alloc() { return NS::Object::alloc<MTL::PipelineBufferDescriptor>(_MTL_PRIVATE_CLS(MTLPipelineBufferDescriptor)); } _MTL_INLINE MTL::PipelineBufferDescriptor* MTL::PipelineBufferDescriptor::init() { return NS::Object::init<MTL::PipelineBufferDescriptor>(); } _MTL_INLINE MTL::Mutability MTL::PipelineBufferDescriptor::mutability() const { return Object::sendMessage<MTL::Mutability>(this, _MTL_PRIVATE_SEL(mutability)); } _MTL_INLINE void MTL::PipelineBufferDescriptor::setMutability(MTL::Mutability mutability) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMutability_), mutability); } _MTL_INLINE MTL::PipelineBufferDescriptorArray* MTL::PipelineBufferDescriptorArray::alloc() { return NS::Object::alloc<MTL::PipelineBufferDescriptorArray>(_MTL_PRIVATE_CLS(MTLPipelineBufferDescriptorArray)); } _MTL_INLINE MTL::PipelineBufferDescriptorArray* MTL::PipelineBufferDescriptorArray::init() { return NS::Object::init<MTL::PipelineBufferDescriptorArray>(); } _MTL_INLINE MTL::PipelineBufferDescriptor* MTL::PipelineBufferDescriptorArray::object(NS::UInteger bufferIndex) { return Object::sendMessage<MTL::PipelineBufferDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), bufferIndex); } _MTL_INLINE void MTL::PipelineBufferDescriptorArray::setObject(const MTL::PipelineBufferDescriptor* buffer, NS::UInteger bufferIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), buffer, bufferIndex); } #pragma once namespace MTL { class RasterizationRateSampleArray : public NS::Referencing<RasterizationRateSampleArray> { public: static class RasterizationRateSampleArray* alloc(); class RasterizationRateSampleArray* init(); NS::Number* object(NS::UInteger index); void setObject(const NS::Number* value, NS::UInteger index); }; class RasterizationRateLayerDescriptor : public NS::Copying<RasterizationRateLayerDescriptor> { public: static class RasterizationRateLayerDescriptor* alloc(); MTL::RasterizationRateLayerDescriptor* init(); MTL::RasterizationRateLayerDescriptor* init(MTL::Size sampleCount); MTL::RasterizationRateLayerDescriptor* init(MTL::Size sampleCount, const float* horizontal, const float* vertical); MTL::Size sampleCount() const; MTL::Size maxSampleCount() const; float* horizontalSampleStorage() const; float* verticalSampleStorage() const; class RasterizationRateSampleArray* horizontal() const; class RasterizationRateSampleArray* vertical() const; void setSampleCount(MTL::Size sampleCount); }; class RasterizationRateLayerArray : public NS::Referencing<RasterizationRateLayerArray> { public: static class RasterizationRateLayerArray* alloc(); class RasterizationRateLayerArray* init(); class RasterizationRateLayerDescriptor* object(NS::UInteger layerIndex); void setObject(const class RasterizationRateLayerDescriptor* layer, NS::UInteger layerIndex); }; class RasterizationRateMapDescriptor : public NS::Copying<RasterizationRateMapDescriptor> { public: static class RasterizationRateMapDescriptor* alloc(); class RasterizationRateMapDescriptor* init(); static class RasterizationRateMapDescriptor* rasterizationRateMapDescriptor(MTL::Size screenSize); static class RasterizationRateMapDescriptor* rasterizationRateMapDescriptor(MTL::Size screenSize, const class RasterizationRateLayerDescriptor* layer); static class RasterizationRateMapDescriptor* rasterizationRateMapDescriptor(MTL::Size screenSize, NS::UInteger layerCount, const class RasterizationRateLayerDescriptor* const* layers); class RasterizationRateLayerDescriptor* layer(NS::UInteger layerIndex); void setLayer(const class RasterizationRateLayerDescriptor* layer, NS::UInteger layerIndex); class RasterizationRateLayerArray* layers() const; MTL::Size screenSize() const; void setScreenSize(MTL::Size screenSize); NS::String* label() const; void setLabel(const NS::String* label); NS::UInteger layerCount() const; }; class RasterizationRateMap : public NS::Referencing<RasterizationRateMap> { public: class Device* device() const; NS::String* label() const; MTL::Size screenSize() const; MTL::Size physicalGranularity() const; NS::UInteger layerCount() const; MTL::SizeAndAlign parameterBufferSizeAndAlign() const; void copyParameterDataToBuffer(const class Buffer* buffer, NS::UInteger offset); MTL::Size physicalSize(NS::UInteger layerIndex); MTL::Coordinate2D mapScreenToPhysicalCoordinates(MTL::Coordinate2D screenCoordinates, NS::UInteger layerIndex); MTL::Coordinate2D mapPhysicalToScreenCoordinates(MTL::Coordinate2D physicalCoordinates, NS::UInteger layerIndex); }; } _MTL_INLINE MTL::RasterizationRateSampleArray* MTL::RasterizationRateSampleArray::alloc() { return NS::Object::alloc<MTL::RasterizationRateSampleArray>(_MTL_PRIVATE_CLS(MTLRasterizationRateSampleArray)); } _MTL_INLINE MTL::RasterizationRateSampleArray* MTL::RasterizationRateSampleArray::init() { return NS::Object::init<MTL::RasterizationRateSampleArray>(); } _MTL_INLINE NS::Number* MTL::RasterizationRateSampleArray::object(NS::UInteger index) { return Object::sendMessage<NS::Number*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), index); } _MTL_INLINE void MTL::RasterizationRateSampleArray::setObject(const NS::Number* value, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), value, index); } _MTL_INLINE MTL::RasterizationRateLayerDescriptor* MTL::RasterizationRateLayerDescriptor::alloc() { return NS::Object::alloc<MTL::RasterizationRateLayerDescriptor>(_MTL_PRIVATE_CLS(MTLRasterizationRateLayerDescriptor)); } _MTL_INLINE MTL::RasterizationRateLayerDescriptor* MTL::RasterizationRateLayerDescriptor::init() { return NS::Object::init<MTL::RasterizationRateLayerDescriptor>(); } _MTL_INLINE MTL::RasterizationRateLayerDescriptor* MTL::RasterizationRateLayerDescriptor::init(MTL::Size sampleCount) { return Object::sendMessage<MTL::RasterizationRateLayerDescriptor*>(this, _MTL_PRIVATE_SEL(initWithSampleCount_), sampleCount); } _MTL_INLINE MTL::RasterizationRateLayerDescriptor* MTL::RasterizationRateLayerDescriptor::init(MTL::Size sampleCount, const float* horizontal, const float* vertical) { return Object::sendMessage<MTL::RasterizationRateLayerDescriptor*>(this, _MTL_PRIVATE_SEL(initWithSampleCount_horizontal_vertical_), sampleCount, horizontal, vertical); } _MTL_INLINE MTL::Size MTL::RasterizationRateLayerDescriptor::sampleCount() const { return Object::sendMessage<MTL::Size>(this, _MTL_PRIVATE_SEL(sampleCount)); } _MTL_INLINE MTL::Size MTL::RasterizationRateLayerDescriptor::maxSampleCount() const { return Object::sendMessage<MTL::Size>(this, _MTL_PRIVATE_SEL(maxSampleCount)); } _MTL_INLINE float* MTL::RasterizationRateLayerDescriptor::horizontalSampleStorage() const { return Object::sendMessage<float*>(this, _MTL_PRIVATE_SEL(horizontalSampleStorage)); } _MTL_INLINE float* MTL::RasterizationRateLayerDescriptor::verticalSampleStorage() const { return Object::sendMessage<float*>(this, _MTL_PRIVATE_SEL(verticalSampleStorage)); } _MTL_INLINE MTL::RasterizationRateSampleArray* MTL::RasterizationRateLayerDescriptor::horizontal() const { return Object::sendMessage<MTL::RasterizationRateSampleArray*>(this, _MTL_PRIVATE_SEL(horizontal)); } _MTL_INLINE MTL::RasterizationRateSampleArray* MTL::RasterizationRateLayerDescriptor::vertical() const { return Object::sendMessage<MTL::RasterizationRateSampleArray*>(this, _MTL_PRIVATE_SEL(vertical)); } _MTL_INLINE void MTL::RasterizationRateLayerDescriptor::setSampleCount(MTL::Size sampleCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSampleCount_), sampleCount); } _MTL_INLINE MTL::RasterizationRateLayerArray* MTL::RasterizationRateLayerArray::alloc() { return NS::Object::alloc<MTL::RasterizationRateLayerArray>(_MTL_PRIVATE_CLS(MTLRasterizationRateLayerArray)); } _MTL_INLINE MTL::RasterizationRateLayerArray* MTL::RasterizationRateLayerArray::init() { return NS::Object::init<MTL::RasterizationRateLayerArray>(); } _MTL_INLINE MTL::RasterizationRateLayerDescriptor* MTL::RasterizationRateLayerArray::object(NS::UInteger layerIndex) { return Object::sendMessage<MTL::RasterizationRateLayerDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), layerIndex); } _MTL_INLINE void MTL::RasterizationRateLayerArray::setObject(const MTL::RasterizationRateLayerDescriptor* layer, NS::UInteger layerIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), layer, layerIndex); } _MTL_INLINE MTL::RasterizationRateMapDescriptor* MTL::RasterizationRateMapDescriptor::alloc() { return NS::Object::alloc<MTL::RasterizationRateMapDescriptor>(_MTL_PRIVATE_CLS(MTLRasterizationRateMapDescriptor)); } _MTL_INLINE MTL::RasterizationRateMapDescriptor* MTL::RasterizationRateMapDescriptor::init() { return NS::Object::init<MTL::RasterizationRateMapDescriptor>(); } _MTL_INLINE MTL::RasterizationRateMapDescriptor* MTL::RasterizationRateMapDescriptor::rasterizationRateMapDescriptor(MTL::Size screenSize) { return Object::sendMessage<MTL::RasterizationRateMapDescriptor*>(_MTL_PRIVATE_CLS(MTLRasterizationRateMapDescriptor), _MTL_PRIVATE_SEL(rasterizationRateMapDescriptorWithScreenSize_), screenSize); } _MTL_INLINE MTL::RasterizationRateMapDescriptor* MTL::RasterizationRateMapDescriptor::rasterizationRateMapDescriptor(MTL::Size screenSize, const MTL::RasterizationRateLayerDescriptor* layer) { return Object::sendMessage<MTL::RasterizationRateMapDescriptor*>(_MTL_PRIVATE_CLS(MTLRasterizationRateMapDescriptor), _MTL_PRIVATE_SEL(rasterizationRateMapDescriptorWithScreenSize_layer_), screenSize, layer); } _MTL_INLINE MTL::RasterizationRateMapDescriptor* MTL::RasterizationRateMapDescriptor::rasterizationRateMapDescriptor(MTL::Size screenSize, NS::UInteger layerCount, const MTL::RasterizationRateLayerDescriptor* const* layers) { return Object::sendMessage<MTL::RasterizationRateMapDescriptor*>(_MTL_PRIVATE_CLS(MTLRasterizationRateMapDescriptor), _MTL_PRIVATE_SEL(rasterizationRateMapDescriptorWithScreenSize_layerCount_layers_), screenSize, layerCount, layers); } _MTL_INLINE MTL::RasterizationRateLayerDescriptor* MTL::RasterizationRateMapDescriptor::layer(NS::UInteger layerIndex) { return Object::sendMessage<MTL::RasterizationRateLayerDescriptor*>(this, _MTL_PRIVATE_SEL(layerAtIndex_), layerIndex); } _MTL_INLINE void MTL::RasterizationRateMapDescriptor::setLayer(const MTL::RasterizationRateLayerDescriptor* layer, NS::UInteger layerIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLayer_atIndex_), layer, layerIndex); } _MTL_INLINE MTL::RasterizationRateLayerArray* MTL::RasterizationRateMapDescriptor::layers() const { return Object::sendMessage<MTL::RasterizationRateLayerArray*>(this, _MTL_PRIVATE_SEL(layers)); } _MTL_INLINE MTL::Size MTL::RasterizationRateMapDescriptor::screenSize() const { return Object::sendMessage<MTL::Size>(this, _MTL_PRIVATE_SEL(screenSize)); } _MTL_INLINE void MTL::RasterizationRateMapDescriptor::setScreenSize(MTL::Size screenSize) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setScreenSize_), screenSize); } _MTL_INLINE NS::String* MTL::RasterizationRateMapDescriptor::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::RasterizationRateMapDescriptor::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE NS::UInteger MTL::RasterizationRateMapDescriptor::layerCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(layerCount)); } _MTL_INLINE MTL::Device* MTL::RasterizationRateMap::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE NS::String* MTL::RasterizationRateMap::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE MTL::Size MTL::RasterizationRateMap::screenSize() const { return Object::sendMessage<MTL::Size>(this, _MTL_PRIVATE_SEL(screenSize)); } _MTL_INLINE MTL::Size MTL::RasterizationRateMap::physicalGranularity() const { return Object::sendMessage<MTL::Size>(this, _MTL_PRIVATE_SEL(physicalGranularity)); } _MTL_INLINE NS::UInteger MTL::RasterizationRateMap::layerCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(layerCount)); } _MTL_INLINE MTL::SizeAndAlign MTL::RasterizationRateMap::parameterBufferSizeAndAlign() const { return Object::sendMessage<MTL::SizeAndAlign>(this, _MTL_PRIVATE_SEL(parameterBufferSizeAndAlign)); } _MTL_INLINE void MTL::RasterizationRateMap::copyParameterDataToBuffer(const MTL::Buffer* buffer, NS::UInteger offset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(copyParameterDataToBuffer_offset_), buffer, offset); } _MTL_INLINE MTL::Size MTL::RasterizationRateMap::physicalSize(NS::UInteger layerIndex) { return Object::sendMessage<MTL::Size>(this, _MTL_PRIVATE_SEL(physicalSizeForLayer_), layerIndex); } _MTL_INLINE MTL::Coordinate2D MTL::RasterizationRateMap::mapScreenToPhysicalCoordinates(MTL::Coordinate2D screenCoordinates, NS::UInteger layerIndex) { return Object::sendMessage<MTL::Coordinate2D>(this, _MTL_PRIVATE_SEL(mapScreenToPhysicalCoordinates_forLayer_), screenCoordinates, layerIndex); } _MTL_INLINE MTL::Coordinate2D MTL::RasterizationRateMap::mapPhysicalToScreenCoordinates(MTL::Coordinate2D physicalCoordinates, NS::UInteger layerIndex) { return Object::sendMessage<MTL::Coordinate2D>(this, _MTL_PRIVATE_SEL(mapPhysicalToScreenCoordinates_forLayer_), physicalCoordinates, layerIndex); } #pragma once namespace MTL { _MTL_ENUM(NS::UInteger, BlendFactor) { BlendFactorZero = 0, BlendFactorOne = 1, BlendFactorSourceColor = 2, BlendFactorOneMinusSourceColor = 3, BlendFactorSourceAlpha = 4, BlendFactorOneMinusSourceAlpha = 5, BlendFactorDestinationColor = 6, BlendFactorOneMinusDestinationColor = 7, BlendFactorDestinationAlpha = 8, BlendFactorOneMinusDestinationAlpha = 9, BlendFactorSourceAlphaSaturated = 10, BlendFactorBlendColor = 11, BlendFactorOneMinusBlendColor = 12, BlendFactorBlendAlpha = 13, BlendFactorOneMinusBlendAlpha = 14, BlendFactorSource1Color = 15, BlendFactorOneMinusSource1Color = 16, BlendFactorSource1Alpha = 17, BlendFactorOneMinusSource1Alpha = 18, }; _MTL_ENUM(NS::UInteger, BlendOperation) { BlendOperationAdd = 0, BlendOperationSubtract = 1, BlendOperationReverseSubtract = 2, BlendOperationMin = 3, BlendOperationMax = 4, }; _MTL_OPTIONS(NS::UInteger, ColorWriteMask) { ColorWriteMaskNone = 0, ColorWriteMaskRed = 8, ColorWriteMaskGreen = 4, ColorWriteMaskBlue = 2, ColorWriteMaskAlpha = 1, ColorWriteMaskAll = 15, }; _MTL_ENUM(NS::UInteger, PrimitiveTopologyClass) { PrimitiveTopologyClassUnspecified = 0, PrimitiveTopologyClassPoint = 1, PrimitiveTopologyClassLine = 2, PrimitiveTopologyClassTriangle = 3, }; _MTL_ENUM(NS::UInteger, TessellationPartitionMode) { TessellationPartitionModePow2 = 0, TessellationPartitionModeInteger = 1, TessellationPartitionModeFractionalOdd = 2, TessellationPartitionModeFractionalEven = 3, }; _MTL_ENUM(NS::UInteger, TessellationFactorStepFunction) { TessellationFactorStepFunctionConstant = 0, TessellationFactorStepFunctionPerPatch = 1, TessellationFactorStepFunctionPerInstance = 2, TessellationFactorStepFunctionPerPatchAndPerInstance = 3, }; _MTL_ENUM(NS::UInteger, TessellationFactorFormat) { TessellationFactorFormatHalf = 0, }; _MTL_ENUM(NS::UInteger, TessellationControlPointIndexType) { TessellationControlPointIndexTypeNone = 0, TessellationControlPointIndexTypeUInt16 = 1, TessellationControlPointIndexTypeUInt32 = 2, }; class RenderPipelineColorAttachmentDescriptor : public NS::Copying<RenderPipelineColorAttachmentDescriptor> { public: static class RenderPipelineColorAttachmentDescriptor* alloc(); class RenderPipelineColorAttachmentDescriptor* init(); MTL::PixelFormat pixelFormat() const; void setPixelFormat(MTL::PixelFormat pixelFormat); bool blendingEnabled() const; void setBlendingEnabled(bool blendingEnabled); MTL::BlendFactor sourceRGBBlendFactor() const; void setSourceRGBBlendFactor(MTL::BlendFactor sourceRGBBlendFactor); MTL::BlendFactor destinationRGBBlendFactor() const; void setDestinationRGBBlendFactor(MTL::BlendFactor destinationRGBBlendFactor); MTL::BlendOperation rgbBlendOperation() const; void setRgbBlendOperation(MTL::BlendOperation rgbBlendOperation); MTL::BlendFactor sourceAlphaBlendFactor() const; void setSourceAlphaBlendFactor(MTL::BlendFactor sourceAlphaBlendFactor); MTL::BlendFactor destinationAlphaBlendFactor() const; void setDestinationAlphaBlendFactor(MTL::BlendFactor destinationAlphaBlendFactor); MTL::BlendOperation alphaBlendOperation() const; void setAlphaBlendOperation(MTL::BlendOperation alphaBlendOperation); MTL::ColorWriteMask writeMask() const; void setWriteMask(MTL::ColorWriteMask writeMask); }; class RenderPipelineReflection : public NS::Referencing<RenderPipelineReflection> { public: static class RenderPipelineReflection* alloc(); class RenderPipelineReflection* init(); NS::Array* vertexBindings() const; NS::Array* fragmentBindings() const; NS::Array* tileBindings() const; NS::Array* objectBindings() const; NS::Array* meshBindings() const; NS::Array* vertexArguments() const; NS::Array* fragmentArguments() const; NS::Array* tileArguments() const; }; class RenderPipelineDescriptor : public NS::Copying<RenderPipelineDescriptor> { public: static class RenderPipelineDescriptor* alloc(); class RenderPipelineDescriptor* init(); NS::String* label() const; void setLabel(const NS::String* label); class Function* vertexFunction() const; void setVertexFunction(const class Function* vertexFunction); class Function* fragmentFunction() const; void setFragmentFunction(const class Function* fragmentFunction); class VertexDescriptor* vertexDescriptor() const; void setVertexDescriptor(const class VertexDescriptor* vertexDescriptor); NS::UInteger sampleCount() const; void setSampleCount(NS::UInteger sampleCount); NS::UInteger rasterSampleCount() const; void setRasterSampleCount(NS::UInteger rasterSampleCount); bool alphaToCoverageEnabled() const; void setAlphaToCoverageEnabled(bool alphaToCoverageEnabled); bool alphaToOneEnabled() const; void setAlphaToOneEnabled(bool alphaToOneEnabled); bool rasterizationEnabled() const; void setRasterizationEnabled(bool rasterizationEnabled); NS::UInteger maxVertexAmplificationCount() const; void setMaxVertexAmplificationCount(NS::UInteger maxVertexAmplificationCount); class RenderPipelineColorAttachmentDescriptorArray* colorAttachments() const; MTL::PixelFormat depthAttachmentPixelFormat() const; void setDepthAttachmentPixelFormat(MTL::PixelFormat depthAttachmentPixelFormat); MTL::PixelFormat stencilAttachmentPixelFormat() const; void setStencilAttachmentPixelFormat(MTL::PixelFormat stencilAttachmentPixelFormat); MTL::PrimitiveTopologyClass inputPrimitiveTopology() const; void setInputPrimitiveTopology(MTL::PrimitiveTopologyClass inputPrimitiveTopology); MTL::TessellationPartitionMode tessellationPartitionMode() const; void setTessellationPartitionMode(MTL::TessellationPartitionMode tessellationPartitionMode); NS::UInteger maxTessellationFactor() const; void setMaxTessellationFactor(NS::UInteger maxTessellationFactor); bool tessellationFactorScaleEnabled() const; void setTessellationFactorScaleEnabled(bool tessellationFactorScaleEnabled); MTL::TessellationFactorFormat tessellationFactorFormat() const; void setTessellationFactorFormat(MTL::TessellationFactorFormat tessellationFactorFormat); MTL::TessellationControlPointIndexType tessellationControlPointIndexType() const; void setTessellationControlPointIndexType(MTL::TessellationControlPointIndexType tessellationControlPointIndexType); MTL::TessellationFactorStepFunction tessellationFactorStepFunction() const; void setTessellationFactorStepFunction(MTL::TessellationFactorStepFunction tessellationFactorStepFunction); MTL::Winding tessellationOutputWindingOrder() const; void setTessellationOutputWindingOrder(MTL::Winding tessellationOutputWindingOrder); class PipelineBufferDescriptorArray* vertexBuffers() const; class PipelineBufferDescriptorArray* fragmentBuffers() const; bool supportIndirectCommandBuffers() const; void setSupportIndirectCommandBuffers(bool supportIndirectCommandBuffers); NS::Array* binaryArchives() const; void setBinaryArchives(const NS::Array* binaryArchives); NS::Array* vertexPreloadedLibraries() const; void setVertexPreloadedLibraries(const NS::Array* vertexPreloadedLibraries); NS::Array* fragmentPreloadedLibraries() const; void setFragmentPreloadedLibraries(const NS::Array* fragmentPreloadedLibraries); class LinkedFunctions* vertexLinkedFunctions() const; void setVertexLinkedFunctions(const class LinkedFunctions* vertexLinkedFunctions); class LinkedFunctions* fragmentLinkedFunctions() const; void setFragmentLinkedFunctions(const class LinkedFunctions* fragmentLinkedFunctions); bool supportAddingVertexBinaryFunctions() const; void setSupportAddingVertexBinaryFunctions(bool supportAddingVertexBinaryFunctions); bool supportAddingFragmentBinaryFunctions() const; void setSupportAddingFragmentBinaryFunctions(bool supportAddingFragmentBinaryFunctions); NS::UInteger maxVertexCallStackDepth() const; void setMaxVertexCallStackDepth(NS::UInteger maxVertexCallStackDepth); NS::UInteger maxFragmentCallStackDepth() const; void setMaxFragmentCallStackDepth(NS::UInteger maxFragmentCallStackDepth); void reset(); }; class RenderPipelineFunctionsDescriptor : public NS::Copying<RenderPipelineFunctionsDescriptor> { public: static class RenderPipelineFunctionsDescriptor* alloc(); class RenderPipelineFunctionsDescriptor* init(); NS::Array* vertexAdditionalBinaryFunctions() const; void setVertexAdditionalBinaryFunctions(const NS::Array* vertexAdditionalBinaryFunctions); NS::Array* fragmentAdditionalBinaryFunctions() const; void setFragmentAdditionalBinaryFunctions(const NS::Array* fragmentAdditionalBinaryFunctions); NS::Array* tileAdditionalBinaryFunctions() const; void setTileAdditionalBinaryFunctions(const NS::Array* tileAdditionalBinaryFunctions); }; class RenderPipelineState : public NS::Referencing<RenderPipelineState> { public: NS::String* label() const; class Device* device() const; NS::UInteger maxTotalThreadsPerThreadgroup() const; bool threadgroupSizeMatchesTileSize() const; NS::UInteger imageblockSampleLength() const; NS::UInteger imageblockMemoryLength(MTL::Size imageblockDimensions); bool supportIndirectCommandBuffers() const; NS::UInteger maxTotalThreadsPerObjectThreadgroup() const; NS::UInteger maxTotalThreadsPerMeshThreadgroup() const; NS::UInteger objectThreadExecutionWidth() const; NS::UInteger meshThreadExecutionWidth() const; NS::UInteger maxTotalThreadgroupsPerMeshGrid() const; MTL::ResourceID gpuResourceID() const; class FunctionHandle* functionHandle(const class Function* function, MTL::RenderStages stage); class VisibleFunctionTable* newVisibleFunctionTable(const class VisibleFunctionTableDescriptor* descriptor, MTL::RenderStages stage); class IntersectionFunctionTable* newIntersectionFunctionTable(const class IntersectionFunctionTableDescriptor* descriptor, MTL::RenderStages stage); class RenderPipelineState* newRenderPipelineState(const class RenderPipelineFunctionsDescriptor* additionalBinaryFunctions, NS::Error** error); }; class RenderPipelineColorAttachmentDescriptorArray : public NS::Referencing<RenderPipelineColorAttachmentDescriptorArray> { public: static class RenderPipelineColorAttachmentDescriptorArray* alloc(); class RenderPipelineColorAttachmentDescriptorArray* init(); class RenderPipelineColorAttachmentDescriptor* object(NS::UInteger attachmentIndex); void setObject(const class RenderPipelineColorAttachmentDescriptor* attachment, NS::UInteger attachmentIndex); }; class TileRenderPipelineColorAttachmentDescriptor : public NS::Copying<TileRenderPipelineColorAttachmentDescriptor> { public: static class TileRenderPipelineColorAttachmentDescriptor* alloc(); class TileRenderPipelineColorAttachmentDescriptor* init(); MTL::PixelFormat pixelFormat() const; void setPixelFormat(MTL::PixelFormat pixelFormat); }; class TileRenderPipelineColorAttachmentDescriptorArray : public NS::Referencing<TileRenderPipelineColorAttachmentDescriptorArray> { public: static class TileRenderPipelineColorAttachmentDescriptorArray* alloc(); class TileRenderPipelineColorAttachmentDescriptorArray* init(); class TileRenderPipelineColorAttachmentDescriptor* object(NS::UInteger attachmentIndex); void setObject(const class TileRenderPipelineColorAttachmentDescriptor* attachment, NS::UInteger attachmentIndex); }; class TileRenderPipelineDescriptor : public NS::Copying<TileRenderPipelineDescriptor> { public: static class TileRenderPipelineDescriptor* alloc(); class TileRenderPipelineDescriptor* init(); NS::String* label() const; void setLabel(const NS::String* label); class Function* tileFunction() const; void setTileFunction(const class Function* tileFunction); NS::UInteger rasterSampleCount() const; void setRasterSampleCount(NS::UInteger rasterSampleCount); class TileRenderPipelineColorAttachmentDescriptorArray* colorAttachments() const; bool threadgroupSizeMatchesTileSize() const; void setThreadgroupSizeMatchesTileSize(bool threadgroupSizeMatchesTileSize); class PipelineBufferDescriptorArray* tileBuffers() const; NS::UInteger maxTotalThreadsPerThreadgroup() const; void setMaxTotalThreadsPerThreadgroup(NS::UInteger maxTotalThreadsPerThreadgroup); NS::Array* binaryArchives() const; void setBinaryArchives(const NS::Array* binaryArchives); NS::Array* preloadedLibraries() const; void setPreloadedLibraries(const NS::Array* preloadedLibraries); class LinkedFunctions* linkedFunctions() const; void setLinkedFunctions(const class LinkedFunctions* linkedFunctions); bool supportAddingBinaryFunctions() const; void setSupportAddingBinaryFunctions(bool supportAddingBinaryFunctions); NS::UInteger maxCallStackDepth() const; void setMaxCallStackDepth(NS::UInteger maxCallStackDepth); void reset(); }; class MeshRenderPipelineDescriptor : public NS::Copying<MeshRenderPipelineDescriptor> { public: static class MeshRenderPipelineDescriptor* alloc(); class MeshRenderPipelineDescriptor* init(); NS::String* label() const; void setLabel(const NS::String* label); class Function* objectFunction() const; void setObjectFunction(const class Function* objectFunction); class Function* meshFunction() const; void setMeshFunction(const class Function* meshFunction); class Function* fragmentFunction() const; void setFragmentFunction(const class Function* fragmentFunction); NS::UInteger maxTotalThreadsPerObjectThreadgroup() const; void setMaxTotalThreadsPerObjectThreadgroup(NS::UInteger maxTotalThreadsPerObjectThreadgroup); NS::UInteger maxTotalThreadsPerMeshThreadgroup() const; void setMaxTotalThreadsPerMeshThreadgroup(NS::UInteger maxTotalThreadsPerMeshThreadgroup); bool objectThreadgroupSizeIsMultipleOfThreadExecutionWidth() const; void setObjectThreadgroupSizeIsMultipleOfThreadExecutionWidth(bool objectThreadgroupSizeIsMultipleOfThreadExecutionWidth); bool meshThreadgroupSizeIsMultipleOfThreadExecutionWidth() const; void setMeshThreadgroupSizeIsMultipleOfThreadExecutionWidth(bool meshThreadgroupSizeIsMultipleOfThreadExecutionWidth); NS::UInteger payloadMemoryLength() const; void setPayloadMemoryLength(NS::UInteger payloadMemoryLength); NS::UInteger maxTotalThreadgroupsPerMeshGrid() const; void setMaxTotalThreadgroupsPerMeshGrid(NS::UInteger maxTotalThreadgroupsPerMeshGrid); class PipelineBufferDescriptorArray* objectBuffers() const; class PipelineBufferDescriptorArray* meshBuffers() const; class PipelineBufferDescriptorArray* fragmentBuffers() const; NS::UInteger rasterSampleCount() const; void setRasterSampleCount(NS::UInteger rasterSampleCount); bool alphaToCoverageEnabled() const; void setAlphaToCoverageEnabled(bool alphaToCoverageEnabled); bool alphaToOneEnabled() const; void setAlphaToOneEnabled(bool alphaToOneEnabled); bool rasterizationEnabled() const; void setRasterizationEnabled(bool rasterizationEnabled); NS::UInteger maxVertexAmplificationCount() const; void setMaxVertexAmplificationCount(NS::UInteger maxVertexAmplificationCount); class RenderPipelineColorAttachmentDescriptorArray* colorAttachments() const; MTL::PixelFormat depthAttachmentPixelFormat() const; void setDepthAttachmentPixelFormat(MTL::PixelFormat depthAttachmentPixelFormat); MTL::PixelFormat stencilAttachmentPixelFormat() const; void setStencilAttachmentPixelFormat(MTL::PixelFormat stencilAttachmentPixelFormat); bool supportIndirectCommandBuffers() const; void setSupportIndirectCommandBuffers(bool supportIndirectCommandBuffers); class LinkedFunctions* objectLinkedFunctions() const; void setObjectLinkedFunctions(const class LinkedFunctions* objectLinkedFunctions); class LinkedFunctions* meshLinkedFunctions() const; void setMeshLinkedFunctions(const class LinkedFunctions* meshLinkedFunctions); class LinkedFunctions* fragmentLinkedFunctions() const; void setFragmentLinkedFunctions(const class LinkedFunctions* fragmentLinkedFunctions); void reset(); }; } _MTL_INLINE MTL::RenderPipelineColorAttachmentDescriptor* MTL::RenderPipelineColorAttachmentDescriptor::alloc() { return NS::Object::alloc<MTL::RenderPipelineColorAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPipelineColorAttachmentDescriptor)); } _MTL_INLINE MTL::RenderPipelineColorAttachmentDescriptor* MTL::RenderPipelineColorAttachmentDescriptor::init() { return NS::Object::init<MTL::RenderPipelineColorAttachmentDescriptor>(); } _MTL_INLINE MTL::PixelFormat MTL::RenderPipelineColorAttachmentDescriptor::pixelFormat() const { return Object::sendMessage<MTL::PixelFormat>(this, _MTL_PRIVATE_SEL(pixelFormat)); } _MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setPixelFormat(MTL::PixelFormat pixelFormat) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPixelFormat_), pixelFormat); } _MTL_INLINE bool MTL::RenderPipelineColorAttachmentDescriptor::blendingEnabled() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isBlendingEnabled)); } _MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setBlendingEnabled(bool blendingEnabled) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBlendingEnabled_), blendingEnabled); } _MTL_INLINE MTL::BlendFactor MTL::RenderPipelineColorAttachmentDescriptor::sourceRGBBlendFactor() const { return Object::sendMessage<MTL::BlendFactor>(this, _MTL_PRIVATE_SEL(sourceRGBBlendFactor)); } _MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setSourceRGBBlendFactor(MTL::BlendFactor sourceRGBBlendFactor) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSourceRGBBlendFactor_), sourceRGBBlendFactor); } _MTL_INLINE MTL::BlendFactor MTL::RenderPipelineColorAttachmentDescriptor::destinationRGBBlendFactor() const { return Object::sendMessage<MTL::BlendFactor>(this, _MTL_PRIVATE_SEL(destinationRGBBlendFactor)); } _MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setDestinationRGBBlendFactor(MTL::BlendFactor destinationRGBBlendFactor) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDestinationRGBBlendFactor_), destinationRGBBlendFactor); } _MTL_INLINE MTL::BlendOperation MTL::RenderPipelineColorAttachmentDescriptor::rgbBlendOperation() const { return Object::sendMessage<MTL::BlendOperation>(this, _MTL_PRIVATE_SEL(rgbBlendOperation)); } _MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setRgbBlendOperation(MTL::BlendOperation rgbBlendOperation) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRgbBlendOperation_), rgbBlendOperation); } _MTL_INLINE MTL::BlendFactor MTL::RenderPipelineColorAttachmentDescriptor::sourceAlphaBlendFactor() const { return Object::sendMessage<MTL::BlendFactor>(this, _MTL_PRIVATE_SEL(sourceAlphaBlendFactor)); } _MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setSourceAlphaBlendFactor(MTL::BlendFactor sourceAlphaBlendFactor) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSourceAlphaBlendFactor_), sourceAlphaBlendFactor); } _MTL_INLINE MTL::BlendFactor MTL::RenderPipelineColorAttachmentDescriptor::destinationAlphaBlendFactor() const { return Object::sendMessage<MTL::BlendFactor>(this, _MTL_PRIVATE_SEL(destinationAlphaBlendFactor)); } _MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setDestinationAlphaBlendFactor(MTL::BlendFactor destinationAlphaBlendFactor) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDestinationAlphaBlendFactor_), destinationAlphaBlendFactor); } _MTL_INLINE MTL::BlendOperation MTL::RenderPipelineColorAttachmentDescriptor::alphaBlendOperation() const { return Object::sendMessage<MTL::BlendOperation>(this, _MTL_PRIVATE_SEL(alphaBlendOperation)); } _MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setAlphaBlendOperation(MTL::BlendOperation alphaBlendOperation) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAlphaBlendOperation_), alphaBlendOperation); } _MTL_INLINE MTL::ColorWriteMask MTL::RenderPipelineColorAttachmentDescriptor::writeMask() const { return Object::sendMessage<MTL::ColorWriteMask>(this, _MTL_PRIVATE_SEL(writeMask)); } _MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptor::setWriteMask(MTL::ColorWriteMask writeMask) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setWriteMask_), writeMask); } _MTL_INLINE MTL::RenderPipelineReflection* MTL::RenderPipelineReflection::alloc() { return NS::Object::alloc<MTL::RenderPipelineReflection>(_MTL_PRIVATE_CLS(MTLRenderPipelineReflection)); } _MTL_INLINE MTL::RenderPipelineReflection* MTL::RenderPipelineReflection::init() { return NS::Object::init<MTL::RenderPipelineReflection>(); } _MTL_INLINE NS::Array* MTL::RenderPipelineReflection::vertexBindings() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(vertexBindings)); } _MTL_INLINE NS::Array* MTL::RenderPipelineReflection::fragmentBindings() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(fragmentBindings)); } _MTL_INLINE NS::Array* MTL::RenderPipelineReflection::tileBindings() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(tileBindings)); } _MTL_INLINE NS::Array* MTL::RenderPipelineReflection::objectBindings() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(objectBindings)); } _MTL_INLINE NS::Array* MTL::RenderPipelineReflection::meshBindings() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(meshBindings)); } _MTL_INLINE NS::Array* MTL::RenderPipelineReflection::vertexArguments() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(vertexArguments)); } _MTL_INLINE NS::Array* MTL::RenderPipelineReflection::fragmentArguments() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(fragmentArguments)); } _MTL_INLINE NS::Array* MTL::RenderPipelineReflection::tileArguments() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(tileArguments)); } _MTL_INLINE MTL::RenderPipelineDescriptor* MTL::RenderPipelineDescriptor::alloc() { return NS::Object::alloc<MTL::RenderPipelineDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPipelineDescriptor)); } _MTL_INLINE MTL::RenderPipelineDescriptor* MTL::RenderPipelineDescriptor::init() { return NS::Object::init<MTL::RenderPipelineDescriptor>(); } _MTL_INLINE NS::String* MTL::RenderPipelineDescriptor::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE MTL::Function* MTL::RenderPipelineDescriptor::vertexFunction() const { return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(vertexFunction)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setVertexFunction(const MTL::Function* vertexFunction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexFunction_), vertexFunction); } _MTL_INLINE MTL::Function* MTL::RenderPipelineDescriptor::fragmentFunction() const { return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(fragmentFunction)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setFragmentFunction(const MTL::Function* fragmentFunction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentFunction_), fragmentFunction); } _MTL_INLINE MTL::VertexDescriptor* MTL::RenderPipelineDescriptor::vertexDescriptor() const { return Object::sendMessage<MTL::VertexDescriptor*>(this, _MTL_PRIVATE_SEL(vertexDescriptor)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setVertexDescriptor(const MTL::VertexDescriptor* vertexDescriptor) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexDescriptor_), vertexDescriptor); } _MTL_INLINE NS::UInteger MTL::RenderPipelineDescriptor::sampleCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(sampleCount)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setSampleCount(NS::UInteger sampleCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSampleCount_), sampleCount); } _MTL_INLINE NS::UInteger MTL::RenderPipelineDescriptor::rasterSampleCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(rasterSampleCount)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setRasterSampleCount(NS::UInteger rasterSampleCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRasterSampleCount_), rasterSampleCount); } _MTL_INLINE bool MTL::RenderPipelineDescriptor::alphaToCoverageEnabled() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isAlphaToCoverageEnabled)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setAlphaToCoverageEnabled(bool alphaToCoverageEnabled) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAlphaToCoverageEnabled_), alphaToCoverageEnabled); } _MTL_INLINE bool MTL::RenderPipelineDescriptor::alphaToOneEnabled() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isAlphaToOneEnabled)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setAlphaToOneEnabled(bool alphaToOneEnabled) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAlphaToOneEnabled_), alphaToOneEnabled); } _MTL_INLINE bool MTL::RenderPipelineDescriptor::rasterizationEnabled() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isRasterizationEnabled)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setRasterizationEnabled(bool rasterizationEnabled) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRasterizationEnabled_), rasterizationEnabled); } _MTL_INLINE NS::UInteger MTL::RenderPipelineDescriptor::maxVertexAmplificationCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxVertexAmplificationCount)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setMaxVertexAmplificationCount(NS::UInteger maxVertexAmplificationCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxVertexAmplificationCount_), maxVertexAmplificationCount); } _MTL_INLINE MTL::RenderPipelineColorAttachmentDescriptorArray* MTL::RenderPipelineDescriptor::colorAttachments() const { return Object::sendMessage<MTL::RenderPipelineColorAttachmentDescriptorArray*>(this, _MTL_PRIVATE_SEL(colorAttachments)); } _MTL_INLINE MTL::PixelFormat MTL::RenderPipelineDescriptor::depthAttachmentPixelFormat() const { return Object::sendMessage<MTL::PixelFormat>(this, _MTL_PRIVATE_SEL(depthAttachmentPixelFormat)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setDepthAttachmentPixelFormat(MTL::PixelFormat depthAttachmentPixelFormat) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthAttachmentPixelFormat_), depthAttachmentPixelFormat); } _MTL_INLINE MTL::PixelFormat MTL::RenderPipelineDescriptor::stencilAttachmentPixelFormat() const { return Object::sendMessage<MTL::PixelFormat>(this, _MTL_PRIVATE_SEL(stencilAttachmentPixelFormat)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setStencilAttachmentPixelFormat(MTL::PixelFormat stencilAttachmentPixelFormat) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilAttachmentPixelFormat_), stencilAttachmentPixelFormat); } _MTL_INLINE MTL::PrimitiveTopologyClass MTL::RenderPipelineDescriptor::inputPrimitiveTopology() const { return Object::sendMessage<MTL::PrimitiveTopologyClass>(this, _MTL_PRIVATE_SEL(inputPrimitiveTopology)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setInputPrimitiveTopology(MTL::PrimitiveTopologyClass inputPrimitiveTopology) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setInputPrimitiveTopology_), inputPrimitiveTopology); } _MTL_INLINE MTL::TessellationPartitionMode MTL::RenderPipelineDescriptor::tessellationPartitionMode() const { return Object::sendMessage<MTL::TessellationPartitionMode>(this, _MTL_PRIVATE_SEL(tessellationPartitionMode)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setTessellationPartitionMode(MTL::TessellationPartitionMode tessellationPartitionMode) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTessellationPartitionMode_), tessellationPartitionMode); } _MTL_INLINE NS::UInteger MTL::RenderPipelineDescriptor::maxTessellationFactor() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxTessellationFactor)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setMaxTessellationFactor(NS::UInteger maxTessellationFactor) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxTessellationFactor_), maxTessellationFactor); } _MTL_INLINE bool MTL::RenderPipelineDescriptor::tessellationFactorScaleEnabled() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isTessellationFactorScaleEnabled)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setTessellationFactorScaleEnabled(bool tessellationFactorScaleEnabled) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTessellationFactorScaleEnabled_), tessellationFactorScaleEnabled); } _MTL_INLINE MTL::TessellationFactorFormat MTL::RenderPipelineDescriptor::tessellationFactorFormat() const { return Object::sendMessage<MTL::TessellationFactorFormat>(this, _MTL_PRIVATE_SEL(tessellationFactorFormat)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setTessellationFactorFormat(MTL::TessellationFactorFormat tessellationFactorFormat) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTessellationFactorFormat_), tessellationFactorFormat); } _MTL_INLINE MTL::TessellationControlPointIndexType MTL::RenderPipelineDescriptor::tessellationControlPointIndexType() const { return Object::sendMessage<MTL::TessellationControlPointIndexType>(this, _MTL_PRIVATE_SEL(tessellationControlPointIndexType)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setTessellationControlPointIndexType(MTL::TessellationControlPointIndexType tessellationControlPointIndexType) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTessellationControlPointIndexType_), tessellationControlPointIndexType); } _MTL_INLINE MTL::TessellationFactorStepFunction MTL::RenderPipelineDescriptor::tessellationFactorStepFunction() const { return Object::sendMessage<MTL::TessellationFactorStepFunction>(this, _MTL_PRIVATE_SEL(tessellationFactorStepFunction)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setTessellationFactorStepFunction(MTL::TessellationFactorStepFunction tessellationFactorStepFunction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTessellationFactorStepFunction_), tessellationFactorStepFunction); } _MTL_INLINE MTL::Winding MTL::RenderPipelineDescriptor::tessellationOutputWindingOrder() const { return Object::sendMessage<MTL::Winding>(this, _MTL_PRIVATE_SEL(tessellationOutputWindingOrder)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setTessellationOutputWindingOrder(MTL::Winding tessellationOutputWindingOrder) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTessellationOutputWindingOrder_), tessellationOutputWindingOrder); } _MTL_INLINE MTL::PipelineBufferDescriptorArray* MTL::RenderPipelineDescriptor::vertexBuffers() const { return Object::sendMessage<MTL::PipelineBufferDescriptorArray*>(this, _MTL_PRIVATE_SEL(vertexBuffers)); } _MTL_INLINE MTL::PipelineBufferDescriptorArray* MTL::RenderPipelineDescriptor::fragmentBuffers() const { return Object::sendMessage<MTL::PipelineBufferDescriptorArray*>(this, _MTL_PRIVATE_SEL(fragmentBuffers)); } _MTL_INLINE bool MTL::RenderPipelineDescriptor::supportIndirectCommandBuffers() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportIndirectCommandBuffers)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setSupportIndirectCommandBuffers(bool supportIndirectCommandBuffers) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSupportIndirectCommandBuffers_), supportIndirectCommandBuffers); } _MTL_INLINE NS::Array* MTL::RenderPipelineDescriptor::binaryArchives() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(binaryArchives)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setBinaryArchives(const NS::Array* binaryArchives) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBinaryArchives_), binaryArchives); } _MTL_INLINE NS::Array* MTL::RenderPipelineDescriptor::vertexPreloadedLibraries() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(vertexPreloadedLibraries)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setVertexPreloadedLibraries(const NS::Array* vertexPreloadedLibraries) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexPreloadedLibraries_), vertexPreloadedLibraries); } _MTL_INLINE NS::Array* MTL::RenderPipelineDescriptor::fragmentPreloadedLibraries() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(fragmentPreloadedLibraries)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setFragmentPreloadedLibraries(const NS::Array* fragmentPreloadedLibraries) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentPreloadedLibraries_), fragmentPreloadedLibraries); } _MTL_INLINE MTL::LinkedFunctions* MTL::RenderPipelineDescriptor::vertexLinkedFunctions() const { return Object::sendMessage<MTL::LinkedFunctions*>(this, _MTL_PRIVATE_SEL(vertexLinkedFunctions)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setVertexLinkedFunctions(const MTL::LinkedFunctions* vertexLinkedFunctions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexLinkedFunctions_), vertexLinkedFunctions); } _MTL_INLINE MTL::LinkedFunctions* MTL::RenderPipelineDescriptor::fragmentLinkedFunctions() const { return Object::sendMessage<MTL::LinkedFunctions*>(this, _MTL_PRIVATE_SEL(fragmentLinkedFunctions)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setFragmentLinkedFunctions(const MTL::LinkedFunctions* fragmentLinkedFunctions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentLinkedFunctions_), fragmentLinkedFunctions); } _MTL_INLINE bool MTL::RenderPipelineDescriptor::supportAddingVertexBinaryFunctions() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportAddingVertexBinaryFunctions)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setSupportAddingVertexBinaryFunctions(bool supportAddingVertexBinaryFunctions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSupportAddingVertexBinaryFunctions_), supportAddingVertexBinaryFunctions); } _MTL_INLINE bool MTL::RenderPipelineDescriptor::supportAddingFragmentBinaryFunctions() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportAddingFragmentBinaryFunctions)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setSupportAddingFragmentBinaryFunctions(bool supportAddingFragmentBinaryFunctions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSupportAddingFragmentBinaryFunctions_), supportAddingFragmentBinaryFunctions); } _MTL_INLINE NS::UInteger MTL::RenderPipelineDescriptor::maxVertexCallStackDepth() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxVertexCallStackDepth)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setMaxVertexCallStackDepth(NS::UInteger maxVertexCallStackDepth) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxVertexCallStackDepth_), maxVertexCallStackDepth); } _MTL_INLINE NS::UInteger MTL::RenderPipelineDescriptor::maxFragmentCallStackDepth() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxFragmentCallStackDepth)); } _MTL_INLINE void MTL::RenderPipelineDescriptor::setMaxFragmentCallStackDepth(NS::UInteger maxFragmentCallStackDepth) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxFragmentCallStackDepth_), maxFragmentCallStackDepth); } _MTL_INLINE void MTL::RenderPipelineDescriptor::reset() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(reset)); } _MTL_INLINE MTL::RenderPipelineFunctionsDescriptor* MTL::RenderPipelineFunctionsDescriptor::alloc() { return NS::Object::alloc<MTL::RenderPipelineFunctionsDescriptor>(_MTL_PRIVATE_CLS(MTLRenderPipelineFunctionsDescriptor)); } _MTL_INLINE MTL::RenderPipelineFunctionsDescriptor* MTL::RenderPipelineFunctionsDescriptor::init() { return NS::Object::init<MTL::RenderPipelineFunctionsDescriptor>(); } _MTL_INLINE NS::Array* MTL::RenderPipelineFunctionsDescriptor::vertexAdditionalBinaryFunctions() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(vertexAdditionalBinaryFunctions)); } _MTL_INLINE void MTL::RenderPipelineFunctionsDescriptor::setVertexAdditionalBinaryFunctions(const NS::Array* vertexAdditionalBinaryFunctions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setVertexAdditionalBinaryFunctions_), vertexAdditionalBinaryFunctions); } _MTL_INLINE NS::Array* MTL::RenderPipelineFunctionsDescriptor::fragmentAdditionalBinaryFunctions() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(fragmentAdditionalBinaryFunctions)); } _MTL_INLINE void MTL::RenderPipelineFunctionsDescriptor::setFragmentAdditionalBinaryFunctions(const NS::Array* fragmentAdditionalBinaryFunctions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentAdditionalBinaryFunctions_), fragmentAdditionalBinaryFunctions); } _MTL_INLINE NS::Array* MTL::RenderPipelineFunctionsDescriptor::tileAdditionalBinaryFunctions() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(tileAdditionalBinaryFunctions)); } _MTL_INLINE void MTL::RenderPipelineFunctionsDescriptor::setTileAdditionalBinaryFunctions(const NS::Array* tileAdditionalBinaryFunctions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileAdditionalBinaryFunctions_), tileAdditionalBinaryFunctions); } _MTL_INLINE NS::String* MTL::RenderPipelineState::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE MTL::Device* MTL::RenderPipelineState::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE NS::UInteger MTL::RenderPipelineState::maxTotalThreadsPerThreadgroup() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxTotalThreadsPerThreadgroup)); } _MTL_INLINE bool MTL::RenderPipelineState::threadgroupSizeMatchesTileSize() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(threadgroupSizeMatchesTileSize)); } _MTL_INLINE NS::UInteger MTL::RenderPipelineState::imageblockSampleLength() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(imageblockSampleLength)); } _MTL_INLINE NS::UInteger MTL::RenderPipelineState::imageblockMemoryLength(MTL::Size imageblockDimensions) { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(imageblockMemoryLengthForDimensions_), imageblockDimensions); } _MTL_INLINE bool MTL::RenderPipelineState::supportIndirectCommandBuffers() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportIndirectCommandBuffers)); } _MTL_INLINE NS::UInteger MTL::RenderPipelineState::maxTotalThreadsPerObjectThreadgroup() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxTotalThreadsPerObjectThreadgroup)); } _MTL_INLINE NS::UInteger MTL::RenderPipelineState::maxTotalThreadsPerMeshThreadgroup() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxTotalThreadsPerMeshThreadgroup)); } _MTL_INLINE NS::UInteger MTL::RenderPipelineState::objectThreadExecutionWidth() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(objectThreadExecutionWidth)); } _MTL_INLINE NS::UInteger MTL::RenderPipelineState::meshThreadExecutionWidth() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(meshThreadExecutionWidth)); } _MTL_INLINE NS::UInteger MTL::RenderPipelineState::maxTotalThreadgroupsPerMeshGrid() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxTotalThreadgroupsPerMeshGrid)); } _MTL_INLINE MTL::ResourceID MTL::RenderPipelineState::gpuResourceID() const { return Object::sendMessage<MTL::ResourceID>(this, _MTL_PRIVATE_SEL(gpuResourceID)); } _MTL_INLINE MTL::FunctionHandle* MTL::RenderPipelineState::functionHandle(const MTL::Function* function, MTL::RenderStages stage) { return Object::sendMessage<MTL::FunctionHandle*>(this, _MTL_PRIVATE_SEL(functionHandleWithFunction_stage_), function, stage); } _MTL_INLINE MTL::VisibleFunctionTable* MTL::RenderPipelineState::newVisibleFunctionTable(const MTL::VisibleFunctionTableDescriptor* descriptor, MTL::RenderStages stage) { return Object::sendMessage<MTL::VisibleFunctionTable*>(this, _MTL_PRIVATE_SEL(newVisibleFunctionTableWithDescriptor_stage_), descriptor, stage); } _MTL_INLINE MTL::IntersectionFunctionTable* MTL::RenderPipelineState::newIntersectionFunctionTable(const MTL::IntersectionFunctionTableDescriptor* descriptor, MTL::RenderStages stage) { return Object::sendMessage<MTL::IntersectionFunctionTable*>(this, _MTL_PRIVATE_SEL(newIntersectionFunctionTableWithDescriptor_stage_), descriptor, stage); } _MTL_INLINE MTL::RenderPipelineState* MTL::RenderPipelineState::newRenderPipelineState(const MTL::RenderPipelineFunctionsDescriptor* additionalBinaryFunctions, NS::Error** error) { return Object::sendMessage<MTL::RenderPipelineState*>(this, _MTL_PRIVATE_SEL(newRenderPipelineStateWithAdditionalBinaryFunctions_error_), additionalBinaryFunctions, error); } _MTL_INLINE MTL::RenderPipelineColorAttachmentDescriptorArray* MTL::RenderPipelineColorAttachmentDescriptorArray::alloc() { return NS::Object::alloc<MTL::RenderPipelineColorAttachmentDescriptorArray>(_MTL_PRIVATE_CLS(MTLRenderPipelineColorAttachmentDescriptorArray)); } _MTL_INLINE MTL::RenderPipelineColorAttachmentDescriptorArray* MTL::RenderPipelineColorAttachmentDescriptorArray::init() { return NS::Object::init<MTL::RenderPipelineColorAttachmentDescriptorArray>(); } _MTL_INLINE MTL::RenderPipelineColorAttachmentDescriptor* MTL::RenderPipelineColorAttachmentDescriptorArray::object(NS::UInteger attachmentIndex) { return Object::sendMessage<MTL::RenderPipelineColorAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), attachmentIndex); } _MTL_INLINE void MTL::RenderPipelineColorAttachmentDescriptorArray::setObject(const MTL::RenderPipelineColorAttachmentDescriptor* attachment, NS::UInteger attachmentIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attachment, attachmentIndex); } _MTL_INLINE MTL::TileRenderPipelineColorAttachmentDescriptor* MTL::TileRenderPipelineColorAttachmentDescriptor::alloc() { return NS::Object::alloc<MTL::TileRenderPipelineColorAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLTileRenderPipelineColorAttachmentDescriptor)); } _MTL_INLINE MTL::TileRenderPipelineColorAttachmentDescriptor* MTL::TileRenderPipelineColorAttachmentDescriptor::init() { return NS::Object::init<MTL::TileRenderPipelineColorAttachmentDescriptor>(); } _MTL_INLINE MTL::PixelFormat MTL::TileRenderPipelineColorAttachmentDescriptor::pixelFormat() const { return Object::sendMessage<MTL::PixelFormat>(this, _MTL_PRIVATE_SEL(pixelFormat)); } _MTL_INLINE void MTL::TileRenderPipelineColorAttachmentDescriptor::setPixelFormat(MTL::PixelFormat pixelFormat) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPixelFormat_), pixelFormat); } _MTL_INLINE MTL::TileRenderPipelineColorAttachmentDescriptorArray* MTL::TileRenderPipelineColorAttachmentDescriptorArray::alloc() { return NS::Object::alloc<MTL::TileRenderPipelineColorAttachmentDescriptorArray>(_MTL_PRIVATE_CLS(MTLTileRenderPipelineColorAttachmentDescriptorArray)); } _MTL_INLINE MTL::TileRenderPipelineColorAttachmentDescriptorArray* MTL::TileRenderPipelineColorAttachmentDescriptorArray::init() { return NS::Object::init<MTL::TileRenderPipelineColorAttachmentDescriptorArray>(); } _MTL_INLINE MTL::TileRenderPipelineColorAttachmentDescriptor* MTL::TileRenderPipelineColorAttachmentDescriptorArray::object(NS::UInteger attachmentIndex) { return Object::sendMessage<MTL::TileRenderPipelineColorAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), attachmentIndex); } _MTL_INLINE void MTL::TileRenderPipelineColorAttachmentDescriptorArray::setObject(const MTL::TileRenderPipelineColorAttachmentDescriptor* attachment, NS::UInteger attachmentIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attachment, attachmentIndex); } _MTL_INLINE MTL::TileRenderPipelineDescriptor* MTL::TileRenderPipelineDescriptor::alloc() { return NS::Object::alloc<MTL::TileRenderPipelineDescriptor>(_MTL_PRIVATE_CLS(MTLTileRenderPipelineDescriptor)); } _MTL_INLINE MTL::TileRenderPipelineDescriptor* MTL::TileRenderPipelineDescriptor::init() { return NS::Object::init<MTL::TileRenderPipelineDescriptor>(); } _MTL_INLINE NS::String* MTL::TileRenderPipelineDescriptor::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::TileRenderPipelineDescriptor::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE MTL::Function* MTL::TileRenderPipelineDescriptor::tileFunction() const { return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(tileFunction)); } _MTL_INLINE void MTL::TileRenderPipelineDescriptor::setTileFunction(const MTL::Function* tileFunction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTileFunction_), tileFunction); } _MTL_INLINE NS::UInteger MTL::TileRenderPipelineDescriptor::rasterSampleCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(rasterSampleCount)); } _MTL_INLINE void MTL::TileRenderPipelineDescriptor::setRasterSampleCount(NS::UInteger rasterSampleCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRasterSampleCount_), rasterSampleCount); } _MTL_INLINE MTL::TileRenderPipelineColorAttachmentDescriptorArray* MTL::TileRenderPipelineDescriptor::colorAttachments() const { return Object::sendMessage<MTL::TileRenderPipelineColorAttachmentDescriptorArray*>(this, _MTL_PRIVATE_SEL(colorAttachments)); } _MTL_INLINE bool MTL::TileRenderPipelineDescriptor::threadgroupSizeMatchesTileSize() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(threadgroupSizeMatchesTileSize)); } _MTL_INLINE void MTL::TileRenderPipelineDescriptor::setThreadgroupSizeMatchesTileSize(bool threadgroupSizeMatchesTileSize) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setThreadgroupSizeMatchesTileSize_), threadgroupSizeMatchesTileSize); } _MTL_INLINE MTL::PipelineBufferDescriptorArray* MTL::TileRenderPipelineDescriptor::tileBuffers() const { return Object::sendMessage<MTL::PipelineBufferDescriptorArray*>(this, _MTL_PRIVATE_SEL(tileBuffers)); } _MTL_INLINE NS::UInteger MTL::TileRenderPipelineDescriptor::maxTotalThreadsPerThreadgroup() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxTotalThreadsPerThreadgroup)); } _MTL_INLINE void MTL::TileRenderPipelineDescriptor::setMaxTotalThreadsPerThreadgroup(NS::UInteger maxTotalThreadsPerThreadgroup) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxTotalThreadsPerThreadgroup_), maxTotalThreadsPerThreadgroup); } _MTL_INLINE NS::Array* MTL::TileRenderPipelineDescriptor::binaryArchives() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(binaryArchives)); } _MTL_INLINE void MTL::TileRenderPipelineDescriptor::setBinaryArchives(const NS::Array* binaryArchives) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBinaryArchives_), binaryArchives); } _MTL_INLINE NS::Array* MTL::TileRenderPipelineDescriptor::preloadedLibraries() const { return Object::sendMessage<NS::Array*>(this, _MTL_PRIVATE_SEL(preloadedLibraries)); } _MTL_INLINE void MTL::TileRenderPipelineDescriptor::setPreloadedLibraries(const NS::Array* preloadedLibraries) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPreloadedLibraries_), preloadedLibraries); } _MTL_INLINE MTL::LinkedFunctions* MTL::TileRenderPipelineDescriptor::linkedFunctions() const { return Object::sendMessage<MTL::LinkedFunctions*>(this, _MTL_PRIVATE_SEL(linkedFunctions)); } _MTL_INLINE void MTL::TileRenderPipelineDescriptor::setLinkedFunctions(const MTL::LinkedFunctions* linkedFunctions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLinkedFunctions_), linkedFunctions); } _MTL_INLINE bool MTL::TileRenderPipelineDescriptor::supportAddingBinaryFunctions() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportAddingBinaryFunctions)); } _MTL_INLINE void MTL::TileRenderPipelineDescriptor::setSupportAddingBinaryFunctions(bool supportAddingBinaryFunctions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSupportAddingBinaryFunctions_), supportAddingBinaryFunctions); } _MTL_INLINE NS::UInteger MTL::TileRenderPipelineDescriptor::maxCallStackDepth() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxCallStackDepth)); } _MTL_INLINE void MTL::TileRenderPipelineDescriptor::setMaxCallStackDepth(NS::UInteger maxCallStackDepth) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxCallStackDepth_), maxCallStackDepth); } _MTL_INLINE void MTL::TileRenderPipelineDescriptor::reset() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(reset)); } _MTL_INLINE MTL::MeshRenderPipelineDescriptor* MTL::MeshRenderPipelineDescriptor::alloc() { return NS::Object::alloc<MTL::MeshRenderPipelineDescriptor>(_MTL_PRIVATE_CLS(MTLMeshRenderPipelineDescriptor)); } _MTL_INLINE MTL::MeshRenderPipelineDescriptor* MTL::MeshRenderPipelineDescriptor::init() { return NS::Object::init<MTL::MeshRenderPipelineDescriptor>(); } _MTL_INLINE NS::String* MTL::MeshRenderPipelineDescriptor::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE MTL::Function* MTL::MeshRenderPipelineDescriptor::objectFunction() const { return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(objectFunction)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setObjectFunction(const MTL::Function* objectFunction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObjectFunction_), objectFunction); } _MTL_INLINE MTL::Function* MTL::MeshRenderPipelineDescriptor::meshFunction() const { return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(meshFunction)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setMeshFunction(const MTL::Function* meshFunction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMeshFunction_), meshFunction); } _MTL_INLINE MTL::Function* MTL::MeshRenderPipelineDescriptor::fragmentFunction() const { return Object::sendMessage<MTL::Function*>(this, _MTL_PRIVATE_SEL(fragmentFunction)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setFragmentFunction(const MTL::Function* fragmentFunction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentFunction_), fragmentFunction); } _MTL_INLINE NS::UInteger MTL::MeshRenderPipelineDescriptor::maxTotalThreadsPerObjectThreadgroup() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxTotalThreadsPerObjectThreadgroup)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setMaxTotalThreadsPerObjectThreadgroup(NS::UInteger maxTotalThreadsPerObjectThreadgroup) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxTotalThreadsPerObjectThreadgroup_), maxTotalThreadsPerObjectThreadgroup); } _MTL_INLINE NS::UInteger MTL::MeshRenderPipelineDescriptor::maxTotalThreadsPerMeshThreadgroup() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxTotalThreadsPerMeshThreadgroup)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setMaxTotalThreadsPerMeshThreadgroup(NS::UInteger maxTotalThreadsPerMeshThreadgroup) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxTotalThreadsPerMeshThreadgroup_), maxTotalThreadsPerMeshThreadgroup); } _MTL_INLINE bool MTL::MeshRenderPipelineDescriptor::objectThreadgroupSizeIsMultipleOfThreadExecutionWidth() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(objectThreadgroupSizeIsMultipleOfThreadExecutionWidth)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setObjectThreadgroupSizeIsMultipleOfThreadExecutionWidth(bool objectThreadgroupSizeIsMultipleOfThreadExecutionWidth) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObjectThreadgroupSizeIsMultipleOfThreadExecutionWidth_), objectThreadgroupSizeIsMultipleOfThreadExecutionWidth); } _MTL_INLINE bool MTL::MeshRenderPipelineDescriptor::meshThreadgroupSizeIsMultipleOfThreadExecutionWidth() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(meshThreadgroupSizeIsMultipleOfThreadExecutionWidth)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setMeshThreadgroupSizeIsMultipleOfThreadExecutionWidth(bool meshThreadgroupSizeIsMultipleOfThreadExecutionWidth) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMeshThreadgroupSizeIsMultipleOfThreadExecutionWidth_), meshThreadgroupSizeIsMultipleOfThreadExecutionWidth); } _MTL_INLINE NS::UInteger MTL::MeshRenderPipelineDescriptor::payloadMemoryLength() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(payloadMemoryLength)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setPayloadMemoryLength(NS::UInteger payloadMemoryLength) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setPayloadMemoryLength_), payloadMemoryLength); } _MTL_INLINE NS::UInteger MTL::MeshRenderPipelineDescriptor::maxTotalThreadgroupsPerMeshGrid() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxTotalThreadgroupsPerMeshGrid)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setMaxTotalThreadgroupsPerMeshGrid(NS::UInteger maxTotalThreadgroupsPerMeshGrid) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxTotalThreadgroupsPerMeshGrid_), maxTotalThreadgroupsPerMeshGrid); } _MTL_INLINE MTL::PipelineBufferDescriptorArray* MTL::MeshRenderPipelineDescriptor::objectBuffers() const { return Object::sendMessage<MTL::PipelineBufferDescriptorArray*>(this, _MTL_PRIVATE_SEL(objectBuffers)); } _MTL_INLINE MTL::PipelineBufferDescriptorArray* MTL::MeshRenderPipelineDescriptor::meshBuffers() const { return Object::sendMessage<MTL::PipelineBufferDescriptorArray*>(this, _MTL_PRIVATE_SEL(meshBuffers)); } _MTL_INLINE MTL::PipelineBufferDescriptorArray* MTL::MeshRenderPipelineDescriptor::fragmentBuffers() const { return Object::sendMessage<MTL::PipelineBufferDescriptorArray*>(this, _MTL_PRIVATE_SEL(fragmentBuffers)); } _MTL_INLINE NS::UInteger MTL::MeshRenderPipelineDescriptor::rasterSampleCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(rasterSampleCount)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setRasterSampleCount(NS::UInteger rasterSampleCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRasterSampleCount_), rasterSampleCount); } _MTL_INLINE bool MTL::MeshRenderPipelineDescriptor::alphaToCoverageEnabled() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isAlphaToCoverageEnabled)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setAlphaToCoverageEnabled(bool alphaToCoverageEnabled) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAlphaToCoverageEnabled_), alphaToCoverageEnabled); } _MTL_INLINE bool MTL::MeshRenderPipelineDescriptor::alphaToOneEnabled() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isAlphaToOneEnabled)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setAlphaToOneEnabled(bool alphaToOneEnabled) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setAlphaToOneEnabled_), alphaToOneEnabled); } _MTL_INLINE bool MTL::MeshRenderPipelineDescriptor::rasterizationEnabled() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(isRasterizationEnabled)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setRasterizationEnabled(bool rasterizationEnabled) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRasterizationEnabled_), rasterizationEnabled); } _MTL_INLINE NS::UInteger MTL::MeshRenderPipelineDescriptor::maxVertexAmplificationCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxVertexAmplificationCount)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setMaxVertexAmplificationCount(NS::UInteger maxVertexAmplificationCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxVertexAmplificationCount_), maxVertexAmplificationCount); } _MTL_INLINE MTL::RenderPipelineColorAttachmentDescriptorArray* MTL::MeshRenderPipelineDescriptor::colorAttachments() const { return Object::sendMessage<MTL::RenderPipelineColorAttachmentDescriptorArray*>(this, _MTL_PRIVATE_SEL(colorAttachments)); } _MTL_INLINE MTL::PixelFormat MTL::MeshRenderPipelineDescriptor::depthAttachmentPixelFormat() const { return Object::sendMessage<MTL::PixelFormat>(this, _MTL_PRIVATE_SEL(depthAttachmentPixelFormat)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setDepthAttachmentPixelFormat(MTL::PixelFormat depthAttachmentPixelFormat) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setDepthAttachmentPixelFormat_), depthAttachmentPixelFormat); } _MTL_INLINE MTL::PixelFormat MTL::MeshRenderPipelineDescriptor::stencilAttachmentPixelFormat() const { return Object::sendMessage<MTL::PixelFormat>(this, _MTL_PRIVATE_SEL(stencilAttachmentPixelFormat)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setStencilAttachmentPixelFormat(MTL::PixelFormat stencilAttachmentPixelFormat) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStencilAttachmentPixelFormat_), stencilAttachmentPixelFormat); } _MTL_INLINE bool MTL::MeshRenderPipelineDescriptor::supportIndirectCommandBuffers() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportIndirectCommandBuffers)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setSupportIndirectCommandBuffers(bool supportIndirectCommandBuffers) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSupportIndirectCommandBuffers_), supportIndirectCommandBuffers); } _MTL_INLINE MTL::LinkedFunctions* MTL::MeshRenderPipelineDescriptor::objectLinkedFunctions() const { return Object::sendMessage<MTL::LinkedFunctions*>(this, _MTL_PRIVATE_SEL(objectLinkedFunctions)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setObjectLinkedFunctions(const MTL::LinkedFunctions* objectLinkedFunctions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObjectLinkedFunctions_), objectLinkedFunctions); } _MTL_INLINE MTL::LinkedFunctions* MTL::MeshRenderPipelineDescriptor::meshLinkedFunctions() const { return Object::sendMessage<MTL::LinkedFunctions*>(this, _MTL_PRIVATE_SEL(meshLinkedFunctions)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setMeshLinkedFunctions(const MTL::LinkedFunctions* meshLinkedFunctions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMeshLinkedFunctions_), meshLinkedFunctions); } _MTL_INLINE MTL::LinkedFunctions* MTL::MeshRenderPipelineDescriptor::fragmentLinkedFunctions() const { return Object::sendMessage<MTL::LinkedFunctions*>(this, _MTL_PRIVATE_SEL(fragmentLinkedFunctions)); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::setFragmentLinkedFunctions(const MTL::LinkedFunctions* fragmentLinkedFunctions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFragmentLinkedFunctions_), fragmentLinkedFunctions); } _MTL_INLINE void MTL::MeshRenderPipelineDescriptor::reset() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(reset)); } #pragma once namespace MTL { _MTL_ENUM(NS::UInteger, SparseTextureMappingMode) { SparseTextureMappingModeMap = 0, SparseTextureMappingModeUnmap = 1, }; struct MapIndirectArguments { uint32_t regionOriginX; uint32_t regionOriginY; uint32_t regionOriginZ; uint32_t regionSizeWidth; uint32_t regionSizeHeight; uint32_t regionSizeDepth; uint32_t mipMapLevel; uint32_t sliceId; } _MTL_PACKED; class ResourceStateCommandEncoder : public NS::Referencing<ResourceStateCommandEncoder, CommandEncoder> { public: void updateTextureMappings(const class Texture* texture, const MTL::SparseTextureMappingMode mode, const MTL::Region* regions, const NS::UInteger* mipLevels, const NS::UInteger* slices, NS::UInteger numRegions); void updateTextureMapping(const class Texture* texture, const MTL::SparseTextureMappingMode mode, const MTL::Region region, const NS::UInteger mipLevel, const NS::UInteger slice); void updateTextureMapping(const class Texture* texture, const MTL::SparseTextureMappingMode mode, const class Buffer* indirectBuffer, NS::UInteger indirectBufferOffset); void updateFence(const class Fence* fence); void waitForFence(const class Fence* fence); void moveTextureMappingsFromTexture(const class Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, MTL::Origin sourceOrigin, MTL::Size sourceSize, const class Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, MTL::Origin destinationOrigin); }; } _MTL_INLINE void MTL::ResourceStateCommandEncoder::updateTextureMappings(const MTL::Texture* texture, const MTL::SparseTextureMappingMode mode, const MTL::Region* regions, const NS::UInteger* mipLevels, const NS::UInteger* slices, NS::UInteger numRegions) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(updateTextureMappings_mode_regions_mipLevels_slices_numRegions_), texture, mode, regions, mipLevels, slices, numRegions); } _MTL_INLINE void MTL::ResourceStateCommandEncoder::updateTextureMapping(const MTL::Texture* texture, const MTL::SparseTextureMappingMode mode, const MTL::Region region, const NS::UInteger mipLevel, const NS::UInteger slice) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(updateTextureMapping_mode_region_mipLevel_slice_), texture, mode, region, mipLevel, slice); } _MTL_INLINE void MTL::ResourceStateCommandEncoder::updateTextureMapping(const MTL::Texture* texture, const MTL::SparseTextureMappingMode mode, const MTL::Buffer* indirectBuffer, NS::UInteger indirectBufferOffset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(updateTextureMapping_mode_indirectBuffer_indirectBufferOffset_), texture, mode, indirectBuffer, indirectBufferOffset); } _MTL_INLINE void MTL::ResourceStateCommandEncoder::updateFence(const MTL::Fence* fence) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(updateFence_), fence); } _MTL_INLINE void MTL::ResourceStateCommandEncoder::waitForFence(const MTL::Fence* fence) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(waitForFence_), fence); } _MTL_INLINE void MTL::ResourceStateCommandEncoder::moveTextureMappingsFromTexture(const MTL::Texture* sourceTexture, NS::UInteger sourceSlice, NS::UInteger sourceLevel, MTL::Origin sourceOrigin, MTL::Size sourceSize, const MTL::Texture* destinationTexture, NS::UInteger destinationSlice, NS::UInteger destinationLevel, MTL::Origin destinationOrigin) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(moveTextureMappingsFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin_), sourceTexture, sourceSlice, sourceLevel, sourceOrigin, sourceSize, destinationTexture, destinationSlice, destinationLevel, destinationOrigin); } #pragma once namespace MTL { class ResourceStatePassSampleBufferAttachmentDescriptor : public NS::Copying<ResourceStatePassSampleBufferAttachmentDescriptor> { public: static class ResourceStatePassSampleBufferAttachmentDescriptor* alloc(); class ResourceStatePassSampleBufferAttachmentDescriptor* init(); class CounterSampleBuffer* sampleBuffer() const; void setSampleBuffer(const class CounterSampleBuffer* sampleBuffer); NS::UInteger startOfEncoderSampleIndex() const; void setStartOfEncoderSampleIndex(NS::UInteger startOfEncoderSampleIndex); NS::UInteger endOfEncoderSampleIndex() const; void setEndOfEncoderSampleIndex(NS::UInteger endOfEncoderSampleIndex); }; class ResourceStatePassSampleBufferAttachmentDescriptorArray : public NS::Referencing<ResourceStatePassSampleBufferAttachmentDescriptorArray> { public: static class ResourceStatePassSampleBufferAttachmentDescriptorArray* alloc(); class ResourceStatePassSampleBufferAttachmentDescriptorArray* init(); class ResourceStatePassSampleBufferAttachmentDescriptor* object(NS::UInteger attachmentIndex); void setObject(const class ResourceStatePassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex); }; class ResourceStatePassDescriptor : public NS::Copying<ResourceStatePassDescriptor> { public: static class ResourceStatePassDescriptor* alloc(); class ResourceStatePassDescriptor* init(); static class ResourceStatePassDescriptor* resourceStatePassDescriptor(); class ResourceStatePassSampleBufferAttachmentDescriptorArray* sampleBufferAttachments() const; }; } _MTL_INLINE MTL::ResourceStatePassSampleBufferAttachmentDescriptor* MTL::ResourceStatePassSampleBufferAttachmentDescriptor::alloc() { return NS::Object::alloc<MTL::ResourceStatePassSampleBufferAttachmentDescriptor>(_MTL_PRIVATE_CLS(MTLResourceStatePassSampleBufferAttachmentDescriptor)); } _MTL_INLINE MTL::ResourceStatePassSampleBufferAttachmentDescriptor* MTL::ResourceStatePassSampleBufferAttachmentDescriptor::init() { return NS::Object::init<MTL::ResourceStatePassSampleBufferAttachmentDescriptor>(); } _MTL_INLINE MTL::CounterSampleBuffer* MTL::ResourceStatePassSampleBufferAttachmentDescriptor::sampleBuffer() const { return Object::sendMessage<MTL::CounterSampleBuffer*>(this, _MTL_PRIVATE_SEL(sampleBuffer)); } _MTL_INLINE void MTL::ResourceStatePassSampleBufferAttachmentDescriptor::setSampleBuffer(const MTL::CounterSampleBuffer* sampleBuffer) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSampleBuffer_), sampleBuffer); } _MTL_INLINE NS::UInteger MTL::ResourceStatePassSampleBufferAttachmentDescriptor::startOfEncoderSampleIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(startOfEncoderSampleIndex)); } _MTL_INLINE void MTL::ResourceStatePassSampleBufferAttachmentDescriptor::setStartOfEncoderSampleIndex(NS::UInteger startOfEncoderSampleIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStartOfEncoderSampleIndex_), startOfEncoderSampleIndex); } _MTL_INLINE NS::UInteger MTL::ResourceStatePassSampleBufferAttachmentDescriptor::endOfEncoderSampleIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(endOfEncoderSampleIndex)); } _MTL_INLINE void MTL::ResourceStatePassSampleBufferAttachmentDescriptor::setEndOfEncoderSampleIndex(NS::UInteger endOfEncoderSampleIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setEndOfEncoderSampleIndex_), endOfEncoderSampleIndex); } _MTL_INLINE MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray* MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray::alloc() { return NS::Object::alloc<MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray>(_MTL_PRIVATE_CLS(MTLResourceStatePassSampleBufferAttachmentDescriptorArray)); } _MTL_INLINE MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray* MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray::init() { return NS::Object::init<MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray>(); } _MTL_INLINE MTL::ResourceStatePassSampleBufferAttachmentDescriptor* MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray::object(NS::UInteger attachmentIndex) { return Object::sendMessage<MTL::ResourceStatePassSampleBufferAttachmentDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), attachmentIndex); } _MTL_INLINE void MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray::setObject(const MTL::ResourceStatePassSampleBufferAttachmentDescriptor* attachment, NS::UInteger attachmentIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attachment, attachmentIndex); } _MTL_INLINE MTL::ResourceStatePassDescriptor* MTL::ResourceStatePassDescriptor::alloc() { return NS::Object::alloc<MTL::ResourceStatePassDescriptor>(_MTL_PRIVATE_CLS(MTLResourceStatePassDescriptor)); } _MTL_INLINE MTL::ResourceStatePassDescriptor* MTL::ResourceStatePassDescriptor::init() { return NS::Object::init<MTL::ResourceStatePassDescriptor>(); } _MTL_INLINE MTL::ResourceStatePassDescriptor* MTL::ResourceStatePassDescriptor::resourceStatePassDescriptor() { return Object::sendMessage<MTL::ResourceStatePassDescriptor*>(_MTL_PRIVATE_CLS(MTLResourceStatePassDescriptor), _MTL_PRIVATE_SEL(resourceStatePassDescriptor)); } _MTL_INLINE MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray* MTL::ResourceStatePassDescriptor::sampleBufferAttachments() const { return Object::sendMessage<MTL::ResourceStatePassSampleBufferAttachmentDescriptorArray*>(this, _MTL_PRIVATE_SEL(sampleBufferAttachments)); } #pragma once namespace MTL { _MTL_ENUM(NS::UInteger, SamplerMinMagFilter) { SamplerMinMagFilterNearest = 0, SamplerMinMagFilterLinear = 1, }; _MTL_ENUM(NS::UInteger, SamplerMipFilter) { SamplerMipFilterNotMipmapped = 0, SamplerMipFilterNearest = 1, SamplerMipFilterLinear = 2, }; _MTL_ENUM(NS::UInteger, SamplerAddressMode) { SamplerAddressModeClampToEdge = 0, SamplerAddressModeMirrorClampToEdge = 1, SamplerAddressModeRepeat = 2, SamplerAddressModeMirrorRepeat = 3, SamplerAddressModeClampToZero = 4, SamplerAddressModeClampToBorderColor = 5, }; _MTL_ENUM(NS::UInteger, SamplerBorderColor) { SamplerBorderColorTransparentBlack = 0, SamplerBorderColorOpaqueBlack = 1, SamplerBorderColorOpaqueWhite = 2, }; class SamplerDescriptor : public NS::Copying<SamplerDescriptor> { public: static class SamplerDescriptor* alloc(); class SamplerDescriptor* init(); MTL::SamplerMinMagFilter minFilter() const; void setMinFilter(MTL::SamplerMinMagFilter minFilter); MTL::SamplerMinMagFilter magFilter() const; void setMagFilter(MTL::SamplerMinMagFilter magFilter); MTL::SamplerMipFilter mipFilter() const; void setMipFilter(MTL::SamplerMipFilter mipFilter); NS::UInteger maxAnisotropy() const; void setMaxAnisotropy(NS::UInteger maxAnisotropy); MTL::SamplerAddressMode sAddressMode() const; void setSAddressMode(MTL::SamplerAddressMode sAddressMode); MTL::SamplerAddressMode tAddressMode() const; void setTAddressMode(MTL::SamplerAddressMode tAddressMode); MTL::SamplerAddressMode rAddressMode() const; void setRAddressMode(MTL::SamplerAddressMode rAddressMode); MTL::SamplerBorderColor borderColor() const; void setBorderColor(MTL::SamplerBorderColor borderColor); bool normalizedCoordinates() const; void setNormalizedCoordinates(bool normalizedCoordinates); float lodMinClamp() const; void setLodMinClamp(float lodMinClamp); float lodMaxClamp() const; void setLodMaxClamp(float lodMaxClamp); bool lodAverage() const; void setLodAverage(bool lodAverage); MTL::CompareFunction compareFunction() const; void setCompareFunction(MTL::CompareFunction compareFunction); bool supportArgumentBuffers() const; void setSupportArgumentBuffers(bool supportArgumentBuffers); NS::String* label() const; void setLabel(const NS::String* label); }; class SamplerState : public NS::Referencing<SamplerState> { public: NS::String* label() const; class Device* device() const; MTL::ResourceID gpuResourceID() const; }; } _MTL_INLINE MTL::SamplerDescriptor* MTL::SamplerDescriptor::alloc() { return NS::Object::alloc<MTL::SamplerDescriptor>(_MTL_PRIVATE_CLS(MTLSamplerDescriptor)); } _MTL_INLINE MTL::SamplerDescriptor* MTL::SamplerDescriptor::init() { return NS::Object::init<MTL::SamplerDescriptor>(); } _MTL_INLINE MTL::SamplerMinMagFilter MTL::SamplerDescriptor::minFilter() const { return Object::sendMessage<MTL::SamplerMinMagFilter>(this, _MTL_PRIVATE_SEL(minFilter)); } _MTL_INLINE void MTL::SamplerDescriptor::setMinFilter(MTL::SamplerMinMagFilter minFilter) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMinFilter_), minFilter); } _MTL_INLINE MTL::SamplerMinMagFilter MTL::SamplerDescriptor::magFilter() const { return Object::sendMessage<MTL::SamplerMinMagFilter>(this, _MTL_PRIVATE_SEL(magFilter)); } _MTL_INLINE void MTL::SamplerDescriptor::setMagFilter(MTL::SamplerMinMagFilter magFilter) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMagFilter_), magFilter); } _MTL_INLINE MTL::SamplerMipFilter MTL::SamplerDescriptor::mipFilter() const { return Object::sendMessage<MTL::SamplerMipFilter>(this, _MTL_PRIVATE_SEL(mipFilter)); } _MTL_INLINE void MTL::SamplerDescriptor::setMipFilter(MTL::SamplerMipFilter mipFilter) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMipFilter_), mipFilter); } _MTL_INLINE NS::UInteger MTL::SamplerDescriptor::maxAnisotropy() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(maxAnisotropy)); } _MTL_INLINE void MTL::SamplerDescriptor::setMaxAnisotropy(NS::UInteger maxAnisotropy) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setMaxAnisotropy_), maxAnisotropy); } _MTL_INLINE MTL::SamplerAddressMode MTL::SamplerDescriptor::sAddressMode() const { return Object::sendMessage<MTL::SamplerAddressMode>(this, _MTL_PRIVATE_SEL(sAddressMode)); } _MTL_INLINE void MTL::SamplerDescriptor::setSAddressMode(MTL::SamplerAddressMode sAddressMode) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSAddressMode_), sAddressMode); } _MTL_INLINE MTL::SamplerAddressMode MTL::SamplerDescriptor::tAddressMode() const { return Object::sendMessage<MTL::SamplerAddressMode>(this, _MTL_PRIVATE_SEL(tAddressMode)); } _MTL_INLINE void MTL::SamplerDescriptor::setTAddressMode(MTL::SamplerAddressMode tAddressMode) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setTAddressMode_), tAddressMode); } _MTL_INLINE MTL::SamplerAddressMode MTL::SamplerDescriptor::rAddressMode() const { return Object::sendMessage<MTL::SamplerAddressMode>(this, _MTL_PRIVATE_SEL(rAddressMode)); } _MTL_INLINE void MTL::SamplerDescriptor::setRAddressMode(MTL::SamplerAddressMode rAddressMode) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setRAddressMode_), rAddressMode); } _MTL_INLINE MTL::SamplerBorderColor MTL::SamplerDescriptor::borderColor() const { return Object::sendMessage<MTL::SamplerBorderColor>(this, _MTL_PRIVATE_SEL(borderColor)); } _MTL_INLINE void MTL::SamplerDescriptor::setBorderColor(MTL::SamplerBorderColor borderColor) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBorderColor_), borderColor); } _MTL_INLINE bool MTL::SamplerDescriptor::normalizedCoordinates() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(normalizedCoordinates)); } _MTL_INLINE void MTL::SamplerDescriptor::setNormalizedCoordinates(bool normalizedCoordinates) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setNormalizedCoordinates_), normalizedCoordinates); } _MTL_INLINE float MTL::SamplerDescriptor::lodMinClamp() const { return Object::sendMessage<float>(this, _MTL_PRIVATE_SEL(lodMinClamp)); } _MTL_INLINE void MTL::SamplerDescriptor::setLodMinClamp(float lodMinClamp) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLodMinClamp_), lodMinClamp); } _MTL_INLINE float MTL::SamplerDescriptor::lodMaxClamp() const { return Object::sendMessage<float>(this, _MTL_PRIVATE_SEL(lodMaxClamp)); } _MTL_INLINE void MTL::SamplerDescriptor::setLodMaxClamp(float lodMaxClamp) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLodMaxClamp_), lodMaxClamp); } _MTL_INLINE bool MTL::SamplerDescriptor::lodAverage() const { return Object::sendMessage<bool>(this, _MTL_PRIVATE_SEL(lodAverage)); } _MTL_INLINE void MTL::SamplerDescriptor::setLodAverage(bool lodAverage) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLodAverage_), lodAverage); } _MTL_INLINE MTL::CompareFunction MTL::SamplerDescriptor::compareFunction() const { return Object::sendMessage<MTL::CompareFunction>(this, _MTL_PRIVATE_SEL(compareFunction)); } _MTL_INLINE void MTL::SamplerDescriptor::setCompareFunction(MTL::CompareFunction compareFunction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setCompareFunction_), compareFunction); } _MTL_INLINE bool MTL::SamplerDescriptor::supportArgumentBuffers() const { return Object::sendMessageSafe<bool>(this, _MTL_PRIVATE_SEL(supportArgumentBuffers)); } _MTL_INLINE void MTL::SamplerDescriptor::setSupportArgumentBuffers(bool supportArgumentBuffers) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setSupportArgumentBuffers_), supportArgumentBuffers); } _MTL_INLINE NS::String* MTL::SamplerDescriptor::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE void MTL::SamplerDescriptor::setLabel(const NS::String* label) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setLabel_), label); } _MTL_INLINE NS::String* MTL::SamplerState::label() const { return Object::sendMessage<NS::String*>(this, _MTL_PRIVATE_SEL(label)); } _MTL_INLINE MTL::Device* MTL::SamplerState::device() const { return Object::sendMessage<MTL::Device*>(this, _MTL_PRIVATE_SEL(device)); } _MTL_INLINE MTL::ResourceID MTL::SamplerState::gpuResourceID() const { return Object::sendMessage<MTL::ResourceID>(this, _MTL_PRIVATE_SEL(gpuResourceID)); } #pragma once namespace MTL { static const NS::UInteger BufferLayoutStrideDynamic = NS::UIntegerMax; _MTL_ENUM(NS::UInteger, VertexFormat) { VertexFormatInvalid = 0, VertexFormatUChar2 = 1, VertexFormatUChar3 = 2, VertexFormatUChar4 = 3, VertexFormatChar2 = 4, VertexFormatChar3 = 5, VertexFormatChar4 = 6, VertexFormatUChar2Normalized = 7, VertexFormatUChar3Normalized = 8, VertexFormatUChar4Normalized = 9, VertexFormatChar2Normalized = 10, VertexFormatChar3Normalized = 11, VertexFormatChar4Normalized = 12, VertexFormatUShort2 = 13, VertexFormatUShort3 = 14, VertexFormatUShort4 = 15, VertexFormatShort2 = 16, VertexFormatShort3 = 17, VertexFormatShort4 = 18, VertexFormatUShort2Normalized = 19, VertexFormatUShort3Normalized = 20, VertexFormatUShort4Normalized = 21, VertexFormatShort2Normalized = 22, VertexFormatShort3Normalized = 23, VertexFormatShort4Normalized = 24, VertexFormatHalf2 = 25, VertexFormatHalf3 = 26, VertexFormatHalf4 = 27, VertexFormatFloat = 28, VertexFormatFloat2 = 29, VertexFormatFloat3 = 30, VertexFormatFloat4 = 31, VertexFormatInt = 32, VertexFormatInt2 = 33, VertexFormatInt3 = 34, VertexFormatInt4 = 35, VertexFormatUInt = 36, VertexFormatUInt2 = 37, VertexFormatUInt3 = 38, VertexFormatUInt4 = 39, VertexFormatInt1010102Normalized = 40, VertexFormatUInt1010102Normalized = 41, VertexFormatUChar4Normalized_BGRA = 42, VertexFormatUChar = 45, VertexFormatChar = 46, VertexFormatUCharNormalized = 47, VertexFormatCharNormalized = 48, VertexFormatUShort = 49, VertexFormatShort = 50, VertexFormatUShortNormalized = 51, VertexFormatShortNormalized = 52, VertexFormatHalf = 53, VertexFormatFloatRG11B10 = 54, VertexFormatFloatRGB9E5 = 55, }; _MTL_ENUM(NS::UInteger, VertexStepFunction) { VertexStepFunctionConstant = 0, VertexStepFunctionPerVertex = 1, VertexStepFunctionPerInstance = 2, VertexStepFunctionPerPatch = 3, VertexStepFunctionPerPatchControlPoint = 4, }; class VertexBufferLayoutDescriptor : public NS::Copying<VertexBufferLayoutDescriptor> { public: static class VertexBufferLayoutDescriptor* alloc(); class VertexBufferLayoutDescriptor* init(); NS::UInteger stride() const; void setStride(NS::UInteger stride); MTL::VertexStepFunction stepFunction() const; void setStepFunction(MTL::VertexStepFunction stepFunction); NS::UInteger stepRate() const; void setStepRate(NS::UInteger stepRate); }; class VertexBufferLayoutDescriptorArray : public NS::Referencing<VertexBufferLayoutDescriptorArray> { public: static class VertexBufferLayoutDescriptorArray* alloc(); class VertexBufferLayoutDescriptorArray* init(); class VertexBufferLayoutDescriptor* object(NS::UInteger index); void setObject(const class VertexBufferLayoutDescriptor* bufferDesc, NS::UInteger index); }; class VertexAttributeDescriptor : public NS::Copying<VertexAttributeDescriptor> { public: static class VertexAttributeDescriptor* alloc(); class VertexAttributeDescriptor* init(); MTL::VertexFormat format() const; void setFormat(MTL::VertexFormat format); NS::UInteger offset() const; void setOffset(NS::UInteger offset); NS::UInteger bufferIndex() const; void setBufferIndex(NS::UInteger bufferIndex); }; class VertexAttributeDescriptorArray : public NS::Referencing<VertexAttributeDescriptorArray> { public: static class VertexAttributeDescriptorArray* alloc(); class VertexAttributeDescriptorArray* init(); class VertexAttributeDescriptor* object(NS::UInteger index); void setObject(const class VertexAttributeDescriptor* attributeDesc, NS::UInteger index); }; class VertexDescriptor : public NS::Copying<VertexDescriptor> { public: static class VertexDescriptor* alloc(); class VertexDescriptor* init(); static class VertexDescriptor* vertexDescriptor(); class VertexBufferLayoutDescriptorArray* layouts() const; class VertexAttributeDescriptorArray* attributes() const; void reset(); }; } _MTL_INLINE MTL::VertexBufferLayoutDescriptor* MTL::VertexBufferLayoutDescriptor::alloc() { return NS::Object::alloc<MTL::VertexBufferLayoutDescriptor>(_MTL_PRIVATE_CLS(MTLVertexBufferLayoutDescriptor)); } _MTL_INLINE MTL::VertexBufferLayoutDescriptor* MTL::VertexBufferLayoutDescriptor::init() { return NS::Object::init<MTL::VertexBufferLayoutDescriptor>(); } _MTL_INLINE NS::UInteger MTL::VertexBufferLayoutDescriptor::stride() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(stride)); } _MTL_INLINE void MTL::VertexBufferLayoutDescriptor::setStride(NS::UInteger stride) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStride_), stride); } _MTL_INLINE MTL::VertexStepFunction MTL::VertexBufferLayoutDescriptor::stepFunction() const { return Object::sendMessage<MTL::VertexStepFunction>(this, _MTL_PRIVATE_SEL(stepFunction)); } _MTL_INLINE void MTL::VertexBufferLayoutDescriptor::setStepFunction(MTL::VertexStepFunction stepFunction) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStepFunction_), stepFunction); } _MTL_INLINE NS::UInteger MTL::VertexBufferLayoutDescriptor::stepRate() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(stepRate)); } _MTL_INLINE void MTL::VertexBufferLayoutDescriptor::setStepRate(NS::UInteger stepRate) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setStepRate_), stepRate); } _MTL_INLINE MTL::VertexBufferLayoutDescriptorArray* MTL::VertexBufferLayoutDescriptorArray::alloc() { return NS::Object::alloc<MTL::VertexBufferLayoutDescriptorArray>(_MTL_PRIVATE_CLS(MTLVertexBufferLayoutDescriptorArray)); } _MTL_INLINE MTL::VertexBufferLayoutDescriptorArray* MTL::VertexBufferLayoutDescriptorArray::init() { return NS::Object::init<MTL::VertexBufferLayoutDescriptorArray>(); } _MTL_INLINE MTL::VertexBufferLayoutDescriptor* MTL::VertexBufferLayoutDescriptorArray::object(NS::UInteger index) { return Object::sendMessage<MTL::VertexBufferLayoutDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), index); } _MTL_INLINE void MTL::VertexBufferLayoutDescriptorArray::setObject(const MTL::VertexBufferLayoutDescriptor* bufferDesc, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), bufferDesc, index); } _MTL_INLINE MTL::VertexAttributeDescriptor* MTL::VertexAttributeDescriptor::alloc() { return NS::Object::alloc<MTL::VertexAttributeDescriptor>(_MTL_PRIVATE_CLS(MTLVertexAttributeDescriptor)); } _MTL_INLINE MTL::VertexAttributeDescriptor* MTL::VertexAttributeDescriptor::init() { return NS::Object::init<MTL::VertexAttributeDescriptor>(); } _MTL_INLINE MTL::VertexFormat MTL::VertexAttributeDescriptor::format() const { return Object::sendMessage<MTL::VertexFormat>(this, _MTL_PRIVATE_SEL(format)); } _MTL_INLINE void MTL::VertexAttributeDescriptor::setFormat(MTL::VertexFormat format) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFormat_), format); } _MTL_INLINE NS::UInteger MTL::VertexAttributeDescriptor::offset() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(offset)); } _MTL_INLINE void MTL::VertexAttributeDescriptor::setOffset(NS::UInteger offset) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setOffset_), offset); } _MTL_INLINE NS::UInteger MTL::VertexAttributeDescriptor::bufferIndex() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(bufferIndex)); } _MTL_INLINE void MTL::VertexAttributeDescriptor::setBufferIndex(NS::UInteger bufferIndex) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setBufferIndex_), bufferIndex); } _MTL_INLINE MTL::VertexAttributeDescriptorArray* MTL::VertexAttributeDescriptorArray::alloc() { return NS::Object::alloc<MTL::VertexAttributeDescriptorArray>(_MTL_PRIVATE_CLS(MTLVertexAttributeDescriptorArray)); } _MTL_INLINE MTL::VertexAttributeDescriptorArray* MTL::VertexAttributeDescriptorArray::init() { return NS::Object::init<MTL::VertexAttributeDescriptorArray>(); } _MTL_INLINE MTL::VertexAttributeDescriptor* MTL::VertexAttributeDescriptorArray::object(NS::UInteger index) { return Object::sendMessage<MTL::VertexAttributeDescriptor*>(this, _MTL_PRIVATE_SEL(objectAtIndexedSubscript_), index); } _MTL_INLINE void MTL::VertexAttributeDescriptorArray::setObject(const MTL::VertexAttributeDescriptor* attributeDesc, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setObject_atIndexedSubscript_), attributeDesc, index); } _MTL_INLINE MTL::VertexDescriptor* MTL::VertexDescriptor::alloc() { return NS::Object::alloc<MTL::VertexDescriptor>(_MTL_PRIVATE_CLS(MTLVertexDescriptor)); } _MTL_INLINE MTL::VertexDescriptor* MTL::VertexDescriptor::init() { return NS::Object::init<MTL::VertexDescriptor>(); } _MTL_INLINE MTL::VertexDescriptor* MTL::VertexDescriptor::vertexDescriptor() { return Object::sendMessage<MTL::VertexDescriptor*>(_MTL_PRIVATE_CLS(MTLVertexDescriptor), _MTL_PRIVATE_SEL(vertexDescriptor)); } _MTL_INLINE MTL::VertexBufferLayoutDescriptorArray* MTL::VertexDescriptor::layouts() const { return Object::sendMessage<MTL::VertexBufferLayoutDescriptorArray*>(this, _MTL_PRIVATE_SEL(layouts)); } _MTL_INLINE MTL::VertexAttributeDescriptorArray* MTL::VertexDescriptor::attributes() const { return Object::sendMessage<MTL::VertexAttributeDescriptorArray*>(this, _MTL_PRIVATE_SEL(attributes)); } _MTL_INLINE void MTL::VertexDescriptor::reset() { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(reset)); } #pragma once namespace MTL { class VisibleFunctionTableDescriptor : public NS::Copying<VisibleFunctionTableDescriptor> { public: static class VisibleFunctionTableDescriptor* alloc(); class VisibleFunctionTableDescriptor* init(); static class VisibleFunctionTableDescriptor* visibleFunctionTableDescriptor(); NS::UInteger functionCount() const; void setFunctionCount(NS::UInteger functionCount); }; class VisibleFunctionTable : public NS::Referencing<VisibleFunctionTable, Resource> { public: MTL::ResourceID gpuResourceID() const; void setFunction(const class FunctionHandle* function, NS::UInteger index); void setFunctions(const class FunctionHandle* const functions[], NS::Range range); }; } _MTL_INLINE MTL::VisibleFunctionTableDescriptor* MTL::VisibleFunctionTableDescriptor::alloc() { return NS::Object::alloc<MTL::VisibleFunctionTableDescriptor>(_MTL_PRIVATE_CLS(MTLVisibleFunctionTableDescriptor)); } _MTL_INLINE MTL::VisibleFunctionTableDescriptor* MTL::VisibleFunctionTableDescriptor::init() { return NS::Object::init<MTL::VisibleFunctionTableDescriptor>(); } _MTL_INLINE MTL::VisibleFunctionTableDescriptor* MTL::VisibleFunctionTableDescriptor::visibleFunctionTableDescriptor() { return Object::sendMessage<MTL::VisibleFunctionTableDescriptor*>(_MTL_PRIVATE_CLS(MTLVisibleFunctionTableDescriptor), _MTL_PRIVATE_SEL(visibleFunctionTableDescriptor)); } _MTL_INLINE NS::UInteger MTL::VisibleFunctionTableDescriptor::functionCount() const { return Object::sendMessage<NS::UInteger>(this, _MTL_PRIVATE_SEL(functionCount)); } _MTL_INLINE void MTL::VisibleFunctionTableDescriptor::setFunctionCount(NS::UInteger functionCount) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunctionCount_), functionCount); } _MTL_INLINE MTL::ResourceID MTL::VisibleFunctionTable::gpuResourceID() const { return Object::sendMessage<MTL::ResourceID>(this, _MTL_PRIVATE_SEL(gpuResourceID)); } _MTL_INLINE void MTL::VisibleFunctionTable::setFunction(const MTL::FunctionHandle* function, NS::UInteger index) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunction_atIndex_), function, index); } _MTL_INLINE void MTL::VisibleFunctionTable::setFunctions(const MTL::FunctionHandle* const functions[], NS::Range range) { Object::sendMessage<void>(this, _MTL_PRIVATE_SEL(setFunctions_withRange_), functions, range); } #define METALCPP_VERSION_MAJOR 354 #define METALCPP_VERSION_MINOR 0 #define METALCPP_VERSION_PATCH 0 #define METALCPP_SUPPORTS_VERSION(major, minor, patch) \ ((major < METALCPP_VERSION_MAJOR) || \ (major == METALCPP_VERSION_MAJOR && minor < METALCPP_VERSION_MINOR) || \ (major == METALCPP_VERSION_MAJOR && minor == METALCPP_VERSION_MINOR && patch <= METALCPP_VERSION_PATCH)) #define _MTLFX_EXPORT _NS_EXPORT #define _MTLFX_EXTERN _NS_EXTERN #define _MTLFX_INLINE _NS_INLINE #define _MTLFX_PACKED _NS_PACKED #define _MTLFX_CONST( type, name ) _NS_CONST( type, name ) #define _MTLFX_ENUM( type, name ) _NS_ENUM( type, name ) #define _MTLFX_OPTIONS( type, name ) _NS_OPTIONS( type, name ) #define _MTLFX_VALIDATE_SIZE( mtlfx, name ) _NS_VALIDATE_SIZE( mtlfx, name ) #define _MTLFX_VALIDATE_ENUM( mtlfx, name ) _NS_VALIDATE_ENUM( mtlfx, name ) #include <objc/runtime.h> #define _MTLFX_PRIVATE_CLS( symbol ) ( Private::Class::s_k##symbol ) #define _MTLFX_PRIVATE_SEL( accessor ) ( Private::Selector::s_k##accessor ) #if defined( MTLFX_PRIVATE_IMPLEMENTATION ) #if defined( METALCPP_SYMBOL_VISIBILITY_HIDDEN ) #define _MTLFX_PRIVATE_VISIBILITY __attribute__( ( visibility("hidden" ) ) ) #else #define _MTLFX_PRIVATE_VISIBILITY __attribute__( ( visibility("default" ) ) ) #endif // METALCPP_SYMBOL_VISIBILITY_HIDDEN #define _MTLFX_PRIVATE_IMPORT __attribute__( ( weak_import ) ) #ifdef __OBJC__ #define _MTLFX_PRIVATE_OBJC_LOOKUP_CLASS( symbol ) ( ( __bridge void* ) objc_lookUpClass( #symbol ) ) #define _MTLFX_PRIVATE_OBJC_GET_PROTOCOL( symbol ) ( ( __bridge void* ) objc_getProtocol( #symbol ) ) #else #define _MTLFX_PRIVATE_OBJC_LOOKUP_CLASS( symbol ) objc_lookUpClass(#symbol) #define _MTLFX_PRIVATE_OBJC_GET_PROTOCOL( symbol ) objc_getProtocol(#symbol) #endif // __OBJC__ #define _MTLFX_PRIVATE_DEF_CLS( symbol ) void* s_k##symbol _MTLFX_PRIVATE_VISIBILITY = _MTLFX_PRIVATE_OBJC_LOOKUP_CLASS( symbol ) #define _MTLFX_PRIVATE_DEF_PRO( symbol ) void* s_k##symbol _MTLFX_PRIVATE_VISIBILITY = _MTLFX_PRIVATE_OBJC_GET_PROTOCOL( symbol ) #define _MTLFX_PRIVATE_DEF_SEL( accessor, symbol ) SEL s_k##accessor _MTLFX_PRIVATE_VISIBILITY = sel_registerName( symbol ) #include <dlfcn.h> #define MTLFX_DEF_FUNC( name, signature ) using Fn##name = signature; \ Fn##name name = reinterpret_cast< Fn##name >( dlsym( RTLD_DEFAULT, #name ) ) namespace MTLFX::Private { template <typename _Type> inline _Type const LoadSymbol(const char* pSymbol) { const _Type* pAddress = static_cast<_Type*>(dlsym(RTLD_DEFAULT, pSymbol)); return pAddress ? *pAddress : nullptr; } } // MTLFX::Private #if defined( __MAC_13_0 ) || defined( __MAC_14_0 ) || defined( __IPHONE_16_0 ) || defined( __IPHONE_17_0 ) || defined( __TVOS_16_0 ) || defined( __TVOS_17_0 ) #define _MTLFX_PRIVATE_DEF_STR( type, symbol ) \ _MTLFX_EXTERN type const MTLFX##symbol _MTLFX_PRIVATE_IMPORT; \ type const MTLFX::symbol = ( nullptr != &MTLFX##symbol ) ? MTLFX##ssymbol : nullptr #define _MTLFX_PRIVATE_DEF_CONST( type, symbol ) \ _MTLFX_EXTERN type const MTLFX##ssymbol _MTLFX_PRIVATE_IMPORT; \ type const MTLFX::symbol = (nullptr != &MTLFX##ssymbol) ? MTLFX##ssymbol : nullptr #define _MTLFX_PRIVATE_DEF_WEAK_CONST( type, symbol ) \ _MTLFX_EXTERN type const MTLFX##ssymbol; \ type const MTLFX::symbol = Private::LoadSymbol< type >( "MTLFX" #symbol ) #else #define _MTLFX_PRIVATE_DEF_STR( type, symbol ) \ _MTLFX_EXTERN type const MTLFX##ssymbol; \ type const MTLFX::symbol = Private::LoadSymbol< type >( "MTLFX" #symbol ) #define _MTLFX_PRIVATE_DEF_CONST( type, symbol ) \ _MTLFX_EXTERN type const MTLFX##ssymbol; \ type const MTLFX::symbol = Private::LoadSymbol< type >( "MTLFX" #symbol ) #define _MTLFX_PRIVATE_DEF_WEAK_CONST( type, symbol ) _MTLFX_PRIVATE_DEF_CONST( type, symbol ) #endif // defined( __MAC_13_0 ) || defined( __MAC_14_0 ) || defined( __IPHONE_16_0 ) || defined( __IPHONE_17_0 ) || defined( __TVOS_16_0 ) || defined( __TVOS_17_0 ) #else #define _MTLFX_PRIVATE_DEF_CLS( symbol ) extern void* s_k##symbol #define _MTLFX_PRIVATE_DEF_PRO( symbol ) extern void* s_k##symbol #define _MTLFX_PRIVATE_DEF_SEL( accessor, symbol ) extern SEL s_k##accessor #define _MTLFX_PRIVATE_DEF_STR( type, symbol ) extern type const MTLFX::symbol #define _MTLFX_PRIVATE_DEF_CONST( type, symbol ) extern type const MTLFX::symbol #define _MTLFX_PRIVATE_DEF_WEAK_CONST( type, symbol ) extern type const MTLFX::symbol #endif // MTLFX_PRIVATE_IMPLEMENTATION namespace MTLFX { namespace Private { namespace Class { _MTLFX_PRIVATE_DEF_CLS( MTLFXSpatialScalerDescriptor ); _MTLFX_PRIVATE_DEF_CLS( MTLFXTemporalScalerDescriptor ); } // Class } // Private } // MTLFX namespace MTLFX { namespace Private { namespace Protocol { _MTLFX_PRIVATE_DEF_PRO( MTLFXSpatialScaler ); _MTLFX_PRIVATE_DEF_PRO( MTLFXTemporalScaler ); } // Protocol } // Private } // MTLFX namespace MTLFX { namespace Private { namespace Selector { _MTLFX_PRIVATE_DEF_SEL( colorProcessingMode, "colorProcessingMode" ); _MTLFX_PRIVATE_DEF_SEL( colorTexture, "colorTexture" ); _MTLFX_PRIVATE_DEF_SEL( colorTextureFormat, "colorTextureFormat" ); _MTLFX_PRIVATE_DEF_SEL( colorTextureUsage, "colorTextureUsage" ); _MTLFX_PRIVATE_DEF_SEL( depthTexture, "depthTexture" ); _MTLFX_PRIVATE_DEF_SEL( depthTextureFormat, "depthTextureFormat" ); _MTLFX_PRIVATE_DEF_SEL( depthTextureUsage, "depthTextureUsage" ); _MTLFX_PRIVATE_DEF_SEL( encodeToCommandBuffer_, "encodeToCommandBuffer:" ); _MTLFX_PRIVATE_DEF_SEL( exposureTexture, "exposureTexture" ); _MTLFX_PRIVATE_DEF_SEL( fence, "fence" ); _MTLFX_PRIVATE_DEF_SEL( inputContentHeight, "inputContentHeight" ); _MTLFX_PRIVATE_DEF_SEL( inputContentMaxScale, "inputContentMaxScale" ); _MTLFX_PRIVATE_DEF_SEL( inputContentMinScale, "inputContentMinScale" ); _MTLFX_PRIVATE_DEF_SEL( inputContentWidth, "inputContentWidth" ); _MTLFX_PRIVATE_DEF_SEL( inputHeight, "inputHeight" ); _MTLFX_PRIVATE_DEF_SEL( inputWidth, "inputWidth" ); _MTLFX_PRIVATE_DEF_SEL( isAutoExposureEnabled, "isAutoExposureEnabled" ); _MTLFX_PRIVATE_DEF_SEL( isDepthReversed, "isDepthReversed" ); _MTLFX_PRIVATE_DEF_SEL( isInputContentPropertiesEnabled, "isInputContentPropertiesEnabled" ); _MTLFX_PRIVATE_DEF_SEL( jitterOffsetX, "jitterOffsetX" ); _MTLFX_PRIVATE_DEF_SEL( jitterOffsetY, "jitterOffsetY" ); _MTLFX_PRIVATE_DEF_SEL( motionTexture, "motionTexture" ); _MTLFX_PRIVATE_DEF_SEL( motionTextureFormat, "motionTextureFormat" ); _MTLFX_PRIVATE_DEF_SEL( motionTextureUsage, "motionTextureUsage" ); _MTLFX_PRIVATE_DEF_SEL( motionVectorScaleX, "motionVectorScaleX" ); _MTLFX_PRIVATE_DEF_SEL( motionVectorScaleY, "motionVectorScaleY" ); _MTLFX_PRIVATE_DEF_SEL( newSpatialScalerWithDevice_, "newSpatialScalerWithDevice:" ); _MTLFX_PRIVATE_DEF_SEL( newTemporalScalerWithDevice_, "newTemporalScalerWithDevice:" ); _MTLFX_PRIVATE_DEF_SEL( outputHeight, "outputHeight" ); _MTLFX_PRIVATE_DEF_SEL( outputTexture, "outputTexture" ); _MTLFX_PRIVATE_DEF_SEL( outputTextureFormat, "outputTextureFormat" ); _MTLFX_PRIVATE_DEF_SEL( outputTextureUsage, "outputTextureUsage" ); _MTLFX_PRIVATE_DEF_SEL( outputWidth, "outputWidth" ); _MTLFX_PRIVATE_DEF_SEL( preExposure, "preExposure" ); _MTLFX_PRIVATE_DEF_SEL( reset, "reset" ); _MTLFX_PRIVATE_DEF_SEL( setAutoExposureEnabled_, "setAutoExposureEnabled:" ); _MTLFX_PRIVATE_DEF_SEL( setColorProcessingMode_, "setColorProcessingMode:" ); _MTLFX_PRIVATE_DEF_SEL( setColorTexture_, "setColorTexture:" ); _MTLFX_PRIVATE_DEF_SEL( setColorTextureFormat_, "setColorTextureFormat:" ); _MTLFX_PRIVATE_DEF_SEL( setDepthReversed_, "setDepthReversed:" ); _MTLFX_PRIVATE_DEF_SEL( setDepthTexture_, "setDepthTexture:" ); _MTLFX_PRIVATE_DEF_SEL( setDepthTextureFormat_, "setDepthTextureFormat:" ); _MTLFX_PRIVATE_DEF_SEL( setExposureTexture_, "setExposureTexture:" ); _MTLFX_PRIVATE_DEF_SEL( setFence_, "setFence:" ); _MTLFX_PRIVATE_DEF_SEL( setInputContentHeight_, "setInputContentHeight:" ); _MTLFX_PRIVATE_DEF_SEL( setInputContentMaxScale_, "setInputContentMaxScale:" ); _MTLFX_PRIVATE_DEF_SEL( setInputContentMinScale_, "setInputContentMinScale:" ); _MTLFX_PRIVATE_DEF_SEL( setInputContentPropertiesEnabled_, "setInputContentPropertiesEnabled:" ); _MTLFX_PRIVATE_DEF_SEL( setInputContentWidth_, "setInputContentWidth:" ); _MTLFX_PRIVATE_DEF_SEL( setInputHeight_, "setInputHeight:" ); _MTLFX_PRIVATE_DEF_SEL( setInputWidth_, "setInputWidth:" ); _MTLFX_PRIVATE_DEF_SEL( setJitterOffsetX_, "setJitterOffsetX:" ); _MTLFX_PRIVATE_DEF_SEL( setJitterOffsetY_, "setJitterOffsetY:" ); _MTLFX_PRIVATE_DEF_SEL( setMotionTexture_, "setMotionTexture:" ); _MTLFX_PRIVATE_DEF_SEL( setMotionTextureFormat_, "setMotionTextureFormat:" ); _MTLFX_PRIVATE_DEF_SEL( setMotionVectorScaleX_, "setMotionVectorScaleX:" ); _MTLFX_PRIVATE_DEF_SEL( setMotionVectorScaleY_, "setMotionVectorScaleY:" ); _MTLFX_PRIVATE_DEF_SEL( setOutputHeight_, "setOutputHeight:" ); _MTLFX_PRIVATE_DEF_SEL( setOutputTexture_, "setOutputTexture:" ); _MTLFX_PRIVATE_DEF_SEL( setOutputTextureFormat_, "setOutputTextureFormat:" ); _MTLFX_PRIVATE_DEF_SEL( setOutputWidth_, "setOutputWidth:" ); _MTLFX_PRIVATE_DEF_SEL( setPreExposure_, "setPreExposure:" ); _MTLFX_PRIVATE_DEF_SEL( setReset_, "setReset:" ); _MTLFX_PRIVATE_DEF_SEL( supportedInputContentMaxScaleForDevice_, "supportedInputContentMaxScaleForDevice:" ); _MTLFX_PRIVATE_DEF_SEL( supportedInputContentMinScaleForDevice_, "supportedInputContentMinScaleForDevice:" ); _MTLFX_PRIVATE_DEF_SEL( supportsDevice_, "supportsDevice:" ); } // Selector } // Private } // MTLFX namespace MTLFX { _MTLFX_ENUM( NS::Integer, SpatialScalerColorProcessingMode ) { SpatialScalerColorProcessingModePerceptual = 0, SpatialScalerColorProcessingModeLinear = 1, SpatialScalerColorProcessingModeHDR = 2 }; class SpatialScalerDescriptor : public NS::Copying< SpatialScalerDescriptor > { public: static class SpatialScalerDescriptor* alloc(); class SpatialScalerDescriptor* init(); MTL::PixelFormat colorTextureFormat() const; void setColorTextureFormat( MTL::PixelFormat format ); MTL::PixelFormat outputTextureFormat() const; void setOutputTextureFormat( MTL::PixelFormat format ); NS::UInteger inputWidth() const; void setInputWidth( NS::UInteger width ); NS::UInteger inputHeight() const; void setInputHeight( NS::UInteger height ); NS::UInteger outputWidth() const; void setOutputWidth( NS::UInteger width ); NS::UInteger outputHeight() const; void setOutputHeight( NS::UInteger height ); SpatialScalerColorProcessingMode colorProcessingMode() const; void setColorProcessingMode( SpatialScalerColorProcessingMode mode ); class SpatialScaler* newSpatialScaler( const MTL::Device* pDevice ); static bool supportsDevice( const MTL::Device* ); }; class SpatialScaler : public NS::Referencing< SpatialScaler > { public: MTL::TextureUsage colorTextureUsage() const; MTL::TextureUsage outputTextureUsage() const; NS::UInteger inputContentWidth() const; void setInputContentWidth( NS::UInteger width ); NS::UInteger inputContentHeight() const; void setInputContentHeight( NS::UInteger height ); MTL::Texture* colorTexture() const; void setColorTexture( MTL::Texture* pTexture ); MTL::Texture* outputTexture() const; void setOutputTexture( MTL::Texture* pTexture ); MTL::PixelFormat colorTextureFormat() const; MTL::PixelFormat outputTextureFormat() const; NS::UInteger inputWidth() const; NS::UInteger inputHeight() const; NS::UInteger outputWidth() const; NS::UInteger outputHeight() const; SpatialScalerColorProcessingMode colorProcessingMode() const; MTL::Fence* fence() const; void setFence( MTL::Fence* pFence ); void encodeToCommandBuffer( MTL::CommandBuffer* pCommandBuffer ); }; } _MTLFX_INLINE MTLFX::SpatialScalerDescriptor* MTLFX::SpatialScalerDescriptor::alloc() { return NS::Object::alloc< SpatialScalerDescriptor >( _MTLFX_PRIVATE_CLS( MTLFXSpatialScalerDescriptor ) ); } _MTLFX_INLINE MTLFX::SpatialScalerDescriptor* MTLFX::SpatialScalerDescriptor::init() { return NS::Object::init< SpatialScalerDescriptor >(); } _MTLFX_INLINE MTL::PixelFormat MTLFX::SpatialScalerDescriptor::colorTextureFormat() const { return Object::sendMessage< MTL::PixelFormat >( this, _MTLFX_PRIVATE_SEL( colorTextureFormat ) ); } _MTLFX_INLINE void MTLFX::SpatialScalerDescriptor::setColorTextureFormat( MTL::PixelFormat format ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setColorTextureFormat_ ), format ); } _MTLFX_INLINE MTL::PixelFormat MTLFX::SpatialScalerDescriptor::outputTextureFormat() const { return Object::sendMessage< MTL::PixelFormat >( this, _MTLFX_PRIVATE_SEL( outputTextureFormat ) ); } _MTLFX_INLINE void MTLFX::SpatialScalerDescriptor::setOutputTextureFormat( MTL::PixelFormat format ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setOutputTextureFormat_ ), format ); } _MTLFX_INLINE NS::UInteger MTLFX::SpatialScalerDescriptor::inputWidth() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( inputWidth ) ); } _MTLFX_INLINE void MTLFX::SpatialScalerDescriptor::setInputWidth( NS::UInteger width ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setInputWidth_ ), width ); } _MTLFX_INLINE NS::UInteger MTLFX::SpatialScalerDescriptor::inputHeight() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( inputHeight ) ); } _MTLFX_INLINE void MTLFX::SpatialScalerDescriptor::setInputHeight( NS::UInteger height ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setInputHeight_ ), height ); } _MTLFX_INLINE NS::UInteger MTLFX::SpatialScalerDescriptor::outputWidth() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( outputWidth ) ); } _MTLFX_INLINE void MTLFX::SpatialScalerDescriptor::setOutputWidth( NS::UInteger width ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setOutputWidth_ ), width ); } _MTLFX_INLINE NS::UInteger MTLFX::SpatialScalerDescriptor::outputHeight() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( outputHeight ) ); } _MTLFX_INLINE void MTLFX::SpatialScalerDescriptor::setOutputHeight( NS::UInteger height ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setOutputHeight_ ), height ); } _MTLFX_INLINE MTLFX::SpatialScalerColorProcessingMode MTLFX::SpatialScalerDescriptor::colorProcessingMode() const { return Object::sendMessage< SpatialScalerColorProcessingMode >( this, _MTLFX_PRIVATE_SEL( colorProcessingMode ) ); } _MTLFX_INLINE void MTLFX::SpatialScalerDescriptor::setColorProcessingMode( SpatialScalerColorProcessingMode mode ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setColorProcessingMode_ ), mode ); } _MTLFX_INLINE MTLFX::SpatialScaler* MTLFX::SpatialScalerDescriptor::newSpatialScaler( const MTL::Device* pDevice ) { return Object::sendMessage< SpatialScaler* >( this, _MTLFX_PRIVATE_SEL( newSpatialScalerWithDevice_ ), pDevice ); } _MTLFX_INLINE bool MTLFX::SpatialScalerDescriptor::supportsDevice( const MTL::Device* pDevice ) { return Object::sendMessageSafe< bool >( _NS_PRIVATE_CLS( MTLFXSpatialScalerDescriptor ), _MTLFX_PRIVATE_SEL( supportsDevice_ ), pDevice ); } _MTLFX_INLINE MTL::TextureUsage MTLFX::SpatialScaler::colorTextureUsage() const { return Object::sendMessage< MTL::TextureUsage >( this, _MTLFX_PRIVATE_SEL( colorTextureUsage ) ); } _MTLFX_INLINE MTL::TextureUsage MTLFX::SpatialScaler::outputTextureUsage() const { return Object::sendMessage< MTL::TextureUsage >( this, _MTLFX_PRIVATE_SEL( outputTextureUsage ) ); } _MTLFX_INLINE NS::UInteger MTLFX::SpatialScaler::inputContentWidth() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( inputContentWidth ) ); } _MTLFX_INLINE void MTLFX::SpatialScaler::setInputContentWidth( NS::UInteger width ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setInputContentWidth_ ), width ); } _MTLFX_INLINE NS::UInteger MTLFX::SpatialScaler::inputContentHeight() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( inputContentHeight ) ); } _MTLFX_INLINE void MTLFX::SpatialScaler::setInputContentHeight( NS::UInteger height ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setInputContentHeight_ ), height ); } _MTLFX_INLINE MTL::Texture* MTLFX::SpatialScaler::colorTexture() const { return Object::sendMessage< MTL::Texture* >( this, _MTLFX_PRIVATE_SEL( colorTexture ) ); } _MTLFX_INLINE void MTLFX::SpatialScaler::setColorTexture( MTL::Texture* pTexture ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setColorTexture_ ), pTexture ); } _MTLFX_INLINE MTL::Texture* MTLFX::SpatialScaler::outputTexture() const { return Object::sendMessage< MTL::Texture* >( this, _MTLFX_PRIVATE_SEL( outputTexture ) ); } _MTLFX_INLINE void MTLFX::SpatialScaler::setOutputTexture( MTL::Texture* pTexture ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setOutputTexture_ ), pTexture ); } _MTLFX_INLINE MTL::PixelFormat MTLFX::SpatialScaler::colorTextureFormat() const { return Object::sendMessage< MTL::PixelFormat >( this, _MTLFX_PRIVATE_SEL( colorTextureFormat ) ); } _MTLFX_INLINE MTL::PixelFormat MTLFX::SpatialScaler::outputTextureFormat() const { return Object::sendMessage< MTL::PixelFormat >( this, _MTLFX_PRIVATE_SEL( outputTextureFormat ) ); } _MTLFX_INLINE NS::UInteger MTLFX::SpatialScaler::inputWidth() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( inputWidth ) ); } _MTLFX_INLINE NS::UInteger MTLFX::SpatialScaler::inputHeight() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( inputHeight ) ); } _MTLFX_INLINE NS::UInteger MTLFX::SpatialScaler::outputWidth() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( outputWidth ) ); } _MTLFX_INLINE NS::UInteger MTLFX::SpatialScaler::outputHeight() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( outputHeight ) ); } _MTLFX_INLINE MTLFX::SpatialScalerColorProcessingMode MTLFX::SpatialScaler::colorProcessingMode() const { return Object::sendMessage< SpatialScalerColorProcessingMode >( this, _MTLFX_PRIVATE_SEL( colorProcessingMode ) ); } _MTLFX_INLINE MTL::Fence* MTLFX::SpatialScaler::fence() const { return Object::sendMessage< MTL::Fence* >( this, _MTLFX_PRIVATE_SEL( fence ) ); } _MTLFX_INLINE void MTLFX::SpatialScaler::setFence( MTL::Fence* pFence ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setFence_ ), pFence ); } _MTLFX_INLINE void MTLFX::SpatialScaler::encodeToCommandBuffer( MTL::CommandBuffer* pCommandBuffer ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( encodeToCommandBuffer_ ), pCommandBuffer ); } namespace MTLFX { class TemporalScalerDescriptor : public NS::Copying< TemporalScalerDescriptor > { public: static class TemporalScalerDescriptor* alloc(); class TemporalScalerDescriptor* init(); MTL::PixelFormat colorTextureFormat() const; void setColorTextureFormat( MTL::PixelFormat format ); MTL::PixelFormat depthTextureFormat() const; void setDepthTextureFormat( MTL::PixelFormat format ); MTL::PixelFormat motionTextureFormat() const; void setMotionTextureFormat( MTL::PixelFormat format ); MTL::PixelFormat outputTextureFormat() const; void setOutputTextureFormat( MTL::PixelFormat format ); NS::UInteger inputWidth() const; void setInputWidth( NS::UInteger width ); NS::UInteger inputHeight() const; void setInputHeight( NS::UInteger height ); NS::UInteger outputWidth() const; void setOutputWidth( NS::UInteger width ); NS::UInteger outputHeight() const; void setOutputHeight( NS::UInteger height ); bool isAutoExposureEnabled() const; void setAutoExposureEnabled( bool enabled ); bool isInputContentPropertiesEnabled() const; void setInputContentPropertiesEnabled( bool enabled ); float inputContentMinScale() const; void setInputContentMinScale( float scale ); float inputContentMaxScale() const; void setInputContentMaxScale( float scale ); class TemporalScaler* newTemporalScaler( const MTL::Device* pDevice ) const; static float supportedInputContentMinScale( const MTL::Device* pDevice ); static float supportedInputContentMaxScale( const MTL::Device* pDevice ); static bool supportsDevice( const MTL::Device* pDevice ); }; class TemporalScaler : public NS::Referencing< TemporalScaler > { public: MTL::TextureUsage colorTextureUsage() const; MTL::TextureUsage depthTextureUsage() const; MTL::TextureUsage motionTextureUsage() const; MTL::TextureUsage outputTextureUsage() const; NS::UInteger inputContentWidth() const; void setInputContentWidth( NS::UInteger width ); NS::UInteger inputContentHeight() const; void setInputContentHeight( NS::UInteger height ); MTL::Texture* colorTexture() const; void setColorTexture( MTL::Texture* pTexture ); MTL::Texture* depthTexture() const; void setDepthTexture( MTL::Texture* pTexture ); MTL::Texture* motionTexture() const; void setMotionTexture( MTL::Texture* pTexture ); MTL::Texture* outputTexture() const; void setOutputTexture( MTL::Texture* pTexture ); MTL::Texture* exposureTexture() const; void setExposureTexture( MTL::Texture* pTexture ); float preExposure() const; void setPreExposure( float preExposure ); float jitterOffsetX() const; void setJitterOffsetX( float offset ); float jitterOffsetY() const; void setJitterOffsetY( float offset ); float motionVectorScaleX() const; void setMotionVectorScaleX( float scale ); float motionVectorScaleY() const; void setMotionVectorScaleY( float scale ); bool reset() const; void setReset( bool reset ); bool isDepthReversed() const; void setDepthReversed( bool depthReversed ); MTL::PixelFormat colorTextureFormat() const; MTL::PixelFormat depthTextureFormat() const; MTL::PixelFormat motionTextureFormat() const; MTL::PixelFormat outputTextureFormat() const; NS::UInteger inputWidth() const; NS::UInteger inputHeight() const; NS::UInteger outputWidth() const; NS::UInteger outputHeight() const; float inputContentMinScale() const; float inputContentMaxScale() const; MTL::Fence* fence() const; void setFence( MTL::Fence* pFence ); void encodeToCommandBuffer( MTL::CommandBuffer* pCommandBuffer ); }; } _MTLFX_INLINE MTLFX::TemporalScalerDescriptor* MTLFX::TemporalScalerDescriptor::alloc() { return NS::Object::alloc< TemporalScalerDescriptor >( _MTLFX_PRIVATE_CLS( MTLFXTemporalScalerDescriptor ) ); } _MTLFX_INLINE MTLFX::TemporalScalerDescriptor* MTLFX::TemporalScalerDescriptor::init() { return NS::Object::init< TemporalScalerDescriptor >(); } _MTLFX_INLINE MTL::PixelFormat MTLFX::TemporalScalerDescriptor::colorTextureFormat() const { return Object::sendMessage< MTL::PixelFormat >( this, _MTLFX_PRIVATE_SEL( colorTextureFormat ) ); } _MTLFX_INLINE void MTLFX::TemporalScalerDescriptor::setColorTextureFormat( MTL::PixelFormat format ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setColorTextureFormat_ ), format ); } _MTLFX_INLINE MTL::PixelFormat MTLFX::TemporalScalerDescriptor::depthTextureFormat() const { return Object::sendMessage< MTL::PixelFormat >( this, _MTLFX_PRIVATE_SEL( depthTextureFormat ) ); } _MTLFX_INLINE void MTLFX::TemporalScalerDescriptor::setDepthTextureFormat( MTL::PixelFormat format ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setDepthTextureFormat_ ), format ); } _MTLFX_INLINE MTL::PixelFormat MTLFX::TemporalScalerDescriptor::motionTextureFormat() const { return Object::sendMessage< MTL::PixelFormat >( this, _MTLFX_PRIVATE_SEL( motionTextureFormat ) ); } _MTLFX_INLINE void MTLFX::TemporalScalerDescriptor::setMotionTextureFormat( MTL::PixelFormat format ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setMotionTextureFormat_ ), format ); } _MTLFX_INLINE MTL::PixelFormat MTLFX::TemporalScalerDescriptor::outputTextureFormat() const { return Object::sendMessage< MTL::PixelFormat >( this, _MTLFX_PRIVATE_SEL( outputTextureFormat ) ); } _MTLFX_INLINE void MTLFX::TemporalScalerDescriptor::setOutputTextureFormat( MTL::PixelFormat format ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setOutputTextureFormat_ ), format ); } _MTLFX_INLINE NS::UInteger MTLFX::TemporalScalerDescriptor::inputWidth() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( inputWidth ) ); } _MTLFX_INLINE void MTLFX::TemporalScalerDescriptor::setInputWidth( NS::UInteger width ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setInputWidth_ ), width ); } _MTLFX_INLINE NS::UInteger MTLFX::TemporalScalerDescriptor::inputHeight() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( inputHeight ) ); } _MTLFX_INLINE void MTLFX::TemporalScalerDescriptor::setInputHeight( NS::UInteger height ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setInputHeight_ ), height ); } _MTLFX_INLINE NS::UInteger MTLFX::TemporalScalerDescriptor::outputWidth() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( outputWidth ) ); } _MTLFX_INLINE void MTLFX::TemporalScalerDescriptor::setOutputWidth( NS::UInteger width ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setOutputWidth_ ), width ); } _MTLFX_INLINE NS::UInteger MTLFX::TemporalScalerDescriptor::outputHeight() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( outputHeight ) ); } _MTLFX_INLINE void MTLFX::TemporalScalerDescriptor::setOutputHeight( NS::UInteger height ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setOutputHeight_ ), height ); } _MTLFX_INLINE bool MTLFX::TemporalScalerDescriptor::isAutoExposureEnabled() const { return Object::sendMessage< bool >( this, _MTLFX_PRIVATE_SEL( isAutoExposureEnabled ) ); } _MTLFX_INLINE void MTLFX::TemporalScalerDescriptor::setAutoExposureEnabled( bool enabled ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setAutoExposureEnabled_ ), enabled ); } _MTLFX_INLINE bool MTLFX::TemporalScalerDescriptor::isInputContentPropertiesEnabled() const { return Object::sendMessage< bool >( this, _MTLFX_PRIVATE_SEL( isInputContentPropertiesEnabled ) ); } _MTLFX_INLINE void MTLFX::TemporalScalerDescriptor::setInputContentPropertiesEnabled( bool enabled ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setInputContentPropertiesEnabled_ ), enabled ); } _MTLFX_INLINE float MTLFX::TemporalScalerDescriptor::inputContentMinScale() const { return Object::sendMessage< float >( this, _MTLFX_PRIVATE_SEL( inputContentMinScale ) ); } _MTLFX_INLINE void MTLFX::TemporalScalerDescriptor::setInputContentMinScale( float scale ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setInputContentMinScale_ ), scale ); } _MTLFX_INLINE float MTLFX::TemporalScalerDescriptor::inputContentMaxScale() const { return Object::sendMessage< float >( this, _MTLFX_PRIVATE_SEL( inputContentMaxScale ) ); } _MTLFX_INLINE void MTLFX::TemporalScalerDescriptor::setInputContentMaxScale( float scale ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setInputContentMaxScale_ ), scale ); } _MTLFX_INLINE MTLFX::TemporalScaler* MTLFX::TemporalScalerDescriptor::newTemporalScaler( const MTL::Device* pDevice ) const { return Object::sendMessage< TemporalScaler* >( this, _MTLFX_PRIVATE_SEL( newTemporalScalerWithDevice_ ), pDevice ); } _MTLFX_INLINE float MTLFX::TemporalScalerDescriptor::supportedInputContentMinScale( const MTL::Device* pDevice ) { float scale = 1.0f; if ( nullptr != methodSignatureForSelector( _NS_PRIVATE_CLS( MTLFXTemporalScalerDescriptor ), _MTLFX_PRIVATE_SEL( supportedInputContentMinScaleForDevice_ ) ) ) { scale = sendMessage< float >( _NS_PRIVATE_CLS( MTLFXTemporalScalerDescriptor ), _MTLFX_PRIVATE_SEL( supportedInputContentMinScaleForDevice_ ), pDevice ); } return scale; } _MTLFX_INLINE float MTLFX::TemporalScalerDescriptor::supportedInputContentMaxScale( const MTL::Device* pDevice ) { float scale = 1.0f; if ( nullptr != methodSignatureForSelector( _NS_PRIVATE_CLS( MTLFXTemporalScalerDescriptor ), _MTLFX_PRIVATE_SEL( supportedInputContentMaxScaleForDevice_ ) ) ) { scale = sendMessage< float >( _NS_PRIVATE_CLS( MTLFXTemporalScalerDescriptor ), _MTLFX_PRIVATE_SEL( supportedInputContentMaxScaleForDevice_ ), pDevice ); } else if ( supportsDevice( pDevice ) ) { scale = 2.0f; } return scale; } _MTLFX_INLINE bool MTLFX::TemporalScalerDescriptor::supportsDevice( const MTL::Device* pDevice ) { return Object::sendMessageSafe< bool >( _NS_PRIVATE_CLS( MTLFXTemporalScalerDescriptor ), _MTLFX_PRIVATE_SEL( supportsDevice_ ), pDevice ); } _MTLFX_INLINE MTL::TextureUsage MTLFX::TemporalScaler::colorTextureUsage() const { return Object::sendMessage< MTL::TextureUsage >( this, _MTLFX_PRIVATE_SEL( colorTextureUsage ) ); } _MTLFX_INLINE MTL::TextureUsage MTLFX::TemporalScaler::depthTextureUsage() const { return Object::sendMessage< MTL::TextureUsage >( this, _MTLFX_PRIVATE_SEL( depthTextureUsage ) ); } _MTLFX_INLINE MTL::TextureUsage MTLFX::TemporalScaler::motionTextureUsage() const { return Object::sendMessage< MTL::TextureUsage >( this, _MTLFX_PRIVATE_SEL( motionTextureUsage ) ); } _MTLFX_INLINE MTL::TextureUsage MTLFX::TemporalScaler::outputTextureUsage() const { return Object::sendMessage< MTL::TextureUsage >( this, _MTLFX_PRIVATE_SEL( outputTextureUsage ) ); } _MTLFX_INLINE NS::UInteger MTLFX::TemporalScaler::inputContentWidth() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( inputContentWidth ) ); } _MTLFX_INLINE void MTLFX::TemporalScaler::setInputContentWidth( NS::UInteger width ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setInputContentWidth_ ), width ); } _MTLFX_INLINE NS::UInteger MTLFX::TemporalScaler::inputContentHeight() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( inputContentHeight ) ); } _MTLFX_INLINE void MTLFX::TemporalScaler::setInputContentHeight( NS::UInteger height ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setInputContentHeight_ ), height ); } _MTLFX_INLINE MTL::Texture* MTLFX::TemporalScaler::colorTexture() const { return Object::sendMessage< MTL::Texture* >( this, _MTLFX_PRIVATE_SEL( colorTexture ) ); } _MTLFX_INLINE void MTLFX::TemporalScaler::setColorTexture( MTL::Texture* pTexture ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setColorTexture_ ), pTexture ); } _MTLFX_INLINE MTL::Texture* MTLFX::TemporalScaler::depthTexture() const { return Object::sendMessage< MTL::Texture* >( this, _MTLFX_PRIVATE_SEL( depthTexture ) ); } _MTLFX_INLINE void MTLFX::TemporalScaler::setDepthTexture( MTL::Texture* pTexture ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setDepthTexture_ ), pTexture ); } _MTLFX_INLINE MTL::Texture* MTLFX::TemporalScaler::motionTexture() const { return Object::sendMessage< MTL::Texture* >( this, _MTLFX_PRIVATE_SEL( motionTexture ) ); } _MTLFX_INLINE void MTLFX::TemporalScaler::setMotionTexture( MTL::Texture* pTexture ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setMotionTexture_ ), pTexture ); } _MTLFX_INLINE MTL::Texture* MTLFX::TemporalScaler::outputTexture() const { return Object::sendMessage< MTL::Texture* >( this, _MTLFX_PRIVATE_SEL( outputTexture ) ); } _MTLFX_INLINE void MTLFX::TemporalScaler::setOutputTexture( MTL::Texture* pTexture ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setOutputTexture_ ), pTexture ); } _MTLFX_INLINE MTL::Texture* MTLFX::TemporalScaler::exposureTexture() const { return Object::sendMessage< MTL::Texture* >( this, _MTLFX_PRIVATE_SEL( exposureTexture ) ); } _MTLFX_INLINE void MTLFX::TemporalScaler::setExposureTexture( MTL::Texture* pTexture ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setExposureTexture_ ), pTexture ); } _MTLFX_INLINE float MTLFX::TemporalScaler::preExposure() const { return Object::sendMessage< float >( this, _MTLFX_PRIVATE_SEL( preExposure ) ); } _MTLFX_INLINE void MTLFX::TemporalScaler::setPreExposure( float preExposure ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setPreExposure_ ), preExposure ); } _MTLFX_INLINE float MTLFX::TemporalScaler::jitterOffsetX() const { return Object::sendMessage< float >( this, _MTLFX_PRIVATE_SEL( jitterOffsetX ) ); } _MTLFX_INLINE void MTLFX::TemporalScaler::setJitterOffsetX( float offset ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setJitterOffsetX_ ), offset ); } _MTLFX_INLINE float MTLFX::TemporalScaler::jitterOffsetY() const { return Object::sendMessage< float >( this, _MTLFX_PRIVATE_SEL( jitterOffsetY ) ); } _MTLFX_INLINE void MTLFX::TemporalScaler::setJitterOffsetY( float offset ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setJitterOffsetY_ ), offset ); } _MTLFX_INLINE float MTLFX::TemporalScaler::motionVectorScaleX() const { return Object::sendMessage< float >( this, _MTLFX_PRIVATE_SEL( motionVectorScaleX ) ); } _MTLFX_INLINE void MTLFX::TemporalScaler::setMotionVectorScaleX( float scale ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setMotionVectorScaleX_ ), scale ); } _MTLFX_INLINE float MTLFX::TemporalScaler::motionVectorScaleY() const { return Object::sendMessage< float >( this, _MTLFX_PRIVATE_SEL( motionVectorScaleY ) ); } _MTLFX_INLINE void MTLFX::TemporalScaler::setMotionVectorScaleY( float scale ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setMotionVectorScaleY_ ), scale ); } _MTLFX_INLINE bool MTLFX::TemporalScaler::reset() const { return Object::sendMessage< bool >( this, _MTLFX_PRIVATE_SEL( reset ) ); } _MTLFX_INLINE void MTLFX::TemporalScaler::setReset( bool reset ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setReset_ ), reset ); } _MTLFX_INLINE bool MTLFX::TemporalScaler::isDepthReversed() const { return Object::sendMessage< bool >( this, _MTLFX_PRIVATE_SEL( isDepthReversed ) ); } _MTLFX_INLINE void MTLFX::TemporalScaler::setDepthReversed( bool depthReversed ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setDepthReversed_ ), depthReversed ); } _MTLFX_INLINE MTL::PixelFormat MTLFX::TemporalScaler::colorTextureFormat() const { return Object::sendMessage< MTL::PixelFormat >( this, _MTLFX_PRIVATE_SEL( colorTextureFormat ) ); } _MTLFX_INLINE MTL::PixelFormat MTLFX::TemporalScaler::depthTextureFormat() const { return Object::sendMessage< MTL::PixelFormat >( this, _MTLFX_PRIVATE_SEL( depthTextureFormat ) ); } _MTLFX_INLINE MTL::PixelFormat MTLFX::TemporalScaler::motionTextureFormat() const { return Object::sendMessage< MTL::PixelFormat >( this, _MTLFX_PRIVATE_SEL( motionTextureFormat ) ); } _MTLFX_INLINE MTL::PixelFormat MTLFX::TemporalScaler::outputTextureFormat() const { return Object::sendMessage< MTL::PixelFormat >( this, _MTLFX_PRIVATE_SEL( outputTextureFormat ) ); } _MTLFX_INLINE NS::UInteger MTLFX::TemporalScaler::inputWidth() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( inputWidth ) ); } _MTLFX_INLINE NS::UInteger MTLFX::TemporalScaler::inputHeight() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( inputHeight ) ); } _MTLFX_INLINE NS::UInteger MTLFX::TemporalScaler::outputWidth() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( outputWidth ) ); } _MTLFX_INLINE NS::UInteger MTLFX::TemporalScaler::outputHeight() const { return Object::sendMessage< NS::UInteger >( this, _MTLFX_PRIVATE_SEL( outputHeight ) ); } _MTLFX_INLINE float MTLFX::TemporalScaler::inputContentMinScale() const { return Object::sendMessage< float >( this, _MTLFX_PRIVATE_SEL( inputContentMinScale ) ); } _MTLFX_INLINE float MTLFX::TemporalScaler::inputContentMaxScale() const { return Object::sendMessage< float >( this, _MTLFX_PRIVATE_SEL( inputContentMaxScale ) ); } _MTLFX_INLINE MTL::Fence* MTLFX::TemporalScaler::fence() const { return Object::sendMessage< MTL::Fence* >( this, _MTLFX_PRIVATE_SEL( fence ) ); } _MTLFX_INLINE void MTLFX::TemporalScaler::setFence( MTL::Fence* pFence ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( setFence_ ), pFence ); } _MTLFX_INLINE void MTLFX::TemporalScaler::encodeToCommandBuffer( MTL::CommandBuffer* pCommandBuffer ) { Object::sendMessage< void >( this, _MTL_PRIVATE_SEL( encodeToCommandBuffer_ ), pCommandBuffer ); }
yhirose/mtlcpp
16
Utilities for Metal-cpp
C++
yhirose
test/bench.cpp
C++
#define NS_PRIVATE_IMPLEMENTATION #define MTL_PRIVATE_IMPLEMENTATION #define ANKERL_NANOBENCH_IMPLEMENT #include <mtlcpp.h> #include <eigen3/Eigen/Core> #include "nanobench.h" using namespace ankerl::nanobench; void add() { const size_t n = 10'000'000; auto a = mtl::ones<float>({n}); auto b = mtl::ones<float>({n}); auto c = mtl::array<float>(); mtl::use_cpu(); Bench().run("CPU: a + b", [&] { c = a + b; }); mtl::use_gpu(); Bench().minEpochIterations(100).run("GPU: a + b", [&] { c = a + b; }); auto aa = Eigen::Vector<float, Eigen::Dynamic>::Ones(n); auto bb = Eigen::Vector<float, Eigen::Dynamic>::Ones(n); auto cc = Eigen::Vector<float, Eigen::Dynamic>(n); Bench().minEpochIterations(100).run("Eigen: a + b", [&] { cc = aa + bb; }); } void dot() { auto a = mtl::ones<float>({1000, 1000}); auto b = mtl::ones<float>({1000, 100}); auto c = mtl::array<float>(); mtl::use_cpu(); Bench().run("CPU: a.dot(b)", [&] { c = a.dot(b); }); mtl::use_gpu(); Bench().minEpochIterations(100).run("GPU: a.dot(b)", [&] { c = a.dot(b); }); auto aa = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>::Ones(1000, 1000); auto bb = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>::Ones(1000, 100); auto cc = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>(); Bench().minEpochIterations(100).run("Eigen: a * b", [&] { cc = aa * bb; }); } int main(void) { add(); dot(); }
yhirose/mtlcpp
16
Utilities for Metal-cpp
C++
yhirose
test/doctest.h
C/C++ Header
// ====================================================================== lgtm [cpp/missing-header-guard] // == DO NOT MODIFY THIS FILE BY HAND - IT IS AUTO GENERATED BY CMAKE! == // ====================================================================== // // doctest.h - the lightest feature-rich C++ single-header testing framework for unit tests and TDD // // Copyright (c) 2016-2023 Viktor Kirilov // // Distributed under the MIT Software License // See accompanying file LICENSE.txt or copy at // https://opensource.org/licenses/MIT // // The documentation can be found at the library's page: // https://github.com/doctest/doctest/blob/master/doc/markdown/readme.md // // ================================================================================================= // ================================================================================================= // ================================================================================================= // // The library is heavily influenced by Catch - https://github.com/catchorg/Catch2 // which uses the Boost Software License - Version 1.0 // see here - https://github.com/catchorg/Catch2/blob/master/LICENSE.txt // // The concept of subcases (sections in Catch) and expression decomposition are from there. // Some parts of the code are taken directly: // - stringification - the detection of "ostream& operator<<(ostream&, const T&)" and StringMaker<> // - the Approx() helper class for floating point comparison // - colors in the console // - breaking into a debugger // - signal / SEH handling // - timer // - XmlWriter class - thanks to Phil Nash for allowing the direct reuse (AKA copy/paste) // // The expression decomposing templates are taken from lest - https://github.com/martinmoene/lest // which uses the Boost Software License - Version 1.0 // see here - https://github.com/martinmoene/lest/blob/master/LICENSE.txt // // ================================================================================================= // ================================================================================================= // ================================================================================================= #ifndef DOCTEST_LIBRARY_INCLUDED #define DOCTEST_LIBRARY_INCLUDED // ================================================================================================= // == VERSION ====================================================================================== // ================================================================================================= #define DOCTEST_VERSION_MAJOR 2 #define DOCTEST_VERSION_MINOR 4 #define DOCTEST_VERSION_PATCH 11 // util we need here #define DOCTEST_TOSTR_IMPL(x) #x #define DOCTEST_TOSTR(x) DOCTEST_TOSTR_IMPL(x) #define DOCTEST_VERSION_STR \ DOCTEST_TOSTR(DOCTEST_VERSION_MAJOR) "." \ DOCTEST_TOSTR(DOCTEST_VERSION_MINOR) "." \ DOCTEST_TOSTR(DOCTEST_VERSION_PATCH) #define DOCTEST_VERSION \ (DOCTEST_VERSION_MAJOR * 10000 + DOCTEST_VERSION_MINOR * 100 + DOCTEST_VERSION_PATCH) // ================================================================================================= // == COMPILER VERSION ============================================================================= // ================================================================================================= // ideas for the version stuff are taken from here: https://github.com/cxxstuff/cxx_detect #ifdef _MSC_VER #define DOCTEST_CPLUSPLUS _MSVC_LANG #else #define DOCTEST_CPLUSPLUS __cplusplus #endif #define DOCTEST_COMPILER(MAJOR, MINOR, PATCH) ((MAJOR)*10000000 + (MINOR)*100000 + (PATCH)) // GCC/Clang and GCC/MSVC are mutually exclusive, but Clang/MSVC are not because of clang-cl... #if defined(_MSC_VER) && defined(_MSC_FULL_VER) #if _MSC_VER == _MSC_FULL_VER / 10000 #define DOCTEST_MSVC DOCTEST_COMPILER(_MSC_VER / 100, _MSC_VER % 100, _MSC_FULL_VER % 10000) #else // MSVC #define DOCTEST_MSVC \ DOCTEST_COMPILER(_MSC_VER / 100, (_MSC_FULL_VER / 100000) % 100, _MSC_FULL_VER % 100000) #endif // MSVC #endif // MSVC #if defined(__clang__) && defined(__clang_minor__) && defined(__clang_patchlevel__) #define DOCTEST_CLANG DOCTEST_COMPILER(__clang_major__, __clang_minor__, __clang_patchlevel__) #elif defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) && \ !defined(__INTEL_COMPILER) #define DOCTEST_GCC DOCTEST_COMPILER(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) #endif // GCC #if defined(__INTEL_COMPILER) #define DOCTEST_ICC DOCTEST_COMPILER(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) #endif // ICC #ifndef DOCTEST_MSVC #define DOCTEST_MSVC 0 #endif // DOCTEST_MSVC #ifndef DOCTEST_CLANG #define DOCTEST_CLANG 0 #endif // DOCTEST_CLANG #ifndef DOCTEST_GCC #define DOCTEST_GCC 0 #endif // DOCTEST_GCC #ifndef DOCTEST_ICC #define DOCTEST_ICC 0 #endif // DOCTEST_ICC // ================================================================================================= // == COMPILER WARNINGS HELPERS ==================================================================== // ================================================================================================= #if DOCTEST_CLANG && !DOCTEST_ICC #define DOCTEST_PRAGMA_TO_STR(x) _Pragma(#x) #define DOCTEST_CLANG_SUPPRESS_WARNING_PUSH _Pragma("clang diagnostic push") #define DOCTEST_CLANG_SUPPRESS_WARNING(w) DOCTEST_PRAGMA_TO_STR(clang diagnostic ignored w) #define DOCTEST_CLANG_SUPPRESS_WARNING_POP _Pragma("clang diagnostic pop") #define DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH(w) \ DOCTEST_CLANG_SUPPRESS_WARNING_PUSH DOCTEST_CLANG_SUPPRESS_WARNING(w) #else // DOCTEST_CLANG #define DOCTEST_CLANG_SUPPRESS_WARNING_PUSH #define DOCTEST_CLANG_SUPPRESS_WARNING(w) #define DOCTEST_CLANG_SUPPRESS_WARNING_POP #define DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH(w) #endif // DOCTEST_CLANG #if DOCTEST_GCC #define DOCTEST_PRAGMA_TO_STR(x) _Pragma(#x) #define DOCTEST_GCC_SUPPRESS_WARNING_PUSH _Pragma("GCC diagnostic push") #define DOCTEST_GCC_SUPPRESS_WARNING(w) DOCTEST_PRAGMA_TO_STR(GCC diagnostic ignored w) #define DOCTEST_GCC_SUPPRESS_WARNING_POP _Pragma("GCC diagnostic pop") #define DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(w) \ DOCTEST_GCC_SUPPRESS_WARNING_PUSH DOCTEST_GCC_SUPPRESS_WARNING(w) #else // DOCTEST_GCC #define DOCTEST_GCC_SUPPRESS_WARNING_PUSH #define DOCTEST_GCC_SUPPRESS_WARNING(w) #define DOCTEST_GCC_SUPPRESS_WARNING_POP #define DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(w) #endif // DOCTEST_GCC #if DOCTEST_MSVC #define DOCTEST_MSVC_SUPPRESS_WARNING_PUSH __pragma(warning(push)) #define DOCTEST_MSVC_SUPPRESS_WARNING(w) __pragma(warning(disable : w)) #define DOCTEST_MSVC_SUPPRESS_WARNING_POP __pragma(warning(pop)) #define DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(w) \ DOCTEST_MSVC_SUPPRESS_WARNING_PUSH DOCTEST_MSVC_SUPPRESS_WARNING(w) #else // DOCTEST_MSVC #define DOCTEST_MSVC_SUPPRESS_WARNING_PUSH #define DOCTEST_MSVC_SUPPRESS_WARNING(w) #define DOCTEST_MSVC_SUPPRESS_WARNING_POP #define DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(w) #endif // DOCTEST_MSVC // ================================================================================================= // == COMPILER WARNINGS ============================================================================ // ================================================================================================= // both the header and the implementation suppress all of these, // so it only makes sense to aggregate them like so #define DOCTEST_SUPPRESS_COMMON_WARNINGS_PUSH \ DOCTEST_CLANG_SUPPRESS_WARNING_PUSH \ DOCTEST_CLANG_SUPPRESS_WARNING("-Wunknown-pragmas") \ DOCTEST_CLANG_SUPPRESS_WARNING("-Wweak-vtables") \ DOCTEST_CLANG_SUPPRESS_WARNING("-Wpadded") \ DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-prototypes") \ DOCTEST_CLANG_SUPPRESS_WARNING("-Wc++98-compat") \ DOCTEST_CLANG_SUPPRESS_WARNING("-Wc++98-compat-pedantic") \ \ DOCTEST_GCC_SUPPRESS_WARNING_PUSH \ DOCTEST_GCC_SUPPRESS_WARNING("-Wunknown-pragmas") \ DOCTEST_GCC_SUPPRESS_WARNING("-Wpragmas") \ DOCTEST_GCC_SUPPRESS_WARNING("-Weffc++") \ DOCTEST_GCC_SUPPRESS_WARNING("-Wstrict-overflow") \ DOCTEST_GCC_SUPPRESS_WARNING("-Wstrict-aliasing") \ DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-declarations") \ DOCTEST_GCC_SUPPRESS_WARNING("-Wuseless-cast") \ DOCTEST_GCC_SUPPRESS_WARNING("-Wnoexcept") \ \ DOCTEST_MSVC_SUPPRESS_WARNING_PUSH \ /* these 4 also disabled globally via cmake: */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4514) /* unreferenced inline function has been removed */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4571) /* SEH related */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4710) /* function not inlined */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4711) /* function selected for inline expansion*/ \ /* common ones */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4616) /* invalid compiler warning */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4619) /* invalid compiler warning */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4996) /* The compiler encountered a deprecated declaration */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4706) /* assignment within conditional expression */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4512) /* 'class' : assignment operator could not be generated */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4127) /* conditional expression is constant */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4820) /* padding */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4625) /* copy constructor was implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4626) /* assignment operator was implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5027) /* move assignment operator implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5026) /* move constructor was implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4640) /* construction of local static object not thread-safe */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5045) /* Spectre mitigation for memory load */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5264) /* 'variable-name': 'const' variable is not used */ \ /* static analysis */ \ DOCTEST_MSVC_SUPPRESS_WARNING(26439) /* Function may not throw. Declare it 'noexcept' */ \ DOCTEST_MSVC_SUPPRESS_WARNING(26495) /* Always initialize a member variable */ \ DOCTEST_MSVC_SUPPRESS_WARNING(26451) /* Arithmetic overflow ... */ \ DOCTEST_MSVC_SUPPRESS_WARNING(26444) /* Avoid unnamed objects with custom ctor and dtor... */ \ DOCTEST_MSVC_SUPPRESS_WARNING(26812) /* Prefer 'enum class' over 'enum' */ #define DOCTEST_SUPPRESS_COMMON_WARNINGS_POP \ DOCTEST_CLANG_SUPPRESS_WARNING_POP \ DOCTEST_GCC_SUPPRESS_WARNING_POP \ DOCTEST_MSVC_SUPPRESS_WARNING_POP DOCTEST_SUPPRESS_COMMON_WARNINGS_PUSH DOCTEST_CLANG_SUPPRESS_WARNING_PUSH DOCTEST_CLANG_SUPPRESS_WARNING("-Wnon-virtual-dtor") DOCTEST_CLANG_SUPPRESS_WARNING("-Wdeprecated") DOCTEST_GCC_SUPPRESS_WARNING_PUSH DOCTEST_GCC_SUPPRESS_WARNING("-Wctor-dtor-privacy") DOCTEST_GCC_SUPPRESS_WARNING("-Wnon-virtual-dtor") DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-promo") DOCTEST_MSVC_SUPPRESS_WARNING_PUSH DOCTEST_MSVC_SUPPRESS_WARNING(4623) // default constructor was implicitly defined as deleted #define DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN \ DOCTEST_MSVC_SUPPRESS_WARNING_PUSH \ DOCTEST_MSVC_SUPPRESS_WARNING(4548) /* before comma no effect; expected side - effect */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4265) /* virtual functions, but destructor is not virtual */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4986) /* exception specification does not match previous */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4350) /* 'member1' called instead of 'member2' */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4668) /* not defined as a preprocessor macro */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4365) /* signed/unsigned mismatch */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4774) /* format string not a string literal */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4820) /* padding */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4625) /* copy constructor was implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4626) /* assignment operator was implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5027) /* move assignment operator implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5026) /* move constructor was implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4623) /* default constructor was implicitly deleted */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5039) /* pointer to pot. throwing function passed to extern C */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5045) /* Spectre mitigation for memory load */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5105) /* macro producing 'defined' has undefined behavior */ \ DOCTEST_MSVC_SUPPRESS_WARNING(4738) /* storing float result in memory, loss of performance */ \ DOCTEST_MSVC_SUPPRESS_WARNING(5262) /* implicit fall-through */ #define DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END DOCTEST_MSVC_SUPPRESS_WARNING_POP // ================================================================================================= // == FEATURE DETECTION ============================================================================ // ================================================================================================= // general compiler feature support table: https://en.cppreference.com/w/cpp/compiler_support // MSVC C++11 feature support table: https://msdn.microsoft.com/en-us/library/hh567368.aspx // GCC C++11 feature support table: https://gcc.gnu.org/projects/cxx-status.html // MSVC version table: // https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B#Internal_version_numbering // MSVC++ 14.3 (17) _MSC_VER == 1930 (Visual Studio 2022) // MSVC++ 14.2 (16) _MSC_VER == 1920 (Visual Studio 2019) // MSVC++ 14.1 (15) _MSC_VER == 1910 (Visual Studio 2017) // MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015) // MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013) // MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012) // MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010) // MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008) // MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005) // Universal Windows Platform support #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) #define DOCTEST_CONFIG_NO_WINDOWS_SEH #endif // WINAPI_FAMILY #if DOCTEST_MSVC && !defined(DOCTEST_CONFIG_WINDOWS_SEH) #define DOCTEST_CONFIG_WINDOWS_SEH #endif // MSVC #if defined(DOCTEST_CONFIG_NO_WINDOWS_SEH) && defined(DOCTEST_CONFIG_WINDOWS_SEH) #undef DOCTEST_CONFIG_WINDOWS_SEH #endif // DOCTEST_CONFIG_NO_WINDOWS_SEH #if !defined(_WIN32) && !defined(__QNX__) && !defined(DOCTEST_CONFIG_POSIX_SIGNALS) && \ !defined(__EMSCRIPTEN__) && !defined(__wasi__) #define DOCTEST_CONFIG_POSIX_SIGNALS #endif // _WIN32 #if defined(DOCTEST_CONFIG_NO_POSIX_SIGNALS) && defined(DOCTEST_CONFIG_POSIX_SIGNALS) #undef DOCTEST_CONFIG_POSIX_SIGNALS #endif // DOCTEST_CONFIG_NO_POSIX_SIGNALS #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS #if !defined(__cpp_exceptions) && !defined(__EXCEPTIONS) && !defined(_CPPUNWIND) \ || defined(__wasi__) #define DOCTEST_CONFIG_NO_EXCEPTIONS #endif // no exceptions #endif // DOCTEST_CONFIG_NO_EXCEPTIONS #ifdef DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS #define DOCTEST_CONFIG_NO_EXCEPTIONS #endif // DOCTEST_CONFIG_NO_EXCEPTIONS #endif // DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS #if defined(DOCTEST_CONFIG_NO_EXCEPTIONS) && !defined(DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS) #define DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS #endif // DOCTEST_CONFIG_NO_EXCEPTIONS && !DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS #ifdef __wasi__ #define DOCTEST_CONFIG_NO_MULTITHREADING #endif #if defined(DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN) && !defined(DOCTEST_CONFIG_IMPLEMENT) #define DOCTEST_CONFIG_IMPLEMENT #endif // DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #if defined(_WIN32) || defined(__CYGWIN__) #if DOCTEST_MSVC #define DOCTEST_SYMBOL_EXPORT __declspec(dllexport) #define DOCTEST_SYMBOL_IMPORT __declspec(dllimport) #else // MSVC #define DOCTEST_SYMBOL_EXPORT __attribute__((dllexport)) #define DOCTEST_SYMBOL_IMPORT __attribute__((dllimport)) #endif // MSVC #else // _WIN32 #define DOCTEST_SYMBOL_EXPORT __attribute__((visibility("default"))) #define DOCTEST_SYMBOL_IMPORT #endif // _WIN32 #ifdef DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL #ifdef DOCTEST_CONFIG_IMPLEMENT #define DOCTEST_INTERFACE DOCTEST_SYMBOL_EXPORT #else // DOCTEST_CONFIG_IMPLEMENT #define DOCTEST_INTERFACE DOCTEST_SYMBOL_IMPORT #endif // DOCTEST_CONFIG_IMPLEMENT #else // DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL #define DOCTEST_INTERFACE #endif // DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL // needed for extern template instantiations // see https://github.com/fmtlib/fmt/issues/2228 #if DOCTEST_MSVC #define DOCTEST_INTERFACE_DECL #define DOCTEST_INTERFACE_DEF DOCTEST_INTERFACE #else // DOCTEST_MSVC #define DOCTEST_INTERFACE_DECL DOCTEST_INTERFACE #define DOCTEST_INTERFACE_DEF #endif // DOCTEST_MSVC #define DOCTEST_EMPTY #if DOCTEST_MSVC #define DOCTEST_NOINLINE __declspec(noinline) #define DOCTEST_UNUSED #define DOCTEST_ALIGNMENT(x) #elif DOCTEST_CLANG && DOCTEST_CLANG < DOCTEST_COMPILER(3, 5, 0) #define DOCTEST_NOINLINE #define DOCTEST_UNUSED #define DOCTEST_ALIGNMENT(x) #else #define DOCTEST_NOINLINE __attribute__((noinline)) #define DOCTEST_UNUSED __attribute__((unused)) #define DOCTEST_ALIGNMENT(x) __attribute__((aligned(x))) #endif #ifdef DOCTEST_CONFIG_NO_CONTRADICTING_INLINE #define DOCTEST_INLINE_NOINLINE inline #else #define DOCTEST_INLINE_NOINLINE inline DOCTEST_NOINLINE #endif #ifndef DOCTEST_NORETURN #if DOCTEST_MSVC && (DOCTEST_MSVC < DOCTEST_COMPILER(19, 0, 0)) #define DOCTEST_NORETURN #else // DOCTEST_MSVC #define DOCTEST_NORETURN [[noreturn]] #endif // DOCTEST_MSVC #endif // DOCTEST_NORETURN #ifndef DOCTEST_NOEXCEPT #if DOCTEST_MSVC && (DOCTEST_MSVC < DOCTEST_COMPILER(19, 0, 0)) #define DOCTEST_NOEXCEPT #else // DOCTEST_MSVC #define DOCTEST_NOEXCEPT noexcept #endif // DOCTEST_MSVC #endif // DOCTEST_NOEXCEPT #ifndef DOCTEST_CONSTEXPR #if DOCTEST_MSVC && (DOCTEST_MSVC < DOCTEST_COMPILER(19, 0, 0)) #define DOCTEST_CONSTEXPR const #define DOCTEST_CONSTEXPR_FUNC inline #else // DOCTEST_MSVC #define DOCTEST_CONSTEXPR constexpr #define DOCTEST_CONSTEXPR_FUNC constexpr #endif // DOCTEST_MSVC #endif // DOCTEST_CONSTEXPR #ifndef DOCTEST_NO_SANITIZE_INTEGER #if DOCTEST_CLANG >= DOCTEST_COMPILER(3, 7, 0) #define DOCTEST_NO_SANITIZE_INTEGER __attribute__((no_sanitize("integer"))) #else #define DOCTEST_NO_SANITIZE_INTEGER #endif #endif // DOCTEST_NO_SANITIZE_INTEGER // ================================================================================================= // == FEATURE DETECTION END ======================================================================== // ================================================================================================= #define DOCTEST_DECLARE_INTERFACE(name) \ virtual ~name(); \ name() = default; \ name(const name&) = delete; \ name(name&&) = delete; \ name& operator=(const name&) = delete; \ name& operator=(name&&) = delete; #define DOCTEST_DEFINE_INTERFACE(name) \ name::~name() = default; // internal macros for string concatenation and anonymous variable name generation #define DOCTEST_CAT_IMPL(s1, s2) s1##s2 #define DOCTEST_CAT(s1, s2) DOCTEST_CAT_IMPL(s1, s2) #ifdef __COUNTER__ // not standard and may be missing for some compilers #define DOCTEST_ANONYMOUS(x) DOCTEST_CAT(x, __COUNTER__) #else // __COUNTER__ #define DOCTEST_ANONYMOUS(x) DOCTEST_CAT(x, __LINE__) #endif // __COUNTER__ #ifndef DOCTEST_CONFIG_ASSERTION_PARAMETERS_BY_VALUE #define DOCTEST_REF_WRAP(x) x& #else // DOCTEST_CONFIG_ASSERTION_PARAMETERS_BY_VALUE #define DOCTEST_REF_WRAP(x) x #endif // DOCTEST_CONFIG_ASSERTION_PARAMETERS_BY_VALUE // not using __APPLE__ because... this is how Catch does it #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED #define DOCTEST_PLATFORM_MAC #elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #define DOCTEST_PLATFORM_IPHONE #elif defined(_WIN32) #define DOCTEST_PLATFORM_WINDOWS #elif defined(__wasi__) #define DOCTEST_PLATFORM_WASI #else // DOCTEST_PLATFORM #define DOCTEST_PLATFORM_LINUX #endif // DOCTEST_PLATFORM namespace doctest { namespace detail { static DOCTEST_CONSTEXPR int consume(const int*, int) noexcept { return 0; } }} #define DOCTEST_GLOBAL_NO_WARNINGS(var, ...) \ DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wglobal-constructors") \ static const int var = doctest::detail::consume(&var, __VA_ARGS__); \ DOCTEST_CLANG_SUPPRESS_WARNING_POP #ifndef DOCTEST_BREAK_INTO_DEBUGGER // should probably take a look at https://github.com/scottt/debugbreak #ifdef DOCTEST_PLATFORM_LINUX #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) // Break at the location of the failing check if possible #define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("int $3\n" : :) // NOLINT(hicpp-no-assembler) #else #include <signal.h> #define DOCTEST_BREAK_INTO_DEBUGGER() raise(SIGTRAP) #endif #elif defined(DOCTEST_PLATFORM_MAC) #if defined(__x86_64) || defined(__x86_64__) || defined(__amd64__) || defined(__i386) #define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("int $3\n" : :) // NOLINT(hicpp-no-assembler) #elif defined(__ppc__) || defined(__ppc64__) // https://www.cocoawithlove.com/2008/03/break-into-debugger.html #define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n": : : "memory","r0","r3","r4") // NOLINT(hicpp-no-assembler) #else #define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("brk #0"); // NOLINT(hicpp-no-assembler) #endif #elif DOCTEST_MSVC #define DOCTEST_BREAK_INTO_DEBUGGER() __debugbreak() #elif defined(__MINGW32__) DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wredundant-decls") extern "C" __declspec(dllimport) void __stdcall DebugBreak(); DOCTEST_GCC_SUPPRESS_WARNING_POP #define DOCTEST_BREAK_INTO_DEBUGGER() ::DebugBreak() #else // linux #define DOCTEST_BREAK_INTO_DEBUGGER() (static_cast<void>(0)) #endif // linux #endif // DOCTEST_BREAK_INTO_DEBUGGER // this is kept here for backwards compatibility since the config option was changed #ifdef DOCTEST_CONFIG_USE_IOSFWD #ifndef DOCTEST_CONFIG_USE_STD_HEADERS #define DOCTEST_CONFIG_USE_STD_HEADERS #endif #endif // DOCTEST_CONFIG_USE_IOSFWD // for clang - always include ciso646 (which drags some std stuff) because // we want to check if we are using libc++ with the _LIBCPP_VERSION macro in // which case we don't want to forward declare stuff from std - for reference: // https://github.com/doctest/doctest/issues/126 // https://github.com/doctest/doctest/issues/356 #if DOCTEST_CLANG #include <ciso646> #endif // clang #ifdef _LIBCPP_VERSION #ifndef DOCTEST_CONFIG_USE_STD_HEADERS #define DOCTEST_CONFIG_USE_STD_HEADERS #endif #endif // _LIBCPP_VERSION #ifdef DOCTEST_CONFIG_USE_STD_HEADERS #ifndef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS #define DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS #endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN #include <cstddef> #include <ostream> #include <istream> DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END #else // DOCTEST_CONFIG_USE_STD_HEADERS // Forward declaring 'X' in namespace std is not permitted by the C++ Standard. DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4643) namespace std { // NOLINT(cert-dcl58-cpp) typedef decltype(nullptr) nullptr_t; // NOLINT(modernize-use-using) typedef decltype(sizeof(void*)) size_t; // NOLINT(modernize-use-using) template <class charT> struct char_traits; template <> struct char_traits<char>; template <class charT, class traits> class basic_ostream; // NOLINT(fuchsia-virtual-inheritance) typedef basic_ostream<char, char_traits<char>> ostream; // NOLINT(modernize-use-using) template<class traits> // NOLINTNEXTLINE basic_ostream<char, traits>& operator<<(basic_ostream<char, traits>&, const char*); template <class charT, class traits> class basic_istream; typedef basic_istream<char, char_traits<char>> istream; // NOLINT(modernize-use-using) template <class... Types> class tuple; #if DOCTEST_MSVC >= DOCTEST_COMPILER(19, 20, 0) // see this issue on why this is needed: https://github.com/doctest/doctest/issues/183 template <class Ty> class allocator; template <class Elem, class Traits, class Alloc> class basic_string; using string = basic_string<char, char_traits<char>, allocator<char>>; #endif // VS 2019 } // namespace std DOCTEST_MSVC_SUPPRESS_WARNING_POP #endif // DOCTEST_CONFIG_USE_STD_HEADERS #ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS #include <type_traits> #endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS namespace doctest { using std::size_t; DOCTEST_INTERFACE extern bool is_running_in_test; #ifndef DOCTEST_CONFIG_STRING_SIZE_TYPE #define DOCTEST_CONFIG_STRING_SIZE_TYPE unsigned #endif // A 24 byte string class (can be as small as 17 for x64 and 13 for x86) that can hold strings with length // of up to 23 chars on the stack before going on the heap - the last byte of the buffer is used for: // - "is small" bit - the highest bit - if "0" then it is small - otherwise its "1" (128) // - if small - capacity left before going on the heap - using the lowest 5 bits // - if small - 2 bits are left unused - the second and third highest ones // - if small - acts as a null terminator if strlen() is 23 (24 including the null terminator) // and the "is small" bit remains "0" ("as well as the capacity left") so its OK // Idea taken from this lecture about the string implementation of facebook/folly - fbstring // https://www.youtube.com/watch?v=kPR8h4-qZdk // TODO: // - optimizations - like not deleting memory unnecessarily in operator= and etc. // - resize/reserve/clear // - replace // - back/front // - iterator stuff // - find & friends // - push_back/pop_back // - assign/insert/erase // - relational operators as free functions - taking const char* as one of the params class DOCTEST_INTERFACE String { public: using size_type = DOCTEST_CONFIG_STRING_SIZE_TYPE; private: static DOCTEST_CONSTEXPR size_type len = 24; //!OCLINT avoid private static members static DOCTEST_CONSTEXPR size_type last = len - 1; //!OCLINT avoid private static members struct view // len should be more than sizeof(view) - because of the final byte for flags { char* ptr; size_type size; size_type capacity; }; union { char buf[len]; // NOLINT(*-avoid-c-arrays) view data; }; char* allocate(size_type sz); bool isOnStack() const noexcept { return (buf[last] & 128) == 0; } void setOnHeap() noexcept; void setLast(size_type in = last) noexcept; void setSize(size_type sz) noexcept; void copy(const String& other); public: static DOCTEST_CONSTEXPR size_type npos = static_cast<size_type>(-1); String() noexcept; ~String(); // cppcheck-suppress noExplicitConstructor String(const char* in); String(const char* in, size_type in_size); String(std::istream& in, size_type in_size); String(const String& other); String& operator=(const String& other); String& operator+=(const String& other); String(String&& other) noexcept; String& operator=(String&& other) noexcept; char operator[](size_type i) const; char& operator[](size_type i); // the only functions I'm willing to leave in the interface - available for inlining const char* c_str() const { return const_cast<String*>(this)->c_str(); } // NOLINT char* c_str() { if (isOnStack()) { return reinterpret_cast<char*>(buf); } return data.ptr; } size_type size() const; size_type capacity() const; String substr(size_type pos, size_type cnt = npos) &&; String substr(size_type pos, size_type cnt = npos) const &; size_type find(char ch, size_type pos = 0) const; size_type rfind(char ch, size_type pos = npos) const; int compare(const char* other, bool no_case = false) const; int compare(const String& other, bool no_case = false) const; friend DOCTEST_INTERFACE std::ostream& operator<<(std::ostream& s, const String& in); }; DOCTEST_INTERFACE String operator+(const String& lhs, const String& rhs); DOCTEST_INTERFACE bool operator==(const String& lhs, const String& rhs); DOCTEST_INTERFACE bool operator!=(const String& lhs, const String& rhs); DOCTEST_INTERFACE bool operator<(const String& lhs, const String& rhs); DOCTEST_INTERFACE bool operator>(const String& lhs, const String& rhs); DOCTEST_INTERFACE bool operator<=(const String& lhs, const String& rhs); DOCTEST_INTERFACE bool operator>=(const String& lhs, const String& rhs); class DOCTEST_INTERFACE Contains { public: explicit Contains(const String& string); bool checkWith(const String& other) const; String string; }; DOCTEST_INTERFACE String toString(const Contains& in); DOCTEST_INTERFACE bool operator==(const String& lhs, const Contains& rhs); DOCTEST_INTERFACE bool operator==(const Contains& lhs, const String& rhs); DOCTEST_INTERFACE bool operator!=(const String& lhs, const Contains& rhs); DOCTEST_INTERFACE bool operator!=(const Contains& lhs, const String& rhs); namespace Color { enum Enum { None = 0, White, Red, Green, Blue, Cyan, Yellow, Grey, Bright = 0x10, BrightRed = Bright | Red, BrightGreen = Bright | Green, LightGrey = Bright | Grey, BrightWhite = Bright | White }; DOCTEST_INTERFACE std::ostream& operator<<(std::ostream& s, Color::Enum code); } // namespace Color namespace assertType { enum Enum { // macro traits is_warn = 1, is_check = 2 * is_warn, is_require = 2 * is_check, is_normal = 2 * is_require, is_throws = 2 * is_normal, is_throws_as = 2 * is_throws, is_throws_with = 2 * is_throws_as, is_nothrow = 2 * is_throws_with, is_false = 2 * is_nothrow, is_unary = 2 * is_false, // not checked anywhere - used just to distinguish the types is_eq = 2 * is_unary, is_ne = 2 * is_eq, is_lt = 2 * is_ne, is_gt = 2 * is_lt, is_ge = 2 * is_gt, is_le = 2 * is_ge, // macro types DT_WARN = is_normal | is_warn, DT_CHECK = is_normal | is_check, DT_REQUIRE = is_normal | is_require, DT_WARN_FALSE = is_normal | is_false | is_warn, DT_CHECK_FALSE = is_normal | is_false | is_check, DT_REQUIRE_FALSE = is_normal | is_false | is_require, DT_WARN_THROWS = is_throws | is_warn, DT_CHECK_THROWS = is_throws | is_check, DT_REQUIRE_THROWS = is_throws | is_require, DT_WARN_THROWS_AS = is_throws_as | is_warn, DT_CHECK_THROWS_AS = is_throws_as | is_check, DT_REQUIRE_THROWS_AS = is_throws_as | is_require, DT_WARN_THROWS_WITH = is_throws_with | is_warn, DT_CHECK_THROWS_WITH = is_throws_with | is_check, DT_REQUIRE_THROWS_WITH = is_throws_with | is_require, DT_WARN_THROWS_WITH_AS = is_throws_with | is_throws_as | is_warn, DT_CHECK_THROWS_WITH_AS = is_throws_with | is_throws_as | is_check, DT_REQUIRE_THROWS_WITH_AS = is_throws_with | is_throws_as | is_require, DT_WARN_NOTHROW = is_nothrow | is_warn, DT_CHECK_NOTHROW = is_nothrow | is_check, DT_REQUIRE_NOTHROW = is_nothrow | is_require, DT_WARN_EQ = is_normal | is_eq | is_warn, DT_CHECK_EQ = is_normal | is_eq | is_check, DT_REQUIRE_EQ = is_normal | is_eq | is_require, DT_WARN_NE = is_normal | is_ne | is_warn, DT_CHECK_NE = is_normal | is_ne | is_check, DT_REQUIRE_NE = is_normal | is_ne | is_require, DT_WARN_GT = is_normal | is_gt | is_warn, DT_CHECK_GT = is_normal | is_gt | is_check, DT_REQUIRE_GT = is_normal | is_gt | is_require, DT_WARN_LT = is_normal | is_lt | is_warn, DT_CHECK_LT = is_normal | is_lt | is_check, DT_REQUIRE_LT = is_normal | is_lt | is_require, DT_WARN_GE = is_normal | is_ge | is_warn, DT_CHECK_GE = is_normal | is_ge | is_check, DT_REQUIRE_GE = is_normal | is_ge | is_require, DT_WARN_LE = is_normal | is_le | is_warn, DT_CHECK_LE = is_normal | is_le | is_check, DT_REQUIRE_LE = is_normal | is_le | is_require, DT_WARN_UNARY = is_normal | is_unary | is_warn, DT_CHECK_UNARY = is_normal | is_unary | is_check, DT_REQUIRE_UNARY = is_normal | is_unary | is_require, DT_WARN_UNARY_FALSE = is_normal | is_false | is_unary | is_warn, DT_CHECK_UNARY_FALSE = is_normal | is_false | is_unary | is_check, DT_REQUIRE_UNARY_FALSE = is_normal | is_false | is_unary | is_require, }; } // namespace assertType DOCTEST_INTERFACE const char* assertString(assertType::Enum at); DOCTEST_INTERFACE const char* failureString(assertType::Enum at); DOCTEST_INTERFACE const char* skipPathFromFilename(const char* file); struct DOCTEST_INTERFACE TestCaseData { String m_file; // the file in which the test was registered (using String - see #350) unsigned m_line; // the line where the test was registered const char* m_name; // name of the test case const char* m_test_suite; // the test suite in which the test was added const char* m_description; bool m_skip; bool m_no_breaks; bool m_no_output; bool m_may_fail; bool m_should_fail; int m_expected_failures; double m_timeout; }; struct DOCTEST_INTERFACE AssertData { // common - for all asserts const TestCaseData* m_test_case; assertType::Enum m_at; const char* m_file; int m_line; const char* m_expr; bool m_failed; // exception-related - for all asserts bool m_threw; String m_exception; // for normal asserts String m_decomp; // for specific exception-related asserts bool m_threw_as; const char* m_exception_type; class DOCTEST_INTERFACE StringContains { private: Contains content; bool isContains; public: StringContains(const String& str) : content(str), isContains(false) { } StringContains(Contains cntn) : content(static_cast<Contains&&>(cntn)), isContains(true) { } bool check(const String& str) { return isContains ? (content == str) : (content.string == str); } operator const String&() const { return content.string; } const char* c_str() const { return content.string.c_str(); } } m_exception_string; AssertData(assertType::Enum at, const char* file, int line, const char* expr, const char* exception_type, const StringContains& exception_string); }; struct DOCTEST_INTERFACE MessageData { String m_string; const char* m_file; int m_line; assertType::Enum m_severity; }; struct DOCTEST_INTERFACE SubcaseSignature { String m_name; const char* m_file; int m_line; bool operator==(const SubcaseSignature& other) const; bool operator<(const SubcaseSignature& other) const; }; struct DOCTEST_INTERFACE IContextScope { DOCTEST_DECLARE_INTERFACE(IContextScope) virtual void stringify(std::ostream*) const = 0; }; namespace detail { struct DOCTEST_INTERFACE TestCase; } // namespace detail struct ContextOptions //!OCLINT too many fields { std::ostream* cout = nullptr; // stdout stream String binary_name; // the test binary name const detail::TestCase* currentTest = nullptr; // == parameters from the command line String out; // output filename String order_by; // how tests should be ordered unsigned rand_seed; // the seed for rand ordering unsigned first; // the first (matching) test to be executed unsigned last; // the last (matching) test to be executed int abort_after; // stop tests after this many failed assertions int subcase_filter_levels; // apply the subcase filters for the first N levels bool success; // include successful assertions in output bool case_sensitive; // if filtering should be case sensitive bool exit; // if the program should be exited after the tests are ran/whatever bool duration; // print the time duration of each test case bool minimal; // minimal console output (only test failures) bool quiet; // no console output bool no_throw; // to skip exceptions-related assertion macros bool no_exitcode; // if the framework should return 0 as the exitcode bool no_run; // to not run the tests at all (can be done with an "*" exclude) bool no_intro; // to not print the intro of the framework bool no_version; // to not print the version of the framework bool no_colors; // if output to the console should be colorized bool force_colors; // forces the use of colors even when a tty cannot be detected bool no_breaks; // to not break into the debugger bool no_skip; // don't skip test cases which are marked to be skipped bool gnu_file_line; // if line numbers should be surrounded with :x: and not (x): bool no_path_in_filenames; // if the path to files should be removed from the output bool no_line_numbers; // if source code line numbers should be omitted from the output bool no_debug_output; // no output in the debug console when a debugger is attached bool no_skipped_summary; // don't print "skipped" in the summary !!! UNDOCUMENTED !!! bool no_time_in_output; // omit any time/timestamps from output !!! UNDOCUMENTED !!! bool help; // to print the help bool version; // to print the version bool count; // if only the count of matching tests is to be retrieved bool list_test_cases; // to list all tests matching the filters bool list_test_suites; // to list all suites matching the filters bool list_reporters; // lists all registered reporters }; namespace detail { namespace types { #ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS using namespace std; #else template <bool COND, typename T = void> struct enable_if { }; template <typename T> struct enable_if<true, T> { using type = T; }; struct true_type { static DOCTEST_CONSTEXPR bool value = true; }; struct false_type { static DOCTEST_CONSTEXPR bool value = false; }; template <typename T> struct remove_reference { using type = T; }; template <typename T> struct remove_reference<T&> { using type = T; }; template <typename T> struct remove_reference<T&&> { using type = T; }; template <typename T> struct is_rvalue_reference : false_type { }; template <typename T> struct is_rvalue_reference<T&&> : true_type { }; template<typename T> struct remove_const { using type = T; }; template <typename T> struct remove_const<const T> { using type = T; }; // Compiler intrinsics template <typename T> struct is_enum { static DOCTEST_CONSTEXPR bool value = __is_enum(T); }; template <typename T> struct underlying_type { using type = __underlying_type(T); }; template <typename T> struct is_pointer : false_type { }; template <typename T> struct is_pointer<T*> : true_type { }; template <typename T> struct is_array : false_type { }; // NOLINTNEXTLINE(*-avoid-c-arrays) template <typename T, size_t SIZE> struct is_array<T[SIZE]> : true_type { }; #endif } // <utility> template <typename T> T&& declval(); template <class T> DOCTEST_CONSTEXPR_FUNC T&& forward(typename types::remove_reference<T>::type& t) DOCTEST_NOEXCEPT { return static_cast<T&&>(t); } template <class T> DOCTEST_CONSTEXPR_FUNC T&& forward(typename types::remove_reference<T>::type&& t) DOCTEST_NOEXCEPT { return static_cast<T&&>(t); } template <typename T> struct deferred_false : types::false_type { }; // MSVS 2015 :( #if !DOCTEST_CLANG && defined(_MSC_VER) && _MSC_VER <= 1900 template <typename T, typename = void> struct has_global_insertion_operator : types::false_type { }; template <typename T> struct has_global_insertion_operator<T, decltype(::operator<<(declval<std::ostream&>(), declval<const T&>()), void())> : types::true_type { }; template <typename T, typename = void> struct has_insertion_operator { static DOCTEST_CONSTEXPR bool value = has_global_insertion_operator<T>::value; }; template <typename T, bool global> struct insert_hack; template <typename T> struct insert_hack<T, true> { static void insert(std::ostream& os, const T& t) { ::operator<<(os, t); } }; template <typename T> struct insert_hack<T, false> { static void insert(std::ostream& os, const T& t) { operator<<(os, t); } }; template <typename T> using insert_hack_t = insert_hack<T, has_global_insertion_operator<T>::value>; #else template <typename T, typename = void> struct has_insertion_operator : types::false_type { }; #endif template <typename T> struct has_insertion_operator<T, decltype(operator<<(declval<std::ostream&>(), declval<const T&>()), void())> : types::true_type { }; template <typename T> struct should_stringify_as_underlying_type { static DOCTEST_CONSTEXPR bool value = detail::types::is_enum<T>::value && !doctest::detail::has_insertion_operator<T>::value; }; DOCTEST_INTERFACE std::ostream* tlssPush(); DOCTEST_INTERFACE String tlssPop(); template <bool C> struct StringMakerBase { template <typename T> static String convert(const DOCTEST_REF_WRAP(T)) { #ifdef DOCTEST_CONFIG_REQUIRE_STRINGIFICATION_FOR_ALL_USED_TYPES static_assert(deferred_false<T>::value, "No stringification detected for type T. See string conversion manual"); #endif return "{?}"; } }; template <typename T> struct filldata; template <typename T> void filloss(std::ostream* stream, const T& in) { filldata<T>::fill(stream, in); } template <typename T, size_t N> void filloss(std::ostream* stream, const T (&in)[N]) { // NOLINT(*-avoid-c-arrays) // T[N], T(&)[N], T(&&)[N] have same behaviour. // Hence remove reference. filloss<typename types::remove_reference<decltype(in)>::type>(stream, in); } template <typename T> String toStream(const T& in) { std::ostream* stream = tlssPush(); filloss(stream, in); return tlssPop(); } template <> struct StringMakerBase<true> { template <typename T> static String convert(const DOCTEST_REF_WRAP(T) in) { return toStream(in); } }; } // namespace detail template <typename T> struct StringMaker : public detail::StringMakerBase< detail::has_insertion_operator<T>::value || detail::types::is_pointer<T>::value || detail::types::is_array<T>::value> {}; #ifndef DOCTEST_STRINGIFY #ifdef DOCTEST_CONFIG_DOUBLE_STRINGIFY #define DOCTEST_STRINGIFY(...) toString(toString(__VA_ARGS__)) #else #define DOCTEST_STRINGIFY(...) toString(__VA_ARGS__) #endif #endif template <typename T> String toString() { #if DOCTEST_CLANG == 0 && DOCTEST_GCC == 0 && DOCTEST_ICC == 0 String ret = __FUNCSIG__; // class doctest::String __cdecl doctest::toString<TYPE>(void) String::size_type beginPos = ret.find('<'); return ret.substr(beginPos + 1, ret.size() - beginPos - static_cast<String::size_type>(sizeof(">(void)"))); #else String ret = __PRETTY_FUNCTION__; // doctest::String toString() [with T = TYPE] String::size_type begin = ret.find('=') + 2; return ret.substr(begin, ret.size() - begin - 1); #endif } template <typename T, typename detail::types::enable_if<!detail::should_stringify_as_underlying_type<T>::value, bool>::type = true> String toString(const DOCTEST_REF_WRAP(T) value) { return StringMaker<T>::convert(value); } #ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING DOCTEST_INTERFACE String toString(const char* in); #endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING #if DOCTEST_MSVC >= DOCTEST_COMPILER(19, 20, 0) // see this issue on why this is needed: https://github.com/doctest/doctest/issues/183 DOCTEST_INTERFACE String toString(const std::string& in); #endif // VS 2019 DOCTEST_INTERFACE String toString(String in); DOCTEST_INTERFACE String toString(std::nullptr_t); DOCTEST_INTERFACE String toString(bool in); DOCTEST_INTERFACE String toString(float in); DOCTEST_INTERFACE String toString(double in); DOCTEST_INTERFACE String toString(double long in); DOCTEST_INTERFACE String toString(char in); DOCTEST_INTERFACE String toString(char signed in); DOCTEST_INTERFACE String toString(char unsigned in); DOCTEST_INTERFACE String toString(short in); DOCTEST_INTERFACE String toString(short unsigned in); DOCTEST_INTERFACE String toString(signed in); DOCTEST_INTERFACE String toString(unsigned in); DOCTEST_INTERFACE String toString(long in); DOCTEST_INTERFACE String toString(long unsigned in); DOCTEST_INTERFACE String toString(long long in); DOCTEST_INTERFACE String toString(long long unsigned in); template <typename T, typename detail::types::enable_if<detail::should_stringify_as_underlying_type<T>::value, bool>::type = true> String toString(const DOCTEST_REF_WRAP(T) value) { using UT = typename detail::types::underlying_type<T>::type; return (DOCTEST_STRINGIFY(static_cast<UT>(value))); } namespace detail { template <typename T> struct filldata { static void fill(std::ostream* stream, const T& in) { #if defined(_MSC_VER) && _MSC_VER <= 1900 insert_hack_t<T>::insert(*stream, in); #else operator<<(*stream, in); #endif } }; DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4866) // NOLINTBEGIN(*-avoid-c-arrays) template <typename T, size_t N> struct filldata<T[N]> { static void fill(std::ostream* stream, const T(&in)[N]) { *stream << "["; for (size_t i = 0; i < N; i++) { if (i != 0) { *stream << ", "; } *stream << (DOCTEST_STRINGIFY(in[i])); } *stream << "]"; } }; // NOLINTEND(*-avoid-c-arrays) DOCTEST_MSVC_SUPPRESS_WARNING_POP // Specialized since we don't want the terminating null byte! // NOLINTBEGIN(*-avoid-c-arrays) template <size_t N> struct filldata<const char[N]> { static void fill(std::ostream* stream, const char (&in)[N]) { *stream << String(in, in[N - 1] ? N : N - 1); } // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks) }; // NOLINTEND(*-avoid-c-arrays) template <> struct filldata<const void*> { static void fill(std::ostream* stream, const void* in); }; template <typename T> struct filldata<T*> { DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4180) static void fill(std::ostream* stream, const T* in) { DOCTEST_MSVC_SUPPRESS_WARNING_POP DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wmicrosoft-cast") filldata<const void*>::fill(stream, #if DOCTEST_GCC == 0 || DOCTEST_GCC >= DOCTEST_COMPILER(4, 9, 0) reinterpret_cast<const void*>(in) #else *reinterpret_cast<const void* const*>(&in) #endif ); DOCTEST_CLANG_SUPPRESS_WARNING_POP } }; } struct DOCTEST_INTERFACE Approx { Approx(double value); Approx operator()(double value) const; #ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS template <typename T> explicit Approx(const T& value, typename detail::types::enable_if<std::is_constructible<double, T>::value>::type* = static_cast<T*>(nullptr)) { *this = static_cast<double>(value); } #endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS Approx& epsilon(double newEpsilon); #ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS template <typename T> typename std::enable_if<std::is_constructible<double, T>::value, Approx&>::type epsilon( const T& newEpsilon) { m_epsilon = static_cast<double>(newEpsilon); return *this; } #endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS Approx& scale(double newScale); #ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS template <typename T> typename std::enable_if<std::is_constructible<double, T>::value, Approx&>::type scale( const T& newScale) { m_scale = static_cast<double>(newScale); return *this; } #endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS // clang-format off DOCTEST_INTERFACE friend bool operator==(double lhs, const Approx & rhs); DOCTEST_INTERFACE friend bool operator==(const Approx & lhs, double rhs); DOCTEST_INTERFACE friend bool operator!=(double lhs, const Approx & rhs); DOCTEST_INTERFACE friend bool operator!=(const Approx & lhs, double rhs); DOCTEST_INTERFACE friend bool operator<=(double lhs, const Approx & rhs); DOCTEST_INTERFACE friend bool operator<=(const Approx & lhs, double rhs); DOCTEST_INTERFACE friend bool operator>=(double lhs, const Approx & rhs); DOCTEST_INTERFACE friend bool operator>=(const Approx & lhs, double rhs); DOCTEST_INTERFACE friend bool operator< (double lhs, const Approx & rhs); DOCTEST_INTERFACE friend bool operator< (const Approx & lhs, double rhs); DOCTEST_INTERFACE friend bool operator> (double lhs, const Approx & rhs); DOCTEST_INTERFACE friend bool operator> (const Approx & lhs, double rhs); #ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS #define DOCTEST_APPROX_PREFIX \ template <typename T> friend typename std::enable_if<std::is_constructible<double, T>::value, bool>::type DOCTEST_APPROX_PREFIX operator==(const T& lhs, const Approx& rhs) { return operator==(static_cast<double>(lhs), rhs); } DOCTEST_APPROX_PREFIX operator==(const Approx& lhs, const T& rhs) { return operator==(rhs, lhs); } DOCTEST_APPROX_PREFIX operator!=(const T& lhs, const Approx& rhs) { return !operator==(lhs, rhs); } DOCTEST_APPROX_PREFIX operator!=(const Approx& lhs, const T& rhs) { return !operator==(rhs, lhs); } DOCTEST_APPROX_PREFIX operator<=(const T& lhs, const Approx& rhs) { return static_cast<double>(lhs) < rhs.m_value || lhs == rhs; } DOCTEST_APPROX_PREFIX operator<=(const Approx& lhs, const T& rhs) { return lhs.m_value < static_cast<double>(rhs) || lhs == rhs; } DOCTEST_APPROX_PREFIX operator>=(const T& lhs, const Approx& rhs) { return static_cast<double>(lhs) > rhs.m_value || lhs == rhs; } DOCTEST_APPROX_PREFIX operator>=(const Approx& lhs, const T& rhs) { return lhs.m_value > static_cast<double>(rhs) || lhs == rhs; } DOCTEST_APPROX_PREFIX operator< (const T& lhs, const Approx& rhs) { return static_cast<double>(lhs) < rhs.m_value && lhs != rhs; } DOCTEST_APPROX_PREFIX operator< (const Approx& lhs, const T& rhs) { return lhs.m_value < static_cast<double>(rhs) && lhs != rhs; } DOCTEST_APPROX_PREFIX operator> (const T& lhs, const Approx& rhs) { return static_cast<double>(lhs) > rhs.m_value && lhs != rhs; } DOCTEST_APPROX_PREFIX operator> (const Approx& lhs, const T& rhs) { return lhs.m_value > static_cast<double>(rhs) && lhs != rhs; } #undef DOCTEST_APPROX_PREFIX #endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS // clang-format on double m_epsilon; double m_scale; double m_value; }; DOCTEST_INTERFACE String toString(const Approx& in); DOCTEST_INTERFACE const ContextOptions* getContextOptions(); template <typename F> struct DOCTEST_INTERFACE_DECL IsNaN { F value; bool flipped; IsNaN(F f, bool flip = false) : value(f), flipped(flip) { } IsNaN<F> operator!() const { return { value, !flipped }; } operator bool() const; }; #ifndef __MINGW32__ extern template struct DOCTEST_INTERFACE_DECL IsNaN<float>; extern template struct DOCTEST_INTERFACE_DECL IsNaN<double>; extern template struct DOCTEST_INTERFACE_DECL IsNaN<long double>; #endif DOCTEST_INTERFACE String toString(IsNaN<float> in); DOCTEST_INTERFACE String toString(IsNaN<double> in); DOCTEST_INTERFACE String toString(IsNaN<double long> in); #ifndef DOCTEST_CONFIG_DISABLE namespace detail { // clang-format off #ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING template<class T> struct decay_array { using type = T; }; template<class T, unsigned N> struct decay_array<T[N]> { using type = T*; }; template<class T> struct decay_array<T[]> { using type = T*; }; template<class T> struct not_char_pointer { static DOCTEST_CONSTEXPR int value = 1; }; template<> struct not_char_pointer<char*> { static DOCTEST_CONSTEXPR int value = 0; }; template<> struct not_char_pointer<const char*> { static DOCTEST_CONSTEXPR int value = 0; }; template<class T> struct can_use_op : public not_char_pointer<typename decay_array<T>::type> {}; #endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING // clang-format on struct DOCTEST_INTERFACE TestFailureException { }; DOCTEST_INTERFACE bool checkIfShouldThrow(assertType::Enum at); #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS DOCTEST_NORETURN #endif // DOCTEST_CONFIG_NO_EXCEPTIONS DOCTEST_INTERFACE void throwException(); struct DOCTEST_INTERFACE Subcase { SubcaseSignature m_signature; bool m_entered = false; Subcase(const String& name, const char* file, int line); Subcase(const Subcase&) = delete; Subcase(Subcase&&) = delete; Subcase& operator=(const Subcase&) = delete; Subcase& operator=(Subcase&&) = delete; ~Subcase(); operator bool() const; private: bool checkFilters(); }; template <typename L, typename R> String stringifyBinaryExpr(const DOCTEST_REF_WRAP(L) lhs, const char* op, const DOCTEST_REF_WRAP(R) rhs) { return (DOCTEST_STRINGIFY(lhs)) + op + (DOCTEST_STRINGIFY(rhs)); } #if DOCTEST_CLANG && DOCTEST_CLANG < DOCTEST_COMPILER(3, 6, 0) DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wunused-comparison") #endif // This will check if there is any way it could find a operator like member or friend and uses it. // If not it doesn't find the operator or if the operator at global scope is defined after // this template, the template won't be instantiated due to SFINAE. Once the template is not // instantiated it can look for global operator using normal conversions. #ifdef __NVCC__ #define SFINAE_OP(ret,op) ret #else #define SFINAE_OP(ret,op) decltype((void)(doctest::detail::declval<L>() op doctest::detail::declval<R>()),ret{}) #endif #define DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(op, op_str, op_macro) \ template <typename R> \ DOCTEST_NOINLINE SFINAE_OP(Result,op) operator op(R&& rhs) { \ bool res = op_macro(doctest::detail::forward<const L>(lhs), doctest::detail::forward<R>(rhs)); \ if(m_at & assertType::is_false) \ res = !res; \ if(!res || doctest::getContextOptions()->success) \ return Result(res, stringifyBinaryExpr(lhs, op_str, rhs)); \ return Result(res); \ } // more checks could be added - like in Catch: // https://github.com/catchorg/Catch2/pull/1480/files // https://github.com/catchorg/Catch2/pull/1481/files #define DOCTEST_FORBIT_EXPRESSION(rt, op) \ template <typename R> \ rt& operator op(const R&) { \ static_assert(deferred_false<R>::value, \ "Expression Too Complex Please Rewrite As Binary Comparison!"); \ return *this; \ } struct DOCTEST_INTERFACE Result // NOLINT(*-member-init) { bool m_passed; String m_decomp; Result() = default; // TODO: Why do we need this? (To remove NOLINT) Result(bool passed, const String& decomposition = String()); // forbidding some expressions based on this table: https://en.cppreference.com/w/cpp/language/operator_precedence DOCTEST_FORBIT_EXPRESSION(Result, &) DOCTEST_FORBIT_EXPRESSION(Result, ^) DOCTEST_FORBIT_EXPRESSION(Result, |) DOCTEST_FORBIT_EXPRESSION(Result, &&) DOCTEST_FORBIT_EXPRESSION(Result, ||) DOCTEST_FORBIT_EXPRESSION(Result, ==) DOCTEST_FORBIT_EXPRESSION(Result, !=) DOCTEST_FORBIT_EXPRESSION(Result, <) DOCTEST_FORBIT_EXPRESSION(Result, >) DOCTEST_FORBIT_EXPRESSION(Result, <=) DOCTEST_FORBIT_EXPRESSION(Result, >=) DOCTEST_FORBIT_EXPRESSION(Result, =) DOCTEST_FORBIT_EXPRESSION(Result, +=) DOCTEST_FORBIT_EXPRESSION(Result, -=) DOCTEST_FORBIT_EXPRESSION(Result, *=) DOCTEST_FORBIT_EXPRESSION(Result, /=) DOCTEST_FORBIT_EXPRESSION(Result, %=) DOCTEST_FORBIT_EXPRESSION(Result, <<=) DOCTEST_FORBIT_EXPRESSION(Result, >>=) DOCTEST_FORBIT_EXPRESSION(Result, &=) DOCTEST_FORBIT_EXPRESSION(Result, ^=) DOCTEST_FORBIT_EXPRESSION(Result, |=) }; #ifndef DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION DOCTEST_CLANG_SUPPRESS_WARNING_PUSH DOCTEST_CLANG_SUPPRESS_WARNING("-Wsign-conversion") DOCTEST_CLANG_SUPPRESS_WARNING("-Wsign-compare") //DOCTEST_CLANG_SUPPRESS_WARNING("-Wdouble-promotion") //DOCTEST_CLANG_SUPPRESS_WARNING("-Wconversion") //DOCTEST_CLANG_SUPPRESS_WARNING("-Wfloat-equal") DOCTEST_GCC_SUPPRESS_WARNING_PUSH DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-conversion") DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-compare") //DOCTEST_GCC_SUPPRESS_WARNING("-Wdouble-promotion") //DOCTEST_GCC_SUPPRESS_WARNING("-Wconversion") //DOCTEST_GCC_SUPPRESS_WARNING("-Wfloat-equal") DOCTEST_MSVC_SUPPRESS_WARNING_PUSH // https://stackoverflow.com/questions/39479163 what's the difference between 4018 and 4389 DOCTEST_MSVC_SUPPRESS_WARNING(4388) // signed/unsigned mismatch DOCTEST_MSVC_SUPPRESS_WARNING(4389) // 'operator' : signed/unsigned mismatch DOCTEST_MSVC_SUPPRESS_WARNING(4018) // 'expression' : signed/unsigned mismatch //DOCTEST_MSVC_SUPPRESS_WARNING(4805) // 'operation' : unsafe mix of type 'type' and type 'type' in operation #endif // DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION // clang-format off #ifndef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING #define DOCTEST_COMPARISON_RETURN_TYPE bool #else // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING #define DOCTEST_COMPARISON_RETURN_TYPE typename types::enable_if<can_use_op<L>::value || can_use_op<R>::value, bool>::type inline bool eq(const char* lhs, const char* rhs) { return String(lhs) == String(rhs); } inline bool ne(const char* lhs, const char* rhs) { return String(lhs) != String(rhs); } inline bool lt(const char* lhs, const char* rhs) { return String(lhs) < String(rhs); } inline bool gt(const char* lhs, const char* rhs) { return String(lhs) > String(rhs); } inline bool le(const char* lhs, const char* rhs) { return String(lhs) <= String(rhs); } inline bool ge(const char* lhs, const char* rhs) { return String(lhs) >= String(rhs); } #endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING // clang-format on #define DOCTEST_RELATIONAL_OP(name, op) \ template <typename L, typename R> \ DOCTEST_COMPARISON_RETURN_TYPE name(const DOCTEST_REF_WRAP(L) lhs, \ const DOCTEST_REF_WRAP(R) rhs) { \ return lhs op rhs; \ } DOCTEST_RELATIONAL_OP(eq, ==) DOCTEST_RELATIONAL_OP(ne, !=) DOCTEST_RELATIONAL_OP(lt, <) DOCTEST_RELATIONAL_OP(gt, >) DOCTEST_RELATIONAL_OP(le, <=) DOCTEST_RELATIONAL_OP(ge, >=) #ifndef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING #define DOCTEST_CMP_EQ(l, r) l == r #define DOCTEST_CMP_NE(l, r) l != r #define DOCTEST_CMP_GT(l, r) l > r #define DOCTEST_CMP_LT(l, r) l < r #define DOCTEST_CMP_GE(l, r) l >= r #define DOCTEST_CMP_LE(l, r) l <= r #else // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING #define DOCTEST_CMP_EQ(l, r) eq(l, r) #define DOCTEST_CMP_NE(l, r) ne(l, r) #define DOCTEST_CMP_GT(l, r) gt(l, r) #define DOCTEST_CMP_LT(l, r) lt(l, r) #define DOCTEST_CMP_GE(l, r) ge(l, r) #define DOCTEST_CMP_LE(l, r) le(l, r) #endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING template <typename L> // cppcheck-suppress copyCtorAndEqOperator struct Expression_lhs { L lhs; assertType::Enum m_at; explicit Expression_lhs(L&& in, assertType::Enum at) : lhs(static_cast<L&&>(in)) , m_at(at) {} DOCTEST_NOINLINE operator Result() { // this is needed only for MSVC 2015 DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4800) // 'int': forcing value to bool bool res = static_cast<bool>(lhs); DOCTEST_MSVC_SUPPRESS_WARNING_POP if(m_at & assertType::is_false) { //!OCLINT bitwise operator in conditional res = !res; } if(!res || getContextOptions()->success) { return { res, (DOCTEST_STRINGIFY(lhs)) }; } return { res }; } /* This is required for user-defined conversions from Expression_lhs to L */ operator L() const { return lhs; } // clang-format off DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(==, " == ", DOCTEST_CMP_EQ) //!OCLINT bitwise operator in conditional DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(!=, " != ", DOCTEST_CMP_NE) //!OCLINT bitwise operator in conditional DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(>, " > ", DOCTEST_CMP_GT) //!OCLINT bitwise operator in conditional DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(<, " < ", DOCTEST_CMP_LT) //!OCLINT bitwise operator in conditional DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(>=, " >= ", DOCTEST_CMP_GE) //!OCLINT bitwise operator in conditional DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(<=, " <= ", DOCTEST_CMP_LE) //!OCLINT bitwise operator in conditional // clang-format on // forbidding some expressions based on this table: https://en.cppreference.com/w/cpp/language/operator_precedence DOCTEST_FORBIT_EXPRESSION(Expression_lhs, &) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, ^) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, |) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, &&) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, ||) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, =) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, +=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, -=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, *=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, /=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, %=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, <<=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, >>=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, &=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, ^=) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, |=) // these 2 are unfortunate because they should be allowed - they have higher precedence over the comparisons, but the // ExpressionDecomposer class uses the left shift operator to capture the left operand of the binary expression... DOCTEST_FORBIT_EXPRESSION(Expression_lhs, <<) DOCTEST_FORBIT_EXPRESSION(Expression_lhs, >>) }; #ifndef DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION DOCTEST_CLANG_SUPPRESS_WARNING_POP DOCTEST_MSVC_SUPPRESS_WARNING_POP DOCTEST_GCC_SUPPRESS_WARNING_POP #endif // DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION #if DOCTEST_CLANG && DOCTEST_CLANG < DOCTEST_COMPILER(3, 6, 0) DOCTEST_CLANG_SUPPRESS_WARNING_POP #endif struct DOCTEST_INTERFACE ExpressionDecomposer { assertType::Enum m_at; ExpressionDecomposer(assertType::Enum at); // The right operator for capturing expressions is "<=" instead of "<<" (based on the operator precedence table) // but then there will be warnings from GCC about "-Wparentheses" and since "_Pragma()" is problematic this will stay for now... // https://github.com/catchorg/Catch2/issues/870 // https://github.com/catchorg/Catch2/issues/565 template <typename L> Expression_lhs<L> operator<<(L&& operand) { return Expression_lhs<L>(static_cast<L&&>(operand), m_at); } template <typename L,typename types::enable_if<!doctest::detail::types::is_rvalue_reference<L>::value,void >::type* = nullptr> Expression_lhs<const L&> operator<<(const L &operand) { return Expression_lhs<const L&>(operand, m_at); } }; struct DOCTEST_INTERFACE TestSuite { const char* m_test_suite = nullptr; const char* m_description = nullptr; bool m_skip = false; bool m_no_breaks = false; bool m_no_output = false; bool m_may_fail = false; bool m_should_fail = false; int m_expected_failures = 0; double m_timeout = 0; TestSuite& operator*(const char* in); template <typename T> TestSuite& operator*(const T& in) { in.fill(*this); return *this; } }; using funcType = void (*)(); struct DOCTEST_INTERFACE TestCase : public TestCaseData { funcType m_test; // a function pointer to the test case String m_type; // for templated test cases - gets appended to the real name int m_template_id; // an ID used to distinguish between the different versions of a templated test case String m_full_name; // contains the name (only for templated test cases!) + the template type TestCase(funcType test, const char* file, unsigned line, const TestSuite& test_suite, const String& type = String(), int template_id = -1); TestCase(const TestCase& other); TestCase(TestCase&&) = delete; DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(26434) // hides a non-virtual function TestCase& operator=(const TestCase& other); DOCTEST_MSVC_SUPPRESS_WARNING_POP TestCase& operator=(TestCase&&) = delete; TestCase& operator*(const char* in); template <typename T> TestCase& operator*(const T& in) { in.fill(*this); return *this; } bool operator<(const TestCase& other) const; ~TestCase() = default; }; // forward declarations of functions used by the macros DOCTEST_INTERFACE int regTest(const TestCase& tc); DOCTEST_INTERFACE int setTestSuite(const TestSuite& ts); DOCTEST_INTERFACE bool isDebuggerActive(); template<typename T> int instantiationHelper(const T&) { return 0; } namespace binaryAssertComparison { enum Enum { eq = 0, ne, gt, lt, ge, le }; } // namespace binaryAssertComparison // clang-format off template <int, class L, class R> struct RelationalComparator { bool operator()(const DOCTEST_REF_WRAP(L), const DOCTEST_REF_WRAP(R) ) const { return false; } }; #define DOCTEST_BINARY_RELATIONAL_OP(n, op) \ template <class L, class R> struct RelationalComparator<n, L, R> { bool operator()(const DOCTEST_REF_WRAP(L) lhs, const DOCTEST_REF_WRAP(R) rhs) const { return op(lhs, rhs); } }; // clang-format on DOCTEST_BINARY_RELATIONAL_OP(0, doctest::detail::eq) DOCTEST_BINARY_RELATIONAL_OP(1, doctest::detail::ne) DOCTEST_BINARY_RELATIONAL_OP(2, doctest::detail::gt) DOCTEST_BINARY_RELATIONAL_OP(3, doctest::detail::lt) DOCTEST_BINARY_RELATIONAL_OP(4, doctest::detail::ge) DOCTEST_BINARY_RELATIONAL_OP(5, doctest::detail::le) struct DOCTEST_INTERFACE ResultBuilder : public AssertData { ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, const char* exception_type = "", const String& exception_string = ""); ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, const char* exception_type, const Contains& exception_string); void setResult(const Result& res); template <int comparison, typename L, typename R> DOCTEST_NOINLINE bool binary_assert(const DOCTEST_REF_WRAP(L) lhs, const DOCTEST_REF_WRAP(R) rhs) { m_failed = !RelationalComparator<comparison, L, R>()(lhs, rhs); if (m_failed || getContextOptions()->success) { m_decomp = stringifyBinaryExpr(lhs, ", ", rhs); } return !m_failed; } template <typename L> DOCTEST_NOINLINE bool unary_assert(const DOCTEST_REF_WRAP(L) val) { m_failed = !val; if (m_at & assertType::is_false) { //!OCLINT bitwise operator in conditional m_failed = !m_failed; } if (m_failed || getContextOptions()->success) { m_decomp = (DOCTEST_STRINGIFY(val)); } return !m_failed; } void translateException(); bool log(); void react() const; }; namespace assertAction { enum Enum { nothing = 0, dbgbreak = 1, shouldthrow = 2 }; } // namespace assertAction DOCTEST_INTERFACE void failed_out_of_a_testing_context(const AssertData& ad); DOCTEST_INTERFACE bool decomp_assert(assertType::Enum at, const char* file, int line, const char* expr, const Result& result); #define DOCTEST_ASSERT_OUT_OF_TESTS(decomp) \ do { \ if(!is_running_in_test) { \ if(failed) { \ ResultBuilder rb(at, file, line, expr); \ rb.m_failed = failed; \ rb.m_decomp = decomp; \ failed_out_of_a_testing_context(rb); \ if(isDebuggerActive() && !getContextOptions()->no_breaks) \ DOCTEST_BREAK_INTO_DEBUGGER(); \ if(checkIfShouldThrow(at)) \ throwException(); \ } \ return !failed; \ } \ } while(false) #define DOCTEST_ASSERT_IN_TESTS(decomp) \ ResultBuilder rb(at, file, line, expr); \ rb.m_failed = failed; \ if(rb.m_failed || getContextOptions()->success) \ rb.m_decomp = decomp; \ if(rb.log()) \ DOCTEST_BREAK_INTO_DEBUGGER(); \ if(rb.m_failed && checkIfShouldThrow(at)) \ throwException() template <int comparison, typename L, typename R> DOCTEST_NOINLINE bool binary_assert(assertType::Enum at, const char* file, int line, const char* expr, const DOCTEST_REF_WRAP(L) lhs, const DOCTEST_REF_WRAP(R) rhs) { bool failed = !RelationalComparator<comparison, L, R>()(lhs, rhs); // ################################################################################### // IF THE DEBUGGER BREAKS HERE - GO 1 LEVEL UP IN THE CALLSTACK FOR THE FAILING ASSERT // THIS IS THE EFFECT OF HAVING 'DOCTEST_CONFIG_SUPER_FAST_ASSERTS' DEFINED // ################################################################################### DOCTEST_ASSERT_OUT_OF_TESTS(stringifyBinaryExpr(lhs, ", ", rhs)); DOCTEST_ASSERT_IN_TESTS(stringifyBinaryExpr(lhs, ", ", rhs)); return !failed; } template <typename L> DOCTEST_NOINLINE bool unary_assert(assertType::Enum at, const char* file, int line, const char* expr, const DOCTEST_REF_WRAP(L) val) { bool failed = !val; if(at & assertType::is_false) //!OCLINT bitwise operator in conditional failed = !failed; // ################################################################################### // IF THE DEBUGGER BREAKS HERE - GO 1 LEVEL UP IN THE CALLSTACK FOR THE FAILING ASSERT // THIS IS THE EFFECT OF HAVING 'DOCTEST_CONFIG_SUPER_FAST_ASSERTS' DEFINED // ################################################################################### DOCTEST_ASSERT_OUT_OF_TESTS((DOCTEST_STRINGIFY(val))); DOCTEST_ASSERT_IN_TESTS((DOCTEST_STRINGIFY(val))); return !failed; } struct DOCTEST_INTERFACE IExceptionTranslator { DOCTEST_DECLARE_INTERFACE(IExceptionTranslator) virtual bool translate(String&) const = 0; }; template <typename T> class ExceptionTranslator : public IExceptionTranslator //!OCLINT destructor of virtual class { public: explicit ExceptionTranslator(String (*translateFunction)(T)) : m_translateFunction(translateFunction) {} bool translate(String& res) const override { #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS try { throw; // lgtm [cpp/rethrow-no-exception] // cppcheck-suppress catchExceptionByValue } catch(const T& ex) { res = m_translateFunction(ex); //!OCLINT parameter reassignment return true; } catch(...) {} //!OCLINT - empty catch statement #endif // DOCTEST_CONFIG_NO_EXCEPTIONS static_cast<void>(res); // to silence -Wunused-parameter return false; } private: String (*m_translateFunction)(T); }; DOCTEST_INTERFACE void registerExceptionTranslatorImpl(const IExceptionTranslator* et); // ContextScope base class used to allow implementing methods of ContextScope // that don't depend on the template parameter in doctest.cpp. struct DOCTEST_INTERFACE ContextScopeBase : public IContextScope { ContextScopeBase(const ContextScopeBase&) = delete; ContextScopeBase& operator=(const ContextScopeBase&) = delete; ContextScopeBase& operator=(ContextScopeBase&&) = delete; ~ContextScopeBase() override = default; protected: ContextScopeBase(); ContextScopeBase(ContextScopeBase&& other) noexcept; void destroy(); bool need_to_destroy{true}; }; template <typename L> class ContextScope : public ContextScopeBase { L lambda_; public: explicit ContextScope(const L &lambda) : lambda_(lambda) {} explicit ContextScope(L&& lambda) : lambda_(static_cast<L&&>(lambda)) { } ContextScope(const ContextScope&) = delete; ContextScope(ContextScope&&) noexcept = default; ContextScope& operator=(const ContextScope&) = delete; ContextScope& operator=(ContextScope&&) = delete; void stringify(std::ostream* s) const override { lambda_(s); } ~ContextScope() override { if (need_to_destroy) { destroy(); } } }; struct DOCTEST_INTERFACE MessageBuilder : public MessageData { std::ostream* m_stream; bool logged = false; MessageBuilder(const char* file, int line, assertType::Enum severity); MessageBuilder(const MessageBuilder&) = delete; MessageBuilder(MessageBuilder&&) = delete; MessageBuilder& operator=(const MessageBuilder&) = delete; MessageBuilder& operator=(MessageBuilder&&) = delete; ~MessageBuilder(); // the preferred way of chaining parameters for stringification DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4866) template <typename T> MessageBuilder& operator,(const T& in) { *m_stream << (DOCTEST_STRINGIFY(in)); return *this; } DOCTEST_MSVC_SUPPRESS_WARNING_POP // kept here just for backwards-compatibility - the comma operator should be preferred now template <typename T> MessageBuilder& operator<<(const T& in) { return this->operator,(in); } // the `,` operator has the lowest operator precedence - if `<<` is used by the user then // the `,` operator will be called last which is not what we want and thus the `*` operator // is used first (has higher operator precedence compared to `<<`) so that we guarantee that // an operator of the MessageBuilder class is called first before the rest of the parameters template <typename T> MessageBuilder& operator*(const T& in) { return this->operator,(in); } bool log(); void react(); }; template <typename L> ContextScope<L> MakeContextScope(const L &lambda) { return ContextScope<L>(lambda); } } // namespace detail #define DOCTEST_DEFINE_DECORATOR(name, type, def) \ struct name \ { \ type data; \ name(type in = def) \ : data(in) {} \ void fill(detail::TestCase& state) const { state.DOCTEST_CAT(m_, name) = data; } \ void fill(detail::TestSuite& state) const { state.DOCTEST_CAT(m_, name) = data; } \ } DOCTEST_DEFINE_DECORATOR(test_suite, const char*, ""); DOCTEST_DEFINE_DECORATOR(description, const char*, ""); DOCTEST_DEFINE_DECORATOR(skip, bool, true); DOCTEST_DEFINE_DECORATOR(no_breaks, bool, true); DOCTEST_DEFINE_DECORATOR(no_output, bool, true); DOCTEST_DEFINE_DECORATOR(timeout, double, 0); DOCTEST_DEFINE_DECORATOR(may_fail, bool, true); DOCTEST_DEFINE_DECORATOR(should_fail, bool, true); DOCTEST_DEFINE_DECORATOR(expected_failures, int, 0); template <typename T> int registerExceptionTranslator(String (*translateFunction)(T)) { DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wexit-time-destructors") static detail::ExceptionTranslator<T> exceptionTranslator(translateFunction); DOCTEST_CLANG_SUPPRESS_WARNING_POP detail::registerExceptionTranslatorImpl(&exceptionTranslator); return 0; } } // namespace doctest // in a separate namespace outside of doctest because the DOCTEST_TEST_SUITE macro // introduces an anonymous namespace in which getCurrentTestSuite gets overridden namespace doctest_detail_test_suite_ns { DOCTEST_INTERFACE doctest::detail::TestSuite& getCurrentTestSuite(); } // namespace doctest_detail_test_suite_ns namespace doctest { #else // DOCTEST_CONFIG_DISABLE template <typename T> int registerExceptionTranslator(String (*)(T)) { return 0; } #endif // DOCTEST_CONFIG_DISABLE namespace detail { using assert_handler = void (*)(const AssertData&); struct ContextState; } // namespace detail class DOCTEST_INTERFACE Context { detail::ContextState* p; void parseArgs(int argc, const char* const* argv, bool withDefaults = false); public: explicit Context(int argc = 0, const char* const* argv = nullptr); Context(const Context&) = delete; Context(Context&&) = delete; Context& operator=(const Context&) = delete; Context& operator=(Context&&) = delete; ~Context(); // NOLINT(performance-trivially-destructible) void applyCommandLine(int argc, const char* const* argv); void addFilter(const char* filter, const char* value); void clearFilters(); void setOption(const char* option, bool value); void setOption(const char* option, int value); void setOption(const char* option, const char* value); bool shouldExit(); void setAsDefaultForAssertsOutOfTestCases(); void setAssertHandler(detail::assert_handler ah); void setCout(std::ostream* out); int run(); }; namespace TestCaseFailureReason { enum Enum { None = 0, AssertFailure = 1, // an assertion has failed in the test case Exception = 2, // test case threw an exception Crash = 4, // a crash... TooManyFailedAsserts = 8, // the abort-after option Timeout = 16, // see the timeout decorator ShouldHaveFailedButDidnt = 32, // see the should_fail decorator ShouldHaveFailedAndDid = 64, // see the should_fail decorator DidntFailExactlyNumTimes = 128, // see the expected_failures decorator FailedExactlyNumTimes = 256, // see the expected_failures decorator CouldHaveFailedAndDid = 512 // see the may_fail decorator }; } // namespace TestCaseFailureReason struct DOCTEST_INTERFACE CurrentTestCaseStats { int numAssertsCurrentTest; int numAssertsFailedCurrentTest; double seconds; int failure_flags; // use TestCaseFailureReason::Enum bool testCaseSuccess; }; struct DOCTEST_INTERFACE TestCaseException { String error_string; bool is_crash; }; struct DOCTEST_INTERFACE TestRunStats { unsigned numTestCases; unsigned numTestCasesPassingFilters; unsigned numTestSuitesPassingFilters; unsigned numTestCasesFailed; int numAsserts; int numAssertsFailed; }; struct QueryData { const TestRunStats* run_stats = nullptr; const TestCaseData** data = nullptr; unsigned num_data = 0; }; struct DOCTEST_INTERFACE IReporter { // The constructor has to accept "const ContextOptions&" as a single argument // which has most of the options for the run + a pointer to the stdout stream // Reporter(const ContextOptions& in) // called when a query should be reported (listing test cases, printing the version, etc.) virtual void report_query(const QueryData&) = 0; // called when the whole test run starts virtual void test_run_start() = 0; // called when the whole test run ends (caching a pointer to the input doesn't make sense here) virtual void test_run_end(const TestRunStats&) = 0; // called when a test case is started (safe to cache a pointer to the input) virtual void test_case_start(const TestCaseData&) = 0; // called when a test case is reentered because of unfinished subcases (safe to cache a pointer to the input) virtual void test_case_reenter(const TestCaseData&) = 0; // called when a test case has ended virtual void test_case_end(const CurrentTestCaseStats&) = 0; // called when an exception is thrown from the test case (or it crashes) virtual void test_case_exception(const TestCaseException&) = 0; // called whenever a subcase is entered (don't cache pointers to the input) virtual void subcase_start(const SubcaseSignature&) = 0; // called whenever a subcase is exited (don't cache pointers to the input) virtual void subcase_end() = 0; // called for each assert (don't cache pointers to the input) virtual void log_assert(const AssertData&) = 0; // called for each message (don't cache pointers to the input) virtual void log_message(const MessageData&) = 0; // called when a test case is skipped either because it doesn't pass the filters, has a skip decorator // or isn't in the execution range (between first and last) (safe to cache a pointer to the input) virtual void test_case_skipped(const TestCaseData&) = 0; DOCTEST_DECLARE_INTERFACE(IReporter) // can obtain all currently active contexts and stringify them if one wishes to do so static int get_num_active_contexts(); static const IContextScope* const* get_active_contexts(); // can iterate through contexts which have been stringified automatically in their destructors when an exception has been thrown static int get_num_stringified_contexts(); static const String* get_stringified_contexts(); }; namespace detail { using reporterCreatorFunc = IReporter* (*)(const ContextOptions&); DOCTEST_INTERFACE void registerReporterImpl(const char* name, int prio, reporterCreatorFunc c, bool isReporter); template <typename Reporter> IReporter* reporterCreator(const ContextOptions& o) { return new Reporter(o); } } // namespace detail template <typename Reporter> int registerReporter(const char* name, int priority, bool isReporter) { detail::registerReporterImpl(name, priority, detail::reporterCreator<Reporter>, isReporter); return 0; } } // namespace doctest #ifdef DOCTEST_CONFIG_ASSERTS_RETURN_VALUES #define DOCTEST_FUNC_EMPTY [] { return false; }() #else #define DOCTEST_FUNC_EMPTY (void)0 #endif // if registering is not disabled #ifndef DOCTEST_CONFIG_DISABLE #ifdef DOCTEST_CONFIG_ASSERTS_RETURN_VALUES #define DOCTEST_FUNC_SCOPE_BEGIN [&] #define DOCTEST_FUNC_SCOPE_END () #define DOCTEST_FUNC_SCOPE_RET(v) return v #else #define DOCTEST_FUNC_SCOPE_BEGIN do #define DOCTEST_FUNC_SCOPE_END while(false) #define DOCTEST_FUNC_SCOPE_RET(v) (void)0 #endif // common code in asserts - for convenience #define DOCTEST_ASSERT_LOG_REACT_RETURN(b) \ if(b.log()) DOCTEST_BREAK_INTO_DEBUGGER(); \ b.react(); \ DOCTEST_FUNC_SCOPE_RET(!b.m_failed) #ifdef DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS #define DOCTEST_WRAP_IN_TRY(x) x; #else // DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS #define DOCTEST_WRAP_IN_TRY(x) \ try { \ x; \ } catch(...) { DOCTEST_RB.translateException(); } #endif // DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS #ifdef DOCTEST_CONFIG_VOID_CAST_EXPRESSIONS #define DOCTEST_CAST_TO_VOID(...) \ DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wuseless-cast") \ static_cast<void>(__VA_ARGS__); \ DOCTEST_GCC_SUPPRESS_WARNING_POP #else // DOCTEST_CONFIG_VOID_CAST_EXPRESSIONS #define DOCTEST_CAST_TO_VOID(...) __VA_ARGS__; #endif // DOCTEST_CONFIG_VOID_CAST_EXPRESSIONS // registers the test by initializing a dummy var with a function #define DOCTEST_REGISTER_FUNCTION(global_prefix, f, decorators) \ global_prefix DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_VAR_), /* NOLINT */ \ doctest::detail::regTest( \ doctest::detail::TestCase( \ f, __FILE__, __LINE__, \ doctest_detail_test_suite_ns::getCurrentTestSuite()) * \ decorators)) #define DOCTEST_IMPLEMENT_FIXTURE(der, base, func, decorators) \ namespace { /* NOLINT */ \ struct der : public base \ { \ void f(); \ }; \ static DOCTEST_INLINE_NOINLINE void func() { \ der v; \ v.f(); \ } \ DOCTEST_REGISTER_FUNCTION(DOCTEST_EMPTY, func, decorators) \ } \ DOCTEST_INLINE_NOINLINE void der::f() // NOLINT(misc-definitions-in-headers) #define DOCTEST_CREATE_AND_REGISTER_FUNCTION(f, decorators) \ static void f(); \ DOCTEST_REGISTER_FUNCTION(DOCTEST_EMPTY, f, decorators) \ static void f() #define DOCTEST_CREATE_AND_REGISTER_FUNCTION_IN_CLASS(f, proxy, decorators) \ static doctest::detail::funcType proxy() { return f; } \ DOCTEST_REGISTER_FUNCTION(inline, proxy(), decorators) \ static void f() // for registering tests #define DOCTEST_TEST_CASE(decorators) \ DOCTEST_CREATE_AND_REGISTER_FUNCTION(DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), decorators) // for registering tests in classes - requires C++17 for inline variables! #if DOCTEST_CPLUSPLUS >= 201703L #define DOCTEST_TEST_CASE_CLASS(decorators) \ DOCTEST_CREATE_AND_REGISTER_FUNCTION_IN_CLASS(DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), \ DOCTEST_ANONYMOUS(DOCTEST_ANON_PROXY_), \ decorators) #else // DOCTEST_TEST_CASE_CLASS #define DOCTEST_TEST_CASE_CLASS(...) \ TEST_CASES_CAN_BE_REGISTERED_IN_CLASSES_ONLY_IN_CPP17_MODE_OR_WITH_VS_2017_OR_NEWER #endif // DOCTEST_TEST_CASE_CLASS // for registering tests with a fixture #define DOCTEST_TEST_CASE_FIXTURE(c, decorators) \ DOCTEST_IMPLEMENT_FIXTURE(DOCTEST_ANONYMOUS(DOCTEST_ANON_CLASS_), c, \ DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), decorators) // for converting types to strings without the <typeinfo> header and demangling #define DOCTEST_TYPE_TO_STRING_AS(str, ...) \ namespace doctest { \ template <> \ inline String toString<__VA_ARGS__>() { \ return str; \ } \ } \ static_assert(true, "") #define DOCTEST_TYPE_TO_STRING(...) DOCTEST_TYPE_TO_STRING_AS(#__VA_ARGS__, __VA_ARGS__) #define DOCTEST_TEST_CASE_TEMPLATE_DEFINE_IMPL(dec, T, iter, func) \ template <typename T> \ static void func(); \ namespace { /* NOLINT */ \ template <typename Tuple> \ struct iter; \ template <typename Type, typename... Rest> \ struct iter<std::tuple<Type, Rest...>> \ { \ iter(const char* file, unsigned line, int index) { \ doctest::detail::regTest(doctest::detail::TestCase(func<Type>, file, line, \ doctest_detail_test_suite_ns::getCurrentTestSuite(), \ doctest::toString<Type>(), \ int(line) * 1000 + index) \ * dec); \ iter<std::tuple<Rest...>>(file, line, index + 1); \ } \ }; \ template <> \ struct iter<std::tuple<>> \ { \ iter(const char*, unsigned, int) {} \ }; \ } \ template <typename T> \ static void func() #define DOCTEST_TEST_CASE_TEMPLATE_DEFINE(dec, T, id) \ DOCTEST_TEST_CASE_TEMPLATE_DEFINE_IMPL(dec, T, DOCTEST_CAT(id, ITERATOR), \ DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_)) #define DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE_IMPL(id, anon, ...) \ DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_CAT(anon, DUMMY), /* NOLINT(cert-err58-cpp, fuchsia-statically-constructed-objects) */ \ doctest::detail::instantiationHelper( \ DOCTEST_CAT(id, ITERATOR)<__VA_ARGS__>(__FILE__, __LINE__, 0))) #define DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id, ...) \ DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE_IMPL(id, DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_), std::tuple<__VA_ARGS__>) \ static_assert(true, "") #define DOCTEST_TEST_CASE_TEMPLATE_APPLY(id, ...) \ DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE_IMPL(id, DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_), __VA_ARGS__) \ static_assert(true, "") #define DOCTEST_TEST_CASE_TEMPLATE_IMPL(dec, T, anon, ...) \ DOCTEST_TEST_CASE_TEMPLATE_DEFINE_IMPL(dec, T, DOCTEST_CAT(anon, ITERATOR), anon); \ DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE_IMPL(anon, anon, std::tuple<__VA_ARGS__>) \ template <typename T> \ static void anon() #define DOCTEST_TEST_CASE_TEMPLATE(dec, T, ...) \ DOCTEST_TEST_CASE_TEMPLATE_IMPL(dec, T, DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_), __VA_ARGS__) // for subcases #define DOCTEST_SUBCASE(name) \ if(const doctest::detail::Subcase & DOCTEST_ANONYMOUS(DOCTEST_ANON_SUBCASE_) DOCTEST_UNUSED = \ doctest::detail::Subcase(name, __FILE__, __LINE__)) // for grouping tests in test suites by using code blocks #define DOCTEST_TEST_SUITE_IMPL(decorators, ns_name) \ namespace ns_name { namespace doctest_detail_test_suite_ns { \ static DOCTEST_NOINLINE doctest::detail::TestSuite& getCurrentTestSuite() noexcept { \ DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4640) \ DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wexit-time-destructors") \ DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wmissing-field-initializers") \ static doctest::detail::TestSuite data{}; \ static bool inited = false; \ DOCTEST_MSVC_SUPPRESS_WARNING_POP \ DOCTEST_CLANG_SUPPRESS_WARNING_POP \ DOCTEST_GCC_SUPPRESS_WARNING_POP \ if(!inited) { \ data* decorators; \ inited = true; \ } \ return data; \ } \ } \ } \ namespace ns_name #define DOCTEST_TEST_SUITE(decorators) \ DOCTEST_TEST_SUITE_IMPL(decorators, DOCTEST_ANONYMOUS(DOCTEST_ANON_SUITE_)) // for starting a testsuite block #define DOCTEST_TEST_SUITE_BEGIN(decorators) \ DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_VAR_), /* NOLINT(cert-err58-cpp) */ \ doctest::detail::setTestSuite(doctest::detail::TestSuite() * decorators)) \ static_assert(true, "") // for ending a testsuite block #define DOCTEST_TEST_SUITE_END \ DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_VAR_), /* NOLINT(cert-err58-cpp) */ \ doctest::detail::setTestSuite(doctest::detail::TestSuite() * "")) \ using DOCTEST_ANONYMOUS(DOCTEST_ANON_FOR_SEMICOLON_) = int // for registering exception translators #define DOCTEST_REGISTER_EXCEPTION_TRANSLATOR_IMPL(translatorName, signature) \ inline doctest::String translatorName(signature); \ DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_TRANSLATOR_), /* NOLINT(cert-err58-cpp) */ \ doctest::registerExceptionTranslator(translatorName)) \ doctest::String translatorName(signature) #define DOCTEST_REGISTER_EXCEPTION_TRANSLATOR(signature) \ DOCTEST_REGISTER_EXCEPTION_TRANSLATOR_IMPL(DOCTEST_ANONYMOUS(DOCTEST_ANON_TRANSLATOR_), \ signature) // for registering reporters #define DOCTEST_REGISTER_REPORTER(name, priority, reporter) \ DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_REPORTER_), /* NOLINT(cert-err58-cpp) */ \ doctest::registerReporter<reporter>(name, priority, true)) \ static_assert(true, "") // for registering listeners #define DOCTEST_REGISTER_LISTENER(name, priority, reporter) \ DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(DOCTEST_ANON_REPORTER_), /* NOLINT(cert-err58-cpp) */ \ doctest::registerReporter<reporter>(name, priority, false)) \ static_assert(true, "") // clang-format off // for logging - disabling formatting because it's important to have these on 2 separate lines - see PR #557 #define DOCTEST_INFO(...) \ DOCTEST_INFO_IMPL(DOCTEST_ANONYMOUS(DOCTEST_CAPTURE_), \ DOCTEST_ANONYMOUS(DOCTEST_CAPTURE_OTHER_), \ __VA_ARGS__) // clang-format on #define DOCTEST_INFO_IMPL(mb_name, s_name, ...) \ auto DOCTEST_ANONYMOUS(DOCTEST_CAPTURE_) = doctest::detail::MakeContextScope( \ [&](std::ostream* s_name) { \ doctest::detail::MessageBuilder mb_name(__FILE__, __LINE__, doctest::assertType::is_warn); \ mb_name.m_stream = s_name; \ mb_name * __VA_ARGS__; \ }) #define DOCTEST_CAPTURE(x) DOCTEST_INFO(#x " := ", x) #define DOCTEST_ADD_AT_IMPL(type, file, line, mb, ...) \ DOCTEST_FUNC_SCOPE_BEGIN { \ doctest::detail::MessageBuilder mb(file, line, doctest::assertType::type); \ mb * __VA_ARGS__; \ if(mb.log()) \ DOCTEST_BREAK_INTO_DEBUGGER(); \ mb.react(); \ } DOCTEST_FUNC_SCOPE_END // clang-format off #define DOCTEST_ADD_MESSAGE_AT(file, line, ...) DOCTEST_ADD_AT_IMPL(is_warn, file, line, DOCTEST_ANONYMOUS(DOCTEST_MESSAGE_), __VA_ARGS__) #define DOCTEST_ADD_FAIL_CHECK_AT(file, line, ...) DOCTEST_ADD_AT_IMPL(is_check, file, line, DOCTEST_ANONYMOUS(DOCTEST_MESSAGE_), __VA_ARGS__) #define DOCTEST_ADD_FAIL_AT(file, line, ...) DOCTEST_ADD_AT_IMPL(is_require, file, line, DOCTEST_ANONYMOUS(DOCTEST_MESSAGE_), __VA_ARGS__) // clang-format on #define DOCTEST_MESSAGE(...) DOCTEST_ADD_MESSAGE_AT(__FILE__, __LINE__, __VA_ARGS__) #define DOCTEST_FAIL_CHECK(...) DOCTEST_ADD_FAIL_CHECK_AT(__FILE__, __LINE__, __VA_ARGS__) #define DOCTEST_FAIL(...) DOCTEST_ADD_FAIL_AT(__FILE__, __LINE__, __VA_ARGS__) #define DOCTEST_TO_LVALUE(...) __VA_ARGS__ // Not removed to keep backwards compatibility. #ifndef DOCTEST_CONFIG_SUPER_FAST_ASSERTS #define DOCTEST_ASSERT_IMPLEMENT_2(assert_type, ...) \ DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Woverloaded-shift-op-parentheses") \ /* NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) */ \ doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ __LINE__, #__VA_ARGS__); \ DOCTEST_WRAP_IN_TRY(DOCTEST_RB.setResult( \ doctest::detail::ExpressionDecomposer(doctest::assertType::assert_type) \ << __VA_ARGS__)) /* NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) */ \ DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB) \ DOCTEST_CLANG_SUPPRESS_WARNING_POP #define DOCTEST_ASSERT_IMPLEMENT_1(assert_type, ...) \ DOCTEST_FUNC_SCOPE_BEGIN { \ DOCTEST_ASSERT_IMPLEMENT_2(assert_type, __VA_ARGS__); \ } DOCTEST_FUNC_SCOPE_END // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks) #define DOCTEST_BINARY_ASSERT(assert_type, comp, ...) \ DOCTEST_FUNC_SCOPE_BEGIN { \ doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ __LINE__, #__VA_ARGS__); \ DOCTEST_WRAP_IN_TRY( \ DOCTEST_RB.binary_assert<doctest::detail::binaryAssertComparison::comp>( \ __VA_ARGS__)) \ DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ } DOCTEST_FUNC_SCOPE_END #define DOCTEST_UNARY_ASSERT(assert_type, ...) \ DOCTEST_FUNC_SCOPE_BEGIN { \ doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ __LINE__, #__VA_ARGS__); \ DOCTEST_WRAP_IN_TRY(DOCTEST_RB.unary_assert(__VA_ARGS__)) \ DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ } DOCTEST_FUNC_SCOPE_END #else // DOCTEST_CONFIG_SUPER_FAST_ASSERTS // necessary for <ASSERT>_MESSAGE #define DOCTEST_ASSERT_IMPLEMENT_2 DOCTEST_ASSERT_IMPLEMENT_1 #define DOCTEST_ASSERT_IMPLEMENT_1(assert_type, ...) \ DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Woverloaded-shift-op-parentheses") \ doctest::detail::decomp_assert( \ doctest::assertType::assert_type, __FILE__, __LINE__, #__VA_ARGS__, \ doctest::detail::ExpressionDecomposer(doctest::assertType::assert_type) \ << __VA_ARGS__) DOCTEST_CLANG_SUPPRESS_WARNING_POP #define DOCTEST_BINARY_ASSERT(assert_type, comparison, ...) \ doctest::detail::binary_assert<doctest::detail::binaryAssertComparison::comparison>( \ doctest::assertType::assert_type, __FILE__, __LINE__, #__VA_ARGS__, __VA_ARGS__) #define DOCTEST_UNARY_ASSERT(assert_type, ...) \ doctest::detail::unary_assert(doctest::assertType::assert_type, __FILE__, __LINE__, \ #__VA_ARGS__, __VA_ARGS__) #endif // DOCTEST_CONFIG_SUPER_FAST_ASSERTS #define DOCTEST_WARN(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_WARN, __VA_ARGS__) #define DOCTEST_CHECK(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_CHECK, __VA_ARGS__) #define DOCTEST_REQUIRE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_REQUIRE, __VA_ARGS__) #define DOCTEST_WARN_FALSE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_WARN_FALSE, __VA_ARGS__) #define DOCTEST_CHECK_FALSE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_CHECK_FALSE, __VA_ARGS__) #define DOCTEST_REQUIRE_FALSE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_REQUIRE_FALSE, __VA_ARGS__) // clang-format off #define DOCTEST_WARN_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_WARN, cond); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_CHECK_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_CHECK, cond); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_REQUIRE_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_REQUIRE, cond); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_WARN_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_WARN_FALSE, cond); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_CHECK_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_CHECK_FALSE, cond); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_REQUIRE_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_ASSERT_IMPLEMENT_2(DT_REQUIRE_FALSE, cond); } DOCTEST_FUNC_SCOPE_END // clang-format on #define DOCTEST_WARN_EQ(...) DOCTEST_BINARY_ASSERT(DT_WARN_EQ, eq, __VA_ARGS__) #define DOCTEST_CHECK_EQ(...) DOCTEST_BINARY_ASSERT(DT_CHECK_EQ, eq, __VA_ARGS__) #define DOCTEST_REQUIRE_EQ(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_EQ, eq, __VA_ARGS__) #define DOCTEST_WARN_NE(...) DOCTEST_BINARY_ASSERT(DT_WARN_NE, ne, __VA_ARGS__) #define DOCTEST_CHECK_NE(...) DOCTEST_BINARY_ASSERT(DT_CHECK_NE, ne, __VA_ARGS__) #define DOCTEST_REQUIRE_NE(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_NE, ne, __VA_ARGS__) #define DOCTEST_WARN_GT(...) DOCTEST_BINARY_ASSERT(DT_WARN_GT, gt, __VA_ARGS__) #define DOCTEST_CHECK_GT(...) DOCTEST_BINARY_ASSERT(DT_CHECK_GT, gt, __VA_ARGS__) #define DOCTEST_REQUIRE_GT(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_GT, gt, __VA_ARGS__) #define DOCTEST_WARN_LT(...) DOCTEST_BINARY_ASSERT(DT_WARN_LT, lt, __VA_ARGS__) #define DOCTEST_CHECK_LT(...) DOCTEST_BINARY_ASSERT(DT_CHECK_LT, lt, __VA_ARGS__) #define DOCTEST_REQUIRE_LT(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_LT, lt, __VA_ARGS__) #define DOCTEST_WARN_GE(...) DOCTEST_BINARY_ASSERT(DT_WARN_GE, ge, __VA_ARGS__) #define DOCTEST_CHECK_GE(...) DOCTEST_BINARY_ASSERT(DT_CHECK_GE, ge, __VA_ARGS__) #define DOCTEST_REQUIRE_GE(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_GE, ge, __VA_ARGS__) #define DOCTEST_WARN_LE(...) DOCTEST_BINARY_ASSERT(DT_WARN_LE, le, __VA_ARGS__) #define DOCTEST_CHECK_LE(...) DOCTEST_BINARY_ASSERT(DT_CHECK_LE, le, __VA_ARGS__) #define DOCTEST_REQUIRE_LE(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_LE, le, __VA_ARGS__) #define DOCTEST_WARN_UNARY(...) DOCTEST_UNARY_ASSERT(DT_WARN_UNARY, __VA_ARGS__) #define DOCTEST_CHECK_UNARY(...) DOCTEST_UNARY_ASSERT(DT_CHECK_UNARY, __VA_ARGS__) #define DOCTEST_REQUIRE_UNARY(...) DOCTEST_UNARY_ASSERT(DT_REQUIRE_UNARY, __VA_ARGS__) #define DOCTEST_WARN_UNARY_FALSE(...) DOCTEST_UNARY_ASSERT(DT_WARN_UNARY_FALSE, __VA_ARGS__) #define DOCTEST_CHECK_UNARY_FALSE(...) DOCTEST_UNARY_ASSERT(DT_CHECK_UNARY_FALSE, __VA_ARGS__) #define DOCTEST_REQUIRE_UNARY_FALSE(...) DOCTEST_UNARY_ASSERT(DT_REQUIRE_UNARY_FALSE, __VA_ARGS__) #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS #define DOCTEST_ASSERT_THROWS_AS(expr, assert_type, message, ...) \ DOCTEST_FUNC_SCOPE_BEGIN { \ if(!doctest::getContextOptions()->no_throw) { \ doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ __LINE__, #expr, #__VA_ARGS__, message); \ try { \ DOCTEST_CAST_TO_VOID(expr) \ } catch(const typename doctest::detail::types::remove_const< \ typename doctest::detail::types::remove_reference<__VA_ARGS__>::type>::type&) {\ DOCTEST_RB.translateException(); \ DOCTEST_RB.m_threw_as = true; \ } catch(...) { DOCTEST_RB.translateException(); } \ DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ } else { /* NOLINT(*-else-after-return) */ \ DOCTEST_FUNC_SCOPE_RET(false); \ } \ } DOCTEST_FUNC_SCOPE_END #define DOCTEST_ASSERT_THROWS_WITH(expr, expr_str, assert_type, ...) \ DOCTEST_FUNC_SCOPE_BEGIN { \ if(!doctest::getContextOptions()->no_throw) { \ doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ __LINE__, expr_str, "", __VA_ARGS__); \ try { \ DOCTEST_CAST_TO_VOID(expr) \ } catch(...) { DOCTEST_RB.translateException(); } \ DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ } else { /* NOLINT(*-else-after-return) */ \ DOCTEST_FUNC_SCOPE_RET(false); \ } \ } DOCTEST_FUNC_SCOPE_END #define DOCTEST_ASSERT_NOTHROW(assert_type, ...) \ DOCTEST_FUNC_SCOPE_BEGIN { \ doctest::detail::ResultBuilder DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ __LINE__, #__VA_ARGS__); \ try { \ DOCTEST_CAST_TO_VOID(__VA_ARGS__) \ } catch(...) { DOCTEST_RB.translateException(); } \ DOCTEST_ASSERT_LOG_REACT_RETURN(DOCTEST_RB); \ } DOCTEST_FUNC_SCOPE_END // clang-format off #define DOCTEST_WARN_THROWS(...) DOCTEST_ASSERT_THROWS_WITH((__VA_ARGS__), #__VA_ARGS__, DT_WARN_THROWS, "") #define DOCTEST_CHECK_THROWS(...) DOCTEST_ASSERT_THROWS_WITH((__VA_ARGS__), #__VA_ARGS__, DT_CHECK_THROWS, "") #define DOCTEST_REQUIRE_THROWS(...) DOCTEST_ASSERT_THROWS_WITH((__VA_ARGS__), #__VA_ARGS__, DT_REQUIRE_THROWS, "") #define DOCTEST_WARN_THROWS_AS(expr, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_WARN_THROWS_AS, "", __VA_ARGS__) #define DOCTEST_CHECK_THROWS_AS(expr, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_CHECK_THROWS_AS, "", __VA_ARGS__) #define DOCTEST_REQUIRE_THROWS_AS(expr, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_REQUIRE_THROWS_AS, "", __VA_ARGS__) #define DOCTEST_WARN_THROWS_WITH(expr, ...) DOCTEST_ASSERT_THROWS_WITH(expr, #expr, DT_WARN_THROWS_WITH, __VA_ARGS__) #define DOCTEST_CHECK_THROWS_WITH(expr, ...) DOCTEST_ASSERT_THROWS_WITH(expr, #expr, DT_CHECK_THROWS_WITH, __VA_ARGS__) #define DOCTEST_REQUIRE_THROWS_WITH(expr, ...) DOCTEST_ASSERT_THROWS_WITH(expr, #expr, DT_REQUIRE_THROWS_WITH, __VA_ARGS__) #define DOCTEST_WARN_THROWS_WITH_AS(expr, message, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_WARN_THROWS_WITH_AS, message, __VA_ARGS__) #define DOCTEST_CHECK_THROWS_WITH_AS(expr, message, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_CHECK_THROWS_WITH_AS, message, __VA_ARGS__) #define DOCTEST_REQUIRE_THROWS_WITH_AS(expr, message, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_REQUIRE_THROWS_WITH_AS, message, __VA_ARGS__) #define DOCTEST_WARN_NOTHROW(...) DOCTEST_ASSERT_NOTHROW(DT_WARN_NOTHROW, __VA_ARGS__) #define DOCTEST_CHECK_NOTHROW(...) DOCTEST_ASSERT_NOTHROW(DT_CHECK_NOTHROW, __VA_ARGS__) #define DOCTEST_REQUIRE_NOTHROW(...) DOCTEST_ASSERT_NOTHROW(DT_REQUIRE_NOTHROW, __VA_ARGS__) #define DOCTEST_WARN_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_THROWS(expr); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_CHECK_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_THROWS(expr); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_THROWS(expr); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_THROWS_AS(expr, ex); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_THROWS_AS(expr, ex); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_THROWS_AS(expr, ex); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_THROWS_WITH(expr, with); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_THROWS_WITH(expr, with); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_THROWS_WITH(expr, with); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_THROWS_WITH_AS(expr, with, ex); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_THROWS_WITH_AS(expr, with, ex); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, ex); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_WARN_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_WARN_NOTHROW(expr); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_CHECK_NOTHROW(expr); } DOCTEST_FUNC_SCOPE_END #define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_SCOPE_BEGIN { DOCTEST_INFO(__VA_ARGS__); DOCTEST_REQUIRE_NOTHROW(expr); } DOCTEST_FUNC_SCOPE_END // clang-format on #endif // DOCTEST_CONFIG_NO_EXCEPTIONS // ================================================================================================= // == WHAT FOLLOWS IS VERSIONS OF THE MACROS THAT DO NOT DO ANY REGISTERING! == // == THIS CAN BE ENABLED BY DEFINING DOCTEST_CONFIG_DISABLE GLOBALLY! == // ================================================================================================= #else // DOCTEST_CONFIG_DISABLE #define DOCTEST_IMPLEMENT_FIXTURE(der, base, func, name) \ namespace /* NOLINT */ { \ template <typename DOCTEST_UNUSED_TEMPLATE_TYPE> \ struct der : public base \ { void f(); }; \ } \ template <typename DOCTEST_UNUSED_TEMPLATE_TYPE> \ inline void der<DOCTEST_UNUSED_TEMPLATE_TYPE>::f() #define DOCTEST_CREATE_AND_REGISTER_FUNCTION(f, name) \ template <typename DOCTEST_UNUSED_TEMPLATE_TYPE> \ static inline void f() // for registering tests #define DOCTEST_TEST_CASE(name) \ DOCTEST_CREATE_AND_REGISTER_FUNCTION(DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), name) // for registering tests in classes #define DOCTEST_TEST_CASE_CLASS(name) \ DOCTEST_CREATE_AND_REGISTER_FUNCTION(DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), name) // for registering tests with a fixture #define DOCTEST_TEST_CASE_FIXTURE(x, name) \ DOCTEST_IMPLEMENT_FIXTURE(DOCTEST_ANONYMOUS(DOCTEST_ANON_CLASS_), x, \ DOCTEST_ANONYMOUS(DOCTEST_ANON_FUNC_), name) // for converting types to strings without the <typeinfo> header and demangling #define DOCTEST_TYPE_TO_STRING_AS(str, ...) static_assert(true, "") #define DOCTEST_TYPE_TO_STRING(...) static_assert(true, "") // for typed tests #define DOCTEST_TEST_CASE_TEMPLATE(name, type, ...) \ template <typename type> \ inline void DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_)() #define DOCTEST_TEST_CASE_TEMPLATE_DEFINE(name, type, id) \ template <typename type> \ inline void DOCTEST_ANONYMOUS(DOCTEST_ANON_TMP_)() #define DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id, ...) static_assert(true, "") #define DOCTEST_TEST_CASE_TEMPLATE_APPLY(id, ...) static_assert(true, "") // for subcases #define DOCTEST_SUBCASE(name) // for a testsuite block #define DOCTEST_TEST_SUITE(name) namespace // NOLINT // for starting a testsuite block #define DOCTEST_TEST_SUITE_BEGIN(name) static_assert(true, "") // for ending a testsuite block #define DOCTEST_TEST_SUITE_END using DOCTEST_ANONYMOUS(DOCTEST_ANON_FOR_SEMICOLON_) = int #define DOCTEST_REGISTER_EXCEPTION_TRANSLATOR(signature) \ template <typename DOCTEST_UNUSED_TEMPLATE_TYPE> \ static inline doctest::String DOCTEST_ANONYMOUS(DOCTEST_ANON_TRANSLATOR_)(signature) #define DOCTEST_REGISTER_REPORTER(name, priority, reporter) #define DOCTEST_REGISTER_LISTENER(name, priority, reporter) #define DOCTEST_INFO(...) (static_cast<void>(0)) #define DOCTEST_CAPTURE(x) (static_cast<void>(0)) #define DOCTEST_ADD_MESSAGE_AT(file, line, ...) (static_cast<void>(0)) #define DOCTEST_ADD_FAIL_CHECK_AT(file, line, ...) (static_cast<void>(0)) #define DOCTEST_ADD_FAIL_AT(file, line, ...) (static_cast<void>(0)) #define DOCTEST_MESSAGE(...) (static_cast<void>(0)) #define DOCTEST_FAIL_CHECK(...) (static_cast<void>(0)) #define DOCTEST_FAIL(...) (static_cast<void>(0)) #if defined(DOCTEST_CONFIG_EVALUATE_ASSERTS_EVEN_WHEN_DISABLED) \ && defined(DOCTEST_CONFIG_ASSERTS_RETURN_VALUES) #define DOCTEST_WARN(...) [&] { return __VA_ARGS__; }() #define DOCTEST_CHECK(...) [&] { return __VA_ARGS__; }() #define DOCTEST_REQUIRE(...) [&] { return __VA_ARGS__; }() #define DOCTEST_WARN_FALSE(...) [&] { return !(__VA_ARGS__); }() #define DOCTEST_CHECK_FALSE(...) [&] { return !(__VA_ARGS__); }() #define DOCTEST_REQUIRE_FALSE(...) [&] { return !(__VA_ARGS__); }() #define DOCTEST_WARN_MESSAGE(cond, ...) [&] { return cond; }() #define DOCTEST_CHECK_MESSAGE(cond, ...) [&] { return cond; }() #define DOCTEST_REQUIRE_MESSAGE(cond, ...) [&] { return cond; }() #define DOCTEST_WARN_FALSE_MESSAGE(cond, ...) [&] { return !(cond); }() #define DOCTEST_CHECK_FALSE_MESSAGE(cond, ...) [&] { return !(cond); }() #define DOCTEST_REQUIRE_FALSE_MESSAGE(cond, ...) [&] { return !(cond); }() namespace doctest { namespace detail { #define DOCTEST_RELATIONAL_OP(name, op) \ template <typename L, typename R> \ bool name(const DOCTEST_REF_WRAP(L) lhs, const DOCTEST_REF_WRAP(R) rhs) { return lhs op rhs; } DOCTEST_RELATIONAL_OP(eq, ==) DOCTEST_RELATIONAL_OP(ne, !=) DOCTEST_RELATIONAL_OP(lt, <) DOCTEST_RELATIONAL_OP(gt, >) DOCTEST_RELATIONAL_OP(le, <=) DOCTEST_RELATIONAL_OP(ge, >=) } // namespace detail } // namespace doctest #define DOCTEST_WARN_EQ(...) [&] { return doctest::detail::eq(__VA_ARGS__); }() #define DOCTEST_CHECK_EQ(...) [&] { return doctest::detail::eq(__VA_ARGS__); }() #define DOCTEST_REQUIRE_EQ(...) [&] { return doctest::detail::eq(__VA_ARGS__); }() #define DOCTEST_WARN_NE(...) [&] { return doctest::detail::ne(__VA_ARGS__); }() #define DOCTEST_CHECK_NE(...) [&] { return doctest::detail::ne(__VA_ARGS__); }() #define DOCTEST_REQUIRE_NE(...) [&] { return doctest::detail::ne(__VA_ARGS__); }() #define DOCTEST_WARN_LT(...) [&] { return doctest::detail::lt(__VA_ARGS__); }() #define DOCTEST_CHECK_LT(...) [&] { return doctest::detail::lt(__VA_ARGS__); }() #define DOCTEST_REQUIRE_LT(...) [&] { return doctest::detail::lt(__VA_ARGS__); }() #define DOCTEST_WARN_GT(...) [&] { return doctest::detail::gt(__VA_ARGS__); }() #define DOCTEST_CHECK_GT(...) [&] { return doctest::detail::gt(__VA_ARGS__); }() #define DOCTEST_REQUIRE_GT(...) [&] { return doctest::detail::gt(__VA_ARGS__); }() #define DOCTEST_WARN_LE(...) [&] { return doctest::detail::le(__VA_ARGS__); }() #define DOCTEST_CHECK_LE(...) [&] { return doctest::detail::le(__VA_ARGS__); }() #define DOCTEST_REQUIRE_LE(...) [&] { return doctest::detail::le(__VA_ARGS__); }() #define DOCTEST_WARN_GE(...) [&] { return doctest::detail::ge(__VA_ARGS__); }() #define DOCTEST_CHECK_GE(...) [&] { return doctest::detail::ge(__VA_ARGS__); }() #define DOCTEST_REQUIRE_GE(...) [&] { return doctest::detail::ge(__VA_ARGS__); }() #define DOCTEST_WARN_UNARY(...) [&] { return __VA_ARGS__; }() #define DOCTEST_CHECK_UNARY(...) [&] { return __VA_ARGS__; }() #define DOCTEST_REQUIRE_UNARY(...) [&] { return __VA_ARGS__; }() #define DOCTEST_WARN_UNARY_FALSE(...) [&] { return !(__VA_ARGS__); }() #define DOCTEST_CHECK_UNARY_FALSE(...) [&] { return !(__VA_ARGS__); }() #define DOCTEST_REQUIRE_UNARY_FALSE(...) [&] { return !(__VA_ARGS__); }() #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS #define DOCTEST_WARN_THROWS_WITH(expr, with, ...) [] { static_assert(false, "Exception translation is not available when doctest is disabled."); return false; }() #define DOCTEST_CHECK_THROWS_WITH(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_REQUIRE_THROWS_WITH(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_WARN_THROWS_WITH_AS(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_CHECK_THROWS_WITH_AS(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH(,,) #define DOCTEST_WARN_THROWS(...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() #define DOCTEST_CHECK_THROWS(...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() #define DOCTEST_REQUIRE_THROWS(...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() #define DOCTEST_WARN_THROWS_AS(expr, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() #define DOCTEST_CHECK_THROWS_AS(expr, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() #define DOCTEST_REQUIRE_THROWS_AS(expr, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() #define DOCTEST_WARN_NOTHROW(...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() #define DOCTEST_CHECK_NOTHROW(...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() #define DOCTEST_REQUIRE_NOTHROW(...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() #define DOCTEST_WARN_THROWS_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() #define DOCTEST_CHECK_THROWS_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() #define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return false; } catch (...) { return true; } }() #define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() #define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() #define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) [&] { try { expr; } catch (__VA_ARGS__) { return true; } catch (...) { } return false; }() #define DOCTEST_WARN_NOTHROW_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() #define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() #define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, ...) [&] { try { __VA_ARGS__; return true; } catch (...) { return false; } }() #endif // DOCTEST_CONFIG_NO_EXCEPTIONS #else // DOCTEST_CONFIG_EVALUATE_ASSERTS_EVEN_WHEN_DISABLED #define DOCTEST_WARN(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_FALSE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_FALSE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_FALSE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_FALSE_MESSAGE(cond, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_EQ(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_EQ(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_EQ(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_NE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_NE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_NE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_GT(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_GT(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_GT(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_LT(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_LT(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_LT(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_GE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_GE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_GE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_LE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_LE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_LE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_UNARY(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_UNARY(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_UNARY(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_UNARY_FALSE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_UNARY_FALSE(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_UNARY_FALSE(...) DOCTEST_FUNC_EMPTY #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS #define DOCTEST_WARN_THROWS(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_THROWS(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_THROWS(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_THROWS_AS(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_THROWS_AS(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_THROWS_AS(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_THROWS_WITH(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_THROWS_WITH(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_THROWS_WITH(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_THROWS_WITH_AS(expr, with, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_THROWS_WITH_AS(expr, with, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_NOTHROW(...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_NOTHROW(...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_NOTHROW(...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_WARN_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY #define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, ...) DOCTEST_FUNC_EMPTY #endif // DOCTEST_CONFIG_NO_EXCEPTIONS #endif // DOCTEST_CONFIG_EVALUATE_ASSERTS_EVEN_WHEN_DISABLED #endif // DOCTEST_CONFIG_DISABLE #ifdef DOCTEST_CONFIG_NO_EXCEPTIONS #ifdef DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS #define DOCTEST_EXCEPTION_EMPTY_FUNC DOCTEST_FUNC_EMPTY #else // DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS #define DOCTEST_EXCEPTION_EMPTY_FUNC [] { static_assert(false, "Exceptions are disabled! " \ "Use DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS if you want to compile with exceptions disabled."); return false; }() #undef DOCTEST_REQUIRE #undef DOCTEST_REQUIRE_FALSE #undef DOCTEST_REQUIRE_MESSAGE #undef DOCTEST_REQUIRE_FALSE_MESSAGE #undef DOCTEST_REQUIRE_EQ #undef DOCTEST_REQUIRE_NE #undef DOCTEST_REQUIRE_GT #undef DOCTEST_REQUIRE_LT #undef DOCTEST_REQUIRE_GE #undef DOCTEST_REQUIRE_LE #undef DOCTEST_REQUIRE_UNARY #undef DOCTEST_REQUIRE_UNARY_FALSE #define DOCTEST_REQUIRE DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_FALSE DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_MESSAGE DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_FALSE_MESSAGE DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_EQ DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_NE DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_GT DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_LT DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_GE DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_LE DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_UNARY DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_UNARY_FALSE DOCTEST_EXCEPTION_EMPTY_FUNC #endif // DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS #define DOCTEST_WARN_THROWS(...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_THROWS(...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_THROWS(...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_THROWS_AS(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_THROWS_AS(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_THROWS_AS(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_THROWS_WITH(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_THROWS_WITH(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_THROWS_WITH(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_THROWS_WITH_AS(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_THROWS_WITH_AS(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_NOTHROW(...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_NOTHROW(...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_NOTHROW(...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_THROWS_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_THROWS_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_WARN_NOTHROW_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, ...) DOCTEST_EXCEPTION_EMPTY_FUNC #endif // DOCTEST_CONFIG_NO_EXCEPTIONS // clang-format off // KEPT FOR BACKWARDS COMPATIBILITY - FORWARDING TO THE RIGHT MACROS #define DOCTEST_FAST_WARN_EQ DOCTEST_WARN_EQ #define DOCTEST_FAST_CHECK_EQ DOCTEST_CHECK_EQ #define DOCTEST_FAST_REQUIRE_EQ DOCTEST_REQUIRE_EQ #define DOCTEST_FAST_WARN_NE DOCTEST_WARN_NE #define DOCTEST_FAST_CHECK_NE DOCTEST_CHECK_NE #define DOCTEST_FAST_REQUIRE_NE DOCTEST_REQUIRE_NE #define DOCTEST_FAST_WARN_GT DOCTEST_WARN_GT #define DOCTEST_FAST_CHECK_GT DOCTEST_CHECK_GT #define DOCTEST_FAST_REQUIRE_GT DOCTEST_REQUIRE_GT #define DOCTEST_FAST_WARN_LT DOCTEST_WARN_LT #define DOCTEST_FAST_CHECK_LT DOCTEST_CHECK_LT #define DOCTEST_FAST_REQUIRE_LT DOCTEST_REQUIRE_LT #define DOCTEST_FAST_WARN_GE DOCTEST_WARN_GE #define DOCTEST_FAST_CHECK_GE DOCTEST_CHECK_GE #define DOCTEST_FAST_REQUIRE_GE DOCTEST_REQUIRE_GE #define DOCTEST_FAST_WARN_LE DOCTEST_WARN_LE #define DOCTEST_FAST_CHECK_LE DOCTEST_CHECK_LE #define DOCTEST_FAST_REQUIRE_LE DOCTEST_REQUIRE_LE #define DOCTEST_FAST_WARN_UNARY DOCTEST_WARN_UNARY #define DOCTEST_FAST_CHECK_UNARY DOCTEST_CHECK_UNARY #define DOCTEST_FAST_REQUIRE_UNARY DOCTEST_REQUIRE_UNARY #define DOCTEST_FAST_WARN_UNARY_FALSE DOCTEST_WARN_UNARY_FALSE #define DOCTEST_FAST_CHECK_UNARY_FALSE DOCTEST_CHECK_UNARY_FALSE #define DOCTEST_FAST_REQUIRE_UNARY_FALSE DOCTEST_REQUIRE_UNARY_FALSE #define DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE(id, ...) DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id,__VA_ARGS__) // clang-format on // BDD style macros // clang-format off #define DOCTEST_SCENARIO(name) DOCTEST_TEST_CASE(" Scenario: " name) #define DOCTEST_SCENARIO_CLASS(name) DOCTEST_TEST_CASE_CLASS(" Scenario: " name) #define DOCTEST_SCENARIO_TEMPLATE(name, T, ...) DOCTEST_TEST_CASE_TEMPLATE(" Scenario: " name, T, __VA_ARGS__) #define DOCTEST_SCENARIO_TEMPLATE_DEFINE(name, T, id) DOCTEST_TEST_CASE_TEMPLATE_DEFINE(" Scenario: " name, T, id) #define DOCTEST_GIVEN(name) DOCTEST_SUBCASE(" Given: " name) #define DOCTEST_WHEN(name) DOCTEST_SUBCASE(" When: " name) #define DOCTEST_AND_WHEN(name) DOCTEST_SUBCASE("And when: " name) #define DOCTEST_THEN(name) DOCTEST_SUBCASE(" Then: " name) #define DOCTEST_AND_THEN(name) DOCTEST_SUBCASE(" And: " name) // clang-format on // == SHORT VERSIONS OF THE MACROS #ifndef DOCTEST_CONFIG_NO_SHORT_MACRO_NAMES #define TEST_CASE(name) DOCTEST_TEST_CASE(name) #define TEST_CASE_CLASS(name) DOCTEST_TEST_CASE_CLASS(name) #define TEST_CASE_FIXTURE(x, name) DOCTEST_TEST_CASE_FIXTURE(x, name) #define TYPE_TO_STRING_AS(str, ...) DOCTEST_TYPE_TO_STRING_AS(str, __VA_ARGS__) #define TYPE_TO_STRING(...) DOCTEST_TYPE_TO_STRING(__VA_ARGS__) #define TEST_CASE_TEMPLATE(name, T, ...) DOCTEST_TEST_CASE_TEMPLATE(name, T, __VA_ARGS__) #define TEST_CASE_TEMPLATE_DEFINE(name, T, id) DOCTEST_TEST_CASE_TEMPLATE_DEFINE(name, T, id) #define TEST_CASE_TEMPLATE_INVOKE(id, ...) DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id, __VA_ARGS__) #define TEST_CASE_TEMPLATE_APPLY(id, ...) DOCTEST_TEST_CASE_TEMPLATE_APPLY(id, __VA_ARGS__) #define SUBCASE(name) DOCTEST_SUBCASE(name) #define TEST_SUITE(decorators) DOCTEST_TEST_SUITE(decorators) #define TEST_SUITE_BEGIN(name) DOCTEST_TEST_SUITE_BEGIN(name) #define TEST_SUITE_END DOCTEST_TEST_SUITE_END #define REGISTER_EXCEPTION_TRANSLATOR(signature) DOCTEST_REGISTER_EXCEPTION_TRANSLATOR(signature) #define REGISTER_REPORTER(name, priority, reporter) DOCTEST_REGISTER_REPORTER(name, priority, reporter) #define REGISTER_LISTENER(name, priority, reporter) DOCTEST_REGISTER_LISTENER(name, priority, reporter) #define INFO(...) DOCTEST_INFO(__VA_ARGS__) #define CAPTURE(x) DOCTEST_CAPTURE(x) #define ADD_MESSAGE_AT(file, line, ...) DOCTEST_ADD_MESSAGE_AT(file, line, __VA_ARGS__) #define ADD_FAIL_CHECK_AT(file, line, ...) DOCTEST_ADD_FAIL_CHECK_AT(file, line, __VA_ARGS__) #define ADD_FAIL_AT(file, line, ...) DOCTEST_ADD_FAIL_AT(file, line, __VA_ARGS__) #define MESSAGE(...) DOCTEST_MESSAGE(__VA_ARGS__) #define FAIL_CHECK(...) DOCTEST_FAIL_CHECK(__VA_ARGS__) #define FAIL(...) DOCTEST_FAIL(__VA_ARGS__) #define TO_LVALUE(...) DOCTEST_TO_LVALUE(__VA_ARGS__) #define WARN(...) DOCTEST_WARN(__VA_ARGS__) #define WARN_FALSE(...) DOCTEST_WARN_FALSE(__VA_ARGS__) #define WARN_THROWS(...) DOCTEST_WARN_THROWS(__VA_ARGS__) #define WARN_THROWS_AS(expr, ...) DOCTEST_WARN_THROWS_AS(expr, __VA_ARGS__) #define WARN_THROWS_WITH(expr, ...) DOCTEST_WARN_THROWS_WITH(expr, __VA_ARGS__) #define WARN_THROWS_WITH_AS(expr, with, ...) DOCTEST_WARN_THROWS_WITH_AS(expr, with, __VA_ARGS__) #define WARN_NOTHROW(...) DOCTEST_WARN_NOTHROW(__VA_ARGS__) #define CHECK(...) DOCTEST_CHECK(__VA_ARGS__) #define CHECK_FALSE(...) DOCTEST_CHECK_FALSE(__VA_ARGS__) #define CHECK_THROWS(...) DOCTEST_CHECK_THROWS(__VA_ARGS__) #define CHECK_THROWS_AS(expr, ...) DOCTEST_CHECK_THROWS_AS(expr, __VA_ARGS__) #define CHECK_THROWS_WITH(expr, ...) DOCTEST_CHECK_THROWS_WITH(expr, __VA_ARGS__) #define CHECK_THROWS_WITH_AS(expr, with, ...) DOCTEST_CHECK_THROWS_WITH_AS(expr, with, __VA_ARGS__) #define CHECK_NOTHROW(...) DOCTEST_CHECK_NOTHROW(__VA_ARGS__) #define REQUIRE(...) DOCTEST_REQUIRE(__VA_ARGS__) #define REQUIRE_FALSE(...) DOCTEST_REQUIRE_FALSE(__VA_ARGS__) #define REQUIRE_THROWS(...) DOCTEST_REQUIRE_THROWS(__VA_ARGS__) #define REQUIRE_THROWS_AS(expr, ...) DOCTEST_REQUIRE_THROWS_AS(expr, __VA_ARGS__) #define REQUIRE_THROWS_WITH(expr, ...) DOCTEST_REQUIRE_THROWS_WITH(expr, __VA_ARGS__) #define REQUIRE_THROWS_WITH_AS(expr, with, ...) DOCTEST_REQUIRE_THROWS_WITH_AS(expr, with, __VA_ARGS__) #define REQUIRE_NOTHROW(...) DOCTEST_REQUIRE_NOTHROW(__VA_ARGS__) #define WARN_MESSAGE(cond, ...) DOCTEST_WARN_MESSAGE(cond, __VA_ARGS__) #define WARN_FALSE_MESSAGE(cond, ...) DOCTEST_WARN_FALSE_MESSAGE(cond, __VA_ARGS__) #define WARN_THROWS_MESSAGE(expr, ...) DOCTEST_WARN_THROWS_MESSAGE(expr, __VA_ARGS__) #define WARN_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, __VA_ARGS__) #define WARN_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, with, __VA_ARGS__) #define WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_WARN_THROWS_WITH_AS_MESSAGE(expr, with, ex, __VA_ARGS__) #define WARN_NOTHROW_MESSAGE(expr, ...) DOCTEST_WARN_NOTHROW_MESSAGE(expr, __VA_ARGS__) #define CHECK_MESSAGE(cond, ...) DOCTEST_CHECK_MESSAGE(cond, __VA_ARGS__) #define CHECK_FALSE_MESSAGE(cond, ...) DOCTEST_CHECK_FALSE_MESSAGE(cond, __VA_ARGS__) #define CHECK_THROWS_MESSAGE(expr, ...) DOCTEST_CHECK_THROWS_MESSAGE(expr, __VA_ARGS__) #define CHECK_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, __VA_ARGS__) #define CHECK_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, with, __VA_ARGS__) #define CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_CHECK_THROWS_WITH_AS_MESSAGE(expr, with, ex, __VA_ARGS__) #define CHECK_NOTHROW_MESSAGE(expr, ...) DOCTEST_CHECK_NOTHROW_MESSAGE(expr, __VA_ARGS__) #define REQUIRE_MESSAGE(cond, ...) DOCTEST_REQUIRE_MESSAGE(cond, __VA_ARGS__) #define REQUIRE_FALSE_MESSAGE(cond, ...) DOCTEST_REQUIRE_FALSE_MESSAGE(cond, __VA_ARGS__) #define REQUIRE_THROWS_MESSAGE(expr, ...) DOCTEST_REQUIRE_THROWS_MESSAGE(expr, __VA_ARGS__) #define REQUIRE_THROWS_AS_MESSAGE(expr, ex, ...) DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, __VA_ARGS__) #define REQUIRE_THROWS_WITH_MESSAGE(expr, with, ...) DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, with, __VA_ARGS__) #define REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, ...) DOCTEST_REQUIRE_THROWS_WITH_AS_MESSAGE(expr, with, ex, __VA_ARGS__) #define REQUIRE_NOTHROW_MESSAGE(expr, ...) DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, __VA_ARGS__) #define SCENARIO(name) DOCTEST_SCENARIO(name) #define SCENARIO_CLASS(name) DOCTEST_SCENARIO_CLASS(name) #define SCENARIO_TEMPLATE(name, T, ...) DOCTEST_SCENARIO_TEMPLATE(name, T, __VA_ARGS__) #define SCENARIO_TEMPLATE_DEFINE(name, T, id) DOCTEST_SCENARIO_TEMPLATE_DEFINE(name, T, id) #define GIVEN(name) DOCTEST_GIVEN(name) #define WHEN(name) DOCTEST_WHEN(name) #define AND_WHEN(name) DOCTEST_AND_WHEN(name) #define THEN(name) DOCTEST_THEN(name) #define AND_THEN(name) DOCTEST_AND_THEN(name) #define WARN_EQ(...) DOCTEST_WARN_EQ(__VA_ARGS__) #define CHECK_EQ(...) DOCTEST_CHECK_EQ(__VA_ARGS__) #define REQUIRE_EQ(...) DOCTEST_REQUIRE_EQ(__VA_ARGS__) #define WARN_NE(...) DOCTEST_WARN_NE(__VA_ARGS__) #define CHECK_NE(...) DOCTEST_CHECK_NE(__VA_ARGS__) #define REQUIRE_NE(...) DOCTEST_REQUIRE_NE(__VA_ARGS__) #define WARN_GT(...) DOCTEST_WARN_GT(__VA_ARGS__) #define CHECK_GT(...) DOCTEST_CHECK_GT(__VA_ARGS__) #define REQUIRE_GT(...) DOCTEST_REQUIRE_GT(__VA_ARGS__) #define WARN_LT(...) DOCTEST_WARN_LT(__VA_ARGS__) #define CHECK_LT(...) DOCTEST_CHECK_LT(__VA_ARGS__) #define REQUIRE_LT(...) DOCTEST_REQUIRE_LT(__VA_ARGS__) #define WARN_GE(...) DOCTEST_WARN_GE(__VA_ARGS__) #define CHECK_GE(...) DOCTEST_CHECK_GE(__VA_ARGS__) #define REQUIRE_GE(...) DOCTEST_REQUIRE_GE(__VA_ARGS__) #define WARN_LE(...) DOCTEST_WARN_LE(__VA_ARGS__) #define CHECK_LE(...) DOCTEST_CHECK_LE(__VA_ARGS__) #define REQUIRE_LE(...) DOCTEST_REQUIRE_LE(__VA_ARGS__) #define WARN_UNARY(...) DOCTEST_WARN_UNARY(__VA_ARGS__) #define CHECK_UNARY(...) DOCTEST_CHECK_UNARY(__VA_ARGS__) #define REQUIRE_UNARY(...) DOCTEST_REQUIRE_UNARY(__VA_ARGS__) #define WARN_UNARY_FALSE(...) DOCTEST_WARN_UNARY_FALSE(__VA_ARGS__) #define CHECK_UNARY_FALSE(...) DOCTEST_CHECK_UNARY_FALSE(__VA_ARGS__) #define REQUIRE_UNARY_FALSE(...) DOCTEST_REQUIRE_UNARY_FALSE(__VA_ARGS__) // KEPT FOR BACKWARDS COMPATIBILITY #define FAST_WARN_EQ(...) DOCTEST_FAST_WARN_EQ(__VA_ARGS__) #define FAST_CHECK_EQ(...) DOCTEST_FAST_CHECK_EQ(__VA_ARGS__) #define FAST_REQUIRE_EQ(...) DOCTEST_FAST_REQUIRE_EQ(__VA_ARGS__) #define FAST_WARN_NE(...) DOCTEST_FAST_WARN_NE(__VA_ARGS__) #define FAST_CHECK_NE(...) DOCTEST_FAST_CHECK_NE(__VA_ARGS__) #define FAST_REQUIRE_NE(...) DOCTEST_FAST_REQUIRE_NE(__VA_ARGS__) #define FAST_WARN_GT(...) DOCTEST_FAST_WARN_GT(__VA_ARGS__) #define FAST_CHECK_GT(...) DOCTEST_FAST_CHECK_GT(__VA_ARGS__) #define FAST_REQUIRE_GT(...) DOCTEST_FAST_REQUIRE_GT(__VA_ARGS__) #define FAST_WARN_LT(...) DOCTEST_FAST_WARN_LT(__VA_ARGS__) #define FAST_CHECK_LT(...) DOCTEST_FAST_CHECK_LT(__VA_ARGS__) #define FAST_REQUIRE_LT(...) DOCTEST_FAST_REQUIRE_LT(__VA_ARGS__) #define FAST_WARN_GE(...) DOCTEST_FAST_WARN_GE(__VA_ARGS__) #define FAST_CHECK_GE(...) DOCTEST_FAST_CHECK_GE(__VA_ARGS__) #define FAST_REQUIRE_GE(...) DOCTEST_FAST_REQUIRE_GE(__VA_ARGS__) #define FAST_WARN_LE(...) DOCTEST_FAST_WARN_LE(__VA_ARGS__) #define FAST_CHECK_LE(...) DOCTEST_FAST_CHECK_LE(__VA_ARGS__) #define FAST_REQUIRE_LE(...) DOCTEST_FAST_REQUIRE_LE(__VA_ARGS__) #define FAST_WARN_UNARY(...) DOCTEST_FAST_WARN_UNARY(__VA_ARGS__) #define FAST_CHECK_UNARY(...) DOCTEST_FAST_CHECK_UNARY(__VA_ARGS__) #define FAST_REQUIRE_UNARY(...) DOCTEST_FAST_REQUIRE_UNARY(__VA_ARGS__) #define FAST_WARN_UNARY_FALSE(...) DOCTEST_FAST_WARN_UNARY_FALSE(__VA_ARGS__) #define FAST_CHECK_UNARY_FALSE(...) DOCTEST_FAST_CHECK_UNARY_FALSE(__VA_ARGS__) #define FAST_REQUIRE_UNARY_FALSE(...) DOCTEST_FAST_REQUIRE_UNARY_FALSE(__VA_ARGS__) #define TEST_CASE_TEMPLATE_INSTANTIATE(id, ...) DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE(id, __VA_ARGS__) #endif // DOCTEST_CONFIG_NO_SHORT_MACRO_NAMES #ifndef DOCTEST_CONFIG_DISABLE // this is here to clear the 'current test suite' for the current translation unit - at the top DOCTEST_TEST_SUITE_END(); #endif // DOCTEST_CONFIG_DISABLE DOCTEST_CLANG_SUPPRESS_WARNING_POP DOCTEST_MSVC_SUPPRESS_WARNING_POP DOCTEST_GCC_SUPPRESS_WARNING_POP DOCTEST_SUPPRESS_COMMON_WARNINGS_POP #endif // DOCTEST_LIBRARY_INCLUDED #ifndef DOCTEST_SINGLE_HEADER #define DOCTEST_SINGLE_HEADER #endif // DOCTEST_SINGLE_HEADER #if defined(DOCTEST_CONFIG_IMPLEMENT) || !defined(DOCTEST_SINGLE_HEADER) #ifndef DOCTEST_SINGLE_HEADER #include "doctest_fwd.h" #endif // DOCTEST_SINGLE_HEADER DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wunused-macros") #ifndef DOCTEST_LIBRARY_IMPLEMENTATION #define DOCTEST_LIBRARY_IMPLEMENTATION DOCTEST_CLANG_SUPPRESS_WARNING_POP DOCTEST_SUPPRESS_COMMON_WARNINGS_PUSH DOCTEST_CLANG_SUPPRESS_WARNING_PUSH DOCTEST_CLANG_SUPPRESS_WARNING("-Wglobal-constructors") DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors") DOCTEST_CLANG_SUPPRESS_WARNING("-Wsign-conversion") DOCTEST_CLANG_SUPPRESS_WARNING("-Wshorten-64-to-32") DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-variable-declarations") DOCTEST_CLANG_SUPPRESS_WARNING("-Wswitch") DOCTEST_CLANG_SUPPRESS_WARNING("-Wswitch-enum") DOCTEST_CLANG_SUPPRESS_WARNING("-Wcovered-switch-default") DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-noreturn") DOCTEST_CLANG_SUPPRESS_WARNING("-Wdisabled-macro-expansion") DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-braces") DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-field-initializers") DOCTEST_CLANG_SUPPRESS_WARNING("-Wunused-member-function") DOCTEST_CLANG_SUPPRESS_WARNING("-Wnonportable-system-include-path") DOCTEST_GCC_SUPPRESS_WARNING_PUSH DOCTEST_GCC_SUPPRESS_WARNING("-Wconversion") DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-conversion") DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-field-initializers") DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-braces") DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch") DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch-enum") DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch-default") DOCTEST_GCC_SUPPRESS_WARNING("-Wunsafe-loop-optimizations") DOCTEST_GCC_SUPPRESS_WARNING("-Wold-style-cast") DOCTEST_GCC_SUPPRESS_WARNING("-Wunused-function") DOCTEST_GCC_SUPPRESS_WARNING("-Wmultiple-inheritance") DOCTEST_GCC_SUPPRESS_WARNING("-Wsuggest-attribute") DOCTEST_MSVC_SUPPRESS_WARNING_PUSH DOCTEST_MSVC_SUPPRESS_WARNING(4267) // 'var' : conversion from 'x' to 'y', possible loss of data DOCTEST_MSVC_SUPPRESS_WARNING(4530) // C++ exception handler used, but unwind semantics not enabled DOCTEST_MSVC_SUPPRESS_WARNING(4577) // 'noexcept' used with no exception handling mode specified DOCTEST_MSVC_SUPPRESS_WARNING(4774) // format string expected in argument is not a string literal DOCTEST_MSVC_SUPPRESS_WARNING(4365) // conversion from 'int' to 'unsigned', signed/unsigned mismatch DOCTEST_MSVC_SUPPRESS_WARNING(5039) // pointer to potentially throwing function passed to extern C DOCTEST_MSVC_SUPPRESS_WARNING(4800) // forcing value to bool 'true' or 'false' (performance warning) DOCTEST_MSVC_SUPPRESS_WARNING(5245) // unreferenced function with internal linkage has been removed DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN // required includes - will go only in one translation unit! #include <ctime> #include <cmath> #include <climits> // borland (Embarcadero) compiler requires math.h and not cmath - https://github.com/doctest/doctest/pull/37 #ifdef __BORLANDC__ #include <math.h> #endif // __BORLANDC__ #include <new> #include <cstdio> #include <cstdlib> #include <cstring> #include <limits> #include <utility> #include <fstream> #include <sstream> #ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM #include <iostream> #endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM #include <algorithm> #include <iomanip> #include <vector> #ifndef DOCTEST_CONFIG_NO_MULTITHREADING #include <atomic> #include <mutex> #define DOCTEST_DECLARE_MUTEX(name) std::mutex name; #define DOCTEST_DECLARE_STATIC_MUTEX(name) static DOCTEST_DECLARE_MUTEX(name) #define DOCTEST_LOCK_MUTEX(name) std::lock_guard<std::mutex> DOCTEST_ANONYMOUS(DOCTEST_ANON_LOCK_)(name); #else // DOCTEST_CONFIG_NO_MULTITHREADING #define DOCTEST_DECLARE_MUTEX(name) #define DOCTEST_DECLARE_STATIC_MUTEX(name) #define DOCTEST_LOCK_MUTEX(name) #endif // DOCTEST_CONFIG_NO_MULTITHREADING #include <set> #include <map> #include <unordered_set> #include <exception> #include <stdexcept> #include <csignal> #include <cfloat> #include <cctype> #include <cstdint> #include <string> #ifdef DOCTEST_PLATFORM_MAC #include <sys/types.h> #include <unistd.h> #include <sys/sysctl.h> #endif // DOCTEST_PLATFORM_MAC #ifdef DOCTEST_PLATFORM_WINDOWS // defines for a leaner windows.h #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #define DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN #endif // WIN32_LEAN_AND_MEAN #ifndef NOMINMAX #define NOMINMAX #define DOCTEST_UNDEF_NOMINMAX #endif // NOMINMAX // not sure what AfxWin.h is for - here I do what Catch does #ifdef __AFXDLL #include <AfxWin.h> #else #include <windows.h> #endif #include <io.h> #else // DOCTEST_PLATFORM_WINDOWS #include <sys/time.h> #include <unistd.h> #endif // DOCTEST_PLATFORM_WINDOWS // this is a fix for https://github.com/doctest/doctest/issues/348 // https://mail.gnome.org/archives/xml/2012-January/msg00000.html #if !defined(HAVE_UNISTD_H) && !defined(STDOUT_FILENO) #define STDOUT_FILENO fileno(stdout) #endif // HAVE_UNISTD_H DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END // counts the number of elements in a C array #define DOCTEST_COUNTOF(x) (sizeof(x) / sizeof(x[0])) #ifdef DOCTEST_CONFIG_DISABLE #define DOCTEST_BRANCH_ON_DISABLED(if_disabled, if_not_disabled) if_disabled #else // DOCTEST_CONFIG_DISABLE #define DOCTEST_BRANCH_ON_DISABLED(if_disabled, if_not_disabled) if_not_disabled #endif // DOCTEST_CONFIG_DISABLE #ifndef DOCTEST_CONFIG_OPTIONS_PREFIX #define DOCTEST_CONFIG_OPTIONS_PREFIX "dt-" #endif #ifndef DOCTEST_THREAD_LOCAL #if defined(DOCTEST_CONFIG_NO_MULTITHREADING) || DOCTEST_MSVC && (DOCTEST_MSVC < DOCTEST_COMPILER(19, 0, 0)) #define DOCTEST_THREAD_LOCAL #else // DOCTEST_MSVC #define DOCTEST_THREAD_LOCAL thread_local #endif // DOCTEST_MSVC #endif // DOCTEST_THREAD_LOCAL #ifndef DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES #define DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES 32 #endif #ifndef DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE #define DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE 64 #endif #ifdef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS #define DOCTEST_OPTIONS_PREFIX_DISPLAY DOCTEST_CONFIG_OPTIONS_PREFIX #else #define DOCTEST_OPTIONS_PREFIX_DISPLAY "" #endif #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) #define DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS #endif #ifndef DOCTEST_CDECL #define DOCTEST_CDECL __cdecl #endif namespace doctest { bool is_running_in_test = false; namespace { using namespace detail; template <typename Ex> DOCTEST_NORETURN void throw_exception(Ex const& e) { #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS throw e; #else // DOCTEST_CONFIG_NO_EXCEPTIONS #ifdef DOCTEST_CONFIG_HANDLE_EXCEPTION DOCTEST_CONFIG_HANDLE_EXCEPTION(e); #else // DOCTEST_CONFIG_HANDLE_EXCEPTION #ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM std::cerr << "doctest will terminate because it needed to throw an exception.\n" << "The message was: " << e.what() << '\n'; #endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM #endif // DOCTEST_CONFIG_HANDLE_EXCEPTION std::terminate(); #endif // DOCTEST_CONFIG_NO_EXCEPTIONS } #ifndef DOCTEST_INTERNAL_ERROR #define DOCTEST_INTERNAL_ERROR(msg) \ throw_exception(std::logic_error( \ __FILE__ ":" DOCTEST_TOSTR(__LINE__) ": Internal doctest error: " msg)) #endif // DOCTEST_INTERNAL_ERROR // case insensitive strcmp int stricmp(const char* a, const char* b) { for(;; a++, b++) { const int d = tolower(*a) - tolower(*b); if(d != 0 || !*a) return d; } } struct Endianness { enum Arch { Big, Little }; static Arch which() { int x = 1; // casting any data pointer to char* is allowed auto ptr = reinterpret_cast<char*>(&x); if(*ptr) return Little; return Big; } }; } // namespace namespace detail { DOCTEST_THREAD_LOCAL class { std::vector<std::streampos> stack; std::stringstream ss; public: std::ostream* push() { stack.push_back(ss.tellp()); return &ss; } String pop() { if (stack.empty()) DOCTEST_INTERNAL_ERROR("TLSS was empty when trying to pop!"); std::streampos pos = stack.back(); stack.pop_back(); unsigned sz = static_cast<unsigned>(ss.tellp() - pos); ss.rdbuf()->pubseekpos(pos, std::ios::in | std::ios::out); return String(ss, sz); } } g_oss; std::ostream* tlssPush() { return g_oss.push(); } String tlssPop() { return g_oss.pop(); } #ifndef DOCTEST_CONFIG_DISABLE namespace timer_large_integer { #if defined(DOCTEST_PLATFORM_WINDOWS) using type = ULONGLONG; #else // DOCTEST_PLATFORM_WINDOWS using type = std::uint64_t; #endif // DOCTEST_PLATFORM_WINDOWS } using ticks_t = timer_large_integer::type; #ifdef DOCTEST_CONFIG_GETCURRENTTICKS ticks_t getCurrentTicks() { return DOCTEST_CONFIG_GETCURRENTTICKS(); } #elif defined(DOCTEST_PLATFORM_WINDOWS) ticks_t getCurrentTicks() { static LARGE_INTEGER hz = { {0} }, hzo = { {0} }; if(!hz.QuadPart) { QueryPerformanceFrequency(&hz); QueryPerformanceCounter(&hzo); } LARGE_INTEGER t; QueryPerformanceCounter(&t); return ((t.QuadPart - hzo.QuadPart) * LONGLONG(1000000)) / hz.QuadPart; } #else // DOCTEST_PLATFORM_WINDOWS ticks_t getCurrentTicks() { timeval t; gettimeofday(&t, nullptr); return static_cast<ticks_t>(t.tv_sec) * 1000000 + static_cast<ticks_t>(t.tv_usec); } #endif // DOCTEST_PLATFORM_WINDOWS struct Timer { void start() { m_ticks = getCurrentTicks(); } unsigned int getElapsedMicroseconds() const { return static_cast<unsigned int>(getCurrentTicks() - m_ticks); } //unsigned int getElapsedMilliseconds() const { // return static_cast<unsigned int>(getElapsedMicroseconds() / 1000); //} double getElapsedSeconds() const { return static_cast<double>(getCurrentTicks() - m_ticks) / 1000000.0; } private: ticks_t m_ticks = 0; }; #ifdef DOCTEST_CONFIG_NO_MULTITHREADING template <typename T> using Atomic = T; #else // DOCTEST_CONFIG_NO_MULTITHREADING template <typename T> using Atomic = std::atomic<T>; #endif // DOCTEST_CONFIG_NO_MULTITHREADING #if defined(DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS) || defined(DOCTEST_CONFIG_NO_MULTITHREADING) template <typename T> using MultiLaneAtomic = Atomic<T>; #else // DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS // Provides a multilane implementation of an atomic variable that supports add, sub, load, // store. Instead of using a single atomic variable, this splits up into multiple ones, // each sitting on a separate cache line. The goal is to provide a speedup when most // operations are modifying. It achieves this with two properties: // // * Multiple atomics are used, so chance of congestion from the same atomic is reduced. // * Each atomic sits on a separate cache line, so false sharing is reduced. // // The disadvantage is that there is a small overhead due to the use of TLS, and load/store // is slower because all atomics have to be accessed. template <typename T> class MultiLaneAtomic { struct CacheLineAlignedAtomic { Atomic<T> atomic{}; char padding[DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE - sizeof(Atomic<T>)]; }; CacheLineAlignedAtomic m_atomics[DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES]; static_assert(sizeof(CacheLineAlignedAtomic) == DOCTEST_MULTI_LANE_ATOMICS_CACHE_LINE_SIZE, "guarantee one atomic takes exactly one cache line"); public: T operator++() DOCTEST_NOEXCEPT { return fetch_add(1) + 1; } T operator++(int) DOCTEST_NOEXCEPT { return fetch_add(1); } T fetch_add(T arg, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT { return myAtomic().fetch_add(arg, order); } T fetch_sub(T arg, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT { return myAtomic().fetch_sub(arg, order); } operator T() const DOCTEST_NOEXCEPT { return load(); } T load(std::memory_order order = std::memory_order_seq_cst) const DOCTEST_NOEXCEPT { auto result = T(); for(auto const& c : m_atomics) { result += c.atomic.load(order); } return result; } T operator=(T desired) DOCTEST_NOEXCEPT { // lgtm [cpp/assignment-does-not-return-this] store(desired); return desired; } void store(T desired, std::memory_order order = std::memory_order_seq_cst) DOCTEST_NOEXCEPT { // first value becomes desired", all others become 0. for(auto& c : m_atomics) { c.atomic.store(desired, order); desired = {}; } } private: // Each thread has a different atomic that it operates on. If more than NumLanes threads // use this, some will use the same atomic. So performance will degrade a bit, but still // everything will work. // // The logic here is a bit tricky. The call should be as fast as possible, so that there // is minimal to no overhead in determining the correct atomic for the current thread. // // 1. A global static counter laneCounter counts continuously up. // 2. Each successive thread will use modulo operation of that counter so it gets an atomic // assigned in a round-robin fashion. // 3. This tlsLaneIdx is stored in the thread local data, so it is directly available with // little overhead. Atomic<T>& myAtomic() DOCTEST_NOEXCEPT { static Atomic<size_t> laneCounter; DOCTEST_THREAD_LOCAL size_t tlsLaneIdx = laneCounter++ % DOCTEST_MULTI_LANE_ATOMICS_THREAD_LANES; return m_atomics[tlsLaneIdx].atomic; } }; #endif // DOCTEST_CONFIG_NO_MULTI_LANE_ATOMICS // this holds both parameters from the command line and runtime data for tests struct ContextState : ContextOptions, TestRunStats, CurrentTestCaseStats { MultiLaneAtomic<int> numAssertsCurrentTest_atomic; MultiLaneAtomic<int> numAssertsFailedCurrentTest_atomic; std::vector<std::vector<String>> filters = decltype(filters)(9); // 9 different filters std::vector<IReporter*> reporters_currently_used; assert_handler ah = nullptr; Timer timer; std::vector<String> stringifiedContexts; // logging from INFO() due to an exception // stuff for subcases bool reachedLeaf; std::vector<SubcaseSignature> subcaseStack; std::vector<SubcaseSignature> nextSubcaseStack; std::unordered_set<unsigned long long> fullyTraversedSubcases; size_t currentSubcaseDepth; Atomic<bool> shouldLogCurrentException; void resetRunData() { numTestCases = 0; numTestCasesPassingFilters = 0; numTestSuitesPassingFilters = 0; numTestCasesFailed = 0; numAsserts = 0; numAssertsFailed = 0; numAssertsCurrentTest = 0; numAssertsFailedCurrentTest = 0; } void finalizeTestCaseData() { seconds = timer.getElapsedSeconds(); // update the non-atomic counters numAsserts += numAssertsCurrentTest_atomic; numAssertsFailed += numAssertsFailedCurrentTest_atomic; numAssertsCurrentTest = numAssertsCurrentTest_atomic; numAssertsFailedCurrentTest = numAssertsFailedCurrentTest_atomic; if(numAssertsFailedCurrentTest) failure_flags |= TestCaseFailureReason::AssertFailure; if(Approx(currentTest->m_timeout).epsilon(DBL_EPSILON) != 0 && Approx(seconds).epsilon(DBL_EPSILON) > currentTest->m_timeout) failure_flags |= TestCaseFailureReason::Timeout; if(currentTest->m_should_fail) { if(failure_flags) { failure_flags |= TestCaseFailureReason::ShouldHaveFailedAndDid; } else { failure_flags |= TestCaseFailureReason::ShouldHaveFailedButDidnt; } } else if(failure_flags && currentTest->m_may_fail) { failure_flags |= TestCaseFailureReason::CouldHaveFailedAndDid; } else if(currentTest->m_expected_failures > 0) { if(numAssertsFailedCurrentTest == currentTest->m_expected_failures) { failure_flags |= TestCaseFailureReason::FailedExactlyNumTimes; } else { failure_flags |= TestCaseFailureReason::DidntFailExactlyNumTimes; } } bool ok_to_fail = (TestCaseFailureReason::ShouldHaveFailedAndDid & failure_flags) || (TestCaseFailureReason::CouldHaveFailedAndDid & failure_flags) || (TestCaseFailureReason::FailedExactlyNumTimes & failure_flags); // if any subcase has failed - the whole test case has failed testCaseSuccess = !(failure_flags && !ok_to_fail); if(!testCaseSuccess) numTestCasesFailed++; } }; ContextState* g_cs = nullptr; // used to avoid locks for the debug output // TODO: figure out if this is indeed necessary/correct - seems like either there still // could be a race or that there wouldn't be a race even if using the context directly DOCTEST_THREAD_LOCAL bool g_no_colors; #endif // DOCTEST_CONFIG_DISABLE } // namespace detail char* String::allocate(size_type sz) { if (sz <= last) { buf[sz] = '\0'; setLast(last - sz); return buf; } else { setOnHeap(); data.size = sz; data.capacity = data.size + 1; data.ptr = new char[data.capacity]; data.ptr[sz] = '\0'; return data.ptr; } } void String::setOnHeap() noexcept { *reinterpret_cast<unsigned char*>(&buf[last]) = 128; } void String::setLast(size_type in) noexcept { buf[last] = char(in); } void String::setSize(size_type sz) noexcept { if (isOnStack()) { buf[sz] = '\0'; setLast(last - sz); } else { data.ptr[sz] = '\0'; data.size = sz; } } void String::copy(const String& other) { if(other.isOnStack()) { memcpy(buf, other.buf, len); } else { memcpy(allocate(other.data.size), other.data.ptr, other.data.size); } } String::String() noexcept { buf[0] = '\0'; setLast(); } String::~String() { if(!isOnStack()) delete[] data.ptr; } // NOLINT(clang-analyzer-cplusplus.NewDeleteLeaks) String::String(const char* in) : String(in, strlen(in)) {} String::String(const char* in, size_type in_size) { memcpy(allocate(in_size), in, in_size); } String::String(std::istream& in, size_type in_size) { in.read(allocate(in_size), in_size); } String::String(const String& other) { copy(other); } String& String::operator=(const String& other) { if(this != &other) { if(!isOnStack()) delete[] data.ptr; copy(other); } return *this; } String& String::operator+=(const String& other) { const size_type my_old_size = size(); const size_type other_size = other.size(); const size_type total_size = my_old_size + other_size; if(isOnStack()) { if(total_size < len) { // append to the current stack space memcpy(buf + my_old_size, other.c_str(), other_size + 1); // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks) setLast(last - total_size); } else { // alloc new chunk char* temp = new char[total_size + 1]; // copy current data to new location before writing in the union memcpy(temp, buf, my_old_size); // skip the +1 ('\0') for speed // update data in union setOnHeap(); data.size = total_size; data.capacity = data.size + 1; data.ptr = temp; // transfer the rest of the data memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1); } } else { if(data.capacity > total_size) { // append to the current heap block data.size = total_size; memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1); } else { // resize data.capacity *= 2; if(data.capacity <= total_size) data.capacity = total_size + 1; // alloc new chunk char* temp = new char[data.capacity]; // copy current data to new location before releasing it memcpy(temp, data.ptr, my_old_size); // skip the +1 ('\0') for speed // release old chunk delete[] data.ptr; // update the rest of the union members data.size = total_size; data.ptr = temp; // transfer the rest of the data memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1); } } return *this; } String::String(String&& other) noexcept { memcpy(buf, other.buf, len); other.buf[0] = '\0'; other.setLast(); } String& String::operator=(String&& other) noexcept { if(this != &other) { if(!isOnStack()) delete[] data.ptr; memcpy(buf, other.buf, len); other.buf[0] = '\0'; other.setLast(); } return *this; } char String::operator[](size_type i) const { return const_cast<String*>(this)->operator[](i); } char& String::operator[](size_type i) { if(isOnStack()) return reinterpret_cast<char*>(buf)[i]; return data.ptr[i]; } DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wmaybe-uninitialized") String::size_type String::size() const { if(isOnStack()) return last - (size_type(buf[last]) & 31); // using "last" would work only if "len" is 32 return data.size; } DOCTEST_GCC_SUPPRESS_WARNING_POP String::size_type String::capacity() const { if(isOnStack()) return len; return data.capacity; } String String::substr(size_type pos, size_type cnt) && { cnt = std::min(cnt, size() - 1 - pos); char* cptr = c_str(); memmove(cptr, cptr + pos, cnt); setSize(cnt); return std::move(*this); } String String::substr(size_type pos, size_type cnt) const & { cnt = std::min(cnt, size() - 1 - pos); return String{ c_str() + pos, cnt }; } String::size_type String::find(char ch, size_type pos) const { const char* begin = c_str(); const char* end = begin + size(); const char* it = begin + pos; for (; it < end && *it != ch; it++); if (it < end) { return static_cast<size_type>(it - begin); } else { return npos; } } String::size_type String::rfind(char ch, size_type pos) const { const char* begin = c_str(); const char* it = begin + std::min(pos, size() - 1); for (; it >= begin && *it != ch; it--); if (it >= begin) { return static_cast<size_type>(it - begin); } else { return npos; } } int String::compare(const char* other, bool no_case) const { if(no_case) return doctest::stricmp(c_str(), other); return std::strcmp(c_str(), other); } int String::compare(const String& other, bool no_case) const { return compare(other.c_str(), no_case); } String operator+(const String& lhs, const String& rhs) { return String(lhs) += rhs; } bool operator==(const String& lhs, const String& rhs) { return lhs.compare(rhs) == 0; } bool operator!=(const String& lhs, const String& rhs) { return lhs.compare(rhs) != 0; } bool operator< (const String& lhs, const String& rhs) { return lhs.compare(rhs) < 0; } bool operator> (const String& lhs, const String& rhs) { return lhs.compare(rhs) > 0; } bool operator<=(const String& lhs, const String& rhs) { return (lhs != rhs) ? lhs.compare(rhs) < 0 : true; } bool operator>=(const String& lhs, const String& rhs) { return (lhs != rhs) ? lhs.compare(rhs) > 0 : true; } std::ostream& operator<<(std::ostream& s, const String& in) { return s << in.c_str(); } Contains::Contains(const String& str) : string(str) { } bool Contains::checkWith(const String& other) const { return strstr(other.c_str(), string.c_str()) != nullptr; } String toString(const Contains& in) { return "Contains( " + in.string + " )"; } bool operator==(const String& lhs, const Contains& rhs) { return rhs.checkWith(lhs); } bool operator==(const Contains& lhs, const String& rhs) { return lhs.checkWith(rhs); } bool operator!=(const String& lhs, const Contains& rhs) { return !rhs.checkWith(lhs); } bool operator!=(const Contains& lhs, const String& rhs) { return !lhs.checkWith(rhs); } namespace { void color_to_stream(std::ostream&, Color::Enum) DOCTEST_BRANCH_ON_DISABLED({}, ;) } // namespace namespace Color { std::ostream& operator<<(std::ostream& s, Color::Enum code) { color_to_stream(s, code); return s; } } // namespace Color // clang-format off const char* assertString(assertType::Enum at) { DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4061) // enum 'x' in switch of enum 'y' is not explicitly handled #define DOCTEST_GENERATE_ASSERT_TYPE_CASE(assert_type) case assertType::DT_ ## assert_type: return #assert_type #define DOCTEST_GENERATE_ASSERT_TYPE_CASES(assert_type) \ DOCTEST_GENERATE_ASSERT_TYPE_CASE(WARN_ ## assert_type); \ DOCTEST_GENERATE_ASSERT_TYPE_CASE(CHECK_ ## assert_type); \ DOCTEST_GENERATE_ASSERT_TYPE_CASE(REQUIRE_ ## assert_type) switch(at) { DOCTEST_GENERATE_ASSERT_TYPE_CASE(WARN); DOCTEST_GENERATE_ASSERT_TYPE_CASE(CHECK); DOCTEST_GENERATE_ASSERT_TYPE_CASE(REQUIRE); DOCTEST_GENERATE_ASSERT_TYPE_CASES(FALSE); DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS); DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS_AS); DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS_WITH); DOCTEST_GENERATE_ASSERT_TYPE_CASES(THROWS_WITH_AS); DOCTEST_GENERATE_ASSERT_TYPE_CASES(NOTHROW); DOCTEST_GENERATE_ASSERT_TYPE_CASES(EQ); DOCTEST_GENERATE_ASSERT_TYPE_CASES(NE); DOCTEST_GENERATE_ASSERT_TYPE_CASES(GT); DOCTEST_GENERATE_ASSERT_TYPE_CASES(LT); DOCTEST_GENERATE_ASSERT_TYPE_CASES(GE); DOCTEST_GENERATE_ASSERT_TYPE_CASES(LE); DOCTEST_GENERATE_ASSERT_TYPE_CASES(UNARY); DOCTEST_GENERATE_ASSERT_TYPE_CASES(UNARY_FALSE); default: DOCTEST_INTERNAL_ERROR("Tried stringifying invalid assert type!"); } DOCTEST_MSVC_SUPPRESS_WARNING_POP } // clang-format on const char* failureString(assertType::Enum at) { if(at & assertType::is_warn) //!OCLINT bitwise operator in conditional return "WARNING"; if(at & assertType::is_check) //!OCLINT bitwise operator in conditional return "ERROR"; if(at & assertType::is_require) //!OCLINT bitwise operator in conditional return "FATAL ERROR"; return ""; } DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wnull-dereference") DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wnull-dereference") // depending on the current options this will remove the path of filenames const char* skipPathFromFilename(const char* file) { #ifndef DOCTEST_CONFIG_DISABLE if(getContextOptions()->no_path_in_filenames) { auto back = std::strrchr(file, '\\'); auto forward = std::strrchr(file, '/'); if(back || forward) { if(back > forward) forward = back; return forward + 1; } } #endif // DOCTEST_CONFIG_DISABLE return file; } DOCTEST_CLANG_SUPPRESS_WARNING_POP DOCTEST_GCC_SUPPRESS_WARNING_POP bool SubcaseSignature::operator==(const SubcaseSignature& other) const { return m_line == other.m_line && std::strcmp(m_file, other.m_file) == 0 && m_name == other.m_name; } bool SubcaseSignature::operator<(const SubcaseSignature& other) const { if(m_line != other.m_line) return m_line < other.m_line; if(std::strcmp(m_file, other.m_file) != 0) return std::strcmp(m_file, other.m_file) < 0; return m_name.compare(other.m_name) < 0; } DOCTEST_DEFINE_INTERFACE(IContextScope) namespace detail { void filldata<const void*>::fill(std::ostream* stream, const void* in) { if (in) { *stream << in; } else { *stream << "nullptr"; } } template <typename T> String toStreamLit(T t) { std::ostream* os = tlssPush(); os->operator<<(t); return tlssPop(); } } #ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING String toString(const char* in) { return String("\"") + (in ? in : "{null string}") + "\""; } #endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING #if DOCTEST_MSVC >= DOCTEST_COMPILER(19, 20, 0) // see this issue on why this is needed: https://github.com/doctest/doctest/issues/183 String toString(const std::string& in) { return in.c_str(); } #endif // VS 2019 String toString(String in) { return in; } String toString(std::nullptr_t) { return "nullptr"; } String toString(bool in) { return in ? "true" : "false"; } String toString(float in) { return toStreamLit(in); } String toString(double in) { return toStreamLit(in); } String toString(double long in) { return toStreamLit(in); } String toString(char in) { return toStreamLit(static_cast<signed>(in)); } String toString(char signed in) { return toStreamLit(static_cast<signed>(in)); } String toString(char unsigned in) { return toStreamLit(static_cast<unsigned>(in)); } String toString(short in) { return toStreamLit(in); } String toString(short unsigned in) { return toStreamLit(in); } String toString(signed in) { return toStreamLit(in); } String toString(unsigned in) { return toStreamLit(in); } String toString(long in) { return toStreamLit(in); } String toString(long unsigned in) { return toStreamLit(in); } String toString(long long in) { return toStreamLit(in); } String toString(long long unsigned in) { return toStreamLit(in); } Approx::Approx(double value) : m_epsilon(static_cast<double>(std::numeric_limits<float>::epsilon()) * 100) , m_scale(1.0) , m_value(value) {} Approx Approx::operator()(double value) const { Approx approx(value); approx.epsilon(m_epsilon); approx.scale(m_scale); return approx; } Approx& Approx::epsilon(double newEpsilon) { m_epsilon = newEpsilon; return *this; } Approx& Approx::scale(double newScale) { m_scale = newScale; return *this; } bool operator==(double lhs, const Approx& rhs) { // Thanks to Richard Harris for his help refining this formula return std::fabs(lhs - rhs.m_value) < rhs.m_epsilon * (rhs.m_scale + std::max<double>(std::fabs(lhs), std::fabs(rhs.m_value))); } bool operator==(const Approx& lhs, double rhs) { return operator==(rhs, lhs); } bool operator!=(double lhs, const Approx& rhs) { return !operator==(lhs, rhs); } bool operator!=(const Approx& lhs, double rhs) { return !operator==(rhs, lhs); } bool operator<=(double lhs, const Approx& rhs) { return lhs < rhs.m_value || lhs == rhs; } bool operator<=(const Approx& lhs, double rhs) { return lhs.m_value < rhs || lhs == rhs; } bool operator>=(double lhs, const Approx& rhs) { return lhs > rhs.m_value || lhs == rhs; } bool operator>=(const Approx& lhs, double rhs) { return lhs.m_value > rhs || lhs == rhs; } bool operator<(double lhs, const Approx& rhs) { return lhs < rhs.m_value && lhs != rhs; } bool operator<(const Approx& lhs, double rhs) { return lhs.m_value < rhs && lhs != rhs; } bool operator>(double lhs, const Approx& rhs) { return lhs > rhs.m_value && lhs != rhs; } bool operator>(const Approx& lhs, double rhs) { return lhs.m_value > rhs && lhs != rhs; } String toString(const Approx& in) { return "Approx( " + doctest::toString(in.m_value) + " )"; } const ContextOptions* getContextOptions() { return DOCTEST_BRANCH_ON_DISABLED(nullptr, g_cs); } DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4738) template <typename F> IsNaN<F>::operator bool() const { return std::isnan(value) ^ flipped; } DOCTEST_MSVC_SUPPRESS_WARNING_POP template struct DOCTEST_INTERFACE_DEF IsNaN<float>; template struct DOCTEST_INTERFACE_DEF IsNaN<double>; template struct DOCTEST_INTERFACE_DEF IsNaN<long double>; template <typename F> String toString(IsNaN<F> in) { return String(in.flipped ? "! " : "") + "IsNaN( " + doctest::toString(in.value) + " )"; } String toString(IsNaN<float> in) { return toString<float>(in); } String toString(IsNaN<double> in) { return toString<double>(in); } String toString(IsNaN<double long> in) { return toString<double long>(in); } } // namespace doctest #ifdef DOCTEST_CONFIG_DISABLE namespace doctest { Context::Context(int, const char* const*) {} Context::~Context() = default; void Context::applyCommandLine(int, const char* const*) {} void Context::addFilter(const char*, const char*) {} void Context::clearFilters() {} void Context::setOption(const char*, bool) {} void Context::setOption(const char*, int) {} void Context::setOption(const char*, const char*) {} bool Context::shouldExit() { return false; } void Context::setAsDefaultForAssertsOutOfTestCases() {} void Context::setAssertHandler(detail::assert_handler) {} void Context::setCout(std::ostream*) {} int Context::run() { return 0; } int IReporter::get_num_active_contexts() { return 0; } const IContextScope* const* IReporter::get_active_contexts() { return nullptr; } int IReporter::get_num_stringified_contexts() { return 0; } const String* IReporter::get_stringified_contexts() { return nullptr; } int registerReporter(const char*, int, IReporter*) { return 0; } } // namespace doctest #else // DOCTEST_CONFIG_DISABLE #if !defined(DOCTEST_CONFIG_COLORS_NONE) #if !defined(DOCTEST_CONFIG_COLORS_WINDOWS) && !defined(DOCTEST_CONFIG_COLORS_ANSI) #ifdef DOCTEST_PLATFORM_WINDOWS #define DOCTEST_CONFIG_COLORS_WINDOWS #else // linux #define DOCTEST_CONFIG_COLORS_ANSI #endif // platform #endif // DOCTEST_CONFIG_COLORS_WINDOWS && DOCTEST_CONFIG_COLORS_ANSI #endif // DOCTEST_CONFIG_COLORS_NONE namespace doctest_detail_test_suite_ns { // holds the current test suite doctest::detail::TestSuite& getCurrentTestSuite() { static doctest::detail::TestSuite data{}; return data; } } // namespace doctest_detail_test_suite_ns namespace doctest { namespace { // the int (priority) is part of the key for automatic sorting - sadly one can register a // reporter with a duplicate name and a different priority but hopefully that won't happen often :| using reporterMap = std::map<std::pair<int, String>, reporterCreatorFunc>; reporterMap& getReporters() { static reporterMap data; return data; } reporterMap& getListeners() { static reporterMap data; return data; } } // namespace namespace detail { #define DOCTEST_ITERATE_THROUGH_REPORTERS(function, ...) \ for(auto& curr_rep : g_cs->reporters_currently_used) \ curr_rep->function(__VA_ARGS__) bool checkIfShouldThrow(assertType::Enum at) { if(at & assertType::is_require) //!OCLINT bitwise operator in conditional return true; if((at & assertType::is_check) //!OCLINT bitwise operator in conditional && getContextOptions()->abort_after > 0 && (g_cs->numAssertsFailed + g_cs->numAssertsFailedCurrentTest_atomic) >= getContextOptions()->abort_after) return true; return false; } #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS DOCTEST_NORETURN void throwException() { g_cs->shouldLogCurrentException = false; throw TestFailureException(); // NOLINT(hicpp-exception-baseclass) } #else // DOCTEST_CONFIG_NO_EXCEPTIONS void throwException() {} #endif // DOCTEST_CONFIG_NO_EXCEPTIONS } // namespace detail namespace { using namespace detail; // matching of a string against a wildcard mask (case sensitivity configurable) taken from // https://www.codeproject.com/Articles/1088/Wildcard-string-compare-globbing int wildcmp(const char* str, const char* wild, bool caseSensitive) { const char* cp = str; const char* mp = wild; while((*str) && (*wild != '*')) { if((caseSensitive ? (*wild != *str) : (tolower(*wild) != tolower(*str))) && (*wild != '?')) { return 0; } wild++; str++; } while(*str) { if(*wild == '*') { if(!*++wild) { return 1; } mp = wild; cp = str + 1; } else if((caseSensitive ? (*wild == *str) : (tolower(*wild) == tolower(*str))) || (*wild == '?')) { wild++; str++; } else { wild = mp; //!OCLINT parameter reassignment str = cp++; //!OCLINT parameter reassignment } } while(*wild == '*') { wild++; } return !*wild; } // checks if the name matches any of the filters (and can be configured what to do when empty) bool matchesAny(const char* name, const std::vector<String>& filters, bool matchEmpty, bool caseSensitive) { if (filters.empty() && matchEmpty) return true; for (auto& curr : filters) if (wildcmp(name, curr.c_str(), caseSensitive)) return true; return false; } DOCTEST_NO_SANITIZE_INTEGER unsigned long long hash(unsigned long long a, unsigned long long b) { return (a << 5) + b; } // C string hash function (djb2) - taken from http://www.cse.yorku.ca/~oz/hash.html DOCTEST_NO_SANITIZE_INTEGER unsigned long long hash(const char* str) { unsigned long long hash = 5381; char c; while ((c = *str++)) hash = ((hash << 5) + hash) + c; // hash * 33 + c return hash; } unsigned long long hash(const SubcaseSignature& sig) { return hash(hash(hash(sig.m_file), hash(sig.m_name.c_str())), sig.m_line); } unsigned long long hash(const std::vector<SubcaseSignature>& sigs, size_t count) { unsigned long long running = 0; auto end = sigs.begin() + count; for (auto it = sigs.begin(); it != end; it++) { running = hash(running, hash(*it)); } return running; } unsigned long long hash(const std::vector<SubcaseSignature>& sigs) { unsigned long long running = 0; for (const SubcaseSignature& sig : sigs) { running = hash(running, hash(sig)); } return running; } } // namespace namespace detail { bool Subcase::checkFilters() { if (g_cs->subcaseStack.size() < size_t(g_cs->subcase_filter_levels)) { if (!matchesAny(m_signature.m_name.c_str(), g_cs->filters[6], true, g_cs->case_sensitive)) return true; if (matchesAny(m_signature.m_name.c_str(), g_cs->filters[7], false, g_cs->case_sensitive)) return true; } return false; } Subcase::Subcase(const String& name, const char* file, int line) : m_signature({name, file, line}) { if (!g_cs->reachedLeaf) { if (g_cs->nextSubcaseStack.size() <= g_cs->subcaseStack.size() || g_cs->nextSubcaseStack[g_cs->subcaseStack.size()] == m_signature) { // Going down. if (checkFilters()) { return; } g_cs->subcaseStack.push_back(m_signature); g_cs->currentSubcaseDepth++; m_entered = true; DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_start, m_signature); } } else { if (g_cs->subcaseStack[g_cs->currentSubcaseDepth] == m_signature) { // This subcase is reentered via control flow. g_cs->currentSubcaseDepth++; m_entered = true; DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_start, m_signature); } else if (g_cs->nextSubcaseStack.size() <= g_cs->currentSubcaseDepth && g_cs->fullyTraversedSubcases.find(hash(hash(g_cs->subcaseStack, g_cs->currentSubcaseDepth), hash(m_signature))) == g_cs->fullyTraversedSubcases.end()) { if (checkFilters()) { return; } // This subcase is part of the one to be executed next. g_cs->nextSubcaseStack.clear(); g_cs->nextSubcaseStack.insert(g_cs->nextSubcaseStack.end(), g_cs->subcaseStack.begin(), g_cs->subcaseStack.begin() + g_cs->currentSubcaseDepth); g_cs->nextSubcaseStack.push_back(m_signature); } } } DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4996) // std::uncaught_exception is deprecated in C++17 DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") Subcase::~Subcase() { if (m_entered) { g_cs->currentSubcaseDepth--; if (!g_cs->reachedLeaf) { // Leaf. g_cs->fullyTraversedSubcases.insert(hash(g_cs->subcaseStack)); g_cs->nextSubcaseStack.clear(); g_cs->reachedLeaf = true; } else if (g_cs->nextSubcaseStack.empty()) { // All children are finished. g_cs->fullyTraversedSubcases.insert(hash(g_cs->subcaseStack)); } #if defined(__cpp_lib_uncaught_exceptions) && __cpp_lib_uncaught_exceptions >= 201411L && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200) if(std::uncaught_exceptions() > 0 #else if(std::uncaught_exception() #endif && g_cs->shouldLogCurrentException) { DOCTEST_ITERATE_THROUGH_REPORTERS( test_case_exception, {"exception thrown in subcase - will translate later " "when the whole test case has been exited (cannot " "translate while there is an active exception)", false}); g_cs->shouldLogCurrentException = false; } DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_end, DOCTEST_EMPTY); } } DOCTEST_CLANG_SUPPRESS_WARNING_POP DOCTEST_GCC_SUPPRESS_WARNING_POP DOCTEST_MSVC_SUPPRESS_WARNING_POP Subcase::operator bool() const { return m_entered; } Result::Result(bool passed, const String& decomposition) : m_passed(passed) , m_decomp(decomposition) {} ExpressionDecomposer::ExpressionDecomposer(assertType::Enum at) : m_at(at) {} TestSuite& TestSuite::operator*(const char* in) { m_test_suite = in; return *this; } TestCase::TestCase(funcType test, const char* file, unsigned line, const TestSuite& test_suite, const String& type, int template_id) { m_file = file; m_line = line; m_name = nullptr; // will be later overridden in operator* m_test_suite = test_suite.m_test_suite; m_description = test_suite.m_description; m_skip = test_suite.m_skip; m_no_breaks = test_suite.m_no_breaks; m_no_output = test_suite.m_no_output; m_may_fail = test_suite.m_may_fail; m_should_fail = test_suite.m_should_fail; m_expected_failures = test_suite.m_expected_failures; m_timeout = test_suite.m_timeout; m_test = test; m_type = type; m_template_id = template_id; } TestCase::TestCase(const TestCase& other) : TestCaseData() { *this = other; } DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(26434) // hides a non-virtual function TestCase& TestCase::operator=(const TestCase& other) { TestCaseData::operator=(other); m_test = other.m_test; m_type = other.m_type; m_template_id = other.m_template_id; m_full_name = other.m_full_name; if(m_template_id != -1) m_name = m_full_name.c_str(); return *this; } DOCTEST_MSVC_SUPPRESS_WARNING_POP TestCase& TestCase::operator*(const char* in) { m_name = in; // make a new name with an appended type for templated test case if(m_template_id != -1) { m_full_name = String(m_name) + "<" + m_type + ">"; // redirect the name to point to the newly constructed full name m_name = m_full_name.c_str(); } return *this; } bool TestCase::operator<(const TestCase& other) const { // this will be used only to differentiate between test cases - not relevant for sorting if(m_line != other.m_line) return m_line < other.m_line; const int name_cmp = strcmp(m_name, other.m_name); if(name_cmp != 0) return name_cmp < 0; const int file_cmp = m_file.compare(other.m_file); if(file_cmp != 0) return file_cmp < 0; return m_template_id < other.m_template_id; } // all the registered tests std::set<TestCase>& getRegisteredTests() { static std::set<TestCase> data; return data; } } // namespace detail namespace { using namespace detail; // for sorting tests by file/line bool fileOrderComparator(const TestCase* lhs, const TestCase* rhs) { // this is needed because MSVC gives different case for drive letters // for __FILE__ when evaluated in a header and a source file const int res = lhs->m_file.compare(rhs->m_file, bool(DOCTEST_MSVC)); if(res != 0) return res < 0; if(lhs->m_line != rhs->m_line) return lhs->m_line < rhs->m_line; return lhs->m_template_id < rhs->m_template_id; } // for sorting tests by suite/file/line bool suiteOrderComparator(const TestCase* lhs, const TestCase* rhs) { const int res = std::strcmp(lhs->m_test_suite, rhs->m_test_suite); if(res != 0) return res < 0; return fileOrderComparator(lhs, rhs); } // for sorting tests by name/suite/file/line bool nameOrderComparator(const TestCase* lhs, const TestCase* rhs) { const int res = std::strcmp(lhs->m_name, rhs->m_name); if(res != 0) return res < 0; return suiteOrderComparator(lhs, rhs); } DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") void color_to_stream(std::ostream& s, Color::Enum code) { static_cast<void>(s); // for DOCTEST_CONFIG_COLORS_NONE or DOCTEST_CONFIG_COLORS_WINDOWS static_cast<void>(code); // for DOCTEST_CONFIG_COLORS_NONE #ifdef DOCTEST_CONFIG_COLORS_ANSI if(g_no_colors || (isatty(STDOUT_FILENO) == false && getContextOptions()->force_colors == false)) return; auto col = ""; // clang-format off switch(code) { //!OCLINT missing break in switch statement / unnecessary default statement in covered switch statement case Color::Red: col = "[0;31m"; break; case Color::Green: col = "[0;32m"; break; case Color::Blue: col = "[0;34m"; break; case Color::Cyan: col = "[0;36m"; break; case Color::Yellow: col = "[0;33m"; break; case Color::Grey: col = "[1;30m"; break; case Color::LightGrey: col = "[0;37m"; break; case Color::BrightRed: col = "[1;31m"; break; case Color::BrightGreen: col = "[1;32m"; break; case Color::BrightWhite: col = "[1;37m"; break; case Color::Bright: // invalid case Color::None: case Color::White: default: col = "[0m"; } // clang-format on s << "\033" << col; #endif // DOCTEST_CONFIG_COLORS_ANSI #ifdef DOCTEST_CONFIG_COLORS_WINDOWS if(g_no_colors || (_isatty(_fileno(stdout)) == false && getContextOptions()->force_colors == false)) return; static struct ConsoleHelper { HANDLE stdoutHandle; WORD origFgAttrs; WORD origBgAttrs; ConsoleHelper() { stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO csbiInfo; GetConsoleScreenBufferInfo(stdoutHandle, &csbiInfo); origFgAttrs = csbiInfo.wAttributes & ~(BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY); origBgAttrs = csbiInfo.wAttributes & ~(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY); } } ch; #define DOCTEST_SET_ATTR(x) SetConsoleTextAttribute(ch.stdoutHandle, x | ch.origBgAttrs) // clang-format off switch (code) { case Color::White: DOCTEST_SET_ATTR(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE); break; case Color::Red: DOCTEST_SET_ATTR(FOREGROUND_RED); break; case Color::Green: DOCTEST_SET_ATTR(FOREGROUND_GREEN); break; case Color::Blue: DOCTEST_SET_ATTR(FOREGROUND_BLUE); break; case Color::Cyan: DOCTEST_SET_ATTR(FOREGROUND_BLUE | FOREGROUND_GREEN); break; case Color::Yellow: DOCTEST_SET_ATTR(FOREGROUND_RED | FOREGROUND_GREEN); break; case Color::Grey: DOCTEST_SET_ATTR(0); break; case Color::LightGrey: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY); break; case Color::BrightRed: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_RED); break; case Color::BrightGreen: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_GREEN); break; case Color::BrightWhite: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE); break; case Color::None: case Color::Bright: // invalid default: DOCTEST_SET_ATTR(ch.origFgAttrs); } // clang-format on #endif // DOCTEST_CONFIG_COLORS_WINDOWS } DOCTEST_CLANG_SUPPRESS_WARNING_POP std::vector<const IExceptionTranslator*>& getExceptionTranslators() { static std::vector<const IExceptionTranslator*> data; return data; } String translateActiveException() { #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS String res; auto& translators = getExceptionTranslators(); for(auto& curr : translators) if(curr->translate(res)) return res; // clang-format off DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wcatch-value") try { throw; } catch(std::exception& ex) { return ex.what(); } catch(std::string& msg) { return msg.c_str(); } catch(const char* msg) { return msg; } catch(...) { return "unknown exception"; } DOCTEST_GCC_SUPPRESS_WARNING_POP // clang-format on #else // DOCTEST_CONFIG_NO_EXCEPTIONS return ""; #endif // DOCTEST_CONFIG_NO_EXCEPTIONS } } // namespace namespace detail { // used by the macros for registering tests int regTest(const TestCase& tc) { getRegisteredTests().insert(tc); return 0; } // sets the current test suite int setTestSuite(const TestSuite& ts) { doctest_detail_test_suite_ns::getCurrentTestSuite() = ts; return 0; } #ifdef DOCTEST_IS_DEBUGGER_ACTIVE bool isDebuggerActive() { return DOCTEST_IS_DEBUGGER_ACTIVE(); } #else // DOCTEST_IS_DEBUGGER_ACTIVE #ifdef DOCTEST_PLATFORM_LINUX class ErrnoGuard { public: ErrnoGuard() : m_oldErrno(errno) {} ~ErrnoGuard() { errno = m_oldErrno; } private: int m_oldErrno; }; // See the comments in Catch2 for the reasoning behind this implementation: // https://github.com/catchorg/Catch2/blob/v2.13.1/include/internal/catch_debugger.cpp#L79-L102 bool isDebuggerActive() { ErrnoGuard guard; std::ifstream in("/proc/self/status"); for(std::string line; std::getline(in, line);) { static const int PREFIX_LEN = 11; if(line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0) { return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0'; } } return false; } #elif defined(DOCTEST_PLATFORM_MAC) // The following function is taken directly from the following technical note: // https://developer.apple.com/library/archive/qa/qa1361/_index.html // Returns true if the current process is being debugged (either // running under the debugger or has a debugger attached post facto). bool isDebuggerActive() { int mib[4]; kinfo_proc info; size_t size; // Initialize the flags so that, if sysctl fails for some bizarre // reason, we get a predictable result. info.kp_proc.p_flag = 0; // Initialize mib, which tells sysctl the info we want, in this case // we're looking for information about a specific process ID. mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = getpid(); // Call sysctl. size = sizeof(info); if(sysctl(mib, DOCTEST_COUNTOF(mib), &info, &size, 0, 0) != 0) { std::cerr << "\nCall to sysctl failed - unable to determine if debugger is active **\n"; return false; } // We're being debugged if the P_TRACED flag is set. return ((info.kp_proc.p_flag & P_TRACED) != 0); } #elif DOCTEST_MSVC || defined(__MINGW32__) || defined(__MINGW64__) bool isDebuggerActive() { return ::IsDebuggerPresent() != 0; } #else bool isDebuggerActive() { return false; } #endif // Platform #endif // DOCTEST_IS_DEBUGGER_ACTIVE void registerExceptionTranslatorImpl(const IExceptionTranslator* et) { if(std::find(getExceptionTranslators().begin(), getExceptionTranslators().end(), et) == getExceptionTranslators().end()) getExceptionTranslators().push_back(et); } DOCTEST_THREAD_LOCAL std::vector<IContextScope*> g_infoContexts; // for logging with INFO() ContextScopeBase::ContextScopeBase() { g_infoContexts.push_back(this); } ContextScopeBase::ContextScopeBase(ContextScopeBase&& other) noexcept { if (other.need_to_destroy) { other.destroy(); } other.need_to_destroy = false; g_infoContexts.push_back(this); } DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4996) // std::uncaught_exception is deprecated in C++17 DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") // destroy cannot be inlined into the destructor because that would mean calling stringify after // ContextScope has been destroyed (base class destructors run after derived class destructors). // Instead, ContextScope calls this method directly from its destructor. void ContextScopeBase::destroy() { #if defined(__cpp_lib_uncaught_exceptions) && __cpp_lib_uncaught_exceptions >= 201411L && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200) if(std::uncaught_exceptions() > 0) { #else if(std::uncaught_exception()) { #endif std::ostringstream s; this->stringify(&s); g_cs->stringifiedContexts.push_back(s.str().c_str()); } g_infoContexts.pop_back(); } DOCTEST_CLANG_SUPPRESS_WARNING_POP DOCTEST_GCC_SUPPRESS_WARNING_POP DOCTEST_MSVC_SUPPRESS_WARNING_POP } // namespace detail namespace { using namespace detail; #if !defined(DOCTEST_CONFIG_POSIX_SIGNALS) && !defined(DOCTEST_CONFIG_WINDOWS_SEH) struct FatalConditionHandler { static void reset() {} static void allocateAltStackMem() {} static void freeAltStackMem() {} }; #else // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH void reportFatal(const std::string&); #ifdef DOCTEST_PLATFORM_WINDOWS struct SignalDefs { DWORD id; const char* name; }; // There is no 1-1 mapping between signals and windows exceptions. // Windows can easily distinguish between SO and SigSegV, // but SigInt, SigTerm, etc are handled differently. SignalDefs signalDefs[] = { {static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal"}, {static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow"}, {static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal"}, {static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error"}, }; struct FatalConditionHandler { static LONG CALLBACK handleException(PEXCEPTION_POINTERS ExceptionInfo) { // Multiple threads may enter this filter/handler at once. We want the error message to be printed on the // console just once no matter how many threads have crashed. DOCTEST_DECLARE_STATIC_MUTEX(mutex) static bool execute = true; { DOCTEST_LOCK_MUTEX(mutex) if(execute) { bool reported = false; for(size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { if(ExceptionInfo->ExceptionRecord->ExceptionCode == signalDefs[i].id) { reportFatal(signalDefs[i].name); reported = true; break; } } if(reported == false) reportFatal("Unhandled SEH exception caught"); if(isDebuggerActive() && !g_cs->no_breaks) DOCTEST_BREAK_INTO_DEBUGGER(); } execute = false; } std::exit(EXIT_FAILURE); } static void allocateAltStackMem() {} static void freeAltStackMem() {} FatalConditionHandler() { isSet = true; // 32k seems enough for doctest to handle stack overflow, // but the value was found experimentally, so there is no strong guarantee guaranteeSize = 32 * 1024; // Register an unhandled exception filter previousTop = SetUnhandledExceptionFilter(handleException); // Pass in guarantee size to be filled SetThreadStackGuarantee(&guaranteeSize); // On Windows uncaught exceptions from another thread, exceptions from // destructors, or calls to std::terminate are not a SEH exception // The terminal handler gets called when: // - std::terminate is called FROM THE TEST RUNNER THREAD // - an exception is thrown from a destructor FROM THE TEST RUNNER THREAD original_terminate_handler = std::get_terminate(); std::set_terminate([]() DOCTEST_NOEXCEPT { reportFatal("Terminate handler called"); if(isDebuggerActive() && !g_cs->no_breaks) DOCTEST_BREAK_INTO_DEBUGGER(); std::exit(EXIT_FAILURE); // explicitly exit - otherwise the SIGABRT handler may be called as well }); // SIGABRT is raised when: // - std::terminate is called FROM A DIFFERENT THREAD // - an exception is thrown from a destructor FROM A DIFFERENT THREAD // - an uncaught exception is thrown FROM A DIFFERENT THREAD prev_sigabrt_handler = std::signal(SIGABRT, [](int signal) DOCTEST_NOEXCEPT { if(signal == SIGABRT) { reportFatal("SIGABRT - Abort (abnormal termination) signal"); if(isDebuggerActive() && !g_cs->no_breaks) DOCTEST_BREAK_INTO_DEBUGGER(); std::exit(EXIT_FAILURE); } }); // The following settings are taken from google test, and more // specifically from UnitTest::Run() inside of gtest.cc // the user does not want to see pop-up dialogs about crashes prev_error_mode_1 = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); // This forces the abort message to go to stderr in all circumstances. prev_error_mode_2 = _set_error_mode(_OUT_TO_STDERR); // In the debug version, Visual Studio pops up a separate dialog // offering a choice to debug the aborted program - we want to disable that. prev_abort_behavior = _set_abort_behavior(0x0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // In debug mode, the Windows CRT can crash with an assertion over invalid // input (e.g. passing an invalid file descriptor). The default handling // for these assertions is to pop up a dialog and wait for user input. // Instead ask the CRT to dump such assertions to stderr non-interactively. prev_report_mode = _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); prev_report_file = _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); } static void reset() { if(isSet) { // Unregister handler and restore the old guarantee SetUnhandledExceptionFilter(previousTop); SetThreadStackGuarantee(&guaranteeSize); std::set_terminate(original_terminate_handler); std::signal(SIGABRT, prev_sigabrt_handler); SetErrorMode(prev_error_mode_1); _set_error_mode(prev_error_mode_2); _set_abort_behavior(prev_abort_behavior, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); static_cast<void>(_CrtSetReportMode(_CRT_ASSERT, prev_report_mode)); static_cast<void>(_CrtSetReportFile(_CRT_ASSERT, prev_report_file)); isSet = false; } } ~FatalConditionHandler() { reset(); } private: static UINT prev_error_mode_1; static int prev_error_mode_2; static unsigned int prev_abort_behavior; static int prev_report_mode; static _HFILE prev_report_file; static void (DOCTEST_CDECL *prev_sigabrt_handler)(int); static std::terminate_handler original_terminate_handler; static bool isSet; static ULONG guaranteeSize; static LPTOP_LEVEL_EXCEPTION_FILTER previousTop; }; UINT FatalConditionHandler::prev_error_mode_1; int FatalConditionHandler::prev_error_mode_2; unsigned int FatalConditionHandler::prev_abort_behavior; int FatalConditionHandler::prev_report_mode; _HFILE FatalConditionHandler::prev_report_file; void (DOCTEST_CDECL *FatalConditionHandler::prev_sigabrt_handler)(int); std::terminate_handler FatalConditionHandler::original_terminate_handler; bool FatalConditionHandler::isSet = false; ULONG FatalConditionHandler::guaranteeSize = 0; LPTOP_LEVEL_EXCEPTION_FILTER FatalConditionHandler::previousTop = nullptr; #else // DOCTEST_PLATFORM_WINDOWS struct SignalDefs { int id; const char* name; }; SignalDefs signalDefs[] = {{SIGINT, "SIGINT - Terminal interrupt signal"}, {SIGILL, "SIGILL - Illegal instruction signal"}, {SIGFPE, "SIGFPE - Floating point error signal"}, {SIGSEGV, "SIGSEGV - Segmentation violation signal"}, {SIGTERM, "SIGTERM - Termination request signal"}, {SIGABRT, "SIGABRT - Abort (abnormal termination) signal"}}; struct FatalConditionHandler { static bool isSet; static struct sigaction oldSigActions[DOCTEST_COUNTOF(signalDefs)]; static stack_t oldSigStack; static size_t altStackSize; static char* altStackMem; static void handleSignal(int sig) { const char* name = "<unknown signal>"; for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { SignalDefs& def = signalDefs[i]; if(sig == def.id) { name = def.name; break; } } reset(); reportFatal(name); raise(sig); } static void allocateAltStackMem() { altStackMem = new char[altStackSize]; } static void freeAltStackMem() { delete[] altStackMem; } FatalConditionHandler() { isSet = true; stack_t sigStack; sigStack.ss_sp = altStackMem; sigStack.ss_size = altStackSize; sigStack.ss_flags = 0; sigaltstack(&sigStack, &oldSigStack); struct sigaction sa = {}; sa.sa_handler = handleSignal; sa.sa_flags = SA_ONSTACK; for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { sigaction(signalDefs[i].id, &sa, &oldSigActions[i]); } } ~FatalConditionHandler() { reset(); } static void reset() { if(isSet) { // Set signals back to previous values -- hopefully nobody overwrote them in the meantime for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { sigaction(signalDefs[i].id, &oldSigActions[i], nullptr); } // Return the old stack sigaltstack(&oldSigStack, nullptr); isSet = false; } } }; bool FatalConditionHandler::isSet = false; struct sigaction FatalConditionHandler::oldSigActions[DOCTEST_COUNTOF(signalDefs)] = {}; stack_t FatalConditionHandler::oldSigStack = {}; size_t FatalConditionHandler::altStackSize = 4 * SIGSTKSZ; char* FatalConditionHandler::altStackMem = nullptr; #endif // DOCTEST_PLATFORM_WINDOWS #endif // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH } // namespace namespace { using namespace detail; #ifdef DOCTEST_PLATFORM_WINDOWS #define DOCTEST_OUTPUT_DEBUG_STRING(text) ::OutputDebugStringA(text) #else // TODO: integration with XCode and other IDEs #define DOCTEST_OUTPUT_DEBUG_STRING(text) #endif // Platform void addAssert(assertType::Enum at) { if((at & assertType::is_warn) == 0) //!OCLINT bitwise operator in conditional g_cs->numAssertsCurrentTest_atomic++; } void addFailedAssert(assertType::Enum at) { if((at & assertType::is_warn) == 0) //!OCLINT bitwise operator in conditional g_cs->numAssertsFailedCurrentTest_atomic++; } #if defined(DOCTEST_CONFIG_POSIX_SIGNALS) || defined(DOCTEST_CONFIG_WINDOWS_SEH) void reportFatal(const std::string& message) { g_cs->failure_flags |= TestCaseFailureReason::Crash; DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_exception, {message.c_str(), true}); while (g_cs->subcaseStack.size()) { g_cs->subcaseStack.pop_back(); DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_end, DOCTEST_EMPTY); } g_cs->finalizeTestCaseData(); DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_end, *g_cs); DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_end, *g_cs); } #endif // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH } // namespace AssertData::AssertData(assertType::Enum at, const char* file, int line, const char* expr, const char* exception_type, const StringContains& exception_string) : m_test_case(g_cs->currentTest), m_at(at), m_file(file), m_line(line), m_expr(expr), m_failed(true), m_threw(false), m_threw_as(false), m_exception_type(exception_type), m_exception_string(exception_string) { #if DOCTEST_MSVC if (m_expr[0] == ' ') // this happens when variadic macros are disabled under MSVC ++m_expr; #endif // MSVC } namespace detail { ResultBuilder::ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, const char* exception_type, const String& exception_string) : AssertData(at, file, line, expr, exception_type, exception_string) { } ResultBuilder::ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, const char* exception_type, const Contains& exception_string) : AssertData(at, file, line, expr, exception_type, exception_string) { } void ResultBuilder::setResult(const Result& res) { m_decomp = res.m_decomp; m_failed = !res.m_passed; } void ResultBuilder::translateException() { m_threw = true; m_exception = translateActiveException(); } bool ResultBuilder::log() { if(m_at & assertType::is_throws) { //!OCLINT bitwise operator in conditional m_failed = !m_threw; } else if((m_at & assertType::is_throws_as) && (m_at & assertType::is_throws_with)) { //!OCLINT m_failed = !m_threw_as || !m_exception_string.check(m_exception); } else if(m_at & assertType::is_throws_as) { //!OCLINT bitwise operator in conditional m_failed = !m_threw_as; } else if(m_at & assertType::is_throws_with) { //!OCLINT bitwise operator in conditional m_failed = !m_exception_string.check(m_exception); } else if(m_at & assertType::is_nothrow) { //!OCLINT bitwise operator in conditional m_failed = m_threw; } if(m_exception.size()) m_exception = "\"" + m_exception + "\""; if(is_running_in_test) { addAssert(m_at); DOCTEST_ITERATE_THROUGH_REPORTERS(log_assert, *this); if(m_failed) addFailedAssert(m_at); } else if(m_failed) { failed_out_of_a_testing_context(*this); } return m_failed && isDebuggerActive() && !getContextOptions()->no_breaks && (g_cs->currentTest == nullptr || !g_cs->currentTest->m_no_breaks); // break into debugger } void ResultBuilder::react() const { if(m_failed && checkIfShouldThrow(m_at)) throwException(); } void failed_out_of_a_testing_context(const AssertData& ad) { if(g_cs->ah) g_cs->ah(ad); else std::abort(); } bool decomp_assert(assertType::Enum at, const char* file, int line, const char* expr, const Result& result) { bool failed = !result.m_passed; // ################################################################################### // IF THE DEBUGGER BREAKS HERE - GO 1 LEVEL UP IN THE CALLSTACK FOR THE FAILING ASSERT // THIS IS THE EFFECT OF HAVING 'DOCTEST_CONFIG_SUPER_FAST_ASSERTS' DEFINED // ################################################################################### DOCTEST_ASSERT_OUT_OF_TESTS(result.m_decomp); DOCTEST_ASSERT_IN_TESTS(result.m_decomp); return !failed; } MessageBuilder::MessageBuilder(const char* file, int line, assertType::Enum severity) { m_stream = tlssPush(); m_file = file; m_line = line; m_severity = severity; } MessageBuilder::~MessageBuilder() { if (!logged) tlssPop(); } DOCTEST_DEFINE_INTERFACE(IExceptionTranslator) bool MessageBuilder::log() { if (!logged) { m_string = tlssPop(); logged = true; } DOCTEST_ITERATE_THROUGH_REPORTERS(log_message, *this); const bool isWarn = m_severity & assertType::is_warn; // warn is just a message in this context so we don't treat it as an assert if(!isWarn) { addAssert(m_severity); addFailedAssert(m_severity); } return isDebuggerActive() && !getContextOptions()->no_breaks && !isWarn && (g_cs->currentTest == nullptr || !g_cs->currentTest->m_no_breaks); // break into debugger } void MessageBuilder::react() { if(m_severity & assertType::is_require) //!OCLINT bitwise operator in conditional throwException(); } } // namespace detail namespace { using namespace detail; // clang-format off // ================================================================================================= // The following code has been taken verbatim from Catch2/include/internal/catch_xmlwriter.h/cpp // This is done so cherry-picking bug fixes is trivial - even the style/formatting is untouched. // ================================================================================================= class XmlEncode { public: enum ForWhat { ForTextNodes, ForAttributes }; XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes ); void encodeTo( std::ostream& os ) const; friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ); private: std::string m_str; ForWhat m_forWhat; }; class XmlWriter { public: class ScopedElement { public: ScopedElement( XmlWriter* writer ); ScopedElement( ScopedElement&& other ) DOCTEST_NOEXCEPT; ScopedElement& operator=( ScopedElement&& other ) DOCTEST_NOEXCEPT; ~ScopedElement(); ScopedElement& writeText( std::string const& text, bool indent = true ); template<typename T> ScopedElement& writeAttribute( std::string const& name, T const& attribute ) { m_writer->writeAttribute( name, attribute ); return *this; } private: mutable XmlWriter* m_writer = nullptr; }; #ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM XmlWriter( std::ostream& os = std::cout ); #else // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM XmlWriter( std::ostream& os ); #endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM ~XmlWriter(); XmlWriter( XmlWriter const& ) = delete; XmlWriter& operator=( XmlWriter const& ) = delete; XmlWriter& startElement( std::string const& name ); ScopedElement scopedElement( std::string const& name ); XmlWriter& endElement(); XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ); XmlWriter& writeAttribute( std::string const& name, const char* attribute ); XmlWriter& writeAttribute( std::string const& name, bool attribute ); template<typename T> XmlWriter& writeAttribute( std::string const& name, T const& attribute ) { std::stringstream rss; rss << attribute; return writeAttribute( name, rss.str() ); } XmlWriter& writeText( std::string const& text, bool indent = true ); //XmlWriter& writeComment( std::string const& text ); //void writeStylesheetRef( std::string const& url ); //XmlWriter& writeBlankLine(); void ensureTagClosed(); void writeDeclaration(); private: void newlineIfNecessary(); bool m_tagIsOpen = false; bool m_needsNewline = false; std::vector<std::string> m_tags; std::string m_indent; std::ostream& m_os; }; // ================================================================================================= // The following code has been taken verbatim from Catch2/include/internal/catch_xmlwriter.h/cpp // This is done so cherry-picking bug fixes is trivial - even the style/formatting is untouched. // ================================================================================================= using uchar = unsigned char; namespace { size_t trailingBytes(unsigned char c) { if ((c & 0xE0) == 0xC0) { return 2; } if ((c & 0xF0) == 0xE0) { return 3; } if ((c & 0xF8) == 0xF0) { return 4; } DOCTEST_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); } uint32_t headerValue(unsigned char c) { if ((c & 0xE0) == 0xC0) { return c & 0x1F; } if ((c & 0xF0) == 0xE0) { return c & 0x0F; } if ((c & 0xF8) == 0xF0) { return c & 0x07; } DOCTEST_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); } void hexEscapeChar(std::ostream& os, unsigned char c) { std::ios_base::fmtflags f(os.flags()); os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(c); os.flags(f); } } // anonymous namespace XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat ) : m_str( str ), m_forWhat( forWhat ) {} void XmlEncode::encodeTo( std::ostream& os ) const { // Apostrophe escaping not necessary if we always use " to write attributes // (see: https://www.w3.org/TR/xml/#syntax) for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) { uchar c = m_str[idx]; switch (c) { case '<': os << "&lt;"; break; case '&': os << "&amp;"; break; case '>': // See: https://www.w3.org/TR/xml/#syntax if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']') os << "&gt;"; else os << c; break; case '\"': if (m_forWhat == ForAttributes) os << "&quot;"; else os << c; break; default: // Check for control characters and invalid utf-8 // Escape control characters in standard ascii // see https://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) { hexEscapeChar(os, c); break; } // Plain ASCII: Write it to stream if (c < 0x7F) { os << c; break; } // UTF-8 territory // Check if the encoding is valid and if it is not, hex escape bytes. // Important: We do not check the exact decoded values for validity, only the encoding format // First check that this bytes is a valid lead byte: // This means that it is not encoded as 1111 1XXX // Or as 10XX XXXX if (c < 0xC0 || c >= 0xF8) { hexEscapeChar(os, c); break; } auto encBytes = trailingBytes(c); // Are there enough bytes left to avoid accessing out-of-bounds memory? if (idx + encBytes - 1 >= m_str.size()) { hexEscapeChar(os, c); break; } // The header is valid, check data // The next encBytes bytes must together be a valid utf-8 // This means: bitpattern 10XX XXXX and the extracted value is sane (ish) bool valid = true; uint32_t value = headerValue(c); for (std::size_t n = 1; n < encBytes; ++n) { uchar nc = m_str[idx + n]; valid &= ((nc & 0xC0) == 0x80); value = (value << 6) | (nc & 0x3F); } if ( // Wrong bit pattern of following bytes (!valid) || // Overlong encodings (value < 0x80) || ( value < 0x800 && encBytes > 2) || // removed "0x80 <= value &&" because redundant (0x800 < value && value < 0x10000 && encBytes > 3) || // Encoded value out of range (value >= 0x110000) ) { hexEscapeChar(os, c); break; } // If we got here, this is in fact a valid(ish) utf-8 sequence for (std::size_t n = 0; n < encBytes; ++n) { os << m_str[idx + n]; } idx += encBytes - 1; break; } } } std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) { xmlEncode.encodeTo( os ); return os; } XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer ) : m_writer( writer ) {} XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) DOCTEST_NOEXCEPT : m_writer( other.m_writer ){ other.m_writer = nullptr; } XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) DOCTEST_NOEXCEPT { if ( m_writer ) { m_writer->endElement(); } m_writer = other.m_writer; other.m_writer = nullptr; return *this; } XmlWriter::ScopedElement::~ScopedElement() { if( m_writer ) m_writer->endElement(); } XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) { m_writer->writeText( text, indent ); return *this; } XmlWriter::XmlWriter( std::ostream& os ) : m_os( os ) { // writeDeclaration(); // called explicitly by the reporters that use the writer class - see issue #627 } XmlWriter::~XmlWriter() { while( !m_tags.empty() ) endElement(); } XmlWriter& XmlWriter::startElement( std::string const& name ) { ensureTagClosed(); newlineIfNecessary(); m_os << m_indent << '<' << name; m_tags.push_back( name ); m_indent += " "; m_tagIsOpen = true; return *this; } XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) { ScopedElement scoped( this ); startElement( name ); return scoped; } XmlWriter& XmlWriter::endElement() { newlineIfNecessary(); m_indent = m_indent.substr( 0, m_indent.size()-2 ); if( m_tagIsOpen ) { m_os << "/>"; m_tagIsOpen = false; } else { m_os << m_indent << "</" << m_tags.back() << ">"; } m_os << std::endl; m_tags.pop_back(); return *this; } XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) { if( !name.empty() && !attribute.empty() ) m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; return *this; } XmlWriter& XmlWriter::writeAttribute( std::string const& name, const char* attribute ) { if( !name.empty() && attribute && attribute[0] != '\0' ) m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; return *this; } XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) { m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"'; return *this; } XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) { if( !text.empty() ){ bool tagWasOpen = m_tagIsOpen; ensureTagClosed(); if( tagWasOpen && indent ) m_os << m_indent; m_os << XmlEncode( text ); m_needsNewline = true; } return *this; } //XmlWriter& XmlWriter::writeComment( std::string const& text ) { // ensureTagClosed(); // m_os << m_indent << "<!--" << text << "-->"; // m_needsNewline = true; // return *this; //} //void XmlWriter::writeStylesheetRef( std::string const& url ) { // m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n"; //} //XmlWriter& XmlWriter::writeBlankLine() { // ensureTagClosed(); // m_os << '\n'; // return *this; //} void XmlWriter::ensureTagClosed() { if( m_tagIsOpen ) { m_os << ">" << std::endl; m_tagIsOpen = false; } } void XmlWriter::writeDeclaration() { m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; } void XmlWriter::newlineIfNecessary() { if( m_needsNewline ) { m_os << std::endl; m_needsNewline = false; } } // ================================================================================================= // End of copy-pasted code from Catch // ================================================================================================= // clang-format on struct XmlReporter : public IReporter { XmlWriter xml; DOCTEST_DECLARE_MUTEX(mutex) // caching pointers/references to objects of these types - safe to do const ContextOptions& opt; const TestCaseData* tc = nullptr; XmlReporter(const ContextOptions& co) : xml(*co.cout) , opt(co) {} void log_contexts() { int num_contexts = get_num_active_contexts(); if(num_contexts) { auto contexts = get_active_contexts(); std::stringstream ss; for(int i = 0; i < num_contexts; ++i) { contexts[i]->stringify(&ss); xml.scopedElement("Info").writeText(ss.str()); ss.str(""); } } } unsigned line(unsigned l) const { return opt.no_line_numbers ? 0 : l; } void test_case_start_impl(const TestCaseData& in) { bool open_ts_tag = false; if(tc != nullptr) { // we have already opened a test suite if(std::strcmp(tc->m_test_suite, in.m_test_suite) != 0) { xml.endElement(); open_ts_tag = true; } } else { open_ts_tag = true; // first test case ==> first test suite } if(open_ts_tag) { xml.startElement("TestSuite"); xml.writeAttribute("name", in.m_test_suite); } tc = &in; xml.startElement("TestCase") .writeAttribute("name", in.m_name) .writeAttribute("filename", skipPathFromFilename(in.m_file.c_str())) .writeAttribute("line", line(in.m_line)) .writeAttribute("description", in.m_description); if(Approx(in.m_timeout) != 0) xml.writeAttribute("timeout", in.m_timeout); if(in.m_may_fail) xml.writeAttribute("may_fail", true); if(in.m_should_fail) xml.writeAttribute("should_fail", true); } // ========================================================================================= // WHAT FOLLOWS ARE OVERRIDES OF THE VIRTUAL METHODS OF THE REPORTER INTERFACE // ========================================================================================= void report_query(const QueryData& in) override { test_run_start(); if(opt.list_reporters) { for(auto& curr : getListeners()) xml.scopedElement("Listener") .writeAttribute("priority", curr.first.first) .writeAttribute("name", curr.first.second); for(auto& curr : getReporters()) xml.scopedElement("Reporter") .writeAttribute("priority", curr.first.first) .writeAttribute("name", curr.first.second); } else if(opt.count || opt.list_test_cases) { for(unsigned i = 0; i < in.num_data; ++i) { xml.scopedElement("TestCase").writeAttribute("name", in.data[i]->m_name) .writeAttribute("testsuite", in.data[i]->m_test_suite) .writeAttribute("filename", skipPathFromFilename(in.data[i]->m_file.c_str())) .writeAttribute("line", line(in.data[i]->m_line)) .writeAttribute("skipped", in.data[i]->m_skip); } xml.scopedElement("OverallResultsTestCases") .writeAttribute("unskipped", in.run_stats->numTestCasesPassingFilters); } else if(opt.list_test_suites) { for(unsigned i = 0; i < in.num_data; ++i) xml.scopedElement("TestSuite").writeAttribute("name", in.data[i]->m_test_suite); xml.scopedElement("OverallResultsTestCases") .writeAttribute("unskipped", in.run_stats->numTestCasesPassingFilters); xml.scopedElement("OverallResultsTestSuites") .writeAttribute("unskipped", in.run_stats->numTestSuitesPassingFilters); } xml.endElement(); } void test_run_start() override { xml.writeDeclaration(); // remove .exe extension - mainly to have the same output on UNIX and Windows std::string binary_name = skipPathFromFilename(opt.binary_name.c_str()); #ifdef DOCTEST_PLATFORM_WINDOWS if(binary_name.rfind(".exe") != std::string::npos) binary_name = binary_name.substr(0, binary_name.length() - 4); #endif // DOCTEST_PLATFORM_WINDOWS xml.startElement("doctest").writeAttribute("binary", binary_name); if(opt.no_version == false) xml.writeAttribute("version", DOCTEST_VERSION_STR); // only the consequential ones (TODO: filters) xml.scopedElement("Options") .writeAttribute("order_by", opt.order_by.c_str()) .writeAttribute("rand_seed", opt.rand_seed) .writeAttribute("first", opt.first) .writeAttribute("last", opt.last) .writeAttribute("abort_after", opt.abort_after) .writeAttribute("subcase_filter_levels", opt.subcase_filter_levels) .writeAttribute("case_sensitive", opt.case_sensitive) .writeAttribute("no_throw", opt.no_throw) .writeAttribute("no_skip", opt.no_skip); } void test_run_end(const TestRunStats& p) override { if(tc) // the TestSuite tag - only if there has been at least 1 test case xml.endElement(); xml.scopedElement("OverallResultsAsserts") .writeAttribute("successes", p.numAsserts - p.numAssertsFailed) .writeAttribute("failures", p.numAssertsFailed); xml.startElement("OverallResultsTestCases") .writeAttribute("successes", p.numTestCasesPassingFilters - p.numTestCasesFailed) .writeAttribute("failures", p.numTestCasesFailed); if(opt.no_skipped_summary == false) xml.writeAttribute("skipped", p.numTestCases - p.numTestCasesPassingFilters); xml.endElement(); xml.endElement(); } void test_case_start(const TestCaseData& in) override { test_case_start_impl(in); xml.ensureTagClosed(); } void test_case_reenter(const TestCaseData&) override {} void test_case_end(const CurrentTestCaseStats& st) override { xml.startElement("OverallResultsAsserts") .writeAttribute("successes", st.numAssertsCurrentTest - st.numAssertsFailedCurrentTest) .writeAttribute("failures", st.numAssertsFailedCurrentTest) .writeAttribute("test_case_success", st.testCaseSuccess); if(opt.duration) xml.writeAttribute("duration", st.seconds); if(tc->m_expected_failures) xml.writeAttribute("expected_failures", tc->m_expected_failures); xml.endElement(); xml.endElement(); } void test_case_exception(const TestCaseException& e) override { DOCTEST_LOCK_MUTEX(mutex) xml.scopedElement("Exception") .writeAttribute("crash", e.is_crash) .writeText(e.error_string.c_str()); } void subcase_start(const SubcaseSignature& in) override { xml.startElement("SubCase") .writeAttribute("name", in.m_name) .writeAttribute("filename", skipPathFromFilename(in.m_file)) .writeAttribute("line", line(in.m_line)); xml.ensureTagClosed(); } void subcase_end() override { xml.endElement(); } void log_assert(const AssertData& rb) override { if(!rb.m_failed && !opt.success) return; DOCTEST_LOCK_MUTEX(mutex) xml.startElement("Expression") .writeAttribute("success", !rb.m_failed) .writeAttribute("type", assertString(rb.m_at)) .writeAttribute("filename", skipPathFromFilename(rb.m_file)) .writeAttribute("line", line(rb.m_line)); xml.scopedElement("Original").writeText(rb.m_expr); if(rb.m_threw) xml.scopedElement("Exception").writeText(rb.m_exception.c_str()); if(rb.m_at & assertType::is_throws_as) xml.scopedElement("ExpectedException").writeText(rb.m_exception_type); if(rb.m_at & assertType::is_throws_with) xml.scopedElement("ExpectedExceptionString").writeText(rb.m_exception_string.c_str()); if((rb.m_at & assertType::is_normal) && !rb.m_threw) xml.scopedElement("Expanded").writeText(rb.m_decomp.c_str()); log_contexts(); xml.endElement(); } void log_message(const MessageData& mb) override { DOCTEST_LOCK_MUTEX(mutex) xml.startElement("Message") .writeAttribute("type", failureString(mb.m_severity)) .writeAttribute("filename", skipPathFromFilename(mb.m_file)) .writeAttribute("line", line(mb.m_line)); xml.scopedElement("Text").writeText(mb.m_string.c_str()); log_contexts(); xml.endElement(); } void test_case_skipped(const TestCaseData& in) override { if(opt.no_skipped_summary == false) { test_case_start_impl(in); xml.writeAttribute("skipped", "true"); xml.endElement(); } } }; DOCTEST_REGISTER_REPORTER("xml", 0, XmlReporter); void fulltext_log_assert_to_stream(std::ostream& s, const AssertData& rb) { if((rb.m_at & (assertType::is_throws_as | assertType::is_throws_with)) == 0) //!OCLINT bitwise operator in conditional s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << " ) " << Color::None; if(rb.m_at & assertType::is_throws) { //!OCLINT bitwise operator in conditional s << (rb.m_threw ? "threw as expected!" : "did NOT throw at all!") << "\n"; } else if((rb.m_at & assertType::is_throws_as) && (rb.m_at & assertType::is_throws_with)) { //!OCLINT s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << ", \"" << rb.m_exception_string.c_str() << "\", " << rb.m_exception_type << " ) " << Color::None; if(rb.m_threw) { if(!rb.m_failed) { s << "threw as expected!\n"; } else { s << "threw a DIFFERENT exception! (contents: " << rb.m_exception << ")\n"; } } else { s << "did NOT throw at all!\n"; } } else if(rb.m_at & assertType::is_throws_as) { //!OCLINT bitwise operator in conditional s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << ", " << rb.m_exception_type << " ) " << Color::None << (rb.m_threw ? (rb.m_threw_as ? "threw as expected!" : "threw a DIFFERENT exception: ") : "did NOT throw at all!") << Color::Cyan << rb.m_exception << "\n"; } else if(rb.m_at & assertType::is_throws_with) { //!OCLINT bitwise operator in conditional s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << ", \"" << rb.m_exception_string.c_str() << "\" ) " << Color::None << (rb.m_threw ? (!rb.m_failed ? "threw as expected!" : "threw a DIFFERENT exception: ") : "did NOT throw at all!") << Color::Cyan << rb.m_exception << "\n"; } else if(rb.m_at & assertType::is_nothrow) { //!OCLINT bitwise operator in conditional s << (rb.m_threw ? "THREW exception: " : "didn't throw!") << Color::Cyan << rb.m_exception << "\n"; } else { s << (rb.m_threw ? "THREW exception: " : (!rb.m_failed ? "is correct!\n" : "is NOT correct!\n")); if(rb.m_threw) s << rb.m_exception << "\n"; else s << " values: " << assertString(rb.m_at) << "( " << rb.m_decomp << " )\n"; } } // TODO: // - log_message() // - respond to queries // - honor remaining options // - more attributes in tags struct JUnitReporter : public IReporter { XmlWriter xml; DOCTEST_DECLARE_MUTEX(mutex) Timer timer; std::vector<String> deepestSubcaseStackNames; struct JUnitTestCaseData { static std::string getCurrentTimestamp() { // Beware, this is not reentrant because of backward compatibility issues // Also, UTC only, again because of backward compatibility (%z is C++11) time_t rawtime; std::time(&rawtime); auto const timeStampSize = sizeof("2017-01-16T17:06:45Z"); std::tm timeInfo; #ifdef DOCTEST_PLATFORM_WINDOWS gmtime_s(&timeInfo, &rawtime); #else // DOCTEST_PLATFORM_WINDOWS gmtime_r(&rawtime, &timeInfo); #endif // DOCTEST_PLATFORM_WINDOWS char timeStamp[timeStampSize]; const char* const fmt = "%Y-%m-%dT%H:%M:%SZ"; std::strftime(timeStamp, timeStampSize, fmt, &timeInfo); return std::string(timeStamp); } struct JUnitTestMessage { JUnitTestMessage(const std::string& _message, const std::string& _type, const std::string& _details) : message(_message), type(_type), details(_details) {} JUnitTestMessage(const std::string& _message, const std::string& _details) : message(_message), type(), details(_details) {} std::string message, type, details; }; struct JUnitTestCase { JUnitTestCase(const std::string& _classname, const std::string& _name) : classname(_classname), name(_name), time(0), failures() {} std::string classname, name; double time; std::vector<JUnitTestMessage> failures, errors; }; void add(const std::string& classname, const std::string& name) { testcases.emplace_back(classname, name); } void appendSubcaseNamesToLastTestcase(std::vector<String> nameStack) { for(auto& curr: nameStack) if(curr.size()) testcases.back().name += std::string("/") + curr.c_str(); } void addTime(double time) { if(time < 1e-4) time = 0; testcases.back().time = time; totalSeconds += time; } void addFailure(const std::string& message, const std::string& type, const std::string& details) { testcases.back().failures.emplace_back(message, type, details); ++totalFailures; } void addError(const std::string& message, const std::string& details) { testcases.back().errors.emplace_back(message, details); ++totalErrors; } std::vector<JUnitTestCase> testcases; double totalSeconds = 0; int totalErrors = 0, totalFailures = 0; }; JUnitTestCaseData testCaseData; // caching pointers/references to objects of these types - safe to do const ContextOptions& opt; const TestCaseData* tc = nullptr; JUnitReporter(const ContextOptions& co) : xml(*co.cout) , opt(co) {} unsigned line(unsigned l) const { return opt.no_line_numbers ? 0 : l; } // ========================================================================================= // WHAT FOLLOWS ARE OVERRIDES OF THE VIRTUAL METHODS OF THE REPORTER INTERFACE // ========================================================================================= void report_query(const QueryData&) override { xml.writeDeclaration(); } void test_run_start() override { xml.writeDeclaration(); } void test_run_end(const TestRunStats& p) override { // remove .exe extension - mainly to have the same output on UNIX and Windows std::string binary_name = skipPathFromFilename(opt.binary_name.c_str()); #ifdef DOCTEST_PLATFORM_WINDOWS if(binary_name.rfind(".exe") != std::string::npos) binary_name = binary_name.substr(0, binary_name.length() - 4); #endif // DOCTEST_PLATFORM_WINDOWS xml.startElement("testsuites"); xml.startElement("testsuite").writeAttribute("name", binary_name) .writeAttribute("errors", testCaseData.totalErrors) .writeAttribute("failures", testCaseData.totalFailures) .writeAttribute("tests", p.numAsserts); if(opt.no_time_in_output == false) { xml.writeAttribute("time", testCaseData.totalSeconds); xml.writeAttribute("timestamp", JUnitTestCaseData::getCurrentTimestamp()); } if(opt.no_version == false) xml.writeAttribute("doctest_version", DOCTEST_VERSION_STR); for(const auto& testCase : testCaseData.testcases) { xml.startElement("testcase") .writeAttribute("classname", testCase.classname) .writeAttribute("name", testCase.name); if(opt.no_time_in_output == false) xml.writeAttribute("time", testCase.time); // This is not ideal, but it should be enough to mimic gtest's junit output. xml.writeAttribute("status", "run"); for(const auto& failure : testCase.failures) { xml.scopedElement("failure") .writeAttribute("message", failure.message) .writeAttribute("type", failure.type) .writeText(failure.details, false); } for(const auto& error : testCase.errors) { xml.scopedElement("error") .writeAttribute("message", error.message) .writeText(error.details); } xml.endElement(); } xml.endElement(); xml.endElement(); } void test_case_start(const TestCaseData& in) override { testCaseData.add(skipPathFromFilename(in.m_file.c_str()), in.m_name); timer.start(); } void test_case_reenter(const TestCaseData& in) override { testCaseData.addTime(timer.getElapsedSeconds()); testCaseData.appendSubcaseNamesToLastTestcase(deepestSubcaseStackNames); deepestSubcaseStackNames.clear(); timer.start(); testCaseData.add(skipPathFromFilename(in.m_file.c_str()), in.m_name); } void test_case_end(const CurrentTestCaseStats&) override { testCaseData.addTime(timer.getElapsedSeconds()); testCaseData.appendSubcaseNamesToLastTestcase(deepestSubcaseStackNames); deepestSubcaseStackNames.clear(); } void test_case_exception(const TestCaseException& e) override { DOCTEST_LOCK_MUTEX(mutex) testCaseData.addError("exception", e.error_string.c_str()); } void subcase_start(const SubcaseSignature& in) override { deepestSubcaseStackNames.push_back(in.m_name); } void subcase_end() override {} void log_assert(const AssertData& rb) override { if(!rb.m_failed) // report only failures & ignore the `success` option return; DOCTEST_LOCK_MUTEX(mutex) std::ostringstream os; os << skipPathFromFilename(rb.m_file) << (opt.gnu_file_line ? ":" : "(") << line(rb.m_line) << (opt.gnu_file_line ? ":" : "):") << std::endl; fulltext_log_assert_to_stream(os, rb); log_contexts(os); testCaseData.addFailure(rb.m_decomp.c_str(), assertString(rb.m_at), os.str()); } void log_message(const MessageData& mb) override { if(mb.m_severity & assertType::is_warn) // report only failures return; DOCTEST_LOCK_MUTEX(mutex) std::ostringstream os; os << skipPathFromFilename(mb.m_file) << (opt.gnu_file_line ? ":" : "(") << line(mb.m_line) << (opt.gnu_file_line ? ":" : "):") << std::endl; os << mb.m_string.c_str() << "\n"; log_contexts(os); testCaseData.addFailure(mb.m_string.c_str(), mb.m_severity & assertType::is_check ? "FAIL_CHECK" : "FAIL", os.str()); } void test_case_skipped(const TestCaseData&) override {} void log_contexts(std::ostringstream& s) { int num_contexts = get_num_active_contexts(); if(num_contexts) { auto contexts = get_active_contexts(); s << " logged: "; for(int i = 0; i < num_contexts; ++i) { s << (i == 0 ? "" : " "); contexts[i]->stringify(&s); s << std::endl; } } } }; DOCTEST_REGISTER_REPORTER("junit", 0, JUnitReporter); struct Whitespace { int nrSpaces; explicit Whitespace(int nr) : nrSpaces(nr) {} }; std::ostream& operator<<(std::ostream& out, const Whitespace& ws) { if(ws.nrSpaces != 0) out << std::setw(ws.nrSpaces) << ' '; return out; } struct ConsoleReporter : public IReporter { std::ostream& s; bool hasLoggedCurrentTestStart; std::vector<SubcaseSignature> subcasesStack; size_t currentSubcaseLevel; DOCTEST_DECLARE_MUTEX(mutex) // caching pointers/references to objects of these types - safe to do const ContextOptions& opt; const TestCaseData* tc; ConsoleReporter(const ContextOptions& co) : s(*co.cout) , opt(co) {} ConsoleReporter(const ContextOptions& co, std::ostream& ostr) : s(ostr) , opt(co) {} // ========================================================================================= // WHAT FOLLOWS ARE HELPERS USED BY THE OVERRIDES OF THE VIRTUAL METHODS OF THE INTERFACE // ========================================================================================= void separator_to_stream() { s << Color::Yellow << "===============================================================================" "\n"; } const char* getSuccessOrFailString(bool success, assertType::Enum at, const char* success_str) { if(success) return success_str; return failureString(at); } Color::Enum getSuccessOrFailColor(bool success, assertType::Enum at) { return success ? Color::BrightGreen : (at & assertType::is_warn) ? Color::Yellow : Color::Red; } void successOrFailColoredStringToStream(bool success, assertType::Enum at, const char* success_str = "SUCCESS") { s << getSuccessOrFailColor(success, at) << getSuccessOrFailString(success, at, success_str) << ": "; } void log_contexts() { int num_contexts = get_num_active_contexts(); if(num_contexts) { auto contexts = get_active_contexts(); s << Color::None << " logged: "; for(int i = 0; i < num_contexts; ++i) { s << (i == 0 ? "" : " "); contexts[i]->stringify(&s); s << "\n"; } } s << "\n"; } // this was requested to be made virtual so users could override it virtual void file_line_to_stream(const char* file, int line, const char* tail = "") { s << Color::LightGrey << skipPathFromFilename(file) << (opt.gnu_file_line ? ":" : "(") << (opt.no_line_numbers ? 0 : line) // 0 or the real num depending on the option << (opt.gnu_file_line ? ":" : "):") << tail; } void logTestStart() { if(hasLoggedCurrentTestStart) return; separator_to_stream(); file_line_to_stream(tc->m_file.c_str(), tc->m_line, "\n"); if(tc->m_description) s << Color::Yellow << "DESCRIPTION: " << Color::None << tc->m_description << "\n"; if(tc->m_test_suite && tc->m_test_suite[0] != '\0') s << Color::Yellow << "TEST SUITE: " << Color::None << tc->m_test_suite << "\n"; if(strncmp(tc->m_name, " Scenario:", 11) != 0) s << Color::Yellow << "TEST CASE: "; s << Color::None << tc->m_name << "\n"; for(size_t i = 0; i < currentSubcaseLevel; ++i) { if(subcasesStack[i].m_name[0] != '\0') s << " " << subcasesStack[i].m_name << "\n"; } if(currentSubcaseLevel != subcasesStack.size()) { s << Color::Yellow << "\nDEEPEST SUBCASE STACK REACHED (DIFFERENT FROM THE CURRENT ONE):\n" << Color::None; for(size_t i = 0; i < subcasesStack.size(); ++i) { if(subcasesStack[i].m_name[0] != '\0') s << " " << subcasesStack[i].m_name << "\n"; } } s << "\n"; hasLoggedCurrentTestStart = true; } void printVersion() { if(opt.no_version == false) s << Color::Cyan << "[doctest] " << Color::None << "doctest version is \"" << DOCTEST_VERSION_STR << "\"\n"; } void printIntro() { if(opt.no_intro == false) { printVersion(); s << Color::Cyan << "[doctest] " << Color::None << "run with \"--" DOCTEST_OPTIONS_PREFIX_DISPLAY "help\" for options\n"; } } void printHelp() { int sizePrefixDisplay = static_cast<int>(strlen(DOCTEST_OPTIONS_PREFIX_DISPLAY)); printVersion(); // clang-format off s << Color::Cyan << "[doctest]\n" << Color::None; s << Color::Cyan << "[doctest] " << Color::None; s << "boolean values: \"1/on/yes/true\" or \"0/off/no/false\"\n"; s << Color::Cyan << "[doctest] " << Color::None; s << "filter values: \"str1,str2,str3\" (comma separated strings)\n"; s << Color::Cyan << "[doctest]\n" << Color::None; s << Color::Cyan << "[doctest] " << Color::None; s << "filters use wildcards for matching strings\n"; s << Color::Cyan << "[doctest] " << Color::None; s << "something passes a filter if any of the strings in a filter matches\n"; #ifndef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS s << Color::Cyan << "[doctest]\n" << Color::None; s << Color::Cyan << "[doctest] " << Color::None; s << "ALL FLAGS, OPTIONS AND FILTERS ALSO AVAILABLE WITH A \"" DOCTEST_CONFIG_OPTIONS_PREFIX "\" PREFIX!!!\n"; #endif s << Color::Cyan << "[doctest]\n" << Color::None; s << Color::Cyan << "[doctest] " << Color::None; s << "Query flags - the program quits after them. Available:\n\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "?, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "help, -" DOCTEST_OPTIONS_PREFIX_DISPLAY "h " << Whitespace(sizePrefixDisplay*0) << "prints this message\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "v, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "version " << Whitespace(sizePrefixDisplay*1) << "prints the version\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "c, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "count " << Whitespace(sizePrefixDisplay*1) << "prints the number of matching tests\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ltc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-test-cases " << Whitespace(sizePrefixDisplay*1) << "lists all matching tests by name\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "lts, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-test-suites " << Whitespace(sizePrefixDisplay*1) << "lists all matching test suites\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "lr, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-reporters " << Whitespace(sizePrefixDisplay*1) << "lists all registered reporters\n\n"; // ================================================================================== << 79 s << Color::Cyan << "[doctest] " << Color::None; s << "The available <int>/<string> options/filters are:\n\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-case=<filters> " << Whitespace(sizePrefixDisplay*1) << "filters tests by their name\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tce, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-case-exclude=<filters> " << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their name\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sf, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "source-file=<filters> " << Whitespace(sizePrefixDisplay*1) << "filters tests by their file\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sfe, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "source-file-exclude=<filters> " << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their file\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ts, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-suite=<filters> " << Whitespace(sizePrefixDisplay*1) << "filters tests by their test suite\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tse, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-suite-exclude=<filters> " << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their test suite\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase=<filters> " << Whitespace(sizePrefixDisplay*1) << "filters subcases by their name\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sce, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase-exclude=<filters> " << Whitespace(sizePrefixDisplay*1) << "filters OUT subcases by their name\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "r, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "reporters=<filters> " << Whitespace(sizePrefixDisplay*1) << "reporters to use (console is default)\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "o, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "out=<string> " << Whitespace(sizePrefixDisplay*1) << "output filename\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ob, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "order-by=<string> " << Whitespace(sizePrefixDisplay*1) << "how the tests should be ordered\n"; s << Whitespace(sizePrefixDisplay*3) << " <string> - [file/suite/name/rand/none]\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "rs, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "rand-seed=<int> " << Whitespace(sizePrefixDisplay*1) << "seed for random ordering\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "f, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "first=<int> " << Whitespace(sizePrefixDisplay*1) << "the first test passing the filters to\n"; s << Whitespace(sizePrefixDisplay*3) << " execute - for range-based execution\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "l, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "last=<int> " << Whitespace(sizePrefixDisplay*1) << "the last test passing the filters to\n"; s << Whitespace(sizePrefixDisplay*3) << " execute - for range-based execution\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "aa, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "abort-after=<int> " << Whitespace(sizePrefixDisplay*1) << "stop after <int> failed assertions\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "scfl,--" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase-filter-levels=<int> " << Whitespace(sizePrefixDisplay*1) << "apply filters for the first <int> levels\n"; s << Color::Cyan << "\n[doctest] " << Color::None; s << "Bool options - can be used like flags and true is assumed. Available:\n\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "s, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "success=<bool> " << Whitespace(sizePrefixDisplay*1) << "include successful assertions in output\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "cs, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "case-sensitive=<bool> " << Whitespace(sizePrefixDisplay*1) << "filters being treated as case sensitive\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "e, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "exit=<bool> " << Whitespace(sizePrefixDisplay*1) << "exits after the tests finish\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "d, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "duration=<bool> " << Whitespace(sizePrefixDisplay*1) << "prints the time duration of each test\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "m, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "minimal=<bool> " << Whitespace(sizePrefixDisplay*1) << "minimal console output (only failures)\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "q, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "quiet=<bool> " << Whitespace(sizePrefixDisplay*1) << "no console output\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nt, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-throw=<bool> " << Whitespace(sizePrefixDisplay*1) << "skips exceptions-related assert checks\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ne, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-exitcode=<bool> " << Whitespace(sizePrefixDisplay*1) << "returns (or exits) always with success\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nr, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-run=<bool> " << Whitespace(sizePrefixDisplay*1) << "skips all runtime doctest operations\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ni, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-intro=<bool> " << Whitespace(sizePrefixDisplay*1) << "omit the framework intro in the output\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nv, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-version=<bool> " << Whitespace(sizePrefixDisplay*1) << "omit the framework version in the output\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-colors=<bool> " << Whitespace(sizePrefixDisplay*1) << "disables colors in output\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "fc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "force-colors=<bool> " << Whitespace(sizePrefixDisplay*1) << "use colors even when not in a tty\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nb, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-breaks=<bool> " << Whitespace(sizePrefixDisplay*1) << "disables breakpoints in debuggers\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ns, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-skip=<bool> " << Whitespace(sizePrefixDisplay*1) << "don't skip test cases marked as skip\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "gfl, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "gnu-file-line=<bool> " << Whitespace(sizePrefixDisplay*1) << ":n: vs (n): for line numbers in output\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "npf, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-path-filenames=<bool> " << Whitespace(sizePrefixDisplay*1) << "only filenames and no paths in output\n"; s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nln, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-line-numbers=<bool> " << Whitespace(sizePrefixDisplay*1) << "0 instead of real line numbers in output\n"; // ================================================================================== << 79 // clang-format on s << Color::Cyan << "\n[doctest] " << Color::None; s << "for more information visit the project documentation\n\n"; } void printRegisteredReporters() { printVersion(); auto printReporters = [this] (const reporterMap& reporters, const char* type) { if(reporters.size()) { s << Color::Cyan << "[doctest] " << Color::None << "listing all registered " << type << "\n"; for(auto& curr : reporters) s << "priority: " << std::setw(5) << curr.first.first << " name: " << curr.first.second << "\n"; } }; printReporters(getListeners(), "listeners"); printReporters(getReporters(), "reporters"); } // ========================================================================================= // WHAT FOLLOWS ARE OVERRIDES OF THE VIRTUAL METHODS OF THE REPORTER INTERFACE // ========================================================================================= void report_query(const QueryData& in) override { if(opt.version) { printVersion(); } else if(opt.help) { printHelp(); } else if(opt.list_reporters) { printRegisteredReporters(); } else if(opt.count || opt.list_test_cases) { if(opt.list_test_cases) { s << Color::Cyan << "[doctest] " << Color::None << "listing all test case names\n"; separator_to_stream(); } for(unsigned i = 0; i < in.num_data; ++i) s << Color::None << in.data[i]->m_name << "\n"; separator_to_stream(); s << Color::Cyan << "[doctest] " << Color::None << "unskipped test cases passing the current filters: " << g_cs->numTestCasesPassingFilters << "\n"; } else if(opt.list_test_suites) { s << Color::Cyan << "[doctest] " << Color::None << "listing all test suites\n"; separator_to_stream(); for(unsigned i = 0; i < in.num_data; ++i) s << Color::None << in.data[i]->m_test_suite << "\n"; separator_to_stream(); s << Color::Cyan << "[doctest] " << Color::None << "unskipped test cases passing the current filters: " << g_cs->numTestCasesPassingFilters << "\n"; s << Color::Cyan << "[doctest] " << Color::None << "test suites with unskipped test cases passing the current filters: " << g_cs->numTestSuitesPassingFilters << "\n"; } } void test_run_start() override { if(!opt.minimal) printIntro(); } void test_run_end(const TestRunStats& p) override { if(opt.minimal && p.numTestCasesFailed == 0) return; separator_to_stream(); s << std::dec; auto totwidth = int(std::ceil(log10(static_cast<double>(std::max(p.numTestCasesPassingFilters, static_cast<unsigned>(p.numAsserts))) + 1))); auto passwidth = int(std::ceil(log10(static_cast<double>(std::max(p.numTestCasesPassingFilters - p.numTestCasesFailed, static_cast<unsigned>(p.numAsserts - p.numAssertsFailed))) + 1))); auto failwidth = int(std::ceil(log10(static_cast<double>(std::max(p.numTestCasesFailed, static_cast<unsigned>(p.numAssertsFailed))) + 1))); const bool anythingFailed = p.numTestCasesFailed > 0 || p.numAssertsFailed > 0; s << Color::Cyan << "[doctest] " << Color::None << "test cases: " << std::setw(totwidth) << p.numTestCasesPassingFilters << " | " << ((p.numTestCasesPassingFilters == 0 || anythingFailed) ? Color::None : Color::Green) << std::setw(passwidth) << p.numTestCasesPassingFilters - p.numTestCasesFailed << " passed" << Color::None << " | " << (p.numTestCasesFailed > 0 ? Color::Red : Color::None) << std::setw(failwidth) << p.numTestCasesFailed << " failed" << Color::None << " |"; if(opt.no_skipped_summary == false) { const int numSkipped = p.numTestCases - p.numTestCasesPassingFilters; s << " " << (numSkipped == 0 ? Color::None : Color::Yellow) << numSkipped << " skipped" << Color::None; } s << "\n"; s << Color::Cyan << "[doctest] " << Color::None << "assertions: " << std::setw(totwidth) << p.numAsserts << " | " << ((p.numAsserts == 0 || anythingFailed) ? Color::None : Color::Green) << std::setw(passwidth) << (p.numAsserts - p.numAssertsFailed) << " passed" << Color::None << " | " << (p.numAssertsFailed > 0 ? Color::Red : Color::None) << std::setw(failwidth) << p.numAssertsFailed << " failed" << Color::None << " |\n"; s << Color::Cyan << "[doctest] " << Color::None << "Status: " << (p.numTestCasesFailed > 0 ? Color::Red : Color::Green) << ((p.numTestCasesFailed > 0) ? "FAILURE!" : "SUCCESS!") << Color::None << std::endl; } void test_case_start(const TestCaseData& in) override { hasLoggedCurrentTestStart = false; tc = &in; subcasesStack.clear(); currentSubcaseLevel = 0; } void test_case_reenter(const TestCaseData&) override { subcasesStack.clear(); } void test_case_end(const CurrentTestCaseStats& st) override { if(tc->m_no_output) return; // log the preamble of the test case only if there is something // else to print - something other than that an assert has failed if(opt.duration || (st.failure_flags && st.failure_flags != static_cast<int>(TestCaseFailureReason::AssertFailure))) logTestStart(); if(opt.duration) s << Color::None << std::setprecision(6) << std::fixed << st.seconds << " s: " << tc->m_name << "\n"; if(st.failure_flags & TestCaseFailureReason::Timeout) s << Color::Red << "Test case exceeded time limit of " << std::setprecision(6) << std::fixed << tc->m_timeout << "!\n"; if(st.failure_flags & TestCaseFailureReason::ShouldHaveFailedButDidnt) { s << Color::Red << "Should have failed but didn't! Marking it as failed!\n"; } else if(st.failure_flags & TestCaseFailureReason::ShouldHaveFailedAndDid) { s << Color::Yellow << "Failed as expected so marking it as not failed\n"; } else if(st.failure_flags & TestCaseFailureReason::CouldHaveFailedAndDid) { s << Color::Yellow << "Allowed to fail so marking it as not failed\n"; } else if(st.failure_flags & TestCaseFailureReason::DidntFailExactlyNumTimes) { s << Color::Red << "Didn't fail exactly " << tc->m_expected_failures << " times so marking it as failed!\n"; } else if(st.failure_flags & TestCaseFailureReason::FailedExactlyNumTimes) { s << Color::Yellow << "Failed exactly " << tc->m_expected_failures << " times as expected so marking it as not failed!\n"; } if(st.failure_flags & TestCaseFailureReason::TooManyFailedAsserts) { s << Color::Red << "Aborting - too many failed asserts!\n"; } s << Color::None; // lgtm [cpp/useless-expression] } void test_case_exception(const TestCaseException& e) override { DOCTEST_LOCK_MUTEX(mutex) if(tc->m_no_output) return; logTestStart(); file_line_to_stream(tc->m_file.c_str(), tc->m_line, " "); successOrFailColoredStringToStream(false, e.is_crash ? assertType::is_require : assertType::is_check); s << Color::Red << (e.is_crash ? "test case CRASHED: " : "test case THREW exception: ") << Color::Cyan << e.error_string << "\n"; int num_stringified_contexts = get_num_stringified_contexts(); if(num_stringified_contexts) { auto stringified_contexts = get_stringified_contexts(); s << Color::None << " logged: "; for(int i = num_stringified_contexts; i > 0; --i) { s << (i == num_stringified_contexts ? "" : " ") << stringified_contexts[i - 1] << "\n"; } } s << "\n" << Color::None; } void subcase_start(const SubcaseSignature& subc) override { subcasesStack.push_back(subc); ++currentSubcaseLevel; hasLoggedCurrentTestStart = false; } void subcase_end() override { --currentSubcaseLevel; hasLoggedCurrentTestStart = false; } void log_assert(const AssertData& rb) override { if((!rb.m_failed && !opt.success) || tc->m_no_output) return; DOCTEST_LOCK_MUTEX(mutex) logTestStart(); file_line_to_stream(rb.m_file, rb.m_line, " "); successOrFailColoredStringToStream(!rb.m_failed, rb.m_at); fulltext_log_assert_to_stream(s, rb); log_contexts(); } void log_message(const MessageData& mb) override { if(tc->m_no_output) return; DOCTEST_LOCK_MUTEX(mutex) logTestStart(); file_line_to_stream(mb.m_file, mb.m_line, " "); s << getSuccessOrFailColor(false, mb.m_severity) << getSuccessOrFailString(mb.m_severity & assertType::is_warn, mb.m_severity, "MESSAGE") << ": "; s << Color::None << mb.m_string << "\n"; log_contexts(); } void test_case_skipped(const TestCaseData&) override {} }; DOCTEST_REGISTER_REPORTER("console", 0, ConsoleReporter); #ifdef DOCTEST_PLATFORM_WINDOWS struct DebugOutputWindowReporter : public ConsoleReporter { DOCTEST_THREAD_LOCAL static std::ostringstream oss; DebugOutputWindowReporter(const ContextOptions& co) : ConsoleReporter(co, oss) {} #define DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(func, type, arg) \ void func(type arg) override { \ bool with_col = g_no_colors; \ g_no_colors = false; \ ConsoleReporter::func(arg); \ if(oss.tellp() != std::streampos{}) { \ DOCTEST_OUTPUT_DEBUG_STRING(oss.str().c_str()); \ oss.str(""); \ } \ g_no_colors = with_col; \ } DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_run_start, DOCTEST_EMPTY, DOCTEST_EMPTY) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_run_end, const TestRunStats&, in) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_start, const TestCaseData&, in) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_reenter, const TestCaseData&, in) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_end, const CurrentTestCaseStats&, in) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_exception, const TestCaseException&, in) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(subcase_start, const SubcaseSignature&, in) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(subcase_end, DOCTEST_EMPTY, DOCTEST_EMPTY) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(log_assert, const AssertData&, in) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(log_message, const MessageData&, in) DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_skipped, const TestCaseData&, in) }; DOCTEST_THREAD_LOCAL std::ostringstream DebugOutputWindowReporter::oss; #endif // DOCTEST_PLATFORM_WINDOWS // the implementation of parseOption() bool parseOptionImpl(int argc, const char* const* argv, const char* pattern, String* value) { // going from the end to the beginning and stopping on the first occurrence from the end for(int i = argc; i > 0; --i) { auto index = i - 1; auto temp = std::strstr(argv[index], pattern); if(temp && (value || strlen(temp) == strlen(pattern))) { //!OCLINT prefer early exits and continue // eliminate matches in which the chars before the option are not '-' bool noBadCharsFound = true; auto curr = argv[index]; while(curr != temp) { if(*curr++ != '-') { noBadCharsFound = false; break; } } if(noBadCharsFound && argv[index][0] == '-') { if(value) { // parsing the value of an option temp += strlen(pattern); const unsigned len = strlen(temp); if(len) { *value = temp; return true; } } else { // just a flag - no value return true; } } } } return false; } // parses an option and returns the string after the '=' character bool parseOption(int argc, const char* const* argv, const char* pattern, String* value = nullptr, const String& defaultVal = String()) { if(value) *value = defaultVal; #ifndef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS // offset (normally 3 for "dt-") to skip prefix if(parseOptionImpl(argc, argv, pattern + strlen(DOCTEST_CONFIG_OPTIONS_PREFIX), value)) return true; #endif // DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS return parseOptionImpl(argc, argv, pattern, value); } // locates a flag on the command line bool parseFlag(int argc, const char* const* argv, const char* pattern) { return parseOption(argc, argv, pattern); } // parses a comma separated list of words after a pattern in one of the arguments in argv bool parseCommaSepArgs(int argc, const char* const* argv, const char* pattern, std::vector<String>& res) { String filtersString; if(parseOption(argc, argv, pattern, &filtersString)) { // tokenize with "," as a separator, unless escaped with backslash std::ostringstream s; auto flush = [&s, &res]() { auto string = s.str(); if(string.size() > 0) { res.push_back(string.c_str()); } s.str(""); }; bool seenBackslash = false; const char* current = filtersString.c_str(); const char* end = current + strlen(current); while(current != end) { char character = *current++; if(seenBackslash) { seenBackslash = false; if(character == ',' || character == '\\') { s.put(character); continue; } s.put('\\'); } if(character == '\\') { seenBackslash = true; } else if(character == ',') { flush(); } else { s.put(character); } } if(seenBackslash) { s.put('\\'); } flush(); return true; } return false; } enum optionType { option_bool, option_int }; // parses an int/bool option from the command line bool parseIntOption(int argc, const char* const* argv, const char* pattern, optionType type, int& res) { String parsedValue; if(!parseOption(argc, argv, pattern, &parsedValue)) return false; if(type) { // integer // TODO: change this to use std::stoi or something else! currently it uses undefined behavior - assumes '0' on failed parse... int theInt = std::atoi(parsedValue.c_str()); if (theInt != 0) { res = theInt; //!OCLINT parameter reassignment return true; } } else { // boolean const char positive[][5] = { "1", "true", "on", "yes" }; // 5 - strlen("true") + 1 const char negative[][6] = { "0", "false", "off", "no" }; // 6 - strlen("false") + 1 // if the value matches any of the positive/negative possibilities for (unsigned i = 0; i < 4; i++) { if (parsedValue.compare(positive[i], true) == 0) { res = 1; //!OCLINT parameter reassignment return true; } if (parsedValue.compare(negative[i], true) == 0) { res = 0; //!OCLINT parameter reassignment return true; } } } return false; } } // namespace Context::Context(int argc, const char* const* argv) : p(new detail::ContextState) { parseArgs(argc, argv, true); if(argc) p->binary_name = argv[0]; } Context::~Context() { if(g_cs == p) g_cs = nullptr; delete p; } void Context::applyCommandLine(int argc, const char* const* argv) { parseArgs(argc, argv); if(argc) p->binary_name = argv[0]; } // parses args void Context::parseArgs(int argc, const char* const* argv, bool withDefaults) { using namespace detail; // clang-format off parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "source-file=", p->filters[0]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sf=", p->filters[0]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "source-file-exclude=",p->filters[1]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sfe=", p->filters[1]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-suite=", p->filters[2]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "ts=", p->filters[2]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-suite-exclude=", p->filters[3]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tse=", p->filters[3]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-case=", p->filters[4]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tc=", p->filters[4]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-case-exclude=", p->filters[5]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tce=", p->filters[5]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "subcase=", p->filters[6]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sc=", p->filters[6]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "subcase-exclude=", p->filters[7]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sce=", p->filters[7]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "reporters=", p->filters[8]); parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "r=", p->filters[8]); // clang-format on int intRes = 0; String strRes; #define DOCTEST_PARSE_AS_BOOL_OR_FLAG(name, sname, var, default) \ if(parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", option_bool, intRes) || \ parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", option_bool, intRes)) \ p->var = static_cast<bool>(intRes); \ else if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name) || \ parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname)) \ p->var = true; \ else if(withDefaults) \ p->var = default #define DOCTEST_PARSE_INT_OPTION(name, sname, var, default) \ if(parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", option_int, intRes) || \ parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", option_int, intRes)) \ p->var = intRes; \ else if(withDefaults) \ p->var = default #define DOCTEST_PARSE_STR_OPTION(name, sname, var, default) \ if(parseOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", &strRes, default) || \ parseOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", &strRes, default) || \ withDefaults) \ p->var = strRes // clang-format off DOCTEST_PARSE_STR_OPTION("out", "o", out, ""); DOCTEST_PARSE_STR_OPTION("order-by", "ob", order_by, "file"); DOCTEST_PARSE_INT_OPTION("rand-seed", "rs", rand_seed, 0); DOCTEST_PARSE_INT_OPTION("first", "f", first, 0); DOCTEST_PARSE_INT_OPTION("last", "l", last, UINT_MAX); DOCTEST_PARSE_INT_OPTION("abort-after", "aa", abort_after, 0); DOCTEST_PARSE_INT_OPTION("subcase-filter-levels", "scfl", subcase_filter_levels, INT_MAX); DOCTEST_PARSE_AS_BOOL_OR_FLAG("success", "s", success, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("case-sensitive", "cs", case_sensitive, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("exit", "e", exit, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("duration", "d", duration, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("minimal", "m", minimal, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("quiet", "q", quiet, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-throw", "nt", no_throw, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-exitcode", "ne", no_exitcode, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-run", "nr", no_run, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-intro", "ni", no_intro, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-version", "nv", no_version, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-colors", "nc", no_colors, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("force-colors", "fc", force_colors, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-breaks", "nb", no_breaks, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-skip", "ns", no_skip, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("gnu-file-line", "gfl", gnu_file_line, !bool(DOCTEST_MSVC)); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-path-filenames", "npf", no_path_in_filenames, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-line-numbers", "nln", no_line_numbers, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-debug-output", "ndo", no_debug_output, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-skipped-summary", "nss", no_skipped_summary, false); DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-time-in-output", "ntio", no_time_in_output, false); // clang-format on if(withDefaults) { p->help = false; p->version = false; p->count = false; p->list_test_cases = false; p->list_test_suites = false; p->list_reporters = false; } if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "help") || parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "h") || parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "?")) { p->help = true; p->exit = true; } if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "version") || parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "v")) { p->version = true; p->exit = true; } if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "count") || parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "c")) { p->count = true; p->exit = true; } if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-test-cases") || parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "ltc")) { p->list_test_cases = true; p->exit = true; } if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-test-suites") || parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "lts")) { p->list_test_suites = true; p->exit = true; } if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-reporters") || parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "lr")) { p->list_reporters = true; p->exit = true; } } // allows the user to add procedurally to the filters from the command line void Context::addFilter(const char* filter, const char* value) { setOption(filter, value); } // allows the user to clear all filters from the command line void Context::clearFilters() { for(auto& curr : p->filters) curr.clear(); } // allows the user to override procedurally the bool options from the command line void Context::setOption(const char* option, bool value) { setOption(option, value ? "true" : "false"); } // allows the user to override procedurally the int options from the command line void Context::setOption(const char* option, int value) { setOption(option, toString(value).c_str()); } // allows the user to override procedurally the string options from the command line void Context::setOption(const char* option, const char* value) { auto argv = String("-") + option + "=" + value; auto lvalue = argv.c_str(); parseArgs(1, &lvalue); } // users should query this in their main() and exit the program if true bool Context::shouldExit() { return p->exit; } void Context::setAsDefaultForAssertsOutOfTestCases() { g_cs = p; } void Context::setAssertHandler(detail::assert_handler ah) { p->ah = ah; } void Context::setCout(std::ostream* out) { p->cout = out; } static class DiscardOStream : public std::ostream { private: class : public std::streambuf { private: // allowing some buffering decreases the amount of calls to overflow char buf[1024]; protected: std::streamsize xsputn(const char_type*, std::streamsize count) override { return count; } int_type overflow(int_type ch) override { setp(std::begin(buf), std::end(buf)); return traits_type::not_eof(ch); } } discardBuf; public: DiscardOStream() : std::ostream(&discardBuf) {} } discardOut; // the main function that does all the filtering and test running int Context::run() { using namespace detail; // save the old context state in case such was setup - for using asserts out of a testing context auto old_cs = g_cs; // this is the current contest g_cs = p; is_running_in_test = true; g_no_colors = p->no_colors; p->resetRunData(); std::fstream fstr; if(p->cout == nullptr) { if(p->quiet) { p->cout = &discardOut; } else if(p->out.size()) { // to a file if specified fstr.open(p->out.c_str(), std::fstream::out); p->cout = &fstr; } else { #ifndef DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM // stdout by default p->cout = &std::cout; #else // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM return EXIT_FAILURE; #endif // DOCTEST_CONFIG_NO_INCLUDE_IOSTREAM } } FatalConditionHandler::allocateAltStackMem(); auto cleanup_and_return = [&]() { FatalConditionHandler::freeAltStackMem(); if(fstr.is_open()) fstr.close(); // restore context g_cs = old_cs; is_running_in_test = false; // we have to free the reporters which were allocated when the run started for(auto& curr : p->reporters_currently_used) delete curr; p->reporters_currently_used.clear(); if(p->numTestCasesFailed && !p->no_exitcode) return EXIT_FAILURE; return EXIT_SUCCESS; }; // setup default reporter if none is given through the command line if(p->filters[8].empty()) p->filters[8].push_back("console"); // check to see if any of the registered reporters has been selected for(auto& curr : getReporters()) { if(matchesAny(curr.first.second.c_str(), p->filters[8], false, p->case_sensitive)) p->reporters_currently_used.push_back(curr.second(*g_cs)); } // TODO: check if there is nothing in reporters_currently_used // prepend all listeners for(auto& curr : getListeners()) p->reporters_currently_used.insert(p->reporters_currently_used.begin(), curr.second(*g_cs)); #ifdef DOCTEST_PLATFORM_WINDOWS if(isDebuggerActive() && p->no_debug_output == false) p->reporters_currently_used.push_back(new DebugOutputWindowReporter(*g_cs)); #endif // DOCTEST_PLATFORM_WINDOWS // handle version, help and no_run if(p->no_run || p->version || p->help || p->list_reporters) { DOCTEST_ITERATE_THROUGH_REPORTERS(report_query, QueryData()); return cleanup_and_return(); } std::vector<const TestCase*> testArray; for(auto& curr : getRegisteredTests()) testArray.push_back(&curr); p->numTestCases = testArray.size(); // sort the collected records if(!testArray.empty()) { if(p->order_by.compare("file", true) == 0) { std::sort(testArray.begin(), testArray.end(), fileOrderComparator); } else if(p->order_by.compare("suite", true) == 0) { std::sort(testArray.begin(), testArray.end(), suiteOrderComparator); } else if(p->order_by.compare("name", true) == 0) { std::sort(testArray.begin(), testArray.end(), nameOrderComparator); } else if(p->order_by.compare("rand", true) == 0) { std::srand(p->rand_seed); // random_shuffle implementation const auto first = &testArray[0]; for(size_t i = testArray.size() - 1; i > 0; --i) { int idxToSwap = std::rand() % (i + 1); const auto temp = first[i]; first[i] = first[idxToSwap]; first[idxToSwap] = temp; } } else if(p->order_by.compare("none", true) == 0) { // means no sorting - beneficial for death tests which call into the executable // with a specific test case in mind - we don't want to slow down the startup times } } std::set<String> testSuitesPassingFilt; bool query_mode = p->count || p->list_test_cases || p->list_test_suites; std::vector<const TestCaseData*> queryResults; if(!query_mode) DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_start, DOCTEST_EMPTY); // invoke the registered functions if they match the filter criteria (or just count them) for(auto& curr : testArray) { const auto& tc = *curr; bool skip_me = false; if(tc.m_skip && !p->no_skip) skip_me = true; if(!matchesAny(tc.m_file.c_str(), p->filters[0], true, p->case_sensitive)) skip_me = true; if(matchesAny(tc.m_file.c_str(), p->filters[1], false, p->case_sensitive)) skip_me = true; if(!matchesAny(tc.m_test_suite, p->filters[2], true, p->case_sensitive)) skip_me = true; if(matchesAny(tc.m_test_suite, p->filters[3], false, p->case_sensitive)) skip_me = true; if(!matchesAny(tc.m_name, p->filters[4], true, p->case_sensitive)) skip_me = true; if(matchesAny(tc.m_name, p->filters[5], false, p->case_sensitive)) skip_me = true; if(!skip_me) p->numTestCasesPassingFilters++; // skip the test if it is not in the execution range if((p->last < p->numTestCasesPassingFilters && p->first <= p->last) || (p->first > p->numTestCasesPassingFilters)) skip_me = true; if(skip_me) { if(!query_mode) DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_skipped, tc); continue; } // do not execute the test if we are to only count the number of filter passing tests if(p->count) continue; // print the name of the test and don't execute it if(p->list_test_cases) { queryResults.push_back(&tc); continue; } // print the name of the test suite if not done already and don't execute it if(p->list_test_suites) { if((testSuitesPassingFilt.count(tc.m_test_suite) == 0) && tc.m_test_suite[0] != '\0') { queryResults.push_back(&tc); testSuitesPassingFilt.insert(tc.m_test_suite); p->numTestSuitesPassingFilters++; } continue; } // execute the test if it passes all the filtering { p->currentTest = &tc; p->failure_flags = TestCaseFailureReason::None; p->seconds = 0; // reset atomic counters p->numAssertsFailedCurrentTest_atomic = 0; p->numAssertsCurrentTest_atomic = 0; p->fullyTraversedSubcases.clear(); DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_start, tc); p->timer.start(); bool run_test = true; do { // reset some of the fields for subcases (except for the set of fully passed ones) p->reachedLeaf = false; // May not be empty if previous subcase exited via exception. p->subcaseStack.clear(); p->currentSubcaseDepth = 0; p->shouldLogCurrentException = true; // reset stuff for logging with INFO() p->stringifiedContexts.clear(); #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS try { #endif // DOCTEST_CONFIG_NO_EXCEPTIONS // MSVC 2015 diagnoses fatalConditionHandler as unused (because reset() is a static method) DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4101) // unreferenced local variable FatalConditionHandler fatalConditionHandler; // Handle signals // execute the test tc.m_test(); fatalConditionHandler.reset(); DOCTEST_MSVC_SUPPRESS_WARNING_POP #ifndef DOCTEST_CONFIG_NO_EXCEPTIONS } catch(const TestFailureException&) { p->failure_flags |= TestCaseFailureReason::AssertFailure; } catch(...) { DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_exception, {translateActiveException(), false}); p->failure_flags |= TestCaseFailureReason::Exception; } #endif // DOCTEST_CONFIG_NO_EXCEPTIONS // exit this loop if enough assertions have failed - even if there are more subcases if(p->abort_after > 0 && p->numAssertsFailed + p->numAssertsFailedCurrentTest_atomic >= p->abort_after) { run_test = false; p->failure_flags |= TestCaseFailureReason::TooManyFailedAsserts; } if(!p->nextSubcaseStack.empty() && run_test) DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_reenter, tc); if(p->nextSubcaseStack.empty()) run_test = false; } while(run_test); p->finalizeTestCaseData(); DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_end, *g_cs); p->currentTest = nullptr; // stop executing tests if enough assertions have failed if(p->abort_after > 0 && p->numAssertsFailed >= p->abort_after) break; } } if(!query_mode) { DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_end, *g_cs); } else { QueryData qdata; qdata.run_stats = g_cs; qdata.data = queryResults.data(); qdata.num_data = unsigned(queryResults.size()); DOCTEST_ITERATE_THROUGH_REPORTERS(report_query, qdata); } return cleanup_and_return(); } DOCTEST_DEFINE_INTERFACE(IReporter) int IReporter::get_num_active_contexts() { return detail::g_infoContexts.size(); } const IContextScope* const* IReporter::get_active_contexts() { return get_num_active_contexts() ? &detail::g_infoContexts[0] : nullptr; } int IReporter::get_num_stringified_contexts() { return detail::g_cs->stringifiedContexts.size(); } const String* IReporter::get_stringified_contexts() { return get_num_stringified_contexts() ? &detail::g_cs->stringifiedContexts[0] : nullptr; } namespace detail { void registerReporterImpl(const char* name, int priority, reporterCreatorFunc c, bool isReporter) { if(isReporter) getReporters().insert(reporterMap::value_type(reporterMap::key_type(priority, name), c)); else getListeners().insert(reporterMap::value_type(reporterMap::key_type(priority, name), c)); } } // namespace detail } // namespace doctest #endif // DOCTEST_CONFIG_DISABLE #ifdef DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4007) // 'function' : must be 'attribute' - see issue #182 int main(int argc, char** argv) { return doctest::Context(argc, argv).run(); } DOCTEST_MSVC_SUPPRESS_WARNING_POP #endif // DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN DOCTEST_CLANG_SUPPRESS_WARNING_POP DOCTEST_MSVC_SUPPRESS_WARNING_POP DOCTEST_GCC_SUPPRESS_WARNING_POP DOCTEST_SUPPRESS_COMMON_WARNINGS_POP #endif // DOCTEST_LIBRARY_IMPLEMENTATION #endif // DOCTEST_CONFIG_IMPLEMENT #ifdef DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN #undef WIN32_LEAN_AND_MEAN #undef DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN #endif // DOCTEST_UNDEF_WIN32_LEAN_AND_MEAN #ifdef DOCTEST_UNDEF_NOMINMAX #undef NOMINMAX #undef DOCTEST_UNDEF_NOMINMAX #endif // DOCTEST_UNDEF_NOMINMAX
yhirose/mtlcpp
16
Utilities for Metal-cpp
C++
yhirose
test/mnist.cpp
C++
#define NS_PRIVATE_IMPLEMENTATION #define MTL_PRIVATE_IMPLEMENTATION #include <mtlcpp.h> #include <sys/stat.h> #include <fstream> #include <iostream> #include <map> class memory_mapped_file { public: memory_mapped_file(const char* path) { fd_ = open(path, O_RDONLY); assert(fd_ != -1); struct stat sb; fstat(fd_, &sb); size_ = sb.st_size; addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0); assert(addr_ != MAP_FAILED); } ~memory_mapped_file() { munmap(addr_, size_); close(fd_); } const char* data() const { return (const char*)addr_; } private: int fd_ = -1; size_t size_ = 0; void* addr_ = MAP_FAILED; }; class mnist_data { public: mnist_data(const char* label_data_path, const char* image_data_path) : label_data_(label_data_path), image_data_(image_data_path) { if (read32(label_data_, 0) != 2049) { throw std::runtime_error("invalid label data format."); } if (read32(image_data_, 0) != 2051) { throw std::runtime_error("invalid image data format."); } number_of_items_ = read32(label_data_, 4); if (number_of_items_ != read32(image_data_, 4)) { throw std::runtime_error("image data doesn't match label data."); } labels_ = reinterpret_cast<const uint8_t*>(label_data_.data() + 8); number_of_rows_ = read32(image_data_, 8); number_of_columns_ = read32(image_data_, 12); pixels_ = reinterpret_cast<const uint8_t*>(image_data_.data() + 16); } size_t size() const { return number_of_items_; } // Label const uint8_t* label_data() const { return labels_; } size_t label(size_t i) const { return labels_[i]; } // Image const float* normalized_image_data() const { if (normalized_pixels_.empty()) { auto total_pixels = image_pixel_size() * size(); normalized_pixels_.resize(total_pixels); for (size_t i = 0; i < total_pixels; i++) { normalized_pixels_[i] = (float)pixels_[i] / (float)255; } } return normalized_pixels_.data(); } size_t image_rows() const { return number_of_rows_; } size_t image_columns() const { return number_of_columns_; } size_t image_pixel_size() const { return number_of_rows_ * number_of_columns_; } uint8_t pixel(size_t row, size_t col) const { return pixels_[number_of_columns_ * row + col]; } private: uint32_t read32(const memory_mapped_file& mm, size_t off) { auto p = mm.data() + off; return __builtin_bswap32(*reinterpret_cast<const uint32_t*>(p)); } size_t number_of_items_ = 0; size_t number_of_rows_ = 0; size_t number_of_columns_ = 0; const uint8_t* labels_ = nullptr; const uint8_t* pixels_ = nullptr; memory_mapped_file label_data_; memory_mapped_file image_data_; mutable std::vector<float> normalized_pixels_; }; struct Network { std::map<std::string, mtl::array<float>> w; std::map<std::string, mtl::array<float>> b; }; Network init_network() { auto split = [](const char* b, const char* e, char d, std::function<void(const char*, const char*)> fn) { size_t i = 0; size_t beg = 0; while (e ? (b + i < e) : (b[i] != '\0')) { if (b[i] == d) { fn(&b[beg], &b[i]); beg = i + 1; } i++; } if (i) { fn(&b[beg], &b[i]); } }; Network network; std::ifstream f("sample_weight.csv"); std::string line; while (std::getline(f, line)) { std::replace(line.begin(), line.end(), ',', ' '); std::istringstream s(line); std::string label; size_t rows; size_t cols; s >> label >> rows >> cols; std::vector<float> values; { values.reserve(rows * cols); auto count = rows; while (count > 0) { std::getline(f, line); split(&line[0], &line[line.size() - 1], ',', [&](auto b, auto /*e*/) { values.push_back(std::atof(b)); }); count--; } } if (rows > 1) { network.w[label] = mtl::array<float>({rows, cols}, values); } else { network.b[label] = mtl::array<float>({cols}, values); } } return network; } auto predict(const Network& network, const mtl::array<float>& x) { auto W1 = network.w.at("W1"); auto W2 = network.w.at("W2"); auto W3 = network.w.at("W3"); auto b1 = network.b.at("b1"); auto b2 = network.b.at("b2"); auto b3 = network.b.at("b3"); auto a1 = x.dot(W1) + b1; auto z1 = a1.sigmoid(); auto a2 = z1.dot(W2) + b2; auto z2 = a2.sigmoid(); auto a3 = z2.dot(W3) + b3; auto y = a3.softmax(); return y; } int main(int argc, const char** argv) { try { if (argc > 1) { if (std::string("--cpu") == argv[1]) { mtl::use_cpu(); } } auto data = mnist_data("t10k-labels-idx1-ubyte", "t10k-images-idx3-ubyte"); auto network = init_network(); auto p = data.normalized_image_data(); size_t batch_size = 100; size_t accuracy_cnt = 0; for (auto i = 0u; i < data.size(); i += batch_size) { auto x = mtl::array<float>({batch_size, data.image_pixel_size()}, p + data.image_pixel_size() * i); auto y = predict(network, x); auto e = mtl::array<int>({batch_size}, data.label_data() + i); auto a = y.argmax(); auto r = e == a; accuracy_cnt += r.count(); } auto accuracy = (double)accuracy_cnt / (double)data.size(); std::cout << "MNIST Accuracy: " << accuracy << std::endl; } catch (const std::runtime_error& e) { std::cerr << e.what() << std::endl; } }
yhirose/mtlcpp
16
Utilities for Metal-cpp
C++
yhirose
test/nanobench.h
C/C++ Header
// __ _ _______ __ _ _____ ______ _______ __ _ _______ _ _ // | \ | |_____| | \ | | | |_____] |______ | \ | | |_____| // | \_| | | | \_| |_____| |_____] |______ | \_| |_____ | | // // Microbenchmark framework for C++11/14/17/20 // https://github.com/martinus/nanobench // // Licensed under the MIT License <http://opensource.org/licenses/MIT>. // SPDX-License-Identifier: MIT // Copyright (c) 2019-2023 Martin Leitner-Ankerl <martin.ankerl@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #ifndef ANKERL_NANOBENCH_H_INCLUDED #define ANKERL_NANOBENCH_H_INCLUDED // see https://semver.org/ #define ANKERL_NANOBENCH_VERSION_MAJOR 4 // incompatible API changes #define ANKERL_NANOBENCH_VERSION_MINOR 3 // backwards-compatible changes #define ANKERL_NANOBENCH_VERSION_PATCH 11 // backwards-compatible bug fixes /////////////////////////////////////////////////////////////////////////////////////////////////// // public facing api - as minimal as possible /////////////////////////////////////////////////////////////////////////////////////////////////// #include <chrono> // high_resolution_clock #include <cstring> // memcpy #include <iosfwd> // for std::ostream* custom output target in Config #include <string> // all names #include <unordered_map> // holds context information of results #include <vector> // holds all results #define ANKERL_NANOBENCH(x) ANKERL_NANOBENCH_PRIVATE_##x() #define ANKERL_NANOBENCH_PRIVATE_CXX() __cplusplus #define ANKERL_NANOBENCH_PRIVATE_CXX98() 199711L #define ANKERL_NANOBENCH_PRIVATE_CXX11() 201103L #define ANKERL_NANOBENCH_PRIVATE_CXX14() 201402L #define ANKERL_NANOBENCH_PRIVATE_CXX17() 201703L #if ANKERL_NANOBENCH(CXX) >= ANKERL_NANOBENCH(CXX17) # define ANKERL_NANOBENCH_PRIVATE_NODISCARD() [[nodiscard]] #else # define ANKERL_NANOBENCH_PRIVATE_NODISCARD() #endif #if defined(__clang__) # define ANKERL_NANOBENCH_PRIVATE_IGNORE_PADDED_PUSH() \ _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wpadded\"") # define ANKERL_NANOBENCH_PRIVATE_IGNORE_PADDED_POP() _Pragma("clang diagnostic pop") #else # define ANKERL_NANOBENCH_PRIVATE_IGNORE_PADDED_PUSH() # define ANKERL_NANOBENCH_PRIVATE_IGNORE_PADDED_POP() #endif #if defined(__GNUC__) # define ANKERL_NANOBENCH_PRIVATE_IGNORE_EFFCPP_PUSH() _Pragma("GCC diagnostic push") _Pragma("GCC diagnostic ignored \"-Weffc++\"") # define ANKERL_NANOBENCH_PRIVATE_IGNORE_EFFCPP_POP() _Pragma("GCC diagnostic pop") #else # define ANKERL_NANOBENCH_PRIVATE_IGNORE_EFFCPP_PUSH() # define ANKERL_NANOBENCH_PRIVATE_IGNORE_EFFCPP_POP() #endif #if defined(ANKERL_NANOBENCH_LOG_ENABLED) # include <iostream> # define ANKERL_NANOBENCH_LOG(x) \ do { \ std::cout << __FUNCTION__ << "@" << __LINE__ << ": " << x << std::endl; \ } while (0) #else # define ANKERL_NANOBENCH_LOG(x) \ do { \ } while (0) #endif #define ANKERL_NANOBENCH_PRIVATE_PERF_COUNTERS() 0 #if defined(__linux__) && !defined(ANKERL_NANOBENCH_DISABLE_PERF_COUNTERS) # include <linux/version.h> # if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 3, 0) // PERF_COUNT_HW_REF_CPU_CYCLES only available since kernel 3.3 // PERF_FLAG_FD_CLOEXEC since kernel 3.14 # undef ANKERL_NANOBENCH_PRIVATE_PERF_COUNTERS # define ANKERL_NANOBENCH_PRIVATE_PERF_COUNTERS() 1 # endif #endif #if defined(__clang__) # define ANKERL_NANOBENCH_NO_SANITIZE(...) __attribute__((no_sanitize(__VA_ARGS__))) #else # define ANKERL_NANOBENCH_NO_SANITIZE(...) #endif #if defined(_MSC_VER) # define ANKERL_NANOBENCH_PRIVATE_NOINLINE() __declspec(noinline) #else # define ANKERL_NANOBENCH_PRIVATE_NOINLINE() __attribute__((noinline)) #endif // workaround missing "is_trivially_copyable" in g++ < 5.0 // See https://stackoverflow.com/a/31798726/48181 #if defined(__GNUC__) && __GNUC__ < 5 # define ANKERL_NANOBENCH_IS_TRIVIALLY_COPYABLE(...) __has_trivial_copy(__VA_ARGS__) #else # define ANKERL_NANOBENCH_IS_TRIVIALLY_COPYABLE(...) std::is_trivially_copyable<__VA_ARGS__>::value #endif // noexcept may be missing for std::string. // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58265 #define ANKERL_NANOBENCH_PRIVATE_NOEXCEPT_STRING_MOVE() std::is_nothrow_move_assignable<std::string>::value // declarations /////////////////////////////////////////////////////////////////////////////////// namespace ankerl { namespace nanobench { using Clock = std::conditional<std::chrono::high_resolution_clock::is_steady, std::chrono::high_resolution_clock, std::chrono::steady_clock>::type; class Bench; struct Config; class Result; class Rng; class BigO; /** * @brief Renders output from a mustache-like template and benchmark results. * * The templating facility here is heavily inspired by [mustache - logic-less templates](https://mustache.github.io/). * It adds a few more features that are necessary to get all of the captured data out of nanobench. Please read the * excellent [mustache manual](https://mustache.github.io/mustache.5.html) to see what this is all about. * * nanobench output has two nested layers, *result* and *measurement*. Here is a hierarchy of the allowed tags: * * * `{{#result}}` Marks the begin of the result layer. Whatever comes after this will be instantiated as often as * a benchmark result is available. Within it, you can use these tags: * * * `{{title}}` See Bench::title. * * * `{{name}}` Benchmark name, usually directly provided with Bench::run, but can also be set with Bench::name. * * * `{{unit}}` Unit, e.g. `byte`. Defaults to `op`, see Bench::unit. * * * `{{batch}}` Batch size, see Bench::batch. * * * `{{complexityN}}` Value used for asymptotic complexity calculation. See Bench::complexityN. * * * `{{epochs}}` Number of epochs, see Bench::epochs. * * * `{{clockResolution}}` Accuracy of the clock, i.e. what's the smallest time possible to measure with the clock. * For modern systems, this can be around 20 ns. This value is automatically determined by nanobench at the first * benchmark that is run, and used as a static variable throughout the application's runtime. * * * `{{clockResolutionMultiple}}` Configuration multiplier for `clockResolution`. See Bench::clockResolutionMultiple. * This is the target runtime for each measurement (epoch). That means the more accurate your clock is, the faster * will be the benchmark. Basing the measurement's runtime on the clock resolution is the main reason why nanobench is so fast. * * * `{{maxEpochTime}}` Configuration for a maximum time each measurement (epoch) is allowed to take. Note that at least * a single iteration will be performed, even when that takes longer than maxEpochTime. See Bench::maxEpochTime. * * * `{{minEpochTime}}` Minimum epoch time, defaults to 1ms. See Bench::minEpochTime. * * * `{{minEpochIterations}}` See Bench::minEpochIterations. * * * `{{epochIterations}}` See Bench::epochIterations. * * * `{{warmup}}` Number of iterations used before measuring starts. See Bench::warmup. * * * `{{relative}}` True or false, depending on the setting you have used. See Bench::relative. * * * `{{context(variableName)}}` See Bench::context. * * Apart from these tags, it is also possible to use some mathematical operations on the measurement data. The operations * are of the form `{{command(name)}}`. Currently `name` can be one of `elapsed`, `iterations`. If performance counters * are available (currently only on current Linux systems), you also have `pagefaults`, `cpucycles`, * `contextswitches`, `instructions`, `branchinstructions`, and `branchmisses`. All the measures (except `iterations`) are * provided for a single iteration (so `elapsed` is the time a single iteration took). The following tags are available: * * * `{{median(<name>)}}` Calculate median of a measurement data set, e.g. `{{median(elapsed)}}`. * * * `{{average(<name>)}}` Average (mean) calculation. * * * `{{medianAbsolutePercentError(<name>)}}` Calculates MdAPE, the Median Absolute Percentage Error. The MdAPE is an excellent * metric for the variation of measurements. It is more robust to outliers than the * [Mean absolute percentage error (M-APE)](https://en.wikipedia.org/wiki/Mean_absolute_percentage_error). * @f[ * \mathrm{MdAPE}(e) = \mathrm{med}\{| \frac{e_i - \mathrm{med}\{e\}}{e_i}| \} * @f] * E.g. for *elapsed*: First, @f$ \mathrm{med}\{e\} @f$ calculates the median by sorting and then taking the middle element * of all *elapsed* measurements. This is used to calculate the absolute percentage * error to this median for each measurement, as in @f$ | \frac{e_i - \mathrm{med}\{e\}}{e_i}| @f$. All these results * are sorted, and the middle value is chosen as the median absolute percent error. * * This measurement is a bit hard to interpret, but it is very robust against outliers. E.g. a value of 5% means that half of the * measurements deviate less than 5% from the median, and the other deviate more than 5% from the median. * * * `{{sum(<name>)}}` Sum of all the measurements. E.g. `{{sum(iterations)}}` will give you the total number of iterations * measured in this benchmark. * * * `{{minimum(<name>)}}` Minimum of all measurements. * * * `{{maximum(<name>)}}` Maximum of all measurements. * * * `{{sumProduct(<first>, <second>)}}` Calculates the sum of the products of corresponding measures: * @f[ * \mathrm{sumProduct}(a,b) = \sum_{i=1}^{n}a_i\cdot b_i * @f] * E.g. to calculate total runtime of the benchmark, you multiply iterations with elapsed time for each measurement, and * sum these results up: * `{{sumProduct(iterations, elapsed)}}`. * * * `{{#measurement}}` To access individual measurement results, open the begin tag for measurements. * * * `{{elapsed}}` Average elapsed wall clock time per iteration, in seconds. * * * `{{iterations}}` Number of iterations in the measurement. The number of iterations will fluctuate due * to some applied randomness, to enhance accuracy. * * * `{{pagefaults}}` Average number of pagefaults per iteration. * * * `{{cpucycles}}` Average number of CPU cycles processed per iteration. * * * `{{contextswitches}}` Average number of context switches per iteration. * * * `{{instructions}}` Average number of retired instructions per iteration. * * * `{{branchinstructions}}` Average number of branches executed per iteration. * * * `{{branchmisses}}` Average number of branches that were missed per iteration. * * * `{{/measurement}}` Ends the measurement tag. * * * `{{/result}}` Marks the end of the result layer. This is the end marker for the template part that will be instantiated * for each benchmark result. * * * For the layer tags *result* and *measurement* you additionally can use these special markers: * * * ``{{#-first}}`` - Begin marker of a template that will be instantiated *only for the first* entry in the layer. Use is only * allowed between the begin and end marker of the layer. So between ``{{#result}}`` and ``{{/result}}``, or between * ``{{#measurement}}`` and ``{{/measurement}}``. Finish the template with ``{{/-first}}``. * * * ``{{^-first}}`` - Begin marker of a template that will be instantiated *for each except the first* entry in the layer. This, * this is basically the inversion of ``{{#-first}}``. Use is only allowed between the begin and end marker of the layer. * So between ``{{#result}}`` and ``{{/result}}``, or between ``{{#measurement}}`` and ``{{/measurement}}``. * * * ``{{/-first}}`` - End marker for either ``{{#-first}}`` or ``{{^-first}}``. * * * ``{{#-last}}`` - Begin marker of a template that will be instantiated *only for the last* entry in the layer. Use is only * allowed between the begin and end marker of the layer. So between ``{{#result}}`` and ``{{/result}}``, or between * ``{{#measurement}}`` and ``{{/measurement}}``. Finish the template with ``{{/-last}}``. * * * ``{{^-last}}`` - Begin marker of a template that will be instantiated *for each except the last* entry in the layer. This, * this is basically the inversion of ``{{#-last}}``. Use is only allowed between the begin and end marker of the layer. * So between ``{{#result}}`` and ``{{/result}}``, or between ``{{#measurement}}`` and ``{{/measurement}}``. * * * ``{{/-last}}`` - End marker for either ``{{#-last}}`` or ``{{^-last}}``. * @verbatim embed:rst For an overview of all the possible data you can get out of nanobench, please see the tutorial at :ref:`tutorial-template-json`. The templates that ship with nanobench are: * :cpp:func:`templates::csv() <ankerl::nanobench::templates::csv()>` * :cpp:func:`templates::json() <ankerl::nanobench::templates::json()>` * :cpp:func:`templates::htmlBoxplot() <ankerl::nanobench::templates::htmlBoxplot()>` * :cpp:func:`templates::pyperf() <ankerl::nanobench::templates::pyperf()>` @endverbatim * * @param mustacheTemplate The template. * @param bench Benchmark, containing all the results. * @param out Output for the generated output. */ void render(char const* mustacheTemplate, Bench const& bench, std::ostream& out); void render(std::string const& mustacheTemplate, Bench const& bench, std::ostream& out); /** * Same as render(char const* mustacheTemplate, Bench const& bench, std::ostream& out), but for when * you only have results available. * * @param mustacheTemplate The template. * @param results All the results to be used for rendering. * @param out Output for the generated output. */ void render(char const* mustacheTemplate, std::vector<Result> const& results, std::ostream& out); void render(std::string const& mustacheTemplate, std::vector<Result> const& results, std::ostream& out); // Contains mustache-like templates namespace templates { /*! @brief CSV data for the benchmark results. Generates a comma-separated values dataset. First line is the header, each following line is a summary of each benchmark run. @verbatim embed:rst See the tutorial at :ref:`tutorial-template-csv` for an example. @endverbatim */ char const* csv() noexcept; /*! @brief HTML output that uses plotly to generate an interactive boxplot chart. See the tutorial for an example output. The output uses only the elapsed wall clock time, and displays each epoch as a single dot. @verbatim embed:rst See the tutorial at :ref:`tutorial-template-html` for an example. @endverbatim @see also ankerl::nanobench::render() */ char const* htmlBoxplot() noexcept; /*! @brief Output in pyperf compatible JSON format, which can be used for more analyzation. @verbatim embed:rst See the tutorial at :ref:`tutorial-template-pyperf` for an example how to further analyze the output. @endverbatim */ char const* pyperf() noexcept; /*! @brief Template to generate JSON data. The generated JSON data contains *all* data that has been generated. All times are as double values, in seconds. The output can get quite large. @verbatim embed:rst See the tutorial at :ref:`tutorial-template-json` for an example. @endverbatim */ char const* json() noexcept; } // namespace templates namespace detail { template <typename T> struct PerfCountSet; class IterationLogic; class PerformanceCounters; #if ANKERL_NANOBENCH(PERF_COUNTERS) class LinuxPerformanceCounters; #endif } // namespace detail } // namespace nanobench } // namespace ankerl // definitions //////////////////////////////////////////////////////////////////////////////////// namespace ankerl { namespace nanobench { namespace detail { template <typename T> struct PerfCountSet { T pageFaults{}; T cpuCycles{}; T contextSwitches{}; T instructions{}; T branchInstructions{}; T branchMisses{}; }; } // namespace detail ANKERL_NANOBENCH(IGNORE_PADDED_PUSH) struct Config { // actual benchmark config std::string mBenchmarkTitle = "benchmark"; // NOLINT(misc-non-private-member-variables-in-classes) std::string mBenchmarkName = "noname"; // NOLINT(misc-non-private-member-variables-in-classes) std::string mUnit = "op"; // NOLINT(misc-non-private-member-variables-in-classes) double mBatch = 1.0; // NOLINT(misc-non-private-member-variables-in-classes) double mComplexityN = -1.0; // NOLINT(misc-non-private-member-variables-in-classes) size_t mNumEpochs = 11; // NOLINT(misc-non-private-member-variables-in-classes) size_t mClockResolutionMultiple = static_cast<size_t>(1000); // NOLINT(misc-non-private-member-variables-in-classes) std::chrono::nanoseconds mMaxEpochTime = std::chrono::milliseconds(100); // NOLINT(misc-non-private-member-variables-in-classes) std::chrono::nanoseconds mMinEpochTime = std::chrono::milliseconds(1); // NOLINT(misc-non-private-member-variables-in-classes) uint64_t mMinEpochIterations{1}; // NOLINT(misc-non-private-member-variables-in-classes) // If not 0, run *exactly* these number of iterations per epoch. uint64_t mEpochIterations{0}; // NOLINT(misc-non-private-member-variables-in-classes) uint64_t mWarmup = 0; // NOLINT(misc-non-private-member-variables-in-classes) std::ostream* mOut = nullptr; // NOLINT(misc-non-private-member-variables-in-classes) std::chrono::duration<double> mTimeUnit = std::chrono::nanoseconds{1}; // NOLINT(misc-non-private-member-variables-in-classes) std::string mTimeUnitName = "ns"; // NOLINT(misc-non-private-member-variables-in-classes) bool mShowPerformanceCounters = true; // NOLINT(misc-non-private-member-variables-in-classes) bool mIsRelative = false; // NOLINT(misc-non-private-member-variables-in-classes) std::unordered_map<std::string, std::string> mContext{}; // NOLINT(misc-non-private-member-variables-in-classes) Config(); ~Config(); Config& operator=(Config const& other); Config& operator=(Config&& other) noexcept(ANKERL_NANOBENCH(NOEXCEPT_STRING_MOVE)); Config(Config const& other); Config(Config&& other) noexcept; }; ANKERL_NANOBENCH(IGNORE_PADDED_POP) // Result returned after a benchmark has finished. Can be used as a baseline for relative(). ANKERL_NANOBENCH(IGNORE_PADDED_PUSH) class Result { public: enum class Measure : size_t { elapsed, iterations, pagefaults, cpucycles, contextswitches, instructions, branchinstructions, branchmisses, _size }; explicit Result(Config benchmarkConfig); ~Result(); Result& operator=(Result const& other); Result& operator=(Result&& other) noexcept(ANKERL_NANOBENCH(NOEXCEPT_STRING_MOVE)); Result(Result const& other); Result(Result&& other) noexcept; // adds new measurement results // all values are scaled by iters (except iters...) void add(Clock::duration totalElapsed, uint64_t iters, detail::PerformanceCounters const& pc); ANKERL_NANOBENCH(NODISCARD) Config const& config() const noexcept; ANKERL_NANOBENCH(NODISCARD) double median(Measure m) const; ANKERL_NANOBENCH(NODISCARD) double medianAbsolutePercentError(Measure m) const; ANKERL_NANOBENCH(NODISCARD) double average(Measure m) const; ANKERL_NANOBENCH(NODISCARD) double sum(Measure m) const noexcept; ANKERL_NANOBENCH(NODISCARD) double sumProduct(Measure m1, Measure m2) const noexcept; ANKERL_NANOBENCH(NODISCARD) double minimum(Measure m) const noexcept; ANKERL_NANOBENCH(NODISCARD) double maximum(Measure m) const noexcept; ANKERL_NANOBENCH(NODISCARD) std::string const& context(char const* variableName) const; ANKERL_NANOBENCH(NODISCARD) std::string const& context(std::string const& variableName) const; ANKERL_NANOBENCH(NODISCARD) bool has(Measure m) const noexcept; ANKERL_NANOBENCH(NODISCARD) double get(size_t idx, Measure m) const; ANKERL_NANOBENCH(NODISCARD) bool empty() const noexcept; ANKERL_NANOBENCH(NODISCARD) size_t size() const noexcept; // Finds string, if not found, returns _size. static Measure fromString(std::string const& str); private: Config mConfig{}; std::vector<std::vector<double>> mNameToMeasurements{}; }; ANKERL_NANOBENCH(IGNORE_PADDED_POP) /** * An extremely fast random generator. Currently, this implements *RomuDuoJr*, developed by Mark Overton. Source: * http://www.romu-random.org/ * * RomuDuoJr is extremely fast and provides reasonable good randomness. Not enough for large jobs, but definitely * good enough for a benchmarking framework. * * * Estimated capacity: @f$ 2^{51} @f$ bytes * * Register pressure: 4 * * State size: 128 bits * * This random generator is a drop-in replacement for the generators supplied by ``<random>``. It is not * cryptographically secure. It's intended purpose is to be very fast so that benchmarks that make use * of randomness are not distorted too much by the random generator. * * Rng also provides a few non-standard helpers, optimized for speed. */ class Rng final { public: /** * @brief This RNG provides 64bit randomness. */ using result_type = uint64_t; static constexpr uint64_t(min)(); static constexpr uint64_t(max)(); /** * As a safety precaution, we don't allow copying. Copying a PRNG would mean you would have two random generators that produce the * same sequence, which is generally not what one wants. Instead create a new rng with the default constructor Rng(), which is * automatically seeded from `std::random_device`. If you really need a copy, use `copy()`. */ Rng(Rng const&) = delete; /** * Same as Rng(Rng const&), we don't allow assignment. If you need a new Rng create one with the default constructor Rng(). */ Rng& operator=(Rng const&) = delete; // moving is ok Rng(Rng&&) noexcept = default; Rng& operator=(Rng&&) noexcept = default; ~Rng() noexcept = default; /** * @brief Creates a new Random generator with random seed. * * Instead of a default seed (as the random generators from the STD), this properly seeds the random generator from * `std::random_device`. It guarantees correct seeding. Note that seeding can be relatively slow, depending on the source of * randomness used. So it is best to create a Rng once and use it for all your randomness purposes. */ Rng(); /*! Creates a new Rng that is seeded with a specific seed. Each Rng created from the same seed will produce the same randomness sequence. This can be useful for deterministic behavior. @verbatim embed:rst .. note:: The random algorithm might change between nanobench releases. Whenever a faster and/or better random generator becomes available, I will switch the implementation. @endverbatim As per the Romu paper, this seeds the Rng with splitMix64 algorithm and performs 10 initial rounds for further mixing up of the internal state. @param seed The 64bit seed. All values are allowed, even 0. */ explicit Rng(uint64_t seed) noexcept; Rng(uint64_t x, uint64_t y) noexcept; explicit Rng(std::vector<uint64_t> const& data); /** * Creates a copy of the Rng, thus the copy provides exactly the same random sequence as the original. */ ANKERL_NANOBENCH(NODISCARD) Rng copy() const noexcept; /** * @brief Produces a 64bit random value. This should be very fast, thus it is marked as inline. In my benchmark, this is ~46 times * faster than `std::default_random_engine` for producing 64bit random values. It seems that the fastest std contender is * `std::mt19937_64`. Still, this RNG is 2-3 times as fast. * * @return uint64_t The next 64 bit random value. */ inline uint64_t operator()() noexcept; // This is slightly biased. See /** * Generates a random number between 0 and range (excluding range). * * The algorithm only produces 32bit numbers, and is slightly biased. The effect is quite small unless your range is close to the * maximum value of an integer. It is possible to correct the bias with rejection sampling (see * [here](https://lemire.me/blog/2016/06/30/fast-random-shuffling/), but this is most likely irrelevant in practices for the * purposes of this Rng. * * See Daniel Lemire's blog post [A fast alternative to the modulo * reduction](https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/) * * @param range Upper exclusive range. E.g a value of 3 will generate random numbers 0, 1, 2. * @return uint32_t Generated random values in range [0, range(. */ inline uint32_t bounded(uint32_t range) noexcept; // random double in range [0, 1( // see http://prng.di.unimi.it/ /** * Provides a random uniform double value between 0 and 1. This uses the method described in [Generating uniform doubles in the * unit interval](http://prng.di.unimi.it/), and is extremely fast. * * @return double Uniformly distributed double value in range [0,1(, excluding 1. */ inline double uniform01() noexcept; /** * Shuffles all entries in the given container. Although this has a slight bias due to the implementation of bounded(), this is * preferable to `std::shuffle` because it is over 5 times faster. See Daniel Lemire's blog post [Fast random * shuffling](https://lemire.me/blog/2016/06/30/fast-random-shuffling/). * * @param container The whole container will be shuffled. */ template <typename Container> void shuffle(Container& container) noexcept; /** * Extracts the full state of the generator, e.g. for serialization. For this RNG this is just 2 values, but to stay API compatible * with future implementations that potentially use more state, we use a vector. * * @return Vector containing the full state: */ ANKERL_NANOBENCH(NODISCARD) std::vector<uint64_t> state() const; private: static constexpr uint64_t rotl(uint64_t x, unsigned k) noexcept; uint64_t mX; uint64_t mY; }; /** * @brief Main entry point to nanobench's benchmarking facility. * * It holds configuration and results from one or more benchmark runs. Usually it is used in a single line, where the object is * constructed, configured, and then a benchmark is run. E.g. like this: * * ankerl::nanobench::Bench().unit("byte").batch(1000).run("random fluctuations", [&] { * // here be the benchmark code * }); * * In that example Bench() constructs the benchmark, it is then configured with unit() and batch(), and after configuration a * benchmark is executed with run(). Once run() has finished, it prints the result to `std::cout`. It would also store the results * in the Bench instance, but in this case the object is immediately destroyed so it's not available any more. */ ANKERL_NANOBENCH(IGNORE_PADDED_PUSH) class Bench { public: /** * @brief Creates a new benchmark for configuration and running of benchmarks. */ Bench(); Bench(Bench&& other) noexcept; Bench& operator=(Bench&& other) noexcept(ANKERL_NANOBENCH(NOEXCEPT_STRING_MOVE)); Bench(Bench const& other); Bench& operator=(Bench const& other); ~Bench() noexcept; /*! @brief Repeatedly calls `op()` based on the configuration, and performs measurements. This call is marked with `noinline` to prevent the compiler to optimize beyond different benchmarks. This can have quite a big effect on benchmark accuracy. @verbatim embed:rst .. note:: Each call to your lambda must have a side effect that the compiler can't possibly optimize it away. E.g. add a result to an externally defined number (like `x` in the above example), and finally call `doNotOptimizeAway` on the variables the compiler must not remove. You can also use :cpp:func:`ankerl::nanobench::doNotOptimizeAway` directly in the lambda, but be aware that this has a small overhead. @endverbatim @tparam Op The code to benchmark. */ template <typename Op> ANKERL_NANOBENCH(NOINLINE) Bench& run(char const* benchmarkName, Op&& op); template <typename Op> ANKERL_NANOBENCH(NOINLINE) Bench& run(std::string const& benchmarkName, Op&& op); /** * @brief Same as run(char const* benchmarkName, Op op), but instead uses the previously set name. * @tparam Op The code to benchmark. */ template <typename Op> ANKERL_NANOBENCH(NOINLINE) Bench& run(Op&& op); /** * @brief Title of the benchmark, will be shown in the table header. Changing the title will start a new markdown table. * * @param benchmarkTitle The title of the benchmark. */ Bench& title(char const* benchmarkTitle); Bench& title(std::string const& benchmarkTitle); /** * @brief Gets the title of the benchmark */ ANKERL_NANOBENCH(NODISCARD) std::string const& title() const noexcept; /// Name of the benchmark, will be shown in the table row. Bench& name(char const* benchmarkName); Bench& name(std::string const& benchmarkName); ANKERL_NANOBENCH(NODISCARD) std::string const& name() const noexcept; /** * @brief Set context information. * * The information can be accessed using custom render templates via `{{context(variableName)}}`. * Trying to render a variable that hasn't been set before raises an exception. * Not included in (default) markdown table. * * @see clearContext, render * * @param variableName The name of the context variable. * @param variableValue The value of the context variable. */ Bench& context(char const* variableName, char const* variableValue); Bench& context(std::string const& variableName, std::string const& variableValue); /** * @brief Reset context information. * * This may improve efficiency when using many context entries, * or improve robustness by removing spurious context entries. * * @see context */ Bench& clearContext(); /** * @brief Sets the batch size. * * E.g. number of processed byte, or some other metric for the size of the processed data in each iteration. If you benchmark * hashing of a 1000 byte long string and want byte/sec as a result, you can specify 1000 as the batch size. * * @tparam T Any input type is internally cast to `double`. * @param b batch size */ template <typename T> Bench& batch(T b) noexcept; ANKERL_NANOBENCH(NODISCARD) double batch() const noexcept; /** * @brief Sets the operation unit. * * Defaults to "op". Could be e.g. "byte" for string processing. This is used for the table header, e.g. to show `ns/byte`. Use * singular (*byte*, not *bytes*). A change clears the currently collected results. * * @param unit The unit name. */ Bench& unit(char const* unit); Bench& unit(std::string const& unit); ANKERL_NANOBENCH(NODISCARD) std::string const& unit() const noexcept; /** * @brief Sets the time unit to be used for the default output. * * Nanobench defaults to using ns (nanoseconds) as output in the markdown. For some benchmarks this is too coarse, so it is * possible to configure this. E.g. use `timeUnit(1ms, "ms")` to show `ms/op` instead of `ns/op`. * * @param tu Time unit to display the results in, default is 1ns. * @param tuName Name for the time unit, default is "ns" */ Bench& timeUnit(std::chrono::duration<double> const& tu, std::string const& tuName); ANKERL_NANOBENCH(NODISCARD) std::string const& timeUnitName() const noexcept; ANKERL_NANOBENCH(NODISCARD) std::chrono::duration<double> const& timeUnit() const noexcept; /** * @brief Set the output stream where the resulting markdown table will be printed to. * * The default is `&std::cout`. You can disable all output by setting `nullptr`. * * @param outstream Pointer to output stream, can be `nullptr`. */ Bench& output(std::ostream* outstream) noexcept; ANKERL_NANOBENCH(NODISCARD) std::ostream* output() const noexcept; /** * Modern processors have a very accurate clock, being able to measure as low as 20 nanoseconds. This is the main trick nanobech to * be so fast: we find out how accurate the clock is, then run the benchmark only so often that the clock's accuracy is good enough * for accurate measurements. * * The default is to run one epoch for 1000 times the clock resolution. So for 20ns resolution and 11 epochs, this gives a total * runtime of * * @f[ * 20ns * 1000 * 11 \approx 0.2ms * @f] * * To be precise, nanobench adds a 0-20% random noise to each evaluation. This is to prevent any aliasing effects, and further * improves accuracy. * * Total runtime will be higher though: Some initial time is needed to find out the target number of iterations for each epoch, and * there is some overhead involved to start & stop timers and calculate resulting statistics and writing the output. * * @param multiple Target number of times of clock resolution. Usually 1000 is a good compromise between runtime and accuracy. */ Bench& clockResolutionMultiple(size_t multiple) noexcept; ANKERL_NANOBENCH(NODISCARD) size_t clockResolutionMultiple() const noexcept; /** * @brief Controls number of epochs, the number of measurements to perform. * * The reported result will be the median of evaluation of each epoch. The higher you choose this, the more * deterministic the result be and outliers will be more easily removed. Also the `err%` will be more accurate the higher this * number is. Note that the `err%` will not necessarily decrease when number of epochs is increased. But it will be a more accurate * representation of the benchmarked code's runtime stability. * * Choose the value wisely. In practice, 11 has been shown to be a reasonable choice between runtime performance and accuracy. * This setting goes hand in hand with minEpochIterations() (or minEpochTime()). If you are more interested in *median* runtime, * you might want to increase epochs(). If you are more interested in *mean* runtime, you might want to increase * minEpochIterations() instead. * * @param numEpochs Number of epochs. */ Bench& epochs(size_t numEpochs) noexcept; ANKERL_NANOBENCH(NODISCARD) size_t epochs() const noexcept; /** * @brief Upper limit for the runtime of each epoch. * * As a safety precaution if the clock is not very accurate, we can set an upper limit for the maximum evaluation time per * epoch. Default is 100ms. At least a single evaluation of the benchmark is performed. * * @see minEpochTime, minEpochIterations * * @param t Maximum target runtime for a single epoch. */ Bench& maxEpochTime(std::chrono::nanoseconds t) noexcept; ANKERL_NANOBENCH(NODISCARD) std::chrono::nanoseconds maxEpochTime() const noexcept; /** * @brief Minimum time each epoch should take. * * Default is zero, so we are fully relying on clockResolutionMultiple(). In most cases this is exactly what you want. If you see * that the evaluation is unreliable with a high `err%`, you can increase either minEpochTime() or minEpochIterations(). * * @see maxEpochTime, minEpochIterations * * @param t Minimum time each epoch should take. */ Bench& minEpochTime(std::chrono::nanoseconds t) noexcept; ANKERL_NANOBENCH(NODISCARD) std::chrono::nanoseconds minEpochTime() const noexcept; /** * @brief Sets the minimum number of iterations each epoch should take. * * Default is 1, and we rely on clockResolutionMultiple(). If the `err%` is high and you want a more smooth result, you might want * to increase the minimum number of iterations, or increase the minEpochTime(). * * @see minEpochTime, maxEpochTime, minEpochIterations * * @param numIters Minimum number of iterations per epoch. */ Bench& minEpochIterations(uint64_t numIters) noexcept; ANKERL_NANOBENCH(NODISCARD) uint64_t minEpochIterations() const noexcept; /** * Sets exactly the number of iterations for each epoch. Ignores all other epoch limits. This forces nanobench to use exactly * the given number of iterations for each epoch, not more and not less. Default is 0 (disabled). * * @param numIters Exact number of iterations to use. Set to 0 to disable. */ Bench& epochIterations(uint64_t numIters) noexcept; ANKERL_NANOBENCH(NODISCARD) uint64_t epochIterations() const noexcept; /** * @brief Sets a number of iterations that are initially performed without any measurements. * * Some benchmarks need a few evaluations to warm up caches / database / whatever access. Normally this should not be needed, since * we show the median result so initial outliers will be filtered away automatically. If the warmup effect is large though, you * might want to set it. Default is 0. * * @param numWarmupIters Number of warmup iterations. */ Bench& warmup(uint64_t numWarmupIters) noexcept; ANKERL_NANOBENCH(NODISCARD) uint64_t warmup() const noexcept; /** * @brief Marks the next run as the baseline. * * Call `relative(true)` to mark the run as the baseline. Successive runs will be compared to this run. It is calculated by * * @f[ * 100\% * \frac{baseline}{runtime} * @f] * * * 100% means it is exactly as fast as the baseline * * >100% means it is faster than the baseline. E.g. 200% means the current run is twice as fast as the baseline. * * <100% means it is slower than the baseline. E.g. 50% means it is twice as slow as the baseline. * * See the tutorial section "Comparing Results" for example usage. * * @param isRelativeEnabled True to enable processing */ Bench& relative(bool isRelativeEnabled) noexcept; ANKERL_NANOBENCH(NODISCARD) bool relative() const noexcept; /** * @brief Enables/disables performance counters. * * On Linux nanobench has a powerful feature to use performance counters. This enables counting of retired instructions, count * number of branches, missed branches, etc. On default this is enabled, but you can disable it if you don't need that feature. * * @param showPerformanceCounters True to enable, false to disable. */ Bench& performanceCounters(bool showPerformanceCounters) noexcept; ANKERL_NANOBENCH(NODISCARD) bool performanceCounters() const noexcept; /** * @brief Retrieves all benchmark results collected by the bench object so far. * * Each call to run() generates a Result that is stored within the Bench instance. This is mostly for advanced users who want to * see all the nitty gritty details. * * @return All results collected so far. */ ANKERL_NANOBENCH(NODISCARD) std::vector<Result> const& results() const noexcept; /*! @verbatim embed:rst Convenience shortcut to :cpp:func:`ankerl::nanobench::doNotOptimizeAway`. @endverbatim */ template <typename Arg> Bench& doNotOptimizeAway(Arg&& arg); /*! @verbatim embed:rst Sets N for asymptotic complexity calculation, so it becomes possible to calculate `Big O <https://en.wikipedia.org/wiki/Big_O_notation>`_ from multiple benchmark evaluations. Use :cpp:func:`ankerl::nanobench::Bench::complexityBigO` when the evaluation has finished. See the tutorial :ref:`asymptotic-complexity` for details. @endverbatim @tparam T Any type is cast to `double`. @param n Length of N for the next benchmark run, so it is possible to calculate `bigO`. */ template <typename T> Bench& complexityN(T n) noexcept; ANKERL_NANOBENCH(NODISCARD) double complexityN() const noexcept; /*! Calculates [Big O](https://en.wikipedia.org/wiki/Big_O_notation>) of the results with all preconfigured complexity functions. Currently these complexity functions are fitted into the benchmark results: @f$ \mathcal{O}(1) @f$, @f$ \mathcal{O}(n) @f$, @f$ \mathcal{O}(\log{}n) @f$, @f$ \mathcal{O}(n\log{}n) @f$, @f$ \mathcal{O}(n^2) @f$, @f$ \mathcal{O}(n^3) @f$. If we e.g. evaluate the complexity of `std::sort`, this is the result of `std::cout << bench.complexityBigO()`: ``` | coefficient | err% | complexity |--------------:|-------:|------------ | 5.08935e-09 | 2.6% | O(n log n) | 6.10608e-08 | 8.0% | O(n) | 1.29307e-11 | 47.2% | O(n^2) | 2.48677e-15 | 69.6% | O(n^3) | 9.88133e-06 | 132.3% | O(log n) | 5.98793e-05 | 162.5% | O(1) ``` So in this case @f$ \mathcal{O}(n\log{}n) @f$ provides the best approximation. @verbatim embed:rst See the tutorial :ref:`asymptotic-complexity` for details. @endverbatim @return Evaluation results, which can be printed or otherwise inspected. */ std::vector<BigO> complexityBigO() const; /** * @brief Calculates bigO for a custom function. * * E.g. to calculate the mean squared error for @f$ \mathcal{O}(\log{}\log{}n) @f$, which is not part of the default set of * complexityBigO(), you can do this: * * ``` * auto logLogN = bench.complexityBigO("O(log log n)", [](double n) { * return std::log2(std::log2(n)); * }); * ``` * * The resulting mean squared error can be printed with `std::cout << logLogN`. E.g. it prints something like this: * * ```text * 2.46985e-05 * O(log log n), rms=1.48121 * ``` * * @tparam Op Type of mapping operation. * @param name Name for the function, e.g. "O(log log n)" * @param op Op's operator() maps a `double` with the desired complexity function, e.g. `log2(log2(n))`. * @return BigO Error calculation, which is streamable to std::cout. */ template <typename Op> BigO complexityBigO(char const* name, Op op) const; template <typename Op> BigO complexityBigO(std::string const& name, Op op) const; /*! @verbatim embed:rst Convenience shortcut to :cpp:func:`ankerl::nanobench::render`. @endverbatim */ Bench& render(char const* templateContent, std::ostream& os); Bench& render(std::string const& templateContent, std::ostream& os); Bench& config(Config const& benchmarkConfig); ANKERL_NANOBENCH(NODISCARD) Config const& config() const noexcept; private: Config mConfig{}; std::vector<Result> mResults{}; }; ANKERL_NANOBENCH(IGNORE_PADDED_POP) /** * @brief Makes sure none of the given arguments are optimized away by the compiler. * * @tparam Arg Type of the argument that shouldn't be optimized away. * @param arg The input that we mark as being used, even though we don't do anything with it. */ template <typename Arg> void doNotOptimizeAway(Arg&& arg); namespace detail { #if defined(_MSC_VER) void doNotOptimizeAwaySink(void const*); template <typename T> void doNotOptimizeAway(T const& val); #else // These assembly magic is directly from what Google Benchmark is doing. I have previously used what facebook's folly was doing, but // this seemed to have compilation problems in some cases. Google Benchmark seemed to be the most well tested anyways. // see https://github.com/google/benchmark/blob/v1.7.1/include/benchmark/benchmark.h#L443-L446 template <typename T> void doNotOptimizeAway(T const& val) { // NOLINTNEXTLINE(hicpp-no-assembler) asm volatile("" : : "r,m"(val) : "memory"); } template <typename T> void doNotOptimizeAway(T& val) { # if defined(__clang__) // NOLINTNEXTLINE(hicpp-no-assembler) asm volatile("" : "+r,m"(val) : : "memory"); # else // NOLINTNEXTLINE(hicpp-no-assembler) asm volatile("" : "+m,r"(val) : : "memory"); # endif } #endif // internally used, but visible because run() is templated. // Not movable/copy-able, so we simply use a pointer instead of unique_ptr. This saves us from // having to include <memory>, and the template instantiation overhead of unique_ptr which is unfortunately quite significant. ANKERL_NANOBENCH(IGNORE_EFFCPP_PUSH) class IterationLogic { public: explicit IterationLogic(Bench const& bench); IterationLogic(IterationLogic&&) = delete; IterationLogic& operator=(IterationLogic&&) = delete; IterationLogic(IterationLogic const&) = delete; IterationLogic& operator=(IterationLogic const&) = delete; ~IterationLogic(); ANKERL_NANOBENCH(NODISCARD) uint64_t numIters() const noexcept; void add(std::chrono::nanoseconds elapsed, PerformanceCounters const& pc) noexcept; void moveResultTo(std::vector<Result>& results) noexcept; private: struct Impl; Impl* mPimpl; }; ANKERL_NANOBENCH(IGNORE_EFFCPP_POP) ANKERL_NANOBENCH(IGNORE_PADDED_PUSH) class PerformanceCounters { public: PerformanceCounters(PerformanceCounters const&) = delete; PerformanceCounters(PerformanceCounters&&) = delete; PerformanceCounters& operator=(PerformanceCounters const&) = delete; PerformanceCounters& operator=(PerformanceCounters&&) = delete; PerformanceCounters(); ~PerformanceCounters(); void beginMeasure(); void endMeasure(); void updateResults(uint64_t numIters); ANKERL_NANOBENCH(NODISCARD) PerfCountSet<uint64_t> const& val() const noexcept; ANKERL_NANOBENCH(NODISCARD) PerfCountSet<bool> const& has() const noexcept; private: #if ANKERL_NANOBENCH(PERF_COUNTERS) LinuxPerformanceCounters* mPc = nullptr; #endif PerfCountSet<uint64_t> mVal{}; PerfCountSet<bool> mHas{}; }; ANKERL_NANOBENCH(IGNORE_PADDED_POP) // Gets the singleton PerformanceCounters& performanceCounters(); } // namespace detail class BigO { public: using RangeMeasure = std::vector<std::pair<double, double>>; template <typename Op> static RangeMeasure mapRangeMeasure(RangeMeasure data, Op op) { for (auto& rangeMeasure : data) { rangeMeasure.first = op(rangeMeasure.first); } return data; } static RangeMeasure collectRangeMeasure(std::vector<Result> const& results); template <typename Op> BigO(char const* bigOName, RangeMeasure const& rangeMeasure, Op rangeToN) : BigO(bigOName, mapRangeMeasure(rangeMeasure, rangeToN)) {} template <typename Op> BigO(std::string bigOName, RangeMeasure const& rangeMeasure, Op rangeToN) : BigO(std::move(bigOName), mapRangeMeasure(rangeMeasure, rangeToN)) {} BigO(char const* bigOName, RangeMeasure const& scaledRangeMeasure); BigO(std::string bigOName, RangeMeasure const& scaledRangeMeasure); ANKERL_NANOBENCH(NODISCARD) std::string const& name() const noexcept; ANKERL_NANOBENCH(NODISCARD) double constant() const noexcept; ANKERL_NANOBENCH(NODISCARD) double normalizedRootMeanSquare() const noexcept; ANKERL_NANOBENCH(NODISCARD) bool operator<(BigO const& other) const noexcept; private: std::string mName{}; double mConstant{}; double mNormalizedRootMeanSquare{}; }; std::ostream& operator<<(std::ostream& os, BigO const& bigO); std::ostream& operator<<(std::ostream& os, std::vector<ankerl::nanobench::BigO> const& bigOs); } // namespace nanobench } // namespace ankerl // implementation ///////////////////////////////////////////////////////////////////////////////// namespace ankerl { namespace nanobench { constexpr uint64_t(Rng::min)() { return 0; } constexpr uint64_t(Rng::max)() { return (std::numeric_limits<uint64_t>::max)(); } ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined") uint64_t Rng::operator()() noexcept { auto x = mX; mX = UINT64_C(15241094284759029579) * mY; mY = rotl(mY - x, 27); return x; } ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined") uint32_t Rng::bounded(uint32_t range) noexcept { uint64_t const r32 = static_cast<uint32_t>(operator()()); auto multiresult = r32 * range; return static_cast<uint32_t>(multiresult >> 32U); } double Rng::uniform01() noexcept { auto i = (UINT64_C(0x3ff) << 52U) | (operator()() >> 12U); // can't use union in c++ here for type puning, it's undefined behavior. // std::memcpy is optimized anyways. double d{}; std::memcpy(&d, &i, sizeof(double)); return d - 1.0; } template <typename Container> void Rng::shuffle(Container& container) noexcept { auto i = container.size(); while (i > 1U) { using std::swap; auto n = operator()(); // using decltype(i) instead of size_t to be compatible to containers with 32bit index (see #80) auto b1 = static_cast<decltype(i)>((static_cast<uint32_t>(n) * static_cast<uint64_t>(i)) >> 32U); swap(container[--i], container[b1]); auto b2 = static_cast<decltype(i)>(((n >> 32U) * static_cast<uint64_t>(i)) >> 32U); swap(container[--i], container[b2]); } } ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined") constexpr uint64_t Rng::rotl(uint64_t x, unsigned k) noexcept { return (x << k) | (x >> (64U - k)); } template <typename Op> ANKERL_NANOBENCH_NO_SANITIZE("integer") Bench& Bench::run(Op&& op) { // It is important that this method is kept short so the compiler can do better optimizations/ inlining of op() detail::IterationLogic iterationLogic(*this); auto& pc = detail::performanceCounters(); while (auto n = iterationLogic.numIters()) { pc.beginMeasure(); Clock::time_point const before = Clock::now(); while (n-- > 0) { op(); } Clock::time_point const after = Clock::now(); pc.endMeasure(); pc.updateResults(iterationLogic.numIters()); iterationLogic.add(after - before, pc); } iterationLogic.moveResultTo(mResults); return *this; } // Performs all evaluations. template <typename Op> Bench& Bench::run(char const* benchmarkName, Op&& op) { name(benchmarkName); return run(std::forward<Op>(op)); } template <typename Op> Bench& Bench::run(std::string const& benchmarkName, Op&& op) { name(benchmarkName); return run(std::forward<Op>(op)); } template <typename Op> BigO Bench::complexityBigO(char const* benchmarkName, Op op) const { return BigO(benchmarkName, BigO::collectRangeMeasure(mResults), op); } template <typename Op> BigO Bench::complexityBigO(std::string const& benchmarkName, Op op) const { return BigO(benchmarkName, BigO::collectRangeMeasure(mResults), op); } // Set the batch size, e.g. number of processed bytes, or some other metric for the size of the processed data in each iteration. // Any argument is cast to double. template <typename T> Bench& Bench::batch(T b) noexcept { mConfig.mBatch = static_cast<double>(b); return *this; } // Sets the computation complexity of the next run. Any argument is cast to double. template <typename T> Bench& Bench::complexityN(T n) noexcept { mConfig.mComplexityN = static_cast<double>(n); return *this; } // Convenience: makes sure none of the given arguments are optimized away by the compiler. template <typename Arg> Bench& Bench::doNotOptimizeAway(Arg&& arg) { detail::doNotOptimizeAway(std::forward<Arg>(arg)); return *this; } // Makes sure none of the given arguments are optimized away by the compiler. template <typename Arg> void doNotOptimizeAway(Arg&& arg) { detail::doNotOptimizeAway(std::forward<Arg>(arg)); } namespace detail { #if defined(_MSC_VER) template <typename T> void doNotOptimizeAway(T const& val) { doNotOptimizeAwaySink(&val); } #endif } // namespace detail } // namespace nanobench } // namespace ankerl #if defined(ANKERL_NANOBENCH_IMPLEMENT) /////////////////////////////////////////////////////////////////////////////////////////////////// // implementation part - only visible in .cpp /////////////////////////////////////////////////////////////////////////////////////////////////// # include <algorithm> // sort, reverse # include <atomic> // compare_exchange_strong in loop overhead # include <cstdlib> // getenv # include <cstring> // strstr, strncmp # include <fstream> // ifstream to parse proc files # include <iomanip> // setw, setprecision # include <iostream> // cout # include <numeric> // accumulate # include <random> // random_device # include <sstream> // to_s in Number # include <stdexcept> // throw for rendering templates # include <tuple> // std::tie # if defined(__linux__) # include <unistd.h> //sysconf # endif # if ANKERL_NANOBENCH(PERF_COUNTERS) # include <map> // map # include <linux/perf_event.h> # include <sys/ioctl.h> # include <sys/syscall.h> # endif // declarations /////////////////////////////////////////////////////////////////////////////////// namespace ankerl { namespace nanobench { // helper stuff that is only intended to be used internally namespace detail { struct TableInfo; // formatting utilities namespace fmt { class NumSep; class StreamStateRestorer; class Number; class MarkDownColumn; class MarkDownCode; } // namespace fmt } // namespace detail } // namespace nanobench } // namespace ankerl // definitions //////////////////////////////////////////////////////////////////////////////////// namespace ankerl { namespace nanobench { uint64_t splitMix64(uint64_t& state) noexcept; namespace detail { // helpers to get double values template <typename T> inline double d(T t) noexcept { return static_cast<double>(t); } inline double d(Clock::duration duration) noexcept { return std::chrono::duration_cast<std::chrono::duration<double>>(duration).count(); } // Calculates clock resolution once, and remembers the result inline Clock::duration clockResolution() noexcept; } // namespace detail namespace templates { char const* csv() noexcept { return R"DELIM("title";"name";"unit";"batch";"elapsed";"error %";"instructions";"branches";"branch misses";"total" {{#result}}"{{title}}";"{{name}}";"{{unit}}";{{batch}};{{median(elapsed)}};{{medianAbsolutePercentError(elapsed)}};{{median(instructions)}};{{median(branchinstructions)}};{{median(branchmisses)}};{{sumProduct(iterations, elapsed)}} {{/result}})DELIM"; } char const* htmlBoxplot() noexcept { return R"DELIM(<html> <head> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </head> <body> <div id="myDiv"></div> <script> var data = [ {{#result}}{ name: '{{name}}', y: [{{#measurement}}{{elapsed}}{{^-last}}, {{/last}}{{/measurement}}], }, {{/result}} ]; var title = '{{title}}'; data = data.map(a => Object.assign(a, { boxpoints: 'all', pointpos: 0, type: 'box' })); var layout = { title: { text: title }, showlegend: false, yaxis: { title: 'time per unit', rangemode: 'tozero', autorange: true } }; Plotly.newPlot('myDiv', data, layout, {responsive: true}); </script> </body> </html>)DELIM"; } char const* pyperf() noexcept { return R"DELIM({ "benchmarks": [ { "runs": [ { "values": [ {{#measurement}} {{elapsed}}{{^-last}}, {{/last}}{{/measurement}} ] } ] } ], "metadata": { "loops": {{sum(iterations)}}, "inner_loops": {{batch}}, "name": "{{title}}", "unit": "second" }, "version": "1.0" })DELIM"; } char const* json() noexcept { return R"DELIM({ "results": [ {{#result}} { "title": "{{title}}", "name": "{{name}}", "unit": "{{unit}}", "batch": {{batch}}, "complexityN": {{complexityN}}, "epochs": {{epochs}}, "clockResolution": {{clockResolution}}, "clockResolutionMultiple": {{clockResolutionMultiple}}, "maxEpochTime": {{maxEpochTime}}, "minEpochTime": {{minEpochTime}}, "minEpochIterations": {{minEpochIterations}}, "epochIterations": {{epochIterations}}, "warmup": {{warmup}}, "relative": {{relative}}, "median(elapsed)": {{median(elapsed)}}, "medianAbsolutePercentError(elapsed)": {{medianAbsolutePercentError(elapsed)}}, "median(instructions)": {{median(instructions)}}, "medianAbsolutePercentError(instructions)": {{medianAbsolutePercentError(instructions)}}, "median(cpucycles)": {{median(cpucycles)}}, "median(contextswitches)": {{median(contextswitches)}}, "median(pagefaults)": {{median(pagefaults)}}, "median(branchinstructions)": {{median(branchinstructions)}}, "median(branchmisses)": {{median(branchmisses)}}, "totalTime": {{sumProduct(iterations, elapsed)}}, "measurements": [ {{#measurement}} { "iterations": {{iterations}}, "elapsed": {{elapsed}}, "pagefaults": {{pagefaults}}, "cpucycles": {{cpucycles}}, "contextswitches": {{contextswitches}}, "instructions": {{instructions}}, "branchinstructions": {{branchinstructions}}, "branchmisses": {{branchmisses}} }{{^-last}},{{/-last}} {{/measurement}} ] }{{^-last}},{{/-last}} {{/result}} ] })DELIM"; } ANKERL_NANOBENCH(IGNORE_PADDED_PUSH) struct Node { enum class Type { tag, content, section, inverted_section }; char const* begin; char const* end; std::vector<Node> children; Type type; template <size_t N> // NOLINTNEXTLINE(hicpp-avoid-c-arrays,modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays) bool operator==(char const (&str)[N]) const noexcept { // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay) return static_cast<size_t>(std::distance(begin, end) + 1) == N && 0 == strncmp(str, begin, N - 1); } }; ANKERL_NANOBENCH(IGNORE_PADDED_POP) // NOLINTNEXTLINE(misc-no-recursion) static std::vector<Node> parseMustacheTemplate(char const** tpl) { std::vector<Node> nodes; while (true) { auto const* begin = std::strstr(*tpl, "{{"); auto const* end = begin; if (begin != nullptr) { // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) begin += 2; end = std::strstr(begin, "}}"); } if (begin == nullptr || end == nullptr) { // nothing found, finish node // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) nodes.emplace_back(Node{*tpl, *tpl + std::strlen(*tpl), std::vector<Node>{}, Node::Type::content}); return nodes; } // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) nodes.emplace_back(Node{*tpl, begin - 2, std::vector<Node>{}, Node::Type::content}); // we found a tag // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) *tpl = end + 2; switch (*begin) { case '/': // finished! bail out return nodes; case '#': // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) nodes.emplace_back(Node{begin + 1, end, parseMustacheTemplate(tpl), Node::Type::section}); break; case '^': // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) nodes.emplace_back(Node{begin + 1, end, parseMustacheTemplate(tpl), Node::Type::inverted_section}); break; default: nodes.emplace_back(Node{begin, end, std::vector<Node>{}, Node::Type::tag}); break; } } } static bool generateFirstLast(Node const& n, size_t idx, size_t size, std::ostream& out) { ANKERL_NANOBENCH_LOG("n.type=" << static_cast<int>(n.type)); bool const matchFirst = n == "-first"; bool const matchLast = n == "-last"; if (!matchFirst && !matchLast) { return false; } bool doWrite = false; if (n.type == Node::Type::section) { doWrite = (matchFirst && idx == 0) || (matchLast && idx == size - 1); } else if (n.type == Node::Type::inverted_section) { doWrite = (matchFirst && idx != 0) || (matchLast && idx != size - 1); } if (doWrite) { for (auto const& child : n.children) { if (child.type == Node::Type::content) { out.write(child.begin, std::distance(child.begin, child.end)); } } } return true; } static bool matchCmdArgs(std::string const& str, std::vector<std::string>& matchResult) { matchResult.clear(); auto idxOpen = str.find('('); auto idxClose = str.find(')', idxOpen); if (idxClose == std::string::npos) { return false; } matchResult.emplace_back(str.substr(0, idxOpen)); // split by comma matchResult.emplace_back(); for (size_t i = idxOpen + 1; i != idxClose; ++i) { if (str[i] == ' ' || str[i] == '\t') { // skip whitespace continue; } if (str[i] == ',') { // got a comma => new string matchResult.emplace_back(); continue; } // no whitespace no comma, append matchResult.back() += str[i]; } return true; } static bool generateConfigTag(Node const& n, Config const& config, std::ostream& out) { using detail::d; if (n == "title") { out << config.mBenchmarkTitle; return true; } if (n == "name") { out << config.mBenchmarkName; return true; } if (n == "unit") { out << config.mUnit; return true; } if (n == "batch") { out << config.mBatch; return true; } if (n == "complexityN") { out << config.mComplexityN; return true; } if (n == "epochs") { out << config.mNumEpochs; return true; } if (n == "clockResolution") { out << d(detail::clockResolution()); return true; } if (n == "clockResolutionMultiple") { out << config.mClockResolutionMultiple; return true; } if (n == "maxEpochTime") { out << d(config.mMaxEpochTime); return true; } if (n == "minEpochTime") { out << d(config.mMinEpochTime); return true; } if (n == "minEpochIterations") { out << config.mMinEpochIterations; return true; } if (n == "epochIterations") { out << config.mEpochIterations; return true; } if (n == "warmup") { out << config.mWarmup; return true; } if (n == "relative") { out << config.mIsRelative; return true; } return false; } // NOLINTNEXTLINE(readability-function-cognitive-complexity) static std::ostream& generateResultTag(Node const& n, Result const& r, std::ostream& out) { if (generateConfigTag(n, r.config(), out)) { return out; } // match e.g. "median(elapsed)" // g++ 4.8 doesn't implement std::regex :( // static std::regex const regOpArg1("^([a-zA-Z]+)\\(([a-zA-Z]*)\\)$"); // std::cmatch matchResult; // if (std::regex_match(n.begin, n.end, matchResult, regOpArg1)) { std::vector<std::string> matchResult; if (matchCmdArgs(std::string(n.begin, n.end), matchResult)) { if (matchResult.size() == 2) { if (matchResult[0] == "context") { return out << r.context(matchResult[1]); } auto m = Result::fromString(matchResult[1]); if (m == Result::Measure::_size) { return out << 0.0; } if (matchResult[0] == "median") { return out << r.median(m); } if (matchResult[0] == "average") { return out << r.average(m); } if (matchResult[0] == "medianAbsolutePercentError") { return out << r.medianAbsolutePercentError(m); } if (matchResult[0] == "sum") { return out << r.sum(m); } if (matchResult[0] == "minimum") { return out << r.minimum(m); } if (matchResult[0] == "maximum") { return out << r.maximum(m); } } else if (matchResult.size() == 3) { auto m1 = Result::fromString(matchResult[1]); auto m2 = Result::fromString(matchResult[2]); if (m1 == Result::Measure::_size || m2 == Result::Measure::_size) { return out << 0.0; } if (matchResult[0] == "sumProduct") { return out << r.sumProduct(m1, m2); } } } // match e.g. "sumProduct(elapsed, iterations)" // static std::regex const regOpArg2("^([a-zA-Z]+)\\(([a-zA-Z]*)\\s*,\\s+([a-zA-Z]*)\\)$"); // nothing matches :( throw std::runtime_error("command '" + std::string(n.begin, n.end) + "' not understood"); } static void generateResultMeasurement(std::vector<Node> const& nodes, size_t idx, Result const& r, std::ostream& out) { for (auto const& n : nodes) { if (!generateFirstLast(n, idx, r.size(), out)) { ANKERL_NANOBENCH_LOG("n.type=" << static_cast<int>(n.type)); switch (n.type) { case Node::Type::content: out.write(n.begin, std::distance(n.begin, n.end)); break; case Node::Type::inverted_section: throw std::runtime_error("got a inverted section inside measurement"); case Node::Type::section: throw std::runtime_error("got a section inside measurement"); case Node::Type::tag: { auto m = Result::fromString(std::string(n.begin, n.end)); if (m == Result::Measure::_size || !r.has(m)) { out << 0.0; } else { out << r.get(idx, m); } break; } } } } } static void generateResult(std::vector<Node> const& nodes, size_t idx, std::vector<Result> const& results, std::ostream& out) { auto const& r = results[idx]; for (auto const& n : nodes) { if (!generateFirstLast(n, idx, results.size(), out)) { ANKERL_NANOBENCH_LOG("n.type=" << static_cast<int>(n.type)); switch (n.type) { case Node::Type::content: out.write(n.begin, std::distance(n.begin, n.end)); break; case Node::Type::inverted_section: throw std::runtime_error("got a inverted section inside result"); case Node::Type::section: if (n == "measurement") { for (size_t i = 0; i < r.size(); ++i) { generateResultMeasurement(n.children, i, r, out); } } else { throw std::runtime_error("got a section inside result"); } break; case Node::Type::tag: generateResultTag(n, r, out); break; } } } } } // namespace templates // helper stuff that only intended to be used internally namespace detail { char const* getEnv(char const* name); bool isEndlessRunning(std::string const& name); bool isWarningsEnabled(); template <typename T> T parseFile(std::string const& filename, bool* fail); void gatherStabilityInformation(std::vector<std::string>& warnings, std::vector<std::string>& recommendations); void printStabilityInformationOnce(std::ostream* outStream); // remembers the last table settings used. When it changes, a new table header is automatically written for the new entry. uint64_t& singletonHeaderHash() noexcept; // determines resolution of the given clock. This is done by measuring multiple times and returning the minimum time difference. Clock::duration calcClockResolution(size_t numEvaluations) noexcept; // formatting utilities namespace fmt { // adds thousands separator to numbers ANKERL_NANOBENCH(IGNORE_PADDED_PUSH) class NumSep : public std::numpunct<char> { public: explicit NumSep(char sep); char do_thousands_sep() const override; std::string do_grouping() const override; private: char mSep; }; ANKERL_NANOBENCH(IGNORE_PADDED_POP) // RAII to save & restore a stream's state ANKERL_NANOBENCH(IGNORE_PADDED_PUSH) class StreamStateRestorer { public: explicit StreamStateRestorer(std::ostream& s); ~StreamStateRestorer(); // sets back all stream info that we remembered at construction void restore(); // don't allow copying / moving StreamStateRestorer(StreamStateRestorer const&) = delete; StreamStateRestorer& operator=(StreamStateRestorer const&) = delete; StreamStateRestorer(StreamStateRestorer&&) = delete; StreamStateRestorer& operator=(StreamStateRestorer&&) = delete; private: std::ostream& mStream; std::locale mLocale; std::streamsize const mPrecision; std::streamsize const mWidth; std::ostream::char_type const mFill; std::ostream::fmtflags const mFmtFlags; }; ANKERL_NANOBENCH(IGNORE_PADDED_POP) // Number formatter class Number { public: Number(int width, int precision, double value); Number(int width, int precision, int64_t value); ANKERL_NANOBENCH(NODISCARD) std::string to_s() const; private: friend std::ostream& operator<<(std::ostream& os, Number const& n); std::ostream& write(std::ostream& os) const; int mWidth; int mPrecision; double mValue; }; // helper replacement for std::to_string of signed/unsigned numbers so we are locale independent std::string to_s(uint64_t n); std::ostream& operator<<(std::ostream& os, Number const& n); class MarkDownColumn { public: MarkDownColumn(int w, int prec, std::string tit, std::string suff, double val) noexcept; ANKERL_NANOBENCH(NODISCARD) std::string title() const; ANKERL_NANOBENCH(NODISCARD) std::string separator() const; ANKERL_NANOBENCH(NODISCARD) std::string invalid() const; ANKERL_NANOBENCH(NODISCARD) std::string value() const; private: int mWidth; int mPrecision; std::string mTitle; std::string mSuffix; double mValue; }; // Formats any text as markdown code, escaping backticks. class MarkDownCode { public: explicit MarkDownCode(std::string const& what); private: friend std::ostream& operator<<(std::ostream& os, MarkDownCode const& mdCode); std::ostream& write(std::ostream& os) const; std::string mWhat{}; }; std::ostream& operator<<(std::ostream& os, MarkDownCode const& mdCode); } // namespace fmt } // namespace detail } // namespace nanobench } // namespace ankerl // implementation ///////////////////////////////////////////////////////////////////////////////// namespace ankerl { namespace nanobench { // NOLINTNEXTLINE(readability-function-cognitive-complexity) void render(char const* mustacheTemplate, std::vector<Result> const& results, std::ostream& out) { detail::fmt::StreamStateRestorer const restorer(out); out.precision(std::numeric_limits<double>::digits10); auto nodes = templates::parseMustacheTemplate(&mustacheTemplate); for (auto const& n : nodes) { ANKERL_NANOBENCH_LOG("n.type=" << static_cast<int>(n.type)); switch (n.type) { case templates::Node::Type::content: out.write(n.begin, std::distance(n.begin, n.end)); break; case templates::Node::Type::inverted_section: throw std::runtime_error("unknown list '" + std::string(n.begin, n.end) + "'"); case templates::Node::Type::section: if (n == "result") { const size_t nbResults = results.size(); for (size_t i = 0; i < nbResults; ++i) { generateResult(n.children, i, results, out); } } else if (n == "measurement") { if (results.size() != 1) { throw std::runtime_error( "render: can only use section 'measurement' here if there is a single result, but there are " + detail::fmt::to_s(results.size())); } // when we only have a single result, we can immediately go into its measurement. auto const& r = results.front(); for (size_t i = 0; i < r.size(); ++i) { generateResultMeasurement(n.children, i, r, out); } } else { throw std::runtime_error("render: unknown section '" + std::string(n.begin, n.end) + "'"); } break; case templates::Node::Type::tag: if (results.size() == 1) { // result & config are both supported there generateResultTag(n, results.front(), out); } else { // This just uses the last result's config. if (!generateConfigTag(n, results.back().config(), out)) { throw std::runtime_error("unknown tag '" + std::string(n.begin, n.end) + "'"); } } break; } } } void render(std::string const& mustacheTemplate, std::vector<Result> const& results, std::ostream& out) { render(mustacheTemplate.c_str(), results, out); } void render(char const* mustacheTemplate, const Bench& bench, std::ostream& out) { render(mustacheTemplate, bench.results(), out); } void render(std::string const& mustacheTemplate, const Bench& bench, std::ostream& out) { render(mustacheTemplate.c_str(), bench.results(), out); } namespace detail { PerformanceCounters& performanceCounters() { # if defined(__clang__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wexit-time-destructors" # endif static PerformanceCounters pc; # if defined(__clang__) # pragma clang diagnostic pop # endif return pc; } // Windows version of doNotOptimizeAway // see https://github.com/google/benchmark/blob/v1.7.1/include/benchmark/benchmark.h#L514 // see https://github.com/facebook/folly/blob/v2023.01.30.00/folly/lang/Hint-inl.h#L54-L58 // see https://learn.microsoft.com/en-us/cpp/preprocessor/optimize # if defined(_MSC_VER) # pragma optimize("", off) void doNotOptimizeAwaySink(void const*) {} # pragma optimize("", on) # endif template <typename T> T parseFile(std::string const& filename, bool* fail) { std::ifstream fin(filename); // NOLINT(misc-const-correctness) T num{}; fin >> num; if (fail != nullptr) { *fail = fin.fail(); } return num; } char const* getEnv(char const* name) { # if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4996) // getenv': This function or variable may be unsafe. # endif return std::getenv(name); // NOLINT(concurrency-mt-unsafe) # if defined(_MSC_VER) # pragma warning(pop) # endif } bool isEndlessRunning(std::string const& name) { auto const* const endless = getEnv("NANOBENCH_ENDLESS"); return nullptr != endless && endless == name; } // True when environment variable NANOBENCH_SUPPRESS_WARNINGS is either not set at all, or set to "0" bool isWarningsEnabled() { auto const* const suppression = getEnv("NANOBENCH_SUPPRESS_WARNINGS"); return nullptr == suppression || suppression == std::string("0"); } void gatherStabilityInformation(std::vector<std::string>& warnings, std::vector<std::string>& recommendations) { warnings.clear(); recommendations.clear(); # if defined(DEBUG) warnings.emplace_back("DEBUG defined"); bool const recommendCheckFlags = true; # else bool const recommendCheckFlags = false; # endif bool recommendPyPerf = false; # if defined(__linux__) auto nprocs = sysconf(_SC_NPROCESSORS_CONF); if (nprocs <= 0) { warnings.emplace_back("couldn't figure out number of processors - no governor, turbo check possible"); } else { // check frequency scaling for (long id = 0; id < nprocs; ++id) { auto idStr = detail::fmt::to_s(static_cast<uint64_t>(id)); auto sysCpu = "/sys/devices/system/cpu/cpu" + idStr; auto minFreq = parseFile<int64_t>(sysCpu + "/cpufreq/scaling_min_freq", nullptr); auto maxFreq = parseFile<int64_t>(sysCpu + "/cpufreq/scaling_max_freq", nullptr); if (minFreq != maxFreq) { auto minMHz = d(minFreq) / 1000.0; auto maxMHz = d(maxFreq) / 1000.0; warnings.emplace_back("CPU frequency scaling enabled: CPU " + idStr + " between " + detail::fmt::Number(1, 1, minMHz).to_s() + " and " + detail::fmt::Number(1, 1, maxMHz).to_s() + " MHz"); recommendPyPerf = true; break; } } auto fail = false; auto currentGovernor = parseFile<std::string>("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor", &fail); if (!fail && "performance" != currentGovernor) { warnings.emplace_back("CPU governor is '" + currentGovernor + "' but should be 'performance'"); recommendPyPerf = true; } auto noTurbo = parseFile<int>("/sys/devices/system/cpu/intel_pstate/no_turbo", &fail); if (!fail && noTurbo == 0) { warnings.emplace_back("Turbo is enabled, CPU frequency will fluctuate"); recommendPyPerf = true; } } # endif if (recommendCheckFlags) { recommendations.emplace_back("Make sure you compile for Release"); } if (recommendPyPerf) { recommendations.emplace_back("Use 'pyperf system tune' before benchmarking. See https://github.com/psf/pyperf"); } } void printStabilityInformationOnce(std::ostream* outStream) { static bool shouldPrint = true; if (shouldPrint && (nullptr != outStream) && isWarningsEnabled()) { auto& os = *outStream; shouldPrint = false; std::vector<std::string> warnings; std::vector<std::string> recommendations; gatherStabilityInformation(warnings, recommendations); if (warnings.empty()) { return; } os << "Warning, results might be unstable:" << std::endl; for (auto const& w : warnings) { os << "* " << w << std::endl; } os << std::endl << "Recommendations" << std::endl; for (auto const& r : recommendations) { os << "* " << r << std::endl; } } } // remembers the last table settings used. When it changes, a new table header is automatically written for the new entry. uint64_t& singletonHeaderHash() noexcept { static uint64_t sHeaderHash{}; return sHeaderHash; } ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined") inline uint64_t hash_combine(uint64_t seed, uint64_t val) { return seed ^ (val + UINT64_C(0x9e3779b9) + (seed << 6U) + (seed >> 2U)); } // determines resolution of the given clock. This is done by measuring multiple times and returning the minimum time difference. Clock::duration calcClockResolution(size_t numEvaluations) noexcept { auto bestDuration = Clock::duration::max(); Clock::time_point tBegin; Clock::time_point tEnd; for (size_t i = 0; i < numEvaluations; ++i) { tBegin = Clock::now(); do { tEnd = Clock::now(); } while (tBegin == tEnd); bestDuration = (std::min)(bestDuration, tEnd - tBegin); } return bestDuration; } // Calculates clock resolution once, and remembers the result Clock::duration clockResolution() noexcept { static Clock::duration const sResolution = calcClockResolution(20); return sResolution; } ANKERL_NANOBENCH(IGNORE_PADDED_PUSH) struct IterationLogic::Impl { enum class State { warmup, upscaling_runtime, measuring, endless }; explicit Impl(Bench const& bench) : mBench(bench) , mResult(bench.config()) { printStabilityInformationOnce(mBench.output()); // determine target runtime per epoch mTargetRuntimePerEpoch = detail::clockResolution() * mBench.clockResolutionMultiple(); if (mTargetRuntimePerEpoch > mBench.maxEpochTime()) { mTargetRuntimePerEpoch = mBench.maxEpochTime(); } if (mTargetRuntimePerEpoch < mBench.minEpochTime()) { mTargetRuntimePerEpoch = mBench.minEpochTime(); } if (isEndlessRunning(mBench.name())) { std::cerr << "NANOBENCH_ENDLESS set: running '" << mBench.name() << "' endlessly" << std::endl; mNumIters = (std::numeric_limits<uint64_t>::max)(); mState = State::endless; } else if (0 != mBench.warmup()) { mNumIters = mBench.warmup(); mState = State::warmup; } else if (0 != mBench.epochIterations()) { // exact number of iterations mNumIters = mBench.epochIterations(); mState = State::measuring; } else { mNumIters = mBench.minEpochIterations(); mState = State::upscaling_runtime; } } // directly calculates new iters based on elapsed&iters, and adds a 10% noise. Makes sure we don't underflow. ANKERL_NANOBENCH(NODISCARD) uint64_t calcBestNumIters(std::chrono::nanoseconds elapsed, uint64_t iters) noexcept { auto doubleElapsed = d(elapsed); auto doubleTargetRuntimePerEpoch = d(mTargetRuntimePerEpoch); auto doubleNewIters = doubleTargetRuntimePerEpoch / doubleElapsed * d(iters); auto doubleMinEpochIters = d(mBench.minEpochIterations()); if (doubleNewIters < doubleMinEpochIters) { doubleNewIters = doubleMinEpochIters; } doubleNewIters *= 1.0 + 0.2 * mRng.uniform01(); // +0.5 for correct rounding when casting // NOLINTNEXTLINE(bugprone-incorrect-roundings) return static_cast<uint64_t>(doubleNewIters + 0.5); } ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined") void upscale(std::chrono::nanoseconds elapsed) { if (elapsed * 10 < mTargetRuntimePerEpoch) { // we are far below the target runtime. Multiply iterations by 10 (with overflow check) if (mNumIters * 10 < mNumIters) { // overflow :-( showResult("iterations overflow. Maybe your code got optimized away?"); mNumIters = 0; return; } mNumIters *= 10; } else { mNumIters = calcBestNumIters(elapsed, mNumIters); } } void add(std::chrono::nanoseconds elapsed, PerformanceCounters const& pc) noexcept { # if defined(ANKERL_NANOBENCH_LOG_ENABLED) auto oldIters = mNumIters; # endif switch (mState) { case State::warmup: if (isCloseEnoughForMeasurements(elapsed)) { // if elapsed is close enough, we can skip upscaling and go right to measurements // still, we don't add the result to the measurements. mState = State::measuring; mNumIters = calcBestNumIters(elapsed, mNumIters); } else { // not close enough: switch to upscaling mState = State::upscaling_runtime; upscale(elapsed); } break; case State::upscaling_runtime: if (isCloseEnoughForMeasurements(elapsed)) { // if we are close enough, add measurement and switch to always measuring mState = State::measuring; mTotalElapsed += elapsed; mTotalNumIters += mNumIters; mResult.add(elapsed, mNumIters, pc); mNumIters = calcBestNumIters(mTotalElapsed, mTotalNumIters); } else { upscale(elapsed); } break; case State::measuring: // just add measurements - no questions asked. Even when runtime is low. But we can't ignore // that fluctuation, or else we would bias the result mTotalElapsed += elapsed; mTotalNumIters += mNumIters; mResult.add(elapsed, mNumIters, pc); if (0 != mBench.epochIterations()) { mNumIters = mBench.epochIterations(); } else { mNumIters = calcBestNumIters(mTotalElapsed, mTotalNumIters); } break; case State::endless: mNumIters = (std::numeric_limits<uint64_t>::max)(); break; } if (static_cast<uint64_t>(mResult.size()) == mBench.epochs()) { // we got all the results that we need, finish it showResult(""); mNumIters = 0; } ANKERL_NANOBENCH_LOG(mBench.name() << ": " << detail::fmt::Number(20, 3, d(elapsed.count())) << " elapsed, " << detail::fmt::Number(20, 3, d(mTargetRuntimePerEpoch.count())) << " target. oldIters=" << oldIters << ", mNumIters=" << mNumIters << ", mState=" << static_cast<int>(mState)); } // NOLINTNEXTLINE(readability-function-cognitive-complexity) void showResult(std::string const& errorMessage) const { ANKERL_NANOBENCH_LOG(errorMessage); if (mBench.output() != nullptr) { // prepare column data /////// std::vector<fmt::MarkDownColumn> columns; auto rMedian = mResult.median(Result::Measure::elapsed); if (mBench.relative()) { double d = 100.0; if (!mBench.results().empty()) { d = rMedian <= 0.0 ? 0.0 : mBench.results().front().median(Result::Measure::elapsed) / rMedian * 100.0; } columns.emplace_back(11, 1, "relative", "%", d); } if (mBench.complexityN() > 0) { columns.emplace_back(14, 0, "complexityN", "", mBench.complexityN()); } columns.emplace_back(22, 2, mBench.timeUnitName() + "/" + mBench.unit(), "", rMedian / (mBench.timeUnit().count() * mBench.batch())); columns.emplace_back(22, 2, mBench.unit() + "/s", "", rMedian <= 0.0 ? 0.0 : mBench.batch() / rMedian); double const rErrorMedian = mResult.medianAbsolutePercentError(Result::Measure::elapsed); columns.emplace_back(10, 1, "err%", "%", rErrorMedian * 100.0); double rInsMedian = -1.0; if (mBench.performanceCounters() && mResult.has(Result::Measure::instructions)) { rInsMedian = mResult.median(Result::Measure::instructions); columns.emplace_back(18, 2, "ins/" + mBench.unit(), "", rInsMedian / mBench.batch()); } double rCycMedian = -1.0; if (mBench.performanceCounters() && mResult.has(Result::Measure::cpucycles)) { rCycMedian = mResult.median(Result::Measure::cpucycles); columns.emplace_back(18, 2, "cyc/" + mBench.unit(), "", rCycMedian / mBench.batch()); } if (rInsMedian > 0.0 && rCycMedian > 0.0) { columns.emplace_back(9, 3, "IPC", "", rCycMedian <= 0.0 ? 0.0 : rInsMedian / rCycMedian); } if (mBench.performanceCounters() && mResult.has(Result::Measure::branchinstructions)) { double const rBraMedian = mResult.median(Result::Measure::branchinstructions); columns.emplace_back(17, 2, "bra/" + mBench.unit(), "", rBraMedian / mBench.batch()); if (mResult.has(Result::Measure::branchmisses)) { double p = 0.0; if (rBraMedian >= 1e-9) { p = 100.0 * mResult.median(Result::Measure::branchmisses) / rBraMedian; } columns.emplace_back(10, 1, "miss%", "%", p); } } columns.emplace_back(12, 2, "total", "", mResult.sumProduct(Result::Measure::iterations, Result::Measure::elapsed)); // write everything auto& os = *mBench.output(); // combine all elements that are relevant for printing the header uint64_t hash = 0; hash = hash_combine(std::hash<std::string>{}(mBench.unit()), hash); hash = hash_combine(std::hash<std::string>{}(mBench.title()), hash); hash = hash_combine(std::hash<std::string>{}(mBench.timeUnitName()), hash); hash = hash_combine(std::hash<double>{}(mBench.timeUnit().count()), hash); hash = hash_combine(std::hash<bool>{}(mBench.relative()), hash); hash = hash_combine(std::hash<bool>{}(mBench.performanceCounters()), hash); if (hash != singletonHeaderHash()) { singletonHeaderHash() = hash; // no result yet, print header os << std::endl; for (auto const& col : columns) { os << col.title(); } os << "| " << mBench.title() << std::endl; for (auto const& col : columns) { os << col.separator(); } os << "|:" << std::string(mBench.title().size() + 1U, '-') << std::endl; } if (!errorMessage.empty()) { for (auto const& col : columns) { os << col.invalid(); } os << "| :boom: " << fmt::MarkDownCode(mBench.name()) << " (" << errorMessage << ')' << std::endl; } else { for (auto const& col : columns) { os << col.value(); } os << "| "; auto showUnstable = isWarningsEnabled() && rErrorMedian >= 0.05; if (showUnstable) { os << ":wavy_dash: "; } os << fmt::MarkDownCode(mBench.name()); if (showUnstable) { auto avgIters = d(mTotalNumIters) / d(mBench.epochs()); // NOLINTNEXTLINE(bugprone-incorrect-roundings) auto suggestedIters = static_cast<uint64_t>(avgIters * 10 + 0.5); os << " (Unstable with ~" << detail::fmt::Number(1, 1, avgIters) << " iters. Increase `minEpochIterations` to e.g. " << suggestedIters << ")"; } os << std::endl; } } } ANKERL_NANOBENCH(NODISCARD) bool isCloseEnoughForMeasurements(std::chrono::nanoseconds elapsed) const noexcept { return elapsed * 3 >= mTargetRuntimePerEpoch * 2; } uint64_t mNumIters = 1; // NOLINT(misc-non-private-member-variables-in-classes) Bench const& mBench; // NOLINT(misc-non-private-member-variables-in-classes) std::chrono::nanoseconds mTargetRuntimePerEpoch{}; // NOLINT(misc-non-private-member-variables-in-classes) Result mResult; // NOLINT(misc-non-private-member-variables-in-classes) Rng mRng{123}; // NOLINT(misc-non-private-member-variables-in-classes) std::chrono::nanoseconds mTotalElapsed{}; // NOLINT(misc-non-private-member-variables-in-classes) uint64_t mTotalNumIters = 0; // NOLINT(misc-non-private-member-variables-in-classes) State mState = State::upscaling_runtime; // NOLINT(misc-non-private-member-variables-in-classes) }; ANKERL_NANOBENCH(IGNORE_PADDED_POP) IterationLogic::IterationLogic(Bench const& bench) : mPimpl(new Impl(bench)) {} IterationLogic::~IterationLogic() { delete mPimpl; } uint64_t IterationLogic::numIters() const noexcept { ANKERL_NANOBENCH_LOG(mPimpl->mBench.name() << ": mNumIters=" << mPimpl->mNumIters); return mPimpl->mNumIters; } void IterationLogic::add(std::chrono::nanoseconds elapsed, PerformanceCounters const& pc) noexcept { mPimpl->add(elapsed, pc); } void IterationLogic::moveResultTo(std::vector<Result>& results) noexcept { results.emplace_back(std::move(mPimpl->mResult)); } # if ANKERL_NANOBENCH(PERF_COUNTERS) ANKERL_NANOBENCH(IGNORE_PADDED_PUSH) class LinuxPerformanceCounters { public: struct Target { Target(uint64_t* targetValue_, bool correctMeasuringOverhead_, bool correctLoopOverhead_) : targetValue(targetValue_) , correctMeasuringOverhead(correctMeasuringOverhead_) , correctLoopOverhead(correctLoopOverhead_) {} uint64_t* targetValue{}; // NOLINT(misc-non-private-member-variables-in-classes) bool correctMeasuringOverhead{}; // NOLINT(misc-non-private-member-variables-in-classes) bool correctLoopOverhead{}; // NOLINT(misc-non-private-member-variables-in-classes) }; LinuxPerformanceCounters() = default; LinuxPerformanceCounters(LinuxPerformanceCounters const&) = delete; LinuxPerformanceCounters(LinuxPerformanceCounters&&) = delete; LinuxPerformanceCounters& operator=(LinuxPerformanceCounters const&) = delete; LinuxPerformanceCounters& operator=(LinuxPerformanceCounters&&) = delete; ~LinuxPerformanceCounters(); // quick operation inline void start() {} inline void stop() {} bool monitor(perf_sw_ids swId, Target target); bool monitor(perf_hw_id hwId, Target target); ANKERL_NANOBENCH(NODISCARD) bool hasError() const noexcept { return mHasError; } // Just reading data is faster than enable & disabling. // we subtract data ourselves. inline void beginMeasure() { if (mHasError) { return; } // NOLINTNEXTLINE(hicpp-signed-bitwise,cppcoreguidelines-pro-type-vararg) mHasError = -1 == ioctl(mFd, PERF_EVENT_IOC_RESET, PERF_IOC_FLAG_GROUP); if (mHasError) { return; } // NOLINTNEXTLINE(hicpp-signed-bitwise,cppcoreguidelines-pro-type-vararg) mHasError = -1 == ioctl(mFd, PERF_EVENT_IOC_ENABLE, PERF_IOC_FLAG_GROUP); } inline void endMeasure() { if (mHasError) { return; } // NOLINTNEXTLINE(hicpp-signed-bitwise,cppcoreguidelines-pro-type-vararg) mHasError = (-1 == ioctl(mFd, PERF_EVENT_IOC_DISABLE, PERF_IOC_FLAG_GROUP)); if (mHasError) { return; } auto const numBytes = sizeof(uint64_t) * mCounters.size(); auto ret = read(mFd, mCounters.data(), numBytes); mHasError = ret != static_cast<ssize_t>(numBytes); } void updateResults(uint64_t numIters); // rounded integer division template <typename T> static inline T divRounded(T a, T divisor) { return (a + divisor / 2) / divisor; } ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined") static inline uint32_t mix(uint32_t x) noexcept { x ^= x << 13U; x ^= x >> 17U; x ^= x << 5U; return x; } template <typename Op> ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined") void calibrate(Op&& op) { // clear current calibration data, for (auto& v : mCalibratedOverhead) { v = UINT64_C(0); } // create new calibration data auto newCalibration = mCalibratedOverhead; for (auto& v : newCalibration) { v = (std::numeric_limits<uint64_t>::max)(); } for (size_t iter = 0; iter < 100; ++iter) { beginMeasure(); op(); endMeasure(); if (mHasError) { return; } for (size_t i = 0; i < newCalibration.size(); ++i) { auto diff = mCounters[i]; if (newCalibration[i] > diff) { newCalibration[i] = diff; } } } mCalibratedOverhead = std::move(newCalibration); { // calibrate loop overhead. For branches & instructions this makes sense, not so much for everything else like cycles. // marsaglia's xorshift: mov, sal/shr, xor. Times 3. // This has the nice property that the compiler doesn't seem to be able to optimize multiple calls any further. // see https://godbolt.org/z/49RVQ5 uint64_t const numIters = 100000U + (std::random_device{}() & 3U); uint64_t n = numIters; uint32_t x = 1234567; beginMeasure(); while (n-- > 0) { x = mix(x); } endMeasure(); detail::doNotOptimizeAway(x); auto measure1 = mCounters; n = numIters; beginMeasure(); while (n-- > 0) { // we now run *twice* so we can easily calculate the overhead x = mix(x); x = mix(x); } endMeasure(); detail::doNotOptimizeAway(x); auto measure2 = mCounters; for (size_t i = 0; i < mCounters.size(); ++i) { // factor 2 because we have two instructions per loop auto m1 = measure1[i] > mCalibratedOverhead[i] ? measure1[i] - mCalibratedOverhead[i] : 0; auto m2 = measure2[i] > mCalibratedOverhead[i] ? measure2[i] - mCalibratedOverhead[i] : 0; auto overhead = m1 * 2 > m2 ? m1 * 2 - m2 : 0; mLoopOverhead[i] = divRounded(overhead, numIters); } } } private: bool monitor(uint32_t type, uint64_t eventid, Target target); std::map<uint64_t, Target> mIdToTarget{}; // start with minimum size of 3 for read_format std::vector<uint64_t> mCounters{3}; std::vector<uint64_t> mCalibratedOverhead{3}; std::vector<uint64_t> mLoopOverhead{3}; uint64_t mTimeEnabledNanos = 0; uint64_t mTimeRunningNanos = 0; int mFd = -1; bool mHasError = false; }; ANKERL_NANOBENCH(IGNORE_PADDED_POP) LinuxPerformanceCounters::~LinuxPerformanceCounters() { if (-1 != mFd) { close(mFd); } } bool LinuxPerformanceCounters::monitor(perf_sw_ids swId, LinuxPerformanceCounters::Target target) { return monitor(PERF_TYPE_SOFTWARE, swId, target); } bool LinuxPerformanceCounters::monitor(perf_hw_id hwId, LinuxPerformanceCounters::Target target) { return monitor(PERF_TYPE_HARDWARE, hwId, target); } // overflow is ok, it's checked ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined") void LinuxPerformanceCounters::updateResults(uint64_t numIters) { // clear old data for (auto& id_value : mIdToTarget) { *id_value.second.targetValue = UINT64_C(0); } if (mHasError) { return; } mTimeEnabledNanos = mCounters[1] - mCalibratedOverhead[1]; mTimeRunningNanos = mCounters[2] - mCalibratedOverhead[2]; for (uint64_t i = 0; i < mCounters[0]; ++i) { auto idx = static_cast<size_t>(3 + i * 2 + 0); auto id = mCounters[idx + 1U]; auto it = mIdToTarget.find(id); if (it != mIdToTarget.end()) { auto& tgt = it->second; *tgt.targetValue = mCounters[idx]; if (tgt.correctMeasuringOverhead) { if (*tgt.targetValue >= mCalibratedOverhead[idx]) { *tgt.targetValue -= mCalibratedOverhead[idx]; } else { *tgt.targetValue = 0U; } } if (tgt.correctLoopOverhead) { auto correctionVal = mLoopOverhead[idx] * numIters; if (*tgt.targetValue >= correctionVal) { *tgt.targetValue -= correctionVal; } else { *tgt.targetValue = 0U; } } } } } bool LinuxPerformanceCounters::monitor(uint32_t type, uint64_t eventid, Target target) { *target.targetValue = (std::numeric_limits<uint64_t>::max)(); if (mHasError) { return false; } auto pea = perf_event_attr(); std::memset(&pea, 0, sizeof(perf_event_attr)); pea.type = type; pea.size = sizeof(perf_event_attr); pea.config = eventid; pea.disabled = 1; // start counter as disabled pea.exclude_kernel = 1; pea.exclude_hv = 1; // NOLINTNEXTLINE(hicpp-signed-bitwise) pea.read_format = PERF_FORMAT_GROUP | PERF_FORMAT_ID | PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING; const int pid = 0; // the current process const int cpu = -1; // all CPUs # if defined(PERF_FLAG_FD_CLOEXEC) // since Linux 3.14 const unsigned long flags = PERF_FLAG_FD_CLOEXEC; # else const unsigned long flags = 0; # endif // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) auto fd = static_cast<int>(syscall(__NR_perf_event_open, &pea, pid, cpu, mFd, flags)); if (-1 == fd) { return false; } if (-1 == mFd) { // first call: set to fd, and use this from now on mFd = fd; } uint64_t id = 0; // NOLINTNEXTLINE(hicpp-signed-bitwise,cppcoreguidelines-pro-type-vararg) if (-1 == ioctl(fd, PERF_EVENT_IOC_ID, &id)) { // couldn't get id return false; } // insert into map, rely on the fact that map's references are constant. mIdToTarget.emplace(id, target); // prepare readformat with the correct size (after the insert) auto size = 3 + 2 * mIdToTarget.size(); mCounters.resize(size); mCalibratedOverhead.resize(size); mLoopOverhead.resize(size); return true; } PerformanceCounters::PerformanceCounters() : mPc(new LinuxPerformanceCounters()) , mVal() , mHas() { // HW events mHas.cpuCycles = mPc->monitor(PERF_COUNT_HW_REF_CPU_CYCLES, LinuxPerformanceCounters::Target(&mVal.cpuCycles, true, false)); if (!mHas.cpuCycles) { // Fallback to cycles counter, reference cycles not available in many systems. mHas.cpuCycles = mPc->monitor(PERF_COUNT_HW_CPU_CYCLES, LinuxPerformanceCounters::Target(&mVal.cpuCycles, true, false)); } mHas.instructions = mPc->monitor(PERF_COUNT_HW_INSTRUCTIONS, LinuxPerformanceCounters::Target(&mVal.instructions, true, true)); mHas.branchInstructions = mPc->monitor(PERF_COUNT_HW_BRANCH_INSTRUCTIONS, LinuxPerformanceCounters::Target(&mVal.branchInstructions, true, false)); mHas.branchMisses = mPc->monitor(PERF_COUNT_HW_BRANCH_MISSES, LinuxPerformanceCounters::Target(&mVal.branchMisses, true, false)); // mHas.branchMisses = false; // SW events mHas.pageFaults = mPc->monitor(PERF_COUNT_SW_PAGE_FAULTS, LinuxPerformanceCounters::Target(&mVal.pageFaults, true, false)); mHas.contextSwitches = mPc->monitor(PERF_COUNT_SW_CONTEXT_SWITCHES, LinuxPerformanceCounters::Target(&mVal.contextSwitches, true, false)); mPc->start(); mPc->calibrate([] { auto before = ankerl::nanobench::Clock::now(); auto after = ankerl::nanobench::Clock::now(); (void)before; (void)after; }); if (mPc->hasError()) { // something failed, don't monitor anything. mHas = PerfCountSet<bool>{}; } } PerformanceCounters::~PerformanceCounters() { // no need to check for nullptr, delete nullptr has no effect delete mPc; } void PerformanceCounters::beginMeasure() { mPc->beginMeasure(); } void PerformanceCounters::endMeasure() { mPc->endMeasure(); } void PerformanceCounters::updateResults(uint64_t numIters) { mPc->updateResults(numIters); } # else PerformanceCounters::PerformanceCounters() = default; PerformanceCounters::~PerformanceCounters() = default; void PerformanceCounters::beginMeasure() {} void PerformanceCounters::endMeasure() {} void PerformanceCounters::updateResults(uint64_t) {} # endif ANKERL_NANOBENCH(NODISCARD) PerfCountSet<uint64_t> const& PerformanceCounters::val() const noexcept { return mVal; } ANKERL_NANOBENCH(NODISCARD) PerfCountSet<bool> const& PerformanceCounters::has() const noexcept { return mHas; } // formatting utilities namespace fmt { // adds thousands separator to numbers NumSep::NumSep(char sep) : mSep(sep) {} char NumSep::do_thousands_sep() const { return mSep; } std::string NumSep::do_grouping() const { return "\003"; } // RAII to save & restore a stream's state StreamStateRestorer::StreamStateRestorer(std::ostream& s) : mStream(s) , mLocale(s.getloc()) , mPrecision(s.precision()) , mWidth(s.width()) , mFill(s.fill()) , mFmtFlags(s.flags()) {} StreamStateRestorer::~StreamStateRestorer() { restore(); } // sets back all stream info that we remembered at construction void StreamStateRestorer::restore() { mStream.imbue(mLocale); mStream.precision(mPrecision); mStream.width(mWidth); mStream.fill(mFill); mStream.flags(mFmtFlags); } Number::Number(int width, int precision, int64_t value) : mWidth(width) , mPrecision(precision) , mValue(d(value)) {} Number::Number(int width, int precision, double value) : mWidth(width) , mPrecision(precision) , mValue(value) {} std::ostream& Number::write(std::ostream& os) const { StreamStateRestorer const restorer(os); os.imbue(std::locale(os.getloc(), new NumSep(','))); os << std::setw(mWidth) << std::setprecision(mPrecision) << std::fixed << mValue; return os; } std::string Number::to_s() const { std::stringstream ss; write(ss); return ss.str(); } std::string to_s(uint64_t n) { std::string str; do { str += static_cast<char>('0' + static_cast<char>(n % 10)); n /= 10; } while (n != 0); std::reverse(str.begin(), str.end()); return str; } std::ostream& operator<<(std::ostream& os, Number const& n) { return n.write(os); } MarkDownColumn::MarkDownColumn(int w, int prec, std::string tit, std::string suff, double val) noexcept : mWidth(w) , mPrecision(prec) , mTitle(std::move(tit)) , mSuffix(std::move(suff)) , mValue(val) {} std::string MarkDownColumn::title() const { std::stringstream ss; ss << '|' << std::setw(mWidth - 2) << std::right << mTitle << ' '; return ss.str(); } std::string MarkDownColumn::separator() const { std::string sep(static_cast<size_t>(mWidth), '-'); sep.front() = '|'; sep.back() = ':'; return sep; } std::string MarkDownColumn::invalid() const { std::string sep(static_cast<size_t>(mWidth), ' '); sep.front() = '|'; sep[sep.size() - 2] = '-'; return sep; } std::string MarkDownColumn::value() const { std::stringstream ss; auto width = mWidth - 2 - static_cast<int>(mSuffix.size()); ss << '|' << Number(width, mPrecision, mValue) << mSuffix << ' '; return ss.str(); } // Formats any text as markdown code, escaping backticks. MarkDownCode::MarkDownCode(std::string const& what) { mWhat.reserve(what.size() + 2); mWhat.push_back('`'); for (char const c : what) { mWhat.push_back(c); if ('`' == c) { mWhat.push_back('`'); } } mWhat.push_back('`'); } std::ostream& MarkDownCode::write(std::ostream& os) const { return os << mWhat; } std::ostream& operator<<(std::ostream& os, MarkDownCode const& mdCode) { return mdCode.write(os); } } // namespace fmt } // namespace detail // provide implementation here so it's only generated once Config::Config() = default; Config::~Config() = default; Config& Config::operator=(Config const&) = default; Config& Config::operator=(Config&&) noexcept(ANKERL_NANOBENCH(NOEXCEPT_STRING_MOVE)) = default; Config::Config(Config const&) = default; Config::Config(Config&&) noexcept = default; // provide implementation here so it's only generated once Result::~Result() = default; Result& Result::operator=(Result const&) = default; Result& Result::operator=(Result&&) noexcept(ANKERL_NANOBENCH(NOEXCEPT_STRING_MOVE)) = default; Result::Result(Result const&) = default; Result::Result(Result&&) noexcept = default; namespace detail { template <typename T> inline constexpr typename std::underlying_type<T>::type u(T val) noexcept { return static_cast<typename std::underlying_type<T>::type>(val); } } // namespace detail // Result returned after a benchmark has finished. Can be used as a baseline for relative(). Result::Result(Config benchmarkConfig) : mConfig(std::move(benchmarkConfig)) , mNameToMeasurements{detail::u(Result::Measure::_size)} {} void Result::add(Clock::duration totalElapsed, uint64_t iters, detail::PerformanceCounters const& pc) { using detail::d; using detail::u; double const dIters = d(iters); mNameToMeasurements[u(Result::Measure::iterations)].push_back(dIters); mNameToMeasurements[u(Result::Measure::elapsed)].push_back(d(totalElapsed) / dIters); if (pc.has().pageFaults) { mNameToMeasurements[u(Result::Measure::pagefaults)].push_back(d(pc.val().pageFaults) / dIters); } if (pc.has().cpuCycles) { mNameToMeasurements[u(Result::Measure::cpucycles)].push_back(d(pc.val().cpuCycles) / dIters); } if (pc.has().contextSwitches) { mNameToMeasurements[u(Result::Measure::contextswitches)].push_back(d(pc.val().contextSwitches) / dIters); } if (pc.has().instructions) { mNameToMeasurements[u(Result::Measure::instructions)].push_back(d(pc.val().instructions) / dIters); } if (pc.has().branchInstructions) { double branchInstructions = 0.0; // correcting branches: remove branch introduced by the while (...) loop for each iteration. if (pc.val().branchInstructions > iters + 1U) { branchInstructions = d(pc.val().branchInstructions - (iters + 1U)); } mNameToMeasurements[u(Result::Measure::branchinstructions)].push_back(branchInstructions / dIters); if (pc.has().branchMisses) { // correcting branch misses double branchMisses = d(pc.val().branchMisses); if (branchMisses > branchInstructions) { // can't have branch misses when there were branches... branchMisses = branchInstructions; } // assuming at least one missed branch for the loop branchMisses -= 1.0; if (branchMisses < 1.0) { branchMisses = 1.0; } mNameToMeasurements[u(Result::Measure::branchmisses)].push_back(branchMisses / dIters); } } } Config const& Result::config() const noexcept { return mConfig; } inline double calcMedian(std::vector<double>& data) { if (data.empty()) { return 0.0; } std::sort(data.begin(), data.end()); auto midIdx = data.size() / 2U; if (1U == (data.size() & 1U)) { return data[midIdx]; } return (data[midIdx - 1U] + data[midIdx]) / 2U; } double Result::median(Measure m) const { // create a copy so we can sort auto data = mNameToMeasurements[detail::u(m)]; return calcMedian(data); } double Result::average(Measure m) const { using detail::d; auto const& data = mNameToMeasurements[detail::u(m)]; if (data.empty()) { return 0.0; } // create a copy so we can sort return sum(m) / d(data.size()); } double Result::medianAbsolutePercentError(Measure m) const { // create copy auto data = mNameToMeasurements[detail::u(m)]; // calculates MdAPE which is the median of percentage error // see https://support.numxl.com/hc/en-us/articles/115001223503-MdAPE-Median-Absolute-Percentage-Error auto med = calcMedian(data); // transform the data to absolute error for (auto& x : data) { x = (x - med) / x; if (x < 0) { x = -x; } } return calcMedian(data); } double Result::sum(Measure m) const noexcept { auto const& data = mNameToMeasurements[detail::u(m)]; return std::accumulate(data.begin(), data.end(), 0.0); } double Result::sumProduct(Measure m1, Measure m2) const noexcept { auto const& data1 = mNameToMeasurements[detail::u(m1)]; auto const& data2 = mNameToMeasurements[detail::u(m2)]; if (data1.size() != data2.size()) { return 0.0; } double result = 0.0; for (size_t i = 0, s = data1.size(); i != s; ++i) { result += data1[i] * data2[i]; } return result; } bool Result::has(Measure m) const noexcept { return !mNameToMeasurements[detail::u(m)].empty(); } double Result::get(size_t idx, Measure m) const { auto const& data = mNameToMeasurements[detail::u(m)]; return data.at(idx); } bool Result::empty() const noexcept { return 0U == size(); } size_t Result::size() const noexcept { auto const& data = mNameToMeasurements[detail::u(Measure::elapsed)]; return data.size(); } double Result::minimum(Measure m) const noexcept { auto const& data = mNameToMeasurements[detail::u(m)]; if (data.empty()) { return 0.0; } // here its save to assume that at least one element is there return *std::min_element(data.begin(), data.end()); } double Result::maximum(Measure m) const noexcept { auto const& data = mNameToMeasurements[detail::u(m)]; if (data.empty()) { return 0.0; } // here its save to assume that at least one element is there return *std::max_element(data.begin(), data.end()); } std::string const& Result::context(char const* variableName) const { return mConfig.mContext.at(variableName); } std::string const& Result::context(std::string const& variableName) const { return mConfig.mContext.at(variableName); } Result::Measure Result::fromString(std::string const& str) { if (str == "elapsed") { return Measure::elapsed; } if (str == "iterations") { return Measure::iterations; } if (str == "pagefaults") { return Measure::pagefaults; } if (str == "cpucycles") { return Measure::cpucycles; } if (str == "contextswitches") { return Measure::contextswitches; } if (str == "instructions") { return Measure::instructions; } if (str == "branchinstructions") { return Measure::branchinstructions; } if (str == "branchmisses") { return Measure::branchmisses; } // not found, return _size return Measure::_size; } // Configuration of a microbenchmark. Bench::Bench() { mConfig.mOut = &std::cout; } Bench::Bench(Bench&&) noexcept = default; Bench& Bench::operator=(Bench&&) noexcept(ANKERL_NANOBENCH(NOEXCEPT_STRING_MOVE)) = default; Bench::Bench(Bench const&) = default; Bench& Bench::operator=(Bench const&) = default; Bench::~Bench() noexcept = default; double Bench::batch() const noexcept { return mConfig.mBatch; } double Bench::complexityN() const noexcept { return mConfig.mComplexityN; } // Set a baseline to compare it to. 100% it is exactly as fast as the baseline, >100% means it is faster than the baseline, <100% // means it is slower than the baseline. Bench& Bench::relative(bool isRelativeEnabled) noexcept { mConfig.mIsRelative = isRelativeEnabled; return *this; } bool Bench::relative() const noexcept { return mConfig.mIsRelative; } Bench& Bench::performanceCounters(bool showPerformanceCounters) noexcept { mConfig.mShowPerformanceCounters = showPerformanceCounters; return *this; } bool Bench::performanceCounters() const noexcept { return mConfig.mShowPerformanceCounters; } // Operation unit. Defaults to "op", could be e.g. "byte" for string processing. // If u differs from currently set unit, the stored results will be cleared. // Use singular (byte, not bytes). Bench& Bench::unit(char const* u) { if (u != mConfig.mUnit) { mResults.clear(); } mConfig.mUnit = u; return *this; } Bench& Bench::unit(std::string const& u) { return unit(u.c_str()); } std::string const& Bench::unit() const noexcept { return mConfig.mUnit; } Bench& Bench::timeUnit(std::chrono::duration<double> const& tu, std::string const& tuName) { mConfig.mTimeUnit = tu; mConfig.mTimeUnitName = tuName; return *this; } std::string const& Bench::timeUnitName() const noexcept { return mConfig.mTimeUnitName; } std::chrono::duration<double> const& Bench::timeUnit() const noexcept { return mConfig.mTimeUnit; } // If benchmarkTitle differs from currently set title, the stored results will be cleared. Bench& Bench::title(const char* benchmarkTitle) { if (benchmarkTitle != mConfig.mBenchmarkTitle) { mResults.clear(); } mConfig.mBenchmarkTitle = benchmarkTitle; return *this; } Bench& Bench::title(std::string const& benchmarkTitle) { if (benchmarkTitle != mConfig.mBenchmarkTitle) { mResults.clear(); } mConfig.mBenchmarkTitle = benchmarkTitle; return *this; } std::string const& Bench::title() const noexcept { return mConfig.mBenchmarkTitle; } Bench& Bench::name(const char* benchmarkName) { mConfig.mBenchmarkName = benchmarkName; return *this; } Bench& Bench::name(std::string const& benchmarkName) { mConfig.mBenchmarkName = benchmarkName; return *this; } std::string const& Bench::name() const noexcept { return mConfig.mBenchmarkName; } Bench& Bench::context(char const* variableName, char const* variableValue) { mConfig.mContext[variableName] = variableValue; return *this; } Bench& Bench::context(std::string const& variableName, std::string const& variableValue) { mConfig.mContext[variableName] = variableValue; return *this; } Bench& Bench::clearContext() { mConfig.mContext.clear(); return *this; } // Number of epochs to evaluate. The reported result will be the median of evaluation of each epoch. Bench& Bench::epochs(size_t numEpochs) noexcept { mConfig.mNumEpochs = numEpochs; return *this; } size_t Bench::epochs() const noexcept { return mConfig.mNumEpochs; } // Desired evaluation time is a multiple of clock resolution. Default is to be 1000 times above this measurement precision. Bench& Bench::clockResolutionMultiple(size_t multiple) noexcept { mConfig.mClockResolutionMultiple = multiple; return *this; } size_t Bench::clockResolutionMultiple() const noexcept { return mConfig.mClockResolutionMultiple; } // Sets the maximum time each epoch should take. Default is 100ms. Bench& Bench::maxEpochTime(std::chrono::nanoseconds t) noexcept { mConfig.mMaxEpochTime = t; return *this; } std::chrono::nanoseconds Bench::maxEpochTime() const noexcept { return mConfig.mMaxEpochTime; } // Sets the maximum time each epoch should take. Default is 100ms. Bench& Bench::minEpochTime(std::chrono::nanoseconds t) noexcept { mConfig.mMinEpochTime = t; return *this; } std::chrono::nanoseconds Bench::minEpochTime() const noexcept { return mConfig.mMinEpochTime; } Bench& Bench::minEpochIterations(uint64_t numIters) noexcept { mConfig.mMinEpochIterations = (numIters == 0) ? 1 : numIters; return *this; } uint64_t Bench::minEpochIterations() const noexcept { return mConfig.mMinEpochIterations; } Bench& Bench::epochIterations(uint64_t numIters) noexcept { mConfig.mEpochIterations = numIters; return *this; } uint64_t Bench::epochIterations() const noexcept { return mConfig.mEpochIterations; } Bench& Bench::warmup(uint64_t numWarmupIters) noexcept { mConfig.mWarmup = numWarmupIters; return *this; } uint64_t Bench::warmup() const noexcept { return mConfig.mWarmup; } Bench& Bench::config(Config const& benchmarkConfig) { mConfig = benchmarkConfig; return *this; } Config const& Bench::config() const noexcept { return mConfig; } Bench& Bench::output(std::ostream* outstream) noexcept { mConfig.mOut = outstream; return *this; } ANKERL_NANOBENCH(NODISCARD) std::ostream* Bench::output() const noexcept { return mConfig.mOut; } std::vector<Result> const& Bench::results() const noexcept { return mResults; } Bench& Bench::render(char const* templateContent, std::ostream& os) { ::ankerl::nanobench::render(templateContent, *this, os); return *this; } Bench& Bench::render(std::string const& templateContent, std::ostream& os) { ::ankerl::nanobench::render(templateContent, *this, os); return *this; } std::vector<BigO> Bench::complexityBigO() const { std::vector<BigO> bigOs; auto rangeMeasure = BigO::collectRangeMeasure(mResults); bigOs.emplace_back("O(1)", rangeMeasure, [](double) { return 1.0; }); bigOs.emplace_back("O(n)", rangeMeasure, [](double n) { return n; }); bigOs.emplace_back("O(log n)", rangeMeasure, [](double n) { return std::log2(n); }); bigOs.emplace_back("O(n log n)", rangeMeasure, [](double n) { return n * std::log2(n); }); bigOs.emplace_back("O(n^2)", rangeMeasure, [](double n) { return n * n; }); bigOs.emplace_back("O(n^3)", rangeMeasure, [](double n) { return n * n * n; }); std::sort(bigOs.begin(), bigOs.end()); return bigOs; } Rng::Rng() : mX(0) , mY(0) { std::random_device rd; std::uniform_int_distribution<uint64_t> dist; do { mX = dist(rd); mY = dist(rd); } while (mX == 0 && mY == 0); } ANKERL_NANOBENCH_NO_SANITIZE("integer", "undefined") uint64_t splitMix64(uint64_t& state) noexcept { uint64_t z = (state += UINT64_C(0x9e3779b97f4a7c15)); z = (z ^ (z >> 30U)) * UINT64_C(0xbf58476d1ce4e5b9); z = (z ^ (z >> 27U)) * UINT64_C(0x94d049bb133111eb); return z ^ (z >> 31U); } // Seeded as described in romu paper (update april 2020) Rng::Rng(uint64_t seed) noexcept : mX(splitMix64(seed)) , mY(splitMix64(seed)) { for (size_t i = 0; i < 10; ++i) { operator()(); } } // only internally used to copy the RNG. Rng::Rng(uint64_t x, uint64_t y) noexcept : mX(x) , mY(y) {} Rng Rng::copy() const noexcept { return Rng{mX, mY}; } Rng::Rng(std::vector<uint64_t> const& data) : mX(0) , mY(0) { if (data.size() != 2) { throw std::runtime_error("ankerl::nanobench::Rng::Rng: needed exactly 2 entries in data, but got " + detail::fmt::to_s(data.size())); } mX = data[0]; mY = data[1]; } std::vector<uint64_t> Rng::state() const { std::vector<uint64_t> data(2); data[0] = mX; data[1] = mY; return data; } BigO::RangeMeasure BigO::collectRangeMeasure(std::vector<Result> const& results) { BigO::RangeMeasure rangeMeasure; for (auto const& result : results) { if (result.config().mComplexityN > 0.0) { rangeMeasure.emplace_back(result.config().mComplexityN, result.median(Result::Measure::elapsed)); } } return rangeMeasure; } BigO::BigO(std::string bigOName, RangeMeasure const& rangeMeasure) : mName(std::move(bigOName)) { // estimate the constant factor double sumRangeMeasure = 0.0; double sumRangeRange = 0.0; for (const auto& rm : rangeMeasure) { sumRangeMeasure += rm.first * rm.second; sumRangeRange += rm.first * rm.first; } mConstant = sumRangeMeasure / sumRangeRange; // calculate root mean square double err = 0.0; double sumMeasure = 0.0; for (const auto& rm : rangeMeasure) { auto diff = mConstant * rm.first - rm.second; err += diff * diff; sumMeasure += rm.second; } auto n = detail::d(rangeMeasure.size()); auto mean = sumMeasure / n; mNormalizedRootMeanSquare = std::sqrt(err / n) / mean; } BigO::BigO(const char* bigOName, RangeMeasure const& rangeMeasure) : BigO(std::string(bigOName), rangeMeasure) {} std::string const& BigO::name() const noexcept { return mName; } double BigO::constant() const noexcept { return mConstant; } double BigO::normalizedRootMeanSquare() const noexcept { return mNormalizedRootMeanSquare; } bool BigO::operator<(BigO const& other) const noexcept { return std::tie(mNormalizedRootMeanSquare, mName) < std::tie(other.mNormalizedRootMeanSquare, other.mName); } std::ostream& operator<<(std::ostream& os, BigO const& bigO) { return os << bigO.constant() << " * " << bigO.name() << ", rms=" << bigO.normalizedRootMeanSquare(); } std::ostream& operator<<(std::ostream& os, std::vector<ankerl::nanobench::BigO> const& bigOs) { detail::fmt::StreamStateRestorer const restorer(os); os << std::endl << "| coefficient | err% | complexity" << std::endl << "|--------------:|-------:|------------" << std::endl; for (auto const& bigO : bigOs) { os << "|" << std::setw(14) << std::setprecision(7) << std::scientific << bigO.constant() << " "; os << "|" << detail::fmt::Number(6, 1, bigO.normalizedRootMeanSquare() * 100.0) << "% "; os << "| " << bigO.name(); os << std::endl; } return os; } } // namespace nanobench } // namespace ankerl #endif // ANKERL_NANOBENCH_IMPLEMENT #endif // ANKERL_NANOBENCH_H_INCLUDED
yhirose/mtlcpp
16
Utilities for Metal-cpp
C++
yhirose
test/test.cpp
C++
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest.h" #define ANKERL_NANOBENCH_IMPLEMENT #include "nanobench.h" #define NS_PRIVATE_IMPLEMENTATION #define MTL_PRIVATE_IMPLEMENTATION #include <Metal/Metal.hpp>
yhirose/mtlcpp
16
Utilities for Metal-cpp
C++
yhirose
test/test_2lnn.cpp
C++
#include <mtlcpp.h> #include "doctest.h" mtl::array<float> mean_square_error_derivative(float dout, const mtl::array<float>& out, const mtl::array<float>& Y) { return dout * (2 * (out - Y)); } mtl::array<float> sigmoid_derivative(const mtl::array<float>& dout, const mtl::array<float>& x) { auto y = x.sigmoid(); return dout * (y * (1 - y)); } std::tuple<mtl::array<float>, mtl::array<float>, mtl::array<float>> linear_derivative(const mtl::array<float>& dout, const mtl::array<float>& x, const mtl::array<float>& W) { auto dx = dout.dot(W.transpose()); auto dW = x.transpose().dot(dout); auto db = dout.sum(0); return {dx, dW, db}; } struct TwoLayerNeuralNetwork { mtl::array<float> W1 = mtl::random({2, 3}) * 2.0 - 1.0; mtl::array<float> b1 = mtl::random({3}) * 2.0 - 1.0; mtl::array<float> W2 = mtl::random({3, 1}) * 2.0 - 1.0; mtl::array<float> b2 = mtl::random({1}) * 2.0 - 1.0; mtl::array<float> x; mtl::array<float> net1; mtl::array<float> out1; mtl::array<float> net2; mtl::array<float> out2; mtl::array<float> Y; mtl::array<float> forward(const mtl::array<float>& x) { // Input → Hidden auto net1 = x.linear(W1, b1); auto out1 = net1.sigmoid(); // Hidden → Output auto net2 = out1.linear(W2, b2); auto out2 = net2.sigmoid(); // Save variables for backpropagation this->x = x; this->net1 = net1; this->out1 = out1; this->net2 = net2; this->out2 = out2; return out2; } float loss(const mtl::array<float>& out, const mtl::array<float>& Y) { // Save variables for back propagation this->Y = Y; return out.mean_square_error(Y); } std::tuple<mtl::array<float>, mtl::array<float>, mtl::array<float>, mtl::array<float>> backward() { auto dout = mean_square_error_derivative(1.0, this->out2, this->Y); dout = sigmoid_derivative(dout, this->net2); const auto& [dout1, dW2, db2] = linear_derivative(dout, this->out1, this->W2); dout = sigmoid_derivative(dout1, this->net1); const auto& [dx, dW1, db1] = linear_derivative(dout, this->x, this->W1); return {dW1, db1, dW2, db2}; } }; mtl::array<float> predict(TwoLayerNeuralNetwork& model, const mtl::array<float>& x) { auto out = model.forward(x); // 0..1 return mtl::where<float>(out > 0.5, 1, 0); } void train(TwoLayerNeuralNetwork& model, const mtl::array<float>& X, const mtl::array<float>& Y, size_t epochs, float learning_rate) { std::vector<float> losses; for (size_t epoch = 0; epoch < epochs; epoch++) { // Save variables for back propagation auto out = model.forward(X); auto loss = model.loss(out, Y); // Get gradients of weight parameters const auto& [dW1, db1, dW2, db2] = model.backward(); // Update weights model.W1 -= dW1 * learning_rate; model.b1 -= db1 * learning_rate; model.W2 -= dW2 * learning_rate; model.b2 -= db2 * learning_rate; losses.push_back(loss); // Show progress message if (epoch % (epochs / 10) == 0) { printf("Epoch: %zu, Loss: %f\n", epoch, loss); } } } TEST_CASE("array: mean_square_error") { auto a = mtl::array<float>{1, 2, 3, 4}; auto b = mtl::array<float>{0, 2, 3, 6}; auto mean = a.mean_square_error(b); CHECK(mean == 1.25); } TEST_CASE("2 layer NN: xor") { auto X = mtl::array<float>{ {0, 0}, {0, 1}, {1, 0}, {1, 1}, }; auto Y_XOR = mtl::array<float>{ {0}, {1}, {1}, {0}, }; TwoLayerNeuralNetwork m; train(m, X, Y_XOR, 2000, 0.5); auto out = predict(m, X); std::cout << out << std::endl; }
yhirose/mtlcpp
16
Utilities for Metal-cpp
C++
yhirose
test/test_array.cpp
C++
#include <mtlcpp.h> #include <iostream> #include <ranges> #include "doctest.h" using namespace mtl; auto itoa(size_t size, size_t init = 1) { return std::views::iota(init) | std::views::take(size); } //------------------------------------------------------------------------------ TEST_CASE("array: scalar size") { auto s = array<int>(100); CHECK(s.element_count() == 1); CHECK_THROWS_WITH_AS(s.length(), "array: cannot call with a scalar value.", std::runtime_error); CHECK(s.dimension() == 0); CHECK(s.shape() == shape_type{}); CHECK(s.at() == 100); } //------------------------------------------------------------------------------ TEST_CASE("array: vector size") { auto v = empty<int>({3}); CHECK(v.element_count() == 3); CHECK(v.length() == 3); CHECK(v.dimension() == 1); CHECK(v.shape() == shape_type{3}); CHECK(v.shape()[0] == 3); } TEST_CASE("array: vector initializer") { auto v = array<int>{1, 2, 3, 4}; CHECK(v.element_count() == 4); } TEST_CASE("vector: container") { std::vector<int> a{1, 2, 3, 4}; auto v1 = array<int>({a.size() - 1}, a); CHECK(v1.element_count() == 3); CHECK(array_equal(v1, {1, 2, 3})); auto v2 = array<int>({a.size() + 1}, a); CHECK(v2.element_count() == 5); CHECK(array_equal(v1, {1, 2, 3})); auto v3 = array<int>(a); CHECK(v3.element_count() == 4); CHECK(array_equal(v3, {1, 2, 3, 4})); } TEST_CASE("array: vector ranges") { auto v = array<int>({10}, std::views::iota(1) | std::views::take(10)); CHECK(v.element_count() == 10); CHECK(array_equal(v, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})); } TEST_CASE("array: vector `clone`") { auto a = ones<float>({8}); auto b = a; a.zeros(); CHECK(array_equal(a, b)); b = a.clone(); a.ones(); CHECK(!array_equal(a, b)); } TEST_CASE("array: vector assignment operator") { auto v = zeros<float>({8}); for (size_t i = 0; i < v.element_count(); i++) { v.at(i) = 1; } CHECK(array_equal(ones<float>({8}), v)); } TEST_CASE("array: vector bounds check") { auto v = array<int>({10}, std::views::iota(0) | std::views::take(10)); CHECK(v.at(9) == 9); CHECK_THROWS_WITH_AS(v.at(10), "array: index is out of bounds.", std::runtime_error); } TEST_CASE("array: vector range-for") { auto v = zeros<float>({8}); std::fill(v.buffer_data(), v.buffer_data() + v.buffer_element_count(), 1); CHECK(array_equal(ones<float>({8}), v)); } TEST_CASE("array: vector arithmatic operations") { constexpr size_t element_count = 16; auto a = array<float>{7.82637e-06, 0.131538, 0.755605, 0.45865, 0.532767, 0.218959, 0.0470446, 0.678865, 0.679296, 0.934693, 0.383502, 0.519416, 0.830965, 0.0345721, 0.0534616, 0.5297}; auto b = array<float>{0.671149, 0.00769819, 0.383416, 0.0668422, 0.417486, 0.686773, 0.588977, 0.930436, 0.846167, 0.526929, 0.0919649, 0.653919, 0.415999, 0.701191, 0.910321, 0.762198}; CHECK(allclose(a + b, {0.671157, 0.139236, 1.13902, 0.525492, 0.950253, 0.905732, 0.636021, 1.6093, 1.52546, 1.46162, 0.475467, 1.17334, 1.24696, 0.735763, 0.963782, 1.2919})); CHECK(allclose( a - b, {-0.671141, 0.12384, 0.372189, 0.391808, 0.115281, -0.467814, -0.541932, -0.251571, -0.166871, 0.407764, 0.291537, -0.134503, 0.414966, -0.666619, -0.856859, -0.232498})); CHECK(allclose( a * b, {5.25266e-06, 0.0010126, 0.289711, 0.0306572, 0.222423, 0.150375, 0.0277082, 0.63164, 0.574798, 0.492517, 0.0352687, 0.339656, 0.345681, 0.0242416, 0.0486672, 0.403736})); CHECK( allclose(a / b, {1.16612e-05, 17.0869, 1.97072, 6.86168, 1.27613, 0.318823, 0.0798751, 0.72962, 0.802792, 1.77385, 4.17009, 0.794312, 1.99752, 0.0493048, 0.0587283, 0.694964})); } TEST_CASE("array: vector arithmatic operation errors") { auto a = random({4}); auto b = random({8}); CHECK(!array_equal(a, b)); CHECK_THROWS_WITH_AS(a + b, "array: invalid operation.", std::runtime_error); } TEST_CASE("array: vector `pow` operation") { { auto a = array<int>{1, 2, 3}; auto b = array<int>{2, 2, 2}; CHECK(array_equal(a.pow(b), {1, 4, 9})); CHECK(array_equal(b.pow(a), {2, 4, 8})); } { auto a = array<float>{1.0, 2.0, 3.0}; auto b = array<float>{2.0, 2.0, 2.0}; CHECK(allclose(a.pow(b), {1.0, 4.0, 9.0})); CHECK(allclose(b.pow(a), {2.0, 4.0, 8.0})); } } //------------------------------------------------------------------------------ TEST_CASE("array: matrix size") { auto m = empty<int>({3, 4}); CHECK(m.element_count() == 12); CHECK(m.shape() == shape_type{3, 4}); CHECK(m.shape()[0] == 3); CHECK(m.shape()[1] == 4); CHECK(m.dimension() == 2); } TEST_CASE("array: matrix container") { auto m1 = array<int>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; CHECK(m1.element_count() == 12); CHECK(m1.dimension() == 1); CHECK(m1.shape() == shape_type{12}); CHECK(m1.strides() == strides_type{1}); auto m2 = array<int>{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; CHECK(m2.element_count() == 12); CHECK(m2.dimension() == 2); CHECK(m2.shape() == shape_type{3, 4}); CHECK(m2.strides() == strides_type{4, 1}); auto m3 = array<int>{{{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}}; CHECK(m3.element_count() == 12); CHECK(m3.dimension() == 3); CHECK(m3.shape() == shape_type{2, 2, 3}); CHECK(m3.strides() == strides_type{6, 3, 1}); CHECK_THROWS_WITH_AS( (array<int>{{{1, 2, 3}, {4, 5}}, {{7, 8, 9}, {10, 11, 12}}}), "array: invalid initializer list.", std::runtime_error); } TEST_CASE("array: matrix ranges") { auto m = array<int>({3, 4}, std::views::iota(1) | std::views::take(12)); size_t i = 0; for (size_t row = 0; row < m.shape()[0]; row++) { for (size_t col = 0; col < m.shape()[1]; col++) { CHECK(m.at(row, col) == m.at(i)); i++; } } CHECK(array_equal(m, {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}})); } TEST_CASE("array: matrix arithmatic operations") { auto r = itoa(12); auto a = array<int>({3, 4}, r); auto b = array<int>({3, 4}, r); CHECK(array_equal(a + b, {{2, 4, 6, 8}, {10, 12, 14, 16}, {18, 20, 22, 24}})); CHECK(array_equal(a - b, {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}})); CHECK(array_equal(a * b, {{1, 4, 9, 16}, {25, 36, 49, 64}, {81, 100, 121, 144}})); CHECK(array_equal(a / b, {{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}})); } TEST_CASE("array: matrix arithmatic operations with scalar") { auto a = array<float>{{1, 2}, {3, 4}}; CHECK(array_equal(a + 1, {{2, 3}, {4, 5}})); CHECK(array_equal(a - 1, {{0, 1}, {2, 3}})); CHECK(array_equal(a * 2, {{2, 4}, {6, 8}})); CHECK(array_equal(a / 2, {{0.5, 1}, {1.5, 2}})); CHECK(array_equal(1 + a, {{2, 3}, {4, 5}})); CHECK(array_equal(1 - a, {{0, -1}, {-2, -3}})); CHECK(array_equal(2 * a, {{2, 4}, {6, 8}})); CHECK(array_equal(2 / a, {{2, 1}, {2.0 / 3.0, 0.5}})); } TEST_CASE("array: matrix v*v `dot` operation") { auto a = array<int>({4}, itoa(4)); auto b = array<int>({4}, itoa(4)); auto out = a.dot(b); CHECK(out.shape() == shape_type{}); CHECK(array_equal(out, array<int>(30))); } TEST_CASE("array: matrix m*m `dot` operation") { auto a = array<int>({3, 4}, itoa(12)); auto b = array<int>({4, 2}, itoa(8)); auto out = a.dot(b); CHECK(out.shape() == shape_type{3, 2}); CHECK(array_equal(out, {{50, 60}, {114, 140}, {178, 220}})); } TEST_CASE("array: matrix v*m `dot` operation") { auto a = array<int>({4}, itoa(4)); auto b = array<int>({4, 2}, itoa(8)); auto out = a.dot(b); CHECK(out.shape() == shape_type{2}); CHECK(array_equal(out, {50, 60})); } TEST_CASE("array: matrix m*v `dot` operation") { auto a = array<int>({2, 4}, itoa(8)); auto b = array<int>({4}, itoa(4)); auto out = a.dot(b); CHECK(out.shape() == shape_type{2}); CHECK(array_equal(out, {30, 70})); } TEST_CASE("array: matrix transpose") { auto v = array<int>{1, 2, 3, 4}; auto vT = v.transpose(); CHECK(vT.element_count() == 4); CHECK(vT.dimension() == 2); CHECK(vT.shape() == shape_type{1, 4}); CHECK(array_equal(vT, {{1, 2, 3, 4}})); auto vT2 = vT.transpose(); CHECK(vT2.element_count() == 4); CHECK(vT2.dimension() == 1); CHECK(vT2.shape() == shape_type{4}); CHECK(array_equal(vT2, {1, 2, 3, 4})); auto m2 = array<int>{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; auto m2T = m2.transpose(); CHECK(m2T.element_count() == 12); CHECK(m2T.dimension() == 2); CHECK(m2T.shape() == shape_type{4, 3}); CHECK(array_equal(m2T, {{1, 5, 9}, {2, 6, 10}, {3, 7, 11}, {4, 8, 12}})); auto m2T2 = m2T.transpose(); CHECK(m2T2.element_count() == m2.element_count()); CHECK(m2T2.dimension() == m2.dimension()); CHECK(m2T2.shape() == m2.shape()); CHECK(array_equal(m2T2, m2)); auto m3 = array<int>{{{1, 2, 3, 4}, {5, 6, 7, 8}}, {{9, 10, 11, 12}, {13, 14, 15, 16}}}; CHECK(m3.element_count() == 16); CHECK(m3.dimension() == 3); CHECK(m3.shape() == shape_type{2, 2, 4}); auto m3T = m3.transpose(); CHECK(m3T.element_count() == 16); CHECK(m3T.dimension() == 3); CHECK(m3T.shape() == shape_type{4, 2, 2}); auto m3T2 = m3T.transpose(); CHECK(m3T2.element_count() == m3.element_count()); CHECK(m3T2.dimension() == m3.dimension()); CHECK(m3T2.shape() == m3.shape()); CHECK(array_equal(m3T2, m3)); } TEST_CASE("array: matrix broadcast") { auto a = array<int>{{1, 2, 3}, {4, 5, 6}}; auto b = a.broadcast({3, 2, 3}); CHECK(array_equal(b, {{{1, 2, 3}, {4, 5, 6}}, {{1, 2, 3}, {4, 5, 6}}, {{1, 2, 3}, {4, 5, 6}}})); CHECK(b.element_count() == 18); CHECK(b.buffer_element_count() == 6); CHECK(b.buffer_bytes() == 6 * sizeof(int)); CHECK(b.at(0) == 1); CHECK(b.at(b.element_count() - 1) == 6); CHECK(b.at(0, 0, 0) == 1); CHECK(b.at(1, 1, 0) == 4); CHECK(b.at(2, 1, 2) == 6); CHECK(b.strides().size() == 3); CHECK(b.strides()[0] == 0); CHECK(b.strides()[1] == 3); CHECK(b.strides()[2] == 1); } TEST_CASE("array: matrix arithmatic operations with broadcast") { auto a_2_3 = array<int>{{1, 2, 3}, {4, 5, 6}}; auto a_2_2_3 = array<int>{{{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}}; auto b = array<int>(1); auto b_3 = array<int>{1, 2, 3}; auto b_2_3 = array<int>{{1, 2, 3}, {4, 5, 6}}; CHECK(array_equal(a_2_3 + b, {{2, 3, 4}, {5, 6, 7}})); CHECK(array_equal(a_2_2_3 + b, {{{2, 3, 4}, {5, 6, 7}}, {{8, 9, 10}, {11, 12, 13}}})); CHECK(array_equal(a_2_3 + b_3, {{2, 4, 6}, {5, 7, 9}})); CHECK(array_equal(a_2_2_3 + b_3, {{{2, 4, 6}, {5, 7, 9}}, {{8, 10, 12}, {11, 13, 15}}})); CHECK(array_equal(a_2_2_3 + b_2_3, {{{2, 4, 6}, {8, 10, 12}}, {{8, 10, 12}, {14, 16, 18}}})); CHECK(array_equal(b + a_2_3, {{2, 3, 4}, {5, 6, 7}})); CHECK(array_equal(b + a_2_2_3, {{{2, 3, 4}, {5, 6, 7}}, {{8, 9, 10}, {11, 12, 13}}})); CHECK(array_equal(b_3 + a_2_3, {{2, 4, 6}, {5, 7, 9}})); CHECK(array_equal(b_3 + a_2_2_3, {{{2, 4, 6}, {5, 7, 9}}, {{8, 10, 12}, {11, 13, 15}}})); CHECK(array_equal(b_2_3 + a_2_2_3, {{{2, 4, 6}, {8, 10, 12}}, {{8, 10, 12}, {14, 16, 18}}})); } TEST_CASE("array: matrix slice") { auto t = array<int>{ {{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}, {{13, 14, 15}, {16, 17, 18}}, }; CHECK_THROWS_WITH_AS(t[3], "array: row is out of bounds.", std::runtime_error); auto m = t[1]; auto v = m[1]; auto s = v[1]; CHECK(array_equal(m, {{7, 8, 9}, {10, 11, 12}})); CHECK(array_equal(v, {10, 11, 12})); CHECK(array_equal(s, array<int>(11))); s.at() += 100; CHECK(array_equal(t, {{{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 111, 12}}, {{13, 14, 15}, {16, 17, 18}}})); CHECK(array_equal(m, {{7, 8, 9}, {10, 111, 12}})); CHECK(array_equal(v, {10, 111, 12})); CHECK(array_equal(s, array<int>(111))); m.zeros(); CHECK(array_equal(t, {{{1, 2, 3}, {4, 5, 6}}, {{0, 0, 0}, {0, 0, 0}}, {{13, 14, 15}, {16, 17, 18}}})); CHECK(array_equal(m, {{0, 0, 0}, {0, 0, 0}})); CHECK(array_equal(v, {0, 0, 0})); CHECK(array_equal(s, array<int>(0))); } //------------------------------------------------------------------------------ TEST_CASE("array: aggregate functions") { auto v = array<int>{1, 2, 3, 4, 5, 6}; auto t = array<int>{ {{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}, {{13, 14, 15}, {16, 17, 18}}, }; CHECK(v.min() == 1); CHECK(v.max() == 6); CHECK(t.min() == 1); CHECK(t.max() == 18); CHECK(v.sum() == 21); CHECK(t.sum() == 171); CHECK(array_equal(t.sum(0), {{21, 24, 27}, {30, 33, 36}})); CHECK(array_equal(t.sum(1), {{5, 7, 9}, {17, 19, 21}, {29, 31, 33}})); CHECK(array_equal(t.sum(2), {{6, 15}, {24, 33}, {42, 51}})); CHECK(is_close(array<float>{1.1, 2.2}.sum(), 3.3)); CHECK(is_close(array<int>{1, 2}.sum(), 3l)); CHECK(v.mean() == 3.5); CHECK(t.mean() == 9.5); CHECK(array_equal(t.mean(0), array<float>{{7, 8, 9}, {10, 11, 12}})); CHECK(array_equal( t.mean(1), array<float>{{2.5, 3.5, 4.5}, {8.5, 9.5, 10.5}, {14.5, 15.5, 16.5}})); CHECK(array_equal(t.mean(2), array<float>{{2, 5}, {8, 11}, {14, 17}})); } TEST_CASE("array: softmax") { auto v = array<int>{1, 2, 3, 4, 5, 6}; auto m = array<int>{{7, 8, 9}, {10, 11, 12}}; auto vsm = v.softmax(); auto msm = m.softmax(); CHECK(vsm.sum() == 1); CHECK(vsm.all([](auto x) { return x <= 1; })); CHECK(array_equal(msm.sum(1), array<float>{1, 1})); CHECK(msm.all([](auto x) { return x <= 1; })); } TEST_CASE("array: iterators") { auto t = array<int>{ {{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}, {{13, 14, 15}, {16, 17, 18}}, }; for (auto row : t) { for (auto &x : row.elements()) { x += 100; } } const auto ct = t; int cur = 101; for (auto row : ct.rows()) { for (const auto &x : row.elements()) { CHECK(x == cur++); } } cur = 101; for (auto row : ct.rows()) { for (auto [a, b, c] : row.rows<3>()) { CHECK(a == cur++); CHECK(b == cur++); CHECK(c == cur++); } } }
yhirose/mtlcpp
16
Utilities for Metal-cpp
C++
yhirose
test/test_examples.cpp
C++
#include <mtlcpp.h> #include "doctest.h" using namespace mtl; TEST_CASE("example: create empty array") { auto i = empty<int>({2, 3, 2}); auto f = empty<float>({2, 3, 2}); // auto d = empty<double>({2, 3}); // cannot compile... } TEST_CASE("example: create array with constants") { auto s = array<float>(1); auto v = array<float>{1, 2, 3, 4, 5, 6}; auto m = array<float>{{1, 2}, {3, 4}, {5, 6}}; auto t = array<float>{{{1, 2}, {3, 4}, {5, 6}}, {{7, 8}, {9, 10}, {11, 12}}}; // std::cout << s.print_info() << std::endl << s << std::endl << std::endl; // std::cout << v.print_info() << std::endl << v << std::endl << std::endl; // std::cout << m.print_info() << std::endl << m << std::endl << std::endl; // std::cout << t.print_info() << std::endl << t << std::endl << std::endl; // dtype: float, dim: 0, shape: {}, strides: {1} // 1 // // dtype: float, dim: 1, shape: {6}, strides: {1} // {1, 2, 3, 4, 5, 6} // // dtype: float, dim: 2, shape: {3, 2}, strides: {2, 1} // {{1, 2}, // {3, 4}, // {5, 6}} // // dtype: float, dim: 3, shape: {2, 3, 2}, strides: {6, 2, 1} // {{{1, 2}, // {3, 4}, // {5, 6}}, // // {{7, 8}, // {9, 10}, // {11, 12}}} } TEST_CASE("example: create array with shape") { auto zeros1 = array<float>({2, 3, 2}, 0); auto zeros2 = zeros<float>({2, 3, 2}); CHECK(array_equal(zeros1, zeros2)); auto ones1 = array<float>({2, 3, 2}, 1); auto ones2 = ones<float>({2, 3, 2}); CHECK(array_equal(ones1, ones2)); auto rand = random({2, 3, 2}); CHECK(rand.all([](auto val) { return 0 <= val && val < 1.0; })); auto v = std::vector<float>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; auto from_iterator = array<float>({2, 3, 2}, v.begin()); auto from_range1 = array<float>({2, 3, 2}, v); auto from_range2 = array<float>({2, 3, 2}, std::views::iota(1)); auto expected = array<float>({ {{1, 2}, {3, 4}, {5, 6}}, {{7, 8}, {9, 10}, {11, 12}}, }); CHECK(array_equal(from_iterator, expected)); CHECK(array_equal(from_range1, expected)); CHECK(array_equal(from_range2, expected)); } TEST_CASE("example: clone array") { auto a = ones<float>({4}); auto cloned = a.clone(); cloned.zeros(); CHECK(array_equal(a, {1, 1, 1, 1})); auto assigned = a; assigned.zeros(); CHECK(array_equal(a, {0, 0, 0, 0})); } TEST_CASE("example: arithmatic operations") { auto a = array<float>{{1, 2}, {3, 4}}; auto b = array<float>{{1, 2}, {3, 4}}; auto add = a + b; CHECK(array_equal(add, {{2, 4}, {6, 8}})); auto sub = a - b; CHECK(array_equal(sub, {{0, 0}, {0, 0}})); auto mul = a * b; CHECK(array_equal(mul, {{1, 4}, {9, 16}})); auto div = a / b; CHECK(array_equal(div, {{1, 1}, {1, 1}})); } TEST_CASE("example: dot operation") { auto x = array<float>{1, 2, 3}; auto W = array<float>{{1, 2}, {3, 4}, {5, 6}}; auto y = x.dot(W); CHECK(array_equal(y, {22, 28})); }
yhirose/mtlcpp
16
Utilities for Metal-cpp
C++
yhirose
test/test_perceptron.cpp
C++
#include <mtlcpp.h> #include "doctest.h" class LogicGate { private: float w0 = 0.1; float w1 = 0.1; float b = 0.1; auto range(size_t count) { return std::views::iota(1) | std::views::take(count); } int predict(int x0, int x1) { auto y = (x0 * w0) + (x1 * w1) + b; return y > 0 ? 1 : 0; } public: LogicGate(mtl::array<int>&& dataset) { auto max_iteration = 10; auto learning_rate = 1.0; for (auto n : range(max_iteration)) { for (auto [x0, x1, t] : dataset.rows<3>()) { auto y = predict(x0, x1); auto diff = t - y; auto update = diff * learning_rate; w0 += update * x0; w1 += update * x1; b += update; } } } int operator()(int x0, int x1) { return predict(x0, x1); } }; TEST_CASE("perceptron: nand") { auto AND = LogicGate({ {0, 0, 0}, {0, 1, 0}, {1, 0, 0}, {1, 1, 1}, }); auto OR = LogicGate({ {0, 0, 0}, {0, 1, 1}, {1, 0, 1}, {1, 1, 1}, }); auto NAND = LogicGate({ {0, 0, 1}, {0, 1, 1}, {1, 0, 1}, {1, 1, 0}, }); auto XOR = [&](int x0, int x1) { return AND(NAND(x0, x1), OR(x0, x1)); }; CHECK(AND(0, 0) == 0); CHECK(AND(0, 1) == 0); CHECK(AND(1, 0) == 0); CHECK(AND(1, 1) == 1); CHECK(OR(0, 0) == 0); CHECK(OR(0, 1) == 1); CHECK(OR(1, 0) == 1); CHECK(OR(1, 1) == 1); CHECK(NAND(0, 0) == 1); CHECK(NAND(0, 1) == 1); CHECK(NAND(1, 0) == 1); CHECK(NAND(1, 1) == 0); CHECK(XOR(0, 0) == 0); CHECK(XOR(0, 1) == 1); CHECK(XOR(1, 0) == 1); CHECK(XOR(1, 1) == 0); }
yhirose/mtlcpp
16
Utilities for Metal-cpp
C++
yhirose
fetch_leetcode.py
Python
#!/usr/bin/env python3 """获取 LeetCode CN 的所有简单题目 - 只做 easy,不要忘了为什么出发""" import requests url = "https://leetcode.cn/graphql/" headers = {"Content-Type": "application/json"} query = """ query problemsetQuestionList($categorySlug: String, $limit: Int, $skip: Int, $filters: QuestionListFilterInput) { problemsetQuestionList( categorySlug: $categorySlug limit: $limit skip: $skip filters: $filters ) { total questions { frontendQuestionId title titleSlug difficulty paidOnly } } } """ easy = [] skip = 0 limit = 500 total = None while True: variables = {"categorySlug": "", "limit": limit, "skip": skip, "filters": {}} response = requests.post( url, json={"query": query, "variables": variables}, headers=headers ) data = response.json() questions = data["data"]["problemsetQuestionList"]["questions"] if total is None: total = data["data"]["problemsetQuestionList"]["total"] print(f"Total questions: {total}") if not questions: break for q in questions: if q["paidOnly"]: continue if q["difficulty"] == "EASY": item = f"{q['frontendQuestionId']}|{q['title']}|{q['titleSlug']}" easy.append(item) skip += limit print(f"Fetched {skip} questions...") if skip >= total: break with open("leetcode_easy.txt", "w") as f: f.write("\n".join(easy)) # 创建空的已使用记录文件(如果不存在) open("leetcode_used.txt", "a").close() print(f"Written {len(easy)} easy problems to leetcode_easy.txt")
yihong0618/2026
11
2026
Python
yihong0618
yihong
apache
get_up.py
Python
import argparse import random import os import tempfile import duckdb import pendulum import requests import telebot from github import Auth, Github from telegramify_markdown import markdownify from zhconv import convert # 1 real get up GET_UP_ISSUE_NUMBER = 1 GET_UP_MESSAGE_TEMPLATE = """今天的起床时间是--{get_up_time}。 起床啦。 今天是今年的第 {day_of_year} 天。 {year_progress} {leetcode} {running_info} {history_today} 今天的一首诗: {sentence} """ # LeetCode 题目文件路径 LEETCODE_EASY_FILE = "leetcode_easy.txt" LEETCODE_USED_FILE = "leetcode_used.txt" # 使用 v2 API 获取完整诗词 SENTENCE_API = "https://v2.jinrishici.com/one.json" DEFAULT_SENTENCE = """《苦笋》 赏花归去马如飞, 去马如飞酒力微, 酒力微醒时已暮, 醒时已暮赏花归。 —— 宋·苏轼""" TIMEZONE = "Asia/Shanghai" BIRTH_YEAR = 1989 # change it to your birth year def login(token): return Github(auth=Auth.Token(token)) def get_one_sentence(): """获取今天的一首诗 使用今日诗词 v2 API 获取完整的诗词内容 返回格式:《诗名》\n诗词内容\n\n—— 朝代·作者 """ try: r = requests.get(SENTENCE_API, timeout=10) if r.ok: data = r.json() # 获取诗词来源信息 origin = data.get("data", {}).get("origin", {}) title = origin.get("title", "") dynasty = origin.get("dynasty", "") author = origin.get("author", "") content_list = origin.get("content", []) if content_list and title and author: # 将诗词内容数组合并为字符串(每句一行) content = "\n".join(content_list) # 格式化输出:《诗名》\n内容\n\n—— 朝代·作者 poem = f"《{title}》\n{content}\n\n—— {dynasty}·{author}" return poem return DEFAULT_SENTENCE except Exception as e: print(f"get SENTENCE_API wrong: {e}") return DEFAULT_SENTENCE def _get_script_dir(): return os.path.dirname(os.path.abspath(__file__)) def _get_leetcode_daily_question(): """获取 LeetCode CN 每日一题 Returns: dict: 包含 id, title, slug, difficulty 的字典,失败返回 None """ try: url = "https://leetcode.cn/graphql/" headers = {"Content-Type": "application/json"} query = """ query questionOfToday { todayRecord { question { questionFrontendId title titleSlug difficulty isPaidOnly } } } """ response = requests.post( url, json={"query": query}, headers=headers, timeout=10 ) if response.ok: data = response.json() records = data.get("data", {}).get("todayRecord", []) if records: q = records[0].get("question", {}) if q and not q.get("isPaidOnly", False): return { "id": q.get("questionFrontendId", ""), "title": q.get("title", ""), "slug": q.get("titleSlug", ""), "difficulty": q.get( "difficulty", "" ).upper(), # EASY, MEDIUM, HARD } return None except Exception as e: print(f"Error getting daily question: {e}") return None def get_daily_leetcode(): try: script_dir = _get_script_dir() easy_file = os.path.join(script_dir, LEETCODE_EASY_FILE) used_file = os.path.join(script_dir, LEETCODE_USED_FILE) now = pendulum.now(TIMEZONE) used_slugs = set() if os.path.exists(used_file): with open(used_file, "r") as f: used_slugs = set(line.strip() for line in f if line.strip()) target_difficulty = "EASY" difficulty = "简单" difficulty_emoji = "🟢" hint = "" problem_file = easy_file daily_question = _get_leetcode_daily_question() use_daily = False if daily_question: if ( daily_question["difficulty"] == target_difficulty and daily_question["slug"] not in used_slugs ): use_daily = True problem_id = daily_question["id"] title = daily_question["title"] slug = daily_question["slug"] hint = "今日官方每日一题!" + (f" {hint}" if hint else "") if not use_daily: if not os.path.exists(problem_file): return "今日 LeetCode:题库文件不存在,请运行 fetch_leetcode.py 获取题目" with open(problem_file, "r") as f: problems = [line.strip() for line in f if line.strip()] available = [] for p in problems: parts = p.split("|") if len(parts) >= 3: slug = parts[2] if slug not in used_slugs: available.append(p) if not available: return f"今日 LeetCode:所有{difficulty}题都做完啦!🎉" day_seed = now.year * 1000 + now.day_of_year random.seed(day_seed) selected = random.choice(available) random.seed() parts = selected.split("|") problem_id = parts[0] title = parts[1] slug = parts[2] with open(used_file, "a") as f: f.write(f"{slug}\n") url = f"https://leetcode.cn/problems/{slug}/" header = f"今日 LeetCode {difficulty_emoji} {difficulty}题" if hint: header = f"{hint} {header}" return f"""{header}: [{problem_id}. {title}]({url})""" except Exception as e: print(f"Error getting daily leetcode: {e}") return "" def get_history_today(birth_year=BIRTH_YEAR, limit=2): try: now = pendulum.now(TIMEZONE) month = now.format("MM") day = now.format("DD") url = f"https://api.wikimedia.org/feed/v1/wikipedia/zh/onthisday/events/{month}/{day}" headers = {"User-Agent": "GetUpBot/1.0 (https://github.com/yihong0618/2026)"} response = requests.get(url, headers=headers, timeout=10) if not response.ok: print(f"Failed to get history today: {response.status_code}") return "" data = response.json() events = data.get("events", []) if not events: return "" current_year = now.year filtered_events = [ event for event in events if "year" in event and 1989 <= event["year"] <= current_year ] if not filtered_events: filtered_events = [e for e in events if "year" in e] if not filtered_events: return "" selected_events = random.sample( filtered_events, min(limit, len(filtered_events)) ) selected_events.sort(key=lambda x: x.get("year", 0), reverse=True) result_lines = ["历史上的今天:\n"] for event in selected_events: year = event.get("year") text = event.get("text", "") pages = event.get("pages", []) wiki_url = "" if pages and len(pages) > 0: content_urls = pages[0].get("content_urls", {}) desktop = content_urls.get("desktop", {}) wiki_url = desktop.get("page", "") if year and year >= birth_year: age = year - birth_year age_text = f"(那年我 {age} 岁)" elif year and year < birth_year: years_before = birth_year - year age_text = f"(我出生前 {years_before} 年)" else: age_text = "" text = text.replace("\n", " ").strip() text = convert(text, "zh-cn") # 繁体转简体 if wiki_url: result_lines.append(f"• {year}年:[{text}]({wiki_url}) {age_text}") else: result_lines.append(f"• {year}年:{text} {age_text}") return "\n".join(result_lines) except Exception: return "fail to get it" def get_running_distance(): try: url = "https://github.com/yihong0618/run/raw/refs/heads/master/run_page/data.parquet" response = requests.get(url) if not response.ok: return "" with tempfile.NamedTemporaryFile() as temp_file: temp_file.write(response.content) temp_file.flush() with duckdb.connect() as conn: now = pendulum.now(TIMEZONE) yesterday = now.subtract(days=1) month_start = now.start_of("month") year_start = now.start_of("year") yesterday_query = f""" SELECT COUNT(*) as count, ROUND(SUM(distance)/1000, 2) as total_km FROM read_parquet('{temp_file.name}') WHERE DATE(start_date_local) = '{yesterday.to_date_string()}' """ month_query = f""" SELECT COUNT(*) as count, ROUND(SUM(distance)/1000, 2) as total_km FROM read_parquet('{temp_file.name}') WHERE start_date_local >= '{month_start.to_date_string()}' AND start_date_local < '{now.add(days=1).to_date_string()}' """ year_query = f""" SELECT COUNT(*) as count, ROUND(SUM(distance)/1000, 2) as total_km FROM read_parquet('{temp_file.name}') WHERE start_date_local >= '{year_start.to_date_string()}' AND start_date_local < '{now.add(days=1).to_date_string()}' """ yesterday_result = conn.execute(yesterday_query).fetchone() month_result = conn.execute(month_query).fetchone() year_result = conn.execute(year_query).fetchone() running_info_parts = [] if yesterday_result and yesterday_result[0] > 0: running_info_parts.append(f"• 昨天跑了 {yesterday_result[1]} 公里") else: running_info_parts.append("• 昨天没跑") if month_result and month_result[0] > 0: running_info_parts.append(f"• 本月跑了 {month_result[1]} 公里") else: running_info_parts.append("• 本月没跑") if year_result and year_result[0] > 0: running_info_parts.append(f"• 今年跑了 {year_result[1]} 公里") else: running_info_parts.append("• 今年没跑") return "Run:\n\n" + "\n".join(running_info_parts) except Exception as e: print(f"Error getting running data: {e}") return "" return "" def get_day_of_year(): now = pendulum.now(TIMEZONE) return now.day_of_year def get_year_progress(): now = pendulum.now(TIMEZONE) day_of_year = now.day_of_year is_leap_year = now.year % 4 == 0 and (now.year % 100 != 0 or now.year % 400 == 0) total_days = 366 if is_leap_year else 365 progress_percent = (day_of_year / total_days) * 100 progress_bar_width = 20 filled_blocks = int((day_of_year / total_days) * progress_bar_width) empty_blocks = progress_bar_width - filled_blocks progress_bar = "█" * filled_blocks + "░" * empty_blocks return f"{progress_bar} {progress_percent:.1f}% ({day_of_year}/{total_days})" def get_today_get_up_status(issue): comments = list(issue.get_comments()) if not comments: return False latest_comment = comments[-1] now = pendulum.now(TIMEZONE) latest_day = pendulum.instance(latest_comment.created_at).in_timezone( "Asia/Shanghai" ) return latest_day.date() == now.date() def make_get_up_message(github_token): sentence = get_one_sentence() now = pendulum.now(TIMEZONE) # 3 - 9 means early for me # 3 means 我喝多了起来上厕所 is_get_up_early = 3 <= now.hour <= 9 try: sentence = get_one_sentence() print(f"Second: {sentence}") except Exception as e: print(str(e)) day_of_year = get_day_of_year() year_progress = get_year_progress() running_info = get_running_distance() history_today = get_history_today() leetcode = get_daily_leetcode() return ( sentence, is_get_up_early, day_of_year, year_progress, running_info, history_today, leetcode, ) def main( github_token, repo_name, tele_token, tele_chat_id, ): u = login(github_token) repo = u.get_repo(repo_name) issue = repo.get_issue(GET_UP_ISSUE_NUMBER) is_today = get_today_get_up_status(issue) if is_today: print("Today I have recorded the wake up time") return ( sentence, is_get_up_early, day_of_year, year_progress, running_info, history_today, leetcode, ) = make_get_up_message(github_token) get_up_time = pendulum.now(TIMEZONE).to_datetime_string() body = GET_UP_MESSAGE_TEMPLATE.format( get_up_time=get_up_time, sentence=sentence, day_of_year=day_of_year, year_progress=year_progress, running_info=running_info, history_today=history_today, leetcode=leetcode, ) if is_get_up_early: if tele_token and tele_chat_id: bot = telebot.TeleBot(tele_token) try: formatted_body = markdownify(body) bot.send_message( tele_chat_id, formatted_body, parse_mode="MarkdownV2", disable_notification=True, ) except Exception as e: print(str(e)) issue.create_comment(body) else: print("You wake up late") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("github_token", help="github_token") parser.add_argument("repo_name", help="repo_name") parser.add_argument( "--weather_message", help="weather_message", nargs="?", default="", const="" ) parser.add_argument( "--tele_token", help="tele_token", nargs="?", default="", const="" ) parser.add_argument( "--tele_chat_id", help="tele_chat_id", nargs="?", default="", const="" ) options = parser.parse_args() main( options.github_token, options.repo_name, options.tele_token, options.tele_chat_id, )
yihong0618/2026
11
2026
Python
yihong0618
yihong
apache
test_daily_message.py
Python
#!/usr/bin/env python3 """测试每天生成的完整起床消息""" import os import sys import pendulum # 导入 get_up.py 中的函数 sys.path.insert(0, os.path.dirname(__file__)) from get_up import ( GET_UP_MESSAGE_TEMPLATE, TIMEZONE, get_one_sentence, get_day_of_year, get_year_progress, get_running_distance, get_history_today, get_daily_leetcode, make_get_up_message, ) def test_full_message(): """测试完整的起床消息""" print("=" * 60) print("测试每天生成的起床消息") print("=" * 60) print() # 使用 None 作为 github_token(因为我们已经移除了 GitHub 动态) ( sentence, is_get_up_early, day_of_year, year_progress, running_info, history_today, leetcode, ) = make_get_up_message(None) get_up_time = pendulum.now(TIMEZONE).to_datetime_string() body = GET_UP_MESSAGE_TEMPLATE.format( get_up_time=get_up_time, sentence=sentence, day_of_year=day_of_year, year_progress=year_progress, running_info=running_info, history_today=history_today, leetcode=leetcode, ) print(body) print() print("=" * 60) print(f"是否早起: {'是' if is_get_up_early else '否'}") print("=" * 60) def test_individual_components(): """测试各个组件""" print("\n" + "=" * 60) print("测试各个组件") print("=" * 60) print() print("📅 今年的第几天:") print(f" {get_day_of_year()}") print() print("📊 年度进度:") print(f" {get_year_progress()}") print() print("🏃 跑步信息:") running = get_running_distance() if running: print(f" {running}") else: print(" 无法获取跑步数据") print() print("📜 历史上的今天:") history = get_history_today() if history: print(f" {history}") else: print(" 无法获取历史事件") print() print("� 今日 LeetCode:") leetcode = get_daily_leetcode() if leetcode: print(f" {leetcode}") else: print(" 无法获取 LeetCode 题目") print() print("�📖 每日一诗:") sentence = get_one_sentence() print(f" {sentence}") print() if __name__ == "__main__": test_full_message() test_individual_components()
yihong0618/2026
11
2026
Python
yihong0618
yihong
apache
src/rogvibe/__init__.py
Python
"""Rogvibe - A terminal-based viber selection tool.""" from __future__ import annotations from .app import DEFAULT_PARTICIPANTS, LotteryApp, SlotMachineApp, run, run_slot_machine from .models import SpinFinished, SpinTick from .widgets import LotteryWheel __all__ = [ "DEFAULT_PARTICIPANTS", "LotteryApp", "SlotMachineApp", "LotteryWheel", "SpinFinished", "SpinTick", "run", "run_slot_machine", ]
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
src/rogvibe/__main__.py
Python
"""Command-line interface for rogvibe.""" from __future__ import annotations import sys from typing import Sequence from .app import run, run_flip_card, run_slot_machine def main(argv: Sequence[str] | None = None) -> None: """CLI entrypoint invoked via `python -m rogvibe` or project scripts.""" args = list(argv) if argv is not None else sys.argv[1:] # Check if --slot mode is requested if args and args[0] == "--slot": run_slot_machine() # Check if --flip mode is requested elif args and args[0] == "--flip": run_flip_card() else: run(args or None) if __name__ == "__main__": main()
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
src/rogvibe/app.py
Python
"""Main entry point and public API for rogvibe.""" from __future__ import annotations from typing import Iterable from .apps import FlipCardApp, LotteryApp, SlotMachineApp from .constants import FALLBACK_DEFAULTS from .utils import detect_default_participants # Prefer detected providers, otherwise fall back to sample names. DEFAULT_PARTICIPANTS: list[str] = detect_default_participants() or FALLBACK_DEFAULTS __all__ = [ "run", "run_slot_machine", "run_flip_card", "LotteryApp", "SlotMachineApp", "FlipCardApp", "DEFAULT_PARTICIPANTS", ] def run(participants: Iterable[str] | None = None) -> None: """Launch the Textual app with the provided participants.""" normalized = ( [name.strip() for name in participants if name.strip()] if participants else [] ) names = normalized or list(DEFAULT_PARTICIPANTS) app = LotteryApp(names) app.run() def run_slot_machine() -> None: """Launch the slot machine app.""" app = SlotMachineApp() app.run() def run_flip_card() -> None: """Launch the flip card game app.""" app = FlipCardApp() app.run()
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
src/rogvibe/apps/__init__.py
Python
"""Application classes for rogvibe.""" from __future__ import annotations from .flip_card_app import FlipCardApp from .lottery_app import LotteryApp from .slot_machine_app import SlotMachineApp __all__ = [ "LotteryApp", "SlotMachineApp", "FlipCardApp", ]
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
src/rogvibe/apps/flip_card_app.py
Python
"""Flip card game application.""" from __future__ import annotations from typing import Any from rich.text import Text from textual.app import App, ComposeResult from textual.containers import Vertical from textual.widgets import Footer, Static from ..models.messages import AllCardsMatched, PairMatched from ..utils.detector import detect_default_participants from ..utils.executor import execute_command from ..widgets.flip_card import FlipCardGrid class FlipCardApp(App): """Flip card matching game app.""" CSS = """ Screen { align: center middle; background: #1b1e28; } #layout { width: 100%; height: auto; align: center middle; padding: 1 2; border: tall #3f6fb5; } #instructions { content-align: center middle; text-style: bold; margin-bottom: 1; } FlipCardGrid { width: 100%; height: auto; } #card_grid { grid-size: 4; grid-gutter: 1 2; } Card { width: 18; height: 7; border: heavy #3f6fb5; content-align: center middle; text-style: bold; } Card.flipped { border: heavy yellow; background: #2a2d3a; } Card.matched { border: heavy green; background: #1f4d1f; } Card:hover { border: heavy cyan; } #result { height: auto; content-align: center middle; margin-top: 1; color: #ffcc66; text-style: bold; } #celebration { height: 8; width: 100%; content-align: center middle; margin-top: 1; } """ BINDINGS = [ ("r", "reset", "Reset"), ("enter", "execute", "Run"), ("q", "quit", "Quit"), ] def __init__(self) -> None: super().__init__() # Get participants from detector participants = detect_default_participants() if not participants or len(participants) < 8: # Need exactly 8 items for 4x4 grid (each appears twice) participants = [ "kimi", "claude", "cursor", "code", "gemini", "amp", "lucky", "handy", ] # Take only first 8 self._participants = participants[:8] self._grid = FlipCardGrid(self._participants) self._result = Static(id="result") self._celebration_display = Static(id="celebration") self._pending_command: str | None = None self._celebration_timer: Any | None = None self._celebration_frame = 0 def compose(self) -> ComposeResult: with Vertical(id="layout"): yield Static( "🃏 Click cards to flip! Match pairs to win.", id="instructions", ) yield self._grid yield self._celebration_display yield self._result yield Footer() def action_reset(self) -> None: """Reset the game.""" self._grid.reset() self._result.update("") self._celebration_display.update("") self._pending_command = None if self._celebration_timer: self._celebration_timer.stop() self._celebration_timer = None def _animate_celebration(self) -> None: """Animate celebration when all cards are matched.""" celebration_frames = [ # Frame 0 """ 🎉 🎊 🎉 ✨ 🌟 ⭐ 🌟 ✨ 🎉 🎊 🎉 """, # Frame 1 """ ⭐ ✨ 🌟 ✨ ⭐ 🎊 🎉 🎊 ⭐ ✨ 🌟 ✨ ⭐ """, # Frame 2 """ 🌟 ⭐ 🌟 🎉 ✨ 💫 ✨ 🎉 🌟 ⭐ 🌟 """, # Frame 3 """ 💫 🎊 ⭐ 🎊 💫 ✨ 🎉 ✨ 💫 🎊 ⭐ 🎊 💫 """, ] from ..constants import ANIMATION_COLORS frame_text = celebration_frames[ self._celebration_frame % len(celebration_frames) ] text = Text(frame_text, justify="center") color = ANIMATION_COLORS[self._celebration_frame % len(ANIMATION_COLORS)] text.stylize(f"bold {color}") self._celebration_display.update(text) self._celebration_frame += 1 if self._celebration_frame < 16: self._celebration_timer = self.set_timer(0.15, self._animate_celebration) else: self._celebration_display.update("") def on_all_cards_matched(self, message: AllCardsMatched) -> None: """Handle all cards matched event.""" winner = message.winner self._pending_command = winner # Start celebration animation self._celebration_frame = 0 self._animate_celebration() self._result.update( f"🎉🎉🎉 All cards matched! Winner: {winner} 🎉🎉🎉\n" f"↩️ Press Enter to run '{winner}' and exit, or R to play again, or q to quit." ) def on_pair_matched(self, message: PairMatched) -> None: """Handle a pair matched event.""" value = message.value self._pending_command = value self._result.update( f"✨ Pair matched: {value}!\n" f"↩️ Press Enter to run '{value}' and exit, or continue playing." ) def action_execute(self) -> None: """Execute the winner command.""" if not self._pending_command: return # Don't execute special participants like "lucky" and "handy" from ..constants import SPECIAL_PARTICIPANTS if self._pending_command in SPECIAL_PARTICIPANTS: return execute_command(self._pending_command, self)
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
src/rogvibe/apps/lottery_app.py
Python
"""Lottery wheel application.""" from __future__ import annotations from typing import Any, Sequence from rich.text import Text from textual.app import App, ComposeResult from textual.containers import Vertical from textual.widgets import Footer, Static from ..constants import SPECIAL_PARTICIPANTS from ..models.messages import SpinFinished, SpinTick from ..utils.executor import execute_command from ..widgets.lottery_wheel import LotteryWheel class LotteryApp(App): """App wiring the wheel and some helper text together.""" CSS = """ Screen { align: center middle; background: #1b1e28; } #layout { width: auto; align: center middle; padding: 1 4; border: tall #3f6fb5; } #instructions { content-align: center middle; text-style: bold; } #warning { color: #ffcc66; text-style: italic; margin-top: 1; } #result { height: auto; content-align: center middle; margin-top: 1; } """ BINDINGS = [ ("space", "spin", "Spin"), ("enter", "execute", "Run"), ("q", "quit", "Quit"), ] def __init__(self, participants: Sequence[str]) -> None: super().__init__() self._participants = list(participants) self._wheel = LotteryWheel(self._participants) self._result = Static(id="result") self._pending_command: str | None = None self._celebration_timer: Any | None = None self._celebration_frame = 0 def compose(self) -> ComposeResult: with Vertical(id="layout"): # Check if all participants are "handy" if all(p == "handy" for p in self._participants): instruction_text = "✍️ You're a hero who hand-writes the code. Press Space to spin; press q to quit." else: instruction_text = "Press Space to spin; press Enter to run the viber; press q to quit." yield Static( instruction_text, id="instructions", ) if self._wheel.truncated: yield Static( f"⚠️ Showing only the first {self._wheel.visible_capacity} names; the remaining {self._wheel.extra_count} are ignored.", id="warning", ) yield self._wheel yield self._result yield Footer() def action_spin(self) -> None: if not self._wheel.is_spinning: self._pending_command = None # Stop any ongoing celebration animation if self._celebration_timer: self._celebration_timer.stop() self._celebration_timer = None # Reset wheel border color self._wheel.celebration_border_color = "yellow" self._result.update("🎲 Spinning...") self._wheel.start_spin() def on_spin_tick(self, message: SpinTick) -> None: """Update the spinning message with animated dice.""" dice_emoji_map = {"⚀": "⚀", "⚁": "⚁", "⚂": "⚂", "⚃": "⚃", "⚄": "⚄", "⚅": "⚅"} dice_display = dice_emoji_map.get(message.dice_face, "🎲") self._result.update(f"{dice_display} Spinning...") def _animate_celebration(self) -> None: """Animate celebration for lucky/handy/claude winners.""" from ..constants import BORDER_COLORS, CELEBRATION_EMOJIS, ANIMATION_COLORS # Cycle through different emojis and colors emoji = CELEBRATION_EMOJIS[self._celebration_frame % len(CELEBRATION_EMOJIS)] # Update wheel border color to flash border_color = BORDER_COLORS[self._celebration_frame % len(BORDER_COLORS)] self._wheel.celebration_border_color = border_color # Create animated text with changing colors current_winner = self._pending_command or "winner" if current_winner == "handy": base_text = f"{emoji} viber: {current_winner} {emoji}\n✍️ You're a hero who hand-writes the code. Press Space to spin again, or q to quit." elif current_winner == "lucky": base_text = f"{emoji} viber: {current_winner} {emoji}\n🍀 Lucky winner! Press Space to spin again, or q to quit." elif current_winner == "claude": base_text = f"{emoji} viber: {current_winner} {emoji}\n🤖 AI Assistant! Press Space to spin again, or q to quit." else: base_text = f"{emoji} viber: {current_winner} {emoji}\n🎉 Special winner! Press Space to spin again, or q to quit." text = Text(base_text) color = ANIMATION_COLORS[self._celebration_frame % len(ANIMATION_COLORS)] # Apply color to the emoji parts text.stylize(f"bold {color}", 0, len(emoji)) self._result.update(text) self._celebration_frame += 1 # Continue animation for 15 frames (~1.5 seconds) if self._celebration_frame < 15: self._celebration_timer = self.set_timer(0.1, self._animate_celebration) else: # Animation done, reset border color and show final message self._wheel.celebration_border_color = "yellow" if current_winner == "handy": if all(p == "handy" for p in self._participants): final_text = f"🎉 viber: {current_winner}\n✍️ You're a hero who hand-writes the code. Press Space to spin again, or q to quit." else: final_text = f"🎉 viber: {current_winner}\n✍️ You're a hero who hand-writes the code. Press Space to spin again, or q to quit." elif current_winner == "lucky": final_text = f"🎉 viber: {current_winner}\n🍀 Lucky winner! Press Space to spin again, or q to quit." elif current_winner == "claude": final_text = f"🎉 viber: {current_winner}\n🤖 AI Assistant! Press Space to spin again, or q to quit." else: final_text = f"🎉 viber: {current_winner}\n🎉 Special winner! Press Space to spin again, or q to quit." self._result.update(final_text) def on_spin_finished(self, message: SpinFinished) -> None: self._pending_command = message.winner # If it's "lucky" or "handy" or "claude", don't allow command execution, but show animation if message.winner in SPECIAL_PARTICIPANTS: # Start celebration animation self._celebration_frame = 0 self._animate_celebration() else: self._result.update( f"🎉 viber: {message.winner}\n↩️ Press Enter to run and exit, or q to quit." ) def action_execute(self) -> None: if not self._pending_command: return if self._pending_command in ("lucky", "handy"): return execute_command(self._pending_command, self)
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
src/rogvibe/apps/slot_machine_app.py
Python
"""Slot machine application.""" from __future__ import annotations from collections import Counter from typing import Any from rich.text import Text from textual.app import App, ComposeResult from textual.containers import Vertical from textual.widgets import Footer, Static from ..models.messages import SlotAllStopped from ..utils.executor import execute_command from ..widgets.slot_machine import SlotMachineWidget class SlotMachineApp(App): """Slot machine app.""" CSS = """ Screen { align: center middle; background: #1b1e28; } #layout { width: auto; align: center middle; padding: 1 4; border: tall #3f6fb5; } #instructions { content-align: center middle; text-style: bold; margin-bottom: 1; } #result { height: auto; content-align: center middle; margin-top: 1; color: #ffcc66; text-style: bold; } #fireworks { height: 15; width: 100%; content-align: center middle; margin-top: 1; } """ BINDINGS = [ ("space", "spin", "Pull Lever"), ("enter", "execute", "Run"), ("q", "quit", "Quit"), ] def __init__(self) -> None: super().__init__() self._slot_machine = SlotMachineWidget() self._result = Static(id="result") self._fireworks_display = Static(id="fireworks") self._pending_command: str | None = None self._fireworks_timer: Any | None = None self._fireworks_frame = 0 def compose(self) -> ComposeResult: with Vertical(id="layout"): yield Static( "🎰 Press Space to pull the lever; press Enter to run the viber; press q to quit.", id="instructions", ) yield self._slot_machine yield self._fireworks_display yield self._result yield Footer() def action_spin(self) -> None: """Handle spin action.""" if not self._slot_machine.is_spinning: self._pending_command = None # Stop any ongoing fireworks if self._fireworks_timer: self._fireworks_timer.stop() self._fireworks_timer = None self._fireworks_display.update("") # Reset reel colors when starting a new spin for reel in self._slot_machine._reels: reel.styles.border = ("double", "ansi_bright_magenta") self._result.update("Pulling lever...") self._slot_machine.start_spin() def _animate_fireworks(self) -> None: """Animate fireworks display frame by frame.""" fireworks_frames = [ # Frame 0 - Initial burst """ * * * * * * * * """, # Frame 1 - Expanding """ * * * * * * * * * * """, # Frame 2 - Peak explosion """ * ✦ ✦ * * ✦ ★ ★ ✦ * * ✦ ★ ✦ ★ ✦ * * ✦ ★ ★ ✦ * * ✦ ✦ * """, # Frame 3 - Sparkling """ ✦ * ✦ * ★ ✦ ★ * ✦ ★ ✦ ★ ✦ * ★ ✦ ★ * ✦ * ✦ """, # Frame 4 - Fading """ · · · · · · · · · """, # Frame 5 - Multiple bursts """ * ✦ ✦ * ★ * ★ ✦ ✦ ✦ ★ * ★ * ✦ ✦ * """, # Frame 6 - Grand finale """ ★ ✦ * ✦ * ✦ ★ * ★ ✦ ★ * ✦ ★ ✦ ★ ✦ ★ ✦ * ★ ✦ ★ * ★ ✦ * ✦ * ✦ ★ """, # Frame 7 - Sparkles """ · ✦ · ✦ ★ ✦ · ✦ · ✦ · ✦ ★ ✦ · ✦ · """, ] # Apply colors to make it more vibrant - use valid Rich color names from ..constants import ANIMATION_COLORS frame_text = fireworks_frames[self._fireworks_frame % len(fireworks_frames)] # Create colored text text = Text(frame_text, justify="center") color = ANIMATION_COLORS[self._fireworks_frame % len(ANIMATION_COLORS)] text.stylize(color) self._fireworks_display.update(text) # Make slot borders flash with different colors border_colors = [ "yellow", "ansi_bright_red", "ansi_bright_magenta", "ansi_bright_cyan", "ansi_bright_yellow", ] border_styles = ["heavy", "double", "heavy", "double"] border_color = border_colors[self._fireworks_frame % len(border_colors)] border_style = border_styles[self._fireworks_frame % len(border_styles)] for reel in self._slot_machine._reels: reel.styles.border = (border_style, border_color) self._fireworks_frame += 1 # Continue animation for a while (20 frames = ~2 seconds) if self._fireworks_frame < 20: self._fireworks_timer = self.set_timer(0.1, self._animate_fireworks) else: # Animation done, clear display and reset borders self._fireworks_display.update("") for reel in self._slot_machine._reels: reel.styles.border = ("heavy", "yellow") def on_slot_all_stopped(self, message: SlotAllStopped) -> None: """Handle all reels stopped.""" results = message.results # Count occurrences of each result counts = Counter(results) # Check if all three are the same - JACKPOT! if len(set(results)) == 1: winner = results[0] self._pending_command = winner # Highlight all reels with yellow color for JACKPOT for reel in self._slot_machine._reels: reel.styles.border = ("heavy", "yellow") # Start fireworks animation! self._fireworks_frame = 0 self._animate_fireworks() self._result.update( f"🎉🎉🎉 JACKPOT! All three show: {winner} 🎉🎉🎉\n" f"↩️ Press Enter to run '{winner}' and exit, or q to quit." ) # Check if two are the same elif max(counts.values()) == 2: # Find the value that appears twice winner = [item for item, count in counts.items() if count == 2][0] self._pending_command = winner # Highlight matching reels for i, reel in enumerate(self._slot_machine._reels): if results[i] == winner: reel.styles.border = ("heavy", "yellow") else: reel.styles.border = ("double", "ansi_bright_magenta") result_text = " | ".join(results) self._result.update( f"✨ Two match: {winner}! Results: {result_text}\n" f"↩️ Press Enter to run '{winner}' and exit, or q to quit." ) else: # All different - no match # Reset reel colors for reel in self._slot_machine._reels: reel.styles.border = ("double", "ansi_bright_magenta") result_text = " | ".join(results) self._result.update( f"Results: {result_text}\n" f"🔄 Press Space to spin again, or q to quit." ) def action_execute(self) -> None: """Execute the winner command.""" if not self._pending_command: return # Don't execute special participants like "lucky" and "handy" from ..constants import SPECIAL_PARTICIPANTS if self._pending_command in SPECIAL_PARTICIPANTS: return execute_command(self._pending_command, self)
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
src/rogvibe/config.py
Python
"""Deprecated: Configuration has been moved to constants.py""" from __future__ import annotations from .constants import MAYBE_VIBER __all__ = ["MAYBE_VIBER"]
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
src/rogvibe/constants.py
Python
"""Constants and configuration for rogvibe.""" from __future__ import annotations # Fallback participant names FALLBACK_DEFAULTS: list[str] = [ "handy", "handy", "handy", "handy", ] # List of potential viber commands to detect on the system # add more here PR welcome MAYBE_VIBER: list[str] = [ "kimi", "claude", "gemini", "codex", "code", "cursor", "amp", "opencode", ] # Animation settings ANIMATION_COLORS: list[str] = ["yellow", "red", "magenta", "cyan", "white"] BORDER_COLORS: list[str] = ["yellow", "red", "magenta", "cyan", "green"] CELEBRATION_EMOJIS: list[str] = ["✨", "🌟", "⭐", "💫", "🎉", "🎊", "🎈"] # Dice faces DICE_FACES: list[str] = ["⚀", "⚁", "⚂", "⚃", "⚄", "⚅"] DICE_EMOJI: str = "🎲" TARGET_EMOJI: str = "🎯" # Special participants SPECIAL_PARTICIPANTS: set[str] = {"lucky", "handy"}
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
src/rogvibe/models/__init__.py
Python
"""Message models for rogvibe.""" from __future__ import annotations from .messages import ( SlotAllStopped, SlotReelSpinning, SlotReelStopped, SpinFinished, SpinTick, ) __all__ = [ "SpinFinished", "SpinTick", "SlotReelSpinning", "SlotReelStopped", "SlotAllStopped", ]
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
src/rogvibe/models/messages.py
Python
"""Message classes for widget communication.""" from __future__ import annotations from textual.message import Message from textual.widget import Widget class SpinFinished(Message): """Fired when the wheel stops spinning.""" def __init__(self, sender: Widget, winner: str) -> None: try: super().__init__(sender) # type: ignore[arg-type] # Textual <=0.43 expects the sender argument. except TypeError: super().__init__() # Newer Textual versions no longer take sender. self._origin = sender self.winner = winner @property def origin(self) -> Widget: """Widget that emitted the message.""" return self._origin class SpinTick(Message): """Fired each time the wheel advances during spinning.""" def __init__(self, sender: Widget, dice_face: str) -> None: try: super().__init__(sender) # type: ignore[arg-type] except TypeError: super().__init__() self._origin = sender self.dice_face = dice_face @property def origin(self) -> Widget: """Widget that emitted the message.""" return self._origin class SlotReelSpinning(Message): """Fired when a reel is spinning.""" def __init__(self, sender: Widget, reel_index: int, value: str) -> None: try: super().__init__(sender) # type: ignore[arg-type] except TypeError: super().__init__() self._origin = sender self.reel_index = reel_index self.value = value @property def origin(self) -> Widget: """Widget that emitted the message.""" return self._origin class SlotReelStopped(Message): """Fired when a reel stops spinning.""" def __init__(self, sender: Widget, reel_index: int, value: str) -> None: try: super().__init__(sender) # type: ignore[arg-type] except TypeError: super().__init__() self._origin = sender self.reel_index = reel_index self.value = value @property def origin(self) -> Widget: """Widget that emitted the message.""" return self._origin class SlotAllStopped(Message): """Fired when all reels have stopped.""" def __init__(self, sender: Widget, results: list[str]) -> None: try: super().__init__(sender) # type: ignore[arg-type] except TypeError: super().__init__() self._origin = sender self.results = results @property def origin(self) -> Widget: """Widget that emitted the message.""" return self._origin class AllCardsMatched(Message): """Fired when all cards are matched in the flip card game.""" def __init__(self, sender: Widget, winner: str) -> None: try: super().__init__(sender) # type: ignore[arg-type] except TypeError: super().__init__() self._origin = sender self.winner = winner @property def origin(self) -> Widget: """Widget that emitted the message.""" return self._origin class PairMatched(Message): """Fired when a pair of cards is matched in the flip card game.""" def __init__(self, sender: Widget, value: str) -> None: try: super().__init__(sender) # type: ignore[arg-type] except TypeError: super().__init__() self._origin = sender self.value = value @property def origin(self) -> Widget: """Widget that emitted the message.""" return self._origin
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
src/rogvibe/utils/__init__.py
Python
"""Utility functions for rogvibe.""" from __future__ import annotations from .detector import detect_default_participants from .executor import execute_command __all__ = [ "detect_default_participants", "execute_command", ]
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
src/rogvibe/utils/detector.py
Python
"""Participant detection utilities.""" from __future__ import annotations import random import shutil from ..constants import MAYBE_VIBER def detect_default_participants() -> list[str]: """Detect available viber commands on the system. Returns: List of detected providers, shuffled and padded to appropriate size. Returns empty list if none found. """ providers: list[str] = [] fillers = ["lucky", "handy"] def on_path(cmd: str) -> bool: result = shutil.which(cmd) is not None print(f"DEBUG: on_path('{cmd}') -> {result}") return result for provider in MAYBE_VIBER: if on_path(provider): providers.append(provider) print(f"DEBUG: Initial providers: {providers}, length: {len(providers)}") if len(providers) == 0: return [] random.shuffle(providers) print(f"DEBUG: After shuffle: {providers}") if len(providers) < 4: filler_index_less = 0 while len(providers) < 4: providers.append(fillers[filler_index_less % 2]) filler_index_less += 1 print(f"DEBUG: After padding to 4: {providers}") elif 5 <= len(providers) < 8: filler_index = 0 while len(providers) < 8: providers.append(fillers[filler_index % 2]) filler_index += 1 print(f"DEBUG: After padding to 8: {providers}") elif len(providers) > 8: providers = random.sample(providers, 8) print(f"DEBUG: After sampling to 8: {providers}") print(f"DEBUG: Final result: {providers}, length: {len(providers)}") return providers
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
src/rogvibe/utils/executor.py
Python
"""Command execution utilities.""" from __future__ import annotations import os import shlex import shutil import sys from contextlib import nullcontext from typing import Any def execute_command(winner: str, app: Any) -> None: """Execute the winner as a command and exit the app. Args: winner: The command to execute app: The Textual app instance (for suspend and exit) - Parses the winner string with shlex to support simple arguments. - If command is not on PATH, exits with code 127. - On success, replaces the current process using os.execvp. """ # if is code or cursor, automatically add '.' argument if winner in ("code", "cursor"): winner = f"{winner} ." argv = shlex.split(winner) if not argv: app.exit(0) return cmd = argv[0] if shutil.which(cmd) is None: print(f"[rogvibe] Command not found: {cmd}") app.exit(127) return # Replace current process with the chosen command. # Use Textual's suspend() to restore terminal state before exec. ctx = app.suspend() if hasattr(app, "suspend") else nullcontext() try: with ctx: os.execvp(cmd, argv) except FileNotFoundError: print(f"[rogvibe] Command not found: {cmd}", file=sys.stderr) app.exit(127) except PermissionError: print(f"[rogvibe] Permission denied: {cmd}", file=sys.stderr) app.exit(126) except OSError as e: print(f"[rogvibe] Failed to exec '{cmd}': {e}", file=sys.stderr) app.exit(1)
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
src/rogvibe/widgets/__init__.py
Python
"""UI widgets for rogvibe.""" from __future__ import annotations from .flip_card import Card, FlipCardGrid from .lottery_wheel import LotteryWheel from .slot_machine import SlotMachineLever, SlotMachineReel, SlotMachineWidget __all__ = [ "LotteryWheel", "SlotMachineReel", "SlotMachineLever", "SlotMachineWidget", "Card", "FlipCardGrid", ]
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
src/rogvibe/widgets/flip_card.py
Python
"""Flip card game widget.""" from __future__ import annotations from textual.app import ComposeResult from textual.containers import Grid from textual.message import Message from textual.widget import Widget from textual.widgets import Static class Card(Static): """A single card widget.""" def __init__(self, value: str, card_id: int) -> None: super().__init__() self.value = value self.card_id = card_id self.is_flipped = False self.is_matched = False self._update_display() def _update_display(self) -> None: """Update the card display based on its state.""" if self.is_matched: self.remove_class("flipped") self.add_class("matched") self.update(f"✓ {self.value} ✓") elif self.is_flipped: self.add_class("flipped") self.update(self.value) else: self.remove_class("flipped") self.remove_class("matched") # Card back design - simple centered question mark self.update("?") def flip(self) -> None: """Flip the card to show its value.""" if not self.is_matched: self.is_flipped = True self._update_display() def unflip(self) -> None: """Flip the card back to hide its value.""" if not self.is_matched: self.is_flipped = False self._update_display() def mark_matched(self) -> None: """Mark the card as matched.""" self.is_matched = True self.is_flipped = True self._update_display() async def on_click(self) -> None: """Handle card click.""" if not self.is_matched and not self.is_flipped: # Notify parent to handle the flip self.post_message(CardClicked(self, self)) class CardClicked(Message): """Message sent when a card is clicked.""" def __init__(self, sender: Widget, card: Card) -> None: try: super().__init__(sender) # type: ignore[arg-type] except TypeError: super().__init__() self._origin = sender self.card = card @property def origin(self) -> Widget: """Widget that emitted the message.""" return self._origin class FlipCardGrid(Grid): """A 4x4 grid of flip cards.""" def __init__(self, participants: list[str]) -> None: super().__init__(id="card_grid") self.participants = participants # Create pairs - each participant appears twice self.values = participants + participants # Shuffle the values import random random.shuffle(self.values) self.cards: list[Card] = [] self.flipped_cards: list[Card] = [] self.matched_count = 0 def compose(self) -> ComposeResult: """Compose the grid of cards.""" for i, value in enumerate(self.values): card = Card(value, i) self.cards.append(card) yield card async def on_card_clicked(self, event: CardClicked) -> None: """Handle card clicks.""" await self.flip_card(event.card) async def flip_card(self, card: Card) -> None: """Flip a card and check for matches.""" # If we already have 2 flipped cards that don't match, flip them back immediately if len(self.flipped_cards) >= 2: # Cancel any pending timer and flip back immediately self._unflip_cards() card.flip() self.flipped_cards.append(card) # Check if we have two cards flipped if len(self.flipped_cards) == 2: card1, card2 = self.flipped_cards if card1.value == card2.value: # Match found! card1.mark_matched() card2.mark_matched() self.matched_count += 2 self.flipped_cards = [] # Post a message if all cards are matched if self.matched_count == len(self.cards): from ..models.messages import AllCardsMatched self.post_message(AllCardsMatched(self, card1.value)) else: # Post a message for pair matched from ..models.messages import PairMatched self.post_message(PairMatched(self, card1.value)) else: # No match - flip back after a delay self.set_timer(1.0, lambda: self._unflip_cards()) def _unflip_cards(self) -> None: """Unflip the currently flipped cards.""" for card in self.flipped_cards: card.unflip() self.flipped_cards = [] def reset(self) -> None: """Reset the game.""" import random random.shuffle(self.values) self.matched_count = 0 self.flipped_cards = [] for i, card in enumerate(self.cards): card.value = self.values[i] card.is_flipped = False card.is_matched = False card._update_display()
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
src/rogvibe/widgets/lottery_wheel.py
Python
"""Lottery wheel widget.""" from __future__ import annotations import random from typing import Any, Sequence from rich import box from rich.align import Align from rich.panel import Panel from rich.table import Table from rich.text import Text from textual.reactive import reactive from textual.widget import Widget from ..constants import DICE_EMOJI, DICE_FACES, TARGET_EMOJI from ..models.messages import SpinFinished, SpinTick class LotteryWheel(Widget): """Simple wheel that highlights one participant at a time. Layout auto-adjusts by participant count with a minimum of 4: - 4 or fewer (but >=4): 2x2 grid (4 visible slots) - 5 to 8: 3x3 grid with a bullseye center (8 visible slots) """ DEFAULT_CSS = """ LotteryWheel { width: 50; height: auto; } """ current_index = reactive(0) current_dice = reactive("🎯") celebration_border_color = reactive("yellow") # For flashing animation def __init__(self, participants: Sequence[str]) -> None: if not participants or len(participants) < 4: raise ValueError("Provide at least 4 participants.") super().__init__() # Determine grid size and visible capacity self._grid_size = 2 if len(participants) <= 4 else 3 self._capacity = 4 if self._grid_size == 2 else 8 self._cell_width = 12 if self._grid_size == 2 else 14 limited = list(participants[: self._capacity]) self._participants = limited self._participant_count = len(self._participants) extra = len(participants) - len(self._participants) self._truncated = extra > 0 if self._truncated: self._extra_count = extra # Slot indices around the perimeter in clockwise order self._layout_slots: list[int | None] = [ idx if idx < self._participant_count else None for idx in range(self._capacity) ] self._is_spinning = False self._steps_remaining = 0 self._initial_steps = 0 self._delay = 0.08 self._timer: Any | None = None self._dice_faces = DICE_FACES self._emoji_dice = DICE_EMOJI def on_mount(self) -> None: """Adjust width for nicer layout depending on grid size.""" # Narrower width for 2x2 so it doesn't look sparse self.styles.width = 36 if self._grid_size == 2 else 50 def render(self) -> Panel: """Render participants in a faux wheel layout.""" table = Table.grid(expand=False, padding=(0, 2)) if self._grid_size == 2: # 2x2 grid: slots arranged clockwise table.add_row(self._render_cell(0), self._render_cell(1)) table.add_row(self._render_cell(3), self._render_cell(2)) else: # 3x3 grid: perimeter slots with bullseye center table.add_row( self._render_cell(0), self._render_cell(1), self._render_cell(2) ) table.add_row( self._render_cell(7), Panel( Text(self.current_dice, justify="center"), box=box.MINIMAL, padding=(0, 2), ), self._render_cell(3), ) table.add_row( self._render_cell(6), self._render_cell(5), self._render_cell(4) ) return Panel( Align.center(table), title="Rogvibe", border_style="bright_cyan", box=box.ROUNDED, ) def _render_cell(self, slot_index: int) -> Panel: participant_index = self._layout_slots[slot_index] if participant_index is None: return Panel( "", box=box.SQUARE, width=self._cell_width, padding=(0, 1), border_style="dim", ) participant = self._participants[participant_index] label = Text(participant, justify="center", overflow="ellipsis") highlight = participant_index == self.current_index # Use celebration_border_color for highlighted cell border = self.celebration_border_color if highlight else "dark_cyan" style = "black on yellow" if highlight else "white on dark_blue" label.stylize(style) return Panel( label, box=box.SQUARE, width=self._cell_width, padding=(0, 1), border_style=border, ) def start_spin(self) -> None: if self._is_spinning: return self._is_spinning = True self.current_dice = DICE_EMOJI self._initial_steps = random.randint( self._participant_count * 4, self._participant_count * 7 ) target_index = random.randrange(self._participant_count) offset = (target_index - self.current_index) % self._participant_count self._steps_remaining = self._initial_steps + offset self._delay = 0.05 self._schedule_tick() def _schedule_tick(self) -> None: self._timer = self.set_timer(self._delay, self._advance) def _advance(self) -> None: self.current_index = (self.current_index + 1) % self._participant_count self._steps_remaining -= 1 dice_face = random.choice(self._dice_faces) self.current_dice = dice_face self.post_message(SpinTick(self, dice_face)) if self._steps_remaining <= 0: self._is_spinning = False self.current_dice = TARGET_EMOJI winner = self._participants[self.current_index] self.post_message(SpinFinished(self, winner)) return progress = 1 - self._steps_remaining / self._initial_steps self._delay = 0.05 + progress * progress * 0.25 self._schedule_tick() @property def is_spinning(self) -> bool: return self._is_spinning @property def truncated(self) -> bool: return self._truncated @property def extra_count(self) -> int: return getattr(self, "_extra_count", 0) @property def visible_capacity(self) -> int: """Number of names that can be shown at once based on layout.""" return self._capacity
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
src/rogvibe/widgets/slot_machine.py
Python
"""Slot machine widgets.""" from __future__ import annotations import random from typing import Any from rich.text import Text from textual.app import ComposeResult from textual.containers import Horizontal from textual.reactive import reactive from textual.widget import Widget from ..models.messages import SlotAllStopped, SlotReelSpinning, SlotReelStopped from ..utils.detector import detect_default_participants from ..constants import MAYBE_VIBER class SlotMachineReel(Widget): """A single reel of the slot machine.""" DEFAULT_CSS = """ SlotMachineReel { width: 20; height: 7; border: double $primary; content-align: center middle; overflow: hidden; } """ current_value = reactive("") current_index = reactive(0) def __init__(self, reel_index: int, items: list[str]) -> None: super().__init__() self._reel_index = reel_index self._items = items self._is_spinning = False self._timer: Any | None = None self._target_value: str | None = None self._spin_count = 0 self.current_index = random.randrange(len(self._items)) if self._items else 0 self.current_value = self._items[self.current_index] if self._items else "?" def render(self) -> Text: """Render the reel with scrolling effect showing 3 items.""" if not self._items: return Text("???", justify="center", style="bold yellow") # Show 3 items: 1 before, current, 1 after indices = [ (self.current_index - 1) % len(self._items), self.current_index, (self.current_index + 1) % len(self._items), ] items = [self._items[i] for i in indices] # Create a vertical scrolling effect lines = [ items[0], # -1 "┄" * 18, items[1], # current (middle) "┄" * 18, items[2], # +1 ] content = "\n".join(lines) text = Text(content, justify="center") # Calculate positions for styling line_lengths = [len(line) + 1 for line in lines] # +1 for newline pos = 0 # Item -1 (dim) text.stylize("dim", pos, pos + len(items[0])) pos += line_lengths[0] pos += line_lengths[1] # skip separator # Current item (highlighted) text.stylize("bold yellow on #444444", pos, pos + len(items[1])) pos += line_lengths[2] pos += line_lengths[3] # skip separator # Item +1 (dim) text.stylize("dim", pos, pos + len(items[2])) return text def start_spin(self, duration_steps: int) -> None: """Start spinning the reel.""" if self._is_spinning: return self._is_spinning = True self._spin_count = 0 # Choose target index instead of target value self._target_index = random.randrange(len(self._items)) self._target_value = self._items[self._target_index] self._total_steps = duration_steps self._initial_delay = 0.03 # Start fast self._schedule_spin() def _schedule_spin(self) -> None: # Calculate dynamic delay - start fast, end slow progress = self._spin_count / self._total_steps # Use quadratic easing for smooth deceleration delay = self._initial_delay + (progress**2) * 0.15 self._timer = self.set_timer(delay, self._advance_spin) def _advance_spin(self) -> None: self._spin_count += 1 # Advance to next index for scrolling effect self.current_index = (self.current_index + 1) % len(self._items) self.current_value = self._items[self.current_index] self.post_message(SlotReelSpinning(self, self._reel_index, self.current_value)) if self._spin_count >= self._total_steps: self._is_spinning = False # Set to target index self.current_index = self._target_index self.current_value = self._items[self.current_index] self.post_message( SlotReelStopped(self, self._reel_index, self.current_value) ) else: self._schedule_spin() @property def is_spinning(self) -> bool: return self._is_spinning @property def value(self) -> str: return self.current_value class SlotMachineLever(Widget): """A lever widget for the slot machine.""" DEFAULT_CSS = """ SlotMachineLever { width: 8; height: auto; align: center middle; } """ lever_state = reactive("up") # "up" or "down" def render(self) -> Text: """Render the lever.""" if self.lever_state == "up": lever_art = """ ║ ║ ●""" else: lever_art = """ ║ ║ ║ ●""" return Text(lever_art, justify="center", style="bright_cyan") class SlotMachineWidget(Widget): """The complete slot machine with 3 reels and a lever.""" DEFAULT_CSS = """ SlotMachineWidget { width: auto; height: auto; align: center middle; } SlotMachineWidget Horizontal { width: auto; height: auto; align: center middle; } """ def __init__(self) -> None: super().__init__() # Use detected providers, fallback to MAYBE_VIBER if none found detected_providers = detect_default_participants() self._items = detected_providers if detected_providers else list(MAYBE_VIBER) self._reels = [ SlotMachineReel(0, self._items), SlotMachineReel(1, self._items), SlotMachineReel(2, self._items), ] self._lever = SlotMachineLever() self._is_spinning = False self._stopped_count = 0 self._results: list[str] = [] def compose(self) -> ComposeResult: """Compose the slot machine layout with horizontal reels.""" with Horizontal(): yield self._reels[0] yield self._reels[1] yield self._reels[2] yield self._lever def start_spin(self) -> None: """Start spinning all reels with staggered stops.""" if self._is_spinning: return self._is_spinning = True self._stopped_count = 0 self._results = [] # Animate lever pull self._lever.lever_state = "down" self.refresh() # Use a timer to return lever after delay def return_lever(): self._lever.lever_state = "up" self.refresh() self.set_timer(0.5, return_lever) # Start spinning all reels for i, reel in enumerate(self._reels): # Each reel spins for a different duration (staggered) duration = random.randint(30, 50) + i * 20 reel.start_spin(duration) def on_slot_reel_stopped(self, message: SlotReelStopped) -> None: """Handle a reel stopping.""" self._stopped_count += 1 self._results.append(message.value) if self._stopped_count == 3: self._is_spinning = False self.post_message(SlotAllStopped(self, self._results)) @property def is_spinning(self) -> bool: return self._is_spinning
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
tests/__init__.py
Python
"""Test package for rogvibe."""
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
tests/conftest.py
Python
"""Pytest configuration and fixtures for rogvibe tests.""" import pytest from unittest.mock import Mock @pytest.fixture def mock_app(): """Create a mock Textual app for testing.""" app = Mock() app.suspend = Mock() app.exit = Mock() return app @pytest.fixture def mock_widget(): """Create a mock Textual widget for testing.""" widget = Mock() return widget
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
tests/test_app.py
Python
"""Tests for rogvibe.app module.""" from unittest.mock import Mock, patch from rogvibe.app import run, run_slot_machine, run_flip_card, DEFAULT_PARTICIPANTS class TestApp: """Test cases for app module functions.""" def test_run_with_none_participants(self): """Test run function with None participants.""" with patch("rogvibe.app.LotteryApp") as mock_lottery_app: mock_instance = Mock() mock_lottery_app.return_value = mock_instance run(None) # Should use DEFAULT_PARTICIPANTS mock_lottery_app.assert_called_once_with(list(DEFAULT_PARTICIPANTS)) mock_instance.run.assert_called_once() def test_run_with_empty_participants(self): """Test run function with empty participants.""" with patch("rogvibe.app.LotteryApp") as mock_lottery_app: mock_instance = Mock() mock_lottery_app.return_value = mock_instance run([]) # Should use DEFAULT_PARTICIPANTS mock_lottery_app.assert_called_once_with(list(DEFAULT_PARTICIPANTS)) mock_instance.run.assert_called_once() def test_run_with_valid_participants(self): """Test run function with valid participants.""" participants = ["user1", "user2", "user3", "user4"] with patch("rogvibe.app.LotteryApp") as mock_lottery_app: mock_instance = Mock() mock_lottery_app.return_value = mock_instance run(participants) mock_lottery_app.assert_called_once_with(participants) mock_instance.run.assert_called_once() def test_run_with_whitespace_participants(self): """Test run function with participants containing whitespace.""" participants = [" user1 ", "", " user2 ", " "] expected = ["user1", "user2"] with patch("rogvibe.app.LotteryApp") as mock_lottery_app: mock_instance = Mock() mock_lottery_app.return_value = mock_instance run(participants) mock_lottery_app.assert_called_once_with(expected) mock_instance.run.assert_called_once() def test_run_slot_machine(self): """Test run_slot_machine function.""" with patch("rogvibe.app.SlotMachineApp") as mock_slot_app: mock_instance = Mock() mock_slot_app.return_value = mock_instance run_slot_machine() mock_slot_app.assert_called_once() mock_instance.run.assert_called_once() def test_run_flip_card(self): """Test run_flip_card function.""" with patch("rogvibe.app.FlipCardApp") as mock_flip_app: mock_instance = Mock() mock_flip_app.return_value = mock_instance run_flip_card() mock_flip_app.assert_called_once() mock_instance.run.assert_called_once() def test_default_participants_import(self): """Test that DEFAULT_PARTICIPANTS is properly imported.""" assert DEFAULT_PARTICIPANTS is not None assert isinstance(DEFAULT_PARTICIPANTS, list) assert len(DEFAULT_PARTICIPANTS) > 0 def test_default_participants_with_detection(self): """Test DEFAULT_PARTICIPANTS when detection returns values.""" # Use actual provider names from MAYBE_VIBER detected_providers = ["kimi", "claude", "gemini", "codex"] # Mock shutil.which to detect specific providers with patch("rogvibe.utils.detector.shutil.which") as mock_which: def which_side_effect(cmd): return "/usr/bin/" + cmd if cmd in detected_providers else None mock_which.side_effect = which_side_effect # Re-import to trigger the detection logic import importlib import rogvibe.app importlib.reload(rogvibe.app) # Should use detected participants (4 detected, so exactly 4 returned) assert len(rogvibe.app.DEFAULT_PARTICIPANTS) == 4 for provider in detected_providers: assert provider in rogvibe.app.DEFAULT_PARTICIPANTS def test_default_participants_fallback(self): """Test DEFAULT_PARTICIPANTS when detection returns empty.""" # Mock shutil.which to detect no providers with patch("rogvibe.utils.detector.shutil.which") as mock_which: mock_which.return_value = None # Re-import to trigger the detection logic import importlib import rogvibe.app from rogvibe.constants import FALLBACK_DEFAULTS importlib.reload(rogvibe.app) # Should fall back to FALLBACK_DEFAULTS assert rogvibe.app.DEFAULT_PARTICIPANTS == list(FALLBACK_DEFAULTS)
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
tests/test_config.py
Python
"""Tests for rogvibe.config module.""" class TestConfig: """Test cases for config module.""" def test_maybe_viber_import(self): """Test that MAYBE_VIBER can be imported from config.""" from rogvibe.config import MAYBE_VIBER assert MAYBE_VIBER is not None assert isinstance(MAYBE_VIBER, list) assert len(MAYBE_VIBER) > 0 def test_config_exports(self): """Test that config module exports expected items.""" from rogvibe import config assert hasattr(config, "MAYBE_VIBER") assert hasattr(config, "__all__") assert "MAYBE_VIBER" in config.__all__
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
tests/test_constants.py
Python
"""Tests for rogvibe.constants module.""" from rogvibe.constants import ( FALLBACK_DEFAULTS, MAYBE_VIBER, ANIMATION_COLORS, BORDER_COLORS, CELEBRATION_EMOJIS, DICE_FACES, DICE_EMOJI, TARGET_EMOJI, SPECIAL_PARTICIPANTS, ) class TestConstants: """Test cases for constants.""" def test_fallback_defaults(self): """Test FALLBACK_DEFAULTS constant.""" assert isinstance(FALLBACK_DEFAULTS, list) assert len(FALLBACK_DEFAULTS) == 4 assert all(name == "handy" for name in FALLBACK_DEFAULTS) def test_maybe_viber(self): """Test MAYBE_VIBER constant.""" assert isinstance(MAYBE_VIBER, list) assert len(MAYBE_VIBER) > 0 expected_commands = [ "kimi", "claude", "gemini", "codex", "code", "cursor", "amp", "opencode", ] for cmd in expected_commands: assert cmd in MAYBE_VIBER def test_animation_colors(self): """Test ANIMATION_COLORS constant.""" assert isinstance(ANIMATION_COLORS, list) assert len(ANIMATION_COLORS) > 0 expected_colors = ["yellow", "red", "magenta", "cyan", "white"] for color in expected_colors: assert color in ANIMATION_COLORS def test_border_colors(self): """Test BORDER_COLORS constant.""" assert isinstance(BORDER_COLORS, list) assert len(BORDER_COLORS) > 0 expected_colors = ["yellow", "red", "magenta", "cyan", "green"] for color in expected_colors: assert color in BORDER_COLORS def test_celebration_emojis(self): """Test CELEBRATION_EMOJIS constant.""" assert isinstance(CELEBRATION_EMOJIS, list) assert len(CELEBRATION_EMOJIS) > 0 expected_emojis = ["✨", "🌟", "⭐", "💫", "🎉", "🎊", "🎈"] for emoji in expected_emojis: assert emoji in CELEBRATION_EMOJIS def test_dice_faces(self): """Test DICE_FACES constant.""" assert isinstance(DICE_FACES, list) assert len(DICE_FACES) == 6 expected_faces = ["⚀", "⚁", "⚂", "⚃", "⚄", "⚅"] for face in expected_faces: assert face in DICE_FACES def test_dice_emoji(self): """Test DICE_EMOJI constant.""" assert isinstance(DICE_EMOJI, str) assert DICE_EMOJI == "🎲" def test_target_emoji(self): """Test TARGET_EMOJI constant.""" assert isinstance(TARGET_EMOJI, str) assert TARGET_EMOJI == "🎯" def test_special_participants(self): """Test SPECIAL_PARTICIPANTS constant.""" assert isinstance(SPECIAL_PARTICIPANTS, set) expected_special = {"lucky", "handy"} assert SPECIAL_PARTICIPANTS == expected_special def test_constants_immutability(self): """Test that constants are not accidentally modified.""" # Test that we can't modify the constants (they should be treated as immutable) original_fallback = FALLBACK_DEFAULTS.copy() original_viber = MAYBE_VIBER.copy() original_colors = ANIMATION_COLORS.copy() # Try to modify (this should not affect the original constants) test_fallback = FALLBACK_DEFAULTS.copy() test_fallback.append("modified") assert len(FALLBACK_DEFAULTS) == len(original_fallback) test_viber = MAYBE_VIBER.copy() test_viber.append("modified") assert len(MAYBE_VIBER) == len(original_viber) test_colors = ANIMATION_COLORS.copy() test_colors.append("modified") assert len(ANIMATION_COLORS) == len(original_colors) def test_no_empty_constants(self): """Test that no constant lists are empty.""" assert len(FALLBACK_DEFAULTS) > 0 assert len(MAYBE_VIBER) > 0 assert len(ANIMATION_COLORS) > 0 assert len(BORDER_COLORS) > 0 assert len(CELEBRATION_EMOJIS) > 0 assert len(DICE_FACES) > 0 assert len(SPECIAL_PARTICIPANTS) > 0
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
tests/test_detector.py
Python
"""Tests for rogvibe.utils.detector module.""" from unittest.mock import patch from rogvibe.utils.detector import detect_default_participants class TestDetector: """Test cases for detector module.""" def test_detect_default_participants_no_providers(self): """Test when no providers are detected.""" with patch("rogvibe.utils.detector.shutil.which") as mock_which: mock_which.return_value = None result = detect_default_participants() assert result == [] # Should be called for each provider in MAYBE_VIBER assert mock_which.call_count > 0 def test_detect_default_participants_less_than_4(self): """Test when less than 4 providers are detected.""" with patch("rogvibe.utils.detector.shutil.which") as mock_which: # Return True for first 2 providers, False for others def which_side_effect(cmd): return "/usr/bin/" + cmd if cmd in ["kimi", "claude"] else None mock_which.side_effect = which_side_effect result = detect_default_participants() assert len(result) == 4 assert "kimi" in result assert "claude" in result # Should have filler elements assert "lucky" in result or "handy" in result def test_detect_default_participants_between_5_and_8(self): """Test when between 5 and 8 providers are detected.""" with patch("rogvibe.utils.detector.shutil.which") as mock_which: # Return True for first 6 providers, False for others providers = ["kimi", "claude", "gemini", "codex", "code", "cursor"] def which_side_effect(cmd): return "/usr/bin/" + cmd if cmd in providers else None mock_which.side_effect = which_side_effect result = detect_default_participants() assert len(result) == 8 # All detected providers should be in result for provider in providers: assert provider in result # Should have filler elements assert "lucky" in result or "handy" in result def test_detect_default_participants_more_than_8(self): """Test when more than 8 providers are detected.""" # Patch MAYBE_VIBER to have more than 8 elements extra_providers = [ "kimi", "claude", "gemini", "codex", "code", "cursor", "amp", "opencode", "extra1", "extra2", ] with patch("rogvibe.utils.detector.MAYBE_VIBER", extra_providers): with patch("rogvibe.utils.detector.shutil.which") as mock_which: # Return True for all providers (more than 8) mock_which.return_value = "/usr/bin/provider" with patch("rogvibe.utils.detector.random.sample") as mock_sample: mock_sample.return_value = [ "kimi", "claude", "gemini", "codex", "code", "cursor", "amp", "opencode", ] result = detect_default_participants() assert len(result) == 8 mock_sample.assert_called_once() def test_detect_default_participants_exactly_4(self): """Test when exactly 4 providers are detected.""" with patch("rogvibe.utils.detector.shutil.which") as mock_which: # Return True for exactly 4 providers providers = ["kimi", "claude", "gemini", "codex"] def which_side_effect(cmd): return "/usr/bin/" + cmd if cmd in providers else None mock_which.side_effect = which_side_effect result = detect_default_participants() assert len(result) == 4 # All detected providers should be in result for provider in providers: assert provider in result # Should not have filler elements (exactly 4 is the minimum) def test_detect_default_participants_exactly_8(self): """Test when exactly 8 providers are detected.""" with patch("rogvibe.utils.detector.shutil.which") as mock_which: # Return True for exactly 8 providers providers = [ "kimi", "claude", "gemini", "codex", "code", "cursor", "amp", "opencode", ] def which_side_effect(cmd): return "/usr/bin/" + cmd if cmd in providers else None mock_which.side_effect = which_side_effect result = detect_default_participants() assert len(result) == 8 # All detected providers should be in result for provider in providers: assert provider in result def test_detect_default_participants_shuffling(self): """Test that providers are shuffled.""" with patch("rogvibe.utils.detector.shutil.which") as mock_which: # Return True for 4 providers providers = ["kimi", "claude", "gemini", "codex"] def which_side_effect(cmd): return "/usr/bin/" + cmd if cmd in providers else None mock_which.side_effect = which_side_effect with patch("rogvibe.utils.detector.random.shuffle") as mock_shuffle: result = detect_default_participants() mock_shuffle.assert_called_once() assert len(result) == 4 def test_detect_default_participants_random_sample(self): """Test random.sample is called when more than 8 providers.""" # Patch MAYBE_VIBER to have more than 8 elements extra_providers = [ "kimi", "claude", "gemini", "codex", "code", "cursor", "amp", "opencode", "extra1", "extra2", ] with patch("rogvibe.utils.detector.MAYBE_VIBER", extra_providers): with patch("rogvibe.utils.detector.shutil.which") as mock_which: # Return True for all providers (more than 8) mock_which.return_value = "/usr/bin/provider" with patch("rogvibe.utils.detector.random.sample") as mock_sample: mock_sample.return_value = [ "kimi", "claude", "gemini", "codex", "code", "cursor", "amp", "opencode", ] result = detect_default_participants() mock_sample.assert_called_once() assert len(result) == 8 def test_internal_on_path_function(self): """Test the internal on_path function.""" with patch("rogvibe.utils.detector.shutil.which") as mock_which: mock_which.side_effect = ( lambda cmd: "/usr/bin/cmd" if cmd == "test_cmd" else None ) # Test by calling detect_default_participants and checking behavior detect_default_participants() # Verify that shutil.which was called with the expected commands calls = [call[0][0] for call in mock_which.call_args_list] # Should include commands from MAYBE_VIBER assert len(calls) > 0 @patch("rogvibe.utils.detector.MAYBE_VIBER", ["test1", "test2", "test3"]) def test_with_custom_maybe_viber(self): """Test with custom MAYBE_VIBER list.""" with patch("rogvibe.utils.detector.shutil.which") as mock_which: mock_which.side_effect = lambda cmd: cmd in ["test1", "test2"] result = detect_default_participants() assert len(result) == 4 assert "test1" in result assert "test2" in result # Should have fillers assert "lucky" in result or "handy" in result
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
tests/test_main.py
Python
"""Tests for rogvibe.__main__ module.""" from unittest.mock import patch from rogvibe.__main__ import main class TestMain: """Test cases for main function.""" def test_main_with_slot_argument(self): """Test main function with --slot argument.""" with patch("rogvibe.__main__.run_slot_machine") as mock_run_slot: main(["--slot"]) mock_run_slot.assert_called_once() def test_main_with_flip_argument(self): """Test main function with --flip argument.""" with patch("rogvibe.__main__.run_flip_card") as mock_run_flip: main(["--flip"]) mock_run_flip.assert_called_once() def test_main_with_no_arguments(self): """Test main function with no arguments.""" with patch("rogvibe.__main__.run") as mock_run: main([]) mock_run.assert_called_once_with(None) def test_main_with_custom_arguments(self): """Test main function with custom arguments.""" with patch("rogvibe.__main__.run") as mock_run: main(["arg1", "arg2"]) mock_run.assert_called_once_with(["arg1", "arg2"]) def test_main_with_none_argv(self): """Test main function with None argv.""" with patch("rogvibe.__main__.sys.argv", ["rogvibe", "test_arg"]): with patch("rogvibe.__main__.run") as mock_run: main(None) mock_run.assert_called_once_with(["test_arg"]) def test_main_direct_execution(self): """Test __name__ == "__main__" block.""" with patch("rogvibe.__main__.main"): # Simulate direct execution by running the module import subprocess import sys result = subprocess.run( [sys.executable, "-m", "rogvibe", "--help"], capture_output=True, timeout=2, ) # The module should be executable (even if it errors out on --help) assert result.returncode in [0, 1, 2] # Any return code is fine def test_main_module_has_main_function(self): """Test that main module properly exports main function.""" import rogvibe.__main__ as main_module assert hasattr(main_module, "main") assert callable(main_module.main)
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
tests/test_models/test_messages.py
Python
"""Tests for rogvibe.models.messages module.""" from unittest.mock import Mock from textual.widget import Widget from rogvibe.models.messages import ( SpinFinished, SpinTick, SlotReelSpinning, SlotReelStopped, SlotAllStopped, AllCardsMatched, PairMatched, ) class TestMessages: """Test cases for message classes.""" def test_spin_finished_message(self): """Test SpinFinished message creation and properties.""" mock_widget = Mock(spec=Widget) winner = "test_winner" msg = SpinFinished(mock_widget, winner) assert msg.winner == winner assert msg.origin == mock_widget def test_spin_tick_message(self): """Test SpinTick message creation and properties.""" mock_widget = Mock(spec=Widget) dice_face = "⚀" msg = SpinTick(mock_widget, dice_face) assert msg.dice_face == dice_face assert msg.origin == mock_widget def test_slot_reel_spinning_message(self): """Test SlotReelSpinning message creation and properties.""" mock_widget = Mock(spec=Widget) reel_index = 0 value = "test_value" msg = SlotReelSpinning(mock_widget, reel_index, value) assert msg.reel_index == reel_index assert msg.value == value assert msg.origin == mock_widget def test_slot_reel_stopped_message(self): """Test SlotReelStopped message creation and properties.""" mock_widget = Mock(spec=Widget) reel_index = 2 value = "stopped_value" msg = SlotReelStopped(mock_widget, reel_index, value) assert msg.reel_index == reel_index assert msg.value == value assert msg.origin == mock_widget def test_slot_all_stopped_message(self): """Test SlotAllStopped message creation and properties.""" mock_widget = Mock(spec=Widget) results = ["val1", "val2", "val3"] msg = SlotAllStopped(mock_widget, results) assert msg.results == results assert msg.origin == mock_widget def test_all_cards_matched_message(self): """Test AllCardsMatched message creation and properties.""" mock_widget = Mock(spec=Widget) winner = "card_winner" msg = AllCardsMatched(mock_widget, winner) assert msg.winner == winner assert msg.origin == mock_widget def test_pair_matched_message(self): """Test PairMatched message creation and properties.""" mock_widget = Mock(spec=Widget) value = "pair_value" msg = PairMatched(mock_widget, value) assert msg.value == value assert msg.origin == mock_widget
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache
tests/test_utils/test_executor.py
Python
"""Tests for rogvibe.utils.executor module.""" from unittest.mock import Mock, patch from rogvibe.utils.executor import execute_command class TestExecutor: """Test cases for executor module.""" def test_execute_command_with_code(self): """Test execute_command with 'code' command adds '.' argument.""" mock_app = Mock() mock_app.suspend = Mock(return_value=Mock(__enter__=Mock(), __exit__=Mock())) with patch("rogvibe.utils.executor.shutil.which") as mock_which: mock_which.return_value = "/usr/bin/code" with patch("rogvibe.utils.executor.os.execvp") as mock_exec: execute_command("code", mock_app) # Should be called with 'code' and '.' mock_exec.assert_called_once_with("code", ["code", "."]) def test_execute_command_with_cursor(self): """Test execute_command with 'cursor' command adds '.' argument.""" mock_app = Mock() mock_app.suspend = Mock(return_value=Mock(__enter__=Mock(), __exit__=Mock())) with patch("rogvibe.utils.executor.shutil.which") as mock_which: mock_which.return_value = "/usr/bin/cursor" with patch("rogvibe.utils.executor.os.execvp") as mock_exec: execute_command("cursor", mock_app) mock_exec.assert_called_once_with("cursor", ["cursor", "."]) def test_execute_command_with_empty_string(self): """Test execute_command with empty string exits with code 0.""" mock_app = Mock() execute_command("", mock_app) mock_app.exit.assert_called_once_with(0) def test_execute_command_not_found(self): """Test execute_command when command is not on PATH.""" mock_app = Mock() with patch("rogvibe.utils.executor.shutil.which") as mock_which: mock_which.return_value = None execute_command("nonexistent", mock_app) mock_app.exit.assert_called_once_with(127) def test_execute_command_with_arguments(self): """Test execute_command with arguments.""" mock_app = Mock() mock_app.suspend = Mock(return_value=Mock(__enter__=Mock(), __exit__=Mock())) with patch("rogvibe.utils.executor.shutil.which") as mock_which: mock_which.return_value = "/usr/bin/ls" with patch("rogvibe.utils.executor.os.execvp") as mock_exec: execute_command("ls -la", mock_app) mock_exec.assert_called_once_with("ls", ["ls", "-la"]) def test_execute_command_file_not_found_error(self): """Test execute_command when FileNotFoundError is raised.""" mock_app = Mock() mock_context = Mock() mock_context.__enter__ = Mock(return_value=None) mock_context.__exit__ = Mock(return_value=None) mock_app.suspend = Mock(return_value=mock_context) with patch("rogvibe.utils.executor.shutil.which") as mock_which: mock_which.return_value = "/usr/bin/cmd" with patch("rogvibe.utils.executor.os.execvp") as mock_exec: with patch("rogvibe.utils.executor.print"): mock_exec.side_effect = FileNotFoundError() execute_command("cmd", mock_app) mock_app.exit.assert_called_once_with(127) def test_execute_command_permission_error(self): """Test execute_command when PermissionError is raised.""" mock_app = Mock() mock_context = Mock() mock_context.__enter__ = Mock(return_value=None) mock_context.__exit__ = Mock(return_value=None) mock_app.suspend = Mock(return_value=mock_context) with patch("rogvibe.utils.executor.shutil.which") as mock_which: mock_which.return_value = "/usr/bin/cmd" with patch("rogvibe.utils.executor.os.execvp") as mock_exec: with patch("rogvibe.utils.executor.print"): mock_exec.side_effect = PermissionError() execute_command("cmd", mock_app) mock_app.exit.assert_called_once_with(126) def test_execute_command_os_error(self): """Test execute_command when OSError is raised.""" mock_app = Mock() mock_context = Mock() mock_context.__enter__ = Mock(return_value=None) mock_context.__exit__ = Mock(return_value=None) mock_app.suspend = Mock(return_value=mock_context) with patch("rogvibe.utils.executor.shutil.which") as mock_which: mock_which.return_value = "/usr/bin/cmd" with patch("rogvibe.utils.executor.os.execvp") as mock_exec: with patch("rogvibe.utils.executor.print"): mock_exec.side_effect = OSError("Some OS error") execute_command("cmd", mock_app) mock_app.exit.assert_called_once_with(1) def test_execute_command_without_suspend(self): """Test execute_command with app that doesn't have suspend method.""" mock_app = Mock(spec=[]) # No suspend method delattr(mock_app, "suspend") with patch("rogvibe.utils.executor.shutil.which") as mock_which: mock_which.return_value = "/usr/bin/echo" with patch("rogvibe.utils.executor.os.execvp") as mock_exec: execute_command("echo hello", mock_app) mock_exec.assert_called_once_with("echo", ["echo", "hello"])
yihong0618/rogvibe
28
Rogue your vibe hero like rogue like.
Python
yihong0618
yihong
apache