text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
import os from distutils.version import LooseVersion import pkg_resources from mlagents.torch_utils import cpu_utils from mlagents.trainers.settings import TorchSettings from mlagents_envs.logging_util import get_logger logger = get_logger(__name__) def assert_torch_installed(): # Check that torch version 1.6.0 or later has been installed. If not, refer # user to the PyTorch webpage for install instructions. torch_pkg = None try: torch_pkg = pkg_resources.get_distribution("torch") except pkg_resources.DistributionNotFound: pass assert torch_pkg is not None and LooseVersion(torch_pkg.version) >= LooseVersion( "1.6.0" ), ( "A compatible version of PyTorch was not installed. Please visit the PyTorch homepage " + "(https://pytorch.org/get-started/locally/) and follow the instructions to install. " + "Version 1.6.0 and later are supported." ) assert_torch_installed() # This should be the only place that we import torch directly. # Everywhere else is caught by the banned-modules setting for flake8 import torch # noqa I201 torch.set_num_threads(cpu_utils.get_num_threads_to_use()) os.environ["KMP_BLOCKTIME"] = "0" _device = torch.device("cpu") def set_torch_config(torch_settings: TorchSettings) -> None: global _device if torch_settings.device is None: device_str = "cuda" if torch.cuda.is_available() else "cpu" else: device_str = torch_settings.device _device = torch.device(device_str) if _device.type == "cuda": torch.set_default_tensor_type(torch.cuda.FloatTensor) else: torch.set_default_tensor_type(torch.FloatTensor) logger.debug(f"default Torch device: {_device}") # Initialize to default settings set_torch_config(TorchSettings(device=None)) nn = torch.nn def default_device(): return _device
ml-agents/ml-agents/mlagents/torch_utils/torch.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/torch_utils/torch.py", "repo_id": "ml-agents", "token_count": 678 }
2,047
import argparse from typing import Optional, List from mlagents.trainers.learn import run_cli from mlagents.trainers.settings import RunOptions from mlagents.trainers.cli_utils import load_config from mlagents.plugins.trainer_type import register_trainer_plugins def parse_command_line(argv: Optional[List[str]] = None) -> argparse.Namespace: parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument("experiment_config_path") return parser.parse_args(argv) def main(): """ Provides an alternative CLI interface to mlagents-learn, 'mlagents-run-experiment'. Accepts a JSON/YAML formatted mlagents.trainers.learn.RunOptions object, and executes the run loop as defined in mlagents.trainers.learn.run_cli. """ args = parse_command_line() expt_config = load_config(args.experiment_config_path) _, _ = register_trainer_plugins() run_cli(RunOptions.from_dict(expt_config)) if __name__ == "__main__": main()
ml-agents/ml-agents/mlagents/trainers/run_experiment.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/run_experiment.py", "repo_id": "ml-agents", "token_count": 345 }
2,048
import numpy as np from mlagents.trainers.buffer import ( AgentBuffer, AgentBufferField, BufferKey, ObservationKeyPrefix, RewardSignalKeyPrefix, ) from mlagents.trainers.trajectory import ObsUtil def assert_array(a, b): assert a.shape == b.shape la = list(a.flatten()) lb = list(b.flatten()) for i in range(len(la)): assert la[i] == lb[i] def construct_fake_buffer(fake_agent_id): b = AgentBuffer() for step in range(9): b[ObsUtil.get_name_at(0)].append( np.array( [ 100 * fake_agent_id + 10 * step + 1, 100 * fake_agent_id + 10 * step + 2, 100 * fake_agent_id + 10 * step + 3, ], dtype=np.float32, ) ) b[BufferKey.CONTINUOUS_ACTION].append( np.array( [ 100 * fake_agent_id + 10 * step + 4, 100 * fake_agent_id + 10 * step + 5, ], dtype=np.float32, ) ) b[BufferKey.GROUP_CONTINUOUS_ACTION].append( [ np.array( [ 100 * fake_agent_id + 10 * step + 4, 100 * fake_agent_id + 10 * step + 5, ], dtype=np.float32, ) ] * 3 ) return b def test_buffer(): agent_1_buffer = construct_fake_buffer(1) agent_2_buffer = construct_fake_buffer(2) agent_3_buffer = construct_fake_buffer(3) # Test get_batch a = agent_1_buffer[ObsUtil.get_name_at(0)].get_batch( batch_size=2, training_length=1, sequential=True ) assert_array( np.array(a), np.array([[171, 172, 173], [181, 182, 183]], dtype=np.float32) ) # Test get_batch a = agent_2_buffer[ObsUtil.get_name_at(0)].get_batch( batch_size=2, training_length=3, sequential=True ) assert_array( np.array(a), np.array( [ [231, 232, 233], [241, 242, 243], [251, 252, 253], [261, 262, 263], [271, 272, 273], [281, 282, 283], ], dtype=np.float32, ), ) a = agent_2_buffer[ObsUtil.get_name_at(0)].get_batch( batch_size=2, training_length=3, sequential=False ) assert_array( np.array(a), np.array( [ [251, 252, 253], [261, 262, 263], [271, 272, 273], [261, 262, 263], [271, 272, 273], [281, 282, 283], ] ), ) # Test padding a = agent_2_buffer[ObsUtil.get_name_at(0)].get_batch( batch_size=None, training_length=4, sequential=True ) assert_array( np.array(a), np.array( [ [201, 202, 203], [211, 212, 213], [221, 222, 223], [231, 232, 233], [241, 242, 243], [251, 252, 253], [261, 262, 263], [271, 272, 273], [281, 282, 283], [0, 0, 0], [0, 0, 0], [0, 0, 0], ] ), ) # Test group entries return Lists of Lists. Make sure to pad properly! a = agent_2_buffer[BufferKey.GROUP_CONTINUOUS_ACTION].get_batch( batch_size=None, training_length=4, sequential=True ) for _group_entry in a[:-3]: assert len(_group_entry) == 3 for _group_entry in a[-3:]: assert len(_group_entry) == 0 agent_1_buffer.reset_agent() assert agent_1_buffer.num_experiences == 0 update_buffer = AgentBuffer() agent_2_buffer.resequence_and_append( update_buffer, batch_size=None, training_length=2 ) agent_3_buffer.resequence_and_append( update_buffer, batch_size=None, training_length=2 ) assert len(update_buffer[BufferKey.CONTINUOUS_ACTION]) == 20 assert np.array(update_buffer[BufferKey.CONTINUOUS_ACTION]).shape == (20, 2) c = update_buffer.make_mini_batch(start=0, end=1) assert c.keys() == update_buffer.keys() # Make sure the values of c are AgentBufferField for val in c.values(): assert isinstance(val, AgentBufferField) assert np.array(c[BufferKey.CONTINUOUS_ACTION]).shape == (1, 2) def test_agentbufferfield(): # Test constructor a = AgentBufferField([0, 1, 2]) for i, num in enumerate(a): assert num == i # Test indexing assert a[i] == num # Test slicing b = a[1:3] assert b == [1, 2] assert isinstance(b, AgentBufferField) # Test padding c = AgentBufferField() for _ in range(2): c.append([np.array(1), np.array(2)]) for _ in range(2): c.append([np.array(1)]) padded = c.padded_to_batch(pad_value=3) assert np.array_equal(padded[0], np.array([1, 1, 1, 1])) assert np.array_equal(padded[1], np.array([2, 2, 3, 3])) # Make sure it doesn't fail when the field isn't a list padded_a = a.padded_to_batch() assert np.array_equal(padded_a, a) def fakerandint(values): return 19 def test_buffer_sample(): agent_1_buffer = construct_fake_buffer(1) agent_2_buffer = construct_fake_buffer(2) update_buffer = AgentBuffer() agent_1_buffer.resequence_and_append( update_buffer, batch_size=None, training_length=2 ) agent_2_buffer.resequence_and_append( update_buffer, batch_size=None, training_length=2 ) # Test non-LSTM mb = update_buffer.sample_mini_batch(batch_size=4, sequence_length=1) assert mb.keys() == update_buffer.keys() assert np.array(mb[BufferKey.CONTINUOUS_ACTION]).shape == (4, 2) # Test LSTM # We need to check if we ever get a breaking start - this will maximize the probability mb = update_buffer.sample_mini_batch(batch_size=20, sequence_length=19) assert mb.keys() == update_buffer.keys() # Should only return one sequence assert np.array(mb[BufferKey.CONTINUOUS_ACTION]).shape == (19, 2) def test_num_experiences(): agent_1_buffer = construct_fake_buffer(1) agent_2_buffer = construct_fake_buffer(2) update_buffer = AgentBuffer() assert len(update_buffer[BufferKey.CONTINUOUS_ACTION]) == 0 assert update_buffer.num_experiences == 0 agent_1_buffer.resequence_and_append( update_buffer, batch_size=None, training_length=2 ) agent_2_buffer.resequence_and_append( update_buffer, batch_size=None, training_length=2 ) assert len(update_buffer[BufferKey.CONTINUOUS_ACTION]) == 20 assert update_buffer.num_experiences == 20 def test_buffer_truncate(): agent_1_buffer = construct_fake_buffer(1) agent_2_buffer = construct_fake_buffer(2) update_buffer = AgentBuffer() agent_1_buffer.resequence_and_append( update_buffer, batch_size=None, training_length=2 ) agent_2_buffer.resequence_and_append( update_buffer, batch_size=None, training_length=2 ) # Test non-LSTM update_buffer.truncate(2) assert update_buffer.num_experiences == 2 agent_1_buffer.resequence_and_append( update_buffer, batch_size=None, training_length=2 ) agent_2_buffer.resequence_and_append( update_buffer, batch_size=None, training_length=2 ) # Test LSTM, truncate should be some multiple of sequence_length update_buffer.truncate(4, sequence_length=3) assert update_buffer.num_experiences == 3 for buffer_field in update_buffer.values(): assert isinstance(buffer_field, AgentBufferField) def test_key_encode_decode(): keys = ( list(BufferKey) + [(k, 42) for k in ObservationKeyPrefix] + [(k, "gail") for k in RewardSignalKeyPrefix] ) for k in keys: assert k == AgentBuffer._decode_key(AgentBuffer._encode_key(k)) def test_buffer_save_load(): original = construct_fake_buffer(3) import io write_buffer = io.BytesIO() original.save_to_file(write_buffer) loaded = AgentBuffer() loaded.load_from_file(write_buffer) assert len(original) == len(loaded) for k in original.keys(): assert np.allclose(original[k], loaded[k])
ml-agents/ml-agents/mlagents/trainers/tests/test_buffer.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/tests/test_buffer.py", "repo_id": "ml-agents", "token_count": 4013 }
2,049
from unittest.mock import patch import pytest from mlagents.trainers.agent_processor import AgentManagerQueue from mlagents.trainers.behavior_id_utils import BehaviorIdentifiers from mlagents.trainers.environment_parameter_manager import EnvironmentParameterManager from mlagents.trainers.settings import RunOptions from mlagents.trainers.tests import mock_brain as mb from mlagents.trainers.tests.dummy_config import ( create_observation_specs_with_shapes, ppo_dummy_config, poca_dummy_config, sac_dummy_config, ) from mlagents.trainers.tests.mock_brain import make_fake_trajectory from mlagents.trainers.trainer import TrainerFactory @pytest.fixture def ppo_config(): return RunOptions(behaviors={"test_brain": ppo_dummy_config()}) @pytest.fixture def sac_config(): return RunOptions(behaviors={"test_brain": sac_dummy_config()}) @pytest.fixture def poca_config(): return RunOptions(behaviors={"test_brain": poca_dummy_config()}) def test_ppo_trainer_update_normalization(ppo_config): behavior_id_team0 = "test_brain?team=0" brain_name = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team0).brain_name mock_specs = mb.setup_test_behavior_specs( True, False, vector_action_space=[2], vector_obs_space=1 ) base_config = ppo_config.behaviors output_path = "results_dir" train_model = True load_model = False seed = 42 trainer_factory = TrainerFactory( trainer_config=base_config, output_path=output_path, train_model=train_model, load_model=load_model, seed=seed, param_manager=EnvironmentParameterManager(), ) ppo_trainer = trainer_factory.generate(brain_name) parsed_behavior_id0 = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team0) policy = ppo_trainer.create_policy(parsed_behavior_id0, mock_specs) ppo_trainer.add_policy(parsed_behavior_id0, policy) trajectory_queue0 = AgentManagerQueue(behavior_id_team0) ppo_trainer.subscribe_trajectory_queue(trajectory_queue0) time_horizon = 15 trajectory = make_fake_trajectory( length=time_horizon, max_step_complete=True, observation_specs=create_observation_specs_with_shapes([(1,)]), action_spec=mock_specs.action_spec, ) trajectory_queue0.put(trajectory) # mocking out update_normalization in both the policy and critic with patch( "mlagents.trainers.torch_entities.networks.ValueNetwork.update_normalization" ) as optimizer_update_normalization_mock, patch( "mlagents.trainers.torch_entities.networks.SimpleActor.update_normalization" ) as policy_update_normalization_mock: ppo_trainer.advance() optimizer_update_normalization_mock.assert_called_once() policy_update_normalization_mock.assert_called_once() def test_sac_trainer_update_normalization(sac_config): behavior_id_team0 = "test_brain?team=0" brain_name = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team0).brain_name mock_specs = mb.setup_test_behavior_specs( True, False, vector_action_space=[2], vector_obs_space=1 ) base_config = sac_config.behaviors output_path = "results_dir" train_model = True load_model = False seed = 42 trainer_factory = TrainerFactory( trainer_config=base_config, output_path=output_path, train_model=train_model, load_model=load_model, seed=seed, param_manager=EnvironmentParameterManager(), ) sac_trainer = trainer_factory.generate(brain_name) parsed_behavior_id0 = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team0) policy = sac_trainer.create_policy(parsed_behavior_id0, mock_specs) sac_trainer.add_policy(parsed_behavior_id0, policy) trajectory_queue0 = AgentManagerQueue(behavior_id_team0) sac_trainer.subscribe_trajectory_queue(trajectory_queue0) time_horizon = 15 trajectory = make_fake_trajectory( length=time_horizon, max_step_complete=True, observation_specs=create_observation_specs_with_shapes([(1,)]), action_spec=mock_specs.action_spec, ) trajectory_queue0.put(trajectory) # mocking out update_normalization in both the policy and critic with patch( "mlagents.trainers.torch_entities.networks.ValueNetwork.update_normalization" ) as optimizer_update_normalization_mock, patch( "mlagents.trainers.torch_entities.networks.SimpleActor.update_normalization" ) as policy_update_normalization_mock: sac_trainer.advance() optimizer_update_normalization_mock.assert_called_once() policy_update_normalization_mock.assert_called_once() def test_poca_trainer_update_normalization(poca_config): behavior_id_team0 = "test_brain?team=0" brain_name = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team0).brain_name mock_specs = mb.setup_test_behavior_specs( True, False, vector_action_space=[2], vector_obs_space=1 ) base_config = poca_config.behaviors output_path = "results_dir" train_model = True load_model = False seed = 42 trainer_factory = TrainerFactory( trainer_config=base_config, output_path=output_path, train_model=train_model, load_model=load_model, seed=seed, param_manager=EnvironmentParameterManager(), ) poca_trainer = trainer_factory.generate(brain_name) parsed_behavior_id0 = BehaviorIdentifiers.from_name_behavior_id(behavior_id_team0) policy = poca_trainer.create_policy(parsed_behavior_id0, mock_specs) poca_trainer.add_policy(parsed_behavior_id0, policy) trajectory_queue0 = AgentManagerQueue(behavior_id_team0) poca_trainer.subscribe_trajectory_queue(trajectory_queue0) time_horizon = 15 trajectory = make_fake_trajectory( length=time_horizon, max_step_complete=True, observation_specs=create_observation_specs_with_shapes([(1,)]), action_spec=mock_specs.action_spec, ) trajectory_queue0.put(trajectory) # mocking out update_normalization in both the policy and critic with patch( "mlagents.trainers.poca.optimizer_torch.TorchPOCAOptimizer.POCAValueNetwork.update_normalization" ) as optimizer_update_normalization_mock, patch( "mlagents.trainers.torch_entities.networks.SimpleActor.update_normalization" ) as policy_update_normalization_mock: poca_trainer.advance() optimizer_update_normalization_mock.assert_called_once() policy_update_normalization_mock.assert_called_once()
ml-agents/ml-agents/mlagents/trainers/tests/test_trainers.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/tests/test_trainers.py", "repo_id": "ml-agents", "token_count": 2597 }
2,050
from mlagents.torch_utils import torch from unittest import mock import pytest from mlagents.trainers.torch_entities.encoders import ( VectorInput, Normalizer, SmallVisualEncoder, FullyConnectedVisualEncoder, SimpleVisualEncoder, ResNetVisualEncoder, NatureVisualEncoder, ) # This test will also reveal issues with states not being saved in the state_dict. def compare_models(module_1, module_2): is_same = True for key_item_1, key_item_2 in zip( module_1.state_dict().items(), module_2.state_dict().items() ): # Compare tensors in state_dict and not the keys. is_same = torch.equal(key_item_1[1], key_item_2[1]) and is_same return is_same def test_normalizer(): input_size = 2 norm = Normalizer(input_size) # These three inputs should mean to 0.5, and variance 2 # with the steps starting at 1 vec_input1 = torch.tensor([[1, 1]]) vec_input2 = torch.tensor([[1, 1]]) vec_input3 = torch.tensor([[0, 0]]) norm.update(vec_input1) norm.update(vec_input2) norm.update(vec_input3) # Test normalization for val in norm(vec_input1)[0].tolist(): assert val == pytest.approx(0.707, abs=0.001) # Test copy normalization norm2 = Normalizer(input_size) assert not compare_models(norm, norm2) norm2.copy_from(norm) assert compare_models(norm, norm2) for val in norm2(vec_input1)[0].tolist(): assert val == pytest.approx(0.707, abs=0.001) @mock.patch("mlagents.trainers.torch_entities.encoders.Normalizer") def test_vector_encoder(mock_normalizer): mock_normalizer_inst = mock.Mock() mock_normalizer.return_value = mock_normalizer_inst input_size = 64 normalize = False vector_encoder = VectorInput(input_size, normalize) output = vector_encoder(torch.ones((1, input_size))) assert output.shape == (1, input_size) normalize = True vector_encoder = VectorInput(input_size, normalize) new_vec = torch.ones((1, input_size)) vector_encoder.update_normalization(new_vec) mock_normalizer.assert_called_with(input_size) mock_normalizer_inst.update.assert_called_with(new_vec) vector_encoder2 = VectorInput(input_size, normalize) vector_encoder.copy_normalization(vector_encoder2) mock_normalizer_inst.copy_from.assert_called_with(mock_normalizer_inst) @pytest.mark.parametrize("image_size", [(3, 36, 36), (4, 84, 84), (5, 256, 256)]) @pytest.mark.parametrize( "vis_class", [ SimpleVisualEncoder, ResNetVisualEncoder, NatureVisualEncoder, SmallVisualEncoder, FullyConnectedVisualEncoder, ], ) def test_visual_encoder(vis_class, image_size): num_outputs = 128 enc = vis_class(image_size[1], image_size[2], image_size[0], num_outputs) # Note: NCHW not NHWC sample_input = torch.ones((1, image_size[0], image_size[1], image_size[2])) encoding = enc(sample_input) assert encoding.shape == (1, num_outputs) @pytest.mark.parametrize( "vis_class, size", [ (SimpleVisualEncoder, 36), (ResNetVisualEncoder, 36), (NatureVisualEncoder, 36), (SmallVisualEncoder, 10), (FullyConnectedVisualEncoder, 36), ], ) @pytest.mark.slow def test_visual_encoder_trains(vis_class, size): torch.manual_seed(0) image_size = (1, size, size) batch = 100 inputs = torch.cat( [torch.zeros((batch,) + image_size), torch.ones((batch,) + image_size)], dim=0 ) target = torch.cat([torch.zeros((batch,)), torch.ones((batch,))], dim=0) enc = vis_class(image_size[1], image_size[2], image_size[0], 1) optimizer = torch.optim.Adam(enc.parameters(), lr=0.001) for _ in range(25): prediction = enc(inputs)[:, 0] loss = torch.mean((target - prediction) ** 2) optimizer.zero_grad() loss.backward() optimizer.step() assert loss.item() < 0.05
ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_encoders.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/tests/torch_entities/test_encoders.py", "repo_id": "ml-agents", "token_count": 1615 }
2,051
import numpy as np from typing import Dict from mlagents.torch_utils import torch from mlagents.trainers.buffer import AgentBuffer from mlagents.trainers.torch_entities.components.reward_providers.base_reward_provider import ( BaseRewardProvider, ) from mlagents.trainers.settings import RNDSettings from mlagents_envs.base_env import BehaviorSpec from mlagents_envs import logging_util from mlagents.trainers.torch_entities.utils import ModelUtils from mlagents.trainers.torch_entities.networks import NetworkBody from mlagents.trainers.trajectory import ObsUtil logger = logging_util.get_logger(__name__) class RNDRewardProvider(BaseRewardProvider): """ Implementation of Random Network Distillation : https://arxiv.org/pdf/1810.12894.pdf """ def __init__(self, specs: BehaviorSpec, settings: RNDSettings) -> None: super().__init__(specs, settings) self._ignore_done = True self._random_network = RNDNetwork(specs, settings) self._training_network = RNDNetwork(specs, settings) self.optimizer = torch.optim.Adam( self._training_network.parameters(), lr=settings.learning_rate ) def evaluate(self, mini_batch: AgentBuffer) -> np.ndarray: with torch.no_grad(): target = self._random_network(mini_batch) prediction = self._training_network(mini_batch) rewards = torch.sum((prediction - target) ** 2, dim=1) return rewards.detach().cpu().numpy() def update(self, mini_batch: AgentBuffer) -> Dict[str, np.ndarray]: with torch.no_grad(): target = self._random_network(mini_batch) prediction = self._training_network(mini_batch) loss = torch.mean(torch.sum((prediction - target) ** 2, dim=1)) self.optimizer.zero_grad() loss.backward() self.optimizer.step() return {"Losses/RND Loss": loss.detach().cpu().numpy()} def get_modules(self): return { f"Module:{self.name}-pred": self._training_network, f"Module:{self.name}-target": self._random_network, } class RNDNetwork(torch.nn.Module): EPSILON = 1e-10 def __init__(self, specs: BehaviorSpec, settings: RNDSettings) -> None: super().__init__() state_encoder_settings = settings.network_settings if state_encoder_settings.memory is not None: state_encoder_settings.memory = None logger.warning( "memory was specified in network_settings but is not supported by RND. It is being ignored." ) self._encoder = NetworkBody(specs.observation_specs, state_encoder_settings) def forward(self, mini_batch: AgentBuffer) -> torch.Tensor: n_obs = len(self._encoder.processors) np_obs = ObsUtil.from_buffer(mini_batch, n_obs) # Convert to tensors tensor_obs = [ModelUtils.list_to_tensor(obs) for obs in np_obs] hidden, _ = self._encoder.forward(tensor_obs) self._encoder.update_normalization(mini_batch) return hidden
ml-agents/ml-agents/mlagents/trainers/torch_entities/components/reward_providers/rnd_reward_provider.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/torch_entities/components/reward_providers/rnd_reward_provider.py", "repo_id": "ml-agents", "token_count": 1217 }
2,052
# # Unity ML-Agents Toolkit # ## ML-Agent Learning """Launches trainers for each External Brains in a Unity Environment.""" import os import threading from typing import Dict, Set, List from collections import defaultdict import numpy as np from mlagents_envs.logging_util import get_logger from mlagents.trainers.env_manager import EnvManager, EnvironmentStep from mlagents_envs.exception import ( UnityEnvironmentException, UnityCommunicationException, UnityCommunicatorStoppedException, ) from mlagents_envs.timers import ( hierarchical_timer, timed, get_timer_stack_for_thread, merge_gauges, ) from mlagents.trainers.trainer import Trainer from mlagents.trainers.environment_parameter_manager import EnvironmentParameterManager from mlagents.trainers.trainer import TrainerFactory from mlagents.trainers.behavior_id_utils import BehaviorIdentifiers from mlagents.trainers.agent_processor import AgentManager from mlagents import torch_utils from mlagents.torch_utils.globals import get_rank class TrainerController: def __init__( self, trainer_factory: TrainerFactory, output_path: str, run_id: str, param_manager: EnvironmentParameterManager, train: bool, training_seed: int, ): """ :param output_path: Path to save the model. :param summaries_dir: Folder to save training summaries. :param run_id: The sub-directory name for model and summary statistics :param param_manager: EnvironmentParameterManager object which stores information about all environment parameters. :param train: Whether to train model, or only run inference. :param training_seed: Seed to use for Numpy and Torch random number generation. :param threaded: Whether or not to run trainers in a separate thread. Disable for testing/debugging. """ self.trainers: Dict[str, Trainer] = {} self.brain_name_to_identifier: Dict[str, Set] = defaultdict(set) self.trainer_factory = trainer_factory self.output_path = output_path self.logger = get_logger(__name__) self.run_id = run_id self.train_model = train self.param_manager = param_manager self.ghost_controller = self.trainer_factory.ghost_controller self.registered_behavior_ids: Set[str] = set() self.trainer_threads: List[threading.Thread] = [] self.kill_trainers = False np.random.seed(training_seed) torch_utils.torch.manual_seed(training_seed) self.rank = get_rank() @timed def _save_models(self): """ Saves current model to checkpoint folder. """ if self.rank is not None and self.rank != 0: return for brain_name in self.trainers.keys(): self.trainers[brain_name].save_model() self.logger.debug("Saved Model") @staticmethod def _create_output_path(output_path): try: if not os.path.exists(output_path): os.makedirs(output_path) except Exception: raise UnityEnvironmentException( f"The folder {output_path} containing the " "generated model could not be " "accessed. Please make sure the " "permissions are set correctly." ) @timed def _reset_env(self, env_manager: EnvManager) -> None: """Resets the environment. Returns: A Data structure corresponding to the initial reset state of the environment. """ new_config = self.param_manager.get_current_samplers() env_manager.reset(config=new_config) # Register any new behavior ids that were generated on the reset. self._register_new_behaviors(env_manager, env_manager.first_step_infos) def _not_done_training(self) -> bool: return ( any(t.should_still_train for t in self.trainers.values()) or not self.train_model ) or len(self.trainers) == 0 def _create_trainer_and_manager( self, env_manager: EnvManager, name_behavior_id: str ) -> None: parsed_behavior_id = BehaviorIdentifiers.from_name_behavior_id(name_behavior_id) brain_name = parsed_behavior_id.brain_name trainerthread = None if brain_name in self.trainers: trainer = self.trainers[brain_name] else: trainer = self.trainer_factory.generate(brain_name) self.trainers[brain_name] = trainer if trainer.threaded: # Only create trainer thread for new trainers trainerthread = threading.Thread( target=self.trainer_update_func, args=(trainer,), daemon=True ) self.trainer_threads.append(trainerthread) env_manager.on_training_started( brain_name, self.trainer_factory.trainer_config[brain_name] ) policy = trainer.create_policy( parsed_behavior_id, env_manager.training_behaviors[name_behavior_id], ) trainer.add_policy(parsed_behavior_id, policy) agent_manager = AgentManager( policy, name_behavior_id, trainer.stats_reporter, trainer.parameters.time_horizon, threaded=trainer.threaded, ) env_manager.set_agent_manager(name_behavior_id, agent_manager) env_manager.set_policy(name_behavior_id, policy) self.brain_name_to_identifier[brain_name].add(name_behavior_id) trainer.publish_policy_queue(agent_manager.policy_queue) trainer.subscribe_trajectory_queue(agent_manager.trajectory_queue) # Only start new trainers if trainerthread is not None: trainerthread.start() def _create_trainers_and_managers( self, env_manager: EnvManager, behavior_ids: Set[str] ) -> None: for behavior_id in behavior_ids: self._create_trainer_and_manager(env_manager, behavior_id) @timed def start_learning(self, env_manager: EnvManager) -> None: self._create_output_path(self.output_path) try: # Initial reset self._reset_env(env_manager) self.param_manager.log_current_lesson() while self._not_done_training(): n_steps = self.advance(env_manager) for _ in range(n_steps): self.reset_env_if_ready(env_manager) # Stop advancing trainers self.join_threads() except ( KeyboardInterrupt, UnityCommunicationException, UnityEnvironmentException, UnityCommunicatorStoppedException, ) as ex: self.join_threads() self.logger.info( "Learning was interrupted. Please wait while the graph is generated." ) if isinstance(ex, KeyboardInterrupt) or isinstance( ex, UnityCommunicatorStoppedException ): pass else: # If the environment failed, we want to make sure to raise # the exception so we exit the process with an return code of 1. raise ex finally: if self.train_model: self._save_models() def end_trainer_episodes(self) -> None: # Reward buffers reset takes place only for curriculum learning # else no reset. for trainer in self.trainers.values(): trainer.end_episode() def reset_env_if_ready(self, env: EnvManager) -> None: # Get the sizes of the reward buffers. reward_buff = {k: list(t.reward_buffer) for (k, t) in self.trainers.items()} curr_step = {k: int(t.get_step) for (k, t) in self.trainers.items()} max_step = {k: int(t.get_max_steps) for (k, t) in self.trainers.items()} # Attempt to increment the lessons of the brains who # were ready. updated, param_must_reset = self.param_manager.update_lessons( curr_step, max_step, reward_buff ) if updated: for trainer in self.trainers.values(): trainer.reward_buffer.clear() # If ghost trainer swapped teams ghost_controller_reset = self.ghost_controller.should_reset() if param_must_reset or ghost_controller_reset: self._reset_env(env) # This reset also sends the new config to env self.end_trainer_episodes() elif updated: env.set_env_parameters(self.param_manager.get_current_samplers()) @timed def advance(self, env_manager: EnvManager) -> int: # Get steps with hierarchical_timer("env_step"): new_step_infos = env_manager.get_steps() self._register_new_behaviors(env_manager, new_step_infos) num_steps = env_manager.process_steps(new_step_infos) # Report current lesson for each environment parameter for ( param_name, lesson_number, ) in self.param_manager.get_current_lesson_number().items(): for trainer in self.trainers.values(): trainer.stats_reporter.set_stat( f"Environment/Lesson Number/{param_name}", lesson_number ) for trainer in self.trainers.values(): if not trainer.threaded: with hierarchical_timer("trainer_advance"): trainer.advance() return num_steps def _register_new_behaviors( self, env_manager: EnvManager, step_infos: List[EnvironmentStep] ) -> None: """ Handle registration (adding trainers and managers) of new behaviors ids. :param env_manager: :param step_infos: :return: """ step_behavior_ids: Set[str] = set() for s in step_infos: step_behavior_ids |= set(s.name_behavior_ids) new_behavior_ids = step_behavior_ids - self.registered_behavior_ids self._create_trainers_and_managers(env_manager, new_behavior_ids) self.registered_behavior_ids |= step_behavior_ids def join_threads(self, timeout_seconds: float = 1.0) -> None: """ Wait for threads to finish, and merge their timer information into the main thread. :param timeout_seconds: :return: """ self.kill_trainers = True for t in self.trainer_threads: try: t.join(timeout_seconds) except Exception: pass with hierarchical_timer("trainer_threads") as main_timer_node: for trainer_thread in self.trainer_threads: thread_timer_stack = get_timer_stack_for_thread(trainer_thread) if thread_timer_stack: main_timer_node.merge( thread_timer_stack.root, root_name="thread_root", is_parallel=True, ) merge_gauges(thread_timer_stack.gauges) def trainer_update_func(self, trainer: Trainer) -> None: while not self.kill_trainers: with hierarchical_timer("trainer_advance"): trainer.advance()
ml-agents/ml-agents/mlagents/trainers/trainer_controller.py/0
{ "file_path": "ml-agents/ml-agents/mlagents/trainers/trainer_controller.py", "repo_id": "ml-agents", "token_count": 5014 }
2,053
import argparse from mlagents_envs.environment import UnityEnvironment from mlagents_envs.side_channel.engine_configuration_channel import ( EngineConfigurationChannel, ) def test_run_environment(env_name): """ Run the low-level API test using the specified environment :param env_name: Name of the Unity environment binary to launch """ engine_configuration_channel = EngineConfigurationChannel() env = UnityEnvironment( file_name=env_name, side_channels=[engine_configuration_channel], no_graphics=True, additional_args=["-logFile", "-"], ) try: # Reset the environment env.reset() # Set the default brain to work with group_name = list(env.behavior_specs.keys())[0] group_spec = env.behavior_specs[group_name] # Set the time scale of the engine engine_configuration_channel.set_configuration_parameters(time_scale=3.0) # Get the state of the agents decision_steps, terminal_steps = env.get_steps(group_name) # Examine the number of observations per Agent print("Number of observations : ", len(group_spec.observation_specs)) for obs_spec in group_spec.observation_specs: # Make sure the name was set in the ObservationSpec assert bool(obs_spec.name) is True, f'obs_spec.name="{obs_spec.name}"' # Is there a visual observation ? vis_obs = any( len(obs_spec.shape) == 3 for obs_spec in group_spec.observation_specs ) print("Is there a visual observation ?", vis_obs) # Examine the state space for the first observation for the first agent print(f"First Agent observation looks like: \n{decision_steps.obs[0][0]}") for _episode in range(10): env.reset() decision_steps, terminal_steps = env.get_steps(group_name) done = False episode_rewards = 0 tracked_agent = -1 while not done: action_tuple = group_spec.action_spec.random_action(len(decision_steps)) if tracked_agent == -1 and len(decision_steps) >= 1: tracked_agent = decision_steps.agent_id[0] env.set_actions(group_name, action_tuple) env.step() decision_steps, terminal_steps = env.get_steps(group_name) done = False if tracked_agent in decision_steps: episode_rewards += decision_steps[tracked_agent].reward if tracked_agent in terminal_steps: episode_rewards += terminal_steps[tracked_agent].reward done = True print(f"Total reward this episode: {episode_rewards}") finally: env.close() def test_closing(env_name): """ Run the low-level API and close the environment :param env_name: Name of the Unity environment binary to launch """ try: env1 = UnityEnvironment( file_name=env_name, base_port=5006, no_graphics=True, additional_args=["-logFile", "-"], ) env1.close() env1 = UnityEnvironment( file_name=env_name, base_port=5006, no_graphics=True, additional_args=["-logFile", "-"], ) env2 = UnityEnvironment( file_name=env_name, base_port=5007, no_graphics=True, additional_args=["-logFile", "-"], ) env2.reset() finally: env1.close() env2.close() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--env", default="artifacts/testPlayer") args = parser.parse_args() test_run_environment(args.env) test_closing(args.env)
ml-agents/ml-agents/tests/yamato/scripts/run_llapi.py/0
{ "file_path": "ml-agents/ml-agents/tests/yamato/scripts/run_llapi.py", "repo_id": "ml-agents", "token_count": 1719 }
2,054
syntax = "proto3"; option csharp_namespace = "Unity.MLAgents.CommunicatorObjects"; package communicator_objects; message EngineConfigurationProto { int32 width = 1; int32 height = 2; int32 quality_level = 3; float time_scale = 4; int32 target_frame_rate = 5; bool show_monitor = 6; }
ml-agents/protobuf-definitions/proto/mlagents_envs/communicator_objects/engine_configuration.proto/0
{ "file_path": "ml-agents/protobuf-definitions/proto/mlagents_envs/communicator_objects/engine_configuration.proto", "repo_id": "ml-agents", "token_count": 115 }
2,055
fileFormatVersion: 2 guid: 6e1b2e17cce240d4c8ff5457ac996e0d timeCreated: 1451443249 licenseType: Pro PluginImporter: serializedVersion: 1 iconMap: {} executionOrder: {} isPreloaded: 0 platformData: Android: enabled: 1 settings: CPU: ARMv7 Any: enabled: 0 settings: {} Editor: enabled: 0 settings: DefaultValueInitialized: true userData: assetBundleName: assetBundleVariant:
xLua/Assets/Plugins/Android/libs/armeabi-v7a/libxlua.so.meta/0
{ "file_path": "xLua/Assets/Plugins/Android/libs/armeabi-v7a/libxlua.so.meta", "repo_id": "xLua", "token_count": 200 }
2,056
extern "C" { #include "../../../WebGLPlugins/lapi.c" #include "../../../WebGLPlugins/lauxlib.c" #include "../../../WebGLPlugins/lbaselib.c" #include "../../../WebGLPlugins/lbitlib.c" #include "../../../WebGLPlugins/lcode.c" #include "../../../WebGLPlugins/lcorolib.c" #include "../../../WebGLPlugins/lctype.c" #include "../../../WebGLPlugins/ldblib.c" #include "../../../WebGLPlugins/ldebug.c" #include "../../../WebGLPlugins/ldo.c" #include "../../../WebGLPlugins/ldump.c" #include "../../../WebGLPlugins/lfunc.c" #include "../../../WebGLPlugins/lgc.c" #include "../../../WebGLPlugins/linit.c" #include "../../../WebGLPlugins/liolib.c" #include "../../../WebGLPlugins/llex.c" #include "../../../WebGLPlugins/lmathlib.c" #include "../../../WebGLPlugins/lmem.c" #include "../../../WebGLPlugins/loadlib.c" #include "../../../WebGLPlugins/lobject.c" #include "../../../WebGLPlugins/lopcodes.c" #include "../../../WebGLPlugins/loslib.c" #include "../../../WebGLPlugins/lparser.c" #include "../../../WebGLPlugins/lstate.c" #include "../../../WebGLPlugins/lstring.c" #include "../../../WebGLPlugins/lstrlib.c" #include "../../../WebGLPlugins/ltable.c" #include "../../../WebGLPlugins/ltablib.c" #include "../../../WebGLPlugins/ltm.c" #include "../../../WebGLPlugins/lundump.c" #include "../../../WebGLPlugins/lutf8lib.c" #include "../../../WebGLPlugins/lvm.c" #include "../../../WebGLPlugins/lzio.c" #include "../../../WebGLPlugins/i64lib.c" #include "../../../WebGLPlugins/perflib.c" #include "../../../WebGLPlugins/xlua.c" }
xLua/Assets/Plugins/WebGL/xlua_webgl.cpp/0
{ "file_path": "xLua/Assets/Plugins/WebGL/xlua_webgl.cpp", "repo_id": "xLua", "token_count": 641 }
2,057
fileFormatVersion: 2 guid: 1055830ddb882704fa71275ed9b2a78d timeCreated: 1488352111 licenseType: Pro PluginImporter: serializedVersion: 1 iconMap: {} executionOrder: {} isPreloaded: 0 platformData: Android: enabled: 0 settings: CPU: AnyCPU Any: enabled: 0 settings: {} Editor: enabled: 1 settings: CPU: x86_64 DefaultValueInitialized: true OS: AnyOS Linux: enabled: 0 settings: CPU: None Linux64: enabled: 1 settings: CPU: x86_64 LinuxUniversal: enabled: 1 settings: CPU: x86_64 OSXIntel: enabled: 0 settings: CPU: None OSXIntel64: enabled: 0 settings: CPU: None OSXUniversal: enabled: 0 settings: CPU: None WP8: enabled: 0 settings: CPU: AnyCPU DontProcess: False PlaceholderPath: Win: enabled: 0 settings: CPU: None Win64: enabled: 1 settings: CPU: AnyCPU WindowsStoreApps: enabled: 0 settings: CPU: AnyCPU DontProcess: False PlaceholderPath: SDK: AnySDK iOS: enabled: 0 settings: CompileFlags: FrameworkDependencies: userData: assetBundleName: assetBundleVariant:
xLua/Assets/Plugins/x86_64/libxlua.so.meta/0
{ "file_path": "xLua/Assets/Plugins/x86_64/libxlua.so.meta", "repo_id": "xLua", "token_count": 698 }
2,058
fileFormatVersion: 2 guid: 13b04a36211388b45849c1fb7dd7b956 timeCreated: 1463554448 licenseType: Pro TextScriptImporter: userData: assetBundleName: assetBundleVariant:
xLua/Assets/XLua/Examples/06_Coroutine/Resources/coruntine_test.lua.txt.meta/0
{ "file_path": "xLua/Assets/XLua/Examples/06_Coroutine/Resources/coruntine_test.lua.txt.meta", "repo_id": "xLua", "token_count": 70 }
2,059
fileFormatVersion: 2 guid: 40d0922483b73c8408f163088c9adc26 TextScriptImporter: userData:
xLua/Assets/XLua/Examples/07_AsyncTest/Resources/async_test.lua.txt.meta/0
{ "file_path": "xLua/Assets/XLua/Examples/07_AsyncTest/Resources/async_test.lua.txt.meta", "repo_id": "xLua", "token_count": 41 }
2,060
using UnityEngine; using System.Collections; using XLua; using System.IO; namespace XLuaTest { public class SignatureLoaderTest : MonoBehaviour { public static string PUBLIC_KEY = "BgIAAACkAABSU0ExAAQAAAEAAQBVDDC5QJ+0uSCJA+EysIC9JBzIsd6wcXa+FuTGXcsJuwyUkabwIiT2+QEjP454RwfSQP8s4VZE1m4npeVD2aDnY4W6ZNJe+V+d9Drt9b+9fc/jushj/5vlEksGBIIC/plU4ZaR6/nDdMIs/JLvhN8lDQthwIYnSLVlPmY1Wgyatw=="; // Use this for initialization void Start() { LuaEnv luaenv = new LuaEnv(); #if UNITY_EDITOR luaenv.AddLoader(new SignatureLoader(PUBLIC_KEY, (ref string filepath) => { filepath = Application.dataPath + "/XLua/Examples/10_SignatureLoader/" + filepath.Replace('.', '/') + ".lua"; if (File.Exists(filepath)) { return File.ReadAllBytes(filepath); } else { return null; } })); #else //为了让手机也能测试 luaenv.AddLoader(new SignatureLoader(PUBLIC_KEY, (ref string filepath) => { filepath = filepath.Replace('.', '/') + ".lua"; TextAsset file = (TextAsset)Resources.Load(filepath); if (file != null) { return file.bytes; } else { return null; } })); #endif luaenv.DoString(@" require 'signatured1' require 'signatured2' "); luaenv.Dispose(); } // Update is called once per frame void Update() { } } }
xLua/Assets/XLua/Examples/10_SignatureLoader/SignatureLoaderTest.cs/0
{ "file_path": "xLua/Assets/XLua/Examples/10_SignatureLoader/SignatureLoaderTest.cs", "repo_id": "xLua", "token_count": 968 }
2,061
fileFormatVersion: 2 guid: c9d3a7e24d889a7418ad19a390178f88 timeCreated: 1489370693 licenseType: Pro DefaultImporter: userData: assetBundleName: assetBundleVariant:
xLua/Assets/XLua/Examples/10_SignatureLoader/signatured1.lua.meta/0
{ "file_path": "xLua/Assets/XLua/Examples/10_SignatureLoader/signatured1.lua.meta", "repo_id": "xLua", "token_count": 72 }
2,062
fileFormatVersion: 2 guid: 266e4ca9a64f701449b0468b9a4f1d32 folderAsset: yes timeCreated: 1531790107 licenseType: Free DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
xLua/Assets/XLua/Examples/13_BuildFromCLI/Editor.meta/0
{ "file_path": "xLua/Assets/XLua/Examples/13_BuildFromCLI/Editor.meta", "repo_id": "xLua", "token_count": 84 }
2,063
fileFormatVersion: 2 guid: e0924e56a40ddb34e9b004c2056288fa folderAsset: yes timeCreated: 1463477791 licenseType: Pro DefaultImporter: userData: assetBundleName: assetBundleVariant:
xLua/Assets/XLua/Resources/xlua.meta/0
{ "file_path": "xLua/Assets/XLua/Resources/xlua.meta", "repo_id": "xLua", "token_count": 76 }
2,064
using UnityEngine; using System.Collections.Generic; using XLua; using System.IO; using System.Text; using System.Linq; using CSObjectWrapEditor; public class LinkXmlGen : ScriptableObject { public TextAsset Template; public static IEnumerable<CustomGenTask> GetTasks(LuaEnv lua_env, UserConfig user_cfg) { LuaTable data = lua_env.NewTable(); var assembly_infos = (from type in (user_cfg.ReflectionUse.Concat(user_cfg.LuaCallCSharp)) group type by type.Assembly.GetName().Name into assembly_info select new { FullName = assembly_info.Key, Types = assembly_info.ToList()}).ToList(); data.Set("assembly_infos", assembly_infos); yield return new CustomGenTask { Data = data, Output = new StreamWriter(GeneratorConfig.common_path + "/link.xml", false, Encoding.UTF8) }; } [GenCodeMenu]//加到Generate Code菜单里头 public static void GenLinkXml() { Generator.CustomGen(ScriptableObject.CreateInstance<LinkXmlGen>().Template.text, GetTasks); } }
xLua/Assets/XLua/Src/Editor/LinkXmlGen/LinkXmlGen.cs/0
{ "file_path": "xLua/Assets/XLua/Src/Editor/LinkXmlGen/LinkXmlGen.cs", "repo_id": "xLua", "token_count": 479 }
2,065
fileFormatVersion: 2 guid: ae16c73aad9a21a44aef65decb7e4928 timeCreated: 1481620508 licenseType: Pro TextScriptImporter: userData: assetBundleName: assetBundleVariant:
xLua/Assets/XLua/Src/Editor/Template/LuaEnumWrap.tpl.txt.meta/0
{ "file_path": "xLua/Assets/XLua/Src/Editor/Template/LuaEnumWrap.tpl.txt.meta", "repo_id": "xLua", "token_count": 73 }
2,066
fileFormatVersion: 2 guid: 4898604144dd928468ddca1af81d58ae timeCreated: 1501232546 licenseType: Pro MonoImporter: serializedVersion: 2 defaultReferences: - LuaClassWrap: {fileID: 4900000, guid: 8503038eabbabe44dac0f5f749d4411a, type: 3} - LuaClassWrapGCM: {fileID: 4900000, guid: 2bd79d95fd859724283926ad8fa4df30, type: 3} - LuaDelegateBridge: {fileID: 4900000, guid: 3d992756e2469044484be75f78e4e556, type: 3} - LuaDelegateWrap: {fileID: 4900000, guid: 33b33e1cd617f794b8c801a32f3b2539, type: 3} - LuaEnumWrap: {fileID: 4900000, guid: ae16c73aad9a21a44aef65decb7e4928, type: 3} - LuaEnumWrapGCM: {fileID: 4900000, guid: ea84a5ee7abf8e347a810eb7848add46, type: 3} - LuaInterfaceBridge: {fileID: 4900000, guid: 7165d08e91378494dadeb10e5338accb, type: 3} - LuaRegister: {fileID: 4900000, guid: e416b82ec9fe340458f97cf1e3468ef7, type: 3} - LuaRegisterGCM: {fileID: 4900000, guid: 46c7366d55afbf1459674448d92c44c8, type: 3} - LuaWrapPusher: {fileID: 4900000, guid: d1a916469d261d447972d287b6c5b7a0, type: 3} - PackUnpack: {fileID: 4900000, guid: c9ef7e8f2a3b37744aad49b99370c16b, type: 3} - TemplateCommon: {fileID: 4900000, guid: cb41d53afe75a9443b182e284298feeb, type: 3} executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
xLua/Assets/XLua/Src/Editor/TemplateRef.cs.meta/0
{ "file_path": "xLua/Assets/XLua/Src/Editor/TemplateRef.cs.meta", "repo_id": "xLua", "token_count": 601 }
2,067
fileFormatVersion: 2 guid: 5dfa9c69dddc18849bd3c1dfc4ac42de timeCreated: 1489222429 licenseType: Pro MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
xLua/Assets/XLua/Src/SignatureLoader.cs.meta/0
{ "file_path": "xLua/Assets/XLua/Src/SignatureLoader.cs.meta", "repo_id": "xLua", "token_count": 102 }
2,068
fileFormatVersion: 2 guid: 74a487ac941ce7b478428f413acc20f6 folderAsset: yes timeCreated: 1455708477 licenseType: Pro DefaultImporter: userData: assetBundleName: assetBundleVariant:
xLua/Assets/XLua/Tutorial/LoadLuaScript.meta/0
{ "file_path": "xLua/Assets/XLua/Tutorial/LoadLuaScript.meta", "repo_id": "xLua", "token_count": 74 }
2,069
using System; using System.Linq; using System.Reflection; using CSObjectWrapEditor; using System.IO; using System.Collections.Generic; namespace XLua { public class XLuaGenerate { public static void Useage() { Console.WriteLine("XLuaGenerate assmbly_path"); } public static void Main(string[] args) { if (args.Length == 0) { Useage(); return; } List<string> assemblyPathList = args.TakeWhile(path => path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)).ToList(); if (args.Length > assemblyPathList.Count) { GeneratorConfig.common_path = args[assemblyPathList.Count]; } if (args.Length > assemblyPathList.Count + 1) { List<string> search_paths = args.Skip(assemblyPathList.Count + 1).ToList(); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler((object sender, ResolveEventArgs rea) => { foreach (var search_path in search_paths) { string assemblyPath = Path.Combine(search_path, new AssemblyName(rea.Name).Name + ".dll"); if (File.Exists(assemblyPath)) { return Assembly.Load(File.ReadAllBytes(assemblyPath)); } } return null; }); } var allTypes = assemblyPathList.Select(path => Assembly.Load(File.ReadAllBytes(Path.GetFullPath(path)))) .SelectMany(assembly => assembly.GetTypes()); Generator.GenAll(new XLuaTemplates() { LuaClassWrap = new XLuaTemplate() { name = "LuaClassWrap", text = global::XLuaGenerate.Src.XLuaTemplates.LuaClassWrap_tpl, }, LuaDelegateBridge = new XLuaTemplate() { name = "LuaDelegateBridge", text = global::XLuaGenerate.Src.XLuaTemplates.LuaDelegateBridge_tpl, }, LuaDelegateWrap = new XLuaTemplate() { name = "LuaDelegateWrap", text = global::XLuaGenerate.Src.XLuaTemplates.LuaDelegateWrap_tpl, }, LuaEnumWrap = new XLuaTemplate() { name = "LuaEnumWrap", text = global::XLuaGenerate.Src.XLuaTemplates.LuaEnumWrap_tpl, }, LuaInterfaceBridge = new XLuaTemplate() { name = "LuaInterfaceBridge", text = global::XLuaGenerate.Src.XLuaTemplates.LuaInterfaceBridge_tpl, }, LuaRegister = new XLuaTemplate() { name = "LuaRegister", text = global::XLuaGenerate.Src.XLuaTemplates.LuaRegister_tpl, }, LuaWrapPusher = new XLuaTemplate() { name = "LuaWrapPusher", text = global::XLuaGenerate.Src.XLuaTemplates.LuaWrapPusher_tpl, }, PackUnpack = new XLuaTemplate() { name = "PackUnpack", text = global::XLuaGenerate.Src.XLuaTemplates.PackUnpack_tpl, }, TemplateCommon = new XLuaTemplate() { name = "TemplateCommon", text = global::XLuaGenerate.Src.XLuaTemplates.TemplateCommon_lua, }, }, allTypes); } } }
xLua/General/Src/XLuaGenerate.cs/0
{ "file_path": "xLua/General/Src/XLuaGenerate.cs", "repo_id": "xLua", "token_count": 2183 }
2,070
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{7F2D7E42-6B90-0DE7-1416-469D0058D969}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>XLuaUnitTest</RootNamespace> <AssemblyName>XLuaUnitTest</AssemblyName> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>..\Bin\</OutputPath> <BaseIntermediateOutputPath>obj\Any CPU\Debug\XLuaUnitTest\</BaseIntermediateOutputPath> <IntermediateOutputPath>$(BaseIntermediateOutputPath)</IntermediateOutputPath> <DefineConstants>_DEBUG;DEBUG;TRACE;;XLUA_GENERAL</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PlatformTarget>AnyCPU</PlatformTarget> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>..\Bin\</OutputPath> <BaseIntermediateOutputPath>obj\Any CPU\Release\XLuaUnitTest\</BaseIntermediateOutputPath> <IntermediateOutputPath>$(BaseIntermediateOutputPath)</IntermediateOutputPath> <DefineConstants>;XLUA_GENERAL</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Compile Include="..\Src\XLuaUnitTest.cs"> <Link>Src\XLuaUnitTest.cs</Link> </Compile> <Compile Include="..\..\Test\UnitTest\xLuaTest\CSharpCallLua\CSObjectForTestCSCallLua.cs"> <Link>Test\UnitTest\xLuaTest\CSharpCallLua\CSObjectForTestCSCallLua.cs</Link> </Compile> <Compile Include="..\..\Test\UnitTest\xLuaTest\CSharpCallLua\TCForTestCSCallLua.cs"> <Link>Test\UnitTest\xLuaTest\CSharpCallLua\TCForTestCSCallLua.cs</Link> </Compile> <Compile Include="..\..\Test\UnitTest\xLuaTest\CSharpCallLua\TestCSCallLua.cs"> <Link>Test\UnitTest\xLuaTest\CSharpCallLua\TestCSCallLua.cs</Link> </Compile> <Compile Include="..\..\Test\UnitTest\xLuaTest\LuaCallCS\CSObjectForLuaCallCS.cs"> <Link>Test\UnitTest\xLuaTest\LuaCallCS\CSObjectForLuaCallCS.cs</Link> </Compile> <Compile Include="..\..\Test\UnitTest\xLuaTest\LuaTestCommon.cs"> <Link>Test\UnitTest\xLuaTest\LuaTestCommon.cs</Link> </Compile> <Compile Include="..\..\Test\UnitTest\xLuaTest\LuaTestObj.cs"> <Link>Test\UnitTest\xLuaTest\LuaTestObj.cs</Link> </Compile> <Compile Include="..\..\Test\UnitTest\xLuaTest\LuaTestObjReflect.cs"> <Link>Test\UnitTest\xLuaTest\LuaTestObjReflect.cs</Link> </Compile> <Compile Include="..\..\Test\UnitTest\xLuaTest\Main.cs"> <Link>Test\UnitTest\xLuaTest\Main.cs</Link> </Compile> </ItemGroup> <ItemGroup> <ProjectReference Include="XLua.Mini.csproj"> <Project>{9A2C7D34-0697-31AB-4FD5-E250BB7E0F00}</Project> <Name>XLua.Mini</Name> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
xLua/General/vs2013/XLuaUnitTest.csproj/0
{ "file_path": "xLua/General/vs2013/XLuaUnitTest.csproj", "repo_id": "xLua", "token_count": 1573 }
2,071
require("ltest.init") function islua53() return not not math.type end -- for test case CMyTestCaseCSCallLua = TestCase:new() function CMyTestCaseCSCallLua:new(oo) local o = oo or {} o.count = 1 setmetatable(o, self) self.__index = self return o end function CMyTestCaseCSCallLua.SetUpTestCase(self) self.count = 1 + self.count self.tcForTestCSCallLuaObj = CS.TCForTestCSCallLua() print("CMyTestCaseCSCallLua.SetUpTestCase") end function CMyTestCaseCSCallLua.TearDownTestCase(self) self.count = 1 + self.count print("CMyTestCaseCSCallLua.TearDownTestCase") end function CMyTestCaseCSCallLua.SetUp(self) self.count = 1 + self.count print("CMyTestCaseCSCallLua.SetUp") end function CMyTestCaseCSCallLua.TearDown(self) self.count = 1 + self.count print("CMyTestCaseCSCallLua.TearDown") end function CMyTestCaseCSCallLua.testDoString2LoadLua_Step_1(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testDoString2LoadLua_Step_1() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testDoString2LoadLua_Step_2(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testDoString2LoadLua_Step_2() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testDoString2LoadLua_Step_3(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testDoString2LoadLua_Step_3() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testRequire2LoadLua_Step_1_3(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testRequire2LoadLua_Step_1_3() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testRequire2LoadLua_Step_4(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testRequire2LoadLua_Step_4() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testRequire2LoadLua_Step_5(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testRequire2LoadLua_Step_5() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testRequire2LoadLua_Step_6(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testRequire2LoadLua_Step_6() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testRequire2LoadLua_Step_7(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testRequire2LoadLua_Step_7() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testAddLoader2LoadLua_Step_1_2(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testAddLoader2LoadLua_Step_1_2() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testAddLoader2LoadLua_Step_3(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testAddLoader2LoadLua_Step_3() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testAddLoader2LoadLua_Step_6(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testAddLoader2LoadLua_Step_6() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testAddLoader2LoadLua_Step_7(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testAddLoader2LoadLua_Step_7() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetBasicDataTypeBool_Step_1(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetBasicDataTypeBool_Step_1() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetBasicDataTypeString_Step_2(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetBasicDataTypeString_Step_2() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetBasicDataTypeNumberToByte(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetBasicDataTypeNumberToByte() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetBasicDataTypeNumberToSByte(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetBasicDataTypeNumberToSByte() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetBasicDataTypeNumberToShort(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetBasicDataTypeNumberToShort() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetBasicDataTypeNumberToUShort(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetBasicDataTypeNumberToUShort() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetBasicDataTypeNumberToInt(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetBasicDataTypeNumberToInt() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetBasicDataTypeNumberToUInt(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetBasicDataTypeNumberToUInt() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetBasicDataTypeNumberToLong(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetBasicDataTypeNumberToLong() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetBasicDataTypeNumberToULong(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetBasicDataTypeNumberToULong() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetBasicDataTypeNumberToDouble(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetBasicDataTypeNumberToDouble() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetBasicDataTypeNumberToChar(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetBasicDataTypeNumberToChar() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetBasicDataTypeNumberToFloat(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetBasicDataTypeNumberToFloat() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetBasicDataTypeNumberToDecimal(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetBasicDataTypeNumberToDecimal() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetBasicDataType_Step_4(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetBasicDataType_Step_4() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetBasicDataType_Step_5(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetBasicDataType_Step_5() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToClass_Step_1(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToClass_Step_1() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToClass_Step_2(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToClass_Step_2() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToClass_Step_3(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToClass_Step_3() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToClass_Step_4(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToClass_Step_4() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToClass_Step_5(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToClass_Step_5() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToClass_Step_1_1(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToClass_Step_1_1() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToClass_Step_1_3(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToClass_Step_1_3() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToClass_Step_1_4(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToClass_Step_1_4() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToInterface_Step_6(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToInterface_Step_6() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToInterface_Step_7(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToInterface_Step_7() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToInterface_Step_8(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToInterface_Step_8() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToInterface_Step_9(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToInterface_Step_9() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToInterface_Step_6_1(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToInterface_Step_6_1() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToDic_Step_10(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToDic_Step_10() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToDic_Step_11_1(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToDic_Step_11_1() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToDic_Step_11_2(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToDic_Step_11_2() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToDic_Step_11_3(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToDic_Step_11_3() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToList_Step_12(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToList_Step_12() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToList_Step_13_1_int(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToList_Step_13_1_int() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToList_Step_13_1_string(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToList_Step_13_1_string() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToList_Step_13_2(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToList_Step_13_2() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetTableToLuaTable_Step_14(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetTableToLuaTable_Step_14() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetFuncToDelegate_Step_1(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToDelegate_Step_1() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetFuncToDelegate_Step_2_1(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToDelegate_Step_2_1() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetFuncToDelegate_Step_2_2(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToDelegate_Step_2_2() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetFuncToDelegate_Step_2_3(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToDelegate_Step_2_3() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetFuncToDelegate_Step_2_4(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToDelegate_Step_2_4() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetFuncToDelegate_Step_3(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToDelegate_Step_3() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetFuncToDelegate_Step_5(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToDelegate_Step_5() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetFuncToDelegate_Step_5_1(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToDelegate_Step_5_1() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetFuncToDelegate_Step_5_1_0(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToDelegate_Step_5_1_0() print(ret.msg) ASSERT_EQ(ret.result, true) end --[[ ios上il2cpp编译有错,注释掉 function CMyTestCaseCSCallLua.testGetFuncToDelegate_Step_5_2(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToDelegate_Step_5_2() ASSERT_EQ(ret.result, true) end ]] function CMyTestCaseCSCallLua.testGetFuncToDelegate_Step_6(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToDelegate_Step_6() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetFuncToLuaFunc_Step_8(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToLuaFunc_Step_8() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetFuncToLuaFunc_Step_9_1(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToLuaFunc_Step_9_1() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetFuncToLuaFunc_Step_10(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToLuaFunc_Step_10() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetFuncToLuaFunc_Step_12(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToLuaFunc_Step_12() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetFuncToLuaFunc_Step_13(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToLuaFunc_Step_13() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetFuncToDelegate_Step_7_1(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToDelegate_Step_7_1() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testGetFuncToDelegate_Step_7_2(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToDelegate_Step_7_2() print(ret.msg) if islua53() then --ASSERT_EQ(false, false) --该用例在lua5.3无意义 ASSERT_EQ(ret.result, true) else ASSERT_EQ(ret.result, true) end end function CMyTestCaseCSCallLua.testGetFuncToDelegate_Step_7_3(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testGetFuncToDelegate_Step_7_3() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_BasicType_int_1(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_BasicType_int_1() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_BasicType_int_2(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_BasicType_int_2() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_BasicType_string_1(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_BasicType_string_1() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_BasicType_sbyte(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_BasicType_sbyte() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_BasicType_byte(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_BasicType_byte() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_BasicType_short(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_BasicType_short() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_BasicType_ushort(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_BasicType_ushort() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_BasicType_long(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_BasicType_long() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_BasicType_ulong(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_BasicType_ulong() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_BasicType_double(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_BasicType_double() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_BasicType_float(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_BasicType_float() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_BasicType_char(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_BasicType_char() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_BasicType_decimal(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_BasicType_decimal() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_struct(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_struct() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_class(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_class() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_interface(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_interface() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_dict(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_dict() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_list(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_list() print(ret.msg) ASSERT_EQ(ret.result, true) end function CMyTestCaseCSCallLua.testLuaTableGetSetKeyValue_delegate(self) self.count = 1 + self.count local ret = self.tcForTestCSCallLuaObj:testLuaTableGetSetKeyValue_delegate() print(ret.msg) ASSERT_EQ(ret.result, true) end
xLua/Test/UnitTest/StreamingAssets/csCallLua.lua/0
{ "file_path": "xLua/Test/UnitTest/StreamingAssets/csCallLua.lua", "repo_id": "xLua", "token_count": 8399 }
2,072
fileFormatVersion: 2 guid: fa1392032a89cd8489d1e9d150190b68 timeCreated: 1483528414 licenseType: Pro DefaultImporter: userData: assetBundleName: assetBundleVariant:
xLua/Test/UnitTest/StreamingAssets/luaTdrTest.lua.meta/0
{ "file_path": "xLua/Test/UnitTest/StreamingAssets/luaTdrTest.lua.meta", "repo_id": "xLua", "token_count": 70 }
2,073
#if !XLUA_GENERAL using UnityEngine; #endif using System.Collections; using System.Collections.Generic; using XLua; using System; public class TestCSCallLua #if !XLUA_GENERAL : MonoBehaviour #endif { // Use this for initialization void Start() { TCForTestCSCallLua testSuite = new TCForTestCSCallLua(); testSuite.testDoString2LoadLua_Step_1(); testSuite.testDoString2LoadLua_Step_2 (); testSuite.testDoString2LoadLua_Step_3 (); testSuite.testRequire2LoadLua_Step_1_3 (); testSuite.testRequire2LoadLua_Step_4 (); testSuite.testRequire2LoadLua_Step_5 (); testSuite.testRequire2LoadLua_Step_6 (); testSuite.testRequire2LoadLua_Step_7 (); testSuite.testAddLoader2LoadLua_Step_1_2 (); testSuite.testAddLoader2LoadLua_Step_3 (); testSuite.testAddLoader2LoadLua_Step_6 (); testSuite.testAddLoader2LoadLua_Step_7 (); testSuite.testGetBasicDataTypeBool_Step_1 (); testSuite.testGetBasicDataTypeString_Step_2 (); testSuite.testGetBasicDataTypeNumberToByte (); testSuite.testGetBasicDataTypeNumberToSByte (); testSuite.testGetBasicDataTypeNumberToShort (); testSuite.testGetBasicDataTypeNumberToUShort (); testSuite.testGetBasicDataTypeNumberToInt (); testSuite.testGetBasicDataTypeNumberToUInt (); testSuite.testGetBasicDataTypeNumberToLong (); testSuite.testGetBasicDataTypeNumberToULong (); testSuite.testGetBasicDataTypeNumberToDouble (); testSuite.testGetBasicDataTypeNumberToChar (); testSuite.testGetBasicDataTypeNumberToFloat(); testSuite.testGetBasicDataTypeNumberToDecimal (); testSuite.testGetBasicDataType_Step_4 (); testSuite.testGetBasicDataType_Step_5 (); testSuite.testGetTableToClass_Step_1 (); testSuite.testGetTableToClass_Step_2 (); testSuite.testGetTableToClass_Step_3 (); testSuite.testGetTableToClass_Step_4 (); testSuite.testGetTableToClass_Step_5 (); testSuite.testGetTableToClass_Step_1_1 (); testSuite.testGetTableToClass_Step_1_3 (); testSuite.testGetTableToClass_Step_1_4 (); testSuite.testGetTableToInterface_Step_6 (); testSuite.testGetTableToInterface_Step_7 (); testSuite.testGetTableToInterface_Step_8 (); testSuite.testGetTableToInterface_Step_9 (); testSuite.testGetTableToInterface_Step_6_1 (); testSuite.testGetTableToDic_Step_10 (); testSuite.testGetTableToDic_Step_11_1 (); testSuite.testGetTableToDic_Step_11_2 (); testSuite.testGetTableToDic_Step_11_3 (); testSuite.testGetTableToList_Step_12 (); testSuite.testGetTableToList_Step_13_1_int (); testSuite.testGetTableToList_Step_13_1_string (); testSuite.testGetTableToList_Step_13_2 (); testSuite.testGetTableToLuaTable_Step_14 (); testSuite.testGetFuncToDelegate_Step_1 (); testSuite.testGetFuncToDelegate_Step_2_1 (); testSuite.testGetFuncToDelegate_Step_2_2 (); testSuite.testGetFuncToDelegate_Step_2_3 (); testSuite.testGetFuncToDelegate_Step_2_4 (); testSuite.testGetFuncToDelegate_Step_3 (); testSuite.testGetFuncToDelegate_Step_5 (); testSuite.testGetFuncToDelegate_Step_5_1 (); testSuite.testGetFuncToDelegate_Step_5_1_0 (); //testSuite.testGetFuncToDelegate_Step_5_2 (); // 在ios il2cpp上运行错误,注释掉 testSuite.testGetFuncToDelegate_Step_6 (); testSuite.testGetFuncToLuaFunc_Step_8 (); testSuite.testGetFuncToLuaFunc_Step_9_1 (); testSuite.testGetFuncToLuaFunc_Step_10 (); testSuite.testGetFuncToLuaFunc_Step_12 (); testSuite.testGetFuncToLuaFunc_Step_13 (); } // Update is called once per frame void Update() { if (TCForTestCSCallLua.luaEnv != null) { TCForTestCSCallLua.luaEnv.GC(); } } }
xLua/Test/UnitTest/xLuaTest/CSharpCallLua/TestCSCallLua.cs/0
{ "file_path": "xLua/Test/UnitTest/xLuaTest/CSharpCallLua/TestCSCallLua.cs", "repo_id": "xLua", "token_count": 1457 }
2,074
<?xml version="1.0" ?> <metalib name="net" > <macro name="MAX_NAME_LEN" value="128" /> <macro name="MAX_PASS_LEN" value="32" /> <struct name="CmdLogin" version="1" id="1" > <entry name="name" type="string" id="1" defaultvalue="腾讯" size="MAX_NAME_LEN" sizeinfo="smalluint" /> <entry name="pass" type="string" id="2" size="MAX_PASS_LEN" /> <entry name="zone" type="string" id="3" size="MAX_PASS_LEN" /> <entry name="destIp" type="ip" id="4" version="2" defaultvalue="10.6.221.149" /> </struct> <macro name="MAX_ATTR_SIZE" value="3" /> <struct name="CmdLogout" version="2" id="2" > <entry name="reason" type="bigint" id="1" /> <entry name="count" type="int" id="2" defaultvalue="10" /> <entry name="attr" type="tinyint" id="3" count="MAX_ATTR_SIZE" refer="count" /> </struct> <struct name="TypeTester" sizeinfo="int" version="2" > <entry name="date" type="Date" id="10" /> <entry name="time" type="Time" id="20" defaultvalue="14:36:30" /> <entry name="int8" type="int8" id="30" version="3" /> <entry name="uint8Array" type="uint8" id="31" count="3" version="3" /> <entry name="int8VarArrayRefer" type="int" id="32" version="3" /> <entry name="int8VarArray" type="int8" id="33" count="3" refer="int8VarArrayRefer" version="3" /> <entry name="int" type="int" id="40" version="3" defaultvalue="0x7FFFFFFF" /> <entry name="uintArray" type="uint" id="41" count="3" version="3" /> <entry name="intVarArrayRefer" type="int" id="42" version="3" /> <entry name="intVarArray" type="int" id="43" count="3" refer="intVarArrayRefer" version="3" /> <entry name="strArray" type="string" id="50" count="2" size="16" version="3" /> <entry name="uint64" type="uint64" id="60" version="3" /> <entry name="int64Array" type="int64" id="61" count="3" version="3" /> <entry name="float" type="float" id="70" version="3" /> <entry name="floatArray" type="float" id="71" count="3" version="3" /> <entry name="double" type="double" id="80" version="3" /> <entry name="doubleArray" type="double" id="81" count="3" version="3" /> </struct> <struct name="InnerStruct" sizeinfo="int" version="2" > <entry name="uint64" type="uint64" id="1" /> <entry name="uint" type="uint" id="2" /> </struct> <struct name="InnerStructList" version="3" > <entry name="count" type="int" id="1" defaultvalue="2" /> <entry name="array" type="InnerStruct" count="3" refer="count" id="2" /> </struct> <union name="InnerUnion" version="3" > <entry name="field1" type="InnerStruct" count="2" id="1" /> <entry name="field2" type="InnerStruct" id="2" /> </union> <struct name="CmdXXX" sizeinfo="int" version="2" > <entry name="typeTester" type="TypeTester" id="1" /> <entry name="boundary" type="float" id="11" /> <entry name="selector" type="int" version="3" id="21" /> <entry name="innerUnion" type="InnerUnion" select="selector" version="3" id="22" sizeinfo="int" /> <entry name="structArray" type="InnerStructList" version="3" id="31" /> <entry name="boundary2" type="float" id="51" version="3" defaultvalue="-3.40282346e+38" /> </struct> <struct name="TestInnerStruct1" sizeinfo="int" version="2" > <entry name="int8" type="int8" id="1" /> <entry name="double" type="double" id="2" /> <entry name="float" type="float" id="3" /> <entry name="int16" type="int16" id="4" /> <entry name="int32Array" type="int32" count="3" id="5" /> </struct> <struct name="TestInnerStruct2" sizeinfo="int" version="2" > <entry name="double" type="double" id="1" /> <entry name="int8" type="int8" id="2" /> <entry name="int32Array" type="int32" count="3" id="10" /> <entry name="int16" type="int16" id="20" /> <entry name="float" type="float" id="21" /> </struct> <union name="TestUnion" version="3" > <entry name="field1" type="TestInnerStruct1" id="1" /> <entry name="field2" type="TestInnerStruct2" id="2" /> </union> <struct name="CmdOther" sizeinfo="int" version="2" > <entry name="int8" type="int8" id="1" /> <entry name="double" type="float" id="11" /> <entry name="selector" type="int" version="3" id="21" /> <entry name="testunion" type="TestUnion" select="selector" version="3" id="22" sizeinfo="int" /> </struct> <!-- Test version compatibility --> <struct name="TypeTesterPrevious" sizeinfo="int" version="2" > <entry name="date" type="Date" id="10" /> <entry name="time" type="Time" id="20" defaultvalue="14:36:30" /> </struct> <struct name="CmdXXXPrevious" sizeinfo="int" version="2" > <entry name="typeTester" type="TypeTesterPrevious" id="1" /> <entry name="boundary" type="float" id="11" /> </struct> </metalib>
xLua/Test/UnitTest/xLuaTest/Resources/non_tlv_net_msg_type.xml/0
{ "file_path": "xLua/Test/UnitTest/xLuaTest/Resources/non_tlv_net_msg_type.xml", "repo_id": "xLua", "token_count": 2292 }
2,075
/* ** $Id: lauxlib.c,v 1.289 2016/12/20 18:37:00 roberto Exp $ ** Auxiliary functions for building Lua libraries ** See Copyright Notice in lua.h */ #define lauxlib_c #define LUA_LIB #include "lprefix.h" #include <errno.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* ** This file uses only the official API of Lua. ** Any function declared here could be written as an application function. */ #include "lua.h" #include "lauxlib.h" /* ** {====================================================== ** Traceback ** ======================================================= */ #define LEVELS1 10 /* size of the first part of the stack */ #define LEVELS2 11 /* size of the second part of the stack */ /* ** search for 'objidx' in table at index -1. ** return 1 + string at top if find a good name. */ static int findfield (lua_State *L, int objidx, int level) { if (level == 0 || !lua_istable(L, -1)) return 0; /* not found */ lua_pushnil(L); /* start 'next' loop */ while (lua_next(L, -2)) { /* for each pair in table */ if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */ if (lua_rawequal(L, objidx, -1)) { /* found object? */ lua_pop(L, 1); /* remove value (but keep name) */ return 1; } else if (findfield(L, objidx, level - 1)) { /* try recursively */ lua_remove(L, -2); /* remove table (but keep name) */ lua_pushliteral(L, "."); lua_insert(L, -2); /* place '.' between the two names */ lua_concat(L, 3); return 1; } } lua_pop(L, 1); /* remove value */ } return 0; /* not found */ } /* ** Search for a name for a function in all loaded modules */ static int pushglobalfuncname (lua_State *L, lua_Debug *ar) { int top = lua_gettop(L); lua_getinfo(L, "f", ar); /* push function */ lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); if (findfield(L, top + 1, 2)) { const char *name = lua_tostring(L, -1); if (strncmp(name, "_G.", 3) == 0) { /* name start with '_G.'? */ lua_pushstring(L, name + 3); /* push name without prefix */ lua_remove(L, -2); /* remove original name */ } lua_copy(L, -1, top + 1); /* move name to proper place */ lua_pop(L, 2); /* remove pushed values */ return 1; } else { lua_settop(L, top); /* remove function and global table */ return 0; } } static void pushfuncname (lua_State *L, lua_Debug *ar) { if (pushglobalfuncname(L, ar)) { /* try first a global name */ lua_pushfstring(L, "function '%s'", lua_tostring(L, -1)); lua_remove(L, -2); /* remove name */ } else if (*ar->namewhat != '\0') /* is there a name from code? */ lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */ else if (*ar->what == 'm') /* main? */ lua_pushliteral(L, "main chunk"); else if (*ar->what != 'C') /* for Lua functions, use <file:line> */ lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined); else /* nothing left... */ lua_pushliteral(L, "?"); } static int lastlevel (lua_State *L) { lua_Debug ar; int li = 1, le = 1; /* find an upper bound */ while (lua_getstack(L, le, &ar)) { li = le; le *= 2; } /* do a binary search */ while (li < le) { int m = (li + le)/2; if (lua_getstack(L, m, &ar)) li = m + 1; else le = m; } return le - 1; } LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, const char *msg, int level) { lua_Debug ar; int top = lua_gettop(L); int last = lastlevel(L1); int n1 = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1; if (msg) lua_pushfstring(L, "%s\n", msg); luaL_checkstack(L, 10, NULL); lua_pushliteral(L, "stack traceback:"); while (lua_getstack(L1, level++, &ar)) { if (n1-- == 0) { /* too many levels? */ lua_pushliteral(L, "\n\t..."); /* add a '...' */ level = last - LEVELS2 + 1; /* and skip to last ones */ } else { lua_getinfo(L1, "Slnt", &ar); lua_pushfstring(L, "\n\t%s:", ar.short_src); if (ar.currentline > 0) lua_pushfstring(L, "%d:", ar.currentline); lua_pushliteral(L, " in "); pushfuncname(L, &ar); if (ar.istailcall) lua_pushliteral(L, "\n\t(...tail calls...)"); lua_concat(L, lua_gettop(L) - top); } } lua_concat(L, lua_gettop(L) - top); } /* }====================================================== */ /* ** {====================================================== ** Error-report functions ** ======================================================= */ LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) { lua_Debug ar; if (!lua_getstack(L, 0, &ar)) /* no stack frame? */ return luaL_error(L, "bad argument #%d (%s)", arg, extramsg); lua_getinfo(L, "n", &ar); if (strcmp(ar.namewhat, "method") == 0) { arg--; /* do not count 'self' */ if (arg == 0) /* error is in the self argument itself? */ return luaL_error(L, "calling '%s' on bad self (%s)", ar.name, extramsg); } if (ar.name == NULL) ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?"; return luaL_error(L, "bad argument #%d to '%s' (%s)", arg, ar.name, extramsg); } static int typeerror (lua_State *L, int arg, const char *tname) { const char *msg; const char *typearg; /* name for the type of the actual argument */ if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING) typearg = lua_tostring(L, -1); /* use the given type name */ else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA) typearg = "light userdata"; /* special name for messages */ else typearg = luaL_typename(L, arg); /* standard name */ msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg); return luaL_argerror(L, arg, msg); } static void tag_error (lua_State *L, int arg, int tag) { typeerror(L, arg, lua_typename(L, tag)); } /* ** The use of 'lua_pushfstring' ensures this function does not ** need reserved stack space when called. */ LUALIB_API void luaL_where (lua_State *L, int level) { lua_Debug ar; if (lua_getstack(L, level, &ar)) { /* check function at level */ lua_getinfo(L, "Sl", &ar); /* get info about it */ if (ar.currentline > 0) { /* is there info? */ lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline); return; } } lua_pushfstring(L, ""); /* else, no information available... */ } /* ** Again, the use of 'lua_pushvfstring' ensures this function does ** not need reserved stack space when called. (At worst, it generates ** an error with "stack overflow" instead of the given message.) */ LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) { va_list argp; va_start(argp, fmt); luaL_where(L, 1); lua_pushvfstring(L, fmt, argp); va_end(argp); lua_concat(L, 2); return lua_error(L); } LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) { int en = errno; /* calls to Lua API may change this value */ if (stat) { lua_pushboolean(L, 1); return 1; } else { lua_pushnil(L); if (fname) lua_pushfstring(L, "%s: %s", fname, strerror(en)); else lua_pushstring(L, strerror(en)); lua_pushinteger(L, en); return 3; } } #if !defined(l_inspectstat) /* { */ #if defined(LUA_USE_POSIX) #include <sys/wait.h> /* ** use appropriate macros to interpret 'pclose' return status */ #define l_inspectstat(stat,what) \ if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \ else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; } #else #define l_inspectstat(stat,what) /* no op */ #endif #endif /* } */ LUALIB_API int luaL_execresult (lua_State *L, int stat) { const char *what = "exit"; /* type of termination */ if (stat == -1) /* error? */ return luaL_fileresult(L, 0, NULL); else { l_inspectstat(stat, what); /* interpret result */ if (*what == 'e' && stat == 0) /* successful termination? */ lua_pushboolean(L, 1); else lua_pushnil(L); lua_pushstring(L, what); lua_pushinteger(L, stat); return 3; /* return true/nil,what,code */ } } /* }====================================================== */ /* ** {====================================================== ** Userdata's metatable manipulation ** ======================================================= */ LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { if (luaL_getmetatable(L, tname) != LUA_TNIL) /* name already in use? */ return 0; /* leave previous value on top, but return 0 */ lua_pop(L, 1); lua_createtable(L, 0, 2); /* create metatable */ lua_pushstring(L, tname); lua_setfield(L, -2, "__name"); /* metatable.__name = tname */ lua_pushvalue(L, -1); lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */ return 1; } LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) { luaL_getmetatable(L, tname); lua_setmetatable(L, -2); } LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) { void *p = lua_touserdata(L, ud); if (p != NULL) { /* value is a userdata? */ if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ luaL_getmetatable(L, tname); /* get correct metatable */ if (!lua_rawequal(L, -1, -2)) /* not the same? */ p = NULL; /* value is a userdata with wrong metatable */ lua_pop(L, 2); /* remove both metatables */ return p; } } return NULL; /* value is not a userdata with a metatable */ } LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { void *p = luaL_testudata(L, ud, tname); if (p == NULL) typeerror(L, ud, tname); return p; } /* }====================================================== */ /* ** {====================================================== ** Argument check functions ** ======================================================= */ LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def, const char *const lst[]) { const char *name = (def) ? luaL_optstring(L, arg, def) : luaL_checkstring(L, arg); int i; for (i=0; lst[i]; i++) if (strcmp(lst[i], name) == 0) return i; return luaL_argerror(L, arg, lua_pushfstring(L, "invalid option '%s'", name)); } /* ** Ensures the stack has at least 'space' extra slots, raising an error ** if it cannot fulfill the request. (The error handling needs a few ** extra slots to format the error message. In case of an error without ** this extra space, Lua will generate the same 'stack overflow' error, ** but without 'msg'.) */ LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) { if (!lua_checkstack(L, space)) { if (msg) luaL_error(L, "stack overflow (%s)", msg); else luaL_error(L, "stack overflow"); } } LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) { if (lua_type(L, arg) != t) tag_error(L, arg, t); } LUALIB_API void luaL_checkany (lua_State *L, int arg) { if (lua_type(L, arg) == LUA_TNONE) luaL_argerror(L, arg, "value expected"); } LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) { const char *s = lua_tolstring(L, arg, len); if (!s) tag_error(L, arg, LUA_TSTRING); return s; } LUALIB_API const char *luaL_optlstring (lua_State *L, int arg, const char *def, size_t *len) { if (lua_isnoneornil(L, arg)) { if (len) *len = (def ? strlen(def) : 0); return def; } else return luaL_checklstring(L, arg, len); } LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) { int isnum; lua_Number d = lua_tonumberx(L, arg, &isnum); if (!isnum) tag_error(L, arg, LUA_TNUMBER); return d; } LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) { return luaL_opt(L, luaL_checknumber, arg, def); } static void interror (lua_State *L, int arg) { if (lua_isnumber(L, arg)) luaL_argerror(L, arg, "number has no integer representation"); else tag_error(L, arg, LUA_TNUMBER); } LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) { int isnum; lua_Integer d = lua_tointegerx(L, arg, &isnum); if (!isnum) { interror(L, arg); } return d; } LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg, lua_Integer def) { return luaL_opt(L, luaL_checkinteger, arg, def); } /* }====================================================== */ /* ** {====================================================== ** Generic Buffer manipulation ** ======================================================= */ /* userdata to box arbitrary data */ typedef struct UBox { void *box; size_t bsize; } UBox; static void *resizebox (lua_State *L, int idx, size_t newsize) { void *ud; lua_Alloc allocf = lua_getallocf(L, &ud); UBox *box = (UBox *)lua_touserdata(L, idx); void *temp = allocf(ud, box->box, box->bsize, newsize); if (temp == NULL && newsize > 0) { /* allocation error? */ resizebox(L, idx, 0); /* free buffer */ luaL_error(L, "not enough memory for buffer allocation"); } box->box = temp; box->bsize = newsize; return temp; } static int boxgc (lua_State *L) { resizebox(L, 1, 0); return 0; } static void *newbox (lua_State *L, size_t newsize) { UBox *box = (UBox *)lua_newuserdata(L, sizeof(UBox)); box->box = NULL; box->bsize = 0; if (luaL_newmetatable(L, "LUABOX")) { /* creating metatable? */ lua_pushcfunction(L, boxgc); lua_setfield(L, -2, "__gc"); /* metatable.__gc = boxgc */ } lua_setmetatable(L, -2); return resizebox(L, -1, newsize); } /* ** check whether buffer is using a userdata on the stack as a temporary ** buffer */ #define buffonstack(B) ((B)->b != (B)->initb) /* ** returns a pointer to a free area with at least 'sz' bytes */ LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) { lua_State *L = B->L; if (B->size - B->n < sz) { /* not enough space? */ char *newbuff; size_t newsize = B->size * 2; /* double buffer size */ if (newsize - B->n < sz) /* not big enough? */ newsize = B->n + sz; if (newsize < B->n || newsize - B->n < sz) luaL_error(L, "buffer too large"); /* create larger buffer */ if (buffonstack(B)) newbuff = (char *)resizebox(L, -1, newsize); else { /* no buffer yet */ newbuff = (char *)newbox(L, newsize); memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */ } B->b = newbuff; B->size = newsize; } return &B->b[B->n]; } LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) { if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */ char *b = luaL_prepbuffsize(B, l); memcpy(b, s, l * sizeof(char)); luaL_addsize(B, l); } } LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) { luaL_addlstring(B, s, strlen(s)); } LUALIB_API void luaL_pushresult (luaL_Buffer *B) { lua_State *L = B->L; lua_pushlstring(L, B->b, B->n); if (buffonstack(B)) { resizebox(L, -2, 0); /* delete old buffer */ lua_remove(L, -2); /* remove its header from the stack */ } } LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) { luaL_addsize(B, sz); luaL_pushresult(B); } LUALIB_API void luaL_addvalue (luaL_Buffer *B) { lua_State *L = B->L; size_t l; const char *s = lua_tolstring(L, -1, &l); if (buffonstack(B)) lua_insert(L, -2); /* put value below buffer */ luaL_addlstring(B, s, l); lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */ } LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) { B->L = L; B->b = B->initb; B->n = 0; B->size = LUAL_BUFFERSIZE; } LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) { luaL_buffinit(L, B); return luaL_prepbuffsize(B, sz); } /* }====================================================== */ /* ** {====================================================== ** Reference system ** ======================================================= */ /* index of free-list header */ #define freelist 0 LUALIB_API int luaL_ref (lua_State *L, int t) { int ref; if (lua_isnil(L, -1)) { lua_pop(L, 1); /* remove from stack */ return LUA_REFNIL; /* 'nil' has a unique fixed reference */ } t = lua_absindex(L, t); lua_rawgeti(L, t, freelist); /* get first free element */ ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */ lua_pop(L, 1); /* remove it from stack */ if (ref != 0) { /* any free element? */ lua_rawgeti(L, t, ref); /* remove it from list */ lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */ } else /* no free elements */ ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */ lua_rawseti(L, t, ref); return ref; } LUALIB_API void luaL_unref (lua_State *L, int t, int ref) { if (ref >= 0) { t = lua_absindex(L, t); lua_rawgeti(L, t, freelist); lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */ lua_pushinteger(L, ref); lua_rawseti(L, t, freelist); /* t[freelist] = ref */ } } /* }====================================================== */ /* ** {====================================================== ** Load functions ** ======================================================= */ typedef struct LoadF { int n; /* number of pre-read characters */ FILE *f; /* file being read */ char buff[BUFSIZ]; /* area for reading file */ } LoadF; static const char *getF (lua_State *L, void *ud, size_t *size) { LoadF *lf = (LoadF *)ud; (void)L; /* not used */ if (lf->n > 0) { /* are there pre-read characters to be read? */ *size = lf->n; /* return them (chars already in buffer) */ lf->n = 0; /* no more pre-read characters */ } else { /* read a block from file */ /* 'fread' can return > 0 *and* set the EOF flag. If next call to 'getF' called 'fread', it might still wait for user input. The next check avoids this problem. */ if (feof(lf->f)) return NULL; *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */ } return lf->buff; } static int errfile (lua_State *L, const char *what, int fnameindex) { const char *serr = strerror(errno); const char *filename = lua_tostring(L, fnameindex) + 1; lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr); lua_remove(L, fnameindex); return LUA_ERRFILE; } static int skipBOM (LoadF *lf) { const char *p = "\xEF\xBB\xBF"; /* UTF-8 BOM mark */ int c; lf->n = 0; do { c = getc(lf->f); if (c == EOF || c != *(const unsigned char *)p++) return c; lf->buff[lf->n++] = c; /* to be read by the parser */ } while (*p != '\0'); lf->n = 0; /* prefix matched; discard it */ return getc(lf->f); /* return next character */ } /* ** reads the first character of file 'f' and skips an optional BOM mark ** in its beginning plus its first line if it starts with '#'. Returns ** true if it skipped the first line. In any case, '*cp' has the ** first "valid" character of the file (after the optional BOM and ** a first-line comment). */ static int skipcomment (LoadF *lf, int *cp) { int c = *cp = skipBOM(lf); if (c == '#') { /* first line is a comment (Unix exec. file)? */ do { /* skip first line */ c = getc(lf->f); } while (c != EOF && c != '\n'); *cp = getc(lf->f); /* skip end-of-line, if present */ return 1; /* there was a comment */ } else return 0; /* no comment */ } LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename, const char *mode) { LoadF lf; int status, readstatus; int c; int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */ if (filename == NULL) { lua_pushliteral(L, "=stdin"); lf.f = stdin; } else { lua_pushfstring(L, "@%s", filename); lf.f = fopen(filename, "r"); if (lf.f == NULL) return errfile(L, "open", fnameindex); } if (skipcomment(&lf, &c)) /* read initial portion */ lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */ if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */ lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */ if (lf.f == NULL) return errfile(L, "reopen", fnameindex); skipcomment(&lf, &c); /* re-read initial portion */ } if (c != EOF) lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */ status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode); readstatus = ferror(lf.f); if (filename) fclose(lf.f); /* close file (even in case of errors) */ if (readstatus) { lua_settop(L, fnameindex); /* ignore results from 'lua_load' */ return errfile(L, "read", fnameindex); } lua_remove(L, fnameindex); return status; } typedef struct LoadS { const char *s; size_t size; } LoadS; static const char *getS (lua_State *L, void *ud, size_t *size) { LoadS *ls = (LoadS *)ud; (void)L; /* not used */ if (ls->size == 0) return NULL; *size = ls->size; ls->size = 0; return ls->s; } LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size, const char *name, const char *mode) { LoadS ls; ls.s = buff; ls.size = size; return lua_load(L, getS, &ls, name, mode); } LUALIB_API int luaL_loadstring (lua_State *L, const char *s) { return luaL_loadbuffer(L, s, strlen(s), s); } /* }====================================================== */ LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) { if (!lua_getmetatable(L, obj)) /* no metatable? */ return LUA_TNIL; else { int tt; lua_pushstring(L, event); tt = lua_rawget(L, -2); if (tt == LUA_TNIL) /* is metafield nil? */ lua_pop(L, 2); /* remove metatable and metafield */ else lua_remove(L, -2); /* remove only metatable */ return tt; /* return metafield type */ } } LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) { obj = lua_absindex(L, obj); if (luaL_getmetafield(L, obj, event) == LUA_TNIL) /* no metafield? */ return 0; lua_pushvalue(L, obj); lua_call(L, 1, 1); return 1; } LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) { lua_Integer l; int isnum; lua_len(L, idx); l = lua_tointegerx(L, -1, &isnum); if (!isnum) luaL_error(L, "object length is not an integer"); lua_pop(L, 1); /* remove object */ return l; } LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) { if (luaL_callmeta(L, idx, "__tostring")) { /* metafield? */ if (!lua_isstring(L, -1)) luaL_error(L, "'__tostring' must return a string"); } else { switch (lua_type(L, idx)) { case LUA_TNUMBER: { if (lua_isinteger(L, idx)) lua_pushfstring(L, "%I", (LUAI_UACINT)lua_tointeger(L, idx)); else lua_pushfstring(L, "%f", (LUAI_UACNUMBER)lua_tonumber(L, idx)); break; } case LUA_TSTRING: lua_pushvalue(L, idx); break; case LUA_TBOOLEAN: lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false")); break; case LUA_TNIL: lua_pushliteral(L, "nil"); break; default: { int tt = luaL_getmetafield(L, idx, "__name"); /* try name */ const char *kind = (tt == LUA_TSTRING) ? lua_tostring(L, -1) : luaL_typename(L, idx); lua_pushfstring(L, "%s: %p", kind, lua_topointer(L, idx)); if (tt != LUA_TNIL) lua_remove(L, -2); /* remove '__name' */ break; } } } return lua_tolstring(L, -1, len); } /* ** {====================================================== ** Compatibility with 5.1 module functions ** ======================================================= */ #if defined(LUA_COMPAT_MODULE) static const char *luaL_findtable (lua_State *L, int idx, const char *fname, int szhint) { const char *e; if (idx) lua_pushvalue(L, idx); do { e = strchr(fname, '.'); if (e == NULL) e = fname + strlen(fname); lua_pushlstring(L, fname, e - fname); if (lua_rawget(L, -2) == LUA_TNIL) { /* no such field? */ lua_pop(L, 1); /* remove this nil */ lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */ lua_pushlstring(L, fname, e - fname); lua_pushvalue(L, -2); lua_settable(L, -4); /* set new table into field */ } else if (!lua_istable(L, -1)) { /* field has a non-table value? */ lua_pop(L, 2); /* remove table and value */ return fname; /* return problematic part of the name */ } lua_remove(L, -2); /* remove previous table */ fname = e + 1; } while (*e == '.'); return NULL; } /* ** Count number of elements in a luaL_Reg list. */ static int libsize (const luaL_Reg *l) { int size = 0; for (; l && l->name; l++) size++; return size; } /* ** Find or create a module table with a given name. The function ** first looks at the LOADED table and, if that fails, try a ** global variable with that name. In any case, leaves on the stack ** the module table. */ LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname, int sizehint) { luaL_findtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE, 1); if (lua_getfield(L, -1, modname) != LUA_TTABLE) { /* no LOADED[modname]? */ lua_pop(L, 1); /* remove previous result */ /* try global variable (and create one if it does not exist) */ lua_pushglobaltable(L); if (luaL_findtable(L, 0, modname, sizehint) != NULL) luaL_error(L, "name conflict for module '%s'", modname); lua_pushvalue(L, -1); lua_setfield(L, -3, modname); /* LOADED[modname] = new table */ } lua_remove(L, -2); /* remove LOADED table */ } LUALIB_API void luaL_openlib (lua_State *L, const char *libname, const luaL_Reg *l, int nup) { luaL_checkversion(L); if (libname) { luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */ lua_insert(L, -(nup + 1)); /* move library table to below upvalues */ } if (l) luaL_setfuncs(L, l, nup); else lua_pop(L, nup); /* remove upvalues */ } #endif /* }====================================================== */ /* ** set functions from list 'l' into table at top - 'nup'; each ** function gets the 'nup' elements at the top as upvalues. ** Returns with only the table at the stack. */ LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) { luaL_checkstack(L, nup, "too many upvalues"); for (; l->name != NULL; l++) { /* fill the table with given functions */ int i; for (i = 0; i < nup; i++) /* copy upvalues to the top */ lua_pushvalue(L, -nup); lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */ lua_setfield(L, -(nup + 2), l->name); } lua_pop(L, nup); /* remove upvalues */ } /* ** ensure that stack[idx][fname] has a table and push that table ** into the stack */ LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) { if (lua_getfield(L, idx, fname) == LUA_TTABLE) return 1; /* table already there */ else { lua_pop(L, 1); /* remove previous result */ idx = lua_absindex(L, idx); lua_newtable(L); lua_pushvalue(L, -1); /* copy to be left at top */ lua_setfield(L, idx, fname); /* assign new table to field */ return 0; /* false, because did not find table there */ } } /* ** Stripped-down 'require': After checking "loaded" table, calls 'openf' ** to open a module, registers the result in 'package.loaded' table and, ** if 'glb' is true, also registers the result in the global table. ** Leaves resulting module on the top. */ LUALIB_API void luaL_requiref (lua_State *L, const char *modname, lua_CFunction openf, int glb) { luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); lua_getfield(L, -1, modname); /* LOADED[modname] */ if (!lua_toboolean(L, -1)) { /* package not already loaded? */ lua_pop(L, 1); /* remove field */ lua_pushcfunction(L, openf); lua_pushstring(L, modname); /* argument to open function */ lua_call(L, 1, 1); /* call 'openf' to open module */ lua_pushvalue(L, -1); /* make copy of module (call result) */ lua_setfield(L, -3, modname); /* LOADED[modname] = module */ } lua_remove(L, -2); /* remove LOADED table */ if (glb) { lua_pushvalue(L, -1); /* copy of module */ lua_setglobal(L, modname); /* _G[modname] = module */ } } LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p, const char *r) { const char *wild; size_t l = strlen(p); luaL_Buffer b; luaL_buffinit(L, &b); while ((wild = strstr(s, p)) != NULL) { luaL_addlstring(&b, s, wild - s); /* push prefix */ luaL_addstring(&b, r); /* push replacement in place of pattern */ s = wild + l; /* continue after 'p' */ } luaL_addstring(&b, s); /* push last suffix */ luaL_pushresult(&b); return lua_tostring(L, -1); } static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { (void)ud; (void)osize; /* not used */ if (nsize == 0) { free(ptr); return NULL; } else return realloc(ptr, nsize); } static int panic (lua_State *L) { lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n", lua_tostring(L, -1)); return 0; /* return to Lua to abort */ } LUALIB_API lua_State *luaL_newstate (void) { lua_State *L = lua_newstate(l_alloc, NULL); if (L) lua_atpanic(L, &panic); return L; } LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) { const lua_Number *v = lua_version(L); if (sz != LUAL_NUMSIZES) /* check numeric types */ luaL_error(L, "core and library have incompatible numeric types"); if (v != lua_version(NULL)) luaL_error(L, "multiple Lua VMs detected"); else if (*v != ver) luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f", (LUAI_UACNUMBER)ver, (LUAI_UACNUMBER)*v); }
xLua/WebGLPlugins/lauxlib.c/0
{ "file_path": "xLua/WebGLPlugins/lauxlib.c", "repo_id": "xLua", "token_count": 12919 }
2,076
/* ** $Id: lfunc.h,v 2.15 2015/01/13 15:49:11 roberto Exp $ ** Auxiliary functions to manipulate prototypes and closures ** See Copyright Notice in lua.h */ #ifndef lfunc_h #define lfunc_h #include "lobject.h" #define sizeCclosure(n) (cast(int, sizeof(CClosure)) + \ cast(int, sizeof(TValue)*((n)-1))) #define sizeLclosure(n) (cast(int, sizeof(LClosure)) + \ cast(int, sizeof(TValue *)*((n)-1))) /* test whether thread is in 'twups' list */ #define isintwups(L) (L->twups != L) /* ** maximum number of upvalues in a closure (both C and Lua). (Value ** must fit in a VM register.) */ #define MAXUPVAL 255 /* ** Upvalues for Lua closures */ struct UpVal { TValue *v; /* points to stack or to its own value */ lu_mem refcount; /* reference counter */ union { struct { /* (when open) */ UpVal *next; /* linked list */ int touched; /* mark to avoid cycles with dead threads */ } open; TValue value; /* the value (when closed) */ } u; }; #define upisopen(up) ((up)->v != &(up)->u.value) LUAI_FUNC Proto *luaF_newproto (lua_State *L); LUAI_FUNC CClosure *luaF_newCclosure (lua_State *L, int nelems); LUAI_FUNC LClosure *luaF_newLclosure (lua_State *L, int nelems); LUAI_FUNC void luaF_initupvals (lua_State *L, LClosure *cl); LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level); LUAI_FUNC void luaF_close (lua_State *L, StkId level); LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f); LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number, int pc); #endif
xLua/WebGLPlugins/lfunc.h/0
{ "file_path": "xLua/WebGLPlugins/lfunc.h", "repo_id": "xLua", "token_count": 690 }
2,077
# This file is based off of the Platform/Darwin.cmake and Platform/UnixPaths.cmake # files which are included with CMake 2.8.4 # It has been altered for iOS development # Options: # # IOS_PLATFORM = OS (default) or SIMULATOR # This decides if SDKS will be selected from the iPhoneOS.platform or iPhoneSimulator.platform folders # OS - the default, used to build for iPhone and iPad physical devices, which have an arm arch. # SIMULATOR - used to build for the Simulator platforms, which have an x86 arch. # # CMAKE_IOS_DEVELOPER_ROOT = automatic(default) or /path/to/platform/Developer folder # By default this location is automatcially chosen based on the IOS_PLATFORM value above. # If set manually, it will override the default location and force the user of a particular Developer Platform # # CMAKE_IOS_SDK_ROOT = automatic(default) or /path/to/platform/Developer/SDKs/SDK folder # By default this location is automatcially chosen based on the CMAKE_IOS_DEVELOPER_ROOT value. # In this case it will always be the most up-to-date SDK found in the CMAKE_IOS_DEVELOPER_ROOT path. # If set manually, this will force the use of a specific SDK version # Macros: # # set_xcode_property (TARGET XCODE_PROPERTY XCODE_VALUE) # A convenience macro for setting xcode specific properties on targets # example: set_xcode_property (myioslib IPHONEOS_DEPLOYMENT_TARGET "3.1") # # find_host_package (PROGRAM ARGS) # A macro used to find executable programs on the host system, not within the iOS environment. # Thanks to the android-cmake project for providing the command # Standard settings set (CMAKE_SYSTEM_NAME Darwin) set (CMAKE_SYSTEM_VERSION 1) set (UNIX True) set (APPLE True) set (IOS True) # Required as of cmake 2.8.10 set (CMAKE_OSX_DEPLOYMENT_TARGET "" CACHE STRING "Force unset of the deployment target for iOS" FORCE) # Determine the cmake host system version so we know where to find the iOS SDKs find_program (CMAKE_UNAME uname /bin /usr/bin /usr/local/bin) if (CMAKE_UNAME) exec_program(uname ARGS -r OUTPUT_VARIABLE CMAKE_HOST_SYSTEM_VERSION) string (REGEX REPLACE "^([0-9]+)\\.([0-9]+).*$" "\\1" DARWIN_MAJOR_VERSION "${CMAKE_HOST_SYSTEM_VERSION}") endif (CMAKE_UNAME) # Force the compilers to gcc for iOS #include (CMakeForceCompiler) #CMAKE_FORCE_C_COMPILER (/usr/bin/clang Apple) #CMAKE_FORCE_CXX_COMPILER (/usr/bin/clang++ Apple) #set(CMAKE_AR ar CACHE FILEPATH "" FORCE) # Skip the platform compiler checks for cross compiling set (CMAKE_CXX_COMPILER_WORKS TRUE) set (CMAKE_C_COMPILER_WORKS TRUE) # All iOS/Darwin specific settings - some may be redundant set (CMAKE_SHARED_LIBRARY_PREFIX "lib") set (CMAKE_SHARED_LIBRARY_SUFFIX ".dylib") set (CMAKE_SHARED_MODULE_PREFIX "lib") set (CMAKE_SHARED_MODULE_SUFFIX ".so") set (CMAKE_MODULE_EXISTS 1) set (CMAKE_DL_LIBS "") set (CMAKE_C_OSX_COMPATIBILITY_VERSION_FLAG "-compatibility_version ") set (CMAKE_C_OSX_CURRENT_VERSION_FLAG "-current_version ") set (CMAKE_CXX_OSX_COMPATIBILITY_VERSION_FLAG "${CMAKE_C_OSX_COMPATIBILITY_VERSION_FLAG}") set (CMAKE_CXX_OSX_CURRENT_VERSION_FLAG "${CMAKE_C_OSX_CURRENT_VERSION_FLAG}") # Hidden visibilty is required for cxx on iOS set (CMAKE_C_FLAGS_INIT "") set (CMAKE_CXX_FLAGS_INIT "-fvisibility=hidden -fvisibility-inlines-hidden -isysroot ${CMAKE_OSX_SYSROOT}") set (CMAKE_C_LINK_FLAGS "-Wl,-search_paths_first ${CMAKE_C_LINK_FLAGS}") set (CMAKE_CXX_LINK_FLAGS "-Wl,-search_paths_first ${CMAKE_CXX_LINK_FLAGS}") set (CMAKE_PLATFORM_HAS_INSTALLNAME 1) set (CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS "-dynamiclib -headerpad_max_install_names") set (CMAKE_SHARED_MODULE_CREATE_C_FLAGS "-bundle -headerpad_max_install_names") set (CMAKE_SHARED_MODULE_LOADER_C_FLAG "-Wl,-bundle_loader,") set (CMAKE_SHARED_MODULE_LOADER_CXX_FLAG "-Wl,-bundle_loader,") set (CMAKE_FIND_LIBRARY_SUFFIXES ".dylib" ".so" ".a") # hack: if a new cmake (which uses CMAKE_INSTALL_NAME_TOOL) runs on an old build tree # (where install_name_tool was hardcoded) and where CMAKE_INSTALL_NAME_TOOL isn't in the cache # and still cmake didn't fail in CMakeFindBinUtils.cmake (because it isn't rerun) # hardcode CMAKE_INSTALL_NAME_TOOL here to install_name_tool, so it behaves as it did before, Alex if (NOT DEFINED CMAKE_INSTALL_NAME_TOOL) find_program(CMAKE_INSTALL_NAME_TOOL install_name_tool) endif (NOT DEFINED CMAKE_INSTALL_NAME_TOOL) # Setup iOS platform unless specified manually with IOS_PLATFORM if (NOT DEFINED IOS_PLATFORM) set (IOS_PLATFORM "OS") endif (NOT DEFINED IOS_PLATFORM) set (IOS_PLATFORM ${IOS_PLATFORM} CACHE STRING "Type of iOS Platform") # Check the platform selection and setup for developer root if (${IOS_PLATFORM} STREQUAL "OS") set (IOS_PLATFORM_LOCATION "iPhoneOS.platform") # This causes the installers to properly locate the output libraries set (CMAKE_XCODE_EFFECTIVE_PLATFORMS "-iphoneos") elseif (${IOS_PLATFORM} STREQUAL "SIMULATOR") set (IOS_PLATFORM_LOCATION "iPhoneSimulator.platform") # This causes the installers to properly locate the output libraries set (CMAKE_XCODE_EFFECTIVE_PLATFORMS "-iphonesimulator") else (${IOS_PLATFORM} STREQUAL "OS") message (FATAL_ERROR "Unsupported IOS_PLATFORM value selected. Please choose OS or SIMULATOR") endif (${IOS_PLATFORM} STREQUAL "OS") # Setup iOS developer location unless specified manually with CMAKE_IOS_DEVELOPER_ROOT # Note Xcode 4.3 changed the installation location, choose the most recent one available set (XCODE_POST_43_ROOT "/Applications/Xcode.app/Contents/Developer/Platforms/${IOS_PLATFORM_LOCATION}/Developer") set (XCODE_PRE_43_ROOT "/Developer/Platforms/${IOS_PLATFORM_LOCATION}/Developer") if (NOT DEFINED CMAKE_IOS_DEVELOPER_ROOT) if (EXISTS ${XCODE_POST_43_ROOT}) set (CMAKE_IOS_DEVELOPER_ROOT ${XCODE_POST_43_ROOT}) elseif(EXISTS ${XCODE_PRE_43_ROOT}) set (CMAKE_IOS_DEVELOPER_ROOT ${XCODE_PRE_43_ROOT}) endif (EXISTS ${XCODE_POST_43_ROOT}) endif (NOT DEFINED CMAKE_IOS_DEVELOPER_ROOT) set (CMAKE_IOS_DEVELOPER_ROOT ${CMAKE_IOS_DEVELOPER_ROOT} CACHE PATH "Location of iOS Platform") # Find and use the most recent iOS sdk unless specified manually with CMAKE_IOS_SDK_ROOT if (NOT DEFINED CMAKE_IOS_SDK_ROOT) file (GLOB _CMAKE_IOS_SDKS "${CMAKE_IOS_DEVELOPER_ROOT}/SDKs/*") if (_CMAKE_IOS_SDKS) list (SORT _CMAKE_IOS_SDKS) list (REVERSE _CMAKE_IOS_SDKS) list (GET _CMAKE_IOS_SDKS 0 CMAKE_IOS_SDK_ROOT) else (_CMAKE_IOS_SDKS) message (FATAL_ERROR "No iOS SDK's found in default search path ${CMAKE_IOS_DEVELOPER_ROOT}. Manually set CMAKE_IOS_SDK_ROOT or install the iOS SDK.") endif (_CMAKE_IOS_SDKS) message (STATUS "Toolchain using default iOS SDK: ${CMAKE_IOS_SDK_ROOT}") endif (NOT DEFINED CMAKE_IOS_SDK_ROOT) set (CMAKE_IOS_SDK_ROOT ${CMAKE_IOS_SDK_ROOT} CACHE PATH "Location of the selected iOS SDK") # Set the sysroot default to the most recent SDK set (CMAKE_OSX_SYSROOT ${CMAKE_IOS_SDK_ROOT} CACHE PATH "Sysroot used for iOS support") # set the architecture for iOS # NOTE: Currently both ARCHS_STANDARD_32_BIT and ARCHS_UNIVERSAL_IPHONE_OS set armv7 only, so set both manually if (${IOS_PLATFORM} STREQUAL "OS") set (IOS_ARCH armv7) else (${IOS_PLATFORM} STREQUAL "OS") set (IOS_ARCH i386) endif (${IOS_PLATFORM} STREQUAL "OS") set (CMAKE_OSX_ARCHITECTURES ${IOS_ARCH} CACHE string "Build architecture for iOS") # Set the find root to the iOS developer roots and to user defined paths set (CMAKE_FIND_ROOT_PATH ${CMAKE_IOS_DEVELOPER_ROOT} ${CMAKE_IOS_SDK_ROOT} ${CMAKE_PREFIX_PATH} CACHE string "iOS find search path root") # default to searching for frameworks first set (CMAKE_FIND_FRAMEWORK FIRST) # set up the default search directories for frameworks set (CMAKE_SYSTEM_FRAMEWORK_PATH ${CMAKE_IOS_SDK_ROOT}/System/Library/Frameworks ${CMAKE_IOS_SDK_ROOT}/System/Library/PrivateFrameworks ${CMAKE_IOS_SDK_ROOT}/Developer/Library/Frameworks ) # only search the iOS sdks, not the remainder of the host filesystem #set (CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY) #set (CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) #set (CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) # This little macro lets you set any XCode specific property macro (set_xcode_property TARGET XCODE_PROPERTY XCODE_VALUE) set_property (TARGET ${TARGET} PROPERTY XCODE_ATTRIBUTE_${XCODE_PROPERTY} ${XCODE_VALUE}) endmacro (set_xcode_property) # This macro lets you find executable programs on the host system macro (find_host_package) set (CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set (CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER) set (CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER) set (IOS FALSE) find_package(${ARGN}) set (IOS TRUE) set (CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY) set (CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set (CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) endmacro (find_host_package) macro(ADD_FRAMEWORK fwname frameworks) find_library(FRAMEWORK_${fwname} NAMES ${fwname} ) if( ${FRAMEWORK_${fwname}} STREQUAL FRAMEWORK_${fwname}-NOTFOUND) MESSAGE(ERROR ": Framework ${fwname} not found") else() list(APPEND ${frameworks} ${FRAMEWORK_${fwname}}) MESSAGE(STATUS "Framework ${fwname} found at ${FRAMEWORK_${fwname}}") endif() endmacro(ADD_FRAMEWORK) # http://stackoverflow.com/questions/14171740/cmake-with-ios-toolchain-cant-find-threads # http://public.kitware.com/Bug/view.php?id=12288 # Fix for try_compile SET(CMAKE_MACOSX_BUNDLE YES) SET(CMAKE_XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "iPhone Developer") SET(MACOSX_BUNDLE_GUI_IDENTIFIER "org.racing") # http://stackoverflow.com/questions/11198878/how-do-you-specify-a-universal-ios-application-when-building-through-cmake SET(CMAKE_XCODE_ATTRIBUTE_TARGETED_DEVICE_FAMILY "1,2")
xLua/build/cmake/iOS.cmake/0
{ "file_path": "xLua/build/cmake/iOS.cmake", "repo_id": "xLua", "token_count": 3838 }
2,078
<!-- $Id: luac.man,v 1.28 2006/01/06 16:03:34 lhf Exp $ --> <HTML> <HEAD> <TITLE>LUAC man page</TITLE> <LINK REL="stylesheet" TYPE="text/css" HREF="lua.css"> </HEAD> <BODY BGCOLOR="#FFFFFF"> <H2>NAME</H2> luac - Lua compiler <H2>SYNOPSIS</H2> <B>luac</B> [ <I>options</I> ] [ <I>filenames</I> ] <H2>DESCRIPTION</H2> <B>luac</B> is the Lua compiler. It translates programs written in the Lua programming language into binary files that can be later loaded and executed. <P> The main advantages of precompiling chunks are: faster loading, protecting source code from accidental user changes, and off-line syntax checking. <P> Precompiling does not imply faster execution because in Lua chunks are always compiled into bytecodes before being executed. <B>luac</B> simply allows those bytecodes to be saved in a file for later execution. <P> Precompiled chunks are not necessarily smaller than the corresponding source. The main goal in precompiling is faster loading. <P> The binary files created by <B>luac</B> are portable only among architectures with the same word size and byte order. <P> <B>luac</B> produces a single output file containing the bytecodes for all source files given. By default, the output file is named <B>luac.out</B>, but you can change this with the <B>-o</B> option. <P> In the command line, you can mix text files containing Lua source and binary files containing precompiled chunks. This is useful because several precompiled chunks, even from different (but compatible) platforms, can be combined into a single precompiled chunk. <P> You can use <B>'-'</B> to indicate the standard input as a source file and <B>'--'</B> to signal the end of options (that is, all remaining arguments will be treated as files even if they start with <B>'-'</B>). <P> The internal format of the binary files produced by <B>luac</B> is likely to change when a new version of Lua is released. So, save the source files of all Lua programs that you precompile. <P> <H2>OPTIONS</H2> Options must be separate. <P> <B>-l</B> produce a listing of the compiled bytecode for Lua's virtual machine. Listing bytecodes is useful to learn about Lua's virtual machine. If no files are given, then <B>luac</B> loads <B>luac.out</B> and lists its contents. <P> <B>-o </B><I>file</I> output to <I>file</I>, instead of the default <B>luac.out</B>. (You can use <B>'-'</B> for standard output, but not on platforms that open standard output in text mode.) The output file may be a source file because all files are loaded before the output file is written. Be careful not to overwrite precious files. <P> <B>-p</B> load files but do not generate any output file. Used mainly for syntax checking and for testing precompiled chunks: corrupted files will probably generate errors when loaded. Lua always performs a thorough integrity test on precompiled chunks. Bytecode that passes this test is completely safe, in the sense that it will not break the interpreter. However, there is no guarantee that such code does anything sensible. (None can be given, because the halting problem is unsolvable.) If no files are given, then <B>luac</B> loads <B>luac.out</B> and tests its contents. No messages are displayed if the file passes the integrity test. <P> <B>-s</B> strip debug information before writing the output file. This saves some space in very large chunks, but if errors occur when running a stripped chunk, then the error messages may not contain the full information they usually do. For instance, line numbers and names of local variables are lost. <P> <B>-v</B> show version information. <H2>FILES</H2> <P> <B>luac.out</B> default output file <H2>SEE ALSO</H2> <B>lua</B>(1) <BR> <A HREF="http://www.lua.org/">http://www.lua.org/</A> <H2>DIAGNOSTICS</H2> Error messages should be self explanatory. <H2>AUTHORS</H2> L. H. de Figueiredo, R. Ierusalimschy and W. Celes <!-- EOF --> </BODY> </HTML>
xLua/build/lua-5.1.5/doc/luac.html/0
{ "file_path": "xLua/build/lua-5.1.5/doc/luac.html", "repo_id": "xLua", "token_count": 1250 }
2,079
/* ** $Id: lapi.h,v 2.2.1.1 2007/12/27 13:02:25 roberto Exp $ ** Auxiliary functions from Lua API ** See Copyright Notice in lua.h */ #ifndef lapi_h #define lapi_h #include "lobject.h" LUAI_FUNC void luaA_pushobject (lua_State *L, const TValue *o); #endif
xLua/build/lua-5.1.5/src/lapi.h/0
{ "file_path": "xLua/build/lua-5.1.5/src/lapi.h", "repo_id": "xLua", "token_count": 113 }
2,080
/* ** $Id: linit.c,v 1.14.1.1 2007/12/27 13:02:25 roberto Exp $ ** Initialization of libraries for lua.c ** See Copyright Notice in lua.h */ #define linit_c #define LUA_LIB #include "lua.h" #include "lualib.h" #include "lauxlib.h" static const luaL_Reg lualibs[] = { {"", luaopen_base}, {LUA_LOADLIBNAME, luaopen_package}, {LUA_TABLIBNAME, luaopen_table}, {LUA_IOLIBNAME, luaopen_io}, {LUA_OSLIBNAME, luaopen_os}, {LUA_STRLIBNAME, luaopen_string}, {LUA_MATHLIBNAME, luaopen_math}, {LUA_DBLIBNAME, luaopen_debug}, {NULL, NULL} }; LUALIB_API void luaL_openlibs (lua_State *L) { const luaL_Reg *lib = lualibs; for (; lib->func; lib++) { lua_pushcfunction(L, lib->func); lua_pushstring(L, lib->name); lua_call(L, 1, 0); } }
xLua/build/lua-5.1.5/src/linit.c/0
{ "file_path": "xLua/build/lua-5.1.5/src/linit.c", "repo_id": "xLua", "token_count": 358 }
2,081
/* ** $Id: lstate.c,v 2.36.1.2 2008/01/03 15:20:39 roberto Exp $ ** Global State ** See Copyright Notice in lua.h */ #include <stddef.h> #define lstate_c #define LUA_CORE #include "lua.h" #include "ldebug.h" #include "ldo.h" #include "lfunc.h" #include "lgc.h" #include "llex.h" #include "lmem.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "ltm.h" #define state_size(x) (sizeof(x) + LUAI_EXTRASPACE) #define fromstate(l) (cast(lu_byte *, (l)) - LUAI_EXTRASPACE) #define tostate(l) (cast(lua_State *, cast(lu_byte *, l) + LUAI_EXTRASPACE)) /* ** Main thread combines a thread state and the global state */ typedef struct LG { lua_State l; global_State g; } LG; static void stack_init (lua_State *L1, lua_State *L) { /* initialize CallInfo array */ L1->base_ci = luaM_newvector(L, BASIC_CI_SIZE, CallInfo); L1->ci = L1->base_ci; L1->size_ci = BASIC_CI_SIZE; L1->end_ci = L1->base_ci + L1->size_ci - 1; /* initialize stack array */ L1->stack = luaM_newvector(L, BASIC_STACK_SIZE + EXTRA_STACK, TValue); L1->stacksize = BASIC_STACK_SIZE + EXTRA_STACK; L1->top = L1->stack; L1->stack_last = L1->stack+(L1->stacksize - EXTRA_STACK)-1; /* initialize first ci */ L1->ci->func = L1->top; setnilvalue(L1->top++); /* `function' entry for this `ci' */ L1->base = L1->ci->base = L1->top; L1->ci->top = L1->top + LUA_MINSTACK; } static void freestack (lua_State *L, lua_State *L1) { luaM_freearray(L, L1->base_ci, L1->size_ci, CallInfo); luaM_freearray(L, L1->stack, L1->stacksize, TValue); } /* ** open parts that may cause memory-allocation errors */ static void f_luaopen (lua_State *L, void *ud) { global_State *g = G(L); UNUSED(ud); stack_init(L, L); /* init stack */ sethvalue(L, gt(L), luaH_new(L, 0, 2)); /* table of globals */ sethvalue(L, registry(L), luaH_new(L, 0, 2)); /* registry */ luaS_resize(L, MINSTRTABSIZE); /* initial size of string table */ luaT_init(L); luaX_init(L); luaS_fix(luaS_newliteral(L, MEMERRMSG)); g->GCthreshold = 4*g->totalbytes; } static void preinit_state (lua_State *L, global_State *g) { G(L) = g; L->stack = NULL; L->stacksize = 0; L->errorJmp = NULL; L->hook = NULL; L->hookmask = 0; L->basehookcount = 0; L->allowhook = 1; resethookcount(L); L->openupval = NULL; L->size_ci = 0; L->nCcalls = L->baseCcalls = 0; L->status = 0; L->base_ci = L->ci = NULL; L->savedpc = NULL; L->errfunc = 0; setnilvalue(gt(L)); } static void close_state (lua_State *L) { global_State *g = G(L); luaF_close(L, L->stack); /* close all upvalues for this thread */ luaC_freeall(L); /* collect all objects */ lua_assert(g->rootgc == obj2gco(L)); lua_assert(g->strt.nuse == 0); luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size, TString *); luaZ_freebuffer(L, &g->buff); freestack(L, L); lua_assert(g->totalbytes == sizeof(LG)); (*g->frealloc)(g->ud, fromstate(L), state_size(LG), 0); } lua_State *luaE_newthread (lua_State *L) { lua_State *L1 = tostate(luaM_malloc(L, state_size(lua_State))); luaC_link(L, obj2gco(L1), LUA_TTHREAD); preinit_state(L1, G(L)); stack_init(L1, L); /* init stack */ setobj2n(L, gt(L1), gt(L)); /* share table of globals */ L1->hookmask = L->hookmask; L1->basehookcount = L->basehookcount; L1->hook = L->hook; resethookcount(L1); lua_assert(iswhite(obj2gco(L1))); return L1; } void luaE_freethread (lua_State *L, lua_State *L1) { luaF_close(L1, L1->stack); /* close all upvalues for this thread */ lua_assert(L1->openupval == NULL); luai_userstatefree(L1); freestack(L, L1); luaM_freemem(L, fromstate(L1), state_size(lua_State)); } LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { int i; lua_State *L; global_State *g; void *l = (*f)(ud, NULL, 0, state_size(LG)); if (l == NULL) return NULL; L = tostate(l); g = &((LG *)L)->g; L->next = NULL; L->tt = LUA_TTHREAD; g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT); L->marked = luaC_white(g); set2bits(L->marked, FIXEDBIT, SFIXEDBIT); preinit_state(L, g); g->frealloc = f; g->ud = ud; g->mainthread = L; g->uvhead.u.l.prev = &g->uvhead; g->uvhead.u.l.next = &g->uvhead; g->GCthreshold = 0; /* mark it as unfinished state */ g->strt.size = 0; g->strt.nuse = 0; g->strt.hash = NULL; setnilvalue(registry(L)); luaZ_initbuffer(L, &g->buff); g->panic = NULL; g->gcstate = GCSpause; g->rootgc = obj2gco(L); g->sweepstrgc = 0; g->sweepgc = &g->rootgc; g->gray = NULL; g->grayagain = NULL; g->weak = NULL; g->tmudata = NULL; g->totalbytes = sizeof(LG); g->gcpause = LUAI_GCPAUSE; g->gcstepmul = LUAI_GCMUL; g->gcdept = 0; for (i=0; i<NUM_TAGS; i++) g->mt[i] = NULL; if (luaD_rawrunprotected(L, f_luaopen, NULL) != 0) { /* memory allocation error: free partial state */ close_state(L); L = NULL; } else luai_userstateopen(L); return L; } static void callallgcTM (lua_State *L, void *ud) { UNUSED(ud); luaC_callGCTM(L); /* call GC metamethods for all udata */ } LUA_API void lua_close (lua_State *L) { L = G(L)->mainthread; /* only the main thread can be closed */ lua_lock(L); luaF_close(L, L->stack); /* close all upvalues for this thread */ luaC_separateudata(L, 1); /* separate udata that have GC metamethods */ L->errfunc = 0; /* no error function during GC metamethods */ do { /* repeat until no more errors */ L->ci = L->base_ci; L->base = L->top = L->ci->base; L->nCcalls = L->baseCcalls = 0; } while (luaD_rawrunprotected(L, callallgcTM, NULL) != 0); lua_assert(G(L)->tmudata == NULL); luai_userstateclose(L); close_state(L); }
xLua/build/lua-5.1.5/src/lstate.c/0
{ "file_path": "xLua/build/lua-5.1.5/src/lstate.c", "repo_id": "xLua", "token_count": 2550 }
2,082
/* ** $Id: lundump.h,v 1.37.1.1 2007/12/27 13:02:25 roberto Exp $ ** load precompiled Lua chunks ** See Copyright Notice in lua.h */ #ifndef lundump_h #define lundump_h #include "lobject.h" #include "lzio.h" /* load one chunk; from lundump.c */ LUAI_FUNC Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name); /* make header; from lundump.c */ LUAI_FUNC void luaU_header (char* h); /* dump one chunk; from ldump.c */ LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip); #ifdef luac_c /* print one chunk; from print.c */ LUAI_FUNC void luaU_print (const Proto* f, int full); #endif /* for header of binary files -- this is Lua 5.1 */ #define LUAC_VERSION 0x51 /* for header of binary files -- this is the official format */ #define LUAC_FORMAT 0 /* size of header of binary files */ #define LUAC_HEADERSIZE 12 #endif
xLua/build/lua-5.1.5/src/lundump.h/0
{ "file_path": "xLua/build/lua-5.1.5/src/lundump.h", "repo_id": "xLua", "token_count": 349 }
2,083
/* ** $Id: lbaselib.c,v 1.313 2016/04/11 19:18:40 roberto Exp $ ** Basic library ** See Copyright Notice in lua.h */ #define lbaselib_c #define LUA_LIB #include "lprefix.h" #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #include "lualib.h" static int luaB_print (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ int i; lua_getglobal(L, "tostring"); for (i=1; i<=n; i++) { const char *s; size_t l; lua_pushvalue(L, -1); /* function to be called */ lua_pushvalue(L, i); /* value to print */ lua_call(L, 1, 1); s = lua_tolstring(L, -1, &l); /* get result */ if (s == NULL) return luaL_error(L, "'tostring' must return a string to 'print'"); if (i>1) lua_writestring("\t", 1); lua_writestring(s, l); lua_pop(L, 1); /* pop result */ } lua_writeline(); return 0; } #define SPACECHARS " \f\n\r\t\v" static const char *b_str2int (const char *s, int base, lua_Integer *pn) { lua_Unsigned n = 0; int neg = 0; s += strspn(s, SPACECHARS); /* skip initial spaces */ if (*s == '-') { s++; neg = 1; } /* handle signal */ else if (*s == '+') s++; if (!isalnum((unsigned char)*s)) /* no digit? */ return NULL; do { int digit = (isdigit((unsigned char)*s)) ? *s - '0' : (toupper((unsigned char)*s) - 'A') + 10; if (digit >= base) return NULL; /* invalid numeral */ n = n * base + digit; s++; } while (isalnum((unsigned char)*s)); s += strspn(s, SPACECHARS); /* skip trailing spaces */ *pn = (lua_Integer)((neg) ? (0u - n) : n); return s; } static int luaB_tonumber (lua_State *L) { if (lua_isnoneornil(L, 2)) { /* standard conversion? */ luaL_checkany(L, 1); if (lua_type(L, 1) == LUA_TNUMBER) { /* already a number? */ lua_settop(L, 1); /* yes; return it */ return 1; } else { size_t l; const char *s = lua_tolstring(L, 1, &l); if (s != NULL && lua_stringtonumber(L, s) == l + 1) return 1; /* successful conversion to number */ /* else not a number */ } } else { size_t l; const char *s; lua_Integer n = 0; /* to avoid warnings */ lua_Integer base = luaL_checkinteger(L, 2); luaL_checktype(L, 1, LUA_TSTRING); /* no numbers as strings */ s = lua_tolstring(L, 1, &l); luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range"); if (b_str2int(s, (int)base, &n) == s + l) { lua_pushinteger(L, n); return 1; } /* else not a number */ } /* else not a number */ lua_pushnil(L); /* not a number */ return 1; } static int luaB_error (lua_State *L) { int level = (int)luaL_optinteger(L, 2, 1); lua_settop(L, 1); if (lua_type(L, 1) == LUA_TSTRING && level > 0) { luaL_where(L, level); /* add extra information */ lua_pushvalue(L, 1); lua_concat(L, 2); } return lua_error(L); } static int luaB_getmetatable (lua_State *L) { luaL_checkany(L, 1); if (!lua_getmetatable(L, 1)) { lua_pushnil(L); return 1; /* no metatable */ } luaL_getmetafield(L, 1, "__metatable"); return 1; /* returns either __metatable field (if present) or metatable */ } static int luaB_setmetatable (lua_State *L) { int t = lua_type(L, 2); luaL_checktype(L, 1, LUA_TTABLE); luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil or table expected"); if (luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL) return luaL_error(L, "cannot change a protected metatable"); lua_settop(L, 2); lua_setmetatable(L, 1); return 1; } static int luaB_rawequal (lua_State *L) { luaL_checkany(L, 1); luaL_checkany(L, 2); lua_pushboolean(L, lua_rawequal(L, 1, 2)); return 1; } static int luaB_rawlen (lua_State *L) { int t = lua_type(L, 1); luaL_argcheck(L, t == LUA_TTABLE || t == LUA_TSTRING, 1, "table or string expected"); lua_pushinteger(L, lua_rawlen(L, 1)); return 1; } static int luaB_rawget (lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); luaL_checkany(L, 2); lua_settop(L, 2); lua_rawget(L, 1); return 1; } static int luaB_rawset (lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); luaL_checkany(L, 2); luaL_checkany(L, 3); lua_settop(L, 3); lua_rawset(L, 1); return 1; } static int luaB_collectgarbage (lua_State *L) { static const char *const opts[] = {"stop", "restart", "collect", "count", "step", "setpause", "setstepmul", "isrunning", NULL}; static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT, LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL, LUA_GCISRUNNING}; int o = optsnum[luaL_checkoption(L, 1, "collect", opts)]; int ex = (int)luaL_optinteger(L, 2, 0); int res = lua_gc(L, o, ex); switch (o) { case LUA_GCCOUNT: { int b = lua_gc(L, LUA_GCCOUNTB, 0); lua_pushnumber(L, (lua_Number)res + ((lua_Number)b/1024)); return 1; } case LUA_GCSTEP: case LUA_GCISRUNNING: { lua_pushboolean(L, res); return 1; } default: { lua_pushinteger(L, res); return 1; } } } static int luaB_type (lua_State *L) { int t = lua_type(L, 1); luaL_argcheck(L, t != LUA_TNONE, 1, "value expected"); lua_pushstring(L, lua_typename(L, t)); return 1; } static int pairsmeta (lua_State *L, const char *method, int iszero, lua_CFunction iter) { if (luaL_getmetafield(L, 1, method) == LUA_TNIL) { /* no metamethod? */ luaL_checktype(L, 1, LUA_TTABLE); /* argument must be a table */ lua_pushcfunction(L, iter); /* will return generator, */ lua_pushvalue(L, 1); /* state, */ if (iszero) lua_pushinteger(L, 0); /* and initial value */ else lua_pushnil(L); } else { lua_pushvalue(L, 1); /* argument 'self' to metamethod */ lua_call(L, 1, 3); /* get 3 values from metamethod */ } return 3; } static int luaB_next (lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); lua_settop(L, 2); /* create a 2nd argument if there isn't one */ if (lua_next(L, 1)) return 2; else { lua_pushnil(L); return 1; } } static int luaB_pairs (lua_State *L) { return pairsmeta(L, "__pairs", 0, luaB_next); } /* ** Traversal function for 'ipairs' */ static int ipairsaux (lua_State *L) { lua_Integer i = luaL_checkinteger(L, 2) + 1; lua_pushinteger(L, i); return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2; } /* ** 'ipairs' function. Returns 'ipairsaux', given "table", 0. ** (The given "table" may not be a table.) */ static int luaB_ipairs (lua_State *L) { #if defined(LUA_COMPAT_IPAIRS) return pairsmeta(L, "__ipairs", 1, ipairsaux); #else luaL_checkany(L, 1); lua_pushcfunction(L, ipairsaux); /* iteration function */ lua_pushvalue(L, 1); /* state */ lua_pushinteger(L, 0); /* initial value */ return 3; #endif } static int load_aux (lua_State *L, int status, int envidx) { if (status == LUA_OK) { if (envidx != 0) { /* 'env' parameter? */ lua_pushvalue(L, envidx); /* environment for loaded function */ if (!lua_setupvalue(L, -2, 1)) /* set it as 1st upvalue */ lua_pop(L, 1); /* remove 'env' if not used by previous call */ } return 1; } else { /* error (message is on top of the stack) */ lua_pushnil(L); lua_insert(L, -2); /* put before error message */ return 2; /* return nil plus error message */ } } static int luaB_loadfile (lua_State *L) { const char *fname = luaL_optstring(L, 1, NULL); const char *mode = luaL_optstring(L, 2, NULL); int env = (!lua_isnone(L, 3) ? 3 : 0); /* 'env' index or 0 if no 'env' */ int status = luaL_loadfilex(L, fname, mode); return load_aux(L, status, env); } /* ** {====================================================== ** Generic Read function ** ======================================================= */ /* ** reserved slot, above all arguments, to hold a copy of the returned ** string to avoid it being collected while parsed. 'load' has four ** optional arguments (chunk, source name, mode, and environment). */ #define RESERVEDSLOT 5 /* ** Reader for generic 'load' function: 'lua_load' uses the ** stack for internal stuff, so the reader cannot change the ** stack top. Instead, it keeps its resulting string in a ** reserved slot inside the stack. */ static const char *generic_reader (lua_State *L, void *ud, size_t *size) { (void)(ud); /* not used */ luaL_checkstack(L, 2, "too many nested functions"); lua_pushvalue(L, 1); /* get function */ lua_call(L, 0, 1); /* call it */ if (lua_isnil(L, -1)) { lua_pop(L, 1); /* pop result */ *size = 0; return NULL; } else if (!lua_isstring(L, -1)) luaL_error(L, "reader function must return a string"); lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */ return lua_tolstring(L, RESERVEDSLOT, size); } static int luaB_load (lua_State *L) { int status; size_t l; const char *s = lua_tolstring(L, 1, &l); const char *mode = luaL_optstring(L, 3, "bt"); int env = (!lua_isnone(L, 4) ? 4 : 0); /* 'env' index or 0 if no 'env' */ if (s != NULL) { /* loading a string? */ const char *chunkname = luaL_optstring(L, 2, s); status = luaL_loadbufferx(L, s, l, chunkname, mode); } else { /* loading from a reader function */ const char *chunkname = luaL_optstring(L, 2, "=(load)"); luaL_checktype(L, 1, LUA_TFUNCTION); lua_settop(L, RESERVEDSLOT); /* create reserved slot */ status = lua_load(L, generic_reader, NULL, chunkname, mode); } return load_aux(L, status, env); } /* }====================================================== */ static int dofilecont (lua_State *L, int d1, lua_KContext d2) { (void)d1; (void)d2; /* only to match 'lua_Kfunction' prototype */ return lua_gettop(L) - 1; } static int luaB_dofile (lua_State *L) { const char *fname = luaL_optstring(L, 1, NULL); lua_settop(L, 1); if (luaL_loadfile(L, fname) != LUA_OK) return lua_error(L); lua_callk(L, 0, LUA_MULTRET, 0, dofilecont); return dofilecont(L, 0, 0); } static int luaB_assert (lua_State *L) { if (lua_toboolean(L, 1)) /* condition is true? */ return lua_gettop(L); /* return all arguments */ else { /* error */ luaL_checkany(L, 1); /* there must be a condition */ lua_remove(L, 1); /* remove it */ lua_pushliteral(L, "assertion failed!"); /* default message */ lua_settop(L, 1); /* leave only message (default if no other one) */ return luaB_error(L); /* call 'error' */ } } static int luaB_select (lua_State *L) { int n = lua_gettop(L); if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') { lua_pushinteger(L, n-1); return 1; } else { lua_Integer i = luaL_checkinteger(L, 1); if (i < 0) i = n + i; else if (i > n) i = n; luaL_argcheck(L, 1 <= i, 1, "index out of range"); return n - (int)i; } } /* ** Continuation function for 'pcall' and 'xpcall'. Both functions ** already pushed a 'true' before doing the call, so in case of success ** 'finishpcall' only has to return everything in the stack minus ** 'extra' values (where 'extra' is exactly the number of items to be ** ignored). */ static int finishpcall (lua_State *L, int status, lua_KContext extra) { if (status != LUA_OK && status != LUA_YIELD) { /* error? */ lua_pushboolean(L, 0); /* first result (false) */ lua_pushvalue(L, -2); /* error message */ return 2; /* return false, msg */ } else return lua_gettop(L) - (int)extra; /* return all results */ } static int luaB_pcall (lua_State *L) { int status; luaL_checkany(L, 1); lua_pushboolean(L, 1); /* first result if no errors */ lua_insert(L, 1); /* put it in place */ status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, finishpcall); return finishpcall(L, status, 0); } /* ** Do a protected call with error handling. After 'lua_rotate', the ** stack will have <f, err, true, f, [args...]>; so, the function passes ** 2 to 'finishpcall' to skip the 2 first values when returning results. */ static int luaB_xpcall (lua_State *L) { int status; int n = lua_gettop(L); luaL_checktype(L, 2, LUA_TFUNCTION); /* check error function */ lua_pushboolean(L, 1); /* first result */ lua_pushvalue(L, 1); /* function */ lua_rotate(L, 3, 2); /* move them below function's arguments */ status = lua_pcallk(L, n - 2, LUA_MULTRET, 2, 2, finishpcall); return finishpcall(L, status, 2); } static int luaB_tostring (lua_State *L) { luaL_checkany(L, 1); luaL_tolstring(L, 1, NULL); return 1; } static const luaL_Reg base_funcs[] = { {"assert", luaB_assert}, {"collectgarbage", luaB_collectgarbage}, {"dofile", luaB_dofile}, {"error", luaB_error}, {"getmetatable", luaB_getmetatable}, {"ipairs", luaB_ipairs}, {"loadfile", luaB_loadfile}, {"load", luaB_load}, #if defined(LUA_COMPAT_LOADSTRING) {"loadstring", luaB_load}, #endif {"next", luaB_next}, {"pairs", luaB_pairs}, {"pcall", luaB_pcall}, {"print", luaB_print}, {"rawequal", luaB_rawequal}, {"rawlen", luaB_rawlen}, {"rawget", luaB_rawget}, {"rawset", luaB_rawset}, {"select", luaB_select}, {"setmetatable", luaB_setmetatable}, {"tonumber", luaB_tonumber}, {"tostring", luaB_tostring}, {"type", luaB_type}, {"xpcall", luaB_xpcall}, /* placeholders */ {"_G", NULL}, {"_VERSION", NULL}, {NULL, NULL} }; LUAMOD_API int luaopen_base (lua_State *L) { /* open lib into global table */ lua_pushglobaltable(L); luaL_setfuncs(L, base_funcs, 0); /* set global _G */ lua_pushvalue(L, -1); lua_setfield(L, -2, "_G"); /* set global _VERSION */ lua_pushliteral(L, LUA_VERSION); lua_setfield(L, -2, "_VERSION"); return 1; }
xLua/build/lua-5.3.3/src/lbaselib.c/0
{ "file_path": "xLua/build/lua-5.3.3/src/lbaselib.c", "repo_id": "xLua", "token_count": 5922 }
2,084
/* ** $Id: lgc.h,v 2.91 2015/12/21 13:02:14 roberto Exp $ ** Garbage Collector ** See Copyright Notice in lua.h */ #ifndef lgc_h #define lgc_h #include "lobject.h" #include "lstate.h" /* ** Collectable objects may have one of three colors: white, which ** means the object is not marked; gray, which means the ** object is marked, but its references may be not marked; and ** black, which means that the object and all its references are marked. ** The main invariant of the garbage collector, while marking objects, ** is that a black object can never point to a white one. Moreover, ** any gray object must be in a "gray list" (gray, grayagain, weak, ** allweak, ephemeron) so that it can be visited again before finishing ** the collection cycle. These lists have no meaning when the invariant ** is not being enforced (e.g., sweep phase). */ /* how much to allocate before next GC step */ #if !defined(GCSTEPSIZE) /* ~100 small strings */ #define GCSTEPSIZE (cast_int(100 * sizeof(TString))) #endif /* ** Possible states of the Garbage Collector */ #define GCSpropagate 0 #define GCSatomic 1 #define GCSswpallgc 2 #define GCSswpfinobj 3 #define GCSswptobefnz 4 #define GCSswpend 5 #define GCScallfin 6 #define GCSpause 7 #define issweepphase(g) \ (GCSswpallgc <= (g)->gcstate && (g)->gcstate <= GCSswpend) /* ** macro to tell when main invariant (white objects cannot point to black ** ones) must be kept. During a collection, the sweep ** phase may break the invariant, as objects turned white may point to ** still-black objects. The invariant is restored when sweep ends and ** all objects are white again. */ #define keepinvariant(g) ((g)->gcstate <= GCSatomic) /* ** some useful bit tricks */ #define resetbits(x,m) ((x) &= cast(lu_byte, ~(m))) #define setbits(x,m) ((x) |= (m)) #define testbits(x,m) ((x) & (m)) #define bitmask(b) (1<<(b)) #define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2)) #define l_setbit(x,b) setbits(x, bitmask(b)) #define resetbit(x,b) resetbits(x, bitmask(b)) #define testbit(x,b) testbits(x, bitmask(b)) /* Layout for bit use in 'marked' field: */ #define WHITE0BIT 0 /* object is white (type 0) */ #define WHITE1BIT 1 /* object is white (type 1) */ #define BLACKBIT 2 /* object is black */ #define FINALIZEDBIT 3 /* object has been marked for finalization */ /* bit 7 is currently used by tests (luaL_checkmemory) */ #define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT) #define iswhite(x) testbits((x)->marked, WHITEBITS) #define isblack(x) testbit((x)->marked, BLACKBIT) #define isgray(x) /* neither white nor black */ \ (!testbits((x)->marked, WHITEBITS | bitmask(BLACKBIT))) #define tofinalize(x) testbit((x)->marked, FINALIZEDBIT) #define otherwhite(g) ((g)->currentwhite ^ WHITEBITS) #define isdeadm(ow,m) (!(((m) ^ WHITEBITS) & (ow))) #define isdead(g,v) isdeadm(otherwhite(g), (v)->marked) #define changewhite(x) ((x)->marked ^= WHITEBITS) #define gray2black(x) l_setbit((x)->marked, BLACKBIT) #define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS) /* ** Does one step of collection when debt becomes positive. 'pre'/'pos' ** allows some adjustments to be done only when needed. macro ** 'condchangemem' is used only for heavy tests (forcing a full ** GC cycle on every opportunity) */ #define luaC_condGC(L,pre,pos) \ { if (G(L)->GCdebt > 0) { pre; luaC_step(L); pos;}; \ condchangemem(L,pre,pos); } /* more often than not, 'pre'/'pos' are empty */ #define luaC_checkGC(L) luaC_condGC(L,(void)0,(void)0) #define luaC_barrier(L,p,v) ( \ (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) ? \ luaC_barrier_(L,obj2gco(p),gcvalue(v)) : cast_void(0)) #define luaC_barrierback(L,p,v) ( \ (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) ? \ luaC_barrierback_(L,p) : cast_void(0)) #define luaC_objbarrier(L,p,o) ( \ (isblack(p) && iswhite(o)) ? \ luaC_barrier_(L,obj2gco(p),obj2gco(o)) : cast_void(0)) #define luaC_upvalbarrier(L,uv) ( \ (iscollectable((uv)->v) && !upisopen(uv)) ? \ luaC_upvalbarrier_(L,uv) : cast_void(0)) LUAI_FUNC void luaC_fix (lua_State *L, GCObject *o); LUAI_FUNC void luaC_freeallobjects (lua_State *L); LUAI_FUNC void luaC_step (lua_State *L); LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask); LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency); LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz); LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v); LUAI_FUNC void luaC_barrierback_ (lua_State *L, Table *o); LUAI_FUNC void luaC_upvalbarrier_ (lua_State *L, UpVal *uv); LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt); LUAI_FUNC void luaC_upvdeccount (lua_State *L, UpVal *uv); #endif
xLua/build/lua-5.3.3/src/lgc.h/0
{ "file_path": "xLua/build/lua-5.3.3/src/lgc.h", "repo_id": "xLua", "token_count": 1862 }
2,085
/* ** $Id: lparser.c,v 2.153 2016/05/13 19:10:16 roberto Exp $ ** Lua Parser ** See Copyright Notice in lua.h */ #define lparser_c #define LUA_CORE #include "lprefix.h" #include <string.h> #include "lua.h" #include "lcode.h" #include "ldebug.h" #include "ldo.h" #include "lfunc.h" #include "llex.h" #include "lmem.h" #include "lobject.h" #include "lopcodes.h" #include "lparser.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" /* maximum number of local variables per function (must be smaller than 250, due to the bytecode format) */ #define MAXVARS 200 #define hasmultret(k) ((k) == VCALL || (k) == VVARARG) /* because all strings are unified by the scanner, the parser can use pointer equality for string equality */ #define eqstr(a,b) ((a) == (b)) /* ** nodes for block list (list of active blocks) */ typedef struct BlockCnt { struct BlockCnt *previous; /* chain */ int firstlabel; /* index of first label in this block */ int firstgoto; /* index of first pending goto in this block */ lu_byte nactvar; /* # active locals outside the block */ lu_byte upval; /* true if some variable in the block is an upvalue */ lu_byte isloop; /* true if 'block' is a loop */ } BlockCnt; /* ** prototypes for recursive non-terminal functions */ static void statement (LexState *ls); static void expr (LexState *ls, expdesc *v); /* semantic error */ static l_noret semerror (LexState *ls, const char *msg) { ls->t.token = 0; /* remove "near <token>" from final message */ luaX_syntaxerror(ls, msg); } static l_noret error_expected (LexState *ls, int token) { luaX_syntaxerror(ls, luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token))); } static l_noret errorlimit (FuncState *fs, int limit, const char *what) { lua_State *L = fs->ls->L; const char *msg; int line = fs->f->linedefined; const char *where = (line == 0) ? "main function" : luaO_pushfstring(L, "function at line %d", line); msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s", what, limit, where); luaX_syntaxerror(fs->ls, msg); } static void checklimit (FuncState *fs, int v, int l, const char *what) { if (v > l) errorlimit(fs, l, what); } static int testnext (LexState *ls, int c) { if (ls->t.token == c) { luaX_next(ls); return 1; } else return 0; } static void check (LexState *ls, int c) { if (ls->t.token != c) error_expected(ls, c); } static void checknext (LexState *ls, int c) { check(ls, c); luaX_next(ls); } #define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); } static void check_match (LexState *ls, int what, int who, int where) { if (!testnext(ls, what)) { if (where == ls->linenumber) error_expected(ls, what); else { luaX_syntaxerror(ls, luaO_pushfstring(ls->L, "%s expected (to close %s at line %d)", luaX_token2str(ls, what), luaX_token2str(ls, who), where)); } } } static TString *str_checkname (LexState *ls) { TString *ts; check(ls, TK_NAME); ts = ls->t.seminfo.ts; luaX_next(ls); return ts; } static void init_exp (expdesc *e, expkind k, int i) { e->f = e->t = NO_JUMP; e->k = k; e->u.info = i; } static void codestring (LexState *ls, expdesc *e, TString *s) { init_exp(e, VK, luaK_stringK(ls->fs, s)); } static void checkname (LexState *ls, expdesc *e) { codestring(ls, e, str_checkname(ls)); } static int registerlocalvar (LexState *ls, TString *varname) { FuncState *fs = ls->fs; Proto *f = fs->f; int oldsize = f->sizelocvars; luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars, LocVar, SHRT_MAX, "local variables"); while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL; f->locvars[fs->nlocvars].varname = varname; luaC_objbarrier(ls->L, f, varname); return fs->nlocvars++; } static void new_localvar (LexState *ls, TString *name) { FuncState *fs = ls->fs; Dyndata *dyd = ls->dyd; int reg = registerlocalvar(ls, name); checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal, MAXVARS, "local variables"); luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1, dyd->actvar.size, Vardesc, MAX_INT, "local variables"); dyd->actvar.arr[dyd->actvar.n++].idx = cast(short, reg); } static void new_localvarliteral_ (LexState *ls, const char *name, size_t sz) { new_localvar(ls, luaX_newstring(ls, name, sz)); } #define new_localvarliteral(ls,v) \ new_localvarliteral_(ls, "" v, (sizeof(v)/sizeof(char))-1) static LocVar *getlocvar (FuncState *fs, int i) { int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx; lua_assert(idx < fs->nlocvars); return &fs->f->locvars[idx]; } static void adjustlocalvars (LexState *ls, int nvars) { FuncState *fs = ls->fs; fs->nactvar = cast_byte(fs->nactvar + nvars); for (; nvars; nvars--) { getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc; } } static void removevars (FuncState *fs, int tolevel) { fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel); while (fs->nactvar > tolevel) getlocvar(fs, --fs->nactvar)->endpc = fs->pc; } static int searchupvalue (FuncState *fs, TString *name) { int i; Upvaldesc *up = fs->f->upvalues; for (i = 0; i < fs->nups; i++) { if (eqstr(up[i].name, name)) return i; } return -1; /* not found */ } static int newupvalue (FuncState *fs, TString *name, expdesc *v) { Proto *f = fs->f; int oldsize = f->sizeupvalues; checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues"); luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues, Upvaldesc, MAXUPVAL, "upvalues"); while (oldsize < f->sizeupvalues) f->upvalues[oldsize++].name = NULL; f->upvalues[fs->nups].instack = (v->k == VLOCAL); f->upvalues[fs->nups].idx = cast_byte(v->u.info); f->upvalues[fs->nups].name = name; luaC_objbarrier(fs->ls->L, f, name); return fs->nups++; } static int searchvar (FuncState *fs, TString *n) { int i; for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) { if (eqstr(n, getlocvar(fs, i)->varname)) return i; } return -1; /* not found */ } /* Mark block where variable at given level was defined (to emit close instructions later). */ static void markupval (FuncState *fs, int level) { BlockCnt *bl = fs->bl; while (bl->nactvar > level) bl = bl->previous; bl->upval = 1; } /* Find variable with given name 'n'. If it is an upvalue, add this upvalue into all intermediate functions. */ static void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) { if (fs == NULL) /* no more levels? */ init_exp(var, VVOID, 0); /* default is global */ else { int v = searchvar(fs, n); /* look up locals at current level */ if (v >= 0) { /* found? */ init_exp(var, VLOCAL, v); /* variable is local */ if (!base) markupval(fs, v); /* local will be used as an upval */ } else { /* not found as local at current level; try upvalues */ int idx = searchupvalue(fs, n); /* try existing upvalues */ if (idx < 0) { /* not found? */ singlevaraux(fs->prev, n, var, 0); /* try upper levels */ if (var->k == VVOID) /* not found? */ return; /* it is a global */ /* else was LOCAL or UPVAL */ idx = newupvalue(fs, n, var); /* will be a new upvalue */ } init_exp(var, VUPVAL, idx); /* new or old upvalue */ } } } static void singlevar (LexState *ls, expdesc *var) { TString *varname = str_checkname(ls); FuncState *fs = ls->fs; singlevaraux(fs, varname, var, 1); if (var->k == VVOID) { /* global name? */ expdesc key; singlevaraux(fs, ls->envn, var, 1); /* get environment variable */ lua_assert(var->k != VVOID); /* this one must exist */ codestring(ls, &key, varname); /* key is variable name */ luaK_indexed(fs, var, &key); /* env[varname] */ } } static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) { FuncState *fs = ls->fs; int extra = nvars - nexps; if (hasmultret(e->k)) { extra++; /* includes call itself */ if (extra < 0) extra = 0; luaK_setreturns(fs, e, extra); /* last exp. provides the difference */ if (extra > 1) luaK_reserveregs(fs, extra-1); } else { if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */ if (extra > 0) { int reg = fs->freereg; luaK_reserveregs(fs, extra); luaK_nil(fs, reg, extra); } } } static void enterlevel (LexState *ls) { lua_State *L = ls->L; ++L->nCcalls; checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, "C levels"); } #define leavelevel(ls) ((ls)->L->nCcalls--) static void closegoto (LexState *ls, int g, Labeldesc *label) { int i; FuncState *fs = ls->fs; Labellist *gl = &ls->dyd->gt; Labeldesc *gt = &gl->arr[g]; lua_assert(eqstr(gt->name, label->name)); if (gt->nactvar < label->nactvar) { TString *vname = getlocvar(fs, gt->nactvar)->varname; const char *msg = luaO_pushfstring(ls->L, "<goto %s> at line %d jumps into the scope of local '%s'", getstr(gt->name), gt->line, getstr(vname)); semerror(ls, msg); } luaK_patchlist(fs, gt->pc, label->pc); /* remove goto from pending list */ for (i = g; i < gl->n - 1; i++) gl->arr[i] = gl->arr[i + 1]; gl->n--; } /* ** try to close a goto with existing labels; this solves backward jumps */ static int findlabel (LexState *ls, int g) { int i; BlockCnt *bl = ls->fs->bl; Dyndata *dyd = ls->dyd; Labeldesc *gt = &dyd->gt.arr[g]; /* check labels in current block for a match */ for (i = bl->firstlabel; i < dyd->label.n; i++) { Labeldesc *lb = &dyd->label.arr[i]; if (eqstr(lb->name, gt->name)) { /* correct label? */ if (gt->nactvar > lb->nactvar && (bl->upval || dyd->label.n > bl->firstlabel)) luaK_patchclose(ls->fs, gt->pc, lb->nactvar); closegoto(ls, g, lb); /* close it */ return 1; } } return 0; /* label not found; cannot close goto */ } static int newlabelentry (LexState *ls, Labellist *l, TString *name, int line, int pc) { int n = l->n; luaM_growvector(ls->L, l->arr, n, l->size, Labeldesc, SHRT_MAX, "labels/gotos"); l->arr[n].name = name; l->arr[n].line = line; l->arr[n].nactvar = ls->fs->nactvar; l->arr[n].pc = pc; l->n = n + 1; return n; } /* ** check whether new label 'lb' matches any pending gotos in current ** block; solves forward jumps */ static void findgotos (LexState *ls, Labeldesc *lb) { Labellist *gl = &ls->dyd->gt; int i = ls->fs->bl->firstgoto; while (i < gl->n) { if (eqstr(gl->arr[i].name, lb->name)) closegoto(ls, i, lb); else i++; } } /* ** export pending gotos to outer level, to check them against ** outer labels; if the block being exited has upvalues, and ** the goto exits the scope of any variable (which can be the ** upvalue), close those variables being exited. */ static void movegotosout (FuncState *fs, BlockCnt *bl) { int i = bl->firstgoto; Labellist *gl = &fs->ls->dyd->gt; /* correct pending gotos to current block and try to close it with visible labels */ while (i < gl->n) { Labeldesc *gt = &gl->arr[i]; if (gt->nactvar > bl->nactvar) { if (bl->upval) luaK_patchclose(fs, gt->pc, bl->nactvar); gt->nactvar = bl->nactvar; } if (!findlabel(fs->ls, i)) i++; /* move to next one */ } } static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) { bl->isloop = isloop; bl->nactvar = fs->nactvar; bl->firstlabel = fs->ls->dyd->label.n; bl->firstgoto = fs->ls->dyd->gt.n; bl->upval = 0; bl->previous = fs->bl; fs->bl = bl; lua_assert(fs->freereg == fs->nactvar); } /* ** create a label named 'break' to resolve break statements */ static void breaklabel (LexState *ls) { TString *n = luaS_new(ls->L, "break"); int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc); findgotos(ls, &ls->dyd->label.arr[l]); } /* ** generates an error for an undefined 'goto'; choose appropriate ** message when label name is a reserved word (which can only be 'break') */ static l_noret undefgoto (LexState *ls, Labeldesc *gt) { const char *msg = isreserved(gt->name) ? "<%s> at line %d not inside a loop" : "no visible label '%s' for <goto> at line %d"; msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line); semerror(ls, msg); } static void leaveblock (FuncState *fs) { BlockCnt *bl = fs->bl; LexState *ls = fs->ls; if (bl->previous && bl->upval) { /* create a 'jump to here' to close upvalues */ int j = luaK_jump(fs); luaK_patchclose(fs, j, bl->nactvar); luaK_patchtohere(fs, j); } if (bl->isloop) breaklabel(ls); /* close pending breaks */ fs->bl = bl->previous; removevars(fs, bl->nactvar); lua_assert(bl->nactvar == fs->nactvar); fs->freereg = fs->nactvar; /* free registers */ ls->dyd->label.n = bl->firstlabel; /* remove local labels */ if (bl->previous) /* inner block? */ movegotosout(fs, bl); /* update pending gotos to outer block */ else if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */ undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */ } /* ** adds a new prototype into list of prototypes */ static Proto *addprototype (LexState *ls) { Proto *clp; lua_State *L = ls->L; FuncState *fs = ls->fs; Proto *f = fs->f; /* prototype of current function */ if (fs->np >= f->sizep) { int oldsize = f->sizep; luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions"); while (oldsize < f->sizep) f->p[oldsize++] = NULL; } f->p[fs->np++] = clp = luaF_newproto(L); luaC_objbarrier(L, f, clp); return clp; } /* ** codes instruction to create new closure in parent function. ** The OP_CLOSURE instruction must use the last available register, ** so that, if it invokes the GC, the GC knows which registers ** are in use at that time. */ static void codeclosure (LexState *ls, expdesc *v) { FuncState *fs = ls->fs->prev; init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1)); luaK_exp2nextreg(fs, v); /* fix it at the last register */ } static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) { Proto *f; fs->prev = ls->fs; /* linked list of funcstates */ fs->ls = ls; ls->fs = fs; fs->pc = 0; fs->lasttarget = 0; fs->jpc = NO_JUMP; fs->freereg = 0; fs->nk = 0; fs->np = 0; fs->nups = 0; fs->nlocvars = 0; fs->nactvar = 0; fs->firstlocal = ls->dyd->actvar.n; fs->bl = NULL; f = fs->f; f->source = ls->source; f->maxstacksize = 2; /* registers 0/1 are always valid */ enterblock(fs, bl, 0); } static void close_func (LexState *ls) { lua_State *L = ls->L; FuncState *fs = ls->fs; Proto *f = fs->f; luaK_ret(fs, 0, 0); /* final return */ leaveblock(fs); luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction); f->sizecode = fs->pc; luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int); f->sizelineinfo = fs->pc; luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue); f->sizek = fs->nk; luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *); f->sizep = fs->np; luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar); f->sizelocvars = fs->nlocvars; luaM_reallocvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc); f->sizeupvalues = fs->nups; lua_assert(fs->bl == NULL); ls->fs = fs->prev; luaC_checkGC(L); } /*============================================================*/ /* GRAMMAR RULES */ /*============================================================*/ /* ** check whether current token is in the follow set of a block. ** 'until' closes syntactical blocks, but do not close scope, ** so it is handled in separate. */ static int block_follow (LexState *ls, int withuntil) { switch (ls->t.token) { case TK_ELSE: case TK_ELSEIF: case TK_END: case TK_EOS: return 1; case TK_UNTIL: return withuntil; default: return 0; } } static void statlist (LexState *ls) { /* statlist -> { stat [';'] } */ while (!block_follow(ls, 1)) { if (ls->t.token == TK_RETURN) { statement(ls); return; /* 'return' must be last statement */ } statement(ls); } } static void fieldsel (LexState *ls, expdesc *v) { /* fieldsel -> ['.' | ':'] NAME */ FuncState *fs = ls->fs; expdesc key; luaK_exp2anyregup(fs, v); luaX_next(ls); /* skip the dot or colon */ checkname(ls, &key); luaK_indexed(fs, v, &key); } static void yindex (LexState *ls, expdesc *v) { /* index -> '[' expr ']' */ luaX_next(ls); /* skip the '[' */ expr(ls, v); luaK_exp2val(ls->fs, v); checknext(ls, ']'); } /* ** {====================================================================== ** Rules for Constructors ** ======================================================================= */ struct ConsControl { expdesc v; /* last list item read */ expdesc *t; /* table descriptor */ int nh; /* total number of 'record' elements */ int na; /* total number of array elements */ int tostore; /* number of array elements pending to be stored */ }; static void recfield (LexState *ls, struct ConsControl *cc) { /* recfield -> (NAME | '['exp1']') = exp1 */ FuncState *fs = ls->fs; int reg = ls->fs->freereg; expdesc key, val; int rkkey; if (ls->t.token == TK_NAME) { checklimit(fs, cc->nh, MAX_INT, "items in a constructor"); checkname(ls, &key); } else /* ls->t.token == '[' */ yindex(ls, &key); cc->nh++; checknext(ls, '='); rkkey = luaK_exp2RK(fs, &key); expr(ls, &val); luaK_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, luaK_exp2RK(fs, &val)); fs->freereg = reg; /* free registers */ } static void closelistfield (FuncState *fs, struct ConsControl *cc) { if (cc->v.k == VVOID) return; /* there is no list item */ luaK_exp2nextreg(fs, &cc->v); cc->v.k = VVOID; if (cc->tostore == LFIELDS_PER_FLUSH) { luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */ cc->tostore = 0; /* no more items pending */ } } static void lastlistfield (FuncState *fs, struct ConsControl *cc) { if (cc->tostore == 0) return; if (hasmultret(cc->v.k)) { luaK_setmultret(fs, &cc->v); luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET); cc->na--; /* do not count last expression (unknown number of elements) */ } else { if (cc->v.k != VVOID) luaK_exp2nextreg(fs, &cc->v); luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); } } static void listfield (LexState *ls, struct ConsControl *cc) { /* listfield -> exp */ expr(ls, &cc->v); checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor"); cc->na++; cc->tostore++; } static void field (LexState *ls, struct ConsControl *cc) { /* field -> listfield | recfield */ switch(ls->t.token) { case TK_NAME: { /* may be 'listfield' or 'recfield' */ if (luaX_lookahead(ls) != '=') /* expression? */ listfield(ls, cc); else recfield(ls, cc); break; } case '[': { recfield(ls, cc); break; } default: { listfield(ls, cc); break; } } } static void constructor (LexState *ls, expdesc *t) { /* constructor -> '{' [ field { sep field } [sep] ] '}' sep -> ',' | ';' */ FuncState *fs = ls->fs; int line = ls->linenumber; int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0); struct ConsControl cc; cc.na = cc.nh = cc.tostore = 0; cc.t = t; init_exp(t, VRELOCABLE, pc); init_exp(&cc.v, VVOID, 0); /* no value (yet) */ luaK_exp2nextreg(ls->fs, t); /* fix it at stack top */ checknext(ls, '{'); do { lua_assert(cc.v.k == VVOID || cc.tostore > 0); if (ls->t.token == '}') break; closelistfield(fs, &cc); field(ls, &cc); } while (testnext(ls, ',') || testnext(ls, ';')); check_match(ls, '}', '{', line); lastlistfield(fs, &cc); SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */ SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */ } /* }====================================================================== */ static void parlist (LexState *ls) { /* parlist -> [ param { ',' param } ] */ FuncState *fs = ls->fs; Proto *f = fs->f; int nparams = 0; f->is_vararg = 0; if (ls->t.token != ')') { /* is 'parlist' not empty? */ do { switch (ls->t.token) { case TK_NAME: { /* param -> NAME */ new_localvar(ls, str_checkname(ls)); nparams++; break; } case TK_DOTS: { /* param -> '...' */ luaX_next(ls); f->is_vararg = 2; /* declared vararg */ break; } default: luaX_syntaxerror(ls, "<name> or '...' expected"); } } while (!f->is_vararg && testnext(ls, ',')); } adjustlocalvars(ls, nparams); f->numparams = cast_byte(fs->nactvar); luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */ } static void body (LexState *ls, expdesc *e, int ismethod, int line) { /* body -> '(' parlist ')' block END */ FuncState new_fs; BlockCnt bl; new_fs.f = addprototype(ls); new_fs.f->linedefined = line; open_func(ls, &new_fs, &bl); checknext(ls, '('); if (ismethod) { new_localvarliteral(ls, "self"); /* create 'self' parameter */ adjustlocalvars(ls, 1); } parlist(ls); checknext(ls, ')'); statlist(ls); new_fs.f->lastlinedefined = ls->linenumber; check_match(ls, TK_END, TK_FUNCTION, line); codeclosure(ls, e); close_func(ls); } static int explist (LexState *ls, expdesc *v) { /* explist -> expr { ',' expr } */ int n = 1; /* at least one expression */ expr(ls, v); while (testnext(ls, ',')) { luaK_exp2nextreg(ls->fs, v); expr(ls, v); n++; } return n; } static void funcargs (LexState *ls, expdesc *f, int line) { FuncState *fs = ls->fs; expdesc args; int base, nparams; switch (ls->t.token) { case '(': { /* funcargs -> '(' [ explist ] ')' */ luaX_next(ls); if (ls->t.token == ')') /* arg list is empty? */ args.k = VVOID; else { explist(ls, &args); luaK_setmultret(fs, &args); } check_match(ls, ')', '(', line); break; } case '{': { /* funcargs -> constructor */ constructor(ls, &args); break; } case TK_STRING: { /* funcargs -> STRING */ codestring(ls, &args, ls->t.seminfo.ts); luaX_next(ls); /* must use 'seminfo' before 'next' */ break; } default: { luaX_syntaxerror(ls, "function arguments expected"); } } lua_assert(f->k == VNONRELOC); base = f->u.info; /* base register for call */ if (hasmultret(args.k)) nparams = LUA_MULTRET; /* open call */ else { if (args.k != VVOID) luaK_exp2nextreg(fs, &args); /* close last argument */ nparams = fs->freereg - (base+1); } init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2)); luaK_fixline(fs, line); fs->freereg = base+1; /* call remove function and arguments and leaves (unless changed) one result */ } /* ** {====================================================================== ** Expression parsing ** ======================================================================= */ static void primaryexp (LexState *ls, expdesc *v) { /* primaryexp -> NAME | '(' expr ')' */ switch (ls->t.token) { case '(': { int line = ls->linenumber; luaX_next(ls); expr(ls, v); check_match(ls, ')', '(', line); luaK_dischargevars(ls->fs, v); return; } case TK_NAME: { singlevar(ls, v); return; } default: { luaX_syntaxerror(ls, "unexpected symbol"); } } } static void suffixedexp (LexState *ls, expdesc *v) { /* suffixedexp -> primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */ FuncState *fs = ls->fs; int line = ls->linenumber; primaryexp(ls, v); for (;;) { switch (ls->t.token) { case '.': { /* fieldsel */ fieldsel(ls, v); break; } case '[': { /* '[' exp1 ']' */ expdesc key; luaK_exp2anyregup(fs, v); yindex(ls, &key); luaK_indexed(fs, v, &key); break; } case ':': { /* ':' NAME funcargs */ expdesc key; luaX_next(ls); checkname(ls, &key); luaK_self(fs, v, &key); funcargs(ls, v, line); break; } case '(': case TK_STRING: case '{': { /* funcargs */ luaK_exp2nextreg(fs, v); funcargs(ls, v, line); break; } default: return; } } } static void simpleexp (LexState *ls, expdesc *v) { /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... | constructor | FUNCTION body | suffixedexp */ switch (ls->t.token) { case TK_FLT: { init_exp(v, VKFLT, 0); v->u.nval = ls->t.seminfo.r; break; } case TK_INT: { init_exp(v, VKINT, 0); v->u.ival = ls->t.seminfo.i; break; } case TK_STRING: { codestring(ls, v, ls->t.seminfo.ts); break; } case TK_NIL: { init_exp(v, VNIL, 0); break; } case TK_TRUE: { init_exp(v, VTRUE, 0); break; } case TK_FALSE: { init_exp(v, VFALSE, 0); break; } case TK_DOTS: { /* vararg */ FuncState *fs = ls->fs; check_condition(ls, fs->f->is_vararg, "cannot use '...' outside a vararg function"); fs->f->is_vararg = 1; /* function actually uses vararg */ init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0)); break; } case '{': { /* constructor */ constructor(ls, v); return; } case TK_FUNCTION: { luaX_next(ls); body(ls, v, 0, ls->linenumber); return; } default: { suffixedexp(ls, v); return; } } luaX_next(ls); } static UnOpr getunopr (int op) { switch (op) { case TK_NOT: return OPR_NOT; case '-': return OPR_MINUS; case '~': return OPR_BNOT; case '#': return OPR_LEN; default: return OPR_NOUNOPR; } } static BinOpr getbinopr (int op) { switch (op) { case '+': return OPR_ADD; case '-': return OPR_SUB; case '*': return OPR_MUL; case '%': return OPR_MOD; case '^': return OPR_POW; case '/': return OPR_DIV; case TK_IDIV: return OPR_IDIV; case '&': return OPR_BAND; case '|': return OPR_BOR; case '~': return OPR_BXOR; case TK_SHL: return OPR_SHL; case TK_SHR: return OPR_SHR; case TK_CONCAT: return OPR_CONCAT; case TK_NE: return OPR_NE; case TK_EQ: return OPR_EQ; case '<': return OPR_LT; case TK_LE: return OPR_LE; case '>': return OPR_GT; case TK_GE: return OPR_GE; case TK_AND: return OPR_AND; case TK_OR: return OPR_OR; default: return OPR_NOBINOPR; } } static const struct { lu_byte left; /* left priority for each binary operator */ lu_byte right; /* right priority */ } priority[] = { /* ORDER OPR */ {10, 10}, {10, 10}, /* '+' '-' */ {11, 11}, {11, 11}, /* '*' '%' */ {14, 13}, /* '^' (right associative) */ {11, 11}, {11, 11}, /* '/' '//' */ {6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */ {7, 7}, {7, 7}, /* '<<' '>>' */ {9, 8}, /* '..' (right associative) */ {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */ {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */ {2, 2}, {1, 1} /* and, or */ }; #define UNARY_PRIORITY 12 /* priority for unary operators */ /* ** subexpr -> (simpleexp | unop subexpr) { binop subexpr } ** where 'binop' is any binary operator with a priority higher than 'limit' */ static BinOpr subexpr (LexState *ls, expdesc *v, int limit) { BinOpr op; UnOpr uop; enterlevel(ls); uop = getunopr(ls->t.token); if (uop != OPR_NOUNOPR) { int line = ls->linenumber; luaX_next(ls); subexpr(ls, v, UNARY_PRIORITY); luaK_prefix(ls->fs, uop, v, line); } else simpleexp(ls, v); /* expand while operators have priorities higher than 'limit' */ op = getbinopr(ls->t.token); while (op != OPR_NOBINOPR && priority[op].left > limit) { expdesc v2; BinOpr nextop; int line = ls->linenumber; luaX_next(ls); luaK_infix(ls->fs, op, v); /* read sub-expression with higher priority */ nextop = subexpr(ls, &v2, priority[op].right); luaK_posfix(ls->fs, op, v, &v2, line); op = nextop; } leavelevel(ls); return op; /* return first untreated operator */ } static void expr (LexState *ls, expdesc *v) { subexpr(ls, v, 0); } /* }==================================================================== */ /* ** {====================================================================== ** Rules for Statements ** ======================================================================= */ static void block (LexState *ls) { /* block -> statlist */ FuncState *fs = ls->fs; BlockCnt bl; enterblock(fs, &bl, 0); statlist(ls); leaveblock(fs); } /* ** structure to chain all variables in the left-hand side of an ** assignment */ struct LHS_assign { struct LHS_assign *prev; expdesc v; /* variable (global, local, upvalue, or indexed) */ }; /* ** check whether, in an assignment to an upvalue/local variable, the ** upvalue/local variable is begin used in a previous assignment to a ** table. If so, save original upvalue/local value in a safe place and ** use this safe copy in the previous assignment. */ static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) { FuncState *fs = ls->fs; int extra = fs->freereg; /* eventual position to save local variable */ int conflict = 0; for (; lh; lh = lh->prev) { /* check all previous assignments */ if (lh->v.k == VINDEXED) { /* assigning to a table? */ /* table is the upvalue/local being assigned now? */ if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) { conflict = 1; lh->v.u.ind.vt = VLOCAL; lh->v.u.ind.t = extra; /* previous assignment will use safe copy */ } /* index is the local being assigned? (index cannot be upvalue) */ if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) { conflict = 1; lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */ } } } if (conflict) { /* copy upvalue/local value to a temporary (in position 'extra') */ OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL; luaK_codeABC(fs, op, extra, v->u.info, 0); luaK_reserveregs(fs, 1); } } static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) { expdesc e; check_condition(ls, vkisvar(lh->v.k), "syntax error"); if (testnext(ls, ',')) { /* assignment -> ',' suffixedexp assignment */ struct LHS_assign nv; nv.prev = lh; suffixedexp(ls, &nv.v); if (nv.v.k != VINDEXED) check_conflict(ls, lh, &nv.v); checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS, "C levels"); assignment(ls, &nv, nvars+1); } else { /* assignment -> '=' explist */ int nexps; checknext(ls, '='); nexps = explist(ls, &e); if (nexps != nvars) { adjust_assign(ls, nvars, nexps, &e); if (nexps > nvars) ls->fs->freereg -= nexps - nvars; /* remove extra values */ } else { luaK_setoneret(ls->fs, &e); /* close last expression */ luaK_storevar(ls->fs, &lh->v, &e); return; /* avoid default */ } } init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */ luaK_storevar(ls->fs, &lh->v, &e); } static int cond (LexState *ls) { /* cond -> exp */ expdesc v; expr(ls, &v); /* read condition */ if (v.k == VNIL) v.k = VFALSE; /* 'falses' are all equal here */ luaK_goiftrue(ls->fs, &v); return v.f; } static void gotostat (LexState *ls, int pc) { int line = ls->linenumber; TString *label; int g; if (testnext(ls, TK_GOTO)) label = str_checkname(ls); else { luaX_next(ls); /* skip break */ label = luaS_new(ls->L, "break"); } g = newlabelentry(ls, &ls->dyd->gt, label, line, pc); findlabel(ls, g); /* close it if label already defined */ } /* check for repeated labels on the same block */ static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) { int i; for (i = fs->bl->firstlabel; i < ll->n; i++) { if (eqstr(label, ll->arr[i].name)) { const char *msg = luaO_pushfstring(fs->ls->L, "label '%s' already defined on line %d", getstr(label), ll->arr[i].line); semerror(fs->ls, msg); } } } /* skip no-op statements */ static void skipnoopstat (LexState *ls) { while (ls->t.token == ';' || ls->t.token == TK_DBCOLON) statement(ls); } static void labelstat (LexState *ls, TString *label, int line) { /* label -> '::' NAME '::' */ FuncState *fs = ls->fs; Labellist *ll = &ls->dyd->label; int l; /* index of new label being created */ checkrepeated(fs, ll, label); /* check for repeated labels */ checknext(ls, TK_DBCOLON); /* skip double colon */ /* create new entry for this label */ l = newlabelentry(ls, ll, label, line, luaK_getlabel(fs)); skipnoopstat(ls); /* skip other no-op statements */ if (block_follow(ls, 0)) { /* label is last no-op statement in the block? */ /* assume that locals are already out of scope */ ll->arr[l].nactvar = fs->bl->nactvar; } findgotos(ls, &ll->arr[l]); } static void whilestat (LexState *ls, int line) { /* whilestat -> WHILE cond DO block END */ FuncState *fs = ls->fs; int whileinit; int condexit; BlockCnt bl; luaX_next(ls); /* skip WHILE */ whileinit = luaK_getlabel(fs); condexit = cond(ls); enterblock(fs, &bl, 1); checknext(ls, TK_DO); block(ls); luaK_jumpto(fs, whileinit); check_match(ls, TK_END, TK_WHILE, line); leaveblock(fs); luaK_patchtohere(fs, condexit); /* false conditions finish the loop */ } static void repeatstat (LexState *ls, int line) { /* repeatstat -> REPEAT block UNTIL cond */ int condexit; FuncState *fs = ls->fs; int repeat_init = luaK_getlabel(fs); BlockCnt bl1, bl2; enterblock(fs, &bl1, 1); /* loop block */ enterblock(fs, &bl2, 0); /* scope block */ luaX_next(ls); /* skip REPEAT */ statlist(ls); check_match(ls, TK_UNTIL, TK_REPEAT, line); condexit = cond(ls); /* read condition (inside scope block) */ if (bl2.upval) /* upvalues? */ luaK_patchclose(fs, condexit, bl2.nactvar); leaveblock(fs); /* finish scope */ luaK_patchlist(fs, condexit, repeat_init); /* close the loop */ leaveblock(fs); /* finish loop */ } static int exp1 (LexState *ls) { expdesc e; int reg; expr(ls, &e); luaK_exp2nextreg(ls->fs, &e); lua_assert(e.k == VNONRELOC); reg = e.u.info; return reg; } static void forbody (LexState *ls, int base, int line, int nvars, int isnum) { /* forbody -> DO block */ BlockCnt bl; FuncState *fs = ls->fs; int prep, endfor; adjustlocalvars(ls, 3); /* control variables */ checknext(ls, TK_DO); prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs); enterblock(fs, &bl, 0); /* scope for declared variables */ adjustlocalvars(ls, nvars); luaK_reserveregs(fs, nvars); block(ls); leaveblock(fs); /* end of scope for declared variables */ luaK_patchtohere(fs, prep); if (isnum) /* numeric for? */ endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP); else { /* generic for */ luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars); luaK_fixline(fs, line); endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP); } luaK_patchlist(fs, endfor, prep + 1); luaK_fixline(fs, line); } static void fornum (LexState *ls, TString *varname, int line) { /* fornum -> NAME = exp1,exp1[,exp1] forbody */ FuncState *fs = ls->fs; int base = fs->freereg; new_localvarliteral(ls, "(for index)"); new_localvarliteral(ls, "(for limit)"); new_localvarliteral(ls, "(for step)"); new_localvar(ls, varname); checknext(ls, '='); exp1(ls); /* initial value */ checknext(ls, ','); exp1(ls); /* limit */ if (testnext(ls, ',')) exp1(ls); /* optional step */ else { /* default step = 1 */ luaK_codek(fs, fs->freereg, luaK_intK(fs, 1)); luaK_reserveregs(fs, 1); } forbody(ls, base, line, 1, 1); } static void forlist (LexState *ls, TString *indexname) { /* forlist -> NAME {,NAME} IN explist forbody */ FuncState *fs = ls->fs; expdesc e; int nvars = 4; /* gen, state, control, plus at least one declared var */ int line; int base = fs->freereg; /* create control variables */ new_localvarliteral(ls, "(for generator)"); new_localvarliteral(ls, "(for state)"); new_localvarliteral(ls, "(for control)"); /* create declared variables */ new_localvar(ls, indexname); while (testnext(ls, ',')) { new_localvar(ls, str_checkname(ls)); nvars++; } checknext(ls, TK_IN); line = ls->linenumber; adjust_assign(ls, 3, explist(ls, &e), &e); luaK_checkstack(fs, 3); /* extra space to call generator */ forbody(ls, base, line, nvars - 3, 0); } static void forstat (LexState *ls, int line) { /* forstat -> FOR (fornum | forlist) END */ FuncState *fs = ls->fs; TString *varname; BlockCnt bl; enterblock(fs, &bl, 1); /* scope for loop and control variables */ luaX_next(ls); /* skip 'for' */ varname = str_checkname(ls); /* first variable name */ switch (ls->t.token) { case '=': fornum(ls, varname, line); break; case ',': case TK_IN: forlist(ls, varname); break; default: luaX_syntaxerror(ls, "'=' or 'in' expected"); } check_match(ls, TK_END, TK_FOR, line); leaveblock(fs); /* loop scope ('break' jumps to this point) */ } static void test_then_block (LexState *ls, int *escapelist) { /* test_then_block -> [IF | ELSEIF] cond THEN block */ BlockCnt bl; FuncState *fs = ls->fs; expdesc v; int jf; /* instruction to skip 'then' code (if condition is false) */ luaX_next(ls); /* skip IF or ELSEIF */ expr(ls, &v); /* read condition */ checknext(ls, TK_THEN); if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) { luaK_goiffalse(ls->fs, &v); /* will jump to label if condition is true */ enterblock(fs, &bl, 0); /* must enter block before 'goto' */ gotostat(ls, v.t); /* handle goto/break */ skipnoopstat(ls); /* skip other no-op statements */ if (block_follow(ls, 0)) { /* 'goto' is the entire block? */ leaveblock(fs); return; /* and that is it */ } else /* must skip over 'then' part if condition is false */ jf = luaK_jump(fs); } else { /* regular case (not goto/break) */ luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */ enterblock(fs, &bl, 0); jf = v.f; } statlist(ls); /* 'then' part */ leaveblock(fs); if (ls->t.token == TK_ELSE || ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */ luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */ luaK_patchtohere(fs, jf); } static void ifstat (LexState *ls, int line) { /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */ FuncState *fs = ls->fs; int escapelist = NO_JUMP; /* exit list for finished parts */ test_then_block(ls, &escapelist); /* IF cond THEN block */ while (ls->t.token == TK_ELSEIF) test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */ if (testnext(ls, TK_ELSE)) block(ls); /* 'else' part */ check_match(ls, TK_END, TK_IF, line); luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */ } static void localfunc (LexState *ls) { expdesc b; FuncState *fs = ls->fs; new_localvar(ls, str_checkname(ls)); /* new local variable */ adjustlocalvars(ls, 1); /* enter its scope */ body(ls, &b, 0, ls->linenumber); /* function created in next register */ /* debug information will only see the variable after this point! */ getlocvar(fs, b.u.info)->startpc = fs->pc; } static void localstat (LexState *ls) { /* stat -> LOCAL NAME {',' NAME} ['=' explist] */ int nvars = 0; int nexps; expdesc e; do { new_localvar(ls, str_checkname(ls)); nvars++; } while (testnext(ls, ',')); if (testnext(ls, '=')) nexps = explist(ls, &e); else { e.k = VVOID; nexps = 0; } adjust_assign(ls, nvars, nexps, &e); adjustlocalvars(ls, nvars); } static int funcname (LexState *ls, expdesc *v) { /* funcname -> NAME {fieldsel} [':' NAME] */ int ismethod = 0; singlevar(ls, v); while (ls->t.token == '.') fieldsel(ls, v); if (ls->t.token == ':') { ismethod = 1; fieldsel(ls, v); } return ismethod; } static void funcstat (LexState *ls, int line) { /* funcstat -> FUNCTION funcname body */ int ismethod; expdesc v, b; luaX_next(ls); /* skip FUNCTION */ ismethod = funcname(ls, &v); body(ls, &b, ismethod, line); luaK_storevar(ls->fs, &v, &b); luaK_fixline(ls->fs, line); /* definition "happens" in the first line */ } static void exprstat (LexState *ls) { /* stat -> func | assignment */ FuncState *fs = ls->fs; struct LHS_assign v; suffixedexp(ls, &v.v); if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */ v.prev = NULL; assignment(ls, &v, 1); } else { /* stat -> func */ check_condition(ls, v.v.k == VCALL, "syntax error"); SETARG_C(getinstruction(fs, &v.v), 1); /* call statement uses no results */ } } static void retstat (LexState *ls) { /* stat -> RETURN [explist] [';'] */ FuncState *fs = ls->fs; expdesc e; int first, nret; /* registers with returned values */ if (block_follow(ls, 1) || ls->t.token == ';') first = nret = 0; /* return no values */ else { nret = explist(ls, &e); /* optional return values */ if (hasmultret(e.k)) { luaK_setmultret(fs, &e); if (e.k == VCALL && nret == 1) { /* tail call? */ SET_OPCODE(getinstruction(fs,&e), OP_TAILCALL); lua_assert(GETARG_A(getinstruction(fs,&e)) == fs->nactvar); } first = fs->nactvar; nret = LUA_MULTRET; /* return all values */ } else { if (nret == 1) /* only one single value? */ first = luaK_exp2anyreg(fs, &e); else { luaK_exp2nextreg(fs, &e); /* values must go to the stack */ first = fs->nactvar; /* return all active values */ lua_assert(nret == fs->freereg - first); } } } luaK_ret(fs, first, nret); testnext(ls, ';'); /* skip optional semicolon */ } static void statement (LexState *ls) { int line = ls->linenumber; /* may be needed for error messages */ enterlevel(ls); switch (ls->t.token) { case ';': { /* stat -> ';' (empty statement) */ luaX_next(ls); /* skip ';' */ break; } case TK_IF: { /* stat -> ifstat */ ifstat(ls, line); break; } case TK_WHILE: { /* stat -> whilestat */ whilestat(ls, line); break; } case TK_DO: { /* stat -> DO block END */ luaX_next(ls); /* skip DO */ block(ls); check_match(ls, TK_END, TK_DO, line); break; } case TK_FOR: { /* stat -> forstat */ forstat(ls, line); break; } case TK_REPEAT: { /* stat -> repeatstat */ repeatstat(ls, line); break; } case TK_FUNCTION: { /* stat -> funcstat */ funcstat(ls, line); break; } case TK_LOCAL: { /* stat -> localstat */ luaX_next(ls); /* skip LOCAL */ if (testnext(ls, TK_FUNCTION)) /* local function? */ localfunc(ls); else localstat(ls); break; } case TK_DBCOLON: { /* stat -> label */ luaX_next(ls); /* skip double colon */ labelstat(ls, str_checkname(ls), line); break; } case TK_RETURN: { /* stat -> retstat */ luaX_next(ls); /* skip RETURN */ retstat(ls); break; } case TK_BREAK: /* stat -> breakstat */ case TK_GOTO: { /* stat -> 'goto' NAME */ gotostat(ls, luaK_jump(ls->fs)); break; } default: { /* stat -> func | assignment */ exprstat(ls); break; } } lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg && ls->fs->freereg >= ls->fs->nactvar); ls->fs->freereg = ls->fs->nactvar; /* free registers */ leavelevel(ls); } /* }====================================================================== */ /* ** compiles the main function, which is a regular vararg function with an ** upvalue named LUA_ENV */ static void mainfunc (LexState *ls, FuncState *fs) { BlockCnt bl; expdesc v; open_func(ls, fs, &bl); fs->f->is_vararg = 2; /* main function is always declared vararg */ init_exp(&v, VLOCAL, 0); /* create and... */ newupvalue(fs, ls->envn, &v); /* ...set environment upvalue */ luaX_next(ls); /* read first token */ statlist(ls); /* parse main body */ check(ls, TK_EOS); close_func(ls); } LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, Dyndata *dyd, const char *name, int firstchar) { LexState lexstate; FuncState funcstate; LClosure *cl = luaF_newLclosure(L, 1); /* create main closure */ setclLvalue(L, L->top, cl); /* anchor it (to avoid being collected) */ luaD_inctop(L); lexstate.h = luaH_new(L); /* create table for scanner */ sethvalue(L, L->top, lexstate.h); /* anchor it */ luaD_inctop(L); funcstate.f = cl->p = luaF_newproto(L); funcstate.f->source = luaS_new(L, name); /* create and anchor TString */ lua_assert(iswhite(funcstate.f)); /* do not need barrier here */ lexstate.buff = buff; lexstate.dyd = dyd; dyd->actvar.n = dyd->gt.n = dyd->label.n = 0; luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar); mainfunc(&lexstate, &funcstate); lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs); /* all scopes should be correctly finished */ lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0); L->top--; /* remove scanner's table */ return cl; /* closure is on the stack, too */ }
xLua/build/lua-5.3.3/src/lparser.c/0
{ "file_path": "xLua/build/lua-5.3.3/src/lparser.c", "repo_id": "xLua", "token_count": 19981 }
2,086
/* ** $Id: lcode.c,v 2.112 2016/12/22 13:08:50 roberto Exp $ ** Code generator for Lua ** See Copyright Notice in lua.h */ #define lcode_c #define LUA_CORE #include "lprefix.h" #include <math.h> #include <stdlib.h> #include "lua.h" #include "lcode.h" #include "ldebug.h" #include "ldo.h" #include "lgc.h" #include "llex.h" #include "lmem.h" #include "lobject.h" #include "lopcodes.h" #include "lparser.h" #include "lstring.h" #include "ltable.h" #include "lvm.h" /* Maximum number of registers in a Lua function (must fit in 8 bits) */ #define MAXREGS 255 #define hasjumps(e) ((e)->t != (e)->f) /* ** If expression is a numeric constant, fills 'v' with its value ** and returns 1. Otherwise, returns 0. */ static int tonumeral(const expdesc *e, TValue *v) { if (hasjumps(e)) return 0; /* not a numeral */ switch (e->k) { case VKINT: if (v) setivalue(v, e->u.ival); return 1; case VKFLT: if (v) setfltvalue(v, e->u.nval); return 1; default: return 0; } } /* ** Create a OP_LOADNIL instruction, but try to optimize: if the previous ** instruction is also OP_LOADNIL and ranges are compatible, adjust ** range of previous instruction instead of emitting a new one. (For ** instance, 'local a; local b' will generate a single opcode.) */ void luaK_nil (FuncState *fs, int from, int n) { Instruction *previous; int l = from + n - 1; /* last register to set nil */ if (fs->pc > fs->lasttarget) { /* no jumps to current position? */ previous = &fs->f->code[fs->pc-1]; if (GET_OPCODE(*previous) == OP_LOADNIL) { /* previous is LOADNIL? */ int pfrom = GETARG_A(*previous); /* get previous range */ int pl = pfrom + GETARG_B(*previous); if ((pfrom <= from && from <= pl + 1) || (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */ if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */ if (pl > l) l = pl; /* l = max(l, pl) */ SETARG_A(*previous, from); SETARG_B(*previous, l - from); return; } } /* else go through */ } luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */ } /* ** Gets the destination address of a jump instruction. Used to traverse ** a list of jumps. */ static int getjump (FuncState *fs, int pc) { int offset = GETARG_sBx(fs->f->code[pc]); if (offset == NO_JUMP) /* point to itself represents end of list */ return NO_JUMP; /* end of list */ else return (pc+1)+offset; /* turn offset into absolute position */ } /* ** Fix jump instruction at position 'pc' to jump to 'dest'. ** (Jump addresses are relative in Lua) */ static void fixjump (FuncState *fs, int pc, int dest) { Instruction *jmp = &fs->f->code[pc]; int offset = dest - (pc + 1); lua_assert(dest != NO_JUMP); if (abs(offset) > MAXARG_sBx) luaX_syntaxerror(fs->ls, "control structure too long"); SETARG_sBx(*jmp, offset); } /* ** Concatenate jump-list 'l2' into jump-list 'l1' */ void luaK_concat (FuncState *fs, int *l1, int l2) { if (l2 == NO_JUMP) return; /* nothing to concatenate? */ else if (*l1 == NO_JUMP) /* no original list? */ *l1 = l2; /* 'l1' points to 'l2' */ else { int list = *l1; int next; while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */ list = next; fixjump(fs, list, l2); /* last element links to 'l2' */ } } /* ** Create a jump instruction and return its position, so its destination ** can be fixed later (with 'fixjump'). If there are jumps to ** this position (kept in 'jpc'), link them all together so that ** 'patchlistaux' will fix all them directly to the final destination. */ int luaK_jump (FuncState *fs) { int jpc = fs->jpc; /* save list of jumps to here */ int j; fs->jpc = NO_JUMP; /* no more jumps to here */ j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP); luaK_concat(fs, &j, jpc); /* keep them on hold */ return j; } /* ** Code a 'return' instruction */ void luaK_ret (FuncState *fs, int first, int nret) { luaK_codeABC(fs, OP_RETURN, first, nret+1, 0); } /* ** Code a "conditional jump", that is, a test or comparison opcode ** followed by a jump. Return jump position. */ static int condjump (FuncState *fs, OpCode op, int A, int B, int C) { luaK_codeABC(fs, op, A, B, C); return luaK_jump(fs); } /* ** returns current 'pc' and marks it as a jump target (to avoid wrong ** optimizations with consecutive instructions not in the same basic block). */ int luaK_getlabel (FuncState *fs) { fs->lasttarget = fs->pc; return fs->pc; } /* ** Returns the position of the instruction "controlling" a given ** jump (that is, its condition), or the jump itself if it is ** unconditional. */ static Instruction *getjumpcontrol (FuncState *fs, int pc) { Instruction *pi = &fs->f->code[pc]; if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1)))) return pi-1; else return pi; } /* ** Patch destination register for a TESTSET instruction. ** If instruction in position 'node' is not a TESTSET, return 0 ("fails"). ** Otherwise, if 'reg' is not 'NO_REG', set it as the destination ** register. Otherwise, change instruction to a simple 'TEST' (produces ** no register value) */ static int patchtestreg (FuncState *fs, int node, int reg) { Instruction *i = getjumpcontrol(fs, node); if (GET_OPCODE(*i) != OP_TESTSET) return 0; /* cannot patch other instructions */ if (reg != NO_REG && reg != GETARG_B(*i)) SETARG_A(*i, reg); else { /* no register to put value or register already has the value; change instruction to simple test */ *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i)); } return 1; } /* ** Traverse a list of tests ensuring no one produces a value */ static void removevalues (FuncState *fs, int list) { for (; list != NO_JUMP; list = getjump(fs, list)) patchtestreg(fs, list, NO_REG); } /* ** Traverse a list of tests, patching their destination address and ** registers: tests producing values jump to 'vtarget' (and put their ** values in 'reg'), other tests jump to 'dtarget'. */ static void patchlistaux (FuncState *fs, int list, int vtarget, int reg, int dtarget) { while (list != NO_JUMP) { int next = getjump(fs, list); if (patchtestreg(fs, list, reg)) fixjump(fs, list, vtarget); else fixjump(fs, list, dtarget); /* jump to default target */ list = next; } } /* ** Ensure all pending jumps to current position are fixed (jumping ** to current position with no values) and reset list of pending ** jumps */ static void dischargejpc (FuncState *fs) { patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc); fs->jpc = NO_JUMP; } /* ** Add elements in 'list' to list of pending jumps to "here" ** (current position) */ void luaK_patchtohere (FuncState *fs, int list) { luaK_getlabel(fs); /* mark "here" as a jump target */ luaK_concat(fs, &fs->jpc, list); } /* ** Path all jumps in 'list' to jump to 'target'. ** (The assert means that we cannot fix a jump to a forward address ** because we only know addresses once code is generated.) */ void luaK_patchlist (FuncState *fs, int list, int target) { if (target == fs->pc) /* 'target' is current position? */ luaK_patchtohere(fs, list); /* add list to pending jumps */ else { lua_assert(target < fs->pc); patchlistaux(fs, list, target, NO_REG, target); } } /* ** Path all jumps in 'list' to close upvalues up to given 'level' ** (The assertion checks that jumps either were closing nothing ** or were closing higher levels, from inner blocks.) */ void luaK_patchclose (FuncState *fs, int list, int level) { level++; /* argument is +1 to reserve 0 as non-op */ for (; list != NO_JUMP; list = getjump(fs, list)) { lua_assert(GET_OPCODE(fs->f->code[list]) == OP_JMP && (GETARG_A(fs->f->code[list]) == 0 || GETARG_A(fs->f->code[list]) >= level)); SETARG_A(fs->f->code[list], level); } } /* ** Emit instruction 'i', checking for array sizes and saving also its ** line information. Return 'i' position. */ static int luaK_code (FuncState *fs, Instruction i) { Proto *f = fs->f; dischargejpc(fs); /* 'pc' will change */ /* put new instruction in code array */ luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction, MAX_INT, "opcodes"); f->code[fs->pc] = i; /* save corresponding line information */ luaM_growvector(fs->ls->L, f->lineinfo, fs->pc, f->sizelineinfo, int, MAX_INT, "opcodes"); f->lineinfo[fs->pc] = fs->ls->lastline; return fs->pc++; } /* ** Format and emit an 'iABC' instruction. (Assertions check consistency ** of parameters versus opcode.) */ int luaK_codeABC (FuncState *fs, OpCode o, int a, int b, int c) { lua_assert(getOpMode(o) == iABC); lua_assert(getBMode(o) != OpArgN || b == 0); lua_assert(getCMode(o) != OpArgN || c == 0); lua_assert(a <= MAXARG_A && b <= MAXARG_B && c <= MAXARG_C); return luaK_code(fs, CREATE_ABC(o, a, b, c)); } /* ** Format and emit an 'iABx' instruction. */ int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) { lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx); lua_assert(getCMode(o) == OpArgN); lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx); return luaK_code(fs, CREATE_ABx(o, a, bc)); } /* ** Emit an "extra argument" instruction (format 'iAx') */ static int codeextraarg (FuncState *fs, int a) { lua_assert(a <= MAXARG_Ax); return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, a)); } /* ** Emit a "load constant" instruction, using either 'OP_LOADK' ** (if constant index 'k' fits in 18 bits) or an 'OP_LOADKX' ** instruction with "extra argument". */ int luaK_codek (FuncState *fs, int reg, int k) { if (k <= MAXARG_Bx) return luaK_codeABx(fs, OP_LOADK, reg, k); else { int p = luaK_codeABx(fs, OP_LOADKX, reg, 0); codeextraarg(fs, k); return p; } } /* ** Check register-stack level, keeping track of its maximum size ** in field 'maxstacksize' */ void luaK_checkstack (FuncState *fs, int n) { int newstack = fs->freereg + n; if (newstack > fs->f->maxstacksize) { if (newstack >= MAXREGS) luaX_syntaxerror(fs->ls, "function or expression needs too many registers"); fs->f->maxstacksize = cast_byte(newstack); } } /* ** Reserve 'n' registers in register stack */ void luaK_reserveregs (FuncState *fs, int n) { luaK_checkstack(fs, n); fs->freereg += n; } /* ** Free register 'reg', if it is neither a constant index nor ** a local variable. ) */ static void freereg (FuncState *fs, int reg) { if (!ISK(reg) && reg >= fs->nactvar) { fs->freereg--; lua_assert(reg == fs->freereg); } } /* ** Free register used by expression 'e' (if any) */ static void freeexp (FuncState *fs, expdesc *e) { if (e->k == VNONRELOC) freereg(fs, e->u.info); } /* ** Free registers used by expressions 'e1' and 'e2' (if any) in proper ** order. */ static void freeexps (FuncState *fs, expdesc *e1, expdesc *e2) { int r1 = (e1->k == VNONRELOC) ? e1->u.info : -1; int r2 = (e2->k == VNONRELOC) ? e2->u.info : -1; if (r1 > r2) { freereg(fs, r1); freereg(fs, r2); } else { freereg(fs, r2); freereg(fs, r1); } } /* ** Add constant 'v' to prototype's list of constants (field 'k'). ** Use scanner's table to cache position of constants in constant list ** and try to reuse constants. Because some values should not be used ** as keys (nil cannot be a key, integer keys can collapse with float ** keys), the caller must provide a useful 'key' for indexing the cache. */ static int addk (FuncState *fs, TValue *key, TValue *v) { lua_State *L = fs->ls->L; Proto *f = fs->f; TValue *idx = luaH_set(L, fs->ls->h, key); /* index scanner table */ int k, oldsize; if (ttisinteger(idx)) { /* is there an index there? */ k = cast_int(ivalue(idx)); /* correct value? (warning: must distinguish floats from integers!) */ if (k < fs->nk && ttype(&f->k[k]) == ttype(v) && luaV_rawequalobj(&f->k[k], v)) return k; /* reuse index */ } /* constant not found; create a new entry */ oldsize = f->sizek; k = fs->nk; /* numerical value does not need GC barrier; table has no metatable, so it does not need to invalidate cache */ setivalue(idx, k); luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants"); while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]); setobj(L, &f->k[k], v); fs->nk++; luaC_barrier(L, f, v); return k; } /* ** Add a string to list of constants and return its index. */ int luaK_stringK (FuncState *fs, TString *s) { TValue o; setsvalue(fs->ls->L, &o, s); return addk(fs, &o, &o); /* use string itself as key */ } /* ** Add an integer to list of constants and return its index. ** Integers use userdata as keys to avoid collision with floats with ** same value; conversion to 'void*' is used only for hashing, so there ** are no "precision" problems. */ int luaK_intK (FuncState *fs, lua_Integer n) { TValue k, o; setpvalue(&k, cast(void*, cast(size_t, n))); setivalue(&o, n); return addk(fs, &k, &o); } /* ** Add a float to list of constants and return its index. */ static int luaK_numberK (FuncState *fs, lua_Number r) { TValue o; setfltvalue(&o, r); return addk(fs, &o, &o); /* use number itself as key */ } /* ** Add a boolean to list of constants and return its index. */ static int boolK (FuncState *fs, int b) { TValue o; setbvalue(&o, b); return addk(fs, &o, &o); /* use boolean itself as key */ } /* ** Add nil to list of constants and return its index. */ static int nilK (FuncState *fs) { TValue k, v; setnilvalue(&v); /* cannot use nil as key; instead use table itself to represent nil */ sethvalue(fs->ls->L, &k, fs->ls->h); return addk(fs, &k, &v); } /* ** Fix an expression to return the number of results 'nresults'. ** Either 'e' is a multi-ret expression (function call or vararg) ** or 'nresults' is LUA_MULTRET (as any expression can satisfy that). */ void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) { if (e->k == VCALL) { /* expression is an open function call? */ SETARG_C(getinstruction(fs, e), nresults + 1); } else if (e->k == VVARARG) { Instruction *pc = &getinstruction(fs, e); SETARG_B(*pc, nresults + 1); SETARG_A(*pc, fs->freereg); luaK_reserveregs(fs, 1); } else lua_assert(nresults == LUA_MULTRET); } /* ** Fix an expression to return one result. ** If expression is not a multi-ret expression (function call or ** vararg), it already returns one result, so nothing needs to be done. ** Function calls become VNONRELOC expressions (as its result comes ** fixed in the base register of the call), while vararg expressions ** become VRELOCABLE (as OP_VARARG puts its results where it wants). ** (Calls are created returning one result, so that does not need ** to be fixed.) */ void luaK_setoneret (FuncState *fs, expdesc *e) { if (e->k == VCALL) { /* expression is an open function call? */ /* already returns 1 value */ lua_assert(GETARG_C(getinstruction(fs, e)) == 2); e->k = VNONRELOC; /* result has fixed position */ e->u.info = GETARG_A(getinstruction(fs, e)); } else if (e->k == VVARARG) { SETARG_B(getinstruction(fs, e), 2); e->k = VRELOCABLE; /* can relocate its simple result */ } } /* ** Ensure that expression 'e' is not a variable. */ void luaK_dischargevars (FuncState *fs, expdesc *e) { switch (e->k) { case VLOCAL: { /* already in a register */ e->k = VNONRELOC; /* becomes a non-relocatable value */ break; } case VUPVAL: { /* move value to some (pending) register */ e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0); e->k = VRELOCABLE; break; } case VINDEXED: { OpCode op; freereg(fs, e->u.ind.idx); if (e->u.ind.vt == VLOCAL) { /* is 't' in a register? */ freereg(fs, e->u.ind.t); op = OP_GETTABLE; } else { lua_assert(e->u.ind.vt == VUPVAL); op = OP_GETTABUP; /* 't' is in an upvalue */ } e->u.info = luaK_codeABC(fs, op, 0, e->u.ind.t, e->u.ind.idx); e->k = VRELOCABLE; break; } case VVARARG: case VCALL: { luaK_setoneret(fs, e); break; } default: break; /* there is one value available (somewhere) */ } } /* ** Ensures expression value is in register 'reg' (and therefore ** 'e' will become a non-relocatable expression). */ static void discharge2reg (FuncState *fs, expdesc *e, int reg) { luaK_dischargevars(fs, e); switch (e->k) { case VNIL: { luaK_nil(fs, reg, 1); break; } case VFALSE: case VTRUE: { luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0); break; } case VK: { luaK_codek(fs, reg, e->u.info); break; } case VKFLT: { luaK_codek(fs, reg, luaK_numberK(fs, e->u.nval)); break; } case VKINT: { luaK_codek(fs, reg, luaK_intK(fs, e->u.ival)); break; } case VRELOCABLE: { Instruction *pc = &getinstruction(fs, e); SETARG_A(*pc, reg); /* instruction will put result in 'reg' */ break; } case VNONRELOC: { if (reg != e->u.info) luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0); break; } default: { lua_assert(e->k == VJMP); return; /* nothing to do... */ } } e->u.info = reg; e->k = VNONRELOC; } /* ** Ensures expression value is in any register. */ static void discharge2anyreg (FuncState *fs, expdesc *e) { if (e->k != VNONRELOC) { /* no fixed register yet? */ luaK_reserveregs(fs, 1); /* get a register */ discharge2reg(fs, e, fs->freereg-1); /* put value there */ } } static int code_loadbool (FuncState *fs, int A, int b, int jump) { luaK_getlabel(fs); /* those instructions may be jump targets */ return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump); } /* ** check whether list has any jump that do not produce a value ** or produce an inverted value */ static int need_value (FuncState *fs, int list) { for (; list != NO_JUMP; list = getjump(fs, list)) { Instruction i = *getjumpcontrol(fs, list); if (GET_OPCODE(i) != OP_TESTSET) return 1; } return 0; /* not found */ } /* ** Ensures final expression result (including results from its jump ** lists) is in register 'reg'. ** If expression has jumps, need to patch these jumps either to ** its final position or to "load" instructions (for those tests ** that do not produce values). */ static void exp2reg (FuncState *fs, expdesc *e, int reg) { discharge2reg(fs, e, reg); if (e->k == VJMP) /* expression itself is a test? */ luaK_concat(fs, &e->t, e->u.info); /* put this jump in 't' list */ if (hasjumps(e)) { int final; /* position after whole expression */ int p_f = NO_JUMP; /* position of an eventual LOAD false */ int p_t = NO_JUMP; /* position of an eventual LOAD true */ if (need_value(fs, e->t) || need_value(fs, e->f)) { int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs); p_f = code_loadbool(fs, reg, 0, 1); p_t = code_loadbool(fs, reg, 1, 0); luaK_patchtohere(fs, fj); } final = luaK_getlabel(fs); patchlistaux(fs, e->f, final, reg, p_f); patchlistaux(fs, e->t, final, reg, p_t); } e->f = e->t = NO_JUMP; e->u.info = reg; e->k = VNONRELOC; } /* ** Ensures final expression result (including results from its jump ** lists) is in next available register. */ void luaK_exp2nextreg (FuncState *fs, expdesc *e) { luaK_dischargevars(fs, e); freeexp(fs, e); luaK_reserveregs(fs, 1); exp2reg(fs, e, fs->freereg - 1); } /* ** Ensures final expression result (including results from its jump ** lists) is in some (any) register and return that register. */ int luaK_exp2anyreg (FuncState *fs, expdesc *e) { luaK_dischargevars(fs, e); if (e->k == VNONRELOC) { /* expression already has a register? */ if (!hasjumps(e)) /* no jumps? */ return e->u.info; /* result is already in a register */ if (e->u.info >= fs->nactvar) { /* reg. is not a local? */ exp2reg(fs, e, e->u.info); /* put final result in it */ return e->u.info; } } luaK_exp2nextreg(fs, e); /* otherwise, use next available register */ return e->u.info; } /* ** Ensures final expression result is either in a register or in an ** upvalue. */ void luaK_exp2anyregup (FuncState *fs, expdesc *e) { if (e->k != VUPVAL || hasjumps(e)) luaK_exp2anyreg(fs, e); } /* ** Ensures final expression result is either in a register or it is ** a constant. */ void luaK_exp2val (FuncState *fs, expdesc *e) { if (hasjumps(e)) luaK_exp2anyreg(fs, e); else luaK_dischargevars(fs, e); } /* ** Ensures final expression result is in a valid R/K index ** (that is, it is either in a register or in 'k' with an index ** in the range of R/K indices). ** Returns R/K index. */ int luaK_exp2RK (FuncState *fs, expdesc *e) { luaK_exp2val(fs, e); switch (e->k) { /* move constants to 'k' */ case VTRUE: e->u.info = boolK(fs, 1); goto vk; case VFALSE: e->u.info = boolK(fs, 0); goto vk; case VNIL: e->u.info = nilK(fs); goto vk; case VKINT: e->u.info = luaK_intK(fs, e->u.ival); goto vk; case VKFLT: e->u.info = luaK_numberK(fs, e->u.nval); goto vk; case VK: vk: e->k = VK; if (e->u.info <= MAXINDEXRK) /* constant fits in 'argC'? */ return RKASK(e->u.info); else break; default: break; } /* not a constant in the right range: put it in a register */ return luaK_exp2anyreg(fs, e); } /* ** Generate code to store result of expression 'ex' into variable 'var'. */ void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) { switch (var->k) { case VLOCAL: { freeexp(fs, ex); exp2reg(fs, ex, var->u.info); /* compute 'ex' into proper place */ return; } case VUPVAL: { int e = luaK_exp2anyreg(fs, ex); luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0); break; } case VINDEXED: { OpCode op = (var->u.ind.vt == VLOCAL) ? OP_SETTABLE : OP_SETTABUP; int e = luaK_exp2RK(fs, ex); luaK_codeABC(fs, op, var->u.ind.t, var->u.ind.idx, e); break; } default: lua_assert(0); /* invalid var kind to store */ } freeexp(fs, ex); } /* ** Emit SELF instruction (convert expression 'e' into 'e:key(e,'). */ void luaK_self (FuncState *fs, expdesc *e, expdesc *key) { int ereg; luaK_exp2anyreg(fs, e); ereg = e->u.info; /* register where 'e' was placed */ freeexp(fs, e); e->u.info = fs->freereg; /* base register for op_self */ e->k = VNONRELOC; /* self expression has a fixed register */ luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */ luaK_codeABC(fs, OP_SELF, e->u.info, ereg, luaK_exp2RK(fs, key)); freeexp(fs, key); } /* ** Negate condition 'e' (where 'e' is a comparison). */ static void negatecondition (FuncState *fs, expdesc *e) { Instruction *pc = getjumpcontrol(fs, e->u.info); lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET && GET_OPCODE(*pc) != OP_TEST); SETARG_A(*pc, !(GETARG_A(*pc))); } /* ** Emit instruction to jump if 'e' is 'cond' (that is, if 'cond' ** is true, code will jump if 'e' is true.) Return jump position. ** Optimize when 'e' is 'not' something, inverting the condition ** and removing the 'not'. */ static int jumponcond (FuncState *fs, expdesc *e, int cond) { if (e->k == VRELOCABLE) { Instruction ie = getinstruction(fs, e); if (GET_OPCODE(ie) == OP_NOT) { fs->pc--; /* remove previous OP_NOT */ return condjump(fs, OP_TEST, GETARG_B(ie), 0, !cond); } /* else go through */ } discharge2anyreg(fs, e); freeexp(fs, e); return condjump(fs, OP_TESTSET, NO_REG, e->u.info, cond); } /* ** Emit code to go through if 'e' is true, jump otherwise. */ void luaK_goiftrue (FuncState *fs, expdesc *e) { int pc; /* pc of new jump */ luaK_dischargevars(fs, e); switch (e->k) { case VJMP: { /* condition? */ negatecondition(fs, e); /* jump when it is false */ pc = e->u.info; /* save jump position */ break; } case VK: case VKFLT: case VKINT: case VTRUE: { pc = NO_JUMP; /* always true; do nothing */ break; } default: { pc = jumponcond(fs, e, 0); /* jump when false */ break; } } luaK_concat(fs, &e->f, pc); /* insert new jump in false list */ luaK_patchtohere(fs, e->t); /* true list jumps to here (to go through) */ e->t = NO_JUMP; } /* ** Emit code to go through if 'e' is false, jump otherwise. */ void luaK_goiffalse (FuncState *fs, expdesc *e) { int pc; /* pc of new jump */ luaK_dischargevars(fs, e); switch (e->k) { case VJMP: { pc = e->u.info; /* already jump if true */ break; } case VNIL: case VFALSE: { pc = NO_JUMP; /* always false; do nothing */ break; } default: { pc = jumponcond(fs, e, 1); /* jump if true */ break; } } luaK_concat(fs, &e->t, pc); /* insert new jump in 't' list */ luaK_patchtohere(fs, e->f); /* false list jumps to here (to go through) */ e->f = NO_JUMP; } /* ** Code 'not e', doing constant folding. */ static void codenot (FuncState *fs, expdesc *e) { luaK_dischargevars(fs, e); switch (e->k) { case VNIL: case VFALSE: { e->k = VTRUE; /* true == not nil == not false */ break; } case VK: case VKFLT: case VKINT: case VTRUE: { e->k = VFALSE; /* false == not "x" == not 0.5 == not 1 == not true */ break; } case VJMP: { negatecondition(fs, e); break; } case VRELOCABLE: case VNONRELOC: { discharge2anyreg(fs, e); freeexp(fs, e); e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0); e->k = VRELOCABLE; break; } default: lua_assert(0); /* cannot happen */ } /* interchange true and false lists */ { int temp = e->f; e->f = e->t; e->t = temp; } removevalues(fs, e->f); /* values are useless when negated */ removevalues(fs, e->t); } /* ** Create expression 't[k]'. 't' must have its final result already in a ** register or upvalue. */ void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) { lua_assert(!hasjumps(t) && (vkisinreg(t->k) || t->k == VUPVAL)); t->u.ind.t = t->u.info; /* register or upvalue index */ t->u.ind.idx = luaK_exp2RK(fs, k); /* R/K index for key */ t->u.ind.vt = (t->k == VUPVAL) ? VUPVAL : VLOCAL; t->k = VINDEXED; } /* ** Return false if folding can raise an error. ** Bitwise operations need operands convertible to integers; division ** operations cannot have 0 as divisor. */ static int validop (int op, TValue *v1, TValue *v2) { switch (op) { case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR: case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* conversion errors */ lua_Integer i; return (tointeger(v1, &i) && tointeger(v2, &i)); } case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */ return (nvalue(v2) != 0); default: return 1; /* everything else is valid */ } } /* ** Try to "constant-fold" an operation; return 1 iff successful. ** (In this case, 'e1' has the final result.) */ static int constfolding (FuncState *fs, int op, expdesc *e1, const expdesc *e2) { TValue v1, v2, res; if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2)) return 0; /* non-numeric operands or not safe to fold */ luaO_arith(fs->ls->L, op, &v1, &v2, &res); /* does operation */ if (ttisinteger(&res)) { e1->k = VKINT; e1->u.ival = ivalue(&res); } else { /* folds neither NaN nor 0.0 (to avoid problems with -0.0) */ lua_Number n = fltvalue(&res); if (luai_numisnan(n) || n == 0) return 0; e1->k = VKFLT; e1->u.nval = n; } return 1; } /* ** Emit code for unary expressions that "produce values" ** (everything but 'not'). ** Expression to produce final result will be encoded in 'e'. */ static void codeunexpval (FuncState *fs, OpCode op, expdesc *e, int line) { int r = luaK_exp2anyreg(fs, e); /* opcodes operate only on registers */ freeexp(fs, e); e->u.info = luaK_codeABC(fs, op, 0, r, 0); /* generate opcode */ e->k = VRELOCABLE; /* all those operations are relocatable */ luaK_fixline(fs, line); } /* ** Emit code for binary expressions that "produce values" ** (everything but logical operators 'and'/'or' and comparison ** operators). ** Expression to produce final result will be encoded in 'e1'. ** Because 'luaK_exp2RK' can free registers, its calls must be ** in "stack order" (that is, first on 'e2', which may have more ** recent registers to be released). */ static void codebinexpval (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2, int line) { int rk2 = luaK_exp2RK(fs, e2); /* both operands are "RK" */ int rk1 = luaK_exp2RK(fs, e1); freeexps(fs, e1, e2); e1->u.info = luaK_codeABC(fs, op, 0, rk1, rk2); /* generate opcode */ e1->k = VRELOCABLE; /* all those operations are relocatable */ luaK_fixline(fs, line); } /* ** Emit code for comparisons. ** 'e1' was already put in R/K form by 'luaK_infix'. */ static void codecomp (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) { int rk1 = (e1->k == VK) ? RKASK(e1->u.info) : check_exp(e1->k == VNONRELOC, e1->u.info); int rk2 = luaK_exp2RK(fs, e2); freeexps(fs, e1, e2); switch (opr) { case OPR_NE: { /* '(a ~= b)' ==> 'not (a == b)' */ e1->u.info = condjump(fs, OP_EQ, 0, rk1, rk2); break; } case OPR_GT: case OPR_GE: { /* '(a > b)' ==> '(b < a)'; '(a >= b)' ==> '(b <= a)' */ OpCode op = cast(OpCode, (opr - OPR_NE) + OP_EQ); e1->u.info = condjump(fs, op, 1, rk2, rk1); /* invert operands */ break; } default: { /* '==', '<', '<=' use their own opcodes */ OpCode op = cast(OpCode, (opr - OPR_EQ) + OP_EQ); e1->u.info = condjump(fs, op, 1, rk1, rk2); break; } } e1->k = VJMP; } /* ** Aplly prefix operation 'op' to expression 'e'. */ void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) { static const expdesc ef = {VKINT, {0}, NO_JUMP, NO_JUMP}; switch (op) { case OPR_MINUS: case OPR_BNOT: /* use 'ef' as fake 2nd operand */ if (constfolding(fs, op + LUA_OPUNM, e, &ef)) break; /* FALLTHROUGH */ case OPR_LEN: codeunexpval(fs, cast(OpCode, op + OP_UNM), e, line); break; case OPR_NOT: codenot(fs, e); break; default: lua_assert(0); } } /* ** Process 1st operand 'v' of binary operation 'op' before reading ** 2nd operand. */ void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) { switch (op) { case OPR_AND: { luaK_goiftrue(fs, v); /* go ahead only if 'v' is true */ break; } case OPR_OR: { luaK_goiffalse(fs, v); /* go ahead only if 'v' is false */ break; } case OPR_CONCAT: { luaK_exp2nextreg(fs, v); /* operand must be on the 'stack' */ break; } case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV: case OPR_IDIV: case OPR_MOD: case OPR_POW: case OPR_BAND: case OPR_BOR: case OPR_BXOR: case OPR_SHL: case OPR_SHR: { if (!tonumeral(v, NULL)) luaK_exp2RK(fs, v); /* else keep numeral, which may be folded with 2nd operand */ break; } default: { luaK_exp2RK(fs, v); break; } } } /* ** Finalize code for binary operation, after reading 2nd operand. ** For '(a .. b .. c)' (which is '(a .. (b .. c))', because ** concatenation is right associative), merge second CONCAT into first ** one. */ void luaK_posfix (FuncState *fs, BinOpr op, expdesc *e1, expdesc *e2, int line) { switch (op) { case OPR_AND: { lua_assert(e1->t == NO_JUMP); /* list closed by 'luK_infix' */ luaK_dischargevars(fs, e2); luaK_concat(fs, &e2->f, e1->f); *e1 = *e2; break; } case OPR_OR: { lua_assert(e1->f == NO_JUMP); /* list closed by 'luK_infix' */ luaK_dischargevars(fs, e2); luaK_concat(fs, &e2->t, e1->t); *e1 = *e2; break; } case OPR_CONCAT: { luaK_exp2val(fs, e2); if (e2->k == VRELOCABLE && GET_OPCODE(getinstruction(fs, e2)) == OP_CONCAT) { lua_assert(e1->u.info == GETARG_B(getinstruction(fs, e2))-1); freeexp(fs, e1); SETARG_B(getinstruction(fs, e2), e1->u.info); e1->k = VRELOCABLE; e1->u.info = e2->u.info; } else { luaK_exp2nextreg(fs, e2); /* operand must be on the 'stack' */ codebinexpval(fs, OP_CONCAT, e1, e2, line); } break; } case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV: case OPR_IDIV: case OPR_MOD: case OPR_POW: case OPR_BAND: case OPR_BOR: case OPR_BXOR: case OPR_SHL: case OPR_SHR: { if (!constfolding(fs, op + LUA_OPADD, e1, e2)) codebinexpval(fs, cast(OpCode, op + OP_ADD), e1, e2, line); break; } case OPR_EQ: case OPR_LT: case OPR_LE: case OPR_NE: case OPR_GT: case OPR_GE: { codecomp(fs, op, e1, e2); break; } default: lua_assert(0); } } /* ** Change line information associated with current position. */ void luaK_fixline (FuncState *fs, int line) { fs->f->lineinfo[fs->pc - 1] = line; } /* ** Emit a SETLIST instruction. ** 'base' is register that keeps table; ** 'nelems' is #table plus those to be stored now; ** 'tostore' is number of values (in registers 'base + 1',...) to add to ** table (or LUA_MULTRET to add up to stack top). */ void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) { int c = (nelems - 1)/LFIELDS_PER_FLUSH + 1; int b = (tostore == LUA_MULTRET) ? 0 : tostore; lua_assert(tostore != 0 && tostore <= LFIELDS_PER_FLUSH); if (c <= MAXARG_C) luaK_codeABC(fs, OP_SETLIST, base, b, c); else if (c <= MAXARG_Ax) { luaK_codeABC(fs, OP_SETLIST, base, b, 0); codeextraarg(fs, c); } else luaX_syntaxerror(fs->ls, "constructor too long"); fs->freereg = base + 1; /* free registers with list values */ }
xLua/build/lua-5.3.4/src/lcode.c/0
{ "file_path": "xLua/build/lua-5.3.4/src/lcode.c", "repo_id": "xLua", "token_count": 14576 }
2,087
/* ** $Id: liolib.c,v 2.151 2016/12/20 18:37:00 roberto Exp $ ** Standard I/O (and system) library ** See Copyright Notice in lua.h */ #define liolib_c #define LUA_LIB #include "lprefix.h" #include <ctype.h> #include <errno.h> #include <locale.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #include "lualib.h" /* ** Change this macro to accept other modes for 'fopen' besides ** the standard ones. */ #if !defined(l_checkmode) /* accepted extensions to 'mode' in 'fopen' */ #if !defined(L_MODEEXT) #define L_MODEEXT "b" #endif /* Check whether 'mode' matches '[rwa]%+?[L_MODEEXT]*' */ static int l_checkmode (const char *mode) { return (*mode != '\0' && strchr("rwa", *(mode++)) != NULL && (*mode != '+' || (++mode, 1)) && /* skip if char is '+' */ (strspn(mode, L_MODEEXT) == strlen(mode))); /* check extensions */ } #endif /* ** {====================================================== ** l_popen spawns a new process connected to the current ** one through the file streams. ** ======================================================= */ #if !defined(l_popen) /* { */ #if defined(LUA_USE_POSIX) /* { */ #define l_popen(L,c,m) (fflush(NULL), popen(c,m)) #define l_pclose(L,file) (pclose(file)) #elif defined(LUA_USE_WINDOWS) /* }{ */ #define l_popen(L,c,m) (_popen(c,m)) #define l_pclose(L,file) (_pclose(file)) #else /* }{ */ /* ISO C definitions */ #define l_popen(L,c,m) \ ((void)((void)c, m), \ luaL_error(L, "'popen' not supported"), \ (FILE*)0) #define l_pclose(L,file) ((void)L, (void)file, -1) #endif /* } */ #endif /* } */ /* }====================================================== */ #if !defined(l_getc) /* { */ #if defined(LUA_USE_POSIX) #define l_getc(f) getc_unlocked(f) #define l_lockfile(f) flockfile(f) #define l_unlockfile(f) funlockfile(f) #else #define l_getc(f) getc(f) #define l_lockfile(f) ((void)0) #define l_unlockfile(f) ((void)0) #endif #endif /* } */ /* ** {====================================================== ** l_fseek: configuration for longer offsets ** ======================================================= */ #if !defined(l_fseek) /* { */ #if defined(LUA_USE_POSIX) /* { */ #include <sys/types.h> #define l_fseek(f,o,w) fseeko(f,o,w) #define l_ftell(f) ftello(f) #define l_seeknum off_t #elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \ && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */ /* Windows (but not DDK) and Visual C++ 2005 or higher */ #define l_fseek(f,o,w) _fseeki64(f,o,w) #define l_ftell(f) _ftelli64(f) #define l_seeknum __int64 #else /* }{ */ /* ISO C definitions */ #define l_fseek(f,o,w) fseek(f,o,w) #define l_ftell(f) ftell(f) #define l_seeknum long #endif /* } */ #endif /* } */ /* }====================================================== */ #define IO_PREFIX "_IO_" #define IOPREF_LEN (sizeof(IO_PREFIX)/sizeof(char) - 1) #define IO_INPUT (IO_PREFIX "input") #define IO_OUTPUT (IO_PREFIX "output") typedef luaL_Stream LStream; #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE)) #define isclosed(p) ((p)->closef == NULL) static int io_type (lua_State *L) { LStream *p; luaL_checkany(L, 1); p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE); if (p == NULL) lua_pushnil(L); /* not a file */ else if (isclosed(p)) lua_pushliteral(L, "closed file"); else lua_pushliteral(L, "file"); return 1; } static int f_tostring (lua_State *L) { LStream *p = tolstream(L); if (isclosed(p)) lua_pushliteral(L, "file (closed)"); else lua_pushfstring(L, "file (%p)", p->f); return 1; } static FILE *tofile (lua_State *L) { LStream *p = tolstream(L); if (isclosed(p)) luaL_error(L, "attempt to use a closed file"); lua_assert(p->f); return p->f; } /* ** When creating file handles, always creates a 'closed' file handle ** before opening the actual file; so, if there is a memory error, the ** handle is in a consistent state. */ static LStream *newprefile (lua_State *L) { LStream *p = (LStream *)lua_newuserdata(L, sizeof(LStream)); p->closef = NULL; /* mark file handle as 'closed' */ luaL_setmetatable(L, LUA_FILEHANDLE); return p; } /* ** Calls the 'close' function from a file handle. The 'volatile' avoids ** a bug in some versions of the Clang compiler (e.g., clang 3.0 for ** 32 bits). */ static int aux_close (lua_State *L) { LStream *p = tolstream(L); volatile lua_CFunction cf = p->closef; p->closef = NULL; /* mark stream as closed */ return (*cf)(L); /* close it */ } static int io_close (lua_State *L) { if (lua_isnone(L, 1)) /* no argument? */ lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use standard output */ tofile(L); /* make sure argument is an open stream */ return aux_close(L); } static int f_gc (lua_State *L) { LStream *p = tolstream(L); if (!isclosed(p) && p->f != NULL) aux_close(L); /* ignore closed and incompletely open files */ return 0; } /* ** function to close regular files */ static int io_fclose (lua_State *L) { LStream *p = tolstream(L); int res = fclose(p->f); return luaL_fileresult(L, (res == 0), NULL); } static LStream *newfile (lua_State *L) { LStream *p = newprefile(L); p->f = NULL; p->closef = &io_fclose; return p; } static void opencheck (lua_State *L, const char *fname, const char *mode) { LStream *p = newfile(L); p->f = fopen(fname, mode); if (p->f == NULL) luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno)); } static int io_open (lua_State *L) { const char *filename = luaL_checkstring(L, 1); const char *mode = luaL_optstring(L, 2, "r"); LStream *p = newfile(L); const char *md = mode; /* to traverse/check mode */ luaL_argcheck(L, l_checkmode(md), 2, "invalid mode"); p->f = fopen(filename, mode); return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1; } /* ** function to close 'popen' files */ static int io_pclose (lua_State *L) { #if defined(WINAPI_FAMILY_PARTITION) return luaL_error(L, "unsupport api in uwp platform"); #else LStream *p = tolstream(L); return luaL_execresult(L, l_pclose(L, p->f)); #endif } static int io_popen (lua_State *L) { #if defined(WINAPI_FAMILY_PARTITION) return luaL_error(L, "unsupport api in uwp platform"); #else const char *filename = luaL_checkstring(L, 1); const char *mode = luaL_optstring(L, 2, "r"); LStream *p = newprefile(L); p->f = l_popen(L, filename, mode); p->closef = &io_pclose; return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1; #endif } static int io_tmpfile (lua_State *L) { LStream *p = newfile(L); p->f = tmpfile(); return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1; } static FILE *getiofile (lua_State *L, const char *findex) { LStream *p; lua_getfield(L, LUA_REGISTRYINDEX, findex); p = (LStream *)lua_touserdata(L, -1); if (isclosed(p)) luaL_error(L, "standard %s file is closed", findex + IOPREF_LEN); return p->f; } static int g_iofile (lua_State *L, const char *f, const char *mode) { if (!lua_isnoneornil(L, 1)) { const char *filename = lua_tostring(L, 1); if (filename) opencheck(L, filename, mode); else { tofile(L); /* check that it's a valid file handle */ lua_pushvalue(L, 1); } lua_setfield(L, LUA_REGISTRYINDEX, f); } /* return current value */ lua_getfield(L, LUA_REGISTRYINDEX, f); return 1; } static int io_input (lua_State *L) { return g_iofile(L, IO_INPUT, "r"); } static int io_output (lua_State *L) { return g_iofile(L, IO_OUTPUT, "w"); } static int io_readline (lua_State *L); /* ** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit ** in the limit for upvalues of a closure) */ #define MAXARGLINE 250 static void aux_lines (lua_State *L, int toclose) { int n = lua_gettop(L) - 1; /* number of arguments to read */ luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, "too many arguments"); lua_pushinteger(L, n); /* number of arguments to read */ lua_pushboolean(L, toclose); /* close/not close file when finished */ lua_rotate(L, 2, 2); /* move 'n' and 'toclose' to their positions */ lua_pushcclosure(L, io_readline, 3 + n); } static int f_lines (lua_State *L) { tofile(L); /* check that it's a valid file handle */ aux_lines(L, 0); return 1; } static int io_lines (lua_State *L) { int toclose; if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */ if (lua_isnil(L, 1)) { /* no file name? */ lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */ lua_replace(L, 1); /* put it at index 1 */ tofile(L); /* check that it's a valid file handle */ toclose = 0; /* do not close it after iteration */ } else { /* open a new file */ const char *filename = luaL_checkstring(L, 1); opencheck(L, filename, "r"); lua_replace(L, 1); /* put file at index 1 */ toclose = 1; /* close it after iteration */ } aux_lines(L, toclose); return 1; } /* ** {====================================================== ** READ ** ======================================================= */ /* maximum length of a numeral */ #if !defined (L_MAXLENNUM) #define L_MAXLENNUM 200 #endif /* auxiliary structure used by 'read_number' */ typedef struct { FILE *f; /* file being read */ int c; /* current character (look ahead) */ int n; /* number of elements in buffer 'buff' */ char buff[L_MAXLENNUM + 1]; /* +1 for ending '\0' */ } RN; /* ** Add current char to buffer (if not out of space) and read next one */ static int nextc (RN *rn) { if (rn->n >= L_MAXLENNUM) { /* buffer overflow? */ rn->buff[0] = '\0'; /* invalidate result */ return 0; /* fail */ } else { rn->buff[rn->n++] = rn->c; /* save current char */ rn->c = l_getc(rn->f); /* read next one */ return 1; } } /* ** Accept current char if it is in 'set' (of size 2) */ static int test2 (RN *rn, const char *set) { if (rn->c == set[0] || rn->c == set[1]) return nextc(rn); else return 0; } /* ** Read a sequence of (hex)digits */ static int readdigits (RN *rn, int hex) { int count = 0; while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn)) count++; return count; } /* ** Read a number: first reads a valid prefix of a numeral into a buffer. ** Then it calls 'lua_stringtonumber' to check whether the format is ** correct and to convert it to a Lua number */ static int read_number (lua_State *L, FILE *f) { RN rn; int count = 0; int hex = 0; char decp[2]; rn.f = f; rn.n = 0; decp[0] = lua_getlocaledecpoint(); /* get decimal point from locale */ decp[1] = '.'; /* always accept a dot */ l_lockfile(rn.f); do { rn.c = l_getc(rn.f); } while (isspace(rn.c)); /* skip spaces */ test2(&rn, "-+"); /* optional signal */ if (test2(&rn, "00")) { if (test2(&rn, "xX")) hex = 1; /* numeral is hexadecimal */ else count = 1; /* count initial '0' as a valid digit */ } count += readdigits(&rn, hex); /* integral part */ if (test2(&rn, decp)) /* decimal point? */ count += readdigits(&rn, hex); /* fractional part */ if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) { /* exponent mark? */ test2(&rn, "-+"); /* exponent signal */ readdigits(&rn, 0); /* exponent digits */ } ungetc(rn.c, rn.f); /* unread look-ahead char */ l_unlockfile(rn.f); rn.buff[rn.n] = '\0'; /* finish string */ if (lua_stringtonumber(L, rn.buff)) /* is this a valid number? */ return 1; /* ok */ else { /* invalid format */ lua_pushnil(L); /* "result" to be removed */ return 0; /* read fails */ } } static int test_eof (lua_State *L, FILE *f) { int c = getc(f); ungetc(c, f); /* no-op when c == EOF */ lua_pushliteral(L, ""); return (c != EOF); } static int read_line (lua_State *L, FILE *f, int chop) { luaL_Buffer b; int c = '\0'; luaL_buffinit(L, &b); while (c != EOF && c != '\n') { /* repeat until end of line */ char *buff = luaL_prepbuffer(&b); /* preallocate buffer */ int i = 0; l_lockfile(f); /* no memory errors can happen inside the lock */ while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n') buff[i++] = c; l_unlockfile(f); luaL_addsize(&b, i); } if (!chop && c == '\n') /* want a newline and have one? */ luaL_addchar(&b, c); /* add ending newline to result */ luaL_pushresult(&b); /* close buffer */ /* return ok if read something (either a newline or something else) */ return (c == '\n' || lua_rawlen(L, -1) > 0); } static void read_all (lua_State *L, FILE *f) { size_t nr; luaL_Buffer b; luaL_buffinit(L, &b); do { /* read file in chunks of LUAL_BUFFERSIZE bytes */ char *p = luaL_prepbuffer(&b); nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f); luaL_addsize(&b, nr); } while (nr == LUAL_BUFFERSIZE); luaL_pushresult(&b); /* close buffer */ } static int read_chars (lua_State *L, FILE *f, size_t n) { size_t nr; /* number of chars actually read */ char *p; luaL_Buffer b; luaL_buffinit(L, &b); p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */ nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */ luaL_addsize(&b, nr); luaL_pushresult(&b); /* close buffer */ return (nr > 0); /* true iff read something */ } static int g_read (lua_State *L, FILE *f, int first) { int nargs = lua_gettop(L) - 1; int success; int n; clearerr(f); if (nargs == 0) { /* no arguments? */ success = read_line(L, f, 1); n = first+1; /* to return 1 result */ } else { /* ensure stack space for all results and for auxlib's buffer */ luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments"); success = 1; for (n = first; nargs-- && success; n++) { if (lua_type(L, n) == LUA_TNUMBER) { size_t l = (size_t)luaL_checkinteger(L, n); success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l); } else { const char *p = luaL_checkstring(L, n); if (*p == '*') p++; /* skip optional '*' (for compatibility) */ switch (*p) { case 'n': /* number */ success = read_number(L, f); break; case 'l': /* line */ success = read_line(L, f, 1); break; case 'L': /* line with end-of-line */ success = read_line(L, f, 0); break; case 'a': /* file */ read_all(L, f); /* read entire file */ success = 1; /* always success */ break; default: return luaL_argerror(L, n, "invalid format"); } } } } if (ferror(f)) return luaL_fileresult(L, 0, NULL); if (!success) { lua_pop(L, 1); /* remove last result */ lua_pushnil(L); /* push nil instead */ } return n - first; } static int io_read (lua_State *L) { return g_read(L, getiofile(L, IO_INPUT), 1); } static int f_read (lua_State *L) { return g_read(L, tofile(L), 2); } static int io_readline (lua_State *L) { LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1)); int i; int n = (int)lua_tointeger(L, lua_upvalueindex(2)); if (isclosed(p)) /* file is already closed? */ return luaL_error(L, "file is already closed"); lua_settop(L , 1); luaL_checkstack(L, n, "too many arguments"); for (i = 1; i <= n; i++) /* push arguments to 'g_read' */ lua_pushvalue(L, lua_upvalueindex(3 + i)); n = g_read(L, p->f, 2); /* 'n' is number of results */ lua_assert(n > 0); /* should return at least a nil */ if (lua_toboolean(L, -n)) /* read at least one value? */ return n; /* return them */ else { /* first result is nil: EOF or error */ if (n > 1) { /* is there error information? */ /* 2nd result is error message */ return luaL_error(L, "%s", lua_tostring(L, -n + 1)); } if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */ lua_settop(L, 0); lua_pushvalue(L, lua_upvalueindex(1)); aux_close(L); /* close it */ } return 0; } } /* }====================================================== */ static int g_write (lua_State *L, FILE *f, int arg) { int nargs = lua_gettop(L) - arg; int status = 1; for (; nargs--; arg++) { if (lua_type(L, arg) == LUA_TNUMBER) { /* optimization: could be done exactly as for strings */ int len = lua_isinteger(L, arg) ? fprintf(f, LUA_INTEGER_FMT, (LUAI_UACINT)lua_tointeger(L, arg)) : fprintf(f, LUA_NUMBER_FMT, (LUAI_UACNUMBER)lua_tonumber(L, arg)); status = status && (len > 0); } else { size_t l; const char *s = luaL_checklstring(L, arg, &l); status = status && (fwrite(s, sizeof(char), l, f) == l); } } if (status) return 1; /* file handle already on stack top */ else return luaL_fileresult(L, status, NULL); } static int io_write (lua_State *L) { return g_write(L, getiofile(L, IO_OUTPUT), 1); } static int f_write (lua_State *L) { FILE *f = tofile(L); lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */ return g_write(L, f, 2); } static int f_seek (lua_State *L) { static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END}; static const char *const modenames[] = {"set", "cur", "end", NULL}; FILE *f = tofile(L); int op = luaL_checkoption(L, 2, "cur", modenames); lua_Integer p3 = luaL_optinteger(L, 3, 0); l_seeknum offset = (l_seeknum)p3; luaL_argcheck(L, (lua_Integer)offset == p3, 3, "not an integer in proper range"); op = l_fseek(f, offset, mode[op]); if (op) return luaL_fileresult(L, 0, NULL); /* error */ else { lua_pushinteger(L, (lua_Integer)l_ftell(f)); return 1; } } static int f_setvbuf (lua_State *L) { static const int mode[] = {_IONBF, _IOFBF, _IOLBF}; static const char *const modenames[] = {"no", "full", "line", NULL}; FILE *f = tofile(L); int op = luaL_checkoption(L, 2, NULL, modenames); lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE); int res = setvbuf(f, NULL, mode[op], (size_t)sz); return luaL_fileresult(L, res == 0, NULL); } static int io_flush (lua_State *L) { return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL); } static int f_flush (lua_State *L) { return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL); } /* ** functions for 'io' library */ static const luaL_Reg iolib[] = { {"close", io_close}, {"flush", io_flush}, {"input", io_input}, {"lines", io_lines}, {"open", io_open}, {"output", io_output}, {"popen", io_popen}, {"read", io_read}, {"tmpfile", io_tmpfile}, {"type", io_type}, {"write", io_write}, {NULL, NULL} }; /* ** methods for file handles */ static const luaL_Reg flib[] = { {"close", io_close}, {"flush", f_flush}, {"lines", f_lines}, {"read", f_read}, {"seek", f_seek}, {"setvbuf", f_setvbuf}, {"write", f_write}, {"__gc", f_gc}, {"__tostring", f_tostring}, {NULL, NULL} }; static void createmeta (lua_State *L) { luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */ lua_pushvalue(L, -1); /* push metatable */ lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */ luaL_setfuncs(L, flib, 0); /* add file methods to new metatable */ lua_pop(L, 1); /* pop new metatable */ } /* ** function to (not) close the standard files stdin, stdout, and stderr */ static int io_noclose (lua_State *L) { LStream *p = tolstream(L); p->closef = &io_noclose; /* keep file opened */ lua_pushnil(L); lua_pushliteral(L, "cannot close standard file"); return 2; } static void createstdfile (lua_State *L, FILE *f, const char *k, const char *fname) { LStream *p = newprefile(L); p->f = f; p->closef = &io_noclose; if (k != NULL) { lua_pushvalue(L, -1); lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */ } lua_setfield(L, -2, fname); /* add file to module */ } LUAMOD_API int luaopen_io (lua_State *L) { luaL_newlib(L, iolib); /* new module */ createmeta(L); /* create (and set) default files */ createstdfile(L, stdin, IO_INPUT, "stdin"); createstdfile(L, stdout, IO_OUTPUT, "stdout"); createstdfile(L, stderr, NULL, "stderr"); return 1; }
xLua/build/lua-5.3.4/src/liolib.c/0
{ "file_path": "xLua/build/lua-5.3.4/src/liolib.c", "repo_id": "xLua", "token_count": 8645 }
2,088
/* ** $Id: lstate.c,v 2.133 2015/11/13 12:16:51 roberto Exp $ ** Global State ** See Copyright Notice in lua.h */ #define lstate_c #define LUA_CORE #include "lprefix.h" #include <stddef.h> #include <string.h> #include "lua.h" #include "lapi.h" #include "ldebug.h" #include "ldo.h" #include "lfunc.h" #include "lgc.h" #include "llex.h" #include "lmem.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "ltm.h" #if !defined(LUAI_GCPAUSE) #define LUAI_GCPAUSE 200 /* 200% */ #endif #if !defined(LUAI_GCMUL) #define LUAI_GCMUL 200 /* GC runs 'twice the speed' of memory allocation */ #endif /* ** a macro to help the creation of a unique random seed when a state is ** created; the seed is used to randomize hashes. */ #if !defined(luai_makeseed) #include <time.h> #define luai_makeseed() cast(unsigned int, time(NULL)) #endif /* ** thread state + extra space */ typedef struct LX { lu_byte extra_[LUA_EXTRASPACE]; lua_State l; } LX; /* ** Main thread combines a thread state and the global state */ typedef struct LG { LX l; global_State g; } LG; #define fromstate(L) (cast(LX *, cast(lu_byte *, (L)) - offsetof(LX, l))) /* ** Compute an initial seed as random as possible. Rely on Address Space ** Layout Randomization (if present) to increase randomness.. */ #define addbuff(b,p,e) \ { size_t t = cast(size_t, e); \ memcpy(b + p, &t, sizeof(t)); p += sizeof(t); } static unsigned int makeseed (lua_State *L) { char buff[4 * sizeof(size_t)]; unsigned int h = luai_makeseed(); int p = 0; addbuff(buff, p, L); /* heap variable */ addbuff(buff, p, &h); /* local variable */ addbuff(buff, p, luaO_nilobject); /* global variable */ addbuff(buff, p, &lua_newstate); /* public function */ lua_assert(p == sizeof(buff)); return luaS_hash(buff, p, h); } /* ** set GCdebt to a new value keeping the value (totalbytes + GCdebt) ** invariant (and avoiding underflows in 'totalbytes') */ void luaE_setdebt (global_State *g, l_mem debt) { l_mem tb = gettotalbytes(g); lua_assert(tb > 0); if (debt < tb - MAX_LMEM) debt = tb - MAX_LMEM; /* will make 'totalbytes == MAX_LMEM' */ g->totalbytes = tb - debt; g->GCdebt = debt; } CallInfo *luaE_extendCI (lua_State *L) { CallInfo *ci = luaM_new(L, CallInfo); lua_assert(L->ci->next == NULL); L->ci->next = ci; ci->previous = L->ci; ci->next = NULL; L->nci++; return ci; } /* ** free all CallInfo structures not in use by a thread */ void luaE_freeCI (lua_State *L) { CallInfo *ci = L->ci; CallInfo *next = ci->next; ci->next = NULL; while ((ci = next) != NULL) { next = ci->next; luaM_free(L, ci); L->nci--; } } /* ** free half of the CallInfo structures not in use by a thread */ void luaE_shrinkCI (lua_State *L) { CallInfo *ci = L->ci; CallInfo *next2; /* next's next */ /* while there are two nexts */ while (ci->next != NULL && (next2 = ci->next->next) != NULL) { luaM_free(L, ci->next); /* free next */ L->nci--; ci->next = next2; /* remove 'next' from the list */ next2->previous = ci; ci = next2; /* keep next's next */ } } static void stack_init (lua_State *L1, lua_State *L) { int i; CallInfo *ci; /* initialize stack array */ L1->stack = luaM_newvector(L, BASIC_STACK_SIZE, TValue); L1->stacksize = BASIC_STACK_SIZE; for (i = 0; i < BASIC_STACK_SIZE; i++) setnilvalue(L1->stack + i); /* erase new stack */ L1->top = L1->stack; L1->stack_last = L1->stack + L1->stacksize - EXTRA_STACK; /* initialize first ci */ ci = &L1->base_ci; ci->next = ci->previous = NULL; ci->callstatus = 0; ci->func = L1->top; setnilvalue(L1->top++); /* 'function' entry for this 'ci' */ ci->top = L1->top + LUA_MINSTACK; L1->ci = ci; } static void freestack (lua_State *L) { if (L->stack == NULL) return; /* stack not completely built yet */ L->ci = &L->base_ci; /* free the entire 'ci' list */ luaE_freeCI(L); lua_assert(L->nci == 0); luaM_freearray(L, L->stack, L->stacksize); /* free stack array */ } /* ** Create registry table and its predefined values */ static void init_registry (lua_State *L, global_State *g) { TValue temp; /* create registry */ Table *registry = luaH_new(L); sethvalue(L, &g->l_registry, registry); luaH_resize(L, registry, LUA_RIDX_LAST, 0); /* registry[LUA_RIDX_MAINTHREAD] = L */ setthvalue(L, &temp, L); /* temp = L */ luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &temp); /* registry[LUA_RIDX_GLOBALS] = table of globals */ sethvalue(L, &temp, luaH_new(L)); /* temp = new table (global table) */ luaH_setint(L, registry, LUA_RIDX_GLOBALS, &temp); } /* ** open parts of the state that may cause memory-allocation errors. ** ('g->version' != NULL flags that the state was completely build) */ static void f_luaopen (lua_State *L, void *ud) { global_State *g = G(L); UNUSED(ud); stack_init(L, L); /* init stack */ init_registry(L, g); luaS_init(L); luaT_init(L); luaX_init(L); g->gcrunning = 1; /* allow gc */ g->version = lua_version(NULL); luai_userstateopen(L); } /* ** preinitialize a thread with consistent values without allocating ** any memory (to avoid errors) */ static void preinit_thread (lua_State *L, global_State *g) { G(L) = g; L->stack = NULL; L->ci = NULL; L->nci = 0; L->stacksize = 0; L->twups = L; /* thread has no upvalues */ L->errorJmp = NULL; L->nCcalls = 0; L->hook = NULL; L->hookmask = 0; L->basehookcount = 0; L->allowhook = 1; resethookcount(L); L->openupval = NULL; L->nny = 1; L->status = LUA_OK; L->errfunc = 0; } static void close_state (lua_State *L) { global_State *g = G(L); luaF_close(L, L->stack); /* close all upvalues for this thread */ luaC_freeallobjects(L); /* collect all objects */ if (g->version) /* closing a fully built state? */ luai_userstateclose(L); luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size); freestack(L); lua_assert(gettotalbytes(g) == sizeof(LG)); (*g->frealloc)(g->ud, fromstate(L), sizeof(LG), 0); /* free main block */ } LUA_API lua_State *lua_newthread (lua_State *L) { global_State *g = G(L); lua_State *L1; lua_lock(L); luaC_checkGC(L); /* create new thread */ L1 = &cast(LX *, luaM_newobject(L, LUA_TTHREAD, sizeof(LX)))->l; L1->marked = luaC_white(g); L1->tt = LUA_TTHREAD; /* link it on list 'allgc' */ L1->next = g->allgc; g->allgc = obj2gco(L1); /* anchor it on L stack */ setthvalue(L, L->top, L1); api_incr_top(L); preinit_thread(L1, g); L1->hookmask = L->hookmask; L1->basehookcount = L->basehookcount; L1->hook = L->hook; resethookcount(L1); /* initialize L1 extra space */ memcpy(lua_getextraspace(L1), lua_getextraspace(g->mainthread), LUA_EXTRASPACE); luai_userstatethread(L, L1); stack_init(L1, L); /* init stack */ lua_unlock(L); return L1; } void luaE_freethread (lua_State *L, lua_State *L1) { LX *l = fromstate(L1); luaF_close(L1, L1->stack); /* close all upvalues for this thread */ lua_assert(L1->openupval == NULL); luai_userstatefree(L, L1); freestack(L1); luaM_free(L, l); } LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { int i; lua_State *L; global_State *g; LG *l = cast(LG *, (*f)(ud, NULL, LUA_TTHREAD, sizeof(LG))); if (l == NULL) return NULL; L = &l->l.l; g = &l->g; L->next = NULL; L->tt = LUA_TTHREAD; g->currentwhite = bitmask(WHITE0BIT); L->marked = luaC_white(g); preinit_thread(L, g); g->frealloc = f; g->ud = ud; g->mainthread = L; g->seed = makeseed(L); g->gcrunning = 0; /* no GC while building state */ g->GCestimate = 0; g->strt.size = g->strt.nuse = 0; g->strt.hash = NULL; setnilvalue(&g->l_registry); g->panic = NULL; g->version = NULL; g->gcstate = GCSpause; g->gckind = KGC_NORMAL; g->allgc = g->finobj = g->tobefnz = g->fixedgc = NULL; g->sweepgc = NULL; g->gray = g->grayagain = NULL; g->weak = g->ephemeron = g->allweak = NULL; g->twups = NULL; g->totalbytes = sizeof(LG); g->GCdebt = 0; g->gcfinnum = 0; g->gcpause = LUAI_GCPAUSE; g->gcstepmul = LUAI_GCMUL; for (i=0; i < LUA_NUMTAGS; i++) g->mt[i] = NULL; if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) { /* memory allocation error: free partial state */ close_state(L); L = NULL; } return L; } LUA_API void lua_close (lua_State *L) { L = G(L)->mainthread; /* only the main thread can be closed */ lua_lock(L); close_state(L); }
xLua/build/lua-5.3.4/src/lstate.c/0
{ "file_path": "xLua/build/lua-5.3.4/src/lstate.c", "repo_id": "xLua", "token_count": 3630 }
2,089
/* ** $Id: lundump.c,v 2.44 2015/11/02 16:09:30 roberto Exp $ ** load precompiled Lua chunks ** See Copyright Notice in lua.h */ #define lundump_c #define LUA_CORE #include "lprefix.h" #include <string.h> #include "lua.h" #include "ldebug.h" #include "ldo.h" #include "lfunc.h" #include "lmem.h" #include "lobject.h" #include "lstring.h" #include "lundump.h" #include "lzio.h" #if !defined(luai_verifycode) #define luai_verifycode(L,b,f) /* empty */ #endif typedef struct { lua_State *L; ZIO *Z; const char *name; } LoadState; static l_noret error(LoadState *S, const char *why) { luaO_pushfstring(S->L, "%s: %s precompiled chunk", S->name, why); luaD_throw(S->L, LUA_ERRSYNTAX); } /* ** All high-level loads go through LoadVector; you can change it to ** adapt to the endianness of the input */ #define LoadVector(S,b,n) LoadBlock(S,b,(n)*sizeof((b)[0])) static void LoadBlock (LoadState *S, void *b, size_t size) { if (luaZ_read(S->Z, b, size) != 0) error(S, "truncated"); } #define LoadVar(S,x) LoadVector(S,&x,1) static lu_byte LoadByte (LoadState *S) { lu_byte x; LoadVar(S, x); return x; } static int LoadInt (LoadState *S) { int x; LoadVar(S, x); return x; } static lua_Number LoadNumber (LoadState *S) { lua_Number x; LoadVar(S, x); return x; } static lua_Integer LoadInteger (LoadState *S) { lua_Integer x; LoadVar(S, x); return x; } static TString *LoadString (LoadState *S) { size_t size = LoadByte(S); if (size == 0xFF) LoadVar(S, size); if (size == 0) return NULL; else if (--size <= LUAI_MAXSHORTLEN) { /* short string? */ char buff[LUAI_MAXSHORTLEN]; LoadVector(S, buff, size); return luaS_newlstr(S->L, buff, size); } else { /* long string */ TString *ts = luaS_createlngstrobj(S->L, size); LoadVector(S, getstr(ts), size); /* load directly in final place */ return ts; } } static void LoadCode (LoadState *S, Proto *f) { int n = LoadInt(S); f->code = luaM_newvector(S->L, n, Instruction); f->sizecode = n; LoadVector(S, f->code, n); } static void LoadFunction(LoadState *S, Proto *f, TString *psource); static void LoadConstants (LoadState *S, Proto *f) { int i; int n = LoadInt(S); f->k = luaM_newvector(S->L, n, TValue); f->sizek = n; for (i = 0; i < n; i++) setnilvalue(&f->k[i]); for (i = 0; i < n; i++) { TValue *o = &f->k[i]; int t = LoadByte(S); switch (t) { case LUA_TNIL: setnilvalue(o); break; case LUA_TBOOLEAN: setbvalue(o, LoadByte(S)); break; case LUA_TNUMFLT: setfltvalue(o, LoadNumber(S)); break; case LUA_TNUMINT: setivalue(o, LoadInteger(S)); break; case LUA_TSHRSTR: case LUA_TLNGSTR: setsvalue2n(S->L, o, LoadString(S)); break; default: lua_assert(0); } } } static void LoadProtos (LoadState *S, Proto *f) { int i; int n = LoadInt(S); f->p = luaM_newvector(S->L, n, Proto *); f->sizep = n; for (i = 0; i < n; i++) f->p[i] = NULL; for (i = 0; i < n; i++) { f->p[i] = luaF_newproto(S->L); LoadFunction(S, f->p[i], f->source); } } static void LoadUpvalues (LoadState *S, Proto *f) { int i, n; n = LoadInt(S); f->upvalues = luaM_newvector(S->L, n, Upvaldesc); f->sizeupvalues = n; for (i = 0; i < n; i++) f->upvalues[i].name = NULL; for (i = 0; i < n; i++) { f->upvalues[i].instack = LoadByte(S); f->upvalues[i].idx = LoadByte(S); } } static void LoadDebug (LoadState *S, Proto *f) { int i, n; n = LoadInt(S); f->lineinfo = luaM_newvector(S->L, n, int); f->sizelineinfo = n; LoadVector(S, f->lineinfo, n); n = LoadInt(S); f->locvars = luaM_newvector(S->L, n, LocVar); f->sizelocvars = n; for (i = 0; i < n; i++) f->locvars[i].varname = NULL; for (i = 0; i < n; i++) { f->locvars[i].varname = LoadString(S); f->locvars[i].startpc = LoadInt(S); f->locvars[i].endpc = LoadInt(S); } n = LoadInt(S); for (i = 0; i < n; i++) f->upvalues[i].name = LoadString(S); } static void LoadFunction (LoadState *S, Proto *f, TString *psource) { f->source = LoadString(S); if (f->source == NULL) /* no source in dump? */ f->source = psource; /* reuse parent's source */ f->linedefined = LoadInt(S); f->lastlinedefined = LoadInt(S); f->numparams = LoadByte(S); f->is_vararg = LoadByte(S); f->maxstacksize = LoadByte(S); LoadCode(S, f); LoadConstants(S, f); LoadUpvalues(S, f); LoadProtos(S, f); LoadDebug(S, f); } static void checkliteral (LoadState *S, const char *s, const char *msg) { char buff[sizeof(LUA_SIGNATURE) + sizeof(LUAC_DATA)]; /* larger than both */ size_t len = strlen(s); LoadVector(S, buff, len); if (memcmp(s, buff, len) != 0) error(S, msg); } static void fchecksize (LoadState *S, size_t size, const char *tname) { if (LoadByte(S) != size) error(S, luaO_pushfstring(S->L, "%s size mismatch in", tname)); } #define checksize(S,t) fchecksize(S,sizeof(t),#t) static void checkHeader (LoadState *S) { checkliteral(S, LUA_SIGNATURE + 1, "not a"); /* 1st char already checked */ if (LoadByte(S) != LUAC_VERSION) error(S, "version mismatch in"); if (LoadByte(S) != LUAC_FORMAT) error(S, "format mismatch in"); checkliteral(S, LUAC_DATA, "corrupted"); checksize(S, int); checksize(S, size_t); checksize(S, Instruction); checksize(S, lua_Integer); checksize(S, lua_Number); if (LoadInteger(S) != LUAC_INT) error(S, "endianness mismatch in"); if (LoadNumber(S) != LUAC_NUM) error(S, "float format mismatch in"); } /* ** load precompiled chunk */ LClosure *luaU_undump(lua_State *L, ZIO *Z, const char *name) { LoadState S; LClosure *cl; if (*name == '@' || *name == '=') S.name = name + 1; else if (*name == LUA_SIGNATURE[0]) S.name = "binary string"; else S.name = name; S.L = L; S.Z = Z; checkHeader(&S); cl = luaF_newLclosure(L, LoadByte(&S)); setclLvalue(L, L->top, cl); luaD_inctop(L); cl->p = luaF_newproto(L); LoadFunction(&S, cl->p, NULL); lua_assert(cl->nupvalues == cl->p->sizeupvalues); luai_verifycode(L, buff, cl->p); return cl; }
xLua/build/lua-5.3.4/src/lundump.c/0
{ "file_path": "xLua/build/lua-5.3.4/src/lundump.c", "repo_id": "xLua", "token_count": 2762 }
2,090
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML> <HEAD> <TITLE>Lua 5.3 Reference Manual</TITLE> <LINK REL="stylesheet" TYPE="text/css" HREF="lua.css"> <LINK REL="stylesheet" TYPE="text/css" HREF="manual.css"> <META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1"> </HEAD> <BODY> <H1> <A HREF="http://www.lua.org/"><IMG SRC="logo.gif" ALT="Lua"></A> Lua 5.3 Reference Manual </H1> <P> by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes <P> <SMALL> Copyright &copy; 2015&ndash;2018 Lua.org, PUC-Rio. Freely available under the terms of the <a href="http://www.lua.org/license.html">Lua license</a>. </SMALL> <DIV CLASS="menubar"> <A HREF="contents.html#contents">contents</A> &middot; <A HREF="contents.html#index">index</A> &middot; <A HREF="http://www.lua.org/manual/">other versions</A> </DIV> <!-- ====================================================================== --> <p> <!-- $Id: manual.of,v 1.167.1.2 2018/06/26 15:49:07 roberto Exp $ --> <h1>1 &ndash; <a name="1">Introduction</a></h1> <p> Lua is a powerful, efficient, lightweight, embeddable scripting language. It supports procedural programming, object-oriented programming, functional programming, data-driven programming, and data description. <p> Lua combines simple procedural syntax with powerful data description constructs based on associative arrays and extensible semantics. Lua is dynamically typed, runs by interpreting bytecode with a register-based virtual machine, and has automatic memory management with incremental garbage collection, making it ideal for configuration, scripting, and rapid prototyping. <p> Lua is implemented as a library, written in <em>clean C</em>, the common subset of Standard&nbsp;C and C++. The Lua distribution includes a host program called <code>lua</code>, which uses the Lua library to offer a complete, standalone Lua interpreter, for interactive or batch use. Lua is intended to be used both as a powerful, lightweight, embeddable scripting language for any program that needs one, and as a powerful but lightweight and efficient stand-alone language. <p> As an extension language, Lua has no notion of a "main" program: it works <em>embedded</em> in a host client, called the <em>embedding program</em> or simply the <em>host</em>. (Frequently, this host is the stand-alone <code>lua</code> program.) The host program can invoke functions to execute a piece of Lua code, can write and read Lua variables, and can register C&nbsp;functions to be called by Lua code. Through the use of C&nbsp;functions, Lua can be augmented to cope with a wide range of different domains, thus creating customized programming languages sharing a syntactical framework. <p> Lua is free software, and is provided as usual with no guarantees, as stated in its license. The implementation described in this manual is available at Lua's official web site, <code>www.lua.org</code>. <p> Like any other reference manual, this document is dry in places. For a discussion of the decisions behind the design of Lua, see the technical papers available at Lua's web site. For a detailed introduction to programming in Lua, see Roberto's book, <em>Programming in Lua</em>. <h1>2 &ndash; <a name="2">Basic Concepts</a></h1> <p> This section describes the basic concepts of the language. <h2>2.1 &ndash; <a name="2.1">Values and Types</a></h2> <p> Lua is a <em>dynamically typed language</em>. This means that variables do not have types; only values do. There are no type definitions in the language. All values carry their own type. <p> All values in Lua are <em>first-class values</em>. This means that all values can be stored in variables, passed as arguments to other functions, and returned as results. <p> There are eight basic types in Lua: <em>nil</em>, <em>boolean</em>, <em>number</em>, <em>string</em>, <em>function</em>, <em>userdata</em>, <em>thread</em>, and <em>table</em>. The type <em>nil</em> has one single value, <b>nil</b>, whose main property is to be different from any other value; it usually represents the absence of a useful value. The type <em>boolean</em> has two values, <b>false</b> and <b>true</b>. Both <b>nil</b> and <b>false</b> make a condition false; any other value makes it true. The type <em>number</em> represents both integer numbers and real (floating-point) numbers. The type <em>string</em> represents immutable sequences of bytes. Lua is 8-bit clean: strings can contain any 8-bit value, including embedded zeros ('<code>\0</code>'). Lua is also encoding-agnostic; it makes no assumptions about the contents of a string. <p> The type <em>number</em> uses two internal representations, or two subtypes, one called <em>integer</em> and the other called <em>float</em>. Lua has explicit rules about when each representation is used, but it also converts between them automatically as needed (see <a href="#3.4.3">&sect;3.4.3</a>). Therefore, the programmer may choose to mostly ignore the difference between integers and floats or to assume complete control over the representation of each number. Standard Lua uses 64-bit integers and double-precision (64-bit) floats, but you can also compile Lua so that it uses 32-bit integers and/or single-precision (32-bit) floats. The option with 32 bits for both integers and floats is particularly attractive for small machines and embedded systems. (See macro <code>LUA_32BITS</code> in file <code>luaconf.h</code>.) <p> Lua can call (and manipulate) functions written in Lua and functions written in C (see <a href="#3.4.10">&sect;3.4.10</a>). Both are represented by the type <em>function</em>. <p> The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data to be stored in Lua variables. A userdata value represents a block of raw memory. There are two kinds of userdata: <em>full userdata</em>, which is an object with a block of memory managed by Lua, and <em>light userdata</em>, which is simply a C&nbsp;pointer value. Userdata has no predefined operations in Lua, except assignment and identity test. By using <em>metatables</em>, the programmer can define operations for full userdata values (see <a href="#2.4">&sect;2.4</a>). Userdata values cannot be created or modified in Lua, only through the C&nbsp;API. This guarantees the integrity of data owned by the host program. <p> The type <em>thread</em> represents independent threads of execution and it is used to implement coroutines (see <a href="#2.6">&sect;2.6</a>). Lua threads are not related to operating-system threads. Lua supports coroutines on all systems, even those that do not support threads natively. <p> The type <em>table</em> implements associative arrays, that is, arrays that can have as indices not only numbers, but any Lua value except <b>nil</b> and NaN. (<em>Not a Number</em> is a special value used to represent undefined or unrepresentable numerical results, such as <code>0/0</code>.) Tables can be <em>heterogeneous</em>; that is, they can contain values of all types (except <b>nil</b>). Any key with value <b>nil</b> is not considered part of the table. Conversely, any key that is not part of a table has an associated value <b>nil</b>. <p> Tables are the sole data-structuring mechanism in Lua; they can be used to represent ordinary arrays, lists, symbol tables, sets, records, graphs, trees, etc. To represent records, Lua uses the field name as an index. The language supports this representation by providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>. There are several convenient ways to create tables in Lua (see <a href="#3.4.9">&sect;3.4.9</a>). <p> Like indices, the values of table fields can be of any type. In particular, because functions are first-class values, table fields can contain functions. Thus tables can also carry <em>methods</em> (see <a href="#3.4.11">&sect;3.4.11</a>). <p> The indexing of tables follows the definition of raw equality in the language. The expressions <code>a[i]</code> and <code>a[j]</code> denote the same table element if and only if <code>i</code> and <code>j</code> are raw equal (that is, equal without metamethods). In particular, floats with integral values are equal to their respective integers (e.g., <code>1.0 == 1</code>). To avoid ambiguities, any float with integral value used as a key is converted to its respective integer. For instance, if you write <code>a[2.0] = true</code>, the actual key inserted into the table will be the integer <code>2</code>. (On the other hand, 2 and "<code>2</code>" are different Lua values and therefore denote different table entries.) <p> Tables, functions, threads, and (full) userdata values are <em>objects</em>: variables do not actually <em>contain</em> these values, only <em>references</em> to them. Assignment, parameter passing, and function returns always manipulate references to such values; these operations do not imply any kind of copy. <p> The library function <a href="#pdf-type"><code>type</code></a> returns a string describing the type of a given value (see <a href="#6.1">&sect;6.1</a>). <h2>2.2 &ndash; <a name="2.2">Environments and the Global Environment</a></h2> <p> As will be discussed in <a href="#3.2">&sect;3.2</a> and <a href="#3.3.3">&sect;3.3.3</a>, any reference to a free name (that is, a name not bound to any declaration) <code>var</code> is syntactically translated to <code>_ENV.var</code>. Moreover, every chunk is compiled in the scope of an external local variable named <code>_ENV</code> (see <a href="#3.3.2">&sect;3.3.2</a>), so <code>_ENV</code> itself is never a free name in a chunk. <p> Despite the existence of this external <code>_ENV</code> variable and the translation of free names, <code>_ENV</code> is a completely regular name. In particular, you can define new variables and parameters with that name. Each reference to a free name uses the <code>_ENV</code> that is visible at that point in the program, following the usual visibility rules of Lua (see <a href="#3.5">&sect;3.5</a>). <p> Any table used as the value of <code>_ENV</code> is called an <em>environment</em>. <p> Lua keeps a distinguished environment called the <em>global environment</em>. This value is kept at a special index in the C registry (see <a href="#4.5">&sect;4.5</a>). In Lua, the global variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value. (<a href="#pdf-_G"><code>_G</code></a> is never used internally.) <p> When Lua loads a chunk, the default value for its <code>_ENV</code> upvalue is the global environment (see <a href="#pdf-load"><code>load</code></a>). Therefore, by default, free names in Lua code refer to entries in the global environment (and, therefore, they are also called <em>global variables</em>). Moreover, all standard libraries are loaded in the global environment and some functions there operate on that environment. You can use <a href="#pdf-load"><code>load</code></a> (or <a href="#pdf-loadfile"><code>loadfile</code></a>) to load a chunk with a different environment. (In C, you have to load the chunk and then change the value of its first upvalue.) <h2>2.3 &ndash; <a name="2.3">Error Handling</a></h2> <p> Because Lua is an embedded extension language, all Lua actions start from C&nbsp;code in the host program calling a function from the Lua library. (When you use Lua standalone, the <code>lua</code> application is the host program.) Whenever an error occurs during the compilation or execution of a Lua chunk, control returns to the host, which can take appropriate measures (such as printing an error message). <p> Lua code can explicitly generate an error by calling the <a href="#pdf-error"><code>error</code></a> function. If you need to catch errors in Lua, you can use <a href="#pdf-pcall"><code>pcall</code></a> or <a href="#pdf-xpcall"><code>xpcall</code></a> to call a given function in <em>protected mode</em>. <p> Whenever there is an error, an <em>error object</em> (also called an <em>error message</em>) is propagated with information about the error. Lua itself only generates errors whose error object is a string, but programs may generate errors with any value as the error object. It is up to the Lua program or its host to handle such error objects. <p> When you use <a href="#pdf-xpcall"><code>xpcall</code></a> or <a href="#lua_pcall"><code>lua_pcall</code></a>, you may give a <em>message handler</em> to be called in case of errors. This function is called with the original error object and returns a new error object. It is called before the error unwinds the stack, so that it can gather more information about the error, for instance by inspecting the stack and creating a stack traceback. This message handler is still protected by the protected call; so, an error inside the message handler will call the message handler again. If this loop goes on for too long, Lua breaks it and returns an appropriate message. (The message handler is called only for regular runtime errors. It is not called for memory-allocation errors nor for errors while running finalizers.) <h2>2.4 &ndash; <a name="2.4">Metatables and Metamethods</a></h2> <p> Every value in Lua can have a <em>metatable</em>. This <em>metatable</em> is an ordinary Lua table that defines the behavior of the original value under certain special operations. You can change several aspects of the behavior of operations over a value by setting specific fields in its metatable. For instance, when a non-numeric value is the operand of an addition, Lua checks for a function in the field "<code>__add</code>" of the value's metatable. If it finds one, Lua calls this function to perform the addition. <p> The key for each event in a metatable is a string with the event name prefixed by two underscores; the corresponding values are called <em>metamethods</em>. In the previous example, the key is "<code>__add</code>" and the metamethod is the function that performs the addition. Unless stated otherwise, metamethods should be function values. <p> You can query the metatable of any value using the <a href="#pdf-getmetatable"><code>getmetatable</code></a> function. Lua queries metamethods in metatables using a raw access (see <a href="#pdf-rawget"><code>rawget</code></a>). So, to retrieve the metamethod for event <code>ev</code> in object <code>o</code>, Lua does the equivalent to the following code: <pre> rawget(getmetatable(<em>o</em>) or {}, "__<em>ev</em>") </pre> <p> You can replace the metatable of tables using the <a href="#pdf-setmetatable"><code>setmetatable</code></a> function. You cannot change the metatable of other types from Lua code (except by using the debug library (<a href="#6.10">&sect;6.10</a>)); you should use the C&nbsp;API for that. <p> Tables and full userdata have individual metatables (although multiple tables and userdata can share their metatables). Values of all other types share one single metatable per type; that is, there is one single metatable for all numbers, one for all strings, etc. By default, a value has no metatable, but the string library sets a metatable for the string type (see <a href="#6.4">&sect;6.4</a>). <p> A metatable controls how an object behaves in arithmetic operations, bitwise operations, order comparisons, concatenation, length operation, calls, and indexing. A metatable also can define a function to be called when a userdata or a table is garbage collected (<a href="#2.5">&sect;2.5</a>). <p> For the unary operators (negation, length, and bitwise NOT), the metamethod is computed and called with a dummy second operand, equal to the first one. This extra operand is only to simplify Lua's internals (by making these operators behave like a binary operation) and may be removed in future versions. (For most uses this extra operand is irrelevant.) <p> A detailed list of events controlled by metatables is given next. Each operation is identified by its corresponding key. <ul> <li><b><code>__add</code>: </b> the addition (<code>+</code>) operation. If any operand for an addition is not a number (nor a string coercible to a number), Lua will try to call a metamethod. First, Lua will check the first operand (even if it is valid). If that operand does not define a metamethod for <code>__add</code>, then Lua will check the second operand. If Lua can find a metamethod, it calls the metamethod with the two operands as arguments, and the result of the call (adjusted to one value) is the result of the operation. Otherwise, it raises an error. </li> <li><b><code>__sub</code>: </b> the subtraction (<code>-</code>) operation. Behavior similar to the addition operation. </li> <li><b><code>__mul</code>: </b> the multiplication (<code>*</code>) operation. Behavior similar to the addition operation. </li> <li><b><code>__div</code>: </b> the division (<code>/</code>) operation. Behavior similar to the addition operation. </li> <li><b><code>__mod</code>: </b> the modulo (<code>%</code>) operation. Behavior similar to the addition operation. </li> <li><b><code>__pow</code>: </b> the exponentiation (<code>^</code>) operation. Behavior similar to the addition operation. </li> <li><b><code>__unm</code>: </b> the negation (unary <code>-</code>) operation. Behavior similar to the addition operation. </li> <li><b><code>__idiv</code>: </b> the floor division (<code>//</code>) operation. Behavior similar to the addition operation. </li> <li><b><code>__band</code>: </b> the bitwise AND (<code>&amp;</code>) operation. Behavior similar to the addition operation, except that Lua will try a metamethod if any operand is neither an integer nor a value coercible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>). </li> <li><b><code>__bor</code>: </b> the bitwise OR (<code>|</code>) operation. Behavior similar to the bitwise AND operation. </li> <li><b><code>__bxor</code>: </b> the bitwise exclusive OR (binary <code>~</code>) operation. Behavior similar to the bitwise AND operation. </li> <li><b><code>__bnot</code>: </b> the bitwise NOT (unary <code>~</code>) operation. Behavior similar to the bitwise AND operation. </li> <li><b><code>__shl</code>: </b> the bitwise left shift (<code>&lt;&lt;</code>) operation. Behavior similar to the bitwise AND operation. </li> <li><b><code>__shr</code>: </b> the bitwise right shift (<code>&gt;&gt;</code>) operation. Behavior similar to the bitwise AND operation. </li> <li><b><code>__concat</code>: </b> the concatenation (<code>..</code>) operation. Behavior similar to the addition operation, except that Lua will try a metamethod if any operand is neither a string nor a number (which is always coercible to a string). </li> <li><b><code>__len</code>: </b> the length (<code>#</code>) operation. If the object is not a string, Lua will try its metamethod. If there is a metamethod, Lua calls it with the object as argument, and the result of the call (always adjusted to one value) is the result of the operation. If there is no metamethod but the object is a table, then Lua uses the table length operation (see <a href="#3.4.7">&sect;3.4.7</a>). Otherwise, Lua raises an error. </li> <li><b><code>__eq</code>: </b> the equal (<code>==</code>) operation. Behavior similar to the addition operation, except that Lua will try a metamethod only when the values being compared are either both tables or both full userdata and they are not primitively equal. The result of the call is always converted to a boolean. </li> <li><b><code>__lt</code>: </b> the less than (<code>&lt;</code>) operation. Behavior similar to the addition operation, except that Lua will try a metamethod only when the values being compared are neither both numbers nor both strings. The result of the call is always converted to a boolean. </li> <li><b><code>__le</code>: </b> the less equal (<code>&lt;=</code>) operation. Unlike other operations, the less-equal operation can use two different events. First, Lua looks for the <code>__le</code> metamethod in both operands, like in the less than operation. If it cannot find such a metamethod, then it will try the <code>__lt</code> metamethod, assuming that <code>a &lt;= b</code> is equivalent to <code>not (b &lt; a)</code>. As with the other comparison operators, the result is always a boolean. (This use of the <code>__lt</code> event can be removed in future versions; it is also slower than a real <code>__le</code> metamethod.) </li> <li><b><code>__index</code>: </b> The indexing access operation <code>table[key]</code>. This event happens when <code>table</code> is not a table or when <code>key</code> is not present in <code>table</code>. The metamethod is looked up in <code>table</code>. <p> Despite the name, the metamethod for this event can be either a function or a table. If it is a function, it is called with <code>table</code> and <code>key</code> as arguments, and the result of the call (adjusted to one value) is the result of the operation. If it is a table, the final result is the result of indexing this table with <code>key</code>. (This indexing is regular, not raw, and therefore can trigger another metamethod.) </li> <li><b><code>__newindex</code>: </b> The indexing assignment <code>table[key] = value</code>. Like the index event, this event happens when <code>table</code> is not a table or when <code>key</code> is not present in <code>table</code>. The metamethod is looked up in <code>table</code>. <p> Like with indexing, the metamethod for this event can be either a function or a table. If it is a function, it is called with <code>table</code>, <code>key</code>, and <code>value</code> as arguments. If it is a table, Lua does an indexing assignment to this table with the same key and value. (This assignment is regular, not raw, and therefore can trigger another metamethod.) <p> Whenever there is a <code>__newindex</code> metamethod, Lua does not perform the primitive assignment. (If necessary, the metamethod itself can call <a href="#pdf-rawset"><code>rawset</code></a> to do the assignment.) </li> <li><b><code>__call</code>: </b> The call operation <code>func(args)</code>. This event happens when Lua tries to call a non-function value (that is, <code>func</code> is not a function). The metamethod is looked up in <code>func</code>. If present, the metamethod is called with <code>func</code> as its first argument, followed by the arguments of the original call (<code>args</code>). All results of the call are the result of the operation. (This is the only metamethod that allows multiple results.) </li> </ul> <p> It is a good practice to add all needed metamethods to a table before setting it as a metatable of some object. In particular, the <code>__gc</code> metamethod works only when this order is followed (see <a href="#2.5.1">&sect;2.5.1</a>). <p> Because metatables are regular tables, they can contain arbitrary fields, not only the event names defined above. Some functions in the standard library (e.g., <a href="#pdf-tostring"><code>tostring</code></a>) use other fields in metatables for their own purposes. <h2>2.5 &ndash; <a name="2.5">Garbage Collection</a></h2> <p> Lua performs automatic memory management. This means that you do not have to worry about allocating memory for new objects or freeing it when the objects are no longer needed. Lua manages memory automatically by running a <em>garbage collector</em> to collect all <em>dead objects</em> (that is, objects that are no longer accessible from Lua). All memory used by Lua is subject to automatic management: strings, tables, userdata, functions, threads, internal structures, etc. <p> Lua implements an incremental mark-and-sweep collector. It uses two numbers to control its garbage-collection cycles: the <em>garbage-collector pause</em> and the <em>garbage-collector step multiplier</em>. Both use percentage points as units (e.g., a value of 100 means an internal value of 1). <p> The garbage-collector pause controls how long the collector waits before starting a new cycle. Larger values make the collector less aggressive. Values smaller than 100 mean the collector will not wait to start a new cycle. A value of 200 means that the collector waits for the total memory in use to double before starting a new cycle. <p> The garbage-collector step multiplier controls the relative speed of the collector relative to memory allocation. Larger values make the collector more aggressive but also increase the size of each incremental step. You should not use values smaller than 100, because they make the collector too slow and can result in the collector never finishing a cycle. The default is 200, which means that the collector runs at "twice" the speed of memory allocation. <p> If you set the step multiplier to a very large number (larger than 10% of the maximum number of bytes that the program may use), the collector behaves like a stop-the-world collector. If you then set the pause to 200, the collector behaves as in old Lua versions, doing a complete collection every time Lua doubles its memory usage. <p> You can change these numbers by calling <a href="#lua_gc"><code>lua_gc</code></a> in C or <a href="#pdf-collectgarbage"><code>collectgarbage</code></a> in Lua. You can also use these functions to control the collector directly (e.g., stop and restart it). <h3>2.5.1 &ndash; <a name="2.5.1">Garbage-Collection Metamethods</a></h3> <p> You can set garbage-collector metamethods for tables and, using the C&nbsp;API, for full userdata (see <a href="#2.4">&sect;2.4</a>). These metamethods are also called <em>finalizers</em>. Finalizers allow you to coordinate Lua's garbage collection with external resource management (such as closing files, network or database connections, or freeing your own memory). <p> For an object (table or userdata) to be finalized when collected, you must <em>mark</em> it for finalization. You mark an object for finalization when you set its metatable and the metatable has a field indexed by the string "<code>__gc</code>". Note that if you set a metatable without a <code>__gc</code> field and later create that field in the metatable, the object will not be marked for finalization. <p> When a marked object becomes garbage, it is not collected immediately by the garbage collector. Instead, Lua puts it in a list. After the collection, Lua goes through that list. For each object in the list, it checks the object's <code>__gc</code> metamethod: If it is a function, Lua calls it with the object as its single argument; if the metamethod is not a function, Lua simply ignores it. <p> At the end of each garbage-collection cycle, the finalizers for objects are called in the reverse order that the objects were marked for finalization, among those collected in that cycle; that is, the first finalizer to be called is the one associated with the object marked last in the program. The execution of each finalizer may occur at any point during the execution of the regular code. <p> Because the object being collected must still be used by the finalizer, that object (and other objects accessible only through it) must be <em>resurrected</em> by Lua. Usually, this resurrection is transient, and the object memory is freed in the next garbage-collection cycle. However, if the finalizer stores the object in some global place (e.g., a global variable), then the resurrection is permanent. Moreover, if the finalizer marks a finalizing object for finalization again, its finalizer will be called again in the next cycle where the object is unreachable. In any case, the object memory is freed only in a GC cycle where the object is unreachable and not marked for finalization. <p> When you close a state (see <a href="#lua_close"><code>lua_close</code></a>), Lua calls the finalizers of all objects marked for finalization, following the reverse order that they were marked. If any finalizer marks objects for collection during that phase, these marks have no effect. <h3>2.5.2 &ndash; <a name="2.5.2">Weak Tables</a></h3> <p> A <em>weak table</em> is a table whose elements are <em>weak references</em>. A weak reference is ignored by the garbage collector. In other words, if the only references to an object are weak references, then the garbage collector will collect that object. <p> A weak table can have weak keys, weak values, or both. A table with weak values allows the collection of its values, but prevents the collection of its keys. A table with both weak keys and weak values allows the collection of both keys and values. In any case, if either the key or the value is collected, the whole pair is removed from the table. The weakness of a table is controlled by the <code>__mode</code> field of its metatable. If the <code>__mode</code> field is a string containing the character&nbsp;'<code>k</code>', the keys in the table are weak. If <code>__mode</code> contains '<code>v</code>', the values in the table are weak. <p> A table with weak keys and strong values is also called an <em>ephemeron table</em>. In an ephemeron table, a value is considered reachable only if its key is reachable. In particular, if the only reference to a key comes through its value, the pair is removed. <p> Any change in the weakness of a table may take effect only at the next collect cycle. In particular, if you change the weakness to a stronger mode, Lua may still collect some items from that table before the change takes effect. <p> Only objects that have an explicit construction are removed from weak tables. Values, such as numbers and light C&nbsp;functions, are not subject to garbage collection, and therefore are not removed from weak tables (unless their associated values are collected). Although strings are subject to garbage collection, they do not have an explicit construction, and therefore are not removed from weak tables. <p> Resurrected objects (that is, objects being finalized and objects accessible only through objects being finalized) have a special behavior in weak tables. They are removed from weak values before running their finalizers, but are removed from weak keys only in the next collection after running their finalizers, when such objects are actually freed. This behavior allows the finalizer to access properties associated with the object through weak tables. <p> If a weak table is among the resurrected objects in a collection cycle, it may not be properly cleared until the next cycle. <h2>2.6 &ndash; <a name="2.6">Coroutines</a></h2> <p> Lua supports coroutines, also called <em>collaborative multithreading</em>. A coroutine in Lua represents an independent thread of execution. Unlike threads in multithread systems, however, a coroutine only suspends its execution by explicitly calling a yield function. <p> You create a coroutine by calling <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>. Its sole argument is a function that is the main function of the coroutine. The <code>create</code> function only creates a new coroutine and returns a handle to it (an object of type <em>thread</em>); it does not start the coroutine. <p> You execute a coroutine by calling <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>. When you first call <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>, passing as its first argument a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>, the coroutine starts its execution by calling its main function. Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed as arguments to that function. After the coroutine starts running, it runs until it terminates or <em>yields</em>. <p> A coroutine can terminate its execution in two ways: normally, when its main function returns (explicitly or implicitly, after the last instruction); and abnormally, if there is an unprotected error. In case of normal termination, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>, plus any values returned by the coroutine main function. In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b> plus an error object. <p> A coroutine yields by calling <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>. When a coroutine yields, the corresponding <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns immediately, even if the yield happens inside nested function calls (that is, not in the main function, but in a function directly or indirectly called by the main function). In the case of a yield, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> also returns <b>true</b>, plus any values passed to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a>. The next time you resume the same coroutine, it continues its execution from the point where it yielded, with the call to <a href="#pdf-coroutine.yield"><code>coroutine.yield</code></a> returning any extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>. <p> Like <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>, the <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> function also creates a coroutine, but instead of returning the coroutine itself, it returns a function that, when called, resumes the coroutine. Any arguments passed to this function go as extra arguments to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>. <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> returns all the values returned by <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>, except the first one (the boolean error code). Unlike <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a>, <a href="#pdf-coroutine.wrap"><code>coroutine.wrap</code></a> does not catch errors; any error is propagated to the caller. <p> As an example of how coroutines work, consider the following code: <pre> function foo (a) print("foo", a) return coroutine.yield(2*a) end co = coroutine.create(function (a,b) print("co-body", a, b) local r = foo(a+1) print("co-body", r) local r, s = coroutine.yield(a+b, a-b) print("co-body", r, s) return b, "end" end) print("main", coroutine.resume(co, 1, 10)) print("main", coroutine.resume(co, "r")) print("main", coroutine.resume(co, "x", "y")) print("main", coroutine.resume(co, "x", "y")) </pre><p> When you run it, it produces the following output: <pre> co-body 1 10 foo 2 main true 4 co-body r main true 11 -9 co-body x y main true 10 end main false cannot resume dead coroutine </pre> <p> You can also create and manipulate coroutines through the C API: see functions <a href="#lua_newthread"><code>lua_newthread</code></a>, <a href="#lua_resume"><code>lua_resume</code></a>, and <a href="#lua_yield"><code>lua_yield</code></a>. <h1>3 &ndash; <a name="3">The Language</a></h1> <p> This section describes the lexis, the syntax, and the semantics of Lua. In other words, this section describes which tokens are valid, how they can be combined, and what their combinations mean. <p> Language constructs will be explained using the usual extended BNF notation, in which {<em>a</em>}&nbsp;means&nbsp;0 or more <em>a</em>'s, and [<em>a</em>]&nbsp;means an optional <em>a</em>. Non-terminals are shown like non-terminal, keywords are shown like <b>kword</b>, and other terminal symbols are shown like &lsquo;<b>=</b>&rsquo;. The complete syntax of Lua can be found in <a href="#9">&sect;9</a> at the end of this manual. <h2>3.1 &ndash; <a name="3.1">Lexical Conventions</a></h2> <p> Lua is a free-form language. It ignores spaces (including new lines) and comments between lexical elements (tokens), except as delimiters between names and keywords. <p> <em>Names</em> (also called <em>identifiers</em>) in Lua can be any string of letters, digits, and underscores, not beginning with a digit and not being a reserved word. Identifiers are used to name variables, table fields, and labels. <p> The following <em>keywords</em> are reserved and cannot be used as names: <pre> and break do else elseif end false for function goto if in local nil not or repeat return then true until while </pre> <p> Lua is a case-sensitive language: <code>and</code> is a reserved word, but <code>And</code> and <code>AND</code> are two different, valid names. As a convention, programs should avoid creating names that start with an underscore followed by one or more uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>). <p> The following strings denote other tokens: <pre> + - * / % ^ # &amp; ~ | &lt;&lt; &gt;&gt; // == ~= &lt;= &gt;= &lt; &gt; = ( ) { } [ ] :: ; : , . .. ... </pre> <p> A <em>short literal string</em> can be delimited by matching single or double quotes, and can contain the following C-like escape sequences: '<code>\a</code>' (bell), '<code>\b</code>' (backspace), '<code>\f</code>' (form feed), '<code>\n</code>' (newline), '<code>\r</code>' (carriage return), '<code>\t</code>' (horizontal tab), '<code>\v</code>' (vertical tab), '<code>\\</code>' (backslash), '<code>\"</code>' (quotation mark [double quote]), and '<code>\'</code>' (apostrophe [single quote]). A backslash followed by a line break results in a newline in the string. The escape sequence '<code>\z</code>' skips the following span of white-space characters, including line breaks; it is particularly useful to break and indent a long literal string into multiple lines without adding the newlines and spaces into the string contents. A short literal string cannot contain unescaped line breaks nor escapes not forming a valid escape sequence. <p> We can specify any byte in a short literal string by its numeric value (including embedded zeros). This can be done with the escape sequence <code>\x<em>XX</em></code>, where <em>XX</em> is a sequence of exactly two hexadecimal digits, or with the escape sequence <code>\<em>ddd</em></code>, where <em>ddd</em> is a sequence of up to three decimal digits. (Note that if a decimal escape sequence is to be followed by a digit, it must be expressed using exactly three digits.) <p> The UTF-8 encoding of a Unicode character can be inserted in a literal string with the escape sequence <code>\u{<em>XXX</em>}</code> (note the mandatory enclosing brackets), where <em>XXX</em> is a sequence of one or more hexadecimal digits representing the character code point. <p> Literal strings can also be defined using a long format enclosed by <em>long brackets</em>. We define an <em>opening long bracket of level <em>n</em></em> as an opening square bracket followed by <em>n</em> equal signs followed by another opening square bracket. So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>, an opening long bracket of level&nbsp;1 is written as <code>[=[</code>, and so on. A <em>closing long bracket</em> is defined similarly; for instance, a closing long bracket of level&nbsp;4 is written as <code>]====]</code>. A <em>long literal</em> starts with an opening long bracket of any level and ends at the first closing long bracket of the same level. It can contain any text except a closing bracket of the same level. Literals in this bracketed form can run for several lines, do not interpret any escape sequences, and ignore long brackets of any other level. Any kind of end-of-line sequence (carriage return, newline, carriage return followed by newline, or newline followed by carriage return) is converted to a simple newline. <p> For convenience, when the opening long bracket is immediately followed by a newline, the newline is not included in the string. As an example, in a system using ASCII (in which '<code>a</code>' is coded as&nbsp;97, newline is coded as&nbsp;10, and '<code>1</code>' is coded as&nbsp;49), the five literal strings below denote the same string: <pre> a = 'alo\n123"' a = "alo\n123\"" a = '\97lo\10\04923"' a = [[alo 123"]] a = [==[ alo 123"]==] </pre> <p> Any byte in a literal string not explicitly affected by the previous rules represents itself. However, Lua opens files for parsing in text mode, and the system file functions may have problems with some control characters. So, it is safer to represent non-text data as a quoted literal with explicit escape sequences for the non-text characters. <p> A <em>numeric constant</em> (or <em>numeral</em>) can be written with an optional fractional part and an optional decimal exponent, marked by a letter '<code>e</code>' or '<code>E</code>'. Lua also accepts hexadecimal constants, which start with <code>0x</code> or <code>0X</code>. Hexadecimal constants also accept an optional fractional part plus an optional binary exponent, marked by a letter '<code>p</code>' or '<code>P</code>'. A numeric constant with a radix point or an exponent denotes a float; otherwise, if its value fits in an integer, it denotes an integer. Examples of valid integer constants are <pre> 3 345 0xff 0xBEBADA </pre><p> Examples of valid float constants are <pre> 3.0 3.1416 314.16e-2 0.31416E1 34e1 0x0.1E 0xA23p-4 0X1.921FB54442D18P+1 </pre> <p> A <em>comment</em> starts with a double hyphen (<code>--</code>) anywhere outside a string. If the text immediately after <code>--</code> is not an opening long bracket, the comment is a <em>short comment</em>, which runs until the end of the line. Otherwise, it is a <em>long comment</em>, which runs until the corresponding closing long bracket. Long comments are frequently used to disable code temporarily. <h2>3.2 &ndash; <a name="3.2">Variables</a></h2> <p> Variables are places that store values. There are three kinds of variables in Lua: global variables, local variables, and table fields. <p> A single name can denote a global variable or a local variable (or a function's formal parameter, which is a particular kind of local variable): <pre> var ::= Name </pre><p> Name denotes identifiers, as defined in <a href="#3.1">&sect;3.1</a>. <p> Any variable name is assumed to be global unless explicitly declared as a local (see <a href="#3.3.7">&sect;3.3.7</a>). Local variables are <em>lexically scoped</em>: local variables can be freely accessed by functions defined inside their scope (see <a href="#3.5">&sect;3.5</a>). <p> Before the first assignment to a variable, its value is <b>nil</b>. <p> Square brackets are used to index a table: <pre> var ::= prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; </pre><p> The meaning of accesses to table fields can be changed via metatables (see <a href="#2.4">&sect;2.4</a>). <p> The syntax <code>var.Name</code> is just syntactic sugar for <code>var["Name"]</code>: <pre> var ::= prefixexp &lsquo;<b>.</b>&rsquo; Name </pre> <p> An access to a global variable <code>x</code> is equivalent to <code>_ENV.x</code>. Due to the way that chunks are compiled, <code>_ENV</code> is never a global name (see <a href="#2.2">&sect;2.2</a>). <h2>3.3 &ndash; <a name="3.3">Statements</a></h2> <p> Lua supports an almost conventional set of statements, similar to those in Pascal or C. This set includes assignments, control structures, function calls, and variable declarations. <h3>3.3.1 &ndash; <a name="3.3.1">Blocks</a></h3> <p> A block is a list of statements, which are executed sequentially: <pre> block ::= {stat} </pre><p> Lua has <em>empty statements</em> that allow you to separate statements with semicolons, start a block with a semicolon or write two semicolons in sequence: <pre> stat ::= &lsquo;<b>;</b>&rsquo; </pre> <p> Function calls and assignments can start with an open parenthesis. This possibility leads to an ambiguity in Lua's grammar. Consider the following fragment: <pre> a = b + c (print or io.write)('done') </pre><p> The grammar could see it in two ways: <pre> a = b + c(print or io.write)('done') a = b + c; (print or io.write)('done') </pre><p> The current parser always sees such constructions in the first way, interpreting the open parenthesis as the start of the arguments to a call. To avoid this ambiguity, it is a good practice to always precede with a semicolon statements that start with a parenthesis: <pre> ;(print or io.write)('done') </pre> <p> A block can be explicitly delimited to produce a single statement: <pre> stat ::= <b>do</b> block <b>end</b> </pre><p> Explicit blocks are useful to control the scope of variable declarations. Explicit blocks are also sometimes used to add a <b>return</b> statement in the middle of another block (see <a href="#3.3.4">&sect;3.3.4</a>). <h3>3.3.2 &ndash; <a name="3.3.2">Chunks</a></h3> <p> The unit of compilation of Lua is called a <em>chunk</em>. Syntactically, a chunk is simply a block: <pre> chunk ::= block </pre> <p> Lua handles a chunk as the body of an anonymous function with a variable number of arguments (see <a href="#3.4.11">&sect;3.4.11</a>). As such, chunks can define local variables, receive arguments, and return values. Moreover, such anonymous function is compiled as in the scope of an external local variable called <code>_ENV</code> (see <a href="#2.2">&sect;2.2</a>). The resulting function always has <code>_ENV</code> as its only upvalue, even if it does not use that variable. <p> A chunk can be stored in a file or in a string inside the host program. To execute a chunk, Lua first <em>loads</em> it, precompiling the chunk's code into instructions for a virtual machine, and then Lua executes the compiled code with an interpreter for the virtual machine. <p> Chunks can also be precompiled into binary form; see program <code>luac</code> and function <a href="#pdf-string.dump"><code>string.dump</code></a> for details. Programs in source and compiled forms are interchangeable; Lua automatically detects the file type and acts accordingly (see <a href="#pdf-load"><code>load</code></a>). <h3>3.3.3 &ndash; <a name="3.3.3">Assignment</a></h3> <p> Lua allows multiple assignments. Therefore, the syntax for assignment defines a list of variables on the left side and a list of expressions on the right side. The elements in both lists are separated by commas: <pre> stat ::= varlist &lsquo;<b>=</b>&rsquo; explist varlist ::= var {&lsquo;<b>,</b>&rsquo; var} explist ::= exp {&lsquo;<b>,</b>&rsquo; exp} </pre><p> Expressions are discussed in <a href="#3.4">&sect;3.4</a>. <p> Before the assignment, the list of values is <em>adjusted</em> to the length of the list of variables. If there are more values than needed, the excess values are thrown away. If there are fewer values than needed, the list is extended with as many <b>nil</b>'s as needed. If the list of expressions ends with a function call, then all values returned by that call enter the list of values, before the adjustment (except when the call is enclosed in parentheses; see <a href="#3.4">&sect;3.4</a>). <p> The assignment statement first evaluates all its expressions and only then the assignments are performed. Thus the code <pre> i = 3 i, a[i] = i+1, 20 </pre><p> sets <code>a[3]</code> to 20, without affecting <code>a[4]</code> because the <code>i</code> in <code>a[i]</code> is evaluated (to 3) before it is assigned&nbsp;4. Similarly, the line <pre> x, y = y, x </pre><p> exchanges the values of <code>x</code> and <code>y</code>, and <pre> x, y, z = y, z, x </pre><p> cyclically permutes the values of <code>x</code>, <code>y</code>, and <code>z</code>. <p> An assignment to a global name <code>x = val</code> is equivalent to the assignment <code>_ENV.x = val</code> (see <a href="#2.2">&sect;2.2</a>). <p> The meaning of assignments to table fields and global variables (which are actually table fields, too) can be changed via metatables (see <a href="#2.4">&sect;2.4</a>). <h3>3.3.4 &ndash; <a name="3.3.4">Control Structures</a></h3><p> The control structures <b>if</b>, <b>while</b>, and <b>repeat</b> have the usual meaning and familiar syntax: <pre> stat ::= <b>while</b> exp <b>do</b> block <b>end</b> stat ::= <b>repeat</b> block <b>until</b> exp stat ::= <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> </pre><p> Lua also has a <b>for</b> statement, in two flavors (see <a href="#3.3.5">&sect;3.3.5</a>). <p> The condition expression of a control structure can return any value. Both <b>false</b> and <b>nil</b> are considered false. All values different from <b>nil</b> and <b>false</b> are considered true (in particular, the number 0 and the empty string are also true). <p> In the <b>repeat</b>&ndash;<b>until</b> loop, the inner block does not end at the <b>until</b> keyword, but only after the condition. So, the condition can refer to local variables declared inside the loop block. <p> The <b>goto</b> statement transfers the program control to a label. For syntactical reasons, labels in Lua are considered statements too: <pre> stat ::= <b>goto</b> Name stat ::= label label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo; </pre> <p> A label is visible in the entire block where it is defined, except inside nested blocks where a label with the same name is defined and inside nested functions. A goto may jump to any visible label as long as it does not enter into the scope of a local variable. <p> Labels and empty statements are called <em>void statements</em>, as they perform no actions. <p> The <b>break</b> statement terminates the execution of a <b>while</b>, <b>repeat</b>, or <b>for</b> loop, skipping to the next statement after the loop: <pre> stat ::= <b>break</b> </pre><p> A <b>break</b> ends the innermost enclosing loop. <p> The <b>return</b> statement is used to return values from a function or a chunk (which is an anonymous function). Functions can return more than one value, so the syntax for the <b>return</b> statement is <pre> stat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;] </pre> <p> The <b>return</b> statement can only be written as the last statement of a block. If it is really necessary to <b>return</b> in the middle of a block, then an explicit inner block can be used, as in the idiom <code>do return end</code>, because now <b>return</b> is the last statement in its (inner) block. <h3>3.3.5 &ndash; <a name="3.3.5">For Statement</a></h3> <p> The <b>for</b> statement has two forms: one numerical and one generic. <p> The numerical <b>for</b> loop repeats a block of code while a control variable runs through an arithmetic progression. It has the following syntax: <pre> stat ::= <b>for</b> Name &lsquo;<b>=</b>&rsquo; exp &lsquo;<b>,</b>&rsquo; exp [&lsquo;<b>,</b>&rsquo; exp] <b>do</b> block <b>end</b> </pre><p> The <em>block</em> is repeated for <em>name</em> starting at the value of the first <em>exp</em>, until it passes the second <em>exp</em> by steps of the third <em>exp</em>. More precisely, a <b>for</b> statement like <pre> for v = <em>e1</em>, <em>e2</em>, <em>e3</em> do <em>block</em> end </pre><p> is equivalent to the code: <pre> do local <em>var</em>, <em>limit</em>, <em>step</em> = tonumber(<em>e1</em>), tonumber(<em>e2</em>), tonumber(<em>e3</em>) if not (<em>var</em> and <em>limit</em> and <em>step</em>) then error() end <em>var</em> = <em>var</em> - <em>step</em> while true do <em>var</em> = <em>var</em> + <em>step</em> if (<em>step</em> &gt;= 0 and <em>var</em> &gt; <em>limit</em>) or (<em>step</em> &lt; 0 and <em>var</em> &lt; <em>limit</em>) then break end local v = <em>var</em> <em>block</em> end end </pre> <p> Note the following: <ul> <li> All three control expressions are evaluated only once, before the loop starts. They must all result in numbers. </li> <li> <code><em>var</em></code>, <code><em>limit</em></code>, and <code><em>step</em></code> are invisible variables. The names shown here are for explanatory purposes only. </li> <li> If the third expression (the step) is absent, then a step of&nbsp;1 is used. </li> <li> You can use <b>break</b> and <b>goto</b> to exit a <b>for</b> loop. </li> <li> The loop variable <code>v</code> is local to the loop body. If you need its value after the loop, assign it to another variable before exiting the loop. </li> </ul> <p> The generic <b>for</b> statement works over functions, called <em>iterators</em>. On each iteration, the iterator function is called to produce a new value, stopping when this new value is <b>nil</b>. The generic <b>for</b> loop has the following syntax: <pre> stat ::= <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name} </pre><p> A <b>for</b> statement like <pre> for <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> in <em>explist</em> do <em>block</em> end </pre><p> is equivalent to the code: <pre> do local <em>f</em>, <em>s</em>, <em>var</em> = <em>explist</em> while true do local <em>var_1</em>, &middot;&middot;&middot;, <em>var_n</em> = <em>f</em>(<em>s</em>, <em>var</em>) if <em>var_1</em> == nil then break end <em>var</em> = <em>var_1</em> <em>block</em> end end </pre><p> Note the following: <ul> <li> <code><em>explist</em></code> is evaluated only once. Its results are an <em>iterator</em> function, a <em>state</em>, and an initial value for the first <em>iterator variable</em>. </li> <li> <code><em>f</em></code>, <code><em>s</em></code>, and <code><em>var</em></code> are invisible variables. The names are here for explanatory purposes only. </li> <li> You can use <b>break</b> to exit a <b>for</b> loop. </li> <li> The loop variables <code><em>var_i</em></code> are local to the loop; you cannot use their values after the <b>for</b> ends. If you need these values, then assign them to other variables before breaking or exiting the loop. </li> </ul> <h3>3.3.6 &ndash; <a name="3.3.6">Function Calls as Statements</a></h3><p> To allow possible side-effects, function calls can be executed as statements: <pre> stat ::= functioncall </pre><p> In this case, all returned values are thrown away. Function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>. <h3>3.3.7 &ndash; <a name="3.3.7">Local Declarations</a></h3><p> Local variables can be declared anywhere inside a block. The declaration can include an initial assignment: <pre> stat ::= <b>local</b> namelist [&lsquo;<b>=</b>&rsquo; explist] </pre><p> If present, an initial assignment has the same semantics of a multiple assignment (see <a href="#3.3.3">&sect;3.3.3</a>). Otherwise, all variables are initialized with <b>nil</b>. <p> A chunk is also a block (see <a href="#3.3.2">&sect;3.3.2</a>), and so local variables can be declared in a chunk outside any explicit block. <p> The visibility rules for local variables are explained in <a href="#3.5">&sect;3.5</a>. <h2>3.4 &ndash; <a name="3.4">Expressions</a></h2> <p> The basic expressions in Lua are the following: <pre> exp ::= prefixexp exp ::= <b>nil</b> | <b>false</b> | <b>true</b> exp ::= Numeral exp ::= LiteralString exp ::= functiondef exp ::= tableconstructor exp ::= &lsquo;<b>...</b>&rsquo; exp ::= exp binop exp exp ::= unop exp prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo; </pre> <p> Numerals and literal strings are explained in <a href="#3.1">&sect;3.1</a>; variables are explained in <a href="#3.2">&sect;3.2</a>; function definitions are explained in <a href="#3.4.11">&sect;3.4.11</a>; function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>; table constructors are explained in <a href="#3.4.9">&sect;3.4.9</a>. Vararg expressions, denoted by three dots ('<code>...</code>'), can only be used when directly inside a vararg function; they are explained in <a href="#3.4.11">&sect;3.4.11</a>. <p> Binary operators comprise arithmetic operators (see <a href="#3.4.1">&sect;3.4.1</a>), bitwise operators (see <a href="#3.4.2">&sect;3.4.2</a>), relational operators (see <a href="#3.4.4">&sect;3.4.4</a>), logical operators (see <a href="#3.4.5">&sect;3.4.5</a>), and the concatenation operator (see <a href="#3.4.6">&sect;3.4.6</a>). Unary operators comprise the unary minus (see <a href="#3.4.1">&sect;3.4.1</a>), the unary bitwise NOT (see <a href="#3.4.2">&sect;3.4.2</a>), the unary logical <b>not</b> (see <a href="#3.4.5">&sect;3.4.5</a>), and the unary <em>length operator</em> (see <a href="#3.4.7">&sect;3.4.7</a>). <p> Both function calls and vararg expressions can result in multiple values. If a function call is used as a statement (see <a href="#3.3.6">&sect;3.3.6</a>), then its return list is adjusted to zero elements, thus discarding all returned values. If an expression is used as the last (or the only) element of a list of expressions, then no adjustment is made (unless the expression is enclosed in parentheses). In all other contexts, Lua adjusts the result list to one element, either discarding all values except the first one or adding a single <b>nil</b> if there are no values. <p> Here are some examples: <pre> f() -- adjusted to 0 results g(f(), x) -- f() is adjusted to 1 result g(x, f()) -- g gets x plus all results from f() a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil) a,b = ... -- a gets the first vararg argument, b gets -- the second (both a and b can get nil if there -- is no corresponding vararg argument) a,b,c = x, f() -- f() is adjusted to 2 results a,b,c = f() -- f() is adjusted to 3 results return f() -- returns all results from f() return ... -- returns all received vararg arguments return x,y,f() -- returns x, y, and all results from f() {f()} -- creates a list with all results from f() {...} -- creates a list with all vararg arguments {f(), nil} -- f() is adjusted to 1 result </pre> <p> Any expression enclosed in parentheses always results in only one value. Thus, <code>(f(x,y,z))</code> is always a single value, even if <code>f</code> returns several values. (The value of <code>(f(x,y,z))</code> is the first value returned by <code>f</code> or <b>nil</b> if <code>f</code> does not return any values.) <h3>3.4.1 &ndash; <a name="3.4.1">Arithmetic Operators</a></h3><p> Lua supports the following arithmetic operators: <ul> <li><b><code>+</code>: </b>addition</li> <li><b><code>-</code>: </b>subtraction</li> <li><b><code>*</code>: </b>multiplication</li> <li><b><code>/</code>: </b>float division</li> <li><b><code>//</code>: </b>floor division</li> <li><b><code>%</code>: </b>modulo</li> <li><b><code>^</code>: </b>exponentiation</li> <li><b><code>-</code>: </b>unary minus</li> </ul> <p> With the exception of exponentiation and float division, the arithmetic operators work as follows: If both operands are integers, the operation is performed over integers and the result is an integer. Otherwise, if both operands are numbers or strings that can be converted to numbers (see <a href="#3.4.3">&sect;3.4.3</a>), then they are converted to floats, the operation is performed following the usual rules for floating-point arithmetic (usually the IEEE 754 standard), and the result is a float. <p> Exponentiation and float division (<code>/</code>) always convert their operands to floats and the result is always a float. Exponentiation uses the ISO&nbsp;C function <code>pow</code>, so that it works for non-integer exponents too. <p> Floor division (<code>//</code>) is a division that rounds the quotient towards minus infinity, that is, the floor of the division of its operands. <p> Modulo is defined as the remainder of a division that rounds the quotient towards minus infinity (floor division). <p> In case of overflows in integer arithmetic, all operations <em>wrap around</em>, according to the usual rules of two-complement arithmetic. (In other words, they return the unique representable integer that is equal modulo <em>2<sup>64</sup></em> to the mathematical result.) <h3>3.4.2 &ndash; <a name="3.4.2">Bitwise Operators</a></h3><p> Lua supports the following bitwise operators: <ul> <li><b><code>&amp;</code>: </b>bitwise AND</li> <li><b><code>&#124;</code>: </b>bitwise OR</li> <li><b><code>~</code>: </b>bitwise exclusive OR</li> <li><b><code>&gt;&gt;</code>: </b>right shift</li> <li><b><code>&lt;&lt;</code>: </b>left shift</li> <li><b><code>~</code>: </b>unary bitwise NOT</li> </ul> <p> All bitwise operations convert its operands to integers (see <a href="#3.4.3">&sect;3.4.3</a>), operate on all bits of those integers, and result in an integer. <p> Both right and left shifts fill the vacant bits with zeros. Negative displacements shift to the other direction; displacements with absolute values equal to or higher than the number of bits in an integer result in zero (as all bits are shifted out). <h3>3.4.3 &ndash; <a name="3.4.3">Coercions and Conversions</a></h3><p> Lua provides some automatic conversions between some types and representations at run time. Bitwise operators always convert float operands to integers. Exponentiation and float division always convert integer operands to floats. All other arithmetic operations applied to mixed numbers (integers and floats) convert the integer operand to a float; this is called the <em>usual rule</em>. The C API also converts both integers to floats and floats to integers, as needed. Moreover, string concatenation accepts numbers as arguments, besides strings. <p> Lua also converts strings to numbers, whenever a number is expected. <p> In a conversion from integer to float, if the integer value has an exact representation as a float, that is the result. Otherwise, the conversion gets the nearest higher or the nearest lower representable value. This kind of conversion never fails. <p> The conversion from float to integer checks whether the float has an exact representation as an integer (that is, the float has an integral value and it is in the range of integer representation). If it does, that representation is the result. Otherwise, the conversion fails. <p> The conversion from strings to numbers goes as follows: First, the string is converted to an integer or a float, following its syntax and the rules of the Lua lexer. (The string may have also leading and trailing spaces and a sign.) Then, the resulting number (float or integer) is converted to the type (float or integer) required by the context (e.g., the operation that forced the conversion). <p> All conversions from strings to numbers accept both a dot and the current locale mark as the radix character. (The Lua lexer, however, accepts only a dot.) <p> The conversion from numbers to strings uses a non-specified human-readable format. For complete control over how numbers are converted to strings, use the <code>format</code> function from the string library (see <a href="#pdf-string.format"><code>string.format</code></a>). <h3>3.4.4 &ndash; <a name="3.4.4">Relational Operators</a></h3><p> Lua supports the following relational operators: <ul> <li><b><code>==</code>: </b>equality</li> <li><b><code>~=</code>: </b>inequality</li> <li><b><code>&lt;</code>: </b>less than</li> <li><b><code>&gt;</code>: </b>greater than</li> <li><b><code>&lt;=</code>: </b>less or equal</li> <li><b><code>&gt;=</code>: </b>greater or equal</li> </ul><p> These operators always result in <b>false</b> or <b>true</b>. <p> Equality (<code>==</code>) first compares the type of its operands. If the types are different, then the result is <b>false</b>. Otherwise, the values of the operands are compared. Strings are compared in the obvious way. Numbers are equal if they denote the same mathematical value. <p> Tables, userdata, and threads are compared by reference: two objects are considered equal only if they are the same object. Every time you create a new object (a table, userdata, or thread), this new object is different from any previously existing object. A closure is always equal to itself. Closures with any detectable difference (different behavior, different definition) are always different. Closures created at different times but with no detectable differences may be classified as equal or not (depending on internal caching details). <p> You can change the way that Lua compares tables and userdata by using the "eq" metamethod (see <a href="#2.4">&sect;2.4</a>). <p> Equality comparisons do not convert strings to numbers or vice versa. Thus, <code>"0"==0</code> evaluates to <b>false</b>, and <code>t[0]</code> and <code>t["0"]</code> denote different entries in a table. <p> The operator <code>~=</code> is exactly the negation of equality (<code>==</code>). <p> The order operators work as follows. If both arguments are numbers, then they are compared according to their mathematical values (regardless of their subtypes). Otherwise, if both arguments are strings, then their values are compared according to the current locale. Otherwise, Lua tries to call the "lt" or the "le" metamethod (see <a href="#2.4">&sect;2.4</a>). A comparison <code>a &gt; b</code> is translated to <code>b &lt; a</code> and <code>a &gt;= b</code> is translated to <code>b &lt;= a</code>. <p> Following the IEEE 754 standard, NaN is considered neither smaller than, nor equal to, nor greater than any value (including itself). <h3>3.4.5 &ndash; <a name="3.4.5">Logical Operators</a></h3><p> The logical operators in Lua are <b>and</b>, <b>or</b>, and <b>not</b>. Like the control structures (see <a href="#3.3.4">&sect;3.3.4</a>), all logical operators consider both <b>false</b> and <b>nil</b> as false and anything else as true. <p> The negation operator <b>not</b> always returns <b>false</b> or <b>true</b>. The conjunction operator <b>and</b> returns its first argument if this value is <b>false</b> or <b>nil</b>; otherwise, <b>and</b> returns its second argument. The disjunction operator <b>or</b> returns its first argument if this value is different from <b>nil</b> and <b>false</b>; otherwise, <b>or</b> returns its second argument. Both <b>and</b> and <b>or</b> use short-circuit evaluation; that is, the second operand is evaluated only if necessary. Here are some examples: <pre> 10 or 20 --&gt; 10 10 or error() --&gt; 10 nil or "a" --&gt; "a" nil and 10 --&gt; nil false and error() --&gt; false false and nil --&gt; false false or nil --&gt; nil 10 and 20 --&gt; 20 </pre><p> (In this manual, <code>--&gt;</code> indicates the result of the preceding expression.) <h3>3.4.6 &ndash; <a name="3.4.6">Concatenation</a></h3><p> The string concatenation operator in Lua is denoted by two dots ('<code>..</code>'). If both operands are strings or numbers, then they are converted to strings according to the rules described in <a href="#3.4.3">&sect;3.4.3</a>. Otherwise, the <code>__concat</code> metamethod is called (see <a href="#2.4">&sect;2.4</a>). <h3>3.4.7 &ndash; <a name="3.4.7">The Length Operator</a></h3> <p> The length operator is denoted by the unary prefix operator <code>#</code>. <p> The length of a string is its number of bytes (that is, the usual meaning of string length when each character is one byte). <p> The length operator applied on a table returns a border in that table. A <em>border</em> in a table <code>t</code> is any natural number that satisfies the following condition: <pre> (border == 0 or t[border] ~= nil) and t[border + 1] == nil </pre><p> In words, a border is any (natural) index in a table where a non-nil value is followed by a nil value (or zero, when index 1 is nil). <p> A table with exactly one border is called a <em>sequence</em>. For instance, the table <code>{10, 20, 30, 40, 50}</code> is a sequence, as it has only one border (5). The table <code>{10, 20, 30, nil, 50}</code> has two borders (3 and 5), and therefore it is not a sequence. The table <code>{nil, 20, 30, nil, nil, 60, nil}</code> has three borders (0, 3, and 6), so it is not a sequence, too. The table <code>{}</code> is a sequence with border 0. Note that non-natural keys do not interfere with whether a table is a sequence. <p> When <code>t</code> is a sequence, <code>#t</code> returns its only border, which corresponds to the intuitive notion of the length of the sequence. When <code>t</code> is not a sequence, <code>#t</code> can return any of its borders. (The exact one depends on details of the internal representation of the table, which in turn can depend on how the table was populated and the memory addresses of its non-numeric keys.) <p> The computation of the length of a table has a guaranteed worst time of <em>O(log n)</em>, where <em>n</em> is the largest natural key in the table. <p> A program can modify the behavior of the length operator for any value but strings through the <code>__len</code> metamethod (see <a href="#2.4">&sect;2.4</a>). <h3>3.4.8 &ndash; <a name="3.4.8">Precedence</a></h3><p> Operator precedence in Lua follows the table below, from lower to higher priority: <pre> or and &lt; &gt; &lt;= &gt;= ~= == | ~ &amp; &lt;&lt; &gt;&gt; .. + - * / // % unary operators (not # - ~) ^ </pre><p> As usual, you can use parentheses to change the precedences of an expression. The concatenation ('<code>..</code>') and exponentiation ('<code>^</code>') operators are right associative. All other binary operators are left associative. <h3>3.4.9 &ndash; <a name="3.4.9">Table Constructors</a></h3><p> Table constructors are expressions that create tables. Every time a constructor is evaluated, a new table is created. A constructor can be used to create an empty table or to create a table and initialize some of its fields. The general syntax for constructors is <pre> tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo; fieldlist ::= field {fieldsep field} [fieldsep] field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo; </pre> <p> Each field of the form <code>[exp1] = exp2</code> adds to the new table an entry with key <code>exp1</code> and value <code>exp2</code>. A field of the form <code>name = exp</code> is equivalent to <code>["name"] = exp</code>. Finally, fields of the form <code>exp</code> are equivalent to <code>[i] = exp</code>, where <code>i</code> are consecutive integers starting with 1. Fields in the other formats do not affect this counting. For example, <pre> a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 } </pre><p> is equivalent to <pre> do local t = {} t[f(1)] = g t[1] = "x" -- 1st exp t[2] = "y" -- 2nd exp t.x = 1 -- t["x"] = 1 t[3] = f(x) -- 3rd exp t[30] = 23 t[4] = 45 -- 4th exp a = t end </pre> <p> The order of the assignments in a constructor is undefined. (This order would be relevant only when there are repeated keys.) <p> If the last field in the list has the form <code>exp</code> and the expression is a function call or a vararg expression, then all values returned by this expression enter the list consecutively (see <a href="#3.4.10">&sect;3.4.10</a>). <p> The field list can have an optional trailing separator, as a convenience for machine-generated code. <h3>3.4.10 &ndash; <a name="3.4.10">Function Calls</a></h3><p> A function call in Lua has the following syntax: <pre> functioncall ::= prefixexp args </pre><p> In a function call, first prefixexp and args are evaluated. If the value of prefixexp has type <em>function</em>, then this function is called with the given arguments. Otherwise, the prefixexp "call" metamethod is called, having as first argument the value of prefixexp, followed by the original call arguments (see <a href="#2.4">&sect;2.4</a>). <p> The form <pre> functioncall ::= prefixexp &lsquo;<b>:</b>&rsquo; Name args </pre><p> can be used to call "methods". A call <code>v:name(<em>args</em>)</code> is syntactic sugar for <code>v.name(v,<em>args</em>)</code>, except that <code>v</code> is evaluated only once. <p> Arguments have the following syntax: <pre> args ::= &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo; args ::= tableconstructor args ::= LiteralString </pre><p> All argument expressions are evaluated before the call. A call of the form <code>f{<em>fields</em>}</code> is syntactic sugar for <code>f({<em>fields</em>})</code>; that is, the argument list is a single new table. A call of the form <code>f'<em>string</em>'</code> (or <code>f"<em>string</em>"</code> or <code>f[[<em>string</em>]]</code>) is syntactic sugar for <code>f('<em>string</em>')</code>; that is, the argument list is a single literal string. <p> A call of the form <code>return <em>functioncall</em></code> is called a <em>tail call</em>. Lua implements <em>proper tail calls</em> (or <em>proper tail recursion</em>): in a tail call, the called function reuses the stack entry of the calling function. Therefore, there is no limit on the number of nested tail calls that a program can execute. However, a tail call erases any debug information about the calling function. Note that a tail call only happens with a particular syntax, where the <b>return</b> has one single function call as argument; this syntax makes the calling function return exactly the returns of the called function. So, none of the following examples are tail calls: <pre> return (f(x)) -- results adjusted to 1 return 2 * f(x) return x, f(x) -- additional results f(x); return -- results discarded return x or f(x) -- results adjusted to 1 </pre> <h3>3.4.11 &ndash; <a name="3.4.11">Function Definitions</a></h3> <p> The syntax for function definition is <pre> functiondef ::= <b>function</b> funcbody funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b> </pre> <p> The following syntactic sugar simplifies function definitions: <pre> stat ::= <b>function</b> funcname funcbody stat ::= <b>local</b> <b>function</b> Name funcbody funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name] </pre><p> The statement <pre> function f () <em>body</em> end </pre><p> translates to <pre> f = function () <em>body</em> end </pre><p> The statement <pre> function t.a.b.c.f () <em>body</em> end </pre><p> translates to <pre> t.a.b.c.f = function () <em>body</em> end </pre><p> The statement <pre> local function f () <em>body</em> end </pre><p> translates to <pre> local f; f = function () <em>body</em> end </pre><p> not to <pre> local f = function () <em>body</em> end </pre><p> (This only makes a difference when the body of the function contains references to <code>f</code>.) <p> A function definition is an executable expression, whose value has type <em>function</em>. When Lua precompiles a chunk, all its function bodies are precompiled too. Then, whenever Lua executes the function definition, the function is <em>instantiated</em> (or <em>closed</em>). This function instance (or <em>closure</em>) is the final value of the expression. <p> Parameters act as local variables that are initialized with the argument values: <pre> parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo; </pre><p> When a function is called, the list of arguments is adjusted to the length of the list of parameters, unless the function is a <em>vararg function</em>, which is indicated by three dots ('<code>...</code>') at the end of its parameter list. A vararg function does not adjust its argument list; instead, it collects all extra arguments and supplies them to the function through a <em>vararg expression</em>, which is also written as three dots. The value of this expression is a list of all actual extra arguments, similar to a function with multiple results. If a vararg expression is used inside another expression or in the middle of a list of expressions, then its return list is adjusted to one element. If the expression is used as the last element of a list of expressions, then no adjustment is made (unless that last expression is enclosed in parentheses). <p> As an example, consider the following definitions: <pre> function f(a, b) end function g(a, b, ...) end function r() return 1,2,3 end </pre><p> Then, we have the following mapping from arguments to parameters and to the vararg expression: <pre> CALL PARAMETERS f(3) a=3, b=nil f(3, 4) a=3, b=4 f(3, 4, 5) a=3, b=4 f(r(), 10) a=1, b=10 f(r()) a=1, b=2 g(3) a=3, b=nil, ... --&gt; (nothing) g(3, 4) a=3, b=4, ... --&gt; (nothing) g(3, 4, 5, 8) a=3, b=4, ... --&gt; 5 8 g(5, r()) a=5, b=1, ... --&gt; 2 3 </pre> <p> Results are returned using the <b>return</b> statement (see <a href="#3.3.4">&sect;3.3.4</a>). If control reaches the end of a function without encountering a <b>return</b> statement, then the function returns with no results. <p> There is a system-dependent limit on the number of values that a function may return. This limit is guaranteed to be larger than 1000. <p> The <em>colon</em> syntax is used for defining <em>methods</em>, that is, functions that have an implicit extra parameter <code>self</code>. Thus, the statement <pre> function t.a.b.c:f (<em>params</em>) <em>body</em> end </pre><p> is syntactic sugar for <pre> t.a.b.c.f = function (self, <em>params</em>) <em>body</em> end </pre> <h2>3.5 &ndash; <a name="3.5">Visibility Rules</a></h2> <p> Lua is a lexically scoped language. The scope of a local variable begins at the first statement after its declaration and lasts until the last non-void statement of the innermost block that includes the declaration. Consider the following example: <pre> x = 10 -- global variable do -- new block local x = x -- new 'x', with value 10 print(x) --&gt; 10 x = x+1 do -- another block local x = x+1 -- another 'x' print(x) --&gt; 12 end print(x) --&gt; 11 end print(x) --&gt; 10 (the global one) </pre> <p> Notice that, in a declaration like <code>local x = x</code>, the new <code>x</code> being declared is not in scope yet, and so the second <code>x</code> refers to the outside variable. <p> Because of the lexical scoping rules, local variables can be freely accessed by functions defined inside their scope. A local variable used by an inner function is called an <em>upvalue</em>, or <em>external local variable</em>, inside the inner function. <p> Notice that each execution of a <b>local</b> statement defines new local variables. Consider the following example: <pre> a = {} local x = 20 for i=1,10 do local y = 0 a[i] = function () y=y+1; return x+y end end </pre><p> The loop creates ten closures (that is, ten instances of the anonymous function). Each of these closures uses a different <code>y</code> variable, while all of them share the same <code>x</code>. <h1>4 &ndash; <a name="4">The Application Program Interface</a></h1> <p> This section describes the C&nbsp;API for Lua, that is, the set of C&nbsp;functions available to the host program to communicate with Lua. All API functions and related types and constants are declared in the header file <a name="pdf-lua.h"><code>lua.h</code></a>. <p> Even when we use the term "function", any facility in the API may be provided as a macro instead. Except where stated otherwise, all such macros use each of their arguments exactly once (except for the first argument, which is always a Lua state), and so do not generate any hidden side-effects. <p> As in most C&nbsp;libraries, the Lua API functions do not check their arguments for validity or consistency. However, you can change this behavior by compiling Lua with the macro <a name="pdf-LUA_USE_APICHECK"><code>LUA_USE_APICHECK</code></a> defined. <p> The Lua library is fully reentrant: it has no global variables. It keeps all information it needs in a dynamic structure, called the <em>Lua state</em>. <p> Each Lua state has one or more threads, which correspond to independent, cooperative lines of execution. The type <a href="#lua_State"><code>lua_State</code></a> (despite its name) refers to a thread. (Indirectly, through the thread, it also refers to the Lua state associated to the thread.) <p> A pointer to a thread must be passed as the first argument to every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>, which creates a Lua state from scratch and returns a pointer to the <em>main thread</em> in the new state. <h2>4.1 &ndash; <a name="4.1">The Stack</a></h2> <p> Lua uses a <em>virtual stack</em> to pass values to and from C. Each element in this stack represents a Lua value (<b>nil</b>, number, string, etc.). Functions in the API can access this stack through the Lua state parameter that they receive. <p> Whenever Lua calls C, the called function gets a new stack, which is independent of previous stacks and of stacks of C&nbsp;functions that are still active. This stack initially contains any arguments to the C&nbsp;function and it is where the C&nbsp;function can store temporary Lua values and must push its results to be returned to the caller (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>). <p> For convenience, most query operations in the API do not follow a strict stack discipline. Instead, they can refer to any element in the stack by using an <em>index</em>: A positive index represents an absolute stack position (starting at&nbsp;1); a negative index represents an offset relative to the top of the stack. More specifically, if the stack has <em>n</em> elements, then index&nbsp;1 represents the first element (that is, the element that was pushed onto the stack first) and index&nbsp;<em>n</em> represents the last element; index&nbsp;-1 also represents the last element (that is, the element at the&nbsp;top) and index <em>-n</em> represents the first element. <h2>4.2 &ndash; <a name="4.2">Stack Size</a></h2> <p> When you interact with the Lua API, you are responsible for ensuring consistency. In particular, <em>you are responsible for controlling stack overflow</em>. You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a> to ensure that the stack has enough space for pushing new elements. <p> Whenever Lua calls C, it ensures that the stack has space for at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra slots. <code>LUA_MINSTACK</code> is defined as 20, so that usually you do not have to worry about stack space unless your code has loops pushing elements onto the stack. <p> When you call a Lua function without a fixed number of results (see <a href="#lua_call"><code>lua_call</code></a>), Lua ensures that the stack has enough space for all results, but it does not ensure any extra space. So, before pushing anything in the stack after such a call you should use <a href="#lua_checkstack"><code>lua_checkstack</code></a>. <h2>4.3 &ndash; <a name="4.3">Valid and Acceptable Indices</a></h2> <p> Any function in the API that receives stack indices works only with <em>valid indices</em> or <em>acceptable indices</em>. <p> A <em>valid index</em> is an index that refers to a position that stores a modifiable Lua value. It comprises stack indices between&nbsp;1 and the stack top (<code>1 &le; abs(index) &le; top</code>) plus <em>pseudo-indices</em>, which represent some positions that are accessible to C&nbsp;code but that are not in the stack. Pseudo-indices are used to access the registry (see <a href="#4.5">&sect;4.5</a>) and the upvalues of a C&nbsp;function (see <a href="#4.4">&sect;4.4</a>). <p> Functions that do not need a specific mutable position, but only a value (e.g., query functions), can be called with acceptable indices. An <em>acceptable index</em> can be any valid index, but it also can be any positive index after the stack top within the space allocated for the stack, that is, indices up to the stack size. (Note that 0 is never an acceptable index.) Except when noted otherwise, functions in the API work with acceptable indices. <p> Acceptable indices serve to avoid extra tests against the stack top when querying the stack. For instance, a C&nbsp;function can query its third argument without the need to first check whether there is a third argument, that is, without the need to check whether 3 is a valid index. <p> For functions that can be called with acceptable indices, any non-valid index is treated as if it contains a value of a virtual type <a name="pdf-LUA_TNONE"><code>LUA_TNONE</code></a>, which behaves like a nil value. <h2>4.4 &ndash; <a name="4.4">C Closures</a></h2> <p> When a C&nbsp;function is created, it is possible to associate some values with it, thus creating a <em>C&nbsp;closure</em> (see <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>); these values are called <em>upvalues</em> and are accessible to the function whenever it is called. <p> Whenever a C&nbsp;function is called, its upvalues are located at specific pseudo-indices. These pseudo-indices are produced by the macro <a href="#lua_upvalueindex"><code>lua_upvalueindex</code></a>. The first upvalue associated with a function is at index <code>lua_upvalueindex(1)</code>, and so on. Any access to <code>lua_upvalueindex(<em>n</em>)</code>, where <em>n</em> is greater than the number of upvalues of the current function (but not greater than 256, which is one plus the maximum number of upvalues in a closure), produces an acceptable but invalid index. <h2>4.5 &ndash; <a name="4.5">Registry</a></h2> <p> Lua provides a <em>registry</em>, a predefined table that can be used by any C&nbsp;code to store whatever Lua values it needs to store. The registry table is always located at pseudo-index <a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>. Any C&nbsp;library can store data into this table, but it must take care to choose keys that are different from those used by other libraries, to avoid collisions. Typically, you should use as key a string containing your library name, or a light userdata with the address of a C&nbsp;object in your code, or any Lua object created by your code. As with variable names, string keys starting with an underscore followed by uppercase letters are reserved for Lua. <p> The integer keys in the registry are used by the reference mechanism (see <a href="#luaL_ref"><code>luaL_ref</code></a>) and by some predefined values. Therefore, integer keys must not be used for other purposes. <p> When you create a new Lua state, its registry comes with some predefined values. These predefined values are indexed with integer keys defined as constants in <code>lua.h</code>. The following constants are defined: <ul> <li><b><a name="pdf-LUA_RIDX_MAINTHREAD"><code>LUA_RIDX_MAINTHREAD</code></a>: </b> At this index the registry has the main thread of the state. (The main thread is the one created together with the state.) </li> <li><b><a name="pdf-LUA_RIDX_GLOBALS"><code>LUA_RIDX_GLOBALS</code></a>: </b> At this index the registry has the global environment. </li> </ul> <h2>4.6 &ndash; <a name="4.6">Error Handling in C</a></h2> <p> Internally, Lua uses the C <code>longjmp</code> facility to handle errors. (Lua will use exceptions if you compile it as C++; search for <code>LUAI_THROW</code> in the source code for details.) When Lua faces any error (such as a memory allocation error or a type error) it <em>raises</em> an error; that is, it does a long jump. A <em>protected environment</em> uses <code>setjmp</code> to set a recovery point; any error jumps to the most recent active recovery point. <p> Inside a C&nbsp;function you can raise an error by calling <a href="#lua_error"><code>lua_error</code></a>. <p> Most functions in the API can raise an error, for instance due to a memory allocation error. The documentation for each function indicates whether it can raise errors. <p> If an error happens outside any protected environment, Lua calls a <em>panic function</em> (see <a href="#lua_atpanic"><code>lua_atpanic</code></a>) and then calls <code>abort</code>, thus exiting the host application. Your panic function can avoid this exit by never returning (e.g., doing a long jump to your own recovery point outside Lua). <p> The panic function, as its name implies, is a mechanism of last resort. Programs should avoid it. As a general rule, when a C&nbsp;function is called by Lua with a Lua state, it can do whatever it wants on that Lua state, as it should be already protected. However, when C code operates on other Lua states (e.g., a Lua argument to the function, a Lua state stored in the registry, or the result of <a href="#lua_newthread"><code>lua_newthread</code></a>), it should use them only in API calls that cannot raise errors. <p> The panic function runs as if it were a message handler (see <a href="#2.3">&sect;2.3</a>); in particular, the error object is at the top of the stack. However, there is no guarantee about stack space. To push anything on the stack, the panic function must first check the available space (see <a href="#4.2">&sect;4.2</a>). <h2>4.7 &ndash; <a name="4.7">Handling Yields in C</a></h2> <p> Internally, Lua uses the C <code>longjmp</code> facility to yield a coroutine. Therefore, if a C&nbsp;function <code>foo</code> calls an API function and this API function yields (directly or indirectly by calling another function that yields), Lua cannot return to <code>foo</code> any more, because the <code>longjmp</code> removes its frame from the C stack. <p> To avoid this kind of problem, Lua raises an error whenever it tries to yield across an API call, except for three functions: <a href="#lua_yieldk"><code>lua_yieldk</code></a>, <a href="#lua_callk"><code>lua_callk</code></a>, and <a href="#lua_pcallk"><code>lua_pcallk</code></a>. All those functions receive a <em>continuation function</em> (as a parameter named <code>k</code>) to continue execution after a yield. <p> We need to set some terminology to explain continuations. We have a C&nbsp;function called from Lua which we will call the <em>original function</em>. This original function then calls one of those three functions in the C API, which we will call the <em>callee function</em>, that then yields the current thread. (This can happen when the callee function is <a href="#lua_yieldk"><code>lua_yieldk</code></a>, or when the callee function is either <a href="#lua_callk"><code>lua_callk</code></a> or <a href="#lua_pcallk"><code>lua_pcallk</code></a> and the function called by them yields.) <p> Suppose the running thread yields while executing the callee function. After the thread resumes, it eventually will finish running the callee function. However, the callee function cannot return to the original function, because its frame in the C stack was destroyed by the yield. Instead, Lua calls a <em>continuation function</em>, which was given as an argument to the callee function. As the name implies, the continuation function should continue the task of the original function. <p> As an illustration, consider the following function: <pre> int original_function (lua_State *L) { ... /* code 1 */ status = lua_pcall(L, n, m, h); /* calls Lua */ ... /* code 2 */ } </pre><p> Now we want to allow the Lua code being run by <a href="#lua_pcall"><code>lua_pcall</code></a> to yield. First, we can rewrite our function like here: <pre> int k (lua_State *L, int status, lua_KContext ctx) { ... /* code 2 */ } int original_function (lua_State *L) { ... /* code 1 */ return k(L, lua_pcall(L, n, m, h), ctx); } </pre><p> In the above code, the new function <code>k</code> is a <em>continuation function</em> (with type <a href="#lua_KFunction"><code>lua_KFunction</code></a>), which should do all the work that the original function was doing after calling <a href="#lua_pcall"><code>lua_pcall</code></a>. Now, we must inform Lua that it must call <code>k</code> if the Lua code being executed by <a href="#lua_pcall"><code>lua_pcall</code></a> gets interrupted in some way (errors or yielding), so we rewrite the code as here, replacing <a href="#lua_pcall"><code>lua_pcall</code></a> by <a href="#lua_pcallk"><code>lua_pcallk</code></a>: <pre> int original_function (lua_State *L) { ... /* code 1 */ return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1); } </pre><p> Note the external, explicit call to the continuation: Lua will call the continuation only if needed, that is, in case of errors or resuming after a yield. If the called function returns normally without ever yielding, <a href="#lua_pcallk"><code>lua_pcallk</code></a> (and <a href="#lua_callk"><code>lua_callk</code></a>) will also return normally. (Of course, instead of calling the continuation in that case, you can do the equivalent work directly inside the original function.) <p> Besides the Lua state, the continuation function has two other parameters: the final status of the call plus the context value (<code>ctx</code>) that was passed originally to <a href="#lua_pcallk"><code>lua_pcallk</code></a>. (Lua does not use this context value; it only passes this value from the original function to the continuation function.) For <a href="#lua_pcallk"><code>lua_pcallk</code></a>, the status is the same value that would be returned by <a href="#lua_pcallk"><code>lua_pcallk</code></a>, except that it is <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when being executed after a yield (instead of <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>). For <a href="#lua_yieldk"><code>lua_yieldk</code></a> and <a href="#lua_callk"><code>lua_callk</code></a>, the status is always <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when Lua calls the continuation. (For these two functions, Lua will not call the continuation in case of errors, because they do not handle errors.) Similarly, when using <a href="#lua_callk"><code>lua_callk</code></a>, you should call the continuation function with <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> as the status. (For <a href="#lua_yieldk"><code>lua_yieldk</code></a>, there is not much point in calling directly the continuation function, because <a href="#lua_yieldk"><code>lua_yieldk</code></a> usually does not return.) <p> Lua treats the continuation function as if it were the original function. The continuation function receives the same Lua stack from the original function, in the same state it would be if the callee function had returned. (For instance, after a <a href="#lua_callk"><code>lua_callk</code></a> the function and its arguments are removed from the stack and replaced by the results from the call.) It also has the same upvalues. Whatever it returns is handled by Lua as if it were the return of the original function. <h2>4.8 &ndash; <a name="4.8">Functions and Types</a></h2> <p> Here we list all functions and types from the C&nbsp;API in alphabetical order. Each function has an indicator like this: <span class="apii">[-o, +p, <em>x</em>]</span> <p> The first field, <code>o</code>, is how many elements the function pops from the stack. The second field, <code>p</code>, is how many elements the function pushes onto the stack. (Any function always pushes its results after popping its arguments.) A field in the form <code>x|y</code> means the function can push (or pop) <code>x</code> or <code>y</code> elements, depending on the situation; an interrogation mark '<code>?</code>' means that we cannot know how many elements the function pops/pushes by looking only at its arguments (e.g., they may depend on what is on the stack). The third field, <code>x</code>, tells whether the function may raise errors: '<code>-</code>' means the function never raises any error; '<code>m</code>' means the function may raise out-of-memory errors and errors running a <code>__gc</code> metamethod; '<code>e</code>' means the function may raise any errors (it can run arbitrary Lua code, either directly or through metamethods); '<code>v</code>' means the function may raise an error on purpose. <hr><h3><a name="lua_absindex"><code>lua_absindex</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_absindex (lua_State *L, int idx);</pre> <p> Converts the acceptable index <code>idx</code> into an equivalent absolute index (that is, one that does not depend on the stack top). <hr><h3><a name="lua_Alloc"><code>lua_Alloc</code></a></h3> <pre>typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize);</pre> <p> The type of the memory-allocation function used by Lua states. The allocator function must provide a functionality similar to <code>realloc</code>, but not exactly the same. Its arguments are <code>ud</code>, an opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>; <code>ptr</code>, a pointer to the block being allocated/reallocated/freed; <code>osize</code>, the original size of the block or some code about what is being allocated; and <code>nsize</code>, the new size of the block. <p> When <code>ptr</code> is not <code>NULL</code>, <code>osize</code> is the size of the block pointed by <code>ptr</code>, that is, the size given when it was allocated or reallocated. <p> When <code>ptr</code> is <code>NULL</code>, <code>osize</code> encodes the kind of object that Lua is allocating. <code>osize</code> is any of <a href="#pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>, <a href="#pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>, <a href="#pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>, <a href="#pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>, or <a href="#pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a> when (and only when) Lua is creating a new object of that type. When <code>osize</code> is some other value, Lua is allocating memory for something else. <p> Lua assumes the following behavior from the allocator function: <p> When <code>nsize</code> is zero, the allocator must behave like <code>free</code> and return <code>NULL</code>. <p> When <code>nsize</code> is not zero, the allocator must behave like <code>realloc</code>. The allocator returns <code>NULL</code> if and only if it cannot fulfill the request. Lua assumes that the allocator never fails when <code>osize &gt;= nsize</code>. <p> Here is a simple implementation for the allocator function. It is used in the auxiliary library by <a href="#luaL_newstate"><code>luaL_newstate</code></a>. <pre> static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { (void)ud; (void)osize; /* not used */ if (nsize == 0) { free(ptr); return NULL; } else return realloc(ptr, nsize); } </pre><p> Note that Standard&nbsp;C ensures that <code>free(NULL)</code> has no effect and that <code>realloc(NULL,size)</code> is equivalent to <code>malloc(size)</code>. This code assumes that <code>realloc</code> does not fail when shrinking a block. (Although Standard&nbsp;C does not ensure this behavior, it seems to be a safe assumption.) <hr><h3><a name="lua_arith"><code>lua_arith</code></a></h3><p> <span class="apii">[-(2|1), +1, <em>e</em>]</span> <pre>void lua_arith (lua_State *L, int op);</pre> <p> Performs an arithmetic or bitwise operation over the two values (or one, in the case of negations) at the top of the stack, with the value at the top being the second operand, pops these values, and pushes the result of the operation. The function follows the semantics of the corresponding Lua operator (that is, it may call metamethods). <p> The value of <code>op</code> must be one of the following constants: <ul> <li><b><a name="pdf-LUA_OPADD"><code>LUA_OPADD</code></a>: </b> performs addition (<code>+</code>)</li> <li><b><a name="pdf-LUA_OPSUB"><code>LUA_OPSUB</code></a>: </b> performs subtraction (<code>-</code>)</li> <li><b><a name="pdf-LUA_OPMUL"><code>LUA_OPMUL</code></a>: </b> performs multiplication (<code>*</code>)</li> <li><b><a name="pdf-LUA_OPDIV"><code>LUA_OPDIV</code></a>: </b> performs float division (<code>/</code>)</li> <li><b><a name="pdf-LUA_OPIDIV"><code>LUA_OPIDIV</code></a>: </b> performs floor division (<code>//</code>)</li> <li><b><a name="pdf-LUA_OPMOD"><code>LUA_OPMOD</code></a>: </b> performs modulo (<code>%</code>)</li> <li><b><a name="pdf-LUA_OPPOW"><code>LUA_OPPOW</code></a>: </b> performs exponentiation (<code>^</code>)</li> <li><b><a name="pdf-LUA_OPUNM"><code>LUA_OPUNM</code></a>: </b> performs mathematical negation (unary <code>-</code>)</li> <li><b><a name="pdf-LUA_OPBNOT"><code>LUA_OPBNOT</code></a>: </b> performs bitwise NOT (<code>~</code>)</li> <li><b><a name="pdf-LUA_OPBAND"><code>LUA_OPBAND</code></a>: </b> performs bitwise AND (<code>&amp;</code>)</li> <li><b><a name="pdf-LUA_OPBOR"><code>LUA_OPBOR</code></a>: </b> performs bitwise OR (<code>|</code>)</li> <li><b><a name="pdf-LUA_OPBXOR"><code>LUA_OPBXOR</code></a>: </b> performs bitwise exclusive OR (<code>~</code>)</li> <li><b><a name="pdf-LUA_OPSHL"><code>LUA_OPSHL</code></a>: </b> performs left shift (<code>&lt;&lt;</code>)</li> <li><b><a name="pdf-LUA_OPSHR"><code>LUA_OPSHR</code></a>: </b> performs right shift (<code>&gt;&gt;</code>)</li> </ul> <hr><h3><a name="lua_atpanic"><code>lua_atpanic</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);</pre> <p> Sets a new panic function and returns the old one (see <a href="#4.6">&sect;4.6</a>). <hr><h3><a name="lua_call"><code>lua_call</code></a></h3><p> <span class="apii">[-(nargs+1), +nresults, <em>e</em>]</span> <pre>void lua_call (lua_State *L, int nargs, int nresults);</pre> <p> Calls a function. <p> To call a function you must use the following protocol: first, the function to be called is pushed onto the stack; then, the arguments to the function are pushed in direct order; that is, the first argument is pushed first. Finally you call <a href="#lua_call"><code>lua_call</code></a>; <code>nargs</code> is the number of arguments that you pushed onto the stack. All arguments and the function value are popped from the stack when the function is called. The function results are pushed onto the stack when the function returns. The number of results is adjusted to <code>nresults</code>, unless <code>nresults</code> is <a name="pdf-LUA_MULTRET"><code>LUA_MULTRET</code></a>. In this case, all results from the function are pushed; Lua takes care that the returned values fit into the stack space, but it does not ensure any extra space in the stack. The function results are pushed onto the stack in direct order (the first result is pushed first), so that after the call the last result is on the top of the stack. <p> Any error inside the called function is propagated upwards (with a <code>longjmp</code>). <p> The following example shows how the host program can do the equivalent to this Lua code: <pre> a = f("how", t.x, 14) </pre><p> Here it is in&nbsp;C: <pre> lua_getglobal(L, "f"); /* function to be called */ lua_pushliteral(L, "how"); /* 1st argument */ lua_getglobal(L, "t"); /* table to be indexed */ lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */ lua_remove(L, -2); /* remove 't' from the stack */ lua_pushinteger(L, 14); /* 3rd argument */ lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */ lua_setglobal(L, "a"); /* set global 'a' */ </pre><p> Note that the code above is <em>balanced</em>: at its end, the stack is back to its original configuration. This is considered good programming practice. <hr><h3><a name="lua_callk"><code>lua_callk</code></a></h3><p> <span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span> <pre>void lua_callk (lua_State *L, int nargs, int nresults, lua_KContext ctx, lua_KFunction k);</pre> <p> This function behaves exactly like <a href="#lua_call"><code>lua_call</code></a>, but allows the called function to yield (see <a href="#4.7">&sect;4.7</a>). <hr><h3><a name="lua_CFunction"><code>lua_CFunction</code></a></h3> <pre>typedef int (*lua_CFunction) (lua_State *L);</pre> <p> Type for C&nbsp;functions. <p> In order to communicate properly with Lua, a C&nbsp;function must use the following protocol, which defines the way parameters and results are passed: a C&nbsp;function receives its arguments from Lua in its stack in direct order (the first argument is pushed first). So, when the function starts, <code>lua_gettop(L)</code> returns the number of arguments received by the function. The first argument (if any) is at index 1 and its last argument is at index <code>lua_gettop(L)</code>. To return values to Lua, a C&nbsp;function just pushes them onto the stack, in direct order (the first result is pushed first), and returns the number of results. Any other value in the stack below the results will be properly discarded by Lua. Like a Lua function, a C&nbsp;function called by Lua can also return many results. <p> As an example, the following function receives a variable number of numeric arguments and returns their average and their sum: <pre> static int foo (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ lua_Number sum = 0.0; int i; for (i = 1; i &lt;= n; i++) { if (!lua_isnumber(L, i)) { lua_pushliteral(L, "incorrect argument"); lua_error(L); } sum += lua_tonumber(L, i); } lua_pushnumber(L, sum/n); /* first result */ lua_pushnumber(L, sum); /* second result */ return 2; /* number of results */ } </pre> <hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_checkstack (lua_State *L, int n);</pre> <p> Ensures that the stack has space for at least <code>n</code> extra slots (that is, that you can safely push up to <code>n</code> values into it). It returns false if it cannot fulfill the request, either because it would cause the stack to be larger than a fixed maximum size (typically at least several thousand elements) or because it cannot allocate memory for the extra space. This function never shrinks the stack; if the stack already has space for the extra slots, it is left unchanged. <hr><h3><a name="lua_close"><code>lua_close</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>void lua_close (lua_State *L);</pre> <p> Destroys all objects in the given Lua state (calling the corresponding garbage-collection metamethods, if any) and frees all dynamic memory used by this state. In several platforms, you may not need to call this function, because all resources are naturally released when the host program ends. On the other hand, long-running programs that create multiple states, such as daemons or web servers, will probably need to close states as soon as they are not needed. <hr><h3><a name="lua_compare"><code>lua_compare</code></a></h3><p> <span class="apii">[-0, +0, <em>e</em>]</span> <pre>int lua_compare (lua_State *L, int index1, int index2, int op);</pre> <p> Compares two Lua values. Returns 1 if the value at index <code>index1</code> satisfies <code>op</code> when compared with the value at index <code>index2</code>, following the semantics of the corresponding Lua operator (that is, it may call metamethods). Otherwise returns&nbsp;0. Also returns&nbsp;0 if any of the indices is not valid. <p> The value of <code>op</code> must be one of the following constants: <ul> <li><b><a name="pdf-LUA_OPEQ"><code>LUA_OPEQ</code></a>: </b> compares for equality (<code>==</code>)</li> <li><b><a name="pdf-LUA_OPLT"><code>LUA_OPLT</code></a>: </b> compares for less than (<code>&lt;</code>)</li> <li><b><a name="pdf-LUA_OPLE"><code>LUA_OPLE</code></a>: </b> compares for less or equal (<code>&lt;=</code>)</li> </ul> <hr><h3><a name="lua_concat"><code>lua_concat</code></a></h3><p> <span class="apii">[-n, +1, <em>e</em>]</span> <pre>void lua_concat (lua_State *L, int n);</pre> <p> Concatenates the <code>n</code> values at the top of the stack, pops them, and leaves the result at the top. If <code>n</code>&nbsp;is&nbsp;1, the result is the single value on the stack (that is, the function does nothing); if <code>n</code> is 0, the result is the empty string. Concatenation is performed following the usual semantics of Lua (see <a href="#3.4.6">&sect;3.4.6</a>). <hr><h3><a name="lua_copy"><code>lua_copy</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>void lua_copy (lua_State *L, int fromidx, int toidx);</pre> <p> Copies the element at index <code>fromidx</code> into the valid index <code>toidx</code>, replacing the value at that position. Values at other positions are not affected. <hr><h3><a name="lua_createtable"><code>lua_createtable</code></a></h3><p> <span class="apii">[-0, +1, <em>m</em>]</span> <pre>void lua_createtable (lua_State *L, int narr, int nrec);</pre> <p> Creates a new empty table and pushes it onto the stack. Parameter <code>narr</code> is a hint for how many elements the table will have as a sequence; parameter <code>nrec</code> is a hint for how many other elements the table will have. Lua may use these hints to preallocate memory for the new table. This preallocation is useful for performance when you know in advance how many elements the table will have. Otherwise you can use the function <a href="#lua_newtable"><code>lua_newtable</code></a>. <hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip);</pre> <p> Dumps a function as a binary chunk. Receives a Lua function on the top of the stack and produces a binary chunk that, if loaded again, results in a function equivalent to the one dumped. As it produces parts of the chunk, <a href="#lua_dump"><code>lua_dump</code></a> calls function <code>writer</code> (see <a href="#lua_Writer"><code>lua_Writer</code></a>) with the given <code>data</code> to write them. <p> If <code>strip</code> is true, the binary representation may not include all debug information about the function, to save space. <p> The value returned is the error code returned by the last call to the writer; 0&nbsp;means no errors. <p> This function does not pop the Lua function from the stack. <hr><h3><a name="lua_error"><code>lua_error</code></a></h3><p> <span class="apii">[-1, +0, <em>v</em>]</span> <pre>int lua_error (lua_State *L);</pre> <p> Generates a Lua error, using the value at the top of the stack as the error object. This function does a long jump, and therefore never returns (see <a href="#luaL_error"><code>luaL_error</code></a>). <hr><h3><a name="lua_gc"><code>lua_gc</code></a></h3><p> <span class="apii">[-0, +0, <em>m</em>]</span> <pre>int lua_gc (lua_State *L, int what, int data);</pre> <p> Controls the garbage collector. <p> This function performs several tasks, according to the value of the parameter <code>what</code>: <ul> <li><b><code>LUA_GCSTOP</code>: </b> stops the garbage collector. </li> <li><b><code>LUA_GCRESTART</code>: </b> restarts the garbage collector. </li> <li><b><code>LUA_GCCOLLECT</code>: </b> performs a full garbage-collection cycle. </li> <li><b><code>LUA_GCCOUNT</code>: </b> returns the current amount of memory (in Kbytes) in use by Lua. </li> <li><b><code>LUA_GCCOUNTB</code>: </b> returns the remainder of dividing the current amount of bytes of memory in use by Lua by 1024. </li> <li><b><code>LUA_GCSTEP</code>: </b> performs an incremental step of garbage collection. </li> <li><b><code>LUA_GCSETPAUSE</code>: </b> sets <code>data</code> as the new value for the <em>pause</em> of the collector (see <a href="#2.5">&sect;2.5</a>) and returns the previous value of the pause. </li> <li><b><code>LUA_GCSETSTEPMUL</code>: </b> sets <code>data</code> as the new value for the <em>step multiplier</em> of the collector (see <a href="#2.5">&sect;2.5</a>) and returns the previous value of the step multiplier. </li> <li><b><code>LUA_GCISRUNNING</code>: </b> returns a boolean that tells whether the collector is running (i.e., not stopped). </li> </ul> <p> For more details about these options, see <a href="#pdf-collectgarbage"><code>collectgarbage</code></a>. <hr><h3><a name="lua_getallocf"><code>lua_getallocf</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>lua_Alloc lua_getallocf (lua_State *L, void **ud);</pre> <p> Returns the memory-allocation function of a given state. If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the opaque pointer given when the memory-allocator function was set. <hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p> <span class="apii">[-0, +1, <em>e</em>]</span> <pre>int lua_getfield (lua_State *L, int index, const char *k);</pre> <p> Pushes onto the stack the value <code>t[k]</code>, where <code>t</code> is the value at the given index. As in Lua, this function may trigger a metamethod for the "index" event (see <a href="#2.4">&sect;2.4</a>). <p> Returns the type of the pushed value. <hr><h3><a name="lua_getextraspace"><code>lua_getextraspace</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>void *lua_getextraspace (lua_State *L);</pre> <p> Returns a pointer to a raw memory area associated with the given Lua state. The application can use this area for any purpose; Lua does not use it for anything. <p> Each new thread has this area initialized with a copy of the area of the main thread. <p> By default, this area has the size of a pointer to void, but you can recompile Lua with a different size for this area. (See <code>LUA_EXTRASPACE</code> in <code>luaconf.h</code>.) <hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p> <span class="apii">[-0, +1, <em>e</em>]</span> <pre>int lua_getglobal (lua_State *L, const char *name);</pre> <p> Pushes onto the stack the value of the global <code>name</code>. Returns the type of that value. <hr><h3><a name="lua_geti"><code>lua_geti</code></a></h3><p> <span class="apii">[-0, +1, <em>e</em>]</span> <pre>int lua_geti (lua_State *L, int index, lua_Integer i);</pre> <p> Pushes onto the stack the value <code>t[i]</code>, where <code>t</code> is the value at the given index. As in Lua, this function may trigger a metamethod for the "index" event (see <a href="#2.4">&sect;2.4</a>). <p> Returns the type of the pushed value. <hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p> <span class="apii">[-0, +(0|1), &ndash;]</span> <pre>int lua_getmetatable (lua_State *L, int index);</pre> <p> If the value at the given index has a metatable, the function pushes that metatable onto the stack and returns&nbsp;1. Otherwise, the function returns&nbsp;0 and pushes nothing on the stack. <hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p> <span class="apii">[-1, +1, <em>e</em>]</span> <pre>int lua_gettable (lua_State *L, int index);</pre> <p> Pushes onto the stack the value <code>t[k]</code>, where <code>t</code> is the value at the given index and <code>k</code> is the value at the top of the stack. <p> This function pops the key from the stack, pushing the resulting value in its place. As in Lua, this function may trigger a metamethod for the "index" event (see <a href="#2.4">&sect;2.4</a>). <p> Returns the type of the pushed value. <hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_gettop (lua_State *L);</pre> <p> Returns the index of the top element in the stack. Because indices start at&nbsp;1, this result is equal to the number of elements in the stack; in particular, 0&nbsp;means an empty stack. <hr><h3><a name="lua_getuservalue"><code>lua_getuservalue</code></a></h3><p> <span class="apii">[-0, +1, &ndash;]</span> <pre>int lua_getuservalue (lua_State *L, int index);</pre> <p> Pushes onto the stack the Lua value associated with the full userdata at the given index. <p> Returns the type of the pushed value. <hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p> <span class="apii">[-1, +1, &ndash;]</span> <pre>void lua_insert (lua_State *L, int index);</pre> <p> Moves the top element into the given valid index, shifting up the elements above this index to open space. This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position. <hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3> <pre>typedef ... lua_Integer;</pre> <p> The type of integers in Lua. <p> By default this type is <code>long long</code>, (usually a 64-bit two-complement integer), but that can be changed to <code>long</code> or <code>int</code> (usually a 32-bit two-complement integer). (See <code>LUA_INT_TYPE</code> in <code>luaconf.h</code>.) <p> Lua also defines the constants <a name="pdf-LUA_MININTEGER"><code>LUA_MININTEGER</code></a> and <a name="pdf-LUA_MAXINTEGER"><code>LUA_MAXINTEGER</code></a>, with the minimum and the maximum values that fit in this type. <hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_isboolean (lua_State *L, int index);</pre> <p> Returns 1 if the value at the given index is a boolean, and 0&nbsp;otherwise. <hr><h3><a name="lua_iscfunction"><code>lua_iscfunction</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_iscfunction (lua_State *L, int index);</pre> <p> Returns 1 if the value at the given index is a C&nbsp;function, and 0&nbsp;otherwise. <hr><h3><a name="lua_isfunction"><code>lua_isfunction</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_isfunction (lua_State *L, int index);</pre> <p> Returns 1 if the value at the given index is a function (either C or Lua), and 0&nbsp;otherwise. <hr><h3><a name="lua_isinteger"><code>lua_isinteger</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_isinteger (lua_State *L, int index);</pre> <p> Returns 1 if the value at the given index is an integer (that is, the value is a number and is represented as an integer), and 0&nbsp;otherwise. <hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_islightuserdata (lua_State *L, int index);</pre> <p> Returns 1 if the value at the given index is a light userdata, and 0&nbsp;otherwise. <hr><h3><a name="lua_isnil"><code>lua_isnil</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_isnil (lua_State *L, int index);</pre> <p> Returns 1 if the value at the given index is <b>nil</b>, and 0&nbsp;otherwise. <hr><h3><a name="lua_isnone"><code>lua_isnone</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_isnone (lua_State *L, int index);</pre> <p> Returns 1 if the given index is not valid, and 0&nbsp;otherwise. <hr><h3><a name="lua_isnoneornil"><code>lua_isnoneornil</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_isnoneornil (lua_State *L, int index);</pre> <p> Returns 1 if the given index is not valid or if the value at this index is <b>nil</b>, and 0&nbsp;otherwise. <hr><h3><a name="lua_isnumber"><code>lua_isnumber</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_isnumber (lua_State *L, int index);</pre> <p> Returns 1 if the value at the given index is a number or a string convertible to a number, and 0&nbsp;otherwise. <hr><h3><a name="lua_isstring"><code>lua_isstring</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_isstring (lua_State *L, int index);</pre> <p> Returns 1 if the value at the given index is a string or a number (which is always convertible to a string), and 0&nbsp;otherwise. <hr><h3><a name="lua_istable"><code>lua_istable</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_istable (lua_State *L, int index);</pre> <p> Returns 1 if the value at the given index is a table, and 0&nbsp;otherwise. <hr><h3><a name="lua_isthread"><code>lua_isthread</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_isthread (lua_State *L, int index);</pre> <p> Returns 1 if the value at the given index is a thread, and 0&nbsp;otherwise. <hr><h3><a name="lua_isuserdata"><code>lua_isuserdata</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_isuserdata (lua_State *L, int index);</pre> <p> Returns 1 if the value at the given index is a userdata (either full or light), and 0&nbsp;otherwise. <hr><h3><a name="lua_isyieldable"><code>lua_isyieldable</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_isyieldable (lua_State *L);</pre> <p> Returns 1 if the given coroutine can yield, and 0&nbsp;otherwise. <hr><h3><a name="lua_KContext"><code>lua_KContext</code></a></h3> <pre>typedef ... lua_KContext;</pre> <p> The type for continuation-function contexts. It must be a numeric type. This type is defined as <code>intptr_t</code> when <code>intptr_t</code> is available, so that it can store pointers too. Otherwise, it is defined as <code>ptrdiff_t</code>. <hr><h3><a name="lua_KFunction"><code>lua_KFunction</code></a></h3> <pre>typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);</pre> <p> Type for continuation functions (see <a href="#4.7">&sect;4.7</a>). <hr><h3><a name="lua_len"><code>lua_len</code></a></h3><p> <span class="apii">[-0, +1, <em>e</em>]</span> <pre>void lua_len (lua_State *L, int index);</pre> <p> Returns the length of the value at the given index. It is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>) and may trigger a metamethod for the "length" event (see <a href="#2.4">&sect;2.4</a>). The result is pushed on the stack. <hr><h3><a name="lua_load"><code>lua_load</code></a></h3><p> <span class="apii">[-0, +1, &ndash;]</span> <pre>int lua_load (lua_State *L, lua_Reader reader, void *data, const char *chunkname, const char *mode);</pre> <p> Loads a Lua chunk without running it. If there are no errors, <code>lua_load</code> pushes the compiled chunk as a Lua function on top of the stack. Otherwise, it pushes an error message. <p> The return values of <code>lua_load</code> are: <ul> <li><b><a href="#pdf-LUA_OK"><code>LUA_OK</code></a>: </b> no errors;</li> <li><b><a name="pdf-LUA_ERRSYNTAX"><code>LUA_ERRSYNTAX</code></a>: </b> syntax error during precompilation;</li> <li><b><a href="#pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b> memory allocation (out-of-memory) error;</li> <li><b><a href="#pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b> error while running a <code>__gc</code> metamethod. (This error has no relation with the chunk being loaded. It is generated by the garbage collector.) </li> </ul> <p> The <code>lua_load</code> function uses a user-supplied <code>reader</code> function to read the chunk (see <a href="#lua_Reader"><code>lua_Reader</code></a>). The <code>data</code> argument is an opaque value passed to the reader function. <p> The <code>chunkname</code> argument gives a name to the chunk, which is used for error messages and in debug information (see <a href="#4.9">&sect;4.9</a>). <p> <code>lua_load</code> automatically detects whether the chunk is text or binary and loads it accordingly (see program <code>luac</code>). The string <code>mode</code> works as in function <a href="#pdf-load"><code>load</code></a>, with the addition that a <code>NULL</code> value is equivalent to the string "<code>bt</code>". <p> <code>lua_load</code> uses the stack internally, so the reader function must always leave the stack unmodified when returning. <p> If the resulting function has upvalues, its first upvalue is set to the value of the global environment stored at index <code>LUA_RIDX_GLOBALS</code> in the registry (see <a href="#4.5">&sect;4.5</a>). When loading main chunks, this upvalue will be the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>). Other upvalues are initialized with <b>nil</b>. <hr><h3><a name="lua_newstate"><code>lua_newstate</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>lua_State *lua_newstate (lua_Alloc f, void *ud);</pre> <p> Creates a new thread running in a new, independent state. Returns <code>NULL</code> if it cannot create the thread or the state (due to lack of memory). The argument <code>f</code> is the allocator function; Lua does all memory allocation for this state through this function (see <a href="#lua_Alloc"><code>lua_Alloc</code></a>). The second argument, <code>ud</code>, is an opaque pointer that Lua passes to the allocator in every call. <hr><h3><a name="lua_newtable"><code>lua_newtable</code></a></h3><p> <span class="apii">[-0, +1, <em>m</em>]</span> <pre>void lua_newtable (lua_State *L);</pre> <p> Creates a new empty table and pushes it onto the stack. It is equivalent to <code>lua_createtable(L, 0, 0)</code>. <hr><h3><a name="lua_newthread"><code>lua_newthread</code></a></h3><p> <span class="apii">[-0, +1, <em>m</em>]</span> <pre>lua_State *lua_newthread (lua_State *L);</pre> <p> Creates a new thread, pushes it on the stack, and returns a pointer to a <a href="#lua_State"><code>lua_State</code></a> that represents this new thread. The new thread returned by this function shares with the original thread its global environment, but has an independent execution stack. <p> There is no explicit function to close or to destroy a thread. Threads are subject to garbage collection, like any Lua object. <hr><h3><a name="lua_newuserdata"><code>lua_newuserdata</code></a></h3><p> <span class="apii">[-0, +1, <em>m</em>]</span> <pre>void *lua_newuserdata (lua_State *L, size_t size);</pre> <p> This function allocates a new block of memory with the given size, pushes onto the stack a new full userdata with the block address, and returns this address. The host program can freely use this memory. <hr><h3><a name="lua_next"><code>lua_next</code></a></h3><p> <span class="apii">[-1, +(2|0), <em>e</em>]</span> <pre>int lua_next (lua_State *L, int index);</pre> <p> Pops a key from the stack, and pushes a key&ndash;value pair from the table at the given index (the "next" pair after the given key). If there are no more elements in the table, then <a href="#lua_next"><code>lua_next</code></a> returns 0 (and pushes nothing). <p> A typical traversal looks like this: <pre> /* table is in the stack at index 't' */ lua_pushnil(L); /* first key */ while (lua_next(L, t) != 0) { /* uses 'key' (at index -2) and 'value' (at index -1) */ printf("%s - %s\n", lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1))); /* removes 'value'; keeps 'key' for next iteration */ lua_pop(L, 1); } </pre> <p> While traversing a table, do not call <a href="#lua_tolstring"><code>lua_tolstring</code></a> directly on a key, unless you know that the key is actually a string. Recall that <a href="#lua_tolstring"><code>lua_tolstring</code></a> may change the value at the given index; this confuses the next call to <a href="#lua_next"><code>lua_next</code></a>. <p> See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying the table during its traversal. <hr><h3><a name="lua_Number"><code>lua_Number</code></a></h3> <pre>typedef ... lua_Number;</pre> <p> The type of floats in Lua. <p> By default this type is double, but that can be changed to a single float or a long double. (See <code>LUA_FLOAT_TYPE</code> in <code>luaconf.h</code>.) <hr><h3><a name="lua_numbertointeger"><code>lua_numbertointeger</code></a></h3> <pre>int lua_numbertointeger (lua_Number n, lua_Integer *p);</pre> <p> Converts a Lua float to a Lua integer. This macro assumes that <code>n</code> has an integral value. If that value is within the range of Lua integers, it is converted to an integer and assigned to <code>*p</code>. The macro results in a boolean indicating whether the conversion was successful. (Note that this range test can be tricky to do correctly without this macro, due to roundings.) <p> This macro may evaluate its arguments more than once. <hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p> <span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span> <pre>int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);</pre> <p> Calls a function in protected mode. <p> Both <code>nargs</code> and <code>nresults</code> have the same meaning as in <a href="#lua_call"><code>lua_call</code></a>. If there are no errors during the call, <a href="#lua_pcall"><code>lua_pcall</code></a> behaves exactly like <a href="#lua_call"><code>lua_call</code></a>. However, if there is any error, <a href="#lua_pcall"><code>lua_pcall</code></a> catches it, pushes a single value on the stack (the error object), and returns an error code. Like <a href="#lua_call"><code>lua_call</code></a>, <a href="#lua_pcall"><code>lua_pcall</code></a> always removes the function and its arguments from the stack. <p> If <code>msgh</code> is 0, then the error object returned on the stack is exactly the original error object. Otherwise, <code>msgh</code> is the stack index of a <em>message handler</em>. (This index cannot be a pseudo-index.) In case of runtime errors, this function will be called with the error object and its return value will be the object returned on the stack by <a href="#lua_pcall"><code>lua_pcall</code></a>. <p> Typically, the message handler is used to add more debug information to the error object, such as a stack traceback. Such information cannot be gathered after the return of <a href="#lua_pcall"><code>lua_pcall</code></a>, since by then the stack has unwound. <p> The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following constants (defined in <code>lua.h</code>): <ul> <li><b><a name="pdf-LUA_OK"><code>LUA_OK</code></a> (0): </b> success.</li> <li><b><a name="pdf-LUA_ERRRUN"><code>LUA_ERRRUN</code></a>: </b> a runtime error. </li> <li><b><a name="pdf-LUA_ERRMEM"><code>LUA_ERRMEM</code></a>: </b> memory allocation error. For such errors, Lua does not call the message handler. </li> <li><b><a name="pdf-LUA_ERRERR"><code>LUA_ERRERR</code></a>: </b> error while running the message handler. </li> <li><b><a name="pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b> error while running a <code>__gc</code> metamethod. For such errors, Lua does not call the message handler (as this kind of error typically has no relation with the function being called). </li> </ul> <hr><h3><a name="lua_pcallk"><code>lua_pcallk</code></a></h3><p> <span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span> <pre>int lua_pcallk (lua_State *L, int nargs, int nresults, int msgh, lua_KContext ctx, lua_KFunction k);</pre> <p> This function behaves exactly like <a href="#lua_pcall"><code>lua_pcall</code></a>, but allows the called function to yield (see <a href="#4.7">&sect;4.7</a>). <hr><h3><a name="lua_pop"><code>lua_pop</code></a></h3><p> <span class="apii">[-n, +0, &ndash;]</span> <pre>void lua_pop (lua_State *L, int n);</pre> <p> Pops <code>n</code> elements from the stack. <hr><h3><a name="lua_pushboolean"><code>lua_pushboolean</code></a></h3><p> <span class="apii">[-0, +1, &ndash;]</span> <pre>void lua_pushboolean (lua_State *L, int b);</pre> <p> Pushes a boolean value with value <code>b</code> onto the stack. <hr><h3><a name="lua_pushcclosure"><code>lua_pushcclosure</code></a></h3><p> <span class="apii">[-n, +1, <em>m</em>]</span> <pre>void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);</pre> <p> Pushes a new C&nbsp;closure onto the stack. <p> When a C&nbsp;function is created, it is possible to associate some values with it, thus creating a C&nbsp;closure (see <a href="#4.4">&sect;4.4</a>); these values are then accessible to the function whenever it is called. To associate values with a C&nbsp;function, first these values must be pushed onto the stack (when there are multiple values, the first value is pushed first). Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> is called to create and push the C&nbsp;function onto the stack, with the argument <code>n</code> telling how many values will be associated with the function. <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack. <p> The maximum value for <code>n</code> is 255. <p> When <code>n</code> is zero, this function creates a <em>light C&nbsp;function</em>, which is just a pointer to the C&nbsp;function. In that case, it never raises a memory error. <hr><h3><a name="lua_pushcfunction"><code>lua_pushcfunction</code></a></h3><p> <span class="apii">[-0, +1, &ndash;]</span> <pre>void lua_pushcfunction (lua_State *L, lua_CFunction f);</pre> <p> Pushes a C&nbsp;function onto the stack. This function receives a pointer to a C&nbsp;function and pushes onto the stack a Lua value of type <code>function</code> that, when called, invokes the corresponding C&nbsp;function. <p> Any function to be callable by Lua must follow the correct protocol to receive its parameters and return its results (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>). <hr><h3><a name="lua_pushfstring"><code>lua_pushfstring</code></a></h3><p> <span class="apii">[-0, +1, <em>e</em>]</span> <pre>const char *lua_pushfstring (lua_State *L, const char *fmt, ...);</pre> <p> Pushes onto the stack a formatted string and returns a pointer to this string. It is similar to the ISO&nbsp;C function <code>sprintf</code>, but has some important differences: <ul> <li> You do not have to allocate space for the result: the result is a Lua string and Lua takes care of memory allocation (and deallocation, through garbage collection). </li> <li> The conversion specifiers are quite restricted. There are no flags, widths, or precisions. The conversion specifiers can only be '<code>%%</code>' (inserts the character '<code>%</code>'), '<code>%s</code>' (inserts a zero-terminated string, with no size restrictions), '<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>), '<code>%I</code>' (inserts a <a href="#lua_Integer"><code>lua_Integer</code></a>), '<code>%p</code>' (inserts a pointer as a hexadecimal numeral), '<code>%d</code>' (inserts an <code>int</code>), '<code>%c</code>' (inserts an <code>int</code> as a one-byte character), and '<code>%U</code>' (inserts a <code>long int</code> as a UTF-8 byte sequence). </li> </ul> <p> Unlike other push functions, this function checks for the stack space it needs, including the slot for its result. <hr><h3><a name="lua_pushglobaltable"><code>lua_pushglobaltable</code></a></h3><p> <span class="apii">[-0, +1, &ndash;]</span> <pre>void lua_pushglobaltable (lua_State *L);</pre> <p> Pushes the global environment onto the stack. <hr><h3><a name="lua_pushinteger"><code>lua_pushinteger</code></a></h3><p> <span class="apii">[-0, +1, &ndash;]</span> <pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre> <p> Pushes an integer with value <code>n</code> onto the stack. <hr><h3><a name="lua_pushlightuserdata"><code>lua_pushlightuserdata</code></a></h3><p> <span class="apii">[-0, +1, &ndash;]</span> <pre>void lua_pushlightuserdata (lua_State *L, void *p);</pre> <p> Pushes a light userdata onto the stack. <p> Userdata represent C&nbsp;values in Lua. A <em>light userdata</em> represents a pointer, a <code>void*</code>. It is a value (like a number): you do not create it, it has no individual metatable, and it is not collected (as it was never created). A light userdata is equal to "any" light userdata with the same C&nbsp;address. <hr><h3><a name="lua_pushliteral"><code>lua_pushliteral</code></a></h3><p> <span class="apii">[-0, +1, <em>m</em>]</span> <pre>const char *lua_pushliteral (lua_State *L, const char *s);</pre> <p> This macro is equivalent to <a href="#lua_pushstring"><code>lua_pushstring</code></a>, but should be used only when <code>s</code> is a literal string. <hr><h3><a name="lua_pushlstring"><code>lua_pushlstring</code></a></h3><p> <span class="apii">[-0, +1, <em>m</em>]</span> <pre>const char *lua_pushlstring (lua_State *L, const char *s, size_t len);</pre> <p> Pushes the string pointed to by <code>s</code> with size <code>len</code> onto the stack. Lua makes (or reuses) an internal copy of the given string, so the memory at <code>s</code> can be freed or reused immediately after the function returns. The string can contain any binary data, including embedded zeros. <p> Returns a pointer to the internal copy of the string. <hr><h3><a name="lua_pushnil"><code>lua_pushnil</code></a></h3><p> <span class="apii">[-0, +1, &ndash;]</span> <pre>void lua_pushnil (lua_State *L);</pre> <p> Pushes a nil value onto the stack. <hr><h3><a name="lua_pushnumber"><code>lua_pushnumber</code></a></h3><p> <span class="apii">[-0, +1, &ndash;]</span> <pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre> <p> Pushes a float with value <code>n</code> onto the stack. <hr><h3><a name="lua_pushstring"><code>lua_pushstring</code></a></h3><p> <span class="apii">[-0, +1, <em>m</em>]</span> <pre>const char *lua_pushstring (lua_State *L, const char *s);</pre> <p> Pushes the zero-terminated string pointed to by <code>s</code> onto the stack. Lua makes (or reuses) an internal copy of the given string, so the memory at <code>s</code> can be freed or reused immediately after the function returns. <p> Returns a pointer to the internal copy of the string. <p> If <code>s</code> is <code>NULL</code>, pushes <b>nil</b> and returns <code>NULL</code>. <hr><h3><a name="lua_pushthread"><code>lua_pushthread</code></a></h3><p> <span class="apii">[-0, +1, &ndash;]</span> <pre>int lua_pushthread (lua_State *L);</pre> <p> Pushes the thread represented by <code>L</code> onto the stack. Returns 1 if this thread is the main thread of its state. <hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p> <span class="apii">[-0, +1, &ndash;]</span> <pre>void lua_pushvalue (lua_State *L, int index);</pre> <p> Pushes a copy of the element at the given index onto the stack. <hr><h3><a name="lua_pushvfstring"><code>lua_pushvfstring</code></a></h3><p> <span class="apii">[-0, +1, <em>m</em>]</span> <pre>const char *lua_pushvfstring (lua_State *L, const char *fmt, va_list argp);</pre> <p> Equivalent to <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>, except that it receives a <code>va_list</code> instead of a variable number of arguments. <hr><h3><a name="lua_rawequal"><code>lua_rawequal</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_rawequal (lua_State *L, int index1, int index2);</pre> <p> Returns 1 if the two values in indices <code>index1</code> and <code>index2</code> are primitively equal (that is, without calling the <code>__eq</code> metamethod). Otherwise returns&nbsp;0. Also returns&nbsp;0 if any of the indices are not valid. <hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p> <span class="apii">[-1, +1, &ndash;]</span> <pre>int lua_rawget (lua_State *L, int index);</pre> <p> Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access (i.e., without metamethods). <hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p> <span class="apii">[-0, +1, &ndash;]</span> <pre>int lua_rawgeti (lua_State *L, int index, lua_Integer n);</pre> <p> Pushes onto the stack the value <code>t[n]</code>, where <code>t</code> is the table at the given index. The access is raw, that is, it does not invoke the <code>__index</code> metamethod. <p> Returns the type of the pushed value. <hr><h3><a name="lua_rawgetp"><code>lua_rawgetp</code></a></h3><p> <span class="apii">[-0, +1, &ndash;]</span> <pre>int lua_rawgetp (lua_State *L, int index, const void *p);</pre> <p> Pushes onto the stack the value <code>t[k]</code>, where <code>t</code> is the table at the given index and <code>k</code> is the pointer <code>p</code> represented as a light userdata. The access is raw; that is, it does not invoke the <code>__index</code> metamethod. <p> Returns the type of the pushed value. <hr><h3><a name="lua_rawlen"><code>lua_rawlen</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>size_t lua_rawlen (lua_State *L, int index);</pre> <p> Returns the raw "length" of the value at the given index: for strings, this is the string length; for tables, this is the result of the length operator ('<code>#</code>') with no metamethods; for userdata, this is the size of the block of memory allocated for the userdata; for other values, it is&nbsp;0. <hr><h3><a name="lua_rawset"><code>lua_rawset</code></a></h3><p> <span class="apii">[-2, +0, <em>m</em>]</span> <pre>void lua_rawset (lua_State *L, int index);</pre> <p> Similar to <a href="#lua_settable"><code>lua_settable</code></a>, but does a raw assignment (i.e., without metamethods). <hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p> <span class="apii">[-1, +0, <em>m</em>]</span> <pre>void lua_rawseti (lua_State *L, int index, lua_Integer i);</pre> <p> Does the equivalent of <code>t[i] = v</code>, where <code>t</code> is the table at the given index and <code>v</code> is the value at the top of the stack. <p> This function pops the value from the stack. The assignment is raw, that is, it does not invoke the <code>__newindex</code> metamethod. <hr><h3><a name="lua_rawsetp"><code>lua_rawsetp</code></a></h3><p> <span class="apii">[-1, +0, <em>m</em>]</span> <pre>void lua_rawsetp (lua_State *L, int index, const void *p);</pre> <p> Does the equivalent of <code>t[p] = v</code>, where <code>t</code> is the table at the given index, <code>p</code> is encoded as a light userdata, and <code>v</code> is the value at the top of the stack. <p> This function pops the value from the stack. The assignment is raw, that is, it does not invoke <code>__newindex</code> metamethod. <hr><h3><a name="lua_Reader"><code>lua_Reader</code></a></h3> <pre>typedef const char * (*lua_Reader) (lua_State *L, void *data, size_t *size);</pre> <p> The reader function used by <a href="#lua_load"><code>lua_load</code></a>. Every time it needs another piece of the chunk, <a href="#lua_load"><code>lua_load</code></a> calls the reader, passing along its <code>data</code> parameter. The reader must return a pointer to a block of memory with a new piece of the chunk and set <code>size</code> to the block size. The block must exist until the reader function is called again. To signal the end of the chunk, the reader must return <code>NULL</code> or set <code>size</code> to zero. The reader function may return pieces of any size greater than zero. <hr><h3><a name="lua_register"><code>lua_register</code></a></h3><p> <span class="apii">[-0, +0, <em>e</em>]</span> <pre>void lua_register (lua_State *L, const char *name, lua_CFunction f);</pre> <p> Sets the C&nbsp;function <code>f</code> as the new value of global <code>name</code>. It is defined as a macro: <pre> #define lua_register(L,n,f) \ (lua_pushcfunction(L, f), lua_setglobal(L, n)) </pre> <hr><h3><a name="lua_remove"><code>lua_remove</code></a></h3><p> <span class="apii">[-1, +0, &ndash;]</span> <pre>void lua_remove (lua_State *L, int index);</pre> <p> Removes the element at the given valid index, shifting down the elements above this index to fill the gap. This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position. <hr><h3><a name="lua_replace"><code>lua_replace</code></a></h3><p> <span class="apii">[-1, +0, &ndash;]</span> <pre>void lua_replace (lua_State *L, int index);</pre> <p> Moves the top element into the given valid index without shifting any element (therefore replacing the value at that given index), and then pops the top element. <hr><h3><a name="lua_resume"><code>lua_resume</code></a></h3><p> <span class="apii">[-?, +?, &ndash;]</span> <pre>int lua_resume (lua_State *L, lua_State *from, int nargs);</pre> <p> Starts and resumes a coroutine in the given thread <code>L</code>. <p> To start a coroutine, you push onto the thread stack the main function plus any arguments; then you call <a href="#lua_resume"><code>lua_resume</code></a>, with <code>nargs</code> being the number of arguments. This call returns when the coroutine suspends or finishes its execution. When it returns, the stack contains all values passed to <a href="#lua_yield"><code>lua_yield</code></a>, or all values returned by the body function. <a href="#lua_resume"><code>lua_resume</code></a> returns <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the coroutine yields, <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> if the coroutine finishes its execution without errors, or an error code in case of errors (see <a href="#lua_pcall"><code>lua_pcall</code></a>). <p> In case of errors, the stack is not unwound, so you can use the debug API over it. The error object is on the top of the stack. <p> To resume a coroutine, you remove any results from the last <a href="#lua_yield"><code>lua_yield</code></a>, put on its stack only the values to be passed as results from <code>yield</code>, and then call <a href="#lua_resume"><code>lua_resume</code></a>. <p> The parameter <code>from</code> represents the coroutine that is resuming <code>L</code>. If there is no such coroutine, this parameter can be <code>NULL</code>. <hr><h3><a name="lua_rotate"><code>lua_rotate</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>void lua_rotate (lua_State *L, int idx, int n);</pre> <p> Rotates the stack elements between the valid index <code>idx</code> and the top of the stack. The elements are rotated <code>n</code> positions in the direction of the top, for a positive <code>n</code>, or <code>-n</code> positions in the direction of the bottom, for a negative <code>n</code>. The absolute value of <code>n</code> must not be greater than the size of the slice being rotated. This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position. <hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre> <p> Changes the allocator function of a given state to <code>f</code> with user data <code>ud</code>. <hr><h3><a name="lua_setfield"><code>lua_setfield</code></a></h3><p> <span class="apii">[-1, +0, <em>e</em>]</span> <pre>void lua_setfield (lua_State *L, int index, const char *k);</pre> <p> Does the equivalent to <code>t[k] = v</code>, where <code>t</code> is the value at the given index and <code>v</code> is the value at the top of the stack. <p> This function pops the value from the stack. As in Lua, this function may trigger a metamethod for the "newindex" event (see <a href="#2.4">&sect;2.4</a>). <hr><h3><a name="lua_setglobal"><code>lua_setglobal</code></a></h3><p> <span class="apii">[-1, +0, <em>e</em>]</span> <pre>void lua_setglobal (lua_State *L, const char *name);</pre> <p> Pops a value from the stack and sets it as the new value of global <code>name</code>. <hr><h3><a name="lua_seti"><code>lua_seti</code></a></h3><p> <span class="apii">[-1, +0, <em>e</em>]</span> <pre>void lua_seti (lua_State *L, int index, lua_Integer n);</pre> <p> Does the equivalent to <code>t[n] = v</code>, where <code>t</code> is the value at the given index and <code>v</code> is the value at the top of the stack. <p> This function pops the value from the stack. As in Lua, this function may trigger a metamethod for the "newindex" event (see <a href="#2.4">&sect;2.4</a>). <hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p> <span class="apii">[-1, +0, &ndash;]</span> <pre>void lua_setmetatable (lua_State *L, int index);</pre> <p> Pops a table from the stack and sets it as the new metatable for the value at the given index. <hr><h3><a name="lua_settable"><code>lua_settable</code></a></h3><p> <span class="apii">[-2, +0, <em>e</em>]</span> <pre>void lua_settable (lua_State *L, int index);</pre> <p> Does the equivalent to <code>t[k] = v</code>, where <code>t</code> is the value at the given index, <code>v</code> is the value at the top of the stack, and <code>k</code> is the value just below the top. <p> This function pops both the key and the value from the stack. As in Lua, this function may trigger a metamethod for the "newindex" event (see <a href="#2.4">&sect;2.4</a>). <hr><h3><a name="lua_settop"><code>lua_settop</code></a></h3><p> <span class="apii">[-?, +?, &ndash;]</span> <pre>void lua_settop (lua_State *L, int index);</pre> <p> Accepts any index, or&nbsp;0, and sets the stack top to this index. If the new top is larger than the old one, then the new elements are filled with <b>nil</b>. If <code>index</code> is&nbsp;0, then all stack elements are removed. <hr><h3><a name="lua_setuservalue"><code>lua_setuservalue</code></a></h3><p> <span class="apii">[-1, +0, &ndash;]</span> <pre>void lua_setuservalue (lua_State *L, int index);</pre> <p> Pops a value from the stack and sets it as the new value associated to the full userdata at the given index. <hr><h3><a name="lua_State"><code>lua_State</code></a></h3> <pre>typedef struct lua_State lua_State;</pre> <p> An opaque structure that points to a thread and indirectly (through the thread) to the whole state of a Lua interpreter. The Lua library is fully reentrant: it has no global variables. All information about a state is accessible through this structure. <p> A pointer to this structure must be passed as the first argument to every function in the library, except to <a href="#lua_newstate"><code>lua_newstate</code></a>, which creates a Lua state from scratch. <hr><h3><a name="lua_status"><code>lua_status</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_status (lua_State *L);</pre> <p> Returns the status of the thread <code>L</code>. <p> The status can be 0 (<a href="#pdf-LUA_OK"><code>LUA_OK</code></a>) for a normal thread, an error code if the thread finished the execution of a <a href="#lua_resume"><code>lua_resume</code></a> with an error, or <a name="pdf-LUA_YIELD"><code>LUA_YIELD</code></a> if the thread is suspended. <p> You can only call functions in threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>. You can resume threads with status <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> (to start a new coroutine) or <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> (to resume a coroutine). <hr><h3><a name="lua_stringtonumber"><code>lua_stringtonumber</code></a></h3><p> <span class="apii">[-0, +1, &ndash;]</span> <pre>size_t lua_stringtonumber (lua_State *L, const char *s);</pre> <p> Converts the zero-terminated string <code>s</code> to a number, pushes that number into the stack, and returns the total size of the string, that is, its length plus one. The conversion can result in an integer or a float, according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>). The string may have leading and trailing spaces and a sign. If the string is not a valid numeral, returns 0 and pushes nothing. (Note that the result can be used as a boolean, true if the conversion succeeds.) <hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_toboolean (lua_State *L, int index);</pre> <p> Converts the Lua value at the given index to a C&nbsp;boolean value (0&nbsp;or&nbsp;1). Like all tests in Lua, <a href="#lua_toboolean"><code>lua_toboolean</code></a> returns true for any Lua value different from <b>false</b> and <b>nil</b>; otherwise it returns false. (If you want to accept only actual boolean values, use <a href="#lua_isboolean"><code>lua_isboolean</code></a> to test the value's type.) <hr><h3><a name="lua_tocfunction"><code>lua_tocfunction</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>lua_CFunction lua_tocfunction (lua_State *L, int index);</pre> <p> Converts a value at the given index to a C&nbsp;function. That value must be a C&nbsp;function; otherwise, returns <code>NULL</code>. <hr><h3><a name="lua_tointeger"><code>lua_tointeger</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>lua_Integer lua_tointeger (lua_State *L, int index);</pre> <p> Equivalent to <a href="#lua_tointegerx"><code>lua_tointegerx</code></a> with <code>isnum</code> equal to <code>NULL</code>. <hr><h3><a name="lua_tointegerx"><code>lua_tointegerx</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>lua_Integer lua_tointegerx (lua_State *L, int index, int *isnum);</pre> <p> Converts the Lua value at the given index to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>. The Lua value must be an integer, or a number or string convertible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>); otherwise, <code>lua_tointegerx</code> returns&nbsp;0. <p> If <code>isnum</code> is not <code>NULL</code>, its referent is assigned a boolean value that indicates whether the operation succeeded. <hr><h3><a name="lua_tolstring"><code>lua_tolstring</code></a></h3><p> <span class="apii">[-0, +0, <em>m</em>]</span> <pre>const char *lua_tolstring (lua_State *L, int index, size_t *len);</pre> <p> Converts the Lua value at the given index to a C&nbsp;string. If <code>len</code> is not <code>NULL</code>, it sets <code>*len</code> with the string length. The Lua value must be a string or a number; otherwise, the function returns <code>NULL</code>. If the value is a number, then <code>lua_tolstring</code> also <em>changes the actual value in the stack to a string</em>. (This change confuses <a href="#lua_next"><code>lua_next</code></a> when <code>lua_tolstring</code> is applied to keys during a table traversal.) <p> <code>lua_tolstring</code> returns a pointer to a string inside the Lua state. This string always has a zero ('<code>\0</code>') after its last character (as in&nbsp;C), but can contain other zeros in its body. <p> Because Lua has garbage collection, there is no guarantee that the pointer returned by <code>lua_tolstring</code> will be valid after the corresponding Lua value is removed from the stack. <hr><h3><a name="lua_tonumber"><code>lua_tonumber</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>lua_Number lua_tonumber (lua_State *L, int index);</pre> <p> Equivalent to <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> with <code>isnum</code> equal to <code>NULL</code>. <hr><h3><a name="lua_tonumberx"><code>lua_tonumberx</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>lua_Number lua_tonumberx (lua_State *L, int index, int *isnum);</pre> <p> Converts the Lua value at the given index to the C&nbsp;type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>). The Lua value must be a number or a string convertible to a number (see <a href="#3.4.3">&sect;3.4.3</a>); otherwise, <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> returns&nbsp;0. <p> If <code>isnum</code> is not <code>NULL</code>, its referent is assigned a boolean value that indicates whether the operation succeeded. <hr><h3><a name="lua_topointer"><code>lua_topointer</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>const void *lua_topointer (lua_State *L, int index);</pre> <p> Converts the value at the given index to a generic C&nbsp;pointer (<code>void*</code>). The value can be a userdata, a table, a thread, or a function; otherwise, <code>lua_topointer</code> returns <code>NULL</code>. Different objects will give different pointers. There is no way to convert the pointer back to its original value. <p> Typically this function is used only for hashing and debug information. <hr><h3><a name="lua_tostring"><code>lua_tostring</code></a></h3><p> <span class="apii">[-0, +0, <em>m</em>]</span> <pre>const char *lua_tostring (lua_State *L, int index);</pre> <p> Equivalent to <a href="#lua_tolstring"><code>lua_tolstring</code></a> with <code>len</code> equal to <code>NULL</code>. <hr><h3><a name="lua_tothread"><code>lua_tothread</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>lua_State *lua_tothread (lua_State *L, int index);</pre> <p> Converts the value at the given index to a Lua thread (represented as <code>lua_State*</code>). This value must be a thread; otherwise, the function returns <code>NULL</code>. <hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>void *lua_touserdata (lua_State *L, int index);</pre> <p> If the value at the given index is a full userdata, returns its block address. If the value is a light userdata, returns its pointer. Otherwise, returns <code>NULL</code>. <hr><h3><a name="lua_type"><code>lua_type</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_type (lua_State *L, int index);</pre> <p> Returns the type of the value in the given valid index, or <code>LUA_TNONE</code> for a non-valid (but acceptable) index. The types returned by <a href="#lua_type"><code>lua_type</code></a> are coded by the following constants defined in <code>lua.h</code>: <a name="pdf-LUA_TNIL"><code>LUA_TNIL</code></a> (0), <a name="pdf-LUA_TNUMBER"><code>LUA_TNUMBER</code></a>, <a name="pdf-LUA_TBOOLEAN"><code>LUA_TBOOLEAN</code></a>, <a name="pdf-LUA_TSTRING"><code>LUA_TSTRING</code></a>, <a name="pdf-LUA_TTABLE"><code>LUA_TTABLE</code></a>, <a name="pdf-LUA_TFUNCTION"><code>LUA_TFUNCTION</code></a>, <a name="pdf-LUA_TUSERDATA"><code>LUA_TUSERDATA</code></a>, <a name="pdf-LUA_TTHREAD"><code>LUA_TTHREAD</code></a>, and <a name="pdf-LUA_TLIGHTUSERDATA"><code>LUA_TLIGHTUSERDATA</code></a>. <hr><h3><a name="lua_typename"><code>lua_typename</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>const char *lua_typename (lua_State *L, int tp);</pre> <p> Returns the name of the type encoded by the value <code>tp</code>, which must be one the values returned by <a href="#lua_type"><code>lua_type</code></a>. <hr><h3><a name="lua_Unsigned"><code>lua_Unsigned</code></a></h3> <pre>typedef ... lua_Unsigned;</pre> <p> The unsigned version of <a href="#lua_Integer"><code>lua_Integer</code></a>. <hr><h3><a name="lua_upvalueindex"><code>lua_upvalueindex</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_upvalueindex (int i);</pre> <p> Returns the pseudo-index that represents the <code>i</code>-th upvalue of the running function (see <a href="#4.4">&sect;4.4</a>). <hr><h3><a name="lua_version"><code>lua_version</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>const lua_Number *lua_version (lua_State *L);</pre> <p> Returns the address of the version number (a C static variable) stored in the Lua core. When called with a valid <a href="#lua_State"><code>lua_State</code></a>, returns the address of the version used to create that state. When called with <code>NULL</code>, returns the address of the version running the call. <hr><h3><a name="lua_Writer"><code>lua_Writer</code></a></h3> <pre>typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud);</pre> <p> The type of the writer function used by <a href="#lua_dump"><code>lua_dump</code></a>. Every time it produces another piece of chunk, <a href="#lua_dump"><code>lua_dump</code></a> calls the writer, passing along the buffer to be written (<code>p</code>), its size (<code>sz</code>), and the <code>data</code> parameter supplied to <a href="#lua_dump"><code>lua_dump</code></a>. <p> The writer returns an error code: 0&nbsp;means no errors; any other value means an error and stops <a href="#lua_dump"><code>lua_dump</code></a> from calling the writer again. <hr><h3><a name="lua_xmove"><code>lua_xmove</code></a></h3><p> <span class="apii">[-?, +?, &ndash;]</span> <pre>void lua_xmove (lua_State *from, lua_State *to, int n);</pre> <p> Exchange values between different threads of the same state. <p> This function pops <code>n</code> values from the stack <code>from</code>, and pushes them onto the stack <code>to</code>. <hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p> <span class="apii">[-?, +?, <em>e</em>]</span> <pre>int lua_yield (lua_State *L, int nresults);</pre> <p> This function is equivalent to <a href="#lua_yieldk"><code>lua_yieldk</code></a>, but it has no continuation (see <a href="#4.7">&sect;4.7</a>). Therefore, when the thread resumes, it continues the function that called the function calling <code>lua_yield</code>. <hr><h3><a name="lua_yieldk"><code>lua_yieldk</code></a></h3><p> <span class="apii">[-?, +?, <em>e</em>]</span> <pre>int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx, lua_KFunction k);</pre> <p> Yields a coroutine (thread). <p> When a C&nbsp;function calls <a href="#lua_yieldk"><code>lua_yieldk</code></a>, the running coroutine suspends its execution, and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns. The parameter <code>nresults</code> is the number of values from the stack that will be passed as results to <a href="#lua_resume"><code>lua_resume</code></a>. <p> When the coroutine is resumed again, Lua calls the given continuation function <code>k</code> to continue the execution of the C&nbsp;function that yielded (see <a href="#4.7">&sect;4.7</a>). This continuation function receives the same stack from the previous function, with the <code>n</code> results removed and replaced by the arguments passed to <a href="#lua_resume"><code>lua_resume</code></a>. Moreover, the continuation function receives the value <code>ctx</code> that was passed to <a href="#lua_yieldk"><code>lua_yieldk</code></a>. <p> Usually, this function does not return; when the coroutine eventually resumes, it continues executing the continuation function. However, there is one special case, which is when this function is called from inside a line or a count hook (see <a href="#4.9">&sect;4.9</a>). In that case, <code>lua_yieldk</code> should be called with no continuation (probably in the form of <a href="#lua_yield"><code>lua_yield</code></a>) and no results, and the hook should return immediately after the call. Lua will yield and, when the coroutine resumes again, it will continue the normal execution of the (Lua) function that triggered the hook. <p> This function can raise an error if it is called from a thread with a pending C call with no continuation function, or it is called from a thread that is not running inside a resume (e.g., the main thread). <h2>4.9 &ndash; <a name="4.9">The Debug Interface</a></h2> <p> Lua has no built-in debugging facilities. Instead, it offers a special interface by means of functions and <em>hooks</em>. This interface allows the construction of different kinds of debuggers, profilers, and other tools that need "inside information" from the interpreter. <hr><h3><a name="lua_Debug"><code>lua_Debug</code></a></h3> <pre>typedef struct lua_Debug { int event; const char *name; /* (n) */ const char *namewhat; /* (n) */ const char *what; /* (S) */ const char *source; /* (S) */ int currentline; /* (l) */ int linedefined; /* (S) */ int lastlinedefined; /* (S) */ unsigned char nups; /* (u) number of upvalues */ unsigned char nparams; /* (u) number of parameters */ char isvararg; /* (u) */ char istailcall; /* (t) */ char short_src[LUA_IDSIZE]; /* (S) */ /* private part */ <em>other fields</em> } lua_Debug;</pre> <p> A structure used to carry different pieces of information about a function or an activation record. <a href="#lua_getstack"><code>lua_getstack</code></a> fills only the private part of this structure, for later use. To fill the other fields of <a href="#lua_Debug"><code>lua_Debug</code></a> with useful information, call <a href="#lua_getinfo"><code>lua_getinfo</code></a>. <p> The fields of <a href="#lua_Debug"><code>lua_Debug</code></a> have the following meaning: <ul> <li><b><code>source</code>: </b> the name of the chunk that created the function. If <code>source</code> starts with a '<code>@</code>', it means that the function was defined in a file where the file name follows the '<code>@</code>'. If <code>source</code> starts with a '<code>=</code>', the remainder of its contents describe the source in a user-dependent manner. Otherwise, the function was defined in a string where <code>source</code> is that string. </li> <li><b><code>short_src</code>: </b> a "printable" version of <code>source</code>, to be used in error messages. </li> <li><b><code>linedefined</code>: </b> the line number where the definition of the function starts. </li> <li><b><code>lastlinedefined</code>: </b> the line number where the definition of the function ends. </li> <li><b><code>what</code>: </b> the string <code>"Lua"</code> if the function is a Lua function, <code>"C"</code> if it is a C&nbsp;function, <code>"main"</code> if it is the main part of a chunk. </li> <li><b><code>currentline</code>: </b> the current line where the given function is executing. When no line information is available, <code>currentline</code> is set to -1. </li> <li><b><code>name</code>: </b> a reasonable name for the given function. Because functions in Lua are first-class values, they do not have a fixed name: some functions can be the value of multiple global variables, while others can be stored only in a table field. The <code>lua_getinfo</code> function checks how the function was called to find a suitable name. If it cannot find a name, then <code>name</code> is set to <code>NULL</code>. </li> <li><b><code>namewhat</code>: </b> explains the <code>name</code> field. The value of <code>namewhat</code> can be <code>"global"</code>, <code>"local"</code>, <code>"method"</code>, <code>"field"</code>, <code>"upvalue"</code>, or <code>""</code> (the empty string), according to how the function was called. (Lua uses the empty string when no other option seems to apply.) </li> <li><b><code>istailcall</code>: </b> true if this function invocation was called by a tail call. In this case, the caller of this level is not in the stack. </li> <li><b><code>nups</code>: </b> the number of upvalues of the function. </li> <li><b><code>nparams</code>: </b> the number of fixed parameters of the function (always 0&nbsp;for C&nbsp;functions). </li> <li><b><code>isvararg</code>: </b> true if the function is a vararg function (always true for C&nbsp;functions). </li> </ul> <hr><h3><a name="lua_gethook"><code>lua_gethook</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>lua_Hook lua_gethook (lua_State *L);</pre> <p> Returns the current hook function. <hr><h3><a name="lua_gethookcount"><code>lua_gethookcount</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_gethookcount (lua_State *L);</pre> <p> Returns the current hook count. <hr><h3><a name="lua_gethookmask"><code>lua_gethookmask</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_gethookmask (lua_State *L);</pre> <p> Returns the current hook mask. <hr><h3><a name="lua_getinfo"><code>lua_getinfo</code></a></h3><p> <span class="apii">[-(0|1), +(0|1|2), <em>e</em>]</span> <pre>int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);</pre> <p> Gets information about a specific function or function invocation. <p> To get information about a function invocation, the parameter <code>ar</code> must be a valid activation record that was filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>). <p> To get information about a function, you push it onto the stack and start the <code>what</code> string with the character '<code>&gt;</code>'. (In that case, <code>lua_getinfo</code> pops the function from the top of the stack.) For instance, to know in which line a function <code>f</code> was defined, you can write the following code: <pre> lua_Debug ar; lua_getglobal(L, "f"); /* get global 'f' */ lua_getinfo(L, "&gt;S", &amp;ar); printf("%d\n", ar.linedefined); </pre> <p> Each character in the string <code>what</code> selects some fields of the structure <code>ar</code> to be filled or a value to be pushed on the stack: <ul> <li><b>'<code>n</code>': </b> fills in the field <code>name</code> and <code>namewhat</code>; </li> <li><b>'<code>S</code>': </b> fills in the fields <code>source</code>, <code>short_src</code>, <code>linedefined</code>, <code>lastlinedefined</code>, and <code>what</code>; </li> <li><b>'<code>l</code>': </b> fills in the field <code>currentline</code>; </li> <li><b>'<code>t</code>': </b> fills in the field <code>istailcall</code>; </li> <li><b>'<code>u</code>': </b> fills in the fields <code>nups</code>, <code>nparams</code>, and <code>isvararg</code>; </li> <li><b>'<code>f</code>': </b> pushes onto the stack the function that is running at the given level; </li> <li><b>'<code>L</code>': </b> pushes onto the stack a table whose indices are the numbers of the lines that are valid on the function. (A <em>valid line</em> is a line with some associated code, that is, a line where you can put a break point. Non-valid lines include empty lines and comments.) <p> If this option is given together with option '<code>f</code>', its table is pushed after the function. </li> </ul> <p> This function returns 0 on error (for instance, an invalid option in <code>what</code>). <hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p> <span class="apii">[-0, +(0|1), &ndash;]</span> <pre>const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);</pre> <p> Gets information about a local variable of a given activation record or a given function. <p> In the first case, the parameter <code>ar</code> must be a valid activation record that was filled by a previous call to <a href="#lua_getstack"><code>lua_getstack</code></a> or given as argument to a hook (see <a href="#lua_Hook"><code>lua_Hook</code></a>). The index <code>n</code> selects which local variable to inspect; see <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for details about variable indices and names. <p> <a href="#lua_getlocal"><code>lua_getlocal</code></a> pushes the variable's value onto the stack and returns its name. <p> In the second case, <code>ar</code> must be <code>NULL</code> and the function to be inspected must be at the top of the stack. In this case, only parameters of Lua functions are visible (as there is no information about what variables are active) and no values are pushed onto the stack. <p> Returns <code>NULL</code> (and pushes nothing) when the index is greater than the number of active local variables. <hr><h3><a name="lua_getstack"><code>lua_getstack</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>int lua_getstack (lua_State *L, int level, lua_Debug *ar);</pre> <p> Gets information about the interpreter runtime stack. <p> This function fills parts of a <a href="#lua_Debug"><code>lua_Debug</code></a> structure with an identification of the <em>activation record</em> of the function executing at a given level. Level&nbsp;0 is the current running function, whereas level <em>n+1</em> is the function that has called level <em>n</em> (except for tail calls, which do not count on the stack). When there are no errors, <a href="#lua_getstack"><code>lua_getstack</code></a> returns 1; when called with a level greater than the stack depth, it returns 0. <hr><h3><a name="lua_getupvalue"><code>lua_getupvalue</code></a></h3><p> <span class="apii">[-0, +(0|1), &ndash;]</span> <pre>const char *lua_getupvalue (lua_State *L, int funcindex, int n);</pre> <p> Gets information about the <code>n</code>-th upvalue of the closure at index <code>funcindex</code>. It pushes the upvalue's value onto the stack and returns its name. Returns <code>NULL</code> (and pushes nothing) when the index <code>n</code> is greater than the number of upvalues. <p> For C&nbsp;functions, this function uses the empty string <code>""</code> as a name for all upvalues. (For Lua functions, upvalues are the external local variables that the function uses, and that are consequently included in its closure.) <p> Upvalues have no particular order, as they are active through the whole function. They are numbered in an arbitrary order. <hr><h3><a name="lua_Hook"><code>lua_Hook</code></a></h3> <pre>typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);</pre> <p> Type for debugging hook functions. <p> Whenever a hook is called, its <code>ar</code> argument has its field <code>event</code> set to the specific event that triggered the hook. Lua identifies these events with the following constants: <a name="pdf-LUA_HOOKCALL"><code>LUA_HOOKCALL</code></a>, <a name="pdf-LUA_HOOKRET"><code>LUA_HOOKRET</code></a>, <a name="pdf-LUA_HOOKTAILCALL"><code>LUA_HOOKTAILCALL</code></a>, <a name="pdf-LUA_HOOKLINE"><code>LUA_HOOKLINE</code></a>, and <a name="pdf-LUA_HOOKCOUNT"><code>LUA_HOOKCOUNT</code></a>. Moreover, for line events, the field <code>currentline</code> is also set. To get the value of any other field in <code>ar</code>, the hook must call <a href="#lua_getinfo"><code>lua_getinfo</code></a>. <p> For call events, <code>event</code> can be <code>LUA_HOOKCALL</code>, the normal value, or <code>LUA_HOOKTAILCALL</code>, for a tail call; in this case, there will be no corresponding return event. <p> While Lua is running a hook, it disables other calls to hooks. Therefore, if a hook calls back Lua to execute a function or a chunk, this execution occurs without any calls to hooks. <p> Hook functions cannot have continuations, that is, they cannot call <a href="#lua_yieldk"><code>lua_yieldk</code></a>, <a href="#lua_pcallk"><code>lua_pcallk</code></a>, or <a href="#lua_callk"><code>lua_callk</code></a> with a non-null <code>k</code>. <p> Hook functions can yield under the following conditions: Only count and line events can yield; to yield, a hook function must finish its execution calling <a href="#lua_yield"><code>lua_yield</code></a> with <code>nresults</code> equal to zero (that is, with no values). <hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre> <p> Sets the debugging hook function. <p> Argument <code>f</code> is the hook function. <code>mask</code> specifies on which events the hook will be called: it is formed by a bitwise OR of the constants <a name="pdf-LUA_MASKCALL"><code>LUA_MASKCALL</code></a>, <a name="pdf-LUA_MASKRET"><code>LUA_MASKRET</code></a>, <a name="pdf-LUA_MASKLINE"><code>LUA_MASKLINE</code></a>, and <a name="pdf-LUA_MASKCOUNT"><code>LUA_MASKCOUNT</code></a>. The <code>count</code> argument is only meaningful when the mask includes <code>LUA_MASKCOUNT</code>. For each event, the hook is called as explained below: <ul> <li><b>The call hook: </b> is called when the interpreter calls a function. The hook is called just after Lua enters the new function, before the function gets its arguments. </li> <li><b>The return hook: </b> is called when the interpreter returns from a function. The hook is called just before Lua leaves the function. There is no standard way to access the values to be returned by the function. </li> <li><b>The line hook: </b> is called when the interpreter is about to start the execution of a new line of code, or when it jumps back in the code (even to the same line). (This event only happens while Lua is executing a Lua function.) </li> <li><b>The count hook: </b> is called after the interpreter executes every <code>count</code> instructions. (This event only happens while Lua is executing a Lua function.) </li> </ul> <p> A hook is disabled by setting <code>mask</code> to zero. <hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p> <span class="apii">[-(0|1), +0, &ndash;]</span> <pre>const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);</pre> <p> Sets the value of a local variable of a given activation record. It assigns the value at the top of the stack to the variable and returns its name. It also pops the value from the stack. <p> Returns <code>NULL</code> (and pops nothing) when the index is greater than the number of active local variables. <p> Parameters <code>ar</code> and <code>n</code> are as in function <a href="#lua_getlocal"><code>lua_getlocal</code></a>. <hr><h3><a name="lua_setupvalue"><code>lua_setupvalue</code></a></h3><p> <span class="apii">[-(0|1), +0, &ndash;]</span> <pre>const char *lua_setupvalue (lua_State *L, int funcindex, int n);</pre> <p> Sets the value of a closure's upvalue. It assigns the value at the top of the stack to the upvalue and returns its name. It also pops the value from the stack. <p> Returns <code>NULL</code> (and pops nothing) when the index <code>n</code> is greater than the number of upvalues. <p> Parameters <code>funcindex</code> and <code>n</code> are as in function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>. <hr><h3><a name="lua_upvalueid"><code>lua_upvalueid</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>void *lua_upvalueid (lua_State *L, int funcindex, int n);</pre> <p> Returns a unique identifier for the upvalue numbered <code>n</code> from the closure at index <code>funcindex</code>. <p> These unique identifiers allow a program to check whether different closures share upvalues. Lua closures that share an upvalue (that is, that access a same external local variable) will return identical ids for those upvalue indices. <p> Parameters <code>funcindex</code> and <code>n</code> are as in function <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>, but <code>n</code> cannot be greater than the number of upvalues. <hr><h3><a name="lua_upvaluejoin"><code>lua_upvaluejoin</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>void lua_upvaluejoin (lua_State *L, int funcindex1, int n1, int funcindex2, int n2);</pre> <p> Make the <code>n1</code>-th upvalue of the Lua closure at index <code>funcindex1</code> refer to the <code>n2</code>-th upvalue of the Lua closure at index <code>funcindex2</code>. <h1>5 &ndash; <a name="5">The Auxiliary Library</a></h1> <p> The <em>auxiliary library</em> provides several convenient functions to interface C with Lua. While the basic API provides the primitive functions for all interactions between C and Lua, the auxiliary library provides higher-level functions for some common tasks. <p> All functions and types from the auxiliary library are defined in header file <code>lauxlib.h</code> and have a prefix <code>luaL_</code>. <p> All functions in the auxiliary library are built on top of the basic API, and so they provide nothing that cannot be done with that API. Nevertheless, the use of the auxiliary library ensures more consistency to your code. <p> Several functions in the auxiliary library use internally some extra stack slots. When a function in the auxiliary library uses less than five slots, it does not check the stack size; it simply assumes that there are enough slots. <p> Several functions in the auxiliary library are used to check C&nbsp;function arguments. Because the error message is formatted for arguments (e.g., "<code>bad argument #1</code>"), you should not use these functions for other stack values. <p> Functions called <code>luaL_check*</code> always raise an error if the check is not satisfied. <h2>5.1 &ndash; <a name="5.1">Functions and Types</a></h2> <p> Here we list all functions and types from the auxiliary library in alphabetical order. <hr><h3><a name="luaL_addchar"><code>luaL_addchar</code></a></h3><p> <span class="apii">[-?, +?, <em>m</em>]</span> <pre>void luaL_addchar (luaL_Buffer *B, char c);</pre> <p> Adds the byte <code>c</code> to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). <hr><h3><a name="luaL_addlstring"><code>luaL_addlstring</code></a></h3><p> <span class="apii">[-?, +?, <em>m</em>]</span> <pre>void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);</pre> <p> Adds the string pointed to by <code>s</code> with length <code>l</code> to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). The string can contain embedded zeros. <hr><h3><a name="luaL_addsize"><code>luaL_addsize</code></a></h3><p> <span class="apii">[-?, +?, &ndash;]</span> <pre>void luaL_addsize (luaL_Buffer *B, size_t n);</pre> <p> Adds to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>) a string of length <code>n</code> previously copied to the buffer area (see <a href="#luaL_prepbuffer"><code>luaL_prepbuffer</code></a>). <hr><h3><a name="luaL_addstring"><code>luaL_addstring</code></a></h3><p> <span class="apii">[-?, +?, <em>m</em>]</span> <pre>void luaL_addstring (luaL_Buffer *B, const char *s);</pre> <p> Adds the zero-terminated string pointed to by <code>s</code> to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). <hr><h3><a name="luaL_addvalue"><code>luaL_addvalue</code></a></h3><p> <span class="apii">[-1, +?, <em>m</em>]</span> <pre>void luaL_addvalue (luaL_Buffer *B);</pre> <p> Adds the value at the top of the stack to the buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). Pops the value. <p> This is the only function on string buffers that can (and must) be called with an extra element on the stack, which is the value to be added to the buffer. <hr><h3><a name="luaL_argcheck"><code>luaL_argcheck</code></a></h3><p> <span class="apii">[-0, +0, <em>v</em>]</span> <pre>void luaL_argcheck (lua_State *L, int cond, int arg, const char *extramsg);</pre> <p> Checks whether <code>cond</code> is true. If it is not, raises an error with a standard message (see <a href="#luaL_argerror"><code>luaL_argerror</code></a>). <hr><h3><a name="luaL_argerror"><code>luaL_argerror</code></a></h3><p> <span class="apii">[-0, +0, <em>v</em>]</span> <pre>int luaL_argerror (lua_State *L, int arg, const char *extramsg);</pre> <p> Raises an error reporting a problem with argument <code>arg</code> of the C&nbsp;function that called it, using a standard message that includes <code>extramsg</code> as a comment: <pre> bad argument #<em>arg</em> to '<em>funcname</em>' (<em>extramsg</em>) </pre><p> This function never returns. <hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3> <pre>typedef struct luaL_Buffer luaL_Buffer;</pre> <p> Type for a <em>string buffer</em>. <p> A string buffer allows C&nbsp;code to build Lua strings piecemeal. Its pattern of use is as follows: <ul> <li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li> <li>Then initialize it with a call <code>luaL_buffinit(L, &amp;b)</code>.</li> <li> Then add string pieces to the buffer calling any of the <code>luaL_add*</code> functions. </li> <li> Finish by calling <code>luaL_pushresult(&amp;b)</code>. This call leaves the final string on the top of the stack. </li> </ul> <p> If you know beforehand the total size of the resulting string, you can use the buffer like this: <ul> <li>First declare a variable <code>b</code> of type <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>.</li> <li>Then initialize it and preallocate a space of size <code>sz</code> with a call <code>luaL_buffinitsize(L, &amp;b, sz)</code>.</li> <li>Then copy the string into that space.</li> <li> Finish by calling <code>luaL_pushresultsize(&amp;b, sz)</code>, where <code>sz</code> is the total size of the resulting string copied into that space. </li> </ul> <p> During its normal operation, a string buffer uses a variable number of stack slots. So, while using a buffer, you cannot assume that you know where the top of the stack is. You can use the stack between successive calls to buffer operations as long as that use is balanced; that is, when you call a buffer operation, the stack is at the same level it was immediately after the previous buffer operation. (The only exception to this rule is <a href="#luaL_addvalue"><code>luaL_addvalue</code></a>.) After calling <a href="#luaL_pushresult"><code>luaL_pushresult</code></a> the stack is back to its level when the buffer was initialized, plus the final string on its top. <hr><h3><a name="luaL_buffinit"><code>luaL_buffinit</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>void luaL_buffinit (lua_State *L, luaL_Buffer *B);</pre> <p> Initializes a buffer <code>B</code>. This function does not allocate any space; the buffer must be declared as a variable (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). <hr><h3><a name="luaL_buffinitsize"><code>luaL_buffinitsize</code></a></h3><p> <span class="apii">[-?, +?, <em>m</em>]</span> <pre>char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);</pre> <p> Equivalent to the sequence <a href="#luaL_buffinit"><code>luaL_buffinit</code></a>, <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a>. <hr><h3><a name="luaL_callmeta"><code>luaL_callmeta</code></a></h3><p> <span class="apii">[-0, +(0|1), <em>e</em>]</span> <pre>int luaL_callmeta (lua_State *L, int obj, const char *e);</pre> <p> Calls a metamethod. <p> If the object at index <code>obj</code> has a metatable and this metatable has a field <code>e</code>, this function calls this field passing the object as its only argument. In this case this function returns true and pushes onto the stack the value returned by the call. If there is no metatable or no metamethod, this function returns false (without pushing any value on the stack). <hr><h3><a name="luaL_checkany"><code>luaL_checkany</code></a></h3><p> <span class="apii">[-0, +0, <em>v</em>]</span> <pre>void luaL_checkany (lua_State *L, int arg);</pre> <p> Checks whether the function has an argument of any type (including <b>nil</b>) at position <code>arg</code>. <hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p> <span class="apii">[-0, +0, <em>v</em>]</span> <pre>lua_Integer luaL_checkinteger (lua_State *L, int arg);</pre> <p> Checks whether the function argument <code>arg</code> is an integer (or can be converted to an integer) and returns this integer cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>. <hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p> <span class="apii">[-0, +0, <em>v</em>]</span> <pre>const char *luaL_checklstring (lua_State *L, int arg, size_t *l);</pre> <p> Checks whether the function argument <code>arg</code> is a string and returns this string; if <code>l</code> is not <code>NULL</code> fills <code>*l</code> with the string's length. <p> This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result, so all conversions and caveats of that function apply here. <hr><h3><a name="luaL_checknumber"><code>luaL_checknumber</code></a></h3><p> <span class="apii">[-0, +0, <em>v</em>]</span> <pre>lua_Number luaL_checknumber (lua_State *L, int arg);</pre> <p> Checks whether the function argument <code>arg</code> is a number and returns this number. <hr><h3><a name="luaL_checkoption"><code>luaL_checkoption</code></a></h3><p> <span class="apii">[-0, +0, <em>v</em>]</span> <pre>int luaL_checkoption (lua_State *L, int arg, const char *def, const char *const lst[]);</pre> <p> Checks whether the function argument <code>arg</code> is a string and searches for this string in the array <code>lst</code> (which must be NULL-terminated). Returns the index in the array where the string was found. Raises an error if the argument is not a string or if the string cannot be found. <p> If <code>def</code> is not <code>NULL</code>, the function uses <code>def</code> as a default value when there is no argument <code>arg</code> or when this argument is <b>nil</b>. <p> This is a useful function for mapping strings to C&nbsp;enums. (The usual convention in Lua libraries is to use strings instead of numbers to select options.) <hr><h3><a name="luaL_checkstack"><code>luaL_checkstack</code></a></h3><p> <span class="apii">[-0, +0, <em>v</em>]</span> <pre>void luaL_checkstack (lua_State *L, int sz, const char *msg);</pre> <p> Grows the stack size to <code>top + sz</code> elements, raising an error if the stack cannot grow to that size. <code>msg</code> is an additional text to go into the error message (or <code>NULL</code> for no additional text). <hr><h3><a name="luaL_checkstring"><code>luaL_checkstring</code></a></h3><p> <span class="apii">[-0, +0, <em>v</em>]</span> <pre>const char *luaL_checkstring (lua_State *L, int arg);</pre> <p> Checks whether the function argument <code>arg</code> is a string and returns this string. <p> This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result, so all conversions and caveats of that function apply here. <hr><h3><a name="luaL_checktype"><code>luaL_checktype</code></a></h3><p> <span class="apii">[-0, +0, <em>v</em>]</span> <pre>void luaL_checktype (lua_State *L, int arg, int t);</pre> <p> Checks whether the function argument <code>arg</code> has type <code>t</code>. See <a href="#lua_type"><code>lua_type</code></a> for the encoding of types for <code>t</code>. <hr><h3><a name="luaL_checkudata"><code>luaL_checkudata</code></a></h3><p> <span class="apii">[-0, +0, <em>v</em>]</span> <pre>void *luaL_checkudata (lua_State *L, int arg, const char *tname);</pre> <p> Checks whether the function argument <code>arg</code> is a userdata of the type <code>tname</code> (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>) and returns the userdata address (see <a href="#lua_touserdata"><code>lua_touserdata</code></a>). <hr><h3><a name="luaL_checkversion"><code>luaL_checkversion</code></a></h3><p> <span class="apii">[-0, +0, <em>v</em>]</span> <pre>void luaL_checkversion (lua_State *L);</pre> <p> Checks whether the core running the call, the core that created the Lua state, and the code making the call are all using the same version of Lua. Also checks whether the core running the call and the core that created the Lua state are using the same address space. <hr><h3><a name="luaL_dofile"><code>luaL_dofile</code></a></h3><p> <span class="apii">[-0, +?, <em>e</em>]</span> <pre>int luaL_dofile (lua_State *L, const char *filename);</pre> <p> Loads and runs the given file. It is defined as the following macro: <pre> (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0)) </pre><p> It returns false if there are no errors or true in case of errors. <hr><h3><a name="luaL_dostring"><code>luaL_dostring</code></a></h3><p> <span class="apii">[-0, +?, &ndash;]</span> <pre>int luaL_dostring (lua_State *L, const char *str);</pre> <p> Loads and runs the given string. It is defined as the following macro: <pre> (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0)) </pre><p> It returns false if there are no errors or true in case of errors. <hr><h3><a name="luaL_error"><code>luaL_error</code></a></h3><p> <span class="apii">[-0, +0, <em>v</em>]</span> <pre>int luaL_error (lua_State *L, const char *fmt, ...);</pre> <p> Raises an error. The error message format is given by <code>fmt</code> plus any extra arguments, following the same rules of <a href="#lua_pushfstring"><code>lua_pushfstring</code></a>. It also adds at the beginning of the message the file name and the line number where the error occurred, if this information is available. <p> This function never returns, but it is an idiom to use it in C&nbsp;functions as <code>return luaL_error(<em>args</em>)</code>. <hr><h3><a name="luaL_execresult"><code>luaL_execresult</code></a></h3><p> <span class="apii">[-0, +3, <em>m</em>]</span> <pre>int luaL_execresult (lua_State *L, int stat);</pre> <p> This function produces the return values for process-related functions in the standard library (<a href="#pdf-os.execute"><code>os.execute</code></a> and <a href="#pdf-io.close"><code>io.close</code></a>). <hr><h3><a name="luaL_fileresult"><code>luaL_fileresult</code></a></h3><p> <span class="apii">[-0, +(1|3), <em>m</em>]</span> <pre>int luaL_fileresult (lua_State *L, int stat, const char *fname);</pre> <p> This function produces the return values for file-related functions in the standard library (<a href="#pdf-io.open"><code>io.open</code></a>, <a href="#pdf-os.rename"><code>os.rename</code></a>, <a href="#pdf-file:seek"><code>file:seek</code></a>, etc.). <hr><h3><a name="luaL_getmetafield"><code>luaL_getmetafield</code></a></h3><p> <span class="apii">[-0, +(0|1), <em>m</em>]</span> <pre>int luaL_getmetafield (lua_State *L, int obj, const char *e);</pre> <p> Pushes onto the stack the field <code>e</code> from the metatable of the object at index <code>obj</code> and returns the type of the pushed value. If the object does not have a metatable, or if the metatable does not have this field, pushes nothing and returns <code>LUA_TNIL</code>. <hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p> <span class="apii">[-0, +1, <em>m</em>]</span> <pre>int luaL_getmetatable (lua_State *L, const char *tname);</pre> <p> Pushes onto the stack the metatable associated with name <code>tname</code> in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>) (<b>nil</b> if there is no metatable associated with that name). Returns the type of the pushed value. <hr><h3><a name="luaL_getsubtable"><code>luaL_getsubtable</code></a></h3><p> <span class="apii">[-0, +1, <em>e</em>]</span> <pre>int luaL_getsubtable (lua_State *L, int idx, const char *fname);</pre> <p> Ensures that the value <code>t[fname]</code>, where <code>t</code> is the value at index <code>idx</code>, is a table, and pushes that table onto the stack. Returns true if it finds a previous table there and false if it creates a new table. <hr><h3><a name="luaL_gsub"><code>luaL_gsub</code></a></h3><p> <span class="apii">[-0, +1, <em>m</em>]</span> <pre>const char *luaL_gsub (lua_State *L, const char *s, const char *p, const char *r);</pre> <p> Creates a copy of string <code>s</code> by replacing any occurrence of the string <code>p</code> with the string <code>r</code>. Pushes the resulting string on the stack and returns it. <hr><h3><a name="luaL_len"><code>luaL_len</code></a></h3><p> <span class="apii">[-0, +0, <em>e</em>]</span> <pre>lua_Integer luaL_len (lua_State *L, int index);</pre> <p> Returns the "length" of the value at the given index as a number; it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>). Raises an error if the result of the operation is not an integer. (This case only can happen through metamethods.) <hr><h3><a name="luaL_loadbuffer"><code>luaL_loadbuffer</code></a></h3><p> <span class="apii">[-0, +1, &ndash;]</span> <pre>int luaL_loadbuffer (lua_State *L, const char *buff, size_t sz, const char *name);</pre> <p> Equivalent to <a href="#luaL_loadbufferx"><code>luaL_loadbufferx</code></a> with <code>mode</code> equal to <code>NULL</code>. <hr><h3><a name="luaL_loadbufferx"><code>luaL_loadbufferx</code></a></h3><p> <span class="apii">[-0, +1, &ndash;]</span> <pre>int luaL_loadbufferx (lua_State *L, const char *buff, size_t sz, const char *name, const char *mode);</pre> <p> Loads a buffer as a Lua chunk. This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the buffer pointed to by <code>buff</code> with size <code>sz</code>. <p> This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>. <code>name</code> is the chunk name, used for debug information and error messages. The string <code>mode</code> works as in function <a href="#lua_load"><code>lua_load</code></a>. <hr><h3><a name="luaL_loadfile"><code>luaL_loadfile</code></a></h3><p> <span class="apii">[-0, +1, <em>m</em>]</span> <pre>int luaL_loadfile (lua_State *L, const char *filename);</pre> <p> Equivalent to <a href="#luaL_loadfilex"><code>luaL_loadfilex</code></a> with <code>mode</code> equal to <code>NULL</code>. <hr><h3><a name="luaL_loadfilex"><code>luaL_loadfilex</code></a></h3><p> <span class="apii">[-0, +1, <em>m</em>]</span> <pre>int luaL_loadfilex (lua_State *L, const char *filename, const char *mode);</pre> <p> Loads a file as a Lua chunk. This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the file named <code>filename</code>. If <code>filename</code> is <code>NULL</code>, then it loads from the standard input. The first line in the file is ignored if it starts with a <code>#</code>. <p> The string <code>mode</code> works as in function <a href="#lua_load"><code>lua_load</code></a>. <p> This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>, but it has an extra error code <a name="pdf-LUA_ERRFILE"><code>LUA_ERRFILE</code></a> for file-related errors (e.g., it cannot open or read the file). <p> As <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk; it does not run it. <hr><h3><a name="luaL_loadstring"><code>luaL_loadstring</code></a></h3><p> <span class="apii">[-0, +1, &ndash;]</span> <pre>int luaL_loadstring (lua_State *L, const char *s);</pre> <p> Loads a string as a Lua chunk. This function uses <a href="#lua_load"><code>lua_load</code></a> to load the chunk in the zero-terminated string <code>s</code>. <p> This function returns the same results as <a href="#lua_load"><code>lua_load</code></a>. <p> Also as <a href="#lua_load"><code>lua_load</code></a>, this function only loads the chunk; it does not run it. <hr><h3><a name="luaL_newlib"><code>luaL_newlib</code></a></h3><p> <span class="apii">[-0, +1, <em>m</em>]</span> <pre>void luaL_newlib (lua_State *L, const luaL_Reg l[]);</pre> <p> Creates a new table and registers there the functions in list <code>l</code>. <p> It is implemented as the following macro: <pre> (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0)) </pre><p> The array <code>l</code> must be the actual array, not a pointer to it. <hr><h3><a name="luaL_newlibtable"><code>luaL_newlibtable</code></a></h3><p> <span class="apii">[-0, +1, <em>m</em>]</span> <pre>void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);</pre> <p> Creates a new table with a size optimized to store all entries in the array <code>l</code> (but does not actually store them). It is intended to be used in conjunction with <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a> (see <a href="#luaL_newlib"><code>luaL_newlib</code></a>). <p> It is implemented as a macro. The array <code>l</code> must be the actual array, not a pointer to it. <hr><h3><a name="luaL_newmetatable"><code>luaL_newmetatable</code></a></h3><p> <span class="apii">[-0, +1, <em>m</em>]</span> <pre>int luaL_newmetatable (lua_State *L, const char *tname);</pre> <p> If the registry already has the key <code>tname</code>, returns 0. Otherwise, creates a new table to be used as a metatable for userdata, adds to this new table the pair <code>__name = tname</code>, adds to the registry the pair <code>[tname] = new table</code>, and returns 1. (The entry <code>__name</code> is used by some error-reporting functions.) <p> In both cases pushes onto the stack the final value associated with <code>tname</code> in the registry. <hr><h3><a name="luaL_newstate"><code>luaL_newstate</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>lua_State *luaL_newstate (void);</pre> <p> Creates a new Lua state. It calls <a href="#lua_newstate"><code>lua_newstate</code></a> with an allocator based on the standard&nbsp;C <code>realloc</code> function and then sets a panic function (see <a href="#4.6">&sect;4.6</a>) that prints an error message to the standard error output in case of fatal errors. <p> Returns the new state, or <code>NULL</code> if there is a memory allocation error. <hr><h3><a name="luaL_openlibs"><code>luaL_openlibs</code></a></h3><p> <span class="apii">[-0, +0, <em>e</em>]</span> <pre>void luaL_openlibs (lua_State *L);</pre> <p> Opens all standard Lua libraries into the given state. <hr><h3><a name="luaL_opt"><code>luaL_opt</code></a></h3><p> <span class="apii">[-0, +0, <em>e</em>]</span> <pre>T luaL_opt (L, func, arg, dflt);</pre> <p> This macro is defined as follows: <pre> (lua_isnoneornil(L,(arg)) ? (dflt) : func(L,(arg))) </pre><p> In words, if the argument <code>arg</code> is nil or absent, the macro results in the default <code>dflt</code>. Otherwise, it results in the result of calling <code>func</code> with the state <code>L</code> and the argument index <code>arg</code> as arguments. Note that it evaluates the expression <code>dflt</code> only if needed. <hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p> <span class="apii">[-0, +0, <em>v</em>]</span> <pre>lua_Integer luaL_optinteger (lua_State *L, int arg, lua_Integer d);</pre> <p> If the function argument <code>arg</code> is an integer (or convertible to an integer), returns this integer. If this argument is absent or is <b>nil</b>, returns <code>d</code>. Otherwise, raises an error. <hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p> <span class="apii">[-0, +0, <em>v</em>]</span> <pre>const char *luaL_optlstring (lua_State *L, int arg, const char *d, size_t *l);</pre> <p> If the function argument <code>arg</code> is a string, returns this string. If this argument is absent or is <b>nil</b>, returns <code>d</code>. Otherwise, raises an error. <p> If <code>l</code> is not <code>NULL</code>, fills the position <code>*l</code> with the result's length. If the result is <code>NULL</code> (only possible when returning <code>d</code> and <code>d == NULL</code>), its length is considered zero. <p> This function uses <a href="#lua_tolstring"><code>lua_tolstring</code></a> to get its result, so all conversions and caveats of that function apply here. <hr><h3><a name="luaL_optnumber"><code>luaL_optnumber</code></a></h3><p> <span class="apii">[-0, +0, <em>v</em>]</span> <pre>lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number d);</pre> <p> If the function argument <code>arg</code> is a number, returns this number. If this argument is absent or is <b>nil</b>, returns <code>d</code>. Otherwise, raises an error. <hr><h3><a name="luaL_optstring"><code>luaL_optstring</code></a></h3><p> <span class="apii">[-0, +0, <em>v</em>]</span> <pre>const char *luaL_optstring (lua_State *L, int arg, const char *d);</pre> <p> If the function argument <code>arg</code> is a string, returns this string. If this argument is absent or is <b>nil</b>, returns <code>d</code>. Otherwise, raises an error. <hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p> <span class="apii">[-?, +?, <em>m</em>]</span> <pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre> <p> Equivalent to <a href="#luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a> with the predefined size <a name="pdf-LUAL_BUFFERSIZE"><code>LUAL_BUFFERSIZE</code></a>. <hr><h3><a name="luaL_prepbuffsize"><code>luaL_prepbuffsize</code></a></h3><p> <span class="apii">[-?, +?, <em>m</em>]</span> <pre>char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);</pre> <p> Returns an address to a space of size <code>sz</code> where you can copy a string to be added to buffer <code>B</code> (see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>). After copying the string into this space you must call <a href="#luaL_addsize"><code>luaL_addsize</code></a> with the size of the string to actually add it to the buffer. <hr><h3><a name="luaL_pushresult"><code>luaL_pushresult</code></a></h3><p> <span class="apii">[-?, +1, <em>m</em>]</span> <pre>void luaL_pushresult (luaL_Buffer *B);</pre> <p> Finishes the use of buffer <code>B</code> leaving the final string on the top of the stack. <hr><h3><a name="luaL_pushresultsize"><code>luaL_pushresultsize</code></a></h3><p> <span class="apii">[-?, +1, <em>m</em>]</span> <pre>void luaL_pushresultsize (luaL_Buffer *B, size_t sz);</pre> <p> Equivalent to the sequence <a href="#luaL_addsize"><code>luaL_addsize</code></a>, <a href="#luaL_pushresult"><code>luaL_pushresult</code></a>. <hr><h3><a name="luaL_ref"><code>luaL_ref</code></a></h3><p> <span class="apii">[-1, +0, <em>m</em>]</span> <pre>int luaL_ref (lua_State *L, int t);</pre> <p> Creates and returns a <em>reference</em>, in the table at index <code>t</code>, for the object at the top of the stack (and pops the object). <p> A reference is a unique integer key. As long as you do not manually add integer keys into table <code>t</code>, <a href="#luaL_ref"><code>luaL_ref</code></a> ensures the uniqueness of the key it returns. You can retrieve an object referred by reference <code>r</code> by calling <code>lua_rawgeti(L, t, r)</code>. Function <a href="#luaL_unref"><code>luaL_unref</code></a> frees a reference and its associated object. <p> If the object at the top of the stack is <b>nil</b>, <a href="#luaL_ref"><code>luaL_ref</code></a> returns the constant <a name="pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>. The constant <a name="pdf-LUA_NOREF"><code>LUA_NOREF</code></a> is guaranteed to be different from any reference returned by <a href="#luaL_ref"><code>luaL_ref</code></a>. <hr><h3><a name="luaL_Reg"><code>luaL_Reg</code></a></h3> <pre>typedef struct luaL_Reg { const char *name; lua_CFunction func; } luaL_Reg;</pre> <p> Type for arrays of functions to be registered by <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>. <code>name</code> is the function name and <code>func</code> is a pointer to the function. Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with a sentinel entry in which both <code>name</code> and <code>func</code> are <code>NULL</code>. <hr><h3><a name="luaL_requiref"><code>luaL_requiref</code></a></h3><p> <span class="apii">[-0, +1, <em>e</em>]</span> <pre>void luaL_requiref (lua_State *L, const char *modname, lua_CFunction openf, int glb);</pre> <p> If <code>modname</code> is not already present in <a href="#pdf-package.loaded"><code>package.loaded</code></a>, calls function <code>openf</code> with string <code>modname</code> as an argument and sets the call result in <code>package.loaded[modname]</code>, as if that function has been called through <a href="#pdf-require"><code>require</code></a>. <p> If <code>glb</code> is true, also stores the module into global <code>modname</code>. <p> Leaves a copy of the module on the stack. <hr><h3><a name="luaL_setfuncs"><code>luaL_setfuncs</code></a></h3><p> <span class="apii">[-nup, +0, <em>m</em>]</span> <pre>void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);</pre> <p> Registers all functions in the array <code>l</code> (see <a href="#luaL_Reg"><code>luaL_Reg</code></a>) into the table on the top of the stack (below optional upvalues, see next). <p> When <code>nup</code> is not zero, all functions are created sharing <code>nup</code> upvalues, which must be previously pushed on the stack on top of the library table. These values are popped from the stack after the registration. <hr><h3><a name="luaL_setmetatable"><code>luaL_setmetatable</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>void luaL_setmetatable (lua_State *L, const char *tname);</pre> <p> Sets the metatable of the object at the top of the stack as the metatable associated with name <code>tname</code> in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>). <hr><h3><a name="luaL_Stream"><code>luaL_Stream</code></a></h3> <pre>typedef struct luaL_Stream { FILE *f; lua_CFunction closef; } luaL_Stream;</pre> <p> The standard representation for file handles, which is used by the standard I/O library. <p> A file handle is implemented as a full userdata, with a metatable called <code>LUA_FILEHANDLE</code> (where <code>LUA_FILEHANDLE</code> is a macro with the actual metatable's name). The metatable is created by the I/O library (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>). <p> This userdata must start with the structure <code>luaL_Stream</code>; it can contain other data after this initial structure. Field <code>f</code> points to the corresponding C stream (or it can be <code>NULL</code> to indicate an incompletely created handle). Field <code>closef</code> points to a Lua function that will be called to close the stream when the handle is closed or collected; this function receives the file handle as its sole argument and must return either <b>true</b> (in case of success) or <b>nil</b> plus an error message (in case of error). Once Lua calls this field, it changes the field value to <code>NULL</code> to signal that the handle is closed. <hr><h3><a name="luaL_testudata"><code>luaL_testudata</code></a></h3><p> <span class="apii">[-0, +0, <em>m</em>]</span> <pre>void *luaL_testudata (lua_State *L, int arg, const char *tname);</pre> <p> This function works like <a href="#luaL_checkudata"><code>luaL_checkudata</code></a>, except that, when the test fails, it returns <code>NULL</code> instead of raising an error. <hr><h3><a name="luaL_tolstring"><code>luaL_tolstring</code></a></h3><p> <span class="apii">[-0, +1, <em>e</em>]</span> <pre>const char *luaL_tolstring (lua_State *L, int idx, size_t *len);</pre> <p> Converts any Lua value at the given index to a C&nbsp;string in a reasonable format. The resulting string is pushed onto the stack and also returned by the function. If <code>len</code> is not <code>NULL</code>, the function also sets <code>*len</code> with the string length. <p> If the value has a metatable with a <code>__tostring</code> field, then <code>luaL_tolstring</code> calls the corresponding metamethod with the value as argument, and uses the result of the call as its result. <hr><h3><a name="luaL_traceback"><code>luaL_traceback</code></a></h3><p> <span class="apii">[-0, +1, <em>m</em>]</span> <pre>void luaL_traceback (lua_State *L, lua_State *L1, const char *msg, int level);</pre> <p> Creates and pushes a traceback of the stack <code>L1</code>. If <code>msg</code> is not <code>NULL</code> it is appended at the beginning of the traceback. The <code>level</code> parameter tells at which level to start the traceback. <hr><h3><a name="luaL_typename"><code>luaL_typename</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>const char *luaL_typename (lua_State *L, int index);</pre> <p> Returns the name of the type of the value at the given index. <hr><h3><a name="luaL_unref"><code>luaL_unref</code></a></h3><p> <span class="apii">[-0, +0, &ndash;]</span> <pre>void luaL_unref (lua_State *L, int t, int ref);</pre> <p> Releases reference <code>ref</code> from the table at index <code>t</code> (see <a href="#luaL_ref"><code>luaL_ref</code></a>). The entry is removed from the table, so that the referred object can be collected. The reference <code>ref</code> is also freed to be used again. <p> If <code>ref</code> is <a href="#pdf-LUA_NOREF"><code>LUA_NOREF</code></a> or <a href="#pdf-LUA_REFNIL"><code>LUA_REFNIL</code></a>, <a href="#luaL_unref"><code>luaL_unref</code></a> does nothing. <hr><h3><a name="luaL_where"><code>luaL_where</code></a></h3><p> <span class="apii">[-0, +1, <em>m</em>]</span> <pre>void luaL_where (lua_State *L, int lvl);</pre> <p> Pushes onto the stack a string identifying the current position of the control at level <code>lvl</code> in the call stack. Typically this string has the following format: <pre> <em>chunkname</em>:<em>currentline</em>: </pre><p> Level&nbsp;0 is the running function, level&nbsp;1 is the function that called the running function, etc. <p> This function is used to build a prefix for error messages. <h1>6 &ndash; <a name="6">Standard Libraries</a></h1> <p> The standard Lua libraries provide useful functions that are implemented directly through the C&nbsp;API. Some of these functions provide essential services to the language (e.g., <a href="#pdf-type"><code>type</code></a> and <a href="#pdf-getmetatable"><code>getmetatable</code></a>); others provide access to "outside" services (e.g., I/O); and others could be implemented in Lua itself, but are quite useful or have critical performance requirements that deserve an implementation in C (e.g., <a href="#pdf-table.sort"><code>table.sort</code></a>). <p> All libraries are implemented through the official C&nbsp;API and are provided as separate C&nbsp;modules. Currently, Lua has the following standard libraries: <ul> <li>basic library (<a href="#6.1">&sect;6.1</a>);</li> <li>coroutine library (<a href="#6.2">&sect;6.2</a>);</li> <li>package library (<a href="#6.3">&sect;6.3</a>);</li> <li>string manipulation (<a href="#6.4">&sect;6.4</a>);</li> <li>basic UTF-8 support (<a href="#6.5">&sect;6.5</a>);</li> <li>table manipulation (<a href="#6.6">&sect;6.6</a>);</li> <li>mathematical functions (<a href="#6.7">&sect;6.7</a>) (sin, log, etc.);</li> <li>input and output (<a href="#6.8">&sect;6.8</a>);</li> <li>operating system facilities (<a href="#6.9">&sect;6.9</a>);</li> <li>debug facilities (<a href="#6.10">&sect;6.10</a>).</li> </ul><p> Except for the basic and the package libraries, each library provides all its functions as fields of a global table or as methods of its objects. <p> To have access to these libraries, the C&nbsp;host program should call the <a href="#luaL_openlibs"><code>luaL_openlibs</code></a> function, which opens all standard libraries. Alternatively, the host program can open them individually by using <a href="#luaL_requiref"><code>luaL_requiref</code></a> to call <a name="pdf-luaopen_base"><code>luaopen_base</code></a> (for the basic library), <a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library), <a name="pdf-luaopen_coroutine"><code>luaopen_coroutine</code></a> (for the coroutine library), <a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library), <a name="pdf-luaopen_utf8"><code>luaopen_utf8</code></a> (for the UTF8 library), <a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library), <a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library), <a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library), <a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the operating system library), and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library). These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>. <h2>6.1 &ndash; <a name="6.1">Basic Functions</a></h2> <p> The basic library provides core functions to Lua. If you do not include this library in your application, you should check carefully whether you need to provide implementations for some of its facilities. <p> <hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3> <p> Calls <a href="#pdf-error"><code>error</code></a> if the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>); otherwise, returns all its arguments. In case of error, <code>message</code> is the error object; when absent, it defaults to "<code>assertion failed!</code>" <p> <hr><h3><a name="pdf-collectgarbage"><code>collectgarbage ([opt [, arg]])</code></a></h3> <p> This function is a generic interface to the garbage collector. It performs different functions according to its first argument, <code>opt</code>: <ul> <li><b>"<code>collect</code>": </b> performs a full garbage-collection cycle. This is the default option. </li> <li><b>"<code>stop</code>": </b> stops automatic execution of the garbage collector. The collector will run only when explicitly invoked, until a call to restart it. </li> <li><b>"<code>restart</code>": </b> restarts automatic execution of the garbage collector. </li> <li><b>"<code>count</code>": </b> returns the total memory in use by Lua in Kbytes. The value has a fractional part, so that it multiplied by 1024 gives the exact number of bytes in use by Lua (except for overflows). </li> <li><b>"<code>step</code>": </b> performs a garbage-collection step. The step "size" is controlled by <code>arg</code>. With a zero value, the collector will perform one basic (indivisible) step. For non-zero values, the collector will perform as if that amount of memory (in KBytes) had been allocated by Lua. Returns <b>true</b> if the step finished a collection cycle. </li> <li><b>"<code>setpause</code>": </b> sets <code>arg</code> as the new value for the <em>pause</em> of the collector (see <a href="#2.5">&sect;2.5</a>). Returns the previous value for <em>pause</em>. </li> <li><b>"<code>setstepmul</code>": </b> sets <code>arg</code> as the new value for the <em>step multiplier</em> of the collector (see <a href="#2.5">&sect;2.5</a>). Returns the previous value for <em>step</em>. </li> <li><b>"<code>isrunning</code>": </b> returns a boolean that tells whether the collector is running (i.e., not stopped). </li> </ul> <p> <hr><h3><a name="pdf-dofile"><code>dofile ([filename])</code></a></h3> Opens the named file and executes its contents as a Lua chunk. When called without arguments, <code>dofile</code> executes the contents of the standard input (<code>stdin</code>). Returns all values returned by the chunk. In case of errors, <code>dofile</code> propagates the error to its caller (that is, <code>dofile</code> does not run in protected mode). <p> <hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3> Terminates the last protected function called and returns <code>message</code> as the error object. Function <code>error</code> never returns. <p> Usually, <code>error</code> adds some information about the error position at the beginning of the message, if the message is a string. The <code>level</code> argument specifies how to get the error position. With level&nbsp;1 (the default), the error position is where the <code>error</code> function was called. Level&nbsp;2 points the error to where the function that called <code>error</code> was called; and so on. Passing a level&nbsp;0 avoids the addition of error position information to the message. <p> <hr><h3><a name="pdf-_G"><code>_G</code></a></h3> A global variable (not a function) that holds the global environment (see <a href="#2.2">&sect;2.2</a>). Lua itself does not use this variable; changing its value does not affect any environment, nor vice versa. <p> <hr><h3><a name="pdf-getmetatable"><code>getmetatable (object)</code></a></h3> <p> If <code>object</code> does not have a metatable, returns <b>nil</b>. Otherwise, if the object's metatable has a <code>__metatable</code> field, returns the associated value. Otherwise, returns the metatable of the given object. <p> <hr><h3><a name="pdf-ipairs"><code>ipairs (t)</code></a></h3> <p> Returns three values (an iterator function, the table <code>t</code>, and 0) so that the construction <pre> for i,v in ipairs(t) do <em>body</em> end </pre><p> will iterate over the key&ndash;value pairs (<code>1,t[1]</code>), (<code>2,t[2]</code>), ..., up to the first nil value. <p> <hr><h3><a name="pdf-load"><code>load (chunk [, chunkname [, mode [, env]]])</code></a></h3> <p> Loads a chunk. <p> If <code>chunk</code> is a string, the chunk is this string. If <code>chunk</code> is a function, <code>load</code> calls it repeatedly to get the chunk pieces. Each call to <code>chunk</code> must return a string that concatenates with previous results. A return of an empty string, <b>nil</b>, or no value signals the end of the chunk. <p> If there are no syntactic errors, returns the compiled chunk as a function; otherwise, returns <b>nil</b> plus the error message. <p> If the resulting function has upvalues, the first upvalue is set to the value of <code>env</code>, if that parameter is given, or to the value of the global environment. Other upvalues are initialized with <b>nil</b>. (When you load a main chunk, the resulting function will always have exactly one upvalue, the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>). However, when you load a binary chunk created from a function (see <a href="#pdf-string.dump"><code>string.dump</code></a>), the resulting function can have an arbitrary number of upvalues.) All upvalues are fresh, that is, they are not shared with any other function. <p> <code>chunkname</code> is used as the name of the chunk for error messages and debug information (see <a href="#4.9">&sect;4.9</a>). When absent, it defaults to <code>chunk</code>, if <code>chunk</code> is a string, or to "<code>=(load)</code>" otherwise. <p> The string <code>mode</code> controls whether the chunk can be text or binary (that is, a precompiled chunk). It may be the string "<code>b</code>" (only binary chunks), "<code>t</code>" (only text chunks), or "<code>bt</code>" (both binary and text). The default is "<code>bt</code>". <p> Lua does not check the consistency of binary chunks. Maliciously crafted binary chunks can crash the interpreter. <p> <hr><h3><a name="pdf-loadfile"><code>loadfile ([filename [, mode [, env]]])</code></a></h3> <p> Similar to <a href="#pdf-load"><code>load</code></a>, but gets the chunk from file <code>filename</code> or from the standard input, if no file name is given. <p> <hr><h3><a name="pdf-next"><code>next (table [, index])</code></a></h3> <p> Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. <code>next</code> returns the next index of the table and its associated value. When called with <b>nil</b> as its second argument, <code>next</code> returns an initial index and its associated value. When called with the last index, or with <b>nil</b> in an empty table, <code>next</code> returns <b>nil</b>. If the second argument is absent, then it is interpreted as <b>nil</b>. In particular, you can use <code>next(t)</code> to check whether a table is empty. <p> The order in which the indices are enumerated is not specified, <em>even for numeric indices</em>. (To traverse a table in numerical order, use a numerical <b>for</b>.) <p> The behavior of <code>next</code> is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields. <p> <hr><h3><a name="pdf-pairs"><code>pairs (t)</code></a></h3> <p> If <code>t</code> has a metamethod <code>__pairs</code>, calls it with <code>t</code> as argument and returns the first three results from the call. <p> Otherwise, returns three values: the <a href="#pdf-next"><code>next</code></a> function, the table <code>t</code>, and <b>nil</b>, so that the construction <pre> for k,v in pairs(t) do <em>body</em> end </pre><p> will iterate over all key&ndash;value pairs of table <code>t</code>. <p> See function <a href="#pdf-next"><code>next</code></a> for the caveats of modifying the table during its traversal. <p> <hr><h3><a name="pdf-pcall"><code>pcall (f [, arg1, &middot;&middot;&middot;])</code></a></h3> <p> Calls function <code>f</code> with the given arguments in <em>protected mode</em>. This means that any error inside&nbsp;<code>f</code> is not propagated; instead, <code>pcall</code> catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, <code>pcall</code> also returns all results from the call, after this first result. In case of any error, <code>pcall</code> returns <b>false</b> plus the error message. <p> <hr><h3><a name="pdf-print"><code>print (&middot;&middot;&middot;)</code></a></h3> Receives any number of arguments and prints their values to <code>stdout</code>, using the <a href="#pdf-tostring"><code>tostring</code></a> function to convert each argument to a string. <code>print</code> is not intended for formatted output, but only as a quick way to show a value, for instance for debugging. For complete control over the output, use <a href="#pdf-string.format"><code>string.format</code></a> and <a href="#pdf-io.write"><code>io.write</code></a>. <p> <hr><h3><a name="pdf-rawequal"><code>rawequal (v1, v2)</code></a></h3> Checks whether <code>v1</code> is equal to <code>v2</code>, without invoking the <code>__eq</code> metamethod. Returns a boolean. <p> <hr><h3><a name="pdf-rawget"><code>rawget (table, index)</code></a></h3> Gets the real value of <code>table[index]</code>, without invoking the <code>__index</code> metamethod. <code>table</code> must be a table; <code>index</code> may be any value. <p> <hr><h3><a name="pdf-rawlen"><code>rawlen (v)</code></a></h3> Returns the length of the object <code>v</code>, which must be a table or a string, without invoking the <code>__len</code> metamethod. Returns an integer. <p> <hr><h3><a name="pdf-rawset"><code>rawset (table, index, value)</code></a></h3> Sets the real value of <code>table[index]</code> to <code>value</code>, without invoking the <code>__newindex</code> metamethod. <code>table</code> must be a table, <code>index</code> any value different from <b>nil</b> and NaN, and <code>value</code> any Lua value. <p> This function returns <code>table</code>. <p> <hr><h3><a name="pdf-select"><code>select (index, &middot;&middot;&middot;)</code></a></h3> <p> If <code>index</code> is a number, returns all arguments after argument number <code>index</code>; a negative number indexes from the end (-1 is the last argument). Otherwise, <code>index</code> must be the string <code>"#"</code>, and <code>select</code> returns the total number of extra arguments it received. <p> <hr><h3><a name="pdf-setmetatable"><code>setmetatable (table, metatable)</code></a></h3> <p> Sets the metatable for the given table. (To change the metatable of other types from Lua code, you must use the debug library (<a href="#6.10">&sect;6.10</a>).) If <code>metatable</code> is <b>nil</b>, removes the metatable of the given table. If the original metatable has a <code>__metatable</code> field, raises an error. <p> This function returns <code>table</code>. <p> <hr><h3><a name="pdf-tonumber"><code>tonumber (e [, base])</code></a></h3> <p> When called with no <code>base</code>, <code>tonumber</code> tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then <code>tonumber</code> returns this number; otherwise, it returns <b>nil</b>. <p> The conversion of strings can result in integers or floats, according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>). (The string may have leading and trailing spaces and a sign.) <p> When called with <code>base</code>, then <code>e</code> must be a string to be interpreted as an integer numeral in that base. The base may be any integer between 2 and 36, inclusive. In bases above&nbsp;10, the letter '<code>A</code>' (in either upper or lower case) represents&nbsp;10, '<code>B</code>' represents&nbsp;11, and so forth, with '<code>Z</code>' representing 35. If the string <code>e</code> is not a valid numeral in the given base, the function returns <b>nil</b>. <p> <hr><h3><a name="pdf-tostring"><code>tostring (v)</code></a></h3> Receives a value of any type and converts it to a string in a human-readable format. (For complete control of how numbers are converted, use <a href="#pdf-string.format"><code>string.format</code></a>.) <p> If the metatable of <code>v</code> has a <code>__tostring</code> field, then <code>tostring</code> calls the corresponding value with <code>v</code> as argument, and uses the result of the call as its result. <p> <hr><h3><a name="pdf-type"><code>type (v)</code></a></h3> Returns the type of its only argument, coded as a string. The possible results of this function are "<code>nil</code>" (a string, not the value <b>nil</b>), "<code>number</code>", "<code>string</code>", "<code>boolean</code>", "<code>table</code>", "<code>function</code>", "<code>thread</code>", and "<code>userdata</code>". <p> <hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3> <p> A global variable (not a function) that holds a string containing the running Lua version. The current value of this variable is "<code>Lua 5.3</code>". <p> <hr><h3><a name="pdf-xpcall"><code>xpcall (f, msgh [, arg1, &middot;&middot;&middot;])</code></a></h3> <p> This function is similar to <a href="#pdf-pcall"><code>pcall</code></a>, except that it sets a new message handler <code>msgh</code>. <h2>6.2 &ndash; <a name="6.2">Coroutine Manipulation</a></h2> <p> This library comprises the operations to manipulate coroutines, which come inside the table <a name="pdf-coroutine"><code>coroutine</code></a>. See <a href="#2.6">&sect;2.6</a> for a general description of coroutines. <p> <hr><h3><a name="pdf-coroutine.create"><code>coroutine.create (f)</code></a></h3> <p> Creates a new coroutine, with body <code>f</code>. <code>f</code> must be a function. Returns this new coroutine, an object with type <code>"thread"</code>. <p> <hr><h3><a name="pdf-coroutine.isyieldable"><code>coroutine.isyieldable ()</code></a></h3> <p> Returns true when the running coroutine can yield. <p> A running coroutine is yieldable if it is not the main thread and it is not inside a non-yieldable C&nbsp;function. <p> <hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, &middot;&middot;&middot;])</code></a></h3> <p> Starts or continues the execution of coroutine <code>co</code>. The first time you resume a coroutine, it starts running its body. The values <code>val1</code>, ... are passed as the arguments to the body function. If the coroutine has yielded, <code>resume</code> restarts it; the values <code>val1</code>, ... are passed as the results from the yield. <p> If the coroutine runs without any errors, <code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code> (when the coroutine yields) or any values returned by the body function (when the coroutine terminates). If there is any error, <code>resume</code> returns <b>false</b> plus the error message. <p> <hr><h3><a name="pdf-coroutine.running"><code>coroutine.running ()</code></a></h3> <p> Returns the running coroutine plus a boolean, true when the running coroutine is the main one. <p> <hr><h3><a name="pdf-coroutine.status"><code>coroutine.status (co)</code></a></h3> <p> Returns the status of coroutine <code>co</code>, as a string: <code>"running"</code>, if the coroutine is running (that is, it called <code>status</code>); <code>"suspended"</code>, if the coroutine is suspended in a call to <code>yield</code>, or if it has not started running yet; <code>"normal"</code> if the coroutine is active but not running (that is, it has resumed another coroutine); and <code>"dead"</code> if the coroutine has finished its body function, or if it has stopped with an error. <p> <hr><h3><a name="pdf-coroutine.wrap"><code>coroutine.wrap (f)</code></a></h3> <p> Creates a new coroutine, with body <code>f</code>. <code>f</code> must be a function. Returns a function that resumes the coroutine each time it is called. Any arguments passed to the function behave as the extra arguments to <code>resume</code>. Returns the same values returned by <code>resume</code>, except the first boolean. In case of error, propagates the error. <p> <hr><h3><a name="pdf-coroutine.yield"><code>coroutine.yield (&middot;&middot;&middot;)</code></a></h3> <p> Suspends the execution of the calling coroutine. Any arguments to <code>yield</code> are passed as extra results to <code>resume</code>. <h2>6.3 &ndash; <a name="6.3">Modules</a></h2> <p> The package library provides basic facilities for loading modules in Lua. It exports one function directly in the global environment: <a href="#pdf-require"><code>require</code></a>. Everything else is exported in a table <a name="pdf-package"><code>package</code></a>. <p> <hr><h3><a name="pdf-require"><code>require (modname)</code></a></h3> <p> Loads the given module. The function starts by looking into the <a href="#pdf-package.loaded"><code>package.loaded</code></a> table to determine whether <code>modname</code> is already loaded. If it is, then <code>require</code> returns the value stored at <code>package.loaded[modname]</code>. Otherwise, it tries to find a <em>loader</em> for the module. <p> To find a loader, <code>require</code> is guided by the <a href="#pdf-package.searchers"><code>package.searchers</code></a> sequence. By changing this sequence, we can change how <code>require</code> looks for a module. The following explanation is based on the default configuration for <a href="#pdf-package.searchers"><code>package.searchers</code></a>. <p> First <code>require</code> queries <code>package.preload[modname]</code>. If it has a value, this value (which must be a function) is the loader. Otherwise <code>require</code> searches for a Lua loader using the path stored in <a href="#pdf-package.path"><code>package.path</code></a>. If that also fails, it searches for a C&nbsp;loader using the path stored in <a href="#pdf-package.cpath"><code>package.cpath</code></a>. If that also fails, it tries an <em>all-in-one</em> loader (see <a href="#pdf-package.searchers"><code>package.searchers</code></a>). <p> Once a loader is found, <code>require</code> calls the loader with two arguments: <code>modname</code> and an extra value dependent on how it got the loader. (If the loader came from a file, this extra value is the file name.) If the loader returns any non-nil value, <code>require</code> assigns the returned value to <code>package.loaded[modname]</code>. If the loader does not return a non-nil value and has not assigned any value to <code>package.loaded[modname]</code>, then <code>require</code> assigns <b>true</b> to this entry. In any case, <code>require</code> returns the final value of <code>package.loaded[modname]</code>. <p> If there is any error loading or running the module, or if it cannot find any loader for the module, then <code>require</code> raises an error. <p> <hr><h3><a name="pdf-package.config"><code>package.config</code></a></h3> <p> A string describing some compile-time configurations for packages. This string is a sequence of lines: <ul> <li>The first line is the directory separator string. Default is '<code>\</code>' for Windows and '<code>/</code>' for all other systems.</li> <li>The second line is the character that separates templates in a path. Default is '<code>;</code>'.</li> <li>The third line is the string that marks the substitution points in a template. Default is '<code>?</code>'.</li> <li>The fourth line is a string that, in a path in Windows, is replaced by the executable's directory. Default is '<code>!</code>'.</li> <li>The fifth line is a mark to ignore all text after it when building the <code>luaopen_</code> function name. Default is '<code>-</code>'.</li> </ul> <p> <hr><h3><a name="pdf-package.cpath"><code>package.cpath</code></a></h3> <p> The path used by <a href="#pdf-require"><code>require</code></a> to search for a C&nbsp;loader. <p> Lua initializes the C&nbsp;path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>, using the environment variable <a name="pdf-LUA_CPATH_5_3"><code>LUA_CPATH_5_3</code></a>, or the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>, or a default path defined in <code>luaconf.h</code>. <p> <hr><h3><a name="pdf-package.loaded"><code>package.loaded</code></a></h3> <p> A table used by <a href="#pdf-require"><code>require</code></a> to control which modules are already loaded. When you require a module <code>modname</code> and <code>package.loaded[modname]</code> is not false, <a href="#pdf-require"><code>require</code></a> simply returns the value stored there. <p> This variable is only a reference to the real table; assignments to this variable do not change the table used by <a href="#pdf-require"><code>require</code></a>. <p> <hr><h3><a name="pdf-package.loadlib"><code>package.loadlib (libname, funcname)</code></a></h3> <p> Dynamically links the host program with the C&nbsp;library <code>libname</code>. <p> If <code>funcname</code> is "<code>*</code>", then it only links with the library, making the symbols exported by the library available to other dynamically linked libraries. Otherwise, it looks for a function <code>funcname</code> inside the library and returns this function as a C&nbsp;function. So, <code>funcname</code> must follow the <a href="#lua_CFunction"><code>lua_CFunction</code></a> prototype (see <a href="#lua_CFunction"><code>lua_CFunction</code></a>). <p> This is a low-level function. It completely bypasses the package and module system. Unlike <a href="#pdf-require"><code>require</code></a>, it does not perform any path searching and does not automatically adds extensions. <code>libname</code> must be the complete file name of the C&nbsp;library, including if necessary a path and an extension. <code>funcname</code> must be the exact name exported by the C&nbsp;library (which may depend on the C&nbsp;compiler and linker used). <p> This function is not supported by Standard&nbsp;C. As such, it is only available on some platforms (Windows, Linux, Mac OS X, Solaris, BSD, plus other Unix systems that support the <code>dlfcn</code> standard). <p> <hr><h3><a name="pdf-package.path"><code>package.path</code></a></h3> <p> The path used by <a href="#pdf-require"><code>require</code></a> to search for a Lua loader. <p> At start-up, Lua initializes this variable with the value of the environment variable <a name="pdf-LUA_PATH_5_3"><code>LUA_PATH_5_3</code></a> or the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or with a default path defined in <code>luaconf.h</code>, if those environment variables are not defined. Any "<code>;;</code>" in the value of the environment variable is replaced by the default path. <p> <hr><h3><a name="pdf-package.preload"><code>package.preload</code></a></h3> <p> A table to store loaders for specific modules (see <a href="#pdf-require"><code>require</code></a>). <p> This variable is only a reference to the real table; assignments to this variable do not change the table used by <a href="#pdf-require"><code>require</code></a>. <p> <hr><h3><a name="pdf-package.searchers"><code>package.searchers</code></a></h3> <p> A table used by <a href="#pdf-require"><code>require</code></a> to control how to load modules. <p> Each entry in this table is a <em>searcher function</em>. When looking for a module, <a href="#pdf-require"><code>require</code></a> calls each of these searchers in ascending order, with the module name (the argument given to <a href="#pdf-require"><code>require</code></a>) as its sole parameter. The function can return another function (the module <em>loader</em>) plus an extra value that will be passed to that loader, or a string explaining why it did not find that module (or <b>nil</b> if it has nothing to say). <p> Lua initializes this table with four searcher functions. <p> The first searcher simply looks for a loader in the <a href="#pdf-package.preload"><code>package.preload</code></a> table. <p> The second searcher looks for a loader as a Lua library, using the path stored at <a href="#pdf-package.path"><code>package.path</code></a>. The search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>. <p> The third searcher looks for a loader as a C&nbsp;library, using the path given by the variable <a href="#pdf-package.cpath"><code>package.cpath</code></a>. Again, the search is done as described in function <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>. For instance, if the C&nbsp;path is the string <pre> "./?.so;./?.dll;/usr/local/?/init.so" </pre><p> the searcher for module <code>foo</code> will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>, and <code>/usr/local/foo/init.so</code>, in that order. Once it finds a C&nbsp;library, this searcher first uses a dynamic link facility to link the application with the library. Then it tries to find a C&nbsp;function inside the library to be used as the loader. The name of this C&nbsp;function is the string "<code>luaopen_</code>" concatenated with a copy of the module name where each dot is replaced by an underscore. Moreover, if the module name has a hyphen, its suffix after (and including) the first hyphen is removed. For instance, if the module name is <code>a.b.c-v2.1</code>, the function name will be <code>luaopen_a_b_c</code>. <p> The fourth searcher tries an <em>all-in-one loader</em>. It searches the C&nbsp;path for a library for the root name of the given module. For instance, when requiring <code>a.b.c</code>, it will search for a C&nbsp;library for <code>a</code>. If found, it looks into it for an open function for the submodule; in our example, that would be <code>luaopen_a_b_c</code>. With this facility, a package can pack several C&nbsp;submodules into one single library, with each submodule keeping its original open function. <p> All searchers except the first one (preload) return as the extra value the file name where the module was found, as returned by <a href="#pdf-package.searchpath"><code>package.searchpath</code></a>. The first searcher returns no extra value. <p> <hr><h3><a name="pdf-package.searchpath"><code>package.searchpath (name, path [, sep [, rep]])</code></a></h3> <p> Searches for the given <code>name</code> in the given <code>path</code>. <p> A path is a string containing a sequence of <em>templates</em> separated by semicolons. For each template, the function replaces each interrogation mark (if any) in the template with a copy of <code>name</code> wherein all occurrences of <code>sep</code> (a dot, by default) were replaced by <code>rep</code> (the system's directory separator, by default), and then tries to open the resulting file name. <p> For instance, if the path is the string <pre> "./?.lua;./?.lc;/usr/local/?/init.lua" </pre><p> the search for the name <code>foo.a</code> will try to open the files <code>./foo/a.lua</code>, <code>./foo/a.lc</code>, and <code>/usr/local/foo/a/init.lua</code>, in that order. <p> Returns the resulting name of the first file that it can open in read mode (after closing the file), or <b>nil</b> plus an error message if none succeeds. (This error message lists all file names it tried to open.) <h2>6.4 &ndash; <a name="6.4">String Manipulation</a></h2> <p> This library provides generic functions for string manipulation, such as finding and extracting substrings, and pattern matching. When indexing a string in Lua, the first character is at position&nbsp;1 (not at&nbsp;0, as in C). Indices are allowed to be negative and are interpreted as indexing backwards, from the end of the string. Thus, the last character is at position -1, and so on. <p> The string library provides all its functions inside the table <a name="pdf-string"><code>string</code></a>. It also sets a metatable for strings where the <code>__index</code> field points to the <code>string</code> table. Therefore, you can use the string functions in object-oriented style. For instance, <code>string.byte(s,i)</code> can be written as <code>s:byte(i)</code>. <p> The string library assumes one-byte character encodings. <p> <hr><h3><a name="pdf-string.byte"><code>string.byte (s [, i [, j]])</code></a></h3> Returns the internal numeric codes of the characters <code>s[i]</code>, <code>s[i+1]</code>, ..., <code>s[j]</code>. The default value for <code>i</code> is&nbsp;1; the default value for <code>j</code> is&nbsp;<code>i</code>. These indices are corrected following the same rules of function <a href="#pdf-string.sub"><code>string.sub</code></a>. <p> Numeric codes are not necessarily portable across platforms. <p> <hr><h3><a name="pdf-string.char"><code>string.char (&middot;&middot;&middot;)</code></a></h3> Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numeric code equal to its corresponding argument. <p> Numeric codes are not necessarily portable across platforms. <p> <hr><h3><a name="pdf-string.dump"><code>string.dump (function [, strip])</code></a></h3> <p> Returns a string containing a binary representation (a <em>binary chunk</em>) of the given function, so that a later <a href="#pdf-load"><code>load</code></a> on this string returns a copy of the function (but with new upvalues). If <code>strip</code> is a true value, the binary representation may not include all debug information about the function, to save space. <p> Functions with upvalues have only their number of upvalues saved. When (re)loaded, those upvalues receive fresh instances containing <b>nil</b>. (You can use the debug library to serialize and reload the upvalues of a function in a way adequate to your needs.) <p> <hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3> <p> Looks for the first match of <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>. If it finds a match, then <code>find</code> returns the indices of&nbsp;<code>s</code> where this occurrence starts and ends; otherwise, it returns <b>nil</b>. A third, optional numeric argument <code>init</code> specifies where to start the search; its default value is&nbsp;1 and can be negative. A value of <b>true</b> as a fourth, optional argument <code>plain</code> turns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters in <code>pattern</code> being considered magic. Note that if <code>plain</code> is given, then <code>init</code> must be given as well. <p> If the pattern has captures, then in a successful match the captured values are also returned, after the two indices. <p> <hr><h3><a name="pdf-string.format"><code>string.format (formatstring, &middot;&middot;&middot;)</code></a></h3> <p> Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). The format string follows the same rules as the ISO&nbsp;C function <code>sprintf</code>. The only differences are that the options/modifiers <code>*</code>, <code>h</code>, <code>L</code>, <code>l</code>, <code>n</code>, and <code>p</code> are not supported and that there is an extra option, <code>q</code>. <p> The <code>q</code> option formats a string between double quotes, using escape sequences when necessary to ensure that it can safely be read back by the Lua interpreter. For instance, the call <pre> string.format('%q', 'a string with "quotes" and \n new line') </pre><p> may produce the string: <pre> "a string with \"quotes\" and \ new line" </pre> <p> Options <code>A</code>, <code>a</code>, <code>E</code>, <code>e</code>, <code>f</code>, <code>G</code>, and <code>g</code> all expect a number as argument. Options <code>c</code>, <code>d</code>, <code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code> expect an integer. When Lua is compiled with a C89 compiler, options <code>A</code> and <code>a</code> (hexadecimal floats) do not support any modifier (flags, width, length). <p> Option <code>s</code> expects a string; if its argument is not a string, it is converted to one following the same rules of <a href="#pdf-tostring"><code>tostring</code></a>. If the option has any modifier (flags, width, length), the string argument should not contain embedded zeros. <p> <hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern)</code></a></h3> Returns an iterator function that, each time it is called, returns the next captures from <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) over the string <code>s</code>. If <code>pattern</code> specifies no captures, then the whole match is produced in each call. <p> As an example, the following loop will iterate over all the words from string <code>s</code>, printing one per line: <pre> s = "hello world from Lua" for w in string.gmatch(s, "%a+") do print(w) end </pre><p> The next example collects all pairs <code>key=value</code> from the given string into a table: <pre> t = {} s = "from=world, to=Lua" for k, v in string.gmatch(s, "(%w+)=(%w+)") do t[k] = v end </pre> <p> For this function, a caret '<code>^</code>' at the start of a pattern does not work as an anchor, as this would prevent the iteration. <p> <hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3> Returns a copy of <code>s</code> in which all (or the first <code>n</code>, if given) occurrences of the <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) have been replaced by a replacement string specified by <code>repl</code>, which can be a string, a table, or a function. <code>gsub</code> also returns, as its second value, the total number of matches that occurred. The name <code>gsub</code> comes from <em>Global SUBstitution</em>. <p> If <code>repl</code> is a string, then its value is used for replacement. The character&nbsp;<code>%</code> works as an escape character: any sequence in <code>repl</code> of the form <code>%<em>d</em></code>, with <em>d</em> between 1 and 9, stands for the value of the <em>d</em>-th captured substring. The sequence <code>%0</code> stands for the whole match. The sequence <code>%%</code> stands for a single&nbsp;<code>%</code>. <p> If <code>repl</code> is a table, then the table is queried for every match, using the first capture as the key. <p> If <code>repl</code> is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order. <p> In any case, if the pattern specifies no captures, then it behaves as if the whole pattern was inside a capture. <p> If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is <b>false</b> or <b>nil</b>, then there is no replacement (that is, the original match is kept in the string). <p> Here are some examples: <pre> x = string.gsub("hello world", "(%w+)", "%1 %1") --&gt; x="hello hello world world" x = string.gsub("hello world", "%w+", "%0 %0", 1) --&gt; x="hello hello world" x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") --&gt; x="world hello Lua from" x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv) --&gt; x="home = /home/roberto, user = roberto" x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s) return load(s)() end) --&gt; x="4+5 = 9" local t = {name="lua", version="5.3"} x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t) --&gt; x="lua-5.3.tar.gz" </pre> <p> <hr><h3><a name="pdf-string.len"><code>string.len (s)</code></a></h3> Receives a string and returns its length. The empty string <code>""</code> has length 0. Embedded zeros are counted, so <code>"a\000bc\000"</code> has length 5. <p> <hr><h3><a name="pdf-string.lower"><code>string.lower (s)</code></a></h3> Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other characters are left unchanged. The definition of what an uppercase letter is depends on the current locale. <p> <hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3> Looks for the first <em>match</em> of <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>. If it finds one, then <code>match</code> returns the captures from the pattern; otherwise it returns <b>nil</b>. If <code>pattern</code> specifies no captures, then the whole match is returned. A third, optional numeric argument <code>init</code> specifies where to start the search; its default value is&nbsp;1 and can be negative. <p> <hr><h3><a name="pdf-string.pack"><code>string.pack (fmt, v1, v2, &middot;&middot;&middot;)</code></a></h3> <p> Returns a binary string containing the values <code>v1</code>, <code>v2</code>, etc. packed (that is, serialized in binary form) according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>). <p> <hr><h3><a name="pdf-string.packsize"><code>string.packsize (fmt)</code></a></h3> <p> Returns the size of a string resulting from <a href="#pdf-string.pack"><code>string.pack</code></a> with the given format. The format string cannot have the variable-length options '<code>s</code>' or '<code>z</code>' (see <a href="#6.4.2">&sect;6.4.2</a>). <p> <hr><h3><a name="pdf-string.rep"><code>string.rep (s, n [, sep])</code></a></h3> Returns a string that is the concatenation of <code>n</code> copies of the string <code>s</code> separated by the string <code>sep</code>. The default value for <code>sep</code> is the empty string (that is, no separator). Returns the empty string if <code>n</code> is not positive. <p> (Note that it is very easy to exhaust the memory of your machine with a single call to this function.) <p> <hr><h3><a name="pdf-string.reverse"><code>string.reverse (s)</code></a></h3> Returns a string that is the string <code>s</code> reversed. <p> <hr><h3><a name="pdf-string.sub"><code>string.sub (s, i [, j])</code></a></h3> Returns the substring of <code>s</code> that starts at <code>i</code> and continues until <code>j</code>; <code>i</code> and <code>j</code> can be negative. If <code>j</code> is absent, then it is assumed to be equal to -1 (which is the same as the string length). In particular, the call <code>string.sub(s,1,j)</code> returns a prefix of <code>s</code> with length <code>j</code>, and <code>string.sub(s, -i)</code> (for a positive <code>i</code>) returns a suffix of <code>s</code> with length <code>i</code>. <p> If, after the translation of negative indices, <code>i</code> is less than 1, it is corrected to 1. If <code>j</code> is greater than the string length, it is corrected to that length. If, after these corrections, <code>i</code> is greater than <code>j</code>, the function returns the empty string. <p> <hr><h3><a name="pdf-string.unpack"><code>string.unpack (fmt, s [, pos])</code></a></h3> <p> Returns the values packed in string <code>s</code> (see <a href="#pdf-string.pack"><code>string.pack</code></a>) according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>). An optional <code>pos</code> marks where to start reading in <code>s</code> (default is 1). After the read values, this function also returns the index of the first unread byte in <code>s</code>. <p> <hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3> Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other characters are left unchanged. The definition of what a lowercase letter is depends on the current locale. <h3>6.4.1 &ndash; <a name="6.4.1">Patterns</a></h3> <p> Patterns in Lua are described by regular strings, which are interpreted as patterns by the pattern-matching functions <a href="#pdf-string.find"><code>string.find</code></a>, <a href="#pdf-string.gmatch"><code>string.gmatch</code></a>, <a href="#pdf-string.gsub"><code>string.gsub</code></a>, and <a href="#pdf-string.match"><code>string.match</code></a>. This section describes the syntax and the meaning (that is, what they match) of these strings. <h4>Character Class:</h4><p> A <em>character class</em> is used to represent a set of characters. The following combinations are allowed in describing a character class: <ul> <li><b><em>x</em>: </b> (where <em>x</em> is not one of the <em>magic characters</em> <code>^$()%.[]*+-?</code>) represents the character <em>x</em> itself. </li> <li><b><code>.</code>: </b> (a dot) represents all characters.</li> <li><b><code>%a</code>: </b> represents all letters.</li> <li><b><code>%c</code>: </b> represents all control characters.</li> <li><b><code>%d</code>: </b> represents all digits.</li> <li><b><code>%g</code>: </b> represents all printable characters except space.</li> <li><b><code>%l</code>: </b> represents all lowercase letters.</li> <li><b><code>%p</code>: </b> represents all punctuation characters.</li> <li><b><code>%s</code>: </b> represents all space characters.</li> <li><b><code>%u</code>: </b> represents all uppercase letters.</li> <li><b><code>%w</code>: </b> represents all alphanumeric characters.</li> <li><b><code>%x</code>: </b> represents all hexadecimal digits.</li> <li><b><code>%<em>x</em></code>: </b> (where <em>x</em> is any non-alphanumeric character) represents the character <em>x</em>. This is the standard way to escape the magic characters. Any non-alphanumeric character (including all punctuation characters, even the non-magical) can be preceded by a '<code>%</code>' when used to represent itself in a pattern. </li> <li><b><code>[<em>set</em>]</code>: </b> represents the class which is the union of all characters in <em>set</em>. A range of characters can be specified by separating the end characters of the range, in ascending order, with a '<code>-</code>'. All classes <code>%</code><em>x</em> described above can also be used as components in <em>set</em>. All other characters in <em>set</em> represent themselves. For example, <code>[%w_]</code> (or <code>[_%w]</code>) represents all alphanumeric characters plus the underscore, <code>[0-7]</code> represents the octal digits, and <code>[0-7%l%-]</code> represents the octal digits plus the lowercase letters plus the '<code>-</code>' character. <p> You can put a closing square bracket in a set by positioning it as the first character in the set. You can put a hyphen in a set by positioning it as the first or the last character in the set. (You can also use an escape for both cases.) <p> The interaction between ranges and classes is not defined. Therefore, patterns like <code>[%a-z]</code> or <code>[a-%%]</code> have no meaning. </li> <li><b><code>[^<em>set</em>]</code>: </b> represents the complement of <em>set</em>, where <em>set</em> is interpreted as above. </li> </ul><p> For all classes represented by single letters (<code>%a</code>, <code>%c</code>, etc.), the corresponding uppercase letter represents the complement of the class. For instance, <code>%S</code> represents all non-space characters. <p> The definitions of letter, space, and other character groups depend on the current locale. In particular, the class <code>[a-z]</code> may not be equivalent to <code>%l</code>. <h4>Pattern Item:</h4><p> A <em>pattern item</em> can be <ul> <li> a single character class, which matches any single character in the class; </li> <li> a single character class followed by '<code>*</code>', which matches zero or more repetitions of characters in the class. These repetition items will always match the longest possible sequence; </li> <li> a single character class followed by '<code>+</code>', which matches one or more repetitions of characters in the class. These repetition items will always match the longest possible sequence; </li> <li> a single character class followed by '<code>-</code>', which also matches zero or more repetitions of characters in the class. Unlike '<code>*</code>', these repetition items will always match the shortest possible sequence; </li> <li> a single character class followed by '<code>?</code>', which matches zero or one occurrence of a character in the class. It always matches one occurrence if possible; </li> <li> <code>%<em>n</em></code>, for <em>n</em> between 1 and 9; such item matches a substring equal to the <em>n</em>-th captured string (see below); </li> <li> <code>%b<em>xy</em></code>, where <em>x</em> and <em>y</em> are two distinct characters; such item matches strings that start with&nbsp;<em>x</em>, end with&nbsp;<em>y</em>, and where the <em>x</em> and <em>y</em> are <em>balanced</em>. This means that, if one reads the string from left to right, counting <em>+1</em> for an <em>x</em> and <em>-1</em> for a <em>y</em>, the ending <em>y</em> is the first <em>y</em> where the count reaches 0. For instance, the item <code>%b()</code> matches expressions with balanced parentheses. </li> <li> <code>%f[<em>set</em>]</code>, a <em>frontier pattern</em>; such item matches an empty string at any position such that the next character belongs to <em>set</em> and the previous character does not belong to <em>set</em>. The set <em>set</em> is interpreted as previously described. The beginning and the end of the subject are handled as if they were the character '<code>\0</code>'. </li> </ul> <h4>Pattern:</h4><p> A <em>pattern</em> is a sequence of pattern items. A caret '<code>^</code>' at the beginning of a pattern anchors the match at the beginning of the subject string. A '<code>$</code>' at the end of a pattern anchors the match at the end of the subject string. At other positions, '<code>^</code>' and '<code>$</code>' have no special meaning and represent themselves. <h4>Captures:</h4><p> A pattern can contain sub-patterns enclosed in parentheses; they describe <em>captures</em>. When a match succeeds, the substrings of the subject string that match captures are stored (<em>captured</em>) for future use. Captures are numbered according to their left parentheses. For instance, in the pattern <code>"(a*(.)%w(%s*))"</code>, the part of the string matching <code>"a*(.)%w(%s*)"</code> is stored as the first capture (and therefore has number&nbsp;1); the character matching "<code>.</code>" is captured with number&nbsp;2, and the part matching "<code>%s*</code>" has number&nbsp;3. <p> As a special case, the empty capture <code>()</code> captures the current string position (a number). For instance, if we apply the pattern <code>"()aa()"</code> on the string <code>"flaaap"</code>, there will be two captures: 3&nbsp;and&nbsp;5. <h3>6.4.2 &ndash; <a name="6.4.2">Format Strings for Pack and Unpack</a></h3> <p> The first argument to <a href="#pdf-string.pack"><code>string.pack</code></a>, <a href="#pdf-string.packsize"><code>string.packsize</code></a>, and <a href="#pdf-string.unpack"><code>string.unpack</code></a> is a format string, which describes the layout of the structure being created or read. <p> A format string is a sequence of conversion options. The conversion options are as follows: <ul> <li><b><code>&lt;</code>: </b>sets little endian</li> <li><b><code>&gt;</code>: </b>sets big endian</li> <li><b><code>=</code>: </b>sets native endian</li> <li><b><code>![<em>n</em>]</code>: </b>sets maximum alignment to <code>n</code> (default is native alignment)</li> <li><b><code>b</code>: </b>a signed byte (<code>char</code>)</li> <li><b><code>B</code>: </b>an unsigned byte (<code>char</code>)</li> <li><b><code>h</code>: </b>a signed <code>short</code> (native size)</li> <li><b><code>H</code>: </b>an unsigned <code>short</code> (native size)</li> <li><b><code>l</code>: </b>a signed <code>long</code> (native size)</li> <li><b><code>L</code>: </b>an unsigned <code>long</code> (native size)</li> <li><b><code>j</code>: </b>a <code>lua_Integer</code></li> <li><b><code>J</code>: </b>a <code>lua_Unsigned</code></li> <li><b><code>T</code>: </b>a <code>size_t</code> (native size)</li> <li><b><code>i[<em>n</em>]</code>: </b>a signed <code>int</code> with <code>n</code> bytes (default is native size)</li> <li><b><code>I[<em>n</em>]</code>: </b>an unsigned <code>int</code> with <code>n</code> bytes (default is native size)</li> <li><b><code>f</code>: </b>a <code>float</code> (native size)</li> <li><b><code>d</code>: </b>a <code>double</code> (native size)</li> <li><b><code>n</code>: </b>a <code>lua_Number</code></li> <li><b><code>c<em>n</em></code>: </b>a fixed-sized string with <code>n</code> bytes</li> <li><b><code>z</code>: </b>a zero-terminated string</li> <li><b><code>s[<em>n</em>]</code>: </b>a string preceded by its length coded as an unsigned integer with <code>n</code> bytes (default is a <code>size_t</code>)</li> <li><b><code>x</code>: </b>one byte of padding</li> <li><b><code>X<em>op</em></code>: </b>an empty item that aligns according to option <code>op</code> (which is otherwise ignored)</li> <li><b>'<code> </code>': </b>(empty space) ignored</li> </ul><p> (A "<code>[<em>n</em>]</code>" means an optional integral numeral.) Except for padding, spaces, and configurations (options "<code>xX &lt;=&gt;!</code>"), each option corresponds to an argument (in <a href="#pdf-string.pack"><code>string.pack</code></a>) or a result (in <a href="#pdf-string.unpack"><code>string.unpack</code></a>). <p> For options "<code>!<em>n</em></code>", "<code>s<em>n</em></code>", "<code>i<em>n</em></code>", and "<code>I<em>n</em></code>", <code>n</code> can be any integer between 1 and 16. All integral options check overflows; <a href="#pdf-string.pack"><code>string.pack</code></a> checks whether the given value fits in the given size; <a href="#pdf-string.unpack"><code>string.unpack</code></a> checks whether the read value fits in a Lua integer. <p> Any format string starts as if prefixed by "<code>!1=</code>", that is, with maximum alignment of 1 (no alignment) and native endianness. <p> Alignment works as follows: For each option, the format gets extra padding until the data starts at an offset that is a multiple of the minimum between the option size and the maximum alignment; this minimum must be a power of 2. Options "<code>c</code>" and "<code>z</code>" are not aligned; option "<code>s</code>" follows the alignment of its starting integer. <p> All padding is filled with zeros by <a href="#pdf-string.pack"><code>string.pack</code></a> (and ignored by <a href="#pdf-string.unpack"><code>string.unpack</code></a>). <h2>6.5 &ndash; <a name="6.5">UTF-8 Support</a></h2> <p> This library provides basic support for UTF-8 encoding. It provides all its functions inside the table <a name="pdf-utf8"><code>utf8</code></a>. This library does not provide any support for Unicode other than the handling of the encoding. Any operation that needs the meaning of a character, such as character classification, is outside its scope. <p> Unless stated otherwise, all functions that expect a byte position as a parameter assume that the given position is either the start of a byte sequence or one plus the length of the subject string. As in the string library, negative indices count from the end of the string. <p> <hr><h3><a name="pdf-utf8.char"><code>utf8.char (&middot;&middot;&middot;)</code></a></h3> Receives zero or more integers, converts each one to its corresponding UTF-8 byte sequence and returns a string with the concatenation of all these sequences. <p> <hr><h3><a name="pdf-utf8.charpattern"><code>utf8.charpattern</code></a></h3> The pattern (a string, not a function) "<code>[\0-\x7F\xC2-\xF4][\x80-\xBF]*</code>" (see <a href="#6.4.1">&sect;6.4.1</a>), which matches exactly one UTF-8 byte sequence, assuming that the subject is a valid UTF-8 string. <p> <hr><h3><a name="pdf-utf8.codes"><code>utf8.codes (s)</code></a></h3> <p> Returns values so that the construction <pre> for p, c in utf8.codes(s) do <em>body</em> end </pre><p> will iterate over all characters in string <code>s</code>, with <code>p</code> being the position (in bytes) and <code>c</code> the code point of each character. It raises an error if it meets any invalid byte sequence. <p> <hr><h3><a name="pdf-utf8.codepoint"><code>utf8.codepoint (s [, i [, j]])</code></a></h3> Returns the codepoints (as integers) from all characters in <code>s</code> that start between byte position <code>i</code> and <code>j</code> (both included). The default for <code>i</code> is 1 and for <code>j</code> is <code>i</code>. It raises an error if it meets any invalid byte sequence. <p> <hr><h3><a name="pdf-utf8.len"><code>utf8.len (s [, i [, j]])</code></a></h3> Returns the number of UTF-8 characters in string <code>s</code> that start between positions <code>i</code> and <code>j</code> (both inclusive). The default for <code>i</code> is 1 and for <code>j</code> is -1. If it finds any invalid byte sequence, returns a false value plus the position of the first invalid byte. <p> <hr><h3><a name="pdf-utf8.offset"><code>utf8.offset (s, n [, i])</code></a></h3> Returns the position (in bytes) where the encoding of the <code>n</code>-th character of <code>s</code> (counting from position <code>i</code>) starts. A negative <code>n</code> gets characters before position <code>i</code>. The default for <code>i</code> is 1 when <code>n</code> is non-negative and <code>#s + 1</code> otherwise, so that <code>utf8.offset(s, -n)</code> gets the offset of the <code>n</code>-th character from the end of the string. If the specified character is neither in the subject nor right after its end, the function returns <b>nil</b>. <p> As a special case, when <code>n</code> is 0 the function returns the start of the encoding of the character that contains the <code>i</code>-th byte of <code>s</code>. <p> This function assumes that <code>s</code> is a valid UTF-8 string. <h2>6.6 &ndash; <a name="6.6">Table Manipulation</a></h2> <p> This library provides generic functions for table manipulation. It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>. <p> Remember that, whenever an operation needs the length of a table, all caveats about the length operator apply (see <a href="#3.4.7">&sect;3.4.7</a>). All functions ignore non-numeric keys in the tables given as arguments. <p> <hr><h3><a name="pdf-table.concat"><code>table.concat (list [, sep [, i [, j]]])</code></a></h3> <p> Given a list where all elements are strings or numbers, returns the string <code>list[i]..sep..list[i+1] &middot;&middot;&middot; sep..list[j]</code>. The default value for <code>sep</code> is the empty string, the default for <code>i</code> is 1, and the default for <code>j</code> is <code>#list</code>. If <code>i</code> is greater than <code>j</code>, returns the empty string. <p> <hr><h3><a name="pdf-table.insert"><code>table.insert (list, [pos,] value)</code></a></h3> <p> Inserts element <code>value</code> at position <code>pos</code> in <code>list</code>, shifting up the elements <code>list[pos], list[pos+1], &middot;&middot;&middot;, list[#list]</code>. The default value for <code>pos</code> is <code>#list+1</code>, so that a call <code>table.insert(t,x)</code> inserts <code>x</code> at the end of list <code>t</code>. <p> <hr><h3><a name="pdf-table.move"><code>table.move (a1, f, e, t [,a2])</code></a></h3> <p> Moves elements from table <code>a1</code> to table <code>a2</code>, performing the equivalent to the following multiple assignment: <code>a2[t],&middot;&middot;&middot; = a1[f],&middot;&middot;&middot;,a1[e]</code>. The default for <code>a2</code> is <code>a1</code>. The destination range can overlap with the source range. The number of elements to be moved must fit in a Lua integer. <p> Returns the destination table <code>a2</code>. <p> <hr><h3><a name="pdf-table.pack"><code>table.pack (&middot;&middot;&middot;)</code></a></h3> <p> Returns a new table with all arguments stored into keys 1, 2, etc. and with a field "<code>n</code>" with the total number of arguments. Note that the resulting table may not be a sequence. <p> <hr><h3><a name="pdf-table.remove"><code>table.remove (list [, pos])</code></a></h3> <p> Removes from <code>list</code> the element at position <code>pos</code>, returning the value of the removed element. When <code>pos</code> is an integer between 1 and <code>#list</code>, it shifts down the elements <code>list[pos+1], list[pos+2], &middot;&middot;&middot;, list[#list]</code> and erases element <code>list[#list]</code>; The index <code>pos</code> can also be 0 when <code>#list</code> is 0, or <code>#list + 1</code>; in those cases, the function erases the element <code>list[pos]</code>. <p> The default value for <code>pos</code> is <code>#list</code>, so that a call <code>table.remove(l)</code> removes the last element of list <code>l</code>. <p> <hr><h3><a name="pdf-table.sort"><code>table.sort (list [, comp])</code></a></h3> <p> Sorts list elements in a given order, <em>in-place</em>, from <code>list[1]</code> to <code>list[#list]</code>. If <code>comp</code> is given, then it must be a function that receives two list elements and returns true when the first element must come before the second in the final order (so that, after the sort, <code>i &lt; j</code> implies <code>not comp(list[j],list[i])</code>). If <code>comp</code> is not given, then the standard Lua operator <code>&lt;</code> is used instead. <p> Note that the <code>comp</code> function must define a strict partial order over the elements in the list; that is, it must be asymmetric and transitive. Otherwise, no valid sort may be possible. <p> The sort algorithm is not stable: elements considered equal by the given order may have their relative positions changed by the sort. <p> <hr><h3><a name="pdf-table.unpack"><code>table.unpack (list [, i [, j]])</code></a></h3> <p> Returns the elements from the given list. This function is equivalent to <pre> return list[i], list[i+1], &middot;&middot;&middot;, list[j] </pre><p> By default, <code>i</code> is&nbsp;1 and <code>j</code> is <code>#list</code>. <h2>6.7 &ndash; <a name="6.7">Mathematical Functions</a></h2> <p> This library provides basic mathematical functions. It provides all its functions and constants inside the table <a name="pdf-math"><code>math</code></a>. Functions with the annotation "<code>integer/float</code>" give integer results for integer arguments and float results for float (or mixed) arguments. Rounding functions (<a href="#pdf-math.ceil"><code>math.ceil</code></a>, <a href="#pdf-math.floor"><code>math.floor</code></a>, and <a href="#pdf-math.modf"><code>math.modf</code></a>) return an integer when the result fits in the range of an integer, or a float otherwise. <p> <hr><h3><a name="pdf-math.abs"><code>math.abs (x)</code></a></h3> <p> Returns the absolute value of <code>x</code>. (integer/float) <p> <hr><h3><a name="pdf-math.acos"><code>math.acos (x)</code></a></h3> <p> Returns the arc cosine of <code>x</code> (in radians). <p> <hr><h3><a name="pdf-math.asin"><code>math.asin (x)</code></a></h3> <p> Returns the arc sine of <code>x</code> (in radians). <p> <hr><h3><a name="pdf-math.atan"><code>math.atan (y [, x])</code></a></h3> <p> Returns the arc tangent of <code>y/x</code> (in radians), but uses the signs of both arguments to find the quadrant of the result. (It also handles correctly the case of <code>x</code> being zero.) <p> The default value for <code>x</code> is 1, so that the call <code>math.atan(y)</code> returns the arc tangent of <code>y</code>. <p> <hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3> <p> Returns the smallest integral value larger than or equal to <code>x</code>. <p> <hr><h3><a name="pdf-math.cos"><code>math.cos (x)</code></a></h3> <p> Returns the cosine of <code>x</code> (assumed to be in radians). <p> <hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3> <p> Converts the angle <code>x</code> from radians to degrees. <p> <hr><h3><a name="pdf-math.exp"><code>math.exp (x)</code></a></h3> <p> Returns the value <em>e<sup>x</sup></em> (where <code>e</code> is the base of natural logarithms). <p> <hr><h3><a name="pdf-math.floor"><code>math.floor (x)</code></a></h3> <p> Returns the largest integral value smaller than or equal to <code>x</code>. <p> <hr><h3><a name="pdf-math.fmod"><code>math.fmod (x, y)</code></a></h3> <p> Returns the remainder of the division of <code>x</code> by <code>y</code> that rounds the quotient towards zero. (integer/float) <p> <hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3> <p> The float value <code>HUGE_VAL</code>, a value larger than any other numeric value. <p> <hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3> <p> Returns the logarithm of <code>x</code> in the given base. The default for <code>base</code> is <em>e</em> (so that the function returns the natural logarithm of <code>x</code>). <p> <hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3> <p> Returns the argument with the maximum value, according to the Lua operator <code>&lt;</code>. (integer/float) <p> <hr><h3><a name="pdf-math.maxinteger"><code>math.maxinteger</code></a></h3> An integer with the maximum value for an integer. <p> <hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3> <p> Returns the argument with the minimum value, according to the Lua operator <code>&lt;</code>. (integer/float) <p> <hr><h3><a name="pdf-math.mininteger"><code>math.mininteger</code></a></h3> An integer with the minimum value for an integer. <p> <hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3> <p> Returns the integral part of <code>x</code> and the fractional part of <code>x</code>. Its second result is always a float. <p> <hr><h3><a name="pdf-math.pi"><code>math.pi</code></a></h3> <p> The value of <em>&pi;</em>. <p> <hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3> <p> Converts the angle <code>x</code> from degrees to radians. <p> <hr><h3><a name="pdf-math.random"><code>math.random ([m [, n]])</code></a></h3> <p> When called without arguments, returns a pseudo-random float with uniform distribution in the range <em>[0,1)</em>. When called with two integers <code>m</code> and <code>n</code>, <code>math.random</code> returns a pseudo-random integer with uniform distribution in the range <em>[m, n]</em>. (The value <em>n-m</em> cannot be negative and must fit in a Lua integer.) The call <code>math.random(n)</code> is equivalent to <code>math.random(1,n)</code>. <p> This function is an interface to the underling pseudo-random generator function provided by C. <p> <hr><h3><a name="pdf-math.randomseed"><code>math.randomseed (x)</code></a></h3> <p> Sets <code>x</code> as the "seed" for the pseudo-random generator: equal seeds produce equal sequences of numbers. <p> <hr><h3><a name="pdf-math.sin"><code>math.sin (x)</code></a></h3> <p> Returns the sine of <code>x</code> (assumed to be in radians). <p> <hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3> <p> Returns the square root of <code>x</code>. (You can also use the expression <code>x^0.5</code> to compute this value.) <p> <hr><h3><a name="pdf-math.tan"><code>math.tan (x)</code></a></h3> <p> Returns the tangent of <code>x</code> (assumed to be in radians). <p> <hr><h3><a name="pdf-math.tointeger"><code>math.tointeger (x)</code></a></h3> <p> If the value <code>x</code> is convertible to an integer, returns that integer. Otherwise, returns <b>nil</b>. <p> <hr><h3><a name="pdf-math.type"><code>math.type (x)</code></a></h3> <p> Returns "<code>integer</code>" if <code>x</code> is an integer, "<code>float</code>" if it is a float, or <b>nil</b> if <code>x</code> is not a number. <p> <hr><h3><a name="pdf-math.ult"><code>math.ult (m, n)</code></a></h3> <p> Returns a boolean, true if and only if integer <code>m</code> is below integer <code>n</code> when they are compared as unsigned integers. <h2>6.8 &ndash; <a name="6.8">Input and Output Facilities</a></h2> <p> The I/O library provides two different styles for file manipulation. The first one uses implicit file handles; that is, there are operations to set a default input file and a default output file, and all input/output operations are over these default files. The second style uses explicit file handles. <p> When using implicit file handles, all operations are supplied by table <a name="pdf-io"><code>io</code></a>. When using explicit file handles, the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file handle and then all operations are supplied as methods of the file handle. <p> The table <code>io</code> also provides three predefined file handles with their usual meanings from C: <a name="pdf-io.stdin"><code>io.stdin</code></a>, <a name="pdf-io.stdout"><code>io.stdout</code></a>, and <a name="pdf-io.stderr"><code>io.stderr</code></a>. The I/O library never closes these files. <p> Unless otherwise stated, all I/O functions return <b>nil</b> on failure (plus an error message as a second result and a system-dependent error code as a third result) and some value different from <b>nil</b> on success. In non-POSIX systems, the computation of the error message and error code in case of errors may be not thread safe, because they rely on the global C variable <code>errno</code>. <p> <hr><h3><a name="pdf-io.close"><code>io.close ([file])</code></a></h3> <p> Equivalent to <code>file:close()</code>. Without a <code>file</code>, closes the default output file. <p> <hr><h3><a name="pdf-io.flush"><code>io.flush ()</code></a></h3> <p> Equivalent to <code>io.output():flush()</code>. <p> <hr><h3><a name="pdf-io.input"><code>io.input ([file])</code></a></h3> <p> When called with a file name, it opens the named file (in text mode), and sets its handle as the default input file. When called with a file handle, it simply sets this file handle as the default input file. When called without arguments, it returns the current default input file. <p> In case of errors this function raises the error, instead of returning an error code. <p> <hr><h3><a name="pdf-io.lines"><code>io.lines ([filename, &middot;&middot;&middot;])</code></a></h3> <p> Opens the given file name in read mode and returns an iterator function that works like <code>file:lines(&middot;&middot;&middot;)</code> over the opened file. When the iterator function detects the end of file, it returns no values (to finish the loop) and automatically closes the file. <p> The call <code>io.lines()</code> (with no file name) is equivalent to <code>io.input():lines("*l")</code>; that is, it iterates over the lines of the default input file. In this case, the iterator does not close the file when the loop ends. <p> In case of errors this function raises the error, instead of returning an error code. <p> <hr><h3><a name="pdf-io.open"><code>io.open (filename [, mode])</code></a></h3> <p> This function opens a file, in the mode specified in the string <code>mode</code>. In case of success, it returns a new file handle. <p> The <code>mode</code> string can be any of the following: <ul> <li><b>"<code>r</code>": </b> read mode (the default);</li> <li><b>"<code>w</code>": </b> write mode;</li> <li><b>"<code>a</code>": </b> append mode;</li> <li><b>"<code>r+</code>": </b> update mode, all previous data is preserved;</li> <li><b>"<code>w+</code>": </b> update mode, all previous data is erased;</li> <li><b>"<code>a+</code>": </b> append update mode, previous data is preserved, writing is only allowed at the end of file.</li> </ul><p> The <code>mode</code> string can also have a '<code>b</code>' at the end, which is needed in some systems to open the file in binary mode. <p> <hr><h3><a name="pdf-io.output"><code>io.output ([file])</code></a></h3> <p> Similar to <a href="#pdf-io.input"><code>io.input</code></a>, but operates over the default output file. <p> <hr><h3><a name="pdf-io.popen"><code>io.popen (prog [, mode])</code></a></h3> <p> This function is system dependent and is not available on all platforms. <p> Starts program <code>prog</code> in a separated process and returns a file handle that you can use to read data from this program (if <code>mode</code> is <code>"r"</code>, the default) or to write data to this program (if <code>mode</code> is <code>"w"</code>). <p> <hr><h3><a name="pdf-io.read"><code>io.read (&middot;&middot;&middot;)</code></a></h3> <p> Equivalent to <code>io.input():read(&middot;&middot;&middot;)</code>. <p> <hr><h3><a name="pdf-io.tmpfile"><code>io.tmpfile ()</code></a></h3> <p> In case of success, returns a handle for a temporary file. This file is opened in update mode and it is automatically removed when the program ends. <p> <hr><h3><a name="pdf-io.type"><code>io.type (obj)</code></a></h3> <p> Checks whether <code>obj</code> is a valid file handle. Returns the string <code>"file"</code> if <code>obj</code> is an open file handle, <code>"closed file"</code> if <code>obj</code> is a closed file handle, or <b>nil</b> if <code>obj</code> is not a file handle. <p> <hr><h3><a name="pdf-io.write"><code>io.write (&middot;&middot;&middot;)</code></a></h3> <p> Equivalent to <code>io.output():write(&middot;&middot;&middot;)</code>. <p> <hr><h3><a name="pdf-file:close"><code>file:close ()</code></a></h3> <p> Closes <code>file</code>. Note that files are automatically closed when their handles are garbage collected, but that takes an unpredictable amount of time to happen. <p> When closing a file handle created with <a href="#pdf-io.popen"><code>io.popen</code></a>, <a href="#pdf-file:close"><code>file:close</code></a> returns the same values returned by <a href="#pdf-os.execute"><code>os.execute</code></a>. <p> <hr><h3><a name="pdf-file:flush"><code>file:flush ()</code></a></h3> <p> Saves any written data to <code>file</code>. <p> <hr><h3><a name="pdf-file:lines"><code>file:lines (&middot;&middot;&middot;)</code></a></h3> <p> Returns an iterator function that, each time it is called, reads the file according to the given formats. When no format is given, uses "<code>l</code>" as a default. As an example, the construction <pre> for c in file:lines(1) do <em>body</em> end </pre><p> will iterate over all characters of the file, starting at the current position. Unlike <a href="#pdf-io.lines"><code>io.lines</code></a>, this function does not close the file when the loop ends. <p> In case of errors this function raises the error, instead of returning an error code. <p> <hr><h3><a name="pdf-file:read"><code>file:read (&middot;&middot;&middot;)</code></a></h3> <p> Reads the file <code>file</code>, according to the given formats, which specify what to read. For each format, the function returns a string or a number with the characters read, or <b>nil</b> if it cannot read data with the specified format. (In this latter case, the function does not read subsequent formats.) When called without formats, it uses a default format that reads the next line (see below). <p> The available formats are <ul> <li><b>"<code>n</code>": </b> reads a numeral and returns it as a float or an integer, following the lexical conventions of Lua. (The numeral may have leading spaces and a sign.) This format always reads the longest input sequence that is a valid prefix for a numeral; if that prefix does not form a valid numeral (e.g., an empty string, "<code>0x</code>", or "<code>3.4e-</code>"), it is discarded and the function returns <b>nil</b>. </li> <li><b>"<code>a</code>": </b> reads the whole file, starting at the current position. On end of file, it returns the empty string. </li> <li><b>"<code>l</code>": </b> reads the next line skipping the end of line, returning <b>nil</b> on end of file. This is the default format. </li> <li><b>"<code>L</code>": </b> reads the next line keeping the end-of-line character (if present), returning <b>nil</b> on end of file. </li> <li><b><em>number</em>: </b> reads a string with up to this number of bytes, returning <b>nil</b> on end of file. If <code>number</code> is zero, it reads nothing and returns an empty string, or <b>nil</b> on end of file. </li> </ul><p> The formats "<code>l</code>" and "<code>L</code>" should be used only for text files. <p> <hr><h3><a name="pdf-file:seek"><code>file:seek ([whence [, offset]])</code></a></h3> <p> Sets and gets the file position, measured from the beginning of the file, to the position given by <code>offset</code> plus a base specified by the string <code>whence</code>, as follows: <ul> <li><b>"<code>set</code>": </b> base is position 0 (beginning of the file);</li> <li><b>"<code>cur</code>": </b> base is current position;</li> <li><b>"<code>end</code>": </b> base is end of file;</li> </ul><p> In case of success, <code>seek</code> returns the final file position, measured in bytes from the beginning of the file. If <code>seek</code> fails, it returns <b>nil</b>, plus a string describing the error. <p> The default value for <code>whence</code> is <code>"cur"</code>, and for <code>offset</code> is 0. Therefore, the call <code>file:seek()</code> returns the current file position, without changing it; the call <code>file:seek("set")</code> sets the position to the beginning of the file (and returns 0); and the call <code>file:seek("end")</code> sets the position to the end of the file, and returns its size. <p> <hr><h3><a name="pdf-file:setvbuf"><code>file:setvbuf (mode [, size])</code></a></h3> <p> Sets the buffering mode for an output file. There are three available modes: <ul> <li><b>"<code>no</code>": </b> no buffering; the result of any output operation appears immediately. </li> <li><b>"<code>full</code>": </b> full buffering; output operation is performed only when the buffer is full or when you explicitly <code>flush</code> the file (see <a href="#pdf-io.flush"><code>io.flush</code></a>). </li> <li><b>"<code>line</code>": </b> line buffering; output is buffered until a newline is output or there is any input from some special files (such as a terminal device). </li> </ul><p> For the last two cases, <code>size</code> specifies the size of the buffer, in bytes. The default is an appropriate size. <p> <hr><h3><a name="pdf-file:write"><code>file:write (&middot;&middot;&middot;)</code></a></h3> <p> Writes the value of each of its arguments to <code>file</code>. The arguments must be strings or numbers. <p> In case of success, this function returns <code>file</code>. Otherwise it returns <b>nil</b> plus a string describing the error. <h2>6.9 &ndash; <a name="6.9">Operating System Facilities</a></h2> <p> This library is implemented through table <a name="pdf-os"><code>os</code></a>. <p> <hr><h3><a name="pdf-os.clock"><code>os.clock ()</code></a></h3> <p> Returns an approximation of the amount in seconds of CPU time used by the program. <p> <hr><h3><a name="pdf-os.date"><code>os.date ([format [, time]])</code></a></h3> <p> Returns a string or a table containing date and time, formatted according to the given string <code>format</code>. <p> If the <code>time</code> argument is present, this is the time to be formatted (see the <a href="#pdf-os.time"><code>os.time</code></a> function for a description of this value). Otherwise, <code>date</code> formats the current time. <p> If <code>format</code> starts with '<code>!</code>', then the date is formatted in Coordinated Universal Time. After this optional character, if <code>format</code> is the string "<code>*t</code>", then <code>date</code> returns a table with the following fields: <code>year</code>, <code>month</code> (1&ndash;12), <code>day</code> (1&ndash;31), <code>hour</code> (0&ndash;23), <code>min</code> (0&ndash;59), <code>sec</code> (0&ndash;61), <code>wday</code> (weekday, 1&ndash;7, Sunday is&nbsp;1), <code>yday</code> (day of the year, 1&ndash;366), and <code>isdst</code> (daylight saving flag, a boolean). This last field may be absent if the information is not available. <p> If <code>format</code> is not "<code>*t</code>", then <code>date</code> returns the date as a string, formatted according to the same rules as the ISO&nbsp;C function <code>strftime</code>. <p> When called without arguments, <code>date</code> returns a reasonable date and time representation that depends on the host system and on the current locale. (More specifically, <code>os.date()</code> is equivalent to <code>os.date("%c")</code>.) <p> In non-POSIX systems, this function may be not thread safe because of its reliance on C&nbsp;function <code>gmtime</code> and C&nbsp;function <code>localtime</code>. <p> <hr><h3><a name="pdf-os.difftime"><code>os.difftime (t2, t1)</code></a></h3> <p> Returns the difference, in seconds, from time <code>t1</code> to time <code>t2</code> (where the times are values returned by <a href="#pdf-os.time"><code>os.time</code></a>). In POSIX, Windows, and some other systems, this value is exactly <code>t2</code><em>-</em><code>t1</code>. <p> <hr><h3><a name="pdf-os.execute"><code>os.execute ([command])</code></a></h3> <p> This function is equivalent to the ISO&nbsp;C function <code>system</code>. It passes <code>command</code> to be executed by an operating system shell. Its first result is <b>true</b> if the command terminated successfully, or <b>nil</b> otherwise. After this first result the function returns a string plus a number, as follows: <ul> <li><b>"<code>exit</code>": </b> the command terminated normally; the following number is the exit status of the command. </li> <li><b>"<code>signal</code>": </b> the command was terminated by a signal; the following number is the signal that terminated the command. </li> </ul> <p> When called without a <code>command</code>, <code>os.execute</code> returns a boolean that is true if a shell is available. <p> <hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close]])</code></a></h3> <p> Calls the ISO&nbsp;C function <code>exit</code> to terminate the host program. If <code>code</code> is <b>true</b>, the returned status is <code>EXIT_SUCCESS</code>; if <code>code</code> is <b>false</b>, the returned status is <code>EXIT_FAILURE</code>; if <code>code</code> is a number, the returned status is this number. The default value for <code>code</code> is <b>true</b>. <p> If the optional second argument <code>close</code> is true, closes the Lua state before exiting. <p> <hr><h3><a name="pdf-os.getenv"><code>os.getenv (varname)</code></a></h3> <p> Returns the value of the process environment variable <code>varname</code>, or <b>nil</b> if the variable is not defined. <p> <hr><h3><a name="pdf-os.remove"><code>os.remove (filename)</code></a></h3> <p> Deletes the file (or empty directory, on POSIX systems) with the given name. If this function fails, it returns <b>nil</b>, plus a string describing the error and the error code. Otherwise, it returns true. <p> <hr><h3><a name="pdf-os.rename"><code>os.rename (oldname, newname)</code></a></h3> <p> Renames the file or directory named <code>oldname</code> to <code>newname</code>. If this function fails, it returns <b>nil</b>, plus a string describing the error and the error code. Otherwise, it returns true. <p> <hr><h3><a name="pdf-os.setlocale"><code>os.setlocale (locale [, category])</code></a></h3> <p> Sets the current locale of the program. <code>locale</code> is a system-dependent string specifying a locale; <code>category</code> is an optional string describing which category to change: <code>"all"</code>, <code>"collate"</code>, <code>"ctype"</code>, <code>"monetary"</code>, <code>"numeric"</code>, or <code>"time"</code>; the default category is <code>"all"</code>. The function returns the name of the new locale, or <b>nil</b> if the request cannot be honored. <p> If <code>locale</code> is the empty string, the current locale is set to an implementation-defined native locale. If <code>locale</code> is the string "<code>C</code>", the current locale is set to the standard C locale. <p> When called with <b>nil</b> as the first argument, this function only returns the name of the current locale for the given category. <p> This function may be not thread safe because of its reliance on C&nbsp;function <code>setlocale</code>. <p> <hr><h3><a name="pdf-os.time"><code>os.time ([table])</code></a></h3> <p> Returns the current time when called without arguments, or a time representing the local date and time specified by the given table. This table must have fields <code>year</code>, <code>month</code>, and <code>day</code>, and may have fields <code>hour</code> (default is 12), <code>min</code> (default is 0), <code>sec</code> (default is 0), and <code>isdst</code> (default is <b>nil</b>). Other fields are ignored. For a description of these fields, see the <a href="#pdf-os.date"><code>os.date</code></a> function. <p> The values in these fields do not need to be inside their valid ranges. For instance, if <code>sec</code> is -10, it means -10 seconds from the time specified by the other fields; if <code>hour</code> is 1000, it means +1000 hours from the time specified by the other fields. <p> The returned value is a number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the number of seconds since some given start time (the "epoch"). In other systems, the meaning is not specified, and the number returned by <code>time</code> can be used only as an argument to <a href="#pdf-os.date"><code>os.date</code></a> and <a href="#pdf-os.difftime"><code>os.difftime</code></a>. <p> <hr><h3><a name="pdf-os.tmpname"><code>os.tmpname ()</code></a></h3> <p> Returns a string with a file name that can be used for a temporary file. The file must be explicitly opened before its use and explicitly removed when no longer needed. <p> In POSIX systems, this function also creates a file with that name, to avoid security risks. (Someone else might create the file with wrong permissions in the time between getting the name and creating the file.) You still have to open the file to use it and to remove it (even if you do not use it). <p> When possible, you may prefer to use <a href="#pdf-io.tmpfile"><code>io.tmpfile</code></a>, which automatically removes the file when the program ends. <h2>6.10 &ndash; <a name="6.10">The Debug Library</a></h2> <p> This library provides the functionality of the debug interface (<a href="#4.9">&sect;4.9</a>) to Lua programs. You should exert care when using this library. Several of its functions violate basic assumptions about Lua code (e.g., that variables local to a function cannot be accessed from outside; that userdata metatables cannot be changed by Lua code; that Lua programs do not crash) and therefore can compromise otherwise secure code. Moreover, some functions in this library may be slow. <p> All functions in this library are provided inside the <a name="pdf-debug"><code>debug</code></a> table. All functions that operate over a thread have an optional first argument which is the thread to operate over. The default is always the current thread. <p> <hr><h3><a name="pdf-debug.debug"><code>debug.debug ()</code></a></h3> <p> Enters an interactive mode with the user, running each string that the user enters. Using simple commands and other debug facilities, the user can inspect global and local variables, change their values, evaluate expressions, and so on. A line containing only the word <code>cont</code> finishes this function, so that the caller continues its execution. <p> Note that commands for <code>debug.debug</code> are not lexically nested within any function and so have no direct access to local variables. <p> <hr><h3><a name="pdf-debug.gethook"><code>debug.gethook ([thread])</code></a></h3> <p> Returns the current hook settings of the thread, as three values: the current hook function, the current hook mask, and the current hook count (as set by the <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> function). <p> <hr><h3><a name="pdf-debug.getinfo"><code>debug.getinfo ([thread,] f [, what])</code></a></h3> <p> Returns a table with information about a function. You can give the function directly or you can give a number as the value of <code>f</code>, which means the function running at level <code>f</code> of the call stack of the given thread: level&nbsp;0 is the current function (<code>getinfo</code> itself); level&nbsp;1 is the function that called <code>getinfo</code> (except for tail calls, which do not count on the stack); and so on. If <code>f</code> is a number larger than the number of active functions, then <code>getinfo</code> returns <b>nil</b>. <p> The returned table can contain all the fields returned by <a href="#lua_getinfo"><code>lua_getinfo</code></a>, with the string <code>what</code> describing which fields to fill in. The default for <code>what</code> is to get all information available, except the table of valid lines. If present, the option '<code>f</code>' adds a field named <code>func</code> with the function itself. If present, the option '<code>L</code>' adds a field named <code>activelines</code> with the table of valid lines. <p> For instance, the expression <code>debug.getinfo(1,"n").name</code> returns a name for the current function, if a reasonable name can be found, and the expression <code>debug.getinfo(print)</code> returns a table with all available information about the <a href="#pdf-print"><code>print</code></a> function. <p> <hr><h3><a name="pdf-debug.getlocal"><code>debug.getlocal ([thread,] f, local)</code></a></h3> <p> This function returns the name and the value of the local variable with index <code>local</code> of the function at level <code>f</code> of the stack. This function accesses not only explicit local variables, but also parameters, temporaries, etc. <p> The first parameter or local variable has index&nbsp;1, and so on, following the order that they are declared in the code, counting only the variables that are active in the current scope of the function. Negative indices refer to vararg arguments; -1 is the first vararg argument. The function returns <b>nil</b> if there is no variable with the given index, and raises an error when called with a level out of range. (You can call <a href="#pdf-debug.getinfo"><code>debug.getinfo</code></a> to check whether the level is valid.) <p> Variable names starting with '<code>(</code>' (open parenthesis) represent variables with no known names (internal variables such as loop control variables, and variables from chunks saved without debug information). <p> The parameter <code>f</code> may also be a function. In that case, <code>getlocal</code> returns only the name of function parameters. <p> <hr><h3><a name="pdf-debug.getmetatable"><code>debug.getmetatable (value)</code></a></h3> <p> Returns the metatable of the given <code>value</code> or <b>nil</b> if it does not have a metatable. <p> <hr><h3><a name="pdf-debug.getregistry"><code>debug.getregistry ()</code></a></h3> <p> Returns the registry table (see <a href="#4.5">&sect;4.5</a>). <p> <hr><h3><a name="pdf-debug.getupvalue"><code>debug.getupvalue (f, up)</code></a></h3> <p> This function returns the name and the value of the upvalue with index <code>up</code> of the function <code>f</code>. The function returns <b>nil</b> if there is no upvalue with the given index. <p> Variable names starting with '<code>(</code>' (open parenthesis) represent variables with no known names (variables from chunks saved without debug information). <p> <hr><h3><a name="pdf-debug.getuservalue"><code>debug.getuservalue (u)</code></a></h3> <p> Returns the Lua value associated to <code>u</code>. If <code>u</code> is not a full userdata, returns <b>nil</b>. <p> <hr><h3><a name="pdf-debug.sethook"><code>debug.sethook ([thread,] hook, mask [, count])</code></a></h3> <p> Sets the given function as a hook. The string <code>mask</code> and the number <code>count</code> describe when the hook will be called. The string mask may have any combination of the following characters, with the given meaning: <ul> <li><b>'<code>c</code>': </b> the hook is called every time Lua calls a function;</li> <li><b>'<code>r</code>': </b> the hook is called every time Lua returns from a function;</li> <li><b>'<code>l</code>': </b> the hook is called every time Lua enters a new line of code.</li> </ul><p> Moreover, with a <code>count</code> different from zero, the hook is called also after every <code>count</code> instructions. <p> When called without arguments, <a href="#pdf-debug.sethook"><code>debug.sethook</code></a> turns off the hook. <p> When the hook is called, its first argument is a string describing the event that has triggered its call: <code>"call"</code> (or <code>"tail call"</code>), <code>"return"</code>, <code>"line"</code>, and <code>"count"</code>. For line events, the hook also gets the new line number as its second parameter. Inside a hook, you can call <code>getinfo</code> with level&nbsp;2 to get more information about the running function (level&nbsp;0 is the <code>getinfo</code> function, and level&nbsp;1 is the hook function). <p> <hr><h3><a name="pdf-debug.setlocal"><code>debug.setlocal ([thread,] level, local, value)</code></a></h3> <p> This function assigns the value <code>value</code> to the local variable with index <code>local</code> of the function at level <code>level</code> of the stack. The function returns <b>nil</b> if there is no local variable with the given index, and raises an error when called with a <code>level</code> out of range. (You can call <code>getinfo</code> to check whether the level is valid.) Otherwise, it returns the name of the local variable. <p> See <a href="#pdf-debug.getlocal"><code>debug.getlocal</code></a> for more information about variable indices and names. <p> <hr><h3><a name="pdf-debug.setmetatable"><code>debug.setmetatable (value, table)</code></a></h3> <p> Sets the metatable for the given <code>value</code> to the given <code>table</code> (which can be <b>nil</b>). Returns <code>value</code>. <p> <hr><h3><a name="pdf-debug.setupvalue"><code>debug.setupvalue (f, up, value)</code></a></h3> <p> This function assigns the value <code>value</code> to the upvalue with index <code>up</code> of the function <code>f</code>. The function returns <b>nil</b> if there is no upvalue with the given index. Otherwise, it returns the name of the upvalue. <p> <hr><h3><a name="pdf-debug.setuservalue"><code>debug.setuservalue (udata, value)</code></a></h3> <p> Sets the given <code>value</code> as the Lua value associated to the given <code>udata</code>. <code>udata</code> must be a full userdata. <p> Returns <code>udata</code>. <p> <hr><h3><a name="pdf-debug.traceback"><code>debug.traceback ([thread,] [message [, level]])</code></a></h3> <p> If <code>message</code> is present but is neither a string nor <b>nil</b>, this function returns <code>message</code> without further processing. Otherwise, it returns a string with a traceback of the call stack. The optional <code>message</code> string is appended at the beginning of the traceback. An optional <code>level</code> number tells at which level to start the traceback (default is 1, the function calling <code>traceback</code>). <p> <hr><h3><a name="pdf-debug.upvalueid"><code>debug.upvalueid (f, n)</code></a></h3> <p> Returns a unique identifier (as a light userdata) for the upvalue numbered <code>n</code> from the given function. <p> These unique identifiers allow a program to check whether different closures share upvalues. Lua closures that share an upvalue (that is, that access a same external local variable) will return identical ids for those upvalue indices. <p> <hr><h3><a name="pdf-debug.upvaluejoin"><code>debug.upvaluejoin (f1, n1, f2, n2)</code></a></h3> <p> Make the <code>n1</code>-th upvalue of the Lua closure <code>f1</code> refer to the <code>n2</code>-th upvalue of the Lua closure <code>f2</code>. <h1>7 &ndash; <a name="7">Lua Standalone</a></h1> <p> Although Lua has been designed as an extension language, to be embedded in a host C&nbsp;program, it is also frequently used as a standalone language. An interpreter for Lua as a standalone language, called simply <code>lua</code>, is provided with the standard distribution. The standalone interpreter includes all standard libraries, including the debug library. Its usage is: <pre> lua [options] [script [args]] </pre><p> The options are: <ul> <li><b><code>-e <em>stat</em></code>: </b> executes string <em>stat</em>;</li> <li><b><code>-l <em>mod</em></code>: </b> "requires" <em>mod</em> and assigns the result to global @<em>mod</em>;</li> <li><b><code>-i</code>: </b> enters interactive mode after running <em>script</em>;</li> <li><b><code>-v</code>: </b> prints version information;</li> <li><b><code>-E</code>: </b> ignores environment variables;</li> <li><b><code>--</code>: </b> stops handling options;</li> <li><b><code>-</code>: </b> executes <code>stdin</code> as a file and stops handling options.</li> </ul><p> After handling its options, <code>lua</code> runs the given <em>script</em>. When called without arguments, <code>lua</code> behaves as <code>lua -v -i</code> when the standard input (<code>stdin</code>) is a terminal, and as <code>lua -</code> otherwise. <p> When called without option <code>-E</code>, the interpreter checks for an environment variable <a name="pdf-LUA_INIT_5_3"><code>LUA_INIT_5_3</code></a> (or <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a> if the versioned name is not defined) before running any argument. If the variable content has the format <code>@<em>filename</em></code>, then <code>lua</code> executes the file. Otherwise, <code>lua</code> executes the string itself. <p> When called with option <code>-E</code>, besides ignoring <code>LUA_INIT</code>, Lua also ignores the values of <code>LUA_PATH</code> and <code>LUA_CPATH</code>, setting the values of <a href="#pdf-package.path"><code>package.path</code></a> and <a href="#pdf-package.cpath"><code>package.cpath</code></a> with the default paths defined in <code>luaconf.h</code>. <p> All options are handled in order, except <code>-i</code> and <code>-E</code>. For instance, an invocation like <pre> $ lua -e'a=1' -e 'print(a)' script.lua </pre><p> will first set <code>a</code> to 1, then print the value of <code>a</code>, and finally run the file <code>script.lua</code> with no arguments. (Here <code>$</code> is the shell prompt. Your prompt may be different.) <p> Before running any code, <code>lua</code> collects all command-line arguments in a global table called <code>arg</code>. The script name goes to index 0, the first argument after the script name goes to index 1, and so on. Any arguments before the script name (that is, the interpreter name plus its options) go to negative indices. For instance, in the call <pre> $ lua -la b.lua t1 t2 </pre><p> the table is like this: <pre> arg = { [-2] = "lua", [-1] = "-la", [0] = "b.lua", [1] = "t1", [2] = "t2" } </pre><p> If there is no script in the call, the interpreter name goes to index 0, followed by the other arguments. For instance, the call <pre> $ lua -e "print(arg[1])" </pre><p> will print "<code>-e</code>". If there is a script, the script is called with arguments <code>arg[1]</code>, &middot;&middot;&middot;, <code>arg[#arg]</code>. (Like all chunks in Lua, the script is compiled as a vararg function.) <p> In interactive mode, Lua repeatedly prompts and waits for a line. After reading a line, Lua first try to interpret the line as an expression. If it succeeds, it prints its value. Otherwise, it interprets the line as a statement. If you write an incomplete statement, the interpreter waits for its completion by issuing a different prompt. <p> If the global variable <a name="pdf-_PROMPT"><code>_PROMPT</code></a> contains a string, then its value is used as the prompt. Similarly, if the global variable <a name="pdf-_PROMPT2"><code>_PROMPT2</code></a> contains a string, its value is used as the secondary prompt (issued during incomplete statements). <p> In case of unprotected errors in the script, the interpreter reports the error to the standard error stream. If the error object is not a string but has a metamethod <code>__tostring</code>, the interpreter calls this metamethod to produce the final message. Otherwise, the interpreter converts the error object to a string and adds a stack traceback to it. <p> When finishing normally, the interpreter closes its main Lua state (see <a href="#lua_close"><code>lua_close</code></a>). The script can avoid this step by calling <a href="#pdf-os.exit"><code>os.exit</code></a> to terminate. <p> To allow the use of Lua as a script interpreter in Unix systems, the standalone interpreter skips the first line of a chunk if it starts with <code>#</code>. Therefore, Lua scripts can be made into executable programs by using <code>chmod +x</code> and the&nbsp;<code>#!</code> form, as in <pre> #!/usr/local/bin/lua </pre><p> (Of course, the location of the Lua interpreter may be different in your machine. If <code>lua</code> is in your <code>PATH</code>, then <pre> #!/usr/bin/env lua </pre><p> is a more portable solution.) <h1>8 &ndash; <a name="8">Incompatibilities with the Previous Version</a></h1> <p> Here we list the incompatibilities that you may find when moving a program from Lua&nbsp;5.2 to Lua&nbsp;5.3. You can avoid some incompatibilities by compiling Lua with appropriate options (see file <code>luaconf.h</code>). However, all these compatibility options will be removed in the future. <p> Lua versions can always change the C API in ways that do not imply source-code changes in a program, such as the numeric values for constants or the implementation of functions as macros. Therefore, you should not assume that binaries are compatible between different Lua versions. Always recompile clients of the Lua API when using a new version. <p> Similarly, Lua versions can always change the internal representation of precompiled chunks; precompiled chunks are not compatible between different Lua versions. <p> The standard paths in the official distribution may change between versions. <h2>8.1 &ndash; <a name="8.1">Changes in the Language</a></h2> <ul> <li> The main difference between Lua&nbsp;5.2 and Lua&nbsp;5.3 is the introduction of an integer subtype for numbers. Although this change should not affect "normal" computations, some computations (mainly those that involve some kind of overflow) can give different results. <p> You can fix these differences by forcing a number to be a float (in Lua&nbsp;5.2 all numbers were float), in particular writing constants with an ending <code>.0</code> or using <code>x = x + 0.0</code> to convert a variable. (This recommendation is only for a quick fix for an occasional incompatibility; it is not a general guideline for good programming. For good programming, use floats where you need floats and integers where you need integers.) </li> <li> The conversion of a float to a string now adds a <code>.0</code> suffix to the result if it looks like an integer. (For instance, the float 2.0 will be printed as <code>2.0</code>, not as <code>2</code>.) You should always use an explicit format when you need a specific format for numbers. <p> (Formally this is not an incompatibility, because Lua does not specify how numbers are formatted as strings, but some programs assumed a specific format.) </li> <li> The generational mode for the garbage collector was removed. (It was an experimental feature in Lua&nbsp;5.2.) </li> </ul> <h2>8.2 &ndash; <a name="8.2">Changes in the Libraries</a></h2> <ul> <li> The <code>bit32</code> library has been deprecated. It is easy to require a compatible external library or, better yet, to replace its functions with appropriate bitwise operations. (Keep in mind that <code>bit32</code> operates on 32-bit integers, while the bitwise operators in Lua&nbsp;5.3 operate on Lua integers, which by default have 64&nbsp;bits.) </li> <li> The Table library now respects metamethods for setting and getting elements. </li> <li> The <a href="#pdf-ipairs"><code>ipairs</code></a> iterator now respects metamethods and its <code>__ipairs</code> metamethod has been deprecated. </li> <li> Option names in <a href="#pdf-io.read"><code>io.read</code></a> do not have a starting '<code>*</code>' anymore. For compatibility, Lua will continue to accept (and ignore) this character. </li> <li> The following functions were deprecated in the mathematical library: <code>atan2</code>, <code>cosh</code>, <code>sinh</code>, <code>tanh</code>, <code>pow</code>, <code>frexp</code>, and <code>ldexp</code>. You can replace <code>math.pow(x,y)</code> with <code>x^y</code>; you can replace <code>math.atan2</code> with <code>math.atan</code>, which now accepts one or two arguments; you can replace <code>math.ldexp(x,exp)</code> with <code>x * 2.0^exp</code>. For the other operations, you can either use an external library or implement them in Lua. </li> <li> The searcher for C loaders used by <a href="#pdf-require"><code>require</code></a> changed the way it handles versioned names. Now, the version should come after the module name (as is usual in most other tools). For compatibility, that searcher still tries the old format if it cannot find an open function according to the new style. (Lua&nbsp;5.2 already worked that way, but it did not document the change.) </li> <li> The call <code>collectgarbage("count")</code> now returns only one result. (You can compute that second result from the fractional part of the first result.) </li> </ul> <h2>8.3 &ndash; <a name="8.3">Changes in the API</a></h2> <ul> <li> Continuation functions now receive as arguments what they needed to get through <code>lua_getctx</code>, so <code>lua_getctx</code> has been removed. Adapt your code accordingly. </li> <li> Function <a href="#lua_dump"><code>lua_dump</code></a> has an extra parameter, <code>strip</code>. Use 0 as the value of this parameter to get the old behavior. </li> <li> Functions to inject/project unsigned integers (<code>lua_pushunsigned</code>, <code>lua_tounsigned</code>, <code>lua_tounsignedx</code>, <code>luaL_checkunsigned</code>, <code>luaL_optunsigned</code>) were deprecated. Use their signed equivalents with a type cast. </li> <li> Macros to project non-default integer types (<code>luaL_checkint</code>, <code>luaL_optint</code>, <code>luaL_checklong</code>, <code>luaL_optlong</code>) were deprecated. Use their equivalent over <a href="#lua_Integer"><code>lua_Integer</code></a> with a type cast (or, when possible, use <a href="#lua_Integer"><code>lua_Integer</code></a> in your code). </li> </ul> <h1>9 &ndash; <a name="9">The Complete Syntax of Lua</a></h1> <p> Here is the complete syntax of Lua in extended BNF. As usual in extended BNF, {A} means 0 or more As, and [A] means an optional A. (For operator precedences, see <a href="#3.4.8">&sect;3.4.8</a>; for a description of the terminals Name, Numeral, and LiteralString, see <a href="#3.1">&sect;3.1</a>.) <pre> chunk ::= block block ::= {stat} [retstat] stat ::= &lsquo;<b>;</b>&rsquo; | varlist &lsquo;<b>=</b>&rsquo; explist | functioncall | label | <b>break</b> | <b>goto</b> Name | <b>do</b> block <b>end</b> | <b>while</b> exp <b>do</b> block <b>end</b> | <b>repeat</b> block <b>until</b> exp | <b>if</b> exp <b>then</b> block {<b>elseif</b> exp <b>then</b> block} [<b>else</b> block] <b>end</b> | <b>for</b> Name &lsquo;<b>=</b>&rsquo; exp &lsquo;<b>,</b>&rsquo; exp [&lsquo;<b>,</b>&rsquo; exp] <b>do</b> block <b>end</b> | <b>for</b> namelist <b>in</b> explist <b>do</b> block <b>end</b> | <b>function</b> funcname funcbody | <b>local</b> <b>function</b> Name funcbody | <b>local</b> namelist [&lsquo;<b>=</b>&rsquo; explist] retstat ::= <b>return</b> [explist] [&lsquo;<b>;</b>&rsquo;] label ::= &lsquo;<b>::</b>&rsquo; Name &lsquo;<b>::</b>&rsquo; funcname ::= Name {&lsquo;<b>.</b>&rsquo; Name} [&lsquo;<b>:</b>&rsquo; Name] varlist ::= var {&lsquo;<b>,</b>&rsquo; var} var ::= Name | prefixexp &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; | prefixexp &lsquo;<b>.</b>&rsquo; Name namelist ::= Name {&lsquo;<b>,</b>&rsquo; Name} explist ::= exp {&lsquo;<b>,</b>&rsquo; exp} exp ::= <b>nil</b> | <b>false</b> | <b>true</b> | Numeral | LiteralString | &lsquo;<b>...</b>&rsquo; | functiondef | prefixexp | tableconstructor | exp binop exp | unop exp prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo; functioncall ::= prefixexp args | prefixexp &lsquo;<b>:</b>&rsquo; Name args args ::= &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo; | tableconstructor | LiteralString functiondef ::= <b>function</b> funcbody funcbody ::= &lsquo;<b>(</b>&rsquo; [parlist] &lsquo;<b>)</b>&rsquo; block <b>end</b> parlist ::= namelist [&lsquo;<b>,</b>&rsquo; &lsquo;<b>...</b>&rsquo;] | &lsquo;<b>...</b>&rsquo; tableconstructor ::= &lsquo;<b>{</b>&rsquo; [fieldlist] &lsquo;<b>}</b>&rsquo; fieldlist ::= field {fieldsep field} [fieldsep] field ::= &lsquo;<b>[</b>&rsquo; exp &lsquo;<b>]</b>&rsquo; &lsquo;<b>=</b>&rsquo; exp | Name &lsquo;<b>=</b>&rsquo; exp | exp fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo; binop ::= &lsquo;<b>+</b>&rsquo; | &lsquo;<b>-</b>&rsquo; | &lsquo;<b>*</b>&rsquo; | &lsquo;<b>/</b>&rsquo; | &lsquo;<b>//</b>&rsquo; | &lsquo;<b>^</b>&rsquo; | &lsquo;<b>%</b>&rsquo; | &lsquo;<b>&amp;</b>&rsquo; | &lsquo;<b>~</b>&rsquo; | &lsquo;<b>|</b>&rsquo; | &lsquo;<b>&gt;&gt;</b>&rsquo; | &lsquo;<b>&lt;&lt;</b>&rsquo; | &lsquo;<b>..</b>&rsquo; | &lsquo;<b>&lt;</b>&rsquo; | &lsquo;<b>&lt;=</b>&rsquo; | &lsquo;<b>&gt;</b>&rsquo; | &lsquo;<b>&gt;=</b>&rsquo; | &lsquo;<b>==</b>&rsquo; | &lsquo;<b>~=</b>&rsquo; | <b>and</b> | <b>or</b> unop ::= &lsquo;<b>-</b>&rsquo; | <b>not</b> | &lsquo;<b>#</b>&rsquo; | &lsquo;<b>~</b>&rsquo; </pre> <p> <P CLASS="footer"> Last update: Tue Jun 26 13:16:37 -03 2018 </P> <!-- Last change: revised for Lua 5.3.5 --> </body></html>
xLua/build/lua-5.3.5/doc/manual.html/0
{ "file_path": "xLua/build/lua-5.3.5/doc/manual.html", "repo_id": "xLua", "token_count": 114787 }
2,091
/* ** $Id: ldebug.c,v 2.121.1.2 2017/07/10 17:21:50 roberto Exp $ ** Debug Interface ** See Copyright Notice in lua.h */ #define ldebug_c #define LUA_CORE #include "lprefix.h" #include <stdarg.h> #include <stddef.h> #include <string.h> #include "lua.h" #include "lapi.h" #include "lcode.h" #include "ldebug.h" #include "ldo.h" #include "lfunc.h" #include "lobject.h" #include "lopcodes.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "ltm.h" #include "lvm.h" #define noLuaClosure(f) ((f) == NULL || (f)->c.tt == LUA_TCCL) /* Active Lua function (given call info) */ #define ci_func(ci) (clLvalue((ci)->func)) static const char *funcnamefromcode (lua_State *L, CallInfo *ci, const char **name); static int currentpc (CallInfo *ci) { lua_assert(isLua(ci)); return pcRel(ci->u.l.savedpc, ci_func(ci)->p); } static int currentline (CallInfo *ci) { return getfuncline(ci_func(ci)->p, currentpc(ci)); } /* ** If function yielded, its 'func' can be in the 'extra' field. The ** next function restores 'func' to its correct value for debugging ** purposes. (It exchanges 'func' and 'extra'; so, when called again, ** after debugging, it also "re-restores" ** 'func' to its altered value. */ static void swapextra (lua_State *L) { if (L->status == LUA_YIELD) { CallInfo *ci = L->ci; /* get function that yielded */ StkId temp = ci->func; /* exchange its 'func' and 'extra' values */ ci->func = restorestack(L, ci->extra); ci->extra = savestack(L, temp); } } /* ** This function can be called asynchronously (e.g. during a signal). ** Fields 'oldpc', 'basehookcount', and 'hookcount' (set by ** 'resethookcount') are for debug only, and it is no problem if they ** get arbitrary values (causes at most one wrong hook call). 'hookmask' ** is an atomic value. We assume that pointers are atomic too (e.g., gcc ** ensures that for all platforms where it runs). Moreover, 'hook' is ** always checked before being called (see 'luaD_hook'). */ LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) { if (func == NULL || mask == 0) { /* turn off hooks? */ mask = 0; func = NULL; } if (isLua(L->ci)) L->oldpc = L->ci->u.l.savedpc; L->hook = func; L->basehookcount = count; resethookcount(L); L->hookmask = cast_byte(mask); } LUA_API lua_Hook lua_gethook (lua_State *L) { return L->hook; } LUA_API int lua_gethookmask (lua_State *L) { return L->hookmask; } LUA_API int lua_gethookcount (lua_State *L) { return L->basehookcount; } LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) { int status; CallInfo *ci; if (level < 0) return 0; /* invalid (negative) level */ lua_lock(L); for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous) level--; if (level == 0 && ci != &L->base_ci) { /* level found? */ status = 1; ar->i_ci = ci; } else status = 0; /* no such level */ lua_unlock(L); return status; } static const char *upvalname (Proto *p, int uv) { TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name); if (s == NULL) return "?"; else return getstr(s); } static const char *findvararg (CallInfo *ci, int n, StkId *pos) { int nparams = clLvalue(ci->func)->p->numparams; if (n >= cast_int(ci->u.l.base - ci->func) - nparams) return NULL; /* no such vararg */ else { *pos = ci->func + nparams + n; return "(*vararg)"; /* generic name for any vararg */ } } static const char *findlocal (lua_State *L, CallInfo *ci, int n, StkId *pos) { const char *name = NULL; StkId base; if (isLua(ci)) { if (n < 0) /* access to vararg values? */ return findvararg(ci, -n, pos); else { base = ci->u.l.base; name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci)); } } else base = ci->func + 1; if (name == NULL) { /* no 'standard' name? */ StkId limit = (ci == L->ci) ? L->top : ci->next->func; if (limit - base >= n && n > 0) /* is 'n' inside 'ci' stack? */ name = "(*temporary)"; /* generic name for any valid slot */ else return NULL; /* no name */ } *pos = base + (n - 1); return name; } LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) { const char *name; lua_lock(L); swapextra(L); if (ar == NULL) { /* information about non-active function? */ if (!isLfunction(L->top - 1)) /* not a Lua function? */ name = NULL; else /* consider live variables at function start (parameters) */ name = luaF_getlocalname(clLvalue(L->top - 1)->p, n, 0); } else { /* active function; get information through 'ar' */ StkId pos = NULL; /* to avoid warnings */ name = findlocal(L, ar->i_ci, n, &pos); if (name) { setobj2s(L, L->top, pos); api_incr_top(L); } } swapextra(L); lua_unlock(L); return name; } LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) { StkId pos = NULL; /* to avoid warnings */ const char *name; lua_lock(L); swapextra(L); name = findlocal(L, ar->i_ci, n, &pos); if (name) { setobjs2s(L, pos, L->top - 1); L->top--; /* pop value */ } swapextra(L); lua_unlock(L); return name; } static void funcinfo (lua_Debug *ar, Closure *cl) { if (noLuaClosure(cl)) { ar->source = "=[C]"; ar->linedefined = -1; ar->lastlinedefined = -1; ar->what = "C"; } else { Proto *p = cl->l.p; ar->source = p->source ? getstr(p->source) : "=?"; ar->linedefined = p->linedefined; ar->lastlinedefined = p->lastlinedefined; ar->what = (ar->linedefined == 0) ? "main" : "Lua"; } luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE); } static void collectvalidlines (lua_State *L, Closure *f) { if (noLuaClosure(f)) { setnilvalue(L->top); api_incr_top(L); } else { int i; TValue v; int *lineinfo = f->l.p->lineinfo; Table *t = luaH_new(L); /* new table to store active lines */ sethvalue(L, L->top, t); /* push it on stack */ api_incr_top(L); setbvalue(&v, 1); /* boolean 'true' to be the value of all indices */ for (i = 0; i < f->l.p->sizelineinfo; i++) /* for all lines with code */ luaH_setint(L, t, lineinfo[i], &v); /* table[line] = true */ } } static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { if (ci == NULL) /* no 'ci'? */ return NULL; /* no info */ else if (ci->callstatus & CIST_FIN) { /* is this a finalizer? */ *name = "__gc"; return "metamethod"; /* report it as such */ } /* calling function is a known Lua function? */ else if (!(ci->callstatus & CIST_TAIL) && isLua(ci->previous)) return funcnamefromcode(L, ci->previous, name); else return NULL; /* no way to find a name */ } static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar, Closure *f, CallInfo *ci) { int status = 1; for (; *what; what++) { switch (*what) { case 'S': { funcinfo(ar, f); break; } case 'l': { ar->currentline = (ci && isLua(ci)) ? currentline(ci) : -1; break; } case 'u': { ar->nups = (f == NULL) ? 0 : f->c.nupvalues; if (noLuaClosure(f)) { ar->isvararg = 1; ar->nparams = 0; } else { ar->isvararg = f->l.p->is_vararg; ar->nparams = f->l.p->numparams; } break; } case 't': { ar->istailcall = (ci) ? ci->callstatus & CIST_TAIL : 0; break; } case 'n': { ar->namewhat = getfuncname(L, ci, &ar->name); if (ar->namewhat == NULL) { ar->namewhat = ""; /* not found */ ar->name = NULL; } break; } case 'L': case 'f': /* handled by lua_getinfo */ break; default: status = 0; /* invalid option */ } } return status; } LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) { int status; Closure *cl; CallInfo *ci; StkId func; lua_lock(L); swapextra(L); if (*what == '>') { ci = NULL; func = L->top - 1; api_check(L, ttisfunction(func), "function expected"); what++; /* skip the '>' */ L->top--; /* pop function */ } else { ci = ar->i_ci; func = ci->func; lua_assert(ttisfunction(ci->func)); } cl = ttisclosure(func) ? clvalue(func) : NULL; status = auxgetinfo(L, what, ar, cl, ci); if (strchr(what, 'f')) { setobjs2s(L, L->top, func); api_incr_top(L); } swapextra(L); /* correct before option 'L', which can raise a mem. error */ if (strchr(what, 'L')) collectvalidlines(L, cl); lua_unlock(L); return status; } /* ** {====================================================== ** Symbolic Execution ** ======================================================= */ static const char *getobjname (Proto *p, int lastpc, int reg, const char **name); /* ** find a "name" for the RK value 'c' */ static void kname (Proto *p, int pc, int c, const char **name) { if (ISK(c)) { /* is 'c' a constant? */ TValue *kvalue = &p->k[INDEXK(c)]; if (ttisstring(kvalue)) { /* literal constant? */ *name = svalue(kvalue); /* it is its own name */ return; } /* else no reasonable name found */ } else { /* 'c' is a register */ const char *what = getobjname(p, pc, c, name); /* search for 'c' */ if (what && *what == 'c') { /* found a constant name? */ return; /* 'name' already filled */ } /* else no reasonable name found */ } *name = "?"; /* no reasonable name found */ } static int filterpc (int pc, int jmptarget) { if (pc < jmptarget) /* is code conditional (inside a jump)? */ return -1; /* cannot know who sets that register */ else return pc; /* current position sets that register */ } /* ** try to find last instruction before 'lastpc' that modified register 'reg' */ static int findsetreg (Proto *p, int lastpc, int reg) { int pc; int setreg = -1; /* keep last instruction that changed 'reg' */ int jmptarget = 0; /* any code before this address is conditional */ for (pc = 0; pc < lastpc; pc++) { Instruction i = p->code[pc]; OpCode op = GET_OPCODE(i); int a = GETARG_A(i); switch (op) { case OP_LOADNIL: { int b = GETARG_B(i); if (a <= reg && reg <= a + b) /* set registers from 'a' to 'a+b' */ setreg = filterpc(pc, jmptarget); break; } case OP_TFORCALL: { if (reg >= a + 2) /* affect all regs above its base */ setreg = filterpc(pc, jmptarget); break; } case OP_CALL: case OP_TAILCALL: { if (reg >= a) /* affect all registers above base */ setreg = filterpc(pc, jmptarget); break; } case OP_JMP: { int b = GETARG_sBx(i); int dest = pc + 1 + b; /* jump is forward and do not skip 'lastpc'? */ if (pc < dest && dest <= lastpc) { if (dest > jmptarget) jmptarget = dest; /* update 'jmptarget' */ } break; } default: if (testAMode(op) && reg == a) /* any instruction that set A */ setreg = filterpc(pc, jmptarget); break; } } return setreg; } static const char *getobjname (Proto *p, int lastpc, int reg, const char **name) { int pc; *name = luaF_getlocalname(p, reg + 1, lastpc); if (*name) /* is a local? */ return "local"; /* else try symbolic execution */ pc = findsetreg(p, lastpc, reg); if (pc != -1) { /* could find instruction? */ Instruction i = p->code[pc]; OpCode op = GET_OPCODE(i); switch (op) { case OP_MOVE: { int b = GETARG_B(i); /* move from 'b' to 'a' */ if (b < GETARG_A(i)) return getobjname(p, pc, b, name); /* get name for 'b' */ break; } case OP_GETTABUP: case OP_GETTABLE: { int k = GETARG_C(i); /* key index */ int t = GETARG_B(i); /* table index */ const char *vn = (op == OP_GETTABLE) /* name of indexed variable */ ? luaF_getlocalname(p, t + 1, pc) : upvalname(p, t); kname(p, pc, k, name); return (vn && strcmp(vn, LUA_ENV) == 0) ? "global" : "field"; } case OP_GETUPVAL: { *name = upvalname(p, GETARG_B(i)); return "upvalue"; } case OP_LOADK: case OP_LOADKX: { int b = (op == OP_LOADK) ? GETARG_Bx(i) : GETARG_Ax(p->code[pc + 1]); if (ttisstring(&p->k[b])) { *name = svalue(&p->k[b]); return "constant"; } break; } case OP_SELF: { int k = GETARG_C(i); /* key index */ kname(p, pc, k, name); return "method"; } default: break; /* go through to return NULL */ } } return NULL; /* could not find reasonable name */ } /* ** Try to find a name for a function based on the code that called it. ** (Only works when function was called by a Lua function.) ** Returns what the name is (e.g., "for iterator", "method", ** "metamethod") and sets '*name' to point to the name. */ static const char *funcnamefromcode (lua_State *L, CallInfo *ci, const char **name) { TMS tm = (TMS)0; /* (initial value avoids warnings) */ Proto *p = ci_func(ci)->p; /* calling function */ int pc = currentpc(ci); /* calling instruction index */ Instruction i = p->code[pc]; /* calling instruction */ if (ci->callstatus & CIST_HOOKED) { /* was it called inside a hook? */ *name = "?"; return "hook"; } switch (GET_OPCODE(i)) { case OP_CALL: case OP_TAILCALL: return getobjname(p, pc, GETARG_A(i), name); /* get function name */ case OP_TFORCALL: { /* for iterator */ *name = "for iterator"; return "for iterator"; } /* other instructions can do calls through metamethods */ case OP_SELF: case OP_GETTABUP: case OP_GETTABLE: tm = TM_INDEX; break; case OP_SETTABUP: case OP_SETTABLE: tm = TM_NEWINDEX; break; case OP_ADD: case OP_SUB: case OP_MUL: case OP_MOD: case OP_POW: case OP_DIV: case OP_IDIV: case OP_BAND: case OP_BOR: case OP_BXOR: case OP_SHL: case OP_SHR: { int offset = cast_int(GET_OPCODE(i)) - cast_int(OP_ADD); /* ORDER OP */ tm = cast(TMS, offset + cast_int(TM_ADD)); /* ORDER TM */ break; } case OP_UNM: tm = TM_UNM; break; case OP_BNOT: tm = TM_BNOT; break; case OP_LEN: tm = TM_LEN; break; case OP_CONCAT: tm = TM_CONCAT; break; case OP_EQ: tm = TM_EQ; break; case OP_LT: tm = TM_LT; break; case OP_LE: tm = TM_LE; break; default: return NULL; /* cannot find a reasonable name */ } *name = getstr(G(L)->tmname[tm]); return "metamethod"; } /* }====================================================== */ /* ** The subtraction of two potentially unrelated pointers is ** not ISO C, but it should not crash a program; the subsequent ** checks are ISO C and ensure a correct result. */ static int isinstack (CallInfo *ci, const TValue *o) { ptrdiff_t i = o - ci->u.l.base; return (0 <= i && i < (ci->top - ci->u.l.base) && ci->u.l.base + i == o); } /* ** Checks whether value 'o' came from an upvalue. (That can only happen ** with instructions OP_GETTABUP/OP_SETTABUP, which operate directly on ** upvalues.) */ static const char *getupvalname (CallInfo *ci, const TValue *o, const char **name) { LClosure *c = ci_func(ci); int i; for (i = 0; i < c->nupvalues; i++) { if (c->upvals[i]->v == o) { *name = upvalname(c->p, i); return "upvalue"; } } return NULL; } static const char *varinfo (lua_State *L, const TValue *o) { const char *name = NULL; /* to avoid warnings */ CallInfo *ci = L->ci; const char *kind = NULL; if (isLua(ci)) { kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */ if (!kind && isinstack(ci, o)) /* no? try a register */ kind = getobjname(ci_func(ci)->p, currentpc(ci), cast_int(o - ci->u.l.base), &name); } return (kind) ? luaO_pushfstring(L, " (%s '%s')", kind, name) : ""; } l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) { const char *t = luaT_objtypename(L, o); luaG_runerror(L, "attempt to %s a %s value%s", op, t, varinfo(L, o)); } l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2) { if (ttisstring(p1) || cvt2str(p1)) p1 = p2; luaG_typeerror(L, p1, "concatenate"); } l_noret luaG_opinterror (lua_State *L, const TValue *p1, const TValue *p2, const char *msg) { lua_Number temp; if (!tonumber(p1, &temp)) /* first operand is wrong? */ p2 = p1; /* now second is wrong */ luaG_typeerror(L, p2, msg); } /* ** Error when both values are convertible to numbers, but not to integers */ l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) { lua_Integer temp; if (!tointeger(p1, &temp)) p2 = p1; luaG_runerror(L, "number%s has no integer representation", varinfo(L, p2)); } l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) { const char *t1 = luaT_objtypename(L, p1); const char *t2 = luaT_objtypename(L, p2); if (strcmp(t1, t2) == 0) luaG_runerror(L, "attempt to compare two %s values", t1); else luaG_runerror(L, "attempt to compare %s with %s", t1, t2); } /* add src:line information to 'msg' */ const char *luaG_addinfo (lua_State *L, const char *msg, TString *src, int line) { char buff[LUA_IDSIZE]; if (src) luaO_chunkid(buff, getstr(src), LUA_IDSIZE); else { /* no source available; use "?" instead */ buff[0] = '?'; buff[1] = '\0'; } return luaO_pushfstring(L, "%s:%d: %s", buff, line, msg); } l_noret luaG_errormsg (lua_State *L) { if (L->errfunc != 0) { /* is there an error handling function? */ StkId errfunc = restorestack(L, L->errfunc); setobjs2s(L, L->top, L->top - 1); /* move argument */ setobjs2s(L, L->top - 1, errfunc); /* push function */ L->top++; /* assume EXTRA_STACK */ luaD_callnoyield(L, L->top - 2, 1); /* call it */ } luaD_throw(L, LUA_ERRRUN); } l_noret luaG_runerror (lua_State *L, const char *fmt, ...) { CallInfo *ci = L->ci; const char *msg; va_list argp; luaC_checkGC(L); /* error message uses memory */ va_start(argp, fmt); msg = luaO_pushvfstring(L, fmt, argp); /* format message */ va_end(argp); if (isLua(ci)) /* if Lua function, add source:line information */ luaG_addinfo(L, msg, ci_func(ci)->p->source, currentline(ci)); luaG_errormsg(L); } void luaG_traceexec (lua_State *L) { CallInfo *ci = L->ci; lu_byte mask = L->hookmask; int counthook = (--L->hookcount == 0 && (mask & LUA_MASKCOUNT)); if (counthook) resethookcount(L); /* reset count */ else if (!(mask & LUA_MASKLINE)) return; /* no line hook and count != 0; nothing to be done */ if (ci->callstatus & CIST_HOOKYIELD) { /* called hook last time? */ ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */ return; /* do not call hook again (VM yielded, so it did not move) */ } if (counthook) luaD_hook(L, LUA_HOOKCOUNT, -1); /* call count hook */ if (mask & LUA_MASKLINE) { Proto *p = ci_func(ci)->p; int npc = pcRel(ci->u.l.savedpc, p); int newline = getfuncline(p, npc); if (npc == 0 || /* call linehook when enter a new function, */ ci->u.l.savedpc <= L->oldpc || /* when jump back (loop), or when */ newline != getfuncline(p, pcRel(L->oldpc, p))) /* enter a new line */ luaD_hook(L, LUA_HOOKLINE, newline); /* call line hook */ } L->oldpc = ci->u.l.savedpc; if (L->status == LUA_YIELD) { /* did hook yield? */ if (counthook) L->hookcount = 1; /* undo decrement to zero */ ci->u.l.savedpc--; /* undo increment (resume will increment it again) */ ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */ ci->func = L->top - 1; /* protect stack below results */ luaD_throw(L, LUA_YIELD); } }
xLua/build/lua-5.3.5/src/ldebug.c/0
{ "file_path": "xLua/build/lua-5.3.5/src/ldebug.c", "repo_id": "xLua", "token_count": 9038 }
2,092
/* ** $Id: lmem.h,v 1.43.1.1 2017/04/19 17:20:42 roberto Exp $ ** Interface to Memory Manager ** See Copyright Notice in lua.h */ #ifndef lmem_h #define lmem_h #include <stddef.h> #include "llimits.h" #include "lua.h" /* ** This macro reallocs a vector 'b' from 'on' to 'n' elements, where ** each element has size 'e'. In case of arithmetic overflow of the ** product 'n'*'e', it raises an error (calling 'luaM_toobig'). Because ** 'e' is always constant, it avoids the runtime division MAX_SIZET/(e). ** ** (The macro is somewhat complex to avoid warnings: The 'sizeof' ** comparison avoids a runtime comparison when overflow cannot occur. ** The compiler should be able to optimize the real test by itself, but ** when it does it, it may give a warning about "comparison is always ** false due to limited range of data type"; the +1 tricks the compiler, ** avoiding this warning but also this optimization.) */ #define luaM_reallocv(L,b,on,n,e) \ (((sizeof(n) >= sizeof(size_t) && cast(size_t, (n)) + 1 > MAX_SIZET/(e)) \ ? luaM_toobig(L) : cast_void(0)) , \ luaM_realloc_(L, (b), (on)*(e), (n)*(e))) /* ** Arrays of chars do not need any test */ #define luaM_reallocvchar(L,b,on,n) \ cast(char *, luaM_realloc_(L, (b), (on)*sizeof(char), (n)*sizeof(char))) #define luaM_freemem(L, b, s) luaM_realloc_(L, (b), (s), 0) #define luaM_free(L, b) luaM_realloc_(L, (b), sizeof(*(b)), 0) #define luaM_freearray(L, b, n) luaM_realloc_(L, (b), (n)*sizeof(*(b)), 0) #define luaM_malloc(L,s) luaM_realloc_(L, NULL, 0, (s)) #define luaM_new(L,t) cast(t *, luaM_malloc(L, sizeof(t))) #define luaM_newvector(L,n,t) \ cast(t *, luaM_reallocv(L, NULL, 0, n, sizeof(t))) #define luaM_newobject(L,tag,s) luaM_realloc_(L, NULL, tag, (s)) #define luaM_growvector(L,v,nelems,size,t,limit,e) \ if ((nelems)+1 > (size)) \ ((v)=cast(t *, luaM_growaux_(L,v,&(size),sizeof(t),limit,e))) #define luaM_reallocvector(L, v,oldn,n,t) \ ((v)=cast(t *, luaM_reallocv(L, v, oldn, n, sizeof(t)))) LUAI_FUNC l_noret luaM_toobig (lua_State *L); /* not to be called directly */ LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize, size_t size); LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elem, int limit, const char *what); #endif
xLua/build/lua-5.3.5/src/lmem.h/0
{ "file_path": "xLua/build/lua-5.3.5/src/lmem.h", "repo_id": "xLua", "token_count": 1112 }
2,093
/* ** $Id: ltable.h,v 2.23.1.2 2018/05/24 19:39:05 roberto Exp $ ** Lua tables (hash) ** See Copyright Notice in lua.h */ #ifndef ltable_h #define ltable_h #include "lobject.h" #define gnode(t,i) (&(t)->node[i]) #define gval(n) (&(n)->i_val) #define gnext(n) ((n)->i_key.nk.next) /* 'const' to avoid wrong writings that can mess up field 'next' */ #define gkey(n) cast(const TValue*, (&(n)->i_key.tvk)) /* ** writable version of 'gkey'; allows updates to individual fields, ** but not to the whole (which has incompatible type) */ #define wgkey(n) (&(n)->i_key.nk) #define invalidateTMcache(t) ((t)->flags = 0) /* true when 't' is using 'dummynode' as its hash part */ #define isdummy(t) ((t)->lastfree == NULL) /* allocated size for hash nodes */ #define allocsizenode(t) (isdummy(t) ? 0 : sizenode(t)) /* returns the key, given the value of a table entry */ #define keyfromval(v) \ (gkey(cast(Node *, cast(char *, (v)) - offsetof(Node, i_val)))) LUAI_FUNC const TValue *luaH_getint (Table *t, lua_Integer key); LUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value); LUAI_FUNC const TValue *luaH_getshortstr (Table *t, TString *key); LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key); LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key); LUAI_FUNC TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key); LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key); LUAI_FUNC Table *luaH_new (lua_State *L); LUAI_FUNC void luaH_resize (lua_State *L, Table *t, unsigned int nasize, unsigned int nhsize); LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize); LUAI_FUNC void luaH_free (lua_State *L, Table *t); LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key); LUAI_FUNC lua_Unsigned luaH_getn (Table *t); #if defined(LUA_DEBUG) LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key); LUAI_FUNC int luaH_isdummy (const Table *t); #endif #endif
xLua/build/lua-5.3.5/src/ltable.h/0
{ "file_path": "xLua/build/lua-5.3.5/src/ltable.h", "repo_id": "xLua", "token_count": 932 }
2,094
/* ** $Id: lzio.h,v 1.31.1.1 2017/04/19 17:20:42 roberto Exp $ ** Buffered streams ** See Copyright Notice in lua.h */ #ifndef lzio_h #define lzio_h #include "lua.h" #include "lmem.h" #define EOZ (-1) /* end of stream */ typedef struct Zio ZIO; #define zgetc(z) (((z)->n--)>0 ? cast_uchar(*(z)->p++) : luaZ_fill(z)) typedef struct Mbuffer { char *buffer; size_t n; size_t buffsize; } Mbuffer; #define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->buffsize = 0) #define luaZ_buffer(buff) ((buff)->buffer) #define luaZ_sizebuffer(buff) ((buff)->buffsize) #define luaZ_bufflen(buff) ((buff)->n) #define luaZ_buffremove(buff,i) ((buff)->n -= (i)) #define luaZ_resetbuffer(buff) ((buff)->n = 0) #define luaZ_resizebuffer(L, buff, size) \ ((buff)->buffer = luaM_reallocvchar(L, (buff)->buffer, \ (buff)->buffsize, size), \ (buff)->buffsize = size) #define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0) LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data); LUAI_FUNC size_t luaZ_read (ZIO* z, void *b, size_t n); /* read next n bytes */ /* --------- Private Part ------------------ */ struct Zio { size_t n; /* bytes still unread */ const char *p; /* current position in buffer */ lua_Reader reader; /* reader function */ void *data; /* additional data */ lua_State *L; /* Lua state (for reader) */ }; LUAI_FUNC int luaZ_fill (ZIO *z); #endif
xLua/build/lua-5.3.5/src/lzio.h/0
{ "file_path": "xLua/build/lua-5.3.5/src/lzio.h", "repo_id": "xLua", "token_count": 663 }
2,095
/* ** $Id: lauxlib.c $ ** Auxiliary functions for building Lua libraries ** See Copyright Notice in lua.h */ #define lauxlib_c #define LUA_LIB #include "lprefix.h" #include <errno.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* ** This file uses only the official API of Lua. ** Any function declared here could be written as an application function. */ #include "lua.h" #include "lauxlib.h" #if !defined(MAX_SIZET) /* maximum value for size_t */ #define MAX_SIZET ((size_t)(~(size_t)0)) #endif /* ** {====================================================== ** Traceback ** ======================================================= */ #define LEVELS1 10 /* size of the first part of the stack */ #define LEVELS2 11 /* size of the second part of the stack */ /* ** Search for 'objidx' in table at index -1. ('objidx' must be an ** absolute index.) Return 1 + string at top if it found a good name. */ static int findfield (lua_State *L, int objidx, int level) { if (level == 0 || !lua_istable(L, -1)) return 0; /* not found */ lua_pushnil(L); /* start 'next' loop */ while (lua_next(L, -2)) { /* for each pair in table */ if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */ if (lua_rawequal(L, objidx, -1)) { /* found object? */ lua_pop(L, 1); /* remove value (but keep name) */ return 1; } else if (findfield(L, objidx, level - 1)) { /* try recursively */ /* stack: lib_name, lib_table, field_name (top) */ lua_pushliteral(L, "."); /* place '.' between the two names */ lua_replace(L, -3); /* (in the slot occupied by table) */ lua_concat(L, 3); /* lib_name.field_name */ return 1; } } lua_pop(L, 1); /* remove value */ } return 0; /* not found */ } /* ** Search for a name for a function in all loaded modules */ static int pushglobalfuncname (lua_State *L, lua_Debug *ar) { int top = lua_gettop(L); lua_getinfo(L, "f", ar); /* push function */ lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); if (findfield(L, top + 1, 2)) { const char *name = lua_tostring(L, -1); if (strncmp(name, LUA_GNAME ".", 3) == 0) { /* name start with '_G.'? */ lua_pushstring(L, name + 3); /* push name without prefix */ lua_remove(L, -2); /* remove original name */ } lua_copy(L, -1, top + 1); /* copy name to proper place */ lua_settop(L, top + 1); /* remove table "loaded" and name copy */ return 1; } else { lua_settop(L, top); /* remove function and global table */ return 0; } } static void pushfuncname (lua_State *L, lua_Debug *ar) { if (pushglobalfuncname(L, ar)) { /* try first a global name */ lua_pushfstring(L, "function '%s'", lua_tostring(L, -1)); lua_remove(L, -2); /* remove name */ } else if (*ar->namewhat != '\0') /* is there a name from code? */ lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */ else if (*ar->what == 'm') /* main? */ lua_pushliteral(L, "main chunk"); else if (*ar->what != 'C') /* for Lua functions, use <file:line> */ lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined); else /* nothing left... */ lua_pushliteral(L, "?"); } static int lastlevel (lua_State *L) { lua_Debug ar; int li = 1, le = 1; /* find an upper bound */ while (lua_getstack(L, le, &ar)) { li = le; le *= 2; } /* do a binary search */ while (li < le) { int m = (li + le)/2; if (lua_getstack(L, m, &ar)) li = m + 1; else le = m; } return le - 1; } LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, const char *msg, int level) { luaL_Buffer b; lua_Debug ar; int last = lastlevel(L1); int limit2show = (last - level > LEVELS1 + LEVELS2) ? LEVELS1 : -1; luaL_buffinit(L, &b); if (msg) { luaL_addstring(&b, msg); luaL_addchar(&b, '\n'); } luaL_addstring(&b, "stack traceback:"); while (lua_getstack(L1, level++, &ar)) { if (limit2show-- == 0) { /* too many levels? */ int n = last - level - LEVELS2 + 1; /* number of levels to skip */ lua_pushfstring(L, "\n\t...\t(skipping %d levels)", n); luaL_addvalue(&b); /* add warning about skip */ level += n; /* and skip to last levels */ } else { lua_getinfo(L1, "Slnt", &ar); if (ar.currentline <= 0) lua_pushfstring(L, "\n\t%s: in ", ar.short_src); else lua_pushfstring(L, "\n\t%s:%d: in ", ar.short_src, ar.currentline); luaL_addvalue(&b); pushfuncname(L, &ar); luaL_addvalue(&b); if (ar.istailcall) luaL_addstring(&b, "\n\t(...tail calls...)"); } } luaL_pushresult(&b); } /* }====================================================== */ /* ** {====================================================== ** Error-report functions ** ======================================================= */ LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) { lua_Debug ar; if (!lua_getstack(L, 0, &ar)) /* no stack frame? */ return luaL_error(L, "bad argument #%d (%s)", arg, extramsg); lua_getinfo(L, "n", &ar); if (strcmp(ar.namewhat, "method") == 0) { arg--; /* do not count 'self' */ if (arg == 0) /* error is in the self argument itself? */ return luaL_error(L, "calling '%s' on bad self (%s)", ar.name, extramsg); } if (ar.name == NULL) ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?"; return luaL_error(L, "bad argument #%d to '%s' (%s)", arg, ar.name, extramsg); } int luaL_typeerror (lua_State *L, int arg, const char *tname) { const char *msg; const char *typearg; /* name for the type of the actual argument */ if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING) typearg = lua_tostring(L, -1); /* use the given type name */ else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA) typearg = "light userdata"; /* special name for messages */ else typearg = luaL_typename(L, arg); /* standard name */ msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg); return luaL_argerror(L, arg, msg); } static void tag_error (lua_State *L, int arg, int tag) { luaL_typeerror(L, arg, lua_typename(L, tag)); } /* ** The use of 'lua_pushfstring' ensures this function does not ** need reserved stack space when called. */ LUALIB_API void luaL_where (lua_State *L, int level) { lua_Debug ar; if (lua_getstack(L, level, &ar)) { /* check function at level */ lua_getinfo(L, "Sl", &ar); /* get info about it */ if (ar.currentline > 0) { /* is there info? */ lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline); return; } } lua_pushfstring(L, ""); /* else, no information available... */ } /* ** Again, the use of 'lua_pushvfstring' ensures this function does ** not need reserved stack space when called. (At worst, it generates ** an error with "stack overflow" instead of the given message.) */ LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) { va_list argp; va_start(argp, fmt); luaL_where(L, 1); lua_pushvfstring(L, fmt, argp); va_end(argp); lua_concat(L, 2); return lua_error(L); } LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) { int en = errno; /* calls to Lua API may change this value */ if (stat) { lua_pushboolean(L, 1); return 1; } else { luaL_pushfail(L); if (fname) lua_pushfstring(L, "%s: %s", fname, strerror(en)); else lua_pushstring(L, strerror(en)); lua_pushinteger(L, en); return 3; } } #if !defined(l_inspectstat) /* { */ #if defined(LUA_USE_POSIX) #include <sys/wait.h> /* ** use appropriate macros to interpret 'pclose' return status */ #define l_inspectstat(stat,what) \ if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \ else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; } #else #define l_inspectstat(stat,what) /* no op */ #endif #endif /* } */ LUALIB_API int luaL_execresult (lua_State *L, int stat) { const char *what = "exit"; /* type of termination */ if (stat != 0 && errno != 0) /* error with an 'errno'? */ return luaL_fileresult(L, 0, NULL); else { l_inspectstat(stat, what); /* interpret result */ if (*what == 'e' && stat == 0) /* successful termination? */ lua_pushboolean(L, 1); else luaL_pushfail(L); lua_pushstring(L, what); lua_pushinteger(L, stat); return 3; /* return true/fail,what,code */ } } /* }====================================================== */ /* ** {====================================================== ** Userdata's metatable manipulation ** ======================================================= */ LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { if (luaL_getmetatable(L, tname) != LUA_TNIL) /* name already in use? */ return 0; /* leave previous value on top, but return 0 */ lua_pop(L, 1); lua_createtable(L, 0, 2); /* create metatable */ lua_pushstring(L, tname); lua_setfield(L, -2, "__name"); /* metatable.__name = tname */ lua_pushvalue(L, -1); lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */ return 1; } LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) { luaL_getmetatable(L, tname); lua_setmetatable(L, -2); } LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) { void *p = lua_touserdata(L, ud); if (p != NULL) { /* value is a userdata? */ if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ luaL_getmetatable(L, tname); /* get correct metatable */ if (!lua_rawequal(L, -1, -2)) /* not the same? */ p = NULL; /* value is a userdata with wrong metatable */ lua_pop(L, 2); /* remove both metatables */ return p; } } return NULL; /* value is not a userdata with a metatable */ } LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { void *p = luaL_testudata(L, ud, tname); luaL_argexpected(L, p != NULL, ud, tname); return p; } /* }====================================================== */ /* ** {====================================================== ** Argument check functions ** ======================================================= */ LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def, const char *const lst[]) { const char *name = (def) ? luaL_optstring(L, arg, def) : luaL_checkstring(L, arg); int i; for (i=0; lst[i]; i++) if (strcmp(lst[i], name) == 0) return i; return luaL_argerror(L, arg, lua_pushfstring(L, "invalid option '%s'", name)); } /* ** Ensures the stack has at least 'space' extra slots, raising an error ** if it cannot fulfill the request. (The error handling needs a few ** extra slots to format the error message. In case of an error without ** this extra space, Lua will generate the same 'stack overflow' error, ** but without 'msg'.) */ LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) { if (!lua_checkstack(L, space)) { if (msg) luaL_error(L, "stack overflow (%s)", msg); else luaL_error(L, "stack overflow"); } } LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) { if (lua_type(L, arg) != t) tag_error(L, arg, t); } LUALIB_API void luaL_checkany (lua_State *L, int arg) { if (lua_type(L, arg) == LUA_TNONE) luaL_argerror(L, arg, "value expected"); } LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) { const char *s = lua_tolstring(L, arg, len); if (!s) tag_error(L, arg, LUA_TSTRING); return s; } LUALIB_API const char *luaL_optlstring (lua_State *L, int arg, const char *def, size_t *len) { if (lua_isnoneornil(L, arg)) { if (len) *len = (def ? strlen(def) : 0); return def; } else return luaL_checklstring(L, arg, len); } LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) { int isnum; lua_Number d = lua_tonumberx(L, arg, &isnum); if (!isnum) tag_error(L, arg, LUA_TNUMBER); return d; } LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) { return luaL_opt(L, luaL_checknumber, arg, def); } static void interror (lua_State *L, int arg) { if (lua_isnumber(L, arg)) luaL_argerror(L, arg, "number has no integer representation"); else tag_error(L, arg, LUA_TNUMBER); } LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) { int isnum; lua_Integer d = lua_tointegerx(L, arg, &isnum); if (!isnum) { interror(L, arg); } return d; } LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg, lua_Integer def) { return luaL_opt(L, luaL_checkinteger, arg, def); } /* }====================================================== */ /* ** {====================================================== ** Generic Buffer manipulation ** ======================================================= */ /* userdata to box arbitrary data */ typedef struct UBox { void *box; size_t bsize; } UBox; static void *resizebox (lua_State *L, int idx, size_t newsize) { void *ud; lua_Alloc allocf = lua_getallocf(L, &ud); UBox *box = (UBox *)lua_touserdata(L, idx); void *temp = allocf(ud, box->box, box->bsize, newsize); if (temp == NULL && newsize > 0) { /* allocation error? */ lua_pushliteral(L, "not enough memory"); lua_error(L); /* raise a memory error */ } box->box = temp; box->bsize = newsize; return temp; } static int boxgc (lua_State *L) { resizebox(L, 1, 0); return 0; } static const luaL_Reg boxmt[] = { /* box metamethods */ {"__gc", boxgc}, {"__close", boxgc}, {NULL, NULL} }; static void newbox (lua_State *L) { UBox *box = (UBox *)lua_newuserdatauv(L, sizeof(UBox), 0); box->box = NULL; box->bsize = 0; if (luaL_newmetatable(L, "_UBOX*")) /* creating metatable? */ luaL_setfuncs(L, boxmt, 0); /* set its metamethods */ lua_setmetatable(L, -2); } /* ** check whether buffer is using a userdata on the stack as a temporary ** buffer */ #define buffonstack(B) ((B)->b != (B)->init.b) /* ** Compute new size for buffer 'B', enough to accommodate extra 'sz' ** bytes. */ static size_t newbuffsize (luaL_Buffer *B, size_t sz) { size_t newsize = B->size * 2; /* double buffer size */ if (MAX_SIZET - sz < B->n) /* overflow in (B->n + sz)? */ return luaL_error(B->L, "buffer too large"); if (newsize < B->n + sz) /* double is not big enough? */ newsize = B->n + sz; return newsize; } /* ** Returns a pointer to a free area with at least 'sz' bytes in buffer ** 'B'. 'boxidx' is the relative position in the stack where the ** buffer's box is or should be. */ static char *prepbuffsize (luaL_Buffer *B, size_t sz, int boxidx) { if (B->size - B->n >= sz) /* enough space? */ return B->b + B->n; else { lua_State *L = B->L; char *newbuff; size_t newsize = newbuffsize(B, sz); /* create larger buffer */ if (buffonstack(B)) /* buffer already has a box? */ newbuff = (char *)resizebox(L, boxidx, newsize); /* resize it */ else { /* no box yet */ lua_pushnil(L); /* reserve slot for final result */ newbox(L); /* create a new box */ /* move box (and slot) to its intended position */ lua_rotate(L, boxidx - 1, 2); lua_toclose(L, boxidx); newbuff = (char *)resizebox(L, boxidx, newsize); memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */ } B->b = newbuff; B->size = newsize; return newbuff + B->n; } } /* ** returns a pointer to a free area with at least 'sz' bytes */ LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) { return prepbuffsize(B, sz, -1); } LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) { if (l > 0) { /* avoid 'memcpy' when 's' can be NULL */ char *b = prepbuffsize(B, l, -1); memcpy(b, s, l * sizeof(char)); luaL_addsize(B, l); } } LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) { luaL_addlstring(B, s, strlen(s)); } LUALIB_API void luaL_pushresult (luaL_Buffer *B) { lua_State *L = B->L; lua_pushlstring(L, B->b, B->n); if (buffonstack(B)) { lua_copy(L, -1, -3); /* move string to reserved slot */ lua_pop(L, 2); /* pop string and box (closing the box) */ } } LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) { luaL_addsize(B, sz); luaL_pushresult(B); } /* ** 'luaL_addvalue' is the only function in the Buffer system where the ** box (if existent) is not on the top of the stack. So, instead of ** calling 'luaL_addlstring', it replicates the code using -2 as the ** last argument to 'prepbuffsize', signaling that the box is (or will ** be) bellow the string being added to the buffer. (Box creation can ** trigger an emergency GC, so we should not remove the string from the ** stack before we have the space guaranteed.) */ LUALIB_API void luaL_addvalue (luaL_Buffer *B) { lua_State *L = B->L; size_t len; const char *s = lua_tolstring(L, -1, &len); char *b = prepbuffsize(B, len, -2); memcpy(b, s, len * sizeof(char)); luaL_addsize(B, len); lua_pop(L, 1); /* pop string */ } LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) { B->L = L; B->b = B->init.b; B->n = 0; B->size = LUAL_BUFFERSIZE; } LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) { luaL_buffinit(L, B); return prepbuffsize(B, sz, -1); } /* }====================================================== */ /* ** {====================================================== ** Reference system ** ======================================================= */ /* index of free-list header */ #define freelist 0 LUALIB_API int luaL_ref (lua_State *L, int t) { int ref; if (lua_isnil(L, -1)) { lua_pop(L, 1); /* remove from stack */ return LUA_REFNIL; /* 'nil' has a unique fixed reference */ } t = lua_absindex(L, t); lua_rawgeti(L, t, freelist); /* get first free element */ ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */ lua_pop(L, 1); /* remove it from stack */ if (ref != 0) { /* any free element? */ lua_rawgeti(L, t, ref); /* remove it from list */ lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */ } else /* no free elements */ ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */ lua_rawseti(L, t, ref); return ref; } LUALIB_API void luaL_unref (lua_State *L, int t, int ref) { if (ref >= 0) { t = lua_absindex(L, t); lua_rawgeti(L, t, freelist); lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */ lua_pushinteger(L, ref); lua_rawseti(L, t, freelist); /* t[freelist] = ref */ } } /* }====================================================== */ /* ** {====================================================== ** Load functions ** ======================================================= */ typedef struct LoadF { int n; /* number of pre-read characters */ FILE *f; /* file being read */ char buff[BUFSIZ]; /* area for reading file */ } LoadF; static const char *getF (lua_State *L, void *ud, size_t *size) { LoadF *lf = (LoadF *)ud; (void)L; /* not used */ if (lf->n > 0) { /* are there pre-read characters to be read? */ *size = lf->n; /* return them (chars already in buffer) */ lf->n = 0; /* no more pre-read characters */ } else { /* read a block from file */ /* 'fread' can return > 0 *and* set the EOF flag. If next call to 'getF' called 'fread', it might still wait for user input. The next check avoids this problem. */ if (feof(lf->f)) return NULL; *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */ } return lf->buff; } static int errfile (lua_State *L, const char *what, int fnameindex) { const char *serr = strerror(errno); const char *filename = lua_tostring(L, fnameindex) + 1; lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr); lua_remove(L, fnameindex); return LUA_ERRFILE; } static int skipBOM (LoadF *lf) { const char *p = "\xEF\xBB\xBF"; /* UTF-8 BOM mark */ int c; lf->n = 0; do { c = getc(lf->f); if (c == EOF || c != *(const unsigned char *)p++) return c; lf->buff[lf->n++] = c; /* to be read by the parser */ } while (*p != '\0'); lf->n = 0; /* prefix matched; discard it */ return getc(lf->f); /* return next character */ } /* ** reads the first character of file 'f' and skips an optional BOM mark ** in its beginning plus its first line if it starts with '#'. Returns ** true if it skipped the first line. In any case, '*cp' has the ** first "valid" character of the file (after the optional BOM and ** a first-line comment). */ static int skipcomment (LoadF *lf, int *cp) { int c = *cp = skipBOM(lf); if (c == '#') { /* first line is a comment (Unix exec. file)? */ do { /* skip first line */ c = getc(lf->f); } while (c != EOF && c != '\n'); *cp = getc(lf->f); /* skip end-of-line, if present */ return 1; /* there was a comment */ } else return 0; /* no comment */ } LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename, const char *mode) { LoadF lf; int status, readstatus; int c; int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */ if (filename == NULL) { lua_pushliteral(L, "=stdin"); lf.f = stdin; } else { lua_pushfstring(L, "@%s", filename); lf.f = fopen(filename, "r"); if (lf.f == NULL) return errfile(L, "open", fnameindex); } if (skipcomment(&lf, &c)) /* read initial portion */ lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */ if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */ lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */ if (lf.f == NULL) return errfile(L, "reopen", fnameindex); skipcomment(&lf, &c); /* re-read initial portion */ } if (c != EOF) lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */ status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode); readstatus = ferror(lf.f); if (filename) fclose(lf.f); /* close file (even in case of errors) */ if (readstatus) { lua_settop(L, fnameindex); /* ignore results from 'lua_load' */ return errfile(L, "read", fnameindex); } lua_remove(L, fnameindex); return status; } typedef struct LoadS { const char *s; size_t size; } LoadS; static const char *getS (lua_State *L, void *ud, size_t *size) { LoadS *ls = (LoadS *)ud; (void)L; /* not used */ if (ls->size == 0) return NULL; *size = ls->size; ls->size = 0; return ls->s; } LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size, const char *name, const char *mode) { LoadS ls; ls.s = buff; ls.size = size; return lua_load(L, getS, &ls, name, mode); } LUALIB_API int luaL_loadstring (lua_State *L, const char *s) { return luaL_loadbuffer(L, s, strlen(s), s); } /* }====================================================== */ LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) { if (!lua_getmetatable(L, obj)) /* no metatable? */ return LUA_TNIL; else { int tt; lua_pushstring(L, event); tt = lua_rawget(L, -2); if (tt == LUA_TNIL) /* is metafield nil? */ lua_pop(L, 2); /* remove metatable and metafield */ else lua_remove(L, -2); /* remove only metatable */ return tt; /* return metafield type */ } } LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) { obj = lua_absindex(L, obj); if (luaL_getmetafield(L, obj, event) == LUA_TNIL) /* no metafield? */ return 0; lua_pushvalue(L, obj); lua_call(L, 1, 1); return 1; } LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) { lua_Integer l; int isnum; lua_len(L, idx); l = lua_tointegerx(L, -1, &isnum); if (!isnum) luaL_error(L, "object length is not an integer"); lua_pop(L, 1); /* remove object */ return l; } LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) { if (luaL_callmeta(L, idx, "__tostring")) { /* metafield? */ if (!lua_isstring(L, -1)) luaL_error(L, "'__tostring' must return a string"); } else { switch (lua_type(L, idx)) { case LUA_TNUMBER: { if (lua_isinteger(L, idx)) lua_pushfstring(L, "%I", (LUAI_UACINT)lua_tointeger(L, idx)); else lua_pushfstring(L, "%f", (LUAI_UACNUMBER)lua_tonumber(L, idx)); break; } case LUA_TSTRING: lua_pushvalue(L, idx); break; case LUA_TBOOLEAN: lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false")); break; case LUA_TNIL: lua_pushliteral(L, "nil"); break; default: { int tt = luaL_getmetafield(L, idx, "__name"); /* try name */ const char *kind = (tt == LUA_TSTRING) ? lua_tostring(L, -1) : luaL_typename(L, idx); lua_pushfstring(L, "%s: %p", kind, lua_topointer(L, idx)); if (tt != LUA_TNIL) lua_remove(L, -2); /* remove '__name' */ break; } } } return lua_tolstring(L, -1, len); } /* ** set functions from list 'l' into table at top - 'nup'; each ** function gets the 'nup' elements at the top as upvalues. ** Returns with only the table at the stack. */ LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) { luaL_checkstack(L, nup, "too many upvalues"); for (; l->name != NULL; l++) { /* fill the table with given functions */ if (l->func == NULL) /* place holder? */ lua_pushboolean(L, 0); else { int i; for (i = 0; i < nup; i++) /* copy upvalues to the top */ lua_pushvalue(L, -nup); lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */ } lua_setfield(L, -(nup + 2), l->name); } lua_pop(L, nup); /* remove upvalues */ } /* ** ensure that stack[idx][fname] has a table and push that table ** into the stack */ LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) { if (lua_getfield(L, idx, fname) == LUA_TTABLE) return 1; /* table already there */ else { lua_pop(L, 1); /* remove previous result */ idx = lua_absindex(L, idx); lua_newtable(L); lua_pushvalue(L, -1); /* copy to be left at top */ lua_setfield(L, idx, fname); /* assign new table to field */ return 0; /* false, because did not find table there */ } } /* ** Stripped-down 'require': After checking "loaded" table, calls 'openf' ** to open a module, registers the result in 'package.loaded' table and, ** if 'glb' is true, also registers the result in the global table. ** Leaves resulting module on the top. */ LUALIB_API void luaL_requiref (lua_State *L, const char *modname, lua_CFunction openf, int glb) { luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); lua_getfield(L, -1, modname); /* LOADED[modname] */ if (!lua_toboolean(L, -1)) { /* package not already loaded? */ lua_pop(L, 1); /* remove field */ lua_pushcfunction(L, openf); lua_pushstring(L, modname); /* argument to open function */ lua_call(L, 1, 1); /* call 'openf' to open module */ lua_pushvalue(L, -1); /* make copy of module (call result) */ lua_setfield(L, -3, modname); /* LOADED[modname] = module */ } lua_remove(L, -2); /* remove LOADED table */ if (glb) { lua_pushvalue(L, -1); /* copy of module */ lua_setglobal(L, modname); /* _G[modname] = module */ } } LUALIB_API void luaL_addgsub (luaL_Buffer *b, const char *s, const char *p, const char *r) { const char *wild; size_t l = strlen(p); while ((wild = strstr(s, p)) != NULL) { luaL_addlstring(b, s, wild - s); /* push prefix */ luaL_addstring(b, r); /* push replacement in place of pattern */ s = wild + l; /* continue after 'p' */ } luaL_addstring(b, s); /* push last suffix */ } LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p, const char *r) { luaL_Buffer b; luaL_buffinit(L, &b); luaL_addgsub(&b, s, p, r); luaL_pushresult(&b); return lua_tostring(L, -1); } static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { (void)ud; (void)osize; /* not used */ if (nsize == 0) { free(ptr); return NULL; } else return realloc(ptr, nsize); } static int panic (lua_State *L) { const char *msg = lua_tostring(L, -1); if (msg == NULL) msg = "error object is not a string"; lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n", msg); return 0; /* return to Lua to abort */ } /* ** Emit a warning. '*warnstate' means: ** 0 - warning system is off; ** 1 - ready to start a new message; ** 2 - previous message is to be continued. */ static void warnf (void *ud, const char *message, int tocont) { int *warnstate = (int *)ud; if (*warnstate != 2 && !tocont && *message == '@') { /* control message? */ if (strcmp(message, "@off") == 0) *warnstate = 0; else if (strcmp(message, "@on") == 0) *warnstate = 1; return; } else if (*warnstate == 0) /* warnings off? */ return; if (*warnstate == 1) /* previous message was the last? */ lua_writestringerror("%s", "Lua warning: "); /* start a new warning */ lua_writestringerror("%s", message); /* write message */ if (tocont) /* not the last part? */ *warnstate = 2; /* to be continued */ else { /* last part */ lua_writestringerror("%s", "\n"); /* finish message with end-of-line */ *warnstate = 1; /* ready to start a new message */ } } LUALIB_API lua_State *luaL_newstate (void) { lua_State *L = lua_newstate(l_alloc, NULL); if (L) { int *warnstate; /* space for warning state */ lua_atpanic(L, &panic); warnstate = (int *)lua_newuserdatauv(L, sizeof(int), 0); luaL_ref(L, LUA_REGISTRYINDEX); /* make sure it won't be collected */ *warnstate = 0; /* default is warnings off */ lua_setwarnf(L, warnf, warnstate); } return L; } LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) { lua_Number v = lua_version(L); if (sz != LUAL_NUMSIZES) /* check numeric types */ luaL_error(L, "core and library have incompatible numeric types"); else if (v != ver) luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f", (LUAI_UACNUMBER)ver, (LUAI_UACNUMBER)v); }
xLua/build/lua-5.4.1/src/lauxlib.c/0
{ "file_path": "xLua/build/lua-5.4.1/src/lauxlib.c", "repo_id": "xLua", "token_count": 12983 }
2,096
/* ** $Id: lgc.c $ ** Garbage Collector ** See Copyright Notice in lua.h */ #define lgc_c #define LUA_CORE #include "lprefix.h" #include <stdio.h> #include <string.h> #include "lua.h" #include "ldebug.h" #include "ldo.h" #include "lfunc.h" #include "lgc.h" #include "lmem.h" #include "lobject.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "ltm.h" /* ** Maximum number of elements to sweep in each single step. ** (Large enough to dissipate fixed overheads but small enough ** to allow small steps for the collector.) */ #define GCSWEEPMAX 100 /* ** Maximum number of finalizers to call in each single step. */ #define GCFINMAX 10 /* ** Cost of calling one finalizer. */ #define GCFINALIZECOST 50 /* ** The equivalent, in bytes, of one unit of "work" (visiting a slot, ** sweeping an object, etc.) */ #define WORK2MEM sizeof(TValue) /* ** macro to adjust 'pause': 'pause' is actually used like ** 'pause / PAUSEADJ' (value chosen by tests) */ #define PAUSEADJ 100 /* mask with all color bits */ #define maskcolors (bitmask(BLACKBIT) | WHITEBITS) /* mask with all GC bits */ #define maskgcbits (maskcolors | AGEBITS) /* macro to erase all color bits then set only the current white bit */ #define makewhite(g,x) \ (x->marked = cast_byte((x->marked & ~maskcolors) | luaC_white(g))) /* make an object gray (neither white nor black) */ #define set2gray(x) resetbits(x->marked, maskcolors) /* make an object black (coming from any color) */ #define set2black(x) \ (x->marked = cast_byte((x->marked & ~WHITEBITS) | bitmask(BLACKBIT))) #define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x))) #define keyiswhite(n) (keyiscollectable(n) && iswhite(gckey(n))) /* ** Protected access to objects in values */ #define gcvalueN(o) (iscollectable(o) ? gcvalue(o) : NULL) #define markvalue(g,o) { checkliveness(g->mainthread,o); \ if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); } #define markkey(g, n) { if keyiswhite(n) reallymarkobject(g,gckey(n)); } #define markobject(g,t) { if (iswhite(t)) reallymarkobject(g, obj2gco(t)); } /* ** mark an object that can be NULL (either because it is really optional, ** or it was stripped as debug info, or inside an uncompleted structure) */ #define markobjectN(g,t) { if (t) markobject(g,t); } static void reallymarkobject (global_State *g, GCObject *o); static lu_mem atomic (lua_State *L); static void entersweep (lua_State *L); /* ** {====================================================== ** Generic functions ** ======================================================= */ /* ** one after last element in a hash array */ #define gnodelast(h) gnode(h, cast_sizet(sizenode(h))) static GCObject **getgclist (GCObject *o) { switch (o->tt) { case LUA_VTABLE: return &gco2t(o)->gclist; case LUA_VLCL: return &gco2lcl(o)->gclist; case LUA_VCCL: return &gco2ccl(o)->gclist; case LUA_VTHREAD: return &gco2th(o)->gclist; case LUA_VPROTO: return &gco2p(o)->gclist; case LUA_VUSERDATA: { Udata *u = gco2u(o); lua_assert(u->nuvalue > 0); return &u->gclist; } default: lua_assert(0); return 0; } } /* ** Link a collectable object 'o' with a known type into the list 'p'. ** (Must be a macro to access the 'gclist' field in different types.) */ #define linkgclist(o,p) linkgclist_(obj2gco(o), &(o)->gclist, &(p)) static void linkgclist_ (GCObject *o, GCObject **pnext, GCObject **list) { lua_assert(!isgray(o)); /* cannot be in a gray list */ *pnext = *list; *list = o; set2gray(o); /* now it is */ } /* ** Link a generic collectable object 'o' into the list 'p'. */ #define linkobjgclist(o,p) linkgclist_(obj2gco(o), getgclist(o), &(p)) /* ** Clear keys for empty entries in tables. If entry is empty ** and its key is not marked, mark its entry as dead. This allows the ** collection of the key, but keeps its entry in the table (its removal ** could break a chain). The main feature of a dead key is that it must ** be different from any other value, to do not disturb searches. ** Other places never manipulate dead keys, because its associated empty ** value is enough to signal that the entry is logically empty. */ static void clearkey (Node *n) { lua_assert(isempty(gval(n))); if (keyiswhite(n)) setdeadkey(n); /* unused and unmarked key; remove it */ } /* ** tells whether a key or value can be cleared from a weak ** table. Non-collectable objects are never removed from weak ** tables. Strings behave as 'values', so are never removed too. for ** other objects: if really collected, cannot keep them; for objects ** being finalized, keep them in keys, but not in values */ static int iscleared (global_State *g, const GCObject *o) { if (o == NULL) return 0; /* non-collectable value */ else if (novariant(o->tt) == LUA_TSTRING) { markobject(g, o); /* strings are 'values', so are never weak */ return 0; } else return iswhite(o); } /* ** Barrier that moves collector forward, that is, marks the white object ** 'v' being pointed by the black object 'o'. In the generational ** mode, 'v' must also become old, if 'o' is old; however, it cannot ** be changed directly to OLD, because it may still point to non-old ** objects. So, it is marked as OLD0. In the next cycle it will become ** OLD1, and in the next it will finally become OLD (regular old). By ** then, any object it points to will also be old. If called in the ** incremental sweep phase, it clears the black object to white (sweep ** it) to avoid other barrier calls for this same object. (That cannot ** be done is generational mode, as its sweep does not distinguish ** whites from deads.) */ void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) { global_State *g = G(L); lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o)); if (keepinvariant(g)) { /* must keep invariant? */ reallymarkobject(g, v); /* restore invariant */ if (isold(o)) { lua_assert(!isold(v)); /* white object could not be old */ setage(v, G_OLD0); /* restore generational invariant */ } } else { /* sweep phase */ lua_assert(issweepphase(g)); if (g->gckind == KGC_INC) /* incremental mode? */ makewhite(g, o); /* mark 'o' as white to avoid other barriers */ } } /* ** barrier that moves collector backward, that is, mark the black object ** pointing to a white object as gray again. */ void luaC_barrierback_ (lua_State *L, GCObject *o) { global_State *g = G(L); lua_assert(isblack(o) && !isdead(g, o)); lua_assert((g->gckind == KGC_GEN) == (isold(o) && getage(o) != G_TOUCHED1)); if (getage(o) == G_TOUCHED2) /* already in gray list? */ set2gray(o); /* make it gray to become touched1 */ else /* link it in 'grayagain' and paint it gray */ linkobjgclist(o, g->grayagain); if (isold(o)) /* generational mode? */ setage(o, G_TOUCHED1); /* touched in current cycle */ } void luaC_fix (lua_State *L, GCObject *o) { global_State *g = G(L); lua_assert(g->allgc == o); /* object must be 1st in 'allgc' list! */ set2gray(o); /* they will be gray forever */ setage(o, G_OLD); /* and old forever */ g->allgc = o->next; /* remove object from 'allgc' list */ o->next = g->fixedgc; /* link it to 'fixedgc' list */ g->fixedgc = o; } /* ** create a new collectable object (with given type and size) and link ** it to 'allgc' list. */ GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) { global_State *g = G(L); GCObject *o = cast(GCObject *, luaM_newobject(L, novariant(tt), sz)); o->marked = luaC_white(g); o->tt = tt; o->next = g->allgc; g->allgc = o; return o; } /* }====================================================== */ /* ** {====================================================== ** Mark functions ** ======================================================= */ /* ** Mark an object. Userdata with no user values, strings, and closed ** upvalues are visited and turned black here. Open upvalues are ** already indirectly linked through their respective threads in the ** 'twups' list, so they don't go to the gray list; nevertheless, they ** are kept gray to avoid barriers, as their values will be revisited ** by the thread or by 'remarkupvals'. Other objects are added to the ** gray list to be visited (and turned black) later. Both userdata and ** upvalues can call this function recursively, but this recursion goes ** for at most two levels: An upvalue cannot refer to another upvalue ** (only closures can), and a userdata's metatable must be a table. */ static void reallymarkobject (global_State *g, GCObject *o) { switch (o->tt) { case LUA_VSHRSTR: case LUA_VLNGSTR: { set2black(o); /* nothing to visit */ break; } case LUA_VUPVAL: { UpVal *uv = gco2upv(o); if (upisopen(uv)) set2gray(uv); /* open upvalues are kept gray */ else set2black(o); /* closed upvalues are visited here */ markvalue(g, uv->v); /* mark its content */ break; } case LUA_VUSERDATA: { Udata *u = gco2u(o); if (u->nuvalue == 0) { /* no user values? */ markobjectN(g, u->metatable); /* mark its metatable */ set2black(o); /* nothing else to mark */ break; } /* else... */ } /* FALLTHROUGH */ case LUA_VLCL: case LUA_VCCL: case LUA_VTABLE: case LUA_VTHREAD: case LUA_VPROTO: { linkobjgclist(o, g->gray); /* to be visited later */ break; } default: lua_assert(0); break; } } /* ** mark metamethods for basic types */ static void markmt (global_State *g) { int i; for (i=0; i < LUA_NUMTAGS; i++) markobjectN(g, g->mt[i]); } /* ** mark all objects in list of being-finalized */ static lu_mem markbeingfnz (global_State *g) { GCObject *o; lu_mem count = 0; for (o = g->tobefnz; o != NULL; o = o->next) { count++; markobject(g, o); } return count; } /* ** For each non-marked thread, simulates a barrier between each open ** upvalue and its value. (If the thread is collected, the value will be ** assigned to the upvalue, but then it can be too late for the barrier ** to act. The "barrier" does not need to check colors: A non-marked ** thread must be young; upvalues cannot be older than their threads; so ** any visited upvalue must be young too.) Also removes the thread from ** the list, as it was already visited. Removes also threads with no ** upvalues, as they have nothing to be checked. (If the thread gets an ** upvalue later, it will be linked in the list again.) */ static int remarkupvals (global_State *g) { lua_State *thread; lua_State **p = &g->twups; int work = 0; /* estimate of how much work was done here */ while ((thread = *p) != NULL) { work++; if (!iswhite(thread) && thread->openupval != NULL) p = &thread->twups; /* keep marked thread with upvalues in the list */ else { /* thread is not marked or without upvalues */ UpVal *uv; lua_assert(!isold(thread) || thread->openupval == NULL); *p = thread->twups; /* remove thread from the list */ thread->twups = thread; /* mark that it is out of list */ for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) { lua_assert(getage(uv) <= getage(thread)); work++; if (!iswhite(uv)) { /* upvalue already visited? */ lua_assert(upisopen(uv) && isgray(uv)); markvalue(g, uv->v); /* mark its value */ } } } } return work; } static void cleargraylists (global_State *g) { g->gray = g->grayagain = NULL; g->weak = g->allweak = g->ephemeron = NULL; } /* ** mark root set and reset all gray lists, to start a new collection */ static void restartcollection (global_State *g) { cleargraylists(g); markobject(g, g->mainthread); markvalue(g, &g->l_registry); markmt(g); markbeingfnz(g); /* mark any finalizing object left from previous cycle */ } /* }====================================================== */ /* ** {====================================================== ** Traverse functions ** ======================================================= */ /* ** Check whether object 'o' should be kept in the 'grayagain' list for ** post-processing by 'correctgraylist'. (It could put all old objects ** in the list and leave all the work to 'correctgraylist', but it is ** more efficient to avoid adding elements that will be removed.) Only ** TOUCHED1 objects need to be in the list. TOUCHED2 doesn't need to go ** back to a gray list, but then it must become OLD. (That is what ** 'correctgraylist' does when it finds a TOUCHED2 object.) */ static void genlink (global_State *g, GCObject *o) { lua_assert(isblack(o)); if (getage(o) == G_TOUCHED1) { /* touched in this cycle? */ linkobjgclist(o, g->grayagain); /* link it back in 'grayagain' */ } /* everything else do not need to be linked back */ else if (getage(o) == G_TOUCHED2) changeage(o, G_TOUCHED2, G_OLD); /* advance age */ } /* ** Traverse a table with weak values and link it to proper list. During ** propagate phase, keep it in 'grayagain' list, to be revisited in the ** atomic phase. In the atomic phase, if table has any white value, ** put it in 'weak' list, to be cleared. */ static void traverseweakvalue (global_State *g, Table *h) { Node *n, *limit = gnodelast(h); /* if there is array part, assume it may have white values (it is not worth traversing it now just to check) */ int hasclears = (h->alimit > 0); for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */ if (isempty(gval(n))) /* entry is empty? */ clearkey(n); /* clear its key */ else { lua_assert(!keyisnil(n)); markkey(g, n); if (!hasclears && iscleared(g, gcvalueN(gval(n)))) /* a white value? */ hasclears = 1; /* table will have to be cleared */ } } if (g->gcstate == GCSatomic && hasclears) linkgclist(h, g->weak); /* has to be cleared later */ else linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */ } /* ** Traverse an ephemeron table and link it to proper list. Returns true ** iff any object was marked during this traversal (which implies that ** convergence has to continue). During propagation phase, keep table ** in 'grayagain' list, to be visited again in the atomic phase. In ** the atomic phase, if table has any white->white entry, it has to ** be revisited during ephemeron convergence (as that key may turn ** black). Otherwise, if it has any white key, table has to be cleared ** (in the atomic phase). In generational mode, some tables ** must be kept in some gray list for post-processing; this is done ** by 'genlink'. */ static int traverseephemeron (global_State *g, Table *h, int inv) { int marked = 0; /* true if an object is marked in this traversal */ int hasclears = 0; /* true if table has white keys */ int hasww = 0; /* true if table has entry "white-key -> white-value" */ unsigned int i; unsigned int asize = luaH_realasize(h); unsigned int nsize = sizenode(h); /* traverse array part */ for (i = 0; i < asize; i++) { if (valiswhite(&h->array[i])) { marked = 1; reallymarkobject(g, gcvalue(&h->array[i])); } } /* traverse hash part; if 'inv', traverse descending (see 'convergeephemerons') */ for (i = 0; i < nsize; i++) { Node *n = inv ? gnode(h, nsize - 1 - i) : gnode(h, i); if (isempty(gval(n))) /* entry is empty? */ clearkey(n); /* clear its key */ else if (iscleared(g, gckeyN(n))) { /* key is not marked (yet)? */ hasclears = 1; /* table must be cleared */ if (valiswhite(gval(n))) /* value not marked yet? */ hasww = 1; /* white-white entry */ } else if (valiswhite(gval(n))) { /* value not marked yet? */ marked = 1; reallymarkobject(g, gcvalue(gval(n))); /* mark it now */ } } /* link table into proper list */ if (g->gcstate == GCSpropagate) linkgclist(h, g->grayagain); /* must retraverse it in atomic phase */ else if (hasww) /* table has white->white entries? */ linkgclist(h, g->ephemeron); /* have to propagate again */ else if (hasclears) /* table has white keys? */ linkgclist(h, g->allweak); /* may have to clean white keys */ else genlink(g, obj2gco(h)); /* check whether collector still needs to see it */ return marked; } static void traversestrongtable (global_State *g, Table *h) { Node *n, *limit = gnodelast(h); unsigned int i; unsigned int asize = luaH_realasize(h); for (i = 0; i < asize; i++) /* traverse array part */ markvalue(g, &h->array[i]); for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */ if (isempty(gval(n))) /* entry is empty? */ clearkey(n); /* clear its key */ else { lua_assert(!keyisnil(n)); markkey(g, n); markvalue(g, gval(n)); } } genlink(g, obj2gco(h)); } static lu_mem traversetable (global_State *g, Table *h) { const char *weakkey, *weakvalue; const TValue *mode = gfasttm(g, h->metatable, TM_MODE); markobjectN(g, h->metatable); if (mode && ttisstring(mode) && /* is there a weak mode? */ (cast_void(weakkey = strchr(svalue(mode), 'k')), cast_void(weakvalue = strchr(svalue(mode), 'v')), (weakkey || weakvalue))) { /* is really weak? */ if (!weakkey) /* strong keys? */ traverseweakvalue(g, h); else if (!weakvalue) /* strong values? */ traverseephemeron(g, h, 0); else /* all weak */ linkgclist(h, g->allweak); /* nothing to traverse now */ } else /* not weak */ traversestrongtable(g, h); return 1 + h->alimit + 2 * allocsizenode(h); } static int traverseudata (global_State *g, Udata *u) { int i; markobjectN(g, u->metatable); /* mark its metatable */ for (i = 0; i < u->nuvalue; i++) markvalue(g, &u->uv[i].uv); genlink(g, obj2gco(u)); return 1 + u->nuvalue; } /* ** Traverse a prototype. (While a prototype is being build, its ** arrays can be larger than needed; the extra slots are filled with ** NULL, so the use of 'markobjectN') */ static int traverseproto (global_State *g, Proto *f) { int i; markobjectN(g, f->source); for (i = 0; i < f->sizek; i++) /* mark literals */ markvalue(g, &f->k[i]); for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */ markobjectN(g, f->upvalues[i].name); for (i = 0; i < f->sizep; i++) /* mark nested protos */ markobjectN(g, f->p[i]); for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */ markobjectN(g, f->locvars[i].varname); return 1 + f->sizek + f->sizeupvalues + f->sizep + f->sizelocvars; } static int traverseCclosure (global_State *g, CClosure *cl) { int i; for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */ markvalue(g, &cl->upvalue[i]); return 1 + cl->nupvalues; } /* ** Traverse a Lua closure, marking its prototype and its upvalues. ** (Both can be NULL while closure is being created.) */ static int traverseLclosure (global_State *g, LClosure *cl) { int i; markobjectN(g, cl->p); /* mark its prototype */ for (i = 0; i < cl->nupvalues; i++) { /* visit its upvalues */ UpVal *uv = cl->upvals[i]; markobjectN(g, uv); /* mark upvalue */ } return 1 + cl->nupvalues; } /* ** Traverse a thread, marking the elements in the stack up to its top ** and cleaning the rest of the stack in the final traversal. That ** ensures that the entire stack have valid (non-dead) objects. ** Threads have no barriers. In gen. mode, old threads must be visited ** at every cycle, because they might point to young objects. In inc. ** mode, the thread can still be modified before the end of the cycle, ** and therefore it must be visited again in the atomic phase. To ensure ** these visits, threads must return to a gray list if they are not new ** (which can only happen in generational mode) or if the traverse is in ** the propagate phase (which can only happen in incremental mode). */ static int traversethread (global_State *g, lua_State *th) { UpVal *uv; StkId o = th->stack; if (isold(th) || g->gcstate == GCSpropagate) linkgclist(th, g->grayagain); /* insert into 'grayagain' list */ if (o == NULL) return 1; /* stack not completely built yet */ lua_assert(g->gcstate == GCSatomic || th->openupval == NULL || isintwups(th)); for (; o < th->top; o++) /* mark live elements in the stack */ markvalue(g, s2v(o)); for (uv = th->openupval; uv != NULL; uv = uv->u.open.next) markobject(g, uv); /* open upvalues cannot be collected */ if (g->gcstate == GCSatomic) { /* final traversal? */ StkId lim = th->stack + th->stacksize; /* real end of stack */ for (; o < lim; o++) /* clear not-marked stack slice */ setnilvalue(s2v(o)); /* 'remarkupvals' may have removed thread from 'twups' list */ if (!isintwups(th) && th->openupval != NULL) { th->twups = g->twups; /* link it back to the list */ g->twups = th; } } else if (!g->gcemergency) luaD_shrinkstack(th); /* do not change stack in emergency cycle */ return 1 + th->stacksize; } /* ** traverse one gray object, turning it to black. */ static lu_mem propagatemark (global_State *g) { GCObject *o = g->gray; nw2black(o); g->gray = *getgclist(o); /* remove from 'gray' list */ switch (o->tt) { case LUA_VTABLE: return traversetable(g, gco2t(o)); case LUA_VUSERDATA: return traverseudata(g, gco2u(o)); case LUA_VLCL: return traverseLclosure(g, gco2lcl(o)); case LUA_VCCL: return traverseCclosure(g, gco2ccl(o)); case LUA_VPROTO: return traverseproto(g, gco2p(o)); case LUA_VTHREAD: return traversethread(g, gco2th(o)); default: lua_assert(0); return 0; } } static lu_mem propagateall (global_State *g) { lu_mem tot = 0; while (g->gray) tot += propagatemark(g); return tot; } /* ** Traverse all ephemeron tables propagating marks from keys to values. ** Repeat until it converges, that is, nothing new is marked. 'dir' ** inverts the direction of the traversals, trying to speed up ** convergence on chains in the same table. ** */ static void convergeephemerons (global_State *g) { int changed; int dir = 0; do { GCObject *w; GCObject *next = g->ephemeron; /* get ephemeron list */ g->ephemeron = NULL; /* tables may return to this list when traversed */ changed = 0; while ((w = next) != NULL) { /* for each ephemeron table */ Table *h = gco2t(w); next = h->gclist; /* list is rebuilt during loop */ nw2black(h); /* out of the list (for now) */ if (traverseephemeron(g, h, dir)) { /* marked some value? */ propagateall(g); /* propagate changes */ changed = 1; /* will have to revisit all ephemeron tables */ } } dir = !dir; /* invert direction next time */ } while (changed); /* repeat until no more changes */ } /* }====================================================== */ /* ** {====================================================== ** Sweep Functions ** ======================================================= */ /* ** clear entries with unmarked keys from all weaktables in list 'l' */ static void clearbykeys (global_State *g, GCObject *l) { for (; l; l = gco2t(l)->gclist) { Table *h = gco2t(l); Node *limit = gnodelast(h); Node *n; for (n = gnode(h, 0); n < limit; n++) { if (iscleared(g, gckeyN(n))) /* unmarked key? */ setempty(gval(n)); /* remove entry */ if (isempty(gval(n))) /* is entry empty? */ clearkey(n); /* clear its key */ } } } /* ** clear entries with unmarked values from all weaktables in list 'l' up ** to element 'f' */ static void clearbyvalues (global_State *g, GCObject *l, GCObject *f) { for (; l != f; l = gco2t(l)->gclist) { Table *h = gco2t(l); Node *n, *limit = gnodelast(h); unsigned int i; unsigned int asize = luaH_realasize(h); for (i = 0; i < asize; i++) { TValue *o = &h->array[i]; if (iscleared(g, gcvalueN(o))) /* value was collected? */ setempty(o); /* remove entry */ } for (n = gnode(h, 0); n < limit; n++) { if (iscleared(g, gcvalueN(gval(n)))) /* unmarked value? */ setempty(gval(n)); /* remove entry */ if (isempty(gval(n))) /* is entry empty? */ clearkey(n); /* clear its key */ } } } static void freeupval (lua_State *L, UpVal *uv) { if (upisopen(uv)) luaF_unlinkupval(uv); luaM_free(L, uv); } static void freeobj (lua_State *L, GCObject *o) { switch (o->tt) { case LUA_VPROTO: luaF_freeproto(L, gco2p(o)); break; case LUA_VUPVAL: freeupval(L, gco2upv(o)); break; case LUA_VLCL: luaM_freemem(L, o, sizeLclosure(gco2lcl(o)->nupvalues)); break; case LUA_VCCL: luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues)); break; case LUA_VTABLE: luaH_free(L, gco2t(o)); break; case LUA_VTHREAD: luaE_freethread(L, gco2th(o)); break; case LUA_VUSERDATA: { Udata *u = gco2u(o); luaM_freemem(L, o, sizeudata(u->nuvalue, u->len)); break; } case LUA_VSHRSTR: luaS_remove(L, gco2ts(o)); /* remove it from hash table */ luaM_freemem(L, o, sizelstring(gco2ts(o)->shrlen)); break; case LUA_VLNGSTR: luaM_freemem(L, o, sizelstring(gco2ts(o)->u.lnglen)); break; default: lua_assert(0); } } /* ** sweep at most 'countin' elements from a list of GCObjects erasing dead ** objects, where a dead object is one marked with the old (non current) ** white; change all non-dead objects back to white, preparing for next ** collection cycle. Return where to continue the traversal or NULL if ** list is finished. ('*countout' gets the number of elements traversed.) */ static GCObject **sweeplist (lua_State *L, GCObject **p, int countin, int *countout) { global_State *g = G(L); int ow = otherwhite(g); int i; int white = luaC_white(g); /* current white */ for (i = 0; *p != NULL && i < countin; i++) { GCObject *curr = *p; int marked = curr->marked; if (isdeadm(ow, marked)) { /* is 'curr' dead? */ *p = curr->next; /* remove 'curr' from list */ freeobj(L, curr); /* erase 'curr' */ } else { /* change mark to 'white' */ curr->marked = cast_byte((marked & ~maskgcbits) | white); p = &curr->next; /* go to next element */ } } if (countout) *countout = i; /* number of elements traversed */ return (*p == NULL) ? NULL : p; } /* ** sweep a list until a live object (or end of list) */ static GCObject **sweeptolive (lua_State *L, GCObject **p) { GCObject **old = p; do { p = sweeplist(L, p, 1, NULL); } while (p == old); return p; } /* }====================================================== */ /* ** {====================================================== ** Finalization ** ======================================================= */ /* ** If possible, shrink string table. */ static void checkSizes (lua_State *L, global_State *g) { if (!g->gcemergency) { if (g->strt.nuse < g->strt.size / 4) { /* string table too big? */ l_mem olddebt = g->GCdebt; luaS_resize(L, g->strt.size / 2); g->GCestimate += g->GCdebt - olddebt; /* correct estimate */ } } } /* ** Get the next udata to be finalized from the 'tobefnz' list, and ** link it back into the 'allgc' list. */ static GCObject *udata2finalize (global_State *g) { GCObject *o = g->tobefnz; /* get first element */ lua_assert(tofinalize(o)); g->tobefnz = o->next; /* remove it from 'tobefnz' list */ o->next = g->allgc; /* return it to 'allgc' list */ g->allgc = o; resetbit(o->marked, FINALIZEDBIT); /* object is "normal" again */ if (issweepphase(g)) makewhite(g, o); /* "sweep" object */ else if (getage(o) == G_OLD1) g->firstold1 = o; /* it is the first OLD1 object in the list */ return o; } static void dothecall (lua_State *L, void *ud) { UNUSED(ud); luaD_callnoyield(L, L->top - 2, 0); } static void GCTM (lua_State *L) { global_State *g = G(L); const TValue *tm; TValue v; lua_assert(!g->gcemergency); setgcovalue(L, &v, udata2finalize(g)); tm = luaT_gettmbyobj(L, &v, TM_GC); if (!notm(tm)) { /* is there a finalizer? */ int status; lu_byte oldah = L->allowhook; int running = g->gcrunning; L->allowhook = 0; /* stop debug hooks during GC metamethod */ g->gcrunning = 0; /* avoid GC steps */ setobj2s(L, L->top++, tm); /* push finalizer... */ setobj2s(L, L->top++, &v); /* ... and its argument */ L->ci->callstatus |= CIST_FIN; /* will run a finalizer */ status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0); L->ci->callstatus &= ~CIST_FIN; /* not running a finalizer anymore */ L->allowhook = oldah; /* restore hooks */ g->gcrunning = running; /* restore state */ if (unlikely(status != LUA_OK)) { /* error while running __gc? */ luaE_warnerror(L, "__gc metamethod"); L->top--; /* pops error object */ } } } /* ** Call a few finalizers */ static int runafewfinalizers (lua_State *L, int n) { global_State *g = G(L); int i; for (i = 0; i < n && g->tobefnz; i++) GCTM(L); /* call one finalizer */ return i; } /* ** call all pending finalizers */ static void callallpendingfinalizers (lua_State *L) { global_State *g = G(L); while (g->tobefnz) GCTM(L); } /* ** find last 'next' field in list 'p' list (to add elements in its end) */ static GCObject **findlast (GCObject **p) { while (*p != NULL) p = &(*p)->next; return p; } /* ** Move all unreachable objects (or 'all' objects) that need ** finalization from list 'finobj' to list 'tobefnz' (to be finalized). ** (Note that objects after 'finobjold1' cannot be white, so they ** don't need to be traversed. In incremental mode, 'finobjold1' is NULL, ** so the whole list is traversed.) */ static void separatetobefnz (global_State *g, int all) { GCObject *curr; GCObject **p = &g->finobj; GCObject **lastnext = findlast(&g->tobefnz); while ((curr = *p) != g->finobjold1) { /* traverse all finalizable objects */ lua_assert(tofinalize(curr)); if (!(iswhite(curr) || all)) /* not being collected? */ p = &curr->next; /* don't bother with it */ else { if (curr == g->finobjsur) /* removing 'finobjsur'? */ g->finobjsur = curr->next; /* correct it */ *p = curr->next; /* remove 'curr' from 'finobj' list */ curr->next = *lastnext; /* link at the end of 'tobefnz' list */ *lastnext = curr; lastnext = &curr->next; } } } /* ** If pointer 'p' points to 'o', move it to the next element. */ static void checkpointer (GCObject **p, GCObject *o) { if (o == *p) *p = o->next; } /* ** Correct pointers to objects inside 'allgc' list when ** object 'o' is being removed from the list. */ static void correctpointers (global_State *g, GCObject *o) { checkpointer(&g->survival, o); checkpointer(&g->old1, o); checkpointer(&g->reallyold, o); checkpointer(&g->firstold1, o); } /* ** if object 'o' has a finalizer, remove it from 'allgc' list (must ** search the list to find it) and link it in 'finobj' list. */ void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) { global_State *g = G(L); if (tofinalize(o) || /* obj. is already marked... */ gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */ return; /* nothing to be done */ else { /* move 'o' to 'finobj' list */ GCObject **p; if (issweepphase(g)) { makewhite(g, o); /* "sweep" object 'o' */ if (g->sweepgc == &o->next) /* should not remove 'sweepgc' object */ g->sweepgc = sweeptolive(L, g->sweepgc); /* change 'sweepgc' */ } else correctpointers(g, o); /* search for pointer pointing to 'o' */ for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ } *p = o->next; /* remove 'o' from 'allgc' list */ o->next = g->finobj; /* link it in 'finobj' list */ g->finobj = o; l_setbit(o->marked, FINALIZEDBIT); /* mark it as such */ } } /* }====================================================== */ /* ** {====================================================== ** Generational Collector ** ======================================================= */ static void setpause (global_State *g); /* ** Sweep a list of objects to enter generational mode. Deletes dead ** objects and turns the non dead to old. All non-dead threads---which ** are now old---must be in a gray list. Everything else is not in a ** gray list. Open upvalues are also kept gray. */ static void sweep2old (lua_State *L, GCObject **p) { GCObject *curr; global_State *g = G(L); while ((curr = *p) != NULL) { if (iswhite(curr)) { /* is 'curr' dead? */ lua_assert(isdead(g, curr)); *p = curr->next; /* remove 'curr' from list */ freeobj(L, curr); /* erase 'curr' */ } else { /* all surviving objects become old */ setage(curr, G_OLD); if (curr->tt == LUA_VTHREAD) { /* threads must be watched */ lua_State *th = gco2th(curr); linkgclist(th, g->grayagain); /* insert into 'grayagain' list */ } else if (curr->tt == LUA_VUPVAL && upisopen(gco2upv(curr))) set2gray(curr); /* open upvalues are always gray */ else /* everything else is black */ nw2black(curr); p = &curr->next; /* go to next element */ } } } /* ** Sweep for generational mode. Delete dead objects. (Because the ** collection is not incremental, there are no "new white" objects ** during the sweep. So, any white object must be dead.) For ** non-dead objects, advance their ages and clear the color of ** new objects. (Old objects keep their colors.) ** The ages of G_TOUCHED1 and G_TOUCHED2 objects cannot be advanced ** here, because these old-generation objects are usually not swept ** here. They will all be advanced in 'correctgraylist'. That function ** will also remove objects turned white here from any gray list. */ static GCObject **sweepgen (lua_State *L, global_State *g, GCObject **p, GCObject *limit, GCObject **pfirstold1) { static const lu_byte nextage[] = { G_SURVIVAL, /* from G_NEW */ G_OLD1, /* from G_SURVIVAL */ G_OLD1, /* from G_OLD0 */ G_OLD, /* from G_OLD1 */ G_OLD, /* from G_OLD (do not change) */ G_TOUCHED1, /* from G_TOUCHED1 (do not change) */ G_TOUCHED2 /* from G_TOUCHED2 (do not change) */ }; int white = luaC_white(g); GCObject *curr; while ((curr = *p) != limit) { if (iswhite(curr)) { /* is 'curr' dead? */ lua_assert(!isold(curr) && isdead(g, curr)); *p = curr->next; /* remove 'curr' from list */ freeobj(L, curr); /* erase 'curr' */ } else { /* correct mark and age */ if (getage(curr) == G_NEW) { /* new objects go back to white */ int marked = curr->marked & ~maskgcbits; /* erase GC bits */ curr->marked = cast_byte(marked | G_SURVIVAL | white); } else { /* all other objects will be old, and so keep their color */ setage(curr, nextage[getage(curr)]); if (getage(curr) == G_OLD1 && *pfirstold1 == NULL) *pfirstold1 = curr; /* first OLD1 object in the list */ } p = &curr->next; /* go to next element */ } } return p; } /* ** Traverse a list making all its elements white and clearing their ** age. In incremental mode, all objects are 'new' all the time, ** except for fixed strings (which are always old). */ static void whitelist (global_State *g, GCObject *p) { int white = luaC_white(g); for (; p != NULL; p = p->next) p->marked = cast_byte((p->marked & ~maskgcbits) | white); } /* ** Correct a list of gray objects. Return pointer to where rest of the ** list should be linked. ** Because this correction is done after sweeping, young objects might ** be turned white and still be in the list. They are only removed. ** 'TOUCHED1' objects are advanced to 'TOUCHED2' and remain on the list; ** Non-white threads also remain on the list; 'TOUCHED2' objects become ** regular old; they and anything else are removed from the list. */ static GCObject **correctgraylist (GCObject **p) { GCObject *curr; while ((curr = *p) != NULL) { GCObject **next = getgclist(curr); if (iswhite(curr)) goto remove; /* remove all white objects */ else if (getage(curr) == G_TOUCHED1) { /* touched in this cycle? */ lua_assert(isgray(curr)); nw2black(curr); /* make it black, for next barrier */ changeage(curr, G_TOUCHED1, G_TOUCHED2); goto remain; /* keep it in the list and go to next element */ } else if (curr->tt == LUA_VTHREAD) { lua_assert(isgray(curr)); goto remain; /* keep non-white threads on the list */ } else { /* everything else is removed */ lua_assert(isold(curr)); /* young objects should be white here */ if (getage(curr) == G_TOUCHED2) /* advance from TOUCHED2... */ changeage(curr, G_TOUCHED2, G_OLD); /* ... to OLD */ nw2black(curr); /* make object black (to be removed) */ goto remove; } remove: *p = *next; continue; remain: p = next; continue; } return p; } /* ** Correct all gray lists, coalescing them into 'grayagain'. */ static void correctgraylists (global_State *g) { GCObject **list = correctgraylist(&g->grayagain); *list = g->weak; g->weak = NULL; list = correctgraylist(list); *list = g->allweak; g->allweak = NULL; list = correctgraylist(list); *list = g->ephemeron; g->ephemeron = NULL; correctgraylist(list); } /* ** Mark black 'OLD1' objects when starting a new young collection. ** Gray objects are already in some gray list, and so will be visited ** in the atomic step. */ static void markold (global_State *g, GCObject *from, GCObject *to) { GCObject *p; for (p = from; p != to; p = p->next) { if (getage(p) == G_OLD1) { lua_assert(!iswhite(p)); changeage(p, G_OLD1, G_OLD); /* now they are old */ if (isblack(p)) reallymarkobject(g, p); } } } /* ** Finish a young-generation collection. */ static void finishgencycle (lua_State *L, global_State *g) { correctgraylists(g); checkSizes(L, g); g->gcstate = GCSpropagate; /* skip restart */ if (!g->gcemergency) callallpendingfinalizers(L); } /* ** Does a young collection. First, mark 'OLD1' objects. Then does the ** atomic step. Then, sweep all lists and advance pointers. Finally, ** finish the collection. */ static void youngcollection (lua_State *L, global_State *g) { GCObject **psurvival; /* to point to first non-dead survival object */ GCObject *dummy; /* dummy out parameter to 'sweepgen' */ lua_assert(g->gcstate == GCSpropagate); if (g->firstold1) { /* are there regular OLD1 objects? */ markold(g, g->firstold1, g->reallyold); /* mark them */ g->firstold1 = NULL; /* no more OLD1 objects (for now) */ } markold(g, g->finobj, g->finobjrold); markold(g, g->tobefnz, NULL); atomic(L); /* sweep nursery and get a pointer to its last live element */ g->gcstate = GCSswpallgc; psurvival = sweepgen(L, g, &g->allgc, g->survival, &g->firstold1); /* sweep 'survival' */ sweepgen(L, g, psurvival, g->old1, &g->firstold1); g->reallyold = g->old1; g->old1 = *psurvival; /* 'survival' survivals are old now */ g->survival = g->allgc; /* all news are survivals */ /* repeat for 'finobj' lists */ dummy = NULL; /* no 'firstold1' optimization for 'finobj' lists */ psurvival = sweepgen(L, g, &g->finobj, g->finobjsur, &dummy); /* sweep 'survival' */ sweepgen(L, g, psurvival, g->finobjold1, &dummy); g->finobjrold = g->finobjold1; g->finobjold1 = *psurvival; /* 'survival' survivals are old now */ g->finobjsur = g->finobj; /* all news are survivals */ sweepgen(L, g, &g->tobefnz, NULL, &dummy); finishgencycle(L, g); } /* ** Clears all gray lists, sweeps objects, and prepare sublists to enter ** generational mode. The sweeps remove dead objects and turn all ** surviving objects to old. Threads go back to 'grayagain'; everything ** else is turned black (not in any gray list). */ static void atomic2gen (lua_State *L, global_State *g) { cleargraylists(g); /* sweep all elements making them old */ g->gcstate = GCSswpallgc; sweep2old(L, &g->allgc); /* everything alive now is old */ g->reallyold = g->old1 = g->survival = g->allgc; g->firstold1 = NULL; /* there are no OLD1 objects anywhere */ /* repeat for 'finobj' lists */ sweep2old(L, &g->finobj); g->finobjrold = g->finobjold1 = g->finobjsur = g->finobj; sweep2old(L, &g->tobefnz); g->gckind = KGC_GEN; g->lastatomic = 0; g->GCestimate = gettotalbytes(g); /* base for memory control */ finishgencycle(L, g); } /* ** Enter generational mode. Must go until the end of an atomic cycle ** to ensure that all objects are correctly marked and weak tables ** are cleared. Then, turn all objects into old and finishes the ** collection. */ static lu_mem entergen (lua_State *L, global_State *g) { lu_mem numobjs; luaC_runtilstate(L, bitmask(GCSpause)); /* prepare to start a new cycle */ luaC_runtilstate(L, bitmask(GCSpropagate)); /* start new cycle */ numobjs = atomic(L); /* propagates all and then do the atomic stuff */ atomic2gen(L, g); return numobjs; } /* ** Enter incremental mode. Turn all objects white, make all ** intermediate lists point to NULL (to avoid invalid pointers), ** and go to the pause state. */ static void enterinc (global_State *g) { whitelist(g, g->allgc); g->reallyold = g->old1 = g->survival = NULL; whitelist(g, g->finobj); whitelist(g, g->tobefnz); g->finobjrold = g->finobjold1 = g->finobjsur = NULL; g->gcstate = GCSpause; g->gckind = KGC_INC; g->lastatomic = 0; } /* ** Change collector mode to 'newmode'. */ void luaC_changemode (lua_State *L, int newmode) { global_State *g = G(L); if (newmode != g->gckind) { if (newmode == KGC_GEN) /* entering generational mode? */ entergen(L, g); else enterinc(g); /* entering incremental mode */ } g->lastatomic = 0; } /* ** Does a full collection in generational mode. */ static lu_mem fullgen (lua_State *L, global_State *g) { enterinc(g); return entergen(L, g); } /* ** Set debt for the next minor collection, which will happen when ** memory grows 'genminormul'%. */ static void setminordebt (global_State *g) { luaE_setdebt(g, -(cast(l_mem, (gettotalbytes(g) / 100)) * g->genminormul)); } /* ** Does a major collection after last collection was a "bad collection". ** ** When the program is building a big structure, it allocates lots of ** memory but generates very little garbage. In those scenarios, ** the generational mode just wastes time doing small collections, and ** major collections are frequently what we call a "bad collection", a ** collection that frees too few objects. To avoid the cost of switching ** between generational mode and the incremental mode needed for full ** (major) collections, the collector tries to stay in incremental mode ** after a bad collection, and to switch back to generational mode only ** after a "good" collection (one that traverses less than 9/8 objects ** of the previous one). ** The collector must choose whether to stay in incremental mode or to ** switch back to generational mode before sweeping. At this point, it ** does not know the real memory in use, so it cannot use memory to ** decide whether to return to generational mode. Instead, it uses the ** number of objects traversed (returned by 'atomic') as a proxy. The ** field 'g->lastatomic' keeps this count from the last collection. ** ('g->lastatomic != 0' also means that the last collection was bad.) */ static void stepgenfull (lua_State *L, global_State *g) { lu_mem newatomic; /* count of traversed objects */ lu_mem lastatomic = g->lastatomic; /* count from last collection */ if (g->gckind == KGC_GEN) /* still in generational mode? */ enterinc(g); /* enter incremental mode */ luaC_runtilstate(L, bitmask(GCSpropagate)); /* start new cycle */ newatomic = atomic(L); /* mark everybody */ if (newatomic < lastatomic + (lastatomic >> 3)) { /* good collection? */ atomic2gen(L, g); /* return to generational mode */ setminordebt(g); } else { /* another bad collection; stay in incremental mode */ g->GCestimate = gettotalbytes(g); /* first estimate */; entersweep(L); luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */ setpause(g); g->lastatomic = newatomic; } } /* ** Does a generational "step". ** Usually, this means doing a minor collection and setting the debt to ** make another collection when memory grows 'genminormul'% larger. ** ** However, there are exceptions. If memory grows 'genmajormul'% ** larger than it was at the end of the last major collection (kept ** in 'g->GCestimate'), the function does a major collection. At the ** end, it checks whether the major collection was able to free a ** decent amount of memory (at least half the growth in memory since ** previous major collection). If so, the collector keeps its state, ** and the next collection will probably be minor again. Otherwise, ** we have what we call a "bad collection". In that case, set the field ** 'g->lastatomic' to signal that fact, so that the next collection will ** go to 'stepgenfull'. ** ** 'GCdebt <= 0' means an explicit call to GC step with "size" zero; ** in that case, do a minor collection. */ static void genstep (lua_State *L, global_State *g) { if (g->lastatomic != 0) /* last collection was a bad one? */ stepgenfull(L, g); /* do a full step */ else { lu_mem majorbase = g->GCestimate; /* memory after last major collection */ lu_mem majorinc = (majorbase / 100) * getgcparam(g->genmajormul); if (g->GCdebt > 0 && gettotalbytes(g) > majorbase + majorinc) { lu_mem numobjs = fullgen(L, g); /* do a major collection */ if (gettotalbytes(g) < majorbase + (majorinc / 2)) { /* collected at least half of memory growth since last major collection; keep doing minor collections */ setminordebt(g); } else { /* bad collection */ g->lastatomic = numobjs; /* signal that last collection was bad */ setpause(g); /* do a long wait for next (major) collection */ } } else { /* regular case; do a minor collection */ youngcollection(L, g); setminordebt(g); g->GCestimate = majorbase; /* preserve base value */ } } lua_assert(isdecGCmodegen(g)); } /* }====================================================== */ /* ** {====================================================== ** GC control ** ======================================================= */ /* ** Set the "time" to wait before starting a new GC cycle; cycle will ** start when memory use hits the threshold of ('estimate' * pause / ** PAUSEADJ). (Division by 'estimate' should be OK: it cannot be zero, ** because Lua cannot even start with less than PAUSEADJ bytes). */ static void setpause (global_State *g) { l_mem threshold, debt; int pause = getgcparam(g->gcpause); l_mem estimate = g->GCestimate / PAUSEADJ; /* adjust 'estimate' */ lua_assert(estimate > 0); threshold = (pause < MAX_LMEM / estimate) /* overflow? */ ? estimate * pause /* no overflow */ : MAX_LMEM; /* overflow; truncate to maximum */ debt = gettotalbytes(g) - threshold; if (debt > 0) debt = 0; luaE_setdebt(g, debt); } /* ** Enter first sweep phase. ** The call to 'sweeptolive' makes the pointer point to an object ** inside the list (instead of to the header), so that the real sweep do ** not need to skip objects created between "now" and the start of the ** real sweep. */ static void entersweep (lua_State *L) { global_State *g = G(L); g->gcstate = GCSswpallgc; lua_assert(g->sweepgc == NULL); g->sweepgc = sweeptolive(L, &g->allgc); } /* ** Delete all objects in list 'p' until (but not including) object ** 'limit'. */ static void deletelist (lua_State *L, GCObject *p, GCObject *limit) { while (p != limit) { GCObject *next = p->next; freeobj(L, p); p = next; } } /* ** Call all finalizers of the objects in the given Lua state, and ** then free all objects, except for the main thread. */ void luaC_freeallobjects (lua_State *L) { global_State *g = G(L); luaC_changemode(L, KGC_INC); separatetobefnz(g, 1); /* separate all objects with finalizers */ lua_assert(g->finobj == NULL); callallpendingfinalizers(L); deletelist(L, g->allgc, obj2gco(g->mainthread)); deletelist(L, g->finobj, NULL); deletelist(L, g->fixedgc, NULL); /* collect fixed objects */ lua_assert(g->strt.nuse == 0); } static lu_mem atomic (lua_State *L) { global_State *g = G(L); lu_mem work = 0; GCObject *origweak, *origall; GCObject *grayagain = g->grayagain; /* save original list */ g->grayagain = NULL; lua_assert(g->ephemeron == NULL && g->weak == NULL); lua_assert(!iswhite(g->mainthread)); g->gcstate = GCSatomic; markobject(g, L); /* mark running thread */ /* registry and global metatables may be changed by API */ markvalue(g, &g->l_registry); markmt(g); /* mark global metatables */ work += propagateall(g); /* empties 'gray' list */ /* remark occasional upvalues of (maybe) dead threads */ work += remarkupvals(g); work += propagateall(g); /* propagate changes */ g->gray = grayagain; work += propagateall(g); /* traverse 'grayagain' list */ convergeephemerons(g); /* at this point, all strongly accessible objects are marked. */ /* Clear values from weak tables, before checking finalizers */ clearbyvalues(g, g->weak, NULL); clearbyvalues(g, g->allweak, NULL); origweak = g->weak; origall = g->allweak; separatetobefnz(g, 0); /* separate objects to be finalized */ work += markbeingfnz(g); /* mark objects that will be finalized */ work += propagateall(g); /* remark, to propagate 'resurrection' */ convergeephemerons(g); /* at this point, all resurrected objects are marked. */ /* remove dead objects from weak tables */ clearbykeys(g, g->ephemeron); /* clear keys from all ephemeron tables */ clearbykeys(g, g->allweak); /* clear keys from all 'allweak' tables */ /* clear values from resurrected weak tables */ clearbyvalues(g, g->weak, origweak); clearbyvalues(g, g->allweak, origall); luaS_clearcache(g); g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */ lua_assert(g->gray == NULL); return work; /* estimate of slots marked by 'atomic' */ } static int sweepstep (lua_State *L, global_State *g, int nextstate, GCObject **nextlist) { if (g->sweepgc) { l_mem olddebt = g->GCdebt; int count; g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX, &count); g->GCestimate += g->GCdebt - olddebt; /* update estimate */ return count; } else { /* enter next state */ g->gcstate = nextstate; g->sweepgc = nextlist; return 0; /* no work done */ } } static lu_mem singlestep (lua_State *L) { global_State *g = G(L); switch (g->gcstate) { case GCSpause: { restartcollection(g); g->gcstate = GCSpropagate; return 1; } case GCSpropagate: { if (g->gray == NULL) { /* no more gray objects? */ g->gcstate = GCSenteratomic; /* finish propagate phase */ return 0; } else return propagatemark(g); /* traverse one gray object */ } case GCSenteratomic: { lu_mem work = atomic(L); /* work is what was traversed by 'atomic' */ entersweep(L); g->GCestimate = gettotalbytes(g); /* first estimate */; return work; } case GCSswpallgc: { /* sweep "regular" objects */ return sweepstep(L, g, GCSswpfinobj, &g->finobj); } case GCSswpfinobj: { /* sweep objects with finalizers */ return sweepstep(L, g, GCSswptobefnz, &g->tobefnz); } case GCSswptobefnz: { /* sweep objects to be finalized */ return sweepstep(L, g, GCSswpend, NULL); } case GCSswpend: { /* finish sweeps */ checkSizes(L, g); g->gcstate = GCScallfin; return 0; } case GCScallfin: { /* call remaining finalizers */ if (g->tobefnz && !g->gcemergency) { int n = runafewfinalizers(L, GCFINMAX); return n * GCFINALIZECOST; } else { /* emergency mode or no more finalizers */ g->gcstate = GCSpause; /* finish collection */ return 0; } } default: lua_assert(0); return 0; } } /* ** advances the garbage collector until it reaches a state allowed ** by 'statemask' */ void luaC_runtilstate (lua_State *L, int statesmask) { global_State *g = G(L); while (!testbit(statesmask, g->gcstate)) singlestep(L); } /* ** Performs a basic incremental step. The debt and step size are ** converted from bytes to "units of work"; then the function loops ** running single steps until adding that many units of work or ** finishing a cycle (pause state). Finally, it sets the debt that ** controls when next step will be performed. */ static void incstep (lua_State *L, global_State *g) { int stepmul = (getgcparam(g->gcstepmul) | 1); /* avoid division by 0 */ l_mem debt = (g->GCdebt / WORK2MEM) * stepmul; l_mem stepsize = (g->gcstepsize <= log2maxs(l_mem)) ? ((cast(l_mem, 1) << g->gcstepsize) / WORK2MEM) * stepmul : MAX_LMEM; /* overflow; keep maximum value */ do { /* repeat until pause or enough "credit" (negative debt) */ lu_mem work = singlestep(L); /* perform one single step */ debt -= work; } while (debt > -stepsize && g->gcstate != GCSpause); if (g->gcstate == GCSpause) setpause(g); /* pause until next cycle */ else { debt = (debt / stepmul) * WORK2MEM; /* convert 'work units' to bytes */ luaE_setdebt(g, debt); } } /* ** performs a basic GC step if collector is running */ void luaC_step (lua_State *L) { global_State *g = G(L); lua_assert(!g->gcemergency); if (g->gcrunning) { /* running? */ if(isdecGCmodegen(g)) genstep(L, g); else incstep(L, g); } } /* ** Perform a full collection in incremental mode. ** Before running the collection, check 'keepinvariant'; if it is true, ** there may be some objects marked as black, so the collector has ** to sweep all objects to turn them back to white (as white has not ** changed, nothing will be collected). */ static void fullinc (lua_State *L, global_State *g) { if (keepinvariant(g)) /* black objects? */ entersweep(L); /* sweep everything to turn them back to white */ /* finish any pending sweep phase to start a new cycle */ luaC_runtilstate(L, bitmask(GCSpause)); luaC_runtilstate(L, bitmask(GCScallfin)); /* run up to finalizers */ /* estimate must be correct after a full GC cycle */ lua_assert(g->GCestimate == gettotalbytes(g)); luaC_runtilstate(L, bitmask(GCSpause)); /* finish collection */ setpause(g); } /* ** Performs a full GC cycle; if 'isemergency', set a flag to avoid ** some operations which could change the interpreter state in some ** unexpected ways (running finalizers and shrinking some structures). */ void luaC_fullgc (lua_State *L, int isemergency) { global_State *g = G(L); lua_assert(!g->gcemergency); g->gcemergency = isemergency; /* set flag */ if (g->gckind == KGC_INC) fullinc(L, g); else fullgen(L, g); g->gcemergency = 0; } /* }====================================================== */
xLua/build/lua-5.4.1/src/lgc.c/0
{ "file_path": "xLua/build/lua-5.4.1/src/lgc.c", "repo_id": "xLua", "token_count": 20709 }
2,097
/* ** $Id: lopnames.h $ ** Opcode names ** See Copyright Notice in lua.h */ #if !defined(lopnames_h) #define lopnames_h #include <stddef.h> /* ORDER OP */ static const char *const opnames[] = { "MOVE", "LOADI", "LOADF", "LOADK", "LOADKX", "LOADFALSE", "LFALSESKIP", "LOADTRUE", "LOADNIL", "GETUPVAL", "SETUPVAL", "GETTABUP", "GETTABLE", "GETI", "GETFIELD", "SETTABUP", "SETTABLE", "SETI", "SETFIELD", "NEWTABLE", "SELF", "ADDI", "ADDK", "SUBK", "MULK", "MODK", "POWK", "DIVK", "IDIVK", "BANDK", "BORK", "BXORK", "SHRI", "SHLI", "ADD", "SUB", "MUL", "MOD", "POW", "DIV", "IDIV", "BAND", "BOR", "BXOR", "SHL", "SHR", "MMBIN", "MMBINI", "MMBINK", "UNM", "BNOT", "NOT", "LEN", "CONCAT", "CLOSE", "TBC", "JMP", "EQ", "LT", "LE", "EQK", "EQI", "LTI", "LEI", "GTI", "GEI", "TEST", "TESTSET", "CALL", "TAILCALL", "RETURN", "RETURN0", "RETURN1", "FORLOOP", "FORPREP", "TFORPREP", "TFORCALL", "TFORLOOP", "SETLIST", "CLOSURE", "VARARG", "VARARGPREP", "EXTRAARG", NULL }; #endif
xLua/build/lua-5.4.1/src/lopnames.h/0
{ "file_path": "xLua/build/lua-5.4.1/src/lopnames.h", "repo_id": "xLua", "token_count": 631 }
2,098
=============================================================================== LuaJIT -- a Just-In-Time Compiler for Lua. http://luajit.org/ Copyright (C) 2005-2016 Mike Pall. All rights reserved. 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. [ MIT license: http://www.opensource.org/licenses/mit-license.php ] =============================================================================== [ LuaJIT includes code from Lua 5.1/5.2, which has this license statement: ] Copyright (C) 1994-2012 Lua.org, PUC-Rio. 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. =============================================================================== [ LuaJIT includes code from dlmalloc, which has this license statement: ] This is a version (aka dlmalloc) of malloc/free/realloc written by Doug Lea and released to the public domain, as explained at http://creativecommons.org/licenses/publicdomain ===============================================================================
xLua/build/luajit-2.1.0b2/COPYRIGHT/0
{ "file_path": "xLua/build/luajit-2.1.0b2/COPYRIGHT", "repo_id": "xLua", "token_count": 717 }
2,099
------------------------------------------------------------------------------ -- DynASM x86/x64 module. -- -- Copyright (C) 2005-2016 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ local x64 = x64 -- Module information: local _info = { arch = x64 and "x64" or "x86", description = "DynASM x86/x64 module", version = "1.4.0", vernum = 10400, release = "2015-10-18", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, unpack, setmetatable = assert, unpack or table.unpack, setmetatable local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local find, match, gmatch, gsub = _s.find, _s.match, _s.gmatch, _s.gsub local concat, sort, remove = table.concat, table.sort, table.remove local bit = bit or require("bit") local band, bxor, shl, shr = bit.band, bit.bxor, bit.lshift, bit.rshift -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { -- int arg, 1 buffer pos: "DISP", "IMM_S", "IMM_B", "IMM_W", "IMM_D", "IMM_WB", "IMM_DB", -- action arg (1 byte), int arg, 1 buffer pos (reg/num): "VREG", "SPACE", -- ptrdiff_t arg, 1 buffer pos (address): !x64 "SETLABEL", "REL_A", -- action arg (1 byte) or int arg, 2 buffer pos (link, offset): "REL_LG", "REL_PC", -- action arg (1 byte) or int arg, 1 buffer pos (link): "IMM_LG", "IMM_PC", -- action arg (1 byte) or int arg, 1 buffer pos (offset): "LABEL_LG", "LABEL_PC", -- action arg (1 byte), 1 buffer pos (offset): "ALIGN", -- action args (2 bytes), no buffer pos. "EXTERN", -- action arg (1 byte), no buffer pos. "ESC", -- no action arg, no buffer pos. "MARK", -- action arg (1 byte), no buffer pos, terminal action: "SECTION", -- no args, no buffer pos, terminal action: "STOP" } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number (dynamically generated below). local map_action = {} -- First action number. Everything below does not need to be escaped. local actfirst = 256-#action_names -- Action list buffer and string (only used to remove dupes). local actlist = {} local actstr = "" -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 -- VREG kind encodings, pre-shifted by 5 bits. local map_vreg = { ["modrm.rm.m"] = 0x00, ["modrm.rm.r"] = 0x20, ["opcode"] = 0x20, ["sib.base"] = 0x20, ["sib.index"] = 0x40, ["modrm.reg"] = 0x80, ["vex.v"] = 0xa0, ["imm.hi"] = 0xc0, } -- Current number of VREG actions contributing to REX/VEX shrinkage. local vreg_shrink_count = 0 ------------------------------------------------------------------------------ -- Compute action numbers for action names. for n,name in ipairs(action_names) do local num = actfirst + n - 1 map_action[name] = num end -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist local last = actlist[nn] or 255 actlist[nn] = nil -- Remove last byte. if nn == 0 then nn = 1 end out:write("static const unsigned char ", name, "[", nn, "] = {\n") local s = " " for n,b in ipairs(actlist) do s = s..b.."," if #s >= 75 then assert(out:write(s, "\n")) s = " " end end out:write(s, last, "\n};\n\n") -- Add last byte back. end ------------------------------------------------------------------------------ -- Add byte to action list. local function wputxb(n) assert(n >= 0 and n <= 255 and n % 1 == 0, "byte out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, a, num) wputxb(assert(map_action[action], "bad action name `"..action.."'")) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Optionally add a VREG action. local function wvreg(kind, vreg, psz, sk, defer) if not vreg then return end waction("VREG", vreg) local b = assert(map_vreg[kind], "bad vreg kind `"..vreg.."'") if b < (sk or 0) then vreg_shrink_count = vreg_shrink_count + 1 end if not defer then b = b + vreg_shrink_count * 8 vreg_shrink_count = 0 end wputxb(b + (psz or 0)) end -- Add call to embedded DynASM C code. local function wcall(func, args) wline(format("dasm_%s(Dst, %s);", func, concat(args, ", ")), true) end -- Delete duplicate action list chunks. A tad slow, but so what. local function dedupechunk(offset) local al, as = actlist, actstr local chunk = char(unpack(al, offset+1, #al)) local orig = find(as, chunk, 1, true) if orig then actargs[1] = orig-1 -- Replace with original offset. for i=offset+1,#al do al[i] = nil end -- Kill dupe. else actstr = as..chunk end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) local offset = actargs[1] if #actlist == offset then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. dedupechunk(offset) wcall("put", actargs) -- Add call to dasm_put(). actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped byte. local function wputb(n) if n >= actfirst then waction("ESC") end -- Need to escape byte. wputxb(n) end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 10 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_@]*$") then werror("bad global label") end local n = next_global if n > 246 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=10,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=10,next_global-1 do out:write(" ", prefix, gsub(t[i], "@.*", ""), ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=10,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = -1 local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n < -256 then werror("too many extern labels") end next_extern = n - 1 t[name] = n return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) local t = {} for name, n in pairs(map_extern) do t[-n] = name end out:write("Extern labels:\n") for i=1,-next_extern-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) local t = {} for name, n in pairs(map_extern) do t[-n] = name end out:write("static const char *const ", name, "[] = {\n") for i=1,-next_extern-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. local map_archdef = {} -- Ext. register name -> int. name. local map_reg_rev = {} -- Int. register name -> ext. name. local map_reg_num = {} -- Int. register name -> register number. local map_reg_opsize = {} -- Int. register name -> operand size. local map_reg_valid_base = {} -- Int. register name -> valid base register? local map_reg_valid_index = {} -- Int. register name -> valid index register? local map_reg_needrex = {} -- Int. register name -> need rex vs. no rex. local reg_list = {} -- Canonical list of int. register names. local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for _PTx macros). local addrsize = x64 and "q" or "d" -- Size for address operands. -- Helper functions to fill register maps. local function mkrmap(sz, cl, names) local cname = format("@%s", sz) reg_list[#reg_list+1] = cname map_archdef[cl] = cname map_reg_rev[cname] = cl map_reg_num[cname] = -1 map_reg_opsize[cname] = sz if sz == addrsize or sz == "d" then map_reg_valid_base[cname] = true map_reg_valid_index[cname] = true end if names then for n,name in ipairs(names) do local iname = format("@%s%x", sz, n-1) reg_list[#reg_list+1] = iname map_archdef[name] = iname map_reg_rev[iname] = name map_reg_num[iname] = n-1 map_reg_opsize[iname] = sz if sz == "b" and n > 4 then map_reg_needrex[iname] = false end if sz == addrsize or sz == "d" then map_reg_valid_base[iname] = true map_reg_valid_index[iname] = true end end end for i=0,(x64 and sz ~= "f") and 15 or 7 do local needrex = sz == "b" and i > 3 local iname = format("@%s%x%s", sz, i, needrex and "R" or "") if needrex then map_reg_needrex[iname] = true end local name if sz == "o" or sz == "y" then name = format("%s%d", cl, i) elseif sz == "f" then name = format("st%d", i) else name = format("r%d%s", i, sz == addrsize and "" or sz) end map_archdef[name] = iname if not map_reg_rev[iname] then reg_list[#reg_list+1] = iname map_reg_rev[iname] = name map_reg_num[iname] = i map_reg_opsize[iname] = sz if sz == addrsize or sz == "d" then map_reg_valid_base[iname] = true map_reg_valid_index[iname] = true end end end reg_list[#reg_list+1] = "" end -- Integer registers (qword, dword, word and byte sized). if x64 then mkrmap("q", "Rq", {"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi"}) end mkrmap("d", "Rd", {"eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"}) mkrmap("w", "Rw", {"ax", "cx", "dx", "bx", "sp", "bp", "si", "di"}) mkrmap("b", "Rb", {"al", "cl", "dl", "bl", "ah", "ch", "dh", "bh"}) map_reg_valid_index[map_archdef.esp] = false if x64 then map_reg_valid_index[map_archdef.rsp] = false end if x64 then map_reg_needrex[map_archdef.Rb] = true end map_archdef["Ra"] = "@"..addrsize -- FP registers (internally tword sized, but use "f" as operand size). mkrmap("f", "Rf") -- SSE registers (oword sized, but qword and dword accessible). mkrmap("o", "xmm") -- AVX registers (yword sized, but oword, qword and dword accessible). mkrmap("y", "ymm") -- Operand size prefixes to codes. local map_opsize = { byte = "b", word = "w", dword = "d", qword = "q", oword = "o", yword = "y", tword = "t", aword = addrsize, } -- Operand size code to number. local map_opsizenum = { b = 1, w = 2, d = 4, q = 8, o = 16, y = 32, t = 10, } -- Operand size code to name. local map_opsizename = { b = "byte", w = "word", d = "dword", q = "qword", o = "oword", y = "yword", t = "tword", f = "fpword", } -- Valid index register scale factors. local map_xsc = { ["1"] = 0, ["2"] = 1, ["4"] = 2, ["8"] = 3, } -- Condition codes. local map_cc = { o = 0, no = 1, b = 2, nb = 3, e = 4, ne = 5, be = 6, nbe = 7, s = 8, ns = 9, p = 10, np = 11, l = 12, nl = 13, le = 14, nle = 15, c = 2, nae = 2, nc = 3, ae = 3, z = 4, nz = 5, na = 6, a = 7, pe = 10, po = 11, nge = 12, ge = 13, ng = 14, g = 15, } -- Reverse defines for registers. function _M.revdef(s) return gsub(s, "@%w+", map_reg_rev) end -- Dump register names and numbers local function dumpregs(out) out:write("Register names, sizes and internal numbers:\n") for _,reg in ipairs(reg_list) do if reg == "" then out:write("\n") else local name = map_reg_rev[reg] local num = map_reg_num[reg] local opsize = map_opsizename[map_reg_opsize[reg]] out:write(format(" %-5s %-8s %s\n", name, opsize, num < 0 and "(variable)" or num)) end end end ------------------------------------------------------------------------------ -- Put action for label arg (IMM_LG, IMM_PC, REL_LG, REL_PC). local function wputlabel(aprefix, imm, num) if type(imm) == "number" then if imm < 0 then waction("EXTERN") wputxb(aprefix == "IMM_" and 0 or 1) imm = -imm-1 else waction(aprefix.."LG", nil, num); end wputxb(imm) else waction(aprefix.."PC", imm, num) end end -- Put signed byte or arg. local function wputsbarg(n) if type(n) == "number" then if n < -128 or n > 127 then werror("signed immediate byte out of range") end if n < 0 then n = n + 256 end wputb(n) else waction("IMM_S", n) end end -- Put unsigned byte or arg. local function wputbarg(n) if type(n) == "number" then if n < 0 or n > 255 then werror("unsigned immediate byte out of range") end wputb(n) else waction("IMM_B", n) end end -- Put unsigned word or arg. local function wputwarg(n) if type(n) == "number" then if shr(n, 16) ~= 0 then werror("unsigned immediate word out of range") end wputb(band(n, 255)); wputb(shr(n, 8)); else waction("IMM_W", n) end end -- Put signed or unsigned dword or arg. local function wputdarg(n) local tn = type(n) if tn == "number" then wputb(band(n, 255)) wputb(band(shr(n, 8), 255)) wputb(band(shr(n, 16), 255)) wputb(shr(n, 24)) elseif tn == "table" then wputlabel("IMM_", n[1], 1) else waction("IMM_D", n) end end -- Put operand-size dependent number or arg (defaults to dword). local function wputszarg(sz, n) if not sz or sz == "d" or sz == "q" then wputdarg(n) elseif sz == "w" then wputwarg(n) elseif sz == "b" then wputbarg(n) elseif sz == "s" then wputsbarg(n) else werror("bad operand size") end end -- Put multi-byte opcode with operand-size dependent modifications. local function wputop(sz, op, rex, vex, vregr, vregxb) local psz, sk = 0, nil if vex then local tail if vex.m == 1 and band(rex, 11) == 0 then if x64 and vregxb then sk = map_vreg["modrm.reg"] else wputb(0xc5) tail = shl(bxor(band(rex, 4), 4), 5) psz = 3 end end if not tail then wputb(0xc4) wputb(shl(bxor(band(rex, 7), 7), 5) + vex.m) tail = shl(band(rex, 8), 4) psz = 4 end local reg, vreg = 0, nil if vex.v then reg = vex.v.reg if not reg then werror("bad vex operand") end if reg < 0 then reg = 0; vreg = vex.v.vreg end end if sz == "y" or vex.l then tail = tail + 4 end wputb(tail + shl(bxor(reg, 15), 3) + vex.p) wvreg("vex.v", vreg) rex = 0 if op >= 256 then werror("bad vex opcode") end else if rex ~= 0 then if not x64 then werror("bad operand size") end elseif (vregr or vregxb) and x64 then rex = 0x10 sk = map_vreg["vex.v"] end end local r if sz == "w" then wputb(102) end -- Needs >32 bit numbers, but only for crc32 eax, word [ebx] if op >= 4294967296 then r = op%4294967296 wputb((op-r)/4294967296) op = r end if op >= 16777216 then wputb(shr(op, 24)); op = band(op, 0xffffff) end if op >= 65536 then if rex ~= 0 then local opc3 = band(op, 0xffff00) if opc3 == 0x0f3a00 or opc3 == 0x0f3800 then wputb(64 + band(rex, 15)); rex = 0; psz = 2 end end wputb(shr(op, 16)); op = band(op, 0xffff); psz = psz + 1 end if op >= 256 then local b = shr(op, 8) if b == 15 and rex ~= 0 then wputb(64 + band(rex, 15)); rex = 0; psz = 2 end wputb(b); op = band(op, 255); psz = psz + 1 end if rex ~= 0 then wputb(64 + band(rex, 15)); psz = 2 end if sz == "b" then op = op - 1 end wputb(op) return psz, sk end -- Put ModRM or SIB formatted byte. local function wputmodrm(m, s, rm, vs, vrm) assert(m < 4 and s < 16 and rm < 16, "bad modrm operands") wputb(shl(m, 6) + shl(band(s, 7), 3) + band(rm, 7)) end -- Put ModRM/SIB plus optional displacement. local function wputmrmsib(t, imark, s, vsreg, psz, sk) local vreg, vxreg local reg, xreg = t.reg, t.xreg if reg and reg < 0 then reg = 0; vreg = t.vreg end if xreg and xreg < 0 then xreg = 0; vxreg = t.vxreg end if s < 0 then s = 0 end -- Register mode. if sub(t.mode, 1, 1) == "r" then wputmodrm(3, s, reg) wvreg("modrm.reg", vsreg, psz+1, sk, vreg) wvreg("modrm.rm.r", vreg, psz+1, sk) return end local disp = t.disp local tdisp = type(disp) -- No base register? if not reg then local riprel = false if xreg then -- Indexed mode with index register only. -- [xreg*xsc+disp] -> (0, s, esp) (xsc, xreg, ebp) wputmodrm(0, s, 4) if imark == "I" then waction("MARK") end wvreg("modrm.reg", vsreg, psz+1, sk, vxreg) wputmodrm(t.xsc, xreg, 5) wvreg("sib.index", vxreg, psz+2, sk) else -- Pure 32 bit displacement. if x64 and tdisp ~= "table" then wputmodrm(0, s, 4) -- [disp] -> (0, s, esp) (0, esp, ebp) wvreg("modrm.reg", vsreg, psz+1, sk) if imark == "I" then waction("MARK") end wputmodrm(0, 4, 5) else riprel = x64 wputmodrm(0, s, 5) -- [disp|rip-label] -> (0, s, ebp) wvreg("modrm.reg", vsreg, psz+1, sk) if imark == "I" then waction("MARK") end end end if riprel then -- Emit rip-relative displacement. if match("UWSiI", imark) then werror("NYI: rip-relative displacement followed by immediate") end -- The previous byte in the action buffer cannot be 0xe9 or 0x80-0x8f. wputlabel("REL_", disp[1], 2) else wputdarg(disp) end return end local m if tdisp == "number" then -- Check displacement size at assembly time. if disp == 0 and band(reg, 7) ~= 5 then -- [ebp] -> [ebp+0] (in SIB, too) if not vreg then m = 0 end -- Force DISP to allow [Rd(5)] -> [ebp+0] elseif disp >= -128 and disp <= 127 then m = 1 else m = 2 end elseif tdisp == "table" then m = 2 end -- Index register present or esp as base register: need SIB encoding. if xreg or band(reg, 7) == 4 then wputmodrm(m or 2, s, 4) -- ModRM. if m == nil or imark == "I" then waction("MARK") end wvreg("modrm.reg", vsreg, psz+1, sk, vxreg or vreg) wputmodrm(t.xsc or 0, xreg or 4, reg) -- SIB. wvreg("sib.index", vxreg, psz+2, sk, vreg) wvreg("sib.base", vreg, psz+2, sk) else wputmodrm(m or 2, s, reg) -- ModRM. if (imark == "I" and (m == 1 or m == 2)) or (m == nil and (vsreg or vreg)) then waction("MARK") end wvreg("modrm.reg", vsreg, psz+1, sk, vreg) wvreg("modrm.rm.m", vreg, psz+1, sk) end -- Put displacement. if m == 1 then wputsbarg(disp) elseif m == 2 then wputdarg(disp) elseif m == nil then waction("DISP", disp) end end ------------------------------------------------------------------------------ -- Return human-readable operand mode string. local function opmodestr(op, args) local m = {} for i=1,#args do local a = args[i] m[#m+1] = sub(a.mode, 1, 1)..(a.opsize or "?") end return op.." "..concat(m, ",") end -- Convert number to valid integer or nil. local function toint(expr) local n = tonumber(expr) if n then if n % 1 ~= 0 or n < -2147483648 or n > 4294967295 then werror("bad integer number `"..expr.."'") end return n end end -- Parse immediate expression. local function immexpr(expr) -- &expr (pointer) if sub(expr, 1, 1) == "&" then return "iPJ", format("(ptrdiff_t)(%s)", sub(expr,2)) end local prefix = sub(expr, 1, 2) -- =>expr (pc label reference) if prefix == "=>" then return "iJ", sub(expr, 3) end -- ->name (global label reference) if prefix == "->" then return "iJ", map_global[sub(expr, 3)] end -- [<>][1-9] (local label reference) local dir, lnum = match(expr, "^([<>])([1-9])$") if dir then -- Fwd: 247-255, Bkwd: 1-9. return "iJ", lnum + (dir == ">" and 246 or 0) end local extname = match(expr, "^extern%s+(%S+)$") if extname then return "iJ", map_extern[extname] end -- expr (interpreted as immediate) return "iI", expr end -- Parse displacement expression: +-num, +-expr, +-opsize*num local function dispexpr(expr) local disp = expr == "" and 0 or toint(expr) if disp then return disp end local c, dispt = match(expr, "^([+-])%s*(.+)$") if c == "+" then expr = dispt elseif not c then werror("bad displacement expression `"..expr.."'") end local opsize, tailops = match(dispt, "^(%w+)%s*%*%s*(.+)$") local ops, imm = map_opsize[opsize], toint(tailops) if ops and imm then if c == "-" then imm = -imm end return imm*map_opsizenum[ops] end local mode, iexpr = immexpr(dispt) if mode == "iJ" then if c == "-" then werror("cannot invert label reference") end return { iexpr } end return expr -- Need to return original signed expression. end -- Parse register or type expression. local function rtexpr(expr) if not expr then return end local tname, ovreg = match(expr, "^([%w_]+):(@[%w_]+)$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg local rnum = map_reg_num[reg] if not rnum then werror("type `"..(tname or expr).."' needs a register override") end if not map_reg_valid_base[reg] then werror("bad base register override `"..(map_reg_rev[reg] or reg).."'") end return reg, rnum, tp end return expr, map_reg_num[expr] end -- Parse operand and return { mode, opsize, reg, xreg, xsc, disp, imm }. local function parseoperand(param) local t = {} local expr = param local opsize, tailops = match(param, "^(%w+)%s*(.+)$") if opsize then t.opsize = map_opsize[opsize] if t.opsize then expr = tailops end end local br = match(expr, "^%[%s*(.-)%s*%]$") repeat if br then t.mode = "xm" -- [disp] t.disp = toint(br) if t.disp then t.mode = x64 and "xm" or "xmO" break end -- [reg...] local tp local reg, tailr = match(br, "^([@%w_:]+)%s*(.*)$") reg, t.reg, tp = rtexpr(reg) if not t.reg then -- [expr] t.mode = x64 and "xm" or "xmO" t.disp = dispexpr("+"..br) break end if t.reg == -1 then t.vreg, tailr = match(tailr, "^(%b())(.*)$") if not t.vreg then werror("bad variable register expression") end end -- [xreg*xsc] or [xreg*xsc+-disp] or [xreg*xsc+-expr] local xsc, tailsc = match(tailr, "^%*%s*([1248])%s*(.*)$") if xsc then if not map_reg_valid_index[reg] then werror("bad index register `"..map_reg_rev[reg].."'") end t.xsc = map_xsc[xsc] t.xreg = t.reg t.vxreg = t.vreg t.reg = nil t.vreg = nil t.disp = dispexpr(tailsc) break end if not map_reg_valid_base[reg] then werror("bad base register `"..map_reg_rev[reg].."'") end -- [reg] or [reg+-disp] t.disp = toint(tailr) or (tailr == "" and 0) if t.disp then break end -- [reg+xreg...] local xreg, tailx = match(tailr, "^+%s*([@%w_:]+)%s*(.*)$") xreg, t.xreg, tp = rtexpr(xreg) if not t.xreg then -- [reg+-expr] t.disp = dispexpr(tailr) break end if not map_reg_valid_index[xreg] then werror("bad index register `"..map_reg_rev[xreg].."'") end if t.xreg == -1 then t.vxreg, tailx = match(tailx, "^(%b())(.*)$") if not t.vxreg then werror("bad variable register expression") end end -- [reg+xreg*xsc...] local xsc, tailsc = match(tailx, "^%*%s*([1248])%s*(.*)$") if xsc then t.xsc = map_xsc[xsc] tailx = tailsc end -- [...] or [...+-disp] or [...+-expr] t.disp = dispexpr(tailx) else -- imm or opsize*imm local imm = toint(expr) if not imm and sub(expr, 1, 1) == "*" and t.opsize then imm = toint(sub(expr, 2)) if imm then imm = imm * map_opsizenum[t.opsize] t.opsize = nil end end if imm then if t.opsize then werror("bad operand size override") end local m = "i" if imm == 1 then m = m.."1" end if imm >= 4294967168 and imm <= 4294967295 then imm = imm-4294967296 end if imm >= -128 and imm <= 127 then m = m.."S" end t.imm = imm t.mode = m break end local tp local reg, tailr = match(expr, "^([@%w_:]+)%s*(.*)$") reg, t.reg, tp = rtexpr(reg) if t.reg then if t.reg == -1 then t.vreg, tailr = match(tailr, "^(%b())(.*)$") if not t.vreg then werror("bad variable register expression") end end -- reg if tailr == "" then if t.opsize then werror("bad operand size override") end t.opsize = map_reg_opsize[reg] if t.opsize == "f" then t.mode = t.reg == 0 and "fF" or "f" else if reg == "@w4" or (x64 and reg == "@d4") then wwarn("bad idea, try again with `"..(x64 and "rsp'" or "esp'")) end t.mode = t.reg == 0 and "rmR" or (reg == "@b1" and "rmC" or "rm") end t.needrex = map_reg_needrex[reg] break end -- type[idx], type[idx].field, type->field -> [reg+offset_expr] if not tp then werror("bad operand `"..param.."'") end t.mode = "xm" t.disp = format(tp.ctypefmt, tailr) else t.mode, t.imm = immexpr(expr) if sub(t.mode, -1) == "J" then if t.opsize and t.opsize ~= addrsize then werror("bad operand size override") end t.opsize = addrsize end end end until true return t end ------------------------------------------------------------------------------ -- x86 Template String Description -- =============================== -- -- Each template string is a list of [match:]pattern pairs, -- separated by "|". The first match wins. No match means a -- bad or unsupported combination of operand modes or sizes. -- -- The match part and the ":" is omitted if the operation has -- no operands. Otherwise the first N characters are matched -- against the mode strings of each of the N operands. -- -- The mode string for each operand type is (see parseoperand()): -- Integer register: "rm", +"R" for eax, ax, al, +"C" for cl -- FP register: "f", +"F" for st0 -- Index operand: "xm", +"O" for [disp] (pure offset) -- Immediate: "i", +"S" for signed 8 bit, +"1" for 1, -- +"I" for arg, +"P" for pointer -- Any: +"J" for valid jump targets -- -- So a match character "m" (mixed) matches both an integer register -- and an index operand (to be encoded with the ModRM/SIB scheme). -- But "r" matches only a register and "x" only an index operand -- (e.g. for FP memory access operations). -- -- The operand size match string starts right after the mode match -- characters and ends before the ":". "dwb" or "qdwb" is assumed, if empty. -- The effective data size of the operation is matched against this list. -- -- If only the regular "b", "w", "d", "q", "t" operand sizes are -- present, then all operands must be the same size. Unspecified sizes -- are ignored, but at least one operand must have a size or the pattern -- won't match (use the "byte", "word", "dword", "qword", "tword" -- operand size overrides. E.g.: mov dword [eax], 1). -- -- If the list has a "1" or "2" prefix, the operand size is taken -- from the respective operand and any other operand sizes are ignored. -- If the list contains only ".", all operand sizes are ignored. -- If the list has a "/" prefix, the concatenated (mixed) operand sizes -- are compared to the match. -- -- E.g. "rrdw" matches for either two dword registers or two word -- registers. "Fx2dq" matches an st0 operand plus an index operand -- pointing to a dword (float) or qword (double). -- -- Every character after the ":" is part of the pattern string: -- Hex chars are accumulated to form the opcode (left to right). -- "n" disables the standard opcode mods -- (otherwise: -1 for "b", o16 prefix for "w", rex.w for "q") -- "X" Force REX.W. -- "r"/"R" adds the reg. number from the 1st/2nd operand to the opcode. -- "m"/"M" generates ModRM/SIB from the 1st/2nd operand. -- The spare 3 bits are either filled with the last hex digit or -- the result from a previous "r"/"R". The opcode is restored. -- "u" Use VEX encoding, vvvv unused. -- "v"/"V" Use VEX encoding, vvvv from 1st/2nd operand (the operand is -- removed from the list used by future characters). -- "L" Force VEX.L -- -- All of the following characters force a flush of the opcode: -- "o"/"O" stores a pure 32 bit disp (offset) from the 1st/2nd operand. -- "s" stores a 4 bit immediate from the last register operand, -- followed by 4 zero bits. -- "S" stores a signed 8 bit immediate from the last operand. -- "U" stores an unsigned 8 bit immediate from the last operand. -- "W" stores an unsigned 16 bit immediate from the last operand. -- "i" stores an operand sized immediate from the last operand. -- "I" dito, but generates an action code to optionally modify -- the opcode (+2) for a signed 8 bit immediate. -- "J" generates one of the REL action codes from the last operand. -- ------------------------------------------------------------------------------ -- Template strings for x86 instructions. Ordered by first opcode byte. -- Unimplemented opcodes (deliberate omissions) are marked with *. local map_op = { -- 00-05: add... -- 06: *push es -- 07: *pop es -- 08-0D: or... -- 0E: *push cs -- 0F: two byte opcode prefix -- 10-15: adc... -- 16: *push ss -- 17: *pop ss -- 18-1D: sbb... -- 1E: *push ds -- 1F: *pop ds -- 20-25: and... es_0 = "26", -- 27: *daa -- 28-2D: sub... cs_0 = "2E", -- 2F: *das -- 30-35: xor... ss_0 = "36", -- 37: *aaa -- 38-3D: cmp... ds_0 = "3E", -- 3F: *aas inc_1 = x64 and "m:FF0m" or "rdw:40r|m:FF0m", dec_1 = x64 and "m:FF1m" or "rdw:48r|m:FF1m", push_1 = (x64 and "rq:n50r|rw:50r|mq:nFF6m|mw:FF6m" or "rdw:50r|mdw:FF6m").."|S.:6AS|ib:n6Ai|i.:68i", pop_1 = x64 and "rq:n58r|rw:58r|mq:n8F0m|mw:8F0m" or "rdw:58r|mdw:8F0m", -- 60: *pusha, *pushad, *pushaw -- 61: *popa, *popad, *popaw -- 62: *bound rdw,x -- 63: x86: *arpl mw,rw movsxd_2 = x64 and "rm/qd:63rM", fs_0 = "64", gs_0 = "65", o16_0 = "66", a16_0 = not x64 and "67" or nil, a32_0 = x64 and "67", -- 68: push idw -- 69: imul rdw,mdw,idw -- 6A: push ib -- 6B: imul rdw,mdw,S -- 6C: *insb -- 6D: *insd, *insw -- 6E: *outsb -- 6F: *outsd, *outsw -- 70-7F: jcc lb -- 80: add... mb,i -- 81: add... mdw,i -- 82: *undefined -- 83: add... mdw,S test_2 = "mr:85Rm|rm:85rM|Ri:A9ri|mi:F70mi", -- 86: xchg rb,mb -- 87: xchg rdw,mdw -- 88: mov mb,r -- 89: mov mdw,r -- 8A: mov r,mb -- 8B: mov r,mdw -- 8C: *mov mdw,seg lea_2 = "rx1dq:8DrM", -- 8E: *mov seg,mdw -- 8F: pop mdw nop_0 = "90", xchg_2 = "Rrqdw:90R|rRqdw:90r|rm:87rM|mr:87Rm", cbw_0 = "6698", cwde_0 = "98", cdqe_0 = "4898", cwd_0 = "6699", cdq_0 = "99", cqo_0 = "4899", -- 9A: *call iw:idw wait_0 = "9B", fwait_0 = "9B", pushf_0 = "9C", pushfd_0 = not x64 and "9C", pushfq_0 = x64 and "9C", popf_0 = "9D", popfd_0 = not x64 and "9D", popfq_0 = x64 and "9D", sahf_0 = "9E", lahf_0 = "9F", mov_2 = "OR:A3o|RO:A1O|mr:89Rm|rm:8BrM|rib:nB0ri|ridw:B8ri|mi:C70mi", movsb_0 = "A4", movsw_0 = "66A5", movsd_0 = "A5", cmpsb_0 = "A6", cmpsw_0 = "66A7", cmpsd_0 = "A7", -- A8: test Rb,i -- A9: test Rdw,i stosb_0 = "AA", stosw_0 = "66AB", stosd_0 = "AB", lodsb_0 = "AC", lodsw_0 = "66AD", lodsd_0 = "AD", scasb_0 = "AE", scasw_0 = "66AF", scasd_0 = "AF", -- B0-B7: mov rb,i -- B8-BF: mov rdw,i -- C0: rol... mb,i -- C1: rol... mdw,i ret_1 = "i.:nC2W", ret_0 = "C3", -- C4: *les rdw,mq -- C5: *lds rdw,mq -- C6: mov mb,i -- C7: mov mdw,i -- C8: *enter iw,ib leave_0 = "C9", -- CA: *retf iw -- CB: *retf int3_0 = "CC", int_1 = "i.:nCDU", into_0 = "CE", -- CF: *iret -- D0: rol... mb,1 -- D1: rol... mdw,1 -- D2: rol... mb,cl -- D3: rol... mb,cl -- D4: *aam ib -- D5: *aad ib -- D6: *salc -- D7: *xlat -- D8-DF: floating point ops -- E0: *loopne -- E1: *loope -- E2: *loop -- E3: *jcxz, *jecxz -- E4: *in Rb,ib -- E5: *in Rdw,ib -- E6: *out ib,Rb -- E7: *out ib,Rdw call_1 = x64 and "mq:nFF2m|J.:E8nJ" or "md:FF2m|J.:E8J", jmp_1 = x64 and "mq:nFF4m|J.:E9nJ" or "md:FF4m|J.:E9J", -- short: EB -- EA: *jmp iw:idw -- EB: jmp ib -- EC: *in Rb,dx -- ED: *in Rdw,dx -- EE: *out dx,Rb -- EF: *out dx,Rdw lock_0 = "F0", int1_0 = "F1", repne_0 = "F2", repnz_0 = "F2", rep_0 = "F3", repe_0 = "F3", repz_0 = "F3", -- F4: *hlt cmc_0 = "F5", -- F6: test... mb,i; div... mb -- F7: test... mdw,i; div... mdw clc_0 = "F8", stc_0 = "F9", -- FA: *cli cld_0 = "FC", std_0 = "FD", -- FE: inc... mb -- FF: inc... mdw -- misc ops not_1 = "m:F72m", neg_1 = "m:F73m", mul_1 = "m:F74m", imul_1 = "m:F75m", div_1 = "m:F76m", idiv_1 = "m:F77m", imul_2 = "rmqdw:0FAFrM|rIqdw:69rmI|rSqdw:6BrmS|riqdw:69rmi", imul_3 = "rmIqdw:69rMI|rmSqdw:6BrMS|rmiqdw:69rMi", movzx_2 = "rm/db:0FB6rM|rm/qb:|rm/wb:0FB6rM|rm/dw:0FB7rM|rm/qw:", movsx_2 = "rm/db:0FBErM|rm/qb:|rm/wb:0FBErM|rm/dw:0FBFrM|rm/qw:", bswap_1 = "rqd:0FC8r", bsf_2 = "rmqdw:0FBCrM", bsr_2 = "rmqdw:0FBDrM", bt_2 = "mrqdw:0FA3Rm|miqdw:0FBA4mU", btc_2 = "mrqdw:0FBBRm|miqdw:0FBA7mU", btr_2 = "mrqdw:0FB3Rm|miqdw:0FBA6mU", bts_2 = "mrqdw:0FABRm|miqdw:0FBA5mU", shld_3 = "mriqdw:0FA4RmU|mrC/qq:0FA5Rm|mrC/dd:|mrC/ww:", shrd_3 = "mriqdw:0FACRmU|mrC/qq:0FADRm|mrC/dd:|mrC/ww:", rdtsc_0 = "0F31", -- P1+ rdpmc_0 = "0F33", -- P6+ cpuid_0 = "0FA2", -- P1+ -- floating point ops fst_1 = "ff:DDD0r|xd:D92m|xq:nDD2m", fstp_1 = "ff:DDD8r|xd:D93m|xq:nDD3m|xt:DB7m", fld_1 = "ff:D9C0r|xd:D90m|xq:nDD0m|xt:DB5m", fpop_0 = "DDD8", -- Alias for fstp st0. fist_1 = "xw:nDF2m|xd:DB2m", fistp_1 = "xw:nDF3m|xd:DB3m|xq:nDF7m", fild_1 = "xw:nDF0m|xd:DB0m|xq:nDF5m", fxch_0 = "D9C9", fxch_1 = "ff:D9C8r", fxch_2 = "fFf:D9C8r|Fff:D9C8R", fucom_1 = "ff:DDE0r", fucom_2 = "Fff:DDE0R", fucomp_1 = "ff:DDE8r", fucomp_2 = "Fff:DDE8R", fucomi_1 = "ff:DBE8r", -- P6+ fucomi_2 = "Fff:DBE8R", -- P6+ fucomip_1 = "ff:DFE8r", -- P6+ fucomip_2 = "Fff:DFE8R", -- P6+ fcomi_1 = "ff:DBF0r", -- P6+ fcomi_2 = "Fff:DBF0R", -- P6+ fcomip_1 = "ff:DFF0r", -- P6+ fcomip_2 = "Fff:DFF0R", -- P6+ fucompp_0 = "DAE9", fcompp_0 = "DED9", fldenv_1 = "x.:D94m", fnstenv_1 = "x.:D96m", fstenv_1 = "x.:9BD96m", fldcw_1 = "xw:nD95m", fstcw_1 = "xw:n9BD97m", fnstcw_1 = "xw:nD97m", fstsw_1 = "Rw:n9BDFE0|xw:n9BDD7m", fnstsw_1 = "Rw:nDFE0|xw:nDD7m", fclex_0 = "9BDBE2", fnclex_0 = "DBE2", fnop_0 = "D9D0", -- D9D1-D9DF: unassigned fchs_0 = "D9E0", fabs_0 = "D9E1", -- D9E2: unassigned -- D9E3: unassigned ftst_0 = "D9E4", fxam_0 = "D9E5", -- D9E6: unassigned -- D9E7: unassigned fld1_0 = "D9E8", fldl2t_0 = "D9E9", fldl2e_0 = "D9EA", fldpi_0 = "D9EB", fldlg2_0 = "D9EC", fldln2_0 = "D9ED", fldz_0 = "D9EE", -- D9EF: unassigned f2xm1_0 = "D9F0", fyl2x_0 = "D9F1", fptan_0 = "D9F2", fpatan_0 = "D9F3", fxtract_0 = "D9F4", fprem1_0 = "D9F5", fdecstp_0 = "D9F6", fincstp_0 = "D9F7", fprem_0 = "D9F8", fyl2xp1_0 = "D9F9", fsqrt_0 = "D9FA", fsincos_0 = "D9FB", frndint_0 = "D9FC", fscale_0 = "D9FD", fsin_0 = "D9FE", fcos_0 = "D9FF", -- SSE, SSE2 andnpd_2 = "rmo:660F55rM", andnps_2 = "rmo:0F55rM", andpd_2 = "rmo:660F54rM", andps_2 = "rmo:0F54rM", clflush_1 = "x.:0FAE7m", cmppd_3 = "rmio:660FC2rMU", cmpps_3 = "rmio:0FC2rMU", cmpsd_3 = "rrio:F20FC2rMU|rxi/oq:", cmpss_3 = "rrio:F30FC2rMU|rxi/od:", comisd_2 = "rro:660F2FrM|rx/oq:", comiss_2 = "rro:0F2FrM|rx/od:", cvtdq2pd_2 = "rro:F30FE6rM|rx/oq:", cvtdq2ps_2 = "rmo:0F5BrM", cvtpd2dq_2 = "rmo:F20FE6rM", cvtpd2ps_2 = "rmo:660F5ArM", cvtpi2pd_2 = "rx/oq:660F2ArM", cvtpi2ps_2 = "rx/oq:0F2ArM", cvtps2dq_2 = "rmo:660F5BrM", cvtps2pd_2 = "rro:0F5ArM|rx/oq:", cvtsd2si_2 = "rr/do:F20F2DrM|rr/qo:|rx/dq:|rxq:", cvtsd2ss_2 = "rro:F20F5ArM|rx/oq:", cvtsi2sd_2 = "rm/od:F20F2ArM|rm/oq:F20F2ArXM", cvtsi2ss_2 = "rm/od:F30F2ArM|rm/oq:F30F2ArXM", cvtss2sd_2 = "rro:F30F5ArM|rx/od:", cvtss2si_2 = "rr/do:F30F2DrM|rr/qo:|rxd:|rx/qd:", cvttpd2dq_2 = "rmo:660FE6rM", cvttps2dq_2 = "rmo:F30F5BrM", cvttsd2si_2 = "rr/do:F20F2CrM|rr/qo:|rx/dq:|rxq:", cvttss2si_2 = "rr/do:F30F2CrM|rr/qo:|rxd:|rx/qd:", fxsave_1 = "x.:0FAE0m", fxrstor_1 = "x.:0FAE1m", ldmxcsr_1 = "xd:0FAE2m", lfence_0 = "0FAEE8", maskmovdqu_2 = "rro:660FF7rM", mfence_0 = "0FAEF0", movapd_2 = "rmo:660F28rM|mro:660F29Rm", movaps_2 = "rmo:0F28rM|mro:0F29Rm", movd_2 = "rm/od:660F6ErM|rm/oq:660F6ErXM|mr/do:660F7ERm|mr/qo:", movdqa_2 = "rmo:660F6FrM|mro:660F7FRm", movdqu_2 = "rmo:F30F6FrM|mro:F30F7FRm", movhlps_2 = "rro:0F12rM", movhpd_2 = "rx/oq:660F16rM|xr/qo:n660F17Rm", movhps_2 = "rx/oq:0F16rM|xr/qo:n0F17Rm", movlhps_2 = "rro:0F16rM", movlpd_2 = "rx/oq:660F12rM|xr/qo:n660F13Rm", movlps_2 = "rx/oq:0F12rM|xr/qo:n0F13Rm", movmskpd_2 = "rr/do:660F50rM", movmskps_2 = "rr/do:0F50rM", movntdq_2 = "xro:660FE7Rm", movnti_2 = "xrqd:0FC3Rm", movntpd_2 = "xro:660F2BRm", movntps_2 = "xro:0F2BRm", movq_2 = "rro:F30F7ErM|rx/oq:|xr/qo:n660FD6Rm", movsd_2 = "rro:F20F10rM|rx/oq:|xr/qo:nF20F11Rm", movss_2 = "rro:F30F10rM|rx/od:|xr/do:F30F11Rm", movupd_2 = "rmo:660F10rM|mro:660F11Rm", movups_2 = "rmo:0F10rM|mro:0F11Rm", orpd_2 = "rmo:660F56rM", orps_2 = "rmo:0F56rM", pause_0 = "F390", pextrw_3 = "rri/do:660FC5rMU|xri/wo:660F3A15nRmU", -- Mem op: SSE4.1 only. pinsrw_3 = "rri/od:660FC4rMU|rxi/ow:", pmovmskb_2 = "rr/do:660FD7rM", prefetchnta_1 = "xb:n0F180m", prefetcht0_1 = "xb:n0F181m", prefetcht1_1 = "xb:n0F182m", prefetcht2_1 = "xb:n0F183m", pshufd_3 = "rmio:660F70rMU", pshufhw_3 = "rmio:F30F70rMU", pshuflw_3 = "rmio:F20F70rMU", pslld_2 = "rmo:660FF2rM|rio:660F726mU", pslldq_2 = "rio:660F737mU", psllq_2 = "rmo:660FF3rM|rio:660F736mU", psllw_2 = "rmo:660FF1rM|rio:660F716mU", psrad_2 = "rmo:660FE2rM|rio:660F724mU", psraw_2 = "rmo:660FE1rM|rio:660F714mU", psrld_2 = "rmo:660FD2rM|rio:660F722mU", psrldq_2 = "rio:660F733mU", psrlq_2 = "rmo:660FD3rM|rio:660F732mU", psrlw_2 = "rmo:660FD1rM|rio:660F712mU", rcpps_2 = "rmo:0F53rM", rcpss_2 = "rro:F30F53rM|rx/od:", rsqrtps_2 = "rmo:0F52rM", rsqrtss_2 = "rmo:F30F52rM", sfence_0 = "0FAEF8", shufpd_3 = "rmio:660FC6rMU", shufps_3 = "rmio:0FC6rMU", stmxcsr_1 = "xd:0FAE3m", ucomisd_2 = "rro:660F2ErM|rx/oq:", ucomiss_2 = "rro:0F2ErM|rx/od:", unpckhpd_2 = "rmo:660F15rM", unpckhps_2 = "rmo:0F15rM", unpcklpd_2 = "rmo:660F14rM", unpcklps_2 = "rmo:0F14rM", xorpd_2 = "rmo:660F57rM", xorps_2 = "rmo:0F57rM", -- SSE3 ops fisttp_1 = "xw:nDF1m|xd:DB1m|xq:nDD1m", addsubpd_2 = "rmo:660FD0rM", addsubps_2 = "rmo:F20FD0rM", haddpd_2 = "rmo:660F7CrM", haddps_2 = "rmo:F20F7CrM", hsubpd_2 = "rmo:660F7DrM", hsubps_2 = "rmo:F20F7DrM", lddqu_2 = "rxo:F20FF0rM", movddup_2 = "rmo:F20F12rM", movshdup_2 = "rmo:F30F16rM", movsldup_2 = "rmo:F30F12rM", -- SSSE3 ops pabsb_2 = "rmo:660F381CrM", pabsd_2 = "rmo:660F381ErM", pabsw_2 = "rmo:660F381DrM", palignr_3 = "rmio:660F3A0FrMU", phaddd_2 = "rmo:660F3802rM", phaddsw_2 = "rmo:660F3803rM", phaddw_2 = "rmo:660F3801rM", phsubd_2 = "rmo:660F3806rM", phsubsw_2 = "rmo:660F3807rM", phsubw_2 = "rmo:660F3805rM", pmaddubsw_2 = "rmo:660F3804rM", pmulhrsw_2 = "rmo:660F380BrM", pshufb_2 = "rmo:660F3800rM", psignb_2 = "rmo:660F3808rM", psignd_2 = "rmo:660F380ArM", psignw_2 = "rmo:660F3809rM", -- SSE4.1 ops blendpd_3 = "rmio:660F3A0DrMU", blendps_3 = "rmio:660F3A0CrMU", blendvpd_3 = "rmRo:660F3815rM", blendvps_3 = "rmRo:660F3814rM", dppd_3 = "rmio:660F3A41rMU", dpps_3 = "rmio:660F3A40rMU", extractps_3 = "mri/do:660F3A17RmU|rri/qo:660F3A17RXmU", insertps_3 = "rrio:660F3A41rMU|rxi/od:", movntdqa_2 = "rxo:660F382ArM", mpsadbw_3 = "rmio:660F3A42rMU", packusdw_2 = "rmo:660F382BrM", pblendvb_3 = "rmRo:660F3810rM", pblendw_3 = "rmio:660F3A0ErMU", pcmpeqq_2 = "rmo:660F3829rM", pextrb_3 = "rri/do:660F3A14nRmU|rri/qo:|xri/bo:", pextrd_3 = "mri/do:660F3A16RmU", pextrq_3 = "mri/qo:660F3A16RmU", -- pextrw is SSE2, mem operand is SSE4.1 only phminposuw_2 = "rmo:660F3841rM", pinsrb_3 = "rri/od:660F3A20nrMU|rxi/ob:", pinsrd_3 = "rmi/od:660F3A22rMU", pinsrq_3 = "rmi/oq:660F3A22rXMU", pmaxsb_2 = "rmo:660F383CrM", pmaxsd_2 = "rmo:660F383DrM", pmaxud_2 = "rmo:660F383FrM", pmaxuw_2 = "rmo:660F383ErM", pminsb_2 = "rmo:660F3838rM", pminsd_2 = "rmo:660F3839rM", pminud_2 = "rmo:660F383BrM", pminuw_2 = "rmo:660F383ArM", pmovsxbd_2 = "rro:660F3821rM|rx/od:", pmovsxbq_2 = "rro:660F3822rM|rx/ow:", pmovsxbw_2 = "rro:660F3820rM|rx/oq:", pmovsxdq_2 = "rro:660F3825rM|rx/oq:", pmovsxwd_2 = "rro:660F3823rM|rx/oq:", pmovsxwq_2 = "rro:660F3824rM|rx/od:", pmovzxbd_2 = "rro:660F3831rM|rx/od:", pmovzxbq_2 = "rro:660F3832rM|rx/ow:", pmovzxbw_2 = "rro:660F3830rM|rx/oq:", pmovzxdq_2 = "rro:660F3835rM|rx/oq:", pmovzxwd_2 = "rro:660F3833rM|rx/oq:", pmovzxwq_2 = "rro:660F3834rM|rx/od:", pmuldq_2 = "rmo:660F3828rM", pmulld_2 = "rmo:660F3840rM", ptest_2 = "rmo:660F3817rM", roundpd_3 = "rmio:660F3A09rMU", roundps_3 = "rmio:660F3A08rMU", roundsd_3 = "rrio:660F3A0BrMU|rxi/oq:", roundss_3 = "rrio:660F3A0ArMU|rxi/od:", -- SSE4.2 ops crc32_2 = "rmqd:F20F38F1rM|rm/dw:66F20F38F1rM|rm/db:F20F38F0rM|rm/qb:", pcmpestri_3 = "rmio:660F3A61rMU", pcmpestrm_3 = "rmio:660F3A60rMU", pcmpgtq_2 = "rmo:660F3837rM", pcmpistri_3 = "rmio:660F3A63rMU", pcmpistrm_3 = "rmio:660F3A62rMU", popcnt_2 = "rmqdw:F30FB8rM", -- SSE4a extrq_2 = "rro:660F79rM", extrq_3 = "riio:660F780mUU", insertq_2 = "rro:F20F79rM", insertq_4 = "rriio:F20F78rMUU", lzcnt_2 = "rmqdw:F30FBDrM", movntsd_2 = "xr/qo:nF20F2BRm", movntss_2 = "xr/do:F30F2BRm", -- popcnt is also in SSE4.2 -- AES-NI aesdec_2 = "rmo:660F38DErM", aesdeclast_2 = "rmo:660F38DFrM", aesenc_2 = "rmo:660F38DCrM", aesenclast_2 = "rmo:660F38DDrM", aesimc_2 = "rmo:660F38DBrM", aeskeygenassist_3 = "rmio:660F3ADFrMU", pclmulqdq_3 = "rmio:660F3A44rMU", -- AVX FP ops vaddsubpd_3 = "rrmoy:660FVD0rM", vaddsubps_3 = "rrmoy:F20FVD0rM", vandpd_3 = "rrmoy:660FV54rM", vandps_3 = "rrmoy:0FV54rM", vandnpd_3 = "rrmoy:660FV55rM", vandnps_3 = "rrmoy:0FV55rM", vblendpd_4 = "rrmioy:660F3AV0DrMU", vblendps_4 = "rrmioy:660F3AV0CrMU", vblendvpd_4 = "rrmroy:660F3AV4BrMs", vblendvps_4 = "rrmroy:660F3AV4ArMs", vbroadcastf128_2 = "rx/yo:660F38u1ArM", vcmppd_4 = "rrmioy:660FVC2rMU", vcmpps_4 = "rrmioy:0FVC2rMU", vcmpsd_4 = "rrrio:F20FVC2rMU|rrxi/ooq:", vcmpss_4 = "rrrio:F30FVC2rMU|rrxi/ood:", vcomisd_2 = "rro:660Fu2FrM|rx/oq:", vcomiss_2 = "rro:0Fu2FrM|rx/od:", vcvtdq2pd_2 = "rro:F30FuE6rM|rx/oq:|rm/yo:", vcvtdq2ps_2 = "rmoy:0Fu5BrM", vcvtpd2dq_2 = "rmoy:F20FuE6rM", vcvtpd2ps_2 = "rmoy:660Fu5ArM", vcvtps2dq_2 = "rmoy:660Fu5BrM", vcvtps2pd_2 = "rro:0Fu5ArM|rx/oq:|rm/yo:", vcvtsd2si_2 = "rr/do:F20Fu2DrM|rx/dq:|rr/qo:|rxq:", vcvtsd2ss_3 = "rrro:F20FV5ArM|rrx/ooq:", vcvtsi2sd_3 = "rrm/ood:F20FV2ArM|rrm/ooq:F20FVX2ArM", vcvtsi2ss_3 = "rrm/ood:F30FV2ArM|rrm/ooq:F30FVX2ArM", vcvtss2sd_3 = "rrro:F30FV5ArM|rrx/ood:", vcvtss2si_2 = "rr/do:F30Fu2DrM|rxd:|rr/qo:|rx/qd:", vcvttpd2dq_2 = "rmo:660FuE6rM|rm/oy:660FuLE6rM", vcvttps2dq_2 = "rmoy:F30Fu5BrM", vcvttsd2si_2 = "rr/do:F20Fu2CrM|rx/dq:|rr/qo:|rxq:", vcvttss2si_2 = "rr/do:F30Fu2CrM|rxd:|rr/qo:|rx/qd:", vdppd_4 = "rrmio:660F3AV41rMU", vdpps_4 = "rrmioy:660F3AV40rMU", vextractf128_3 = "mri/oy:660F3AuL19RmU", vextractps_3 = "mri/do:660F3Au17RmU", vhaddpd_3 = "rrmoy:660FV7CrM", vhaddps_3 = "rrmoy:F20FV7CrM", vhsubpd_3 = "rrmoy:660FV7DrM", vhsubps_3 = "rrmoy:F20FV7DrM", vinsertf128_4 = "rrmi/yyo:660F3AV18rMU", vinsertps_4 = "rrrio:660F3AV21rMU|rrxi/ood:", vldmxcsr_1 = "xd:0FuAE2m", vmaskmovps_3 = "rrxoy:660F38V2CrM|xrroy:660F38V2ERm", vmaskmovpd_3 = "rrxoy:660F38V2DrM|xrroy:660F38V2FRm", vmovapd_2 = "rmoy:660Fu28rM|mroy:660Fu29Rm", vmovaps_2 = "rmoy:0Fu28rM|mroy:0Fu29Rm", vmovd_2 = "rm/od:660Fu6ErM|rm/oq:660FuX6ErM|mr/do:660Fu7ERm|mr/qo:", vmovq_2 = "rro:F30Fu7ErM|rx/oq:|xr/qo:660FuD6Rm", vmovddup_2 = "rmy:F20Fu12rM|rro:|rx/oq:", vmovhlps_3 = "rrro:0FV12rM", vmovhpd_2 = "xr/qo:660Fu17Rm", vmovhpd_3 = "rrx/ooq:660FV16rM", vmovhps_2 = "xr/qo:0Fu17Rm", vmovhps_3 = "rrx/ooq:0FV16rM", vmovlhps_3 = "rrro:0FV16rM", vmovlpd_2 = "xr/qo:660Fu13Rm", vmovlpd_3 = "rrx/ooq:660FV12rM", vmovlps_2 = "xr/qo:0Fu13Rm", vmovlps_3 = "rrx/ooq:0FV12rM", vmovmskpd_2 = "rr/do:660Fu50rM|rr/dy:660FuL50rM", vmovmskps_2 = "rr/do:0Fu50rM|rr/dy:0FuL50rM", vmovntpd_2 = "xroy:660Fu2BRm", vmovntps_2 = "xroy:0Fu2BRm", vmovsd_2 = "rx/oq:F20Fu10rM|xr/qo:F20Fu11Rm", vmovsd_3 = "rrro:F20FV10rM", vmovshdup_2 = "rmoy:F30Fu16rM", vmovsldup_2 = "rmoy:F30Fu12rM", vmovss_2 = "rx/od:F30Fu10rM|xr/do:F30Fu11Rm", vmovss_3 = "rrro:F30FV10rM", vmovupd_2 = "rmoy:660Fu10rM|mroy:660Fu11Rm", vmovups_2 = "rmoy:0Fu10rM|mroy:0Fu11Rm", vorpd_3 = "rrmoy:660FV56rM", vorps_3 = "rrmoy:0FV56rM", vpermilpd_3 = "rrmoy:660F38V0DrM|rmioy:660F3Au05rMU", vpermilps_3 = "rrmoy:660F38V0CrM|rmioy:660F3Au04rMU", vperm2f128_4 = "rrmiy:660F3AV06rMU", vptestpd_2 = "rmoy:660F38u0FrM", vptestps_2 = "rmoy:660F38u0ErM", vrcpps_2 = "rmoy:0Fu53rM", vrcpss_3 = "rrro:F30FV53rM|rrx/ood:", vrsqrtps_2 = "rmoy:0Fu52rM", vrsqrtss_3 = "rrro:F30FV52rM|rrx/ood:", vroundpd_3 = "rmioy:660F3AV09rMU", vroundps_3 = "rmioy:660F3AV08rMU", vroundsd_4 = "rrrio:660F3AV0BrMU|rrxi/ooq:", vroundss_4 = "rrrio:660F3AV0ArMU|rrxi/ood:", vshufpd_4 = "rrmioy:660FVC6rMU", vshufps_4 = "rrmioy:0FVC6rMU", vsqrtps_2 = "rmoy:0Fu51rM", vsqrtss_2 = "rro:F30Fu51rM|rx/od:", vsqrtpd_2 = "rmoy:660Fu51rM", vsqrtsd_2 = "rro:F20Fu51rM|rx/oq:", vstmxcsr_1 = "xd:0FuAE3m", vucomisd_2 = "rro:660Fu2ErM|rx/oq:", vucomiss_2 = "rro:0Fu2ErM|rx/od:", vunpckhpd_3 = "rrmoy:660FV15rM", vunpckhps_3 = "rrmoy:0FV15rM", vunpcklpd_3 = "rrmoy:660FV14rM", vunpcklps_3 = "rrmoy:0FV14rM", vxorpd_3 = "rrmoy:660FV57rM", vxorps_3 = "rrmoy:0FV57rM", vzeroall_0 = "0FuL77", vzeroupper_0 = "0Fu77", -- AVX2 FP ops vbroadcastss_2 = "rx/od:660F38u18rM|rx/yd:|rro:|rr/yo:", vbroadcastsd_2 = "rx/yq:660F38u19rM|rr/yo:", -- *vgather* (!vsib) vpermpd_3 = "rmiy:660F3AuX01rMU", vpermps_3 = "rrmy:660F38V16rM", -- AVX, AVX2 integer ops -- In general, xmm requires AVX, ymm requires AVX2. vaesdec_3 = "rrmo:660F38VDErM", vaesdeclast_3 = "rrmo:660F38VDFrM", vaesenc_3 = "rrmo:660F38VDCrM", vaesenclast_3 = "rrmo:660F38VDDrM", vaesimc_2 = "rmo:660F38uDBrM", vaeskeygenassist_3 = "rmio:660F3AuDFrMU", vlddqu_2 = "rxoy:F20FuF0rM", vmaskmovdqu_2 = "rro:660FuF7rM", vmovdqa_2 = "rmoy:660Fu6FrM|mroy:660Fu7FRm", vmovdqu_2 = "rmoy:F30Fu6FrM|mroy:F30Fu7FRm", vmovntdq_2 = "xroy:660FuE7Rm", vmovntdqa_2 = "rxoy:660F38u2ArM", vmpsadbw_4 = "rrmioy:660F3AV42rMU", vpabsb_2 = "rmoy:660F38u1CrM", vpabsd_2 = "rmoy:660F38u1ErM", vpabsw_2 = "rmoy:660F38u1DrM", vpackusdw_3 = "rrmoy:660F38V2BrM", vpalignr_4 = "rrmioy:660F3AV0FrMU", vpblendvb_4 = "rrmroy:660F3AV4CrMs", vpblendw_4 = "rrmioy:660F3AV0ErMU", vpclmulqdq_4 = "rrmio:660F3AV44rMU", vpcmpeqq_3 = "rrmoy:660F38V29rM", vpcmpestri_3 = "rmio:660F3Au61rMU", vpcmpestrm_3 = "rmio:660F3Au60rMU", vpcmpgtq_3 = "rrmoy:660F38V37rM", vpcmpistri_3 = "rmio:660F3Au63rMU", vpcmpistrm_3 = "rmio:660F3Au62rMU", vpextrb_3 = "rri/do:660F3Au14nRmU|rri/qo:|xri/bo:", vpextrw_3 = "rri/do:660FuC5rMU|xri/wo:660F3Au15nRmU", vpextrd_3 = "mri/do:660F3Au16RmU", vpextrq_3 = "mri/qo:660F3Au16RmU", vphaddw_3 = "rrmoy:660F38V01rM", vphaddd_3 = "rrmoy:660F38V02rM", vphaddsw_3 = "rrmoy:660F38V03rM", vphminposuw_2 = "rmo:660F38u41rM", vphsubw_3 = "rrmoy:660F38V05rM", vphsubd_3 = "rrmoy:660F38V06rM", vphsubsw_3 = "rrmoy:660F38V07rM", vpinsrb_4 = "rrri/ood:660F3AV20rMU|rrxi/oob:", vpinsrw_4 = "rrri/ood:660FVC4rMU|rrxi/oow:", vpinsrd_4 = "rrmi/ood:660F3AV22rMU", vpinsrq_4 = "rrmi/ooq:660F3AVX22rMU", vpmaddubsw_3 = "rrmoy:660F38V04rM", vpmaxsb_3 = "rrmoy:660F38V3CrM", vpmaxsd_3 = "rrmoy:660F38V3DrM", vpmaxuw_3 = "rrmoy:660F38V3ErM", vpmaxud_3 = "rrmoy:660F38V3FrM", vpminsb_3 = "rrmoy:660F38V38rM", vpminsd_3 = "rrmoy:660F38V39rM", vpminuw_3 = "rrmoy:660F38V3ArM", vpminud_3 = "rrmoy:660F38V3BrM", vpmovmskb_2 = "rr/do:660FuD7rM|rr/dy:660FuLD7rM", vpmovsxbw_2 = "rroy:660F38u20rM|rx/oq:|rx/yo:", vpmovsxbd_2 = "rroy:660F38u21rM|rx/od:|rx/yq:", vpmovsxbq_2 = "rroy:660F38u22rM|rx/ow:|rx/yd:", vpmovsxwd_2 = "rroy:660F38u23rM|rx/oq:|rx/yo:", vpmovsxwq_2 = "rroy:660F38u24rM|rx/od:|rx/yq:", vpmovsxdq_2 = "rroy:660F38u25rM|rx/oq:|rx/yo:", vpmovzxbw_2 = "rroy:660F38u30rM|rx/oq:|rx/yo:", vpmovzxbd_2 = "rroy:660F38u31rM|rx/od:|rx/yq:", vpmovzxbq_2 = "rroy:660F38u32rM|rx/ow:|rx/yd:", vpmovzxwd_2 = "rroy:660F38u33rM|rx/oq:|rx/yo:", vpmovzxwq_2 = "rroy:660F38u34rM|rx/od:|rx/yq:", vpmovzxdq_2 = "rroy:660F38u35rM|rx/oq:|rx/yo:", vpmuldq_3 = "rrmoy:660F38V28rM", vpmulhrsw_3 = "rrmoy:660F38V0BrM", vpmulld_3 = "rrmoy:660F38V40rM", vpshufb_3 = "rrmoy:660F38V00rM", vpshufd_3 = "rmioy:660Fu70rMU", vpshufhw_3 = "rmioy:F30Fu70rMU", vpshuflw_3 = "rmioy:F20Fu70rMU", vpsignb_3 = "rrmoy:660F38V08rM", vpsignw_3 = "rrmoy:660F38V09rM", vpsignd_3 = "rrmoy:660F38V0ArM", vpslldq_3 = "rrioy:660Fv737mU", vpsllw_3 = "rrmoy:660FVF1rM|rrioy:660Fv716mU", vpslld_3 = "rrmoy:660FVF2rM|rrioy:660Fv726mU", vpsllq_3 = "rrmoy:660FVF3rM|rrioy:660Fv736mU", vpsraw_3 = "rrmoy:660FVE1rM|rrioy:660Fv714mU", vpsrad_3 = "rrmoy:660FVE2rM|rrioy:660Fv724mU", vpsrldq_3 = "rrioy:660Fv733mU", vpsrlw_3 = "rrmoy:660FVD1rM|rrioy:660Fv712mU", vpsrld_3 = "rrmoy:660FVD2rM|rrioy:660Fv722mU", vpsrlq_3 = "rrmoy:660FVD3rM|rrioy:660Fv732mU", vptest_2 = "rmoy:660F38u17rM", -- AVX2 integer ops vbroadcasti128_2 = "rx/yo:660F38u5ArM", vinserti128_4 = "rrmi/yyo:660F3AV38rMU", vextracti128_3 = "mri/oy:660F3AuL39RmU", vpblendd_4 = "rrmioy:660F3AV02rMU", vpbroadcastb_2 = "rro:660F38u78rM|rx/ob:|rr/yo:|rx/yb:", vpbroadcastw_2 = "rro:660F38u79rM|rx/ow:|rr/yo:|rx/yw:", vpbroadcastd_2 = "rro:660F38u58rM|rx/od:|rr/yo:|rx/yd:", vpbroadcastq_2 = "rro:660F38u59rM|rx/oq:|rr/yo:|rx/yq:", vpermd_3 = "rrmy:660F38V36rM", vpermq_3 = "rmiy:660F3AuX00rMU", -- *vpgather* (!vsib) vperm2i128_4 = "rrmiy:660F3AV46rMU", vpmaskmovd_3 = "rrxoy:660F38V8CrM|xrroy:660F38V8ERm", vpmaskmovq_3 = "rrxoy:660F38VX8CrM|xrroy:660F38VX8ERm", vpsllvd_3 = "rrmoy:660F38V47rM", vpsllvq_3 = "rrmoy:660F38VX47rM", vpsravd_3 = "rrmoy:660F38V46rM", vpsrlvd_3 = "rrmoy:660F38V45rM", vpsrlvq_3 = "rrmoy:660F38VX45rM", } ------------------------------------------------------------------------------ -- Arithmetic ops. for name,n in pairs{ add = 0, ["or"] = 1, adc = 2, sbb = 3, ["and"] = 4, sub = 5, xor = 6, cmp = 7 } do local n8 = shl(n, 3) map_op[name.."_2"] = format( "mr:%02XRm|rm:%02XrM|mI1qdw:81%XmI|mS1qdw:83%XmS|Ri1qdwb:%02Xri|mi1qdwb:81%Xmi", 1+n8, 3+n8, n, n, 5+n8, n) end -- Shift ops. for name,n in pairs{ rol = 0, ror = 1, rcl = 2, rcr = 3, shl = 4, shr = 5, sar = 7, sal = 4 } do map_op[name.."_2"] = format("m1:D1%Xm|mC1qdwb:D3%Xm|mi:C1%XmU", n, n, n) end -- Conditional ops. for cc,n in pairs(map_cc) do map_op["j"..cc.."_1"] = format("J.:n0F8%XJ", n) -- short: 7%X map_op["set"..cc.."_1"] = format("mb:n0F9%X2m", n) map_op["cmov"..cc.."_2"] = format("rmqdw:0F4%XrM", n) -- P6+ end -- FP arithmetic ops. for name,n in pairs{ add = 0, mul = 1, com = 2, comp = 3, sub = 4, subr = 5, div = 6, divr = 7 } do local nc = 0xc0 + shl(n, 3) local nr = nc + (n < 4 and 0 or (n % 2 == 0 and 8 or -8)) local fn = "f"..name map_op[fn.."_1"] = format("ff:D8%02Xr|xd:D8%Xm|xq:nDC%Xm", nc, n, n) if n == 2 or n == 3 then map_op[fn.."_2"] = format("Fff:D8%02XR|Fx2d:D8%XM|Fx2q:nDC%XM", nc, n, n) else map_op[fn.."_2"] = format("Fff:D8%02XR|fFf:DC%02Xr|Fx2d:D8%XM|Fx2q:nDC%XM", nc, nr, n, n) map_op[fn.."p_1"] = format("ff:DE%02Xr", nr) map_op[fn.."p_2"] = format("fFf:DE%02Xr", nr) end map_op["fi"..name.."_1"] = format("xd:DA%Xm|xw:nDE%Xm", n, n) end -- FP conditional moves. for cc,n in pairs{ b=0, e=1, be=2, u=3, nb=4, ne=5, nbe=6, nu=7 } do local nc = 0xdac0 + shl(band(n, 3), 3) + shl(band(n, 4), 6) map_op["fcmov"..cc.."_1"] = format("ff:%04Xr", nc) -- P6+ map_op["fcmov"..cc.."_2"] = format("Fff:%04XR", nc) -- P6+ end -- SSE / AVX FP arithmetic ops. for name,n in pairs{ sqrt = 1, add = 8, mul = 9, sub = 12, min = 13, div = 14, max = 15 } do map_op[name.."ps_2"] = format("rmo:0F5%XrM", n) map_op[name.."ss_2"] = format("rro:F30F5%XrM|rx/od:", n) map_op[name.."pd_2"] = format("rmo:660F5%XrM", n) map_op[name.."sd_2"] = format("rro:F20F5%XrM|rx/oq:", n) if n ~= 1 then map_op["v"..name.."ps_3"] = format("rrmoy:0FV5%XrM", n) map_op["v"..name.."ss_3"] = format("rrro:F30FV5%XrM|rrx/ood:", n) map_op["v"..name.."pd_3"] = format("rrmoy:660FV5%XrM", n) map_op["v"..name.."sd_3"] = format("rrro:F20FV5%XrM|rrx/ooq:", n) end end -- SSE2 / AVX / AVX2 integer arithmetic ops (66 0F leaf). for name,n in pairs{ paddb = 0xFC, paddw = 0xFD, paddd = 0xFE, paddq = 0xD4, paddsb = 0xEC, paddsw = 0xED, packssdw = 0x6B, packsswb = 0x63, packuswb = 0x67, paddusb = 0xDC, paddusw = 0xDD, pand = 0xDB, pandn = 0xDF, pavgb = 0xE0, pavgw = 0xE3, pcmpeqb = 0x74, pcmpeqd = 0x76, pcmpeqw = 0x75, pcmpgtb = 0x64, pcmpgtd = 0x66, pcmpgtw = 0x65, pmaddwd = 0xF5, pmaxsw = 0xEE, pmaxub = 0xDE, pminsw = 0xEA, pminub = 0xDA, pmulhuw = 0xE4, pmulhw = 0xE5, pmullw = 0xD5, pmuludq = 0xF4, por = 0xEB, psadbw = 0xF6, psubb = 0xF8, psubw = 0xF9, psubd = 0xFA, psubq = 0xFB, psubsb = 0xE8, psubsw = 0xE9, psubusb = 0xD8, psubusw = 0xD9, punpckhbw = 0x68, punpckhwd = 0x69, punpckhdq = 0x6A, punpckhqdq = 0x6D, punpcklbw = 0x60, punpcklwd = 0x61, punpckldq = 0x62, punpcklqdq = 0x6C, pxor = 0xEF } do map_op[name.."_2"] = format("rmo:660F%02XrM", n) map_op["v"..name.."_3"] = format("rrmoy:660FV%02XrM", n) end ------------------------------------------------------------------------------ local map_vexarg = { u = false, v = 1, V = 2 } -- Process pattern string. local function dopattern(pat, args, sz, op, needrex) local digit, addin, vex local opcode = 0 local szov = sz local narg = 1 local rex = 0 -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 6 positions. if secpos+6 > maxsecpos then wflush() end -- Process each character. for c in gmatch(pat.."|", ".") do if match(c, "%x") then -- Hex digit. digit = byte(c) - 48 if digit > 48 then digit = digit - 39 elseif digit > 16 then digit = digit - 7 end opcode = opcode*16 + digit addin = nil elseif c == "n" then -- Disable operand size mods for opcode. szov = nil elseif c == "X" then -- Force REX.W. rex = 8 elseif c == "L" then -- Force VEX.L. vex.l = true elseif c == "r" then -- Merge 1st operand regno. into opcode. addin = args[1]; opcode = opcode + (addin.reg % 8) if narg < 2 then narg = 2 end elseif c == "R" then -- Merge 2nd operand regno. into opcode. addin = args[2]; opcode = opcode + (addin.reg % 8) narg = 3 elseif c == "m" or c == "M" then -- Encode ModRM/SIB. local s if addin then s = addin.reg opcode = opcode - band(s, 7) -- Undo regno opcode merge. else s = band(opcode, 15) -- Undo last digit. opcode = shr(opcode, 4) end local nn = c == "m" and 1 or 2 local t = args[nn] if narg <= nn then narg = nn + 1 end if szov == "q" and rex == 0 then rex = rex + 8 end if t.reg and t.reg > 7 then rex = rex + 1 end if t.xreg and t.xreg > 7 then rex = rex + 2 end if s > 7 then rex = rex + 4 end if needrex then rex = rex + 16 end local psz, sk = wputop(szov, opcode, rex, vex, s < 0, t.vreg or t.vxreg) opcode = nil local imark = sub(pat, -1) -- Force a mark (ugly). -- Put ModRM/SIB with regno/last digit as spare. wputmrmsib(t, imark, s, addin and addin.vreg, psz, sk) addin = nil elseif map_vexarg[c] ~= nil then -- Encode using VEX prefix local b = band(opcode, 255); opcode = shr(opcode, 8) local m = 1 if b == 0x38 then m = 2 elseif b == 0x3a then m = 3 end if m ~= 1 then b = band(opcode, 255); opcode = shr(opcode, 8) end if b ~= 0x0f then werror("expected `0F', `0F38', or `0F3A' to precede `"..c.. "' in pattern `"..pat.."' for `"..op.."'") end local v = map_vexarg[c] if v then v = remove(args, v) end b = band(opcode, 255) local p = 0 if b == 0x66 then p = 1 elseif b == 0xf3 then p = 2 elseif b == 0xf2 then p = 3 end if p ~= 0 then opcode = shr(opcode, 8) end if opcode ~= 0 then wputop(nil, opcode, 0); opcode = 0 end vex = { m = m, p = p, v = v } else if opcode then -- Flush opcode. if szov == "q" and rex == 0 then rex = rex + 8 end if needrex then rex = rex + 16 end if addin and addin.reg == -1 then local psz, sk = wputop(szov, opcode - 7, rex, vex, true) wvreg("opcode", addin.vreg, psz, sk) else if addin and addin.reg > 7 then rex = rex + 1 end wputop(szov, opcode, rex, vex) end opcode = nil end if c == "|" then break end if c == "o" then -- Offset (pure 32 bit displacement). wputdarg(args[1].disp); if narg < 2 then narg = 2 end elseif c == "O" then wputdarg(args[2].disp); narg = 3 else -- Anything else is an immediate operand. local a = args[narg] narg = narg + 1 local mode, imm = a.mode, a.imm if mode == "iJ" and not match("iIJ", c) then werror("bad operand size for label") end if c == "S" then wputsbarg(imm) elseif c == "U" then wputbarg(imm) elseif c == "W" then wputwarg(imm) elseif c == "i" or c == "I" then if mode == "iJ" then wputlabel("IMM_", imm, 1) elseif mode == "iI" and c == "I" then waction(sz == "w" and "IMM_WB" or "IMM_DB", imm) else wputszarg(sz, imm) end elseif c == "J" then if mode == "iPJ" then waction("REL_A", imm) -- !x64 (secpos) else wputlabel("REL_", imm, 2) end elseif c == "s" then local reg = a.reg if reg < 0 then wputb(0) wvreg("imm.hi", a.vreg) else wputb(shl(reg, 4)) end else werror("bad char `"..c.."' in pattern `"..pat.."' for `"..op.."'") end end end end end ------------------------------------------------------------------------------ -- Mapping of operand modes to short names. Suppress output with '#'. local map_modename = { r = "reg", R = "eax", C = "cl", x = "mem", m = "mrm", i = "imm", f = "stx", F = "st0", J = "lbl", ["1"] = "1", I = "#", S = "#", O = "#", } -- Return a table/string showing all possible operand modes. local function templatehelp(template, nparams) if nparams == 0 then return "" end local t = {} for tm in gmatch(template, "[^%|]+") do local s = map_modename[sub(tm, 1, 1)] s = s..gsub(sub(tm, 2, nparams), ".", function(c) return ", "..map_modename[c] end) if not match(s, "#") then t[#t+1] = s end end return t end -- Match operand modes against mode match part of template. local function matchtm(tm, args) for i=1,#args do if not match(args[i].mode, sub(tm, i, i)) then return end end return true end -- Handle opcodes defined with template strings. map_op[".template__"] = function(params, template, nparams) if not params then return templatehelp(template, nparams) end local args = {} -- Zero-operand opcodes have no match part. if #params == 0 then dopattern(template, args, "d", params.op, nil) return end -- Determine common operand size (coerce undefined size) or flag as mixed. local sz, szmix, needrex for i,p in ipairs(params) do args[i] = parseoperand(p) local nsz = args[i].opsize if nsz then if sz and sz ~= nsz then szmix = true else sz = nsz end end local nrex = args[i].needrex if nrex ~= nil then if needrex == nil then needrex = nrex elseif needrex ~= nrex then werror("bad mix of byte-addressable registers") end end end -- Try all match:pattern pairs (separated by '|'). local gotmatch, lastpat for tm in gmatch(template, "[^%|]+") do -- Split off size match (starts after mode match) and pattern string. local szm, pat = match(tm, "^(.-):(.*)$", #args+1) if pat == "" then pat = lastpat else lastpat = pat end if matchtm(tm, args) then local prefix = sub(szm, 1, 1) if prefix == "/" then -- Exactly match leading operand sizes. for i = #szm,1,-1 do if i == 1 then dopattern(pat, args, sz, params.op, needrex) -- Process pattern. return elseif args[i-1].opsize ~= sub(szm, i, i) then break end end else -- Match common operand size. local szp = sz if szm == "" then szm = x64 and "qdwb" or "dwb" end -- Default sizes. if prefix == "1" then szp = args[1].opsize; szmix = nil elseif prefix == "2" then szp = args[2].opsize; szmix = nil end if not szmix and (prefix == "." or match(szm, szp or "#")) then dopattern(pat, args, szp, params.op, needrex) -- Process pattern. return end end gotmatch = true end end local msg = "bad operand mode" if gotmatch then if szmix then msg = "mixed operand size" else msg = sz and "bad operand size" or "missing operand size" end end werror(msg.." in `"..opmodestr(params.op, args).."'") end ------------------------------------------------------------------------------ -- x64-specific opcode for 64 bit immediates and displacements. if x64 then function map_op.mov64_2(params) if not params then return { "reg, imm", "reg, [disp]", "[disp], reg" } end if secpos+2 > maxsecpos then wflush() end local opcode, op64, sz, rex, vreg local op64 = match(params[1], "^%[%s*(.-)%s*%]$") if op64 then local a = parseoperand(params[2]) if a.mode ~= "rmR" then werror("bad operand mode") end sz = a.opsize rex = sz == "q" and 8 or 0 opcode = 0xa3 else op64 = match(params[2], "^%[%s*(.-)%s*%]$") local a = parseoperand(params[1]) if op64 then if a.mode ~= "rmR" then werror("bad operand mode") end sz = a.opsize rex = sz == "q" and 8 or 0 opcode = 0xa1 else if sub(a.mode, 1, 1) ~= "r" or a.opsize ~= "q" then werror("bad operand mode") end op64 = params[2] if a.reg == -1 then vreg = a.vreg opcode = 0xb8 else opcode = 0xb8 + band(a.reg, 7) end rex = a.reg > 7 and 9 or 8 end end local psz, sk = wputop(sz, opcode, rex, nil, vreg) wvreg("opcode", vreg, psz, sk) waction("IMM_D", format("(unsigned int)(%s)", op64)) waction("IMM_D", format("(unsigned int)((%s)>>32)", op64)) end end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. local function op_data(params) if not params then return "imm..." end local sz = sub(params.op, 2, 2) if sz == "a" then sz = addrsize end for _,p in ipairs(params) do local a = parseoperand(p) if sub(a.mode, 1, 1) ~= "i" or (a.opsize and a.opsize ~= sz) then werror("bad mode or size in `"..p.."'") end if a.mode == "iJ" then wputlabel("IMM_", a.imm, 1) else wputszarg(sz, a.imm) end if secpos+2 > maxsecpos then wflush() end end end map_op[".byte_*"] = op_data map_op[".sbyte_*"] = op_data map_op[".word_*"] = op_data map_op[".dword_*"] = op_data map_op[".aword_*"] = op_data ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_2"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr [, addr]" end if secpos+2 > maxsecpos then wflush() end local a = parseoperand(params[1]) local mode, imm = a.mode, a.imm if type(imm) == "number" and (mode == "iJ" or (imm >= 1 and imm <= 9)) then -- Local label (1: ... 9:) or global label (->global:). waction("LABEL_LG", nil, 1) wputxb(imm) elseif mode == "iJ" then -- PC label (=>pcexpr:). waction("LABEL_PC", imm) else werror("bad label definition") end -- SETLABEL must immediately follow LABEL_LG/LABEL_PC. local addr = params[2] if addr then local a = parseoperand(addr) if a.mode == "iPJ" then waction("SETLABEL", a.imm) else werror("bad label assignment") end end end map_op[".label_1"] = map_op[".label_2"] ------------------------------------------------------------------------------ -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) or map_opsizenum[map_opsize[params[1]]] if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", nil, 1) wputxb(align-1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end -- Spacing pseudo-opcode. map_op[".space_2"] = function(params) if not params then return "num [, filler]" end if secpos+1 > maxsecpos then wflush() end waction("SPACE", params[1]) local fill = params[2] if fill then fill = tonumber(fill) if not fill or fill < 0 or fill > 255 then werror("bad filler") end end wputxb(fill or 0) end map_op[".space_1"] = map_op[".space_2"] ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end if reg and not map_reg_valid_base[reg] then werror("bad base register `"..(map_reg_rev[reg] or reg).."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg and map_reg_rev[tp.reg] or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION") wputxb(num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpregs(out) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = map_coreop }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
xLua/build/luajit-2.1.0b2/dynasm/dasm_x86.lua/0
{ "file_path": "xLua/build/luajit-2.1.0b2/dynasm/dasm_x86.lua", "repo_id": "xLua", "token_count": 34748 }
2,100
/* This is a heavily customized and minimized copy of Lua 5.1.5. */ /* It's only used to build LuaJIT. It does NOT have all standard functions! */ /****************************************************************************** * Copyright (C) 1994-2012 Lua.org, PUC-Rio. All rights reserved. * * 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. ******************************************************************************/ #ifdef _MSC_VER typedef unsigned __int64 U64; #else typedef unsigned long long U64; #endif int _CRT_glob = 0; #include <stddef.h> #include <stdarg.h> #include <limits.h> #include <math.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <setjmp.h> #include <errno.h> #include <time.h> typedef enum{ TM_INDEX, TM_NEWINDEX, TM_GC, TM_MODE, TM_EQ, TM_ADD, TM_SUB, TM_MUL, TM_DIV, TM_MOD, TM_POW, TM_UNM, TM_LEN, TM_LT, TM_LE, TM_CONCAT, TM_CALL, TM_N }TMS; enum OpMode{iABC,iABx,iAsBx}; typedef enum{ OP_MOVE, OP_LOADK, OP_LOADBOOL, OP_LOADNIL, OP_GETUPVAL, OP_GETGLOBAL, OP_GETTABLE, OP_SETGLOBAL, OP_SETUPVAL, OP_SETTABLE, OP_NEWTABLE, OP_SELF, OP_ADD, OP_SUB, OP_MUL, OP_DIV, OP_MOD, OP_POW, OP_UNM, OP_NOT, OP_LEN, OP_CONCAT, OP_JMP, OP_EQ, OP_LT, OP_LE, OP_TEST, OP_TESTSET, OP_CALL, OP_TAILCALL, OP_RETURN, OP_FORLOOP, OP_FORPREP, OP_TFORLOOP, OP_SETLIST, OP_CLOSE, OP_CLOSURE, OP_VARARG }OpCode; enum OpArgMask{ OpArgN, OpArgU, OpArgR, OpArgK }; typedef enum{ VVOID, VNIL, VTRUE, VFALSE, VK, VKNUM, VLOCAL, VUPVAL, VGLOBAL, VINDEXED, VJMP, VRELOCABLE, VNONRELOC, VCALL, VVARARG }expkind; enum RESERVED{ TK_AND=257,TK_BREAK, TK_DO,TK_ELSE,TK_ELSEIF,TK_END,TK_FALSE,TK_FOR,TK_FUNCTION, TK_IF,TK_IN,TK_LOCAL,TK_NIL,TK_NOT,TK_OR,TK_REPEAT, TK_RETURN,TK_THEN,TK_TRUE,TK_UNTIL,TK_WHILE, TK_CONCAT,TK_DOTS,TK_EQ,TK_GE,TK_LE,TK_NE,TK_NUMBER, TK_NAME,TK_STRING,TK_EOS }; typedef enum BinOpr{ OPR_ADD,OPR_SUB,OPR_MUL,OPR_DIV,OPR_MOD,OPR_POW, OPR_CONCAT, OPR_NE,OPR_EQ, OPR_LT,OPR_LE,OPR_GT,OPR_GE, OPR_AND,OPR_OR, OPR_NOBINOPR }BinOpr; typedef enum UnOpr{OPR_MINUS,OPR_NOT,OPR_LEN,OPR_NOUNOPR}UnOpr; #define LUA_QL(x)"'"x"'" #define luai_apicheck(L,o){(void)L;} #define lua_number2str(s,n)sprintf((s),"%.14g",(n)) #define lua_str2number(s,p)strtod((s),(p)) #define luai_numadd(a,b)((a)+(b)) #define luai_numsub(a,b)((a)-(b)) #define luai_nummul(a,b)((a)*(b)) #define luai_numdiv(a,b)((a)/(b)) #define luai_nummod(a,b)((a)-floor((a)/(b))*(b)) #define luai_numpow(a,b)(pow(a,b)) #define luai_numunm(a)(-(a)) #define luai_numeq(a,b)((a)==(b)) #define luai_numlt(a,b)((a)<(b)) #define luai_numle(a,b)((a)<=(b)) #define luai_numisnan(a)(!luai_numeq((a),(a))) #define lua_number2int(i,d)((i)=(int)(d)) #define lua_number2integer(i,d)((i)=(lua_Integer)(d)) #define LUAI_THROW(L,c)longjmp((c)->b,1) #define LUAI_TRY(L,c,a)if(setjmp((c)->b)==0){a} #define lua_pclose(L,file)((void)((void)L,file),0) #define lua_upvalueindex(i)((-10002)-(i)) typedef struct lua_State lua_State; typedef int(*lua_CFunction)(lua_State*L); typedef const char*(*lua_Reader)(lua_State*L,void*ud,size_t*sz); typedef void*(*lua_Alloc)(void*ud,void*ptr,size_t osize,size_t nsize); typedef double lua_Number; typedef ptrdiff_t lua_Integer; static void lua_settop(lua_State*L,int idx); static int lua_type(lua_State*L,int idx); static const char* lua_tolstring(lua_State*L,int idx,size_t*len); static size_t lua_objlen(lua_State*L,int idx); static void lua_pushlstring(lua_State*L,const char*s,size_t l); static void lua_pushcclosure(lua_State*L,lua_CFunction fn,int n); static void lua_createtable(lua_State*L,int narr,int nrec); static void lua_setfield(lua_State*L,int idx,const char*k); #define lua_pop(L,n)lua_settop(L,-(n)-1) #define lua_newtable(L)lua_createtable(L,0,0) #define lua_pushcfunction(L,f)lua_pushcclosure(L,(f),0) #define lua_strlen(L,i)lua_objlen(L,(i)) #define lua_isfunction(L,n)(lua_type(L,(n))==6) #define lua_istable(L,n)(lua_type(L,(n))==5) #define lua_isnil(L,n)(lua_type(L,(n))==0) #define lua_isboolean(L,n)(lua_type(L,(n))==1) #define lua_isnone(L,n)(lua_type(L,(n))==(-1)) #define lua_isnoneornil(L,n)(lua_type(L,(n))<=0) #define lua_pushliteral(L,s)lua_pushlstring(L,""s,(sizeof(s)/sizeof(char))-1) #define lua_setglobal(L,s)lua_setfield(L,(-10002),(s)) #define lua_tostring(L,i)lua_tolstring(L,(i),NULL) typedef struct lua_Debug lua_Debug; typedef void(*lua_Hook)(lua_State*L,lua_Debug*ar); struct lua_Debug{ int event; const char*name; const char*namewhat; const char*what; const char*source; int currentline; int nups; int linedefined; int lastlinedefined; char short_src[60]; int i_ci; }; typedef unsigned int lu_int32; typedef size_t lu_mem; typedef ptrdiff_t l_mem; typedef unsigned char lu_byte; #define IntPoint(p)((unsigned int)(lu_mem)(p)) typedef union{double u;void*s;long l;}L_Umaxalign; typedef double l_uacNumber; #define check_exp(c,e)(e) #define UNUSED(x)((void)(x)) #define cast(t,exp)((t)(exp)) #define cast_byte(i)cast(lu_byte,(i)) #define cast_num(i)cast(lua_Number,(i)) #define cast_int(i)cast(int,(i)) typedef lu_int32 Instruction; #define condhardstacktests(x)((void)0) typedef union GCObject GCObject; typedef struct GCheader{ GCObject*next;lu_byte tt;lu_byte marked; }GCheader; typedef union{ GCObject*gc; void*p; lua_Number n; int b; }Value; typedef struct lua_TValue{ Value value;int tt; }TValue; #define ttisnil(o)(ttype(o)==0) #define ttisnumber(o)(ttype(o)==3) #define ttisstring(o)(ttype(o)==4) #define ttistable(o)(ttype(o)==5) #define ttisfunction(o)(ttype(o)==6) #define ttisboolean(o)(ttype(o)==1) #define ttisuserdata(o)(ttype(o)==7) #define ttisthread(o)(ttype(o)==8) #define ttislightuserdata(o)(ttype(o)==2) #define ttype(o)((o)->tt) #define gcvalue(o)check_exp(iscollectable(o),(o)->value.gc) #define pvalue(o)check_exp(ttislightuserdata(o),(o)->value.p) #define nvalue(o)check_exp(ttisnumber(o),(o)->value.n) #define rawtsvalue(o)check_exp(ttisstring(o),&(o)->value.gc->ts) #define tsvalue(o)(&rawtsvalue(o)->tsv) #define rawuvalue(o)check_exp(ttisuserdata(o),&(o)->value.gc->u) #define uvalue(o)(&rawuvalue(o)->uv) #define clvalue(o)check_exp(ttisfunction(o),&(o)->value.gc->cl) #define hvalue(o)check_exp(ttistable(o),&(o)->value.gc->h) #define bvalue(o)check_exp(ttisboolean(o),(o)->value.b) #define thvalue(o)check_exp(ttisthread(o),&(o)->value.gc->th) #define l_isfalse(o)(ttisnil(o)||(ttisboolean(o)&&bvalue(o)==0)) #define checkconsistency(obj) #define checkliveness(g,obj) #define setnilvalue(obj)((obj)->tt=0) #define setnvalue(obj,x){TValue*i_o=(obj);i_o->value.n=(x);i_o->tt=3;} #define setbvalue(obj,x){TValue*i_o=(obj);i_o->value.b=(x);i_o->tt=1;} #define setsvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=4;checkliveness(G(L),i_o);} #define setuvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=7;checkliveness(G(L),i_o);} #define setthvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=8;checkliveness(G(L),i_o);} #define setclvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=6;checkliveness(G(L),i_o);} #define sethvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=5;checkliveness(G(L),i_o);} #define setptvalue(L,obj,x){TValue*i_o=(obj);i_o->value.gc=cast(GCObject*,(x));i_o->tt=(8+1);checkliveness(G(L),i_o);} #define setobj(L,obj1,obj2){const TValue*o2=(obj2);TValue*o1=(obj1);o1->value=o2->value;o1->tt=o2->tt;checkliveness(G(L),o1);} #define setttype(obj,tt)(ttype(obj)=(tt)) #define iscollectable(o)(ttype(o)>=4) typedef TValue*StkId; typedef union TString{ L_Umaxalign dummy; struct{ GCObject*next;lu_byte tt;lu_byte marked; lu_byte reserved; unsigned int hash; size_t len; }tsv; }TString; #define getstr(ts)cast(const char*,(ts)+1) #define svalue(o)getstr(rawtsvalue(o)) typedef union Udata{ L_Umaxalign dummy; struct{ GCObject*next;lu_byte tt;lu_byte marked; struct Table*metatable; struct Table*env; size_t len; }uv; }Udata; typedef struct Proto{ GCObject*next;lu_byte tt;lu_byte marked; TValue*k; Instruction*code; struct Proto**p; int*lineinfo; struct LocVar*locvars; TString**upvalues; TString*source; int sizeupvalues; int sizek; int sizecode; int sizelineinfo; int sizep; int sizelocvars; int linedefined; int lastlinedefined; GCObject*gclist; lu_byte nups; lu_byte numparams; lu_byte is_vararg; lu_byte maxstacksize; }Proto; typedef struct LocVar{ TString*varname; int startpc; int endpc; }LocVar; typedef struct UpVal{ GCObject*next;lu_byte tt;lu_byte marked; TValue*v; union{ TValue value; struct{ struct UpVal*prev; struct UpVal*next; }l; }u; }UpVal; typedef struct CClosure{ GCObject*next;lu_byte tt;lu_byte marked;lu_byte isC;lu_byte nupvalues;GCObject*gclist;struct Table*env; lua_CFunction f; TValue upvalue[1]; }CClosure; typedef struct LClosure{ GCObject*next;lu_byte tt;lu_byte marked;lu_byte isC;lu_byte nupvalues;GCObject*gclist;struct Table*env; struct Proto*p; UpVal*upvals[1]; }LClosure; typedef union Closure{ CClosure c; LClosure l; }Closure; #define iscfunction(o)(ttype(o)==6&&clvalue(o)->c.isC) typedef union TKey{ struct{ Value value;int tt; struct Node*next; }nk; TValue tvk; }TKey; typedef struct Node{ TValue i_val; TKey i_key; }Node; typedef struct Table{ GCObject*next;lu_byte tt;lu_byte marked; lu_byte flags; lu_byte lsizenode; struct Table*metatable; TValue*array; Node*node; Node*lastfree; GCObject*gclist; int sizearray; }Table; #define lmod(s,size)(check_exp((size&(size-1))==0,(cast(int,(s)&((size)-1))))) #define twoto(x)((size_t)1<<(x)) #define sizenode(t)(twoto((t)->lsizenode)) static const TValue luaO_nilobject_; #define ceillog2(x)(luaO_log2((x)-1)+1) static int luaO_log2(unsigned int x); #define gfasttm(g,et,e)((et)==NULL?NULL:((et)->flags&(1u<<(e)))?NULL:luaT_gettm(et,e,(g)->tmname[e])) #define fasttm(l,et,e)gfasttm(G(l),et,e) static const TValue*luaT_gettm(Table*events,TMS event,TString*ename); #define luaM_reallocv(L,b,on,n,e)((cast(size_t,(n)+1)<=((size_t)(~(size_t)0)-2)/(e))?luaM_realloc_(L,(b),(on)*(e),(n)*(e)):luaM_toobig(L)) #define luaM_freemem(L,b,s)luaM_realloc_(L,(b),(s),0) #define luaM_free(L,b)luaM_realloc_(L,(b),sizeof(*(b)),0) #define luaM_freearray(L,b,n,t)luaM_reallocv(L,(b),n,0,sizeof(t)) #define luaM_malloc(L,t)luaM_realloc_(L,NULL,0,(t)) #define luaM_new(L,t)cast(t*,luaM_malloc(L,sizeof(t))) #define luaM_newvector(L,n,t)cast(t*,luaM_reallocv(L,NULL,0,n,sizeof(t))) #define luaM_growvector(L,v,nelems,size,t,limit,e)if((nelems)+1>(size))((v)=cast(t*,luaM_growaux_(L,v,&(size),sizeof(t),limit,e))) #define luaM_reallocvector(L,v,oldn,n,t)((v)=cast(t*,luaM_reallocv(L,v,oldn,n,sizeof(t)))) static void*luaM_realloc_(lua_State*L,void*block,size_t oldsize, size_t size); static void*luaM_toobig(lua_State*L); static void*luaM_growaux_(lua_State*L,void*block,int*size, size_t size_elem,int limit, const char*errormsg); typedef struct Zio ZIO; #define char2int(c)cast(int,cast(unsigned char,(c))) #define zgetc(z)(((z)->n--)>0?char2int(*(z)->p++):luaZ_fill(z)) typedef struct Mbuffer{ char*buffer; size_t n; size_t buffsize; }Mbuffer; #define luaZ_initbuffer(L,buff)((buff)->buffer=NULL,(buff)->buffsize=0) #define luaZ_buffer(buff)((buff)->buffer) #define luaZ_sizebuffer(buff)((buff)->buffsize) #define luaZ_bufflen(buff)((buff)->n) #define luaZ_resetbuffer(buff)((buff)->n=0) #define luaZ_resizebuffer(L,buff,size)(luaM_reallocvector(L,(buff)->buffer,(buff)->buffsize,size,char),(buff)->buffsize=size) #define luaZ_freebuffer(L,buff)luaZ_resizebuffer(L,buff,0) struct Zio{ size_t n; const char*p; lua_Reader reader; void*data; lua_State*L; }; static int luaZ_fill(ZIO*z); struct lua_longjmp; #define gt(L)(&L->l_gt) #define registry(L)(&G(L)->l_registry) typedef struct stringtable{ GCObject**hash; lu_int32 nuse; int size; }stringtable; typedef struct CallInfo{ StkId base; StkId func; StkId top; const Instruction*savedpc; int nresults; int tailcalls; }CallInfo; #define curr_func(L)(clvalue(L->ci->func)) #define ci_func(ci)(clvalue((ci)->func)) #define f_isLua(ci)(!ci_func(ci)->c.isC) #define isLua(ci)(ttisfunction((ci)->func)&&f_isLua(ci)) typedef struct global_State{ stringtable strt; lua_Alloc frealloc; void*ud; lu_byte currentwhite; lu_byte gcstate; int sweepstrgc; GCObject*rootgc; GCObject**sweepgc; GCObject*gray; GCObject*grayagain; GCObject*weak; GCObject*tmudata; Mbuffer buff; lu_mem GCthreshold; lu_mem totalbytes; lu_mem estimate; lu_mem gcdept; int gcpause; int gcstepmul; lua_CFunction panic; TValue l_registry; struct lua_State*mainthread; UpVal uvhead; struct Table*mt[(8+1)]; TString*tmname[TM_N]; }global_State; struct lua_State{ GCObject*next;lu_byte tt;lu_byte marked; lu_byte status; StkId top; StkId base; global_State*l_G; CallInfo*ci; const Instruction*savedpc; StkId stack_last; StkId stack; CallInfo*end_ci; CallInfo*base_ci; int stacksize; int size_ci; unsigned short nCcalls; unsigned short baseCcalls; lu_byte hookmask; lu_byte allowhook; int basehookcount; int hookcount; lua_Hook hook; TValue l_gt; TValue env; GCObject*openupval; GCObject*gclist; struct lua_longjmp*errorJmp; ptrdiff_t errfunc; }; #define G(L)(L->l_G) union GCObject{ GCheader gch; union TString ts; union Udata u; union Closure cl; struct Table h; struct Proto p; struct UpVal uv; struct lua_State th; }; #define rawgco2ts(o)check_exp((o)->gch.tt==4,&((o)->ts)) #define gco2ts(o)(&rawgco2ts(o)->tsv) #define rawgco2u(o)check_exp((o)->gch.tt==7,&((o)->u)) #define gco2u(o)(&rawgco2u(o)->uv) #define gco2cl(o)check_exp((o)->gch.tt==6,&((o)->cl)) #define gco2h(o)check_exp((o)->gch.tt==5,&((o)->h)) #define gco2p(o)check_exp((o)->gch.tt==(8+1),&((o)->p)) #define gco2uv(o)check_exp((o)->gch.tt==(8+2),&((o)->uv)) #define ngcotouv(o)check_exp((o)==NULL||(o)->gch.tt==(8+2),&((o)->uv)) #define gco2th(o)check_exp((o)->gch.tt==8,&((o)->th)) #define obj2gco(v)(cast(GCObject*,(v))) static void luaE_freethread(lua_State*L,lua_State*L1); #define pcRel(pc,p)(cast(int,(pc)-(p)->code)-1) #define getline_(f,pc)(((f)->lineinfo)?(f)->lineinfo[pc]:0) #define resethookcount(L)(L->hookcount=L->basehookcount) static void luaG_typeerror(lua_State*L,const TValue*o, const char*opname); static void luaG_runerror(lua_State*L,const char*fmt,...); #define luaD_checkstack(L,n)if((char*)L->stack_last-(char*)L->top<=(n)*(int)sizeof(TValue))luaD_growstack(L,n);else condhardstacktests(luaD_reallocstack(L,L->stacksize-5-1)); #define incr_top(L){luaD_checkstack(L,1);L->top++;} #define savestack(L,p)((char*)(p)-(char*)L->stack) #define restorestack(L,n)((TValue*)((char*)L->stack+(n))) #define saveci(L,p)((char*)(p)-(char*)L->base_ci) #define restoreci(L,n)((CallInfo*)((char*)L->base_ci+(n))) typedef void(*Pfunc)(lua_State*L,void*ud); static int luaD_poscall(lua_State*L,StkId firstResult); static void luaD_reallocCI(lua_State*L,int newsize); static void luaD_reallocstack(lua_State*L,int newsize); static void luaD_growstack(lua_State*L,int n); static void luaD_throw(lua_State*L,int errcode); static void*luaM_growaux_(lua_State*L,void*block,int*size,size_t size_elems, int limit,const char*errormsg){ void*newblock; int newsize; if(*size>=limit/2){ if(*size>=limit) luaG_runerror(L,errormsg); newsize=limit; } else{ newsize=(*size)*2; if(newsize<4) newsize=4; } newblock=luaM_reallocv(L,block,*size,newsize,size_elems); *size=newsize; return newblock; } static void*luaM_toobig(lua_State*L){ luaG_runerror(L,"memory allocation error: block too big"); return NULL; } static void*luaM_realloc_(lua_State*L,void*block,size_t osize,size_t nsize){ global_State*g=G(L); block=(*g->frealloc)(g->ud,block,osize,nsize); if(block==NULL&&nsize>0) luaD_throw(L,4); g->totalbytes=(g->totalbytes-osize)+nsize; return block; } #define resetbits(x,m)((x)&=cast(lu_byte,~(m))) #define setbits(x,m)((x)|=(m)) #define testbits(x,m)((x)&(m)) #define bitmask(b)(1<<(b)) #define bit2mask(b1,b2)(bitmask(b1)|bitmask(b2)) #define l_setbit(x,b)setbits(x,bitmask(b)) #define resetbit(x,b)resetbits(x,bitmask(b)) #define testbit(x,b)testbits(x,bitmask(b)) #define set2bits(x,b1,b2)setbits(x,(bit2mask(b1,b2))) #define reset2bits(x,b1,b2)resetbits(x,(bit2mask(b1,b2))) #define test2bits(x,b1,b2)testbits(x,(bit2mask(b1,b2))) #define iswhite(x)test2bits((x)->gch.marked,0,1) #define isblack(x)testbit((x)->gch.marked,2) #define isgray(x)(!isblack(x)&&!iswhite(x)) #define otherwhite(g)(g->currentwhite^bit2mask(0,1)) #define isdead(g,v)((v)->gch.marked&otherwhite(g)&bit2mask(0,1)) #define changewhite(x)((x)->gch.marked^=bit2mask(0,1)) #define gray2black(x)l_setbit((x)->gch.marked,2) #define valiswhite(x)(iscollectable(x)&&iswhite(gcvalue(x))) #define luaC_white(g)cast(lu_byte,(g)->currentwhite&bit2mask(0,1)) #define luaC_checkGC(L){condhardstacktests(luaD_reallocstack(L,L->stacksize-5-1));if(G(L)->totalbytes>=G(L)->GCthreshold)luaC_step(L);} #define luaC_barrier(L,p,v){if(valiswhite(v)&&isblack(obj2gco(p)))luaC_barrierf(L,obj2gco(p),gcvalue(v));} #define luaC_barriert(L,t,v){if(valiswhite(v)&&isblack(obj2gco(t)))luaC_barrierback(L,t);} #define luaC_objbarrier(L,p,o){if(iswhite(obj2gco(o))&&isblack(obj2gco(p)))luaC_barrierf(L,obj2gco(p),obj2gco(o));} #define luaC_objbarriert(L,t,o){if(iswhite(obj2gco(o))&&isblack(obj2gco(t)))luaC_barrierback(L,t);} static void luaC_step(lua_State*L); static void luaC_link(lua_State*L,GCObject*o,lu_byte tt); static void luaC_linkupval(lua_State*L,UpVal*uv); static void luaC_barrierf(lua_State*L,GCObject*o,GCObject*v); static void luaC_barrierback(lua_State*L,Table*t); #define sizestring(s)(sizeof(union TString)+((s)->len+1)*sizeof(char)) #define sizeudata(u)(sizeof(union Udata)+(u)->len) #define luaS_new(L,s)(luaS_newlstr(L,s,strlen(s))) #define luaS_newliteral(L,s)(luaS_newlstr(L,""s,(sizeof(s)/sizeof(char))-1)) #define luaS_fix(s)l_setbit((s)->tsv.marked,5) static TString*luaS_newlstr(lua_State*L,const char*str,size_t l); #define tostring(L,o)((ttype(o)==4)||(luaV_tostring(L,o))) #define tonumber(o,n)(ttype(o)==3||(((o)=luaV_tonumber(o,n))!=NULL)) #define equalobj(L,o1,o2)(ttype(o1)==ttype(o2)&&luaV_equalval(L,o1,o2)) static int luaV_equalval(lua_State*L,const TValue*t1,const TValue*t2); static const TValue*luaV_tonumber(const TValue*obj,TValue*n); static int luaV_tostring(lua_State*L,StkId obj); static void luaV_execute(lua_State*L,int nexeccalls); static void luaV_concat(lua_State*L,int total,int last); static const TValue luaO_nilobject_={{NULL},0}; static int luaO_int2fb(unsigned int x){ int e=0; while(x>=16){ x=(x+1)>>1; e++; } if(x<8)return x; else return((e+1)<<3)|(cast_int(x)-8); } static int luaO_fb2int(int x){ int e=(x>>3)&31; if(e==0)return x; else return((x&7)+8)<<(e-1); } static int luaO_log2(unsigned int x){ static const lu_byte log_2[256]={ 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8 }; int l=-1; while(x>=256){l+=8;x>>=8;} return l+log_2[x]; } static int luaO_rawequalObj(const TValue*t1,const TValue*t2){ if(ttype(t1)!=ttype(t2))return 0; else switch(ttype(t1)){ case 0: return 1; case 3: return luai_numeq(nvalue(t1),nvalue(t2)); case 1: return bvalue(t1)==bvalue(t2); case 2: return pvalue(t1)==pvalue(t2); default: return gcvalue(t1)==gcvalue(t2); } } static int luaO_str2d(const char*s,lua_Number*result){ char*endptr; *result=lua_str2number(s,&endptr); if(endptr==s)return 0; if(*endptr=='x'||*endptr=='X') *result=cast_num(strtoul(s,&endptr,16)); if(*endptr=='\0')return 1; while(isspace(cast(unsigned char,*endptr)))endptr++; if(*endptr!='\0')return 0; return 1; } static void pushstr(lua_State*L,const char*str){ setsvalue(L,L->top,luaS_new(L,str)); incr_top(L); } static const char*luaO_pushvfstring(lua_State*L,const char*fmt,va_list argp){ int n=1; pushstr(L,""); for(;;){ const char*e=strchr(fmt,'%'); if(e==NULL)break; setsvalue(L,L->top,luaS_newlstr(L,fmt,e-fmt)); incr_top(L); switch(*(e+1)){ case's':{ const char*s=va_arg(argp,char*); if(s==NULL)s="(null)"; pushstr(L,s); break; } case'c':{ char buff[2]; buff[0]=cast(char,va_arg(argp,int)); buff[1]='\0'; pushstr(L,buff); break; } case'd':{ setnvalue(L->top,cast_num(va_arg(argp,int))); incr_top(L); break; } case'f':{ setnvalue(L->top,cast_num(va_arg(argp,l_uacNumber))); incr_top(L); break; } case'p':{ char buff[4*sizeof(void*)+8]; sprintf(buff,"%p",va_arg(argp,void*)); pushstr(L,buff); break; } case'%':{ pushstr(L,"%"); break; } default:{ char buff[3]; buff[0]='%'; buff[1]=*(e+1); buff[2]='\0'; pushstr(L,buff); break; } } n+=2; fmt=e+2; } pushstr(L,fmt); luaV_concat(L,n+1,cast_int(L->top-L->base)-1); L->top-=n; return svalue(L->top-1); } static const char*luaO_pushfstring(lua_State*L,const char*fmt,...){ const char*msg; va_list argp; va_start(argp,fmt); msg=luaO_pushvfstring(L,fmt,argp); va_end(argp); return msg; } static void luaO_chunkid(char*out,const char*source,size_t bufflen){ if(*source=='='){ strncpy(out,source+1,bufflen); out[bufflen-1]='\0'; } else{ if(*source=='@'){ size_t l; source++; bufflen-=sizeof(" '...' "); l=strlen(source); strcpy(out,""); if(l>bufflen){ source+=(l-bufflen); strcat(out,"..."); } strcat(out,source); } else{ size_t len=strcspn(source,"\n\r"); bufflen-=sizeof(" [string \"...\"] "); if(len>bufflen)len=bufflen; strcpy(out,"[string \""); if(source[len]!='\0'){ strncat(out,source,len); strcat(out,"..."); } else strcat(out,source); strcat(out,"\"]"); } } } #define gnode(t,i)(&(t)->node[i]) #define gkey(n)(&(n)->i_key.nk) #define gval(n)(&(n)->i_val) #define gnext(n)((n)->i_key.nk.next) #define key2tval(n)(&(n)->i_key.tvk) static TValue*luaH_setnum(lua_State*L,Table*t,int key); static const TValue*luaH_getstr(Table*t,TString*key); static TValue*luaH_set(lua_State*L,Table*t,const TValue*key); static const char*const luaT_typenames[]={ "nil","boolean","userdata","number", "string","table","function","userdata","thread", "proto","upval" }; static void luaT_init(lua_State*L){ static const char*const luaT_eventname[]={ "__index","__newindex", "__gc","__mode","__eq", "__add","__sub","__mul","__div","__mod", "__pow","__unm","__len","__lt","__le", "__concat","__call" }; int i; for(i=0;i<TM_N;i++){ G(L)->tmname[i]=luaS_new(L,luaT_eventname[i]); luaS_fix(G(L)->tmname[i]); } } static const TValue*luaT_gettm(Table*events,TMS event,TString*ename){ const TValue*tm=luaH_getstr(events,ename); if(ttisnil(tm)){ events->flags|=cast_byte(1u<<event); return NULL; } else return tm; } static const TValue*luaT_gettmbyobj(lua_State*L,const TValue*o,TMS event){ Table*mt; switch(ttype(o)){ case 5: mt=hvalue(o)->metatable; break; case 7: mt=uvalue(o)->metatable; break; default: mt=G(L)->mt[ttype(o)]; } return(mt?luaH_getstr(mt,G(L)->tmname[event]):(&luaO_nilobject_)); } #define sizeCclosure(n)(cast(int,sizeof(CClosure))+cast(int,sizeof(TValue)*((n)-1))) #define sizeLclosure(n)(cast(int,sizeof(LClosure))+cast(int,sizeof(TValue*)*((n)-1))) static Closure*luaF_newCclosure(lua_State*L,int nelems,Table*e){ Closure*c=cast(Closure*,luaM_malloc(L,sizeCclosure(nelems))); luaC_link(L,obj2gco(c),6); c->c.isC=1; c->c.env=e; c->c.nupvalues=cast_byte(nelems); return c; } static Closure*luaF_newLclosure(lua_State*L,int nelems,Table*e){ Closure*c=cast(Closure*,luaM_malloc(L,sizeLclosure(nelems))); luaC_link(L,obj2gco(c),6); c->l.isC=0; c->l.env=e; c->l.nupvalues=cast_byte(nelems); while(nelems--)c->l.upvals[nelems]=NULL; return c; } static UpVal*luaF_newupval(lua_State*L){ UpVal*uv=luaM_new(L,UpVal); luaC_link(L,obj2gco(uv),(8+2)); uv->v=&uv->u.value; setnilvalue(uv->v); return uv; } static UpVal*luaF_findupval(lua_State*L,StkId level){ global_State*g=G(L); GCObject**pp=&L->openupval; UpVal*p; UpVal*uv; while(*pp!=NULL&&(p=ngcotouv(*pp))->v>=level){ if(p->v==level){ if(isdead(g,obj2gco(p))) changewhite(obj2gco(p)); return p; } pp=&p->next; } uv=luaM_new(L,UpVal); uv->tt=(8+2); uv->marked=luaC_white(g); uv->v=level; uv->next=*pp; *pp=obj2gco(uv); uv->u.l.prev=&g->uvhead; uv->u.l.next=g->uvhead.u.l.next; uv->u.l.next->u.l.prev=uv; g->uvhead.u.l.next=uv; return uv; } static void unlinkupval(UpVal*uv){ uv->u.l.next->u.l.prev=uv->u.l.prev; uv->u.l.prev->u.l.next=uv->u.l.next; } static void luaF_freeupval(lua_State*L,UpVal*uv){ if(uv->v!=&uv->u.value) unlinkupval(uv); luaM_free(L,uv); } static void luaF_close(lua_State*L,StkId level){ UpVal*uv; global_State*g=G(L); while(L->openupval!=NULL&&(uv=ngcotouv(L->openupval))->v>=level){ GCObject*o=obj2gco(uv); L->openupval=uv->next; if(isdead(g,o)) luaF_freeupval(L,uv); else{ unlinkupval(uv); setobj(L,&uv->u.value,uv->v); uv->v=&uv->u.value; luaC_linkupval(L,uv); } } } static Proto*luaF_newproto(lua_State*L){ Proto*f=luaM_new(L,Proto); luaC_link(L,obj2gco(f),(8+1)); f->k=NULL; f->sizek=0; f->p=NULL; f->sizep=0; f->code=NULL; f->sizecode=0; f->sizelineinfo=0; f->sizeupvalues=0; f->nups=0; f->upvalues=NULL; f->numparams=0; f->is_vararg=0; f->maxstacksize=0; f->lineinfo=NULL; f->sizelocvars=0; f->locvars=NULL; f->linedefined=0; f->lastlinedefined=0; f->source=NULL; return f; } static void luaF_freeproto(lua_State*L,Proto*f){ luaM_freearray(L,f->code,f->sizecode,Instruction); luaM_freearray(L,f->p,f->sizep,Proto*); luaM_freearray(L,f->k,f->sizek,TValue); luaM_freearray(L,f->lineinfo,f->sizelineinfo,int); luaM_freearray(L,f->locvars,f->sizelocvars,struct LocVar); luaM_freearray(L,f->upvalues,f->sizeupvalues,TString*); luaM_free(L,f); } static void luaF_freeclosure(lua_State*L,Closure*c){ int size=(c->c.isC)?sizeCclosure(c->c.nupvalues): sizeLclosure(c->l.nupvalues); luaM_freemem(L,c,size); } #define MASK1(n,p)((~((~(Instruction)0)<<n))<<p) #define MASK0(n,p)(~MASK1(n,p)) #define GET_OPCODE(i)(cast(OpCode,((i)>>0)&MASK1(6,0))) #define SET_OPCODE(i,o)((i)=(((i)&MASK0(6,0))|((cast(Instruction,o)<<0)&MASK1(6,0)))) #define GETARG_A(i)(cast(int,((i)>>(0+6))&MASK1(8,0))) #define SETARG_A(i,u)((i)=(((i)&MASK0(8,(0+6)))|((cast(Instruction,u)<<(0+6))&MASK1(8,(0+6))))) #define GETARG_B(i)(cast(int,((i)>>(((0+6)+8)+9))&MASK1(9,0))) #define SETARG_B(i,b)((i)=(((i)&MASK0(9,(((0+6)+8)+9)))|((cast(Instruction,b)<<(((0+6)+8)+9))&MASK1(9,(((0+6)+8)+9))))) #define GETARG_C(i)(cast(int,((i)>>((0+6)+8))&MASK1(9,0))) #define SETARG_C(i,b)((i)=(((i)&MASK0(9,((0+6)+8)))|((cast(Instruction,b)<<((0+6)+8))&MASK1(9,((0+6)+8))))) #define GETARG_Bx(i)(cast(int,((i)>>((0+6)+8))&MASK1((9+9),0))) #define SETARG_Bx(i,b)((i)=(((i)&MASK0((9+9),((0+6)+8)))|((cast(Instruction,b)<<((0+6)+8))&MASK1((9+9),((0+6)+8))))) #define GETARG_sBx(i)(GETARG_Bx(i)-(((1<<(9+9))-1)>>1)) #define SETARG_sBx(i,b)SETARG_Bx((i),cast(unsigned int,(b)+(((1<<(9+9))-1)>>1))) #define CREATE_ABC(o,a,b,c)((cast(Instruction,o)<<0)|(cast(Instruction,a)<<(0+6))|(cast(Instruction,b)<<(((0+6)+8)+9))|(cast(Instruction,c)<<((0+6)+8))) #define CREATE_ABx(o,a,bc)((cast(Instruction,o)<<0)|(cast(Instruction,a)<<(0+6))|(cast(Instruction,bc)<<((0+6)+8))) #define ISK(x)((x)&(1<<(9-1))) #define INDEXK(r)((int)(r)&~(1<<(9-1))) #define RKASK(x)((x)|(1<<(9-1))) static const lu_byte luaP_opmodes[(cast(int,OP_VARARG)+1)]; #define getBMode(m)(cast(enum OpArgMask,(luaP_opmodes[m]>>4)&3)) #define getCMode(m)(cast(enum OpArgMask,(luaP_opmodes[m]>>2)&3)) #define testTMode(m)(luaP_opmodes[m]&(1<<7)) typedef struct expdesc{ expkind k; union{ struct{int info,aux;}s; lua_Number nval; }u; int t; int f; }expdesc; typedef struct upvaldesc{ lu_byte k; lu_byte info; }upvaldesc; struct BlockCnt; typedef struct FuncState{ Proto*f; Table*h; struct FuncState*prev; struct LexState*ls; struct lua_State*L; struct BlockCnt*bl; int pc; int lasttarget; int jpc; int freereg; int nk; int np; short nlocvars; lu_byte nactvar; upvaldesc upvalues[60]; unsigned short actvar[200]; }FuncState; static Proto*luaY_parser(lua_State*L,ZIO*z,Mbuffer*buff, const char*name); struct lua_longjmp{ struct lua_longjmp*previous; jmp_buf b; volatile int status; }; static void luaD_seterrorobj(lua_State*L,int errcode,StkId oldtop){ switch(errcode){ case 4:{ setsvalue(L,oldtop,luaS_newliteral(L,"not enough memory")); break; } case 5:{ setsvalue(L,oldtop,luaS_newliteral(L,"error in error handling")); break; } case 3: case 2:{ setobj(L,oldtop,L->top-1); break; } } L->top=oldtop+1; } static void restore_stack_limit(lua_State*L){ if(L->size_ci>20000){ int inuse=cast_int(L->ci-L->base_ci); if(inuse+1<20000) luaD_reallocCI(L,20000); } } static void resetstack(lua_State*L,int status){ L->ci=L->base_ci; L->base=L->ci->base; luaF_close(L,L->base); luaD_seterrorobj(L,status,L->base); L->nCcalls=L->baseCcalls; L->allowhook=1; restore_stack_limit(L); L->errfunc=0; L->errorJmp=NULL; } static void luaD_throw(lua_State*L,int errcode){ if(L->errorJmp){ L->errorJmp->status=errcode; LUAI_THROW(L,L->errorJmp); } else{ L->status=cast_byte(errcode); if(G(L)->panic){ resetstack(L,errcode); G(L)->panic(L); } exit(EXIT_FAILURE); } } static int luaD_rawrunprotected(lua_State*L,Pfunc f,void*ud){ struct lua_longjmp lj; lj.status=0; lj.previous=L->errorJmp; L->errorJmp=&lj; LUAI_TRY(L,&lj, (*f)(L,ud); ); L->errorJmp=lj.previous; return lj.status; } static void correctstack(lua_State*L,TValue*oldstack){ CallInfo*ci; GCObject*up; L->top=(L->top-oldstack)+L->stack; for(up=L->openupval;up!=NULL;up=up->gch.next) gco2uv(up)->v=(gco2uv(up)->v-oldstack)+L->stack; for(ci=L->base_ci;ci<=L->ci;ci++){ ci->top=(ci->top-oldstack)+L->stack; ci->base=(ci->base-oldstack)+L->stack; ci->func=(ci->func-oldstack)+L->stack; } L->base=(L->base-oldstack)+L->stack; } static void luaD_reallocstack(lua_State*L,int newsize){ TValue*oldstack=L->stack; int realsize=newsize+1+5; luaM_reallocvector(L,L->stack,L->stacksize,realsize,TValue); L->stacksize=realsize; L->stack_last=L->stack+newsize; correctstack(L,oldstack); } static void luaD_reallocCI(lua_State*L,int newsize){ CallInfo*oldci=L->base_ci; luaM_reallocvector(L,L->base_ci,L->size_ci,newsize,CallInfo); L->size_ci=newsize; L->ci=(L->ci-oldci)+L->base_ci; L->end_ci=L->base_ci+L->size_ci-1; } static void luaD_growstack(lua_State*L,int n){ if(n<=L->stacksize) luaD_reallocstack(L,2*L->stacksize); else luaD_reallocstack(L,L->stacksize+n); } static CallInfo*growCI(lua_State*L){ if(L->size_ci>20000) luaD_throw(L,5); else{ luaD_reallocCI(L,2*L->size_ci); if(L->size_ci>20000) luaG_runerror(L,"stack overflow"); } return++L->ci; } static StkId adjust_varargs(lua_State*L,Proto*p,int actual){ int i; int nfixargs=p->numparams; Table*htab=NULL; StkId base,fixed; for(;actual<nfixargs;++actual) setnilvalue(L->top++); fixed=L->top-actual; base=L->top; for(i=0;i<nfixargs;i++){ setobj(L,L->top++,fixed+i); setnilvalue(fixed+i); } if(htab){ sethvalue(L,L->top++,htab); } return base; } static StkId tryfuncTM(lua_State*L,StkId func){ const TValue*tm=luaT_gettmbyobj(L,func,TM_CALL); StkId p; ptrdiff_t funcr=savestack(L,func); if(!ttisfunction(tm)) luaG_typeerror(L,func,"call"); for(p=L->top;p>func;p--)setobj(L,p,p-1); incr_top(L); func=restorestack(L,funcr); setobj(L,func,tm); return func; } #define inc_ci(L)((L->ci==L->end_ci)?growCI(L):(condhardstacktests(luaD_reallocCI(L,L->size_ci)),++L->ci)) static int luaD_precall(lua_State*L,StkId func,int nresults){ LClosure*cl; ptrdiff_t funcr; if(!ttisfunction(func)) func=tryfuncTM(L,func); funcr=savestack(L,func); cl=&clvalue(func)->l; L->ci->savedpc=L->savedpc; if(!cl->isC){ CallInfo*ci; StkId st,base; Proto*p=cl->p; luaD_checkstack(L,p->maxstacksize); func=restorestack(L,funcr); if(!p->is_vararg){ base=func+1; if(L->top>base+p->numparams) L->top=base+p->numparams; } else{ int nargs=cast_int(L->top-func)-1; base=adjust_varargs(L,p,nargs); func=restorestack(L,funcr); } ci=inc_ci(L); ci->func=func; L->base=ci->base=base; ci->top=L->base+p->maxstacksize; L->savedpc=p->code; ci->tailcalls=0; ci->nresults=nresults; for(st=L->top;st<ci->top;st++) setnilvalue(st); L->top=ci->top; return 0; } else{ CallInfo*ci; int n; luaD_checkstack(L,20); ci=inc_ci(L); ci->func=restorestack(L,funcr); L->base=ci->base=ci->func+1; ci->top=L->top+20; ci->nresults=nresults; n=(*curr_func(L)->c.f)(L); if(n<0) return 2; else{ luaD_poscall(L,L->top-n); return 1; } } } static int luaD_poscall(lua_State*L,StkId firstResult){ StkId res; int wanted,i; CallInfo*ci; ci=L->ci--; res=ci->func; wanted=ci->nresults; L->base=(ci-1)->base; L->savedpc=(ci-1)->savedpc; for(i=wanted;i!=0&&firstResult<L->top;i--) setobj(L,res++,firstResult++); while(i-->0) setnilvalue(res++); L->top=res; return(wanted-(-1)); } static void luaD_call(lua_State*L,StkId func,int nResults){ if(++L->nCcalls>=200){ if(L->nCcalls==200) luaG_runerror(L,"C stack overflow"); else if(L->nCcalls>=(200+(200>>3))) luaD_throw(L,5); } if(luaD_precall(L,func,nResults)==0) luaV_execute(L,1); L->nCcalls--; luaC_checkGC(L); } static int luaD_pcall(lua_State*L,Pfunc func,void*u, ptrdiff_t old_top,ptrdiff_t ef){ int status; unsigned short oldnCcalls=L->nCcalls; ptrdiff_t old_ci=saveci(L,L->ci); lu_byte old_allowhooks=L->allowhook; ptrdiff_t old_errfunc=L->errfunc; L->errfunc=ef; status=luaD_rawrunprotected(L,func,u); if(status!=0){ StkId oldtop=restorestack(L,old_top); luaF_close(L,oldtop); luaD_seterrorobj(L,status,oldtop); L->nCcalls=oldnCcalls; L->ci=restoreci(L,old_ci); L->base=L->ci->base; L->savedpc=L->ci->savedpc; L->allowhook=old_allowhooks; restore_stack_limit(L); } L->errfunc=old_errfunc; return status; } struct SParser{ ZIO*z; Mbuffer buff; const char*name; }; static void f_parser(lua_State*L,void*ud){ int i; Proto*tf; Closure*cl; struct SParser*p=cast(struct SParser*,ud); luaC_checkGC(L); tf=luaY_parser(L,p->z, &p->buff,p->name); cl=luaF_newLclosure(L,tf->nups,hvalue(gt(L))); cl->l.p=tf; for(i=0;i<tf->nups;i++) cl->l.upvals[i]=luaF_newupval(L); setclvalue(L,L->top,cl); incr_top(L); } static int luaD_protectedparser(lua_State*L,ZIO*z,const char*name){ struct SParser p; int status; p.z=z;p.name=name; luaZ_initbuffer(L,&p.buff); status=luaD_pcall(L,f_parser,&p,savestack(L,L->top),L->errfunc); luaZ_freebuffer(L,&p.buff); return status; } static void luaS_resize(lua_State*L,int newsize){ GCObject**newhash; stringtable*tb; int i; if(G(L)->gcstate==2) return; newhash=luaM_newvector(L,newsize,GCObject*); tb=&G(L)->strt; for(i=0;i<newsize;i++)newhash[i]=NULL; for(i=0;i<tb->size;i++){ GCObject*p=tb->hash[i]; while(p){ GCObject*next=p->gch.next; unsigned int h=gco2ts(p)->hash; int h1=lmod(h,newsize); p->gch.next=newhash[h1]; newhash[h1]=p; p=next; } } luaM_freearray(L,tb->hash,tb->size,TString*); tb->size=newsize; tb->hash=newhash; } static TString*newlstr(lua_State*L,const char*str,size_t l, unsigned int h){ TString*ts; stringtable*tb; if(l+1>(((size_t)(~(size_t)0)-2)-sizeof(TString))/sizeof(char)) luaM_toobig(L); ts=cast(TString*,luaM_malloc(L,(l+1)*sizeof(char)+sizeof(TString))); ts->tsv.len=l; ts->tsv.hash=h; ts->tsv.marked=luaC_white(G(L)); ts->tsv.tt=4; ts->tsv.reserved=0; memcpy(ts+1,str,l*sizeof(char)); ((char*)(ts+1))[l]='\0'; tb=&G(L)->strt; h=lmod(h,tb->size); ts->tsv.next=tb->hash[h]; tb->hash[h]=obj2gco(ts); tb->nuse++; if(tb->nuse>cast(lu_int32,tb->size)&&tb->size<=(INT_MAX-2)/2) luaS_resize(L,tb->size*2); return ts; } static TString*luaS_newlstr(lua_State*L,const char*str,size_t l){ GCObject*o; unsigned int h=cast(unsigned int,l); size_t step=(l>>5)+1; size_t l1; for(l1=l;l1>=step;l1-=step) h=h^((h<<5)+(h>>2)+cast(unsigned char,str[l1-1])); for(o=G(L)->strt.hash[lmod(h,G(L)->strt.size)]; o!=NULL; o=o->gch.next){ TString*ts=rawgco2ts(o); if(ts->tsv.len==l&&(memcmp(str,getstr(ts),l)==0)){ if(isdead(G(L),o))changewhite(o); return ts; } } return newlstr(L,str,l,h); } static Udata*luaS_newudata(lua_State*L,size_t s,Table*e){ Udata*u; if(s>((size_t)(~(size_t)0)-2)-sizeof(Udata)) luaM_toobig(L); u=cast(Udata*,luaM_malloc(L,s+sizeof(Udata))); u->uv.marked=luaC_white(G(L)); u->uv.tt=7; u->uv.len=s; u->uv.metatable=NULL; u->uv.env=e; u->uv.next=G(L)->mainthread->next; G(L)->mainthread->next=obj2gco(u); return u; } #define hashpow2(t,n)(gnode(t,lmod((n),sizenode(t)))) #define hashstr(t,str)hashpow2(t,(str)->tsv.hash) #define hashboolean(t,p)hashpow2(t,p) #define hashmod(t,n)(gnode(t,((n)%((sizenode(t)-1)|1)))) #define hashpointer(t,p)hashmod(t,IntPoint(p)) static const Node dummynode_={ {{NULL},0}, {{{NULL},0,NULL}} }; static Node*hashnum(const Table*t,lua_Number n){ unsigned int a[cast_int(sizeof(lua_Number)/sizeof(int))]; int i; if(luai_numeq(n,0)) return gnode(t,0); memcpy(a,&n,sizeof(a)); for(i=1;i<cast_int(sizeof(lua_Number)/sizeof(int));i++)a[0]+=a[i]; return hashmod(t,a[0]); } static Node*mainposition(const Table*t,const TValue*key){ switch(ttype(key)){ case 3: return hashnum(t,nvalue(key)); case 4: return hashstr(t,rawtsvalue(key)); case 1: return hashboolean(t,bvalue(key)); case 2: return hashpointer(t,pvalue(key)); default: return hashpointer(t,gcvalue(key)); } } static int arrayindex(const TValue*key){ if(ttisnumber(key)){ lua_Number n=nvalue(key); int k; lua_number2int(k,n); if(luai_numeq(cast_num(k),n)) return k; } return-1; } static int findindex(lua_State*L,Table*t,StkId key){ int i; if(ttisnil(key))return-1; i=arrayindex(key); if(0<i&&i<=t->sizearray) return i-1; else{ Node*n=mainposition(t,key); do{ if(luaO_rawequalObj(key2tval(n),key)|| (ttype(gkey(n))==(8+3)&&iscollectable(key)&& gcvalue(gkey(n))==gcvalue(key))){ i=cast_int(n-gnode(t,0)); return i+t->sizearray; } else n=gnext(n); }while(n); luaG_runerror(L,"invalid key to "LUA_QL("next")); return 0; } } static int luaH_next(lua_State*L,Table*t,StkId key){ int i=findindex(L,t,key); for(i++;i<t->sizearray;i++){ if(!ttisnil(&t->array[i])){ setnvalue(key,cast_num(i+1)); setobj(L,key+1,&t->array[i]); return 1; } } for(i-=t->sizearray;i<(int)sizenode(t);i++){ if(!ttisnil(gval(gnode(t,i)))){ setobj(L,key,key2tval(gnode(t,i))); setobj(L,key+1,gval(gnode(t,i))); return 1; } } return 0; } static int computesizes(int nums[],int*narray){ int i; int twotoi; int a=0; int na=0; int n=0; for(i=0,twotoi=1;twotoi/2<*narray;i++,twotoi*=2){ if(nums[i]>0){ a+=nums[i]; if(a>twotoi/2){ n=twotoi; na=a; } } if(a==*narray)break; } *narray=n; return na; } static int countint(const TValue*key,int*nums){ int k=arrayindex(key); if(0<k&&k<=(1<<(32-2))){ nums[ceillog2(k)]++; return 1; } else return 0; } static int numusearray(const Table*t,int*nums){ int lg; int ttlg; int ause=0; int i=1; for(lg=0,ttlg=1;lg<=(32-2);lg++,ttlg*=2){ int lc=0; int lim=ttlg; if(lim>t->sizearray){ lim=t->sizearray; if(i>lim) break; } for(;i<=lim;i++){ if(!ttisnil(&t->array[i-1])) lc++; } nums[lg]+=lc; ause+=lc; } return ause; } static int numusehash(const Table*t,int*nums,int*pnasize){ int totaluse=0; int ause=0; int i=sizenode(t); while(i--){ Node*n=&t->node[i]; if(!ttisnil(gval(n))){ ause+=countint(key2tval(n),nums); totaluse++; } } *pnasize+=ause; return totaluse; } static void setarrayvector(lua_State*L,Table*t,int size){ int i; luaM_reallocvector(L,t->array,t->sizearray,size,TValue); for(i=t->sizearray;i<size;i++) setnilvalue(&t->array[i]); t->sizearray=size; } static void setnodevector(lua_State*L,Table*t,int size){ int lsize; if(size==0){ t->node=cast(Node*,(&dummynode_)); lsize=0; } else{ int i; lsize=ceillog2(size); if(lsize>(32-2)) luaG_runerror(L,"table overflow"); size=twoto(lsize); t->node=luaM_newvector(L,size,Node); for(i=0;i<size;i++){ Node*n=gnode(t,i); gnext(n)=NULL; setnilvalue(gkey(n)); setnilvalue(gval(n)); } } t->lsizenode=cast_byte(lsize); t->lastfree=gnode(t,size); } static void resize(lua_State*L,Table*t,int nasize,int nhsize){ int i; int oldasize=t->sizearray; int oldhsize=t->lsizenode; Node*nold=t->node; if(nasize>oldasize) setarrayvector(L,t,nasize); setnodevector(L,t,nhsize); if(nasize<oldasize){ t->sizearray=nasize; for(i=nasize;i<oldasize;i++){ if(!ttisnil(&t->array[i])) setobj(L,luaH_setnum(L,t,i+1),&t->array[i]); } luaM_reallocvector(L,t->array,oldasize,nasize,TValue); } for(i=twoto(oldhsize)-1;i>=0;i--){ Node*old=nold+i; if(!ttisnil(gval(old))) setobj(L,luaH_set(L,t,key2tval(old)),gval(old)); } if(nold!=(&dummynode_)) luaM_freearray(L,nold,twoto(oldhsize),Node); } static void luaH_resizearray(lua_State*L,Table*t,int nasize){ int nsize=(t->node==(&dummynode_))?0:sizenode(t); resize(L,t,nasize,nsize); } static void rehash(lua_State*L,Table*t,const TValue*ek){ int nasize,na; int nums[(32-2)+1]; int i; int totaluse; for(i=0;i<=(32-2);i++)nums[i]=0; nasize=numusearray(t,nums); totaluse=nasize; totaluse+=numusehash(t,nums,&nasize); nasize+=countint(ek,nums); totaluse++; na=computesizes(nums,&nasize); resize(L,t,nasize,totaluse-na); } static Table*luaH_new(lua_State*L,int narray,int nhash){ Table*t=luaM_new(L,Table); luaC_link(L,obj2gco(t),5); t->metatable=NULL; t->flags=cast_byte(~0); t->array=NULL; t->sizearray=0; t->lsizenode=0; t->node=cast(Node*,(&dummynode_)); setarrayvector(L,t,narray); setnodevector(L,t,nhash); return t; } static void luaH_free(lua_State*L,Table*t){ if(t->node!=(&dummynode_)) luaM_freearray(L,t->node,sizenode(t),Node); luaM_freearray(L,t->array,t->sizearray,TValue); luaM_free(L,t); } static Node*getfreepos(Table*t){ while(t->lastfree-->t->node){ if(ttisnil(gkey(t->lastfree))) return t->lastfree; } return NULL; } static TValue*newkey(lua_State*L,Table*t,const TValue*key){ Node*mp=mainposition(t,key); if(!ttisnil(gval(mp))||mp==(&dummynode_)){ Node*othern; Node*n=getfreepos(t); if(n==NULL){ rehash(L,t,key); return luaH_set(L,t,key); } othern=mainposition(t,key2tval(mp)); if(othern!=mp){ while(gnext(othern)!=mp)othern=gnext(othern); gnext(othern)=n; *n=*mp; gnext(mp)=NULL; setnilvalue(gval(mp)); } else{ gnext(n)=gnext(mp); gnext(mp)=n; mp=n; } } gkey(mp)->value=key->value;gkey(mp)->tt=key->tt; luaC_barriert(L,t,key); return gval(mp); } static const TValue*luaH_getnum(Table*t,int key){ if(cast(unsigned int,key-1)<cast(unsigned int,t->sizearray)) return&t->array[key-1]; else{ lua_Number nk=cast_num(key); Node*n=hashnum(t,nk); do{ if(ttisnumber(gkey(n))&&luai_numeq(nvalue(gkey(n)),nk)) return gval(n); else n=gnext(n); }while(n); return(&luaO_nilobject_); } } static const TValue*luaH_getstr(Table*t,TString*key){ Node*n=hashstr(t,key); do{ if(ttisstring(gkey(n))&&rawtsvalue(gkey(n))==key) return gval(n); else n=gnext(n); }while(n); return(&luaO_nilobject_); } static const TValue*luaH_get(Table*t,const TValue*key){ switch(ttype(key)){ case 0:return(&luaO_nilobject_); case 4:return luaH_getstr(t,rawtsvalue(key)); case 3:{ int k; lua_Number n=nvalue(key); lua_number2int(k,n); if(luai_numeq(cast_num(k),nvalue(key))) return luaH_getnum(t,k); } default:{ Node*n=mainposition(t,key); do{ if(luaO_rawequalObj(key2tval(n),key)) return gval(n); else n=gnext(n); }while(n); return(&luaO_nilobject_); } } } static TValue*luaH_set(lua_State*L,Table*t,const TValue*key){ const TValue*p=luaH_get(t,key); t->flags=0; if(p!=(&luaO_nilobject_)) return cast(TValue*,p); else{ if(ttisnil(key))luaG_runerror(L,"table index is nil"); else if(ttisnumber(key)&&luai_numisnan(nvalue(key))) luaG_runerror(L,"table index is NaN"); return newkey(L,t,key); } } static TValue*luaH_setnum(lua_State*L,Table*t,int key){ const TValue*p=luaH_getnum(t,key); if(p!=(&luaO_nilobject_)) return cast(TValue*,p); else{ TValue k; setnvalue(&k,cast_num(key)); return newkey(L,t,&k); } } static TValue*luaH_setstr(lua_State*L,Table*t,TString*key){ const TValue*p=luaH_getstr(t,key); if(p!=(&luaO_nilobject_)) return cast(TValue*,p); else{ TValue k; setsvalue(L,&k,key); return newkey(L,t,&k); } } static int unbound_search(Table*t,unsigned int j){ unsigned int i=j; j++; while(!ttisnil(luaH_getnum(t,j))){ i=j; j*=2; if(j>cast(unsigned int,(INT_MAX-2))){ i=1; while(!ttisnil(luaH_getnum(t,i)))i++; return i-1; } } while(j-i>1){ unsigned int m=(i+j)/2; if(ttisnil(luaH_getnum(t,m)))j=m; else i=m; } return i; } static int luaH_getn(Table*t){ unsigned int j=t->sizearray; if(j>0&&ttisnil(&t->array[j-1])){ unsigned int i=0; while(j-i>1){ unsigned int m=(i+j)/2; if(ttisnil(&t->array[m-1]))j=m; else i=m; } return i; } else if(t->node==(&dummynode_)) return j; else return unbound_search(t,j); } #define makewhite(g,x)((x)->gch.marked=cast_byte(((x)->gch.marked&cast_byte(~(bitmask(2)|bit2mask(0,1))))|luaC_white(g))) #define white2gray(x)reset2bits((x)->gch.marked,0,1) #define black2gray(x)resetbit((x)->gch.marked,2) #define stringmark(s)reset2bits((s)->tsv.marked,0,1) #define isfinalized(u)testbit((u)->marked,3) #define markfinalized(u)l_setbit((u)->marked,3) #define markvalue(g,o){checkconsistency(o);if(iscollectable(o)&&iswhite(gcvalue(o)))reallymarkobject(g,gcvalue(o));} #define markobject(g,t){if(iswhite(obj2gco(t)))reallymarkobject(g,obj2gco(t));} #define setthreshold(g)(g->GCthreshold=(g->estimate/100)*g->gcpause) static void removeentry(Node*n){ if(iscollectable(gkey(n))) setttype(gkey(n),(8+3)); } static void reallymarkobject(global_State*g,GCObject*o){ white2gray(o); switch(o->gch.tt){ case 4:{ return; } case 7:{ Table*mt=gco2u(o)->metatable; gray2black(o); if(mt)markobject(g,mt); markobject(g,gco2u(o)->env); return; } case(8+2):{ UpVal*uv=gco2uv(o); markvalue(g,uv->v); if(uv->v==&uv->u.value) gray2black(o); return; } case 6:{ gco2cl(o)->c.gclist=g->gray; g->gray=o; break; } case 5:{ gco2h(o)->gclist=g->gray; g->gray=o; break; } case 8:{ gco2th(o)->gclist=g->gray; g->gray=o; break; } case(8+1):{ gco2p(o)->gclist=g->gray; g->gray=o; break; } default:; } } static void marktmu(global_State*g){ GCObject*u=g->tmudata; if(u){ do{ u=u->gch.next; makewhite(g,u); reallymarkobject(g,u); }while(u!=g->tmudata); } } static size_t luaC_separateudata(lua_State*L,int all){ global_State*g=G(L); size_t deadmem=0; GCObject**p=&g->mainthread->next; GCObject*curr; while((curr=*p)!=NULL){ if(!(iswhite(curr)||all)||isfinalized(gco2u(curr))) p=&curr->gch.next; else if(fasttm(L,gco2u(curr)->metatable,TM_GC)==NULL){ markfinalized(gco2u(curr)); p=&curr->gch.next; } else{ deadmem+=sizeudata(gco2u(curr)); markfinalized(gco2u(curr)); *p=curr->gch.next; if(g->tmudata==NULL) g->tmudata=curr->gch.next=curr; else{ curr->gch.next=g->tmudata->gch.next; g->tmudata->gch.next=curr; g->tmudata=curr; } } } return deadmem; } static int traversetable(global_State*g,Table*h){ int i; int weakkey=0; int weakvalue=0; const TValue*mode; if(h->metatable) markobject(g,h->metatable); mode=gfasttm(g,h->metatable,TM_MODE); if(mode&&ttisstring(mode)){ weakkey=(strchr(svalue(mode),'k')!=NULL); weakvalue=(strchr(svalue(mode),'v')!=NULL); if(weakkey||weakvalue){ h->marked&=~(bitmask(3)|bitmask(4)); h->marked|=cast_byte((weakkey<<3)| (weakvalue<<4)); h->gclist=g->weak; g->weak=obj2gco(h); } } if(weakkey&&weakvalue)return 1; if(!weakvalue){ i=h->sizearray; while(i--) markvalue(g,&h->array[i]); } i=sizenode(h); while(i--){ Node*n=gnode(h,i); if(ttisnil(gval(n))) removeentry(n); else{ if(!weakkey)markvalue(g,gkey(n)); if(!weakvalue)markvalue(g,gval(n)); } } return weakkey||weakvalue; } static void traverseproto(global_State*g,Proto*f){ int i; if(f->source)stringmark(f->source); for(i=0;i<f->sizek;i++) markvalue(g,&f->k[i]); for(i=0;i<f->sizeupvalues;i++){ if(f->upvalues[i]) stringmark(f->upvalues[i]); } for(i=0;i<f->sizep;i++){ if(f->p[i]) markobject(g,f->p[i]); } for(i=0;i<f->sizelocvars;i++){ if(f->locvars[i].varname) stringmark(f->locvars[i].varname); } } static void traverseclosure(global_State*g,Closure*cl){ markobject(g,cl->c.env); if(cl->c.isC){ int i; for(i=0;i<cl->c.nupvalues;i++) markvalue(g,&cl->c.upvalue[i]); } else{ int i; markobject(g,cl->l.p); for(i=0;i<cl->l.nupvalues;i++) markobject(g,cl->l.upvals[i]); } } static void checkstacksizes(lua_State*L,StkId max){ int ci_used=cast_int(L->ci-L->base_ci); int s_used=cast_int(max-L->stack); if(L->size_ci>20000) return; if(4*ci_used<L->size_ci&&2*8<L->size_ci) luaD_reallocCI(L,L->size_ci/2); condhardstacktests(luaD_reallocCI(L,ci_used+1)); if(4*s_used<L->stacksize&& 2*((2*20)+5)<L->stacksize) luaD_reallocstack(L,L->stacksize/2); condhardstacktests(luaD_reallocstack(L,s_used)); } static void traversestack(global_State*g,lua_State*l){ StkId o,lim; CallInfo*ci; markvalue(g,gt(l)); lim=l->top; for(ci=l->base_ci;ci<=l->ci;ci++){ if(lim<ci->top)lim=ci->top; } for(o=l->stack;o<l->top;o++) markvalue(g,o); for(;o<=lim;o++) setnilvalue(o); checkstacksizes(l,lim); } static l_mem propagatemark(global_State*g){ GCObject*o=g->gray; gray2black(o); switch(o->gch.tt){ case 5:{ Table*h=gco2h(o); g->gray=h->gclist; if(traversetable(g,h)) black2gray(o); return sizeof(Table)+sizeof(TValue)*h->sizearray+ sizeof(Node)*sizenode(h); } case 6:{ Closure*cl=gco2cl(o); g->gray=cl->c.gclist; traverseclosure(g,cl); return(cl->c.isC)?sizeCclosure(cl->c.nupvalues): sizeLclosure(cl->l.nupvalues); } case 8:{ lua_State*th=gco2th(o); g->gray=th->gclist; th->gclist=g->grayagain; g->grayagain=o; black2gray(o); traversestack(g,th); return sizeof(lua_State)+sizeof(TValue)*th->stacksize+ sizeof(CallInfo)*th->size_ci; } case(8+1):{ Proto*p=gco2p(o); g->gray=p->gclist; traverseproto(g,p); return sizeof(Proto)+sizeof(Instruction)*p->sizecode+ sizeof(Proto*)*p->sizep+ sizeof(TValue)*p->sizek+ sizeof(int)*p->sizelineinfo+ sizeof(LocVar)*p->sizelocvars+ sizeof(TString*)*p->sizeupvalues; } default:return 0; } } static size_t propagateall(global_State*g){ size_t m=0; while(g->gray)m+=propagatemark(g); return m; } static int iscleared(const TValue*o,int iskey){ if(!iscollectable(o))return 0; if(ttisstring(o)){ stringmark(rawtsvalue(o)); return 0; } return iswhite(gcvalue(o))|| (ttisuserdata(o)&&(!iskey&&isfinalized(uvalue(o)))); } static void cleartable(GCObject*l){ while(l){ Table*h=gco2h(l); int i=h->sizearray; if(testbit(h->marked,4)){ while(i--){ TValue*o=&h->array[i]; if(iscleared(o,0)) setnilvalue(o); } } i=sizenode(h); while(i--){ Node*n=gnode(h,i); if(!ttisnil(gval(n))&& (iscleared(key2tval(n),1)||iscleared(gval(n),0))){ setnilvalue(gval(n)); removeentry(n); } } l=h->gclist; } } static void freeobj(lua_State*L,GCObject*o){ switch(o->gch.tt){ case(8+1):luaF_freeproto(L,gco2p(o));break; case 6:luaF_freeclosure(L,gco2cl(o));break; case(8+2):luaF_freeupval(L,gco2uv(o));break; case 5:luaH_free(L,gco2h(o));break; case 8:{ luaE_freethread(L,gco2th(o)); break; } case 4:{ G(L)->strt.nuse--; luaM_freemem(L,o,sizestring(gco2ts(o))); break; } case 7:{ luaM_freemem(L,o,sizeudata(gco2u(o))); break; } default:; } } #define sweepwholelist(L,p)sweeplist(L,p,((lu_mem)(~(lu_mem)0)-2)) static GCObject**sweeplist(lua_State*L,GCObject**p,lu_mem count){ GCObject*curr; global_State*g=G(L); int deadmask=otherwhite(g); while((curr=*p)!=NULL&&count-->0){ if(curr->gch.tt==8) sweepwholelist(L,&gco2th(curr)->openupval); if((curr->gch.marked^bit2mask(0,1))&deadmask){ makewhite(g,curr); p=&curr->gch.next; } else{ *p=curr->gch.next; if(curr==g->rootgc) g->rootgc=curr->gch.next; freeobj(L,curr); } } return p; } static void checkSizes(lua_State*L){ global_State*g=G(L); if(g->strt.nuse<cast(lu_int32,g->strt.size/4)&& g->strt.size>32*2) luaS_resize(L,g->strt.size/2); if(luaZ_sizebuffer(&g->buff)>32*2){ size_t newsize=luaZ_sizebuffer(&g->buff)/2; luaZ_resizebuffer(L,&g->buff,newsize); } } static void GCTM(lua_State*L){ global_State*g=G(L); GCObject*o=g->tmudata->gch.next; Udata*udata=rawgco2u(o); const TValue*tm; if(o==g->tmudata) g->tmudata=NULL; else g->tmudata->gch.next=udata->uv.next; udata->uv.next=g->mainthread->next; g->mainthread->next=o; makewhite(g,o); tm=fasttm(L,udata->uv.metatable,TM_GC); if(tm!=NULL){ lu_byte oldah=L->allowhook; lu_mem oldt=g->GCthreshold; L->allowhook=0; g->GCthreshold=2*g->totalbytes; setobj(L,L->top,tm); setuvalue(L,L->top+1,udata); L->top+=2; luaD_call(L,L->top-2,0); L->allowhook=oldah; g->GCthreshold=oldt; } } static void luaC_callGCTM(lua_State*L){ while(G(L)->tmudata) GCTM(L); } static void luaC_freeall(lua_State*L){ global_State*g=G(L); int i; g->currentwhite=bit2mask(0,1)|bitmask(6); sweepwholelist(L,&g->rootgc); for(i=0;i<g->strt.size;i++) sweepwholelist(L,&g->strt.hash[i]); } static void markmt(global_State*g){ int i; for(i=0;i<(8+1);i++) if(g->mt[i])markobject(g,g->mt[i]); } static void markroot(lua_State*L){ global_State*g=G(L); g->gray=NULL; g->grayagain=NULL; g->weak=NULL; markobject(g,g->mainthread); markvalue(g,gt(g->mainthread)); markvalue(g,registry(L)); markmt(g); g->gcstate=1; } static void remarkupvals(global_State*g){ UpVal*uv; for(uv=g->uvhead.u.l.next;uv!=&g->uvhead;uv=uv->u.l.next){ if(isgray(obj2gco(uv))) markvalue(g,uv->v); } } static void atomic(lua_State*L){ global_State*g=G(L); size_t udsize; remarkupvals(g); propagateall(g); g->gray=g->weak; g->weak=NULL; markobject(g,L); markmt(g); propagateall(g); g->gray=g->grayagain; g->grayagain=NULL; propagateall(g); udsize=luaC_separateudata(L,0); marktmu(g); udsize+=propagateall(g); cleartable(g->weak); g->currentwhite=cast_byte(otherwhite(g)); g->sweepstrgc=0; g->sweepgc=&g->rootgc; g->gcstate=2; g->estimate=g->totalbytes-udsize; } static l_mem singlestep(lua_State*L){ global_State*g=G(L); switch(g->gcstate){ case 0:{ markroot(L); return 0; } case 1:{ if(g->gray) return propagatemark(g); else{ atomic(L); return 0; } } case 2:{ lu_mem old=g->totalbytes; sweepwholelist(L,&g->strt.hash[g->sweepstrgc++]); if(g->sweepstrgc>=g->strt.size) g->gcstate=3; g->estimate-=old-g->totalbytes; return 10; } case 3:{ lu_mem old=g->totalbytes; g->sweepgc=sweeplist(L,g->sweepgc,40); if(*g->sweepgc==NULL){ checkSizes(L); g->gcstate=4; } g->estimate-=old-g->totalbytes; return 40*10; } case 4:{ if(g->tmudata){ GCTM(L); if(g->estimate>100) g->estimate-=100; return 100; } else{ g->gcstate=0; g->gcdept=0; return 0; } } default:return 0; } } static void luaC_step(lua_State*L){ global_State*g=G(L); l_mem lim=(1024u/100)*g->gcstepmul; if(lim==0) lim=(((lu_mem)(~(lu_mem)0)-2)-1)/2; g->gcdept+=g->totalbytes-g->GCthreshold; do{ lim-=singlestep(L); if(g->gcstate==0) break; }while(lim>0); if(g->gcstate!=0){ if(g->gcdept<1024u) g->GCthreshold=g->totalbytes+1024u; else{ g->gcdept-=1024u; g->GCthreshold=g->totalbytes; } } else{ setthreshold(g); } } static void luaC_barrierf(lua_State*L,GCObject*o,GCObject*v){ global_State*g=G(L); if(g->gcstate==1) reallymarkobject(g,v); else makewhite(g,o); } static void luaC_barrierback(lua_State*L,Table*t){ global_State*g=G(L); GCObject*o=obj2gco(t); black2gray(o); t->gclist=g->grayagain; g->grayagain=o; } static void luaC_link(lua_State*L,GCObject*o,lu_byte tt){ global_State*g=G(L); o->gch.next=g->rootgc; g->rootgc=o; o->gch.marked=luaC_white(g); o->gch.tt=tt; } static void luaC_linkupval(lua_State*L,UpVal*uv){ global_State*g=G(L); GCObject*o=obj2gco(uv); o->gch.next=g->rootgc; g->rootgc=o; if(isgray(o)){ if(g->gcstate==1){ gray2black(o); luaC_barrier(L,uv,uv->v); } else{ makewhite(g,o); } } } typedef union{ lua_Number r; TString*ts; }SemInfo; typedef struct Token{ int token; SemInfo seminfo; }Token; typedef struct LexState{ int current; int linenumber; int lastline; Token t; Token lookahead; struct FuncState*fs; struct lua_State*L; ZIO*z; Mbuffer*buff; TString*source; char decpoint; }LexState; static void luaX_init(lua_State*L); static void luaX_lexerror(LexState*ls,const char*msg,int token); #define state_size(x)(sizeof(x)+0) #define fromstate(l)(cast(lu_byte*,(l))-0) #define tostate(l)(cast(lua_State*,cast(lu_byte*,l)+0)) typedef struct LG{ lua_State l; global_State g; }LG; static void stack_init(lua_State*L1,lua_State*L){ L1->base_ci=luaM_newvector(L,8,CallInfo); L1->ci=L1->base_ci; L1->size_ci=8; L1->end_ci=L1->base_ci+L1->size_ci-1; L1->stack=luaM_newvector(L,(2*20)+5,TValue); L1->stacksize=(2*20)+5; L1->top=L1->stack; L1->stack_last=L1->stack+(L1->stacksize-5)-1; L1->ci->func=L1->top; setnilvalue(L1->top++); L1->base=L1->ci->base=L1->top; L1->ci->top=L1->top+20; } static void freestack(lua_State*L,lua_State*L1){ luaM_freearray(L,L1->base_ci,L1->size_ci,CallInfo); luaM_freearray(L,L1->stack,L1->stacksize,TValue); } static void f_luaopen(lua_State*L,void*ud){ global_State*g=G(L); UNUSED(ud); stack_init(L,L); sethvalue(L,gt(L),luaH_new(L,0,2)); sethvalue(L,registry(L),luaH_new(L,0,2)); luaS_resize(L,32); luaT_init(L); luaX_init(L); luaS_fix(luaS_newliteral(L,"not enough memory")); g->GCthreshold=4*g->totalbytes; } static void preinit_state(lua_State*L,global_State*g){ G(L)=g; L->stack=NULL; L->stacksize=0; L->errorJmp=NULL; L->hook=NULL; L->hookmask=0; L->basehookcount=0; L->allowhook=1; resethookcount(L); L->openupval=NULL; L->size_ci=0; L->nCcalls=L->baseCcalls=0; L->status=0; L->base_ci=L->ci=NULL; L->savedpc=NULL; L->errfunc=0; setnilvalue(gt(L)); } static void close_state(lua_State*L){ global_State*g=G(L); luaF_close(L,L->stack); luaC_freeall(L); luaM_freearray(L,G(L)->strt.hash,G(L)->strt.size,TString*); luaZ_freebuffer(L,&g->buff); freestack(L,L); (*g->frealloc)(g->ud,fromstate(L),state_size(LG),0); } static void luaE_freethread(lua_State*L,lua_State*L1){ luaF_close(L1,L1->stack); freestack(L,L1); luaM_freemem(L,fromstate(L1),state_size(lua_State)); } static lua_State*lua_newstate(lua_Alloc f,void*ud){ int i; lua_State*L; global_State*g; void*l=(*f)(ud,NULL,0,state_size(LG)); if(l==NULL)return NULL; L=tostate(l); g=&((LG*)L)->g; L->next=NULL; L->tt=8; g->currentwhite=bit2mask(0,5); L->marked=luaC_white(g); set2bits(L->marked,5,6); preinit_state(L,g); g->frealloc=f; g->ud=ud; g->mainthread=L; g->uvhead.u.l.prev=&g->uvhead; g->uvhead.u.l.next=&g->uvhead; g->GCthreshold=0; g->strt.size=0; g->strt.nuse=0; g->strt.hash=NULL; setnilvalue(registry(L)); luaZ_initbuffer(L,&g->buff); g->panic=NULL; g->gcstate=0; g->rootgc=obj2gco(L); g->sweepstrgc=0; g->sweepgc=&g->rootgc; g->gray=NULL; g->grayagain=NULL; g->weak=NULL; g->tmudata=NULL; g->totalbytes=sizeof(LG); g->gcpause=200; g->gcstepmul=200; g->gcdept=0; for(i=0;i<(8+1);i++)g->mt[i]=NULL; if(luaD_rawrunprotected(L,f_luaopen,NULL)!=0){ close_state(L); L=NULL; } else {} return L; } static void callallgcTM(lua_State*L,void*ud){ UNUSED(ud); luaC_callGCTM(L); } static void lua_close(lua_State*L){ L=G(L)->mainthread; luaF_close(L,L->stack); luaC_separateudata(L,1); L->errfunc=0; do{ L->ci=L->base_ci; L->base=L->top=L->ci->base; L->nCcalls=L->baseCcalls=0; }while(luaD_rawrunprotected(L,callallgcTM,NULL)!=0); close_state(L); } #define getcode(fs,e)((fs)->f->code[(e)->u.s.info]) #define luaK_codeAsBx(fs,o,A,sBx)luaK_codeABx(fs,o,A,(sBx)+(((1<<(9+9))-1)>>1)) #define luaK_setmultret(fs,e)luaK_setreturns(fs,e,(-1)) static int luaK_codeABx(FuncState*fs,OpCode o,int A,unsigned int Bx); static int luaK_codeABC(FuncState*fs,OpCode o,int A,int B,int C); static void luaK_setreturns(FuncState*fs,expdesc*e,int nresults); static void luaK_patchtohere(FuncState*fs,int list); static void luaK_concat(FuncState*fs,int*l1,int l2); static int currentpc(lua_State*L,CallInfo*ci){ if(!isLua(ci))return-1; if(ci==L->ci) ci->savedpc=L->savedpc; return pcRel(ci->savedpc,ci_func(ci)->l.p); } static int currentline(lua_State*L,CallInfo*ci){ int pc=currentpc(L,ci); if(pc<0) return-1; else return getline_(ci_func(ci)->l.p,pc); } static int lua_getstack(lua_State*L,int level,lua_Debug*ar){ int status; CallInfo*ci; for(ci=L->ci;level>0&&ci>L->base_ci;ci--){ level--; if(f_isLua(ci)) level-=ci->tailcalls; } if(level==0&&ci>L->base_ci){ status=1; ar->i_ci=cast_int(ci-L->base_ci); } else if(level<0){ status=1; ar->i_ci=0; } else status=0; return status; } static Proto*getluaproto(CallInfo*ci){ return(isLua(ci)?ci_func(ci)->l.p:NULL); } static void funcinfo(lua_Debug*ar,Closure*cl){ if(cl->c.isC){ ar->source="=[C]"; ar->linedefined=-1; ar->lastlinedefined=-1; ar->what="C"; } else{ ar->source=getstr(cl->l.p->source); ar->linedefined=cl->l.p->linedefined; ar->lastlinedefined=cl->l.p->lastlinedefined; ar->what=(ar->linedefined==0)?"main":"Lua"; } luaO_chunkid(ar->short_src,ar->source,60); } static void info_tailcall(lua_Debug*ar){ ar->name=ar->namewhat=""; ar->what="tail"; ar->lastlinedefined=ar->linedefined=ar->currentline=-1; ar->source="=(tail call)"; luaO_chunkid(ar->short_src,ar->source,60); ar->nups=0; } static void collectvalidlines(lua_State*L,Closure*f){ if(f==NULL||f->c.isC){ setnilvalue(L->top); } else{ Table*t=luaH_new(L,0,0); int*lineinfo=f->l.p->lineinfo; int i; for(i=0;i<f->l.p->sizelineinfo;i++) setbvalue(luaH_setnum(L,t,lineinfo[i]),1); sethvalue(L,L->top,t); } incr_top(L); } static int auxgetinfo(lua_State*L,const char*what,lua_Debug*ar, Closure*f,CallInfo*ci){ int status=1; if(f==NULL){ info_tailcall(ar); return status; } for(;*what;what++){ switch(*what){ case'S':{ funcinfo(ar,f); break; } case'l':{ ar->currentline=(ci)?currentline(L,ci):-1; break; } case'u':{ ar->nups=f->c.nupvalues; break; } case'n':{ ar->namewhat=(ci)?NULL:NULL; if(ar->namewhat==NULL){ ar->namewhat=""; ar->name=NULL; } break; } case'L': case'f': break; default:status=0; } } return status; } static int lua_getinfo(lua_State*L,const char*what,lua_Debug*ar){ int status; Closure*f=NULL; CallInfo*ci=NULL; if(*what=='>'){ StkId func=L->top-1; luai_apicheck(L,ttisfunction(func)); what++; f=clvalue(func); L->top--; } else if(ar->i_ci!=0){ ci=L->base_ci+ar->i_ci; f=clvalue(ci->func); } status=auxgetinfo(L,what,ar,f,ci); if(strchr(what,'f')){ if(f==NULL)setnilvalue(L->top); else setclvalue(L,L->top,f); incr_top(L); } if(strchr(what,'L')) collectvalidlines(L,f); return status; } static int isinstack(CallInfo*ci,const TValue*o){ StkId p; for(p=ci->base;p<ci->top;p++) if(o==p)return 1; return 0; } static void luaG_typeerror(lua_State*L,const TValue*o,const char*op){ const char*name=NULL; const char*t=luaT_typenames[ttype(o)]; const char*kind=(isinstack(L->ci,o))? NULL: NULL; if(kind) luaG_runerror(L,"attempt to %s %s "LUA_QL("%s")" (a %s value)", op,kind,name,t); else luaG_runerror(L,"attempt to %s a %s value",op,t); } static void luaG_concaterror(lua_State*L,StkId p1,StkId p2){ if(ttisstring(p1)||ttisnumber(p1))p1=p2; luaG_typeerror(L,p1,"concatenate"); } static void luaG_aritherror(lua_State*L,const TValue*p1,const TValue*p2){ TValue temp; if(luaV_tonumber(p1,&temp)==NULL) p2=p1; luaG_typeerror(L,p2,"perform arithmetic on"); } static int luaG_ordererror(lua_State*L,const TValue*p1,const TValue*p2){ const char*t1=luaT_typenames[ttype(p1)]; const char*t2=luaT_typenames[ttype(p2)]; if(t1[2]==t2[2]) luaG_runerror(L,"attempt to compare two %s values",t1); else luaG_runerror(L,"attempt to compare %s with %s",t1,t2); return 0; } static void addinfo(lua_State*L,const char*msg){ CallInfo*ci=L->ci; if(isLua(ci)){ char buff[60]; int line=currentline(L,ci); luaO_chunkid(buff,getstr(getluaproto(ci)->source),60); luaO_pushfstring(L,"%s:%d: %s",buff,line,msg); } } static void luaG_errormsg(lua_State*L){ if(L->errfunc!=0){ StkId errfunc=restorestack(L,L->errfunc); if(!ttisfunction(errfunc))luaD_throw(L,5); setobj(L,L->top,L->top-1); setobj(L,L->top-1,errfunc); incr_top(L); luaD_call(L,L->top-2,1); } luaD_throw(L,2); } static void luaG_runerror(lua_State*L,const char*fmt,...){ va_list argp; va_start(argp,fmt); addinfo(L,luaO_pushvfstring(L,fmt,argp)); va_end(argp); luaG_errormsg(L); } static int luaZ_fill(ZIO*z){ size_t size; lua_State*L=z->L; const char*buff; buff=z->reader(L,z->data,&size); if(buff==NULL||size==0)return(-1); z->n=size-1; z->p=buff; return char2int(*(z->p++)); } static void luaZ_init(lua_State*L,ZIO*z,lua_Reader reader,void*data){ z->L=L; z->reader=reader; z->data=data; z->n=0; z->p=NULL; } static char*luaZ_openspace(lua_State*L,Mbuffer*buff,size_t n){ if(n>buff->buffsize){ if(n<32)n=32; luaZ_resizebuffer(L,buff,n); } return buff->buffer; } #define opmode(t,a,b,c,m)(((t)<<7)|((a)<<6)|((b)<<4)|((c)<<2)|(m)) static const lu_byte luaP_opmodes[(cast(int,OP_VARARG)+1)]={ opmode(0,1,OpArgR,OpArgN,iABC) ,opmode(0,1,OpArgK,OpArgN,iABx) ,opmode(0,1,OpArgU,OpArgU,iABC) ,opmode(0,1,OpArgR,OpArgN,iABC) ,opmode(0,1,OpArgU,OpArgN,iABC) ,opmode(0,1,OpArgK,OpArgN,iABx) ,opmode(0,1,OpArgR,OpArgK,iABC) ,opmode(0,0,OpArgK,OpArgN,iABx) ,opmode(0,0,OpArgU,OpArgN,iABC) ,opmode(0,0,OpArgK,OpArgK,iABC) ,opmode(0,1,OpArgU,OpArgU,iABC) ,opmode(0,1,OpArgR,OpArgK,iABC) ,opmode(0,1,OpArgK,OpArgK,iABC) ,opmode(0,1,OpArgK,OpArgK,iABC) ,opmode(0,1,OpArgK,OpArgK,iABC) ,opmode(0,1,OpArgK,OpArgK,iABC) ,opmode(0,1,OpArgK,OpArgK,iABC) ,opmode(0,1,OpArgK,OpArgK,iABC) ,opmode(0,1,OpArgR,OpArgN,iABC) ,opmode(0,1,OpArgR,OpArgN,iABC) ,opmode(0,1,OpArgR,OpArgN,iABC) ,opmode(0,1,OpArgR,OpArgR,iABC) ,opmode(0,0,OpArgR,OpArgN,iAsBx) ,opmode(1,0,OpArgK,OpArgK,iABC) ,opmode(1,0,OpArgK,OpArgK,iABC) ,opmode(1,0,OpArgK,OpArgK,iABC) ,opmode(1,1,OpArgR,OpArgU,iABC) ,opmode(1,1,OpArgR,OpArgU,iABC) ,opmode(0,1,OpArgU,OpArgU,iABC) ,opmode(0,1,OpArgU,OpArgU,iABC) ,opmode(0,0,OpArgU,OpArgN,iABC) ,opmode(0,1,OpArgR,OpArgN,iAsBx) ,opmode(0,1,OpArgR,OpArgN,iAsBx) ,opmode(1,0,OpArgN,OpArgU,iABC) ,opmode(0,0,OpArgU,OpArgU,iABC) ,opmode(0,0,OpArgN,OpArgN,iABC) ,opmode(0,1,OpArgU,OpArgN,iABx) ,opmode(0,1,OpArgU,OpArgN,iABC) }; #define next(ls)(ls->current=zgetc(ls->z)) #define currIsNewline(ls)(ls->current=='\n'||ls->current=='\r') static const char*const luaX_tokens[]={ "and","break","do","else","elseif", "end","false","for","function","if", "in","local","nil","not","or","repeat", "return","then","true","until","while", "..","...","==",">=","<=","~=", "<number>","<name>","<string>","<eof>", NULL }; #define save_and_next(ls)(save(ls,ls->current),next(ls)) static void save(LexState*ls,int c){ Mbuffer*b=ls->buff; if(b->n+1>b->buffsize){ size_t newsize; if(b->buffsize>=((size_t)(~(size_t)0)-2)/2) luaX_lexerror(ls,"lexical element too long",0); newsize=b->buffsize*2; luaZ_resizebuffer(ls->L,b,newsize); } b->buffer[b->n++]=cast(char,c); } static void luaX_init(lua_State*L){ int i; for(i=0;i<(cast(int,TK_WHILE-257+1));i++){ TString*ts=luaS_new(L,luaX_tokens[i]); luaS_fix(ts); ts->tsv.reserved=cast_byte(i+1); } } static const char*luaX_token2str(LexState*ls,int token){ if(token<257){ return(iscntrl(token))?luaO_pushfstring(ls->L,"char(%d)",token): luaO_pushfstring(ls->L,"%c",token); } else return luaX_tokens[token-257]; } static const char*txtToken(LexState*ls,int token){ switch(token){ case TK_NAME: case TK_STRING: case TK_NUMBER: save(ls,'\0'); return luaZ_buffer(ls->buff); default: return luaX_token2str(ls,token); } } static void luaX_lexerror(LexState*ls,const char*msg,int token){ char buff[80]; luaO_chunkid(buff,getstr(ls->source),80); msg=luaO_pushfstring(ls->L,"%s:%d: %s",buff,ls->linenumber,msg); if(token) luaO_pushfstring(ls->L,"%s near "LUA_QL("%s"),msg,txtToken(ls,token)); luaD_throw(ls->L,3); } static void luaX_syntaxerror(LexState*ls,const char*msg){ luaX_lexerror(ls,msg,ls->t.token); } static TString*luaX_newstring(LexState*ls,const char*str,size_t l){ lua_State*L=ls->L; TString*ts=luaS_newlstr(L,str,l); TValue*o=luaH_setstr(L,ls->fs->h,ts); if(ttisnil(o)){ setbvalue(o,1); luaC_checkGC(L); } return ts; } static void inclinenumber(LexState*ls){ int old=ls->current; next(ls); if(currIsNewline(ls)&&ls->current!=old) next(ls); if(++ls->linenumber>=(INT_MAX-2)) luaX_syntaxerror(ls,"chunk has too many lines"); } static void luaX_setinput(lua_State*L,LexState*ls,ZIO*z,TString*source){ ls->decpoint='.'; ls->L=L; ls->lookahead.token=TK_EOS; ls->z=z; ls->fs=NULL; ls->linenumber=1; ls->lastline=1; ls->source=source; luaZ_resizebuffer(ls->L,ls->buff,32); next(ls); } static int check_next(LexState*ls,const char*set){ if(!strchr(set,ls->current)) return 0; save_and_next(ls); return 1; } static void buffreplace(LexState*ls,char from,char to){ size_t n=luaZ_bufflen(ls->buff); char*p=luaZ_buffer(ls->buff); while(n--) if(p[n]==from)p[n]=to; } static void read_numeral(LexState*ls,SemInfo*seminfo){ do{ save_and_next(ls); }while(isdigit(ls->current)||ls->current=='.'); if(check_next(ls,"Ee")) check_next(ls,"+-"); while(isalnum(ls->current)||ls->current=='_') save_and_next(ls); save(ls,'\0'); buffreplace(ls,'.',ls->decpoint); if(!luaO_str2d(luaZ_buffer(ls->buff),&seminfo->r)) luaX_lexerror(ls,"malformed number",TK_NUMBER); } static int skip_sep(LexState*ls){ int count=0; int s=ls->current; save_and_next(ls); while(ls->current=='='){ save_and_next(ls); count++; } return(ls->current==s)?count:(-count)-1; } static void read_long_string(LexState*ls,SemInfo*seminfo,int sep){ int cont=0; (void)(cont); save_and_next(ls); if(currIsNewline(ls)) inclinenumber(ls); for(;;){ switch(ls->current){ case(-1): luaX_lexerror(ls,(seminfo)?"unfinished long string": "unfinished long comment",TK_EOS); break; case']':{ if(skip_sep(ls)==sep){ save_and_next(ls); goto endloop; } break; } case'\n': case'\r':{ save(ls,'\n'); inclinenumber(ls); if(!seminfo)luaZ_resetbuffer(ls->buff); break; } default:{ if(seminfo)save_and_next(ls); else next(ls); } } }endloop: if(seminfo) seminfo->ts=luaX_newstring(ls,luaZ_buffer(ls->buff)+(2+sep), luaZ_bufflen(ls->buff)-2*(2+sep)); } static void read_string(LexState*ls,int del,SemInfo*seminfo){ save_and_next(ls); while(ls->current!=del){ switch(ls->current){ case(-1): luaX_lexerror(ls,"unfinished string",TK_EOS); continue; case'\n': case'\r': luaX_lexerror(ls,"unfinished string",TK_STRING); continue; case'\\':{ int c; next(ls); switch(ls->current){ case'a':c='\a';break; case'b':c='\b';break; case'f':c='\f';break; case'n':c='\n';break; case'r':c='\r';break; case't':c='\t';break; case'v':c='\v';break; case'\n': case'\r':save(ls,'\n');inclinenumber(ls);continue; case(-1):continue; default:{ if(!isdigit(ls->current)) save_and_next(ls); else{ int i=0; c=0; do{ c=10*c+(ls->current-'0'); next(ls); }while(++i<3&&isdigit(ls->current)); if(c>UCHAR_MAX) luaX_lexerror(ls,"escape sequence too large",TK_STRING); save(ls,c); } continue; } } save(ls,c); next(ls); continue; } default: save_and_next(ls); } } save_and_next(ls); seminfo->ts=luaX_newstring(ls,luaZ_buffer(ls->buff)+1, luaZ_bufflen(ls->buff)-2); } static int llex(LexState*ls,SemInfo*seminfo){ luaZ_resetbuffer(ls->buff); for(;;){ switch(ls->current){ case'\n': case'\r':{ inclinenumber(ls); continue; } case'-':{ next(ls); if(ls->current!='-')return'-'; next(ls); if(ls->current=='['){ int sep=skip_sep(ls); luaZ_resetbuffer(ls->buff); if(sep>=0){ read_long_string(ls,NULL,sep); luaZ_resetbuffer(ls->buff); continue; } } while(!currIsNewline(ls)&&ls->current!=(-1)) next(ls); continue; } case'[':{ int sep=skip_sep(ls); if(sep>=0){ read_long_string(ls,seminfo,sep); return TK_STRING; } else if(sep==-1)return'['; else luaX_lexerror(ls,"invalid long string delimiter",TK_STRING); } case'=':{ next(ls); if(ls->current!='=')return'='; else{next(ls);return TK_EQ;} } case'<':{ next(ls); if(ls->current!='=')return'<'; else{next(ls);return TK_LE;} } case'>':{ next(ls); if(ls->current!='=')return'>'; else{next(ls);return TK_GE;} } case'~':{ next(ls); if(ls->current!='=')return'~'; else{next(ls);return TK_NE;} } case'"': case'\'':{ read_string(ls,ls->current,seminfo); return TK_STRING; } case'.':{ save_and_next(ls); if(check_next(ls,".")){ if(check_next(ls,".")) return TK_DOTS; else return TK_CONCAT; } else if(!isdigit(ls->current))return'.'; else{ read_numeral(ls,seminfo); return TK_NUMBER; } } case(-1):{ return TK_EOS; } default:{ if(isspace(ls->current)){ next(ls); continue; } else if(isdigit(ls->current)){ read_numeral(ls,seminfo); return TK_NUMBER; } else if(isalpha(ls->current)||ls->current=='_'){ TString*ts; do{ save_and_next(ls); }while(isalnum(ls->current)||ls->current=='_'); ts=luaX_newstring(ls,luaZ_buffer(ls->buff), luaZ_bufflen(ls->buff)); if(ts->tsv.reserved>0) return ts->tsv.reserved-1+257; else{ seminfo->ts=ts; return TK_NAME; } } else{ int c=ls->current; next(ls); return c; } } } } } static void luaX_next(LexState*ls){ ls->lastline=ls->linenumber; if(ls->lookahead.token!=TK_EOS){ ls->t=ls->lookahead; ls->lookahead.token=TK_EOS; } else ls->t.token=llex(ls,&ls->t.seminfo); } static void luaX_lookahead(LexState*ls){ ls->lookahead.token=llex(ls,&ls->lookahead.seminfo); } #define hasjumps(e)((e)->t!=(e)->f) static int isnumeral(expdesc*e){ return(e->k==VKNUM&&e->t==(-1)&&e->f==(-1)); } static void luaK_nil(FuncState*fs,int from,int n){ Instruction*previous; if(fs->pc>fs->lasttarget){ if(fs->pc==0){ if(from>=fs->nactvar) return; } else{ previous=&fs->f->code[fs->pc-1]; if(GET_OPCODE(*previous)==OP_LOADNIL){ int pfrom=GETARG_A(*previous); int pto=GETARG_B(*previous); if(pfrom<=from&&from<=pto+1){ if(from+n-1>pto) SETARG_B(*previous,from+n-1); return; } } } } luaK_codeABC(fs,OP_LOADNIL,from,from+n-1,0); } static int luaK_jump(FuncState*fs){ int jpc=fs->jpc; int j; fs->jpc=(-1); j=luaK_codeAsBx(fs,OP_JMP,0,(-1)); luaK_concat(fs,&j,jpc); return j; } static void luaK_ret(FuncState*fs,int first,int nret){ luaK_codeABC(fs,OP_RETURN,first,nret+1,0); } static int condjump(FuncState*fs,OpCode op,int A,int B,int C){ luaK_codeABC(fs,op,A,B,C); return luaK_jump(fs); } static void fixjump(FuncState*fs,int pc,int dest){ Instruction*jmp=&fs->f->code[pc]; int offset=dest-(pc+1); if(abs(offset)>(((1<<(9+9))-1)>>1)) luaX_syntaxerror(fs->ls,"control structure too long"); SETARG_sBx(*jmp,offset); } static int luaK_getlabel(FuncState*fs){ fs->lasttarget=fs->pc; return fs->pc; } static int getjump(FuncState*fs,int pc){ int offset=GETARG_sBx(fs->f->code[pc]); if(offset==(-1)) return(-1); else return(pc+1)+offset; } static Instruction*getjumpcontrol(FuncState*fs,int pc){ Instruction*pi=&fs->f->code[pc]; if(pc>=1&&testTMode(GET_OPCODE(*(pi-1)))) return pi-1; else return pi; } static int need_value(FuncState*fs,int list){ for(;list!=(-1);list=getjump(fs,list)){ Instruction i=*getjumpcontrol(fs,list); if(GET_OPCODE(i)!=OP_TESTSET)return 1; } return 0; } static int patchtestreg(FuncState*fs,int node,int reg){ Instruction*i=getjumpcontrol(fs,node); if(GET_OPCODE(*i)!=OP_TESTSET) return 0; if(reg!=((1<<8)-1)&&reg!=GETARG_B(*i)) SETARG_A(*i,reg); else *i=CREATE_ABC(OP_TEST,GETARG_B(*i),0,GETARG_C(*i)); return 1; } static void removevalues(FuncState*fs,int list){ for(;list!=(-1);list=getjump(fs,list)) patchtestreg(fs,list,((1<<8)-1)); } static void patchlistaux(FuncState*fs,int list,int vtarget,int reg, int dtarget){ while(list!=(-1)){ int next=getjump(fs,list); if(patchtestreg(fs,list,reg)) fixjump(fs,list,vtarget); else fixjump(fs,list,dtarget); list=next; } } static void dischargejpc(FuncState*fs){ patchlistaux(fs,fs->jpc,fs->pc,((1<<8)-1),fs->pc); fs->jpc=(-1); } static void luaK_patchlist(FuncState*fs,int list,int target){ if(target==fs->pc) luaK_patchtohere(fs,list); else{ patchlistaux(fs,list,target,((1<<8)-1),target); } } static void luaK_patchtohere(FuncState*fs,int list){ luaK_getlabel(fs); luaK_concat(fs,&fs->jpc,list); } static void luaK_concat(FuncState*fs,int*l1,int l2){ if(l2==(-1))return; else if(*l1==(-1)) *l1=l2; else{ int list=*l1; int next; while((next=getjump(fs,list))!=(-1)) list=next; fixjump(fs,list,l2); } } static void luaK_checkstack(FuncState*fs,int n){ int newstack=fs->freereg+n; if(newstack>fs->f->maxstacksize){ if(newstack>=250) luaX_syntaxerror(fs->ls,"function or expression too complex"); fs->f->maxstacksize=cast_byte(newstack); } } static void luaK_reserveregs(FuncState*fs,int n){ luaK_checkstack(fs,n); fs->freereg+=n; } static void freereg(FuncState*fs,int reg){ if(!ISK(reg)&&reg>=fs->nactvar){ fs->freereg--; } } static void freeexp(FuncState*fs,expdesc*e){ if(e->k==VNONRELOC) freereg(fs,e->u.s.info); } static int addk(FuncState*fs,TValue*k,TValue*v){ lua_State*L=fs->L; TValue*idx=luaH_set(L,fs->h,k); Proto*f=fs->f; int oldsize=f->sizek; if(ttisnumber(idx)){ return cast_int(nvalue(idx)); } else{ setnvalue(idx,cast_num(fs->nk)); luaM_growvector(L,f->k,fs->nk,f->sizek,TValue, ((1<<(9+9))-1),"constant table overflow"); while(oldsize<f->sizek)setnilvalue(&f->k[oldsize++]); setobj(L,&f->k[fs->nk],v); luaC_barrier(L,f,v); return fs->nk++; } } static int luaK_stringK(FuncState*fs,TString*s){ TValue o; setsvalue(fs->L,&o,s); return addk(fs,&o,&o); } static int luaK_numberK(FuncState*fs,lua_Number r){ TValue o; setnvalue(&o,r); return addk(fs,&o,&o); } static int boolK(FuncState*fs,int b){ TValue o; setbvalue(&o,b); return addk(fs,&o,&o); } static int nilK(FuncState*fs){ TValue k,v; setnilvalue(&v); sethvalue(fs->L,&k,fs->h); return addk(fs,&k,&v); } static void luaK_setreturns(FuncState*fs,expdesc*e,int nresults){ if(e->k==VCALL){ SETARG_C(getcode(fs,e),nresults+1); } else if(e->k==VVARARG){ SETARG_B(getcode(fs,e),nresults+1); SETARG_A(getcode(fs,e),fs->freereg); luaK_reserveregs(fs,1); } } static void luaK_setoneret(FuncState*fs,expdesc*e){ if(e->k==VCALL){ e->k=VNONRELOC; e->u.s.info=GETARG_A(getcode(fs,e)); } else if(e->k==VVARARG){ SETARG_B(getcode(fs,e),2); e->k=VRELOCABLE; } } static void luaK_dischargevars(FuncState*fs,expdesc*e){ switch(e->k){ case VLOCAL:{ e->k=VNONRELOC; break; } case VUPVAL:{ e->u.s.info=luaK_codeABC(fs,OP_GETUPVAL,0,e->u.s.info,0); e->k=VRELOCABLE; break; } case VGLOBAL:{ e->u.s.info=luaK_codeABx(fs,OP_GETGLOBAL,0,e->u.s.info); e->k=VRELOCABLE; break; } case VINDEXED:{ freereg(fs,e->u.s.aux); freereg(fs,e->u.s.info); e->u.s.info=luaK_codeABC(fs,OP_GETTABLE,0,e->u.s.info,e->u.s.aux); e->k=VRELOCABLE; break; } case VVARARG: case VCALL:{ luaK_setoneret(fs,e); break; } default:break; } } static int code_label(FuncState*fs,int A,int b,int jump){ luaK_getlabel(fs); return luaK_codeABC(fs,OP_LOADBOOL,A,b,jump); } static void discharge2reg(FuncState*fs,expdesc*e,int reg){ luaK_dischargevars(fs,e); switch(e->k){ case VNIL:{ luaK_nil(fs,reg,1); break; } case VFALSE:case VTRUE:{ luaK_codeABC(fs,OP_LOADBOOL,reg,e->k==VTRUE,0); break; } case VK:{ luaK_codeABx(fs,OP_LOADK,reg,e->u.s.info); break; } case VKNUM:{ luaK_codeABx(fs,OP_LOADK,reg,luaK_numberK(fs,e->u.nval)); break; } case VRELOCABLE:{ Instruction*pc=&getcode(fs,e); SETARG_A(*pc,reg); break; } case VNONRELOC:{ if(reg!=e->u.s.info) luaK_codeABC(fs,OP_MOVE,reg,e->u.s.info,0); break; } default:{ return; } } e->u.s.info=reg; e->k=VNONRELOC; } static void discharge2anyreg(FuncState*fs,expdesc*e){ if(e->k!=VNONRELOC){ luaK_reserveregs(fs,1); discharge2reg(fs,e,fs->freereg-1); } } static void exp2reg(FuncState*fs,expdesc*e,int reg){ discharge2reg(fs,e,reg); if(e->k==VJMP) luaK_concat(fs,&e->t,e->u.s.info); if(hasjumps(e)){ int final; int p_f=(-1); int p_t=(-1); if(need_value(fs,e->t)||need_value(fs,e->f)){ int fj=(e->k==VJMP)?(-1):luaK_jump(fs); p_f=code_label(fs,reg,0,1); p_t=code_label(fs,reg,1,0); luaK_patchtohere(fs,fj); } final=luaK_getlabel(fs); patchlistaux(fs,e->f,final,reg,p_f); patchlistaux(fs,e->t,final,reg,p_t); } e->f=e->t=(-1); e->u.s.info=reg; e->k=VNONRELOC; } static void luaK_exp2nextreg(FuncState*fs,expdesc*e){ luaK_dischargevars(fs,e); freeexp(fs,e); luaK_reserveregs(fs,1); exp2reg(fs,e,fs->freereg-1); } static int luaK_exp2anyreg(FuncState*fs,expdesc*e){ luaK_dischargevars(fs,e); if(e->k==VNONRELOC){ if(!hasjumps(e))return e->u.s.info; if(e->u.s.info>=fs->nactvar){ exp2reg(fs,e,e->u.s.info); return e->u.s.info; } } luaK_exp2nextreg(fs,e); return e->u.s.info; } static void luaK_exp2val(FuncState*fs,expdesc*e){ if(hasjumps(e)) luaK_exp2anyreg(fs,e); else luaK_dischargevars(fs,e); } static int luaK_exp2RK(FuncState*fs,expdesc*e){ luaK_exp2val(fs,e); switch(e->k){ case VKNUM: case VTRUE: case VFALSE: case VNIL:{ if(fs->nk<=((1<<(9-1))-1)){ e->u.s.info=(e->k==VNIL)?nilK(fs): (e->k==VKNUM)?luaK_numberK(fs,e->u.nval): boolK(fs,(e->k==VTRUE)); e->k=VK; return RKASK(e->u.s.info); } else break; } case VK:{ if(e->u.s.info<=((1<<(9-1))-1)) return RKASK(e->u.s.info); else break; } default:break; } return luaK_exp2anyreg(fs,e); } static void luaK_storevar(FuncState*fs,expdesc*var,expdesc*ex){ switch(var->k){ case VLOCAL:{ freeexp(fs,ex); exp2reg(fs,ex,var->u.s.info); return; } case VUPVAL:{ int e=luaK_exp2anyreg(fs,ex); luaK_codeABC(fs,OP_SETUPVAL,e,var->u.s.info,0); break; } case VGLOBAL:{ int e=luaK_exp2anyreg(fs,ex); luaK_codeABx(fs,OP_SETGLOBAL,e,var->u.s.info); break; } case VINDEXED:{ int e=luaK_exp2RK(fs,ex); luaK_codeABC(fs,OP_SETTABLE,var->u.s.info,var->u.s.aux,e); break; } default:{ break; } } freeexp(fs,ex); } static void luaK_self(FuncState*fs,expdesc*e,expdesc*key){ int func; luaK_exp2anyreg(fs,e); freeexp(fs,e); func=fs->freereg; luaK_reserveregs(fs,2); luaK_codeABC(fs,OP_SELF,func,e->u.s.info,luaK_exp2RK(fs,key)); freeexp(fs,key); e->u.s.info=func; e->k=VNONRELOC; } static void invertjump(FuncState*fs,expdesc*e){ Instruction*pc=getjumpcontrol(fs,e->u.s.info); SETARG_A(*pc,!(GETARG_A(*pc))); } static int jumponcond(FuncState*fs,expdesc*e,int cond){ if(e->k==VRELOCABLE){ Instruction ie=getcode(fs,e); if(GET_OPCODE(ie)==OP_NOT){ fs->pc--; return condjump(fs,OP_TEST,GETARG_B(ie),0,!cond); } } discharge2anyreg(fs,e); freeexp(fs,e); return condjump(fs,OP_TESTSET,((1<<8)-1),e->u.s.info,cond); } static void luaK_goiftrue(FuncState*fs,expdesc*e){ int pc; luaK_dischargevars(fs,e); switch(e->k){ case VK:case VKNUM:case VTRUE:{ pc=(-1); break; } case VJMP:{ invertjump(fs,e); pc=e->u.s.info; break; } default:{ pc=jumponcond(fs,e,0); break; } } luaK_concat(fs,&e->f,pc); luaK_patchtohere(fs,e->t); e->t=(-1); } static void luaK_goiffalse(FuncState*fs,expdesc*e){ int pc; luaK_dischargevars(fs,e); switch(e->k){ case VNIL:case VFALSE:{ pc=(-1); break; } case VJMP:{ pc=e->u.s.info; break; } default:{ pc=jumponcond(fs,e,1); break; } } luaK_concat(fs,&e->t,pc); luaK_patchtohere(fs,e->f); e->f=(-1); } static void codenot(FuncState*fs,expdesc*e){ luaK_dischargevars(fs,e); switch(e->k){ case VNIL:case VFALSE:{ e->k=VTRUE; break; } case VK:case VKNUM:case VTRUE:{ e->k=VFALSE; break; } case VJMP:{ invertjump(fs,e); break; } case VRELOCABLE: case VNONRELOC:{ discharge2anyreg(fs,e); freeexp(fs,e); e->u.s.info=luaK_codeABC(fs,OP_NOT,0,e->u.s.info,0); e->k=VRELOCABLE; break; } default:{ break; } } {int temp=e->f;e->f=e->t;e->t=temp;} removevalues(fs,e->f); removevalues(fs,e->t); } static void luaK_indexed(FuncState*fs,expdesc*t,expdesc*k){ t->u.s.aux=luaK_exp2RK(fs,k); t->k=VINDEXED; } static int constfolding(OpCode op,expdesc*e1,expdesc*e2){ lua_Number v1,v2,r; if(!isnumeral(e1)||!isnumeral(e2))return 0; v1=e1->u.nval; v2=e2->u.nval; switch(op){ case OP_ADD:r=luai_numadd(v1,v2);break; case OP_SUB:r=luai_numsub(v1,v2);break; case OP_MUL:r=luai_nummul(v1,v2);break; case OP_DIV: if(v2==0)return 0; r=luai_numdiv(v1,v2);break; case OP_MOD: if(v2==0)return 0; r=luai_nummod(v1,v2);break; case OP_POW:r=luai_numpow(v1,v2);break; case OP_UNM:r=luai_numunm(v1);break; case OP_LEN:return 0; default:r=0;break; } if(luai_numisnan(r))return 0; e1->u.nval=r; return 1; } static void codearith(FuncState*fs,OpCode op,expdesc*e1,expdesc*e2){ if(constfolding(op,e1,e2)) return; else{ int o2=(op!=OP_UNM&&op!=OP_LEN)?luaK_exp2RK(fs,e2):0; int o1=luaK_exp2RK(fs,e1); if(o1>o2){ freeexp(fs,e1); freeexp(fs,e2); } else{ freeexp(fs,e2); freeexp(fs,e1); } e1->u.s.info=luaK_codeABC(fs,op,0,o1,o2); e1->k=VRELOCABLE; } } static void codecomp(FuncState*fs,OpCode op,int cond,expdesc*e1, expdesc*e2){ int o1=luaK_exp2RK(fs,e1); int o2=luaK_exp2RK(fs,e2); freeexp(fs,e2); freeexp(fs,e1); if(cond==0&&op!=OP_EQ){ int temp; temp=o1;o1=o2;o2=temp; cond=1; } e1->u.s.info=condjump(fs,op,cond,o1,o2); e1->k=VJMP; } static void luaK_prefix(FuncState*fs,UnOpr op,expdesc*e){ expdesc e2; e2.t=e2.f=(-1);e2.k=VKNUM;e2.u.nval=0; switch(op){ case OPR_MINUS:{ if(!isnumeral(e)) luaK_exp2anyreg(fs,e); codearith(fs,OP_UNM,e,&e2); break; } case OPR_NOT:codenot(fs,e);break; case OPR_LEN:{ luaK_exp2anyreg(fs,e); codearith(fs,OP_LEN,e,&e2); break; } default:; } } static void luaK_infix(FuncState*fs,BinOpr op,expdesc*v){ switch(op){ case OPR_AND:{ luaK_goiftrue(fs,v); break; } case OPR_OR:{ luaK_goiffalse(fs,v); break; } case OPR_CONCAT:{ luaK_exp2nextreg(fs,v); break; } case OPR_ADD:case OPR_SUB:case OPR_MUL:case OPR_DIV: case OPR_MOD:case OPR_POW:{ if(!isnumeral(v))luaK_exp2RK(fs,v); break; } default:{ luaK_exp2RK(fs,v); break; } } } static void luaK_posfix(FuncState*fs,BinOpr op,expdesc*e1,expdesc*e2){ switch(op){ case OPR_AND:{ luaK_dischargevars(fs,e2); luaK_concat(fs,&e2->f,e1->f); *e1=*e2; break; } case OPR_OR:{ luaK_dischargevars(fs,e2); luaK_concat(fs,&e2->t,e1->t); *e1=*e2; break; } case OPR_CONCAT:{ luaK_exp2val(fs,e2); if(e2->k==VRELOCABLE&&GET_OPCODE(getcode(fs,e2))==OP_CONCAT){ freeexp(fs,e1); SETARG_B(getcode(fs,e2),e1->u.s.info); e1->k=VRELOCABLE;e1->u.s.info=e2->u.s.info; } else{ luaK_exp2nextreg(fs,e2); codearith(fs,OP_CONCAT,e1,e2); } break; } case OPR_ADD:codearith(fs,OP_ADD,e1,e2);break; case OPR_SUB:codearith(fs,OP_SUB,e1,e2);break; case OPR_MUL:codearith(fs,OP_MUL,e1,e2);break; case OPR_DIV:codearith(fs,OP_DIV,e1,e2);break; case OPR_MOD:codearith(fs,OP_MOD,e1,e2);break; case OPR_POW:codearith(fs,OP_POW,e1,e2);break; case OPR_EQ:codecomp(fs,OP_EQ,1,e1,e2);break; case OPR_NE:codecomp(fs,OP_EQ,0,e1,e2);break; case OPR_LT:codecomp(fs,OP_LT,1,e1,e2);break; case OPR_LE:codecomp(fs,OP_LE,1,e1,e2);break; case OPR_GT:codecomp(fs,OP_LT,0,e1,e2);break; case OPR_GE:codecomp(fs,OP_LE,0,e1,e2);break; default:; } } static void luaK_fixline(FuncState*fs,int line){ fs->f->lineinfo[fs->pc-1]=line; } static int luaK_code(FuncState*fs,Instruction i,int line){ Proto*f=fs->f; dischargejpc(fs); luaM_growvector(fs->L,f->code,fs->pc,f->sizecode,Instruction, (INT_MAX-2),"code size overflow"); f->code[fs->pc]=i; luaM_growvector(fs->L,f->lineinfo,fs->pc,f->sizelineinfo,int, (INT_MAX-2),"code size overflow"); f->lineinfo[fs->pc]=line; return fs->pc++; } static int luaK_codeABC(FuncState*fs,OpCode o,int a,int b,int c){ return luaK_code(fs,CREATE_ABC(o,a,b,c),fs->ls->lastline); } static int luaK_codeABx(FuncState*fs,OpCode o,int a,unsigned int bc){ return luaK_code(fs,CREATE_ABx(o,a,bc),fs->ls->lastline); } static void luaK_setlist(FuncState*fs,int base,int nelems,int tostore){ int c=(nelems-1)/50+1; int b=(tostore==(-1))?0:tostore; if(c<=((1<<9)-1)) luaK_codeABC(fs,OP_SETLIST,base,b,c); else{ luaK_codeABC(fs,OP_SETLIST,base,b,0); luaK_code(fs,cast(Instruction,c),fs->ls->lastline); } fs->freereg=base+1; } #define hasmultret(k)((k)==VCALL||(k)==VVARARG) #define getlocvar(fs,i)((fs)->f->locvars[(fs)->actvar[i]]) #define luaY_checklimit(fs,v,l,m)if((v)>(l))errorlimit(fs,l,m) typedef struct BlockCnt{ struct BlockCnt*previous; int breaklist; lu_byte nactvar; lu_byte upval; lu_byte isbreakable; }BlockCnt; static void chunk(LexState*ls); static void expr(LexState*ls,expdesc*v); static void anchor_token(LexState*ls){ if(ls->t.token==TK_NAME||ls->t.token==TK_STRING){ TString*ts=ls->t.seminfo.ts; luaX_newstring(ls,getstr(ts),ts->tsv.len); } } static void error_expected(LexState*ls,int token){ luaX_syntaxerror(ls, luaO_pushfstring(ls->L,LUA_QL("%s")" expected",luaX_token2str(ls,token))); } static void errorlimit(FuncState*fs,int limit,const char*what){ const char*msg=(fs->f->linedefined==0)? luaO_pushfstring(fs->L,"main function has more than %d %s",limit,what): luaO_pushfstring(fs->L,"function at line %d has more than %d %s", fs->f->linedefined,limit,what); luaX_lexerror(fs->ls,msg,0); } static int testnext(LexState*ls,int c){ if(ls->t.token==c){ luaX_next(ls); return 1; } else return 0; } static void check(LexState*ls,int c){ if(ls->t.token!=c) error_expected(ls,c); } static void checknext(LexState*ls,int c){ check(ls,c); luaX_next(ls); } #define check_condition(ls,c,msg){if(!(c))luaX_syntaxerror(ls,msg);} static void check_match(LexState*ls,int what,int who,int where){ if(!testnext(ls,what)){ if(where==ls->linenumber) error_expected(ls,what); else{ luaX_syntaxerror(ls,luaO_pushfstring(ls->L, LUA_QL("%s")" expected (to close "LUA_QL("%s")" at line %d)", luaX_token2str(ls,what),luaX_token2str(ls,who),where)); } } } static TString*str_checkname(LexState*ls){ TString*ts; check(ls,TK_NAME); ts=ls->t.seminfo.ts; luaX_next(ls); return ts; } static void init_exp(expdesc*e,expkind k,int i){ e->f=e->t=(-1); e->k=k; e->u.s.info=i; } static void codestring(LexState*ls,expdesc*e,TString*s){ init_exp(e,VK,luaK_stringK(ls->fs,s)); } static void checkname(LexState*ls,expdesc*e){ codestring(ls,e,str_checkname(ls)); } static int registerlocalvar(LexState*ls,TString*varname){ FuncState*fs=ls->fs; Proto*f=fs->f; int oldsize=f->sizelocvars; luaM_growvector(ls->L,f->locvars,fs->nlocvars,f->sizelocvars, LocVar,SHRT_MAX,"too many local variables"); while(oldsize<f->sizelocvars)f->locvars[oldsize++].varname=NULL; f->locvars[fs->nlocvars].varname=varname; luaC_objbarrier(ls->L,f,varname); return fs->nlocvars++; } #define new_localvarliteral(ls,v,n)new_localvar(ls,luaX_newstring(ls,""v,(sizeof(v)/sizeof(char))-1),n) static void new_localvar(LexState*ls,TString*name,int n){ FuncState*fs=ls->fs; luaY_checklimit(fs,fs->nactvar+n+1,200,"local variables"); fs->actvar[fs->nactvar+n]=cast(unsigned short,registerlocalvar(ls,name)); } static void adjustlocalvars(LexState*ls,int nvars){ FuncState*fs=ls->fs; fs->nactvar=cast_byte(fs->nactvar+nvars); for(;nvars;nvars--){ getlocvar(fs,fs->nactvar-nvars).startpc=fs->pc; } } static void removevars(LexState*ls,int tolevel){ FuncState*fs=ls->fs; while(fs->nactvar>tolevel) getlocvar(fs,--fs->nactvar).endpc=fs->pc; } static int indexupvalue(FuncState*fs,TString*name,expdesc*v){ int i; Proto*f=fs->f; int oldsize=f->sizeupvalues; for(i=0;i<f->nups;i++){ if(fs->upvalues[i].k==v->k&&fs->upvalues[i].info==v->u.s.info){ return i; } } luaY_checklimit(fs,f->nups+1,60,"upvalues"); luaM_growvector(fs->L,f->upvalues,f->nups,f->sizeupvalues, TString*,(INT_MAX-2),""); while(oldsize<f->sizeupvalues)f->upvalues[oldsize++]=NULL; f->upvalues[f->nups]=name; luaC_objbarrier(fs->L,f,name); fs->upvalues[f->nups].k=cast_byte(v->k); fs->upvalues[f->nups].info=cast_byte(v->u.s.info); return f->nups++; } static int searchvar(FuncState*fs,TString*n){ int i; for(i=fs->nactvar-1;i>=0;i--){ if(n==getlocvar(fs,i).varname) return i; } return-1; } static void markupval(FuncState*fs,int level){ BlockCnt*bl=fs->bl; while(bl&&bl->nactvar>level)bl=bl->previous; if(bl)bl->upval=1; } static int singlevaraux(FuncState*fs,TString*n,expdesc*var,int base){ if(fs==NULL){ init_exp(var,VGLOBAL,((1<<8)-1)); return VGLOBAL; } else{ int v=searchvar(fs,n); if(v>=0){ init_exp(var,VLOCAL,v); if(!base) markupval(fs,v); return VLOCAL; } else{ if(singlevaraux(fs->prev,n,var,0)==VGLOBAL) return VGLOBAL; var->u.s.info=indexupvalue(fs,n,var); var->k=VUPVAL; return VUPVAL; } } } static void singlevar(LexState*ls,expdesc*var){ TString*varname=str_checkname(ls); FuncState*fs=ls->fs; if(singlevaraux(fs,varname,var,1)==VGLOBAL) var->u.s.info=luaK_stringK(fs,varname); } static void adjust_assign(LexState*ls,int nvars,int nexps,expdesc*e){ FuncState*fs=ls->fs; int extra=nvars-nexps; if(hasmultret(e->k)){ extra++; if(extra<0)extra=0; luaK_setreturns(fs,e,extra); if(extra>1)luaK_reserveregs(fs,extra-1); } else{ if(e->k!=VVOID)luaK_exp2nextreg(fs,e); if(extra>0){ int reg=fs->freereg; luaK_reserveregs(fs,extra); luaK_nil(fs,reg,extra); } } } static void enterlevel(LexState*ls){ if(++ls->L->nCcalls>200) luaX_lexerror(ls,"chunk has too many syntax levels",0); } #define leavelevel(ls)((ls)->L->nCcalls--) static void enterblock(FuncState*fs,BlockCnt*bl,lu_byte isbreakable){ bl->breaklist=(-1); bl->isbreakable=isbreakable; bl->nactvar=fs->nactvar; bl->upval=0; bl->previous=fs->bl; fs->bl=bl; } static void leaveblock(FuncState*fs){ BlockCnt*bl=fs->bl; fs->bl=bl->previous; removevars(fs->ls,bl->nactvar); if(bl->upval) luaK_codeABC(fs,OP_CLOSE,bl->nactvar,0,0); fs->freereg=fs->nactvar; luaK_patchtohere(fs,bl->breaklist); } static void pushclosure(LexState*ls,FuncState*func,expdesc*v){ FuncState*fs=ls->fs; Proto*f=fs->f; int oldsize=f->sizep; int i; luaM_growvector(ls->L,f->p,fs->np,f->sizep,Proto*, ((1<<(9+9))-1),"constant table overflow"); while(oldsize<f->sizep)f->p[oldsize++]=NULL; f->p[fs->np++]=func->f; luaC_objbarrier(ls->L,f,func->f); init_exp(v,VRELOCABLE,luaK_codeABx(fs,OP_CLOSURE,0,fs->np-1)); for(i=0;i<func->f->nups;i++){ OpCode o=(func->upvalues[i].k==VLOCAL)?OP_MOVE:OP_GETUPVAL; luaK_codeABC(fs,o,0,func->upvalues[i].info,0); } } static void open_func(LexState*ls,FuncState*fs){ lua_State*L=ls->L; Proto*f=luaF_newproto(L); fs->f=f; fs->prev=ls->fs; fs->ls=ls; fs->L=L; ls->fs=fs; fs->pc=0; fs->lasttarget=-1; fs->jpc=(-1); fs->freereg=0; fs->nk=0; fs->np=0; fs->nlocvars=0; fs->nactvar=0; fs->bl=NULL; f->source=ls->source; f->maxstacksize=2; fs->h=luaH_new(L,0,0); sethvalue(L,L->top,fs->h); incr_top(L); setptvalue(L,L->top,f); incr_top(L); } static void close_func(LexState*ls){ lua_State*L=ls->L; FuncState*fs=ls->fs; Proto*f=fs->f; removevars(ls,0); luaK_ret(fs,0,0); luaM_reallocvector(L,f->code,f->sizecode,fs->pc,Instruction); f->sizecode=fs->pc; luaM_reallocvector(L,f->lineinfo,f->sizelineinfo,fs->pc,int); f->sizelineinfo=fs->pc; luaM_reallocvector(L,f->k,f->sizek,fs->nk,TValue); f->sizek=fs->nk; luaM_reallocvector(L,f->p,f->sizep,fs->np,Proto*); f->sizep=fs->np; luaM_reallocvector(L,f->locvars,f->sizelocvars,fs->nlocvars,LocVar); f->sizelocvars=fs->nlocvars; luaM_reallocvector(L,f->upvalues,f->sizeupvalues,f->nups,TString*); f->sizeupvalues=f->nups; ls->fs=fs->prev; if(fs)anchor_token(ls); L->top-=2; } static Proto*luaY_parser(lua_State*L,ZIO*z,Mbuffer*buff,const char*name){ struct LexState lexstate; struct FuncState funcstate; lexstate.buff=buff; luaX_setinput(L,&lexstate,z,luaS_new(L,name)); open_func(&lexstate,&funcstate); funcstate.f->is_vararg=2; luaX_next(&lexstate); chunk(&lexstate); check(&lexstate,TK_EOS); close_func(&lexstate); return funcstate.f; } static void field(LexState*ls,expdesc*v){ FuncState*fs=ls->fs; expdesc key; luaK_exp2anyreg(fs,v); luaX_next(ls); checkname(ls,&key); luaK_indexed(fs,v,&key); } static void yindex(LexState*ls,expdesc*v){ luaX_next(ls); expr(ls,v); luaK_exp2val(ls->fs,v); checknext(ls,']'); } struct ConsControl{ expdesc v; expdesc*t; int nh; int na; int tostore; }; static void recfield(LexState*ls,struct ConsControl*cc){ FuncState*fs=ls->fs; int reg=ls->fs->freereg; expdesc key,val; int rkkey; if(ls->t.token==TK_NAME){ luaY_checklimit(fs,cc->nh,(INT_MAX-2),"items in a constructor"); checkname(ls,&key); } else yindex(ls,&key); cc->nh++; checknext(ls,'='); rkkey=luaK_exp2RK(fs,&key); expr(ls,&val); luaK_codeABC(fs,OP_SETTABLE,cc->t->u.s.info,rkkey,luaK_exp2RK(fs,&val)); fs->freereg=reg; } static void closelistfield(FuncState*fs,struct ConsControl*cc){ if(cc->v.k==VVOID)return; luaK_exp2nextreg(fs,&cc->v); cc->v.k=VVOID; if(cc->tostore==50){ luaK_setlist(fs,cc->t->u.s.info,cc->na,cc->tostore); cc->tostore=0; } } static void lastlistfield(FuncState*fs,struct ConsControl*cc){ if(cc->tostore==0)return; if(hasmultret(cc->v.k)){ luaK_setmultret(fs,&cc->v); luaK_setlist(fs,cc->t->u.s.info,cc->na,(-1)); cc->na--; } else{ if(cc->v.k!=VVOID) luaK_exp2nextreg(fs,&cc->v); luaK_setlist(fs,cc->t->u.s.info,cc->na,cc->tostore); } } static void listfield(LexState*ls,struct ConsControl*cc){ expr(ls,&cc->v); luaY_checklimit(ls->fs,cc->na,(INT_MAX-2),"items in a constructor"); cc->na++; cc->tostore++; } static void constructor(LexState*ls,expdesc*t){ FuncState*fs=ls->fs; int line=ls->linenumber; int pc=luaK_codeABC(fs,OP_NEWTABLE,0,0,0); struct ConsControl cc; cc.na=cc.nh=cc.tostore=0; cc.t=t; init_exp(t,VRELOCABLE,pc); init_exp(&cc.v,VVOID,0); luaK_exp2nextreg(ls->fs,t); checknext(ls,'{'); do{ if(ls->t.token=='}')break; closelistfield(fs,&cc); switch(ls->t.token){ case TK_NAME:{ luaX_lookahead(ls); if(ls->lookahead.token!='=') listfield(ls,&cc); else recfield(ls,&cc); break; } case'[':{ recfield(ls,&cc); break; } default:{ listfield(ls,&cc); break; } } }while(testnext(ls,',')||testnext(ls,';')); check_match(ls,'}','{',line); lastlistfield(fs,&cc); SETARG_B(fs->f->code[pc],luaO_int2fb(cc.na)); SETARG_C(fs->f->code[pc],luaO_int2fb(cc.nh)); } static void parlist(LexState*ls){ FuncState*fs=ls->fs; Proto*f=fs->f; int nparams=0; f->is_vararg=0; if(ls->t.token!=')'){ do{ switch(ls->t.token){ case TK_NAME:{ new_localvar(ls,str_checkname(ls),nparams++); break; } case TK_DOTS:{ luaX_next(ls); f->is_vararg|=2; break; } default:luaX_syntaxerror(ls,"<name> or "LUA_QL("...")" expected"); } }while(!f->is_vararg&&testnext(ls,',')); } adjustlocalvars(ls,nparams); f->numparams=cast_byte(fs->nactvar-(f->is_vararg&1)); luaK_reserveregs(fs,fs->nactvar); } static void body(LexState*ls,expdesc*e,int needself,int line){ FuncState new_fs; open_func(ls,&new_fs); new_fs.f->linedefined=line; checknext(ls,'('); if(needself){ new_localvarliteral(ls,"self",0); adjustlocalvars(ls,1); } parlist(ls); checknext(ls,')'); chunk(ls); new_fs.f->lastlinedefined=ls->linenumber; check_match(ls,TK_END,TK_FUNCTION,line); close_func(ls); pushclosure(ls,&new_fs,e); } static int explist1(LexState*ls,expdesc*v){ int n=1; expr(ls,v); while(testnext(ls,',')){ luaK_exp2nextreg(ls->fs,v); expr(ls,v); n++; } return n; } static void funcargs(LexState*ls,expdesc*f){ FuncState*fs=ls->fs; expdesc args; int base,nparams; int line=ls->linenumber; switch(ls->t.token){ case'(':{ if(line!=ls->lastline) luaX_syntaxerror(ls,"ambiguous syntax (function call x new statement)"); luaX_next(ls); if(ls->t.token==')') args.k=VVOID; else{ explist1(ls,&args); luaK_setmultret(fs,&args); } check_match(ls,')','(',line); break; } case'{':{ constructor(ls,&args); break; } case TK_STRING:{ codestring(ls,&args,ls->t.seminfo.ts); luaX_next(ls); break; } default:{ luaX_syntaxerror(ls,"function arguments expected"); return; } } base=f->u.s.info; if(hasmultret(args.k)) nparams=(-1); else{ if(args.k!=VVOID) luaK_exp2nextreg(fs,&args); nparams=fs->freereg-(base+1); } init_exp(f,VCALL,luaK_codeABC(fs,OP_CALL,base,nparams+1,2)); luaK_fixline(fs,line); fs->freereg=base+1; } static void prefixexp(LexState*ls,expdesc*v){ switch(ls->t.token){ case'(':{ int line=ls->linenumber; luaX_next(ls); expr(ls,v); check_match(ls,')','(',line); luaK_dischargevars(ls->fs,v); return; } case TK_NAME:{ singlevar(ls,v); return; } default:{ luaX_syntaxerror(ls,"unexpected symbol"); return; } } } static void primaryexp(LexState*ls,expdesc*v){ FuncState*fs=ls->fs; prefixexp(ls,v); for(;;){ switch(ls->t.token){ case'.':{ field(ls,v); break; } case'[':{ expdesc key; luaK_exp2anyreg(fs,v); yindex(ls,&key); luaK_indexed(fs,v,&key); break; } case':':{ expdesc key; luaX_next(ls); checkname(ls,&key); luaK_self(fs,v,&key); funcargs(ls,v); break; } case'(':case TK_STRING:case'{':{ luaK_exp2nextreg(fs,v); funcargs(ls,v); break; } default:return; } } } static void simpleexp(LexState*ls,expdesc*v){ switch(ls->t.token){ case TK_NUMBER:{ init_exp(v,VKNUM,0); v->u.nval=ls->t.seminfo.r; break; } case TK_STRING:{ codestring(ls,v,ls->t.seminfo.ts); break; } case TK_NIL:{ init_exp(v,VNIL,0); break; } case TK_TRUE:{ init_exp(v,VTRUE,0); break; } case TK_FALSE:{ init_exp(v,VFALSE,0); break; } case TK_DOTS:{ FuncState*fs=ls->fs; check_condition(ls,fs->f->is_vararg, "cannot use "LUA_QL("...")" outside a vararg function"); fs->f->is_vararg&=~4; init_exp(v,VVARARG,luaK_codeABC(fs,OP_VARARG,0,1,0)); break; } case'{':{ constructor(ls,v); return; } case TK_FUNCTION:{ luaX_next(ls); body(ls,v,0,ls->linenumber); return; } default:{ primaryexp(ls,v); return; } } luaX_next(ls); } static UnOpr getunopr(int op){ switch(op){ case TK_NOT:return OPR_NOT; case'-':return OPR_MINUS; case'#':return OPR_LEN; default:return OPR_NOUNOPR; } } static BinOpr getbinopr(int op){ switch(op){ case'+':return OPR_ADD; case'-':return OPR_SUB; case'*':return OPR_MUL; case'/':return OPR_DIV; case'%':return OPR_MOD; case'^':return OPR_POW; case TK_CONCAT:return OPR_CONCAT; case TK_NE:return OPR_NE; case TK_EQ:return OPR_EQ; case'<':return OPR_LT; case TK_LE:return OPR_LE; case'>':return OPR_GT; case TK_GE:return OPR_GE; case TK_AND:return OPR_AND; case TK_OR:return OPR_OR; default:return OPR_NOBINOPR; } } static const struct{ lu_byte left; lu_byte right; }priority[]={ {6,6},{6,6},{7,7},{7,7},{7,7}, {10,9},{5,4}, {3,3},{3,3}, {3,3},{3,3},{3,3},{3,3}, {2,2},{1,1} }; static BinOpr subexpr(LexState*ls,expdesc*v,unsigned int limit){ BinOpr op; UnOpr uop; enterlevel(ls); uop=getunopr(ls->t.token); if(uop!=OPR_NOUNOPR){ luaX_next(ls); subexpr(ls,v,8); luaK_prefix(ls->fs,uop,v); } else simpleexp(ls,v); op=getbinopr(ls->t.token); while(op!=OPR_NOBINOPR&&priority[op].left>limit){ expdesc v2; BinOpr nextop; luaX_next(ls); luaK_infix(ls->fs,op,v); nextop=subexpr(ls,&v2,priority[op].right); luaK_posfix(ls->fs,op,v,&v2); op=nextop; } leavelevel(ls); return op; } static void expr(LexState*ls,expdesc*v){ subexpr(ls,v,0); } static int block_follow(int token){ switch(token){ case TK_ELSE:case TK_ELSEIF:case TK_END: case TK_UNTIL:case TK_EOS: return 1; default:return 0; } } static void block(LexState*ls){ FuncState*fs=ls->fs; BlockCnt bl; enterblock(fs,&bl,0); chunk(ls); leaveblock(fs); } struct LHS_assign{ struct LHS_assign*prev; expdesc v; }; static void check_conflict(LexState*ls,struct LHS_assign*lh,expdesc*v){ FuncState*fs=ls->fs; int extra=fs->freereg; int conflict=0; for(;lh;lh=lh->prev){ if(lh->v.k==VINDEXED){ if(lh->v.u.s.info==v->u.s.info){ conflict=1; lh->v.u.s.info=extra; } if(lh->v.u.s.aux==v->u.s.info){ conflict=1; lh->v.u.s.aux=extra; } } } if(conflict){ luaK_codeABC(fs,OP_MOVE,fs->freereg,v->u.s.info,0); luaK_reserveregs(fs,1); } } static void assignment(LexState*ls,struct LHS_assign*lh,int nvars){ expdesc e; check_condition(ls,VLOCAL<=lh->v.k&&lh->v.k<=VINDEXED, "syntax error"); if(testnext(ls,',')){ struct LHS_assign nv; nv.prev=lh; primaryexp(ls,&nv.v); if(nv.v.k==VLOCAL) check_conflict(ls,lh,&nv.v); luaY_checklimit(ls->fs,nvars,200-ls->L->nCcalls, "variables in assignment"); assignment(ls,&nv,nvars+1); } else{ int nexps; checknext(ls,'='); nexps=explist1(ls,&e); if(nexps!=nvars){ adjust_assign(ls,nvars,nexps,&e); if(nexps>nvars) ls->fs->freereg-=nexps-nvars; } else{ luaK_setoneret(ls->fs,&e); luaK_storevar(ls->fs,&lh->v,&e); return; } } init_exp(&e,VNONRELOC,ls->fs->freereg-1); luaK_storevar(ls->fs,&lh->v,&e); } static int cond(LexState*ls){ expdesc v; expr(ls,&v); if(v.k==VNIL)v.k=VFALSE; luaK_goiftrue(ls->fs,&v); return v.f; } static void breakstat(LexState*ls){ FuncState*fs=ls->fs; BlockCnt*bl=fs->bl; int upval=0; while(bl&&!bl->isbreakable){ upval|=bl->upval; bl=bl->previous; } if(!bl) luaX_syntaxerror(ls,"no loop to break"); if(upval) luaK_codeABC(fs,OP_CLOSE,bl->nactvar,0,0); luaK_concat(fs,&bl->breaklist,luaK_jump(fs)); } static void whilestat(LexState*ls,int line){ FuncState*fs=ls->fs; int whileinit; int condexit; BlockCnt bl; luaX_next(ls); whileinit=luaK_getlabel(fs); condexit=cond(ls); enterblock(fs,&bl,1); checknext(ls,TK_DO); block(ls); luaK_patchlist(fs,luaK_jump(fs),whileinit); check_match(ls,TK_END,TK_WHILE,line); leaveblock(fs); luaK_patchtohere(fs,condexit); } static void repeatstat(LexState*ls,int line){ int condexit; FuncState*fs=ls->fs; int repeat_init=luaK_getlabel(fs); BlockCnt bl1,bl2; enterblock(fs,&bl1,1); enterblock(fs,&bl2,0); luaX_next(ls); chunk(ls); check_match(ls,TK_UNTIL,TK_REPEAT,line); condexit=cond(ls); if(!bl2.upval){ leaveblock(fs); luaK_patchlist(ls->fs,condexit,repeat_init); } else{ breakstat(ls); luaK_patchtohere(ls->fs,condexit); leaveblock(fs); luaK_patchlist(ls->fs,luaK_jump(fs),repeat_init); } leaveblock(fs); } static int exp1(LexState*ls){ expdesc e; int k; expr(ls,&e); k=e.k; luaK_exp2nextreg(ls->fs,&e); return k; } static void forbody(LexState*ls,int base,int line,int nvars,int isnum){ BlockCnt bl; FuncState*fs=ls->fs; int prep,endfor; adjustlocalvars(ls,3); checknext(ls,TK_DO); prep=isnum?luaK_codeAsBx(fs,OP_FORPREP,base,(-1)):luaK_jump(fs); enterblock(fs,&bl,0); adjustlocalvars(ls,nvars); luaK_reserveregs(fs,nvars); block(ls); leaveblock(fs); luaK_patchtohere(fs,prep); endfor=(isnum)?luaK_codeAsBx(fs,OP_FORLOOP,base,(-1)): luaK_codeABC(fs,OP_TFORLOOP,base,0,nvars); luaK_fixline(fs,line); luaK_patchlist(fs,(isnum?endfor:luaK_jump(fs)),prep+1); } static void fornum(LexState*ls,TString*varname,int line){ FuncState*fs=ls->fs; int base=fs->freereg; new_localvarliteral(ls,"(for index)",0); new_localvarliteral(ls,"(for limit)",1); new_localvarliteral(ls,"(for step)",2); new_localvar(ls,varname,3); checknext(ls,'='); exp1(ls); checknext(ls,','); exp1(ls); if(testnext(ls,',')) exp1(ls); else{ luaK_codeABx(fs,OP_LOADK,fs->freereg,luaK_numberK(fs,1)); luaK_reserveregs(fs,1); } forbody(ls,base,line,1,1); } static void forlist(LexState*ls,TString*indexname){ FuncState*fs=ls->fs; expdesc e; int nvars=0; int line; int base=fs->freereg; new_localvarliteral(ls,"(for generator)",nvars++); new_localvarliteral(ls,"(for state)",nvars++); new_localvarliteral(ls,"(for control)",nvars++); new_localvar(ls,indexname,nvars++); while(testnext(ls,',')) new_localvar(ls,str_checkname(ls),nvars++); checknext(ls,TK_IN); line=ls->linenumber; adjust_assign(ls,3,explist1(ls,&e),&e); luaK_checkstack(fs,3); forbody(ls,base,line,nvars-3,0); } static void forstat(LexState*ls,int line){ FuncState*fs=ls->fs; TString*varname; BlockCnt bl; enterblock(fs,&bl,1); luaX_next(ls); varname=str_checkname(ls); switch(ls->t.token){ case'=':fornum(ls,varname,line);break; case',':case TK_IN:forlist(ls,varname);break; default:luaX_syntaxerror(ls,LUA_QL("=")" or "LUA_QL("in")" expected"); } check_match(ls,TK_END,TK_FOR,line); leaveblock(fs); } static int test_then_block(LexState*ls){ int condexit; luaX_next(ls); condexit=cond(ls); checknext(ls,TK_THEN); block(ls); return condexit; } static void ifstat(LexState*ls,int line){ FuncState*fs=ls->fs; int flist; int escapelist=(-1); flist=test_then_block(ls); while(ls->t.token==TK_ELSEIF){ luaK_concat(fs,&escapelist,luaK_jump(fs)); luaK_patchtohere(fs,flist); flist=test_then_block(ls); } if(ls->t.token==TK_ELSE){ luaK_concat(fs,&escapelist,luaK_jump(fs)); luaK_patchtohere(fs,flist); luaX_next(ls); block(ls); } else luaK_concat(fs,&escapelist,flist); luaK_patchtohere(fs,escapelist); check_match(ls,TK_END,TK_IF,line); } static void localfunc(LexState*ls){ expdesc v,b; FuncState*fs=ls->fs; new_localvar(ls,str_checkname(ls),0); init_exp(&v,VLOCAL,fs->freereg); luaK_reserveregs(fs,1); adjustlocalvars(ls,1); body(ls,&b,0,ls->linenumber); luaK_storevar(fs,&v,&b); getlocvar(fs,fs->nactvar-1).startpc=fs->pc; } static void localstat(LexState*ls){ int nvars=0; int nexps; expdesc e; do{ new_localvar(ls,str_checkname(ls),nvars++); }while(testnext(ls,',')); if(testnext(ls,'=')) nexps=explist1(ls,&e); else{ e.k=VVOID; nexps=0; } adjust_assign(ls,nvars,nexps,&e); adjustlocalvars(ls,nvars); } static int funcname(LexState*ls,expdesc*v){ int needself=0; singlevar(ls,v); while(ls->t.token=='.') field(ls,v); if(ls->t.token==':'){ needself=1; field(ls,v); } return needself; } static void funcstat(LexState*ls,int line){ int needself; expdesc v,b; luaX_next(ls); needself=funcname(ls,&v); body(ls,&b,needself,line); luaK_storevar(ls->fs,&v,&b); luaK_fixline(ls->fs,line); } static void exprstat(LexState*ls){ FuncState*fs=ls->fs; struct LHS_assign v; primaryexp(ls,&v.v); if(v.v.k==VCALL) SETARG_C(getcode(fs,&v.v),1); else{ v.prev=NULL; assignment(ls,&v,1); } } static void retstat(LexState*ls){ FuncState*fs=ls->fs; expdesc e; int first,nret; luaX_next(ls); if(block_follow(ls->t.token)||ls->t.token==';') first=nret=0; else{ nret=explist1(ls,&e); if(hasmultret(e.k)){ luaK_setmultret(fs,&e); if(e.k==VCALL&&nret==1){ SET_OPCODE(getcode(fs,&e),OP_TAILCALL); } first=fs->nactvar; nret=(-1); } else{ if(nret==1) first=luaK_exp2anyreg(fs,&e); else{ luaK_exp2nextreg(fs,&e); first=fs->nactvar; } } } luaK_ret(fs,first,nret); } static int statement(LexState*ls){ int line=ls->linenumber; switch(ls->t.token){ case TK_IF:{ ifstat(ls,line); return 0; } case TK_WHILE:{ whilestat(ls,line); return 0; } case TK_DO:{ luaX_next(ls); block(ls); check_match(ls,TK_END,TK_DO,line); return 0; } case TK_FOR:{ forstat(ls,line); return 0; } case TK_REPEAT:{ repeatstat(ls,line); return 0; } case TK_FUNCTION:{ funcstat(ls,line); return 0; } case TK_LOCAL:{ luaX_next(ls); if(testnext(ls,TK_FUNCTION)) localfunc(ls); else localstat(ls); return 0; } case TK_RETURN:{ retstat(ls); return 1; } case TK_BREAK:{ luaX_next(ls); breakstat(ls); return 1; } default:{ exprstat(ls); return 0; } } } static void chunk(LexState*ls){ int islast=0; enterlevel(ls); while(!islast&&!block_follow(ls->t.token)){ islast=statement(ls); testnext(ls,';'); ls->fs->freereg=ls->fs->nactvar; } leavelevel(ls); } static const TValue*luaV_tonumber(const TValue*obj,TValue*n){ lua_Number num; if(ttisnumber(obj))return obj; if(ttisstring(obj)&&luaO_str2d(svalue(obj),&num)){ setnvalue(n,num); return n; } else return NULL; } static int luaV_tostring(lua_State*L,StkId obj){ if(!ttisnumber(obj)) return 0; else{ char s[32]; lua_Number n=nvalue(obj); lua_number2str(s,n); setsvalue(L,obj,luaS_new(L,s)); return 1; } } static void callTMres(lua_State*L,StkId res,const TValue*f, const TValue*p1,const TValue*p2){ ptrdiff_t result=savestack(L,res); setobj(L,L->top,f); setobj(L,L->top+1,p1); setobj(L,L->top+2,p2); luaD_checkstack(L,3); L->top+=3; luaD_call(L,L->top-3,1); res=restorestack(L,result); L->top--; setobj(L,res,L->top); } static void callTM(lua_State*L,const TValue*f,const TValue*p1, const TValue*p2,const TValue*p3){ setobj(L,L->top,f); setobj(L,L->top+1,p1); setobj(L,L->top+2,p2); setobj(L,L->top+3,p3); luaD_checkstack(L,4); L->top+=4; luaD_call(L,L->top-4,0); } static void luaV_gettable(lua_State*L,const TValue*t,TValue*key,StkId val){ int loop; for(loop=0;loop<100;loop++){ const TValue*tm; if(ttistable(t)){ Table*h=hvalue(t); const TValue*res=luaH_get(h,key); if(!ttisnil(res)|| (tm=fasttm(L,h->metatable,TM_INDEX))==NULL){ setobj(L,val,res); return; } } else if(ttisnil(tm=luaT_gettmbyobj(L,t,TM_INDEX))) luaG_typeerror(L,t,"index"); if(ttisfunction(tm)){ callTMres(L,val,tm,t,key); return; } t=tm; } luaG_runerror(L,"loop in gettable"); } static void luaV_settable(lua_State*L,const TValue*t,TValue*key,StkId val){ int loop; TValue temp; for(loop=0;loop<100;loop++){ const TValue*tm; if(ttistable(t)){ Table*h=hvalue(t); TValue*oldval=luaH_set(L,h,key); if(!ttisnil(oldval)|| (tm=fasttm(L,h->metatable,TM_NEWINDEX))==NULL){ setobj(L,oldval,val); h->flags=0; luaC_barriert(L,h,val); return; } } else if(ttisnil(tm=luaT_gettmbyobj(L,t,TM_NEWINDEX))) luaG_typeerror(L,t,"index"); if(ttisfunction(tm)){ callTM(L,tm,t,key,val); return; } setobj(L,&temp,tm); t=&temp; } luaG_runerror(L,"loop in settable"); } static int call_binTM(lua_State*L,const TValue*p1,const TValue*p2, StkId res,TMS event){ const TValue*tm=luaT_gettmbyobj(L,p1,event); if(ttisnil(tm)) tm=luaT_gettmbyobj(L,p2,event); if(ttisnil(tm))return 0; callTMres(L,res,tm,p1,p2); return 1; } static const TValue*get_compTM(lua_State*L,Table*mt1,Table*mt2, TMS event){ const TValue*tm1=fasttm(L,mt1,event); const TValue*tm2; if(tm1==NULL)return NULL; if(mt1==mt2)return tm1; tm2=fasttm(L,mt2,event); if(tm2==NULL)return NULL; if(luaO_rawequalObj(tm1,tm2)) return tm1; return NULL; } static int call_orderTM(lua_State*L,const TValue*p1,const TValue*p2, TMS event){ const TValue*tm1=luaT_gettmbyobj(L,p1,event); const TValue*tm2; if(ttisnil(tm1))return-1; tm2=luaT_gettmbyobj(L,p2,event); if(!luaO_rawequalObj(tm1,tm2)) return-1; callTMres(L,L->top,tm1,p1,p2); return!l_isfalse(L->top); } static int l_strcmp(const TString*ls,const TString*rs){ const char*l=getstr(ls); size_t ll=ls->tsv.len; const char*r=getstr(rs); size_t lr=rs->tsv.len; for(;;){ int temp=strcoll(l,r); if(temp!=0)return temp; else{ size_t len=strlen(l); if(len==lr) return(len==ll)?0:1; else if(len==ll) return-1; len++; l+=len;ll-=len;r+=len;lr-=len; } } } static int luaV_lessthan(lua_State*L,const TValue*l,const TValue*r){ int res; if(ttype(l)!=ttype(r)) return luaG_ordererror(L,l,r); else if(ttisnumber(l)) return luai_numlt(nvalue(l),nvalue(r)); else if(ttisstring(l)) return l_strcmp(rawtsvalue(l),rawtsvalue(r))<0; else if((res=call_orderTM(L,l,r,TM_LT))!=-1) return res; return luaG_ordererror(L,l,r); } static int lessequal(lua_State*L,const TValue*l,const TValue*r){ int res; if(ttype(l)!=ttype(r)) return luaG_ordererror(L,l,r); else if(ttisnumber(l)) return luai_numle(nvalue(l),nvalue(r)); else if(ttisstring(l)) return l_strcmp(rawtsvalue(l),rawtsvalue(r))<=0; else if((res=call_orderTM(L,l,r,TM_LE))!=-1) return res; else if((res=call_orderTM(L,r,l,TM_LT))!=-1) return!res; return luaG_ordererror(L,l,r); } static int luaV_equalval(lua_State*L,const TValue*t1,const TValue*t2){ const TValue*tm; switch(ttype(t1)){ case 0:return 1; case 3:return luai_numeq(nvalue(t1),nvalue(t2)); case 1:return bvalue(t1)==bvalue(t2); case 2:return pvalue(t1)==pvalue(t2); case 7:{ if(uvalue(t1)==uvalue(t2))return 1; tm=get_compTM(L,uvalue(t1)->metatable,uvalue(t2)->metatable, TM_EQ); break; } case 5:{ if(hvalue(t1)==hvalue(t2))return 1; tm=get_compTM(L,hvalue(t1)->metatable,hvalue(t2)->metatable,TM_EQ); break; } default:return gcvalue(t1)==gcvalue(t2); } if(tm==NULL)return 0; callTMres(L,L->top,tm,t1,t2); return!l_isfalse(L->top); } static void luaV_concat(lua_State*L,int total,int last){ do{ StkId top=L->base+last+1; int n=2; if(!(ttisstring(top-2)||ttisnumber(top-2))||!tostring(L,top-1)){ if(!call_binTM(L,top-2,top-1,top-2,TM_CONCAT)) luaG_concaterror(L,top-2,top-1); }else if(tsvalue(top-1)->len==0) (void)tostring(L,top-2); else{ size_t tl=tsvalue(top-1)->len; char*buffer; int i; for(n=1;n<total&&tostring(L,top-n-1);n++){ size_t l=tsvalue(top-n-1)->len; if(l>=((size_t)(~(size_t)0)-2)-tl)luaG_runerror(L,"string length overflow"); tl+=l; } buffer=luaZ_openspace(L,&G(L)->buff,tl); tl=0; for(i=n;i>0;i--){ size_t l=tsvalue(top-i)->len; memcpy(buffer+tl,svalue(top-i),l); tl+=l; } setsvalue(L,top-n,luaS_newlstr(L,buffer,tl)); } total-=n-1; last-=n-1; }while(total>1); } static void Arith(lua_State*L,StkId ra,const TValue*rb, const TValue*rc,TMS op){ TValue tempb,tempc; const TValue*b,*c; if((b=luaV_tonumber(rb,&tempb))!=NULL&& (c=luaV_tonumber(rc,&tempc))!=NULL){ lua_Number nb=nvalue(b),nc=nvalue(c); switch(op){ case TM_ADD:setnvalue(ra,luai_numadd(nb,nc));break; case TM_SUB:setnvalue(ra,luai_numsub(nb,nc));break; case TM_MUL:setnvalue(ra,luai_nummul(nb,nc));break; case TM_DIV:setnvalue(ra,luai_numdiv(nb,nc));break; case TM_MOD:setnvalue(ra,luai_nummod(nb,nc));break; case TM_POW:setnvalue(ra,luai_numpow(nb,nc));break; case TM_UNM:setnvalue(ra,luai_numunm(nb));break; default:break; } } else if(!call_binTM(L,rb,rc,ra,op)) luaG_aritherror(L,rb,rc); } #define runtime_check(L,c){if(!(c))break;} #define RA(i)(base+GETARG_A(i)) #define RB(i)check_exp(getBMode(GET_OPCODE(i))==OpArgR,base+GETARG_B(i)) #define RKB(i)check_exp(getBMode(GET_OPCODE(i))==OpArgK,ISK(GETARG_B(i))?k+INDEXK(GETARG_B(i)):base+GETARG_B(i)) #define RKC(i)check_exp(getCMode(GET_OPCODE(i))==OpArgK,ISK(GETARG_C(i))?k+INDEXK(GETARG_C(i)):base+GETARG_C(i)) #define KBx(i)check_exp(getBMode(GET_OPCODE(i))==OpArgK,k+GETARG_Bx(i)) #define dojump(L,pc,i){(pc)+=(i);} #define Protect(x){L->savedpc=pc;{x;};base=L->base;} #define arith_op(op,tm){TValue*rb=RKB(i);TValue*rc=RKC(i);if(ttisnumber(rb)&&ttisnumber(rc)){lua_Number nb=nvalue(rb),nc=nvalue(rc);setnvalue(ra,op(nb,nc));}else Protect(Arith(L,ra,rb,rc,tm));} static void luaV_execute(lua_State*L,int nexeccalls){ LClosure*cl; StkId base; TValue*k; const Instruction*pc; reentry: pc=L->savedpc; cl=&clvalue(L->ci->func)->l; base=L->base; k=cl->p->k; for(;;){ const Instruction i=*pc++; StkId ra; ra=RA(i); switch(GET_OPCODE(i)){ case OP_MOVE:{ setobj(L,ra,RB(i)); continue; } case OP_LOADK:{ setobj(L,ra,KBx(i)); continue; } case OP_LOADBOOL:{ setbvalue(ra,GETARG_B(i)); if(GETARG_C(i))pc++; continue; } case OP_LOADNIL:{ TValue*rb=RB(i); do{ setnilvalue(rb--); }while(rb>=ra); continue; } case OP_GETUPVAL:{ int b=GETARG_B(i); setobj(L,ra,cl->upvals[b]->v); continue; } case OP_GETGLOBAL:{ TValue g; TValue*rb=KBx(i); sethvalue(L,&g,cl->env); Protect(luaV_gettable(L,&g,rb,ra)); continue; } case OP_GETTABLE:{ Protect(luaV_gettable(L,RB(i),RKC(i),ra)); continue; } case OP_SETGLOBAL:{ TValue g; sethvalue(L,&g,cl->env); Protect(luaV_settable(L,&g,KBx(i),ra)); continue; } case OP_SETUPVAL:{ UpVal*uv=cl->upvals[GETARG_B(i)]; setobj(L,uv->v,ra); luaC_barrier(L,uv,ra); continue; } case OP_SETTABLE:{ Protect(luaV_settable(L,ra,RKB(i),RKC(i))); continue; } case OP_NEWTABLE:{ int b=GETARG_B(i); int c=GETARG_C(i); sethvalue(L,ra,luaH_new(L,luaO_fb2int(b),luaO_fb2int(c))); Protect(luaC_checkGC(L)); continue; } case OP_SELF:{ StkId rb=RB(i); setobj(L,ra+1,rb); Protect(luaV_gettable(L,rb,RKC(i),ra)); continue; } case OP_ADD:{ arith_op(luai_numadd,TM_ADD); continue; } case OP_SUB:{ arith_op(luai_numsub,TM_SUB); continue; } case OP_MUL:{ arith_op(luai_nummul,TM_MUL); continue; } case OP_DIV:{ arith_op(luai_numdiv,TM_DIV); continue; } case OP_MOD:{ arith_op(luai_nummod,TM_MOD); continue; } case OP_POW:{ arith_op(luai_numpow,TM_POW); continue; } case OP_UNM:{ TValue*rb=RB(i); if(ttisnumber(rb)){ lua_Number nb=nvalue(rb); setnvalue(ra,luai_numunm(nb)); } else{ Protect(Arith(L,ra,rb,rb,TM_UNM)); } continue; } case OP_NOT:{ int res=l_isfalse(RB(i)); setbvalue(ra,res); continue; } case OP_LEN:{ const TValue*rb=RB(i); switch(ttype(rb)){ case 5:{ setnvalue(ra,cast_num(luaH_getn(hvalue(rb)))); break; } case 4:{ setnvalue(ra,cast_num(tsvalue(rb)->len)); break; } default:{ Protect( if(!call_binTM(L,rb,(&luaO_nilobject_),ra,TM_LEN)) luaG_typeerror(L,rb,"get length of"); ) } } continue; } case OP_CONCAT:{ int b=GETARG_B(i); int c=GETARG_C(i); Protect(luaV_concat(L,c-b+1,c);luaC_checkGC(L)); setobj(L,RA(i),base+b); continue; } case OP_JMP:{ dojump(L,pc,GETARG_sBx(i)); continue; } case OP_EQ:{ TValue*rb=RKB(i); TValue*rc=RKC(i); Protect( if(equalobj(L,rb,rc)==GETARG_A(i)) dojump(L,pc,GETARG_sBx(*pc)); ) pc++; continue; } case OP_LT:{ Protect( if(luaV_lessthan(L,RKB(i),RKC(i))==GETARG_A(i)) dojump(L,pc,GETARG_sBx(*pc)); ) pc++; continue; } case OP_LE:{ Protect( if(lessequal(L,RKB(i),RKC(i))==GETARG_A(i)) dojump(L,pc,GETARG_sBx(*pc)); ) pc++; continue; } case OP_TEST:{ if(l_isfalse(ra)!=GETARG_C(i)) dojump(L,pc,GETARG_sBx(*pc)); pc++; continue; } case OP_TESTSET:{ TValue*rb=RB(i); if(l_isfalse(rb)!=GETARG_C(i)){ setobj(L,ra,rb); dojump(L,pc,GETARG_sBx(*pc)); } pc++; continue; } case OP_CALL:{ int b=GETARG_B(i); int nresults=GETARG_C(i)-1; if(b!=0)L->top=ra+b; L->savedpc=pc; switch(luaD_precall(L,ra,nresults)){ case 0:{ nexeccalls++; goto reentry; } case 1:{ if(nresults>=0)L->top=L->ci->top; base=L->base; continue; } default:{ return; } } } case OP_TAILCALL:{ int b=GETARG_B(i); if(b!=0)L->top=ra+b; L->savedpc=pc; switch(luaD_precall(L,ra,(-1))){ case 0:{ CallInfo*ci=L->ci-1; int aux; StkId func=ci->func; StkId pfunc=(ci+1)->func; if(L->openupval)luaF_close(L,ci->base); L->base=ci->base=ci->func+((ci+1)->base-pfunc); for(aux=0;pfunc+aux<L->top;aux++) setobj(L,func+aux,pfunc+aux); ci->top=L->top=func+aux; ci->savedpc=L->savedpc; ci->tailcalls++; L->ci--; goto reentry; } case 1:{ base=L->base; continue; } default:{ return; } } } case OP_RETURN:{ int b=GETARG_B(i); if(b!=0)L->top=ra+b-1; if(L->openupval)luaF_close(L,base); L->savedpc=pc; b=luaD_poscall(L,ra); if(--nexeccalls==0) return; else{ if(b)L->top=L->ci->top; goto reentry; } } case OP_FORLOOP:{ lua_Number step=nvalue(ra+2); lua_Number idx=luai_numadd(nvalue(ra),step); lua_Number limit=nvalue(ra+1); if(luai_numlt(0,step)?luai_numle(idx,limit) :luai_numle(limit,idx)){ dojump(L,pc,GETARG_sBx(i)); setnvalue(ra,idx); setnvalue(ra+3,idx); } continue; } case OP_FORPREP:{ const TValue*init=ra; const TValue*plimit=ra+1; const TValue*pstep=ra+2; L->savedpc=pc; if(!tonumber(init,ra)) luaG_runerror(L,LUA_QL("for")" initial value must be a number"); else if(!tonumber(plimit,ra+1)) luaG_runerror(L,LUA_QL("for")" limit must be a number"); else if(!tonumber(pstep,ra+2)) luaG_runerror(L,LUA_QL("for")" step must be a number"); setnvalue(ra,luai_numsub(nvalue(ra),nvalue(pstep))); dojump(L,pc,GETARG_sBx(i)); continue; } case OP_TFORLOOP:{ StkId cb=ra+3; setobj(L,cb+2,ra+2); setobj(L,cb+1,ra+1); setobj(L,cb,ra); L->top=cb+3; Protect(luaD_call(L,cb,GETARG_C(i))); L->top=L->ci->top; cb=RA(i)+3; if(!ttisnil(cb)){ setobj(L,cb-1,cb); dojump(L,pc,GETARG_sBx(*pc)); } pc++; continue; } case OP_SETLIST:{ int n=GETARG_B(i); int c=GETARG_C(i); int last; Table*h; if(n==0){ n=cast_int(L->top-ra)-1; L->top=L->ci->top; } if(c==0)c=cast_int(*pc++); runtime_check(L,ttistable(ra)); h=hvalue(ra); last=((c-1)*50)+n; if(last>h->sizearray) luaH_resizearray(L,h,last); for(;n>0;n--){ TValue*val=ra+n; setobj(L,luaH_setnum(L,h,last--),val); luaC_barriert(L,h,val); } continue; } case OP_CLOSE:{ luaF_close(L,ra); continue; } case OP_CLOSURE:{ Proto*p; Closure*ncl; int nup,j; p=cl->p->p[GETARG_Bx(i)]; nup=p->nups; ncl=luaF_newLclosure(L,nup,cl->env); ncl->l.p=p; for(j=0;j<nup;j++,pc++){ if(GET_OPCODE(*pc)==OP_GETUPVAL) ncl->l.upvals[j]=cl->upvals[GETARG_B(*pc)]; else{ ncl->l.upvals[j]=luaF_findupval(L,base+GETARG_B(*pc)); } } setclvalue(L,ra,ncl); Protect(luaC_checkGC(L)); continue; } case OP_VARARG:{ int b=GETARG_B(i)-1; int j; CallInfo*ci=L->ci; int n=cast_int(ci->base-ci->func)-cl->p->numparams-1; if(b==(-1)){ Protect(luaD_checkstack(L,n)); ra=RA(i); b=n; L->top=ra+n; } for(j=0;j<b;j++){ if(j<n){ setobj(L,ra+j,ci->base-n+j); } else{ setnilvalue(ra+j); } } continue; } } } } #define api_checknelems(L,n)luai_apicheck(L,(n)<=(L->top-L->base)) #define api_checkvalidindex(L,i)luai_apicheck(L,(i)!=(&luaO_nilobject_)) #define api_incr_top(L){luai_apicheck(L,L->top<L->ci->top);L->top++;} static TValue*index2adr(lua_State*L,int idx){ if(idx>0){ TValue*o=L->base+(idx-1); luai_apicheck(L,idx<=L->ci->top-L->base); if(o>=L->top)return cast(TValue*,(&luaO_nilobject_)); else return o; } else if(idx>(-10000)){ luai_apicheck(L,idx!=0&&-idx<=L->top-L->base); return L->top+idx; } else switch(idx){ case(-10000):return registry(L); case(-10001):{ Closure*func=curr_func(L); sethvalue(L,&L->env,func->c.env); return&L->env; } case(-10002):return gt(L); default:{ Closure*func=curr_func(L); idx=(-10002)-idx; return(idx<=func->c.nupvalues) ?&func->c.upvalue[idx-1] :cast(TValue*,(&luaO_nilobject_)); } } } static Table*getcurrenv(lua_State*L){ if(L->ci==L->base_ci) return hvalue(gt(L)); else{ Closure*func=curr_func(L); return func->c.env; } } static int lua_checkstack(lua_State*L,int size){ int res=1; if(size>8000||(L->top-L->base+size)>8000) res=0; else if(size>0){ luaD_checkstack(L,size); if(L->ci->top<L->top+size) L->ci->top=L->top+size; } return res; } static lua_CFunction lua_atpanic(lua_State*L,lua_CFunction panicf){ lua_CFunction old; old=G(L)->panic; G(L)->panic=panicf; return old; } static int lua_gettop(lua_State*L){ return cast_int(L->top-L->base); } static void lua_settop(lua_State*L,int idx){ if(idx>=0){ luai_apicheck(L,idx<=L->stack_last-L->base); while(L->top<L->base+idx) setnilvalue(L->top++); L->top=L->base+idx; } else{ luai_apicheck(L,-(idx+1)<=(L->top-L->base)); L->top+=idx+1; } } static void lua_remove(lua_State*L,int idx){ StkId p; p=index2adr(L,idx); api_checkvalidindex(L,p); while(++p<L->top)setobj(L,p-1,p); L->top--; } static void lua_insert(lua_State*L,int idx){ StkId p; StkId q; p=index2adr(L,idx); api_checkvalidindex(L,p); for(q=L->top;q>p;q--)setobj(L,q,q-1); setobj(L,p,L->top); } static void lua_replace(lua_State*L,int idx){ StkId o; if(idx==(-10001)&&L->ci==L->base_ci) luaG_runerror(L,"no calling environment"); api_checknelems(L,1); o=index2adr(L,idx); api_checkvalidindex(L,o); if(idx==(-10001)){ Closure*func=curr_func(L); luai_apicheck(L,ttistable(L->top-1)); func->c.env=hvalue(L->top-1); luaC_barrier(L,func,L->top-1); } else{ setobj(L,o,L->top-1); if(idx<(-10002)) luaC_barrier(L,curr_func(L),L->top-1); } L->top--; } static void lua_pushvalue(lua_State*L,int idx){ setobj(L,L->top,index2adr(L,idx)); api_incr_top(L); } static int lua_type(lua_State*L,int idx){ StkId o=index2adr(L,idx); return(o==(&luaO_nilobject_))?(-1):ttype(o); } static const char*lua_typename(lua_State*L,int t){ UNUSED(L); return(t==(-1))?"no value":luaT_typenames[t]; } static int lua_iscfunction(lua_State*L,int idx){ StkId o=index2adr(L,idx); return iscfunction(o); } static int lua_isnumber(lua_State*L,int idx){ TValue n; const TValue*o=index2adr(L,idx); return tonumber(o,&n); } static int lua_isstring(lua_State*L,int idx){ int t=lua_type(L,idx); return(t==4||t==3); } static int lua_rawequal(lua_State*L,int index1,int index2){ StkId o1=index2adr(L,index1); StkId o2=index2adr(L,index2); return(o1==(&luaO_nilobject_)||o2==(&luaO_nilobject_))?0 :luaO_rawequalObj(o1,o2); } static int lua_lessthan(lua_State*L,int index1,int index2){ StkId o1,o2; int i; o1=index2adr(L,index1); o2=index2adr(L,index2); i=(o1==(&luaO_nilobject_)||o2==(&luaO_nilobject_))?0 :luaV_lessthan(L,o1,o2); return i; } static lua_Number lua_tonumber(lua_State*L,int idx){ TValue n; const TValue*o=index2adr(L,idx); if(tonumber(o,&n)) return nvalue(o); else return 0; } static lua_Integer lua_tointeger(lua_State*L,int idx){ TValue n; const TValue*o=index2adr(L,idx); if(tonumber(o,&n)){ lua_Integer res; lua_Number num=nvalue(o); lua_number2integer(res,num); return res; } else return 0; } static int lua_toboolean(lua_State*L,int idx){ const TValue*o=index2adr(L,idx); return!l_isfalse(o); } static const char*lua_tolstring(lua_State*L,int idx,size_t*len){ StkId o=index2adr(L,idx); if(!ttisstring(o)){ if(!luaV_tostring(L,o)){ if(len!=NULL)*len=0; return NULL; } luaC_checkGC(L); o=index2adr(L,idx); } if(len!=NULL)*len=tsvalue(o)->len; return svalue(o); } static size_t lua_objlen(lua_State*L,int idx){ StkId o=index2adr(L,idx); switch(ttype(o)){ case 4:return tsvalue(o)->len; case 7:return uvalue(o)->len; case 5:return luaH_getn(hvalue(o)); case 3:{ size_t l; l=(luaV_tostring(L,o)?tsvalue(o)->len:0); return l; } default:return 0; } } static lua_CFunction lua_tocfunction(lua_State*L,int idx){ StkId o=index2adr(L,idx); return(!iscfunction(o))?NULL:clvalue(o)->c.f; } static void*lua_touserdata(lua_State*L,int idx){ StkId o=index2adr(L,idx); switch(ttype(o)){ case 7:return(rawuvalue(o)+1); case 2:return pvalue(o); default:return NULL; } } static void lua_pushnil(lua_State*L){ setnilvalue(L->top); api_incr_top(L); } static void lua_pushnumber(lua_State*L,lua_Number n){ setnvalue(L->top,n); api_incr_top(L); } static void lua_pushinteger(lua_State*L,lua_Integer n){ setnvalue(L->top,cast_num(n)); api_incr_top(L); } static void lua_pushlstring(lua_State*L,const char*s,size_t len){ luaC_checkGC(L); setsvalue(L,L->top,luaS_newlstr(L,s,len)); api_incr_top(L); } static void lua_pushstring(lua_State*L,const char*s){ if(s==NULL) lua_pushnil(L); else lua_pushlstring(L,s,strlen(s)); } static const char*lua_pushvfstring(lua_State*L,const char*fmt, va_list argp){ const char*ret; luaC_checkGC(L); ret=luaO_pushvfstring(L,fmt,argp); return ret; } static const char*lua_pushfstring(lua_State*L,const char*fmt,...){ const char*ret; va_list argp; luaC_checkGC(L); va_start(argp,fmt); ret=luaO_pushvfstring(L,fmt,argp); va_end(argp); return ret; } static void lua_pushcclosure(lua_State*L,lua_CFunction fn,int n){ Closure*cl; luaC_checkGC(L); api_checknelems(L,n); cl=luaF_newCclosure(L,n,getcurrenv(L)); cl->c.f=fn; L->top-=n; while(n--) setobj(L,&cl->c.upvalue[n],L->top+n); setclvalue(L,L->top,cl); api_incr_top(L); } static void lua_pushboolean(lua_State*L,int b){ setbvalue(L->top,(b!=0)); api_incr_top(L); } static int lua_pushthread(lua_State*L){ setthvalue(L,L->top,L); api_incr_top(L); return(G(L)->mainthread==L); } static void lua_gettable(lua_State*L,int idx){ StkId t; t=index2adr(L,idx); api_checkvalidindex(L,t); luaV_gettable(L,t,L->top-1,L->top-1); } static void lua_getfield(lua_State*L,int idx,const char*k){ StkId t; TValue key; t=index2adr(L,idx); api_checkvalidindex(L,t); setsvalue(L,&key,luaS_new(L,k)); luaV_gettable(L,t,&key,L->top); api_incr_top(L); } static void lua_rawget(lua_State*L,int idx){ StkId t; t=index2adr(L,idx); luai_apicheck(L,ttistable(t)); setobj(L,L->top-1,luaH_get(hvalue(t),L->top-1)); } static void lua_rawgeti(lua_State*L,int idx,int n){ StkId o; o=index2adr(L,idx); luai_apicheck(L,ttistable(o)); setobj(L,L->top,luaH_getnum(hvalue(o),n)); api_incr_top(L); } static void lua_createtable(lua_State*L,int narray,int nrec){ luaC_checkGC(L); sethvalue(L,L->top,luaH_new(L,narray,nrec)); api_incr_top(L); } static int lua_getmetatable(lua_State*L,int objindex){ const TValue*obj; Table*mt=NULL; int res; obj=index2adr(L,objindex); switch(ttype(obj)){ case 5: mt=hvalue(obj)->metatable; break; case 7: mt=uvalue(obj)->metatable; break; default: mt=G(L)->mt[ttype(obj)]; break; } if(mt==NULL) res=0; else{ sethvalue(L,L->top,mt); api_incr_top(L); res=1; } return res; } static void lua_getfenv(lua_State*L,int idx){ StkId o; o=index2adr(L,idx); api_checkvalidindex(L,o); switch(ttype(o)){ case 6: sethvalue(L,L->top,clvalue(o)->c.env); break; case 7: sethvalue(L,L->top,uvalue(o)->env); break; case 8: setobj(L,L->top,gt(thvalue(o))); break; default: setnilvalue(L->top); break; } api_incr_top(L); } static void lua_settable(lua_State*L,int idx){ StkId t; api_checknelems(L,2); t=index2adr(L,idx); api_checkvalidindex(L,t); luaV_settable(L,t,L->top-2,L->top-1); L->top-=2; } static void lua_setfield(lua_State*L,int idx,const char*k){ StkId t; TValue key; api_checknelems(L,1); t=index2adr(L,idx); api_checkvalidindex(L,t); setsvalue(L,&key,luaS_new(L,k)); luaV_settable(L,t,&key,L->top-1); L->top--; } static void lua_rawset(lua_State*L,int idx){ StkId t; api_checknelems(L,2); t=index2adr(L,idx); luai_apicheck(L,ttistable(t)); setobj(L,luaH_set(L,hvalue(t),L->top-2),L->top-1); luaC_barriert(L,hvalue(t),L->top-1); L->top-=2; } static void lua_rawseti(lua_State*L,int idx,int n){ StkId o; api_checknelems(L,1); o=index2adr(L,idx); luai_apicheck(L,ttistable(o)); setobj(L,luaH_setnum(L,hvalue(o),n),L->top-1); luaC_barriert(L,hvalue(o),L->top-1); L->top--; } static int lua_setmetatable(lua_State*L,int objindex){ TValue*obj; Table*mt; api_checknelems(L,1); obj=index2adr(L,objindex); api_checkvalidindex(L,obj); if(ttisnil(L->top-1)) mt=NULL; else{ luai_apicheck(L,ttistable(L->top-1)); mt=hvalue(L->top-1); } switch(ttype(obj)){ case 5:{ hvalue(obj)->metatable=mt; if(mt) luaC_objbarriert(L,hvalue(obj),mt); break; } case 7:{ uvalue(obj)->metatable=mt; if(mt) luaC_objbarrier(L,rawuvalue(obj),mt); break; } default:{ G(L)->mt[ttype(obj)]=mt; break; } } L->top--; return 1; } static int lua_setfenv(lua_State*L,int idx){ StkId o; int res=1; api_checknelems(L,1); o=index2adr(L,idx); api_checkvalidindex(L,o); luai_apicheck(L,ttistable(L->top-1)); switch(ttype(o)){ case 6: clvalue(o)->c.env=hvalue(L->top-1); break; case 7: uvalue(o)->env=hvalue(L->top-1); break; case 8: sethvalue(L,gt(thvalue(o)),hvalue(L->top-1)); break; default: res=0; break; } if(res)luaC_objbarrier(L,gcvalue(o),hvalue(L->top-1)); L->top--; return res; } #define adjustresults(L,nres){if(nres==(-1)&&L->top>=L->ci->top)L->ci->top=L->top;} #define checkresults(L,na,nr)luai_apicheck(L,(nr)==(-1)||(L->ci->top-L->top>=(nr)-(na))) static void lua_call(lua_State*L,int nargs,int nresults){ StkId func; api_checknelems(L,nargs+1); checkresults(L,nargs,nresults); func=L->top-(nargs+1); luaD_call(L,func,nresults); adjustresults(L,nresults); } struct CallS{ StkId func; int nresults; }; static void f_call(lua_State*L,void*ud){ struct CallS*c=cast(struct CallS*,ud); luaD_call(L,c->func,c->nresults); } static int lua_pcall(lua_State*L,int nargs,int nresults,int errfunc){ struct CallS c; int status; ptrdiff_t func; api_checknelems(L,nargs+1); checkresults(L,nargs,nresults); if(errfunc==0) func=0; else{ StkId o=index2adr(L,errfunc); api_checkvalidindex(L,o); func=savestack(L,o); } c.func=L->top-(nargs+1); c.nresults=nresults; status=luaD_pcall(L,f_call,&c,savestack(L,c.func),func); adjustresults(L,nresults); return status; } static int lua_load(lua_State*L,lua_Reader reader,void*data, const char*chunkname){ ZIO z; int status; if(!chunkname)chunkname="?"; luaZ_init(L,&z,reader,data); status=luaD_protectedparser(L,&z,chunkname); return status; } static int lua_error(lua_State*L){ api_checknelems(L,1); luaG_errormsg(L); return 0; } static int lua_next(lua_State*L,int idx){ StkId t; int more; t=index2adr(L,idx); luai_apicheck(L,ttistable(t)); more=luaH_next(L,hvalue(t),L->top-1); if(more){ api_incr_top(L); } else L->top-=1; return more; } static void lua_concat(lua_State*L,int n){ api_checknelems(L,n); if(n>=2){ luaC_checkGC(L); luaV_concat(L,n,cast_int(L->top-L->base)-1); L->top-=(n-1); } else if(n==0){ setsvalue(L,L->top,luaS_newlstr(L,"",0)); api_incr_top(L); } } static void*lua_newuserdata(lua_State*L,size_t size){ Udata*u; luaC_checkGC(L); u=luaS_newudata(L,size,getcurrenv(L)); setuvalue(L,L->top,u); api_incr_top(L); return u+1; } #define luaL_getn(L,i)((int)lua_objlen(L,i)) #define luaL_setn(L,i,j)((void)0) typedef struct luaL_Reg{ const char*name; lua_CFunction func; }luaL_Reg; static void luaI_openlib(lua_State*L,const char*libname, const luaL_Reg*l,int nup); static int luaL_argerror(lua_State*L,int numarg,const char*extramsg); static const char* luaL_checklstring(lua_State*L,int numArg, size_t*l); static const char* luaL_optlstring(lua_State*L,int numArg, const char*def,size_t*l); static lua_Integer luaL_checkinteger(lua_State*L,int numArg); static lua_Integer luaL_optinteger(lua_State*L,int nArg, lua_Integer def); static int luaL_error(lua_State*L,const char*fmt,...); static const char* luaL_findtable(lua_State*L,int idx, const char*fname,int szhint); #define luaL_argcheck(L,cond,numarg,extramsg)((void)((cond)||luaL_argerror(L,(numarg),(extramsg)))) #define luaL_checkstring(L,n)(luaL_checklstring(L,(n),NULL)) #define luaL_optstring(L,n,d)(luaL_optlstring(L,(n),(d),NULL)) #define luaL_checkint(L,n)((int)luaL_checkinteger(L,(n))) #define luaL_optint(L,n,d)((int)luaL_optinteger(L,(n),(d))) #define luaL_typename(L,i)lua_typename(L,lua_type(L,(i))) #define luaL_getmetatable(L,n)(lua_getfield(L,(-10000),(n))) #define luaL_opt(L,f,n,d)(lua_isnoneornil(L,(n))?(d):f(L,(n))) typedef struct luaL_Buffer{ char*p; int lvl; lua_State*L; char buffer[BUFSIZ]; }luaL_Buffer; #define luaL_addchar(B,c)((void)((B)->p<((B)->buffer+BUFSIZ)||luaL_prepbuffer(B)),(*(B)->p++=(char)(c))) #define luaL_addsize(B,n)((B)->p+=(n)) static char* luaL_prepbuffer(luaL_Buffer*B); static int luaL_argerror(lua_State*L,int narg,const char*extramsg){ lua_Debug ar; if(!lua_getstack(L,0,&ar)) return luaL_error(L,"bad argument #%d (%s)",narg,extramsg); lua_getinfo(L,"n",&ar); if(strcmp(ar.namewhat,"method")==0){ narg--; if(narg==0) return luaL_error(L,"calling "LUA_QL("%s")" on bad self (%s)", ar.name,extramsg); } if(ar.name==NULL) ar.name="?"; return luaL_error(L,"bad argument #%d to "LUA_QL("%s")" (%s)", narg,ar.name,extramsg); } static int luaL_typerror(lua_State*L,int narg,const char*tname){ const char*msg=lua_pushfstring(L,"%s expected, got %s", tname,luaL_typename(L,narg)); return luaL_argerror(L,narg,msg); } static void tag_error(lua_State*L,int narg,int tag){ luaL_typerror(L,narg,lua_typename(L,tag)); } static void luaL_where(lua_State*L,int level){ lua_Debug ar; if(lua_getstack(L,level,&ar)){ lua_getinfo(L,"Sl",&ar); if(ar.currentline>0){ lua_pushfstring(L,"%s:%d: ",ar.short_src,ar.currentline); return; } } lua_pushliteral(L,""); } static int luaL_error(lua_State*L,const char*fmt,...){ va_list argp; va_start(argp,fmt); luaL_where(L,1); lua_pushvfstring(L,fmt,argp); va_end(argp); lua_concat(L,2); return lua_error(L); } static int luaL_newmetatable(lua_State*L,const char*tname){ lua_getfield(L,(-10000),tname); if(!lua_isnil(L,-1)) return 0; lua_pop(L,1); lua_newtable(L); lua_pushvalue(L,-1); lua_setfield(L,(-10000),tname); return 1; } static void*luaL_checkudata(lua_State*L,int ud,const char*tname){ void*p=lua_touserdata(L,ud); if(p!=NULL){ if(lua_getmetatable(L,ud)){ lua_getfield(L,(-10000),tname); if(lua_rawequal(L,-1,-2)){ lua_pop(L,2); return p; } } } luaL_typerror(L,ud,tname); return NULL; } static void luaL_checkstack(lua_State*L,int space,const char*mes){ if(!lua_checkstack(L,space)) luaL_error(L,"stack overflow (%s)",mes); } static void luaL_checktype(lua_State*L,int narg,int t){ if(lua_type(L,narg)!=t) tag_error(L,narg,t); } static void luaL_checkany(lua_State*L,int narg){ if(lua_type(L,narg)==(-1)) luaL_argerror(L,narg,"value expected"); } static const char*luaL_checklstring(lua_State*L,int narg,size_t*len){ const char*s=lua_tolstring(L,narg,len); if(!s)tag_error(L,narg,4); return s; } static const char*luaL_optlstring(lua_State*L,int narg, const char*def,size_t*len){ if(lua_isnoneornil(L,narg)){ if(len) *len=(def?strlen(def):0); return def; } else return luaL_checklstring(L,narg,len); } static lua_Number luaL_checknumber(lua_State*L,int narg){ lua_Number d=lua_tonumber(L,narg); if(d==0&&!lua_isnumber(L,narg)) tag_error(L,narg,3); return d; } static lua_Integer luaL_checkinteger(lua_State*L,int narg){ lua_Integer d=lua_tointeger(L,narg); if(d==0&&!lua_isnumber(L,narg)) tag_error(L,narg,3); return d; } static lua_Integer luaL_optinteger(lua_State*L,int narg, lua_Integer def){ return luaL_opt(L,luaL_checkinteger,narg,def); } static int luaL_getmetafield(lua_State*L,int obj,const char*event){ if(!lua_getmetatable(L,obj)) return 0; lua_pushstring(L,event); lua_rawget(L,-2); if(lua_isnil(L,-1)){ lua_pop(L,2); return 0; } else{ lua_remove(L,-2); return 1; } } static void luaL_register(lua_State*L,const char*libname, const luaL_Reg*l){ luaI_openlib(L,libname,l,0); } static int libsize(const luaL_Reg*l){ int size=0; for(;l->name;l++)size++; return size; } static void luaI_openlib(lua_State*L,const char*libname, const luaL_Reg*l,int nup){ if(libname){ int size=libsize(l); luaL_findtable(L,(-10000),"_LOADED",1); lua_getfield(L,-1,libname); if(!lua_istable(L,-1)){ lua_pop(L,1); if(luaL_findtable(L,(-10002),libname,size)!=NULL) luaL_error(L,"name conflict for module "LUA_QL("%s"),libname); lua_pushvalue(L,-1); lua_setfield(L,-3,libname); } lua_remove(L,-2); lua_insert(L,-(nup+1)); } for(;l->name;l++){ int i; for(i=0;i<nup;i++) lua_pushvalue(L,-nup); lua_pushcclosure(L,l->func,nup); lua_setfield(L,-(nup+2),l->name); } lua_pop(L,nup); } static const char*luaL_findtable(lua_State*L,int idx, const char*fname,int szhint){ const char*e; lua_pushvalue(L,idx); do{ e=strchr(fname,'.'); if(e==NULL)e=fname+strlen(fname); lua_pushlstring(L,fname,e-fname); lua_rawget(L,-2); if(lua_isnil(L,-1)){ lua_pop(L,1); lua_createtable(L,0,(*e=='.'?1:szhint)); lua_pushlstring(L,fname,e-fname); lua_pushvalue(L,-2); lua_settable(L,-4); } else if(!lua_istable(L,-1)){ lua_pop(L,2); return fname; } lua_remove(L,-2); fname=e+1; }while(*e=='.'); return NULL; } #define bufflen(B)((B)->p-(B)->buffer) #define bufffree(B)((size_t)(BUFSIZ-bufflen(B))) static int emptybuffer(luaL_Buffer*B){ size_t l=bufflen(B); if(l==0)return 0; else{ lua_pushlstring(B->L,B->buffer,l); B->p=B->buffer; B->lvl++; return 1; } } static void adjuststack(luaL_Buffer*B){ if(B->lvl>1){ lua_State*L=B->L; int toget=1; size_t toplen=lua_strlen(L,-1); do{ size_t l=lua_strlen(L,-(toget+1)); if(B->lvl-toget+1>=(20/2)||toplen>l){ toplen+=l; toget++; } else break; }while(toget<B->lvl); lua_concat(L,toget); B->lvl=B->lvl-toget+1; } } static char*luaL_prepbuffer(luaL_Buffer*B){ if(emptybuffer(B)) adjuststack(B); return B->buffer; } static void luaL_addlstring(luaL_Buffer*B,const char*s,size_t l){ while(l--) luaL_addchar(B,*s++); } static void luaL_pushresult(luaL_Buffer*B){ emptybuffer(B); lua_concat(B->L,B->lvl); B->lvl=1; } static void luaL_addvalue(luaL_Buffer*B){ lua_State*L=B->L; size_t vl; const char*s=lua_tolstring(L,-1,&vl); if(vl<=bufffree(B)){ memcpy(B->p,s,vl); B->p+=vl; lua_pop(L,1); } else{ if(emptybuffer(B)) lua_insert(L,-2); B->lvl++; adjuststack(B); } } static void luaL_buffinit(lua_State*L,luaL_Buffer*B){ B->L=L; B->p=B->buffer; B->lvl=0; } typedef struct LoadF{ int extraline; FILE*f; char buff[BUFSIZ]; }LoadF; static const char*getF(lua_State*L,void*ud,size_t*size){ LoadF*lf=(LoadF*)ud; (void)L; if(lf->extraline){ lf->extraline=0; *size=1; return"\n"; } if(feof(lf->f))return NULL; *size=fread(lf->buff,1,sizeof(lf->buff),lf->f); return(*size>0)?lf->buff:NULL; } static int errfile(lua_State*L,const char*what,int fnameindex){ const char*serr=strerror(errno); const char*filename=lua_tostring(L,fnameindex)+1; lua_pushfstring(L,"cannot %s %s: %s",what,filename,serr); lua_remove(L,fnameindex); return(5+1); } static int luaL_loadfile(lua_State*L,const char*filename){ LoadF lf; int status,readstatus; int c; int fnameindex=lua_gettop(L)+1; lf.extraline=0; if(filename==NULL){ lua_pushliteral(L,"=stdin"); lf.f=stdin; } else{ lua_pushfstring(L,"@%s",filename); lf.f=fopen(filename,"r"); if(lf.f==NULL)return errfile(L,"open",fnameindex); } c=getc(lf.f); if(c=='#'){ lf.extraline=1; while((c=getc(lf.f))!=EOF&&c!='\n'); if(c=='\n')c=getc(lf.f); } if(c=="\033Lua"[0]&&filename){ lf.f=freopen(filename,"rb",lf.f); if(lf.f==NULL)return errfile(L,"reopen",fnameindex); while((c=getc(lf.f))!=EOF&&c!="\033Lua"[0]); lf.extraline=0; } ungetc(c,lf.f); status=lua_load(L,getF,&lf,lua_tostring(L,-1)); readstatus=ferror(lf.f); if(filename)fclose(lf.f); if(readstatus){ lua_settop(L,fnameindex); return errfile(L,"read",fnameindex); } lua_remove(L,fnameindex); return status; } typedef struct LoadS{ const char*s; size_t size; }LoadS; static const char*getS(lua_State*L,void*ud,size_t*size){ LoadS*ls=(LoadS*)ud; (void)L; if(ls->size==0)return NULL; *size=ls->size; ls->size=0; return ls->s; } static int luaL_loadbuffer(lua_State*L,const char*buff,size_t size, const char*name){ LoadS ls; ls.s=buff; ls.size=size; return lua_load(L,getS,&ls,name); } static void*l_alloc(void*ud,void*ptr,size_t osize,size_t nsize){ (void)ud; (void)osize; if(nsize==0){ free(ptr); return NULL; } else return realloc(ptr,nsize); } static int panic(lua_State*L){ (void)L; fprintf(stderr,"PANIC: unprotected error in call to Lua API (%s)\n", lua_tostring(L,-1)); return 0; } static lua_State*luaL_newstate(void){ lua_State*L=lua_newstate(l_alloc,NULL); if(L)lua_atpanic(L,&panic); return L; } static int luaB_tonumber(lua_State*L){ int base=luaL_optint(L,2,10); if(base==10){ luaL_checkany(L,1); if(lua_isnumber(L,1)){ lua_pushnumber(L,lua_tonumber(L,1)); return 1; } } else{ const char*s1=luaL_checkstring(L,1); char*s2; unsigned long n; luaL_argcheck(L,2<=base&&base<=36,2,"base out of range"); n=strtoul(s1,&s2,base); if(s1!=s2){ while(isspace((unsigned char)(*s2)))s2++; if(*s2=='\0'){ lua_pushnumber(L,(lua_Number)n); return 1; } } } lua_pushnil(L); return 1; } static int luaB_error(lua_State*L){ int level=luaL_optint(L,2,1); lua_settop(L,1); if(lua_isstring(L,1)&&level>0){ luaL_where(L,level); lua_pushvalue(L,1); lua_concat(L,2); } return lua_error(L); } static int luaB_setmetatable(lua_State*L){ int t=lua_type(L,2); luaL_checktype(L,1,5); luaL_argcheck(L,t==0||t==5,2, "nil or table expected"); if(luaL_getmetafield(L,1,"__metatable")) luaL_error(L,"cannot change a protected metatable"); lua_settop(L,2); lua_setmetatable(L,1); return 1; } static void getfunc(lua_State*L,int opt){ if(lua_isfunction(L,1))lua_pushvalue(L,1); else{ lua_Debug ar; int level=opt?luaL_optint(L,1,1):luaL_checkint(L,1); luaL_argcheck(L,level>=0,1,"level must be non-negative"); if(lua_getstack(L,level,&ar)==0) luaL_argerror(L,1,"invalid level"); lua_getinfo(L,"f",&ar); if(lua_isnil(L,-1)) luaL_error(L,"no function environment for tail call at level %d", level); } } static int luaB_setfenv(lua_State*L){ luaL_checktype(L,2,5); getfunc(L,0); lua_pushvalue(L,2); if(lua_isnumber(L,1)&&lua_tonumber(L,1)==0){ lua_pushthread(L); lua_insert(L,-2); lua_setfenv(L,-2); return 0; } else if(lua_iscfunction(L,-2)||lua_setfenv(L,-2)==0) luaL_error(L, LUA_QL("setfenv")" cannot change environment of given object"); return 1; } static int luaB_rawget(lua_State*L){ luaL_checktype(L,1,5); luaL_checkany(L,2); lua_settop(L,2); lua_rawget(L,1); return 1; } static int luaB_type(lua_State*L){ luaL_checkany(L,1); lua_pushstring(L,luaL_typename(L,1)); return 1; } static int luaB_next(lua_State*L){ luaL_checktype(L,1,5); lua_settop(L,2); if(lua_next(L,1)) return 2; else{ lua_pushnil(L); return 1; } } static int luaB_pairs(lua_State*L){ luaL_checktype(L,1,5); lua_pushvalue(L,lua_upvalueindex(1)); lua_pushvalue(L,1); lua_pushnil(L); return 3; } static int ipairsaux(lua_State*L){ int i=luaL_checkint(L,2); luaL_checktype(L,1,5); i++; lua_pushinteger(L,i); lua_rawgeti(L,1,i); return(lua_isnil(L,-1))?0:2; } static int luaB_ipairs(lua_State*L){ luaL_checktype(L,1,5); lua_pushvalue(L,lua_upvalueindex(1)); lua_pushvalue(L,1); lua_pushinteger(L,0); return 3; } static int load_aux(lua_State*L,int status){ if(status==0) return 1; else{ lua_pushnil(L); lua_insert(L,-2); return 2; } } static int luaB_loadstring(lua_State*L){ size_t l; const char*s=luaL_checklstring(L,1,&l); const char*chunkname=luaL_optstring(L,2,s); return load_aux(L,luaL_loadbuffer(L,s,l,chunkname)); } static int luaB_loadfile(lua_State*L){ const char*fname=luaL_optstring(L,1,NULL); return load_aux(L,luaL_loadfile(L,fname)); } static int luaB_assert(lua_State*L){ luaL_checkany(L,1); if(!lua_toboolean(L,1)) return luaL_error(L,"%s",luaL_optstring(L,2,"assertion failed!")); return lua_gettop(L); } static int luaB_unpack(lua_State*L){ int i,e,n; luaL_checktype(L,1,5); i=luaL_optint(L,2,1); e=luaL_opt(L,luaL_checkint,3,luaL_getn(L,1)); if(i>e)return 0; n=e-i+1; if(n<=0||!lua_checkstack(L,n)) return luaL_error(L,"too many results to unpack"); lua_rawgeti(L,1,i); while(i++<e) lua_rawgeti(L,1,i); return n; } static int luaB_pcall(lua_State*L){ int status; luaL_checkany(L,1); status=lua_pcall(L,lua_gettop(L)-1,(-1),0); lua_pushboolean(L,(status==0)); lua_insert(L,1); return lua_gettop(L); } static int luaB_newproxy(lua_State*L){ lua_settop(L,1); lua_newuserdata(L,0); if(lua_toboolean(L,1)==0) return 1; else if(lua_isboolean(L,1)){ lua_newtable(L); lua_pushvalue(L,-1); lua_pushboolean(L,1); lua_rawset(L,lua_upvalueindex(1)); } else{ int validproxy=0; if(lua_getmetatable(L,1)){ lua_rawget(L,lua_upvalueindex(1)); validproxy=lua_toboolean(L,-1); lua_pop(L,1); } luaL_argcheck(L,validproxy,1,"boolean or proxy expected"); lua_getmetatable(L,1); } lua_setmetatable(L,2); return 1; } static const luaL_Reg base_funcs[]={ {"assert",luaB_assert}, {"error",luaB_error}, {"loadfile",luaB_loadfile}, {"loadstring",luaB_loadstring}, {"next",luaB_next}, {"pcall",luaB_pcall}, {"rawget",luaB_rawget}, {"setfenv",luaB_setfenv}, {"setmetatable",luaB_setmetatable}, {"tonumber",luaB_tonumber}, {"type",luaB_type}, {"unpack",luaB_unpack}, {NULL,NULL} }; static void auxopen(lua_State*L,const char*name, lua_CFunction f,lua_CFunction u){ lua_pushcfunction(L,u); lua_pushcclosure(L,f,1); lua_setfield(L,-2,name); } static void base_open(lua_State*L){ lua_pushvalue(L,(-10002)); lua_setglobal(L,"_G"); luaL_register(L,"_G",base_funcs); lua_pushliteral(L,"Lua 5.1"); lua_setglobal(L,"_VERSION"); auxopen(L,"ipairs",luaB_ipairs,ipairsaux); auxopen(L,"pairs",luaB_pairs,luaB_next); lua_createtable(L,0,1); lua_pushvalue(L,-1); lua_setmetatable(L,-2); lua_pushliteral(L,"kv"); lua_setfield(L,-2,"__mode"); lua_pushcclosure(L,luaB_newproxy,1); lua_setglobal(L,"newproxy"); } static int luaopen_base(lua_State*L){ base_open(L); return 1; } #define aux_getn(L,n)(luaL_checktype(L,n,5),luaL_getn(L,n)) static int tinsert(lua_State*L){ int e=aux_getn(L,1)+1; int pos; switch(lua_gettop(L)){ case 2:{ pos=e; break; } case 3:{ int i; pos=luaL_checkint(L,2); if(pos>e)e=pos; for(i=e;i>pos;i--){ lua_rawgeti(L,1,i-1); lua_rawseti(L,1,i); } break; } default:{ return luaL_error(L,"wrong number of arguments to "LUA_QL("insert")); } } luaL_setn(L,1,e); lua_rawseti(L,1,pos); return 0; } static int tremove(lua_State*L){ int e=aux_getn(L,1); int pos=luaL_optint(L,2,e); if(!(1<=pos&&pos<=e)) return 0; luaL_setn(L,1,e-1); lua_rawgeti(L,1,pos); for(;pos<e;pos++){ lua_rawgeti(L,1,pos+1); lua_rawseti(L,1,pos); } lua_pushnil(L); lua_rawseti(L,1,e); return 1; } static void addfield(lua_State*L,luaL_Buffer*b,int i){ lua_rawgeti(L,1,i); if(!lua_isstring(L,-1)) luaL_error(L,"invalid value (%s) at index %d in table for " LUA_QL("concat"),luaL_typename(L,-1),i); luaL_addvalue(b); } static int tconcat(lua_State*L){ luaL_Buffer b; size_t lsep; int i,last; const char*sep=luaL_optlstring(L,2,"",&lsep); luaL_checktype(L,1,5); i=luaL_optint(L,3,1); last=luaL_opt(L,luaL_checkint,4,luaL_getn(L,1)); luaL_buffinit(L,&b); for(;i<last;i++){ addfield(L,&b,i); luaL_addlstring(&b,sep,lsep); } if(i==last) addfield(L,&b,i); luaL_pushresult(&b); return 1; } static void set2(lua_State*L,int i,int j){ lua_rawseti(L,1,i); lua_rawseti(L,1,j); } static int sort_comp(lua_State*L,int a,int b){ if(!lua_isnil(L,2)){ int res; lua_pushvalue(L,2); lua_pushvalue(L,a-1); lua_pushvalue(L,b-2); lua_call(L,2,1); res=lua_toboolean(L,-1); lua_pop(L,1); return res; } else return lua_lessthan(L,a,b); } static void auxsort(lua_State*L,int l,int u){ while(l<u){ int i,j; lua_rawgeti(L,1,l); lua_rawgeti(L,1,u); if(sort_comp(L,-1,-2)) set2(L,l,u); else lua_pop(L,2); if(u-l==1)break; i=(l+u)/2; lua_rawgeti(L,1,i); lua_rawgeti(L,1,l); if(sort_comp(L,-2,-1)) set2(L,i,l); else{ lua_pop(L,1); lua_rawgeti(L,1,u); if(sort_comp(L,-1,-2)) set2(L,i,u); else lua_pop(L,2); } if(u-l==2)break; lua_rawgeti(L,1,i); lua_pushvalue(L,-1); lua_rawgeti(L,1,u-1); set2(L,i,u-1); i=l;j=u-1; for(;;){ while(lua_rawgeti(L,1,++i),sort_comp(L,-1,-2)){ if(i>u)luaL_error(L,"invalid order function for sorting"); lua_pop(L,1); } while(lua_rawgeti(L,1,--j),sort_comp(L,-3,-1)){ if(j<l)luaL_error(L,"invalid order function for sorting"); lua_pop(L,1); } if(j<i){ lua_pop(L,3); break; } set2(L,i,j); } lua_rawgeti(L,1,u-1); lua_rawgeti(L,1,i); set2(L,u-1,i); if(i-l<u-i){ j=l;i=i-1;l=i+2; } else{ j=i+1;i=u;u=j-2; } auxsort(L,j,i); } } static int sort(lua_State*L){ int n=aux_getn(L,1); luaL_checkstack(L,40,""); if(!lua_isnoneornil(L,2)) luaL_checktype(L,2,6); lua_settop(L,2); auxsort(L,1,n); return 0; } static const luaL_Reg tab_funcs[]={ {"concat",tconcat}, {"insert",tinsert}, {"remove",tremove}, {"sort",sort}, {NULL,NULL} }; static int luaopen_table(lua_State*L){ luaL_register(L,"table",tab_funcs); return 1; } static const char*const fnames[]={"input","output"}; static int pushresult(lua_State*L,int i,const char*filename){ int en=errno; if(i){ lua_pushboolean(L,1); return 1; } else{ lua_pushnil(L); if(filename) lua_pushfstring(L,"%s: %s",filename,strerror(en)); else lua_pushfstring(L,"%s",strerror(en)); lua_pushinteger(L,en); return 3; } } static void fileerror(lua_State*L,int arg,const char*filename){ lua_pushfstring(L,"%s: %s",filename,strerror(errno)); luaL_argerror(L,arg,lua_tostring(L,-1)); } #define tofilep(L)((FILE**)luaL_checkudata(L,1,"FILE*")) static int io_type(lua_State*L){ void*ud; luaL_checkany(L,1); ud=lua_touserdata(L,1); lua_getfield(L,(-10000),"FILE*"); if(ud==NULL||!lua_getmetatable(L,1)||!lua_rawequal(L,-2,-1)) lua_pushnil(L); else if(*((FILE**)ud)==NULL) lua_pushliteral(L,"closed file"); else lua_pushliteral(L,"file"); return 1; } static FILE*tofile(lua_State*L){ FILE**f=tofilep(L); if(*f==NULL) luaL_error(L,"attempt to use a closed file"); return*f; } static FILE**newfile(lua_State*L){ FILE**pf=(FILE**)lua_newuserdata(L,sizeof(FILE*)); *pf=NULL; luaL_getmetatable(L,"FILE*"); lua_setmetatable(L,-2); return pf; } static int io_noclose(lua_State*L){ lua_pushnil(L); lua_pushliteral(L,"cannot close standard file"); return 2; } static int io_pclose(lua_State*L){ FILE**p=tofilep(L); int ok=lua_pclose(L,*p); *p=NULL; return pushresult(L,ok,NULL); } static int io_fclose(lua_State*L){ FILE**p=tofilep(L); int ok=(fclose(*p)==0); *p=NULL; return pushresult(L,ok,NULL); } static int aux_close(lua_State*L){ lua_getfenv(L,1); lua_getfield(L,-1,"__close"); return(lua_tocfunction(L,-1))(L); } static int io_close(lua_State*L){ if(lua_isnone(L,1)) lua_rawgeti(L,(-10001),2); tofile(L); return aux_close(L); } static int io_gc(lua_State*L){ FILE*f=*tofilep(L); if(f!=NULL) aux_close(L); return 0; } static int io_open(lua_State*L){ const char*filename=luaL_checkstring(L,1); const char*mode=luaL_optstring(L,2,"r"); FILE**pf=newfile(L); *pf=fopen(filename,mode); return(*pf==NULL)?pushresult(L,0,filename):1; } static FILE*getiofile(lua_State*L,int findex){ FILE*f; lua_rawgeti(L,(-10001),findex); f=*(FILE**)lua_touserdata(L,-1); if(f==NULL) luaL_error(L,"standard %s file is closed",fnames[findex-1]); return f; } static int g_iofile(lua_State*L,int f,const char*mode){ if(!lua_isnoneornil(L,1)){ const char*filename=lua_tostring(L,1); if(filename){ FILE**pf=newfile(L); *pf=fopen(filename,mode); if(*pf==NULL) fileerror(L,1,filename); } else{ tofile(L); lua_pushvalue(L,1); } lua_rawseti(L,(-10001),f); } lua_rawgeti(L,(-10001),f); return 1; } static int io_input(lua_State*L){ return g_iofile(L,1,"r"); } static int io_output(lua_State*L){ return g_iofile(L,2,"w"); } static int io_readline(lua_State*L); static void aux_lines(lua_State*L,int idx,int toclose){ lua_pushvalue(L,idx); lua_pushboolean(L,toclose); lua_pushcclosure(L,io_readline,2); } static int f_lines(lua_State*L){ tofile(L); aux_lines(L,1,0); return 1; } static int io_lines(lua_State*L){ if(lua_isnoneornil(L,1)){ lua_rawgeti(L,(-10001),1); return f_lines(L); } else{ const char*filename=luaL_checkstring(L,1); FILE**pf=newfile(L); *pf=fopen(filename,"r"); if(*pf==NULL) fileerror(L,1,filename); aux_lines(L,lua_gettop(L),1); return 1; } } static int read_number(lua_State*L,FILE*f){ lua_Number d; if(fscanf(f,"%lf",&d)==1){ lua_pushnumber(L,d); return 1; } else{ lua_pushnil(L); return 0; } } static int test_eof(lua_State*L,FILE*f){ int c=getc(f); ungetc(c,f); lua_pushlstring(L,NULL,0); return(c!=EOF); } static int read_line(lua_State*L,FILE*f){ luaL_Buffer b; luaL_buffinit(L,&b); for(;;){ size_t l; char*p=luaL_prepbuffer(&b); if(fgets(p,BUFSIZ,f)==NULL){ luaL_pushresult(&b); return(lua_objlen(L,-1)>0); } l=strlen(p); if(l==0||p[l-1]!='\n') luaL_addsize(&b,l); else{ luaL_addsize(&b,l-1); luaL_pushresult(&b); return 1; } } } static int read_chars(lua_State*L,FILE*f,size_t n){ size_t rlen; size_t nr; luaL_Buffer b; luaL_buffinit(L,&b); rlen=BUFSIZ; do{ char*p=luaL_prepbuffer(&b); if(rlen>n)rlen=n; nr=fread(p,sizeof(char),rlen,f); luaL_addsize(&b,nr); n-=nr; }while(n>0&&nr==rlen); luaL_pushresult(&b); return(n==0||lua_objlen(L,-1)>0); } static int g_read(lua_State*L,FILE*f,int first){ int nargs=lua_gettop(L)-1; int success; int n; clearerr(f); if(nargs==0){ success=read_line(L,f); n=first+1; } else{ luaL_checkstack(L,nargs+20,"too many arguments"); success=1; for(n=first;nargs--&&success;n++){ if(lua_type(L,n)==3){ size_t l=(size_t)lua_tointeger(L,n); success=(l==0)?test_eof(L,f):read_chars(L,f,l); } else{ const char*p=lua_tostring(L,n); luaL_argcheck(L,p&&p[0]=='*',n,"invalid option"); switch(p[1]){ case'n': success=read_number(L,f); break; case'l': success=read_line(L,f); break; case'a': read_chars(L,f,~((size_t)0)); success=1; break; default: return luaL_argerror(L,n,"invalid format"); } } } } if(ferror(f)) return pushresult(L,0,NULL); if(!success){ lua_pop(L,1); lua_pushnil(L); } return n-first; } static int io_read(lua_State*L){ return g_read(L,getiofile(L,1),1); } static int f_read(lua_State*L){ return g_read(L,tofile(L),2); } static int io_readline(lua_State*L){ FILE*f=*(FILE**)lua_touserdata(L,lua_upvalueindex(1)); int sucess; if(f==NULL) luaL_error(L,"file is already closed"); sucess=read_line(L,f); if(ferror(f)) return luaL_error(L,"%s",strerror(errno)); if(sucess)return 1; else{ if(lua_toboolean(L,lua_upvalueindex(2))){ lua_settop(L,0); lua_pushvalue(L,lua_upvalueindex(1)); aux_close(L); } return 0; } } static int g_write(lua_State*L,FILE*f,int arg){ int nargs=lua_gettop(L)-1; int status=1; for(;nargs--;arg++){ if(lua_type(L,arg)==3){ status=status&& fprintf(f,"%.14g",lua_tonumber(L,arg))>0; } else{ size_t l; const char*s=luaL_checklstring(L,arg,&l); status=status&&(fwrite(s,sizeof(char),l,f)==l); } } return pushresult(L,status,NULL); } static int io_write(lua_State*L){ return g_write(L,getiofile(L,2),1); } static int f_write(lua_State*L){ return g_write(L,tofile(L),2); } static int io_flush(lua_State*L){ return pushresult(L,fflush(getiofile(L,2))==0,NULL); } static int f_flush(lua_State*L){ return pushresult(L,fflush(tofile(L))==0,NULL); } static const luaL_Reg iolib[]={ {"close",io_close}, {"flush",io_flush}, {"input",io_input}, {"lines",io_lines}, {"open",io_open}, {"output",io_output}, {"read",io_read}, {"type",io_type}, {"write",io_write}, {NULL,NULL} }; static const luaL_Reg flib[]={ {"close",io_close}, {"flush",f_flush}, {"lines",f_lines}, {"read",f_read}, {"write",f_write}, {"__gc",io_gc}, {NULL,NULL} }; static void createmeta(lua_State*L){ luaL_newmetatable(L,"FILE*"); lua_pushvalue(L,-1); lua_setfield(L,-2,"__index"); luaL_register(L,NULL,flib); } static void createstdfile(lua_State*L,FILE*f,int k,const char*fname){ *newfile(L)=f; if(k>0){ lua_pushvalue(L,-1); lua_rawseti(L,(-10001),k); } lua_pushvalue(L,-2); lua_setfenv(L,-2); lua_setfield(L,-3,fname); } static void newfenv(lua_State*L,lua_CFunction cls){ lua_createtable(L,0,1); lua_pushcfunction(L,cls); lua_setfield(L,-2,"__close"); } static int luaopen_io(lua_State*L){ createmeta(L); newfenv(L,io_fclose); lua_replace(L,(-10001)); luaL_register(L,"io",iolib); newfenv(L,io_noclose); createstdfile(L,stdin,1,"stdin"); createstdfile(L,stdout,2,"stdout"); createstdfile(L,stderr,0,"stderr"); lua_pop(L,1); lua_getfield(L,-1,"popen"); newfenv(L,io_pclose); lua_setfenv(L,-2); lua_pop(L,1); return 1; } static int os_pushresult(lua_State*L,int i,const char*filename){ int en=errno; if(i){ lua_pushboolean(L,1); return 1; } else{ lua_pushnil(L); lua_pushfstring(L,"%s: %s",filename,strerror(en)); lua_pushinteger(L,en); return 3; } } static int os_remove(lua_State*L){ const char*filename=luaL_checkstring(L,1); return os_pushresult(L,remove(filename)==0,filename); } static int os_exit(lua_State*L){ exit(luaL_optint(L,1,EXIT_SUCCESS)); } static const luaL_Reg syslib[]={ {"exit",os_exit}, {"remove",os_remove}, {NULL,NULL} }; static int luaopen_os(lua_State*L){ luaL_register(L,"os",syslib); return 1; } #define uchar(c)((unsigned char)(c)) static ptrdiff_t posrelat(ptrdiff_t pos,size_t len){ if(pos<0)pos+=(ptrdiff_t)len+1; return(pos>=0)?pos:0; } static int str_sub(lua_State*L){ size_t l; const char*s=luaL_checklstring(L,1,&l); ptrdiff_t start=posrelat(luaL_checkinteger(L,2),l); ptrdiff_t end=posrelat(luaL_optinteger(L,3,-1),l); if(start<1)start=1; if(end>(ptrdiff_t)l)end=(ptrdiff_t)l; if(start<=end) lua_pushlstring(L,s+start-1,end-start+1); else lua_pushliteral(L,""); return 1; } static int str_lower(lua_State*L){ size_t l; size_t i; luaL_Buffer b; const char*s=luaL_checklstring(L,1,&l); luaL_buffinit(L,&b); for(i=0;i<l;i++) luaL_addchar(&b,tolower(uchar(s[i]))); luaL_pushresult(&b); return 1; } static int str_upper(lua_State*L){ size_t l; size_t i; luaL_Buffer b; const char*s=luaL_checklstring(L,1,&l); luaL_buffinit(L,&b); for(i=0;i<l;i++) luaL_addchar(&b,toupper(uchar(s[i]))); luaL_pushresult(&b); return 1; } static int str_rep(lua_State*L){ size_t l; luaL_Buffer b; const char*s=luaL_checklstring(L,1,&l); int n=luaL_checkint(L,2); luaL_buffinit(L,&b); while(n-->0) luaL_addlstring(&b,s,l); luaL_pushresult(&b); return 1; } static int str_byte(lua_State*L){ size_t l; const char*s=luaL_checklstring(L,1,&l); ptrdiff_t posi=posrelat(luaL_optinteger(L,2,1),l); ptrdiff_t pose=posrelat(luaL_optinteger(L,3,posi),l); int n,i; if(posi<=0)posi=1; if((size_t)pose>l)pose=l; if(posi>pose)return 0; n=(int)(pose-posi+1); if(posi+n<=pose) luaL_error(L,"string slice too long"); luaL_checkstack(L,n,"string slice too long"); for(i=0;i<n;i++) lua_pushinteger(L,uchar(s[posi+i-1])); return n; } static int str_char(lua_State*L){ int n=lua_gettop(L); int i; luaL_Buffer b; luaL_buffinit(L,&b); for(i=1;i<=n;i++){ int c=luaL_checkint(L,i); luaL_argcheck(L,uchar(c)==c,i,"invalid value"); luaL_addchar(&b,uchar(c)); } luaL_pushresult(&b); return 1; } typedef struct MatchState{ const char*src_init; const char*src_end; lua_State*L; int level; struct{ const char*init; ptrdiff_t len; }capture[32]; }MatchState; static int check_capture(MatchState*ms,int l){ l-='1'; if(l<0||l>=ms->level||ms->capture[l].len==(-1)) return luaL_error(ms->L,"invalid capture index"); return l; } static int capture_to_close(MatchState*ms){ int level=ms->level; for(level--;level>=0;level--) if(ms->capture[level].len==(-1))return level; return luaL_error(ms->L,"invalid pattern capture"); } static const char*classend(MatchState*ms,const char*p){ switch(*p++){ case'%':{ if(*p=='\0') luaL_error(ms->L,"malformed pattern (ends with "LUA_QL("%%")")"); return p+1; } case'[':{ if(*p=='^')p++; do{ if(*p=='\0') luaL_error(ms->L,"malformed pattern (missing "LUA_QL("]")")"); if(*(p++)=='%'&&*p!='\0') p++; }while(*p!=']'); return p+1; } default:{ return p; } } } static int match_class(int c,int cl){ int res; switch(tolower(cl)){ case'a':res=isalpha(c);break; case'c':res=iscntrl(c);break; case'd':res=isdigit(c);break; case'l':res=islower(c);break; case'p':res=ispunct(c);break; case's':res=isspace(c);break; case'u':res=isupper(c);break; case'w':res=isalnum(c);break; case'x':res=isxdigit(c);break; case'z':res=(c==0);break; default:return(cl==c); } return(islower(cl)?res:!res); } static int matchbracketclass(int c,const char*p,const char*ec){ int sig=1; if(*(p+1)=='^'){ sig=0; p++; } while(++p<ec){ if(*p=='%'){ p++; if(match_class(c,uchar(*p))) return sig; } else if((*(p+1)=='-')&&(p+2<ec)){ p+=2; if(uchar(*(p-2))<=c&&c<=uchar(*p)) return sig; } else if(uchar(*p)==c)return sig; } return!sig; } static int singlematch(int c,const char*p,const char*ep){ switch(*p){ case'.':return 1; case'%':return match_class(c,uchar(*(p+1))); case'[':return matchbracketclass(c,p,ep-1); default:return(uchar(*p)==c); } } static const char*match(MatchState*ms,const char*s,const char*p); static const char*matchbalance(MatchState*ms,const char*s, const char*p){ if(*p==0||*(p+1)==0) luaL_error(ms->L,"unbalanced pattern"); if(*s!=*p)return NULL; else{ int b=*p; int e=*(p+1); int cont=1; while(++s<ms->src_end){ if(*s==e){ if(--cont==0)return s+1; } else if(*s==b)cont++; } } return NULL; } static const char*max_expand(MatchState*ms,const char*s, const char*p,const char*ep){ ptrdiff_t i=0; while((s+i)<ms->src_end&&singlematch(uchar(*(s+i)),p,ep)) i++; while(i>=0){ const char*res=match(ms,(s+i),ep+1); if(res)return res; i--; } return NULL; } static const char*min_expand(MatchState*ms,const char*s, const char*p,const char*ep){ for(;;){ const char*res=match(ms,s,ep+1); if(res!=NULL) return res; else if(s<ms->src_end&&singlematch(uchar(*s),p,ep)) s++; else return NULL; } } static const char*start_capture(MatchState*ms,const char*s, const char*p,int what){ const char*res; int level=ms->level; if(level>=32)luaL_error(ms->L,"too many captures"); ms->capture[level].init=s; ms->capture[level].len=what; ms->level=level+1; if((res=match(ms,s,p))==NULL) ms->level--; return res; } static const char*end_capture(MatchState*ms,const char*s, const char*p){ int l=capture_to_close(ms); const char*res; ms->capture[l].len=s-ms->capture[l].init; if((res=match(ms,s,p))==NULL) ms->capture[l].len=(-1); return res; } static const char*match_capture(MatchState*ms,const char*s,int l){ size_t len; l=check_capture(ms,l); len=ms->capture[l].len; if((size_t)(ms->src_end-s)>=len&& memcmp(ms->capture[l].init,s,len)==0) return s+len; else return NULL; } static const char*match(MatchState*ms,const char*s,const char*p){ init: switch(*p){ case'(':{ if(*(p+1)==')') return start_capture(ms,s,p+2,(-2)); else return start_capture(ms,s,p+1,(-1)); } case')':{ return end_capture(ms,s,p+1); } case'%':{ switch(*(p+1)){ case'b':{ s=matchbalance(ms,s,p+2); if(s==NULL)return NULL; p+=4;goto init; } case'f':{ const char*ep;char previous; p+=2; if(*p!='[') luaL_error(ms->L,"missing "LUA_QL("[")" after " LUA_QL("%%f")" in pattern"); ep=classend(ms,p); previous=(s==ms->src_init)?'\0':*(s-1); if(matchbracketclass(uchar(previous),p,ep-1)|| !matchbracketclass(uchar(*s),p,ep-1))return NULL; p=ep;goto init; } default:{ if(isdigit(uchar(*(p+1)))){ s=match_capture(ms,s,uchar(*(p+1))); if(s==NULL)return NULL; p+=2;goto init; } goto dflt; } } } case'\0':{ return s; } case'$':{ if(*(p+1)=='\0') return(s==ms->src_end)?s:NULL; else goto dflt; } default:dflt:{ const char*ep=classend(ms,p); int m=s<ms->src_end&&singlematch(uchar(*s),p,ep); switch(*ep){ case'?':{ const char*res; if(m&&((res=match(ms,s+1,ep+1))!=NULL)) return res; p=ep+1;goto init; } case'*':{ return max_expand(ms,s,p,ep); } case'+':{ return(m?max_expand(ms,s+1,p,ep):NULL); } case'-':{ return min_expand(ms,s,p,ep); } default:{ if(!m)return NULL; s++;p=ep;goto init; } } } } } static const char*lmemfind(const char*s1,size_t l1, const char*s2,size_t l2){ if(l2==0)return s1; else if(l2>l1)return NULL; else{ const char*init; l2--; l1=l1-l2; while(l1>0&&(init=(const char*)memchr(s1,*s2,l1))!=NULL){ init++; if(memcmp(init,s2+1,l2)==0) return init-1; else{ l1-=init-s1; s1=init; } } return NULL; } } static void push_onecapture(MatchState*ms,int i,const char*s, const char*e){ if(i>=ms->level){ if(i==0) lua_pushlstring(ms->L,s,e-s); else luaL_error(ms->L,"invalid capture index"); } else{ ptrdiff_t l=ms->capture[i].len; if(l==(-1))luaL_error(ms->L,"unfinished capture"); if(l==(-2)) lua_pushinteger(ms->L,ms->capture[i].init-ms->src_init+1); else lua_pushlstring(ms->L,ms->capture[i].init,l); } } static int push_captures(MatchState*ms,const char*s,const char*e){ int i; int nlevels=(ms->level==0&&s)?1:ms->level; luaL_checkstack(ms->L,nlevels,"too many captures"); for(i=0;i<nlevels;i++) push_onecapture(ms,i,s,e); return nlevels; } static int str_find_aux(lua_State*L,int find){ size_t l1,l2; const char*s=luaL_checklstring(L,1,&l1); const char*p=luaL_checklstring(L,2,&l2); ptrdiff_t init=posrelat(luaL_optinteger(L,3,1),l1)-1; if(init<0)init=0; else if((size_t)(init)>l1)init=(ptrdiff_t)l1; if(find&&(lua_toboolean(L,4)|| strpbrk(p,"^$*+?.([%-")==NULL)){ const char*s2=lmemfind(s+init,l1-init,p,l2); if(s2){ lua_pushinteger(L,s2-s+1); lua_pushinteger(L,s2-s+l2); return 2; } } else{ MatchState ms; int anchor=(*p=='^')?(p++,1):0; const char*s1=s+init; ms.L=L; ms.src_init=s; ms.src_end=s+l1; do{ const char*res; ms.level=0; if((res=match(&ms,s1,p))!=NULL){ if(find){ lua_pushinteger(L,s1-s+1); lua_pushinteger(L,res-s); return push_captures(&ms,NULL,0)+2; } else return push_captures(&ms,s1,res); } }while(s1++<ms.src_end&&!anchor); } lua_pushnil(L); return 1; } static int str_find(lua_State*L){ return str_find_aux(L,1); } static int str_match(lua_State*L){ return str_find_aux(L,0); } static int gmatch_aux(lua_State*L){ MatchState ms; size_t ls; const char*s=lua_tolstring(L,lua_upvalueindex(1),&ls); const char*p=lua_tostring(L,lua_upvalueindex(2)); const char*src; ms.L=L; ms.src_init=s; ms.src_end=s+ls; for(src=s+(size_t)lua_tointeger(L,lua_upvalueindex(3)); src<=ms.src_end; src++){ const char*e; ms.level=0; if((e=match(&ms,src,p))!=NULL){ lua_Integer newstart=e-s; if(e==src)newstart++; lua_pushinteger(L,newstart); lua_replace(L,lua_upvalueindex(3)); return push_captures(&ms,src,e); } } return 0; } static int gmatch(lua_State*L){ luaL_checkstring(L,1); luaL_checkstring(L,2); lua_settop(L,2); lua_pushinteger(L,0); lua_pushcclosure(L,gmatch_aux,3); return 1; } static void add_s(MatchState*ms,luaL_Buffer*b,const char*s, const char*e){ size_t l,i; const char*news=lua_tolstring(ms->L,3,&l); for(i=0;i<l;i++){ if(news[i]!='%') luaL_addchar(b,news[i]); else{ i++; if(!isdigit(uchar(news[i]))) luaL_addchar(b,news[i]); else if(news[i]=='0') luaL_addlstring(b,s,e-s); else{ push_onecapture(ms,news[i]-'1',s,e); luaL_addvalue(b); } } } } static void add_value(MatchState*ms,luaL_Buffer*b,const char*s, const char*e){ lua_State*L=ms->L; switch(lua_type(L,3)){ case 3: case 4:{ add_s(ms,b,s,e); return; } case 6:{ int n; lua_pushvalue(L,3); n=push_captures(ms,s,e); lua_call(L,n,1); break; } case 5:{ push_onecapture(ms,0,s,e); lua_gettable(L,3); break; } } if(!lua_toboolean(L,-1)){ lua_pop(L,1); lua_pushlstring(L,s,e-s); } else if(!lua_isstring(L,-1)) luaL_error(L,"invalid replacement value (a %s)",luaL_typename(L,-1)); luaL_addvalue(b); } static int str_gsub(lua_State*L){ size_t srcl; const char*src=luaL_checklstring(L,1,&srcl); const char*p=luaL_checkstring(L,2); int tr=lua_type(L,3); int max_s=luaL_optint(L,4,srcl+1); int anchor=(*p=='^')?(p++,1):0; int n=0; MatchState ms; luaL_Buffer b; luaL_argcheck(L,tr==3||tr==4|| tr==6||tr==5,3, "string/function/table expected"); luaL_buffinit(L,&b); ms.L=L; ms.src_init=src; ms.src_end=src+srcl; while(n<max_s){ const char*e; ms.level=0; e=match(&ms,src,p); if(e){ n++; add_value(&ms,&b,src,e); } if(e&&e>src) src=e; else if(src<ms.src_end) luaL_addchar(&b,*src++); else break; if(anchor)break; } luaL_addlstring(&b,src,ms.src_end-src); luaL_pushresult(&b); lua_pushinteger(L,n); return 2; } static void addquoted(lua_State*L,luaL_Buffer*b,int arg){ size_t l; const char*s=luaL_checklstring(L,arg,&l); luaL_addchar(b,'"'); while(l--){ switch(*s){ case'"':case'\\':case'\n':{ luaL_addchar(b,'\\'); luaL_addchar(b,*s); break; } case'\r':{ luaL_addlstring(b,"\\r",2); break; } case'\0':{ luaL_addlstring(b,"\\000",4); break; } default:{ luaL_addchar(b,*s); break; } } s++; } luaL_addchar(b,'"'); } static const char*scanformat(lua_State*L,const char*strfrmt,char*form){ const char*p=strfrmt; while(*p!='\0'&&strchr("-+ #0",*p)!=NULL)p++; if((size_t)(p-strfrmt)>=sizeof("-+ #0")) luaL_error(L,"invalid format (repeated flags)"); if(isdigit(uchar(*p)))p++; if(isdigit(uchar(*p)))p++; if(*p=='.'){ p++; if(isdigit(uchar(*p)))p++; if(isdigit(uchar(*p)))p++; } if(isdigit(uchar(*p))) luaL_error(L,"invalid format (width or precision too long)"); *(form++)='%'; strncpy(form,strfrmt,p-strfrmt+1); form+=p-strfrmt+1; *form='\0'; return p; } static void addintlen(char*form){ size_t l=strlen(form); char spec=form[l-1]; strcpy(form+l-1,"l"); form[l+sizeof("l")-2]=spec; form[l+sizeof("l")-1]='\0'; } static int str_format(lua_State*L){ int top=lua_gettop(L); int arg=1; size_t sfl; const char*strfrmt=luaL_checklstring(L,arg,&sfl); const char*strfrmt_end=strfrmt+sfl; luaL_Buffer b; luaL_buffinit(L,&b); while(strfrmt<strfrmt_end){ if(*strfrmt!='%') luaL_addchar(&b,*strfrmt++); else if(*++strfrmt=='%') luaL_addchar(&b,*strfrmt++); else{ char form[(sizeof("-+ #0")+sizeof("l")+10)]; char buff[512]; if(++arg>top) luaL_argerror(L,arg,"no value"); strfrmt=scanformat(L,strfrmt,form); switch(*strfrmt++){ case'c':{ sprintf(buff,form,(int)luaL_checknumber(L,arg)); break; } case'd':case'i':{ addintlen(form); sprintf(buff,form,(long)luaL_checknumber(L,arg)); break; } case'o':case'u':case'x':case'X':{ addintlen(form); sprintf(buff,form,(unsigned long)luaL_checknumber(L,arg)); break; } case'e':case'E':case'f': case'g':case'G':{ sprintf(buff,form,(double)luaL_checknumber(L,arg)); break; } case'q':{ addquoted(L,&b,arg); continue; } case's':{ size_t l; const char*s=luaL_checklstring(L,arg,&l); if(!strchr(form,'.')&&l>=100){ lua_pushvalue(L,arg); luaL_addvalue(&b); continue; } else{ sprintf(buff,form,s); break; } } default:{ return luaL_error(L,"invalid option "LUA_QL("%%%c")" to " LUA_QL("format"),*(strfrmt-1)); } } luaL_addlstring(&b,buff,strlen(buff)); } } luaL_pushresult(&b); return 1; } static const luaL_Reg strlib[]={ {"byte",str_byte}, {"char",str_char}, {"find",str_find}, {"format",str_format}, {"gmatch",gmatch}, {"gsub",str_gsub}, {"lower",str_lower}, {"match",str_match}, {"rep",str_rep}, {"sub",str_sub}, {"upper",str_upper}, {NULL,NULL} }; static void createmetatable(lua_State*L){ lua_createtable(L,0,1); lua_pushliteral(L,""); lua_pushvalue(L,-2); lua_setmetatable(L,-2); lua_pop(L,1); lua_pushvalue(L,-2); lua_setfield(L,-2,"__index"); lua_pop(L,1); } static int luaopen_string(lua_State*L){ luaL_register(L,"string",strlib); createmetatable(L); return 1; } static const luaL_Reg lualibs[]={ {"",luaopen_base}, {"table",luaopen_table}, {"io",luaopen_io}, {"os",luaopen_os}, {"string",luaopen_string}, {NULL,NULL} }; static void luaL_openlibs(lua_State*L){ const luaL_Reg*lib=lualibs; for(;lib->func;lib++){ lua_pushcfunction(L,lib->func); lua_pushstring(L,lib->name); lua_call(L,1,0); } } typedef unsigned int UB; static UB barg(lua_State*L,int idx){ union{lua_Number n;U64 b;}bn; bn.n=lua_tonumber(L,idx)+6755399441055744.0; if(bn.n==0.0&&!lua_isnumber(L,idx))luaL_typerror(L,idx,"number"); return(UB)bn.b; } #define BRET(b)lua_pushnumber(L,(lua_Number)(int)(b));return 1; static int tobit(lua_State*L){ BRET(barg(L,1))} static int bnot(lua_State*L){ BRET(~barg(L,1))} static int band(lua_State*L){ int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b&=barg(L,i);BRET(b)} static int bor(lua_State*L){ int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b|=barg(L,i);BRET(b)} static int bxor(lua_State*L){ int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b^=barg(L,i);BRET(b)} static int lshift(lua_State*L){ UB b=barg(L,1),n=barg(L,2)&31;BRET(b<<n)} static int rshift(lua_State*L){ UB b=barg(L,1),n=barg(L,2)&31;BRET(b>>n)} static int arshift(lua_State*L){ UB b=barg(L,1),n=barg(L,2)&31;BRET((int)b>>n)} static int rol(lua_State*L){ UB b=barg(L,1),n=barg(L,2)&31;BRET((b<<n)|(b>>(32-n)))} static int ror(lua_State*L){ UB b=barg(L,1),n=barg(L,2)&31;BRET((b>>n)|(b<<(32-n)))} static int bswap(lua_State*L){ UB b=barg(L,1);b=(b>>24)|((b>>8)&0xff00)|((b&0xff00)<<8)|(b<<24);BRET(b)} static int tohex(lua_State*L){ UB b=barg(L,1); int n=lua_isnone(L,2)?8:(int)barg(L,2); const char*hexdigits="0123456789abcdef"; char buf[8]; int i; if(n<0){n=-n;hexdigits="0123456789ABCDEF";} if(n>8)n=8; for(i=(int)n;--i>=0;){buf[i]=hexdigits[b&15];b>>=4;} lua_pushlstring(L,buf,(size_t)n); return 1; } static const struct luaL_Reg bitlib[]={ {"tobit",tobit}, {"bnot",bnot}, {"band",band}, {"bor",bor}, {"bxor",bxor}, {"lshift",lshift}, {"rshift",rshift}, {"arshift",arshift}, {"rol",rol}, {"ror",ror}, {"bswap",bswap}, {"tohex",tohex}, {NULL,NULL} }; int main(int argc,char**argv){ lua_State*L=luaL_newstate(); int i; luaL_openlibs(L); luaL_register(L,"bit",bitlib); if(argc<2)return sizeof(void*); lua_createtable(L,0,1); lua_pushstring(L,argv[1]); lua_rawseti(L,-2,0); lua_setglobal(L,"arg"); if(luaL_loadfile(L,argv[1])) goto err; for(i=2;i<argc;i++) lua_pushstring(L,argv[i]); if(lua_pcall(L,argc-2,0,0)){ err: fprintf(stderr,"Error: %s\n",lua_tostring(L,-1)); return 1; } lua_close(L); return 0; }
xLua/build/luajit-2.1.0b2/src/host/minilua.c/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/host/minilua.c", "repo_id": "xLua", "token_count": 85658 }
2,101
/* ** Bit manipulation library. ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ #define lib_bit_c #define LUA_LIB #include "lua.h" #include "lauxlib.h" #include "lualib.h" #include "lj_obj.h" #include "lj_err.h" #include "lj_buf.h" #include "lj_strscan.h" #include "lj_strfmt.h" #if LJ_HASFFI #include "lj_ctype.h" #include "lj_cdata.h" #include "lj_cconv.h" #include "lj_carith.h" #endif #include "lj_ff.h" #include "lj_lib.h" /* ------------------------------------------------------------------------ */ #define LJLIB_MODULE_bit #if LJ_HASFFI static int bit_result64(lua_State *L, CTypeID id, uint64_t x) { GCcdata *cd = lj_cdata_new_(L, id, 8); *(uint64_t *)cdataptr(cd) = x; setcdataV(L, L->base-1-LJ_FR2, cd); return FFH_RES(1); } #else static int32_t bit_checkbit(lua_State *L, int narg) { TValue *o = L->base + narg-1; if (!(o < L->top && lj_strscan_numberobj(o))) lj_err_argt(L, narg, LUA_TNUMBER); if (LJ_LIKELY(tvisint(o))) { return intV(o); } else { int32_t i = lj_num2bit(numV(o)); if (LJ_DUALNUM) setintV(o, i); return i; } } #endif LJLIB_ASM(bit_tobit) LJLIB_REC(bit_tobit) { #if LJ_HASFFI CTypeID id = 0; setintV(L->base-1-LJ_FR2, (int32_t)lj_carith_check64(L, 1, &id)); return FFH_RES(1); #else lj_lib_checknumber(L, 1); return FFH_RETRY; #endif } LJLIB_ASM(bit_bnot) LJLIB_REC(bit_unary IR_BNOT) { #if LJ_HASFFI CTypeID id = 0; uint64_t x = lj_carith_check64(L, 1, &id); return id ? bit_result64(L, id, ~x) : FFH_RETRY; #else lj_lib_checknumber(L, 1); return FFH_RETRY; #endif } LJLIB_ASM(bit_bswap) LJLIB_REC(bit_unary IR_BSWAP) { #if LJ_HASFFI CTypeID id = 0; uint64_t x = lj_carith_check64(L, 1, &id); return id ? bit_result64(L, id, lj_bswap64(x)) : FFH_RETRY; #else lj_lib_checknumber(L, 1); return FFH_RETRY; #endif } LJLIB_ASM(bit_lshift) LJLIB_REC(bit_shift IR_BSHL) { #if LJ_HASFFI CTypeID id = 0, id2 = 0; uint64_t x = lj_carith_check64(L, 1, &id); int32_t sh = (int32_t)lj_carith_check64(L, 2, &id2); if (id) { x = lj_carith_shift64(x, sh, curr_func(L)->c.ffid - (int)FF_bit_lshift); return bit_result64(L, id, x); } if (id2) setintV(L->base+1, sh); return FFH_RETRY; #else lj_lib_checknumber(L, 1); bit_checkbit(L, 2); return FFH_RETRY; #endif } LJLIB_ASM_(bit_rshift) LJLIB_REC(bit_shift IR_BSHR) LJLIB_ASM_(bit_arshift) LJLIB_REC(bit_shift IR_BSAR) LJLIB_ASM_(bit_rol) LJLIB_REC(bit_shift IR_BROL) LJLIB_ASM_(bit_ror) LJLIB_REC(bit_shift IR_BROR) LJLIB_ASM(bit_band) LJLIB_REC(bit_nary IR_BAND) { #if LJ_HASFFI CTypeID id = 0; TValue *o = L->base, *top = L->top; int i = 0; do { lj_carith_check64(L, ++i, &id); } while (++o < top); if (id) { CTState *cts = ctype_cts(L); CType *ct = ctype_get(cts, id); int op = curr_func(L)->c.ffid - (int)FF_bit_bor; uint64_t x, y = op >= 0 ? 0 : ~(uint64_t)0; o = L->base; do { lj_cconv_ct_tv(cts, ct, (uint8_t *)&x, o, 0); if (op < 0) y &= x; else if (op == 0) y |= x; else y ^= x; } while (++o < top); return bit_result64(L, id, y); } return FFH_RETRY; #else int i = 0; do { lj_lib_checknumber(L, ++i); } while (L->base+i < L->top); return FFH_RETRY; #endif } LJLIB_ASM_(bit_bor) LJLIB_REC(bit_nary IR_BOR) LJLIB_ASM_(bit_bxor) LJLIB_REC(bit_nary IR_BXOR) /* ------------------------------------------------------------------------ */ LJLIB_CF(bit_tohex) LJLIB_REC(.) { #if LJ_HASFFI CTypeID id = 0, id2 = 0; uint64_t b = lj_carith_check64(L, 1, &id); int32_t n = L->base+1>=L->top ? (id ? 16 : 8) : (int32_t)lj_carith_check64(L, 2, &id2); #else uint32_t b = (uint32_t)bit_checkbit(L, 1); int32_t n = L->base+1>=L->top ? 8 : bit_checkbit(L, 2); #endif SBuf *sb = lj_buf_tmp_(L); SFormat sf = (STRFMT_UINT|STRFMT_T_HEX); if (n < 0) { n = -n; sf |= STRFMT_F_UPPER; } sf |= ((SFormat)((n+1)&255) << STRFMT_SH_PREC); #if LJ_HASFFI if (n < 16) b &= ((uint64_t)1 << 4*n)-1; #else if (n < 8) b &= (1u << 4*n)-1; #endif sb = lj_strfmt_putfxint(sb, sf, b); setstrV(L, L->top-1, lj_buf_str(L, sb)); lj_gc_check(L); return 1; } /* ------------------------------------------------------------------------ */ #include "lj_libdef.h" LUALIB_API int luaopen_bit(lua_State *L) { LJ_LIB_REG(L, LUA_BITLIBNAME, bit); return 1; }
xLua/build/luajit-2.1.0b2/src/lib_bit.c/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lib_bit.c", "repo_id": "xLua", "token_count": 2230 }
2,102
/* ** IR assembler (SSA IR -> machine code). ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ #define lj_asm_c #define LUA_CORE #include "lj_obj.h" #if LJ_HASJIT #include "lj_gc.h" #include "lj_str.h" #include "lj_tab.h" #include "lj_frame.h" #if LJ_HASFFI #include "lj_ctype.h" #endif #include "lj_ir.h" #include "lj_jit.h" #include "lj_ircall.h" #include "lj_iropt.h" #include "lj_mcode.h" #include "lj_iropt.h" #include "lj_trace.h" #include "lj_snap.h" #include "lj_asm.h" #include "lj_dispatch.h" #include "lj_vm.h" #include "lj_target.h" #ifdef LUA_USE_ASSERT #include <stdio.h> #endif /* -- Assembler state and common macros ----------------------------------- */ /* Assembler state. */ typedef struct ASMState { RegCost cost[RID_MAX]; /* Reference and blended allocation cost for regs. */ MCode *mcp; /* Current MCode pointer (grows down). */ MCode *mclim; /* Lower limit for MCode memory + red zone. */ #ifdef LUA_USE_ASSERT MCode *mcp_prev; /* Red zone overflow check. */ #endif IRIns *ir; /* Copy of pointer to IR instructions/constants. */ jit_State *J; /* JIT compiler state. */ #if LJ_TARGET_X86ORX64 x86ModRM mrm; /* Fused x86 address operand. */ #endif RegSet freeset; /* Set of free registers. */ RegSet modset; /* Set of registers modified inside the loop. */ RegSet weakset; /* Set of weakly referenced registers. */ RegSet phiset; /* Set of PHI registers. */ uint32_t flags; /* Copy of JIT compiler flags. */ int loopinv; /* Loop branch inversion (0:no, 1:yes, 2:yes+CC_P). */ int32_t evenspill; /* Next even spill slot. */ int32_t oddspill; /* Next odd spill slot (or 0). */ IRRef curins; /* Reference of current instruction. */ IRRef stopins; /* Stop assembly before hitting this instruction. */ IRRef orignins; /* Original T->nins. */ IRRef snapref; /* Current snapshot is active after this reference. */ IRRef snaprename; /* Rename highwater mark for snapshot check. */ SnapNo snapno; /* Current snapshot number. */ SnapNo loopsnapno; /* Loop snapshot number. */ IRRef fuseref; /* Fusion limit (loopref, 0 or FUSE_DISABLED). */ IRRef sectref; /* Section base reference (loopref or 0). */ IRRef loopref; /* Reference of LOOP instruction (or 0). */ BCReg topslot; /* Number of slots for stack check (unless 0). */ int32_t gcsteps; /* Accumulated number of GC steps (per section). */ GCtrace *T; /* Trace to assemble. */ GCtrace *parent; /* Parent trace (or NULL). */ MCode *mcbot; /* Bottom of reserved MCode. */ MCode *mctop; /* Top of generated MCode. */ MCode *mcloop; /* Pointer to loop MCode (or NULL). */ MCode *invmcp; /* Points to invertible loop branch (or NULL). */ MCode *flagmcp; /* Pending opportunity to merge flag setting ins. */ MCode *realign; /* Realign loop if not NULL. */ #ifdef RID_NUM_KREF int32_t krefk[RID_NUM_KREF]; #endif IRRef1 phireg[RID_MAX]; /* PHI register references. */ uint16_t parentmap[LJ_MAX_JSLOTS]; /* Parent instruction to RegSP map. */ } ASMState; #define IR(ref) (&as->ir[(ref)]) #define ASMREF_TMP1 REF_TRUE /* Temp. register. */ #define ASMREF_TMP2 REF_FALSE /* Temp. register. */ #define ASMREF_L REF_NIL /* Stores register for L. */ /* Check for variant to invariant references. */ #define iscrossref(as, ref) ((ref) < as->sectref) /* Inhibit memory op fusion from variant to invariant references. */ #define FUSE_DISABLED (~(IRRef)0) #define mayfuse(as, ref) ((ref) > as->fuseref) #define neverfuse(as) (as->fuseref == FUSE_DISABLED) #define canfuse(as, ir) (!neverfuse(as) && !irt_isphi((ir)->t)) #define opisfusableload(o) \ ((o) == IR_ALOAD || (o) == IR_HLOAD || (o) == IR_ULOAD || \ (o) == IR_FLOAD || (o) == IR_XLOAD || (o) == IR_SLOAD || (o) == IR_VLOAD) /* Sparse limit checks using a red zone before the actual limit. */ #define MCLIM_REDZONE 64 static LJ_NORET LJ_NOINLINE void asm_mclimit(ASMState *as) { lj_mcode_limiterr(as->J, (size_t)(as->mctop - as->mcp + 4*MCLIM_REDZONE)); } static LJ_AINLINE void checkmclim(ASMState *as) { #ifdef LUA_USE_ASSERT if (as->mcp + MCLIM_REDZONE < as->mcp_prev) { IRIns *ir = IR(as->curins+1); fprintf(stderr, "RED ZONE OVERFLOW: %p IR %04d %02d %04d %04d\n", as->mcp, as->curins+1-REF_BIAS, ir->o, ir->op1-REF_BIAS, ir->op2-REF_BIAS); lua_assert(0); } #endif if (LJ_UNLIKELY(as->mcp < as->mclim)) asm_mclimit(as); #ifdef LUA_USE_ASSERT as->mcp_prev = as->mcp; #endif } #ifdef RID_NUM_KREF #define ra_iskref(ref) ((ref) < RID_NUM_KREF) #define ra_krefreg(ref) ((Reg)(RID_MIN_KREF + (Reg)(ref))) #define ra_krefk(as, ref) (as->krefk[(ref)]) static LJ_AINLINE void ra_setkref(ASMState *as, Reg r, int32_t k) { IRRef ref = (IRRef)(r - RID_MIN_KREF); as->krefk[ref] = k; as->cost[r] = REGCOST(ref, ref); } #else #define ra_iskref(ref) 0 #define ra_krefreg(ref) RID_MIN_GPR #define ra_krefk(as, ref) 0 #endif /* Arch-specific field offsets. */ static const uint8_t field_ofs[IRFL__MAX+1] = { #define FLOFS(name, ofs) (uint8_t)(ofs), IRFLDEF(FLOFS) #undef FLOFS 0 }; /* -- Target-specific instruction emitter --------------------------------- */ #if LJ_TARGET_X86ORX64 #include "lj_emit_x86.h" #elif LJ_TARGET_ARM #include "lj_emit_arm.h" #elif LJ_TARGET_PPC #include "lj_emit_ppc.h" #elif LJ_TARGET_MIPS #include "lj_emit_mips.h" #else #error "Missing instruction emitter for target CPU" #endif /* Generic load/store of register from/to stack slot. */ #define emit_spload(as, ir, r, ofs) \ emit_loadofs(as, ir, (r), RID_SP, (ofs)) #define emit_spstore(as, ir, r, ofs) \ emit_storeofs(as, ir, (r), RID_SP, (ofs)) /* -- Register allocator debugging ---------------------------------------- */ /* #define LUAJIT_DEBUG_RA */ #ifdef LUAJIT_DEBUG_RA #include <stdio.h> #include <stdarg.h> #define RIDNAME(name) #name, static const char *const ra_regname[] = { GPRDEF(RIDNAME) FPRDEF(RIDNAME) VRIDDEF(RIDNAME) NULL }; #undef RIDNAME static char ra_dbg_buf[65536]; static char *ra_dbg_p; static char *ra_dbg_merge; static MCode *ra_dbg_mcp; static void ra_dstart(void) { ra_dbg_p = ra_dbg_buf; ra_dbg_merge = NULL; ra_dbg_mcp = NULL; } static void ra_dflush(void) { fwrite(ra_dbg_buf, 1, (size_t)(ra_dbg_p-ra_dbg_buf), stdout); ra_dstart(); } static void ra_dprintf(ASMState *as, const char *fmt, ...) { char *p; va_list argp; va_start(argp, fmt); p = ra_dbg_mcp == as->mcp ? ra_dbg_merge : ra_dbg_p; ra_dbg_mcp = NULL; p += sprintf(p, "%08x \e[36m%04d ", (uintptr_t)as->mcp, as->curins-REF_BIAS); for (;;) { const char *e = strchr(fmt, '$'); if (e == NULL) break; memcpy(p, fmt, (size_t)(e-fmt)); p += e-fmt; if (e[1] == 'r') { Reg r = va_arg(argp, Reg) & RID_MASK; if (r <= RID_MAX) { const char *q; for (q = ra_regname[r]; *q; q++) *p++ = *q >= 'A' && *q <= 'Z' ? *q + 0x20 : *q; } else { *p++ = '?'; lua_assert(0); } } else if (e[1] == 'f' || e[1] == 'i') { IRRef ref; if (e[1] == 'f') ref = va_arg(argp, IRRef); else ref = va_arg(argp, IRIns *) - as->ir; if (ref >= REF_BIAS) p += sprintf(p, "%04d", ref - REF_BIAS); else p += sprintf(p, "K%03d", REF_BIAS - ref); } else if (e[1] == 's') { uint32_t slot = va_arg(argp, uint32_t); p += sprintf(p, "[sp+0x%x]", sps_scale(slot)); } else if (e[1] == 'x') { p += sprintf(p, "%08x", va_arg(argp, int32_t)); } else { lua_assert(0); } fmt = e+2; } va_end(argp); while (*fmt) *p++ = *fmt++; *p++ = '\e'; *p++ = '['; *p++ = 'm'; *p++ = '\n'; if (p > ra_dbg_buf+sizeof(ra_dbg_buf)-256) { fwrite(ra_dbg_buf, 1, (size_t)(p-ra_dbg_buf), stdout); p = ra_dbg_buf; } ra_dbg_p = p; } #define RA_DBG_START() ra_dstart() #define RA_DBG_FLUSH() ra_dflush() #define RA_DBG_REF() \ do { char *_p = ra_dbg_p; ra_dprintf(as, ""); \ ra_dbg_merge = _p; ra_dbg_mcp = as->mcp; } while (0) #define RA_DBGX(x) ra_dprintf x #else #define RA_DBG_START() ((void)0) #define RA_DBG_FLUSH() ((void)0) #define RA_DBG_REF() ((void)0) #define RA_DBGX(x) ((void)0) #endif /* -- Register allocator -------------------------------------------------- */ #define ra_free(as, r) rset_set(as->freeset, (r)) #define ra_modified(as, r) rset_set(as->modset, (r)) #define ra_weak(as, r) rset_set(as->weakset, (r)) #define ra_noweak(as, r) rset_clear(as->weakset, (r)) #define ra_used(ir) (ra_hasreg((ir)->r) || ra_hasspill((ir)->s)) /* Setup register allocator. */ static void ra_setup(ASMState *as) { Reg r; /* Initially all regs (except the stack pointer) are free for use. */ as->freeset = RSET_INIT; as->modset = RSET_EMPTY; as->weakset = RSET_EMPTY; as->phiset = RSET_EMPTY; memset(as->phireg, 0, sizeof(as->phireg)); for (r = RID_MIN_GPR; r < RID_MAX; r++) as->cost[r] = REGCOST(~0u, 0u); } /* Rematerialize constants. */ static Reg ra_rematk(ASMState *as, IRRef ref) { IRIns *ir; Reg r; if (ra_iskref(ref)) { r = ra_krefreg(ref); lua_assert(!rset_test(as->freeset, r)); ra_free(as, r); ra_modified(as, r); emit_loadi(as, r, ra_krefk(as, ref)); return r; } ir = IR(ref); r = ir->r; lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s)); ra_free(as, r); ra_modified(as, r); ir->r = RID_INIT; /* Do not keep any hint. */ RA_DBGX((as, "remat $i $r", ir, r)); #if !LJ_SOFTFP if (ir->o == IR_KNUM) { emit_loadn(as, r, ir_knum(ir)); } else #endif if (emit_canremat(REF_BASE) && ir->o == IR_BASE) { ra_sethint(ir->r, RID_BASE); /* Restore BASE register hint. */ emit_getgl(as, r, jit_base); } else if (emit_canremat(ASMREF_L) && ir->o == IR_KPRI) { lua_assert(irt_isnil(ir->t)); /* REF_NIL stores ASMREF_L register. */ emit_getgl(as, r, cur_L); #if LJ_64 } else if (ir->o == IR_KINT64) { emit_loadu64(as, r, ir_kint64(ir)->u64); #endif } else { lua_assert(ir->o == IR_KINT || ir->o == IR_KGC || ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL); emit_loadi(as, r, ir->i); } return r; } /* Force a spill. Allocate a new spill slot if needed. */ static int32_t ra_spill(ASMState *as, IRIns *ir) { int32_t slot = ir->s; lua_assert(ir >= as->ir + REF_TRUE); if (!ra_hasspill(slot)) { if (irt_is64(ir->t)) { slot = as->evenspill; as->evenspill += 2; } else if (as->oddspill) { slot = as->oddspill; as->oddspill = 0; } else { slot = as->evenspill; as->oddspill = slot+1; as->evenspill += 2; } if (as->evenspill > 256) lj_trace_err(as->J, LJ_TRERR_SPILLOV); ir->s = (uint8_t)slot; } return sps_scale(slot); } /* Release the temporarily allocated register in ASMREF_TMP1/ASMREF_TMP2. */ static Reg ra_releasetmp(ASMState *as, IRRef ref) { IRIns *ir = IR(ref); Reg r = ir->r; lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s)); ra_free(as, r); ra_modified(as, r); ir->r = RID_INIT; return r; } /* Restore a register (marked as free). Rematerialize or force a spill. */ static Reg ra_restore(ASMState *as, IRRef ref) { if (emit_canremat(ref)) { return ra_rematk(as, ref); } else { IRIns *ir = IR(ref); int32_t ofs = ra_spill(as, ir); /* Force a spill slot. */ Reg r = ir->r; lua_assert(ra_hasreg(r)); ra_sethint(ir->r, r); /* Keep hint. */ ra_free(as, r); if (!rset_test(as->weakset, r)) { /* Only restore non-weak references. */ ra_modified(as, r); RA_DBGX((as, "restore $i $r", ir, r)); emit_spload(as, ir, r, ofs); } return r; } } /* Save a register to a spill slot. */ static void ra_save(ASMState *as, IRIns *ir, Reg r) { RA_DBGX((as, "save $i $r", ir, r)); emit_spstore(as, ir, r, sps_scale(ir->s)); } #define MINCOST(name) \ if (rset_test(RSET_ALL, RID_##name) && \ LJ_LIKELY(allow&RID2RSET(RID_##name)) && as->cost[RID_##name] < cost) \ cost = as->cost[RID_##name]; /* Evict the register with the lowest cost, forcing a restore. */ static Reg ra_evict(ASMState *as, RegSet allow) { IRRef ref; RegCost cost = ~(RegCost)0; lua_assert(allow != RSET_EMPTY); if (RID_NUM_FPR == 0 || allow < RID2RSET(RID_MAX_GPR)) { GPRDEF(MINCOST) } else { FPRDEF(MINCOST) } ref = regcost_ref(cost); lua_assert(ra_iskref(ref) || (ref >= as->T->nk && ref < as->T->nins)); /* Preferably pick any weak ref instead of a non-weak, non-const ref. */ if (!irref_isk(ref) && (as->weakset & allow)) { IRIns *ir = IR(ref); if (!rset_test(as->weakset, ir->r)) ref = regcost_ref(as->cost[rset_pickbot((as->weakset & allow))]); } return ra_restore(as, ref); } /* Pick any register (marked as free). Evict on-demand. */ static Reg ra_pick(ASMState *as, RegSet allow) { RegSet pick = as->freeset & allow; if (!pick) return ra_evict(as, allow); else return rset_picktop(pick); } /* Get a scratch register (marked as free). */ static Reg ra_scratch(ASMState *as, RegSet allow) { Reg r = ra_pick(as, allow); ra_modified(as, r); RA_DBGX((as, "scratch $r", r)); return r; } /* Evict all registers from a set (if not free). */ static void ra_evictset(ASMState *as, RegSet drop) { RegSet work; as->modset |= drop; #if !LJ_SOFTFP work = (drop & ~as->freeset) & RSET_FPR; while (work) { Reg r = rset_pickbot(work); ra_restore(as, regcost_ref(as->cost[r])); rset_clear(work, r); checkmclim(as); } #endif work = (drop & ~as->freeset); while (work) { Reg r = rset_pickbot(work); ra_restore(as, regcost_ref(as->cost[r])); rset_clear(work, r); checkmclim(as); } } /* Evict (rematerialize) all registers allocated to constants. */ static void ra_evictk(ASMState *as) { RegSet work; #if !LJ_SOFTFP work = ~as->freeset & RSET_FPR; while (work) { Reg r = rset_pickbot(work); IRRef ref = regcost_ref(as->cost[r]); if (emit_canremat(ref) && irref_isk(ref)) { ra_rematk(as, ref); checkmclim(as); } rset_clear(work, r); } #endif work = ~as->freeset & RSET_GPR; while (work) { Reg r = rset_pickbot(work); IRRef ref = regcost_ref(as->cost[r]); if (emit_canremat(ref) && irref_isk(ref)) { ra_rematk(as, ref); checkmclim(as); } rset_clear(work, r); } } #ifdef RID_NUM_KREF /* Allocate a register for a constant. */ static Reg ra_allock(ASMState *as, int32_t k, RegSet allow) { /* First try to find a register which already holds the same constant. */ RegSet pick, work = ~as->freeset & RSET_GPR; Reg r; while (work) { IRRef ref; r = rset_pickbot(work); ref = regcost_ref(as->cost[r]); if (ref < ASMREF_L && k == (ra_iskref(ref) ? ra_krefk(as, ref) : IR(ref)->i)) return r; rset_clear(work, r); } pick = as->freeset & allow; if (pick) { /* Constants should preferably get unmodified registers. */ if ((pick & ~as->modset)) pick &= ~as->modset; r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */ } else { r = ra_evict(as, allow); } RA_DBGX((as, "allock $x $r", k, r)); ra_setkref(as, r, k); rset_clear(as->freeset, r); ra_noweak(as, r); return r; } /* Allocate a specific register for a constant. */ static void ra_allockreg(ASMState *as, int32_t k, Reg r) { Reg kr = ra_allock(as, k, RID2RSET(r)); if (kr != r) { IRIns irdummy; irdummy.t.irt = IRT_INT; ra_scratch(as, RID2RSET(r)); emit_movrr(as, &irdummy, r, kr); } } #else #define ra_allockreg(as, k, r) emit_loadi(as, (r), (k)) #endif /* Allocate a register for ref from the allowed set of registers. ** Note: this function assumes the ref does NOT have a register yet! ** Picks an optimal register, sets the cost and marks the register as non-free. */ static Reg ra_allocref(ASMState *as, IRRef ref, RegSet allow) { IRIns *ir = IR(ref); RegSet pick = as->freeset & allow; Reg r; lua_assert(ra_noreg(ir->r)); if (pick) { /* First check register hint from propagation or PHI. */ if (ra_hashint(ir->r)) { r = ra_gethint(ir->r); if (rset_test(pick, r)) /* Use hint register if possible. */ goto found; /* Rematerialization is cheaper than missing a hint. */ if (rset_test(allow, r) && emit_canremat(regcost_ref(as->cost[r]))) { ra_rematk(as, regcost_ref(as->cost[r])); goto found; } RA_DBGX((as, "hintmiss $f $r", ref, r)); } /* Invariants should preferably get unmodified registers. */ if (ref < as->loopref && !irt_isphi(ir->t)) { if ((pick & ~as->modset)) pick &= ~as->modset; r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */ } else { /* We've got plenty of regs, so get callee-save regs if possible. */ if (RID_NUM_GPR > 8 && (pick & ~RSET_SCRATCH)) pick &= ~RSET_SCRATCH; r = rset_picktop(pick); } } else { r = ra_evict(as, allow); } found: RA_DBGX((as, "alloc $f $r", ref, r)); ir->r = (uint8_t)r; rset_clear(as->freeset, r); ra_noweak(as, r); as->cost[r] = REGCOST_REF_T(ref, irt_t(ir->t)); return r; } /* Allocate a register on-demand. */ static Reg ra_alloc1(ASMState *as, IRRef ref, RegSet allow) { Reg r = IR(ref)->r; /* Note: allow is ignored if the register is already allocated. */ if (ra_noreg(r)) r = ra_allocref(as, ref, allow); ra_noweak(as, r); return r; } /* Rename register allocation and emit move. */ static void ra_rename(ASMState *as, Reg down, Reg up) { IRRef ren, ref = regcost_ref(as->cost[up] = as->cost[down]); IRIns *ir = IR(ref); ir->r = (uint8_t)up; as->cost[down] = 0; lua_assert((down < RID_MAX_GPR) == (up < RID_MAX_GPR)); lua_assert(!rset_test(as->freeset, down) && rset_test(as->freeset, up)); ra_free(as, down); /* 'down' is free ... */ ra_modified(as, down); rset_clear(as->freeset, up); /* ... and 'up' is now allocated. */ ra_noweak(as, up); RA_DBGX((as, "rename $f $r $r", regcost_ref(as->cost[up]), down, up)); emit_movrr(as, ir, down, up); /* Backwards codegen needs inverse move. */ if (!ra_hasspill(IR(ref)->s)) { /* Add the rename to the IR. */ lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), ref, as->snapno); ren = tref_ref(lj_ir_emit(as->J)); as->ir = as->T->ir; /* The IR may have been reallocated. */ IR(ren)->r = (uint8_t)down; IR(ren)->s = SPS_NONE; } } /* Pick a destination register (marked as free). ** Caveat: allow is ignored if there's already a destination register. ** Use ra_destreg() to get a specific register. */ static Reg ra_dest(ASMState *as, IRIns *ir, RegSet allow) { Reg dest = ir->r; if (ra_hasreg(dest)) { ra_free(as, dest); ra_modified(as, dest); } else { if (ra_hashint(dest) && rset_test((as->freeset&allow), ra_gethint(dest))) { dest = ra_gethint(dest); ra_modified(as, dest); RA_DBGX((as, "dest $r", dest)); } else { dest = ra_scratch(as, allow); } ir->r = dest; } if (LJ_UNLIKELY(ra_hasspill(ir->s))) ra_save(as, ir, dest); return dest; } /* Force a specific destination register (marked as free). */ static void ra_destreg(ASMState *as, IRIns *ir, Reg r) { Reg dest = ra_dest(as, ir, RID2RSET(r)); if (dest != r) { lua_assert(rset_test(as->freeset, r)); ra_modified(as, r); emit_movrr(as, ir, dest, r); } } #if LJ_TARGET_X86ORX64 /* Propagate dest register to left reference. Emit moves as needed. ** This is a required fixup step for all 2-operand machine instructions. */ static void ra_left(ASMState *as, Reg dest, IRRef lref) { IRIns *ir = IR(lref); Reg left = ir->r; if (ra_noreg(left)) { if (irref_isk(lref)) { if (ir->o == IR_KNUM) { cTValue *tv = ir_knum(ir); /* FP remat needs a load except for +0. Still better than eviction. */ if (tvispzero(tv) || !(as->freeset & RSET_FPR)) { emit_loadn(as, dest, tv); return; } #if LJ_64 } else if (ir->o == IR_KINT64) { emit_loadu64(as, dest, ir_kint64(ir)->u64); return; #endif } else if (ir->o != IR_KPRI) { lua_assert(ir->o == IR_KINT || ir->o == IR_KGC || ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL); emit_loadi(as, dest, ir->i); return; } } if (!ra_hashint(left) && !iscrossref(as, lref)) ra_sethint(ir->r, dest); /* Propagate register hint. */ left = ra_allocref(as, lref, dest < RID_MAX_GPR ? RSET_GPR : RSET_FPR); } ra_noweak(as, left); /* Move needed for true 3-operand instruction: y=a+b ==> y=a; y+=b. */ if (dest != left) { /* Use register renaming if dest is the PHI reg. */ if (irt_isphi(ir->t) && as->phireg[dest] == lref) { ra_modified(as, left); ra_rename(as, left, dest); } else { emit_movrr(as, ir, dest, left); } } } #else /* Similar to ra_left, except we override any hints. */ static void ra_leftov(ASMState *as, Reg dest, IRRef lref) { IRIns *ir = IR(lref); Reg left = ir->r; if (ra_noreg(left)) { ra_sethint(ir->r, dest); /* Propagate register hint. */ left = ra_allocref(as, lref, (LJ_SOFTFP || dest < RID_MAX_GPR) ? RSET_GPR : RSET_FPR); } ra_noweak(as, left); if (dest != left) { /* Use register renaming if dest is the PHI reg. */ if (irt_isphi(ir->t) && as->phireg[dest] == lref) { ra_modified(as, left); ra_rename(as, left, dest); } else { emit_movrr(as, ir, dest, left); } } } #endif #if !LJ_64 /* Force a RID_RETLO/RID_RETHI destination register pair (marked as free). */ static void ra_destpair(ASMState *as, IRIns *ir) { Reg destlo = ir->r, desthi = (ir+1)->r; /* First spill unrelated refs blocking the destination registers. */ if (!rset_test(as->freeset, RID_RETLO) && destlo != RID_RETLO && desthi != RID_RETLO) ra_restore(as, regcost_ref(as->cost[RID_RETLO])); if (!rset_test(as->freeset, RID_RETHI) && destlo != RID_RETHI && desthi != RID_RETHI) ra_restore(as, regcost_ref(as->cost[RID_RETHI])); /* Next free the destination registers (if any). */ if (ra_hasreg(destlo)) { ra_free(as, destlo); ra_modified(as, destlo); } else { destlo = RID_RETLO; } if (ra_hasreg(desthi)) { ra_free(as, desthi); ra_modified(as, desthi); } else { desthi = RID_RETHI; } /* Check for conflicts and shuffle the registers as needed. */ if (destlo == RID_RETHI) { if (desthi == RID_RETLO) { #if LJ_TARGET_X86 *--as->mcp = XI_XCHGa + RID_RETHI; #else emit_movrr(as, ir, RID_RETHI, RID_TMP); emit_movrr(as, ir, RID_RETLO, RID_RETHI); emit_movrr(as, ir, RID_TMP, RID_RETLO); #endif } else { emit_movrr(as, ir, RID_RETHI, RID_RETLO); if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI); } } else if (desthi == RID_RETLO) { emit_movrr(as, ir, RID_RETLO, RID_RETHI); if (destlo != RID_RETLO) emit_movrr(as, ir, destlo, RID_RETLO); } else { if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI); if (destlo != RID_RETLO) emit_movrr(as, ir, destlo, RID_RETLO); } /* Restore spill slots (if any). */ if (ra_hasspill((ir+1)->s)) ra_save(as, ir+1, RID_RETHI); if (ra_hasspill(ir->s)) ra_save(as, ir, RID_RETLO); } #endif /* -- Snapshot handling --------- ----------------------------------------- */ /* Can we rematerialize a KNUM instead of forcing a spill? */ static int asm_snap_canremat(ASMState *as) { Reg r; for (r = RID_MIN_FPR; r < RID_MAX_FPR; r++) if (irref_isk(regcost_ref(as->cost[r]))) return 1; return 0; } /* Check whether a sunk store corresponds to an allocation. */ static int asm_sunk_store(ASMState *as, IRIns *ira, IRIns *irs) { if (irs->s == 255) { if (irs->o == IR_ASTORE || irs->o == IR_HSTORE || irs->o == IR_FSTORE || irs->o == IR_XSTORE) { IRIns *irk = IR(irs->op1); if (irk->o == IR_AREF || irk->o == IR_HREFK) irk = IR(irk->op1); return (IR(irk->op1) == ira); } return 0; } else { return (ira + irs->s == irs); /* Quick check. */ } } /* Allocate register or spill slot for a ref that escapes to a snapshot. */ static void asm_snap_alloc1(ASMState *as, IRRef ref) { IRIns *ir = IR(ref); if (!irref_isk(ref) && (!(ra_used(ir) || ir->r == RID_SUNK))) { if (ir->r == RID_SINK) { ir->r = RID_SUNK; #if LJ_HASFFI if (ir->o == IR_CNEWI) { /* Allocate CNEWI value. */ asm_snap_alloc1(as, ir->op2); if (LJ_32 && (ir+1)->o == IR_HIOP) asm_snap_alloc1(as, (ir+1)->op2); } else #endif { /* Allocate stored values for TNEW, TDUP and CNEW. */ IRIns *irs; lua_assert(ir->o == IR_TNEW || ir->o == IR_TDUP || ir->o == IR_CNEW); for (irs = IR(as->snapref-1); irs > ir; irs--) if (irs->r == RID_SINK && asm_sunk_store(as, ir, irs)) { lua_assert(irs->o == IR_ASTORE || irs->o == IR_HSTORE || irs->o == IR_FSTORE || irs->o == IR_XSTORE); asm_snap_alloc1(as, irs->op2); if (LJ_32 && (irs+1)->o == IR_HIOP) asm_snap_alloc1(as, (irs+1)->op2); } } } else { RegSet allow; if (ir->o == IR_CONV && ir->op2 == IRCONV_NUM_INT) { IRIns *irc; for (irc = IR(as->curins); irc > ir; irc--) if ((irc->op1 == ref || irc->op2 == ref) && !(irc->r == RID_SINK || irc->r == RID_SUNK)) goto nosink; /* Don't sink conversion if result is used. */ asm_snap_alloc1(as, ir->op1); return; } nosink: allow = (!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR; if ((as->freeset & allow) || (allow == RSET_FPR && asm_snap_canremat(as))) { /* Get a weak register if we have a free one or can rematerialize. */ Reg r = ra_allocref(as, ref, allow); /* Allocate a register. */ if (!irt_isphi(ir->t)) ra_weak(as, r); /* But mark it as weakly referenced. */ checkmclim(as); RA_DBGX((as, "snapreg $f $r", ref, ir->r)); } else { ra_spill(as, ir); /* Otherwise force a spill slot. */ RA_DBGX((as, "snapspill $f $s", ref, ir->s)); } } } } /* Allocate refs escaping to a snapshot. */ static void asm_snap_alloc(ASMState *as) { SnapShot *snap = &as->T->snap[as->snapno]; SnapEntry *map = &as->T->snapmap[snap->mapofs]; MSize n, nent = snap->nent; for (n = 0; n < nent; n++) { SnapEntry sn = map[n]; IRRef ref = snap_ref(sn); if (!irref_isk(ref)) { asm_snap_alloc1(as, ref); if (LJ_SOFTFP && (sn & SNAP_SOFTFPNUM)) { lua_assert(irt_type(IR(ref+1)->t) == IRT_SOFTFP); asm_snap_alloc1(as, ref+1); } } } } /* All guards for a snapshot use the same exitno. This is currently the ** same as the snapshot number. Since the exact origin of the exit cannot ** be determined, all guards for the same snapshot must exit with the same ** RegSP mapping. ** A renamed ref which has been used in a prior guard for the same snapshot ** would cause an inconsistency. The easy way out is to force a spill slot. */ static int asm_snap_checkrename(ASMState *as, IRRef ren) { SnapShot *snap = &as->T->snap[as->snapno]; SnapEntry *map = &as->T->snapmap[snap->mapofs]; MSize n, nent = snap->nent; for (n = 0; n < nent; n++) { SnapEntry sn = map[n]; IRRef ref = snap_ref(sn); if (ref == ren || (LJ_SOFTFP && (sn & SNAP_SOFTFPNUM) && ++ref == ren)) { IRIns *ir = IR(ref); ra_spill(as, ir); /* Register renamed, so force a spill slot. */ RA_DBGX((as, "snaprensp $f $s", ref, ir->s)); return 1; /* Found. */ } } return 0; /* Not found. */ } /* Prepare snapshot for next guard instruction. */ static void asm_snap_prep(ASMState *as) { if (as->curins < as->snapref) { do { if (as->snapno == 0) return; /* Called by sunk stores before snap #0. */ as->snapno--; as->snapref = as->T->snap[as->snapno].ref; } while (as->curins < as->snapref); asm_snap_alloc(as); as->snaprename = as->T->nins; } else { /* Process any renames above the highwater mark. */ for (; as->snaprename < as->T->nins; as->snaprename++) { IRIns *ir = IR(as->snaprename); if (asm_snap_checkrename(as, ir->op1)) ir->op2 = REF_BIAS-1; /* Kill rename. */ } } } /* -- Miscellaneous helpers ----------------------------------------------- */ /* Calculate stack adjustment. */ static int32_t asm_stack_adjust(ASMState *as) { if (as->evenspill <= SPS_FIXED) return 0; return sps_scale(sps_align(as->evenspill)); } /* Must match with hash*() in lj_tab.c. */ static uint32_t ir_khash(IRIns *ir) { uint32_t lo, hi; if (irt_isstr(ir->t)) { return ir_kstr(ir)->hash; } else if (irt_isnum(ir->t)) { lo = ir_knum(ir)->u32.lo; hi = ir_knum(ir)->u32.hi << 1; } else if (irt_ispri(ir->t)) { lua_assert(!irt_isnil(ir->t)); return irt_type(ir->t)-IRT_FALSE; } else { lua_assert(irt_isgcv(ir->t)); lo = u32ptr(ir_kgc(ir)); hi = lo + HASH_BIAS; } return hashrot(lo, hi); } /* -- Allocations --------------------------------------------------------- */ static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args); static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci); static void asm_snew(ASMState *as, IRIns *ir) { const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_new]; IRRef args[3]; args[0] = ASMREF_L; /* lua_State *L */ args[1] = ir->op1; /* const char *str */ args[2] = ir->op2; /* size_t len */ as->gcsteps++; asm_setupresult(as, ir, ci); /* GCstr * */ asm_gencall(as, ci, args); } static void asm_tnew(ASMState *as, IRIns *ir) { const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_new1]; IRRef args[2]; args[0] = ASMREF_L; /* lua_State *L */ args[1] = ASMREF_TMP1; /* uint32_t ahsize */ as->gcsteps++; asm_setupresult(as, ir, ci); /* GCtab * */ asm_gencall(as, ci, args); ra_allockreg(as, ir->op1 | (ir->op2 << 24), ra_releasetmp(as, ASMREF_TMP1)); } static void asm_tdup(ASMState *as, IRIns *ir) { const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_dup]; IRRef args[2]; args[0] = ASMREF_L; /* lua_State *L */ args[1] = ir->op1; /* const GCtab *kt */ as->gcsteps++; asm_setupresult(as, ir, ci); /* GCtab * */ asm_gencall(as, ci, args); } static void asm_gc_check(ASMState *as); /* Explicit GC step. */ static void asm_gcstep(ASMState *as, IRIns *ir) { IRIns *ira; for (ira = IR(as->stopins+1); ira < ir; ira++) if ((ira->o == IR_TNEW || ira->o == IR_TDUP || (LJ_HASFFI && (ira->o == IR_CNEW || ira->o == IR_CNEWI))) && ra_used(ira)) as->gcsteps++; if (as->gcsteps) asm_gc_check(as); as->gcsteps = 0x80000000; /* Prevent implicit GC check further up. */ } /* -- Buffer operations --------------------------------------------------- */ static void asm_tvptr(ASMState *as, Reg dest, IRRef ref); static void asm_bufhdr(ASMState *as, IRIns *ir) { Reg sb = ra_dest(as, ir, RSET_GPR); if ((ir->op2 & IRBUFHDR_APPEND)) { /* Rematerialize const buffer pointer instead of likely spill. */ IRIns *irp = IR(ir->op1); if (!(ra_hasreg(irp->r) || irp == ir-1 || (irp == ir-2 && !ra_used(ir-1)))) { while (!(irp->o == IR_BUFHDR && !(irp->op2 & IRBUFHDR_APPEND))) irp = IR(irp->op1); if (irref_isk(irp->op1)) { ra_weak(as, ra_allocref(as, ir->op1, RSET_GPR)); ir = irp; } } } else { Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, sb)); /* Passing ir isn't strictly correct, but it's an IRT_P32, too. */ emit_storeofs(as, ir, tmp, sb, offsetof(SBuf, p)); emit_loadofs(as, ir, tmp, sb, offsetof(SBuf, b)); } #if LJ_TARGET_X86ORX64 ra_left(as, sb, ir->op1); #else ra_leftov(as, sb, ir->op1); #endif } static void asm_bufput(ASMState *as, IRIns *ir) { const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_buf_putstr]; IRRef args[3]; IRIns *irs; int kchar = -1; args[0] = ir->op1; /* SBuf * */ args[1] = ir->op2; /* GCstr * */ irs = IR(ir->op2); lua_assert(irt_isstr(irs->t)); if (irs->o == IR_KGC) { GCstr *s = ir_kstr(irs); if (s->len == 1) { /* Optimize put of single-char string constant. */ kchar = strdata(s)[0]; args[1] = ASMREF_TMP1; /* int, truncated to char */ ci = &lj_ir_callinfo[IRCALL_lj_buf_putchar]; } } else if (mayfuse(as, ir->op2) && ra_noreg(irs->r)) { if (irs->o == IR_TOSTR) { /* Fuse number to string conversions. */ if (irs->op2 == IRTOSTR_NUM) { args[1] = ASMREF_TMP1; /* TValue * */ ci = &lj_ir_callinfo[IRCALL_lj_strfmt_putnum]; } else { lua_assert(irt_isinteger(IR(irs->op1)->t)); args[1] = irs->op1; /* int */ if (irs->op2 == IRTOSTR_INT) ci = &lj_ir_callinfo[IRCALL_lj_strfmt_putint]; else ci = &lj_ir_callinfo[IRCALL_lj_buf_putchar]; } } else if (irs->o == IR_SNEW) { /* Fuse string allocation. */ args[1] = irs->op1; /* const void * */ args[2] = irs->op2; /* MSize */ ci = &lj_ir_callinfo[IRCALL_lj_buf_putmem]; } } asm_setupresult(as, ir, ci); /* SBuf * */ asm_gencall(as, ci, args); if (args[1] == ASMREF_TMP1) { Reg tmp = ra_releasetmp(as, ASMREF_TMP1); if (kchar == -1) asm_tvptr(as, tmp, irs->op1); else ra_allockreg(as, kchar, tmp); } } static void asm_bufstr(ASMState *as, IRIns *ir) { const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_buf_tostr]; IRRef args[1]; args[0] = ir->op1; /* SBuf *sb */ as->gcsteps++; asm_setupresult(as, ir, ci); /* GCstr * */ asm_gencall(as, ci, args); } /* -- Type conversions ---------------------------------------------------- */ static void asm_tostr(ASMState *as, IRIns *ir) { const CCallInfo *ci; IRRef args[2]; args[0] = ASMREF_L; as->gcsteps++; if (ir->op2 == IRTOSTR_NUM) { args[1] = ASMREF_TMP1; /* cTValue * */ ci = &lj_ir_callinfo[IRCALL_lj_strfmt_num]; } else { args[1] = ir->op1; /* int32_t k */ if (ir->op2 == IRTOSTR_INT) ci = &lj_ir_callinfo[IRCALL_lj_strfmt_int]; else ci = &lj_ir_callinfo[IRCALL_lj_strfmt_char]; } asm_setupresult(as, ir, ci); /* GCstr * */ asm_gencall(as, ci, args); if (ir->op2 == IRTOSTR_NUM) asm_tvptr(as, ra_releasetmp(as, ASMREF_TMP1), ir->op1); } #if LJ_32 && LJ_HASFFI && !LJ_SOFTFP && !LJ_TARGET_X86 static void asm_conv64(ASMState *as, IRIns *ir) { IRType st = (IRType)((ir-1)->op2 & IRCONV_SRCMASK); IRType dt = (((ir-1)->op2 & IRCONV_DSTMASK) >> IRCONV_DSH); IRCallID id; IRRef args[2]; lua_assert((ir-1)->o == IR_CONV && ir->o == IR_HIOP); args[LJ_BE] = (ir-1)->op1; args[LJ_LE] = ir->op1; if (st == IRT_NUM || st == IRT_FLOAT) { id = IRCALL_fp64_d2l + ((st == IRT_FLOAT) ? 2 : 0) + (dt - IRT_I64); ir--; } else { id = IRCALL_fp64_l2d + ((dt == IRT_FLOAT) ? 2 : 0) + (st - IRT_I64); } { #if LJ_TARGET_ARM && !LJ_ABI_SOFTFP CCallInfo cim = lj_ir_callinfo[id], *ci = &cim; cim.flags |= CCI_VARARG; /* These calls don't use the hard-float ABI! */ #else const CCallInfo *ci = &lj_ir_callinfo[id]; #endif asm_setupresult(as, ir, ci); asm_gencall(as, ci, args); } } #endif /* -- Memory references --------------------------------------------------- */ static void asm_newref(ASMState *as, IRIns *ir) { const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_newkey]; IRRef args[3]; if (ir->r == RID_SINK) return; args[0] = ASMREF_L; /* lua_State *L */ args[1] = ir->op1; /* GCtab *t */ args[2] = ASMREF_TMP1; /* cTValue *key */ asm_setupresult(as, ir, ci); /* TValue * */ asm_gencall(as, ci, args); asm_tvptr(as, ra_releasetmp(as, ASMREF_TMP1), ir->op2); } static void asm_lref(ASMState *as, IRIns *ir) { Reg r = ra_dest(as, ir, RSET_GPR); #if LJ_TARGET_X86ORX64 ra_left(as, r, ASMREF_L); #else ra_leftov(as, r, ASMREF_L); #endif } /* -- Calls --------------------------------------------------------------- */ /* Collect arguments from CALL* and CARG instructions. */ static void asm_collectargs(ASMState *as, IRIns *ir, const CCallInfo *ci, IRRef *args) { uint32_t n = CCI_XNARGS(ci); lua_assert(n <= CCI_NARGS_MAX*2); /* Account for split args. */ if ((ci->flags & CCI_L)) { *args++ = ASMREF_L; n--; } while (n-- > 1) { ir = IR(ir->op1); lua_assert(ir->o == IR_CARG); args[n] = ir->op2 == REF_NIL ? 0 : ir->op2; } args[0] = ir->op1 == REF_NIL ? 0 : ir->op1; lua_assert(IR(ir->op1)->o != IR_CARG); } /* Reconstruct CCallInfo flags for CALLX*. */ static uint32_t asm_callx_flags(ASMState *as, IRIns *ir) { uint32_t nargs = 0; if (ir->op1 != REF_NIL) { /* Count number of arguments first. */ IRIns *ira = IR(ir->op1); nargs++; while (ira->o == IR_CARG) { nargs++; ira = IR(ira->op1); } } #if LJ_HASFFI if (IR(ir->op2)->o == IR_CARG) { /* Copy calling convention info. */ CTypeID id = (CTypeID)IR(IR(ir->op2)->op2)->i; CType *ct = ctype_get(ctype_ctsG(J2G(as->J)), id); nargs |= ((ct->info & CTF_VARARG) ? CCI_VARARG : 0); #if LJ_TARGET_X86 nargs |= (ctype_cconv(ct->info) << CCI_CC_SHIFT); #endif } #endif return (nargs | (ir->t.irt << CCI_OTSHIFT)); } static void asm_callid(ASMState *as, IRIns *ir, IRCallID id) { const CCallInfo *ci = &lj_ir_callinfo[id]; IRRef args[2]; args[0] = ir->op1; args[1] = ir->op2; asm_setupresult(as, ir, ci); asm_gencall(as, ci, args); } static void asm_call(ASMState *as, IRIns *ir) { IRRef args[CCI_NARGS_MAX]; const CCallInfo *ci = &lj_ir_callinfo[ir->op2]; asm_collectargs(as, ir, ci, args); asm_setupresult(as, ir, ci); asm_gencall(as, ci, args); } #if !LJ_SOFTFP static void asm_fppow(ASMState *as, IRIns *ir, IRRef lref, IRRef rref) { const CCallInfo *ci = &lj_ir_callinfo[IRCALL_pow]; IRRef args[2]; args[0] = lref; args[1] = rref; asm_setupresult(as, ir, ci); asm_gencall(as, ci, args); } static int asm_fpjoin_pow(ASMState *as, IRIns *ir) { IRIns *irp = IR(ir->op1); if (irp == ir-1 && irp->o == IR_MUL && !ra_used(irp)) { IRIns *irpp = IR(irp->op1); if (irpp == ir-2 && irpp->o == IR_FPMATH && irpp->op2 == IRFPM_LOG2 && !ra_used(irpp)) { asm_fppow(as, ir, irpp->op1, irp->op2); return 1; } } return 0; } #endif /* -- PHI and loop handling ----------------------------------------------- */ /* Break a PHI cycle by renaming to a free register (evict if needed). */ static void asm_phi_break(ASMState *as, RegSet blocked, RegSet blockedby, RegSet allow) { RegSet candidates = blocked & allow; if (candidates) { /* If this register file has candidates. */ /* Note: the set for ra_pick cannot be empty, since each register file ** has some registers never allocated to PHIs. */ Reg down, up = ra_pick(as, ~blocked & allow); /* Get a free register. */ if (candidates & ~blockedby) /* Optimize shifts, else it's a cycle. */ candidates = candidates & ~blockedby; down = rset_picktop(candidates); /* Pick candidate PHI register. */ ra_rename(as, down, up); /* And rename it to the free register. */ } } /* PHI register shuffling. ** ** The allocator tries hard to preserve PHI register assignments across ** the loop body. Most of the time this loop does nothing, since there ** are no register mismatches. ** ** If a register mismatch is detected and ... ** - the register is currently free: rename it. ** - the register is blocked by an invariant: restore/remat and rename it. ** - Otherwise the register is used by another PHI, so mark it as blocked. ** ** The renames are order-sensitive, so just retry the loop if a register ** is marked as blocked, but has been freed in the meantime. A cycle is ** detected if all of the blocked registers are allocated. To break the ** cycle rename one of them to a free register and retry. ** ** Note that PHI spill slots are kept in sync and don't need to be shuffled. */ static void asm_phi_shuffle(ASMState *as) { RegSet work; /* Find and resolve PHI register mismatches. */ for (;;) { RegSet blocked = RSET_EMPTY; RegSet blockedby = RSET_EMPTY; RegSet phiset = as->phiset; while (phiset) { /* Check all left PHI operand registers. */ Reg r = rset_pickbot(phiset); IRIns *irl = IR(as->phireg[r]); Reg left = irl->r; if (r != left) { /* Mismatch? */ if (!rset_test(as->freeset, r)) { /* PHI register blocked? */ IRRef ref = regcost_ref(as->cost[r]); /* Blocked by other PHI (w/reg)? */ if (!ra_iskref(ref) && irt_ismarked(IR(ref)->t)) { rset_set(blocked, r); if (ra_hasreg(left)) rset_set(blockedby, left); left = RID_NONE; } else { /* Otherwise grab register from invariant. */ ra_restore(as, ref); checkmclim(as); } } if (ra_hasreg(left)) { ra_rename(as, left, r); checkmclim(as); } } rset_clear(phiset, r); } if (!blocked) break; /* Finished. */ if (!(as->freeset & blocked)) { /* Break cycles if none are free. */ asm_phi_break(as, blocked, blockedby, RSET_GPR); if (!LJ_SOFTFP) asm_phi_break(as, blocked, blockedby, RSET_FPR); checkmclim(as); } /* Else retry some more renames. */ } /* Restore/remat invariants whose registers are modified inside the loop. */ #if !LJ_SOFTFP work = as->modset & ~(as->freeset | as->phiset) & RSET_FPR; while (work) { Reg r = rset_pickbot(work); ra_restore(as, regcost_ref(as->cost[r])); rset_clear(work, r); checkmclim(as); } #endif work = as->modset & ~(as->freeset | as->phiset); while (work) { Reg r = rset_pickbot(work); ra_restore(as, regcost_ref(as->cost[r])); rset_clear(work, r); checkmclim(as); } /* Allocate and save all unsaved PHI regs and clear marks. */ work = as->phiset; while (work) { Reg r = rset_picktop(work); IRRef lref = as->phireg[r]; IRIns *ir = IR(lref); if (ra_hasspill(ir->s)) { /* Left PHI gained a spill slot? */ irt_clearmark(ir->t); /* Handled here, so clear marker now. */ ra_alloc1(as, lref, RID2RSET(r)); ra_save(as, ir, r); /* Save to spill slot inside the loop. */ checkmclim(as); } rset_clear(work, r); } } /* Copy unsynced left/right PHI spill slots. Rarely needed. */ static void asm_phi_copyspill(ASMState *as) { int need = 0; IRIns *ir; for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--) if (ra_hasspill(ir->s) && ra_hasspill(IR(ir->op1)->s)) need |= irt_isfp(ir->t) ? 2 : 1; /* Unsynced spill slot? */ if ((need & 1)) { /* Copy integer spill slots. */ #if !LJ_TARGET_X86ORX64 Reg r = RID_TMP; #else Reg r = RID_RET; if ((as->freeset & RSET_GPR)) r = rset_pickbot((as->freeset & RSET_GPR)); else emit_spload(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP); #endif for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--) { if (ra_hasspill(ir->s)) { IRIns *irl = IR(ir->op1); if (ra_hasspill(irl->s) && !irt_isfp(ir->t)) { emit_spstore(as, irl, r, sps_scale(irl->s)); emit_spload(as, ir, r, sps_scale(ir->s)); checkmclim(as); } } } #if LJ_TARGET_X86ORX64 if (!rset_test(as->freeset, r)) emit_spstore(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP); #endif } #if !LJ_SOFTFP if ((need & 2)) { /* Copy FP spill slots. */ #if LJ_TARGET_X86 Reg r = RID_XMM0; #else Reg r = RID_FPRET; #endif if ((as->freeset & RSET_FPR)) r = rset_pickbot((as->freeset & RSET_FPR)); if (!rset_test(as->freeset, r)) emit_spload(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP); for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--) { if (ra_hasspill(ir->s)) { IRIns *irl = IR(ir->op1); if (ra_hasspill(irl->s) && irt_isfp(ir->t)) { emit_spstore(as, irl, r, sps_scale(irl->s)); emit_spload(as, ir, r, sps_scale(ir->s)); checkmclim(as); } } } if (!rset_test(as->freeset, r)) emit_spstore(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP); } #endif } /* Emit renames for left PHIs which are only spilled outside the loop. */ static void asm_phi_fixup(ASMState *as) { RegSet work = as->phiset; while (work) { Reg r = rset_picktop(work); IRRef lref = as->phireg[r]; IRIns *ir = IR(lref); if (irt_ismarked(ir->t)) { irt_clearmark(ir->t); /* Left PHI gained a spill slot before the loop? */ if (ra_hasspill(ir->s)) { IRRef ren; lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), lref, as->loopsnapno); ren = tref_ref(lj_ir_emit(as->J)); as->ir = as->T->ir; /* The IR may have been reallocated. */ IR(ren)->r = (uint8_t)r; IR(ren)->s = SPS_NONE; } } rset_clear(work, r); } } /* Setup right PHI reference. */ static void asm_phi(ASMState *as, IRIns *ir) { RegSet allow = ((!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR) & ~as->phiset; RegSet afree = (as->freeset & allow); IRIns *irl = IR(ir->op1); IRIns *irr = IR(ir->op2); if (ir->r == RID_SINK) /* Sink PHI. */ return; /* Spill slot shuffling is not implemented yet (but rarely needed). */ if (ra_hasspill(irl->s) || ra_hasspill(irr->s)) lj_trace_err(as->J, LJ_TRERR_NYIPHI); /* Leave at least one register free for non-PHIs (and PHI cycle breaking). */ if ((afree & (afree-1))) { /* Two or more free registers? */ Reg r; if (ra_noreg(irr->r)) { /* Get a register for the right PHI. */ r = ra_allocref(as, ir->op2, allow); } else { /* Duplicate right PHI, need a copy (rare). */ r = ra_scratch(as, allow); emit_movrr(as, irr, r, irr->r); } ir->r = (uint8_t)r; rset_set(as->phiset, r); as->phireg[r] = (IRRef1)ir->op1; irt_setmark(irl->t); /* Marks left PHIs _with_ register. */ if (ra_noreg(irl->r)) ra_sethint(irl->r, r); /* Set register hint for left PHI. */ } else { /* Otherwise allocate a spill slot. */ /* This is overly restrictive, but it triggers only on synthetic code. */ if (ra_hasreg(irl->r) || ra_hasreg(irr->r)) lj_trace_err(as->J, LJ_TRERR_NYIPHI); ra_spill(as, ir); irr->s = ir->s; /* Set right PHI spill slot. Sync left slot later. */ } } static void asm_loop_fixup(ASMState *as); /* Middle part of a loop. */ static void asm_loop(ASMState *as) { MCode *mcspill; /* LOOP is a guard, so the snapno is up to date. */ as->loopsnapno = as->snapno; if (as->gcsteps) asm_gc_check(as); /* LOOP marks the transition from the variant to the invariant part. */ as->flagmcp = as->invmcp = NULL; as->sectref = 0; if (!neverfuse(as)) as->fuseref = 0; asm_phi_shuffle(as); mcspill = as->mcp; asm_phi_copyspill(as); asm_loop_fixup(as); as->mcloop = as->mcp; RA_DBGX((as, "===== LOOP =====")); if (!as->realign) RA_DBG_FLUSH(); if (as->mcp != mcspill) emit_jmp(as, mcspill); } /* -- Target-specific assembler ------------------------------------------- */ #if LJ_TARGET_X86ORX64 #include "lj_asm_x86.h" #elif LJ_TARGET_ARM #include "lj_asm_arm.h" #elif LJ_TARGET_PPC #include "lj_asm_ppc.h" #elif LJ_TARGET_MIPS #include "lj_asm_mips.h" #else #error "Missing assembler for target CPU" #endif /* -- Instruction dispatch ------------------------------------------------ */ /* Assemble a single instruction. */ static void asm_ir(ASMState *as, IRIns *ir) { switch ((IROp)ir->o) { /* Miscellaneous ops. */ case IR_LOOP: asm_loop(as); break; case IR_NOP: case IR_XBAR: lua_assert(!ra_used(ir)); break; case IR_USE: ra_alloc1(as, ir->op1, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR); break; case IR_PHI: asm_phi(as, ir); break; case IR_HIOP: asm_hiop(as, ir); break; case IR_GCSTEP: asm_gcstep(as, ir); break; case IR_PROF: asm_prof(as, ir); break; /* Guarded assertions. */ case IR_LT: case IR_GE: case IR_LE: case IR_GT: case IR_ULT: case IR_UGE: case IR_ULE: case IR_UGT: case IR_ABC: asm_comp(as, ir); break; case IR_EQ: case IR_NE: if ((ir-1)->o == IR_HREF && ir->op1 == as->curins-1) { as->curins--; asm_href(as, ir-1, (IROp)ir->o); } else { asm_equal(as, ir); } break; case IR_RETF: asm_retf(as, ir); break; /* Bit ops. */ case IR_BNOT: asm_bnot(as, ir); break; case IR_BSWAP: asm_bswap(as, ir); break; case IR_BAND: asm_band(as, ir); break; case IR_BOR: asm_bor(as, ir); break; case IR_BXOR: asm_bxor(as, ir); break; case IR_BSHL: asm_bshl(as, ir); break; case IR_BSHR: asm_bshr(as, ir); break; case IR_BSAR: asm_bsar(as, ir); break; case IR_BROL: asm_brol(as, ir); break; case IR_BROR: asm_bror(as, ir); break; /* Arithmetic ops. */ case IR_ADD: asm_add(as, ir); break; case IR_SUB: asm_sub(as, ir); break; case IR_MUL: asm_mul(as, ir); break; case IR_MOD: asm_mod(as, ir); break; case IR_NEG: asm_neg(as, ir); break; #if LJ_SOFTFP case IR_DIV: case IR_POW: case IR_ABS: case IR_ATAN2: case IR_LDEXP: case IR_FPMATH: case IR_TOBIT: lua_assert(0); /* Unused for LJ_SOFTFP. */ break; #else case IR_DIV: asm_div(as, ir); break; case IR_POW: asm_pow(as, ir); break; case IR_ABS: asm_abs(as, ir); break; case IR_ATAN2: asm_atan2(as, ir); break; case IR_LDEXP: asm_ldexp(as, ir); break; case IR_FPMATH: asm_fpmath(as, ir); break; case IR_TOBIT: asm_tobit(as, ir); break; #endif case IR_MIN: asm_min(as, ir); break; case IR_MAX: asm_max(as, ir); break; /* Overflow-checking arithmetic ops. */ case IR_ADDOV: asm_addov(as, ir); break; case IR_SUBOV: asm_subov(as, ir); break; case IR_MULOV: asm_mulov(as, ir); break; /* Memory references. */ case IR_AREF: asm_aref(as, ir); break; case IR_HREF: asm_href(as, ir, 0); break; case IR_HREFK: asm_hrefk(as, ir); break; case IR_NEWREF: asm_newref(as, ir); break; case IR_UREFO: case IR_UREFC: asm_uref(as, ir); break; case IR_FREF: asm_fref(as, ir); break; case IR_STRREF: asm_strref(as, ir); break; case IR_LREF: asm_lref(as, ir); break; /* Loads and stores. */ case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD: asm_ahuvload(as, ir); break; case IR_FLOAD: asm_fload(as, ir); break; case IR_XLOAD: asm_xload(as, ir); break; case IR_SLOAD: asm_sload(as, ir); break; case IR_ASTORE: case IR_HSTORE: case IR_USTORE: asm_ahustore(as, ir); break; case IR_FSTORE: asm_fstore(as, ir); break; case IR_XSTORE: asm_xstore(as, ir); break; /* Allocations. */ case IR_SNEW: case IR_XSNEW: asm_snew(as, ir); break; case IR_TNEW: asm_tnew(as, ir); break; case IR_TDUP: asm_tdup(as, ir); break; case IR_CNEW: case IR_CNEWI: asm_cnew(as, ir); break; /* Buffer operations. */ case IR_BUFHDR: asm_bufhdr(as, ir); break; case IR_BUFPUT: asm_bufput(as, ir); break; case IR_BUFSTR: asm_bufstr(as, ir); break; /* Write barriers. */ case IR_TBAR: asm_tbar(as, ir); break; case IR_OBAR: asm_obar(as, ir); break; /* Type conversions. */ case IR_CONV: asm_conv(as, ir); break; case IR_TOSTR: asm_tostr(as, ir); break; case IR_STRTO: asm_strto(as, ir); break; /* Calls. */ case IR_CALLA: as->gcsteps++; /* fallthrough */ case IR_CALLN: case IR_CALLL: case IR_CALLS: asm_call(as, ir); break; case IR_CALLXS: asm_callx(as, ir); break; case IR_CARG: break; default: setintV(&as->J->errinfo, ir->o); lj_trace_err_info(as->J, LJ_TRERR_NYIIR); break; } } /* -- Head of trace ------------------------------------------------------- */ /* Head of a root trace. */ static void asm_head_root(ASMState *as) { int32_t spadj; asm_head_root_base(as); emit_setvmstate(as, (int32_t)as->T->traceno); spadj = asm_stack_adjust(as); as->T->spadjust = (uint16_t)spadj; emit_spsub(as, spadj); /* Root traces assume a checked stack for the starting proto. */ as->T->topslot = gcref(as->T->startpt)->pt.framesize; } /* Head of a side trace. ** ** The current simplistic algorithm requires that all slots inherited ** from the parent are live in a register between pass 2 and pass 3. This ** avoids the complexity of stack slot shuffling. But of course this may ** overflow the register set in some cases and cause the dreaded error: ** "NYI: register coalescing too complex". A refined algorithm is needed. */ static void asm_head_side(ASMState *as) { IRRef1 sloadins[RID_MAX]; RegSet allow = RSET_ALL; /* Inverse of all coalesced registers. */ RegSet live = RSET_EMPTY; /* Live parent registers. */ IRIns *irp = &as->parent->ir[REF_BASE]; /* Parent base. */ int32_t spadj, spdelta; int pass2 = 0; int pass3 = 0; IRRef i; if (as->snapno && as->topslot > as->parent->topslot) { /* Force snap #0 alloc to prevent register overwrite in stack check. */ as->snapno = 0; asm_snap_alloc(as); } allow = asm_head_side_base(as, irp, allow); /* Scan all parent SLOADs and collect register dependencies. */ for (i = as->stopins; i > REF_BASE; i--) { IRIns *ir = IR(i); RegSP rs; lua_assert((ir->o == IR_SLOAD && (ir->op2 & IRSLOAD_PARENT)) || (LJ_SOFTFP && ir->o == IR_HIOP) || ir->o == IR_PVAL); rs = as->parentmap[i - REF_FIRST]; if (ra_hasreg(ir->r)) { rset_clear(allow, ir->r); if (ra_hasspill(ir->s)) { ra_save(as, ir, ir->r); checkmclim(as); } } else if (ra_hasspill(ir->s)) { irt_setmark(ir->t); pass2 = 1; } if (ir->r == rs) { /* Coalesce matching registers right now. */ ra_free(as, ir->r); } else if (ra_hasspill(regsp_spill(rs))) { if (ra_hasreg(ir->r)) pass3 = 1; } else if (ra_used(ir)) { sloadins[rs] = (IRRef1)i; rset_set(live, rs); /* Block live parent register. */ } } /* Calculate stack frame adjustment. */ spadj = asm_stack_adjust(as); spdelta = spadj - (int32_t)as->parent->spadjust; if (spdelta < 0) { /* Don't shrink the stack frame. */ spadj = (int32_t)as->parent->spadjust; spdelta = 0; } as->T->spadjust = (uint16_t)spadj; /* Reload spilled target registers. */ if (pass2) { for (i = as->stopins; i > REF_BASE; i--) { IRIns *ir = IR(i); if (irt_ismarked(ir->t)) { RegSet mask; Reg r; RegSP rs; irt_clearmark(ir->t); rs = as->parentmap[i - REF_FIRST]; if (!ra_hasspill(regsp_spill(rs))) ra_sethint(ir->r, rs); /* Hint may be gone, set it again. */ else if (sps_scale(regsp_spill(rs))+spdelta == sps_scale(ir->s)) continue; /* Same spill slot, do nothing. */ mask = ((!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR) & allow; if (mask == RSET_EMPTY) lj_trace_err(as->J, LJ_TRERR_NYICOAL); r = ra_allocref(as, i, mask); ra_save(as, ir, r); rset_clear(allow, r); if (r == rs) { /* Coalesce matching registers right now. */ ra_free(as, r); rset_clear(live, r); } else if (ra_hasspill(regsp_spill(rs))) { pass3 = 1; } checkmclim(as); } } } /* Store trace number and adjust stack frame relative to the parent. */ emit_setvmstate(as, (int32_t)as->T->traceno); emit_spsub(as, spdelta); #if !LJ_TARGET_X86ORX64 /* Restore BASE register from parent spill slot. */ if (ra_hasspill(irp->s)) emit_spload(as, IR(REF_BASE), IR(REF_BASE)->r, sps_scale(irp->s)); #endif /* Restore target registers from parent spill slots. */ if (pass3) { RegSet work = ~as->freeset & RSET_ALL; while (work) { Reg r = rset_pickbot(work); IRRef ref = regcost_ref(as->cost[r]); RegSP rs = as->parentmap[ref - REF_FIRST]; rset_clear(work, r); if (ra_hasspill(regsp_spill(rs))) { int32_t ofs = sps_scale(regsp_spill(rs)); ra_free(as, r); emit_spload(as, IR(ref), r, ofs); checkmclim(as); } } } /* Shuffle registers to match up target regs with parent regs. */ for (;;) { RegSet work; /* Repeatedly coalesce free live registers by moving to their target. */ while ((work = as->freeset & live) != RSET_EMPTY) { Reg rp = rset_pickbot(work); IRIns *ir = IR(sloadins[rp]); rset_clear(live, rp); rset_clear(allow, rp); ra_free(as, ir->r); emit_movrr(as, ir, ir->r, rp); checkmclim(as); } /* We're done if no live registers remain. */ if (live == RSET_EMPTY) break; /* Break cycles by renaming one target to a temp. register. */ if (live & RSET_GPR) { RegSet tmpset = as->freeset & ~live & allow & RSET_GPR; if (tmpset == RSET_EMPTY) lj_trace_err(as->J, LJ_TRERR_NYICOAL); ra_rename(as, rset_pickbot(live & RSET_GPR), rset_pickbot(tmpset)); } if (!LJ_SOFTFP && (live & RSET_FPR)) { RegSet tmpset = as->freeset & ~live & allow & RSET_FPR; if (tmpset == RSET_EMPTY) lj_trace_err(as->J, LJ_TRERR_NYICOAL); ra_rename(as, rset_pickbot(live & RSET_FPR), rset_pickbot(tmpset)); } checkmclim(as); /* Continue with coalescing to fix up the broken cycle(s). */ } /* Inherit top stack slot already checked by parent trace. */ as->T->topslot = as->parent->topslot; if (as->topslot > as->T->topslot) { /* Need to check for higher slot? */ #ifdef EXITSTATE_CHECKEXIT /* Highest exit + 1 indicates stack check. */ ExitNo exitno = as->T->nsnap; #else /* Reuse the parent exit in the context of the parent trace. */ ExitNo exitno = as->J->exitno; #endif as->T->topslot = (uint8_t)as->topslot; /* Remember for child traces. */ asm_stack_check(as, as->topslot, irp, allow & RSET_GPR, exitno); } } /* -- Tail of trace ------------------------------------------------------- */ /* Get base slot for a snapshot. */ static BCReg asm_baseslot(ASMState *as, SnapShot *snap, int *gotframe) { SnapEntry *map = &as->T->snapmap[snap->mapofs]; MSize n; for (n = snap->nent; n > 0; n--) { SnapEntry sn = map[n-1]; if ((sn & SNAP_FRAME)) { *gotframe = 1; return snap_slot(sn); } } return 0; } /* Link to another trace. */ static void asm_tail_link(ASMState *as) { SnapNo snapno = as->T->nsnap-1; /* Last snapshot. */ SnapShot *snap = &as->T->snap[snapno]; int gotframe = 0; BCReg baseslot = asm_baseslot(as, snap, &gotframe); as->topslot = snap->topslot; checkmclim(as); ra_allocref(as, REF_BASE, RID2RSET(RID_BASE)); if (as->T->link == 0) { /* Setup fixed registers for exit to interpreter. */ const BCIns *pc = snap_pc(as->T->snapmap[snap->mapofs + snap->nent]); int32_t mres; if (bc_op(*pc) == BC_JLOOP) { /* NYI: find a better way to do this. */ BCIns *retpc = &traceref(as->J, bc_d(*pc))->startins; if (bc_isret(bc_op(*retpc))) pc = retpc; } ra_allockreg(as, i32ptr(J2GG(as->J)->dispatch), RID_DISPATCH); ra_allockreg(as, i32ptr(pc), RID_LPC); mres = (int32_t)(snap->nslots - baseslot); switch (bc_op(*pc)) { case BC_CALLM: case BC_CALLMT: mres -= (int32_t)(1 + LJ_FR2 + bc_a(*pc) + bc_c(*pc)); break; case BC_RETM: mres -= (int32_t)(bc_a(*pc) + bc_d(*pc)); break; case BC_TSETM: mres -= (int32_t)bc_a(*pc); break; default: if (bc_op(*pc) < BC_FUNCF) mres = 0; break; } ra_allockreg(as, mres, RID_RET); /* Return MULTRES or 0. */ } else if (baseslot) { /* Save modified BASE for linking to trace with higher start frame. */ emit_setgl(as, RID_BASE, jit_base); } emit_addptr(as, RID_BASE, 8*(int32_t)baseslot); /* Sync the interpreter state with the on-trace state. */ asm_stack_restore(as, snap); /* Root traces that add frames need to check the stack at the end. */ if (!as->parent && gotframe) asm_stack_check(as, as->topslot, NULL, as->freeset & RSET_GPR, snapno); } /* -- Trace setup --------------------------------------------------------- */ /* Clear reg/sp for all instructions and add register hints. */ static void asm_setup_regsp(ASMState *as) { GCtrace *T = as->T; int sink = T->sinktags; IRRef nins = T->nins; IRIns *ir, *lastir; int inloop; #if LJ_TARGET_ARM uint32_t rload = 0xa6402a64; #endif ra_setup(as); /* Clear reg/sp for constants. */ for (ir = IR(T->nk), lastir = IR(REF_BASE); ir < lastir; ir++) ir->prev = REGSP_INIT; /* REF_BASE is used for implicit references to the BASE register. */ lastir->prev = REGSP_HINT(RID_BASE); ir = IR(nins-1); if (ir->o == IR_RENAME) { do { ir--; nins--; } while (ir->o == IR_RENAME); T->nins = nins; /* Remove any renames left over from ASM restart. */ } as->snaprename = nins; as->snapref = nins; as->snapno = T->nsnap; as->stopins = REF_BASE; as->orignins = nins; as->curins = nins; /* Setup register hints for parent link instructions. */ ir = IR(REF_FIRST); if (as->parent) { uint16_t *p; lastir = lj_snap_regspmap(as->parent, as->J->exitno, ir); if (lastir - ir > LJ_MAX_JSLOTS) lj_trace_err(as->J, LJ_TRERR_NYICOAL); as->stopins = (IRRef)((lastir-1) - as->ir); for (p = as->parentmap; ir < lastir; ir++) { RegSP rs = ir->prev; *p++ = (uint16_t)rs; /* Copy original parent RegSP to parentmap. */ if (!ra_hasspill(regsp_spill(rs))) ir->prev = (uint16_t)REGSP_HINT(regsp_reg(rs)); else ir->prev = REGSP_INIT; } } inloop = 0; as->evenspill = SPS_FIRST; for (lastir = IR(nins); ir < lastir; ir++) { if (sink) { if (ir->r == RID_SINK) continue; if (ir->r == RID_SUNK) { /* Revert after ASM restart. */ ir->r = RID_SINK; continue; } } switch (ir->o) { case IR_LOOP: inloop = 1; break; #if LJ_TARGET_ARM case IR_SLOAD: if (!((ir->op2 & IRSLOAD_TYPECHECK) || (ir+1)->o == IR_HIOP)) break; /* fallthrough */ case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD: if (!LJ_SOFTFP && irt_isnum(ir->t)) break; ir->prev = (uint16_t)REGSP_HINT((rload & 15)); rload = lj_ror(rload, 4); continue; #endif case IR_CALLXS: { CCallInfo ci; ci.flags = asm_callx_flags(as, ir); ir->prev = asm_setup_call_slots(as, ir, &ci); if (inloop) as->modset |= RSET_SCRATCH; continue; } case IR_CALLN: case IR_CALLA: case IR_CALLL: case IR_CALLS: { const CCallInfo *ci = &lj_ir_callinfo[ir->op2]; ir->prev = asm_setup_call_slots(as, ir, ci); if (inloop) as->modset |= (ci->flags & CCI_NOFPRCLOBBER) ? (RSET_SCRATCH & ~RSET_FPR) : RSET_SCRATCH; continue; } #if LJ_SOFTFP || (LJ_32 && LJ_HASFFI) case IR_HIOP: switch ((ir-1)->o) { #if LJ_SOFTFP && LJ_TARGET_ARM case IR_SLOAD: case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD: if (ra_hashint((ir-1)->r)) { ir->prev = (ir-1)->prev + 1; continue; } break; #endif #if !LJ_SOFTFP && LJ_NEED_FP64 case IR_CONV: if (irt_isfp((ir-1)->t)) { ir->prev = REGSP_HINT(RID_FPRET); continue; } /* fallthrough */ #endif case IR_CALLN: case IR_CALLXS: #if LJ_SOFTFP case IR_MIN: case IR_MAX: #endif (ir-1)->prev = REGSP_HINT(RID_RETLO); ir->prev = REGSP_HINT(RID_RETHI); continue; default: break; } break; #endif #if LJ_SOFTFP case IR_MIN: case IR_MAX: if ((ir+1)->o != IR_HIOP) break; /* fallthrough */ #endif /* C calls evict all scratch regs and return results in RID_RET. */ case IR_SNEW: case IR_XSNEW: case IR_NEWREF: case IR_BUFPUT: if (REGARG_NUMGPR < 3 && as->evenspill < 3) as->evenspill = 3; /* lj_str_new and lj_tab_newkey need 3 args. */ #if LJ_TARGET_X86 && LJ_HASFFI if (0) { case IR_CNEW: if (ir->op2 != REF_NIL && as->evenspill < 4) as->evenspill = 4; /* lj_cdata_newv needs 4 args. */ } #else case IR_CNEW: #endif case IR_TNEW: case IR_TDUP: case IR_CNEWI: case IR_TOSTR: case IR_BUFSTR: ir->prev = REGSP_HINT(RID_RET); if (inloop) as->modset = RSET_SCRATCH; continue; case IR_STRTO: case IR_OBAR: if (inloop) as->modset = RSET_SCRATCH; break; #if !LJ_SOFTFP case IR_ATAN2: #if LJ_TARGET_X86 if (as->evenspill < 4) /* Leave room to call atan2(). */ as->evenspill = 4; #endif #if !LJ_TARGET_X86ORX64 case IR_LDEXP: #endif #endif case IR_POW: if (!LJ_SOFTFP && irt_isnum(ir->t)) { if (inloop) as->modset |= RSET_SCRATCH; #if LJ_TARGET_X86 break; #else ir->prev = REGSP_HINT(RID_FPRET); continue; #endif } /* fallthrough for integer POW */ case IR_DIV: case IR_MOD: if (!irt_isnum(ir->t)) { ir->prev = REGSP_HINT(RID_RET); if (inloop) as->modset |= (RSET_SCRATCH & RSET_GPR); continue; } break; case IR_FPMATH: #if LJ_TARGET_X86ORX64 if (ir->op2 <= IRFPM_TRUNC) { if (!(as->flags & JIT_F_SSE4_1)) { ir->prev = REGSP_HINT(RID_XMM0); if (inloop) as->modset |= RSET_RANGE(RID_XMM0, RID_XMM3+1)|RID2RSET(RID_EAX); continue; } break; } else if (ir->op2 == IRFPM_EXP2 && !LJ_64) { if (as->evenspill < 4) /* Leave room to call pow(). */ as->evenspill = 4; } #endif if (inloop) as->modset |= RSET_SCRATCH; #if LJ_TARGET_X86 break; #else ir->prev = REGSP_HINT(RID_FPRET); continue; #endif #if LJ_TARGET_X86ORX64 /* Non-constant shift counts need to be in RID_ECX on x86/x64. */ case IR_BSHL: case IR_BSHR: case IR_BSAR: case IR_BROL: case IR_BROR: if (!irref_isk(ir->op2) && !ra_hashint(IR(ir->op2)->r)) { IR(ir->op2)->r = REGSP_HINT(RID_ECX); if (inloop) rset_set(as->modset, RID_ECX); } break; #endif /* Do not propagate hints across type conversions or loads. */ case IR_TOBIT: case IR_XLOAD: #if !LJ_TARGET_ARM case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD: #endif break; case IR_CONV: if (irt_isfp(ir->t) || (ir->op2 & IRCONV_SRCMASK) == IRT_NUM || (ir->op2 & IRCONV_SRCMASK) == IRT_FLOAT) break; /* fallthrough */ default: /* Propagate hints across likely 'op reg, imm' or 'op reg'. */ if (irref_isk(ir->op2) && !irref_isk(ir->op1) && ra_hashint(regsp_reg(IR(ir->op1)->prev))) { ir->prev = IR(ir->op1)->prev; continue; } break; } ir->prev = REGSP_INIT; } if ((as->evenspill & 1)) as->oddspill = as->evenspill++; else as->oddspill = 0; } /* -- Assembler core ------------------------------------------------------ */ /* Assemble a trace. */ void lj_asm_trace(jit_State *J, GCtrace *T) { ASMState as_; ASMState *as = &as_; MCode *origtop; /* Ensure an initialized instruction beyond the last one for HIOP checks. */ J->cur.nins = lj_ir_nextins(J); J->cur.ir[J->cur.nins].o = IR_NOP; /* Setup initial state. Copy some fields to reduce indirections. */ as->J = J; as->T = T; as->ir = T->ir; as->flags = J->flags; as->loopref = J->loopref; as->realign = NULL; as->loopinv = 0; as->parent = J->parent ? traceref(J, J->parent) : NULL; /* Reserve MCode memory. */ as->mctop = origtop = lj_mcode_reserve(J, &as->mcbot); as->mcp = as->mctop; as->mclim = as->mcbot + MCLIM_REDZONE; asm_setup_target(as); do { as->mcp = as->mctop; #ifdef LUA_USE_ASSERT as->mcp_prev = as->mcp; #endif as->curins = T->nins; RA_DBG_START(); RA_DBGX((as, "===== STOP =====")); /* General trace setup. Emit tail of trace. */ asm_tail_prep(as); as->mcloop = NULL; as->flagmcp = NULL; as->topslot = 0; as->gcsteps = 0; as->sectref = as->loopref; as->fuseref = (as->flags & JIT_F_OPT_FUSE) ? as->loopref : FUSE_DISABLED; asm_setup_regsp(as); if (!as->loopref) asm_tail_link(as); /* Assemble a trace in linear backwards order. */ for (as->curins--; as->curins > as->stopins; as->curins--) { IRIns *ir = IR(as->curins); lua_assert(!(LJ_32 && irt_isint64(ir->t))); /* Handled by SPLIT. */ if (!ra_used(ir) && !ir_sideeff(ir) && (as->flags & JIT_F_OPT_DCE)) continue; /* Dead-code elimination can be soooo easy. */ if (irt_isguard(ir->t)) asm_snap_prep(as); RA_DBG_REF(); checkmclim(as); asm_ir(as, ir); } } while (as->realign); /* Retry in case the MCode needs to be realigned. */ /* Emit head of trace. */ RA_DBG_REF(); checkmclim(as); if (as->gcsteps > 0) { as->curins = as->T->snap[0].ref; asm_snap_prep(as); /* The GC check is a guard. */ asm_gc_check(as); } ra_evictk(as); if (as->parent) asm_head_side(as); else asm_head_root(as); asm_phi_fixup(as); RA_DBGX((as, "===== START ====")); RA_DBG_FLUSH(); if (as->freeset != RSET_ALL) lj_trace_err(as->J, LJ_TRERR_BADRA); /* Ouch! Should never happen. */ /* Set trace entry point before fixing up tail to allow link to self. */ T->mcode = as->mcp; T->mcloop = as->mcloop ? (MSize)((char *)as->mcloop - (char *)as->mcp) : 0; if (!as->loopref) asm_tail_fixup(as, T->link); /* Note: this may change as->mctop! */ T->szmcode = (MSize)((char *)as->mctop - (char *)as->mcp); lj_mcode_sync(T->mcode, origtop); } #undef IR #endif
xLua/build/luajit-2.1.0b2/src/lj_asm.c/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lj_asm.c", "repo_id": "xLua", "token_count": 31215 }
2,103
/* ** FFI C call handling. ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ #ifndef _LJ_CCALL_H #define _LJ_CCALL_H #include "lj_obj.h" #include "lj_ctype.h" #if LJ_HASFFI /* -- C calling conventions ----------------------------------------------- */ #if LJ_TARGET_X86ORX64 #if LJ_TARGET_X86 #define CCALL_NARG_GPR 2 /* For fastcall arguments. */ #define CCALL_NARG_FPR 0 #define CCALL_NRET_GPR 2 #define CCALL_NRET_FPR 1 /* For FP results on x87 stack. */ #define CCALL_ALIGN_STACKARG 0 /* Don't align argument on stack. */ #elif LJ_ABI_WIN #define CCALL_NARG_GPR 4 #define CCALL_NARG_FPR 4 #define CCALL_NRET_GPR 1 #define CCALL_NRET_FPR 1 #define CCALL_SPS_EXTRA 4 #else #define CCALL_NARG_GPR 6 #define CCALL_NARG_FPR 8 #define CCALL_NRET_GPR 2 #define CCALL_NRET_FPR 2 #define CCALL_VECTOR_REG 1 /* Pass vectors in registers. */ #endif #define CCALL_SPS_FREE 1 #define CCALL_ALIGN_CALLSTATE 16 typedef LJ_ALIGN(16) union FPRArg { double d[2]; float f[4]; uint8_t b[16]; uint16_t s[8]; int i[4]; int64_t l[2]; } FPRArg; typedef intptr_t GPRArg; #elif LJ_TARGET_ARM #define CCALL_NARG_GPR 4 #define CCALL_NRET_GPR 2 /* For softfp double. */ #if LJ_ABI_SOFTFP #define CCALL_NARG_FPR 0 #define CCALL_NRET_FPR 0 #else #define CCALL_NARG_FPR 8 #define CCALL_NRET_FPR 4 #endif #define CCALL_SPS_FREE 0 typedef intptr_t GPRArg; typedef union FPRArg { double d; float f[2]; } FPRArg; #elif LJ_TARGET_ARM64 #define CCALL_NARG_GPR 8 #define CCALL_NRET_GPR 2 #define CCALL_NARG_FPR 8 #define CCALL_NRET_FPR 4 #define CCALL_SPS_FREE 0 typedef intptr_t GPRArg; typedef union FPRArg { double d; float f; uint32_t u32; } FPRArg; #elif LJ_TARGET_PPC #define CCALL_NARG_GPR 8 #define CCALL_NARG_FPR 8 #define CCALL_NRET_GPR 4 /* For complex double. */ #define CCALL_NRET_FPR 1 #define CCALL_SPS_EXTRA 4 #define CCALL_SPS_FREE 0 typedef intptr_t GPRArg; typedef double FPRArg; #elif LJ_TARGET_MIPS #define CCALL_NARG_GPR 4 #define CCALL_NARG_FPR (LJ_ABI_SOFTFP ? 0 : 2) #define CCALL_NRET_GPR 2 #define CCALL_NRET_FPR (LJ_ABI_SOFTFP ? 0 : 2) #define CCALL_SPS_EXTRA 7 #define CCALL_SPS_FREE 1 typedef intptr_t GPRArg; typedef union FPRArg { double d; struct { LJ_ENDIAN_LOHI(float f; , float g;) }; } FPRArg; #else #error "Missing calling convention definitions for this architecture" #endif #ifndef CCALL_SPS_EXTRA #define CCALL_SPS_EXTRA 0 #endif #ifndef CCALL_VECTOR_REG #define CCALL_VECTOR_REG 0 #endif #ifndef CCALL_ALIGN_STACKARG #define CCALL_ALIGN_STACKARG 1 #endif #ifndef CCALL_ALIGN_CALLSTATE #define CCALL_ALIGN_CALLSTATE 8 #endif #define CCALL_NUM_GPR \ (CCALL_NARG_GPR > CCALL_NRET_GPR ? CCALL_NARG_GPR : CCALL_NRET_GPR) #define CCALL_NUM_FPR \ (CCALL_NARG_FPR > CCALL_NRET_FPR ? CCALL_NARG_FPR : CCALL_NRET_FPR) /* Check against constants in lj_ctype.h. */ LJ_STATIC_ASSERT(CCALL_NUM_GPR <= CCALL_MAX_GPR); LJ_STATIC_ASSERT(CCALL_NUM_FPR <= CCALL_MAX_FPR); #define CCALL_MAXSTACK 32 /* -- C call state -------------------------------------------------------- */ typedef LJ_ALIGN(CCALL_ALIGN_CALLSTATE) struct CCallState { void (*func)(void); /* Pointer to called function. */ uint32_t spadj; /* Stack pointer adjustment. */ uint8_t nsp; /* Number of stack slots. */ uint8_t retref; /* Return value by reference. */ #if LJ_TARGET_X64 uint8_t ngpr; /* Number of arguments in GPRs. */ uint8_t nfpr; /* Number of arguments in FPRs. */ #elif LJ_TARGET_X86 uint8_t resx87; /* Result on x87 stack: 1:float, 2:double. */ #elif LJ_TARGET_ARM64 void *retp; /* Aggregate return pointer in x8. */ #elif LJ_TARGET_PPC uint8_t nfpr; /* Number of arguments in FPRs. */ #endif #if LJ_32 int32_t align1; #endif #if CCALL_NUM_FPR FPRArg fpr[CCALL_NUM_FPR]; /* Arguments/results in FPRs. */ #endif GPRArg gpr[CCALL_NUM_GPR]; /* Arguments/results in GPRs. */ GPRArg stack[CCALL_MAXSTACK]; /* Stack slots. */ } CCallState; /* -- C call handling ----------------------------------------------------- */ /* Really belongs to lj_vm.h. */ LJ_ASMF void LJ_FASTCALL lj_vm_ffi_call(CCallState *cc); LJ_FUNC CTypeID lj_ccall_ctid_vararg(CTState *cts, cTValue *o); LJ_FUNC int lj_ccall_func(lua_State *L, GCcdata *cd); #endif #endif
xLua/build/luajit-2.1.0b2/src/lj_ccall.h/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lj_ccall.h", "repo_id": "xLua", "token_count": 1981 }
2,104
/* ** C type management. ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ #ifndef _LJ_CTYPE_H #define _LJ_CTYPE_H #include "lj_obj.h" #include "lj_gc.h" #if LJ_HASFFI /* -- C type definitions -------------------------------------------------- */ /* C type numbers. Highest 4 bits of C type info. ORDER CT. */ enum { /* Externally visible types. */ CT_NUM, /* Integer or floating-point numbers. */ CT_STRUCT, /* Struct or union. */ CT_PTR, /* Pointer or reference. */ CT_ARRAY, /* Array or complex type. */ CT_MAYCONVERT = CT_ARRAY, CT_VOID, /* Void type. */ CT_ENUM, /* Enumeration. */ CT_HASSIZE = CT_ENUM, /* Last type where ct->size holds the actual size. */ CT_FUNC, /* Function. */ CT_TYPEDEF, /* Typedef. */ CT_ATTRIB, /* Miscellaneous attributes. */ /* Internal element types. */ CT_FIELD, /* Struct/union field or function parameter. */ CT_BITFIELD, /* Struct/union bitfield. */ CT_CONSTVAL, /* Constant value. */ CT_EXTERN, /* External reference. */ CT_KW /* Keyword. */ }; LJ_STATIC_ASSERT(((int)CT_PTR & (int)CT_ARRAY) == CT_PTR); LJ_STATIC_ASSERT(((int)CT_STRUCT & (int)CT_ARRAY) == CT_STRUCT); /* ** ---------- info ------------ ** |type flags... A cid | size | sib | next | name | ** +----------------------------+--------+-------+-------+-------+-- ** |NUM BFvcUL.. A | size | | type | | ** |STRUCT ..vcU..V A | size | field | name? | name? | ** |PTR ..vcR... A cid | size | | type | | ** |ARRAY VCvc...V A cid | size | | type | | ** |VOID ..vc.... A | size | | type | | ** |ENUM A cid | size | const | name? | name? | ** |FUNC ....VS.. cc cid | nargs | field | name? | name? | ** |TYPEDEF cid | | | name | name | ** |ATTRIB attrnum cid | attr | sib? | type? | | ** |FIELD cid | offset | field | | name? | ** |BITFIELD B.vcU csz bsz pos | offset | field | | name? | ** |CONSTVAL c cid | value | const | name | name | ** |EXTERN cid | | sib? | name | name | ** |KW tok | size | | name | name | ** +----------------------------+--------+-------+-------+-------+-- ** ^^ ^^--- bits used for C type conversion dispatch */ /* C type info flags. TFFArrrr */ #define CTF_BOOL 0x08000000u /* Boolean: NUM, BITFIELD. */ #define CTF_FP 0x04000000u /* Floating-point: NUM. */ #define CTF_CONST 0x02000000u /* Const qualifier. */ #define CTF_VOLATILE 0x01000000u /* Volatile qualifier. */ #define CTF_UNSIGNED 0x00800000u /* Unsigned: NUM, BITFIELD. */ #define CTF_LONG 0x00400000u /* Long: NUM. */ #define CTF_VLA 0x00100000u /* Variable-length: ARRAY, STRUCT. */ #define CTF_REF 0x00800000u /* Reference: PTR. */ #define CTF_VECTOR 0x08000000u /* Vector: ARRAY. */ #define CTF_COMPLEX 0x04000000u /* Complex: ARRAY. */ #define CTF_UNION 0x00800000u /* Union: STRUCT. */ #define CTF_VARARG 0x00800000u /* Vararg: FUNC. */ #define CTF_SSEREGPARM 0x00400000u /* SSE register parameters: FUNC. */ #define CTF_QUAL (CTF_CONST|CTF_VOLATILE) #define CTF_ALIGN (CTMASK_ALIGN<<CTSHIFT_ALIGN) #define CTF_UCHAR ((char)-1 > 0 ? CTF_UNSIGNED : 0) /* Flags used in parser. .F.Ammvf cp->attr */ #define CTFP_ALIGNED 0x00000001u /* cp->attr + ALIGN */ #define CTFP_PACKED 0x00000002u /* cp->attr */ /* ...C...f cp->fattr */ #define CTFP_CCONV 0x00000001u /* cp->fattr + CCONV/[SSE]REGPARM */ /* C type info bitfields. */ #define CTMASK_CID 0x0000ffffu /* Max. 65536 type IDs. */ #define CTMASK_NUM 0xf0000000u /* Max. 16 type numbers. */ #define CTSHIFT_NUM 28 #define CTMASK_ALIGN 15 /* Max. alignment is 2^15. */ #define CTSHIFT_ALIGN 16 #define CTMASK_ATTRIB 255 /* Max. 256 attributes. */ #define CTSHIFT_ATTRIB 16 #define CTMASK_CCONV 3 /* Max. 4 calling conventions. */ #define CTSHIFT_CCONV 16 #define CTMASK_REGPARM 3 /* Max. 0-3 regparms. */ #define CTSHIFT_REGPARM 18 /* Bitfields only used in parser. */ #define CTMASK_VSIZEP 15 /* Max. vector size is 2^15. */ #define CTSHIFT_VSIZEP 4 #define CTMASK_MSIZEP 255 /* Max. type size (via mode) is 128. */ #define CTSHIFT_MSIZEP 8 /* Info bits for BITFIELD. Max. size of bitfield is 64 bits. */ #define CTBSZ_MAX 32 /* Max. size of bitfield is 32 bit. */ #define CTBSZ_FIELD 127 /* Temp. marker for regular field. */ #define CTMASK_BITPOS 127 #define CTMASK_BITBSZ 127 #define CTMASK_BITCSZ 127 #define CTSHIFT_BITPOS 0 #define CTSHIFT_BITBSZ 8 #define CTSHIFT_BITCSZ 16 #define CTF_INSERT(info, field, val) \ info = (info & ~(CTMASK_##field<<CTSHIFT_##field)) | \ (((CTSize)(val) & CTMASK_##field) << CTSHIFT_##field) /* Calling conventions. ORDER CC */ enum { CTCC_CDECL, CTCC_THISCALL, CTCC_FASTCALL, CTCC_STDCALL }; /* Attribute numbers. */ enum { CTA_NONE, /* Ignored attribute. Must be zero. */ CTA_QUAL, /* Unmerged qualifiers. */ CTA_ALIGN, /* Alignment override. */ CTA_SUBTYPE, /* Transparent sub-type. */ CTA_REDIR, /* Redirected symbol name. */ CTA_BAD, /* To catch bad IDs. */ CTA__MAX }; /* Special sizes. */ #define CTSIZE_INVALID 0xffffffffu typedef uint32_t CTInfo; /* Type info. */ typedef uint32_t CTSize; /* Type size. */ typedef uint32_t CTypeID; /* Type ID. */ typedef uint16_t CTypeID1; /* Minimum-sized type ID. */ /* C type table element. */ typedef struct CType { CTInfo info; /* Type info. */ CTSize size; /* Type size or other info. */ CTypeID1 sib; /* Sibling element. */ CTypeID1 next; /* Next element in hash chain. */ GCRef name; /* Element name (GCstr). */ } CType; #define CTHASH_SIZE 128 /* Number of hash anchors. */ #define CTHASH_MASK (CTHASH_SIZE-1) /* Simplify target-specific configuration. Checked in lj_ccall.h. */ #define CCALL_MAX_GPR 8 #define CCALL_MAX_FPR 8 typedef LJ_ALIGN(8) union FPRCBArg { double d; float f[2]; } FPRCBArg; /* C callback state. Defined here, to avoid dragging in lj_ccall.h. */ typedef LJ_ALIGN(8) struct CCallback { FPRCBArg fpr[CCALL_MAX_FPR]; /* Arguments/results in FPRs. */ intptr_t gpr[CCALL_MAX_GPR]; /* Arguments/results in GPRs. */ intptr_t *stack; /* Pointer to arguments on stack. */ void *mcode; /* Machine code for callback func. pointers. */ CTypeID1 *cbid; /* Callback type table. */ MSize sizeid; /* Size of callback type table. */ MSize topid; /* Highest unused callback type table slot. */ MSize slot; /* Current callback slot. */ } CCallback; /* C type state. */ typedef struct CTState { CType *tab; /* C type table. */ CTypeID top; /* Current top of C type table. */ MSize sizetab; /* Size of C type table. */ lua_State *L; /* Lua state (needed for errors and allocations). */ global_State *g; /* Global state. */ GCtab *finalizer; /* Map of cdata to finalizer. */ GCtab *miscmap; /* Map of -CTypeID to metatable and cb slot to func. */ CCallback cb; /* Temporary callback state. */ CTypeID1 hash[CTHASH_SIZE]; /* Hash anchors for C type table. */ } CTState; #define CTINFO(ct, flags) (((CTInfo)(ct) << CTSHIFT_NUM) + (flags)) #define CTALIGN(al) ((CTSize)(al) << CTSHIFT_ALIGN) #define CTATTRIB(at) ((CTInfo)(at) << CTSHIFT_ATTRIB) #define ctype_type(info) ((info) >> CTSHIFT_NUM) #define ctype_cid(info) ((CTypeID)((info) & CTMASK_CID)) #define ctype_align(info) (((info) >> CTSHIFT_ALIGN) & CTMASK_ALIGN) #define ctype_attrib(info) (((info) >> CTSHIFT_ATTRIB) & CTMASK_ATTRIB) #define ctype_bitpos(info) (((info) >> CTSHIFT_BITPOS) & CTMASK_BITPOS) #define ctype_bitbsz(info) (((info) >> CTSHIFT_BITBSZ) & CTMASK_BITBSZ) #define ctype_bitcsz(info) (((info) >> CTSHIFT_BITCSZ) & CTMASK_BITCSZ) #define ctype_vsizeP(info) (((info) >> CTSHIFT_VSIZEP) & CTMASK_VSIZEP) #define ctype_msizeP(info) (((info) >> CTSHIFT_MSIZEP) & CTMASK_MSIZEP) #define ctype_cconv(info) (((info) >> CTSHIFT_CCONV) & CTMASK_CCONV) /* Simple type checks. */ #define ctype_isnum(info) (ctype_type((info)) == CT_NUM) #define ctype_isvoid(info) (ctype_type((info)) == CT_VOID) #define ctype_isptr(info) (ctype_type((info)) == CT_PTR) #define ctype_isarray(info) (ctype_type((info)) == CT_ARRAY) #define ctype_isstruct(info) (ctype_type((info)) == CT_STRUCT) #define ctype_isfunc(info) (ctype_type((info)) == CT_FUNC) #define ctype_isenum(info) (ctype_type((info)) == CT_ENUM) #define ctype_istypedef(info) (ctype_type((info)) == CT_TYPEDEF) #define ctype_isattrib(info) (ctype_type((info)) == CT_ATTRIB) #define ctype_isfield(info) (ctype_type((info)) == CT_FIELD) #define ctype_isbitfield(info) (ctype_type((info)) == CT_BITFIELD) #define ctype_isconstval(info) (ctype_type((info)) == CT_CONSTVAL) #define ctype_isextern(info) (ctype_type((info)) == CT_EXTERN) #define ctype_hassize(info) (ctype_type((info)) <= CT_HASSIZE) /* Combined type and flag checks. */ #define ctype_isinteger(info) \ (((info) & (CTMASK_NUM|CTF_BOOL|CTF_FP)) == CTINFO(CT_NUM, 0)) #define ctype_isinteger_or_bool(info) \ (((info) & (CTMASK_NUM|CTF_FP)) == CTINFO(CT_NUM, 0)) #define ctype_isbool(info) \ (((info) & (CTMASK_NUM|CTF_BOOL)) == CTINFO(CT_NUM, CTF_BOOL)) #define ctype_isfp(info) \ (((info) & (CTMASK_NUM|CTF_FP)) == CTINFO(CT_NUM, CTF_FP)) #define ctype_ispointer(info) \ ((ctype_type(info) >> 1) == (CT_PTR >> 1)) /* Pointer or array. */ #define ctype_isref(info) \ (((info) & (CTMASK_NUM|CTF_REF)) == CTINFO(CT_PTR, CTF_REF)) #define ctype_isrefarray(info) \ (((info) & (CTMASK_NUM|CTF_VECTOR|CTF_COMPLEX)) == CTINFO(CT_ARRAY, 0)) #define ctype_isvector(info) \ (((info) & (CTMASK_NUM|CTF_VECTOR)) == CTINFO(CT_ARRAY, CTF_VECTOR)) #define ctype_iscomplex(info) \ (((info) & (CTMASK_NUM|CTF_COMPLEX)) == CTINFO(CT_ARRAY, CTF_COMPLEX)) #define ctype_isvltype(info) \ (((info) & ((CTMASK_NUM|CTF_VLA) - (2u<<CTSHIFT_NUM))) == \ CTINFO(CT_STRUCT, CTF_VLA)) /* VL array or VL struct. */ #define ctype_isvlarray(info) \ (((info) & (CTMASK_NUM|CTF_VLA)) == CTINFO(CT_ARRAY, CTF_VLA)) #define ctype_isxattrib(info, at) \ (((info) & (CTMASK_NUM|CTATTRIB(CTMASK_ATTRIB))) == \ CTINFO(CT_ATTRIB, CTATTRIB(at))) /* Target-dependent sizes and alignments. */ #if LJ_64 #define CTSIZE_PTR 8 #define CTALIGN_PTR CTALIGN(3) #else #define CTSIZE_PTR 4 #define CTALIGN_PTR CTALIGN(2) #endif #define CTINFO_REF(ref) \ CTINFO(CT_PTR, (CTF_CONST|CTF_REF|CTALIGN_PTR) + (ref)) #define CT_MEMALIGN 3 /* Alignment guaranteed by memory allocator. */ /* -- Predefined types ---------------------------------------------------- */ /* Target-dependent types. */ #if LJ_TARGET_PPC #define CTTYDEFP(_) \ _(LINT32, 4, CT_NUM, CTF_LONG|CTALIGN(2)) #else #define CTTYDEFP(_) #endif /* Common types. */ #define CTTYDEF(_) \ _(NONE, 0, CT_ATTRIB, CTATTRIB(CTA_BAD)) \ _(VOID, -1, CT_VOID, CTALIGN(0)) \ _(CVOID, -1, CT_VOID, CTF_CONST|CTALIGN(0)) \ _(BOOL, 1, CT_NUM, CTF_BOOL|CTF_UNSIGNED|CTALIGN(0)) \ _(CCHAR, 1, CT_NUM, CTF_CONST|CTF_UCHAR|CTALIGN(0)) \ _(INT8, 1, CT_NUM, CTALIGN(0)) \ _(UINT8, 1, CT_NUM, CTF_UNSIGNED|CTALIGN(0)) \ _(INT16, 2, CT_NUM, CTALIGN(1)) \ _(UINT16, 2, CT_NUM, CTF_UNSIGNED|CTALIGN(1)) \ _(INT32, 4, CT_NUM, CTALIGN(2)) \ _(UINT32, 4, CT_NUM, CTF_UNSIGNED|CTALIGN(2)) \ _(INT64, 8, CT_NUM, CTF_LONG|CTALIGN(3)) \ _(UINT64, 8, CT_NUM, CTF_UNSIGNED|CTF_LONG|CTALIGN(3)) \ _(FLOAT, 4, CT_NUM, CTF_FP|CTALIGN(2)) \ _(DOUBLE, 8, CT_NUM, CTF_FP|CTALIGN(3)) \ _(COMPLEX_FLOAT, 8, CT_ARRAY, CTF_COMPLEX|CTALIGN(2)|CTID_FLOAT) \ _(COMPLEX_DOUBLE, 16, CT_ARRAY, CTF_COMPLEX|CTALIGN(3)|CTID_DOUBLE) \ _(P_VOID, CTSIZE_PTR, CT_PTR, CTALIGN_PTR|CTID_VOID) \ _(P_CVOID, CTSIZE_PTR, CT_PTR, CTALIGN_PTR|CTID_CVOID) \ _(P_CCHAR, CTSIZE_PTR, CT_PTR, CTALIGN_PTR|CTID_CCHAR) \ _(A_CCHAR, -1, CT_ARRAY, CTF_CONST|CTALIGN(0)|CTID_CCHAR) \ _(CTYPEID, 4, CT_ENUM, CTALIGN(2)|CTID_INT32) \ CTTYDEFP(_) \ /* End of type list. */ /* Public predefined type IDs. */ enum { #define CTTYIDDEF(id, sz, ct, info) CTID_##id, CTTYDEF(CTTYIDDEF) #undef CTTYIDDEF /* Predefined typedefs and keywords follow. */ CTID_MAX = 65536 }; /* Target-dependent type IDs. */ #if LJ_64 #define CTID_INT_PSZ CTID_INT64 #define CTID_UINT_PSZ CTID_UINT64 #else #define CTID_INT_PSZ CTID_INT32 #define CTID_UINT_PSZ CTID_UINT32 #endif #if LJ_ABI_WIN #define CTID_WCHAR CTID_UINT16 #elif LJ_TARGET_PPC #define CTID_WCHAR CTID_LINT32 #else #define CTID_WCHAR CTID_INT32 #endif /* -- C tokens and keywords ----------------------------------------------- */ /* C lexer keywords. */ #define CTOKDEF(_) \ _(IDENT, "<identifier>") _(STRING, "<string>") \ _(INTEGER, "<integer>") _(EOF, "<eof>") \ _(OROR, "||") _(ANDAND, "&&") _(EQ, "==") _(NE, "!=") \ _(LE, "<=") _(GE, ">=") _(SHL, "<<") _(SHR, ">>") _(DEREF, "->") /* Simple declaration specifiers. */ #define CDSDEF(_) \ _(VOID) _(BOOL) _(CHAR) _(INT) _(FP) \ _(LONG) _(LONGLONG) _(SHORT) _(COMPLEX) _(SIGNED) _(UNSIGNED) \ _(CONST) _(VOLATILE) _(RESTRICT) _(INLINE) \ _(TYPEDEF) _(EXTERN) _(STATIC) _(AUTO) _(REGISTER) /* C keywords. */ #define CKWDEF(_) \ CDSDEF(_) _(EXTENSION) _(ASM) _(ATTRIBUTE) \ _(DECLSPEC) _(CCDECL) _(PTRSZ) \ _(STRUCT) _(UNION) _(ENUM) \ _(SIZEOF) _(ALIGNOF) /* C token numbers. */ enum { CTOK_OFS = 255, #define CTOKNUM(name, sym) CTOK_##name, #define CKWNUM(name) CTOK_##name, CTOKDEF(CTOKNUM) CKWDEF(CKWNUM) #undef CTOKNUM #undef CKWNUM CTOK_FIRSTDECL = CTOK_VOID, CTOK_FIRSTSCL = CTOK_TYPEDEF, CTOK_LASTDECLFLAG = CTOK_REGISTER, CTOK_LASTDECL = CTOK_ENUM }; /* Declaration specifier flags. */ enum { #define CDSFLAG(name) CDF_##name = (1u << (CTOK_##name - CTOK_FIRSTDECL)), CDSDEF(CDSFLAG) #undef CDSFLAG CDF__END }; #define CDF_SCL (CDF_TYPEDEF|CDF_EXTERN|CDF_STATIC|CDF_AUTO|CDF_REGISTER) /* -- C type management --------------------------------------------------- */ #define ctype_ctsG(g) (mref((g)->ctype_state, CTState)) /* Get C type state. */ static LJ_AINLINE CTState *ctype_cts(lua_State *L) { CTState *cts = ctype_ctsG(G(L)); cts->L = L; /* Save L for errors and allocations. */ return cts; } /* Save and restore state of C type table. */ #define LJ_CTYPE_SAVE(cts) CTState savects_ = *(cts) #define LJ_CTYPE_RESTORE(cts) \ ((cts)->top = savects_.top, \ memcpy((cts)->hash, savects_.hash, sizeof(savects_.hash))) /* Check C type ID for validity when assertions are enabled. */ static LJ_AINLINE CTypeID ctype_check(CTState *cts, CTypeID id) { lua_assert(id > 0 && id < cts->top); UNUSED(cts); return id; } /* Get C type for C type ID. */ static LJ_AINLINE CType *ctype_get(CTState *cts, CTypeID id) { return &cts->tab[ctype_check(cts, id)]; } /* Get C type ID for a C type. */ #define ctype_typeid(cts, ct) ((CTypeID)((ct) - (cts)->tab)) /* Get child C type. */ static LJ_AINLINE CType *ctype_child(CTState *cts, CType *ct) { lua_assert(!(ctype_isvoid(ct->info) || ctype_isstruct(ct->info) || ctype_isbitfield(ct->info))); /* These don't have children. */ return ctype_get(cts, ctype_cid(ct->info)); } /* Get raw type for a C type ID. */ static LJ_AINLINE CType *ctype_raw(CTState *cts, CTypeID id) { CType *ct = ctype_get(cts, id); while (ctype_isattrib(ct->info)) ct = ctype_child(cts, ct); return ct; } /* Get raw type of the child of a C type. */ static LJ_AINLINE CType *ctype_rawchild(CTState *cts, CType *ct) { do { ct = ctype_child(cts, ct); } while (ctype_isattrib(ct->info)); return ct; } /* Set the name of a C type table element. */ static LJ_AINLINE void ctype_setname(CType *ct, GCstr *s) { /* NOBARRIER: mark string as fixed -- the C type table is never collected. */ fixstring(s); setgcref(ct->name, obj2gco(s)); } LJ_FUNC CTypeID lj_ctype_new(CTState *cts, CType **ctp); LJ_FUNC CTypeID lj_ctype_intern(CTState *cts, CTInfo info, CTSize size); LJ_FUNC void lj_ctype_addname(CTState *cts, CType *ct, CTypeID id); LJ_FUNC CTypeID lj_ctype_getname(CTState *cts, CType **ctp, GCstr *name, uint32_t tmask); LJ_FUNC CType *lj_ctype_getfieldq(CTState *cts, CType *ct, GCstr *name, CTSize *ofs, CTInfo *qual); #define lj_ctype_getfield(cts, ct, name, ofs) \ lj_ctype_getfieldq((cts), (ct), (name), (ofs), NULL) LJ_FUNC CType *lj_ctype_rawref(CTState *cts, CTypeID id); LJ_FUNC CTSize lj_ctype_size(CTState *cts, CTypeID id); LJ_FUNC CTSize lj_ctype_vlsize(CTState *cts, CType *ct, CTSize nelem); LJ_FUNC CTInfo lj_ctype_info(CTState *cts, CTypeID id, CTSize *szp); LJ_FUNC cTValue *lj_ctype_meta(CTState *cts, CTypeID id, MMS mm); LJ_FUNC GCstr *lj_ctype_repr(lua_State *L, CTypeID id, GCstr *name); LJ_FUNC GCstr *lj_ctype_repr_int64(lua_State *L, uint64_t n, int isunsigned); LJ_FUNC GCstr *lj_ctype_repr_complex(lua_State *L, void *sp, CTSize size); LJ_FUNC CTState *lj_ctype_init(lua_State *L); LJ_FUNC void lj_ctype_freestate(global_State *g); #endif #endif
xLua/build/luajit-2.1.0b2/src/lj_ctype.h/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lj_ctype.h", "repo_id": "xLua", "token_count": 7738 }
2,105
/* ** Stack frames. ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ #ifndef _LJ_FRAME_H #define _LJ_FRAME_H #include "lj_obj.h" #include "lj_bc.h" /* -- Lua stack frame ----------------------------------------------------- */ /* Frame type markers in LSB of PC (4-byte aligned) or delta (8-byte aligned: ** ** PC 00 Lua frame ** delta 001 C frame ** delta 010 Continuation frame ** delta 011 Lua vararg frame ** delta 101 cpcall() frame ** delta 110 ff pcall() frame ** delta 111 ff pcall() frame with active hook */ enum { FRAME_LUA, FRAME_C, FRAME_CONT, FRAME_VARG, FRAME_LUAP, FRAME_CP, FRAME_PCALL, FRAME_PCALLH }; #define FRAME_TYPE 3 #define FRAME_P 4 #define FRAME_TYPEP (FRAME_TYPE|FRAME_P) /* Macros to access and modify Lua frames. */ #if LJ_FR2 /* Two-slot frame info, required for 64 bit PC/GCRef: ** ** base-2 base-1 | base base+1 ... ** [func PC/delta/ft] | [slots ...] ** ^-- frame | ^-- base ^-- top ** ** Continuation frames: ** ** base-4 base-3 base-2 base-1 | base base+1 ... ** [cont PC ] [func PC/delta/ft] | [slots ...] ** ^-- frame | ^-- base ^-- top */ #define frame_gc(f) (gcval((f)-1)) #define frame_ftsz(f) ((ptrdiff_t)(f)->ftsz) #define frame_pc(f) ((const BCIns *)frame_ftsz(f)) #define setframe_gc(f, p, tp) (setgcVraw((f)-1, (p), (tp))) #define setframe_ftsz(f, sz) ((f)->ftsz = (sz)) #define setframe_pc(f, pc) ((f)->ftsz = (int64_t)(intptr_t)(pc)) #else /* One-slot frame info, sufficient for 32 bit PC/GCRef: ** ** base-1 | base base+1 ... ** lo hi | ** [func | PC/delta/ft] | [slots ...] ** ^-- frame | ^-- base ^-- top ** ** Continuation frames: ** ** base-2 base-1 | base base+1 ... ** lo hi lo hi | ** [cont | PC] [func | PC/delta/ft] | [slots ...] ** ^-- frame | ^-- base ^-- top */ #define frame_gc(f) (gcref((f)->fr.func)) #define frame_ftsz(f) ((ptrdiff_t)(f)->fr.tp.ftsz) #define frame_pc(f) (mref((f)->fr.tp.pcr, const BCIns)) #define setframe_gc(f, p, tp) (setgcref((f)->fr.func, (p)), UNUSED(tp)) #define setframe_ftsz(f, sz) ((f)->fr.tp.ftsz = (int32_t)(sz)) #define setframe_pc(f, pc) (setmref((f)->fr.tp.pcr, (pc))) #endif #define frame_type(f) (frame_ftsz(f) & FRAME_TYPE) #define frame_typep(f) (frame_ftsz(f) & FRAME_TYPEP) #define frame_islua(f) (frame_type(f) == FRAME_LUA) #define frame_isc(f) (frame_type(f) == FRAME_C) #define frame_iscont(f) (frame_typep(f) == FRAME_CONT) #define frame_isvarg(f) (frame_typep(f) == FRAME_VARG) #define frame_ispcall(f) ((frame_ftsz(f) & 6) == FRAME_PCALL) #define frame_func(f) (&frame_gc(f)->fn) #define frame_delta(f) (frame_ftsz(f) >> 3) #define frame_sized(f) (frame_ftsz(f) & ~FRAME_TYPEP) enum { LJ_CONT_TAILCALL, LJ_CONT_FFI_CALLBACK }; /* Special continuations. */ #if LJ_FR2 #define frame_contpc(f) (frame_pc((f)-2)) #define frame_contv(f) (((f)-3)->u64) #else #define frame_contpc(f) (frame_pc((f)-1)) #define frame_contv(f) (((f)-1)->u32.lo) #endif #if LJ_FR2 #define frame_contf(f) ((ASMFunction)(uintptr_t)((f)-3)->u64) #elif LJ_64 #define frame_contf(f) \ ((ASMFunction)(void *)((intptr_t)lj_vm_asm_begin + \ (intptr_t)(int32_t)((f)-1)->u32.lo)) #else #define frame_contf(f) ((ASMFunction)gcrefp(((f)-1)->gcr, void)) #endif #define frame_iscont_fficb(f) \ (LJ_HASFFI && frame_contv(f) == LJ_CONT_FFI_CALLBACK) #define frame_prevl(f) ((f) - (1+LJ_FR2+bc_a(frame_pc(f)[-1]))) #define frame_prevd(f) ((TValue *)((char *)(f) - frame_sized(f))) #define frame_prev(f) (frame_islua(f)?frame_prevl(f):frame_prevd(f)) /* Note: this macro does not skip over FRAME_VARG. */ /* -- C stack frame ------------------------------------------------------- */ /* Macros to access and modify the C stack frame chain. */ /* These definitions must match with the arch-specific *.dasc files. */ #if LJ_TARGET_X86 #define CFRAME_OFS_ERRF (15*4) #define CFRAME_OFS_NRES (14*4) #define CFRAME_OFS_PREV (13*4) #define CFRAME_OFS_L (12*4) #define CFRAME_OFS_PC (6*4) #define CFRAME_OFS_MULTRES (5*4) #define CFRAME_SIZE (12*4) #define CFRAME_SHIFT_MULTRES 0 #elif LJ_TARGET_X64 #if LJ_ABI_WIN #define CFRAME_OFS_PREV (13*8) #if LJ_GC64 #define CFRAME_OFS_PC (12*8) #define CFRAME_OFS_L (11*8) #define CFRAME_OFS_ERRF (21*4) #define CFRAME_OFS_NRES (20*4) #define CFRAME_OFS_MULTRES (8*4) #else #define CFRAME_OFS_PC (25*4) #define CFRAME_OFS_L (24*4) #define CFRAME_OFS_ERRF (23*4) #define CFRAME_OFS_NRES (22*4) #define CFRAME_OFS_MULTRES (21*4) #endif #define CFRAME_SIZE (10*8) #define CFRAME_SIZE_JIT (CFRAME_SIZE + 9*16 + 4*8) #define CFRAME_SHIFT_MULTRES 0 #else #define CFRAME_OFS_PREV (4*8) #if LJ_GC64 #define CFRAME_OFS_PC (3*8) #define CFRAME_OFS_L (2*8) #define CFRAME_OFS_ERRF (3*4) #define CFRAME_OFS_NRES (2*4) #define CFRAME_OFS_MULTRES (0*4) #else #define CFRAME_OFS_PC (7*4) #define CFRAME_OFS_L (6*4) #define CFRAME_OFS_ERRF (5*4) #define CFRAME_OFS_NRES (4*4) #define CFRAME_OFS_MULTRES (1*4) #endif #if LJ_NO_UNWIND #define CFRAME_SIZE (12*8) #else #define CFRAME_SIZE (10*8) #endif #define CFRAME_SIZE_JIT (CFRAME_SIZE + 16) #define CFRAME_SHIFT_MULTRES 0 #endif #elif LJ_TARGET_ARM #define CFRAME_OFS_ERRF 24 #define CFRAME_OFS_NRES 20 #define CFRAME_OFS_PREV 16 #define CFRAME_OFS_L 12 #define CFRAME_OFS_PC 8 #define CFRAME_OFS_MULTRES 4 #if LJ_ARCH_HASFPU #define CFRAME_SIZE 128 #else #define CFRAME_SIZE 64 #endif #define CFRAME_SHIFT_MULTRES 3 #elif LJ_TARGET_ARM64 #define CFRAME_OFS_ERRF 196 #define CFRAME_OFS_NRES 200 #define CFRAME_OFS_PREV 160 #define CFRAME_OFS_L 176 #define CFRAME_OFS_PC 168 #define CFRAME_OFS_MULTRES 192 #define CFRAME_SIZE 208 #define CFRAME_SHIFT_MULTRES 3 #elif LJ_TARGET_PPC #if LJ_TARGET_XBOX360 #define CFRAME_OFS_ERRF 424 #define CFRAME_OFS_NRES 420 #define CFRAME_OFS_PREV 400 #define CFRAME_OFS_L 416 #define CFRAME_OFS_PC 412 #define CFRAME_OFS_MULTRES 408 #define CFRAME_SIZE 384 #define CFRAME_SHIFT_MULTRES 3 #elif LJ_ARCH_PPC32ON64 #define CFRAME_OFS_ERRF 472 #define CFRAME_OFS_NRES 468 #define CFRAME_OFS_PREV 448 #define CFRAME_OFS_L 464 #define CFRAME_OFS_PC 460 #define CFRAME_OFS_MULTRES 456 #define CFRAME_SIZE 400 #define CFRAME_SHIFT_MULTRES 3 #else #define CFRAME_OFS_ERRF 48 #define CFRAME_OFS_NRES 44 #define CFRAME_OFS_PREV 40 #define CFRAME_OFS_L 36 #define CFRAME_OFS_PC 32 #define CFRAME_OFS_MULTRES 28 #define CFRAME_SIZE 272 #define CFRAME_SHIFT_MULTRES 3 #endif #elif LJ_TARGET_MIPS #if LJ_ARCH_HASFPU #define CFRAME_OFS_ERRF 124 #define CFRAME_OFS_NRES 120 #define CFRAME_OFS_PREV 116 #define CFRAME_OFS_L 112 #define CFRAME_OFS_PC 20 #define CFRAME_OFS_MULTRES 16 #define CFRAME_SIZE 112 #define CFRAME_SHIFT_MULTRES 3 #else #define CFRAME_OFS_ERRF 76 #define CFRAME_OFS_NRES 72 #define CFRAME_OFS_PREV 68 #define CFRAME_OFS_L 64 #define CFRAME_OFS_PC 20 #define CFRAME_OFS_MULTRES 16 #define CFRAME_SIZE 64 #define CFRAME_SHIFT_MULTRES 3 #endif #else #error "Missing CFRAME_* definitions for this architecture" #endif #ifndef CFRAME_SIZE_JIT #define CFRAME_SIZE_JIT CFRAME_SIZE #endif #define CFRAME_RESUME 1 #define CFRAME_UNWIND_FF 2 /* Only used in unwinder. */ #define CFRAME_RAWMASK (~(intptr_t)(CFRAME_RESUME|CFRAME_UNWIND_FF)) #define cframe_errfunc(cf) (*(int32_t *)(((char *)(cf))+CFRAME_OFS_ERRF)) #define cframe_nres(cf) (*(int32_t *)(((char *)(cf))+CFRAME_OFS_NRES)) #define cframe_prev(cf) (*(void **)(((char *)(cf))+CFRAME_OFS_PREV)) #define cframe_multres(cf) (*(uint32_t *)(((char *)(cf))+CFRAME_OFS_MULTRES)) #define cframe_multres_n(cf) (cframe_multres((cf)) >> CFRAME_SHIFT_MULTRES) #define cframe_L(cf) \ (&gcref(*(GCRef *)(((char *)(cf))+CFRAME_OFS_L))->th) #define cframe_pc(cf) \ (mref(*(MRef *)(((char *)(cf))+CFRAME_OFS_PC), const BCIns)) #define setcframe_L(cf, L) \ (setmref(*(MRef *)(((char *)(cf))+CFRAME_OFS_L), (L))) #define setcframe_pc(cf, pc) \ (setmref(*(MRef *)(((char *)(cf))+CFRAME_OFS_PC), (pc))) #define cframe_canyield(cf) ((intptr_t)(cf) & CFRAME_RESUME) #define cframe_unwind_ff(cf) ((intptr_t)(cf) & CFRAME_UNWIND_FF) #define cframe_raw(cf) ((void *)((intptr_t)(cf) & CFRAME_RAWMASK)) #define cframe_Lpc(L) cframe_pc(cframe_raw(L->cframe)) #endif
xLua/build/luajit-2.1.0b2/src/lj_frame.h/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lj_frame.h", "repo_id": "xLua", "token_count": 4169 }
2,106
/* ** Load and dump code. ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ #include <errno.h> #include <stdio.h> #define lj_load_c #define LUA_CORE #include "lua.h" #include "lauxlib.h" #include "lj_obj.h" #include "lj_gc.h" #include "lj_err.h" #include "lj_buf.h" #include "lj_func.h" #include "lj_frame.h" #include "lj_vm.h" #include "lj_lex.h" #include "lj_bcdump.h" #include "lj_parse.h" /* -- Load Lua source code and bytecode ----------------------------------- */ static TValue *cpparser(lua_State *L, lua_CFunction dummy, void *ud) { LexState *ls = (LexState *)ud; GCproto *pt; GCfunc *fn; int bc; UNUSED(dummy); cframe_errfunc(L->cframe) = -1; /* Inherit error function. */ bc = lj_lex_setup(L, ls); if (ls->mode && !strchr(ls->mode, bc ? 'b' : 't')) { setstrV(L, L->top++, lj_err_str(L, LJ_ERR_XMODE)); lj_err_throw(L, LUA_ERRSYNTAX); } pt = bc ? lj_bcread(ls) : lj_parse(ls); fn = lj_func_newL_empty(L, pt, tabref(L->env)); /* Don't combine above/below into one statement. */ setfuncV(L, L->top++, fn); return NULL; } LUA_API int lua_loadx(lua_State *L, lua_Reader reader, void *data, const char *chunkname, const char *mode) { LexState ls; int status; ls.rfunc = reader; ls.rdata = data; ls.chunkarg = chunkname ? chunkname : "?"; ls.mode = mode; lj_buf_init(L, &ls.sb); status = lj_vm_cpcall(L, NULL, &ls, cpparser); lj_lex_cleanup(L, &ls); lj_gc_check(L); return status; } LUA_API int lua_load(lua_State *L, lua_Reader reader, void *data, const char *chunkname) { return lua_loadx(L, reader, data, chunkname, NULL); } typedef struct FileReaderCtx { FILE *fp; char buf[LUAL_BUFFERSIZE]; } FileReaderCtx; static const char *reader_file(lua_State *L, void *ud, size_t *size) { FileReaderCtx *ctx = (FileReaderCtx *)ud; UNUSED(L); if (feof(ctx->fp)) return NULL; *size = fread(ctx->buf, 1, sizeof(ctx->buf), ctx->fp); return *size > 0 ? ctx->buf : NULL; } LUALIB_API int luaL_loadfilex(lua_State *L, const char *filename, const char *mode) { FileReaderCtx ctx; int status; const char *chunkname; if (filename) { ctx.fp = fopen(filename, "rb"); if (ctx.fp == NULL) { lua_pushfstring(L, "cannot open %s: %s", filename, strerror(errno)); return LUA_ERRFILE; } chunkname = lua_pushfstring(L, "@%s", filename); } else { ctx.fp = stdin; chunkname = "=stdin"; } status = lua_loadx(L, reader_file, &ctx, chunkname, mode); if (ferror(ctx.fp)) { L->top -= filename ? 2 : 1; lua_pushfstring(L, "cannot read %s: %s", chunkname+1, strerror(errno)); if (filename) fclose(ctx.fp); return LUA_ERRFILE; } if (filename) { L->top--; copyTV(L, L->top-1, L->top); fclose(ctx.fp); } return status; } LUALIB_API int luaL_loadfile(lua_State *L, const char *filename) { return luaL_loadfilex(L, filename, NULL); } typedef struct StringReaderCtx { const char *str; size_t size; } StringReaderCtx; static const char *reader_string(lua_State *L, void *ud, size_t *size) { StringReaderCtx *ctx = (StringReaderCtx *)ud; UNUSED(L); if (ctx->size == 0) return NULL; *size = ctx->size; ctx->size = 0; return ctx->str; } LUALIB_API int luaL_loadbufferx(lua_State *L, const char *buf, size_t size, const char *name, const char *mode) { StringReaderCtx ctx; ctx.str = buf; ctx.size = size; return lua_loadx(L, reader_string, &ctx, name, mode); } LUALIB_API int luaL_loadbuffer(lua_State *L, const char *buf, size_t size, const char *name) { return luaL_loadbufferx(L, buf, size, name, NULL); } LUALIB_API int luaL_loadstring(lua_State *L, const char *s) { return luaL_loadbuffer(L, s, strlen(s), s); } /* -- Dump bytecode ------------------------------------------------------- */ LUA_API int lua_dump(lua_State *L, lua_Writer writer, void *data) { cTValue *o = L->top-1; api_check(L, L->top > L->base); if (tvisfunc(o) && isluafunc(funcV(o))) return lj_bcwrite(L, funcproto(funcV(o)), writer, data, 0); else return 1; }
xLua/build/luajit-2.1.0b2/src/lj_load.c/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lj_load.c", "repo_id": "xLua", "token_count": 1802 }
2,107
/* ** Low-overhead profiling. ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ #define lj_profile_c #define LUA_CORE #include "lj_obj.h" #if LJ_HASPROFILE #include "lj_buf.h" #include "lj_frame.h" #include "lj_debug.h" #include "lj_dispatch.h" #if LJ_HASJIT #include "lj_jit.h" #include "lj_trace.h" #endif #include "lj_profile.h" #include "luajit.h" #if LJ_PROFILE_SIGPROF #include <sys/time.h> #include <signal.h> #define profile_lock(ps) UNUSED(ps) #define profile_unlock(ps) UNUSED(ps) #elif LJ_PROFILE_PTHREAD #include <pthread.h> #include <time.h> #if LJ_TARGET_PS3 #include <sys/timer.h> #endif #define profile_lock(ps) pthread_mutex_lock(&ps->lock) #define profile_unlock(ps) pthread_mutex_unlock(&ps->lock) #elif LJ_PROFILE_WTHREAD #define WIN32_LEAN_AND_MEAN #if LJ_TARGET_XBOX360 #include <xtl.h> #include <xbox.h> #else #include <windows.h> #endif typedef unsigned int (WINAPI *WMM_TPFUNC)(unsigned int); #define profile_lock(ps) EnterCriticalSection(&ps->lock) #define profile_unlock(ps) LeaveCriticalSection(&ps->lock) #endif /* Profiler state. */ typedef struct ProfileState { global_State *g; /* VM state that started the profiler. */ luaJIT_profile_callback cb; /* Profiler callback. */ void *data; /* Profiler callback data. */ SBuf sb; /* String buffer for stack dumps. */ int interval; /* Sample interval in milliseconds. */ int samples; /* Number of samples for next callback. */ int vmstate; /* VM state when profile timer triggered. */ #if LJ_PROFILE_SIGPROF struct sigaction oldsa; /* Previous SIGPROF state. */ #elif LJ_PROFILE_PTHREAD pthread_mutex_t lock; /* g->hookmask update lock. */ pthread_t thread; /* Timer thread. */ int abort; /* Abort timer thread. */ #elif LJ_PROFILE_WTHREAD #if LJ_TARGET_WINDOWS HINSTANCE wmm; /* WinMM library handle. */ WMM_TPFUNC wmm_tbp; /* WinMM timeBeginPeriod function. */ WMM_TPFUNC wmm_tep; /* WinMM timeEndPeriod function. */ #endif CRITICAL_SECTION lock; /* g->hookmask update lock. */ HANDLE thread; /* Timer thread. */ int abort; /* Abort timer thread. */ #endif } ProfileState; /* Sadly, we have to use a static profiler state. ** ** The SIGPROF variant needs a static pointer to the global state, anyway. ** And it would be hard to extend for multiple threads. You can still use ** multiple VMs in multiple threads, but only profile one at a time. */ static ProfileState profile_state; /* Default sample interval in milliseconds. */ #define LJ_PROFILE_INTERVAL_DEFAULT 10 /* -- Profiler/hook interaction ------------------------------------------- */ #if !LJ_PROFILE_SIGPROF void LJ_FASTCALL lj_profile_hook_enter(global_State *g) { ProfileState *ps = &profile_state; if (ps->g) { profile_lock(ps); hook_enter(g); profile_unlock(ps); } else { hook_enter(g); } } void LJ_FASTCALL lj_profile_hook_leave(global_State *g) { ProfileState *ps = &profile_state; if (ps->g) { profile_lock(ps); hook_leave(g); profile_unlock(ps); } else { hook_leave(g); } } #endif /* -- Profile callbacks --------------------------------------------------- */ /* Callback from profile hook (HOOK_PROFILE already cleared). */ void LJ_FASTCALL lj_profile_interpreter(lua_State *L) { ProfileState *ps = &profile_state; global_State *g = G(L); uint8_t mask; profile_lock(ps); mask = (g->hookmask & ~HOOK_PROFILE); if (!(mask & HOOK_VMEVENT)) { int samples = ps->samples; ps->samples = 0; g->hookmask = HOOK_VMEVENT; lj_dispatch_update(g); profile_unlock(ps); ps->cb(ps->data, L, samples, ps->vmstate); /* Invoke user callback. */ profile_lock(ps); mask |= (g->hookmask & HOOK_PROFILE); } g->hookmask = mask; lj_dispatch_update(g); profile_unlock(ps); } /* Trigger profile hook. Asynchronous call from OS-specific profile timer. */ static void profile_trigger(ProfileState *ps) { global_State *g = ps->g; uint8_t mask; profile_lock(ps); ps->samples++; /* Always increment number of samples. */ mask = g->hookmask; if (!(mask & (HOOK_PROFILE|HOOK_VMEVENT))) { /* Set profile hook. */ int st = g->vmstate; ps->vmstate = st >= 0 ? 'N' : st == ~LJ_VMST_INTERP ? 'I' : st == ~LJ_VMST_C ? 'C' : st == ~LJ_VMST_GC ? 'G' : 'J'; g->hookmask = (mask | HOOK_PROFILE); lj_dispatch_update(g); } profile_unlock(ps); } /* -- OS-specific profile timer handling ---------------------------------- */ #if LJ_PROFILE_SIGPROF /* SIGPROF handler. */ static void profile_signal(int sig) { UNUSED(sig); profile_trigger(&profile_state); } /* Start profiling timer. */ static void profile_timer_start(ProfileState *ps) { int interval = ps->interval; struct itimerval tm; struct sigaction sa; tm.it_value.tv_sec = tm.it_interval.tv_sec = interval / 1000; tm.it_value.tv_usec = tm.it_interval.tv_usec = (interval % 1000) * 1000; setitimer(ITIMER_PROF, &tm, NULL); sa.sa_flags = SA_RESTART; sa.sa_handler = profile_signal; sigemptyset(&sa.sa_mask); sigaction(SIGPROF, &sa, &ps->oldsa); } /* Stop profiling timer. */ static void profile_timer_stop(ProfileState *ps) { struct itimerval tm; tm.it_value.tv_sec = tm.it_interval.tv_sec = 0; tm.it_value.tv_usec = tm.it_interval.tv_usec = 0; setitimer(ITIMER_PROF, &tm, NULL); sigaction(SIGPROF, &ps->oldsa, NULL); } #elif LJ_PROFILE_PTHREAD /* POSIX timer thread. */ static void *profile_thread(ProfileState *ps) { int interval = ps->interval; #if !LJ_TARGET_PS3 struct timespec ts; ts.tv_sec = interval / 1000; ts.tv_nsec = (interval % 1000) * 1000000; #endif while (1) { #if LJ_TARGET_PS3 sys_timer_usleep(interval * 1000); #else nanosleep(&ts, NULL); #endif if (ps->abort) break; profile_trigger(ps); } return NULL; } /* Start profiling timer thread. */ static void profile_timer_start(ProfileState *ps) { pthread_mutex_init(&ps->lock, 0); ps->abort = 0; pthread_create(&ps->thread, NULL, (void *(*)(void *))profile_thread, ps); } /* Stop profiling timer thread. */ static void profile_timer_stop(ProfileState *ps) { ps->abort = 1; pthread_join(ps->thread, NULL); pthread_mutex_destroy(&ps->lock); } #elif LJ_PROFILE_WTHREAD /* Windows timer thread. */ static DWORD WINAPI profile_thread(void *psx) { ProfileState *ps = (ProfileState *)psx; int interval = ps->interval; #if LJ_TARGET_WINDOWS ps->wmm_tbp(interval); #endif while (1) { Sleep(interval); if (ps->abort) break; profile_trigger(ps); } #if LJ_TARGET_WINDOWS ps->wmm_tep(interval); #endif return 0; } /* Start profiling timer thread. */ static void profile_timer_start(ProfileState *ps) { #if LJ_TARGET_WINDOWS if (!ps->wmm) { /* Load WinMM library on-demand. */ ps->wmm = LoadLibraryExA("winmm.dll", NULL, 0); if (ps->wmm) { ps->wmm_tbp = (WMM_TPFUNC)GetProcAddress(ps->wmm, "timeBeginPeriod"); ps->wmm_tep = (WMM_TPFUNC)GetProcAddress(ps->wmm, "timeEndPeriod"); if (!ps->wmm_tbp || !ps->wmm_tep) { ps->wmm = NULL; return; } } } #endif InitializeCriticalSection(&ps->lock); ps->abort = 0; ps->thread = CreateThread(NULL, 0, profile_thread, ps, 0, NULL); } /* Stop profiling timer thread. */ static void profile_timer_stop(ProfileState *ps) { ps->abort = 1; WaitForSingleObject(ps->thread, INFINITE); DeleteCriticalSection(&ps->lock); } #endif /* -- Public profiling API ------------------------------------------------ */ /* Start profiling. */ LUA_API void luaJIT_profile_start(lua_State *L, const char *mode, luaJIT_profile_callback cb, void *data) { ProfileState *ps = &profile_state; int interval = LJ_PROFILE_INTERVAL_DEFAULT; while (*mode) { int m = *mode++; switch (m) { case 'i': interval = 0; while (*mode >= '0' && *mode <= '9') interval = interval * 10 + (*mode++ - '0'); if (interval <= 0) interval = 1; break; #if LJ_HASJIT case 'l': case 'f': L2J(L)->prof_mode = m; lj_trace_flushall(L); break; #endif default: /* Ignore unknown mode chars. */ break; } } if (ps->g) { luaJIT_profile_stop(L); if (ps->g) return; /* Profiler in use by another VM. */ } ps->g = G(L); ps->interval = interval; ps->cb = cb; ps->data = data; ps->samples = 0; lj_buf_init(L, &ps->sb); profile_timer_start(ps); } /* Stop profiling. */ LUA_API void luaJIT_profile_stop(lua_State *L) { ProfileState *ps = &profile_state; global_State *g = ps->g; if (G(L) == g) { /* Only stop profiler if started by this VM. */ profile_timer_stop(ps); g->hookmask &= ~HOOK_PROFILE; lj_dispatch_update(g); #if LJ_HASJIT G2J(g)->prof_mode = 0; lj_trace_flushall(L); #endif lj_buf_free(g, &ps->sb); setmref(ps->sb.b, NULL); setmref(ps->sb.e, NULL); ps->g = NULL; } } /* Return a compact stack dump. */ LUA_API const char *luaJIT_profile_dumpstack(lua_State *L, const char *fmt, int depth, size_t *len) { ProfileState *ps = &profile_state; SBuf *sb = &ps->sb; setsbufL(sb, L); lj_buf_reset(sb); lj_debug_dumpstack(L, sb, fmt, depth); *len = (size_t)sbuflen(sb); return sbufB(sb); } #endif
xLua/build/luajit-2.1.0b2/src/lj_profile.c/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lj_profile.c", "repo_id": "xLua", "token_count": 3764 }
2,108
/* ** Table handling. ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ #ifndef _LJ_TAB_H #define _LJ_TAB_H #include "lj_obj.h" /* Hash constants. Tuned using a brute force search. */ #define HASH_BIAS (-0x04c11db7) #define HASH_ROT1 14 #define HASH_ROT2 5 #define HASH_ROT3 13 /* Scramble the bits of numbers and pointers. */ static LJ_AINLINE uint32_t hashrot(uint32_t lo, uint32_t hi) { #if LJ_TARGET_X86ORX64 /* Prefer variant that compiles well for a 2-operand CPU. */ lo ^= hi; hi = lj_rol(hi, HASH_ROT1); lo -= hi; hi = lj_rol(hi, HASH_ROT2); hi ^= lo; hi -= lj_rol(lo, HASH_ROT3); #else lo ^= hi; lo = lo - lj_rol(hi, HASH_ROT1); hi = lo ^ lj_rol(hi, HASH_ROT1 + HASH_ROT2); hi = hi - lj_rol(lo, HASH_ROT3); #endif return hi; } #define hsize2hbits(s) ((s) ? ((s)==1 ? 1 : 1+lj_fls((uint32_t)((s)-1))) : 0) LJ_FUNCA GCtab *lj_tab_new(lua_State *L, uint32_t asize, uint32_t hbits); LJ_FUNC GCtab *lj_tab_new_ah(lua_State *L, int32_t a, int32_t h); #if LJ_HASJIT LJ_FUNC GCtab * LJ_FASTCALL lj_tab_new1(lua_State *L, uint32_t ahsize); #endif LJ_FUNCA GCtab * LJ_FASTCALL lj_tab_dup(lua_State *L, const GCtab *kt); LJ_FUNC void LJ_FASTCALL lj_tab_clear(GCtab *t); LJ_FUNC void LJ_FASTCALL lj_tab_free(global_State *g, GCtab *t); #if LJ_HASFFI LJ_FUNC void lj_tab_rehash(lua_State *L, GCtab *t); #endif LJ_FUNC void lj_tab_resize(lua_State *L, GCtab *t, uint32_t asize, uint32_t hbits); LJ_FUNCA void lj_tab_reasize(lua_State *L, GCtab *t, uint32_t nasize); /* Caveat: all getters except lj_tab_get() can return NULL! */ LJ_FUNCA cTValue * LJ_FASTCALL lj_tab_getinth(GCtab *t, int32_t key); LJ_FUNC cTValue *lj_tab_getstr(GCtab *t, GCstr *key); LJ_FUNCA cTValue *lj_tab_get(lua_State *L, GCtab *t, cTValue *key); /* Caveat: all setters require a write barrier for the stored value. */ LJ_FUNCA TValue *lj_tab_newkey(lua_State *L, GCtab *t, cTValue *key); LJ_FUNCA TValue *lj_tab_setinth(lua_State *L, GCtab *t, int32_t key); LJ_FUNC TValue *lj_tab_setstr(lua_State *L, GCtab *t, GCstr *key); LJ_FUNC TValue *lj_tab_set(lua_State *L, GCtab *t, cTValue *key); #define inarray(t, key) ((MSize)(key) < (MSize)(t)->asize) #define arrayslot(t, i) (&tvref((t)->array)[(i)]) #define lj_tab_getint(t, key) \ (inarray((t), (key)) ? arrayslot((t), (key)) : lj_tab_getinth((t), (key))) #define lj_tab_setint(L, t, key) \ (inarray((t), (key)) ? arrayslot((t), (key)) : lj_tab_setinth(L, (t), (key))) LJ_FUNCA int lj_tab_next(lua_State *L, GCtab *t, TValue *key); LJ_FUNCA MSize LJ_FASTCALL lj_tab_len(GCtab *t); #endif
xLua/build/luajit-2.1.0b2/src/lj_tab.h/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lj_tab.h", "repo_id": "xLua", "token_count": 1248 }
2,109
/* ** LuaJIT core and libraries amalgamation. ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ /* +--------------------------------------------------------------------------+ | WARNING: Compiling the amalgamation needs a lot of virtual memory | | (around 300 MB with GCC 4.x)! If you don't have enough physical memory | | your machine will start swapping to disk and the compile will not finish | | within a reasonable amount of time. | | So either compile on a bigger machine or use the non-amalgamated build. | +--------------------------------------------------------------------------+ */ #define ljamalg_c #define LUA_CORE /* To get the mremap prototype. Must be defined before any system includes. */ #if defined(__linux__) && !defined(_GNU_SOURCE) #define _GNU_SOURCE #endif #ifndef WINVER #define WINVER 0x0501 #endif #include "lua.h" #include "lauxlib.h" #include "lj_gc.c" #include "lj_err.c" #include "lj_char.c" #include "lj_bc.c" #include "lj_obj.c" #include "lj_buf.c" #include "lj_str.c" #include "lj_tab.c" #include "lj_func.c" #include "lj_udata.c" #include "lj_meta.c" #include "lj_debug.c" #include "lj_state.c" #include "lj_dispatch.c" #include "lj_vmevent.c" #include "lj_vmmath.c" #include "lj_strscan.c" #include "lj_strfmt.c" #include "lj_strfmt_num.c" #include "lj_api.c" #include "lj_profile.c" #include "lj_lex.c" #include "lj_parse.c" #include "lj_bcread.c" #include "lj_bcwrite.c" #include "lj_load.c" #include "lj_ctype.c" #include "lj_cdata.c" #include "lj_cconv.c" #include "lj_ccall.c" #include "lj_ccallback.c" #include "lj_carith.c" #include "lj_clib.c" #include "lj_cparse.c" #include "lj_lib.c" #include "lj_ir.c" #include "lj_opt_mem.c" #include "lj_opt_fold.c" #include "lj_opt_narrow.c" #include "lj_opt_dce.c" #include "lj_opt_loop.c" #include "lj_opt_split.c" #include "lj_opt_sink.c" #include "lj_mcode.c" #include "lj_snap.c" #include "lj_record.c" #include "lj_crecord.c" #include "lj_ffrecord.c" #include "lj_asm.c" #include "lj_trace.c" #include "lj_gdbjit.c" #include "lj_alloc.c" #include "lib_aux.c" #include "lib_base.c" #include "lib_math.c" #include "lib_string.c" #include "lib_table.c" #include "lib_io.c" #include "lib_os.c" #include "lib_package.c" #include "lib_debug.c" #include "lib_bit.c" #include "lib_jit.c" #include "lib_ffi.c" #include "lib_init.c"
xLua/build/luajit-2.1.0b2/src/ljamalg.c/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/ljamalg.c", "repo_id": "xLua", "token_count": 1041 }
2,110
|// Low-level VM code for x64 CPUs in LJ_GC64 mode. |// Bytecode interpreter, fast functions and helper functions. |// Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h | |.arch x64 |.section code_op, code_sub | |.actionlist build_actionlist |.globals GLOB_ |.globalnames globnames |.externnames extnames | |//----------------------------------------------------------------------- | |.if WIN |.define X64WIN, 1 // Windows/x64 calling conventions. |.endif | |// Fixed register assignments for the interpreter. |// This is very fragile and has many dependencies. Caveat emptor. |.define BASE, rdx // Not C callee-save, refetched anyway. |.if X64WIN |.define KBASE, rdi // Must be C callee-save. |.define PC, rsi // Must be C callee-save. |.define DISPATCH, rbx // Must be C callee-save. |.define KBASEd, edi |.define PCd, esi |.define DISPATCHd, ebx |.else |.define KBASE, r15 // Must be C callee-save. |.define PC, rbx // Must be C callee-save. |.define DISPATCH, r14 // Must be C callee-save. |.define KBASEd, r15d |.define PCd, ebx |.define DISPATCHd, r14d |.endif | |.define RA, rcx |.define RAd, ecx |.define RAH, ch |.define RAL, cl |.define RB, rbp // Must be rbp (C callee-save). |.define RBd, ebp |.define RC, rax // Must be rax. |.define RCd, eax |.define RCW, ax |.define RCH, ah |.define RCL, al |.define OP, RBd |.define RD, RC |.define RDd, RCd |.define RDW, RCW |.define RDL, RCL |.define TMPR, r10 |.define TMPRd, r10d |.define ITYPE, r11 |.define ITYPEd, r11d | |.if X64WIN |.define CARG1, rcx // x64/WIN64 C call arguments. |.define CARG2, rdx |.define CARG3, r8 |.define CARG4, r9 |.define CARG1d, ecx |.define CARG2d, edx |.define CARG3d, r8d |.define CARG4d, r9d |.else |.define CARG1, rdi // x64/POSIX C call arguments. |.define CARG2, rsi |.define CARG3, rdx |.define CARG4, rcx |.define CARG5, r8 |.define CARG6, r9 |.define CARG1d, edi |.define CARG2d, esi |.define CARG3d, edx |.define CARG4d, ecx |.define CARG5d, r8d |.define CARG6d, r9d |.endif | |// Type definitions. Some of these are only used for documentation. |.type L, lua_State |.type GL, global_State |.type TVALUE, TValue |.type GCOBJ, GCobj |.type STR, GCstr |.type TAB, GCtab |.type LFUNC, GCfuncL |.type CFUNC, GCfuncC |.type PROTO, GCproto |.type UPVAL, GCupval |.type NODE, Node |.type NARGS, int |.type TRACE, GCtrace |.type SBUF, SBuf | |// Stack layout while in interpreter. Must match with lj_frame.h. |//----------------------------------------------------------------------- |.if X64WIN // x64/Windows stack layout | |.define CFRAME_SPACE, aword*5 // Delta for rsp (see <--). |.macro saveregs_ | push rdi; push rsi; push rbx | sub rsp, CFRAME_SPACE |.endmacro |.macro saveregs | push rbp; saveregs_ |.endmacro |.macro restoreregs | add rsp, CFRAME_SPACE | pop rbx; pop rsi; pop rdi; pop rbp |.endmacro | |.define SAVE_CFRAME, aword [rsp+aword*13] |.define SAVE_PC, aword [rsp+aword*12] |.define SAVE_L, aword [rsp+aword*11] |.define SAVE_ERRF, dword [rsp+dword*21] |.define SAVE_NRES, dword [rsp+dword*20] |//----- 16 byte aligned, ^^^ 32 byte register save area, owned by interpreter |.define SAVE_RET, aword [rsp+aword*9] //<-- rsp entering interpreter. |.define SAVE_R4, aword [rsp+aword*8] |.define SAVE_R3, aword [rsp+aword*7] |.define SAVE_R2, aword [rsp+aword*6] |.define SAVE_R1, aword [rsp+aword*5] //<-- rsp after register saves. |.define ARG5, aword [rsp+aword*4] |.define CSAVE_4, aword [rsp+aword*3] |.define CSAVE_3, aword [rsp+aword*2] |.define CSAVE_2, aword [rsp+aword*1] |.define CSAVE_1, aword [rsp] //<-- rsp while in interpreter. |//----- 16 byte aligned, ^^^ 32 byte register save area, owned by callee | |.define ARG5d, dword [rsp+dword*8] |.define TMP1, ARG5 // TMP1 overlaps ARG5 |.define TMP1d, ARG5d |.define TMP1hi, dword [rsp+dword*9] |.define MULTRES, TMP1d // MULTRES overlaps TMP1d. | |//----------------------------------------------------------------------- |.else // x64/POSIX stack layout | |.define CFRAME_SPACE, aword*5 // Delta for rsp (see <--). |.macro saveregs_ | push rbx; push r15; push r14 |.if NO_UNWIND | push r13; push r12 |.endif | sub rsp, CFRAME_SPACE |.endmacro |.macro saveregs | push rbp; saveregs_ |.endmacro |.macro restoreregs | add rsp, CFRAME_SPACE |.if NO_UNWIND | pop r12; pop r13 |.endif | pop r14; pop r15; pop rbx; pop rbp |.endmacro | |//----- 16 byte aligned, |.if NO_UNWIND |.define SAVE_RET, aword [rsp+aword*11] //<-- rsp entering interpreter. |.define SAVE_R4, aword [rsp+aword*10] |.define SAVE_R3, aword [rsp+aword*9] |.define SAVE_R2, aword [rsp+aword*8] |.define SAVE_R1, aword [rsp+aword*7] |.define SAVE_RU2, aword [rsp+aword*6] |.define SAVE_RU1, aword [rsp+aword*5] //<-- rsp after register saves. |.else |.define SAVE_RET, aword [rsp+aword*9] //<-- rsp entering interpreter. |.define SAVE_R4, aword [rsp+aword*8] |.define SAVE_R3, aword [rsp+aword*7] |.define SAVE_R2, aword [rsp+aword*6] |.define SAVE_R1, aword [rsp+aword*5] //<-- rsp after register saves. |.endif |.define SAVE_CFRAME, aword [rsp+aword*4] |.define SAVE_PC, aword [rsp+aword*3] |.define SAVE_L, aword [rsp+aword*2] |.define SAVE_ERRF, dword [rsp+dword*3] |.define SAVE_NRES, dword [rsp+dword*2] |.define TMP1, aword [rsp] //<-- rsp while in interpreter. |//----- 16 byte aligned | |.define TMP1d, dword [rsp] |.define TMP1hi, dword [rsp+dword*1] |.define MULTRES, TMP1d // MULTRES overlaps TMP1d. | |.endif | |//----------------------------------------------------------------------- | |// Instruction headers. |.macro ins_A; .endmacro |.macro ins_AD; .endmacro |.macro ins_AJ; .endmacro |.macro ins_ABC; movzx RBd, RCH; movzx RCd, RCL; .endmacro |.macro ins_AB_; movzx RBd, RCH; .endmacro |.macro ins_A_C; movzx RCd, RCL; .endmacro |.macro ins_AND; not RD; .endmacro | |// Instruction decode+dispatch. Carefully tuned (nope, lodsd is not faster). |.macro ins_NEXT | mov RCd, [PC] | movzx RAd, RCH | movzx OP, RCL | add PC, 4 | shr RCd, 16 | jmp aword [DISPATCH+OP*8] |.endmacro | |// Instruction footer. |.if 1 | // Replicated dispatch. Less unpredictable branches, but higher I-Cache use. | .define ins_next, ins_NEXT | .define ins_next_, ins_NEXT |.else | // Common dispatch. Lower I-Cache use, only one (very) unpredictable branch. | // Affects only certain kinds of benchmarks (and only with -j off). | // Around 10%-30% slower on Core2, a lot more slower on P4. | .macro ins_next | jmp ->ins_next | .endmacro | .macro ins_next_ | ->ins_next: | ins_NEXT | .endmacro |.endif | |// Call decode and dispatch. |.macro ins_callt | // BASE = new base, RB = LFUNC, RD = nargs+1, [BASE-8] = PC | mov PC, LFUNC:RB->pc | mov RAd, [PC] | movzx OP, RAL | movzx RAd, RAH | add PC, 4 | jmp aword [DISPATCH+OP*8] |.endmacro | |.macro ins_call | // BASE = new base, RB = LFUNC, RD = nargs+1 | mov [BASE-8], PC | ins_callt |.endmacro | |//----------------------------------------------------------------------- | |// Macros to clear or set tags. |.macro cleartp, reg; shl reg, 17; shr reg, 17; .endmacro |.macro settp, reg, tp | mov64 ITYPE, ((int64_t)tp<<47) | or reg, ITYPE |.endmacro |.macro settp, dst, reg, tp | mov64 dst, ((int64_t)tp<<47) | or dst, reg |.endmacro |.macro setint, reg | settp reg, LJ_TISNUM |.endmacro |.macro setint, dst, reg | settp dst, reg, LJ_TISNUM |.endmacro | |// Macros to test operand types. |.macro checktp_nc, reg, tp, target | mov ITYPE, reg | sar ITYPE, 47 | cmp ITYPEd, tp | jne target |.endmacro |.macro checktp, reg, tp, target | mov ITYPE, reg | cleartp reg | sar ITYPE, 47 | cmp ITYPEd, tp | jne target |.endmacro |.macro checktptp, src, tp, target | mov ITYPE, src | sar ITYPE, 47 | cmp ITYPEd, tp | jne target |.endmacro |.macro checkstr, reg, target; checktp reg, LJ_TSTR, target; .endmacro |.macro checktab, reg, target; checktp reg, LJ_TTAB, target; .endmacro |.macro checkfunc, reg, target; checktp reg, LJ_TFUNC, target; .endmacro | |.macro checknumx, reg, target, jump | mov ITYPE, reg | sar ITYPE, 47 | cmp ITYPEd, LJ_TISNUM | jump target |.endmacro |.macro checkint, reg, target; checknumx reg, target, jne; .endmacro |.macro checkinttp, src, target; checknumx src, target, jne; .endmacro |.macro checknum, reg, target; checknumx reg, target, jae; .endmacro |.macro checknumtp, src, target; checknumx src, target, jae; .endmacro |.macro checknumber, src, target; checknumx src, target, ja; .endmacro | |.macro mov_false, reg; mov64 reg, (int64_t)~((uint64_t)1<<47); .endmacro |.macro mov_true, reg; mov64 reg, (int64_t)~((uint64_t)2<<47); .endmacro | |// These operands must be used with movzx. |.define PC_OP, byte [PC-4] |.define PC_RA, byte [PC-3] |.define PC_RB, byte [PC-1] |.define PC_RC, byte [PC-2] |.define PC_RD, word [PC-2] | |.macro branchPC, reg | lea PC, [PC+reg*4-BCBIAS_J*4] |.endmacro | |// Assumes DISPATCH is relative to GL. #define DISPATCH_GL(field) (GG_DISP2G + (int)offsetof(global_State, field)) #define DISPATCH_J(field) (GG_DISP2J + (int)offsetof(jit_State, field)) | #define PC2PROTO(field) ((int)offsetof(GCproto, field)-(int)sizeof(GCproto)) | |// Decrement hashed hotcount and trigger trace recorder if zero. |.macro hotloop, reg | mov reg, PCd | shr reg, 1 | and reg, HOTCOUNT_PCMASK | sub word [DISPATCH+reg+GG_DISP2HOT], HOTCOUNT_LOOP | jb ->vm_hotloop |.endmacro | |.macro hotcall, reg | mov reg, PCd | shr reg, 1 | and reg, HOTCOUNT_PCMASK | sub word [DISPATCH+reg+GG_DISP2HOT], HOTCOUNT_CALL | jb ->vm_hotcall |.endmacro | |// Set current VM state. |.macro set_vmstate, st | mov dword [DISPATCH+DISPATCH_GL(vmstate)], ~LJ_VMST_..st |.endmacro | |.macro fpop1; fstp st1; .endmacro | |// Synthesize SSE FP constants. |.macro sseconst_abs, reg, tmp // Synthesize abs mask. | mov64 tmp, U64x(7fffffff,ffffffff); movd reg, tmp |.endmacro | |.macro sseconst_hi, reg, tmp, val // Synthesize hi-32 bit const. | mov64 tmp, U64x(val,00000000); movd reg, tmp |.endmacro | |.macro sseconst_sign, reg, tmp // Synthesize sign mask. | sseconst_hi reg, tmp, 80000000 |.endmacro |.macro sseconst_1, reg, tmp // Synthesize 1.0. | sseconst_hi reg, tmp, 3ff00000 |.endmacro |.macro sseconst_m1, reg, tmp // Synthesize -1.0. | sseconst_hi reg, tmp, bff00000 |.endmacro |.macro sseconst_2p52, reg, tmp // Synthesize 2^52. | sseconst_hi reg, tmp, 43300000 |.endmacro |.macro sseconst_tobit, reg, tmp // Synthesize 2^52 + 2^51. | sseconst_hi reg, tmp, 43380000 |.endmacro | |// Move table write barrier back. Overwrites reg. |.macro barrierback, tab, reg | and byte tab->marked, (uint8_t)~LJ_GC_BLACK // black2gray(tab) | mov reg, [DISPATCH+DISPATCH_GL(gc.grayagain)] | mov [DISPATCH+DISPATCH_GL(gc.grayagain)], tab | mov tab->gclist, reg |.endmacro | |//----------------------------------------------------------------------- /* Generate subroutines used by opcodes and other parts of the VM. */ /* The .code_sub section should be last to help static branch prediction. */ static void build_subroutines(BuildCtx *ctx) { |.code_sub | |//----------------------------------------------------------------------- |//-- Return handling ---------------------------------------------------- |//----------------------------------------------------------------------- | |->vm_returnp: | test PCd, FRAME_P | jz ->cont_dispatch | | // Return from pcall or xpcall fast func. | and PC, -8 | sub BASE, PC // Restore caller base. | lea RA, [RA+PC-8] // Rebase RA and prepend one result. | mov PC, [BASE-8] // Fetch PC of previous frame. | // Prepending may overwrite the pcall frame, so do it at the end. | mov_true ITYPE | mov aword [BASE+RA], ITYPE // Prepend true to results. | |->vm_returnc: | add RDd, 1 // RD = nresults+1 | jz ->vm_unwind_yield | mov MULTRES, RDd | test PC, FRAME_TYPE | jz ->BC_RET_Z // Handle regular return to Lua. | |->vm_return: | // BASE = base, RA = resultofs, RD = nresults+1 (= MULTRES), PC = return | xor PC, FRAME_C | test PCd, FRAME_TYPE | jnz ->vm_returnp | | // Return to C. | set_vmstate C | and PC, -8 | sub PC, BASE | neg PC // Previous base = BASE - delta. | | sub RDd, 1 | jz >2 |1: // Move results down. | mov RB, [BASE+RA] | mov [BASE-16], RB | add BASE, 8 | sub RDd, 1 | jnz <1 |2: | mov L:RB, SAVE_L | mov L:RB->base, PC |3: | mov RDd, MULTRES | mov RAd, SAVE_NRES // RA = wanted nresults+1 |4: | cmp RAd, RDd | jne >6 // More/less results wanted? |5: | sub BASE, 16 | mov L:RB->top, BASE | |->vm_leave_cp: | mov RA, SAVE_CFRAME // Restore previous C frame. | mov L:RB->cframe, RA | xor eax, eax // Ok return status for vm_pcall. | |->vm_leave_unw: | restoreregs | ret | |6: | jb >7 // Less results wanted? | // More results wanted. Check stack size and fill up results with nil. | cmp BASE, L:RB->maxstack | ja >8 | mov aword [BASE-16], LJ_TNIL | add BASE, 8 | add RDd, 1 | jmp <4 | |7: // Less results wanted. | test RAd, RAd | jz <5 // But check for LUA_MULTRET+1. | sub RA, RD // Negative result! | lea BASE, [BASE+RA*8] // Correct top. | jmp <5 | |8: // Corner case: need to grow stack for filling up results. | // This can happen if: | // - A C function grows the stack (a lot). | // - The GC shrinks the stack in between. | // - A return back from a lua_call() with (high) nresults adjustment. | mov L:RB->top, BASE // Save current top held in BASE (yes). | mov MULTRES, RDd // Need to fill only remainder with nil. | mov CARG2d, RAd | mov CARG1, L:RB | call extern lj_state_growstack // (lua_State *L, int n) | mov BASE, L:RB->top // Need the (realloced) L->top in BASE. | jmp <3 | |->vm_unwind_yield: | mov al, LUA_YIELD | jmp ->vm_unwind_c_eh | |->vm_unwind_c: // Unwind C stack, return from vm_pcall. | // (void *cframe, int errcode) | mov eax, CARG2d // Error return status for vm_pcall. | mov rsp, CARG1 |->vm_unwind_c_eh: // Landing pad for external unwinder. | mov L:RB, SAVE_L | mov GL:RB, L:RB->glref | mov dword GL:RB->vmstate, ~LJ_VMST_C | jmp ->vm_leave_unw | |->vm_unwind_rethrow: |.if not X64WIN | mov CARG1, SAVE_L | mov CARG2d, eax | restoreregs | jmp extern lj_err_throw // (lua_State *L, int errcode) |.endif | |->vm_unwind_ff: // Unwind C stack, return from ff pcall. | // (void *cframe) | and CARG1, CFRAME_RAWMASK | mov rsp, CARG1 |->vm_unwind_ff_eh: // Landing pad for external unwinder. | mov L:RB, SAVE_L | mov RDd, 1+1 // Really 1+2 results, incr. later. | mov BASE, L:RB->base | mov DISPATCH, L:RB->glref // Setup pointer to dispatch table. | add DISPATCH, GG_G2DISP | mov PC, [BASE-8] // Fetch PC of previous frame. | mov_false RA | mov RB, [BASE] | mov [BASE-16], RA // Prepend false to error message. | mov [BASE-8], RB | mov RA, -16 // Results start at BASE+RA = BASE-16. | set_vmstate INTERP | jmp ->vm_returnc // Increments RD/MULTRES and returns. | |//----------------------------------------------------------------------- |//-- Grow stack for calls ----------------------------------------------- |//----------------------------------------------------------------------- | |->vm_growstack_c: // Grow stack for C function. | mov CARG2d, LUA_MINSTACK | jmp >2 | |->vm_growstack_v: // Grow stack for vararg Lua function. | sub RD, 16 // LJ_FR2 | jmp >1 | |->vm_growstack_f: // Grow stack for fixarg Lua function. | // BASE = new base, RD = nargs+1, RB = L, PC = first PC | lea RD, [BASE+NARGS:RD*8-8] |1: | movzx RAd, byte [PC-4+PC2PROTO(framesize)] | add PC, 4 // Must point after first instruction. | mov L:RB->base, BASE | mov L:RB->top, RD | mov SAVE_PC, PC | mov CARG2, RA |2: | // RB = L, L->base = new base, L->top = top | mov CARG1, L:RB | call extern lj_state_growstack // (lua_State *L, int n) | mov BASE, L:RB->base | mov RD, L:RB->top | mov LFUNC:RB, [BASE-16] | cleartp LFUNC:RB | sub RD, BASE | shr RDd, 3 | add NARGS:RDd, 1 | // BASE = new base, RB = LFUNC, RD = nargs+1 | ins_callt // Just retry the call. | |//----------------------------------------------------------------------- |//-- Entry points into the assembler VM --------------------------------- |//----------------------------------------------------------------------- | |->vm_resume: // Setup C frame and resume thread. | // (lua_State *L, TValue *base, int nres1 = 0, ptrdiff_t ef = 0) | saveregs | mov L:RB, CARG1 // Caveat: CARG1 may be RA. | mov SAVE_L, CARG1 | mov RA, CARG2 | mov PCd, FRAME_CP | xor RDd, RDd | lea KBASE, [esp+CFRAME_RESUME] | mov DISPATCH, L:RB->glref // Setup pointer to dispatch table. | add DISPATCH, GG_G2DISP | mov SAVE_PC, RD // Any value outside of bytecode is ok. | mov SAVE_CFRAME, RD | mov SAVE_NRES, RDd | mov SAVE_ERRF, RDd | mov L:RB->cframe, KBASE | cmp byte L:RB->status, RDL | je >2 // Initial resume (like a call). | | // Resume after yield (like a return). | mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB | set_vmstate INTERP | mov byte L:RB->status, RDL | mov BASE, L:RB->base | mov RD, L:RB->top | sub RD, RA | shr RDd, 3 | add RDd, 1 // RD = nresults+1 | sub RA, BASE // RA = resultofs | mov PC, [BASE-8] | mov MULTRES, RDd | test PCd, FRAME_TYPE | jz ->BC_RET_Z | jmp ->vm_return | |->vm_pcall: // Setup protected C frame and enter VM. | // (lua_State *L, TValue *base, int nres1, ptrdiff_t ef) | saveregs | mov PCd, FRAME_CP | mov SAVE_ERRF, CARG4d | jmp >1 | |->vm_call: // Setup C frame and enter VM. | // (lua_State *L, TValue *base, int nres1) | saveregs | mov PCd, FRAME_C | |1: // Entry point for vm_pcall above (PC = ftype). | mov SAVE_NRES, CARG3d | mov L:RB, CARG1 // Caveat: CARG1 may be RA. | mov SAVE_L, CARG1 | mov RA, CARG2 | | mov DISPATCH, L:RB->glref // Setup pointer to dispatch table. | mov KBASE, L:RB->cframe // Add our C frame to cframe chain. | mov SAVE_CFRAME, KBASE | mov SAVE_PC, L:RB // Any value outside of bytecode is ok. | add DISPATCH, GG_G2DISP | mov L:RB->cframe, rsp | |2: // Entry point for vm_resume/vm_cpcall (RA = base, RB = L, PC = ftype). | mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB | set_vmstate INTERP | mov BASE, L:RB->base // BASE = old base (used in vmeta_call). | add PC, RA | sub PC, BASE // PC = frame delta + frame type | | mov RD, L:RB->top | sub RD, RA | shr NARGS:RDd, 3 | add NARGS:RDd, 1 // RD = nargs+1 | |->vm_call_dispatch: | mov LFUNC:RB, [RA-16] | checkfunc LFUNC:RB, ->vmeta_call // Ensure KBASE defined and != BASE. | |->vm_call_dispatch_f: | mov BASE, RA | ins_call | // BASE = new base, RB = func, RD = nargs+1, PC = caller PC | |->vm_cpcall: // Setup protected C frame, call C. | // (lua_State *L, lua_CFunction func, void *ud, lua_CPFunction cp) | saveregs | mov L:RB, CARG1 // Caveat: CARG1 may be RA. | mov SAVE_L, CARG1 | mov SAVE_PC, L:RB // Any value outside of bytecode is ok. | | mov KBASE, L:RB->stack // Compute -savestack(L, L->top). | sub KBASE, L:RB->top | mov DISPATCH, L:RB->glref // Setup pointer to dispatch table. | mov SAVE_ERRF, 0 // No error function. | mov SAVE_NRES, KBASEd // Neg. delta means cframe w/o frame. | add DISPATCH, GG_G2DISP | // Handler may change cframe_nres(L->cframe) or cframe_errfunc(L->cframe). | | mov KBASE, L:RB->cframe // Add our C frame to cframe chain. | mov SAVE_CFRAME, KBASE | mov L:RB->cframe, rsp | mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB | | call CARG4 // (lua_State *L, lua_CFunction func, void *ud) | // TValue * (new base) or NULL returned in eax (RC). | test RC, RC | jz ->vm_leave_cp // No base? Just remove C frame. | mov RA, RC | mov PCd, FRAME_CP | jmp <2 // Else continue with the call. | |//----------------------------------------------------------------------- |//-- Metamethod handling ------------------------------------------------ |//----------------------------------------------------------------------- | |//-- Continuation dispatch ---------------------------------------------- | |->cont_dispatch: | // BASE = meta base, RA = resultofs, RD = nresults+1 (also in MULTRES) | add RA, BASE | and PC, -8 | mov RB, BASE | sub BASE, PC // Restore caller BASE. | mov aword [RA+RD*8-8], LJ_TNIL // Ensure one valid arg. | mov RC, RA // ... in [RC] | mov PC, [RB-24] // Restore PC from [cont|PC]. | mov RA, qword [RB-32] // May be negative on WIN64 with debug. |.if FFI | cmp RA, 1 | jbe >1 |.endif | mov LFUNC:KBASE, [BASE-16] | cleartp LFUNC:KBASE | mov KBASE, LFUNC:KBASE->pc | mov KBASE, [KBASE+PC2PROTO(k)] | // BASE = base, RC = result, RB = meta base | jmp RA // Jump to continuation. | |.if FFI |1: | je ->cont_ffi_callback // cont = 1: return from FFI callback. | // cont = 0: Tail call from C function. | sub RB, BASE | shr RBd, 3 | lea RDd, [RBd-3] | jmp ->vm_call_tail |.endif | |->cont_cat: // BASE = base, RC = result, RB = mbase | movzx RAd, PC_RB | sub RB, 32 | lea RA, [BASE+RA*8] | sub RA, RB | je ->cont_ra | neg RA | shr RAd, 3 |.if X64WIN | mov CARG3d, RAd | mov L:CARG1, SAVE_L | mov L:CARG1->base, BASE | mov RC, [RC] | mov [RB], RC | mov CARG2, RB |.else | mov L:CARG1, SAVE_L | mov L:CARG1->base, BASE | mov CARG3d, RAd | mov RA, [RC] | mov [RB], RA | mov CARG2, RB |.endif | jmp ->BC_CAT_Z | |//-- Table indexing metamethods ----------------------------------------- | |->vmeta_tgets: | settp STR:RC, LJ_TSTR // STR:RC = GCstr * | mov TMP1, STR:RC | lea RC, TMP1 | cmp PC_OP, BC_GGET | jne >1 | settp TAB:RA, TAB:RB, LJ_TTAB // TAB:RB = GCtab * | lea RB, [DISPATCH+DISPATCH_GL(tmptv)] // Store fn->l.env in g->tmptv. | mov [RB], TAB:RA | jmp >2 | |->vmeta_tgetb: | movzx RCd, PC_RC |.if DUALNUM | setint RC | mov TMP1, RC |.else | cvtsi2sd xmm0, RCd | movsd TMP1, xmm0 |.endif | lea RC, TMP1 | jmp >1 | |->vmeta_tgetv: | movzx RCd, PC_RC // Reload TValue *k from RC. | lea RC, [BASE+RC*8] |1: | movzx RBd, PC_RB // Reload TValue *t from RB. | lea RB, [BASE+RB*8] |2: | mov L:CARG1, SAVE_L | mov L:CARG1->base, BASE // Caveat: CARG2/CARG3 may be BASE. | mov CARG2, RB | mov CARG3, RC | mov L:RB, L:CARG1 | mov SAVE_PC, PC | call extern lj_meta_tget // (lua_State *L, TValue *o, TValue *k) | // TValue * (finished) or NULL (metamethod) returned in eax (RC). | mov BASE, L:RB->base | test RC, RC | jz >3 |->cont_ra: // BASE = base, RC = result | movzx RAd, PC_RA | mov RB, [RC] | mov [BASE+RA*8], RB | ins_next | |3: // Call __index metamethod. | // BASE = base, L->top = new base, stack = cont/func/t/k | mov RA, L:RB->top | mov [RA-24], PC // [cont|PC] | lea PC, [RA+FRAME_CONT] | sub PC, BASE | mov LFUNC:RB, [RA-16] // Guaranteed to be a function here. | mov NARGS:RDd, 2+1 // 2 args for func(t, k). | cleartp LFUNC:RB | jmp ->vm_call_dispatch_f | |->vmeta_tgetr: | mov CARG1, TAB:RB | mov RB, BASE // Save BASE. | mov CARG2d, RCd // Caveat: CARG2 == BASE | call extern lj_tab_getinth // (GCtab *t, int32_t key) | // cTValue * or NULL returned in eax (RC). | movzx RAd, PC_RA | mov BASE, RB // Restore BASE. | test RC, RC | jnz ->BC_TGETR_Z | mov ITYPE, LJ_TNIL | jmp ->BC_TGETR2_Z | |//----------------------------------------------------------------------- | |->vmeta_tsets: | settp STR:RC, LJ_TSTR // STR:RC = GCstr * | mov TMP1, STR:RC | lea RC, TMP1 | cmp PC_OP, BC_GSET | jne >1 | settp TAB:RA, TAB:RB, LJ_TTAB // TAB:RB = GCtab * | lea RB, [DISPATCH+DISPATCH_GL(tmptv)] // Store fn->l.env in g->tmptv. | mov [RB], TAB:RA | jmp >2 | |->vmeta_tsetb: | movzx RCd, PC_RC |.if DUALNUM | setint RC | mov TMP1, RC |.else | cvtsi2sd xmm0, RCd | movsd TMP1, xmm0 |.endif | lea RC, TMP1 | jmp >1 | |->vmeta_tsetv: | movzx RCd, PC_RC // Reload TValue *k from RC. | lea RC, [BASE+RC*8] |1: | movzx RBd, PC_RB // Reload TValue *t from RB. | lea RB, [BASE+RB*8] |2: | mov L:CARG1, SAVE_L | mov L:CARG1->base, BASE // Caveat: CARG2/CARG3 may be BASE. | mov CARG2, RB | mov CARG3, RC | mov L:RB, L:CARG1 | mov SAVE_PC, PC | call extern lj_meta_tset // (lua_State *L, TValue *o, TValue *k) | // TValue * (finished) or NULL (metamethod) returned in eax (RC). | mov BASE, L:RB->base | test RC, RC | jz >3 | // NOBARRIER: lj_meta_tset ensures the table is not black. | movzx RAd, PC_RA | mov RB, [BASE+RA*8] | mov [RC], RB |->cont_nop: // BASE = base, (RC = result) | ins_next | |3: // Call __newindex metamethod. | // BASE = base, L->top = new base, stack = cont/func/t/k/(v) | mov RA, L:RB->top | mov [RA-24], PC // [cont|PC] | movzx RCd, PC_RA | // Copy value to third argument. | mov RB, [BASE+RC*8] | mov [RA+16], RB | lea PC, [RA+FRAME_CONT] | sub PC, BASE | mov LFUNC:RB, [RA-16] // Guaranteed to be a function here. | mov NARGS:RDd, 3+1 // 3 args for func(t, k, v). | cleartp LFUNC:RB | jmp ->vm_call_dispatch_f | |->vmeta_tsetr: |.if X64WIN | mov L:CARG1, SAVE_L | mov CARG3d, RCd | mov L:CARG1->base, BASE | xchg CARG2, TAB:RB // Caveat: CARG2 == BASE. |.else | mov L:CARG1, SAVE_L | mov CARG2, TAB:RB | mov L:CARG1->base, BASE | mov RB, BASE // Save BASE. | mov CARG3d, RCd // Caveat: CARG3 == BASE. |.endif | mov SAVE_PC, PC | call extern lj_tab_setinth // (lua_State *L, GCtab *t, int32_t key) | // TValue * returned in eax (RC). | movzx RAd, PC_RA | mov BASE, RB // Restore BASE. | jmp ->BC_TSETR_Z | |//-- Comparison metamethods --------------------------------------------- | |->vmeta_comp: | movzx RDd, PC_RD | movzx RAd, PC_RA | mov L:RB, SAVE_L | mov L:RB->base, BASE // Caveat: CARG2/CARG3 == BASE. |.if X64WIN | lea CARG3, [BASE+RD*8] | lea CARG2, [BASE+RA*8] |.else | lea CARG2, [BASE+RA*8] | lea CARG3, [BASE+RD*8] |.endif | mov CARG1, L:RB // Caveat: CARG1/CARG4 == RA. | movzx CARG4d, PC_OP | mov SAVE_PC, PC | call extern lj_meta_comp // (lua_State *L, TValue *o1, *o2, int op) | // 0/1 or TValue * (metamethod) returned in eax (RC). |3: | mov BASE, L:RB->base | cmp RC, 1 | ja ->vmeta_binop |4: | lea PC, [PC+4] | jb >6 |5: | movzx RDd, PC_RD | branchPC RD |6: | ins_next | |->cont_condt: // BASE = base, RC = result | add PC, 4 | mov ITYPE, [RC] | sar ITYPE, 47 | cmp ITYPEd, LJ_TISTRUECOND // Branch if result is true. | jb <5 | jmp <6 | |->cont_condf: // BASE = base, RC = result | mov ITYPE, [RC] | sar ITYPE, 47 | cmp ITYPEd, LJ_TISTRUECOND // Branch if result is false. | jmp <4 | |->vmeta_equal: | cleartp TAB:RD | sub PC, 4 |.if X64WIN | mov CARG3, RD | mov CARG4d, RBd | mov L:RB, SAVE_L | mov L:RB->base, BASE // Caveat: CARG2 == BASE. | mov CARG2, RA | mov CARG1, L:RB // Caveat: CARG1 == RA. |.else | mov CARG2, RA | mov CARG4d, RBd // Caveat: CARG4 == RA. | mov L:RB, SAVE_L | mov L:RB->base, BASE // Caveat: CARG3 == BASE. | mov CARG3, RD | mov CARG1, L:RB |.endif | mov SAVE_PC, PC | call extern lj_meta_equal // (lua_State *L, GCobj *o1, *o2, int ne) | // 0/1 or TValue * (metamethod) returned in eax (RC). | jmp <3 | |->vmeta_equal_cd: |.if FFI | sub PC, 4 | mov L:RB, SAVE_L | mov L:RB->base, BASE | mov CARG1, L:RB | mov CARG2d, dword [PC-4] | mov SAVE_PC, PC | call extern lj_meta_equal_cd // (lua_State *L, BCIns ins) | // 0/1 or TValue * (metamethod) returned in eax (RC). | jmp <3 |.endif | |->vmeta_istype: | mov L:RB, SAVE_L | mov L:RB->base, BASE // Caveat: CARG2/CARG3 may be BASE. | mov CARG2d, RAd | mov CARG3d, RDd | mov L:CARG1, L:RB | mov SAVE_PC, PC | call extern lj_meta_istype // (lua_State *L, BCReg ra, BCReg tp) | mov BASE, L:RB->base | jmp <6 | |//-- Arithmetic metamethods --------------------------------------------- | |->vmeta_arith_vno: |.if DUALNUM | movzx RBd, PC_RB | movzx RCd, PC_RC |.endif |->vmeta_arith_vn: | lea RC, [KBASE+RC*8] | jmp >1 | |->vmeta_arith_nvo: |.if DUALNUM | movzx RBd, PC_RB | movzx RCd, PC_RC |.endif |->vmeta_arith_nv: | lea TMPR, [KBASE+RC*8] | lea RC, [BASE+RB*8] | mov RB, TMPR | jmp >2 | |->vmeta_unm: | lea RC, [BASE+RD*8] | mov RB, RC | jmp >2 | |->vmeta_arith_vvo: |.if DUALNUM | movzx RBd, PC_RB | movzx RCd, PC_RC |.endif |->vmeta_arith_vv: | lea RC, [BASE+RC*8] |1: | lea RB, [BASE+RB*8] |2: | lea RA, [BASE+RA*8] |.if X64WIN | mov CARG3, RB | mov CARG4, RC | movzx RCd, PC_OP | mov ARG5d, RCd | mov L:RB, SAVE_L | mov L:RB->base, BASE // Caveat: CARG2 == BASE. | mov CARG2, RA | mov CARG1, L:RB // Caveat: CARG1 == RA. |.else | movzx CARG5d, PC_OP | mov CARG2, RA | mov CARG4, RC // Caveat: CARG4 == RA. | mov L:CARG1, SAVE_L | mov L:CARG1->base, BASE // Caveat: CARG3 == BASE. | mov CARG3, RB | mov L:RB, L:CARG1 |.endif | mov SAVE_PC, PC | call extern lj_meta_arith // (lua_State *L, TValue *ra,*rb,*rc, BCReg op) | // NULL (finished) or TValue * (metamethod) returned in eax (RC). | mov BASE, L:RB->base | test RC, RC | jz ->cont_nop | | // Call metamethod for binary op. |->vmeta_binop: | // BASE = base, RC = new base, stack = cont/func/o1/o2 | mov RA, RC | sub RC, BASE | mov [RA-24], PC // [cont|PC] | lea PC, [RC+FRAME_CONT] | mov NARGS:RDd, 2+1 // 2 args for func(o1, o2). | jmp ->vm_call_dispatch | |->vmeta_len: | movzx RDd, PC_RD | mov L:RB, SAVE_L | mov L:RB->base, BASE | lea CARG2, [BASE+RD*8] // Caveat: CARG2 == BASE | mov L:CARG1, L:RB | mov SAVE_PC, PC | call extern lj_meta_len // (lua_State *L, TValue *o) | // NULL (retry) or TValue * (metamethod) returned in eax (RC). | mov BASE, L:RB->base #if LJ_52 | test RC, RC | jne ->vmeta_binop // Binop call for compatibility. | movzx RDd, PC_RD | mov TAB:CARG1, [BASE+RD*8] | cleartp TAB:CARG1 | jmp ->BC_LEN_Z #else | jmp ->vmeta_binop // Binop call for compatibility. #endif | |//-- Call metamethod ---------------------------------------------------- | |->vmeta_call_ra: | lea RA, [BASE+RA*8+16] |->vmeta_call: // Resolve and call __call metamethod. | // BASE = old base, RA = new base, RC = nargs+1, PC = return | mov TMP1d, NARGS:RDd // Save RA, RC for us. | mov RB, RA |.if X64WIN | mov L:TMPR, SAVE_L | mov L:TMPR->base, BASE // Caveat: CARG2 is BASE. | lea CARG2, [RA-16] | lea CARG3, [RA+NARGS:RD*8-8] | mov CARG1, L:TMPR // Caveat: CARG1 is RA. |.else | mov L:CARG1, SAVE_L | mov L:CARG1->base, BASE // Caveat: CARG3 is BASE. | lea CARG2, [RA-16] | lea CARG3, [RA+NARGS:RD*8-8] |.endif | mov SAVE_PC, PC | call extern lj_meta_call // (lua_State *L, TValue *func, TValue *top) | mov RA, RB | mov L:RB, SAVE_L | mov BASE, L:RB->base | mov NARGS:RDd, TMP1d | mov LFUNC:RB, [RA-16] | cleartp LFUNC:RB | add NARGS:RDd, 1 | // This is fragile. L->base must not move, KBASE must always be defined. | cmp KBASE, BASE // Continue with CALLT if flag set. | je ->BC_CALLT_Z | mov BASE, RA | ins_call // Otherwise call resolved metamethod. | |//-- Argument coercion for 'for' statement ------------------------------ | |->vmeta_for: | mov L:RB, SAVE_L | mov L:RB->base, BASE | mov CARG2, RA // Caveat: CARG2 == BASE | mov L:CARG1, L:RB // Caveat: CARG1 == RA | mov SAVE_PC, PC | call extern lj_meta_for // (lua_State *L, TValue *base) | mov BASE, L:RB->base | mov RCd, [PC-4] | movzx RAd, RCH | movzx OP, RCL | shr RCd, 16 | jmp aword [DISPATCH+OP*8+GG_DISP2STATIC] // Retry FORI or JFORI. | |//----------------------------------------------------------------------- |//-- Fast functions ----------------------------------------------------- |//----------------------------------------------------------------------- | |.macro .ffunc, name |->ff_ .. name: |.endmacro | |.macro .ffunc_1, name |->ff_ .. name: | cmp NARGS:RDd, 1+1; jb ->fff_fallback |.endmacro | |.macro .ffunc_2, name |->ff_ .. name: | cmp NARGS:RDd, 2+1; jb ->fff_fallback |.endmacro | |.macro .ffunc_n, name, op | .ffunc_1 name | checknumtp [BASE], ->fff_fallback | op xmm0, qword [BASE] |.endmacro | |.macro .ffunc_n, name | .ffunc_n name, movsd |.endmacro | |.macro .ffunc_nn, name | .ffunc_2 name | checknumtp [BASE], ->fff_fallback | checknumtp [BASE+8], ->fff_fallback | movsd xmm0, qword [BASE] | movsd xmm1, qword [BASE+8] |.endmacro | |// Inlined GC threshold check. Caveat: uses label 1. |.macro ffgccheck | mov RB, [DISPATCH+DISPATCH_GL(gc.total)] | cmp RB, [DISPATCH+DISPATCH_GL(gc.threshold)] | jb >1 | call ->fff_gcstep |1: |.endmacro | |//-- Base library: checks ----------------------------------------------- | |.ffunc_1 assert | mov ITYPE, [BASE] | mov RB, ITYPE | sar ITYPE, 47 | cmp ITYPEd, LJ_TISTRUECOND; jae ->fff_fallback | mov PC, [BASE-8] | mov MULTRES, RDd | mov RB, [BASE] | mov [BASE-16], RB | sub RDd, 2 | jz >2 | mov RA, BASE |1: | add RA, 8 | mov RB, [RA] | mov [RA-16], RB | sub RDd, 1 | jnz <1 |2: | mov RDd, MULTRES | jmp ->fff_res_ | |.ffunc_1 type | mov RC, [BASE] | sar RC, 47 | mov RBd, LJ_TISNUM | cmp RCd, RBd | cmovb RCd, RBd | not RCd |2: | mov CFUNC:RB, [BASE-16] | cleartp CFUNC:RB | mov STR:RC, [CFUNC:RB+RC*8+((char *)(&((GCfuncC *)0)->upvalue))] | mov PC, [BASE-8] | settp STR:RC, LJ_TSTR | mov [BASE-16], STR:RC | jmp ->fff_res1 | |//-- Base library: getters and setters --------------------------------- | |.ffunc_1 getmetatable | mov TAB:RB, [BASE] | mov PC, [BASE-8] | checktab TAB:RB, >6 |1: // Field metatable must be at same offset for GCtab and GCudata! | mov TAB:RB, TAB:RB->metatable |2: | test TAB:RB, TAB:RB | mov aword [BASE-16], LJ_TNIL | jz ->fff_res1 | settp TAB:RC, TAB:RB, LJ_TTAB | mov [BASE-16], TAB:RC // Store metatable as default result. | mov STR:RC, [DISPATCH+DISPATCH_GL(gcroot)+8*(GCROOT_MMNAME+MM_metatable)] | mov RAd, TAB:RB->hmask | and RAd, STR:RC->hash | settp STR:RC, LJ_TSTR | imul RAd, #NODE | add NODE:RA, TAB:RB->node |3: // Rearranged logic, because we expect _not_ to find the key. | cmp NODE:RA->key, STR:RC | je >5 |4: | mov NODE:RA, NODE:RA->next | test NODE:RA, NODE:RA | jnz <3 | jmp ->fff_res1 // Not found, keep default result. |5: | mov RB, NODE:RA->val | cmp RB, LJ_TNIL; je ->fff_res1 // Ditto for nil value. | mov [BASE-16], RB // Return value of mt.__metatable. | jmp ->fff_res1 | |6: | cmp ITYPEd, LJ_TUDATA; je <1 | cmp ITYPEd, LJ_TISNUM; ja >7 | mov ITYPEd, LJ_TISNUM |7: | not ITYPEd | mov TAB:RB, [DISPATCH+ITYPE*8+DISPATCH_GL(gcroot[GCROOT_BASEMT])] | jmp <2 | |.ffunc_2 setmetatable | mov TAB:RB, [BASE] | mov TAB:TMPR, TAB:RB | checktab TAB:RB, ->fff_fallback | // Fast path: no mt for table yet and not clearing the mt. | cmp aword TAB:RB->metatable, 0; jne ->fff_fallback | mov TAB:RA, [BASE+8] | checktab TAB:RA, ->fff_fallback | mov TAB:RB->metatable, TAB:RA | mov PC, [BASE-8] | mov [BASE-16], TAB:TMPR // Return original table. | test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table) | jz >1 | // Possible write barrier. Table is black, but skip iswhite(mt) check. | barrierback TAB:RB, RC |1: | jmp ->fff_res1 | |.ffunc_2 rawget |.if X64WIN | mov TAB:RA, [BASE] | checktab TAB:RA, ->fff_fallback | mov RB, BASE // Save BASE. | lea CARG3, [BASE+8] | mov CARG2, TAB:RA // Caveat: CARG2 == BASE. | mov CARG1, SAVE_L |.else | mov TAB:CARG2, [BASE] | checktab TAB:CARG2, ->fff_fallback | mov RB, BASE // Save BASE. | lea CARG3, [BASE+8] // Caveat: CARG3 == BASE. | mov CARG1, SAVE_L |.endif | call extern lj_tab_get // (lua_State *L, GCtab *t, cTValue *key) | // cTValue * returned in eax (RD). | mov BASE, RB // Restore BASE. | // Copy table slot. | mov RB, [RD] | mov PC, [BASE-8] | mov [BASE-16], RB | jmp ->fff_res1 | |//-- Base library: conversions ------------------------------------------ | |.ffunc tonumber | // Only handles the number case inline (without a base argument). | cmp NARGS:RDd, 1+1; jne ->fff_fallback // Exactly one argument. | mov RB, [BASE] | checknumber RB, ->fff_fallback | mov PC, [BASE-8] | mov [BASE-16], RB | jmp ->fff_res1 | |.ffunc_1 tostring | // Only handles the string or number case inline. | mov PC, [BASE-8] | mov STR:RB, [BASE] | checktp_nc STR:RB, LJ_TSTR, >3 | // A __tostring method in the string base metatable is ignored. |2: | mov [BASE-16], STR:RB | jmp ->fff_res1 |3: // Handle numbers inline, unless a number base metatable is present. | cmp ITYPEd, LJ_TISNUM; ja ->fff_fallback_1 | cmp aword [DISPATCH+DISPATCH_GL(gcroot[GCROOT_BASEMT_NUM])], 0 | jne ->fff_fallback | ffgccheck // Caveat: uses label 1. | mov L:RB, SAVE_L | mov L:RB->base, BASE // Add frame since C call can throw. | mov SAVE_PC, PC // Redundant (but a defined value). |.if not X64WIN | mov CARG2, BASE // Otherwise: CARG2 == BASE |.endif | mov L:CARG1, L:RB |.if DUALNUM | call extern lj_strfmt_number // (lua_State *L, cTValue *o) |.else | call extern lj_strfmt_num // (lua_State *L, lua_Number *np) |.endif | // GCstr returned in eax (RD). | mov BASE, L:RB->base | settp STR:RB, RD, LJ_TSTR | jmp <2 | |//-- Base library: iterators ------------------------------------------- | |.ffunc_1 next | je >2 // Missing 2nd arg? |1: |.if X64WIN | mov RA, [BASE] | checktab RA, ->fff_fallback |.else | mov CARG2, [BASE] | checktab CARG2, ->fff_fallback |.endif | mov L:RB, SAVE_L | mov L:RB->base, BASE // Add frame since C call can throw. | mov L:RB->top, BASE // Dummy frame length is ok. | mov PC, [BASE-8] |.if X64WIN | lea CARG3, [BASE+8] | mov CARG2, RA // Caveat: CARG2 == BASE. | mov CARG1, L:RB |.else | lea CARG3, [BASE+8] // Caveat: CARG3 == BASE. | mov CARG1, L:RB |.endif | mov SAVE_PC, PC // Needed for ITERN fallback. | call extern lj_tab_next // (lua_State *L, GCtab *t, TValue *key) | // Flag returned in eax (RD). | mov BASE, L:RB->base | test RDd, RDd; jz >3 // End of traversal? | // Copy key and value to results. | mov RB, [BASE+8] | mov RD, [BASE+16] | mov [BASE-16], RB | mov [BASE-8], RD |->fff_res2: | mov RDd, 1+2 | jmp ->fff_res |2: // Set missing 2nd arg to nil. | mov aword [BASE+8], LJ_TNIL | jmp <1 |3: // End of traversal: return nil. | mov aword [BASE-16], LJ_TNIL | jmp ->fff_res1 | |.ffunc_1 pairs | mov TAB:RB, [BASE] | mov TMPR, TAB:RB | checktab TAB:RB, ->fff_fallback #if LJ_52 | cmp aword TAB:RB->metatable, 0; jne ->fff_fallback #endif | mov CFUNC:RD, [BASE-16] | cleartp CFUNC:RD | mov CFUNC:RD, CFUNC:RD->upvalue[0] | settp CFUNC:RD, LJ_TFUNC | mov PC, [BASE-8] | mov [BASE-16], CFUNC:RD | mov [BASE-8], TMPR | mov aword [BASE], LJ_TNIL | mov RDd, 1+3 | jmp ->fff_res | |.ffunc_2 ipairs_aux | mov TAB:RB, [BASE] | checktab TAB:RB, ->fff_fallback |.if DUALNUM | mov RA, [BASE+8] | checkint RA, ->fff_fallback |.else | checknumtp [BASE+8], ->fff_fallback | movsd xmm0, qword [BASE+8] |.endif | mov PC, [BASE-8] |.if DUALNUM | add RAd, 1 | setint ITYPE, RA | mov [BASE-16], ITYPE |.else | sseconst_1 xmm1, TMPR | addsd xmm0, xmm1 | cvttsd2si RAd, xmm0 | movsd qword [BASE-16], xmm0 |.endif | cmp RAd, TAB:RB->asize; jae >2 // Not in array part? | mov RD, TAB:RB->array | lea RD, [RD+RA*8] |1: | cmp aword [RD], LJ_TNIL; je ->fff_res0 | // Copy array slot. | mov RB, [RD] | mov [BASE-8], RB | jmp ->fff_res2 |2: // Check for empty hash part first. Otherwise call C function. | cmp dword TAB:RB->hmask, 0; je ->fff_res0 |.if X64WIN | mov TMPR, BASE | mov CARG2d, RAd | mov CARG1, TAB:RB | mov RB, TMPR |.else | mov CARG1, TAB:RB | mov RB, BASE // Save BASE. | mov CARG2d, RAd // Caveat: CARG2 == BASE |.endif | call extern lj_tab_getinth // (GCtab *t, int32_t key) | // cTValue * or NULL returned in eax (RD). | mov BASE, RB | test RD, RD | jnz <1 |->fff_res0: | mov RDd, 1+0 | jmp ->fff_res | |.ffunc_1 ipairs | mov TAB:RB, [BASE] | mov TMPR, TAB:RB | checktab TAB:RB, ->fff_fallback #if LJ_52 | cmp aword TAB:RB->metatable, 0; jne ->fff_fallback #endif | mov CFUNC:RD, [BASE-16] | cleartp CFUNC:RD | mov CFUNC:RD, CFUNC:RD->upvalue[0] | settp CFUNC:RD, LJ_TFUNC | mov PC, [BASE-8] | mov [BASE-16], CFUNC:RD | mov [BASE-8], TMPR |.if DUALNUM | mov64 RD, ((int64_t)LJ_TISNUM<<47) | mov [BASE], RD |.else | mov qword [BASE], 0 |.endif | mov RDd, 1+3 | jmp ->fff_res | |//-- Base library: catch errors ---------------------------------------- | |.ffunc_1 pcall | lea RA, [BASE+16] | sub NARGS:RDd, 1 | mov PCd, 16+FRAME_PCALL |1: | movzx RBd, byte [DISPATCH+DISPATCH_GL(hookmask)] | shr RB, HOOK_ACTIVE_SHIFT | and RB, 1 | add PC, RB // Remember active hook before pcall. | // Note: this does a (harmless) copy of the function to the PC slot, too. | mov KBASE, RD |2: | mov RB, [RA+KBASE*8-24] | mov [RA+KBASE*8-16], RB | sub KBASE, 1 | ja <2 | jmp ->vm_call_dispatch | |.ffunc_2 xpcall | mov LFUNC:RA, [BASE+8] | checktp_nc LFUNC:RA, LJ_TFUNC, ->fff_fallback | mov LFUNC:RB, [BASE] // Swap function and traceback. | mov [BASE], LFUNC:RA | mov [BASE+8], LFUNC:RB | lea RA, [BASE+24] | sub NARGS:RDd, 2 | mov PCd, 24+FRAME_PCALL | jmp <1 | |//-- Coroutine library -------------------------------------------------- | |.macro coroutine_resume_wrap, resume |.if resume |.ffunc_1 coroutine_resume | mov L:RB, [BASE] | cleartp L:RB |.else |.ffunc coroutine_wrap_aux | mov CFUNC:RB, [BASE-16] | cleartp CFUNC:RB | mov L:RB, CFUNC:RB->upvalue[0].gcr | cleartp L:RB |.endif | mov PC, [BASE-8] | mov SAVE_PC, PC | mov TMP1, L:RB |.if resume | checktptp [BASE], LJ_TTHREAD, ->fff_fallback |.endif | cmp aword L:RB->cframe, 0; jne ->fff_fallback | cmp byte L:RB->status, LUA_YIELD; ja ->fff_fallback | mov RA, L:RB->top | je >1 // Status != LUA_YIELD (i.e. 0)? | cmp RA, L:RB->base // Check for presence of initial func. | je ->fff_fallback | mov PC, [RA-8] // Move initial function up. | mov [RA], PC | add RA, 8 |1: |.if resume | lea PC, [RA+NARGS:RD*8-16] // Check stack space (-1-thread). |.else | lea PC, [RA+NARGS:RD*8-8] // Check stack space (-1). |.endif | cmp PC, L:RB->maxstack; ja ->fff_fallback | mov L:RB->top, PC | | mov L:RB, SAVE_L | mov L:RB->base, BASE |.if resume | add BASE, 8 // Keep resumed thread in stack for GC. |.endif | mov L:RB->top, BASE |.if resume | lea RB, [BASE+NARGS:RD*8-24] // RB = end of source for stack move. |.else | lea RB, [BASE+NARGS:RD*8-16] // RB = end of source for stack move. |.endif | sub RB, PC // Relative to PC. | | cmp PC, RA | je >3 |2: // Move args to coroutine. | mov RC, [PC+RB] | mov [PC-8], RC | sub PC, 8 | cmp PC, RA | jne <2 |3: | mov CARG2, RA | mov CARG1, TMP1 | call ->vm_resume // (lua_State *L, TValue *base, 0, 0) | | mov L:RB, SAVE_L | mov L:PC, TMP1 | mov BASE, L:RB->base | mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB | set_vmstate INTERP | | cmp eax, LUA_YIELD | ja >8 |4: | mov RA, L:PC->base | mov KBASE, L:PC->top | mov L:PC->top, RA // Clear coroutine stack. | mov PC, KBASE | sub PC, RA | je >6 // No results? | lea RD, [BASE+PC] | shr PCd, 3 | cmp RD, L:RB->maxstack | ja >9 // Need to grow stack? | | mov RB, BASE | sub RB, RA |5: // Move results from coroutine. | mov RD, [RA] | mov [RA+RB], RD | add RA, 8 | cmp RA, KBASE | jne <5 |6: |.if resume | lea RDd, [PCd+2] // nresults+1 = 1 + true + results. | mov_true ITYPE // Prepend true to results. | mov [BASE-8], ITYPE |.else | lea RDd, [PCd+1] // nresults+1 = 1 + results. |.endif |7: | mov PC, SAVE_PC | mov MULTRES, RDd |.if resume | mov RA, -8 |.else | xor RAd, RAd |.endif | test PCd, FRAME_TYPE | jz ->BC_RET_Z | jmp ->vm_return | |8: // Coroutine returned with error (at co->top-1). |.if resume | mov_false ITYPE // Prepend false to results. | mov [BASE-8], ITYPE | mov RA, L:PC->top | sub RA, 8 | mov L:PC->top, RA // Clear error from coroutine stack. | // Copy error message. | mov RD, [RA] | mov [BASE], RD | mov RDd, 1+2 // nresults+1 = 1 + false + error. | jmp <7 |.else | mov CARG2, L:PC | mov CARG1, L:RB | call extern lj_ffh_coroutine_wrap_err // (lua_State *L, lua_State *co) | // Error function does not return. |.endif | |9: // Handle stack expansion on return from yield. | mov L:RA, TMP1 | mov L:RA->top, KBASE // Undo coroutine stack clearing. | mov CARG2, PC | mov CARG1, L:RB | call extern lj_state_growstack // (lua_State *L, int n) | mov L:PC, TMP1 | mov BASE, L:RB->base | jmp <4 // Retry the stack move. |.endmacro | | coroutine_resume_wrap 1 // coroutine.resume | coroutine_resume_wrap 0 // coroutine.wrap | |.ffunc coroutine_yield | mov L:RB, SAVE_L | test aword L:RB->cframe, CFRAME_RESUME | jz ->fff_fallback | mov L:RB->base, BASE | lea RD, [BASE+NARGS:RD*8-8] | mov L:RB->top, RD | xor RDd, RDd | mov aword L:RB->cframe, RD | mov al, LUA_YIELD | mov byte L:RB->status, al | jmp ->vm_leave_unw | |//-- Math library ------------------------------------------------------- | | .ffunc_1 math_abs | mov RB, [BASE] |.if DUALNUM | checkint RB, >3 | cmp RBd, 0; jns ->fff_resi | neg RBd; js >2 |->fff_resbit: |->fff_resi: | setint RB |->fff_resRB: | mov PC, [BASE-8] | mov [BASE-16], RB | jmp ->fff_res1 |2: | mov64 RB, U64x(41e00000,00000000) // 2^31. | jmp ->fff_resRB |3: | ja ->fff_fallback |.else | checknum RB, ->fff_fallback |.endif | shl RB, 1 | shr RB, 1 | mov PC, [BASE-8] | mov [BASE-16], RB | jmp ->fff_res1 | |.ffunc_n math_sqrt, sqrtsd |->fff_resxmm0: | mov PC, [BASE-8] | movsd qword [BASE-16], xmm0 | // fallthrough | |->fff_res1: | mov RDd, 1+1 |->fff_res: | mov MULTRES, RDd |->fff_res_: | test PCd, FRAME_TYPE | jnz >7 |5: | cmp PC_RB, RDL // More results expected? | ja >6 | // Adjust BASE. KBASE is assumed to be set for the calling frame. | movzx RAd, PC_RA | neg RA | lea BASE, [BASE+RA*8-16] // base = base - (RA+2)*8 | ins_next | |6: // Fill up results with nil. | mov aword [BASE+RD*8-24], LJ_TNIL | add RD, 1 | jmp <5 | |7: // Non-standard return case. | mov RA, -16 // Results start at BASE+RA = BASE-16. | jmp ->vm_return | |.macro math_round, func | .ffunc math_ .. func |.if DUALNUM | mov RB, [BASE] | checknumx RB, ->fff_resRB, je | ja ->fff_fallback |.else | checknumtp [BASE], ->fff_fallback |.endif | movsd xmm0, qword [BASE] | call ->vm_ .. func .. _sse |.if DUALNUM | cvttsd2si RBd, xmm0 | cmp RBd, 0x80000000 | jne ->fff_resi | cvtsi2sd xmm1, RBd | ucomisd xmm0, xmm1 | jp ->fff_resxmm0 | je ->fff_resi |.endif | jmp ->fff_resxmm0 |.endmacro | | math_round floor | math_round ceil | |.ffunc math_log | cmp NARGS:RDd, 1+1; jne ->fff_fallback // Exactly one argument. | checknumtp [BASE], ->fff_fallback | movsd xmm0, qword [BASE] | mov RB, BASE | call extern log | mov BASE, RB | jmp ->fff_resxmm0 | |.macro math_extern, func | .ffunc_n math_ .. func | mov RB, BASE | call extern func | mov BASE, RB | jmp ->fff_resxmm0 |.endmacro | |.macro math_extern2, func | .ffunc_nn math_ .. func | mov RB, BASE | call extern func | mov BASE, RB | jmp ->fff_resxmm0 |.endmacro | | math_extern log10 | math_extern exp | math_extern sin | math_extern cos | math_extern tan | math_extern asin | math_extern acos | math_extern atan | math_extern sinh | math_extern cosh | math_extern tanh | math_extern2 pow | math_extern2 atan2 | math_extern2 fmod | |.ffunc_2 math_ldexp | checknumtp [BASE], ->fff_fallback | checknumtp [BASE+8], ->fff_fallback | fld qword [BASE+8] | fld qword [BASE] | fscale | fpop1 | mov PC, [BASE-8] | fstp qword [BASE-16] | jmp ->fff_res1 | |.ffunc_n math_frexp |.if X64WIN | lea CARG2, TMP1 |.else | lea CARG1, TMP1 |.endif | mov RB, BASE | call extern frexp | mov BASE, RB | mov RBd, TMP1d | mov PC, [BASE-8] | movsd qword [BASE-16], xmm0 |.if DUALNUM | setint RB | mov [BASE-8], RB |.else | cvtsi2sd xmm1, RBd | movsd qword [BASE-8], xmm1 |.endif | mov RDd, 1+2 | jmp ->fff_res | |.ffunc_n math_modf |.if X64WIN | lea CARG2, [BASE-16] |.else | lea CARG1, [BASE-16] |.endif | mov PC, [BASE-8] | mov RB, BASE | call extern modf | mov BASE, RB | mov PC, [BASE-8] | movsd qword [BASE-8], xmm0 | mov RDd, 1+2 | jmp ->fff_res | |.macro math_minmax, name, cmovop, sseop | .ffunc name | mov RAd, 2 |.if DUALNUM | mov RB, [BASE] | checkint RB, >4 |1: // Handle integers. | cmp RAd, RDd; jae ->fff_resRB | mov TMPR, [BASE+RA*8-8] | checkint TMPR, >3 | cmp RBd, TMPRd | cmovop RB, TMPR | add RAd, 1 | jmp <1 |3: | ja ->fff_fallback | // Convert intermediate result to number and continue below. | cvtsi2sd xmm0, RBd | jmp >6 |4: | ja ->fff_fallback |.else | checknumtp [BASE], ->fff_fallback |.endif | | movsd xmm0, qword [BASE] |5: // Handle numbers or integers. | cmp RAd, RDd; jae ->fff_resxmm0 |.if DUALNUM | mov RB, [BASE+RA*8-8] | checknumx RB, >6, jb | ja ->fff_fallback | cvtsi2sd xmm1, RBd | jmp >7 |.else | checknumtp [BASE+RA*8-8], ->fff_fallback |.endif |6: | movsd xmm1, qword [BASE+RA*8-8] |7: | sseop xmm0, xmm1 | add RAd, 1 | jmp <5 |.endmacro | | math_minmax math_min, cmovg, minsd | math_minmax math_max, cmovl, maxsd | |//-- String library ----------------------------------------------------- | |.ffunc string_byte // Only handle the 1-arg case here. | cmp NARGS:RDd, 1+1; jne ->fff_fallback | mov STR:RB, [BASE] | checkstr STR:RB, ->fff_fallback | mov PC, [BASE-8] | cmp dword STR:RB->len, 1 | jb ->fff_res0 // Return no results for empty string. | movzx RBd, byte STR:RB[1] |.if DUALNUM | jmp ->fff_resi |.else | cvtsi2sd xmm0, RBd; jmp ->fff_resxmm0 |.endif | |.ffunc string_char // Only handle the 1-arg case here. | ffgccheck | cmp NARGS:RDd, 1+1; jne ->fff_fallback // *Exactly* 1 arg. |.if DUALNUM | mov RB, [BASE] | checkint RB, ->fff_fallback |.else | checknumtp [BASE], ->fff_fallback | cvttsd2si RBd, qword [BASE] |.endif | cmp RBd, 255; ja ->fff_fallback | mov TMP1d, RBd | mov TMPRd, 1 | lea RD, TMP1 // Points to stack. Little-endian. |->fff_newstr: | mov L:RB, SAVE_L | mov L:RB->base, BASE | mov CARG3d, TMPRd // Zero-extended to size_t. | mov CARG2, RD | mov CARG1, L:RB | mov SAVE_PC, PC | call extern lj_str_new // (lua_State *L, char *str, size_t l) |->fff_resstr: | // GCstr * returned in eax (RD). | mov BASE, L:RB->base | mov PC, [BASE-8] | settp STR:RD, LJ_TSTR | mov [BASE-16], STR:RD | jmp ->fff_res1 | |.ffunc string_sub | ffgccheck | mov TMPRd, -1 | cmp NARGS:RDd, 1+2; jb ->fff_fallback | jna >1 |.if DUALNUM | mov TMPR, [BASE+16] | checkint TMPR, ->fff_fallback |.else | checknumtp [BASE+16], ->fff_fallback | cvttsd2si TMPRd, qword [BASE+16] |.endif |1: | mov STR:RB, [BASE] | checkstr STR:RB, ->fff_fallback |.if DUALNUM | mov ITYPE, [BASE+8] | mov RAd, ITYPEd // Must clear hiword for lea below. | sar ITYPE, 47 | cmp ITYPEd, LJ_TISNUM | jne ->fff_fallback |.else | checknumtp [BASE+8], ->fff_fallback | cvttsd2si RAd, qword [BASE+8] |.endif | mov RCd, STR:RB->len | cmp RCd, TMPRd // len < end? (unsigned compare) | jb >5 |2: | test RAd, RAd // start <= 0? | jle >7 |3: | sub TMPRd, RAd // start > end? | jl ->fff_emptystr | lea RD, [STR:RB+RAd+#STR-1] | add TMPRd, 1 |4: | jmp ->fff_newstr | |5: // Negative end or overflow. | jl >6 | lea TMPRd, [TMPRd+RCd+1] // end = end+(len+1) | jmp <2 |6: // Overflow. | mov TMPRd, RCd // end = len | jmp <2 | |7: // Negative start or underflow. | je >8 | add RAd, RCd // start = start+(len+1) | add RAd, 1 | jg <3 // start > 0? |8: // Underflow. | mov RAd, 1 // start = 1 | jmp <3 | |->fff_emptystr: // Range underflow. | xor TMPRd, TMPRd // Zero length. Any ptr in RD is ok. | jmp <4 | |.macro ffstring_op, name | .ffunc_1 string_ .. name | ffgccheck |.if X64WIN | mov STR:TMPR, [BASE] | checkstr STR:TMPR, ->fff_fallback |.else | mov STR:CARG2, [BASE] | checkstr STR:CARG2, ->fff_fallback |.endif | mov L:RB, SAVE_L | lea SBUF:CARG1, [DISPATCH+DISPATCH_GL(tmpbuf)] | mov L:RB->base, BASE |.if X64WIN | mov STR:CARG2, STR:TMPR // Caveat: CARG2 == BASE |.endif | mov RC, SBUF:CARG1->b | mov SBUF:CARG1->L, L:RB | mov SBUF:CARG1->p, RC | mov SAVE_PC, PC | call extern lj_buf_putstr_ .. name | mov CARG1, rax | call extern lj_buf_tostr | jmp ->fff_resstr |.endmacro | |ffstring_op reverse |ffstring_op lower |ffstring_op upper | |//-- Bit library -------------------------------------------------------- | |.macro .ffunc_bit, name, kind, fdef | fdef name |.if kind == 2 | sseconst_tobit xmm1, RB |.endif |.if DUALNUM | mov RB, [BASE] | checkint RB, >1 |.if kind > 0 | jmp >2 |.else | jmp ->fff_resbit |.endif |1: | ja ->fff_fallback | movd xmm0, RB |.else | checknumtp [BASE], ->fff_fallback | movsd xmm0, qword [BASE] |.endif |.if kind < 2 | sseconst_tobit xmm1, RB |.endif | addsd xmm0, xmm1 | movd RBd, xmm0 |2: |.endmacro | |.macro .ffunc_bit, name, kind | .ffunc_bit name, kind, .ffunc_1 |.endmacro | |.ffunc_bit bit_tobit, 0 | jmp ->fff_resbit | |.macro .ffunc_bit_op, name, ins | .ffunc_bit name, 2 | mov TMPRd, NARGS:RDd // Save for fallback. | lea RD, [BASE+NARGS:RD*8-16] |1: | cmp RD, BASE | jbe ->fff_resbit |.if DUALNUM | mov RA, [RD] | checkint RA, >2 | ins RBd, RAd | sub RD, 8 | jmp <1 |2: | ja ->fff_fallback_bit_op | movd xmm0, RA |.else | checknumtp [RD], ->fff_fallback_bit_op | movsd xmm0, qword [RD] |.endif | addsd xmm0, xmm1 | movd RAd, xmm0 | ins RBd, RAd | sub RD, 8 | jmp <1 |.endmacro | |.ffunc_bit_op bit_band, and |.ffunc_bit_op bit_bor, or |.ffunc_bit_op bit_bxor, xor | |.ffunc_bit bit_bswap, 1 | bswap RBd | jmp ->fff_resbit | |.ffunc_bit bit_bnot, 1 | not RBd |.if DUALNUM | jmp ->fff_resbit |.else |->fff_resbit: | cvtsi2sd xmm0, RBd | jmp ->fff_resxmm0 |.endif | |->fff_fallback_bit_op: | mov NARGS:RDd, TMPRd // Restore for fallback | jmp ->fff_fallback | |.macro .ffunc_bit_sh, name, ins |.if DUALNUM | .ffunc_bit name, 1, .ffunc_2 | // Note: no inline conversion from number for 2nd argument! | mov RA, [BASE+8] | checkint RA, ->fff_fallback |.else | .ffunc_nn name | sseconst_tobit xmm2, RB | addsd xmm0, xmm2 | addsd xmm1, xmm2 | movd RBd, xmm0 | movd RAd, xmm1 |.endif | ins RBd, cl // Assumes RA is ecx. | jmp ->fff_resbit |.endmacro | |.ffunc_bit_sh bit_lshift, shl |.ffunc_bit_sh bit_rshift, shr |.ffunc_bit_sh bit_arshift, sar |.ffunc_bit_sh bit_rol, rol |.ffunc_bit_sh bit_ror, ror | |//----------------------------------------------------------------------- | |->fff_fallback_2: | mov NARGS:RDd, 1+2 // Other args are ignored, anyway. | jmp ->fff_fallback |->fff_fallback_1: | mov NARGS:RDd, 1+1 // Other args are ignored, anyway. |->fff_fallback: // Call fast function fallback handler. | // BASE = new base, RD = nargs+1 | mov L:RB, SAVE_L | mov PC, [BASE-8] // Fallback may overwrite PC. | mov SAVE_PC, PC // Redundant (but a defined value). | mov L:RB->base, BASE | lea RD, [BASE+NARGS:RD*8-8] | lea RA, [RD+8*LUA_MINSTACK] // Ensure enough space for handler. | mov L:RB->top, RD | mov CFUNC:RD, [BASE-16] | cleartp CFUNC:RD | cmp RA, L:RB->maxstack | ja >5 // Need to grow stack. | mov CARG1, L:RB | call aword CFUNC:RD->f // (lua_State *L) | mov BASE, L:RB->base | // Either throws an error, or recovers and returns -1, 0 or nresults+1. | test RDd, RDd; jg ->fff_res // Returned nresults+1? |1: | mov RA, L:RB->top | sub RA, BASE | shr RAd, 3 | test RDd, RDd | lea NARGS:RDd, [RAd+1] | mov LFUNC:RB, [BASE-16] | jne ->vm_call_tail // Returned -1? | cleartp LFUNC:RB | ins_callt // Returned 0: retry fast path. | |// Reconstruct previous base for vmeta_call during tailcall. |->vm_call_tail: | mov RA, BASE | test PCd, FRAME_TYPE | jnz >3 | movzx RBd, PC_RA | neg RB | lea BASE, [BASE+RB*8-16] // base = base - (RB+2)*8 | jmp ->vm_call_dispatch // Resolve again for tailcall. |3: | mov RB, PC | and RB, -8 | sub BASE, RB | jmp ->vm_call_dispatch // Resolve again for tailcall. | |5: // Grow stack for fallback handler. | mov CARG2d, LUA_MINSTACK | mov CARG1, L:RB | call extern lj_state_growstack // (lua_State *L, int n) | mov BASE, L:RB->base | xor RDd, RDd // Simulate a return 0. | jmp <1 // Dumb retry (goes through ff first). | |->fff_gcstep: // Call GC step function. | // BASE = new base, RD = nargs+1 | pop RB // Must keep stack at same level. | mov TMP1, RB // Save return address | mov L:RB, SAVE_L | mov SAVE_PC, PC // Redundant (but a defined value). | mov L:RB->base, BASE | lea RD, [BASE+NARGS:RD*8-8] | mov CARG1, L:RB | mov L:RB->top, RD | call extern lj_gc_step // (lua_State *L) | mov BASE, L:RB->base | mov RD, L:RB->top | sub RD, BASE | shr RDd, 3 | add NARGS:RDd, 1 | mov RB, TMP1 | push RB // Restore return address. | ret | |//----------------------------------------------------------------------- |//-- Special dispatch targets ------------------------------------------- |//----------------------------------------------------------------------- | |->vm_record: // Dispatch target for recording phase. |.if JIT | movzx RDd, byte [DISPATCH+DISPATCH_GL(hookmask)] | test RDL, HOOK_VMEVENT // No recording while in vmevent. | jnz >5 | // Decrement the hookcount for consistency, but always do the call. | test RDL, HOOK_ACTIVE | jnz >1 | test RDL, LUA_MASKLINE|LUA_MASKCOUNT | jz >1 | dec dword [DISPATCH+DISPATCH_GL(hookcount)] | jmp >1 |.endif | |->vm_rethook: // Dispatch target for return hooks. | movzx RDd, byte [DISPATCH+DISPATCH_GL(hookmask)] | test RDL, HOOK_ACTIVE // Hook already active? | jnz >5 | jmp >1 | |->vm_inshook: // Dispatch target for instr/line hooks. | movzx RDd, byte [DISPATCH+DISPATCH_GL(hookmask)] | test RDL, HOOK_ACTIVE // Hook already active? | jnz >5 | | test RDL, LUA_MASKLINE|LUA_MASKCOUNT | jz >5 | dec dword [DISPATCH+DISPATCH_GL(hookcount)] | jz >1 | test RDL, LUA_MASKLINE | jz >5 |1: | mov L:RB, SAVE_L | mov L:RB->base, BASE | mov CARG2, PC // Caveat: CARG2 == BASE | mov CARG1, L:RB | // SAVE_PC must hold the _previous_ PC. The callee updates it with PC. | call extern lj_dispatch_ins // (lua_State *L, const BCIns *pc) |3: | mov BASE, L:RB->base |4: | movzx RAd, PC_RA |5: | movzx OP, PC_OP | movzx RDd, PC_RD | jmp aword [DISPATCH+OP*8+GG_DISP2STATIC] // Re-dispatch to static ins. | |->cont_hook: // Continue from hook yield. | add PC, 4 | mov RA, [RB-40] | mov MULTRES, RAd // Restore MULTRES for *M ins. | jmp <4 | |->vm_hotloop: // Hot loop counter underflow. |.if JIT | mov LFUNC:RB, [BASE-16] // Same as curr_topL(L). | cleartp LFUNC:RB | mov RB, LFUNC:RB->pc | movzx RDd, byte [RB+PC2PROTO(framesize)] | lea RD, [BASE+RD*8] | mov L:RB, SAVE_L | mov L:RB->base, BASE | mov L:RB->top, RD | mov CARG2, PC | lea CARG1, [DISPATCH+GG_DISP2J] | mov aword [DISPATCH+DISPATCH_J(L)], L:RB | mov SAVE_PC, PC | call extern lj_trace_hot // (jit_State *J, const BCIns *pc) | jmp <3 |.endif | |->vm_callhook: // Dispatch target for call hooks. | mov SAVE_PC, PC |.if JIT | jmp >1 |.endif | |->vm_hotcall: // Hot call counter underflow. |.if JIT | mov SAVE_PC, PC | or PC, 1 // Marker for hot call. |1: |.endif | lea RD, [BASE+NARGS:RD*8-8] | mov L:RB, SAVE_L | mov L:RB->base, BASE | mov L:RB->top, RD | mov CARG2, PC | mov CARG1, L:RB | call extern lj_dispatch_call // (lua_State *L, const BCIns *pc) | // ASMFunction returned in eax/rax (RD). | mov SAVE_PC, 0 // Invalidate for subsequent line hook. |.if JIT | and PC, -2 |.endif | mov BASE, L:RB->base | mov RA, RD | mov RD, L:RB->top | sub RD, BASE | mov RB, RA | movzx RAd, PC_RA | shr RDd, 3 | add NARGS:RDd, 1 | jmp RB | |->cont_stitch: // Trace stitching. |.if JIT | // BASE = base, RC = result, RB = mbase | mov ITYPEd, [RB-24] // Save previous trace number. | mov TMPRd, MULTRES | movzx RAd, PC_RA | lea RA, [BASE+RA*8] // Call base. | sub TMPRd, 1 | jz >2 |1: // Move results down. | mov RB, [RC] | mov [RA], RB | add RC, 8 | add RA, 8 | sub TMPRd, 1 | jnz <1 |2: | movzx RCd, PC_RA | movzx RBd, PC_RB | add RC, RB | lea RC, [BASE+RC*8-8] |3: | cmp RC, RA | ja >9 // More results wanted? | | mov RA, [DISPATCH+DISPATCH_J(trace)] | mov TRACE:RD, [RA+ITYPE*8] | test TRACE:RD, TRACE:RD | jz ->cont_nop | movzx RDd, word TRACE:RD->link | cmp RDd, RBd | je ->cont_nop // Blacklisted. | test RDd, RDd | jne =>BC_JLOOP // Jump to stitched trace. | | // Stitch a new trace to the previous trace. | mov [DISPATCH+DISPATCH_J(exitno)], RB | mov L:RB, SAVE_L | mov L:RB->base, BASE | mov CARG2, PC | lea CARG1, [DISPATCH+GG_DISP2J] | mov aword [DISPATCH+DISPATCH_J(L)], L:RB | call extern lj_dispatch_stitch // (jit_State *J, const BCIns *pc) | mov BASE, L:RB->base | jmp ->cont_nop | |9: // Fill up results with nil. | mov aword [RA], LJ_TNIL | add RA, 8 | jmp <3 |.endif | |->vm_profhook: // Dispatch target for profiler hook. #if LJ_HASPROFILE | mov L:RB, SAVE_L | mov L:RB->base, BASE | mov CARG2, PC // Caveat: CARG2 == BASE | mov CARG1, L:RB | call extern lj_dispatch_profile // (lua_State *L, const BCIns *pc) | mov BASE, L:RB->base | // HOOK_PROFILE is off again, so re-dispatch to dynamic instruction. | sub PC, 4 | jmp ->cont_nop #endif | |//----------------------------------------------------------------------- |//-- Trace exit handler ------------------------------------------------- |//----------------------------------------------------------------------- | |// Called from an exit stub with the exit number on the stack. |// The 16 bit exit number is stored with two (sign-extended) push imm8. |->vm_exit_handler: |.if JIT | push r13; push r12 | push r11; push r10; push r9; push r8 | push rdi; push rsi; push rbp; lea rbp, [rsp+88]; push rbp | push rbx; push rdx; push rcx; push rax | movzx RCd, byte [rbp-8] // Reconstruct exit number. | mov RCH, byte [rbp-16] | mov [rbp-8], r15; mov [rbp-16], r14 | // Caveat: DISPATCH is rbx. | mov DISPATCH, [ebp] | mov RA, [DISPATCH+DISPATCH_GL(vmstate)] // Get trace number. | set_vmstate EXIT | mov [DISPATCH+DISPATCH_J(exitno)], RC | mov [DISPATCH+DISPATCH_J(parent)], RA |.if X64WIN | sub rsp, 16*8+4*8 // Room for SSE regs + save area. |.else | sub rsp, 16*8 // Room for SSE regs. |.endif | add rbp, -128 | movsd qword [rbp-8], xmm15; movsd qword [rbp-16], xmm14 | movsd qword [rbp-24], xmm13; movsd qword [rbp-32], xmm12 | movsd qword [rbp-40], xmm11; movsd qword [rbp-48], xmm10 | movsd qword [rbp-56], xmm9; movsd qword [rbp-64], xmm8 | movsd qword [rbp-72], xmm7; movsd qword [rbp-80], xmm6 | movsd qword [rbp-88], xmm5; movsd qword [rbp-96], xmm4 | movsd qword [rbp-104], xmm3; movsd qword [rbp-112], xmm2 | movsd qword [rbp-120], xmm1; movsd qword [rbp-128], xmm0 | // Caveat: RB is rbp. | mov L:RB, [DISPATCH+DISPATCH_GL(cur_L)] | mov BASE, [DISPATCH+DISPATCH_GL(jit_base)] | mov aword [DISPATCH+DISPATCH_J(L)], L:RB | mov L:RB->base, BASE |.if X64WIN | lea CARG2, [rsp+4*8] |.else | mov CARG2, rsp |.endif | lea CARG1, [DISPATCH+GG_DISP2J] | mov dword [DISPATCH+DISPATCH_GL(jit_base)], 0 | call extern lj_trace_exit // (jit_State *J, ExitState *ex) | // MULTRES or negated error code returned in eax (RD). | mov RA, L:RB->cframe | and RA, CFRAME_RAWMASK | mov [RA+CFRAME_OFS_L], L:RB // Set SAVE_L (on-trace resume/yield). | mov BASE, L:RB->base | mov PC, [RA+CFRAME_OFS_PC] // Get SAVE_PC. | jmp >1 |.endif |->vm_exit_interp: | // RD = MULTRES or negated error code, BASE, PC and DISPATCH set. |.if JIT | // Restore additional callee-save registers only used in compiled code. |.if X64WIN | lea RA, [rsp+10*16+4*8] |1: | movdqa xmm15, [RA-10*16] | movdqa xmm14, [RA-9*16] | movdqa xmm13, [RA-8*16] | movdqa xmm12, [RA-7*16] | movdqa xmm11, [RA-6*16] | movdqa xmm10, [RA-5*16] | movdqa xmm9, [RA-4*16] | movdqa xmm8, [RA-3*16] | movdqa xmm7, [RA-2*16] | mov rsp, RA // Reposition stack to C frame. | movdqa xmm6, [RA-1*16] | mov r15, CSAVE_1 | mov r14, CSAVE_2 | mov r13, CSAVE_3 | mov r12, CSAVE_4 |.else | lea RA, [rsp+16] |1: | mov r13, [RA-8] | mov r12, [RA] | mov rsp, RA // Reposition stack to C frame. |.endif | test RDd, RDd; js >9 // Check for error from exit. | mov L:RB, SAVE_L | mov MULTRES, RDd | mov LFUNC:KBASE, [BASE-16] | cleartp LFUNC:KBASE | mov KBASE, LFUNC:KBASE->pc | mov KBASE, [KBASE+PC2PROTO(k)] | mov L:RB->base, BASE | mov dword [DISPATCH+DISPATCH_GL(jit_base)], 0 | set_vmstate INTERP | // Modified copy of ins_next which handles function header dispatch, too. | mov RCd, [PC] | movzx RAd, RCH | movzx OP, RCL | add PC, 4 | shr RCd, 16 | cmp OP, BC_FUNCF // Function header? | jb >3 | cmp OP, BC_FUNCC+2 // Fast function? | jae >4 |2: | mov RCd, MULTRES // RC/RD holds nres+1. |3: | jmp aword [DISPATCH+OP*8] | |4: // Check frame below fast function. | mov RC, [BASE-8] | test RCd, FRAME_TYPE | jnz <2 // Trace stitching continuation? | // Otherwise set KBASE for Lua function below fast function. | movzx RCd, byte [RC-3] | neg RC | mov LFUNC:KBASE, [BASE+RC*8-24] | cleartp LFUNC:KBASE | mov KBASE, LFUNC:KBASE->pc | mov KBASE, [KBASE+PC2PROTO(k)] | jmp <2 | |9: // Rethrow error from the right C frame. | neg RD | mov CARG1, L:RB | mov CARG2, RD | call extern lj_err_throw // (lua_State *L, int errcode) |.endif | |//----------------------------------------------------------------------- |//-- Math helper functions ---------------------------------------------- |//----------------------------------------------------------------------- | |// FP value rounding. Called by math.floor/math.ceil fast functions |// and from JIT code. arg/ret is xmm0. xmm0-xmm3 and RD (eax) modified. |.macro vm_round, name, mode, cond |->name: |->name .. _sse: | sseconst_abs xmm2, RD | sseconst_2p52 xmm3, RD | movaps xmm1, xmm0 | andpd xmm1, xmm2 // |x| | ucomisd xmm3, xmm1 // No truncation if 2^52 <= |x|. | jbe >1 | andnpd xmm2, xmm0 // Isolate sign bit. |.if mode == 2 // trunc(x)? | movaps xmm0, xmm1 | addsd xmm1, xmm3 // (|x| + 2^52) - 2^52 | subsd xmm1, xmm3 | sseconst_1 xmm3, RD | cmpsd xmm0, xmm1, 1 // |x| < result? | andpd xmm0, xmm3 | subsd xmm1, xmm0 // If yes, subtract -1. | orpd xmm1, xmm2 // Merge sign bit back in. |.else | addsd xmm1, xmm3 // (|x| + 2^52) - 2^52 | subsd xmm1, xmm3 | orpd xmm1, xmm2 // Merge sign bit back in. | .if mode == 1 // ceil(x)? | sseconst_m1 xmm2, RD // Must subtract -1 to preserve -0. | cmpsd xmm0, xmm1, 6 // x > result? | .else // floor(x)? | sseconst_1 xmm2, RD | cmpsd xmm0, xmm1, 1 // x < result? | .endif | andpd xmm0, xmm2 | subsd xmm1, xmm0 // If yes, subtract +-1. |.endif | movaps xmm0, xmm1 |1: | ret |.endmacro | | vm_round vm_floor, 0, 1 | vm_round vm_ceil, 1, JIT | vm_round vm_trunc, 2, JIT | |// FP modulo x%y. Called by BC_MOD* and vm_arith. |->vm_mod: |// Args in xmm0/xmm1, return value in xmm0. |// Caveat: xmm0-xmm5 and RC (eax) modified! | movaps xmm5, xmm0 | divsd xmm0, xmm1 | sseconst_abs xmm2, RD | sseconst_2p52 xmm3, RD | movaps xmm4, xmm0 | andpd xmm4, xmm2 // |x/y| | ucomisd xmm3, xmm4 // No truncation if 2^52 <= |x/y|. | jbe >1 | andnpd xmm2, xmm0 // Isolate sign bit. | addsd xmm4, xmm3 // (|x/y| + 2^52) - 2^52 | subsd xmm4, xmm3 | orpd xmm4, xmm2 // Merge sign bit back in. | sseconst_1 xmm2, RD | cmpsd xmm0, xmm4, 1 // x/y < result? | andpd xmm0, xmm2 | subsd xmm4, xmm0 // If yes, subtract 1.0. | movaps xmm0, xmm5 | mulsd xmm1, xmm4 | subsd xmm0, xmm1 | ret |1: | mulsd xmm1, xmm0 | movaps xmm0, xmm5 | subsd xmm0, xmm1 | ret | |// Args in xmm0/eax. Ret in xmm0. xmm0-xmm1 and eax modified. |->vm_powi_sse: | cmp eax, 1; jle >6 // i<=1? | // Now 1 < (unsigned)i <= 0x80000000. |1: // Handle leading zeros. | test eax, 1; jnz >2 | mulsd xmm0, xmm0 | shr eax, 1 | jmp <1 |2: | shr eax, 1; jz >5 | movaps xmm1, xmm0 |3: // Handle trailing bits. | mulsd xmm0, xmm0 | shr eax, 1; jz >4 | jnc <3 | mulsd xmm1, xmm0 | jmp <3 |4: | mulsd xmm0, xmm1 |5: | ret |6: | je <5 // x^1 ==> x | jb >7 // x^0 ==> 1 | neg eax | call <1 | sseconst_1 xmm1, RD | divsd xmm1, xmm0 | movaps xmm0, xmm1 | ret |7: | sseconst_1 xmm0, RD | ret | |//----------------------------------------------------------------------- |//-- Miscellaneous functions -------------------------------------------- |//----------------------------------------------------------------------- | |// int lj_vm_cpuid(uint32_t f, uint32_t res[4]) |->vm_cpuid: | mov eax, CARG1d | .if X64WIN; push rsi; mov rsi, CARG2; .endif | push rbx | cpuid | mov [rsi], eax | mov [rsi+4], ebx | mov [rsi+8], ecx | mov [rsi+12], edx | pop rbx | .if X64WIN; pop rsi; .endif | ret | |//----------------------------------------------------------------------- |//-- Assertions --------------------------------------------------------- |//----------------------------------------------------------------------- | |->assert_bad_for_arg_type: #ifdef LUA_USE_ASSERT | int3 #endif | int3 | |//----------------------------------------------------------------------- |//-- FFI helper functions ----------------------------------------------- |//----------------------------------------------------------------------- | |// Handler for callback functions. Callback slot number in ah/al. |->vm_ffi_callback: |.if FFI |.type CTSTATE, CTState, PC | saveregs_ // ebp/rbp already saved. ebp now holds global_State *. | lea DISPATCH, [ebp+GG_G2DISP] | mov CTSTATE, GL:ebp->ctype_state | movzx eax, ax | mov CTSTATE->cb.slot, eax | mov CTSTATE->cb.gpr[0], CARG1 | mov CTSTATE->cb.gpr[1], CARG2 | mov CTSTATE->cb.gpr[2], CARG3 | mov CTSTATE->cb.gpr[3], CARG4 | movsd qword CTSTATE->cb.fpr[0], xmm0 | movsd qword CTSTATE->cb.fpr[1], xmm1 | movsd qword CTSTATE->cb.fpr[2], xmm2 | movsd qword CTSTATE->cb.fpr[3], xmm3 |.if X64WIN | lea rax, [rsp+CFRAME_SIZE+4*8] |.else | lea rax, [rsp+CFRAME_SIZE] | mov CTSTATE->cb.gpr[4], CARG5 | mov CTSTATE->cb.gpr[5], CARG6 | movsd qword CTSTATE->cb.fpr[4], xmm4 | movsd qword CTSTATE->cb.fpr[5], xmm5 | movsd qword CTSTATE->cb.fpr[6], xmm6 | movsd qword CTSTATE->cb.fpr[7], xmm7 |.endif | mov CTSTATE->cb.stack, rax | mov CARG2, rsp | mov SAVE_PC, CTSTATE // Any value outside of bytecode is ok. | mov CARG1, CTSTATE | call extern lj_ccallback_enter // (CTState *cts, void *cf) | // lua_State * returned in eax (RD). | set_vmstate INTERP | mov BASE, L:RD->base | mov RD, L:RD->top | sub RD, BASE | mov LFUNC:RB, [BASE-16] | cleartp LFUNC:RB | shr RD, 3 | add RD, 1 | ins_callt |.endif | |->cont_ffi_callback: // Return from FFI callback. |.if FFI | mov L:RA, SAVE_L | mov CTSTATE, [DISPATCH+DISPATCH_GL(ctype_state)] | mov aword CTSTATE->L, L:RA | mov L:RA->base, BASE | mov L:RA->top, RB | mov CARG1, CTSTATE | mov CARG2, RC | call extern lj_ccallback_leave // (CTState *cts, TValue *o) | mov rax, CTSTATE->cb.gpr[0] | movsd xmm0, qword CTSTATE->cb.fpr[0] | jmp ->vm_leave_unw |.endif | |->vm_ffi_call: // Call C function via FFI. | // Caveat: needs special frame unwinding, see below. |.if FFI | .type CCSTATE, CCallState, rbx | push rbp; mov rbp, rsp; push rbx; mov CCSTATE, CARG1 | | // Readjust stack. | mov eax, CCSTATE->spadj | sub rsp, rax | | // Copy stack slots. | movzx ecx, byte CCSTATE->nsp | sub ecx, 1 | js >2 |1: | mov rax, [CCSTATE+rcx*8+offsetof(CCallState, stack)] | mov [rsp+rcx*8+CCALL_SPS_EXTRA*8], rax | sub ecx, 1 | jns <1 |2: | | movzx eax, byte CCSTATE->nfpr | mov CARG1, CCSTATE->gpr[0] | mov CARG2, CCSTATE->gpr[1] | mov CARG3, CCSTATE->gpr[2] | mov CARG4, CCSTATE->gpr[3] |.if not X64WIN | mov CARG5, CCSTATE->gpr[4] | mov CARG6, CCSTATE->gpr[5] |.endif | test eax, eax; jz >5 | movaps xmm0, CCSTATE->fpr[0] | movaps xmm1, CCSTATE->fpr[1] | movaps xmm2, CCSTATE->fpr[2] | movaps xmm3, CCSTATE->fpr[3] |.if not X64WIN | cmp eax, 4; jbe >5 | movaps xmm4, CCSTATE->fpr[4] | movaps xmm5, CCSTATE->fpr[5] | movaps xmm6, CCSTATE->fpr[6] | movaps xmm7, CCSTATE->fpr[7] |.endif |5: | | call aword CCSTATE->func | | mov CCSTATE->gpr[0], rax | movaps CCSTATE->fpr[0], xmm0 |.if not X64WIN | mov CCSTATE->gpr[1], rdx | movaps CCSTATE->fpr[1], xmm1 |.endif | | mov rbx, [rbp-8]; leave; ret |.endif |// Note: vm_ffi_call must be the last function in this object file! | |//----------------------------------------------------------------------- } /* Generate the code for a single instruction. */ static void build_ins(BuildCtx *ctx, BCOp op, int defop) { int vk = 0; |// Note: aligning all instructions does not pay off. |=>defop: switch (op) { /* -- Comparison ops ---------------------------------------------------- */ /* Remember: all ops branch for a true comparison, fall through otherwise. */ |.macro jmp_comp, lt, ge, le, gt, target ||switch (op) { ||case BC_ISLT: | lt target ||break; ||case BC_ISGE: | ge target ||break; ||case BC_ISLE: | le target ||break; ||case BC_ISGT: | gt target ||break; ||default: break; /* Shut up GCC. */ ||} |.endmacro case BC_ISLT: case BC_ISGE: case BC_ISLE: case BC_ISGT: | // RA = src1, RD = src2, JMP with RD = target | ins_AD | mov ITYPE, [BASE+RA*8] | mov RB, [BASE+RD*8] | mov RA, ITYPE | mov RD, RB | sar ITYPE, 47 | sar RB, 47 |.if DUALNUM | cmp ITYPEd, LJ_TISNUM; jne >7 | cmp RBd, LJ_TISNUM; jne >8 | add PC, 4 | cmp RAd, RDd | jmp_comp jge, jl, jg, jle, >9 |6: | movzx RDd, PC_RD | branchPC RD |9: | ins_next | |7: // RA is not an integer. | ja ->vmeta_comp | // RA is a number. | cmp RBd, LJ_TISNUM; jb >1; jne ->vmeta_comp | // RA is a number, RD is an integer. | cvtsi2sd xmm0, RDd | jmp >2 | |8: // RA is an integer, RD is not an integer. | ja ->vmeta_comp | // RA is an integer, RD is a number. | cvtsi2sd xmm1, RAd | movd xmm0, RD | jmp >3 |.else | cmp ITYPEd, LJ_TISNUM; jae ->vmeta_comp | cmp RBd, LJ_TISNUM; jae ->vmeta_comp |.endif |1: | movd xmm0, RD |2: | movd xmm1, RA |3: | add PC, 4 | ucomisd xmm0, xmm1 | // Unordered: all of ZF CF PF set, ordered: PF clear. | // To preserve NaN semantics GE/GT branch on unordered, but LT/LE don't. |.if DUALNUM | jmp_comp jbe, ja, jb, jae, <9 | jmp <6 |.else | jmp_comp jbe, ja, jb, jae, >1 | movzx RDd, PC_RD | branchPC RD |1: | ins_next |.endif break; case BC_ISEQV: case BC_ISNEV: vk = op == BC_ISEQV; | ins_AD // RA = src1, RD = src2, JMP with RD = target | mov RB, [BASE+RD*8] | mov ITYPE, [BASE+RA*8] | add PC, 4 | mov RD, RB | mov RA, ITYPE | sar RB, 47 | sar ITYPE, 47 |.if DUALNUM | cmp RBd, LJ_TISNUM; jne >7 | cmp ITYPEd, LJ_TISNUM; jne >8 | cmp RDd, RAd if (vk) { | jne >9 } else { | je >9 } | movzx RDd, PC_RD | branchPC RD |9: | ins_next | |7: // RD is not an integer. | ja >5 | // RD is a number. | movd xmm1, RD | cmp ITYPEd, LJ_TISNUM; jb >1; jne >5 | // RD is a number, RA is an integer. | cvtsi2sd xmm0, RAd | jmp >2 | |8: // RD is an integer, RA is not an integer. | ja >5 | // RD is an integer, RA is a number. | cvtsi2sd xmm1, RDd | jmp >1 | |.else | cmp RBd, LJ_TISNUM; jae >5 | cmp ITYPEd, LJ_TISNUM; jae >5 | movd xmm1, RD |.endif |1: | movd xmm0, RA |2: | ucomisd xmm0, xmm1 |4: iseqne_fp: if (vk) { | jp >2 // Unordered means not equal. | jne >2 } else { | jp >2 // Unordered means not equal. | je >1 } iseqne_end: if (vk) { |1: // EQ: Branch to the target. | movzx RDd, PC_RD | branchPC RD |2: // NE: Fallthrough to next instruction. |.if not FFI |3: |.endif } else { |.if not FFI |3: |.endif |2: // NE: Branch to the target. | movzx RDd, PC_RD | branchPC RD |1: // EQ: Fallthrough to next instruction. } if (LJ_DUALNUM && (op == BC_ISEQV || op == BC_ISNEV || op == BC_ISEQN || op == BC_ISNEN)) { | jmp <9 } else { | ins_next } | if (op == BC_ISEQV || op == BC_ISNEV) { |5: // Either or both types are not numbers. |.if FFI | cmp RBd, LJ_TCDATA; je ->vmeta_equal_cd | cmp ITYPEd, LJ_TCDATA; je ->vmeta_equal_cd |.endif | cmp RA, RD | je <1 // Same GCobjs or pvalues? | cmp RBd, ITYPEd | jne <2 // Not the same type? | cmp RBd, LJ_TISTABUD | ja <2 // Different objects and not table/ud? | | // Different tables or userdatas. Need to check __eq metamethod. | // Field metatable must be at same offset for GCtab and GCudata! | cleartp TAB:RA | mov TAB:RB, TAB:RA->metatable | test TAB:RB, TAB:RB | jz <2 // No metatable? | test byte TAB:RB->nomm, 1<<MM_eq | jnz <2 // Or 'no __eq' flag set? if (vk) { | xor RBd, RBd // ne = 0 } else { | mov RBd, 1 // ne = 1 } | jmp ->vmeta_equal // Handle __eq metamethod. } else { |.if FFI |3: | cmp ITYPEd, LJ_TCDATA if (LJ_DUALNUM && vk) { | jne <9 } else { | jne <2 } | jmp ->vmeta_equal_cd |.endif } break; case BC_ISEQS: case BC_ISNES: vk = op == BC_ISEQS; | ins_AND // RA = src, RD = str const, JMP with RD = target | mov RB, [BASE+RA*8] | add PC, 4 | checkstr RB, >3 | cmp RB, [KBASE+RD*8] iseqne_test: if (vk) { | jne >2 } else { | je >1 } goto iseqne_end; case BC_ISEQN: case BC_ISNEN: vk = op == BC_ISEQN; | ins_AD // RA = src, RD = num const, JMP with RD = target | mov RB, [BASE+RA*8] | add PC, 4 |.if DUALNUM | checkint RB, >7 | mov RD, [KBASE+RD*8] | checkint RD, >8 | cmp RBd, RDd if (vk) { | jne >9 } else { | je >9 } | movzx RDd, PC_RD | branchPC RD |9: | ins_next | |7: // RA is not an integer. | ja >3 | // RA is a number. | mov RD, [KBASE+RD*8] | checkint RD, >1 | // RA is a number, RD is an integer. | cvtsi2sd xmm0, RDd | jmp >2 | |8: // RA is an integer, RD is a number. | cvtsi2sd xmm0, RBd | movd xmm1, RD | ucomisd xmm0, xmm1 | jmp >4 |1: | movd xmm0, RD |.else | checknum RB, >3 |1: | movsd xmm0, qword [KBASE+RD*8] |.endif |2: | ucomisd xmm0, qword [BASE+RA*8] |4: goto iseqne_fp; case BC_ISEQP: case BC_ISNEP: vk = op == BC_ISEQP; | ins_AND // RA = src, RD = primitive type (~), JMP with RD = target | mov RB, [BASE+RA*8] | sar RB, 47 | add PC, 4 | cmp RBd, RDd if (!LJ_HASFFI) goto iseqne_test; if (vk) { | jne >3 | movzx RDd, PC_RD | branchPC RD |2: | ins_next |3: | cmp RBd, LJ_TCDATA; jne <2 | jmp ->vmeta_equal_cd } else { | je >2 | cmp RBd, LJ_TCDATA; je ->vmeta_equal_cd | movzx RDd, PC_RD | branchPC RD |2: | ins_next } break; /* -- Unary test and copy ops ------------------------------------------- */ case BC_ISTC: case BC_ISFC: case BC_IST: case BC_ISF: | ins_AD // RA = dst or unused, RD = src, JMP with RD = target | mov ITYPE, [BASE+RD*8] | add PC, 4 if (op == BC_ISTC || op == BC_ISFC) { | mov RB, ITYPE } | sar ITYPE, 47 | cmp ITYPEd, LJ_TISTRUECOND if (op == BC_IST || op == BC_ISTC) { | jae >1 } else { | jb >1 } if (op == BC_ISTC || op == BC_ISFC) { | mov [BASE+RA*8], RB } | movzx RDd, PC_RD | branchPC RD |1: // Fallthrough to the next instruction. | ins_next break; case BC_ISTYPE: | ins_AD // RA = src, RD = -type | mov RB, [BASE+RA*8] | sar RB, 47 | add RBd, RDd | jne ->vmeta_istype | ins_next break; case BC_ISNUM: | ins_AD // RA = src, RD = -(TISNUM-1) | checknumtp [BASE+RA*8], ->vmeta_istype | ins_next break; /* -- Unary ops --------------------------------------------------------- */ case BC_MOV: | ins_AD // RA = dst, RD = src | mov RB, [BASE+RD*8] | mov [BASE+RA*8], RB | ins_next_ break; case BC_NOT: | ins_AD // RA = dst, RD = src | mov RB, [BASE+RD*8] | sar RB, 47 | mov RCd, 2 | cmp RB, LJ_TISTRUECOND | sbb RCd, 0 | shl RC, 47 | not RC | mov [BASE+RA*8], RC | ins_next break; case BC_UNM: | ins_AD // RA = dst, RD = src | mov RB, [BASE+RD*8] |.if DUALNUM | checkint RB, >5 | neg RBd | jo >4 | setint RB |9: | mov [BASE+RA*8], RB | ins_next |4: | mov64 RB, U64x(41e00000,00000000) // 2^31. | jmp <9 |5: | ja ->vmeta_unm |.else | checknum RB, ->vmeta_unm |.endif | mov64 RD, U64x(80000000,00000000) | xor RB, RD |.if DUALNUM | jmp <9 |.else | mov [BASE+RA*8], RB | ins_next |.endif break; case BC_LEN: | ins_AD // RA = dst, RD = src | mov RD, [BASE+RD*8] | checkstr RD, >2 |.if DUALNUM | mov RDd, dword STR:RD->len |1: | setint RD | mov [BASE+RA*8], RD |.else | xorps xmm0, xmm0 | cvtsi2sd xmm0, dword STR:RD->len |1: | movsd qword [BASE+RA*8], xmm0 |.endif | ins_next |2: | cmp ITYPEd, LJ_TTAB; jne ->vmeta_len | mov TAB:CARG1, TAB:RD #if LJ_52 | mov TAB:RB, TAB:RD->metatable | cmp TAB:RB, 0 | jnz >9 |3: #endif |->BC_LEN_Z: | mov RB, BASE // Save BASE. | call extern lj_tab_len // (GCtab *t) | // Length of table returned in eax (RD). |.if DUALNUM | // Nothing to do. |.else | cvtsi2sd xmm0, RDd |.endif | mov BASE, RB // Restore BASE. | movzx RAd, PC_RA | jmp <1 #if LJ_52 |9: // Check for __len. | test byte TAB:RB->nomm, 1<<MM_len | jnz <3 | jmp ->vmeta_len // 'no __len' flag NOT set: check. #endif break; /* -- Binary ops -------------------------------------------------------- */ |.macro ins_arithpre, sseins, ssereg | ins_ABC ||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN); ||switch (vk) { ||case 0: | checknumtp [BASE+RB*8], ->vmeta_arith_vn | .if DUALNUM | checknumtp [KBASE+RC*8], ->vmeta_arith_vn | .endif | movsd xmm0, qword [BASE+RB*8] | sseins ssereg, qword [KBASE+RC*8] || break; ||case 1: | checknumtp [BASE+RB*8], ->vmeta_arith_nv | .if DUALNUM | checknumtp [KBASE+RC*8], ->vmeta_arith_nv | .endif | movsd xmm0, qword [KBASE+RC*8] | sseins ssereg, qword [BASE+RB*8] || break; ||default: | checknumtp [BASE+RB*8], ->vmeta_arith_vv | checknumtp [BASE+RC*8], ->vmeta_arith_vv | movsd xmm0, qword [BASE+RB*8] | sseins ssereg, qword [BASE+RC*8] || break; ||} |.endmacro | |.macro ins_arithdn, intins | ins_ABC ||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN); ||switch (vk) { ||case 0: | mov RB, [BASE+RB*8] | mov RC, [KBASE+RC*8] | checkint RB, ->vmeta_arith_vno | checkint RC, ->vmeta_arith_vno | intins RBd, RCd; jo ->vmeta_arith_vno || break; ||case 1: | mov RB, [BASE+RB*8] | mov RC, [KBASE+RC*8] | checkint RB, ->vmeta_arith_nvo | checkint RC, ->vmeta_arith_nvo | intins RCd, RBd; jo ->vmeta_arith_nvo || break; ||default: | mov RB, [BASE+RB*8] | mov RC, [BASE+RC*8] | checkint RB, ->vmeta_arith_vvo | checkint RC, ->vmeta_arith_vvo | intins RBd, RCd; jo ->vmeta_arith_vvo || break; ||} ||if (vk == 1) { | setint RC | mov [BASE+RA*8], RC ||} else { | setint RB | mov [BASE+RA*8], RB ||} | ins_next |.endmacro | |.macro ins_arithpost | movsd qword [BASE+RA*8], xmm0 |.endmacro | |.macro ins_arith, sseins | ins_arithpre sseins, xmm0 | ins_arithpost | ins_next |.endmacro | |.macro ins_arith, intins, sseins |.if DUALNUM | ins_arithdn intins |.else | ins_arith, sseins |.endif |.endmacro | // RA = dst, RB = src1 or num const, RC = src2 or num const case BC_ADDVN: case BC_ADDNV: case BC_ADDVV: | ins_arith add, addsd break; case BC_SUBVN: case BC_SUBNV: case BC_SUBVV: | ins_arith sub, subsd break; case BC_MULVN: case BC_MULNV: case BC_MULVV: | ins_arith imul, mulsd break; case BC_DIVVN: case BC_DIVNV: case BC_DIVVV: | ins_arith divsd break; case BC_MODVN: | ins_arithpre movsd, xmm1 |->BC_MODVN_Z: | call ->vm_mod | ins_arithpost | ins_next break; case BC_MODNV: case BC_MODVV: | ins_arithpre movsd, xmm1 | jmp ->BC_MODVN_Z // Avoid 3 copies. It's slow anyway. break; case BC_POW: | ins_arithpre movsd, xmm1 | mov RB, BASE | call extern pow | movzx RAd, PC_RA | mov BASE, RB | ins_arithpost | ins_next break; case BC_CAT: | ins_ABC // RA = dst, RB = src_start, RC = src_end | mov L:CARG1, SAVE_L | mov L:CARG1->base, BASE | lea CARG2, [BASE+RC*8] | mov CARG3d, RCd | sub CARG3d, RBd |->BC_CAT_Z: | mov L:RB, L:CARG1 | mov SAVE_PC, PC | call extern lj_meta_cat // (lua_State *L, TValue *top, int left) | // NULL (finished) or TValue * (metamethod) returned in eax (RC). | mov BASE, L:RB->base | test RC, RC | jnz ->vmeta_binop | movzx RBd, PC_RB // Copy result to Stk[RA] from Stk[RB]. | movzx RAd, PC_RA | mov RC, [BASE+RB*8] | mov [BASE+RA*8], RC | ins_next break; /* -- Constant ops ------------------------------------------------------ */ case BC_KSTR: | ins_AND // RA = dst, RD = str const (~) | mov RD, [KBASE+RD*8] | settp RD, LJ_TSTR | mov [BASE+RA*8], RD | ins_next break; case BC_KCDATA: |.if FFI | ins_AND // RA = dst, RD = cdata const (~) | mov RD, [KBASE+RD*8] | settp RD, LJ_TCDATA | mov [BASE+RA*8], RD | ins_next |.endif break; case BC_KSHORT: | ins_AD // RA = dst, RD = signed int16 literal |.if DUALNUM | movsx RDd, RDW | setint RD | mov [BASE+RA*8], RD |.else | movsx RDd, RDW // Sign-extend literal. | cvtsi2sd xmm0, RDd | movsd qword [BASE+RA*8], xmm0 |.endif | ins_next break; case BC_KNUM: | ins_AD // RA = dst, RD = num const | movsd xmm0, qword [KBASE+RD*8] | movsd qword [BASE+RA*8], xmm0 | ins_next break; case BC_KPRI: | ins_AD // RA = dst, RD = primitive type (~) | shl RD, 47 | not RD | mov [BASE+RA*8], RD | ins_next break; case BC_KNIL: | ins_AD // RA = dst_start, RD = dst_end | lea RA, [BASE+RA*8+8] | lea RD, [BASE+RD*8] | mov RB, LJ_TNIL | mov [RA-8], RB // Sets minimum 2 slots. |1: | mov [RA], RB | add RA, 8 | cmp RA, RD | jbe <1 | ins_next break; /* -- Upvalue and function ops ------------------------------------------ */ case BC_UGET: | ins_AD // RA = dst, RD = upvalue # | mov LFUNC:RB, [BASE-16] | cleartp LFUNC:RB | mov UPVAL:RB, [LFUNC:RB+RD*8+offsetof(GCfuncL, uvptr)] | mov RB, UPVAL:RB->v | mov RD, [RB] | mov [BASE+RA*8], RD | ins_next break; case BC_USETV: #define TV2MARKOFS \ ((int32_t)offsetof(GCupval, marked)-(int32_t)offsetof(GCupval, tv)) | ins_AD // RA = upvalue #, RD = src | mov LFUNC:RB, [BASE-16] | cleartp LFUNC:RB | mov UPVAL:RB, [LFUNC:RB+RA*8+offsetof(GCfuncL, uvptr)] | cmp byte UPVAL:RB->closed, 0 | mov RB, UPVAL:RB->v | mov RA, [BASE+RD*8] | mov [RB], RA | jz >1 | // Check barrier for closed upvalue. | test byte [RB+TV2MARKOFS], LJ_GC_BLACK // isblack(uv) | jnz >2 |1: | ins_next | |2: // Upvalue is black. Check if new value is collectable and white. | mov RD, RA | sar RD, 47 | sub RDd, LJ_TISGCV | cmp RDd, LJ_TNUMX - LJ_TISGCV // tvisgcv(v) | jbe <1 | cleartp GCOBJ:RA | test byte GCOBJ:RA->gch.marked, LJ_GC_WHITES // iswhite(v) | jz <1 | // Crossed a write barrier. Move the barrier forward. |.if not X64WIN | mov CARG2, RB | mov RB, BASE // Save BASE. |.else | xchg CARG2, RB // Save BASE (CARG2 == BASE). |.endif | lea GL:CARG1, [DISPATCH+GG_DISP2G] | call extern lj_gc_barrieruv // (global_State *g, TValue *tv) | mov BASE, RB // Restore BASE. | jmp <1 break; #undef TV2MARKOFS case BC_USETS: | ins_AND // RA = upvalue #, RD = str const (~) | mov LFUNC:RB, [BASE-16] | cleartp LFUNC:RB | mov UPVAL:RB, [LFUNC:RB+RA*8+offsetof(GCfuncL, uvptr)] | mov STR:RA, [KBASE+RD*8] | mov RD, UPVAL:RB->v | settp STR:ITYPE, STR:RA, LJ_TSTR | mov [RD], STR:ITYPE | test byte UPVAL:RB->marked, LJ_GC_BLACK // isblack(uv) | jnz >2 |1: | ins_next | |2: // Check if string is white and ensure upvalue is closed. | test byte GCOBJ:RA->gch.marked, LJ_GC_WHITES // iswhite(str) | jz <1 | cmp byte UPVAL:RB->closed, 0 | jz <1 | // Crossed a write barrier. Move the barrier forward. | mov RB, BASE // Save BASE (CARG2 == BASE). | mov CARG2, RD | lea GL:CARG1, [DISPATCH+GG_DISP2G] | call extern lj_gc_barrieruv // (global_State *g, TValue *tv) | mov BASE, RB // Restore BASE. | jmp <1 break; case BC_USETN: | ins_AD // RA = upvalue #, RD = num const | mov LFUNC:RB, [BASE-16] | cleartp LFUNC:RB | movsd xmm0, qword [KBASE+RD*8] | mov UPVAL:RB, [LFUNC:RB+RA*8+offsetof(GCfuncL, uvptr)] | mov RA, UPVAL:RB->v | movsd qword [RA], xmm0 | ins_next break; case BC_USETP: | ins_AD // RA = upvalue #, RD = primitive type (~) | mov LFUNC:RB, [BASE-16] | cleartp LFUNC:RB | mov UPVAL:RB, [LFUNC:RB+RA*8+offsetof(GCfuncL, uvptr)] | shl RD, 47 | not RD | mov RA, UPVAL:RB->v | mov [RA], RD | ins_next break; case BC_UCLO: | ins_AD // RA = level, RD = target | branchPC RD // Do this first to free RD. | mov L:RB, SAVE_L | cmp dword L:RB->openupval, 0 | je >1 | mov L:RB->base, BASE | lea CARG2, [BASE+RA*8] // Caveat: CARG2 == BASE | mov L:CARG1, L:RB // Caveat: CARG1 == RA | call extern lj_func_closeuv // (lua_State *L, TValue *level) | mov BASE, L:RB->base |1: | ins_next break; case BC_FNEW: | ins_AND // RA = dst, RD = proto const (~) (holding function prototype) | mov L:RB, SAVE_L | mov L:RB->base, BASE // Caveat: CARG2/CARG3 may be BASE. | mov CARG3, [BASE-16] | cleartp CARG3 | mov CARG2, [KBASE+RD*8] // Fetch GCproto *. | mov CARG1, L:RB | mov SAVE_PC, PC | // (lua_State *L, GCproto *pt, GCfuncL *parent) | call extern lj_func_newL_gc | // GCfuncL * returned in eax (RC). | mov BASE, L:RB->base | movzx RAd, PC_RA | settp LFUNC:RC, LJ_TFUNC | mov [BASE+RA*8], LFUNC:RC | ins_next break; /* -- Table ops --------------------------------------------------------- */ case BC_TNEW: | ins_AD // RA = dst, RD = hbits|asize | mov L:RB, SAVE_L | mov L:RB->base, BASE | mov RA, [DISPATCH+DISPATCH_GL(gc.total)] | cmp RA, [DISPATCH+DISPATCH_GL(gc.threshold)] | mov SAVE_PC, PC | jae >5 |1: | mov CARG3d, RDd | and RDd, 0x7ff | shr CARG3d, 11 | cmp RDd, 0x7ff | je >3 |2: | mov L:CARG1, L:RB | mov CARG2d, RDd | call extern lj_tab_new // (lua_State *L, int32_t asize, uint32_t hbits) | // Table * returned in eax (RC). | mov BASE, L:RB->base | movzx RAd, PC_RA | settp TAB:RC, LJ_TTAB | mov [BASE+RA*8], TAB:RC | ins_next |3: // Turn 0x7ff into 0x801. | mov RDd, 0x801 | jmp <2 |5: | mov L:CARG1, L:RB | call extern lj_gc_step_fixtop // (lua_State *L) | movzx RDd, PC_RD | jmp <1 break; case BC_TDUP: | ins_AND // RA = dst, RD = table const (~) (holding template table) | mov L:RB, SAVE_L | mov RA, [DISPATCH+DISPATCH_GL(gc.total)] | mov SAVE_PC, PC | cmp RA, [DISPATCH+DISPATCH_GL(gc.threshold)] | mov L:RB->base, BASE | jae >3 |2: | mov TAB:CARG2, [KBASE+RD*8] // Caveat: CARG2 == BASE | mov L:CARG1, L:RB // Caveat: CARG1 == RA | call extern lj_tab_dup // (lua_State *L, Table *kt) | // Table * returned in eax (RC). | mov BASE, L:RB->base | movzx RAd, PC_RA | settp TAB:RC, LJ_TTAB | mov [BASE+RA*8], TAB:RC | ins_next |3: | mov L:CARG1, L:RB | call extern lj_gc_step_fixtop // (lua_State *L) | movzx RDd, PC_RD // Need to reload RD. | not RD | jmp <2 break; case BC_GGET: | ins_AND // RA = dst, RD = str const (~) | mov LFUNC:RB, [BASE-16] | cleartp LFUNC:RB | mov TAB:RB, LFUNC:RB->env | mov STR:RC, [KBASE+RD*8] | jmp ->BC_TGETS_Z break; case BC_GSET: | ins_AND // RA = src, RD = str const (~) | mov LFUNC:RB, [BASE-16] | cleartp LFUNC:RB | mov TAB:RB, LFUNC:RB->env | mov STR:RC, [KBASE+RD*8] | jmp ->BC_TSETS_Z break; case BC_TGETV: | ins_ABC // RA = dst, RB = table, RC = key | mov TAB:RB, [BASE+RB*8] | mov RC, [BASE+RC*8] | checktab TAB:RB, ->vmeta_tgetv | | // Integer key? |.if DUALNUM | checkint RC, >5 |.else | // Convert number to int and back and compare. | checknum RC, >5 | movd xmm0, RC | cvttsd2si RCd, xmm0 | cvtsi2sd xmm1, RCd | ucomisd xmm0, xmm1 | jne ->vmeta_tgetv // Generic numeric key? Use fallback. |.endif | cmp RCd, TAB:RB->asize // Takes care of unordered, too. | jae ->vmeta_tgetv // Not in array part? Use fallback. | shl RCd, 3 | add RC, TAB:RB->array | // Get array slot. | mov ITYPE, [RC] | cmp ITYPE, LJ_TNIL // Avoid overwriting RB in fastpath. | je >2 |1: | mov [BASE+RA*8], ITYPE | ins_next | |2: // Check for __index if table value is nil. | mov TAB:TMPR, TAB:RB->metatable | test TAB:TMPR, TAB:TMPR | jz <1 | test byte TAB:TMPR->nomm, 1<<MM_index | jz ->vmeta_tgetv // 'no __index' flag NOT set: check. | jmp <1 | |5: // String key? | cmp ITYPEd, LJ_TSTR; jne ->vmeta_tgetv | cleartp STR:RC | jmp ->BC_TGETS_Z break; case BC_TGETS: | ins_ABC // RA = dst, RB = table, RC = str const (~) | mov TAB:RB, [BASE+RB*8] | not RC | mov STR:RC, [KBASE+RC*8] | checktab TAB:RB, ->vmeta_tgets |->BC_TGETS_Z: // RB = GCtab *, RC = GCstr * | mov TMPRd, TAB:RB->hmask | and TMPRd, STR:RC->hash | imul TMPRd, #NODE | add NODE:TMPR, TAB:RB->node | settp ITYPE, STR:RC, LJ_TSTR |1: | cmp NODE:TMPR->key, ITYPE | jne >4 | // Get node value. | mov ITYPE, NODE:TMPR->val | cmp ITYPE, LJ_TNIL | je >5 // Key found, but nil value? |2: | mov [BASE+RA*8], ITYPE | ins_next | |4: // Follow hash chain. | mov NODE:TMPR, NODE:TMPR->next | test NODE:TMPR, NODE:TMPR | jnz <1 | // End of hash chain: key not found, nil result. | mov ITYPE, LJ_TNIL | |5: // Check for __index if table value is nil. | mov TAB:TMPR, TAB:RB->metatable | test TAB:TMPR, TAB:TMPR | jz <2 // No metatable: done. | test byte TAB:TMPR->nomm, 1<<MM_index | jnz <2 // 'no __index' flag set: done. | jmp ->vmeta_tgets // Caveat: preserve STR:RC. break; case BC_TGETB: | ins_ABC // RA = dst, RB = table, RC = byte literal | mov TAB:RB, [BASE+RB*8] | checktab TAB:RB, ->vmeta_tgetb | cmp RCd, TAB:RB->asize | jae ->vmeta_tgetb | shl RCd, 3 | add RC, TAB:RB->array | // Get array slot. | mov ITYPE, [RC] | cmp ITYPE, LJ_TNIL | je >2 |1: | mov [BASE+RA*8], ITYPE | ins_next | |2: // Check for __index if table value is nil. | mov TAB:TMPR, TAB:RB->metatable | test TAB:TMPR, TAB:TMPR | jz <1 | test byte TAB:TMPR->nomm, 1<<MM_index | jz ->vmeta_tgetb // 'no __index' flag NOT set: check. | jmp <1 break; case BC_TGETR: | ins_ABC // RA = dst, RB = table, RC = key | mov TAB:RB, [BASE+RB*8] | cleartp TAB:RB |.if DUALNUM | mov RCd, dword [BASE+RC*8] |.else | cvttsd2si RCd, qword [BASE+RC*8] |.endif | cmp RCd, TAB:RB->asize | jae ->vmeta_tgetr // Not in array part? Use fallback. | shl RCd, 3 | add RC, TAB:RB->array | // Get array slot. |->BC_TGETR_Z: | mov ITYPE, [RC] |->BC_TGETR2_Z: | mov [BASE+RA*8], ITYPE | ins_next break; case BC_TSETV: | ins_ABC // RA = src, RB = table, RC = key | mov TAB:RB, [BASE+RB*8] | mov RC, [BASE+RC*8] | checktab TAB:RB, ->vmeta_tsetv | | // Integer key? |.if DUALNUM | checkint RC, >5 |.else | // Convert number to int and back and compare. | checknum RC, >5 | movd xmm0, RC | cvttsd2si RCd, xmm0 | cvtsi2sd xmm1, RCd | ucomisd xmm0, xmm1 | jne ->vmeta_tsetv // Generic numeric key? Use fallback. |.endif | cmp RCd, TAB:RB->asize // Takes care of unordered, too. | jae ->vmeta_tsetv | shl RCd, 3 | add RC, TAB:RB->array | cmp aword [RC], LJ_TNIL | je >3 // Previous value is nil? |1: | test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table) | jnz >7 |2: // Set array slot. | mov RB, [BASE+RA*8] | mov [RC], RB | ins_next | |3: // Check for __newindex if previous value is nil. | mov TAB:TMPR, TAB:RB->metatable | test TAB:TMPR, TAB:TMPR | jz <1 | test byte TAB:TMPR->nomm, 1<<MM_newindex | jz ->vmeta_tsetv // 'no __newindex' flag NOT set: check. | jmp <1 | |5: // String key? | cmp ITYPEd, LJ_TSTR; jne ->vmeta_tsetv | cleartp STR:RC | jmp ->BC_TSETS_Z | |7: // Possible table write barrier for the value. Skip valiswhite check. | barrierback TAB:RB, TMPR | jmp <2 break; case BC_TSETS: | ins_ABC // RA = src, RB = table, RC = str const (~) | mov TAB:RB, [BASE+RB*8] | not RC | mov STR:RC, [KBASE+RC*8] | checktab TAB:RB, ->vmeta_tsets |->BC_TSETS_Z: // RB = GCtab *, RC = GCstr * | mov TMPRd, TAB:RB->hmask | and TMPRd, STR:RC->hash | imul TMPRd, #NODE | mov byte TAB:RB->nomm, 0 // Clear metamethod cache. | add NODE:TMPR, TAB:RB->node | settp ITYPE, STR:RC, LJ_TSTR |1: | cmp NODE:TMPR->key, ITYPE | jne >5 | // Ok, key found. Assumes: offsetof(Node, val) == 0 | cmp aword [TMPR], LJ_TNIL | je >4 // Previous value is nil? |2: | test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table) | jnz >7 |3: // Set node value. | mov ITYPE, [BASE+RA*8] | mov [TMPR], ITYPE | ins_next | |4: // Check for __newindex if previous value is nil. | mov TAB:ITYPE, TAB:RB->metatable | test TAB:ITYPE, TAB:ITYPE | jz <2 | test byte TAB:ITYPE->nomm, 1<<MM_newindex | jz ->vmeta_tsets // 'no __newindex' flag NOT set: check. | jmp <2 | |5: // Follow hash chain. | mov NODE:TMPR, NODE:TMPR->next | test NODE:TMPR, NODE:TMPR | jnz <1 | // End of hash chain: key not found, add a new one. | | // But check for __newindex first. | mov TAB:TMPR, TAB:RB->metatable | test TAB:TMPR, TAB:TMPR | jz >6 // No metatable: continue. | test byte TAB:TMPR->nomm, 1<<MM_newindex | jz ->vmeta_tsets // 'no __newindex' flag NOT set: check. |6: | mov TMP1, ITYPE | mov L:CARG1, SAVE_L | mov L:CARG1->base, BASE | lea CARG3, TMP1 | mov CARG2, TAB:RB | mov SAVE_PC, PC | call extern lj_tab_newkey // (lua_State *L, GCtab *t, TValue *k) | // Handles write barrier for the new key. TValue * returned in eax (RC). | mov L:CARG1, SAVE_L | mov BASE, L:CARG1->base | mov TMPR, rax | movzx RAd, PC_RA | jmp <2 // Must check write barrier for value. | |7: // Possible table write barrier for the value. Skip valiswhite check. | barrierback TAB:RB, ITYPE | jmp <3 break; case BC_TSETB: | ins_ABC // RA = src, RB = table, RC = byte literal | mov TAB:RB, [BASE+RB*8] | checktab TAB:RB, ->vmeta_tsetb | cmp RCd, TAB:RB->asize | jae ->vmeta_tsetb | shl RCd, 3 | add RC, TAB:RB->array | cmp aword [RC], LJ_TNIL | je >3 // Previous value is nil? |1: | test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table) | jnz >7 |2: // Set array slot. | mov ITYPE, [BASE+RA*8] | mov [RC], ITYPE | ins_next | |3: // Check for __newindex if previous value is nil. | mov TAB:TMPR, TAB:RB->metatable | test TAB:TMPR, TAB:TMPR | jz <1 | test byte TAB:TMPR->nomm, 1<<MM_newindex | jz ->vmeta_tsetb // 'no __newindex' flag NOT set: check. | jmp <1 | |7: // Possible table write barrier for the value. Skip valiswhite check. | barrierback TAB:RB, TMPR | jmp <2 break; case BC_TSETR: | ins_ABC // RA = src, RB = table, RC = key | mov TAB:RB, [BASE+RB*8] | cleartp TAB:RB |.if DUALNUM | mov RC, [BASE+RC*8] |.else | cvttsd2si RCd, qword [BASE+RC*8] |.endif | test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table) | jnz >7 |2: | cmp RCd, TAB:RB->asize | jae ->vmeta_tsetr | shl RCd, 3 | add RC, TAB:RB->array | // Set array slot. |->BC_TSETR_Z: | mov ITYPE, [BASE+RA*8] | mov [RC], ITYPE | ins_next | |7: // Possible table write barrier for the value. Skip valiswhite check. | barrierback TAB:RB, TMPR | jmp <2 break; case BC_TSETM: | ins_AD // RA = base (table at base-1), RD = num const (start index) |1: | mov TMPRd, dword [KBASE+RD*8] // Integer constant is in lo-word. | lea RA, [BASE+RA*8] | mov TAB:RB, [RA-8] // Guaranteed to be a table. | cleartp TAB:RB | test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table) | jnz >7 |2: | mov RDd, MULTRES | sub RDd, 1 | jz >4 // Nothing to copy? | add RDd, TMPRd // Compute needed size. | cmp RDd, TAB:RB->asize | ja >5 // Doesn't fit into array part? | sub RDd, TMPRd | shl TMPRd, 3 | add TMPR, TAB:RB->array |3: // Copy result slots to table. | mov RB, [RA] | add RA, 8 | mov [TMPR], RB | add TMPR, 8 | sub RDd, 1 | jnz <3 |4: | ins_next | |5: // Need to resize array part. | mov L:CARG1, SAVE_L | mov L:CARG1->base, BASE // Caveat: CARG2/CARG3 may be BASE. | mov CARG2, TAB:RB | mov CARG3d, RDd | mov L:RB, L:CARG1 | mov SAVE_PC, PC | call extern lj_tab_reasize // (lua_State *L, GCtab *t, int nasize) | mov BASE, L:RB->base | movzx RAd, PC_RA // Restore RA. | movzx RDd, PC_RD // Restore RD. | jmp <1 // Retry. | |7: // Possible table write barrier for any value. Skip valiswhite check. | barrierback TAB:RB, RD | jmp <2 break; /* -- Calls and vararg handling ----------------------------------------- */ case BC_CALL: case BC_CALLM: | ins_A_C // RA = base, (RB = nresults+1,) RC = nargs+1 | extra_nargs if (op == BC_CALLM) { | add NARGS:RDd, MULTRES } | mov LFUNC:RB, [BASE+RA*8] | checkfunc LFUNC:RB, ->vmeta_call_ra | lea BASE, [BASE+RA*8+16] | ins_call break; case BC_CALLMT: | ins_AD // RA = base, RD = extra_nargs | add NARGS:RDd, MULTRES | // Fall through. Assumes BC_CALLT follows and ins_AD is a no-op. break; case BC_CALLT: | ins_AD // RA = base, RD = nargs+1 | lea RA, [BASE+RA*8+16] | mov KBASE, BASE // Use KBASE for move + vmeta_call hint. | mov LFUNC:RB, [RA-16] | checktp_nc LFUNC:RB, LJ_TFUNC, ->vmeta_call |->BC_CALLT_Z: | mov PC, [BASE-8] | test PCd, FRAME_TYPE | jnz >7 |1: | mov [BASE-16], LFUNC:RB // Copy func+tag down, reloaded below. | mov MULTRES, NARGS:RDd | sub NARGS:RDd, 1 | jz >3 |2: // Move args down. | mov RB, [RA] | add RA, 8 | mov [KBASE], RB | add KBASE, 8 | sub NARGS:RDd, 1 | jnz <2 | | mov LFUNC:RB, [BASE-16] |3: | cleartp LFUNC:RB | mov NARGS:RDd, MULTRES | cmp byte LFUNC:RB->ffid, 1 // (> FF_C) Calling a fast function? | ja >5 |4: | ins_callt | |5: // Tailcall to a fast function. | test PCd, FRAME_TYPE // Lua frame below? | jnz <4 | movzx RAd, PC_RA | neg RA | mov LFUNC:KBASE, [BASE+RA*8-32] // Need to prepare KBASE. | cleartp LFUNC:KBASE | mov KBASE, LFUNC:KBASE->pc | mov KBASE, [KBASE+PC2PROTO(k)] | jmp <4 | |7: // Tailcall from a vararg function. | sub PC, FRAME_VARG | test PCd, FRAME_TYPEP | jnz >8 // Vararg frame below? | sub BASE, PC // Need to relocate BASE/KBASE down. | mov KBASE, BASE | mov PC, [BASE-8] | jmp <1 |8: | add PCd, FRAME_VARG | jmp <1 break; case BC_ITERC: | ins_A // RA = base, (RB = nresults+1,) RC = nargs+1 (2+1) | lea RA, [BASE+RA*8+16] // fb = base+2 | mov RB, [RA-32] // Copy state. fb[0] = fb[-4]. | mov RC, [RA-24] // Copy control var. fb[1] = fb[-3]. | mov [RA], RB | mov [RA+8], RC | mov LFUNC:RB, [RA-40] // Copy callable. fb[-1] = fb[-5] | mov [RA-16], LFUNC:RB | mov NARGS:RDd, 2+1 // Handle like a regular 2-arg call. | checkfunc LFUNC:RB, ->vmeta_call | mov BASE, RA | ins_call break; case BC_ITERN: | ins_A // RA = base, (RB = nresults+1, RC = nargs+1 (2+1)) |.if JIT | // NYI: add hotloop, record BC_ITERN. |.endif | mov TAB:RB, [BASE+RA*8-16] | cleartp TAB:RB | mov RCd, [BASE+RA*8-8] // Get index from control var. | mov TMPRd, TAB:RB->asize | add PC, 4 | mov ITYPE, TAB:RB->array |1: // Traverse array part. | cmp RCd, TMPRd; jae >5 // Index points after array part? | cmp aword [ITYPE+RC*8], LJ_TNIL; je >4 |.if not DUALNUM | cvtsi2sd xmm0, RCd |.endif | // Copy array slot to returned value. | mov RB, [ITYPE+RC*8] | mov [BASE+RA*8+8], RB | // Return array index as a numeric key. |.if DUALNUM | setint ITYPE, RC | mov [BASE+RA*8], ITYPE |.else | movsd qword [BASE+RA*8], xmm0 |.endif | add RCd, 1 | mov [BASE+RA*8-8], RCd // Update control var. |2: | movzx RDd, PC_RD // Get target from ITERL. | branchPC RD |3: | ins_next | |4: // Skip holes in array part. | add RCd, 1 | jmp <1 | |5: // Traverse hash part. | sub RCd, TMPRd |6: | cmp RCd, TAB:RB->hmask; ja <3 // End of iteration? Branch to ITERL+1. | imul ITYPEd, RCd, #NODE | add NODE:ITYPE, TAB:RB->node | cmp aword NODE:ITYPE->val, LJ_TNIL; je >7 | lea TMPRd, [RCd+TMPRd+1] | // Copy key and value from hash slot. | mov RB, NODE:ITYPE->key | mov RC, NODE:ITYPE->val | mov [BASE+RA*8], RB | mov [BASE+RA*8+8], RC | mov [BASE+RA*8-8], TMPRd | jmp <2 | |7: // Skip holes in hash part. | add RCd, 1 | jmp <6 break; case BC_ISNEXT: | ins_AD // RA = base, RD = target (points to ITERN) | mov CFUNC:RB, [BASE+RA*8-24] | checkfunc CFUNC:RB, >5 | checktptp [BASE+RA*8-16], LJ_TTAB, >5 | cmp aword [BASE+RA*8-8], LJ_TNIL; jne >5 | cmp byte CFUNC:RB->ffid, FF_next_N; jne >5 | branchPC RD | mov64 TMPR, U64x(fffe7fff, 00000000) | mov [BASE+RA*8-8], TMPR // Initialize control var. |1: | ins_next |5: // Despecialize bytecode if any of the checks fail. | mov PC_OP, BC_JMP | branchPC RD | mov byte [PC], BC_ITERC | jmp <1 break; case BC_VARG: | ins_ABC // RA = base, RB = nresults+1, RC = numparams | lea TMPR, [BASE+RC*8+(16+FRAME_VARG)] | lea RA, [BASE+RA*8] | sub TMPR, [BASE-8] | // Note: TMPR may now be even _above_ BASE if nargs was < numparams. | test RB, RB | jz >5 // Copy all varargs? | lea RB, [RA+RB*8-8] | cmp TMPR, BASE // No vararg slots? | jnb >2 |1: // Copy vararg slots to destination slots. | mov RC, [TMPR-16] | add TMPR, 8 | mov [RA], RC | add RA, 8 | cmp RA, RB // All destination slots filled? | jnb >3 | cmp TMPR, BASE // No more vararg slots? | jb <1 |2: // Fill up remainder with nil. | mov aword [RA], LJ_TNIL | add RA, 8 | cmp RA, RB | jb <2 |3: | ins_next | |5: // Copy all varargs. | mov MULTRES, 1 // MULTRES = 0+1 | mov RC, BASE | sub RC, TMPR | jbe <3 // No vararg slots? | mov RBd, RCd | shr RBd, 3 | add RBd, 1 | mov MULTRES, RBd // MULTRES = #varargs+1 | mov L:RB, SAVE_L | add RC, RA | cmp RC, L:RB->maxstack | ja >7 // Need to grow stack? |6: // Copy all vararg slots. | mov RC, [TMPR-16] | add TMPR, 8 | mov [RA], RC | add RA, 8 | cmp TMPR, BASE // No more vararg slots? | jb <6 | jmp <3 | |7: // Grow stack for varargs. | mov L:RB->base, BASE | mov L:RB->top, RA | mov SAVE_PC, PC | sub TMPR, BASE // Need delta, because BASE may change. | mov TMP1hi, TMPRd | mov CARG2d, MULTRES | sub CARG2d, 1 | mov CARG1, L:RB | call extern lj_state_growstack // (lua_State *L, int n) | mov BASE, L:RB->base | movsxd TMPR, TMP1hi | mov RA, L:RB->top | add TMPR, BASE | jmp <6 break; /* -- Returns ----------------------------------------------------------- */ case BC_RETM: | ins_AD // RA = results, RD = extra_nresults | add RDd, MULTRES // MULTRES >=1, so RD >=1. | // Fall through. Assumes BC_RET follows and ins_AD is a no-op. break; case BC_RET: case BC_RET0: case BC_RET1: | ins_AD // RA = results, RD = nresults+1 if (op != BC_RET0) { | shl RAd, 3 } |1: | mov PC, [BASE-8] | mov MULTRES, RDd // Save nresults+1. | test PCd, FRAME_TYPE // Check frame type marker. | jnz >7 // Not returning to a fixarg Lua func? switch (op) { case BC_RET: |->BC_RET_Z: | mov KBASE, BASE // Use KBASE for result move. | sub RDd, 1 | jz >3 |2: // Move results down. | mov RB, [KBASE+RA] | mov [KBASE-16], RB | add KBASE, 8 | sub RDd, 1 | jnz <2 |3: | mov RDd, MULTRES // Note: MULTRES may be >255. | movzx RBd, PC_RB // So cannot compare with RDL! |5: | cmp RBd, RDd // More results expected? | ja >6 break; case BC_RET1: | mov RB, [BASE+RA] | mov [BASE-16], RB /* fallthrough */ case BC_RET0: |5: | cmp PC_RB, RDL // More results expected? | ja >6 default: break; } | movzx RAd, PC_RA | neg RA | lea BASE, [BASE+RA*8-16] // base = base - (RA+2)*8 | mov LFUNC:KBASE, [BASE-16] | cleartp LFUNC:KBASE | mov KBASE, LFUNC:KBASE->pc | mov KBASE, [KBASE+PC2PROTO(k)] | ins_next | |6: // Fill up results with nil. if (op == BC_RET) { | mov aword [KBASE-16], LJ_TNIL // Note: relies on shifted base. | add KBASE, 8 } else { | mov aword [BASE+RD*8-24], LJ_TNIL } | add RD, 1 | jmp <5 | |7: // Non-standard return case. | lea RB, [PC-FRAME_VARG] | test RBd, FRAME_TYPEP | jnz ->vm_return | // Return from vararg function: relocate BASE down and RA up. | sub BASE, RB if (op != BC_RET0) { | add RA, RB } | jmp <1 break; /* -- Loops and branches ------------------------------------------------ */ |.define FOR_IDX, [RA] |.define FOR_STOP, [RA+8] |.define FOR_STEP, [RA+16] |.define FOR_EXT, [RA+24] case BC_FORL: |.if JIT | hotloop RBd |.endif | // Fall through. Assumes BC_IFORL follows and ins_AJ is a no-op. break; case BC_JFORI: case BC_JFORL: #if !LJ_HASJIT break; #endif case BC_FORI: case BC_IFORL: vk = (op == BC_IFORL || op == BC_JFORL); | ins_AJ // RA = base, RD = target (after end of loop or start of loop) | lea RA, [BASE+RA*8] if (LJ_DUALNUM) { | mov RB, FOR_IDX | checkint RB, >9 | mov TMPR, FOR_STOP if (!vk) { | checkint TMPR, ->vmeta_for | mov ITYPE, FOR_STEP | test ITYPEd, ITYPEd; js >5 | sar ITYPE, 47; | cmp ITYPEd, LJ_TISNUM; jne ->vmeta_for } else { #ifdef LUA_USE_ASSERT | checkinttp FOR_STOP, ->assert_bad_for_arg_type | checkinttp FOR_STEP, ->assert_bad_for_arg_type #endif | mov ITYPE, FOR_STEP | test ITYPEd, ITYPEd; js >5 | add RBd, ITYPEd; jo >1 | setint RB | mov FOR_IDX, RB } | cmp RBd, TMPRd | mov FOR_EXT, RB if (op == BC_FORI) { | jle >7 |1: |6: | branchPC RD } else if (op == BC_JFORI) { | branchPC RD | movzx RDd, PC_RD | jle =>BC_JLOOP |1: |6: } else if (op == BC_IFORL) { | jg >7 |6: | branchPC RD |1: } else { | jle =>BC_JLOOP |1: |6: } |7: | ins_next | |5: // Invert check for negative step. if (!vk) { | sar ITYPE, 47; | cmp ITYPEd, LJ_TISNUM; jne ->vmeta_for } else { | add RBd, ITYPEd; jo <1 | setint RB | mov FOR_IDX, RB } | cmp RBd, TMPRd | mov FOR_EXT, RB if (op == BC_FORI) { | jge <7 } else if (op == BC_JFORI) { | branchPC RD | movzx RDd, PC_RD | jge =>BC_JLOOP } else if (op == BC_IFORL) { | jl <7 } else { | jge =>BC_JLOOP } | jmp <6 |9: // Fallback to FP variant. if (!vk) { | jae ->vmeta_for } } else if (!vk) { | checknumtp FOR_IDX, ->vmeta_for } if (!vk) { | checknumtp FOR_STOP, ->vmeta_for } else { #ifdef LUA_USE_ASSERT | checknumtp FOR_STOP, ->assert_bad_for_arg_type | checknumtp FOR_STEP, ->assert_bad_for_arg_type #endif } | mov RB, FOR_STEP if (!vk) { | checknum RB, ->vmeta_for } | movsd xmm0, qword FOR_IDX | movsd xmm1, qword FOR_STOP if (vk) { | addsd xmm0, qword FOR_STEP | movsd qword FOR_IDX, xmm0 | test RB, RB; js >3 } else { | jl >3 } | ucomisd xmm1, xmm0 |1: | movsd qword FOR_EXT, xmm0 if (op == BC_FORI) { |.if DUALNUM | jnb <7 |.else | jnb >2 | branchPC RD |.endif } else if (op == BC_JFORI) { | branchPC RD | movzx RDd, PC_RD | jnb =>BC_JLOOP } else if (op == BC_IFORL) { |.if DUALNUM | jb <7 |.else | jb >2 | branchPC RD |.endif } else { | jnb =>BC_JLOOP } |.if DUALNUM | jmp <6 |.else |2: | ins_next |.endif | |3: // Invert comparison if step is negative. | ucomisd xmm0, xmm1 | jmp <1 break; case BC_ITERL: |.if JIT | hotloop RBd |.endif | // Fall through. Assumes BC_IITERL follows and ins_AJ is a no-op. break; case BC_JITERL: #if !LJ_HASJIT break; #endif case BC_IITERL: | ins_AJ // RA = base, RD = target | lea RA, [BASE+RA*8] | mov RB, [RA] | cmp RB, LJ_TNIL; je >1 // Stop if iterator returned nil. if (op == BC_JITERL) { | mov [RA-8], RB | jmp =>BC_JLOOP } else { | branchPC RD // Otherwise save control var + branch. | mov [RA-8], RB } |1: | ins_next break; case BC_LOOP: | ins_A // RA = base, RD = target (loop extent) | // Note: RA/RD is only used by trace recorder to determine scope/extent | // This opcode does NOT jump, it's only purpose is to detect a hot loop. |.if JIT | hotloop RBd |.endif | // Fall through. Assumes BC_ILOOP follows and ins_A is a no-op. break; case BC_ILOOP: | ins_A // RA = base, RD = target (loop extent) | ins_next break; case BC_JLOOP: |.if JIT | ins_AD // RA = base (ignored), RD = traceno | mov RA, [DISPATCH+DISPATCH_J(trace)] | mov TRACE:RD, [RA+RD*8] | mov RD, TRACE:RD->mcode | mov L:RB, SAVE_L | mov [DISPATCH+DISPATCH_GL(jit_base)], BASE | mov [DISPATCH+DISPATCH_GL(tmpbuf.L)], L:RB | // Save additional callee-save registers only used in compiled code. |.if X64WIN | mov CSAVE_4, r12 | mov CSAVE_3, r13 | mov CSAVE_2, r14 | mov CSAVE_1, r15 | mov RA, rsp | sub rsp, 10*16+4*8 | movdqa [RA-1*16], xmm6 | movdqa [RA-2*16], xmm7 | movdqa [RA-3*16], xmm8 | movdqa [RA-4*16], xmm9 | movdqa [RA-5*16], xmm10 | movdqa [RA-6*16], xmm11 | movdqa [RA-7*16], xmm12 | movdqa [RA-8*16], xmm13 | movdqa [RA-9*16], xmm14 | movdqa [RA-10*16], xmm15 |.else | sub rsp, 16 | mov [rsp+16], r12 | mov [rsp+8], r13 |.endif | jmp RD |.endif break; case BC_JMP: | ins_AJ // RA = unused, RD = target | branchPC RD | ins_next break; /* -- Function headers -------------------------------------------------- */ /* ** Reminder: A function may be called with func/args above L->maxstack, ** i.e. occupying EXTRA_STACK slots. And vmeta_call may add one extra slot, ** too. This means all FUNC* ops (including fast functions) must check ** for stack overflow _before_ adding more slots! */ case BC_FUNCF: |.if JIT | hotcall RBd |.endif case BC_FUNCV: /* NYI: compiled vararg functions. */ | // Fall through. Assumes BC_IFUNCF/BC_IFUNCV follow and ins_AD is a no-op. break; case BC_JFUNCF: #if !LJ_HASJIT break; #endif case BC_IFUNCF: | ins_AD // BASE = new base, RA = framesize, RD = nargs+1 | mov KBASE, [PC-4+PC2PROTO(k)] | mov L:RB, SAVE_L | lea RA, [BASE+RA*8] // Top of frame. | cmp RA, L:RB->maxstack | ja ->vm_growstack_f | movzx RAd, byte [PC-4+PC2PROTO(numparams)] | cmp NARGS:RDd, RAd // Check for missing parameters. | jbe >3 |2: if (op == BC_JFUNCF) { | movzx RDd, PC_RD | jmp =>BC_JLOOP } else { | ins_next } | |3: // Clear missing parameters. | mov aword [BASE+NARGS:RD*8-8], LJ_TNIL | add NARGS:RDd, 1 | cmp NARGS:RDd, RAd | jbe <3 | jmp <2 break; case BC_JFUNCV: #if !LJ_HASJIT break; #endif | int3 // NYI: compiled vararg functions break; /* NYI: compiled vararg functions. */ case BC_IFUNCV: | ins_AD // BASE = new base, RA = framesize, RD = nargs+1 | lea RBd, [NARGS:RD*8+FRAME_VARG+8] | lea RD, [BASE+NARGS:RD*8+8] | mov LFUNC:KBASE, [BASE-16] | mov [RD-8], RB // Store delta + FRAME_VARG. | mov [RD-16], LFUNC:KBASE // Store copy of LFUNC. | mov L:RB, SAVE_L | lea RA, [RD+RA*8] | cmp RA, L:RB->maxstack | ja ->vm_growstack_v // Need to grow stack. | mov RA, BASE | mov BASE, RD | movzx RBd, byte [PC-4+PC2PROTO(numparams)] | test RBd, RBd | jz >2 | add RA, 8 |1: // Copy fixarg slots up to new frame. | add RA, 8 | cmp RA, BASE | jnb >3 // Less args than parameters? | mov KBASE, [RA-16] | mov [RD], KBASE | add RD, 8 | mov aword [RA-16], LJ_TNIL // Clear old fixarg slot (help the GC). | sub RBd, 1 | jnz <1 |2: if (op == BC_JFUNCV) { | movzx RDd, PC_RD | jmp =>BC_JLOOP } else { | mov KBASE, [PC-4+PC2PROTO(k)] | ins_next } | |3: // Clear missing parameters. | mov aword [RD], LJ_TNIL | add RD, 8 | sub RBd, 1 | jnz <3 | jmp <2 break; case BC_FUNCC: case BC_FUNCCW: | ins_AD // BASE = new base, RA = ins RA|RD (unused), RD = nargs+1 | mov CFUNC:RB, [BASE-16] | cleartp CFUNC:RB | mov KBASE, CFUNC:RB->f | mov L:RB, SAVE_L | lea RD, [BASE+NARGS:RD*8-8] | mov L:RB->base, BASE | lea RA, [RD+8*LUA_MINSTACK] | cmp RA, L:RB->maxstack | mov L:RB->top, RD if (op == BC_FUNCC) { | mov CARG1, L:RB // Caveat: CARG1 may be RA. } else { | mov CARG2, KBASE | mov CARG1, L:RB // Caveat: CARG1 may be RA. } | ja ->vm_growstack_c // Need to grow stack. | set_vmstate C if (op == BC_FUNCC) { | call KBASE // (lua_State *L) } else { | // (lua_State *L, lua_CFunction f) | call aword [DISPATCH+DISPATCH_GL(wrapf)] } | // nresults returned in eax (RD). | mov BASE, L:RB->base | mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB | set_vmstate INTERP | lea RA, [BASE+RD*8] | neg RA | add RA, L:RB->top // RA = (L->top-(L->base+nresults))*8 | mov PC, [BASE-8] // Fetch PC of caller. | jmp ->vm_returnc break; /* ---------------------------------------------------------------------- */ default: fprintf(stderr, "Error: undefined opcode BC_%s\n", bc_names[op]); exit(2); break; } } static int build_backend(BuildCtx *ctx) { int op; dasm_growpc(Dst, BC__MAX); build_subroutines(ctx); |.code_op for (op = 0; op < BC__MAX; op++) build_ins(ctx, (BCOp)op, op); return BC__MAX; } /* Emit pseudo frame-info for all assembler functions. */ static void emit_asm_debug(BuildCtx *ctx) { int fcofs = (int)((uint8_t *)ctx->glob[GLOB_vm_ffi_call] - ctx->code); switch (ctx->mode) { case BUILD_elfasm: fprintf(ctx->fp, "\t.section .debug_frame,\"\",@progbits\n"); fprintf(ctx->fp, ".Lframe0:\n" "\t.long .LECIE0-.LSCIE0\n" ".LSCIE0:\n" "\t.long 0xffffffff\n" "\t.byte 0x1\n" "\t.string \"\"\n" "\t.uleb128 0x1\n" "\t.sleb128 -8\n" "\t.byte 0x10\n" "\t.byte 0xc\n\t.uleb128 0x7\n\t.uleb128 8\n" "\t.byte 0x80+0x10\n\t.uleb128 0x1\n" "\t.align 8\n" ".LECIE0:\n\n"); fprintf(ctx->fp, ".LSFDE0:\n" "\t.long .LEFDE0-.LASFDE0\n" ".LASFDE0:\n" "\t.long .Lframe0\n" "\t.quad .Lbegin\n" "\t.quad %d\n" "\t.byte 0xe\n\t.uleb128 %d\n" /* def_cfa_offset */ "\t.byte 0x86\n\t.uleb128 0x2\n" /* offset rbp */ "\t.byte 0x83\n\t.uleb128 0x3\n" /* offset rbx */ "\t.byte 0x8f\n\t.uleb128 0x4\n" /* offset r15 */ "\t.byte 0x8e\n\t.uleb128 0x5\n" /* offset r14 */ #if LJ_NO_UNWIND "\t.byte 0x8d\n\t.uleb128 0x6\n" /* offset r13 */ "\t.byte 0x8c\n\t.uleb128 0x7\n" /* offset r12 */ #endif "\t.align 8\n" ".LEFDE0:\n\n", fcofs, CFRAME_SIZE); #if LJ_HASFFI fprintf(ctx->fp, ".LSFDE1:\n" "\t.long .LEFDE1-.LASFDE1\n" ".LASFDE1:\n" "\t.long .Lframe0\n" "\t.quad lj_vm_ffi_call\n" "\t.quad %d\n" "\t.byte 0xe\n\t.uleb128 16\n" /* def_cfa_offset */ "\t.byte 0x86\n\t.uleb128 0x2\n" /* offset rbp */ "\t.byte 0xd\n\t.uleb128 0x6\n" /* def_cfa_register rbp */ "\t.byte 0x83\n\t.uleb128 0x3\n" /* offset rbx */ "\t.align 8\n" ".LEFDE1:\n\n", (int)ctx->codesz - fcofs); #endif #if !LJ_NO_UNWIND #if (defined(__sun__) && defined(__svr4__)) fprintf(ctx->fp, "\t.section .eh_frame,\"a\",@unwind\n"); #else fprintf(ctx->fp, "\t.section .eh_frame,\"a\",@progbits\n"); #endif fprintf(ctx->fp, ".Lframe1:\n" "\t.long .LECIE1-.LSCIE1\n" ".LSCIE1:\n" "\t.long 0\n" "\t.byte 0x1\n" "\t.string \"zPR\"\n" "\t.uleb128 0x1\n" "\t.sleb128 -8\n" "\t.byte 0x10\n" "\t.uleb128 6\n" /* augmentation length */ "\t.byte 0x1b\n" /* pcrel|sdata4 */ "\t.long lj_err_unwind_dwarf-.\n" "\t.byte 0x1b\n" /* pcrel|sdata4 */ "\t.byte 0xc\n\t.uleb128 0x7\n\t.uleb128 8\n" "\t.byte 0x80+0x10\n\t.uleb128 0x1\n" "\t.align 8\n" ".LECIE1:\n\n"); fprintf(ctx->fp, ".LSFDE2:\n" "\t.long .LEFDE2-.LASFDE2\n" ".LASFDE2:\n" "\t.long .LASFDE2-.Lframe1\n" "\t.long .Lbegin-.\n" "\t.long %d\n" "\t.uleb128 0\n" /* augmentation length */ "\t.byte 0xe\n\t.uleb128 %d\n" /* def_cfa_offset */ "\t.byte 0x86\n\t.uleb128 0x2\n" /* offset rbp */ "\t.byte 0x83\n\t.uleb128 0x3\n" /* offset rbx */ "\t.byte 0x8f\n\t.uleb128 0x4\n" /* offset r15 */ "\t.byte 0x8e\n\t.uleb128 0x5\n" /* offset r14 */ "\t.align 8\n" ".LEFDE2:\n\n", fcofs, CFRAME_SIZE); #if LJ_HASFFI fprintf(ctx->fp, ".Lframe2:\n" "\t.long .LECIE2-.LSCIE2\n" ".LSCIE2:\n" "\t.long 0\n" "\t.byte 0x1\n" "\t.string \"zR\"\n" "\t.uleb128 0x1\n" "\t.sleb128 -8\n" "\t.byte 0x10\n" "\t.uleb128 1\n" /* augmentation length */ "\t.byte 0x1b\n" /* pcrel|sdata4 */ "\t.byte 0xc\n\t.uleb128 0x7\n\t.uleb128 8\n" "\t.byte 0x80+0x10\n\t.uleb128 0x1\n" "\t.align 8\n" ".LECIE2:\n\n"); fprintf(ctx->fp, ".LSFDE3:\n" "\t.long .LEFDE3-.LASFDE3\n" ".LASFDE3:\n" "\t.long .LASFDE3-.Lframe2\n" "\t.long lj_vm_ffi_call-.\n" "\t.long %d\n" "\t.uleb128 0\n" /* augmentation length */ "\t.byte 0xe\n\t.uleb128 16\n" /* def_cfa_offset */ "\t.byte 0x86\n\t.uleb128 0x2\n" /* offset rbp */ "\t.byte 0xd\n\t.uleb128 0x6\n" /* def_cfa_register rbp */ "\t.byte 0x83\n\t.uleb128 0x3\n" /* offset rbx */ "\t.align 8\n" ".LEFDE3:\n\n", (int)ctx->codesz - fcofs); #endif #endif break; #if !LJ_NO_UNWIND /* Mental note: never let Apple design an assembler. ** Or a linker. Or a plastic case. But I digress. */ case BUILD_machasm: { #if LJ_HASFFI int fcsize = 0; #endif int i; fprintf(ctx->fp, "\t.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support\n"); fprintf(ctx->fp, "EH_frame1:\n" "\t.set L$set$x,LECIEX-LSCIEX\n" "\t.long L$set$x\n" "LSCIEX:\n" "\t.long 0\n" "\t.byte 0x1\n" "\t.ascii \"zPR\\0\"\n" "\t.byte 0x1\n" "\t.byte 128-8\n" "\t.byte 0x10\n" "\t.byte 6\n" /* augmentation length */ "\t.byte 0x9b\n" /* indirect|pcrel|sdata4 */ "\t.long _lj_err_unwind_dwarf+4@GOTPCREL\n" "\t.byte 0x1b\n" /* pcrel|sdata4 */ "\t.byte 0xc\n\t.byte 0x7\n\t.byte 8\n" "\t.byte 0x80+0x10\n\t.byte 0x1\n" "\t.align 3\n" "LECIEX:\n\n"); for (i = 0; i < ctx->nsym; i++) { const char *name = ctx->sym[i].name; int32_t size = ctx->sym[i+1].ofs - ctx->sym[i].ofs; if (size == 0) continue; #if LJ_HASFFI if (!strcmp(name, "_lj_vm_ffi_call")) { fcsize = size; continue; } #endif fprintf(ctx->fp, "%s.eh:\n" "LSFDE%d:\n" "\t.set L$set$%d,LEFDE%d-LASFDE%d\n" "\t.long L$set$%d\n" "LASFDE%d:\n" "\t.long LASFDE%d-EH_frame1\n" "\t.long %s-.\n" "\t.long %d\n" "\t.byte 0\n" /* augmentation length */ "\t.byte 0xe\n\t.byte %d\n" /* def_cfa_offset */ "\t.byte 0x86\n\t.byte 0x2\n" /* offset rbp */ "\t.byte 0x83\n\t.byte 0x3\n" /* offset rbx */ "\t.byte 0x8f\n\t.byte 0x4\n" /* offset r15 */ "\t.byte 0x8e\n\t.byte 0x5\n" /* offset r14 */ "\t.align 3\n" "LEFDE%d:\n\n", name, i, i, i, i, i, i, i, name, size, CFRAME_SIZE, i); } #if LJ_HASFFI if (fcsize) { fprintf(ctx->fp, "EH_frame2:\n" "\t.set L$set$y,LECIEY-LSCIEY\n" "\t.long L$set$y\n" "LSCIEY:\n" "\t.long 0\n" "\t.byte 0x1\n" "\t.ascii \"zR\\0\"\n" "\t.byte 0x1\n" "\t.byte 128-8\n" "\t.byte 0x10\n" "\t.byte 1\n" /* augmentation length */ "\t.byte 0x1b\n" /* pcrel|sdata4 */ "\t.byte 0xc\n\t.byte 0x7\n\t.byte 8\n" "\t.byte 0x80+0x10\n\t.byte 0x1\n" "\t.align 3\n" "LECIEY:\n\n"); fprintf(ctx->fp, "_lj_vm_ffi_call.eh:\n" "LSFDEY:\n" "\t.set L$set$yy,LEFDEY-LASFDEY\n" "\t.long L$set$yy\n" "LASFDEY:\n" "\t.long LASFDEY-EH_frame2\n" "\t.long _lj_vm_ffi_call-.\n" "\t.long %d\n" "\t.byte 0\n" /* augmentation length */ "\t.byte 0xe\n\t.byte 16\n" /* def_cfa_offset */ "\t.byte 0x86\n\t.byte 0x2\n" /* offset rbp */ "\t.byte 0xd\n\t.byte 0x6\n" /* def_cfa_register rbp */ "\t.byte 0x83\n\t.byte 0x3\n" /* offset rbx */ "\t.align 3\n" "LEFDEY:\n\n", fcsize); } #endif fprintf(ctx->fp, ".subsections_via_symbols\n"); } break; #endif default: /* Difficult for other modes. */ break; } }
xLua/build/luajit-2.1.0b2/src/vm_x64.dasc/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/vm_x64.dasc", "repo_id": "xLua", "token_count": 66241 }
2,111
<!DOCTYPE html> <html> <head> <title>FFI Semantics</title> <meta charset="utf-8"> <meta name="Copyright" content="Copyright (C) 2005-2021"> <meta name="Language" content="en"> <link rel="stylesheet" type="text/css" href="bluequad.css" media="screen"> <link rel="stylesheet" type="text/css" href="bluequad-print.css" media="print"> <style type="text/css"> table.convtable { line-height: 1.2; } tr.convhead td { font-weight: bold; } td.convop { font-style: italic; width: 40%; } </style> </head> <body> <div id="site"> <a href="https://luajit.org"><span>Lua<span id="logo">JIT</span></span></a> </div> <div id="head"> <h1>FFI Semantics</h1> </div> <div id="nav"> <ul><li> <a href="luajit.html">LuaJIT</a> <ul><li> <a href="https://luajit.org/download.html">Download <span class="ext">&raquo;</span></a> </li><li> <a href="install.html">Installation</a> </li><li> <a href="running.html">Running</a> </li></ul> </li><li> <a href="extensions.html">Extensions</a> <ul><li> <a href="ext_ffi.html">FFI Library</a> <ul><li> <a href="ext_ffi_tutorial.html">FFI Tutorial</a> </li><li> <a href="ext_ffi_api.html">ffi.* API</a> </li><li> <a class="current" href="ext_ffi_semantics.html">FFI Semantics</a> </li></ul> </li><li> <a href="ext_buffer.html">String Buffers</a> </li><li> <a href="ext_jit.html">jit.* Library</a> </li><li> <a href="ext_c_api.html">Lua/C API</a> </li><li> <a href="ext_profiler.html">Profiler</a> </li></ul> </li><li> <a href="status.html">Status</a> </li><li> <a href="faq.html">FAQ</a> </li><li> <a href="http://wiki.luajit.org/">Wiki <span class="ext">&raquo;</span></a> </li><li> <a href="https://luajit.org/list.html">Mailing List <span class="ext">&raquo;</span></a> </li></ul> </div> <div id="main"> <p> This page describes the detailed semantics underlying the FFI library and its interaction with both Lua and C&nbsp;code. </p> <p> Given that the FFI library is designed to interface with C&nbsp;code and that declarations can be written in plain C&nbsp;syntax, <b>it closely follows the C&nbsp;language semantics</b>, wherever possible. Some minor concessions are needed for smoother interoperation with Lua language semantics. </p> <p> Please don't be overwhelmed by the contents of this page &mdash; this is a reference and you may need to consult it, if in doubt. It doesn't hurt to skim this page, but most of the semantics "just work" as you'd expect them to work. It should be straightforward to write applications using the LuaJIT FFI for developers with a C or C++ background. </p> <h2 id="clang">C Language Support</h2> <p> The FFI library has a built-in C&nbsp;parser with a minimal memory footprint. It's used by the <a href="ext_ffi_api.html">ffi.* library functions</a> to declare C&nbsp;types or external symbols. </p> <p> It's only purpose is to parse C&nbsp;declarations, as found e.g. in C&nbsp;header files. Although it does evaluate constant expressions, it's <em>not</em> a C&nbsp;compiler. The body of <tt>inline</tt> C&nbsp;function definitions is simply ignored. </p> <p> Also, this is <em>not</em> a validating C&nbsp;parser. It expects and accepts correctly formed C&nbsp;declarations, but it may choose to ignore bad declarations or show rather generic error messages. If in doubt, please check the input against your favorite C&nbsp;compiler. </p> <p> The C&nbsp;parser complies to the <b>C99 language standard</b> plus the following extensions: </p> <ul> <li>The <tt>'\e'</tt> escape in character and string literals.</li> <li>The C99/C++ boolean type, declared with the keywords <tt>bool</tt> or <tt>_Bool</tt>.</li> <li>Complex numbers, declared with the keywords <tt>complex</tt> or <tt>_Complex</tt>.</li> <li>Two complex number types: <tt>complex</tt> (aka <tt>complex&nbsp;double</tt>) and <tt>complex&nbsp;float</tt>.</li> <li>Vector types, declared with the GCC <tt>mode</tt> or <tt>vector_size</tt> attribute.</li> <li>Unnamed ('transparent') <tt>struct</tt>/<tt>union</tt> fields inside a <tt>struct</tt>/<tt>union</tt>.</li> <li>Incomplete <tt>enum</tt> declarations, handled like incomplete <tt>struct</tt> declarations.</li> <li>Unnamed <tt>enum</tt> fields inside a <tt>struct</tt>/<tt>union</tt>. This is similar to a scoped C++ <tt>enum</tt>, except that declared constants are visible in the global namespace, too.</li> <li>Scoped <tt>static&nbsp;const</tt> declarations inside a <tt>struct</tt>/<tt>union</tt> (from C++).</li> <li>Zero-length arrays (<tt>[0]</tt>), empty <tt>struct</tt>/<tt>union</tt>, variable-length arrays (VLA, <tt>[?]</tt>) and variable-length structs (VLS, with a trailing VLA).</li> <li>C++ reference types (<tt>int&nbsp;&amp;x</tt>).</li> <li>Alternate GCC keywords with '<tt>__</tt>', e.g. <tt>__const__</tt>.</li> <li>GCC <tt>__attribute__</tt> with the following attributes: <tt>aligned</tt>, <tt>packed</tt>, <tt>mode</tt>, <tt>vector_size</tt>, <tt>cdecl</tt>, <tt>fastcall</tt>, <tt>stdcall</tt>, <tt>thiscall</tt>.</li> <li>The GCC <tt>__extension__</tt> keyword and the GCC <tt>__alignof__</tt> operator.</li> <li>GCC <tt>__asm__("symname")</tt> symbol name redirection for function declarations.</li> <li>MSVC keywords for fixed-length types: <tt>__int8</tt>, <tt>__int16</tt>, <tt>__int32</tt> and <tt>__int64</tt>.</li> <li>MSVC <tt>__cdecl</tt>, <tt>__fastcall</tt>, <tt>__stdcall</tt>, <tt>__thiscall</tt>, <tt>__ptr32</tt>, <tt>__ptr64</tt>, <tt>__declspec(align(n))</tt> and <tt>#pragma&nbsp;pack</tt>.</li> <li>All other GCC/MSVC-specific attributes are ignored.</li> </ul> <p> The following C&nbsp;types are pre-defined by the C&nbsp;parser (like a <tt>typedef</tt>, except re-declarations will be ignored): </p> <ul> <li>Vararg handling: <tt>va_list</tt>, <tt>__builtin_va_list</tt>, <tt>__gnuc_va_list</tt>.</li> <li>From <tt>&lt;stddef.h&gt;</tt>: <tt>ptrdiff_t</tt>, <tt>size_t</tt>, <tt>wchar_t</tt>.</li> <li>From <tt>&lt;stdint.h&gt;</tt>: <tt>int8_t</tt>, <tt>int16_t</tt>, <tt>int32_t</tt>, <tt>int64_t</tt>, <tt>uint8_t</tt>, <tt>uint16_t</tt>, <tt>uint32_t</tt>, <tt>uint64_t</tt>, <tt>intptr_t</tt>, <tt>uintptr_t</tt>.</li> <li>From <tt>&lt;unistd.h&gt;</tt> (POSIX): <tt>ssize_t</tt>.</li> </ul> <p> You're encouraged to use these types in preference to compiler-specific extensions or target-dependent standard types. E.g. <tt>char</tt> differs in signedness and <tt>long</tt> differs in size, depending on the target architecture and platform ABI. </p> <p> The following C&nbsp;features are <b>not</b> supported: </p> <ul> <li>A declaration must always have a type specifier; it doesn't default to an <tt>int</tt> type.</li> <li>Old-style empty function declarations (K&amp;R) are not allowed. All C&nbsp;functions must have a proper prototype declaration. A function declared without parameters (<tt>int&nbsp;foo();</tt>) is treated as a function taking zero arguments, like in C++.</li> <li>The <tt>long double</tt> C&nbsp;type is parsed correctly, but there's no support for the related conversions, accesses or arithmetic operations.</li> <li>Wide character strings and character literals are not supported.</li> <li><a href="#status">See below</a> for features that are currently not implemented.</li> </ul> <h2 id="convert">C Type Conversion Rules</h2> <h3 id="convert_tolua">Conversions from C&nbsp;types to Lua objects</h3> <p> These conversion rules apply for <em>read accesses</em> to C&nbsp;types: indexing pointers, arrays or <tt>struct</tt>/<tt>union</tt> types; reading external variables or constant values; retrieving return values from C&nbsp;calls: </p> <table class="convtable"> <tr class="convhead"> <td class="convin">Input</td> <td class="convop">Conversion</td> <td class="convout">Output</td> </tr> <tr class="odd separate"> <td class="convin"><tt>int8_t</tt>, <tt>int16_t</tt></td><td class="convop">&rarr;<sup>sign-ext</sup> <tt>int32_t</tt> &rarr; <tt>double</tt></td><td class="convout">number</td></tr> <tr class="even"> <td class="convin"><tt>uint8_t</tt>, <tt>uint16_t</tt></td><td class="convop">&rarr;<sup>zero-ext</sup> <tt>int32_t</tt> &rarr; <tt>double</tt></td><td class="convout">number</td></tr> <tr class="odd"> <td class="convin"><tt>int32_t</tt>, <tt>uint32_t</tt></td><td class="convop">&rarr; <tt>double</tt></td><td class="convout">number</td></tr> <tr class="even"> <td class="convin"><tt>int64_t</tt>, <tt>uint64_t</tt></td><td class="convop">boxed value</td><td class="convout">64 bit int cdata</td></tr> <tr class="odd separate"> <td class="convin"><tt>double</tt>, <tt>float</tt></td><td class="convop">&rarr; <tt>double</tt></td><td class="convout">number</td></tr> <tr class="even separate"> <td class="convin"><tt>bool</tt></td><td class="convop">0 &rarr; <tt>false</tt>, otherwise <tt>true</tt></td><td class="convout">boolean</td></tr> <tr class="odd separate"> <td class="convin"><tt>enum</tt></td><td class="convop">boxed value</td><td class="convout">enum cdata</td></tr> <tr class="even"> <td class="convin">Complex number</td><td class="convop">boxed value</td><td class="convout">complex cdata</td></tr> <tr class="odd"> <td class="convin">Vector</td><td class="convop">boxed value</td><td class="convout">vector cdata</td></tr> <tr class="even"> <td class="convin">Pointer</td><td class="convop">boxed value</td><td class="convout">pointer cdata</td></tr> <tr class="odd separate"> <td class="convin">Array</td><td class="convop">boxed reference</td><td class="convout">reference cdata</td></tr> <tr class="even"> <td class="convin"><tt>struct</tt>/<tt>union</tt></td><td class="convop">boxed reference</td><td class="convout">reference cdata</td></tr> </table> <p> Bitfields are treated like their underlying type. </p> <p> Reference types are dereferenced <em>before</em> a conversion can take place &mdash; the conversion is applied to the C&nbsp;type pointed to by the reference. </p> <h3 id="convert_fromlua">Conversions from Lua objects to C&nbsp;types</h3> <p> These conversion rules apply for <em>write accesses</em> to C&nbsp;types: indexing pointers, arrays or <tt>struct</tt>/<tt>union</tt> types; initializing cdata objects; casts to C&nbsp;types; writing to external variables; passing arguments to C&nbsp;calls: </p> <table class="convtable"> <tr class="convhead"> <td class="convin">Input</td> <td class="convop">Conversion</td> <td class="convout">Output</td> </tr> <tr class="odd separate"> <td class="convin">number</td><td class="convop">&rarr;</td><td class="convout"><tt>double</tt></td></tr> <tr class="even"> <td class="convin">boolean</td><td class="convop"><tt>false</tt> &rarr; 0, <tt>true</tt> &rarr; 1</td><td class="convout"><tt>bool</tt></td></tr> <tr class="odd separate"> <td class="convin">nil</td><td class="convop"><tt>NULL</tt> &rarr;</td><td class="convout"><tt>(void *)</tt></td></tr> <tr class="even"> <td class="convin">lightuserdata</td><td class="convop">lightuserdata address &rarr;</td><td class="convout"><tt>(void *)</tt></td></tr> <tr class="odd"> <td class="convin">userdata</td><td class="convop">userdata payload &rarr;</td><td class="convout"><tt>(void *)</tt></td></tr> <tr class="even"> <td class="convin">io.* file</td><td class="convop">get FILE * handle &rarr;</td><td class="convout"><tt>(void *)</tt></td></tr> <tr class="odd separate"> <td class="convin">string</td><td class="convop">match against <tt>enum</tt> constant</td><td class="convout"><tt>enum</tt></td></tr> <tr class="even"> <td class="convin">string</td><td class="convop">copy string data + zero-byte</td><td class="convout"><tt>int8_t[]</tt>, <tt>uint8_t[]</tt></td></tr> <tr class="odd"> <td class="convin">string</td><td class="convop">string data &rarr;</td><td class="convout"><tt>const char[]</tt></td></tr> <tr class="even separate"> <td class="convin">function</td><td class="convop"><a href="#callback">create callback</a> &rarr;</td><td class="convout">C function type</td></tr> <tr class="odd separate"> <td class="convin">table</td><td class="convop"><a href="#init_table">table initializer</a></td><td class="convout">Array</td></tr> <tr class="even"> <td class="convin">table</td><td class="convop"><a href="#init_table">table initializer</a></td><td class="convout"><tt>struct</tt>/<tt>union</tt></td></tr> <tr class="odd separate"> <td class="convin">cdata</td><td class="convop">cdata payload &rarr;</td><td class="convout">C type</td></tr> </table> <p> If the result type of this conversion doesn't match the C&nbsp;type of the destination, the <a href="#convert_between">conversion rules between C&nbsp;types</a> are applied. </p> <p> Reference types are immutable after initialization ("no re-seating of references"). For initialization purposes or when passing values to reference parameters, they are treated like pointers. Note that unlike in C++, there's no way to implement automatic reference generation of variables under the Lua language semantics. If you want to call a function with a reference parameter, you need to explicitly pass a one-element array. </p> <h3 id="convert_between">Conversions between C&nbsp;types</h3> <p> These conversion rules are more or less the same as the standard C&nbsp;conversion rules. Some rules only apply to casts, or require pointer or type compatibility: </p> <table class="convtable"> <tr class="convhead"> <td class="convin">Input</td> <td class="convop">Conversion</td> <td class="convout">Output</td> </tr> <tr class="odd separate"> <td class="convin">Signed integer</td><td class="convop">&rarr;<sup>narrow or sign-extend</sup></td><td class="convout">Integer</td></tr> <tr class="even"> <td class="convin">Unsigned integer</td><td class="convop">&rarr;<sup>narrow or zero-extend</sup></td><td class="convout">Integer</td></tr> <tr class="odd"> <td class="convin">Integer</td><td class="convop">&rarr;<sup>round</sup></td><td class="convout"><tt>double</tt>, <tt>float</tt></td></tr> <tr class="even"> <td class="convin"><tt>double</tt>, <tt>float</tt></td><td class="convop">&rarr;<sup>trunc</sup> <tt>int32_t</tt> &rarr;<sup>narrow</sup></td><td class="convout"><tt>(u)int8_t</tt>, <tt>(u)int16_t</tt></td></tr> <tr class="odd"> <td class="convin"><tt>double</tt>, <tt>float</tt></td><td class="convop">&rarr;<sup>trunc</sup></td><td class="convout"><tt>(u)int32_t</tt>, <tt>(u)int64_t</tt></td></tr> <tr class="even"> <td class="convin"><tt>double</tt>, <tt>float</tt></td><td class="convop">&rarr;<sup>round</sup></td><td class="convout"><tt>float</tt>, <tt>double</tt></td></tr> <tr class="odd separate"> <td class="convin">Number</td><td class="convop">n == 0 &rarr; 0, otherwise 1</td><td class="convout"><tt>bool</tt></td></tr> <tr class="even"> <td class="convin"><tt>bool</tt></td><td class="convop"><tt>false</tt> &rarr; 0, <tt>true</tt> &rarr; 1</td><td class="convout">Number</td></tr> <tr class="odd separate"> <td class="convin">Complex number</td><td class="convop">convert real part</td><td class="convout">Number</td></tr> <tr class="even"> <td class="convin">Number</td><td class="convop">convert real part, imag = 0</td><td class="convout">Complex number</td></tr> <tr class="odd"> <td class="convin">Complex number</td><td class="convop">convert real and imag part</td><td class="convout">Complex number</td></tr> <tr class="even separate"> <td class="convin">Number</td><td class="convop">convert scalar and replicate</td><td class="convout">Vector</td></tr> <tr class="odd"> <td class="convin">Vector</td><td class="convop">copy (same size)</td><td class="convout">Vector</td></tr> <tr class="even separate"> <td class="convin"><tt>struct</tt>/<tt>union</tt></td><td class="convop">take base address (compat)</td><td class="convout">Pointer</td></tr> <tr class="odd"> <td class="convin">Array</td><td class="convop">take base address (compat)</td><td class="convout">Pointer</td></tr> <tr class="even"> <td class="convin">Function</td><td class="convop">take function address</td><td class="convout">Function pointer</td></tr> <tr class="odd separate"> <td class="convin">Number</td><td class="convop">convert via <tt>uintptr_t</tt> (cast)</td><td class="convout">Pointer</td></tr> <tr class="even"> <td class="convin">Pointer</td><td class="convop">convert address (compat/cast)</td><td class="convout">Pointer</td></tr> <tr class="odd"> <td class="convin">Pointer</td><td class="convop">convert address (cast)</td><td class="convout">Integer</td></tr> <tr class="even"> <td class="convin">Array</td><td class="convop">convert base address (cast)</td><td class="convout">Integer</td></tr> <tr class="odd separate"> <td class="convin">Array</td><td class="convop">copy (compat)</td><td class="convout">Array</td></tr> <tr class="even"> <td class="convin"><tt>struct</tt>/<tt>union</tt></td><td class="convop">copy (identical type)</td><td class="convout"><tt>struct</tt>/<tt>union</tt></td></tr> </table> <p> Bitfields or <tt>enum</tt> types are treated like their underlying type. </p> <p> Conversions not listed above will raise an error. E.g. it's not possible to convert a pointer to a complex number or vice versa. </p> <h3 id="convert_vararg">Conversions for vararg C&nbsp;function arguments</h3> <p> The following default conversion rules apply when passing Lua objects to the variable argument part of vararg C&nbsp;functions: </p> <table class="convtable"> <tr class="convhead"> <td class="convin">Input</td> <td class="convop">Conversion</td> <td class="convout">Output</td> </tr> <tr class="odd separate"> <td class="convin">number</td><td class="convop">&rarr;</td><td class="convout"><tt>double</tt></td></tr> <tr class="even"> <td class="convin">boolean</td><td class="convop"><tt>false</tt> &rarr; 0, <tt>true</tt> &rarr; 1</td><td class="convout"><tt>bool</tt></td></tr> <tr class="odd separate"> <td class="convin">nil</td><td class="convop"><tt>NULL</tt> &rarr;</td><td class="convout"><tt>(void *)</tt></td></tr> <tr class="even"> <td class="convin">userdata</td><td class="convop">userdata payload &rarr;</td><td class="convout"><tt>(void *)</tt></td></tr> <tr class="odd"> <td class="convin">lightuserdata</td><td class="convop">lightuserdata address &rarr;</td><td class="convout"><tt>(void *)</tt></td></tr> <tr class="even separate"> <td class="convin">string</td><td class="convop">string data &rarr;</td><td class="convout"><tt>const char *</tt></td></tr> <tr class="odd separate"> <td class="convin"><tt>float</tt> cdata</td><td class="convop">&rarr;</td><td class="convout"><tt>double</tt></td></tr> <tr class="even"> <td class="convin">Array cdata</td><td class="convop">take base address</td><td class="convout">Element pointer</td></tr> <tr class="odd"> <td class="convin"><tt>struct</tt>/<tt>union</tt> cdata</td><td class="convop">take base address</td><td class="convout"><tt>struct</tt>/<tt>union</tt> pointer</td></tr> <tr class="even"> <td class="convin">Function cdata</td><td class="convop">take function address</td><td class="convout">Function pointer</td></tr> <tr class="odd"> <td class="convin">Any other cdata</td><td class="convop">no conversion</td><td class="convout">C type</td></tr> </table> <p> To pass a Lua object, other than a cdata object, as a specific type, you need to override the conversion rules: create a temporary cdata object with a constructor or a cast and initialize it with the value to pass: </p> <p> Assuming <tt>x</tt> is a Lua number, here's how to pass it as an integer to a vararg function: </p> <pre class="code"> ffi.cdef[[ int printf(const char *fmt, ...); ]] ffi.C.printf("integer value: %d\n", ffi.new("int", x)) </pre> <p> If you don't do this, the default Lua number &rarr; <tt>double</tt> conversion rule applies. A vararg C&nbsp;function expecting an integer will see a garbled or uninitialized value. </p> <h2 id="init">Initializers</h2> <p> Creating a cdata object with <a href="ext_ffi_api.html#ffi_new"><tt>ffi.new()</tt></a> or the equivalent constructor syntax always initializes its contents, too. Different rules apply, depending on the number of optional initializers and the C&nbsp;types involved: </p> <ul> <li>If no initializers are given, the object is filled with zero bytes.</li> <li>Scalar types (numbers and pointers) accept a single initializer. The Lua object is <a href="#convert_fromlua">converted to the scalar C&nbsp;type</a>.</li> <li>Valarrays (complex numbers and vectors) are treated like scalars when a single initializer is given. Otherwise they are treated like regular arrays.</li> <li>Aggregate types (arrays and structs) accept either a single cdata initializer of the same type (copy constructor), a single <a href="#init_table">table initializer</a>, or a flat list of initializers.</li> <li>The elements of an array are initialized, starting at index zero. If a single initializer is given for an array, it's repeated for all remaining elements. This doesn't happen if two or more initializers are given: all remaining uninitialized elements are filled with zero bytes.</li> <li>Byte arrays may also be initialized with a Lua string. This copies the whole string plus a terminating zero-byte. The copy stops early only if the array has a known, fixed size.</li> <li>The fields of a <tt>struct</tt> are initialized in the order of their declaration. Uninitialized fields are filled with zero bytes.</li> <li>Only the first field of a <tt>union</tt> can be initialized with a flat initializer.</li> <li>Elements or fields which are aggregates themselves are initialized with a <em>single</em> initializer, but this may be a table initializer or a compatible aggregate.</li> <li>Excess initializers cause an error.</li> </ul> <h2 id="init_table">Table Initializers</h2> <p> The following rules apply if a Lua table is used to initialize an Array or a <tt>struct</tt>/<tt>union</tt>: </p> <ul> <li>If the table index <tt>[0]</tt> is non-<tt>nil</tt>, then the table is assumed to be zero-based. Otherwise it's assumed to be one-based.</li> <li>Array elements, starting at index zero, are initialized one-by-one with the consecutive table elements, starting at either index <tt>[0]</tt> or <tt>[1]</tt>. This process stops at the first <tt>nil</tt> table element.</li> <li>If exactly one array element was initialized, it's repeated for all the remaining elements. Otherwise all remaining uninitialized elements are filled with zero bytes.</li> <li>The above logic only applies to arrays with a known fixed size. A VLA is only initialized with the element(s) given in the table. Depending on the use case, you may need to explicitly add a <tt>NULL</tt> or <tt>0</tt> terminator to a VLA.</li> <li>A <tt>struct</tt>/<tt>union</tt> can be initialized in the order of the declaration of its fields. Each field is initialized with consecutive table elements, starting at either index <tt>[0]</tt> or <tt>[1]</tt>. This process stops at the first <tt>nil</tt> table element.</li> <li>Otherwise, if neither index <tt>[0]</tt> nor <tt>[1]</tt> is present, a <tt>struct</tt>/<tt>union</tt> is initialized by looking up each field name (as a string key) in the table. Each non-<tt>nil</tt> value is used to initialize the corresponding field.</li> <li>Uninitialized fields of a <tt>struct</tt> are filled with zero bytes, except for the trailing VLA of a VLS.</li> <li>Initialization of a <tt>union</tt> stops after one field has been initialized. If no field has been initialized, the <tt>union</tt> is filled with zero bytes.</li> <li>Elements or fields which are aggregates themselves are initialized with a <em>single</em> initializer, but this may be a nested table initializer (or a compatible aggregate).</li> <li>Excess initializers for an array cause an error. Excess initializers for a <tt>struct</tt>/<tt>union</tt> are ignored. Unrelated table entries are ignored, too.</li> </ul> <p> Example: </p> <pre class="code"> local ffi = require("ffi") ffi.cdef[[ struct foo { int a, b; }; union bar { int i; double d; }; struct nested { int x; struct foo y; }; ]] ffi.new("int[3]", {}) --> 0, 0, 0 ffi.new("int[3]", {1}) --> 1, 1, 1 ffi.new("int[3]", {1,2}) --> 1, 2, 0 ffi.new("int[3]", {1,2,3}) --> 1, 2, 3 ffi.new("int[3]", {[0]=1}) --> 1, 1, 1 ffi.new("int[3]", {[0]=1,2}) --> 1, 2, 0 ffi.new("int[3]", {[0]=1,2,3}) --> 1, 2, 3 ffi.new("int[3]", {[0]=1,2,3,4}) --> error: too many initializers ffi.new("struct foo", {}) --> a = 0, b = 0 ffi.new("struct foo", {1}) --> a = 1, b = 0 ffi.new("struct foo", {1,2}) --> a = 1, b = 2 ffi.new("struct foo", {[0]=1,2}) --> a = 1, b = 2 ffi.new("struct foo", {b=2}) --> a = 0, b = 2 ffi.new("struct foo", {a=1,b=2,c=3}) --> a = 1, b = 2 'c' is ignored ffi.new("union bar", {}) --> i = 0, d = 0.0 ffi.new("union bar", {1}) --> i = 1, d = ? ffi.new("union bar", {[0]=1,2}) --> i = 1, d = ? '2' is ignored ffi.new("union bar", {d=2}) --> i = ?, d = 2.0 ffi.new("struct nested", {1,{2,3}}) --> x = 1, y.a = 2, y.b = 3 ffi.new("struct nested", {x=1,y={2,3}}) --> x = 1, y.a = 2, y.b = 3 </pre> <h2 id="cdata_ops">Operations on cdata Objects</h2> <p> All of the standard Lua operators can be applied to cdata objects or a mix of a cdata object and another Lua object. The following list shows the pre-defined operations. </p> <p> Reference types are dereferenced <em>before</em> performing each of the operations below &mdash; the operation is applied to the C&nbsp;type pointed to by the reference. </p> <p> The pre-defined operations are always tried first before deferring to a metamethod or index table (if any) for the corresponding ctype (except for <tt>__new</tt>). An error is raised if the metamethod lookup or index table lookup fails. </p> <h3 id="cdata_array">Indexing a cdata object</h3> <ul> <li><b>Indexing a pointer/array</b>: a cdata pointer/array can be indexed by a cdata number or a Lua number. The element address is computed as the base address plus the number value multiplied by the element size in bytes. A read access loads the element value and <a href="#convert_tolua">converts it to a Lua object</a>. A write access <a href="#convert_fromlua">converts a Lua object to the element type</a> and stores the converted value to the element. An error is raised if the element size is undefined or a write access to a constant element is attempted.</li> <li><b>Dereferencing a <tt>struct</tt>/<tt>union</tt> field</b>: a cdata <tt>struct</tt>/<tt>union</tt> or a pointer to a <tt>struct</tt>/<tt>union</tt> can be dereferenced by a string key, giving the field name. The field address is computed as the base address plus the relative offset of the field. A read access loads the field value and <a href="#convert_tolua">converts it to a Lua object</a>. A write access <a href="#convert_fromlua">converts a Lua object to the field type</a> and stores the converted value to the field. An error is raised if a write access to a constant <tt>struct</tt>/<tt>union</tt> or a constant field is attempted. Scoped enum constants or static constants are treated like a constant field.</li> <li><b>Indexing a complex number</b>: a complex number can be indexed either by a cdata number or a Lua number with the values 0 or 1, or by the strings <tt>"re"</tt> or <tt>"im"</tt>. A read access loads the real part (<tt>[0]</tt>, <tt>.re</tt>) or the imaginary part (<tt>[1]</tt>, <tt>.im</tt>) part of a complex number and <a href="#convert_tolua">converts it to a Lua number</a>. The sub-parts of a complex number are immutable &mdash; assigning to an index of a complex number raises an error. Accessing out-of-bound indexes returns unspecified results, but is guaranteed not to trigger memory access violations.</li> <li><b>Indexing a vector</b>: a vector is treated like an array for indexing purposes, except the vector elements are immutable &mdash; assigning to an index of a vector raises an error.</li> </ul> <p> A ctype object can be indexed with a string key, too. The only pre-defined operation is reading scoped constants of <tt>struct</tt>/<tt>union</tt> types. All other accesses defer to the corresponding metamethods or index tables (if any). </p> <p> Note: since there's (deliberately) no address-of operator, a cdata object holding a value type is effectively immutable after initialization. The JIT compiler benefits from this fact when applying certain optimizations. </p> <p> As a consequence, the <em>elements</em> of complex numbers and vectors are immutable. But the elements of an aggregate holding these types <em>may</em> be modified of course. I.e. you cannot assign to <tt>foo.c.im</tt>, but you can assign a (newly created) complex number to <tt>foo.c</tt>. </p> <p> The JIT compiler implements strict aliasing rules: accesses to different types do <b>not</b> alias, except for differences in signedness (this applies even to <tt>char</tt> pointers, unlike C99). Type punning through unions is explicitly detected and allowed. </p> <h3 id="cdata_call">Calling a cdata object</h3> <ul> <li><b>Constructor</b>: a ctype object can be called and used as a <a href="ext_ffi_api.html#ffi_new">constructor</a>. This is equivalent to <tt>ffi.new(ct, ...)</tt>, unless a <tt>__new</tt> metamethod is defined. The <tt>__new</tt> metamethod is called with the ctype object plus any other arguments passed to the constructor. Note that you have to use <tt>ffi.new</tt> inside of it, since calling <tt>ct(...)</tt> would cause infinite recursion.</li> <li><b>C&nbsp;function call</b>: a cdata function or cdata function pointer can be called. The passed arguments are <a href="#convert_fromlua">converted to the C&nbsp;types</a> of the parameters given by the function declaration. Arguments passed to the variable argument part of vararg C&nbsp;function use <a href="#convert_vararg">special conversion rules</a>. This C&nbsp;function is called and the return value (if any) is <a href="#convert_tolua">converted to a Lua object</a>.<br> On Windows/x86 systems, <tt>__stdcall</tt> functions are automatically detected and a function declared as <tt>__cdecl</tt> (the default) is silently fixed up after the first call.</li> </ul> <h3 id="cdata_arith">Arithmetic on cdata objects</h3> <ul> <li><b>Pointer arithmetic</b>: a cdata pointer/array and a cdata number or a Lua number can be added or subtracted. The number must be on the right hand side for a subtraction. The result is a pointer of the same type with an address plus or minus the number value multiplied by the element size in bytes. An error is raised if the element size is undefined.</li> <li><b>Pointer difference</b>: two compatible cdata pointers/arrays can be subtracted. The result is the difference between their addresses, divided by the element size in bytes. An error is raised if the element size is undefined or zero.</li> <li><b>64&nbsp;bit integer arithmetic</b>: the standard arithmetic operators (<tt>+&nbsp;-&nbsp;*&nbsp;/&nbsp;%&nbsp;^</tt> and unary minus) can be applied to two cdata numbers, or a cdata number and a Lua number. If one of them is an <tt>uint64_t</tt>, the other side is converted to an <tt>uint64_t</tt> and an unsigned arithmetic operation is performed. Otherwise both sides are converted to an <tt>int64_t</tt> and a signed arithmetic operation is performed. The result is a boxed 64&nbsp;bit cdata object.<br> If one of the operands is an <tt>enum</tt> and the other operand is a string, the string is converted to the value of a matching <tt>enum</tt> constant before the above conversion.<br> These rules ensure that 64&nbsp;bit integers are "sticky". Any expression involving at least one 64&nbsp;bit integer operand results in another one. The undefined cases for the division, modulo and power operators return <tt>2LL&nbsp;^&nbsp;63</tt> or <tt>2ULL&nbsp;^&nbsp;63</tt>.<br> You'll have to explicitly convert a 64&nbsp;bit integer to a Lua number (e.g. for regular floating-point calculations) with <tt>tonumber()</tt>. But note this may incur a precision loss.</li> <li><b>64&nbsp;bit bitwise operations</b>: the rules for 64&nbsp;bit arithmetic operators apply analogously.<br> Unlike the other <tt>bit.*</tt> operations, <tt>bit.tobit()</tt> converts a cdata number via <tt>int64_t</tt> to <tt>int32_t</tt> and returns a Lua number.<br> For <tt>bit.band()</tt>, <tt>bit.bor()</tt> and <tt>bit.bxor()</tt>, the conversion to <tt>int64_t</tt> or <tt>uint64_t</tt> applies to <em>all</em> arguments, if <em>any</em> argument is a cdata number.<br> For all other operations, only the first argument is used to determine the output type. This implies that a cdata number as a shift count for shifts and rotates is accepted, but that alone does <em>not</em> cause a cdata number output. </ul> <h3 id="cdata_comp">Comparisons of cdata objects</h3> <ul> <li><b>Pointer comparison</b>: two compatible cdata pointers/arrays can be compared. The result is the same as an unsigned comparison of their addresses. <tt>nil</tt> is treated like a <tt>NULL</tt> pointer, which is compatible with any other pointer type.</li> <li><b>64&nbsp;bit integer comparison</b>: two cdata numbers, or a cdata number and a Lua number can be compared with each other. If one of them is an <tt>uint64_t</tt>, the other side is converted to an <tt>uint64_t</tt> and an unsigned comparison is performed. Otherwise both sides are converted to an <tt>int64_t</tt> and a signed comparison is performed.<br> If one of the operands is an <tt>enum</tt> and the other operand is a string, the string is converted to the value of a matching <tt>enum</tt> constant before the above conversion.<br> <li><b>Comparisons for equality/inequality</b> never raise an error. Even incompatible pointers can be compared for equality by address. Any other incompatible comparison (also with non-cdata objects) treats the two sides as unequal.</li> </ul> <h3 id="cdata_key">cdata objects as table keys</h3> <p> Lua tables may be indexed by cdata objects, but this doesn't provide any useful semantics &mdash; <b>cdata objects are unsuitable as table keys!</b> </p> <p> A cdata object is treated like any other garbage-collected object and is hashed and compared by its address for table indexing. Since there's no interning for cdata value types, the same value may be boxed in different cdata objects with different addresses. Thus <tt>t[1LL+1LL]</tt> and <tt>t[2LL]</tt> usually <b>do not</b> point to the same hash slot and they certainly <b>do not</b> point to the same hash slot as <tt>t[2]</tt>. </p> <p> It would seriously drive up implementation complexity and slow down the common case, if one were to add extra handling for by-value hashing and comparisons to Lua tables. Given the ubiquity of their use inside the VM, this is not acceptable. </p> <p> There are three viable alternatives, if you really need to use cdata objects as keys: </p> <ul> <li>If you can get by with the precision of Lua numbers (52&nbsp;bits), then use <tt>tonumber()</tt> on a cdata number or combine multiple fields of a cdata aggregate to a Lua number. Then use the resulting Lua number as a key when indexing tables.<br> One obvious benefit: <tt>t[tonumber(2LL)]</tt> <b>does</b> point to the same slot as <tt>t[2]</tt>.</li> <li>Otherwise use either <tt>tostring()</tt> on 64&nbsp;bit integers or complex numbers or combine multiple fields of a cdata aggregate to a Lua string (e.g. with <a href="ext_ffi_api.html#ffi_string"><tt>ffi.string()</tt></a>). Then use the resulting Lua string as a key when indexing tables.</li> <li>Create your own specialized hash table implementation using the C&nbsp;types provided by the FFI library, just like you would in C&nbsp;code. Ultimately this may give much better performance than the other alternatives or what a generic by-value hash table could possibly provide.</li> </ul> <h2 id="param">Parameterized Types</h2> <p> To facilitate some abstractions, the two functions <a href="ext_ffi_api.html#ffi_typeof"><tt>ffi.typeof</tt></a> and <a href="ext_ffi_api.html#ffi_cdef"><tt>ffi.cdef</tt></a> support parameterized types in C&nbsp;declarations. Note: none of the other API functions taking a cdecl allow this. </p> <p> Any place you can write a <b><tt>typedef</tt> name</b>, an <b>identifier</b> or a <b>number</b> in a declaration, you can write <tt>$</tt> (the dollar sign) instead. These placeholders are replaced in order of appearance with the arguments following the cdecl string: </p> <pre class="code"> -- Declare a struct with a parameterized field type and name: ffi.cdef([[ typedef struct { $ $; } foo_t; ]], type1, name1) -- Anonymous struct with dynamic names: local bar_t = ffi.typeof("struct { int $, $; }", name1, name2) -- Derived pointer type: local bar_ptr_t = ffi.typeof("$ *", bar_t) -- Parameterized dimensions work even where a VLA won't work: local matrix_t = ffi.typeof("uint8_t[$][$]", width, height) </pre> <p> Caveat: this is <em>not</em> simple text substitution! A passed ctype or cdata object is treated like the underlying type, a passed string is considered an identifier and a number is considered a number. You must not mix this up: e.g. passing <tt>"int"</tt> as a string doesn't work in place of a type, you'd need to use <tt>ffi.typeof("int")</tt> instead. </p> <p> The main use for parameterized types are libraries implementing abstract data types (<a href="https://www.freelists.org/post/luajit/ffi-type-of-pointer-to,8"><span class="ext">&raquo;</span>&nbsp;example</a>), similar to what can be achieved with C++ template metaprogramming. Another use case are derived types of anonymous structs, which avoids pollution of the global struct namespace. </p> <p> Please note that parameterized types are a nice tool and indispensable for certain use cases. But you'll want to use them sparingly in regular code, e.g. when all types are actually fixed. </p> <h2 id="gc">Garbage Collection of cdata Objects</h2> <p> All explicitly (<tt>ffi.new()</tt>, <tt>ffi.cast()</tt> etc.) or implicitly (accessors) created cdata objects are garbage collected. You need to ensure to retain valid references to cdata objects somewhere on a Lua stack, an upvalue or in a Lua table while they are still in use. Once the last reference to a cdata object is gone, the garbage collector will automatically free the memory used by it (at the end of the next GC cycle). </p> <p> Please note that pointers themselves are cdata objects, however they are <b>not</b> followed by the garbage collector. So e.g. if you assign a cdata array to a pointer, you must keep the cdata object holding the array alive as long as the pointer is still in use: </p> <pre class="code"> ffi.cdef[[ typedef struct { int *a; } foo_t; ]] local s = ffi.new("foo_t", ffi.new("int[10]")) -- <span style="color:#c00000;">WRONG!</span> local a = ffi.new("int[10]") -- <span style="color:#00a000;">OK</span> local s = ffi.new("foo_t", a) -- Now do something with 's', but keep 'a' alive until you're done. </pre> <p> Similar rules apply for Lua strings which are implicitly converted to <tt>"const&nbsp;char&nbsp;*"</tt>: the string object itself must be referenced somewhere or it'll be garbage collected eventually. The pointer will then point to stale data, which may have already been overwritten. Note that <em>string literals</em> are automatically kept alive as long as the function containing it (actually its prototype) is not garbage collected. </p> <p> Objects which are passed as an argument to an external C&nbsp;function are kept alive until the call returns. So it's generally safe to create temporary cdata objects in argument lists. This is a common idiom for <a href="#convert_vararg">passing specific C&nbsp;types to vararg functions</a>. </p> <p> Memory areas returned by C functions (e.g. from <tt>malloc()</tt>) must be manually managed, of course (or use <a href="ext_ffi_api.html#ffi_gc"><tt>ffi.gc()</tt></a>). Pointers to cdata objects are indistinguishable from pointers returned by C functions (which is one of the reasons why the GC cannot follow them). </p> <h2 id="callback">Callbacks</h2> <p> The LuaJIT FFI automatically generates special callback functions whenever a Lua function is converted to a C&nbsp;function pointer. This associates the generated callback function pointer with the C&nbsp;type of the function pointer and the Lua function object (closure). </p> <p> This can happen implicitly due to the usual conversions, e.g. when passing a Lua function to a function pointer argument. Or you can use <tt>ffi.cast()</tt> to explicitly cast a Lua function to a C&nbsp;function pointer. </p> <p> Currently only certain C&nbsp;function types can be used as callback functions. Neither C&nbsp;vararg functions nor functions with pass-by-value aggregate argument or result types are supported. There are no restrictions for the kind of Lua functions that can be called from the callback &mdash; no checks for the proper number of arguments are made. The return value of the Lua function will be converted to the result type and an error will be thrown for invalid conversions. </p> <p> It's allowed to throw errors across a callback invocation, but it's not advisable in general. Do this only if you know the C&nbsp;function, that called the callback, copes with the forced stack unwinding and doesn't leak resources. </p> <p> One thing that's not allowed, is to let an FFI call into a C&nbsp;function get JIT-compiled, which in turn calls a callback, calling into Lua again. Usually this attempt is caught by the interpreter first and the C&nbsp;function is blacklisted for compilation. </p> <p> However, this heuristic may fail under specific circumstances: e.g. a message polling function might not run Lua callbacks right away and the call gets JIT-compiled. If it later happens to call back into Lua (e.g. a rarely invoked error callback), you'll get a VM PANIC with the message <tt>"bad callback"</tt>. Then you'll need to manually turn off JIT-compilation with <a href="ext_jit.html#jit_onoff_func"><tt>jit.off()</tt></a> for the surrounding Lua function that invokes such a message polling function (or similar). </p> <h3 id="callback_resources">Callback resource handling</h3> <p> Callbacks take up resources &mdash; you can only have a limited number of them at the same time (500&nbsp;-&nbsp;1000, depending on the architecture). The associated Lua functions are anchored to prevent garbage collection, too. </p> <p> <b>Callbacks due to implicit conversions are permanent!</b> There is no way to guess their lifetime, since the C&nbsp;side might store the function pointer for later use (typical for GUI toolkits). The associated resources cannot be reclaimed until termination: </p> <pre class="code"> ffi.cdef[[ typedef int (__stdcall *WNDENUMPROC)(void *hwnd, intptr_t l); int EnumWindows(WNDENUMPROC func, intptr_t l); ]] -- Implicit conversion to a callback via function pointer argument. local count = 0 ffi.C.EnumWindows(function(hwnd, l) count = count + 1 return true end, 0) -- The callback is permanent and its resources cannot be reclaimed! -- Ok, so this may not be a problem, if you do this only once. </pre> <p> Note: this example shows that you <em>must</em> properly declare <tt>__stdcall</tt> callbacks on Windows/x86 systems. The calling convention cannot be automatically detected, unlike for <tt>__stdcall</tt> calls <em>to</em> Windows functions. </p> <p> For some use cases it's necessary to free up the resources or to dynamically redirect callbacks. Use an explicit cast to a C&nbsp;function pointer and keep the resulting cdata object. Then use the <a href="ext_ffi_api.html#callback_free"><tt>cb:free()</tt></a> or <a href="ext_ffi_api.html#callback_set"><tt>cb:set()</tt></a> methods on the cdata object: </p> <pre class="code"> -- Explicitly convert to a callback via cast. local count = 0 local cb = ffi.cast("WNDENUMPROC", function(hwnd, l) count = count + 1 return true end) -- Pass it to a C function. ffi.C.EnumWindows(cb, 0) -- EnumWindows doesn't need the callback after it returns, so free it. cb:free() -- The callback function pointer is no longer valid and its resources -- will be reclaimed. The created Lua closure will be garbage collected. </pre> <h3 id="callback_performance">Callback performance</h3> <p> <b>Callbacks are slow!</b> First, the C&nbsp;to Lua transition itself has an unavoidable cost, similar to a <tt>lua_call()</tt> or <tt>lua_pcall()</tt>. Argument and result marshalling add to that cost. And finally, neither the C&nbsp;compiler nor LuaJIT can inline or optimize across the language barrier and hoist repeated computations out of a callback function. </p> <p> Do not use callbacks for performance-sensitive work: e.g. consider a numerical integration routine which takes a user-defined function to integrate over. It's a bad idea to call a user-defined Lua function from C&nbsp;code millions of times. The callback overhead will be absolutely detrimental for performance. </p> <p> It's considerably faster to write the numerical integration routine itself in Lua &mdash; the JIT compiler will be able to inline the user-defined function and optimize it together with its calling context, with very competitive performance. </p> <p> As a general guideline: <b>use callbacks only when you must</b>, because of existing C&nbsp;APIs. E.g. callback performance is irrelevant for a GUI application, which waits for user input most of the time, anyway. </p> <p> For new designs <b>avoid push-style APIs</b>: a C&nbsp;function repeatedly calling a callback for each result. Instead <b>use pull-style APIs</b>: call a C&nbsp;function repeatedly to get a new result. Calls from Lua to C via the FFI are much faster than the other way round. Most well-designed libraries already use pull-style APIs (read/write, get/put). </p> <h2 id="clib">C Library Namespaces</h2> <p> A C&nbsp;library namespace is a special kind of object which allows access to the symbols contained in shared libraries or the default symbol namespace. The default <a href="ext_ffi_api.html#ffi_C"><tt>ffi.C</tt></a> namespace is automatically created when the FFI library is loaded. C&nbsp;library namespaces for specific shared libraries may be created with the <a href="ext_ffi_api.html#ffi_load"><tt>ffi.load()</tt></a> API function. </p> <p> Indexing a C&nbsp;library namespace object with a symbol name (a Lua string) automatically binds it to the library. First the symbol type is resolved &mdash; it must have been declared with <a href="ext_ffi_api.html#ffi_cdef"><tt>ffi.cdef</tt></a>. Then the symbol address is resolved by searching for the symbol name in the associated shared libraries or the default symbol namespace. Finally, the resulting binding between the symbol name, the symbol type and its address is cached. Missing symbol declarations or nonexistent symbol names cause an error. </p> <p> This is what happens on a <b>read access</b> for the different kinds of symbols: </p> <ul> <li>External functions: a cdata object with the type of the function and its address is returned.</li> <li>External variables: the symbol address is dereferenced and the loaded value is <a href="#convert_tolua">converted to a Lua object</a> and returned.</li> <li>Constant values (<tt>static&nbsp;const</tt> or <tt>enum</tt> constants): the constant is <a href="#convert_tolua">converted to a Lua object</a> and returned.</li> </ul> <p> This is what happens on a <b>write access</b>: </p> <ul> <li>External variables: the value to be written is <a href="#convert_fromlua">converted to the C&nbsp;type</a> of the variable and then stored at the symbol address.</li> <li>Writing to constant variables or to any other symbol type causes an error, like any other attempted write to a constant location.</li> </ul> <p> C&nbsp;library namespaces themselves are garbage collected objects. If the last reference to the namespace object is gone, the garbage collector will eventually release the shared library reference and remove all memory associated with the namespace. Since this may trigger the removal of the shared library from the memory of the running process, it's generally <em>not safe</em> to use function cdata objects obtained from a library if the namespace object may be unreferenced. </p> <p> Performance notice: the JIT compiler specializes to the identity of namespace objects and to the strings used to index it. This effectively turns function cdata objects into constants. It's not useful and actually counter-productive to explicitly cache these function objects, e.g. <tt>local strlen = ffi.C.strlen</tt>. OTOH it <em>is</em> useful to cache the namespace itself, e.g. <tt>local C = ffi.C</tt>. </p> <h2 id="policy">No Hand-holding!</h2> <p> The FFI library has been designed as <b>a low-level library</b>. The goal is to interface with C&nbsp;code and C&nbsp;data types with a minimum of overhead. This means <b>you can do anything you can do from&nbsp;C</b>: access all memory, overwrite anything in memory, call machine code at any memory address and so on. </p> <p> The FFI library provides <b>no memory safety</b>, unlike regular Lua code. It will happily allow you to dereference a <tt>NULL</tt> pointer, to access arrays out of bounds or to misdeclare C&nbsp;functions. If you make a mistake, your application might crash, just like equivalent C&nbsp;code would. </p> <p> This behavior is inevitable, since the goal is to provide full interoperability with C&nbsp;code. Adding extra safety measures, like bounds checks, would be futile. There's no way to detect misdeclarations of C&nbsp;functions, since shared libraries only provide symbol names, but no type information. Likewise there's no way to infer the valid range of indexes for a returned pointer. </p> <p> Again: the FFI library is a low-level library. This implies it needs to be used with care, but it's flexibility and performance often outweigh this concern. If you're a C or C++ developer, it'll be easy to apply your existing knowledge. OTOH writing code for the FFI library is not for the faint of heart and probably shouldn't be the first exercise for someone with little experience in Lua, C or C++. </p> <p> As a corollary of the above, the FFI library is <b>not safe for use by untrusted Lua code</b>. If you're sandboxing untrusted Lua code, you definitely don't want to give this code access to the FFI library or to <em>any</em> cdata object (except 64&nbsp;bit integers or complex numbers). Any properly engineered Lua sandbox needs to provide safety wrappers for many of the standard Lua library functions &mdash; similar wrappers need to be written for high-level operations on FFI data types, too. </p> <h2 id="status">Current Status</h2> <p> The initial release of the FFI library has some limitations and is missing some features. Most of these will be fixed in future releases. </p> <p> <a href="#clang">C language support</a> is currently incomplete: </p> <ul> <li>C&nbsp;declarations are not passed through a C&nbsp;pre-processor, yet.</li> <li>The C&nbsp;parser is able to evaluate most constant expressions commonly found in C&nbsp;header files. However it doesn't handle the full range of C&nbsp;expression semantics and may fail for some obscure constructs.</li> <li><tt>static const</tt> declarations only work for integer types up to 32&nbsp;bits. Neither declaring string constants nor floating-point constants is supported.</li> <li>Packed <tt>struct</tt> bitfields that cross container boundaries are not implemented.</li> <li>Native vector types may be defined with the GCC <tt>mode</tt> or <tt>vector_size</tt> attribute. But no operations other than loading, storing and initializing them are supported, yet.</li> <li>The <tt>volatile</tt> type qualifier is currently ignored by compiled code.</li> <li><a href="ext_ffi_api.html#ffi_cdef"><tt>ffi.cdef</tt></a> silently ignores most re-declarations. Note: avoid re-declarations which do not conform to C99. The implementation will eventually be changed to perform strict checks.</li> </ul> <p> The JIT compiler already handles a large subset of all FFI operations. It automatically falls back to the interpreter for unimplemented operations (you can check for this with the <a href="running.html#opt_j"><tt>-jv</tt></a> command line option). The following operations are currently not compiled and may exhibit suboptimal performance, especially when used in inner loops: </p> <ul> <li>Vector operations.</li> <li>Table initializers.</li> <li>Initialization of nested <tt>struct</tt>/<tt>union</tt> types.</li> <li>Non-default initialization of VLA/VLS or large C&nbsp;types (&gt; 128&nbsp;bytes or &gt; 16 array elements).</li> <li>Bitfield initializations.</li> <li>Pointer differences for element sizes that are not a power of two.</li> <li>Calls to C&nbsp;functions with aggregates passed or returned by value.</li> <li>Calls to ctype metamethods which are not plain functions.</li> <li>ctype <tt>__newindex</tt> tables and non-string lookups in ctype <tt>__index</tt> tables.</li> <li><tt>tostring()</tt> for cdata types.</li> <li>Calls to <tt>ffi.cdef()</tt>, <tt>ffi.load()</tt> and <tt>ffi.metatype()</tt>.</li> </ul> <p> Other missing features: </p> <ul> <li>Arithmetic for <tt>complex</tt> numbers.</li> <li>Passing structs by value to vararg C&nbsp;functions.</li> <li><a href="extensions.html#exceptions">C++ exception interoperability</a> does not extend to C&nbsp;functions called via the FFI, if the call is compiled.</li> </ul> <br class="flush"> </div> <div id="foot"> <hr class="hide"> Copyright &copy; 2005-2021 <span class="noprint"> &middot; <a href="contact.html">Contact</a> </span> </div> </body> </html>
xLua/build/luajit-2.1.0b3/doc/ext_ffi_semantics.html/0
{ "file_path": "xLua/build/luajit-2.1.0b3/doc/ext_ffi_semantics.html", "repo_id": "xLua", "token_count": 17709 }
2,112
------------------------------------------------------------------------------ -- DynASM ARM64 module. -- -- Copyright (C) 2005-2021 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ -- Module information: local _info = { arch = "arm", description = "DynASM ARM64 module", version = "1.5.0", vernum = 10500, release = "2021-05-02", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, setmetatable, rawget = assert, setmetatable, rawget local _s = string local format, byte, char = _s.format, _s.byte, _s.char local match, gmatch, gsub = _s.match, _s.gmatch, _s.gsub local concat, sort, insert = table.concat, table.sort, table.insert local bit = bit or require("bit") local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift local ror, tohex, tobit = bit.ror, bit.tohex, bit.tobit -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { "STOP", "SECTION", "ESC", "REL_EXT", "ALIGN", "REL_LG", "LABEL_LG", "REL_PC", "LABEL_PC", "REL_A", "IMM", "IMM6", "IMM12", "IMM13W", "IMM13X", "IMML", "IMMV", "VREG", } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number. local map_action = {} for n,name in ipairs(action_names) do map_action[name] = n-1 end -- Action list buffer. local actlist = {} -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 ------------------------------------------------------------------------------ -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist if nn == 0 then nn = 1; actlist[0] = map_action.STOP end out:write("static const unsigned int ", name, "[", nn, "] = {\n") for i = 1,nn-1 do assert(out:write("0x", tohex(actlist[i]), ",\n")) end assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n")) end ------------------------------------------------------------------------------ -- Add word to action list. local function wputxw(n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, val, a, num) local w = assert(map_action[action], "bad action name `"..action.."'") wputxw(w * 0x10000 + (val or 0)) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) if #actlist == actargs[1] then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true) actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped word. local function wputw(n) if n <= 0x000fffff then waction("ESC") end wputxw(n) end -- Reserve position for word. local function wpos() local pos = #actlist+1 actlist[pos] = "" return pos end -- Store word to reserved position. local function wputpos(pos, n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") if n <= 0x000fffff then insert(actlist, pos+1, n) n = map_action.ESC * 0x10000 end actlist[pos] = n end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 20 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end local n = next_global if n > 2047 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=20,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=20,next_global-1 do out:write(" ", prefix, t[i], ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=20,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = 0 local map_extern_ = {} local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n > 2047 then werror("too many extern labels") end next_extern = n + 1 t[name] = n map_extern_[n] = name return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) out:write("Extern labels:\n") for i=0,next_extern-1 do out:write(format(" %s\n", map_extern_[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) out:write("static const char *const ", name, "[] = {\n") for i=0,next_extern-1 do out:write(" \"", map_extern_[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. -- Ext. register name -> int. name. local map_archdef = { xzr = "@x31", wzr = "@w31", lr = "x30", } -- Int. register name -> ext. name. local map_reg_rev = { ["@x31"] = "xzr", ["@w31"] = "wzr", x30 = "lr", } local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for Dt... macros). -- Reverse defines for registers. function _M.revdef(s) return map_reg_rev[s] or s end local map_shift = { lsl = 0, lsr = 1, asr = 2, } local map_extend = { uxtb = 0, uxth = 1, uxtw = 2, uxtx = 3, sxtb = 4, sxth = 5, sxtw = 6, sxtx = 7, } local map_cond = { eq = 0, ne = 1, cs = 2, cc = 3, mi = 4, pl = 5, vs = 6, vc = 7, hi = 8, ls = 9, ge = 10, lt = 11, gt = 12, le = 13, al = 14, hs = 2, lo = 3, } ------------------------------------------------------------------------------ local parse_reg_type local function parse_reg(expr, shift) if not expr then werror("expected register name") end local tname, ovreg = match(expr, "^([%w_]+):(@?%l%d+)$") if not tname then tname, ovreg = match(expr, "^([%w_]+):(R[xwqdshb]%b())$") end local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg if not reg then werror("type `"..(tname or expr).."' needs a register override") end expr = reg end local ok31, rt, r = match(expr, "^(@?)([xwqdshb])([123]?[0-9])$") if r then r = tonumber(r) if r <= 30 or (r == 31 and ok31 ~= "" or (rt ~= "w" and rt ~= "x")) then if not parse_reg_type then parse_reg_type = rt elseif parse_reg_type ~= rt then werror("register size mismatch") end return shl(r, shift), tp end end local vrt, vreg = match(expr, "^R([xwqdshb])(%b())$") if vreg then if not parse_reg_type then parse_reg_type = vrt elseif parse_reg_type ~= vrt then werror("register size mismatch") end if shift then waction("VREG", shift, vreg) end return 0 end werror("bad register name `"..expr.."'") end local function parse_reg_base(expr) if expr == "sp" then return 0x3e0 end local base, tp = parse_reg(expr, 5) if parse_reg_type ~= "x" then werror("bad register type") end parse_reg_type = false return base, tp end local parse_ctx = {} local loadenv = setfenv and function(s) local code = loadstring(s, "") if code then setfenv(code, parse_ctx) end return code end or function(s) return load(s, "", nil, parse_ctx) end -- Try to parse simple arithmetic, too, since some basic ops are aliases. local function parse_number(n) local x = tonumber(n) if x then return x end local code = loadenv("return "..n) if code then local ok, y = pcall(code) if ok and type(y) == "number" then return y end end return nil end local function parse_imm(imm, bits, shift, scale, signed) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) if n then local m = sar(n, scale) if shl(m, scale) == n then if signed then local s = sar(m, bits-1) if s == 0 then return shl(m, shift) elseif s == -1 then return shl(m + shl(1, bits), shift) end else if sar(m, bits) == 0 then return shl(m, shift) end end end werror("out of range immediate `"..imm.."'") else waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm) return 0 end end local function parse_imm12(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) if n then if shr(n, 12) == 0 then return shl(n, 10) elseif band(n, 0xff000fff) == 0 then return shr(n, 2) + 0x00400000 end werror("out of range immediate `"..imm.."'") else waction("IMM12", 0, imm) return 0 end end local function parse_imm13(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) local r64 = parse_reg_type == "x" if n and n % 1 == 0 and n >= 0 and n <= 0xffffffff then local inv = false if band(n, 1) == 1 then n = bit.bnot(n); inv = true end local t = {} for i=1,32 do t[i] = band(n, 1); n = shr(n, 1) end local b = table.concat(t) b = b..(r64 and (inv and "1" or "0"):rep(32) or b) local p0, p1, p0a, p1a = b:match("^(0+)(1+)(0*)(1*)") if p0 then local w = p1a == "" and (r64 and 64 or 32) or #p1+#p0a if band(w, w-1) == 0 and b == b:sub(1, w):rep(64/w) then local s = band(-2*w, 0x3f) - 1 if w == 64 then s = s + 0x1000 end if inv then return shl(w-#p1-#p0, 16) + shl(s+w-#p1, 10) else return shl(w-#p0, 16) + shl(s+#p1, 10) end end end werror("out of range immediate `"..imm.."'") elseif r64 then waction("IMM13X", 0, format("(unsigned int)(%s)", imm)) actargs[#actargs+1] = format("(unsigned int)((unsigned long long)(%s)>>32)", imm) return 0 else waction("IMM13W", 0, imm) return 0 end end local function parse_imm6(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) if n then if n >= 0 and n <= 63 then return shl(band(n, 0x1f), 19) + (n >= 32 and 0x80000000 or 0) end werror("out of range immediate `"..imm.."'") else waction("IMM6", 0, imm) return 0 end end local function parse_imm_load(imm, scale) local n = parse_number(imm) if n then local m = sar(n, scale) if shl(m, scale) == n and m >= 0 and m < 0x1000 then return shl(m, 10) + 0x01000000 -- Scaled, unsigned 12 bit offset. elseif n >= -256 and n < 256 then return shl(band(n, 511), 12) -- Unscaled, signed 9 bit offset. end werror("out of range immediate `"..imm.."'") else waction("IMML", scale, imm) return 0 end end local function parse_fpimm(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) if n then local m, e = math.frexp(n) local s, e2 = 0, band(e-2, 7) if m < 0 then m = -m; s = 0x00100000 end m = m*32-16 if m % 1 == 0 and m >= 0 and m <= 15 and sar(shl(e2, 29), 29)+2 == e then return s + shl(e2, 17) + shl(m, 13) end werror("out of range immediate `"..imm.."'") else werror("NYI fpimm action") end end local function parse_shift(expr) local s, s2 = match(expr, "^(%S+)%s*(.*)$") s = map_shift[s] if not s then werror("expected shift operand") end return parse_imm(s2, 6, 10, 0, false) + shl(s, 22) end local function parse_lslx16(expr) local n = match(expr, "^lsl%s*#(%d+)$") n = tonumber(n) if not n then werror("expected shift operand") end if band(n, parse_reg_type == "x" and 0xffffffcf or 0xffffffef) ~= 0 then werror("bad shift amount") end return shl(n, 17) end local function parse_extend(expr) local s, s2 = match(expr, "^(%S+)%s*(.*)$") if s == "lsl" then s = parse_reg_type == "x" and 3 or 2 else s = map_extend[s] end if not s then werror("expected extend operand") end return (s2 == "" and 0 or parse_imm(s2, 3, 10, 0, false)) + shl(s, 13) end local function parse_cond(expr, inv) local c = map_cond[expr] if not c then werror("expected condition operand") end return shl(bit.bxor(c, inv), 12) end local function parse_load(params, nparams, n, op) if params[n+2] then werror("too many operands") end local scale = shr(op, 30) local pn, p2 = params[n], params[n+1] local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$") if not p1 then if not p2 then local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local base, tp = parse_reg_base(reg) if tp then waction("IMML", scale, format(tp.ctypefmt, tailr)) return op + base end end end werror("expected address operand") end if p2 then if wb == "!" then werror("bad use of '!'") end op = op + parse_reg_base(p1) + parse_imm(p2, 9, 12, 0, true) + 0x400 elseif wb == "!" then local p1a, p2a = match(p1, "^([^,%s]*)%s*,%s*(.*)$") if not p1a then werror("bad use of '!'") end op = op + parse_reg_base(p1a) + parse_imm(p2a, 9, 12, 0, true) + 0xc00 else local p1a, p2a = match(p1, "^([^,%s]*)%s*(.*)$") op = op + parse_reg_base(p1a) if p2a ~= "" then local imm = match(p2a, "^,%s*#(.*)$") if imm then op = op + parse_imm_load(imm, scale) else local p2b, p3b, p3s = match(p2a, "^,%s*([^,%s]*)%s*,?%s*(%S*)%s*(.*)$") op = op + parse_reg(p2b, 16) + 0x00200800 if parse_reg_type ~= "x" and parse_reg_type ~= "w" then werror("bad index register type") end if p3b == "" then if parse_reg_type ~= "x" then werror("bad index register type") end op = op + 0x6000 else if p3s == "" or p3s == "#0" then elseif p3s == "#"..scale then op = op + 0x1000 else werror("bad scale") end if parse_reg_type == "x" then if p3b == "lsl" and p3s ~= "" then op = op + 0x6000 elseif p3b == "sxtx" then op = op + 0xe000 else werror("bad extend/shift specifier") end else if p3b == "uxtw" then op = op + 0x4000 elseif p3b == "sxtw" then op = op + 0xc000 else werror("bad extend/shift specifier") end end end end else if wb == "!" then werror("bad use of '!'") end op = op + 0x01000000 end end return op end local function parse_load_pair(params, nparams, n, op) if params[n+2] then werror("too many operands") end local pn, p2 = params[n], params[n+1] local scale = shr(op, 30) == 0 and 2 or 3 local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$") if not p1 then if not p2 then local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local base, tp = parse_reg_base(reg) if tp then waction("IMM", 32768+7*32+15+scale*1024, format(tp.ctypefmt, tailr)) return op + base + 0x01000000 end end end werror("expected address operand") end if p2 then if wb == "!" then werror("bad use of '!'") end op = op + 0x00800000 else local p1a, p2a = match(p1, "^([^,%s]*)%s*,%s*(.*)$") if p1a then p1, p2 = p1a, p2a else p2 = "#0" end op = op + (wb == "!" and 0x01800000 or 0x01000000) end return op + parse_reg_base(p1) + parse_imm(p2, 7, 15, scale, true) end local function parse_label(label, def) local prefix = label:sub(1, 2) -- =>label (pc label reference) if prefix == "=>" then return "PC", 0, label:sub(3) end -- ->name (global label reference) if prefix == "->" then return "LG", map_global[label:sub(3)] end if def then -- [1-9] (local label definition) if match(label, "^[1-9]$") then return "LG", 10+tonumber(label) end else -- [<>][1-9] (local label reference) local dir, lnum = match(label, "^([<>])([1-9])$") if dir then -- Fwd: 1-9, Bkwd: 11-19. return "LG", lnum + (dir == ">" and 0 or 10) end -- extern label (extern label reference) local extname = match(label, "^extern%s+(%S+)$") if extname then return "EXT", map_extern[extname] end -- &expr (pointer) if label:sub(1, 1) == "&" then return "A", 0, format("(ptrdiff_t)(%s)", label:sub(2)) end end end local function branch_type(op) if band(op, 0x7c000000) == 0x14000000 then return 0 -- B, BL elseif shr(op, 24) == 0x54 or band(op, 0x7e000000) == 0x34000000 or band(op, 0x3b000000) == 0x18000000 then return 0x800 -- B.cond, CBZ, CBNZ, LDR* literal elseif band(op, 0x7e000000) == 0x36000000 then return 0x1000 -- TBZ, TBNZ elseif band(op, 0x9f000000) == 0x10000000 then return 0x2000 -- ADR elseif band(op, 0x9f000000) == band(0x90000000) then return 0x3000 -- ADRP else assert(false, "unknown branch type") end end ------------------------------------------------------------------------------ local map_op, op_template local function op_alias(opname, f) return function(params, nparams) if not params then return "-> "..opname:sub(1, -3) end f(params, nparams) op_template(params, map_op[opname], nparams) end end local function alias_bfx(p) p[4] = "#("..p[3]:sub(2)..")+("..p[4]:sub(2)..")-1" end local function alias_bfiz(p) parse_reg(p[1], 0) if parse_reg_type == "w" then p[3] = "#(32-("..p[3]:sub(2).."))%32" p[4] = "#("..p[4]:sub(2)..")-1" else p[3] = "#(64-("..p[3]:sub(2).."))%64" p[4] = "#("..p[4]:sub(2)..")-1" end end local alias_lslimm = op_alias("ubfm_4", function(p) parse_reg(p[1], 0) local sh = p[3]:sub(2) if parse_reg_type == "w" then p[3] = "#(32-("..sh.."))%32" p[4] = "#31-("..sh..")" else p[3] = "#(64-("..sh.."))%64" p[4] = "#63-("..sh..")" end end) -- Template strings for ARM instructions. map_op = { -- Basic data processing instructions. add_3 = "0b000000DNMg|11000000pDpNIg|8b206000pDpNMx", add_4 = "0b000000DNMSg|0b200000DNMXg|8b200000pDpNMXx|8b200000pDpNxMwX", adds_3 = "2b000000DNMg|31000000DpNIg|ab206000DpNMx", adds_4 = "2b000000DNMSg|2b200000DNMXg|ab200000DpNMXx|ab200000DpNxMwX", cmn_2 = "2b00001fNMg|3100001fpNIg|ab20601fpNMx", cmn_3 = "2b00001fNMSg|2b20001fNMXg|ab20001fpNMXx|ab20001fpNxMwX", sub_3 = "4b000000DNMg|51000000pDpNIg|cb206000pDpNMx", sub_4 = "4b000000DNMSg|4b200000DNMXg|cb200000pDpNMXx|cb200000pDpNxMwX", subs_3 = "6b000000DNMg|71000000DpNIg|eb206000DpNMx", subs_4 = "6b000000DNMSg|6b200000DNMXg|eb200000DpNMXx|eb200000DpNxMwX", cmp_2 = "6b00001fNMg|7100001fpNIg|eb20601fpNMx", cmp_3 = "6b00001fNMSg|6b20001fNMXg|eb20001fpNMXx|eb20001fpNxMwX", neg_2 = "4b0003e0DMg", neg_3 = "4b0003e0DMSg", negs_2 = "6b0003e0DMg", negs_3 = "6b0003e0DMSg", adc_3 = "1a000000DNMg", adcs_3 = "3a000000DNMg", sbc_3 = "5a000000DNMg", sbcs_3 = "7a000000DNMg", ngc_2 = "5a0003e0DMg", ngcs_2 = "7a0003e0DMg", and_3 = "0a000000DNMg|12000000pDNig", and_4 = "0a000000DNMSg", orr_3 = "2a000000DNMg|32000000pDNig", orr_4 = "2a000000DNMSg", eor_3 = "4a000000DNMg|52000000pDNig", eor_4 = "4a000000DNMSg", ands_3 = "6a000000DNMg|72000000DNig", ands_4 = "6a000000DNMSg", tst_2 = "6a00001fNMg|7200001fNig", tst_3 = "6a00001fNMSg", bic_3 = "0a200000DNMg", bic_4 = "0a200000DNMSg", orn_3 = "2a200000DNMg", orn_4 = "2a200000DNMSg", eon_3 = "4a200000DNMg", eon_4 = "4a200000DNMSg", bics_3 = "6a200000DNMg", bics_4 = "6a200000DNMSg", movn_2 = "12800000DWg", movn_3 = "12800000DWRg", movz_2 = "52800000DWg", movz_3 = "52800000DWRg", movk_2 = "72800000DWg", movk_3 = "72800000DWRg", -- TODO: this doesn't cover all valid immediates for mov reg, #imm. mov_2 = "2a0003e0DMg|52800000DW|320003e0pDig|11000000pDpNg", mov_3 = "2a0003e0DMSg", mvn_2 = "2a2003e0DMg", mvn_3 = "2a2003e0DMSg", adr_2 = "10000000DBx", adrp_2 = "90000000DBx", csel_4 = "1a800000DNMCg", csinc_4 = "1a800400DNMCg", csinv_4 = "5a800000DNMCg", csneg_4 = "5a800400DNMCg", cset_2 = "1a9f07e0Dcg", csetm_2 = "5a9f03e0Dcg", cinc_3 = "1a800400DNmcg", cinv_3 = "5a800000DNmcg", cneg_3 = "5a800400DNmcg", ccmn_4 = "3a400000NMVCg|3a400800N5VCg", ccmp_4 = "7a400000NMVCg|7a400800N5VCg", madd_4 = "1b000000DNMAg", msub_4 = "1b008000DNMAg", mul_3 = "1b007c00DNMg", mneg_3 = "1b00fc00DNMg", smaddl_4 = "9b200000DxNMwAx", smsubl_4 = "9b208000DxNMwAx", smull_3 = "9b207c00DxNMw", smnegl_3 = "9b20fc00DxNMw", smulh_3 = "9b407c00DNMx", umaddl_4 = "9ba00000DxNMwAx", umsubl_4 = "9ba08000DxNMwAx", umull_3 = "9ba07c00DxNMw", umnegl_3 = "9ba0fc00DxNMw", umulh_3 = "9bc07c00DNMx", udiv_3 = "1ac00800DNMg", sdiv_3 = "1ac00c00DNMg", -- Bit operations. sbfm_4 = "13000000DN12w|93400000DN12x", bfm_4 = "33000000DN12w|b3400000DN12x", ubfm_4 = "53000000DN12w|d3400000DN12x", extr_4 = "13800000DNM2w|93c00000DNM2x", sxtb_2 = "13001c00DNw|93401c00DNx", sxth_2 = "13003c00DNw|93403c00DNx", sxtw_2 = "93407c00DxNw", uxtb_2 = "53001c00DNw", uxth_2 = "53003c00DNw", sbfx_4 = op_alias("sbfm_4", alias_bfx), bfxil_4 = op_alias("bfm_4", alias_bfx), ubfx_4 = op_alias("ubfm_4", alias_bfx), sbfiz_4 = op_alias("sbfm_4", alias_bfiz), bfi_4 = op_alias("bfm_4", alias_bfiz), ubfiz_4 = op_alias("ubfm_4", alias_bfiz), lsl_3 = function(params, nparams) if params and params[3]:byte() == 35 then return alias_lslimm(params, nparams) else return op_template(params, "1ac02000DNMg", nparams) end end, lsr_3 = "1ac02400DNMg|53007c00DN1w|d340fc00DN1x", asr_3 = "1ac02800DNMg|13007c00DN1w|9340fc00DN1x", ror_3 = "1ac02c00DNMg|13800000DNm2w|93c00000DNm2x", clz_2 = "5ac01000DNg", cls_2 = "5ac01400DNg", rbit_2 = "5ac00000DNg", rev_2 = "5ac00800DNw|dac00c00DNx", rev16_2 = "5ac00400DNg", rev32_2 = "dac00800DNx", -- Loads and stores. ["strb_*"] = "38000000DwL", ["ldrb_*"] = "38400000DwL", ["ldrsb_*"] = "38c00000DwL|38800000DxL", ["strh_*"] = "78000000DwL", ["ldrh_*"] = "78400000DwL", ["ldrsh_*"] = "78c00000DwL|78800000DxL", ["str_*"] = "b8000000DwL|f8000000DxL|bc000000DsL|fc000000DdL", ["ldr_*"] = "18000000DwB|58000000DxB|1c000000DsB|5c000000DdB|b8400000DwL|f8400000DxL|bc400000DsL|fc400000DdL", ["ldrsw_*"] = "98000000DxB|b8800000DxL", -- NOTE: ldur etc. are handled by ldr et al. ["stp_*"] = "28000000DAwP|a8000000DAxP|2c000000DAsP|6c000000DAdP", ["ldp_*"] = "28400000DAwP|a8400000DAxP|2c400000DAsP|6c400000DAdP", ["ldpsw_*"] = "68400000DAxP", -- Branches. b_1 = "14000000B", bl_1 = "94000000B", blr_1 = "d63f0000Nx", br_1 = "d61f0000Nx", ret_0 = "d65f03c0", ret_1 = "d65f0000Nx", -- b.cond is added below. cbz_2 = "34000000DBg", cbnz_2 = "35000000DBg", tbz_3 = "36000000DTBw|36000000DTBx", tbnz_3 = "37000000DTBw|37000000DTBx", -- Miscellaneous instructions. -- TODO: hlt, hvc, smc, svc, eret, dcps[123], drps, mrs, msr -- TODO: sys, sysl, ic, dc, at, tlbi -- TODO: hint, yield, wfe, wfi, sev, sevl -- TODO: clrex, dsb, dmb, isb nop_0 = "d503201f", brk_0 = "d4200000", brk_1 = "d4200000W", -- Floating point instructions. fmov_2 = "1e204000DNf|1e260000DwNs|1e270000DsNw|9e660000DxNd|9e670000DdNx|1e201000DFf", fabs_2 = "1e20c000DNf", fneg_2 = "1e214000DNf", fsqrt_2 = "1e21c000DNf", fcvt_2 = "1e22c000DdNs|1e624000DsNd", -- TODO: half-precision and fixed-point conversions. fcvtas_2 = "1e240000DwNs|9e240000DxNs|1e640000DwNd|9e640000DxNd", fcvtau_2 = "1e250000DwNs|9e250000DxNs|1e650000DwNd|9e650000DxNd", fcvtms_2 = "1e300000DwNs|9e300000DxNs|1e700000DwNd|9e700000DxNd", fcvtmu_2 = "1e310000DwNs|9e310000DxNs|1e710000DwNd|9e710000DxNd", fcvtns_2 = "1e200000DwNs|9e200000DxNs|1e600000DwNd|9e600000DxNd", fcvtnu_2 = "1e210000DwNs|9e210000DxNs|1e610000DwNd|9e610000DxNd", fcvtps_2 = "1e280000DwNs|9e280000DxNs|1e680000DwNd|9e680000DxNd", fcvtpu_2 = "1e290000DwNs|9e290000DxNs|1e690000DwNd|9e690000DxNd", fcvtzs_2 = "1e380000DwNs|9e380000DxNs|1e780000DwNd|9e780000DxNd", fcvtzu_2 = "1e390000DwNs|9e390000DxNs|1e790000DwNd|9e790000DxNd", scvtf_2 = "1e220000DsNw|9e220000DsNx|1e620000DdNw|9e620000DdNx", ucvtf_2 = "1e230000DsNw|9e230000DsNx|1e630000DdNw|9e630000DdNx", frintn_2 = "1e244000DNf", frintp_2 = "1e24c000DNf", frintm_2 = "1e254000DNf", frintz_2 = "1e25c000DNf", frinta_2 = "1e264000DNf", frintx_2 = "1e274000DNf", frinti_2 = "1e27c000DNf", fadd_3 = "1e202800DNMf", fsub_3 = "1e203800DNMf", fmul_3 = "1e200800DNMf", fnmul_3 = "1e208800DNMf", fdiv_3 = "1e201800DNMf", fmadd_4 = "1f000000DNMAf", fmsub_4 = "1f008000DNMAf", fnmadd_4 = "1f200000DNMAf", fnmsub_4 = "1f208000DNMAf", fmax_3 = "1e204800DNMf", fmaxnm_3 = "1e206800DNMf", fmin_3 = "1e205800DNMf", fminnm_3 = "1e207800DNMf", fcmp_2 = "1e202000NMf|1e202008NZf", fcmpe_2 = "1e202010NMf|1e202018NZf", fccmp_4 = "1e200400NMVCf", fccmpe_4 = "1e200410NMVCf", fcsel_4 = "1e200c00DNMCf", -- TODO: crc32*, aes*, sha*, pmull -- TODO: SIMD instructions. } for cond,c in pairs(map_cond) do map_op["b"..cond.."_1"] = tohex(0x54000000+c).."B" end ------------------------------------------------------------------------------ -- Handle opcodes defined with template strings. local function parse_template(params, template, nparams, pos) local op = tonumber(template:sub(1, 8), 16) local n = 1 local rtt = {} parse_reg_type = false -- Process each character. for p in gmatch(template:sub(9), ".") do local q = params[n] if p == "D" then op = op + parse_reg(q, 0); n = n + 1 elseif p == "N" then op = op + parse_reg(q, 5); n = n + 1 elseif p == "M" then op = op + parse_reg(q, 16); n = n + 1 elseif p == "A" then op = op + parse_reg(q, 10); n = n + 1 elseif p == "m" then op = op + parse_reg(params[n-1], 16) elseif p == "p" then if q == "sp" then params[n] = "@x31" end elseif p == "g" then if parse_reg_type == "x" then op = op + 0x80000000 elseif parse_reg_type ~= "w" then werror("bad register type") end parse_reg_type = false elseif p == "f" then if parse_reg_type == "d" then op = op + 0x00400000 elseif parse_reg_type ~= "s" then werror("bad register type") end parse_reg_type = false elseif p == "x" or p == "w" or p == "d" or p == "s" then if parse_reg_type ~= p then werror("register size mismatch") end parse_reg_type = false elseif p == "L" then op = parse_load(params, nparams, n, op) elseif p == "P" then op = parse_load_pair(params, nparams, n, op) elseif p == "B" then local mode, v, s = parse_label(q, false); n = n + 1 if not mode then werror("bad label `"..q.."'") end local m = branch_type(op) if mode == "A" then waction("REL_"..mode, v+m, format("(unsigned int)(%s)", s)) actargs[#actargs+1] = format("(unsigned int)((%s)>>32)", s) else waction("REL_"..mode, v+m, s, 1) end elseif p == "I" then op = op + parse_imm12(q); n = n + 1 elseif p == "i" then op = op + parse_imm13(q); n = n + 1 elseif p == "W" then op = op + parse_imm(q, 16, 5, 0, false); n = n + 1 elseif p == "T" then op = op + parse_imm6(q); n = n + 1 elseif p == "1" then op = op + parse_imm(q, 6, 16, 0, false); n = n + 1 elseif p == "2" then op = op + parse_imm(q, 6, 10, 0, false); n = n + 1 elseif p == "5" then op = op + parse_imm(q, 5, 16, 0, false); n = n + 1 elseif p == "V" then op = op + parse_imm(q, 4, 0, 0, false); n = n + 1 elseif p == "F" then op = op + parse_fpimm(q); n = n + 1 elseif p == "Z" then if q ~= "#0" and q ~= "#0.0" then werror("expected zero immediate") end n = n + 1 elseif p == "S" then op = op + parse_shift(q); n = n + 1 elseif p == "X" then op = op + parse_extend(q); n = n + 1 elseif p == "R" then op = op + parse_lslx16(q); n = n + 1 elseif p == "C" then op = op + parse_cond(q, 0); n = n + 1 elseif p == "c" then op = op + parse_cond(q, 1); n = n + 1 else assert(false) end end wputpos(pos, op) end function op_template(params, template, nparams) if not params then return template:gsub("%x%x%x%x%x%x%x%x", "") end -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 4 positions. if secpos+4 > maxsecpos then wflush() end local pos = wpos() local lpos, apos, spos = #actlist, #actargs, secpos local ok, err for t in gmatch(template, "[^|]+") do ok, err = pcall(parse_template, params, t, nparams, pos) if ok then return end secpos = spos actlist[lpos+1] = nil actlist[lpos+2] = nil actlist[lpos+3] = nil actlist[lpos+4] = nil actargs[apos+1] = nil actargs[apos+2] = nil actargs[apos+3] = nil actargs[apos+4] = nil end error(err, 0) end map_op[".template__"] = op_template ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_1"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr" end if secpos+1 > maxsecpos then wflush() end local mode, n, s = parse_label(params[1], true) if not mode or mode == "EXT" then werror("bad label definition") end waction("LABEL_"..mode, n, s, 1) end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. local function op_data(params) if not params then return "imm..." end local sz = params.op == ".long" and 4 or 8 for _,p in ipairs(params) do local imm = parse_number(p) if imm then local n = tobit(imm) if n == imm or (n < 0 and n + 2^32 == imm) then wputw(n < 0 and n + 2^32 or n) if sz == 8 then wputw(imm < 0 and 0xffffffff or 0) end elseif sz == 4 then werror("bad immediate `"..p.."'") else imm = nil end end if not imm then local mode, v, s = parse_label(p, false) if sz == 4 then if mode then werror("label does not fit into .long") end waction("IMMV", 0, p) elseif mode and mode ~= "A" then waction("REL_"..mode, v+0x8000, s, 1) else if mode == "A" then p = s end waction("IMMV", 0, format("(unsigned int)(%s)", p)) waction("IMMV", 0, format("(unsigned int)((unsigned long long)(%s)>>32)", p)) end end if secpos+2 > maxsecpos then wflush() end end end map_op[".long_*"] = op_data map_op[".quad_*"] = op_data map_op[".addr_*"] = op_data -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION", num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = map_coreop }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
xLua/build/luajit-2.1.0b3/dynasm/dasm_arm64.lua/0
{ "file_path": "xLua/build/luajit-2.1.0b3/dynasm/dasm_arm64.lua", "repo_id": "xLua", "token_count": 15833 }
2,113
############################################################################## # LuaJIT Makefile. Requires GNU Make. # # Please read doc/install.html before changing any variables! # # Suitable for POSIX platforms (Linux, *BSD, OSX etc.). # Also works with MinGW and Cygwin on Windows. # Please check msvcbuild.bat for building with MSVC on Windows. # # Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h ############################################################################## MAJVER= 2 MINVER= 1 RELVER= 0 ABIVER= 5.1 NODOTABIVER= 51 ############################################################################## ############################# COMPILER OPTIONS ############################# ############################################################################## # These options mainly affect the speed of the JIT compiler itself, not the # speed of the JIT-compiled code. Turn any of the optional settings on by # removing the '#' in front of them. Make sure you force a full recompile # with "make clean", followed by "make" if you change any options. # DEFAULT_CC = gcc # # LuaJIT builds as a native 32 or 64 bit binary by default. CC= $(DEFAULT_CC) # # Use this if you want to force a 32 bit build on a 64 bit multilib OS. #CC= $(DEFAULT_CC) -m32 # # Since the assembler part does NOT maintain a frame pointer, it's pointless # to slow down the C part by not omitting it. Debugging, tracebacks and # unwinding are not affected -- the assembler part has frame unwind # information and GCC emits it where needed (x64) or with -g (see CCDEBUG). CCOPT= -O2 -fomit-frame-pointer # Use this if you want to generate a smaller binary (but it's slower): #CCOPT= -Os -fomit-frame-pointer # Note: it's no longer recommended to use -O3 with GCC 4.x. # The I-Cache bloat usually outweighs the benefits from aggressive inlining. # # Target-specific compiler options: # # x86/x64 only: For GCC 4.2 or higher and if you don't intend to distribute # the binaries to a different machine you could also use: -march=native # CCOPT_x86= -march=i686 -msse -msse2 -mfpmath=sse CCOPT_x64= CCOPT_arm= CCOPT_arm64= CCOPT_ppc= CCOPT_mips= # CCDEBUG= # Uncomment the next line to generate debug information: #CCDEBUG= -g # CCWARN= -Wall # Uncomment the next line to enable more warnings: #CCWARN+= -Wextra -Wdeclaration-after-statement -Wredundant-decls -Wshadow -Wpointer-arith # ############################################################################## ############################################################################## ################################ BUILD MODE ################################ ############################################################################## # The default build mode is mixed mode on POSIX. On Windows this is the same # as dynamic mode. # # Mixed mode creates a static + dynamic library and a statically linked luajit. BUILDMODE= mixed # # Static mode creates a static library and a statically linked luajit. #BUILDMODE= static # # Dynamic mode creates a dynamic library and a dynamically linked luajit. # Note: this executable will only run when the library is installed! #BUILDMODE= dynamic # ############################################################################## ############################################################################## ################################# FEATURES ################################# ############################################################################## # Enable/disable these features as needed, but make sure you force a full # recompile with "make clean", followed by "make". XCFLAGS= # # Permanently disable the FFI extension to reduce the size of the LuaJIT # executable. But please consider that the FFI library is compiled-in, # but NOT loaded by default. It only allocates any memory, if you actually # make use of it. #XCFLAGS+= -DLUAJIT_DISABLE_FFI # # Features from Lua 5.2 that are unlikely to break existing code are # enabled by default. Some other features that *might* break some existing # code (e.g. __pairs or os.execute() return values) can be enabled here. # Note: this does not provide full compatibility with Lua 5.2 at this time. #XCFLAGS+= -DLUAJIT_ENABLE_LUA52COMPAT # # Disable the JIT compiler, i.e. turn LuaJIT into a pure interpreter. #XCFLAGS+= -DLUAJIT_DISABLE_JIT # # Some architectures (e.g. PPC) can use either single-number (1) or # dual-number (2) mode. Uncomment one of these lines to override the # default mode. Please see LJ_ARCH_NUMMODE in lj_arch.h for details. #XCFLAGS+= -DLUAJIT_NUMMODE=1 #XCFLAGS+= -DLUAJIT_NUMMODE=2 # # Disable LJ_GC64 mode for x64. #XCFLAGS+= -DLUAJIT_DISABLE_GC64 # ############################################################################## ############################################################################## ############################ DEBUGGING SUPPORT ############################# ############################################################################## # Enable these options as needed, but make sure you force a full recompile # with "make clean", followed by "make". # Note that most of these are NOT suitable for benchmarking or release mode! # # Use the system provided memory allocator (realloc) instead of the # bundled memory allocator. This is slower, but sometimes helpful for # debugging. This option cannot be enabled on x64 without GC64, since # realloc usually doesn't return addresses in the right address range. # OTOH this option is mandatory for Valgrind's memcheck tool on x64 and # the only way to get useful results from it for all other architectures. #XCFLAGS+= -DLUAJIT_USE_SYSMALLOC # # This define is required to run LuaJIT under Valgrind. The Valgrind # header files must be installed. You should enable debug information, too. #XCFLAGS+= -DLUAJIT_USE_VALGRIND # # This is the client for the GDB JIT API. GDB 7.0 or higher is required # to make use of it. See lj_gdbjit.c for details. Enabling this causes # a non-negligible overhead, even when not running under GDB. #XCFLAGS+= -DLUAJIT_USE_GDBJIT # # Turn on assertions for the Lua/C API to debug problems with lua_* calls. # This is rather slow -- use only while developing C libraries/embeddings. #XCFLAGS+= -DLUA_USE_APICHECK # # Turn on assertions for the whole LuaJIT VM. This significantly slows down # everything. Use only if you suspect a problem with LuaJIT itself. #XCFLAGS+= -DLUA_USE_ASSERT # ############################################################################## # You probably don't need to change anything below this line! ############################################################################## ############################################################################## # Host system detection. ############################################################################## ifeq (Windows,$(findstring Windows,$(OS))$(MSYSTEM)$(TERM)) HOST_SYS= Windows else HOST_SYS:= $(shell uname -s) ifneq (,$(findstring MINGW,$(HOST_SYS))) HOST_SYS= Windows HOST_MSYS= mingw endif ifneq (,$(findstring MSYS,$(HOST_SYS))) HOST_SYS= Windows HOST_MSYS= mingw endif ifneq (,$(findstring CYGWIN,$(HOST_SYS))) HOST_SYS= Windows HOST_MSYS= cygwin endif endif ############################################################################## # Flags and options for host and target. ############################################################################## # You can override the following variables at the make command line: # CC HOST_CC STATIC_CC DYNAMIC_CC # CFLAGS HOST_CFLAGS TARGET_CFLAGS # LDFLAGS HOST_LDFLAGS TARGET_LDFLAGS TARGET_SHLDFLAGS # LIBS HOST_LIBS TARGET_LIBS # CROSS HOST_SYS TARGET_SYS TARGET_FLAGS # # Cross-compilation examples: # make HOST_CC="gcc -m32" CROSS=i586-mingw32msvc- TARGET_SYS=Windows # make HOST_CC="gcc -m32" CROSS=powerpc-linux-gnu- ASOPTIONS= $(CCOPT) $(CCWARN) $(XCFLAGS) $(CFLAGS) CCOPTIONS= $(CCDEBUG) $(ASOPTIONS) LDOPTIONS= $(CCDEBUG) $(LDFLAGS) HOST_CC= $(CC) HOST_RM?= rm -f # If left blank, minilua is built and used. You can supply an installed # copy of (plain) Lua 5.1 or 5.2, plus Lua BitOp. E.g. with: HOST_LUA=lua HOST_LUA= HOST_XCFLAGS= -I. HOST_XLDFLAGS= HOST_XLIBS= HOST_ACFLAGS= $(CCOPTIONS) $(HOST_XCFLAGS) $(TARGET_ARCH) $(HOST_CFLAGS) HOST_ALDFLAGS= $(LDOPTIONS) $(HOST_XLDFLAGS) $(HOST_LDFLAGS) HOST_ALIBS= $(HOST_XLIBS) $(LIBS) $(HOST_LIBS) STATIC_CC = $(CROSS)$(CC) DYNAMIC_CC = $(CROSS)$(CC) -fPIC TARGET_CC= $(STATIC_CC) TARGET_STCC= $(STATIC_CC) TARGET_DYNCC= $(DYNAMIC_CC) TARGET_LD= $(CROSS)$(CC) TARGET_AR= $(CROSS)ar rcus TARGET_STRIP= $(CROSS)strip TARGET_LIBPATH= $(or $(PREFIX),/usr/local)/$(or $(MULTILIB),lib) TARGET_SONAME= libluajit-$(ABIVER).so.$(MAJVER) TARGET_DYLIBNAME= libluajit-$(ABIVER).$(MAJVER).dylib TARGET_DYLIBPATH= $(TARGET_LIBPATH)/$(TARGET_DYLIBNAME) TARGET_DLLNAME= lua$(NODOTABIVER).dll TARGET_DLLDOTANAME= libluajit-$(ABIVER).dll.a TARGET_XSHLDFLAGS= -shared -fPIC -Wl,-soname,$(TARGET_SONAME) TARGET_DYNXLDOPTS= TARGET_LFSFLAGS= -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE TARGET_XCFLAGS= $(TARGET_LFSFLAGS) -U_FORTIFY_SOURCE TARGET_XLDFLAGS= TARGET_XLIBS= -lm TARGET_TCFLAGS= $(CCOPTIONS) $(TARGET_XCFLAGS) $(TARGET_FLAGS) $(TARGET_CFLAGS) TARGET_ACFLAGS= $(CCOPTIONS) $(TARGET_XCFLAGS) $(TARGET_FLAGS) $(TARGET_CFLAGS) TARGET_ASFLAGS= $(ASOPTIONS) $(TARGET_XCFLAGS) $(TARGET_FLAGS) $(TARGET_CFLAGS) TARGET_ALDFLAGS= $(LDOPTIONS) $(TARGET_XLDFLAGS) $(TARGET_FLAGS) $(TARGET_LDFLAGS) TARGET_ASHLDFLAGS= $(LDOPTIONS) $(TARGET_XSHLDFLAGS) $(TARGET_FLAGS) $(TARGET_SHLDFLAGS) TARGET_ALIBS= $(TARGET_XLIBS) $(LIBS) $(TARGET_LIBS) TARGET_TESTARCH=$(shell $(TARGET_CC) $(TARGET_TCFLAGS) -E lj_arch.h -dM) ifneq (,$(findstring LJ_TARGET_X64 ,$(TARGET_TESTARCH))) TARGET_LJARCH= x64 else ifneq (,$(findstring LJ_TARGET_X86 ,$(TARGET_TESTARCH))) TARGET_LJARCH= x86 else ifneq (,$(findstring LJ_TARGET_ARM ,$(TARGET_TESTARCH))) TARGET_LJARCH= arm else ifneq (,$(findstring LJ_TARGET_ARM64 ,$(TARGET_TESTARCH))) ifneq (,$(findstring __AARCH64EB__ ,$(TARGET_TESTARCH))) TARGET_ARCH= -D__AARCH64EB__=1 endif TARGET_LJARCH= arm64 else ifneq (,$(findstring LJ_TARGET_PPC ,$(TARGET_TESTARCH))) ifneq (,$(findstring LJ_LE 1,$(TARGET_TESTARCH))) TARGET_ARCH= -DLJ_ARCH_ENDIAN=LUAJIT_LE else TARGET_ARCH= -DLJ_ARCH_ENDIAN=LUAJIT_BE endif TARGET_LJARCH= ppc else ifneq (,$(findstring LJ_TARGET_MIPS ,$(TARGET_TESTARCH))) ifneq (,$(findstring MIPSEL ,$(TARGET_TESTARCH))) TARGET_ARCH= -D__MIPSEL__=1 endif ifneq (,$(findstring LJ_TARGET_MIPS64 ,$(TARGET_TESTARCH))) TARGET_LJARCH= mips64 else TARGET_LJARCH= mips endif else $(error Unsupported target architecture) endif endif endif endif endif endif ifneq (,$(findstring LJ_TARGET_PS3 1,$(TARGET_TESTARCH))) TARGET_SYS= PS3 TARGET_ARCH+= -D__CELLOS_LV2__ TARGET_XCFLAGS+= -DLUAJIT_USE_SYSMALLOC TARGET_XLIBS+= -lpthread endif TARGET_XCFLAGS+= $(CCOPT_$(TARGET_LJARCH)) TARGET_ARCH+= $(patsubst %,-DLUAJIT_TARGET=LUAJIT_ARCH_%,$(TARGET_LJARCH)) ifneq (,$(PREFIX)) ifneq (/usr/local,$(PREFIX)) TARGET_XCFLAGS+= -DLUA_ROOT=\"$(PREFIX)\" ifneq (/usr,$(PREFIX)) TARGET_DYNXLDOPTS= -Wl,-rpath,$(TARGET_LIBPATH) endif endif endif ifneq (,$(MULTILIB)) TARGET_XCFLAGS+= -DLUA_MULTILIB=\"$(MULTILIB)\" endif ifneq (,$(LMULTILIB)) TARGET_XCFLAGS+= -DLUA_LMULTILIB=\"$(LMULTILIB)\" endif ############################################################################## # Target system detection. ############################################################################## TARGET_SYS?= $(HOST_SYS) ifeq (Windows,$(TARGET_SYS)) TARGET_STRIP+= --strip-unneeded TARGET_XSHLDFLAGS= -shared -Wl,--out-implib,$(TARGET_DLLDOTANAME) TARGET_DYNXLDOPTS= else TARGET_AR+= 2>/dev/null ifeq (,$(shell $(TARGET_CC) -o /dev/null -c -x c /dev/null -fno-stack-protector 2>/dev/null || echo 1)) TARGET_XCFLAGS+= -fno-stack-protector endif ifeq (Darwin,$(TARGET_SYS)) ifeq (,$(MACOSX_DEPLOYMENT_TARGET)) $(error missing: export MACOSX_DEPLOYMENT_TARGET=XX.YY) endif TARGET_STRIP+= -x TARGET_XCFLAGS+= -DLUAJIT_UNWIND_EXTERNAL TARGET_XSHLDFLAGS= -dynamiclib -single_module -undefined dynamic_lookup -fPIC TARGET_DYNXLDOPTS= TARGET_XSHLDFLAGS+= -install_name $(TARGET_DYLIBPATH) -compatibility_version $(MAJVER).$(MINVER) -current_version $(MAJVER).$(MINVER).$(RELVER) else ifeq (iOS,$(TARGET_SYS)) TARGET_STRIP+= -x TARGET_XSHLDFLAGS= -dynamiclib -single_module -undefined dynamic_lookup -fPIC TARGET_DYNXLDOPTS= TARGET_XSHLDFLAGS+= -install_name $(TARGET_DYLIBPATH) -compatibility_version $(MAJVER).$(MINVER) -current_version $(MAJVER).$(MINVER).$(RELVER) ifeq (arm64,$(TARGET_LJARCH)) TARGET_XCFLAGS+= -fno-omit-frame-pointer endif else ifeq (,$(findstring LJ_NO_UNWIND 1,$(TARGET_TESTARCH))) # Find out whether the target toolchain always generates unwind tables. TARGET_TESTUNWIND=$(shell exec 2>/dev/null; echo 'extern void b(void);int a(void){b();return 0;}' | $(TARGET_CC) -c -x c - -o tmpunwind.o && { grep -qa -e eh_frame -e __unwind_info tmpunwind.o || grep -qU -e eh_frame -e __unwind_info tmpunwind.o; } && echo E; rm -f tmpunwind.o) ifneq (,$(findstring E,$(TARGET_TESTUNWIND))) TARGET_XCFLAGS+= -DLUAJIT_UNWIND_EXTERNAL endif endif ifneq (SunOS,$(TARGET_SYS)) ifneq (PS3,$(TARGET_SYS)) TARGET_XLDFLAGS+= -Wl,-E endif endif ifeq (Linux,$(TARGET_SYS)) TARGET_XLIBS+= -ldl endif ifeq (GNU/kFreeBSD,$(TARGET_SYS)) TARGET_XLIBS+= -ldl endif endif endif endif ifneq ($(HOST_SYS),$(TARGET_SYS)) ifeq (Windows,$(TARGET_SYS)) HOST_XCFLAGS+= -malign-double -DLUAJIT_OS=LUAJIT_OS_WINDOWS else ifeq (Linux,$(TARGET_SYS)) HOST_XCFLAGS+= -DLUAJIT_OS=LUAJIT_OS_LINUX else ifeq (Darwin,$(TARGET_SYS)) HOST_XCFLAGS+= -DLUAJIT_OS=LUAJIT_OS_OSX else ifeq (iOS,$(TARGET_SYS)) HOST_XCFLAGS+= -DLUAJIT_OS=LUAJIT_OS_OSX -DTARGET_OS_IPHONE=1 else HOST_XCFLAGS+= -DLUAJIT_OS=LUAJIT_OS_OTHER endif endif endif endif endif ifneq (,$(CCDEBUG)) TARGET_STRIP= @: endif ############################################################################## # Files and pathnames. ############################################################################## MINILUA_O= host/minilua.o MINILUA_LIBS= -lm MINILUA_T= host/minilua MINILUA_X= $(MINILUA_T) ifeq (,$(HOST_LUA)) HOST_LUA= $(MINILUA_X) DASM_DEP= $(MINILUA_T) endif DASM_DIR= ../dynasm DASM= $(HOST_LUA) $(DASM_DIR)/dynasm.lua DASM_XFLAGS= DASM_AFLAGS= DASM_ARCH= $(TARGET_LJARCH) ifneq (,$(findstring LJ_LE 1,$(TARGET_TESTARCH))) DASM_AFLAGS+= -D ENDIAN_LE else DASM_AFLAGS+= -D ENDIAN_BE endif ifneq (,$(findstring LJ_ARCH_BITS 64,$(TARGET_TESTARCH))) DASM_AFLAGS+= -D P64 endif ifneq (,$(findstring LJ_HASJIT 1,$(TARGET_TESTARCH))) DASM_AFLAGS+= -D JIT endif ifneq (,$(findstring LJ_HASFFI 1,$(TARGET_TESTARCH))) DASM_AFLAGS+= -D FFI endif ifneq (,$(findstring LJ_DUALNUM 1,$(TARGET_TESTARCH))) DASM_AFLAGS+= -D DUALNUM endif ifneq (,$(findstring LJ_ARCH_HASFPU 1,$(TARGET_TESTARCH))) DASM_AFLAGS+= -D FPU TARGET_ARCH+= -DLJ_ARCH_HASFPU=1 else TARGET_ARCH+= -DLJ_ARCH_HASFPU=0 endif ifeq (,$(findstring LJ_ABI_SOFTFP 1,$(TARGET_TESTARCH))) DASM_AFLAGS+= -D HFABI TARGET_ARCH+= -DLJ_ABI_SOFTFP=0 else TARGET_ARCH+= -DLJ_ABI_SOFTFP=1 endif ifneq (,$(findstring LJ_NO_UNWIND 1,$(TARGET_TESTARCH))) DASM_AFLAGS+= -D NO_UNWIND TARGET_ARCH+= -DLUAJIT_NO_UNWIND endif DASM_AFLAGS+= -D VER=$(subst LJ_ARCH_VERSION_,,$(filter LJ_ARCH_VERSION_%,$(subst LJ_ARCH_VERSION ,LJ_ARCH_VERSION_,$(TARGET_TESTARCH)))) ifeq (Windows,$(TARGET_SYS)) DASM_AFLAGS+= -D WIN endif ifeq (x64,$(TARGET_LJARCH)) ifeq (,$(findstring LJ_FR2 1,$(TARGET_TESTARCH))) DASM_ARCH= x86 endif else ifeq (arm,$(TARGET_LJARCH)) ifeq (iOS,$(TARGET_SYS)) DASM_AFLAGS+= -D IOS endif else ifneq (,$(findstring LJ_TARGET_MIPSR6 ,$(TARGET_TESTARCH))) DASM_AFLAGS+= -D MIPSR6 endif ifeq (ppc,$(TARGET_LJARCH)) ifneq (,$(findstring LJ_ARCH_SQRT 1,$(TARGET_TESTARCH))) DASM_AFLAGS+= -D SQRT endif ifneq (,$(findstring LJ_ARCH_ROUND 1,$(TARGET_TESTARCH))) DASM_AFLAGS+= -D ROUND endif ifneq (,$(findstring LJ_ARCH_PPC32ON64 1,$(TARGET_TESTARCH))) DASM_AFLAGS+= -D GPR64 endif ifeq (PS3,$(TARGET_SYS)) DASM_AFLAGS+= -D PPE -D TOC endif endif endif endif DASM_FLAGS= $(DASM_XFLAGS) $(DASM_AFLAGS) DASM_DASC= vm_$(DASM_ARCH).dasc BUILDVM_O= host/buildvm.o host/buildvm_asm.o host/buildvm_peobj.o \ host/buildvm_lib.o host/buildvm_fold.o BUILDVM_T= host/buildvm BUILDVM_X= $(BUILDVM_T) HOST_O= $(MINILUA_O) $(BUILDVM_O) HOST_T= $(MINILUA_T) $(BUILDVM_T) LJVM_S= lj_vm.S LJVM_O= lj_vm.o LJVM_BOUT= $(LJVM_S) LJVM_MODE= elfasm LJLIB_O= lib_base.o lib_math.o lib_bit.o lib_string.o lib_table.o \ lib_io.o lib_os.o lib_package.o lib_debug.o lib_jit.o lib_ffi.o \ lib_buffer.o LJLIB_C= $(LJLIB_O:.o=.c) LJCORE_O= lj_assert.o lj_gc.o lj_err.o lj_char.o lj_bc.o lj_obj.o lj_buf.o \ lj_str.o lj_tab.o lj_func.o lj_udata.o lj_meta.o lj_debug.o \ lj_prng.o lj_state.o lj_dispatch.o lj_vmevent.o lj_vmmath.o \ lj_strscan.o lj_strfmt.o lj_strfmt_num.o lj_serialize.o \ lj_api.o lj_profile.o \ lj_lex.o lj_parse.o lj_bcread.o lj_bcwrite.o lj_load.o \ lj_ir.o lj_opt_mem.o lj_opt_fold.o lj_opt_narrow.o \ lj_opt_dce.o lj_opt_loop.o lj_opt_split.o lj_opt_sink.o \ lj_mcode.o lj_snap.o lj_record.o lj_crecord.o lj_ffrecord.o \ lj_asm.o lj_trace.o lj_gdbjit.o \ lj_ctype.o lj_cdata.o lj_cconv.o lj_ccall.o lj_ccallback.o \ lj_carith.o lj_clib.o lj_cparse.o \ lj_lib.o lj_alloc.o lib_aux.o \ $(LJLIB_O) lib_init.o LJVMCORE_O= $(LJVM_O) $(LJCORE_O) LJVMCORE_DYNO= $(LJVMCORE_O:.o=_dyn.o) LIB_VMDEF= jit/vmdef.lua LIB_VMDEFP= $(LIB_VMDEF) LUAJIT_O= luajit.o LUAJIT_A= libluajit.a LUAJIT_SO= libluajit.so LUAJIT_T= luajit ALL_T= $(LUAJIT_T) $(LUAJIT_A) $(LUAJIT_SO) $(HOST_T) ALL_HDRGEN= lj_bcdef.h lj_ffdef.h lj_libdef.h lj_recdef.h lj_folddef.h \ host/buildvm_arch.h ALL_GEN= $(LJVM_S) $(ALL_HDRGEN) $(LIB_VMDEFP) WIN_RM= *.obj *.lib *.exp *.dll *.exe *.manifest *.pdb *.ilk ALL_RM= $(ALL_T) $(ALL_GEN) *.o host/*.o $(WIN_RM) ############################################################################## # Build mode handling. ############################################################################## # Mixed mode defaults. TARGET_O= $(LUAJIT_A) TARGET_T= $(LUAJIT_T) $(LUAJIT_SO) TARGET_DEP= $(LIB_VMDEF) $(LUAJIT_SO) ifeq (Windows,$(TARGET_SYS)) TARGET_DYNCC= $(STATIC_CC) LJVM_MODE= peobj LJVM_BOUT= $(LJVM_O) LUAJIT_T= luajit.exe ifeq (cygwin,$(HOST_MSYS)) LUAJIT_SO= cyg$(TARGET_DLLNAME) else LUAJIT_SO= $(TARGET_DLLNAME) endif # Mixed mode is not supported on Windows. And static mode doesn't work well. # C modules cannot be loaded, because they bind to lua51.dll. ifneq (static,$(BUILDMODE)) BUILDMODE= dynamic TARGET_XCFLAGS+= -DLUA_BUILD_AS_DLL endif endif ifeq (Darwin,$(TARGET_SYS)) LJVM_MODE= machasm endif ifeq (iOS,$(TARGET_SYS)) LJVM_MODE= machasm endif ifeq (SunOS,$(TARGET_SYS)) BUILDMODE= static endif ifeq (PS3,$(TARGET_SYS)) BUILDMODE= static endif ifeq (Windows,$(HOST_SYS)) MINILUA_T= host/minilua.exe BUILDVM_T= host/buildvm.exe ifeq (,$(HOST_MSYS)) MINILUA_X= host\minilua BUILDVM_X= host\buildvm ALL_RM:= $(subst /,\,$(ALL_RM)) HOST_RM= del endif endif ifeq (static,$(BUILDMODE)) TARGET_DYNCC= @: TARGET_T= $(LUAJIT_T) TARGET_DEP= $(LIB_VMDEF) else ifeq (dynamic,$(BUILDMODE)) ifneq (Windows,$(TARGET_SYS)) TARGET_CC= $(DYNAMIC_CC) endif TARGET_DYNCC= @: LJVMCORE_DYNO= $(LJVMCORE_O) TARGET_O= $(LUAJIT_SO) TARGET_XLDFLAGS+= $(TARGET_DYNXLDOPTS) else ifeq (Darwin,$(TARGET_SYS)) TARGET_DYNCC= @: LJVMCORE_DYNO= $(LJVMCORE_O) endif ifeq (iOS,$(TARGET_SYS)) TARGET_DYNCC= @: LJVMCORE_DYNO= $(LJVMCORE_O) endif endif endif Q= @ E= @echo #Q= #E= @: ############################################################################## # Make targets. ############################################################################## default all: $(TARGET_T) amalg: $(MAKE) all "LJCORE_O=ljamalg.o" clean: $(HOST_RM) $(ALL_RM) libbc: ./$(LUAJIT_T) host/genlibbc.lua -o host/buildvm_libbc.h $(LJLIB_C) $(MAKE) all depend: @for file in $(ALL_HDRGEN); do \ test -f $$file || touch $$file; \ done @$(HOST_CC) $(HOST_ACFLAGS) -MM *.c host/*.c | \ sed -e "s| [^ ]*/dasm_\S*\.h||g" \ -e "s|^\([^l ]\)|host/\1|" \ -e "s| lj_target_\S*\.h| lj_target_*.h|g" \ -e "s| lj_emit_\S*\.h| lj_emit_*.h|g" \ -e "s| lj_asm_\S*\.h| lj_asm_*.h|g" >Makefile.dep @for file in $(ALL_HDRGEN); do \ test -s $$file || $(HOST_RM) $$file; \ done .PHONY: default all amalg clean libbc depend ############################################################################## # Rules for generated files. ############################################################################## $(MINILUA_T): $(MINILUA_O) $(E) "HOSTLINK $@" $(Q)$(HOST_CC) $(HOST_ALDFLAGS) -o $@ $(MINILUA_O) $(MINILUA_LIBS) $(HOST_ALIBS) host/buildvm_arch.h: $(DASM_DASC) $(DASM_DEP) $(DASM_DIR)/*.lua lj_arch.h lua.h luaconf.h $(E) "DYNASM $@" $(Q)$(DASM) $(DASM_FLAGS) -o $@ $(DASM_DASC) host/buildvm.o: $(DASM_DIR)/dasm_*.h $(BUILDVM_T): $(BUILDVM_O) $(E) "HOSTLINK $@" $(Q)$(HOST_CC) $(HOST_ALDFLAGS) -o $@ $(BUILDVM_O) $(HOST_ALIBS) $(LJVM_BOUT): $(BUILDVM_T) $(E) "BUILDVM $@" $(Q)$(BUILDVM_X) -m $(LJVM_MODE) -o $@ lj_bcdef.h: $(BUILDVM_T) $(LJLIB_C) $(E) "BUILDVM $@" $(Q)$(BUILDVM_X) -m bcdef -o $@ $(LJLIB_C) lj_ffdef.h: $(BUILDVM_T) $(LJLIB_C) $(E) "BUILDVM $@" $(Q)$(BUILDVM_X) -m ffdef -o $@ $(LJLIB_C) lj_libdef.h: $(BUILDVM_T) $(LJLIB_C) $(E) "BUILDVM $@" $(Q)$(BUILDVM_X) -m libdef -o $@ $(LJLIB_C) lj_recdef.h: $(BUILDVM_T) $(LJLIB_C) $(E) "BUILDVM $@" $(Q)$(BUILDVM_X) -m recdef -o $@ $(LJLIB_C) $(LIB_VMDEF): $(BUILDVM_T) $(LJLIB_C) $(E) "BUILDVM $@" $(Q)$(BUILDVM_X) -m vmdef -o $(LIB_VMDEFP) $(LJLIB_C) lj_folddef.h: $(BUILDVM_T) lj_opt_fold.c $(E) "BUILDVM $@" $(Q)$(BUILDVM_X) -m folddef -o $@ lj_opt_fold.c ############################################################################## # Object file rules. ############################################################################## %.o: %.c $(E) "CC $@" $(Q)$(TARGET_DYNCC) $(TARGET_ACFLAGS) -c -o $(@:.o=_dyn.o) $< $(Q)$(TARGET_CC) $(TARGET_ACFLAGS) -c -o $@ $< %.o: %.S $(E) "ASM $@" $(Q)$(TARGET_DYNCC) $(TARGET_ASFLAGS) -c -o $(@:.o=_dyn.o) $< $(Q)$(TARGET_CC) $(TARGET_ASFLAGS) -c -o $@ $< $(LUAJIT_O): $(E) "CC $@" $(Q)$(TARGET_STCC) $(TARGET_ACFLAGS) -c -o $@ $< $(HOST_O): %.o: %.c $(E) "HOSTCC $@" $(Q)$(HOST_CC) $(HOST_ACFLAGS) -c -o $@ $< include Makefile.dep ############################################################################## # Target file rules. ############################################################################## $(LUAJIT_A): $(LJVMCORE_O) $(E) "AR $@" $(Q)$(TARGET_AR) $@ $(LJVMCORE_O) # The dependency on _O, but linking with _DYNO is intentional. $(LUAJIT_SO): $(LJVMCORE_O) $(E) "DYNLINK $@" $(Q)$(TARGET_LD) $(TARGET_ASHLDFLAGS) -o $@ $(LJVMCORE_DYNO) $(TARGET_ALIBS) $(Q)$(TARGET_STRIP) $@ $(LUAJIT_T): $(TARGET_O) $(LUAJIT_O) $(TARGET_DEP) $(E) "LINK $@" $(Q)$(TARGET_LD) $(TARGET_ALDFLAGS) -o $@ $(LUAJIT_O) $(TARGET_O) $(TARGET_ALIBS) $(Q)$(TARGET_STRIP) $@ $(E) "OK Successfully built LuaJIT" ##############################################################################
xLua/build/luajit-2.1.0b3/src/Makefile/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/Makefile", "repo_id": "xLua", "token_count": 10041 }
2,114
---------------------------------------------------------------------------- -- LuaJIT module to save/list bytecode. -- -- Copyright (C) 2005-2021 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module saves or lists the bytecode for an input file. -- It's run by the -b command line option. -- ------------------------------------------------------------------------------ local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local bit = require("bit") -- Symbol name prefix for LuaJIT bytecode. local LJBC_PREFIX = "luaJIT_BC_" local type, assert = type, assert local format = string.format local tremove, tconcat = table.remove, table.concat ------------------------------------------------------------------------------ local function usage() io.stderr:write[[ Save LuaJIT bytecode: luajit -b[options] input output -l Only list bytecode. -s Strip debug info (default). -g Keep debug info. -n name Set module name (default: auto-detect from input name). -t type Set output file type (default: auto-detect from output name). -a arch Override architecture for object files (default: native). -o os Override OS for object files (default: native). -e chunk Use chunk string as input. -- Stop handling options. - Use stdin as input and/or stdout as output. File types: c h obj o raw (default) ]] os.exit(1) end local function check(ok, ...) if ok then return ok, ... end io.stderr:write("luajit: ", ...) io.stderr:write("\n") os.exit(1) end local function readfile(input) if type(input) == "function" then return input end if input == "-" then input = nil end return check(loadfile(input)) end local function savefile(name, mode) if name == "-" then return io.stdout end return check(io.open(name, mode)) end local function set_stdout_binary(ffi) ffi.cdef[[int _setmode(int fd, int mode);]] ffi.C._setmode(1, 0x8000) end ------------------------------------------------------------------------------ local map_type = { raw = "raw", c = "c", h = "h", o = "obj", obj = "obj", } local map_arch = { x86 = { e = "le", b = 32, m = 3, p = 0x14c, }, x64 = { e = "le", b = 64, m = 62, p = 0x8664, }, arm = { e = "le", b = 32, m = 40, p = 0x1c0, }, arm64 = { e = "le", b = 64, m = 183, p = 0xaa64, }, arm64be = { e = "be", b = 64, m = 183, }, ppc = { e = "be", b = 32, m = 20, }, mips = { e = "be", b = 32, m = 8, f = 0x50001006, }, mipsel = { e = "le", b = 32, m = 8, f = 0x50001006, }, mips64 = { e = "be", b = 64, m = 8, f = 0x80000007, }, mips64el = { e = "le", b = 64, m = 8, f = 0x80000007, }, mips64r6 = { e = "be", b = 64, m = 8, f = 0xa0000407, }, mips64r6el = { e = "le", b = 64, m = 8, f = 0xa0000407, }, } local map_os = { linux = true, windows = true, osx = true, freebsd = true, netbsd = true, openbsd = true, dragonfly = true, solaris = true, } local function checkarg(str, map, err) str = str:lower() local s = check(map[str], "unknown ", err) return type(s) == "string" and s or str end local function detecttype(str) local ext = str:lower():match("%.(%a+)$") return map_type[ext] or "raw" end local function checkmodname(str) check(str:match("^[%w_.%-]+$"), "bad module name") return str:gsub("[%.%-]", "_") end local function detectmodname(str) if type(str) == "string" then local tail = str:match("[^/\\]+$") if tail then str = tail end local head = str:match("^(.*)%.[^.]*$") if head then str = head end str = str:match("^[%w_.%-]+") else str = nil end check(str, "cannot derive module name, use -n name") return str:gsub("[%.%-]", "_") end ------------------------------------------------------------------------------ local function bcsave_tail(fp, output, s) local ok, err = fp:write(s) if ok and output ~= "-" then ok, err = fp:close() end check(ok, "cannot write ", output, ": ", err) end local function bcsave_raw(output, s) if output == "-" and jit.os == "Windows" then local ok, ffi = pcall(require, "ffi") check(ok, "FFI library required to write binary file to stdout") set_stdout_binary(ffi) end local fp = savefile(output, "wb") bcsave_tail(fp, output, s) end local function bcsave_c(ctx, output, s) local fp = savefile(output, "w") if ctx.type == "c" then fp:write(format([[ #ifdef __cplusplus extern "C" #endif #ifdef _WIN32 __declspec(dllexport) #endif const unsigned char %s%s[] = { ]], LJBC_PREFIX, ctx.modname)) else fp:write(format([[ #define %s%s_SIZE %d static const unsigned char %s%s[] = { ]], LJBC_PREFIX, ctx.modname, #s, LJBC_PREFIX, ctx.modname)) end local t, n, m = {}, 0, 0 for i=1,#s do local b = tostring(string.byte(s, i)) m = m + #b + 1 if m > 78 then fp:write(tconcat(t, ",", 1, n), ",\n") n, m = 0, #b + 1 end n = n + 1 t[n] = b end bcsave_tail(fp, output, tconcat(t, ",", 1, n).."\n};\n") end local function bcsave_elfobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7]; uint16_t type, machine; uint32_t version; uint32_t entry, phofs, shofs; uint32_t flags; uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx; } ELF32header; typedef struct { uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7]; uint16_t type, machine; uint32_t version; uint64_t entry, phofs, shofs; uint32_t flags; uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx; } ELF64header; typedef struct { uint32_t name, type, flags, addr, ofs, size, link, info, align, entsize; } ELF32sectheader; typedef struct { uint32_t name, type; uint64_t flags, addr, ofs, size; uint32_t link, info; uint64_t align, entsize; } ELF64sectheader; typedef struct { uint32_t name, value, size; uint8_t info, other; uint16_t sectidx; } ELF32symbol; typedef struct { uint32_t name; uint8_t info, other; uint16_t sectidx; uint64_t value, size; } ELF64symbol; typedef struct { ELF32header hdr; ELF32sectheader sect[6]; ELF32symbol sym[2]; uint8_t space[4096]; } ELF32obj; typedef struct { ELF64header hdr; ELF64sectheader sect[6]; ELF64symbol sym[2]; uint8_t space[4096]; } ELF64obj; ]] local symname = LJBC_PREFIX..ctx.modname local ai = assert(map_arch[ctx.arch]) local is64, isbe = ai.b == 64, ai.e == "be" -- Handle different host/target endianess. local function f32(x) return x end local f16, fofs = f32, f32 if ffi.abi("be") ~= isbe then f32 = bit.bswap function f16(x) return bit.rshift(bit.bswap(x), 16) end if is64 then local two32 = ffi.cast("int64_t", 2^32) function fofs(x) return bit.bswap(x)*two32 end else fofs = f32 end end -- Create ELF object and fill in header. local o = ffi.new(is64 and "ELF64obj" or "ELF32obj") local hdr = o.hdr if ctx.os == "bsd" or ctx.os == "other" then -- Determine native hdr.eosabi. local bf = assert(io.open("/bin/ls", "rb")) local bs = bf:read(9) bf:close() ffi.copy(o, bs, 9) check(hdr.emagic[0] == 127, "no support for writing native object files") else hdr.emagic = "\127ELF" hdr.eosabi = ({ freebsd=9, netbsd=2, openbsd=12, solaris=6 })[ctx.os] or 0 end hdr.eclass = is64 and 2 or 1 hdr.eendian = isbe and 2 or 1 hdr.eversion = 1 hdr.type = f16(1) hdr.machine = f16(ai.m) hdr.flags = f32(ai.f or 0) hdr.version = f32(1) hdr.shofs = fofs(ffi.offsetof(o, "sect")) hdr.ehsize = f16(ffi.sizeof(hdr)) hdr.shentsize = f16(ffi.sizeof(o.sect[0])) hdr.shnum = f16(6) hdr.shstridx = f16(2) -- Fill in sections and symbols. local sofs, ofs = ffi.offsetof(o, "space"), 1 for i,name in ipairs{ ".symtab", ".shstrtab", ".strtab", ".rodata", ".note.GNU-stack", } do local sect = o.sect[i] sect.align = fofs(1) sect.name = f32(ofs) ffi.copy(o.space+ofs, name) ofs = ofs + #name+1 end o.sect[1].type = f32(2) -- .symtab o.sect[1].link = f32(3) o.sect[1].info = f32(1) o.sect[1].align = fofs(8) o.sect[1].ofs = fofs(ffi.offsetof(o, "sym")) o.sect[1].entsize = fofs(ffi.sizeof(o.sym[0])) o.sect[1].size = fofs(ffi.sizeof(o.sym)) o.sym[1].name = f32(1) o.sym[1].sectidx = f16(4) o.sym[1].size = fofs(#s) o.sym[1].info = 17 o.sect[2].type = f32(3) -- .shstrtab o.sect[2].ofs = fofs(sofs) o.sect[2].size = fofs(ofs) o.sect[3].type = f32(3) -- .strtab o.sect[3].ofs = fofs(sofs + ofs) o.sect[3].size = fofs(#symname+2) ffi.copy(o.space+ofs+1, symname) ofs = ofs + #symname + 2 o.sect[4].type = f32(1) -- .rodata o.sect[4].flags = fofs(2) o.sect[4].ofs = fofs(sofs + ofs) o.sect[4].size = fofs(#s) o.sect[5].type = f32(1) -- .note.GNU-stack o.sect[5].ofs = fofs(sofs + ofs + #s) -- Write ELF object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs)) bcsave_tail(fp, output, s) end local function bcsave_peobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint16_t arch, nsects; uint32_t time, symtabofs, nsyms; uint16_t opthdrsz, flags; } PEheader; typedef struct { char name[8]; uint32_t vsize, vaddr, size, ofs, relocofs, lineofs; uint16_t nreloc, nline; uint32_t flags; } PEsection; typedef struct __attribute((packed)) { union { char name[8]; uint32_t nameref[2]; }; uint32_t value; int16_t sect; uint16_t type; uint8_t scl, naux; } PEsym; typedef struct __attribute((packed)) { uint32_t size; uint16_t nreloc, nline; uint32_t cksum; uint16_t assoc; uint8_t comdatsel, unused[3]; } PEsymaux; typedef struct { PEheader hdr; PEsection sect[2]; // Must be an even number of symbol structs. PEsym sym0; PEsymaux sym0aux; PEsym sym1; PEsymaux sym1aux; PEsym sym2; PEsym sym3; uint32_t strtabsize; uint8_t space[4096]; } PEobj; ]] local symname = LJBC_PREFIX..ctx.modname local ai = assert(map_arch[ctx.arch]) local is64 = ai.b == 64 local symexport = " /EXPORT:"..symname..",DATA " -- The file format is always little-endian. Swap if the host is big-endian. local function f32(x) return x end local f16 = f32 if ffi.abi("be") then f32 = bit.bswap function f16(x) return bit.rshift(bit.bswap(x), 16) end end -- Create PE object and fill in header. local o = ffi.new("PEobj") local hdr = o.hdr hdr.arch = f16(assert(ai.p)) hdr.nsects = f16(2) hdr.symtabofs = f32(ffi.offsetof(o, "sym0")) hdr.nsyms = f32(6) -- Fill in sections and symbols. o.sect[0].name = ".drectve" o.sect[0].size = f32(#symexport) o.sect[0].flags = f32(0x00100a00) o.sym0.sect = f16(1) o.sym0.scl = 3 o.sym0.name = ".drectve" o.sym0.naux = 1 o.sym0aux.size = f32(#symexport) o.sect[1].name = ".rdata" o.sect[1].size = f32(#s) o.sect[1].flags = f32(0x40300040) o.sym1.sect = f16(2) o.sym1.scl = 3 o.sym1.name = ".rdata" o.sym1.naux = 1 o.sym1aux.size = f32(#s) o.sym2.sect = f16(2) o.sym2.scl = 2 o.sym2.nameref[1] = f32(4) o.sym3.sect = f16(-1) o.sym3.scl = 2 o.sym3.value = f32(1) o.sym3.name = "@feat.00" -- Mark as SafeSEH compliant. ffi.copy(o.space, symname) local ofs = #symname + 1 o.strtabsize = f32(ofs + 4) o.sect[0].ofs = f32(ffi.offsetof(o, "space") + ofs) ffi.copy(o.space + ofs, symexport) ofs = ofs + #symexport o.sect[1].ofs = f32(ffi.offsetof(o, "space") + ofs) -- Write PE object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs)) bcsave_tail(fp, output, s) end local function bcsave_machobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint32_t magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags; } mach_header; typedef struct { mach_header; uint32_t reserved; } mach_header_64; typedef struct { uint32_t cmd, cmdsize; char segname[16]; uint32_t vmaddr, vmsize, fileoff, filesize; uint32_t maxprot, initprot, nsects, flags; } mach_segment_command; typedef struct { uint32_t cmd, cmdsize; char segname[16]; uint64_t vmaddr, vmsize, fileoff, filesize; uint32_t maxprot, initprot, nsects, flags; } mach_segment_command_64; typedef struct { char sectname[16], segname[16]; uint32_t addr, size; uint32_t offset, align, reloff, nreloc, flags; uint32_t reserved1, reserved2; } mach_section; typedef struct { char sectname[16], segname[16]; uint64_t addr, size; uint32_t offset, align, reloff, nreloc, flags; uint32_t reserved1, reserved2, reserved3; } mach_section_64; typedef struct { uint32_t cmd, cmdsize, symoff, nsyms, stroff, strsize; } mach_symtab_command; typedef struct { int32_t strx; uint8_t type, sect; int16_t desc; uint32_t value; } mach_nlist; typedef struct { uint32_t strx; uint8_t type, sect; uint16_t desc; uint64_t value; } mach_nlist_64; typedef struct { uint32_t magic, nfat_arch; } mach_fat_header; typedef struct { uint32_t cputype, cpusubtype, offset, size, align; } mach_fat_arch; typedef struct { struct { mach_header hdr; mach_segment_command seg; mach_section sec; mach_symtab_command sym; } arch[1]; mach_nlist sym_entry; uint8_t space[4096]; } mach_obj; typedef struct { struct { mach_header_64 hdr; mach_segment_command_64 seg; mach_section_64 sec; mach_symtab_command sym; } arch[1]; mach_nlist_64 sym_entry; uint8_t space[4096]; } mach_obj_64; typedef struct { mach_fat_header fat; mach_fat_arch fat_arch[2]; struct { mach_header hdr; mach_segment_command seg; mach_section sec; mach_symtab_command sym; } arch[2]; mach_nlist sym_entry; uint8_t space[4096]; } mach_fat_obj; ]] local symname = '_'..LJBC_PREFIX..ctx.modname local isfat, is64, align, mobj = false, false, 4, "mach_obj" if ctx.arch == "x64" then is64, align, mobj = true, 8, "mach_obj_64" elseif ctx.arch == "arm" then isfat, mobj = true, "mach_fat_obj" elseif ctx.arch == "arm64" then is64, align, isfat, mobj = true, 8, true, "mach_fat_obj" else check(ctx.arch == "x86", "unsupported architecture for OSX") end local function aligned(v, a) return bit.band(v+a-1, -a) end local be32 = bit.bswap -- Mach-O FAT is BE, supported archs are LE. -- Create Mach-O object and fill in header. local o = ffi.new(mobj) local mach_size = aligned(ffi.offsetof(o, "space")+#symname+2, align) local cputype = ({ x86={7}, x64={0x01000007}, arm={7,12}, arm64={0x01000007,0x0100000c} })[ctx.arch] local cpusubtype = ({ x86={3}, x64={3}, arm={3,9}, arm64={3,0} })[ctx.arch] if isfat then o.fat.magic = be32(0xcafebabe) o.fat.nfat_arch = be32(#cpusubtype) end -- Fill in sections and symbols. for i=0,#cpusubtype-1 do local ofs = 0 if isfat then local a = o.fat_arch[i] a.cputype = be32(cputype[i+1]) a.cpusubtype = be32(cpusubtype[i+1]) -- Subsequent slices overlap each other to share data. ofs = ffi.offsetof(o, "arch") + i*ffi.sizeof(o.arch[0]) a.offset = be32(ofs) a.size = be32(mach_size-ofs+#s) end local a = o.arch[i] a.hdr.magic = is64 and 0xfeedfacf or 0xfeedface a.hdr.cputype = cputype[i+1] a.hdr.cpusubtype = cpusubtype[i+1] a.hdr.filetype = 1 a.hdr.ncmds = 2 a.hdr.sizeofcmds = ffi.sizeof(a.seg)+ffi.sizeof(a.sec)+ffi.sizeof(a.sym) a.seg.cmd = is64 and 0x19 or 0x1 a.seg.cmdsize = ffi.sizeof(a.seg)+ffi.sizeof(a.sec) a.seg.vmsize = #s a.seg.fileoff = mach_size-ofs a.seg.filesize = #s a.seg.maxprot = 1 a.seg.initprot = 1 a.seg.nsects = 1 ffi.copy(a.sec.sectname, "__data") ffi.copy(a.sec.segname, "__DATA") a.sec.size = #s a.sec.offset = mach_size-ofs a.sym.cmd = 2 a.sym.cmdsize = ffi.sizeof(a.sym) a.sym.symoff = ffi.offsetof(o, "sym_entry")-ofs a.sym.nsyms = 1 a.sym.stroff = ffi.offsetof(o, "sym_entry")+ffi.sizeof(o.sym_entry)-ofs a.sym.strsize = aligned(#symname+2, align) end o.sym_entry.type = 0xf o.sym_entry.sect = 1 o.sym_entry.strx = 1 ffi.copy(o.space+1, symname) -- Write Macho-O object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, mach_size)) bcsave_tail(fp, output, s) end local function bcsave_obj(ctx, output, s) local ok, ffi = pcall(require, "ffi") check(ok, "FFI library required to write this file type") if output == "-" and jit.os == "Windows" then set_stdout_binary(ffi) end if ctx.os == "windows" then return bcsave_peobj(ctx, output, s, ffi) elseif ctx.os == "osx" then return bcsave_machobj(ctx, output, s, ffi) else return bcsave_elfobj(ctx, output, s, ffi) end end ------------------------------------------------------------------------------ local function bclist(input, output) local f = readfile(input) require("jit.bc").dump(f, savefile(output, "w"), true) end local function bcsave(ctx, input, output) local f = readfile(input) local s = string.dump(f, ctx.strip) local t = ctx.type if not t then t = detecttype(output) ctx.type = t end if t == "raw" then bcsave_raw(output, s) else if not ctx.modname then ctx.modname = detectmodname(input) end if t == "obj" then bcsave_obj(ctx, output, s) else bcsave_c(ctx, output, s) end end end local function docmd(...) local arg = {...} local n = 1 local list = false local ctx = { strip = true, arch = jit.arch, os = jit.os:lower(), type = false, modname = false, } while n <= #arg do local a = arg[n] if type(a) == "string" and a:sub(1, 1) == "-" and a ~= "-" then tremove(arg, n) if a == "--" then break end for m=2,#a do local opt = a:sub(m, m) if opt == "l" then list = true elseif opt == "s" then ctx.strip = true elseif opt == "g" then ctx.strip = false else if arg[n] == nil or m ~= #a then usage() end if opt == "e" then if n ~= 1 then usage() end arg[1] = check(loadstring(arg[1])) elseif opt == "n" then ctx.modname = checkmodname(tremove(arg, n)) elseif opt == "t" then ctx.type = checkarg(tremove(arg, n), map_type, "file type") elseif opt == "a" then ctx.arch = checkarg(tremove(arg, n), map_arch, "architecture") elseif opt == "o" then ctx.os = checkarg(tremove(arg, n), map_os, "OS name") else usage() end end end else n = n + 1 end end if list then if #arg == 0 or #arg > 2 then usage() end bclist(arg[1], arg[2] or "-") else if #arg ~= 2 then usage() end bcsave(ctx, arg[1], arg[2]) end end ------------------------------------------------------------------------------ -- Public module functions. return { start = docmd -- Process -b command line option. }
xLua/build/luajit-2.1.0b3/src/jit/bcsave.lua/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/jit/bcsave.lua", "repo_id": "xLua", "token_count": 8227 }
2,115
---------------------------------------------------------------------------- -- LuaJIT profiler zones. -- -- Copyright (C) 2005-2021 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module implements a simple hierarchical zone model. -- -- Example usage: -- -- local zone = require("jit.zone") -- zone("AI") -- ... -- zone("A*") -- ... -- print(zone:get()) --> "A*" -- ... -- zone() -- ... -- print(zone:get()) --> "AI" -- ... -- zone() -- ---------------------------------------------------------------------------- local remove = table.remove return setmetatable({ flush = function(t) for i=#t,1,-1 do t[i] = nil end end, get = function(t) return t[#t] end }, { __call = function(t, zone) if zone then t[#t+1] = zone else return (assert(remove(t), "empty zone stack")) end end })
xLua/build/luajit-2.1.0b3/src/jit/zone.lua/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/jit/zone.lua", "repo_id": "xLua", "token_count": 323 }
2,116
# Valgrind suppression file for LuaJIT 2.0. { Optimized string compare Memcheck:Addr4 fun:lj_str_cmp } { Optimized string compare Memcheck:Addr1 fun:lj_str_cmp } { Optimized string compare Memcheck:Addr4 fun:lj_str_new } { Optimized string compare Memcheck:Addr1 fun:lj_str_new } { Optimized string compare Memcheck:Cond fun:lj_str_new } { Optimized string compare Memcheck:Addr4 fun:str_fastcmp } { Optimized string compare Memcheck:Addr1 fun:str_fastcmp } { Optimized string compare Memcheck:Cond fun:str_fastcmp }
xLua/build/luajit-2.1.0b3/src/lj.supp/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj.supp", "repo_id": "xLua", "token_count": 253 }
2,117
/* ** Bytecode reader. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #define lj_bcread_c #define LUA_CORE #include "lj_obj.h" #include "lj_gc.h" #include "lj_err.h" #include "lj_buf.h" #include "lj_str.h" #include "lj_tab.h" #include "lj_bc.h" #if LJ_HASFFI #include "lj_ctype.h" #include "lj_cdata.h" #include "lualib.h" #endif #include "lj_lex.h" #include "lj_bcdump.h" #include "lj_state.h" #include "lj_strfmt.h" /* Reuse some lexer fields for our own purposes. */ #define bcread_flags(ls) ls->level #define bcread_swap(ls) \ ((bcread_flags(ls) & BCDUMP_F_BE) != LJ_BE*BCDUMP_F_BE) #define bcread_oldtop(L, ls) restorestack(L, ls->lastline) #define bcread_savetop(L, ls, top) \ ls->lastline = (BCLine)savestack(L, (top)) /* -- Input buffer handling ----------------------------------------------- */ /* Throw reader error. */ static LJ_NOINLINE void bcread_error(LexState *ls, ErrMsg em) { lua_State *L = ls->L; const char *name = ls->chunkarg; if (*name == BCDUMP_HEAD1) name = "(binary)"; else if (*name == '@' || *name == '=') name++; lj_strfmt_pushf(L, "%s: %s", name, err2msg(em)); lj_err_throw(L, LUA_ERRSYNTAX); } /* Refill buffer. */ static LJ_NOINLINE void bcread_fill(LexState *ls, MSize len, int need) { lj_assertLS(len != 0, "empty refill"); if (len > LJ_MAX_BUF || ls->c < 0) bcread_error(ls, LJ_ERR_BCBAD); do { const char *buf; size_t sz; char *p = ls->sb.b; MSize n = (MSize)(ls->pe - ls->p); if (n) { /* Copy remainder to buffer. */ if (sbuflen(&ls->sb)) { /* Move down in buffer. */ lj_assertLS(ls->pe == ls->sb.w, "bad buffer pointer"); if (ls->p != p) memmove(p, ls->p, n); } else { /* Copy from buffer provided by reader. */ p = lj_buf_need(&ls->sb, len); memcpy(p, ls->p, n); } ls->p = p; ls->pe = p + n; } ls->sb.w = p + n; buf = ls->rfunc(ls->L, ls->rdata, &sz); /* Get more data from reader. */ if (buf == NULL || sz == 0) { /* EOF? */ if (need) bcread_error(ls, LJ_ERR_BCBAD); ls->c = -1; /* Only bad if we get called again. */ break; } if (sz >= LJ_MAX_BUF - n) lj_err_mem(ls->L); if (n) { /* Append to buffer. */ n += (MSize)sz; p = lj_buf_need(&ls->sb, n < len ? len : n); memcpy(ls->sb.w, buf, sz); ls->sb.w = p + n; ls->p = p; ls->pe = p + n; } else { /* Return buffer provided by reader. */ ls->p = buf; ls->pe = buf + sz; } } while ((MSize)(ls->pe - ls->p) < len); } /* Need a certain number of bytes. */ static LJ_AINLINE void bcread_need(LexState *ls, MSize len) { if (LJ_UNLIKELY((MSize)(ls->pe - ls->p) < len)) bcread_fill(ls, len, 1); } /* Want to read up to a certain number of bytes, but may need less. */ static LJ_AINLINE void bcread_want(LexState *ls, MSize len) { if (LJ_UNLIKELY((MSize)(ls->pe - ls->p) < len)) bcread_fill(ls, len, 0); } /* Return memory block from buffer. */ static LJ_AINLINE uint8_t *bcread_mem(LexState *ls, MSize len) { uint8_t *p = (uint8_t *)ls->p; ls->p += len; lj_assertLS(ls->p <= ls->pe, "buffer read overflow"); return p; } /* Copy memory block from buffer. */ static void bcread_block(LexState *ls, void *q, MSize len) { memcpy(q, bcread_mem(ls, len), len); } /* Read byte from buffer. */ static LJ_AINLINE uint32_t bcread_byte(LexState *ls) { lj_assertLS(ls->p < ls->pe, "buffer read overflow"); return (uint32_t)(uint8_t)*ls->p++; } /* Read ULEB128 value from buffer. */ static LJ_AINLINE uint32_t bcread_uleb128(LexState *ls) { uint32_t v = lj_buf_ruleb128(&ls->p); lj_assertLS(ls->p <= ls->pe, "buffer read overflow"); return v; } /* Read top 32 bits of 33 bit ULEB128 value from buffer. */ static uint32_t bcread_uleb128_33(LexState *ls) { const uint8_t *p = (const uint8_t *)ls->p; uint32_t v = (*p++ >> 1); if (LJ_UNLIKELY(v >= 0x40)) { int sh = -1; v &= 0x3f; do { v |= ((*p & 0x7f) << (sh += 7)); } while (*p++ >= 0x80); } ls->p = (char *)p; lj_assertLS(ls->p <= ls->pe, "buffer read overflow"); return v; } /* -- Bytecode reader ----------------------------------------------------- */ /* Read debug info of a prototype. */ static void bcread_dbg(LexState *ls, GCproto *pt, MSize sizedbg) { void *lineinfo = (void *)proto_lineinfo(pt); bcread_block(ls, lineinfo, sizedbg); /* Swap lineinfo if the endianess differs. */ if (bcread_swap(ls) && pt->numline >= 256) { MSize i, n = pt->sizebc-1; if (pt->numline < 65536) { uint16_t *p = (uint16_t *)lineinfo; for (i = 0; i < n; i++) p[i] = (uint16_t)((p[i] >> 8)|(p[i] << 8)); } else { uint32_t *p = (uint32_t *)lineinfo; for (i = 0; i < n; i++) p[i] = lj_bswap(p[i]); } } } /* Find pointer to varinfo. */ static const void *bcread_varinfo(GCproto *pt) { const uint8_t *p = proto_uvinfo(pt); MSize n = pt->sizeuv; if (n) while (*p++ || --n) ; return p; } /* Read a single constant key/value of a template table. */ static void bcread_ktabk(LexState *ls, TValue *o) { MSize tp = bcread_uleb128(ls); if (tp >= BCDUMP_KTAB_STR) { MSize len = tp - BCDUMP_KTAB_STR; const char *p = (const char *)bcread_mem(ls, len); setstrV(ls->L, o, lj_str_new(ls->L, p, len)); } else if (tp == BCDUMP_KTAB_INT) { setintV(o, (int32_t)bcread_uleb128(ls)); } else if (tp == BCDUMP_KTAB_NUM) { o->u32.lo = bcread_uleb128(ls); o->u32.hi = bcread_uleb128(ls); } else { lj_assertLS(tp <= BCDUMP_KTAB_TRUE, "bad constant type %d", tp); setpriV(o, ~tp); } } /* Read a template table. */ static GCtab *bcread_ktab(LexState *ls) { MSize narray = bcread_uleb128(ls); MSize nhash = bcread_uleb128(ls); GCtab *t = lj_tab_new(ls->L, narray, hsize2hbits(nhash)); if (narray) { /* Read array entries. */ MSize i; TValue *o = tvref(t->array); for (i = 0; i < narray; i++, o++) bcread_ktabk(ls, o); } if (nhash) { /* Read hash entries. */ MSize i; for (i = 0; i < nhash; i++) { TValue key; bcread_ktabk(ls, &key); lj_assertLS(!tvisnil(&key), "nil key"); bcread_ktabk(ls, lj_tab_set(ls->L, t, &key)); } } return t; } /* Read GC constants of a prototype. */ static void bcread_kgc(LexState *ls, GCproto *pt, MSize sizekgc) { MSize i; GCRef *kr = mref(pt->k, GCRef) - (ptrdiff_t)sizekgc; for (i = 0; i < sizekgc; i++, kr++) { MSize tp = bcread_uleb128(ls); if (tp >= BCDUMP_KGC_STR) { MSize len = tp - BCDUMP_KGC_STR; const char *p = (const char *)bcread_mem(ls, len); setgcref(*kr, obj2gco(lj_str_new(ls->L, p, len))); } else if (tp == BCDUMP_KGC_TAB) { setgcref(*kr, obj2gco(bcread_ktab(ls))); #if LJ_HASFFI } else if (tp != BCDUMP_KGC_CHILD) { CTypeID id = tp == BCDUMP_KGC_COMPLEX ? CTID_COMPLEX_DOUBLE : tp == BCDUMP_KGC_I64 ? CTID_INT64 : CTID_UINT64; CTSize sz = tp == BCDUMP_KGC_COMPLEX ? 16 : 8; GCcdata *cd = lj_cdata_new_(ls->L, id, sz); TValue *p = (TValue *)cdataptr(cd); setgcref(*kr, obj2gco(cd)); p[0].u32.lo = bcread_uleb128(ls); p[0].u32.hi = bcread_uleb128(ls); if (tp == BCDUMP_KGC_COMPLEX) { p[1].u32.lo = bcread_uleb128(ls); p[1].u32.hi = bcread_uleb128(ls); } #endif } else { lua_State *L = ls->L; lj_assertLS(tp == BCDUMP_KGC_CHILD, "bad constant type %d", tp); if (L->top <= bcread_oldtop(L, ls)) /* Stack underflow? */ bcread_error(ls, LJ_ERR_BCBAD); L->top--; setgcref(*kr, obj2gco(protoV(L->top))); } } } /* Read number constants of a prototype. */ static void bcread_knum(LexState *ls, GCproto *pt, MSize sizekn) { MSize i; TValue *o = mref(pt->k, TValue); for (i = 0; i < sizekn; i++, o++) { int isnum = (ls->p[0] & 1); uint32_t lo = bcread_uleb128_33(ls); if (isnum) { o->u32.lo = lo; o->u32.hi = bcread_uleb128(ls); } else { setintV(o, lo); } } } /* Read bytecode instructions. */ static void bcread_bytecode(LexState *ls, GCproto *pt, MSize sizebc) { BCIns *bc = proto_bc(pt); bc[0] = BCINS_AD((pt->flags & PROTO_VARARG) ? BC_FUNCV : BC_FUNCF, pt->framesize, 0); bcread_block(ls, bc+1, (sizebc-1)*(MSize)sizeof(BCIns)); /* Swap bytecode instructions if the endianess differs. */ if (bcread_swap(ls)) { MSize i; for (i = 1; i < sizebc; i++) bc[i] = lj_bswap(bc[i]); } } /* Read upvalue refs. */ static void bcread_uv(LexState *ls, GCproto *pt, MSize sizeuv) { if (sizeuv) { uint16_t *uv = proto_uv(pt); bcread_block(ls, uv, sizeuv*2); /* Swap upvalue refs if the endianess differs. */ if (bcread_swap(ls)) { MSize i; for (i = 0; i < sizeuv; i++) uv[i] = (uint16_t)((uv[i] >> 8)|(uv[i] << 8)); } } } /* Read a prototype. */ GCproto *lj_bcread_proto(LexState *ls) { GCproto *pt; MSize framesize, numparams, flags, sizeuv, sizekgc, sizekn, sizebc, sizept; MSize ofsk, ofsuv, ofsdbg; MSize sizedbg = 0; BCLine firstline = 0, numline = 0; /* Read prototype header. */ flags = bcread_byte(ls); numparams = bcread_byte(ls); framesize = bcread_byte(ls); sizeuv = bcread_byte(ls); sizekgc = bcread_uleb128(ls); sizekn = bcread_uleb128(ls); sizebc = bcread_uleb128(ls) + 1; if (!(bcread_flags(ls) & BCDUMP_F_STRIP)) { sizedbg = bcread_uleb128(ls); if (sizedbg) { firstline = bcread_uleb128(ls); numline = bcread_uleb128(ls); } } /* Calculate total size of prototype including all colocated arrays. */ sizept = (MSize)sizeof(GCproto) + sizebc*(MSize)sizeof(BCIns) + sizekgc*(MSize)sizeof(GCRef); sizept = (sizept + (MSize)sizeof(TValue)-1) & ~((MSize)sizeof(TValue)-1); ofsk = sizept; sizept += sizekn*(MSize)sizeof(TValue); ofsuv = sizept; sizept += ((sizeuv+1)&~1)*2; ofsdbg = sizept; sizept += sizedbg; /* Allocate prototype object and initialize its fields. */ pt = (GCproto *)lj_mem_newgco(ls->L, (MSize)sizept); pt->gct = ~LJ_TPROTO; pt->numparams = (uint8_t)numparams; pt->framesize = (uint8_t)framesize; pt->sizebc = sizebc; setmref(pt->k, (char *)pt + ofsk); setmref(pt->uv, (char *)pt + ofsuv); pt->sizekgc = 0; /* Set to zero until fully initialized. */ pt->sizekn = sizekn; pt->sizept = sizept; pt->sizeuv = (uint8_t)sizeuv; pt->flags = (uint8_t)flags; pt->trace = 0; setgcref(pt->chunkname, obj2gco(ls->chunkname)); /* Close potentially uninitialized gap between bc and kgc. */ *(uint32_t *)((char *)pt + ofsk - sizeof(GCRef)*(sizekgc+1)) = 0; /* Read bytecode instructions and upvalue refs. */ bcread_bytecode(ls, pt, sizebc); bcread_uv(ls, pt, sizeuv); /* Read constants. */ bcread_kgc(ls, pt, sizekgc); pt->sizekgc = sizekgc; bcread_knum(ls, pt, sizekn); /* Read and initialize debug info. */ pt->firstline = firstline; pt->numline = numline; if (sizedbg) { MSize sizeli = (sizebc-1) << (numline < 256 ? 0 : numline < 65536 ? 1 : 2); setmref(pt->lineinfo, (char *)pt + ofsdbg); setmref(pt->uvinfo, (char *)pt + ofsdbg + sizeli); bcread_dbg(ls, pt, sizedbg); setmref(pt->varinfo, bcread_varinfo(pt)); } else { setmref(pt->lineinfo, NULL); setmref(pt->uvinfo, NULL); setmref(pt->varinfo, NULL); } return pt; } /* Read and check header of bytecode dump. */ static int bcread_header(LexState *ls) { uint32_t flags; bcread_want(ls, 3+5+5); if (bcread_byte(ls) != BCDUMP_HEAD2 || bcread_byte(ls) != BCDUMP_HEAD3 || bcread_byte(ls) != BCDUMP_VERSION) return 0; bcread_flags(ls) = flags = bcread_uleb128(ls); if ((flags & ~(BCDUMP_F_KNOWN)) != 0) return 0; if ((flags & BCDUMP_F_FR2) != LJ_FR2*BCDUMP_F_FR2) return 0; if ((flags & BCDUMP_F_FFI)) { #if LJ_HASFFI lua_State *L = ls->L; ctype_loadffi(L); #else return 0; #endif } if ((flags & BCDUMP_F_STRIP)) { ls->chunkname = lj_str_newz(ls->L, ls->chunkarg); } else { MSize len = bcread_uleb128(ls); bcread_need(ls, len); ls->chunkname = lj_str_new(ls->L, (const char *)bcread_mem(ls, len), len); } return 1; /* Ok. */ } /* Read a bytecode dump. */ GCproto *lj_bcread(LexState *ls) { lua_State *L = ls->L; lj_assertLS(ls->c == BCDUMP_HEAD1, "bad bytecode header"); bcread_savetop(L, ls, L->top); lj_buf_reset(&ls->sb); /* Check for a valid bytecode dump header. */ if (!bcread_header(ls)) bcread_error(ls, LJ_ERR_BCFMT); for (;;) { /* Process all prototypes in the bytecode dump. */ GCproto *pt; MSize len; const char *startp; /* Read length. */ if (ls->p < ls->pe && ls->p[0] == 0) { /* Shortcut EOF. */ ls->p++; break; } bcread_want(ls, 5); len = bcread_uleb128(ls); if (!len) break; /* EOF */ bcread_need(ls, len); startp = ls->p; pt = lj_bcread_proto(ls); if (ls->p != startp + len) bcread_error(ls, LJ_ERR_BCBAD); setprotoV(L, L->top, pt); incr_top(L); } if ((ls->pe != ls->p && !ls->endmark) || L->top-1 != bcread_oldtop(L, ls)) bcread_error(ls, LJ_ERR_BCBAD); /* Pop off last prototype. */ L->top--; return protoV(L->top); }
xLua/build/luajit-2.1.0b3/src/lj_bcread.c/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_bcread.c", "repo_id": "xLua", "token_count": 6138 }
2,118
/* ** FFI C library loader. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #include "lj_obj.h" #if LJ_HASFFI #include "lj_gc.h" #include "lj_err.h" #include "lj_tab.h" #include "lj_str.h" #include "lj_udata.h" #include "lj_ctype.h" #include "lj_cconv.h" #include "lj_cdata.h" #include "lj_clib.h" #include "lj_strfmt.h" /* -- OS-specific functions ----------------------------------------------- */ #if LJ_TARGET_DLOPEN #include <dlfcn.h> #include <stdio.h> #if defined(RTLD_DEFAULT) #define CLIB_DEFHANDLE RTLD_DEFAULT #elif LJ_TARGET_OSX || LJ_TARGET_BSD #define CLIB_DEFHANDLE ((void *)(intptr_t)-2) #else #define CLIB_DEFHANDLE NULL #endif LJ_NORET LJ_NOINLINE static void clib_error_(lua_State *L) { lj_err_callermsg(L, dlerror()); } #define clib_error(L, fmt, name) clib_error_(L) #if LJ_TARGET_CYGWIN #define CLIB_SOPREFIX "cyg" #else #define CLIB_SOPREFIX "lib" #endif #if LJ_TARGET_OSX #define CLIB_SOEXT "%s.dylib" #elif LJ_TARGET_CYGWIN #define CLIB_SOEXT "%s.dll" #else #define CLIB_SOEXT "%s.so" #endif static const char *clib_extname(lua_State *L, const char *name) { if (!strchr(name, '/') #if LJ_TARGET_CYGWIN && !strchr(name, '\\') #endif ) { if (!strchr(name, '.')) { name = lj_strfmt_pushf(L, CLIB_SOEXT, name); L->top--; #if LJ_TARGET_CYGWIN } else { return name; #endif } if (!(name[0] == CLIB_SOPREFIX[0] && name[1] == CLIB_SOPREFIX[1] && name[2] == CLIB_SOPREFIX[2])) { name = lj_strfmt_pushf(L, CLIB_SOPREFIX "%s", name); L->top--; } } return name; } /* Check for a recognized ld script line. */ static const char *clib_check_lds(lua_State *L, const char *buf) { char *p, *e; if ((!strncmp(buf, "GROUP", 5) || !strncmp(buf, "INPUT", 5)) && (p = strchr(buf, '('))) { while (*++p == ' ') ; for (e = p; *e && *e != ' ' && *e != ')'; e++) ; return strdata(lj_str_new(L, p, e-p)); } return NULL; } /* Quick and dirty solution to resolve shared library name from ld script. */ static const char *clib_resolve_lds(lua_State *L, const char *name) { FILE *fp = fopen(name, "r"); const char *p = NULL; if (fp) { char buf[256]; if (fgets(buf, sizeof(buf), fp)) { if (!strncmp(buf, "/* GNU ld script", 16)) { /* ld script magic? */ while (fgets(buf, sizeof(buf), fp)) { /* Check all lines. */ p = clib_check_lds(L, buf); if (p) break; } } else { /* Otherwise check only the first line. */ p = clib_check_lds(L, buf); } } fclose(fp); } return p; } static void *clib_loadlib(lua_State *L, const char *name, int global) { void *h = dlopen(clib_extname(L, name), RTLD_LAZY | (global?RTLD_GLOBAL:RTLD_LOCAL)); if (!h) { const char *e, *err = dlerror(); if (err && *err == '/' && (e = strchr(err, ':')) && (name = clib_resolve_lds(L, strdata(lj_str_new(L, err, e-err))))) { h = dlopen(name, RTLD_LAZY | (global?RTLD_GLOBAL:RTLD_LOCAL)); if (h) return h; err = dlerror(); } if (!err) err = "dlopen failed"; lj_err_callermsg(L, err); } return h; } static void clib_unloadlib(CLibrary *cl) { if (cl->handle && cl->handle != CLIB_DEFHANDLE) dlclose(cl->handle); } static void *clib_getsym(CLibrary *cl, const char *name) { void *p = dlsym(cl->handle, name); return p; } #elif LJ_TARGET_WINDOWS #define WIN32_LEAN_AND_MEAN #include <windows.h> #ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS #define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4 #define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2 BOOL WINAPI GetModuleHandleExA(DWORD, LPCSTR, HMODULE*); #endif #define CLIB_DEFHANDLE ((void *)-1) /* Default libraries. */ enum { CLIB_HANDLE_EXE, #if !LJ_TARGET_UWP CLIB_HANDLE_DLL, CLIB_HANDLE_CRT, CLIB_HANDLE_KERNEL32, CLIB_HANDLE_USER32, CLIB_HANDLE_GDI32, #endif CLIB_HANDLE_MAX }; static void *clib_def_handle[CLIB_HANDLE_MAX]; LJ_NORET LJ_NOINLINE static void clib_error(lua_State *L, const char *fmt, const char *name) { DWORD err = GetLastError(); #if LJ_TARGET_XBOXONE wchar_t wbuf[128]; char buf[128*2]; if (!FormatMessageW(FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0, wbuf, sizeof(wbuf)/sizeof(wchar_t), NULL) || !WideCharToMultiByte(CP_ACP, 0, wbuf, 128, buf, 128*2, NULL, NULL)) #else char buf[128]; if (!FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0, buf, sizeof(buf), NULL)) #endif buf[0] = '\0'; lj_err_callermsg(L, lj_strfmt_pushf(L, fmt, name, buf)); } static int clib_needext(const char *s) { while (*s) { if (*s == '/' || *s == '\\' || *s == '.') return 0; s++; } return 1; } static const char *clib_extname(lua_State *L, const char *name) { if (clib_needext(name)) { name = lj_strfmt_pushf(L, "%s.dll", name); L->top--; } return name; } static void *clib_loadlib(lua_State *L, const char *name, int global) { DWORD oldwerr = GetLastError(); void *h = LJ_WIN_LOADLIBA(clib_extname(L, name)); if (!h) clib_error(L, "cannot load module " LUA_QS ": %s", name); SetLastError(oldwerr); UNUSED(global); return h; } static void clib_unloadlib(CLibrary *cl) { if (cl->handle == CLIB_DEFHANDLE) { #if !LJ_TARGET_UWP MSize i; for (i = CLIB_HANDLE_KERNEL32; i < CLIB_HANDLE_MAX; i++) { void *h = clib_def_handle[i]; if (h) { clib_def_handle[i] = NULL; FreeLibrary((HINSTANCE)h); } } #endif } else if (cl->handle) { FreeLibrary((HINSTANCE)cl->handle); } } #if LJ_TARGET_UWP EXTERN_C IMAGE_DOS_HEADER __ImageBase; #endif static void *clib_getsym(CLibrary *cl, const char *name) { void *p = NULL; if (cl->handle == CLIB_DEFHANDLE) { /* Search default libraries. */ MSize i; for (i = 0; i < CLIB_HANDLE_MAX; i++) { HINSTANCE h = (HINSTANCE)clib_def_handle[i]; if (!(void *)h) { /* Resolve default library handles (once). */ #if LJ_TARGET_UWP h = (HINSTANCE)&__ImageBase; #else switch (i) { case CLIB_HANDLE_EXE: GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, NULL, &h); break; case CLIB_HANDLE_DLL: GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (const char *)clib_def_handle, &h); break; case CLIB_HANDLE_CRT: GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (const char *)&_fmode, &h); break; case CLIB_HANDLE_KERNEL32: h = LJ_WIN_LOADLIBA("kernel32.dll"); break; case CLIB_HANDLE_USER32: h = LJ_WIN_LOADLIBA("user32.dll"); break; case CLIB_HANDLE_GDI32: h = LJ_WIN_LOADLIBA("gdi32.dll"); break; } if (!h) continue; #endif clib_def_handle[i] = (void *)h; } p = (void *)GetProcAddress(h, name); if (p) break; } } else { p = (void *)GetProcAddress((HINSTANCE)cl->handle, name); } return p; } #else #define CLIB_DEFHANDLE NULL LJ_NORET LJ_NOINLINE static void clib_error(lua_State *L, const char *fmt, const char *name) { lj_err_callermsg(L, lj_strfmt_pushf(L, fmt, name, "no support for this OS")); } static void *clib_loadlib(lua_State *L, const char *name, int global) { lj_err_callermsg(L, "no support for loading dynamic libraries for this OS"); UNUSED(name); UNUSED(global); return NULL; } static void clib_unloadlib(CLibrary *cl) { UNUSED(cl); } static void *clib_getsym(CLibrary *cl, const char *name) { UNUSED(cl); UNUSED(name); return NULL; } #endif /* -- C library indexing -------------------------------------------------- */ #if LJ_TARGET_X86 && LJ_ABI_WIN /* Compute argument size for fastcall/stdcall functions. */ static CTSize clib_func_argsize(CTState *cts, CType *ct) { CTSize n = 0; while (ct->sib) { CType *d; ct = ctype_get(cts, ct->sib); if (ctype_isfield(ct->info)) { d = ctype_rawchild(cts, ct); n += ((d->size + 3) & ~3); } } return n; } #endif /* Get redirected or mangled external symbol. */ static const char *clib_extsym(CTState *cts, CType *ct, GCstr *name) { if (ct->sib) { CType *ctf = ctype_get(cts, ct->sib); if (ctype_isxattrib(ctf->info, CTA_REDIR)) return strdata(gco2str(gcref(ctf->name))); } return strdata(name); } /* Index a C library by name. */ TValue *lj_clib_index(lua_State *L, CLibrary *cl, GCstr *name) { TValue *tv = lj_tab_setstr(L, cl->cache, name); if (LJ_UNLIKELY(tvisnil(tv))) { CTState *cts = ctype_cts(L); CType *ct; CTypeID id = lj_ctype_getname(cts, &ct, name, CLNS_INDEX); if (!id) lj_err_callerv(L, LJ_ERR_FFI_NODECL, strdata(name)); if (ctype_isconstval(ct->info)) { CType *ctt = ctype_child(cts, ct); lj_assertCTS(ctype_isinteger(ctt->info) && ctt->size <= 4, "only 32 bit const supported"); /* NYI */ if ((ctt->info & CTF_UNSIGNED) && (int32_t)ct->size < 0) setnumV(tv, (lua_Number)(uint32_t)ct->size); else setintV(tv, (int32_t)ct->size); } else { const char *sym = clib_extsym(cts, ct, name); #if LJ_TARGET_WINDOWS DWORD oldwerr = GetLastError(); #endif void *p = clib_getsym(cl, sym); GCcdata *cd; lj_assertCTS(ctype_isfunc(ct->info) || ctype_isextern(ct->info), "unexpected ctype %08x in clib", ct->info); #if LJ_TARGET_X86 && LJ_ABI_WIN /* Retry with decorated name for fastcall/stdcall functions. */ if (!p && ctype_isfunc(ct->info)) { CTInfo cconv = ctype_cconv(ct->info); if (cconv == CTCC_FASTCALL || cconv == CTCC_STDCALL) { CTSize sz = clib_func_argsize(cts, ct); const char *symd = lj_strfmt_pushf(L, cconv == CTCC_FASTCALL ? "@%s@%d" : "_%s@%d", sym, sz); L->top--; p = clib_getsym(cl, symd); } } #endif if (!p) clib_error(L, "cannot resolve symbol " LUA_QS ": %s", sym); #if LJ_TARGET_WINDOWS SetLastError(oldwerr); #endif cd = lj_cdata_new(cts, id, CTSIZE_PTR); *(void **)cdataptr(cd) = p; setcdataV(L, tv, cd); lj_gc_anybarriert(L, cl->cache); } } return tv; } /* -- C library management ------------------------------------------------ */ /* Create a new CLibrary object and push it on the stack. */ static CLibrary *clib_new(lua_State *L, GCtab *mt) { GCtab *t = lj_tab_new(L, 0, 0); GCudata *ud = lj_udata_new(L, sizeof(CLibrary), t); CLibrary *cl = (CLibrary *)uddata(ud); cl->cache = t; ud->udtype = UDTYPE_FFI_CLIB; /* NOBARRIER: The GCudata is new (marked white). */ setgcref(ud->metatable, obj2gco(mt)); setudataV(L, L->top++, ud); return cl; } /* Load a C library. */ void lj_clib_load(lua_State *L, GCtab *mt, GCstr *name, int global) { void *handle = clib_loadlib(L, strdata(name), global); CLibrary *cl = clib_new(L, mt); cl->handle = handle; } /* Unload a C library. */ void lj_clib_unload(CLibrary *cl) { clib_unloadlib(cl); cl->handle = NULL; } /* Create the default C library object. */ void lj_clib_default(lua_State *L, GCtab *mt) { CLibrary *cl = clib_new(L, mt); cl->handle = CLIB_DEFHANDLE; } #endif
xLua/build/luajit-2.1.0b3/src/lj_clib.c/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_clib.c", "repo_id": "xLua", "token_count": 5180 }
2,119
/* ** PPC instruction emitter. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ /* -- Emit basic instructions --------------------------------------------- */ static void emit_tab(ASMState *as, PPCIns pi, Reg rt, Reg ra, Reg rb) { *--as->mcp = pi | PPCF_T(rt) | PPCF_A(ra) | PPCF_B(rb); } #define emit_asb(as, pi, ra, rs, rb) emit_tab(as, (pi), (rs), (ra), (rb)) #define emit_as(as, pi, ra, rs) emit_tab(as, (pi), (rs), (ra), 0) #define emit_ab(as, pi, ra, rb) emit_tab(as, (pi), 0, (ra), (rb)) static void emit_tai(ASMState *as, PPCIns pi, Reg rt, Reg ra, int32_t i) { *--as->mcp = pi | PPCF_T(rt) | PPCF_A(ra) | (i & 0xffff); } #define emit_ti(as, pi, rt, i) emit_tai(as, (pi), (rt), 0, (i)) #define emit_ai(as, pi, ra, i) emit_tai(as, (pi), 0, (ra), (i)) #define emit_asi(as, pi, ra, rs, i) emit_tai(as, (pi), (rs), (ra), (i)) #define emit_fab(as, pi, rf, ra, rb) \ emit_tab(as, (pi), (rf)&31, (ra)&31, (rb)&31) #define emit_fb(as, pi, rf, rb) emit_tab(as, (pi), (rf)&31, 0, (rb)&31) #define emit_fac(as, pi, rf, ra, rc) \ emit_tab(as, (pi) | PPCF_C((rc) & 31), (rf)&31, (ra)&31, 0) #define emit_facb(as, pi, rf, ra, rc, rb) \ emit_tab(as, (pi) | PPCF_C((rc) & 31), (rf)&31, (ra)&31, (rb)&31) #define emit_fai(as, pi, rf, ra, i) emit_tai(as, (pi), (rf)&31, (ra), (i)) static void emit_rot(ASMState *as, PPCIns pi, Reg ra, Reg rs, int32_t n, int32_t b, int32_t e) { *--as->mcp = pi | PPCF_T(rs) | PPCF_A(ra) | PPCF_B(n) | PPCF_MB(b) | PPCF_ME(e); } static void emit_slwi(ASMState *as, Reg ra, Reg rs, int32_t n) { lj_assertA(n >= 0 && n < 32, "shift out or range"); emit_rot(as, PPCI_RLWINM, ra, rs, n, 0, 31-n); } static void emit_rotlwi(ASMState *as, Reg ra, Reg rs, int32_t n) { lj_assertA(n >= 0 && n < 32, "shift out or range"); emit_rot(as, PPCI_RLWINM, ra, rs, n, 0, 31); } /* -- Emit loads/stores --------------------------------------------------- */ /* Prefer rematerialization of BASE/L from global_State over spills. */ #define emit_canremat(ref) ((ref) <= REF_BASE) /* Try to find a one step delta relative to another constant. */ static int emit_kdelta1(ASMState *as, Reg rd, int32_t i) { RegSet work = ~as->freeset & RSET_GPR; while (work) { Reg r = rset_picktop(work); IRRef ref = regcost_ref(as->cost[r]); lj_assertA(r != rd, "dest reg %d not free", rd); if (ref < ASMREF_L) { int32_t delta = i - (ra_iskref(ref) ? ra_krefk(as, ref) : IR(ref)->i); if (checki16(delta)) { emit_tai(as, PPCI_ADDI, rd, r, delta); return 1; } } rset_clear(work, r); } return 0; /* Failed. */ } /* Load a 32 bit constant into a GPR. */ static void emit_loadi(ASMState *as, Reg r, int32_t i) { if (checki16(i)) { emit_ti(as, PPCI_LI, r, i); } else { if ((i & 0xffff)) { int32_t jgl = i32ptr(J2G(as->J)); if ((uint32_t)(i-jgl) < 65536) { emit_tai(as, PPCI_ADDI, r, RID_JGL, i-jgl-32768); return; } else if (emit_kdelta1(as, r, i)) { return; } emit_asi(as, PPCI_ORI, r, r, i); } emit_ti(as, PPCI_LIS, r, (i >> 16)); } } #define emit_loada(as, r, addr) emit_loadi(as, (r), i32ptr((addr))) static Reg ra_allock(ASMState *as, intptr_t k, RegSet allow); /* Get/set from constant pointer. */ static void emit_lsptr(ASMState *as, PPCIns pi, Reg r, void *p, RegSet allow) { int32_t jgl = i32ptr(J2G(as->J)); int32_t i = i32ptr(p); Reg base; if ((uint32_t)(i-jgl) < 65536) { i = i-jgl-32768; base = RID_JGL; } else { base = ra_allock(as, i-(int16_t)i, allow); } emit_tai(as, pi, r, base, i); } #define emit_loadk64(as, r, ir) \ emit_lsptr(as, PPCI_LFD, ((r) & 31), (void *)&ir_knum((ir))->u64, RSET_GPR) /* Get/set global_State fields. */ static void emit_lsglptr(ASMState *as, PPCIns pi, Reg r, int32_t ofs) { emit_tai(as, pi, r, RID_JGL, ofs-32768); } #define emit_getgl(as, r, field) \ emit_lsglptr(as, PPCI_LWZ, (r), (int32_t)offsetof(global_State, field)) #define emit_setgl(as, r, field) \ emit_lsglptr(as, PPCI_STW, (r), (int32_t)offsetof(global_State, field)) /* Trace number is determined from per-trace exit stubs. */ #define emit_setvmstate(as, i) UNUSED(i) /* -- Emit control-flow instructions -------------------------------------- */ /* Label for internal jumps. */ typedef MCode *MCLabel; /* Return label pointing to current PC. */ #define emit_label(as) ((as)->mcp) static void emit_condbranch(ASMState *as, PPCIns pi, PPCCC cc, MCode *target) { MCode *p = --as->mcp; ptrdiff_t delta = (char *)target - (char *)p; lj_assertA(((delta + 0x8000) >> 16) == 0, "branch target out of range"); pi ^= (delta & 0x8000) * (PPCF_Y/0x8000); *p = pi | PPCF_CC(cc) | ((uint32_t)delta & 0xffffu); } static void emit_jmp(ASMState *as, MCode *target) { MCode *p = --as->mcp; ptrdiff_t delta = (char *)target - (char *)p; *p = PPCI_B | (delta & 0x03fffffcu); } static void emit_call(ASMState *as, void *target) { MCode *p = --as->mcp; ptrdiff_t delta = (char *)target - (char *)p; if ((((delta>>2) + 0x00800000) >> 24) == 0) { *p = PPCI_BL | (delta & 0x03fffffcu); } else { /* Target out of range: need indirect call. Don't use arg reg. */ RegSet allow = RSET_GPR & ~RSET_RANGE(RID_R0, REGARG_LASTGPR+1); Reg r = ra_allock(as, i32ptr(target), allow); *p = PPCI_BCTRL; p[-1] = PPCI_MTCTR | PPCF_T(r); as->mcp = p-1; } } /* -- Emit generic operations --------------------------------------------- */ #define emit_mr(as, dst, src) \ emit_asb(as, PPCI_MR, (dst), (src), (src)) /* Generic move between two regs. */ static void emit_movrr(ASMState *as, IRIns *ir, Reg dst, Reg src) { UNUSED(ir); if (dst < RID_MAX_GPR) emit_mr(as, dst, src); else emit_fb(as, PPCI_FMR, dst, src); } /* Generic load of register with base and (small) offset address. */ static void emit_loadofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs) { if (r < RID_MAX_GPR) emit_tai(as, PPCI_LWZ, r, base, ofs); else emit_fai(as, irt_isnum(ir->t) ? PPCI_LFD : PPCI_LFS, r, base, ofs); } /* Generic store of register with base and (small) offset address. */ static void emit_storeofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs) { if (r < RID_MAX_GPR) emit_tai(as, PPCI_STW, r, base, ofs); else emit_fai(as, irt_isnum(ir->t) ? PPCI_STFD : PPCI_STFS, r, base, ofs); } /* Emit a compare (for equality) with a constant operand. */ static void emit_cmpi(ASMState *as, Reg r, int32_t k) { if (checki16(k)) { emit_ai(as, PPCI_CMPWI, r, k); } else if (checku16(k)) { emit_ai(as, PPCI_CMPLWI, r, k); } else { emit_ai(as, PPCI_CMPLWI, RID_TMP, k); emit_asi(as, PPCI_XORIS, RID_TMP, r, (k >> 16)); } } /* Add offset to pointer. */ static void emit_addptr(ASMState *as, Reg r, int32_t ofs) { if (ofs) { emit_tai(as, PPCI_ADDI, r, r, ofs); if (!checki16(ofs)) emit_tai(as, PPCI_ADDIS, r, r, (ofs + 32768) >> 16); } } static void emit_spsub(ASMState *as, int32_t ofs) { if (ofs) { emit_tai(as, PPCI_STWU, RID_TMP, RID_SP, -ofs); emit_tai(as, PPCI_ADDI, RID_TMP, RID_SP, CFRAME_SIZE + (as->parent ? as->parent->spadjust : 0)); } }
xLua/build/luajit-2.1.0b3/src/lj_emit_ppc.h/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_emit_ppc.h", "repo_id": "xLua", "token_count": 3435 }
2,120
/* ** SSA IR (Intermediate Representation) format. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #ifndef _LJ_IR_H #define _LJ_IR_H #include "lj_obj.h" /* -- IR instructions ----------------------------------------------------- */ /* IR instruction definition. Order matters, see below. ORDER IR */ #define IRDEF(_) \ /* Guarded assertions. */ \ /* Must be properly aligned to flip opposites (^1) and (un)ordered (^4). */ \ _(LT, N , ref, ref) \ _(GE, N , ref, ref) \ _(LE, N , ref, ref) \ _(GT, N , ref, ref) \ \ _(ULT, N , ref, ref) \ _(UGE, N , ref, ref) \ _(ULE, N , ref, ref) \ _(UGT, N , ref, ref) \ \ _(EQ, C , ref, ref) \ _(NE, C , ref, ref) \ \ _(ABC, N , ref, ref) \ _(RETF, S , ref, ref) \ \ /* Miscellaneous ops. */ \ _(NOP, N , ___, ___) \ _(BASE, N , lit, lit) \ _(PVAL, N , lit, ___) \ _(GCSTEP, S , ___, ___) \ _(HIOP, S , ref, ref) \ _(LOOP, S , ___, ___) \ _(USE, S , ref, ___) \ _(PHI, S , ref, ref) \ _(RENAME, S , ref, lit) \ _(PROF, S , ___, ___) \ \ /* Constants. */ \ _(KPRI, N , ___, ___) \ _(KINT, N , cst, ___) \ _(KGC, N , cst, ___) \ _(KPTR, N , cst, ___) \ _(KKPTR, N , cst, ___) \ _(KNULL, N , cst, ___) \ _(KNUM, N , cst, ___) \ _(KINT64, N , cst, ___) \ _(KSLOT, N , ref, lit) \ \ /* Bit ops. */ \ _(BNOT, N , ref, ___) \ _(BSWAP, N , ref, ___) \ _(BAND, C , ref, ref) \ _(BOR, C , ref, ref) \ _(BXOR, C , ref, ref) \ _(BSHL, N , ref, ref) \ _(BSHR, N , ref, ref) \ _(BSAR, N , ref, ref) \ _(BROL, N , ref, ref) \ _(BROR, N , ref, ref) \ \ /* Arithmetic ops. ORDER ARITH */ \ _(ADD, C , ref, ref) \ _(SUB, N , ref, ref) \ _(MUL, C , ref, ref) \ _(DIV, N , ref, ref) \ _(MOD, N , ref, ref) \ _(POW, N , ref, ref) \ _(NEG, N , ref, ref) \ \ _(ABS, N , ref, ref) \ _(LDEXP, N , ref, ref) \ _(MIN, C , ref, ref) \ _(MAX, C , ref, ref) \ _(FPMATH, N , ref, lit) \ \ /* Overflow-checking arithmetic ops. */ \ _(ADDOV, CW, ref, ref) \ _(SUBOV, NW, ref, ref) \ _(MULOV, CW, ref, ref) \ \ /* Memory ops. A = array, H = hash, U = upvalue, F = field, S = stack. */ \ \ /* Memory references. */ \ _(AREF, R , ref, ref) \ _(HREFK, R , ref, ref) \ _(HREF, L , ref, ref) \ _(NEWREF, S , ref, ref) \ _(UREFO, LW, ref, lit) \ _(UREFC, LW, ref, lit) \ _(FREF, R , ref, lit) \ _(TMPREF, S , ref, lit) \ _(STRREF, N , ref, ref) \ _(LREF, L , ___, ___) \ \ /* Loads and Stores. These must be in the same order. */ \ _(ALOAD, L , ref, ___) \ _(HLOAD, L , ref, ___) \ _(ULOAD, L , ref, ___) \ _(FLOAD, L , ref, lit) \ _(XLOAD, L , ref, lit) \ _(SLOAD, L , lit, lit) \ _(VLOAD, L , ref, lit) \ _(ALEN, L , ref, ref) \ \ _(ASTORE, S , ref, ref) \ _(HSTORE, S , ref, ref) \ _(USTORE, S , ref, ref) \ _(FSTORE, S , ref, ref) \ _(XSTORE, S , ref, ref) \ \ /* Allocations. */ \ _(SNEW, N , ref, ref) /* CSE is ok, not marked as A. */ \ _(XSNEW, A , ref, ref) \ _(TNEW, AW, lit, lit) \ _(TDUP, AW, ref, ___) \ _(CNEW, AW, ref, ref) \ _(CNEWI, NW, ref, ref) /* CSE is ok, not marked as A. */ \ \ /* Buffer operations. */ \ _(BUFHDR, L , ref, lit) \ _(BUFPUT, LW, ref, ref) \ _(BUFSTR, AW, ref, ref) \ \ /* Barriers. */ \ _(TBAR, S , ref, ___) \ _(OBAR, S , ref, ref) \ _(XBAR, S , ___, ___) \ \ /* Type conversions. */ \ _(CONV, N , ref, lit) \ _(TOBIT, N , ref, ref) \ _(TOSTR, N , ref, lit) \ _(STRTO, N , ref, ___) \ \ /* Calls. */ \ _(CALLN, NW, ref, lit) \ _(CALLA, AW, ref, lit) \ _(CALLL, LW, ref, lit) \ _(CALLS, S , ref, lit) \ _(CALLXS, S , ref, ref) \ _(CARG, N , ref, ref) \ \ /* End of list. */ /* IR opcodes (max. 256). */ typedef enum { #define IRENUM(name, m, m1, m2) IR_##name, IRDEF(IRENUM) #undef IRENUM IR__MAX } IROp; /* Stored opcode. */ typedef uint8_t IROp1; LJ_STATIC_ASSERT(((int)IR_EQ^1) == (int)IR_NE); LJ_STATIC_ASSERT(((int)IR_LT^1) == (int)IR_GE); LJ_STATIC_ASSERT(((int)IR_LE^1) == (int)IR_GT); LJ_STATIC_ASSERT(((int)IR_LT^3) == (int)IR_GT); LJ_STATIC_ASSERT(((int)IR_LT^4) == (int)IR_ULT); /* Delta between xLOAD and xSTORE. */ #define IRDELTA_L2S ((int)IR_ASTORE - (int)IR_ALOAD) LJ_STATIC_ASSERT((int)IR_HLOAD + IRDELTA_L2S == (int)IR_HSTORE); LJ_STATIC_ASSERT((int)IR_ULOAD + IRDELTA_L2S == (int)IR_USTORE); LJ_STATIC_ASSERT((int)IR_FLOAD + IRDELTA_L2S == (int)IR_FSTORE); LJ_STATIC_ASSERT((int)IR_XLOAD + IRDELTA_L2S == (int)IR_XSTORE); /* -- Named IR literals --------------------------------------------------- */ /* FPMATH sub-functions. ORDER FPM. */ #define IRFPMDEF(_) \ _(FLOOR) _(CEIL) _(TRUNC) /* Must be first and in this order. */ \ _(SQRT) _(LOG) _(LOG2) \ _(OTHER) typedef enum { #define FPMENUM(name) IRFPM_##name, IRFPMDEF(FPMENUM) #undef FPMENUM IRFPM__MAX } IRFPMathOp; /* FLOAD fields. */ #define IRFLDEF(_) \ _(STR_LEN, offsetof(GCstr, len)) \ _(FUNC_ENV, offsetof(GCfunc, l.env)) \ _(FUNC_PC, offsetof(GCfunc, l.pc)) \ _(FUNC_FFID, offsetof(GCfunc, l.ffid)) \ _(THREAD_ENV, offsetof(lua_State, env)) \ _(TAB_META, offsetof(GCtab, metatable)) \ _(TAB_ARRAY, offsetof(GCtab, array)) \ _(TAB_NODE, offsetof(GCtab, node)) \ _(TAB_ASIZE, offsetof(GCtab, asize)) \ _(TAB_HMASK, offsetof(GCtab, hmask)) \ _(TAB_NOMM, offsetof(GCtab, nomm)) \ _(UDATA_META, offsetof(GCudata, metatable)) \ _(UDATA_UDTYPE, offsetof(GCudata, udtype)) \ _(UDATA_FILE, sizeof(GCudata)) \ _(SBUF_W, sizeof(GCudata) + offsetof(SBufExt, w)) \ _(SBUF_E, sizeof(GCudata) + offsetof(SBufExt, e)) \ _(SBUF_B, sizeof(GCudata) + offsetof(SBufExt, b)) \ _(SBUF_L, sizeof(GCudata) + offsetof(SBufExt, L)) \ _(SBUF_REF, sizeof(GCudata) + offsetof(SBufExt, cowref)) \ _(SBUF_R, sizeof(GCudata) + offsetof(SBufExt, r)) \ _(CDATA_CTYPEID, offsetof(GCcdata, ctypeid)) \ _(CDATA_PTR, sizeof(GCcdata)) \ _(CDATA_INT, sizeof(GCcdata)) \ _(CDATA_INT64, sizeof(GCcdata)) \ _(CDATA_INT64_4, sizeof(GCcdata) + 4) typedef enum { #define FLENUM(name, ofs) IRFL_##name, IRFLDEF(FLENUM) #undef FLENUM IRFL__MAX } IRFieldID; /* TMPREF mode bits, stored in op2. */ #define IRTMPREF_IN1 0x01 /* First input value. */ #define IRTMPREF_OUT1 0x02 /* First output value. */ #define IRTMPREF_OUT2 0x04 /* Second output value. */ /* SLOAD mode bits, stored in op2. */ #define IRSLOAD_PARENT 0x01 /* Coalesce with parent trace. */ #define IRSLOAD_FRAME 0x02 /* Load 32 bits of ftsz. */ #define IRSLOAD_TYPECHECK 0x04 /* Needs type check. */ #define IRSLOAD_CONVERT 0x08 /* Number to integer conversion. */ #define IRSLOAD_READONLY 0x10 /* Read-only, omit slot store. */ #define IRSLOAD_INHERIT 0x20 /* Inherited by exits/side traces. */ #define IRSLOAD_KEYINDEX 0x40 /* Table traversal key index. */ /* XLOAD mode bits, stored in op2. */ #define IRXLOAD_READONLY 0x01 /* Load from read-only data. */ #define IRXLOAD_VOLATILE 0x02 /* Load from volatile data. */ #define IRXLOAD_UNALIGNED 0x04 /* Unaligned load. */ /* BUFHDR mode, stored in op2. */ #define IRBUFHDR_RESET 0 /* Reset buffer. */ #define IRBUFHDR_APPEND 1 /* Append to buffer. */ #define IRBUFHDR_WRITE 2 /* Write to string buffer. */ /* CONV mode, stored in op2. */ #define IRCONV_SRCMASK 0x001f /* Source IRType. */ #define IRCONV_DSTMASK 0x03e0 /* Dest. IRType (also in ir->t). */ #define IRCONV_DSH 5 #define IRCONV_NUM_INT ((IRT_NUM<<IRCONV_DSH)|IRT_INT) #define IRCONV_INT_NUM ((IRT_INT<<IRCONV_DSH)|IRT_NUM) #define IRCONV_SEXT 0x0800 /* Sign-extend integer to integer. */ #define IRCONV_MODEMASK 0x0fff #define IRCONV_CONVMASK 0xf000 #define IRCONV_CSH 12 /* Number to integer conversion mode. Ordered by strength of the checks. */ #define IRCONV_TOBIT (0<<IRCONV_CSH) /* None. Cache only: TOBIT conv. */ #define IRCONV_ANY (1<<IRCONV_CSH) /* Any FP number is ok. */ #define IRCONV_INDEX (2<<IRCONV_CSH) /* Check + special backprop rules. */ #define IRCONV_CHECK (3<<IRCONV_CSH) /* Number checked for integerness. */ #define IRCONV_NONE IRCONV_ANY /* INT|*64 no conv, but change type. */ /* TOSTR mode, stored in op2. */ #define IRTOSTR_INT 0 /* Convert integer to string. */ #define IRTOSTR_NUM 1 /* Convert number to string. */ #define IRTOSTR_CHAR 2 /* Convert char value to string. */ /* -- IR operands --------------------------------------------------------- */ /* IR operand mode (2 bit). */ typedef enum { IRMref, /* IR reference. */ IRMlit, /* 16 bit unsigned literal. */ IRMcst, /* Constant literal: i, gcr or ptr. */ IRMnone /* Unused operand. */ } IRMode; #define IRM___ IRMnone /* Mode bits: Commutative, {Normal/Ref, Alloc, Load, Store}, Non-weak guard. */ #define IRM_C 0x10 #define IRM_N 0x00 #define IRM_R IRM_N #define IRM_A 0x20 #define IRM_L 0x40 #define IRM_S 0x60 #define IRM_W 0x80 #define IRM_NW (IRM_N|IRM_W) #define IRM_CW (IRM_C|IRM_W) #define IRM_AW (IRM_A|IRM_W) #define IRM_LW (IRM_L|IRM_W) #define irm_op1(m) ((IRMode)((m)&3)) #define irm_op2(m) ((IRMode)(((m)>>2)&3)) #define irm_iscomm(m) ((m) & IRM_C) #define irm_kind(m) ((m) & IRM_S) #define IRMODE(name, m, m1, m2) (((IRM##m1)|((IRM##m2)<<2)|(IRM_##m))^IRM_W), LJ_DATA const uint8_t lj_ir_mode[IR__MAX+1]; /* -- IR instruction types ------------------------------------------------ */ #define IRTSIZE_PGC (LJ_GC64 ? 8 : 4) /* Map of itypes to non-negative numbers and their sizes. ORDER LJ_T. ** LJ_TUPVAL/LJ_TTRACE never appear in a TValue. Use these itypes for ** IRT_P32 and IRT_P64, which never escape the IR. ** The various integers are only used in the IR and can only escape to ** a TValue after implicit or explicit conversion. Their types must be ** contiguous and next to IRT_NUM (see the typerange macros below). */ #define IRTDEF(_) \ _(NIL, 4) _(FALSE, 4) _(TRUE, 4) _(LIGHTUD, LJ_64 ? 8 : 4) \ _(STR, IRTSIZE_PGC) _(P32, 4) _(THREAD, IRTSIZE_PGC) _(PROTO, IRTSIZE_PGC) \ _(FUNC, IRTSIZE_PGC) _(P64, 8) _(CDATA, IRTSIZE_PGC) _(TAB, IRTSIZE_PGC) \ _(UDATA, IRTSIZE_PGC) \ _(FLOAT, 4) _(NUM, 8) _(I8, 1) _(U8, 1) _(I16, 2) _(U16, 2) \ _(INT, 4) _(U32, 4) _(I64, 8) _(U64, 8) \ _(SOFTFP, 4) /* There is room for 8 more types. */ /* IR result type and flags (8 bit). */ typedef enum { #define IRTENUM(name, size) IRT_##name, IRTDEF(IRTENUM) #undef IRTENUM IRT__MAX, /* Native pointer type and the corresponding integer type. */ IRT_PTR = LJ_64 ? IRT_P64 : IRT_P32, IRT_PGC = LJ_GC64 ? IRT_P64 : IRT_P32, IRT_IGC = LJ_GC64 ? IRT_I64 : IRT_INT, IRT_INTP = LJ_64 ? IRT_I64 : IRT_INT, IRT_UINTP = LJ_64 ? IRT_U64 : IRT_U32, /* Additional flags. */ IRT_MARK = 0x20, /* Marker for misc. purposes. */ IRT_ISPHI = 0x40, /* Instruction is left or right PHI operand. */ IRT_GUARD = 0x80, /* Instruction is a guard. */ /* Masks. */ IRT_TYPE = 0x1f, IRT_T = 0xff } IRType; #define irtype_ispri(irt) ((uint32_t)(irt) <= IRT_TRUE) /* Stored IRType. */ typedef struct IRType1 { uint8_t irt; } IRType1; #define IRT(o, t) ((uint32_t)(((o)<<8) | (t))) #define IRTI(o) (IRT((o), IRT_INT)) #define IRTN(o) (IRT((o), IRT_NUM)) #define IRTG(o, t) (IRT((o), IRT_GUARD|(t))) #define IRTGI(o) (IRT((o), IRT_GUARD|IRT_INT)) #define irt_t(t) ((IRType)(t).irt) #define irt_type(t) ((IRType)((t).irt & IRT_TYPE)) #define irt_sametype(t1, t2) ((((t1).irt ^ (t2).irt) & IRT_TYPE) == 0) #define irt_typerange(t, first, last) \ ((uint32_t)((t).irt & IRT_TYPE) - (uint32_t)(first) <= (uint32_t)(last-first)) #define irt_isnil(t) (irt_type(t) == IRT_NIL) #define irt_ispri(t) ((uint32_t)irt_type(t) <= IRT_TRUE) #define irt_islightud(t) (irt_type(t) == IRT_LIGHTUD) #define irt_isstr(t) (irt_type(t) == IRT_STR) #define irt_istab(t) (irt_type(t) == IRT_TAB) #define irt_iscdata(t) (irt_type(t) == IRT_CDATA) #define irt_isfloat(t) (irt_type(t) == IRT_FLOAT) #define irt_isnum(t) (irt_type(t) == IRT_NUM) #define irt_isint(t) (irt_type(t) == IRT_INT) #define irt_isi8(t) (irt_type(t) == IRT_I8) #define irt_isu8(t) (irt_type(t) == IRT_U8) #define irt_isi16(t) (irt_type(t) == IRT_I16) #define irt_isu16(t) (irt_type(t) == IRT_U16) #define irt_isu32(t) (irt_type(t) == IRT_U32) #define irt_isi64(t) (irt_type(t) == IRT_I64) #define irt_isu64(t) (irt_type(t) == IRT_U64) #define irt_isfp(t) (irt_isnum(t) || irt_isfloat(t)) #define irt_isinteger(t) (irt_typerange((t), IRT_I8, IRT_INT)) #define irt_isgcv(t) (irt_typerange((t), IRT_STR, IRT_UDATA)) #define irt_isaddr(t) (irt_typerange((t), IRT_LIGHTUD, IRT_UDATA)) #define irt_isint64(t) (irt_typerange((t), IRT_I64, IRT_U64)) #if LJ_GC64 /* Include IRT_NIL, so IR(ASMREF_L) (aka REF_NIL) is considered 64 bit. */ #define IRT_IS64 \ ((1u<<IRT_NUM)|(1u<<IRT_I64)|(1u<<IRT_U64)|(1u<<IRT_P64)|\ (1u<<IRT_LIGHTUD)|(1u<<IRT_STR)|(1u<<IRT_THREAD)|(1u<<IRT_PROTO)|\ (1u<<IRT_FUNC)|(1u<<IRT_CDATA)|(1u<<IRT_TAB)|(1u<<IRT_UDATA)|\ (1u<<IRT_NIL)) #elif LJ_64 #define IRT_IS64 \ ((1u<<IRT_NUM)|(1u<<IRT_I64)|(1u<<IRT_U64)|(1u<<IRT_P64)|(1u<<IRT_LIGHTUD)) #else #define IRT_IS64 \ ((1u<<IRT_NUM)|(1u<<IRT_I64)|(1u<<IRT_U64)) #endif #define irt_is64(t) ((IRT_IS64 >> irt_type(t)) & 1) #define irt_is64orfp(t) (((IRT_IS64|(1u<<IRT_FLOAT))>>irt_type(t)) & 1) #define irt_size(t) (lj_ir_type_size[irt_t((t))]) LJ_DATA const uint8_t lj_ir_type_size[]; static LJ_AINLINE IRType itype2irt(const TValue *tv) { if (tvisint(tv)) return IRT_INT; else if (tvisnum(tv)) return IRT_NUM; #if LJ_64 && !LJ_GC64 else if (tvislightud(tv)) return IRT_LIGHTUD; #endif else return (IRType)~itype(tv); } static LJ_AINLINE uint32_t irt_toitype_(IRType t) { lj_assertX(!LJ_64 || LJ_GC64 || t != IRT_LIGHTUD, "no plain type tag for lightuserdata"); if (LJ_DUALNUM && t > IRT_NUM) { return LJ_TISNUM; } else { lj_assertX(t <= IRT_NUM, "no plain type tag for IR type %d", t); return ~(uint32_t)t; } } #define irt_toitype(t) irt_toitype_(irt_type((t))) #define irt_isguard(t) ((t).irt & IRT_GUARD) #define irt_ismarked(t) ((t).irt & IRT_MARK) #define irt_setmark(t) ((t).irt |= IRT_MARK) #define irt_clearmark(t) ((t).irt &= ~IRT_MARK) #define irt_isphi(t) ((t).irt & IRT_ISPHI) #define irt_setphi(t) ((t).irt |= IRT_ISPHI) #define irt_clearphi(t) ((t).irt &= ~IRT_ISPHI) /* Stored combined IR opcode and type. */ typedef uint16_t IROpT; /* -- IR references ------------------------------------------------------- */ /* IR references. */ typedef uint16_t IRRef1; /* One stored reference. */ typedef uint32_t IRRef2; /* Two stored references. */ typedef uint32_t IRRef; /* Used to pass around references. */ /* Fixed references. */ enum { REF_BIAS = 0x8000, REF_TRUE = REF_BIAS-3, REF_FALSE = REF_BIAS-2, REF_NIL = REF_BIAS-1, /* \--- Constants grow downwards. */ REF_BASE = REF_BIAS, /* /--- IR grows upwards. */ REF_FIRST = REF_BIAS+1, REF_DROP = 0xffff }; /* Note: IRMlit operands must be < REF_BIAS, too! ** This allows for fast and uniform manipulation of all operands ** without looking up the operand mode in lj_ir_mode: ** - CSE calculates the maximum reference of two operands. ** This must work with mixed reference/literal operands, too. ** - DCE marking only checks for operand >= REF_BIAS. ** - LOOP needs to substitute reference operands. ** Constant references and literals must not be modified. */ #define IRREF2(lo, hi) ((IRRef2)(lo) | ((IRRef2)(hi) << 16)) #define irref_isk(ref) ((ref) < REF_BIAS) /* Tagged IR references (32 bit). ** ** +-------+-------+---------------+ ** | irt | flags | ref | ** +-------+-------+---------------+ ** ** The tag holds a copy of the IRType and speeds up IR type checks. */ typedef uint32_t TRef; #define TREF_REFMASK 0x0000ffff #define TREF_FRAME 0x00010000 #define TREF_CONT 0x00020000 #define TREF_KEYINDEX 0x00100000 #define TREF(ref, t) ((TRef)((ref) + ((t)<<24))) #define tref_ref(tr) ((IRRef1)(tr)) #define tref_t(tr) ((IRType)((tr)>>24)) #define tref_type(tr) ((IRType)(((tr)>>24) & IRT_TYPE)) #define tref_typerange(tr, first, last) \ ((((tr)>>24) & IRT_TYPE) - (TRef)(first) <= (TRef)(last-first)) #define tref_istype(tr, t) (((tr) & (IRT_TYPE<<24)) == ((t)<<24)) #define tref_isnil(tr) (tref_istype((tr), IRT_NIL)) #define tref_isfalse(tr) (tref_istype((tr), IRT_FALSE)) #define tref_istrue(tr) (tref_istype((tr), IRT_TRUE)) #define tref_islightud(tr) (tref_istype((tr), IRT_LIGHTUD)) #define tref_isstr(tr) (tref_istype((tr), IRT_STR)) #define tref_isfunc(tr) (tref_istype((tr), IRT_FUNC)) #define tref_iscdata(tr) (tref_istype((tr), IRT_CDATA)) #define tref_istab(tr) (tref_istype((tr), IRT_TAB)) #define tref_isudata(tr) (tref_istype((tr), IRT_UDATA)) #define tref_isnum(tr) (tref_istype((tr), IRT_NUM)) #define tref_isint(tr) (tref_istype((tr), IRT_INT)) #define tref_isbool(tr) (tref_typerange((tr), IRT_FALSE, IRT_TRUE)) #define tref_ispri(tr) (tref_typerange((tr), IRT_NIL, IRT_TRUE)) #define tref_istruecond(tr) (!tref_typerange((tr), IRT_NIL, IRT_FALSE)) #define tref_isinteger(tr) (tref_typerange((tr), IRT_I8, IRT_INT)) #define tref_isnumber(tr) (tref_typerange((tr), IRT_NUM, IRT_INT)) #define tref_isnumber_str(tr) (tref_isnumber((tr)) || tref_isstr((tr))) #define tref_isgcv(tr) (tref_typerange((tr), IRT_STR, IRT_UDATA)) #define tref_isk(tr) (irref_isk(tref_ref((tr)))) #define tref_isk2(tr1, tr2) (irref_isk(tref_ref((tr1) | (tr2)))) #define TREF_PRI(t) (TREF(REF_NIL-(t), (t))) #define TREF_NIL (TREF_PRI(IRT_NIL)) #define TREF_FALSE (TREF_PRI(IRT_FALSE)) #define TREF_TRUE (TREF_PRI(IRT_TRUE)) /* -- IR format ----------------------------------------------------------- */ /* IR instruction format (64 bit). ** ** 16 16 8 8 8 8 ** +-------+-------+---+---+---+---+ ** | op1 | op2 | t | o | r | s | ** +-------+-------+---+---+---+---+ ** | op12/i/gco32 | ot | prev | (alternative fields in union) ** +-------+-------+---+---+---+---+ ** | TValue/gco64 | (2nd IR slot for 64 bit constants) ** +---------------+-------+-------+ ** 32 16 16 ** ** prev is only valid prior to register allocation and then reused for r + s. */ typedef union IRIns { struct { LJ_ENDIAN_LOHI( IRRef1 op1; /* IR operand 1. */ , IRRef1 op2; /* IR operand 2. */ ) IROpT ot; /* IR opcode and type (overlaps t and o). */ IRRef1 prev; /* Previous ins in same chain (overlaps r and s). */ }; struct { IRRef2 op12; /* IR operand 1 and 2 (overlaps op1 and op2). */ LJ_ENDIAN_LOHI( IRType1 t; /* IR type. */ , IROp1 o; /* IR opcode. */ ) LJ_ENDIAN_LOHI( uint8_t r; /* Register allocation (overlaps prev). */ , uint8_t s; /* Spill slot allocation (overlaps prev). */ ) }; int32_t i; /* 32 bit signed integer literal (overlaps op12). */ GCRef gcr; /* GCobj constant (overlaps op12 or entire slot). */ MRef ptr; /* Pointer constant (overlaps op12 or entire slot). */ TValue tv; /* TValue constant (overlaps entire slot). */ } IRIns; #define ir_isk64(ir) \ ((ir)->o == IR_KNUM || (ir)->o == IR_KINT64 || \ (LJ_GC64 && \ ((ir)->o == IR_KGC || (ir)->o == IR_KPTR || (ir)->o == IR_KKPTR))) #define ir_kgc(ir) check_exp((ir)->o == IR_KGC, gcref((ir)[LJ_GC64].gcr)) #define ir_kstr(ir) (gco2str(ir_kgc((ir)))) #define ir_ktab(ir) (gco2tab(ir_kgc((ir)))) #define ir_kfunc(ir) (gco2func(ir_kgc((ir)))) #define ir_kcdata(ir) (gco2cd(ir_kgc((ir)))) #define ir_knum(ir) check_exp((ir)->o == IR_KNUM, &(ir)[1].tv) #define ir_kint64(ir) check_exp((ir)->o == IR_KINT64, &(ir)[1].tv) #define ir_k64(ir) check_exp(ir_isk64(ir), &(ir)[1].tv) #define ir_kptr(ir) \ check_exp((ir)->o == IR_KPTR || (ir)->o == IR_KKPTR, \ mref((ir)[LJ_GC64].ptr, void)) /* A store or any other op with a non-weak guard has a side-effect. */ static LJ_AINLINE int ir_sideeff(IRIns *ir) { return (((ir->t.irt | ~IRT_GUARD) & lj_ir_mode[ir->o]) >= IRM_S); } LJ_STATIC_ASSERT((int)IRT_GUARD == (int)IRM_W); /* Replace IR instruction with NOP. */ static LJ_AINLINE void lj_ir_nop(IRIns *ir) { ir->ot = IRT(IR_NOP, IRT_NIL); ir->op1 = ir->op2 = 0; ir->prev = 0; } #endif
xLua/build/luajit-2.1.0b3/src/lj_ir.h/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_ir.h", "repo_id": "xLua", "token_count": 9625 }
2,121
/* ** FOLD: Constant Folding, Algebraic Simplifications and Reassociation. ** ABCelim: Array Bounds Check Elimination. ** CSE: Common-Subexpression Elimination. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #define lj_opt_fold_c #define LUA_CORE #include <math.h> #include "lj_obj.h" #if LJ_HASJIT #include "lj_buf.h" #include "lj_str.h" #include "lj_tab.h" #include "lj_ir.h" #include "lj_jit.h" #include "lj_ircall.h" #include "lj_iropt.h" #include "lj_trace.h" #if LJ_HASFFI #include "lj_ctype.h" #include "lj_carith.h" #endif #include "lj_vm.h" #include "lj_strscan.h" #include "lj_strfmt.h" /* Here's a short description how the FOLD engine processes instructions: ** ** The FOLD engine receives a single instruction stored in fins (J->fold.ins). ** The instruction and its operands are used to select matching fold rules. ** These are applied iteratively until a fixed point is reached. ** ** The 8 bit opcode of the instruction itself plus the opcodes of the ** two instructions referenced by its operands form a 24 bit key ** 'ins left right' (unused operands -> 0, literals -> lowest 8 bits). ** ** This key is used for partial matching against the fold rules. The ** left/right operand fields of the key are successively masked with ** the 'any' wildcard, from most specific to least specific: ** ** ins left right ** ins any right ** ins left any ** ins any any ** ** The masked key is used to lookup a matching fold rule in a semi-perfect ** hash table. If a matching rule is found, the related fold function is run. ** Multiple rules can share the same fold function. A fold rule may return ** one of several special values: ** ** - NEXTFOLD means no folding was applied, because an additional test ** inside the fold function failed. Matching continues against less ** specific fold rules. Finally the instruction is passed on to CSE. ** ** - RETRYFOLD means the instruction was modified in-place. Folding is ** retried as if this instruction had just been received. ** ** All other return values are terminal actions -- no further folding is ** applied: ** ** - INTFOLD(i) returns a reference to the integer constant i. ** ** - LEFTFOLD and RIGHTFOLD return the left/right operand reference ** without emitting an instruction. ** ** - CSEFOLD and EMITFOLD pass the instruction directly to CSE or emit ** it without passing through any further optimizations. ** ** - FAILFOLD, DROPFOLD and CONDFOLD only apply to instructions which have ** no result (e.g. guarded assertions): FAILFOLD means the guard would ** always fail, i.e. the current trace is pointless. DROPFOLD means ** the guard is always true and has been eliminated. CONDFOLD is a ** shortcut for FAILFOLD + cond (i.e. drop if true, otherwise fail). ** ** - Any other return value is interpreted as an IRRef or TRef. This ** can be a reference to an existing or a newly created instruction. ** Only the least-significant 16 bits (IRRef1) are used to form a TRef ** which is finally returned to the caller. ** ** The FOLD engine receives instructions both from the trace recorder and ** substituted instructions from LOOP unrolling. This means all types ** of instructions may end up here, even though the recorder bypasses ** FOLD in some cases. Thus all loads, stores and allocations must have ** an any/any rule to avoid being passed on to CSE. ** ** Carefully read the following requirements before adding or modifying ** any fold rules: ** ** Requirement #1: All fold rules must preserve their destination type. ** ** Consistently use INTFOLD() (KINT result) or lj_ir_knum() (KNUM result). ** Never use lj_ir_knumint() which can have either a KINT or KNUM result. ** ** Requirement #2: Fold rules should not create *new* instructions which ** reference operands *across* PHIs. ** ** E.g. a RETRYFOLD with 'fins->op1 = fleft->op1' is invalid if the ** left operand is a PHI. Then fleft->op1 would point across the PHI ** frontier to an invariant instruction. Adding a PHI for this instruction ** would be counterproductive. The solution is to add a barrier which ** prevents folding across PHIs, i.e. 'PHIBARRIER(fleft)' in this case. ** The only exception is for recurrences with high latencies like ** repeated int->num->int conversions. ** ** One could relax this condition a bit if the referenced instruction is ** a PHI, too. But this often leads to worse code due to excessive ** register shuffling. ** ** Note: returning *existing* instructions (e.g. LEFTFOLD) is ok, though. ** Even returning fleft->op1 would be ok, because a new PHI will added, ** if needed. But again, this leads to excessive register shuffling and ** should be avoided. ** ** Requirement #3: The set of all fold rules must be monotonic to guarantee ** termination. ** ** The goal is optimization, so one primarily wants to add strength-reducing ** rules. This means eliminating an instruction or replacing an instruction ** with one or more simpler instructions. Don't add fold rules which point ** into the other direction. ** ** Some rules (like commutativity) do not directly reduce the strength of ** an instruction, but enable other fold rules (e.g. by moving constants ** to the right operand). These rules must be made unidirectional to avoid ** cycles. ** ** Rule of thumb: the trace recorder expands the IR and FOLD shrinks it. */ /* Some local macros to save typing. Undef'd at the end. */ #define IR(ref) (&J->cur.ir[(ref)]) #define fins (&J->fold.ins) #define fleft (J->fold.left) #define fright (J->fold.right) #define knumleft (ir_knum(fleft)->n) #define knumright (ir_knum(fright)->n) /* Pass IR on to next optimization in chain (FOLD). */ #define emitir(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_opt_fold(J)) /* Fold function type. Fastcall on x86 significantly reduces their size. */ typedef IRRef (LJ_FASTCALL *FoldFunc)(jit_State *J); /* Macros for the fold specs, so buildvm can recognize them. */ #define LJFOLD(x) #define LJFOLDX(x) #define LJFOLDF(name) static TRef LJ_FASTCALL fold_##name(jit_State *J) /* Note: They must be at the start of a line or buildvm ignores them! */ /* Barrier to prevent using operands across PHIs. */ #define PHIBARRIER(ir) if (irt_isphi((ir)->t)) return NEXTFOLD /* Barrier to prevent folding across a GC step. ** GC steps can only happen at the head of a trace and at LOOP. ** And the GC is only driven forward if there's at least one allocation. */ #define gcstep_barrier(J, ref) \ ((ref) < J->chain[IR_LOOP] && \ (J->chain[IR_SNEW] || J->chain[IR_XSNEW] || \ J->chain[IR_TNEW] || J->chain[IR_TDUP] || \ J->chain[IR_CNEW] || J->chain[IR_CNEWI] || \ J->chain[IR_BUFSTR] || J->chain[IR_TOSTR] || J->chain[IR_CALLA])) /* -- Constant folding for FP numbers ------------------------------------- */ LJFOLD(ADD KNUM KNUM) LJFOLD(SUB KNUM KNUM) LJFOLD(MUL KNUM KNUM) LJFOLD(DIV KNUM KNUM) LJFOLD(LDEXP KNUM KNUM) LJFOLD(MIN KNUM KNUM) LJFOLD(MAX KNUM KNUM) LJFOLDF(kfold_numarith) { lua_Number a = knumleft; lua_Number b = knumright; lua_Number y = lj_vm_foldarith(a, b, fins->o - IR_ADD); return lj_ir_knum(J, y); } LJFOLD(NEG KNUM FLOAD) LJFOLD(ABS KNUM FLOAD) LJFOLDF(kfold_numabsneg) { lua_Number a = knumleft; lua_Number y = lj_vm_foldarith(a, a, fins->o - IR_ADD); return lj_ir_knum(J, y); } LJFOLD(LDEXP KNUM KINT) LJFOLDF(kfold_ldexp) { #if LJ_TARGET_X86ORX64 UNUSED(J); return NEXTFOLD; #else return lj_ir_knum(J, ldexp(knumleft, fright->i)); #endif } LJFOLD(FPMATH KNUM any) LJFOLDF(kfold_fpmath) { lua_Number a = knumleft; lua_Number y = lj_vm_foldfpm(a, fins->op2); return lj_ir_knum(J, y); } LJFOLD(CALLN KNUM any) LJFOLDF(kfold_fpcall1) { const CCallInfo *ci = &lj_ir_callinfo[fins->op2]; if (CCI_TYPE(ci) == IRT_NUM) { double y = ((double (*)(double))ci->func)(knumleft); return lj_ir_knum(J, y); } return NEXTFOLD; } LJFOLD(CALLN CARG IRCALL_atan2) LJFOLDF(kfold_fpcall2) { if (irref_isk(fleft->op1) && irref_isk(fleft->op2)) { const CCallInfo *ci = &lj_ir_callinfo[fins->op2]; double a = ir_knum(IR(fleft->op1))->n; double b = ir_knum(IR(fleft->op2))->n; double y = ((double (*)(double, double))ci->func)(a, b); return lj_ir_knum(J, y); } return NEXTFOLD; } LJFOLD(POW KNUM KINT) LJFOLD(POW KNUM KNUM) LJFOLDF(kfold_numpow) { lua_Number a = knumleft; lua_Number b = fright->o == IR_KINT ? (lua_Number)fright->i : knumright; lua_Number y = lj_vm_foldarith(a, b, IR_POW - IR_ADD); return lj_ir_knum(J, y); } /* Must not use kfold_kref for numbers (could be NaN). */ LJFOLD(EQ KNUM KNUM) LJFOLD(NE KNUM KNUM) LJFOLD(LT KNUM KNUM) LJFOLD(GE KNUM KNUM) LJFOLD(LE KNUM KNUM) LJFOLD(GT KNUM KNUM) LJFOLD(ULT KNUM KNUM) LJFOLD(UGE KNUM KNUM) LJFOLD(ULE KNUM KNUM) LJFOLD(UGT KNUM KNUM) LJFOLDF(kfold_numcomp) { return CONDFOLD(lj_ir_numcmp(knumleft, knumright, (IROp)fins->o)); } /* -- Constant folding for 32 bit integers -------------------------------- */ static int32_t kfold_intop(int32_t k1, int32_t k2, IROp op) { switch (op) { case IR_ADD: k1 += k2; break; case IR_SUB: k1 -= k2; break; case IR_MUL: k1 *= k2; break; case IR_MOD: k1 = lj_vm_modi(k1, k2); break; case IR_NEG: k1 = -k1; break; case IR_BAND: k1 &= k2; break; case IR_BOR: k1 |= k2; break; case IR_BXOR: k1 ^= k2; break; case IR_BSHL: k1 <<= (k2 & 31); break; case IR_BSHR: k1 = (int32_t)((uint32_t)k1 >> (k2 & 31)); break; case IR_BSAR: k1 >>= (k2 & 31); break; case IR_BROL: k1 = (int32_t)lj_rol((uint32_t)k1, (k2 & 31)); break; case IR_BROR: k1 = (int32_t)lj_ror((uint32_t)k1, (k2 & 31)); break; case IR_MIN: k1 = k1 < k2 ? k1 : k2; break; case IR_MAX: k1 = k1 > k2 ? k1 : k2; break; default: lj_assertX(0, "bad IR op %d", op); break; } return k1; } LJFOLD(ADD KINT KINT) LJFOLD(SUB KINT KINT) LJFOLD(MUL KINT KINT) LJFOLD(MOD KINT KINT) LJFOLD(NEG KINT KINT) LJFOLD(BAND KINT KINT) LJFOLD(BOR KINT KINT) LJFOLD(BXOR KINT KINT) LJFOLD(BSHL KINT KINT) LJFOLD(BSHR KINT KINT) LJFOLD(BSAR KINT KINT) LJFOLD(BROL KINT KINT) LJFOLD(BROR KINT KINT) LJFOLD(MIN KINT KINT) LJFOLD(MAX KINT KINT) LJFOLDF(kfold_intarith) { return INTFOLD(kfold_intop(fleft->i, fright->i, (IROp)fins->o)); } LJFOLD(ADDOV KINT KINT) LJFOLD(SUBOV KINT KINT) LJFOLD(MULOV KINT KINT) LJFOLDF(kfold_intovarith) { lua_Number n = lj_vm_foldarith((lua_Number)fleft->i, (lua_Number)fright->i, fins->o - IR_ADDOV); int32_t k = lj_num2int(n); if (n != (lua_Number)k) return FAILFOLD; return INTFOLD(k); } LJFOLD(BNOT KINT) LJFOLDF(kfold_bnot) { return INTFOLD(~fleft->i); } LJFOLD(BSWAP KINT) LJFOLDF(kfold_bswap) { return INTFOLD((int32_t)lj_bswap((uint32_t)fleft->i)); } LJFOLD(LT KINT KINT) LJFOLD(GE KINT KINT) LJFOLD(LE KINT KINT) LJFOLD(GT KINT KINT) LJFOLD(ULT KINT KINT) LJFOLD(UGE KINT KINT) LJFOLD(ULE KINT KINT) LJFOLD(UGT KINT KINT) LJFOLD(ABC KINT KINT) LJFOLDF(kfold_intcomp) { int32_t a = fleft->i, b = fright->i; switch ((IROp)fins->o) { case IR_LT: return CONDFOLD(a < b); case IR_GE: return CONDFOLD(a >= b); case IR_LE: return CONDFOLD(a <= b); case IR_GT: return CONDFOLD(a > b); case IR_ULT: return CONDFOLD((uint32_t)a < (uint32_t)b); case IR_UGE: return CONDFOLD((uint32_t)a >= (uint32_t)b); case IR_ULE: return CONDFOLD((uint32_t)a <= (uint32_t)b); case IR_ABC: case IR_UGT: return CONDFOLD((uint32_t)a > (uint32_t)b); default: lj_assertJ(0, "bad IR op %d", fins->o); return FAILFOLD; } } LJFOLD(UGE any KINT) LJFOLDF(kfold_intcomp0) { if (fright->i == 0) return DROPFOLD; return NEXTFOLD; } /* -- Constant folding for 64 bit integers -------------------------------- */ static uint64_t kfold_int64arith(jit_State *J, uint64_t k1, uint64_t k2, IROp op) { UNUSED(J); #if LJ_HASFFI switch (op) { case IR_ADD: k1 += k2; break; case IR_SUB: k1 -= k2; break; case IR_MUL: k1 *= k2; break; case IR_BAND: k1 &= k2; break; case IR_BOR: k1 |= k2; break; case IR_BXOR: k1 ^= k2; break; case IR_BSHL: k1 <<= (k2 & 63); break; case IR_BSHR: k1 = (int32_t)((uint32_t)k1 >> (k2 & 63)); break; case IR_BSAR: k1 >>= (k2 & 63); break; case IR_BROL: k1 = (int32_t)lj_rol((uint32_t)k1, (k2 & 63)); break; case IR_BROR: k1 = (int32_t)lj_ror((uint32_t)k1, (k2 & 63)); break; default: lj_assertJ(0, "bad IR op %d", op); break; } #else UNUSED(k2); UNUSED(op); lj_assertJ(0, "FFI IR op without FFI"); #endif return k1; } LJFOLD(ADD KINT64 KINT64) LJFOLD(SUB KINT64 KINT64) LJFOLD(MUL KINT64 KINT64) LJFOLD(BAND KINT64 KINT64) LJFOLD(BOR KINT64 KINT64) LJFOLD(BXOR KINT64 KINT64) LJFOLDF(kfold_int64arith) { return INT64FOLD(kfold_int64arith(J, ir_k64(fleft)->u64, ir_k64(fright)->u64, (IROp)fins->o)); } LJFOLD(DIV KINT64 KINT64) LJFOLD(MOD KINT64 KINT64) LJFOLD(POW KINT64 KINT64) LJFOLDF(kfold_int64arith2) { #if LJ_HASFFI uint64_t k1 = ir_k64(fleft)->u64, k2 = ir_k64(fright)->u64; if (irt_isi64(fins->t)) { k1 = fins->o == IR_DIV ? lj_carith_divi64((int64_t)k1, (int64_t)k2) : fins->o == IR_MOD ? lj_carith_modi64((int64_t)k1, (int64_t)k2) : lj_carith_powi64((int64_t)k1, (int64_t)k2); } else { k1 = fins->o == IR_DIV ? lj_carith_divu64(k1, k2) : fins->o == IR_MOD ? lj_carith_modu64(k1, k2) : lj_carith_powu64(k1, k2); } return INT64FOLD(k1); #else UNUSED(J); lj_assertJ(0, "FFI IR op without FFI"); return FAILFOLD; #endif } LJFOLD(BSHL KINT64 KINT) LJFOLD(BSHR KINT64 KINT) LJFOLD(BSAR KINT64 KINT) LJFOLD(BROL KINT64 KINT) LJFOLD(BROR KINT64 KINT) LJFOLDF(kfold_int64shift) { #if LJ_HASFFI uint64_t k = ir_k64(fleft)->u64; int32_t sh = (fright->i & 63); return INT64FOLD(lj_carith_shift64(k, sh, fins->o - IR_BSHL)); #else UNUSED(J); lj_assertJ(0, "FFI IR op without FFI"); return FAILFOLD; #endif } LJFOLD(BNOT KINT64) LJFOLDF(kfold_bnot64) { #if LJ_HASFFI return INT64FOLD(~ir_k64(fleft)->u64); #else UNUSED(J); lj_assertJ(0, "FFI IR op without FFI"); return FAILFOLD; #endif } LJFOLD(BSWAP KINT64) LJFOLDF(kfold_bswap64) { #if LJ_HASFFI return INT64FOLD(lj_bswap64(ir_k64(fleft)->u64)); #else UNUSED(J); lj_assertJ(0, "FFI IR op without FFI"); return FAILFOLD; #endif } LJFOLD(LT KINT64 KINT64) LJFOLD(GE KINT64 KINT64) LJFOLD(LE KINT64 KINT64) LJFOLD(GT KINT64 KINT64) LJFOLD(ULT KINT64 KINT64) LJFOLD(UGE KINT64 KINT64) LJFOLD(ULE KINT64 KINT64) LJFOLD(UGT KINT64 KINT64) LJFOLDF(kfold_int64comp) { #if LJ_HASFFI uint64_t a = ir_k64(fleft)->u64, b = ir_k64(fright)->u64; switch ((IROp)fins->o) { case IR_LT: return CONDFOLD((int64_t)a < (int64_t)b); case IR_GE: return CONDFOLD((int64_t)a >= (int64_t)b); case IR_LE: return CONDFOLD((int64_t)a <= (int64_t)b); case IR_GT: return CONDFOLD((int64_t)a > (int64_t)b); case IR_ULT: return CONDFOLD(a < b); case IR_UGE: return CONDFOLD(a >= b); case IR_ULE: return CONDFOLD(a <= b); case IR_UGT: return CONDFOLD(a > b); default: lj_assertJ(0, "bad IR op %d", fins->o); return FAILFOLD; } #else UNUSED(J); lj_assertJ(0, "FFI IR op without FFI"); return FAILFOLD; #endif } LJFOLD(UGE any KINT64) LJFOLDF(kfold_int64comp0) { #if LJ_HASFFI if (ir_k64(fright)->u64 == 0) return DROPFOLD; return NEXTFOLD; #else UNUSED(J); lj_assertJ(0, "FFI IR op without FFI"); return FAILFOLD; #endif } /* -- Constant folding for strings ---------------------------------------- */ LJFOLD(SNEW KKPTR KINT) LJFOLDF(kfold_snew_kptr) { GCstr *s = lj_str_new(J->L, (const char *)ir_kptr(fleft), (size_t)fright->i); return lj_ir_kstr(J, s); } LJFOLD(SNEW any KINT) LJFOLD(XSNEW any KINT) LJFOLDF(kfold_snew_empty) { if (fright->i == 0) return lj_ir_kstr(J, &J2G(J)->strempty); return NEXTFOLD; } LJFOLD(STRREF KGC KINT) LJFOLDF(kfold_strref) { GCstr *str = ir_kstr(fleft); lj_assertJ((MSize)fright->i <= str->len, "bad string ref"); return lj_ir_kkptr(J, (char *)strdata(str) + fright->i); } LJFOLD(STRREF SNEW any) LJFOLDF(kfold_strref_snew) { PHIBARRIER(fleft); if (irref_isk(fins->op2) && fright->i == 0) { return fleft->op1; /* strref(snew(ptr, len), 0) ==> ptr */ } else { /* Reassociate: strref(snew(strref(str, a), len), b) ==> strref(str, a+b) */ IRIns *ir = IR(fleft->op1); if (ir->o == IR_STRREF) { IRRef1 str = ir->op1; /* IRIns * is not valid across emitir. */ PHIBARRIER(ir); fins->op2 = emitir(IRTI(IR_ADD), ir->op2, fins->op2); /* Clobbers fins! */ fins->op1 = str; fins->ot = IRT(IR_STRREF, IRT_PGC); return RETRYFOLD; } } return NEXTFOLD; } LJFOLD(CALLN CARG IRCALL_lj_str_cmp) LJFOLDF(kfold_strcmp) { if (irref_isk(fleft->op1) && irref_isk(fleft->op2)) { GCstr *a = ir_kstr(IR(fleft->op1)); GCstr *b = ir_kstr(IR(fleft->op2)); return INTFOLD(lj_str_cmp(a, b)); } return NEXTFOLD; } /* -- Constant folding and forwarding for buffers ------------------------- */ /* ** Buffer ops perform stores, but their effect is limited to the buffer ** itself. Also, buffer ops are chained: a use of an op implies a use of ** all other ops up the chain. Conversely, if an op is unused, all ops ** up the chain can go unsed. This largely eliminates the need to treat ** them as stores. ** ** Alas, treating them as normal (IRM_N) ops doesn't work, because they ** cannot be CSEd in isolation. CSE for IRM_N is implicitly done in LOOP ** or if FOLD is disabled. ** ** The compromise is to declare them as loads, emit them like stores and ** CSE whole chains manually when the BUFSTR is to be emitted. Any chain ** fragments left over from CSE are eliminated by DCE. ** ** The string buffer methods emit a USE instead of a BUFSTR to keep the ** chain alive. */ LJFOLD(BUFHDR any any) LJFOLDF(bufhdr_merge) { return fins->op2 == IRBUFHDR_WRITE ? CSEFOLD : EMITFOLD; } LJFOLD(BUFPUT any BUFSTR) LJFOLDF(bufput_bufstr) { if ((J->flags & JIT_F_OPT_FWD)) { IRRef hdr = fright->op2; /* New buffer, no other buffer op inbetween and same buffer? */ if (fleft->o == IR_BUFHDR && fleft->op2 == IRBUFHDR_RESET && fleft->prev == hdr && fleft->op1 == IR(hdr)->op1) { IRRef ref = fins->op1; IR(ref)->op2 = IRBUFHDR_APPEND; /* Modify BUFHDR. */ IR(ref)->op1 = fright->op1; return ref; } /* Replay puts to global temporary buffer. */ if (IR(hdr)->op2 == IRBUFHDR_RESET) { IRIns *ir = IR(fright->op1); /* For now only handle single string.reverse .lower .upper .rep. */ if (ir->o == IR_CALLL && ir->op2 >= IRCALL_lj_buf_putstr_reverse && ir->op2 <= IRCALL_lj_buf_putstr_rep) { IRIns *carg1 = IR(ir->op1); if (ir->op2 == IRCALL_lj_buf_putstr_rep) { IRIns *carg2 = IR(carg1->op1); if (carg2->op1 == hdr) { return lj_ir_call(J, ir->op2, fins->op1, carg2->op2, carg1->op2); } } else if (carg1->op1 == hdr) { return lj_ir_call(J, ir->op2, fins->op1, carg1->op2); } } } } return EMITFOLD; /* Always emit, CSE later. */ } LJFOLD(BUFPUT any any) LJFOLDF(bufput_kgc) { if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD) && fright->o == IR_KGC) { GCstr *s2 = ir_kstr(fright); if (s2->len == 0) { /* Empty string? */ return LEFTFOLD; } else { if (fleft->o == IR_BUFPUT && irref_isk(fleft->op2) && !irt_isphi(fleft->t)) { /* Join two constant string puts in a row. */ GCstr *s1 = ir_kstr(IR(fleft->op2)); IRRef kref = lj_ir_kstr(J, lj_buf_cat2str(J->L, s1, s2)); /* lj_ir_kstr() may realloc the IR and invalidates any IRIns *. */ IR(fins->op1)->op2 = kref; /* Modify previous BUFPUT. */ return fins->op1; } } } return EMITFOLD; /* Always emit, CSE later. */ } LJFOLD(BUFSTR any any) LJFOLDF(bufstr_kfold_cse) { lj_assertJ(fleft->o == IR_BUFHDR || fleft->o == IR_BUFPUT || fleft->o == IR_CALLL, "bad buffer constructor IR op %d", fleft->o); if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD)) { if (fleft->o == IR_BUFHDR) { /* No put operations? */ if (fleft->op2 == IRBUFHDR_RESET) /* Empty buffer? */ return lj_ir_kstr(J, &J2G(J)->strempty); fins->op1 = fleft->op1; fins->op2 = fleft->prev; /* Relies on checks in bufput_append. */ return CSEFOLD; } else if (fleft->o == IR_BUFPUT) { IRIns *irb = IR(fleft->op1); if (irb->o == IR_BUFHDR && irb->op2 == IRBUFHDR_RESET) return fleft->op2; /* Shortcut for a single put operation. */ } } /* Try to CSE the whole chain. */ if (LJ_LIKELY(J->flags & JIT_F_OPT_CSE)) { IRRef ref = J->chain[IR_BUFSTR]; while (ref) { IRIns *irs = IR(ref), *ira = fleft, *irb = IR(irs->op1); while (ira->o == irb->o && ira->op2 == irb->op2) { lj_assertJ(ira->o == IR_BUFHDR || ira->o == IR_BUFPUT || ira->o == IR_CALLL || ira->o == IR_CARG, "bad buffer constructor IR op %d", ira->o); if (ira->o == IR_BUFHDR && ira->op2 == IRBUFHDR_RESET) return ref; /* CSE succeeded. */ if (ira->o == IR_CALLL && ira->op2 == IRCALL_lj_buf_puttab) break; ira = IR(ira->op1); irb = IR(irb->op1); } ref = irs->prev; } } return EMITFOLD; /* No CSE possible. */ } LJFOLD(CALLL CARG IRCALL_lj_buf_putstr_reverse) LJFOLD(CALLL CARG IRCALL_lj_buf_putstr_upper) LJFOLD(CALLL CARG IRCALL_lj_buf_putstr_lower) LJFOLD(CALLL CARG IRCALL_lj_strfmt_putquoted) LJFOLDF(bufput_kfold_op) { if (irref_isk(fleft->op2)) { const CCallInfo *ci = &lj_ir_callinfo[fins->op2]; SBuf *sb = lj_buf_tmp_(J->L); sb = ((SBuf * (LJ_FASTCALL *)(SBuf *, GCstr *))ci->func)(sb, ir_kstr(IR(fleft->op2))); fins->o = IR_BUFPUT; fins->op1 = fleft->op1; fins->op2 = lj_ir_kstr(J, lj_buf_tostr(sb)); return RETRYFOLD; } return EMITFOLD; /* Always emit, CSE later. */ } LJFOLD(CALLL CARG IRCALL_lj_buf_putstr_rep) LJFOLDF(bufput_kfold_rep) { if (irref_isk(fleft->op2)) { IRIns *irc = IR(fleft->op1); if (irref_isk(irc->op2)) { SBuf *sb = lj_buf_tmp_(J->L); sb = lj_buf_putstr_rep(sb, ir_kstr(IR(irc->op2)), IR(fleft->op2)->i); fins->o = IR_BUFPUT; fins->op1 = irc->op1; fins->op2 = lj_ir_kstr(J, lj_buf_tostr(sb)); return RETRYFOLD; } } return EMITFOLD; /* Always emit, CSE later. */ } LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfxint) LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfnum_int) LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfnum_uint) LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfnum) LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfstr) LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfchar) LJFOLDF(bufput_kfold_fmt) { IRIns *irc = IR(fleft->op1); lj_assertJ(irref_isk(irc->op2), "SFormat must be const"); if (irref_isk(fleft->op2)) { SFormat sf = (SFormat)IR(irc->op2)->i; IRIns *ira = IR(fleft->op2); SBuf *sb = lj_buf_tmp_(J->L); switch (fins->op2) { case IRCALL_lj_strfmt_putfxint: sb = lj_strfmt_putfxint(sb, sf, ir_k64(ira)->u64); break; case IRCALL_lj_strfmt_putfstr: sb = lj_strfmt_putfstr(sb, sf, ir_kstr(ira)); break; case IRCALL_lj_strfmt_putfchar: sb = lj_strfmt_putfchar(sb, sf, ira->i); break; case IRCALL_lj_strfmt_putfnum_int: case IRCALL_lj_strfmt_putfnum_uint: case IRCALL_lj_strfmt_putfnum: default: { const CCallInfo *ci = &lj_ir_callinfo[fins->op2]; sb = ((SBuf * (*)(SBuf *, SFormat, lua_Number))ci->func)(sb, sf, ir_knum(ira)->n); break; } } fins->o = IR_BUFPUT; fins->op1 = irc->op1; fins->op2 = lj_ir_kstr(J, lj_buf_tostr(sb)); return RETRYFOLD; } return EMITFOLD; /* Always emit, CSE later. */ } /* -- Constant folding of pointer arithmetic ------------------------------ */ LJFOLD(ADD KGC KINT) LJFOLD(ADD KGC KINT64) LJFOLDF(kfold_add_kgc) { GCobj *o = ir_kgc(fleft); #if LJ_64 ptrdiff_t ofs = (ptrdiff_t)ir_kint64(fright)->u64; #else ptrdiff_t ofs = fright->i; #endif #if LJ_HASFFI if (irt_iscdata(fleft->t)) { CType *ct = ctype_raw(ctype_ctsG(J2G(J)), gco2cd(o)->ctypeid); if (ctype_isnum(ct->info) || ctype_isenum(ct->info) || ctype_isptr(ct->info) || ctype_isfunc(ct->info) || ctype_iscomplex(ct->info) || ctype_isvector(ct->info)) return lj_ir_kkptr(J, (char *)o + ofs); } #endif return lj_ir_kptr(J, (char *)o + ofs); } LJFOLD(ADD KPTR KINT) LJFOLD(ADD KPTR KINT64) LJFOLD(ADD KKPTR KINT) LJFOLD(ADD KKPTR KINT64) LJFOLDF(kfold_add_kptr) { void *p = ir_kptr(fleft); #if LJ_64 ptrdiff_t ofs = (ptrdiff_t)ir_kint64(fright)->u64; #else ptrdiff_t ofs = fright->i; #endif return lj_ir_kptr_(J, fleft->o, (char *)p + ofs); } LJFOLD(ADD any KGC) LJFOLD(ADD any KPTR) LJFOLD(ADD any KKPTR) LJFOLDF(kfold_add_kright) { if (fleft->o == IR_KINT || fleft->o == IR_KINT64) { IRRef1 tmp = fins->op1; fins->op1 = fins->op2; fins->op2 = tmp; return RETRYFOLD; } return NEXTFOLD; } /* -- Constant folding of conversions ------------------------------------- */ LJFOLD(TOBIT KNUM KNUM) LJFOLDF(kfold_tobit) { return INTFOLD(lj_num2bit(knumleft)); } LJFOLD(CONV KINT IRCONV_NUM_INT) LJFOLDF(kfold_conv_kint_num) { return lj_ir_knum(J, (lua_Number)fleft->i); } LJFOLD(CONV KINT IRCONV_NUM_U32) LJFOLDF(kfold_conv_kintu32_num) { return lj_ir_knum(J, (lua_Number)(uint32_t)fleft->i); } LJFOLD(CONV KINT IRCONV_INT_I8) LJFOLD(CONV KINT IRCONV_INT_U8) LJFOLD(CONV KINT IRCONV_INT_I16) LJFOLD(CONV KINT IRCONV_INT_U16) LJFOLDF(kfold_conv_kint_ext) { int32_t k = fleft->i; if ((fins->op2 & IRCONV_SRCMASK) == IRT_I8) k = (int8_t)k; else if ((fins->op2 & IRCONV_SRCMASK) == IRT_U8) k = (uint8_t)k; else if ((fins->op2 & IRCONV_SRCMASK) == IRT_I16) k = (int16_t)k; else k = (uint16_t)k; return INTFOLD(k); } LJFOLD(CONV KINT IRCONV_I64_INT) LJFOLD(CONV KINT IRCONV_U64_INT) LJFOLD(CONV KINT IRCONV_I64_U32) LJFOLD(CONV KINT IRCONV_U64_U32) LJFOLDF(kfold_conv_kint_i64) { if ((fins->op2 & IRCONV_SEXT)) return INT64FOLD((uint64_t)(int64_t)fleft->i); else return INT64FOLD((uint64_t)(int64_t)(uint32_t)fleft->i); } LJFOLD(CONV KINT64 IRCONV_NUM_I64) LJFOLDF(kfold_conv_kint64_num_i64) { return lj_ir_knum(J, (lua_Number)(int64_t)ir_kint64(fleft)->u64); } LJFOLD(CONV KINT64 IRCONV_NUM_U64) LJFOLDF(kfold_conv_kint64_num_u64) { return lj_ir_knum(J, (lua_Number)ir_kint64(fleft)->u64); } LJFOLD(CONV KINT64 IRCONV_INT_I64) LJFOLD(CONV KINT64 IRCONV_U32_I64) LJFOLDF(kfold_conv_kint64_int_i64) { return INTFOLD((int32_t)ir_kint64(fleft)->u64); } LJFOLD(CONV KNUM IRCONV_INT_NUM) LJFOLDF(kfold_conv_knum_int_num) { lua_Number n = knumleft; int32_t k = lj_num2int(n); if (irt_isguard(fins->t) && n != (lua_Number)k) { /* We're about to create a guard which always fails, like CONV +1.5. ** Some pathological loops cause this during LICM, e.g.: ** local x,k,t = 0,1.5,{1,[1.5]=2} ** for i=1,200 do x = x+ t[k]; k = k == 1 and 1.5 or 1 end ** assert(x == 300) */ return FAILFOLD; } return INTFOLD(k); } LJFOLD(CONV KNUM IRCONV_U32_NUM) LJFOLDF(kfold_conv_knum_u32_num) { #ifdef _MSC_VER { /* Workaround for MSVC bug. */ volatile uint32_t u = (uint32_t)knumleft; return INTFOLD((int32_t)u); } #else return INTFOLD((int32_t)(uint32_t)knumleft); #endif } LJFOLD(CONV KNUM IRCONV_I64_NUM) LJFOLDF(kfold_conv_knum_i64_num) { return INT64FOLD((uint64_t)(int64_t)knumleft); } LJFOLD(CONV KNUM IRCONV_U64_NUM) LJFOLDF(kfold_conv_knum_u64_num) { return INT64FOLD(lj_num2u64(knumleft)); } LJFOLD(TOSTR KNUM any) LJFOLDF(kfold_tostr_knum) { return lj_ir_kstr(J, lj_strfmt_num(J->L, ir_knum(fleft))); } LJFOLD(TOSTR KINT any) LJFOLDF(kfold_tostr_kint) { return lj_ir_kstr(J, fins->op2 == IRTOSTR_INT ? lj_strfmt_int(J->L, fleft->i) : lj_strfmt_char(J->L, fleft->i)); } LJFOLD(STRTO KGC) LJFOLDF(kfold_strto) { TValue n; if (lj_strscan_num(ir_kstr(fleft), &n)) return lj_ir_knum(J, numV(&n)); return FAILFOLD; } /* -- Constant folding of equality checks --------------------------------- */ /* Don't constant-fold away FLOAD checks against KNULL. */ LJFOLD(EQ FLOAD KNULL) LJFOLD(NE FLOAD KNULL) LJFOLDX(lj_opt_cse) /* But fold all other KNULL compares, since only KNULL is equal to KNULL. */ LJFOLD(EQ any KNULL) LJFOLD(NE any KNULL) LJFOLD(EQ KNULL any) LJFOLD(NE KNULL any) LJFOLD(EQ KINT KINT) /* Constants are unique, so same refs <==> same value. */ LJFOLD(NE KINT KINT) LJFOLD(EQ KINT64 KINT64) LJFOLD(NE KINT64 KINT64) LJFOLD(EQ KGC KGC) LJFOLD(NE KGC KGC) LJFOLDF(kfold_kref) { return CONDFOLD((fins->op1 == fins->op2) ^ (fins->o == IR_NE)); } /* -- Algebraic shortcuts ------------------------------------------------- */ LJFOLD(FPMATH FPMATH IRFPM_FLOOR) LJFOLD(FPMATH FPMATH IRFPM_CEIL) LJFOLD(FPMATH FPMATH IRFPM_TRUNC) LJFOLDF(shortcut_round) { IRFPMathOp op = (IRFPMathOp)fleft->op2; if (op == IRFPM_FLOOR || op == IRFPM_CEIL || op == IRFPM_TRUNC) return LEFTFOLD; /* round(round_left(x)) = round_left(x) */ return NEXTFOLD; } LJFOLD(ABS ABS FLOAD) LJFOLDF(shortcut_left) { return LEFTFOLD; /* f(g(x)) ==> g(x) */ } LJFOLD(ABS NEG FLOAD) LJFOLDF(shortcut_dropleft) { PHIBARRIER(fleft); fins->op1 = fleft->op1; /* abs(neg(x)) ==> abs(x) */ return RETRYFOLD; } /* Note: no safe shortcuts with STRTO and TOSTR ("1e2" ==> +100 ==> "100"). */ LJFOLD(NEG NEG any) LJFOLD(BNOT BNOT) LJFOLD(BSWAP BSWAP) LJFOLDF(shortcut_leftleft) { PHIBARRIER(fleft); /* See above. Fold would be ok, but not beneficial. */ return fleft->op1; /* f(g(x)) ==> x */ } /* -- FP algebraic simplifications ---------------------------------------- */ /* FP arithmetic is tricky -- there's not much to simplify. ** Please note the following common pitfalls before sending "improvements": ** x+0 ==> x is INVALID for x=-0 ** 0-x ==> -x is INVALID for x=+0 ** x*0 ==> 0 is INVALID for x=-0, x=+-Inf or x=NaN */ LJFOLD(ADD NEG any) LJFOLDF(simplify_numadd_negx) { PHIBARRIER(fleft); fins->o = IR_SUB; /* (-a) + b ==> b - a */ fins->op1 = fins->op2; fins->op2 = fleft->op1; return RETRYFOLD; } LJFOLD(ADD any NEG) LJFOLDF(simplify_numadd_xneg) { PHIBARRIER(fright); fins->o = IR_SUB; /* a + (-b) ==> a - b */ fins->op2 = fright->op1; return RETRYFOLD; } LJFOLD(SUB any KNUM) LJFOLDF(simplify_numsub_k) { if (ir_knum(fright)->u64 == 0) /* x - (+0) ==> x */ return LEFTFOLD; return NEXTFOLD; } LJFOLD(SUB NEG KNUM) LJFOLDF(simplify_numsub_negk) { PHIBARRIER(fleft); fins->op2 = fleft->op1; /* (-x) - k ==> (-k) - x */ fins->op1 = (IRRef1)lj_ir_knum(J, -knumright); return RETRYFOLD; } LJFOLD(SUB any NEG) LJFOLDF(simplify_numsub_xneg) { PHIBARRIER(fright); fins->o = IR_ADD; /* a - (-b) ==> a + b */ fins->op2 = fright->op1; return RETRYFOLD; } LJFOLD(MUL any KNUM) LJFOLD(DIV any KNUM) LJFOLDF(simplify_nummuldiv_k) { lua_Number n = knumright; if (n == 1.0) { /* x o 1 ==> x */ return LEFTFOLD; } else if (n == -1.0) { /* x o -1 ==> -x */ IRRef op1 = fins->op1; fins->op2 = (IRRef1)lj_ir_ksimd(J, LJ_KSIMD_NEG); /* Modifies fins. */ fins->op1 = op1; fins->o = IR_NEG; return RETRYFOLD; } else if (fins->o == IR_MUL && n == 2.0) { /* x * 2 ==> x + x */ fins->o = IR_ADD; fins->op2 = fins->op1; return RETRYFOLD; } else if (fins->o == IR_DIV) { /* x / 2^k ==> x * 2^-k */ uint64_t u = ir_knum(fright)->u64; uint32_t ex = ((uint32_t)(u >> 52) & 0x7ff); if ((u & U64x(000fffff,ffffffff)) == 0 && ex - 1 < 0x7fd) { u = (u & ((uint64_t)1 << 63)) | ((uint64_t)(0x7fe - ex) << 52); fins->o = IR_MUL; /* Multiply by exact reciprocal. */ fins->op2 = lj_ir_knum_u64(J, u); return RETRYFOLD; } } return NEXTFOLD; } LJFOLD(MUL NEG KNUM) LJFOLD(DIV NEG KNUM) LJFOLDF(simplify_nummuldiv_negk) { PHIBARRIER(fleft); fins->op1 = fleft->op1; /* (-a) o k ==> a o (-k) */ fins->op2 = (IRRef1)lj_ir_knum(J, -knumright); return RETRYFOLD; } LJFOLD(MUL NEG NEG) LJFOLD(DIV NEG NEG) LJFOLDF(simplify_nummuldiv_negneg) { PHIBARRIER(fleft); PHIBARRIER(fright); fins->op1 = fleft->op1; /* (-a) o (-b) ==> a o b */ fins->op2 = fright->op1; return RETRYFOLD; } LJFOLD(POW any KINT) LJFOLDF(simplify_numpow_xkint) { int32_t k = fright->i; TRef ref = fins->op1; if (k == 0) /* x ^ 0 ==> 1 */ return lj_ir_knum_one(J); /* Result must be a number, not an int. */ if (k == 1) /* x ^ 1 ==> x */ return LEFTFOLD; if ((uint32_t)(k+65536) > 2*65536u) /* Limit code explosion. */ return NEXTFOLD; if (k < 0) { /* x ^ (-k) ==> (1/x) ^ k. */ ref = emitir(IRTN(IR_DIV), lj_ir_knum_one(J), ref); k = -k; } /* Unroll x^k for 1 <= k <= 65536. */ for (; (k & 1) == 0; k >>= 1) /* Handle leading zeros. */ ref = emitir(IRTN(IR_MUL), ref, ref); if ((k >>= 1) != 0) { /* Handle trailing bits. */ TRef tmp = emitir(IRTN(IR_MUL), ref, ref); for (; k != 1; k >>= 1) { if (k & 1) ref = emitir(IRTN(IR_MUL), ref, tmp); tmp = emitir(IRTN(IR_MUL), tmp, tmp); } ref = emitir(IRTN(IR_MUL), ref, tmp); } return ref; } LJFOLD(POW any KNUM) LJFOLDF(simplify_numpow_xknum) { if (knumright == 0.5) /* x ^ 0.5 ==> sqrt(x) */ return emitir(IRTN(IR_FPMATH), fins->op1, IRFPM_SQRT); return NEXTFOLD; } LJFOLD(POW KNUM any) LJFOLDF(simplify_numpow_kx) { lua_Number n = knumleft; if (n == 2.0 && irt_isint(fright->t)) { /* 2.0 ^ i ==> ldexp(1.0, i) */ #if LJ_TARGET_X86ORX64 /* Different IR_LDEXP calling convention on x86/x64 requires conversion. */ fins->o = IR_CONV; fins->op1 = fins->op2; fins->op2 = IRCONV_NUM_INT; fins->op2 = (IRRef1)lj_opt_fold(J); #endif fins->op1 = (IRRef1)lj_ir_knum_one(J); fins->o = IR_LDEXP; return RETRYFOLD; } return NEXTFOLD; } /* -- Simplify conversions ------------------------------------------------ */ LJFOLD(CONV CONV IRCONV_NUM_INT) /* _NUM */ LJFOLDF(shortcut_conv_num_int) { PHIBARRIER(fleft); /* Only safe with a guarded conversion to int. */ if ((fleft->op2 & IRCONV_SRCMASK) == IRT_NUM && irt_isguard(fleft->t)) return fleft->op1; /* f(g(x)) ==> x */ return NEXTFOLD; } LJFOLD(CONV CONV IRCONV_INT_NUM) /* _INT */ LJFOLD(CONV CONV IRCONV_U32_NUM) /* _U32*/ LJFOLDF(simplify_conv_int_num) { /* Fold even across PHI to avoid expensive num->int conversions in loop. */ if ((fleft->op2 & IRCONV_SRCMASK) == ((fins->op2 & IRCONV_DSTMASK) >> IRCONV_DSH)) return fleft->op1; return NEXTFOLD; } LJFOLD(CONV CONV IRCONV_I64_NUM) /* _INT or _U32 */ LJFOLD(CONV CONV IRCONV_U64_NUM) /* _INT or _U32 */ LJFOLDF(simplify_conv_i64_num) { PHIBARRIER(fleft); if ((fleft->op2 & IRCONV_SRCMASK) == IRT_INT) { /* Reduce to a sign-extension. */ fins->op1 = fleft->op1; fins->op2 = ((IRT_I64<<5)|IRT_INT|IRCONV_SEXT); return RETRYFOLD; } else if ((fleft->op2 & IRCONV_SRCMASK) == IRT_U32) { #if LJ_TARGET_X64 return fleft->op1; #else /* Reduce to a zero-extension. */ fins->op1 = fleft->op1; fins->op2 = (IRT_I64<<5)|IRT_U32; return RETRYFOLD; #endif } return NEXTFOLD; } LJFOLD(CONV CONV IRCONV_INT_I64) /* _INT or _U32 */ LJFOLD(CONV CONV IRCONV_INT_U64) /* _INT or _U32 */ LJFOLD(CONV CONV IRCONV_U32_I64) /* _INT or _U32 */ LJFOLD(CONV CONV IRCONV_U32_U64) /* _INT or _U32 */ LJFOLDF(simplify_conv_int_i64) { int src; PHIBARRIER(fleft); src = (fleft->op2 & IRCONV_SRCMASK); if (src == IRT_INT || src == IRT_U32) { if (src == ((fins->op2 & IRCONV_DSTMASK) >> IRCONV_DSH)) { return fleft->op1; } else { fins->op2 = ((fins->op2 & IRCONV_DSTMASK) | src); fins->op1 = fleft->op1; return RETRYFOLD; } } return NEXTFOLD; } LJFOLD(CONV CONV IRCONV_FLOAT_NUM) /* _FLOAT */ LJFOLDF(simplify_conv_flt_num) { PHIBARRIER(fleft); if ((fleft->op2 & IRCONV_SRCMASK) == IRT_FLOAT) return fleft->op1; return NEXTFOLD; } /* Shortcut TOBIT + IRT_NUM <- IRT_INT/IRT_U32 conversion. */ LJFOLD(TOBIT CONV KNUM) LJFOLDF(simplify_tobit_conv) { /* Fold even across PHI to avoid expensive num->int conversions in loop. */ if ((fleft->op2 & IRCONV_SRCMASK) == IRT_INT) { lj_assertJ(irt_isnum(fleft->t), "expected TOBIT number arg"); return fleft->op1; } else if ((fleft->op2 & IRCONV_SRCMASK) == IRT_U32) { lj_assertJ(irt_isnum(fleft->t), "expected TOBIT number arg"); fins->o = IR_CONV; fins->op1 = fleft->op1; fins->op2 = (IRT_INT<<5)|IRT_U32; return RETRYFOLD; } return NEXTFOLD; } /* Shortcut floor/ceil/round + IRT_NUM <- IRT_INT/IRT_U32 conversion. */ LJFOLD(FPMATH CONV IRFPM_FLOOR) LJFOLD(FPMATH CONV IRFPM_CEIL) LJFOLD(FPMATH CONV IRFPM_TRUNC) LJFOLDF(simplify_floor_conv) { if ((fleft->op2 & IRCONV_SRCMASK) == IRT_INT || (fleft->op2 & IRCONV_SRCMASK) == IRT_U32) return LEFTFOLD; return NEXTFOLD; } /* Strength reduction of widening. */ LJFOLD(CONV any IRCONV_I64_INT) LJFOLD(CONV any IRCONV_U64_INT) LJFOLDF(simplify_conv_sext) { IRRef ref = fins->op1; int64_t ofs = 0; if (!(fins->op2 & IRCONV_SEXT)) return NEXTFOLD; PHIBARRIER(fleft); if (fleft->o == IR_XLOAD && (irt_isu8(fleft->t) || irt_isu16(fleft->t))) goto ok_reduce; if (fleft->o == IR_ADD && irref_isk(fleft->op2)) { ofs = (int64_t)IR(fleft->op2)->i; ref = fleft->op1; } /* Use scalar evolution analysis results to strength-reduce sign-extension. */ if (ref == J->scev.idx) { IRRef lo = J->scev.dir ? J->scev.start : J->scev.stop; lj_assertJ(irt_isint(J->scev.t), "only int SCEV supported"); if (lo && IR(lo)->o == IR_KINT && IR(lo)->i + ofs >= 0) { ok_reduce: #if LJ_TARGET_X64 /* Eliminate widening. All 32 bit ops do an implicit zero-extension. */ return LEFTFOLD; #else /* Reduce to a (cheaper) zero-extension. */ fins->op2 &= ~IRCONV_SEXT; return RETRYFOLD; #endif } } return NEXTFOLD; } /* Strength reduction of narrowing. */ LJFOLD(CONV ADD IRCONV_INT_I64) LJFOLD(CONV SUB IRCONV_INT_I64) LJFOLD(CONV MUL IRCONV_INT_I64) LJFOLD(CONV ADD IRCONV_INT_U64) LJFOLD(CONV SUB IRCONV_INT_U64) LJFOLD(CONV MUL IRCONV_INT_U64) LJFOLD(CONV ADD IRCONV_U32_I64) LJFOLD(CONV SUB IRCONV_U32_I64) LJFOLD(CONV MUL IRCONV_U32_I64) LJFOLD(CONV ADD IRCONV_U32_U64) LJFOLD(CONV SUB IRCONV_U32_U64) LJFOLD(CONV MUL IRCONV_U32_U64) LJFOLDF(simplify_conv_narrow) { #if LJ_64 UNUSED(J); return NEXTFOLD; #else IROp op = (IROp)fleft->o; IRType t = irt_type(fins->t); IRRef op1 = fleft->op1, op2 = fleft->op2, mode = fins->op2; PHIBARRIER(fleft); op1 = emitir(IRT(IR_CONV, t), op1, mode); op2 = emitir(IRT(IR_CONV, t), op2, mode); fins->ot = IRT(op, t); fins->op1 = op1; fins->op2 = op2; return RETRYFOLD; #endif } /* Special CSE rule for CONV. */ LJFOLD(CONV any any) LJFOLDF(cse_conv) { if (LJ_LIKELY(J->flags & JIT_F_OPT_CSE)) { IRRef op1 = fins->op1, op2 = (fins->op2 & IRCONV_MODEMASK); uint8_t guard = irt_isguard(fins->t); IRRef ref = J->chain[IR_CONV]; while (ref > op1) { IRIns *ir = IR(ref); /* Commoning with stronger checks is ok. */ if (ir->op1 == op1 && (ir->op2 & IRCONV_MODEMASK) == op2 && irt_isguard(ir->t) >= guard) return ref; ref = ir->prev; } } return EMITFOLD; /* No fallthrough to regular CSE. */ } /* FP conversion narrowing. */ LJFOLD(TOBIT ADD KNUM) LJFOLD(TOBIT SUB KNUM) LJFOLD(CONV ADD IRCONV_INT_NUM) LJFOLD(CONV SUB IRCONV_INT_NUM) LJFOLD(CONV ADD IRCONV_I64_NUM) LJFOLD(CONV SUB IRCONV_I64_NUM) LJFOLDF(narrow_convert) { PHIBARRIER(fleft); /* Narrowing ignores PHIs and repeating it inside the loop is not useful. */ if (J->chain[IR_LOOP]) return NEXTFOLD; lj_assertJ(fins->o != IR_CONV || (fins->op2&IRCONV_CONVMASK) != IRCONV_TOBIT, "unexpected CONV TOBIT"); return lj_opt_narrow_convert(J); } /* -- Integer algebraic simplifications ----------------------------------- */ LJFOLD(ADD any KINT) LJFOLD(ADDOV any KINT) LJFOLD(SUBOV any KINT) LJFOLDF(simplify_intadd_k) { if (fright->i == 0) /* i o 0 ==> i */ return LEFTFOLD; return NEXTFOLD; } LJFOLD(MULOV any KINT) LJFOLDF(simplify_intmul_k) { if (fright->i == 0) /* i * 0 ==> 0 */ return RIGHTFOLD; if (fright->i == 1) /* i * 1 ==> i */ return LEFTFOLD; if (fright->i == 2) { /* i * 2 ==> i + i */ fins->o = IR_ADDOV; fins->op2 = fins->op1; return RETRYFOLD; } return NEXTFOLD; } LJFOLD(SUB any KINT) LJFOLDF(simplify_intsub_k) { if (fright->i == 0) /* i - 0 ==> i */ return LEFTFOLD; fins->o = IR_ADD; /* i - k ==> i + (-k) */ fins->op2 = (IRRef1)lj_ir_kint(J, -fright->i); /* Overflow for -2^31 ok. */ return RETRYFOLD; } LJFOLD(SUB KINT any) LJFOLD(SUB KINT64 any) LJFOLDF(simplify_intsub_kleft) { if (fleft->o == IR_KINT ? (fleft->i == 0) : (ir_kint64(fleft)->u64 == 0)) { fins->o = IR_NEG; /* 0 - i ==> -i */ fins->op1 = fins->op2; return RETRYFOLD; } return NEXTFOLD; } LJFOLD(ADD any KINT64) LJFOLDF(simplify_intadd_k64) { if (ir_kint64(fright)->u64 == 0) /* i + 0 ==> i */ return LEFTFOLD; return NEXTFOLD; } LJFOLD(SUB any KINT64) LJFOLDF(simplify_intsub_k64) { uint64_t k = ir_kint64(fright)->u64; if (k == 0) /* i - 0 ==> i */ return LEFTFOLD; fins->o = IR_ADD; /* i - k ==> i + (-k) */ fins->op2 = (IRRef1)lj_ir_kint64(J, (uint64_t)-(int64_t)k); return RETRYFOLD; } static TRef simplify_intmul_k(jit_State *J, int32_t k) { /* Note: many more simplifications are possible, e.g. 2^k1 +- 2^k2. ** But this is mainly intended for simple address arithmetic. ** Also it's easier for the backend to optimize the original multiplies. */ if (k == 0) { /* i * 0 ==> 0 */ return RIGHTFOLD; } else if (k == 1) { /* i * 1 ==> i */ return LEFTFOLD; } else if ((k & (k-1)) == 0) { /* i * 2^k ==> i << k */ fins->o = IR_BSHL; fins->op2 = lj_ir_kint(J, lj_fls((uint32_t)k)); return RETRYFOLD; } return NEXTFOLD; } LJFOLD(MUL any KINT) LJFOLDF(simplify_intmul_k32) { if (fright->i >= 0) return simplify_intmul_k(J, fright->i); return NEXTFOLD; } LJFOLD(MUL any KINT64) LJFOLDF(simplify_intmul_k64) { #if LJ_HASFFI if (ir_kint64(fright)->u64 < 0x80000000u) return simplify_intmul_k(J, (int32_t)ir_kint64(fright)->u64); return NEXTFOLD; #else UNUSED(J); lj_assertJ(0, "FFI IR op without FFI"); return FAILFOLD; #endif } LJFOLD(MOD any KINT) LJFOLDF(simplify_intmod_k) { int32_t k = fright->i; lj_assertJ(k != 0, "integer mod 0"); if (k > 0 && (k & (k-1)) == 0) { /* i % (2^k) ==> i & (2^k-1) */ fins->o = IR_BAND; fins->op2 = lj_ir_kint(J, k-1); return RETRYFOLD; } return NEXTFOLD; } LJFOLD(MOD KINT any) LJFOLDF(simplify_intmod_kleft) { if (fleft->i == 0) return INTFOLD(0); return NEXTFOLD; } LJFOLD(SUB any any) LJFOLD(SUBOV any any) LJFOLDF(simplify_intsub) { if (fins->op1 == fins->op2 && !irt_isnum(fins->t)) /* i - i ==> 0 */ return irt_is64(fins->t) ? INT64FOLD(0) : INTFOLD(0); return NEXTFOLD; } LJFOLD(SUB ADD any) LJFOLDF(simplify_intsubadd_leftcancel) { if (!irt_isnum(fins->t)) { PHIBARRIER(fleft); if (fins->op2 == fleft->op1) /* (i + j) - i ==> j */ return fleft->op2; if (fins->op2 == fleft->op2) /* (i + j) - j ==> i */ return fleft->op1; } return NEXTFOLD; } LJFOLD(SUB SUB any) LJFOLDF(simplify_intsubsub_leftcancel) { if (!irt_isnum(fins->t)) { PHIBARRIER(fleft); if (fins->op2 == fleft->op1) { /* (i - j) - i ==> 0 - j */ fins->op1 = (IRRef1)lj_ir_kint(J, 0); fins->op2 = fleft->op2; return RETRYFOLD; } } return NEXTFOLD; } LJFOLD(SUB any SUB) LJFOLDF(simplify_intsubsub_rightcancel) { if (!irt_isnum(fins->t)) { PHIBARRIER(fright); if (fins->op1 == fright->op1) /* i - (i - j) ==> j */ return fright->op2; } return NEXTFOLD; } LJFOLD(SUB any ADD) LJFOLDF(simplify_intsubadd_rightcancel) { if (!irt_isnum(fins->t)) { PHIBARRIER(fright); if (fins->op1 == fright->op1) { /* i - (i + j) ==> 0 - j */ fins->op2 = fright->op2; fins->op1 = (IRRef1)lj_ir_kint(J, 0); return RETRYFOLD; } if (fins->op1 == fright->op2) { /* i - (j + i) ==> 0 - j */ fins->op2 = fright->op1; fins->op1 = (IRRef1)lj_ir_kint(J, 0); return RETRYFOLD; } } return NEXTFOLD; } LJFOLD(SUB ADD ADD) LJFOLDF(simplify_intsubaddadd_cancel) { if (!irt_isnum(fins->t)) { PHIBARRIER(fleft); PHIBARRIER(fright); if (fleft->op1 == fright->op1) { /* (i + j1) - (i + j2) ==> j1 - j2 */ fins->op1 = fleft->op2; fins->op2 = fright->op2; return RETRYFOLD; } if (fleft->op1 == fright->op2) { /* (i + j1) - (j2 + i) ==> j1 - j2 */ fins->op1 = fleft->op2; fins->op2 = fright->op1; return RETRYFOLD; } if (fleft->op2 == fright->op1) { /* (j1 + i) - (i + j2) ==> j1 - j2 */ fins->op1 = fleft->op1; fins->op2 = fright->op2; return RETRYFOLD; } if (fleft->op2 == fright->op2) { /* (j1 + i) - (j2 + i) ==> j1 - j2 */ fins->op1 = fleft->op1; fins->op2 = fright->op1; return RETRYFOLD; } } return NEXTFOLD; } LJFOLD(BAND any KINT) LJFOLD(BAND any KINT64) LJFOLDF(simplify_band_k) { int64_t k = fright->o == IR_KINT ? (int64_t)fright->i : (int64_t)ir_k64(fright)->u64; if (k == 0) /* i & 0 ==> 0 */ return RIGHTFOLD; if (k == -1) /* i & -1 ==> i */ return LEFTFOLD; return NEXTFOLD; } LJFOLD(BOR any KINT) LJFOLD(BOR any KINT64) LJFOLDF(simplify_bor_k) { int64_t k = fright->o == IR_KINT ? (int64_t)fright->i : (int64_t)ir_k64(fright)->u64; if (k == 0) /* i | 0 ==> i */ return LEFTFOLD; if (k == -1) /* i | -1 ==> -1 */ return RIGHTFOLD; return NEXTFOLD; } LJFOLD(BXOR any KINT) LJFOLD(BXOR any KINT64) LJFOLDF(simplify_bxor_k) { int64_t k = fright->o == IR_KINT ? (int64_t)fright->i : (int64_t)ir_k64(fright)->u64; if (k == 0) /* i xor 0 ==> i */ return LEFTFOLD; if (k == -1) { /* i xor -1 ==> ~i */ fins->o = IR_BNOT; fins->op2 = 0; return RETRYFOLD; } return NEXTFOLD; } LJFOLD(BSHL any KINT) LJFOLD(BSHR any KINT) LJFOLD(BSAR any KINT) LJFOLD(BROL any KINT) LJFOLD(BROR any KINT) LJFOLDF(simplify_shift_ik) { int32_t mask = irt_is64(fins->t) ? 63 : 31; int32_t k = (fright->i & mask); if (k == 0) /* i o 0 ==> i */ return LEFTFOLD; if (k == 1 && fins->o == IR_BSHL) { /* i << 1 ==> i + i */ fins->o = IR_ADD; fins->op2 = fins->op1; return RETRYFOLD; } if (k != fright->i) { /* i o k ==> i o (k & mask) */ fins->op2 = (IRRef1)lj_ir_kint(J, k); return RETRYFOLD; } #ifndef LJ_TARGET_UNIFYROT if (fins->o == IR_BROR) { /* bror(i, k) ==> brol(i, (-k)&mask) */ fins->o = IR_BROL; fins->op2 = (IRRef1)lj_ir_kint(J, (-k)&mask); return RETRYFOLD; } #endif return NEXTFOLD; } LJFOLD(BSHL any BAND) LJFOLD(BSHR any BAND) LJFOLD(BSAR any BAND) LJFOLD(BROL any BAND) LJFOLD(BROR any BAND) LJFOLDF(simplify_shift_andk) { IRIns *irk = IR(fright->op2); PHIBARRIER(fright); if ((fins->o < IR_BROL ? LJ_TARGET_MASKSHIFT : LJ_TARGET_MASKROT) && irk->o == IR_KINT) { /* i o (j & mask) ==> i o j */ int32_t mask = irt_is64(fins->t) ? 63 : 31; int32_t k = irk->i & mask; if (k == mask) { fins->op2 = fright->op1; return RETRYFOLD; } } return NEXTFOLD; } LJFOLD(BSHL KINT any) LJFOLD(BSHR KINT any) LJFOLD(BSHL KINT64 any) LJFOLD(BSHR KINT64 any) LJFOLDF(simplify_shift1_ki) { int64_t k = fleft->o == IR_KINT ? (int64_t)fleft->i : (int64_t)ir_k64(fleft)->u64; if (k == 0) /* 0 o i ==> 0 */ return LEFTFOLD; return NEXTFOLD; } LJFOLD(BSAR KINT any) LJFOLD(BROL KINT any) LJFOLD(BROR KINT any) LJFOLD(BSAR KINT64 any) LJFOLD(BROL KINT64 any) LJFOLD(BROR KINT64 any) LJFOLDF(simplify_shift2_ki) { int64_t k = fleft->o == IR_KINT ? (int64_t)fleft->i : (int64_t)ir_k64(fleft)->u64; if (k == 0 || k == -1) /* 0 o i ==> 0; -1 o i ==> -1 */ return LEFTFOLD; return NEXTFOLD; } LJFOLD(BSHL BAND KINT) LJFOLD(BSHR BAND KINT) LJFOLD(BROL BAND KINT) LJFOLD(BROR BAND KINT) LJFOLDF(simplify_shiftk_andk) { IRIns *irk = IR(fleft->op2); PHIBARRIER(fleft); if (irk->o == IR_KINT) { /* (i & k1) o k2 ==> (i o k2) & (k1 o k2) */ int32_t k = kfold_intop(irk->i, fright->i, (IROp)fins->o); fins->op1 = fleft->op1; fins->op1 = (IRRef1)lj_opt_fold(J); fins->op2 = (IRRef1)lj_ir_kint(J, k); fins->ot = IRTI(IR_BAND); return RETRYFOLD; } else if (irk->o == IR_KINT64) { uint64_t k = kfold_int64arith(J, ir_k64(irk)->u64, fright->i, (IROp)fins->o); IROpT ot = fleft->ot; fins->op1 = fleft->op1; fins->op1 = (IRRef1)lj_opt_fold(J); fins->op2 = (IRRef1)lj_ir_kint64(J, k); fins->ot = ot; return RETRYFOLD; } return NEXTFOLD; } LJFOLD(BAND BSHL KINT) LJFOLD(BAND BSHR KINT) LJFOLDF(simplify_andk_shiftk) { IRIns *irk = IR(fleft->op2); if (irk->o == IR_KINT && kfold_intop(-1, irk->i, (IROp)fleft->o) == fright->i) return LEFTFOLD; /* (i o k1) & k2 ==> i, if (-1 o k1) == k2 */ return NEXTFOLD; } LJFOLD(BAND BOR KINT) LJFOLD(BOR BAND KINT) LJFOLDF(simplify_andor_k) { IRIns *irk = IR(fleft->op2); PHIBARRIER(fleft); if (irk->o == IR_KINT) { int32_t k = kfold_intop(irk->i, fright->i, (IROp)fins->o); /* (i | k1) & k2 ==> i & k2, if (k1 & k2) == 0. */ /* (i & k1) | k2 ==> i | k2, if (k1 | k2) == -1. */ if (k == (fins->o == IR_BAND ? 0 : -1)) { fins->op1 = fleft->op1; return RETRYFOLD; } } return NEXTFOLD; } LJFOLD(BAND BOR KINT64) LJFOLD(BOR BAND KINT64) LJFOLDF(simplify_andor_k64) { #if LJ_HASFFI IRIns *irk = IR(fleft->op2); PHIBARRIER(fleft); if (irk->o == IR_KINT64) { uint64_t k = kfold_int64arith(J, ir_k64(irk)->u64, ir_k64(fright)->u64, (IROp)fins->o); /* (i | k1) & k2 ==> i & k2, if (k1 & k2) == 0. */ /* (i & k1) | k2 ==> i | k2, if (k1 | k2) == -1. */ if (k == (fins->o == IR_BAND ? (uint64_t)0 : ~(uint64_t)0)) { fins->op1 = fleft->op1; return RETRYFOLD; } } return NEXTFOLD; #else UNUSED(J); lj_assertJ(0, "FFI IR op without FFI"); return FAILFOLD; #endif } /* -- Reassociation ------------------------------------------------------- */ LJFOLD(ADD ADD KINT) LJFOLD(MUL MUL KINT) LJFOLD(BAND BAND KINT) LJFOLD(BOR BOR KINT) LJFOLD(BXOR BXOR KINT) LJFOLDF(reassoc_intarith_k) { IRIns *irk = IR(fleft->op2); if (irk->o == IR_KINT) { int32_t k = kfold_intop(irk->i, fright->i, (IROp)fins->o); if (k == irk->i) /* (i o k1) o k2 ==> i o k1, if (k1 o k2) == k1. */ return LEFTFOLD; PHIBARRIER(fleft); fins->op1 = fleft->op1; fins->op2 = (IRRef1)lj_ir_kint(J, k); return RETRYFOLD; /* (i o k1) o k2 ==> i o (k1 o k2) */ } return NEXTFOLD; } LJFOLD(ADD ADD KINT64) LJFOLD(MUL MUL KINT64) LJFOLD(BAND BAND KINT64) LJFOLD(BOR BOR KINT64) LJFOLD(BXOR BXOR KINT64) LJFOLDF(reassoc_intarith_k64) { #if LJ_HASFFI IRIns *irk = IR(fleft->op2); if (irk->o == IR_KINT64) { uint64_t k = kfold_int64arith(J, ir_k64(irk)->u64, ir_k64(fright)->u64, (IROp)fins->o); PHIBARRIER(fleft); fins->op1 = fleft->op1; fins->op2 = (IRRef1)lj_ir_kint64(J, k); return RETRYFOLD; /* (i o k1) o k2 ==> i o (k1 o k2) */ } return NEXTFOLD; #else UNUSED(J); lj_assertJ(0, "FFI IR op without FFI"); return FAILFOLD; #endif } LJFOLD(BAND BAND any) LJFOLD(BOR BOR any) LJFOLDF(reassoc_dup) { if (fins->op2 == fleft->op1 || fins->op2 == fleft->op2) return LEFTFOLD; /* (a o b) o a ==> a o b; (a o b) o b ==> a o b */ return NEXTFOLD; } LJFOLD(MIN MIN any) LJFOLD(MAX MAX any) LJFOLDF(reassoc_dup_minmax) { if (fins->op2 == fleft->op2) return LEFTFOLD; /* (a o b) o b ==> a o b */ return NEXTFOLD; } LJFOLD(BXOR BXOR any) LJFOLDF(reassoc_bxor) { PHIBARRIER(fleft); if (fins->op2 == fleft->op1) /* (a xor b) xor a ==> b */ return fleft->op2; if (fins->op2 == fleft->op2) /* (a xor b) xor b ==> a */ return fleft->op1; return NEXTFOLD; } LJFOLD(BSHL BSHL KINT) LJFOLD(BSHR BSHR KINT) LJFOLD(BSAR BSAR KINT) LJFOLD(BROL BROL KINT) LJFOLD(BROR BROR KINT) LJFOLDF(reassoc_shift) { IRIns *irk = IR(fleft->op2); PHIBARRIER(fleft); /* The (shift any KINT) rule covers k2 == 0 and more. */ if (irk->o == IR_KINT) { /* (i o k1) o k2 ==> i o (k1 + k2) */ int32_t mask = irt_is64(fins->t) ? 63 : 31; int32_t k = (irk->i & mask) + (fright->i & mask); if (k > mask) { /* Combined shift too wide? */ if (fins->o == IR_BSHL || fins->o == IR_BSHR) return mask == 31 ? INTFOLD(0) : INT64FOLD(0); else if (fins->o == IR_BSAR) k = mask; else k &= mask; } fins->op1 = fleft->op1; fins->op2 = (IRRef1)lj_ir_kint(J, k); return RETRYFOLD; } return NEXTFOLD; } LJFOLD(MIN MIN KINT) LJFOLD(MAX MAX KINT) LJFOLDF(reassoc_minmax_k) { IRIns *irk = IR(fleft->op2); if (irk->o == IR_KINT) { int32_t a = irk->i; int32_t y = kfold_intop(a, fright->i, fins->o); if (a == y) /* (x o k1) o k2 ==> x o k1, if (k1 o k2) == k1. */ return LEFTFOLD; PHIBARRIER(fleft); fins->op1 = fleft->op1; fins->op2 = (IRRef1)lj_ir_kint(J, y); return RETRYFOLD; /* (x o k1) o k2 ==> x o (k1 o k2) */ } return NEXTFOLD; } /* -- Array bounds check elimination -------------------------------------- */ /* Eliminate ABC across PHIs to handle t[i-1] forwarding case. ** ABC(asize, (i+k)+(-k)) ==> ABC(asize, i), but only if it already exists. ** Could be generalized to (i+k1)+k2 ==> i+(k1+k2), but needs better disambig. */ LJFOLD(ABC any ADD) LJFOLDF(abc_fwd) { if (LJ_LIKELY(J->flags & JIT_F_OPT_ABC)) { if (irref_isk(fright->op2)) { IRIns *add2 = IR(fright->op1); if (add2->o == IR_ADD && irref_isk(add2->op2) && IR(fright->op2)->i == -IR(add2->op2)->i) { IRRef ref = J->chain[IR_ABC]; IRRef lim = add2->op1; if (fins->op1 > lim) lim = fins->op1; while (ref > lim) { IRIns *ir = IR(ref); if (ir->op1 == fins->op1 && ir->op2 == add2->op1) return DROPFOLD; ref = ir->prev; } } } } return NEXTFOLD; } /* Eliminate ABC for constants. ** ABC(asize, k1), ABC(asize k2) ==> ABC(asize, max(k1, k2)) ** Drop second ABC if k2 is lower. Otherwise patch first ABC with k2. */ LJFOLD(ABC any KINT) LJFOLDF(abc_k) { if (LJ_LIKELY(J->flags & JIT_F_OPT_ABC)) { IRRef ref = J->chain[IR_ABC]; IRRef asize = fins->op1; while (ref > asize) { IRIns *ir = IR(ref); if (ir->op1 == asize && irref_isk(ir->op2)) { int32_t k = IR(ir->op2)->i; if (fright->i > k) ir->op2 = fins->op2; return DROPFOLD; } ref = ir->prev; } return EMITFOLD; /* Already performed CSE. */ } return NEXTFOLD; } /* Eliminate invariant ABC inside loop. */ LJFOLD(ABC any any) LJFOLDF(abc_invar) { /* Invariant ABC marked as PTR. Drop if op1 is invariant, too. */ if (!irt_isint(fins->t) && fins->op1 < J->chain[IR_LOOP] && !irt_isphi(IR(fins->op1)->t)) return DROPFOLD; return NEXTFOLD; } /* -- Commutativity ------------------------------------------------------- */ /* The refs of commutative ops are canonicalized. Lower refs go to the right. ** Rationale behind this: ** - It (also) moves constants to the right. ** - It reduces the number of FOLD rules (e.g. (BOR any KINT) suffices). ** - It helps CSE to find more matches. ** - The assembler generates better code with constants at the right. */ LJFOLD(ADD any any) LJFOLD(MUL any any) LJFOLD(ADDOV any any) LJFOLD(MULOV any any) LJFOLDF(comm_swap) { if (fins->op1 < fins->op2) { /* Move lower ref to the right. */ IRRef1 tmp = fins->op1; fins->op1 = fins->op2; fins->op2 = tmp; return RETRYFOLD; } return NEXTFOLD; } LJFOLD(EQ any any) LJFOLD(NE any any) LJFOLDF(comm_equal) { /* For non-numbers only: x == x ==> drop; x ~= x ==> fail */ if (fins->op1 == fins->op2 && !irt_isnum(fins->t)) return CONDFOLD(fins->o == IR_EQ); return fold_comm_swap(J); } LJFOLD(LT any any) LJFOLD(GE any any) LJFOLD(LE any any) LJFOLD(GT any any) LJFOLD(ULT any any) LJFOLD(UGE any any) LJFOLD(ULE any any) LJFOLD(UGT any any) LJFOLDF(comm_comp) { /* For non-numbers only: x <=> x ==> drop; x <> x ==> fail */ if (fins->op1 == fins->op2 && !irt_isnum(fins->t)) return CONDFOLD((fins->o ^ (fins->o >> 1)) & 1); if (fins->op1 < fins->op2) { /* Move lower ref to the right. */ IRRef1 tmp = fins->op1; fins->op1 = fins->op2; fins->op2 = tmp; fins->o ^= 3; /* GT <-> LT, GE <-> LE, does not affect U */ return RETRYFOLD; } return NEXTFOLD; } LJFOLD(BAND any any) LJFOLD(BOR any any) LJFOLDF(comm_dup) { if (fins->op1 == fins->op2) /* x o x ==> x */ return LEFTFOLD; return fold_comm_swap(J); } LJFOLD(MIN any any) LJFOLD(MAX any any) LJFOLDF(comm_dup_minmax) { if (fins->op1 == fins->op2) /* x o x ==> x */ return LEFTFOLD; return NEXTFOLD; } LJFOLD(BXOR any any) LJFOLDF(comm_bxor) { if (fins->op1 == fins->op2) /* i xor i ==> 0 */ return irt_is64(fins->t) ? INT64FOLD(0) : INTFOLD(0); return fold_comm_swap(J); } /* -- Simplification of compound expressions ------------------------------ */ static TRef kfold_xload(jit_State *J, IRIns *ir, const void *p) { int32_t k; switch (irt_type(ir->t)) { case IRT_NUM: return lj_ir_knum_u64(J, *(uint64_t *)p); case IRT_I8: k = (int32_t)*(int8_t *)p; break; case IRT_U8: k = (int32_t)*(uint8_t *)p; break; case IRT_I16: k = (int32_t)(int16_t)lj_getu16(p); break; case IRT_U16: k = (int32_t)(uint16_t)lj_getu16(p); break; case IRT_INT: case IRT_U32: k = (int32_t)lj_getu32(p); break; case IRT_I64: case IRT_U64: return lj_ir_kint64(J, *(uint64_t *)p); default: return 0; } return lj_ir_kint(J, k); } /* Turn: string.sub(str, a, b) == kstr ** into: string.byte(str, a) == string.byte(kstr, 1) etc. ** Note: this creates unaligned XLOADs on x86/x64. */ LJFOLD(EQ SNEW KGC) LJFOLD(NE SNEW KGC) LJFOLDF(merge_eqne_snew_kgc) { GCstr *kstr = ir_kstr(fright); int32_t len = (int32_t)kstr->len; lj_assertJ(irt_isstr(fins->t), "bad equality IR type"); #if LJ_TARGET_UNALIGNED #define FOLD_SNEW_MAX_LEN 4 /* Handle string lengths 0, 1, 2, 3, 4. */ #define FOLD_SNEW_TYPE8 IRT_I8 /* Creates shorter immediates. */ #else #define FOLD_SNEW_MAX_LEN 1 /* Handle string lengths 0 or 1. */ #define FOLD_SNEW_TYPE8 IRT_U8 /* Prefer unsigned loads. */ #endif PHIBARRIER(fleft); if (len <= FOLD_SNEW_MAX_LEN) { IROp op = (IROp)fins->o; IRRef strref = fleft->op1; if (IR(strref)->o != IR_STRREF) return NEXTFOLD; if (op == IR_EQ) { emitir(IRTGI(IR_EQ), fleft->op2, lj_ir_kint(J, len)); /* Caveat: fins/fleft/fright is no longer valid after emitir. */ } else { /* NE is not expanded since this would need an OR of two conds. */ if (!irref_isk(fleft->op2)) /* Only handle the constant length case. */ return NEXTFOLD; if (IR(fleft->op2)->i != len) return DROPFOLD; } if (len > 0) { /* A 4 byte load for length 3 is ok -- all strings have an extra NUL. */ uint16_t ot = (uint16_t)(len == 1 ? IRT(IR_XLOAD, FOLD_SNEW_TYPE8) : len == 2 ? IRT(IR_XLOAD, IRT_U16) : IRTI(IR_XLOAD)); TRef tmp = emitir(ot, strref, IRXLOAD_READONLY | (len > 1 ? IRXLOAD_UNALIGNED : 0)); TRef val = kfold_xload(J, IR(tref_ref(tmp)), strdata(kstr)); if (len == 3) tmp = emitir(IRTI(IR_BAND), tmp, lj_ir_kint(J, LJ_ENDIAN_SELECT(0x00ffffff, 0xffffff00))); fins->op1 = (IRRef1)tmp; fins->op2 = (IRRef1)val; fins->ot = (IROpT)IRTGI(op); return RETRYFOLD; } else { return DROPFOLD; } } return NEXTFOLD; } /* -- Loads --------------------------------------------------------------- */ /* Loads cannot be folded or passed on to CSE in general. ** Alias analysis is needed to check for forwarding opportunities. ** ** Caveat: *all* loads must be listed here or they end up at CSE! */ LJFOLD(ALOAD any) LJFOLDX(lj_opt_fwd_aload) /* From HREF fwd (see below). Must eliminate, not supported by fwd/backend. */ LJFOLD(HLOAD KKPTR) LJFOLDF(kfold_hload_kkptr) { UNUSED(J); lj_assertJ(ir_kptr(fleft) == niltvg(J2G(J)), "expected niltv"); return TREF_NIL; } LJFOLD(HLOAD any) LJFOLDX(lj_opt_fwd_hload) LJFOLD(ULOAD any) LJFOLDX(lj_opt_fwd_uload) LJFOLD(ALEN any any) LJFOLDX(lj_opt_fwd_alen) /* Upvalue refs are really loads, but there are no corresponding stores. ** So CSE is ok for them, except for UREFO across a GC step (see below). ** If the referenced function is const, its upvalue addresses are const, too. ** This can be used to improve CSE by looking for the same address, ** even if the upvalues originate from a different function. */ LJFOLD(UREFO KGC any) LJFOLD(UREFC KGC any) LJFOLDF(cse_uref) { if (LJ_LIKELY(J->flags & JIT_F_OPT_CSE)) { IRRef ref = J->chain[fins->o]; GCfunc *fn = ir_kfunc(fleft); GCupval *uv = gco2uv(gcref(fn->l.uvptr[(fins->op2 >> 8)])); while (ref > 0) { IRIns *ir = IR(ref); if (irref_isk(ir->op1)) { GCfunc *fn2 = ir_kfunc(IR(ir->op1)); if (gco2uv(gcref(fn2->l.uvptr[(ir->op2 >> 8)])) == uv) { if (fins->o == IR_UREFO && gcstep_barrier(J, ref)) break; return ref; } } ref = ir->prev; } } return EMITFOLD; } LJFOLD(HREFK any any) LJFOLDX(lj_opt_fwd_hrefk) LJFOLD(HREF TNEW any) LJFOLDF(fwd_href_tnew) { if (lj_opt_fwd_href_nokey(J)) return lj_ir_kkptr(J, niltvg(J2G(J))); return NEXTFOLD; } LJFOLD(HREF TDUP KPRI) LJFOLD(HREF TDUP KGC) LJFOLD(HREF TDUP KNUM) LJFOLDF(fwd_href_tdup) { TValue keyv; lj_ir_kvalue(J->L, &keyv, fright); if (lj_tab_get(J->L, ir_ktab(IR(fleft->op1)), &keyv) == niltvg(J2G(J)) && lj_opt_fwd_href_nokey(J)) return lj_ir_kkptr(J, niltvg(J2G(J))); return NEXTFOLD; } /* We can safely FOLD/CSE array/hash refs and field loads, since there ** are no corresponding stores. But we need to check for any NEWREF with ** an aliased table, as it may invalidate all of the pointers and fields. ** Only HREF needs the NEWREF check -- AREF and HREFK already depend on ** FLOADs. And NEWREF itself is treated like a store (see below). ** LREF is constant (per trace) since coroutine switches are not inlined. */ LJFOLD(FLOAD TNEW IRFL_TAB_ASIZE) LJFOLDF(fload_tab_tnew_asize) { if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD) && lj_opt_fwd_tptr(J, fins->op1)) return INTFOLD(fleft->op1); return NEXTFOLD; } LJFOLD(FLOAD TNEW IRFL_TAB_HMASK) LJFOLDF(fload_tab_tnew_hmask) { if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD) && lj_opt_fwd_tptr(J, fins->op1)) return INTFOLD((1 << fleft->op2)-1); return NEXTFOLD; } LJFOLD(FLOAD TDUP IRFL_TAB_ASIZE) LJFOLDF(fload_tab_tdup_asize) { if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD) && lj_opt_fwd_tptr(J, fins->op1)) return INTFOLD((int32_t)ir_ktab(IR(fleft->op1))->asize); return NEXTFOLD; } LJFOLD(FLOAD TDUP IRFL_TAB_HMASK) LJFOLDF(fload_tab_tdup_hmask) { if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD) && lj_opt_fwd_tptr(J, fins->op1)) return INTFOLD((int32_t)ir_ktab(IR(fleft->op1))->hmask); return NEXTFOLD; } LJFOLD(HREF any any) LJFOLD(FLOAD any IRFL_TAB_ARRAY) LJFOLD(FLOAD any IRFL_TAB_NODE) LJFOLD(FLOAD any IRFL_TAB_ASIZE) LJFOLD(FLOAD any IRFL_TAB_HMASK) LJFOLDF(fload_tab_ah) { TRef tr = lj_opt_cse(J); return lj_opt_fwd_tptr(J, tref_ref(tr)) ? tr : EMITFOLD; } /* Strings are immutable, so we can safely FOLD/CSE the related FLOAD. */ LJFOLD(FLOAD KGC IRFL_STR_LEN) LJFOLDF(fload_str_len_kgc) { if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD)) return INTFOLD((int32_t)ir_kstr(fleft)->len); return NEXTFOLD; } LJFOLD(FLOAD SNEW IRFL_STR_LEN) LJFOLDF(fload_str_len_snew) { if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD)) { PHIBARRIER(fleft); return fleft->op2; } return NEXTFOLD; } LJFOLD(FLOAD TOSTR IRFL_STR_LEN) LJFOLDF(fload_str_len_tostr) { if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD) && fleft->op2 == IRTOSTR_CHAR) return INTFOLD(1); return NEXTFOLD; } LJFOLD(FLOAD any IRFL_SBUF_W) LJFOLD(FLOAD any IRFL_SBUF_E) LJFOLD(FLOAD any IRFL_SBUF_B) LJFOLD(FLOAD any IRFL_SBUF_L) LJFOLD(FLOAD any IRFL_SBUF_REF) LJFOLD(FLOAD any IRFL_SBUF_R) LJFOLDF(fload_sbuf) { TRef tr = lj_opt_fwd_fload(J); return lj_opt_fwd_sbuf(J, tref_ref(tr)) ? tr : EMITFOLD; } /* The fast function ID of function objects is immutable. */ LJFOLD(FLOAD KGC IRFL_FUNC_FFID) LJFOLDF(fload_func_ffid_kgc) { if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD)) return INTFOLD((int32_t)ir_kfunc(fleft)->c.ffid); return NEXTFOLD; } /* The C type ID of cdata objects is immutable. */ LJFOLD(FLOAD KGC IRFL_CDATA_CTYPEID) LJFOLDF(fload_cdata_typeid_kgc) { if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD)) return INTFOLD((int32_t)ir_kcdata(fleft)->ctypeid); return NEXTFOLD; } /* Get the contents of immutable cdata objects. */ LJFOLD(FLOAD KGC IRFL_CDATA_PTR) LJFOLD(FLOAD KGC IRFL_CDATA_INT) LJFOLD(FLOAD KGC IRFL_CDATA_INT64) LJFOLDF(fload_cdata_int64_kgc) { if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD)) { void *p = cdataptr(ir_kcdata(fleft)); if (irt_is64(fins->t)) return INT64FOLD(*(uint64_t *)p); else return INTFOLD(*(int32_t *)p); } return NEXTFOLD; } LJFOLD(FLOAD CNEW IRFL_CDATA_CTYPEID) LJFOLD(FLOAD CNEWI IRFL_CDATA_CTYPEID) LJFOLDF(fload_cdata_typeid_cnew) { if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD)) return fleft->op1; /* No PHI barrier needed. CNEW/CNEWI op1 is const. */ return NEXTFOLD; } /* Pointer, int and int64 cdata objects are immutable. */ LJFOLD(FLOAD CNEWI IRFL_CDATA_PTR) LJFOLD(FLOAD CNEWI IRFL_CDATA_INT) LJFOLD(FLOAD CNEWI IRFL_CDATA_INT64) LJFOLDF(fload_cdata_ptr_int64_cnew) { if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD)) return fleft->op2; /* Fold even across PHI to avoid allocations. */ return NEXTFOLD; } LJFOLD(FLOAD any IRFL_STR_LEN) LJFOLD(FLOAD any IRFL_FUNC_ENV) LJFOLD(FLOAD any IRFL_THREAD_ENV) LJFOLD(FLOAD any IRFL_CDATA_CTYPEID) LJFOLD(FLOAD any IRFL_CDATA_PTR) LJFOLD(FLOAD any IRFL_CDATA_INT) LJFOLD(FLOAD any IRFL_CDATA_INT64) LJFOLD(VLOAD any any) /* Vararg loads have no corresponding stores. */ LJFOLDX(lj_opt_cse) /* All other field loads need alias analysis. */ LJFOLD(FLOAD any any) LJFOLDX(lj_opt_fwd_fload) /* This is for LOOP only. Recording handles SLOADs internally. */ LJFOLD(SLOAD any any) LJFOLDF(fwd_sload) { if ((fins->op2 & IRSLOAD_FRAME)) { TRef tr = lj_opt_cse(J); return tref_ref(tr) < J->chain[IR_RETF] ? EMITFOLD : tr; } else { lj_assertJ(J->slot[fins->op1] != 0, "uninitialized slot accessed"); return J->slot[fins->op1]; } } /* Only fold for KKPTR. The pointer _and_ the contents must be const. */ LJFOLD(XLOAD KKPTR any) LJFOLDF(xload_kptr) { TRef tr = kfold_xload(J, fins, ir_kptr(fleft)); return tr ? tr : NEXTFOLD; } LJFOLD(XLOAD any any) LJFOLDX(lj_opt_fwd_xload) /* -- Frame handling ------------------------------------------------------ */ /* Prevent CSE of a REF_BASE operand across IR_RETF. */ LJFOLD(SUB any BASE) LJFOLD(SUB BASE any) LJFOLD(EQ any BASE) LJFOLDF(fold_base) { return lj_opt_cselim(J, J->chain[IR_RETF]); } /* -- Write barriers ------------------------------------------------------ */ /* Write barriers are amenable to CSE, but not across any incremental ** GC steps. ** ** The same logic applies to open upvalue references, because a stack ** may be resized during a GC step (not the current stack, but maybe that ** of a coroutine). */ LJFOLD(TBAR any) LJFOLD(OBAR any any) LJFOLD(UREFO any any) LJFOLDF(barrier_tab) { TRef tr = lj_opt_cse(J); if (gcstep_barrier(J, tref_ref(tr))) /* CSE across GC step? */ return EMITFOLD; /* Raw emit. Assumes fins is left intact by CSE. */ return tr; } LJFOLD(TBAR TNEW) LJFOLD(TBAR TDUP) LJFOLDF(barrier_tnew_tdup) { /* New tables are always white and never need a barrier. */ if (fins->op1 < J->chain[IR_LOOP]) /* Except across a GC step. */ return NEXTFOLD; return DROPFOLD; } /* -- Profiling ----------------------------------------------------------- */ LJFOLD(PROF any any) LJFOLDF(prof) { IRRef ref = J->chain[IR_PROF]; if (ref+1 == J->cur.nins) /* Drop neighbouring IR_PROF. */ return ref; return EMITFOLD; } /* -- Stores and allocations ---------------------------------------------- */ /* Stores and allocations cannot be folded or passed on to CSE in general. ** But some stores can be eliminated with dead-store elimination (DSE). ** ** Caveat: *all* stores and allocs must be listed here or they end up at CSE! */ LJFOLD(ASTORE any any) LJFOLD(HSTORE any any) LJFOLDX(lj_opt_dse_ahstore) LJFOLD(USTORE any any) LJFOLDX(lj_opt_dse_ustore) LJFOLD(FSTORE any any) LJFOLDX(lj_opt_dse_fstore) LJFOLD(XSTORE any any) LJFOLDX(lj_opt_dse_xstore) LJFOLD(NEWREF any any) /* Treated like a store. */ LJFOLD(TMPREF any any) LJFOLD(CALLA any any) LJFOLD(CALLL any any) /* Safeguard fallback. */ LJFOLD(CALLS any any) LJFOLD(CALLXS any any) LJFOLD(XBAR) LJFOLD(RETF any any) /* Modifies BASE. */ LJFOLD(TNEW any any) LJFOLD(TDUP any) LJFOLD(CNEW any any) LJFOLD(XSNEW any any) LJFOLDX(lj_ir_emit) /* ------------------------------------------------------------------------ */ /* Every entry in the generated hash table is a 32 bit pattern: ** ** xxxxxxxx iiiiiii lllllll rrrrrrrrrr ** ** xxxxxxxx = 8 bit index into fold function table ** iiiiiii = 7 bit folded instruction opcode ** lllllll = 7 bit left instruction opcode ** rrrrrrrrrr = 8 bit right instruction opcode or 10 bits from literal field */ #include "lj_folddef.h" /* ------------------------------------------------------------------------ */ /* Fold IR instruction. */ TRef LJ_FASTCALL lj_opt_fold(jit_State *J) { uint32_t key, any; IRRef ref; if (LJ_UNLIKELY((J->flags & JIT_F_OPT_MASK) != JIT_F_OPT_DEFAULT)) { lj_assertJ(((JIT_F_OPT_FOLD|JIT_F_OPT_FWD|JIT_F_OPT_CSE|JIT_F_OPT_DSE) | JIT_F_OPT_DEFAULT) == JIT_F_OPT_DEFAULT, "bad JIT_F_OPT_DEFAULT"); /* Folding disabled? Chain to CSE, but not for loads/stores/allocs. */ if (!(J->flags & JIT_F_OPT_FOLD) && irm_kind(lj_ir_mode[fins->o]) == IRM_N) return lj_opt_cse(J); /* No FOLD, forwarding or CSE? Emit raw IR for loads, except for SLOAD. */ if ((J->flags & (JIT_F_OPT_FOLD|JIT_F_OPT_FWD|JIT_F_OPT_CSE)) != (JIT_F_OPT_FOLD|JIT_F_OPT_FWD|JIT_F_OPT_CSE) && irm_kind(lj_ir_mode[fins->o]) == IRM_L && fins->o != IR_SLOAD) return lj_ir_emit(J); /* No FOLD or DSE? Emit raw IR for stores. */ if ((J->flags & (JIT_F_OPT_FOLD|JIT_F_OPT_DSE)) != (JIT_F_OPT_FOLD|JIT_F_OPT_DSE) && irm_kind(lj_ir_mode[fins->o]) == IRM_S) return lj_ir_emit(J); } /* Fold engine start/retry point. */ retry: /* Construct key from opcode and operand opcodes (unless literal/none). */ key = ((uint32_t)fins->o << 17); if (fins->op1 >= J->cur.nk) { key += (uint32_t)IR(fins->op1)->o << 10; *fleft = *IR(fins->op1); if (fins->op1 < REF_TRUE) fleft[1] = IR(fins->op1)[1]; } if (fins->op2 >= J->cur.nk) { key += (uint32_t)IR(fins->op2)->o; *fright = *IR(fins->op2); if (fins->op2 < REF_TRUE) fright[1] = IR(fins->op2)[1]; } else { key += (fins->op2 & 0x3ffu); /* Literal mask. Must include IRCONV_*MASK. */ } /* Check for a match in order from most specific to least specific. */ any = 0; for (;;) { uint32_t k = key | (any & 0x1ffff); uint32_t h = fold_hashkey(k); uint32_t fh = fold_hash[h]; /* Lookup key in semi-perfect hash table. */ if ((fh & 0xffffff) == k || (fh = fold_hash[h+1], (fh & 0xffffff) == k)) { ref = (IRRef)tref_ref(fold_func[fh >> 24](J)); if (ref != NEXTFOLD) break; } if (any == 0xfffff) /* Exhausted folding. Pass on to CSE. */ return lj_opt_cse(J); any = (any | (any >> 10)) ^ 0xffc00; } /* Return value processing, ordered by frequency. */ if (LJ_LIKELY(ref >= MAX_FOLD)) return TREF(ref, irt_t(IR(ref)->t)); if (ref == RETRYFOLD) goto retry; if (ref == KINTFOLD) return lj_ir_kint(J, fins->i); if (ref == FAILFOLD) lj_trace_err(J, LJ_TRERR_GFAIL); lj_assertJ(ref == DROPFOLD, "bad fold result"); return REF_DROP; } /* -- Common-Subexpression Elimination ------------------------------------ */ /* CSE an IR instruction. This is very fast due to the skip-list chains. */ TRef LJ_FASTCALL lj_opt_cse(jit_State *J) { /* Avoid narrow to wide store-to-load forwarding stall */ IRRef2 op12 = (IRRef2)fins->op1 + ((IRRef2)fins->op2 << 16); IROp op = fins->o; if (LJ_LIKELY(J->flags & JIT_F_OPT_CSE)) { /* Limited search for same operands in per-opcode chain. */ IRRef ref = J->chain[op]; IRRef lim = fins->op1; if (fins->op2 > lim) lim = fins->op2; /* Relies on lit < REF_BIAS. */ while (ref > lim) { if (IR(ref)->op12 == op12) return TREF(ref, irt_t(IR(ref)->t)); /* Common subexpression found. */ ref = IR(ref)->prev; } } /* Otherwise emit IR (inlined for speed). */ { IRRef ref = lj_ir_nextins(J); IRIns *ir = IR(ref); ir->prev = J->chain[op]; ir->op12 = op12; J->chain[op] = (IRRef1)ref; ir->o = fins->o; J->guardemit.irt |= fins->t.irt; return TREF(ref, irt_t((ir->t = fins->t))); } } /* CSE with explicit search limit. */ TRef LJ_FASTCALL lj_opt_cselim(jit_State *J, IRRef lim) { IRRef ref = J->chain[fins->o]; IRRef2 op12 = (IRRef2)fins->op1 + ((IRRef2)fins->op2 << 16); while (ref > lim) { if (IR(ref)->op12 == op12) return ref; ref = IR(ref)->prev; } return lj_ir_emit(J); } /* ------------------------------------------------------------------------ */ #undef IR #undef fins #undef fleft #undef fright #undef knumleft #undef knumright #undef emitir #endif
xLua/build/luajit-2.1.0b3/src/lj_opt_fold.c/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_opt_fold.c", "repo_id": "xLua", "token_count": 35060 }
2,122
/* ** Snapshot handling. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #define lj_snap_c #define LUA_CORE #include "lj_obj.h" #if LJ_HASJIT #include "lj_gc.h" #include "lj_tab.h" #include "lj_state.h" #include "lj_frame.h" #include "lj_bc.h" #include "lj_ir.h" #include "lj_jit.h" #include "lj_iropt.h" #include "lj_trace.h" #include "lj_snap.h" #include "lj_target.h" #if LJ_HASFFI #include "lj_ctype.h" #include "lj_cdata.h" #endif /* Pass IR on to next optimization in chain (FOLD). */ #define emitir(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_opt_fold(J)) /* Emit raw IR without passing through optimizations. */ #define emitir_raw(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_ir_emit(J)) /* -- Snapshot buffer allocation ------------------------------------------ */ /* Grow snapshot buffer. */ void lj_snap_grow_buf_(jit_State *J, MSize need) { MSize maxsnap = (MSize)J->param[JIT_P_maxsnap]; if (need > maxsnap) lj_trace_err(J, LJ_TRERR_SNAPOV); lj_mem_growvec(J->L, J->snapbuf, J->sizesnap, maxsnap, SnapShot); J->cur.snap = J->snapbuf; } /* Grow snapshot map buffer. */ void lj_snap_grow_map_(jit_State *J, MSize need) { if (need < 2*J->sizesnapmap) need = 2*J->sizesnapmap; else if (need < 64) need = 64; J->snapmapbuf = (SnapEntry *)lj_mem_realloc(J->L, J->snapmapbuf, J->sizesnapmap*sizeof(SnapEntry), need*sizeof(SnapEntry)); J->cur.snapmap = J->snapmapbuf; J->sizesnapmap = need; } /* -- Snapshot generation ------------------------------------------------- */ /* Add all modified slots to the snapshot. */ static MSize snapshot_slots(jit_State *J, SnapEntry *map, BCReg nslots) { IRRef retf = J->chain[IR_RETF]; /* Limits SLOAD restore elimination. */ BCReg s; MSize n = 0; for (s = 0; s < nslots; s++) { TRef tr = J->slot[s]; IRRef ref = tref_ref(tr); #if LJ_FR2 if (s == 1) { /* Ignore slot 1 in LJ_FR2 mode, except if tailcalled. */ if ((tr & TREF_FRAME)) map[n++] = SNAP(1, SNAP_FRAME | SNAP_NORESTORE, REF_NIL); continue; } if ((tr & (TREF_FRAME | TREF_CONT)) && !ref) { cTValue *base = J->L->base - J->baseslot; tr = J->slot[s] = (tr & 0xff0000) | lj_ir_k64(J, IR_KNUM, base[s].u64); ref = tref_ref(tr); } #endif if (ref) { SnapEntry sn = SNAP_TR(s, tr); IRIns *ir = &J->cur.ir[ref]; if ((LJ_FR2 || !(sn & (SNAP_CONT|SNAP_FRAME))) && ir->o == IR_SLOAD && ir->op1 == s && ref > retf) { /* ** No need to snapshot unmodified non-inherited slots. ** But always snapshot the function below a frame in LJ_FR2 mode. */ if (!(ir->op2 & IRSLOAD_INHERIT) && (!LJ_FR2 || s == 0 || s+1 == nslots || !(J->slot[s+1] & (TREF_CONT|TREF_FRAME)))) continue; /* No need to restore readonly slots and unmodified non-parent slots. */ if (!(LJ_DUALNUM && (ir->op2 & IRSLOAD_CONVERT)) && (ir->op2 & (IRSLOAD_READONLY|IRSLOAD_PARENT)) != IRSLOAD_PARENT) sn |= SNAP_NORESTORE; } if (LJ_SOFTFP32 && irt_isnum(ir->t)) sn |= SNAP_SOFTFPNUM; map[n++] = sn; } } return n; } /* Add frame links at the end of the snapshot. */ static MSize snapshot_framelinks(jit_State *J, SnapEntry *map, uint8_t *topslot) { cTValue *frame = J->L->base - 1; cTValue *lim = J->L->base - J->baseslot + LJ_FR2; GCfunc *fn = frame_func(frame); cTValue *ftop = isluafunc(fn) ? (frame+funcproto(fn)->framesize) : J->L->top; #if LJ_FR2 uint64_t pcbase = (u64ptr(J->pc) << 8) | (J->baseslot - 2); lj_assertJ(2 <= J->baseslot && J->baseslot <= 257, "bad baseslot"); memcpy(map, &pcbase, sizeof(uint64_t)); #else MSize f = 0; map[f++] = SNAP_MKPC(J->pc); /* The current PC is always the first entry. */ #endif lj_assertJ(!J->pt || (J->pc >= proto_bc(J->pt) && J->pc < proto_bc(J->pt) + J->pt->sizebc), "bad snapshot PC"); while (frame > lim) { /* Backwards traversal of all frames above base. */ if (frame_islua(frame)) { #if !LJ_FR2 map[f++] = SNAP_MKPC(frame_pc(frame)); #endif frame = frame_prevl(frame); } else if (frame_iscont(frame)) { #if !LJ_FR2 map[f++] = SNAP_MKFTSZ(frame_ftsz(frame)); map[f++] = SNAP_MKPC(frame_contpc(frame)); #endif frame = frame_prevd(frame); } else { lj_assertJ(!frame_isc(frame), "broken frame chain"); #if !LJ_FR2 map[f++] = SNAP_MKFTSZ(frame_ftsz(frame)); #endif frame = frame_prevd(frame); continue; } if (frame + funcproto(frame_func(frame))->framesize > ftop) ftop = frame + funcproto(frame_func(frame))->framesize; } *topslot = (uint8_t)(ftop - lim); #if LJ_FR2 lj_assertJ(sizeof(SnapEntry) * 2 == sizeof(uint64_t), "bad SnapEntry def"); return 2; #else lj_assertJ(f == (MSize)(1 + J->framedepth), "miscalculated snapshot size"); return f; #endif } /* Take a snapshot of the current stack. */ static void snapshot_stack(jit_State *J, SnapShot *snap, MSize nsnapmap) { BCReg nslots = J->baseslot + J->maxslot; MSize nent; SnapEntry *p; /* Conservative estimate. */ lj_snap_grow_map(J, nsnapmap + nslots + (MSize)(LJ_FR2?2:J->framedepth+1)); p = &J->cur.snapmap[nsnapmap]; nent = snapshot_slots(J, p, nslots); snap->nent = (uint8_t)nent; nent += snapshot_framelinks(J, p + nent, &snap->topslot); snap->mapofs = (uint32_t)nsnapmap; snap->ref = (IRRef1)J->cur.nins; snap->mcofs = 0; snap->nslots = (uint8_t)nslots; snap->count = 0; J->cur.nsnapmap = (uint32_t)(nsnapmap + nent); } /* Add or merge a snapshot. */ void lj_snap_add(jit_State *J) { MSize nsnap = J->cur.nsnap; MSize nsnapmap = J->cur.nsnapmap; /* Merge if no ins. inbetween or if requested and no guard inbetween. */ if ((nsnap > 0 && J->cur.snap[nsnap-1].ref == J->cur.nins) || (J->mergesnap && !irt_isguard(J->guardemit))) { if (nsnap == 1) { /* But preserve snap #0 PC. */ emitir_raw(IRT(IR_NOP, IRT_NIL), 0, 0); goto nomerge; } nsnapmap = J->cur.snap[--nsnap].mapofs; } else { nomerge: lj_snap_grow_buf(J, nsnap+1); J->cur.nsnap = (uint16_t)(nsnap+1); } J->mergesnap = 0; J->guardemit.irt = 0; snapshot_stack(J, &J->cur.snap[nsnap], nsnapmap); } /* -- Snapshot modification ----------------------------------------------- */ #define SNAP_USEDEF_SLOTS (LJ_MAX_JSLOTS+LJ_STACK_EXTRA) /* Find unused slots with reaching-definitions bytecode data-flow analysis. */ static BCReg snap_usedef(jit_State *J, uint8_t *udf, const BCIns *pc, BCReg maxslot) { BCReg s; GCobj *o; if (maxslot == 0) return 0; #ifdef LUAJIT_USE_VALGRIND /* Avoid errors for harmless reads beyond maxslot. */ memset(udf, 1, SNAP_USEDEF_SLOTS); #else memset(udf, 1, maxslot); #endif /* Treat open upvalues as used. */ o = gcref(J->L->openupval); while (o) { if (uvval(gco2uv(o)) < J->L->base) break; udf[uvval(gco2uv(o)) - J->L->base] = 0; o = gcref(o->gch.nextgc); } #define USE_SLOT(s) udf[(s)] &= ~1 #define DEF_SLOT(s) udf[(s)] *= 3 /* Scan through following bytecode and check for uses/defs. */ lj_assertJ(pc >= proto_bc(J->pt) && pc < proto_bc(J->pt) + J->pt->sizebc, "snapshot PC out of range"); for (;;) { BCIns ins = *pc++; BCOp op = bc_op(ins); switch (bcmode_b(op)) { case BCMvar: USE_SLOT(bc_b(ins)); break; default: break; } switch (bcmode_c(op)) { case BCMvar: USE_SLOT(bc_c(ins)); break; case BCMrbase: lj_assertJ(op == BC_CAT, "unhandled op %d with RC rbase", op); for (s = bc_b(ins); s <= bc_c(ins); s++) USE_SLOT(s); for (; s < maxslot; s++) DEF_SLOT(s); break; case BCMjump: handle_jump: { BCReg minslot = bc_a(ins); if (op >= BC_FORI && op <= BC_JFORL) minslot += FORL_EXT; else if (op >= BC_ITERL && op <= BC_JITERL) minslot += bc_b(pc[-2])-1; else if (op == BC_UCLO) { ptrdiff_t delta = bc_j(ins); if (delta < 0) return maxslot; /* Prevent loop. */ pc += delta; break; } for (s = minslot; s < maxslot; s++) DEF_SLOT(s); return minslot < maxslot ? minslot : maxslot; } case BCMlit: if (op == BC_JFORL || op == BC_JITERL || op == BC_JLOOP) { goto handle_jump; } else if (bc_isret(op)) { BCReg top = op == BC_RETM ? maxslot : (bc_a(ins) + bc_d(ins)-1); for (s = 0; s < bc_a(ins); s++) DEF_SLOT(s); for (; s < top; s++) USE_SLOT(s); for (; s < maxslot; s++) DEF_SLOT(s); return 0; } break; case BCMfunc: return maxslot; /* NYI: will abort, anyway. */ default: break; } switch (bcmode_a(op)) { case BCMvar: USE_SLOT(bc_a(ins)); break; case BCMdst: if (!(op == BC_ISTC || op == BC_ISFC)) DEF_SLOT(bc_a(ins)); break; case BCMbase: if (op >= BC_CALLM && op <= BC_ITERN) { BCReg top = (op == BC_CALLM || op == BC_CALLMT || bc_c(ins) == 0) ? maxslot : (bc_a(ins) + bc_c(ins)+LJ_FR2); if (LJ_FR2) DEF_SLOT(bc_a(ins)+1); s = bc_a(ins) - ((op == BC_ITERC || op == BC_ITERN) ? 3 : 0); for (; s < top; s++) USE_SLOT(s); for (; s < maxslot; s++) DEF_SLOT(s); if (op == BC_CALLT || op == BC_CALLMT) { for (s = 0; s < bc_a(ins); s++) DEF_SLOT(s); return 0; } } else if (op == BC_VARG) { return maxslot; /* NYI: punt. */ } else if (op == BC_KNIL) { for (s = bc_a(ins); s <= bc_d(ins); s++) DEF_SLOT(s); } else if (op == BC_TSETM) { for (s = bc_a(ins)-1; s < maxslot; s++) USE_SLOT(s); } break; default: break; } lj_assertJ(pc >= proto_bc(J->pt) && pc < proto_bc(J->pt) + J->pt->sizebc, "use/def analysis PC out of range"); } #undef USE_SLOT #undef DEF_SLOT return 0; /* unreachable */ } /* Mark slots used by upvalues of child prototypes as used. */ void snap_useuv(GCproto *pt, uint8_t *udf) { /* This is a coarse check, because it's difficult to correlate the lifetime ** of slots and closures. But the number of false positives is quite low. ** A false positive may cause a slot not to be purged, which is just ** a missed optimization. */ if ((pt->flags & PROTO_CHILD)) { ptrdiff_t i, j, n = pt->sizekgc; GCRef *kr = mref(pt->k, GCRef) - 1; for (i = 0; i < n; i++, kr--) { GCobj *o = gcref(*kr); if (o->gch.gct == ~LJ_TPROTO) { for (j = 0; j < gco2pt(o)->sizeuv; j++) { uint32_t v = proto_uv(gco2pt(o))[j]; if ((v & PROTO_UV_LOCAL)) { udf[(v & 0xff)] = 0; } } } } } } /* Purge dead slots before the next snapshot. */ void lj_snap_purge(jit_State *J) { uint8_t udf[SNAP_USEDEF_SLOTS]; BCReg s, maxslot = J->maxslot; if (bc_op(*J->pc) == BC_FUNCV && maxslot > J->pt->numparams) maxslot = J->pt->numparams; s = snap_usedef(J, udf, J->pc, maxslot); if (s < maxslot) { snap_useuv(J->pt, udf); for (; s < maxslot; s++) if (udf[s] != 0) J->base[s] = 0; /* Purge dead slots. */ } } /* Shrink last snapshot. */ void lj_snap_shrink(jit_State *J) { SnapShot *snap = &J->cur.snap[J->cur.nsnap-1]; SnapEntry *map = &J->cur.snapmap[snap->mapofs]; MSize n, m, nlim, nent = snap->nent; uint8_t udf[SNAP_USEDEF_SLOTS]; BCReg maxslot = J->maxslot; BCReg baseslot = J->baseslot; BCReg minslot = snap_usedef(J, udf, snap_pc(&map[nent]), maxslot); if (minslot < maxslot) snap_useuv(J->pt, udf); maxslot += baseslot; minslot += baseslot; snap->nslots = (uint8_t)maxslot; for (n = m = 0; n < nent; n++) { /* Remove unused slots from snapshot. */ BCReg s = snap_slot(map[n]); if (s < minslot || (s < maxslot && udf[s-baseslot] == 0)) map[m++] = map[n]; /* Only copy used slots. */ } snap->nent = (uint8_t)m; nlim = J->cur.nsnapmap - snap->mapofs - 1; while (n <= nlim) map[m++] = map[n++]; /* Move PC + frame links down. */ J->cur.nsnapmap = (uint32_t)(snap->mapofs + m); /* Free up space in map. */ } /* -- Snapshot access ----------------------------------------------------- */ /* Initialize a Bloom Filter with all renamed refs. ** There are very few renames (often none), so the filter has ** very few bits set. This makes it suitable for negative filtering. */ static BloomFilter snap_renamefilter(GCtrace *T, SnapNo lim) { BloomFilter rfilt = 0; IRIns *ir; for (ir = &T->ir[T->nins-1]; ir->o == IR_RENAME; ir--) if (ir->op2 <= lim) bloomset(rfilt, ir->op1); return rfilt; } /* Process matching renames to find the original RegSP. */ static RegSP snap_renameref(GCtrace *T, SnapNo lim, IRRef ref, RegSP rs) { IRIns *ir; for (ir = &T->ir[T->nins-1]; ir->o == IR_RENAME; ir--) if (ir->op1 == ref && ir->op2 <= lim) rs = ir->prev; return rs; } /* Copy RegSP from parent snapshot to the parent links of the IR. */ IRIns *lj_snap_regspmap(jit_State *J, GCtrace *T, SnapNo snapno, IRIns *ir) { SnapShot *snap = &T->snap[snapno]; SnapEntry *map = &T->snapmap[snap->mapofs]; BloomFilter rfilt = snap_renamefilter(T, snapno); MSize n = 0; IRRef ref = 0; UNUSED(J); for ( ; ; ir++) { uint32_t rs; if (ir->o == IR_SLOAD) { if (!(ir->op2 & IRSLOAD_PARENT)) break; for ( ; ; n++) { lj_assertJ(n < snap->nent, "slot %d not found in snapshot", ir->op1); if (snap_slot(map[n]) == ir->op1) { ref = snap_ref(map[n++]); break; } } } else if (LJ_SOFTFP32 && ir->o == IR_HIOP) { ref++; } else if (ir->o == IR_PVAL) { ref = ir->op1 + REF_BIAS; } else { break; } rs = T->ir[ref].prev; if (bloomtest(rfilt, ref)) rs = snap_renameref(T, snapno, ref, rs); ir->prev = (uint16_t)rs; lj_assertJ(regsp_used(rs), "unused IR %04d in snapshot", ref - REF_BIAS); } return ir; } /* -- Snapshot replay ----------------------------------------------------- */ /* Replay constant from parent trace. */ static TRef snap_replay_const(jit_State *J, IRIns *ir) { /* Only have to deal with constants that can occur in stack slots. */ switch ((IROp)ir->o) { case IR_KPRI: return TREF_PRI(irt_type(ir->t)); case IR_KINT: return lj_ir_kint(J, ir->i); case IR_KGC: return lj_ir_kgc(J, ir_kgc(ir), irt_t(ir->t)); case IR_KNUM: case IR_KINT64: return lj_ir_k64(J, (IROp)ir->o, ir_k64(ir)->u64); case IR_KPTR: return lj_ir_kptr(J, ir_kptr(ir)); /* Continuation. */ default: lj_assertJ(0, "bad IR constant op %d", ir->o); return TREF_NIL; } } /* De-duplicate parent reference. */ static TRef snap_dedup(jit_State *J, SnapEntry *map, MSize nmax, IRRef ref) { MSize j; for (j = 0; j < nmax; j++) if (snap_ref(map[j]) == ref) return J->slot[snap_slot(map[j])] & ~(SNAP_KEYINDEX|SNAP_CONT|SNAP_FRAME); return 0; } /* Emit parent reference with de-duplication. */ static TRef snap_pref(jit_State *J, GCtrace *T, SnapEntry *map, MSize nmax, BloomFilter seen, IRRef ref) { IRIns *ir = &T->ir[ref]; TRef tr; if (irref_isk(ref)) tr = snap_replay_const(J, ir); else if (!regsp_used(ir->prev)) tr = 0; else if (!bloomtest(seen, ref) || (tr = snap_dedup(J, map, nmax, ref)) == 0) tr = emitir(IRT(IR_PVAL, irt_type(ir->t)), ref - REF_BIAS, 0); return tr; } /* Check whether a sunk store corresponds to an allocation. Slow path. */ static int snap_sunk_store2(GCtrace *T, IRIns *ira, IRIns *irs) { if (irs->o == IR_ASTORE || irs->o == IR_HSTORE || irs->o == IR_FSTORE || irs->o == IR_XSTORE) { IRIns *irk = &T->ir[irs->op1]; if (irk->o == IR_AREF || irk->o == IR_HREFK) irk = &T->ir[irk->op1]; return (&T->ir[irk->op1] == ira); } return 0; } /* Check whether a sunk store corresponds to an allocation. Fast path. */ static LJ_AINLINE int snap_sunk_store(GCtrace *T, IRIns *ira, IRIns *irs) { if (irs->s != 255) return (ira + irs->s == irs); /* Fast check. */ return snap_sunk_store2(T, ira, irs); } /* Replay snapshot state to setup side trace. */ void lj_snap_replay(jit_State *J, GCtrace *T) { SnapShot *snap = &T->snap[J->exitno]; SnapEntry *map = &T->snapmap[snap->mapofs]; MSize n, nent = snap->nent; BloomFilter seen = 0; int pass23 = 0; J->framedepth = 0; /* Emit IR for slots inherited from parent snapshot. */ for (n = 0; n < nent; n++) { SnapEntry sn = map[n]; BCReg s = snap_slot(sn); IRRef ref = snap_ref(sn); IRIns *ir = &T->ir[ref]; TRef tr; /* The bloom filter avoids O(nent^2) overhead for de-duping slots. */ if (bloomtest(seen, ref) && (tr = snap_dedup(J, map, n, ref)) != 0) goto setslot; bloomset(seen, ref); if (irref_isk(ref)) { /* See special treatment of LJ_FR2 slot 1 in snapshot_slots() above. */ if (LJ_FR2 && (sn == SNAP(1, SNAP_FRAME | SNAP_NORESTORE, REF_NIL))) tr = 0; else tr = snap_replay_const(J, ir); } else if (!regsp_used(ir->prev)) { pass23 = 1; lj_assertJ(s != 0, "unused slot 0 in snapshot"); tr = s; } else { IRType t = irt_type(ir->t); uint32_t mode = IRSLOAD_INHERIT|IRSLOAD_PARENT; if (LJ_SOFTFP32 && (sn & SNAP_SOFTFPNUM)) t = IRT_NUM; if (ir->o == IR_SLOAD) mode |= (ir->op2 & IRSLOAD_READONLY); if ((sn & SNAP_KEYINDEX)) mode |= IRSLOAD_KEYINDEX; tr = emitir_raw(IRT(IR_SLOAD, t), s, mode); } setslot: /* Same as TREF_* flags. */ J->slot[s] = tr | (sn&(SNAP_KEYINDEX|SNAP_CONT|SNAP_FRAME)); J->framedepth += ((sn & (SNAP_CONT|SNAP_FRAME)) && (s != LJ_FR2)); if ((sn & SNAP_FRAME)) J->baseslot = s+1; } if (pass23) { IRIns *irlast = &T->ir[snap->ref]; pass23 = 0; /* Emit dependent PVALs. */ for (n = 0; n < nent; n++) { SnapEntry sn = map[n]; IRRef refp = snap_ref(sn); IRIns *ir = &T->ir[refp]; if (regsp_reg(ir->r) == RID_SUNK) { if (J->slot[snap_slot(sn)] != snap_slot(sn)) continue; pass23 = 1; lj_assertJ(ir->o == IR_TNEW || ir->o == IR_TDUP || ir->o == IR_CNEW || ir->o == IR_CNEWI, "sunk parent IR %04d has bad op %d", refp - REF_BIAS, ir->o); if (ir->op1 >= T->nk) snap_pref(J, T, map, nent, seen, ir->op1); if (ir->op2 >= T->nk) snap_pref(J, T, map, nent, seen, ir->op2); if (LJ_HASFFI && ir->o == IR_CNEWI) { if (LJ_32 && refp+1 < T->nins && (ir+1)->o == IR_HIOP) snap_pref(J, T, map, nent, seen, (ir+1)->op2); } else { IRIns *irs; for (irs = ir+1; irs < irlast; irs++) if (irs->r == RID_SINK && snap_sunk_store(T, ir, irs)) { if (snap_pref(J, T, map, nent, seen, irs->op2) == 0) snap_pref(J, T, map, nent, seen, T->ir[irs->op2].op1); else if ((LJ_SOFTFP32 || (LJ_32 && LJ_HASFFI)) && irs+1 < irlast && (irs+1)->o == IR_HIOP) snap_pref(J, T, map, nent, seen, (irs+1)->op2); } } } else if (!irref_isk(refp) && !regsp_used(ir->prev)) { lj_assertJ(ir->o == IR_CONV && ir->op2 == IRCONV_NUM_INT, "sunk parent IR %04d has bad op %d", refp - REF_BIAS, ir->o); J->slot[snap_slot(sn)] = snap_pref(J, T, map, nent, seen, ir->op1); } } /* Replay sunk instructions. */ for (n = 0; pass23 && n < nent; n++) { SnapEntry sn = map[n]; IRRef refp = snap_ref(sn); IRIns *ir = &T->ir[refp]; if (regsp_reg(ir->r) == RID_SUNK) { TRef op1, op2; if (J->slot[snap_slot(sn)] != snap_slot(sn)) { /* De-dup allocs. */ J->slot[snap_slot(sn)] = J->slot[J->slot[snap_slot(sn)]]; continue; } op1 = ir->op1; if (op1 >= T->nk) op1 = snap_pref(J, T, map, nent, seen, op1); op2 = ir->op2; if (op2 >= T->nk) op2 = snap_pref(J, T, map, nent, seen, op2); if (LJ_HASFFI && ir->o == IR_CNEWI) { if (LJ_32 && refp+1 < T->nins && (ir+1)->o == IR_HIOP) { lj_needsplit(J); /* Emit joining HIOP. */ op2 = emitir_raw(IRT(IR_HIOP, IRT_I64), op2, snap_pref(J, T, map, nent, seen, (ir+1)->op2)); } J->slot[snap_slot(sn)] = emitir(ir->ot & ~(IRT_MARK|IRT_ISPHI), op1, op2); } else { IRIns *irs; TRef tr = emitir(ir->ot, op1, op2); J->slot[snap_slot(sn)] = tr; for (irs = ir+1; irs < irlast; irs++) if (irs->r == RID_SINK && snap_sunk_store(T, ir, irs)) { IRIns *irr = &T->ir[irs->op1]; TRef val, key = irr->op2, tmp = tr; if (irr->o != IR_FREF) { IRIns *irk = &T->ir[key]; if (irr->o == IR_HREFK) key = lj_ir_kslot(J, snap_replay_const(J, &T->ir[irk->op1]), irk->op2); else key = snap_replay_const(J, irk); if (irr->o == IR_HREFK || irr->o == IR_AREF) { IRIns *irf = &T->ir[irr->op1]; tmp = emitir(irf->ot, tmp, irf->op2); } } tmp = emitir(irr->ot, tmp, key); val = snap_pref(J, T, map, nent, seen, irs->op2); if (val == 0) { IRIns *irc = &T->ir[irs->op2]; lj_assertJ(irc->o == IR_CONV && irc->op2 == IRCONV_NUM_INT, "sunk store for parent IR %04d with bad op %d", refp - REF_BIAS, irc->o); val = snap_pref(J, T, map, nent, seen, irc->op1); val = emitir(IRTN(IR_CONV), val, IRCONV_NUM_INT); } else if ((LJ_SOFTFP32 || (LJ_32 && LJ_HASFFI)) && irs+1 < irlast && (irs+1)->o == IR_HIOP) { IRType t = IRT_I64; if (LJ_SOFTFP32 && irt_type((irs+1)->t) == IRT_SOFTFP) t = IRT_NUM; lj_needsplit(J); if (irref_isk(irs->op2) && irref_isk((irs+1)->op2)) { uint64_t k = (uint32_t)T->ir[irs->op2].i + ((uint64_t)T->ir[(irs+1)->op2].i << 32); val = lj_ir_k64(J, t == IRT_I64 ? IR_KINT64 : IR_KNUM, k); } else { val = emitir_raw(IRT(IR_HIOP, t), val, snap_pref(J, T, map, nent, seen, (irs+1)->op2)); } tmp = emitir(IRT(irs->o, t), tmp, val); continue; } tmp = emitir(irs->ot, tmp, val); } else if (LJ_HASFFI && irs->o == IR_XBAR && ir->o == IR_CNEW) { emitir(IRT(IR_XBAR, IRT_NIL), 0, 0); } } } } } J->base = J->slot + J->baseslot; J->maxslot = snap->nslots - J->baseslot; lj_snap_add(J); if (pass23) /* Need explicit GC step _after_ initial snapshot. */ emitir_raw(IRTG(IR_GCSTEP, IRT_NIL), 0, 0); } /* -- Snapshot restore ---------------------------------------------------- */ static void snap_unsink(jit_State *J, GCtrace *T, ExitState *ex, SnapNo snapno, BloomFilter rfilt, IRIns *ir, TValue *o); /* Restore a value from the trace exit state. */ static void snap_restoreval(jit_State *J, GCtrace *T, ExitState *ex, SnapNo snapno, BloomFilter rfilt, IRRef ref, TValue *o) { IRIns *ir = &T->ir[ref]; IRType1 t = ir->t; RegSP rs = ir->prev; if (irref_isk(ref)) { /* Restore constant slot. */ if (ir->o == IR_KPTR) { o->u64 = (uint64_t)(uintptr_t)ir_kptr(ir); } else { lj_assertJ(!(ir->o == IR_KKPTR || ir->o == IR_KNULL), "restore of const from IR %04d with bad op %d", ref - REF_BIAS, ir->o); lj_ir_kvalue(J->L, o, ir); } return; } if (LJ_UNLIKELY(bloomtest(rfilt, ref))) rs = snap_renameref(T, snapno, ref, rs); if (ra_hasspill(regsp_spill(rs))) { /* Restore from spill slot. */ int32_t *sps = &ex->spill[regsp_spill(rs)]; if (irt_isinteger(t)) { setintV(o, *sps); #if !LJ_SOFTFP32 } else if (irt_isnum(t)) { o->u64 = *(uint64_t *)sps; #endif #if LJ_64 && !LJ_GC64 } else if (irt_islightud(t)) { /* 64 bit lightuserdata which may escape already has the tag bits. */ o->u64 = *(uint64_t *)sps; #endif } else { lj_assertJ(!irt_ispri(t), "PRI ref with spill slot"); setgcV(J->L, o, (GCobj *)(uintptr_t)*(GCSize *)sps, irt_toitype(t)); } } else { /* Restore from register. */ Reg r = regsp_reg(rs); if (ra_noreg(r)) { lj_assertJ(ir->o == IR_CONV && ir->op2 == IRCONV_NUM_INT, "restore from IR %04d has no reg", ref - REF_BIAS); snap_restoreval(J, T, ex, snapno, rfilt, ir->op1, o); if (LJ_DUALNUM) setnumV(o, (lua_Number)intV(o)); return; } else if (irt_isinteger(t)) { setintV(o, (int32_t)ex->gpr[r-RID_MIN_GPR]); #if !LJ_SOFTFP } else if (irt_isnum(t)) { setnumV(o, ex->fpr[r-RID_MIN_FPR]); #elif LJ_64 /* && LJ_SOFTFP */ } else if (irt_isnum(t)) { o->u64 = ex->gpr[r-RID_MIN_GPR]; #endif #if LJ_64 && !LJ_GC64 } else if (irt_is64(t)) { /* 64 bit values that already have the tag bits. */ o->u64 = ex->gpr[r-RID_MIN_GPR]; #endif } else if (irt_ispri(t)) { setpriV(o, irt_toitype(t)); } else { setgcV(J->L, o, (GCobj *)ex->gpr[r-RID_MIN_GPR], irt_toitype(t)); } } } #if LJ_HASFFI /* Restore raw data from the trace exit state. */ static void snap_restoredata(jit_State *J, GCtrace *T, ExitState *ex, SnapNo snapno, BloomFilter rfilt, IRRef ref, void *dst, CTSize sz) { IRIns *ir = &T->ir[ref]; RegSP rs = ir->prev; int32_t *src; uint64_t tmp; UNUSED(J); if (irref_isk(ref)) { if (ir_isk64(ir)) { src = (int32_t *)&ir[1]; } else if (sz == 8) { tmp = (uint64_t)(uint32_t)ir->i; src = (int32_t *)&tmp; } else { src = &ir->i; } } else { if (LJ_UNLIKELY(bloomtest(rfilt, ref))) rs = snap_renameref(T, snapno, ref, rs); if (ra_hasspill(regsp_spill(rs))) { src = &ex->spill[regsp_spill(rs)]; if (sz == 8 && !irt_is64(ir->t)) { tmp = (uint64_t)(uint32_t)*src; src = (int32_t *)&tmp; } } else { Reg r = regsp_reg(rs); if (ra_noreg(r)) { /* Note: this assumes CNEWI is never used for SOFTFP split numbers. */ lj_assertJ(sz == 8 && ir->o == IR_CONV && ir->op2 == IRCONV_NUM_INT, "restore from IR %04d has no reg", ref - REF_BIAS); snap_restoredata(J, T, ex, snapno, rfilt, ir->op1, dst, 4); *(lua_Number *)dst = (lua_Number)*(int32_t *)dst; return; } src = (int32_t *)&ex->gpr[r-RID_MIN_GPR]; #if !LJ_SOFTFP if (r >= RID_MAX_GPR) { src = (int32_t *)&ex->fpr[r-RID_MIN_FPR]; #if LJ_TARGET_PPC if (sz == 4) { /* PPC FPRs are always doubles. */ *(float *)dst = (float)*(double *)src; return; } #else if (LJ_BE && sz == 4) src++; #endif } else #endif if (LJ_64 && LJ_BE && sz == 4) src++; } } lj_assertJ(sz == 1 || sz == 2 || sz == 4 || sz == 8, "restore from IR %04d with bad size %d", ref - REF_BIAS, sz); if (sz == 4) *(int32_t *)dst = *src; else if (sz == 8) *(int64_t *)dst = *(int64_t *)src; else if (sz == 1) *(int8_t *)dst = (int8_t)*src; else *(int16_t *)dst = (int16_t)*src; } #endif /* Unsink allocation from the trace exit state. Unsink sunk stores. */ static void snap_unsink(jit_State *J, GCtrace *T, ExitState *ex, SnapNo snapno, BloomFilter rfilt, IRIns *ir, TValue *o) { lj_assertJ(ir->o == IR_TNEW || ir->o == IR_TDUP || ir->o == IR_CNEW || ir->o == IR_CNEWI, "sunk allocation with bad op %d", ir->o); #if LJ_HASFFI if (ir->o == IR_CNEW || ir->o == IR_CNEWI) { CTState *cts = ctype_cts(J->L); CTypeID id = (CTypeID)T->ir[ir->op1].i; CTSize sz; CTInfo info = lj_ctype_info(cts, id, &sz); GCcdata *cd = lj_cdata_newx(cts, id, sz, info); setcdataV(J->L, o, cd); if (ir->o == IR_CNEWI) { uint8_t *p = (uint8_t *)cdataptr(cd); lj_assertJ(sz == 4 || sz == 8, "sunk cdata with bad size %d", sz); if (LJ_32 && sz == 8 && ir+1 < T->ir + T->nins && (ir+1)->o == IR_HIOP) { snap_restoredata(J, T, ex, snapno, rfilt, (ir+1)->op2, LJ_LE ? p+4 : p, 4); if (LJ_BE) p += 4; sz = 4; } snap_restoredata(J, T, ex, snapno, rfilt, ir->op2, p, sz); } else { IRIns *irs, *irlast = &T->ir[T->snap[snapno].ref]; for (irs = ir+1; irs < irlast; irs++) if (irs->r == RID_SINK && snap_sunk_store(T, ir, irs)) { IRIns *iro = &T->ir[T->ir[irs->op1].op2]; uint8_t *p = (uint8_t *)cd; CTSize szs; lj_assertJ(irs->o == IR_XSTORE, "sunk store with bad op %d", irs->o); lj_assertJ(T->ir[irs->op1].o == IR_ADD, "sunk store with bad add op %d", T->ir[irs->op1].o); lj_assertJ(iro->o == IR_KINT || iro->o == IR_KINT64, "sunk store with bad const offset op %d", iro->o); if (irt_is64(irs->t)) szs = 8; else if (irt_isi8(irs->t) || irt_isu8(irs->t)) szs = 1; else if (irt_isi16(irs->t) || irt_isu16(irs->t)) szs = 2; else szs = 4; if (LJ_64 && iro->o == IR_KINT64) p += (int64_t)ir_k64(iro)->u64; else p += iro->i; lj_assertJ(p >= (uint8_t *)cdataptr(cd) && p + szs <= (uint8_t *)cdataptr(cd) + sz, "sunk store with offset out of range"); if (LJ_32 && irs+1 < T->ir + T->nins && (irs+1)->o == IR_HIOP) { lj_assertJ(szs == 4, "sunk store with bad size %d", szs); snap_restoredata(J, T, ex, snapno, rfilt, (irs+1)->op2, LJ_LE ? p+4 : p, 4); if (LJ_BE) p += 4; } snap_restoredata(J, T, ex, snapno, rfilt, irs->op2, p, szs); } } } else #endif { IRIns *irs, *irlast; GCtab *t = ir->o == IR_TNEW ? lj_tab_new(J->L, ir->op1, ir->op2) : lj_tab_dup(J->L, ir_ktab(&T->ir[ir->op1])); settabV(J->L, o, t); irlast = &T->ir[T->snap[snapno].ref]; for (irs = ir+1; irs < irlast; irs++) if (irs->r == RID_SINK && snap_sunk_store(T, ir, irs)) { IRIns *irk = &T->ir[irs->op1]; TValue tmp, *val; lj_assertJ(irs->o == IR_ASTORE || irs->o == IR_HSTORE || irs->o == IR_FSTORE, "sunk store with bad op %d", irs->o); if (irk->o == IR_FREF) { lj_assertJ(irk->op2 == IRFL_TAB_META, "sunk store with bad field %d", irk->op2); snap_restoreval(J, T, ex, snapno, rfilt, irs->op2, &tmp); /* NOBARRIER: The table is new (marked white). */ setgcref(t->metatable, obj2gco(tabV(&tmp))); } else { irk = &T->ir[irk->op2]; if (irk->o == IR_KSLOT) irk = &T->ir[irk->op1]; lj_ir_kvalue(J->L, &tmp, irk); val = lj_tab_set(J->L, t, &tmp); /* NOBARRIER: The table is new (marked white). */ snap_restoreval(J, T, ex, snapno, rfilt, irs->op2, val); if (LJ_SOFTFP32 && irs+1 < T->ir + T->nins && (irs+1)->o == IR_HIOP) { snap_restoreval(J, T, ex, snapno, rfilt, (irs+1)->op2, &tmp); val->u32.hi = tmp.u32.lo; } } } } } /* Restore interpreter state from exit state with the help of a snapshot. */ const BCIns *lj_snap_restore(jit_State *J, void *exptr) { ExitState *ex = (ExitState *)exptr; SnapNo snapno = J->exitno; /* For now, snapno == exitno. */ GCtrace *T = traceref(J, J->parent); SnapShot *snap = &T->snap[snapno]; MSize n, nent = snap->nent; SnapEntry *map = &T->snapmap[snap->mapofs]; #if !LJ_FR2 || defined(LUA_USE_ASSERT) SnapEntry *flinks = &T->snapmap[snap_nextofs(T, snap)-1-LJ_FR2]; #endif #if !LJ_FR2 ptrdiff_t ftsz0; #endif TValue *frame; BloomFilter rfilt = snap_renamefilter(T, snapno); const BCIns *pc = snap_pc(&map[nent]); lua_State *L = J->L; /* Set interpreter PC to the next PC to get correct error messages. */ setcframe_pc(cframe_raw(L->cframe), pc+1); /* Make sure the stack is big enough for the slots from the snapshot. */ if (LJ_UNLIKELY(L->base + snap->topslot >= tvref(L->maxstack))) { L->top = curr_topL(L); lj_state_growstack(L, snap->topslot - curr_proto(L)->framesize); } /* Fill stack slots with data from the registers and spill slots. */ frame = L->base-1-LJ_FR2; #if !LJ_FR2 ftsz0 = frame_ftsz(frame); /* Preserve link to previous frame in slot #0. */ #endif for (n = 0; n < nent; n++) { SnapEntry sn = map[n]; if (!(sn & SNAP_NORESTORE)) { TValue *o = &frame[snap_slot(sn)]; IRRef ref = snap_ref(sn); IRIns *ir = &T->ir[ref]; if (ir->r == RID_SUNK) { MSize j; for (j = 0; j < n; j++) if (snap_ref(map[j]) == ref) { /* De-duplicate sunk allocations. */ copyTV(L, o, &frame[snap_slot(map[j])]); goto dupslot; } snap_unsink(J, T, ex, snapno, rfilt, ir, o); dupslot: continue; } snap_restoreval(J, T, ex, snapno, rfilt, ref, o); if (LJ_SOFTFP32 && (sn & SNAP_SOFTFPNUM) && tvisint(o)) { TValue tmp; snap_restoreval(J, T, ex, snapno, rfilt, ref+1, &tmp); o->u32.hi = tmp.u32.lo; #if !LJ_FR2 } else if ((sn & (SNAP_CONT|SNAP_FRAME))) { /* Overwrite tag with frame link. */ setframe_ftsz(o, snap_slot(sn) != 0 ? (int32_t)*flinks-- : ftsz0); L->base = o+1; #endif } else if ((sn & SNAP_KEYINDEX)) { /* A IRT_INT key index slot is restored as a number. Undo this. */ o->u32.lo = (uint32_t)(LJ_DUALNUM ? intV(o) : lj_num2int(numV(o))); o->u32.hi = LJ_KEYINDEX; } } } #if LJ_FR2 L->base += (map[nent+LJ_BE] & 0xff); #endif lj_assertJ(map + nent == flinks, "inconsistent frames in snapshot"); /* Compute current stack top. */ switch (bc_op(*pc)) { default: if (bc_op(*pc) < BC_FUNCF) { L->top = curr_topL(L); break; } /* fallthrough */ case BC_CALLM: case BC_CALLMT: case BC_RETM: case BC_TSETM: L->top = frame + snap->nslots; break; } return pc; } #undef emitir_raw #undef emitir #endif
xLua/build/luajit-2.1.0b3/src/lj_snap.c/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_snap.c", "repo_id": "xLua", "token_count": 15557 }
2,123
/* ** Definitions for MIPS CPUs. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #ifndef _LJ_TARGET_MIPS_H #define _LJ_TARGET_MIPS_H /* -- Registers IDs ------------------------------------------------------- */ #define GPRDEF(_) \ _(R0) _(R1) _(R2) _(R3) _(R4) _(R5) _(R6) _(R7) \ _(R8) _(R9) _(R10) _(R11) _(R12) _(R13) _(R14) _(R15) \ _(R16) _(R17) _(R18) _(R19) _(R20) _(R21) _(R22) _(R23) \ _(R24) _(R25) _(SYS1) _(SYS2) _(R28) _(SP) _(R30) _(RA) #if LJ_SOFTFP #define FPRDEF(_) #else #define FPRDEF(_) \ _(F0) _(F1) _(F2) _(F3) _(F4) _(F5) _(F6) _(F7) \ _(F8) _(F9) _(F10) _(F11) _(F12) _(F13) _(F14) _(F15) \ _(F16) _(F17) _(F18) _(F19) _(F20) _(F21) _(F22) _(F23) \ _(F24) _(F25) _(F26) _(F27) _(F28) _(F29) _(F30) _(F31) #endif #define VRIDDEF(_) #define RIDENUM(name) RID_##name, enum { GPRDEF(RIDENUM) /* General-purpose registers (GPRs). */ FPRDEF(RIDENUM) /* Floating-point registers (FPRs). */ RID_MAX, RID_ZERO = RID_R0, RID_TMP = RID_RA, RID_GP = RID_R28, /* Calling conventions. */ RID_RET = RID_R2, #if LJ_LE RID_RETHI = RID_R3, RID_RETLO = RID_R2, #else RID_RETHI = RID_R2, RID_RETLO = RID_R3, #endif #if LJ_SOFTFP RID_FPRET = RID_R2, #else RID_FPRET = RID_F0, #endif RID_CFUNCADDR = RID_R25, /* These definitions must match with the *.dasc file(s): */ RID_BASE = RID_R16, /* Interpreter BASE. */ RID_LPC = RID_R18, /* Interpreter PC. */ RID_DISPATCH = RID_R19, /* Interpreter DISPATCH table. */ RID_LREG = RID_R20, /* Interpreter L. */ RID_JGL = RID_R30, /* On-trace: global_State + 32768. */ /* Register ranges [min, max) and number of registers. */ RID_MIN_GPR = RID_R0, RID_MAX_GPR = RID_RA+1, RID_MIN_FPR = RID_MAX_GPR, #if LJ_SOFTFP RID_MAX_FPR = RID_MIN_FPR, #else RID_MAX_FPR = RID_F31+1, #endif RID_NUM_GPR = RID_MAX_GPR - RID_MIN_GPR, RID_NUM_FPR = RID_MAX_FPR - RID_MIN_FPR /* Only even regs are used. */ }; #define RID_NUM_KREF RID_NUM_GPR #define RID_MIN_KREF RID_R0 /* -- Register sets ------------------------------------------------------- */ /* Make use of all registers, except ZERO, TMP, SP, SYS1, SYS2, JGL and GP. */ #define RSET_FIXED \ (RID2RSET(RID_ZERO)|RID2RSET(RID_TMP)|RID2RSET(RID_SP)|\ RID2RSET(RID_SYS1)|RID2RSET(RID_SYS2)|RID2RSET(RID_JGL)|RID2RSET(RID_GP)) #define RSET_GPR (RSET_RANGE(RID_MIN_GPR, RID_MAX_GPR) - RSET_FIXED) #if LJ_SOFTFP #define RSET_FPR 0 #else #if LJ_32 #define RSET_FPR \ (RID2RSET(RID_F0)|RID2RSET(RID_F2)|RID2RSET(RID_F4)|RID2RSET(RID_F6)|\ RID2RSET(RID_F8)|RID2RSET(RID_F10)|RID2RSET(RID_F12)|RID2RSET(RID_F14)|\ RID2RSET(RID_F16)|RID2RSET(RID_F18)|RID2RSET(RID_F20)|RID2RSET(RID_F22)|\ RID2RSET(RID_F24)|RID2RSET(RID_F26)|RID2RSET(RID_F28)|RID2RSET(RID_F30)) #else #define RSET_FPR RSET_RANGE(RID_MIN_FPR, RID_MAX_FPR) #endif #endif #define RSET_ALL (RSET_GPR|RSET_FPR) #define RSET_INIT RSET_ALL #define RSET_SCRATCH_GPR \ (RSET_RANGE(RID_R1, RID_R15+1)|\ RID2RSET(RID_R24)|RID2RSET(RID_R25)) #if LJ_SOFTFP #define RSET_SCRATCH_FPR 0 #else #if LJ_32 #define RSET_SCRATCH_FPR \ (RID2RSET(RID_F0)|RID2RSET(RID_F2)|RID2RSET(RID_F4)|RID2RSET(RID_F6)|\ RID2RSET(RID_F8)|RID2RSET(RID_F10)|RID2RSET(RID_F12)|RID2RSET(RID_F14)|\ RID2RSET(RID_F16)|RID2RSET(RID_F18)) #else #define RSET_SCRATCH_FPR RSET_RANGE(RID_F0, RID_F24) #endif #endif #define RSET_SCRATCH (RSET_SCRATCH_GPR|RSET_SCRATCH_FPR) #define REGARG_FIRSTGPR RID_R4 #if LJ_32 #define REGARG_LASTGPR RID_R7 #define REGARG_NUMGPR 4 #else #define REGARG_LASTGPR RID_R11 #define REGARG_NUMGPR 8 #endif #if LJ_ABI_SOFTFP #define REGARG_FIRSTFPR 0 #define REGARG_LASTFPR 0 #define REGARG_NUMFPR 0 #else #define REGARG_FIRSTFPR RID_F12 #if LJ_32 #define REGARG_LASTFPR RID_F14 #define REGARG_NUMFPR 2 #else #define REGARG_LASTFPR RID_F19 #define REGARG_NUMFPR 8 #endif #endif /* -- Spill slots --------------------------------------------------------- */ /* Spill slots are 32 bit wide. An even/odd pair is used for FPRs. ** ** SPS_FIXED: Available fixed spill slots in interpreter frame. ** This definition must match with the *.dasc file(s). ** ** SPS_FIRST: First spill slot for general use. */ #if LJ_32 #define SPS_FIXED 5 #else #define SPS_FIXED 4 #endif #define SPS_FIRST 4 #define SPOFS_TMP 0 #define sps_scale(slot) (4 * (int32_t)(slot)) #define sps_align(slot) (((slot) - SPS_FIXED + 1) & ~1) /* -- Exit state ---------------------------------------------------------- */ /* This definition must match with the *.dasc file(s). */ typedef struct { #if !LJ_SOFTFP lua_Number fpr[RID_NUM_FPR]; /* Floating-point registers. */ #endif intptr_t gpr[RID_NUM_GPR]; /* General-purpose registers. */ int32_t spill[256]; /* Spill slots. */ } ExitState; /* Highest exit + 1 indicates stack check. */ #define EXITSTATE_CHECKEXIT 1 /* Return the address of a per-trace exit stub. */ static LJ_AINLINE uint32_t *exitstub_trace_addr_(uint32_t *p) { while (*p == 0x00000000) p++; /* Skip MIPSI_NOP. */ return p; } /* Avoid dependence on lj_jit.h if only including lj_target.h. */ #define exitstub_trace_addr(T, exitno) \ exitstub_trace_addr_((MCode *)((char *)(T)->mcode + (T)->szmcode)) /* -- Instructions -------------------------------------------------------- */ /* Instruction fields. */ #define MIPSF_S(r) ((r) << 21) #define MIPSF_T(r) ((r) << 16) #define MIPSF_D(r) ((r) << 11) #define MIPSF_R(r) ((r) << 21) #define MIPSF_H(r) ((r) << 16) #define MIPSF_G(r) ((r) << 11) #define MIPSF_F(r) ((r) << 6) #define MIPSF_A(n) ((n) << 6) #define MIPSF_M(n) ((n) << 11) #define MIPSF_L(n) ((n) << 6) typedef enum MIPSIns { MIPSI_D = 0x38, MIPSI_DV = 0x10, MIPSI_D32 = 0x3c, /* Integer instructions. */ MIPSI_MOVE = 0x00000025, MIPSI_NOP = 0x00000000, MIPSI_LI = 0x24000000, MIPSI_LU = 0x34000000, MIPSI_LUI = 0x3c000000, MIPSI_AND = 0x00000024, MIPSI_ANDI = 0x30000000, MIPSI_OR = 0x00000025, MIPSI_ORI = 0x34000000, MIPSI_XOR = 0x00000026, MIPSI_XORI = 0x38000000, MIPSI_NOR = 0x00000027, MIPSI_SLT = 0x0000002a, MIPSI_SLTU = 0x0000002b, MIPSI_SLTI = 0x28000000, MIPSI_SLTIU = 0x2c000000, MIPSI_ADDU = 0x00000021, MIPSI_ADDIU = 0x24000000, MIPSI_SUB = 0x00000022, MIPSI_SUBU = 0x00000023, #if !LJ_TARGET_MIPSR6 MIPSI_MUL = 0x70000002, MIPSI_DIV = 0x0000001a, MIPSI_DIVU = 0x0000001b, MIPSI_MOVZ = 0x0000000a, MIPSI_MOVN = 0x0000000b, MIPSI_MFHI = 0x00000010, MIPSI_MFLO = 0x00000012, MIPSI_MULT = 0x00000018, #else MIPSI_MUL = 0x00000098, MIPSI_MUH = 0x000000d8, MIPSI_DIV = 0x0000009a, MIPSI_DIVU = 0x0000009b, MIPSI_SELEQZ = 0x00000035, MIPSI_SELNEZ = 0x00000037, #endif MIPSI_SLL = 0x00000000, MIPSI_SRL = 0x00000002, MIPSI_SRA = 0x00000003, MIPSI_ROTR = 0x00200002, /* MIPSXXR2 */ MIPSI_DROTR = 0x0020003a, MIPSI_DROTR32 = 0x0020003e, MIPSI_SLLV = 0x00000004, MIPSI_SRLV = 0x00000006, MIPSI_SRAV = 0x00000007, MIPSI_ROTRV = 0x00000046, /* MIPSXXR2 */ MIPSI_DROTRV = 0x00000056, MIPSI_INS = 0x7c000004, /* MIPSXXR2 */ MIPSI_SEB = 0x7c000420, /* MIPSXXR2 */ MIPSI_SEH = 0x7c000620, /* MIPSXXR2 */ MIPSI_WSBH = 0x7c0000a0, /* MIPSXXR2 */ MIPSI_DSBH = 0x7c0000a4, MIPSI_B = 0x10000000, MIPSI_J = 0x08000000, MIPSI_JAL = 0x0c000000, #if !LJ_TARGET_MIPSR6 MIPSI_JALX = 0x74000000, MIPSI_JR = 0x00000008, #else MIPSI_JR = 0x00000009, MIPSI_BALC = 0xe8000000, #endif MIPSI_JALR = 0x0000f809, MIPSI_BEQ = 0x10000000, MIPSI_BNE = 0x14000000, MIPSI_BLEZ = 0x18000000, MIPSI_BGTZ = 0x1c000000, MIPSI_BLTZ = 0x04000000, MIPSI_BGEZ = 0x04010000, /* Load/store instructions. */ MIPSI_LW = 0x8c000000, MIPSI_LD = 0xdc000000, MIPSI_SW = 0xac000000, MIPSI_SD = 0xfc000000, MIPSI_LB = 0x80000000, MIPSI_SB = 0xa0000000, MIPSI_LH = 0x84000000, MIPSI_SH = 0xa4000000, MIPSI_LBU = 0x90000000, MIPSI_LHU = 0x94000000, MIPSI_LWC1 = 0xc4000000, MIPSI_SWC1 = 0xe4000000, MIPSI_LDC1 = 0xd4000000, MIPSI_SDC1 = 0xf4000000, /* MIPS64 instructions. */ MIPSI_DADD = 0x0000002c, MIPSI_DADDU = 0x0000002d, MIPSI_DADDIU = 0x64000000, MIPSI_DSUB = 0x0000002e, MIPSI_DSUBU = 0x0000002f, #if !LJ_TARGET_MIPSR6 MIPSI_DDIV = 0x0000001e, MIPSI_DDIVU = 0x0000001f, MIPSI_DMULT = 0x0000001c, MIPSI_DMULTU = 0x0000001d, #else MIPSI_DDIV = 0x0000009e, MIPSI_DMOD = 0x000000de, MIPSI_DDIVU = 0x0000009f, MIPSI_DMODU = 0x000000df, MIPSI_DMUL = 0x0000009c, MIPSI_DMUH = 0x000000dc, #endif MIPSI_DSLL = 0x00000038, MIPSI_DSRL = 0x0000003a, MIPSI_DSLLV = 0x00000014, MIPSI_DSRLV = 0x00000016, MIPSI_DSRA = 0x0000003b, MIPSI_DSRAV = 0x00000017, MIPSI_DSRA32 = 0x0000003f, MIPSI_DSLL32 = 0x0000003c, MIPSI_DSRL32 = 0x0000003e, MIPSI_DSHD = 0x7c000164, MIPSI_AADDU = LJ_32 ? MIPSI_ADDU : MIPSI_DADDU, MIPSI_AADDIU = LJ_32 ? MIPSI_ADDIU : MIPSI_DADDIU, MIPSI_ASUBU = LJ_32 ? MIPSI_SUBU : MIPSI_DSUBU, MIPSI_AL = LJ_32 ? MIPSI_LW : MIPSI_LD, MIPSI_AS = LJ_32 ? MIPSI_SW : MIPSI_SD, #if LJ_TARGET_MIPSR6 MIPSI_LSA = 0x00000005, MIPSI_DLSA = 0x00000015, MIPSI_ALSA = LJ_32 ? MIPSI_LSA : MIPSI_DLSA, #endif /* Extract/insert instructions. */ MIPSI_DEXTM = 0x7c000001, MIPSI_DEXTU = 0x7c000002, MIPSI_DEXT = 0x7c000003, MIPSI_DINSM = 0x7c000005, MIPSI_DINSU = 0x7c000006, MIPSI_DINS = 0x7c000007, MIPSI_FLOOR_D = 0x4620000b, /* FP instructions. */ MIPSI_MOV_S = 0x46000006, MIPSI_MOV_D = 0x46200006, #if !LJ_TARGET_MIPSR6 MIPSI_MOVT_D = 0x46210011, MIPSI_MOVF_D = 0x46200011, #else MIPSI_MIN_D = 0x4620001C, MIPSI_MAX_D = 0x4620001E, MIPSI_SEL_D = 0x46200010, #endif MIPSI_ABS_D = 0x46200005, MIPSI_NEG_D = 0x46200007, MIPSI_ADD_D = 0x46200000, MIPSI_SUB_D = 0x46200001, MIPSI_MUL_D = 0x46200002, MIPSI_DIV_D = 0x46200003, MIPSI_SQRT_D = 0x46200004, MIPSI_ADD_S = 0x46000000, MIPSI_SUB_S = 0x46000001, MIPSI_CVT_D_S = 0x46000021, MIPSI_CVT_W_S = 0x46000024, MIPSI_CVT_S_D = 0x46200020, MIPSI_CVT_W_D = 0x46200024, MIPSI_CVT_S_W = 0x46800020, MIPSI_CVT_D_W = 0x46800021, MIPSI_CVT_S_L = 0x46a00020, MIPSI_CVT_D_L = 0x46a00021, MIPSI_TRUNC_W_S = 0x4600000d, MIPSI_TRUNC_W_D = 0x4620000d, MIPSI_TRUNC_L_S = 0x46000009, MIPSI_TRUNC_L_D = 0x46200009, MIPSI_FLOOR_W_S = 0x4600000f, MIPSI_FLOOR_W_D = 0x4620000f, MIPSI_MFC1 = 0x44000000, MIPSI_MTC1 = 0x44800000, MIPSI_DMTC1 = 0x44a00000, MIPSI_DMFC1 = 0x44200000, #if !LJ_TARGET_MIPSR6 MIPSI_BC1F = 0x45000000, MIPSI_BC1T = 0x45010000, MIPSI_C_EQ_D = 0x46200032, MIPSI_C_OLT_S = 0x46000034, MIPSI_C_OLT_D = 0x46200034, MIPSI_C_ULT_D = 0x46200035, MIPSI_C_OLE_D = 0x46200036, MIPSI_C_ULE_D = 0x46200037, #else MIPSI_BC1EQZ = 0x45200000, MIPSI_BC1NEZ = 0x45a00000, MIPSI_CMP_EQ_D = 0x46a00002, MIPSI_CMP_LT_S = 0x46800004, MIPSI_CMP_LT_D = 0x46a00004, #endif } MIPSIns; #endif
xLua/build/luajit-2.1.0b3/src/lj_target_mips.h/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_target_mips.h", "repo_id": "xLua", "token_count": 5795 }
2,124
/* ** Configuration header. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #ifndef luaconf_h #define luaconf_h #ifndef WINVER #define WINVER 0x0501 #endif #include <limits.h> #include <stddef.h> /* Default path for loading Lua and C modules with require(). */ #if defined(_WIN32) /* ** In Windows, any exclamation mark ('!') in the path is replaced by the ** path of the directory of the executable file of the current process. */ #define LUA_LDIR "!\\lua\\" #define LUA_CDIR "!\\" #define LUA_PATH_DEFAULT \ ".\\?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" #define LUA_CPATH_DEFAULT \ ".\\?.dll;" LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll" #else /* ** Note to distribution maintainers: do NOT patch the following lines! ** Please read ../doc/install.html#distro and pass PREFIX=/usr instead. */ #ifndef LUA_MULTILIB #define LUA_MULTILIB "lib" #endif #ifndef LUA_LMULTILIB #define LUA_LMULTILIB "lib" #endif #define LUA_LROOT "/usr/local" #define LUA_LUADIR "/lua/5.1/" #define LUA_LJDIR "/luajit-2.1.0-beta3/" #ifdef LUA_ROOT #define LUA_JROOT LUA_ROOT #define LUA_RLDIR LUA_ROOT "/share" LUA_LUADIR #define LUA_RCDIR LUA_ROOT "/" LUA_MULTILIB LUA_LUADIR #define LUA_RLPATH ";" LUA_RLDIR "?.lua;" LUA_RLDIR "?/init.lua" #define LUA_RCPATH ";" LUA_RCDIR "?.so" #else #define LUA_JROOT LUA_LROOT #define LUA_RLPATH #define LUA_RCPATH #endif #define LUA_JPATH ";" LUA_JROOT "/share" LUA_LJDIR "?.lua" #define LUA_LLDIR LUA_LROOT "/share" LUA_LUADIR #define LUA_LCDIR LUA_LROOT "/" LUA_LMULTILIB LUA_LUADIR #define LUA_LLPATH ";" LUA_LLDIR "?.lua;" LUA_LLDIR "?/init.lua" #define LUA_LCPATH1 ";" LUA_LCDIR "?.so" #define LUA_LCPATH2 ";" LUA_LCDIR "loadall.so" #define LUA_PATH_DEFAULT "./?.lua" LUA_JPATH LUA_LLPATH LUA_RLPATH #define LUA_CPATH_DEFAULT "./?.so" LUA_LCPATH1 LUA_RCPATH LUA_LCPATH2 #endif /* Environment variable names for path overrides and initialization code. */ #define LUA_PATH "LUA_PATH" #define LUA_CPATH "LUA_CPATH" #define LUA_INIT "LUA_INIT" /* Special file system characters. */ #if defined(_WIN32) #define LUA_DIRSEP "\\" #else #define LUA_DIRSEP "/" #endif #define LUA_PATHSEP ";" #define LUA_PATH_MARK "?" #define LUA_EXECDIR "!" #define LUA_IGMARK "-" #define LUA_PATH_CONFIG \ LUA_DIRSEP "\n" LUA_PATHSEP "\n" LUA_PATH_MARK "\n" \ LUA_EXECDIR "\n" LUA_IGMARK "\n" /* Quoting in error messages. */ #define LUA_QL(x) "'" x "'" #define LUA_QS LUA_QL("%s") /* Various tunables. */ #define LUAI_MAXSTACK 65500 /* Max. # of stack slots for a thread (<64K). */ #define LUAI_MAXCSTACK 8000 /* Max. # of stack slots for a C func (<10K). */ #define LUAI_GCPAUSE 200 /* Pause GC until memory is at 200%. */ #define LUAI_GCMUL 200 /* Run GC at 200% of allocation speed. */ #define LUA_MAXCAPTURES 32 /* Max. pattern captures. */ /* Configuration for the frontend (the luajit executable). */ #if defined(luajit_c) #define LUA_PROGNAME "luajit" /* Fallback frontend name. */ #define LUA_PROMPT "> " /* Interactive prompt. */ #define LUA_PROMPT2 ">> " /* Continuation prompt. */ #define LUA_MAXINPUT 512 /* Max. input line length. */ #endif /* Note: changing the following defines breaks the Lua 5.1 ABI. */ #define LUA_INTEGER ptrdiff_t #define LUA_IDSIZE 60 /* Size of lua_Debug.short_src. */ /* ** Size of lauxlib and io.* on-stack buffers. Weird workaround to avoid using ** unreasonable amounts of stack space, but still retain ABI compatibility. ** Blame Lua for depending on BUFSIZ in the ABI, blame **** for wrecking it. */ #define LUAL_BUFFERSIZE (BUFSIZ > 16384 ? 8192 : BUFSIZ) /* The following defines are here only for compatibility with luaconf.h ** from the standard Lua distribution. They must not be changed for LuaJIT. */ #define LUA_NUMBER_DOUBLE #define LUA_NUMBER double #define LUAI_UACNUMBER double #define LUA_NUMBER_SCAN "%lf" #define LUA_NUMBER_FMT "%.14g" #define lua_number2str(s, n) sprintf((s), LUA_NUMBER_FMT, (n)) #define LUAI_MAXNUMBER2STR 32 #define LUA_INTFRMLEN "l" #define LUA_INTFRM_T long /* Linkage of public API functions. */ #if defined(LUA_BUILD_AS_DLL) #if defined(LUA_CORE) || defined(LUA_LIB) #define LUA_API __declspec(dllexport) #else #define LUA_API __declspec(dllimport) #endif #else #define LUA_API extern #endif #define LUALIB_API LUA_API /* Compatibility support for assertions. */ #if defined(LUA_USE_ASSERT) || defined(LUA_USE_APICHECK) #include <assert.h> #endif #ifdef LUA_USE_ASSERT #define lua_assert(x) assert(x) #endif #ifdef LUA_USE_APICHECK #define luai_apicheck(L, o) { (void)L; assert(o); } #else #define luai_apicheck(L, o) { (void)L; } #endif #endif
xLua/build/luajit-2.1.0b3/src/luaconf.h/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/luaconf.h", "repo_id": "xLua", "token_count": 1919 }
2,125
.PHONY: default test benchmark clean default: @echo "make target include: test bechmark clean" test: $(MAKE) -C test test benchmark: $(MAKE) -C test benchmark clean: $(MAKE) -C test clean
xLua/build/luajit-2.1.0b3/src/x64/Makefile/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/x64/Makefile", "repo_id": "xLua", "token_count": 74 }
2,126
#ifndef AUXILIAR_H #define AUXILIAR_H /*=========================================================================*\ * Auxiliar routines for class hierarchy manipulation * LuaSocket toolkit (but completely independent of other LuaSocket modules) * * A LuaSocket class is a name associated with Lua metatables. A LuaSocket * group is a name associated with a class. A class can belong to any number * of groups. This module provides the functionality to: * * - create new classes * - add classes to groups * - set the class of objects * - check if an object belongs to a given class or group * - get the userdata associated to objects * - print objects in a pretty way * * LuaSocket class names follow the convention <module>{<class>}. Modules * can define any number of classes and groups. The module tcp.c, for * example, defines the classes tcp{master}, tcp{client} and tcp{server} and * the groups tcp{client,server} and tcp{any}. Module functions can then * perform type-checking on their arguments by either class or group. * * LuaSocket metatables define the __index metamethod as being a table. This * table has one field for each method supported by the class, and a field * "class" with the class name. * * The mapping from class name to the corresponding metatable and the * reverse mapping are done using lauxlib. \*=========================================================================*/ #include "lua.h" #include "lauxlib.h" int auxiliar_open(lua_State *L); void auxiliar_newclass(lua_State *L, const char *classname, luaL_Reg *func); void auxiliar_add2group(lua_State *L, const char *classname, const char *group); void auxiliar_setclass(lua_State *L, const char *classname, int objidx); void *auxiliar_checkclass(lua_State *L, const char *classname, int objidx); void *auxiliar_checkgroup(lua_State *L, const char *groupname, int objidx); void *auxiliar_getclassudata(lua_State *L, const char *groupname, int objidx); void *auxiliar_getgroupudata(lua_State *L, const char *groupname, int objidx); int auxiliar_checkboolean(lua_State *L, int objidx); int auxiliar_tostring(lua_State *L); int auxiliar_typeerror(lua_State *L, int narg, const char *tname); #endif /* AUXILIAR_H */
xLua/build/luasocket/auxiliar.h/0
{ "file_path": "xLua/build/luasocket/auxiliar.h", "repo_id": "xLua", "token_count": 648 }
2,127
#ifndef OPTIONS_H #define OPTIONS_H /*=========================================================================*\ * Common option interface * LuaSocket toolkit * * This module provides a common interface to socket options, used mainly by * modules UDP and TCP. \*=========================================================================*/ #include "lua.h" #include "socket.h" /* option registry */ typedef struct t_opt { const char *name; int (*func)(lua_State *L, p_socket ps); } t_opt; typedef t_opt *p_opt; /* supported options for setoption */ int opt_set_dontroute(lua_State *L, p_socket ps); int opt_set_broadcast(lua_State *L, p_socket ps); int opt_set_reuseaddr(lua_State *L, p_socket ps); int opt_set_tcp_nodelay(lua_State *L, p_socket ps); int opt_set_keepalive(lua_State *L, p_socket ps); int opt_set_linger(lua_State *L, p_socket ps); int opt_set_reuseaddr(lua_State *L, p_socket ps); int opt_set_reuseport(lua_State *L, p_socket ps); int opt_set_ip_multicast_if(lua_State *L, p_socket ps); int opt_set_ip_multicast_ttl(lua_State *L, p_socket ps); int opt_set_ip_multicast_loop(lua_State *L, p_socket ps); int opt_set_ip_add_membership(lua_State *L, p_socket ps); int opt_set_ip_drop_membersip(lua_State *L, p_socket ps); int opt_set_ip6_unicast_hops(lua_State *L, p_socket ps); int opt_set_ip6_multicast_hops(lua_State *L, p_socket ps); int opt_set_ip6_multicast_loop(lua_State *L, p_socket ps); int opt_set_ip6_add_membership(lua_State *L, p_socket ps); int opt_set_ip6_drop_membersip(lua_State *L, p_socket ps); int opt_set_ip6_v6only(lua_State *L, p_socket ps); /* supported options for getoption */ int opt_get_reuseaddr(lua_State *L, p_socket ps); int opt_get_tcp_nodelay(lua_State *L, p_socket ps); int opt_get_keepalive(lua_State *L, p_socket ps); int opt_get_linger(lua_State *L, p_socket ps); int opt_get_reuseaddr(lua_State *L, p_socket ps); int opt_get_ip_multicast_loop(lua_State *L, p_socket ps); int opt_get_ip_multicast_if(lua_State *L, p_socket ps); int opt_get_error(lua_State *L, p_socket ps); int opt_get_ip6_multicast_loop(lua_State *L, p_socket ps); int opt_get_ip6_multicast_hops(lua_State *L, p_socket ps); int opt_get_ip6_unicast_hops(lua_State *L, p_socket ps); int opt_get_ip6_v6only(lua_State *L, p_socket ps); /* invokes the appropriate option handler */ int opt_meth_setoption(lua_State *L, p_opt opt, p_socket ps); int opt_meth_getoption(lua_State *L, p_opt opt, p_socket ps); #endif
xLua/build/luasocket/options.h/0
{ "file_path": "xLua/build/luasocket/options.h", "repo_id": "xLua", "token_count": 947 }
2,128
#ifndef WSOCKET_H #define WSOCKET_H /*=========================================================================*\ * Socket compatibilization module for Win32 * LuaSocket toolkit \*=========================================================================*/ /*=========================================================================*\ * WinSock include files \*=========================================================================*/ #include <winsock2.h> #include <ws2tcpip.h> typedef int socklen_t; typedef SOCKADDR_STORAGE t_sockaddr_storage; typedef SOCKET t_socket; typedef t_socket *p_socket; #ifndef IPV6_V6ONLY #define IPV6_V6ONLY 27 #endif #define SOCKET_INVALID (INVALID_SOCKET) #ifndef SO_REUSEPORT #define SO_REUSEPORT SO_REUSEADDR #endif #ifndef AI_NUMERICSERV #define AI_NUMERICSERV (0) #endif #endif /* WSOCKET_H */
xLua/build/luasocket/wsocket.h/0
{ "file_path": "xLua/build/luasocket/wsocket.h", "repo_id": "xLua", "token_count": 267 }
2,129
mkdir -p build_osx && cd build_osx cmake -GXcode ../ cd .. cmake --build build_osx --config Release mkdir -p plugin_lua53/Plugins/xlua.bundle/Contents/MacOS/ cp build_osx/Release/xlua.bundle/Contents/MacOS/xlua plugin_lua53/Plugins/xlua.bundle/Contents/MacOS/xlua
xLua/build/make_osx_lua53.sh/0
{ "file_path": "xLua/build/make_osx_lua53.sh", "repo_id": "xLua", "token_count": 106 }
2,130
mkdir build_uwp & pushd build_uwp cmake -G "Visual Studio 14 2015" -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=10.0 .. IF %ERRORLEVEL% NEQ 0 cmake -G "Visual Studio 15 2017" -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=10.0 .. popd cmake --build build_uwp --config Release md plugin_lua53\Plugins\WSA\x86 copy /Y build_uwp\Release\xlua.dll plugin_lua53\Plugins\WSA\x86\xlua.dll mkdir build_uwp64 & pushd build_uwp64 cmake -G "Visual Studio 14 2015 Win64" -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=10.0 .. IF %ERRORLEVEL% NEQ 0 cmake -G "Visual Studio 15 2017 Win64" -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=10.0 .. popd cmake --build build_uwp64 --config Release md plugin_lua53\Plugins\WSA\x64 copy /Y build_uwp64\Release\xlua.dll plugin_lua53\Plugins\WSA\x64\xlua.dll mkdir build_uwp_arm & pushd build_uwp_arm cmake -G "Visual Studio 14 2015 ARM" -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=10.0 .. IF %ERRORLEVEL% NEQ 0 cmake -G "Visual Studio 15 2017 ARM" -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=10.0 .. popd cmake --build build_uwp_arm --config Release md plugin_lua53\Plugins\WSA\ARM copy /Y build_uwp_arm\Release\xlua.dll plugin_lua53\Plugins\WSA\ARM\xlua.dll pause
xLua/build/vs2015/make_uwp.bat/0
{ "file_path": "xLua/build/vs2015/make_uwp.bat", "repo_id": "xLua", "token_count": 501 }
2,131
--- title: FAQ type: guide order: 3 --- ## FAQ ### xLua发布包怎么用? xLua目前以zip包形式发布,在工程目录下解压即可。 ### xLua可以放别的目录吗? 可以,但生成代码目录需要配置一下(默认放`Assets\XLua\Gen`目录),具体可以看《XLua的配置.doc》的GenPath配置介绍。 ### lua源码只能以txt后缀? 什么后缀都可以。 如果你想以`TextAsset`打包到安装包(比如放到`Resources`目录),Unity不认`lua`后缀,这是Unity的规则。 如果你不打包到安装包,就没有后缀的限制:比如自行下载到某个目录(这也是热更的正确姿势),然后通过CustomLoader或者设置package.path去读这个目录。 那为啥xLua本身带的lua源码(包括示例)为什么都是txt结尾呢?因为xLua本身就一个库,不含下载功能,也不方便运行时去某个地方下载代码,通过TextAsset是较简单的方式。 ### Plugins源码在哪里可以找到,怎么使用? Plugins源码位于`xLua_Project_Root/build`下。 源码编译依赖cmake,安装cmake后执行make_xxxx_yyyy.zz即可,xxxx代表平台,比如ios,android等,yyyy是要集成的虚拟机,有lua53和luajit两者,zz是后缀,windows下是bat,其它平台是sh。 windows编译依赖Visual Studio 2015。 android编译在linux下执行,依赖NDK,并且需要把脚本中ANDROID_NDK指向NDK的安装目录。 ios和osx需要在mac下编译。 ### 报类似“xlua.access, no field __Hitfix0_Update”的错误怎么解决? 按[Hotfix操作指南](hotfix.html)一步步操作。 ### 报“please install the Tools” 没有把Tools安装到Assets平级目录,安装包,或者master下都能找到这个目录。 ### 报“This delegate/interface must add to CSharpCallLua : XXX”异常怎么解决? 在编辑器下xLua不生成代码都可以运行,出现这种提示,要么是该类型没加CSharpCallLua,要么是加之前生成过代码,没重新执行生成。 解决办法,确认XXX(类型名)加上CSharpCallLua后,清除代码后运行。 ### hotfix下怎么触发一个event 首先通过xlua.private_accessible开启私有成员访问。 跟着通过对象的"&事件名"字段调用delegate,例如self\['&MyEvent'\](),其中MyEvent是事件名。 ### 怎么对Unity Coroutine的实现函数打补丁? 见[Hotfix操作指南](hotfix.html)相应章节。 ### 支持NGUI(或者UGUI/DOTween等等)么? 支持,xLua最主要的特性是让你原来用C#写的地方可以换成用lua写,你C#能用的插件,基本都能用。 ### 如果需要调试,CustomLoader的filepath参数该如何处理? lua里头调用require 'a.b'时,CustomLoader会被调用,并传入字符串"a.b",你需要理解这字符串,(从文件/内存/网络等)加载好lua文件,返回两个东西,第一个是调试器可以理解的路径,比如:a/b.lua,这个通过设置ref类型的filepath参数返回,第二个是UTF8格式的源码的字节流(byte[]),通过返回值返回。 ### 什么是生成代码? xLua支持的lua和C#间交互技术之一,这种技术通过生成两者间的适配代码来实现交互,性能较好,是推荐的方式。 另一种交互技术是反射,这种方式对安装包的影响更少,可以在性能要求不高或者对安装包大小很敏感的场景下使用。 ### 改了接口后,之前生成的代码出现错误怎么办? 清除掉生成代码(执行“Clear Generated Code”菜单,如果你重启过,会找不到这个菜单,这时你可以手动删除整个生成代码目录),等编译完成后重新生成。 ### 应该什么时候生成代码? 开发期不建议生成代码,可以避免很多由于不一致导致的编译失败,以及生成代码本身的编译等待。 build手机版本前必须执行生成代码,建议做成自动化的。 做性能调优,性能测试前必须执行生成代码,因为生成和不生成性能的区别还是很大的。 ### CS名字空间下有所有C# API是不是很占内存? 由于用了lazyload,这个“有”只是个虚拟的概念,比如UnityEngine.GameObject,是访问第一次CS.UnityEngine.GameObject或者第一个实例往lua传送才加载该类型方法,属性等。 ### LuaCallSharp以及CSharpCallLua两种生成各在什么场景下用? 看调用者和被调用者,比如要在lua调用C#的GameObject.Find函数,或者调用gameobject的实例方法,属性等,GameObject类要加LuaCallSharp,而想把一个lua函数挂到UI回调,这是调用者是C#,被调用的是一个lua函数,所以回调声明的delegate要加CSharpCallLua。 有时会比较迷惑人,比如`List<int>.Find(Predicate<int> match)`的调用,`List<int>`当然是加LuaCallSharp,而`Predicate<int>`却要加CSharpCallLua,因为match的调用者在C#,被调用的是一个lua函数。 更无脑一点的方式是看到“This delegate/interface must add to CSharpCallLua : XXX”,就把XXX加到CSharpCallLua即可。 ### 值类型传递会有gc alloc么? 如果你使用的是delegate调用lua函数,或者用LuaTable、LuaFunction的无gc接口,或者数组的话,以下值类型都是没gc的: 1、所有的基本值类型(所有整数,所有浮点数,decimal); 2、所有的枚举类型; 3、字段只包含值类型的struct,可嵌套其它只包含值类型struct; 其中2、3需要把该类型加到GCOptimize。 ### 反射在ios下可用吗? ios下的限制有两个:1、没有jit;2、代码剪裁(stripping); 对于C#通过delegate或者interface调用lua,如果不生成代码是用反射的emit,这依赖jit,所以这目前只在编辑器可用。 对于lua调用C#,主要会被代码剪裁影响,这时你可以配置ReflectionUse(不要配LuaCallSharp),执行“Generate Code”,这时不会对该类生成封装代码,而是生成link.xml把该类配置为不剪裁。 简而言之,除了CSharpCallLua是必须的(这类生成代码往往不多),LuaCallSharp生成都可以改为用反射。 ### 支持泛化方法的调用么? 不直接支持,但能调用到。如果是静态方法,可以自己写个封装来实例化泛化方法。 如果是成员方法,xLua支持扩展方法,你可以添加一个扩展方法来实例化泛化方法。该扩展方法使用起来就和普通成员方法一样。 ```csharp // C# public static Button GetButton(this GameObject go) { return go.GetComponent<Button>(); } ``` ```lua -- lua local go = CS.UnityEngine.GameObject.Find("button") go:GetButton().onClick:AddListener(function() print('onClick') end) ``` ### 支持lua调用C#重载函数吗? 支持,但没有C#端支持的那么完善,比如重载方法void Foo(int a)和void Foo(short a),由于int和short都对应lua的number,是没法根据参数判断调用的是哪个重载。这时你可以借助扩展方法来为其中一个起一个别名。 ### 编辑器下运行正常,打包的时候生成代码报“没有某方法/属性/字段定义”怎么办? 往往是由于该方法/属性/字段是扩在条件编译里头,只在UNITY_EDITOR下有效,这是可以通过把这方法/属性/字段加到黑名单来解决,加了之后要等编译完成后重新执行代码生成。 ### this[string field]或者this[object field]操作符重载为什么在lua无法访问?(比如`Dictionary<string, xxx>`, `Dictionary<object, xxx>`在lua中无法通过dic['abc']或者dic.abc检索值) 在2.1.5~2.1.6版本把这个特性去掉,因为:1、这个特性会导致基类定义的方法、属性、字段等无法访问(比如Animation无法访问到GetComponent方法);2、key为当前类某方法、属性、字段的名字的数据无法检索,比如Dictionary类型,dic['TryGetValue']返回的是一个函数,指向Dictionary的TryGetValue方法。 建议直接方法该操作符的等效方法,比如Dictionary的TryGetValue,如果该方法没有提供,可以在C#那通过Extension method封装一个使用。 ### 有的Unity对象,在C#为null,在lua为啥不为nil呢?比如一个已经Destroy的GameObject 其实那C#对象并不为null,是UnityEngine.Object重载的==操作符,当一个对象被Destroy,未初始化等情况,obj == null返回true,但这C#对象并不为null,可以通过System.Object.ReferenceEquals(null, obj)来验证下。 对应这种情况,可以为UnityEngine.Object写一个扩展方法: ~~~csharp [LuaCallCSharp] [ReflectionUse] public static class UnityEngineObjectExtention { public static bool IsNull(this UnityEngine.Object o) // 或者名字叫IsDestroyed等等 { return o == null; } } ~~~ 然后在lua那你对所有UnityEngine.Object实例都使用IsNull判断 ~~~lua print(go:GetComponent('Animator'):IsNull()) ~~~ ### 泛型实例怎么构造 涉及的类型都在mscorlib,Assembly-CSharp程序集的话,泛型实例的构造和普通类型是一样的,都是CS.namespace.typename(),可能比较特殊的是typename的表达,泛型实例的typename的表达包含了标识符非法符号,最后一部分要换成["typename"],以`List<string>`为例 ~~~lua local lst = CS.System.Collections.Generic["List`1[System.String]"]() ~~~ 如果某个泛型实例的typename不确定,可以在C#测打印下typeof(不确定的类型).ToString() 如果涉及mscorlib,Assembly-CSharp程序集之外的类型的话,可以用C#的反射来做: ~~~lua local dic = CS.System.Activator.CreateInstance(CS.System.Type.GetType('System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[UnityEngine.Vector3, UnityEngine]],mscorlib')) dic:Add('a', CS.UnityEngine.Vector3(1, 2, 3)) print(dic:TryGetValue('a')) ~~~ ### 调用LuaEnv.Dispose时,报“try to dispose a LuaEnv with C# callback!”错是什么原因? 这是由于C#还存在指向lua虚拟机里头某个函数的delegate,为了防止业务在虚拟机释放后调用这些无效(因为其引用的lua函数所在虚拟机都释放了)delegate导致的异常甚至崩溃,做了这个检查。 怎么解决?释放这些delegate即可,所谓释放,在C#中,就是没有引用: 你是在C#通过LuaTable.Get获取并保存到对象成员,赋值该成员为null; 你是在lua那把lua函数注册到一些事件事件回调,反注册这些回调; 如果你是通过xlua.hotfix(class, method, func)注入到C#,则通过xlua.hotfix(class, method, nil)删除; 要注意以上操作在Dispose之前完成。 ### C#参数(或字段)类型是object时,传递整数默认是以long类型传递,如何指明其它类型?比如int 看[例子11](https://github.com/Tencent/xLua/blob/master/Assets/XLua/Examples/11_RawObject/RawObjectTest.cs)
xLua/docs/source/src/v1/guide/faq.md/0
{ "file_path": "xLua/docs/source/src/v1/guide/faq.md", "repo_id": "xLua", "token_count": 6694 }
2,132
@import "_settings" body,footer,header, h1, h2, h3, h4, h5, h6, hr, p, blockquote, dl, dt, dd, ul, ol, li, form, fieldset, legend, button, input, textarea, th, td margin 0 padding 0 text-align center -webkit-text-size-adjust none color: $main-color body,button, input, select, textarea, ol,p, blockquote, dl, dt, dd, ul, ol, li, form, fieldset, legend, button, input, textarea, th, td outline none font 1em "Helvetica Neue","Helvetica","Lucida Grande","Arial","Hiragino Sans GB","Microsoft Yahei","WenQuanYi Micro Hei","sans-serif",arial,sans-serif; text-align left color: $main-color body background-color white background-attachment fixed ul, ol list-style none a text-decoration none transition all 0.5s -moz-transition all 0.5s -webkit-transition all 0.5s -o-transition all 0.5s cursor pointer color: $main-color text-decoration none a:hover text-decoration underline outline 0 color: $main-color .abs position absolute .clear:after content "." display block height 0 clear both visibility hidden .clear zoom 1 button border none html overflow-x hidden body min-width 20rem overflow-x hidden .border padding-left 1rem padding-right 1rem
xLua/docs/source/themes/catlib/source/css/_common.styl/0
{ "file_path": "xLua/docs/source/themes/catlib/source/css/_common.styl", "repo_id": "xLua", "token_count": 531 }
2,133
/* (C) 2019 David Lettier lettier.com */ #version 150 uniform sampler2D colorTexture; uniform vec2 parameters; out vec4 fragColor; void main() { vec2 texSize = textureSize(colorTexture, 0).xy; vec2 texCoord = gl_FragCoord.xy / texSize; fragColor = texture(colorTexture, texCoord); int size = int(parameters.x); if (size <= 0) { return; } float separation = parameters.y; separation = max(separation, 1); fragColor.rgb = vec3(0); float count = 0.0; for (int i = -size; i <= size; ++i) { for (int j = -size; j <= size; ++j) { fragColor.rgb += texture ( colorTexture , ( gl_FragCoord.xy + (vec2(i, j) * separation) ) / texSize ).rgb; count += 1.0; } } fragColor.rgb /= count; }
3d-game-shaders-for-beginners/demonstration/shaders/fragment/box-blur.frag/0
{ "file_path": "3d-game-shaders-for-beginners/demonstration/shaders/fragment/box-blur.frag", "repo_id": "3d-game-shaders-for-beginners", "token_count": 377 }
0
/* (C) 2019 David Lettier lettier.com */ #version 150 #define MAX_SHININESS 127.75 uniform struct { vec3 specular ; float shininess ; } p3d_Material; out vec4 fragColor; void main() { fragColor = vec4 ( p3d_Material.specular , clamp(p3d_Material.shininess / MAX_SHININESS, 0.0, 1.0) ); }
3d-game-shaders-for-beginners/demonstration/shaders/fragment/material-specular.frag/0
{ "file_path": "3d-game-shaders-for-beginners/demonstration/shaders/fragment/material-specular.frag", "repo_id": "3d-game-shaders-for-beginners", "token_count": 149 }
1
/* (C) 2019 David Lettier lettier.com */ #version 150 #define NUMBER_OF_LIGHTS 4 uniform mat4 p3d_ModelViewMatrix; uniform mat4 p3d_ProjectionMatrix; uniform mat3 p3d_NormalMatrix; uniform struct p3d_LightSourceParameters { vec4 color ; vec4 ambient ; vec4 diffuse ; vec4 specular ; vec4 position ; vec3 spotDirection ; float spotExponent ; float spotCutoff ; float spotCosCutoff ; float constantAttenuation ; float linearAttenuation ; float quadraticAttenuation ; vec3 attenuation ; sampler2DShadow shadowMap ; mat4 shadowViewMatrix ; } p3d_LightSource[NUMBER_OF_LIGHTS]; in vec4 p3d_Vertex; in vec3 p3d_Normal; in vec4 p3d_Color; in vec2 p3d_MultiTexCoord0; in vec2 p3d_MultiTexCoord1; in vec3 p3d_Binormal; in vec3 p3d_Tangent; out vec4 vertexPosition; out vec4 vertexColor; out vec3 vertexNormal; out vec3 binormal; out vec3 tangent; out vec2 normalCoord; out vec2 diffuseCoord; out vec4 vertexInShadowSpaces[NUMBER_OF_LIGHTS]; void main() { vertexColor = p3d_Color; vertexPosition = p3d_ModelViewMatrix * p3d_Vertex; vertexNormal = normalize(p3d_NormalMatrix * p3d_Normal); binormal = normalize(p3d_NormalMatrix * p3d_Binormal); tangent = normalize(p3d_NormalMatrix * p3d_Tangent); normalCoord = p3d_MultiTexCoord0; diffuseCoord = p3d_MultiTexCoord1; for (int i = 0; i < p3d_LightSource.length(); ++i) { vertexInShadowSpaces[i] = p3d_LightSource[i].shadowViewMatrix * vertexPosition; } gl_Position = p3d_ProjectionMatrix * vertexPosition; }
3d-game-shaders-for-beginners/demonstration/shaders/vertex/base.vert/0
{ "file_path": "3d-game-shaders-for-beginners/demonstration/shaders/vertex/base.vert", "repo_id": "3d-game-shaders-for-beginners", "token_count": 606 }
2
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang=""> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" /> <meta name="description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta property="og:title" content="Depth Of Field | 3D Game Shaders For Beginners" /> <meta property="og:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta property="og:image" content="https://i.imgur.com/JIDwVTm.png" /> <meta name="twitter:title" content="Depth Of Field | 3D Game Shaders For Beginners" /> <meta name="twitter:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta name="twitter:image" content="https://i.imgur.com/JIDwVTm.png" /> <meta name="twitter:card" content="summary_large_image" /> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <meta name="author" content="David Lettier" /> <title>Depth Of Field | 3D Game Shaders For Beginners</title> <style> code{white-space: pre-wrap;} span.smallcaps{font-variant: small-caps;} span.underline{text-decoration: underline;} div.column{display: inline-block; vertical-align: top; width: 50%;} </style> <style> code.sourceCode > span { display: inline-block; line-height: 1.25; } code.sourceCode > span { color: inherit; text-decoration: inherit; } code.sourceCode > span:empty { height: 1.2em; } .sourceCode { overflow: visible; } code.sourceCode { white-space: pre; position: relative; } div.sourceCode { margin: 1em 0; } pre.sourceCode { margin: 0; } @media screen { div.sourceCode { overflow: auto; } } @media print { code.sourceCode { white-space: pre-wrap; } code.sourceCode > span { text-indent: -5em; padding-left: 5em; } } pre.numberSource code { counter-reset: source-line 0; } pre.numberSource code > span { position: relative; left: -4em; counter-increment: source-line; } pre.numberSource code > span > a:first-child::before { content: counter(source-line); position: relative; left: -1em; text-align: right; vertical-align: baseline; border: none; display: inline-block; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; padding: 0 4px; width: 4em; background-color: #232629; color: #7a7c7d; } pre.numberSource { margin-left: 3em; border-left: 1px solid #7a7c7d; padding-left: 4px; } div.sourceCode { color: #cfcfc2; background-color: #232629; } @media screen { code.sourceCode > span > a:first-child::before { text-decoration: underline; } } code span. { color: #cfcfc2; } /* Normal */ code span.al { color: #95da4c; } /* Alert */ code span.an { color: #3f8058; } /* Annotation */ code span.at { color: #2980b9; } /* Attribute */ code span.bn { color: #f67400; } /* BaseN */ code span.bu { color: #7f8c8d; } /* BuiltIn */ code span.cf { color: #fdbc4b; } /* ControlFlow */ code span.ch { color: #3daee9; } /* Char */ code span.cn { color: #27aeae; } /* Constant */ code span.co { color: #7a7c7d; } /* Comment */ code span.cv { color: #7f8c8d; } /* CommentVar */ code span.do { color: #a43340; } /* Documentation */ code span.dt { color: #2980b9; } /* DataType */ code span.dv { color: #f67400; } /* DecVal */ code span.er { color: #da4453; } /* Error */ code span.ex { color: #0099ff; } /* Extension */ code span.fl { color: #f67400; } /* Float */ code span.fu { color: #8e44ad; } /* Function */ code span.im { color: #27ae60; } /* Import */ code span.in { color: #c45b00; } /* Information */ code span.kw { color: #cfcfc2; } /* Keyword */ code span.op { color: #cfcfc2; } /* Operator */ code span.ot { color: #27ae60; } /* Other */ code span.pp { color: #27ae60; } /* Preprocessor */ code span.re { color: #2980b9; } /* RegionMarker */ code span.sc { color: #3daee9; } /* SpecialChar */ code span.ss { color: #da4453; } /* SpecialString */ code span.st { color: #f44f4f; } /* String */ code span.va { color: #27aeae; } /* Variable */ code span.vs { color: #da4453; } /* VerbatimString */ code span.wa { color: #da4453; } /* Warning */ </style> <!--[if lt IE 9]> <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script> <![endif]--> <link rel="stylesheet" href="style.css" /> </head> <body> <p><a href="outlining.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="posterization.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p> <h1 id="3d-game-shaders-for-beginners">3D Game Shaders For Beginners</h1> <h2 id="depth-of-field">Depth Of Field</h2> <p align="center"> <img src="https://i.imgur.com/DEa77Bh.gif" alt="Depth Of Field" title="Depth Of Field"> </p> <p>Like <a href="ssao.html">SSAO</a>, depth of field is an effect you can't live without once you've used it. Artistically, you can use it to draw your viewer's eye to a certain subject. But in general, depth of field adds a lot of realism for a little bit of effort.</p> <h3 id="in-focus">In Focus</h3> <p>The first step is to render your scene completely in focus. Be sure to render this into a framebuffer texture. This will be one of the inputs to the depth of field shader.</p> <h3 id="out-of-focus">Out Of Focus</h3> <p>The second step is to blur the scene as if it was completely out of focus. Like bloom and SSAO, you can use a <a href="blur.html#box-blur">box blur</a>. Be sure to render this out-of-focus-scene into a framebuffer texture. This will be one of the inputs to the depth of field shader.</p> <h4 id="bokeh">Bokeh</h4> <p align="center"> <img src="https://i.imgur.com/aQ9Ga8J.gif" alt="Bokeh" title="Bokeh"> </p> <p>For a great bokeh effect, dilate the out of focus texture and use that as the out of focus input. See <a href="dilation.html">dilation</a> for more details.</p> <h3 id="mixing">Mixing</h3> <div class="sourceCode" id="cb1"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb1-1"><a href="#cb1-1"></a> <span class="co">// ...</span></span> <span id="cb1-2"><a href="#cb1-2"></a></span> <span id="cb1-3"><a href="#cb1-3"></a> <span class="dt">float</span> minDistance = <span class="fl">1.0</span>;</span> <span id="cb1-4"><a href="#cb1-4"></a> <span class="dt">float</span> maxDistance = <span class="fl">3.0</span>;</span> <span id="cb1-5"><a href="#cb1-5"></a></span> <span id="cb1-6"><a href="#cb1-6"></a> <span class="co">// ...</span></span></code></pre></div> <p>Feel free to tweak these two parameters. All positions at or below <code>minDistance</code> will be completely in focus. All positions at or beyond <code>maxDistance</code> will be completely out of focus.</p> <div class="sourceCode" id="cb2"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb2-1"><a href="#cb2-1"></a> <span class="co">// ...</span></span> <span id="cb2-2"><a href="#cb2-2"></a></span> <span id="cb2-3"><a href="#cb2-3"></a> vec4 focusColor = texture(focusTexture, texCoord);</span> <span id="cb2-4"><a href="#cb2-4"></a> vec4 outOfFocusColor = texture(outOfFocusTexture, texCoord);</span> <span id="cb2-5"><a href="#cb2-5"></a></span> <span id="cb2-6"><a href="#cb2-6"></a> <span class="co">// ...</span></span></code></pre></div> <p>You'll need the in focus and out of focus colors.</p> <div class="sourceCode" id="cb3"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb3-1"><a href="#cb3-1"></a> <span class="co">// ...</span></span> <span id="cb3-2"><a href="#cb3-2"></a></span> <span id="cb3-3"><a href="#cb3-3"></a> vec4 position = texture(positionTexture, texCoord);</span> <span id="cb3-4"><a href="#cb3-4"></a></span> <span id="cb3-5"><a href="#cb3-5"></a> <span class="co">// ...</span></span></code></pre></div> <p>You'll also need the vertex position in view space. You can reuse the position framebuffer texture you used for <a href="ssao.html#vertex-positions">SSAO</a>.</p> <div class="sourceCode" id="cb4"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb4-1"><a href="#cb4-1"></a> <span class="co">// ...</span></span> <span id="cb4-2"><a href="#cb4-2"></a></span> <span id="cb4-3"><a href="#cb4-3"></a> vec4 focusPoint = texture(positionTexture, mouseFocusPoint);</span> <span id="cb4-4"><a href="#cb4-4"></a></span> <span id="cb4-5"><a href="#cb4-5"></a> <span class="co">// ...</span></span></code></pre></div> <p>The focus point is a position somewhere in your scene. All of the points in your scene are measured from the focus point.</p> <p>Choosing the focus point is up to you. The demo uses the scene position directly under the mouse when clicking the middle mouse button. However, it could be a constant distance from the camera or a static position.</p> <p align="center"> <img src="https://i.imgur.com/idDZr62.png" alt="smoothstep" title="smoothstep"> </p> <div class="sourceCode" id="cb5"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb5-1"><a href="#cb5-1"></a> <span class="co">// ...</span></span> <span id="cb5-2"><a href="#cb5-2"></a></span> <span id="cb5-3"><a href="#cb5-3"></a> <span class="dt">float</span> blur =</span> <span id="cb5-4"><a href="#cb5-4"></a> smoothstep</span> <span id="cb5-5"><a href="#cb5-5"></a> ( minDistance</span> <span id="cb5-6"><a href="#cb5-6"></a> , maxDistance</span> <span id="cb5-7"><a href="#cb5-7"></a> , abs(position.y - focusPoint.y)</span> <span id="cb5-8"><a href="#cb5-8"></a> );</span> <span id="cb5-9"><a href="#cb5-9"></a></span> <span id="cb5-10"><a href="#cb5-10"></a> <span class="co">// ...</span></span></code></pre></div> <p><code>smoothstep</code> returns values from zero to one. The <code>minDistance</code> is the left-most edge. Any position less than the minimum distance, from the focus point, will be in focus or have a blur of zero. The <code>maxDistance</code> is the right-most edge. Any position greater than the maximum distance, from the focus point, will be out of focus or have a blur or one. For distances between the edges, blur will be between zero and one. These values are interpolated along a s-shaped curve.</p> <div class="sourceCode" id="cb6"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb6-1"><a href="#cb6-1"></a></span> <span id="cb6-2"><a href="#cb6-2"></a> <span class="co">// ...</span></span> <span id="cb6-3"><a href="#cb6-3"></a></span> <span id="cb6-4"><a href="#cb6-4"></a> fragColor = mix(focusColor, outOfFocusColor, blur);</span> <span id="cb6-5"><a href="#cb6-5"></a></span> <span id="cb6-6"><a href="#cb6-6"></a> <span class="co">// ...</span></span></code></pre></div> <p>The <code>fragColor</code> is a mixture of the in focus and out of focus color. The closer <code>blur</code> is to one, the more it will use the <code>outOfFocusColor</code>. Zero <code>blur</code> means this fragment is entirely in focus. At <code>blur &gt;= 1</code>, this fragment is completely out of focus.</p> <h3 id="source">Source</h3> <ul> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/src/main.cxx" target="_blank" rel="noopener noreferrer">main.cxx</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/vertex/basic.vert" target="_blank" rel="noopener noreferrer">basic.vert</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/fragment/box-blur.frag" target="_blank" rel="noopener noreferrer">box-blur.frag</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/fragment/depth-of-field.frag" target="_blank" rel="noopener noreferrer">depth-of-field.frag</a></li> </ul> <h2 id="copyright">Copyright</h2> <p>(C) 2019 David Lettier <br> <a href="https://www.lettier.com">lettier.com</a></p> <p><a href="outlining.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="posterization.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p> </body> </html>
3d-game-shaders-for-beginners/docs/depth-of-field.html/0
{ "file_path": "3d-game-shaders-for-beginners/docs/depth-of-field.html", "repo_id": "3d-game-shaders-for-beginners", "token_count": 5159 }
3
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang=""> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" /> <meta name="description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta property="og:title" content="Pixelization | 3D Game Shaders For Beginners" /> <meta property="og:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta property="og:image" content="https://i.imgur.com/JIDwVTm.png" /> <meta name="twitter:title" content="Pixelization | 3D Game Shaders For Beginners" /> <meta name="twitter:description" content="Interested in adding textures, lighting, shadows, normal maps, glowing objects, ambient occlusion, reflections, refractions, and more to your 3D game? Great! 3D Game Shaders For Beginners is a collection of shading techniques that will take your game visuals to new heights." /> <meta name="twitter:image" content="https://i.imgur.com/JIDwVTm.png" /> <meta name="twitter:card" content="summary_large_image" /> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <meta name="author" content="David Lettier" /> <title>Pixelization | 3D Game Shaders For Beginners</title> <style> code{white-space: pre-wrap;} span.smallcaps{font-variant: small-caps;} span.underline{text-decoration: underline;} div.column{display: inline-block; vertical-align: top; width: 50%;} </style> <style> code.sourceCode > span { display: inline-block; line-height: 1.25; } code.sourceCode > span { color: inherit; text-decoration: inherit; } code.sourceCode > span:empty { height: 1.2em; } .sourceCode { overflow: visible; } code.sourceCode { white-space: pre; position: relative; } div.sourceCode { margin: 1em 0; } pre.sourceCode { margin: 0; } @media screen { div.sourceCode { overflow: auto; } } @media print { code.sourceCode { white-space: pre-wrap; } code.sourceCode > span { text-indent: -5em; padding-left: 5em; } } pre.numberSource code { counter-reset: source-line 0; } pre.numberSource code > span { position: relative; left: -4em; counter-increment: source-line; } pre.numberSource code > span > a:first-child::before { content: counter(source-line); position: relative; left: -1em; text-align: right; vertical-align: baseline; border: none; display: inline-block; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; padding: 0 4px; width: 4em; background-color: #232629; color: #7a7c7d; } pre.numberSource { margin-left: 3em; border-left: 1px solid #7a7c7d; padding-left: 4px; } div.sourceCode { color: #cfcfc2; background-color: #232629; } @media screen { code.sourceCode > span > a:first-child::before { text-decoration: underline; } } code span. { color: #cfcfc2; } /* Normal */ code span.al { color: #95da4c; } /* Alert */ code span.an { color: #3f8058; } /* Annotation */ code span.at { color: #2980b9; } /* Attribute */ code span.bn { color: #f67400; } /* BaseN */ code span.bu { color: #7f8c8d; } /* BuiltIn */ code span.cf { color: #fdbc4b; } /* ControlFlow */ code span.ch { color: #3daee9; } /* Char */ code span.cn { color: #27aeae; } /* Constant */ code span.co { color: #7a7c7d; } /* Comment */ code span.cv { color: #7f8c8d; } /* CommentVar */ code span.do { color: #a43340; } /* Documentation */ code span.dt { color: #2980b9; } /* DataType */ code span.dv { color: #f67400; } /* DecVal */ code span.er { color: #da4453; } /* Error */ code span.ex { color: #0099ff; } /* Extension */ code span.fl { color: #f67400; } /* Float */ code span.fu { color: #8e44ad; } /* Function */ code span.im { color: #27ae60; } /* Import */ code span.in { color: #c45b00; } /* Information */ code span.kw { color: #cfcfc2; } /* Keyword */ code span.op { color: #cfcfc2; } /* Operator */ code span.ot { color: #27ae60; } /* Other */ code span.pp { color: #27ae60; } /* Preprocessor */ code span.re { color: #2980b9; } /* RegionMarker */ code span.sc { color: #3daee9; } /* SpecialChar */ code span.ss { color: #da4453; } /* SpecialString */ code span.st { color: #f44f4f; } /* String */ code span.va { color: #27aeae; } /* Variable */ code span.vs { color: #da4453; } /* VerbatimString */ code span.wa { color: #da4453; } /* Warning */ </style> <!--[if lt IE 9]> <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv-printshiv.min.js"></script> <![endif]--> <link rel="stylesheet" href="style.css" /> </head> <body> <p><a href="posterization.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="sharpen.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p> <h1 id="3d-game-shaders-for-beginners">3D Game Shaders For Beginners</h1> <h2 id="pixelization">Pixelization</h2> <p align="center"> <img src="https://i.imgur.com/IbnyYZN.gif" alt="Pixelization" title="Pixelization"> </p> <p>Pixelizing your 3D game can give it a interesting look and possibly save you time by not having to create all of the pixel art by hand. Combine it with the posterization for a true retro look.</p> <div class="sourceCode" id="cb1"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb1-1"><a href="#cb1-1"></a> <span class="co">// ...</span></span> <span id="cb1-2"><a href="#cb1-2"></a></span> <span id="cb1-3"><a href="#cb1-3"></a> <span class="dt">int</span> pixelSize = <span class="dv">5</span>;</span> <span id="cb1-4"><a href="#cb1-4"></a></span> <span id="cb1-5"><a href="#cb1-5"></a> <span class="co">// ...</span></span></code></pre></div> <p>Feel free to adjust the pixel size. The bigger the pixel size, the blockier the image will be.</p> <p align="center"> <img src="https://i.imgur.com/WF5MmM0.gif" alt="Pixelization Process" title="Pixelization Process"> </p> <div class="sourceCode" id="cb2"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb2-1"><a href="#cb2-1"></a> <span class="co">// ...</span></span> <span id="cb2-2"><a href="#cb2-2"></a></span> <span id="cb2-3"><a href="#cb2-3"></a> <span class="dt">float</span> x = <span class="dt">int</span>(gl_FragCoord.x) % pixelSize;</span> <span id="cb2-4"><a href="#cb2-4"></a> <span class="dt">float</span> y = <span class="dt">int</span>(gl_FragCoord.y) % pixelSize;</span> <span id="cb2-5"><a href="#cb2-5"></a></span> <span id="cb2-6"><a href="#cb2-6"></a> x = floor(pixelSize / <span class="fl">2.0</span>) - x;</span> <span id="cb2-7"><a href="#cb2-7"></a> y = floor(pixelSize / <span class="fl">2.0</span>) - y;</span> <span id="cb2-8"><a href="#cb2-8"></a></span> <span id="cb2-9"><a href="#cb2-9"></a> x = gl_FragCoord.x + x;</span> <span id="cb2-10"><a href="#cb2-10"></a> y = gl_FragCoord.y + y;</span> <span id="cb2-11"><a href="#cb2-11"></a></span> <span id="cb2-12"><a href="#cb2-12"></a> <span class="co">// ...</span></span></code></pre></div> <p>The technique works by mapping each fragment to the center of its closest, non-overlapping pixel-sized window. These windows are laid out in a grid over the input texture. The center-of-the-window fragments determine the color for the other fragments in their window.</p> <div class="sourceCode" id="cb3"><pre class="sourceCode c"><code class="sourceCode c"><span id="cb3-1"><a href="#cb3-1"></a> <span class="co">// ...</span></span> <span id="cb3-2"><a href="#cb3-2"></a></span> <span id="cb3-3"><a href="#cb3-3"></a> fragColor = texture(colorTexture, vec2(x, y) / texSize);</span> <span id="cb3-4"><a href="#cb3-4"></a></span> <span id="cb3-5"><a href="#cb3-5"></a> <span class="co">// ...</span></span></code></pre></div> <p>Once you have determined the correct fragment coordinate to use, pull its color from the input texture and assign that to the fragment color.</p> <h3 id="source">Source</h3> <ul> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/src/main.cxx" target="_blank" rel="noopener noreferrer">main.cxx</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/vertex/basic.vert" target="_blank" rel="noopener noreferrer">basic.vert</a></li> <li><a href="https://github.com/lettier/3d-game-shaders-for-beginners/blob/master/demonstration/shaders/fragment/pixelize.frag" target="_blank" rel="noopener noreferrer">pixelize.frag</a></li> </ul> <h2 id="copyright">Copyright</h2> <p>(C) 2019 David Lettier <br> <a href="https://www.lettier.com">lettier.com</a></p> <p><a href="posterization.html"><span class="emoji" data-emoji="arrow_backward">◀️</span></a> <a href="index.html"><span class="emoji" data-emoji="arrow_double_up">⏫</span></a> <a href="#"><span class="emoji" data-emoji="arrow_up_small">🔼</span></a> <a href="#copyright"><span class="emoji" data-emoji="arrow_down_small">🔽</span></a> <a href="sharpen.html"><span class="emoji" data-emoji="arrow_forward">▶️</span></a></p> </body> </html>
3d-game-shaders-for-beginners/docs/pixelization.html/0
{ "file_path": "3d-game-shaders-for-beginners/docs/pixelization.html", "repo_id": "3d-game-shaders-for-beginners", "token_count": 3924 }
4
[:arrow_backward:](setup.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](running-the-demo.md) # 3D Game Shaders For Beginners ## Building The Demo <p align="center"> <img src="https://i.imgur.com/PQcDnIu.gif" alt="Building The Demo" title="Building The Demo"> </p> Before you can try out the demo program, you'll have to build the example code first. ### Dependencies Before you can compile the example code, you'll need to install [Panda3D](https://www.panda3d.org/) for your platform. Panda3D is available for Linux, Mac, and Windows. ### Linux Start by [installing](https://www.panda3d.org/manual/?title=Installing_Panda3D_in_Linux) the [Panda3D SDK](https://www.panda3d.org/download/sdk-1-10-9/) for your distribution. Make sure to locate where the Panda3D headers and libraries are. The headers and libraries are most likely in `/usr/include/panda3d/` and `/usr/lib/panda3d/` respectively. Next clone this repository and change directory into it. ```bash git clone https://github.com/lettier/3d-game-shaders-for-beginners.git cd 3d-game-shaders-for-beginners/demonstration ``` Now compile the source code into an object file. ```bash g++ \ -c src/main.cxx \ -o 3d-game-shaders-for-beginners.o \ -std=gnu++11 \ -O2 \ -I/path/to/python/include/ \ -I/path/to/panda3d/include/ ``` With the object file created, create the executable by linking the object file to its dependencies. ```bash g++ \ 3d-game-shaders-for-beginners.o \ -o 3d-game-shaders-for-beginners \ -L/path/to/panda3d/lib \ -lp3framework \ -lpanda \ -lpandafx \ -lpandaexpress \ -lpandaphysics \ -lp3dtoolconfig \ -lp3dtool \ -lpthread ``` For more help, see the [Panda3D manual](https://www.panda3d.org/manual/?title=How_to_compile_a_C++_Panda3D_program_on_Linux). ### Mac Start by installing the [Panda3D SDK](https://www.panda3d.org/download/sdk-1-10-9/) for Mac. Make sure to locate where the Panda3D headers and libraries are. Next clone this repository and change directory into it. ```bash git clone https://github.com/lettier/3d-game-shaders-for-beginners.git cd 3d-game-shaders-for-beginners ``` Now compile the source code into an object file. You'll have to find where the Python 2.7 and Panda3D include directories are. ```bash clang++ \ -c main.cxx \ -o 3d-game-shaders-for-beginners.o \ -std=gnu++11 \ -g \ -O2 \ -I/path/to/python/include/ \ -I/path/to/panda3d/include/ ``` With the object file created, create the executable by linking the object file to its dependencies. You'll need to track down where the Panda3D libraries are located. ```bash clang++ \ 3d-game-shaders-for-beginners.o \ -o 3d-game-shaders-for-beginners \ -L/path/to/panda3d/lib \ -lp3framework \ -lpanda \ -lpandafx \ -lpandaexpress \ -lpandaphysics \ -lp3dtoolconfig \ -lp3dtool \ -lpthread ``` For more help, see the [Panda3D manual](https://www.panda3d.org/manual/?title=How_to_compile_a_C++_Panda3D_program_on_macOS). ### Windows Start by [installing](https://www.panda3d.org/manual/?title=Installing_Panda3D_in_Windows) the [Panda3D SDK](https://www.panda3d.org/download/sdk-1-10-9/) for Windows. Make sure to locate where the Panda3D headers and libraries are. Next clone this repository and change directory into it. ```bash git clone https://github.com/lettier/3d-game-shaders-for-beginners.git cd 3d-game-shaders-for-beginners ``` For more help, see the [Panda3D manual](https://www.panda3d.org/manual/?title=Running_your_Program&language=cxx). ## Copyright (C) 2019 David Lettier <br> [lettier.com](https://www.lettier.com) [:arrow_backward:](setup.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](running-the-demo.md)
3d-game-shaders-for-beginners/sections/building-the-demo.md/0
{ "file_path": "3d-game-shaders-for-beginners/sections/building-the-demo.md", "repo_id": "3d-game-shaders-for-beginners", "token_count": 1450 }
5
[:arrow_backward:](cel-shading.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](deferred-rendering.md) # 3D Game Shaders For Beginners ## Normal Mapping <p align="center"> <img src="https://i.imgur.com/M4eHo9I.gif" alt="Normal Mapping" title="Normal Mapping"> </p> Normal mapping allows you to add surface details without adding any geometry. Typically, in a modeling program like Blender, you create a high poly and a low poly version of your mesh. You take the vertex normals from the high poly mesh and bake them into a texture. This texture is the normal map. Then inside the fragment shader, you replace the low poly mesh's vertex normals with the high poly mesh's normals you baked into the normal map. Now when you light your mesh, it will appear to have more polygons than it really has. This will keep your FPS high while at the same time retain most of the details from the high poly version. <p align="center"> <img src="https://i.imgur.com/nSY9AW4.gif" alt="From high to low poly with normal mapping." title="From high to low poly with normal mapping."> </p> Here you see the progression from the high poly model to the low poly model to the low poly model with the normal map applied. <p align="center"> <img src="https://i.imgur.com/jvkRPE7.gif" alt="Normal Map Illusion" title="Normal Map Illusion"> </p> Keep in mind though, normal mapping is only an illusion. After a certain angle, the surface will look flat again. ### Vertex ```c // ... uniform mat3 p3d_NormalMatrix; // ... in vec3 p3d_Normal; // ... in vec3 p3d_Binormal; in vec3 p3d_Tangent; // ... vertexNormal = normalize(p3d_NormalMatrix * p3d_Normal); binormal = normalize(p3d_NormalMatrix * p3d_Binormal); tangent = normalize(p3d_NormalMatrix * p3d_Tangent); // ... ``` Starting in the vertex shader, you'll need to output to the fragment shader the normal vector, binormal vector, and the tangent vector. These vectors are used, in the fragment shader, to transform the normal map normal from tangent space to view space. `p3d_NormalMatrix` transforms the vertex normal, binormal, and tangent vectors to view space. Remember that in view space, all of the coordinates are relative to the camera's position. <blockquote> [p3d_NormalMatrix] is the upper 3x3 of the inverse transpose of the ModelViewMatrix. It is used to transform the normal vector into view-space coordinates. <br> <br> <footer> <a href="http://www.panda3d.org/manual/?title=List_of_GLSL_Shader_Inputs">Source</a> </footer> </blockquote> ```c // ... in vec2 p3d_MultiTexCoord0; // ... out vec2 normalCoord; // ... normalCoord = p3d_MultiTexCoord0; // ... ``` <p align="center"> <img src="https://i.imgur.com/tLIA6Hu.gif" alt="Normal Maps" title="Normal Maps"> </p> You'll also need to output, to the fragment shader, the UV coordinates for the normal map. ### Fragment Recall that the vertex normal was used to calculate the lighting. However, the normal map provides us with different normals to use when calculating the lighting. In the fragment shader, you need to swap out the vertex normals for the normals found in the normal map. ```c // ... uniform sampler2D p3d_Texture1; // ... in vec2 normalCoord; // ... /* Find */ vec4 normalTex = texture(p3d_Texture1, normalCoord); // ... ``` Using the normal map coordinates the vertex shader sent, pull out the normal from the normal map. ```c // ... vec3 normal; // ... /* Unpack */ normal = normalize ( normalTex.rgb * 2.0 - 1.0 ); // ... ``` Earlier I showed how the normals are mapped to colors to create the normal map. Now this process needs to be reversed so you can get back the original normals that were baked into the map. ```c (r, g, b) = ( r * 2 - 1 , g * 2 - 1 , b * 2 - 1 ) = (x, y, z) ``` Here's the process for unpacking the normals from the normal map. ```c // ... /* Transform */ normal = normalize ( mat3 ( tangent , binormal , vertexNormal ) * normal ); // ... ``` The normals you get back from the normal map are typically in tangent space. They could be in another space, however. For example, Blender allows you to bake the normals in tangent, object, world, or camera space. <p align="center"> <img src="https://i.imgur.com/EzHJPd4.gif" alt="Replacing the vertex normals with the normal map normals." title="Replacing the vertex normals with the normal map normals."> </p> To take the normal map normal from tangent space to view pace, construct a three by three matrix using the tangent, binormal, and vertex normal vectors. Multiply the normal by this matrix and be sure to normalize it. At this point, you're done. The rest of the lighting calculations are the same. ### Source - [main.cxx](../demonstration/src/main.cxx) - [base.vert](../demonstration/shaders/vertex/base.vert) - [base.frag](../demonstration/shaders/fragment/base.frag) ## Copyright (C) 2019 David Lettier <br> [lettier.com](https://www.lettier.com) [:arrow_backward:](cel-shading.md) [:arrow_double_up:](../README.md) [:arrow_up_small:](#) [:arrow_down_small:](#copyright) [:arrow_forward:](deferred-rendering.md)
3d-game-shaders-for-beginners/sections/normal-mapping.md/0
{ "file_path": "3d-game-shaders-for-beginners/sections/normal-mapping.md", "repo_id": "3d-game-shaders-for-beginners", "token_count": 1808 }
6
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef air_VehicleSimApiBase_hpp #define air_VehicleSimApiBase_hpp #include "common/CommonStructs.hpp" #include "common/UpdatableObject.hpp" #include "common/ImageCaptureBase.hpp" #include "physics/Kinematics.hpp" #include "physics/Environment.hpp" #include "common/AirSimSettings.hpp" namespace msr { namespace airlib { class VehicleSimApiBase : public msr::airlib::UpdatableObject { public: virtual ~VehicleSimApiBase() = default; virtual void update() override { UpdatableObject::update(); } //this method is called at every render tick when we want to transfer state from //physics engine to render engine. As physics engine is halted while //this happens, this method should do minimal processing virtual void updateRenderedState(float dt) { unused(dt); //derived class should override if needed } //called when render changes are required at every render tick virtual void updateRendering(float dt) { unused(dt); //derived class should override if needed } virtual const ImageCaptureBase* getImageCapture() const = 0; virtual ImageCaptureBase* getImageCapture() { return const_cast<ImageCaptureBase*>(static_cast<const VehicleSimApiBase*>(this)->getImageCapture()); } virtual void initialize() = 0; virtual bool testLineOfSightToPoint(const GeoPoint& point) const = 0; virtual Pose getPose() const = 0; virtual void setPose(const Pose& pose, bool ignore_collision) = 0; virtual const Kinematics::State* getGroundTruthKinematics() const = 0; virtual void setKinematics(const Kinematics::State& state, bool ignore_collision) = 0; virtual const msr::airlib::Environment* getGroundTruthEnvironment() const = 0; virtual CollisionInfo getCollisionInfo() const = 0; virtual CollisionInfo getCollisionInfoAndReset() = 0; virtual int getRemoteControlID() const = 0; //which RC to use, 0 is first one, -1 means disable RC (use keyborad) virtual RCData getRCData() const = 0; //get reading from RC from simulator's host OS virtual std::string getVehicleName() const = 0; virtual std::string getRecordFileLine(bool is_header_line) const = 0; virtual void toggleTrace() = 0; virtual void setTraceLine(const std::vector<float>& color_rgba, float thickness) = 0; //use pointer here because of derived classes for VehicleSetting const AirSimSettings::VehicleSetting* getVehicleSetting() const { return AirSimSettings::singleton().getVehicleSetting(getVehicleName()); } }; } } //namespace #endif
AirSim/AirLib/include/api/VehicleSimApiBase.hpp/0
{ "file_path": "AirSim/AirLib/include/api/VehicleSimApiBase.hpp", "repo_id": "AirSim", "token_count": 1070 }
7
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef common_utils_LogFileWriter_hpp #define common_utils_LogFileWriter_hpp #include <iostream> #include <fstream> #include "common/Common.hpp" namespace msr { namespace airlib { class LogFileWriter { public: LogFileWriter() { } LogFileWriter(const string& file_name, bool enabled = true) { open(file_name, enabled); } ~LogFileWriter() { close(); } void open(const string& file_name, bool enabled = true) { close(); file_name_ = file_name; enabled_ = enabled; if (enabled_) log_file_ = std::ofstream(file_name); } void close() { if (log_file_.is_open()) log_file_.close(); } template <typename T> void write(const T& val) { if (enabled_) log_file_ << val << "\t"; } void write(const Vector3r& vec) { if (enabled_) log_file_ << vec.x() << "\t" << vec.y() << "\t" << vec.z() << "\t"; } void write(const Quaternionr& q) { if (enabled_) { real_T p, r, y; VectorMath::toEulerianAngle(q, p, r, y); log_file_ << Utils::radiansToDegrees(r) << "\t" << Utils::radiansToDegrees(p) << "\t" << Utils::radiansToDegrees(y) << "\t"; } } void endl() { if (enabled_) { log_file_ << std::endl; } } private: std::ofstream log_file_; string file_name_; bool enabled_ = false; }; } } //namespace #endif
AirSim/AirLib/include/common/LogFileWriter.hpp/0
{ "file_path": "AirSim/AirLib/include/common/LogFileWriter.hpp", "repo_id": "AirSim", "token_count": 1004 }
8
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef common_utils_FileSystem_hpp #define common_utils_FileSystem_hpp #include <codecvt> #include <fstream> #include <string> #include "Utils.hpp" // This defines a default folder name for all the files created by AirLib so they // are all gathered nicely in one place in the user's documents folder. #ifndef ProductFolderName #define ProductFolderName "AirSim" #endif #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS 1 #endif namespace common_utils { class FileSystem { typedef unsigned int uint; public: // please use the combine() method instead. static const char kPathSeparator = #ifdef _WIN32 '\\'; #else '/'; #endif static std::string createDirectory(const std::string& fullPath); static std::string getUserHomeFolder() { //Windows uses USERPROFILE, Linux uses HOME #ifdef _WIN32 std::wstring userProfile = _wgetenv(L"USERPROFILE"); std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter; return converter.to_bytes(userProfile); #else return std::getenv("HOME"); #endif } static std::string getUserDocumentsFolder(); static std::string getExecutableFolder(); static std::string getAppDataFolder() { return ensureFolder(combine(getUserDocumentsFolder(), ProductFolderName)); } static std::string ensureFolder(const std::string& fullpath) { // make sure this directory exists. return createDirectory(fullpath); } static std::string ensureFolder(const std::string& parentFolder, const std::string& child) { // make sure this directory exists. return createDirectory(combine(parentFolder, child)); } static std::string combine(const std::string& parentFolder, const std::string& child) { if (child.size() == 0) return parentFolder; size_t len = parentFolder.size(); if (parentFolder.size() > 0 && parentFolder[len - 1] == kPathSeparator) { // parent already ends with '/' return parentFolder + child; } len = child.size(); if (len > 0 && child[0] == kPathSeparator) { // child already starts with '/' return parentFolder + child; } return parentFolder + kPathSeparator + child; } static void removeLeaf(std::string& path) { size_t size = path.size(); size_t pos = path.find_last_of('/'); if (pos != std::string::npos) { path.erase(pos, size - pos); } } static std::string getFileExtension(const std::string& str) { // bugbug: this is not unicode safe. int len = static_cast<int>(str.size()); const char* ptr = str.c_str(); int i = 0; for (i = len - 1; i >= 0; i--) { if (ptr[i] == '.') break; } if (i < 0) return ""; return str.substr(i, len - i); } static std::string getLogFolderPath(bool folder_timestamp, const std::string& parent = "") { std::string logfolder = folder_timestamp ? Utils::to_string(Utils::now()) : ""; std::string parent_folder = (parent == "") ? getAppDataFolder() : parent; std::string fullPath = combine(parent_folder, logfolder); ensureFolder(fullPath); return fullPath; } static std::string getLogFileNamePath(const std::string& fullPath, const std::string& prefix, const std::string& suffix, const std::string& extension, bool file_timestamp) { //TODO: because this bug we are using alternative code with stringstream //https://answers.unrealengine.com/questions/664905/unreal-crashes-on-two-lines-of-extremely-simple-st.html std::string filename; filename.append(ensureFolder(fullPath)) .push_back(kPathSeparator); filename.append(prefix) .append(suffix) .append(file_timestamp ? Utils::to_string(Utils::now()) : "") .append(extension); return filename; //std::stringstream filename_ss; //filename_ss << ensureFolder(fullPath) << kPathSeparator << prefix << suffix << timestamp << extension; //return filename_ss.str(); } static void openTextFile(const std::string& filepath, std::ifstream& file) { #ifdef _WIN32 // WIN32 will create the wrong file names if we don't first convert them to UTF-16. std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter; std::wstring wide_path = converter.from_bytes(filepath); file.open(wide_path, std::ios::in); #else file.open(filepath, std::ios::in); #endif } static void createBinaryFile(const std::string& filepath, std::ofstream& file) { #ifdef _WIN32 // WIN32 will create the wrong file names if we don't first convert them to UTF-16. std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter; std::wstring wide_path = converter.from_bytes(filepath); file.open(wide_path, std::ios::binary | std::ios::trunc); #else file.open(filepath, std::ios::binary | std::ios::trunc); #endif } static void createTextFile(const std::string& filepath, std::ofstream& file) { #ifdef _WIN32 // WIN32 will create the wrong file names if we don't first convert them to UTF-16. std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter; std::wstring wide_path = converter.from_bytes(filepath); file.open(wide_path, std::ios::out | std::ios::trunc); #else file.open(filepath, std::ios::trunc); #endif if (file.fail()) throw std::ios_base::failure(std::strerror(errno)); } static std::string createLogFile(const std::string& suffix, std::ofstream& flog) { std::string log_folderpath = common_utils::FileSystem::getLogFolderPath(false); std::string filepath = getLogFileNamePath(log_folderpath, "log_", suffix, ".tsv", true); createTextFile(filepath, flog); Utils::log(Utils::stringf("log file started: %s", filepath.c_str())); flog.exceptions(flog.exceptions() | std::ios::failbit | std::ifstream::badbit); return filepath; } static std::string readLineFromFile(std::ifstream& file) { std::string line; try { std::getline(file, line); } catch (...) { if (!file.eof()) throw; } return line; } static void appendLineToFile(const std::string& filepath, const std::string& line) { std::ofstream file; #ifdef _WIN32 // WIN32 will create the wrong file names if we don't first convert them to UTF-16. std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter; std::wstring wide_path = converter.from_bytes(filepath); file.open(wide_path, std::ios::out | std::ios::app); #else file.open(filepath, std::ios::out | std::ios::app); #endif if (file.fail()) throw std::ios_base::failure(std::strerror(errno)); file.exceptions(file.exceptions() | std::ios::failbit | std::ifstream::badbit); file << line << std::endl; } }; } #endif
AirSim/AirLib/include/common/common_utils/FileSystem.hpp/0
{ "file_path": "AirSim/AirLib/include/common/common_utils/FileSystem.hpp", "repo_id": "AirSim", "token_count": 3049 }
9
/********************************************************* * * Copyright (C) 2014 by Vitaliy Vitsentiy * * 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. * *********************************************************/ #ifndef __ctpl_stl_thread_pool_H__ #define __ctpl_stl_thread_pool_H__ // clang-format off #include <functional> #include <thread> #include <atomic> #include <vector> #include <memory> #include <exception> #include <future> #include <mutex> #include <queue> // thread pool to run user's functors with signature // ret func(int id, other_params) // where id is the index of the thread that runs the functor // ret is some return type namespace ctpl { namespace detail { template <typename T> class Queue { public: bool push(T const & value) { std::unique_lock<std::mutex> lock(this->mutex); this->q.push(value); return true; } // deletes the retrieved element, do not use for non integral types bool pop(T & v) { std::unique_lock<std::mutex> lock(this->mutex); if (this->q.empty()) return false; v = this->q.front(); this->q.pop(); return true; } bool empty() { std::unique_lock<std::mutex> lock(this->mutex); return this->q.empty(); } private: std::queue<T> q; std::mutex mutex; }; } class thread_pool { public: thread_pool() { this->init(); } thread_pool(int nThreads) { this->init(); this->resize(nThreads); } // the destructor waits for all the functions in the queue to be finished ~thread_pool() { this->stop(true); } // get the number of running threads in the pool int size() { return static_cast<int>(this->threads.size()); } // number of idle threads int n_idle() { return this->nWaiting; } std::thread & get_thread(int i) { return *this->threads[i]; } // change the number of threads in the pool // should be called from one thread, otherwise be careful to not interleave, also with this->stop() // nThreads must be >= 0 void resize(int nThreads) { if (!this->isStop && !this->isDone) { int oldNThreads = static_cast<int>(this->threads.size()); if (oldNThreads <= nThreads) { // if the number of threads is increased this->threads.resize(nThreads); this->flags.resize(nThreads); for (int i = oldNThreads; i < nThreads; ++i) { this->flags[i] = std::make_shared<std::atomic<bool>>(false); this->set_thread(i); } } else { // the number of threads is decreased for (int i = oldNThreads - 1; i >= nThreads; --i) { *this->flags[i] = true; // this thread will finish this->threads[i]->detach(); } { // stop the detached threads that were waiting std::unique_lock<std::mutex> lock(this->mutex); this->cv.notify_all(); } this->threads.resize(nThreads); // safe to delete because the threads are detached this->flags.resize(nThreads); // safe to delete because the threads have copies of shared_ptr of the flags, not originals } } } // empty the queue void clear_queue() { std::function<void(int id)> * _f; while (this->q.pop(_f)) delete _f; // empty the queue } // pops a functional wrapper to the original function std::function<void(int)> pop() { std::function<void(int id)> * _f = nullptr; this->q.pop(_f); std::unique_ptr<std::function<void(int id)>> func(_f); // at return, delete the function even if an exception occurred std::function<void(int)> f; if (_f) f = *_f; return f; } // wait for all computing threads to finish and stop all threads // may be called asynchronously to not pause the calling thread while waiting // if isWait == true, all the functions in the queue are run, otherwise the queue is cleared without running the functions void stop(bool isWait = false) { if (!isWait) { if (this->isStop) return; this->isStop = true; for (int i = 0, n = this->size(); i < n; ++i) { *this->flags[i] = true; // command the threads to stop } this->clear_queue(); // empty the queue } else { if (this->isDone || this->isStop) return; this->isDone = true; // give the waiting threads a command to finish } { std::unique_lock<std::mutex> lock(this->mutex); this->cv.notify_all(); // stop all waiting threads } for (int i = 0; i < static_cast<int>(this->threads.size()); ++i) { // wait for the computing threads to finish if (this->threads[i]->joinable()) this->threads[i]->join(); } // if there were no threads in the pool but some functors in the queue, the functors are not deleted by the threads // therefore delete them here this->clear_queue(); this->threads.clear(); this->flags.clear(); } template<typename F, typename... Rest> auto push(F && f, Rest&&... rest) ->std::future<decltype(f(0, rest...))> { auto pck = std::make_shared<std::packaged_task<decltype(f(0, rest...))(int)>>( std::bind(std::forward<F>(f), std::placeholders::_1, std::forward<Rest>(rest)...) ); auto _f = new std::function<void(int id)>([pck](int id) { (*pck)(id); }); this->q.push(_f); std::unique_lock<std::mutex> lock(this->mutex); this->cv.notify_one(); return pck->get_future(); } // run the user's function that excepts argument int - id of the running thread. returned value is templatized // operator returns std::future, where the user can get the result and rethrow the catched exceptins template<typename F> auto push(F && f) ->std::future<decltype(f(0))> { auto pck = std::make_shared<std::packaged_task<decltype(f(0))(int)>>(std::forward<F>(f)); auto _f = new std::function<void(int id)>([pck](int id) { (*pck)(id); }); this->q.push(_f); std::unique_lock<std::mutex> lock(this->mutex); this->cv.notify_one(); return pck->get_future(); } private: // deleted thread_pool(const thread_pool &);// = delete; thread_pool(thread_pool &&);// = delete; thread_pool & operator=(const thread_pool &);// = delete; thread_pool & operator=(thread_pool &&);// = delete; void set_thread(int i) { std::shared_ptr<std::atomic<bool>> flag(this->flags[i]); // a copy of the shared ptr to the flag auto f = [this, i, flag/* a copy of the shared ptr to the flag */]() { std::atomic<bool> & _flag = *flag; std::function<void(int id)> * _f; bool isPop = this->q.pop(_f); while (true) { while (isPop) { // if there is anything in the queue std::unique_ptr<std::function<void(int id)>> func(_f); // at return, delete the function even if an exception occurred (*_f)(i); if (_flag) return; // the thread is wanted to stop, return even if the queue is not empty yet else isPop = this->q.pop(_f); } // the queue is empty here, wait for the next command std::unique_lock<std::mutex> lock(this->mutex); ++this->nWaiting; this->cv.wait(lock, [this, &_f, &isPop, &_flag](){ isPop = this->q.pop(_f); return isPop || this->isDone || _flag; }); --this->nWaiting; if (!isPop) return; // if the queue is empty and this->isDone == true or *flag then return } }; if (this->threads[i] != nullptr && this->threads[i]->joinable()) this->threads[i]->detach(); this->threads[i].reset(new std::thread(f)); // compiler may not support std::make_unique() } void init() { this->nWaiting = 0; this->isStop = false; this->isDone = false; } std::vector<std::unique_ptr<std::thread>> threads; std::vector<std::shared_ptr<std::atomic<bool>>> flags; detail::Queue<std::function<void(int id)> *> q; std::atomic<bool> isDone; std::atomic<bool> isStop; std::atomic<int> nWaiting; // how many threads are waiting std::mutex mutex; std::condition_variable cv; }; } // clang-format on #endif // __ctpl_stl_thread_pool_H__
AirSim/AirLib/include/common/common_utils/ctpl_stl.h/0
{ "file_path": "AirSim/AirLib/include/common/common_utils/ctpl_stl.h", "repo_id": "AirSim", "token_count": 4896 }
10
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef air_CubeGeoFence_hpp #define air_CubeGeoFence_hpp #include "common/Common.hpp" namespace msr { namespace airlib { class CubeGeoFence : public IGeoFence { private: Vector3r point_min_, point_max_, point_center_; float distance_accuracy_; public: CubeGeoFence(const Vector3r& point_min, const Vector3r& point_max, float distance_accuracy) : point_min_(point_min), point_max_(point_max), distance_accuracy_(distance_accuracy) { calculateCenter(); Utils::logMessage("CubeGeoFence: %s", toString().c_str()); } void setBoundry(const Vector3r& origin, float xy_length, float max_z, float min_z) override { point_min_ = Vector3r(-xy_length, -xy_length, 0) + origin; point_min_[2] = max_z; point_max_ = Vector3r(xy_length, xy_length, 0) + origin; point_max_[2] = min_z; calculateCenter(); Utils::logMessage("CubeGeoFence: %s", toString().c_str()); } void checkFence(const Vector3r& cur_loc, const Vector3r& dest_loc, bool& in_fence, bool& allow) override { in_fence = dest_loc[0] >= point_min_[0] && dest_loc[1] >= point_min_[1] && dest_loc[2] >= point_min_[2] && dest_loc[0] <= point_max_[0] && dest_loc[1] <= point_max_[1] && dest_loc[2] <= point_max_[2]; if (!in_fence) { //are we better off with dest than cur location? float dest_dist = (dest_loc - point_center_).norm(); float cur_dist = (cur_loc - point_center_).norm(); allow = cur_dist - dest_dist >= -distance_accuracy_; } else allow = true; } string toString() const override { return Utils::stringf("min=%s, max=%s", VectorMath::toString(point_min_).c_str(), VectorMath::toString(point_max_).c_str()); } virtual ~CubeGeoFence(){}; private: void calculateCenter() { point_center_ = (point_max_ + point_min_) / 2; } }; } } //namespace #endif
AirSim/AirLib/include/safety/CubeGeoFence.hpp/0
{ "file_path": "AirSim/AirLib/include/safety/CubeGeoFence.hpp", "repo_id": "AirSim", "token_count": 1114 }
11
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef msr_airlib_GpsSimpleParams_hpp #define msr_airlib_GpsSimpleParams_hpp #include "common/Common.hpp" namespace msr { namespace airlib { struct GpsSimpleParams { real_T eph_time_constant = 0.9f, epv_time_constant = 0.9f; real_T eph_initial = 100.0f, epv_initial = 100.0f; //initially fully diluted positions real_T eph_final = 0.1f, epv_final = 0.1f; // PX4 won't converge GPS sensor fusion until we get to 10% accuracty. real_T eph_min_3d = 3.0f, eph_min_2d = 4.0f; real_T update_latency = 0.2f; //sec real_T update_frequency = 50; //Hz real_T startup_delay = 1; //sec void initializeFromSettings(const AirSimSettings::GpsSetting& settings) { const auto& json = settings.settings; eph_time_constant = json.getFloat("EPH_TimeConstant", eph_time_constant); epv_time_constant = json.getFloat("EPV_TimeConstant", epv_time_constant); eph_initial = json.getFloat("EphInitial", eph_initial); epv_initial = json.getFloat("EpvInitial", epv_initial); eph_final = json.getFloat("EphFinal", eph_final); epv_final = json.getFloat("EpvFinal", epv_final); eph_min_3d = json.getFloat("EphMin3d", eph_min_3d); eph_min_2d = json.getFloat("EphMin2d", eph_min_2d); update_latency = json.getFloat("UpdateLatency", update_latency); update_frequency = json.getFloat("UpdateFrequency", update_frequency); startup_delay = json.getFloat("StartupDelay", startup_delay); } }; } } //namespace #endif
AirSim/AirLib/include/sensors/gps/GpsSimpleParams.hpp/0
{ "file_path": "AirSim/AirLib/include/sensors/gps/GpsSimpleParams.hpp", "repo_id": "AirSim", "token_count": 773 }
12