patch
stringlengths 17
31.2k
| y
int64 1
1
| oldf
stringlengths 0
2.21M
| idx
int64 1
1
| id
int64 4.29k
68.4k
| msg
stringlengths 8
843
| proj
stringclasses 212
values | lang
stringclasses 9
values |
---|---|---|---|---|---|---|---|
@@ -1,3 +1,5 @@
+'use strict';
+
require('classtool');
function ClassSpec(b) { | 1 | require('classtool');
function ClassSpec(b) {
var superclass = b.superclass || require('./util/VersionedData').class();
function Address() {
Address.super(this, arguments);
};
Address.superclass = superclass;
superclass.applyEncodingsTo(Address);
Address.prototype.validate = function() {
this.doAsBinary(function() {
Address.super(this, 'validate', arguments);
if(this.data.length != 21) throw new Error('invalid data length');
});
};
return Address;
};
module.defineClass(ClassSpec);
| 1 | 12,145 | For now, don't add "use strict" to any existing files. That's a separate project that we'll do later. (New files can use "use strict".) | bitpay-bitcore | js |
@@ -216,6 +216,12 @@ func TestConfigCommandInteractiveCreateDocrootDenied(t *testing.T) {
// Set up tests and give ourselves a working directory.
assert := asrt.New(t)
+ noninteractive := "DRUD_NONINTERACTIVE"
+ // nolint: errcheck
+ defer os.Setenv(noninteractive, os.Getenv(noninteractive))
+ err := os.Unsetenv(noninteractive)
+ assert.NoError(err)
+
testMatrix := map[string][]string{
"drupal6phpversion": {AppTypeDrupal6, PHP56},
"drupal7phpversion": {AppTypeDrupal7, PHP71}, | 1 | package ddevapp_test
import (
"bufio"
"fmt"
"github.com/drud/ddev/pkg/exec"
"github.com/stretchr/testify/require"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
. "github.com/drud/ddev/pkg/ddevapp"
"github.com/drud/ddev/pkg/fileutil"
"github.com/drud/ddev/pkg/testcommon"
"github.com/drud/ddev/pkg/util"
"github.com/drud/ddev/pkg/version"
"github.com/google/uuid"
asrt "github.com/stretchr/testify/assert"
)
// TestNewConfig tests functionality around creating a new config, writing it to disk, and reading the resulting config.
func TestNewConfig(t *testing.T) {
assert := asrt.New(t)
// Create a temporary directory and change to it for the duration of this test.
testDir := testcommon.CreateTmpDir("TestNewConfig")
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
// Load a new Config
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
// Ensure the config uses specified defaults.
assert.Equal(app.APIVersion, version.DdevVersion)
assert.Equal(app.DBImage, version.DBImg+":"+version.DBTag)
assert.Equal(app.WebImage, version.WebImg+":"+version.WebTag)
assert.Equal(app.DBAImage, version.DBAImg+":"+version.DBATag)
app.Name = util.RandString(32)
app.Type = AppTypeDrupal8
// WriteConfig the app.
err = app.WriteConfig()
assert.NoError(err)
_, err = os.Stat(app.ConfigPath)
assert.NoError(err)
loadedConfig, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
assert.Equal(app.Name, loadedConfig.Name)
assert.Equal(app.Type, loadedConfig.Type)
}
// TestAllowedAppType tests the IsAllowedAppType function.
func TestAllowedAppTypes(t *testing.T) {
assert := asrt.New(t)
for _, v := range GetValidAppTypes() {
assert.True(IsValidAppType(v))
}
for i := 1; i <= 50; i++ {
randomType := util.RandString(32)
assert.False(IsValidAppType(randomType))
}
}
// TestPrepDirectory ensures the configuration directory can be created with the correct permissions.
func TestPrepDirectory(t *testing.T) {
assert := asrt.New(t)
// Create a temporary directory and change to it for the duration of this test.
testDir := testcommon.CreateTmpDir("TestPrepDirectory")
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
// Prep the directory.
err = PrepDdevDirectory(filepath.Dir(app.ConfigPath))
assert.NoError(err)
// Read directory info an ensure it exists.
_, err = os.Stat(filepath.Dir(app.ConfigPath))
assert.NoError(err)
}
// TestHostName tests that the TestSite.Hostname() field returns the hostname as expected.
func TestHostName(t *testing.T) {
assert := asrt.New(t)
testDir := testcommon.CreateTmpDir("TestHostName")
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
app.Name = util.RandString(32)
assert.Equal(app.GetHostname(), app.Name+"."+version.DDevTLD)
}
// TestWriteDockerComposeYaml tests the writing of a docker-compose.yaml file.
func TestWriteDockerComposeYaml(t *testing.T) {
// Set up tests and give ourselves a working directory.
assert := asrt.New(t)
testDir := testcommon.CreateTmpDir("TestWriteDockerCompose")
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
app.Name = util.RandString(32)
app.Type = GetValidAppTypes()[0]
// WriteConfig a config to create/prep necessary directories.
err = app.WriteConfig()
assert.NoError(err)
// After the config has been written and directories exist, the write should work.
err = app.WriteDockerComposeConfig()
assert.NoError(err)
// Ensure we can read from the file and that it's a regular file with the expected name.
fileinfo, err := os.Stat(app.DockerComposeYAMLPath())
assert.NoError(err)
assert.False(fileinfo.IsDir())
assert.Equal(fileinfo.Name(), filepath.Base(app.DockerComposeYAMLPath()))
composeBytes, err := ioutil.ReadFile(app.DockerComposeYAMLPath())
assert.NoError(err)
contentString := string(composeBytes)
assert.Contains(contentString, app.Platform)
assert.Contains(contentString, app.Type)
}
// TestConfigCommand tests the interactive config options.
func TestConfigCommand(t *testing.T) {
// Set up tests and give ourselves a working directory.
assert := asrt.New(t)
const apptypePos = 0
const phpVersionPos = 1
testMatrix := map[string][]string{
"drupal6phpversion": {AppTypeDrupal6, PHP56},
"drupal7phpversion": {AppTypeDrupal7, PHP71},
"drupal8phpversion": {AppTypeDrupal8, PHP71},
}
for testName, testValues := range testMatrix {
testDir := testcommon.CreateTmpDir("TestConfigCommand_" + testName)
// testcommon.Chdir()() and CleanupDir() checks their own errors (and exit)
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
// Create a docroot folder.
err := os.Mkdir(filepath.Join(testDir, "docroot"), 0644)
if err != nil {
t.Errorf("Could not create docroot directory under %s", testDir)
}
// Create the ddevapp we'll use for testing.
// This will not return an error, since there is no existing configuration.
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
// Randomize some values to use for Stdin during testing.
name := strings.ToLower(util.RandString(16))
invalidAppType := strings.ToLower(util.RandString(8))
// Create an example input buffer that writes the sitename, a valid document root,
// an invalid app type, and finally a valid app type (from test matrix)
input := fmt.Sprintf("%s\ndocroot\n%s\n%s", name, invalidAppType, testValues[apptypePos])
scanner := bufio.NewScanner(strings.NewReader(input))
util.SetInputScanner(scanner)
restoreOutput := util.CaptureUserOut()
err = app.PromptForConfig()
assert.NoError(err, t)
out := restoreOutput()
// Ensure we have expected vales in output.
assert.Contains(out, testDir)
assert.Contains(out, fmt.Sprintf("'%s' is not a valid project type", invalidAppType))
// Create an example input buffer that writes an invalid projectname, then a valid-project-name,
// a valid document root,
// a valid app type
input = fmt.Sprintf("invalid_project_name\n%s\ndocroot\n%s", name, testValues[apptypePos])
scanner = bufio.NewScanner(strings.NewReader(input))
util.SetInputScanner(scanner)
restoreOutput = util.CaptureUserOut()
err = app.PromptForConfig()
assert.NoError(err, t)
out = restoreOutput()
// Ensure we have expected vales in output.
assert.Contains(out, testDir)
assert.Contains(out, "invalid_project_name is not a valid project name")
// Ensure values were properly set on the app struct.
assert.Equal(name, app.Name)
assert.Equal(testValues[apptypePos], app.Type)
assert.Equal("docroot", app.Docroot)
assert.EqualValues(testValues[phpVersionPos], app.PHPVersion)
err = PrepDdevDirectory(testDir)
assert.NoError(err)
}
}
// TestConfigCommandInteractiveCreateDocrootDenied
func TestConfigCommandInteractiveCreateDocrootDenied(t *testing.T) {
// Set up tests and give ourselves a working directory.
assert := asrt.New(t)
testMatrix := map[string][]string{
"drupal6phpversion": {AppTypeDrupal6, PHP56},
"drupal7phpversion": {AppTypeDrupal7, PHP71},
"drupal8phpversion": {AppTypeDrupal8, PHP71},
}
for testName := range testMatrix {
testDir := testcommon.CreateTmpDir(t.Name() + testName)
// testcommon.Chdir()() and CleanupDir() checks their own errors (and exit)
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
// Create the ddevapp we'll use for testing.
// This will not return an error, since there is no existing configuration.
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
// Randomize some values to use for Stdin during testing.
name := uuid.New().String()
nonexistentDocroot := filepath.Join("does", "not", "exist")
// Create an example input buffer that writes the sitename, a nonexistent document root,
// and a "no"
input := fmt.Sprintf("%s\n%s\nno", name, nonexistentDocroot)
scanner := bufio.NewScanner(strings.NewReader(input))
util.SetInputScanner(scanner)
err = app.PromptForConfig()
assert.Error(err, t)
// Ensure we have expected vales in output.
assert.Contains(err.Error(), "docroot must exist to continue configuration")
err = PrepDdevDirectory(testDir)
assert.NoError(err)
}
}
// TestConfigCommandCreateDocrootAllowed
func TestConfigCommandCreateDocrootAllowed(t *testing.T) {
// Set up tests and give ourselves a working directory.
assert := asrt.New(t)
const apptypePos = 0
const phpVersionPos = 1
testMatrix := map[string][]string{
"drupal6phpversion": {AppTypeDrupal6, PHP56},
"drupal7phpversion": {AppTypeDrupal7, PHP71},
"drupal8phpversion": {AppTypeDrupal8, PHP71},
}
for testName, testValues := range testMatrix {
testDir := testcommon.CreateTmpDir(t.Name() + testName)
// testcommon.Chdir()() and CleanupDir() checks their own errors (and exit)
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
// Create the ddevapp we'll use for testing.
// This will not return an error, since there is no existing configuration.
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
// Randomize some values to use for Stdin during testing.
name := uuid.New().String()
nonexistentDocroot := filepath.Join("does", "not", "exist")
// Create an example input buffer that writes the sitename, a nonexistent document root,
// a "yes", and a valid apptype
input := fmt.Sprintf("%s\n%s\nyes\n%s", name, nonexistentDocroot, testValues[apptypePos])
scanner := bufio.NewScanner(strings.NewReader(input))
util.SetInputScanner(scanner)
restoreOutput := util.CaptureUserOut()
err = app.PromptForConfig()
assert.NoError(err, t)
out := restoreOutput()
// Ensure we have expected vales in output.
assert.Contains(out, nonexistentDocroot)
assert.Contains(out, "Created docroot")
// Ensure values were properly set on the app struct.
assert.Equal(name, app.Name)
assert.Equal(testValues[apptypePos], app.Type)
assert.Equal(nonexistentDocroot, app.Docroot)
assert.EqualValues(testValues[phpVersionPos], app.PHPVersion)
err = PrepDdevDirectory(testDir)
assert.NoError(err)
}
}
// TestConfigCommandDocrootDetection asserts the default docroot is detected.
func TestConfigCommandDocrootDetection(t *testing.T) {
// Set up tests and give ourselves a working directory.
assert := asrt.New(t)
testMatrix := AvailableDocrootLocations()
for index, testDocrootName := range testMatrix {
testDir := testcommon.CreateTmpDir(fmt.Sprintf("TestConfigCommand_%v", index))
// testcommon.Chdir()() and CleanupDir() checks their own errors (and exit)
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
// Create a document root folder.
err := os.MkdirAll(filepath.Join(testDir, filepath.Join(testDocrootName)), 0755)
if err != nil {
t.Errorf("Could not create %s directory under %s", testDocrootName, testDir)
}
_, err = os.OpenFile(filepath.Join(testDir, filepath.Join(testDocrootName), "index.php"), os.O_RDONLY|os.O_CREATE, 0664)
assert.NoError(err)
// Create the ddevapp we'll use for testing.
// This will not return an error, since there is no existing configuration.
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
// Randomize some values to use for Stdin during testing.
name := strings.ToLower(util.RandString(16))
// Create an example input buffer that writes the site name, accepts the
// default document root and provides a valid app type.
input := fmt.Sprintf("%s\n\ndrupal8", name)
scanner := bufio.NewScanner(strings.NewReader(input))
util.SetInputScanner(scanner)
restoreOutput := util.CaptureStdOut()
err = app.PromptForConfig()
assert.NoError(err, t)
out := restoreOutput()
assert.Contains(out, fmt.Sprintf("Docroot Location (%s)", testDocrootName))
// Ensure values were properly set on the app struct.
assert.Equal(name, app.Name)
assert.Equal(AppTypeDrupal8, app.Type)
assert.Equal(testDocrootName, app.Docroot)
err = PrepDdevDirectory(testDir)
assert.NoError(err)
}
}
// TestConfigCommandDocrootDetection asserts the default docroot is detected and has index.php.
// The `web` docroot check is before `docroot` this verifies the directory with an
// existing index.php is selected.
func TestConfigCommandDocrootDetectionIndexVerification(t *testing.T) {
// Set up tests and give ourselves a working directory.
assert := asrt.New(t)
testDir := testcommon.CreateTmpDir("TestConfigCommand_testDocrootIndex")
// testcommon.Chdir()() and CleanupDir() checks their own errors (and exit)
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
// Create a document root folder.
err := os.MkdirAll(filepath.Join(testDir, filepath.Join("web")), 0755)
if err != nil {
t.Errorf("Could not create %s directory under %s", "web", testDir)
}
err = os.MkdirAll(filepath.Join(testDir, filepath.Join("docroot")), 0755)
if err != nil {
t.Errorf("Could not create %s directory under %s", "docroot", testDir)
}
_, err = os.OpenFile(filepath.Join(testDir, "docroot", "index.php"), os.O_RDONLY|os.O_CREATE, 0664)
assert.NoError(err)
// Create the ddevapp we'll use for testing.
// This will not return an error, since there is no existing configuration.
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
// Randomize some values to use for Stdin during testing.
name := strings.ToLower(util.RandString(16))
// Create an example input buffer that writes the site name, accepts the
// default document root and provides a valid app type.
input := fmt.Sprintf("%s\n\ndrupal8", name)
scanner := bufio.NewScanner(strings.NewReader(input))
util.SetInputScanner(scanner)
restoreOutput := util.CaptureStdOut()
err = app.PromptForConfig()
assert.NoError(err, t)
out := restoreOutput()
assert.Contains(out, fmt.Sprintf("Docroot Location (%s)", "docroot"))
// Ensure values were properly set on the app struct.
assert.Equal(name, app.Name)
assert.Equal(AppTypeDrupal8, app.Type)
assert.Equal("docroot", app.Docroot)
err = PrepDdevDirectory(testDir)
assert.NoError(err)
}
// TestReadConfig tests reading config values from file and fallback to defaults for values not exposed.
func TestReadConfig(t *testing.T) {
assert := asrt.New(t)
// This closely resembles the values one would have from NewApp()
app := &DdevApp{
APIVersion: version.DdevVersion,
ConfigPath: filepath.Join("testdata", "config.yaml"),
AppRoot: "testdata",
Name: "TestRead",
Provider: ProviderDefault,
}
err := app.ReadConfig()
if err != nil {
t.Fatalf("Unable to c.ReadConfig(), err: %v", err)
}
// Values not defined in file, we should still have default values
assert.Equal(app.Name, "TestRead")
assert.Equal(app.APIVersion, version.DdevVersion)
// Values defined in file, we should have values from file
assert.Equal(app.Type, AppTypeDrupal8)
assert.Equal(app.Docroot, "test")
assert.Equal(app.WebImage, "test/testimage:latest")
}
// TestValidate tests validation of configuration values.
func TestValidate(t *testing.T) {
assert := asrt.New(t)
cwd, err := os.Getwd()
assert.NoError(err)
app := &DdevApp{
Name: "TestValidate",
ConfigPath: filepath.Join("testdata", "config.yaml"),
AppRoot: cwd,
Docroot: "testdata",
Type: AppTypeWordPress,
PHPVersion: PHPDefault,
WebserverType: WebserverDefault,
Provider: ProviderDefault,
}
err = app.ValidateConfig()
if err != nil {
t.Fatalf("Failed to app.ValidateConfig(), err=%v", err)
}
app.Name = "Invalid!"
err = app.ValidateConfig()
assert.Error(err)
assert.Contains(err.Error(), "not a valid project name")
app.Docroot = "testdata"
app.Name = "valid"
app.Type = "potato"
err = app.ValidateConfig()
assert.Error(err)
assert.Contains(err.Error(), "invalid app type")
app.Type = AppTypeWordPress
app.PHPVersion = "1.1"
err = app.ValidateConfig()
assert.Error(err)
assert.Contains(err.Error(), "invalid PHP")
app.PHPVersion = PHPDefault
app.WebserverType = "server"
err = app.ValidateConfig()
assert.Error(err)
assert.Contains(err.Error(), "invalid webserver type")
app.WebserverType = WebserverDefault
app.AdditionalHostnames = []string{"good", "b@d"}
err = app.ValidateConfig()
assert.Error(err)
assert.Contains(err.Error(), "invalid hostname")
app.AdditionalHostnames = []string{}
app.AdditionalFQDNs = []string{"good.com", "[email protected]"}
err = app.ValidateConfig()
assert.Error(err)
assert.Contains(err.Error(), "invalid hostname")
}
// TestWriteConfig tests writing config values to file
func TestWriteConfig(t *testing.T) {
assert := asrt.New(t)
testDir := testcommon.CreateTmpDir("TestConfigWrite")
// This closely resembles the values one would have from NewApp()
app := &DdevApp{
ConfigPath: filepath.Join(testDir, "config.yaml"),
AppRoot: testDir,
APIVersion: version.DdevVersion,
Name: "TestWrite",
WebImage: version.WebImg + ":" + version.WebTag,
DBImage: version.DBImg + ":" + version.DBTag,
DBAImage: version.DBAImg + ":" + version.DBATag,
Type: AppTypeDrupal8,
Provider: ProviderDefault,
}
err := app.WriteConfig()
assert.NoError(err)
out, err := ioutil.ReadFile(filepath.Join(testDir, "config.yaml"))
assert.NoError(err)
assert.Contains(string(out), "TestWrite")
assert.Contains(string(out), `exec: drush cr`)
app.Type = AppTypeWordPress
err = app.WriteConfig()
assert.NoError(err)
out, err = ioutil.ReadFile(filepath.Join(testDir, "config.yaml"))
assert.NoError(err)
assert.Contains(string(out), `- exec: wp cli version`)
err = os.RemoveAll(testDir)
assert.NoError(err)
}
// TestConfigOverrideDetection tests to make sure we tell them about config overrides.
func TestConfigOverrideDetection(t *testing.T) {
assert := asrt.New(t)
testcommon.ClearDockerEnv()
testDir := testcommon.CreateTmpDir("TestConfigOverrideDetection")
targetDdev := filepath.Join(testDir, ".ddev")
err := fileutil.CopyDir("testdata/.ddev", targetDdev)
assert.NoError(err)
// testcommon.Chdir()() and CleanupDir() checks their own errors (and exit)
defer testcommon.CleanupDir(testDir)
defer testcommon.Chdir(testDir)()
app, err := NewApp(testDir, ProviderDefault)
assert.NoError(err)
err = app.ReadConfig()
assert.NoError(err)
restoreOutput := util.CaptureUserOut()
err = app.Start()
out := restoreOutput()
if strings.Contains(out, "ddev-ssh-agent failed to become ready") {
dockerLogs, err := exec.RunCommand("docker", []string{"logs", "ddev-ssh-agent"})
assert.NoError(err)
t.Logf("ddev-ssh-agent failed to become ready, docker logs:===\n%s\n===", dockerLogs)
}
require.NoError(t, err, "app.Start() did not succeed: output:===\n%s\n===", out)
assert.Contains(out, "utf.cnf")
assert.Contains(out, "my-php.ini")
switch app.WebserverType {
case WebserverNginxFPM:
assert.Contains(out, "nginx-site.conf")
assert.NotContains(out, "apache-site.conf")
default:
assert.Contains(out, "apache-site.conf")
assert.NotContains(out, "nginx-site.conf")
}
assert.Contains(out, "Custom configuration takes effect")
_ = app.Down(true, false)
}
| 1 | 13,217 | I was confused by this env name variable, assuming it was the value, not the name. Silly nit, but maybe name it noninteractiveEnv? | drud-ddev | go |
@@ -139,7 +139,7 @@ def py_run(command_options='', return_std=False, stdout=None, stderr=None):
"""
# Create command line to call pylint
epylint_part = [sys.executable, "-c", "from pylint import epylint;epylint.Run()"]
- options = shlex.split(command_options)
+ options = shlex.split(command_options, posix='win' not in sys.platform)
cli = epylint_part + options
# Providing standard output and/or error if not set | 1 | # -*- coding: utf-8;
# mode: python; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4
# -*- vim:fenc=utf-8:ft=python:et:sw=4:ts=4:sts=4
# Copyright (c) 2008-2014 LOGILAB S.A. (Paris, FRANCE) <[email protected]>
# Copyright (c) 2014 Jakob Normark <[email protected]>
# Copyright (c) 2014 Brett Cannon <[email protected]>
# Copyright (c) 2014 Manuel Vázquez Acosta <[email protected]>
# Copyright (c) 2014 Derek Harland <[email protected]>
# Copyright (c) 2014 Arun Persaud <[email protected]>
# Copyright (c) 2015-2016 Claudiu Popa <[email protected]>
# Copyright (c) 2015 Mihai Balint <[email protected]>
# Copyright (c) 2015 Ionel Cristian Maries <[email protected]>
# Copyright (c) 2017 hippo91 <[email protected]>
# Copyright (c) 2017 Daniela Plascencia <[email protected]>
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
"""Emacs and Flymake compatible Pylint.
This script is for integration with emacs and is compatible with flymake mode.
epylint walks out of python packages before invoking pylint. This avoids
reporting import errors that occur when a module within a package uses the
absolute import path to get another module within this package.
For example:
- Suppose a package is structured as
a/__init__.py
a/b/x.py
a/c/y.py
- Then if y.py imports x as "from a.b import x" the following produces pylint
errors
cd a/c; pylint y.py
- The following obviously doesn't
pylint a/c/y.py
- As this script will be invoked by emacs within the directory of the file
we are checking we need to go out of it to avoid these false positives.
You may also use py_run to run pylint with desired options and get back (or not)
its output.
"""
from __future__ import print_function
import os
import os.path as osp
import sys
import shlex
from subprocess import Popen, PIPE
import six
def _get_env():
'''Extracts the environment PYTHONPATH and appends the current sys.path to
those.'''
env = dict(os.environ)
env['PYTHONPATH'] = os.pathsep.join(sys.path)
return env
def lint(filename, options=None):
"""Pylint the given file.
When run from emacs we will be in the directory of a file, and passed its
filename. If this file is part of a package and is trying to import other
modules from within its own package or another package rooted in a directory
below it, pylint will classify it as a failed import.
To get around this, we traverse down the directory tree to find the root of
the package this module is in. We then invoke pylint from this directory.
Finally, we must correct the filenames in the output generated by pylint so
Emacs doesn't become confused (it will expect just the original filename,
while pylint may extend it with extra directories if we've traversed down
the tree)
"""
# traverse downwards until we are out of a python package
full_path = osp.abspath(filename)
parent_path = osp.dirname(full_path)
child_path = osp.basename(full_path)
while parent_path != "/" and osp.exists(osp.join(parent_path, '__init__.py')):
child_path = osp.join(osp.basename(parent_path), child_path)
parent_path = osp.dirname(parent_path)
# Start pylint
# Ensure we use the python and pylint associated with the running epylint
run_cmd = "import sys; from pylint.lint import Run; Run(sys.argv[1:])"
options = options or ['--disable=C,R,I']
cmd = [sys.executable, "-c", run_cmd] + [
'--msg-template', '{path}:{line}: {category} ({msg_id}, {symbol}, {obj}) {msg}',
'-r', 'n', child_path] + options
process = Popen(cmd, stdout=PIPE, cwd=parent_path, env=_get_env(),
universal_newlines=True)
for line in process.stdout:
# remove pylintrc warning
if line.startswith("No config file found"):
continue
# modify the file name thats output to reverse the path traversal we made
parts = line.split(":")
if parts and parts[0] == child_path:
line = ":".join([filename] + parts[1:])
print(line, end=' ')
process.wait()
return process.returncode
def py_run(command_options='', return_std=False, stdout=None, stderr=None):
"""Run pylint from python
``command_options`` is a string containing ``pylint`` command line options;
``return_std`` (boolean) indicates return of created standard output
and error (see below);
``stdout`` and ``stderr`` are 'file-like' objects in which standard output
could be written.
Calling agent is responsible for stdout/err management (creation, close).
Default standard output and error are those from sys,
or standalone ones (``subprocess.PIPE``) are used
if they are not set and ``return_std``.
If ``return_std`` is set to ``True``, this function returns a 2-uple
containing standard output and error related to created process,
as follows: ``(stdout, stderr)``.
To silently run Pylint on a module, and get its standard output and error:
>>> (pylint_stdout, pylint_stderr) = py_run( 'module_name.py', True)
"""
# Create command line to call pylint
epylint_part = [sys.executable, "-c", "from pylint import epylint;epylint.Run()"]
options = shlex.split(command_options)
cli = epylint_part + options
# Providing standard output and/or error if not set
if stdout is None:
if return_std:
stdout = PIPE
else:
stdout = sys.stdout
if stderr is None:
if return_std:
stderr = PIPE
else:
stderr = sys.stderr
# Call pylint in a subprocess
process = Popen(cli, shell=False, stdout=stdout, stderr=stderr,
env=_get_env(), universal_newlines=True)
proc_stdout, proc_stderr = process.communicate()
# Return standard output and error
if return_std:
return six.moves.StringIO(proc_stdout), six.moves.StringIO(proc_stderr)
return None
def Run():
if len(sys.argv) == 1:
print("Usage: %s <filename> [options]" % sys.argv[0])
sys.exit(1)
elif not osp.exists(sys.argv[1]):
print("%s does not exist" % sys.argv[1])
sys.exit(1)
else:
sys.exit(lint(sys.argv[1], sys.argv[2:]))
if __name__ == '__main__':
Run()
| 1 | 9,934 | `sys.platform` could be equal to `darwin` which is posix. Use `not startswith('win')`? | PyCQA-pylint | py |
@@ -38,11 +38,12 @@ func New(cfg *any.Any, logger *zap.Logger, scope tally.Scope) (service.Service,
}
s := &svc{
- logger: logger,
- filter: config.Filter,
- scope: scope,
- slack: slack.New(config.Token),
- channel: config.Channel,
+ logger: logger,
+ filter: config.Filter,
+ overrides: NewOverrideLookup(config.Overrides),
+ scope: scope,
+ slack: slack.New(config.Token),
+ channel: config.Channel,
}
return s, nil
} | 1 | package slack
// <!-- START clutchdoc -->
// description: Posts events to a configured Slack workspace and channel.
// <!-- END clutchdoc -->
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"strings"
"text/template"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/any"
"github.com/slack-go/slack"
"github.com/uber-go/tally"
"go.uber.org/zap"
"google.golang.org/protobuf/encoding/protojson"
auditv1 "github.com/lyft/clutch/backend/api/audit/v1"
auditconfigv1 "github.com/lyft/clutch/backend/api/config/service/audit/v1"
configv1 "github.com/lyft/clutch/backend/api/config/service/auditsink/slack/v1"
"github.com/lyft/clutch/backend/service"
"github.com/lyft/clutch/backend/service/auditsink"
)
const (
Name = "clutch.service.auditsink.slack"
defaultNone = "None"
)
func New(cfg *any.Any, logger *zap.Logger, scope tally.Scope) (service.Service, error) {
config := &configv1.SlackConfig{}
if err := ptypes.UnmarshalAny(cfg, config); err != nil {
return nil, err
}
s := &svc{
logger: logger,
filter: config.Filter,
scope: scope,
slack: slack.New(config.Token),
channel: config.Channel,
}
return s, nil
}
// The struct is used in a Go template and the fields need to be exported
type auditTemplateData struct {
Request map[string]interface{}
Response map[string]interface{}
}
// TODO: (sperry) expand on helper funcs
// helper functions to format values in the Go template
var funcMap = template.FuncMap{
// for inputs that are type slice/map, returns a formatted slack list
// currently only iterates 1-level deep
"slackList": slackList,
}
type svc struct {
logger *zap.Logger
scope tally.Scope
filter *auditconfigv1.Filter
slack *slack.Client
channel string
}
func (s *svc) Write(event *auditv1.Event) error {
if !auditsink.Filter(s.filter, event) {
return nil
}
switch event.GetEventType().(type) {
case *auditv1.Event_Event:
return s.writeRequestEvent(event.GetEvent())
default:
return nil
}
}
func (s *svc) writeRequestEvent(event *auditv1.RequestEvent) error {
// Get user ID for pretty message printing.
user, err := s.slack.GetUserByEmail(event.Username)
var username string
if err != nil {
s.logger.Warn(
"failure to get user information from slack",
zap.String("username", event.Username),
zap.Error(err),
)
username = event.Username
} else {
username = fmt.Sprintf("<@%s>", user.ID)
}
messageText := formatText(username, event)
// Post
if _, _, err := s.slack.PostMessage(s.channel, slack.MsgOptionText(messageText, false)); err != nil {
return err
}
return nil
}
func formatText(username string, event *auditv1.RequestEvent) string {
// Make text: `user` performed `/path/to/action` via `service` using Clutch on resources: ...
const messageFormat = "`%s` performed `%s` via `%s` using Clutch on resource(s):"
messageText := fmt.Sprintf(
messageFormat,
username,
event.MethodName,
event.ServiceName,
)
// - resourceName (`resourceTypeUrl`)
const resourceFormat = "\n- %s (`%s`)"
for _, resource := range event.Resources {
messageText += fmt.Sprintf(resourceFormat, resource.Id, resource.TypeUrl)
}
return messageText
}
// FormatCustomText applies the audit event metadata to the custom slack message
func FormatCustomText(message string, event *auditv1.RequestEvent) (string, error) {
tmpl, err := template.New("customText").Funcs(funcMap).Parse(message)
if err != nil {
return "", err
}
data, err := getAuditTemplateData(event)
if err != nil {
return "", err
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return "", err
}
// When a value is nil, the Go Template sets the value as "<no value>".
// Ex of when we hit this scenario: https://github.com/lyft/clutch/blob/main/api/k8s/v1/k8s.proto#L860
sanitized := strings.ReplaceAll(buf.String(), "<no value>", defaultNone)
return sanitized, nil
}
// returns the API request/response details saved in an audit event
func getAuditTemplateData(event *auditv1.RequestEvent) (*auditTemplateData, error) {
// proto -> json
reqJSON, err := protojson.Marshal(event.RequestMetadata.Body)
if err != nil {
return nil, err
}
respJSON, err := protojson.Marshal(event.ResponseMetadata.Body)
if err != nil {
return nil, err
}
var requestMetadata map[string]interface{}
var responseMetadata map[string]interface{}
// json -> map[string]interface{}
err = json.Unmarshal(reqJSON, &requestMetadata)
if err != nil {
return nil, err
}
err = json.Unmarshal(respJSON, &responseMetadata)
if err != nil {
return nil, err
}
return &auditTemplateData{
Request: requestMetadata,
Response: responseMetadata,
}, nil
}
// for inputs that are type slice/map, returns a formatted slack list
func slackList(data interface{}) string {
if data == nil {
return defaultNone
}
var b strings.Builder
const sliceItemFormat = "\n- %v"
const mapItemFormat = "\n- %v: %v"
switch reflect.TypeOf(data).Kind() {
case reflect.Slice:
s := reflect.ValueOf(data)
if s.Len() == 0 {
return defaultNone
}
// example:
// - foo
// - bar
for i := 0; i < s.Len(); i++ {
fmt.Fprintf(&b, sliceItemFormat, s.Index(i).Interface())
}
return b.String()
case reflect.Map:
m := reflect.ValueOf(data)
if m.Len() == 0 {
return defaultNone
}
// example:
// - foo: value
// - bar: value
for _, k := range m.MapKeys() {
v := m.MapIndex(k)
fmt.Fprintf(&b, mapItemFormat, k.Interface(), v.Interface())
}
return b.String()
}
// We don't return an error so that the custom slack message is still returned
// in this way, the user will know they didn't pass the correct input type to slackList
return "ERR_INPUT_NOT_SLICE_OR_MAP"
}
| 1 | 10,357 | let's move this into `slack_helper.go` | lyft-clutch | go |
@@ -54,7 +54,7 @@ class Azure(base.Base):
driver:
name: azure
ssh_connection_options:
- -o ControlPath=~/.ansible/cp/%r@%h-%p
+ - '-o ControlPath=~/.ansible/cp/%r@%h-%p'
.. important::
| 1 | # Copyright (c) 2015-2018 Cisco Systems, Inc.
#
# 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.
from molecule import logger
from molecule.driver import base
from molecule import util
LOG = logger.get_logger(__name__)
class Azure(base.Base):
"""
The class responsible for managing `Azure`_ instances. `Azure`_
is ``not`` the default driver used in Molecule.
Molecule leverages Ansible's `azure_module`_, by mapping variables
from ``molecule.yml`` into ``create.yml`` and ``destroy.yml``.
.. _`azure_module`: https://docs.ansible.com/ansible/latest/guide_azure.html
.. code-block:: yaml
driver:
name: azure
platforms:
- name: instance
.. code-block:: bash
$ pip install 'ansible[azure]'
Change the options passed to the ssh client.
.. code-block:: yaml
driver:
name: azure
ssh_connection_options:
-o ControlPath=~/.ansible/cp/%r@%h-%p
.. important::
Molecule does not merge lists, when overriding the developer must
provide all options.
Provide a list of files Molecule will preserve, relative to the scenario
ephemeral directory, after any ``destroy`` subcommand execution.
.. code-block:: yaml
driver:
name: azure
safe_files:
- foo
.. _`Azure`: https://azure.microsoft.com
""" # noqa
def __init__(self, config):
super(Azure, self).__init__(config)
self._name = 'azure'
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
@property
def login_cmd_template(self):
connection_options = ' '.join(self.ssh_connection_options)
return (
'ssh {{address}} '
'-l {{user}} '
'-p {{port}} '
'-i {{identity_file}} '
'{}'
).format(connection_options)
@property
def default_safe_files(self):
return [self.instance_config]
@property
def default_ssh_connection_options(self):
return self._get_ssh_connection_options()
def login_options(self, instance_name):
d = {'instance': instance_name}
return util.merge_dicts(d, self._get_instance_config(instance_name))
def ansible_connection_options(self, instance_name):
try:
d = self._get_instance_config(instance_name)
return {
'ansible_user': d['user'],
'ansible_host': d['address'],
'ansible_port': d['port'],
'ansible_private_key_file': d['identity_file'],
'connection': 'ssh',
'ansible_ssh_common_args': ' '.join(self.ssh_connection_options),
}
except StopIteration:
return {}
except IOError:
# Instance has yet to be provisioned , therefore the
# instance_config is not on disk.
return {}
def _get_instance_config(self, instance_name):
instance_config_dict = util.safe_load_file(self._config.driver.instance_config)
return next(
item for item in instance_config_dict if item['instance'] == instance_name
)
def sanity_checks(self):
# FIXME(decentral1se): Implement sanity checks
pass
| 1 | 9,942 | I doubt it will work, but without space between -o and ControlPath it should. Lets see. What I do not understand is why we did not see a failure on CI related to this? | ansible-community-molecule | py |
@@ -56,7 +56,7 @@ DiscreteBearing BearingClass::getDiscreteBearing(const double bearing)
{
BOOST_ASSERT(0. <= bearing && bearing <= 360.);
auto shifted_bearing = (bearing + 0.5 * discrete_step_size);
- if (shifted_bearing > 360.)
+ if (shifted_bearing >= 360.)
shifted_bearing -= 360;
return static_cast<DiscreteBearing>(shifted_bearing / discrete_step_size);
} | 1 | #include "util/guidance/bearing_class.hpp"
#include "util/bearing.hpp"
#include <algorithm>
#include <boost/assert.hpp>
namespace osrm
{
namespace util
{
namespace guidance
{
BearingClass::BearingClass() { available_bearings.reserve(10); }
bool BearingClass::operator==(const BearingClass &other) const
{
BOOST_ASSERT(std::is_sorted(available_bearings.begin(), available_bearings.end()));
BOOST_ASSERT(std::is_sorted(other.available_bearings.begin(), other.available_bearings.end()));
if (other.available_bearings.size() != available_bearings.size())
return false;
for (std::size_t i = 0; i < available_bearings.size(); ++i)
if (available_bearings[i] != other.available_bearings[i])
return false;
return true;
}
bool BearingClass::operator<(const BearingClass &other) const
{
BOOST_ASSERT(std::is_sorted(available_bearings.begin(), available_bearings.end()));
BOOST_ASSERT(std::is_sorted(other.available_bearings.begin(), other.available_bearings.end()));
if (available_bearings.size() < other.available_bearings.size())
return true;
if (available_bearings.size() > other.available_bearings.size())
return false;
for (std::size_t i = 0; i < available_bearings.size(); ++i)
{
if (available_bearings[i] < other.available_bearings[i])
return true;
if (available_bearings[i] > other.available_bearings[i])
return false;
}
return false;
}
void BearingClass::add(const DiscreteBearing bearing) { available_bearings.push_back(bearing); }
const std::vector<DiscreteBearing> &BearingClass::getAvailableBearings() const
{
return available_bearings;
}
DiscreteBearing BearingClass::getDiscreteBearing(const double bearing)
{
BOOST_ASSERT(0. <= bearing && bearing <= 360.);
auto shifted_bearing = (bearing + 0.5 * discrete_step_size);
if (shifted_bearing > 360.)
shifted_bearing -= 360;
return static_cast<DiscreteBearing>(shifted_bearing / discrete_step_size);
}
std::size_t BearingClass::findMatchingBearing(const double bearing) const
{
BOOST_ASSERT(!available_bearings.empty());
// the small size of the intersections allows a linear compare
auto discrete_bearing = static_cast<DiscreteBearing>(bearing);
auto max_element =
std::max_element(available_bearings.begin(),
available_bearings.end(),
[&](const DiscreteBearing first, const DiscreteBearing second) {
return angularDeviation(first, discrete_bearing) >
angularDeviation(second, discrete_bearing);
});
return std::distance(available_bearings.begin(), max_element);
}
} // namespace guidance
} // namespace extractor
} // namespace osrm
| 1 | 19,648 | this is the reason we might be seeing 360 as discrete bearing | Project-OSRM-osrm-backend | cpp |
@@ -72,6 +72,9 @@ from pylint.__pkginfo__ import version
from pylint.reporters.ureports import nodes as report_nodes
+FULL_VERSION = '%%(prog)s %s\nastroid %s\nPython %s' % (
+ version, astroid_version, sys.version)
+
MANAGER = astroid.MANAGER
| 1 | # -*- coding: utf-8 -*-
# Copyright (c) 2006-2015 LOGILAB S.A. (Paris, FRANCE) <[email protected]>
# Copyright (c) 2008 Fabrice Douchant <[email protected]>
# Copyright (c) 2009 Vincent
# Copyright (c) 2009 Mads Kiilerich <[email protected]>
# Copyright (c) 2011-2014 Google, Inc.
# Copyright (c) 2012 David Pursehouse <[email protected]>
# Copyright (c) 2012 Kevin Jing Qiu <[email protected]>
# Copyright (c) 2012 FELD Boris <[email protected]>
# Copyright (c) 2012 JT Olds <[email protected]>
# Copyright (c) 2014-2017 Claudiu Popa <[email protected]>
# Copyright (c) 2014-2015 Michal Nowikowski <[email protected]>
# Copyright (c) 2014 Brett Cannon <[email protected]>
# Copyright (c) 2014 Alexandru Coman <[email protected]>
# Copyright (c) 2014 Daniel Harding <[email protected]>
# Copyright (c) 2014 Arun Persaud <[email protected]>
# Copyright (c) 2014 Dan Goldsmith <[email protected]>
# Copyright (c) 2015-2016 Florian Bruhin <[email protected]>
# Copyright (c) 2015 Aru Sahni <[email protected]>
# Copyright (c) 2015 Steven Myint <[email protected]>
# Copyright (c) 2015 Simu Toni <[email protected]>
# Copyright (c) 2015 Mihai Balint <[email protected]>
# Copyright (c) 2015 Ionel Cristian Maries <[email protected]>
# Copyright (c) 2016-2017 Łukasz Rogalski <[email protected]>
# Copyright (c) 2016 Glenn Matthews <[email protected]>
# Copyright (c) 2016 Alan Evangelista <[email protected]>
# Copyright (c) 2017 Daniel Miller <[email protected]>
# Copyright (c) 2017 hippo91 <[email protected]>
# Copyright (c) 2017 Roman Ivanov <[email protected]>
# Copyright (c) 2017 Ned Batchelder <[email protected]>
# Copyright (c) 2017 Ville Skyttä <[email protected]>
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
# pylint: disable=broad-except
""" %prog [options] modules_or_packages
Check that module(s) satisfy a coding standard (and more !).
%prog --help
Display this help message and exit.
%prog --help-msg <msg-id>[,<msg-id>]
Display help messages about given message identifiers and exit.
"""
from __future__ import print_function
import collections
import contextlib
import operator
import os
import sys
import tokenize
import warnings
import six
import astroid
from astroid.__pkginfo__ import version as astroid_version
from astroid import modutils
from pylint import checkers
from pylint import interfaces
from pylint import reporters
from pylint import exceptions
from pylint import utils
from pylint import config
from pylint.__pkginfo__ import version
from pylint.reporters.ureports import nodes as report_nodes
MANAGER = astroid.MANAGER
def _get_python_path(filepath):
dirname = os.path.realpath(os.path.expanduser(filepath))
if not os.path.isdir(dirname):
dirname = os.path.dirname(dirname)
while True:
if not os.path.exists(os.path.join(dirname, "__init__.py")):
return dirname
old_dirname = dirname
dirname = os.path.dirname(dirname)
if old_dirname == dirname:
return os.getcwd()
return None
@contextlib.contextmanager
def _patch_sysmodules():
# Context manager that permits running pylint, on Windows, with -m switch
# and with --jobs, as in 'python -2 -m pylint .. --jobs'.
# For more details why this is needed,
# see Python issue http://bugs.python.org/issue10845.
mock_main = __name__ != '__main__' # -m switch
if mock_main:
sys.modules['__main__'] = sys.modules[__name__]
try:
yield
finally:
if mock_main:
sys.modules.pop('__main__')
# some reporting functions ####################################################
def report_total_messages_stats(sect, stats, previous_stats):
"""make total errors / warnings report"""
lines = ['type', 'number', 'previous', 'difference']
lines += checkers.table_lines_from_stats(stats, previous_stats,
('convention', 'refactor',
'warning', 'error'))
sect.append(report_nodes.Table(children=lines, cols=4, rheaders=1))
def report_messages_stats(sect, stats, _):
"""make messages type report"""
if not stats['by_msg']:
# don't print this report when we didn't detected any errors
raise exceptions.EmptyReportError()
in_order = sorted([(value, msg_id)
for msg_id, value in six.iteritems(stats['by_msg'])
if not msg_id.startswith('I')])
in_order.reverse()
lines = ('message id', 'occurrences')
for value, msg_id in in_order:
lines += (msg_id, str(value))
sect.append(report_nodes.Table(children=lines, cols=2, rheaders=1))
def report_messages_by_module_stats(sect, stats, _):
"""make errors / warnings by modules report"""
if len(stats['by_module']) == 1:
# don't print this report when we are analysing a single module
raise exceptions.EmptyReportError()
by_mod = collections.defaultdict(dict)
for m_type in ('fatal', 'error', 'warning', 'refactor', 'convention'):
total = stats[m_type]
for module in six.iterkeys(stats['by_module']):
mod_total = stats['by_module'][module][m_type]
if total == 0:
percent = 0
else:
percent = float((mod_total)*100) / total
by_mod[module][m_type] = percent
sorted_result = []
for module, mod_info in six.iteritems(by_mod):
sorted_result.append((mod_info['error'],
mod_info['warning'],
mod_info['refactor'],
mod_info['convention'],
module))
sorted_result.sort()
sorted_result.reverse()
lines = ['module', 'error', 'warning', 'refactor', 'convention']
for line in sorted_result:
# Don't report clean modules.
if all(entry == 0 for entry in line[:-1]):
continue
lines.append(line[-1])
for val in line[:-1]:
lines.append('%.2f' % val)
if len(lines) == 5:
raise exceptions.EmptyReportError()
sect.append(report_nodes.Table(children=lines, cols=5, rheaders=1))
# Python Linter class #########################################################
MSGS = {
'F0001': ('%s',
'fatal',
'Used when an error occurred preventing the analysis of a \
module (unable to find it for instance).'),
'F0002': ('%s: %s',
'astroid-error',
'Used when an unexpected error occurred while building the '
'Astroid representation. This is usually accompanied by a '
'traceback. Please report such errors !'),
'F0010': ('error while code parsing: %s',
'parse-error',
'Used when an exception occurred while building the Astroid '
'representation which could be handled by astroid.'),
'I0001': ('Unable to run raw checkers on built-in module %s',
'raw-checker-failed',
'Used to inform that a built-in module has not been checked '
'using the raw checkers.'),
'I0010': ('Unable to consider inline option %r',
'bad-inline-option',
'Used when an inline option is either badly formatted or can\'t '
'be used inside modules.'),
'I0011': ('Locally disabling %s (%s)',
'locally-disabled',
'Used when an inline option disables a message or a messages '
'category.'),
'I0012': ('Locally enabling %s (%s)',
'locally-enabled',
'Used when an inline option enables a message or a messages '
'category.'),
'I0013': ('Ignoring entire file',
'file-ignored',
'Used to inform that the file will not be checked'),
'I0020': ('Suppressed %s (from line %d)',
'suppressed-message',
'A message was triggered on a line, but suppressed explicitly '
'by a disable= comment in the file. This message is not '
'generated for messages that are ignored due to configuration '
'settings.'),
'I0021': ('Useless suppression of %s',
'useless-suppression',
'Reported when a message is explicitly disabled for a line or '
'a block of code, but never triggered.'),
'I0022': ('Pragma "%s" is deprecated, use "%s" instead',
'deprecated-pragma',
'Some inline pylint options have been renamed or reworked, '
'only the most recent form should be used. '
'NOTE:skip-all is only available with pylint >= 0.26',
{'old_names': [('I0014', 'deprecated-disable-all')]}),
'E0001': ('%s',
'syntax-error',
'Used when a syntax error is raised for a module.'),
'E0011': ('Unrecognized file option %r',
'unrecognized-inline-option',
'Used when an unknown inline option is encountered.'),
'E0012': ('Bad option value %r',
'bad-option-value',
'Used when a bad value for an inline option is encountered.'),
}
# pylint: disable=too-many-instance-attributes
class PyLinter(utils.MessagesHandlerMixIn,
checkers.BaseTokenChecker):
"""lint Python modules using external checkers.
This is the main checker controlling the other ones and the reports
generation. It is itself both a raw checker and an astroid checker in order
to:
* handle message activation / deactivation at the module level
* handle some basic but necessary stats'data (number of classes, methods...)
IDE plugin developers: you may have to call
`astroid.builder.MANAGER.astroid_cache.clear()` across runs if you want
to ensure the latest code version is actually checked.
"""
__implements__ = (interfaces.ITokenChecker, )
name = 'master'
priority = 0
level = 0
msgs = MSGS
options = (
('ignore',
{'type' : 'csv', 'metavar' : '<file>,...',
'dest' : 'black_list', 'default' : ('CVS',),
'help' : 'Add files or directories to the blacklist. '
'They should be base names, not paths.'}),
('ignore-patterns',
{'type' : 'regexp_csv', 'metavar' : '<pattern>,...',
'dest' : 'black_list_re', 'default' : (),
'help' : 'Add files or directories matching the regex patterns to the'
' blacklist. The regex matches against base names, not paths.'}),
('persistent',
{'default': True, 'type' : 'yn', 'metavar' : '<y_or_n>',
'level': 1,
'help' : 'Pickle collected data for later comparisons.'}),
('load-plugins',
{'type' : 'csv', 'metavar' : '<modules>', 'default' : (),
'level': 1,
'help' : 'List of plugins (as comma separated values of '
'python modules names) to load, usually to register '
'additional checkers.'}),
('output-format',
{'default': 'text', 'type': 'string', 'metavar' : '<format>',
'short': 'f',
'group': 'Reports',
'help' : 'Set the output format. Available formats are text,'
' parseable, colorized, json and msvs (visual studio).'
' You can also give a reporter class, e.g. mypackage.mymodule.'
'MyReporterClass.'}),
('reports',
{'default': False, 'type' : 'yn', 'metavar' : '<y_or_n>',
'short': 'r',
'group': 'Reports',
'help' : 'Tells whether to display a full report or only the '
'messages'}),
('evaluation',
{'type' : 'string', 'metavar' : '<python_expression>',
'group': 'Reports', 'level': 1,
'default': '10.0 - ((float(5 * error + warning + refactor + '
'convention) / statement) * 10)',
'help' : 'Python expression which should return a note less '
'than 10 (10 is the highest note). You have access '
'to the variables errors warning, statement which '
'respectively contain the number of errors / '
'warnings messages and the total number of '
'statements analyzed. This is used by the global '
'evaluation report (RP0004).'}),
('score',
{'default': True, 'type': 'yn', 'metavar': '<y_or_n>',
'short': 's',
'group': 'Reports',
'help': 'Activate the evaluation score.'}),
('confidence',
{'type' : 'multiple_choice', 'metavar': '<levels>',
'default': '',
'choices': [c.name for c in interfaces.CONFIDENCE_LEVELS],
'group': 'Messages control',
'help' : 'Only show warnings with the listed confidence levels.'
' Leave empty to show all. Valid levels: %s' % (
', '.join(c.name for c in interfaces.CONFIDENCE_LEVELS),)}),
('enable',
{'type' : 'csv', 'metavar': '<msg ids>',
'short': 'e',
'group': 'Messages control',
'help' : 'Enable the message, report, category or checker with the '
'given id(s). You can either give multiple identifier '
'separated by comma (,) or put this option multiple time '
'(only on the command line, not in the configuration file '
'where it should appear only once). '
'See also the "--disable" option for examples. '}),
('disable',
{'type' : 'csv', 'metavar': '<msg ids>',
'short': 'd',
'group': 'Messages control',
'help' : 'Disable the message, report, category or checker '
'with the given id(s). You can either give multiple identifiers'
' separated by comma (,) or put this option multiple times '
'(only on the command line, not in the configuration file '
'where it should appear only once).'
'You can also use "--disable=all" to disable everything first '
'and then reenable specific checks. For example, if you want '
'to run only the similarities checker, you can use '
'"--disable=all --enable=similarities". '
'If you want to run only the classes checker, but have no '
'Warning level messages displayed, use'
'"--disable=all --enable=classes --disable=W"'}),
('msg-template',
{'type' : 'string', 'metavar': '<template>', 'default': '',
'group': 'Reports',
'help' : ('Template used to display messages. '
'This is a python new-style format string '
'used to format the message information. '
'See doc for all details')
}),
('jobs',
{'type' : 'int', 'metavar': '<n-processes>',
'short': 'j',
'default': 1,
'help' : '''Use multiple processes to speed up Pylint.''',
}),
('unsafe-load-any-extension',
{'type': 'yn', 'metavar': '<yn>', 'default': False, 'hide': True,
'help': ('Allow loading of arbitrary C extensions. Extensions'
' are imported into the active Python interpreter and'
' may run arbitrary code.')}),
('extension-pkg-whitelist',
{'type': 'csv', 'metavar': '<pkg>,...', 'default': [],
'help': ('A comma-separated list of package or module names'
' from where C extensions may be loaded. Extensions are'
' loading into the active Python interpreter and may run'
' arbitrary code')}),
('suggestion-mode',
{'type': 'yn', 'metavar': '<yn>', 'default': True,
'help': ('When enabled, pylint would attempt to guess common '
'misconfiguration and emit user-friendly hints instead '
'of false-positive error messages')}),
)
option_groups = (
('Messages control', 'Options controlling analysis messages'),
('Reports', 'Options related to output formatting and reporting'),
)
reports = (
('RP0001', 'Messages by category',
report_total_messages_stats),
('RP0002', '% errors / warnings by module',
report_messages_by_module_stats),
('RP0003', 'Messages',
report_messages_stats),
)
def __init__(self, config=None):
# some stuff has to be done before ancestors initialization...
#
# messages store / checkers / reporter / astroid manager
self.config = config
self._checkers = collections.defaultdict(list)
self._pragma_lineno = {}
self._ignore_file = False
# visit variables
self.current_name = None
self.current_file = None
# TODO: Runner needs to give this to parser?
full_version = '%%prog %s\nastroid %s\nPython %s' % (
version, astroid_version, sys.version)
super().__init__()
# provided reports
self._dynamic_plugins = set()
self._python3_porting_mode = False
self._error_mode = False
# checkers manipulation methods ############################################
def disable_noerror_messages(self):
for msgcat, msgids in six.iteritems(self.msgs_store._msgs_by_category):
# enable only messages with 'error' severity and above ('fatal')
if msgcat in ['E', 'F']:
for msgid in msgids:
self.enable(msgid)
else:
for msgid in msgids:
self.disable(msgid)
def error_mode(self):
"""error mode: enable only errors; no reports, no persistent"""
self._error_mode = True
self.disable_noerror_messages()
self.disable('miscellaneous')
if self._python3_porting_mode:
self.disable('all')
for msg_id in self._checker_messages('python3'):
if msg_id.startswith('E'):
self.enable(msg_id)
config_parser = self.cfgfile_parser
if config_parser.has_option('MESSAGES CONTROL', 'disable'):
value = config_parser.get('MESSAGES CONTROL', 'disable')
self.global_set_option('disable', value)
else:
self.disable('python3')
def python3_porting_mode(self):
"""Disable all other checkers and enable Python 3 warnings."""
self.disable('all')
self.enable('python3')
if self._error_mode:
# The error mode was activated, using the -E flag.
# So we'll need to enable only the errors from the
# Python 3 porting checker.
for msg_id in self._checker_messages('python3'):
if msg_id.startswith('E'):
self.enable(msg_id)
else:
self.disable(msg_id)
config_parser = self.cfgfile_parser
if config_parser.has_option('MESSAGES CONTROL', 'disable'):
value = config_parser.get('MESSAGES CONTROL', 'disable')
self.global_set_option('disable', value)
self._python3_porting_mode = True
# block level option handling #############################################
#
# see func_block_disable_msg.py test case for expected behaviour
def process_tokens(self, tokens):
"""process tokens from the current module to search for module/block
level options
"""
options_methods = {
'enable': self.enable,
'disable': self.disable,
}
control_pragmas = {'disable', 'enable'}
for (tok_type, content, start, _, _) in tokens:
if tok_type != tokenize.COMMENT:
continue
match = utils.OPTION_RGX.search(content)
if match is None:
continue
if match.group(1).strip() == "disable-all" or \
match.group(1).strip() == 'skip-file':
if match.group(1).strip() == "disable-all":
self.add_message('deprecated-pragma', line=start[0],
args=('disable-all', 'skip-file'))
self.add_message('file-ignored', line=start[0])
self._ignore_file = True
return
try:
opt, value = match.group(1).split('=', 1)
except ValueError:
self.add_message('bad-inline-option', args=match.group(1).strip(),
line=start[0])
continue
opt = opt.strip()
if opt in options_methods:
meth = options_methods[opt]
for msgid in utils._splitstrip(value):
# Add the line where a control pragma was encountered.
if opt in control_pragmas:
self._pragma_lineno[msgid] = start[0]
try:
if (opt, msgid) == ('disable', 'all'):
self.add_message('deprecated-pragma', line=start[0],
args=('disable=all', 'skip-file'))
self.add_message('file-ignored', line=start[0])
self._ignore_file = True
return
comments_sharp_sep = content.split('#')[1:]
first_comment = "#" + comments_sharp_sep[0]
first_comment_match_disable = utils.OPTION_RGX.search(first_comment)
# Deactivate msg emission for whole module only if
# we are sure the disable directive is the first comment.
# If not then it refers to the comment before
# and not to the module itself.
if first_comment_match_disable:
meth(msgid, 'module', start[0])
except exceptions.UnknownMessageError:
self.add_message('bad-option-value', args=msgid, line=start[0])
else:
self.add_message('unrecognized-inline-option', args=opt, line=start[0])
# code checking methods ###################################################
# pylint: disable=unused-argument
@staticmethod
def should_analyze_file(modname, path, is_argument=False):
"""Returns whether or not a module should be checked.
This implementation returns True for all python source file, indicating
that all files should be linted.
Subclasses may override this method to indicate that modules satisfying
certain conditions should not be linted.
:param str modname: The name of the module to be checked.
:param str path: The full path to the source code of the module.
:param bool is_argument: Whetter the file is an argument to pylint or not.
Files which respect this property are always
checked, since the user requested it explicitly.
:returns: True if the module should be checked.
:rtype: bool
"""
if is_argument:
return True
return path.endswith('.py')
# pylint: enable=unused-argument
def _init_msg_states(self):
for msg in self.msgs_store.messages:
if not msg.may_be_emitted():
self._msgs_state[msg.msgid] = False
def check(self, files_or_modules, checkers_):
"""main checking entry: check a list of files or modules from their
name.
"""
# initialize msgs_state now that all messages have been registered into
# the store
self._init_msg_states()
if not isinstance(files_or_modules, (list, tuple)):
files_or_modules = (files_or_modules,)
self._do_check(files_or_modules, checkers_)
def _do_check(self, files_or_modules, checkers_):
walker = utils.PyLintASTWalker(self)
tokencheckers = [c for c in checkers_
if interfaces.implements(c, interfaces.ITokenChecker)
and c is not self]
rawcheckers = [c for c in checkers_
if interfaces.implements(c, interfaces.IRawChecker)]
# notify global begin
for checker in checkers_:
checker.open()
if interfaces.implements(checker, interfaces.IAstroidChecker):
walker.add_checker(checker)
# build ast and check modules or packages
expanded_files = utils.expand_files(
files_or_modules,
self,
self.config.black_list,
self.config.black_list_re
)
for module_desc in expanded_files:
modname = module_desc.name
filepath = module_desc.path
if not module_desc.isarg and not self.should_analyze_file(modname, filepath):
continue
self.set_current_module(modname, filepath)
# get the module representation
ast_node = self.get_ast(filepath, modname)
if ast_node is None:
continue
# XXX to be correct we need to keep module_msgs_state for every
# analyzed module (the problem stands with localized messages which
# are only detected in the .close step)
self.file_state = utils.FileState(module_desc.basename)
self._ignore_file = False
# fix the current file (if the source file was not available or
# if it's actually a c extension)
self.current_file = ast_node.file # pylint: disable=maybe-no-member
self.check_astroid_module(ast_node, walker, rawcheckers, tokencheckers)
# warn about spurious inline messages handling
spurious_messages = self.file_state.iter_spurious_suppression_messages(self.msgs_store)
for msgid, line, args in spurious_messages:
self.add_message(msgid, line, None, args)
# notify global end
self.stats['statement'] = walker.nbstatements
for checker in reversed(checkers_):
checker.close()
def set_current_module(self, modname, filepath=None):
"""set the name of the currently analyzed module and
init statistics for it
"""
if not modname and filepath is None:
return
self.reporter.on_set_current_module(modname, filepath)
self.current_name = modname
self.current_file = filepath or modname
self.stats['by_module'][modname] = {}
self.stats['by_module'][modname]['statement'] = 0
for msg_cat in six.itervalues(utils.MSG_TYPES):
self.stats['by_module'][modname][msg_cat] = 0
def get_ast(self, filepath, modname):
"""return an ast(roid) representation for a module"""
try:
return MANAGER.ast_from_file(filepath, modname, source=True)
except astroid.AstroidSyntaxError as ex:
# pylint: disable=no-member
self.add_message('syntax-error',
line=getattr(ex.error, 'lineno', 0),
args=str(ex.error))
except astroid.AstroidBuildingException as ex:
self.add_message('parse-error', args=ex)
except Exception as ex:
import traceback
traceback.print_exc()
self.add_message('astroid-error', args=(ex.__class__, ex))
def check_astroid_module(self, ast_node, walker,
rawcheckers, tokencheckers):
"""Check a module from its astroid representation."""
try:
tokens = utils.tokenize_module(ast_node)
except tokenize.TokenError as ex:
self.add_message('syntax-error', line=ex.args[1][0], args=ex.args[0])
return None
if not ast_node.pure_python:
self.add_message('raw-checker-failed', args=ast_node.name)
else:
#assert astroid.file.endswith('.py')
# invoke ITokenChecker interface on self to fetch module/block
# level options
self.process_tokens(tokens)
if self._ignore_file:
return False
# walk ast to collect line numbers
self.file_state.collect_block_lines(self.msgs_store, ast_node)
# run raw and tokens checkers
for checker in rawcheckers:
checker.process_module(ast_node)
for checker in tokencheckers:
checker.process_tokens(tokens)
# generate events to astroid checkers
walker.walk(ast_node)
return True
# IAstroidChecker interface #################################################
def open(self):
"""initialize counters"""
self.stats = {
'by_module': {},
'by_msg': {},
}
MANAGER.always_load_extensions = self.config.unsafe_load_any_extension
MANAGER.extension_package_whitelist.update(
self.config.extension_pkg_whitelist)
for msg_cat in six.itervalues(utils.MSG_TYPES):
self.stats[msg_cat] = 0
# utilities ###################################################################
@contextlib.contextmanager
def fix_import_path(args):
"""Prepare sys.path for running the linter checks.
Within this context, each of the given arguments is importable.
Paths are added to sys.path in corresponding order to the arguments.
We avoid adding duplicate directories to sys.path.
`sys.path` is reset to its original value upon exiting this context.
"""
orig = list(sys.path)
changes = []
for arg in args:
path = _get_python_path(arg)
if path in changes:
continue
else:
changes.append(path)
sys.path[:] = changes + ["."] + sys.path
try:
yield
finally:
sys.path[:] = orig
def guess_lint_path(args):
"""Attempt to determine the file being linted from a list of arguments.
:param args: The list of command line arguments to guess from.
:type args: list(str)
:returns: The path to file being linted if it can be guessed.
None otherwise.
:rtype: str or None
"""
value = None
# We only care if it's a path. If it's a module,
# we can't get a config from it
if args and os.path.exists(args[-1]):
value = args[-1]
return value
# TODO: Split the ReportsHandlerMixIn, keeping register methods here,
# and moving report_order and make_reports to the runner.
class PluginRegistry(utils.ReportsHandlerMixIn):
"""A class to register checkers to."""
def __init__(self, linter, register_options=(lambda options: None)):
super(PluginRegistry, self).__init__()
self.register_options = register_options
self._checkers = collections.defaultdict(list)
# TODO: Remove. This is needed for the MessagesHandlerMixIn for now.
linter._checkers = self._checkers
self._reporters = {}
self._linter = linter
for r_id, r_title, r_cb in linter.reports:
self.register_post_report(r_id, r_title, r_cb)
self.register_options(linter.options)
# TODO: Move elsewhere
linter.msgs_store.register_messages(linter)
def for_all_checkers(self):
"""Loop through all registered checkers.
:returns: Each registered checker.
:rtype: iterable(BaseChecker)
"""
for checkers in self._checkers.values():
yield from checkers
def register_checker(self, checker):
"""Register a checker.
:param checker: The checker to register.
:type checker: BaseChecker
:raises InvalidCheckerError: If the priority of the checker is
invalid.
"""
existing_checker_types = set(
type(existing_checker)
for name_checkers in self._checkers.values()
for existing_checker in name_checkers
)
checker_type = type(checker)
if checker_type in existing_checker_types:
msg_fmt = (
'Not registering checker {}. A checker of type {} has '
'already been registered.'
)
msg = msg_fmt.format(checker.name, checker_type.__name__)
warnings.warn(msg)
return
if checker.priority > 0:
msg = '{}.priority must be <= 0'.format(checker.__class__)
raise exceptions.InvalidCheckerError(msg)
self._checkers[checker.name].append(checker)
for r_id, r_title, r_cb in checker.reports:
self.register_report(r_id, r_title, r_cb, checker)
self.register_options(checker.options)
# TODO: Move elsewhere
if hasattr(checker, 'msgs'):
self._linter.msgs_store.register_messages(checker)
# Register the checker, but disable all of its messages.
# TODO(cpopa): we should have a better API for this.
if not getattr(checker, 'enabled', True):
self._linter.disable(checker.name)
def register_reporter(self, reporter_class):
if reporter_class.name in self._reporters:
# TODO: Raise if classes are the same
duplicate = self._reporters[reporter_class.name]
msg = 'A reporter called {} has already been registered ({}).'
msg = msg.format(reporter.name, duplicate.__class__)
warnings.warn(msg)
self._reporters[reporter_class.name] = reporter_class
# For now simply defer missing attributes to the linter,
# until we know what API we want.
def __getattr__(self, attribute):
return getattr(self._linter, attribute)
class Runner(object):
"""A class to manager how the linter runs."""
option_definitions = ()
"""The runner specific configuration options.
:type: set(OptionDefinition)
"""
class CLIRunner(Runner):
option_definitions = (
('rcfile',
{'type': 'string', 'metavar': '<file>',
'help' : 'Specify a configuration file.'}),
('init-hook',
{'type' : 'string', 'metavar': '<code>',
'level': 1,
'help' : 'Python code to execute, usually for sys.path '
'manipulation such as pygtk.require().'}),
('help-msg',
{'type' : 'string', 'metavar': '<msg-id>',
'group': 'Commands', 'default': None,
'help' : 'Display a help message for the given message id and '
'exit. The value may be a comma separated list of message ids.'}),
('list-msgs',
{'metavar': '<msg-id>',
'group': 'Commands', 'level': 1, 'default': None,
'help' : "Generate pylint's messages."}),
('list-conf-levels',
{'group': 'Commands', 'level': 1,
'action': 'store_true', 'default': False,
'help' : "Generate pylint's confidence levels."}),
('full-documentation',
{'metavar': '<msg-id>', 'default': None,
'group': 'Commands', 'level': 1,
'help' : "Generate pylint's full documentation."}),
('generate-rcfile',
{'group': 'Commands', 'action': 'store_true', 'default': False,
'help' : 'Generate a sample configuration file according to '
'the current configuration. You can put other options '
'before this one to get them in the generated '
'configuration.'}),
('generate-man',
{'group': 'Commands', 'action': 'store_true', 'default': False,
'help' : "Generate pylint's man page.", 'hide': True}),
('errors-only',
{'short': 'E', 'action': 'store_true', 'default': False,
'help' : 'In error mode, checkers without error messages are '
'disabled and for others, only the ERROR messages are '
'displayed, and no reports are done by default'''}),
('py3k',
{'action': 'store_true', 'default': False,
'help' : 'In Python 3 porting mode, all checkers will be '
'disabled and only messages emitted by the porting '
'checker will be displayed'}),
)
option_groups = (
('Commands', 'Options which are actually commands. Options in this \
group are mutually exclusive.'),
)
description = (
'pylint [options] module_or_package\n'
'\n'
' Check that a module satisfies a coding standard (and more !).\n'
'\n'
' pylint --help\n'
'\n'
' Display this help message and exit.\n'
'\n'
' pylint --help-msg <msg-id>[,<msg-id>]\n'
'\n'
' Display help messages about given message identifiers and exit.\n'
)
def __init__(self):
super().__init__()
self._linter = PyLinter()
self._plugin_registry = PluginRegistry(self._linter)
self._loaded_plugins = set()
self._global_config = config.Configuration()
self._reporter = None
def run(self, args):
# Phase 1: Preprocessing
option_definitions = self.option_definitions + PyLinter.options
parser = config.CLIParser(self.description)
parser.add_option_definitions(option_definitions)
parser.add_help_section('Environment variables', config.ENV_HELP, level=1)
# pylint: disable=bad-continuation
parser.add_help_section('Output',
'Using the default text output, the message format is : \n'
' \n'
' MESSAGE_TYPE: LINE_NUM:[OBJECT:] MESSAGE \n'
' \n'
'There are 5 kind of message types : \n'
' * (C) convention, for programming standard violation \n'
' * (R) refactor, for bad code smell \n'
' * (W) warning, for python specific problems \n'
' * (E) error, for probable bugs in the code \n'
' * (F) fatal, if an error occurred which prevented pylint from doing further\n'
'processing.\n'
, level=1)
parser.add_help_section('Output status code',
'Pylint should leave with following status code: \n'
' * 0 if everything went fine \n'
' * 1 if a fatal message was issued \n'
' * 2 if an error message was issued \n'
' * 4 if a warning message was issued \n'
' * 8 if a refactor message was issued \n'
' * 16 if a convention message was issued \n'
' * 32 on usage error \n'
' \n'
'status 1 to 16 will be bit-ORed so you can know which different categories has\n'
'been issued by analysing pylint output status code\n',
level=1)
self._global_config.add_options(option_definitions)
self._linter.config = self._global_config
parsed = parser.preprocess(
args,
'init_hook',
'rcfile',
'load_plugins',
'ignore',
'ignore_patterns',
)
# Call init-hook
if parsed.init_hook:
exec(parsed.init_hook)
# Load rcfile, else system rcfile
file_parser = config.IniFileParser()
file_parser.add_option_definitions(PyLinter.options)
rcfile = parsed.rcfile or config.PYLINTRC
if rcfile:
file_parser.parse(rcfile, self._global_config)
def register_options(options):
self._global_config.add_options(options)
parser.add_option_definitions(options)
file_parser.add_option_definitions(options)
self._plugin_registry.register_options = register_options
checkers.initialize(self._plugin_registry)
# Load plugins from CLI
plugins = parsed.load_plugins or []
for plugin in plugins:
self.load_plugin(plugin)
# TODO: This is for per directory config support (#618)
# Phase 2: Discover more plugins found in config files
# Walk and discover config files, watching for blacklists as we go
# Load plugins from config files
# Phase 3: Full load
# Fully load config files
if rcfile:
file_parser.parse(rcfile, self._global_config)
# Fully load CLI into global config
parser.parse(args, self._global_config)
if self._global_config.generate_rcfile:
file_parser.write()
sys.exit(0)
# TODO: if global_config.generate_man
if self._global_config.errors_only:
self._linter.error_mode()
self._global_config.reports = False
self._global_config.persistent = False
self._global_config.score = False
if self._global_config.py3k:
self._linter.python3_porting_mode()
if self._global_config.full_documentation:
self._linter.print_full_documentation()
sys.exit(0)
if self._global_config.list_conf_levels:
for level in interfaces.CONFIDENCE_LEVELS:
print('%-18s: %s' % level)
sys.exit(0)
if self._global_config.list_msgs:
self._linter.msgs_store.list_messages()
sys.exit(0)
if self._global_config.help_msg:
msg = utils._splitstrip(self._global_config.help_msg)
self._linter.msgs_store.help_message(msg)
sys.exit(0)
self.load_default_plugins()
self._linter.disable('I')
self._linter.enable('c-extension-no-member')
for checker in self._plugin_registry.for_all_checkers():
checker.config = self._global_config
if not self._global_config.reports:
self._plugin_registry.disable_reporters()
with fix_import_path(self._global_config.module_or_package):
assert self._global_config.jobs == 1
self._linter.check(
self._global_config.module_or_package, self.prepare_checkers(),
)
self.generate_reports()
sys.exit(self._linter.msg_status)
def load_plugin(self, module_name):
if module_name in self._loaded_plugins:
msg = 'Already loaded plugin {0}. Ignoring'.format(module_name)
warnings.warn(msg)
else:
module = astroid.modutils.load_module_from_name(module_name)
module.register(self._plugin_registry)
def load_plugins(self, module_names):
"""Load a plugin.
Args:
module_names (list(str)): The name of plugin modules to load.
"""
for module_name in module_names:
self.load_plugin(module_name)
def load_default_plugins(self):
"""Load all of the default plugins."""
reporters.initialize(self._plugin_registry)
# Make sure to load the default reporter, because
# the option has been set before the plugins had been loaded.
if not self._reporter:
self.load_reporter()
def load_reporter(self):
name = self._global_config.output_format.lower()
if name in self._plugin_registry._reporters:
self._reporter = self._plugin_registry._reporters[name]()
self._linter.reporter = self._reporter
# TODO: Remove the need to do this
self._reporter.linter = self._linter
else:
try:
reporter_class = self._load_reporter_class()
except (ImportError, AttributeError):
raise exceptions.InvalidReporterError(name)
else:
self._reporter = reporter_class()
self._linter.reporter = self._reporter
self._reporter.linter = self._linter
def _load_reporter_class(self):
qname = self._global_config.output_format
module = modutils.load_module_from_name(
modutils.get_module_part(qname)
)
class_name = qname.split('.')[-1]
reporter_class = getattr(module, class_name)
return reporter_class
def generate_reports(self):
"""close the whole package /module, it's time to make reports !
if persistent run, pickle results for later comparison
"""
# Display whatever messages are left on the reporter.
self._reporter.display_messages(report_nodes.Section())
if self._linter.file_state.base_name is not None:
# load previous results if any
previous_stats = config.load_results(self._linter.file_state.base_name)
# XXX code below needs refactoring to be more reporter agnostic
self._reporter.on_close(self._linter.stats, previous_stats)
if self._global_config.reports:
# TODO: The Runner should make reports, not the registry.
sect = self._plugin_registry.make_reports(self._linter.stats, previous_stats)
else:
sect = report_nodes.Section()
if self._global_config.reports:
self._reporter.display_reports(sect)
self._report_evaluation()
# save results if persistent run
if self._global_config.persistent:
config.save_results(self._linter.stats, self._linter.file_state.base_name)
else:
self._reporter.on_close(self._linter.stats, {})
def _report_evaluation(self):
"""make the global evaluation report"""
# check with at least check 1 statements (usually 0 when there is a
# syntax error preventing pylint from further processing)
previous_stats = config.load_results(self._linter.file_state.base_name)
if self._linter.stats['statement'] == 0:
return
# get a global note for the code
evaluation = self._global_config.evaluation
try:
note = eval(evaluation, {}, self._linter.stats) # pylint: disable=eval-used
except Exception as ex:
msg = 'An exception occurred while rating: %s' % ex
else:
self._linter.stats['global_note'] = note
msg = 'Your code has been rated at %.2f/10' % note
pnote = previous_stats.get('global_note')
if pnote is not None:
msg += ' (previous run: %.2f/10, %+.2f)' % (pnote, note - pnote)
if self._global_config.score:
sect = report_nodes.EvaluationSection(msg)
self._reporter.display_reports(sect)
def get_checkers(self):
"""return all available checkers as a list"""
return [self._linter] + [
c for c in self._plugin_registry.for_all_checkers() if c is not self._linter
]
def prepare_checkers(self):
"""return checkers needed for activated messages and reports"""
# get needed checkers
neededcheckers = [self._linter]
for checker in self.get_checkers()[1:]:
messages = set(msg for msg in checker.msgs
if self._linter.is_message_enabled(msg))
if (messages or
any(self._plugin_registry.report_is_enabled(r[0]) for r in checker.reports)):
neededcheckers.append(checker)
# Sort checkers by priority
neededcheckers = sorted(neededcheckers,
key=operator.attrgetter('priority'),
reverse=True)
return neededcheckers
if __name__ == '__main__':
CLIRunner().run(sys.argv[1:])
| 1 | 9,945 | `FULL_VERSION` is available at module level for others to use, but it won't have `%(prog)s` substituted with pylint. Will that be a problem. Also put it here instead of __pkginfo__ with other versions because it isn't pkginfo related. | PyCQA-pylint | py |
@@ -34,6 +34,7 @@ public abstract class BaseColumnIterator {
protected long triplesRead = 0L;
protected long advanceNextPageCount = 0L;
protected Dictionary dictionary;
+ protected long rowPosition;
protected BaseColumnIterator(ColumnDescriptor descriptor) {
this.desc = descriptor; | 1 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.iceberg.parquet;
import org.apache.parquet.column.ColumnDescriptor;
import org.apache.parquet.column.Dictionary;
import org.apache.parquet.column.page.DataPage;
import org.apache.parquet.column.page.PageReader;
@SuppressWarnings("checkstyle:VisibilityModifier")
public abstract class BaseColumnIterator {
protected final ColumnDescriptor desc;
// state reset for each row group
protected PageReader pageSource = null;
protected long triplesCount = 0L;
protected long triplesRead = 0L;
protected long advanceNextPageCount = 0L;
protected Dictionary dictionary;
protected BaseColumnIterator(ColumnDescriptor descriptor) {
this.desc = descriptor;
}
public void setPageSource(PageReader source) {
this.pageSource = source;
this.triplesCount = source.getTotalValueCount();
this.triplesRead = 0L;
this.advanceNextPageCount = 0L;
BasePageIterator pageIterator = pageIterator();
pageIterator.reset();
dictionary = ParquetUtil.readDictionary(desc, pageSource);
pageIterator.setDictionary(dictionary);
advance();
}
protected abstract BasePageIterator pageIterator();
protected void advance() {
if (triplesRead >= advanceNextPageCount) {
BasePageIterator pageIterator = pageIterator();
while (!pageIterator.hasNext()) {
DataPage page = pageSource.readPage();
if (page != null) {
pageIterator.setPage(page);
this.advanceNextPageCount += pageIterator.currentPageCount();
} else {
return;
}
}
}
}
public boolean hasNext() {
return triplesRead < triplesCount;
}
}
| 1 | 22,235 | Is this needed? I don't see any uses. | apache-iceberg | java |
@@ -29,6 +29,15 @@ func (c *Client) DeletePubSubOrFail(name string) {
}
}
+func (c *Client) DeleteBuildOrFail(name string) {
+ c.T.Helper()
+ builds := c.KnativeGCP.EventsV1alpha1().CloudBuildSources(c.Namespace)
+ err := builds.Delete(name, &metav1.DeleteOptions{})
+ if err != nil {
+ c.T.Fatalf("Failed to delete build %s/%s: %v", c.Namespace, name, err)
+ }
+}
+
func (c *Client) DeleteSchedulerOrFail(name string) {
c.T.Helper()
schedulers := c.KnativeGCP.EventsV1alpha1().CloudSchedulerSources(c.Namespace) | 1 | /*
Copyright 2020 Google LLC
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.
*/
package lib
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func (c *Client) DeletePubSubOrFail(name string) {
c.T.Helper()
pubsubs := c.KnativeGCP.EventsV1alpha1().CloudPubSubSources(c.Namespace)
err := pubsubs.Delete(name, &metav1.DeleteOptions{})
if err != nil {
c.T.Fatalf("Failed to delete pubsub %s/%s: %v", c.Namespace, name, err)
}
}
func (c *Client) DeleteSchedulerOrFail(name string) {
c.T.Helper()
schedulers := c.KnativeGCP.EventsV1alpha1().CloudSchedulerSources(c.Namespace)
err := schedulers.Delete(name, &metav1.DeleteOptions{})
if err != nil {
c.T.Fatalf("Failed to delete scheduler %s/%s: %v", c.Namespace, name, err)
}
}
func (c *Client) DeleteStorageOrFail(name string) {
c.T.Helper()
storages := c.KnativeGCP.EventsV1alpha1().CloudStorageSources(c.Namespace)
err := storages.Delete(name, &metav1.DeleteOptions{})
if err != nil {
c.T.Fatalf("Failed to delete storage %s/%s: %v", c.Namespace, name, err)
}
}
func (c *Client) DeleteAuditLogsOrFail(name string) {
c.T.Helper()
auditLogs := c.KnativeGCP.EventsV1alpha1().CloudAuditLogsSources(c.Namespace)
err := auditLogs.Delete(name, &metav1.DeleteOptions{})
if err != nil {
c.T.Fatalf("Failed to delete storage %s/%s: %v", c.Namespace, name, err)
}
}
func (c *Client) DeleteGCPBrokerOrFail(name string) {
c.T.Helper()
brokers := c.KnativeGCP.EventingV1beta1().Brokers(c.Namespace)
err := brokers.Delete(name, &metav1.DeleteOptions{})
if err != nil {
c.T.Fatalf("Failed to delete gcp broker %s/%s: %v", c.Namespace, name, err)
}
}
| 1 | 16,058 | Shouldn't this be V1beta1? | google-knative-gcp | go |
@@ -102,6 +102,13 @@ class Proposal < ActiveRecord::Base
approval
end
+ def remove_approver(email)
+ user = User.for_email(email)
+ approval = self.approvals.find_by(user_id: user.id)
+ CommunicartMailer.notification_for_approver_removed(email,approval)
+ approval.destroy
+ end
+
def initialize_approvals()
if self.linear? && self.approvals.any?
self.approvals.update_all(status: 'pending') | 1 | class Proposal < ActiveRecord::Base
include WorkflowModel
include ValueHelper
workflow do
state :pending do
# partial *may* trigger a full approval
event :partial_approve, transitions_to: :approved, if: lambda { |p| p.all_approved? }
event :partial_approve, transitions_to: :pending
event :approve, :transitions_to => :approved
event :reject, :transitions_to => :rejected
event :restart, :transitions_to => :pending
end
state :approved do
event :restart, :transitions_to => :pending
end
state :rejected do
# partial approvals and rejections can't break out of this state
event :partial_approve, :transitions_to => :rejected
event :reject, :transitions_to => :rejected
event :restart, :transitions_to => :pending
end
end
has_one :cart
has_many :approvals
has_many :approvers, through: :approvals, source: :user
has_many :api_tokens, through: :approvals
has_many :attachments
has_many :approval_delegates, through: :approvers, source: :outgoing_delegates
has_many :comments
has_many :observations
has_many :observers, through: :observations, source: :user
belongs_to :client_data, polymorphic: true
belongs_to :requester, class_name: 'User'
# The following list also servers as an interface spec for client_datas
# Note: clients may implement:
# :fields_for_display
# :public_identifier
# :version
# Note: clients should also implement :version
delegate :client, to: :client_data_legacy, allow_nil: true
validates :flow, presence: true, inclusion: {in: ApprovalGroup::FLOWS}
# TODO validates :requester_id, presence: true
self.statuses.each do |status|
scope status, -> { where(status: status) }
end
scope :closed, -> { where(status: ['approved', 'rejected']) }
after_initialize :set_defaults
after_create :update_public_id
def set_defaults
self.flow ||= 'parallel'
end
def parallel?
self.flow == 'parallel'
end
def linear?
self.flow == 'linear'
end
def delegate?(user)
self.approval_delegates.exists?(assignee_id: user.id)
end
def approval_for(user)
# TODO convert to SQL
self.approvals.find do |approval|
approver = approval.user
approver == user || approver.outgoing_delegates.exists?(assignee_id: user.id)
end
end
# Use this until all clients are migrated to models (and we no longer have a
# dependence on "Cart"
def client_data_legacy
self.client_data || self.cart
end
# TODO convert to an association
def delegates
self.approval_delegates.map(&:assignee)
end
# Returns a list of all users involved with the Proposal.
def users
# TODO use SQL
results = self.approvers + self.observers + self.delegates + [self.requester]
results.compact
end
# returns the Approval
def add_approver(email)
user = User.for_email(email)
approval = self.approvals.create!(user_id: user.id)
approval
end
def initialize_approvals()
if self.linear? && self.approvals.any?
self.approvals.update_all(status: 'pending')
self.approvals.first.make_actionable!
elsif self.parallel?
self.approvals.update_all(status: 'actionable')
end
end
def add_observer(email)
user = User.for_email(email)
self.observations.create!(user_id: user.id)
end
def add_requester(email)
user = User.for_email(email)
self.set_requester(user)
end
def set_requester(user)
self.update_attributes!(requester_id: user.id)
end
def currently_awaiting_approvals
self.approvals.actionable
end
def currently_awaiting_approvers
self.approvers.merge(self.currently_awaiting_approvals)
end
# delegated, with a fallback
# TODO refactor to class method in a module
def delegate_with_default(method)
data = self.client_data_legacy
result = nil
if data && data.respond_to?(method)
result = data.public_send(method)
end
if result.present?
result
elsif block_given?
yield
else
result
end
end
## delegated methods ##
def public_identifier
self.delegate_with_default(:public_identifier) { "##{self.id}" }
end
def name
self.delegate_with_default(:name) {
"Request #{self.public_identifier}"
}
end
def fields_for_display
# TODO better default
self.delegate_with_default(:fields_for_display) { [] }
end
# Be careful if altering the identifier. You run the risk of "expiring" all
# pending approval emails
def version
[
self.updated_at.to_i,
self.client_data_legacy.try(:version)
].compact.max
end
#######################
#### state machine methods ####
def on_rejected_entry(prev_state, event)
if prev_state.name != :rejected
Dispatcher.on_proposal_rejected(self)
end
end
def restart
# Note that none of the state machine's history is stored
self.api_tokens.update_all(expires_at: Time.now)
self.initialize_approvals()
Dispatcher.deliver_new_proposal_emails(self)
end
def all_approved?
self.approvals.where.not(status: 'approved').empty?
end
# An approval has been approved. Mark the next as actionable
# Note: this won't affect a parallel flow (as approvals start actionable)
def partial_approve
if next_approval = self.approvals.pending.first
next_approval.make_actionable!
end
end
protected
def update_public_id
self.update_attribute(:public_id, self.public_identifier)
end
end
| 1 | 13,461 | I think there's an `approval_for` | 18F-C2 | rb |
@@ -719,6 +719,8 @@ public interface Stack<T> extends LinearSeq<T> {
@Override
Stack<T> takeWhile(Predicate<? super T> predicate);
+ <U> U transform(Function<? super List<T>, ? extends U> f);
+
@Override
<U> Stack<U> unit(Iterable<? extends U> iterable);
| 1 | /* / \____ _ _ ____ ______ / \ ____ __ _ _____
* / / \/ \ / \/ \ / /\__\/ // \/ \ / / _ \ Javaslang
* _/ / /\ \ \/ / /\ \\__\\ \ // /\ \ /\\/ \__/ / Copyright 2014-now Daniel Dietrich
* /___/\_/ \_/\____/\_/ \_/\__\/__/___\_/ \_// \__/_____/ Licensed under the Apache License, Version 2.0
*/
package javaslang.collection;
import javaslang.Tuple2;
import javaslang.control.Match;
import javaslang.control.Option;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Objects;
import java.util.function.*;
import java.util.stream.Collector;
/**
* An immutable {@code Stack} stores elements allowing a last-in-first-out (LIFO) retrieval.
* <p>
* Stack API:
*
* <ul>
* <li>{@link #peek()}</li>
* <li>{@link #peekOption()}</li>
* <li>{@link #pop()}</li>
* <li>{@link #popOption()}</li>
* <li>{@link #pop2()}</li>
* <li>{@link #pop2Option()}</li>
* <li>{@link #push(Object)}</li>
* <li>{@link #push(Object[])}</li>
* <li>{@link #pushAll(Iterable)}</li>
* </ul>
*
* See Okasaki, Chris: <em>Purely Functional Data Structures</em> (p. 7 ff.). Cambridge, 2003.
*
* @param <T> component type
* @author Daniel Dietrich
* @since 2.0.0
*/
public interface Stack<T> extends LinearSeq<T> {
long serialVersionUID = 1L;
/**
* Returns a {@link java.util.stream.Collector} which may be used in conjunction with
* {@link java.util.stream.Stream#collect(java.util.stream.Collector)} to obtain a {@link javaslang.collection.Stack}
* .
*
* @param <T> Component type of the Stack.
* @return A javaslang.collection.Stack Collector.
*/
static <T> Collector<T, ArrayList<T>, Stack<T>> collector() {
final Supplier<ArrayList<T>> supplier = ArrayList::new;
final BiConsumer<ArrayList<T>, T> accumulator = ArrayList::add;
final BinaryOperator<ArrayList<T>> combiner = (left, right) -> {
left.addAll(right);
return left;
};
final Function<ArrayList<T>, Stack<T>> finisher = Stack::ofAll;
return Collector.of(supplier, accumulator, combiner, finisher);
}
/**
* Returns the empty Stack.
*
* @param <T> Component type
* @return The empty Stack.
*/
static <T> Stack<T> empty() {
return List.empty();
}
/**
* Narrows a widened {@code Stack<? extends T>} to {@code Stack<T>}
* by performing a type safe-cast. This is eligible because immutable/read-only
* collections are covariant.
*
* @param stack A {@code Stack}.
* @param <T> Component type of the {@code Stack}.
* @return the given {@code stack} instance as narrowed type {@code Stack<T>}.
*/
@SuppressWarnings("unchecked")
static <T> Stack<T> narrow(Stack<? extends T> stack) {
return (Stack<T>) stack;
}
/**
* Returns a singleton {@code Stack}, i.e. a {@code Stack} of one element.
*
* @param element An element.
* @param <T> The component type
* @return A new Stack instance containing the given element
*/
static <T> Stack<T> of(T element) {
return List.of(element);
}
/**
* Creates a Stack of the given elements.
*
* @param <T> Component type of the Stack.
* @param elements Zero or more elements.
* @return A stack containing the given elements in the same order.
* @throws NullPointerException if {@code elements} is null
*/
@SuppressWarnings("varargs")
@SafeVarargs
static <T> Stack<T> of(T... elements) {
Objects.requireNonNull(elements, "elements is null");
return List.of(elements);
}
/**
* Creates a Stack of the given elements.
*
* @param <T> Component type of the Stack.
* @param elements An Iterable of elements.
* @return A stack containing the given elements in the same order.
* @throws NullPointerException if {@code elements} is null
*/
@SuppressWarnings("unchecked")
static <T> Stack<T> ofAll(Iterable<? extends T> elements) {
Objects.requireNonNull(elements, "elements is null");
if (elements instanceof Stack) {
return (Stack<T>) elements;
} else {
return List.ofAll(elements);
}
}
/**
* Creates a Stack based on the elements of a boolean array.
*
* @param array a boolean array
* @return A new Stack of Boolean values
*/
static Stack<Boolean> ofAll(boolean[] array) {
Objects.requireNonNull(array, "array is null");
return List.ofAll(array);
}
/**
* Creates a Stack based on the elements of a byte array.
*
* @param array a byte array
* @return A new Stack of Byte values
*/
static Stack<Byte> ofAll(byte[] array) {
Objects.requireNonNull(array, "array is null");
return List.ofAll(array);
}
/**
* Creates a Stack based on the elements of a char array.
*
* @param array a char array
* @return A new Stack of Character values
*/
static Stack<Character> ofAll(char[] array) {
Objects.requireNonNull(array, "array is null");
return List.ofAll(array);
}
/**
* Creates a Stack based on the elements of a double array.
*
* @param array a double array
* @return A new Stack of Double values
*/
static Stack<Double> ofAll(double[] array) {
Objects.requireNonNull(array, "array is null");
return List.ofAll(array);
}
/**
* Creates a Stack based on the elements of a float array.
*
* @param array a float array
* @return A new Stack of Float values
*/
static Stack<Float> ofAll(float[] array) {
Objects.requireNonNull(array, "array is null");
return List.ofAll(array);
}
/**
* Creates a Stack based on the elements of an int array.
*
* @param array an int array
* @return A new Stack of Integer values
*/
static Stack<Integer> ofAll(int[] array) {
Objects.requireNonNull(array, "array is null");
return List.ofAll(array);
}
/**
* Creates a Stack based on the elements of a long array.
*
* @param array a long array
* @return A new Stack of Long values
*/
static Stack<Long> ofAll(long[] array) {
Objects.requireNonNull(array, "array is null");
return List.ofAll(array);
}
/**
* Creates a Stack based on the elements of a short array.
*
* @param array a short array
* @return A new Stack of Short values
*/
static Stack<Short> ofAll(short[] array) {
Objects.requireNonNull(array, "array is null");
return List.ofAll(array);
}
/**
* Returns a Stack containing {@code n} values of a given Function {@code f}
* over a range of integer values from 0 to {@code n - 1}.
*
* @param <T> Component type of the Stack
* @param n The number of elements in the Stack
* @param f The Function computing element values
* @return A Stack consisting of elements {@code f(0),f(1), ..., f(n - 1)}
* @throws NullPointerException if {@code f} is null
*/
static <T> Stack<T> tabulate(int n, Function<? super Integer, ? extends T> f) {
Objects.requireNonNull(f, "f is null");
return Collections.tabulate(n, f, Stack.empty(), Stack::of);
}
/**
* Returns a Stack containing {@code n} values supplied by a given Supplier {@code s}.
*
* @param <T> Component type of the Stack
* @param n The number of elements in the Stack
* @param s The Supplier computing element values
* @return A Stack of size {@code n}, where each element contains the result supplied by {@code s}.
* @throws NullPointerException if {@code s} is null
*/
static <T> Stack<T> fill(int n, Supplier<? extends T> s) {
Objects.requireNonNull(s, "s is null");
return Collections.fill(n, s, Stack.empty(), Stack::of);
}
static Stack<Character> range(char from, char toExclusive) {
return List.range(from, toExclusive);
}
static Stack<Character> rangeBy(char from, char toExclusive, int step) {
return List.rangeBy(from, toExclusive, step);
}
static Stack<Double> rangeBy(double from, double toExclusive, double step) {
return List.rangeBy(from, toExclusive, step);
}
/**
* Creates a Stack of int numbers starting from {@code from}, extending to {@code toExclusive - 1}.
* <p>
* Examples:
* <pre>
* <code>
* Stack.range(0, 0) // = Stack()
* Stack.range(2, 0) // = Stack()
* Stack.range(-2, 2) // = Stack(-2, -1, 0, 1)
* </code>
* </pre>
*
* @param from the first number
* @param toExclusive the last number + 1
* @return a range of int values as specified or the empty range if {@code from >= toExclusive}
*/
static Stack<Integer> range(int from, int toExclusive) {
return List.range(from, toExclusive);
}
/**
* Creates a Stack of int numbers starting from {@code from}, extending to {@code toExclusive - 1},
* with {@code step}.
* <p>
* Examples:
* <pre>
* <code>
* Stack.rangeBy(1, 3, 1) // = Stack(1, 2)
* Stack.rangeBy(1, 4, 2) // = Stack(1, 3)
* Stack.rangeBy(4, 1, -2) // = Stack(4, 2)
* Stack.rangeBy(4, 1, 2) // = Stack()
* </code>
* </pre>
*
* @param from the first number
* @param toExclusive the last number + 1
* @param step the step
* @return a range of long values as specified or the empty range if<br>
* {@code from >= toInclusive} and {@code step > 0} or<br>
* {@code from <= toInclusive} and {@code step < 0}
* @throws IllegalArgumentException if {@code step} is zero
*/
static Stack<Integer> rangeBy(int from, int toExclusive, int step) {
return List.rangeBy(from, toExclusive, step);
}
/**
* Creates a Stack of long numbers starting from {@code from}, extending to {@code toExclusive - 1}.
* <p>
* Examples:
* <pre>
* <code>
* Stack.range(0L, 0L) // = Stack()
* Stack.range(2L, 0L) // = Stack()
* Stack.range(-2L, 2L) // = Stack(-2L, -1L, 0L, 1L)
* </code>
* </pre>
*
* @param from the first number
* @param toExclusive the last number + 1
* @return a range of long values as specified or the empty range if {@code from >= toExclusive}
*/
static Stack<Long> range(long from, long toExclusive) {
return List.range(from, toExclusive);
}
/**
* Creates a Stack of long numbers starting from {@code from}, extending to {@code toExclusive - 1},
* with {@code step}.
* <p>
* Examples:
* <pre>
* <code>
* Stack.rangeBy(1L, 3L, 1L) // = Stack(1L, 2L)
* Stack.rangeBy(1L, 4L, 2L) // = Stack(1L, 3L)
* Stack.rangeBy(4L, 1L, -2L) // = Stack(4L, 2L)
* Stack.rangeBy(4L, 1L, 2L) // = Stack()
* </code>
* </pre>
*
* @param from the first number
* @param toExclusive the last number + 1
* @param step the step
* @return a range of long values as specified or the empty range if<br>
* {@code from >= toInclusive} and {@code step > 0} or<br>
* {@code from <= toInclusive} and {@code step < 0}
* @throws IllegalArgumentException if {@code step} is zero
*/
static Stack<Long> rangeBy(long from, long toExclusive, long step) {
return List.rangeBy(from, toExclusive, step);
}
static Stack<Character> rangeClosed(char from, char toInclusive) {
return List.rangeClosed(from, toInclusive);
}
static Stack<Character> rangeClosedBy(char from, char toInclusive, int step) {
return List.rangeClosedBy(from, toInclusive, step);
}
static Stack<Double> rangeClosedBy(double from, double toInclusive, double step) {
return List.rangeClosedBy(from, toInclusive, step);
}
/**
* Creates a Stack of int numbers starting from {@code from}, extending to {@code toInclusive}.
* <p>
* Examples:
* <pre>
* <code>
* Stack.rangeClosed(0, 0) // = Stack(0)
* Stack.rangeClosed(2, 0) // = Stack()
* Stack.rangeClosed(-2, 2) // = Stack(-2, -1, 0, 1, 2)
* </code>
* </pre>
*
* @param from the first number
* @param toInclusive the last number
* @return a range of int values as specified or the empty range if {@code from > toInclusive}
*/
static Stack<Integer> rangeClosed(int from, int toInclusive) {
return List.rangeClosed(from, toInclusive);
}
/**
* Creates a Stack of int numbers starting from {@code from}, extending to {@code toInclusive},
* with {@code step}.
* <p>
* Examples:
* <pre>
* <code>
* Stack.rangeClosedBy(1, 3, 1) // = Stack(1, 2, 3)
* Stack.rangeClosedBy(1, 4, 2) // = Stack(1, 3)
* Stack.rangeClosedBy(4, 1, -2) // = Stack(4, 2)
* Stack.rangeClosedBy(4, 1, 2) // = Stack()
* </code>
* </pre>
*
* @param from the first number
* @param toInclusive the last number
* @param step the step
* @return a range of int values as specified or the empty range if<br>
* {@code from > toInclusive} and {@code step > 0} or<br>
* {@code from < toInclusive} and {@code step < 0}
* @throws IllegalArgumentException if {@code step} is zero
*/
static Stack<Integer> rangeClosedBy(int from, int toInclusive, int step) {
return List.rangeClosedBy(from, toInclusive, step);
}
/**
* Creates a Stack of long numbers starting from {@code from}, extending to {@code toInclusive}.
* <p>
* Examples:
* <pre>
* <code>
* Stack.rangeClosed(0L, 0L) // = Stack(0L)
* Stack.rangeClosed(2L, 0L) // = Stack()
* Stack.rangeClosed(-2L, 2L) // = Stack(-2L, -1L, 0L, 1L, 2L)
* </code>
* </pre>
*
* @param from the first number
* @param toInclusive the last number
* @return a range of long values as specified or the empty range if {@code from > toInclusive}
*/
static Stack<Long> rangeClosed(long from, long toInclusive) {
return List.rangeClosed(from, toInclusive);
}
/**
* Creates a Stack of long numbers starting from {@code from}, extending to {@code toInclusive},
* with {@code step}.
* <p>
* Examples:
* <pre>
* <code>
* Stack.rangeClosedBy(1L, 3L, 1L) // = Stack(1L, 2L, 3L)
* Stack.rangeClosedBy(1L, 4L, 2L) // = Stack(1L, 3L)
* Stack.rangeClosedBy(4L, 1L, -2L) // = Stack(4L, 2L)
* Stack.rangeClosedBy(4L, 1L, 2L) // = Stack()
* </code>
* </pre>
*
* @param from the first number
* @param toInclusive the last number
* @param step the step
* @return a range of int values as specified or the empty range if<br>
* {@code from > toInclusive} and {@code step > 0} or<br>
* {@code from < toInclusive} and {@code step < 0}
* @throws IllegalArgumentException if {@code step} is zero
*/
static Stack<Long> rangeClosedBy(long from, long toInclusive, long step) {
return List.rangeClosedBy(from, toInclusive, step);
}
/**
* Returns the head element without modifying the Stack.
*
* @return the first element
* @throws java.util.NoSuchElementException if this Stack is empty
*/
T peek();
/**
* Returns the head element without modifying the Stack.
*
* @return {@code None} if this Stack is empty, otherwise a {@code Some} containing the head element
*/
Option<T> peekOption();
/**
* Removes the head element from this Stack.
*
* @return the elements of this Stack without the head element
* @throws java.util.NoSuchElementException if this Stack is empty
*/
Stack<T> pop();
/**
* Removes the head element from this Stack.
*
* @return {@code None} if this Stack is empty, otherwise a {@code Some} containing the elements of this Stack without the head element
*/
Option<? extends Stack<T>> popOption();
/**
* Removes the head element from this Stack.
*
* @return a tuple containing the head element and the remaining elements of this Stack
* @throws java.util.NoSuchElementException if this Stack is empty
*/
Tuple2<T, ? extends Stack<T>> pop2();
/**
* Removes the head element from this Stack.
*
* @return {@code None} if this Stack is empty, otherwise {@code Some} {@code Tuple} containing the head element and the remaining elements of this Stack
*/
Option<? extends Tuple2<T, ? extends Stack<T>>> pop2Option();
/**
* Pushes a new element on top of this Stack.
*
* @param element The new element
* @return a new {@code Stack} instance, containing the new element on top of this Stack
*/
Stack<T> push(T element);
/**
* Pushes the given elements on top of this Stack. A Stack has LIFO order, i.e. the last of the given elements is
* the first which will be retrieved.
*
* @param elements Elements, may be empty
* @return a new {@code Stack} instance, containing the new elements on top of this Stack
* @throws NullPointerException if elements is null
*/
@SuppressWarnings("unchecked")
Stack<T> push(T... elements);
/**
* Pushes the given elements on top of this Stack. A Stack has LIFO order, i.e. the last of the given elements is
* the first which will be retrieved.
*
* @param elements An Iterable of elements, may be empty
* @return a new {@code Stack} instance, containing the new elements on top of this Stack
* @throws NullPointerException if elements is null
*/
Stack<T> pushAll(Iterable<T> elements);
// -- Adjusted return types of Seq methods
@Override
Stack<T> append(T element);
@Override
Stack<T> appendAll(Iterable<? extends T> elements);
@Override
Stack<T> clear();
@Override
Stack<? extends Stack<T>> combinations();
@Override
Stack<? extends Stack<T>> combinations(int k);
@Override
Iterator<? extends Stack<T>> crossProduct(int power);
@Override
Stack<T> distinct();
@Override
Stack<T> distinctBy(Comparator<? super T> comparator);
@Override
<U> Stack<T> distinctBy(Function<? super T, ? extends U> keyExtractor);
@Override
Stack<T> drop(long n);
@Override
Stack<T> dropRight(long n);
@Override
Stack<T> dropUntil(Predicate<? super T> predicate);
@Override
Stack<T> dropWhile(Predicate<? super T> predicate);
@Override
Stack<T> filter(Predicate<? super T> predicate);
@Override
<U> Stack<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper);
@Override
<C> Map<C, ? extends Stack<T>> groupBy(Function<? super T, ? extends C> classifier);
@Override
Iterator<? extends Stack<T>> grouped(long size);
@Override
Stack<T> init();
@Override
Option<? extends Stack<T>> initOption();
@Override
Stack<T> insert(int index, T element);
@Override
Stack<T> insertAll(int index, Iterable<? extends T> elements);
@Override
Stack<T> intersperse(T element);
@Override
<U> Stack<U> map(Function<? super T, ? extends U> mapper);
@Override
Match.MatchValue.Of<? extends Stack<T>> match();
@Override
Stack<T> padTo(int length, T element);
@Override
Stack<T> patch(int from, Iterable<? extends T> that, int replaced);
@Override
Tuple2<? extends Stack<T>, ? extends Stack<T>> partition(Predicate<? super T> predicate);
@Override
Stack<T> peek(Consumer<? super T> action);
@Override
Stack<? extends Stack<T>> permutations();
@Override
Stack<T> prepend(T element);
@Override
Stack<T> prependAll(Iterable<? extends T> elements);
@Override
Stack<T> remove(T element);
@Override
Stack<T> removeFirst(Predicate<T> predicate);
@Override
Stack<T> removeLast(Predicate<T> predicate);
@Override
Stack<T> removeAt(int index);
@Override
Stack<T> removeAll(T element);
@Override
Stack<T> removeAll(Iterable<? extends T> elements);
@Override
Stack<T> replace(T currentElement, T newElement);
@Override
Stack<T> replaceAll(T currentElement, T newElement);
@Override
Stack<T> retainAll(Iterable<? extends T> elements);
@Override
Stack<T> reverse();
@Override
Stack<T> scan(T zero, BiFunction<? super T, ? super T, ? extends T> operation);
@Override
<U> Stack<U> scanLeft(U zero, BiFunction<? super U, ? super T, ? extends U> operation);
@Override
<U> Stack<U> scanRight(U zero, BiFunction<? super T, ? super U, ? extends U> operation);
@Override
Stack<T> slice(long beginIndex, long endIndex);
@Override
Iterator<? extends Stack<T>> sliding(long size);
@Override
Iterator<? extends Stack<T>> sliding(long size, long step);
@Override
Stack<T> sorted();
@Override
Stack<T> sorted(Comparator<? super T> comparator);
@Override
<U extends Comparable<? super U>> Stack<T> sortBy(Function<? super T, ? extends U> mapper);
@Override
<U> Stack<T> sortBy(Comparator<? super U> comparator, Function<? super T, ? extends U> mapper);
@Override
Tuple2<? extends Stack<T>, ? extends Stack<T>> span(Predicate<? super T> predicate);
@Override
Tuple2<? extends Stack<T>, ? extends Stack<T>> splitAt(long n);
@Override
Tuple2<? extends Stack<T>, ? extends Stack<T>> splitAt(Predicate<? super T> predicate);
@Override
Tuple2<? extends Stack<T>, ? extends Stack<T>> splitAtInclusive(Predicate<? super T> predicate);
@Override
Stack<T> subSequence(int beginIndex);
@Override
Stack<T> subSequence(int beginIndex, int endIndex);
@Override
Stack<T> tail();
@Override
Option<? extends Stack<T>> tailOption();
@Override
Stack<T> take(long n);
@Override
Stack<T> takeRight(long n);
@Override
Stack<T> takeUntil(Predicate<? super T> predicate);
@Override
Stack<T> takeWhile(Predicate<? super T> predicate);
@Override
<U> Stack<U> unit(Iterable<? extends U> iterable);
@Override
<T1, T2> Tuple2<? extends Stack<T1>, ? extends Stack<T2>> unzip(
Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper);
@Override
Stack<T> update(int index, T element);
@Override
<U> Stack<Tuple2<T, U>> zip(Iterable<U> that);
@Override
<U> Stack<Tuple2<T, U>> zipAll(Iterable<U> that, T thisElem, U thatElem);
@Override
Stack<Tuple2<T, Long>> zipWithIndex();
}
| 1 | 7,342 | Here we should use <code>List</code> in generic | vavr-io-vavr | java |
@@ -56,8 +56,7 @@ public final class BaselineReleaseCompatibility extends AbstractBaselinePlugin {
@Override
public Iterable<String> asArguments() {
- JavaVersion jdkVersion =
- JavaVersion.toVersion(javaCompile.getToolChain().getVersion());
+ JavaVersion jdkVersion = JavaVersion.toVersion(javaCompile.getTargetCompatibility());
if (!supportsReleaseFlag(jdkVersion)) {
log.debug(
"BaselineReleaseCompatibility is a no-op for {} in {} as {} doesn't support --release", | 1 | /*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* 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.
*/
package com.palantir.baseline.plugins;
import com.google.common.collect.ImmutableList;
import java.util.Collections;
import java.util.Optional;
import org.gradle.api.JavaVersion;
import org.gradle.api.Project;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.process.CommandLineArgumentProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* When using JDK 9+ to compile with a targetCompatibility less than JDK 9, this plugin adds compiler arguments per <a
* href="https://openjdk.java.net/jeps/247">JEP 247</a> to explicitly set the target JDK platform API to maintain binary
* compatibility.
*
* <p>See also <a href="https://github.com/gradle/gradle/issues/2510">Gradle JDK release issue</a>.
*/
public final class BaselineReleaseCompatibility extends AbstractBaselinePlugin {
private static final Logger log = LoggerFactory.getLogger(BaselineReleaseCompatibility.class);
@Override
public void apply(Project project) {
this.project = project;
project.getTasks().withType(JavaCompile.class).configureEach(javaCompile -> {
javaCompile.getOptions().getCompilerArgumentProviders().add(new ReleaseFlagProvider(javaCompile));
});
}
// using a lazy argument provider is crucial because otherwise we'd try to read sourceCompat / targetCompat
// before the user has even set it in their build.gradle!
private static final class ReleaseFlagProvider implements CommandLineArgumentProvider {
private final JavaCompile javaCompile;
private ReleaseFlagProvider(JavaCompile javaCompile) {
this.javaCompile = javaCompile;
}
@Override
public Iterable<String> asArguments() {
JavaVersion jdkVersion =
JavaVersion.toVersion(javaCompile.getToolChain().getVersion());
if (!supportsReleaseFlag(jdkVersion)) {
log.debug(
"BaselineReleaseCompatibility is a no-op for {} in {} as {} doesn't support --release",
javaCompile.getName(),
javaCompile.getProject(),
jdkVersion);
return Collections.emptyList();
}
// The java compiler does not allow using --add-exports in combination with --release
if (javaCompile.getOptions().getCompilerArgs().stream().anyMatch(arg -> arg.startsWith("--add-exports"))) {
log.debug(
"BaselineReleaseCompatibility is a no-op for {} in {} as --add-exports flag is also used",
javaCompile.getName(),
javaCompile.getProject());
return Collections.emptyList();
}
Optional<JavaVersion> taskTarget =
Optional.ofNullable(javaCompile.getTargetCompatibility()).map(JavaVersion::toVersion);
if (!taskTarget.isPresent()) {
log.debug(
"BaselineReleaseCompatibility is a no-op for {} in {} as no targetCompatibility is set",
javaCompile.getName(),
javaCompile.getProject());
return Collections.emptyList();
}
JavaVersion target = taskTarget.get();
if (jdkVersion.compareTo(target) <= 0) {
log.debug(
"BaselineReleaseCompatibility is a no-op for {} in {} as targetCompatibility is higher",
javaCompile.getName(),
javaCompile.getProject());
return Collections.emptyList();
}
return ImmutableList.of("--release", target.getMajorVersion());
}
// The --release flag was added in Java 9: https://openjdk.java.net/jeps/247
private static boolean supportsReleaseFlag(JavaVersion jdkVersion) {
return jdkVersion.isJava9Compatible();
}
}
}
| 1 | 9,161 | The `JavaCompile#getToolChain` method got removed and I am not sure what a good replacement is. I replaced it with `targetCompat` for now but they are not equivalent. Maybe we can use `JavaVersion#current` here? | palantir-gradle-baseline | java |
@@ -14,7 +14,7 @@ use Ergonode\SharedKernel\Domain\Aggregate\MultimediaId;
interface MultimediaQueryInterface
{
- public function fileExists(Hash $hash): bool;
+ public function fileExists(string $name): bool;
public function findIdByHash(Hash $hash): ?MultimediaId;
| 1 | <?php
/**
* Copyright © Ergonode Sp. z o.o. All rights reserved.
* See LICENSE.txt for license details.
*/
declare(strict_types=1);
namespace Ergonode\Multimedia\Domain\Query;
use Ergonode\Multimedia\Domain\ValueObject\Hash;
use Ergonode\SharedKernel\Domain\Aggregate\MultimediaId;
interface MultimediaQueryInterface
{
public function fileExists(Hash $hash): bool;
public function findIdByHash(Hash $hash): ?MultimediaId;
public function findIdByFilename(string $filename): ?MultimediaId;
/**
* @return array
*/
public function getAll(): array;
/**
* @return string[]
*/
public function getTypes(): array;
}
| 1 | 9,582 | The method name is incorrect. It does not check the existence of the file. I'd suggest deprecating both methods `fileExists` and `findIdByHash` and use findIdByFilename instead of fileExits | ergonode-backend | php |
@@ -336,6 +336,7 @@ static CALI_BPF_INLINE int calico_tc(struct __sk_buff *skb)
.reason = CALI_REASON_UNKNOWN,
};
struct calico_nat_dest *nat_dest = NULL;
+ __u8 nat_lvl1_drop = 0;
/* we assume we do FIB and from this point on, we only set it to false
* if we decide not to do it. | 1 | // Project Calico BPF dataplane programs.
// Copyright (c) 2020 Tigera, Inc. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#include <asm/types.h>
#include <linux/bpf.h>
#include <linux/pkt_cls.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/icmp.h>
#include <linux/in.h>
#include <linux/udp.h>
#include <linux/if_ether.h>
#include <iproute2/bpf_elf.h>
#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
#include "bpf.h"
#include "log.h"
#include "skb.h"
#include "policy.h"
#include "conntrack.h"
#include "nat.h"
#include "routes.h"
#include "jump.h"
#include "reasons.h"
#include "icmp.h"
#ifndef CALI_FIB_LOOKUP_ENABLED
#define CALI_FIB_LOOKUP_ENABLED true
#endif
#ifndef CALI_DROP_WORKLOAD_TO_HOST
#define CALI_DROP_WORKLOAD_TO_HOST false
#endif
#ifdef CALI_DEBUG_ALLOW_ALL
/* If we want to just compile the code without defining any policies and to
* avoid compiling out code paths that are not reachable if traffic is denied,
* we can compile it with allow all
*/
static CALI_BPF_INLINE enum calico_policy_result execute_policy_norm(struct __sk_buff *skb,
__u8 ip_proto, __u32 saddr, __u32 daddr, __u16 sport, __u16 dport)
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-label"
RULE_START(0);
RULE_END(0, allow);
return CALI_POL_NO_MATCH;
deny:
return CALI_POL_DENY;
allow:
return CALI_POL_ALLOW;
#pragma clang diagnostic pop
}
#else
static CALI_BPF_INLINE enum calico_policy_result execute_policy_norm(struct __sk_buff *skb,
__u8 ip_proto, __u32 saddr, __u32 daddr, __u16 sport, __u16 dport)
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-label"
RULE_START(0);
RULE_END(0, deny);
return CALI_POL_NO_MATCH;
deny:
return CALI_POL_DENY;
allow:
return CALI_POL_ALLOW;
#pragma clang diagnostic pop
}
#endif /* CALI_DEBUG_ALLOW_ALL */
__attribute__((section("1/0")))
int calico_tc_norm_pol_tail(struct __sk_buff *skb)
{
CALI_DEBUG("Entering normal policy tail call\n");
__u32 key = 0;
struct cali_tc_state *state = cali_v4_state_lookup_elem(&key);
if (!state) {
CALI_DEBUG("State map lookup failed: DROP\n");
goto deny;
}
state->pol_rc = execute_policy_norm(skb, state->ip_proto, state->ip_src,
state->ip_dst, state->sport, state->dport);
bpf_tail_call(skb, &cali_jump, 1);
CALI_DEBUG("Tail call to post-policy program failed: DROP\n");
deny:
return TC_ACT_SHOT;
}
struct fwd {
int res;
uint32_t mark;
enum calico_reason reason;
#if FIB_ENABLED
uint32_t fib_flags;
bool fib;
#endif
};
#if FIB_ENABLED
#define fwd_fib(fwd) ((fwd)->fib)
#define fwd_fib_set(fwd, v) ((fwd)->fib = v)
#define fwd_fib_set_flags(fwd, flags) ((fwd)->fib_flags = flags)
#else
#define fwd_fib(fwd) false
#define fwd_fib_set(fwd, v)
#define fwd_fib_set_flags(fwd, flags)
#endif
static CALI_BPF_INLINE struct fwd calico_tc_skb_accepted(struct __sk_buff *skb,
struct iphdr *ip_header,
struct cali_tc_state *state,
struct calico_nat_dest *nat_dest);
static CALI_BPF_INLINE int skb_nat_l4_csum_ipv4(struct __sk_buff *skb, size_t off,
__be32 ip_from, __be32 ip_to,
__u16 port_from, __u16 port_to,
uint64_t flags)
{
int ret = 0;
if (ip_from != ip_to) {
CALI_DEBUG("L4 checksum update (csum is at %d) IP from %x to %x\n", off,
be32_to_host(ip_from), be32_to_host(ip_to));
ret = bpf_l4_csum_replace(skb, off, ip_from, ip_to, flags | BPF_F_PSEUDO_HDR | 4);
CALI_DEBUG("bpf_l4_csum_replace(IP): %d\n", ret);
}
if (port_from != port_to) {
CALI_DEBUG("L4 checksum update (csum is at %d) port from %d to %d\n",
off, be16_to_host(port_from), be16_to_host(port_to));
int rc = bpf_l4_csum_replace(skb, off, port_from, port_to, flags | 2);
CALI_DEBUG("bpf_l4_csum_replace(port): %d\n", rc);
ret |= rc;
}
return ret;
}
static CALI_BPF_INLINE int forward_or_drop(struct __sk_buff *skb,
struct cali_tc_state *state,
struct fwd *fwd)
{
int rc = fwd->res;
enum calico_reason reason = fwd->reason;
if (rc == TC_ACT_SHOT) {
goto deny;
}
if (rc == CALI_RES_REDIR_IFINDEX) {
int redir_flags = 0;
if (CALI_F_FROM_HOST) {
redir_flags = BPF_F_INGRESS;
}
/* Revalidate the access to the packet */
if ((void *)(long)skb->data + sizeof(struct ethhdr) > (void *)(long)skb->data_end) {
reason = CALI_REASON_SHORT;
goto deny;
}
/* Swap the MACs as we are turning it back */
struct ethhdr *eth_hdr = (void *)(long)skb->data;
unsigned char mac[ETH_ALEN];
__builtin_memcpy(mac, ð_hdr->h_dest, ETH_ALEN);
__builtin_memcpy(ð_hdr->h_dest, ð_hdr->h_source, ETH_ALEN);
__builtin_memcpy(ð_hdr->h_source, mac, ETH_ALEN);
rc = bpf_redirect(skb->ifindex, redir_flags);
if (rc == TC_ACT_REDIRECT) {
CALI_DEBUG("Redirect to the same interface (%d) succeeded\n", skb->ifindex);
goto skip_fib;
}
CALI_DEBUG("Redirect to the same interface (%d) failed\n", skb->ifindex);
goto deny;
}
#if FIB_ENABLED
// Try a short-circuit FIB lookup.
if (fwd_fib(fwd)) {
/* XXX we might include the tot_len in the fwd, set it once when
* we get the ip_header the first time and only adjust the value
* when we modify the packet - to avoid geting the header here
* again - it is simpler though.
*/
if (skb_too_short(skb)) {
reason = CALI_REASON_SHORT;
CALI_DEBUG("Too short\n");
goto deny;
}
struct iphdr *ip_header = skb_iphdr(skb);
struct bpf_fib_lookup fib_params = {
.family = 2, /* AF_INET */
.tot_len = be16_to_host(ip_header->tot_len),
.ifindex = skb->ingress_ifindex,
.l4_protocol = state->ip_proto,
.sport = host_to_be16(state->sport),
.dport = host_to_be16(state->dport),
};
/* set the ipv4 here, otherwise the ipv4/6 unions do not get
* zeroed properly
*/
fib_params.ipv4_src = state->ip_src;
fib_params.ipv4_dst = state->ip_dst;
CALI_DEBUG("FIB family=%d\n", fib_params.family);
CALI_DEBUG("FIB tot_len=%d\n", fib_params.tot_len);
CALI_DEBUG("FIB ifindex=%d\n", fib_params.ifindex);
CALI_DEBUG("FIB l4_protocol=%d\n", fib_params.l4_protocol);
CALI_DEBUG("FIB sport=%d\n", be16_to_host(fib_params.sport));
CALI_DEBUG("FIB dport=%d\n", be16_to_host(fib_params.dport));
CALI_DEBUG("FIB ipv4_src=%x\n", be32_to_host(fib_params.ipv4_src));
CALI_DEBUG("FIB ipv4_dst=%x\n", be32_to_host(fib_params.ipv4_dst));
CALI_DEBUG("Traffic is towards the host namespace, doing Linux FIB lookup\n");
rc = bpf_fib_lookup(skb, &fib_params, sizeof(fib_params), fwd->fib_flags);
if (rc == 0) {
CALI_DEBUG("FIB lookup succeeded\n");
/* Since we are going to short circuit the IP stack on
* forward, check if TTL is still alive. If not, let the
* IP stack handle it. It was approved by policy, so it
* is safe.
*/
if ip_ttl_exceeded(ip_header) {
rc = TC_ACT_UNSPEC;
goto cancel_fib;
}
// Update the MACs. NAT may have invalidated pointer into the packet so need to
// revalidate.
if ((void *)(long)skb->data + sizeof(struct ethhdr) > (void *)(long)skb->data_end) {
reason = CALI_REASON_SHORT;
goto deny;
}
struct ethhdr *eth_hdr = (void *)(long)skb->data;
__builtin_memcpy(ð_hdr->h_source, fib_params.smac, sizeof(eth_hdr->h_source));
__builtin_memcpy(ð_hdr->h_dest, fib_params.dmac, sizeof(eth_hdr->h_dest));
// Redirect the packet.
CALI_DEBUG("Got Linux FIB hit, redirecting to iface %d.\n", fib_params.ifindex);
rc = bpf_redirect(fib_params.ifindex, 0);
/* now we know we will bypass IP stack and ip->ttl > 1, decrement it! */
if (rc == TC_ACT_REDIRECT) {
ip_dec_ttl(ip_header);
}
} else if (rc < 0) {
CALI_DEBUG("FIB lookup failed (bad input): %d.\n", rc);
rc = TC_ACT_UNSPEC;
} else {
CALI_DEBUG("FIB lookup failed (FIB problem): %d.\n", rc);
rc = TC_ACT_UNSPEC;
}
}
cancel_fib:
#endif /* FIB_ENABLED */
skip_fib:
if (CALI_F_TO_HOST) {
/* If we received the packet from the tunnel and we forward it to a
* workload we need to skip RPF check since there might be a better path
* for the packet if the host has multiple ifaces and might get dropped.
*
* XXX We should check ourselves that we got our tunnel packets only from
* XXX those devices where we expect them before we even decap.
*/
if (CALI_F_FROM_HEP && state->tun_ip != 0) {
fwd->mark = CALI_SKB_MARK_SKIP_RPF;
}
/* Packet is towards host namespace, mark it so that downstream
* programs know that they're not the first to see the packet.
*/
CALI_DEBUG("Traffic is towards host namespace, marking with %x.\n", fwd->mark);
/* FIXME: this ignores the mask that we should be using.
* However, if we mask off the bits, then clang spots that it
* can do a 16-bit store instead of a 32-bit load/modify/store,
* which trips up the validator.
*/
skb->mark = fwd->mark | CALI_SKB_MARK_SEEN; /* make sure that each pkt has SEEN mark */
}
if (CALI_LOG_LEVEL >= CALI_LOG_LEVEL_INFO) {
uint64_t prog_end_time = bpf_ktime_get_ns();
CALI_INFO("Final result=ALLOW (%d). Program execution time: %lluns\n",
rc, prog_end_time-state->prog_start_time);
}
return rc;
deny:
if (CALI_LOG_LEVEL >= CALI_LOG_LEVEL_INFO) {
uint64_t prog_end_time = bpf_ktime_get_ns();
CALI_INFO("Final result=DENY (%x). Program execution time: %lluns\n",
reason, prog_end_time-state->prog_start_time);
}
return TC_ACT_SHOT;
}
static CALI_BPF_INLINE int calico_tc(struct __sk_buff *skb)
{
struct cali_tc_state state = {};
struct fwd fwd = {
.res = TC_ACT_UNSPEC,
.reason = CALI_REASON_UNKNOWN,
};
struct calico_nat_dest *nat_dest = NULL;
/* we assume we do FIB and from this point on, we only set it to false
* if we decide not to do it.
*/
fwd_fib_set(&fwd, true);
if (CALI_LOG_LEVEL >= CALI_LOG_LEVEL_INFO) {
state.prog_start_time = bpf_ktime_get_ns();
}
state.tun_ip = 0;
#ifdef CALI_SET_SKB_MARK
/* workaround for test since bpftool run cannot set it in context, wont
* be necessary if fixed in kernel
*/
skb->mark = CALI_SET_SKB_MARK;
#endif
if (!CALI_F_TO_HOST && skb->mark == CALI_SKB_MARK_BYPASS) {
CALI_DEBUG("Packet pre-approved by another hook, allow.\n");
fwd.reason = CALI_REASON_BYPASS;
goto allow;
}
struct iphdr *ip_header;
if (CALI_F_TO_HEP || CALI_F_TO_WEP) {
switch (skb->mark) {
case CALI_SKB_MARK_BYPASS_FWD:
CALI_DEBUG("Packet approved for forward.\n");
fwd.reason = CALI_REASON_BYPASS;
goto allow;
case CALI_SKB_MARK_BYPASS_FWD_SRC_FIXUP:
CALI_DEBUG("Packet approved for forward - src ip fixup\n");
fwd.reason = CALI_REASON_BYPASS;
/* we need to fix up the right src host IP */
if (skb_too_short(skb)) {
fwd.reason = CALI_REASON_SHORT;
CALI_DEBUG("Too short\n");
goto deny;
}
ip_header = skb_iphdr(skb);
__be32 ip_src = ip_header->saddr;
if (ip_src == HOST_IP) {
CALI_DEBUG("src ip fixup not needed %x\n", be32_to_host(ip_src));
goto allow;
}
/* XXX do a proper CT lookup to find this */
ip_header->saddr = HOST_IP;
int l3_csum_off = skb_iphdr_offset(skb) + offsetof(struct iphdr, check);
int res = bpf_l3_csum_replace(skb, l3_csum_off, ip_src, HOST_IP, 4);
if (res) {
fwd.reason = CALI_REASON_CSUM_FAIL;
goto deny;
}
goto allow;
}
}
// Parse the packet.
// TODO Do we need to handle any odd-ball frames here (e.g. with a 0 VLAN header)?
switch (host_to_be16(skb->protocol)) {
case ETH_P_IP:
break;
case ETH_P_ARP:
CALI_DEBUG("ARP: allowing packet\n");
fwd_fib_set(&fwd, false);
goto allow;
case ETH_P_IPV6:
if (CALI_F_WEP) {
CALI_DEBUG("IPv6 from workload: drop\n");
return TC_ACT_SHOT;
} else {
// FIXME: support IPv6.
CALI_DEBUG("IPv6 on host interface: allow\n");
return TC_ACT_UNSPEC;
}
default:
if (CALI_F_WEP) {
CALI_DEBUG("Unknown ethertype (%x), drop\n", be16_to_host(skb->protocol));
goto deny;
} else {
CALI_DEBUG("Unknown ethertype on host interface (%x), allow\n",
be16_to_host(skb->protocol));
return TC_ACT_UNSPEC;
}
}
if (skb_too_short(skb)) {
fwd.reason = CALI_REASON_SHORT;
CALI_DEBUG("Too short\n");
goto deny;
}
ip_header = skb_iphdr(skb);
if (dnat_should_decap() && is_vxlan_tunnel(ip_header)) {
struct udphdr *udp_header = (void*)(ip_header+1);
/* decap on host ep only if directly for the node */
CALI_DEBUG("VXLAN tunnel packet to %x (host IP=%x)\n", ip_header->daddr, HOST_IP);
if (rt_addr_is_local_host(ip_header->daddr) &&
vxlan_udp_csum_ok(udp_header) &&
vxlan_size_ok(skb, udp_header) &&
vxlan_vni_is_valid(skb, udp_header) &&
vxlan_vni(skb, udp_header) == CALI_VXLAN_VNI) {
state.tun_ip = ip_header->saddr;
CALI_DEBUG("vxlan decap\n");
if (vxlan_v4_decap(skb)) {
fwd.reason = CALI_REASON_DECAP_FAIL;
goto deny;
}
if (skb_too_short(skb)) {
fwd.reason = CALI_REASON_SHORT;
CALI_DEBUG("Too short after VXLAN decap\n");
goto deny;
}
ip_header = skb_iphdr(skb);
CALI_DEBUG("vxlan decap origin %x\n", be32_to_host(state.tun_ip));
}
}
// Drop malformed IP packets
if (ip_header->ihl < 5) {
fwd.reason = CALI_REASON_IP_MALFORMED;
CALI_DEBUG("Drop malformed IP packets\n");
goto deny;
} else if (ip_header->ihl > 5) {
/* Drop packets with IP options from/to WEP.
* Also drop packets with IP options if the dest IP is not host IP
*/
if (CALI_F_WEP || (CALI_F_FROM_HEP && !rt_addr_is_local_host(ip_header->daddr))) {
fwd.reason = CALI_REASON_IP_OPTIONS;
CALI_DEBUG("Drop packets with IP options\n");
goto deny;
}
CALI_DEBUG("Allow packets with IP options and dst IP = hostIP\n");
goto allow;
}
// Setting all of these up-front to keep the verifier happy.
struct tcphdr *tcp_header = (void*)(ip_header+1);
struct udphdr *udp_header = (void*)(ip_header+1);
struct icmphdr *icmp_header = (void*)(ip_header+1);
tc_state_fill_from_iphdr(&state, ip_header);
switch (state.ip_proto) {
case IPPROTO_TCP:
// Re-check buffer space for TCP (has larger headers than UDP).
if (!skb_has_data_after(skb, ip_header, sizeof(struct tcphdr))) {
CALI_DEBUG("Too short for TCP: DROP\n");
goto deny;
}
state.sport = be16_to_host(tcp_header->source);
state.dport = be16_to_host(tcp_header->dest);
CALI_DEBUG("TCP; ports: s=%d d=%d\n", state.sport, state.dport);
break;
case IPPROTO_UDP:
state.sport = be16_to_host(udp_header->source);
state.dport = be16_to_host(udp_header->dest);
CALI_DEBUG("UDP; ports: s=%d d=%d\n", state.sport, state.dport);
break;
case IPPROTO_ICMP:
icmp_header = (void*)(ip_header+1);
CALI_DEBUG("ICMP; type=%d code=%d\n",
icmp_header->type, icmp_header->code);
break;
case 4:
// IPIP
if (CALI_F_HEP) {
// TODO IPIP whitelist.
CALI_DEBUG("IPIP: allow\n");
fwd_fib_set(&fwd, false);
goto allow;
}
default:
CALI_DEBUG("Unknown protocol (%d), unable to extract ports\n", (int)state.ip_proto);
}
state.pol_rc = CALI_POL_NO_MATCH;
switch (state.ip_proto) {
case IPPROTO_TCP:
case IPPROTO_UDP:
case IPPROTO_ICMP:
break;
default:
if (CALI_F_HEP) {
// FIXME: allow unknown protocols through on host endpoints.
goto allow;
}
// FIXME non-port based conntrack.
goto deny;
}
struct ct_ctx ct_lookup_ctx = {
.skb = skb,
.proto = state.ip_proto,
.src = state.ip_src,
.sport = state.sport,
.dst = state.ip_dst,
.dport = state.dport,
.tun_ip = state.tun_ip,
};
if (state.ip_proto == IPPROTO_TCP) {
if (!skb_has_data_after(skb, ip_header, sizeof(struct tcphdr))) {
CALI_DEBUG("Too short for TCP: DROP\n");
goto deny;
}
tcp_header = (void*)(ip_header+1);
ct_lookup_ctx.tcp = tcp_header;
}
/* Do conntrack lookup before anything else */
state.ct_result = calico_ct_v4_lookup(&ct_lookup_ctx);
/* check if someone is trying to spoof a tunnel packet */
if (CALI_F_FROM_HEP && ct_result_tun_src_changed(state.ct_result.rc)) {
CALI_DEBUG("dropping tunnel pkt with changed source node\n");
goto deny;
}
if (state.ct_result.flags & CALI_CT_FLAG_NAT_OUT) {
state.flags |= CALI_ST_NAT_OUTGOING;
}
/* We are possibly past (D)NAT, but that is ok, we need to let the IP
* stack do the RPF check on the source, dest is not importatnt.
*/
if (CALI_F_TO_HOST && ct_result_rpf_failed(state.ct_result.rc)) {
fwd_fib_set(&fwd, false);
}
/* skip policy if we get conntrack hit */
if (ct_result_rc(state.ct_result.rc) != CALI_CT_NEW) {
goto skip_policy;
}
/* Unlike from WEP where we can do RPF by comparing to calico routing
* info, we must rely in Linux to do it for us when receiving packets
* from outside of the host. We enforce RPF failed on every new flow.
* This will make it to skip fib in calico_tc_skb_accepted()
*/
if (CALI_F_FROM_HEP) {
ct_result_set_flag(state.ct_result.rc, CALI_CT_RPF_FAILED);
}
/* No conntrack entry, check if we should do NAT */
nat_dest = calico_v4_nat_lookup2(state.ip_src, state.ip_dst,
state.ip_proto, state.dport,
state.tun_ip != 0);
if (nat_dest != NULL) {
state.post_nat_ip_dst = nat_dest->addr;
state.post_nat_dport = nat_dest->port;
} else {
state.post_nat_ip_dst = state.ip_dst;
state.post_nat_dport = state.dport;
}
if (CALI_F_TO_WEP &&
skb->mark != CALI_SKB_MARK_SEEN &&
cali_rt_flags_local_host(cali_rt_lookup_flags(state.ip_src))) {
/* Host to workload traffic always allowed. We discount traffic that was
* seen by another program since it must have come in via another interface.
*/
CALI_DEBUG("Packet is from the host: ACCEPT\n");
state.pol_rc = CALI_POL_ALLOW;
goto skip_policy;
}
if (CALI_F_FROM_WEP) {
/* Do RPF check since it's our responsibility to police that. */
CALI_DEBUG("Workload RPF check src=%x skb iface=%d.\n",
be32_to_host(state.ip_src), skb->ifindex);
struct cali_rt *r = cali_rt_lookup(state.ip_src);
if (!r) {
CALI_INFO("Workload RPF fail: missing route.\n");
goto deny;
}
if (!cali_rt_flags_local_workload(r->flags)) {
CALI_INFO("Workload RPF fail: not a local workload.\n");
goto deny;
}
if (r->if_index != skb->ifindex) {
CALI_INFO("Workload RPF fail skb iface (%d) != route iface (%d)\n",
skb->ifindex, r->if_index);
goto deny;
}
// Check whether the workload needs outgoing NAT to this address.
if (r->flags & CALI_RT_NAT_OUT) {
if (!(cali_rt_lookup_flags(state.post_nat_ip_dst) & CALI_RT_IN_POOL)) {
CALI_DEBUG("Source is in NAT-outgoing pool "
"but dest is not, need to SNAT.\n");
state.flags |= CALI_ST_NAT_OUTGOING;
}
}
}
/* icmp_type and icmp_code share storage with the ports; now we've used
* the ports set to 0 to do the conntrack lookup, we can set the ICMP fields
* for policy.
*/
if (state.ip_proto == IPPROTO_ICMP) {
state.icmp_type = icmp_header->type;
state.icmp_code = icmp_header->code;
}
// Set up an entry in the state map and then jump to the normal policy program.
int key = 0;
struct cali_tc_state *map_state = cali_v4_state_lookup_elem(&key);
if (!map_state) {
// Shouldn't be possible; the map is pre-allocated.
CALI_INFO("State map lookup failed: DROP\n");
goto deny;
}
state.pol_rc = CALI_POL_NO_MATCH;
if (nat_dest) {
state.nat_dest.addr = nat_dest->addr;
state.nat_dest.port = nat_dest->port;
} else {
state.nat_dest.addr = 0;
state.nat_dest.port = 0;
}
*map_state = state;
if (CALI_F_HEP) {
/* We don't support host-endpoint policy yet, skip straight to
* the epilogue program.
* FIXME we really want to just call calico_tc_skb_accepted()
* here but that runs out of stack space.
*/
map_state->pol_rc = CALI_POL_ALLOW;
bpf_tail_call(skb, &cali_jump, 1);
CALI_DEBUG("Tail call to epilogue program failed: ALLOW\n");
return TC_ACT_UNSPEC;
}
CALI_DEBUG("About to jump to policy program; lack of further "
"logs means policy dropped the packet...\n");
bpf_tail_call(skb, &cali_jump, 0);
CALI_DEBUG("Tail call to policy program failed: DROP\n");
return TC_ACT_SHOT;
skip_policy:
fwd = calico_tc_skb_accepted(skb, ip_header, &state, nat_dest);
allow:
finalize:
return forward_or_drop(skb, &state, &fwd);
deny:
fwd.res = TC_ACT_SHOT;
goto finalize;
}
__attribute__((section("1/1")))
int calico_tc_skb_accepted_entrypoint(struct __sk_buff *skb)
{
CALI_DEBUG("Entering calico_tc_skb_accepted_entrypoint\n");
struct iphdr *ip_header = NULL;
if (skb_too_short(skb)) {
CALI_DEBUG("Too short\n");
goto deny;
}
ip_header = skb_iphdr(skb);
__u32 key = 0;
struct cali_tc_state *state = bpf_map_lookup_elem(&cali_v4_state, &key);
if (!state) {
CALI_DEBUG("State map lookup failed: DROP\n");
goto deny;
}
struct calico_nat_dest *nat_dest = NULL;
struct calico_nat_dest nat_dest_2 = {
.addr=state->nat_dest.addr,
.port=state->nat_dest.port,
};
if (state->nat_dest.addr != 0) {
nat_dest = &nat_dest_2;
}
struct fwd fwd = calico_tc_skb_accepted(skb, ip_header, state, nat_dest);
return forward_or_drop(skb, state, &fwd);
deny:
return TC_ACT_SHOT;
}
static CALI_BPF_INLINE struct fwd calico_tc_skb_accepted(struct __sk_buff *skb,
struct iphdr *ip_header,
struct cali_tc_state *state,
struct calico_nat_dest *nat_dest)
{
CALI_DEBUG("Entering calico_tc_skb_accepted\n");
enum calico_reason reason = CALI_REASON_UNKNOWN;
int rc = TC_ACT_UNSPEC;
bool fib = false;
struct ct_ctx ct_nat_ctx = {};
int ct_rc = ct_result_rc(state->ct_result.rc);
bool ct_related = ct_result_is_related(state->ct_result.rc);
uint32_t seen_mark;
size_t l4_csum_off = 0, l3_csum_off;
uint32_t fib_flags = 0;
CALI_DEBUG("src=%x dst=%x\n", be32_to_host(state->ip_src), be32_to_host(state->ip_dst));
CALI_DEBUG("post_nat=%x:%d\n", be32_to_host(state->post_nat_ip_dst), state->post_nat_dport);
CALI_DEBUG("tun_ip=%x\n", state->tun_ip);
CALI_DEBUG("pol_rc=%d\n", state->pol_rc);
CALI_DEBUG("sport=%d\n", state->sport);
CALI_DEBUG("flags=%x\n", state->flags);
CALI_DEBUG("ct_rc=%d\n", ct_rc);
CALI_DEBUG("ct_related=%d\n", ct_related);
// Set the dport to 0, to make sure conntrack entries for icmp is proper as we use
// dport to hold icmp type and code
if (state->ip_proto == IPPROTO_ICMP) {
state->dport = 0;
}
if (CALI_F_FROM_WEP && (state->flags & CALI_ST_NAT_OUTGOING)) {
seen_mark = CALI_SKB_MARK_NAT_OUT;
} else {
/* XXX we do it here again because doing it in one place only
* XXX in calico_tc() irritates the verifier :'(
*/
if (!CALI_F_TO_HOST || !ct_result_rpf_failed(state->ct_result.rc)) {
fib = true;
}
seen_mark = CALI_SKB_MARK_SEEN;
}
/* We check the ttl here to avoid needing complicated handling of
* related trafic back from the host if we let the host to handle it.
*/
CALI_DEBUG("ip->ttl %d\n", ip_header->ttl);
if (ip_ttl_exceeded(ip_header)) {
switch (ct_rc){
case CALI_CT_NEW:
if (nat_dest) {
goto icmp_ttl_exceeded;
}
break;
case CALI_CT_ESTABLISHED_DNAT:
case CALI_CT_ESTABLISHED_SNAT:
goto icmp_ttl_exceeded;
}
}
l3_csum_off = skb_iphdr_offset(skb) + offsetof(struct iphdr, check);
if (ct_related) {
if (ip_header->protocol == IPPROTO_ICMP) {
struct icmphdr *icmp;
bool outer_ip_snat;
/* if we do SNAT ... */
outer_ip_snat = ct_rc == CALI_CT_ESTABLISHED_SNAT;
/* ... there is a return path to the tunnel ... */
outer_ip_snat = outer_ip_snat && state->ct_result.tun_ip;
/* ... and should do encap and it is not DSR or it is leaving host
* and either DSR from WEP or originated at host ... */
outer_ip_snat = outer_ip_snat &&
((dnat_return_should_encap() && !CALI_F_DSR) ||
(CALI_F_TO_HEP &&
((CALI_F_DSR && skb_seen(skb)) || !skb_seen(skb))));
/* ... then fix the outer header IP first */
if (outer_ip_snat) {
ip_header->saddr = state->ct_result.nat_ip;
int res = bpf_l3_csum_replace(skb, l3_csum_off,
state->ip_src, state->ct_result.nat_ip, 4);
if (res) {
reason = CALI_REASON_CSUM_FAIL;
goto deny;
}
CALI_DEBUG("ICMP related: outer IP SNAT to %x\n",
be32_to_host(state->ct_result.nat_ip));
}
if (!icmp_skb_get_hdr(skb, &icmp)) {
CALI_DEBUG("Ooops, we already passed one such a check!!!\n");
goto deny;
}
l3_csum_off += sizeof(*ip_header) + sizeof(*icmp);
ip_header = (struct iphdr *)(icmp + 1); /* skip to inner ip */
/* flip the direction, we need to reverse the original packet */
switch (ct_rc) {
case CALI_CT_ESTABLISHED_SNAT:
/* handle the DSR case, see CALI_CT_ESTABLISHED_SNAT where nat is done */
if (dnat_return_should_encap() && state->ct_result.tun_ip) {
if (CALI_F_DSR) {
/* SNAT will be done after routing, when leaving HEP */
CALI_DEBUG("DSR enabled, skipping SNAT + encap\n");
goto allow;
}
}
ct_rc = CALI_CT_ESTABLISHED_DNAT;
break;
case CALI_CT_ESTABLISHED_DNAT:
if (CALI_F_FROM_HEP && state->tun_ip && ct_result_np_node(state->ct_result)) {
/* Packet is returning from a NAT tunnel, just forward it. */
seen_mark = CALI_SKB_MARK_BYPASS_FWD;
CALI_DEBUG("ICMP related returned from NAT tunnel\n");
goto allow;
}
ct_rc = CALI_CT_ESTABLISHED_SNAT;
break;
}
}
}
struct tcphdr *tcp_header = (void*)(ip_header+1);
struct udphdr *udp_header = (void*)(ip_header+1);
__u8 ihl = ip_header->ihl * 4;
int res = 0;
bool encap_needed = false;
if (state->ip_proto == IPPROTO_ICMP && ct_related) {
/* do not fix up embedded L4 checksum for related ICMP */
} else {
switch (ip_header->protocol) {
case IPPROTO_TCP:
l4_csum_off = skb_l4hdr_offset(skb, ihl) + offsetof(struct tcphdr, check);
break;
case IPPROTO_UDP:
l4_csum_off = skb_l4hdr_offset(skb, ihl) + offsetof(struct udphdr, check);
break;
}
}
switch (ct_rc){
case CALI_CT_NEW:
switch (state->pol_rc) {
case CALI_POL_NO_MATCH:
CALI_DEBUG("Implicitly denied by normal policy: DROP\n");
goto deny;
case CALI_POL_DENY:
CALI_DEBUG("Denied by normal policy: DROP\n");
goto deny;
case CALI_POL_ALLOW:
CALI_DEBUG("Allowed by normal policy: ACCEPT\n");
}
if (CALI_F_FROM_WEP &&
CALI_DROP_WORKLOAD_TO_HOST &&
cali_rt_flags_local_host(
cali_rt_lookup_flags(state->post_nat_ip_dst))) {
CALI_DEBUG("Workload to host traffic blocked by "
"DefaultEndpointToHostAction: DROP\n");
goto deny;
}
ct_nat_ctx.skb = skb;
ct_nat_ctx.proto = state->ip_proto;
ct_nat_ctx.src = state->ip_src;
ct_nat_ctx.sport = state->sport;
ct_nat_ctx.dst = state->post_nat_ip_dst;
ct_nat_ctx.dport = state->post_nat_dport;
ct_nat_ctx.tun_ip = state->tun_ip;
if (state->flags & CALI_ST_NAT_OUTGOING) {
ct_nat_ctx.flags |= CALI_CT_FLAG_NAT_OUT;
}
if (state->ip_proto == IPPROTO_TCP) {
if (!skb_has_data_after(skb, ip_header, sizeof(struct tcphdr))) {
CALI_DEBUG("Too short for TCP: DROP\n");
goto deny;
}
tcp_header = (void*)(ip_header+1);
ct_nat_ctx.tcp = tcp_header;
}
// If we get here, we've passed policy.
if (nat_dest == NULL) {
if (conntrack_create(&ct_nat_ctx, CT_CREATE_NORMAL)) {
CALI_DEBUG("Creating normal conntrack failed\n");
goto deny;
}
goto allow;
}
ct_nat_ctx.orig_dst = state->ip_dst;
ct_nat_ctx.orig_dport = state->dport;
/* fall through as DNAT is now established */
case CALI_CT_ESTABLISHED_DNAT:
/* align with CALI_CT_NEW */
if (ct_rc == CALI_CT_ESTABLISHED_DNAT) {
if (CALI_F_FROM_HEP && state->tun_ip && ct_result_np_node(state->ct_result)) {
/* Packet is returning from a NAT tunnel,
* already SNATed, just forward it.
*/
seen_mark = CALI_SKB_MARK_BYPASS_FWD;
CALI_DEBUG("returned from NAT tunnel\n");
goto allow;
}
state->post_nat_ip_dst = state->ct_result.nat_ip;
state->post_nat_dport = state->ct_result.nat_port;
}
CALI_DEBUG("CT: DNAT to %x:%d\n",
be32_to_host(state->post_nat_ip_dst), state->post_nat_dport);
encap_needed = dnat_should_encap();
/* We have not created the conntrack yet since we did not know
* if we need encap or not. Must do before MTU check and before
* we jump to do the encap.
*/
if (ct_rc == CALI_CT_NEW) {
struct cali_rt * rt;
int nat_type = CT_CREATE_NAT;
if (encap_needed) {
/* When we need to encap, we need to find out if the backend is
* local or not. If local, we actually do not need the encap.
*/
rt = cali_rt_lookup(state->post_nat_ip_dst);
if (!rt) {
reason = CALI_REASON_RT_UNKNOWN;
goto deny;
}
CALI_DEBUG("rt found for 0x%x local %d\n",
be32_to_host(state->post_nat_ip_dst), !!cali_rt_is_local(rt));
encap_needed = !cali_rt_is_local(rt);
if (encap_needed) {
if (CALI_F_FROM_HEP && state->tun_ip == 0) {
if (CALI_F_DSR) {
ct_nat_ctx.flags |= CALI_CT_FLAG_DSR_FWD;
}
ct_nat_ctx.flags |= CALI_CT_FLAG_NP_FWD;
}
nat_type = CT_CREATE_NAT_FWD;
ct_nat_ctx.tun_ip = rt->next_hop;
state->ip_dst = rt->next_hop;
}
}
if (conntrack_create(&ct_nat_ctx, nat_type)) {
CALI_DEBUG("Creating NAT conntrack failed\n");
goto deny;
}
} else {
if (encap_needed && ct_result_np_node(state->ct_result)) {
CALI_DEBUG("CT says encap to node %x\n", be32_to_host(state->ct_result.tun_ip));
state->ip_dst = state->ct_result.tun_ip;
} else {
encap_needed = false;
}
}
if (encap_needed) {
if (!(state->ip_proto == IPPROTO_TCP && skb_is_gso(skb)) &&
ip_is_dnf(ip_header) && vxlan_v4_encap_too_big(skb)) {
CALI_DEBUG("Request packet with DNF set is too big\n");
goto icmp_too_big;
}
state->ip_src = HOST_IP;
seen_mark = CALI_SKB_MARK_BYPASS_FWD_SRC_FIXUP;
/* We cannot enforce RPF check on encapped traffic, do FIB if you can */
fib = true;
goto nat_encap;
}
ip_header->daddr = state->post_nat_ip_dst;
switch (ip_header->protocol) {
case IPPROTO_TCP:
tcp_header->dest = host_to_be16(state->post_nat_dport);
break;
case IPPROTO_UDP:
udp_header->dest = host_to_be16(state->post_nat_dport);
break;
}
CALI_VERB("L3 csum at %d L4 csum at %d\n", l3_csum_off, l4_csum_off);
if (l4_csum_off) {
res = skb_nat_l4_csum_ipv4(skb, l4_csum_off, state->ip_dst,
state->post_nat_ip_dst, host_to_be16(state->dport),
host_to_be16(state->post_nat_dport),
ip_header->protocol == IPPROTO_UDP ? BPF_F_MARK_MANGLED_0 : 0);
}
res |= bpf_l3_csum_replace(skb, l3_csum_off, state->ip_dst, state->post_nat_ip_dst, 4);
if (res) {
reason = CALI_REASON_CSUM_FAIL;
goto deny;
}
/* Handle returning ICMP related to tunnel
*
* N.B. we assume that we can fit in the MTU. Since it is ICMP
* and even though Linux sends up to min ipv4 MTU, it is
* unlikely that we are anywhere to close the MTU limit. If we
* are, we need to fail anyway.
*/
if (ct_related && state->ip_proto == IPPROTO_ICMP
&& state->ct_result.tun_ip
&& !CALI_F_DSR) {
if (dnat_return_should_encap()) {
CALI_DEBUG("Returning related ICMP from workload to tunnel\n");
state->ip_dst = state->ct_result.tun_ip;
seen_mark = CALI_SKB_MARK_BYPASS_FWD_SRC_FIXUP;
goto nat_encap;
} else if (CALI_F_TO_HEP) {
/* Special case for ICMP error being returned by the host with the
* backing workload into the tunnel back to the original host. It is
* ICMP related and there is a return tunnel path. We need to change
* both the source and destination at once.
*
* XXX the packet was routed to the original client as if it was XXX
* DSR and we might not be on the right iface!!! Should we XXX try
* to reinject it to fix the routing?
*/
CALI_DEBUG("Returning related ICMP from host to tunnel\n");
state->ip_src = HOST_IP;
state->ip_dst = state->ct_result.tun_ip;
goto nat_encap;
}
}
state->dport = state->post_nat_dport;
state->ip_dst = state->post_nat_ip_dst;
goto allow;
case CALI_CT_ESTABLISHED_SNAT:
CALI_DEBUG("CT: SNAT from %x:%d\n",
be32_to_host(state->ct_result.nat_ip), state->ct_result.nat_port);
if (dnat_return_should_encap() && state->ct_result.tun_ip) {
if (CALI_F_DSR) {
/* SNAT will be done after routing, when leaving HEP */
CALI_DEBUG("DSR enabled, skipping SNAT + encap\n");
goto allow;
}
if (!(state->ip_proto == IPPROTO_TCP && skb_is_gso(skb)) &&
ip_is_dnf(ip_header) && vxlan_v4_encap_too_big(skb)) {
CALI_DEBUG("Return ICMP mtu is too big\n");
goto icmp_too_big;
}
}
// Actually do the NAT.
ip_header->saddr = state->ct_result.nat_ip;
switch (ip_header->protocol) {
case IPPROTO_TCP:
tcp_header->source = host_to_be16(state->ct_result.nat_port);
break;
case IPPROTO_UDP:
udp_header->source = host_to_be16(state->ct_result.nat_port);
break;
}
CALI_VERB("L3 csum at %d L4 csum at %d\n", l3_csum_off, l4_csum_off);
if (l4_csum_off) {
res = skb_nat_l4_csum_ipv4(skb, l4_csum_off, state->ip_src,
state->ct_result.nat_ip, host_to_be16(state->sport),
host_to_be16(state->ct_result.nat_port),
ip_header->protocol == IPPROTO_UDP ? BPF_F_MARK_MANGLED_0 : 0);
}
CALI_VERB("L3 checksum update (csum is at %d) port from %x to %x\n",
l3_csum_off, state->ip_src, state->ct_result.nat_ip);
int csum_rc = bpf_l3_csum_replace(skb, l3_csum_off,
state->ip_src, state->ct_result.nat_ip, 4);
CALI_VERB("bpf_l3_csum_replace(IP): %d\n", csum_rc);
res |= csum_rc;
if (res) {
reason = CALI_REASON_CSUM_FAIL;
goto deny;
}
if (dnat_return_should_encap() && state->ct_result.tun_ip) {
state->ip_dst = state->ct_result.tun_ip;
seen_mark = CALI_SKB_MARK_BYPASS_FWD_SRC_FIXUP;
goto nat_encap;
}
state->sport = state->ct_result.nat_port;
state->ip_src = state->ct_result.nat_ip;
goto allow;
case CALI_CT_ESTABLISHED_BYPASS:
seen_mark = CALI_SKB_MARK_BYPASS;
// fall through
case CALI_CT_ESTABLISHED:
goto allow;
default:
if (CALI_F_FROM_HEP) {
/* Since we're using the host endpoint program for TC-redirect
* acceleration for workloads (but we haven't fully implemented
* host endpoint support yet), we can get an incorrect conntrack
* invalid for host traffic.
*
* FIXME: Properly handle host endpoint conntrack failures
*/
CALI_DEBUG("Traffic is towards host namespace but not conntracked, "
"falling through to iptables\n");
fib = false;
goto allow;
}
goto deny;
}
CALI_INFO("We should never fall through here\n");
goto deny;
icmp_ttl_exceeded:
if (skb_too_short(skb)) {
reason = CALI_REASON_SHORT;
CALI_DEBUG("Too short\n");
goto deny;
}
ip_header = skb_iphdr(skb);
/* we silently drop the packet if things go wrong */
/* XXX we should check if it is broadcast or multicast and not respond */
/* do not respond to IP fragments except the first */
if (ip_frag_no(ip_header)) {
goto deny;
}
if (icmp_v4_ttl_exceeded(skb)) {
goto deny;
}
/* we need to allow the reponse for the IP stack to route it back.
* XXX we might want to send it back the same iface
*/
goto icmp_allow;
icmp_too_big:
if (icmp_v4_too_big(skb)) {
reason = CALI_REASON_ICMP_DF;
goto deny;
}
/* XXX we might use skb->ifindex to redirect it straight back
* to where it came from if it is guaranteed to be the path
*/
fib_flags |= BPF_FIB_LOOKUP_OUTPUT;
if (CALI_F_FROM_WEP) {
/* we know it came from workload, just send it back the same way */
rc = CALI_RES_REDIR_IFINDEX;
}
goto icmp_allow;
icmp_allow:
/* recheck the size of the packet after it was turned into icmp and set
* state so that it can processed further.
*/
if (skb_shorter(skb, ETH_IPV4_UDP_SIZE)) {
reason = CALI_REASON_SHORT;
goto deny;
}
ip_header = skb_iphdr(skb);
tc_state_fill_from_iphdr(state, ip_header);
state->sport = state->dport = 0;
/* packet was created because of approved traffic, treat it as related */
seen_mark = CALI_SKB_MARK_BYPASS_FWD;
goto allow;
nat_encap:
if (vxlan_v4_encap(skb, state->ip_src, state->ip_dst)) {
reason = CALI_REASON_ENCAP_FAIL;
goto deny;
}
state->sport = state->dport = CALI_VXLAN_PORT;
state->ip_proto = IPPROTO_UDP;
allow:
{
struct fwd fwd = {
.res = rc,
.mark = seen_mark,
};
fwd_fib_set(&fwd, fib);
fwd_fib_set_flags(&fwd, fib_flags);
return fwd;
}
deny:
{
struct fwd fwd = {
.res = TC_ACT_SHOT,
.reason = reason,
};
return fwd;
}
}
#ifndef CALI_ENTRYPOINT_NAME
#define CALI_ENTRYPOINT_NAME calico_entrypoint
#endif
// Entrypoint with definable name. It's useful to redefine the name for each entrypoint
// because the name is exposed by bpftool et al.
__attribute__((section(XSTR(CALI_ENTRYPOINT_NAME))))
int tc_calico_entry(struct __sk_buff *skb)
{
return calico_tc(skb);
}
char ____license[] __attribute__((section("license"), used)) = "GPL";
| 1 | 17,892 | We have `stdbool` imported, might as well use that for clarity. | projectcalico-felix | c |
@@ -0,0 +1 @@
+package batchstore | 1 | 1 | 13,198 | File is empty, consider removing? | ethersphere-bee | go |
|
@@ -760,7 +760,7 @@ describe('Bulk', function() {
batch.insert({ b: 1 });
// Execute the operations
- batch.execute(self.configuration.writeConcernMax(), function(err, result) {
+ batch.execute(self.configuration.writeConcernMax().writeConcern, function(err, result) {
expect(err).to.exist;
expect(result).to.not.exist;
| 1 | 'use strict';
const test = require('./shared').assert,
setupDatabase = require('./shared').setupDatabase,
expect = require('chai').expect;
const MongoError = require('../../index').MongoError;
const ignoreNsNotFound = require('./shared').ignoreNsNotFound;
describe('Bulk', function() {
before(function() {
return setupDatabase(this.configuration);
});
it('should correctly handle ordered single batch api write command error', {
metadata: {
requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
},
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var col = db.collection('batch_write_ordered_ops_10');
// Add unique index on b field causing all updates to fail
col.ensureIndex({ a: 1 }, { unique: true, sparse: false }, function(err) {
test.equal(err, null);
var batch = col.initializeOrderedBulkOp();
batch.insert({ b: 1, a: 1 });
batch
.find({ b: 2 })
.upsert()
.updateOne({ $set: { a: 1 } });
batch.insert({ b: 3, a: 2 });
batch.execute(function(err, result) {
expect(err).to.exist;
expect(result).to.not.exist;
result = err.result;
// Basic properties check
test.equal(1, result.nInserted);
test.equal(true, result.hasWriteErrors());
test.equal(1, result.getWriteErrorCount());
// Get the write error
var error = result.getWriteErrorAt(0);
test.equal(11000, error.code);
test.ok(error.errmsg != null);
// Get the operation that caused the error
var op = error.getOperation();
test.equal(2, op.q.b);
test.equal(1, op.u['$set'].a);
test.equal(false, op.multi);
test.equal(true, op.upsert);
// Get the first error
error = result.getWriteErrorAt(1);
test.equal(null, error);
// Finish up test
client.close(done);
});
});
});
}
});
it('should use arrayFilters for updateMany', {
metadata: { requires: { mongodb: '>=3.6.x' } },
test: function(done) {
const configuration = this.configuration;
const client = configuration.newClient({}, { w: 1 });
client.connect((err, client) => {
const db = client.db(configuration.db);
const collection = db.collection('arrayfilterstest');
const docs = [{ a: [{ x: 1 }, { x: 2 }] }, { a: [{ x: 3 }, { x: 4 }] }];
const close = e => client.close(() => done(e));
collection.insertMany(docs).then(() =>
collection.updateMany(
{},
{ $set: { 'a.$[i].x': 5 } },
{ arrayFilters: [{ 'i.x': 5 }] },
(err, data) => {
expect(err).to.not.exist;
expect(data.matchedCount).to.equal(2);
close(err);
}
)
);
});
}
});
it('should ignore undefined values in unordered bulk operation if `ignoreUndefined` specified', {
metadata: {
requires: { topology: ['single'] }
},
test: function() {
const client = this.configuration.newClient(this.configuration.writeConcernMax(), {
poolSize: 1
});
return client
.connect()
.then(client => {
const db = client.db(this.configuration.db);
const col = db.collection('batch_write_unordered_ops_1');
return col
.initializeUnorderedBulkOp({ ignoreUndefined: true })
.insert({ a: 1, b: undefined })
.execute()
.then(() => col.find({}).toArray())
.then(docs => {
expect(docs[0]['a']).to.equal(1);
expect(docs[0]['b']).to.not.exist;
});
})
.then(() => client.close());
}
});
it('should ignore undefined values in ordered bulk operation if `ignoreUndefined` specified', {
metadata: {
requires: { topology: ['single'] }
},
test: function() {
var client = this.configuration.newClient(this.configuration.writeConcernMax(), {
poolSize: 1
});
return client.connect().then(client => {
var db = client.db(this.configuration.db);
var col = db.collection('batch_write_ordered_ops_3');
return col
.initializeOrderedBulkOp({ ignoreUndefined: true })
.insert({ a: 1, b: undefined })
.execute()
.then(() => col.find({}).toArray())
.then(docs => {
expect(docs[0]['a']).to.equal(1);
expect(docs[0]['b']).to.not.exist;
})
.then(() => client.close());
});
}
});
it('should correctly handle ordered multiple batch api write command errors', {
metadata: {
requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
},
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var col = db.collection('batch_write_ordered_ops_2');
// Add unique index on field `a` causing all updates to fail
col.ensureIndex({ a: 1 }, { unique: true, sparse: false }, function(err) {
test.equal(err, null);
var batch = col.initializeOrderedBulkOp();
batch.insert({ b: 1, a: 1 });
batch
.find({ b: 2 })
.upsert()
.updateOne({ $set: { a: 1 } });
batch
.find({ b: 3 })
.upsert()
.updateOne({ $set: { a: 2 } });
batch
.find({ b: 2 })
.upsert()
.updateOne({ $set: { a: 1 } });
batch.insert({ b: 4, a: 3 });
batch.insert({ b: 5, a: 1 });
batch.execute(function(err, result) {
expect(err).to.exist;
expect(result).to.not.exist;
// Basic properties check
result = err.result;
test.equal(err instanceof Error, true);
test.equal(1, result.nInserted);
test.equal(true, result.hasWriteErrors());
test.ok(1, result.getWriteErrorCount());
// Individual error checking
var error = result.getWriteErrorAt(0);
test.equal(1, error.index);
test.equal(11000, error.code);
test.ok(error.errmsg != null);
test.equal(2, error.getOperation().q.b);
test.equal(1, error.getOperation().u['$set'].a);
test.equal(false, error.getOperation().multi);
test.equal(true, error.getOperation().upsert);
// Finish up test
client.close(done);
});
});
});
}
});
it('should fail due to ordered document being to big', {
metadata: {
requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
},
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var coll = db.collection('batch_write_ordered_ops_3');
// Set up a giant string to blow through the max message size
var hugeString = '';
// Create it bigger than 16MB
for (var i = 0; i < 1024 * 1100; i++) {
hugeString = hugeString + '1234567890123456';
}
// Set up the batch
var batch = coll.initializeOrderedBulkOp();
batch.insert({ b: 1, a: 1 });
// should fail on insert due to string being to big
try {
batch.insert({ string: hugeString });
test.ok(false);
} catch (err) {} // eslint-disable-line
// Finish up test
client.close(done);
});
}
});
it('should correctly split up ordered messages into more batches', {
metadata: {
requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
},
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var coll = db.collection('batch_write_ordered_ops_4');
// Set up a giant string to blow through the max message size
var hugeString = '';
// Create it bigger than 16MB
for (var i = 0; i < 1024 * 256; i++) {
hugeString = hugeString + '1234567890123456';
}
// Insert the string a couple of times, should force split into multiple batches
var batch = coll.initializeOrderedBulkOp();
batch.insert({ a: 1, b: hugeString });
batch.insert({ a: 2, b: hugeString });
batch.insert({ a: 3, b: hugeString });
batch.insert({ a: 4, b: hugeString });
batch.insert({ a: 5, b: hugeString });
batch.insert({ a: 6, b: hugeString });
// Execute the operations
batch.execute(function(err, result) {
// Basic properties check
test.equal(6, result.nInserted);
test.equal(false, result.hasWriteErrors());
// Finish up test
client.close(done);
});
});
}
});
it(
'should Correctly Execute Ordered Batch of Write Operations with duplicate key errors on updates',
{
metadata: {
requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
},
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var col = db.collection('batch_write_ordered_ops_6');
// Add unique index on b field causing all updates to fail
col.ensureIndex({ b: 1 }, { unique: true, sparse: false }, function(err) {
test.equal(err, null);
var batch = col.initializeOrderedBulkOp();
// Add some operations to be executed in order
batch.insert({ a: 1 });
batch.find({ a: 1 }).update({ $set: { b: 1 } });
batch.insert({ b: 1 });
// Execute the operations
batch.execute(function(err, result) {
expect(err).to.exist;
expect(result).to.not.exist;
// Test basic settings
result = err.result;
test.equal(1, result.nInserted);
test.equal(1, result.nMatched);
test.ok(1 === result.nModified || result.nModified == null);
test.equal(true, result.hasWriteErrors());
test.ok(1, result.getWriteErrorCount());
// Individual error checking
var error = result.getWriteErrorAt(0);
test.equal(2, error.index);
test.equal(11000, error.code);
test.ok(error.errmsg != null);
test.equal(1, error.getOperation().b);
client.close(done);
});
});
});
}
}
);
it(
'should Correctly Execute Ordered Batch of Write Operations with upserts causing duplicate key errors on updates',
{
metadata: {
requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
},
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var col = db.collection('batch_write_ordered_ops_7');
// Add unique index on b field causing all updates to fail
col.ensureIndex({ b: 1 }, { unique: true, sparse: false }, function(err) {
test.equal(err, null);
var batch = col.initializeOrderedBulkOp();
batch.insert({ a: 1 });
batch.find({ a: 1 }).update({ $set: { b: 1 } });
batch
.find({ a: 2 })
.upsert()
.update({ $set: { b: 2 } });
batch
.find({ a: 3 })
.upsert()
.update({ $set: { b: 3 } });
batch.insert({ b: 1 });
// Execute the operations
batch.execute(function(err, result) {
expect(err).to.exist;
expect(result).to.not.exist;
// Test basic settings
result = err.result;
test.equal(1, result.nInserted);
test.equal(2, result.nUpserted);
test.equal(1, result.nMatched);
test.ok(1 === result.nModified || result.nModified == null);
test.equal(true, result.hasWriteErrors());
test.ok(1, result.getWriteErrorCount());
// Individual error checking
var error = result.getWriteErrorAt(0);
test.equal(4, error.index);
test.equal(11000, error.code);
test.ok(error.errmsg != null);
test.equal(1, error.getOperation().b);
// Check for upserted values
var ids = result.getUpsertedIds();
test.equal(2, ids.length);
test.equal(2, ids[0].index);
test.ok(ids[0]._id != null);
test.equal(3, ids[1].index);
test.ok(ids[1]._id != null);
client.close(done);
});
});
});
}
}
);
it('should correctly perform ordered upsert with custom _id', {
metadata: {
requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
},
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var col = db.collection('batch_write_ordered_ops_8');
var batch = col.initializeOrderedBulkOp();
// Add some operations to be executed in order
batch
.find({ _id: 2 })
.upsert()
.updateOne({ $set: { b: 2 } });
// Execute the operations
batch.execute(function(err, result) {
// Check state of result
test.equal(1, result.nUpserted);
test.equal(0, result.nInserted);
test.equal(0, result.nMatched);
test.ok(0 === result.nModified || result.nModified == null);
test.equal(0, result.nRemoved);
var upserts = result.getUpsertedIds();
test.equal(1, upserts.length);
test.equal(0, upserts[0].index);
test.equal(2, upserts[0]._id);
// Finish up test
client.close(done);
});
});
}
});
it('should return an error when no operations in ordered batch', {
metadata: {
requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
},
test: function(done) {
var self = this;
var client = self.configuration.newClient({ w: 1 }, { poolSize: 1, auto_reconnect: false });
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var col = db.collection('batch_write_ordered_ops_8');
col.initializeOrderedBulkOp().execute(function(err) {
test.equal(err instanceof Error, true);
test.equal(err.message, 'Invalid Operation, no operations specified');
client.close(done);
});
});
}
});
it('should correctly execute ordered batch using w:0', {
metadata: {
requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] }
},
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var col = db.collection('batch_write_ordered_ops_9');
var bulk = col.initializeOrderedBulkOp();
for (var i = 0; i < 100; i++) {
bulk.insert({ a: 1 });
}
bulk
.find({ b: 1 })
.upsert()
.update({ b: 1 });
bulk.find({ c: 1 }).remove();
bulk.execute({ w: 0 }, function(err, result) {
test.equal(null, err);
test.equal(0, result.nUpserted);
test.equal(0, result.nInserted);
test.equal(0, result.nMatched);
test.ok(0 === result.nModified || result.nModified == null);
test.equal(0, result.nRemoved);
test.equal(false, result.hasWriteErrors());
client.close(done);
});
});
}
});
it('should correctly handle single unordered batch API', {
metadata: { requires: { topology: ['single', 'replicaset', 'ssl', 'heap', 'wiredtiger'] } },
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var col = db.collection('batch_write_unordered_ops_legacy_1');
// Add unique index on b field causing all updates to fail
col.ensureIndex({ a: 1 }, { unique: true, sparse: false }, function(err) {
test.equal(err, null);
// Initialize the unordered Batch
var batch = col.initializeUnorderedBulkOp();
// Add some operations to be executed in order
batch.insert({ b: 1, a: 1 });
batch
.find({ b: 2 })
.upsert()
.updateOne({ $set: { a: 1 } });
batch.insert({ b: 3, a: 2 });
// Execute the operations
batch.execute(function(err, result) {
expect(err).to.exist;
expect(result).to.not.exist;
// Basic properties check
result = err.result;
test.equal(err instanceof Error, true);
test.equal(2, result.nInserted);
test.equal(0, result.nUpserted);
test.equal(0, result.nMatched);
test.ok(0 === result.nModified || result.nModified == null);
test.equal(true, result.hasWriteErrors());
test.equal(1, result.getWriteErrorCount());
// Get the first error
var error = result.getWriteErrorAt(0);
test.equal(11000, error.code);
test.ok(error.errmsg != null);
// Get the operation that caused the error
var op = error.getOperation();
test.equal(2, op.q.b);
test.equal(1, op.u['$set'].a);
test.equal(false, op.multi);
test.equal(true, op.upsert);
// Get the first error
error = result.getWriteErrorAt(1);
test.equal(null, error);
// Finish up test
client.close(done);
});
});
});
}
});
it('should correctly handle multiple unordered batch API', function(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), {
poolSize: 1
});
client.connect((err, client) => {
const db = client.db(configuration.db);
const col = db.collection('batch_write_unordered_ops_legacy_2');
// Add unique index on b field causing all updates to fail
col.ensureIndex({ a: 1 }, { unique: true, sparse: false }, err => {
expect(err).to.not.exist;
// Initialize the unordered Batch
const batch = col.initializeUnorderedBulkOp({ useLegacyOps: true });
// Add some operations to be executed in order
batch.insert({ b: 1, a: 1 });
batch.insert({ b: 5, a: 1 });
// Execute the operations
batch.execute((err, result) => {
expect(err).to.exist;
expect(result).to.not.exist;
// Basic properties check
result = err.result;
expect(result.nInserted).to.equal(1);
expect(result.hasWriteErrors()).to.equal(true);
expect(result.getWriteErrorCount()).to.equal(1);
// Go over the error
const error = result.getWriteErrorAt(0);
expect(error.code).to.equal(11000);
expect(error.errmsg).to.exist;
expect(error.getOperation().b).to.equal(5);
expect(error.getOperation().a).to.equal(1);
// Finish up test
client.close(done);
});
});
});
});
it('should fail due to document being to big for unordered batch', {
metadata: { requires: { topology: ['single', 'replicaset', 'ssl', 'heap', 'wiredtiger'] } },
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var coll = db.collection('batch_write_unordered_ops_legacy_3');
// Set up a giant string to blow through the max message size
var hugeString = '';
// Create it bigger than 16MB
for (var i = 0; i < 1024 * 1100; i++) {
hugeString = hugeString + '1234567890123456';
}
// Set up the batch
var batch = coll.initializeUnorderedBulkOp();
batch.insert({ b: 1, a: 1 });
// should fail on insert due to string being to big
try {
batch.insert({ string: hugeString });
test.ok(false);
} catch (err) {} // eslint-disable-line
// Finish up test
client.close(done);
});
}
});
it('should correctly split up messages into more batches for unordered batches', {
metadata: { requires: { topology: ['single', 'replicaset', 'ssl', 'heap', 'wiredtiger'] } },
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var coll = db.collection('batch_write_unordered_ops_legacy_4');
// Set up a giant string to blow through the max message size
var hugeString = '';
// Create it bigger than 16MB
for (var i = 0; i < 1024 * 256; i++) {
hugeString = hugeString + '1234567890123456';
}
// Insert the string a couple of times, should force split into multiple batches
var batch = coll.initializeUnorderedBulkOp();
batch.insert({ a: 1, b: hugeString });
batch.insert({ a: 2, b: hugeString });
batch.insert({ a: 3, b: hugeString });
batch.insert({ a: 4, b: hugeString });
batch.insert({ a: 5, b: hugeString });
batch.insert({ a: 6, b: hugeString });
// Execute the operations
batch.execute(function(err, result) {
// Basic properties check
test.equal(6, result.nInserted);
test.equal(false, result.hasWriteErrors());
// Finish up test
client.close(done);
});
});
}
});
it('should Correctly Execute Unordered Batch with duplicate key errors on updates', {
metadata: { requires: { topology: ['single', 'replicaset', 'ssl', 'heap', 'wiredtiger'] } },
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var col = db.collection('batch_write_unordered_ops_legacy_6');
// Write concern
var writeConcern = self.configuration.writeConcernMax();
writeConcern.unique = true;
writeConcern.sparse = false;
// Add unique index on b field causing all updates to fail
col.ensureIndex({ b: 1 }, writeConcern, function(err) {
test.equal(err, null);
// Initialize the unordered Batch
var batch = col.initializeUnorderedBulkOp();
// Add some operations to be executed in order
batch.insert({ a: 1 });
batch.find({ a: 1 }).update({ $set: { b: 1 } });
batch.insert({ b: 1 });
batch.insert({ b: 1 });
batch.insert({ b: 1 });
batch.insert({ b: 1 });
// Execute the operations
batch.execute(self.configuration.writeConcernMax(), function(err, result) {
expect(err).to.exist;
expect(result).to.not.exist;
// Test basic settings
result = err.result;
test.equal(2, result.nInserted);
test.equal(true, result.hasWriteErrors());
test.ok(result.getWriteErrorCount() === 4 || result.getWriteErrorCount() === 3);
// Individual error checking
var error = result.getWriteErrorAt(0);
test.ok(error.code === 11000 || error.code === 11001);
test.ok(error.errmsg != null);
client.close(done);
});
});
});
}
});
it('should provide descriptive error message for unordered batch with duplicate key errors on inserts', function(done) {
const configuration = this.configuration;
const client = configuration.newClient(configuration.writeConcernMax(), {
poolSize: 1
});
client.connect((err, client) => {
const db = client.db(configuration.db);
const col = db.collection('err_batch_write_unordered_ops_legacy_6');
// Add unique index on a field causing all inserts to fail
col.createIndexes(
[
{
name: 'err_batch_write_unordered_ops_legacy_6',
key: { a: 1 },
unique: true
}
],
err => {
expect(err).to.not.exist;
// Initialize the unordered Batch
const batch = col.initializeUnorderedBulkOp();
// Add some operations to be executed in order
batch.insert({ a: 1 });
batch.insert({ a: 1 });
// Execute the operations
batch.execute(configuration.writeConcernMax(), (err, result) => {
expect(err).to.exist;
expect(result).to.not.exist;
// Test basic settings
result = err.result;
expect(result.nInserted).to.equal(1);
expect(result.hasWriteErrors()).to.equal(true);
expect(result.getWriteErrorCount() === 1).to.equal(true);
// Individual error checking
const error = result.getWriteErrorAt(0);
expect(error.code === 11000).to.equal(true);
expect(error.errmsg).to.exist;
expect(err.message).to.equal(error.errmsg);
client.close(done);
});
}
);
});
});
it(
'should Correctly Execute Unordered Batch of with upserts causing duplicate key errors on updates',
{
metadata: { requires: { topology: ['single', 'replicaset', 'ssl', 'heap', 'wiredtiger'] } },
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var col = db.collection('batch_write_unordered_ops_legacy_7');
// Add unique index on b field causing all updates to fail
col.ensureIndex({ b: 1 }, { unique: true, sparse: false }, function(err) {
test.equal(err, null);
// Initialize the unordered Batch
var batch = col.initializeUnorderedBulkOp();
// Add some operations to be executed in order
batch.insert({ a: 1 });
batch.find({ a: 1 }).update({ $set: { b: 1 } });
batch
.find({ a: 2 })
.upsert()
.update({ $set: { b: 2 } });
batch
.find({ a: 3 })
.upsert()
.update({ $set: { b: 3 } });
batch.find({ a: 1 }).update({ $set: { b: 1 } });
batch.insert({ b: 1 });
// Execute the operations
batch.execute(self.configuration.writeConcernMax(), function(err, result) {
expect(err).to.exist;
expect(result).to.not.exist;
// Test basic settings
result = err.result;
test.equal(2, result.nInserted);
test.equal(2, result.nUpserted);
test.ok(0 === result.nModified || result.nModified == null);
test.equal(0, result.nRemoved);
test.equal(true, result.hasWriteErrors());
test.ok(1, result.getWriteErrorCount());
// Individual error checking
var error = result.getWriteErrorAt(0);
test.ok(error.code === 11000 || error.code === 11001);
test.ok(error.errmsg != null);
test.equal(1, error.getOperation().u['$set'].b);
// Check for upserted values
var ids = result.getUpsertedIds();
test.equal(2, ids.length);
test.equal(2, ids[0].index);
test.ok(ids[0]._id != null);
test.equal(3, ids[1].index);
test.ok(ids[1]._id != null);
client.close(done);
});
});
});
}
}
);
it('should correctly perform unordered upsert with custom _id', {
metadata: { requires: { topology: ['single', 'replicaset', 'ssl', 'heap', 'wiredtiger'] } },
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var col = db.collection('batch_write_unordered_ops_legacy_8');
var batch = col.initializeUnorderedBulkOp();
// Add some operations to be executed in order
batch
.find({ _id: 2 })
.upsert()
.updateOne({ $set: { b: 2 } });
// Execute the operations
batch.execute(self.configuration.writeConcernMax(), function(err, result) {
// Check state of result
test.equal(1, result.nUpserted);
test.equal(0, result.nInserted);
test.equal(0, result.nMatched);
test.ok(0 === result.nModified || result.nModified == null);
test.equal(0, result.nRemoved);
var upserts = result.getUpsertedIds();
test.equal(1, upserts.length);
test.equal(0, upserts[0].index);
test.equal(2, upserts[0]._id);
// Finish up test
client.close(done);
});
});
}
});
it('should prohibit batch finds with no selector', {
metadata: { requires: { topology: ['single', 'replicaset', 'ssl', 'heap', 'wiredtiger'] } },
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var col = db.collection('batch_write_unordered_ops_legacy_9');
var unorderedBatch = col.initializeUnorderedBulkOp();
var orderedBatch = col.initializeOrderedBulkOp();
try {
unorderedBatch.find();
test.ok(false);
} catch (e) {
test.equal('MongoError: Bulk find operation must specify a selector', e.toString());
}
try {
orderedBatch.find();
test.ok(false);
} catch (e) {
test.equal('MongoError: Bulk find operation must specify a selector', e.toString());
}
client.close(done);
});
}
});
it('should return an error when no operations in unordered batch', {
metadata: { requires: { topology: ['single', 'replicaset', 'ssl', 'heap', 'wiredtiger'] } },
test: function(done) {
var self = this;
var client = self.configuration.newClient({ w: 1 }, { poolSize: 1, auto_reconnect: false });
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var col = db.collection('batch_write_ordered_ops_8');
col
.initializeUnorderedBulkOp()
.execute(self.configuration.writeConcernMax(), function(err) {
test.equal(err instanceof Error, true);
test.equal(err.message, 'Invalid Operation, no operations specified');
client.close(done);
});
});
}
});
it('should correctly execute unordered batch using w:0', {
metadata: { requires: { topology: ['single', 'replicaset', 'ssl', 'heap', 'wiredtiger'] } },
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var col = db.collection('batch_write_ordered_ops_9');
var bulk = col.initializeUnorderedBulkOp();
for (var i = 0; i < 100; i++) {
bulk.insert({ a: 1 });
}
bulk
.find({ b: 1 })
.upsert()
.update({ b: 1 });
bulk.find({ c: 1 }).remove();
bulk.execute({ w: 0 }, function(err, result) {
test.equal(null, err);
test.equal(0, result.nUpserted);
test.equal(0, result.nInserted);
test.equal(0, result.nMatched);
test.ok(0 === result.nModified || result.nModified == null);
test.equal(0, result.nRemoved);
test.equal(false, result.hasWriteErrors());
client.close(done);
});
});
}
});
/*******************************************************************
*
* Ordered
*
*******************************************************************/
it('should fail with w:2 and wtimeout write concern due single mongod instance ordered', {
metadata: { requires: { topology: 'single', mongodb: '>2.5.4' } },
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var col = db.collection('batch_write_concerns_ops_1');
var batch = col.initializeOrderedBulkOp();
batch.insert({ a: 1 });
batch.insert({ a: 2 });
batch.execute({ w: 2, wtimeout: 1000 }, function(err) {
test.ok(err != null);
test.ok(err.code != null);
test.ok(err.errmsg != null);
client.close(done);
});
});
}
});
it('should correctly handle bulk operation split for ordered bulk operation', {
// Add a tag that our runner can trigger on
// in this case we are setting that node needs to be higher than 0.10.X to run
metadata: {
requires: {
mongodb: '>=2.6.0',
topology: 'single'
}
},
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var docs = [];
for (var i = 0; i < 5; i++) {
docs.push({
s: new Array(6000000).join('x')
});
}
db.collection('bigdocs_ordered').insertMany(docs, function(err) {
test.equal(null, err);
db.collection('bigdocs_ordered').count(function(err, c) {
test.equal(null, err);
test.equal(5, c);
client.close(done);
});
});
});
}
});
/*******************************************************************
*
* Unordered
*
*******************************************************************/
it('should fail with w:2 and wtimeout write concern due single mongod instance unordered', {
metadata: { requires: { topology: 'single', mongodb: '>2.5.4' } },
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var col = db.collection('batch_write_concerns_ops_1');
var batch = col.initializeUnorderedBulkOp();
batch.insert({ a: 1 });
batch.insert({ a: 2 });
batch.execute({ w: 2, wtimeout: 1000 }, function(err) {
test.ok(err != null);
test.ok(err.code != null);
test.ok(err.errmsg != null);
client.close(done);
});
});
}
});
it('should correctly return the number of operations in the bulk', {
metadata: { requires: { topology: 'single', mongodb: '>2.5.4' } },
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var col = db.collection('batch_write_concerns_ops_1');
var batch = col.initializeOrderedBulkOp();
batch.insert({ a: 1 });
batch
.find({})
.upsert()
.update({ $set: { b: 1 } });
test.equal(2, batch.length);
batch = col.initializeUnorderedBulkOp();
batch.insert({ a: 1 });
batch
.find({})
.upsert()
.update({ $set: { b: 1 } });
test.equal(2, batch.length);
client.close(done);
});
}
});
it('should correctly split unordered bulk batch', {
metadata: { requires: { topology: 'single', mongodb: '>2.5.4' } },
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var insertFirst = false;
var batchSize = 1000;
var collection = db.collection('batch_write_unordered_split_test');
var operation = collection.initializeUnorderedBulkOp(),
documents = [];
for (var i = 0; i < 10000; i++) {
var document = { name: 'bob' + i };
documents.push(document);
operation.insert(document);
}
operation.execute(function(err) {
test.equal(null, err);
operation = collection.initializeUnorderedBulkOp();
if (insertFirst) {
// if you add the inserts to the batch first, it works fine.
insertDocuments();
replaceDocuments();
} else {
// if you add the updates to the batch first, it fails with the error "insert must contain at least one document"
replaceDocuments();
insertDocuments();
}
operation.execute(function(err) {
test.equal(null, err);
client.close(done);
});
});
function insertDocuments() {
for (i = 10000; i < 10200; i++) {
operation.insert({ name: 'bob' + i });
}
}
function replaceDocuments() {
for (var i = 0; i < batchSize; i++) {
operation.find({ _id: documents[i]._id }).replaceOne({ name: 'joe' + i });
}
}
});
}
});
it('should correctly split ordered bulk batch', {
metadata: { requires: { topology: 'single', mongodb: '>2.5.4' } },
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var insertFirst = false;
var batchSize = 1000;
var collection = db.collection('batch_write_ordered_split_test');
var operation = collection.initializeOrderedBulkOp(),
documents = [];
for (var i = 0; i < 10000; i++) {
var document = { name: 'bob' + i };
documents.push(document);
operation.insert(document);
}
operation.execute(function(err) {
test.equal(null, err);
operation = collection.initializeOrderedBulkOp();
if (insertFirst) {
// if you add the inserts to the batch first, it works fine.
insertDocuments();
replaceDocuments();
} else {
// if you add the updates to the batch first, it fails with the error "insert must contain at least one document"
replaceDocuments();
insertDocuments();
}
operation.execute(function(err) {
test.equal(null, err);
client.close(done);
});
});
function insertDocuments() {
for (i = 10000; i < 10200; i++) {
operation.insert({ name: 'bob' + i });
}
}
function replaceDocuments() {
for (var i = 0; i < batchSize; i++) {
operation.find({ _id: documents[i]._id }).replaceOne({ name: 'joe' + i });
}
}
});
}
});
it('should correctly handle bulk operation split for unordered bulk operation', {
// Add a tag that our runner can trigger on
// in this case we are setting that node needs to be higher than 0.10.X to run
metadata: {
requires: {
mongodb: '>=2.6.0',
topology: 'single'
}
},
test: function(done) {
var self = this;
var client = self.configuration.newClient(self.configuration.writeConcernMax(), {
poolSize: 1
});
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
var docs = [];
for (var i = 0; i < 5; i++) {
docs.push({
s: new Array(6000000).join('x')
});
}
db.collection('bigdocs_unordered').insertMany(docs, { ordered: false }, function(err) {
test.equal(null, err);
db.collection('bigdocs_unordered').count(function(err, c) {
test.equal(null, err);
test.equal(5, c);
client.close(done);
});
});
});
}
});
it(
'should return an error instead of throwing when no operations are provided for ordered bulk operation execute',
{
metadata: { requires: { mongodb: '>=2.6.0', topology: 'single' } },
test: function(done) {
var self = this;
var client = self.configuration.newClient({ w: 1 }, { poolSize: 1 });
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
db.collection('doesnt_matter').insertMany([], function(err) {
test.equal(err instanceof Error, true);
test.equal(err.message, 'Invalid Operation, no operations specified');
client.close(done);
});
});
}
}
);
it(
'should return an error instead of throwing when no operations are provided for unordered bulk operation execute',
{
metadata: { requires: { mongodb: '>=2.6.0', topology: 'single' } },
test: function(done) {
var self = this;
var client = self.configuration.newClient({ w: 1 }, { poolSize: 1 });
client.connect(function(err, client) {
var db = client.db(self.configuration.db);
db.collection('doesnt_matter').insertMany([], { ordered: false }, function(err) {
test.equal(err instanceof Error, true);
test.equal(err.message, 'Invalid Operation, no operations specified');
client.close(done);
});
});
}
}
);
it('should return an error instead of throwing when an empty bulk operation is submitted (with promise)', function() {
var self = this;
var client = self.configuration.newClient({ w: 1 }, { poolSize: 1 });
return client
.connect()
.then(function() {
var db = client.db(self.configuration.db);
return db.collection('doesnt_matter').insertMany([]);
})
.then(function() {
test.equal(false, true); // this should not happen!
})
.catch(function(err) {
test.equal(err instanceof Error, true);
test.equal(err.message, 'Invalid Operation, no operations specified');
})
.then(function() {
return client.close();
});
});
it('should properly account for array key size in bulk unordered inserts', function(done) {
const client = this.configuration.newClient();
const documents = new Array(20000).fill('').map(() => ({
arr: new Array(19).fill('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
}));
let db;
client
.connect()
// NOTE: Hack to get around unrelated strange error in bulkWrites for right now.
.then(() => {
db = client.db(this.configuration.db);
return db.dropCollection('doesnt_matter').catch(() => {});
})
.then(() => {
return db.createCollection('doesnt_matter');
})
.then(() => {
const coll = db.collection('doesnt_matter');
coll.insertMany(documents, { ordered: false }, err => {
client.close(() => {
done(err);
});
});
});
});
it('should properly account for array key size in bulk ordered inserts', function(done) {
const client = this.configuration.newClient();
const documents = new Array(20000).fill('').map(() => ({
arr: new Array(19).fill('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
}));
let db;
client
.connect()
// NOTE: Hack to get around unrelated strange error in bulkWrites for right now.
.then(() => {
db = client.db(this.configuration.db);
return db.dropCollection('doesnt_matter').catch(() => {});
})
.then(() => {
return db.createCollection('doesnt_matter');
})
.then(() => {
const coll = db.collection('doesnt_matter');
coll.insertMany(documents, { ordered: true }, err => {
client.close(() => {
done(err);
});
});
});
});
function testPropagationOfBulkWriteError(bulk) {
return bulk.execute().then(
err => {
expect(err).to.be.an.instanceOf(MongoError);
},
err => {
expect(err).to.be.an.instanceOf(MongoError);
expect(err).to.not.be.an.instanceOf(TypeError);
expect(err.driver).to.equal(true);
expect(err.name).to.equal('MongoError');
}
);
}
it('should propagate the proper error from executing an empty ordered batch', function() {
const client = this.configuration.newClient();
return client
.connect()
.then(() => {
const collection = client.db(this.configuration.db).collection('doesnt_matter');
return testPropagationOfBulkWriteError(collection.initializeOrderedBulkOp());
})
.then(() => client.close());
});
it('should propagate the proper error from executing an empty unordered batch', function() {
const client = this.configuration.newClient();
return client
.connect()
.then(() => {
const collection = client.db(this.configuration.db).collection('doesnt_matter');
return testPropagationOfBulkWriteError(collection.initializeUnorderedBulkOp());
})
.then(() => client.close());
});
it('should promote a single error to the top-level message, and preserve writeErrors', function() {
const client = this.configuration.newClient();
return client.connect().then(() => {
this.defer(() => client.close());
const coll = client.db().collection('single_bulk_write_error');
return coll
.drop()
.catch(ignoreNsNotFound)
.then(() => coll.insert(Array.from({ length: 4 }, (_, i) => ({ _id: i, a: i }))))
.then(() =>
coll.bulkWrite([{ insertOne: { _id: 5, a: 0 } }, { insertOne: { _id: 5, a: 0 } }])
)
.then(
() => {
throw new Error('expected a bulk error');
},
err => {
expect(err)
.property('message')
.to.match(/E11000/);
expect(err)
.to.have.property('writeErrors')
.with.length(1);
}
);
});
});
it('should preserve order of operation index in unordered bulkWrite', function() {
const client = this.configuration.newClient();
return client.connect().then(() => {
this.defer(() => client.close());
const coll = client.db().collection('bulk_write_ordering_test');
return coll
.drop()
.catch(ignoreNsNotFound)
.then(() => coll.insert(Array.from({ length: 4 }, (_, i) => ({ _id: i, a: i }))))
.then(() =>
coll
.createIndex({ a: 1 }, { unique: true })
.then(() =>
coll.bulkWrite(
[
{ insertOne: { _id: 5, a: 0 } },
{ updateOne: { filter: { _id: 1 }, update: { $set: { a: 15 } } } },
{ insertOne: { _id: 6, a: 0 } },
{ updateOne: { filter: { _id: 2 }, update: { $set: { a: 42 } } } }
],
{ ordered: false }
)
)
)
.then(
() => {
throw new Error('expected a bulk error');
},
err => {
expect(err)
.to.have.property('writeErrors')
.with.length(2);
expect(err).to.have.nested.property('writeErrors[0].err.index', 0);
expect(err).to.have.nested.property('writeErrors[1].err.index', 2);
}
);
});
});
it('should preserve order of operation index in unordered bulk operation', function() {
const client = this.configuration.newClient();
return client.connect().then(() => {
this.defer(() => client.close());
const coll = client.db().collection('unordered_preserve_order');
return coll
.drop()
.catch(ignoreNsNotFound)
.then(() => {
const batch = coll.initializeUnorderedBulkOp();
batch.insert({ _id: 1, a: 0 });
batch.insert({ _id: 1, a: 0 });
batch.insert({ _id: 2, a: 0 });
batch.insert({ _id: 2, a: 0 });
return batch.execute();
})
.then(
() => {
throw new Error('expected a bulk error');
},
err => {
expect(err)
.to.have.property('writeErrors')
.with.length(2);
expect(err).to.have.nested.property('writeErrors[0].err.index', 1);
expect(err).to.have.nested.property('writeErrors[1].err.index', 3);
}
);
});
});
it('should not fail on the first error in an unorderd bulkWrite', function() {
const client = this.configuration.newClient();
return client.connect().then(() => {
this.defer(() => client.close());
const coll = client.db().collection('bulk_op_ordering_test');
return coll
.drop()
.catch(ignoreNsNotFound)
.then(() => coll.createIndex({ email: 1 }, { unique: 1, background: false }))
.then(() =>
Promise.all([
coll.updateOne(
{ email: '[email protected]' },
{ $set: { name: 'Adam Smith', age: 29 } },
{ upsert: true }
),
coll.updateOne(
{ email: '[email protected]' },
{ $set: { name: 'John Doe', age: 32 } },
{ upsert: true }
)
])
)
.then(() =>
coll.bulkWrite(
[
{
updateOne: {
filter: { email: '[email protected]' },
update: { $set: { age: 39 } }
}
},
{
insertOne: {
document: {
email: '[email protected]'
}
}
}
],
{ ordered: false }
)
)
.then(
() => {
throw new Error('expected a bulk error');
},
err =>
expect(err)
.property('code')
.to.equal(11000)
)
.then(() => coll.findOne({ email: '[email protected]' }))
.then(updatedAdam =>
expect(updatedAdam)
.property('age')
.to.equal(39)
);
});
});
});
| 1 | 19,135 | `writeConcernMax` was changed to return a `writeConcern` formatted the new way-- `writeConcern: {w:1, ...}`. Bulk execute takes an actual `WriteConcern` object as its first parameter (this was changed in master), so we have to un-wrap the `writeConcernMax` result here. | mongodb-node-mongodb-native | js |
@@ -1,9 +1,10 @@
module TabularData
class Container
- attr_reader :columns
+ attr_reader :columns, :frozen_sort
def initialize(name, config)
@name = name
+ @frozen_sort = false
self.init_query(config[:engine].constantize, config.fetch(:joins, []))
self.init_columns(config.fetch(:column_configs, {}), config.fetch(:columns, {}))
self.set_sort(config[:sort]) | 1 | module TabularData
class Container
attr_reader :columns
def initialize(name, config)
@name = name
self.init_query(config[:engine].constantize, config.fetch(:joins, []))
self.init_columns(config.fetch(:column_configs, {}), config.fetch(:columns, {}))
self.set_sort(config[:sort])
end
def alter_query
@query = yield(@query)
self
end
# @todo filtering, paging, etc.
def rows
@query.order(@sort)
end
def set_state_from_params(params)
relevant = params.permit(tables: {@name => [:sort]})
config = relevant.fetch(:tables, {}).fetch(@name, {}) || {}
if config.has_key? :sort
self.set_sort(config[:sort])
end
self
end
def sort_params(original_params, col)
if col.sort_dir == :asc # flip to descending
original_params.deep_merge(tables: {@name => {sort: '-' + col.name}})
else
original_params.deep_merge(tables: {@name => {sort: col.name}})
end
end
def self.config_for_client(container_name, client_name)
filename = "#{Rails.root}/config/tables/#{container_name}.yml"
container_yaml = YAML.load_file(filename)
key = "default"
if container_yaml.has_key?(client_name)
key = client_name
end
container_yaml[key].deep_symbolize_keys
end
protected
def set_sort(field)
field = field || ''
dir = field.start_with?('-') ? :desc : :asc
field = field.gsub(/\A-/, '')
@columns.each do |column|
if column.name == field
@sort = column.sort(dir)
else
column.sort(nil)
end
end
end
def init_query(engine, joins)
@query = engine.all() # convert into a query
joins.each do |name, config|
if config == true
join_tables = engine.joins(name).join_sources
join_tables[-1].left.table_alias = name # alias the table
@query = @query.joins(join_tables).includes(name)
else # String config
@query = @query.joins(config)
end
end
end
def init_columns(config, order)
column_hash = {}
config.map do |name, col_config|
if col_config == true # short hand for "no configuration"
col_config = {}
end
qualified_name = "#{@query.table_name}.#{name}"
column_hash[name] = Column.new(name, qualified_name, col_config)
end
@columns = order.map{|name| column_hash[name.to_sym]}
end
end
end
| 1 | 13,737 | How about passing this through the `config`? | 18F-C2 | rb |
@@ -373,10 +373,10 @@ def create_secret(secretsmanager_client):
secretsmanager_client.delete_secret(SecretId=item)
-only_localstack = pytest.mark.skipif(
- os.environ.get("TEST_TARGET") == "AWS_CLOUD",
- reason="test only applicable if run against localstack",
-)
[email protected]
+def only_localstack():
+ if os.environ.get("TEST_TARGET") == "AWS_CLOUD":
+ pytest.skip("test only applicable if run against localstack")
@pytest.fixture | 1 | import logging
import os
from typing import TYPE_CHECKING, List
import boto3
import botocore.config
import pytest
from localstack.utils import testutil
from localstack.utils.aws import aws_stack
from localstack.utils.aws.aws_stack import create_dynamodb_table
from localstack.utils.common import short_uid
from localstack.utils.testutil import start_http_server
if TYPE_CHECKING:
from mypy_boto3_apigateway import APIGatewayClient
from mypy_boto3_cloudformation import CloudFormationClient
from mypy_boto3_dynamodb import DynamoDBClient
from mypy_boto3_es import ElasticsearchServiceClient
from mypy_boto3_events import EventBridgeClient
from mypy_boto3_iam import IAMClient
from mypy_boto3_kinesis import KinesisClient
from mypy_boto3_kms import KMSClient
from mypy_boto3_lambda import LambdaClient
from mypy_boto3_logs import CloudWatchLogsClient
from mypy_boto3_s3 import S3Client
from mypy_boto3_secretsmanager import SecretsManagerClient
from mypy_boto3_ses import SESClient
from mypy_boto3_sns import SNSClient
from mypy_boto3_sqs import SQSClient
from mypy_boto3_ssm import SSMClient
from mypy_boto3_stepfunctions import SFNClient
LOG = logging.getLogger(__name__)
def _client(service):
if os.environ.get("TEST_TARGET") == "AWS_CLOUD":
return boto3.client(service)
# can't set the timeouts to 0 like in the AWS CLI because the underlying http client requires values > 0
config = (
botocore.config.Config(
connect_timeout=1_000, read_timeout=1_000, retries={"total_max_attempts": 1}
)
if os.environ.get("TEST_DISABLE_RETRIES_AND_TIMEOUTS")
else None
)
return aws_stack.connect_to_service(service, config=config)
@pytest.fixture(scope="class")
def dynamodb_client() -> "DynamoDBClient":
return _client("dynamodb")
@pytest.fixture(scope="class")
def apigateway_client() -> "APIGatewayClient":
return _client("apigateway")
@pytest.fixture(scope="class")
def iam_client() -> "IAMClient":
return _client("iam")
@pytest.fixture(scope="class")
def s3_client() -> "S3Client":
return _client("s3")
@pytest.fixture(scope="class")
def sqs_client() -> "SQSClient":
return _client("sqs")
@pytest.fixture(scope="class")
def sns_client() -> "SNSClient":
return _client("sns")
@pytest.fixture(scope="class")
def cfn_client() -> "CloudFormationClient":
return _client("cloudformation")
@pytest.fixture(scope="class")
def ssm_client() -> "SSMClient":
return _client("ssm")
@pytest.fixture(scope="class")
def lambda_client() -> "LambdaClient":
return _client("lambda")
@pytest.fixture(scope="class")
def kinesis_client() -> "KinesisClient":
return _client("kinesis")
@pytest.fixture(scope="class")
def kms_client() -> "KMSClient":
return _client("kms")
@pytest.fixture(scope="class")
def logs_client() -> "CloudWatchLogsClient":
return _client("logs")
@pytest.fixture(scope="class")
def events_client() -> "EventBridgeClient":
return _client("events")
@pytest.fixture(scope="class")
def secretsmanager_client() -> "SecretsManagerClient":
return _client("secretsmanager")
@pytest.fixture(scope="class")
def stepfunctions_client() -> "SFNClient":
return _client("stepfunctions")
@pytest.fixture(scope="class")
def ses_client() -> "SESClient":
return _client("ses")
@pytest.fixture(scope="class")
def es_client() -> "ElasticsearchServiceClient":
return _client("es")
@pytest.fixture
def dynamodb_create_table(dynamodb_client):
tables = list()
def factory(**kwargs):
kwargs["client"] = dynamodb_client
if "table_name" not in kwargs:
kwargs["table_name"] = "test-table-%s" % short_uid()
if "partition_key" not in kwargs:
kwargs["partition_key"] = "id"
kwargs["sleep_after"] = 0
tables.append(kwargs["table_name"])
return create_dynamodb_table(**kwargs)
yield factory
# cleanup
for table in tables:
try:
dynamodb_client.delete_table(TableName=table)
except Exception as e:
LOG.debug("error cleaning up table %s: %s", table, e)
@pytest.fixture
def s3_create_bucket(s3_client):
buckets = list()
def factory(**kwargs) -> str:
if "Bucket" not in kwargs:
kwargs["Bucket"] = "test-bucket-%s" % short_uid()
s3_client.create_bucket(**kwargs)
buckets.append(kwargs["Bucket"])
return kwargs["Bucket"]
yield factory
# cleanup
for bucket in buckets:
try:
s3_client.delete_bucket(Bucket=bucket)
except Exception as e:
LOG.debug("error cleaning up bucket %s: %s", bucket, e)
@pytest.fixture
def s3_bucket(s3_create_bucket) -> str:
return s3_create_bucket()
@pytest.fixture
def sqs_create_queue(sqs_client):
queue_urls = list()
def factory(**kwargs):
if "QueueName" not in kwargs:
kwargs["QueueName"] = "test-queue-%s" % short_uid()
response = sqs_client.create_queue(**kwargs)
url = response["QueueUrl"]
queue_urls.append(url)
return url
yield factory
# cleanup
for queue_url in queue_urls:
try:
sqs_client.delete_queue(QueueUrl=queue_url)
except Exception as e:
LOG.debug("error cleaning up queue %s: %s", queue_url, e)
@pytest.fixture
def sqs_queue(sqs_create_queue):
return sqs_create_queue()
@pytest.fixture
def sns_topic(sns_client):
# TODO: add fixture factories
topic_name = "test-topic-%s" % short_uid()
response = sns_client.create_topic(Name=topic_name)
topic_arn = response["TopicArn"]
yield sns_client.get_topic_attributes(TopicArn=topic_arn)
sns_client.delete_topic(TopicArn=topic_arn)
@pytest.fixture
def kms_key(kms_client):
return kms_client.create_key(
Policy="policy1", Description="test key 123", KeyUsage="ENCRYPT_DECRYPT"
)
@pytest.fixture
def kms_grant_and_key(kms_client, kms_key):
return [
kms_client.create_grant(
KeyId=kms_key["KeyMetadata"]["KeyId"],
GranteePrincipal="arn:aws:iam::000000000000:role/test",
Operations=["Decrypt", "Encrypt"],
),
kms_key,
]
# Cleanup fixtures
@pytest.fixture
def cleanup_stacks(cfn_client):
def _cleanup_stacks(stacks: List[str]) -> None:
for stack in stacks:
try:
cfn_client.delete_stack(StackName=stack)
except Exception:
LOG.debug(f"Failed to cleanup stack '{stack}'")
return _cleanup_stacks
@pytest.fixture
def cleanup_changesets(cfn_client):
def _cleanup_changesets(changesets: List[str]) -> None:
for cs in changesets:
try:
cfn_client.delete_change_set(ChangeSetName=cs)
except Exception:
LOG.debug(f"Failed to cleanup changeset '{cs}'")
return _cleanup_changesets
# Helpers for Cfn
@pytest.fixture
def is_change_set_created_and_available(cfn_client):
def _is_change_set_created_and_available(change_set_id: str):
def _inner():
change_set = cfn_client.describe_change_set(ChangeSetName=change_set_id)
return (
# TODO: CREATE_FAILED should also not lead to further retries
change_set.get("Status") == "CREATE_COMPLETE"
and change_set.get("ExecutionStatus") == "AVAILABLE"
)
return _inner
return _is_change_set_created_and_available
@pytest.fixture
def is_stack_created(cfn_client):
return _has_stack_status(cfn_client, ["CREATE_COMPLETE", "CREATE_FAILED"])
@pytest.fixture
def is_stack_updated(cfn_client):
return _has_stack_status(cfn_client, ["UPDATE_COMPLETE", "UPDATE_FAILED"])
@pytest.fixture
def is_stack_deleted(cfn_client):
return _has_stack_status(cfn_client, ["DELETE_COMPLETE"])
def _has_stack_status(cfn_client, statuses: List[str]):
def _has_status(stack_id: str):
def _inner():
resp = cfn_client.describe_stacks(StackName=stack_id)
s = resp["Stacks"][0] # since the lookup uses the id we can only get a single response
return s.get("StackStatus") in statuses
return _inner
return _has_status
@pytest.fixture
def is_change_set_finished(cfn_client):
def _is_change_set_finished(change_set_id: str):
def _inner():
check_set = cfn_client.describe_change_set(ChangeSetName=change_set_id)
return check_set.get("ExecutionStatus") == "EXECUTE_COMPLETE"
return _inner
return _is_change_set_finished
@pytest.fixture
def create_lambda_function(lambda_client: "LambdaClient"):
lambda_arns = list()
def _create_lambda_function(*args, **kwargs):
# TODO move create function logic here to use lambda_client fixture
resp = testutil.create_lambda_function(*args, **kwargs)
lambda_arns.append(resp["CreateFunctionResponse"]["FunctionArn"])
return resp
yield _create_lambda_function
for arn in lambda_arns:
lambda_client.delete_function(FunctionName=arn)
@pytest.fixture
def create_parameter(ssm_client):
params = []
def _create_parameter(**kwargs):
params.append(kwargs["Name"])
return ssm_client.put_parameter(**kwargs)
yield _create_parameter
for param in params:
ssm_client.delete_parameter(Name=param)
@pytest.fixture
def create_secret(secretsmanager_client):
items = []
def _create_parameter(**kwargs):
create_response = secretsmanager_client.create_secret(**kwargs)
items.append(create_response["ARN"])
return create_response
yield _create_parameter
for item in items:
secretsmanager_client.delete_secret(SecretId=item)
only_localstack = pytest.mark.skipif(
os.environ.get("TEST_TARGET") == "AWS_CLOUD",
reason="test only applicable if run against localstack",
)
@pytest.fixture
def tmp_http_server():
test_port, invocations, proxy = start_http_server()
yield test_port, invocations, proxy
proxy.stop()
| 1 | 13,787 | Out of curiosity - did we make this change to allow dynamically assigning a value to `os.environ["TEST_TARGET"]` during test execution? I kind of liked the decorator style `@only_localstack` - makes the condition a bit more explicit. Looks like `skipif` also allows to specify a condition string, e.g. `pytest.mark.skipif('os.environ.get("TEST_TARGET") == "AWS_CLOUD"')` - could that be an option? (not sure if that gets lazily evaluated at runtime right before the execution of the annotated test method starts, though..) | localstack-localstack | py |
@@ -72,6 +72,7 @@ class SliderItem implements OrderableEntityInterface
*/
public function edit(SliderItemData $sliderItemData)
{
+ $this->domainId = $sliderItemData->domainId;
$this->name = $sliderItemData->name;
$this->link = $sliderItemData->link;
$this->hidden = $sliderItemData->hidden; | 1 | <?php
namespace Shopsys\FrameworkBundle\Model\Slider;
use Doctrine\ORM\Mapping as ORM;
use Shopsys\FrameworkBundle\Component\Grid\Ordering\OrderableEntityInterface;
/**
* SliderItem
*
* @ORM\Table(name="slider_items")
* @ORM\Entity
*/
class SliderItem implements OrderableEntityInterface
{
/**
* @var int
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @var string
*
* @ORM\Column(type="text")
*/
protected $name;
/**
* @var string
*
* @ORM\Column(type="text")
*/
protected $link;
/**
* @var int
*
* @ORM\Column(type="integer")
*/
protected $domainId;
/**
* @var int|null
*
* @ORM\Column(type="integer", nullable=true)
*/
protected $position;
/**
* @var bool
*
* @ORM\Column(type="boolean")
*/
protected $hidden;
/**
* @param \Shopsys\FrameworkBundle\Model\Slider\SliderItemData $sliderItemData
*/
public function __construct(SliderItemData $sliderItemData)
{
$this->domainId = $sliderItemData->domainId;
$this->name = $sliderItemData->name;
$this->link = $sliderItemData->link;
$this->hidden = $sliderItemData->hidden;
}
/**
* @param \Shopsys\FrameworkBundle\Model\Slider\SliderItemData $sliderItemData
*/
public function edit(SliderItemData $sliderItemData)
{
$this->name = $sliderItemData->name;
$this->link = $sliderItemData->link;
$this->hidden = $sliderItemData->hidden;
}
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getLink()
{
return $this->link;
}
/**
* @return int
*/
public function getDomainId()
{
return $this->domainId;
}
/**
* @return int|null
*/
public function getPosition()
{
return $this->position;
}
/**
* @param int $position
*/
public function setPosition($position)
{
$this->position = $position;
}
/**
* @return bool
*/
public function isHidden()
{
return $this->hidden;
}
}
| 1 | 21,489 | I noticed (SonarCloud noticed actually) that the implementation of `::edit` method is the same as `__construct` is. Does it make sense to call the `edit` method from the constructor? | shopsys-shopsys | php |
@@ -78,6 +78,7 @@ int syslog_prot_process(struct syslog_conn *conn)
/* Incomplete message */
if (eof == end || (*eof != '\n' && *eof != '\0')) {
+ flb_debug("[syslog-prot] incomplete message! (Enable trace log to see the message.)");
return 0;
}
| 1 | /* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* Fluent Bit
* ==========
* Copyright (C) 2019 The Fluent Bit Authors
* Copyright (C) 2015-2018 Treasure Data Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string.h>
#include <fluent-bit/flb_info.h>
#include <fluent-bit/flb_parser.h>
#include <fluent-bit/flb_time.h>
#include "syslog.h"
#include "syslog_conn.h"
static inline void consume_bytes(char *buf, int bytes, int length)
{
memmove(buf, buf + bytes, length - bytes);
}
static inline int pack_line(struct flb_syslog *ctx,
struct flb_time *time, char *data, size_t data_size)
{
msgpack_packer mp_pck;
msgpack_sbuffer mp_sbuf;
/* Initialize local msgpack buffer */
msgpack_sbuffer_init(&mp_sbuf);
msgpack_packer_init(&mp_pck, &mp_sbuf, msgpack_sbuffer_write);
msgpack_pack_array(&mp_pck, 2);
flb_time_append_to_msgpack(time, &mp_pck, 0);
msgpack_sbuffer_write(&mp_sbuf, data, data_size);
flb_input_chunk_append_raw(ctx->i_ins, NULL, 0, mp_sbuf.data, mp_sbuf.size);
msgpack_sbuffer_destroy(&mp_sbuf);
return 0;
}
int syslog_prot_process(struct syslog_conn *conn)
{
int len;
int ret;
char *p;
char *eof;
char *end;
void *out_buf;
size_t out_size;
struct flb_time out_time;
struct flb_syslog *ctx = conn->ctx;
eof = p = conn->buf_data;
end = conn->buf_data + conn->buf_len;
/* Always parse while some remaining bytes exists */
while (eof < end) {
/* Lookup the ending byte */
eof = conn->buf_data + conn->buf_parsed;
while (*eof != '\n' && *eof != '\0' && eof < end) {
eof++;
}
/* Incomplete message */
if (eof == end || (*eof != '\n' && *eof != '\0')) {
return 0;
}
/* No data ? */
len = (eof - p);
if (len == 0) {
consume_bytes(conn->buf_data, 1, conn->buf_len);
conn->buf_len--;
conn->buf_parsed = 0;
conn->buf_data[conn->buf_len] = '\0';
end = conn->buf_data + conn->buf_len;
if (conn->buf_len == 0) {
return 0;
}
continue;
}
/* Process the string */
ret = flb_parser_do(ctx->parser, p, len,
&out_buf, &out_size, &out_time);
if (ret >= 0) {
pack_line(ctx, &out_time, out_buf, out_size);
flb_free(out_buf);
}
else {
flb_warn("[in_syslog] error parsing log message");
}
conn->buf_parsed += len + 1;
end = conn->buf_data + conn->buf_len;
eof = p = conn->buf_data + conn->buf_parsed;
}
consume_bytes(conn->buf_data, conn->buf_parsed, conn->buf_len);
conn->buf_len -= conn->buf_parsed;
conn->buf_parsed = 0;
conn->buf_data[conn->buf_len] = '\0';
return 0;
}
int syslog_prot_process_udp(char *buf, size_t size, struct flb_syslog *ctx)
{
int ret;
void *out_buf;
size_t out_size;
struct flb_time out_time = {0};
ret = flb_parser_do(ctx->parser, buf, size,
&out_buf, &out_size, &out_time);
if (ret >= 0) {
if (flb_time_to_double(&out_time) == 0) {
flb_time_get(&out_time);
}
pack_line(ctx, &out_time, out_buf, out_size);
flb_free(out_buf);
}
else {
flb_warn("[in_syslog] error parsing log message");
return -1;
}
return 0;
}
| 1 | 9,744 | would you please rename the message prefix to: [in_syslog] ..." | fluent-fluent-bit | c |
@@ -600,8 +600,8 @@ struct AtomMatch { // for each seed atom (matched)
};
typedef std::vector<AtomMatch> AtomMatchSet;
-std::string MaximumCommonSubgraph::generateResultSMARTS(
- const MCS& mcsIdx) const {
+std::string MaximumCommonSubgraph::generateResultSMARTSAndQueryMol(
+ const MCS& mcsIdx, RWMol **molExt) const {
// match the result MCS with all targets to check if it is exact match or
// template
Seed seed; // result MCS | 1 | //
// Copyright (C) 2014 Novartis Institutes for BioMedical Research
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <list>
#include <algorithm>
#include <math.h>
#include "../QueryAtom.h"
#include "../QueryBond.h"
#include "../SmilesParse/SmilesWrite.h"
#include "../SmilesParse/SmartsWrite.h"
#include "../SmilesParse/SmilesParse.h"
#include "../Substruct/SubstructMatch.h"
#include "SubstructMatchCustom.h"
#include "MaximumCommonSubgraph.h"
#include <boost/graph/adjacency_list.hpp>
namespace RDKit {
namespace FMCS {
struct LabelDefinition {
unsigned ItemIndex; // item with this label value
unsigned Value;
LabelDefinition() : ItemIndex(NotSet), Value(NotSet) {}
LabelDefinition(unsigned i, unsigned value) : ItemIndex(i), Value(value) {}
};
MaximumCommonSubgraph::MaximumCommonSubgraph(const MCSParameters* params) {
Parameters = (nullptr != params ? *params : MCSParameters());
if (!Parameters.ProgressCallback) {
Parameters.ProgressCallback = MCSProgressCallbackTimeout;
Parameters.ProgressCallbackUserData = &To;
}
if ((Parameters.AtomCompareParameters.MatchChiralTag ||
Parameters.BondCompareParameters.MatchFusedRings ||
Parameters.BondCompareParameters.MatchFusedRingsStrict) &&
nullptr == Parameters.FinalMatchChecker) {
Parameters.FinalMatchChecker = FinalMatchCheckFunction;
if (Parameters.AtomCompareParameters.MatchChiralTag)
Parameters.BondCompareParameters.MatchStereo = true;
}
To = nanoClock();
}
static bool molPtr_NumBondLess(
const ROMol* l,
const ROMol* r) { // need for sorting the source molecules by size
return l->getNumBonds() < r->getNumBonds();
}
void MaximumCommonSubgraph::init() {
QueryMolecule = Molecules.front();
Targets.clear();
#ifdef FAST_SUBSTRUCT_CACHE
QueryAtomLabels.clear();
QueryBondLabels.clear();
QueryAtomMatchTable.clear();
QueryBondMatchTable.clear();
RingMatchTables.clear();
#endif
#ifdef DUP_SUBSTRUCT_CACHE
DuplicateCache.clear();
#endif
void* userData = Parameters.CompareFunctionsUserData;
if (Parameters.BondCompareParameters.CompleteRingsOnly ||
Parameters.BondCompareParameters.RingMatchesRingOnly ||
Parameters.AtomCompareParameters.RingMatchesRingOnly) {
#ifdef FAST_SUBSTRUCT_CACHE
RingMatchTables.init(QueryMolecule);
Parameters.CompareFunctionsUserData = &RingMatchTables;
#endif
}
size_t nq = 0;
#ifdef FAST_SUBSTRUCT_CACHE
// fill out RingMatchTables to check cache Hash collision by checking match a
// part of Query to Query
if (!userData // predefined functor - compute RingMatchTable for all targets
&& (Parameters.BondCompareParameters.CompleteRingsOnly ||
Parameters.BondCompareParameters.RingMatchesRingOnly ||
Parameters.AtomCompareParameters.RingMatchesRingOnly))
RingMatchTables.computeRingMatchTable(QueryMolecule, QueryMolecule,
Parameters);
// fill out match tables
nq = QueryMolecule->getNumAtoms();
QueryAtomMatchTable.resize(nq, nq);
for (size_t aj = 0; aj < nq; aj++)
for (size_t ai = 0; ai < nq; ai++)
QueryAtomMatchTable.set(
ai, aj,
Parameters.AtomTyper(Parameters.AtomCompareParameters, *QueryMolecule,
ai, *QueryMolecule, aj,
Parameters.CompareFunctionsUserData));
nq = QueryMolecule->getNumBonds();
QueryBondMatchTable.resize(nq, nq);
for (size_t aj = 0; aj < nq; aj++)
for (size_t ai = 0; ai < nq; ai++)
QueryBondMatchTable.set(
ai, aj,
Parameters.BondTyper(Parameters.BondCompareParameters, *QueryMolecule,
ai, *QueryMolecule, aj,
Parameters.CompareFunctionsUserData));
// Compute label values based on current functor and parameters for code
// Morgan correct computation.
unsigned currentLabelValue = 1;
std::vector<LabelDefinition> labels;
nq = QueryMolecule->getNumAtoms();
QueryAtomLabels.resize(nq);
for (size_t ai = 0; ai < nq; ai++) {
if (MCSAtomCompareAny ==
Parameters
.AtomTyper) // predefined functor without atom compare parameters
QueryAtomLabels[ai] = 1;
else {
const Atom* atom = QueryMolecule->getAtomWithIdx(ai);
if (MCSAtomCompareElements ==
Parameters
.AtomTyper) // predefined functor without atom compare parameters
QueryAtomLabels[ai] = atom->getAtomicNum() |
(Parameters.AtomCompareParameters.MatchValences
? (atom->getTotalValence() >> 8)
: 0);
else if (MCSAtomCompareIsotopes ==
Parameters.AtomTyper) // predefined functor without atom compare
// parameters
QueryAtomLabels[ai] = atom->getAtomicNum() | (atom->getIsotope() >> 8) |
(Parameters.AtomCompareParameters.MatchValences
? (atom->getTotalValence() >> 16)
: 0);
else { // custom user defined functor
QueryAtomLabels[ai] = NotSet;
for (auto& label : labels)
if (Parameters.AtomTyper(Parameters.AtomCompareParameters,
*QueryMolecule, label.ItemIndex,
*QueryMolecule, ai,
userData)) { // equal itoms
QueryAtomLabels[ai] = label.Value;
break;
}
if (NotSet == QueryAtomLabels[ai]) { // not found -> create new label
QueryAtomLabels[ai] = ++currentLabelValue;
labels.push_back(LabelDefinition(ai, currentLabelValue));
}
}
}
}
labels.clear();
currentLabelValue = 1;
nq = QueryMolecule->getNumBonds();
QueryBondLabels.resize(nq);
for (size_t aj = 0; aj < nq; aj++) {
const Bond* bond = QueryMolecule->getBondWithIdx(aj);
unsigned ring = 0;
if (Parameters.BondCompareParameters.CompleteRingsOnly ||
Parameters.BondCompareParameters.RingMatchesRingOnly) {
ring = RingMatchTables.isQueryBondInRing(aj) ? 0 : 1; // is bond in ring
}
if (MCSBondCompareAny ==
Parameters
.BondTyper) // predefined functor without atom compare parameters
QueryBondLabels[aj] = 1 | (ring >> 8);
else if (MCSBondCompareOrderExact ==
Parameters
.BondTyper) // predefined functor without compare parameters
QueryBondLabels[aj] = (bond->getBondType() + 1) | (ring >> 8);
else if (MCSBondCompareOrder ==
Parameters
.BondTyper) { // predefined functor, ignore Aromatization
unsigned order = bond->getBondType();
if (Bond::AROMATIC == order ||
Bond::ONEANDAHALF == order) // ignore Aromatization
order = Bond::SINGLE;
else if (Bond::TWOANDAHALF == order)
order = Bond::DOUBLE;
else if (Bond::THREEANDAHALF == order)
order = Bond::TRIPLE;
else if (Bond::FOURANDAHALF == order)
order = Bond::QUADRUPLE;
else if (Bond::FIVEANDAHALF == order)
order = Bond::QUINTUPLE;
QueryBondLabels[aj] = (order + 1) | (ring >> 8);
} else { // custom user defined functor
QueryBondLabels[aj] = NotSet;
for (auto& label : labels)
if (Parameters.BondTyper(Parameters.BondCompareParameters,
*QueryMolecule, label.ItemIndex,
*QueryMolecule, aj,
userData)) { // equal bonds + ring ...
QueryBondLabels[aj] = label.Value;
break;
}
if (NotSet == QueryAtomLabels[aj]) { // not found -> create new label
QueryBondLabels[aj] = ++currentLabelValue;
labels.push_back(LabelDefinition(aj, currentLabelValue));
}
}
}
#endif
Targets.resize(Molecules.size() - 1);
size_t i = 0;
for (auto it = Molecules.begin() + 1; it != Molecules.end(); it++, i++) {
Targets[i].Molecule = *it;
// build Target Topology ADD ATOMs
size_t j = 0; // current item
for (ROMol::ConstAtomIterator a = Targets[i].Molecule->beginAtoms();
a != Targets[i].Molecule->endAtoms(); a++, j++) {
Targets[i].Topology.addAtom((*a)->getIdx());
}
// build Target Topology ADD BONDs
for (ROMol::ConstBondIterator b = Targets[i].Molecule->beginBonds();
b != Targets[i].Molecule->endBonds(); b++) {
const Bond* bond = *b;
unsigned ii = bond->getBeginAtomIdx();
unsigned jj = bond->getEndAtomIdx();
Targets[i].Topology.addBond((*b)->getIdx(), ii, jj);
}
// fill out RingMatchTables
if (!userData // predefined functor - compute RingMatchTable for all
// targets
&& (Parameters.BondCompareParameters.CompleteRingsOnly ||
Parameters.BondCompareParameters.RingMatchesRingOnly)) {
#ifdef FAST_SUBSTRUCT_CACHE
RingMatchTables.addTargetBondRingsIndeces(Targets[i].Molecule);
RingMatchTables.computeRingMatchTable(QueryMolecule, Targets[i].Molecule,
Parameters);
#endif
}
// fill out match tables
size_t nq = QueryMolecule->getNumAtoms();
size_t nt = (*it)->getNumAtoms();
Targets[i].AtomMatchTable.resize(nq, nt);
for (size_t aj = 0; aj < nt; aj++)
for (size_t ai = 0; ai < nq; ai++)
Targets[i].AtomMatchTable.set(
ai, aj,
Parameters.AtomTyper(Parameters.AtomCompareParameters,
*QueryMolecule, ai, *Targets[i].Molecule, aj,
Parameters.CompareFunctionsUserData));
nq = QueryMolecule->getNumBonds();
nt = (*it)->getNumBonds();
Targets[i].BondMatchTable.resize(nq, nt);
for (size_t aj = 0; aj < nt; aj++)
for (size_t ai = 0; ai < nq; ai++)
Targets[i].BondMatchTable.set(
ai, aj,
Parameters.BondTyper(Parameters.BondCompareParameters,
*QueryMolecule, ai, *Targets[i].Molecule, aj,
Parameters.CompareFunctionsUserData));
}
Parameters.CompareFunctionsUserData = userData; // restore
}
struct QueryRings {
std::vector<unsigned> BondRings; // amount of rings
std::vector<unsigned> AtomRings; // amount of rings
QueryRings(const ROMol* query)
: BondRings(query->getNumBonds()), AtomRings(query->getNumAtoms()) {
{
for (unsigned int& BondRing : BondRings) BondRing = 0;
const RingInfo::VECT_INT_VECT& rings = query->getRingInfo()->bondRings();
for (const auto& ring : rings)
for (int ri : ring) ++BondRings[ri];
}
{
for (unsigned int& AtomRing : AtomRings) AtomRing = 0;
const RingInfo::VECT_INT_VECT& rings = query->getRingInfo()->atomRings();
for (const auto& ring : rings)
for (int ri : ring) ++AtomRings[ri];
}
}
inline unsigned getNumberRings(const Bond* bond) const {
return BondRings[bond->getIdx()];
}
inline unsigned getNumberRings(const Atom* atom) const {
return AtomRings[atom->getIdx()];
}
};
struct WeightedBond {
const Bond* BondPtr;
unsigned Weight;
WeightedBond() : BondPtr(nullptr), Weight(0) {}
WeightedBond(const Bond* bond, const QueryRings& r)
: BondPtr(bond), Weight(0) {
// score ((bond.is_in_ring + atom1.is_in_ring + atom2.is_in_ring)
if (r.getNumberRings(bond)) Weight += 1;
if (r.getNumberRings(bond->getBeginAtom())) Weight += 1;
if (r.getNumberRings(bond->getEndAtom())) Weight += 1;
}
bool operator<(const WeightedBond& r) {
return Weight >= r.Weight; // sort in Z-A order (Rings first)
}
};
void MaximumCommonSubgraph::makeInitialSeeds() {
// build a set of initial seeds as "all" single bonds from query molecule
std::vector<bool> excludedBonds(QueryMolecule->getNumBonds(), false);
Seeds.clear();
QueryMoleculeMatchedBonds = 0;
QueryMoleculeMatchedAtoms = 0;
if (!Parameters.InitialSeed.empty()) { // make user defined seed
std::auto_ptr<const ROMol> initialSeedMolecule(
(const ROMol*)SmartsToMol(Parameters.InitialSeed));
// make a set of of seed as indeces and pointers to current query molecule
// items based on matching results
std::vector<MatchVectType> matching_substructs;
SubstructMatch(*QueryMolecule, *initialSeedMolecule, matching_substructs);
// loop throw all fragments of Query matched to initial seed
for (std::vector<MatchVectType>::const_iterator ms =
matching_substructs.begin();
ms != matching_substructs.end(); ms++) {
Seed seed;
seed.ExcludedBonds = excludedBonds;
seed.MatchResult.resize(Targets.size());
#ifdef VERBOSE_STATISTICS_ON
{
++VerboseStatistics.Seed;
++VerboseStatistics.InitialSeed;
}
#endif
// add all matched atoms of the matched query fragment
std::map<unsigned, unsigned> initialSeedToQueryAtom;
for (const auto& msb : *ms) {
unsigned qai = msb.second;
unsigned sai = msb.first;
seed.addAtom(QueryMolecule->getAtomWithIdx(qai));
initialSeedToQueryAtom[sai] = qai;
}
// add all bonds (existed in initial seed !!!) between all matched atoms
// in query
for (const auto& msb : *ms) {
const Atom* atom = initialSeedMolecule->getAtomWithIdx(msb.first);
ROMol::OEDGE_ITER beg, end;
for (boost::tie(beg, end) = initialSeedMolecule->getAtomBonds(atom);
beg != end; beg++) {
const Bond& initialBond = *((*initialSeedMolecule)[*beg]);
unsigned qai1 =
initialSeedToQueryAtom.find(initialBond.getBeginAtomIdx())
->second;
unsigned qai2 =
initialSeedToQueryAtom.find(initialBond.getEndAtomIdx())->second;
const Bond* b = QueryMolecule->getBondBetweenAtoms(qai1, qai2);
if (!seed.ExcludedBonds[b->getIdx()]) {
seed.addBond(b);
seed.ExcludedBonds[b->getIdx()] = true;
}
}
}
seed.computeRemainingSize(*QueryMolecule);
if (checkIfMatchAndAppend(seed))
QueryMoleculeMatchedBonds = seed.getNumBonds();
}
} else { // create a set of seeds from each query bond
// R1 additional performance OPTIMISATION
// if(Parameters.BondCompareParameters.CompleteRingsOnly)
// disable all mismatched rings, and do not generate initial seeds from such
// disabled bonds
// for( rings .....) for(i......)
// if(mismatched) excludedBonds[i.......] = true;
QueryRings r(QueryMolecule);
std::vector<WeightedBond> wb;
wb.reserve(QueryMolecule->getNumBonds());
for (RWMol::ConstBondIterator bi = QueryMolecule->beginBonds();
bi != QueryMolecule->endBonds(); bi++)
wb.push_back(WeightedBond(*bi, r));
for (std::vector<WeightedBond>::const_iterator bi = wb.begin();
bi != wb.end(); bi++) {
// R1 additional performance OPTIMISATION
// if(excludedBonds[(*bi)->getIdx()])
// continue;
Seed seed;
seed.MatchResult.resize(Targets.size());
#ifdef VERBOSE_STATISTICS_ON
{
++VerboseStatistics.Seed;
++VerboseStatistics.InitialSeed;
}
#endif
seed.addAtom(bi->BondPtr->getBeginAtom());
seed.addAtom(bi->BondPtr->getEndAtom());
seed.ExcludedBonds = excludedBonds; // all bonds from first to current
seed.addBond(bi->BondPtr);
excludedBonds[bi->BondPtr->getIdx()] = true;
seed.computeRemainingSize(*QueryMolecule);
if (checkIfMatchAndAppend(seed)) {
++QueryMoleculeMatchedBonds;
} else {
// optionally remove all such bonds from all targets TOPOLOGY where it
// exists.
//..........
// disable (mark as already processed) mismatched bond in all seeds
for (auto& Seed : Seeds)
Seed.ExcludedBonds[bi->BondPtr->getIdx()] = true;
#ifdef VERBOSE_STATISTICS_ON
++VerboseStatistics.MismatchedInitialSeed;
#endif
}
}
}
size_t nq = QueryMolecule->getNumAtoms();
for (size_t i = 0; i < nq; i++) { // all query's atoms
unsigned matched = 0;
for (std::vector<Target>::const_iterator tag = Targets.begin();
tag != Targets.end(); tag++) {
size_t nt = tag->Molecule->getNumAtoms();
for (size_t aj = 0; aj < nt; aj++) {
if (tag->AtomMatchTable.at(i, aj)) {
++matched;
break;
}
}
}
if (matched >= ThresholdCount) ++QueryMoleculeMatchedAtoms;
}
}
namespace {
void _DFS(const Graph& g, const boost::dynamic_bitset<>& ringBonds,
boost::dynamic_bitset<>& openBonds, unsigned vertex,
std::vector<unsigned> apath, std::vector<unsigned>& colors,
unsigned fromVertex) {
std::pair<Graph::out_edge_iterator, Graph::out_edge_iterator> bonds =
boost::out_edges(vertex, g);
colors[vertex] = 1;
while (bonds.first != bonds.second) {
unsigned bIdx = g[*(bonds.first)];
if (!ringBonds[bIdx]) {
++bonds.first;
continue;
}
// find the other vertex:
unsigned oVertex = boost::source(*(bonds.first), g);
if (oVertex == vertex) oVertex = boost::target((*bonds.first), g);
++bonds.first;
if (oVertex == fromVertex) continue;
if (colors[oVertex] == 1) {
// closing a cycle
for (auto ai = apath.rbegin(); ai != apath.rend() && *ai != oVertex;
++ai) {
auto epair = boost::edge(*ai, *(ai + 1), g);
CHECK_INVARIANT(epair.second, "edge not found");
openBonds.reset(g[epair.first]);
}
auto epair = boost::edge(oVertex, *apath.rbegin(), g);
CHECK_INVARIANT(epair.second, "edge not found");
openBonds.reset(g[epair.first]);
} else if (colors[oVertex] == 0) {
std::vector<unsigned> napath = apath;
napath.push_back(oVertex);
_DFS(g, ringBonds, openBonds, oVertex, napath, colors, vertex);
}
}
colors[vertex] = 2;
return;
}
bool checkIfRingsAreClosed(const Seed& fs) {
if (!fs.MoleculeFragment.Bonds.size()) return true;
bool res = true;
const auto& om = fs.MoleculeFragment.Bonds[0]->getOwningMol();
const auto ri = om.getRingInfo();
boost::dynamic_bitset<> ringBonds(om.getNumBonds());
for (const auto bond : fs.MoleculeFragment.Bonds) {
if (ri->numBondRings(bond->getIdx())) ringBonds.set(bond->getIdx());
}
boost::dynamic_bitset<> openBonds = ringBonds;
if (openBonds.any()) {
std::vector<unsigned> colors(om.getNumAtoms());
for (unsigned bi = 0; bi < openBonds.size(); ++bi) {
if (!openBonds[bi]) continue;
std::pair<Graph::edge_iterator, Graph::edge_iterator> bonds =
boost::edges(fs.Topology);
while (bonds.first != bonds.second && fs.Topology[*(bonds.first)] != bi)
++bonds.first;
CHECK_INVARIANT(bonds.first != bonds.second, "bond not found");
unsigned startVertex = boost::source(*(bonds.first), fs.Topology);
std::vector<unsigned> apath = {startVertex};
_DFS(fs.Topology, ringBonds, openBonds, startVertex, apath, colors,
om.getNumAtoms() + 1);
}
res = openBonds.none();
}
return res;
}
} // namespace
bool MaximumCommonSubgraph::growSeeds() {
bool mcsFound = false;
bool canceled = false;
unsigned steps = 99999; // steps from last progress callback call. call it
// immediately in the begining
// Find MCS -- SDF Seed growing OPTIMISATION (it works in 3 times faster)
while (!Seeds.empty()) {
if (getMaxNumberBonds() == QueryMoleculeMatchedBonds) // MCS == Query
break;
++steps;
#ifdef VERBOSE_STATISTICS_ON
VerboseStatistics.TotalSteps++;
#endif
auto si = Seeds.begin();
si->grow(*this);
{
const Seed& fs = Seeds.front();
// bigger substructure found
if (fs.CopyComplete) {
bool possibleMCS = false;
if ((!Parameters.MaximizeBonds &&
(fs.getNumAtoms() > getMaxNumberAtoms() ||
(fs.getNumAtoms() == getMaxNumberAtoms() &&
fs.getNumBonds() > getMaxNumberBonds())))) {
possibleMCS = true;
} else if (Parameters.MaximizeBonds &&
(fs.getNumBonds() > getMaxNumberBonds() ||
(fs.getNumBonds() == getMaxNumberBonds() &&
fs.getNumAtoms() > getMaxNumberAtoms()))) {
possibleMCS = true;
}
// #945: test here to see if the MCS actually has all rings closed
if (possibleMCS && Parameters.BondCompareParameters.CompleteRingsOnly) {
possibleMCS = checkIfRingsAreClosed(fs);
}
if (possibleMCS) {
mcsFound = true;
#ifdef VERBOSE_STATISTICS_ON
VerboseStatistics.MCSFoundStep = VerboseStatistics.TotalSteps;
VerboseStatistics.MCSFoundTime = nanoClock();
#endif
McsIdx.Atoms = fs.MoleculeFragment.Atoms;
McsIdx.Bonds = fs.MoleculeFragment.Bonds;
McsIdx.AtomsIdx = fs.MoleculeFragment.AtomsIdx;
McsIdx.BondsIdx = fs.MoleculeFragment.BondsIdx;
if (Parameters.Verbose) {
std::cout << VerboseStatistics.TotalSteps
<< " Seeds:" << Seeds.size() << " MCS "
<< McsIdx.Atoms.size() << " atoms, "
<< McsIdx.Bonds.size() << " bonds";
printf(" for %.4lf seconds. bond[0]=%u\n",
double(VerboseStatistics.MCSFoundTime - To) / 1000000.,
McsIdx.BondsIdx[0]);
}
}
}
}
if (NotSet == si->GrowingStage) // finished
Seeds.erase(si);
if (Parameters.ProgressCallback) {
steps = 0;
Stat.NumAtoms = getMaxNumberAtoms();
Stat.NumBonds = getMaxNumberBonds();
if (!Parameters.ProgressCallback(Stat, Parameters,
Parameters.ProgressCallbackUserData)) {
canceled = true;
break;
}
}
}
if (mcsFound) { // postponed copy of current set of molecules for threshold <
// 1.
McsIdx.QueryMolecule = QueryMolecule;
McsIdx.Targets = Targets;
}
return !canceled;
} // namespace FMCS
struct AtomMatch { // for each seed atom (matched)
unsigned QueryAtomIdx;
unsigned TargetAtomIdx;
AtomMatch() : QueryAtomIdx(NotSet), TargetAtomIdx(NotSet) {}
};
typedef std::vector<AtomMatch> AtomMatchSet;
std::string MaximumCommonSubgraph::generateResultSMARTS(
const MCS& mcsIdx) const {
// match the result MCS with all targets to check if it is exact match or
// template
Seed seed; // result MCS
seed.ExcludedBonds.resize(mcsIdx.QueryMolecule->getNumBonds(), false);
std::vector<AtomMatchSet> atomMatchResult(mcsIdx.Targets.size());
std::vector<unsigned> atomIdxMap(mcsIdx.QueryMolecule->getNumAtoms());
std::vector<std::map<unsigned, const Bond*>> bondMatchSet(
mcsIdx.Bonds.size()); // key is unique BondType
std::vector<std::map<unsigned, const Atom*>> atomMatchSet(
mcsIdx.Atoms.size()); // key is unique atomic number
for (auto atom : mcsIdx.Atoms) {
atomIdxMap[atom->getIdx()] = seed.getNumAtoms();
seed.addAtom(atom);
}
for (auto bond : mcsIdx.Bonds) seed.addBond(bond);
unsigned itarget = 0;
for (auto tag = mcsIdx.Targets.begin(); tag != mcsIdx.Targets.end();
tag++, itarget++) {
match_V_t match; // THERE IS NO Bonds match INFO !!!!
bool target_matched = SubstructMatchCustomTable(
tag->Topology, *tag->Molecule, seed.Topology, *QueryMolecule,
tag->AtomMatchTable, tag->BondMatchTable, &Parameters, &match);
if (!target_matched) continue;
atomMatchResult[itarget].resize(seed.getNumAtoms());
for (match_V_t::const_iterator mit = match.begin(); mit != match.end();
mit++) {
unsigned ai = mit->first; // SeedAtomIdx
atomMatchResult[itarget][ai].QueryAtomIdx = seed.Topology[mit->first];
atomMatchResult[itarget][ai].TargetAtomIdx = tag->Topology[mit->second];
const Atom* ta =
tag->Molecule->getAtomWithIdx(tag->Topology[mit->second]);
if (ta &&
ta->getAtomicNum() != seed.MoleculeFragment.Atoms[ai]->getAtomicNum())
atomMatchSet[ai][ta->getAtomicNum()] = ta; // add
}
// AND BUILD BOND MATCH INFO
unsigned bi = 0;
for (auto bond = mcsIdx.Bonds.begin(); bond != mcsIdx.Bonds.end();
bond++, bi++) {
unsigned i = atomIdxMap[(*bond)->getBeginAtomIdx()];
unsigned j = atomIdxMap[(*bond)->getEndAtomIdx()];
unsigned ti = atomMatchResult[itarget][i].TargetAtomIdx;
unsigned tj = atomMatchResult[itarget][j].TargetAtomIdx;
const Bond* tb = tag->Molecule->getBondBetweenAtoms(ti, tj);
if (tb && (*bond)->getBondType() != tb->getBondType())
bondMatchSet[bi][tb->getBondType()] = tb; // add
}
}
// Generate result's SMARTS
RWMol mol; // create molecule from MCS for MolToSmarts()
unsigned ai = 0; // SeedAtomIdx
for (auto atom = mcsIdx.Atoms.begin(); atom != mcsIdx.Atoms.end();
atom++, ai++) {
QueryAtom a;
if (Parameters.AtomTyper ==
MCSAtomCompareIsotopes) { // do '[0*]-[0*]-[13*]' for CC[13NH2]
a.setQuery(makeAtomIsotopeQuery((int)(*atom)->getIsotope()));
} else {
// generate [#6] instead of C or c !
a.setQuery(makeAtomNumQuery((*atom)->getAtomicNum()));
// for all atomMatchSet[ai] items add atom query to template like
// [#6,#17,#9, ... ]
for (std::map<unsigned, const Atom*>::const_iterator am =
atomMatchSet[ai].begin();
am != atomMatchSet[ai].end(); am++) {
a.expandQuery(makeAtomNumQuery(am->second->getAtomicNum()),
Queries::COMPOSITE_OR);
if (Parameters.AtomCompareParameters.MatchChiralTag &&
(am->second->getChiralTag() == Atom::CHI_TETRAHEDRAL_CW ||
am->second->getChiralTag() == Atom::CHI_TETRAHEDRAL_CCW))
a.setChiralTag(am->second->getChiralTag());
}
}
if (Parameters.AtomCompareParameters.RingMatchesRingOnly) {
ATOM_EQUALS_QUERY *q = makeAtomInRingQuery();
q->setNegation(!queryIsAtomInRing(*atom));
a.expandQuery(q, Queries::COMPOSITE_AND, true);
}
mol.addAtom(&a, true, false);
}
unsigned bi = 0; // Seed Idx
for (auto bond = mcsIdx.Bonds.begin(); bond != mcsIdx.Bonds.end();
bond++, bi++) {
QueryBond b;
unsigned beginAtomIdx = atomIdxMap[(*bond)->getBeginAtomIdx()];
unsigned endAtomIdx = atomIdxMap[(*bond)->getEndAtomIdx()];
b.setBeginAtomIdx(beginAtomIdx);
b.setEndAtomIdx(endAtomIdx);
b.setQuery(makeBondOrderEqualsQuery((*bond)->getBondType()));
// add OR template if need
for (std::map<unsigned, const Bond*>::const_iterator bm =
bondMatchSet[bi].begin();
bm != bondMatchSet[bi].end(); bm++) {
b.expandQuery(makeBondOrderEqualsQuery(bm->second->getBondType()),
Queries::COMPOSITE_OR);
if (Parameters.BondCompareParameters.MatchStereo &&
bm->second->getStereo() > Bond::STEREOANY)
b.setStereo(bm->second->getStereo());
}
if (Parameters.BondCompareParameters.RingMatchesRingOnly) {
BOND_EQUALS_QUERY *q = makeBondIsInRingQuery();
q->setNegation(!queryIsBondInRing(*bond));
b.expandQuery(q, Queries::COMPOSITE_AND, true);
}
mol.addBond(&b, false);
}
return MolToSmarts(mol, true);
}
bool MaximumCommonSubgraph::createSeedFromMCS(size_t newQueryTarget,
Seed& newSeed) {
Seed mcs;
mcs.ExcludedBonds.resize(McsIdx.QueryMolecule->getNumBonds(), false);
std::vector<unsigned> mcsAtomIdxMap(McsIdx.QueryMolecule->getNumAtoms());
for (std::vector<const Atom*>::const_iterator atom = McsIdx.Atoms.begin();
atom != McsIdx.Atoms.end(); atom++) {
mcsAtomIdxMap[(*atom)->getIdx()] = mcs.addAtom((*atom));
}
for (std::vector<const Bond*>::const_iterator bond = McsIdx.Bonds.begin();
bond != McsIdx.Bonds.end(); bond++)
mcs.addBond((*bond));
const Target& newQuery = McsIdx.Targets[newQueryTarget];
match_V_t match;
bool target_matched = SubstructMatchCustomTable(
newQuery.Topology, *newQuery.Molecule, mcs.Topology,
*McsIdx.QueryMolecule, newQuery.AtomMatchTable, newQuery.BondMatchTable,
&Parameters, &match);
if (!target_matched) return false;
AtomMatchSet atomMatchResult(mcs.getNumAtoms());
newSeed.ExcludedBonds.resize(newQuery.Molecule->getNumBonds(), false);
for (match_V_t::const_iterator mit = match.begin(); mit != match.end();
mit++) {
unsigned ai = mit->first; // SeedAtomIdx in mcs seed
atomMatchResult[ai].QueryAtomIdx = mcs.Topology[mit->first];
atomMatchResult[ai].TargetAtomIdx = newQuery.Topology[mit->second];
const Atom* ta =
newQuery.Molecule->getAtomWithIdx(newQuery.Topology[mit->second]);
newSeed.addAtom(ta);
}
for (std::vector<const Bond*>::const_iterator bond = McsIdx.Bonds.begin();
bond != McsIdx.Bonds.end(); bond++) {
unsigned i = mcsAtomIdxMap[(*bond)->getBeginAtomIdx()];
unsigned j = mcsAtomIdxMap[(*bond)->getEndAtomIdx()];
unsigned ti = atomMatchResult[i].TargetAtomIdx;
unsigned tj = atomMatchResult[j].TargetAtomIdx;
const Bond* tb = newQuery.Molecule->getBondBetweenAtoms(ti, tj);
newSeed.addBond(tb);
}
newSeed.computeRemainingSize(*newQuery.Molecule);
return true;
}
MCSResult MaximumCommonSubgraph::find(const std::vector<ROMOL_SPTR>& src_mols) {
clear();
MCSResult res;
if (src_mols.size() < 2)
throw std::runtime_error(
"FMCS. Invalid argument. mols.size() must be at least 2");
if (Parameters.Threshold > 1.0)
throw std::runtime_error(
"FMCS. Invalid argument. Parameter Threshold must be 1.0 or less.");
ThresholdCount = (unsigned)ceil((src_mols.size()) * Parameters.Threshold) -
1; // minimal required number of matched targets
if (ThresholdCount < 1) // at least one target
ThresholdCount = 1;
if (ThresholdCount > src_mols.size() - 1) // max all targets
ThresholdCount = src_mols.size() - 1;
// Selecting CompleteRingsOnly option also enables --ring-matches-ring-only.
// ring--ring and chain bonds only match chain bonds.
if (Parameters.BondCompareParameters.MatchFusedRings
|| Parameters.BondCompareParameters.MatchFusedRingsStrict)
Parameters.BondCompareParameters.CompleteRingsOnly = true;
if (Parameters.BondCompareParameters.CompleteRingsOnly)
Parameters.BondCompareParameters.RingMatchesRingOnly = true;
for (const auto& src_mol : src_mols) {
Molecules.push_back(src_mol.get());
if (!Molecules.back()->getRingInfo()->isInitialized())
Molecules.back()->getRingInfo()->initialize(); // but do not fill out !!!
}
// sort source set of molecules by their 'size' and assume the smallest
// molecule as a query
std::stable_sort(Molecules.begin(), Molecules.end(), molPtr_NumBondLess);
for (size_t i = 0; i < Molecules.size() - ThresholdCount && !res.Canceled;
i++) {
init();
if (Targets.empty()) break;
MCSFinalMatchCheckFunction tff = Parameters.FinalMatchChecker;
if (FinalMatchCheckFunction == Parameters.FinalMatchChecker)
Parameters.FinalMatchChecker = nullptr; // skip final match check for
// initial seed to allow future growing
// of it
makeInitialSeeds();
Parameters.FinalMatchChecker = tff; // restore final functor
if (Parameters.Verbose)
std::cout << "Query " << MolToSmiles(*QueryMolecule) << " "
<< QueryMolecule->getNumAtoms() << "("
<< QueryMoleculeMatchedAtoms << ") atoms, "
<< QueryMolecule->getNumBonds() << "("
<< QueryMoleculeMatchedBonds << ") bonds\n";
if (Seeds.empty()) break;
res.Canceled = growSeeds() ? false : true;
// verify what MCS is equal to one of initial seed for chirality match
if ((FinalMatchCheckFunction == Parameters.FinalMatchChecker &&
1 == getMaxNumberBonds()) || 0 == getMaxNumberBonds()) {
McsIdx = MCS(); // clear
makeInitialSeeds(); // check all possible initial seeds
if (!Seeds.empty()) {
const Seed& fs = Seeds.front();
if (1 == getMaxNumberBonds()
|| !(Parameters.BondCompareParameters.CompleteRingsOnly
&& fs.MoleculeFragment.Bonds.size() == 1
&& queryIsBondInRing(fs.MoleculeFragment.Bonds.front()))) {
McsIdx.QueryMolecule = QueryMolecule;
McsIdx.Atoms = fs.MoleculeFragment.Atoms;
McsIdx.Bonds = fs.MoleculeFragment.Bonds;
McsIdx.AtomsIdx = fs.MoleculeFragment.AtomsIdx;
McsIdx.BondsIdx = fs.MoleculeFragment.BondsIdx;
}
}
} else if (i + 1 < Molecules.size() - ThresholdCount) {
Seed seed;
if (createSeedFromMCS(i, seed)) // MCS is matched with new query
Seeds.push_back(seed);
std::swap(Molecules[0],
Molecules[i + 1]); // change query molecule for threshold < 1.
}
}
res.NumAtoms = getMaxNumberAtoms();
res.NumBonds = getMaxNumberBonds();
if (res.NumBonds > 0) res.SmartsString = generateResultSMARTS(McsIdx);
#ifdef VERBOSE_STATISTICS_ON
if (Parameters.Verbose) {
unsigned itarget = 0;
for (std::vector<Target>::const_iterator tag = Targets.begin();
res.NumAtoms > 0 && tag != Targets.end(); tag++, itarget++) {
MatchVectType match;
RWMol* m = SmartsToMol(res.SmartsString.c_str());
bool target_matched = SubstructMatch(*tag->Molecule, *m, match);
if (!target_matched)
std::cout << "Target " << itarget + 1
<< (target_matched ? " matched " : " MISMATCHED ")
<< MolToSmiles(*tag->Molecule) << "\n";
delete m;
}
std::cout << "STATISTICS:\n";
std::cout << "Total Growing Steps = " << VerboseStatistics.TotalSteps
<< ", MCS found on " << VerboseStatistics.MCSFoundStep << " step";
if (VerboseStatistics.MCSFoundTime - To > 0)
printf(", for %.4lf seconds\n",
double(VerboseStatistics.MCSFoundTime - To) / 1000000.);
else
std::cout << ", for less than 1 second\n";
std::cout << "Initial Seeds = " << VerboseStatistics.InitialSeed
<< ", Mismatched " << VerboseStatistics.MismatchedInitialSeed
<< "\n";
std::cout << "Inspected Seeds = " << VerboseStatistics.Seed << "\n";
std::cout << "Rejected by BestSize = "
<< VerboseStatistics.RemainingSizeRejected << "\n";
std::cout << "SingleBondExcluded = "
<< VerboseStatistics.SingleBondExcluded << "\n";
#ifdef EXCLUDE_WRONG_COMPOSITION
std::cout << "Rejected by WrongComposition = "
<< VerboseStatistics.WrongCompositionRejected << " [ "
<< VerboseStatistics.WrongCompositionDetected << " Detected ]\n";
#endif
std::cout << "MatchCheck Seeds = " << VerboseStatistics.SeedCheck
<< "\n";
std::cout //<< "\n"
<< " MatchCalls = " << VerboseStatistics.MatchCall << "\n"
<< " MatchFound = " << VerboseStatistics.MatchCallTrue << "\n";
std::cout << " fastMatchCalls = " << VerboseStatistics.FastMatchCall << "\n"
<< " fastMatchFound = " << VerboseStatistics.FastMatchCallTrue
<< "\n";
std::cout << " slowMatchCalls = "
<< VerboseStatistics.MatchCall -
VerboseStatistics.FastMatchCallTrue
<< "\n"
<< " slowMatchFound = " << VerboseStatistics.SlowMatchCallTrue
<< "\n";
#ifdef VERBOSE_STATISTICS_FASTCALLS_ON
std::cout << "AtomFunctorCalls = " << VerboseStatistics.AtomFunctorCalls
<< "\n";
std::cout << "BondCompareCalls = " << VerboseStatistics.BondCompareCalls
<< "\n";
#endif
std::cout << " DupCacheFound = " << VerboseStatistics.DupCacheFound
<< " " << VerboseStatistics.DupCacheFoundMatch << " matched, "
<< VerboseStatistics.DupCacheFound -
VerboseStatistics.DupCacheFoundMatch
<< " mismatched\n";
#ifdef FAST_SUBSTRUCT_CACHE
std::cout << "HashCache size = " << HashCache.keyssize() << " keys\n";
std::cout << "HashCache size = " << HashCache.fullsize() << " entries\n";
std::cout << "FindHashInCache = " << VerboseStatistics.FindHashInCache
<< "\n";
std::cout << "HashFoundInCache= " << VerboseStatistics.HashKeyFoundInCache
<< "\n";
std::cout << "ExactMatchCalls = " << VerboseStatistics.ExactMatchCall
<< "\n"
<< "ExactMatchFound = " << VerboseStatistics.ExactMatchCallTrue
<< "\n";
#endif
}
#endif
clear();
return res;
}
bool MaximumCommonSubgraph::checkIfMatchAndAppend(Seed& seed) {
#ifdef VERBOSE_STATISTICS_ON
++VerboseStatistics.SeedCheck;
#endif
#ifdef FAST_SUBSTRUCT_CACHE
SubstructureCache::HashKey cacheKey;
SubstructureCache::TIndexEntry* cacheEntry = nullptr;
bool cacheEntryIsValid = false;
RDUNUSED_PARAM(cacheEntryIsValid); // unused var
#endif
bool foundInCache = false;
bool foundInDupCache = false;
{
#ifdef DUP_SUBSTRUCT_CACHE
if (DuplicateCache.find(seed.DupCacheKey, foundInCache)) {
// duplicate found. skip match() but store both seeds, because they will grow by
// different paths !!!
#ifdef VERBOSE_STATISTICS_ON
VerboseStatistics.DupCacheFound++;
VerboseStatistics.DupCacheFoundMatch += foundInCache ? 1 : 0;
#endif
if (!foundInCache) // mismatched !!!
return false;
}
foundInDupCache = foundInCache;
#endif
#ifdef FAST_SUBSTRUCT_CACHE
if (!foundInCache) {
#ifdef VERBOSE_STATISTICS_ON
++VerboseStatistics.FindHashInCache;
#endif
cacheEntry =
HashCache.find(seed, QueryAtomLabels, QueryBondLabels, cacheKey);
cacheEntryIsValid = true;
if (cacheEntry) { // possibly found. check for hash collision
#ifdef VERBOSE_STATISTICS_ON
++VerboseStatistics.HashKeyFoundInCache;
#endif
// check hash collisions (time +3%):
for (SubstructureCache::TIndexEntry::const_iterator g =
cacheEntry->begin();
!foundInCache && g != cacheEntry->end(); g++) {
if (g->m_vertices.size() != seed.getNumAtoms() ||
g->m_edges.size() != seed.getNumBonds())
continue;
#ifdef VERBOSE_STATISTICS_ON
++VerboseStatistics.ExactMatchCall;
#endif
// EXACT MATCH
foundInCache = SubstructMatchCustomTable(
(*g), *QueryMolecule, seed.Topology, *QueryMolecule,
QueryAtomMatchTable, QueryBondMatchTable, &Parameters);
#ifdef VERBOSE_STATISTICS_ON
if (foundInCache) ++VerboseStatistics.ExactMatchCallTrue;
#endif
}
}
}
#endif
}
bool found = foundInCache;
if (!found) {
found = match(seed);
}
Seed* newSeed = nullptr;
{
if (found) { // Store new generated seed, if found in cache or in all(-
// threshold) targets
{
newSeed = &Seeds.add(seed);
newSeed->CopyComplete = false;
}
#ifdef DUP_SUBSTRUCT_CACHE
if (!foundInDupCache && seed.getNumBonds() >= 3) // only seed with a ring
// can be duplicated -
// do not store very
// small seed in cache
DuplicateCache.add(seed.DupCacheKey, true);
#endif
#ifdef FAST_SUBSTRUCT_CACHE
if (!foundInCache) HashCache.add(seed, cacheKey, cacheEntry);
#endif
} else {
#ifdef DUP_SUBSTRUCT_CACHE
if (seed.getNumBonds() > 3)
DuplicateCache.add(seed.DupCacheKey,
false); // opt. cache mismatched duplicates too
#endif
}
}
if (newSeed)
*newSeed =
seed; // non-blocking copy for MULTI_THREAD and best CPU utilization
return found; // new matched seed has been actualy added
}
bool MaximumCommonSubgraph::match(Seed& seed) {
unsigned max_miss = Targets.size() - ThresholdCount;
unsigned missing = 0;
unsigned passed = 0;
unsigned itarget = 0;
for (std::vector<Target>::const_iterator tag = Targets.begin();
tag != Targets.end(); tag++, itarget++) {
#ifdef VERBOSE_STATISTICS_ON
{ ++VerboseStatistics.MatchCall; }
#endif
bool target_matched = false;
if (!seed.MatchResult.empty() && !seed.MatchResult[itarget].empty())
target_matched = matchIncrementalFast(seed, itarget);
if (!target_matched) { // slow full match
match_V_t match; // THERE IS NO Bonds match INFO !!!!
target_matched = SubstructMatchCustomTable(
tag->Topology, *tag->Molecule, seed.Topology, *QueryMolecule,
tag->AtomMatchTable, tag->BondMatchTable, &Parameters, &match);
// save current match info
if (target_matched) {
if (seed.MatchResult.empty()) seed.MatchResult.resize(Targets.size());
seed.MatchResult[itarget].init(seed, match, *QueryMolecule, *tag);
} else if (!seed.MatchResult.empty())
seed.MatchResult[itarget].clear(); //.Empty = true; // == fast clear();
#ifdef VERBOSE_STATISTICS_ON
if (target_matched) {
++VerboseStatistics.SlowMatchCallTrue;
}
#endif
}
if (target_matched) {
if (++passed >= ThresholdCount) // it's enought
break;
} else { // mismatched
if (++missing > max_miss) break;
}
}
if (missing <= max_miss) {
#ifdef VERBOSE_STATISTICS_ON
++VerboseStatistics.MatchCallTrue;
#endif
return true;
}
return false;
}
// call it for each target, if failed perform full match check
bool MaximumCommonSubgraph::matchIncrementalFast(Seed& seed, unsigned itarget) {
// use and update results of previous match stored in the seed
#ifdef VERBOSE_STATISTICS_ON
{ ++VerboseStatistics.FastMatchCall; }
#endif
const Target& target = Targets[itarget];
TargetMatch& match = seed.MatchResult[itarget];
if (match.empty()) return false;
/*
// CHIRALITY: FinalMatchCheck:
if(Parameters.AtomCompareParameters.MatchChiralTag ||
Parameters.FinalMatchChecker) { // TEMP
match.clear();
return false;
}
*/
bool matched = false;
for (unsigned newBondSeedIdx = match.MatchedBondSize;
newBondSeedIdx < seed.getNumBonds(); newBondSeedIdx++) {
matched = false;
bool atomAdded = false;
const Bond* newBond = seed.MoleculeFragment.Bonds[newBondSeedIdx];
unsigned newBondQueryIdx = seed.MoleculeFragment.BondsIdx[newBondSeedIdx];
unsigned newBondSourceAtomSeedIdx; // seed's index of atom from which new
// bond was added
unsigned newBondAnotherAtomSeedIdx; // seed's index of atom on another end
// of the bond
unsigned i =
seed.MoleculeFragment.SeedAtomIdxMap[newBond->getBeginAtomIdx()];
unsigned j = seed.MoleculeFragment.SeedAtomIdxMap[newBond->getEndAtomIdx()];
if (i >= match.MatchedAtomSize) { // this is new atom in the seed
newBondSourceAtomSeedIdx = j;
newBondAnotherAtomSeedIdx = i;
} else {
newBondSourceAtomSeedIdx = i;
newBondAnotherAtomSeedIdx = j;
}
unsigned newBondAnotherAtomQueryIdx =
seed.MoleculeFragment.AtomsIdx[newBondAnotherAtomSeedIdx];
unsigned newBondSourceAtomQueryIdx =
seed.MoleculeFragment.AtomsIdx[newBondSourceAtomSeedIdx];
unsigned newBondSourceAtomTargetIdx =
match.TargetAtomIdx
[newBondSourceAtomQueryIdx]; // matched to newBondSourceAtomSeedIdx
const Bond* tb = nullptr;
unsigned newBondAnotherAtomTargetIdx = NotSet;
if (newBondAnotherAtomSeedIdx <
match.MatchedAtomSize) { // new bond between old atoms - both are
// matched to exact atoms in the target
newBondAnotherAtomTargetIdx =
match.TargetAtomIdx[newBondAnotherAtomQueryIdx];
tb = target.Molecule->getBondBetweenAtoms(
newBondSourceAtomTargetIdx,
newBondAnotherAtomTargetIdx); // target bond between Source and
// Another atoms
if (tb) { // bond exists, check match with query molecule
unsigned tbi = tb->getIdx();
unsigned qbi = seed.MoleculeFragment.BondsIdx[newBondSeedIdx];
if (!match.VisitedTargetBonds[tbi]) // false if target bond is already
// matched
matched = target.BondMatchTable.at(qbi, tbi);
}
} else { // enumerate all bonds from source atom in the target
const Atom* atom =
target.Molecule->getAtomWithIdx(newBondSourceAtomTargetIdx);
ROMol::OEDGE_ITER beg, end;
for (boost::tie(beg, end) = target.Molecule->getAtomBonds(atom);
beg != end; beg++) {
tb = &*((*target.Molecule)[*beg]);
if (!match.VisitedTargetBonds[tb->getIdx()]) {
newBondAnotherAtomTargetIdx = tb->getBeginAtomIdx();
if (newBondSourceAtomTargetIdx == newBondAnotherAtomTargetIdx)
newBondAnotherAtomTargetIdx = tb->getEndAtomIdx();
if (newBondAnotherAtomSeedIdx <
seed.LastAddedAtomsBeginIdx // RING: old atom, new atom in
// matched substructure must be
// new in seed
|| std::find(seed.MoleculeFragment.AtomsIdx.begin() +
seed.LastAddedAtomsBeginIdx,
seed.MoleculeFragment.AtomsIdx.begin() +
newBondAnotherAtomSeedIdx,
newBondAnotherAtomQueryIdx) ==
seed.MoleculeFragment.AtomsIdx.end()) {
if (!match.VisitedTargetAtoms[newBondAnotherAtomTargetIdx])
continue;
} else {
if (match.VisitedTargetAtoms[newBondAnotherAtomTargetIdx]) continue;
}
// check AnotherAtom and bond
matched =
target.AtomMatchTable.at(newBondAnotherAtomQueryIdx,
newBondAnotherAtomTargetIdx) &&
target.BondMatchTable.at(
seed.MoleculeFragment.BondsIdx[newBondSeedIdx], tb->getIdx());
if (matched) {
atomAdded = true;
break;
}
}
}
}
if (matched) { // update match history
if (atomAdded) { // new atom has been added
match.MatchedAtomSize++;
match.TargetAtomIdx[newBondAnotherAtomQueryIdx] =
newBondAnotherAtomTargetIdx;
match.VisitedTargetAtoms[newBondAnotherAtomTargetIdx] = true;
}
match.MatchedBondSize++;
match.TargetBondIdx[newBondQueryIdx] = tb->getIdx();
match.VisitedTargetBonds[tb->getIdx()] = true;
} else {
match.clear();
return false;
}
}
if (match.MatchedAtomSize != seed.getNumAtoms() ||
match.MatchedBondSize !=
seed.getNumBonds()) { // number of unique items !!!
match.clear();
return false;
}
// CHIRALITY: FinalMatchCheck
if (matched && Parameters.FinalMatchChecker) {
std::vector<short unsigned> c1;
c1.reserve(4096);
std::vector<short unsigned> c2;
c2.reserve(4096);
for (unsigned si = 0; si < seed.getNumAtoms();
si++) { // index in the seed topology
c1.push_back(si);
c2.push_back(match.TargetAtomIdx[seed.Topology[si]]);
}
matched = Parameters.FinalMatchChecker(
c1.data(), c2.data(), *QueryMolecule, seed.Topology, *target.Molecule,
target.Topology, &Parameters); // check CHIRALITY
if (!matched) match.clear();
}
#ifdef VERBOSE_STATISTICS_ON
if (matched) {
#ifdef MULTI_THREAD
Guard statlock(StatisticsMutex);
#endif
++VerboseStatistics.FastMatchCallTrue;
}
#endif
return matched;
}
} // namespace FMCS
} // namespace RDKit
| 1 | 20,048 | The pointer to a pointer is kind of gross. How about either taking the `ROMOL_SPTR` directly or, preferably, returning an `std::pair`? | rdkit-rdkit | cpp |
@@ -164,7 +164,12 @@ func (pool *TransactionPool) rememberCommit(flush bool) {
func (pool *TransactionPool) PendingCount() int {
pool.pendingMu.RLock()
defer pool.pendingMu.RUnlock()
+ return pool.pendingCountLocked()
+}
+// pendingCountLocked is a helper for PendingCount that returns the number of
+// transactions pending in the pool
+func (pool *TransactionPool) pendingCountLocked() int {
var count int
for _, txgroup := range pool.pendingTxGroups {
count += len(txgroup) | 1 | // Copyright (C) 2019-2020 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand. If not, see <https://www.gnu.org/licenses/>.
package pools
import (
"fmt"
"sync"
"time"
"github.com/algorand/go-deadlock"
"github.com/algorand/go-algorand/config"
"github.com/algorand/go-algorand/data/basics"
"github.com/algorand/go-algorand/data/bookkeeping"
"github.com/algorand/go-algorand/data/transactions"
"github.com/algorand/go-algorand/data/transactions/verify"
"github.com/algorand/go-algorand/ledger"
"github.com/algorand/go-algorand/logging"
"github.com/algorand/go-algorand/logging/telemetryspec"
"github.com/algorand/go-algorand/util/condvar"
)
// TransactionPool is a struct maintaining a sanitized pool of transactions that are available for inclusion in
// a Block. We sanitize it by preventing duplicates and limiting the number of transactions retained for each account
type TransactionPool struct {
mu deadlock.Mutex
cond sync.Cond
expiredTxCount map[basics.Round]int
pendingBlockEvaluator *ledger.BlockEvaluator
numPendingWholeBlocks basics.Round
feeThresholdMultiplier uint64
ledger *ledger.Ledger
statusCache *statusCache
logStats bool
expFeeFactor uint64
txPoolMaxSize int
// pendingMu protects pendingTxGroups and pendingTxids
pendingMu deadlock.RWMutex
pendingTxGroups [][]transactions.SignedTxn
pendingVerifyParams [][]verify.Params
pendingTxids map[transactions.Txid]txPoolVerifyCacheVal
// Calls to remember() add transactions to rememberedTxGroups and
// rememberedTxids. Calling rememberCommit() adds them to the
// pendingTxGroups and pendingTxids. This allows us to batch the
// changes in OnNewBlock() without preventing a concurrent call
// to Pending() or Verified().
rememberedTxGroups [][]transactions.SignedTxn
rememberedVerifyParams [][]verify.Params
rememberedTxids map[transactions.Txid]txPoolVerifyCacheVal
}
// MakeTransactionPool is the constructor, it uses Ledger to ensure that no account has pending transactions that together overspend.
//
// The pool also contains status information for the last transactionPoolStatusSize
// transactions that were removed from the pool without being committed.
func MakeTransactionPool(ledger *ledger.Ledger, cfg config.Local) *TransactionPool {
if cfg.TxPoolExponentialIncreaseFactor < 1 {
cfg.TxPoolExponentialIncreaseFactor = 1
}
pool := TransactionPool{
pendingTxids: make(map[transactions.Txid]txPoolVerifyCacheVal),
rememberedTxids: make(map[transactions.Txid]txPoolVerifyCacheVal),
expiredTxCount: make(map[basics.Round]int),
ledger: ledger,
statusCache: makeStatusCache(cfg.TxPoolSize),
logStats: cfg.EnableAssembleStats,
expFeeFactor: cfg.TxPoolExponentialIncreaseFactor,
txPoolMaxSize: cfg.TxPoolSize,
}
pool.cond.L = &pool.mu
pool.recomputeBlockEvaluator(make(map[transactions.Txid]basics.Round))
return &pool
}
type txPoolVerifyCacheVal struct {
txn transactions.SignedTxn
params verify.Params
}
// TODO I moved this number to be a constant in the module, we should consider putting it in the local config
const expiredHistory = 10
// timeoutOnNewBlock determines how long Test() and Remember() wait for
// OnNewBlock() to process a new block that appears to be in the ledger.
const timeoutOnNewBlock = time.Second
// NumExpired returns the number of transactions that expired at the end of a round (only meaningful if cleanup has
// been called for that round)
func (pool *TransactionPool) NumExpired(round basics.Round) int {
pool.mu.Lock()
defer pool.mu.Unlock()
return pool.expiredTxCount[round]
}
// PendingTxIDs return the IDs of all pending transactions
func (pool *TransactionPool) PendingTxIDs() []transactions.Txid {
pool.pendingMu.RLock()
defer pool.pendingMu.RUnlock()
ids := make([]transactions.Txid, len(pool.pendingTxids))
i := 0
for txid := range pool.pendingTxids {
ids[i] = txid
i++
}
return ids
}
// Pending returns a list of transaction groups that should be proposed
// in the next block, in order.
func (pool *TransactionPool) Pending() [][]transactions.SignedTxn {
pool.pendingMu.RLock()
defer pool.pendingMu.RUnlock()
// note that this operation is safe for the sole reason that arrays in go are immutable.
// if the underlaying array need to be expanded, the actual underlaying array would need
// to be reallocated.
return pool.pendingTxGroups
}
// rememberCommit() saves the changes added by remember to
// pendingTxGroups and pendingTxids. The caller is assumed to
// be holding pool.mu. flush indicates whether previous
// pendingTxGroups and pendingTxids should be flushed out and
// replaced altogether by rememberedTxGroups and rememberedTxids.
func (pool *TransactionPool) rememberCommit(flush bool) {
pool.pendingMu.Lock()
defer pool.pendingMu.Unlock()
if flush {
pool.pendingTxGroups = pool.rememberedTxGroups
pool.pendingVerifyParams = pool.rememberedVerifyParams
pool.pendingTxids = pool.rememberedTxids
} else {
pool.pendingTxGroups = append(pool.pendingTxGroups, pool.rememberedTxGroups...)
pool.pendingVerifyParams = append(pool.pendingVerifyParams, pool.rememberedVerifyParams...)
for txid, txn := range pool.rememberedTxids {
pool.pendingTxids[txid] = txn
}
}
pool.rememberedTxGroups = nil
pool.rememberedVerifyParams = nil
pool.rememberedTxids = make(map[transactions.Txid]txPoolVerifyCacheVal)
}
// PendingCount returns the number of transactions currently pending in the pool.
func (pool *TransactionPool) PendingCount() int {
pool.pendingMu.RLock()
defer pool.pendingMu.RUnlock()
var count int
for _, txgroup := range pool.pendingTxGroups {
count += len(txgroup)
}
return count
}
// checkPendingQueueSize test to see if there is more room in the pending
// group transaction list. As long as we haven't surpassed the size limit, we
// should be good to go.
func (pool *TransactionPool) checkPendingQueueSize() error {
pendingSize := len(pool.Pending())
if pendingSize >= pool.txPoolMaxSize {
return fmt.Errorf("TransactionPool.Test: transaction pool have reached capacity")
}
return nil
}
func (pool *TransactionPool) checkSufficientFee(txgroup []transactions.SignedTxn) error {
// The baseline threshold fee per byte is 1, the smallest fee we can
// represent. This amounts to a fee of 100 for a 100-byte txn, which
// is well below MinTxnFee (1000). This means that, when the pool
// is not under load, the total MinFee dominates for small txns,
// but once the pool comes under load, the fee-per-byte will quickly
// come to dominate.
feePerByte := uint64(1)
// The threshold is multiplied by the feeThresholdMultiplier that
// tracks the load on the transaction pool over time. If the pool
// is mostly idle, feeThresholdMultiplier will be 0, and all txns
// are accepted (assuming the BlockEvaluator approves them, which
// requires a flat MinTxnFee).
feePerByte = feePerByte * pool.feeThresholdMultiplier
// The feePerByte should be bumped to 1 to make the exponentially
// threshold growing valid.
if feePerByte == 0 && pool.numPendingWholeBlocks > 1 {
feePerByte = uint64(1)
}
// The threshold grows exponentially if there are multiple blocks
// pending in the pool.
// golang has no convenient integer exponentiation, so we just
// do this in a loop
for i := 0; i < int(pool.numPendingWholeBlocks)-1; i++ {
feePerByte *= pool.expFeeFactor
}
for _, t := range txgroup {
feeThreshold := feePerByte * uint64(t.GetEncodedLength())
if t.Txn.Fee.Raw < feeThreshold {
return fmt.Errorf("fee %d below threshold %d (%d per byte * %d bytes)",
t.Txn.Fee, feeThreshold, feePerByte, t.GetEncodedLength())
}
}
return nil
}
// Test performs basic duplicate detection and well-formedness checks
// on a transaction group without storing the group.
func (pool *TransactionPool) Test(txgroup []transactions.SignedTxn) error {
if err := pool.checkPendingQueueSize(); err != nil {
return err
}
pool.mu.Lock()
defer pool.mu.Unlock()
if pool.pendingBlockEvaluator == nil {
return fmt.Errorf("Test: pendingBlockEvaluator is nil")
}
return pool.pendingBlockEvaluator.TestTransactionGroup(txgroup)
}
type poolIngestParams struct {
checkFee bool // if set, perform fee checks
preferSync bool // if set, wait until ledger is caught up
}
// remember attempts to add a transaction group to the pool.
func (pool *TransactionPool) remember(txgroup []transactions.SignedTxn, verifyParams []verify.Params) error {
params := poolIngestParams{
checkFee: true,
preferSync: true,
}
return pool.ingest(txgroup, verifyParams, params)
}
// add tries to add the transaction group to the pool, bypassing the fee
// priority checks.
func (pool *TransactionPool) add(txgroup []transactions.SignedTxn, verifyParams []verify.Params) error {
params := poolIngestParams{
checkFee: false,
preferSync: false,
}
return pool.ingest(txgroup, verifyParams, params)
}
// ingest checks whether a transaction group could be remembered in the pool,
// and stores this transaction if valid.
//
// ingest assumes that pool.mu is locked. It might release the lock
// while it waits for OnNewBlock() to be called.
func (pool *TransactionPool) ingest(txgroup []transactions.SignedTxn, verifyParams []verify.Params, params poolIngestParams) error {
if pool.pendingBlockEvaluator == nil {
return fmt.Errorf("TransactionPool.ingest: no pending block evaluator")
}
if params.preferSync {
// Make sure that the latest block has been processed by OnNewBlock().
// If not, we might be in a race, so wait a little bit for OnNewBlock()
// to catch up to the ledger.
latest := pool.ledger.Latest()
waitExpires := time.Now().Add(timeoutOnNewBlock)
for pool.pendingBlockEvaluator.Round() <= latest && time.Now().Before(waitExpires) {
condvar.TimedWait(&pool.cond, timeoutOnNewBlock)
if pool.pendingBlockEvaluator == nil {
return fmt.Errorf("TransactionPool.ingest: no pending block evaluator")
}
}
}
if params.checkFee {
err := pool.checkSufficientFee(txgroup)
if err != nil {
return err
}
}
err := pool.addToPendingBlockEvaluator(txgroup)
if err != nil {
return err
}
pool.rememberedTxGroups = append(pool.rememberedTxGroups, txgroup)
pool.rememberedVerifyParams = append(pool.rememberedVerifyParams, verifyParams)
for i, t := range txgroup {
pool.rememberedTxids[t.ID()] = txPoolVerifyCacheVal{txn: t, params: verifyParams[i]}
}
return nil
}
// RememberOne stores the provided transaction
// Precondition: Only RememberOne() properly-signed and well-formed transactions (i.e., ensure t.WellFormed())
func (pool *TransactionPool) RememberOne(t transactions.SignedTxn, verifyParams verify.Params) error {
return pool.Remember([]transactions.SignedTxn{t}, []verify.Params{verifyParams})
}
// Remember stores the provided transaction group
// Precondition: Only Remember() properly-signed and well-formed transactions (i.e., ensure t.WellFormed())
func (pool *TransactionPool) Remember(txgroup []transactions.SignedTxn, verifyParams []verify.Params) error {
if err := pool.checkPendingQueueSize(); err != nil {
return err
}
pool.mu.Lock()
defer pool.mu.Unlock()
err := pool.remember(txgroup, verifyParams)
if err != nil {
return fmt.Errorf("TransactionPool.Remember: %v", err)
}
pool.rememberCommit(false)
return nil
}
// Lookup returns the error associated with a transaction that used
// to be in the pool. If no status information is available (e.g., because
// it was too long ago, or the transaction committed successfully), then
// found is false. If the transaction is still in the pool, txErr is empty.
func (pool *TransactionPool) Lookup(txid transactions.Txid) (tx transactions.SignedTxn, txErr string, found bool) {
if pool == nil {
return transactions.SignedTxn{}, "", false
}
pool.mu.Lock()
defer pool.mu.Unlock()
pool.pendingMu.RLock()
defer pool.pendingMu.RUnlock()
cacheval, inPool := pool.pendingTxids[txid]
tx = cacheval.txn
if inPool {
return tx, "", true
}
return pool.statusCache.check(txid)
}
// Verified returns whether a given SignedTxn is already in the
// pool, and, since only verified transactions should be added
// to the pool, whether that transaction is verified (i.e., Verify
// returned success). This is used as an optimization to avoid
// re-checking signatures on transactions that we have already
// verified.
func (pool *TransactionPool) Verified(txn transactions.SignedTxn, params verify.Params) bool {
if pool == nil {
return false
}
pool.pendingMu.RLock()
defer pool.pendingMu.RUnlock()
cacheval, ok := pool.pendingTxids[txn.ID()]
if !ok {
return false
}
if cacheval.params != params {
return false
}
pendingSigTxn := cacheval.txn
return pendingSigTxn.Sig == txn.Sig && pendingSigTxn.Msig.Equal(txn.Msig) && pendingSigTxn.Lsig.Equal(&txn.Lsig)
}
// OnNewBlock excises transactions from the pool that are included in the specified Block or if they've expired
func (pool *TransactionPool) OnNewBlock(block bookkeeping.Block, delta ledger.StateDelta) {
var stats telemetryspec.ProcessBlockMetrics
var knownCommitted uint
var unknownCommitted uint
commitedTxids := delta.Txids
if pool.logStats {
pool.pendingMu.RLock()
for txid := range commitedTxids {
if _, ok := pool.pendingTxids[txid]; ok {
knownCommitted++
} else {
unknownCommitted++
}
}
pool.pendingMu.RUnlock()
}
pool.mu.Lock()
defer pool.mu.Unlock()
defer pool.cond.Broadcast()
if pool.pendingBlockEvaluator == nil || block.Round() >= pool.pendingBlockEvaluator.Round() {
// Adjust the pool fee threshold. The rules are:
// - If there was less than one full block in the pool, reduce
// the multiplier by 2x. It will eventually go to 0, so that
// only the flat MinTxnFee matters if the pool is idle.
// - If there were less than two full blocks in the pool, keep
// the multiplier as-is.
// - If there were two or more full blocks in the pool, grow
// the multiplier by 2x (or increment by 1, if 0).
switch pool.numPendingWholeBlocks {
case 0:
pool.feeThresholdMultiplier = pool.feeThresholdMultiplier / pool.expFeeFactor
case 1:
// Keep the fee multiplier the same.
default:
if pool.feeThresholdMultiplier == 0 {
pool.feeThresholdMultiplier = 1
} else {
pool.feeThresholdMultiplier = pool.feeThresholdMultiplier * pool.expFeeFactor
}
}
// Recompute the pool by starting from the new latest block.
// This has the side-effect of discarding transactions that
// have been committed (or that are otherwise no longer valid).
stats = pool.recomputeBlockEvaluator(commitedTxids)
}
stats.KnownCommittedCount = knownCommitted
stats.UnknownCommittedCount = unknownCommitted
proto := config.Consensus[block.CurrentProtocol]
pool.expiredTxCount[block.Round()] = int(stats.ExpiredCount)
delete(pool.expiredTxCount, block.Round()-expiredHistory*basics.Round(proto.MaxTxnLife))
if pool.logStats {
var details struct {
Round uint64
}
details.Round = uint64(block.Round())
logging.Base().Metrics(telemetryspec.Transaction, stats, details)
}
}
func (pool *TransactionPool) addToPendingBlockEvaluatorOnce(txgroup []transactions.SignedTxn) error {
r := pool.pendingBlockEvaluator.Round() + pool.numPendingWholeBlocks
for _, tx := range txgroup {
if tx.Txn.LastValid < r {
return transactions.TxnDeadError{
Round: r,
FirstValid: tx.Txn.FirstValid,
LastValid: tx.Txn.LastValid,
}
}
}
txgroupad := make([]transactions.SignedTxnWithAD, len(txgroup))
for i, tx := range txgroup {
txgroupad[i].SignedTxn = tx
}
return pool.pendingBlockEvaluator.TransactionGroup(txgroupad)
}
func (pool *TransactionPool) addToPendingBlockEvaluator(txgroup []transactions.SignedTxn) error {
err := pool.addToPendingBlockEvaluatorOnce(txgroup)
if err == ledger.ErrNoSpace {
pool.numPendingWholeBlocks++
pool.pendingBlockEvaluator.ResetTxnBytes()
err = pool.addToPendingBlockEvaluatorOnce(txgroup)
}
return err
}
// recomputeBlockEvaluator constructs a new BlockEvaluator and feeds all
// in-pool transactions to it (removing any transactions that are rejected
// by the BlockEvaluator).
func (pool *TransactionPool) recomputeBlockEvaluator(committedTxIds map[transactions.Txid]basics.Round) (stats telemetryspec.ProcessBlockMetrics) {
pool.pendingBlockEvaluator = nil
latest := pool.ledger.Latest()
prev, err := pool.ledger.BlockHdr(latest)
if err != nil {
logging.Base().Warnf("TransactionPool.recomputeBlockEvaluator: cannot get prev header for %d: %v",
latest, err)
return
}
// Process upgrade to see if we support the next protocol version
_, upgradeState, err := bookkeeping.ProcessUpgradeParams(prev)
if err != nil {
logging.Base().Warnf("TransactionPool.recomputeBlockEvaluator: error processing upgrade params for next round: %v", err)
return
}
// Ensure we know about the next protocol version (MakeBlock will panic
// if we don't, and we would rather stall locally than panic)
_, ok := config.Consensus[upgradeState.CurrentProtocol]
if !ok {
logging.Base().Warnf("TransactionPool.recomputeBlockEvaluator: next protocol version %v is not supported", upgradeState.CurrentProtocol)
return
}
next := bookkeeping.MakeBlock(prev)
pool.numPendingWholeBlocks = 0
pool.pendingBlockEvaluator, err = pool.ledger.StartEvaluator(next.BlockHeader)
if err != nil {
logging.Base().Warnf("TransactionPool.recomputeBlockEvaluator: cannot start evaluator: %v", err)
return
}
// Feed the transactions in order.
pool.pendingMu.RLock()
txgroups := pool.pendingTxGroups
verifyParams := pool.pendingVerifyParams
pool.pendingMu.RUnlock()
for i, txgroup := range txgroups {
if len(txgroup) == 0 {
continue
}
if _, alreadyCommitted := committedTxIds[txgroup[0].ID()]; alreadyCommitted {
continue
}
err := pool.add(txgroup, verifyParams[i])
if err != nil {
for _, tx := range txgroup {
pool.statusCache.put(tx, err.Error())
}
switch err.(type) {
case transactions.TxnDeadError:
stats.ExpiredCount++
default:
stats.RemovedInvalidCount++
}
}
}
pool.rememberCommit(true)
return
}
| 1 | 38,093 | the name confusing, please rename to `pendingCountNoLock` or similar | algorand-go-algorand | go |
@@ -44,13 +44,11 @@ func addTestingTsfBlocks(bc Blockchain) error {
[]byte{}, uint64(100000),
big.NewInt(10),
)
- sk, err := keypair.DecodePrivateKey(Gen.CreatorPrivKey)
- if err != nil {
- return err
- }
- if err := action.Sign(tsf0, sk); err != nil {
- return err
- }
+ pk, _ := hex.DecodeString(Gen.CreatorPubKey)
+ pubk, _ := keypair.BytesToPublicKey(pk)
+ sig, _ := hex.DecodeString("ea18385718db2a8b92fa2dcdc158a05aae17fc7e800cc735850bdc99ab7b081f32fce70080888742d7b6bee892034e38298b69ce5fff671c18f0bed827e1e21f9da2ba5d8c434e00")
+ tsf0.SetSrcPubkey(pubk)
+ tsf0.SetSignature(sig)
blk, err := bc.MintNewBlock([]action.Action{tsf0}, ta.Addrinfo["producer"],
nil, nil, "")
if err != nil { | 1 | // Copyright (c) 2018 IoTeX
// This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no
// warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent
// permitted by law, all liability for your use of the code is disclaimed. This source code is governed by Apache
// License 2.0 that can be found in the LICENSE file.
package blockchain
import (
"context"
"encoding/hex"
"fmt"
"math/big"
"testing"
"github.com/facebookgo/clock"
"github.com/stretchr/testify/require"
"github.com/iotexproject/iotex-core/action"
"github.com/iotexproject/iotex-core/address"
"github.com/iotexproject/iotex-core/config"
"github.com/iotexproject/iotex-core/crypto"
"github.com/iotexproject/iotex-core/iotxaddress"
"github.com/iotexproject/iotex-core/pkg/hash"
_hash "github.com/iotexproject/iotex-core/pkg/hash"
"github.com/iotexproject/iotex-core/pkg/keypair"
"github.com/iotexproject/iotex-core/state"
ta "github.com/iotexproject/iotex-core/test/testaddress"
"github.com/iotexproject/iotex-core/testutil"
)
const (
testDBPath = "db.test"
testTriePath = "trie.test"
)
func addTestingTsfBlocks(bc Blockchain) error {
// Add block 0
tsf0, _ := action.NewTransfer(
1,
big.NewInt(3000000000),
Gen.CreatorAddr(config.Default.Chain.ID),
ta.Addrinfo["producer"].RawAddress,
[]byte{}, uint64(100000),
big.NewInt(10),
)
sk, err := keypair.DecodePrivateKey(Gen.CreatorPrivKey)
if err != nil {
return err
}
if err := action.Sign(tsf0, sk); err != nil {
return err
}
blk, err := bc.MintNewBlock([]action.Action{tsf0}, ta.Addrinfo["producer"],
nil, nil, "")
if err != nil {
return err
}
if err := bc.ValidateBlock(blk, true); err != nil {
return err
}
if err := bc.CommitBlock(blk); err != nil {
return err
}
// Add block 1
// test --> A, B, C, D, E, F
tsf1, _ := action.NewTransfer(1, big.NewInt(20), ta.Addrinfo["producer"].RawAddress, ta.Addrinfo["alfa"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf1, ta.Addrinfo["producer"].PrivateKey)
tsf2, _ := action.NewTransfer(2, big.NewInt(30), ta.Addrinfo["producer"].RawAddress, ta.Addrinfo["bravo"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf2, ta.Addrinfo["producer"].PrivateKey)
tsf3, _ := action.NewTransfer(3, big.NewInt(50), ta.Addrinfo["producer"].RawAddress, ta.Addrinfo["charlie"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf3, ta.Addrinfo["producer"].PrivateKey)
tsf4, _ := action.NewTransfer(4, big.NewInt(70), ta.Addrinfo["producer"].RawAddress, ta.Addrinfo["delta"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf4, ta.Addrinfo["producer"].PrivateKey)
tsf5, _ := action.NewTransfer(5, big.NewInt(110), ta.Addrinfo["producer"].RawAddress, ta.Addrinfo["echo"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf5, ta.Addrinfo["producer"].PrivateKey)
tsf6, _ := action.NewTransfer(6, big.NewInt(50<<20), ta.Addrinfo["producer"].RawAddress, ta.Addrinfo["foxtrot"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf6, ta.Addrinfo["producer"].PrivateKey)
blk, err = bc.MintNewBlock([]action.Action{tsf1, tsf2, tsf3, tsf4, tsf5, tsf6}, ta.Addrinfo["producer"], nil, nil, "")
if err != nil {
return err
}
if err := bc.ValidateBlock(blk, true); err != nil {
return err
}
if err := bc.CommitBlock(blk); err != nil {
return err
}
// Add block 2
// Charlie --> A, B, D, E, test
tsf1, _ = action.NewTransfer(1, big.NewInt(1), ta.Addrinfo["charlie"].RawAddress, ta.Addrinfo["alfa"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf1, ta.Addrinfo["charlie"].PrivateKey)
tsf2, _ = action.NewTransfer(2, big.NewInt(1), ta.Addrinfo["charlie"].RawAddress, ta.Addrinfo["bravo"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf2, ta.Addrinfo["charlie"].PrivateKey)
tsf3, _ = action.NewTransfer(3, big.NewInt(1), ta.Addrinfo["charlie"].RawAddress, ta.Addrinfo["delta"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf3, ta.Addrinfo["charlie"].PrivateKey)
tsf4, _ = action.NewTransfer(4, big.NewInt(1), ta.Addrinfo["charlie"].RawAddress, ta.Addrinfo["echo"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf4, ta.Addrinfo["charlie"].PrivateKey)
tsf5, _ = action.NewTransfer(5, big.NewInt(1), ta.Addrinfo["charlie"].RawAddress, ta.Addrinfo["producer"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf5, ta.Addrinfo["charlie"].PrivateKey)
blk, err = bc.MintNewBlock([]action.Action{tsf1, tsf2, tsf3, tsf4, tsf5}, ta.Addrinfo["producer"], nil, nil, "")
if err != nil {
return err
}
if err := bc.ValidateBlock(blk, true); err != nil {
return err
}
if err := bc.CommitBlock(blk); err != nil {
return err
}
// Add block 3
// Delta --> B, E, F, test
tsf1, _ = action.NewTransfer(1, big.NewInt(1), ta.Addrinfo["delta"].RawAddress, ta.Addrinfo["bravo"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf1, ta.Addrinfo["delta"].PrivateKey)
tsf2, _ = action.NewTransfer(2, big.NewInt(1), ta.Addrinfo["delta"].RawAddress, ta.Addrinfo["echo"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf2, ta.Addrinfo["delta"].PrivateKey)
tsf3, _ = action.NewTransfer(3, big.NewInt(1), ta.Addrinfo["delta"].RawAddress, ta.Addrinfo["foxtrot"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf3, ta.Addrinfo["delta"].PrivateKey)
tsf4, _ = action.NewTransfer(4, big.NewInt(1), ta.Addrinfo["delta"].RawAddress, ta.Addrinfo["producer"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf4, ta.Addrinfo["delta"].PrivateKey)
blk, err = bc.MintNewBlock([]action.Action{tsf1, tsf2, tsf3, tsf4}, ta.Addrinfo["producer"], nil, nil, "")
if err != nil {
return err
}
if err := bc.ValidateBlock(blk, true); err != nil {
return err
}
if err := bc.CommitBlock(blk); err != nil {
return err
}
// Add block 4
// Delta --> A, B, C, D, F, test
tsf1, _ = action.NewTransfer(1, big.NewInt(2), ta.Addrinfo["echo"].RawAddress, ta.Addrinfo["alfa"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf1, ta.Addrinfo["echo"].PrivateKey)
tsf2, _ = action.NewTransfer(2, big.NewInt(2), ta.Addrinfo["echo"].RawAddress, ta.Addrinfo["bravo"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf2, ta.Addrinfo["echo"].PrivateKey)
tsf3, _ = action.NewTransfer(3, big.NewInt(2), ta.Addrinfo["echo"].RawAddress, ta.Addrinfo["charlie"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf3, ta.Addrinfo["echo"].PrivateKey)
tsf4, _ = action.NewTransfer(4, big.NewInt(2), ta.Addrinfo["echo"].RawAddress, ta.Addrinfo["delta"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf4, ta.Addrinfo["echo"].PrivateKey)
tsf5, _ = action.NewTransfer(5, big.NewInt(2), ta.Addrinfo["echo"].RawAddress, ta.Addrinfo["foxtrot"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf5, ta.Addrinfo["echo"].PrivateKey)
tsf6, _ = action.NewTransfer(6, big.NewInt(2), ta.Addrinfo["echo"].RawAddress, ta.Addrinfo["producer"].RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
_ = action.Sign(tsf6, ta.Addrinfo["echo"].PrivateKey)
vote1, _ := action.NewVote(6, ta.Addrinfo["charlie"].RawAddress, ta.Addrinfo["alfa"].RawAddress, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
vote2, _ := action.NewVote(1, ta.Addrinfo["alfa"].RawAddress, ta.Addrinfo["charlie"].RawAddress, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
if err := action.Sign(vote1, ta.Addrinfo["charlie"].PrivateKey); err != nil {
return err
}
if err := action.Sign(vote2, ta.Addrinfo["alfa"].PrivateKey); err != nil {
return err
}
blk, err = bc.MintNewBlock([]action.Action{tsf1, tsf2, tsf3, tsf4, tsf5, tsf6, vote1, vote2},
ta.Addrinfo["producer"], nil, nil, "")
if err != nil {
return err
}
if err := bc.ValidateBlock(blk, true); err != nil {
return err
}
return bc.CommitBlock(blk)
}
func TestCreateBlockchain(t *testing.T) {
require := require.New(t)
ctx := context.Background()
cfg := config.Default
// disable account-based testing
cfg.Chain.TrieDBPath = ""
// Disable block reward to make bookkeeping easier
Gen.BlockReward = big.NewInt(0)
// create chain
bc := NewBlockchain(cfg, InMemStateFactoryOption(), InMemDaoOption())
require.NoError(bc.Start(ctx))
require.NotNil(bc)
height := bc.TipHeight()
require.Equal(0, int(height))
fmt.Printf("Create blockchain pass, height = %d\n", height)
defer func() {
err := bc.Stop(ctx)
require.NoError(err)
}()
// verify Genesis block
genesis, _ := bc.GetBlockByHeight(0)
require.NotNil(genesis)
// serialize
data, err := genesis.Serialize()
require.Nil(err)
transfers, votes, _ := action.ClassifyActions(genesis.Actions)
require.Equal(23, len(transfers))
require.Equal(21, len(votes))
fmt.Printf("Block size match pass\n")
fmt.Printf("Marshaling Block pass\n")
// deserialize
deserialize := Block{}
err = deserialize.Deserialize(data)
require.Nil(err)
fmt.Printf("Unmarshaling Block pass\n")
hash := genesis.HashBlock()
require.Equal(hash, deserialize.HashBlock())
fmt.Printf("Serialize/Deserialize Block hash = %x match\n", hash)
hash = genesis.CalculateTxRoot()
require.Equal(hash, deserialize.CalculateTxRoot())
fmt.Printf("Serialize/Deserialize Block merkle = %x match\n", hash)
// add 4 sample blocks
require.Nil(addTestingTsfBlocks(bc))
height = bc.TipHeight()
require.Equal(5, int(height))
}
func TestLoadBlockchainfromDB(t *testing.T) {
require := require.New(t)
ctx := context.Background()
testutil.CleanupPath(t, testTriePath)
defer testutil.CleanupPath(t, testTriePath)
testutil.CleanupPath(t, testDBPath)
defer testutil.CleanupPath(t, testDBPath)
// Disable block reward to make bookkeeping easier
Gen.BlockReward = big.NewInt(0)
cfg := config.Default
cfg.Chain.TrieDBPath = testTriePath
cfg.Chain.ChainDBPath = testDBPath
cfg.Explorer.Enabled = true
sf, err := state.NewFactory(cfg, state.DefaultTrieOption())
require.Nil(err)
require.NoError(sf.Start(context.Background()))
require.NoError(addCreatorToFactory(sf))
// Create a blockchain from scratch
bc := NewBlockchain(cfg, PrecreatedStateFactoryOption(sf), BoltDBDaoOption())
require.NoError(bc.Start(ctx))
require.NotNil(bc)
var transfers = int(0)
testchan := make(chan *Block)
err = bc.SubscribeBlockCreation(testchan)
require.Nil(err)
go func() {
for {
select {
case blk := <-testchan:
tsfs, _, _ := action.ClassifyActions(blk.Actions)
transfers += len(tsfs)
}
}
}()
require.Equal(0, transfers)
height := bc.TipHeight()
fmt.Printf("Open blockchain pass, height = %d\n", height)
require.Nil(addTestingTsfBlocks(bc))
err = bc.Stop(ctx)
require.NoError(err)
require.Equal(27, transfers)
// Load a blockchain from DB
bc = NewBlockchain(cfg, PrecreatedStateFactoryOption(sf), BoltDBDaoOption())
require.NoError(bc.Start(ctx))
defer func() {
err := bc.Stop(ctx)
require.NoError(err)
}()
require.NotNil(bc)
// check hash<-->height mapping
hash, err := bc.GetHashByHeight(0)
require.Nil(err)
height, err = bc.GetHeightByHash(hash)
require.Nil(err)
require.Equal(uint64(0), height)
blk, err := bc.GetBlockByHash(hash)
require.Nil(err)
require.Equal(hash, blk.HashBlock())
fmt.Printf("Genesis hash = %x\n", hash)
hash1, err := bc.GetHashByHeight(1)
require.Nil(err)
height, err = bc.GetHeightByHash(hash1)
require.Nil(err)
require.Equal(uint64(1), height)
blk, err = bc.GetBlockByHash(hash1)
require.Nil(err)
require.Equal(hash1, blk.HashBlock())
fmt.Printf("block 1 hash = %x\n", hash1)
hash2, err := bc.GetHashByHeight(2)
require.Nil(err)
height, err = bc.GetHeightByHash(hash2)
require.Nil(err)
require.Equal(uint64(2), height)
blk, err = bc.GetBlockByHash(hash2)
require.Nil(err)
require.Equal(hash2, blk.HashBlock())
fmt.Printf("block 2 hash = %x\n", hash2)
hash3, err := bc.GetHashByHeight(3)
require.Nil(err)
height, err = bc.GetHeightByHash(hash3)
require.Nil(err)
require.Equal(uint64(3), height)
blk, err = bc.GetBlockByHash(hash3)
require.Nil(err)
require.Equal(hash3, blk.HashBlock())
fmt.Printf("block 3 hash = %x\n", hash3)
hash4, err := bc.GetHashByHeight(4)
require.Nil(err)
height, err = bc.GetHeightByHash(hash4)
require.Nil(err)
require.Equal(uint64(4), height)
blk, err = bc.GetBlockByHash(hash4)
require.Nil(err)
require.Equal(hash4, blk.HashBlock())
fmt.Printf("block 4 hash = %x\n", hash4)
hash5, err := bc.GetHashByHeight(5)
require.Nil(err)
height, err = bc.GetHeightByHash(hash5)
require.Nil(err)
require.Equal(uint64(5), height)
blk, err = bc.GetBlockByHash(hash5)
require.Nil(err)
require.Equal(hash5, blk.HashBlock())
fmt.Printf("block 5 hash = %x\n", hash5)
empblk, err := bc.GetBlockByHash(_hash.ZeroHash32B)
require.Nil(empblk)
require.NotNil(err.Error())
blk, err = bc.GetBlockByHeight(60000)
require.Nil(blk)
require.NotNil(err)
// add wrong blocks
h := bc.TipHeight()
hash = bc.TipHash()
blk, err = bc.GetBlockByHeight(h)
require.Nil(err)
require.Equal(hash, blk.HashBlock())
fmt.Printf("Current tip = %d hash = %x\n", h, hash)
// add block with wrong height
cbTsf := action.NewCoinBaseTransfer(big.NewInt(50), ta.Addrinfo["bravo"].RawAddress)
require.NotNil(cbTsf)
blk = NewBlock(0, h+2, hash, testutil.TimestampNow(), ta.Addrinfo["bravo"].PublicKey, []action.Action{cbTsf})
err = bc.ValidateBlock(blk, true)
require.NotNil(err)
fmt.Printf("Cannot validate block %d: %v\n", blk.Height(), err)
// add block with zero prev hash
cbTsf2 := action.NewCoinBaseTransfer(big.NewInt(50), ta.Addrinfo["bravo"].RawAddress)
require.NotNil(cbTsf2)
blk = NewBlock(
0,
h+1,
_hash.ZeroHash32B,
testutil.TimestampNow(),
ta.Addrinfo["bravo"].PublicKey,
[]action.Action{cbTsf2},
)
err = bc.ValidateBlock(blk, true)
require.NotNil(err)
fmt.Printf("Cannot validate block %d: %v\n", blk.Height(), err)
// cannot add existing block again
blk, err = bc.GetBlockByHeight(3)
require.NotNil(blk)
require.Nil(err)
err = bc.(*blockchain).commitBlock(blk)
require.NotNil(err)
fmt.Printf("Cannot add block 3 again: %v\n", err)
// check all Tx from block 4
blk, err = bc.GetBlockByHeight(5)
require.Nil(err)
require.Equal(hash5, blk.HashBlock())
tsfs, votes, _ := action.ClassifyActions(blk.Actions)
for _, transfer := range tsfs {
transferHash := transfer.Hash()
hash, err := bc.GetBlockHashByTransferHash(transferHash)
require.Nil(err)
require.Equal(hash, hash5)
transfer1, err := bc.GetTransferByTransferHash(transferHash)
require.Nil(err)
require.Equal(transfer1.Hash(), transferHash)
}
for _, vote := range votes {
voteHash := vote.Hash()
hash, err := bc.GetBlockHashByVoteHash(voteHash)
require.Nil(err)
require.Equal(hash, hash5)
vote1, err := bc.GetVoteByVoteHash(voteHash)
require.Nil(err)
require.Equal(vote1.Hash(), voteHash)
}
fromTransfers, err := bc.GetTransfersFromAddress(ta.Addrinfo["charlie"].RawAddress)
require.Nil(err)
require.Equal(len(fromTransfers), 5)
toTransfers, err := bc.GetTransfersToAddress(ta.Addrinfo["charlie"].RawAddress)
require.Nil(err)
require.Equal(len(toTransfers), 2)
fromVotes, err := bc.GetVotesFromAddress(ta.Addrinfo["charlie"].RawAddress)
require.Nil(err)
require.Equal(len(fromVotes), 1)
fromVotes, err = bc.GetVotesFromAddress(ta.Addrinfo["alfa"].RawAddress)
require.Nil(err)
require.Equal(len(fromVotes), 1)
toVotes, err := bc.GetVotesToAddress(ta.Addrinfo["charlie"].RawAddress)
require.Nil(err)
require.Equal(len(toVotes), 1)
toVotes, err = bc.GetVotesToAddress(ta.Addrinfo["alfa"].RawAddress)
require.Nil(err)
require.Equal(len(toVotes), 1)
totalTransfers, err := bc.GetTotalTransfers()
require.Nil(err)
require.Equal(totalTransfers, uint64(50))
totalVotes, err := bc.GetTotalVotes()
require.Nil(err)
require.Equal(totalVotes, uint64(23))
_, err = bc.GetTransferByTransferHash(_hash.ZeroHash32B)
require.NotNil(err)
_, err = bc.GetVoteByVoteHash(_hash.ZeroHash32B)
require.NotNil(err)
_, err = bc.StateByAddr("")
require.NotNil(err)
}
func TestLoadBlockchainfromDBWithoutExplorer(t *testing.T) {
require := require.New(t)
testutil.CleanupPath(t, testTriePath)
defer testutil.CleanupPath(t, testTriePath)
testutil.CleanupPath(t, testDBPath)
defer testutil.CleanupPath(t, testDBPath)
ctx := context.Background()
// Disable block reward to make bookkeeping easier
Gen.BlockReward = big.NewInt(0)
cfg := config.Default
cfg.Chain.TrieDBPath = testTriePath
cfg.Chain.ChainDBPath = testDBPath
sf, err := state.NewFactory(cfg, state.DefaultTrieOption())
require.Nil(err)
require.NoError(sf.Start(context.Background()))
require.NoError(addCreatorToFactory(sf))
// Create a blockchain from scratch
bc := NewBlockchain(cfg, PrecreatedStateFactoryOption(sf), BoltDBDaoOption())
require.NoError(bc.Start(ctx))
require.NotNil(bc)
var transfers = int(0)
testchan := make(chan *Block)
err = bc.SubscribeBlockCreation(testchan)
require.Nil(err)
go func() {
for {
select {
case blk := <-testchan:
tsfs, _, _ := action.ClassifyActions(blk.Actions)
transfers += len(tsfs)
}
}
}()
require.Equal(0, transfers)
err = bc.UnsubscribeBlockCreation(testchan)
require.Nil(err)
height := bc.TipHeight()
fmt.Printf("Open blockchain pass, height = %d\n", height)
require.Nil(addTestingTsfBlocks(bc))
err = bc.Stop(ctx)
require.NoError(err)
require.Equal(0, transfers)
// Load a blockchain from DB
bc = NewBlockchain(cfg, PrecreatedStateFactoryOption(sf), BoltDBDaoOption())
require.NoError(bc.Start(ctx))
defer func() {
err := bc.Stop(ctx)
require.NoError(err)
}()
require.NotNil(bc)
// check hash<-->height mapping
hash, err := bc.GetHashByHeight(0)
require.Nil(err)
height, err = bc.GetHeightByHash(hash)
require.Nil(err)
require.Equal(uint64(0), height)
blk, err := bc.GetBlockByHash(hash)
require.Nil(err)
require.Equal(hash, blk.HashBlock())
fmt.Printf("Genesis hash = %x\n", hash)
hash1, err := bc.GetHashByHeight(1)
require.Nil(err)
height, err = bc.GetHeightByHash(hash1)
require.Nil(err)
require.Equal(uint64(1), height)
blk, err = bc.GetBlockByHash(hash1)
require.Nil(err)
require.Equal(hash1, blk.HashBlock())
fmt.Printf("block 1 hash = %x\n", hash1)
hash2, err := bc.GetHashByHeight(2)
require.Nil(err)
height, err = bc.GetHeightByHash(hash2)
require.Nil(err)
require.Equal(uint64(2), height)
blk, err = bc.GetBlockByHash(hash2)
require.Nil(err)
require.Equal(hash2, blk.HashBlock())
fmt.Printf("block 2 hash = %x\n", hash2)
hash3, err := bc.GetHashByHeight(3)
require.Nil(err)
height, err = bc.GetHeightByHash(hash3)
require.Nil(err)
require.Equal(uint64(3), height)
blk, err = bc.GetBlockByHash(hash3)
require.Nil(err)
require.Equal(hash3, blk.HashBlock())
fmt.Printf("block 3 hash = %x\n", hash3)
hash4, err := bc.GetHashByHeight(4)
require.Nil(err)
height, err = bc.GetHeightByHash(hash4)
require.Nil(err)
require.Equal(uint64(4), height)
blk, err = bc.GetBlockByHash(hash4)
require.Nil(err)
require.Equal(hash4, blk.HashBlock())
fmt.Printf("block 4 hash = %x\n", hash4)
empblk, err := bc.GetBlockByHash(_hash.ZeroHash32B)
require.Nil(empblk)
require.NotNil(err.Error())
blk, err = bc.GetBlockByHeight(60000)
require.Nil(blk)
require.NotNil(err)
// add wrong blocks
h := bc.TipHeight()
hash = bc.TipHash()
blk, err = bc.GetBlockByHeight(h)
require.Nil(err)
require.Equal(hash, blk.HashBlock())
fmt.Printf("Current tip = %d hash = %x\n", h, hash)
// add block with wrong height
cbTsf := action.NewCoinBaseTransfer(big.NewInt(50), ta.Addrinfo["bravo"].RawAddress)
require.NotNil(cbTsf)
blk = NewBlock(0, h+2, hash, testutil.TimestampNow(), ta.Addrinfo["bravo"].PublicKey, []action.Action{cbTsf})
err = bc.ValidateBlock(blk, true)
require.NotNil(err)
fmt.Printf("Cannot validate block %d: %v\n", blk.Height(), err)
// add block with zero prev hash
cbTsf2 := action.NewCoinBaseTransfer(big.NewInt(50), ta.Addrinfo["bravo"].RawAddress)
require.NotNil(cbTsf2)
blk = NewBlock(
0,
h+1,
_hash.ZeroHash32B,
testutil.TimestampNow(),
ta.Addrinfo["bravo"].PublicKey,
[]action.Action{cbTsf2},
)
err = bc.ValidateBlock(blk, true)
require.NotNil(err)
fmt.Printf("Cannot validate block %d: %v\n", blk.Height(), err)
// cannot add existing block again
blk, err = bc.GetBlockByHeight(3)
require.NotNil(blk)
require.Nil(err)
err = bc.(*blockchain).commitBlock(blk)
require.NotNil(err)
fmt.Printf("Cannot add block 3 again: %v\n", err)
// check all Tx from block 4
blk, err = bc.GetBlockByHeight(4)
require.Nil(err)
require.Equal(hash4, blk.HashBlock())
tsfs, votes, _ := action.ClassifyActions(blk.Actions)
for _, transfer := range tsfs {
transferHash := transfer.Hash()
_, err := bc.GetBlockHashByTransferHash(transferHash)
require.NotNil(err)
_, err = bc.GetTransferByTransferHash(transferHash)
require.NotNil(err)
}
for _, vote := range votes {
voteHash := vote.Hash()
_, err := bc.GetBlockHashByVoteHash(voteHash)
require.NotNil(err)
_, err = bc.GetVoteByVoteHash(voteHash)
require.NotNil(err)
}
_, err = bc.GetTransfersFromAddress(ta.Addrinfo["charlie"].RawAddress)
require.NotNil(err)
_, err = bc.GetTransfersToAddress(ta.Addrinfo["charlie"].RawAddress)
require.NotNil(err)
_, err = bc.GetVotesFromAddress(ta.Addrinfo["charlie"].RawAddress)
require.NotNil(err)
_, err = bc.GetVotesFromAddress(ta.Addrinfo["alfa"].RawAddress)
require.NotNil(err)
_, err = bc.GetVotesToAddress(ta.Addrinfo["charlie"].RawAddress)
require.NotNil(err)
_, err = bc.GetVotesToAddress(ta.Addrinfo["alfa"].RawAddress)
require.NotNil(err)
_, err = bc.GetTotalTransfers()
require.NotNil(err)
_, err = bc.GetTotalVotes()
require.NotNil(err)
_, err = bc.GetTransferByTransferHash(_hash.ZeroHash32B)
require.NotNil(err)
_, err = bc.GetVoteByVoteHash(_hash.ZeroHash32B)
require.NotNil(err)
_, err = bc.StateByAddr("")
require.NotNil(err)
}
func TestBlockchain_Validator(t *testing.T) {
cfg := config.Default
// disable account-based testing
cfg.Chain.TrieDBPath = ""
ctx := context.Background()
bc := NewBlockchain(cfg, InMemDaoOption(), InMemStateFactoryOption())
require.NoError(t, bc.Start(ctx))
defer func() {
err := bc.Stop(ctx)
require.Nil(t, err)
}()
require.NotNil(t, bc)
val := bc.Validator()
require.NotNil(t, bc)
bc.SetValidator(val)
require.NotNil(t, bc.Validator())
}
func TestBlockchainInitialCandidate(t *testing.T) {
require := require.New(t)
testutil.CleanupPath(t, testTriePath)
defer testutil.CleanupPath(t, testTriePath)
testutil.CleanupPath(t, testDBPath)
defer testutil.CleanupPath(t, testDBPath)
cfg := config.Default
cfg.Chain.TrieDBPath = testTriePath
cfg.Chain.ChainDBPath = testDBPath
cfg.Chain.NumCandidates = 2
// Disable block reward to make bookkeeping easier
Gen.BlockReward = big.NewInt(0)
sf, err := state.NewFactory(cfg, state.DefaultTrieOption())
require.Nil(err)
require.NoError(sf.Start(context.Background()))
bc := NewBlockchain(cfg, PrecreatedStateFactoryOption(sf), BoltDBDaoOption())
require.NoError(bc.Start(context.Background()))
require.NotNil(bc)
// TODO: change the value when Candidates size is changed
height, err := sf.Height()
require.NoError(err)
require.Equal(uint64(0), height)
candidate, err := sf.CandidatesByHeight(height)
require.NoError(err)
require.True(len(candidate) == 2)
}
func TestCoinbaseTransfer(t *testing.T) {
require := require.New(t)
testutil.CleanupPath(t, testTriePath)
defer testutil.CleanupPath(t, testTriePath)
testutil.CleanupPath(t, testDBPath)
defer testutil.CleanupPath(t, testDBPath)
cfg := config.Default
cfg.Chain.TrieDBPath = testTriePath
cfg.Chain.ChainDBPath = testDBPath
sf, err := state.NewFactory(cfg, state.DefaultTrieOption())
require.Nil(err)
require.NoError(sf.Start(context.Background()))
require.NoError(addCreatorToFactory(sf))
Gen.BlockReward = big.NewInt(0)
bc := NewBlockchain(cfg, PrecreatedStateFactoryOption(sf), BoltDBDaoOption())
require.NoError(bc.Start(context.Background()))
require.NotNil(bc)
height := bc.TipHeight()
require.Equal(0, int(height))
actions := []action.Action{}
blk, err := bc.MintNewBlock(actions, ta.Addrinfo["producer"], nil, nil, "")
require.Nil(err)
s, err := bc.StateByAddr(ta.Addrinfo["producer"].RawAddress)
require.Nil(err)
b := s.Balance
require.True(b.String() == Gen.TotalSupply.String())
require.Nil(bc.ValidateBlock(blk, true))
require.Nil(bc.CommitBlock(blk))
height = bc.TipHeight()
require.True(height == 1)
require.True(len(blk.Actions) == 1)
s, err = bc.StateByAddr(ta.Addrinfo["producer"].RawAddress)
require.Nil(err)
b = s.Balance
expectedBalance := big.NewInt(0)
expectedBalance.Add(Gen.TotalSupply, Gen.BlockReward)
require.True(b.String() == expectedBalance.String())
}
func TestBlockchain_StateByAddr(t *testing.T) {
require := require.New(t)
cfg := config.Default
// disable account-based testing
// create chain
bc := NewBlockchain(cfg, InMemDaoOption(), InMemStateFactoryOption())
require.NoError(bc.Start(context.Background()))
require.NotNil(bc)
s, err := bc.StateByAddr(Gen.CreatorAddr(cfg.Chain.ID))
require.NoError(err)
require.Equal(uint64(0), s.Nonce)
bal := big.NewInt(7700000000)
require.Equal(bal.Mul(bal, big.NewInt(1e18)).String(), s.Balance.String())
require.Equal(hash.ZeroHash32B, s.Root)
require.Equal([]byte(nil), s.CodeHash)
require.Equal(false, s.IsCandidate)
require.Equal(big.NewInt(0), s.VotingWeight)
require.Equal("", s.Votee)
}
func TestBlocks(t *testing.T) {
// This test is used for committing block verify benchmark purpose
t.Skip()
require := require.New(t)
cfg := config.Default
testutil.CleanupPath(t, testTriePath)
defer testutil.CleanupPath(t, testTriePath)
testutil.CleanupPath(t, testDBPath)
defer testutil.CleanupPath(t, testDBPath)
cfg.Chain.TrieDBPath = testTriePath
cfg.Chain.ChainDBPath = testDBPath
sf, _ := state.NewFactory(cfg, state.InMemTrieOption())
require.NoError(sf.Start(context.Background()))
require.NoError(addCreatorToFactory(sf))
// Create a blockchain from scratch
bc := NewBlockchain(cfg, PrecreatedStateFactoryOption(sf), BoltDBDaoOption())
require.NoError(bc.Start(context.Background()))
a := ta.Addrinfo["alfa"]
c := ta.Addrinfo["bravo"]
ws, err := sf.NewWorkingSet()
require.NoError(err)
_, err = ws.LoadOrCreateAccountState(a.RawAddress, big.NewInt(100000))
require.NoError(err)
_, err = ws.LoadOrCreateAccountState(c.RawAddress, big.NewInt(100000))
require.NoError(err)
gasLimit := testutil.TestGasLimit
ctx := state.WithRunActionsCtx(context.Background(),
state.RunActionsCtx{
ProducerAddr: ta.Addrinfo["producer"].RawAddress,
GasLimit: &gasLimit,
EnableGasCharge: testutil.EnableGasCharge,
})
_, _, err = ws.RunActions(ctx, 0, nil)
require.NoError(err)
require.NoError(sf.Commit(ws))
for i := 0; i < 10; i++ {
acts := []action.Action{}
for i := 0; i < 1000; i++ {
tsf, err := action.NewTransfer(1, big.NewInt(2), a.RawAddress, c.RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
require.NoError(err)
_ = action.Sign(tsf, a.PrivateKey)
acts = append(acts, tsf)
}
blk, _ := bc.MintNewBlock(acts, ta.Addrinfo["producer"], nil, nil, "")
require.Nil(bc.ValidateBlock(blk, true))
require.Nil(bc.CommitBlock(blk))
}
}
func TestActions(t *testing.T) {
// This test is used for block verify benchmark purpose
t.Skip()
require := require.New(t)
cfg := config.Default
testutil.CleanupPath(t, testTriePath)
defer testutil.CleanupPath(t, testTriePath)
testutil.CleanupPath(t, testDBPath)
defer testutil.CleanupPath(t, testDBPath)
cfg.Chain.TrieDBPath = testTriePath
cfg.Chain.ChainDBPath = testDBPath
sf, _ := state.NewFactory(cfg, state.InMemTrieOption())
require.NoError(sf.Start(context.Background()))
require.NoError(addCreatorToFactory(sf))
// Create a blockchain from scratch
bc := NewBlockchain(cfg, PrecreatedStateFactoryOption(sf), BoltDBDaoOption())
require.NoError(bc.Start(context.Background()))
a := ta.Addrinfo["alfa"]
c := ta.Addrinfo["bravo"]
ws, err := sf.NewWorkingSet()
require.NoError(err)
_, err = ws.LoadOrCreateAccountState(a.RawAddress, big.NewInt(100000))
require.NoError(err)
_, err = ws.LoadOrCreateAccountState(c.RawAddress, big.NewInt(100000))
require.NoError(err)
gasLimit := testutil.TestGasLimit
ctx := state.WithRunActionsCtx(context.Background(),
state.RunActionsCtx{
ProducerAddr: ta.Addrinfo["producer"].RawAddress,
GasLimit: &gasLimit,
EnableGasCharge: testutil.EnableGasCharge,
})
_, _, err = ws.RunActions(ctx, 0, nil)
require.NoError(err)
require.NoError(sf.Commit(ws))
val := validator{sf, ""}
acts := []action.Action{}
for i := 0; i < 5000; i++ {
tsf, err := action.NewTransfer(1, big.NewInt(2), a.RawAddress, c.RawAddress, []byte{}, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
require.NoError(err)
_ = action.Sign(tsf, a.PrivateKey)
acts = append(acts, tsf)
vote, err := action.NewVote(1, a.RawAddress, a.RawAddress, testutil.TestGasLimit, big.NewInt(testutil.TestGasPrice))
require.NoError(err)
_ = action.Sign(vote, a.PrivateKey)
acts = append(acts, vote)
}
blk, _ := bc.MintNewBlock(acts, ta.Addrinfo["producer"], nil,
nil, "")
require.Nil(val.Validate(blk, 0, blk.PrevHash(), true))
}
func TestMintDKGBlock(t *testing.T) {
require := require.New(t)
lastSeed, _ := hex.DecodeString("9de6306b08158c423330f7a27243a1a5cbe39bfd764f07818437882d21241567")
cfg := config.Default
clk := clock.NewMock()
chain := NewBlockchain(cfg, InMemDaoOption(), InMemStateFactoryOption(), ClockOption(clk))
require.NoError(chain.Start(context.Background()))
var err error
const numNodes = 21
addresses := make([]string, numNodes)
skList := make([][]uint32, numNodes)
idList := make([][]uint8, numNodes)
coeffsList := make([][][]uint32, numNodes)
sharesList := make([][][]uint32, numNodes)
shares := make([][]uint32, numNodes)
witnessesList := make([][][]byte, numNodes)
sharestatusmatrix := make([][numNodes]bool, numNodes)
qsList := make([][]byte, numNodes)
pkList := make([][]byte, numNodes)
askList := make([][]uint32, numNodes)
ec283PKList := make([]keypair.PublicKey, numNodes)
ec283SKList := make([]keypair.PrivateKey, numNodes)
// Generate 21 identifiers for the delegates
for i := 0; i < numNodes; i++ {
var err error
ec283PKList[i], ec283SKList[i], err = crypto.EC283.NewKeyPair()
require.NoError(err)
pkHash := keypair.HashPubKey(ec283PKList[i])
addresses[i] = address.New(cfg.Chain.ID, pkHash[:]).IotxAddress()
idList[i] = hash.Hash256b([]byte(addresses[i]))
skList[i] = crypto.DKG.SkGeneration()
}
// Initialize DKG and generate secret shares
for i := 0; i < numNodes; i++ {
coeffsList[i], sharesList[i], witnessesList[i], err = crypto.DKG.Init(skList[i], idList)
require.NoError(err)
}
// Verify all the received secret shares
for i := 0; i < numNodes; i++ {
for j := 0; j < numNodes; j++ {
result, err := crypto.DKG.ShareVerify(idList[i], sharesList[j][i], witnessesList[j])
require.NoError(err)
require.True(result)
shares[j] = sharesList[j][i]
}
sharestatusmatrix[i], err = crypto.DKG.SharesCollect(idList[i], shares, witnessesList)
require.NoError(err)
for _, b := range sharestatusmatrix[i] {
require.True(b)
}
}
// Generate private and public key shares of a group key
for i := 0; i < numNodes; i++ {
for j := 0; j < numNodes; j++ {
shares[j] = sharesList[j][i]
}
qsList[i], pkList[i], askList[i], err = crypto.DKG.KeyPairGeneration(shares, sharestatusmatrix)
require.NoError(err)
}
// Generate dkg signature for each block
for i := 1; i < numNodes; i++ {
iotxAddr := iotxaddress.Address{
PublicKey: ec283PKList[i],
PrivateKey: ec283SKList[i],
RawAddress: addresses[i],
}
blk, err := chain.MintNewBlock(nil, &iotxAddr,
&iotxaddress.DKGAddress{PrivateKey: askList[i], PublicKey: pkList[i], ID: idList[i]}, lastSeed, "")
require.NoError(err)
require.NoError(chain.ValidateBlock(blk, true))
require.NoError(chain.CommitBlock(blk))
require.Equal(pkList[i], blk.Header.DKGPubkey)
require.Equal(idList[i], blk.Header.DKGID)
require.True(len(blk.Header.DKGBlockSig) > 0)
}
height, err := chain.GetFactory().Height()
require.NoError(err)
require.Equal(uint64(20), height)
candidates, err := chain.CandidatesByHeight(height)
require.NoError(err)
require.Equal(21, len(candidates))
}
| 1 | 13,300 | line is 175 characters | iotexproject-iotex-core | go |
@@ -230,12 +230,10 @@ public abstract class SalesforceReactActivity extends ReactActivity {
}
protected void setRestClient(RestClient restClient) {
- if(restClient!= null && client != restClient){
- if(reactActivityDelegate != null){
- reactActivityDelegate.loadReactAppOnceIfReady(getMainComponentName());
- }
- }
client = restClient;
+ if(client != null && reactActivityDelegate != null){
+ reactActivityDelegate.loadReactAppOnceIfReady(getMainComponentName());
+ }
}
protected ClientManager buildClientManager() { | 1 | /*
* Copyright (c) 2016-present, salesforce.com, inc.
* All rights reserved.
* Redistribution and use of this software in source and binary forms, with or
* without modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of salesforce.com, inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission of salesforce.com, inc.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.androidsdk.reactnative.ui;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.bridge.Callback;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.reactnative.R;
import com.salesforce.androidsdk.reactnative.bridge.ReactBridgeHelper;
import com.salesforce.androidsdk.rest.ClientManager;
import com.salesforce.androidsdk.rest.ClientManager.RestClientCallback;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.security.PasscodeManager;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;
import com.salesforce.androidsdk.util.LogoutCompleteReceiver;
/**
* Super class for all Salesforce activities.
*/
public abstract class SalesforceReactActivity extends ReactActivity {
private static final String TAG = "SfReactActivity";
private RestClient client;
private ClientManager clientManager;
private PasscodeManager passcodeManager;
private LogoutCompleteReceiver logoutCompleteReceiver;
private SalesforceReactActivityDelegate reactActivityDelegate;
/**
* @return true if you want login to happen as soon as activity is loaded
* false if you want do login at a later point
*/
public boolean shouldAuthenticate() {
return true;
}
/**
* Called if shouldAuthenticate() returned true but device is offline
*/
public void onErrorAuthenticateOffline() {
Toast t = Toast.makeText(this, R.string.sf__should_authenticate_but_is_offline, Toast.LENGTH_LONG);
t.show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate called");
super.onCreate(savedInstanceState);
// Get clientManager
clientManager = buildClientManager();
// Gets an instance of the passcode manager.
passcodeManager = SalesforceSDKManager.getInstance().getPasscodeManager();
// TODO
// Have a user switcher once we have an account manager bridge for react native
logoutCompleteReceiver = new ReactActivityLogoutCompleteReceiver();
registerReceiver(logoutCompleteReceiver, new IntentFilter(SalesforceSDKManager.LOGOUT_COMPLETE_INTENT_ACTION));
// Let observers know
EventsObservable.get().notifyEvent(EventType.MainActivityCreateComplete, this);
}
@Override
public void onDestroy() {
unregisterReceiver(logoutCompleteReceiver);
super.onDestroy();
}
@Override
public void onResume() {
super.onResume();
// Brings up the passcode screen if needed.
if (passcodeManager.onResume(this)) {
// Get client (if already logged in)
try {
setRestClient(clientManager.peekRestClient());
} catch (ClientManager.AccountInfoNotFoundException e) {
setRestClient(client);
}
// Not logged in
if (client == null) {
onResumeNotLoggedIn();
}
// Logged in
else {
Log.i(TAG, "onResume - Already logged in");
}
}
}
/**
* Called when resuming activity and user is not authenticated
*/
private void onResumeNotLoggedIn() {
// Need to be authenticated
if (shouldAuthenticate()) {
// Online
if (SalesforceSDKManager.getInstance().hasNetwork()) {
Log.i(TAG, "onResumeNotLoggedIn - Should authenticate / online - authenticating");
login();
}
// Offline
else {
Log.w(TAG, "onResumeNotLoggedIn - Should authenticate / offline - cannot proceed");
onErrorAuthenticateOffline();
}
}
// Does not need to be authenticated
else {
Log.i(TAG, "onResumeNotLoggedIn - Should not authenticate");
}
}
@Override
public void onUserInteraction() {
passcodeManager.recordUserInteraction();
}
@Override
public void onPause() {
super.onPause();
passcodeManager.onPause(this);
}
protected void login() {
Log.i(TAG, "login called");
clientManager.getRestClient(this, new RestClientCallback() {
@Override
public void authenticatedRestClient(RestClient client) {
if (client == null) {
Log.i(TAG, "login - authenticatedRestClient called with null client");
logout(null);
} else {
Log.i(TAG, "login - authenticatedRestClient called with actual client");
SalesforceReactActivity.this.recreate(); // starting fresh
}
}
});
}
/**
* Method called from bridge to logout
* @param successCallback
*/
public void logout(Callback successCallback) {
Log.i(TAG, "logout called");
SalesforceSDKManager.getInstance().logout(this);
}
/**
* Method called from bridge to authenticate
* @param successCallback
* @param errorCallback
*/
public void authenticate(final Callback successCallback, final Callback errorCallback) {
Log.i(TAG, "authenticate called");
clientManager.getRestClient(this, new RestClientCallback() {
@Override
public void authenticatedRestClient(RestClient client) {
SalesforceReactActivity.this.setRestClient(client);
getAuthCredentials(successCallback, errorCallback);
}
});
}
/**
* Method called from bridge to get auth credentials
* @param successCallback
* @param errorCallback
*/
public void getAuthCredentials(Callback successCallback, Callback errorCallback) {
Log.i(TAG, "getAuthCredentials called");
if (client != null) {
if (successCallback != null) {
ReactBridgeHelper.invokeSuccess(successCallback, client.getJSONCredentials());
}
} else {
if (errorCallback != null) {
errorCallback.invoke("Not authenticated");
}
}
}
public RestClient getRestClient() {
return client;
}
protected void setRestClient(RestClient restClient) {
if(restClient!= null && client != restClient){
if(reactActivityDelegate != null){
reactActivityDelegate.loadReactAppOnceIfReady(getMainComponentName());
}
}
client = restClient;
}
protected ClientManager buildClientManager() {
return new ClientManager(this, SalesforceSDKManager.getInstance().getAccountType(),
SalesforceSDKManager.getInstance().getLoginOptions(),
SalesforceSDKManager.getInstance().shouldLogoutWhenTokenRevoked());
}
/**
* Performs actions on logout complete.
*/
protected void logoutCompleteActions() {
}
/**
* Acts on the logout complete event.
*
* @author bhariharan
*/
private class ReactActivityLogoutCompleteReceiver extends LogoutCompleteReceiver {
@Override
protected void onLogoutComplete() {
logoutCompleteActions();
}
}
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
reactActivityDelegate = new SalesforceReactActivityDelegate(this, getMainComponentName());
return reactActivityDelegate;
}
protected boolean shouldReactBeRunning(){
if(shouldAuthenticate()){
return client != null;
}
return true;
}
}
| 1 | 15,735 | @ivanbogdanov Does this fix the first time load gray screen issue that @wmathurin noticed? | forcedotcom-SalesforceMobileSDK-Android | java |
@@ -35,11 +35,12 @@ __all__ = ['Dataset', 'Booster',
'print_evaluation', 'record_evaluation', 'reset_parameter', 'early_stopping',
'plot_importance', 'plot_metric', 'plot_tree', 'create_tree_digraph']
+# REMOVEME: remove warning after 2.3.0 version release
if system() == 'Darwin':
warnings.warn("Starting from version 2.2.1, the library file in distribution wheels for macOS "
- "will be built by the Apple Clang compiler.\n"
+ "is built by the Apple Clang (Xcode_9.4.1) compiler.\n"
"This means that in case of installing LightGBM from PyPI via the ``pip install lightgbm`` command, "
- "you won't need to install the gcc compiler anymore.\n"
- "Instead of that, you'll need to install the OpenMP library, "
+ "you don't need to install the gcc compiler anymore.\n"
+ "Instead of that, you need to install the OpenMP library, "
"which is required for running LightGBM on the system with the Apple Clang compiler.\n"
- "You can install the OpenMP library by the following command: ``brew install libomp``.", FutureWarning)
+ "You can install the OpenMP library by the following command: ``brew install libomp``.", UserWarning) | 1 | # coding: utf-8
"""LightGBM, Light Gradient Boosting Machine.
Contributors: https://github.com/Microsoft/LightGBM/graphs/contributors
"""
from __future__ import absolute_import
from .basic import Booster, Dataset
from .callback import (early_stopping, print_evaluation, record_evaluation,
reset_parameter)
from .engine import cv, train
import os
import warnings
from platform import system
try:
from .sklearn import LGBMModel, LGBMRegressor, LGBMClassifier, LGBMRanker
except ImportError:
pass
try:
from .plotting import plot_importance, plot_metric, plot_tree, create_tree_digraph
except ImportError:
pass
dir_path = os.path.dirname(os.path.realpath(__file__))
if os.path.isfile(os.path.join(dir_path, 'VERSION.txt')):
__version__ = open(os.path.join(dir_path, 'VERSION.txt')).read().strip()
__all__ = ['Dataset', 'Booster',
'train', 'cv',
'LGBMModel', 'LGBMRegressor', 'LGBMClassifier', 'LGBMRanker',
'print_evaluation', 'record_evaluation', 'reset_parameter', 'early_stopping',
'plot_importance', 'plot_metric', 'plot_tree', 'create_tree_digraph']
if system() == 'Darwin':
warnings.warn("Starting from version 2.2.1, the library file in distribution wheels for macOS "
"will be built by the Apple Clang compiler.\n"
"This means that in case of installing LightGBM from PyPI via the ``pip install lightgbm`` command, "
"you won't need to install the gcc compiler anymore.\n"
"Instead of that, you'll need to install the OpenMP library, "
"which is required for running LightGBM on the system with the Apple Clang compiler.\n"
"You can install the OpenMP library by the following command: ``brew install libomp``.", FutureWarning)
| 1 | 19,206 | Is `2.3.0` version OK? | microsoft-LightGBM | cpp |
@@ -26,6 +26,18 @@ describe "Selenium::WebDriver::TargetLocator" do
end
end
+ it "should switch to parent frame" do
+ driver.navigate.to url_for("iframes.html")
+
+ iframe = driver.find_element(:tag_name => "iframe")
+ driver.switch_to.frame(iframe)
+
+ driver.find_element(:name, 'login').should be_kind_of(WebDriver::Element)
+
+ driver.switch_to.parent_frame
+ driver.find_element(:id, 'iframe_page_heading').should be_kind_of(WebDriver::Element)
+ end
+
# switching by name not yet supported by safari
not_compliant_on :browser => [:ie, :iphone, :safari] do
it "should switch to a window and back when given a block" do | 1 | require File.expand_path("../spec_helper", __FILE__)
describe "Selenium::WebDriver::TargetLocator" do
let(:wait) { Selenium::WebDriver::Wait.new }
it "should find the active element" do
driver.navigate.to url_for("xhtmlTest.html")
driver.switch_to.active_element.should be_an_instance_of(WebDriver::Element)
end
not_compliant_on :browser => [:iphone] do
it "should switch to a frame" do
driver.navigate.to url_for("iframes.html")
driver.switch_to.frame("iframe1")
driver.find_element(:name, 'login').should be_kind_of(WebDriver::Element)
end
it "should switch to a frame by Element" do
driver.navigate.to url_for("iframes.html")
iframe = driver.find_element(:tag_name => "iframe")
driver.switch_to.frame(iframe)
driver.find_element(:name, 'login').should be_kind_of(WebDriver::Element)
end
end
# switching by name not yet supported by safari
not_compliant_on :browser => [:ie, :iphone, :safari] do
it "should switch to a window and back when given a block" do
driver.navigate.to url_for("xhtmlTest.html")
driver.find_element(:link, "Open new window").click
driver.title.should == "XHTML Test Page"
driver.switch_to.window("result") do
wait.until { driver.title == "We Arrive Here" }
end
wait.until { driver.title == "XHTML Test Page" }
reset_driver!
end
it "should handle exceptions inside the block" do
driver.navigate.to url_for("xhtmlTest.html")
driver.find_element(:link, "Open new window").click
driver.title.should == "XHTML Test Page"
lambda {
driver.switch_to.window("result") { raise "foo" }
}.should raise_error(RuntimeError, "foo")
driver.title.should == "XHTML Test Page"
reset_driver!
end
it "should switch to a window" do
driver.navigate.to url_for("xhtmlTest.html")
driver.find_element(:link, "Open new window").click
wait.until { driver.title == "XHTML Test Page" }
driver.switch_to.window("result")
wait.until { driver.title == "We Arrive Here" }
reset_driver!
end
it "should use the original window if the block closes the popup" do
driver.navigate.to url_for("xhtmlTest.html")
driver.find_element(:link, "Open new window").click
driver.title.should == "XHTML Test Page"
driver.switch_to.window("result") do
wait.until { driver.title == "We Arrive Here" }
driver.close
end
driver.current_url.should include("xhtmlTest.html")
driver.title.should == "XHTML Test Page"
reset_driver!
end
end
not_compliant_on :browser => [:android, :iphone, :safari] do
it "should switch to default content" do
driver.navigate.to url_for("iframes.html")
driver.switch_to.frame 0
driver.switch_to.default_content
driver.find_element(:id => "iframe_page_heading")
end
end
describe "alerts" do
not_compliant_on :browser => [:opera, :iphone, :safari, :phantomjs] do
it "allows the user to accept an alert" do
driver.navigate.to url_for("alerts.html")
driver.find_element(:id => "alert").click
driver.switch_to.alert.accept
driver.title.should == "Testing Alerts"
end
end
not_compliant_on({:browser => :chrome, :platform => :macosx}, # http://code.google.com/p/chromedriver/issues/detail?id=26
{:browser => :opera},
{:browser => :iphone},
{:browser => :safari},
{:browser => :phantomjs}) do
it "allows the user to dismiss an alert" do
driver.navigate.to url_for("alerts.html")
driver.find_element(:id => "alert").click
alert = wait_for_alert
alert.dismiss
driver.title.should == "Testing Alerts"
end
end
not_compliant_on :browser => [:opera, :iphone, :safari, :phantomjs] do
it "allows the user to set the value of a prompt" do
driver.navigate.to url_for("alerts.html")
driver.find_element(:id => "prompt").click
alert = wait_for_alert
alert.send_keys "cheese"
alert.accept
text = driver.find_element(:id => "text").text
text.should == "cheese"
end
it "allows the user to get the text of an alert" do
driver.navigate.to url_for("alerts.html")
driver.find_element(:id => "alert").click
alert = wait_for_alert
text = alert.text
alert.accept
text.should == "cheese"
end
it "raises when calling #text on a closed alert" do
driver.navigate.to url_for("alerts.html")
driver.find_element(:id => "alert").click
alert = wait_for_alert
alert.accept
expect { alert.text }.to raise_error(Selenium::WebDriver::Error::NoAlertPresentError)
end
end
not_compliant_on :browser => [:ie, :opera, :iphone, :safari, :phantomjs] do
it "raises NoAlertOpenError if no alert is present" do
lambda { driver.switch_to.alert }.should raise_error(
Selenium::WebDriver::Error::NoAlertPresentError, /alert|modal dialog/i)
end
end
compliant_on :browser => [:firefox, :ie] do
it "raises an UnhandledAlertError if an alert has not been dealt with" do
driver.navigate.to url_for("alerts.html")
driver.find_element(:id => "alert").click
wait_for_alert
lambda { driver.title }.should raise_error(Selenium::WebDriver::Error::UnhandledAlertError, /: "cheese"/)
driver.title.should == "Testing Alerts" # :chrome does not auto-dismiss the alert
end
end
end
end
| 1 | 11,085 | I tested it only in Firefox (`./go //rb:firefox-test`) | SeleniumHQ-selenium | rb |
@@ -10,6 +10,8 @@ import (
"net/http/httptest"
)
+// NewTestClient returns a TestClient with a replacement http handler function.
+// Methods on the new TestClient are overrideable as well.
func NewTestClient(handleFunc http.HandlerFunc) (*httptest.Server, *TestClient, error) {
ts := httptest.NewServer(handleFunc)
opts := []option.ClientOption{ | 1 | package compute
import (
"context"
"time"
"google.golang.org/api/compute/v1"
"google.golang.org/api/option"
"net/http"
"net/http/httptest"
)
func NewTestClient(handleFunc http.HandlerFunc) (*httptest.Server, *TestClient, error) {
ts := httptest.NewServer(handleFunc)
opts := []option.ClientOption{
option.WithEndpoint(ts.URL),
option.WithHTTPClient(http.DefaultClient),
}
c, err := NewClient(context.Background(), opts...)
if err != nil {
return nil, nil, err
}
tc := &TestClient{}
tc.client = *c.(*client)
tc.client.i = tc
return ts, tc, nil
}
type TestClient struct {
client
CreateDiskFn func(project, zone string, d *compute.Disk) error
CreateImageFn func(project string, i *compute.Image) error
CreateInstanceFn func(project, zone string, i *compute.Instance) error
DeleteDiskFn func(project, zone, name string) error
DeleteImageFn func(project, name string) error
DeleteInstanceFn func(project, zone, name string) error
GetSerialPortOutputFn func(project, zone, name string, port, start int64) (*compute.SerialPortOutput, error)
InstanceStatusFn func(project, zone, name string) (string, error)
InstanceStoppedFn func(project, zone, name string) (bool, error)
NewInstanceFn func(name, project, zone, machineType string) (*Instance, error)
WaitForInstanceStoppedFn func(project, zone, name string, interval time.Duration) error
operationsWaitFn func(project, zone, name string) error
}
func (c *TestClient) CreateDisk(project, zone string, d *compute.Disk) error {
if c.CreateDiskFn != nil {
return c.CreateDiskFn(project, zone, d)
}
return c.client.CreateDisk(project, zone, d)
}
func (c *TestClient) CreateImage(project string, i *compute.Image) error {
if c.CreateImageFn != nil {
return c.CreateImageFn(project, i)
}
return c.client.CreateImage(project, i)
}
func (c *TestClient) CreateInstance(project, zone string, i *compute.Instance) error {
if c.CreateImageFn != nil {
return c.CreateInstanceFn(project, zone, i)
}
return c.client.CreateInstance(project, zone, i)
}
func (c *TestClient) DeleteDisk(project, zone, name string) error {
if c.DeleteDiskFn != nil {
return c.DeleteDiskFn(project, zone, name)
}
return c.client.DeleteDisk(project, zone, name)
}
func (c *TestClient) DeleteImage(project, name string) error {
if c.DeleteImageFn != nil {
return c.DeleteImageFn(project, name)
}
return c.client.DeleteImage(project, name)
}
func (c *TestClient) DeleteInstance(project, zone, name string) error {
if c.DeleteInstanceFn != nil {
return c.DeleteInstanceFn(project, zone, name)
}
return c.client.DeleteInstance(project, zone, name)
}
func (c *TestClient) GetSerialPortOutput(project, zone, name string, port, start int64) (*compute.SerialPortOutput, error) {
if c.GetSerialPortOutputFn != nil {
return c.GetSerialPortOutputFn(project, zone, name, port, start)
}
return c.client.GetSerialPortOutput(project, zone, name, port, start)
}
func (c *TestClient) InstanceStatus(project, zone, name string) (string, error) {
if c.InstanceStatusFn != nil {
return c.InstanceStatusFn(project, zone, name)
}
return c.client.InstanceStatus(project, zone, name)
}
func (c *TestClient) InstanceStopped(project, zone, name string) (bool, error) {
if c.InstanceStoppedFn != nil {
return c.InstanceStoppedFn(project, zone, name)
}
return c.client.InstanceStopped(project, zone, name)
}
func (c *TestClient) NewInstance(name, project, zone, machineType string) (*Instance, error) {
if c.NewInstanceFn != nil {
return c.NewInstanceFn(name, project, zone, machineType)
}
return c.client.NewInstance(name, project, zone, machineType)
}
func (c *TestClient) WaitForInstanceStopped(project, zone, name string, interval time.Duration) error {
if c.WaitForInstanceStoppedFn != nil {
return c.WaitForInstanceStoppedFn(project, zone, name, interval)
}
return c.client.WaitForInstanceStopped(project, zone, name, interval)
}
func (c *TestClient) operationsWait(project, zone, name string) error {
if c.operationsWaitFn != nil {
return c.operationsWaitFn(project, zone, name)
}
return c.client.operationsWait(project, zone, name)
}
| 1 | 6,559 | separate third party and builtin | GoogleCloudPlatform-compute-image-tools | go |
@@ -818,7 +818,9 @@ public class SalesforceSDKManager {
// Finishes front activity if specified, and if this is the last account.
if (frontActivity != null && (users == null || users.size() <= 1)) {
- frontActivity.finish();
+ // only finish if it isn't hybrid or if hybrid, requires authentication
+ if (!isHybrid() || BootConfig.getBootConfig(frontActivity).shouldAuthenticate())
+ frontActivity.finish();
}
/* | 1 | /*
* Copyright (c) 2014-present, salesforce.com, inc.
* All rights reserved.
* Redistribution and use of this software in source and binary forms, with or
* without modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of salesforce.com, inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission of salesforce.com, inc.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.androidsdk.app;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Build;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.TextUtils;
import android.webkit.CookieManager;
import com.salesforce.androidsdk.BuildConfig;
import com.salesforce.androidsdk.R;
import com.salesforce.androidsdk.accounts.UserAccount;
import com.salesforce.androidsdk.accounts.UserAccountManager;
import com.salesforce.androidsdk.analytics.EventBuilderHelper;
import com.salesforce.androidsdk.analytics.SalesforceAnalyticsManager;
import com.salesforce.androidsdk.analytics.security.Encryptor;
import com.salesforce.androidsdk.auth.AuthenticatorService;
import com.salesforce.androidsdk.auth.HttpAccess;
import com.salesforce.androidsdk.auth.OAuth2;
import com.salesforce.androidsdk.auth.idp.IDPAccountPickerActivity;
import com.salesforce.androidsdk.config.AdminPermsManager;
import com.salesforce.androidsdk.config.AdminSettingsManager;
import com.salesforce.androidsdk.config.BootConfig;
import com.salesforce.androidsdk.config.LoginServerManager;
import com.salesforce.androidsdk.config.RuntimeConfig;
import com.salesforce.androidsdk.push.PushMessaging;
import com.salesforce.androidsdk.push.PushNotificationInterface;
import com.salesforce.androidsdk.rest.ClientManager;
import com.salesforce.androidsdk.rest.ClientManager.LoginOptions;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.security.PasscodeManager;
import com.salesforce.androidsdk.security.SalesforceKeyGenerator;
import com.salesforce.androidsdk.ui.AccountSwitcherActivity;
import com.salesforce.androidsdk.ui.DevInfoActivity;
import com.salesforce.androidsdk.ui.LoginActivity;
import com.salesforce.androidsdk.ui.PasscodeActivity;
import com.salesforce.androidsdk.ui.SalesforceR;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;
import com.salesforce.androidsdk.util.SalesforceSDKLogger;
import org.json.JSONObject;
import java.lang.reflect.Field;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.SortedSet;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListSet;
/**
* This class serves as an interface to the various
* functions of the Salesforce SDK. In order to use the SDK,
* your app must first instantiate the singleton SalesforceSDKManager
* object by calling the static init() method. After calling init(),
* use the static getInstance() method to access the
* singleton SalesforceSDKManager object.
*/
public class SalesforceSDKManager {
/**
* Current version of this SDK.
*/
public static final String SDK_VERSION = "6.2.0.dev";
/**
* Intent action meant for instances of SalesforceSDKManager residing in other processes
* to order them to clean up in-memory caches
*/
private static final String CLEANUP_INTENT_ACTION = "com.salesforce.CLEANUP";
// Receiver for CLEANUP_INTENT_ACTION broadcast
private CleanupReceiver cleanupReceiver;
// Key in broadcast for process id
private static final String PROCESS_ID_KEY = "processId";
// Unique per process id added to broadcast to prevent processing broadcast from own process
private static final String PROCESS_ID = UUID.randomUUID().toString();
// Key in broadcast for user account
private static final String USER_ACCOUNT = "userAccount";
/**
* Intent action that specifies that logout was completed.
*/
public static final String LOGOUT_COMPLETE_INTENT_ACTION = "com.salesforce.LOGOUT_COMPLETE";
/**
* Default app name.
*/
private static final String DEFAULT_APP_DISPLAY_NAME = "Salesforce";
private static final String INTERNAL_ENTROPY = "6cgs4f";
private static final String TAG = "SalesforceSDKManager";
protected static String AILTN_APP_NAME;
/**
* Instance of the SalesforceSDKManager to use for this process.
*/
protected static SalesforceSDKManager INSTANCE;
private static final int PUSH_UNREGISTER_TIMEOUT_MILLIS = 30000;
private static final String FEATURE_BROWSER_LOGIN = "BW";
private static final String FEATURE_APP_IS_SP = "SP";
protected Context context;
protected KeyInterface keyImpl;
protected LoginOptions loginOptions;
protected Class<? extends Activity> mainActivityClass;
protected Class<? extends Activity> loginActivityClass = LoginActivity.class;
protected Class<? extends PasscodeActivity> passcodeActivityClass = PasscodeActivity.class;
protected Class<? extends AccountSwitcherActivity> switcherActivityClass = AccountSwitcherActivity.class;
private SalesforceR salesforceR = new SalesforceR();
private PasscodeManager passcodeManager;
private LoginServerManager loginServerManager;
private boolean isTestRun = false;
private boolean isLoggingOut = false;
private AdminSettingsManager adminSettingsManager;
private AdminPermsManager adminPermsManager;
private PushNotificationInterface pushNotificationInterface;
private String uid; // device id
private volatile boolean loggedOut = false;
private SortedSet<String> features;
private List<String> additionalOauthKeys;
private String loginBrand;
private boolean browserLoginEnabled;
private String idpAppURIScheme;
private boolean idpAppLoginFlowActive;
/**
* PasscodeManager object lock.
*/
private Object passcodeManagerLock = new Object();
/**
* Dev support
*/
private AlertDialog devActionsDialog;
private Boolean isDevSupportEnabled; // NB: if null, it defaults to BuildConfig.DEBUG
/**
* Returns a singleton instance of this class.
*
* @return Singleton instance of SalesforceSDKManager.
*/
public static SalesforceSDKManager getInstance() {
if (INSTANCE != null) {
return INSTANCE;
} else {
throw new RuntimeException("Applications need to call SalesforceSDKManager.init() first.");
}
}
/**
*
* @return true if SalesforceSDKManager has been initialized already
*/
public static boolean hasInstance() {
return INSTANCE != null;
}
/**
* Sets the app name to be used by the analytics framework.
*
* @param appName App name.
*/
public static void setAiltnAppName(String appName) {
if (!TextUtils.isEmpty(appName)) {
AILTN_APP_NAME = appName;
}
}
/**
* Returns the app name being used by the analytics framework.
*
* @return App name.
*/
public static String getAiltnAppName() {
return AILTN_APP_NAME;
}
/**
* Protected constructor.
*
* @param context Application context.
* @param mainActivity Activity that should be launched after the login flow.
* @param loginActivity Login activity.
*/
protected SalesforceSDKManager(Context context, Class<? extends Activity> mainActivity,
Class<? extends Activity> loginActivity) {
this(context, null, mainActivity, loginActivity);
}
/**
* Protected constructor.
*
* @param context Application context.
* @param keyImpl Implementation for KeyInterface.
* @param mainActivity Activity that should be launched after the login flow.
* @param loginActivity Login activity.
* @deprecated Will be removed in Mobile SDK 7.0. Use {@link #SalesforceSDKManager(Context, Class, Class)} instead.
*/
@Deprecated
protected SalesforceSDKManager(Context context, KeyInterface keyImpl,
Class<? extends Activity> mainActivity, Class<? extends Activity> loginActivity) {
this.uid = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
this.context = context;
this.keyImpl = keyImpl;
this.mainActivityClass = mainActivity;
if (loginActivity != null) {
this.loginActivityClass = loginActivity;
}
this.features = new ConcurrentSkipListSet<>(String.CASE_INSENSITIVE_ORDER);
/*
* Checks if an analytics app name has already been set by the app.
* If not, fetches the default app name to be used and sets it.
*/
final String currentAiltnAppName = getAiltnAppName();
if (TextUtils.isEmpty(currentAiltnAppName)) {
String ailtnAppName = null;
try {
final PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
ailtnAppName = context.getString(packageInfo.applicationInfo.labelRes);
} catch (NameNotFoundException e) {
SalesforceSDKLogger.e(TAG, "Package not found", e);
}
if (!TextUtils.isEmpty(ailtnAppName)) {
setAiltnAppName(ailtnAppName);
}
}
// If your app runs in multiple processes, all the SalesforceSDKManager need to run cleanup during a logout
cleanupReceiver = new CleanupReceiver();
context.registerReceiver(cleanupReceiver, new IntentFilter(SalesforceSDKManager.CLEANUP_INTENT_ACTION));
}
/**
* Returns the class for the main activity.
*
* @return The class for the main activity.
*/
public Class<? extends Activity> getMainActivityClass() {
return mainActivityClass;
}
/**
* Returns the class for the account switcher activity.
*
* @return The class for the account switcher activity.
*/
public Class<? extends AccountSwitcherActivity> getAccountSwitcherActivityClass() {
return switcherActivityClass;
}
/**
* Returns the class for the account switcher activity.
*
* @return The class for the account switcher activity.
*/
public void setAccountSwitcherActivityClass(Class<? extends AccountSwitcherActivity> activity) {
if (activity != null) {
switcherActivityClass = activity;
}
}
/**
* @deprecated This interface has been deprecated in Mobile SDK 6.1 and will be removed
* in Mobile SDK 7.0. This is required to upgrade an app built on an older version of
* Mobile SDK to Mobile SDK 6.x.
*/
@Deprecated
public interface KeyInterface {
/**
* Defines a single function for retrieving the key
* associated with a given name.
*
* For the given name, this function must return the same key
* even when the application is restarted. The value this
* function returns must be Base64 encoded.
*
* {@link Encryptor#isBase64Encoded(String)} can be used to
* determine whether the generated key is Base64 encoded.
*
* {@link Encryptor#hash(String, String)} can be used to
* generate a Base64 encoded string.
*
* For example:
* <code>
* Encryptor.hash(name + "12s9adfgret=6235inkasd=012", name + "12kl0dsakj4-cuygsdf625wkjasdol8");
* </code>
*
* @param name The name associated with the key.
* @return The key used for encrypting salts and keys.
* @deprecated This interface has been deprecated in Mobile SDK 6.1 and will be removed
* in Mobile SDK 7.0. This is required to upgrade an app built on an older version of
* Mobile SDK to Mobile SDK 6.x.
*/
@Deprecated
public String getKey(String name);
}
/**
* For the given name, this function must return the same key
* even when the application is restarted. The value this
* function returns must be Base64 encoded.
*
* {@link Encryptor#isBase64Encoded(String)} can be used to
* determine whether the generated key is Base64 encoded.
*
* {@link Encryptor#hash(String, String)} can be used to
* generate a Base64 encoded string.
*
* For example:
* <code>
* Encryptor.hash(name + "12s9adfgret=6235inkasd=012", name + "12kl0dsakj4-cuygsdf625wkjasdol8");
* </code>
*
* @param name The name associated with the key.
* @return The key used for encrypting salts and keys.
* @deprecated This interface has been deprecated in Mobile SDK 6.1 and will be removed
* in Mobile SDK 7.0. This is required to upgrade an app built on an older version of
* Mobile SDK to Mobile SDK 6.x.
*/
@Deprecated
public String getKey(String name) {
String key = null;
if (keyImpl != null) {
key = keyImpl.getKey(name);
}
return key;
}
/**
* Before Mobile SDK 1.3, SalesforceSDK was packaged as a jar, and each project had to provide
* a subclass of SalesforceR.
*
* Since 1.3, SalesforceSDK is packaged as a library project, so the SalesforceR subclass is no longer needed.
* @return SalesforceR object which allows reference to resources living outside the SDK.
* @deprecated Will be removed in Mobile SDK 7.0. Resources can be referenced directly in a library project.
*/
@Deprecated
public SalesforceR getSalesforceR() {
return salesforceR;
}
/**
* Returns the class of the activity used to perform the login process and create the account.
*
* @return the class of the activity used to perform the login process and create the account.
*/
public Class<? extends Activity> getLoginActivityClass() {
return loginActivityClass;
}
/**
* Returns unique device ID.
*
* @return Device ID.
*/
public String getDeviceId() {
return uid;
}
/**
* Returns login options associated with the app.
*
* @return LoginOptions instance.
*/
public LoginOptions getLoginOptions() {
return getLoginOptions(null, null);
}
public LoginOptions getLoginOptions(String jwt, String url) {
if (loginOptions == null) {
final BootConfig config = BootConfig.getBootConfig(context);
if (TextUtils.isEmpty(jwt)) {
loginOptions = new LoginOptions(url, config.getOauthRedirectURI(),
config.getRemoteAccessConsumerKey(), config.getOauthScopes());
} else {
loginOptions = new LoginOptions(url, config.getOauthRedirectURI(),
config.getRemoteAccessConsumerKey(), config.getOauthScopes(), jwt);
}
} else {
loginOptions.setJwt(jwt);
loginOptions.setUrl(url);
}
return loginOptions;
}
private static void init(Context context, KeyInterface keyImpl,
Class<? extends Activity> mainActivity, Class<? extends Activity> loginActivity) {
if (INSTANCE == null) {
INSTANCE = new SalesforceSDKManager(context, keyImpl, mainActivity, loginActivity);
}
initInternal(context);
EventsObservable.get().notifyEvent(EventType.AppCreateComplete);
}
/**
* For internal use by Salesforce Mobile SDK or by subclasses
* of SalesforceSDKManager. Initializes required components.
*
* @param context Application context.
*/
public static void initInternal(Context context) {
// Upgrades to the latest version.
SalesforceSDKUpgradeManager.getInstance().upgrade();
// Initializes the encryption module.
Encryptor.init(context);
// Initializes the HTTP client.
HttpAccess.init(context, INSTANCE.getUserAgent());
// Enables IDP login flow if it's set through MDM.
final RuntimeConfig runtimeConfig = RuntimeConfig.getRuntimeConfig(context);
final String idpAppUrlScheme = runtimeConfig.getString(RuntimeConfig.ConfigKey.IDPAppURLScheme);
if (!TextUtils.isEmpty(idpAppUrlScheme)) {
INSTANCE.idpAppURIScheme = idpAppUrlScheme;
}
}
/**
* Initializes required components. Native apps must call one overload of
* this method before using the Salesforce Mobile SDK.
*
* @param context Application context.
* @param mainActivity Activity that should be launched after the login flow.
*/
public static void initNative(Context context, Class<? extends Activity> mainActivity) {
SalesforceSDKManager.init(context, null, mainActivity, LoginActivity.class);
}
/**
* Initializes required components. Native apps must call one overload of
* this method before using the Salesforce Mobile SDK.
*
* @param context Application context.
* @param keyImpl Implementation of KeyInterface.
* @param mainActivity Activity that should be launched after the login flow.
* @deprecated Will be removed in Mobile SDK 7.0. Use {@link #initNative(Context, Class)} instead.
*/
@Deprecated
public static void initNative(Context context, KeyInterface keyImpl, Class<? extends Activity> mainActivity) {
SalesforceSDKManager.init(context, keyImpl, mainActivity, LoginActivity.class);
}
/**
* Initializes required components. Native apps must call one overload of
* this method before using the Salesforce Mobile SDK.
*
* @param context Application context.
* @param mainActivity Activity that should be launched after the login flow.
* @param loginActivity Login activity.
*/
public static void initNative(Context context, Class<? extends Activity> mainActivity,
Class<? extends Activity> loginActivity) {
SalesforceSDKManager.init(context, null, mainActivity, loginActivity);
}
/**
* Initializes required components. Native apps must call one overload of
* this method before using the Salesforce Mobile SDK.
*
* @param context Application context.
* @param keyImpl Implementation of KeyInterface.
* @param mainActivity Activity that should be launched after the login flow.
* @param loginActivity Login activity.
* @deprecated Will be removed in Mobile SDK 7.0. Use {@link #initNative(Context, Class, Class)} instead.
*/
@Deprecated
public static void initNative(Context context, KeyInterface keyImpl,
Class<? extends Activity> mainActivity, Class<? extends Activity> loginActivity) {
SalesforceSDKManager.init(context, keyImpl, mainActivity, loginActivity);
}
/**
* Sets a custom passcode activity class to be used instead of the default class.
* The custom class must subclass PasscodeActivity.
*
* @param activity Subclass of PasscodeActivity.
*/
public void setPasscodeActivity(Class<? extends PasscodeActivity> activity) {
if (activity != null) {
passcodeActivityClass = activity;
}
}
/**
* Returns the descriptor of the passcode activity class that's currently in use.
*
* @return Passcode activity class descriptor.
*/
public Class<? extends PasscodeActivity> getPasscodeActivity() {
return passcodeActivityClass;
}
/**
* Indicates whether the SDK should automatically log out when the
* access token is revoked. If you override this method to return
* false, your app is responsible for handling its own cleanup when the
* access token is revoked.
*
* @return True if the SDK should automatically logout.
*/
public boolean shouldLogoutWhenTokenRevoked() {
return true;
}
/**
* Returns the application context.
*
* @return Application context.
*/
public Context getAppContext() {
return context;
}
/**
* Returns the login server manager associated with SalesforceSDKManager.
*
* @return LoginServerManager instance.
*/
public synchronized LoginServerManager getLoginServerManager() {
if (loginServerManager == null) {
loginServerManager = new LoginServerManager(context);
}
return loginServerManager;
}
/**
* Sets a receiver that handles received push notifications.
*
* @param pnInterface Implementation of PushNotificationInterface.
*/
public synchronized void setPushNotificationReceiver(PushNotificationInterface pnInterface) {
pushNotificationInterface = pnInterface;
}
/**
* Returns the receiver that's configured to handle incoming push notifications.
*
* @return Configured implementation of PushNotificationInterface.
*/
public synchronized PushNotificationInterface getPushNotificationReceiver() {
return pushNotificationInterface;
}
/**
* Returns the passcode manager that's associated with SalesforceSDKManager.
*
* @return PasscodeManager instance.
*/
public PasscodeManager getPasscodeManager() {
synchronized (passcodeManagerLock) {
if (passcodeManager == null) {
passcodeManager = new PasscodeManager(context);
}
return passcodeManager;
}
}
/**
* Returns the user account manager that's associated with SalesforceSDKManager.
*
* @return UserAccountManager instance.
*/
public UserAccountManager getUserAccountManager() {
return UserAccountManager.getInstance();
}
/**
* Returns the administrator settings manager that's associated with SalesforceSDKManager.
*
* @return AdminSettingsManager instance.
*/
public synchronized AdminSettingsManager getAdminSettingsManager() {
if (adminSettingsManager == null) {
adminSettingsManager = new AdminSettingsManager();
}
return adminSettingsManager;
}
/**
* Returns the administrator permissions manager that's associated with SalesforceSDKManager.
*
* @return AdminPermsManager instance.
*/
public synchronized AdminPermsManager getAdminPermsManager() {
if (adminPermsManager == null) {
adminPermsManager = new AdminPermsManager();
}
return adminPermsManager;
}
/**
* Returns the login brand parameter.
*
* @return Login brand, if configured.
*/
public String getLoginBrand() {
return loginBrand;
}
/**
* Sets the login brand. In the following example, "<brand>" should be set here.
* https://community.force.com/services/oauth2/authorize/<brand>?response_type=code&...
* Note: This API might change in the future.
*
* @param loginBrand Login brand param.
*/
public synchronized void setLoginBrand(String loginBrand) {
this.loginBrand = loginBrand;
}
/**
* Returns whether browser based login should be used instead of WebView.
*
* @return True - if Chrome should be used for login, False - otherwise.
*/
public boolean isBrowserLoginEnabled() {
return browserLoginEnabled;
}
/**
* Sets whether browser based login should be used instead of WebView.
*
* @param browserLoginEnabled True - if Chrome should be used for login, False - otherwise.
*/
public synchronized void setBrowserLoginEnabled(boolean browserLoginEnabled) {
this.browserLoginEnabled = browserLoginEnabled;
if (browserLoginEnabled) {
SalesforceSDKManager.getInstance().registerUsedAppFeature(FEATURE_BROWSER_LOGIN);
} else {
SalesforceSDKManager.getInstance().unregisterUsedAppFeature(FEATURE_BROWSER_LOGIN);
}
}
/**
* Returns whether the IDP login flow is enabled.
*
* @return True - if IDP login flow is enabled, False - otherwise.
*/
public boolean isIDPLoginFlowEnabled() {
boolean isIDPFlowEnabled = !TextUtils.isEmpty(idpAppURIScheme);
if (isIDPFlowEnabled) {
SalesforceSDKManager.getInstance().registerUsedAppFeature(FEATURE_APP_IS_SP);
} else {
SalesforceSDKManager.getInstance().unregisterUsedAppFeature(FEATURE_APP_IS_SP);
}
return isIDPFlowEnabled;
}
/**
* Checks for IDPAccountPickerActivity in manifest
* @return True - if this application is configured as a Identity Provider
*/
private boolean isIdentityProvider() {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(),
PackageManager.GET_ACTIVITIES);
for (ActivityInfo activityInfo : packageInfo.activities) {
if (activityInfo.name.equals(IDPAccountPickerActivity.class.getName())) {
return true;
}
}
} catch (NameNotFoundException e) {
SalesforceSDKLogger.e(TAG, "Exception occurred while examining application info", e);
}
return false;
}
/**
* Returns whether the IDP app is currently going through a login flow.
*
* @return True - if the IDP app is currently going through a login flow, False - otherwise.
*/
public boolean isIDPAppLoginFlowActive() {
return idpAppLoginFlowActive;
}
/**
* Sets whether the IDP app is currently going through a login flow.
*
* @param idpAppLoginFlowActive True - if the IDP app is kicking off login, False - otherwise.
*/
public synchronized void setIDPAppLoginFlowActive(boolean idpAppLoginFlowActive) {
this.idpAppLoginFlowActive = idpAppLoginFlowActive;
}
/**
* Returns the configured IDP app's URI scheme.
*
* @return IDP app's URI scheme.
*/
public String getIDPAppURIScheme() {
return idpAppURIScheme;
}
/**
* Sets the IDP app's URI scheme.
*
* @param idpAppURIScheme IDP app's URI scheme.
*/
public synchronized void setIDPAppURIScheme(String idpAppURIScheme) {
this.idpAppURIScheme = idpAppURIScheme;
}
/**
* Returns the app display name used by the passcode dialog.
*
* @return App display string.
*/
public String getAppDisplayString() {
return DEFAULT_APP_DISPLAY_NAME;
}
/**
* Returns the name of the application (as defined in AndroidManifest.xml).
*
* @return The name of the application.
*/
public String getApplicationName() {
return context.getPackageManager().getApplicationLabel(context.getApplicationInfo()).toString();
}
/**
* Checks if network connectivity exists.
*
* @return True if a network connection is available.
*/
public boolean hasNetwork() {
return HttpAccess.DEFAULT.hasNetwork();
}
/**
* Adds an additional set of OAuth keys to fetch and store from the token endpoint.
*
* @param additionalOauthKeys List of additional OAuth keys.
*/
public void setAdditionalOauthKeys(List<String> additionalOauthKeys) {
this.additionalOauthKeys = additionalOauthKeys;
}
/**
* Returns the list of additional OAuth keys set for this application.
*
* @return List of additional OAuth keys.
*/
public List<String> getAdditionalOauthKeys() {
return additionalOauthKeys;
}
/**
* Cleans up cached credentials and data.
*
* @param frontActivity Front activity.
* @param account Account.
*/
private void cleanUp(Activity frontActivity, Account account) {
final UserAccount userAccount = UserAccountManager.getInstance().buildUserAccount(account);
// Clean up in this process
cleanUp(userAccount);
// Have SalesforceSDKManager living in separate processes also clean up
sendCleanupIntent(userAccount);
final List<UserAccount> users = getUserAccountManager().getAuthenticatedUsers();
// Finishes front activity if specified, and if this is the last account.
if (frontActivity != null && (users == null || users.size() <= 1)) {
frontActivity.finish();
}
/*
* Checks how many accounts are left that are authenticated. If only one
* account is left, this is the account that is being removed. In this
* case, we can safely reset passcode manager, admin prefs, and encryption keys.
* Otherwise, we don't reset passcode manager and admin prefs since
* there might be other accounts on that same org, and these policies
* are stored at the org level.
*/
if (users == null || users.size() <= 1) {
getAdminSettingsManager().resetAll();
getAdminPermsManager().resetAll();
adminSettingsManager = null;
adminPermsManager = null;
getPasscodeManager().reset(context);
passcodeManager = null;
UUIDManager.resetUuids();
}
}
/**
* Clean up cached data
*
* @param userAccount
*/
protected void cleanUp(UserAccount userAccount) {
SalesforceAnalyticsManager.reset(userAccount);
RestClient.clearCaches(userAccount);
}
/**
* Starts login flow if user account has been removed.
*/
protected void startLoginPage() {
// Clears cookies.
removeAllCookies();
// Restarts the application.
final Intent i = new Intent(context, getMainActivityClass());
i.setPackage(getAppContext().getPackageName());
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
/**
* Starts account switcher activity if an account has been removed.
*/
public void startSwitcherActivityIfRequired() {
// Clears cookies.
removeAllCookies();
/*
* If the number of accounts remaining is 0, shows the login page.
* If the number of accounts remaining is 1, switches to that user
* automatically. If there is more than 1 account logged in, shows
* the account switcher screen, so that the user can pick which
* account to switch to.
*/
final UserAccountManager userAccMgr = getUserAccountManager();
final List<UserAccount> accounts = userAccMgr.getAuthenticatedUsers();
if (accounts == null || accounts.size() == 0) {
startLoginPage();
} else if (accounts.size() == 1) {
userAccMgr.switchToUser(accounts.get(0), UserAccountManager.USER_SWITCH_TYPE_LOGOUT, null);
} else {
final Intent i = new Intent(context, switcherActivityClass);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
/**
* Unregisters from push notifications for both GCM (Android) and SFDC, and waits either for
* unregistration to complete or for the operation to time out. The timeout period is defined
* in PUSH_UNREGISTER_TIMEOUT_MILLIS.
*
* If timeout occurs while the user is logged in, this method attempts to unregister the push
* unregistration receiver, and then removes the user's account.
*
* @param clientMgr ClientManager instance.
* @param showLoginPage True - if the login page should be shown, False - otherwise.
* @param refreshToken Refresh token.
* @param loginServer Login server.
* @param account Account instance.
* @param frontActivity Front activity.
*/
private void unregisterPush(final ClientManager clientMgr, final boolean showLoginPage,
final String refreshToken, final String loginServer,
final Account account, final Activity frontActivity) {
final IntentFilter intentFilter = new IntentFilter(PushMessaging.UNREGISTERED_ATTEMPT_COMPLETE_EVENT);
final BroadcastReceiver pushUnregisterReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(PushMessaging.UNREGISTERED_ATTEMPT_COMPLETE_EVENT)) {
postPushUnregister(this, clientMgr, showLoginPage,
refreshToken, loginServer, account, frontActivity);
}
}
};
getAppContext().registerReceiver(pushUnregisterReceiver, intentFilter);
// Unregisters from notifications on logout.
final UserAccount userAcc = getUserAccountManager().buildUserAccount(account);
PushMessaging.unregister(context, userAcc);
/*
* Starts a background thread to wait up to the timeout period. If
* another thread has already performed logout, we exit immediately.
*/
(new Thread() {
public void run() {
long startTime = System.currentTimeMillis();
while ((System.currentTimeMillis() - startTime) < PUSH_UNREGISTER_TIMEOUT_MILLIS && !loggedOut) {
// Waits for half a second at a time.
SystemClock.sleep(500);
}
postPushUnregister(pushUnregisterReceiver, clientMgr, showLoginPage,
refreshToken, loginServer, account, frontActivity);
};
}).start();
}
/**
* This method is called either when unregistration for push notifications
* is complete and the user has logged out, or when a timeout occurs while waiting.
* If the user has not logged out, this method attempts to unregister the push
* notification unregistration receiver, and then removes the user's account.
*
* @param pushReceiver Broadcast receiver.
* @param clientMgr ClientManager instance.
* @param showLoginPage True - if the login page should be shown, False - otherwise.
* @param refreshToken Refresh token.
* @param loginServer Login server.
* @param account Account instance.
* @param frontActivity Front activity.
*/
private synchronized void postPushUnregister(BroadcastReceiver pushReceiver,
final ClientManager clientMgr, final boolean showLoginPage,
final String refreshToken, final String loginServer,
final Account account, Activity frontActivity) {
if (!loggedOut) {
try {
context.unregisterReceiver(pushReceiver);
} catch (Exception e) {
SalesforceSDKLogger.e(TAG, "Exception occurred while unregistering", e);
}
removeAccount(clientMgr, showLoginPage, refreshToken, loginServer, account, frontActivity);
}
}
/**
* Destroys the stored authentication credentials (removes the account).
*
* @param frontActivity Front activity.
*/
public void logout(Activity frontActivity) {
logout(frontActivity, true);
}
/**
* Destroys the stored authentication credentials (removes the account).
*
* @param account Account.
* @param frontActivity Front activity.
*/
public void logout(Account account, Activity frontActivity) {
logout(account, frontActivity, true);
}
/**
* Destroys the stored authentication credentials (removes the account)
* and, if requested, restarts the app.
*
* @param frontActivity Front activity.
* @param showLoginPage If true, displays the login page after removing the account.
*/
public void logout(Activity frontActivity, final boolean showLoginPage) {
final ClientManager clientMgr = new ClientManager(context, getAccountType(),
null, shouldLogoutWhenTokenRevoked());
final Account account = clientMgr.getAccount();
logout(account, frontActivity, showLoginPage);
}
/**
* Destroys the stored authentication credentials (removes the account)
* and, if requested, restarts the app.
*
* @param account Account.
* @param frontActivity Front activity.
* @param showLoginPage If true, displays the login page after removing the account.
*/
public void logout(Account account, Activity frontActivity, final boolean showLoginPage) {
EventBuilderHelper.createAndStoreEvent("userLogout", null, TAG, null);
final ClientManager clientMgr = new ClientManager(context, getAccountType(),
null, shouldLogoutWhenTokenRevoked());
isLoggingOut = true;
final AccountManager mgr = AccountManager.get(context);
String refreshToken = null;
String loginServer = null;
if (account != null) {
refreshToken = SalesforceSDKManager.decrypt(mgr.getPassword(account));
loginServer = SalesforceSDKManager.decrypt(mgr.getUserData(account,
AuthenticatorService.KEY_INSTANCE_URL));
}
/*
* Makes a call to un-register from push notifications, only
* if the refresh token is available.
*/
final UserAccount userAcc = getUserAccountManager().buildUserAccount(account);
if (PushMessaging.isRegistered(context, userAcc) && refreshToken != null) {
loggedOut = false;
unregisterPush(clientMgr, showLoginPage, refreshToken,
loginServer, account, frontActivity);
} else {
removeAccount(clientMgr, showLoginPage, refreshToken,
loginServer, account, frontActivity);
}
}
/**
* Removes the account upon logout.
*
* @param clientMgr ClientManager instance.
* @param showLoginPage If true, displays the login page after removing the account.
* @param refreshToken Refresh token.
* @param loginServer Login server.
* @param account Account instance.
* @param frontActivity Front activity.
*/
private void removeAccount(ClientManager clientMgr, final boolean showLoginPage,
String refreshToken, String loginServer,
Account account, Activity frontActivity) {
loggedOut = true;
cleanUp(frontActivity, account);
/*
* Removes the existing account, if any. 'account == null' does not
* guarantee that there are no accounts to remove. In the 'Forgot Passcode'
* flow there could be accounts to remove, but we don't have them, since
* we don't have the passcode hash to decrypt them. Hence, we query
* AccountManager directly here and remove the accounts for the case
* where 'account == null'. If AccountManager doesn't have accounts
* either, then there's nothing to do.
*/
if (account == null) {
final AccountManager accMgr = AccountManager.get(context);
if (accMgr != null) {
final Account[] accounts = accMgr.getAccountsByType(getAccountType());
if (accounts.length > 0) {
for (int i = 0; i < accounts.length - 1; i++) {
clientMgr.removeAccounts(accounts);
}
clientMgr.removeAccountAsync(accounts[accounts.length - 1],
new AccountManagerCallback<Boolean>() {
@Override
public void run(AccountManagerFuture<Boolean> arg0) {
notifyLogoutComplete(showLoginPage);
}
});
} else {
notifyLogoutComplete(showLoginPage);
}
} else {
notifyLogoutComplete(showLoginPage);
}
} else {
clientMgr.removeAccountAsync(account, new AccountManagerCallback<Boolean>() {
@Override
public void run(AccountManagerFuture<Boolean> arg0) {
notifyLogoutComplete(showLoginPage);
}
});
}
isLoggingOut = false;
// Revokes the existing refresh token.
if (shouldLogoutWhenTokenRevoked() && account != null && refreshToken != null) {
new RevokeTokenTask(refreshToken, loginServer).execute();
}
}
private void notifyLogoutComplete(boolean showLoginPage) {
EventsObservable.get().notifyEvent(EventType.LogoutComplete);
sendLogoutCompleteIntent();
if (showLoginPage) {
startSwitcherActivityIfRequired();
}
}
/**
* Returns a user agent string based on the Mobile SDK version. The user agent takes the following form:
* SalesforceMobileSDK/{salesforceSDK version} android/{android OS version} appName/appVersion {Native|Hybrid} uid_{device id}
*
* @return The user agent string to use for all requests.
*/
public final String getUserAgent() {
return getUserAgent("");
}
public String getUserAgent(String qualifier) {
String appName = "";
String appVersion = "";
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
appName = context.getString(packageInfo.applicationInfo.labelRes);
appVersion = packageInfo.versionName;
} catch (NameNotFoundException e) {
SalesforceSDKLogger.w(TAG, "Package info could not be retrieved", e);
} catch (Resources.NotFoundException nfe) {
// A test harness such as Gradle does NOT have an application name.
SalesforceSDKLogger.w(TAG, "Package info could not be retrieved", nfe);
}
String appTypeWithQualifier = getAppType() + qualifier;
return String.format("SalesforceMobileSDK/%s android mobile/%s (%s) %s/%s %s uid_%s ftr_%s",
SDK_VERSION, Build.VERSION.RELEASE, Build.MODEL, appName, appVersion,
appTypeWithQualifier, uid, TextUtils.join(".", features));
}
/**
* Adds AppFeature code to User Agent header for reporting.
*/
public void registerUsedAppFeature(String appFeatureCode) {
features.add(appFeatureCode);
}
/**
* Removed AppFeature code to User Agent header for reporting.
*/
public void unregisterUsedAppFeature(String appFeatureCode) {
features.remove(appFeatureCode);
}
/**
* @return app type as String
*/
public String getAppType() {
return "Native";
}
/**
* Indicates whether the application is a hybrid application.
*
* @return True if this is a hybrid application.
*/
public boolean isHybrid() {
return false;
}
/**
* Returns the authentication account type (which should match authenticator.xml).
*
* @return Account type string.
*/
public String getAccountType() {
return context.getString(R.string.account_type);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(this.getClass()).append(": {\n")
.append(" accountType: ").append(getAccountType()).append("\n")
.append(" userAgent: ").append(getUserAgent()).append("\n")
.append(" mainActivityClass: ").append(getMainActivityClass()).append("\n")
.append(" isFileSystemEncrypted: ").append(Encryptor.isFileSystemEncrypted()).append("\n");
if (passcodeManager != null) {
// passcodeManager may be null at startup if the app is running in debug mode.
sb.append(" hasStoredPasscode: ").append(passcodeManager.hasStoredPasscode(context)).append("\n");
}
sb.append("}\n");
return sb.toString();
}
/**
* Encrypts the given data.
*
* @param data Data to be encrypted.
* @return Encrypted data.
*/
public static String encrypt(String data) {
return Encryptor.encrypt(data, getEncryptionKey());
}
/**
* Returns the encryption key being used.
*
* @return Encryption key.
*/
public static String getEncryptionKey() {
return SalesforceKeyGenerator.getEncryptionKey(INTERNAL_ENTROPY);
}
/**
* Decrypts the given data.
*
* @param data Data to be decrypted.
* @return Decrypted data.
*/
public static String decrypt(String data) {
return Encryptor.decrypt(data, getEncryptionKey());
}
/**
* Asynchronous task for revoking the refresh token on logout.
*
* @author bhariharan
*/
private static class RevokeTokenTask extends AsyncTask<Void, Void, Void> {
private String refreshToken;
private String loginServer;
public RevokeTokenTask(String refreshToken, String loginServer) {
this.refreshToken = refreshToken;
this.loginServer = loginServer;
}
@Override
protected Void doInBackground(Void... nothings) {
try {
OAuth2.revokeRefreshToken(HttpAccess.DEFAULT, new URI(loginServer), refreshToken);
} catch (Exception e) {
SalesforceSDKLogger.w(TAG, "Revoking token failed", e);
}
return null;
}
}
/**
* Retrieves a property value that indicates whether the current run is a test run.
*
* @return True if the current run is a test run.
*/
public boolean getIsTestRun() {
return INSTANCE.isTestRun;
}
/**
* Sets a property that indicates whether the current run is a test run.
*
* @param isTestRun True if the current run is a test run.
*/
public void setIsTestRun(boolean isTestRun) {
INSTANCE.isTestRun = isTestRun;
}
/**
* Retrieves a property value that indicates whether logout is in progress.
*
* @return True if logout is in progress.
*/
public boolean isLoggingOut() {
return isLoggingOut;
}
/**
* @return ClientManager
*/
public ClientManager getClientManager() {
return new ClientManager(getAppContext(), getAccountType(), getLoginOptions(), true);
}
/**
* @return ClientManager
*/
public ClientManager getClientManager(String jwt, String url) {
return new ClientManager(getAppContext(), getAccountType(), getLoginOptions(jwt, url), true);
}
public void removeAllCookies() {
CookieManager.getInstance().removeAllCookies(null);
}
public void removeSessionCookies() {
CookieManager.getInstance().removeSessionCookies(null);
}
public void syncCookies() {
CookieManager.getInstance().flush();
}
/**
* Show dev support dialog
*/
public void showDevSupportDialog(final Activity frontActivity) {
if (!isDevSupportEnabled()) {
return;
}
frontActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
final LinkedHashMap<String, DevActionHandler> devActions = getDevActions(frontActivity);
final DevActionHandler[] devActionHandlers = devActions.values().toArray(new DevActionHandler[0]);
devActionsDialog =
new AlertDialog.Builder(frontActivity)
.setItems(
devActions.keySet().toArray(new String[0]),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
devActionHandlers[which].onSelected();
devActionsDialog = null;
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
devActionsDialog = null;
}
})
.setTitle(R.string.sf__dev_support_title)
.create();
devActionsDialog.show();
}
});
}
/**
* Build dev actions to display in dev support dialog
* @param frontActivity
* @return map of title to dev actions handlers to display
*/
protected LinkedHashMap<String,DevActionHandler> getDevActions(final Activity frontActivity) {
LinkedHashMap<String, DevActionHandler> devActions = new LinkedHashMap<>();
devActions.put(
"Show dev info", new DevActionHandler() {
@Override
public void onSelected() {
frontActivity.startActivity(new Intent(frontActivity, DevInfoActivity.class));
}
});
devActions.put(
"Logout", new DevActionHandler() {
@Override
public void onSelected() {
SalesforceSDKManager.getInstance().logout(frontActivity);
}
});
devActions.put(
"Switch user", new DevActionHandler() {
@Override
public void onSelected() {
final Intent i = new Intent(SalesforceSDKManager.getInstance().getAppContext(),
SalesforceSDKManager.getInstance().getAccountSwitcherActivityClass());
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SalesforceSDKManager.getInstance().getAppContext().startActivity(i);
}
});
return devActions;
}
/**
* If the application did not call setDevSupportEnabled(..) then it defaults to BuildConfig.DEBUG
* @return true if dev support is enabled
*/
public boolean isDevSupportEnabled() {
return isDevSupportEnabled == null ? isDebugBuild() : isDevSupportEnabled.booleanValue();
}
/**
* Set isDevSupportEnabled
* @param isDevSupportEnabled
*/
public void setDevSupportEnabled(boolean isDevSupportEnabled) {
this.isDevSupportEnabled = isDevSupportEnabled;
}
/**
* @return Dev info (list of name1, value1, name2, value2 etc) to show in DevInfoActivity
*/
public List<String> getDevSupportInfos() {
List<String> devInfos = new ArrayList<>(Arrays.asList(
"SDK Version", SDK_VERSION,
"App Type", getAppType(),
"User Agent", getUserAgent(),
"Browser Login Enabled", isBrowserLoginEnabled() + "",
"IDP Enabled", isIDPLoginFlowEnabled() + "",
"Identity Provider", isIdentityProvider() + "",
"Current User", usersToString(getUserAccountManager().getCurrentUser()),
"Authenticated Users", usersToString(getUserAccountManager().getAuthenticatedUsers().toArray(new UserAccount[0]))
));
devInfos.addAll(getDevInfosFor(BootConfig.getBootConfig(context).asJSON(), "BootConfig"));
RuntimeConfig runtimeConfig = RuntimeConfig.getRuntimeConfig(context);
devInfos.addAll(Arrays.asList("Managed?", runtimeConfig.isManagedApp() + ""));
if (runtimeConfig.isManagedApp()) {
devInfos.addAll(getDevInfosFor(runtimeConfig.asJSON(), "Managed Pref"));
}
return devInfos;
}
private List<String> getDevInfosFor(JSONObject jsonObject, String keyPrefix) {
List<String> devInfos = new ArrayList<>();
if (jsonObject != null) {
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
devInfos.add(keyPrefix + " - " + key);
devInfos.add(jsonObject.opt(key) + "");
}
}
return devInfos;
}
private String usersToString(UserAccount... userAccounts) {
List<String> accountNames = new ArrayList<>();
if (userAccounts != null) {
for (UserAccount userAccount : userAccounts) {
accountNames.add(userAccount.getAccountName());
}
}
return TextUtils.join(", ", accountNames);
}
private void sendLogoutCompleteIntent() {
final Intent intent = new Intent(LOGOUT_COMPLETE_INTENT_ACTION);
intent.setPackage(context.getPackageName());
context.sendBroadcast(intent);
}
private void sendCleanupIntent(UserAccount userAccount) {
final Intent intent = new Intent(CLEANUP_INTENT_ACTION);
intent.setPackage(context.getPackageName());
intent.putExtra(PROCESS_ID_KEY, PROCESS_ID);
if (null != userAccount) {
intent.putExtra(USER_ACCOUNT, userAccount.toBundle());
}
context.sendBroadcast(intent);
}
private class CleanupReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null
&& intent.getAction().equals(SalesforceSDKManager.CLEANUP_INTENT_ACTION)
&& !intent.getStringExtra(PROCESS_ID_KEY).equals(PROCESS_ID)) {
UserAccount userAccount = null;
if (intent.hasExtra(USER_ACCOUNT)) {
userAccount = new UserAccount(intent.getBundleExtra(USER_ACCOUNT));
}
cleanUp(userAccount);
}
}
}
/**
* Action handler in dev support dialog
*/
public interface DevActionHandler {
/**
* Triggered in case when user select the action
*/
void onSelected();
}
/**
* Get BuildConfig.DEBUG by reflection (since it's only available in the app project)
* @return true if app's BuildConfig.DEBUG is true
*/
private boolean isDebugBuild() {
return ((Boolean) getBuildConfigValue(getAppContext(), "DEBUG")).booleanValue();
}
/**
* Gets a field from the project's BuildConfig.
* @param context Used to find the correct file
* @param fieldName The name of the field-to-access
* @return The value of the field, or {@code null} if the field is not found.
*/
private Object getBuildConfigValue(Context context, String fieldName) {
try {
Class<?> clazz = Class.forName(context.getPackageName() + ".BuildConfig");
Field field = clazz.getField(fieldName);
return field.get(null);
} catch (ClassNotFoundException e) {
SalesforceSDKLogger.e(TAG, "getBuildConfigValue failed", e);
} catch (NoSuchFieldException e) {
SalesforceSDKLogger.e(TAG, "getBuildConfigValue failed", e);
} catch (IllegalAccessException e) {
SalesforceSDKLogger.e(TAG, "getBuildConfigValue failed", e);
}
return BuildConfig.DEBUG; // we don't want to return a null value; return this value at minimum
}
}
| 1 | 16,681 | @smcnulty-sfdc We do want to finish the hybrid activity in our hybrid apps though. Could the caller not pass in `frontActivity` instead? Or start it up again post-logout? | forcedotcom-SalesforceMobileSDK-Android | java |
@@ -111,7 +111,7 @@ func (o outbound) Call(ctx context.Context, req *transport.Request) (*transport.
response, err := ctxhttp.Do(ctx, o.Client, request)
if err != nil {
- if err == context.DeadlineExceeded {
+ if err == ctx.Err() {
return nil, errors.NewTimeoutError(req.Service, req.Procedure, deadline.Sub(start))
}
| 1 | // Copyright (c) 2016 Uber Technologies, Inc.
//
// 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.
package http
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/yarpc/yarpc-go/internal/baggage"
"github.com/yarpc/yarpc-go/internal/errors"
"github.com/yarpc/yarpc-go/transport"
"github.com/uber-go/atomic"
"golang.org/x/net/context"
"golang.org/x/net/context/ctxhttp"
)
var (
errOutboundAlreadyStarted = errors.ErrOutboundAlreadyStarted("http.Outbound")
errOutboundNotStarted = errors.ErrOutboundNotStarted("http.Outbound")
)
// NewOutbound builds a new HTTP outbound that sends requests to the given
// URL.
func NewOutbound(url string) transport.Outbound {
return NewOutboundWithClient(url, nil)
}
// NewOutboundWithClient builds a new HTTP outbound that sends requests to the
// given URL using the given HTTP client.
func NewOutboundWithClient(url string, client *http.Client) transport.Outbound {
// TODO: Use option pattern with varargs instead
return outbound{Client: client, URL: url, started: atomic.NewBool(false)}
}
type outbound struct {
started *atomic.Bool
Client *http.Client
URL string
}
func (o outbound) Start() error {
if o.started.Swap(true) {
return errOutboundAlreadyStarted
}
return nil
}
// Options for the HTTP transport.
func (outbound) Options() (o transport.Options) {
return o
}
func (o outbound) Stop() error {
if !o.started.Swap(false) {
return errOutboundNotStarted
}
return nil
}
func (o outbound) Call(ctx context.Context, req *transport.Request) (*transport.Response, error) {
if !o.started.Load() {
// panic because there's no recovery from this
panic(errOutboundNotStarted)
}
start := time.Now()
deadline, _ := ctx.Deadline()
ttl := deadline.Sub(start)
request, err := http.NewRequest("POST", o.URL, req.Body)
if err != nil {
return nil, err
}
request.Header = applicationHeaders.ToHTTPHeaders(req.Headers, nil)
if hs := baggage.FromContext(ctx); hs.Len() > 0 {
request.Header = baggageHeaders.ToHTTPHeaders(hs, request.Header)
}
request.Header.Set(CallerHeader, req.Caller)
request.Header.Set(ServiceHeader, req.Service)
request.Header.Set(ProcedureHeader, req.Procedure)
request.Header.Set(TTLMSHeader, fmt.Sprintf("%d", ttl/time.Millisecond))
encoding := string(req.Encoding)
if encoding != "" {
request.Header.Set(EncodingHeader, encoding)
}
response, err := ctxhttp.Do(ctx, o.Client, request)
if err != nil {
if err == context.DeadlineExceeded {
return nil, errors.NewTimeoutError(req.Service, req.Procedure, deadline.Sub(start))
}
return nil, err
}
if response.StatusCode >= 200 && response.StatusCode < 300 {
appHeaders := applicationHeaders.FromHTTPHeaders(
response.Header, transport.NewHeaders())
return &transport.Response{
Headers: appHeaders,
Body: response.Body,
}, nil
}
// TODO Behavior for 300-range status codes is undefined
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
if err := response.Body.Close(); err != nil {
return nil, err
}
// Trim the trailing newline from HTTP error messages
message := strings.TrimSuffix(string(contents), "\n")
if response.StatusCode >= 400 && response.StatusCode < 500 {
return nil, errors.RemoteBadRequestError(message)
}
return nil, errors.RemoteUnexpectedError(message)
}
| 1 | 10,304 | isn't this going to return a timeout error if the context is canceled? | yarpc-yarpc-go | go |
@@ -15,6 +15,10 @@ class ArgsParser {
ArgsParser(String[] args) {
for (String arg : args) {
String[] argNameVal = arg.split("=");
+ if (argNameVal.length == 1) {
+ parsedArgs.put(argNameVal[0], "true");
+ continue;
+ }
if (argNameVal.length != 2) {
System.out.println("WARNING: Ignoring unrecognized argument: " + arg);
continue; | 1 | package com.google.api.codegen.bazel;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
class ArgsParser {
private final Map<String, String> parsedArgs = new HashMap<>();
ArgsParser(String[] args) {
for (String arg : args) {
String[] argNameVal = arg.split("=");
if (argNameVal.length != 2) {
System.out.println("WARNING: Ignoring unrecognized argument: " + arg);
continue;
}
parsedArgs.put(argNameVal[0], argNameVal[1].trim());
}
List<String> required = Collections.singletonList("--src");
if (!parsedArgs.keySet().containsAll(required)) {
String msg =
"ERROR: Not all of the required arguments are specified. "
+ "The required arguments are: "
+ required;
System.out.println(msg);
throw new IllegalArgumentException(msg);
}
}
ApisVisitor createApisVisitor(ApisVisitor.FileWriter fileWriter, String relativePathPrefix)
throws IOException {
String gapicApiTemplPath = parsedArgs.get("--gapic_api_templ");
String rootApiTemplPath = parsedArgs.get("--root_api_templ");
String rawApiTempl = parsedArgs.get("--raw_api_templ");
Path srcPath = Paths.get(parsedArgs.get("--src")).normalize();
Path destPath = srcPath;
String destArg = parsedArgs.get("--dest");
if (destArg != null) {
destPath = Paths.get(destArg).normalize();
}
if (relativePathPrefix != null) {
if (!srcPath.isAbsolute()) {
srcPath = Paths.get(relativePathPrefix, srcPath.toString());
}
if (!destPath.isAbsolute()) {
destPath = Paths.get(relativePathPrefix, destPath.toString());
}
}
return new ApisVisitor(
srcPath,
destPath,
gapicApiTemplPath == null
? readResource("BUILD.bazel.gapic_api.mustache")
: ApisVisitor.readFile(gapicApiTemplPath),
rootApiTemplPath == null
? readResource("BUILD.bazel.root_api.mustache")
: ApisVisitor.readFile(rootApiTemplPath),
rawApiTempl == null
? readResource("BUILD.bazel.raw_api.mustache")
: ApisVisitor.readFile(rawApiTempl),
fileWriter);
}
private String readResource(String resourcename) {
return new Scanner(getClass().getResourceAsStream(resourcename), "UTF-8")
.useDelimiter("\\A")
.next();
}
}
| 1 | 30,769 | `argNameVal.length` will still be !=2, so line 22 will give true and then continue on line 24 | googleapis-gapic-generator | java |
@@ -237,7 +237,7 @@ class FunctionDocblockManipulator
continue;
}
- if ($char === '\\' || preg_match('/\w/', $char)) {
+ if ($chars[$i + 1] === '\\' || preg_match('/\w/', $char)) {
if ($this->return_typehint_start === null) {
$this->return_typehint_start = $i + $end_bracket_position + 1;
} | 1 | <?php
namespace Psalm\Internal\FileManipulation;
use PhpParser;
use PhpParser\Node\Expr\ArrowFunction;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\FunctionLike;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Function_;
use Psalm\DocComment;
use Psalm\FileManipulation;
use Psalm\Internal\Analyzer\CommentAnalyzer;
use Psalm\Internal\Analyzer\ProjectAnalyzer;
use function array_merge;
use function count;
use function ltrim;
use function preg_match;
use function reset;
use function str_replace;
use function str_split;
use function strlen;
use function strpos;
use function strrpos;
use function substr;
/**
* @internal
*/
class FunctionDocblockManipulator
{
/**
* Manipulators ordered by line number
*
* @var array<string, array<int, FunctionDocblockManipulator>>
*/
private static $manipulators = [];
/** @var Closure|Function_|ClassMethod|ArrowFunction */
private $stmt;
/** @var int */
private $docblock_start;
/** @var int */
private $docblock_end;
/** @var int */
private $return_typehint_area_start;
/** @var null|int */
private $return_typehint_colon_start;
/** @var null|int */
private $return_typehint_start;
/** @var null|int */
private $return_typehint_end;
/** @var null|string */
private $new_php_return_type;
/** @var bool */
private $return_type_is_php_compatible = false;
/** @var null|string */
private $new_phpdoc_return_type;
/** @var null|string */
private $new_psalm_return_type;
/** @var array<string, string> */
private $new_php_param_types = [];
/** @var array<string, string> */
private $new_phpdoc_param_types = [];
/** @var array<string, string> */
private $new_psalm_param_types = [];
/** @var string */
private $indentation;
/** @var string|null */
private $return_type_description;
/** @var array<string, int> */
private $param_offsets = [];
/** @var array<string, array{int, int}> */
private $param_typehint_offsets = [];
/** @var bool */
private $is_pure = false;
/**
* @param Closure|Function_|ClassMethod|ArrowFunction $stmt
*/
public static function getForFunction(
ProjectAnalyzer $project_analyzer,
string $file_path,
FunctionLike $stmt
): FunctionDocblockManipulator {
if (isset(self::$manipulators[$file_path][$stmt->getLine()])) {
return self::$manipulators[$file_path][$stmt->getLine()];
}
$manipulator
= self::$manipulators[$file_path][$stmt->getLine()]
= new self($file_path, $stmt, $project_analyzer);
return $manipulator;
}
/**
* @param Closure|Function_|ClassMethod|ArrowFunction $stmt
*/
private function __construct(string $file_path, FunctionLike $stmt, ProjectAnalyzer $project_analyzer)
{
$this->stmt = $stmt;
$docblock = $stmt->getDocComment();
$this->docblock_start = $docblock ? $docblock->getStartFilePos() : (int)$stmt->getAttribute('startFilePos');
$this->docblock_end = $function_start = (int)$stmt->getAttribute('startFilePos');
$function_end = (int)$stmt->getAttribute('endFilePos');
$attributes = $stmt->getAttrGroups();
foreach ($attributes as $attribute) {
// if we have attribute groups, we need to consider that the function starts after them
if ((int) $attribute->getAttribute('endFilePos') > $function_start) {
$function_start = (int) $attribute->getAttribute('endFilePos');
}
}
foreach ($stmt->params as $param) {
if ($param->var instanceof PhpParser\Node\Expr\Variable
&& \is_string($param->var->name)
) {
$this->param_offsets[$param->var->name] = (int) $param->getAttribute('startFilePos');
if ($param->type) {
$this->param_typehint_offsets[$param->var->name] = [
(int) $param->type->getAttribute('startFilePos'),
(int) $param->type->getAttribute('endFilePos')
];
}
}
}
$codebase = $project_analyzer->getCodebase();
$file_contents = $codebase->getFileContents($file_path);
$last_arg_position = $stmt->params
? (int) $stmt->params[count($stmt->params) - 1]->getAttribute('endFilePos') + 1
: null;
if ($stmt instanceof Closure && $stmt->uses) {
$last_arg_position = (int) $stmt->uses[count($stmt->uses) - 1]->getAttribute('endFilePos') + 1;
}
$end_bracket_position = (int) strpos($file_contents, ')', $last_arg_position ?: $function_start);
$this->return_typehint_area_start = $end_bracket_position + 1;
$function_code = substr($file_contents, $function_start, $function_end);
$function_code_after_bracket = substr($function_code, $end_bracket_position + 1 - $function_start);
// do a little parsing here
$chars = str_split($function_code_after_bracket);
$in_single_line_comment = $in_multi_line_comment = false;
for ($i = 0, $iMax = count($chars); $i < $iMax; ++$i) {
$char = $chars[$i];
switch ($char) {
case "\n":
$in_single_line_comment = false;
continue 2;
case ':':
if ($in_multi_line_comment || $in_single_line_comment) {
continue 2;
}
$this->return_typehint_colon_start = $i + $end_bracket_position + 1;
continue 2;
case '/':
if ($in_multi_line_comment || $in_single_line_comment) {
continue 2;
}
if ($chars[$i + 1] === '*') {
$in_multi_line_comment = true;
++$i;
}
if ($chars[$i + 1] === '/') {
$in_single_line_comment = true;
++$i;
}
continue 2;
case '*':
if ($in_single_line_comment) {
continue 2;
}
if ($chars[$i + 1] === '/') {
$in_multi_line_comment = false;
++$i;
}
continue 2;
case '{':
if ($in_multi_line_comment || $in_single_line_comment) {
continue 2;
}
break 2;
case '?':
if ($in_multi_line_comment || $in_single_line_comment) {
continue 2;
}
$this->return_typehint_start = $i + $end_bracket_position + 1;
break;
}
if ($in_multi_line_comment || $in_single_line_comment) {
continue;
}
if ($char === '\\' || preg_match('/\w/', $char)) {
if ($this->return_typehint_start === null) {
$this->return_typehint_start = $i + $end_bracket_position + 1;
}
if ($chars[$i + 1] !== '\\' && !preg_match('/[\w]/', $chars[$i + 1])) {
$this->return_typehint_end = $i + $end_bracket_position + 2;
break;
}
}
}
$preceding_newline_pos = strrpos($file_contents, "\n", $this->docblock_end - strlen($file_contents));
if ($preceding_newline_pos === false) {
$this->indentation = '';
return;
}
$first_line = substr($file_contents, $preceding_newline_pos + 1, $this->docblock_end - $preceding_newline_pos);
$this->indentation = str_replace(ltrim($first_line), '', $first_line);
}
/**
* Sets the new return type
*
*/
public function setReturnType(
?string $php_type,
string $new_type,
string $phpdoc_type,
bool $is_php_compatible,
?string $description
): void {
$new_type = str_replace(['<mixed, mixed>', '<array-key, mixed>'], '', $new_type);
$this->new_php_return_type = $php_type;
$this->new_phpdoc_return_type = $phpdoc_type;
$this->new_psalm_return_type = $new_type;
$this->return_type_is_php_compatible = $is_php_compatible;
$this->return_type_description = $description;
}
/**
* Sets a new param type
*/
public function setParamType(
string $param_name,
?string $php_type,
string $new_type,
string $phpdoc_type
): void {
$new_type = str_replace(['<mixed, mixed>', '<array-key, mixed>', '<empty, empty>'], '', $new_type);
if ($php_type) {
$this->new_php_param_types[$param_name] = $php_type;
}
if ($php_type !== $phpdoc_type) {
$this->new_phpdoc_param_types[$param_name] = $phpdoc_type;
}
if ($php_type !== $new_type && $phpdoc_type !== $new_type) {
$this->new_psalm_param_types[$param_name] = $new_type;
}
}
/**
* Gets a new docblock given the existing docblock, if one exists, and the updated return types
* and/or parameters
*
*/
private function getDocblock(): string
{
$docblock = $this->stmt->getDocComment();
if ($docblock) {
$parsed_docblock = DocComment::parsePreservingLength($docblock);
} else {
$parsed_docblock = new \Psalm\Internal\Scanner\ParsedDocblock('', []);
}
$modified_docblock = false;
foreach ($this->new_phpdoc_param_types as $param_name => $phpdoc_type) {
$found_in_params = false;
$new_param_block = $phpdoc_type . ' ' . '$' . $param_name;
if (isset($parsed_docblock->tags['param'])) {
foreach ($parsed_docblock->tags['param'] as &$param_block) {
$doc_parts = CommentAnalyzer::splitDocLine($param_block);
if (($doc_parts[1] ?? null) === '$' . $param_name) {
if ($param_block !== $new_param_block) {
$modified_docblock = true;
}
$param_block = $new_param_block;
$found_in_params = true;
break;
}
}
}
if (!$found_in_params) {
$modified_docblock = true;
$parsed_docblock->tags['param'][] = $new_param_block;
}
}
foreach ($this->new_psalm_param_types as $param_name => $psalm_type) {
$found_in_params = false;
$new_param_block = $psalm_type . ' ' . '$' . $param_name;
if (isset($parsed_docblock->tags['psalm-param'])) {
foreach ($parsed_docblock->tags['psalm-param'] as &$param_block) {
$doc_parts = CommentAnalyzer::splitDocLine($param_block);
if (($doc_parts[1] ?? null) === '$' . $param_name) {
if ($param_block !== $new_param_block) {
$modified_docblock = true;
}
$param_block = $new_param_block;
$found_in_params = true;
break;
}
}
}
if (!$found_in_params) {
$modified_docblock = true;
$parsed_docblock->tags['psalm-param'][] = $new_param_block;
}
}
$old_phpdoc_return_type = null;
if (isset($parsed_docblock->tags['return'])) {
$old_phpdoc_return_type = reset($parsed_docblock->tags['return']);
}
if ($this->is_pure) {
$modified_docblock = true;
$parsed_docblock->tags['psalm-pure'] = [''];
}
if ($this->new_phpdoc_return_type && $this->new_phpdoc_return_type !== $old_phpdoc_return_type) {
$modified_docblock = true;
if ($this->new_phpdoc_return_type !== $this->new_php_return_type || $this->return_type_description) {
//only add the type if it's different than signature or if there's a description
$parsed_docblock->tags['return'] = [
$this->new_phpdoc_return_type
. ($this->return_type_description ? (' ' . $this->return_type_description) : ''),
];
} else {
unset($parsed_docblock->tags['return']);
}
}
$old_psalm_return_type = null;
if (isset($parsed_docblock->tags['psalm-return'])) {
$old_psalm_return_type = reset($parsed_docblock->tags['psalm-return']);
}
if ($this->new_psalm_return_type
&& $this->new_phpdoc_return_type !== $this->new_psalm_return_type
&& $this->new_psalm_return_type !== $old_psalm_return_type
) {
$modified_docblock = true;
$parsed_docblock->tags['psalm-return'] = [$this->new_psalm_return_type];
}
if (!$parsed_docblock->tags && !$parsed_docblock->description) {
return '';
}
if (!$modified_docblock) {
return (string)$docblock . "\n" . $this->indentation;
}
return $parsed_docblock->render($this->indentation);
}
/**
* @return array<int, FileManipulation>
*/
public static function getManipulationsForFile(string $file_path): array
{
if (!isset(self::$manipulators[$file_path])) {
return [];
}
$file_manipulations = [];
foreach (self::$manipulators[$file_path] as $manipulator) {
if ($manipulator->new_php_return_type) {
if ($manipulator->return_typehint_start && $manipulator->return_typehint_end) {
$file_manipulations[$manipulator->return_typehint_start] = new FileManipulation(
$manipulator->return_typehint_start,
$manipulator->return_typehint_end,
$manipulator->new_php_return_type
);
} else {
$file_manipulations[$manipulator->return_typehint_area_start] = new FileManipulation(
$manipulator->return_typehint_area_start,
$manipulator->return_typehint_area_start,
': ' . $manipulator->new_php_return_type
);
}
} elseif ($manipulator->new_php_return_type === ''
&& $manipulator->return_typehint_colon_start
&& $manipulator->new_phpdoc_return_type
&& $manipulator->return_typehint_start
&& $manipulator->return_typehint_end
) {
$file_manipulations[$manipulator->return_typehint_start] = new FileManipulation(
$manipulator->return_typehint_colon_start,
$manipulator->return_typehint_end,
''
);
}
if (!$manipulator->new_php_return_type
|| !$manipulator->return_type_is_php_compatible
|| $manipulator->docblock_start !== $manipulator->docblock_end
|| $manipulator->is_pure
) {
$file_manipulations[$manipulator->docblock_start] = new FileManipulation(
$manipulator->docblock_start,
$manipulator->docblock_end,
$manipulator->getDocblock()
);
}
foreach ($manipulator->new_php_param_types as $param_name => $new_php_param_type) {
if (!isset($manipulator->param_offsets[$param_name])) {
continue;
}
$param_offset = $manipulator->param_offsets[$param_name];
$typehint_offsets = $manipulator->param_typehint_offsets[$param_name] ?? null;
if ($new_php_param_type) {
if ($typehint_offsets) {
$file_manipulations[$typehint_offsets[0]] = new FileManipulation(
$typehint_offsets[0],
$typehint_offsets[1],
$new_php_param_type
);
} else {
$file_manipulations[$param_offset] = new FileManipulation(
$param_offset,
$param_offset,
$new_php_param_type . ' '
);
}
} elseif ($new_php_param_type === ''
&& $typehint_offsets
) {
$file_manipulations[$typehint_offsets[0]] = new FileManipulation(
$typehint_offsets[0],
$param_offset,
''
);
}
}
}
return $file_manipulations;
}
public function makePure() : void
{
$this->is_pure = true;
}
public static function clearCache(): void
{
self::$manipulators = [];
}
/**
* @param array<string, array<int, FunctionDocblockManipulator>> $manipulators
*/
public static function addManipulators(array $manipulators) : void
{
self::$manipulators = array_merge($manipulators, self::$manipulators);
}
/**
* @return array<string, array<int, FunctionDocblockManipulator>>
*/
public static function getManipulators(): array
{
return self::$manipulators;
}
}
| 1 | 11,380 | It was `$chars[$i]` I believe. | vimeo-psalm | php |
@@ -246,7 +246,7 @@ module Unix::Exec
else
val = val.to_s
end
- env_array << "#{key.to_s.upcase}=\"#{val}\""
+ env_array << "#{key.to_s}=\"#{val}\""
end
env_array
end | 1 | module Unix::Exec
include Beaker::CommandFactory
def reboot
if self['platform'] =~ /solaris/
exec(Beaker::Command.new("reboot"), :expect_connection_failure => true)
else
exec(Beaker::Command.new("/sbin/shutdown -r now"), :expect_connection_failure => true)
end
sleep(10) #if we attempt a reconnect too quickly we end up blocking ¯\_(ツ)_/¯
end
def echo(msg, abs=true)
(abs ? '/bin/echo' : 'echo') + " #{msg}"
end
def touch(file, abs=true)
(abs ? '/bin/touch' : 'touch') + " #{file}"
end
def path
'/bin:/usr/bin'
end
def get_ip
if self['platform'].include?('solaris') || self['platform'].include?('osx')
execute("ifconfig -a inet| awk '/broadcast/ {print $2}' | cut -d/ -f1 | head -1").strip
else
execute("ip a|awk '/global/{print$2}' | cut -d/ -f1 | head -1").strip
end
end
# Create the provided directory structure on the host
# @param [String] dir The directory structure to create on the host
# @return [Boolean] True, if directory construction succeeded, otherwise False
def mkdir_p dir
cmd = "mkdir -p #{dir}"
result = exec(Beaker::Command.new(cmd), :acceptable_exit_codes => [0, 1])
result.exit_code == 0
end
# Recursively remove the path provided
# @param [String] path The path to remove
def rm_rf path
execute("rm -rf #{path}")
end
# Move the origin to destination. The destination is removed prior to moving.
# @param [String] orig The origin path
# @param [String] dest the destination path
# @param [Boolean] rm Remove the destination prior to move
def mv orig, dest, rm=true
rm_rf dest unless !rm
execute("mv #{orig} #{dest}")
end
# Attempt to ping the provided target hostname
# @param [String] target The hostname to ping
# @param [Integer] attempts Amount of times to attempt ping before giving up
# @return [Boolean] true of ping successful, overwise false
def ping target, attempts=5
try = 0
while try < attempts do
result = exec(Beaker::Command.new("ping -c 1 #{target}"), :accept_all_exit_codes => true)
if result.exit_code == 0
return true
end
try+=1
end
result.exit_code == 0
end
# Converts the provided environment file to a new shell script in /etc/profile.d, then sources that file.
# This is for sles and debian based hosts.
# @param [String] env_file The ssh environment file to read from
def mirror_env_to_profile_d env_file
if self[:platform] =~ /sles-|debian/
@logger.debug("mirroring environment to /etc/profile.d on sles platform host")
cur_env = exec(Beaker::Command.new("cat #{env_file}")).stdout
shell_env = ''
cur_env.each_line do |env_line|
shell_env << "export #{env_line}"
end
#here doc it over
exec(Beaker::Command.new("cat << EOF > #{self[:profile_d_env_file]}\n#{shell_env}EOF"))
#set permissions
exec(Beaker::Command.new("chmod +x #{self[:profile_d_env_file]}"))
#keep it current
exec(Beaker::Command.new("source #{self[:profile_d_env_file]}"))
else
#noop
@logger.debug("will not mirror environment to /etc/profile.d on non-sles/debian platform host")
end
end
#Add the provided key/val to the current ssh environment
#@param [String] key The key to add the value to
#@param [String] val The value for the key
#@example
# host.add_env_var('PATH', '/usr/bin:PATH')
def add_env_var key, val
key = key.to_s
env_file = self[:ssh_env_file]
escaped_val = Regexp.escape(val).gsub('/', '\/').gsub(';', '\;')
#see if the key/value pair already exists
if exec(Beaker::Command.new("grep ^#{key}=.*#{escaped_val} #{env_file}"), :accept_all_exit_codes => true ).exit_code == 0
return #nothing to do here, key value pair already exists
#see if the key already exists
elsif exec(Beaker::Command.new("grep ^#{key}= #{env_file}"), :accept_all_exit_codes => true ).exit_code == 0
exec(Beaker::SedCommand.new(self['platform'], "s/^#{key}=/#{key}=#{escaped_val}:/", env_file))
else
exec(Beaker::Command.new("echo \"#{key}=#{val}\" >> #{env_file}"))
end
#update the profile.d to current state
#match it to the contents of ssh_env_file
mirror_env_to_profile_d(env_file)
end
#Delete the provided key/val from the current ssh environment
#@param [String] key The key to delete the value from
#@param [String] val The value to delete for the key
#@example
# host.delete_env_var('PATH', '/usr/bin:PATH')
def delete_env_var key, val
key = key.to_s
env_file = self[:ssh_env_file]
val = Regexp.escape(val).gsub('/', '\/').gsub(';', '\;')
#if the key only has that single value remove the entire line
exec(Beaker::SedCommand.new(self['platform'], "/#{key}=#{val}$/d", env_file))
#value in middle of list
exec(Beaker::SedCommand.new(self['platform'], "s/#{key}=\\(.*\\)[;:]#{val}/#{key}=\\1/", env_file))
#value in start of list
exec(Beaker::SedCommand.new(self['platform'], "s/#{key}=#{val}[;:]/#{key}=/", env_file))
#update the profile.d to current state
#match it to the contents of ssh_env_file
mirror_env_to_profile_d(env_file)
end
#Return the value of a specific env var
#@param [String] key The key to look for
#@example
# host.get_env_var('path')
def get_env_var key
key = key.to_s
exec(Beaker::Command.new("env | grep ^#{key}="), :accept_all_exit_codes => true).stdout.chomp
end
#Delete the environment variable from the current ssh environment
#@param [String] key The key to delete
#@example
# host.clear_env_var('PATH')
def clear_env_var key
key = key.to_s
env_file = self[:ssh_env_file]
#remove entire line
exec(Beaker::SedCommand.new(self['platform'], "/^#{key}=.*$/d", env_file))
#update the profile.d to current state
#match it to the contents of ssh_env_file
mirror_env_to_profile_d(env_file)
end
# Restarts the SSH service.
#
# @return [Result] result of restarting the SSH service
def ssh_service_restart
case self['platform']
when /debian|ubuntu|cumulus|huaweios/
exec(Beaker::Command.new("service ssh restart"))
when /el-7|centos-7|redhat-7|oracle-7|scientific-7|eos-7|fedora-(1[4-9]|2[0-9])|archlinux-/
exec(Beaker::Command.new("systemctl restart sshd.service"))
when /el-|centos|fedora|redhat|oracle|scientific|eos/
exec(Beaker::Command.new("/sbin/service sshd restart"))
when /sles/
exec(Beaker::Command.new("rcsshd restart"))
when /solaris/
exec(Beaker::Command.new("svcadm restart svc:/network/ssh:default"))
when /(free|open)bsd/
exec(Beaker::Command.new("sudo /etc/rc.d/sshd restart"))
else
raise ArgumentError, "Unsupported Platform: '#{self['platform']}'"
end
end
# Sets the PermitUserEnvironment setting & restarts the SSH service.
#
# @api private
# @return [Result] result of the command restarting the SSH service
# (from {#ssh_service_restart}).
def ssh_permit_user_environment
case self['platform']
when /debian|ubuntu|cumulus|huaweios|archlinux/
directory = create_tmpdir_on(self)
exec(Beaker::Command.new("echo 'PermitUserEnvironment yes' | cat - /etc/ssh/sshd_config > #{directory}/sshd_config.permit"))
exec(Beaker::Command.new("mv #{directory}/sshd_config.permit /etc/ssh/sshd_config"))
when /el-7|centos-7|redhat-7|oracle-7|scientific-7|eos-7/
directory = create_tmpdir_on(self)
exec(Beaker::Command.new("echo 'PermitUserEnvironment yes' | cat - /etc/ssh/sshd_config > #{directory}/sshd_config.permit"))
exec(Beaker::Command.new("mv #{directory}/sshd_config.permit /etc/ssh/sshd_config"))
when /el-|centos|fedora|redhat|oracle|scientific|eos/
directory = create_tmpdir_on(self)
exec(Beaker::Command.new("echo 'PermitUserEnvironment yes' | cat - /etc/ssh/sshd_config > #{directory}/sshd_config.permit"))
exec(Beaker::Command.new("mv #{directory}/sshd_config.permit /etc/ssh/sshd_config"))
when /sles/
directory = create_tmpdir_on(self)
exec(Beaker::Command.new("echo 'PermitUserEnvironment yes' | cat - /etc/ssh/sshd_config > #{directory}/sshd_config.permit"))
exec(Beaker::Command.new("mv #{directory}/sshd_config.permit /etc/ssh/sshd_config"))
when /solaris/
# kept solaris here because refactoring it into its own Host module
# conflicts with the solaris hypervisor that already exists
directory = create_tmpdir_on(self)
exec(Beaker::Command.new("echo 'PermitUserEnvironment yes' | cat - /etc/ssh/sshd_config > #{directory}/sshd_config.permit"))
exec(Beaker::Command.new("mv #{directory}/sshd_config.permit /etc/ssh/sshd_config"))
when /(free|open)bsd/
exec(Beaker::Command.new("sudo perl -pi -e 's/^#?PermitUserEnvironment no/PermitUserEnvironment yes/' /etc/ssh/sshd_config"), {:pty => true} )
else
raise ArgumentError, "Unsupported Platform: '#{self['platform']}'"
end
ssh_service_restart()
end
# Construct the environment string for this command
#
# @param [Hash{String=>String}] env An optional Hash containing
# key-value pairs to be treated
# as environment variables that
# should be set for the duration
# of the puppet command.
#
# @return [String] Returns a string containing command line arguments that
# will ensure the environment is correctly set for the
# given host.
def environment_string env
return '' if env.empty?
env_array = self.environment_variable_string_pair_array( env )
environment_string = env_array.join(' ')
"env #{environment_string}"
end
def environment_variable_string_pair_array env
env_array = []
env.each_key do |key|
val = env[key]
if val.is_a?(Array)
val = val.join(':')
else
val = val.to_s
end
env_array << "#{key.to_s.upcase}=\"#{val}\""
end
env_array
end
# Gets the specific prepend commands as needed for this host
#
# @param [String] command Command to be executed
# @param [String] user_pc List of user-specified commands to prepend
# @param [Hash] opts optional parameters
#
# @return [String] Command string as needed for this host
def prepend_commands(command = '', user_pc = '', opts = {})
user_pc
end
# Fills the user SSH environment file.
#
# @param [Hash{String=>String}] env Environment variables to set on the system,
# in the form of a hash of String variable
# names to their corresponding String values.
#
# @api private
# @return nil
def ssh_set_user_environment(env)
#ensure that ~/.ssh/environment exists
ssh_env_file_dir = Pathname.new(self[:ssh_env_file]).dirname
mkdir_p(ssh_env_file_dir)
exec(Beaker::Command.new("chmod 0600 #{ssh_env_file_dir}"))
exec(Beaker::Command.new("touch #{self[:ssh_env_file]}"))
#add the constructed env vars to this host
add_env_var('PATH', '$PATH')
# FIXME
if self['platform'] =~ /openbsd-(\d)\.?(\d)-(.+)/
version = "#{$1}.#{$2}"
arch = $3
arch = 'amd64' if ['x64', 'x86_64'].include?(arch)
add_env_var('PKG_PATH', "http://ftp.openbsd.org/pub/OpenBSD/#{version}/packages/#{arch}/")
elsif self['platform'] =~ /solaris-10/
add_env_var('PATH', '/opt/csw/bin')
end
#add the env var set to this test host
env.each_pair do |var, value|
add_env_var(var, value)
end
end
# Checks if selinux is enabled
#
# @return [Boolean] true if selinux is enabled, false otherwise
def selinux_enabled?()
exec(Beaker::Command.new("sudo selinuxenabled"), :accept_all_exit_codes => true).exit_code == 0
end
end
| 1 | 14,283 | This has the likely potential to break existing tests that are relying on the old beaker behavior. If we are going to release this in beaker 3.x, then we need to preserve the old behavior as well (so set both the `upcase` and original values). On Windows, they env variables will overwrite each other, with the same value, so not an issue. On *nix, there will be two env variables, but they will have the same value, so again no issue. | voxpupuli-beaker | rb |
@@ -299,6 +299,7 @@ Blockly.Variables.createVariable = function(workspace, opt_callback, opt_type) {
// Prompt the user to enter a name for the variable
Blockly.prompt(newMsg, '',
function(text, additionalVars, variableOptions) {
+ variableOptions = variableOptions || {};
var scope = variableOptions.scope;
var isLocal = (scope === 'local') || false;
var isCloud = variableOptions.isCloud || false; | 1 | /**
* @license
* Visual Blocks Editor
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* 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.
*/
/**
* @fileoverview Utility functions for handling variables.
* @author [email protected] (Neil Fraser)
*/
'use strict';
/**
* @name Blockly.Variables
* @namespace
**/
goog.provide('Blockly.Variables');
goog.require('Blockly.Blocks');
goog.require('Blockly.constants');
goog.require('Blockly.VariableModel');
goog.require('Blockly.Workspace');
goog.require('goog.string');
/**
* Constant to separate variable names from procedures and generated functions
* when running generators.
* @deprecated Use Blockly.VARIABLE_CATEGORY_NAME
*/
Blockly.Variables.NAME_TYPE = Blockly.VARIABLE_CATEGORY_NAME;
/**
* Constant prefix to differentiate cloud variable names from other types
* of variables.
* This is the \u2601 cloud unicode character followed by a space.
* @type {string}
* @package
*/
Blockly.Variables.CLOUD_PREFIX = '☁ ';
/**
* Find all user-created variables that are in use in the workspace.
* For use by generators.
* @param {!Blockly.Block|!Blockly.Workspace} root Root block or workspace.
* @return {!Array.<string>} Array of variable names.
*/
Blockly.Variables.allUsedVariables = function(root) {
var blocks;
if (root instanceof Blockly.Block) {
// Root is Block.
blocks = root.getDescendants(false);
} else if (root instanceof Blockly.Workspace ||
root instanceof Blockly.WorkspaceSvg) {
// Root is Workspace.
blocks = root.getAllBlocks();
} else {
throw 'Not Block or Workspace: ' + root;
}
var ignorableName = Blockly.Variables.noVariableText();
var variableHash = Object.create(null);
// Iterate through every block and add each variable to the hash.
for (var x = 0; x < blocks.length; x++) {
var blockVariables = blocks[x].getVarModels();
if (blockVariables) {
for (var y = 0; y < blockVariables.length; y++) {
var variable = blockVariables[y];
// Variable ID may be null if the block is only half-built.
if (variable.getId() && variable.name.toLowerCase() != ignorableName) {
variableHash[variable.name.toLowerCase()] = variable.name;
}
}
}
}
// Flatten the hash into a list.
var variableList = [];
for (var name in variableHash) {
variableList.push(variableHash[name]);
}
return variableList;
};
/**
* Find all variables that the user has created through the workspace or
* toolbox. For use by generators.
* @param {!Blockly.Workspace} root The workspace to inspect.
* @return {!Array.<Blockly.VariableModel>} Array of variable models.
*/
Blockly.Variables.allVariables = function(root) {
if (root instanceof Blockly.Block) {
// Root is Block.
console.warn('Deprecated call to Blockly.Variables.allVariables ' +
'with a block instead of a workspace. You may want ' +
'Blockly.Variables.allUsedVariables');
return {};
}
return root.getAllVariables();
};
/**
* Find all developer variables used by blocks in the workspace.
* Developer variables are never shown to the user, but are declared as global
* variables in the generated code.
* To declare developer variables, define the getDeveloperVariables function on
* your block and return a list of variable names.
* For use by generators.
* @param {!Blockly.Workspace} workspace The workspace to search.
* @return {!Array.<string>} A list of non-duplicated variable names.
* @package
*/
Blockly.Variables.allDeveloperVariables = function(workspace) {
var blocks = workspace.getAllBlocks();
var hash = {};
for (var i = 0; i < blocks.length; i++) {
var block = blocks[i];
if (block.getDeveloperVars) {
var devVars = block.getDeveloperVars();
for (var j = 0; j < devVars.length; j++) {
hash[devVars[j]] = devVars[j];
}
}
}
// Flatten the hash into a list.
var list = [];
for (var name in hash) {
list.push(hash[name]);
}
return list;
};
/**
* Return the text that should be used in a field_variable or
* field_variable_getter when no variable exists.
* TODO: #572
* @return {string} The text to display.
*/
Blockly.Variables.noVariableText = function() {
return "No variable selected";
};
/**
* Return a new variable name that is not yet being used. This will try to
* generate single letter variable names in the range 'i' to 'z' to start with.
* If no unique name is located it will try 'i' to 'z', 'a' to 'h',
* then 'i2' to 'z2' etc. Skip 'l'.
* @param {!Blockly.Workspace} workspace The workspace to be unique in.
* @return {string} New variable name.
*/
Blockly.Variables.generateUniqueName = function(workspace) {
var variableList = workspace.getAllVariables();
var newName = '';
if (variableList.length) {
var nameSuffix = 1;
var letters = 'ijkmnopqrstuvwxyzabcdefgh'; // No 'l'.
var letterIndex = 0;
var potName = letters.charAt(letterIndex);
while (!newName) {
var inUse = false;
for (var i = 0; i < variableList.length; i++) {
if (variableList[i].name.toLowerCase() == potName) {
// This potential name is already used.
inUse = true;
break;
}
}
if (inUse) {
// Try the next potential name.
letterIndex++;
if (letterIndex == letters.length) {
// Reached the end of the character sequence so back to 'i'.
// a new suffix.
letterIndex = 0;
nameSuffix++;
}
potName = letters.charAt(letterIndex);
if (nameSuffix > 1) {
potName += nameSuffix;
}
} else {
// We can use the current potential name.
newName = potName;
}
}
} else {
newName = 'i';
}
return newName;
};
/**
* Remove any possiblity of conflict/duplication between a real and potential variable.
* When creating a new variable, checks whether the desired name and type already exists
* as a real or potential variable.
* If 'checkReal' is true, checks whether a real variable with the given
* name and type already exists.
* Checks whether a potential variable (using the given 'potentialVarWs') exists.
* If a potential var exists and a real var also exists, discards the potential var
* and returns the real var.
* If a potential var exists and a real var does not exist (or 'checkReal'
* was false), creates the potential var as a real var,
* discards the potential var, and returns the newly created real var.
* If a potential var does not exist, returns null.
*
* @param {string} varName The name of the variable to check for.
* @param {string} varType The type of the variable to check for.
* @param {!Blockly.Workspace} potentialVarWs The workspace containing the
* potential variable map we want to check against.
* @param {boolean} checkReal Whether or not to check if a variable of the given
* name and type exists as a real variable.
* @return {?Blockly.VariableModel} The matching variable, if one already existed
* in the real workspace; the newly transformed variable, if one already
* existed as a potential variable. Null, if no matching variable, real or
* potential, was found.
*/
Blockly.Variables.realizePotentialVar = function(varName, varType, potentialVarWs,
checkReal) {
var potentialVarMap = potentialVarWs.getPotentialVariableMap();
var realWs = potentialVarWs.targetWorkspace;
if (!potentialVarMap) {
console.warn('Called Blockly.Variables.realizePotentialVar with incorrect ' +
'workspace. The provided workspace does not have a potential variable map.');
return;
}
// First check if a variable with the same name and type already exists as a
// real variable.
var realVar;
if (checkReal) {
realVar = Blockly.Variables.getVariable(realWs, null, varName, varType);
}
// Check if variable with same name and type exists as a potential var
var potentialVar = potentialVarMap.getVariable(varName, varType);
if (!potentialVar) {
return null;
}
// The potential var exists, so save its id and delete it from the potential
// variable map.
var id = potentialVar.getId();
potentialVarMap.deleteVariable(potentialVar);
// Depending on whether a real var already exists or not, either return the
// existing real var or turn the potential var into a new one using its id.
if (realVar) {
return realVar;
}
return realWs.createVariable(varName, varType, id);
};
/**
* Create a new variable on the given workspace.
* @param {!Blockly.Workspace} workspace The workspace on which to create the
* variable.
* @param {function(?string=)=} opt_callback An optional callback function to act
* on the id of the variable that is created from the user's input, or null
* if the change is to be aborted (cancel button or an invalid name was provided).
* @param {string} opt_type Optional type of the variable to be created,
* like 'string' or 'list'.
*/
Blockly.Variables.createVariable = function(workspace, opt_callback, opt_type) {
// Decide on a modal message based on the opt_type. If opt_type was not
// provided, default to the original message for scalar variables.
var newMsg, modalTitle;
if (opt_type == Blockly.BROADCAST_MESSAGE_VARIABLE_TYPE) {
newMsg = Blockly.Msg.NEW_BROADCAST_MESSAGE_TITLE;
modalTitle = Blockly.Msg.BROADCAST_MODAL_TITLE;
} else if (opt_type == Blockly.LIST_VARIABLE_TYPE) {
newMsg = Blockly.Msg.NEW_LIST_TITLE;
modalTitle = Blockly.Msg.LIST_MODAL_TITLE;
} else {
// Note: this case covers 1) scalar variables, 2) any new type of
// variable not explicitly checked for above, and 3) a null or undefined
// opt_type -- turns a falsey opt_type into ''
// TODO (#1251) Warn developers that they didn't provide an opt_type/provided
// a falsey opt_type
opt_type = opt_type ? opt_type : '';
newMsg = Blockly.Msg.NEW_VARIABLE_TITLE;
modalTitle = Blockly.Msg.VARIABLE_MODAL_TITLE;
}
var validate = Blockly.Variables.nameValidator_.bind(null, opt_type);
// Prompt the user to enter a name for the variable
Blockly.prompt(newMsg, '',
function(text, additionalVars, variableOptions) {
var scope = variableOptions.scope;
var isLocal = (scope === 'local') || false;
var isCloud = variableOptions.isCloud || false;
// Default to [] if additionalVars is not provided
additionalVars = additionalVars || [];
// Only use additionalVars for global variable creation.
var additionalVarNames = isLocal ? [] : additionalVars;
var validatedText = validate(text, workspace, additionalVarNames, isCloud, opt_callback);
if (validatedText) {
// The name is valid according to the type, create the variable
var potentialVarMap = workspace.getPotentialVariableMap();
var variable;
// This check ensures that if a new variable is being created from a
// workspace that already has a variable of the same name and type as
// a potential variable, that potential variable gets turned into a
// real variable and thus there aren't duplicate options in the field_variable
// dropdown.
if (potentialVarMap && opt_type) {
variable = Blockly.Variables.realizePotentialVar(validatedText,
opt_type, workspace, false);
}
if (!variable) {
variable = workspace.createVariable(validatedText, opt_type, null, isLocal, isCloud);
}
var flyout = workspace.isFlyout ? workspace : workspace.getFlyout();
var variableBlockId = variable.getId();
if (flyout.setCheckboxState) {
flyout.setCheckboxState(variableBlockId, true);
}
if (opt_callback) {
opt_callback(variableBlockId);
}
} else {
// User canceled prompt without a value.
if (opt_callback) {
opt_callback(null);
}
}
}, modalTitle, opt_type);
};
/**
* This function provides a common interface for variable name validation agnostic
* of type. This is so that functions like Blockly.Variables.createVariable and
* Blockly.Variables.renameVariable can call a single function (with a single
* type signature) to validate the user-provided name for a variable.
* @param {string} type The type of the variable for which the provided name
* should be validated.
* @param {string} text The user-provided text that should be validated as a
* variable name.
* @param {!Blockly.Workspace} workspace The workspace on which to validate the
* variable name. This is the workspace used to check whether the variable
* already exists.
* @param {Array<string>} additionalVars A list of additional var names to check
* for conflicts against.
* @param {boolean} isCloud Whether the variable is a cloud variable.
* @param {function(?string=)=} opt_callback An optional function to be called on
* a pre-existing variable of the user-provided name. This function is currently
* only used for broadcast messages.
* @return {string} The validated name according to the parameters given, if
* the name is determined to be valid, or null if the name
* is determined to be invalid/in-use, and the calling function should not
* proceed with creating or renaming the variable.
* @private
*/
Blockly.Variables.nameValidator_ = function(type, text, workspace, additionalVars,
isCloud, opt_callback) {
// The validators for the different variable types require slightly different arguments.
// For broadcast messages, if a broadcast message of the provided name already exists,
// the validator needs to call a function that updates the selected
// field option of the dropdown menu of the block that was used to create the new message.
// For scalar variables and lists, the validator has the same validation behavior, but needs
// to know which type of variable to check for and needs a type-specific error message
// that is displayed when a variable of the given name and type already exists.
if (type == Blockly.BROADCAST_MESSAGE_VARIABLE_TYPE) {
return Blockly.Variables.validateBroadcastMessageName_(text, workspace, opt_callback);
} else if (type == Blockly.LIST_VARIABLE_TYPE) {
return Blockly.Variables.validateScalarVarOrListName_(text, workspace, additionalVars, false, type,
Blockly.Msg.LIST_ALREADY_EXISTS);
} else {
return Blockly.Variables.validateScalarVarOrListName_(text, workspace, additionalVars, isCloud, type,
Blockly.Msg.VARIABLE_ALREADY_EXISTS);
}
};
/**
* Validate the given name as a broadcast message type.
* @param {string} name The name to validate
* @param {!Blockly.Workspace} workspace The workspace the name should be validated
* against.
* @param {function(?string=)=} opt_callback An optional function to call if a broadcast
* message already exists with the given name. This function will be called on the id
* of the existing variable.
* @return {string} The validated name, or null if invalid.
* @private
*/
Blockly.Variables.validateBroadcastMessageName_ = function(name, workspace, opt_callback) {
if (!name) { // no name was provided or the user cancelled the prompt
return null;
}
var variable = workspace.getVariable(name, Blockly.BROADCAST_MESSAGE_VARIABLE_TYPE);
if (variable) {
// If the user provided a name for a broadcast message that already exists,
// use the provided callback function to update the selected option in
// the field of the block that was used to create
// this message.
if (opt_callback) {
opt_callback(variable.getId());
}
// Return null to signal to the calling function that we do not want to create
// a new variable since one already exists.
return null;
} else {
// The name provided is actually a new name, so the calling
// function should go ahead and create it as a new variable.
return name;
}
};
/**
* Validate the given name as a scalar variable or list type.
* This function is also responsible for any user facing error-handling.
* @param {string} name The name to validate
* @param {!Blockly.Workspace} workspace The workspace the name should be validated
* against.
* @param {Array<string>} additionalVars A list of additional variable names to check
* for conflicts against.
* @param {boolean} isCloud Whether the variable is a cloud variable.
* @param {string} type The type to validate the variable as. This should be one of
* Blockly.SCALAR_VARIABLE_TYPE or Blockly.LIST_VARIABLE_TYPE.
* @param {string} errorMsg The type-specific error message the user should see
* if a variable of the validated, given name and type already exists.
* @return {string} The validated name, or null if invalid.
* @private
*/
Blockly.Variables.validateScalarVarOrListName_ = function(name, workspace, additionalVars,
isCloud, type, errorMsg) {
// For scalar variables, we don't want leading or trailing white space
name = Blockly.Variables.trimName_(name);
if (!name) {
return null;
}
if (isCloud) {
name = Blockly.Variables.CLOUD_PREFIX + name;
}
if (workspace.getVariable(name, type) || additionalVars.indexOf(name) >= 0) {
// error
Blockly.alert(errorMsg.replace('%1', name));
return null;
} else { // trimmed name is valid
return name;
}
};
/**
* Rename a variable with the given workspace, variableType, and oldName.
* @param {!Blockly.Workspace} workspace The workspace on which to rename the
* variable.
* @param {Blockly.VariableModel} variable Variable to rename.
* @param {function(?string=)=} opt_callback A callback. It will
* be passed an acceptable new variable name, or null if change is to be
* aborted (cancel button), or undefined if an existing variable was chosen.
*/
Blockly.Variables.renameVariable = function(workspace, variable,
opt_callback) {
// Validation and modal message/title depends on the variable type
var promptMsg, modalTitle;
var varType = variable.type;
if (varType == Blockly.BROADCAST_MESSAGE_VARIABLE_TYPE) {
console.warn('Unexpected attempt to rename a broadcast message with ' +
'id: ' + variable.getId() + ' and name: ' + variable.name);
return;
}
if (varType == Blockly.LIST_VARIABLE_TYPE) {
promptMsg = Blockly.Msg.RENAME_LIST_TITLE;
modalTitle = Blockly.Msg.RENAME_LIST_MODAL_TITLE;
} else {
// Default for all other types of variables
promptMsg = Blockly.Msg.RENAME_VARIABLE_TITLE;
modalTitle = Blockly.Msg.RENAME_VARIABLE_MODAL_TITLE;
}
var validate = Blockly.Variables.nameValidator_.bind(null, varType);
var promptText = promptMsg.replace('%1', variable.name);
Blockly.prompt(promptText, '',
function(newName, additionalVars) {
if (variable.isCloud &&
newName.length > 0 && newName.indexOf(Blockly.Variables.CLOUD_PREFIX) == 0 ) {
newName = newName.substring(2); // The name validator will add the prefix back
}
additionalVars = additionalVars || [];
var additionalVarNames = variable.isLocal ? [] : additionalVars;
var validatedText = validate(newName, workspace, additionalVarNames, variable.isCloud);
if (validatedText) {
workspace.renameVariableById(variable.getId(), validatedText);
if (opt_callback) {
opt_callback(newName);
}
} else {
// User canceled prompt without a value.
if (opt_callback) {
opt_callback(null);
}
}
}, modalTitle, varType);
};
/**
* Strip leading and trailing whitespace from the given name, for use with
* user provided name for scalar variables and lists.
* @param {string} name The user-provided name of the variable.
* @return {string} The trimmed name, or whatever falsey value was originally provided.
*/
Blockly.Variables.trimName_ = function(name) {
if (name) {
return goog.string.trim(name);
} else {
// Return whatever was provided
return name;
}
};
/**
* Generate XML string for variable field.
* @param {!Blockly.VariableModel} variableModel The variable model to generate
* an XML string from.
* @param {?string} opt_name The optional name of the field, such as "VARIABLE"
* or "LIST". Defaults to "VARIABLE".
* @return {string} The generated XML.
* @private
*/
Blockly.Variables.generateVariableFieldXml_ = function(variableModel, opt_name) {
// The variable name may be user input, so it may contain characters that need
// to be escaped to create valid XML.
var typeString = variableModel.type;
if (typeString == '') {
typeString = '\'\'';
}
var fieldName = opt_name || 'VARIABLE';
var text = '<field name="' + fieldName + '" id="' + variableModel.getId() +
'" variabletype="' + goog.string.htmlEscape(typeString) +
'">' + goog.string.htmlEscape(variableModel.name) + '</field>';
return text;
};
/**
* Helper function to look up or create a variable on the given workspace.
* If no variable exists, creates and returns it.
* @param {!Blockly.Workspace} workspace The workspace to search for the
* variable. It may be a flyout workspace or main workspace.
* @param {string} id The ID to use to look up or create the variable, or null.
* @param {string=} opt_name The string to use to look up or create the
* variable.
* @param {string=} opt_type The type to use to look up or create the variable.
* @return {!Blockly.VariableModel} The variable corresponding to the given ID
* or name + type combination.
* @package
*/
Blockly.Variables.getOrCreateVariablePackage = function(workspace, id, opt_name,
opt_type) {
var variable = Blockly.Variables.getVariable(workspace, id, opt_name,
opt_type);
if (!variable) {
variable = Blockly.Variables.createVariable_(workspace, id, opt_name,
opt_type);
}
return variable;
};
/**
* Look up a variable on the given workspace.
* Always looks in the main workspace before looking in the flyout workspace.
* Always prefers lookup by ID to lookup by name + type.
* @param {!Blockly.Workspace} workspace The workspace to search for the
* variable. It may be a flyout workspace or main workspace.
* @param {string} id The ID to use to look up the variable, or null.
* @param {string=} opt_name The string to use to look up the variable. Only
* used if lookup by ID fails.
* @param {string=} opt_type The type to use to look up the variable. Only used
* if lookup by ID fails.
* @return {?Blockly.VariableModel} The variable corresponding to the given ID
* or name + type combination, or null if not found.
* @package
*/
Blockly.Variables.getVariable = function(workspace, id, opt_name, opt_type) {
var potentialVariableMap = workspace.getPotentialVariableMap();
// Try to just get the variable, by ID if possible.
if (id) {
// Look in the real variable map before checking the potential variable map.
var variable = workspace.getVariableById(id);
if (!variable && potentialVariableMap) {
variable = potentialVariableMap.getVariableById(id);
}
} else if (opt_name) {
if (opt_type == undefined) {
throw new Error('Tried to look up a variable by name without a type');
}
// Otherwise look up by name and type.
var variable = workspace.getVariable(opt_name, opt_type);
if (!variable && potentialVariableMap) {
variable = potentialVariableMap.getVariable(opt_name, opt_type);
}
}
return variable;
};
/**
* Helper function to create a variable on the given workspace.
* @param {!Blockly.Workspace} workspace The workspace in which to create the
* variable. It may be a flyout workspace or main workspace.
* @param {string} id The ID to use to create the variable, or null.
* @param {string=} opt_name The string to use to create the variable.
* @param {string=} opt_type The type to use to create the variable.
* @return {!Blockly.VariableModel} The variable corresponding to the given ID
* or name + type combination.
* @private
*/
Blockly.Variables.createVariable_ = function(workspace, id, opt_name,
opt_type) {
var potentialVariableMap = workspace.getPotentialVariableMap();
// Variables without names get uniquely named for this workspace.
if (!opt_name) {
var ws = workspace.isFlyout ? workspace.targetWorkspace : workspace;
opt_name = Blockly.Variables.generateUniqueName(ws);
}
// Create a potential variable if in the flyout.
if (potentialVariableMap) {
var variable = potentialVariableMap.createVariable(opt_name, opt_type, id);
} else { // In the main workspace, create a real variable.
var variable = workspace.createVariable(opt_name, opt_type, id);
}
return variable;
};
/**
* Helper function to get the list of variables that have been added to the
* workspace after adding a new block, using the given list of variables that
* were in the workspace before the new block was added.
* @param {!Blockly.Workspace} workspace The workspace to inspect.
* @param {!Array.<!Blockly.VariableModel>} originalVariables The array of
* variables that existed in the workspace before adding the new block.
* @return {!Array.<!Blockly.VariableModel>} The new array of variables that were
* freshly added to the workspace after creating the new block, or [] if no
* new variables were added to the workspace.
* @package
*/
Blockly.Variables.getAddedVariables = function(workspace, originalVariables) {
var allCurrentVariables = workspace.getAllVariables();
var addedVariables = [];
if (originalVariables.length != allCurrentVariables.length) {
for (var i = 0; i < allCurrentVariables.length; i++) {
var variable = allCurrentVariables[i];
// For any variable that is present in allCurrentVariables but not
// present in originalVariables, add the variable to addedVariables.
if (!originalVariables.includes(variable)) {
addedVariables.push(variable);
}
}
}
return addedVariables;
};
| 1 | 9,860 | Thanks for fixing this! I probably didn't test the playground when making changes here for cloud variables. | LLK-scratch-blocks | js |
@@ -39,6 +39,7 @@ class PruneColumns extends AvroSchemaVisitor<Schema> {
private final NameMapping nameMapping;
PruneColumns(Set<Integer> selectedIds, NameMapping nameMapping) {
+ Preconditions.checkNotNull(selectedIds, "Selected field ids cannot be null");
this.selectedIds = selectedIds;
this.nameMapping = nameMapping;
} | 1 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.iceberg.avro;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.avro.JsonProperties;
import org.apache.avro.Schema;
import org.apache.avro.SchemaNormalization;
import org.apache.iceberg.mapping.NameMapping;
import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class PruneColumns extends AvroSchemaVisitor<Schema> {
private static final Logger LOG = LoggerFactory.getLogger(PruneColumns.class);
private final Set<Integer> selectedIds;
private final NameMapping nameMapping;
PruneColumns(Set<Integer> selectedIds, NameMapping nameMapping) {
this.selectedIds = selectedIds;
this.nameMapping = nameMapping;
}
Schema rootSchema(Schema record) {
Schema result = visit(record, this);
if (result != null) {
return result;
}
return copyRecord(record, ImmutableList.of());
}
@Override
public Schema record(Schema record, List<String> names, List<Schema> fields) {
// Then this should access the record's fields by name
List<Schema.Field> filteredFields = Lists.newArrayListWithExpectedSize(fields.size());
boolean hasChange = false;
for (Schema.Field field : record.getFields()) {
Integer fieldId = AvroSchemaUtil.getFieldId(field, nameMapping, fieldNames());
if (fieldId == null) {
// Both the schema and the nameMapping does not have field id. We prune this field.
continue;
}
if (!AvroSchemaUtil.hasFieldId(field)) {
// fieldId was resolved from nameMapping, we updated hasChange
// flag to make sure a new field is created with the field id
hasChange = true;
}
if (isOptionSchemaWithNonNullFirstOption(field.schema())) {
// if the field has an optional schema where the first option is not NULL,
// we update hasChange flag to make sure we reorder the schema and make the
// NULL option as the first
hasChange = true;
}
Schema fieldSchema = fields.get(field.pos());
// All primitives are selected by selecting the field, but map and list
// types can be selected by projecting the keys, values, or elements.
// This creates two conditions where the field should be selected: if the
// id is selected or if the result of the field is non-null. The only
// case where the converted field is non-null is when a map or list is
// selected by lower IDs.
if (selectedIds.contains(fieldId)) {
filteredFields.add(copyField(field, field.schema(), fieldId));
} else if (fieldSchema != null) {
hasChange = true;
filteredFields.add(copyField(field, fieldSchema, fieldId));
}
}
if (hasChange) {
return copyRecord(record, filteredFields);
} else if (filteredFields.size() == record.getFields().size()) {
return record;
} else if (!filteredFields.isEmpty()) {
return copyRecord(record, filteredFields);
}
return null;
}
@Override
public Schema union(Schema union, List<Schema> options) {
Preconditions.checkState(AvroSchemaUtil.isOptionSchema(union),
"Invalid schema: non-option unions are not supported: %s", union);
// only unions with null are allowed, and a null schema results in null
Schema pruned = null;
if (options.get(0) != null) {
pruned = options.get(0);
} else if (options.get(1) != null) {
pruned = options.get(1);
}
if (pruned != null) {
if (pruned != AvroSchemaUtil.fromOption(union)) {
return AvroSchemaUtil.toOption(pruned);
}
return union;
}
return null;
}
@Override
@SuppressWarnings("checkstyle:CyclomaticComplexity")
public Schema array(Schema array, Schema element) {
if (array.getLogicalType() instanceof LogicalMap) {
Schema keyValue = array.getElementType();
Integer keyId = AvroSchemaUtil.getFieldId(keyValue.getField("key"), nameMapping, fieldNames());
Integer valueId = AvroSchemaUtil.getFieldId(keyValue.getField("value"), nameMapping, fieldNames());
if (keyId == null || valueId == null) {
if (keyId != null || valueId != null) {
LOG.warn("Map schema {} should have both key and value ids set or both unset", array);
}
return null;
}
// if either key or value is selected, the whole map must be projected
if (selectedIds.contains(keyId) || selectedIds.contains(valueId)) {
return complexMapWithIds(array, keyId, valueId);
} else if (element != null) {
Schema.Field keyProjectionField = element.getField("key");
Schema valueProjection = element.getField("value").schema();
// it is possible that key is not selected, and
// key schemas can be different if new field ids were assigned to them
if (keyProjectionField != null && keyValue.getField("key").schema() != keyProjectionField.schema()) {
Preconditions.checkState(
SchemaNormalization.parsingFingerprint64(keyValue.getField("key").schema()) ==
SchemaNormalization.parsingFingerprint64(keyProjectionField.schema()),
"Map keys should not be projected");
return AvroSchemaUtil.createMap(keyId, keyProjectionField.schema(), valueId, valueProjection);
} else if (keyValue.getField("value").schema() != valueProjection) {
return AvroSchemaUtil.createMap(keyId, keyValue.getField("key").schema(), valueId, valueProjection);
} else {
return complexMapWithIds(array, keyId, valueId);
}
}
} else {
Integer elementId = AvroSchemaUtil.getElementId(array, nameMapping, fieldNames());
if (elementId == null) {
return null;
}
if (selectedIds.contains(elementId)) {
return arrayWithId(array, elementId);
} else if (element != null) {
if (element != array.getElementType()) {
// the element must be a projection
return arrayWithId(Schema.createArray(element), elementId);
}
return arrayWithId(array, elementId);
}
}
return null;
}
@Override
public Schema map(Schema map, Schema value) {
Integer keyId = AvroSchemaUtil.getKeyId(map, nameMapping, fieldNames());
Integer valueId = AvroSchemaUtil.getValueId(map, nameMapping, fieldNames());
if (keyId == null || valueId == null) {
if (keyId != null || valueId != null) {
LOG.warn("Map schema {} should have both key and value ids set or both unset", map);
}
return null;
}
// if either key or value is selected, the whole map must be projected
if (selectedIds.contains(keyId) || selectedIds.contains(valueId)) {
// Assign ids. Ids may not always be present in the schema,
// e.g if we are reading data not written by Iceberg writers
return mapWithIds(map, keyId, valueId);
} else if (value != null) {
if (value != map.getValueType()) {
// the value must be a projection
return mapWithIds(Schema.createMap(value), keyId, valueId);
}
return map;
}
return null;
}
private Schema arrayWithId(Schema array, Integer elementId) {
if (!AvroSchemaUtil.hasProperty(array, AvroSchemaUtil.ELEMENT_ID_PROP)) {
Schema result = Schema.createArray(array.getElementType());
result.addProp(AvroSchemaUtil.ELEMENT_ID_PROP, elementId);
return result;
}
return array;
}
private Schema complexMapWithIds(Schema map, Integer keyId, Integer valueId) {
Schema keyValue = map.getElementType();
if (!AvroSchemaUtil.hasFieldId(keyValue.getField("key")) ||
!AvroSchemaUtil.hasFieldId(keyValue.getField("value"))) {
return AvroSchemaUtil.createMap(
keyId, keyValue.getField("key").schema(),
valueId, keyValue.getField("value").schema());
}
return map;
}
private Schema mapWithIds(Schema map, Integer keyId, Integer valueId) {
if (!AvroSchemaUtil.hasProperty(map, AvroSchemaUtil.KEY_ID_PROP) ||
!AvroSchemaUtil.hasProperty(map, AvroSchemaUtil.VALUE_ID_PROP)) {
Schema result = Schema.createMap(map.getValueType());
result.addProp(AvroSchemaUtil.KEY_ID_PROP, keyId);
result.addProp(AvroSchemaUtil.VALUE_ID_PROP, valueId);
return result;
}
return map;
}
@Override
public Schema primitive(Schema primitive) {
// primitives are not selected directly
return null;
}
private static Schema copyRecord(Schema record, List<Schema.Field> newFields) {
Schema copy = Schema.createRecord(record.getName(),
record.getDoc(), record.getNamespace(), record.isError(), newFields);
for (Map.Entry<String, Object> prop : record.getObjectProps().entrySet()) {
copy.addProp(prop.getKey(), prop.getValue());
}
return copy;
}
private static Schema.Field copyField(Schema.Field field, Schema newSchema, Integer fieldId) {
Schema newSchemaReordered;
// if the newSchema is an optional schema, make sure the NULL option is always the first
if (isOptionSchemaWithNonNullFirstOption(newSchema)) {
newSchemaReordered = AvroSchemaUtil.toOption(AvroSchemaUtil.fromOption(newSchema));
} else {
newSchemaReordered = newSchema;
}
// do not copy over default values as the file is expected to have values for fields already in the file schema
Schema.Field copy = new Schema.Field(field.name(),
newSchemaReordered, field.doc(),
AvroSchemaUtil.isOptionSchema(newSchemaReordered) ? JsonProperties.NULL_VALUE : null, field.order());
for (Map.Entry<String, Object> prop : field.getObjectProps().entrySet()) {
copy.addProp(prop.getKey(), prop.getValue());
}
if (AvroSchemaUtil.hasFieldId(field)) {
int existingFieldId = AvroSchemaUtil.getFieldId(field);
Preconditions.checkArgument(existingFieldId == fieldId,
"Existing field does match with that fetched from name mapping");
} else {
// field may not have a fieldId if the fieldId was fetched from nameMapping
copy.addProp(AvroSchemaUtil.FIELD_ID_PROP, fieldId);
}
return copy;
}
private static boolean isOptionSchemaWithNonNullFirstOption(Schema schema) {
return AvroSchemaUtil.isOptionSchema(schema) && schema.getTypes().get(0).getType() != Schema.Type.NULL;
}
}
| 1 | 24,956 | I will also check if `nameMapping` needs a precondition null check. | apache-iceberg | java |
@@ -60,9 +60,8 @@ public class Files {
if (!file.getParentFile().isDirectory() && !file.getParentFile().mkdirs()) {
throw new RuntimeIOException(
- String.format(
"Failed to create the file's directory at %s.",
- file.getParentFile().getAbsolutePath()));
+ file.getParentFile().getAbsolutePath());
}
try { | 1 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.iceberg;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Paths;
import org.apache.iceberg.exceptions.AlreadyExistsException;
import org.apache.iceberg.exceptions.NotFoundException;
import org.apache.iceberg.exceptions.RuntimeIOException;
import org.apache.iceberg.io.InputFile;
import org.apache.iceberg.io.OutputFile;
import org.apache.iceberg.io.PositionOutputStream;
import org.apache.iceberg.io.SeekableInputStream;
public class Files {
private Files() {
}
public static OutputFile localOutput(File file) {
return new LocalOutputFile(file);
}
public static OutputFile localOutput(String file) {
return localOutput(Paths.get(file).toAbsolutePath().toFile());
}
private static class LocalOutputFile implements OutputFile {
private final File file;
private LocalOutputFile(File file) {
this.file = file;
}
@Override
public PositionOutputStream create() {
if (file.exists()) {
throw new AlreadyExistsException("File already exists: %s", file);
}
if (!file.getParentFile().isDirectory() && !file.getParentFile().mkdirs()) {
throw new RuntimeIOException(
String.format(
"Failed to create the file's directory at %s.",
file.getParentFile().getAbsolutePath()));
}
try {
return new PositionFileOutputStream(file, new RandomAccessFile(file, "rw"));
} catch (FileNotFoundException e) {
throw new NotFoundException(e, "Failed to create file: %s", file);
}
}
@Override
public PositionOutputStream createOrOverwrite() {
if (file.exists()) {
if (!file.delete()) {
throw new RuntimeIOException("Failed to delete: " + file);
}
}
return create();
}
@Override
public String location() {
return file.toString();
}
@Override
public InputFile toInputFile() {
return localInput(file);
}
@Override
public String toString() {
return location();
}
}
public static InputFile localInput(File file) {
return new LocalInputFile(file);
}
public static InputFile localInput(String file) {
if (file.startsWith("file:")) {
return localInput(new File(file.replaceFirst("file:", "")));
}
return localInput(new File(file));
}
private static class LocalInputFile implements InputFile {
private final File file;
private LocalInputFile(File file) {
this.file = file;
}
@Override
public long getLength() {
return file.length();
}
@Override
public SeekableInputStream newStream() {
try {
return new SeekableFileInputStream(new RandomAccessFile(file, "r"));
} catch (FileNotFoundException e) {
throw new NotFoundException(e, "Failed to read file: %s", file);
}
}
@Override
public String location() {
return file.toString();
}
@Override
public boolean exists() {
return file.exists();
}
@Override
public String toString() {
return location();
}
}
private static class SeekableFileInputStream extends SeekableInputStream {
private final RandomAccessFile stream;
private SeekableFileInputStream(RandomAccessFile stream) {
this.stream = stream;
}
@Override
public long getPos() throws IOException {
return stream.getFilePointer();
}
@Override
public void seek(long newPos) throws IOException {
stream.seek(newPos);
}
@Override
public int read() throws IOException {
return stream.read();
}
@Override
public int read(byte[] b) throws IOException {
return stream.read(b);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return stream.read(b, off, len);
}
@Override
public long skip(long n) throws IOException {
if (n > Integer.MAX_VALUE) {
return stream.skipBytes(Integer.MAX_VALUE);
} else {
return stream.skipBytes((int) n);
}
}
@Override
public void close() throws IOException {
stream.close();
}
}
private static class PositionFileOutputStream extends PositionOutputStream {
private final File file;
private final RandomAccessFile stream;
private boolean isClosed = false;
private PositionFileOutputStream(File file, RandomAccessFile stream) {
this.file = file;
this.stream = stream;
}
@Override
public long getPos() throws IOException {
if (isClosed) {
return file.length();
}
return stream.getFilePointer();
}
@Override
public void write(byte[] b) throws IOException {
stream.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
stream.write(b, off, len);
}
@Override
public void write(int b) throws IOException {
stream.write(b);
}
@Override
public void close() throws IOException {
stream.close();
this.isClosed = true;
}
}
}
| 1 | 24,303 | Since RuntimeIOException is deprecated and you are touching this code, why not replace it? | apache-iceberg | java |
@@ -59,7 +59,9 @@ class ClusterParamsTest(TestCaseBase):
self.assertGreaterEqual(encodersDict['c1']['resolution'], 0.001,
"Resolution is too low")
-
+ # Ensure incorrect tmImplementation throws exception
+ with self.assertRaises(ValueError):
+ getScalarMetricWithTimeOfDayAnomalyParams([0], tmImplementation="")
if __name__ == '__main__':
unittest.main() | 1 | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""Unit tests for model selection via cluster params."""
import unittest
from nupic.support.unittesthelpers.testcasebase import TestCaseBase
from nupic.frameworks.opf.modelfactory import ModelFactory
from nupic.frameworks.opf.clamodel import CLAModel
from nupic.frameworks.opf.common_models.cluster_params import (
getScalarMetricWithTimeOfDayAnomalyParams)
class ClusterParamsTest(TestCaseBase):
def testModelParams(self):
"""
Test that clusterParams loads returns a valid dict that can be instantiated
as a CLAModel.
"""
params = getScalarMetricWithTimeOfDayAnomalyParams([0],
minVal=23.42,
maxVal=23.420001)
encodersDict= (
params['modelConfig']['modelParams']['sensorParams']['encoders'])
model = ModelFactory.create(modelConfig=params['modelConfig'])
self.assertIsInstance(model,
CLAModel,
"JSON returned cannot be used to create a model")
# Ensure we have a time of day field
self.assertIsNotNone(encodersDict['c0_timeOfDay'])
# Ensure resolution doesn't get too low
if encodersDict['c1']['type'] == 'RandomDistributedScalarEncoder':
self.assertGreaterEqual(encodersDict['c1']['resolution'], 0.001,
"Resolution is too low")
if __name__ == '__main__':
unittest.main()
| 1 | 20,920 | You should also have a test that calls it with tm_cpp and make sure it returns the correct JSON file. | numenta-nupic | py |
@@ -168,17 +168,12 @@ define(["jQuery", "globalize", "scripts/taskbutton", "dom", "libraryMenu", "layo
}), menuItems.push({
name: "Xml TV",
id: "xmltv"
- }), menuItems.push({
- name: globalize.translate("ButtonOther"),
- id: "other"
}), require(["actionsheet"], function(actionsheet) {
actionsheet.show({
items: menuItems,
positionTo: button,
callback: function(id) {
- "other" == id ? Dashboard.alert({
- message: globalize.translate("ForAdditionalLiveTvOptions")
- }) : Dashboard.navigate(getProviderConfigurationUrl(id))
+ Dashboard.navigate(getProviderConfigurationUrl(id))
}
})
}) | 1 | define(["jQuery", "globalize", "scripts/taskbutton", "dom", "libraryMenu", "layoutManager", "loading", "listViewStyle", "flexStyles", "emby-itemscontainer", "cardStyle", "material-icons", "emby-button"], function($, globalize, taskButton, dom, libraryMenu, layoutManager, loading) {
"use strict";
function getDeviceHtml(device) {
var padderClass, html = "",
cssClass = "card scalableCard",
cardBoxCssClass = "cardBox visualCardBox";
return cssClass += " backdropCard backdropCard-scalable", padderClass = "cardPadder-backdrop", layoutManager.tv && (cssClass += " card-focusscale", cardBoxCssClass += " cardBox-focustransform"), cardBoxCssClass += " card-focuscontent", html += '<div type="button" class="' + cssClass + '" data-id="' + device.Id + '">', html += '<div class="' + cardBoxCssClass + '">', html += '<div class="cardScalable visualCardBox-cardScalable">', html += '<div class="' + padderClass + '"></div>', html += '<div class="cardContent searchImage">', html += '<div class="cardImageContainer coveredImage"><i class="cardImageIcon md-icon">dvr</i></div>', html += "</div>", html += "</div>", html += '<div class="cardFooter visualCardBox-cardFooter">', html += '<button is="paper-icon-button-light" class="itemAction btnCardOptions autoSize" data-action="menu"><i class="md-icon">more_horiz</i></button>', html += '<div class="cardText">' + (device.FriendlyName || getTunerName(device.Type)) + "</div>", html += '<div class="cardText cardText-secondary">', html += device.Url || " ", html += "</div>", html += "</div>", html += "</div>", html += "</div>"
}
function renderDevices(page, devices) {
var html = devices.map(getDeviceHtml).join("");
page.querySelector(".devicesList").innerHTML = html
}
function deleteDevice(page, id) {
var message = globalize.translate("MessageConfirmDeleteTunerDevice");
require(["confirm"], function(confirm) {
confirm(message, globalize.translate("HeaderDeleteDevice")).then(function() {
loading.show(), ApiClient.ajax({
type: "DELETE",
url: ApiClient.getUrl("LiveTv/TunerHosts", {
Id: id
})
}).then(function() {
reload(page)
})
})
})
}
function reload(page) {
loading.show(), ApiClient.getNamedConfiguration("livetv").then(function(config) {
renderDevices(page, config.TunerHosts), renderProviders(page, config.ListingProviders)
}), loading.hide()
}
function submitAddDeviceForm(page) {
page.querySelector(".dlgAddDevice").close(), loading.show(), ApiClient.ajax({
type: "POST",
url: ApiClient.getUrl("LiveTv/TunerHosts"),
data: JSON.stringify({
Type: $("#selectTunerDeviceType", page).val(),
Url: $("#txtDevicePath", page).val()
}),
contentType: "application/json"
}).then(function() {
reload(page)
}, function() {
Dashboard.alert({
message: globalize.translate("ErrorAddingTunerDevice")
})
})
}
function renderProviders(page, providers) {
var html = "";
if (providers.length) {
html += '<div class="paperList">';
for (var i = 0, length = providers.length; i < length; i++) {
var provider = providers[i];
html += '<div class="listItem">', html += '<i class="listItemIcon md-icon">dvr</i>', html += '<div class="listItemBody two-line">', html += '<a is="emby-linkbutton" style="display:block;padding:0;margin:0;text-align:left;" class="clearLink" href="' + getProviderConfigurationUrl(provider.Type) + "&id=" + provider.Id + '">', html += '<h3 class="listItemBodyText">', html += getProviderName(provider.Type), html += "</h3>", html += '<div class="listItemBodyText secondary">', html += provider.Path || provider.ListingsId || "", html += "</div>", html += "</a>", html += "</div>", html += '<button type="button" is="paper-icon-button-light" class="btnOptions" data-id="' + provider.Id + '"><i class="md-icon listItemAside">more_horiz</i></button>', html += "</div>"
}
html += "</div>"
}
var elem = $(".providerList", page).html(html);
$(".btnOptions", elem).on("click", function() {
var id = this.getAttribute("data-id");
showProviderOptions(page, id, this)
})
}
function showProviderOptions(page, providerId, button) {
var items = [];
items.push({
name: globalize.translate("ButtonDelete"),
id: "delete"
}), items.push({
name: globalize.translate("MapChannels"),
id: "map"
}), require(["actionsheet"], function(actionsheet) {
actionsheet.show({
items: items,
positionTo: button
}).then(function(id) {
switch (id) {
case "delete":
deleteProvider(page, providerId);
break;
case "map":
mapChannels(page, providerId)
}
})
})
}
function mapChannels(page, providerId) {
require(["components/channelmapper/channelmapper"], function(channelmapper) {
new channelmapper({
serverId: ApiClient.serverInfo().Id,
providerId: providerId
}).show()
})
}
function deleteProvider(page, id) {
var message = globalize.translate("MessageConfirmDeleteGuideProvider");
require(["confirm"], function(confirm) {
confirm(message, globalize.translate("HeaderDeleteProvider")).then(function() {
loading.show(), ApiClient.ajax({
type: "DELETE",
url: ApiClient.getUrl("LiveTv/ListingProviders", {
Id: id
})
}).then(function() {
reload(page)
}, function() {
reload(page)
})
})
})
}
function getTunerName(providerId) {
switch (providerId = providerId.toLowerCase()) {
case "m3u":
return "M3U";
case "hdhomerun":
return "HDHomerun";
case "hauppauge":
return "Hauppauge";
case "satip":
return "DVB";
default:
return "Unknown"
}
}
function getProviderName(providerId) {
switch (providerId = providerId.toLowerCase()) {
case "schedulesdirect":
return "Schedules Direct";
case "xmltv":
return "Xml TV";
case "emby":
return "Emby Guide";
default:
return "Unknown"
}
}
function getProviderConfigurationUrl(providerId) {
switch (providerId = providerId.toLowerCase()) {
case "xmltv":
return "livetvguideprovider.html?type=xmltv";
case "schedulesdirect":
return "livetvguideprovider.html?type=schedulesdirect";
case "emby":
return "livetvguideprovider.html?type=emby"
}
}
function addProvider(button) {
var menuItems = [];
menuItems.push({
name: "Schedules Direct",
id: "SchedulesDirect"
}), menuItems.push({
name: "Xml TV",
id: "xmltv"
}), menuItems.push({
name: globalize.translate("ButtonOther"),
id: "other"
}), require(["actionsheet"], function(actionsheet) {
actionsheet.show({
items: menuItems,
positionTo: button,
callback: function(id) {
"other" == id ? Dashboard.alert({
message: globalize.translate("ForAdditionalLiveTvOptions")
}) : Dashboard.navigate(getProviderConfigurationUrl(id))
}
})
})
}
function addDevice(button) {
Dashboard.navigate("livetvtuner.html")
}
function showDeviceMenu(button, tunerDeviceId) {
var items = [];
items.push({
name: globalize.translate("ButtonDelete"),
id: "delete"
}), items.push({
name: globalize.translate("ButtonEdit"),
id: "edit"
}), require(["actionsheet"], function(actionsheet) {
actionsheet.show({
items: items,
positionTo: button
}).then(function(id) {
switch (id) {
case "delete":
deleteDevice(dom.parentWithClass(button, "page"), tunerDeviceId);
break;
case "edit":
Dashboard.navigate("livetvtuner.html?id=" + tunerDeviceId)
}
})
})
}
function onDevicesListClick(e) {
var card = dom.parentWithClass(e.target, "card");
if (card) {
var id = card.getAttribute("data-id"),
btnCardOptions = dom.parentWithClass(e.target, "btnCardOptions");
btnCardOptions ? showDeviceMenu(btnCardOptions, id) : Dashboard.navigate("livetvtuner.html?id=" + id)
}
}
$(document).on("pageinit", "#liveTvStatusPage", function() {
var page = this;
$(".btnAddDevice", page).on("click", function() {
addDevice(this)
}), $(".formAddDevice", page).on("submit", function() {
return submitAddDeviceForm(page), !1
}), $(".btnAddProvider", page).on("click", function() {
addProvider(this)
}), page.querySelector(".devicesList").addEventListener("click", onDevicesListClick)
}).on("pageshow", "#liveTvStatusPage", function() {
var page = this;
reload(page), taskButton({
mode: "on",
progressElem: page.querySelector(".refreshGuideProgress"),
taskKey: "RefreshGuide",
button: page.querySelector(".btnRefresh")
})
}).on("pagehide", "#liveTvStatusPage", function() {
var page = this;
taskButton({
mode: "off",
progressElem: page.querySelector(".refreshGuideProgress"),
taskKey: "RefreshGuide",
button: page.querySelector(".btnRefresh")
})
})
}); | 1 | 11,663 | One more minor change, the string `ForAdditionalLiveTvOptions` is probably also unused. | jellyfin-jellyfin-web | js |
@@ -107,7 +107,7 @@ bool RowReaderWrapper::reset(meta::SchemaProviderIf const* schema,
currReader_ = &readerV2_;
return true;
} else {
- LOG(ERROR) << "Unsupported row reader version " << readerVer;
+ LOG(WARNING) << "Unsupported row reader version " << readerVer;
currReader_ = nullptr;
return false;
} | 1 | /* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License.
*/
#include "codec/RowReaderWrapper.h"
namespace nebula {
// static
RowReaderWrapper RowReaderWrapper::getTagPropReader(meta::SchemaManager* schemaMan,
GraphSpaceID space,
TagID tag,
folly::StringPiece row) {
SchemaVer schemaVer;
int32_t readerVer;
RowReaderWrapper::getVersions(row, schemaVer, readerVer);
if (schemaVer >= 0) {
auto schema = schemaMan->getTagSchema(space, tag, schemaVer);
if (schema == nullptr) {
return RowReaderWrapper();
}
return RowReaderWrapper(schema.get(), row, readerVer);
} else {
LOG(WARNING) << "Invalid schema version in the row data!";
return RowReaderWrapper();
}
}
// static
RowReaderWrapper RowReaderWrapper::getEdgePropReader(meta::SchemaManager* schemaMan,
GraphSpaceID space,
EdgeType edge,
folly::StringPiece row) {
if (schemaMan == nullptr) {
LOG(ERROR) << "schemaMan should not be nullptr!";
return RowReaderWrapper();
}
SchemaVer schemaVer;
int32_t readerVer;
RowReaderWrapper::getVersions(row, schemaVer, readerVer);
if (schemaVer >= 0) {
auto schema = schemaMan->getEdgeSchema(space, edge, schemaVer);
if (schema == nullptr) {
return RowReaderWrapper();
}
return RowReaderWrapper(schema.get(), row, readerVer);
} else {
LOG(WARNING) << "Invalid schema version in the row data!";
return RowReaderWrapper();
}
}
// static
RowReaderWrapper RowReaderWrapper::getRowReader(const meta::SchemaProviderIf* schema,
folly::StringPiece row) {
SchemaVer schemaVer;
int32_t readerVer;
RowReaderWrapper::getVersions(row, schemaVer, readerVer);
if (schemaVer != schema->getVersion()) {
return RowReaderWrapper();
}
return RowReaderWrapper(schema, row, readerVer);
}
// static
RowReaderWrapper RowReaderWrapper::getRowReader(
const std::vector<std::shared_ptr<const meta::NebulaSchemaProvider>>& schemas,
folly::StringPiece row) {
SchemaVer schemaVer;
int32_t readerVer;
RowReaderWrapper::getVersions(row, schemaVer, readerVer);
if (static_cast<size_t>(schemaVer) >= schemas.size() ||
schemaVer != schemas[schemaVer]->getVersion()) {
return RowReaderWrapper();
}
return RowReaderWrapper(schemas[schemaVer].get(), row, readerVer);
}
RowReaderWrapper::RowReaderWrapper(const meta::SchemaProviderIf* schema,
const folly::StringPiece& row,
int32_t& readerVer)
: readerVer_(readerVer) {
CHECK_NOTNULL(schema);
if (readerVer_ == 1) {
readerV1_.resetImpl(schema, row);
currReader_ = &readerV1_;
} else if (readerVer_ == 2) {
readerV2_.resetImpl(schema, row);
currReader_ = &readerV2_;
} else {
LOG(FATAL) << "Should not reach here";
}
}
bool RowReaderWrapper::reset(meta::SchemaProviderIf const* schema,
folly::StringPiece row,
int32_t readerVer) noexcept {
CHECK_NOTNULL(schema);
readerVer_ = readerVer;
if (readerVer_ == 1) {
readerV1_.resetImpl(schema, row);
currReader_ = &readerV1_;
return true;
} else if (readerVer_ == 2) {
readerV2_.resetImpl(schema, row);
currReader_ = &readerV2_;
return true;
} else {
LOG(ERROR) << "Unsupported row reader version " << readerVer;
currReader_ = nullptr;
return false;
}
}
bool RowReaderWrapper::reset(meta::SchemaProviderIf const* schema,
folly::StringPiece row) noexcept {
currReader_ = nullptr;
if (schema == nullptr) {
return false;
}
SchemaVer schemaVer;
int32_t readerVer;
RowReaderWrapper::getVersions(row, schemaVer, readerVer);
if (schemaVer != schema->getVersion()) {
return false;
}
return reset(schema, row, readerVer);
}
bool RowReaderWrapper::reset(
const std::vector<std::shared_ptr<const meta::NebulaSchemaProvider>>& schemas,
folly::StringPiece row) noexcept {
currReader_ = nullptr;
SchemaVer schemaVer;
int32_t readerVer;
RowReaderWrapper::getVersions(row, schemaVer, readerVer);
if (static_cast<size_t>(schemaVer) >= schemas.size()) {
return false;
}
// the schema is stored from oldest to newest, so just use version as idx
if (schemaVer != schemas[schemaVer]->getVersion()) {
return false;
}
return reset(schemas[schemaVer].get(), row, readerVer);
}
// static
void RowReaderWrapper::getVersions(const folly::StringPiece& row,
SchemaVer& schemaVer,
int32_t& readerVer) {
size_t index = 0;
if (row.empty()) {
LOG(WARNING) << "Row data is empty, so there is no version info";
schemaVer = -1;
readerVer = 2;
return;
}
readerVer = ((row[index] & 0x18) >> 3) + 1;
size_t verBytes = 0;
if (readerVer == 1) {
// The first three bits indicate the number of bytes for the
// schema version. If the number is zero, no schema version
// presents
verBytes = row[index++] >> 5;
} else if (readerVer == 2) {
// The last three bits indicate the number of bytes for the
// schema version. If the number is zero, no schema version
// presents
verBytes = row[index++] & 0x07;
} else {
LOG(ERROR) << "Invalid reader version: " << readerVer;
schemaVer = -1;
return;
}
schemaVer = 0;
if (verBytes > 0) {
if (verBytes + 1 > row.size()) {
// Data is too short
LOG(ERROR) << "Row data is too short: " << toHexStr(row);
schemaVer = -1;
return;
}
// Schema Version is stored in Little Endian
memcpy(reinterpret_cast<void*>(&schemaVer), &row[index], verBytes);
}
return;
}
} // namespace nebula
| 1 | 33,205 | How to distinguish between warning and error? | vesoft-inc-nebula | cpp |
@@ -171,6 +171,10 @@ def doPreGainFocus(obj,sleepMode=False):
else:
newForeground=obj
api.setForegroundObject(newForeground)
+ import UIAHandler
+ if UIAHandler.isUIAAvailable:
+ # Notify UIAHandler of the new foreground so that it can deregister old events and register new ones
+ UIAHandler.handler.onForegroundChange(newForeground.windowHandle)
executeEvent('foreground',newForeground)
if sleepMode: return True
#Fire focus entered events for all new ancestors of the focus if this is a gainFocus event | 1 | #eventHandler.py
#A part of NonVisual Desktop Access (NVDA)
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
#Copyright (C) 2007-2017 NV Access Limited, Babbage B.V.
import threading
import queueHandler
import api
import speech
import appModuleHandler
import treeInterceptorHandler
import globalVars
import controlTypes
from logHandler import log
import globalPluginHandler
import config
import winUser
import extensionPoints
#Some dicts to store event counts by name and or obj
_pendingEventCountsByName={}
_pendingEventCountsByObj={}
_pendingEventCountsByNameAndObj={}
# Needed to ensure updates are atomic, as these might be updated from multiple threads simultaneously.
_pendingEventCountsLock=threading.RLock()
#: the last object queued for a gainFocus event. Useful for code running outside NVDA's core queue
lastQueuedFocusObject=None
def queueEvent(eventName,obj,**kwargs):
"""Queues an NVDA event to be executed.
@param eventName: the name of the event type (e.g. 'gainFocus', 'nameChange')
@type eventName: string
"""
global lastQueuedFocusObject
if eventName=="gainFocus":
lastQueuedFocusObject=obj
with _pendingEventCountsLock:
_pendingEventCountsByName[eventName]=_pendingEventCountsByName.get(eventName,0)+1
_pendingEventCountsByObj[obj]=_pendingEventCountsByObj.get(obj,0)+1
_pendingEventCountsByNameAndObj[(eventName,obj)]=_pendingEventCountsByNameAndObj.get((eventName,obj),0)+1
queueHandler.queueFunction(queueHandler.eventQueue,_queueEventCallback,eventName,obj,kwargs)
def _queueEventCallback(eventName,obj,kwargs):
with _pendingEventCountsLock:
curCount=_pendingEventCountsByName.get(eventName,0)
if curCount>1:
_pendingEventCountsByName[eventName]=(curCount-1)
elif curCount==1:
del _pendingEventCountsByName[eventName]
curCount=_pendingEventCountsByObj.get(obj,0)
if curCount>1:
_pendingEventCountsByObj[obj]=(curCount-1)
elif curCount==1:
del _pendingEventCountsByObj[obj]
curCount=_pendingEventCountsByNameAndObj.get((eventName,obj),0)
if curCount>1:
_pendingEventCountsByNameAndObj[(eventName,obj)]=(curCount-1)
elif curCount==1:
del _pendingEventCountsByNameAndObj[(eventName,obj)]
executeEvent(eventName,obj,**kwargs)
def isPendingEvents(eventName=None,obj=None):
"""Are there currently any events queued?
@param eventName: an optional name of an event type. If given then only if there are events of this type queued will it return True.
@type eventName: string
@param obj: the NVDAObject the event is for
@type obj: L{NVDAObjects.NVDAObject}
@returns: True if there are events queued, False otherwise.
@rtype: boolean
"""
if not eventName and not obj:
return bool(len(_pendingEventCountsByName))
elif not eventName and obj:
return obj in _pendingEventCountsByObj
elif eventName and not obj:
return eventName in _pendingEventCountsByName
elif eventName and obj:
return (eventName,obj) in _pendingEventCountsByNameAndObj
class _EventExecuter(object):
"""Facilitates execution of a chain of event functions.
L{gen} generates the event functions and positional arguments.
L{next} calls the next function in the chain.
"""
def __init__(self, eventName, obj, kwargs):
self.kwargs = kwargs
self._gen = self.gen(eventName, obj)
try:
self.next()
except StopIteration:
pass
del self._gen
def next(self):
func, args = next(self._gen)
try:
return func(*args, **self.kwargs)
except TypeError:
log.warning("Could not execute function {func} defined in {module} module due to unsupported kwargs: {kwargs}".format(
func=func.__name__,
module=func.__module__ or "unknown",
kwargs=self.kwargs
), exc_info=True)
return extensionPoints.callWithSupportedKwargs(func, *args, **self.kwargs)
def gen(self, eventName, obj):
funcName = "event_%s" % eventName
# Global plugin level.
for plugin in globalPluginHandler.runningPlugins:
func = getattr(plugin, funcName, None)
if func:
yield func, (obj, self.next)
# App module level.
app = obj.appModule
if app:
func = getattr(app, funcName, None)
if func:
yield func, (obj, self.next)
# Tree interceptor level.
treeInterceptor = obj.treeInterceptor
if treeInterceptor:
func = getattr(treeInterceptor, funcName, None)
if func and (getattr(func,'ignoreIsReady',False) or treeInterceptor.isReady):
yield func, (obj, self.next)
# NVDAObject level.
func = getattr(obj, funcName, None)
if func:
yield func, ()
def executeEvent(eventName,obj,**kwargs):
"""Executes an NVDA event.
@param eventName: the name of the event type (e.g. 'gainFocus', 'nameChange')
@type eventName: string
@param obj: the object the event is for
@type obj: L{NVDAObjects.NVDAObject}
@param kwargs: Additional event parameters as keyword arguments.
"""
try:
# Allow NVDAObjects to redirect focus events to another object of their choosing.
if eventName=="gainFocus" and obj.focusRedirect:
obj=obj.focusRedirect
sleepMode=obj.sleepMode
if eventName=="gainFocus" and not doPreGainFocus(obj,sleepMode=sleepMode):
return
elif not sleepMode and eventName=="documentLoadComplete" and not doPreDocumentLoadComplete(obj):
return
elif not sleepMode:
_EventExecuter(eventName,obj,kwargs)
except:
log.exception("error executing event: %s on %s with extra args of %s"%(eventName,obj,kwargs))
def doPreGainFocus(obj,sleepMode=False):
oldForeground=api.getForegroundObject()
oldFocus=api.getFocusObject()
oldTreeInterceptor=oldFocus.treeInterceptor if oldFocus else None
api.setFocusObject(obj)
if globalVars.focusDifferenceLevel<=1:
newForeground=api.getDesktopObject().objectInForeground()
if not newForeground:
log.debugWarning("Can not get real foreground, resorting to focus ancestors")
ancestors=api.getFocusAncestors()
if len(ancestors)>1:
newForeground=ancestors[1]
else:
newForeground=obj
api.setForegroundObject(newForeground)
executeEvent('foreground',newForeground)
if sleepMode: return True
#Fire focus entered events for all new ancestors of the focus if this is a gainFocus event
for parent in globalVars.focusAncestors[globalVars.focusDifferenceLevel:]:
executeEvent("focusEntered",parent)
if obj.treeInterceptor is not oldTreeInterceptor:
if hasattr(oldTreeInterceptor,"event_treeInterceptor_loseFocus"):
oldTreeInterceptor.event_treeInterceptor_loseFocus()
if obj.treeInterceptor and obj.treeInterceptor.isReady and hasattr(obj.treeInterceptor,"event_treeInterceptor_gainFocus"):
obj.treeInterceptor.event_treeInterceptor_gainFocus()
return True
def doPreDocumentLoadComplete(obj):
focusObject=api.getFocusObject()
if (not obj.treeInterceptor or not obj.treeInterceptor.isAlive or obj.treeInterceptor.shouldPrepare) and (obj==focusObject or obj in api.getFocusAncestors()):
ti=treeInterceptorHandler.update(obj)
if ti:
obj.treeInterceptor=ti
#Focus may be in this new treeInterceptor, so force focus to look up its treeInterceptor
focusObject.treeInterceptor=treeInterceptorHandler.getTreeInterceptor(focusObject)
return True
#: set of (eventName, processId, windowClassName) of events to accept.
_acceptEvents = set()
#: Maps process IDs to sets of events so they can be cleaned up when the process exits.
_acceptEventsByProcess = {}
def requestEvents(eventName=None, processId=None, windowClassName=None):
"""Request that particular events be accepted from a platform API.
Normally, L{shouldAcceptEvent} rejects certain events, including
most show events, events indicating changes in background processes, etc.
This function allows plugins to override this for specific cases;
e.g. to receive show events from a specific control or
to receive certain events even when in the background.
Note that NVDA may block some events at a lower level and doesn't listen for some event types at all.
In these cases, you will not be able to override this.
This should generally be called when a plugin is instantiated.
All arguments must be provided.
"""
if not eventName or not processId or not windowClassName:
raise ValueError("eventName, processId or windowClassName not specified")
entry = (eventName, processId, windowClassName)
procEvents = _acceptEventsByProcess.get(processId)
if not procEvents:
procEvents = _acceptEventsByProcess[processId] = set()
procEvents.add(entry)
_acceptEvents.add(entry)
def handleAppTerminate(appModule):
global _acceptEvents
events = _acceptEventsByProcess.pop(appModule.processID, None)
if not events:
return
_acceptEvents -= events
def shouldAcceptEvent(eventName, windowHandle=None):
"""Check whether an event should be accepted from a platform API.
Creating NVDAObjects and executing events can be expensive
and might block the main thread noticeably if the object is slow to respond.
Therefore, this should be used before NVDAObject creation to filter out any unnecessary events.
A platform API handler may do its own filtering before this.
"""
if not windowHandle:
# We can't filter without a window handle.
return True
wClass = winUser.getClassName(windowHandle)
key = (eventName,
winUser.getWindowThreadProcessID(windowHandle)[0],
wClass)
if key in _acceptEvents:
return True
if eventName == "valueChange" and config.conf["presentation"]["progressBarUpdates"]["reportBackgroundProgressBars"]:
return True
if eventName == "show":
# Only accept 'show' events for specific cases, as otherwise we get flooded.
return wClass in (
"Frame Notification Bar", # notification bars
"tooltips_class32", # tooltips
"mscandui21.candidate", "mscandui40.candidate", "MSCandUIWindow_Candidate", # IMM candidates
"TTrayAlert", # 5405: Skype
)
if eventName == "reorder":
# Prevent another flood risk.
return wClass == "TTrayAlert" # #4841: Skype
if eventName == "alert" and winUser.getClassName(winUser.getAncestor(windowHandle, winUser.GA_PARENT)) == "ToastChildWindowClass":
# Toast notifications.
return True
if eventName in ("menuEnd", "switchEnd", "desktopSwitch"):
# #5302, #5462: These events can be fired on the desktop window
# or windows that would otherwise be blocked.
# Platform API handlers will translate these events to focus events anyway,
# so we must allow them here.
return True
if windowHandle == winUser.getDesktopWindow():
# #5595: Events for the cursor get mapped to the desktop window.
return True
# #6713: Edge (and soon all UWP apps) will no longer have windows as descendants of the foreground window.
# However, it does look like they are always equal to or descendants of the "active" window of the input thread.
if wClass.startswith('Windows.UI.Core'):
gi=winUser.getGUIThreadInfo(0)
if winUser.isDescendantWindow(gi.hwndActive,windowHandle):
return True
fg = winUser.getForegroundWindow()
if wClass == "NetUIHWND" and winUser.getClassName(fg) == "Net UI Tool Window Layered":
# #5504: In Office >= 2013 with the ribbon showing only tabs,
# when a tab is expanded, the window we get from the focus object is incorrect.
# This window isn't beneath the foreground window,
# so our foreground application checks fail.
# Just compare the root owners.
if winUser.getAncestor(windowHandle, winUser.GA_ROOTOWNER) == winUser.getAncestor(fg, winUser.GA_ROOTOWNER):
return True
if (winUser.isDescendantWindow(fg, windowHandle)
# #3899, #3905: Covers cases such as the Firefox Page Bookmarked window and OpenOffice/LibreOffice context menus.
or winUser.isDescendantWindow(fg, winUser.getAncestor(windowHandle, winUser.GA_ROOTOWNER))):
# This is for the foreground application.
return True
if (winUser.user32.GetWindowLongW(windowHandle, winUser.GWL_EXSTYLE) & winUser.WS_EX_TOPMOST
or winUser.user32.GetWindowLongW(winUser.getAncestor(windowHandle, winUser.GA_ROOT), winUser.GWL_EXSTYLE) & winUser.WS_EX_TOPMOST):
# This window or its root is a topmost window.
# This includes menus, combo box pop-ups and the task switching list.
return True
return False
| 1 | 23,254 | Perhaps you want to check if UIAHandler.handler is not None. The current check will break NVDA if you call UIAHandler.terminate() for some reason. | nvaccess-nvda | py |
@@ -27,6 +27,7 @@ public class BaseReplacePartitions
extends MergingSnapshotProducer<ReplacePartitions> implements ReplacePartitions {
BaseReplacePartitions(String tableName, TableOperations ops) {
super(tableName, ops);
+ set("replace-partitions", "true");
}
@Override | 1 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.iceberg;
import java.util.List;
import org.apache.iceberg.exceptions.ValidationException;
import org.apache.iceberg.expressions.Expressions;
public class BaseReplacePartitions
extends MergingSnapshotProducer<ReplacePartitions> implements ReplacePartitions {
BaseReplacePartitions(String tableName, TableOperations ops) {
super(tableName, ops);
}
@Override
protected ReplacePartitions self() {
return this;
}
@Override
protected String operation() {
return DataOperations.OVERWRITE;
}
@Override
public ReplacePartitions addFile(DataFile file) {
dropPartition(file.partition());
add(file);
return this;
}
@Override
public ReplacePartitions validateAppendOnly() {
failAnyDelete();
return this;
}
@Override
public List<ManifestFile> apply(TableMetadata base) {
if (writeSpec().fields().size() <= 0) {
// replace all data in an unpartitioned table
deleteByRowFilter(Expressions.alwaysTrue());
}
try {
return super.apply(base);
} catch (DeleteException e) {
throw new ValidationException(
"Cannot commit file that conflicts with existing partition: %s", e.partition());
}
}
}
| 1 | 20,223 | can we make `replace-partitions` property a static variable in `SnaphotSummary.java`? | apache-iceberg | java |
@@ -57,8 +57,10 @@ module Selenium
#
# @return [Driver]
#
- # @see Selenium::WebDriver::Remote::Bridge
+ # @see Selenium::WebDriver::Remote::OSSBridge
+ # @see Selenium::WebDriver::Remote::W3CBridge
# @see Selenium::WebDriver::Firefox::Bridge
+ # @see Selenium::WebDriver::Firefox::W3CBridge
# @see Selenium::WebDriver::IE::Bridge
# @see Selenium::WebDriver::Edge::Bridge
# @see Selenium::WebDriver::Chrome::Bridge | 1 | # encoding: utf-8
#
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you 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.
require 'childprocess'
require 'tmpdir'
require 'fileutils'
require 'date'
require 'json'
require 'selenium/webdriver/common'
require 'selenium/webdriver/atoms'
module Selenium
module WebDriver
Point = Struct.new(:x, :y)
Dimension = Struct.new(:width, :height)
Location = Struct.new(:latitude, :longitude, :altitude)
autoload :Chrome, 'selenium/webdriver/chrome'
autoload :Edge, 'selenium/webdriver/edge'
autoload :Firefox, 'selenium/webdriver/firefox'
autoload :IE, 'selenium/webdriver/ie'
autoload :PhantomJS, 'selenium/webdriver/phantomjs'
autoload :Remote, 'selenium/webdriver/remote'
autoload :Safari, 'selenium/webdriver/safari'
autoload :Support, 'selenium/webdriver/support'
# @api private
def self.root
@root ||= File.expand_path('../..', __FILE__)
end
#
# Create a new Driver instance with the correct bridge for the given browser
#
# @param browser [:ie, :internet_explorer, :edge, :remote, :chrome, :firefox, :ff, :phantomjs, :safari]
# the driver type to use
# @param *rest
# arguments passed to Bridge.new
#
# @return [Driver]
#
# @see Selenium::WebDriver::Remote::Bridge
# @see Selenium::WebDriver::Firefox::Bridge
# @see Selenium::WebDriver::IE::Bridge
# @see Selenium::WebDriver::Edge::Bridge
# @see Selenium::WebDriver::Chrome::Bridge
# @see Selenium::WebDriver::PhantomJS::Bridge
# @see Selenium::WebDriver::Safari::Bridge
#
# @example
#
# WebDriver.for :firefox, :profile => "some-profile"
# WebDriver.for :firefox, :profile => Profile.new
# WebDriver.for :remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => caps
#
# One special argument is not passed on to the bridges, :listener.
# You can pass a listener for this option to get notified of WebDriver events.
# The passed object must respond to #call or implement the methods from AbstractEventListener.
#
# @see Selenium::WebDriver::Support::AbstractEventListener
#
def self.for(*args)
WebDriver::Driver.for(*args)
end
end # WebDriver
end # Selenium
| 1 | 14,227 | Maybe call it `WireBridge`? | SeleniumHQ-selenium | js |
@@ -79,7 +79,9 @@ def get_admins():
def activate_response(link):
payload = verify_activation_link(link)
if payload:
- _activate_user(User.query.filter_by(id=payload['id']).with_for_update().one_or_none())
+ user = User.query.filter_by(id=payload['id']).with_for_update().one_or_none()
+ _activate_user(user)
+ send_welcome_email(user)
db.session.commit()
return redirect("{CATALOG_URL}/signin".format(CATALOG_URL=CATALOG_URL), code=302)
| 1 | import base64
from datetime import datetime, timedelta
import json
import uuid
from flask import redirect, request
import itsdangerous
import jwt
from passlib.context import CryptContext
from sqlalchemy import func
from . import app, db
from .const import (ACTIVATE_SALT, CODE_TTL_DEFAULT, INVALID_USERNAMES,
MAX_LINK_AGE, PASSWORD_RESET_SALT, TOKEN_TTL_DEFAULT,
VALID_EMAIL_RE, VALID_USERNAME_RE)
from .mail import (send_activation_email, send_reset_email, send_new_user_email,
send_welcome_email)
from .models import ActivationToken, Code, PasswordResetToken, Token, User
CATALOG_URL = app.config['CATALOG_URL']
pwd_context = CryptContext(
schemes=['pbkdf2_sha512', 'django_pbkdf2_sha256'],
pbkdf2_sha512__default_rounds=500000
)
# Each round should take about half a second,
# 500000 rounds experimentally determined
class AuthException(Exception):
"""
Base class for Auth exceptions.
"""
def __init__(self, msg):
super().__init__()
self.message = msg
class ValidationException(AuthException):
"""
Represents a failure to deserialize a signed link,
a password that is too short, etc.
"""
pass
class ConflictException(AuthException):
"""
Represents an exception involving an attempt to register a
username that already exists, etc.
"""
pass
class NotFoundException(AuthException):
"""
Represents an exception involving an attempted operation on an entity
that could not be located.
"""
pass
class CredentialException(AuthException):
"""
Represents an exception involving things like an incorrect token,
an incorrect password, etc.
"""
pass
def generate_uuid():
return str(uuid.uuid4())
def hash_password(password):
return pwd_context.hash(password)
def get_admins():
return [user.email for user in User.query.filter_by(is_admin=True).all()]
def activate_response(link):
payload = verify_activation_link(link)
if payload:
_activate_user(User.query.filter_by(id=payload['id']).with_for_update().one_or_none())
db.session.commit()
return redirect("{CATALOG_URL}/signin".format(CATALOG_URL=CATALOG_URL), code=302)
return redirect("{CATALOG_URL}/activation_error".format(CATALOG_URL=CATALOG_URL), code=302)
def validate_password(password):
if len(password) < 8:
raise ValidationException("Password must be at least 8 characters long.")
def reset_password_from_email(email):
user = User.query.filter_by(email=email).with_for_update().one_or_none()
if user:
reset_password(user)
def change_password(raw_password, link):
validate_password(raw_password)
payload = verify_reset_link(link)
if not payload:
raise CredentialException("Reset token invalid")
user_id = payload['id']
user = User.query.filter_by(id=user_id).with_for_update().one_or_none()
if not user:
raise NotFoundException("User not found")
user.password = hash_password(raw_password)
revoke_user_code_tokens(user)
db.session.add(user)
def _create_user(username, password='', email=None, is_admin=False,
requires_activation=True, requires_reset=False):
def check_conflicts(username, email):
if not VALID_USERNAME_RE.match(username):
raise ValidationException("Invalid username.")
if username in INVALID_USERNAMES:
raise ValidationException("Invalid username.")
if email is None:
raise ValidationException("Must provide email.")
if not VALID_EMAIL_RE.match(email):
raise ValidationException("Invalid email.")
if User.query.filter_by(name=username).one_or_none():
raise ConflictException("Username already taken.")
if User.query.filter_by(email=email).one_or_none():
raise ConflictException("Email already taken.")
check_conflicts(username, email)
if requires_reset:
new_password = ""
else:
validate_password(password)
new_password = hash_password(password)
if requires_activation:
is_active = False
else:
is_active = True
user = User(
id=generate_uuid(),
name=username,
password=new_password,
email=email,
is_active=is_active,
is_admin=is_admin
)
db.session.add(user)
if requires_activation:
db.session.flush() # necessary due to link token foreign key relationship with User
send_activation_email(user, generate_activation_link(user.id))
if requires_reset:
db.session.flush() # necessary due to link token foreign key relationship with User
send_welcome_email(user, user.email, generate_reset_link(user.id))
def _update_user(username, password=None, email=None, is_admin=None, is_active=None):
existing_user = User.query.filter_by(name=username).with_for_update().one_or_none()
if not existing_user:
raise NotFoundException("User to update not found")
if password is not None:
new_password = hash_password(password)
existing_user.password = new_password
if email is not None:
existing_user.email = email
if is_admin is not None:
existing_user.is_admin = is_admin
if is_active is not None:
existing_user.is_active = is_active
db.session.add(existing_user)
def _activate_user(user):
if user is None:
raise NotFoundException("User not found")
user.is_active = True
db.session.add(user)
admins = get_admins()
if admins:
send_new_user_email(user.name, user.email, admins)
def update_last_login(user):
user.last_login = func.now()
db.session.add(user)
def _delete_user(user):
if user:
revoke_user_code_tokens(user)
db.session.delete(user)
else:
raise NotFoundException("User to delete not found")
return user
def _enable_user(user):
if user:
user.is_active = True
db.session.add(user)
else:
raise NotFoundException("User to enable not found")
def _disable_user(user):
if user:
revoke_user_code_tokens(user)
user.is_active = False
db.session.add(user)
else:
raise NotFoundException("User to disable not found")
def issue_code(user):
user_id = user.id
expires = datetime.utcnow() + timedelta(**CODE_TTL_DEFAULT)
code = Code(user_id=user_id, code=generate_uuid(), expires=expires)
db.session.add(code)
return encode_code({'id': user_id, 'code': code.code})
def encode_code(code_dict):
return base64.b64encode(bytes(json.dumps(code_dict), 'utf-8')).decode('utf8')
def decode_code(code_str):
try:
return json.loads(base64.b64decode(code_str).decode('utf8'))
except Exception:
raise ValidationException("Decoding code failed")
def decode_token(token_str):
try:
return jwt.decode(token_str, app.secret_key, algorithm='HS256')
except jwt.exceptions.InvalidTokenError:
raise ValidationException("Token could not be deserialized")
def check_token(user_id, token):
return Token.query.filter_by(user_id=user_id, token=token).one_or_none() is not None
def _verify(payload):
user_id = payload['id']
uuid = payload['uuid']
user = User.query.filter_by(id=user_id).one_or_none()
if user is None:
raise CredentialException('User ID invalid')
if not check_token(user_id, uuid):
raise CredentialException('Token invalid')
return user
def verify_token_string(token_string):
token = decode_token(token_string)
user = _verify(token)
return user
def exp_from_token(token):
token = decode_token(token)
return token['exp']
def revoke_token_string(token_str):
token = decode_token(token_str)
user_id = token['id']
uuid = token['uuid']
return revoke_token(user_id, uuid)
def revoke_token(user_id, token):
found = Token.query.filter_by(user_id=user_id, token=token).with_for_update().one_or_none()
if found is None:
return False
db.session.delete(found)
return True
def revoke_tokens(user):
Token.query.filter_by(user_id=user.id).delete()
def revoke_user_code_tokens(user):
Code.query.filter_by(user_id=user.id).delete()
revoke_tokens(user)
def calculate_exp(**kwargs):
kw = kwargs or TOKEN_TTL_DEFAULT
delta = timedelta(**kw)
return datetime.utcnow() + delta
def issue_token(user):
uuid = generate_uuid()
token = Token(user_id=user.id, token=uuid)
db.session.add(token)
exp = calculate_exp()
payload = {'id': user.id, 'uuid': uuid, 'exp': exp}
token = jwt.encode(payload, app.secret_key, algorithm='HS256')
return token.decode('utf-8')
def consume_code_string(code_str):
code = decode_code(code_str)
return consume_code(code['id'], code['code'])
def consume_code(user_id, code):
found = Code.query.filter_by(user_id=user_id, code=code).with_for_update().one_or_none()
if found is None:
raise ValidationException("Code not found")
if found.expires.timetuple() < datetime.utcnow().timetuple():
db.session.delete(found)
raise CredentialException("Code expired")
db.session.delete(found)
return User.query.filter_by(id=user_id).one_or_none()
def verify_hash(password, pw_hash):
try:
if not pwd_context.verify(password, pw_hash):
raise CredentialException('Password verification failed')
except ValueError:
raise CredentialException('Password verification failed')
def try_login(user, password):
if not user.is_active:
return False
try:
verify_hash(password, user.password)
except CredentialException:
return False
update_last_login(user)
return True
linkgenerator = itsdangerous.URLSafeTimedSerializer(
app.secret_key,
salt='quilt'
)
def dump_link(payload, salt=None):
link = linkgenerator.dumps(payload, salt=salt)
return link.replace('.', '~')
def load_link(link, max_age, salt=None):
payload = link.replace('~', '.')
return linkgenerator.loads(payload, max_age=max_age, salt=salt)
def generate_activation_token(user_id):
new_token = ActivationToken(user_id=user_id, token=generate_uuid())
db.session.add(new_token)
return new_token.token
def consume_activation_token(user_id, token):
found = (
ActivationToken.query
.filter_by(user_id=user_id, token=token)
.with_for_update()
.one_or_none()
)
if not found:
return False
db.session.delete(found)
return True
def generate_reset_token(user_id):
reset_token = generate_uuid()
PasswordResetToken.upsert(user_id, reset_token)
return reset_token
def consume_reset_token(user_id, token):
found = (
PasswordResetToken
.query
.filter_by(user_id=user_id, token=token)
.with_for_update()
.one_or_none()
)
if not found:
return False
db.session.delete(found)
return True
def generate_activation_link(user_id):
token = generate_activation_token(user_id)
payload = {'id': user_id, 'token': token}
return dump_link(payload, ACTIVATE_SALT)
def generate_reset_link(user_id):
token = generate_reset_token(user_id)
payload = {'id': user_id, 'token': token}
return dump_link(payload, PASSWORD_RESET_SALT)
def verify_activation_link(link, max_age=None):
max_age = max_age if max_age is not None else MAX_LINK_AGE
try:
payload = load_link(link, max_age=max_age, salt=ACTIVATE_SALT)
if not consume_activation_token(payload['id'], payload['token']):
return None
return payload
except (TypeError, KeyError, ValueError, itsdangerous.BadData):
return None
def verify_reset_link(link, max_age=None):
max_age = max_age if max_age is not None else MAX_LINK_AGE
try:
payload = load_link(link, max_age=max_age, salt=PASSWORD_RESET_SALT)
if not consume_reset_token(payload['id'], payload['token']):
return None
return payload
except (TypeError, KeyError, ValueError, itsdangerous.BadData):
return None
def reset_password(user, set_unusable=False):
if set_unusable:
user.password = ''
revoke_user_code_tokens(user)
db.session.add(user)
link = generate_reset_link(user.id)
send_reset_email(user, link)
| 1 | 16,965 | Should really be `one()`, not `one_or_none()` | quiltdata-quilt | py |
@@ -193,7 +193,11 @@ func SetJoinNodeConfigurationOverrides(caCertHash, bootstrapToken string, machin
}
out.NodeRegistration.KubeletExtraArgs["cloud-provider"] = CloudProvider
if !util.IsControlPlaneMachine(machine.GetMachine()) {
- out.NodeRegistration.KubeletExtraArgs["node-labels"] = nodeRole
+ if labels, ok := out.NodeRegistration.KubeletExtraArgs["node-labels"]; ok {
+ out.NodeRegistration.KubeletExtraArgs["node-labels"] = fmt.Sprintf("%s,%s", labels, nodeRole)
+ } else {
+ out.NodeRegistration.KubeletExtraArgs["node-labels"] = nodeRole
+ }
}
return out
} | 1 | /*
Copyright 2019 The Kubernetes Authors.
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.
*/
package kubeadm
import (
"fmt"
"sigs.k8s.io/cluster-api/pkg/apis/cluster/v1alpha1"
"sigs.k8s.io/cluster-api/pkg/util"
kubeadmv1beta1 "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1beta1"
"sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/aws/actuators"
)
const (
// localIPV4lookup looks up the instance's IP through the metadata service.
// See https://cloudinit.readthedocs.io/en/latest/topics/instancedata.html
localIPV4Lookup = "{{ ds.meta_data.local_ipv4 }}"
// HostnameLookup uses the instance metadata service to lookup its own hostname.
HostnameLookup = "{{ ds.meta_data.hostname }}"
// ContainerdSocket is the expected path to containerd socket.
ContainerdSocket = "/var/run/containerd/containerd.sock"
// APIServerBindPort is the default port for the kube-apiserver to bind to.
APIServerBindPort = 6443
// CloudProvider is the name of the cloud provider passed to various
// kubernetes components.
CloudProvider = "aws"
nodeRole = "node-role.kubernetes.io/node="
)
// joinMachine is a local interface to scope down dependencies
type joinMachine interface {
GetScope() *actuators.Scope
GetMachine() *v1alpha1.Machine
}
// SetDefaultClusterConfiguration sets default dynamic values without overriding
// user specified values.
func SetDefaultClusterConfiguration(machine joinMachine, base *kubeadmv1beta1.ClusterConfiguration) *kubeadmv1beta1.ClusterConfiguration {
if base == nil {
base = &kubeadmv1beta1.ClusterConfiguration{}
}
out := base.DeepCopy()
s := machine.GetScope()
// Only set the control plane endpoint if the user hasn't specified one.
if out.ControlPlaneEndpoint == "" {
out.ControlPlaneEndpoint = fmt.Sprintf("%s:%d", s.Network().APIServerELB.DNSName, APIServerBindPort)
}
// Add the control plane endpoint to the list of cert SAN
out.APIServer.CertSANs = append(out.APIServer.CertSANs, localIPV4Lookup, s.Network().APIServerELB.DNSName)
return out
}
// SetClusterConfigurationOverrides will modify the supplied configuration with certain values
// that cluster-api-provider-aws requires overriding user specified input.
func SetClusterConfigurationOverrides(machine joinMachine, base *kubeadmv1beta1.ClusterConfiguration) *kubeadmv1beta1.ClusterConfiguration {
if base == nil {
base = &kubeadmv1beta1.ClusterConfiguration{}
}
s := machine.GetScope()
out := SetDefaultClusterConfiguration(machine, base.DeepCopy())
// cloud-provider for the APIServer must be set to 'aws'.
if out.APIServer.ControlPlaneComponent.ExtraArgs == nil {
out.APIServer.ControlPlaneComponent.ExtraArgs = map[string]string{}
}
if cp, ok := out.APIServer.ControlPlaneComponent.ExtraArgs["cloud-provider"]; ok && cp != CloudProvider {
machine.GetScope().Logger.Info("Overriding cloud provider with required value", "provided-cloud-provider", cp, "required-cloud-provider", CloudProvider)
}
out.APIServer.ControlPlaneComponent.ExtraArgs["cloud-provider"] = CloudProvider
if out.ControllerManager.ExtraArgs == nil {
out.ControllerManager.ExtraArgs = map[string]string{}
}
if cp, ok := out.ControllerManager.ExtraArgs["cloud-provider"]; ok && cp != CloudProvider {
machine.GetScope().Logger.Info("Overriding cloud provider with required value", "provided-cloud-provider", cp, "required-cloud-provider", CloudProvider)
}
out.ControllerManager.ExtraArgs["cloud-provider"] = CloudProvider
// The kubeadm config clustername must match the provided name of the cluster.
if out.ClusterName != "" && out.ClusterName != s.Name() {
machine.GetScope().Logger.Info("Overriding provided cluster name. The kubeadm cluster name and cluster-api name must match.",
"provided-cluster-name", out.ClusterName,
"required-cluster-name", s.Name())
}
out.ClusterName = s.Name()
// The networking values provided by the Cluster object must equal the
// kubeadm networking configuration.
out.Networking.DNSDomain = s.Cluster.Spec.ClusterNetwork.ServiceDomain
out.Networking.PodSubnet = s.Cluster.Spec.ClusterNetwork.Pods.CIDRBlocks[0]
out.Networking.ServiceSubnet = s.Cluster.Spec.ClusterNetwork.Services.CIDRBlocks[0]
// The kubernetes version that kubeadm is using must be the same as the
// requested version in the config
out.KubernetesVersion = machine.GetMachine().Spec.Versions.ControlPlane
return out
}
// SetInitConfigurationOverrides overrides user input on particular fields for
// the kubeadm InitConfiguration.
func SetInitConfigurationOverrides(machine joinMachine, base *kubeadmv1beta1.InitConfiguration) *kubeadmv1beta1.InitConfiguration {
if base == nil {
base = &kubeadmv1beta1.InitConfiguration{}
}
out := base.DeepCopy()
if out.NodeRegistration.Name != "" && out.NodeRegistration.Name != HostnameLookup {
machine.GetScope().Info("Overriding NodeRegistration name. The node registration needs to be dynamically generated in aws.",
"provided-node-registration-name", out.NodeRegistration.Name,
"required-node-registration-name", HostnameLookup)
}
out.NodeRegistration.Name = HostnameLookup
// TODO(chuckha): This may become a default instead of an override.
if out.NodeRegistration.CRISocket != "" && out.NodeRegistration.CRISocket != ContainerdSocket {
machine.GetScope().Info("Overriding CRISocket. Containerd is only supported container runtime.",
"provided-container-runtime-socket", out.NodeRegistration.CRISocket,
"required-container-runtime-socket", ContainerdSocket)
}
out.NodeRegistration.CRISocket = ContainerdSocket
if out.NodeRegistration.KubeletExtraArgs == nil {
out.NodeRegistration.KubeletExtraArgs = map[string]string{}
}
if cp, ok := out.NodeRegistration.KubeletExtraArgs["cloud-provider"]; ok && cp != CloudProvider {
machine.GetScope().Info("Overriding node's cloud-provider", "provided-cloud-provider", cp, "required-cloud-provider", CloudProvider)
}
out.NodeRegistration.KubeletExtraArgs["cloud-provider"] = CloudProvider
return out
}
// SetJoinNodeConfigurationOverrides overrides user input for certain fields of
// the kubeadm JoinConfiguration during a worker node join.
func SetJoinNodeConfigurationOverrides(caCertHash, bootstrapToken string, machine joinMachine, base *kubeadmv1beta1.JoinConfiguration) *kubeadmv1beta1.JoinConfiguration {
if base == nil {
base = &kubeadmv1beta1.JoinConfiguration{}
}
out := base.DeepCopy()
if out.Discovery.BootstrapToken == nil {
out.Discovery.BootstrapToken = &kubeadmv1beta1.BootstrapTokenDiscovery{}
}
// TODO: should this actually be the cluster's ContolPlaneEndpoint?
out.Discovery.BootstrapToken.APIServerEndpoint = fmt.Sprintf("%s:%d", machine.GetScope().Network().APIServerELB.DNSName, APIServerBindPort)
out.Discovery.BootstrapToken.Token = bootstrapToken
out.Discovery.BootstrapToken.CACertHashes = append(out.Discovery.BootstrapToken.CACertHashes, caCertHash)
if out.NodeRegistration.Name != "" && out.NodeRegistration.Name != HostnameLookup {
machine.GetScope().Logger.Info("Overriding NodeRegistration name . The node registration needs to be dynamically generated in aws.",
"provided-node-registration-name", out.NodeRegistration.Name,
"required-node-registration-name", HostnameLookup)
}
out.NodeRegistration.Name = HostnameLookup
// TODO(chuckha): This may become a default instead of an override.
if out.NodeRegistration.CRISocket != "" && out.NodeRegistration.CRISocket != ContainerdSocket {
machine.GetScope().Logger.Info("Overriding CRISocket. Containerd is only supported container runtime.",
"provided-container-runtime-socket", out.NodeRegistration.CRISocket,
"required-container-runtime-socket", ContainerdSocket)
}
out.NodeRegistration.CRISocket = ContainerdSocket
if out.NodeRegistration.KubeletExtraArgs == nil {
out.NodeRegistration.KubeletExtraArgs = map[string]string{}
}
if cp, ok := out.NodeRegistration.KubeletExtraArgs["cloud-provider"]; ok && cp != CloudProvider {
machine.GetScope().Logger.Info("Overriding node's cloud-provider to the required value",
"provided-cloud-provider", cp,
"required-cloud-provider", CloudProvider)
}
out.NodeRegistration.KubeletExtraArgs["cloud-provider"] = CloudProvider
if !util.IsControlPlaneMachine(machine.GetMachine()) {
out.NodeRegistration.KubeletExtraArgs["node-labels"] = nodeRole
}
return out
}
// SetControlPlaneJoinConfigurationOverrides user input for kubeadm join
// configuration during a control plane join action.
func SetControlPlaneJoinConfigurationOverrides(base *kubeadmv1beta1.JoinConfiguration) *kubeadmv1beta1.JoinConfiguration {
if base == nil {
base = &kubeadmv1beta1.JoinConfiguration{}
}
out := base.DeepCopy()
if out.ControlPlane == nil {
out.ControlPlane = &kubeadmv1beta1.JoinControlPlane{}
}
out.ControlPlane.LocalAPIEndpoint.AdvertiseAddress = localIPV4Lookup
out.ControlPlane.LocalAPIEndpoint.BindPort = APIServerBindPort
return out
}
| 1 | 9,611 | Should we use strings.Split and strings.Join instead of manual concatenation? | kubernetes-sigs-cluster-api-provider-aws | go |
@@ -374,6 +374,18 @@ class In(
asset_partitions=asset_partitions,
)
+ @staticmethod
+ def from_definition(input_def: InputDefinition):
+ return In(
+ dagster_type=input_def.dagster_type,
+ description=input_def.description,
+ default_value=input_def._default_value, # pylint: disable=protected-access
+ root_manager_key=input_def.root_manager_key,
+ metadata=input_def.metadata,
+ asset_key=input_def._asset_key, # pylint: disable=protected-access
+ asset_partitions=input_def._asset_partitions_fn, # pylint: disable=protected-access
+ )
+
def to_definition(self, name: str) -> InputDefinition:
dagster_type = self.dagster_type if self.dagster_type is not NoValueSentinel else None
return InputDefinition( | 1 | from collections import namedtuple
from typing import NamedTuple, Optional, Set
from dagster import check
from dagster.core.definitions.events import AssetKey
from dagster.core.errors import DagsterError, DagsterInvalidDefinitionError
from dagster.core.types.dagster_type import (
BuiltinScalarDagsterType,
DagsterType,
resolve_dagster_type,
)
from dagster.utils.backcompat import experimental_arg_warning
from .inference import InferredInputProps
from .utils import NoValueSentinel, check_valid_name
# unfortunately since type_check functions need TypeCheckContext which is only available
# at runtime, we can only check basic types before runtime
def _check_default_value(input_name, dagster_type, default_value):
if default_value is not NoValueSentinel:
if dagster_type.is_nothing:
raise DagsterInvalidDefinitionError(
"Setting a default_value is invalid on InputDefinitions of type Nothing"
)
if isinstance(dagster_type, BuiltinScalarDagsterType):
type_check = dagster_type.type_check_scalar_value(default_value)
if not type_check.success:
raise DagsterInvalidDefinitionError(
(
"Type check failed for the default_value of InputDefinition "
"{input_name} of type {dagster_type}. "
"Received value {value} of type {type}"
).format(
input_name=input_name,
dagster_type=dagster_type.display_name,
value=default_value,
type=type(default_value),
),
)
return default_value
class InputDefinition:
"""Defines an argument to a solid's compute function.
Inputs may flow from previous solids' outputs, or be stubbed using config. They may optionally
be typed using the Dagster type system.
Args:
name (str): Name of the input.
dagster_type (Optional[Union[Type, DagsterType]]]): The type of this input.
Users should provide the Python type of the objects that they expect to be passed for
this input, or a :py:class:`DagsterType` that defines a runtime check that they want
to be run on this input. Defaults to :py:class:`Any`.
description (Optional[str]): Human-readable description of the input.
default_value (Optional[Any]): The default value to use if no input is provided.
root_manager_key (Optional[str]): (Experimental) The resource key for the
:py:class:`RootInputManager` used for loading this input when it is not connected to an
upstream output.
metadata (Optional[Dict[str, Any]]): A dict of metadata for the input.
asset_key (Optional[Union[AssetKey, InputContext -> AssetKey]]): (Experimental) An AssetKey
(or function that produces an AssetKey from the InputContext) which should be associated
with this InputDefinition. Used for tracking lineage information through Dagster.
asset_partitions (Optional[Union[Set[str], InputContext -> Set[str]]]): (Experimental) A
set of partitions of the given asset_key (or a function that produces this list of
partitions from the InputContext) which should be associated with this InputDefinition.
"""
def __init__(
self,
name=None,
dagster_type=None,
description=None,
default_value=NoValueSentinel,
root_manager_key=None,
metadata=None,
asset_key=None,
asset_partitions=None,
# when adding new params, make sure to update combine_with_inferred below
):
self._name = check_valid_name(name) if name else None
self._type_not_set = dagster_type is None
self._dagster_type = check.inst(resolve_dagster_type(dagster_type), DagsterType)
self._description = check.opt_str_param(description, "description")
self._default_value = _check_default_value(self._name, self._dagster_type, default_value)
if root_manager_key:
experimental_arg_warning("root_manager_key", "InputDefinition.__init__")
self._root_manager_key = check.opt_str_param(root_manager_key, "root_manager_key")
self._metadata = check.opt_dict_param(metadata, "metadata", key_type=str)
if asset_key:
experimental_arg_warning("asset_key", "InputDefinition.__init__")
if not callable(asset_key):
check.opt_inst_param(asset_key, "asset_key", AssetKey)
self._asset_key = asset_key
if asset_partitions:
experimental_arg_warning("asset_partitions", "InputDefinition.__init__")
check.param_invariant(
asset_key is not None,
"asset_partitions",
'Cannot specify "asset_partitions" argument without also specifying "asset_key"',
)
if callable(asset_partitions):
self._asset_partitions_fn = asset_partitions
elif asset_partitions is not None:
asset_partitions = check.opt_set_param(asset_partitions, "asset_partitions", str)
self._asset_partitions_fn = lambda _: asset_partitions
else:
self._asset_partitions_fn = None
@property
def name(self):
return self._name
@property
def dagster_type(self):
return self._dagster_type
@property
def description(self):
return self._description
@property
def has_default_value(self):
return self._default_value is not NoValueSentinel
@property
def default_value(self):
check.invariant(self.has_default_value, "Can only fetch default_value if has_default_value")
return self._default_value
@property
def root_manager_key(self):
return self._root_manager_key
@property
def metadata(self):
return self._metadata
@property
def is_asset(self):
return self._asset_key is not None
@property
def hardcoded_asset_key(self) -> Optional[AssetKey]:
if not callable(self._asset_key):
return self._asset_key
else:
return None
def get_asset_key(self, context) -> Optional[AssetKey]:
"""Get the AssetKey associated with this InputDefinition for the given
:py:class:`InputContext` (if any).
Args:
context (InputContext): The InputContext that this InputDefinition is being evaluated
in
"""
if callable(self._asset_key):
return self._asset_key(context)
else:
return self.hardcoded_asset_key
def get_asset_partitions(self, context) -> Optional[Set[str]]:
"""Get the set of partitions that this solid will read from this InputDefinition for the given
:py:class:`InputContext` (if any).
Args:
context (InputContext): The InputContext that this InputDefinition is being evaluated
in
"""
if self._asset_partitions_fn is None:
return None
return self._asset_partitions_fn(context)
def mapping_to(self, solid_name, input_name, fan_in_index=None):
"""Create an input mapping to an input of a child solid.
In a CompositeSolidDefinition, you can use this helper function to construct
an :py:class:`InputMapping` to the input of a child solid.
Args:
solid_name (str): The name of the child solid to which to map this input.
input_name (str): The name of the child solid' input to which to map this input.
fan_in_index (Optional[int]): The index in to a fanned in input, else None
Examples:
.. code-block:: python
input_mapping = InputDefinition('composite_input', Int).mapping_to(
'child_solid', 'int_input'
)
"""
check.str_param(solid_name, "solid_name")
check.str_param(input_name, "input_name")
check.opt_int_param(fan_in_index, "fan_in_index")
if fan_in_index is not None:
maps_to = FanInInputPointer(solid_name, input_name, fan_in_index)
else:
maps_to = InputPointer(solid_name, input_name)
return InputMapping(self, maps_to)
@staticmethod
def create_from_inferred(inferred: InferredInputProps) -> "InputDefinition":
return InputDefinition(
name=inferred.name,
dagster_type=_checked_inferred_type(inferred),
description=inferred.description,
default_value=inferred.default_value,
)
def combine_with_inferred(self, inferred: InferredInputProps) -> "InputDefinition":
"""
Return a new InputDefinition that merges this ones properties with those inferred from type signature.
This can update: dagster_type, description, and default_value if they are not set.
"""
check.invariant(
self.name == inferred.name,
f"InferredInputProps name {inferred.name} did not align with InputDefinition name {self.name}",
)
dagster_type = self._dagster_type
if self._type_not_set:
dagster_type = _checked_inferred_type(inferred)
description = self._description
if description is None and inferred.description is not None:
description = inferred.description
default_value = self._default_value
if not self.has_default_value:
default_value = inferred.default_value
return InputDefinition(
name=self.name,
dagster_type=dagster_type,
description=description,
default_value=default_value,
root_manager_key=self._root_manager_key,
metadata=self._metadata,
asset_key=self._asset_key,
asset_partitions=self._asset_partitions_fn,
)
def _checked_inferred_type(inferred: InferredInputProps) -> DagsterType:
try:
resolved_type = resolve_dagster_type(inferred.annotation)
except DagsterError as e:
raise DagsterInvalidDefinitionError(
f"Problem using type '{inferred.annotation}' from type annotation for argument "
f"'{inferred.name}', correct the issue or explicitly set the dagster_type on "
"your InputDefinition."
) from e
if resolved_type.is_nothing:
raise DagsterInvalidDefinitionError(
f"Input parameter {inferred.name} is annotated with {resolved_type.display_name} "
"which is a type that represents passing no data. This type must be used "
"via InputDefinition and no parameter should be included in the solid function."
)
return resolved_type
class InputPointer(namedtuple("_InputPointer", "solid_name input_name")):
def __new__(cls, solid_name, input_name):
return super(InputPointer, cls).__new__(
cls,
check.str_param(solid_name, "solid_name"),
check.str_param(input_name, "input_name"),
)
class FanInInputPointer(namedtuple("_FanInInputPointer", "solid_name input_name fan_in_index")):
def __new__(cls, solid_name, input_name, fan_in_index):
return super(FanInInputPointer, cls).__new__(
cls,
check.str_param(solid_name, "solid_name"),
check.str_param(input_name, "input_name"),
check.int_param(fan_in_index, "fan_in_index"),
)
class InputMapping(namedtuple("_InputMapping", "definition maps_to")):
"""Defines an input mapping for a composite solid.
Args:
definition (InputDefinition): Defines the input to the composite solid.
solid_name (str): The name of the child solid onto which to map the input.
input_name (str): The name of the input to the child solid onto which to map the input.
"""
def __new__(cls, definition, maps_to):
return super(InputMapping, cls).__new__(
cls,
check.inst_param(definition, "definition", InputDefinition),
check.inst_param(maps_to, "maps_to", (InputPointer, FanInInputPointer)),
)
@property
def maps_to_fan_in(self):
return isinstance(self.maps_to, FanInInputPointer)
def describe(self) -> str:
idx = self.maps_to.fan_in_index if isinstance(self.maps_to, FanInInputPointer) else ""
return f"{self.definition.name} -> {self.maps_to.solid_name}:{self.maps_to.input_name}{idx}"
class In(
namedtuple(
"_In",
"dagster_type description default_value root_manager_key metadata "
"asset_key asset_partitions",
)
):
"""
Defines an argument to an op's compute function.
Inputs may flow from previous op's outputs, or be stubbed using config. They may optionally
be typed using the Dagster type system.
Args:
dagster_type (Optional[Union[Type, DagsterType]]]):
The type of this input. Should only be set if the correct type can not
be inferred directly from the type signature of the decorated function.
description (Optional[str]): Human-readable description of the input.
default_value (Optional[Any]): The default value to use if no input is provided.
root_manager_key (Optional[str]): (Experimental) The resource key for the
:py:class:`RootInputManager` used for loading this input when it is not connected to an
upstream output.
metadata (Optional[Dict[str, Any]]): A dict of metadata for the input.
asset_key (Optional[Union[AssetKey, InputContext -> AssetKey]]): (Experimental) An AssetKey
(or function that produces an AssetKey from the InputContext) which should be associated
with this In. Used for tracking lineage information through Dagster.
asset_partitions (Optional[Union[Set[str], InputContext -> Set[str]]]): (Experimental) A
set of partitions of the given asset_key (or a function that produces this list of
partitions from the InputContext) which should be associated with this In.
"""
def __new__(
cls,
dagster_type=NoValueSentinel,
description=None,
default_value=NoValueSentinel,
root_manager_key=None,
metadata=None,
asset_key=None,
asset_partitions=None,
):
return super(In, cls).__new__(
cls,
dagster_type=dagster_type,
description=description,
default_value=default_value,
root_manager_key=root_manager_key,
metadata=metadata,
asset_key=asset_key,
asset_partitions=asset_partitions,
)
def to_definition(self, name: str) -> InputDefinition:
dagster_type = self.dagster_type if self.dagster_type is not NoValueSentinel else None
return InputDefinition(
name=name,
dagster_type=dagster_type,
description=self.description,
default_value=self.default_value,
root_manager_key=self.root_manager_key,
metadata=self.metadata,
asset_key=self.asset_key,
asset_partitions=self.asset_partitions,
)
class GraphIn(NamedTuple("_GraphIn", [("description", Optional[str])])):
"""
Represents information about an input that a graph maps.
Args:
description (Optional[str]): Human-readable description of the input.
"""
def __new__(cls, description=None):
return super(GraphIn, cls).__new__(cls, description=description)
def to_definition(self, name: str) -> InputDefinition:
return InputDefinition(name=name, description=self.description)
| 1 | 16,516 | rough that this needs to exist, but it is what it is | dagster-io-dagster | py |
@@ -117,6 +117,17 @@ describe('render()', () => {
expect(scratch.firstChild).to.have.property('nodeName', 'X-BAR');
});
+ // TODO: the test doesn't seem to work as it throws, maybe due to not knowing the props allowed for x-bar
+ // it('should not set empty string for null props in custom attributes', () => {
+ // render(<x-bar val={null} />, scratch);
+ // expect(scratch.childNodes).to.have.length(1);
+ // expect(scratch.firstChild).to.have.property('nodeName', 'X-BAR');
+ // expect(scratch.firstChild.attributes['val']).to.equal('null');
+ // expect(scratch.innerHTML).to.equal(
+ // '<x-bar val="null"></x-bar>'
+ // );
+ // });
+
it('should support the form attribute', () => {
render(
<div> | 1 | import { setupRerender } from 'preact/test-utils';
import { createElement, render, Component, options } from 'preact';
import {
setupScratch,
teardown,
getMixedArray,
mixedArrayHTML,
serializeHtml,
supportsDataList,
sortAttributes,
spyOnElementAttributes,
createEvent
} from '../_util/helpers';
import { clearLog, getLog, logCall } from '../_util/logCall';
import { useState } from 'preact/hooks';
/** @jsx createElement */
function getAttributes(node) {
let attrs = {};
for (let i = node.attributes.length; i--; ) {
attrs[node.attributes[i].name] = node.attributes[i].value;
}
return attrs;
}
const isIE11 = /Trident\//.test(navigator.userAgent);
describe('render()', () => {
let scratch, rerender;
let resetAppendChild;
let resetInsertBefore;
let resetRemoveChild;
let resetRemove;
beforeEach(() => {
scratch = setupScratch();
rerender = setupRerender();
});
afterEach(() => {
teardown(scratch);
});
before(() => {
resetAppendChild = logCall(Element.prototype, 'appendChild');
resetInsertBefore = logCall(Element.prototype, 'insertBefore');
resetRemoveChild = logCall(Element.prototype, 'removeChild');
resetRemove = logCall(Element.prototype, 'remove');
});
after(() => {
resetAppendChild();
resetInsertBefore();
resetRemoveChild();
resetRemove();
});
it('should rerender when value from "" to 0', () => {
render('', scratch);
expect(scratch.innerHTML).to.equal('');
render(0, scratch);
expect(scratch.innerHTML).to.equal('0');
});
it('should render an empty text node given an empty string', () => {
render('', scratch);
let c = scratch.childNodes;
expect(c).to.have.length(1);
expect(c[0].data).to.equal('');
expect(c[0].nodeName).to.equal('#text');
});
it('should allow node type change with content', () => {
render(<span>Bad</span>, scratch);
render(<div>Good</div>, scratch);
expect(scratch.innerHTML).to.eql(`<div>Good</div>`);
});
it('should not render when detecting JSON-injection', () => {
const vnode = JSON.parse('{"type":"span","children":"Malicious"}');
render(vnode, scratch);
expect(scratch.firstChild).to.be.null;
});
it('should create empty nodes (<* />)', () => {
render(<div />, scratch);
expect(scratch.childNodes).to.have.length(1);
expect(scratch.childNodes[0].nodeName).to.equal('DIV');
scratch.parentNode.removeChild(scratch);
scratch = document.createElement('div');
(document.body || document.documentElement).appendChild(scratch);
render(<span />, scratch);
expect(scratch.childNodes).to.have.length(1);
expect(scratch.childNodes[0].nodeName).to.equal('SPAN');
});
it('should not throw error in IE11 with type date', () => {
expect(() => render(<input type="date" />, scratch)).to.not.throw();
});
it('should support custom tag names', () => {
render(<foo />, scratch);
expect(scratch.childNodes).to.have.length(1);
expect(scratch.firstChild).to.have.property('nodeName', 'FOO');
scratch.parentNode.removeChild(scratch);
scratch = document.createElement('div');
(document.body || document.documentElement).appendChild(scratch);
render(<x-bar />, scratch);
expect(scratch.childNodes).to.have.length(1);
expect(scratch.firstChild).to.have.property('nodeName', 'X-BAR');
});
it('should support the form attribute', () => {
render(
<div>
<form id="myform" />
<button form="myform">test</button>
<input form="myform" />
</div>,
scratch
);
const div = scratch.childNodes[0];
const form = div.childNodes[0];
const button = div.childNodes[1];
const input = div.childNodes[2];
// IE11 doesn't support the form attribute
if (!isIE11) {
expect(button).to.have.property('form', form);
expect(input).to.have.property('form', form);
}
});
it('should allow VNode reuse', () => {
let reused = <div class="reuse">Hello World!</div>;
render(
<div>
{reused}
<hr />
{reused}
</div>,
scratch
);
expect(serializeHtml(scratch)).to.eql(
`<div><div class="reuse">Hello World!</div><hr><div class="reuse">Hello World!</div></div>`
);
render(
<div>
<hr />
{reused}
</div>,
scratch
);
expect(serializeHtml(scratch)).to.eql(
`<div><hr><div class="reuse">Hello World!</div></div>`
);
});
it('should merge new elements when called multiple times', () => {
render(<div />, scratch);
expect(scratch.childNodes).to.have.length(1);
expect(scratch.firstChild).to.have.property('nodeName', 'DIV');
expect(scratch.innerHTML).to.equal('<div></div>');
render(<span />, scratch);
expect(scratch.childNodes).to.have.length(1);
expect(scratch.firstChild).to.have.property('nodeName', 'SPAN');
expect(scratch.innerHTML).to.equal('<span></span>');
render(<span class="hello">Hello!</span>, scratch);
expect(scratch.childNodes).to.have.length(1);
expect(scratch.firstChild).to.have.property('nodeName', 'SPAN');
expect(scratch.innerHTML).to.equal('<span class="hello">Hello!</span>');
});
it('should nest empty nodes', () => {
render(
<div>
<span />
<foo />
<x-bar />
</div>,
scratch
);
expect(scratch.childNodes).to.have.length(1);
expect(scratch.childNodes[0].nodeName).to.equal('DIV');
let c = scratch.childNodes[0].childNodes;
expect(c).to.have.length(3);
expect(c[0].nodeName).to.equal('SPAN');
expect(c[1].nodeName).to.equal('FOO');
expect(c[2].nodeName).to.equal('X-BAR');
});
it('should not render falsy values', () => {
render(
<div>
{null},{undefined},{false},{0},{NaN}
</div>,
scratch
);
expect(scratch.firstChild).to.have.property('innerHTML', ',,,0,NaN');
});
it('should not render null', () => {
render(null, scratch);
expect(scratch.innerHTML).to.equal('');
expect(scratch.childNodes).to.have.length(0);
});
it('should not render undefined', () => {
render(undefined, scratch);
expect(scratch.innerHTML).to.equal('');
expect(scratch.childNodes).to.have.length(0);
});
it('should not render boolean true', () => {
render(true, scratch);
expect(scratch.innerHTML).to.equal('');
expect(scratch.childNodes).to.have.length(0);
});
it('should not render boolean false', () => {
render(false, scratch);
expect(scratch.innerHTML).to.equal('');
expect(scratch.childNodes).to.have.length(0);
});
it('should not render children when using function children', () => {
render(<div>{() => {}}</div>, scratch);
expect(scratch.innerHTML).to.equal('<div></div>');
});
it('should render NaN as text content', () => {
render(NaN, scratch);
expect(scratch.innerHTML).to.equal('NaN');
});
it('should render numbers (0) as text content', () => {
render(0, scratch);
expect(scratch.innerHTML).to.equal('0');
});
it('should render numbers (42) as text content', () => {
render(42, scratch);
expect(scratch.innerHTML).to.equal('42');
});
it('should render bigint as text content', () => {
// Skip in browsers not supporting big integers
if (typeof BigInt === 'undefined') {
return;
}
// eslint-disable-next-line no-undef, new-cap
render(BigInt(4), scratch);
expect(scratch.innerHTML).to.equal('4');
});
it('should render strings as text content', () => {
render('Testing, huh! How is it going?', scratch);
expect(scratch.innerHTML).to.equal('Testing, huh! How is it going?');
});
it('should render arrays of mixed elements', () => {
render(getMixedArray(), scratch);
expect(scratch.innerHTML).to.equal(mixedArrayHTML);
});
it('should clear falsy attributes', () => {
render(
<div
anull="anull"
aundefined="aundefined"
afalse="afalse"
anan="aNaN"
a0="a0"
/>,
scratch
);
render(
<div
anull={null}
aundefined={undefined}
afalse={false}
anan={NaN}
a0={0}
/>,
scratch
);
expect(
getAttributes(scratch.firstChild),
'from previous truthy values'
).to.eql({
a0: '0',
anan: 'NaN'
});
});
it('should not render falsy attributes on hydrate', () => {
render(
<div
anull={null}
aundefined={undefined}
afalse={false}
anan={NaN}
a0={0}
/>,
scratch
);
expect(getAttributes(scratch.firstChild), 'initial render').to.eql({
a0: '0',
anan: 'NaN'
});
});
it('should clear falsy input values', () => {
// Note: this test just demonstrates the default browser behavior
render(
<div>
<input value={0} />
<input value={false} />
<input value={null} />
<input value={undefined} />
</div>,
scratch
);
let root = scratch.firstChild;
expect(root.children[0]).to.have.property('value', '0');
expect(root.children[1]).to.have.property('value', 'false');
expect(root.children[2]).to.have.property('value', '');
expect(root.children[3]).to.have.property('value', '');
});
it('should set value inside the specified range', () => {
render(
<input type="range" value={0.5} min="0" max="1" step="0.05" />,
scratch
);
expect(scratch.firstChild.value).to.equal('0.5');
});
// IE or IE Edge will throw when attribute values don't conform to the
// spec. That's the correct behaviour, but bad for this test...
if (!/(Edge|MSIE|Trident)/.test(navigator.userAgent)) {
it('should not clear falsy DOM properties', () => {
function test(val) {
render(
<div>
<input value={val} />
<table border={val} />
</div>,
scratch
);
}
test('2');
test(false);
expect(scratch.innerHTML).to.equal(
'<div><input><table border="false"></table></div>',
'for false'
);
test('3');
test(null);
expect(scratch.innerHTML).to.equal(
'<div><input><table border=""></table></div>',
'for null'
);
test('4');
test(undefined);
expect(scratch.innerHTML).to.equal(
'<div><input><table border=""></table></div>',
'for undefined'
);
});
}
// Test for preactjs/preact#651
it('should set enumerable boolean attribute', () => {
render(<input spellcheck={false} />, scratch);
expect(scratch.firstChild.spellcheck).to.equal(false);
});
it('should render download attribute', () => {
render(<a download="" />, scratch);
expect(scratch.firstChild.getAttribute('download')).to.equal('');
render(<a download={null} />, scratch);
expect(scratch.firstChild.getAttribute('download')).to.equal(null);
});
it('should not set tagName', () => {
expect(() => render(<input tagName="div" />, scratch)).not.to.throw();
});
it('should apply string attributes', () => {
render(<div foo="bar" data-foo="databar" />, scratch);
expect(serializeHtml(scratch)).to.equal(
'<div data-foo="databar" foo="bar"></div>'
);
});
it('should not serialize function props as attributes', () => {
render(<div click={function a() {}} ONCLICK={function b() {}} />, scratch);
let div = scratch.childNodes[0];
expect(div.attributes.length).to.equal(0);
});
it('should serialize object props as attributes', () => {
render(
<div
foo={{ a: 'b' }}
bar={{
toString() {
return 'abc';
}
}}
/>,
scratch
);
let div = scratch.childNodes[0];
expect(div.attributes.length).to.equal(2);
// Normalize attribute order because it's different in various browsers
let normalized = {};
for (let i = 0; i < div.attributes.length; i++) {
let attr = div.attributes[i];
normalized[attr.name] = attr.value;
}
expect(normalized).to.deep.equal({
bar: 'abc',
foo: '[object Object]'
});
});
it('should apply class as String', () => {
render(<div class="foo" />, scratch);
expect(scratch.childNodes[0]).to.have.property('className', 'foo');
});
it('should alias className to class', () => {
render(<div className="bar" />, scratch);
expect(scratch.childNodes[0]).to.have.property('className', 'bar');
});
it('should support false aria-* attributes', () => {
render(<div aria-checked="false" />, scratch);
expect(scratch.firstChild.getAttribute('aria-checked')).to.equal('false');
});
it('should set checked attribute on custom elements without checked property', () => {
render(<o-checkbox checked />, scratch);
expect(scratch.innerHTML).to.equal(
'<o-checkbox checked="true"></o-checkbox>'
);
});
it('should set value attribute on custom elements without value property', () => {
render(<o-input value="test" />, scratch);
expect(scratch.innerHTML).to.equal('<o-input value="test"></o-input>');
});
it('should mask value on password input elements', () => {
render(<input value="xyz" type="password" />, scratch);
expect(scratch.innerHTML).to.equal('<input type="password">');
});
it('should unset href if null || undefined', () => {
render(
<pre>
<a href="#">href="#"</a>
<a href={undefined}>href="undefined"</a>
<a href={null}>href="null"</a>
<a href={''}>href="''"</a>
</pre>,
scratch
);
const links = scratch.querySelectorAll('a');
expect(links[0].hasAttribute('href')).to.equal(true);
expect(links[1].hasAttribute('href')).to.equal(false);
expect(links[2].hasAttribute('href')).to.equal(false);
expect(links[3].hasAttribute('href')).to.equal(true);
});
describe('dangerouslySetInnerHTML', () => {
it('should support dangerouslySetInnerHTML', () => {
let html = '<b>foo & bar</b>';
// eslint-disable-next-line react/no-danger
render(<div dangerouslySetInnerHTML={{ __html: html }} />, scratch);
expect(scratch.firstChild, 'set').to.have.property('innerHTML', html);
expect(scratch.innerHTML).to.equal('<div>' + html + '</div>');
render(
<div>
a<strong>b</strong>
</div>,
scratch
);
expect(scratch, 'unset').to.have.property(
'innerHTML',
`<div>a<strong>b</strong></div>`
);
// eslint-disable-next-line react/no-danger
render(<div dangerouslySetInnerHTML={{ __html: html }} />, scratch);
expect(scratch.innerHTML, 're-set').to.equal('<div>' + html + '</div>');
});
it('should apply proper mutation for VNodes with dangerouslySetInnerHTML attr', () => {
let thing;
class Thing extends Component {
constructor(props, context) {
super(props, context);
this.state = { html: this.props.html };
thing = this;
}
render(props, { html }) {
// eslint-disable-next-line react/no-danger
return html ? (
<div dangerouslySetInnerHTML={{ __html: html }} />
) : (
<div />
);
}
}
render(<Thing html="<b><i>test</i></b>" />, scratch);
expect(scratch.innerHTML).to.equal('<div><b><i>test</i></b></div>');
thing.setState({ html: false });
rerender();
expect(scratch.innerHTML).to.equal('<div></div>');
thing.setState({ html: '<foo><bar>test</bar></foo>' });
rerender();
expect(scratch.innerHTML).to.equal(
'<div><foo><bar>test</bar></foo></div>'
);
});
it('should not hydrate with dangerouslySetInnerHTML', () => {
let html = '<b>foo & bar</b>';
scratch.innerHTML = `<div>${html}</div>`;
// eslint-disable-next-line react/no-danger
render(<div dangerouslySetInnerHTML={{ __html: html }} />, scratch);
expect(scratch.firstChild).to.have.property('innerHTML', html);
expect(scratch.innerHTML).to.equal(`<div>${html}</div>`);
});
it('should avoid reapplying innerHTML when __html property of dangerouslySetInnerHTML attr remains unchanged', () => {
class Thing extends Component {
render() {
// eslint-disable-next-line react/no-danger
return (
<div dangerouslySetInnerHTML={{ __html: '<span>same</span>' }} />
);
}
}
let thing;
render(<Thing ref={r => (thing = r)} />, scratch);
let firstInnerHTMLChild = scratch.firstChild.firstChild;
// Re-render
thing.forceUpdate();
expect(firstInnerHTMLChild).to.equalNode(scratch.firstChild.firstChild);
});
it('should unmount dangerouslySetInnerHTML', () => {
let set;
const TextDiv = () => (
<div dangerouslySetInnerHTML={{ __html: '' }}>some text</div>
);
class App extends Component {
constructor(props) {
super(props);
set = this.setState.bind(this);
this.state = { show: true };
}
render() {
return this.state.show && <TextDiv />;
}
}
render(<App />, scratch);
expect(scratch.innerHTML).to.equal('<div></div>');
set({ show: false });
rerender();
expect(scratch.innerHTML).to.equal('');
});
});
it('should reconcile mutated DOM attributes', () => {
let check = p => render(<input type="checkbox" checked={p} />, scratch),
value = () => scratch.lastChild.checked,
setValue = p => (scratch.lastChild.checked = p);
check(true);
expect(value()).to.equal(true);
check(false);
expect(value()).to.equal(false);
check(true);
expect(value()).to.equal(true);
setValue(true);
check(false);
expect(value()).to.equal(false);
setValue(false);
check(true);
expect(value()).to.equal(true);
});
it('should reorder child pairs', () => {
render(
<div>
<a>a</a>
<b>b</b>
</div>,
scratch
);
let a = scratch.firstChild.firstChild;
let b = scratch.firstChild.lastChild;
expect(a).to.have.property('nodeName', 'A');
expect(b).to.have.property('nodeName', 'B');
render(
<div>
<b>b</b>
<a>a</a>
</div>,
scratch
);
expect(scratch.firstChild.firstChild).to.equalNode(b);
expect(scratch.firstChild.lastChild).to.equalNode(a);
});
// Discussion: https://github.com/preactjs/preact/issues/287
// <datalist> is not supported in Safari, even though the element
// constructor is present
if (supportsDataList()) {
it('should allow <input list /> to pass through as an attribute', () => {
render(
<div>
<input type="range" min="0" max="100" list="steplist" />
<datalist id="steplist">
<option>0</option>
<option>50</option>
<option>100</option>
</datalist>
</div>,
scratch
);
let html = scratch.firstElementChild.firstElementChild.outerHTML;
expect(sortAttributes(html)).to.equal(
sortAttributes('<input type="range" min="0" max="100" list="steplist">')
);
});
}
// Issue #2284
it('should not throw when setting size to an invalid value', () => {
// These values are usually used to reset the `size` attribute to its
// initial state.
expect(() => render(<input size={undefined} />, scratch)).to.not.throw();
expect(() => render(<input size={null} />, scratch)).to.not.throw();
expect(() => render(<input size={0} />, scratch)).to.not.throw();
});
it('should not execute append operation when child is at last', () => {
// See preactjs/preact#717 for discussion about the issue this addresses
let todoText = 'new todo that I should complete';
let input;
let setText;
let addTodo;
const ENTER = 13;
class TodoList extends Component {
constructor(props) {
super(props);
this.state = { todos: [], text: '' };
setText = this.setText = this.setText.bind(this);
addTodo = this.addTodo = this.addTodo.bind(this);
}
setText(e) {
this.setState({ text: e.target.value });
}
addTodo(e) {
if (e.keyCode === ENTER) {
let { todos, text } = this.state;
todos = todos.concat({ text });
this.setState({ todos, text: '' });
}
}
render() {
const { todos, text } = this.state;
return (
<div onKeyDown={this.addTodo}>
{todos.map(todo => [
<span>{todo.text}</span>,
<span>
{' '}
[ <a href="javascript:;">Delete</a> ]
</span>,
<br />
])}
<input value={text} onInput={this.setText} ref={i => (input = i)} />
</div>
);
}
}
render(<TodoList />, scratch);
// Simulate user typing
input.focus();
input.value = todoText;
setText({
target: input
});
// Commit the user typing setState call
rerender();
// Simulate user pressing enter
addTodo({
keyCode: ENTER
});
// Before Preact rerenders, focus should be on the input
expect(document.activeElement).to.equalNode(input);
rerender();
// After Preact rerenders, focus should remain on the input
expect(document.activeElement).to.equalNode(input);
expect(scratch.innerHTML).to.contain(`<span>${todoText}</span>`);
});
it('should keep value of uncontrolled inputs', () => {
render(<input value={undefined} />, scratch);
scratch.firstChild.value = 'foo';
render(<input value={undefined} />, scratch);
expect(scratch.firstChild.value).to.equal('foo');
});
it('should keep value of uncontrolled checkboxes', () => {
render(<input type="checkbox" checked={undefined} />, scratch);
scratch.firstChild.checked = true;
render(<input type="checkbox" checked={undefined} />, scratch);
expect(scratch.firstChild.checked).to.equal(true);
});
// #2756
it('should set progress value to 0', () => {
render(<progress value={0} max="100" />, scratch);
expect(scratch.firstChild.value).to.equal(0);
expect(scratch.firstChild.getAttribute('value')).to.equal('0');
});
it('should always diff `checked` and `value` properties against the DOM', () => {
// See https://github.com/preactjs/preact/issues/1324
let inputs;
let text;
let checkbox;
class Inputs extends Component {
render() {
return (
<div>
<input value={'Hello'} ref={el => (text = el)} />
<input type="checkbox" checked ref={el => (checkbox = el)} />
</div>
);
}
}
render(<Inputs ref={x => (inputs = x)} />, scratch);
expect(text.value).to.equal('Hello');
expect(checkbox.checked).to.equal(true);
text.value = 'World';
checkbox.checked = false;
inputs.forceUpdate();
rerender();
expect(text.value).to.equal('Hello');
expect(checkbox.checked).to.equal(true);
});
it('should always diff `contenteditable` `innerHTML` against the DOM', () => {
// This tests that we do not cause any cursor jumps in contenteditable fields
// See https://github.com/preactjs/preact/issues/2691
function Editable() {
const [value, setValue] = useState('Hello');
return (
<div
contentEditable
dangerouslySetInnerHTML={{ __html: value }}
onInput={e => setValue(e.currentTarget.innerHTML)}
/>
);
}
render(<Editable />, scratch);
let editable = scratch.querySelector('[contenteditable]');
// modify the innerHTML and set the caret to character 2 to simulate a user typing
editable.innerHTML = 'World';
const range = document.createRange();
range.selectNodeContents(editable);
range.setStart(editable.childNodes[0], 2);
range.collapse(true);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
// ensure we didn't mess up setting the cursor to position 2
expect(window.getSelection().getRangeAt(0).startOffset).to.equal(2);
// dispatch the input event to tell preact to re-render
editable.dispatchEvent(createEvent('input'));
rerender();
// ensure innerHTML is still correct (was not an issue before) and
// more importantly the caret is still at character 2
editable = scratch.querySelector('[contenteditable]');
expect(editable.innerHTML).to.equal('World');
expect(window.getSelection().getRangeAt(0).startOffset).to.equal(2);
});
it('should not re-render when a component returns undefined', () => {
let Dialog = () => undefined;
let updateState;
class App extends Component {
constructor(props) {
super(props);
this.state = { name: '' };
updateState = () => this.setState({ name: ', friend' });
}
render(props, { name }) {
return (
<div>
<Dialog />
<h1 class="fade-down">Hi{name}</h1>
</div>
);
}
}
render(<App />, scratch);
clearLog();
updateState();
rerender();
// We don't log text updates
expect(getLog()).to.deep.equal([]);
});
it('should not lead to stale DOM nodes', () => {
let i = 0;
let updateApp;
class App extends Component {
render() {
updateApp = () => this.forceUpdate();
return <Parent />;
}
}
let updateParent;
function Parent() {
updateParent = () => this.forceUpdate();
i++;
return <Child i={i} />;
}
function Child({ i }) {
return i < 3 ? null : <div>foo</div>;
}
render(<App />, scratch);
updateApp();
rerender();
updateParent();
rerender();
updateApp();
rerender();
// Without a fix it would render: `<div>foo</div><div></div>`
expect(scratch.innerHTML).to.equal('<div>foo</div>');
});
// see preact/#1327
it('should not reuse unkeyed components', () => {
class X extends Component {
constructor() {
super();
this.state = { i: 0 };
}
update() {
this.setState(prev => ({ i: prev.i + 1 }));
}
componentWillUnmount() {
clearTimeout(this.id);
}
render() {
return <div>{this.state.i}</div>;
}
}
let ref;
let updateApp;
class App extends Component {
constructor() {
super();
this.state = { i: 0 };
updateApp = () => this.setState(prev => ({ i: prev.i ^ 1 }));
}
render() {
return (
<div>
{this.state.i === 0 && <X />}
<X ref={node => (ref = node)} />
</div>
);
}
}
render(<App />, scratch);
expect(scratch.textContent).to.equal('00');
ref.update();
updateApp();
rerender();
expect(scratch.textContent).to.equal('1');
updateApp();
rerender();
expect(scratch.textContent).to.equal('01');
});
it('should not cause infinite loop with referentially equal props', () => {
let i = 0;
let prevDiff = options._diff;
options._diff = () => {
if (++i > 10) {
options._diff = prevDiff;
throw new Error('Infinite loop');
}
};
function App({ children, ...rest }) {
return (
<div {...rest}>
<div {...rest}>{children}</div>
</div>
);
}
render(<App>10</App>, scratch);
expect(scratch.textContent).to.equal('10');
options._diff = prevDiff;
});
it('should not call options.debounceRendering unnecessarily', () => {
let comp;
class A extends Component {
constructor(props) {
super(props);
this.state = { updates: 0 };
comp = this;
}
render() {
return <div>{this.state.updates}</div>;
}
}
render(<A />, scratch);
expect(scratch.innerHTML).to.equal('<div>0</div>');
const sandbox = sinon.createSandbox();
try {
sandbox.spy(options, 'debounceRendering');
comp.setState({ updates: 1 }, () => {
comp.setState({ updates: 2 });
});
rerender();
expect(scratch.innerHTML).to.equal('<div>2</div>');
expect(options.debounceRendering).to.have.been.calledOnce;
} finally {
sandbox.restore();
}
});
it('should remove attributes on pre-existing DOM', () => {
const div = document.createElement('div');
div.setAttribute('class', 'red');
const span = document.createElement('span');
const text = document.createTextNode('Hi');
span.appendChild(text);
div.appendChild(span);
scratch.appendChild(div);
const App = () => (
<div>
<span>Bye</span>
</div>
);
render(<App />, scratch);
expect(serializeHtml(scratch)).to.equal('<div><span>Bye</span></div>');
});
it('should remove class attributes', () => {
const App = props => (
<div className={props.class}>
<span>Bye</span>
</div>
);
render(<App class="hi" />, scratch);
expect(scratch.innerHTML).to.equal(
'<div class="hi"><span>Bye</span></div>'
);
render(<App />, scratch);
expect(serializeHtml(scratch)).to.equal('<div><span>Bye</span></div>');
});
it('should not read DOM attributes on render without existing DOM', () => {
const attributesSpy = spyOnElementAttributes();
render(
<div id="wrapper">
<div id="page1">Page 1</div>
</div>,
scratch
);
expect(scratch.innerHTML).to.equal(
'<div id="wrapper"><div id="page1">Page 1</div></div>'
);
// IE11 doesn't allow modifying Element.prototype functions properly.
// Custom spies will never be called.
if (!isIE11) {
expect(attributesSpy.get).to.not.have.been.called;
}
render(
<div id="wrapper">
<div id="page2">Page 2</div>
</div>,
scratch
);
expect(scratch.innerHTML).to.equal(
'<div id="wrapper"><div id="page2">Page 2</div></div>'
);
// IE11 doesn't allow modifying Element.prototype functions properly.
// Custom spies will never be called.
if (!isIE11) {
expect(attributesSpy.get).to.not.have.been.called;
}
});
// #2926
it('should not throw when changing contentEditable to undefined or null', () => {
render(<p contentEditable>foo</p>, scratch);
expect(() =>
render(<p contentEditable={undefined}>foo</p>, scratch)
).to.not.throw();
expect(scratch.firstChild.contentEditable).to.equal('inherit');
expect(() =>
render(<p contentEditable={null}>foo</p>, scratch)
).to.not.throw();
expect(scratch.firstChild.contentEditable).to.equal('inherit');
});
// #2926 Part 2
it('should allow setting contentEditable to false', () => {
render(
<div contentEditable>
<span>editable</span>
<p contentEditable={false}>not editable</p>
</div>,
scratch
);
expect(scratch.firstChild.contentEditable).to.equal('true');
expect(scratch.querySelector('p').contentEditable).to.equal('false');
});
// #3060
it('should reset tabindex on undefined/null', () => {
const defaultValue = isIE11 ? 0 : -1;
render(<div tabIndex={0} />, scratch);
expect(scratch.firstChild.tabIndex).to.equal(0);
render(<div tabIndex={undefined} />, scratch);
expect(scratch.firstChild.tabIndex).to.equal(defaultValue);
render(<div tabIndex={null} />, scratch);
expect(scratch.firstChild.tabIndex).to.equal(defaultValue);
render(<div tabindex={0} />, scratch);
expect(scratch.firstChild.tabIndex).to.equal(0);
render(<div tabindex={undefined} />, scratch);
expect(scratch.firstChild.tabIndex).to.equal(defaultValue);
render(<div tabindex={null} />, scratch);
expect(scratch.firstChild.tabIndex).to.equal(defaultValue);
});
});
| 1 | 17,349 | FYI, I pulled your branch and hacked a little on your test case. This passes for me (you may want to tweak further): <pre> it('should not set empty string for null props in custom elements', () => { customElements.define('x-bar', class extends HTMLElement { val; }); // @ts-ignore render(<x-bar val={null} />, scratch); expect(scratch.childNodes).to.have.length(1); expect(scratch.firstChild).to.have.property('nodeName', 'X-BAR'); expect(scratch.firstChild.attributes.length).to.equal(0); expect(scratch.firstChild.val).to.equal(null); }); </pre> | preactjs-preact | js |
@@ -43,7 +43,7 @@ import android.util.Log;
*/
public class SmartStoreLoadExternalStorageTest extends SmartStoreLoadTest {
- static final int ONE_MEGABYTE = 1024 * 1024;
+ static final int LARGE_BYTES = 512 * 1024;
@Override
protected String getPasscode() { | 1 | /*
* Copyright (c) 2011, salesforce.com, inc.
* All rights reserved.
* Redistribution and use of this software in source and binary forms, with or
* without modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of salesforce.com, inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission of salesforce.com, inc.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.androidsdk.store;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.salesforce.androidsdk.security.Encryptor;
import com.salesforce.androidsdk.smartstore.store.IndexSpec;
import com.salesforce.androidsdk.smartstore.store.SmartStore;
import com.salesforce.androidsdk.smartstore.store.SmartStore.Type;
import com.salesforce.androidsdk.smartstore.store.SoupSpec;
import android.util.Log;
/**
* Set of tests for the smart store loading numerous and/or large entries and querying them back
*/
public class SmartStoreLoadExternalStorageTest extends SmartStoreLoadTest {
static final int ONE_MEGABYTE = 1024 * 1024;
@Override
protected String getPasscode() {
return Encryptor.hash("test123", "hashing-key");
}
@Override
protected void registerSoup(SmartStore store, String soupName, IndexSpec[] indexSpecs) {
store.registerSoupWithSpec(new SoupSpec(soupName, SoupSpec.FEATURE_EXTERNAL_STORAGE), indexSpecs);
}
// Test very large payloads for smartstore
public void testUpsertLargePayload() throws JSONException {
setupSoup(TEST_SOUP, 1, Type.string);
JSONObject entry = new JSONObject();
for (int i = 0; i < 5; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < ONE_MEGABYTE; j++) {
sb.append(i);
}
entry.put("value_" + i, sb.toString());
}
// Upsert
long start = System.currentTimeMillis();
store.upsert(TEST_SOUP, entry);
long end = System.currentTimeMillis();
// Log time taken
Log.i("SmartStoreLoadTest", "Upserting 5MB+ payload time taken: " + (end - start) + " ms");
// Verify
JSONArray result = store.retrieve(TEST_SOUP, 1L);
for (int i = 0; i < 5; i++) {
assertTrue("Value at index " + i + " is incorrect", result.getJSONObject(0).getString("value_" + i).startsWith("" + i));
}
}
@Override
public void testAlterSoupJSON1Indexing() throws JSONException {
// json1 is not compatible with external storage.
}
@Override
public void testUpsertQuery1JSON1Index1field20characters() throws JSONException {
// json1 is not compatible with external storage.
}
@Override
public void testUpsertQuery1JSON1Index1field1000characters() throws JSONException {
// json1 is not compatible with external storage.
}
@Override
public void testUpsertQuery1JSON1Index10fields20characters() throws JSONException {
// json1 is not compatible with external storage.
}
@Override
public void testUpsertQuery10JSON1Indexes10fields20characters() throws JSONException {
// json1 is not compatible with external storage.
}
}
| 1 | 15,456 | It is the maximum value that the configured emulator can support. | forcedotcom-SalesforceMobileSDK-Android | java |
@@ -210,14 +210,17 @@ def _load_session(name):
name: The name of the session to load, or None to read state file.
"""
state_config = objreg.get('state-config')
+ session_manager = objreg.get('session-manager')
if name is None:
try:
name = state_config['general']['session']
except KeyError:
# No session given as argument and none in the session file ->
# start without loading a session
- return
- session_manager = objreg.get('session-manager')
+ if session_manager.exists('_autosave'):
+ name = '_autosave'
+ else:
+ return
try:
session_manager.load(name)
except sessions.SessionNotFoundError: | 1 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2016 Florian Bruhin (The Compiler) <[email protected]>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""Initialization of qutebrowser and application-wide things."""
import os
import sys
import subprocess
import configparser
import functools
import json
import shutil
import tempfile
import atexit
import datetime
import tokenize
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QDesktopServices, QPixmap, QIcon, QWindow
from PyQt5.QtCore import (pyqtSlot, qInstallMessageHandler, QTimer, QUrl,
QObject, QEvent, pyqtSignal)
try:
import hunter
except ImportError:
hunter = None
import qutebrowser
import qutebrowser.resources
from qutebrowser.completion.models import instances as completionmodels
from qutebrowser.commands import cmdutils, runners, cmdexc
from qutebrowser.config import style, config, websettings, configexc
from qutebrowser.browser import urlmarks, adblock, history, browsertab
from qutebrowser.browser.webkit import cookies, cache, downloads
from qutebrowser.browser.webkit.network import (webkitqutescheme, proxy,
networkmanager)
from qutebrowser.mainwindow import mainwindow
from qutebrowser.misc import (readline, ipc, savemanager, sessions,
crashsignal, earlyinit)
from qutebrowser.misc import utilcmds # pylint: disable=unused-import
from qutebrowser.utils import (log, version, message, utils, qtutils, urlutils,
objreg, usertypes, standarddir, error, debug)
# We import utilcmds to run the cmdutils.register decorators.
qApp = None
def run(args):
"""Initialize everything and run the application."""
if args.temp_basedir:
args.basedir = tempfile.mkdtemp(prefix='qutebrowser-basedir-')
quitter = Quitter(args)
objreg.register('quitter', quitter)
global qApp
qApp = Application(args)
qApp.setOrganizationName("qutebrowser")
qApp.setApplicationName("qutebrowser")
qApp.setApplicationVersion(qutebrowser.__version__)
qApp.lastWindowClosed.connect(quitter.on_last_window_closed)
log.init.debug("Initializing directories...")
standarddir.init(args)
if args.version:
print(version.version())
sys.exit(usertypes.Exit.ok)
crash_handler = crashsignal.CrashHandler(
app=qApp, quitter=quitter, args=args, parent=qApp)
crash_handler.activate()
objreg.register('crash-handler', crash_handler)
signal_handler = crashsignal.SignalHandler(app=qApp, quitter=quitter,
parent=qApp)
signal_handler.activate()
objreg.register('signal-handler', signal_handler)
try:
server = ipc.send_or_listen(args)
except ipc.Error:
# ipc.send_or_listen already displays the error message for us.
# We didn't really initialize much so far, so we just quit hard.
sys.exit(usertypes.Exit.err_ipc)
if server is None:
sys.exit(usertypes.Exit.ok)
else:
server.got_args.connect(lambda args, target_arg, cwd:
process_pos_args(args, cwd=cwd, via_ipc=True,
target_arg=target_arg))
init(args, crash_handler)
ret = qt_mainloop()
return ret
def qt_mainloop():
"""Simple wrapper to get a nicer stack trace for segfaults.
WARNING: misc/crashdialog.py checks the stacktrace for this function
name, so if this is changed, it should be changed there as well!
"""
return qApp.exec_()
def init(args, crash_handler):
"""Initialize everything.
Args:
args: The argparse namespace.
crash_handler: The CrashHandler instance.
"""
log.init.debug("Starting init...")
qApp.setQuitOnLastWindowClosed(False)
_init_icon()
utils.actute_warning()
try:
_init_modules(args, crash_handler)
except (OSError, UnicodeDecodeError) as e:
error.handle_fatal_exc(e, args, "Error while initializing!",
pre_text="Error while initializing")
sys.exit(usertypes.Exit.err_init)
QTimer.singleShot(0, functools.partial(_process_args, args))
QTimer.singleShot(10, functools.partial(_init_late_modules, args))
log.init.debug("Initializing eventfilter...")
event_filter = EventFilter(qApp)
qApp.installEventFilter(event_filter)
objreg.register('event-filter', event_filter)
log.init.debug("Connecting signals...")
config_obj = objreg.get('config')
config_obj.style_changed.connect(style.get_stylesheet.cache_clear)
qApp.focusChanged.connect(on_focus_changed)
QDesktopServices.setUrlHandler('http', open_desktopservices_url)
QDesktopServices.setUrlHandler('https', open_desktopservices_url)
QDesktopServices.setUrlHandler('qute', open_desktopservices_url)
log.init.debug("Init done!")
crash_handler.raise_crashdlg()
def _init_icon():
"""Initialize the icon of qutebrowser."""
icon = QIcon()
fallback_icon = QIcon()
for size in [16, 24, 32, 48, 64, 96, 128, 256, 512]:
filename = ':/icons/qutebrowser-{}x{}.png'.format(size, size)
pixmap = QPixmap(filename)
qtutils.ensure_not_null(pixmap)
fallback_icon.addPixmap(pixmap)
qtutils.ensure_not_null(fallback_icon)
icon = QIcon.fromTheme('qutebrowser', fallback_icon)
qtutils.ensure_not_null(icon)
qApp.setWindowIcon(icon)
def _process_args(args):
"""Open startpage etc. and process commandline args."""
config_obj = objreg.get('config')
for sect, opt, val in args.temp_settings:
try:
config_obj.set('temp', sect, opt, val)
except (configexc.Error, configparser.Error) as e:
message.error("set: {} - {}".format(e.__class__.__name__, e))
if not args.override_restore:
_load_session(args.session)
session_manager = objreg.get('session-manager')
if not session_manager.did_load:
log.init.debug("Initializing main window...")
window = mainwindow.MainWindow()
if not args.nowindow:
window.show()
qApp.setActiveWindow(window)
process_pos_args(args.command)
_open_startpage()
_open_quickstart(args)
delta = datetime.datetime.now() - earlyinit.START_TIME
log.init.debug("Init finished after {}s".format(delta.total_seconds()))
def _load_session(name):
"""Load the default session.
Args:
name: The name of the session to load, or None to read state file.
"""
state_config = objreg.get('state-config')
if name is None:
try:
name = state_config['general']['session']
except KeyError:
# No session given as argument and none in the session file ->
# start without loading a session
return
session_manager = objreg.get('session-manager')
try:
session_manager.load(name)
except sessions.SessionNotFoundError:
message.error("Session {} not found!".format(name))
except sessions.SessionError as e:
message.error("Failed to load session {}: {}".format(name, e))
try:
del state_config['general']['session']
except KeyError:
pass
# If this was a _restart session, delete it.
if name == '_restart':
session_manager.delete('_restart')
def process_pos_args(args, via_ipc=False, cwd=None, target_arg=None):
"""Process positional commandline args.
URLs to open have no prefix, commands to execute begin with a colon.
Args:
args: A list of arguments to process.
via_ipc: Whether the arguments were transmitted over IPC.
cwd: The cwd to use for fuzzy_url.
target_arg: Command line argument received by a running instance via
ipc. If the --target argument was not specified, target_arg
will be an empty string.
"""
if via_ipc and not args:
win_id = mainwindow.get_window(via_ipc, force_window=True)
_open_startpage(win_id)
return
win_id = None
for cmd in args:
if cmd.startswith(':'):
if win_id is None:
win_id = mainwindow.get_window(via_ipc, force_tab=True)
log.init.debug("Startup cmd {!r}".format(cmd))
commandrunner = runners.CommandRunner(win_id)
commandrunner.run_safely_init(cmd[1:])
elif not cmd:
log.init.debug("Empty argument")
win_id = mainwindow.get_window(via_ipc, force_window=True)
else:
if via_ipc and target_arg and target_arg != 'auto':
open_target = target_arg
else:
open_target = config.get('general', 'new-instance-open-target')
win_id = mainwindow.get_window(via_ipc, force_target=open_target)
tabbed_browser = objreg.get('tabbed-browser', scope='window',
window=win_id)
log.init.debug("Startup URL {}".format(cmd))
if not cwd: # could also be an empty string due to the PyQt signal
cwd = None
try:
url = urlutils.fuzzy_url(cmd, cwd, relative=True)
except urlutils.InvalidUrlError as e:
message.error("Error in startup argument '{}': {}".format(
cmd, e))
else:
background = open_target in ['tab-bg', 'tab-bg-silent']
tabbed_browser.tabopen(url, background=background,
explicit=True)
def _open_startpage(win_id=None):
"""Open startpage.
The startpage is never opened if the given windows are not empty.
Args:
win_id: If None, open startpage in all empty windows.
If set, open the startpage in the given window.
"""
if win_id is not None:
window_ids = [win_id]
else:
window_ids = objreg.window_registry
for cur_win_id in window_ids:
tabbed_browser = objreg.get('tabbed-browser', scope='window',
window=cur_win_id)
if tabbed_browser.count() == 0:
log.init.debug("Opening startpage")
for urlstr in config.get('general', 'startpage'):
try:
url = urlutils.fuzzy_url(urlstr, do_search=False)
except urlutils.InvalidUrlError as e:
message.error("Error when opening startpage: {}".format(e))
tabbed_browser.tabopen(QUrl('about:blank'))
else:
tabbed_browser.tabopen(url)
def _open_quickstart(args):
"""Open quickstart if it's the first start.
Args:
args: The argparse namespace.
"""
if args.datadir is not None or args.basedir is not None:
# With --datadir or --basedir given, don't open quickstart.
return
state_config = objreg.get('state-config')
try:
quickstart_done = state_config['general']['quickstart-done'] == '1'
except KeyError:
quickstart_done = False
if not quickstart_done:
tabbed_browser = objreg.get('tabbed-browser', scope='window',
window='last-focused')
tabbed_browser.tabopen(
QUrl('http://www.qutebrowser.org/quickstart.html'))
state_config['general']['quickstart-done'] = '1'
def _save_version():
"""Save the current version to the state config."""
state_config = objreg.get('state-config')
state_config['general']['version'] = qutebrowser.__version__
def on_focus_changed(_old, new):
"""Register currently focused main window in the object registry."""
if new is None:
return
if not isinstance(new, QWidget):
log.misc.debug("on_focus_changed called with non-QWidget {!r}".format(
new))
return
window = new.window()
if isinstance(window, mainwindow.MainWindow):
objreg.register('last-focused-main-window', window, update=True)
# A focused window must also be visible, and in this case we should
# consider it as the most recently looked-at window
objreg.register('last-visible-main-window', window, update=True)
def open_desktopservices_url(url):
"""Handler to open a URL via QDesktopServices."""
win_id = mainwindow.get_window(via_ipc=True, force_window=False)
tabbed_browser = objreg.get('tabbed-browser', scope='window',
window=win_id)
tabbed_browser.tabopen(url)
def _init_modules(args, crash_handler):
"""Initialize all 'modules' which need to be initialized.
Args:
args: The argparse namespace.
crash_handler: The CrashHandler instance.
"""
# pylint: disable=too-many-statements
log.init.debug("Initializing save manager...")
save_manager = savemanager.SaveManager(qApp)
objreg.register('save-manager', save_manager)
save_manager.add_saveable('version', _save_version)
log.init.debug("Initializing network...")
networkmanager.init()
log.init.debug("Initializing readline-bridge...")
readline_bridge = readline.ReadlineBridge()
objreg.register('readline-bridge', readline_bridge)
log.init.debug("Initializing config...")
config.init(qApp)
save_manager.init_autosave()
log.init.debug("Initializing web history...")
history.init(qApp)
log.init.debug("Initializing crashlog...")
if not args.no_err_windows:
crash_handler.handle_segfault()
log.init.debug("Initializing sessions...")
sessions.init(qApp)
log.init.debug("Initializing js-bridge...")
js_bridge = webkitqutescheme.JSBridge(qApp)
objreg.register('js-bridge', js_bridge)
log.init.debug("Initializing websettings...")
websettings.init()
log.init.debug("Initializing adblock...")
host_blocker = adblock.HostBlocker()
host_blocker.read_hosts()
objreg.register('host-blocker', host_blocker)
log.init.debug("Initializing quickmarks...")
quickmark_manager = urlmarks.QuickmarkManager(qApp)
objreg.register('quickmark-manager', quickmark_manager)
log.init.debug("Initializing bookmarks...")
bookmark_manager = urlmarks.BookmarkManager(qApp)
objreg.register('bookmark-manager', bookmark_manager)
log.init.debug("Initializing proxy...")
proxy.init()
log.init.debug("Initializing cookies...")
cookie_jar = cookies.CookieJar(qApp)
ram_cookie_jar = cookies.RAMCookieJar(qApp)
objreg.register('cookie-jar', cookie_jar)
objreg.register('ram-cookie-jar', ram_cookie_jar)
log.init.debug("Initializing cache...")
diskcache = cache.DiskCache(standarddir.cache(), parent=qApp)
objreg.register('cache', diskcache)
log.init.debug("Initializing completions...")
completionmodels.init()
log.init.debug("Misc initialization...")
if config.get('ui', 'hide-wayland-decoration'):
os.environ['QT_WAYLAND_DISABLE_WINDOWDECORATION'] = '1'
else:
os.environ.pop('QT_WAYLAND_DISABLE_WINDOWDECORATION', None)
temp_downloads = downloads.TempDownloadManager(qApp)
objreg.register('temporary-downloads', temp_downloads)
# Init backend-specific stuff
browsertab.init(args)
def _init_late_modules(args):
"""Initialize modules which can be inited after the window is shown."""
log.init.debug("Reading web history...")
reader = objreg.get('web-history').async_read()
with debug.log_time(log.init, 'Reading history'):
while True:
QApplication.processEvents()
try:
next(reader)
except StopIteration:
break
except (OSError, UnicodeDecodeError) as e:
error.handle_fatal_exc(e, args, "Error while initializing!",
pre_text="Error while initializing")
sys.exit(usertypes.Exit.err_init)
class Quitter:
"""Utility class to quit/restart the QApplication.
Attributes:
quit_status: The current quitting status.
_shutting_down: Whether we're currently shutting down.
_args: The argparse namespace.
"""
def __init__(self, args):
self.quit_status = {
'crash': True,
'tabs': False,
'main': False,
}
self._shutting_down = False
self._args = args
def on_last_window_closed(self):
"""Slot which gets invoked when the last window was closed."""
self.shutdown(last_window=True)
def _compile_modules(self):
"""Compile all modules to catch SyntaxErrors."""
if os.path.basename(sys.argv[0]) == 'qutebrowser':
# Launched via launcher script
return
elif hasattr(sys, 'frozen'):
return
else:
path = os.path.abspath(os.path.dirname(qutebrowser.__file__))
if not os.path.isdir(path):
# Probably running from a python egg.
return
for dirpath, _dirnames, filenames in os.walk(path):
for fn in filenames:
if os.path.splitext(fn)[1] == '.py' and os.path.isfile(fn):
with tokenize.open(os.path.join(dirpath, fn)) as f:
compile(f.read(), fn, 'exec')
def _get_restart_args(self, pages=(), session=None):
"""Get the current working directory and args to relaunch qutebrowser.
Args:
pages: The pages to re-open.
session: The session to load, or None.
Return:
An (args, cwd) tuple.
args: The commandline as a list of strings.
cwd: The current working directory as a string.
"""
if os.path.basename(sys.argv[0]) == 'qutebrowser':
# Launched via launcher script
args = [sys.argv[0]]
cwd = None
elif hasattr(sys, 'frozen'):
args = [sys.executable]
cwd = os.path.abspath(os.path.dirname(sys.executable))
else:
args = [sys.executable, '-m', 'qutebrowser']
cwd = os.path.join(os.path.abspath(os.path.dirname(
qutebrowser.__file__)), '..')
if not os.path.isdir(cwd):
# Probably running from a python egg. Let's fallback to
# cwd=None and see if that works out.
# See https://github.com/The-Compiler/qutebrowser/issues/323
cwd = None
# Add all open pages so they get reopened.
page_args = []
for win in pages:
page_args.extend(win)
page_args.append('')
# Serialize the argparse namespace into json and pass that to the new
# process via --json-args.
# We do this as there's no way to "unparse" the namespace while
# ignoring some arguments.
argdict = vars(self._args)
argdict['session'] = None
argdict['url'] = []
argdict['command'] = page_args[:-1]
argdict['json_args'] = None
# Ensure the given session (or none at all) gets opened.
if session is None:
argdict['session'] = None
argdict['override_restore'] = True
else:
argdict['session'] = session
argdict['override_restore'] = False
# Ensure :restart works with --temp-basedir
if self._args.temp_basedir:
argdict['temp_basedir'] = False
argdict['temp_basedir_restarted'] = True
# Dump the data
data = json.dumps(argdict)
args += ['--json-args', data]
log.destroy.debug("args: {}".format(args))
log.destroy.debug("cwd: {}".format(cwd))
return args, cwd
@cmdutils.register(instance='quitter', name='restart')
def restart_cmd(self):
"""Restart qutebrowser while keeping existing tabs open."""
try:
ok = self.restart(session='_restart')
except sessions.SessionError as e:
log.destroy.exception("Failed to save session!")
raise cmdexc.CommandError("Failed to save session: {}!".format(e))
except SyntaxError as e:
log.destroy.exception("Got SyntaxError")
raise cmdexc.CommandError("SyntaxError in {}:{}: {}".format(
e.filename, e.lineno, e))
if ok:
self.shutdown(restart=True)
def restart(self, pages=(), session=None):
"""Inner logic to restart qutebrowser.
The "better" way to restart is to pass a session (_restart usually) as
that'll save the complete state.
However we don't do that (and pass a list of pages instead) when we
restart because of an exception, as that's a lot simpler and we don't
want to risk anything going wrong.
Args:
pages: A list of URLs to open.
session: The session to load, or None.
Return:
True if the restart succeeded, False otherwise.
"""
self._compile_modules()
log.destroy.debug("sys.executable: {}".format(sys.executable))
log.destroy.debug("sys.path: {}".format(sys.path))
log.destroy.debug("sys.argv: {}".format(sys.argv))
log.destroy.debug("frozen: {}".format(hasattr(sys, 'frozen')))
# Save the session if one is given.
if session is not None:
session_manager = objreg.get('session-manager')
session_manager.save(session)
# Open a new process and immediately shutdown the existing one
try:
args, cwd = self._get_restart_args(pages, session)
if cwd is None:
subprocess.Popen(args)
else:
subprocess.Popen(args, cwd=cwd)
except OSError:
log.destroy.exception("Failed to restart")
return False
else:
return True
@cmdutils.register(instance='quitter', name=['quit', 'q'],
ignore_args=True)
def shutdown(self, status=0, session=None, last_window=False,
restart=False):
"""Quit qutebrowser.
Args:
status: The status code to exit with.
session: A session name if saving should be forced.
last_window: If the shutdown was triggered due to the last window
closing.
restart: If we're planning to restart.
"""
if self._shutting_down:
return
self._shutting_down = True
log.destroy.debug("Shutting down with status {}, session {}...".format(
status, session))
session_manager = objreg.get('session-manager')
if session is not None:
session_manager.save(session, last_window=last_window,
load_next_time=True)
elif config.get('general', 'save-session'):
session_manager.save(sessions.default, last_window=last_window,
load_next_time=True)
deferrer = False
for win_id in objreg.window_registry:
prompter = objreg.get('prompter', None, scope='window',
window=win_id)
if prompter is not None and prompter.shutdown():
deferrer = True
if deferrer:
# If shutdown was called while we were asking a question, we're in
# a still sub-eventloop (which gets quit now) and not in the main
# one.
# This means we need to defer the real shutdown to when we're back
# in the real main event loop, or we'll get a segfault.
log.destroy.debug("Deferring real shutdown because question was "
"active.")
QTimer.singleShot(0, functools.partial(self._shutdown, status,
restart=restart))
else:
# If we have no questions to shut down, we are already in the real
# event loop, so we can shut down immediately.
self._shutdown(status, restart=restart)
def _shutdown(self, status, restart):
"""Second stage of shutdown."""
log.destroy.debug("Stage 2 of shutting down...")
if qApp is None:
# No QApplication exists yet, so quit hard.
sys.exit(status)
# Remove eventfilter
try:
log.destroy.debug("Removing eventfilter...")
qApp.removeEventFilter(objreg.get('event-filter'))
except AttributeError:
pass
# Close all windows
QApplication.closeAllWindows()
# Shut down IPC
try:
objreg.get('ipc-server').shutdown()
except KeyError:
pass
# Save everything
try:
save_manager = objreg.get('save-manager')
except KeyError:
log.destroy.debug("Save manager not initialized yet, so not "
"saving anything.")
else:
for key in save_manager.saveables:
try:
save_manager.save(key, is_exit=True)
except OSError as e:
error.handle_fatal_exc(
e, self._args, "Error while saving!",
pre_text="Error while saving {}".format(key))
# Disable storage so removing tempdir will work
websettings.shutdown()
# Re-enable faulthandler to stdout, then remove crash log
log.destroy.debug("Deactivating crash log...")
objreg.get('crash-handler').destroy_crashlogfile()
# Delete temp basedir
if ((self._args.temp_basedir or self._args.temp_basedir_restarted) and
not restart):
atexit.register(shutil.rmtree, self._args.basedir,
ignore_errors=True)
# Delete temp download dir
objreg.get('temporary-downloads').cleanup()
# If we don't kill our custom handler here we might get segfaults
log.destroy.debug("Deactivating message handler...")
qInstallMessageHandler(None)
# Now we can hopefully quit without segfaults
log.destroy.debug("Deferring QApplication::exit...")
objreg.get('signal-handler').deactivate()
# We use a singleshot timer to exit here to minimize the likelihood of
# segfaults.
QTimer.singleShot(0, functools.partial(qApp.exit, status))
@cmdutils.register(instance='quitter', name='wq')
@cmdutils.argument('name', completion=usertypes.Completion.sessions)
def save_and_quit(self, name=sessions.default):
"""Save open pages and quit.
Args:
name: The name of the session.
"""
self.shutdown(session=name)
class Application(QApplication):
"""Main application instance.
Attributes:
_args: ArgumentParser instance.
"""
new_window = pyqtSignal(mainwindow.MainWindow)
def __init__(self, args):
"""Constructor.
Args:
Argument namespace from argparse.
"""
qt_args = qtutils.get_args(args)
log.init.debug("Qt arguments: {}, based on {}".format(qt_args, args))
super().__init__(qt_args)
log.init.debug("Initializing application...")
self._args = args
objreg.register('args', args)
objreg.register('app', self)
self.launch_time = datetime.datetime.now()
self.focusObjectChanged.connect(self.on_focus_object_changed)
@pyqtSlot(QObject)
def on_focus_object_changed(self, obj):
"""Log when the focus object changed."""
log.misc.debug("Focus object changed: {!r}".format(obj))
def __repr__(self):
return utils.get_repr(self)
def exit(self, status):
"""Extend QApplication::exit to log the event."""
log.destroy.debug("Now calling QApplication::exit.")
if self._args.debug_exit:
if hunter is None:
print("Not logging late shutdown because hunter could not be "
"imported!", file=sys.stderr)
else:
print("Now logging late shutdown.", file=sys.stderr)
hunter.trace()
super().exit(status)
class EventFilter(QObject):
"""Global Qt event filter.
Attributes:
_activated: Whether the EventFilter is currently active.
_handlers; A {QEvent.Type: callable} dict with the handlers for an
event.
"""
def __init__(self, parent=None):
super().__init__(parent)
self._activated = True
self._handlers = {
QEvent.MouseButtonDblClick: self._handle_mouse_event,
QEvent.MouseButtonPress: self._handle_mouse_event,
QEvent.MouseButtonRelease: self._handle_mouse_event,
QEvent.MouseMove: self._handle_mouse_event,
QEvent.KeyPress: self._handle_key_event,
QEvent.KeyRelease: self._handle_key_event,
}
def _handle_key_event(self, event):
"""Handle a key press/release event.
Args:
event: The QEvent which is about to be delivered.
Return:
True if the event should be filtered, False if it's passed through.
"""
if qApp.activeWindow() not in objreg.window_registry.values():
# Some other window (print dialog, etc.) is focused so we pass the
# event through.
return False
try:
man = objreg.get('mode-manager', scope='window', window='current')
return man.eventFilter(event)
except objreg.RegistryUnavailableError:
# No window available yet, or not a MainWindow
return False
def _handle_mouse_event(self, _event):
"""Handle a mouse event.
Args:
_event: The QEvent which is about to be delivered.
Return:
True if the event should be filtered, False if it's passed through.
"""
# Mouse cursor shown (overrideCursor None) -> don't filter event
# Mouse cursor hidden (overrideCursor not None) -> filter event
return qApp.overrideCursor() is not None
def eventFilter(self, obj, event):
"""Handle an event.
Args:
obj: The object which will get the event.
event: The QEvent which is about to be delivered.
Return:
True if the event should be filtered, False if it's passed through.
"""
try:
if not self._activated:
return False
if not isinstance(obj, QWindow):
# We already handled this same event at some point earlier, so
# we're not interested in it anymore.
return False
try:
handler = self._handlers[event.type()]
except KeyError:
return False
else:
return handler(event)
except:
# If there is an exception in here and we leave the eventfilter
# activated, we'll get an infinite loop and a stack overflow.
self._activated = False
raise
| 1 | 16,951 | Here, I've been giving priority to the session saved by the user. This means, that if the user quits with `:wq`, then restarts `qutebrowser`, and then `qutebrowser` crashes for some reason, next time `qutebrowser` is restarted, the session saved lastly with `wq` will be restored, and not the one autosaved. What do you think? | qutebrowser-qutebrowser | py |
@@ -64,7 +64,7 @@ func membership(l LedgerReader, addr basics.Address, r basics.Round, p period, s
balanceRound := balanceRound(r, cparams)
seedRound := seedRound(r, cparams)
- record, err := l.BalanceRecord(balanceRound, addr)
+ record, err := l.AccountData(balanceRound, addr)
if err != nil {
err = fmt.Errorf("Service.initializeVote (r=%d): Failed to obtain balance record for address %v in round %d: %v", r, addr, balanceRound, err)
return | 1 | // Copyright (C) 2019-2020 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand. If not, see <https://www.gnu.org/licenses/>.
package agreement
import (
"fmt"
"github.com/algorand/go-algorand/config"
"github.com/algorand/go-algorand/data/basics"
"github.com/algorand/go-algorand/data/committee"
"github.com/algorand/go-algorand/protocol"
)
// A Selector is the input used to define proposers and members of voting
// committees.
type selector struct {
_struct struct{} `codec:""` // not omitempty
Seed committee.Seed `codec:"seed"`
Round basics.Round `codec:"rnd"`
Period period `codec:"per"`
Step step `codec:"step"`
}
// ToBeHashed implements the crypto.Hashable interface.
func (sel selector) ToBeHashed() (protocol.HashID, []byte) {
return protocol.AgreementSelector, protocol.Encode(&sel)
}
// CommitteeSize returns the size of the committee, which is determined by
// Selector.Step.
func (sel selector) CommitteeSize(proto config.ConsensusParams) uint64 {
return sel.Step.committeeSize(proto)
}
func balanceRound(r basics.Round, cparams config.ConsensusParams) basics.Round {
return r.SubSaturate(basics.Round(2 * cparams.SeedRefreshInterval * cparams.SeedLookback))
}
func seedRound(r basics.Round, cparams config.ConsensusParams) basics.Round {
return r.SubSaturate(basics.Round(cparams.SeedLookback))
}
// a helper function for obtaining memberhship verification parameters.
func membership(l LedgerReader, addr basics.Address, r basics.Round, p period, s step) (m committee.Membership, err error) {
cparams, err := l.ConsensusParams(ParamsRound(r))
if err != nil {
return
}
balanceRound := balanceRound(r, cparams)
seedRound := seedRound(r, cparams)
record, err := l.BalanceRecord(balanceRound, addr)
if err != nil {
err = fmt.Errorf("Service.initializeVote (r=%d): Failed to obtain balance record for address %v in round %d: %v", r, addr, balanceRound, err)
return
}
total, err := l.Circulation(balanceRound)
if err != nil {
err = fmt.Errorf("Service.initializeVote (r=%d): Failed to obtain total circulation in round %d: %v", r, balanceRound, err)
return
}
seed, err := l.Seed(seedRound)
if err != nil {
err = fmt.Errorf("Service.initializeVote (r=%d): Failed to obtain seed in round %d: %v", r, seedRound, err)
return
}
m.Record = record
m.Selector = selector{Seed: seed, Round: r, Period: p, Step: s}
m.TotalMoney = total
return m, nil
}
| 1 | 39,885 | this line got me confused for few seconds, as the `AccountData` is both the name of the data structure as well as the function name. I think that `GetAccountData` is a better choice for a name. ( note that the same applies for the previous `BalanceRecord` function name ) | algorand-go-algorand | go |
@@ -61,11 +61,7 @@ public:
void helper_block_for_at_least_entries(
uint32_t amount)
{
- std::unique_lock<std::mutex> lck(*xml_mutex_);
- mock_consumer->cv().wait(lck, [this, amount]
- {
- return mock_consumer->ConsumedEntriesSize_nts() >= amount;
- });
+ mock_consumer->wait_for_at_least_entries(amount);
}
MockConsumer* mock_consumer; | 1 | // Copyright 2020 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
#include <thread>
#include <mutex>
#include <fastrtps/xmlparser/XMLParser.h>
#include <fastrtps/xmlparser/XMLTree.h>
#include <fastrtps/xmlparser/XMLProfileManager.h>
#include <fastrtps/utils/IPLocator.h>
#include "../logging/mock/MockConsumer.h"
#include "wrapper/XMLParserTest.hpp"
#include <tinyxml2.h>
#include <gtest/gtest.h>
#include <fstream>
#include <sstream>
using namespace eprosima::fastdds::dds;
using namespace eprosima::fastrtps;
using namespace eprosima::fastrtps::rtps;
using eprosima::fastrtps::xmlparser::BaseNode;
using eprosima::fastrtps::xmlparser::DataNode;
using eprosima::fastrtps::xmlparser::NodeType;
using eprosima::fastrtps::xmlparser::XMLP_ret;
using eprosima::fastrtps::xmlparser::XMLParser;
using eprosima::fastrtps::xmlparser::up_participant_t;
using eprosima::fastrtps::xmlparser::up_node_participant_t;
using eprosima::fastrtps::xmlparser::node_participant_t;
using eprosima::fastrtps::xmlparser::sp_transport_t;
using eprosima::fastrtps::xmlparser::XMLProfileManager;
class XMLParserTests : public ::testing::Test
{
public:
XMLParserTests()
{
}
~XMLParserTests()
{
Log::Reset();
Log::KillThread();
}
void helper_block_for_at_least_entries(
uint32_t amount)
{
std::unique_lock<std::mutex> lck(*xml_mutex_);
mock_consumer->cv().wait(lck, [this, amount]
{
return mock_consumer->ConsumedEntriesSize_nts() >= amount;
});
}
MockConsumer* mock_consumer;
mutable std::mutex* xml_mutex_;
protected:
void SetUp() override
{
xml_mutex_ = new std::mutex();
}
void TearDown() override
{
delete xml_mutex_;
xml_mutex_ = nullptr;
}
};
/*
* This test checks the proper parsing of the <lifespan> xml element to LifespanQosPolicy, and negative cases.
* 1. Correct parsing of a valid element.
* 2. Check an empty definition of <sec> and <nanosec> in <duration> child xml element.
* 3. Check an bad element as a child xml element.
* 4. Check an empty xml definition.
*/
TEST_F(XMLParserTests, getXMLLifespanQos)
{
uint8_t ident = 1;
LifespanQosPolicy lifespan;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<lifespan>\
<duration>\
<sec>%s</sec>\
<nanosec>%s</nanosec>\
</duration>\
%s\
</lifespan>\
";
char xml[500];
// Valid XML
sprintf(xml, xml_p, "5", "0", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLLifespanQos_wrapper(titleElement, lifespan, ident));
EXPECT_EQ(lifespan.duration.seconds, 5);
EXPECT_EQ(lifespan.duration.nanosec, 0u);
// Missing data
sprintf(xml, xml_p, "", "", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLifespanQos_wrapper(titleElement, lifespan, ident));
// Invalid element
sprintf(xml, xml_p, "5", "0", "<bad_element></bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLifespanQos_wrapper(titleElement, lifespan, ident));
// Missing element
const char* miss_xml =
"\
<lifespan></lifespan>\
";
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(miss_xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLifespanQos_wrapper(titleElement, lifespan, ident));
}
/*
* This test checks the proper parsing of the <disablePositiveACKs> xml element to DisablePositiveACKsQosPolicy,
* and negative cases.
* 1. Correct parsing of a valid element.
* 2. Check an empty definition of <enabled>.
* 3. Check an empty definition of <sec> and <nanosec> in <duration> child xml element and empty <enabled>.
* 4. Check an bad element as a child xml element.
*/
TEST_F(XMLParserTests, getXMLDisablePositiveAcksQos)
{
uint8_t ident = 1;
DisablePositiveACKsQosPolicy disablePositiveACKs;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<disablePositiveAcks>\
<enabled>%s</enabled>\
<duration>\
<sec>%s</sec>\
<nanosec>%s</nanosec>\
</duration>\
%s\
</disablePositiveAcks>\
";
char xml[500];
// Valid XML
sprintf(xml, xml_p, "true", "5", "0", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK,
XMLParserTest::getXMLDisablePositiveAcksQos_wrapper(titleElement, disablePositiveACKs, ident));
EXPECT_EQ(disablePositiveACKs.enabled, true);
EXPECT_EQ(disablePositiveACKs.enabled, true);
EXPECT_EQ(disablePositiveACKs.duration.seconds, 5);
EXPECT_EQ(disablePositiveACKs.duration.nanosec, 0u);
// Missing data - enabled
sprintf(xml, xml_p, "", "", "", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLDisablePositiveAcksQos_wrapper(titleElement, disablePositiveACKs, ident));
// Missing data - duration
sprintf(xml, xml_p, "true", "", "", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLDisablePositiveAcksQos_wrapper(titleElement, disablePositiveACKs, ident));
// Invalid element
sprintf(xml, xml_p, "true", "5", "0", "<bad_element></bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLDisablePositiveAcksQos_wrapper(titleElement, disablePositiveACKs, ident));
}
/*
* This test checks the proper parsing of the <disable_heartbeat_piggyback> xml element to WriterQos,
* and negative cases.
* 1. Correct parsing of a valid element.
* 2. Check an bad element as a child xml element.
* 3. Check an empty xml definition.
*/
TEST_F(XMLParserTests, get_xml_disable_heartbeat_piggyback)
{
uint8_t ident = 1;
WriterQos writer_qos;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<qos>\
<disable_heartbeat_piggyback>%s</disable_heartbeat_piggyback>\
</qos>\
";
char xml[500];
// Valid XML
sprintf(xml, xml_p, "true");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK,
XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, writer_qos, ident));
EXPECT_EQ(true, writer_qos.disable_heartbeat_piggyback);
// Invalid element
sprintf(xml, xml_p, "fail");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, writer_qos, ident));
// Missing element
const char* miss_xml =
"\
<qos>\
<disable_heartbeat_piggyback></disable_heartbeat_piggyback>\
</qos>\
";
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(miss_xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, writer_qos, ident));
}
/*
* This test checks the parsing of a <udpv6> element from a list of locators.
* 1. Correct parsing of a valid element.
* 2. Check an empty definition of <port> .
* 3. Check an empty definition of <address>.
* 4. Check an bad element as a child xml element.
*/
TEST_F(XMLParserTests, getXMLLocatorUDPv6)
{
uint8_t ident = 1;
LocatorList_t list;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<unicastLocatorList>\
<locator>\
<udpv6>\
<port>%s</port>\
<address>%s</address>\
%s\
</udpv6>\
</locator>\
</unicastLocatorList>\
";
char xml[500];
// Valid XML
sprintf(xml, xml_p, "8844", "::1", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLLocatorList_wrapper(titleElement, list, ident));
EXPECT_EQ(list.begin()->port, 8844u);
EXPECT_EQ(list.begin()->address[15], 1);
EXPECT_EQ(list.begin()->kind, LOCATOR_KIND_UDPv6);
// Missing data - port
sprintf(xml, xml_p, "", "::1", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLocatorList_wrapper(titleElement, list, ident));
// Missing data - address
sprintf(xml, xml_p, "8844", "", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLocatorList_wrapper(titleElement, list, ident));
// Invalid element
sprintf(xml, xml_p, "8844", "::1", "<bad_element></bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLocatorList_wrapper(titleElement, list, ident));
}
/*
* This test checks the parsing of a <tcpv4> element from a list of locators.
* 1. Correct parsing of a valid element.
* 2. Check an empty definition of <physical_port> .
* 3. Check an empty definition of <port>.
* 4. Check an empty definition of <unique_lan_id>.
* 5. Check an empty definition of <wan_address>.
* 6. Check an empty definition of <address>.
* 7. Check an bad element as a child xml element.
*/
TEST_F(XMLParserTests, getXMLLocatorTCPv4)
{
uint8_t ident = 1;
LocatorList_t list;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<unicastLocatorList>\
<locator>\
<tcpv4>\
<physical_port>%s</physical_port>\
<port>%s</port>\
<unique_lan_id>%s</unique_lan_id>\
<wan_address>%s</wan_address>\
<address>%s</address>\
%s\
</tcpv4>\
</locator>\
</unicastLocatorList>\
";
char xml[1000];
// Valid XML
sprintf(xml, xml_p, "5100", "8844", "192.168.1.1.1.1.2.55", "80.80.99.45", "192.168.1.55", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLLocatorList_wrapper(titleElement, list, ident));
EXPECT_EQ(IPLocator::getPhysicalPort(list.begin()->port), 5100u);
EXPECT_EQ(IPLocator::getLogicalPort(list.begin()->port), 8844u);
//<unique_lan_id>
EXPECT_EQ(list.begin()->address[0], 192);
EXPECT_EQ(list.begin()->address[1], 168);
EXPECT_EQ(list.begin()->address[2], 1);
EXPECT_EQ(list.begin()->address[3], 1);
EXPECT_EQ(list.begin()->address[4], 1);
EXPECT_EQ(list.begin()->address[5], 1);
EXPECT_EQ(list.begin()->address[6], 2);
EXPECT_EQ(list.begin()->address[7], 55);
//<wan_address>
EXPECT_EQ(list.begin()->address[8], 80);
EXPECT_EQ(list.begin()->address[9], 80);
EXPECT_EQ(list.begin()->address[10], 99);
EXPECT_EQ(list.begin()->address[11], 45);
// <address>
EXPECT_EQ(list.begin()->address[12], 192);
EXPECT_EQ(list.begin()->address[13], 168);
EXPECT_EQ(list.begin()->address[14], 1);
EXPECT_EQ(list.begin()->address[15], 55);
EXPECT_EQ(list.begin()->kind, LOCATOR_KIND_TCPv4);
// Missing data - physical_port
sprintf(xml, xml_p, "", "8844", "192.168.1.1.1.1.2.55", "80.80.99.45", "192.168.1.55", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLocatorList_wrapper(titleElement, list, ident));
// Missing data - port
sprintf(xml, xml_p, "5100", "", "192.168.1.1.1.1.2.55", "80.80.99.45", "192.168.1.55", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLocatorList_wrapper(titleElement, list, ident));
// Missing data - unique_lan_id
sprintf(xml, xml_p, "5100", "8844", "", "80.80.99.45", "192.168.1.55", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLocatorList_wrapper(titleElement, list, ident));
// Missing data - wan_address
sprintf(xml, xml_p, "5100", "8844", "192.168.1.1.1.1.2.55", "", "192.168.1.55", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLocatorList_wrapper(titleElement, list, ident));
// Missing data - address
sprintf(xml, xml_p, "5100", "8844", "192.168.1.1.1.1.2.55", "80.80.99.45", "", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLocatorList_wrapper(titleElement, list, ident));
// Invalid element
sprintf(xml, xml_p, "5100", "8844", "192.168.1.1.1.1.2.55", "80.80.99.45", "192.168.1.55",
"<bad_element></bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLocatorList_wrapper(titleElement, list, ident));
}
/*
* This test checks the parsing of a <tcpv6> element from a list of locators.
* 1. Correct parsing of a valid element.
* 2. Check an empty definition of <physical_port> .
* 3. Check an empty definition of <port>.
* 5. Check an empty definition of <address>.
* 6. Check an bad element as a child xml element.
*/
TEST_F(XMLParserTests, getXMLLocatorTCPv6)
{
uint8_t ident = 1;
LocatorList_t list;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<unicastLocatorList>\
<locator>\
<tcpv6>\
<physical_port>%s</physical_port>\
<port>%s</port>\
<address>%s</address>\
%s\
</tcpv6>\
</locator>\
</unicastLocatorList>\
";
char xml[500];
// Valid XML
sprintf(xml, xml_p, "5100", "8844", "::1", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLLocatorList_wrapper(titleElement, list, ident));
EXPECT_EQ(IPLocator::getPhysicalPort(list.begin()->port), 5100u);
EXPECT_EQ(IPLocator::getLogicalPort(list.begin()->port), 8844u);
EXPECT_EQ(list.begin()->address[15], 1);
EXPECT_EQ(list.begin()->kind, LOCATOR_KIND_TCPv6);
// Missing data - physical_port
sprintf(xml, xml_p, "", "8844", "::1", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLocatorList_wrapper(titleElement, list, ident));
// Missing data - port
sprintf(xml, xml_p, "5100", "", "::1", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLocatorList_wrapper(titleElement, list, ident));
// Missing data - address
sprintf(xml, xml_p, "5100", "8844", "", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLocatorList_wrapper(titleElement, list, ident));
// Invalid element
sprintf(xml, xml_p, "5100", "8844", "::1", "<bad_element></bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLocatorList_wrapper(titleElement, list, ident));
}
/*
* This test checks the proper parsing of the <transport_descriptors> xml elements to in a vector of pointers to
* TransportDescriptorInterface, and negative cases.
* 1. Correct parsing of a valid descriptor present in the XmlProfileManager.
* 2. Check a reference to a non existentTransportDescriptorInterface.
* 3. Check an empty definition of <transport_id>.
* 5. Check an empty definition of <transport_descriptor>.
* 6. Check an empty list of transports.
*/
TEST_F(XMLParserTests, getXMLTransports)
{
uint8_t ident = 1;
std::vector<std::shared_ptr<TransportDescriptorInterface>> transports;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Profile describing the transport
const char* xml_profile =
"\
<profiles>\
<transport_descriptors>\
<transport_descriptor>\
<transport_id>ExampleTransportId1</transport_id>\
<type>UDPv6</type>\
<maxMessageSize>31416</maxMessageSize>\
</transport_descriptor>\
</transport_descriptors>\
</profiles>\
";
tinyxml2::XMLDocument xml_profile_doc;
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_profile_doc.Parse(xml_profile));
ASSERT_EQ(xmlparser::XMLP_ret::XML_OK, xmlparser::XMLProfileManager::loadXMLNode(xml_profile_doc));
// Parametrized XML
const char* xml_p =
"\
<userTransports>\
<transport_id>%s</transport_id>\
</userTransports>\
";
char xml[500];
// Valid XML
sprintf(xml, xml_p, "ExampleTransportId1");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
ASSERT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLTransports_wrapper(titleElement, transports, ident));
EXPECT_EQ(transports[0]->max_message_size(), 31416u);
// Wrong ID
sprintf(xml, xml_p, "WrongTransportId");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
ASSERT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLTransports_wrapper(titleElement, transports, ident));
// Missing data
sprintf(xml, xml_p, "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
ASSERT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLTransports_wrapper(titleElement, transports, ident));
// No Elements
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse( "<userTransports></userTransports>"));
titleElement = xml_doc.RootElement();
ASSERT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLTransports_wrapper(titleElement, transports, ident));
// Clean up
xmlparser::XMLProfileManager::DeleteInstance();
}
/*
* This test checks the proper parsing of the <property_policy> xml elements to a PropertyPolicy object, and negative
* cases.
* 1. Correct parsing of a valid <property_policy>.
* 2. Check missing values for the possible elemnts of the properties.
* 3. Check an empty list of <properties>.
* 5. Check an empty list of <binary_properties>.
* 6. Check an wrong descriptor for properties.
*/
TEST_F(XMLParserTests, getXMLPropertiesPolicy)
{
uint8_t ident = 1;
PropertyPolicy property_policy;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
const std::vector<std::string> valid_parameters {
"Property1Name",
"Property1Value",
"false",
"BinProperty1Name",
"false"};
std::vector<std::string> parameters(valid_parameters);
// Template xml
const char* xml_p =
"\
<propertiesPolicy>\
<properties>\
<property>\
<name>%s</name>\
<value>%s</value>\
<propagate>%s</propagate>\
</property>\
</properties>\
<binary_properties>\
<property>\
<name>%s</name>\
<value></value>\
<propagate>%s</propagate>\
</property>\
</binary_properties>\
</propertiesPolicy>\
";
char xml[1000];
sprintf(xml, xml_p,
valid_parameters[0].c_str(),
valid_parameters[1].c_str(),
valid_parameters[2].c_str(),
valid_parameters[3].c_str(),
valid_parameters[4].c_str());
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::propertiesPolicy_wrapper(titleElement, property_policy, ident));
EXPECT_EQ(property_policy.properties()[0].name(), valid_parameters[0]);
EXPECT_EQ(property_policy.properties()[0].value(), valid_parameters[1]);
EXPECT_EQ(property_policy.properties()[0].propagate(), false);
EXPECT_EQ(property_policy.binary_properties()[0].name(), valid_parameters[3]);
// TODO check when binary property values are suported
// EXPECT_EQ(property_policy.binary_properties()[0].name(), valid_parameters[4]);
EXPECT_EQ(property_policy.binary_properties()[0].propagate(), false);
for (int i = 0; i < 5; i++)
{
parameters = valid_parameters;
parameters[i] = "";
sprintf(xml, xml_p,
parameters[0].c_str(),
parameters[1].c_str(),
parameters[2].c_str(),
parameters[3].c_str(),
parameters[4].c_str());
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::propertiesPolicy_wrapper(titleElement, property_policy, ident));
}
// Empty property XML
const char* xml_empty_prop =
"\
<propertiesPolicy>\
<properties></properties>\
</propertiesPolicy>\
";
// Missing data
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml_empty_prop));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::propertiesPolicy_wrapper(titleElement, property_policy, ident));
// Empty binary_property XML
const char* xml_empty_bin_prop =
"\
<propertiesPolicy>\
<binary_properties></binary_properties>\
</propertiesPolicy>\
";
// Missing data
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml_empty_bin_prop));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::propertiesPolicy_wrapper(titleElement, property_policy, ident));
// wrong XML
const char* xml_bad_prop =
"\
<propertiesPolicy>\
<bad_properties></bad_properties>\
</propertiesPolicy>\
";
// Wrong property
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml_bad_prop));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::propertiesPolicy_wrapper(titleElement, property_policy, ident));
}
/*
* This test checks the proper parsing of a <RemoteServer> xml element to a RemoteServerAttributes object, and negative
* cases.
* 1. Check nullptr as tinyxml2::XMLElement argument.
* 2. Check missing prefix in the <RemoteServer> tag.
* 3. Check wrongly formated in the <RemoteServer> tag.
* 5. Check an empty <metatrafficUnicastLocatorList> tag.
* 6. Check an empty <metatrafficMulticastLocatorList> tag.
* 6. Check a <RemoteServer> tag with no locators.
*/
TEST_F(XMLParserTests, getXMLRemoteServer)
{
uint8_t ident = 1;
RemoteServerAttributes attr;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
const std::vector<std::string> valid_parameters {
"prefix=\"4D.49.47.55.45.4c.5f.42.41.52.52.4f\"",
"<locator>\
<udpv6>\
<port>8844</port>\
<address>::1</address>\
</udpv6>\
</locator>",
"<locator>\
<udpv6>\
<port>8844</port>\
<address>::1</address>\
</udpv6>\
</locator>", };
std::vector<std::string> parameters(valid_parameters);
// Parametrized XML
const char* xml_p =
"\
<RemoteServer %s>\
<metatrafficUnicastLocatorList>%s</metatrafficUnicastLocatorList>\
<metatrafficMulticastLocatorList>%s</metatrafficMulticastLocatorList>\
</RemoteServer>\
";
char xml[1200];
// Valid XML
sprintf(xml, xml_p, valid_parameters[0].c_str(), valid_parameters[1].c_str(), valid_parameters[2].c_str());
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
ASSERT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLRemoteServer_wrapper(titleElement, attr, ident));
EXPECT_EQ(attr.guidPrefix.value[0], (octet)0x4d);
EXPECT_EQ(attr.guidPrefix.value[1], (octet)0x49);
EXPECT_EQ(attr.guidPrefix.value[2], (octet)0x47);
EXPECT_EQ(attr.guidPrefix.value[3], (octet)0x55);
EXPECT_EQ(attr.guidPrefix.value[4], (octet)0x45);
EXPECT_EQ(attr.guidPrefix.value[5], (octet)0x4c);
EXPECT_EQ(attr.guidPrefix.value[6], (octet)0x5f);
EXPECT_EQ(attr.guidPrefix.value[7], (octet)0x42);
EXPECT_EQ(attr.guidPrefix.value[8], (octet)0x41);
EXPECT_EQ(attr.guidPrefix.value[9], (octet)0x52);
EXPECT_EQ(attr.guidPrefix.value[10], (octet)0x52);
EXPECT_EQ(attr.guidPrefix.value[11], (octet)0x4f);
EXPECT_EQ(attr.metatrafficUnicastLocatorList.begin()->port, 8844u);
EXPECT_EQ(attr.metatrafficUnicastLocatorList.begin()->address[15], 1);
EXPECT_EQ(attr.metatrafficMulticastLocatorList.begin()->port, 8844u);
EXPECT_EQ(attr.metatrafficMulticastLocatorList.begin()->address[15], 1);
// nullptr element
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLRemoteServer_wrapper(nullptr, attr, ident));
// No prefix
sprintf(xml, xml_p, "", valid_parameters[1].c_str(), valid_parameters[2].c_str());
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLRemoteServer_wrapper(titleElement, attr, ident));
// Bad prefix value
sprintf(xml, xml_p, "prefix=\"\"", valid_parameters[1].c_str(), valid_parameters[2].c_str());
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLRemoteServer_wrapper(titleElement, attr, ident));
// Bad unicast
sprintf(xml, xml_p, valid_parameters[0].c_str(), "", valid_parameters[2].c_str());
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLRemoteServer_wrapper(titleElement, attr, ident));
// Bad multicast
sprintf(xml, xml_p, valid_parameters[0].c_str(), valid_parameters[1].c_str(), "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLRemoteServer_wrapper(titleElement, attr, ident));
// No locators
sprintf(xml, "<RemoteServer %s></RemoteServer>", valid_parameters[0].c_str());
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLRemoteServer_wrapper(titleElement, attr, ident));
}
/*
* This test checks the negative cases of a <port> xml element.
* 1. Check a missing case of each of the <port> child tags.
* 2. Check a wrong child tag.
*/
TEST_F(XMLParserTests, getXMLPortParameters_NegativeClauses)
{
uint8_t ident = 1;
PortParameters port;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
std::string xml;
std::vector<std::string> parameters;
for (int i = 0; i < 8; i++)
{
if (i < 7)
{
parameters.assign (7, "1");
parameters[i] = "";
xml =
"\
<port>\
<portBase>" + parameters[0] + "</portBase>\
<domainIDGain>" + parameters[1] + "</domainIDGain>\
<participantIDGain>" + parameters[2] +
"</participantIDGain>\
<offsetd0>" + parameters[3] + "</offsetd0>\
<offsetd1>" + parameters[4] + "</offsetd1>\
<offsetd2>" + parameters[5] + "</offsetd2>\
<offsetd3>" + parameters[6] + "</offsetd3>\
</port>\
";
}
else
{
xml =
"\
<port>\
<bad_element></bad_element>\
</port>\
";
}
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml.c_str()));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLPortParameters_wrapper(titleElement, port, ident));
}
}
/*
* This test checks the negative cases of a <subscriber> xml profile.
* 1. Check an incorrect for each of the possible SubscriberAttributes.
* 2. Check an non existant attribute.
*/
TEST_F(XMLParserTests, getXMLSubscriberAttributes_NegativeClauses)
{
uint8_t ident = 1;
SubscriberAttributes attr;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
std::string xml;
std::vector<std::string> parameters {
"<topic><bad_element></bad_element></topic>",
"<qos><bad_element></bad_element></qos>",
"<times><bad_element></bad_element></times>",
"<unicastLocatorList><bad_element></bad_element></unicastLocatorList>",
"<multicastLocatorList><bad_element></bad_element></multicastLocatorList>",
"<remoteLocatorList><bad_element></bad_element></remoteLocatorList>",
"<expectsInlineQos><bad_element></bad_element></expectsInlineQos>",
"<historyMemoryPolicy><bad_element></bad_element></historyMemoryPolicy>",
"<propertiesPolicy><bad_element></bad_element></propertiesPolicy>",
"<userDefinedID><bad_element></bad_element></userDefinedID>",
"<entityID><bad_element></bad_element></entityID>",
"<matchedPublishersAllocation><bad_element></bad_element></matchedPublishersAllocation>",
"<bad_element></bad_element>"
};
for (std::vector<std::string>::iterator it = parameters.begin(); it != parameters.end(); ++it)
{
xml =
"\
<subscriber profile_name=\"test_subscriber_profile\" is_default_profile=\"true\">\
" + *it + "\
</subscriber>\
";
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml.c_str()));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLSubscriberAttributes_wrapper(titleElement, attr, ident));
}
}
/*
* This test checks the negative cases of a <publisher> xml profile.
* 1. Check an incorrect for each of the possible PublisherAttributes.
* 2. Check an non existant attribute.
*/
TEST_F(XMLParserTests, getXMLPublisherAttributes_NegativeClauses)
{
uint8_t ident = 1;
PublisherAttributes attr;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
std::string xml;
std::vector<std::string> parameters {
"<topic><bad_element></bad_element></topic>",
"<qos><bad_element></bad_element></qos>",
"<times><bad_element></bad_element></times>",
"<unicastLocatorList><bad_element></bad_element></unicastLocatorList>",
"<multicastLocatorList><bad_element></bad_element></multicastLocatorList>",
"<remoteLocatorList><bad_element></bad_element></remoteLocatorList>",
"<throughputController><bad_element></bad_element></throughputController>",
"<historyMemoryPolicy><bad_element></bad_element></historyMemoryPolicy>",
"<propertiesPolicy><bad_element></bad_element></propertiesPolicy>",
"<userDefinedID><bad_element></bad_element></userDefinedID>",
"<entityID><bad_element></bad_element></entityID>",
"<matchedSubscribersAllocation><bad_element></bad_element></matchedSubscribersAllocation>",
"<bad_element></bad_element>"
};
for (std::vector<std::string>::iterator it = parameters.begin(); it != parameters.end(); ++it)
{
xml =
"\
<publisher profile_name=\"test_publisher_profile\" is_default_profile=\"true\">\
" + *it + "\
</publisher>\
";
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml.c_str()));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLPublisherAttributes_wrapper(titleElement, attr, ident));
}
}
/*
* This test checks the negative cases of a locator list xml element.
* 1. Check an incorrect for each of the possible types of <locator>.
* 2. Check an non existant type of locator.
*/
TEST_F(XMLParserTests, getXMLLocatorList_NegativeClauses)
{
uint8_t ident = 1;
LocatorList_t list;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
std::string xml;
std::vector<std::string> parameters {
"<locator><udpv4><bad_element></bad_element></udpv4></locator>",
"<locator><udpv6><bad_element></bad_element></udpv6></locator>",
"<locator><tcpv4><bad_element></bad_element></tcpv4></locator>",
"<locator><tcpv6><bad_element></bad_element></tcpv6></locator>",
"<locator><bad_element></bad_element></locator>",
"<bad_element></bad_element>"
};
for (std::vector<std::string>::iterator it = parameters.begin(); it != parameters.end(); ++it)
{
xml =
"\
<locatorList>\
" + *it + "\
</locatorList>\
";
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml.c_str()));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLocatorList_wrapper(titleElement, list, ident));
}
}
/*
* This test checks the negative cases of the XMLParser::getXMLguidPrefix method.
* 1. Check a missing value for a <guid>.
* 2. Check passing a nullptr as a tinyxml2::XMLElement argument.
*/
TEST_F(XMLParserTests, getXMLguidPrefix_NegativeClauses)
{
uint8_t ident = 1;
GuidPrefix_t prefix;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse("<guid></guid>"));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLguidPrefix_wrapper(titleElement, prefix, ident));
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLguidPrefix_wrapper(nullptr, prefix, ident));
}
/*
* This test checks the positive cases of the XMLParser::getXMLguidPrefix method.
* 1. Check a correct return of the method.
* 2. Check the correct values have been passed to the prefix variable.
*/
TEST_F(XMLParserTests, getXMLguidPrefix_positive)
{
uint8_t ident = 1;
GuidPrefix_t prefix;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse("<guid>4D.49.47.55.45.4c.5f.42.41.52.52.4f</guid>"));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLguidPrefix_wrapper(titleElement, prefix, ident));
EXPECT_EQ(prefix.value[0], (octet)0x4d);
EXPECT_EQ(prefix.value[1], (octet)0x49);
EXPECT_EQ(prefix.value[2], (octet)0x47);
EXPECT_EQ(prefix.value[3], (octet)0x55);
EXPECT_EQ(prefix.value[4], (octet)0x45);
EXPECT_EQ(prefix.value[5], (octet)0x4c);
EXPECT_EQ(prefix.value[6], (octet)0x5f);
EXPECT_EQ(prefix.value[7], (octet)0x42);
EXPECT_EQ(prefix.value[8], (octet)0x41);
EXPECT_EQ(prefix.value[9], (octet)0x52);
EXPECT_EQ(prefix.value[10], (octet)0x52);
EXPECT_EQ(prefix.value[11], (octet)0x4f);
}
/*
* This test checks the negative cases of the XMLParser::getXMLDuration method.
* 1. Check passing an infinite duration and a finite duration at the same time.
* 2. Check passing a missing value of <sec> and <nanosec>.
* 3. Check passing a non valid value of <sec> and <nanosec>.
* 4. Check passing an empty <duration> field.
*/
TEST_F(XMLParserTests, getXMLDuration_NegativeClauses)
{
uint8_t ident = 1;
Duration_t duration;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
std::string xml;
std::vector<std::string> parameters {
"DURATION_INFINITY<sec>1</sec>",
"<sec></sec>",
"<sec>not_an_int</sec>",
"<nanosec></nanosec>",
"<nanosec>not_an_int</nanosec>",
"<bad_element></bad_element>",
""
};
for (std::vector<std::string>::iterator it = parameters.begin(); it != parameters.end(); ++it)
{
xml =
"\
<duration>\
" + *it + "\
</duration>\
";
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml.c_str()));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLDuration_wrapper(titleElement, duration, ident));
}
}
/*
* This test checks the positive cases of the XMLParser::getXMLDuration method.
* 1. Check correct return of the method.
* 2. Check correct parsing on DURATION_INFINITY in the <sec> field.
* 3. Check correct parsing on DURATION_INFINITY in the <nanosec> field.
*/
TEST_F(XMLParserTests, getXMLDuration_infinite)
{
uint8_t ident = 1;
Duration_t duration;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
std::string xml;
std::vector<std::string> parameters {
"<sec>DURATION_INFINITY</sec>",
"<nanosec>DURATION_INFINITY</nanosec>"
};
for (std::vector<std::string>::iterator it = parameters.begin(); it != parameters.end(); ++it)
{
xml =
"\
<duration>\
" + *it + "\
</duration>\
";
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml.c_str()));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLDuration_wrapper(titleElement, duration, ident));
EXPECT_EQ(duration, c_TimeInfinite);
}
}
/*
* This test checks the correct parsing of a string field with the XMLParser::getXMLString method.
* 1. Check passing a valid string field.
* 2. Check passing a nullptr as a tinyxml2::XMLElement argument.
* 4. Check passing an empty field.
*/
TEST_F(XMLParserTests, getXMLString)
{
uint8_t ident = 1;
std::string s;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse("<field>field_text</field>"));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLString_wrapper(titleElement, &s, ident));
EXPECT_EQ(s, "field_text");
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLString_wrapper(nullptr, &s, ident));
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse("<field></field>"));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLString_wrapper(titleElement, &s, ident));
}
/*
* This test checks the negative cases of the XMLParser::getXMLList method.
* 1. Check passing a nullptr as a tinyxml2::XMLElement argument.
* 2. Check passing an empty <list> field.
* 3. Check passing a non valid value of <RemoteServer> descriptor as an element of <list>.
*/
TEST_F(XMLParserTests, getXMLList_NegativeClauses)
{
uint8_t ident = 1;
RemoteServerList_t list;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// empty element
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLList_wrapper(nullptr, list, ident));
// empty list
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse("<list></list>"));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLList_wrapper(titleElement, list, ident));
// bad remote server element
const char* xml = "<list><RemoteServer>bad_remote_server</RemoteServer></list>";
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLList_wrapper(titleElement, list, ident));
}
/*
* This test checks the positive case of the XMLParser::getXMLList method.
* 1. Check an valid return on the function.
* 2. Check the correct element has been placed on the list.
*/
TEST_F(XMLParserTests, getXMLList_positive)
{
uint8_t ident = 1;
RemoteServerList_t list;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// bad remote server element
const char* xml =
"<list>\
<RemoteServer prefix=\"4D.49.47.55.45.4c.5f.42.41.52.52.4f\">\
<metatrafficUnicastLocatorList>\
<locator>\
<udpv6>\
<port>8844</port>\
<address>::1</address>\
</udpv6>\
</locator>\
</metatrafficUnicastLocatorList>\
</RemoteServer>\
</list>";
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLList_wrapper(titleElement, list, ident));
EXPECT_EQ(list.begin()->metatrafficUnicastLocatorList.begin()->port, 8844u);
EXPECT_EQ(list.begin()->metatrafficUnicastLocatorList.begin()->address[15], 1);
EXPECT_EQ(list.begin()->guidPrefix.value[0], 0x4d);
EXPECT_EQ(list.begin()->guidPrefix.value[1], 0x49);
EXPECT_EQ(list.begin()->guidPrefix.value[2], 0x47);
EXPECT_EQ(list.begin()->guidPrefix.value[3], 0x55);
EXPECT_EQ(list.begin()->guidPrefix.value[4], 0x45);
}
/*
* This test checks the negative cases of the XMLParser::getXMLBool method.
* 1. Check passing a nullptr as a tinyxml2::XMLElement argument.
* 2. Check passing a non boolean valid inside the field.
*/
TEST_F(XMLParserTests, getXMLBool_NegativeClauses)
{
uint8_t ident = 1;
bool b;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLBool_wrapper(nullptr, &b, ident));
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse("<field>not_a_bool</field>"));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLBool_wrapper(titleElement, &b, ident));
}
/*
* This test checks the negative cases of the XMLParser::getXMLInt method.
* 1. Check passing a nullptr as a tinyxml2::XMLElement argument.
* 2. Check passing a non integer valid inside the field.
*/
TEST_F(XMLParserTests, getXMLInt_NegativeClauses)
{
uint8_t ident = 1;
int i;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLInt_wrapper(nullptr, &i, ident));
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse("<field>not_an_int</field>"));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLInt_wrapper(titleElement, &i, ident));
}
/*
* This test checks the negative cases of the two definitions of XMLParser::getXMLInt method.
* 1. Check passing a nullptr as a tinyxml2::XMLElement argument.
* 2. Check passing a non integer valid inside the field.
* Both for each definition.
*/
TEST_F(XMLParserTests, getXMLUint_NegativeClauses)
{
uint8_t ident = 1;
unsigned int ui;
uint16_t ui16;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLUint_wrapper(nullptr, &ui, ident));
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse("<field>not_an_uint</field>"));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLUint_wrapper(titleElement, &ui, ident));
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLUint_wrapper(nullptr, &ui16, ident));
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse("<field>not_an_uint</field>"));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLUint_wrapper(titleElement, &ui16, ident));
}
/*
* This test checks the negative cases in the <initialAnnouncements> xml element.
* 1. Check an empty definition of <count> child xml element.
* 2. Check an empty definition of <sec> in <period> child xml element.
* 3. Check an empty definition of <nanosec> in <period> child xml element.
* 4. Check a wrong xml element definition inside <initialAnnouncements>
*/
TEST_F(XMLParserTests, getXMLInitialAnnouncementsConfig_NegativeClauses)
{
uint8_t ident = 1;
DiscoverySettings settings;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<discovery_config>\
<initialAnnouncements>\
%s\
<count>%s</count>\
<period>\
<sec>%s</sec>\
<nanosec>%s</nanosec>\
</period>\
</initialAnnouncements>\
</discovery_config>\
";
char xml[600];
// Check an empty definition of <count> child xml element.
sprintf(xml, xml_p, "", "", "5", "123");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLDiscoverySettings_wrapper(titleElement, settings, ident));
// Check an empty definition of <sec> in <period> child xml element.
sprintf(xml, xml_p, "", "5", "", "123");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLDiscoverySettings_wrapper(titleElement, settings, ident));
// Check an empty definition of <nanosec> in <period> child xml element.
sprintf(xml, xml_p, "", "5", "5", "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLDiscoverySettings_wrapper(titleElement, settings, ident));
const char* xml_e =
"\
<discovery_config>\
<initialAnnouncements>\
<bad_element>1</bad_element>\
</initialAnnouncements>\
</discovery_config>\
";
// Check a wrong xml element definition inside <initialAnnouncements>
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml_e));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLDiscoverySettings_wrapper(titleElement, settings, ident));
}
/*
* This test checks the negative cases in the <qos> xml child element of <data_writer>/<data_reader>
* 1. Check an empty definition of <durability> xml element.
* 2. Check an empty definition of <liveliness> xml element.
* 3. Check an empty definition of <reliability> xml element.
* 4. Check an empty definition of <partition> xml element.
* 5. Check an empty definition of <publishMode> xml element.
* 6. Check an empty definition of <deadline> xml element.
* 7. Check an empty definition of <disablePositiveAcks> xml element.
* 8. Check an empty definition of <latencyBudget> xml element.
* 9. Check a wrong xml element definition inside <qos>
*/
TEST_F(XMLParserTests, getXMLWriterReaderQosPolicies)
{
uint8_t ident = 1;
WriterQos wqos;
ReaderQos rqos;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<qos>\
%s\
</qos>\
";
char xml[600];
// Check an empty definition of <durability> xml element.
sprintf(xml, xml_p, "<durability></durability>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
// Check an empty definition of <liveliness> xml element.
sprintf(xml, xml_p, "<liveliness><kind></kind></liveliness>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
// Check an empty definition of <reliability> xml element.
sprintf(xml, xml_p, "<reliability><kind></kind></reliability>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
// Check an empty definition of <partition> xml element.
sprintf(xml, xml_p, "<partition></partition>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
// Check an empty definition of <publishMode> xml element.
sprintf(xml, xml_p, "<publishMode></publishMode>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
// Check an empty definition of <deadline> xml element.
sprintf(xml, xml_p, "<deadline></deadline>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
// Check an empty definition of <disablePositiveAcks> xml element.
sprintf(xml, xml_p, "<disablePositiveAcks><enabled></enabled></disablePositiveAcks>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
// Check an empty definition of <latencyBudget> xml element.
sprintf(xml, xml_p, "<latencyBudget></latencyBudget>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
// Check an empty definition of <lifespan> xml element.
sprintf(xml, xml_p, "<lifespan></lifespan>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
// Check an empty definition of <latencyBudget> xml element.
sprintf(xml, xml_p, "<latencyBudget></latencyBudget>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
// Check an empty definition of <disablePositiveAcks> xml element.
sprintf(xml, xml_p, "<disablePositiveAcks><enabled></enabled></disablePositiveAcks>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
// Check a wrong xml element definition inside <qos>
sprintf(xml, xml_p, "<bad_element></bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
}
/*
* This test checks that there is a logError when setting up a non supported <data_writer>/<data_reader> qos
* 1. Check that there is a logError when trying to set up the <durabilityService> Qos.
* 2. Check that there is a logError when trying to set up the <userData> Qos.
* 3. Check that there is a logError when trying to set up the <timeBasedFilter> Qos.
* 4. Check that there is a logError when trying to set up the <ownership> Qos.
* 5. Check that there is a logError when trying to set up the <ownershipStrength> Qos.
* 6. Check that there is a logError when trying to set up the <destinationOrder> Qos.
* 7. Check that there is a logError when trying to set up the <presentation> Qos.
* 8. Check that there is a logError when trying to set up the <topicData> Qos.
* 9. Check that there is a logError when trying to set up the <groupData> Qos.
*/
TEST_F(XMLParserTests, getXMLWriterReaderUnsupportedQosPolicies)
{
uint8_t ident = 1;
WriterQos wqos;
ReaderQos rqos;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
mock_consumer = new MockConsumer();
Log::RegisterConsumer(std::unique_ptr<LogConsumer>(mock_consumer));
Log::SetCategoryFilter(std::regex("(XMLPARSER)"));
// Parametrized XML
const char* xml_p =
"\
<qos>\
%s\
</qos>\
";
char xml[600];
// Check that there is a logError when trying to set up the <durabilityService> Qos.
sprintf(xml, xml_p, "<durabilityService></durabilityService>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
// Check that there is a logError when trying to set up the <userData> Qos.
sprintf(xml, xml_p, "<userData></userData>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
// Check that there is a logError when trying to set up the <timeBasedFilter> Qos.
sprintf(xml, xml_p, "<timeBasedFilter></timeBasedFilter>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
// Check that there is a logError when trying to set up the <ownership> Qos.
sprintf(xml, xml_p, "<ownership></ownership>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
// Check that there is a logError when trying to set up the <ownershipStrength> Qos.
sprintf(xml, xml_p, "<ownershipStrength></ownershipStrength>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
// Check that there is a logError when trying to set up the <destinationOrder> Qos.
sprintf(xml, xml_p, "<destinationOrder></destinationOrder>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
// Check that there is a logError when trying to set up the <presentation> Qos.
sprintf(xml, xml_p, "<presentation></presentation>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
// Check that there is a logError when trying to set up the <topicData> Qos.
sprintf(xml, xml_p, "<topicData></topicData>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
// Check that there is a logError when trying to set up the <groupData> Qos.
sprintf(xml, xml_p, "<groupData></groupData>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLWriterQosPolicies_wrapper(titleElement, wqos, ident));
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLReaderQosPolicies_wrapper(titleElement, rqos, ident));
helper_block_for_at_least_entries(18);
auto consumed_entries = mock_consumer->ConsumedEntries();
// Expect 18 log errors.
uint32_t num_errors = 0;
for (const auto& entry : consumed_entries)
{
if (entry.kind == Log::Kind::Error)
{
num_errors++;
}
}
EXPECT_EQ(num_errors, 18u);
}
/*
* This test checks the positive cases of configuration through XML of the data limits of the participant's allocation
* attributes.
* 1. Check that the XML return code is correct for the data limit settings.
* 2. Check that the maximum number of properties attribute (max_properties) is set correctly.
* 3. Check that the maximum user data attribute (max_user_data) is set correctly.
* 4. Check that the maximum number of partitions attribute (max_partitions) is set correctly.
*/
TEST_F(XMLParserTests, ParticipantAllocationAttributesDataLimits)
{
uint8_t ident = 1;
rtps::RTPSParticipantAllocationAttributes allocation;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// XML snippet
const char* xml =
"\
<rtpsParticipantAllocationAttributes>\
<max_properties>10</max_properties>\
<max_user_data>20</max_user_data>\
<max_partitions>3</max_partitions>\
</rtpsParticipantAllocationAttributes>\
";
// Load the xml
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
// Check that the XML return code is correct for the data limit settings.
EXPECT_EQ(
XMLP_ret::XML_OK,
XMLParserTest::getXMLParticipantAllocationAttributes_wrapper(titleElement, allocation, ident));
// Check that the maximum number of properties attribute (max_properties) is set correctly.
EXPECT_EQ(allocation.data_limits.max_properties, 10ul);
// Check that the maximum user data attribute (max_user_data) is set correctly.
EXPECT_EQ(allocation.data_limits.max_user_data, 20ul);
// Check that the maximum number of partitions attribute (max_partitions) is set correctly.
EXPECT_EQ(allocation.data_limits.max_partitions, 3ul);
}
/*
* This test checks the positive cases of configuration through XML of the STATIC EDP.
* 1. Check that the XML return code is correct for the STATIC EDP settings.
* 2. Check that the SIMPLE discovery protocol is set to false.
* 3. Check that the STATIC discovery protocol is set to true.
* 4. Check that the static endpoint XML filename is set correctly.
*/
TEST_F(XMLParserTests, getXMLDiscoverySettingsStaticEDP)
{
uint8_t ident = 1;
rtps::DiscoverySettings settings;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// XML snippet
const char* xml =
"\
<discovery_config>\
<EDP>STATIC</EDP>\
<static_edp_xml_config>file://my_static_edp.xml</static_edp_xml_config>\
</discovery_config>\
";
// Load the xml
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
// Check that the XML return code is correct for the STATIC EDP settings.
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLDiscoverySettings_wrapper(titleElement, settings, ident));
// Check that the SIMPLE discovery protocol is set to false.
EXPECT_FALSE(settings.use_SIMPLE_EndpointDiscoveryProtocol);
// Check that the STATIC discovery protocol is set to true.
EXPECT_TRUE(settings.use_STATIC_EndpointDiscoveryProtocol);
// Check that the static endpoint XML filename is set correctly.
EXPECT_STREQ(settings.static_edp_xml_config(), "file://my_static_edp.xml");
}
/*
* This test checks the positive case of configuration via XML of the livelines automatic kind.
* 1. Check that the XML return code is correct for the liveliness kind setting.
* 2. Check that the liveliness kind is set to AUTOMATIC.
*/
TEST_F(XMLParserTests, getXMLLivelinessQosAutomaticKind)
{
uint8_t ident = 1;
LivelinessQosPolicy liveliness;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// XML snippet
const char* xml =
"\
<liveliness>\
<kind>AUTOMATIC</kind>\
</liveliness>\
";
// Load the xml
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
// Check that the XML return code is correct for the liveliness kind setting.
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLLivelinessQos_wrapper(titleElement, liveliness, ident));
// Check that the liveliness kind is set to AUTOMATIC.
EXPECT_EQ(liveliness.kind, LivelinessQosPolicyKind::AUTOMATIC_LIVELINESS_QOS);
}
/*
* This test checks the positive case of configuration via XML of the publish mode synchronous kind.
* 1. Check that the XML return code is correct for the publish mode kind setting.
* 2. Check that the publish mode kind is set to SYNCHRONOUS_PUBLISH_MODE.
*/
TEST_F(XMLParserTests, getXMLPublishModeQosSynchronousKind)
{
uint8_t ident = 1;
PublishModeQosPolicy publishMode;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// XML snippet
const char* xml =
"\
<publishMode>\
<kind>SYNCHRONOUS</kind>\
</publishMode>\
";
// Load the xml
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
// Check that the XML return code is correct for the publish mode kind setting.
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLPublishModeQos_wrapper(titleElement, publishMode, ident));
// Check that the publish mode kind is set to SYNCHRONOUS_PUBLISH_MODE.
EXPECT_EQ(publishMode.kind, PublishModeQosPolicyKind::SYNCHRONOUS_PUBLISH_MODE);
}
/*
* This test checks the positive case of configuration via XML of the history memory policy.
* 1. Check that the XML return code is correct for the history memory policy setting.
* 2. Check that the history memory policy mode is set to PREALLOCATED_MEMORY_MODE.
* 3. Check that the history memory policy mode is set to PREALLOCATED_WITH_REALLOC_MEMORY_MODE.
* 4. Check that the history memory policy mode is set to DYNAMIC_RESERVE_MEMORY_MODE.
* 5. Check that the history memory policy mode is set to DYNAMIC_REUSABLE_MEMORY_MODE.
*/
TEST_F(XMLParserTests, getXMLHistoryMemoryPolicy)
{
uint8_t ident = 1;
MemoryManagementPolicy_t historyMemoryPolicy;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
std::map<std::string, MemoryManagementPolicy> policies =
{
{"PREALLOCATED", MemoryManagementPolicy::PREALLOCATED_MEMORY_MODE},
{"PREALLOCATED_WITH_REALLOC", MemoryManagementPolicy::PREALLOCATED_WITH_REALLOC_MEMORY_MODE},
{"DYNAMIC", MemoryManagementPolicy::DYNAMIC_RESERVE_MEMORY_MODE},
{"DYNAMIC_REUSABLE", MemoryManagementPolicy::DYNAMIC_REUSABLE_MEMORY_MODE}
};
// Parametrized XML
const char* xml_p =
"\
<historyMemoryPolicyType>%s</historyMemoryPolicyType>\
";
char xml[500];
for (const auto& policy : policies)
{
// Load the xml
sprintf(xml, xml_p, policy.first.c_str());
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(
XMLP_ret::XML_OK,
XMLParserTest::getXMLHistoryMemoryPolicy_wrapper(titleElement, historyMemoryPolicy, ident));
EXPECT_EQ(historyMemoryPolicy, policy.second);
}
}
/*
* This test checks the positive case of configuration via XML of the durability QoS policy kind.
* 1. Check that the XML return code is correct for all the durability QoS policy kind values.
* 2. Check that the durability QoS policy kind is set to VOLATILE.
* 3. Check that the durability QoS policy kind is set to TRANSIENT_LOCAL.
* 4. Check that the durability QoS policy kind is set to TRANSIENT.
* 5. Check that the durability QoS policy kind is set to PERSISTENT.
*/
TEST_F(XMLParserTests, getXMLDurabilityQosKind)
{
uint8_t ident = 1;
DurabilityQosPolicy durability;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<durability>\
<kind>%s</kind>\
</durability>\
";
char xml[500];
std::vector<std::string> kinds = {"VOLATILE", "TRANSIENT_LOCAL", "TRANSIENT", "PERSISTENT"};
sprintf(xml, xml_p, "VOLATILE");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
// Check that the XML return code is correct for the durability QoS policy VOLATILE kind.
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLDurabilityQos_wrapper(titleElement, durability, ident));
// Check that the durability QoS policy kind is set to VOLATILE.
EXPECT_EQ(durability.kind, DurabilityQosPolicyKind::VOLATILE_DURABILITY_QOS);
sprintf(xml, xml_p, "TRANSIENT_LOCAL");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
// Check that the XML return code is correct for the durability QoS policy TRANSIENT_LOCAL kind.
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLDurabilityQos_wrapper(titleElement, durability, ident));
// Check that the durability QoS policy kind is set to TRANSIENT_LOCAL.
EXPECT_EQ(durability.kind, DurabilityQosPolicyKind::TRANSIENT_LOCAL_DURABILITY_QOS);
sprintf(xml, xml_p, "TRANSIENT");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
// Check that the XML return code is correct for the durability QoS policy TRANSIENT kind.
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLDurabilityQos_wrapper(titleElement, durability, ident));
// Check that the durability QoS policy kind is set to TRANSIENT.
EXPECT_EQ(durability.kind, DurabilityQosPolicyKind::TRANSIENT_DURABILITY_QOS);
sprintf(xml, xml_p, "PERSISTENT");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
// Check that the XML return code is correct for the durability QoS policy PERSISTENT kind.
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLDurabilityQos_wrapper(titleElement, durability, ident));
// Check that the durability QoS policy kind is set to PERSISTENT.
EXPECT_EQ(durability.kind, DurabilityQosPolicyKind::PERSISTENT_DURABILITY_QOS);
}
/*
* This test checks the negative cases in the xml child element of <BuiltinAttributes>
* 1. Check an invalid tag of:
* <discovery_config>
* <use_WriterLivelinessProtocol>
* <metatrafficUnicastLocatorList>
* <metatrafficMulticastLocatorList>
* <initialPeersList>
* <readerHistoryMemoryPolicy>
* <writerHistoryMemoryPolicy>
* <readerPayloadSize>
* <writerPayloadSize>
* <mutation_tries>
* <avoid_builtin_multicast>
* 2. Check invalid element
*/
TEST_F(XMLParserTests, getXMLBuiltinAttributes_NegativeClauses)
{
uint8_t ident = 1;
BuiltinAttributes builtin;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<builtinAttributes>\
%s\
</builtinAttributes>\
";
char xml[1000];
const char* field_p =
"\
<%s>\
<bad_element> </bad_element>\
</%s>\
";
char field[500];
std::vector<std::string> field_vec =
{
"discovery_config",
"use_WriterLivelinessProtocol",
"metatrafficUnicastLocatorList",
"metatrafficMulticastLocatorList",
"initialPeersList",
"readerHistoryMemoryPolicy",
"writerHistoryMemoryPolicy",
"readerPayloadSize",
"writerPayloadSize",
"mutation_tries",
"avoid_builtin_multicast"
};
for (std::string tag : field_vec)
{
sprintf(field, field_p, tag.c_str(), tag.c_str());
sprintf(xml, xml_p, field);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLBuiltinAttributes_wrapper(titleElement, builtin, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLBuiltinAttributes_wrapper(titleElement, builtin, ident));
}
/*
* This test checks the negative cases in the xml child element of <ThroughputController>
* 1. Check an invalid tag of:
* <dbytesPerPeriod>
* <periodMillisecs>
* 2. Check invalid element
*/
TEST_F(XMLParserTests, getXMLThroughputController_NegativeClauses)
{
uint8_t ident = 1;
ThroughputControllerDescriptor throughputController;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<throughputController>\
%s\
</throughputController>\
";
char xml[1000];
const char* field_p =
"\
<%s>\
<bad_element> </bad_element>\
</%s>\
";
char field[500];
std::vector<std::string> field_vec =
{
"bytesPerPeriod",
"periodMillisecs",
};
for (std::string tag : field_vec)
{
sprintf(field, field_p, tag.c_str(), tag.c_str());
sprintf(xml, xml_p, field);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLThroughputController_wrapper(titleElement, throughputController, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLThroughputController_wrapper(titleElement, throughputController, ident));
}
/*
* This test checks the negative cases in the xml child element of <TopicAttributes>
* 1. Check an invalid tag of:
* <kind>
* <name>
* <data>
* <kind>
* <historyQos>
* <resourceLimitsQos>
* 2. Check invalid <kind> type
* 3. Check invalid element
*/
TEST_F(XMLParserTests, getXMLTopicAttributes_NegativeClauses)
{
uint8_t ident = 1;
TopicAttributes topic;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<topicAttributes>\
%s\
</topicAttributes>\
";
char xml[1000];
const char* field_p =
"\
<%s>\
<bad_element> </bad_element>\
</%s>\
";
char field[500];
std::vector<std::string> field_vec =
{
"kind",
"name",
"dataType",
"kind",
"historyQos",
"resourceLimitsQos",
};
for (std::string tag : field_vec)
{
sprintf(field, field_p, tag.c_str(), tag.c_str());
sprintf(xml, xml_p, field);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLTopicAttributes_wrapper(titleElement, topic, ident));
}
// Invalid key in kind field
{
const char* tag =
"\
<kind>\
BAD_KEY\
</kind>\
";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLTopicAttributes_wrapper(titleElement, topic, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLTopicAttributes_wrapper(titleElement, topic, ident));
}
/*
* This test checks the negative cases in the xml child element of <ResourceLimitsQos>
* 1. Check an invalid tag of:
* <max_samples>
* <max_instances>
* <max_samples_per_instance>
* <allocated_samples>
* 2. Check invalid <kind> type
* 3. Check invalid element
*/
TEST_F(XMLParserTests, getXMLResourceLimitsQos_NegativeClauses)
{
uint8_t ident = 1;
ResourceLimitsQosPolicy resourceLimitsQos;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<topicAttributes>\
%s\
</topicAttributes>\
";
char xml[1000];
const char* field_p =
"\
<%s>\
<bad_element> </bad_element>\
</%s>\
";
char field[500];
std::vector<std::string> field_vec =
{
"max_samples",
"max_instances",
"max_samples_per_instance",
"allocated_samples",
};
for (std::string tag : field_vec)
{
sprintf(field, field_p, tag.c_str(), tag.c_str());
sprintf(xml, xml_p, field);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLResourceLimitsQos_wrapper(titleElement, resourceLimitsQos, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLResourceLimitsQos_wrapper(titleElement, resourceLimitsQos,
ident));
}
/*
* This test checks the negative cases in the xml child element of <ContainerAllocationConfig>
* 1. Check an invalid tag of:
* <initial>
* <maximum>
* <increment>
* 2. Check invalid config <initial> > <maximum>
* 3. Check incalid config <increment> = 0
* 4. Check invalid element
*/
TEST_F(XMLParserTests, getXMLContainerAllocationConfig_NegativeClauses)
{
uint8_t ident = 1;
ResourceLimitedContainerConfig allocation_config;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<containerAllocationConfig>\
%s\
</containerAllocationConfig>\
";
char xml[1000];
const char* field_p =
"\
<%s>\
<bad_element> </bad_element>\
</%s>\
";
char field[500];
std::vector<std::string> field_vec =
{
"initial",
"maximum",
"increment",
};
for (std::string tag : field_vec)
{
sprintf(field, field_p, tag.c_str(), tag.c_str());
sprintf(xml, xml_p, field);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLContainerAllocationConfig_wrapper(titleElement, allocation_config, ident));
}
// Invalid tuple initial-maximum parameters
{
const char* tag =
"\
<initial> 2 </initial>\
<maximum> 1 </maximum>\
<increment> 1 </increment>\
";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLContainerAllocationConfig_wrapper(titleElement, allocation_config, ident));
}
// Invalid increment parameters
{
const char* tag =
"\
<initial> 1 </initial>\
<maximum> 2 </maximum>\
<increment> 0 </increment>\
";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLContainerAllocationConfig_wrapper(titleElement, allocation_config, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLContainerAllocationConfig_wrapper(titleElement, allocation_config, ident));
}
/*
* This test checks the negative cases in the xml child element of <HistoryQosPolicy>
* 1. Check an invalid tag of:
* <kind>
* <depth>
* 2. Check invalid <kind> element
* 3. Check invalid element
*/
TEST_F(XMLParserTests, getXMLHistoryQosPolicy_NegativeClauses)
{
uint8_t ident = 1;
HistoryQosPolicy historyQos;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<historyQosPolicy>\
%s\
</historyQosPolicy>\
";
char xml[1000];
const char* field_p =
"\
<%s>\
<bad_element> </bad_element>\
</%s>\
";
char field[500];
std::vector<std::string> field_vec =
{
"kind",
"depth",
};
for (std::string tag : field_vec)
{
sprintf(field, field_p, tag.c_str(), tag.c_str());
sprintf(xml, xml_p, field);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLHistoryQosPolicy_wrapper(titleElement, historyQos, ident));
}
// Invalid tuple initial-maximum parameters
{
const char* tag =
"\
<kind> KEEP_BAD </kind>\
";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLHistoryQosPolicy_wrapper(titleElement, historyQos, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLHistoryQosPolicy_wrapper(titleElement, historyQos, ident));
}
/*
* This test checks the negative cases in the xml child element of <DurabilityQos>
* 1. Check invalid <kind> element
* 2. Check empty <kind> element
* 3. Check no <kind> element
* 4. Check invalid element
*/
TEST_F(XMLParserTests, getXMLDurabilityQos_NegativeClauses)
{
uint8_t ident = 1;
DurabilityQosPolicy durability;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<durabilityQosPolicy>\
%s\
</durabilityQosPolicy>\
";
char xml[1000];
// Invalid kind
{
const char* tag =
"\
<kind> BAD_KIND </kind>\
";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLDurabilityQos_wrapper(titleElement, durability, ident));
}
// Void kind
{
const char* tag =
"\
<kind> </kind>\
";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLDurabilityQos_wrapper(titleElement, durability, ident));
}
// No kind
{
const char* tag = "";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLDurabilityQos_wrapper(titleElement, durability, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLDurabilityQos_wrapper(titleElement, durability, ident));
}
/*
* This test checks the negative cases in the xml child element of <DeadlineQos>
* 1. Check invalid <period> element
* 2. Check no <period> element
* 3. Check invalid element
*/
TEST_F(XMLParserTests, getXMLDeadlineQos_NegativeClauses)
{
uint8_t ident = 1;
DeadlineQosPolicy deadline;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<deadlineQosPolicy>\
%s\
</deadlineQosPolicy>\
";
char xml[1000];
// Invalid kind
{
const char* tag =
"\
<period> BAD_PERIOD </period>\
";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLDeadlineQos_wrapper(titleElement, deadline, ident));
}
// No period
{
const char* tag = "";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLDeadlineQos_wrapper(titleElement, deadline, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLDeadlineQos_wrapper(titleElement, deadline, ident));
}
/*
* This test checks the negative cases in the xml child element of <LatencyBudgetQos>
* 1. Check invalid <duration> element
* 2. Check no <duration> element
* 3. Check invalid element
*/
TEST_F(XMLParserTests, getXMLLatencyBudgetQos_NegativeClauses)
{
uint8_t ident = 1;
LatencyBudgetQosPolicy latencyBudget;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<latencyBudgetQosPolicy>\
%s\
</latencyBudgetQosPolicy>\
";
char xml[1000];
// Invalid duration
{
const char* tag =
"\
<duration> BAD_DURATION </duration>\
";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLLatencyBudgetQos_wrapper(titleElement, latencyBudget, ident));
}
// No duration
{
const char* tag = "";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLLatencyBudgetQos_wrapper(titleElement, latencyBudget, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLatencyBudgetQos_wrapper(titleElement, latencyBudget, ident));
}
/*
* This test checks the negative cases in the xml child element of <ReliabilityQos>
* 1. Check invalid <kind> element
* 2. Check empty <kind> element
* 3. Check no <max_blocking_time> element
* 4. Check invalid element
*/
TEST_F(XMLParserTests, getXMLReliabilityQos_NegativeClauses)
{
uint8_t ident = 1;
ReliabilityQosPolicy reliability;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<reliabilityQosPolicy>\
%s\
</reliabilityQosPolicy>\
";
char xml[1000];
// Invalid kind
{
const char* tag =
"\
<kind> BAD_KIND </kind>\
";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLReliabilityQos_wrapper(titleElement, reliability, ident));
}
// Void kind
{
const char* tag =
"\
<kind> </kind>\
";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLReliabilityQos_wrapper(titleElement, reliability, ident));
}
// No max_blocking_time
{
const char* tag =
"\
<max_blocking_time> BAD_MBT </max_blocking_time>\
";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLReliabilityQos_wrapper(titleElement, reliability, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLReliabilityQos_wrapper(titleElement, reliability, ident));
}
/*
* This test checks the negative cases in the xml child element of <PartitionQos>
* 1. Check invalid <names> element
* 2. Check empty <names> element
* 3. Check no <names> element
* 4. Check invalid element
*/
TEST_F(XMLParserTests, getXMLPartitionQos_NegativeClauses)
{
uint8_t ident = 1;
PartitionQosPolicy partition;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<partitionQosPolicy>\
%s\
</partitionQosPolicy>\
";
char xml[1000];
// Invalid names
{
const char* tag =
"\
<names>\
<name> </name>\
</names>\
";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLPartitionQos_wrapper(titleElement, partition, ident));
}
// Void names
{
const char* tag =
"\
<names>\
</names>\
";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLPartitionQos_wrapper(titleElement, partition, ident));
}
// Void args
{
const char* tag =
"\
";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLPartitionQos_wrapper(titleElement, partition, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLPartitionQos_wrapper(titleElement, partition, ident));
}
/*
* This test checks the negative cases in the xml child element of <WriterTimes>
* 1. Check an invalid tag of:
* <initialHeartbeatDelay>
* <heartbeatPeriod>
* <nackResponseDelay>
* <nackSupressionDuration>
* 2. Check invalid element
*/
TEST_F(XMLParserTests, getXMLWriterTimes_NegativeClauses)
{
uint8_t ident = 1;
WriterTimes times;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<writerTimes>\
%s\
</writerTimes>\
";
char xml[1000];
const char* field_p =
"\
<%s>\
<bad_element> </bad_element>\
</%s>\
";
char field[500];
std::vector<std::string> field_vec =
{
"initialHeartbeatDelay",
"heartbeatPeriod",
"nackResponseDelay",
"nackSupressionDuration",
};
for (std::string tag : field_vec)
{
sprintf(field, field_p, tag.c_str(), tag.c_str());
sprintf(xml, xml_p, field);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLWriterTimes_wrapper(titleElement, times, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLWriterTimes_wrapper(titleElement, times, ident));
}
/*
* This test checks the negative cases in the xml child element of <ReaderTimes>
* 1. Check an invalid tag of:
* <initialAcknackDelay>
* <heartbeatResponseDelay>
* 2. Check invalid element
*/
TEST_F(XMLParserTests, getXMLReaderTimes_NegativeClauses)
{
uint8_t ident = 1;
ReaderTimes times;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<readerTimes>\
%s\
</readerTimes>\
";
char xml[1000];
const char* field_p =
"\
<%s>\
<bad_element> </bad_element>\
</%s>\
";
char field[500];
std::vector<std::string> field_vec =
{
"initialAcknackDelay",
"heartbeatResponseDelay",
};
for (std::string tag : field_vec)
{
sprintf(field, field_p, tag.c_str(), tag.c_str());
sprintf(xml, xml_p, field);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLReaderTimes_wrapper(titleElement, times, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLReaderTimes_wrapper(titleElement, times, ident));
}
/*
* This test checks the negative cases in the xml child element of <LocatorUDPv4>
* 1. Check an invalid tag of:
* <port>
* <address>
* 2. Check invalid element
*/
TEST_F(XMLParserTests, getXMLLocatorUDPv4_NegativeClauses)
{
uint8_t ident = 1;
Locator_t locator;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<udpv4Locator>\
%s\
</udpv4Locator>\
";
char xml[1000];
const char* field_p =
"\
<%s>\
<bad_element> </bad_element>\
</%s>\
";
char field[500];
std::vector<std::string> field_vec =
{
"port",
"address",
};
for (std::string tag : field_vec)
{
sprintf(field, field_p, tag.c_str(), tag.c_str());
sprintf(xml, xml_p, field);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLocatorUDPv4_wrapper(titleElement, locator, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLocatorUDPv4_wrapper(titleElement, locator, ident));
}
/*
* This test checks the negative cases in the xml child element of <HistoryMemoryPolicy>
* 1. Check no elements
* 2. Check invalid element
*/
TEST_F(XMLParserTests, getXMLHistoryMemoryPolicy_NegativeClauses)
{
uint8_t ident = 1;
MemoryManagementPolicy_t historyMemoryPolicy;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<historyMemoryPolicy>\
%s\
</historyMemoryPolicy>\
";
char xml[1000];
// Void historyMemoryPolicyType
{
const char* tag = "BAD POLICY";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLHistoryMemoryPolicy_wrapper(titleElement, historyMemoryPolicy, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLHistoryMemoryPolicy_wrapper(titleElement, historyMemoryPolicy, ident));
}
/*
* This test checks the negative cases in the xml child element of <LivelinessQos>
* 1. Check an invalid tag of:
* <kind>
* <lease_duration>
* <announcement_period>
* 2. Check invalid <kind> element
* 3. Check invalid element
*/
TEST_F(XMLParserTests, getXMLLivelinessQos_NegativeClauses)
{
uint8_t ident = 1;
LivelinessQosPolicy liveliness;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<livelinessQosPolicy>\
%s\
</livelinessQosPolicy>\
";
char xml[1000];
const char* field_p =
"\
<%s>\
<bad_element> </bad_element>\
</%s>\
";
char field[500];
std::vector<std::string> field_vec =
{
"kind",
"lease_duration",
"announcement_period"
};
for (std::string tag : field_vec)
{
sprintf(field, field_p, tag.c_str(), tag.c_str());
sprintf(xml, xml_p, field);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLivelinessQos_wrapper(titleElement, liveliness, ident));
}
// Invalid kind
{
const char* tag = "<kind> BAD_KIND </kind>";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLivelinessQos_wrapper(titleElement, liveliness, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLLivelinessQos_wrapper(titleElement, liveliness, ident));
}
/*
* This test checks the negative cases in the xml child element of <PublishModeQos>
* 1. Check invalid <kind> element
* 2. Check empty <kind> element
* 3. Check no <kind> element
* 4. Check invalid element
*/
TEST_F(XMLParserTests, getXMLPublishModeQos_NegativeClauses)
{
uint8_t ident = 1;
PublishModeQosPolicy publishMode;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<publishModeQosPolicy>\
%s\
</publishModeQosPolicy>\
";
char xml[1000];
// Invalid kind
{
const char* tag = "<kind> BAD_KIND </kind>";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLPublishModeQos_wrapper(titleElement, publishMode, ident));
}
// Empty kind
{
const char* tag = "<kind> </kind>";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLPublishModeQos_wrapper(titleElement, publishMode, ident));
}
// Empty kind
{
const char* tag = "";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLPublishModeQos_wrapper(titleElement, publishMode, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLPublishModeQos_wrapper(titleElement, publishMode, ident));
}
/*
* This test checks the negative cases in the xml child element of <ParticipantAllocationAttributes>
* 1. Check an invalid tag of:
* <remote_locators>
* <total_participants>
* <total_readers>
* <total_writers>
* <send_buffers>
* <max_properties>
* <max_user_data>
* <max_partitions>
* 2. Check invalid element
*/
TEST_F(XMLParserTests, getXMLParticipantAllocationAttributes_NegativeClauses)
{
uint8_t ident = 1;
RTPSParticipantAllocationAttributes allocation;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<rtpsParticipantAllocationAttributes>\
%s\
</rtpsParticipantAllocationAttributes>\
";
char xml[1000];
const char* field_p =
"\
<%s>\
<bad_element> </bad_element>\
</%s>\
";
char field[500];
std::vector<std::string> field_vec =
{
"remote_locators",
"total_participants",
"total_readers",
"total_writers",
"send_buffers",
"max_properties",
"max_user_data",
"max_partitions"
};
for (std::string tag : field_vec)
{
sprintf(field, field_p, tag.c_str(), tag.c_str());
sprintf(xml, xml_p, field);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLParticipantAllocationAttributes_wrapper(titleElement, allocation, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLParticipantAllocationAttributes_wrapper(titleElement, allocation, ident));
}
/*
* This test checks the negative cases in the xml child element of <DiscoverySettings>
* 1. Check an invalid tag of:
* <discoveryProtocol>
* <ignoreParticipantFlags>
* <EDP>
* <leaseDuration>
* <leaseAnnouncement>
* <initialAnnouncements>
* <simpleEDP>
* <clientAnnouncementPeriod>
* <discoveryServersList>
* <static_edp_xml_config>
* 2. Check invalid <EDP> element
* 3. Check invalid <SimpleEDP <PUBWRITER_SUBREADER>> element
* 4. Check invalid <SimpleEDP <PUBREADER_SUBWRITER>> element
* 5. Check invalid element
*/
TEST_F(XMLParserTests, getXMLDiscoverySettings_NegativeClauses)
{
uint8_t ident = 1;
DiscoverySettings settings;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<discoverySettings>\
%s\
</discoverySettings>\
";
char xml[1000];
const char* field_p =
"\
<%s>\
<bad_element> </bad_element>\
</%s>\
";
char field[500];
std::vector<std::string> field_vec =
{
"discoveryProtocol",
"ignoreParticipantFlags",
"EDP",
"leaseDuration",
"leaseAnnouncement",
"initialAnnouncements",
"simpleEDP",
"clientAnnouncementPeriod",
"discoveryServersList",
"static_edp_xml_config"
};
for (std::string tag : field_vec)
{
sprintf(field, field_p, tag.c_str(), tag.c_str());
sprintf(xml, xml_p, field);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLDiscoverySettings_wrapper(titleElement, settings, ident));
}
// Bad EDP
{
const char* tag = "<EDP> BAD_EDP </EDP>";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLDiscoverySettings_wrapper(titleElement, settings, ident));
}
// Bad simpleEDP PUBWRITER_SUBREADER
{
const char* tag = "<simpleEDP> <PUBWRITER_SUBREADER> </PUBWRITER_SUBREADER> </simpleEDP>";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLDiscoverySettings_wrapper(titleElement, settings, ident));
}
// Bad simpleEDP PUBREADER_SUBWRITER
{
const char* tag = "<simpleEDP> <PUBREADER_SUBWRITER> </PUBREADER_SUBWRITER> </simpleEDP>";
sprintf(xml, xml_p, tag);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLDiscoverySettings_wrapper(titleElement, settings, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLDiscoverySettings_wrapper(titleElement, settings, ident));
}
/*
* This test checks the negative cases in the xml child element of <SendBuffersAllocationAttributes>
* 1. Check an invalid tag of:
* <preallocated_number>
* <dynamic>
* 2. Check invalid element
*/
TEST_F(XMLParserTests, getXMLSendBuffersAllocationAttributes_NegativeClauses)
{
uint8_t ident = 1;
SendBuffersAllocationAttributes allocation;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<sendBuffersAllocationConfig>\
%s\
</sendBuffersAllocationConfig>\
";
char xml[1000];
const char* field_p =
"\
<%s>\
<bad_element> </bad_element>\
</%s>\
";
char field[500];
std::vector<std::string> field_vec =
{
"preallocated_number",
"dynamic",
};
for (std::string tag : field_vec)
{
sprintf(field, field_p, tag.c_str(), tag.c_str());
sprintf(xml, xml_p, field);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLSendBuffersAllocationAttributes_wrapper(titleElement, allocation, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLSendBuffersAllocationAttributes_wrapper(titleElement, allocation, ident));
}
/*
* This test checks the negative cases in the xml child element of <RemoteLocatorsAllocationAttributes>
* 1. Check an invalid tag of:
* <max_unicast_locators>
* <max_multicast_locators>
* 2. Check invalid element
*/
TEST_F(XMLParserTests, getXMLRemoteLocatorsAllocationAttributes_NegativeClauses)
{
uint8_t ident = 1;
RemoteLocatorsAllocationAttributes allocation;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
// Parametrized XML
const char* xml_p =
"\
<remoteLocatorsAllocationConfig>\
%s\
</remoteLocatorsAllocationConfig>\
";
char xml[1000];
const char* field_p =
"\
<%s>\
<bad_element> </bad_element>\
</%s>\
";
char field[500];
std::vector<std::string> field_vec =
{
"max_unicast_locators",
"max_multicast_locators",
};
for (std::string tag : field_vec)
{
sprintf(field, field_p, tag.c_str(), tag.c_str());
sprintf(xml, xml_p, field);
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLRemoteLocatorsAllocationAttributes_wrapper(titleElement, allocation, ident));
}
// Invalid element
sprintf(xml, xml_p, "<bad_element> </bad_element>");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLRemoteLocatorsAllocationAttributes_wrapper(titleElement, allocation, ident));
}
/*
* This test checks the negative cases of parsing an enum type field with getXMLEnum
* 1. Check XMLEnum with arg IntraprocessDeliveryType
* 1. null input
* 2. empty input
* 3. invalid input
* 2. Check XMLEnum with arg DiscoveryProtocol_t
* 1. null input
* 2. empty input
* 3. invalid input
* 3. Check XMLEnum with arg ParticipantFilteringFlags_t
* 1. null input
* 2. empty input
* 3. invalid input
*/
TEST_F(XMLParserTests, getXMLEnum_NegativeClauses)
{
uint8_t ident = 1;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
char xml[1000];
// IntraprocessDeliveryType Enum
{
IntraprocessDeliveryType e;
const char* enum_p =
"\
<IntraprocessDelivery>\
%s\
</IntraprocessDelivery>\
";
// null input
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLEnum_wrapper(static_cast<tinyxml2::XMLElement*>(nullptr), &e, ident));
// void tag
sprintf(xml, enum_p, "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLEnum_wrapper(titleElement, &e, ident));
// Invalid argument
sprintf(xml, enum_p, "BAD FIELD");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLEnum_wrapper(titleElement, &e, ident));
}
// DiscoveryProtocol Enum
{
DiscoveryProtocol_t e;
const char* enum_p =
"\
<DiscoveryProtocol>\
%s\
</DiscoveryProtocol>\
";
// null input
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLEnum_wrapper(static_cast<tinyxml2::XMLElement*>(nullptr), &e, ident));
// void tag
sprintf(xml, enum_p, "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLEnum_wrapper(titleElement, &e, ident));
// Invalid argument
sprintf(xml, enum_p, "BAD FIELD");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLEnum_wrapper(titleElement, &e, ident));
}
// ParticipantFilteringFlags_t Enum
{
ParticipantFilteringFlags_t e;
const char* enum_p =
"\
<ParticipantFilteringFlags>%s</ParticipantFilteringFlags>\
";
// null input
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::getXMLEnum_wrapper(static_cast<tinyxml2::XMLElement*>(nullptr), &e, ident));
// void tag
sprintf(xml, enum_p, "");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLEnum_wrapper(titleElement, &e, ident));
// Invalid argument
sprintf(xml, enum_p, "BAD FIELD");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLEnum_wrapper(titleElement, &e, ident));
}
}
/*
* This function is not implemented, so this test checks fulfillment of the XMLElementParser coverage
* 1. Check an error message is received
*/
TEST_F(XMLParserTests, getXMLOctetVector_NegativeClauses)
{
uint8_t indent = 1;
std::vector<octet> v;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
const char* xml = "</void>";
mock_consumer = new MockConsumer();
Log::RegisterConsumer(std::unique_ptr<LogConsumer>(mock_consumer));
Log::SetCategoryFilter(std::regex("(XMLPARSER)"));
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR, XMLParserTest::getXMLOctetVector_wrapper(titleElement, v, indent));
helper_block_for_at_least_entries(1);
auto consumed_entries = mock_consumer->ConsumedEntries();
// Expect 1 log error.
uint32_t num_errors = 0;
for (const auto& entry : consumed_entries)
{
if (entry.kind == Log::Kind::Error)
{
num_errors++;
}
}
EXPECT_EQ(num_errors, 1u);
}
/*
* This test checks the positive cases in the xml child element of <XMLEnum>
* 1. Check XMLEnum with arg IntraprocessDeliveryType
* 1. INTRAPROCESS_OFF
* 2. Check XMLEnum with arg DiscoveryProtocol_t
* 1. NONE
* 2. CLIENT
* 3. SERVER
* 4. BACKUP
* 5. SUPER_CLIENT
* 3. Check XMLEnum with arg ParticipantFilteringFlags_t
* 1. FILTER_DIFFERENT_PROCESS
*/
TEST_F(XMLParserTests, getXMLEnum_positive)
{
uint8_t ident = 1;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
char xml[1000];
// IntraprocessDeliveryType Enum
{
IntraprocessDeliveryType e;
const char* enum_p =
"\
<IntraprocessDelivery>OFF</IntraprocessDelivery>\
";
// INTRAPROCESS_OFF case
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(enum_p));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLEnum_wrapper(titleElement, &e, ident));
EXPECT_EQ(IntraprocessDeliveryType::INTRAPROCESS_OFF, e);
}
// IntraprocessDeliveryType Enum
{
IntraprocessDeliveryType e;
const char* enum_p =
"\
<IntraprocessDelivery>USER_DATA_ONLY</IntraprocessDelivery>\
";
// INTRAPROCESS_OFF case
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(enum_p));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLEnum_wrapper(titleElement, &e, ident));
EXPECT_EQ(IntraprocessDeliveryType::INTRAPROCESS_USER_DATA_ONLY, e);
}
// DiscoveryProtocol Enum
{
DiscoveryProtocol_t e;
const char* enum_p =
"\
<DiscoveryProtocol>%s</DiscoveryProtocol>\
";
// NONE case
sprintf(xml, enum_p, "NONE");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLEnum_wrapper(titleElement, &e, ident));
EXPECT_EQ(DiscoveryProtocol_t::NONE, e);
// CLIENT case
sprintf(xml, enum_p, "CLIENT");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLEnum_wrapper(titleElement, &e, ident));
EXPECT_EQ(DiscoveryProtocol_t::CLIENT, e);
// SERVER case
sprintf(xml, enum_p, "SERVER");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLEnum_wrapper(titleElement, &e, ident));
EXPECT_EQ(DiscoveryProtocol_t::SERVER, e);
// BACKUP case
sprintf(xml, enum_p, "BACKUP");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLEnum_wrapper(titleElement, &e, ident));
EXPECT_EQ(DiscoveryProtocol_t::BACKUP, e);
// SUPER_CLIENT case
sprintf(xml, enum_p, "SUPER_CLIENT");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLEnum_wrapper(titleElement, &e, ident));
EXPECT_EQ(DiscoveryProtocol_t::SUPER_CLIENT, e);
}
// ParticipantFilteringFlags_t Enum
{
ParticipantFilteringFlags_t e(ParticipantFilteringFlags_t::NO_FILTER);
const char* enum_p =
"\
<ParticipantFilteringFlags>FILTER_DIFFERENT_PROCESS</ParticipantFilteringFlags>\
";
// FILTER_DIFFERENT_PROCESS case
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(enum_p));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::getXMLEnum_wrapper(titleElement, &e, ident));
EXPECT_EQ(ParticipantFilteringFlags_t::FILTER_DIFFERENT_PROCESS, e);
}
}
/*
* This test checks the proper parsing of the <data_sharing> xml elements to a DataSharingQosPolicy object.
* 1. Correct parsing of a valid <data_sharing> set to AUTO with domain IDs and shared memory directory.
* 2. Correct parsing of a valid <data_sharing> set to ON with domain IDs and shared memory directory.
* 3. Correct parsing of a valid <data_sharing> set to OFF with domain IDs and shared memory directory.
* 4. Correct parsing of a valid <data_sharing> set to AUTO with domain IDs.
* 5. Correct parsing of a valid <data_sharing> set to ON with domain IDs.
* 6. Correct parsing of a valid <data_sharing> set to OFF with domain IDs.
* 7. Correct parsing of a valid <data_sharing> set to AUTO with shared memory directory.
* 8. Correct parsing of a valid <data_sharing> set to ON with shared memory directory.
* 9. Correct parsing of a valid <data_sharing> set to OFF with shared memory directory.
*/
TEST_F(XMLParserTests, getXMLDataSharingQos)
{
uint8_t ident = 1;
DataSharingQosPolicy datasharing_policy;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
{
// Template xml
const char* xml_p =
"\
<data_sharing>\
<kind>%s</kind>\
<shared_dir>shared_dir</shared_dir>\
<domain_ids>\
<domainId>10</domainId>\
<domainId>20</domainId>\
</domain_ids>\
</data_sharing>\
";
char xml[1000];
sprintf(xml, xml_p, "AUTOMATIC");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::propertiesPolicy_wrapper(titleElement, datasharing_policy, ident));
EXPECT_EQ(datasharing_policy.kind(), DataSharingKind::AUTO);
EXPECT_EQ(datasharing_policy.shm_directory(), "shared_dir");
EXPECT_EQ(datasharing_policy.max_domains(), 0u);
EXPECT_EQ(datasharing_policy.domain_ids().size(), 2u);
EXPECT_EQ(datasharing_policy.domain_ids()[0], 10u);
EXPECT_EQ(datasharing_policy.domain_ids()[1], 20u);
sprintf(xml, xml_p, "ON");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::propertiesPolicy_wrapper(titleElement, datasharing_policy, ident));
EXPECT_EQ(datasharing_policy.kind(), DataSharingKind::ON);
EXPECT_EQ(datasharing_policy.shm_directory(), "shared_dir");
EXPECT_EQ(datasharing_policy.max_domains(), 0u);
EXPECT_EQ(datasharing_policy.domain_ids().size(), 2u);
EXPECT_EQ(datasharing_policy.domain_ids()[0], 10u);
EXPECT_EQ(datasharing_policy.domain_ids()[1], 20u);
sprintf(xml, xml_p, "OFF");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::propertiesPolicy_wrapper(titleElement, datasharing_policy, ident));
EXPECT_EQ(datasharing_policy.kind(), DataSharingKind::OFF);
EXPECT_EQ(datasharing_policy.shm_directory().size(), 0u);
EXPECT_EQ(datasharing_policy.max_domains(), 0u);
EXPECT_EQ(datasharing_policy.domain_ids().size(), 0u);
}
{
// Template xml
const char* xml_p =
"\
<data_sharing>\
<kind>%s</kind>\
<max_domains>5</max_domains>\
<domain_ids>\
<domainId>10</domainId>\
<domainId>20</domainId>\
</domain_ids>\
</data_sharing>\
";
char xml[1000];
sprintf(xml, xml_p, "AUTOMATIC");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::propertiesPolicy_wrapper(titleElement, datasharing_policy, ident));
EXPECT_EQ(datasharing_policy.kind(), DataSharingKind::AUTO);
EXPECT_EQ(datasharing_policy.shm_directory().size(), 0u);
EXPECT_EQ(datasharing_policy.max_domains(), 5u);
EXPECT_EQ(datasharing_policy.domain_ids().size(), 2u);
EXPECT_EQ(datasharing_policy.domain_ids()[0], 10u);
EXPECT_EQ(datasharing_policy.domain_ids()[1], 20u);
sprintf(xml, xml_p, "ON");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::propertiesPolicy_wrapper(titleElement, datasharing_policy, ident));
EXPECT_EQ(datasharing_policy.kind(), DataSharingKind::ON);
EXPECT_EQ(datasharing_policy.shm_directory().size(), 0u);
EXPECT_EQ(datasharing_policy.max_domains(), 5u);
EXPECT_EQ(datasharing_policy.domain_ids().size(), 2u);
EXPECT_EQ(datasharing_policy.domain_ids()[0], 10u);
EXPECT_EQ(datasharing_policy.domain_ids()[1], 20u);
sprintf(xml, xml_p, "OFF");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::propertiesPolicy_wrapper(titleElement, datasharing_policy, ident));
EXPECT_EQ(datasharing_policy.kind(), DataSharingKind::OFF);
EXPECT_EQ(datasharing_policy.shm_directory().size(), 0u);
EXPECT_EQ(datasharing_policy.max_domains(), 5u);
EXPECT_EQ(datasharing_policy.domain_ids().size(), 0u);
}
{
// Template xml
const char* xml_p =
"\
<data_sharing>\
<kind>%s</kind>\
<shared_dir>shared_dir</shared_dir>\
</data_sharing>\
";
char xml[1000];
sprintf(xml, xml_p, "AUTOMATIC");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::propertiesPolicy_wrapper(titleElement, datasharing_policy, ident));
EXPECT_EQ(datasharing_policy.kind(), DataSharingKind::AUTO);
EXPECT_EQ(datasharing_policy.shm_directory(), "shared_dir");
EXPECT_EQ(datasharing_policy.max_domains(), 0u);
EXPECT_EQ(datasharing_policy.domain_ids().size(), 0u);
sprintf(xml, xml_p, "ON");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::propertiesPolicy_wrapper(titleElement, datasharing_policy, ident));
EXPECT_EQ(datasharing_policy.kind(), DataSharingKind::ON);
EXPECT_EQ(datasharing_policy.shm_directory(), "shared_dir");
EXPECT_EQ(datasharing_policy.max_domains(), 0u);
EXPECT_EQ(datasharing_policy.domain_ids().size(), 0u);
sprintf(xml, xml_p, "OFF");
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_OK, XMLParserTest::propertiesPolicy_wrapper(titleElement, datasharing_policy, ident));
EXPECT_EQ(datasharing_policy.kind(), DataSharingKind::OFF);
EXPECT_EQ(datasharing_policy.shm_directory().size(), 0u);
EXPECT_EQ(datasharing_policy.max_domains(), 0u);
EXPECT_EQ(datasharing_policy.domain_ids().size(), 0u);
}
}
/*
* This test checks the negative cases on parsing of the <data_sharing> xml elements to a DataSharingQosPolicy object.
* 1. Check an empty list of <domain_ids>.
* 2. Check a list of <domain_ids> with more domains than the maximum.
* 3. Check no kind.
* 4. Check an invalid kind.
* 5. Check a negative max_domains.
* 6. Check empty shared_dir.
* 7. Check invalid tags (at different levels)
*/
TEST_F(XMLParserTests, getXMLDataSharingQos_negativeCases)
{
uint8_t ident = 1;
DataSharingQosPolicy datasharing_policy;
tinyxml2::XMLDocument xml_doc;
tinyxml2::XMLElement* titleElement;
{
const char* xml =
"\
<data_sharing>\
<kind>AUTOMATIC</kind>\
<domain_ids>\
</domain_ids>\
</data_sharing>\
";
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::propertiesPolicy_wrapper(titleElement, datasharing_policy, ident));
}
{
const char* xml =
"\
<data_sharing>\
<kind>AUTOMATIC</kind>\
<max_domains>1</max_domains>\
<domain_ids>\
<domainId>10</domainId>\
<domainId>20</domainId>\
</domain_ids>\
</data_sharing>\
";
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::propertiesPolicy_wrapper(titleElement, datasharing_policy, ident));
}
{
const char* xml =
"\
<data_sharing>\
<domain_ids>\
<domainId>10</domainId>\
<domainId>20</domainId>\
</domain_ids>\
</data_sharing>\
";
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::propertiesPolicy_wrapper(titleElement, datasharing_policy, ident));
}
{
const char* xml =
"\
<data_sharing>\
<kind>INVALID</kind>\
</data_sharing>\
";
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::propertiesPolicy_wrapper(titleElement, datasharing_policy, ident));
}
{
const char* xml =
"\
<data_sharing>\
<kind>AUTOMATIC</kind>\
<max_domains>-1</max_domains>\
</data_sharing>\
";
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::propertiesPolicy_wrapper(titleElement, datasharing_policy, ident));
}
{
const char* xml =
"\
<data_sharing>\
<kind>AUTOMATIC</kind>\
<shared_dir></shared_dir>\
</data_sharing>\
";
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::propertiesPolicy_wrapper(titleElement, datasharing_policy, ident));
}
{
const char* xml =
"\
<data_sharing>\
<kind>AUTOMATIC</kind>\
<invalid_tag>value</invalid_tag>\
</data_sharing>\
";
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::propertiesPolicy_wrapper(titleElement, datasharing_policy, ident));
}
{
const char* xml =
"\
<data_sharing>\
<kind>AUTOMATIC</kind>\
<domain_ids>\
<domainId>10</domainId>\
<domainId>20</domainId>\
<invalid_tag>value</invalid_tag>\
</domain_ids>\
</data_sharing>\
";
ASSERT_EQ(tinyxml2::XMLError::XML_SUCCESS, xml_doc.Parse(xml));
titleElement = xml_doc.RootElement();
EXPECT_EQ(XMLP_ret::XML_ERROR,
XMLParserTest::propertiesPolicy_wrapper(titleElement, datasharing_policy, ident));
}
}
| 1 | 23,456 | I think this mutex is only used here. Remove it. | eProsima-Fast-DDS | cpp |
@@ -234,6 +234,11 @@ func NewMutableState(
logger: logger,
metricsClient: shard.GetMetricsClient(),
}
+
+ if migration.IsDBVersionEnabled() {
+ s.dbRecordVersion = 1
+ }
+
s.executionInfo = &persistencespb.WorkflowExecutionInfo{
WorkflowTaskVersion: common.EmptyVersion,
WorkflowTaskScheduleId: common.EmptyEventID, | 1 | // The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// 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.
package workflow
import (
"fmt"
"math/rand"
"time"
"github.com/gogo/protobuf/proto"
"github.com/pborman/uuid"
commandpb "go.temporal.io/api/command/v1"
commonpb "go.temporal.io/api/common/v1"
enumspb "go.temporal.io/api/enums/v1"
failurepb "go.temporal.io/api/failure/v1"
historypb "go.temporal.io/api/history/v1"
"go.temporal.io/api/serviceerror"
taskqueuepb "go.temporal.io/api/taskqueue/v1"
workflowpb "go.temporal.io/api/workflow/v1"
"go.temporal.io/api/workflowservice/v1"
enumsspb "go.temporal.io/server/api/enums/v1"
historyspb "go.temporal.io/server/api/history/v1"
"go.temporal.io/server/api/historyservice/v1"
persistencespb "go.temporal.io/server/api/persistence/v1"
workflowspb "go.temporal.io/server/api/workflow/v1"
"go.temporal.io/server/common"
"go.temporal.io/server/common/backoff"
"go.temporal.io/server/common/cache"
"go.temporal.io/server/common/clock"
"go.temporal.io/server/common/cluster"
"go.temporal.io/server/common/convert"
"go.temporal.io/server/common/definition"
"go.temporal.io/server/common/enums"
"go.temporal.io/server/common/log"
"go.temporal.io/server/common/log/tag"
"go.temporal.io/server/common/metrics"
"go.temporal.io/server/common/migration"
"go.temporal.io/server/common/persistence"
"go.temporal.io/server/common/persistence/versionhistory"
"go.temporal.io/server/common/primitives/timestamp"
"go.temporal.io/server/common/searchattribute"
"go.temporal.io/server/service/history/configs"
"go.temporal.io/server/service/history/consts"
"go.temporal.io/server/service/history/events"
"go.temporal.io/server/service/history/shard"
)
const (
emptyUUID = "emptyUuid"
mutableStateInvalidHistoryActionMsg = "invalid history builder state for action"
mutableStateInvalidHistoryActionMsgTemplate = mutableStateInvalidHistoryActionMsg + ": %v"
)
var (
// ErrWorkflowFinished indicates trying to mutate mutable state after workflow finished
ErrWorkflowFinished = serviceerror.NewInternal("invalid mutable state action: mutation after finish")
// ErrMissingTimerInfo indicates missing timer info
ErrMissingTimerInfo = serviceerror.NewInternal("unable to get timer info")
// ErrMissingActivityInfo indicates missing activity info
ErrMissingActivityInfo = serviceerror.NewInternal("unable to get activity info")
// ErrMissingChildWorkflowInfo indicates missing child workflow info
ErrMissingChildWorkflowInfo = serviceerror.NewInternal("unable to get child workflow info")
// ErrMissingRequestCancelInfo indicates missing request cancel info
ErrMissingRequestCancelInfo = serviceerror.NewInternal("unable to get request cancel info")
// ErrMissingSignalInfo indicates missing signal external
ErrMissingSignalInfo = serviceerror.NewInternal("unable to get signal info")
// ErrMissingWorkflowStartEvent indicates missing workflow start event
ErrMissingWorkflowStartEvent = serviceerror.NewInternal("unable to get workflow start event")
// ErrMissingWorkflowCompletionEvent indicates missing workflow completion event
ErrMissingWorkflowCompletionEvent = serviceerror.NewInternal("unable to get workflow completion event")
// ErrMissingActivityScheduledEvent indicates missing workflow activity scheduled event
ErrMissingActivityScheduledEvent = serviceerror.NewInternal("unable to get activity scheduled event")
// ErrMissingChildWorkflowInitiatedEvent indicates missing child workflow initiated event
ErrMissingChildWorkflowInitiatedEvent = serviceerror.NewInternal("unable to get child workflow initiated event")
)
type (
MutableStateImpl struct {
pendingActivityTimerHeartbeats map[int64]time.Time // Schedule Event ID -> LastHeartbeatTimeoutVisibilityInSeconds.
pendingActivityInfoIDs map[int64]*persistencespb.ActivityInfo // Schedule Event ID -> Activity Info.
pendingActivityIDToEventID map[string]int64 // Activity ID -> Schedule Event ID of the activity.
updateActivityInfos map[int64]*persistencespb.ActivityInfo // Modified activities from last update.
deleteActivityInfos map[int64]struct{} // Deleted activities from last update.
syncActivityTasks map[int64]struct{} // Activity to be sync to remote
pendingTimerInfoIDs map[string]*persistencespb.TimerInfo // User Timer ID -> Timer Info.
pendingTimerEventIDToID map[int64]string // User Timer Start Event ID -> User Timer ID.
updateTimerInfos map[string]*persistencespb.TimerInfo // Modified timers from last update.
deleteTimerInfos map[string]struct{} // Deleted timers from last update.
pendingChildExecutionInfoIDs map[int64]*persistencespb.ChildExecutionInfo // Initiated Event ID -> Child Execution Info
updateChildExecutionInfos map[int64]*persistencespb.ChildExecutionInfo // Modified ChildExecution Infos since last update
deleteChildExecutionInfos map[int64]struct{} // Deleted ChildExecution Info since last update
pendingRequestCancelInfoIDs map[int64]*persistencespb.RequestCancelInfo // Initiated Event ID -> RequestCancelInfo
updateRequestCancelInfos map[int64]*persistencespb.RequestCancelInfo // Modified RequestCancel Infos since last update, for persistence update
deleteRequestCancelInfos map[int64]struct{} // Deleted RequestCancel Info since last update, for persistence update
pendingSignalInfoIDs map[int64]*persistencespb.SignalInfo // Initiated Event ID -> SignalInfo
updateSignalInfos map[int64]*persistencespb.SignalInfo // Modified SignalInfo since last update
deleteSignalInfos map[int64]struct{} // Deleted SignalInfo since last update
pendingSignalRequestedIDs map[string]struct{} // Set of signaled requestIds
updateSignalRequestedIDs map[string]struct{} // Set of signaled requestIds since last update
deleteSignalRequestedIDs map[string]struct{} // Deleted signaled requestId
executionInfo *persistencespb.WorkflowExecutionInfo // Workflow mutable state info.
executionState *persistencespb.WorkflowExecutionState
hBuilder *HistoryBuilder
// in memory only attributes
// indicate the current version
currentVersion int64
// buffer events from DB
bufferEventsInDB []*historypb.HistoryEvent
// indicates the workflow state in DB, can be used to calculate
// whether this workflow is pointed by current workflow record
stateInDB enumsspb.WorkflowExecutionState
// TODO deprecate nextEventIDInDB in favor of dbRecordVersion
// indicates the next event ID in DB, for conditional update
nextEventIDInDB int64
// indicates the DB record version, for conditional update
dbRecordVersion int64
// namespace entry contains a snapshot of namespace
// NOTE: do not use the failover version inside, use currentVersion above
namespaceEntry *cache.NamespaceCacheEntry
// record if a event has been applied to mutable state
// TODO: persist this to db
appliedEvents map[string]struct{}
InsertTransferTasks []persistence.Task
InsertTimerTasks []persistence.Task
InsertReplicationTasks []persistence.Task
InsertVisibilityTasks []persistence.Task
// do not rely on this, this is only updated on
// Load() and closeTransactionXXX methods. So when
// a transaction is in progress, this value will be
// wrong. This exist primarily for visibility via CLI
checksum *persistencespb.Checksum
taskGenerator TaskGenerator
workflowTaskManager *workflowTaskStateMachine
QueryRegistry QueryRegistry
shard shard.Context
clusterMetadata cluster.Metadata
eventsCache events.Cache
config *configs.Config
timeSource clock.TimeSource
logger log.Logger
metricsClient metrics.Client
}
)
var _ MutableState = (*MutableStateImpl)(nil)
func NewMutableState(
shard shard.Context,
eventsCache events.Cache,
logger log.Logger,
namespaceEntry *cache.NamespaceCacheEntry,
startTime time.Time,
) *MutableStateImpl {
s := &MutableStateImpl{
updateActivityInfos: make(map[int64]*persistencespb.ActivityInfo),
pendingActivityTimerHeartbeats: make(map[int64]time.Time),
pendingActivityInfoIDs: make(map[int64]*persistencespb.ActivityInfo),
pendingActivityIDToEventID: make(map[string]int64),
deleteActivityInfos: make(map[int64]struct{}),
syncActivityTasks: make(map[int64]struct{}),
pendingTimerInfoIDs: make(map[string]*persistencespb.TimerInfo),
pendingTimerEventIDToID: make(map[int64]string),
updateTimerInfos: make(map[string]*persistencespb.TimerInfo),
deleteTimerInfos: make(map[string]struct{}),
updateChildExecutionInfos: make(map[int64]*persistencespb.ChildExecutionInfo),
pendingChildExecutionInfoIDs: make(map[int64]*persistencespb.ChildExecutionInfo),
deleteChildExecutionInfos: make(map[int64]struct{}),
updateRequestCancelInfos: make(map[int64]*persistencespb.RequestCancelInfo),
pendingRequestCancelInfoIDs: make(map[int64]*persistencespb.RequestCancelInfo),
deleteRequestCancelInfos: make(map[int64]struct{}),
updateSignalInfos: make(map[int64]*persistencespb.SignalInfo),
pendingSignalInfoIDs: make(map[int64]*persistencespb.SignalInfo),
deleteSignalInfos: make(map[int64]struct{}),
updateSignalRequestedIDs: make(map[string]struct{}),
pendingSignalRequestedIDs: make(map[string]struct{}),
deleteSignalRequestedIDs: make(map[string]struct{}),
currentVersion: namespaceEntry.GetFailoverVersion(),
bufferEventsInDB: nil,
stateInDB: enumsspb.WORKFLOW_EXECUTION_STATE_VOID,
nextEventIDInDB: common.FirstEventID,
dbRecordVersion: 0,
namespaceEntry: namespaceEntry,
appliedEvents: make(map[string]struct{}),
QueryRegistry: NewQueryRegistry(),
shard: shard,
clusterMetadata: shard.GetClusterMetadata(),
eventsCache: eventsCache,
config: shard.GetConfig(),
timeSource: shard.GetTimeSource(),
logger: logger,
metricsClient: shard.GetMetricsClient(),
}
s.executionInfo = &persistencespb.WorkflowExecutionInfo{
WorkflowTaskVersion: common.EmptyVersion,
WorkflowTaskScheduleId: common.EmptyEventID,
WorkflowTaskStartedId: common.EmptyEventID,
WorkflowTaskRequestId: emptyUUID,
WorkflowTaskTimeout: timestamp.DurationFromSeconds(0),
WorkflowTaskAttempt: 1,
LastWorkflowTaskStartId: common.EmptyEventID,
StartTime: timestamp.TimePtr(startTime),
VersionHistories: versionhistory.NewVersionHistories(&historyspb.VersionHistory{}),
}
s.executionState = &persistencespb.WorkflowExecutionState{State: enumsspb.WORKFLOW_EXECUTION_STATE_CREATED,
Status: enumspb.WORKFLOW_EXECUTION_STATUS_RUNNING}
s.hBuilder = NewMutableHistoryBuilder(
s.timeSource,
s.shard.GenerateTransferTaskIDs,
s.currentVersion,
common.FirstEventID,
s.bufferEventsInDB,
)
s.taskGenerator = NewTaskGenerator(shard.GetNamespaceCache(), s.logger, s)
s.workflowTaskManager = newWorkflowTaskStateMachine(s)
return s
}
func newMutableStateBuilderFromDB(
shard shard.Context,
eventsCache events.Cache,
logger log.Logger,
namespaceEntry *cache.NamespaceCacheEntry,
dbRecord *persistencespb.WorkflowMutableState,
dbRecordVersion int64,
) (*MutableStateImpl, error) {
// startTime will be overridden by DB record
startTime := time.Time{}
mutableState := NewMutableState(shard, eventsCache, logger, namespaceEntry, startTime)
if dbRecord.ActivityInfos != nil {
mutableState.pendingActivityInfoIDs = dbRecord.ActivityInfos
}
for _, activityInfo := range dbRecord.ActivityInfos {
mutableState.pendingActivityIDToEventID[activityInfo.ActivityId] = activityInfo.ScheduleId
if (activityInfo.TimerTaskStatus & TimerTaskStatusCreatedHeartbeat) > 0 {
// Sets last pending timer heartbeat to year 2000.
// This ensures at least one heartbeat task will be processed for the pending activity.
mutableState.pendingActivityTimerHeartbeats[activityInfo.ScheduleId] = time.Unix(946684800, 0)
}
}
if dbRecord.TimerInfos != nil {
mutableState.pendingTimerInfoIDs = dbRecord.TimerInfos
}
for _, timerInfo := range dbRecord.TimerInfos {
mutableState.pendingTimerEventIDToID[timerInfo.GetStartedId()] = timerInfo.GetTimerId()
}
if dbRecord.ChildExecutionInfos != nil {
mutableState.pendingChildExecutionInfoIDs = dbRecord.ChildExecutionInfos
}
if dbRecord.RequestCancelInfos != nil {
mutableState.pendingRequestCancelInfoIDs = dbRecord.RequestCancelInfos
}
if dbRecord.SignalInfos != nil {
mutableState.pendingSignalInfoIDs = dbRecord.SignalInfos
}
mutableState.pendingSignalRequestedIDs = convert.StringSliceToSet(dbRecord.SignalRequestedIds)
mutableState.executionInfo = dbRecord.ExecutionInfo
// Workflows created before 1.11 doesn't have ExecutionTime and it must be computed for backwards compatibility.
// Remove this "if" block when it is ok to rely on executionInfo.ExecutionTime only (added 6/9/21).
if mutableState.executionInfo.ExecutionTime == nil {
startEvent, err := mutableState.GetStartEvent()
if err != nil {
return nil, err
}
backoffDuration := timestamp.DurationValue(startEvent.GetWorkflowExecutionStartedEventAttributes().GetFirstWorkflowTaskBackoff())
mutableState.executionInfo.ExecutionTime = timestamp.TimePtr(timestamp.TimeValue(mutableState.executionInfo.GetStartTime()).Add(backoffDuration))
}
mutableState.executionState = dbRecord.ExecutionState
mutableState.hBuilder = NewMutableHistoryBuilder(
mutableState.timeSource,
mutableState.shard.GenerateTransferTaskIDs,
common.EmptyVersion,
dbRecord.NextEventId,
dbRecord.BufferedEvents,
)
mutableState.currentVersion = common.EmptyVersion
mutableState.bufferEventsInDB = dbRecord.BufferedEvents
mutableState.stateInDB = dbRecord.ExecutionState.State
mutableState.nextEventIDInDB = dbRecord.NextEventId
mutableState.dbRecordVersion = dbRecordVersion
mutableState.checksum = dbRecord.Checksum
if len(dbRecord.Checksum.GetValue()) > 0 {
switch {
case mutableState.shouldInvalidateCheckum():
mutableState.checksum = nil
mutableState.metricsClient.IncCounter(metrics.WorkflowContextScope, metrics.MutableStateChecksumInvalidated)
case mutableState.shouldVerifyChecksum():
if err := verifyMutableStateChecksum(mutableState, dbRecord.Checksum); err != nil {
// we ignore checksum verification errors for now until this
// feature is tested and/or we have mechanisms in place to deal
// with these types of errors
mutableState.metricsClient.IncCounter(metrics.WorkflowContextScope, metrics.MutableStateChecksumMismatch)
mutableState.logError("mutable state checksum mismatch", tag.Error(err))
}
}
}
return mutableState, nil
}
func (e *MutableStateImpl) CloneToProto() *persistencespb.WorkflowMutableState {
ms := &persistencespb.WorkflowMutableState{
ActivityInfos: e.pendingActivityInfoIDs,
TimerInfos: e.pendingTimerInfoIDs,
ChildExecutionInfos: e.pendingChildExecutionInfoIDs,
RequestCancelInfos: e.pendingRequestCancelInfoIDs,
SignalInfos: e.pendingSignalInfoIDs,
SignalRequestedIds: convert.StringSetToSlice(e.pendingSignalRequestedIDs),
ExecutionInfo: e.executionInfo,
ExecutionState: e.executionState,
NextEventId: e.hBuilder.NextEventID(),
BufferedEvents: e.bufferEventsInDB,
Checksum: e.checksum,
}
return proto.Clone(ms).(*persistencespb.WorkflowMutableState)
}
func (e *MutableStateImpl) GetCurrentBranchToken() ([]byte, error) {
currentVersionHistory, err := versionhistory.GetCurrentVersionHistory(e.executionInfo.VersionHistories)
if err != nil {
return nil, err
}
return currentVersionHistory.GetBranchToken(), nil
}
// SetHistoryTree set treeID/historyBranches
func (e *MutableStateImpl) SetHistoryTree(
treeID string,
) error {
initialBranchToken, err := persistence.NewHistoryBranchToken(treeID)
if err != nil {
return err
}
return e.SetCurrentBranchToken(initialBranchToken)
}
func (e *MutableStateImpl) SetCurrentBranchToken(
branchToken []byte,
) error {
currentVersionHistory, err := versionhistory.GetCurrentVersionHistory(e.executionInfo.VersionHistories)
if err != nil {
return err
}
versionhistory.SetVersionHistoryBranchToken(currentVersionHistory, branchToken)
return nil
}
func (e *MutableStateImpl) SetHistoryBuilder(hBuilder *HistoryBuilder) {
e.hBuilder = hBuilder
}
func (e *MutableStateImpl) GetExecutionInfo() *persistencespb.WorkflowExecutionInfo {
return e.executionInfo
}
func (e *MutableStateImpl) GetExecutionState() *persistencespb.WorkflowExecutionState {
return e.executionState
}
func (e *MutableStateImpl) FlushBufferedEvents() {
if e.HasInFlightWorkflowTask() {
return
}
e.updatePendingEventIDs(e.hBuilder.FlushBufferToCurrentBatch())
}
func (e *MutableStateImpl) UpdateCurrentVersion(
version int64,
forceUpdate bool,
) error {
if state, _ := e.GetWorkflowStateStatus(); state == enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED {
// do not update current version only when workflow is completed
return nil
}
versionHistory, err := versionhistory.GetCurrentVersionHistory(e.executionInfo.VersionHistories)
if err != nil {
return err
}
if !versionhistory.IsEmptyVersionHistory(versionHistory) {
// this make sure current version >= last write version
versionHistoryItem, err := versionhistory.GetLastVersionHistoryItem(versionHistory)
if err != nil {
return err
}
e.currentVersion = versionHistoryItem.GetVersion()
}
if version > e.currentVersion || forceUpdate {
e.currentVersion = version
}
e.hBuilder = NewMutableHistoryBuilder(
e.timeSource,
e.shard.GenerateTransferTaskIDs,
e.currentVersion,
e.nextEventIDInDB,
e.bufferEventsInDB,
)
return nil
}
func (e *MutableStateImpl) GetCurrentVersion() int64 {
if e.executionInfo.VersionHistories != nil {
return e.currentVersion
}
return common.EmptyVersion
}
func (e *MutableStateImpl) GetStartVersion() (int64, error) {
if e.executionInfo.VersionHistories != nil {
versionHistory, err := versionhistory.GetCurrentVersionHistory(e.executionInfo.VersionHistories)
if err != nil {
return 0, err
}
firstItem, err := versionhistory.GetFirstVersionHistoryItem(versionHistory)
if err != nil {
return 0, err
}
return firstItem.GetVersion(), nil
}
return common.EmptyVersion, nil
}
func (e *MutableStateImpl) GetLastWriteVersion() (int64, error) {
if e.executionInfo.VersionHistories != nil {
versionHistory, err := versionhistory.GetCurrentVersionHistory(e.executionInfo.VersionHistories)
if err != nil {
return 0, err
}
lastItem, err := versionhistory.GetLastVersionHistoryItem(versionHistory)
if err != nil {
return 0, err
}
return lastItem.GetVersion(), nil
}
return common.EmptyVersion, nil
}
func (e *MutableStateImpl) IsCurrentWorkflowGuaranteed() bool {
// stateInDB is used like a bloom filter:
//
// 1. stateInDB being created / running meaning that this workflow must be the current
// workflow (assuming there is no rebuild of mutable state).
// 2. stateInDB being completed does not guarantee this workflow being the current workflow
// 3. stateInDB being zombie guarantees this workflow not being the current workflow
// 4. stateInDB cannot be void, void is only possible when mutable state is just initialized
switch e.stateInDB {
case enumsspb.WORKFLOW_EXECUTION_STATE_VOID:
return false
case enumsspb.WORKFLOW_EXECUTION_STATE_CREATED:
return true
case enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING:
return true
case enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED:
return false
case enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE:
return false
case enumsspb.WORKFLOW_EXECUTION_STATE_CORRUPTED:
return false
default:
panic(fmt.Sprintf("unknown workflow state: %v", e.executionState.State))
}
}
func (e *MutableStateImpl) GetNamespaceEntry() *cache.NamespaceCacheEntry {
return e.namespaceEntry
}
func (e *MutableStateImpl) IsStickyTaskQueueEnabled() bool {
return e.executionInfo.StickyTaskQueue != ""
}
func (e *MutableStateImpl) GetWorkflowType() *commonpb.WorkflowType {
wType := &commonpb.WorkflowType{}
wType.Name = e.executionInfo.WorkflowTypeName
return wType
}
func (e *MutableStateImpl) GetQueryRegistry() QueryRegistry {
return e.QueryRegistry
}
func (e *MutableStateImpl) GetActivityScheduledEvent(
scheduleEventID int64,
) (*historypb.HistoryEvent, error) {
ai, ok := e.pendingActivityInfoIDs[scheduleEventID]
if !ok {
return nil, ErrMissingActivityInfo
}
currentBranchToken, err := e.GetCurrentBranchToken()
if err != nil {
return nil, err
}
scheduledEvent, err := e.eventsCache.GetEvent(
e.executionInfo.NamespaceId,
e.executionInfo.WorkflowId,
e.executionState.RunId,
ai.ScheduledEventBatchId,
ai.ScheduleId,
currentBranchToken,
)
if err != nil {
// do not return the original error
// since original error can be of type entity not exists
// which can cause task processing side to fail silently
return nil, ErrMissingActivityScheduledEvent
}
return scheduledEvent, nil
}
// GetActivityInfo gives details about an activity that is currently in progress.
func (e *MutableStateImpl) GetActivityInfo(
scheduleEventID int64,
) (*persistencespb.ActivityInfo, bool) {
ai, ok := e.pendingActivityInfoIDs[scheduleEventID]
return ai, ok
}
// GetActivityInfoWithTimerHeartbeat gives details about an activity that is currently in progress.
func (e *MutableStateImpl) GetActivityInfoWithTimerHeartbeat(
scheduleEventID int64,
) (*persistencespb.ActivityInfo, time.Time, bool) {
ai, ok := e.pendingActivityInfoIDs[scheduleEventID]
timerVis, ok := e.pendingActivityTimerHeartbeats[scheduleEventID]
return ai, timerVis, ok
}
// GetActivityByActivityID gives details about an activity that is currently in progress.
func (e *MutableStateImpl) GetActivityByActivityID(
activityID string,
) (*persistencespb.ActivityInfo, bool) {
eventID, ok := e.pendingActivityIDToEventID[activityID]
if !ok {
return nil, false
}
return e.GetActivityInfo(eventID)
}
// GetChildExecutionInfo gives details about a child execution that is currently in progress.
func (e *MutableStateImpl) GetChildExecutionInfo(
initiatedEventID int64,
) (*persistencespb.ChildExecutionInfo, bool) {
ci, ok := e.pendingChildExecutionInfoIDs[initiatedEventID]
return ci, ok
}
// GetChildExecutionInitiatedEvent reads out the ChildExecutionInitiatedEvent from mutable state for in-progress child
// executions
func (e *MutableStateImpl) GetChildExecutionInitiatedEvent(
initiatedEventID int64,
) (*historypb.HistoryEvent, error) {
ci, ok := e.pendingChildExecutionInfoIDs[initiatedEventID]
if !ok {
return nil, ErrMissingChildWorkflowInfo
}
currentBranchToken, err := e.GetCurrentBranchToken()
if err != nil {
return nil, err
}
initiatedEvent, err := e.eventsCache.GetEvent(
e.executionInfo.NamespaceId,
e.executionInfo.WorkflowId,
e.executionState.RunId,
ci.InitiatedEventBatchId,
ci.InitiatedId,
currentBranchToken,
)
if err != nil {
// do not return the original error
// since original error can be of type entity not exists
// which can cause task processing side to fail silently
return nil, ErrMissingChildWorkflowInitiatedEvent
}
return initiatedEvent, nil
}
// GetRequestCancelInfo gives details about a request cancellation that is currently in progress.
func (e *MutableStateImpl) GetRequestCancelInfo(
initiatedEventID int64,
) (*persistencespb.RequestCancelInfo, bool) {
ri, ok := e.pendingRequestCancelInfoIDs[initiatedEventID]
return ri, ok
}
func (e *MutableStateImpl) GetRetryBackoffDuration(
failure *failurepb.Failure,
) (time.Duration, enumspb.RetryState) {
info := e.executionInfo
if !info.HasRetryPolicy {
return backoff.NoBackoff, enumspb.RETRY_STATE_RETRY_POLICY_NOT_SET
}
return getBackoffInterval(
e.timeSource.Now(),
info.Attempt,
info.RetryMaximumAttempts,
info.RetryInitialInterval,
info.RetryMaximumInterval,
info.WorkflowExecutionExpirationTime,
info.RetryBackoffCoefficient,
failure,
info.RetryNonRetryableErrorTypes,
)
}
func (e *MutableStateImpl) GetCronBackoffDuration() (time.Duration, error) {
if e.executionInfo.CronSchedule == "" {
return backoff.NoBackoff, nil
}
executionTime := timestamp.TimeValue(e.GetExecutionInfo().GetExecutionTime())
return backoff.GetBackoffForNextSchedule(e.executionInfo.CronSchedule, executionTime, e.timeSource.Now()), nil
}
// GetSignalInfo get details about a signal request that is currently in progress.
func (e *MutableStateImpl) GetSignalInfo(
initiatedEventID int64,
) (*persistencespb.SignalInfo, bool) {
ri, ok := e.pendingSignalInfoIDs[initiatedEventID]
return ri, ok
}
// GetCompletionEvent retrieves the workflow completion event from mutable state
func (e *MutableStateImpl) GetCompletionEvent() (*historypb.HistoryEvent, error) {
if e.executionState.State != enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED {
return nil, ErrMissingWorkflowCompletionEvent
}
currentBranchToken, err := e.GetCurrentBranchToken()
if err != nil {
return nil, err
}
// Completion EventID is always one less than NextEventID after workflow is completed
completionEventID := e.hBuilder.NextEventID() - 1
firstEventID := e.executionInfo.CompletionEventBatchId
completionEvent, err := e.eventsCache.GetEvent(
e.executionInfo.NamespaceId,
e.executionInfo.WorkflowId,
e.executionState.RunId,
firstEventID,
completionEventID,
currentBranchToken,
)
if err != nil {
// do not return the original error
// since original error can be of type entity not exists
// which can cause task processing side to fail silently
return nil, ErrMissingWorkflowCompletionEvent
}
return completionEvent, nil
}
// GetStartEvent retrieves the workflow start event from mutable state
func (e *MutableStateImpl) GetStartEvent() (*historypb.HistoryEvent, error) {
currentBranchToken, err := e.GetCurrentBranchToken()
if err != nil {
return nil, err
}
startEvent, err := e.eventsCache.GetEvent(
e.executionInfo.NamespaceId,
e.executionInfo.WorkflowId,
e.executionState.RunId,
common.FirstEventID,
common.FirstEventID,
currentBranchToken,
)
if err != nil {
// do not return the original error
// since original error can be of type entity not exists
// which can cause task processing side to fail silently
return nil, ErrMissingWorkflowStartEvent
}
return startEvent, nil
}
// DeletePendingChildExecution deletes details about a ChildExecutionInfo.
func (e *MutableStateImpl) DeletePendingChildExecution(
initiatedEventID int64,
) error {
if _, ok := e.pendingChildExecutionInfoIDs[initiatedEventID]; ok {
delete(e.pendingChildExecutionInfoIDs, initiatedEventID)
} else {
e.logError(
fmt.Sprintf("unable to find child workflow event ID: %v in mutable state", initiatedEventID),
tag.ErrorTypeInvalidMutableStateAction,
)
// log data inconsistency instead of returning an error
e.logDataInconsistency()
}
delete(e.updateChildExecutionInfos, initiatedEventID)
e.deleteChildExecutionInfos[initiatedEventID] = struct{}{}
return nil
}
// DeletePendingRequestCancel deletes details about a RequestCancelInfo.
func (e *MutableStateImpl) DeletePendingRequestCancel(
initiatedEventID int64,
) error {
if _, ok := e.pendingRequestCancelInfoIDs[initiatedEventID]; ok {
delete(e.pendingRequestCancelInfoIDs, initiatedEventID)
} else {
e.logError(
fmt.Sprintf("unable to find request cancel external workflow event ID: %v in mutable state", initiatedEventID),
tag.ErrorTypeInvalidMutableStateAction,
)
// log data inconsistency instead of returning an error
e.logDataInconsistency()
}
delete(e.updateRequestCancelInfos, initiatedEventID)
e.deleteRequestCancelInfos[initiatedEventID] = struct{}{}
return nil
}
// DeletePendingSignal deletes details about a SignalInfo
func (e *MutableStateImpl) DeletePendingSignal(
initiatedEventID int64,
) error {
if _, ok := e.pendingSignalInfoIDs[initiatedEventID]; ok {
delete(e.pendingSignalInfoIDs, initiatedEventID)
} else {
e.logError(
fmt.Sprintf("unable to find signal external workflow event ID: %v in mutable state", initiatedEventID),
tag.ErrorTypeInvalidMutableStateAction,
)
// log data inconsistency instead of returning an error
e.logDataInconsistency()
}
delete(e.updateSignalInfos, initiatedEventID)
e.deleteSignalInfos[initiatedEventID] = struct{}{}
return nil
}
func (e *MutableStateImpl) writeEventToCache(
event *historypb.HistoryEvent,
) {
// For start event: store it within events cache so the recordWorkflowStarted transfer task doesn't need to
// load it from database
// For completion event: store it within events cache so we can communicate the result to parent execution
// during the processing of DeleteTransferTask without loading this event from database
e.eventsCache.PutEvent(
e.executionInfo.NamespaceId,
e.executionInfo.WorkflowId,
e.executionState.RunId,
event.GetEventId(),
event,
)
}
func (e *MutableStateImpl) HasParentExecution() bool {
return e.executionInfo.ParentNamespaceId != "" && e.executionInfo.ParentWorkflowId != ""
}
func (e *MutableStateImpl) UpdateActivityProgress(
ai *persistencespb.ActivityInfo,
request *workflowservice.RecordActivityTaskHeartbeatRequest,
) {
ai.Version = e.GetCurrentVersion()
ai.LastHeartbeatDetails = request.Details
now := e.timeSource.Now()
ai.LastHeartbeatUpdateTime = &now
e.updateActivityInfos[ai.ScheduleId] = ai
e.syncActivityTasks[ai.ScheduleId] = struct{}{}
}
// ReplicateActivityInfo replicate the necessary activity information
func (e *MutableStateImpl) ReplicateActivityInfo(
request *historyservice.SyncActivityRequest,
resetActivityTimerTaskStatus bool,
) error {
ai, ok := e.pendingActivityInfoIDs[request.GetScheduledId()]
if !ok {
e.logError(
fmt.Sprintf("unable to find activity event ID: %v in mutable state", request.GetScheduledId()),
tag.ErrorTypeInvalidMutableStateAction,
)
return ErrMissingActivityInfo
}
ai.Version = request.GetVersion()
ai.ScheduledTime = request.GetScheduledTime()
ai.StartedId = request.GetStartedId()
ai.LastHeartbeatUpdateTime = request.GetLastHeartbeatTime()
if ai.StartedId == common.EmptyEventID {
ai.StartedTime = timestamp.TimePtr(time.Time{})
} else {
ai.StartedTime = request.GetStartedTime()
}
ai.LastHeartbeatDetails = request.GetDetails()
ai.Attempt = request.GetAttempt()
ai.RetryLastWorkerIdentity = request.GetLastWorkerIdentity()
ai.RetryLastFailure = request.GetLastFailure()
if resetActivityTimerTaskStatus {
ai.TimerTaskStatus = TimerTaskStatusNone
}
e.updateActivityInfos[ai.ScheduleId] = ai
return nil
}
// UpdateActivity updates an activity
func (e *MutableStateImpl) UpdateActivity(
ai *persistencespb.ActivityInfo,
) error {
if _, ok := e.pendingActivityInfoIDs[ai.ScheduleId]; !ok {
e.logError(
fmt.Sprintf("unable to find activity ID: %v in mutable state", ai.ActivityId),
tag.ErrorTypeInvalidMutableStateAction,
)
return ErrMissingActivityInfo
}
e.pendingActivityInfoIDs[ai.ScheduleId] = ai
e.updateActivityInfos[ai.ScheduleId] = ai
return nil
}
// UpdateActivityWithTimerHeartbeat updates an activity
func (e *MutableStateImpl) UpdateActivityWithTimerHeartbeat(
ai *persistencespb.ActivityInfo,
timerTimeoutVisibility time.Time,
) error {
err := e.UpdateActivity(ai)
if err != nil {
return err
}
e.pendingActivityTimerHeartbeats[ai.ScheduleId] = timerTimeoutVisibility
return nil
}
// DeleteActivity deletes details about an activity.
func (e *MutableStateImpl) DeleteActivity(
scheduleEventID int64,
) error {
if activityInfo, ok := e.pendingActivityInfoIDs[scheduleEventID]; ok {
delete(e.pendingActivityInfoIDs, scheduleEventID)
delete(e.pendingActivityTimerHeartbeats, scheduleEventID)
if _, ok = e.pendingActivityIDToEventID[activityInfo.ActivityId]; ok {
delete(e.pendingActivityIDToEventID, activityInfo.ActivityId)
} else {
e.logError(
fmt.Sprintf("unable to find activity ID: %v in mutable state", activityInfo.ActivityId),
tag.ErrorTypeInvalidMutableStateAction,
)
// log data inconsistency instead of returning an error
e.logDataInconsistency()
}
} else {
e.logError(
fmt.Sprintf("unable to find activity event id: %v in mutable state", scheduleEventID),
tag.ErrorTypeInvalidMutableStateAction,
)
// log data inconsistency instead of returning an error
e.logDataInconsistency()
}
delete(e.updateActivityInfos, scheduleEventID)
e.deleteActivityInfos[scheduleEventID] = struct{}{}
return nil
}
// GetUserTimerInfo gives details about a user timer.
func (e *MutableStateImpl) GetUserTimerInfo(
timerID string,
) (*persistencespb.TimerInfo, bool) {
timerInfo, ok := e.pendingTimerInfoIDs[timerID]
return timerInfo, ok
}
// GetUserTimerInfoByEventID gives details about a user timer.
func (e *MutableStateImpl) GetUserTimerInfoByEventID(
startEventID int64,
) (*persistencespb.TimerInfo, bool) {
timerID, ok := e.pendingTimerEventIDToID[startEventID]
if !ok {
return nil, false
}
return e.GetUserTimerInfo(timerID)
}
// UpdateUserTimer updates the user timer in progress.
func (e *MutableStateImpl) UpdateUserTimer(
ti *persistencespb.TimerInfo,
) error {
timerID, ok := e.pendingTimerEventIDToID[ti.GetStartedId()]
if !ok {
e.logError(
fmt.Sprintf("unable to find timer event ID: %v in mutable state", ti.GetStartedId()),
tag.ErrorTypeInvalidMutableStateAction,
)
return ErrMissingTimerInfo
}
if _, ok := e.pendingTimerInfoIDs[timerID]; !ok {
e.logError(
fmt.Sprintf("unable to find timer ID: %v in mutable state", timerID),
tag.ErrorTypeInvalidMutableStateAction,
)
return ErrMissingTimerInfo
}
e.pendingTimerInfoIDs[ti.TimerId] = ti
e.updateTimerInfos[ti.TimerId] = ti
return nil
}
// DeleteUserTimer deletes an user timer.
func (e *MutableStateImpl) DeleteUserTimer(
timerID string,
) error {
if timerInfo, ok := e.pendingTimerInfoIDs[timerID]; ok {
delete(e.pendingTimerInfoIDs, timerID)
if _, ok = e.pendingTimerEventIDToID[timerInfo.GetStartedId()]; ok {
delete(e.pendingTimerEventIDToID, timerInfo.GetStartedId())
} else {
e.logError(
fmt.Sprintf("unable to find timer event ID: %v in mutable state", timerID),
tag.ErrorTypeInvalidMutableStateAction,
)
// log data inconsistency instead of returning an error
e.logDataInconsistency()
}
} else {
e.logError(
fmt.Sprintf("unable to find timer ID: %v in mutable state", timerID),
tag.ErrorTypeInvalidMutableStateAction,
)
// log data inconsistency instead of returning an error
e.logDataInconsistency()
}
delete(e.updateTimerInfos, timerID)
e.deleteTimerInfos[timerID] = struct{}{}
return nil
}
// nolint:unused
func (e *MutableStateImpl) getWorkflowTaskInfo() *WorkflowTaskInfo {
taskQueue := &taskqueuepb.TaskQueue{}
if e.IsStickyTaskQueueEnabled() {
taskQueue.Name = e.executionInfo.StickyTaskQueue
taskQueue.Kind = enumspb.TASK_QUEUE_KIND_STICKY
} else {
taskQueue.Name = e.executionInfo.TaskQueue
taskQueue.Kind = enumspb.TASK_QUEUE_KIND_NORMAL
}
return &WorkflowTaskInfo{
Version: e.executionInfo.WorkflowTaskVersion,
ScheduleID: e.executionInfo.WorkflowTaskScheduleId,
StartedID: e.executionInfo.WorkflowTaskStartedId,
RequestID: e.executionInfo.WorkflowTaskRequestId,
WorkflowTaskTimeout: e.executionInfo.WorkflowTaskTimeout,
Attempt: e.executionInfo.WorkflowTaskAttempt,
StartedTime: e.executionInfo.WorkflowTaskStartedTime,
ScheduledTime: e.executionInfo.WorkflowTaskScheduledTime,
TaskQueue: taskQueue,
OriginalScheduledTime: e.executionInfo.WorkflowTaskOriginalScheduledTime,
}
}
// GetWorkflowTaskInfo returns details about the in-progress workflow task
func (e *MutableStateImpl) GetWorkflowTaskInfo(
scheduleEventID int64,
) (*WorkflowTaskInfo, bool) {
return e.workflowTaskManager.GetWorkflowTaskInfo(scheduleEventID)
}
func (e *MutableStateImpl) GetPendingActivityInfos() map[int64]*persistencespb.ActivityInfo {
return e.pendingActivityInfoIDs
}
func (e *MutableStateImpl) GetPendingTimerInfos() map[string]*persistencespb.TimerInfo {
return e.pendingTimerInfoIDs
}
func (e *MutableStateImpl) GetPendingChildExecutionInfos() map[int64]*persistencespb.ChildExecutionInfo {
return e.pendingChildExecutionInfoIDs
}
func (e *MutableStateImpl) GetPendingRequestCancelExternalInfos() map[int64]*persistencespb.RequestCancelInfo {
return e.pendingRequestCancelInfoIDs
}
func (e *MutableStateImpl) GetPendingSignalExternalInfos() map[int64]*persistencespb.SignalInfo {
return e.pendingSignalInfoIDs
}
func (e *MutableStateImpl) HasProcessedOrPendingWorkflowTask() bool {
return e.workflowTaskManager.HasProcessedOrPendingWorkflowTask()
}
func (e *MutableStateImpl) HasPendingWorkflowTask() bool {
return e.workflowTaskManager.HasPendingWorkflowTask()
}
func (e *MutableStateImpl) GetPendingWorkflowTask() (*WorkflowTaskInfo, bool) {
return e.workflowTaskManager.GetPendingWorkflowTask()
}
func (e *MutableStateImpl) HasInFlightWorkflowTask() bool {
return e.workflowTaskManager.HasInFlightWorkflowTask()
}
func (e *MutableStateImpl) GetInFlightWorkflowTask() (*WorkflowTaskInfo, bool) {
return e.workflowTaskManager.GetInFlightWorkflowTask()
}
func (e *MutableStateImpl) HasBufferedEvents() bool {
return e.hBuilder.HasBufferEvents()
}
// UpdateWorkflowTask updates a workflow task.
func (e *MutableStateImpl) UpdateWorkflowTask(
workflowTask *WorkflowTaskInfo,
) {
e.workflowTaskManager.UpdateWorkflowTask(workflowTask)
}
// DeleteWorkflowTask deletes a workflow task.
func (e *MutableStateImpl) DeleteWorkflowTask() {
e.workflowTaskManager.DeleteWorkflowTask()
}
func (e *MutableStateImpl) ClearStickyness() {
e.executionInfo.StickyTaskQueue = ""
e.executionInfo.StickyScheduleToStartTimeout = timestamp.DurationFromSeconds(0)
}
// GetLastFirstEventIDTxnID returns last first event ID and corresponding transaction ID
// first event ID is the ID of a batch of events in a single history events record
func (e *MutableStateImpl) GetLastFirstEventIDTxnID() (int64, int64) {
return e.executionInfo.LastFirstEventId, e.executionInfo.LastFirstEventTxnId
}
// GetNextEventID returns next event ID
func (e *MutableStateImpl) GetNextEventID() int64 {
return e.hBuilder.NextEventID()
}
// GetPreviousStartedEventID returns last started workflow task event ID
func (e *MutableStateImpl) GetPreviousStartedEventID() int64 {
return e.executionInfo.LastWorkflowTaskStartId
}
func (e *MutableStateImpl) IsWorkflowExecutionRunning() bool {
switch e.executionState.State {
case enumsspb.WORKFLOW_EXECUTION_STATE_CREATED:
return true
case enumsspb.WORKFLOW_EXECUTION_STATE_RUNNING:
return true
case enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED:
return false
case enumsspb.WORKFLOW_EXECUTION_STATE_ZOMBIE:
return false
case enumsspb.WORKFLOW_EXECUTION_STATE_CORRUPTED:
return false
default:
panic(fmt.Sprintf("unknown workflow state: %v", e.executionState.State))
}
}
func (e *MutableStateImpl) IsCancelRequested() bool {
return e.executionInfo.CancelRequested
}
func (e *MutableStateImpl) IsSignalRequested(
requestID string,
) bool {
if _, ok := e.pendingSignalRequestedIDs[requestID]; ok {
return true
}
return false
}
func (e *MutableStateImpl) AddSignalRequested(
requestID string,
) {
if e.pendingSignalRequestedIDs == nil {
e.pendingSignalRequestedIDs = make(map[string]struct{})
}
if e.updateSignalRequestedIDs == nil {
e.updateSignalRequestedIDs = make(map[string]struct{})
}
e.pendingSignalRequestedIDs[requestID] = struct{}{} // add requestID to set
e.updateSignalRequestedIDs[requestID] = struct{}{}
}
func (e *MutableStateImpl) DeleteSignalRequested(
requestID string,
) {
delete(e.pendingSignalRequestedIDs, requestID)
delete(e.updateSignalRequestedIDs, requestID)
e.deleteSignalRequestedIDs[requestID] = struct{}{}
}
func (e *MutableStateImpl) addWorkflowExecutionStartedEventForContinueAsNew(
parentExecutionInfo *workflowspb.ParentExecutionInfo,
execution commonpb.WorkflowExecution,
previousExecutionState MutableState,
command *commandpb.ContinueAsNewWorkflowExecutionCommandAttributes,
firstRunID string,
) (*historypb.HistoryEvent, error) {
previousExecutionInfo := previousExecutionState.GetExecutionInfo()
taskQueue := previousExecutionInfo.TaskQueue
if command.TaskQueue != nil {
taskQueue = command.TaskQueue.GetName()
}
tq := &taskqueuepb.TaskQueue{
Name: taskQueue,
Kind: enumspb.TASK_QUEUE_KIND_NORMAL,
}
workflowType := previousExecutionInfo.WorkflowTypeName
if command.WorkflowType != nil {
workflowType = command.WorkflowType.GetName()
}
wType := &commonpb.WorkflowType{}
wType.Name = workflowType
var taskTimeout *time.Duration
if timestamp.DurationValue(command.GetWorkflowTaskTimeout()) == 0 {
taskTimeout = previousExecutionInfo.DefaultWorkflowTaskTimeout
} else {
taskTimeout = command.GetWorkflowTaskTimeout()
}
// Workflow runTimeout is already set to the correct value in
// validateContinueAsNewWorkflowExecutionAttributes
runTimeout := command.GetWorkflowRunTimeout()
createRequest := &workflowservice.StartWorkflowExecutionRequest{
RequestId: uuid.New(),
Namespace: e.namespaceEntry.GetInfo().Name,
WorkflowId: execution.WorkflowId,
TaskQueue: tq,
WorkflowType: wType,
WorkflowExecutionTimeout: previousExecutionState.GetExecutionInfo().WorkflowExecutionTimeout,
WorkflowRunTimeout: runTimeout,
WorkflowTaskTimeout: taskTimeout,
Input: command.Input,
Header: command.Header,
RetryPolicy: command.RetryPolicy,
CronSchedule: command.CronSchedule,
Memo: command.Memo,
SearchAttributes: command.SearchAttributes,
}
enums.SetDefaultContinueAsNewInitiator(&command.Initiator)
req := &historyservice.StartWorkflowExecutionRequest{
NamespaceId: e.namespaceEntry.GetInfo().Id,
StartRequest: createRequest,
ParentExecutionInfo: parentExecutionInfo,
LastCompletionResult: command.LastCompletionResult,
ContinuedFailure: command.GetFailure(),
ContinueAsNewInitiator: command.Initiator,
FirstWorkflowTaskBackoff: command.BackoffStartInterval,
}
if command.GetInitiator() == enumspb.CONTINUE_AS_NEW_INITIATOR_RETRY {
req.Attempt = previousExecutionState.GetExecutionInfo().Attempt + 1
} else {
req.Attempt = 1
}
workflowTimeoutTime := timestamp.TimeValue(previousExecutionState.GetExecutionInfo().WorkflowExecutionExpirationTime)
if !workflowTimeoutTime.IsZero() {
req.WorkflowExecutionExpirationTime = &workflowTimeoutTime
}
// History event only has namespace so namespaceID has to be passed in explicitly to update the mutable state
var parentNamespaceID string
if parentExecutionInfo != nil {
parentNamespaceID = parentExecutionInfo.GetNamespaceId()
}
event := e.hBuilder.AddWorkflowExecutionStartedEvent(
*e.executionInfo.StartTime,
req,
previousExecutionInfo.AutoResetPoints,
previousExecutionState.GetExecutionState().GetRunId(),
firstRunID,
execution.GetRunId(),
)
if err := e.ReplicateWorkflowExecutionStartedEvent(
parentNamespaceID,
execution,
createRequest.GetRequestId(),
event,
); err != nil {
return nil, err
}
if err := e.SetHistoryTree(e.GetExecutionState().GetRunId()); err != nil {
return nil, err
}
// TODO merge active & passive task generation
if err := e.taskGenerator.GenerateWorkflowStartTasks(
timestamp.TimeValue(event.GetEventTime()),
event,
); err != nil {
return nil, err
}
if err := e.taskGenerator.GenerateRecordWorkflowStartedTasks(
timestamp.TimeValue(event.GetEventTime()),
event,
); err != nil {
return nil, err
}
if err := e.AddFirstWorkflowTaskScheduled(
event,
); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) AddWorkflowExecutionStartedEvent(
execution commonpb.WorkflowExecution,
startRequest *historyservice.StartWorkflowExecutionRequest,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionWorkflowStarted
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
request := startRequest.StartRequest
eventID := e.GetNextEventID()
if eventID != common.FirstEventID {
e.logger.Warn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(eventID),
tag.ErrorTypeInvalidHistoryAction)
return nil, e.createInternalServerError(opTag)
}
e.executionInfo.ExecutionTime = timestamp.TimePtr(e.executionInfo.StartTime.Add(timestamp.DurationValue(startRequest.GetFirstWorkflowTaskBackoff())))
event := e.hBuilder.AddWorkflowExecutionStartedEvent(
*e.executionInfo.StartTime,
startRequest,
nil,
"",
execution.GetRunId(),
execution.GetRunId(),
)
var parentNamespaceID string
if startRequest.ParentExecutionInfo != nil {
parentNamespaceID = startRequest.ParentExecutionInfo.GetNamespaceId()
}
if err := e.ReplicateWorkflowExecutionStartedEvent(
parentNamespaceID,
execution,
request.GetRequestId(),
event,
); err != nil {
return nil, err
}
// TODO merge active & passive task generation
if err := e.taskGenerator.GenerateWorkflowStartTasks(
timestamp.TimeValue(event.GetEventTime()),
event,
); err != nil {
return nil, err
}
if err := e.taskGenerator.GenerateRecordWorkflowStartedTasks(
timestamp.TimeValue(event.GetEventTime()),
event,
); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateWorkflowExecutionStartedEvent(
parentNamespaceID string,
execution commonpb.WorkflowExecution,
requestID string,
startEvent *historypb.HistoryEvent,
) error {
event := startEvent.GetWorkflowExecutionStartedEventAttributes()
e.executionState.CreateRequestId = requestID
e.executionState.RunId = execution.GetRunId()
e.executionInfo.NamespaceId = e.namespaceEntry.GetInfo().Id
e.executionInfo.WorkflowId = execution.GetWorkflowId()
e.executionInfo.FirstExecutionRunId = event.GetFirstExecutionRunId()
e.executionInfo.TaskQueue = event.TaskQueue.GetName()
e.executionInfo.WorkflowTypeName = event.WorkflowType.GetName()
e.executionInfo.WorkflowRunTimeout = event.GetWorkflowRunTimeout()
e.executionInfo.WorkflowExecutionTimeout = event.GetWorkflowExecutionTimeout()
e.executionInfo.DefaultWorkflowTaskTimeout = event.GetWorkflowTaskTimeout()
if err := e.UpdateWorkflowStateStatus(
enumsspb.WORKFLOW_EXECUTION_STATE_CREATED,
enumspb.WORKFLOW_EXECUTION_STATUS_RUNNING,
); err != nil {
return err
}
e.executionInfo.LastWorkflowTaskStartId = common.EmptyEventID
e.executionInfo.LastFirstEventId = startEvent.GetEventId()
e.executionInfo.WorkflowTaskVersion = common.EmptyVersion
e.executionInfo.WorkflowTaskScheduleId = common.EmptyEventID
e.executionInfo.WorkflowTaskStartedId = common.EmptyEventID
e.executionInfo.WorkflowTaskRequestId = emptyUUID
e.executionInfo.WorkflowTaskTimeout = timestamp.DurationFromSeconds(0)
e.executionInfo.CronSchedule = event.GetCronSchedule()
e.executionInfo.ParentNamespaceId = parentNamespaceID
if event.ParentWorkflowExecution != nil {
e.executionInfo.ParentWorkflowId = event.ParentWorkflowExecution.GetWorkflowId()
e.executionInfo.ParentRunId = event.ParentWorkflowExecution.GetRunId()
}
if event.ParentInitiatedEventId != 0 {
e.executionInfo.InitiatedId = event.GetParentInitiatedEventId()
} else {
e.executionInfo.InitiatedId = common.EmptyEventID
}
e.executionInfo.Attempt = event.GetAttempt()
if !timestamp.TimeValue(event.GetWorkflowExecutionExpirationTime()).IsZero() {
e.executionInfo.WorkflowExecutionExpirationTime = event.GetWorkflowExecutionExpirationTime()
}
var workflowRunTimeoutTime time.Time
workflowRunTimeoutDuration := timestamp.DurationValue(e.executionInfo.WorkflowRunTimeout)
// if workflowRunTimeoutDuration == 0 then the workflowRunTimeoutTime will be 0
// meaning that there is not workflow run timeout
if workflowRunTimeoutDuration != 0 {
firstWorkflowTaskDelayDuration := timestamp.DurationValue(event.GetFirstWorkflowTaskBackoff())
workflowRunTimeoutDuration = workflowRunTimeoutDuration + firstWorkflowTaskDelayDuration
workflowRunTimeoutTime = e.executionInfo.StartTime.Add(workflowRunTimeoutDuration)
workflowExecutionTimeoutTime := timestamp.TimeValue(e.executionInfo.WorkflowExecutionExpirationTime)
if !workflowExecutionTimeoutTime.IsZero() && workflowRunTimeoutTime.After(workflowExecutionTimeoutTime) {
workflowRunTimeoutTime = workflowExecutionTimeoutTime
}
}
e.executionInfo.WorkflowRunExpirationTime = timestamp.TimePtr(workflowRunTimeoutTime)
if event.RetryPolicy != nil {
e.executionInfo.HasRetryPolicy = true
e.executionInfo.RetryBackoffCoefficient = event.RetryPolicy.GetBackoffCoefficient()
e.executionInfo.RetryInitialInterval = event.RetryPolicy.GetInitialInterval()
e.executionInfo.RetryMaximumAttempts = event.RetryPolicy.GetMaximumAttempts()
e.executionInfo.RetryMaximumInterval = event.RetryPolicy.GetMaximumInterval()
e.executionInfo.RetryNonRetryableErrorTypes = event.RetryPolicy.GetNonRetryableErrorTypes()
}
e.executionInfo.AutoResetPoints = rolloverAutoResetPointsWithExpiringTime(
event.GetPrevAutoResetPoints(),
event.GetContinuedExecutionRunId(),
timestamp.TimeValue(startEvent.GetEventTime()),
e.namespaceEntry.GetRetention(e.executionInfo.WorkflowId),
)
if event.Memo != nil {
e.executionInfo.Memo = event.Memo.GetFields()
}
if event.SearchAttributes != nil {
e.executionInfo.SearchAttributes = event.SearchAttributes.GetIndexedFields()
}
e.writeEventToCache(startEvent)
return nil
}
func (e *MutableStateImpl) AddFirstWorkflowTaskScheduled(
startEvent *historypb.HistoryEvent,
) error {
opTag := tag.WorkflowActionWorkflowTaskScheduled
if err := e.checkMutability(opTag); err != nil {
return err
}
return e.workflowTaskManager.AddFirstWorkflowTaskScheduled(startEvent)
}
func (e *MutableStateImpl) AddWorkflowTaskScheduledEvent(
bypassTaskGeneration bool,
) (*WorkflowTaskInfo, error) {
opTag := tag.WorkflowActionWorkflowTaskScheduled
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
return e.workflowTaskManager.AddWorkflowTaskScheduledEvent(bypassTaskGeneration)
}
// AddWorkflowTaskScheduledEventAsHeartbeat is to record the first WorkflowTaskScheduledEvent during workflow task heartbeat.
func (e *MutableStateImpl) AddWorkflowTaskScheduledEventAsHeartbeat(
bypassTaskGeneration bool,
originalScheduledTimestamp *time.Time,
) (*WorkflowTaskInfo, error) {
opTag := tag.WorkflowActionWorkflowTaskScheduled
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
return e.workflowTaskManager.AddWorkflowTaskScheduledEventAsHeartbeat(bypassTaskGeneration, originalScheduledTimestamp)
}
func (e *MutableStateImpl) ReplicateTransientWorkflowTaskScheduled() (*WorkflowTaskInfo, error) {
return e.workflowTaskManager.ReplicateTransientWorkflowTaskScheduled()
}
func (e *MutableStateImpl) ReplicateWorkflowTaskScheduledEvent(
version int64,
scheduleID int64,
taskQueue *taskqueuepb.TaskQueue,
startToCloseTimeoutSeconds int32,
attempt int32,
scheduleTimestamp *time.Time,
originalScheduledTimestamp *time.Time,
) (*WorkflowTaskInfo, error) {
return e.workflowTaskManager.ReplicateWorkflowTaskScheduledEvent(version, scheduleID, taskQueue, startToCloseTimeoutSeconds, attempt, scheduleTimestamp, originalScheduledTimestamp)
}
func (e *MutableStateImpl) AddWorkflowTaskStartedEvent(
scheduleEventID int64,
requestID string,
taskQueue *taskqueuepb.TaskQueue,
identity string,
) (*historypb.HistoryEvent, *WorkflowTaskInfo, error) {
opTag := tag.WorkflowActionWorkflowTaskStarted
if err := e.checkMutability(opTag); err != nil {
return nil, nil, err
}
return e.workflowTaskManager.AddWorkflowTaskStartedEvent(scheduleEventID, requestID, taskQueue, identity)
}
func (e *MutableStateImpl) ReplicateWorkflowTaskStartedEvent(
workflowTask *WorkflowTaskInfo,
version int64,
scheduleID int64,
startedID int64,
requestID string,
timestamp time.Time,
) (*WorkflowTaskInfo, error) {
return e.workflowTaskManager.ReplicateWorkflowTaskStartedEvent(workflowTask, version, scheduleID, startedID, requestID, timestamp)
}
func (e *MutableStateImpl) CreateTransientWorkflowTaskEvents(
workflowTask *WorkflowTaskInfo,
identity string,
) (*historypb.HistoryEvent, *historypb.HistoryEvent) {
return e.workflowTaskManager.CreateTransientWorkflowTaskEvents(workflowTask, identity)
}
// add BinaryCheckSum for the first workflowTaskCompletedID for auto-reset
func (e *MutableStateImpl) addBinaryCheckSumIfNotExists(
event *historypb.HistoryEvent,
maxResetPoints int,
) error {
binChecksum := event.GetWorkflowTaskCompletedEventAttributes().GetBinaryChecksum()
if len(binChecksum) == 0 {
return nil
}
exeInfo := e.executionInfo
var currResetPoints []*workflowpb.ResetPointInfo
if exeInfo.AutoResetPoints != nil && exeInfo.AutoResetPoints.Points != nil {
currResetPoints = e.executionInfo.AutoResetPoints.Points
} else {
currResetPoints = make([]*workflowpb.ResetPointInfo, 0, 1)
}
// List of all recent binary checksums associated with the workflow.
var recentBinaryChecksums []string
for _, rp := range currResetPoints {
recentBinaryChecksums = append(recentBinaryChecksums, rp.GetBinaryChecksum())
if rp.GetBinaryChecksum() == binChecksum {
// this checksum already exists
return nil
}
}
if len(currResetPoints) == maxResetPoints {
// If exceeding the max limit, do rotation by taking the oldest one out.
currResetPoints = currResetPoints[1:]
recentBinaryChecksums = recentBinaryChecksums[1:]
}
// Adding current version of the binary checksum.
recentBinaryChecksums = append(recentBinaryChecksums, binChecksum)
resettable := true
err := e.CheckResettable()
if err != nil {
resettable = false
}
info := &workflowpb.ResetPointInfo{
BinaryChecksum: binChecksum,
RunId: e.executionState.GetRunId(),
FirstWorkflowTaskCompletedId: event.GetEventId(),
CreateTime: timestamp.TimePtr(e.timeSource.Now()),
Resettable: resettable,
}
currResetPoints = append(currResetPoints, info)
exeInfo.AutoResetPoints = &workflowpb.ResetPoints{
Points: currResetPoints,
}
checksumsPayload, err := searchattribute.EncodeValue(recentBinaryChecksums, enumspb.INDEXED_VALUE_TYPE_KEYWORD)
if err != nil {
return err
}
if exeInfo.SearchAttributes == nil {
exeInfo.SearchAttributes = make(map[string]*commonpb.Payload, 1)
}
exeInfo.SearchAttributes[searchattribute.BinaryChecksums] = checksumsPayload
if e.shard.GetConfig().AdvancedVisibilityWritingMode() != common.AdvancedVisibilityWritingModeOff {
return e.taskGenerator.GenerateWorkflowSearchAttrTasks(timestamp.TimeValue(event.GetEventTime()))
}
return nil
}
// TODO: we will release the restriction when reset API allow those pending
// CheckResettable check if workflow can be reset
func (e *MutableStateImpl) CheckResettable() error {
if len(e.GetPendingChildExecutionInfos()) > 0 {
return serviceerror.NewInvalidArgument(fmt.Sprintf("it is not allowed resetting to a point that workflow has pending child workflow."))
}
if len(e.GetPendingRequestCancelExternalInfos()) > 0 {
return serviceerror.NewInvalidArgument(fmt.Sprintf("it is not allowed resetting to a point that workflow has pending request cancel."))
}
if len(e.GetPendingSignalExternalInfos()) > 0 {
return serviceerror.NewInvalidArgument(fmt.Sprintf("it is not allowed resetting to a point that workflow has pending signals to send."))
}
return nil
}
func (e *MutableStateImpl) AddWorkflowTaskCompletedEvent(
scheduleEventID int64,
startedEventID int64,
request *workflowservice.RespondWorkflowTaskCompletedRequest,
maxResetPoints int,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionWorkflowTaskCompleted
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
return e.workflowTaskManager.AddWorkflowTaskCompletedEvent(scheduleEventID, startedEventID, request, maxResetPoints)
}
func (e *MutableStateImpl) ReplicateWorkflowTaskCompletedEvent(
event *historypb.HistoryEvent,
) error {
return e.workflowTaskManager.ReplicateWorkflowTaskCompletedEvent(event)
}
func (e *MutableStateImpl) AddWorkflowTaskTimedOutEvent(
scheduleEventID int64,
startedEventID int64,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionWorkflowTaskTimedOut
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
return e.workflowTaskManager.AddWorkflowTaskTimedOutEvent(scheduleEventID, startedEventID)
}
func (e *MutableStateImpl) ReplicateWorkflowTaskTimedOutEvent(
timeoutType enumspb.TimeoutType,
) error {
return e.workflowTaskManager.ReplicateWorkflowTaskTimedOutEvent(timeoutType)
}
func (e *MutableStateImpl) AddWorkflowTaskScheduleToStartTimeoutEvent(
scheduleEventID int64,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionWorkflowTaskTimedOut
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
return e.workflowTaskManager.AddWorkflowTaskScheduleToStartTimeoutEvent(scheduleEventID)
}
func (e *MutableStateImpl) AddWorkflowTaskFailedEvent(
scheduleEventID int64,
startedEventID int64,
cause enumspb.WorkflowTaskFailedCause,
failure *failurepb.Failure,
identity string,
binChecksum string,
baseRunID string,
newRunID string,
forkEventVersion int64,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionWorkflowTaskFailed
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
return e.workflowTaskManager.AddWorkflowTaskFailedEvent(
scheduleEventID,
startedEventID,
cause,
failure,
identity,
binChecksum,
baseRunID,
newRunID,
forkEventVersion,
)
}
func (e *MutableStateImpl) ReplicateWorkflowTaskFailedEvent() error {
return e.workflowTaskManager.ReplicateWorkflowTaskFailedEvent()
}
func (e *MutableStateImpl) AddActivityTaskScheduledEvent(
workflowTaskCompletedEventID int64,
command *commandpb.ScheduleActivityTaskCommandAttributes,
) (*historypb.HistoryEvent, *persistencespb.ActivityInfo, error) {
opTag := tag.WorkflowActionActivityTaskScheduled
if err := e.checkMutability(opTag); err != nil {
return nil, nil, err
}
_, ok := e.GetActivityByActivityID(command.GetActivityId())
if ok {
e.logger.Warn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction)
return nil, nil, e.createCallerError(opTag)
}
event := e.hBuilder.AddActivityTaskScheduledEvent(workflowTaskCompletedEventID, command)
// Write the event to cache only on active cluster for processing on activity started or retried
e.eventsCache.PutEvent(
e.executionInfo.NamespaceId,
e.executionInfo.WorkflowId,
e.executionState.RunId,
event.GetEventId(),
event,
)
ai, err := e.ReplicateActivityTaskScheduledEvent(workflowTaskCompletedEventID, event)
// TODO merge active & passive task generation
if err := e.taskGenerator.GenerateActivityTransferTasks(
timestamp.TimeValue(event.GetEventTime()),
event,
); err != nil {
return nil, nil, err
}
return event, ai, err
}
func (e *MutableStateImpl) ReplicateActivityTaskScheduledEvent(
firstEventID int64,
event *historypb.HistoryEvent,
) (*persistencespb.ActivityInfo, error) {
attributes := event.GetActivityTaskScheduledEventAttributes()
targetNamespaceID := e.executionInfo.NamespaceId
if attributes.GetNamespace() != "" {
targetNamespaceEntry, err := e.shard.GetNamespaceCache().GetNamespace(attributes.GetNamespace())
if err != nil {
return nil, err
}
targetNamespaceID = targetNamespaceEntry.GetInfo().Id
}
scheduleEventID := event.GetEventId()
scheduleToCloseTimeout := attributes.GetScheduleToCloseTimeout()
ai := &persistencespb.ActivityInfo{
Version: event.GetVersion(),
ScheduleId: scheduleEventID,
ScheduledEventBatchId: firstEventID,
ScheduledTime: event.GetEventTime(),
StartedId: common.EmptyEventID,
StartedTime: timestamp.TimePtr(time.Time{}),
ActivityId: attributes.ActivityId,
NamespaceId: targetNamespaceID,
ScheduleToStartTimeout: attributes.GetScheduleToStartTimeout(),
ScheduleToCloseTimeout: scheduleToCloseTimeout,
StartToCloseTimeout: attributes.GetStartToCloseTimeout(),
HeartbeatTimeout: attributes.GetHeartbeatTimeout(),
CancelRequested: false,
CancelRequestId: common.EmptyEventID,
LastHeartbeatUpdateTime: timestamp.TimePtr(time.Time{}),
TimerTaskStatus: TimerTaskStatusNone,
TaskQueue: attributes.TaskQueue.GetName(),
HasRetryPolicy: attributes.RetryPolicy != nil,
Attempt: 1,
}
if ai.HasRetryPolicy {
ai.RetryInitialInterval = attributes.RetryPolicy.GetInitialInterval()
ai.RetryBackoffCoefficient = attributes.RetryPolicy.GetBackoffCoefficient()
ai.RetryMaximumInterval = attributes.RetryPolicy.GetMaximumInterval()
ai.RetryMaximumAttempts = attributes.RetryPolicy.GetMaximumAttempts()
ai.RetryNonRetryableErrorTypes = attributes.RetryPolicy.NonRetryableErrorTypes
if timestamp.DurationValue(scheduleToCloseTimeout) > 0 {
ai.RetryExpirationTime = timestamp.TimePtr(
timestamp.TimeValue(ai.ScheduledTime).Add(timestamp.DurationValue(scheduleToCloseTimeout)),
)
} else {
ai.RetryExpirationTime = timestamp.TimePtr(time.Time{})
}
}
e.pendingActivityInfoIDs[ai.ScheduleId] = ai
e.pendingActivityIDToEventID[ai.ActivityId] = ai.ScheduleId
e.updateActivityInfos[ai.ScheduleId] = ai
return ai, nil
}
func (e *MutableStateImpl) addTransientActivityStartedEvent(
scheduleEventID int64,
) error {
ai, ok := e.GetActivityInfo(scheduleEventID)
if !ok || ai.StartedId != common.TransientEventID {
return nil
}
// activity task was started (as transient event), we need to add it now.
event := e.hBuilder.AddActivityTaskStartedEvent(
scheduleEventID,
ai.Attempt,
ai.RequestId,
ai.StartedIdentity,
ai.RetryLastFailure,
)
if !ai.StartedTime.IsZero() {
// overwrite started event time to the one recorded in ActivityInfo
event.EventTime = ai.StartedTime
}
return e.ReplicateActivityTaskStartedEvent(event)
}
func (e *MutableStateImpl) AddActivityTaskStartedEvent(
ai *persistencespb.ActivityInfo,
scheduleEventID int64,
requestID string,
identity string,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionActivityTaskStarted
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
if !ai.HasRetryPolicy {
event := e.hBuilder.AddActivityTaskStartedEvent(
scheduleEventID,
ai.Attempt,
requestID,
identity,
ai.RetryLastFailure,
)
if err := e.ReplicateActivityTaskStartedEvent(event); err != nil {
return nil, err
}
return event, nil
}
// we might need to retry, so do not append started event just yet,
// instead update mutable state and will record started event when activity task is closed
ai.Version = e.GetCurrentVersion()
ai.StartedId = common.TransientEventID
ai.RequestId = requestID
ai.StartedTime = timestamp.TimePtr(e.timeSource.Now())
ai.LastHeartbeatUpdateTime = ai.StartedTime
ai.StartedIdentity = identity
if err := e.UpdateActivity(ai); err != nil {
return nil, err
}
e.syncActivityTasks[ai.ScheduleId] = struct{}{}
return nil, nil
}
func (e *MutableStateImpl) ReplicateActivityTaskStartedEvent(
event *historypb.HistoryEvent,
) error {
attributes := event.GetActivityTaskStartedEventAttributes()
scheduleID := attributes.GetScheduledEventId()
ai, ok := e.GetActivityInfo(scheduleID)
if !ok {
e.logError(
fmt.Sprintf("unable to find activity event id: %v in mutable state", scheduleID),
tag.ErrorTypeInvalidMutableStateAction,
)
return ErrMissingActivityInfo
}
ai.Version = event.GetVersion()
ai.StartedId = event.GetEventId()
ai.RequestId = attributes.GetRequestId()
ai.StartedTime = event.GetEventTime()
ai.LastHeartbeatUpdateTime = ai.StartedTime
e.updateActivityInfos[ai.ScheduleId] = ai
return nil
}
func (e *MutableStateImpl) AddActivityTaskCompletedEvent(
scheduleEventID int64,
startedEventID int64,
request *workflowservice.RespondActivityTaskCompletedRequest,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionActivityTaskCompleted
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
if ai, ok := e.GetActivityInfo(scheduleEventID); !ok || ai.StartedId != startedEventID {
e.logger.Warn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.Bool(ok),
tag.WorkflowScheduleID(scheduleEventID),
tag.WorkflowStartedID(startedEventID))
return nil, e.createInternalServerError(opTag)
}
if err := e.addTransientActivityStartedEvent(scheduleEventID); err != nil {
return nil, err
}
event := e.hBuilder.AddActivityTaskCompletedEvent(
scheduleEventID,
startedEventID,
request.Identity,
request.Result,
)
if err := e.ReplicateActivityTaskCompletedEvent(event); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateActivityTaskCompletedEvent(
event *historypb.HistoryEvent,
) error {
attributes := event.GetActivityTaskCompletedEventAttributes()
scheduleID := attributes.GetScheduledEventId()
return e.DeleteActivity(scheduleID)
}
func (e *MutableStateImpl) AddActivityTaskFailedEvent(
scheduleEventID int64,
startedEventID int64,
failure *failurepb.Failure,
retryState enumspb.RetryState,
identity string,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionActivityTaskFailed
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
if ai, ok := e.GetActivityInfo(scheduleEventID); !ok || ai.StartedId != startedEventID {
e.logger.Warn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.Bool(ok),
tag.WorkflowScheduleID(scheduleEventID),
tag.WorkflowStartedID(startedEventID))
return nil, e.createInternalServerError(opTag)
}
if err := e.addTransientActivityStartedEvent(scheduleEventID); err != nil {
return nil, err
}
event := e.hBuilder.AddActivityTaskFailedEvent(
scheduleEventID,
startedEventID,
failure,
retryState,
identity,
)
if err := e.ReplicateActivityTaskFailedEvent(event); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateActivityTaskFailedEvent(
event *historypb.HistoryEvent,
) error {
attributes := event.GetActivityTaskFailedEventAttributes()
scheduleID := attributes.GetScheduledEventId()
return e.DeleteActivity(scheduleID)
}
func (e *MutableStateImpl) AddActivityTaskTimedOutEvent(
scheduleEventID int64,
startedEventID int64,
timeoutFailure *failurepb.Failure,
retryState enumspb.RetryState,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionActivityTaskTimedOut
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
timeoutType := timeoutFailure.GetTimeoutFailureInfo().GetTimeoutType()
ai, ok := e.GetActivityInfo(scheduleEventID)
if !ok || ai.StartedId != startedEventID || ((timeoutType == enumspb.TIMEOUT_TYPE_START_TO_CLOSE ||
timeoutType == enumspb.TIMEOUT_TYPE_HEARTBEAT) && ai.StartedId == common.EmptyEventID) {
e.logger.Warn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.Bool(ok),
tag.WorkflowScheduleID(ai.ScheduleId),
tag.WorkflowStartedID(ai.StartedId),
tag.WorkflowTimeoutType(timeoutType))
return nil, e.createInternalServerError(opTag)
}
timeoutFailure.Cause = ai.RetryLastFailure
if err := e.addTransientActivityStartedEvent(scheduleEventID); err != nil {
return nil, err
}
event := e.hBuilder.AddActivityTaskTimedOutEvent(
scheduleEventID,
startedEventID,
timeoutFailure,
retryState,
)
if err := e.ReplicateActivityTaskTimedOutEvent(event); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateActivityTaskTimedOutEvent(
event *historypb.HistoryEvent,
) error {
attributes := event.GetActivityTaskTimedOutEventAttributes()
scheduleID := attributes.GetScheduledEventId()
return e.DeleteActivity(scheduleID)
}
func (e *MutableStateImpl) AddActivityTaskCancelRequestedEvent(
workflowTaskCompletedEventID int64,
scheduleID int64,
_ string,
) (*historypb.HistoryEvent, *persistencespb.ActivityInfo, error) {
opTag := tag.WorkflowActionActivityTaskCancelRequested
if err := e.checkMutability(opTag); err != nil {
return nil, nil, err
}
ai, ok := e.GetActivityInfo(scheduleID)
if !ok {
// It is possible both started and completed events are buffered for this activity
if !e.hBuilder.HasActivityFinishEvent(scheduleID) {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.Bool(ok),
tag.WorkflowScheduleID(scheduleID))
return nil, nil, e.createCallerError(opTag)
}
}
// Check for duplicate cancellation
if ok && ai.CancelRequested {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.Bool(ok),
tag.WorkflowScheduleID(scheduleID))
return nil, nil, e.createCallerError(opTag)
}
// At this point we know this is a valid activity cancellation request
actCancelReqEvent := e.hBuilder.AddActivityTaskCancelRequestedEvent(workflowTaskCompletedEventID, scheduleID)
if err := e.ReplicateActivityTaskCancelRequestedEvent(actCancelReqEvent); err != nil {
return nil, nil, err
}
return actCancelReqEvent, ai, nil
}
func (e *MutableStateImpl) ReplicateActivityTaskCancelRequestedEvent(
event *historypb.HistoryEvent,
) error {
attributes := event.GetActivityTaskCancelRequestedEventAttributes()
scheduleID := attributes.GetScheduledEventId()
ai, ok := e.GetActivityInfo(scheduleID)
if !ok {
// This will only be called on active cluster if activity info is found in mutable state
// Passive side logic should always have activity info in mutable state if this is called, as the only
// scenario where active side logic could have this event without activity info in mutable state is when
// activity start and complete events are buffered.
return nil
}
ai.Version = event.GetVersion()
// - We have the activity dispatched to worker.
// - The activity might not be heartbeat'ing, but the activity can still call RecordActivityHeartBeat()
// to see cancellation while reporting progress of the activity.
ai.CancelRequested = true
ai.CancelRequestId = event.GetEventId()
e.updateActivityInfos[ai.ScheduleId] = ai
return nil
}
func (e *MutableStateImpl) AddActivityTaskCanceledEvent(
scheduleEventID int64,
startedEventID int64,
latestCancelRequestedEventID int64,
details *commonpb.Payloads,
identity string,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionActivityTaskCanceled
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
ai, ok := e.GetActivityInfo(scheduleEventID)
if !ok || ai.StartedId != startedEventID {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.WorkflowScheduleID(scheduleEventID))
return nil, e.createInternalServerError(opTag)
}
// Verify cancel request as well.
if !ai.CancelRequested {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.WorkflowScheduleID(scheduleEventID),
tag.WorkflowActivityID(ai.ActivityId),
tag.WorkflowStartedID(ai.StartedId))
return nil, e.createInternalServerError(opTag)
}
if err := e.addTransientActivityStartedEvent(scheduleEventID); err != nil {
return nil, err
}
event := e.hBuilder.AddActivityTaskCanceledEvent(
scheduleEventID,
startedEventID,
latestCancelRequestedEventID,
details,
identity,
)
if err := e.ReplicateActivityTaskCanceledEvent(event); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateActivityTaskCanceledEvent(
event *historypb.HistoryEvent,
) error {
attributes := event.GetActivityTaskCanceledEventAttributes()
scheduleID := attributes.GetScheduledEventId()
return e.DeleteActivity(scheduleID)
}
func (e *MutableStateImpl) AddCompletedWorkflowEvent(
workflowTaskCompletedEventID int64,
command *commandpb.CompleteWorkflowExecutionCommandAttributes,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionWorkflowCompleted
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
event := e.hBuilder.AddCompletedWorkflowEvent(workflowTaskCompletedEventID, command)
if err := e.ReplicateWorkflowExecutionCompletedEvent(workflowTaskCompletedEventID, event); err != nil {
return nil, err
}
// TODO merge active & passive task generation
if err := e.taskGenerator.GenerateWorkflowCloseTasks(
timestamp.TimeValue(event.GetEventTime()),
); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateWorkflowExecutionCompletedEvent(
firstEventID int64,
event *historypb.HistoryEvent,
) error {
if err := e.UpdateWorkflowStateStatus(
enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED,
enumspb.WORKFLOW_EXECUTION_STATUS_COMPLETED,
); err != nil {
return err
}
e.executionInfo.CompletionEventBatchId = firstEventID // Used when completion event needs to be loaded from database
e.ClearStickyness()
e.writeEventToCache(event)
return nil
}
func (e *MutableStateImpl) AddFailWorkflowEvent(
workflowTaskCompletedEventID int64,
retryState enumspb.RetryState,
command *commandpb.FailWorkflowExecutionCommandAttributes,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionWorkflowFailed
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
event := e.hBuilder.AddFailWorkflowEvent(workflowTaskCompletedEventID, retryState, command)
if err := e.ReplicateWorkflowExecutionFailedEvent(workflowTaskCompletedEventID, event); err != nil {
return nil, err
}
// TODO merge active & passive task generation
if err := e.taskGenerator.GenerateWorkflowCloseTasks(
timestamp.TimeValue(event.GetEventTime()),
); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateWorkflowExecutionFailedEvent(
firstEventID int64,
event *historypb.HistoryEvent,
) error {
if err := e.UpdateWorkflowStateStatus(
enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED,
enumspb.WORKFLOW_EXECUTION_STATUS_FAILED,
); err != nil {
return err
}
e.executionInfo.CompletionEventBatchId = firstEventID // Used when completion event needs to be loaded from database
e.ClearStickyness()
e.writeEventToCache(event)
return nil
}
func (e *MutableStateImpl) AddTimeoutWorkflowEvent(
firstEventID int64,
retryState enumspb.RetryState,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionWorkflowTimeout
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
event := e.hBuilder.AddTimeoutWorkflowEvent(retryState)
if err := e.ReplicateWorkflowExecutionTimedoutEvent(firstEventID, event); err != nil {
return nil, err
}
// TODO merge active & passive task generation
if err := e.taskGenerator.GenerateWorkflowCloseTasks(
timestamp.TimeValue(event.GetEventTime()),
); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateWorkflowExecutionTimedoutEvent(
firstEventID int64,
event *historypb.HistoryEvent,
) error {
if err := e.UpdateWorkflowStateStatus(
enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED,
enumspb.WORKFLOW_EXECUTION_STATUS_TIMED_OUT,
); err != nil {
return err
}
e.executionInfo.CompletionEventBatchId = firstEventID // Used when completion event needs to be loaded from database
e.ClearStickyness()
e.writeEventToCache(event)
return nil
}
func (e *MutableStateImpl) AddWorkflowExecutionCancelRequestedEvent(
request *historyservice.RequestCancelWorkflowExecutionRequest,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionWorkflowCancelRequested
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
if e.executionInfo.CancelRequested {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.WorkflowState(e.executionState.State),
tag.Bool(e.executionInfo.CancelRequested),
tag.Key(e.executionInfo.CancelRequestId),
)
return nil, e.createInternalServerError(opTag)
}
event := e.hBuilder.AddWorkflowExecutionCancelRequestedEvent(request)
if err := e.ReplicateWorkflowExecutionCancelRequestedEvent(event); err != nil {
return nil, err
}
// Set the CancelRequestID on the active cluster. This information is not part of the history event.
e.executionInfo.CancelRequestId = request.CancelRequest.GetRequestId()
return event, nil
}
func (e *MutableStateImpl) ReplicateWorkflowExecutionCancelRequestedEvent(
_ *historypb.HistoryEvent,
) error {
e.executionInfo.CancelRequested = true
return nil
}
func (e *MutableStateImpl) AddWorkflowExecutionCanceledEvent(
workflowTaskCompletedEventID int64,
command *commandpb.CancelWorkflowExecutionCommandAttributes,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionWorkflowCanceled
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
event := e.hBuilder.AddWorkflowExecutionCanceledEvent(workflowTaskCompletedEventID, command)
if err := e.ReplicateWorkflowExecutionCanceledEvent(workflowTaskCompletedEventID, event); err != nil {
return nil, err
}
// TODO merge active & passive task generation
if err := e.taskGenerator.GenerateWorkflowCloseTasks(
timestamp.TimeValue(event.GetEventTime()),
); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateWorkflowExecutionCanceledEvent(
firstEventID int64,
event *historypb.HistoryEvent,
) error {
if err := e.UpdateWorkflowStateStatus(
enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED,
enumspb.WORKFLOW_EXECUTION_STATUS_CANCELED,
); err != nil {
return err
}
e.executionInfo.CompletionEventBatchId = firstEventID // Used when completion event needs to be loaded from database
e.ClearStickyness()
e.writeEventToCache(event)
return nil
}
func (e *MutableStateImpl) AddRequestCancelExternalWorkflowExecutionInitiatedEvent(
workflowTaskCompletedEventID int64,
cancelRequestID string,
command *commandpb.RequestCancelExternalWorkflowExecutionCommandAttributes,
) (*historypb.HistoryEvent, *persistencespb.RequestCancelInfo, error) {
opTag := tag.WorkflowActionExternalWorkflowCancelInitiated
if err := e.checkMutability(opTag); err != nil {
return nil, nil, err
}
event := e.hBuilder.AddRequestCancelExternalWorkflowExecutionInitiatedEvent(workflowTaskCompletedEventID, command)
rci, err := e.ReplicateRequestCancelExternalWorkflowExecutionInitiatedEvent(workflowTaskCompletedEventID, event, cancelRequestID)
if err != nil {
return nil, nil, err
}
// TODO merge active & passive task generation
if err := e.taskGenerator.GenerateRequestCancelExternalTasks(
timestamp.TimeValue(event.GetEventTime()),
event,
); err != nil {
return nil, nil, err
}
return event, rci, nil
}
func (e *MutableStateImpl) ReplicateRequestCancelExternalWorkflowExecutionInitiatedEvent(
firstEventID int64,
event *historypb.HistoryEvent,
cancelRequestID string,
) (*persistencespb.RequestCancelInfo, error) {
// TODO: Evaluate if we need cancelRequestID also part of history event
initiatedEventID := event.GetEventId()
rci := &persistencespb.RequestCancelInfo{
Version: event.GetVersion(),
InitiatedEventBatchId: firstEventID,
InitiatedId: initiatedEventID,
CancelRequestId: cancelRequestID,
}
e.pendingRequestCancelInfoIDs[rci.InitiatedId] = rci
e.updateRequestCancelInfos[rci.InitiatedId] = rci
return rci, nil
}
func (e *MutableStateImpl) AddExternalWorkflowExecutionCancelRequested(
initiatedID int64,
namespace string,
workflowID string,
runID string,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionExternalWorkflowCancelRequested
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
_, ok := e.GetRequestCancelInfo(initiatedID)
if !ok {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.WorkflowInitiatedID(initiatedID))
return nil, e.createInternalServerError(opTag)
}
event := e.hBuilder.AddExternalWorkflowExecutionCancelRequested(
initiatedID,
namespace,
workflowID,
runID,
)
if err := e.ReplicateExternalWorkflowExecutionCancelRequested(event); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateExternalWorkflowExecutionCancelRequested(
event *historypb.HistoryEvent,
) error {
initiatedID := event.GetExternalWorkflowExecutionCancelRequestedEventAttributes().GetInitiatedEventId()
return e.DeletePendingRequestCancel(initiatedID)
}
func (e *MutableStateImpl) AddRequestCancelExternalWorkflowExecutionFailedEvent(
initiatedID int64,
namespace string,
workflowID string,
runID string,
cause enumspb.CancelExternalWorkflowExecutionFailedCause,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionExternalWorkflowCancelFailed
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
_, ok := e.GetRequestCancelInfo(initiatedID)
if !ok {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.WorkflowInitiatedID(initiatedID))
return nil, e.createInternalServerError(opTag)
}
event := e.hBuilder.AddRequestCancelExternalWorkflowExecutionFailedEvent(
common.EmptyEventID, // TODO this field is not used at all
initiatedID,
namespace,
workflowID,
runID,
cause,
)
if err := e.ReplicateRequestCancelExternalWorkflowExecutionFailedEvent(event); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateRequestCancelExternalWorkflowExecutionFailedEvent(
event *historypb.HistoryEvent,
) error {
initiatedID := event.GetRequestCancelExternalWorkflowExecutionFailedEventAttributes().GetInitiatedEventId()
return e.DeletePendingRequestCancel(initiatedID)
}
func (e *MutableStateImpl) AddSignalExternalWorkflowExecutionInitiatedEvent(
workflowTaskCompletedEventID int64,
signalRequestID string,
command *commandpb.SignalExternalWorkflowExecutionCommandAttributes,
) (*historypb.HistoryEvent, *persistencespb.SignalInfo, error) {
opTag := tag.WorkflowActionExternalWorkflowSignalInitiated
if err := e.checkMutability(opTag); err != nil {
return nil, nil, err
}
event := e.hBuilder.AddSignalExternalWorkflowExecutionInitiatedEvent(workflowTaskCompletedEventID, command)
si, err := e.ReplicateSignalExternalWorkflowExecutionInitiatedEvent(workflowTaskCompletedEventID, event, signalRequestID)
if err != nil {
return nil, nil, err
}
// TODO merge active & passive task generation
if err := e.taskGenerator.GenerateSignalExternalTasks(
timestamp.TimeValue(event.GetEventTime()),
event,
); err != nil {
return nil, nil, err
}
return event, si, nil
}
func (e *MutableStateImpl) ReplicateSignalExternalWorkflowExecutionInitiatedEvent(
firstEventID int64,
event *historypb.HistoryEvent,
signalRequestID string,
) (*persistencespb.SignalInfo, error) {
// TODO: Consider also writing signalRequestID to history event
initiatedEventID := event.GetEventId()
attributes := event.GetSignalExternalWorkflowExecutionInitiatedEventAttributes()
si := &persistencespb.SignalInfo{
Version: event.GetVersion(),
InitiatedEventBatchId: firstEventID,
InitiatedId: initiatedEventID,
RequestId: signalRequestID,
Name: attributes.GetSignalName(),
Input: attributes.Input,
Control: attributes.Control,
}
e.pendingSignalInfoIDs[si.InitiatedId] = si
e.updateSignalInfos[si.InitiatedId] = si
return si, nil
}
func (e *MutableStateImpl) AddUpsertWorkflowSearchAttributesEvent(
workflowTaskCompletedEventID int64,
command *commandpb.UpsertWorkflowSearchAttributesCommandAttributes,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionUpsertWorkflowSearchAttributes
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
event := e.hBuilder.AddUpsertWorkflowSearchAttributesEvent(workflowTaskCompletedEventID, command)
e.ReplicateUpsertWorkflowSearchAttributesEvent(event)
// TODO merge active & passive task generation
if err := e.taskGenerator.GenerateWorkflowSearchAttrTasks(
timestamp.TimeValue(event.GetEventTime()),
); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateUpsertWorkflowSearchAttributesEvent(
event *historypb.HistoryEvent,
) {
upsertSearchAttr := event.GetUpsertWorkflowSearchAttributesEventAttributes().GetSearchAttributes().GetIndexedFields()
currentSearchAttr := e.GetExecutionInfo().SearchAttributes
e.executionInfo.SearchAttributes = mergeMapOfPayload(currentSearchAttr, upsertSearchAttr)
}
func mergeMapOfPayload(
current map[string]*commonpb.Payload,
upsert map[string]*commonpb.Payload,
) map[string]*commonpb.Payload {
if current == nil {
current = make(map[string]*commonpb.Payload)
}
for k, v := range upsert {
current[k] = v
}
return current
}
func (e *MutableStateImpl) AddExternalWorkflowExecutionSignaled(
initiatedID int64,
namespace string,
workflowID string,
runID string,
control string, // TODO this field is probably deprecated
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionExternalWorkflowSignalRequested
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
_, ok := e.GetSignalInfo(initiatedID)
if !ok {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.WorkflowInitiatedID(initiatedID))
return nil, e.createInternalServerError(opTag)
}
event := e.hBuilder.AddExternalWorkflowExecutionSignaled(
initiatedID,
namespace,
workflowID,
runID,
control, // TODO this field is probably deprecated
)
if err := e.ReplicateExternalWorkflowExecutionSignaled(event); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateExternalWorkflowExecutionSignaled(
event *historypb.HistoryEvent,
) error {
initiatedID := event.GetExternalWorkflowExecutionSignaledEventAttributes().GetInitiatedEventId()
return e.DeletePendingSignal(initiatedID)
}
func (e *MutableStateImpl) AddSignalExternalWorkflowExecutionFailedEvent(
initiatedID int64,
namespace string,
workflowID string,
runID string,
control string, // TODO this field is probably deprecated
cause enumspb.SignalExternalWorkflowExecutionFailedCause,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionExternalWorkflowSignalFailed
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
_, ok := e.GetSignalInfo(initiatedID)
if !ok {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.WorkflowInitiatedID(initiatedID))
return nil, e.createInternalServerError(opTag)
}
event := e.hBuilder.AddSignalExternalWorkflowExecutionFailedEvent(
common.EmptyEventID, // TODO this field is not used at all
initiatedID,
namespace,
workflowID,
runID,
control, // TODO this field is probably deprecated
cause,
)
if err := e.ReplicateSignalExternalWorkflowExecutionFailedEvent(event); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateSignalExternalWorkflowExecutionFailedEvent(
event *historypb.HistoryEvent,
) error {
initiatedID := event.GetSignalExternalWorkflowExecutionFailedEventAttributes().GetInitiatedEventId()
return e.DeletePendingSignal(initiatedID)
}
func (e *MutableStateImpl) AddTimerStartedEvent(
workflowTaskCompletedEventID int64,
command *commandpb.StartTimerCommandAttributes,
) (*historypb.HistoryEvent, *persistencespb.TimerInfo, error) {
opTag := tag.WorkflowActionTimerStarted
if err := e.checkMutability(opTag); err != nil {
return nil, nil, err
}
timerID := command.GetTimerId()
_, ok := e.GetUserTimerInfo(timerID)
if ok {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.WorkflowTimerID(timerID))
return nil, nil, e.createCallerError(opTag)
}
event := e.hBuilder.AddTimerStartedEvent(workflowTaskCompletedEventID, command)
ti, err := e.ReplicateTimerStartedEvent(event)
if err != nil {
return nil, nil, err
}
return event, ti, err
}
func (e *MutableStateImpl) ReplicateTimerStartedEvent(
event *historypb.HistoryEvent,
) (*persistencespb.TimerInfo, error) {
attributes := event.GetTimerStartedEventAttributes()
timerID := attributes.GetTimerId()
startToFireTimeout := timestamp.DurationValue(attributes.GetStartToFireTimeout())
// TODO: Time skew need to be taken in to account.
expiryTime := timestamp.TimeValue(event.GetEventTime()).Add(startToFireTimeout) // should use the event time, not now
ti := &persistencespb.TimerInfo{
Version: event.GetVersion(),
TimerId: timerID,
ExpiryTime: &expiryTime,
StartedId: event.GetEventId(),
TaskStatus: TimerTaskStatusNone,
}
e.pendingTimerInfoIDs[ti.TimerId] = ti
e.pendingTimerEventIDToID[ti.StartedId] = ti.TimerId
e.updateTimerInfos[ti.TimerId] = ti
return ti, nil
}
func (e *MutableStateImpl) AddTimerFiredEvent(
timerID string,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionTimerFired
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
timerInfo, ok := e.GetUserTimerInfo(timerID)
if !ok {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.WorkflowTimerID(timerID))
return nil, e.createInternalServerError(opTag)
}
// Timer is running.
event := e.hBuilder.AddTimerFiredEvent(timerInfo.GetStartedId(), timerInfo.TimerId)
if err := e.ReplicateTimerFiredEvent(event); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateTimerFiredEvent(
event *historypb.HistoryEvent,
) error {
attributes := event.GetTimerFiredEventAttributes()
timerID := attributes.GetTimerId()
return e.DeleteUserTimer(timerID)
}
func (e *MutableStateImpl) AddTimerCanceledEvent(
workflowTaskCompletedEventID int64,
command *commandpb.CancelTimerCommandAttributes,
identity string,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionTimerCanceled
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
var timerStartedID int64
timerID := command.GetTimerId()
ti, ok := e.GetUserTimerInfo(timerID)
if !ok {
// if timer is not running then check if it has fired in the mutable state.
// If so clear the timer from the mutable state. We need to check both the
// bufferedEvents and the history builder
timerFiredEvent := e.hBuilder.GetAndRemoveTimerFireEvent(timerID)
if timerFiredEvent == nil {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.WorkflowTimerID(timerID))
return nil, e.createCallerError(opTag)
}
timerStartedID = timerFiredEvent.GetTimerFiredEventAttributes().GetStartedEventId()
} else {
timerStartedID = ti.GetStartedId()
}
// Timer is running.
event := e.hBuilder.AddTimerCanceledEvent(
workflowTaskCompletedEventID,
timerStartedID,
timerID,
identity,
)
if ok {
if err := e.ReplicateTimerCanceledEvent(event); err != nil {
return nil, err
}
}
return event, nil
}
func (e *MutableStateImpl) ReplicateTimerCanceledEvent(
event *historypb.HistoryEvent,
) error {
attributes := event.GetTimerCanceledEventAttributes()
timerID := attributes.GetTimerId()
return e.DeleteUserTimer(timerID)
}
func (e *MutableStateImpl) AddRecordMarkerEvent(
workflowTaskCompletedEventID int64,
command *commandpb.RecordMarkerCommandAttributes,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionWorkflowRecordMarker
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
return e.hBuilder.AddMarkerRecordedEvent(workflowTaskCompletedEventID, command), nil
}
func (e *MutableStateImpl) AddWorkflowExecutionTerminatedEvent(
firstEventID int64,
reason string,
details *commonpb.Payloads,
identity string,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionWorkflowTerminated
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
event := e.hBuilder.AddWorkflowExecutionTerminatedEvent(reason, details, identity)
if err := e.ReplicateWorkflowExecutionTerminatedEvent(firstEventID, event); err != nil {
return nil, err
}
// TODO merge active & passive task generation
if err := e.taskGenerator.GenerateWorkflowCloseTasks(
timestamp.TimeValue(event.GetEventTime()),
); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateWorkflowExecutionTerminatedEvent(
firstEventID int64,
event *historypb.HistoryEvent,
) error {
if err := e.UpdateWorkflowStateStatus(
enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED,
enumspb.WORKFLOW_EXECUTION_STATUS_TERMINATED,
); err != nil {
return err
}
e.executionInfo.CompletionEventBatchId = firstEventID // Used when completion event needs to be loaded from database
e.ClearStickyness()
e.writeEventToCache(event)
return nil
}
func (e *MutableStateImpl) AddWorkflowExecutionSignaled(
signalName string,
input *commonpb.Payloads,
identity string,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionWorkflowSignaled
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
event := e.hBuilder.AddWorkflowExecutionSignaledEvent(signalName, input, identity)
if err := e.ReplicateWorkflowExecutionSignaled(event); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateWorkflowExecutionSignaled(
_ *historypb.HistoryEvent,
) error {
// Increment signal count in mutable state for this workflow execution
e.executionInfo.SignalCount++
return nil
}
func (e *MutableStateImpl) AddContinueAsNewEvent(
firstEventID int64,
workflowTaskCompletedEventID int64,
parentNamespace string,
command *commandpb.ContinueAsNewWorkflowExecutionCommandAttributes,
) (*historypb.HistoryEvent, MutableState, error) {
opTag := tag.WorkflowActionWorkflowContinueAsNew
if err := e.checkMutability(opTag); err != nil {
return nil, nil, err
}
var err error
newRunID := uuid.New()
newExecution := commonpb.WorkflowExecution{
WorkflowId: e.executionInfo.WorkflowId,
RunId: newRunID,
}
// Extract ParentExecutionInfo from current run so it can be passed down to the next
var parentInfo *workflowspb.ParentExecutionInfo
if e.HasParentExecution() {
parentInfo = &workflowspb.ParentExecutionInfo{
NamespaceId: e.executionInfo.ParentNamespaceId,
Namespace: parentNamespace,
Execution: &commonpb.WorkflowExecution{
WorkflowId: e.executionInfo.ParentWorkflowId,
RunId: e.executionInfo.ParentRunId,
},
InitiatedId: e.executionInfo.InitiatedId,
}
}
continueAsNewEvent := e.hBuilder.AddContinuedAsNewEvent(
workflowTaskCompletedEventID,
newRunID,
command,
)
firstRunID := e.executionInfo.FirstExecutionRunId
// This is needed for backwards compatibility. Workflow execution create with Temporal release v0.28.0 or earlier
// does not have FirstExecutionRunID stored as part of mutable state. If this is not set then load it from
// workflow execution started event.
if len(firstRunID) == 0 {
currentStartEvent, err := e.GetStartEvent()
if err != nil {
return nil, nil, err
}
firstRunID = currentStartEvent.GetWorkflowExecutionStartedEventAttributes().GetFirstExecutionRunId()
}
namespaceID := e.namespaceEntry.GetInfo().Id
var newStateBuilder *MutableStateImpl
newStateBuilder = NewMutableState(
e.shard,
e.shard.GetEventsCache(),
e.logger,
e.namespaceEntry,
timestamp.TimeValue(continueAsNewEvent.GetEventTime()),
)
if _, err = newStateBuilder.addWorkflowExecutionStartedEventForContinueAsNew(
parentInfo,
newExecution,
e,
command,
firstRunID,
); err != nil {
return nil, nil, serviceerror.NewInternal("Failed to add workflow execution started event.")
}
if err = e.ReplicateWorkflowExecutionContinuedAsNewEvent(
firstEventID,
namespaceID,
continueAsNewEvent,
); err != nil {
return nil, nil, err
}
// TODO merge active & passive task generation
if err := e.taskGenerator.GenerateWorkflowCloseTasks(
timestamp.TimeValue(continueAsNewEvent.GetEventTime()),
); err != nil {
return nil, nil, err
}
return continueAsNewEvent, newStateBuilder, nil
}
func rolloverAutoResetPointsWithExpiringTime(
resetPoints *workflowpb.ResetPoints,
prevRunID string,
now time.Time,
namespaceRetention time.Duration,
) *workflowpb.ResetPoints {
if resetPoints == nil || resetPoints.Points == nil {
return resetPoints
}
newPoints := make([]*workflowpb.ResetPointInfo, 0, len(resetPoints.Points))
expireTime := now.Add(namespaceRetention)
for _, rp := range resetPoints.Points {
if rp.GetRunId() == prevRunID {
rp.ExpireTime = &expireTime
}
newPoints = append(newPoints, rp)
}
return &workflowpb.ResetPoints{
Points: newPoints,
}
}
func (e *MutableStateImpl) ReplicateWorkflowExecutionContinuedAsNewEvent(
firstEventID int64,
_ string,
continueAsNewEvent *historypb.HistoryEvent,
) error {
if err := e.UpdateWorkflowStateStatus(
enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED,
enumspb.WORKFLOW_EXECUTION_STATUS_CONTINUED_AS_NEW,
); err != nil {
return err
}
e.executionInfo.CompletionEventBatchId = firstEventID // Used when completion event needs to be loaded from database
e.ClearStickyness()
e.writeEventToCache(continueAsNewEvent)
return nil
}
func (e *MutableStateImpl) AddStartChildWorkflowExecutionInitiatedEvent(
workflowTaskCompletedEventID int64,
createRequestID string,
command *commandpb.StartChildWorkflowExecutionCommandAttributes,
) (*historypb.HistoryEvent, *persistencespb.ChildExecutionInfo, error) {
opTag := tag.WorkflowActionChildWorkflowInitiated
if err := e.checkMutability(opTag); err != nil {
return nil, nil, err
}
event := e.hBuilder.AddStartChildWorkflowExecutionInitiatedEvent(workflowTaskCompletedEventID, command)
// Write the event to cache only on active cluster
e.eventsCache.PutEvent(e.executionInfo.NamespaceId, e.executionInfo.WorkflowId, e.executionState.RunId,
event.GetEventId(), event)
ci, err := e.ReplicateStartChildWorkflowExecutionInitiatedEvent(workflowTaskCompletedEventID, event, createRequestID)
if err != nil {
return nil, nil, err
}
// TODO merge active & passive task generation
if err := e.taskGenerator.GenerateChildWorkflowTasks(
timestamp.TimeValue(event.GetEventTime()),
event,
); err != nil {
return nil, nil, err
}
return event, ci, nil
}
func (e *MutableStateImpl) ReplicateStartChildWorkflowExecutionInitiatedEvent(
firstEventID int64,
event *historypb.HistoryEvent,
createRequestID string,
) (*persistencespb.ChildExecutionInfo, error) {
initiatedEventID := event.GetEventId()
attributes := event.GetStartChildWorkflowExecutionInitiatedEventAttributes()
ci := &persistencespb.ChildExecutionInfo{
Version: event.GetVersion(),
InitiatedId: initiatedEventID,
InitiatedEventBatchId: firstEventID,
StartedId: common.EmptyEventID,
StartedWorkflowId: attributes.GetWorkflowId(),
CreateRequestId: createRequestID,
Namespace: attributes.GetNamespace(),
WorkflowTypeName: attributes.GetWorkflowType().GetName(),
ParentClosePolicy: attributes.GetParentClosePolicy(),
}
e.pendingChildExecutionInfoIDs[ci.InitiatedId] = ci
e.updateChildExecutionInfos[ci.InitiatedId] = ci
return ci, nil
}
func (e *MutableStateImpl) AddChildWorkflowExecutionStartedEvent(
namespace string,
execution *commonpb.WorkflowExecution,
workflowType *commonpb.WorkflowType,
initiatedID int64,
header *commonpb.Header,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionChildWorkflowStarted
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
ci, ok := e.GetChildExecutionInfo(initiatedID)
if !ok || ci.StartedId != common.EmptyEventID {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.Bool(ok),
tag.WorkflowInitiatedID(initiatedID))
return nil, e.createInternalServerError(opTag)
}
event := e.hBuilder.AddChildWorkflowExecutionStartedEvent(
initiatedID,
namespace,
execution,
workflowType,
header,
)
if err := e.ReplicateChildWorkflowExecutionStartedEvent(event); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateChildWorkflowExecutionStartedEvent(
event *historypb.HistoryEvent,
) error {
attributes := event.GetChildWorkflowExecutionStartedEventAttributes()
initiatedID := attributes.GetInitiatedEventId()
ci, _ := e.GetChildExecutionInfo(initiatedID)
ci.StartedId = event.GetEventId()
ci.StartedRunId = attributes.GetWorkflowExecution().GetRunId()
e.updateChildExecutionInfos[ci.InitiatedId] = ci
return nil
}
func (e *MutableStateImpl) AddStartChildWorkflowExecutionFailedEvent(
initiatedID int64,
cause enumspb.StartChildWorkflowExecutionFailedCause,
initiatedEventAttributes *historypb.StartChildWorkflowExecutionInitiatedEventAttributes,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionChildWorkflowInitiationFailed
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
ci, ok := e.GetChildExecutionInfo(initiatedID)
if !ok || ci.StartedId != common.EmptyEventID {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.Bool(ok),
tag.WorkflowInitiatedID(initiatedID))
return nil, e.createInternalServerError(opTag)
}
event := e.hBuilder.AddStartChildWorkflowExecutionFailedEvent(
common.EmptyEventID, // TODO this field is not used at all
initiatedID,
cause,
initiatedEventAttributes.Namespace,
initiatedEventAttributes.WorkflowId,
initiatedEventAttributes.WorkflowType,
initiatedEventAttributes.Control, // TODO this field is probably deprecated
)
if err := e.ReplicateStartChildWorkflowExecutionFailedEvent(event); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateStartChildWorkflowExecutionFailedEvent(
event *historypb.HistoryEvent,
) error {
attributes := event.GetStartChildWorkflowExecutionFailedEventAttributes()
initiatedID := attributes.GetInitiatedEventId()
return e.DeletePendingChildExecution(initiatedID)
}
func (e *MutableStateImpl) AddChildWorkflowExecutionCompletedEvent(
initiatedID int64,
childExecution *commonpb.WorkflowExecution,
attributes *historypb.WorkflowExecutionCompletedEventAttributes,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionChildWorkflowCompleted
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
ci, ok := e.GetChildExecutionInfo(initiatedID)
if !ok || ci.StartedId == common.EmptyEventID {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.Bool(ok),
tag.WorkflowInitiatedID(initiatedID))
return nil, e.createInternalServerError(opTag)
}
workflowType := &commonpb.WorkflowType{
Name: ci.WorkflowTypeName,
}
event := e.hBuilder.AddChildWorkflowExecutionCompletedEvent(
ci.InitiatedId,
ci.StartedId,
ci.Namespace,
childExecution,
workflowType,
attributes.Result,
)
if err := e.ReplicateChildWorkflowExecutionCompletedEvent(event); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateChildWorkflowExecutionCompletedEvent(
event *historypb.HistoryEvent,
) error {
attributes := event.GetChildWorkflowExecutionCompletedEventAttributes()
initiatedID := attributes.GetInitiatedEventId()
return e.DeletePendingChildExecution(initiatedID)
}
func (e *MutableStateImpl) AddChildWorkflowExecutionFailedEvent(
initiatedID int64,
childExecution *commonpb.WorkflowExecution,
attributes *historypb.WorkflowExecutionFailedEventAttributes,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionChildWorkflowFailed
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
ci, ok := e.GetChildExecutionInfo(initiatedID)
if !ok || ci.StartedId == common.EmptyEventID {
e.logWarn(mutableStateInvalidHistoryActionMsg,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.Bool(!ok),
tag.WorkflowInitiatedID(initiatedID))
return nil, e.createInternalServerError(opTag)
}
workflowType := &commonpb.WorkflowType{
Name: ci.WorkflowTypeName,
}
event := e.hBuilder.AddChildWorkflowExecutionFailedEvent(
ci.InitiatedId,
ci.StartedId,
ci.Namespace,
childExecution,
workflowType,
attributes.Failure,
attributes.RetryState,
)
if err := e.ReplicateChildWorkflowExecutionFailedEvent(event); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateChildWorkflowExecutionFailedEvent(
event *historypb.HistoryEvent,
) error {
attributes := event.GetChildWorkflowExecutionFailedEventAttributes()
initiatedID := attributes.GetInitiatedEventId()
return e.DeletePendingChildExecution(initiatedID)
}
func (e *MutableStateImpl) AddChildWorkflowExecutionCanceledEvent(
initiatedID int64,
childExecution *commonpb.WorkflowExecution,
attributes *historypb.WorkflowExecutionCanceledEventAttributes,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionChildWorkflowCanceled
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
ci, ok := e.GetChildExecutionInfo(initiatedID)
if !ok || ci.StartedId == common.EmptyEventID {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.Bool(ok),
tag.WorkflowInitiatedID(initiatedID))
return nil, e.createInternalServerError(opTag)
}
workflowType := &commonpb.WorkflowType{
Name: ci.WorkflowTypeName,
}
event := e.hBuilder.AddChildWorkflowExecutionCanceledEvent(
ci.InitiatedId,
ci.StartedId,
ci.Namespace,
childExecution,
workflowType,
attributes.Details,
)
if err := e.ReplicateChildWorkflowExecutionCanceledEvent(event); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateChildWorkflowExecutionCanceledEvent(
event *historypb.HistoryEvent,
) error {
attributes := event.GetChildWorkflowExecutionCanceledEventAttributes()
initiatedID := attributes.GetInitiatedEventId()
return e.DeletePendingChildExecution(initiatedID)
}
func (e *MutableStateImpl) AddChildWorkflowExecutionTerminatedEvent(
initiatedID int64,
childExecution *commonpb.WorkflowExecution,
_ *historypb.WorkflowExecutionTerminatedEventAttributes, // TODO this field is not used at all
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionChildWorkflowTerminated
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
ci, ok := e.GetChildExecutionInfo(initiatedID)
if !ok || ci.StartedId == common.EmptyEventID {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.Bool(ok),
tag.WorkflowInitiatedID(initiatedID))
return nil, e.createInternalServerError(opTag)
}
workflowType := &commonpb.WorkflowType{
Name: ci.WorkflowTypeName,
}
event := e.hBuilder.AddChildWorkflowExecutionTerminatedEvent(
ci.InitiatedId,
ci.StartedId,
ci.Namespace,
childExecution,
workflowType,
)
if err := e.ReplicateChildWorkflowExecutionTerminatedEvent(event); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateChildWorkflowExecutionTerminatedEvent(
event *historypb.HistoryEvent,
) error {
attributes := event.GetChildWorkflowExecutionTerminatedEventAttributes()
initiatedID := attributes.GetInitiatedEventId()
return e.DeletePendingChildExecution(initiatedID)
}
func (e *MutableStateImpl) AddChildWorkflowExecutionTimedOutEvent(
initiatedID int64,
childExecution *commonpb.WorkflowExecution,
attributes *historypb.WorkflowExecutionTimedOutEventAttributes,
) (*historypb.HistoryEvent, error) {
opTag := tag.WorkflowActionChildWorkflowTimedOut
if err := e.checkMutability(opTag); err != nil {
return nil, err
}
ci, ok := e.GetChildExecutionInfo(initiatedID)
if !ok || ci.StartedId == common.EmptyEventID {
e.logWarn(mutableStateInvalidHistoryActionMsg, opTag,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.Bool(ok),
tag.WorkflowInitiatedID(initiatedID))
return nil, e.createInternalServerError(opTag)
}
workflowType := &commonpb.WorkflowType{
Name: ci.WorkflowTypeName,
}
event := e.hBuilder.AddChildWorkflowExecutionTimedOutEvent(
ci.InitiatedId,
ci.StartedId,
ci.Namespace,
childExecution,
workflowType,
attributes.RetryState,
)
if err := e.ReplicateChildWorkflowExecutionTimedOutEvent(event); err != nil {
return nil, err
}
return event, nil
}
func (e *MutableStateImpl) ReplicateChildWorkflowExecutionTimedOutEvent(
event *historypb.HistoryEvent,
) error {
attributes := event.GetChildWorkflowExecutionTimedOutEventAttributes()
initiatedID := attributes.GetInitiatedEventId()
return e.DeletePendingChildExecution(initiatedID)
}
func (e *MutableStateImpl) RetryActivity(
ai *persistencespb.ActivityInfo,
failure *failurepb.Failure,
) (enumspb.RetryState, error) {
opTag := tag.WorkflowActionActivityTaskRetry
if err := e.checkMutability(opTag); err != nil {
return enumspb.RETRY_STATE_INTERNAL_SERVER_ERROR, err
}
if !ai.HasRetryPolicy {
return enumspb.RETRY_STATE_RETRY_POLICY_NOT_SET, nil
}
if ai.CancelRequested {
return enumspb.RETRY_STATE_CANCEL_REQUESTED, nil
}
now := e.timeSource.Now()
backoffInterval, retryState := getBackoffInterval(
now,
ai.Attempt,
ai.RetryMaximumAttempts,
ai.RetryInitialInterval,
ai.RetryMaximumInterval,
ai.RetryExpirationTime,
ai.RetryBackoffCoefficient,
failure,
ai.RetryNonRetryableErrorTypes,
)
if retryState != enumspb.RETRY_STATE_IN_PROGRESS {
return retryState, nil
}
// a retry is needed, update activity info for next retry
ai.Version = e.GetCurrentVersion()
ai.Attempt++
ai.ScheduledTime = timestamp.TimePtr(now.Add(backoffInterval)) // update to next schedule time
ai.StartedId = common.EmptyEventID
ai.RequestId = ""
ai.StartedTime = timestamp.TimePtr(time.Time{})
ai.TimerTaskStatus = TimerTaskStatusNone
ai.RetryLastWorkerIdentity = ai.StartedIdentity
ai.RetryLastFailure = failure
if err := e.taskGenerator.GenerateActivityRetryTasks(
ai.ScheduleId,
); err != nil {
return enumspb.RETRY_STATE_INTERNAL_SERVER_ERROR, err
}
e.updateActivityInfos[ai.ScheduleId] = ai
e.syncActivityTasks[ai.ScheduleId] = struct{}{}
return enumspb.RETRY_STATE_IN_PROGRESS, nil
}
// TODO mutable state should generate corresponding transfer / timer tasks according to
// updates accumulated, while currently all transfer / timer tasks are managed manually
// TODO convert AddTransferTasks to prepareTransferTasks
// AddTransferTasks append transfer tasks
func (e *MutableStateImpl) AddTransferTasks(
transferTasks ...persistence.Task,
) {
e.InsertTransferTasks = append(e.InsertTransferTasks, transferTasks...)
}
// TODO convert AddTransferTasks to prepareTimerTasks
// AddTimerTasks append timer tasks
func (e *MutableStateImpl) AddTimerTasks(
timerTasks ...persistence.Task,
) {
e.InsertTimerTasks = append(e.InsertTimerTasks, timerTasks...)
}
// AddVisibilityTasks append visibility tasks
func (e *MutableStateImpl) AddVisibilityTasks(
visibilityTasks ...persistence.Task,
) {
e.InsertVisibilityTasks = append(e.InsertVisibilityTasks, visibilityTasks...)
}
func (e *MutableStateImpl) SetUpdateCondition(
nextEventIDInDB int64,
dbRecordVersion int64,
) {
e.nextEventIDInDB = nextEventIDInDB
e.dbRecordVersion = dbRecordVersion
}
func (e *MutableStateImpl) GetUpdateCondition() (int64, int64) {
return e.nextEventIDInDB, e.dbRecordVersion
}
func (e *MutableStateImpl) GetWorkflowStateStatus() (enumsspb.WorkflowExecutionState, enumspb.WorkflowExecutionStatus) {
return e.executionState.State, e.executionState.Status
}
func (e *MutableStateImpl) UpdateWorkflowStateStatus(
state enumsspb.WorkflowExecutionState,
status enumspb.WorkflowExecutionStatus,
) error {
return setStateStatus(e.executionState, state, status)
}
func (e *MutableStateImpl) StartTransaction(
namespaceEntry *cache.NamespaceCacheEntry,
) (bool, error) {
e.namespaceEntry = namespaceEntry
if err := e.UpdateCurrentVersion(namespaceEntry.GetFailoverVersion(), false); err != nil {
return false, err
}
flushBeforeReady, err := e.startTransactionHandleWorkflowTaskFailover(false)
if err != nil {
return false, err
}
e.startTransactionHandleWorkflowTaskTTL()
return flushBeforeReady, nil
}
func (e *MutableStateImpl) StartTransactionSkipWorkflowTaskFail(
namespaceEntry *cache.NamespaceCacheEntry,
) error {
e.namespaceEntry = namespaceEntry
if err := e.UpdateCurrentVersion(namespaceEntry.GetFailoverVersion(), false); err != nil {
return err
}
_, err := e.startTransactionHandleWorkflowTaskFailover(true)
return err
}
func (e *MutableStateImpl) CloseTransactionAsMutation(
now time.Time,
transactionPolicy TransactionPolicy,
) (*persistence.WorkflowMutation, []*persistence.WorkflowEvents, error) {
if err := e.prepareCloseTransaction(
now,
transactionPolicy,
); err != nil {
return nil, nil, err
}
workflowEventsSeq, bufferEvents, clearBuffer, err := e.prepareEventsAndReplicationTasks(transactionPolicy)
if err != nil {
return nil, nil, err
}
if len(workflowEventsSeq) > 0 {
lastEvents := workflowEventsSeq[len(workflowEventsSeq)-1].Events
lastEvent := lastEvents[len(lastEvents)-1]
if err := e.updateWithLastWriteEvent(
lastEvent,
transactionPolicy,
); err != nil {
return nil, nil, err
}
}
setTaskInfo(e.GetCurrentVersion(), now, e.InsertTransferTasks, e.InsertTimerTasks, e.InsertVisibilityTasks)
// update last update time
e.executionInfo.LastUpdateTime = &now
e.executionInfo.StateTransitionCount += 1
// we generate checksum here based on the assumption that the returned
// snapshot object is considered immutable. As of this writing, the only
// code that modifies the returned object lives inside Context.resetWorkflowExecution
// currently, the updates done inside Context.resetWorkflowExecution doesn't
// impact the checksum calculation
checksum := e.generateChecksum()
if e.dbRecordVersion == 0 && !migration.IsDBVersionEnabled() {
// noop, existing behavior
} else {
e.dbRecordVersion += 1
}
workflowMutation := &persistence.WorkflowMutation{
ExecutionInfo: e.executionInfo,
ExecutionState: e.executionState,
NextEventID: e.hBuilder.NextEventID(),
UpsertActivityInfos: e.updateActivityInfos,
DeleteActivityInfos: e.deleteActivityInfos,
UpsertTimerInfos: e.updateTimerInfos,
DeleteTimerInfos: e.deleteTimerInfos,
UpsertChildExecutionInfos: e.updateChildExecutionInfos,
DeleteChildExecutionInfos: e.deleteChildExecutionInfos,
UpsertRequestCancelInfos: e.updateRequestCancelInfos,
DeleteRequestCancelInfos: e.deleteRequestCancelInfos,
UpsertSignalInfos: e.updateSignalInfos,
DeleteSignalInfos: e.deleteSignalInfos,
UpsertSignalRequestedIDs: e.updateSignalRequestedIDs,
DeleteSignalRequestedIDs: e.deleteSignalRequestedIDs,
NewBufferedEvents: bufferEvents,
ClearBufferedEvents: clearBuffer,
TransferTasks: e.InsertTransferTasks,
ReplicationTasks: e.InsertReplicationTasks,
TimerTasks: e.InsertTimerTasks,
VisibilityTasks: e.InsertVisibilityTasks,
Condition: e.nextEventIDInDB,
DBRecordVersion: e.dbRecordVersion,
Checksum: checksum,
}
e.checksum = checksum
if err := e.cleanupTransaction(transactionPolicy); err != nil {
return nil, nil, err
}
return workflowMutation, workflowEventsSeq, nil
}
func (e *MutableStateImpl) CloseTransactionAsSnapshot(
now time.Time,
transactionPolicy TransactionPolicy,
) (*persistence.WorkflowSnapshot, []*persistence.WorkflowEvents, error) {
if err := e.prepareCloseTransaction(
now,
transactionPolicy,
); err != nil {
return nil, nil, err
}
workflowEventsSeq, bufferEvents, _, err := e.prepareEventsAndReplicationTasks(transactionPolicy)
if err != nil {
return nil, nil, err
}
if len(bufferEvents) > 0 {
// TODO do we need the functionality to generate snapshot with buffered events?
return nil, nil, serviceerror.NewInternal("cannot generate workflow snapshot with buffered events")
}
if len(workflowEventsSeq) > 0 {
lastEvents := workflowEventsSeq[len(workflowEventsSeq)-1].Events
lastEvent := lastEvents[len(lastEvents)-1]
if err := e.updateWithLastWriteEvent(
lastEvent,
transactionPolicy,
); err != nil {
return nil, nil, err
}
}
setTaskInfo(e.GetCurrentVersion(), now, e.InsertTransferTasks, e.InsertTimerTasks, e.InsertVisibilityTasks)
// update last update time
e.executionInfo.LastUpdateTime = &now
e.executionInfo.StateTransitionCount += 1
// we generate checksum here based on the assumption that the returned
// snapshot object is considered immutable. As of this writing, the only
// code that modifies the returned object lives inside Context.resetWorkflowExecution
// currently, the updates done inside Context.resetWorkflowExecution doesn't
// impact the checksum calculation
checksum := e.generateChecksum()
if e.dbRecordVersion == 0 && !migration.IsDBVersionEnabled() {
// noop, existing behavior
} else {
e.dbRecordVersion += 1
}
workflowSnapshot := &persistence.WorkflowSnapshot{
ExecutionInfo: e.executionInfo,
ExecutionState: e.executionState,
NextEventID: e.hBuilder.NextEventID(),
ActivityInfos: e.pendingActivityInfoIDs,
TimerInfos: e.pendingTimerInfoIDs,
ChildExecutionInfos: e.pendingChildExecutionInfoIDs,
RequestCancelInfos: e.pendingRequestCancelInfoIDs,
SignalInfos: e.pendingSignalInfoIDs,
SignalRequestedIDs: e.pendingSignalRequestedIDs,
TransferTasks: e.InsertTransferTasks,
ReplicationTasks: e.InsertReplicationTasks,
TimerTasks: e.InsertTimerTasks,
VisibilityTasks: e.InsertVisibilityTasks,
Condition: e.nextEventIDInDB,
DBRecordVersion: e.dbRecordVersion,
Checksum: checksum,
}
e.checksum = checksum
if err := e.cleanupTransaction(transactionPolicy); err != nil {
return nil, nil, err
}
return workflowSnapshot, workflowEventsSeq, nil
}
func (e *MutableStateImpl) IsResourceDuplicated(
resourceDedupKey definition.DeduplicationID,
) bool {
id := definition.GenerateDeduplicationKey(resourceDedupKey)
_, duplicated := e.appliedEvents[id]
return duplicated
}
func (e *MutableStateImpl) UpdateDuplicatedResource(
resourceDedupKey definition.DeduplicationID,
) {
id := definition.GenerateDeduplicationKey(resourceDedupKey)
e.appliedEvents[id] = struct{}{}
}
func (e *MutableStateImpl) prepareCloseTransaction(
now time.Time,
transactionPolicy TransactionPolicy,
) error {
if err := e.closeTransactionWithPolicyCheck(
transactionPolicy,
); err != nil {
return err
}
if err := e.closeTransactionHandleBufferedEventsLimit(
transactionPolicy,
); err != nil {
return err
}
if err := e.closeTransactionHandleWorkflowReset(
now,
transactionPolicy,
); err != nil {
return err
}
// TODO merge active & passive task generation
// NOTE: this function must be the last call
// since we only generate at most one activity & user timer,
// regardless of how many activity & user timer created
// so the calculation must be at the very end
return e.closeTransactionHandleActivityUserTimerTasks(
now,
transactionPolicy,
)
}
func (e *MutableStateImpl) cleanupTransaction(
_ TransactionPolicy,
) error {
e.updateActivityInfos = make(map[int64]*persistencespb.ActivityInfo)
e.deleteActivityInfos = make(map[int64]struct{})
e.syncActivityTasks = make(map[int64]struct{})
e.updateTimerInfos = make(map[string]*persistencespb.TimerInfo)
e.deleteTimerInfos = make(map[string]struct{})
e.updateChildExecutionInfos = make(map[int64]*persistencespb.ChildExecutionInfo)
e.deleteChildExecutionInfos = make(map[int64]struct{})
e.updateRequestCancelInfos = make(map[int64]*persistencespb.RequestCancelInfo)
e.deleteRequestCancelInfos = make(map[int64]struct{})
e.updateSignalInfos = make(map[int64]*persistencespb.SignalInfo)
e.deleteSignalInfos = make(map[int64]struct{})
e.updateSignalRequestedIDs = make(map[string]struct{})
e.deleteSignalRequestedIDs = make(map[string]struct{})
e.stateInDB = e.executionState.State
e.nextEventIDInDB = e.GetNextEventID()
// e.dbRecordVersion remains the same
e.hBuilder = NewMutableHistoryBuilder(
e.timeSource,
e.shard.GenerateTransferTaskIDs,
e.GetCurrentVersion(),
e.nextEventIDInDB,
e.bufferEventsInDB,
)
e.InsertTransferTasks = nil
e.InsertReplicationTasks = nil
e.InsertTimerTasks = nil
e.InsertVisibilityTasks = nil
return nil
}
func (e *MutableStateImpl) prepareEventsAndReplicationTasks(
transactionPolicy TransactionPolicy,
) ([]*persistence.WorkflowEvents, []*historypb.HistoryEvent, bool, error) {
currentBranchToken, err := e.GetCurrentBranchToken()
if err != nil {
return nil, nil, false, err
}
historyMutation, err := e.hBuilder.Finish(!e.HasInFlightWorkflowTask())
if err != nil {
return nil, nil, false, err
}
// TODO @wxing1292 need more refactoring to make the logic clean
e.bufferEventsInDB = historyMutation.MemBufferBatch
newBufferBatch := historyMutation.DBBufferBatch
clearBuffer := historyMutation.DBClearBuffer
newEventsBatches := historyMutation.DBEventsBatches
e.updatePendingEventIDs(historyMutation.ScheduleIDToStartID)
workflowEventsSeq := make([]*persistence.WorkflowEvents, len(newEventsBatches))
historyNodeTxnIDs, err := e.shard.GenerateTransferTaskIDs(len(newEventsBatches))
if err != nil {
return nil, nil, false, err
}
for index, eventBatch := range newEventsBatches {
workflowEventsSeq[index] = &persistence.WorkflowEvents{
NamespaceID: e.executionInfo.NamespaceId,
WorkflowID: e.executionInfo.WorkflowId,
RunID: e.executionState.RunId,
BranchToken: currentBranchToken,
PrevTxnID: e.executionInfo.LastFirstEventTxnId,
TxnID: historyNodeTxnIDs[index],
Events: eventBatch,
}
e.GetExecutionInfo().LastEventTaskId = eventBatch[len(eventBatch)-1].GetTaskId()
e.executionInfo.LastFirstEventId = eventBatch[0].GetEventId()
e.executionInfo.LastFirstEventTxnId = historyNodeTxnIDs[index]
}
if err := e.validateNoEventsAfterWorkflowFinish(
transactionPolicy,
workflowEventsSeq,
); err != nil {
return nil, nil, false, err
}
for _, workflowEvents := range workflowEventsSeq {
replicationTasks, err := e.eventsToReplicationTask(transactionPolicy, workflowEvents.Events)
if err != nil {
return nil, nil, false, err
}
e.InsertReplicationTasks = append(
e.InsertReplicationTasks,
replicationTasks...,
)
}
e.InsertReplicationTasks = append(
e.InsertReplicationTasks,
e.syncActivityToReplicationTask(transactionPolicy)...,
)
if transactionPolicy == TransactionPolicyPassive && len(e.InsertReplicationTasks) > 0 {
return nil, nil, false, serviceerror.NewInternal("should not generate replication task when close transaction as passive")
}
return workflowEventsSeq, newBufferBatch, clearBuffer, nil
}
func (e *MutableStateImpl) eventsToReplicationTask(
transactionPolicy TransactionPolicy,
events []*historypb.HistoryEvent,
) ([]persistence.Task, error) {
if transactionPolicy == TransactionPolicyPassive ||
!e.canReplicateEvents() ||
len(events) == 0 {
return emptyTasks, nil
}
firstEvent := events[0]
lastEvent := events[len(events)-1]
version := firstEvent.GetVersion()
sourceCluster := e.clusterMetadata.ClusterNameForFailoverVersion(version)
currentCluster := e.clusterMetadata.GetCurrentClusterName()
if currentCluster != sourceCluster {
return nil, serviceerror.NewInternal("MutableStateImpl encounter contradicting version & transaction policy")
}
currentBranchToken, err := e.GetCurrentBranchToken()
if err != nil {
return nil, err
}
replicationTask := &persistence.HistoryReplicationTask{
FirstEventID: firstEvent.GetEventId(),
NextEventID: lastEvent.GetEventId() + 1,
Version: firstEvent.GetVersion(),
BranchToken: currentBranchToken,
NewRunBranchToken: nil,
}
if e.executionInfo.GetVersionHistories() == nil {
return nil, serviceerror.NewInternal("should not generate replication task when missing replication state & version history")
}
return []persistence.Task{replicationTask}, nil
}
func (e *MutableStateImpl) syncActivityToReplicationTask(
transactionPolicy TransactionPolicy,
) []persistence.Task {
if transactionPolicy == TransactionPolicyPassive ||
!e.canReplicateEvents() {
return emptyTasks
}
return convertSyncActivityInfos(
e.pendingActivityInfoIDs,
e.syncActivityTasks,
)
}
func (e *MutableStateImpl) updatePendingEventIDs(
scheduleIDToStartID map[int64]int64,
) {
Loop:
for scheduleID, startID := range scheduleIDToStartID {
if activityInfo, ok := e.GetActivityInfo(scheduleID); ok {
activityInfo.StartedId = startID
e.updateActivityInfos[activityInfo.ScheduleId] = activityInfo
continue Loop
}
if childInfo, ok := e.GetChildExecutionInfo(scheduleID); ok {
childInfo.StartedId = startID
e.updateChildExecutionInfos[childInfo.InitiatedId] = childInfo
continue Loop
}
}
}
func (e *MutableStateImpl) updateWithLastWriteEvent(
lastEvent *historypb.HistoryEvent,
transactionPolicy TransactionPolicy,
) error {
if transactionPolicy == TransactionPolicyPassive {
// already handled in state builder
return nil
}
if e.executionInfo.VersionHistories != nil {
currentVersionHistory, err := versionhistory.GetCurrentVersionHistory(e.executionInfo.VersionHistories)
if err != nil {
return err
}
if err := versionhistory.AddOrUpdateVersionHistoryItem(currentVersionHistory, versionhistory.NewVersionHistoryItem(
lastEvent.GetEventId(), lastEvent.GetVersion(),
)); err != nil {
return err
}
}
return nil
}
func (e *MutableStateImpl) canReplicateEvents() bool {
return e.namespaceEntry.GetReplicationPolicy() == cache.ReplicationPolicyMultiCluster
}
// validateNoEventsAfterWorkflowFinish perform check on history event batch
// NOTE: do not apply this check on every batch, since transient
// workflow task && workflow finish will be broken (the first batch)
func (e *MutableStateImpl) validateNoEventsAfterWorkflowFinish(
transactionPolicy TransactionPolicy,
workflowEventSeq []*persistence.WorkflowEvents,
) error {
if transactionPolicy == TransactionPolicyPassive ||
len(workflowEventSeq) == 0 {
return nil
}
// only do check if workflow is finished
if e.executionState.State != enumsspb.WORKFLOW_EXECUTION_STATE_COMPLETED {
return nil
}
// workflow close
// this will perform check on the last event of last batch
// NOTE: do not apply this check on every batch, since transient
// workflow task && workflow finish will be broken (the first batch)
eventBatch := workflowEventSeq[len(workflowEventSeq)-1].Events
lastEvent := eventBatch[len(eventBatch)-1]
switch lastEvent.GetEventType() {
case enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED,
enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_FAILED,
enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_TIMED_OUT,
enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_TERMINATED,
enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_CONTINUED_AS_NEW,
enumspb.EVENT_TYPE_WORKFLOW_EXECUTION_CANCELED:
return nil
default:
e.logError(
"encounter case where events appears after workflow finish.",
tag.WorkflowNamespaceID(e.executionInfo.NamespaceId),
tag.WorkflowID(e.executionInfo.WorkflowId),
tag.WorkflowRunID(e.executionState.RunId),
)
return consts.ErrEventsAterWorkflowFinish
}
}
func (e *MutableStateImpl) startTransactionHandleWorkflowTaskTTL() {
if e.executionInfo.StickyTaskQueue == "" {
return
}
ttl := e.config.StickyTTL(e.GetNamespaceEntry().GetInfo().Name)
expired := e.timeSource.Now().After(timestamp.TimeValue(e.executionInfo.LastUpdateTime).Add(ttl))
if expired && !e.HasPendingWorkflowTask() {
e.ClearStickyness()
}
}
func (e *MutableStateImpl) startTransactionHandleWorkflowTaskFailover(
skipWorkflowTaskFailed bool,
) (bool, error) {
if !e.IsWorkflowExecutionRunning() ||
!e.canReplicateEvents() {
return false, nil
}
// NOTE:
// the main idea here is to guarantee that once there is a workflow task started
// all events ending in the buffer should have the same version
// Handling mutable state turn from standby to active, while having a workflow task on the fly
workflowTask, ok := e.GetInFlightWorkflowTask()
if !ok || workflowTask.Version >= e.GetCurrentVersion() {
// no pending workflow tasks, no buffered events
// or workflow task has higher / equal version
return false, nil
}
currentVersion := e.GetCurrentVersion()
lastWriteVersion, err := e.GetLastWriteVersion()
if err != nil {
return false, err
}
if lastWriteVersion != workflowTask.Version {
return false, serviceerror.NewInternal(fmt.Sprintf("MutableStateImpl encounter mismatch version, workflow task: %v, last write version %v", workflowTask.Version, lastWriteVersion))
}
lastWriteSourceCluster := e.clusterMetadata.ClusterNameForFailoverVersion(lastWriteVersion)
currentVersionCluster := e.clusterMetadata.ClusterNameForFailoverVersion(currentVersion)
currentCluster := e.clusterMetadata.GetCurrentClusterName()
// there are 4 cases for version changes (based on version from namespace cache)
// NOTE: namespace cache version change may occur after seeing events with higher version
// meaning that the flush buffer logic in NDC branch manager should be kept.
//
// 1. active -> passive => fail workflow task & flush buffer using last write version
// 2. active -> active => fail workflow task & flush buffer using last write version
// 3. passive -> active => fail workflow task using current version, no buffered events
// 4. passive -> passive => no buffered events, since always passive, nothing to be done
// handle case 4
if lastWriteSourceCluster != currentCluster && currentVersionCluster != currentCluster {
// do a sanity check on buffered events
if e.HasBufferedEvents() {
return false, serviceerror.NewInternal("MutableStateImpl encounter previous passive workflow with buffered events")
}
return false, nil
}
// handle case 1 & 2
var flushBufferVersion = lastWriteVersion
// handle case 3
if lastWriteSourceCluster != currentCluster && currentVersionCluster == currentCluster {
// do a sanity check on buffered events
if e.HasBufferedEvents() {
return false, serviceerror.NewInternal("MutableStateImpl encounter previous passive workflow with buffered events")
}
flushBufferVersion = currentVersion
}
// this workflow was previous active (whether it has buffered events or not),
// the in flight workflow task must be failed to guarantee all events within same
// event batch shard the same version
if err := e.UpdateCurrentVersion(flushBufferVersion, true); err != nil {
return false, err
}
if skipWorkflowTaskFailed {
return false, nil
}
// we have a workflow task with buffered events on the fly with a lower version, fail it
if err := failWorkflowTask(
e,
workflowTask,
enumspb.WORKFLOW_TASK_FAILED_CAUSE_FAILOVER_CLOSE_COMMAND,
); err != nil {
return false, err
}
err = ScheduleWorkflowTask(e)
if err != nil {
return false, err
}
return true, nil
}
func (e *MutableStateImpl) closeTransactionWithPolicyCheck(
transactionPolicy TransactionPolicy,
) error {
if transactionPolicy == TransactionPolicyPassive ||
!e.canReplicateEvents() {
return nil
}
activeCluster := e.clusterMetadata.ClusterNameForFailoverVersion(e.GetCurrentVersion())
currentCluster := e.clusterMetadata.GetCurrentClusterName()
if activeCluster != currentCluster {
namespaceID := e.GetExecutionInfo().NamespaceId
return serviceerror.NewNamespaceNotActive(namespaceID, currentCluster, activeCluster)
}
return nil
}
func (e *MutableStateImpl) closeTransactionHandleBufferedEventsLimit(
transactionPolicy TransactionPolicy,
) error {
if transactionPolicy == TransactionPolicyPassive ||
!e.IsWorkflowExecutionRunning() {
return nil
}
if e.hBuilder.BufferEventSize() < e.config.MaximumBufferedEventsBatch() {
return nil
}
// Handling buffered events size issue
if workflowTask, ok := e.GetInFlightWorkflowTask(); ok {
// we have a workflow task on the fly with a lower version, fail it
if err := failWorkflowTask(
e,
workflowTask,
enumspb.WORKFLOW_TASK_FAILED_CAUSE_FORCE_CLOSE_COMMAND,
); err != nil {
return err
}
err := ScheduleWorkflowTask(e)
if err != nil {
return err
}
}
return nil
}
func (e *MutableStateImpl) closeTransactionHandleWorkflowReset(
now time.Time,
transactionPolicy TransactionPolicy,
) error {
if transactionPolicy == TransactionPolicyPassive ||
!e.IsWorkflowExecutionRunning() {
return nil
}
// compare with bad client binary checksum and schedule a reset task
// only schedule reset task if current doesn't have childWFs.
// TODO: This will be removed once our reset allows childWFs
if len(e.GetPendingChildExecutionInfos()) != 0 {
return nil
}
namespaceEntry, err := e.shard.GetNamespaceCache().GetNamespaceByID(e.executionInfo.NamespaceId)
if err != nil {
return err
}
if _, pt := FindAutoResetPoint(
e.timeSource,
namespaceEntry.GetConfig().BadBinaries,
e.GetExecutionInfo().AutoResetPoints,
); pt != nil {
if err := e.taskGenerator.GenerateWorkflowResetTasks(
e.unixNanoToTime(now.UnixNano()),
); err != nil {
return err
}
e.logInfo("Auto-Reset task is scheduled",
tag.WorkflowNamespace(namespaceEntry.GetInfo().Name),
tag.WorkflowID(e.executionInfo.WorkflowId),
tag.WorkflowRunID(e.executionState.RunId),
tag.WorkflowResetBaseRunID(pt.GetRunId()),
tag.WorkflowEventID(pt.GetFirstWorkflowTaskCompletedId()),
tag.WorkflowBinaryChecksum(pt.GetBinaryChecksum()),
)
}
return nil
}
func (e *MutableStateImpl) closeTransactionHandleActivityUserTimerTasks(
now time.Time,
transactionPolicy TransactionPolicy,
) error {
if transactionPolicy == TransactionPolicyPassive ||
!e.IsWorkflowExecutionRunning() {
return nil
}
if err := e.taskGenerator.GenerateActivityTimerTasks(
e.unixNanoToTime(now.UnixNano()),
); err != nil {
return err
}
return e.taskGenerator.GenerateUserTimerTasks(
e.unixNanoToTime(now.UnixNano()),
)
}
func (e *MutableStateImpl) checkMutability(
actionTag tag.ZapTag,
) error {
if !e.IsWorkflowExecutionRunning() {
e.logWarn(
mutableStateInvalidHistoryActionMsg,
tag.WorkflowEventID(e.GetNextEventID()),
tag.ErrorTypeInvalidHistoryAction,
tag.WorkflowState(e.executionState.State),
actionTag,
)
return ErrWorkflowFinished
}
return nil
}
func (e *MutableStateImpl) generateChecksum() *persistencespb.Checksum {
if !e.shouldGenerateChecksum() {
return nil
}
csum, err := generateMutableStateChecksum(e)
if err != nil {
e.logWarn("error generating MutableState checksum", tag.Error(err))
return nil
}
return csum
}
func (e *MutableStateImpl) shouldGenerateChecksum() bool {
if e.namespaceEntry == nil {
return false
}
return rand.Intn(100) < e.config.MutableStateChecksumGenProbability(e.namespaceEntry.GetInfo().Name)
}
func (e *MutableStateImpl) shouldVerifyChecksum() bool {
if e.namespaceEntry == nil {
return false
}
return rand.Intn(100) < e.config.MutableStateChecksumVerifyProbability(e.namespaceEntry.GetInfo().Name)
}
func (e *MutableStateImpl) shouldInvalidateCheckum() bool {
invalidateBeforeEpochSecs := int64(e.config.MutableStateChecksumInvalidateBefore())
if invalidateBeforeEpochSecs > 0 {
invalidateBefore := time.Unix(invalidateBeforeEpochSecs, 0).UTC()
return e.executionInfo.LastUpdateTime.Before(invalidateBefore)
}
return false
}
func (e *MutableStateImpl) createInternalServerError(
actionTag tag.ZapTag,
) error {
return serviceerror.NewInternal(actionTag.Field().String + " operation failed")
}
func (e *MutableStateImpl) createCallerError(
actionTag tag.ZapTag,
) error {
return serviceerror.NewInvalidArgument(fmt.Sprintf(mutableStateInvalidHistoryActionMsgTemplate, actionTag.Field().String))
}
func (_ *MutableStateImpl) unixNanoToTime(
timestampNanos int64,
) time.Time {
return time.Unix(0, timestampNanos).UTC()
}
func (e *MutableStateImpl) logInfo(msg string, tags ...tag.Tag) {
tags = append(tags, tag.WorkflowID(e.executionInfo.WorkflowId))
tags = append(tags, tag.WorkflowRunID(e.executionState.RunId))
tags = append(tags, tag.WorkflowNamespaceID(e.executionInfo.NamespaceId))
e.logger.Info(msg, tags...)
}
func (e *MutableStateImpl) logWarn(msg string, tags ...tag.Tag) {
tags = append(tags, tag.WorkflowID(e.executionInfo.WorkflowId))
tags = append(tags, tag.WorkflowRunID(e.executionState.RunId))
tags = append(tags, tag.WorkflowNamespaceID(e.executionInfo.NamespaceId))
e.logger.Warn(msg, tags...)
}
func (e *MutableStateImpl) logError(msg string, tags ...tag.Tag) {
tags = append(tags, tag.WorkflowID(e.executionInfo.WorkflowId))
tags = append(tags, tag.WorkflowRunID(e.executionState.RunId))
tags = append(tags, tag.WorkflowNamespaceID(e.executionInfo.NamespaceId))
e.logger.Error(msg, tags...)
}
func (e *MutableStateImpl) logDataInconsistency() {
namespaceID := e.executionInfo.NamespaceId
workflowID := e.executionInfo.WorkflowId
runID := e.executionState.RunId
e.logger.Error("encounter cassandra data inconsistency",
tag.WorkflowNamespaceID(namespaceID),
tag.WorkflowID(workflowID),
tag.WorkflowRunID(runID),
)
}
| 1 | 12,095 | so this is now init to 1? | temporalio-temporal | go |
@@ -191,7 +191,8 @@ bool ZoneDatabase::LoadSpawnGroups(const char *zone_name, uint16 version, SpawnG
WHERE
spawn2.spawngroupID = spawngroup.ID
AND
- spawn2.version = {} and zone = '{}'
+ (spawn2.version = {} OR version = -1)
+ AND zone = '{}'
{}
),
version, | 1 | /* EQEMu: Everquest Server Emulator
Copyright (C) 2001-2002 EQEMu Development Team (http://eqemu.org)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY except by those people which sell it, which
are required to give you total support for your newly bought product;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <fmt/format.h>
#include "../common/global_define.h"
#include "../common/types.h"
#include "entity.h"
#include "spawngroup.h"
#include "zone.h"
#include "zonedb.h"
#include "zone_store.h"
#include "../common/repositories/criteria/content_filter_criteria.h"
extern EntityList entity_list;
extern Zone *zone;
SpawnEntry::SpawnEntry(uint32 in_NPCType, int in_chance, uint16 in_filter, uint8 in_npc_spawn_limit)
{
NPCType = in_NPCType;
chance = in_chance;
condition_value_filter = in_filter;
npc_spawn_limit = in_npc_spawn_limit;
}
SpawnGroup::SpawnGroup(
uint32 in_id,
char *name,
int in_group_spawn_limit,
float dist,
float maxx,
float minx,
float maxy,
float miny,
int delay_in,
int despawn_in,
uint32 despawn_timer_in,
int min_delay_in,
bool wp_spawns_in
)
{
id = in_id;
strn0cpy(name_, name, 120);
group_spawn_limit = in_group_spawn_limit;
roambox[0] = maxx;
roambox[1] = minx;
roambox[2] = maxy;
roambox[3] = miny;
roamdist = dist;
min_delay = min_delay_in;
delay = delay_in;
despawn = despawn_in;
despawn_timer = despawn_timer_in;
wp_spawns = wp_spawns_in;
}
uint32 SpawnGroup::GetNPCType(uint16 in_filter)
{
int npcType = 0;
int totalchance = 0;
if (!entity_list.LimitCheckGroup(id, group_spawn_limit)) {
return (0);
}
std::list<SpawnEntry *> possible;
for (auto &it : list_) {
auto se = it.get();
if (!entity_list.LimitCheckType(se->NPCType, se->npc_spawn_limit)) {
continue;
}
if (se->condition_value_filter != in_filter)
continue;
totalchance += se->chance;
possible.push_back(se);
}
if (totalchance == 0) {
return 0;
}
int32 roll = 0;
roll = zone->random.Int(0, totalchance - 1);
for (auto se : possible) {
if (roll < se->chance) {
npcType = se->NPCType;
break;
}
else {
roll -= se->chance;
}
}
return npcType;
}
void SpawnGroup::AddSpawnEntry(std::unique_ptr<SpawnEntry> &newEntry)
{
list_.push_back(std::move(newEntry));
}
SpawnGroup::~SpawnGroup()
{
list_.clear();
}
SpawnGroupList::~SpawnGroupList()
{
m_spawn_groups.clear();
}
void SpawnGroupList::AddSpawnGroup(std::unique_ptr<SpawnGroup> &new_group)
{
if (new_group == nullptr) {
return;
}
m_spawn_groups[new_group->id] = std::move(new_group);
}
SpawnGroup *SpawnGroupList::GetSpawnGroup(uint32 in_id)
{
if (m_spawn_groups.count(in_id) != 1) {
return nullptr;
}
return (m_spawn_groups[in_id].get());
}
bool SpawnGroupList::RemoveSpawnGroup(uint32 in_id)
{
if (m_spawn_groups.count(in_id) != 1) {
return (false);
}
m_spawn_groups.erase(in_id);
return (true);
}
void SpawnGroupList::ReloadSpawnGroups()
{
ClearSpawnGroups();
content_db.LoadSpawnGroups(zone->GetShortName(), zone->GetInstanceVersion(), &zone->spawn_group_list);
}
void SpawnGroupList::ClearSpawnGroups()
{
m_spawn_groups.clear();
}
bool ZoneDatabase::LoadSpawnGroups(const char *zone_name, uint16 version, SpawnGroupList *spawn_group_list)
{
std::string query = fmt::format(
SQL(
SELECT
DISTINCT(spawngroupID),
spawngroup.name,
spawngroup.spawn_limit,
spawngroup.dist,
spawngroup.max_x,
spawngroup.min_x,
spawngroup.max_y,
spawngroup.min_y,
spawngroup.delay,
spawngroup.despawn,
spawngroup.despawn_timer,
spawngroup.mindelay,
spawngroup.wp_spawns
FROM
spawn2,
spawngroup
WHERE
spawn2.spawngroupID = spawngroup.ID
AND
spawn2.version = {} and zone = '{}'
{}
),
version,
zone_name,
ContentFilterCriteria::apply()
);
auto results = QueryDatabase(query);
if (!results.Success()) {
return false;
}
for (auto row = results.begin(); row != results.end(); ++row) {
auto new_spawn_group = std::make_unique<SpawnGroup>(
atoi(row[0]),
row[1],
atoi(row[2]),
atof(row[3]),
atof(row[4]),
atof(row[5]),
atof(row[6]),
atof(row[7]),
atoi(row[8]),
atoi(row[9]),
atoi(row[10]),
atoi(row[11]),
atoi(row[12])
);
spawn_group_list->AddSpawnGroup(new_spawn_group);
}
query = fmt::format(
SQL(
SELECT
DISTINCT
spawnentry.spawngroupID,
npcid,
chance,
condition_value_filter,
npc_types.spawn_limit
AS sl
FROM
spawnentry,
spawn2,
npc_types
WHERE
spawnentry.npcID = npc_types.id
AND
spawnentry.spawngroupID = spawn2.spawngroupID
AND
zone = '{}'),
zone_name
);
results = QueryDatabase(query);
if (!results.Success()) {
return false;
}
for (auto row = results.begin(); row != results.end(); ++row) {
auto new_spawn_entry = std::make_unique<SpawnEntry>(
atoi(row[1]),
atoi(row[2]),
atoi(row[3]),
(row[4] ? atoi(row[4]) : 0)
);
SpawnGroup *spawn_group = spawn_group_list->GetSpawnGroup(atoi(row[0]));
if (!spawn_group) {
continue;
}
spawn_group->AddSpawnEntry(new_spawn_entry);
}
return true;
}
/**
* @param spawn_group_id
* @param spawn_group_list
* @return
*/
bool ZoneDatabase::LoadSpawnGroupsByID(int spawn_group_id, SpawnGroupList *spawn_group_list)
{
std::string query = fmt::format(
SQL(
SELECT DISTINCT
(spawngroup.id),
spawngroup.name,
spawngroup.spawn_limit,
spawngroup.dist,
spawngroup.max_x,
spawngroup.min_x,
spawngroup.max_y,
spawngroup.min_y,
spawngroup.delay,
spawngroup.despawn,
spawngroup.despawn_timer,
spawngroup.mindelay,
spawngroup.wp_spawns
FROM
spawngroup
WHERE
spawngroup.ID = '{}'
),
spawn_group_id
);
auto results = QueryDatabase(query);
if (!results.Success()) {
return false;
}
for (auto row = results.begin(); row != results.end(); ++row) {
LogSpawnsDetail(
"[LoadSpawnGroupsByID] Loading spawn_group spawn_group_id [{}] name [{}] spawn_limit [{}] dist [{}]",
row[0],
row[1],
row[2],
row[3]
);
auto new_spawn_group = std::make_unique<SpawnGroup>(
atoi(row[0]),
row[1],
atoi(row[2]),
atof(row[3]),
atof(row[4]),
atof(row[5]),
atof(row[6]),
atof(row[7]),
atoi(row[8]),
atoi(row[9]),
atoi(row[10]),
atoi(row[11]),
atoi(row[12])
);
spawn_group_list->AddSpawnGroup(new_spawn_group);
}
query = fmt::format(
SQL(
SELECT DISTINCT
(spawnentry.spawngroupID),
spawnentry.npcid,
spawnentry.chance,
spawnentry.condition_value_filter,
spawngroup.spawn_limit
FROM
spawnentry,
spawngroup
WHERE
spawnentry.spawngroupID = '{}'
AND spawngroup.spawn_limit = '0'
ORDER BY chance),
spawn_group_id
);
results = QueryDatabase(query);
if (!results.Success()) {
return false;
}
for (auto row = results.begin(); row != results.end(); ++row) {
auto new_spawn_entry = std::make_unique<SpawnEntry>(
atoi(row[1]),
atoi(row[2]),
atoi(row[3]),
(row[4] ? atoi(row[4]) : 0)
);
LogSpawnsDetail(
"[LoadSpawnGroupsByID] Loading spawn_entry spawn_group_id [{}] npc_id [{}] chance [{}] condition_value_filter [{}] spawn_limit [{}]",
row[0],
row[1],
row[2],
row[3],
row[4]
);
SpawnGroup *spawn_group = spawn_group_list->GetSpawnGroup(atoi(row[0]));
if (!spawn_group) {
continue;
}
spawn_group->AddSpawnEntry(new_spawn_entry);
}
return true;
}
| 1 | 10,304 | For future note; not prefixing the table in a join can throw an error in the query parser depending on how the query is built I am making an assumption this was tested | EQEmu-Server | cpp |
@@ -42,9 +42,13 @@ var c client.Client
var expectedRequest = reconcile.Request{NamespacedName: types.NamespacedName{Name: "foo", Namespace: "default"}}
-var jobKey = types.NamespacedName{Name: "install-foo", Namespace: "default"}
+var jobKey = types.NamespacedName{Name: "foo-install", Namespace: "default"}
-const timeout = time.Second * 5
+const (
+ timeout = time.Second * 10
+ fakeClusterUUID = "fe953108-f64c-4166-bb8e-20da7665ba00"
+ fakeClusterMetadata = `{"clusterName":"foo","aws":{"region":"us-east-1","identifier":{"tectonicClusterID":"fe953108-f64c-4166-bb8e-20da7665ba00"}}}`
+)
func init() {
log.SetLevel(log.DebugLevel) | 1 | /*
Copyright 2018 The Kubernetes Authors.
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.
*/
package clusterdeployment
import (
"fmt"
"testing"
"time"
hivev1 "github.com/openshift/hive/pkg/apis/hive/v1alpha1"
"github.com/onsi/gomega"
log "github.com/sirupsen/logrus"
"golang.org/x/net/context"
kbatch "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
var c client.Client
var expectedRequest = reconcile.Request{NamespacedName: types.NamespacedName{Name: "foo", Namespace: "default"}}
var jobKey = types.NamespacedName{Name: "install-foo", Namespace: "default"}
const timeout = time.Second * 5
func init() {
log.SetLevel(log.DebugLevel)
}
func testClusterDeployment() *hivev1.ClusterDeployment {
return &hivev1.ClusterDeployment{
ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "default"},
Spec: hivev1.ClusterDeploymentSpec{
Config: hivev1.InstallConfig{
Admin: hivev1.Admin{
Email: "[email protected]",
Password: corev1.LocalObjectReference{
Name: "admin-password",
},
SSHKey: &corev1.LocalObjectReference{
Name: "ssh-key",
},
},
Machines: []hivev1.MachinePool{},
PullSecret: corev1.LocalObjectReference{
Name: "pull-secret",
},
Platform: hivev1.Platform{
AWS: &hivev1.AWSPlatform{
Region: "us-east-1",
},
},
},
PlatformSecrets: hivev1.PlatformSecrets{
AWS: &hivev1.AWSPlatformSecrets{
Credentials: corev1.LocalObjectReference{
Name: "aws-credentials",
},
},
},
},
}
}
func TestReconcileNewClusterDeployment(t *testing.T) {
g := gomega.NewGomegaWithT(t)
// Setup the Manager and Controller. Wrap the Controller Reconcile function so it writes each request to a
// channel when it is finished.
mgr, err := manager.New(cfg, manager.Options{})
g.Expect(err).NotTo(gomega.HaveOccurred())
c = mgr.GetClient()
recFn, requests := SetupTestReconcile(newReconciler(mgr))
g.Expect(add(mgr, recFn)).NotTo(gomega.HaveOccurred())
defer close(StartTestManager(mgr, g))
instance := testClusterDeployment()
// Create the ClusterDeployment object and expect the Reconcile and Deployment to be created
err = c.Create(context.TODO(), instance)
// The instance object may not be a valid object because it might be missing some required fields.
// Please modify the instance object by adding required fields and then remove the following if statement.
if apierrors.IsInvalid(err) {
t.Errorf("failed to create object, got an invalid object error: %v", err)
t.Fail()
return
}
g.Expect(err).NotTo(gomega.HaveOccurred())
defer c.Delete(context.TODO(), instance)
g.Eventually(requests, timeout).Should(gomega.Receive(gomega.Equal(expectedRequest)))
job := &kbatch.Job{}
g.Eventually(func() error { return c.Get(context.TODO(), jobKey, job) }, timeout).
Should(gomega.Succeed())
// Fake that the install job was successful:
job.Status.Conditions = []kbatch.JobCondition{
{
Type: kbatch.JobComplete,
Status: corev1.ConditionTrue,
},
}
g.Expect(c.Status().Update(context.TODO(), job)).NotTo(gomega.HaveOccurred())
g.Eventually(requests, timeout).Should(gomega.Receive(gomega.Equal(expectedRequest)))
// Test that our cluster deployment is updated as we would expect:
g.Eventually(func() error {
updatedCD := &hivev1.ClusterDeployment{}
err := c.Get(context.TODO(), expectedRequest.NamespacedName, updatedCD)
if err != nil {
return err
}
// All of these conditions should eventually be true:
if !updatedCD.Status.Installed {
return fmt.Errorf("cluster deployment status not marked installed")
}
if !HasFinalizer(updatedCD, hivev1.FinalizerDeprovision) {
return fmt.Errorf("cluster deployment does not have expected finalizer")
}
return nil
}, timeout).Should(gomega.Succeed())
// Delete the Job and expect Reconcile to be called for Job deletion
g.Expect(c.Delete(context.TODO(), job)).NotTo(gomega.HaveOccurred())
g.Eventually(requests, timeout).Should(gomega.Receive(gomega.Equal(expectedRequest)))
g.Eventually(func() error { return c.Get(context.TODO(), jobKey, job) }, timeout).
Should(gomega.Succeed())
// Manually delete Job since GC isn't enabled in the test control plane
g.Expect(c.Delete(context.TODO(), job)).To(gomega.Succeed())
}
// TODO: how to mimic objects already existing?
| 1 | 4,472 | Had to bring this up, will abandon this style of testing based on Joel's work soon. | openshift-hive | go |
@@ -493,7 +493,7 @@ public class HttpSolrCall {
}
if (statusCode == AuthorizationResponse.FORBIDDEN.statusCode) {
if (log.isDebugEnabled()) {
- log.debug("UNAUTHORIZED auth header {} context : {}, msg: {}", req.getHeader("Authorization"), context, authResponse.getMessage()); // logOk
+ log.debug("UNAUTHORIZED auth header {} context : {}, msg: {}", req.getHeader("Authorization"), context, authResponse.getMessage()); // nowarn
}
sendError(statusCode,
"Unauthorized request, Response code: " + statusCode); | 1 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.solr.servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.invoke.MethodHandles;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import io.opentracing.Span;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.InputStreamEntity;
import org.apache.solr.api.ApiBag;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.HttpClientUtil;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.annotation.SolrThreadSafe;
import org.apache.solr.common.cloud.Aliases;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.DocCollection;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.cloud.ZkNodeProps;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.MapSolrParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.CommandOperation;
import org.apache.solr.common.util.ContentStream;
import org.apache.solr.common.util.JsonSchemaValidator;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.common.util.StrUtils;
import org.apache.solr.common.util.TimeSource;
import org.apache.solr.common.util.Utils;
import org.apache.solr.common.util.ValidatingJsonMap;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.SolrConfig;
import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.ContentStreamHandlerBase;
import org.apache.solr.logging.MDCLoggingContext;
import org.apache.solr.request.LocalSolrQueryRequest;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrQueryRequestBase;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.request.SolrRequestInfo;
import org.apache.solr.response.QueryResponseWriter;
import org.apache.solr.response.QueryResponseWriterUtil;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.security.AuditEvent;
import org.apache.solr.security.AuditEvent.EventType;
import org.apache.solr.security.AuthenticationPlugin;
import org.apache.solr.security.AuthorizationContext;
import org.apache.solr.security.AuthorizationContext.CollectionRequest;
import org.apache.solr.security.AuthorizationContext.RequestType;
import org.apache.solr.security.AuthorizationResponse;
import org.apache.solr.security.PublicKeyHandler;
import org.apache.solr.servlet.SolrDispatchFilter.Action;
import org.apache.solr.servlet.cache.HttpCacheHeaderUtil;
import org.apache.solr.servlet.cache.Method;
import org.apache.solr.update.processor.DistributingUpdateProcessorFactory;
import org.apache.solr.util.RTimerTree;
import org.apache.solr.util.TimeOut;
import org.apache.solr.util.tracing.GlobalTracer;
import org.apache.zookeeper.KeeperException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MarkerFactory;
import static org.apache.solr.common.cloud.ZkStateReader.BASE_URL_PROP;
import static org.apache.solr.common.cloud.ZkStateReader.COLLECTION_PROP;
import static org.apache.solr.common.cloud.ZkStateReader.CORE_NAME_PROP;
import static org.apache.solr.common.cloud.ZkStateReader.NODE_NAME_PROP;
import static org.apache.solr.common.cloud.ZkStateReader.REPLICATION_FACTOR;
import static org.apache.solr.common.params.CollectionAdminParams.SYSTEM_COLL;
import static org.apache.solr.common.params.CollectionParams.CollectionAction.CREATE;
import static org.apache.solr.common.params.CollectionParams.CollectionAction.DELETE;
import static org.apache.solr.common.params.CollectionParams.CollectionAction.RELOAD;
import static org.apache.solr.common.params.CommonParams.NAME;
import static org.apache.solr.common.params.CoreAdminParams.ACTION;
import static org.apache.solr.servlet.SolrDispatchFilter.Action.ADMIN;
import static org.apache.solr.servlet.SolrDispatchFilter.Action.FORWARD;
import static org.apache.solr.servlet.SolrDispatchFilter.Action.PASSTHROUGH;
import static org.apache.solr.servlet.SolrDispatchFilter.Action.PROCESS;
import static org.apache.solr.servlet.SolrDispatchFilter.Action.REMOTEQUERY;
import static org.apache.solr.servlet.SolrDispatchFilter.Action.RETRY;
import static org.apache.solr.servlet.SolrDispatchFilter.Action.RETURN;
/**
* This class represents a call made to Solr
**/
@SolrThreadSafe
public class HttpSolrCall {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
public static final String ORIGINAL_USER_PRINCIPAL_HEADER = "originalUserPrincipal";
public static final String INTERNAL_REQUEST_COUNT = "_forwardedCount";
public static final Random random;
static {
// We try to make things reproducible in the context of our tests by initializing the random instance
// based on the current seed
String seed = System.getProperty("tests.seed");
if (seed == null) {
random = new Random();
} else {
random = new Random(seed.hashCode());
}
}
protected final SolrDispatchFilter solrDispatchFilter;
protected final CoreContainer cores;
protected final HttpServletRequest req;
protected final HttpServletResponse response;
protected final boolean retry;
protected SolrCore core = null;
protected SolrQueryRequest solrReq = null;
private boolean mustClearSolrRequestInfo = false;
protected SolrRequestHandler handler = null;
protected final SolrParams queryParams;
protected String path;
protected Action action;
protected String coreUrl;
protected SolrConfig config;
protected Map<String, Integer> invalidStates;
//The states of client that is invalid in this request
protected String origCorename; // What's in the URL path; might reference a collection/alias or a Solr core name
protected List<String> collectionsList; // The list of SolrCloud collections if in SolrCloud (usually 1)
public RequestType getRequestType() {
return requestType;
}
protected RequestType requestType;
public HttpSolrCall(SolrDispatchFilter solrDispatchFilter, CoreContainer cores,
HttpServletRequest request, HttpServletResponse response, boolean retry) {
this.solrDispatchFilter = solrDispatchFilter;
this.cores = cores;
this.req = request;
this.response = response;
this.retry = retry;
this.requestType = RequestType.UNKNOWN;
req.setAttribute(HttpSolrCall.class.getName(), this);
queryParams = SolrRequestParsers.parseQueryString(req.getQueryString());
// set a request timer which can be reused by requests if needed
req.setAttribute(SolrRequestParsers.REQUEST_TIMER_SERVLET_ATTRIBUTE, new RTimerTree());
// put the core container in request attribute
req.setAttribute("org.apache.solr.CoreContainer", cores);
path = ServletUtils.getPathAfterContext(req);
}
public String getPath() {
return path;
}
public HttpServletRequest getReq() {
return req;
}
public SolrCore getCore() {
return core;
}
public SolrParams getQueryParams() {
return queryParams;
}
protected Aliases getAliases() {
return cores.isZooKeeperAware() ? cores.getZkController().getZkStateReader().getAliases() : Aliases.EMPTY;
}
/** The collection(s) referenced in this request. Populated in {@link #init()}. Not null. */
public List<String> getCollectionsList() {
return collectionsList != null ? collectionsList : Collections.emptyList();
}
protected void init() throws Exception {
// check for management path
String alternate = cores.getManagementPath();
if (alternate != null && path.startsWith(alternate)) {
path = path.substring(0, alternate.length());
}
// unused feature ?
int idx = path.indexOf(':');
if (idx > 0) {
// save the portion after the ':' for a 'handler' path parameter
path = path.substring(0, idx);
}
// Check for container handlers
handler = cores.getRequestHandler(path);
if (handler != null) {
solrReq = SolrRequestParsers.DEFAULT.parse(null, path, req);
solrReq.getContext().put(CoreContainer.class.getName(), cores);
requestType = RequestType.ADMIN;
action = ADMIN;
return;
}
// Parse a core or collection name from the path and attempt to see if it's a core name
idx = path.indexOf("/", 1);
if (idx > 1) {
origCorename = path.substring(1, idx);
// Try to resolve a Solr core name
core = cores.getCore(origCorename);
if (core != null) {
path = path.substring(idx);
} else {
if (cores.isCoreLoading(origCorename)) { // extra mem barriers, so don't look at this before trying to get core
throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "SolrCore is loading");
}
// the core may have just finished loading
core = cores.getCore(origCorename);
if (core != null) {
path = path.substring(idx);
} else {
if (!cores.isZooKeeperAware()) {
core = cores.getCore("");
}
}
}
}
if (cores.isZooKeeperAware()) {
// init collectionList (usually one name but not when there are aliases)
String def = core != null ? core.getCoreDescriptor().getCollectionName() : origCorename;
collectionsList = resolveCollectionListOrAlias(queryParams.get(COLLECTION_PROP, def)); // &collection= takes precedence
if (core == null) {
// lookup core from collection, or route away if need to
String collectionName = collectionsList.isEmpty() ? null : collectionsList.get(0); // route to 1st
//TODO try the other collections if can't find a local replica of the first? (and do to V2HttpSolrCall)
boolean isPreferLeader = (path.endsWith("/update") || path.contains("/update/"));
core = getCoreByCollection(collectionName, isPreferLeader); // find a local replica/core for the collection
if (core != null) {
if (idx > 0) {
path = path.substring(idx);
}
} else {
// if we couldn't find it locally, look on other nodes
if (idx > 0) {
extractRemotePath(collectionName, origCorename);
if (action == REMOTEQUERY) {
path = path.substring(idx);
return;
}
}
//core is not available locally or remotely
autoCreateSystemColl(collectionName);
if (action != null) return;
}
}
}
// With a valid core...
if (core != null) {
config = core.getSolrConfig();
// get or create/cache the parser for the core
SolrRequestParsers parser = config.getRequestParsers();
// Determine the handler from the url path if not set
// (we might already have selected the cores handler)
extractHandlerFromURLPath(parser);
if (action != null) return;
// With a valid handler and a valid core...
if (handler != null) {
// if not a /select, create the request
if (solrReq == null) {
solrReq = parser.parse(core, path, req);
}
invalidStates = checkStateVersionsAreValid(solrReq.getParams().get(CloudSolrClient.STATE_VERSION));
addCollectionParamIfNeeded(getCollectionsList());
action = PROCESS;
return; // we are done with a valid handler
}
}
log.debug("no handler or core retrieved for {}, follow through...", path);
action = PASSTHROUGH;
}
protected void autoCreateSystemColl(String corename) throws Exception {
if (core == null &&
SYSTEM_COLL.equals(corename) &&
"POST".equals(req.getMethod()) &&
!cores.getZkController().getClusterState().hasCollection(SYSTEM_COLL)) {
log.info("Going to auto-create {} collection", SYSTEM_COLL);
SolrQueryResponse rsp = new SolrQueryResponse();
String repFactor = String.valueOf(Math.min(3, cores.getZkController().getClusterState().getLiveNodes().size()));
cores.getCollectionsHandler().handleRequestBody(new LocalSolrQueryRequest(null,
new ModifiableSolrParams()
.add(ACTION, CREATE.toString())
.add( NAME, SYSTEM_COLL)
.add(REPLICATION_FACTOR, repFactor)), rsp);
if (rsp.getValues().get("success") == null) {
throw new SolrException(ErrorCode.SERVER_ERROR, "Could not auto-create " + SYSTEM_COLL + " collection: "+ Utils.toJSONString(rsp.getValues()));
}
TimeOut timeOut = new TimeOut(3, TimeUnit.SECONDS, TimeSource.NANO_TIME);
for (; ; ) {
if (cores.getZkController().getClusterState().getCollectionOrNull(SYSTEM_COLL) != null) {
break;
} else {
if (timeOut.hasTimedOut()) {
throw new SolrException(ErrorCode.SERVER_ERROR, "Could not find " + SYSTEM_COLL + " collection even after 3 seconds");
}
timeOut.sleep(50);
}
}
action = RETRY;
}
}
/**
* Resolves the parameter as a potential comma delimited list of collections, and resolves aliases too.
* One level of aliases pointing to another alias is supported.
* De-duplicates and retains the order.
* {@link #getCollectionsList()}
*/
protected List<String> resolveCollectionListOrAlias(String collectionStr) {
if (collectionStr == null || collectionStr.trim().isEmpty()) {
return Collections.emptyList();
}
List<String> result = null;
LinkedHashSet<String> uniqueList = null;
Aliases aliases = getAliases();
List<String> inputCollections = StrUtils.splitSmart(collectionStr, ",", true);
if (inputCollections.size() > 1) {
uniqueList = new LinkedHashSet<>();
}
for (String inputCollection : inputCollections) {
List<String> resolvedCollections = aliases.resolveAliases(inputCollection);
if (uniqueList != null) {
uniqueList.addAll(resolvedCollections);
} else {
result = resolvedCollections;
}
}
if (uniqueList != null) {
return new ArrayList<>(uniqueList);
} else {
return result;
}
}
/**
* Extract handler from the URL path if not set.
*/
protected void extractHandlerFromURLPath(SolrRequestParsers parser) throws Exception {
if (handler == null && path.length() > 1) { // don't match "" or "/" as valid path
handler = core.getRequestHandler(path);
if (handler == null) {
//may be a restlet path
// Handle /schema/* paths via Restlet
if (path.equals("/schema") || path.startsWith("/schema/")) {
solrReq = parser.parse(core, path, req);
SolrRequestInfo.setRequestInfo(new SolrRequestInfo(solrReq, new SolrQueryResponse()));
mustClearSolrRequestInfo = true;
if (path.equals(req.getServletPath())) {
// avoid endless loop - pass through to Restlet via webapp
action = PASSTHROUGH;
} else {
// forward rewritten URI (without path prefix and core/collection name) to Restlet
action = FORWARD;
}
SolrRequestInfo.getRequestInfo().setAction(action);
return;
}
}
// no handler yet but <requestDispatcher> allows us to handle /select with a 'qt' param
if (handler == null && parser.isHandleSelect()) {
if ("/select".equals(path) || "/select/".equals(path)) {
solrReq = parser.parse(core, path, req);
String qt = solrReq.getParams().get(CommonParams.QT);
handler = core.getRequestHandler(qt);
if (handler == null) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "unknown handler: " + qt);
}
if (qt != null && qt.startsWith("/") && (handler instanceof ContentStreamHandlerBase)) {
//For security reasons it's a bad idea to allow a leading '/', ex: /select?qt=/update see SOLR-3161
//There was no restriction from Solr 1.4 thru 3.5 and it's not supported for update handlers.
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Invalid Request Handler ('qt'). Do not use /select to access: " + qt);
}
}
}
}
}
protected void extractRemotePath(String collectionName, String origCorename) throws UnsupportedEncodingException, KeeperException, InterruptedException, SolrException {
assert core == null;
coreUrl = getRemoteCoreUrl(collectionName, origCorename);
// don't proxy for internal update requests
invalidStates = checkStateVersionsAreValid(queryParams.get(CloudSolrClient.STATE_VERSION));
if (coreUrl != null
&& queryParams.get(DistributingUpdateProcessorFactory.DISTRIB_UPDATE_PARAM) == null) {
if (invalidStates != null) {
//it does not make sense to send the request to a remote node
throw new SolrException(SolrException.ErrorCode.INVALID_STATE, new String(Utils.toJSON(invalidStates), org.apache.lucene.util.IOUtils.UTF_8));
}
action = REMOTEQUERY;
} else {
if (!retry) {
// we couldn't find a core to work with, try reloading aliases & this collection
cores.getZkController().getZkStateReader().aliasesManager.update();
cores.getZkController().zkStateReader.forceUpdateCollection(collectionName);
action = RETRY;
}
}
}
Action authorize() throws IOException {
AuthorizationContext context = getAuthCtx();
log.debug("AuthorizationContext : {}", context);
AuthorizationResponse authResponse = cores.getAuthorizationPlugin().authorize(context);
int statusCode = authResponse.statusCode;
if (statusCode == AuthorizationResponse.PROMPT.statusCode) {
@SuppressWarnings({"unchecked"})
Map<String, String> headers = (Map) getReq().getAttribute(AuthenticationPlugin.class.getName());
if (headers != null) {
for (Map.Entry<String, String> e : headers.entrySet()) response.setHeader(e.getKey(), e.getValue());
}
if (log.isDebugEnabled()) {
log.debug("USER_REQUIRED {} {}", req.getHeader("Authorization"), req.getUserPrincipal());
}
sendError(statusCode,
"Authentication failed, Response code: " + statusCode);
if (shouldAudit(EventType.REJECTED)) {
cores.getAuditLoggerPlugin().doAudit(new AuditEvent(EventType.REJECTED, req, context));
}
return RETURN;
}
if (statusCode == AuthorizationResponse.FORBIDDEN.statusCode) {
if (log.isDebugEnabled()) {
log.debug("UNAUTHORIZED auth header {} context : {}, msg: {}", req.getHeader("Authorization"), context, authResponse.getMessage()); // logOk
}
sendError(statusCode,
"Unauthorized request, Response code: " + statusCode);
if (shouldAudit(EventType.UNAUTHORIZED)) {
cores.getAuditLoggerPlugin().doAudit(new AuditEvent(EventType.UNAUTHORIZED, req, context));
}
return RETURN;
}
if (!(statusCode == HttpStatus.SC_ACCEPTED) && !(statusCode == HttpStatus.SC_OK)) {
log.warn("ERROR {} during authentication: {}", statusCode, authResponse.getMessage()); // logOk
sendError(statusCode,
"ERROR during authorization, Response code: " + statusCode);
if (shouldAudit(EventType.ERROR)) {
cores.getAuditLoggerPlugin().doAudit(new AuditEvent(EventType.ERROR, req, context));
}
return RETURN;
}
if (shouldAudit(EventType.AUTHORIZED)) {
cores.getAuditLoggerPlugin().doAudit(new AuditEvent(EventType.AUTHORIZED, req, context));
}
return null;
}
/**
* This method processes the request.
*/
public Action call() throws IOException {
MDCLoggingContext.reset();
Span activeSpan = GlobalTracer.getTracer().activeSpan();
if (activeSpan != null) {
MDCLoggingContext.setTracerId(activeSpan.context().toTraceId());
}
MDCLoggingContext.setNode(cores);
if (cores == null) {
sendError(503, "Server is shutting down or failed to initialize");
return RETURN;
}
if (solrDispatchFilter.abortErrorMessage != null) {
sendError(500, solrDispatchFilter.abortErrorMessage);
if (shouldAudit(EventType.ERROR)) {
cores.getAuditLoggerPlugin().doAudit(new AuditEvent(EventType.ERROR, getReq()));
}
return RETURN;
}
try {
init();
// Perform authorization here, if:
// (a) Authorization is enabled, and
// (b) The requested resource is not a known static file
// (c) And this request should be handled by this node (see NOTE below)
// NOTE: If the query is to be handled by another node, then let that node do the authorization.
// In case of authentication using BasicAuthPlugin, for example, the internode request
// is secured using PKI authentication and the internode request here will contain the
// original user principal as a payload/header, using which the receiving node should be
// able to perform the authorization.
if (cores.getAuthorizationPlugin() != null && shouldAuthorize()
&& !(action == REMOTEQUERY || action == FORWARD)) {
Action authorizationAction = authorize();
if (authorizationAction != null) return authorizationAction;
}
HttpServletResponse resp = response;
switch (action) {
case ADMIN:
handleAdminRequest();
return RETURN;
case REMOTEQUERY:
SolrRequestInfo.setRequestInfo(new SolrRequestInfo(req, new SolrQueryResponse(), action));
mustClearSolrRequestInfo = true;
remoteQuery(coreUrl + path, resp);
return RETURN;
case PROCESS:
final Method reqMethod = Method.getMethod(req.getMethod());
HttpCacheHeaderUtil.setCacheControlHeader(config, resp, reqMethod);
// unless we have been explicitly told not to, do cache validation
// if we fail cache validation, execute the query
if (config.getHttpCachingConfig().isNever304() ||
!HttpCacheHeaderUtil.doCacheHeaderValidation(solrReq, req, reqMethod, resp)) {
SolrQueryResponse solrRsp = new SolrQueryResponse();
/* even for HEAD requests, we need to execute the handler to
* ensure we don't get an error (and to make sure the correct
* QueryResponseWriter is selected and we get the correct
* Content-Type)
*/
SolrRequestInfo.setRequestInfo(new SolrRequestInfo(solrReq, solrRsp, action));
mustClearSolrRequestInfo = true;
execute(solrRsp);
if (shouldAudit()) {
EventType eventType = solrRsp.getException() == null ? EventType.COMPLETED : EventType.ERROR;
if (shouldAudit(eventType)) {
cores.getAuditLoggerPlugin().doAudit(
new AuditEvent(eventType, req, getAuthCtx(), solrReq.getRequestTimer().getTime(), solrRsp.getException()));
}
}
HttpCacheHeaderUtil.checkHttpCachingVeto(solrRsp, resp, reqMethod);
Iterator<Map.Entry<String, String>> headers = solrRsp.httpHeaders();
while (headers.hasNext()) {
Map.Entry<String, String> entry = headers.next();
resp.addHeader(entry.getKey(), entry.getValue());
}
QueryResponseWriter responseWriter = getResponseWriter();
if (invalidStates != null) solrReq.getContext().put(CloudSolrClient.STATE_VERSION, invalidStates);
writeResponse(solrRsp, responseWriter, reqMethod);
}
return RETURN;
default: return action;
}
} catch (Throwable ex) {
if (shouldAudit(EventType.ERROR)) {
cores.getAuditLoggerPlugin().doAudit(new AuditEvent(EventType.ERROR, ex, req));
}
sendError(ex);
// walk the entire cause chain to search for an Error
Throwable t = ex;
while (t != null) {
if (t instanceof Error) {
if (t != ex) {
log.error("An Error was wrapped in another exception - please report complete stacktrace on SOLR-6161", ex);
}
throw (Error) t;
}
t = t.getCause();
}
return RETURN;
}
}
private boolean shouldAudit() {
return cores.getAuditLoggerPlugin() != null;
}
private boolean shouldAudit(AuditEvent.EventType eventType) {
return shouldAudit() && cores.getAuditLoggerPlugin().shouldLog(eventType);
}
private boolean shouldAuthorize() {
if(PublicKeyHandler.PATH.equals(path)) return false;
//admin/info/key is the path where public key is exposed . it is always unsecured
if ("/".equals(path) || "/solr/".equals(path)) return false; // Static Admin UI files must always be served
if (cores.getPkiAuthenticationPlugin() != null && req.getUserPrincipal() != null) {
boolean b = cores.getPkiAuthenticationPlugin().needsAuthorization(req);
log.debug("PkiAuthenticationPlugin says authorization required : {} ", b);
return b;
}
return true;
}
void destroy() {
try {
if (solrReq != null) {
log.debug("Closing out SolrRequest: {}", solrReq);
solrReq.close();
}
} finally {
try {
if (core != null) core.close();
} finally {
if (mustClearSolrRequestInfo) {
SolrRequestInfo.clearRequestInfo();
}
}
AuthenticationPlugin authcPlugin = cores.getAuthenticationPlugin();
if (authcPlugin != null) authcPlugin.closeRequest();
}
}
//TODO using Http2Client
private void remoteQuery(String coreUrl, HttpServletResponse resp) throws IOException {
HttpRequestBase method;
HttpEntity httpEntity = null;
ModifiableSolrParams updatedQueryParams = new ModifiableSolrParams(queryParams);
int forwardCount = queryParams.getInt(INTERNAL_REQUEST_COUNT, 0) + 1;
updatedQueryParams.set(INTERNAL_REQUEST_COUNT, forwardCount);
String queryStr = updatedQueryParams.toQueryString();
try {
String urlstr = coreUrl + queryStr;
boolean isPostOrPutRequest = "POST".equals(req.getMethod()) || "PUT".equals(req.getMethod());
if ("GET".equals(req.getMethod())) {
method = new HttpGet(urlstr);
} else if ("HEAD".equals(req.getMethod())) {
method = new HttpHead(urlstr);
} else if (isPostOrPutRequest) {
HttpEntityEnclosingRequestBase entityRequest =
"POST".equals(req.getMethod()) ? new HttpPost(urlstr) : new HttpPut(urlstr);
InputStream in = req.getInputStream();
HttpEntity entity = new InputStreamEntity(in, req.getContentLength());
entityRequest.setEntity(entity);
method = entityRequest;
} else if ("DELETE".equals(req.getMethod())) {
method = new HttpDelete(urlstr);
} else if ("OPTIONS".equals(req.getMethod())) {
method = new HttpOptions(urlstr);
} else {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"Unexpected method type: " + req.getMethod());
}
for (Enumeration<String> e = req.getHeaderNames(); e.hasMoreElements(); ) {
String headerName = e.nextElement();
if (!"host".equalsIgnoreCase(headerName)
&& !"authorization".equalsIgnoreCase(headerName)
&& !"accept".equalsIgnoreCase(headerName)) {
method.addHeader(headerName, req.getHeader(headerName));
}
}
// These headers not supported for HttpEntityEnclosingRequests
if (method instanceof HttpEntityEnclosingRequest) {
method.removeHeaders(TRANSFER_ENCODING_HEADER);
method.removeHeaders(CONTENT_LENGTH_HEADER);
}
final HttpResponse response
= solrDispatchFilter.httpClient.execute(method, HttpClientUtil.createNewHttpClientRequestContext());
int httpStatus = response.getStatusLine().getStatusCode();
httpEntity = response.getEntity();
resp.setStatus(httpStatus);
for (HeaderIterator responseHeaders = response.headerIterator(); responseHeaders.hasNext(); ) {
Header header = responseHeaders.nextHeader();
// We pull out these two headers below because they can cause chunked
// encoding issues with Tomcat
if (header != null && !header.getName().equalsIgnoreCase(TRANSFER_ENCODING_HEADER)
&& !header.getName().equalsIgnoreCase(CONNECTION_HEADER)) {
// NOTE: explicitly using 'setHeader' instead of 'addHeader' so that
// the remote nodes values for any response headers will overide any that
// may have already been set locally (ex: by the local jetty's RewriteHandler config)
resp.setHeader(header.getName(), header.getValue());
}
}
if (httpEntity != null) {
if (httpEntity.getContentEncoding() != null)
resp.setHeader(httpEntity.getContentEncoding().getName(), httpEntity.getContentEncoding().getValue());
if (httpEntity.getContentType() != null) resp.setContentType(httpEntity.getContentType().getValue());
InputStream is = httpEntity.getContent();
OutputStream os = resp.getOutputStream();
IOUtils.copyLarge(is, os);
}
} catch (IOException e) {
sendError(new SolrException(
SolrException.ErrorCode.SERVER_ERROR,
"Error trying to proxy request for url: " + coreUrl + " with _forwardCount: " + forwardCount, e));
} finally {
Utils.consumeFully(httpEntity);
}
}
protected void sendError(Throwable ex) throws IOException {
Exception exp = null;
SolrCore localCore = null;
try {
SolrQueryResponse solrResp = new SolrQueryResponse();
if (ex instanceof Exception) {
solrResp.setException((Exception) ex);
} else {
solrResp.setException(new RuntimeException(ex));
}
localCore = core;
if (solrReq == null) {
final SolrParams solrParams;
if (req != null) {
// use GET parameters if available:
solrParams = SolrRequestParsers.parseQueryString(req.getQueryString());
} else {
// we have no params at all, use empty ones:
solrParams = new MapSolrParams(Collections.emptyMap());
}
solrReq = new SolrQueryRequestBase(core, solrParams) {
};
}
QueryResponseWriter writer = getResponseWriter();
writeResponse(solrResp, writer, Method.GET);
} catch (Exception e) { // This error really does not matter
exp = e;
} finally {
try {
if (exp != null) {
@SuppressWarnings({"rawtypes"})
SimpleOrderedMap info = new SimpleOrderedMap();
int code = ResponseUtils.getErrorInfo(ex, info, log);
sendError(code, info.toString());
}
} finally {
if (core == null && localCore != null) {
localCore.close();
}
}
}
}
protected void sendError(int code, String message) throws IOException {
try {
response.sendError(code, message);
} catch (EOFException e) {
log.info("Unable to write error response, client closed connection or we are shutting down", e);
}
}
protected void execute(SolrQueryResponse rsp) {
// a custom filter could add more stuff to the request before passing it on.
// for example: sreq.getContext().put( "HttpServletRequest", req );
// used for logging query stats in SolrCore.execute()
solrReq.getContext().put("webapp", req.getContextPath());
solrReq.getCore().execute(handler, solrReq, rsp);
}
private void handleAdminRequest() throws IOException {
SolrQueryResponse solrResp = new SolrQueryResponse();
SolrCore.preDecorateResponse(solrReq, solrResp);
handleAdmin(solrResp);
SolrCore.postDecorateResponse(handler, solrReq, solrResp);
if (solrResp.getToLog().size() > 0) {
if (log.isInfoEnabled()) { // has to come second and in it's own if to keep ./gradlew check happy.
log.info(handler != null ? MarkerFactory.getMarker(handler.getClass().getName()) : MarkerFactory.getMarker(HttpSolrCall.class.getName()), solrResp.getToLogAsString("[admin]"));
}
}
QueryResponseWriter respWriter = SolrCore.DEFAULT_RESPONSE_WRITERS.get(solrReq.getParams().get(CommonParams.WT));
if (respWriter == null) respWriter = getResponseWriter();
writeResponse(solrResp, respWriter, Method.getMethod(req.getMethod()));
if (shouldAudit()) {
EventType eventType = solrResp.getException() == null ? EventType.COMPLETED : EventType.ERROR;
if (shouldAudit(eventType)) {
cores.getAuditLoggerPlugin().doAudit(
new AuditEvent(eventType, req, getAuthCtx(), solrReq.getRequestTimer().getTime(), solrResp.getException()));
}
}
}
/**
* Returns {@link QueryResponseWriter} to be used.
* When {@link CommonParams#WT} not specified in the request or specified value doesn't have
* corresponding {@link QueryResponseWriter} then, returns the default query response writer
* Note: This method must not return null
*/
protected QueryResponseWriter getResponseWriter() {
String wt = solrReq.getParams().get(CommonParams.WT);
if (core != null) {
return core.getQueryResponseWriter(wt);
} else {
return SolrCore.DEFAULT_RESPONSE_WRITERS.getOrDefault(wt,
SolrCore.DEFAULT_RESPONSE_WRITERS.get("standard"));
}
}
protected void handleAdmin(SolrQueryResponse solrResp) {
handler.handleRequest(solrReq, solrResp);
}
/**
* Sets the "collection" parameter on the request to the list of alias-resolved collections for this request.
* It can be avoided sometimes.
* Note: {@link org.apache.solr.handler.component.HttpShardHandler} processes this param.
* @see #getCollectionsList()
*/
protected void addCollectionParamIfNeeded(List<String> collections) {
if (collections.isEmpty()) {
return;
}
assert cores.isZooKeeperAware();
String collectionParam = queryParams.get(COLLECTION_PROP);
// if there is no existing collection param and the core we go to is for the expected collection,
// then we needn't add a collection param
if (collectionParam == null && // if collection param already exists, we may need to over-write it
core != null && collections.equals(Collections.singletonList(core.getCoreDescriptor().getCollectionName()))) {
return;
}
String newCollectionParam = StrUtils.join(collections, ',');
if (newCollectionParam.equals(collectionParam)) {
return;
}
// TODO add a SolrRequest.getModifiableParams ?
ModifiableSolrParams params = new ModifiableSolrParams(solrReq.getParams());
params.set(COLLECTION_PROP, newCollectionParam);
solrReq.setParams(params);
}
private void writeResponse(SolrQueryResponse solrRsp, QueryResponseWriter responseWriter, Method reqMethod)
throws IOException {
try {
Object invalidStates = solrReq.getContext().get(CloudSolrClient.STATE_VERSION);
//This is the last item added to the response and the client would expect it that way.
//If that assumption is changed , it would fail. This is done to avoid an O(n) scan on
// the response for each request
if (invalidStates != null) solrRsp.add(CloudSolrClient.STATE_VERSION, invalidStates);
// Now write it out
final String ct = responseWriter.getContentType(solrReq, solrRsp);
// don't call setContentType on null
if (null != ct) response.setContentType(ct);
if (solrRsp.getException() != null) {
@SuppressWarnings({"rawtypes"})
NamedList info = new SimpleOrderedMap();
int code = ResponseUtils.getErrorInfo(solrRsp.getException(), info, log);
solrRsp.add("error", info);
response.setStatus(code);
}
if (Method.HEAD != reqMethod) {
OutputStream out = response.getOutputStream();
QueryResponseWriterUtil.writeQueryResponse(out, responseWriter, solrReq, solrRsp, ct);
}
//else http HEAD request, nothing to write out, waited this long just to get ContentType
} catch (EOFException e) {
log.info("Unable to write response, client closed connection or we are shutting down", e);
}
}
/** Returns null if the state ({@link CloudSolrClient#STATE_VERSION}) is good; otherwise returns state problems. */
private Map<String, Integer> checkStateVersionsAreValid(String stateVer) {
Map<String, Integer> result = null;
String[] pairs;
if (stateVer != null && !stateVer.isEmpty() && cores.isZooKeeperAware()) {
// many have multiple collections separated by |
pairs = StringUtils.split(stateVer, '|');
for (String pair : pairs) {
String[] pcs = StringUtils.split(pair, ':');
if (pcs.length == 2 && !pcs[0].isEmpty() && !pcs[1].isEmpty()) {
Integer status = cores.getZkController().getZkStateReader().compareStateVersions(pcs[0], Integer.parseInt(pcs[1]));
if (status != null) {
if (result == null) result = new HashMap<>();
result.put(pcs[0], status);
}
}
}
}
return result;
}
protected SolrCore getCoreByCollection(String collectionName, boolean isPreferLeader) {
ZkStateReader zkStateReader = cores.getZkController().getZkStateReader();
ClusterState clusterState = zkStateReader.getClusterState();
DocCollection collection = clusterState.getCollectionOrNull(collectionName, true);
if (collection == null) {
return null;
}
Set<String> liveNodes = clusterState.getLiveNodes();
if (isPreferLeader) {
List<Replica> leaderReplicas = collection.getLeaderReplicas(cores.getZkController().getNodeName());
SolrCore core = randomlyGetSolrCore(liveNodes, leaderReplicas);
if (core != null) return core;
}
List<Replica> replicas = collection.getReplicas(cores.getZkController().getNodeName());
return randomlyGetSolrCore(liveNodes, replicas);
}
private SolrCore randomlyGetSolrCore(Set<String> liveNodes, List<Replica> replicas) {
if (replicas != null) {
RandomIterator<Replica> it = new RandomIterator<>(random, replicas);
while (it.hasNext()) {
Replica replica = it.next();
if (liveNodes.contains(replica.getNodeName()) && replica.getState() == Replica.State.ACTIVE) {
SolrCore core = checkProps(replica);
if (core != null) return core;
}
}
}
return null;
}
private SolrCore checkProps(ZkNodeProps zkProps) {
String corename;
SolrCore core = null;
if (cores.getZkController().getNodeName().equals(zkProps.getStr(NODE_NAME_PROP))) {
corename = zkProps.getStr(CORE_NAME_PROP);
core = cores.getCore(corename);
}
return core;
}
private void getSlicesForCollections(ClusterState clusterState,
Collection<Slice> slices, boolean activeSlices) {
if (activeSlices) {
for (Map.Entry<String, DocCollection> entry : clusterState.getCollectionsMap().entrySet()) {
final Slice[] activeCollectionSlices = entry.getValue().getActiveSlicesArr();
if (activeCollectionSlices != null) {
Collections.addAll(slices, activeCollectionSlices);
}
}
} else {
for (Map.Entry<String, DocCollection> entry : clusterState.getCollectionsMap().entrySet()) {
final Collection<Slice> collectionSlices = entry.getValue().getSlices();
if (collectionSlices != null) {
slices.addAll(collectionSlices);
}
}
}
}
protected String getRemoteCoreUrl(String collectionName, String origCorename) throws SolrException {
ClusterState clusterState = cores.getZkController().getClusterState();
final DocCollection docCollection = clusterState.getCollectionOrNull(collectionName);
Slice[] slices = (docCollection != null) ? docCollection.getActiveSlicesArr() : null;
List<Slice> activeSlices = new ArrayList<>();
boolean byCoreName = false;
int totalReplicas = 0;
if (slices == null) {
byCoreName = true;
activeSlices = new ArrayList<>();
getSlicesForCollections(clusterState, activeSlices, true);
if (activeSlices.isEmpty()) {
getSlicesForCollections(clusterState, activeSlices, false);
}
} else {
Collections.addAll(activeSlices, slices);
}
for (Slice s: activeSlices) {
totalReplicas += s.getReplicas().size();
}
if (activeSlices.isEmpty()) {
return null;
}
// XXX (ab) most likely this is not needed? it seems all code paths
// XXX already make sure the collectionName is on the list
if (!collectionsList.contains(collectionName)) {
collectionsList = new ArrayList<>(collectionsList);
collectionsList.add(collectionName);
}
// Avoid getting into a recursive loop of requests being forwarded by
// stopping forwarding and erroring out after (totalReplicas) forwards
if (queryParams.getInt(INTERNAL_REQUEST_COUNT, 0) > totalReplicas){
throw new SolrException(SolrException.ErrorCode.INVALID_STATE,
"No active replicas found for collection: " + collectionName);
}
String coreUrl = getCoreUrl(collectionName, origCorename, clusterState,
activeSlices, byCoreName, true);
if (coreUrl == null) {
coreUrl = getCoreUrl(collectionName, origCorename, clusterState,
activeSlices, byCoreName, false);
}
return coreUrl;
}
private String getCoreUrl(String collectionName,
String origCorename, ClusterState clusterState, List<Slice> slices,
boolean byCoreName, boolean activeReplicas) {
String coreUrl;
Set<String> liveNodes = clusterState.getLiveNodes();
Collections.shuffle(slices, random);
for (Slice slice : slices) {
List<Replica> randomizedReplicas = new ArrayList<>(slice.getReplicas());
Collections.shuffle(randomizedReplicas, random);
for (Replica replica : randomizedReplicas) {
if (!activeReplicas || (liveNodes.contains(replica.getNodeName())
&& replica.getState() == Replica.State.ACTIVE)) {
if (byCoreName && !origCorename.equals(replica.getStr(CORE_NAME_PROP))) {
// if it's by core name, make sure they match
continue;
}
if (replica.getStr(BASE_URL_PROP).equals(cores.getZkController().getBaseUrl())) {
// don't count a local core
continue;
}
if (origCorename != null) {
coreUrl = replica.getStr(BASE_URL_PROP) + "/" + origCorename;
} else {
coreUrl = replica.getCoreUrl();
if (coreUrl.endsWith("/")) {
coreUrl = coreUrl.substring(0, coreUrl.length() - 1);
}
}
return coreUrl;
}
}
}
return null;
}
protected Object _getHandler(){
return handler;
}
private AuthorizationContext getAuthCtx() {
String resource = getPath();
SolrParams params = getQueryParams();
final ArrayList<CollectionRequest> collectionRequests = new ArrayList<>();
for (String collection : getCollectionsList()) {
collectionRequests.add(new CollectionRequest(collection));
}
// Extract collection name from the params in case of a Collection Admin request
if (getPath().equals("/admin/collections")) {
if (CREATE.isEqual(params.get("action"))||
RELOAD.isEqual(params.get("action"))||
DELETE.isEqual(params.get("action")))
collectionRequests.add(new CollectionRequest(params.get("name")));
else if (params.get(COLLECTION_PROP) != null)
collectionRequests.add(new CollectionRequest(params.get(COLLECTION_PROP)));
}
// Populate the request type if the request is select or update
if(requestType == RequestType.UNKNOWN) {
if(resource.startsWith("/select") || resource.startsWith("/get"))
requestType = RequestType.READ;
if(resource.startsWith("/update"))
requestType = RequestType.WRITE;
}
return new AuthorizationContext() {
@Override
public SolrParams getParams() {
return null == solrReq ? null : solrReq.getParams();
}
@Override
public Principal getUserPrincipal() {
return getReq().getUserPrincipal();
}
@Override
public String getUserName() {
return getReq().getRemoteUser();
}
@Override
public String getHttpHeader(String s) {
return getReq().getHeader(s);
}
@Override
public Enumeration<String> getHeaderNames() {
return getReq().getHeaderNames();
}
@Override
public List<CollectionRequest> getCollectionRequests() {
return collectionRequests;
}
@Override
public RequestType getRequestType() {
return requestType;
}
public String getResource() {
return path;
}
@Override
public String getHttpMethod() {
return getReq().getMethod();
}
@Override
public Object getHandler() {
return _getHandler();
}
@Override
public String toString() {
StringBuilder response = new StringBuilder("userPrincipal: [").append(getUserPrincipal()).append("]")
.append(" type: [").append(requestType.toString()).append("], collections: [");
for (CollectionRequest collectionRequest : collectionRequests) {
response.append(collectionRequest.collectionName).append(", ");
}
if(collectionRequests.size() > 0)
response.delete(response.length() - 1, response.length());
response.append("], Path: [").append(resource).append("]");
response.append(" path : ").append(path).append(" params :").append(getParams());
return response.toString();
}
@Override
public String getRemoteAddr() {
return getReq().getRemoteAddr();
}
@Override
public String getRemoteHost() {
return getReq().getRemoteHost();
}
};
}
static final String CONNECTION_HEADER = "Connection";
static final String TRANSFER_ENCODING_HEADER = "Transfer-Encoding";
static final String CONTENT_LENGTH_HEADER = "Content-Length";
List<CommandOperation> parsedCommands;
public List<CommandOperation> getCommands(boolean validateInput) {
if (parsedCommands == null) {
Iterable<ContentStream> contentStreams = solrReq.getContentStreams();
if (contentStreams == null) parsedCommands = Collections.emptyList();
else {
parsedCommands = ApiBag.getCommandOperations(contentStreams.iterator().next(), getValidators(), validateInput);
}
}
return CommandOperation.clone(parsedCommands);
}
protected ValidatingJsonMap getSpec() {
return null;
}
@SuppressWarnings({"unchecked"})
protected Map<String, JsonSchemaValidator> getValidators(){
return Collections.EMPTY_MAP;
}
/**
* A faster method for randomly picking items when you do not need to
* consume all items.
*/
private static class RandomIterator<E> implements Iterator<E> {
private Random rand;
private ArrayList<E> elements;
private int size;
public RandomIterator(Random rand, Collection<E> elements) {
this.rand = rand;
this.elements = new ArrayList<>(elements);
this.size = elements.size();
}
@Override
public boolean hasNext() {
return size > 0;
}
@Override
public E next() {
int idx = rand.nextInt(size);
E e1 = elements.get(idx);
E e2 = elements.get(size-1);
elements.set(idx,e2);
size--;
return e1;
}
}
}
| 1 | 37,483 | What does our source validation complain about here? Many of the logok/nowarn places look fine to me at a glance but I'm no match for the logging policeman ;-) | apache-lucene-solr | java |
@@ -22,14 +22,17 @@ import (
"strconv"
"time"
+ "github.com/mysteriumnetwork/node/client/stats"
"github.com/mysteriumnetwork/node/openvpn/management"
)
// SessionStatsHandler is invoked when middleware receives statistics
-type SessionStatsHandler func(SessionStats) error
+type SessionStatsHandler func(stats.SessionStats) error
const byteCountCommandTemplate = "bytecount %d"
+var rule = regexp.MustCompile("^>BYTECOUNT:(.*),(.*)$")
+
type middleware struct {
sessionStatsHandler SessionStatsHandler
interval time.Duration | 1 | /*
* Copyright (C) 2017 The "MysteriumNetwork/node" Authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package bytescount
import (
"regexp"
"strconv"
"time"
"github.com/mysteriumnetwork/node/openvpn/management"
)
// SessionStatsHandler is invoked when middleware receives statistics
type SessionStatsHandler func(SessionStats) error
const byteCountCommandTemplate = "bytecount %d"
type middleware struct {
sessionStatsHandler SessionStatsHandler
interval time.Duration
}
// NewMiddleware returns new bytescount middleware
func NewMiddleware(sessionStatsHandler SessionStatsHandler, interval time.Duration) management.Middleware {
return &middleware{
sessionStatsHandler: sessionStatsHandler,
interval: interval,
}
}
func (middleware *middleware) Start(commandWriter management.CommandWriter) error {
_, err := commandWriter.SingleLineCommand(byteCountCommandTemplate, int(middleware.interval.Seconds()))
return err
}
func (middleware *middleware) Stop(commandWriter management.CommandWriter) error {
_, err := commandWriter.SingleLineCommand(byteCountCommandTemplate, 0)
return err
}
func (middleware *middleware) ConsumeLine(line string) (consumed bool, err error) {
rule, err := regexp.Compile("^>BYTECOUNT:(.*),(.*)$")
if err != nil {
return
}
match := rule.FindStringSubmatch(line)
consumed = len(match) > 0
if !consumed {
return
}
bytesIn, err := strconv.Atoi(match[1])
if err != nil {
return
}
bytesOut, err := strconv.Atoi(match[2])
if err != nil {
return
}
stats := SessionStats{BytesSent: bytesOut, BytesReceived: bytesIn}
err = middleware.sessionStatsHandler(stats)
return
}
| 1 | 11,740 | It feels like this dependency should not be here. Some deep internal openvpn package (middleware) knows about one of possible stats consumers. Maybe as an alternative, statistics and state callbacks can be extracted as separate interfaces in top openvpn package and reused by both sides | mysteriumnetwork-node | go |
@@ -1744,7 +1744,7 @@ func (fd *fileData) deepCopy(ctx context.Context, codec kbfscodec.Codec,
// Handle the single-level case first.
if !topBlock.IsInd {
- newTopBlock, err := topBlock.DeepCopy(codec)
+ newTopBlock := topBlock.DeepCopy()
if err != nil {
return zeroPtr, nil, err
} | 1 | // Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"fmt"
"time"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/kbfs/kbfsblock"
"github.com/keybase/kbfs/kbfscodec"
"github.com/keybase/kbfs/tlf"
"golang.org/x/net/context"
"golang.org/x/sync/errgroup"
)
// fileBlockGetter is a function that gets a block suitable for
// reading or writing, and also returns whether the block was already
// dirty. It may be called from new goroutines, and must handle any
// required locks accordingly.
type fileBlockGetter func(context.Context, KeyMetadata, BlockPointer,
path, blockReqType) (fblock *FileBlock, wasDirty bool, err error)
// dirtyBlockCacher writes dirty blocks to a cache.
type dirtyBlockCacher func(ptr BlockPointer, block Block) error
// fileData is a helper struct for accessing and manipulating data
// within a file. It's meant for use within a single scope, not for
// long-term storage. The caller must ensure goroutine-safety.
type fileData struct {
file path
uid keybase1.UID
crypto cryptoPure
kmd KeyMetadata
bsplit BlockSplitter
getter fileBlockGetter
cacher dirtyBlockCacher
log logger.Logger
}
func newFileData(file path, uid keybase1.UID, crypto cryptoPure,
bsplit BlockSplitter, kmd KeyMetadata, getter fileBlockGetter,
cacher dirtyBlockCacher, log logger.Logger) *fileData {
return &fileData{
file: file,
uid: uid,
crypto: crypto,
bsplit: bsplit,
kmd: kmd,
getter: getter,
cacher: cacher,
log: log,
}
}
// parentBlockAndChildIndex is a node on a path down the tree to a
// particular leaf node. `pblock` is an indirect block corresponding
// to one of that leaf node's parents, and `childIndex` is an index
// into `pblock.IPtrs` to the next node along the path.
type parentBlockAndChildIndex struct {
pblock *FileBlock
childIndex int
}
func (pbci parentBlockAndChildIndex) childIPtr() IndirectFilePtr {
return pbci.pblock.IPtrs[pbci.childIndex]
}
func (fd *fileData) rootBlockPointer() BlockPointer {
return fd.file.tailPointer()
}
// getFileBlockAtOffset returns the leaf block containing the given
// `off`, along with the set of indirect blocks leading to that leaf
// (if any).
func (fd *fileData) getFileBlockAtOffset(ctx context.Context,
topBlock *FileBlock, off int64, rtype blockReqType) (
ptr BlockPointer, parentBlocks []parentBlockAndChildIndex,
block *FileBlock, nextBlockStartOff, startOff int64,
wasDirty bool, err error) {
// Find the block matching the offset, if it exists.
ptr = fd.rootBlockPointer()
block = topBlock
nextBlockStartOff = -1
startOff = 0
if !topBlock.IsInd {
// If it's not an indirect block, we just need to figure out
// if it's dirty.
_, wasDirty, err = fd.getter(ctx, fd.kmd, ptr, fd.file, rtype)
if err != nil {
return zeroPtr, nil, nil, 0, 0, false, err
}
return ptr, nil, block, nextBlockStartOff, startOff, wasDirty, nil
}
// Search until it's not an indirect block.
for block.IsInd {
nextIndex := len(block.IPtrs) - 1
for i, iptr := range block.IPtrs {
if iptr.Off == off {
// Small optimization to avoid iterating past the correct ptr.
nextIndex = i
break
} else if iptr.Off > off {
// Use the previous block. i can never be 0, because
// the first ptr always has an offset at the beginning
// of the range.
nextIndex = i - 1
break
}
}
nextPtr := block.IPtrs[nextIndex]
parentBlocks = append(parentBlocks,
parentBlockAndChildIndex{block, nextIndex})
startOff = nextPtr.Off
// There is more to read if we ever took a path through a
// ptr that wasn't the final ptr in its respective list.
if nextIndex != len(block.IPtrs)-1 {
nextBlockStartOff = block.IPtrs[nextIndex+1].Off
}
ptr = nextPtr.BlockPointer
block, wasDirty, err = fd.getter(ctx, fd.kmd, ptr, fd.file, rtype)
if err != nil {
return zeroPtr, nil, nil, 0, 0, false, err
}
}
return ptr, parentBlocks, block, nextBlockStartOff, startOff, wasDirty, nil
}
// getNextDirtyFileBlockAtOffset returns the next dirty leaf block
// with a starting offset that is equal or greater than the given
// `off`. This assumes that any code that dirties a leaf block also
// dirties all of its parents, even if those parents haven't yet
// changed. It can be used iteratively (by feeding
// `nextBlockStartOff` back in as `off`) to find all the dirty blocks
// of the file. Note that there is no need to parallelize that
// process, since all the dirty blocks are guaranteed to be local.
func (fd *fileData) getNextDirtyFileBlockAtOffset(ctx context.Context,
topBlock *FileBlock, off int64, rtype blockReqType,
dirtyBcache DirtyBlockCache) (
ptr BlockPointer, parentBlocks []parentBlockAndChildIndex,
block *FileBlock, nextBlockStartOff, startOff int64,
err error) {
// Find the block matching the offset, if it exists.
ptr = fd.rootBlockPointer()
if !dirtyBcache.IsDirty(fd.file.Tlf, ptr, fd.file.Branch) {
// The top block isn't dirty, so we know none of the leaves
// are dirty.
return zeroPtr, nil, nil, 0, 0, nil
}
block = topBlock
nextBlockStartOff = -1
startOff = 0
// Search along paths of dirty blocks until we find a dirty leaf
// block with an offset equal or greater than `off`.
for block.IsInd {
index := -1
checkedPrevBlock := false
for i, iptr := range block.IPtrs {
if iptr.Off < off && i != len(block.IPtrs)-1 {
continue
}
// No need to check the previous block if we align exactly
// with `off`, or this is the right-most leaf block.
if iptr.Off <= off {
checkedPrevBlock = true
}
// If we haven't checked the previous block yet, do so now
// since it contains `off`.
if !checkedPrevBlock && i > 0 && dirtyBcache.IsDirty(
fd.file.Tlf, block.IPtrs[i-1].BlockPointer, fd.file.Branch) {
index = i - 1
break
}
checkedPrevBlock = true
// Now check the current block.
if dirtyBcache.IsDirty(
fd.file.Tlf, block.IPtrs[i].BlockPointer, fd.file.Branch) {
index = i
break
}
}
if index == -1 {
// There's no dirty block at or after `off`.
return zeroPtr, nil, nil, 0, 0, nil
}
iptr := block.IPtrs[index]
parentBlocks = append(parentBlocks,
parentBlockAndChildIndex{block, index})
startOff = iptr.Off
// There is more to read if we ever took a path through a
// ptr that wasn't the final ptr in its respective list.
if index != len(block.IPtrs)-1 {
nextBlockStartOff = block.IPtrs[index+1].Off
}
ptr = iptr.BlockPointer
block, _, err = fd.getter(ctx, fd.kmd, ptr, fd.file, rtype)
if err != nil {
return zeroPtr, nil, nil, 0, 0, err
}
}
// The leaf block doesn't cover this index. (If the contents
// length is 0, then this is the start or end of a hole, and it
// should still count as dirty.)
if len(block.Contents) > 0 && off >= startOff+int64(len(block.Contents)) {
return zeroPtr, nil, nil, -1, 0, nil
}
return ptr, parentBlocks, block, nextBlockStartOff, startOff, nil
}
// getBlocksForOffsetRange fetches all the blocks making up paths down
// the file tree to leaf ("direct") blocks that encompass the given
// offset range (half-inclusive) in the file. If `endOff` is -1, it
// returns blocks until reaching the end of the file. Note the range
// could be made up of holes, meaning that the last byte of a direct
// block doesn't immediately precede the first byte of the subsequent
// block. If `prefixOk` is true, the function will ignore context
// deadline errors and return whatever prefix of the data it could
// fetch within the deadine. Return params:
//
// * pathsFromRoot is a slice, ordered by file offset, of paths from
// the root to each block that makes up the range. If the path is
// empty, it indicates that pblock is a direct block and has no
// children.
// * blocks: a map from block pointer to a data-containing leaf node
// in the given range of offsets, if `getDirect` is true.
// * nextBlockOff is the offset of the block that follows the last
// block given in `pathsFromRoot`. If `pathsFromRoot` contains
// the last block among the children, nextBlockOff is -1.
func (fd *fileData) getBlocksForOffsetRange(ctx context.Context,
ptr BlockPointer, pblock *FileBlock, startOff, endOff int64,
prefixOk bool, getDirect bool) (pathsFromRoot [][]parentBlockAndChildIndex,
blocks map[BlockPointer]*FileBlock, nextBlockOffset int64, err error) {
if !pblock.IsInd {
// Return a single empty path, under the assumption that the
// caller already checked the range for this block.
if getDirect {
// Return a child map with only this block in it.
return [][]parentBlockAndChildIndex{nil},
map[BlockPointer]*FileBlock{ptr: pblock}, -1, nil
}
// Return an empty child map with no blocks in it (since
// getDirect is false).
return [][]parentBlockAndChildIndex{nil}, nil, -1, nil
}
type resp struct {
pathsFromRoot [][]parentBlockAndChildIndex
blocks map[BlockPointer]*FileBlock
nextBlockOffset int64
}
// Search all of the in-range child blocks, and their child
// blocks, etc, in parallel.
respChans := make([]<-chan resp, 0, len(pblock.IPtrs))
eg, groupCtx := errgroup.WithContext(ctx)
nextBlockOffsetThisLevel := int64(-1)
for i, iptr := range pblock.IPtrs {
// Some byte of this block is included in the left side of the
// range if `startOff` is less than the largest byte offset in
// the block.
inRangeLeft := true
if i < len(pblock.IPtrs)-1 {
inRangeLeft = startOff < pblock.IPtrs[i+1].Off
}
if !inRangeLeft {
continue
}
// Some byte of this block is included in the right side of
// the range if `endOff` is bigger than the smallest byte
// offset in the block (or if we're explicitly reading all the
// data to the end).
inRangeRight := endOff == -1 || endOff > iptr.Off
if !inRangeRight {
// This block is the first one past the offset range
// amount the children.
nextBlockOffsetThisLevel = iptr.Off
break
}
ptr := iptr.BlockPointer
childIndex := i
respCh := make(chan resp, 1)
respChans = append(respChans, respCh)
// Don't reference the uncaptured `i` or `iptr` variables below.
eg.Go(func() error {
var pfr [][]parentBlockAndChildIndex
var blocks map[BlockPointer]*FileBlock
var nextBlockOffset int64
// We only need to fetch direct blocks if we've been asked
// to do so.
if getDirect || ptr.DirectType != DirectBlock {
block, _, err := fd.getter(
groupCtx, fd.kmd, ptr, fd.file, blockReadParallel)
if err != nil {
return err
}
// Recurse down to the level of the child.
pfr, blocks, nextBlockOffset, err = fd.getBlocksForOffsetRange(
groupCtx, ptr, block, startOff, endOff, prefixOk, getDirect)
if err != nil {
return err
}
} else {
// We don't care about direct blocks, so leave the
// `blocks` map `nil`.
pfr = [][]parentBlockAndChildIndex{nil}
nextBlockOffset = -1
}
// Append self to the front of every path.
var r resp
for _, p := range pfr {
newPath := append([]parentBlockAndChildIndex{{
pblock: pblock,
childIndex: childIndex,
}}, p...)
r.pathsFromRoot = append(r.pathsFromRoot, newPath)
}
r.blocks = blocks
r.nextBlockOffset = nextBlockOffset
respCh <- r
return nil
})
}
err = eg.Wait()
// If we are ok with just getting the prefix, don't treat a
// deadline exceeded error as fatal.
if prefixOk && err == context.DeadlineExceeded {
err = nil
}
if err != nil {
return nil, nil, 0, err
}
blocks = make(map[BlockPointer]*FileBlock)
minNextBlockOffsetChild := int64(-1)
outer:
for _, respCh := range respChans {
select {
case r := <-respCh:
pathsFromRoot = append(pathsFromRoot, r.pathsFromRoot...)
for ptr, block := range r.blocks {
blocks[ptr] = block
}
// We want to find the leftmost block offset that's to the
// right of the range, the one immediately following the
// end of the range.
if r.nextBlockOffset != -1 &&
(minNextBlockOffsetChild == -1 ||
r.nextBlockOffset < minNextBlockOffsetChild) {
minNextBlockOffsetChild = r.nextBlockOffset
}
default:
// There should always be a response ready in every
// channel, unless prefixOk is true.
if prefixOk {
break outer
} else {
panic("No response ready when !prefixOk")
}
}
}
// If this level has no offset, or one of the children has an
// offset that's smaller than the one at this level, use the child
// offset instead.
if nextBlockOffsetThisLevel == -1 {
nextBlockOffset = minNextBlockOffsetChild
} else if minNextBlockOffsetChild != -1 &&
minNextBlockOffsetChild < nextBlockOffsetThisLevel {
nextBlockOffset = minNextBlockOffsetChild
} else {
nextBlockOffset = nextBlockOffsetThisLevel
}
return pathsFromRoot, blocks, nextBlockOffset, nil
}
func (fd *fileData) getLeafBlocksForOffsetRange(ctx context.Context,
ptr BlockPointer, pblock *FileBlock, startOff, endOff int64,
prefixOk bool) (pathsFromRoot [][]parentBlockAndChildIndex,
blocks map[BlockPointer]*FileBlock, nextBlockOffset int64, err error) {
return fd.getBlocksForOffsetRange(
ctx, ptr, pblock, startOff, endOff, prefixOk, true)
}
func (fd *fileData) getIndirectBlocksForOffsetRange(ctx context.Context,
pblock *FileBlock, startOff, endOff int64) (
pathsFromRoot [][]parentBlockAndChildIndex, err error) {
// Fetch the paths of indirect blocks, without getting the direct
// blocks.
pfr, _, _, err := fd.getBlocksForOffsetRange(
ctx, fd.rootBlockPointer(), pblock, startOff, endOff, false,
false /* no direct blocks */)
if err != nil {
return nil, err
}
return pfr, nil
}
// getByteSlicesInOffsetRange returns an ordered, continuous slice of
// byte ranges for the data described by the half-inclusive offset
// range `[startOff, endOff)`. If `endOff` == -1, it returns data to
// the end of the file. The caller is responsible for concatenating
// the data into a single buffer if desired. If `prefixOk` is true,
// the function will ignore context deadline errors and return
// whatever prefix of the data it could fetch within the deadine.
func (fd *fileData) getByteSlicesInOffsetRange(ctx context.Context,
startOff, endOff int64, prefixOk bool) ([][]byte, error) {
if startOff < 0 || endOff < -1 {
return nil, fmt.Errorf("Bad offset range [%d, %d)", startOff, endOff)
} else if endOff != -1 && endOff <= startOff {
return nil, nil
}
topBlock, _, err := fd.getter(ctx, fd.kmd, fd.rootBlockPointer(),
fd.file, blockRead)
if err != nil {
return nil, err
}
// Find all the indirect pointers to leaf blocks in the offset range.
var iptrs []IndirectFilePtr
firstBlockOff := int64(-1)
endBlockOff := int64(-1)
nextBlockOff := int64(-1)
var blockMap map[BlockPointer]*FileBlock
if topBlock.IsInd {
var pfr [][]parentBlockAndChildIndex
pfr, blockMap, nextBlockOff, err = fd.getLeafBlocksForOffsetRange(
ctx, fd.rootBlockPointer(), topBlock, startOff, endOff, prefixOk)
if err != nil {
return nil, err
}
for i, p := range pfr {
if len(p) == 0 {
return nil, fmt.Errorf("Unexpected empty path to child for "+
"file %v", fd.rootBlockPointer())
}
lowestAncestor := p[len(p)-1]
iptr := lowestAncestor.childIPtr()
iptrs = append(iptrs, iptr)
if firstBlockOff < 0 {
firstBlockOff = iptr.Off
}
if i == len(pfr)-1 {
leafBlock := blockMap[iptr.BlockPointer]
endBlockOff = iptr.Off + int64(len(leafBlock.Contents))
}
}
} else {
iptrs = []IndirectFilePtr{{
BlockInfo: BlockInfo{BlockPointer: fd.rootBlockPointer()},
Off: 0,
}}
firstBlockOff = 0
endBlockOff = int64(len(topBlock.Contents))
blockMap = map[BlockPointer]*FileBlock{fd.rootBlockPointer(): topBlock}
}
if len(iptrs) == 0 {
return nil, nil
}
nRead := int64(0)
n := endOff - startOff
if endOff == -1 {
n = endBlockOff - startOff
}
// Grab the relevant byte slices from each block described by the
// indirect pointer, filling in holes as needed.
var bytes [][]byte
for _, iptr := range iptrs {
block := blockMap[iptr.BlockPointer]
blockLen := int64(len(block.Contents))
nextByte := nRead + startOff
toRead := n - nRead
blockOff := iptr.Off
lastByteInBlock := blockOff + blockLen
if nextByte >= lastByteInBlock {
if nextBlockOff > 0 {
fill := nextBlockOff - nextByte
if fill > toRead {
fill = toRead
}
fd.log.CDebugf(ctx, "Read from hole: nextByte=%d "+
"lastByteInBlock=%d fill=%d", nextByte, lastByteInBlock,
fill)
if fill <= 0 {
fd.log.CErrorf(ctx,
"Read invalid file fill <= 0 while reading hole")
return nil, BadSplitError{}
}
bytes = append(bytes, make([]byte, fill))
nRead += fill
continue
}
return bytes, nil
} else if toRead > lastByteInBlock-nextByte {
toRead = lastByteInBlock - nextByte
}
// Check for holes in the middle of a file.
if nextByte < blockOff {
fill := blockOff - nextByte
bytes = append(bytes, make([]byte, fill))
nRead += fill
nextByte += fill
toRead -= fill
}
firstByteToRead := nextByte - blockOff
bytes = append(bytes,
block.Contents[firstByteToRead:toRead+firstByteToRead])
nRead += toRead
}
// If we didn't complete the read and there's another block, then
// we've hit another hole and need to add a fill.
if nRead < n && nextBlockOff > 0 {
toRead := n - nRead
nextByte := nRead + startOff
fill := nextBlockOff - nextByte
if fill > toRead {
fill = toRead
}
fd.log.CDebugf(ctx, "Read from hole at end of file: nextByte=%d "+
"fill=%d", nextByte, fill)
if fill <= 0 {
fd.log.CErrorf(ctx,
"Read invalid file fill <= 0 while reading hole")
return nil, BadSplitError{}
}
bytes = append(bytes, make([]byte, fill))
}
return bytes, nil
}
// The amount that the read timeout is smaller than the global one.
const readTimeoutSmallerBy = 2 * time.Second
// read fills the `dest` buffer with data from the file, starting at
// `startOff`. Returns the number of bytes copied. If the read
// operation nears the deadline set in `ctx`, it returns as big a
// prefix as possible before reaching the deadline.
func (fd *fileData) read(ctx context.Context, dest []byte, startOff int64) (
int64, error) {
if len(dest) == 0 {
return 0, nil
}
// If we have a large enough timeout add a temporary timeout that is
// readTimeoutSmallerBy. Use that for reading so short reads get returned
// upstream without triggering the global timeout.
now := time.Now()
deadline, haveTimeout := ctx.Deadline()
if haveTimeout {
rem := deadline.Sub(now) - readTimeoutSmallerBy
if rem > 0 {
var cancel func()
ctx, cancel = context.WithTimeout(ctx, rem)
defer cancel()
}
}
bytes, err := fd.getByteSlicesInOffsetRange(ctx, startOff,
startOff+int64(len(dest)), true)
if err != nil {
return 0, err
}
currLen := int64(0)
for _, b := range bytes {
bLen := int64(len(b))
copy(dest[currLen:currLen+bLen], b)
currLen += bLen
}
return currLen, nil
}
// getBytes returns a buffer containing data from the file, in the
// half-inclusive range `[startOff, endOff)`. If `endOff` == -1, it
// returns data until the end of the file.
func (fd *fileData) getBytes(ctx context.Context, startOff, endOff int64) (
data []byte, err error) {
bytes, err := fd.getByteSlicesInOffsetRange(ctx, startOff, endOff, false)
if err != nil {
return nil, err
}
bufSize := 0
for _, b := range bytes {
bufSize += len(b)
}
data = make([]byte, bufSize)
currLen := 0
for _, b := range bytes {
copy(data[currLen:currLen+len(b)], b)
currLen += len(b)
}
return data, nil
}
// createIndirectBlock creates a new indirect block and pick a new id
// for the existing block, and use the existing block's ID for the new
// indirect block that becomes the parent.
func (fd *fileData) createIndirectBlock(
ctx context.Context, df *dirtyFile, dver DataVer) (*FileBlock, error) {
newID, err := fd.crypto.MakeTemporaryBlockID()
if err != nil {
return nil, err
}
fblock := &FileBlock{
CommonBlock: CommonBlock{
IsInd: true,
},
IPtrs: []IndirectFilePtr{
{
BlockInfo: BlockInfo{
BlockPointer: BlockPointer{
ID: newID,
KeyGen: fd.kmd.LatestKeyGeneration(),
DataVer: dver,
Context: kbfsblock.MakeFirstContext(fd.uid),
},
EncodedSize: 0,
},
Off: 0,
},
},
}
fd.log.CDebugf(ctx, "Creating new level of indirection for file %v, "+
"new block id for old top level is %v", fd.rootBlockPointer(), newID)
// Mark the old block ID as not dirty, so that we will treat the
// old block ID as newly dirtied in cacheBlockIfNotYetDirtyLocked.
df.setBlockNotDirty(fd.rootBlockPointer())
err = fd.cacher(fd.rootBlockPointer(), fblock)
if err != nil {
return nil, err
}
return fblock, nil
}
// newRightBlock creates space for a new rightmost block, creating
// parent blocks and a new level of indirection in the tree as needed.
// If there's no new level of indirection, it modifies the blocks in
// `parentBlocks` to include the new right-most pointers
// (`parentBlocks` must consist of blocks copied for writing). It
// also returns the set of parents pointing to the new block (whether
// or not there is a new level of indirection), and also returns any
// newly-dirtied block pointers.
//
// The new block is pointed to using offset `off`, and doesn't have to
// represent an append to the end of the file. In particular, if
// `off` is less than the offset of its leftmost neighbor, it's the
// caller's responsibility to move the new right block into the
// correct place in the tree (e.g., using `shiftBlocksToFillHole()`).
func (fd *fileData) newRightBlock(
ctx context.Context, parentBlocks []parentBlockAndChildIndex, off int64,
df *dirtyFile, dver DataVer) (
[]parentBlockAndChildIndex, []BlockPointer, error) {
// Find the lowest block that can accommodate a new right block.
lowestAncestorWithRoom := -1
for i := len(parentBlocks) - 1; i >= 0; i-- {
pb := parentBlocks[i]
if len(pb.pblock.IPtrs) < fd.bsplit.MaxPtrsPerBlock() {
lowestAncestorWithRoom = i
break
}
}
var newTopBlock *FileBlock
var newDirtyPtrs []BlockPointer
if lowestAncestorWithRoom < 0 {
// Create a new level of indirection at the top.
var err error
newTopBlock, err = fd.createIndirectBlock(ctx, df, dver)
if err != nil {
return nil, nil, err
}
// The old top block needs to be cached under its new ID if it
// was indirect.
if len(parentBlocks) > 0 {
ptr := newTopBlock.IPtrs[0].BlockPointer
err = fd.cacher(ptr, parentBlocks[0].pblock)
if err != nil {
return nil, nil, err
}
newDirtyPtrs = append(newDirtyPtrs, ptr)
}
parentBlocks = append([]parentBlockAndChildIndex{{newTopBlock, 0}},
parentBlocks...)
lowestAncestorWithRoom = 0
}
rightParentBlocks := make([]parentBlockAndChildIndex, len(parentBlocks))
fd.log.CDebugf(ctx, "Making new right block at off %d for file %v, "+
"lowestAncestor at level %d", off, fd.rootBlockPointer(),
lowestAncestorWithRoom)
// Make a new right block for every parent, starting with the
// lowest ancestor with room. Note that we're not iterating over
// the actual parent blocks here; we're only using its length to
// figure out how many levels need new blocks.
pblock := parentBlocks[lowestAncestorWithRoom].pblock
for i := lowestAncestorWithRoom; i < len(parentBlocks); i++ {
newRID, err := fd.crypto.MakeTemporaryBlockID()
if err != nil {
return nil, nil, err
}
newPtr := BlockPointer{
ID: newRID,
KeyGen: fd.kmd.LatestKeyGeneration(),
DataVer: dver,
Context: kbfsblock.MakeFirstContext(fd.uid),
}
fd.log.CDebugf(ctx, "New right block for file %v, level %d, ptr %v",
fd.rootBlockPointer(), i, newPtr)
pblock.IPtrs = append(pblock.IPtrs, IndirectFilePtr{
BlockInfo: BlockInfo{
BlockPointer: newPtr,
EncodedSize: 0,
},
Off: off,
})
rightParentBlocks[i].pblock = pblock
rightParentBlocks[i].childIndex = len(pblock.IPtrs) - 1
rblock := &FileBlock{}
if i != len(parentBlocks)-1 {
rblock.IsInd = true
pblock = rblock
}
err = fd.cacher(newPtr, rblock)
if err != nil {
return nil, nil, err
}
newDirtyPtrs = append(newDirtyPtrs, newPtr)
}
// All parents up to and including the lowest ancestor with room
// will have to change, so mark them as dirty.
ptr := fd.rootBlockPointer()
for i := 0; i <= lowestAncestorWithRoom; i++ {
pb := parentBlocks[i]
if err := fd.cacher(ptr, pb.pblock); err != nil {
return nil, nil, err
}
newDirtyPtrs = append(newDirtyPtrs, ptr)
ptr = pb.childIPtr().BlockPointer
rightParentBlocks[i].pblock = pb.pblock
rightParentBlocks[i].childIndex = len(pb.pblock.IPtrs) - 1
}
return rightParentBlocks, newDirtyPtrs, nil
}
// shiftBlocksToFillHole should be called after newRightBlock when the
// offset for the new block is smaller than the size of the file.
// This happens when there is a hole in the file, and the user is now
// writing data into that hole. This function moves the new block
// into the correct place, and rearranges all the indirect pointers in
// the file as needed. It returns any block pointers that were
// dirtied in the process.
func (fd *fileData) shiftBlocksToFillHole(
ctx context.Context, newTopBlock *FileBlock,
parents []parentBlockAndChildIndex) (
newDirtyPtrs []BlockPointer, err error) {
// `parents` should represent the right side of the tree down to
// the new rightmost indirect pointer, the offset of which should
// match `newHoleStartOff`. Keep swapping it with its sibling on
// the left until its offset would be lower than that child's
// offset. If there are no children to the left, continue on with
// the children in the cousin block to the left. If we swap a
// child between cousin blocks, we must update the offset in the
// right cousin's parent block. If *that* updated pointer is the
// leftmost pointer in its parent block, update that one as well,
// up to the root.
//
// We are guaranteed at least one level of indirection because
// `newRightBlock` should have been called before
// `shiftBlocksToFillHole`.
immedParent := parents[len(parents)-1]
currIndex := immedParent.childIndex
newBlockStartOff := immedParent.childIPtr().Off
fd.log.CDebugf(ctx, "Shifting block with offset %d for file %v into "+
"position", newBlockStartOff, fd.rootBlockPointer())
// Swap left as needed.
for {
var leftOff int64
var newParents []parentBlockAndChildIndex
if currIndex > 0 {
leftOff = immedParent.pblock.IPtrs[currIndex-1].Off
} else {
// Construct the new set of parents for the shifted block,
// by looking for the next left cousin.
newParents = make([]parentBlockAndChildIndex, len(parents))
copy(newParents, parents)
var level int
for level = len(newParents) - 2; level >= 0; level-- {
// The parent at the level being evaluated has a left
// sibling, so we use that sibling.
if newParents[level].childIndex > 0 {
break
}
// Keep going up until we find a way back down a left branch.
}
if level < 0 {
// We are already all the way on the left, we're done!
return newDirtyPtrs, nil
}
newParents[level].childIndex--
// Walk back down, shifting the new parents into position.
for ; level < len(newParents)-1; level++ {
nextChildPtr := newParents[level].childIPtr()
childBlock, _, err := fd.getter(
ctx, fd.kmd, nextChildPtr.BlockPointer, fd.file, blockWrite)
if err != nil {
return nil, err
}
newParents[level+1].pblock = childBlock
newParents[level+1].childIndex = len(childBlock.IPtrs) - 1
leftOff = childBlock.IPtrs[len(childBlock.IPtrs)-1].Off
}
}
// We're done!
if leftOff < newBlockStartOff {
return newDirtyPtrs, nil
}
// Otherwise, we need to swap the indirect file pointers.
if currIndex > 0 {
immedParent.pblock.IPtrs[currIndex-1],
immedParent.pblock.IPtrs[currIndex] =
immedParent.pblock.IPtrs[currIndex],
immedParent.pblock.IPtrs[currIndex-1]
currIndex--
continue
}
// Swap block pointers across cousins at the lowest level of
// indirection.
newImmedParent := newParents[len(newParents)-1]
newCurrIndex := len(newImmedParent.pblock.IPtrs) - 1
newImmedParent.pblock.IPtrs[newCurrIndex],
immedParent.pblock.IPtrs[currIndex] =
immedParent.pblock.IPtrs[currIndex],
newImmedParent.pblock.IPtrs[newCurrIndex]
// Cache the new immediate parent as dirty.
if len(newParents) > 1 {
i := len(newParents) - 2
iptr := newParents[i].childIPtr()
if err := fd.cacher(
iptr.BlockPointer, newImmedParent.pblock); err != nil {
return nil, err
}
newDirtyPtrs = append(newDirtyPtrs, iptr.BlockPointer)
}
// Now we need to update the parent offsets on the right side,
// all the way up to the common ancestor (which is the one
// with the one that doesn't have a childIndex of 0). (We
// don't need to update the left side, since the offset of the
// new right-most block on that side doesn't affect the
// incoming indirect pointer offset, which already points to
// the left side of that branch.)
newRightOff := immedParent.pblock.IPtrs[currIndex].Off
for level := len(parents) - 2; level >= 0; level-- {
// Cache the block below this level, which was just
// modified.
childPtr := parents[level].childIPtr()
if err := fd.cacher(childPtr.BlockPointer,
parents[level+1].pblock); err != nil {
return nil, err
}
newDirtyPtrs = append(newDirtyPtrs, childPtr.BlockPointer)
// If we've reached a level where the child indirect
// offset wasn't affected, we're done. If not, update the
// offset at this level and move up the tree.
if parents[level+1].childIndex > 0 {
break
}
index := parents[level].childIndex
parents[level].pblock.IPtrs[index].Off = newRightOff
}
immedParent = newImmedParent
currIndex = newCurrIndex
parents = newParents
}
// The loop above must exit via one of the returns.
}
// markParentsDirty caches all the blocks in `parentBlocks` as dirty,
// and returns the dirtied block pointers as well as any block infos
// with non-zero encoded sizes that will now need to be unreferenced.
func (fd *fileData) markParentsDirty(ctx context.Context,
parentBlocks []parentBlockAndChildIndex) (
dirtyPtrs []BlockPointer, unrefs []BlockInfo, err error) {
parentPtr := fd.rootBlockPointer()
for _, pb := range parentBlocks {
if err := fd.cacher(parentPtr, pb.pblock); err != nil {
return nil, unrefs, err
}
dirtyPtrs = append(dirtyPtrs, parentPtr)
parentPtr = pb.childIPtr().BlockPointer
// Remember the size of each newly-dirtied child.
if pb.childIPtr().EncodedSize != 0 {
unrefs = append(unrefs, pb.childIPtr().BlockInfo)
pb.pblock.IPtrs[pb.childIndex].EncodedSize = 0
}
}
return dirtyPtrs, unrefs, nil
}
// write sets the given data and the given offset within the file,
// making new blocks and new levels of indirection as needed. Return
// params:
// * newDe: a new directory entry with the EncodedSize cleared if the file
// was extended.
// * dirtyPtrs: a slice of the BlockPointers that have been dirtied during
// the write. This includes any interior indirect blocks that may not
// have been changed yet, but which will need to change as part of the
// sync process because of leaf node changes below it.
// * unrefs: a slice of BlockInfos that must be unreferenced as part of an
// eventual sync of this write. May be non-nil even if err != nil.
// * newlyDirtiedChildBytes is the total amount of block data dirtied by this
// write, including the entire size of blocks that have had at least one
// byte dirtied. As above, it may be non-zero even if err != nil.
// * bytesExtended is the number of bytes the length of the file has been
// extended as part of this write.
func (fd *fileData) write(ctx context.Context, data []byte, off int64,
topBlock *FileBlock, oldDe DirEntry, df *dirtyFile) (
newDe DirEntry, dirtyPtrs []BlockPointer, unrefs []BlockInfo,
newlyDirtiedChildBytes int64, bytesExtended int64, err error) {
n := int64(len(data))
nCopied := int64(0)
oldSizeWithoutHoles := oldDe.Size
newDe = oldDe
fd.log.CDebugf(ctx, "Writing %d bytes at off %d", n, off)
dirtyMap := make(map[BlockPointer]bool)
for nCopied < n {
ptr, parentBlocks, block, nextBlockOff, startOff, wasDirty, err :=
fd.getFileBlockAtOffset(ctx, topBlock, off+nCopied, blockWrite)
if err != nil {
return newDe, nil, unrefs, newlyDirtiedChildBytes, 0, err
}
oldLen := len(block.Contents)
// Take care not to write past the beginning of the next block
// by using max.
max := len(data)
if nextBlockOff > 0 {
if room := int(nextBlockOff - off); room < max {
max = room
}
}
oldNCopied := nCopied
nCopied += fd.bsplit.CopyUntilSplit(
block, nextBlockOff < 0, data[nCopied:max], off+nCopied-startOff)
// If we need another block but there are no more, then make one.
switchToIndirect := false
if nCopied < n {
needExtendFile := nextBlockOff < 0
needFillHole := off+nCopied < nextBlockOff
newBlockOff := startOff + int64(len(block.Contents))
if nCopied == 0 {
if newBlockOff < off {
// We are writing somewhere inside a hole, not right
// at the start of it; all we have done so far it
// reached the end of an existing block (possibly
// zero-filling it out to its capacity). Make sure
// the next block starts right at the offset we care
// about.
newBlockOff = off
}
} else if newBlockOff != off+nCopied {
return newDe, nil, unrefs, newlyDirtiedChildBytes, 0,
fmt.Errorf("Copied %d bytes, but newBlockOff=%d does not "+
"match off=%d plus new bytes",
nCopied, newBlockOff, off)
}
var rightParents []parentBlockAndChildIndex
if needExtendFile || needFillHole {
// Make a new right block and update the parent's
// indirect block list, adding a level of indirection
// if needed. If we're just filling a hole, the block
// will end up all the way to the right of the range,
// and its offset will be smaller than the block to
// its left -- we'll fix that up below.
var newDirtyPtrs []BlockPointer
fd.log.CDebugf(ctx, "Making new right block at nCopied=%d, "+
"newBlockOff=%d", nCopied, newBlockOff)
wasIndirect := topBlock.IsInd
rightParents, newDirtyPtrs, err = fd.newRightBlock(
ctx, parentBlocks, newBlockOff, df,
DefaultNewBlockDataVersion(false))
if err != nil {
return newDe, nil, unrefs, newlyDirtiedChildBytes, 0, err
}
topBlock = rightParents[0].pblock
for _, p := range newDirtyPtrs {
dirtyMap[p] = true
}
if topBlock.IsInd != wasIndirect {
// The whole direct data block needs to be
// re-uploaded as a child block with a new block
// pointer, so below we'll need to track the dirty
// bytes of the direct block and cache the block
// as dirty. (Note that currently we don't track
// dirty bytes for indirect blocks.)
switchToIndirect = true
ptr = topBlock.IPtrs[0].BlockPointer
}
}
// If we're filling a hole, swap the new right block into
// the hole and shift everything else over.
if needFillHole {
newDirtyPtrs, err := fd.shiftBlocksToFillHole(
ctx, topBlock, rightParents)
if err != nil {
return newDe, nil, unrefs, newlyDirtiedChildBytes, 0, err
}
for _, p := range newDirtyPtrs {
dirtyMap[p] = true
}
if oldSizeWithoutHoles == oldDe.Size {
// For the purposes of calculating the newly-dirtied
// bytes for the deferral calculation, disregard the
// existing "hole" in the file.
oldSizeWithoutHoles = uint64(newBlockOff)
}
}
}
// Nothing was copied, no need to dirty anything. This can
// happen when trying to append to the contents of the file
// (i.e., either to the end of the file or right before the
// "hole"), and the last block is already full.
if nCopied == oldNCopied && !switchToIndirect {
continue
}
// Only in the last block does the file size grow.
if oldLen != len(block.Contents) && nextBlockOff < 0 {
newDe.EncodedSize = 0
// update the file info
newDe.Size += uint64(len(block.Contents) - oldLen)
}
// Calculate the amount of bytes we've newly-dirtied as part
// of this write.
newlyDirtiedChildBytes += int64(len(block.Contents))
if wasDirty {
newlyDirtiedChildBytes -= int64(oldLen)
}
newDirtyPtrs, newUnrefs, err := fd.markParentsDirty(ctx, parentBlocks)
unrefs = append(unrefs, newUnrefs...)
if err != nil {
return newDe, nil, unrefs, newlyDirtiedChildBytes, 0, err
}
for _, p := range newDirtyPtrs {
dirtyMap[p] = true
}
// keep the old block ID while it's dirty
if err = fd.cacher(ptr, block); err != nil {
return newDe, nil, unrefs, newlyDirtiedChildBytes, 0, err
}
dirtyMap[ptr] = true
}
if topBlock.IsInd {
// Always make the top block dirty, so we will sync its
// indirect blocks. This has the added benefit of ensuring
// that any write to a file while it's being sync'd will be
// deferred, even if it's to a block that's not currently
// being sync'd, since this top-most block will always be in
// the dirtyFiles map.
if err = fd.cacher(fd.rootBlockPointer(), topBlock); err != nil {
return newDe, nil, unrefs, newlyDirtiedChildBytes, 0, err
}
dirtyMap[fd.rootBlockPointer()] = true
}
lastByteWritten := off + int64(len(data)) // not counting holes
bytesExtended = 0
if lastByteWritten > int64(oldSizeWithoutHoles) {
bytesExtended = lastByteWritten - int64(oldSizeWithoutHoles)
}
dirtyPtrs = make([]BlockPointer, 0, len(dirtyMap))
for p := range dirtyMap {
dirtyPtrs = append(dirtyPtrs, p)
}
return newDe, dirtyPtrs, unrefs, newlyDirtiedChildBytes, bytesExtended, nil
}
// truncateExtend increases file size to the given size by appending
// a "hole" to the file. Return params:
// * newDe: a new directory entry with the EncodedSize cleared.
// * dirtyPtrs: a slice of the BlockPointers that have been dirtied during
// the truncate.
func (fd *fileData) truncateExtend(ctx context.Context, size uint64,
topBlock *FileBlock, parentBlocks []parentBlockAndChildIndex,
oldDe DirEntry, df *dirtyFile) (
newDe DirEntry, dirtyPtrs []BlockPointer, err error) {
fd.log.CDebugf(ctx, "truncateExtend: extending file %v to size %d",
fd.rootBlockPointer(), size)
switchToIndirect := !topBlock.IsInd
oldTopBlock := topBlock
if switchToIndirect {
fd.log.CDebugf(ctx, "truncateExtend: making block indirect %v",
fd.rootBlockPointer())
}
rightParents, newDirtyPtrs, err := fd.newRightBlock(
ctx, parentBlocks, int64(size), df,
DefaultNewBlockDataVersion(true))
if err != nil {
return DirEntry{}, nil, err
}
topBlock = rightParents[0].pblock
if switchToIndirect {
topBlock.IPtrs[0].Holes = true
err = fd.cacher(topBlock.IPtrs[0].BlockPointer, oldTopBlock)
if err != nil {
return DirEntry{}, nil, err
}
dirtyPtrs = append(dirtyPtrs, topBlock.IPtrs[0].BlockPointer)
fd.log.CDebugf(ctx, "truncateExtend: new zero data block %v",
topBlock.IPtrs[0].BlockPointer)
}
dirtyPtrs = append(dirtyPtrs, newDirtyPtrs...)
newDe = oldDe
newDe.EncodedSize = 0
// update the file info
newDe.Size = size
// Mark all for presence of holes, one would be enough,
// but this is more robust and easy.
for i := range topBlock.IPtrs {
topBlock.IPtrs[i].Holes = true
}
// Always make the top block dirty, so we will sync its
// indirect blocks. This has the added benefit of ensuring
// that any write to a file while it's being sync'd will be
// deferred, even if it's to a block that's not currently
// being sync'd, since this top-most block will always be in
// the fileBlockStates map.
err = fd.cacher(fd.rootBlockPointer(), topBlock)
if err != nil {
return DirEntry{}, nil, err
}
dirtyPtrs = append(dirtyPtrs, fd.rootBlockPointer())
return newDe, dirtyPtrs, nil
}
// truncateShrink shrinks the file to the given size. Return params:
// * newDe: a new directory entry with the EncodedSize cleared if the file
// shrunk.
// * dirtyPtrs: a slice of the BlockPointers that have been dirtied during
// the truncate. This includes any interior indirect blocks that may not
// have been changed yet, but which will need to change as part of the
// sync process because of leaf node changes below it.
// * unrefs: a slice of BlockInfos that must be unreferenced as part of an
// eventual sync of this write. May be non-nil even if err != nil.
// * newlyDirtiedChildBytes is the total amount of block data dirtied by this
// truncate, including the entire size of blocks that have had at least one
// byte dirtied. As above, it may be non-zero even if err != nil.
func (fd *fileData) truncateShrink(ctx context.Context, size uint64,
topBlock *FileBlock, oldDe DirEntry) (
newDe DirEntry, dirtyPtrs []BlockPointer, unrefs []BlockInfo,
newlyDirtiedChildBytes int64, err error) {
iSize := int64(size) // TODO: deal with overflow
ptr, parentBlocks, block, nextBlockOff, startOff, wasDirty, err :=
fd.getFileBlockAtOffset(ctx, topBlock, iSize, blockWrite)
if err != nil {
return DirEntry{}, nil, nil, 0, err
}
oldLen := len(block.Contents)
// We need to delete some data (and possibly entire blocks). Note
// we make a new slice and copy data in order to make sure the
// data being truncated can be fully garbage-collected.
block.Contents = append([]byte(nil), block.Contents[:iSize-startOff]...)
newlyDirtiedChildBytes = int64(len(block.Contents))
if wasDirty {
newlyDirtiedChildBytes -= int64(oldLen) // negative
}
// Need to mark the parents dirty before calling
// `getIndirectBlocksForOffsetRange`, so that function will see
// the new copies when fetching the blocks.
newDirtyPtrs, newUnrefs, err := fd.markParentsDirty(ctx, parentBlocks)
unrefs = append(unrefs, newUnrefs...)
if err != nil {
return DirEntry{}, nil, unrefs, newlyDirtiedChildBytes, err
}
dirtyMap := make(map[BlockPointer]bool)
for _, p := range newDirtyPtrs {
dirtyMap[p] = true
}
if nextBlockOff > 0 {
// TODO: remove any unnecessary levels of indirection if the
// number of leaf nodes shrinks significantly (KBFS-1824).
// Get all paths to any leaf nodes following the new
// right-most block, since those blocks need to be
// unreferenced, and their parents need to be modified or
// unreferenced.
pfr, err := fd.getIndirectBlocksForOffsetRange(
ctx, topBlock, nextBlockOff, -1)
if err != nil {
return DirEntry{}, nil, nil, 0, err
}
// A map from a pointer to an indirect block -> that block's
// original set of block pointers, before they are truncated
// in the loop below. It also tracks which pointed-to blocks
// have already been processed.
savedChildPtrs := make(map[BlockPointer][]IndirectFilePtr)
for _, path := range pfr {
// parentInfo points to pb.pblock in the loop below. The
// initial case is the top block, for which we need to
// fake a block info using just the root block pointer.
parentInfo := BlockInfo{BlockPointer: fd.rootBlockPointer()}
leftMost := true
for i, pb := range path {
ptrs := savedChildPtrs[parentInfo.BlockPointer]
if ptrs == nil {
// Process each block exactly once, removing all
// now-unnecessary indirect pointers (but caching
// that list so we can still walk the tree on the
// next iterations).
pblock := pb.pblock
ptrs = pblock.IPtrs
savedChildPtrs[parentInfo.BlockPointer] = ptrs
// Remove the first child iptr and everything
// following it if all the child indices below
// this level are 0.
removeStartingFromIndex := pb.childIndex
for j := i + 1; j < len(path); j++ {
if path[j].childIndex > 0 {
removeStartingFromIndex++
break
}
}
// If we remove iptr 0, this block can be
// unreferenced (unless it's on the left-most edge
// of the tree, in which case we keep it around
// for now -- see above TODO).
if pb.childIndex == 0 && !leftMost {
if parentInfo.EncodedSize != 0 {
unrefs = append(unrefs, parentInfo)
}
} else if removeStartingFromIndex < len(pblock.IPtrs) {
// Make sure we're modifying a copy of the
// block by fetching it again with blockWrite.
// We do this instead of calling DeepCopy in
// case the a copy of the block has already
// been made and put into the dirty
// cache. (e.g., in a previous iteration of
// this loop).
pblock, _, err = fd.getter(
ctx, fd.kmd, parentInfo.BlockPointer, fd.file,
blockWrite)
if err != nil {
return DirEntry{}, nil, nil,
newlyDirtiedChildBytes, err
}
pblock.IPtrs = pblock.IPtrs[:removeStartingFromIndex]
err = fd.cacher(parentInfo.BlockPointer, pblock)
if err != nil {
return DirEntry{}, nil, nil,
newlyDirtiedChildBytes, err
}
dirtyMap[parentInfo.BlockPointer] = true
}
}
// Down to the next level. If we've hit the leaf
// level, unreference the block.
parentInfo = ptrs[pb.childIndex].BlockInfo
if i == len(path)-1 && parentInfo.EncodedSize != 0 {
unrefs = append(unrefs, parentInfo)
} else if pb.childIndex > 0 {
leftMost = false
}
}
}
}
if topBlock.IsInd {
// Always make the top block dirty, so we will sync its
// indirect blocks. This has the added benefit of ensuring
// that any truncate to a file while it's being sync'd will be
// deferred, even if it's to a block that's not currently
// being sync'd, since this top-most block will always be in
// the dirtyFiles map.
if err = fd.cacher(fd.rootBlockPointer(), topBlock); err != nil {
return DirEntry{}, nil, nil, newlyDirtiedChildBytes, err
}
dirtyMap[fd.rootBlockPointer()] = true
}
newDe = oldDe
newDe.EncodedSize = 0
newDe.Size = size
// Keep the old block ID while it's dirty.
if err = fd.cacher(ptr, block); err != nil {
return DirEntry{}, nil, nil, newlyDirtiedChildBytes, err
}
dirtyMap[ptr] = true
dirtyPtrs = make([]BlockPointer, 0, len(dirtyMap))
for p := range dirtyMap {
dirtyPtrs = append(dirtyPtrs, p)
}
return newDe, dirtyPtrs, unrefs, newlyDirtiedChildBytes, nil
}
// split, if given an indirect top block of a file, checks whether any
// of the dirty leaf blocks in that file need to be split up
// differently (i.e., if the BlockSplitter is using
// fingerprinting-based boundaries). It returns the set of blocks
// that now need to be unreferenced.
func (fd *fileData) split(ctx context.Context, id tlf.ID,
dirtyBcache DirtyBlockCache, topBlock *FileBlock, df *dirtyFile) (
unrefs []BlockInfo, err error) {
if !topBlock.IsInd {
return nil, nil
}
// For an indirect file:
// 1) check if each dirty block is split at the right place.
// 2) if it needs fewer bytes, prepend the extra bytes to the next
// block (making a new one if it doesn't exist), and the next block
// gets marked dirty
// 3) if it needs more bytes, then use copyUntilSplit() to fetch bytes
// from the next block (if there is one), remove the copied bytes
// from the next block and mark it dirty
// 4) Then go through once more, and ready and finalize each
// dirty block, updating its ID in the indirect pointer list
off := int64(0)
for off >= 0 {
_, parentBlocks, block, nextBlockOff, startOff, err :=
fd.getNextDirtyFileBlockAtOffset(
ctx, topBlock, off, blockWrite, dirtyBcache)
if err != nil {
return unrefs, err
}
if block == nil {
// No more dirty blocks.
break
}
off = nextBlockOff // Will be -1 if there are no more blocks.
splitAt := fd.bsplit.CheckSplit(block)
switch {
case splitAt == 0:
continue
case splitAt > 0:
endOfBlock := startOff + int64(len(block.Contents))
extraBytes := block.Contents[splitAt:]
block.Contents = block.Contents[:splitAt]
// put the extra bytes in front of the next block
if nextBlockOff < 0 {
// Need to make a new block.
if _, _, err := fd.newRightBlock(
ctx, parentBlocks, endOfBlock, df,
DefaultNewBlockDataVersion(false)); err != nil {
return unrefs, err
}
}
rPtr, rParentBlocks, rblock, _, _, _, err :=
fd.getFileBlockAtOffset(
ctx, topBlock, endOfBlock, blockWrite)
if err != nil {
return unrefs, err
}
rblock.Contents = append(extraBytes, rblock.Contents...)
if err = fd.cacher(rPtr, rblock); err != nil {
return unrefs, err
}
endOfBlock = startOff + int64(len(block.Contents))
// Mark the old rblock as unref'd.
pb := rParentBlocks[len(rParentBlocks)-1]
unrefs = append(unrefs, pb.childIPtr().BlockInfo)
pb.pblock.IPtrs[pb.childIndex].EncodedSize = 0
// Update parent pointer offsets as needed.
for i := len(rParentBlocks) - 1; i >= 0; i-- {
pb := rParentBlocks[i]
pb.pblock.IPtrs[pb.childIndex].Off = endOfBlock
// If this isn't the leftmost child at this level,
// there's no need to update the parent.
if pb.childIndex > 0 {
break
}
}
_, newUnrefs, err := fd.markParentsDirty(ctx, rParentBlocks)
unrefs = append(unrefs, newUnrefs...)
if err != nil {
return unrefs, err
}
off = endOfBlock
case splitAt < 0:
if nextBlockOff < 0 {
// End of the line.
continue
}
endOfBlock := startOff + int64(len(block.Contents))
rPtr, rParentBlocks, rblock, _, _, _, err :=
fd.getFileBlockAtOffset(
ctx, topBlock, endOfBlock, blockWrite)
if err != nil {
return unrefs, err
}
// Copy some of that block's data into this block.
nCopied := fd.bsplit.CopyUntilSplit(block, false,
rblock.Contents, int64(len(block.Contents)))
rblock.Contents = rblock.Contents[nCopied:]
endOfBlock = startOff + int64(len(block.Contents))
// Mark the old right block as unref'd.
pb := rParentBlocks[len(rParentBlocks)-1]
unrefs = append(unrefs, pb.childIPtr().BlockInfo)
pb.pblock.IPtrs[pb.childIndex].EncodedSize = 0
// For the right block, adjust offset or delete as needed.
if len(rblock.Contents) > 0 {
if err = fd.cacher(rPtr, rblock); err != nil {
return unrefs, err
}
// Update parent pointer offsets as needed.
for i := len(rParentBlocks) - 1; i >= 0; i-- {
pb := rParentBlocks[i]
pb.pblock.IPtrs[pb.childIndex].Off = endOfBlock
// If this isn't the leftmost child at this level,
// there's no need to update the parent.
if pb.childIndex > 0 {
break
}
}
} else {
// TODO: If we're down to just one leaf block at this
// level, remove the layer of indirection (KBFS-1824).
iptrs := pb.pblock.IPtrs
pb.pblock.IPtrs =
append(iptrs[:pb.childIndex], iptrs[pb.childIndex+1:]...)
}
// Mark all parents as dirty.
_, newUnrefs, err := fd.markParentsDirty(ctx, rParentBlocks)
unrefs = append(unrefs, newUnrefs...)
if err != nil {
return unrefs, err
}
off = endOfBlock
}
}
return unrefs, nil
}
// readyHelper takes a set of paths from a root down to a child block,
// and readies all the blocks represented in those paths. If the
// caller wants leaf blocks readied, then the last element of each
// slice in `pathsFromRoot` should contain a leaf block, with a child
// index of -1. It's assumed that all slices in `pathsFromRoot` have
// the same size. This function returns a map pointing from the new
// block info from any readied block to its corresponding old block
// pointer.
func (fd *fileData) readyHelper(ctx context.Context, id tlf.ID,
bcache BlockCache, bops BlockOps, bps *blockPutState,
pathsFromRoot [][]parentBlockAndChildIndex,
df *dirtyFile) (map[BlockInfo]BlockPointer, error) {
oldPtrs := make(map[BlockInfo]BlockPointer)
newPtrs := make(map[BlockPointer]bool)
// Starting from the leaf level, ready each block at each
// level, and put the new BlockInfo into the parent block at the
// level above. At each level, only ready each block once. Don't
// ready the root block though; the folderBranchOps Sync code will
// do that.
for level := len(pathsFromRoot[0]) - 1; level > 0; level-- {
for i := 0; i < len(pathsFromRoot); i++ {
// Ready the dirty block.
pb := pathsFromRoot[i][level]
parentPB := pathsFromRoot[i][level-1]
ptr := parentPB.childIPtr().BlockPointer
// If this is already a new pointer, skip it.
if newPtrs[ptr] {
continue
}
newInfo, _, readyBlockData, err := ReadyBlock(
ctx, bcache, bops, fd.crypto, fd.kmd, pb.pblock, fd.uid)
if err != nil {
return nil, err
}
err = bcache.Put(
newInfo.BlockPointer, id, pb.pblock, PermanentEntry)
if err != nil {
return nil, err
}
// Only the leaf level need to be tracked by the dirty file.
var syncFunc func() error
if level == len(pathsFromRoot[0])-1 && df != nil {
syncFunc = func() error { return df.setBlockSynced(ptr) }
}
bps.addNewBlock(
newInfo.BlockPointer, pb.pblock, readyBlockData, syncFunc)
parentPB.pblock.IPtrs[parentPB.childIndex].BlockInfo = newInfo
oldPtrs[newInfo] = ptr
newPtrs[newInfo.BlockPointer] = true
}
}
return oldPtrs, nil
}
// ready, if given an indirect top-block, readies all the dirty child
// blocks, and updates their block IDs in their parent block's list of
// indirect pointers. It returns a map pointing from the new block
// info from any readied block to its corresponding old block pointer.
func (fd *fileData) ready(ctx context.Context, id tlf.ID, bcache BlockCache,
dirtyBcache DirtyBlockCache, bops BlockOps, bps *blockPutState,
topBlock *FileBlock, df *dirtyFile) (map[BlockInfo]BlockPointer, error) {
if !topBlock.IsInd {
return nil, nil
}
// This will contain paths to all dirty leaf paths. The final
// entry index in each path will be the leaf node block itself
// (with a -1 child index).
var dirtyLeafPaths [][]parentBlockAndChildIndex
// Gather all the paths to all dirty leaf blocks first.
off := int64(0)
for off >= 0 {
_, parentBlocks, block, nextBlockOff, _, err :=
fd.getNextDirtyFileBlockAtOffset(
ctx, topBlock, off, blockWrite, dirtyBcache)
if err != nil {
return nil, err
}
if block == nil {
// No more dirty blocks.
break
}
off = nextBlockOff // Will be -1 if there are no more blocks.
dirtyLeafPaths = append(dirtyLeafPaths,
append(parentBlocks, parentBlockAndChildIndex{block, -1}))
}
// No dirty blocks means nothing to do.
if len(dirtyLeafPaths) == 0 {
return nil, nil
}
return fd.readyHelper(ctx, id, bcache, bops, bps, dirtyLeafPaths, df)
}
func (fd *fileData) getIndirectFileBlockInfosWithTopBlock(ctx context.Context,
topBlock *FileBlock) ([]BlockInfo, error) {
if !topBlock.IsInd {
return nil, nil
}
pfr, err := fd.getIndirectBlocksForOffsetRange(ctx, topBlock, 0, -1)
if err != nil {
return nil, err
}
var blockInfos []BlockInfo
infoSeen := make(map[BlockPointer]bool)
for _, path := range pfr {
for _, pb := range path {
for _, iptr := range pb.pblock.IPtrs {
if infoSeen[iptr.BlockPointer] {
continue
}
infoSeen[iptr.BlockPointer] = true
blockInfos = append(blockInfos, iptr.BlockInfo)
}
}
}
return blockInfos, nil
}
func (fd *fileData) getIndirectFileBlockInfos(ctx context.Context) (
[]BlockInfo, error) {
if fd.rootBlockPointer().DirectType == DirectBlock {
return nil, nil
}
topBlock, _, err := fd.getter(
ctx, fd.kmd, fd.rootBlockPointer(), fd.file, blockRead)
if err != nil {
return nil, err
}
return fd.getIndirectFileBlockInfosWithTopBlock(ctx, topBlock)
}
// findIPtrsAndClearSize looks for the given set of indirect pointers,
// and returns whether they could be found. As a side effect, it also
// clears the encoded size for those indirect pointers.
func (fd *fileData) findIPtrsAndClearSize(
ctx context.Context, topBlock *FileBlock, ptrs map[BlockPointer]bool) (
found map[BlockPointer]bool, err error) {
if !topBlock.IsInd || len(ptrs) == 0 {
return nil, nil
}
pfr, err := fd.getIndirectBlocksForOffsetRange(ctx, topBlock, 0, -1)
if err != nil {
return nil, err
}
found = make(map[BlockPointer]bool)
// Search all paths for the given block pointer, clear its encoded
// size, and dirty all its parents up to the root.
infoSeen := make(map[BlockPointer]bool)
for _, path := range pfr {
parentPtr := fd.rootBlockPointer()
for level, pb := range path {
if infoSeen[parentPtr] {
parentPtr = pb.childIPtr().BlockPointer
continue
}
infoSeen[parentPtr] = true
for _, iptr := range pb.pblock.IPtrs {
if ptrs[iptr.BlockPointer] {
// Mark this pointer, and all parent blocks, as dirty.
parentPtr := fd.rootBlockPointer()
for i := 0; i <= level; i++ {
// Get a writeable copy for each block.
pblock, _, err := fd.getter(
ctx, fd.kmd, parentPtr, fd.file, blockWrite)
if err != nil {
return nil, err
}
path[i].pblock = pblock
parentPtr = path[i].childIPtr().BlockPointer
}
_, _, err = fd.markParentsDirty(ctx, path[:level+1])
if err != nil {
return nil, err
}
found[iptr.BlockPointer] = true
if len(found) == len(ptrs) {
return found, nil
}
}
}
parentPtr = pb.childIPtr().BlockPointer
}
}
return found, nil
}
// deepCopy makes a complete copy of this file, deduping leaf blocks
// and making new random BlockPointers for all indirect blocks. It
// returns the new top pointer of the copy, and all the new child
// pointers in the copy.
func (fd *fileData) deepCopy(ctx context.Context, codec kbfscodec.Codec,
dataVer DataVer) (
newTopPtr BlockPointer, allChildPtrs []BlockPointer, err error) {
topBlock, _, err := fd.getter(ctx, fd.kmd, fd.rootBlockPointer(),
fd.file, blockRead)
if err != nil {
return zeroPtr, nil, err
}
// Handle the single-level case first.
if !topBlock.IsInd {
newTopBlock, err := topBlock.DeepCopy(codec)
if err != nil {
return zeroPtr, nil, err
}
newTopPtr = fd.rootBlockPointer()
newTopPtr.RefNonce, err = fd.crypto.MakeBlockRefNonce()
if err != nil {
return zeroPtr, nil, err
}
newTopPtr.SetWriter(fd.uid)
if err = fd.cacher(newTopPtr, newTopBlock); err != nil {
return zeroPtr, nil, err
}
fd.log.CDebugf(ctx, "Deep copied file %s: %v -> %v",
fd.file.tailName(), fd.rootBlockPointer(), newTopPtr)
return newTopPtr, nil, nil
}
// For indirect files, get all the paths to leaf blocks.
pfr, err := fd.getIndirectBlocksForOffsetRange(ctx, topBlock, 0, -1)
if err != nil {
return zeroPtr, nil, err
}
if len(pfr) == 0 {
return zeroPtr, nil,
fmt.Errorf("Indirect file %v had no indirect blocks",
fd.rootBlockPointer())
}
// Make a new reference for all leaf blocks first.
copiedBlocks := make(map[BlockPointer]*FileBlock)
leafLevel := len(pfr[0]) - 1
for level := leafLevel; level >= 0; level-- {
for _, path := range pfr {
// What is the current ptr for this pblock?
ptr := fd.rootBlockPointer()
if level > 0 {
ptr = path[level-1].childIPtr().BlockPointer
}
if _, ok := copiedBlocks[ptr]; ok {
continue
}
// Copy the parent block and save it for later (it will be
// cached below).
pblock, err := path[level].pblock.DeepCopy(codec)
if err != nil {
return zeroPtr, nil, err
}
copiedBlocks[ptr] = pblock
for i, iptr := range pblock.IPtrs {
if level == leafLevel {
// Generate a new nonce for each indirect pointer
// to a leaf.
iptr.RefNonce, err = fd.crypto.MakeBlockRefNonce()
if err != nil {
return zeroPtr, nil, err
}
iptr.SetWriter(fd.uid)
pblock.IPtrs[i] = iptr
allChildPtrs = append(allChildPtrs, iptr.BlockPointer)
} else {
// Generate a new random ID for each indirect
// pointer to an indirect block.
newID, err := fd.crypto.MakeTemporaryBlockID()
if err != nil {
return zeroPtr, nil, err
}
// No need for a new refnonce here, since indirect
// blocks are guaranteed to get a new block ID
// when readied, since the child block pointers
// will have changed.
newPtr := BlockPointer{
ID: newID,
KeyGen: fd.kmd.LatestKeyGeneration(),
DataVer: dataVer,
Context: kbfsblock.MakeFirstContext(fd.uid),
}
pblock.IPtrs[i].BlockPointer = newPtr
allChildPtrs = append(allChildPtrs, newPtr)
childBlock, ok := copiedBlocks[iptr.BlockPointer]
if !ok {
return zeroPtr, nil, fmt.Errorf(
"No copied child block found for ptr %v",
iptr.BlockPointer)
}
if err = fd.cacher(newPtr, childBlock); err != nil {
return zeroPtr, nil, err
}
}
}
}
}
// Finally, make a new ID for the top block and cache it.
newTopPtr = fd.rootBlockPointer()
newID, err := fd.crypto.MakeTemporaryBlockID()
if err != nil {
return zeroPtr, nil, err
}
newTopPtr = BlockPointer{
ID: newID,
KeyGen: fd.kmd.LatestKeyGeneration(),
DataVer: dataVer,
Context: kbfsblock.Context{
Creator: fd.uid,
RefNonce: kbfsblock.ZeroRefNonce,
},
}
fd.log.CDebugf(ctx, "Deep copied indirect file %s: %v -> %v",
fd.file.tailName(), fd.rootBlockPointer(), newTopPtr)
newTopBlock, ok := copiedBlocks[fd.rootBlockPointer()]
if !ok {
return zeroPtr, nil, fmt.Errorf(
"No copied root block found for ptr %v",
fd.rootBlockPointer())
}
if err = fd.cacher(newTopPtr, newTopBlock); err != nil {
return zeroPtr, nil, err
}
return newTopPtr, allChildPtrs, nil
}
// undupChildrenInCopy takes a top block that's been copied via
// deepCopy(), and un-deduplicates all leaf children of the block. It
// adds all child blocks to the provided `bps`, including both the
// ones that were deduplicated and the ones that weren't. It returns
// the BlockInfos for all children.
func (fd *fileData) undupChildrenInCopy(ctx context.Context,
bcache BlockCache, bops BlockOps, bps *blockPutState,
topBlock *FileBlock) ([]BlockInfo, error) {
if !topBlock.IsInd {
return nil, nil
}
// For indirect files, get all the paths to leaf blocks. Note
// that because topBlock is a result of `deepCopy`, all of the
// indirect blocks that will make up the paths are also deep
// copies, and thus are modifiable.
pfr, err := fd.getIndirectBlocksForOffsetRange(ctx, topBlock, 0, -1)
if err != nil {
return nil, err
}
if len(pfr) == 0 {
return nil, fmt.Errorf(
"Indirect file %v had no indirect blocks", fd.rootBlockPointer())
}
// If the number of leaf blocks (len(pfr)) is likely to represent
// a file greater than 2 GB, abort conflict resolution. Until
// disk caching is ready, we'll have to help people deal with this
// on a case-by-case basis. // TODO: once the disk-backed cache
// is ready, make sure we use it here for both the dirty block
// cache and blockPutState (via some sort of "ready" block cache),
// so we avoid memory explosion in the case of journaling and
// multiple devices modifying the same large file or set of files.
// And then remove this check.
if len(pfr) > (2*1024*1024*1024)/MaxBlockSizeBytesDefault {
return nil, FileTooBigForCRError{fd.file}
}
// Append the leaf block to each path, since readyHelper expects it.
// TODO: parallelize these fetches.
for i, path := range pfr {
leafPtr := path[len(path)-1].childIPtr().BlockPointer
leafBlock, _, err := fd.getter(
ctx, fd.kmd, leafPtr, fd.file, blockWrite)
if err != nil {
return nil, err
}
pfr[i] = append(pfr[i], parentBlockAndChildIndex{leafBlock, -1})
}
newInfos, err := fd.readyHelper(
ctx, fd.file.Tlf, bcache, bops, bps, pfr, nil)
if err != nil {
return nil, err
}
blockInfos := make([]BlockInfo, 0, len(newInfos))
for newInfo := range newInfos {
blockInfos = append(blockInfos, newInfo)
}
return blockInfos, nil
}
// readyNonLeafBlocksInCopy takes a top block that's been copied via
// deepCopy(), and readies all the non-leaf children of the top block.
// It adds all readied blocks to the provided `bps`. It returns the
// BlockInfos for all non-leaf children.
func (fd *fileData) readyNonLeafBlocksInCopy(ctx context.Context,
bcache BlockCache, bops BlockOps, bps *blockPutState,
topBlock *FileBlock) ([]BlockInfo, error) {
if !topBlock.IsInd {
return nil, nil
}
// For indirect files, get all the paths to leaf blocks. Note
// that because topBlock is a deepCopy, all of the blocks are also
// deepCopys and thus are modifiable.
pfr, err := fd.getIndirectBlocksForOffsetRange(ctx, topBlock, 0, -1)
if err != nil {
return nil, err
}
if len(pfr) == 0 {
return nil, fmt.Errorf(
"Indirect file %v had no indirect blocks", fd.rootBlockPointer())
}
newInfos, err := fd.readyHelper(
ctx, fd.file.Tlf, bcache, bops, bps, pfr, nil)
if err != nil {
return nil, err
}
blockInfos := make([]BlockInfo, 0, len(newInfos))
for newInfo := range newInfos {
blockInfos = append(blockInfos, newInfo)
}
return blockInfos, nil
}
| 1 | 15,533 | Can you please remove `codec` from the parameters too? I think it's unused now. | keybase-kbfs | go |
@@ -126,6 +126,7 @@ class ContextTest extends AbstractSymbolResolutionTest {
when(compilationUnitDecl.getName()).thenReturn("CompilationUnit");
when(compilationUnitDecl.getQualifiedName()).thenReturn("com.github.javaparser.ast.CompilationUnit");
TypeSolver typeSolver = mock(TypeSolver.class);
+ when(typeSolver.getSolvedJavaLangObject()).thenReturn(new ReflectionClassDeclaration(Object.class, typeSolver));
when(typeSolver.getRoot()).thenReturn(typeSolver);
when(typeSolver.solveType("java.lang.Object")).thenReturn(new ReflectionClassDeclaration(Object.class, typeSolver));
when(typeSolver.tryToSolveType("com.github.javaparser.ast.CompilationUnit")).thenReturn(SymbolReference.solved(compilationUnitDecl)); | 1 | /*
* Copyright (C) 2015-2016 Federico Tomassetti
* Copyright (C) 2017-2019 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.symbolsolver.resolution;
import com.github.javaparser.*;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.ConstructorDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.*;
import com.github.javaparser.ast.stmt.*;
import com.github.javaparser.resolution.MethodUsage;
import com.github.javaparser.resolution.declarations.ResolvedClassDeclaration;
import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration;
import com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration;
import com.github.javaparser.resolution.types.ResolvedType;
import com.github.javaparser.symbolsolver.AbstractSymbolResolutionTest;
import com.github.javaparser.symbolsolver.core.resolution.Context;
import com.github.javaparser.symbolsolver.javaparser.Navigator;
import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade;
import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFactory;
import com.github.javaparser.symbolsolver.model.resolution.SymbolReference;
import com.github.javaparser.symbolsolver.model.resolution.TypeSolver;
import com.github.javaparser.symbolsolver.reflectionmodel.ReflectionClassDeclaration;
import com.github.javaparser.symbolsolver.resolution.typesolvers.*;
import com.github.javaparser.symbolsolver.utils.LeanParserConfiguration;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ContextTest extends AbstractSymbolResolutionTest {
private TypeSolver typeSolver = new CombinedTypeSolver(new MemoryTypeSolver(), new ReflectionTypeSolver());
private CompilationUnit parseSample(String sampleName) {
InputStream is = ContextTest.class.getClassLoader().getResourceAsStream(sampleName + ".java.txt");
return StaticJavaParser.parse(is);
}
@Test
void resolveDeclaredFieldReference() {
CompilationUnit cu = parseSample("ReferencesToField");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration referencesToField = Navigator.demandClass(cu, "ReferencesToField");
MethodDeclaration method1 = Navigator.demandMethod(referencesToField, "method1");
ExpressionStmt stmt = (ExpressionStmt) method1.getBody().get().getStatements().get(0);
AssignExpr assignExpr = (AssignExpr) stmt.getExpression();
SymbolSolver symbolSolver = new SymbolSolver(typeSolver);
SymbolReference symbolReference = symbolSolver.solveSymbol("i", assignExpr.getTarget());
assertTrue(symbolReference.isSolved());
assertEquals("i", symbolReference.getCorrespondingDeclaration().getName());
assertTrue(symbolReference.getCorrespondingDeclaration().isField());
}
@Test
void resolveInheritedFieldReference() {
CompilationUnit cu = parseSample("ReferencesToField");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration referencesToField = Navigator.demandClass(cu, "ReferencesToFieldExtendingClass");
MethodDeclaration method1 = Navigator.demandMethod(referencesToField, "method2");
ExpressionStmt stmt = (ExpressionStmt) method1.getBody().get().getStatements().get(0);
AssignExpr assignExpr = (AssignExpr) stmt.getExpression();
SymbolSolver symbolSolver = new SymbolSolver(typeSolver);
SymbolReference symbolReference = symbolSolver.solveSymbol("i", assignExpr.getTarget());
assertTrue(symbolReference.isSolved());
assertEquals("i", symbolReference.getCorrespondingDeclaration().getName());
assertTrue(symbolReference.getCorrespondingDeclaration().isField());
}
@Test
void resolveParameterReference() {
CompilationUnit cu = parseSample("ReferencesToParameter");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration referencesToField = Navigator.demandClass(cu, "ReferenceToParameter");
MethodDeclaration method1 = Navigator.demandMethod(referencesToField, "aMethod");
NameExpr foo = Navigator.findNameExpression(method1, "foo").get();
SymbolSolver symbolSolver = new SymbolSolver(typeSolver);
SymbolReference symbolReference = symbolSolver.solveSymbol("foo", foo);
assertTrue(symbolReference.isSolved());
assertEquals("foo", symbolReference.getCorrespondingDeclaration().getName());
assertTrue(symbolReference.getCorrespondingDeclaration().isParameter());
}
@Test
void resolveReferenceToImportedType() {
CompilationUnit cu = parseSample("Navigator");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration referencesToField = Navigator.demandClass(cu, "Navigator");
MethodDeclaration method = Navigator.demandMethod(referencesToField, "findType");
Parameter param = method.getParameters().get(0);
ResolvedClassDeclaration compilationUnitDecl = mock(ResolvedClassDeclaration.class);
when(compilationUnitDecl.getName()).thenReturn("CompilationUnit");
when(compilationUnitDecl.getQualifiedName()).thenReturn("com.github.javaparser.ast.CompilationUnit");
TypeSolver typeSolver = mock(TypeSolver.class);
when(typeSolver.getRoot()).thenReturn(typeSolver);
when(typeSolver.solveType("java.lang.Object")).thenReturn(new ReflectionClassDeclaration(Object.class, typeSolver));
when(typeSolver.tryToSolveType("com.github.javaparser.ast.CompilationUnit")).thenReturn(SymbolReference.solved(compilationUnitDecl));
SymbolSolver symbolSolver = new SymbolSolver(typeSolver);
SymbolReference<? extends ResolvedTypeDeclaration> ref = symbolSolver.solveType("CompilationUnit", param);
assertTrue(ref.isSolved());
assertEquals("CompilationUnit", ref.getCorrespondingDeclaration().getName());
assertEquals("com.github.javaparser.ast.CompilationUnit", ref.getCorrespondingDeclaration().getQualifiedName());
}
@Test
void resolveReferenceUsingQualifiedName() {
CompilationUnit cu = parseSample("Navigator2");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration referencesToField = Navigator.demandClass(cu, "Navigator");
MethodDeclaration method = Navigator.demandMethod(referencesToField, "findType");
Parameter param = method.getParameters().get(0);
ResolvedClassDeclaration compilationUnitDecl = mock(ResolvedClassDeclaration.class);
when(compilationUnitDecl.getName()).thenReturn("CompilationUnit");
when(compilationUnitDecl.getQualifiedName()).thenReturn("com.github.javaparser.ast.CompilationUnit");
TypeSolver typeSolver = mock(TypeSolver.class);
//when(typeSolver.tryToSolveType("java.lang.com.github.javaparser.ast.CompilationUnit")).thenReturn(SymbolReference.unsolved(ClassDeclaration.class));
when(typeSolver.getRoot()).thenReturn(typeSolver);
when(typeSolver.solveType("java.lang.Object")).thenReturn(new ReflectionClassDeclaration(Object.class, typeSolver));
when(typeSolver.tryToSolveType("com.github.javaparser.ast.CompilationUnit")).thenReturn(SymbolReference.solved(compilationUnitDecl));
SymbolSolver symbolSolver = new SymbolSolver(typeSolver);
SymbolReference<? extends ResolvedTypeDeclaration> ref = symbolSolver.solveType("com.github.javaparser.ast.CompilationUnit", param);
assertTrue(ref.isSolved());
assertEquals("CompilationUnit", ref.getCorrespondingDeclaration().getName());
assertEquals("com.github.javaparser.ast.CompilationUnit", ref.getCorrespondingDeclaration().getQualifiedName());
}
@Test
void resolveReferenceToClassesInTheSamePackage() {
CompilationUnit cu = parseSample("Navigator3");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration referencesToField = Navigator.demandClass(cu, "Navigator");
MethodDeclaration method = Navigator.demandMethod(referencesToField, "findType");
Parameter param = method.getParameters().get(0);
ResolvedClassDeclaration compilationUnitDecl = mock(ResolvedClassDeclaration.class);
when(compilationUnitDecl.getName()).thenReturn("CompilationUnit");
when(compilationUnitDecl.getQualifiedName()).thenReturn("my.packagez.CompilationUnit");
TypeSolver typeSolver = mock(TypeSolver.class);
when(typeSolver.getRoot()).thenReturn(typeSolver);
when(typeSolver.solveType("java.lang.Object")).thenReturn(new ReflectionClassDeclaration(Object.class, typeSolver));
when(typeSolver.tryToSolveType("my.packagez.CompilationUnit")).thenReturn(SymbolReference.solved(compilationUnitDecl));
SymbolSolver symbolSolver = new SymbolSolver(typeSolver);
SymbolReference<? extends ResolvedTypeDeclaration> ref = symbolSolver.solveType("CompilationUnit", param);
assertTrue(ref.isSolved());
assertEquals("CompilationUnit", ref.getCorrespondingDeclaration().getName());
assertEquals("my.packagez.CompilationUnit", ref.getCorrespondingDeclaration().getQualifiedName());
}
@Test
void resolveReferenceToClassInJavaLang() {
CompilationUnit cu = parseSample("Navigator");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration referencesToField = Navigator.demandClass(cu, "Navigator");
MethodDeclaration method = Navigator.demandMethod(referencesToField, "findType");
Parameter param = method.getParameters().get(1);
ResolvedClassDeclaration stringDecl = mock(ResolvedClassDeclaration.class);
when(stringDecl.getName()).thenReturn("String");
when(stringDecl.getQualifiedName()).thenReturn("java.lang.String");
TypeSolver typeSolver = mock(TypeSolver.class);
when(typeSolver.tryToSolveType("me.tomassetti.symbolsolver.javaparser.String")).thenReturn(SymbolReference.unsolved(ResolvedReferenceTypeDeclaration.class));
when(typeSolver.getRoot()).thenReturn(typeSolver);
when(typeSolver.solveType("java.lang.Object")).thenReturn(new ReflectionClassDeclaration(Object.class, typeSolver));
when(typeSolver.tryToSolveType("java.lang.String")).thenReturn(SymbolReference.solved(stringDecl));
SymbolSolver symbolSolver = new SymbolSolver(typeSolver);
SymbolReference<? extends ResolvedTypeDeclaration> ref = symbolSolver.solveType("String", param);
assertTrue(ref.isSolved());
assertEquals("String", ref.getCorrespondingDeclaration().getName());
assertEquals("java.lang.String", ref.getCorrespondingDeclaration().getQualifiedName());
}
@Test
void resolveReferenceToMethod() throws IOException {
CompilationUnit cu = parseSample("Navigator");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration referencesToField = Navigator.demandClass(cu, "Navigator");
MethodDeclaration method = Navigator.demandMethod(referencesToField, "findType");
MethodCallExpr callToGetTypes = Navigator.findMethodCall(method, "getTypes").get();
Path pathToJar = adaptPath("src/test/resources/javaparser-core-2.1.0.jar");
TypeSolver typeSolver = new CombinedTypeSolver(new JarTypeSolver(pathToJar), new ReflectionTypeSolver(true));
SymbolSolver symbolSolver = new SymbolSolver(typeSolver);
MethodUsage ref = symbolSolver.solveMethod("getTypes", Collections.emptyList(), callToGetTypes);
assertEquals("getTypes", ref.getName());
assertEquals("com.github.javaparser.ast.CompilationUnit", ref.declaringType().getQualifiedName());
//verify(typeSolver);
}
@Test
void resolveCascadeOfReferencesToMethod() throws IOException {
CompilationUnit cu = parseSample("Navigator");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration referencesToField = Navigator.demandClass(cu, "Navigator");
MethodDeclaration method = Navigator.demandMethod(referencesToField, "findType");
MethodCallExpr callToStream = Navigator.findMethodCall(method, "stream").get();
Path pathToJar = adaptPath("src/test/resources/javaparser-core-2.1.0.jar");
TypeSolver typeSolver = new CombinedTypeSolver(new JarTypeSolver(pathToJar), new ReflectionTypeSolver(true));
SymbolSolver symbolSolver = new SymbolSolver(typeSolver);
MethodUsage ref = symbolSolver.solveMethod("stream", Collections.emptyList(), callToStream);
assertEquals("stream", ref.getName());
assertEquals("java.util.Collection", ref.declaringType().getQualifiedName());
}
@Test
void resolveReferenceToMethodCalledOnArrayAccess() {
CompilationUnit cu = parseSample("ArrayAccess");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "ArrayAccess");
MethodDeclaration method = Navigator.demandMethod(clazz, "access");
MethodCallExpr callToTrim = Navigator.findMethodCall(method, "trim").get();
Path src = adaptPath("src/test/resources");
TypeSolver typeSolver = new CombinedTypeSolver(new ReflectionTypeSolver(), new JavaParserTypeSolver(src, new LeanParserConfiguration()));
SymbolSolver symbolSolver = new SymbolSolver(typeSolver);
MethodUsage ref = symbolSolver.solveMethod("trim", Collections.emptyList(), callToTrim);
assertEquals("trim", ref.getName());
assertEquals("java.lang.String", ref.declaringType().getQualifiedName());
}
@Test
void resolveReferenceToJreType() {
CompilationUnit cu = parseSample("NavigatorSimplified");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Navigator");
MethodDeclaration method = Navigator.demandMethod(clazz, "foo");
com.github.javaparser.ast.type.Type streamJavaParserType = method.getParameters().get(0).getType();
TypeSolver typeSolver = new ReflectionTypeSolver();
ResolvedType streamType = JavaParserFacade.get(typeSolver).convert(streamJavaParserType, method);
assertEquals("java.util.stream.Stream<java.lang.String>", streamType.describe());
}
@Test
void resolveReferenceToMethodWithLambda() {
CompilationUnit cu = parseSample("NavigatorSimplified");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Navigator");
MethodDeclaration method = Navigator.demandMethod(clazz, "findType");
MethodCallExpr methodCallExpr = Navigator.findMethodCall(method, "filter").get();
TypeSolver typeSolver = new ReflectionTypeSolver();
ResolvedType ref = JavaParserFacade.get(typeSolver).getType(methodCallExpr);
assertEquals("java.util.stream.Stream<java.lang.String>", ref.describe());
assertEquals(1, ref.asReferenceType().typeParametersValues().size());
assertEquals("java.lang.String", ref.asReferenceType().typeParametersValues().get(0).describe());
}
@Test
void resolveReferenceToLambdaParamBase() {
CompilationUnit cu = parseSample("NavigatorSimplified");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Navigator");
MethodDeclaration method = Navigator.demandMethod(clazz, "findType");
NameExpr refToT = Navigator.findNameExpression(method, "t").get();
TypeSolver typeSolver = new ReflectionTypeSolver();
JavaParserFacade javaParserFacade = JavaParserFacade.get(typeSolver);
ResolvedType ref = javaParserFacade.getType(refToT);
assertEquals("? super java.lang.String", ref.describe());
}
@Test
void resolveReferenceToLambdaParamSimplified() {
CompilationUnit cu = parseSample("NavigatorSimplified");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Navigator");
MethodDeclaration method = Navigator.demandMethod(clazz, "findType");
MethodCallExpr call = Navigator.findMethodCall(method, "isEmpty").get();
TypeSolver typeSolver = new ReflectionTypeSolver();
SymbolSolver symbolSolver = new SymbolSolver(typeSolver);
MethodUsage ref = symbolSolver.solveMethod("isEmpty", Collections.emptyList(), call);
assertEquals("isEmpty", ref.getName());
assertEquals("java.lang.String", ref.declaringType().getQualifiedName());
}
@Test
void resolveGenericReturnTypeOfMethodInJar() throws IOException {
CompilationUnit cu = parseSample("Navigator");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Navigator");
MethodDeclaration method = Navigator.demandMethod(clazz, "findType");
MethodCallExpr call = Navigator.findMethodCall(method, "getTypes").get();
Path pathToJar = adaptPath("src/test/resources/javaparser-core-2.1.0.jar");
TypeSolver typeSolver = new CombinedTypeSolver(new ReflectionTypeSolver(), new JarTypeSolver(pathToJar));
MethodUsage methodUsage = JavaParserFacade.get(typeSolver).solveMethodAsUsage(call);
assertEquals("getTypes", methodUsage.getName());
assertEquals("java.util.List<com.github.javaparser.ast.body.TypeDeclaration>", methodUsage.returnType().describe());
assertEquals(1, methodUsage.returnType().asReferenceType().typeParametersValues().size());
assertEquals("com.github.javaparser.ast.body.TypeDeclaration", methodUsage.returnType().asReferenceType().typeParametersValues().get(0).describe());
}
@Test
void resolveCompoundGenericReturnTypeOfMethodInJar() throws IOException {
CompilationUnit cu = parseSample("GenericClassNavigator");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "GenericClassNavigator");
MethodDeclaration method = Navigator.demandMethod(clazz, "doubleTyped");
MethodCallExpr call = Navigator.findMethodCall(method, "genericMethodWithDoubleTypedReturnType").get();
Path pathToJar = adaptPath("src/test/resources/javassist_generics/generics.jar");
TypeSolver typeSolver = new CombinedTypeSolver(new ReflectionTypeSolver(), new JarTypeSolver(pathToJar));
MethodUsage methodUsage = JavaParserFacade.get(typeSolver).solveMethodAsUsage(call);
assertEquals("genericMethodWithDoubleTypedReturnType", methodUsage.getName());
assertEquals("java.util.Map<T, V>", methodUsage.returnType().describe());
}
@Test
void resolveNestedGenericReturnTypeOfMethodInJar() throws IOException {
CompilationUnit cu = parseSample("GenericClassNavigator");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "GenericClassNavigator");
MethodDeclaration method = Navigator.demandMethod(clazz, "nestedTyped");
MethodCallExpr call = Navigator.findMethodCall(method, "genericMethodWithNestedReturnType").get();
Path pathToJar = adaptPath("src/test/resources/javassist_generics/generics.jar");
TypeSolver typeSolver = new CombinedTypeSolver(new ReflectionTypeSolver(), new JarTypeSolver(pathToJar));
MethodUsage methodUsage = JavaParserFacade.get(typeSolver).solveMethodAsUsage(call);
assertEquals("genericMethodWithNestedReturnType", methodUsage.getName());
assertEquals("java.util.List<java.util.List<T>>", methodUsage.returnType().describe());
}
@Test
void resolveSimpleGenericReturnTypeOfMethodInJar() throws IOException {
CompilationUnit cu = parseSample("GenericClassNavigator");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "GenericClassNavigator");
MethodDeclaration method = Navigator.demandMethod(clazz, "simple");
MethodCallExpr call = Navigator.findMethodCall(method, "get").get();
Path pathToJar = adaptPath("src/test/resources/javassist_generics/generics.jar");
TypeSolver typeSolver = new CombinedTypeSolver(new ReflectionTypeSolver(), new JarTypeSolver(pathToJar));
MethodUsage methodUsage = JavaParserFacade.get(typeSolver).solveMethodAsUsage(call);
assertEquals("get", methodUsage.getName());
assertEquals("java.util.List<java.util.List<java.lang.String>>", methodUsage.returnType().describe());
}
@Test
void resolveGenericReturnTypeFromInputParam() throws IOException {
CompilationUnit cu = parseSample("GenericClassNavigator");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "GenericClassNavigator");
MethodDeclaration method = Navigator.demandMethod(clazz, "input");
MethodCallExpr call = Navigator.findMethodCall(method, "copy").get();
Path pathToJar = adaptPath("src/test/resources/javassist_generics/generics.jar");
TypeSolver typeSolver = new CombinedTypeSolver(new ReflectionTypeSolver(), new JarTypeSolver(pathToJar));
MethodUsage methodUsage = JavaParserFacade.get(typeSolver).solveMethodAsUsage(call);
assertEquals("copy", methodUsage.getName());
assertEquals("javaparser.GenericClass<java.util.List<java.lang.String>>", methodUsage.returnType().describe());
}
@Test
void resolveComplexGenericReturnType() throws IOException {
CompilationUnit cu = parseSample("GenericClassNavigator");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "GenericClassNavigator");
MethodDeclaration method = Navigator.demandMethod(clazz, "complex");
MethodCallExpr call = Navigator.findMethodCall(method, "complexGenerics").get();
Path pathToJar = adaptPath("src/test/resources/javassist_generics/generics.jar");
TypeSolver typeSolver = new CombinedTypeSolver(new ReflectionTypeSolver(), new JarTypeSolver(pathToJar));
MethodUsage methodUsage = JavaParserFacade.get(typeSolver).solveMethodAsUsage(call);
assertEquals("complexGenerics", methodUsage.getName());
assertEquals("T", methodUsage.returnType().describe());
}
@Test
void resolveDoubleNestedClassType() throws IOException {
CompilationUnit cu = parseSample("GenericClassNavigator");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "GenericClassNavigator");
MethodDeclaration method = Navigator.demandMethod(clazz, "nestedTypes");
MethodCallExpr call = Navigator.findMethodCall(method, "asList").get();
Path pathToJar = adaptPath("src/test/resources/javassist_generics/generics.jar");
TypeSolver typeSolver = new CombinedTypeSolver(new ReflectionTypeSolver(), new JarTypeSolver(pathToJar));
MethodUsage methodUsage = JavaParserFacade.get(typeSolver).solveMethodAsUsage(call);
assertEquals("asList", methodUsage.getName());
assertEquals("java.util.List<javaparser.GenericClass.Bar.NestedBar>", methodUsage.getParamType(0).describe());
}
@Test
void resolveTypeUsageOfFirstMethodInGenericClass() throws IOException {
CompilationUnit cu = parseSample("Navigator");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Navigator");
MethodDeclaration method = Navigator.demandMethod(clazz, "findType");
MethodCallExpr callToGetTypes = Navigator.findMethodCall(method, "getTypes").get();
Path pathToJar = adaptPath("src/test/resources/javaparser-core-2.1.0.jar");
TypeSolver typeSolver = new CombinedTypeSolver(new ReflectionTypeSolver(), new JarTypeSolver(pathToJar));
MethodUsage filterUsage = JavaParserFacade.get(typeSolver).solveMethodAsUsage(callToGetTypes);
assertEquals("java.util.List<com.github.javaparser.ast.body.TypeDeclaration>", filterUsage.returnType().describe());
assertEquals(1, filterUsage.returnType().asReferenceType().typeParametersValues().size());
assertEquals("com.github.javaparser.ast.body.TypeDeclaration", filterUsage.returnType().asReferenceType().typeParametersValues().get(0).describe());
}
@Test
void resolveTypeUsageOfMethodInGenericClass() throws IOException {
CompilationUnit cu = parseSample("Navigator");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Navigator");
MethodDeclaration method = Navigator.demandMethod(clazz, "findType");
MethodCallExpr callToStream = Navigator.findMethodCall(method, "stream").get();
Path pathToJar = adaptPath("src/test/resources/javaparser-core-2.1.0.jar");
TypeSolver typeSolver = new CombinedTypeSolver(new ReflectionTypeSolver(), new JarTypeSolver(pathToJar));
MethodUsage filterUsage = JavaParserFacade.get(typeSolver).solveMethodAsUsage(callToStream);
assertEquals("java.util.stream.Stream<com.github.javaparser.ast.body.TypeDeclaration>", filterUsage.returnType().describe());
}
@Test
void resolveTypeUsageOfCascadeMethodInGenericClass() throws IOException {
CompilationUnit cu = parseSample("Navigator");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Navigator");
MethodDeclaration method = Navigator.demandMethod(clazz, "findType");
MethodCallExpr callToFilter = Navigator.findMethodCall(method, "filter").get();
Path pathToJar = adaptPath("src/test/resources/javaparser-core-2.1.0.jar");
TypeSolver typeSolver = new CombinedTypeSolver(new ReflectionTypeSolver(), new JarTypeSolver(pathToJar));
MethodUsage filterUsage = JavaParserFacade.get(typeSolver).solveMethodAsUsage(callToFilter);
assertEquals("java.util.stream.Stream<com.github.javaparser.ast.body.TypeDeclaration>", filterUsage.returnType().describe());
}
@Test
void resolveLambdaType() throws IOException {
CompilationUnit cu = parseSample("Navigator");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Navigator");
MethodDeclaration method = Navigator.demandMethod(clazz, "findType");
MethodCallExpr callToFilter = Navigator.findMethodCall(method, "filter").get();
Expression lambdaExpr = callToFilter.getArguments().get(0);
Path pathToJar = adaptPath("src/test/resources/javaparser-core-2.1.0.jar");
TypeSolver typeSolver = new CombinedTypeSolver(new ReflectionTypeSolver(), new JarTypeSolver(pathToJar));
ResolvedType typeOfLambdaExpr = JavaParserFacade.get(typeSolver).getType(lambdaExpr);
assertEquals("java.util.function.Predicate<? super com.github.javaparser.ast.body.TypeDeclaration>", typeOfLambdaExpr.describe());
}
@Test
void resolveReferenceToLambdaParam() throws IOException {
CompilationUnit cu = parseSample("Navigator");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Navigator");
MethodDeclaration method = Navigator.demandMethod(clazz, "findType");
MethodCallExpr callToGetName = Navigator.findMethodCall(method, "getName").get();
Expression referenceToT = callToGetName.getScope().get();
Path pathToJar = adaptPath("src/test/resources/javaparser-core-2.1.0.jar");
TypeSolver typeSolver = new CombinedTypeSolver(new ReflectionTypeSolver(), new JarTypeSolver(pathToJar));
ResolvedType typeOfT = JavaParserFacade.get(typeSolver).getType(referenceToT);
assertEquals("? super com.github.javaparser.ast.body.TypeDeclaration", typeOfT.describe());
}
@Test
void resolveReferenceToCallOnLambdaParam() throws IOException {
CompilationUnit cu = parseSample("Navigator");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Navigator");
MethodDeclaration method = Navigator.demandMethod(clazz, "findType");
MethodCallExpr callToGetName = Navigator.findMethodCall(method, "getName").get();
Path pathToJar = adaptPath("src/test/resources/javaparser-core-2.1.0.jar");
TypeSolver typeSolver = new CombinedTypeSolver(new ReflectionTypeSolver(), new JarTypeSolver(pathToJar));
MethodUsage methodUsage = JavaParserFacade.get(typeSolver).solveMethodAsUsage(callToGetName);
assertEquals("getName", methodUsage.getName());
assertEquals("com.github.javaparser.ast.body.TypeDeclaration", methodUsage.declaringType().getQualifiedName());
}
@Test
void resolveReferenceToOverloadMethodWithNullParam() {
CompilationUnit cu = parseSample("OverloadedMethods");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "OverloadedMethods");
MethodDeclaration method = Navigator.demandMethod(clazz, "m1");
MethodCallExpr call = Navigator.findMethodCall(method, "overloaded").get();
ReflectionTypeSolver typeSolver = new ReflectionTypeSolver();
MethodUsage ref = JavaParserFacade.get(typeSolver).solveMethodAsUsage(call);
assertEquals("overloaded", ref.getName());
assertEquals(1, ref.getNoParams());
assertEquals("java.lang.String", ref.getParamTypes().get(0).describe());
}
@Test
void resolveReferenceToOverloadMethodFindStricter() {
CompilationUnit cu = parseSample("OverloadedMethods");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "OverloadedMethods");
MethodDeclaration method = Navigator.demandMethod(clazz, "m2");
MethodCallExpr call = Navigator.findMethodCall(method, "overloaded").get();
ReflectionTypeSolver typeSolver = new ReflectionTypeSolver();
MethodUsage ref = JavaParserFacade.get(typeSolver).solveMethodAsUsage(call);
assertEquals("overloaded", ref.getName());
assertEquals(1, ref.getNoParams());
assertEquals("java.lang.String", ref.getParamTypes().get(0).describe());
}
@Test
void resolveReferenceToMethodWithGenericArrayTypeParam() {
CompilationUnit cu = parseSample("GenericArrayMethodArgument");
ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "GenericArrayMethodArgument");
MethodDeclaration method = Navigator.demandMethod(clazz, "bar");
MethodCallExpr call = Navigator.findMethodCall(method, "foo").get();
TypeSolver typeSolver = new ReflectionTypeSolver();
MethodUsage ref = JavaParserFacade.get(typeSolver).solveMethodAsUsage(call);
assertEquals("foo", ref.getName());
assertEquals(1, ref.getNoParams());
assertEquals("java.lang.String[]", ref.getParamType(0).describe());
}
@Test
void resolveInheritedMethodFromInterface() {
CompilationUnit cu = parseSample("InterfaceInheritance");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Test");
MethodDeclaration method = Navigator.demandMethod(clazz, "test");
MethodCallExpr call = Navigator.findMethodCall(method, "foobar").get();
Path src = adaptPath("src/test/resources");
TypeSolver typeSolver = new CombinedTypeSolver(new ReflectionTypeSolver(), new JavaParserTypeSolver(src));
ResolvedType type = JavaParserFacade.get(typeSolver).getType(call);
assertEquals("double", type.describe());
}
@Test
void resolveReferenceToOverloadMethodFindOnlyCompatible() {
CompilationUnit cu = parseSample("OverloadedMethods");
com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "OverloadedMethods");
MethodDeclaration method = Navigator.demandMethod(clazz, "m3");
MethodCallExpr call = Navigator.findMethodCall(method, "overloaded").get();
ReflectionTypeSolver typeSolver = new ReflectionTypeSolver();
MethodUsage ref = JavaParserFacade.get(typeSolver).solveMethodAsUsage(call);
assertEquals("overloaded", ref.getName());
assertEquals(1, ref.getNoParams());
assertEquals("java.lang.Object", ref.getParamTypes().get(0).describe());
}
private <PS extends Node> PS parse(String code, ParseStart<PS> parseStart) {
ParserConfiguration parserConfiguration = new ParserConfiguration();
parserConfiguration.setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_10);
ParseResult<PS> parseResult = new JavaParser(parserConfiguration).parse(parseStart, new StringProvider(code));
if (!parseResult.isSuccessful()) {
parseResult.getProblems().forEach(p -> System.out.println("ERR: " + p));
}
assertTrue(parseResult.isSuccessful());
PS root = parseResult.getResult().get();
return root;
}
@Test
void localVariableDeclarationInScope() {
String name = "a";
CompilationUnit cu = parse("class A { void foo() {\n" +
"SomeClass a; a.aField;" + "\n" +
"} }", ParseStart.COMPILATION_UNIT);
// The block statement expose to the 2nd statement the local var
BlockStmt blockStmt = cu.findAll(BlockStmt.class).get(0);
Context context1 = JavaParserFactory.getContext(blockStmt, typeSolver);
assertEquals(1, context1.localVariablesExposedToChild(blockStmt.getStatement(1)).size());
Node nameNode = cu.findAll(NameExpr.class).get(0);
Context context = JavaParserFactory.getContext(nameNode, typeSolver);
assertTrue(context.localVariableDeclarationInScope(name).isPresent());
}
//
// Testing JLS 6.3 Scope of a Declaration
//
// The scope of a formal parameter of a method (§8.4.1), constructor (§8.8.1), or lambda expression (§15.27) is the
// entire body of the method, constructor, or lambda expression.
private void assertNoParamsExposedToChildInContextNamed(Node parent, Node child, String paramName) {
assertNumberOfParamsExposedToChildInContextNamed(parent, child, paramName, 0, "the element is exposed and it should not");
}
private void assertOneParamExposedToChildInContextNamed(Node parent, Node child, String paramName) {
assertNumberOfParamsExposedToChildInContextNamed(parent, child, paramName, 1, "the element is not exposed as expected");
}
private void assertNumberOfParamsExposedToChildInContextNamed(Node parent, Node child, String paramName,
int expectedNumber, String message) {
assertEquals(expectedNumber, JavaParserFactory.getContext(parent, typeSolver)
.parametersExposedToChild(child).stream().filter(p -> p.getNameAsString().equals(paramName)).count(), message);
}
private void assertNoVarsExposedToChildInContextNamed(Node parent, Node child, String paramName) {
assertNumberOfVarsExposedToChildInContextNamed(parent, child, paramName, 0, "the element is exposed and it should not");
}
private void assertOneVarExposedToChildInContextNamed(Node parent, Node child, String paramName) {
assertNumberOfVarsExposedToChildInContextNamed(parent, child, paramName, 1, "the element is not exposed as expected");
}
private void assertNumberOfVarsExposedToChildInContextNamed(Node parent, Node child, String paramName,
int expectedNumber, String message) {
List<VariableDeclarator> vars = JavaParserFactory.getContext(parent, typeSolver)
.localVariablesExposedToChild(child);
assertEquals(expectedNumber, vars.stream().filter(p -> p.getNameAsString().equals(paramName)).count(), message);
}
@Test
void parametersExposedToChildForMethod() {
MethodDeclaration method = parse("void foo(int myParam) { aCall(); }",
ParseStart.CLASS_BODY).asMethodDeclaration();
assertOneParamExposedToChildInContextNamed(method, method.getBody().get(), "myParam");
assertNoParamsExposedToChildInContextNamed(method, method.getType(), "myParam");
assertNoParamsExposedToChildInContextNamed(method, method.getParameter(0), "myParam");
}
@Test
void parametersExposedToChildForConstructor() {
ConstructorDeclaration constructor = parse("Foo(int myParam) { aCall(); }",
ParseStart.CLASS_BODY).asConstructorDeclaration();
assertOneParamExposedToChildInContextNamed(constructor, constructor.getBody(), "myParam");
assertNoParamsExposedToChildInContextNamed(constructor, constructor.getParameter(0), "myParam");
}
@Test
void parametersExposedToChildForLambda() {
LambdaExpr lambda = (LambdaExpr)parse("Object myLambda = (myParam) -> myParam * 2;",
ParseStart.STATEMENT).asExpressionStmt().getExpression().asVariableDeclarationExpr()
.getVariables().get(0).getInitializer().get();
assertOneParamExposedToChildInContextNamed(lambda, lambda.getBody(), "myParam");
assertNoParamsExposedToChildInContextNamed(lambda, lambda.getParameter(0), "myParam");
}
// The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration
// appears, starting with its own initializer and including any further declarators to the right in the local
// variable declaration statement.
@Test
void localVariablesExposedToChildWithinABlock() {
BlockStmt blockStmt = parse("{ preStatement(); int a = 1, b = 2; otherStatement(); }",
ParseStart.STATEMENT).asBlockStmt();
assertNoVarsExposedToChildInContextNamed(blockStmt, blockStmt.getStatement(0), "a");
assertNoVarsExposedToChildInContextNamed(blockStmt, blockStmt.getStatement(0), "b");
assertOneVarExposedToChildInContextNamed(blockStmt, blockStmt.getStatement(2), "a");
assertOneVarExposedToChildInContextNamed(blockStmt, blockStmt.getStatement(2), "b");
VariableDeclarationExpr varDecl = blockStmt.getStatement(1).asExpressionStmt().getExpression()
.asVariableDeclarationExpr();
VariableDeclarator varA = varDecl.getVariables().get(0);
VariableDeclarator varB = varDecl.getVariables().get(1);
assertOneVarExposedToChildInContextNamed(varA,
varA.getInitializer().get(), "a");
assertOneVarExposedToChildInContextNamed(varDecl,
varB, "a");
assertNoVarsExposedToChildInContextNamed(varDecl,
varA, "b");
}
// The scope of a local variable declared in the ForInit part of a basic for statement (§14.14.1) includes all of the following:
// * Its own initializer
// * Any further declarators to the right in the ForInit part of the for statement
// * The Expression and ForUpdate parts of the for statement
// * The contained Statement
@Test
void localVariablesExposedToChildWithinForStmt() {
ForStmt forStmt = parse("for (int i=0, j=1;i<10;i++) { body(); }",
ParseStart.STATEMENT).asForStmt();
VariableDeclarationExpr initializations = forStmt.getInitialization().get(0).asVariableDeclarationExpr();
assertOneVarExposedToChildInContextNamed(initializations,
initializations.getVariable(1),
"i");
assertOneVarExposedToChildInContextNamed(forStmt,
forStmt.getCompare().get(),
"i");
assertOneVarExposedToChildInContextNamed(forStmt,
forStmt.getUpdate().get(0),
"i");
assertOneVarExposedToChildInContextNamed(forStmt,
forStmt.getBody(),
"i");
}
// The scope of a local variable declared in the FormalParameter part of an enhanced for statement (§14.14.2) is
// the contained Statement.
@Test
void localVariablesExposedToChildWithinEnhancedForeachStmt() {
ForEachStmt foreachStmt = parse("for (int i: myList) { body(); }",
ParseStart.STATEMENT).asForEachStmt();
assertOneVarExposedToChildInContextNamed(foreachStmt, foreachStmt.getBody(), "i");
assertNoVarsExposedToChildInContextNamed(foreachStmt, foreachStmt.getVariable(), "i");
assertNoVarsExposedToChildInContextNamed(foreachStmt, foreachStmt.getIterable(), "i");
}
// The scope of a parameter of an exception handler that is declared in a catch clause of a try statement (§14.20)
// is the entire block associated with the catch.
@Test
void parametersExposedToChildWithinTryStatement() {
CatchClause catchClause = parse("try { } catch(Exception e) { body(); }",
ParseStart.STATEMENT).asTryStmt().getCatchClauses().get(0);
assertOneParamExposedToChildInContextNamed(catchClause, catchClause.getBody(), "e");
assertNoParamsExposedToChildInContextNamed(catchClause, catchClause.getParameter(), "e");
}
// The scope of a variable declared in the ResourceSpecification of a try-with-resources statement (§14.20.3) is
// from the declaration rightward over the remainder of the ResourceSpecification and the entire try block
// associated with the try-with-resources statement.
@Test
void localVariablesExposedToChildWithinTryWithResourcesStatement() {
TryStmt stmt = parse("try (Object res1 = foo(); Object res2 = foo()) { body(); }",
ParseStart.STATEMENT).asTryStmt();
assertOneVarExposedToChildInContextNamed(stmt, stmt.getResources().get(1), "res1");
assertNoVarsExposedToChildInContextNamed(stmt, stmt.getResources().get(0), "res1");
assertOneVarExposedToChildInContextNamed(stmt, stmt.getTryBlock(), "res1");
}
}
| 1 | 14,122 | mocks needed this change so that it returns the "right" thing | javaparser-javaparser | java |
@@ -128,9 +128,14 @@ public class MenuEntrySwapperPlugin extends Plugin
@Getter
private boolean configuringShiftClick = false;
+ @Getter
@Setter
private boolean shiftModifier = false;
+ @Getter
+ @Setter
+ private boolean controlModifier = false;
+
@Provides
MenuEntrySwapperConfig provideConfig(ConfigManager configManager)
{ | 1 | /*
* Copyright (c) 2018, Adam <[email protected]>
* Copyright (c) 2018, Kamiel
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.menuentryswapper;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Provides;
import java.util.Set;
import javax.inject.Inject;
import lombok.Getter;
import lombok.Setter;
import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.ItemComposition;
import net.runelite.api.MenuAction;
import net.runelite.api.MenuEntry;
import net.runelite.api.NPC;
import net.runelite.api.events.ConfigChanged;
import net.runelite.api.events.FocusChanged;
import net.runelite.api.events.MenuEntryAdded;
import net.runelite.api.events.MenuOpened;
import net.runelite.api.events.MenuOptionClicked;
import net.runelite.api.events.PostItemComposition;
import net.runelite.api.events.WidgetMenuOptionClicked;
import net.runelite.api.widgets.WidgetInfo;
import net.runelite.client.callback.ClientThread;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.game.ItemManager;
import net.runelite.client.game.ItemVariationMapping;
import net.runelite.client.input.KeyManager;
import net.runelite.client.menus.MenuManager;
import net.runelite.client.menus.WidgetMenuOption;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import static net.runelite.client.util.MenuUtil.swap;
import net.runelite.client.util.Text;
import org.apache.commons.lang3.ArrayUtils;
@PluginDescriptor(
name = "Menu Entry Swapper",
description = "Change the default option that is displayed when hovering over objects",
tags = {"npcs", "inventory", "items", "objects"},
enabledByDefault = false
)
public class MenuEntrySwapperPlugin extends Plugin
{
private static final String CONFIGURE = "Configure";
private static final String SAVE = "Save";
private static final String RESET = "Reset";
private static final String MENU_TARGET = "Shift-click";
private static final String CONFIG_GROUP = "shiftclick";
private static final String ITEM_KEY_PREFIX = "item_";
private static final WidgetMenuOption FIXED_INVENTORY_TAB_CONFIGURE = new WidgetMenuOption(CONFIGURE,
MENU_TARGET, WidgetInfo.FIXED_VIEWPORT_INVENTORY_TAB);
private static final WidgetMenuOption FIXED_INVENTORY_TAB_SAVE = new WidgetMenuOption(SAVE,
MENU_TARGET, WidgetInfo.FIXED_VIEWPORT_INVENTORY_TAB);
private static final WidgetMenuOption RESIZABLE_INVENTORY_TAB_CONFIGURE = new WidgetMenuOption(CONFIGURE,
MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_INVENTORY_TAB);
private static final WidgetMenuOption RESIZABLE_INVENTORY_TAB_SAVE = new WidgetMenuOption(SAVE,
MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_INVENTORY_TAB);
private static final WidgetMenuOption RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_CONFIGURE = new WidgetMenuOption(CONFIGURE,
MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_TAB);
private static final WidgetMenuOption RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_SAVE = new WidgetMenuOption(SAVE,
MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_TAB);
private static final Set<MenuAction> NPC_MENU_TYPES = ImmutableSet.of(
MenuAction.NPC_FIRST_OPTION,
MenuAction.NPC_SECOND_OPTION,
MenuAction.NPC_THIRD_OPTION,
MenuAction.NPC_FOURTH_OPTION,
MenuAction.NPC_FIFTH_OPTION,
MenuAction.EXAMINE_NPC);
@Inject
private Client client;
@Inject
private ClientThread clientThread;
@Inject
private MenuEntrySwapperConfig config;
@Inject
private ShiftClickInputListener inputListener;
@Inject
private ConfigManager configManager;
@Inject
private KeyManager keyManager;
@Inject
private MenuManager menuManager;
@Inject
private ItemManager itemManager;
@Getter
private boolean configuringShiftClick = false;
@Setter
private boolean shiftModifier = false;
@Provides
MenuEntrySwapperConfig provideConfig(ConfigManager configManager)
{
return configManager.getConfig(MenuEntrySwapperConfig.class);
}
@Override
public void startUp()
{
if (config.shiftClickCustomization())
{
enableCustomization();
}
}
@Override
public void shutDown()
{
disableCustomization();
}
@Subscribe
public void onConfigChanged(ConfigChanged event)
{
if (!CONFIG_GROUP.equals(event.getGroup()))
{
return;
}
if (event.getKey().equals("shiftClickCustomization"))
{
if (config.shiftClickCustomization())
{
enableCustomization();
}
else
{
disableCustomization();
}
}
else if (event.getKey().startsWith(ITEM_KEY_PREFIX))
{
clientThread.invoke(this::resetItemCompositionCache);
}
}
private void resetItemCompositionCache()
{
itemManager.invalidateItemCompositionCache();
client.getItemCompositionCache().reset();
}
private Integer getSwapConfig(int itemId)
{
itemId = ItemVariationMapping.map(itemId);
String config = configManager.getConfiguration(CONFIG_GROUP, ITEM_KEY_PREFIX + itemId);
if (config == null || config.isEmpty())
{
return null;
}
return Integer.parseInt(config);
}
private void setSwapConfig(int itemId, int index)
{
itemId = ItemVariationMapping.map(itemId);
configManager.setConfiguration(CONFIG_GROUP, ITEM_KEY_PREFIX + itemId, index);
}
private void unsetSwapConfig(int itemId)
{
itemId = ItemVariationMapping.map(itemId);
configManager.unsetConfiguration(CONFIG_GROUP, ITEM_KEY_PREFIX + itemId);
}
private void enableCustomization()
{
keyManager.registerKeyListener(inputListener);
refreshShiftClickCustomizationMenus();
clientThread.invoke(this::resetItemCompositionCache);
}
private void disableCustomization()
{
keyManager.unregisterKeyListener(inputListener);
removeShiftClickCustomizationMenus();
configuringShiftClick = false;
clientThread.invoke(this::resetItemCompositionCache);
}
@Subscribe
public void onWidgetMenuOptionClicked(WidgetMenuOptionClicked event)
{
if (event.getWidget() == WidgetInfo.FIXED_VIEWPORT_INVENTORY_TAB
|| event.getWidget() == WidgetInfo.RESIZABLE_VIEWPORT_INVENTORY_TAB
|| event.getWidget() == WidgetInfo.RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_TAB)
{
configuringShiftClick = event.getMenuOption().equals(CONFIGURE) && Text.removeTags(event.getMenuTarget()).equals(MENU_TARGET);
refreshShiftClickCustomizationMenus();
}
}
@Subscribe
public void onMenuOpened(MenuOpened event)
{
if (!configuringShiftClick)
{
return;
}
MenuEntry firstEntry = event.getFirstEntry();
if (firstEntry == null)
{
return;
}
int widgetId = firstEntry.getParam1();
if (widgetId != WidgetInfo.INVENTORY.getId())
{
return;
}
int itemId = firstEntry.getIdentifier();
if (itemId == -1)
{
return;
}
ItemComposition itemComposition = client.getItemDefinition(itemId);
String itemName = itemComposition.getName();
String option = "Use";
int shiftClickActionindex = itemComposition.getShiftClickActionIndex();
String[] inventoryActions = itemComposition.getInventoryActions();
if (shiftClickActionindex >= 0 && shiftClickActionindex < inventoryActions.length)
{
option = inventoryActions[shiftClickActionindex];
}
MenuEntry[] entries = event.getMenuEntries();
for (MenuEntry entry : entries)
{
if (itemName.equals(Text.removeTags(entry.getTarget())))
{
entry.setType(MenuAction.RUNELITE.getId());
if (option.equals(entry.getOption()))
{
entry.setOption("* " + option);
}
}
}
final MenuEntry resetShiftClickEntry = new MenuEntry();
resetShiftClickEntry.setOption(RESET);
resetShiftClickEntry.setTarget(MENU_TARGET);
resetShiftClickEntry.setIdentifier(itemId);
resetShiftClickEntry.setParam1(widgetId);
resetShiftClickEntry.setType(MenuAction.RUNELITE.getId());
client.setMenuEntries(ArrayUtils.addAll(entries, resetShiftClickEntry));
}
@Subscribe
public void onMenuOptionClicked(MenuOptionClicked event)
{
if (event.getMenuAction() != MenuAction.RUNELITE || event.getWidgetId() != WidgetInfo.INVENTORY.getId())
{
return;
}
int itemId = event.getId();
if (itemId == -1)
{
return;
}
String option = event.getMenuOption();
String target = event.getMenuTarget();
ItemComposition itemComposition = client.getItemDefinition(itemId);
if (option.equals(RESET) && target.equals(MENU_TARGET))
{
unsetSwapConfig(itemId);
return;
}
if (!itemComposition.getName().equals(Text.removeTags(target)))
{
return;
}
int index = -1;
boolean valid = false;
if (option.equals("Use")) //because "Use" is not in inventoryActions
{
valid = true;
}
else
{
String[] inventoryActions = itemComposition.getInventoryActions();
for (index = 0; index < inventoryActions.length; index++)
{
if (option.equals(inventoryActions[index]))
{
valid = true;
break;
}
}
}
if (valid)
{
setSwapConfig(itemId, index);
}
}
@Subscribe
public void onMenuEntryAdded(MenuEntryAdded event)
{
if (client.getGameState() != GameState.LOGGED_IN)
{
return;
}
final int eventId = event.getIdentifier();
final String option = Text.removeTags(event.getOption()).toLowerCase();
final String target = Text.removeTags(event.getTarget()).toLowerCase();
final NPC hintArrowNpc = client.getHintArrowNpc();
if (hintArrowNpc != null
&& hintArrowNpc.getIndex() == eventId
&& NPC_MENU_TYPES.contains(MenuAction.of(event.getType())))
{
return;
}
if (option.equals("talk-to"))
{
if (config.swapPickpocket() && target.contains("h.a.m."))
{
swap(client, "pickpocket", option, target, true);
}
if (config.swapAbyssTeleport() && target.contains("mage of zamorak"))
{
swap(client, "teleport", option, target, true);
}
if (config.swapBank())
{
swap(client, "bank", option, target, true);
}
if (config.swapContract())
{
swap(client, "contract", option, target, true);
}
if (config.swapExchange())
{
swap(client, "exchange", option, target, true);
}
if (config.swapDarkMage())
{
swap(client, "repairs", option, target, true);
}
// make sure assignment swap is higher priority than trade swap for slayer masters
if (config.swapAssignment())
{
swap(client, "assignment", option, target, true);
}
if (config.swapTrade())
{
swap(client, "trade", option, target, true);
swap(client, "trade-with", option, target, true);
}
if (config.claimSlime() && target.equals("robin"))
{
swap(client, "claim-slime", option, target, true);
}
if (config.swapTravel())
{
swap(client, "travel", option, target, true);
swap(client, "pay-fare", option, target, true);
swap(client, "charter", option, target, true);
swap(client, "take-boat", option, target, true);
swap(client, "fly", option, target, true);
swap(client, "jatizso", option, target, true);
swap(client, "neitiznot", option, target, true);
swap(client, "rellekka", option, target, true);
swap(client, "follow", option, target, true);
swap(client, "transport", option, target, true);
}
if (config.swapPay())
{
swap(client, "pay", option, target, true);
swap(client, "pay (", option, target, false);
}
if (config.swapDecant())
{
swap(client, "decant", option, target, true);
}
if (config.swapQuick())
{
swap(client, "quick-travel", option, target, true);
}
}
else if (config.swapTravel() && option.equals("pass") && target.equals("energy barrier"))
{
swap(client, "pay-toll(2-ecto)", option, target, true);
}
else if (config.swapTravel() && option.equals("open") && target.equals("gate"))
{
swap(client, "pay-toll(10gp)", option, target, true);
}
else if (config.swapTravel() && option.equals("inspect") && target.equals("trapdoor"))
{
swap(client, "travel", option, target, true);
}
else if (config.swapHarpoon() && option.equals("cage"))
{
swap(client, "harpoon", option, target, true);
}
else if (config.swapHarpoon() && (option.equals("big net") || option.equals("net")))
{
swap(client, "harpoon", option, target, true);
}
else if (config.swapHomePortal() != HouseMode.ENTER && option.equals("enter"))
{
switch (config.swapHomePortal())
{
case HOME:
swap(client, "home", option, target, true);
break;
case BUILD_MODE:
swap(client, "build mode", option, target, true);
break;
case FRIENDS_HOUSE:
swap(client, "friend's house", option, target, true);
break;
}
}
else if (config.swapFairyRing() != FairyRingMode.OFF && config.swapFairyRing() != FairyRingMode.ZANARIS
&& (option.equals("zanaris") || option.equals("configure") || option.equals("tree")))
{
if (config.swapFairyRing() == FairyRingMode.LAST_DESTINATION)
{
swap(client, "last-destination", option, target, false);
}
else if (config.swapFairyRing() == FairyRingMode.CONFIGURE)
{
swap(client, "configure", option, target, false);
}
}
else if (config.swapFairyRing() == FairyRingMode.ZANARIS && option.equals("tree"))
{
swap(client, "zanaris", option, target, false);
}
else if (config.swapBoxTrap() && (option.equals("check") || option.equals("dismantle")))
{
swap(client, "reset", option, target, true);
}
else if (config.swapBoxTrap() && option.equals("take"))
{
swap(client, "lay", option, target, true);
}
else if (config.swapChase() && option.equals("pick-up"))
{
swap(client, "chase", option, target, true);
}
else if (config.swapBirdhouseEmpty() && option.equals("interact") && target.contains("birdhouse"))
{
swap(client, "empty", option, target, true);
}
else if (config.swapQuick() && option.equals("ring"))
{
swap(client, "quick-start", option, target, true);
}
else if (config.swapQuick() && option.equals("pass"))
{
swap(client, "quick-pass", option, target, true);
swap(client, "quick pass", option, target, true);
}
else if (config.swapQuick() && option.equals("open"))
{
swap(client, "quick-open", option, target, true);
}
else if (config.swapAdmire() && option.equals("admire"))
{
swap(client, "teleport", option, target, true);
swap(client, "spellbook", option, target, true);
swap(client, "perks", option, target, true);
}
else if (config.swapPrivate() && option.equals("shared"))
{
swap(client, "private", option, target, true);
}
else if (config.swapPick() && option.equals("pick"))
{
swap(client, "pick-lots", option, target, true);
}
else if (config.swapRogueschests() && target.contains("chest"))
{
swap(client, "search for traps", option, target, true);
}
else if (config.rockCake() && option.equals("eat"))
{
swap(client, "guzzle", option, target, true);
}
else if (config.shiftClickCustomization() && shiftModifier && !option.equals("use"))
{
Integer customOption = getSwapConfig(eventId);
if (customOption != null && customOption == -1)
{
swap(client, "use", option, target, true);
}
}
// Put all item-related swapping after shift-click
else if (config.swapTeleportItem() && option.equals("wear"))
{
swap(client, "rub", option, target, true);
swap(client, "teleport", option, target, true);
}
else if (option.equals("wield"))
{
if (config.swapTeleportItem())
{
swap(client, "teleport", option, target, true);
}
}
else if (config.swapBones() && option.equals("bury"))
{
swap(client, "use", option, target, true);
}
}
@Subscribe
public void onPostItemComposition(PostItemComposition event)
{
ItemComposition itemComposition = event.getItemComposition();
Integer option = getSwapConfig(itemComposition.getId());
if (option != null)
{
itemComposition.setShiftClickActionIndex(option);
}
}
@Subscribe
public void onFocusChanged(FocusChanged event)
{
if (!event.isFocused())
{
shiftModifier = false;
}
}
private int searchIndex(MenuEntry[] entries, String option, String target, boolean strict)
{
for (int i = entries.length - 1; i >= 0; i--)
{
MenuEntry entry = entries[i];
String entryOption = Text.removeTags(entry.getOption()).toLowerCase();
String entryTarget = Text.removeTags(entry.getTarget()).toLowerCase();
if (strict)
{
if (entryOption.equals(option) && entryTarget.equals(target))
{
return i;
}
}
else
{
if (entryOption.contains(option.toLowerCase()) && entryTarget.equals(target))
{
return i;
}
}
}
return -1;
}
private void removeShiftClickCustomizationMenus()
{
menuManager.removeManagedCustomMenu(FIXED_INVENTORY_TAB_CONFIGURE);
menuManager.removeManagedCustomMenu(FIXED_INVENTORY_TAB_SAVE);
menuManager.removeManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_CONFIGURE);
menuManager.removeManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_SAVE);
menuManager.removeManagedCustomMenu(RESIZABLE_INVENTORY_TAB_CONFIGURE);
menuManager.removeManagedCustomMenu(RESIZABLE_INVENTORY_TAB_SAVE);
}
private void refreshShiftClickCustomizationMenus()
{
removeShiftClickCustomizationMenus();
if (configuringShiftClick)
{
menuManager.addManagedCustomMenu(FIXED_INVENTORY_TAB_SAVE);
menuManager.addManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_SAVE);
menuManager.addManagedCustomMenu(RESIZABLE_INVENTORY_TAB_SAVE);
}
else
{
menuManager.addManagedCustomMenu(FIXED_INVENTORY_TAB_CONFIGURE);
menuManager.addManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_CONFIGURE);
menuManager.addManagedCustomMenu(RESIZABLE_INVENTORY_TAB_CONFIGURE);
}
}
}
| 1 | 14,904 | I don't think the getters for this are needed, but looks good other than that | open-osrs-runelite | java |
@@ -1,3 +1,16 @@
<%= content_tag_for :div, video do %>
- <%= render 'videos/summary', video: video %>
+ <div class="video-text <%= video.status_class %>">
+ <%= link_to video_path(video) do %>
+ <h3><%= video.name %></h3>
+ <% end %>
+ <div class="video-tags">
+ <%= render video.topics %>
+ </div>
+ <p class="video-length" data-wistia-id="<%= video.clip.wistia_id %>">
+ <%= video.length_in_minutes %> minutes
+ </p>
+ <p class="video-summary">
+ <%= format_markdown(video.summary) %>
+ </p>
+ </div>
<% end %> | 1 | <%= content_tag_for :div, video do %>
<%= render 'videos/summary', video: video %>
<% end %>
| 1 | 15,676 | :+1: to inlining this. | thoughtbot-upcase | rb |
@@ -13785,7 +13785,7 @@ return [
'stream_get_contents' => ['string|false', 'stream'=>'resource', 'length='=>'int', 'offset='=>'int'],
'stream_get_filters' => ['array'],
'stream_get_line' => ['string|false', 'stream'=>'resource', 'length'=>'int', 'ending='=>'string'],
-'stream_get_meta_data' => ['array{timed_out:bool,blocked:bool,eof:bool,unread_bytes:int,stream_type:string,wrapper_type:string,wrapper_data:mixed,mode:string,seekable:bool,uri:string,mediatype:string}', 'stream'=>'resource'],
+'stream_get_meta_data' => ['array{timed_out:bool,blocked:bool,eof:bool,unread_bytes:int,stream_type:string,wrapper_type:string,wrapper_data:mixed,mode:string,seekable:bool,uri:string,mediatype:string,crypto?:mixed}', 'stream'=>'resource'],
'stream_get_transports' => ['list<string>'],
'stream_get_wrappers' => ['list<string>'],
'stream_is_local' => ['bool', 'stream'=>'resource|string'], | 1 | <?php // phpcs:ignoreFile
namespace Phan\Language\Internal;
/**
* CURRENT PHP TARGET VERSION: 8.1
* The version above has to match Psalm\Internal\Codebase\InternalCallMapHandler::PHP_(MAJOR|MINOR)_VERSION
*
* Format
*
* '<function_name>' => ['<return_type>, '<arg_name>'=>'<arg_type>']
* alternative signature for the same function
* '<function_name\'1>' => ['<return_type>, '<arg_name>'=>'<arg_type>']
*
* A '&' in front of the <arg_name> means the arg is always passed by reference.
* (i.e. ReflectionParameter->isPassedByReference())
* This was previously only used in cases where the function actually created the
* variable in the local scope.
* Some reference arguments will have prefixes in <arg_name> to indicate the way the argument is used.
* Currently, the only prefixes with meaning are 'rw_' (read-write) and 'w_' (write).
* Those prefixes don't mean anything for non-references.
* Code using these signatures should remove those prefixes from messages rendered to the user.
* 1. '&rw_<arg_name>' indicates that a parameter with a value is expected to be passed in, and may be modified.
* Phan will warn if the variable has an incompatible type, or is undefined.
* 2. '&w_<arg_name>' indicates that a parameter is expected to be passed in, and the value will be ignored, and may be overwritten.
* 3. The absence of a prefix is treated by Phan the same way as having the prefix 'w_' (Some may be changed to 'rw_name'). These will have prefixes added later.
*
* So, for functions like sort() where technically the arg is by-ref,
* indicate the reference param's signature by-ref and read-write,
* as `'&rw_array'=>'array'`
* so that Phan won't create it in the local scope
*
* However, for a function like preg_match() where the 3rd arg is an array of sub-pattern matches (and optional),
* this arg needs to be marked as by-ref and write-only, as `'&w_matches='=>'array'`.
*
* A '=' following the <arg_name> indicates this arg is optional.
*
* The <arg_name> can begin with '...' to indicate the arg is variadic.
* '...args=' indicates it is both variadic and optional.
*
* Some reference arguments will have prefixes in <arg_name> to indicate the way the argument is used.
* Currently, the only prefixes with meaning are 'rw_' and 'w_'.
* Code using these signatures should remove those prefixes from messages rendered to the user.
* 1. '&rw_name' indicates that a parameter with a value is expected to be passed in, and may be modified.
* 2. '&w_name' indicates that a parameter is expected to be passed in, and the value will be ignored, and may be overwritten.
*
* This file contains the signatures for the most recent minor release of PHP supported by phan (php 7.2)
*
* Changes:
*
* In Phan 0.12.3,
*
* - This started using array shapes for union types (array{...}).
*
* \Phan\Language\UnionType->withFlattenedArrayShapeOrLiteralTypeInstances() may be of help to programmatically convert these to array<string,T1>|array<string,T2>
*
* - This started using array shapes with optional fields for union types (array{key?:int}).
* A `?` after the array shape field's key indicates that the field is optional.
*
* - This started adding param signatures and return signatures to `callable` types.
* E.g. 'usort' => ['bool', '&rw_array_arg'=>'array', 'cmp_function'=>'callable(mixed,mixed):int'].
* See NEWS.md for 0.12.3 for possible syntax. A suffix of `=` within `callable(...)` means that a parameter is optional.
*
* (Phan assumes that callbacks with optional arguments can be cast to callbacks with/without those args (Similar to inheritance checks)
* (e.g. callable(T1,T2=) can be cast to callable(T1) or callable(T1,T2), in the same way that a subclass would check).
* For some signatures, e.g. set_error_handler, this results in repetition, because callable(T1=) can't cast to callable(T1).
*
* Sources of stub info:
*
* 1. Reflection
* 2. docs.php.net's SVN repo or website, and examples (See internal/internalsignatures.php)
*
* See https://secure.php.net/manual/en/copyright.php
*
* The PHP manual text and comments are covered by the [Creative Commons Attribution 3.0 License](http://creativecommons.org/licenses/by/3.0/legalcode),
* copyright (c) the PHP Documentation Group
* 3. Various websites documenting individual extensions
* 4. PHPStorm stubs (For anything missing from the above sources)
* See internal/internalsignatures.php
*
* Available from https://github.com/JetBrains/phpstorm-stubs under the [Apache 2 license](https://www.apache.org/licenses/LICENSE-2.0)
*
* @phan-file-suppress PhanPluginMixedKeyNoKey (read by Phan when analyzing this file)
*
* Note: Some of Phan's inferences about return types are written as plugins for functions/methods where the return type depends on the parameter types.
* E.g. src/Phan/Plugin/Internal/DependentReturnTypeOverridePlugin.php is one plugin
*/
return [
'_' => ['string', 'message'=>'string'],
'__halt_compiler' => ['void'],
'abs' => ['int', 'num'=>'int'],
'abs\'1' => ['float', 'num'=>'float'],
'abs\'2' => ['numeric', 'num'=>'numeric'],
'accelerator_get_configuration' => ['array'],
'accelerator_get_scripts' => ['array'],
'accelerator_get_status' => ['array', 'fetch_scripts'=>'bool'],
'accelerator_reset' => [''],
'accelerator_set_status' => ['void', 'status'=>'bool'],
'acos' => ['float', 'num'=>'float'],
'acosh' => ['float', 'num'=>'float'],
'addcslashes' => ['string', 'string'=>'string', 'characters'=>'string'],
'addslashes' => ['string', 'string'=>'string'],
'AMQPBasicProperties::__construct' => ['void', 'content_type='=>'string', 'content_encoding='=>'string', 'headers='=>'array', 'delivery_mode='=>'int', 'priority='=>'int', 'correlation_id='=>'string', 'reply_to='=>'string', 'expiration='=>'string', 'message_id='=>'string', 'timestamp='=>'int', 'type='=>'string', 'user_id='=>'string', 'app_id='=>'string', 'cluster_id='=>'string'],
'AMQPBasicProperties::getAppId' => ['string'],
'AMQPBasicProperties::getClusterId' => ['string'],
'AMQPBasicProperties::getContentEncoding' => ['string'],
'AMQPBasicProperties::getContentType' => ['string'],
'AMQPBasicProperties::getCorrelationId' => ['string'],
'AMQPBasicProperties::getDeliveryMode' => ['int'],
'AMQPBasicProperties::getExpiration' => ['string'],
'AMQPBasicProperties::getHeaders' => ['array'],
'AMQPBasicProperties::getMessageId' => ['string'],
'AMQPBasicProperties::getPriority' => ['int'],
'AMQPBasicProperties::getReplyTo' => ['string'],
'AMQPBasicProperties::getTimestamp' => ['string'],
'AMQPBasicProperties::getType' => ['string'],
'AMQPBasicProperties::getUserId' => ['string'],
'AMQPChannel::__construct' => ['void', 'amqp_connection'=>'AMQPConnection'],
'AMQPChannel::basicRecover' => ['', 'requeue='=>'bool'],
'AMQPChannel::close' => [''],
'AMQPChannel::commitTransaction' => ['bool'],
'AMQPChannel::confirmSelect' => [''],
'AMQPChannel::getChannelId' => ['int'],
'AMQPChannel::getConnection' => ['AMQPConnection'],
'AMQPChannel::getConsumers' => ['AMQPQueue[]'],
'AMQPChannel::getPrefetchCount' => ['int'],
'AMQPChannel::getPrefetchSize' => ['int'],
'AMQPChannel::isConnected' => ['bool'],
'AMQPChannel::qos' => ['bool', 'size'=>'int', 'count'=>'int'],
'AMQPChannel::rollbackTransaction' => ['bool'],
'AMQPChannel::setConfirmCallback' => ['', 'ack_callback='=>'?callable', 'nack_callback='=>'?callable'],
'AMQPChannel::setPrefetchCount' => ['bool', 'count'=>'int'],
'AMQPChannel::setPrefetchSize' => ['bool', 'size'=>'int'],
'AMQPChannel::setReturnCallback' => ['', 'return_callback='=>'?callable'],
'AMQPChannel::startTransaction' => ['bool'],
'AMQPChannel::waitForBasicReturn' => ['', 'timeout='=>'float'],
'AMQPChannel::waitForConfirm' => ['', 'timeout='=>'float'],
'AMQPConnection::__construct' => ['void', 'credentials='=>'array'],
'AMQPConnection::connect' => ['bool'],
'AMQPConnection::disconnect' => ['bool'],
'AMQPConnection::getCACert' => ['string'],
'AMQPConnection::getCert' => ['string'],
'AMQPConnection::getHeartbeatInterval' => ['int'],
'AMQPConnection::getHost' => ['string'],
'AMQPConnection::getKey' => ['string'],
'AMQPConnection::getLogin' => ['string'],
'AMQPConnection::getMaxChannels' => ['?int'],
'AMQPConnection::getMaxFrameSize' => ['int'],
'AMQPConnection::getPassword' => ['string'],
'AMQPConnection::getPort' => ['int'],
'AMQPConnection::getReadTimeout' => ['float'],
'AMQPConnection::getTimeout' => ['float'],
'AMQPConnection::getUsedChannels' => ['int'],
'AMQPConnection::getVerify' => ['bool'],
'AMQPConnection::getVhost' => ['string'],
'AMQPConnection::getWriteTimeout' => ['float'],
'AMQPConnection::isConnected' => ['bool'],
'AMQPConnection::isPersistent' => ['?bool'],
'AMQPConnection::pconnect' => ['bool'],
'AMQPConnection::pdisconnect' => ['bool'],
'AMQPConnection::preconnect' => ['bool'],
'AMQPConnection::reconnect' => ['bool'],
'AMQPConnection::setCACert' => ['', 'cacert'=>'string'],
'AMQPConnection::setCert' => ['', 'cert'=>'string'],
'AMQPConnection::setHost' => ['bool', 'host'=>'string'],
'AMQPConnection::setKey' => ['', 'key'=>'string'],
'AMQPConnection::setLogin' => ['bool', 'login'=>'string'],
'AMQPConnection::setPassword' => ['bool', 'password'=>'string'],
'AMQPConnection::setPort' => ['bool', 'port'=>'int'],
'AMQPConnection::setReadTimeout' => ['bool', 'timeout'=>'int'],
'AMQPConnection::setTimeout' => ['bool', 'timeout'=>'int'],
'AMQPConnection::setVerify' => ['', 'verify'=>'bool'],
'AMQPConnection::setVhost' => ['bool', 'vhost'=>'string'],
'AMQPConnection::setWriteTimeout' => ['bool', 'timeout'=>'int'],
'AMQPDecimal::__construct' => ['void', 'exponent'=>'', 'significand'=>''],
'AMQPDecimal::getExponent' => ['int'],
'AMQPDecimal::getSignificand' => ['int'],
'AMQPEnvelope::__construct' => ['void'],
'AMQPEnvelope::getAppId' => ['string'],
'AMQPEnvelope::getBody' => ['string'],
'AMQPEnvelope::getClusterId' => ['string'],
'AMQPEnvelope::getConsumerTag' => ['string'],
'AMQPEnvelope::getContentEncoding' => ['string'],
'AMQPEnvelope::getContentType' => ['string'],
'AMQPEnvelope::getCorrelationId' => ['string'],
'AMQPEnvelope::getDeliveryMode' => ['int'],
'AMQPEnvelope::getDeliveryTag' => ['string'],
'AMQPEnvelope::getExchangeName' => ['string'],
'AMQPEnvelope::getExpiration' => ['string'],
'AMQPEnvelope::getHeader' => ['string|false', 'header_key'=>'string'],
'AMQPEnvelope::getHeaders' => ['array'],
'AMQPEnvelope::getMessageId' => ['string'],
'AMQPEnvelope::getPriority' => ['int'],
'AMQPEnvelope::getReplyTo' => ['string'],
'AMQPEnvelope::getRoutingKey' => ['string'],
'AMQPEnvelope::getTimeStamp' => ['string'],
'AMQPEnvelope::getType' => ['string'],
'AMQPEnvelope::getUserId' => ['string'],
'AMQPEnvelope::hasHeader' => ['bool', 'header_key'=>'string'],
'AMQPEnvelope::isRedelivery' => ['bool'],
'AMQPExchange::__construct' => ['void', 'amqp_channel'=>'AMQPChannel'],
'AMQPExchange::bind' => ['bool', 'exchange_name'=>'string', 'routing_key='=>'string', 'arguments='=>'array'],
'AMQPExchange::declareExchange' => ['bool'],
'AMQPExchange::delete' => ['bool', 'exchangeName='=>'string', 'flags='=>'int'],
'AMQPExchange::getArgument' => ['int|string|false', 'key'=>'string'],
'AMQPExchange::getArguments' => ['array'],
'AMQPExchange::getChannel' => ['AMQPChannel'],
'AMQPExchange::getConnection' => ['AMQPConnection'],
'AMQPExchange::getFlags' => ['int'],
'AMQPExchange::getName' => ['string'],
'AMQPExchange::getType' => ['string'],
'AMQPExchange::hasArgument' => ['bool', 'key'=>'string'],
'AMQPExchange::publish' => ['bool', 'message'=>'string', 'routing_key='=>'string', 'flags='=>'int', 'attributes='=>'array'],
'AMQPExchange::setArgument' => ['bool', 'key'=>'string', 'value'=>'int|string'],
'AMQPExchange::setArguments' => ['bool', 'arguments'=>'array'],
'AMQPExchange::setFlags' => ['bool', 'flags'=>'int'],
'AMQPExchange::setName' => ['bool', 'exchange_name'=>'string'],
'AMQPExchange::setType' => ['bool', 'exchange_type'=>'string'],
'AMQPExchange::unbind' => ['bool', 'exchange_name'=>'string', 'routing_key='=>'string', 'arguments='=>'array'],
'AMQPQueue::__construct' => ['void', 'amqp_channel'=>'AMQPChannel'],
'AMQPQueue::ack' => ['bool', 'delivery_tag'=>'string', 'flags='=>'int'],
'AMQPQueue::bind' => ['bool', 'exchange_name'=>'string', 'routing_key='=>'string', 'arguments='=>'array'],
'AMQPQueue::cancel' => ['bool', 'consumer_tag='=>'string'],
'AMQPQueue::consume' => ['void', 'callback='=>'?callable', 'flags='=>'int', 'consumerTag='=>'string'],
'AMQPQueue::declareQueue' => ['int'],
'AMQPQueue::delete' => ['int', 'flags='=>'int'],
'AMQPQueue::get' => ['AMQPEnvelope|false', 'flags='=>'int'],
'AMQPQueue::getArgument' => ['int|string|false', 'key'=>'string'],
'AMQPQueue::getArguments' => ['array'],
'AMQPQueue::getChannel' => ['AMQPChannel'],
'AMQPQueue::getConnection' => ['AMQPConnection'],
'AMQPQueue::getConsumerTag' => ['?string'],
'AMQPQueue::getFlags' => ['int'],
'AMQPQueue::getName' => ['string'],
'AMQPQueue::hasArgument' => ['bool', 'key'=>'string'],
'AMQPQueue::nack' => ['bool', 'delivery_tag'=>'string', 'flags='=>'int'],
'AMQPQueue::purge' => ['bool'],
'AMQPQueue::reject' => ['bool', 'delivery_tag'=>'string', 'flags='=>'int'],
'AMQPQueue::setArgument' => ['bool', 'key'=>'string', 'value'=>'mixed'],
'AMQPQueue::setArguments' => ['bool', 'arguments'=>'array'],
'AMQPQueue::setFlags' => ['bool', 'flags'=>'int'],
'AMQPQueue::setName' => ['bool', 'queue_name'=>'string'],
'AMQPQueue::unbind' => ['bool', 'exchange_name'=>'string', 'routing_key='=>'string', 'arguments='=>'array'],
'AMQPTimestamp::__construct' => ['void', 'timestamp'=>'string'],
'AMQPTimestamp::__toString' => ['string'],
'AMQPTimestamp::getTimestamp' => ['string'],
'apache_child_terminate' => ['bool'],
'apache_get_modules' => ['array'],
'apache_get_version' => ['string|false'],
'apache_getenv' => ['string|false', 'variable'=>'string', 'walk_to_top='=>'bool'],
'apache_lookup_uri' => ['object', 'filename'=>'string'],
'apache_note' => ['string|false', 'note_name'=>'string', 'note_value='=>'string'],
'apache_request_headers' => ['array|false'],
'apache_reset_timeout' => ['bool'],
'apache_response_headers' => ['array|false'],
'apache_setenv' => ['bool', 'variable'=>'string', 'value'=>'string', 'walk_to_top='=>'bool'],
'apc_add' => ['bool', 'key'=>'string', 'var'=>'mixed', 'ttl='=>'int'],
'apc_add\'1' => ['array', 'values'=>'array', 'unused='=>'', 'ttl='=>'int'],
'apc_bin_dump' => ['string|false|null', 'files='=>'array', 'user_vars='=>'array'],
'apc_bin_dumpfile' => ['int|false', 'files'=>'array', 'user_vars'=>'array', 'filename'=>'string', 'flags='=>'int', 'context='=>'resource'],
'apc_bin_load' => ['bool', 'data'=>'string', 'flags='=>'int'],
'apc_bin_loadfile' => ['bool', 'filename'=>'string', 'context='=>'resource', 'flags='=>'int'],
'apc_cache_info' => ['array|false', 'cache_type='=>'string', 'limited='=>'bool'],
'apc_cas' => ['bool', 'key'=>'string', 'old'=>'int', 'new'=>'int'],
'apc_clear_cache' => ['bool', 'cache_type='=>'string'],
'apc_compile_file' => ['bool', 'filename'=>'string', 'atomic='=>'bool'],
'apc_dec' => ['int|false', 'key'=>'string', 'step='=>'int', '&w_success='=>'bool'],
'apc_define_constants' => ['bool', 'key'=>'string', 'constants'=>'array', 'case_sensitive='=>'bool'],
'apc_delete' => ['bool', 'key'=>'string|string[]|APCIterator'],
'apc_delete_file' => ['bool|string[]', 'keys'=>'mixed'],
'apc_exists' => ['bool', 'keys'=>'string'],
'apc_exists\'1' => ['array', 'keys'=>'string[]'],
'apc_fetch' => ['mixed|false', 'key'=>'string', '&w_success='=>'bool'],
'apc_fetch\'1' => ['array|false', 'key'=>'string[]', '&w_success='=>'bool'],
'apc_inc' => ['int|false', 'key'=>'string', 'step='=>'int', '&w_success='=>'bool'],
'apc_load_constants' => ['bool', 'key'=>'string', 'case_sensitive='=>'bool'],
'apc_sma_info' => ['array|false', 'limited='=>'bool'],
'apc_store' => ['bool', 'key'=>'string', 'var'=>'', 'ttl='=>'int'],
'apc_store\'1' => ['array', 'values'=>'array', 'unused='=>'', 'ttl='=>'int'],
'APCIterator::__construct' => ['void', 'cache'=>'string', 'search='=>'null|string|string[]', 'format='=>'int', 'chunk_size='=>'int', 'list='=>'int'],
'APCIterator::current' => ['mixed|false'],
'APCIterator::getTotalCount' => ['int|false'],
'APCIterator::getTotalHits' => ['int|false'],
'APCIterator::getTotalSize' => ['int|false'],
'APCIterator::key' => ['string'],
'APCIterator::next' => ['void'],
'APCIterator::rewind' => ['void'],
'APCIterator::valid' => ['bool'],
'apcu_add' => ['bool', 'key'=>'string', 'var'=>'', 'ttl='=>'int'],
'apcu_add\'1' => ['array<string,int>', 'values'=>'array<string,mixed>', 'unused='=>'', 'ttl='=>'int'],
'apcu_cache_info' => ['array<string,mixed>|false', 'limited='=>'bool'],
'apcu_cas' => ['bool', 'key'=>'string', 'old'=>'int', 'new'=>'int'],
'apcu_clear_cache' => ['bool'],
'apcu_dec' => ['int|false', 'key'=>'string', 'step='=>'int', '&w_success='=>'bool', 'ttl='=>'int'],
'apcu_delete' => ['bool', 'key'=>'string|APCuIterator'],
'apcu_delete\'1' => ['list<string>', 'key'=>'string[]'],
'apcu_enabled' => ['bool'],
'apcu_entry' => ['mixed', 'key'=>'string', 'generator'=>'callable', 'ttl='=>'int'],
'apcu_exists' => ['bool', 'keys'=>'string'],
'apcu_exists\'1' => ['array', 'keys'=>'string[]'],
'apcu_fetch' => ['mixed|false', 'key'=>'string', '&w_success='=>'bool'],
'apcu_fetch\'1' => ['array|false', 'key'=>'string[]', '&w_success='=>'bool'],
'apcu_inc' => ['int|false', 'key'=>'string', 'step='=>'int', '&w_success='=>'bool', 'ttl='=>'int'],
'apcu_key_info' => ['?array', 'key'=>'string'],
'apcu_sma_info' => ['array|false', 'limited='=>'bool'],
'apcu_store' => ['bool', 'key'=>'string', 'var='=>'', 'ttl='=>'int'],
'apcu_store\'1' => ['array', 'values'=>'array', 'unused='=>'', 'ttl='=>'int'],
'APCuIterator::__construct' => ['void', 'search='=>'string|string[]|null', 'format='=>'int', 'chunk_size='=>'int', 'list='=>'int'],
'APCuIterator::current' => ['mixed'],
'APCuIterator::getTotalCount' => ['int'],
'APCuIterator::getTotalHits' => ['int'],
'APCuIterator::getTotalSize' => ['int'],
'APCuIterator::key' => ['string'],
'APCuIterator::next' => ['void'],
'APCuIterator::rewind' => ['void'],
'APCuIterator::valid' => ['bool'],
'apd_breakpoint' => ['bool', 'debug_level'=>'int'],
'apd_callstack' => ['array'],
'apd_clunk' => ['void', 'warning'=>'string', 'delimiter='=>'string'],
'apd_continue' => ['bool', 'debug_level'=>'int'],
'apd_croak' => ['void', 'warning'=>'string', 'delimiter='=>'string'],
'apd_dump_function_table' => ['void'],
'apd_dump_persistent_resources' => ['array'],
'apd_dump_regular_resources' => ['array'],
'apd_echo' => ['bool', 'output'=>'string'],
'apd_get_active_symbols' => ['array'],
'apd_set_pprof_trace' => ['string', 'dump_directory='=>'string', 'fragment='=>'string'],
'apd_set_session' => ['void', 'debug_level'=>'int'],
'apd_set_session_trace' => ['void', 'debug_level'=>'int', 'dump_directory='=>'string'],
'apd_set_session_trace_socket' => ['bool', 'tcp_server'=>'string', 'socket_type'=>'int', 'port'=>'int', 'debug_level'=>'int'],
'AppendIterator::__construct' => ['void'],
'AppendIterator::append' => ['void', 'iterator'=>'Iterator'],
'AppendIterator::current' => ['mixed'],
'AppendIterator::getArrayIterator' => ['ArrayIterator'],
'AppendIterator::getInnerIterator' => ['Iterator'],
'AppendIterator::getIteratorIndex' => ['int'],
'AppendIterator::key' => ['int|string|float|bool'],
'AppendIterator::next' => ['void'],
'AppendIterator::rewind' => ['void'],
'AppendIterator::valid' => ['bool'],
'ArgumentCountError::__clone' => ['void'],
'ArgumentCountError::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?Error'],
'ArgumentCountError::__toString' => ['string'],
'ArgumentCountError::__wakeup' => ['void'],
'ArgumentCountError::getCode' => ['int'],
'ArgumentCountError::getFile' => ['string'],
'ArgumentCountError::getLine' => ['int'],
'ArgumentCountError::getMessage' => ['string'],
'ArgumentCountError::getPrevious' => ['?Throwable'],
'ArgumentCountError::getTrace' => ['list<array<string,mixed>>'],
'ArgumentCountError::getTraceAsString' => ['string'],
'ArithmeticError::__clone' => ['void'],
'ArithmeticError::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?Error'],
'ArithmeticError::__toString' => ['string'],
'ArithmeticError::__wakeup' => ['void'],
'ArithmeticError::getCode' => ['int'],
'ArithmeticError::getFile' => ['string'],
'ArithmeticError::getLine' => ['int'],
'ArithmeticError::getMessage' => ['string'],
'ArithmeticError::getPrevious' => ['?Throwable'],
'ArithmeticError::getTrace' => ['list<array<string,mixed>>'],
'ArithmeticError::getTraceAsString' => ['string'],
'array_change_key_case' => ['associative-array', 'array'=>'array', 'case='=>'int'],
'array_chunk' => ['list<array[]>', 'array'=>'array', 'length'=>'int', 'preserve_keys='=>'bool'],
'array_column' => ['array', 'array'=>'array', 'column_key'=>'mixed', 'index_key='=>'mixed'],
'array_combine' => ['associative-array', 'keys'=>'string[]|int[]', 'values'=>'array'],
'array_count_values' => ['associative-array<mixed,int>', 'array'=>'array'],
'array_diff' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_diff_assoc' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_diff_key' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_diff_uassoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_comp_func'=>'callable(mixed,mixed):int'],
'array_diff_uassoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_diff_ukey' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'key_comp_func'=>'callable(mixed,mixed):int'],
'array_diff_ukey\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_fill' => ['array<int,mixed>', 'start_index'=>'int', 'count'=>'int', 'value'=>'mixed'],
'array_fill_keys' => ['array', 'keys'=>'array', 'value'=>'mixed'],
'array_filter' => ['associative-array', 'array'=>'array', 'callback='=>'callable(mixed,mixed=):scalar', 'mode='=>'int'],
'array_flip' => ['associative-array<mixed,int>|associative-array<mixed,string>', 'array'=>'array'],
'array_intersect' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_intersect_assoc' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_intersect_key' => ['associative-array', 'array'=>'array', 'arrays'=>'array', '...args='=>'array'],
'array_intersect_uassoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'key_compare_func'=>'callable(mixed,mixed):int'],
'array_intersect_uassoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest'=>'array|callable(mixed,mixed):int'],
'array_intersect_ukey' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'key_compare_func'=>'callable(mixed,mixed):int'],
'array_intersect_ukey\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest'=>'array|callable(mixed,mixed):int'],
'array_is_list' => ['bool', 'array'=>'array'],
'array_key_exists' => ['bool', 'key'=>'string|int', 'array'=>'array|ArrayObject'],
'array_key_first' => ['int|string|null', 'array'=>'array'],
'array_key_last' => ['int|string|null', 'array'=>'array'],
'array_keys' => ['list<string|int>', 'array'=>'array', 'filter_value='=>'mixed', 'strict='=>'bool'],
'array_map' => ['array', 'callback'=>'?callable', 'array'=>'array', '...arrays='=>'array'],
'array_merge' => ['array', 'arrays'=>'array', '...args='=>'array'],
'array_merge_recursive' => ['array', 'arrays'=>'array', '...args='=>'array'],
'array_multisort' => ['bool', '&rw_array'=>'array', 'rest='=>'array|int', 'array1_sort_flags='=>'array|int', '...args='=>'array|int'],
'array_pad' => ['array', 'array'=>'array', 'length'=>'int', 'value'=>'mixed'],
'array_pop' => ['mixed', '&rw_array'=>'array'],
'array_product' => ['int|float', 'array'=>'array'],
'array_push' => ['int', '&rw_array'=>'array', 'values'=>'mixed', '...vars='=>'mixed'],
'array_rand' => ['int|string|array<int,int>|array<int,string>', 'array'=>'non-empty-array', 'num'=>'int'],
'array_rand\'1' => ['int|string', 'array'=>'array'],
'array_reduce' => ['mixed', 'array'=>'array', 'callback'=>'callable(mixed,mixed):mixed', 'initial='=>'mixed'],
'array_replace' => ['array', 'array'=>'array', 'replacements'=>'array', '...args='=>'array'],
'array_replace_recursive' => ['array', 'array'=>'array', 'replacements'=>'array', '...args='=>'array'],
'array_reverse' => ['array', 'array'=>'array', 'preserve_keys='=>'bool'],
'array_search' => ['int|string|false', 'needle'=>'mixed', 'haystack'=>'array', 'strict='=>'bool'],
'array_shift' => ['mixed|null', '&rw_array'=>'array'],
'array_slice' => ['array', 'array'=>'array', 'offset'=>'int', 'length='=>'?int', 'preserve_keys='=>'bool'],
'array_splice' => ['array', '&rw_array'=>'array', 'offset'=>'int', 'length='=>'int', 'replacement='=>'array|string'],
'array_sum' => ['int|float', 'array'=>'array'],
'array_udiff' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_comp_func'=>'callable(mixed,mixed):int'],
'array_udiff\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_udiff_assoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'key_comp_func'=>'callable(mixed,mixed):int'],
'array_udiff_assoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_udiff_uassoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_comp_func'=>'callable(mixed,mixed):int', 'key_comp_func'=>'callable(mixed,mixed):int'],
'array_udiff_uassoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', 'arg5'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_uintersect' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_compare_func'=>'callable(mixed,mixed):int'],
'array_uintersect\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_uintersect_assoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_compare_func'=>'callable(mixed,mixed):int'],
'array_uintersect_assoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable', '...rest='=>'array|callable(mixed,mixed):int'],
'array_uintersect_uassoc' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'data_compare_func'=>'callable(mixed,mixed):int', 'key_compare_func'=>'callable(mixed,mixed):int'],
'array_uintersect_uassoc\'1' => ['associative-array', 'array'=>'array', 'rest'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', 'arg5'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_unique' => ['associative-array', 'array'=>'array', 'flags='=>'int'],
'array_unshift' => ['int', '&rw_array'=>'array', 'values'=>'mixed', '...vars='=>'mixed'],
'array_values' => ['list<mixed>', 'array'=>'array'],
'array_walk' => ['bool', '&rw_array'=>'array', 'callback'=>'callable', 'arg='=>'mixed'],
'array_walk\'1' => ['bool', '&rw_array'=>'object', 'callback'=>'callable', 'arg='=>'mixed'],
'array_walk_recursive' => ['bool', '&rw_array'=>'array', 'callback'=>'callable', 'arg='=>'mixed'],
'array_walk_recursive\'1' => ['bool', '&rw_array'=>'object', 'callback'=>'callable', 'arg='=>'mixed'],
'ArrayAccess::offsetExists' => ['bool', 'offset'=>'mixed'],
'ArrayAccess::offsetGet' => ['mixed', 'offset'=>'mixed'],
'ArrayAccess::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'ArrayAccess::offsetUnset' => ['void', 'offset'=>'mixed'],
'ArrayIterator::__construct' => ['void', 'array='=>'array|object', 'flags='=>'int'],
'ArrayIterator::append' => ['void', 'value'=>'mixed'],
'ArrayIterator::asort' => ['void'],
'ArrayIterator::count' => ['int'],
'ArrayIterator::current' => ['mixed'],
'ArrayIterator::getArrayCopy' => ['array'],
'ArrayIterator::getFlags' => ['int'],
'ArrayIterator::key' => ['int|string|false'],
'ArrayIterator::ksort' => ['void'],
'ArrayIterator::natcasesort' => ['void'],
'ArrayIterator::natsort' => ['void'],
'ArrayIterator::next' => ['void'],
'ArrayIterator::offsetExists' => ['bool', 'index'=>'string|int'],
'ArrayIterator::offsetGet' => ['mixed', 'index'=>'string|int'],
'ArrayIterator::offsetSet' => ['void', 'index'=>'string|int', 'newval'=>'mixed'],
'ArrayIterator::offsetUnset' => ['void', 'index'=>'string|int'],
'ArrayIterator::rewind' => ['void'],
'ArrayIterator::seek' => ['void', 'position'=>'int'],
'ArrayIterator::serialize' => ['string'],
'ArrayIterator::setFlags' => ['void', 'flags'=>'string'],
'ArrayIterator::uasort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'ArrayIterator::uksort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'ArrayIterator::unserialize' => ['void', 'serialized'=>'string'],
'ArrayIterator::valid' => ['bool'],
'ArrayObject::__construct' => ['void', 'input='=>'array|object', 'flags='=>'int', 'iterator_class='=>'string'],
'ArrayObject::append' => ['void', 'value'=>'mixed'],
'ArrayObject::asort' => ['void'],
'ArrayObject::count' => ['int'],
'ArrayObject::exchangeArray' => ['array', 'ar'=>'mixed'],
'ArrayObject::getArrayCopy' => ['array'],
'ArrayObject::getFlags' => ['int'],
'ArrayObject::getIterator' => ['ArrayIterator'],
'ArrayObject::getIteratorClass' => ['string'],
'ArrayObject::ksort' => ['void'],
'ArrayObject::natcasesort' => ['void'],
'ArrayObject::natsort' => ['void'],
'ArrayObject::offsetExists' => ['bool', 'index'=>'int|string'],
'ArrayObject::offsetGet' => ['mixed|null', 'index'=>'int|string'],
'ArrayObject::offsetSet' => ['void', 'index'=>'int|string', 'newval'=>'mixed'],
'ArrayObject::offsetUnset' => ['void', 'index'=>'int|string'],
'ArrayObject::serialize' => ['string'],
'ArrayObject::setFlags' => ['void', 'flags'=>'int'],
'ArrayObject::setIteratorClass' => ['void', 'iterator_class'=>'string'],
'ArrayObject::uasort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'ArrayObject::uksort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'ArrayObject::unserialize' => ['void', 'serialized'=>'string'],
'arsort' => ['bool', '&rw_array'=>'array', 'flags='=>'int'],
'asin' => ['float', 'num'=>'float'],
'asinh' => ['float', 'num'=>'float'],
'asort' => ['bool', '&rw_array'=>'array', 'flags='=>'int'],
'assert' => ['bool', 'assertion'=>'string|bool|int', 'description='=>'string|Throwable|null'],
'assert_options' => ['mixed|false', 'option'=>'int', 'value='=>'mixed'],
'ast\get_kind_name' => ['string', 'kind'=>'int'],
'ast\get_metadata' => ['array<int,ast\Metadata>'],
'ast\get_supported_versions' => ['array<int,int>', 'exclude_deprecated='=>'bool'],
'ast\kind_uses_flags' => ['bool', 'kind'=>'int'],
'ast\Node::__construct' => ['void', 'kind='=>'int', 'flags='=>'int', 'children='=>'ast\Node\Decl[]|ast\Node[]|int[]|string[]|float[]|bool[]|null[]', 'start_line='=>'int'],
'ast\parse_code' => ['ast\Node', 'code'=>'string', 'version'=>'int', 'filename='=>'string'],
'ast\parse_file' => ['ast\Node', 'filename'=>'string', 'version'=>'int'],
'atan' => ['float', 'num'=>'float'],
'atan2' => ['float', 'y'=>'float', 'x'=>'float'],
'atanh' => ['float', 'num'=>'float'],
'BadFunctionCallException::__clone' => ['void'],
'BadFunctionCallException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?BadFunctionCallException'],
'BadFunctionCallException::__toString' => ['string'],
'BadFunctionCallException::getCode' => ['int'],
'BadFunctionCallException::getFile' => ['string'],
'BadFunctionCallException::getLine' => ['int'],
'BadFunctionCallException::getMessage' => ['string'],
'BadFunctionCallException::getPrevious' => ['?Throwable|?BadFunctionCallException'],
'BadFunctionCallException::getTrace' => ['list<array<string,mixed>>'],
'BadFunctionCallException::getTraceAsString' => ['string'],
'BadMethodCallException::__clone' => ['void'],
'BadMethodCallException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?BadMethodCallException'],
'BadMethodCallException::__toString' => ['string'],
'BadMethodCallException::getCode' => ['int'],
'BadMethodCallException::getFile' => ['string'],
'BadMethodCallException::getLine' => ['int'],
'BadMethodCallException::getMessage' => ['string'],
'BadMethodCallException::getPrevious' => ['?Throwable|?BadMethodCallException'],
'BadMethodCallException::getTrace' => ['list<array<string,mixed>>'],
'BadMethodCallException::getTraceAsString' => ['string'],
'base64_decode' => ['string|false', 'string'=>'string', 'strict='=>'bool'],
'base64_encode' => ['string', 'string'=>'string'],
'base_convert' => ['string', 'num'=>'string', 'from_base'=>'int', 'to_base'=>'int'],
'basename' => ['string', 'path'=>'string', 'suffix='=>'string'],
'bbcode_add_element' => ['bool', 'bbcode_container'=>'resource', 'tag_name'=>'string', 'tag_rules'=>'array'],
'bbcode_add_smiley' => ['bool', 'bbcode_container'=>'resource', 'smiley'=>'string', 'replace_by'=>'string'],
'bbcode_create' => ['resource', 'bbcode_initial_tags='=>'array'],
'bbcode_destroy' => ['bool', 'bbcode_container'=>'resource'],
'bbcode_parse' => ['string', 'bbcode_container'=>'resource', 'to_parse'=>'string'],
'bbcode_set_arg_parser' => ['bool', 'bbcode_container'=>'resource', 'bbcode_arg_parser'=>'resource'],
'bbcode_set_flags' => ['bool', 'bbcode_container'=>'resource', 'flags'=>'int', 'mode='=>'int'],
'bcadd' => ['numeric-string', 'num1'=>'numeric-string', 'num2'=>'numeric-string', 'scale='=>'int|null'],
'bccomp' => ['int', 'num1'=>'numeric-string', 'num2'=>'numeric-string', 'scale='=>'int|null'],
'bcdiv' => ['numeric-string|null', 'dividend'=>'numeric-string', 'divisor'=>'numeric-string', 'scale='=>'int|null'],
'bcmod' => ['numeric-string|null', 'dividend'=>'numeric-string', 'divisor'=>'numeric-string', 'scale='=>'int|null'],
'bcmul' => ['numeric-string', 'num1'=>'numeric-string', 'num2'=>'numeric-string', 'scale='=>'int|null'],
'bcompiler_load' => ['bool', 'filename'=>'string'],
'bcompiler_load_exe' => ['bool', 'filename'=>'string'],
'bcompiler_parse_class' => ['bool', 'class'=>'string', 'callback'=>'string'],
'bcompiler_read' => ['bool', 'filehandle'=>'resource'],
'bcompiler_write_class' => ['bool', 'filehandle'=>'resource', 'classname'=>'string', 'extends='=>'string'],
'bcompiler_write_constant' => ['bool', 'filehandle'=>'resource', 'constantname'=>'string'],
'bcompiler_write_exe_footer' => ['bool', 'filehandle'=>'resource', 'startpos'=>'int'],
'bcompiler_write_file' => ['bool', 'filehandle'=>'resource', 'filename'=>'string'],
'bcompiler_write_footer' => ['bool', 'filehandle'=>'resource'],
'bcompiler_write_function' => ['bool', 'filehandle'=>'resource', 'functionname'=>'string'],
'bcompiler_write_functions_from_file' => ['bool', 'filehandle'=>'resource', 'filename'=>'string'],
'bcompiler_write_header' => ['bool', 'filehandle'=>'resource', 'write_ver='=>'string'],
'bcompiler_write_included_filename' => ['bool', 'filehandle'=>'resource', 'filename'=>'string'],
'bcpow' => ['numeric-string', 'num'=>'numeric-string', 'exponent'=>'numeric-string', 'scale='=>'int|null'],
'bcpowmod' => ['numeric-string|false', 'base'=>'numeric-string', 'exponent'=>'numeric-string', 'modulus'=>'numeric-string', 'scale='=>'int|null'],
'bcscale' => ['int', 'scale='=>'int|null'],
'bcsqrt' => ['numeric-string|null', 'num'=>'numeric-string', 'scale='=>'int|null'],
'bcsub' => ['numeric-string', 'num1'=>'numeric-string', 'num2'=>'numeric-string', 'scale='=>'int|null'],
'bin2hex' => ['string', 'string'=>'string'],
'bind_textdomain_codeset' => ['string', 'domain'=>'string', 'codeset'=>'string'],
'bindec' => ['float|int', 'binary_string'=>'string'],
'bindtextdomain' => ['string', 'domain'=>'string', 'directory'=>'string'],
'birdstep_autocommit' => ['bool', 'index'=>'int'],
'birdstep_close' => ['bool', 'id'=>'int'],
'birdstep_commit' => ['bool', 'index'=>'int'],
'birdstep_connect' => ['int', 'server'=>'string', 'user'=>'string', 'pass'=>'string'],
'birdstep_exec' => ['int', 'index'=>'int', 'exec_str'=>'string'],
'birdstep_fetch' => ['bool', 'index'=>'int'],
'birdstep_fieldname' => ['string', 'index'=>'int', 'col'=>'int'],
'birdstep_fieldnum' => ['int', 'index'=>'int'],
'birdstep_freeresult' => ['bool', 'index'=>'int'],
'birdstep_off_autocommit' => ['bool', 'index'=>'int'],
'birdstep_result' => ['', 'index'=>'int', 'col'=>''],
'birdstep_rollback' => ['bool', 'index'=>'int'],
'blenc_encrypt' => ['string', 'plaintext'=>'string', 'encodedfile'=>'string', 'encryption_key='=>'string'],
'boolval' => ['bool', 'value'=>'mixed'],
'bson_decode' => ['array', 'bson'=>'string'],
'bson_encode' => ['string', 'anything'=>'mixed'],
'bzclose' => ['bool', 'bz'=>'resource'],
'bzcompress' => ['string|int', 'data'=>'string', 'block_size='=>'int', 'work_factor='=>'int'],
'bzdecompress' => ['string|int', 'data'=>'string', 'use_less_memory='=>'int'],
'bzerrno' => ['int', 'bz'=>'resource'],
'bzerror' => ['array', 'bz'=>'resource'],
'bzerrstr' => ['string', 'bz'=>'resource'],
'bzflush' => ['bool', 'bz'=>'resource'],
'bzopen' => ['resource|false', 'file'=>'string|resource', 'mode'=>'string'],
'bzread' => ['string|false', 'bz'=>'resource', 'length='=>'int'],
'bzwrite' => ['int|false', 'bz'=>'resource', 'data'=>'string', 'length='=>'int'],
'CachingIterator::__construct' => ['void', 'iterator'=>'Iterator', 'flags='=>''],
'CachingIterator::__toString' => ['string'],
'CachingIterator::count' => ['int'],
'CachingIterator::current' => ['mixed'],
'CachingIterator::getCache' => ['array'],
'CachingIterator::getFlags' => ['int'],
'CachingIterator::getInnerIterator' => ['Iterator'],
'CachingIterator::hasNext' => ['bool'],
'CachingIterator::key' => ['int|string|float|bool'],
'CachingIterator::next' => ['void'],
'CachingIterator::offsetExists' => ['bool', 'index'=>'string'],
'CachingIterator::offsetGet' => ['mixed', 'index'=>'string'],
'CachingIterator::offsetSet' => ['void', 'index'=>'string', 'newval'=>'mixed'],
'CachingIterator::offsetUnset' => ['void', 'index'=>'string'],
'CachingIterator::rewind' => ['void'],
'CachingIterator::setFlags' => ['void', 'flags'=>'int'],
'CachingIterator::valid' => ['bool'],
'Cairo::availableFonts' => ['array'],
'Cairo::availableSurfaces' => ['array'],
'Cairo::statusToString' => ['string', 'status'=>'int'],
'Cairo::version' => ['int'],
'Cairo::versionString' => ['string'],
'cairo_append_path' => ['', 'path'=>'cairopath', 'context'=>'cairocontext'],
'cairo_arc' => ['', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'angle1'=>'float', 'angle2'=>'float', 'context'=>'cairocontext'],
'cairo_arc_negative' => ['', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'angle1'=>'float', 'angle2'=>'float', 'context'=>'cairocontext'],
'cairo_available_fonts' => ['array'],
'cairo_available_surfaces' => ['array'],
'cairo_clip' => ['', 'context'=>'cairocontext'],
'cairo_clip_extents' => ['array', 'context'=>'cairocontext'],
'cairo_clip_preserve' => ['', 'context'=>'cairocontext'],
'cairo_clip_rectangle_list' => ['array', 'context'=>'cairocontext'],
'cairo_close_path' => ['', 'context'=>'cairocontext'],
'cairo_copy_page' => ['', 'context'=>'cairocontext'],
'cairo_copy_path' => ['CairoPath', 'context'=>'cairocontext'],
'cairo_copy_path_flat' => ['CairoPath', 'context'=>'cairocontext'],
'cairo_create' => ['CairoContext', 'surface'=>'cairosurface'],
'cairo_curve_to' => ['', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float', 'context'=>'cairocontext'],
'cairo_device_to_user' => ['array', 'x'=>'float', 'y'=>'float', 'context'=>'cairocontext'],
'cairo_device_to_user_distance' => ['array', 'x'=>'float', 'y'=>'float', 'context'=>'cairocontext'],
'cairo_fill' => ['', 'context'=>'cairocontext'],
'cairo_fill_extents' => ['array', 'context'=>'cairocontext'],
'cairo_fill_preserve' => ['', 'context'=>'cairocontext'],
'cairo_font_extents' => ['array', 'context'=>'cairocontext'],
'cairo_font_face_get_type' => ['int', 'fontface'=>'cairofontface'],
'cairo_font_face_status' => ['int', 'fontface'=>'cairofontface'],
'cairo_font_options_create' => ['CairoFontOptions'],
'cairo_font_options_equal' => ['bool', 'options'=>'cairofontoptions', 'other'=>'cairofontoptions'],
'cairo_font_options_get_antialias' => ['int', 'options'=>'cairofontoptions'],
'cairo_font_options_get_hint_metrics' => ['int', 'options'=>'cairofontoptions'],
'cairo_font_options_get_hint_style' => ['int', 'options'=>'cairofontoptions'],
'cairo_font_options_get_subpixel_order' => ['int', 'options'=>'cairofontoptions'],
'cairo_font_options_hash' => ['int', 'options'=>'cairofontoptions'],
'cairo_font_options_merge' => ['void', 'options'=>'cairofontoptions', 'other'=>'cairofontoptions'],
'cairo_font_options_set_antialias' => ['void', 'options'=>'cairofontoptions', 'antialias'=>'int'],
'cairo_font_options_set_hint_metrics' => ['void', 'options'=>'cairofontoptions', 'hint_metrics'=>'int'],
'cairo_font_options_set_hint_style' => ['void', 'options'=>'cairofontoptions', 'hint_style'=>'int'],
'cairo_font_options_set_subpixel_order' => ['void', 'options'=>'cairofontoptions', 'subpixel_order'=>'int'],
'cairo_font_options_status' => ['int', 'options'=>'cairofontoptions'],
'cairo_format_stride_for_width' => ['int', 'format'=>'int', 'width'=>'int'],
'cairo_get_antialias' => ['int', 'context'=>'cairocontext'],
'cairo_get_current_point' => ['array', 'context'=>'cairocontext'],
'cairo_get_dash' => ['array', 'context'=>'cairocontext'],
'cairo_get_dash_count' => ['int', 'context'=>'cairocontext'],
'cairo_get_fill_rule' => ['int', 'context'=>'cairocontext'],
'cairo_get_font_face' => ['', 'context'=>'cairocontext'],
'cairo_get_font_matrix' => ['', 'context'=>'cairocontext'],
'cairo_get_font_options' => ['', 'context'=>'cairocontext'],
'cairo_get_group_target' => ['', 'context'=>'cairocontext'],
'cairo_get_line_cap' => ['int', 'context'=>'cairocontext'],
'cairo_get_line_join' => ['int', 'context'=>'cairocontext'],
'cairo_get_line_width' => ['float', 'context'=>'cairocontext'],
'cairo_get_matrix' => ['', 'context'=>'cairocontext'],
'cairo_get_miter_limit' => ['float', 'context'=>'cairocontext'],
'cairo_get_operator' => ['int', 'context'=>'cairocontext'],
'cairo_get_scaled_font' => ['', 'context'=>'cairocontext'],
'cairo_get_source' => ['', 'context'=>'cairocontext'],
'cairo_get_target' => ['', 'context'=>'cairocontext'],
'cairo_get_tolerance' => ['float', 'context'=>'cairocontext'],
'cairo_glyph_path' => ['', 'glyphs'=>'array', 'context'=>'cairocontext'],
'cairo_has_current_point' => ['bool', 'context'=>'cairocontext'],
'cairo_identity_matrix' => ['', 'context'=>'cairocontext'],
'cairo_image_surface_create' => ['CairoImageSurface', 'format'=>'int', 'width'=>'int', 'height'=>'int'],
'cairo_image_surface_create_for_data' => ['CairoImageSurface', 'data'=>'string', 'format'=>'int', 'width'=>'int', 'height'=>'int', 'stride='=>'int'],
'cairo_image_surface_create_from_png' => ['CairoImageSurface', 'file'=>'string'],
'cairo_image_surface_get_data' => ['string', 'surface'=>'cairoimagesurface'],
'cairo_image_surface_get_format' => ['int', 'surface'=>'cairoimagesurface'],
'cairo_image_surface_get_height' => ['int', 'surface'=>'cairoimagesurface'],
'cairo_image_surface_get_stride' => ['int', 'surface'=>'cairoimagesurface'],
'cairo_image_surface_get_width' => ['int', 'surface'=>'cairoimagesurface'],
'cairo_in_fill' => ['bool', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_in_stroke' => ['bool', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_line_to' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_mask' => ['', 'pattern'=>'cairopattern', 'context'=>'cairocontext'],
'cairo_mask_surface' => ['', 'surface'=>'cairosurface', 'x='=>'string', 'y='=>'string', 'context='=>'cairocontext'],
'cairo_matrix_create_scale' => ['object', 'sx'=>'float', 'sy'=>'float'],
'cairo_matrix_init' => ['object', 'xx='=>'float', 'yx='=>'float', 'xy='=>'float', 'yy='=>'float', 'x0='=>'float', 'y0='=>'float'],
'cairo_matrix_init_identity' => ['object'],
'cairo_matrix_init_rotate' => ['object', 'radians'=>'float'],
'cairo_matrix_init_scale' => ['object', 'sx'=>'float', 'sy'=>'float'],
'cairo_matrix_init_translate' => ['object', 'tx'=>'float', 'ty'=>'float'],
'cairo_matrix_invert' => ['void', 'matrix'=>'cairomatrix'],
'cairo_matrix_multiply' => ['CairoMatrix', 'matrix1'=>'cairomatrix', 'matrix2'=>'cairomatrix'],
'cairo_matrix_rotate' => ['', 'matrix'=>'cairomatrix', 'radians'=>'float'],
'cairo_matrix_scale' => ['', 'sx'=>'float', 'sy'=>'float', 'context'=>'cairocontext'],
'cairo_matrix_transform_distance' => ['array', 'matrix'=>'cairomatrix', 'dx'=>'float', 'dy'=>'float'],
'cairo_matrix_transform_point' => ['array', 'matrix'=>'cairomatrix', 'dx'=>'float', 'dy'=>'float'],
'cairo_matrix_translate' => ['void', 'matrix'=>'cairomatrix', 'tx'=>'float', 'ty'=>'float'],
'cairo_move_to' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_new_path' => ['', 'context'=>'cairocontext'],
'cairo_new_sub_path' => ['', 'context'=>'cairocontext'],
'cairo_paint' => ['', 'context'=>'cairocontext'],
'cairo_paint_with_alpha' => ['', 'alpha'=>'string', 'context'=>'cairocontext'],
'cairo_path_extents' => ['array', 'context'=>'cairocontext'],
'cairo_pattern_add_color_stop_rgb' => ['void', 'pattern'=>'cairogradientpattern', 'offset'=>'float', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'cairo_pattern_add_color_stop_rgba' => ['void', 'pattern'=>'cairogradientpattern', 'offset'=>'float', 'red'=>'float', 'green'=>'float', 'blue'=>'float', 'alpha'=>'float'],
'cairo_pattern_create_for_surface' => ['CairoPattern', 'surface'=>'cairosurface'],
'cairo_pattern_create_linear' => ['CairoPattern', 'x0'=>'float', 'y0'=>'float', 'x1'=>'float', 'y1'=>'float'],
'cairo_pattern_create_radial' => ['CairoPattern', 'x0'=>'float', 'y0'=>'float', 'r0'=>'float', 'x1'=>'float', 'y1'=>'float', 'r1'=>'float'],
'cairo_pattern_create_rgb' => ['CairoPattern', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'cairo_pattern_create_rgba' => ['CairoPattern', 'red'=>'float', 'green'=>'float', 'blue'=>'float', 'alpha'=>'float'],
'cairo_pattern_get_color_stop_count' => ['int', 'pattern'=>'cairogradientpattern'],
'cairo_pattern_get_color_stop_rgba' => ['array', 'pattern'=>'cairogradientpattern', 'index'=>'int'],
'cairo_pattern_get_extend' => ['int', 'pattern'=>'string'],
'cairo_pattern_get_filter' => ['int', 'pattern'=>'cairosurfacepattern'],
'cairo_pattern_get_linear_points' => ['array', 'pattern'=>'cairolineargradient'],
'cairo_pattern_get_matrix' => ['CairoMatrix', 'pattern'=>'cairopattern'],
'cairo_pattern_get_radial_circles' => ['array', 'pattern'=>'cairoradialgradient'],
'cairo_pattern_get_rgba' => ['array', 'pattern'=>'cairosolidpattern'],
'cairo_pattern_get_surface' => ['CairoSurface', 'pattern'=>'cairosurfacepattern'],
'cairo_pattern_get_type' => ['int', 'pattern'=>'cairopattern'],
'cairo_pattern_set_extend' => ['void', 'pattern'=>'string', 'extend'=>'string'],
'cairo_pattern_set_filter' => ['void', 'pattern'=>'cairosurfacepattern', 'filter'=>'int'],
'cairo_pattern_set_matrix' => ['void', 'pattern'=>'cairopattern', 'matrix'=>'cairomatrix'],
'cairo_pattern_status' => ['int', 'pattern'=>'cairopattern'],
'cairo_pdf_surface_create' => ['CairoPdfSurface', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'cairo_pdf_surface_set_size' => ['void', 'surface'=>'cairopdfsurface', 'width'=>'float', 'height'=>'float'],
'cairo_pop_group' => ['', 'context'=>'cairocontext'],
'cairo_pop_group_to_source' => ['', 'context'=>'cairocontext'],
'cairo_ps_get_levels' => ['array'],
'cairo_ps_level_to_string' => ['string', 'level'=>'int'],
'cairo_ps_surface_create' => ['CairoPsSurface', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'cairo_ps_surface_dsc_begin_page_setup' => ['void', 'surface'=>'cairopssurface'],
'cairo_ps_surface_dsc_begin_setup' => ['void', 'surface'=>'cairopssurface'],
'cairo_ps_surface_dsc_comment' => ['void', 'surface'=>'cairopssurface', 'comment'=>'string'],
'cairo_ps_surface_get_eps' => ['bool', 'surface'=>'cairopssurface'],
'cairo_ps_surface_restrict_to_level' => ['void', 'surface'=>'cairopssurface', 'level'=>'int'],
'cairo_ps_surface_set_eps' => ['void', 'surface'=>'cairopssurface', 'level'=>'bool'],
'cairo_ps_surface_set_size' => ['void', 'surface'=>'cairopssurface', 'width'=>'float', 'height'=>'float'],
'cairo_push_group' => ['', 'context'=>'cairocontext'],
'cairo_push_group_with_content' => ['', 'content'=>'string', 'context'=>'cairocontext'],
'cairo_rectangle' => ['', 'x'=>'string', 'y'=>'string', 'width'=>'string', 'height'=>'string', 'context'=>'cairocontext'],
'cairo_rel_curve_to' => ['', 'x1'=>'string', 'y1'=>'string', 'x2'=>'string', 'y2'=>'string', 'x3'=>'string', 'y3'=>'string', 'context'=>'cairocontext'],
'cairo_rel_line_to' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_rel_move_to' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_reset_clip' => ['', 'context'=>'cairocontext'],
'cairo_restore' => ['', 'context'=>'cairocontext'],
'cairo_rotate' => ['', 'sx'=>'string', 'sy'=>'string', 'context'=>'cairocontext', 'angle'=>'string'],
'cairo_save' => ['', 'context'=>'cairocontext'],
'cairo_scale' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_scaled_font_create' => ['CairoScaledFont', 'fontface'=>'cairofontface', 'matrix'=>'cairomatrix', 'ctm'=>'cairomatrix', 'fontoptions'=>'cairofontoptions'],
'cairo_scaled_font_extents' => ['array', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_ctm' => ['CairoMatrix', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_font_face' => ['CairoFontFace', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_font_matrix' => ['CairoFontOptions', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_font_options' => ['CairoFontOptions', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_scale_matrix' => ['CairoMatrix', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_type' => ['int', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_glyph_extents' => ['array', 'scaledfont'=>'cairoscaledfont', 'glyphs'=>'array'],
'cairo_scaled_font_status' => ['int', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_text_extents' => ['array', 'scaledfont'=>'cairoscaledfont', 'text'=>'string'],
'cairo_select_font_face' => ['', 'family'=>'string', 'slant='=>'string', 'weight='=>'string', 'context='=>'cairocontext'],
'cairo_set_antialias' => ['', 'antialias='=>'string', 'context='=>'cairocontext'],
'cairo_set_dash' => ['', 'dashes'=>'array', 'offset='=>'string', 'context='=>'cairocontext'],
'cairo_set_fill_rule' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'cairo_set_font_face' => ['', 'fontface'=>'cairofontface', 'context'=>'cairocontext'],
'cairo_set_font_matrix' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'cairo_set_font_options' => ['', 'fontoptions'=>'cairofontoptions', 'context'=>'cairocontext'],
'cairo_set_font_size' => ['', 'size'=>'string', 'context'=>'cairocontext'],
'cairo_set_line_cap' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'cairo_set_line_join' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'cairo_set_line_width' => ['', 'width'=>'string', 'context'=>'cairocontext'],
'cairo_set_matrix' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'cairo_set_miter_limit' => ['', 'limit'=>'string', 'context'=>'cairocontext'],
'cairo_set_operator' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'cairo_set_scaled_font' => ['', 'scaledfont'=>'cairoscaledfont', 'context'=>'cairocontext'],
'cairo_set_source' => ['', 'red'=>'string', 'green'=>'string', 'blue'=>'string', 'alpha'=>'string', 'context'=>'cairocontext', 'pattern'=>'cairopattern'],
'cairo_set_source_surface' => ['', 'surface'=>'cairosurface', 'x='=>'string', 'y='=>'string', 'context='=>'cairocontext'],
'cairo_set_tolerance' => ['', 'tolerance'=>'string', 'context'=>'cairocontext'],
'cairo_show_page' => ['', 'context'=>'cairocontext'],
'cairo_show_text' => ['', 'text'=>'string', 'context'=>'cairocontext'],
'cairo_status' => ['int', 'context'=>'cairocontext'],
'cairo_status_to_string' => ['string', 'status'=>'int'],
'cairo_stroke' => ['', 'context'=>'cairocontext'],
'cairo_stroke_extents' => ['array', 'context'=>'cairocontext'],
'cairo_stroke_preserve' => ['', 'context'=>'cairocontext'],
'cairo_surface_copy_page' => ['void', 'surface'=>'cairosurface'],
'cairo_surface_create_similar' => ['CairoSurface', 'surface'=>'cairosurface', 'content'=>'int', 'width'=>'float', 'height'=>'float'],
'cairo_surface_finish' => ['void', 'surface'=>'cairosurface'],
'cairo_surface_flush' => ['void', 'surface'=>'cairosurface'],
'cairo_surface_get_content' => ['int', 'surface'=>'cairosurface'],
'cairo_surface_get_device_offset' => ['array', 'surface'=>'cairosurface'],
'cairo_surface_get_font_options' => ['CairoFontOptions', 'surface'=>'cairosurface'],
'cairo_surface_get_type' => ['int', 'surface'=>'cairosurface'],
'cairo_surface_mark_dirty' => ['void', 'surface'=>'cairosurface'],
'cairo_surface_mark_dirty_rectangle' => ['void', 'surface'=>'cairosurface', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'cairo_surface_set_device_offset' => ['void', 'surface'=>'cairosurface', 'x'=>'float', 'y'=>'float'],
'cairo_surface_set_fallback_resolution' => ['void', 'surface'=>'cairosurface', 'x'=>'float', 'y'=>'float'],
'cairo_surface_show_page' => ['void', 'surface'=>'cairosurface'],
'cairo_surface_status' => ['int', 'surface'=>'cairosurface'],
'cairo_surface_write_to_png' => ['void', 'surface'=>'cairosurface', 'stream'=>'resource'],
'cairo_svg_get_versions' => ['array'],
'cairo_svg_surface_create' => ['CairoSvgSurface', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'cairo_svg_surface_get_versions' => ['array'],
'cairo_svg_surface_restrict_to_version' => ['void', 'surface'=>'cairosvgsurface', 'version'=>'int'],
'cairo_svg_version_to_string' => ['string', 'version'=>'int'],
'cairo_text_extents' => ['array', 'text'=>'string', 'context'=>'cairocontext'],
'cairo_text_path' => ['', 'string'=>'string', 'context'=>'cairocontext', 'text'=>'string'],
'cairo_transform' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'cairo_translate' => ['', 'tx'=>'string', 'ty'=>'string', 'context'=>'cairocontext', 'x'=>'string', 'y'=>'string'],
'cairo_user_to_device' => ['array', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_user_to_device_distance' => ['array', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_version' => ['int'],
'cairo_version_string' => ['string'],
'CairoContext::__construct' => ['void', 'surface'=>'CairoSurface'],
'CairoContext::appendPath' => ['', 'path'=>'cairopath', 'context'=>'cairocontext'],
'CairoContext::arc' => ['', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'angle1'=>'float', 'angle2'=>'float', 'context'=>'cairocontext'],
'CairoContext::arcNegative' => ['', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'angle1'=>'float', 'angle2'=>'float', 'context'=>'cairocontext'],
'CairoContext::clip' => ['', 'context'=>'cairocontext'],
'CairoContext::clipExtents' => ['array', 'context'=>'cairocontext'],
'CairoContext::clipPreserve' => ['', 'context'=>'cairocontext'],
'CairoContext::clipRectangleList' => ['array', 'context'=>'cairocontext'],
'CairoContext::closePath' => ['', 'context'=>'cairocontext'],
'CairoContext::copyPage' => ['', 'context'=>'cairocontext'],
'CairoContext::copyPath' => ['CairoPath', 'context'=>'cairocontext'],
'CairoContext::copyPathFlat' => ['CairoPath', 'context'=>'cairocontext'],
'CairoContext::curveTo' => ['', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float', 'context'=>'cairocontext'],
'CairoContext::deviceToUser' => ['array', 'x'=>'float', 'y'=>'float', 'context'=>'cairocontext'],
'CairoContext::deviceToUserDistance' => ['array', 'x'=>'float', 'y'=>'float', 'context'=>'cairocontext'],
'CairoContext::fill' => ['', 'context'=>'cairocontext'],
'CairoContext::fillExtents' => ['array', 'context'=>'cairocontext'],
'CairoContext::fillPreserve' => ['', 'context'=>'cairocontext'],
'CairoContext::fontExtents' => ['array', 'context'=>'cairocontext'],
'CairoContext::getAntialias' => ['int', 'context'=>'cairocontext'],
'CairoContext::getCurrentPoint' => ['array', 'context'=>'cairocontext'],
'CairoContext::getDash' => ['array', 'context'=>'cairocontext'],
'CairoContext::getDashCount' => ['int', 'context'=>'cairocontext'],
'CairoContext::getFillRule' => ['int', 'context'=>'cairocontext'],
'CairoContext::getFontFace' => ['', 'context'=>'cairocontext'],
'CairoContext::getFontMatrix' => ['', 'context'=>'cairocontext'],
'CairoContext::getFontOptions' => ['', 'context'=>'cairocontext'],
'CairoContext::getGroupTarget' => ['', 'context'=>'cairocontext'],
'CairoContext::getLineCap' => ['int', 'context'=>'cairocontext'],
'CairoContext::getLineJoin' => ['int', 'context'=>'cairocontext'],
'CairoContext::getLineWidth' => ['float', 'context'=>'cairocontext'],
'CairoContext::getMatrix' => ['', 'context'=>'cairocontext'],
'CairoContext::getMiterLimit' => ['float', 'context'=>'cairocontext'],
'CairoContext::getOperator' => ['int', 'context'=>'cairocontext'],
'CairoContext::getScaledFont' => ['', 'context'=>'cairocontext'],
'CairoContext::getSource' => ['', 'context'=>'cairocontext'],
'CairoContext::getTarget' => ['', 'context'=>'cairocontext'],
'CairoContext::getTolerance' => ['float', 'context'=>'cairocontext'],
'CairoContext::glyphPath' => ['', 'glyphs'=>'array', 'context'=>'cairocontext'],
'CairoContext::hasCurrentPoint' => ['bool', 'context'=>'cairocontext'],
'CairoContext::identityMatrix' => ['', 'context'=>'cairocontext'],
'CairoContext::inFill' => ['bool', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::inStroke' => ['bool', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::lineTo' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::mask' => ['', 'pattern'=>'cairopattern', 'context'=>'cairocontext'],
'CairoContext::maskSurface' => ['', 'surface'=>'cairosurface', 'x='=>'string', 'y='=>'string', 'context='=>'cairocontext'],
'CairoContext::moveTo' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::newPath' => ['', 'context'=>'cairocontext'],
'CairoContext::newSubPath' => ['', 'context'=>'cairocontext'],
'CairoContext::paint' => ['', 'context'=>'cairocontext'],
'CairoContext::paintWithAlpha' => ['', 'alpha'=>'string', 'context'=>'cairocontext'],
'CairoContext::pathExtents' => ['array', 'context'=>'cairocontext'],
'CairoContext::popGroup' => ['', 'context'=>'cairocontext'],
'CairoContext::popGroupToSource' => ['', 'context'=>'cairocontext'],
'CairoContext::pushGroup' => ['', 'context'=>'cairocontext'],
'CairoContext::pushGroupWithContent' => ['', 'content'=>'string', 'context'=>'cairocontext'],
'CairoContext::rectangle' => ['', 'x'=>'string', 'y'=>'string', 'width'=>'string', 'height'=>'string', 'context'=>'cairocontext'],
'CairoContext::relCurveTo' => ['', 'x1'=>'string', 'y1'=>'string', 'x2'=>'string', 'y2'=>'string', 'x3'=>'string', 'y3'=>'string', 'context'=>'cairocontext'],
'CairoContext::relLineTo' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::relMoveTo' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::resetClip' => ['', 'context'=>'cairocontext'],
'CairoContext::restore' => ['', 'context'=>'cairocontext'],
'CairoContext::rotate' => ['', 'angle'=>'string', 'context'=>'cairocontext'],
'CairoContext::save' => ['', 'context'=>'cairocontext'],
'CairoContext::scale' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::selectFontFace' => ['', 'family'=>'string', 'slant='=>'string', 'weight='=>'string', 'context='=>'cairocontext'],
'CairoContext::setAntialias' => ['', 'antialias='=>'string', 'context='=>'cairocontext'],
'CairoContext::setDash' => ['', 'dashes'=>'array', 'offset='=>'string', 'context='=>'cairocontext'],
'CairoContext::setFillRule' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'CairoContext::setFontFace' => ['', 'fontface'=>'cairofontface', 'context'=>'cairocontext'],
'CairoContext::setFontMatrix' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'CairoContext::setFontOptions' => ['', 'fontoptions'=>'cairofontoptions', 'context'=>'cairocontext'],
'CairoContext::setFontSize' => ['', 'size'=>'string', 'context'=>'cairocontext'],
'CairoContext::setLineCap' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'CairoContext::setLineJoin' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'CairoContext::setLineWidth' => ['', 'width'=>'string', 'context'=>'cairocontext'],
'CairoContext::setMatrix' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'CairoContext::setMiterLimit' => ['', 'limit'=>'string', 'context'=>'cairocontext'],
'CairoContext::setOperator' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'CairoContext::setScaledFont' => ['', 'scaledfont'=>'cairoscaledfont', 'context'=>'cairocontext'],
'CairoContext::setSource' => ['', 'pattern'=>'cairopattern', 'context'=>'cairocontext'],
'CairoContext::setSourceRGB' => ['', 'red'=>'string', 'green'=>'string', 'blue'=>'string', 'context'=>'cairocontext', 'pattern'=>'cairopattern'],
'CairoContext::setSourceRGBA' => ['', 'red'=>'string', 'green'=>'string', 'blue'=>'string', 'alpha'=>'string', 'context'=>'cairocontext', 'pattern'=>'cairopattern'],
'CairoContext::setSourceSurface' => ['', 'surface'=>'cairosurface', 'x='=>'string', 'y='=>'string', 'context='=>'cairocontext'],
'CairoContext::setTolerance' => ['', 'tolerance'=>'string', 'context'=>'cairocontext'],
'CairoContext::showPage' => ['', 'context'=>'cairocontext'],
'CairoContext::showText' => ['', 'text'=>'string', 'context'=>'cairocontext'],
'CairoContext::status' => ['int', 'context'=>'cairocontext'],
'CairoContext::stroke' => ['', 'context'=>'cairocontext'],
'CairoContext::strokeExtents' => ['array', 'context'=>'cairocontext'],
'CairoContext::strokePreserve' => ['', 'context'=>'cairocontext'],
'CairoContext::textExtents' => ['array', 'text'=>'string', 'context'=>'cairocontext'],
'CairoContext::textPath' => ['', 'string'=>'string', 'context'=>'cairocontext', 'text'=>'string'],
'CairoContext::transform' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'CairoContext::translate' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::userToDevice' => ['array', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::userToDeviceDistance' => ['array', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoFontFace::__construct' => ['void'],
'CairoFontFace::getType' => ['int'],
'CairoFontFace::status' => ['int', 'fontface'=>'cairofontface'],
'CairoFontOptions::__construct' => ['void'],
'CairoFontOptions::equal' => ['bool', 'other'=>'string'],
'CairoFontOptions::getAntialias' => ['int', 'context'=>'cairocontext'],
'CairoFontOptions::getHintMetrics' => ['int'],
'CairoFontOptions::getHintStyle' => ['int'],
'CairoFontOptions::getSubpixelOrder' => ['int'],
'CairoFontOptions::hash' => ['int'],
'CairoFontOptions::merge' => ['void', 'other'=>'string'],
'CairoFontOptions::setAntialias' => ['', 'antialias='=>'string', 'context='=>'cairocontext'],
'CairoFontOptions::setHintMetrics' => ['void', 'hint_metrics'=>'string'],
'CairoFontOptions::setHintStyle' => ['void', 'hint_style'=>'string'],
'CairoFontOptions::setSubpixelOrder' => ['void', 'subpixel_order'=>'string'],
'CairoFontOptions::status' => ['int', 'context'=>'cairocontext'],
'CairoFormat::strideForWidth' => ['int', 'format'=>'int', 'width'=>'int'],
'CairoGradientPattern::addColorStopRgb' => ['void', 'offset'=>'string', 'red'=>'string', 'green'=>'string', 'blue'=>'string'],
'CairoGradientPattern::addColorStopRgba' => ['void', 'offset'=>'string', 'red'=>'string', 'green'=>'string', 'blue'=>'string', 'alpha'=>'string'],
'CairoGradientPattern::getColorStopCount' => ['int'],
'CairoGradientPattern::getColorStopRgba' => ['array', 'index'=>'string'],
'CairoGradientPattern::getExtend' => ['int'],
'CairoGradientPattern::setExtend' => ['void', 'extend'=>'int'],
'CairoImageSurface::__construct' => ['void', 'format'=>'int', 'width'=>'int', 'height'=>'int'],
'CairoImageSurface::createForData' => ['void', 'data'=>'string', 'format'=>'int', 'width'=>'int', 'height'=>'int', 'stride='=>'int'],
'CairoImageSurface::createFromPng' => ['CairoImageSurface', 'file'=>'string'],
'CairoImageSurface::getData' => ['string'],
'CairoImageSurface::getFormat' => ['int'],
'CairoImageSurface::getHeight' => ['int'],
'CairoImageSurface::getStride' => ['int'],
'CairoImageSurface::getWidth' => ['int'],
'CairoLinearGradient::__construct' => ['void', 'x0'=>'float', 'y0'=>'float', 'x1'=>'float', 'y1'=>'float'],
'CairoLinearGradient::getPoints' => ['array'],
'CairoMatrix::__construct' => ['void', 'xx='=>'float', 'yx='=>'float', 'xy='=>'float', 'yy='=>'float', 'x0='=>'float', 'y0='=>'float'],
'CairoMatrix::initIdentity' => ['object'],
'CairoMatrix::initRotate' => ['object', 'radians'=>'float'],
'CairoMatrix::initScale' => ['object', 'sx'=>'float', 'sy'=>'float'],
'CairoMatrix::initTranslate' => ['object', 'tx'=>'float', 'ty'=>'float'],
'CairoMatrix::invert' => ['void'],
'CairoMatrix::multiply' => ['CairoMatrix', 'matrix1'=>'cairomatrix', 'matrix2'=>'cairomatrix'],
'CairoMatrix::rotate' => ['', 'sx'=>'string', 'sy'=>'string', 'context'=>'cairocontext', 'angle'=>'string'],
'CairoMatrix::scale' => ['', 'sx'=>'float', 'sy'=>'float', 'context'=>'cairocontext'],
'CairoMatrix::transformDistance' => ['array', 'dx'=>'string', 'dy'=>'string'],
'CairoMatrix::transformPoint' => ['array', 'dx'=>'string', 'dy'=>'string'],
'CairoMatrix::translate' => ['', 'tx'=>'string', 'ty'=>'string', 'context'=>'cairocontext', 'x'=>'string', 'y'=>'string'],
'CairoPattern::__construct' => ['void'],
'CairoPattern::getMatrix' => ['', 'context'=>'cairocontext'],
'CairoPattern::getType' => ['int'],
'CairoPattern::setMatrix' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'CairoPattern::status' => ['int', 'context'=>'cairocontext'],
'CairoPdfSurface::__construct' => ['void', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'CairoPdfSurface::setSize' => ['void', 'width'=>'string', 'height'=>'string'],
'CairoPsSurface::__construct' => ['void', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'CairoPsSurface::dscBeginPageSetup' => ['void'],
'CairoPsSurface::dscBeginSetup' => ['void'],
'CairoPsSurface::dscComment' => ['void', 'comment'=>'string'],
'CairoPsSurface::getEps' => ['bool'],
'CairoPsSurface::getLevels' => ['array'],
'CairoPsSurface::levelToString' => ['string', 'level'=>'int'],
'CairoPsSurface::restrictToLevel' => ['void', 'level'=>'string'],
'CairoPsSurface::setEps' => ['void', 'level'=>'string'],
'CairoPsSurface::setSize' => ['void', 'width'=>'string', 'height'=>'string'],
'CairoRadialGradient::__construct' => ['void', 'x0'=>'float', 'y0'=>'float', 'r0'=>'float', 'x1'=>'float', 'y1'=>'float', 'r1'=>'float'],
'CairoRadialGradient::getCircles' => ['array'],
'CairoScaledFont::__construct' => ['void', 'font_face'=>'CairoFontFace', 'matrix'=>'CairoMatrix', 'ctm'=>'CairoMatrix', 'options'=>'CairoFontOptions'],
'CairoScaledFont::extents' => ['array'],
'CairoScaledFont::getCtm' => ['CairoMatrix'],
'CairoScaledFont::getFontFace' => ['', 'context'=>'cairocontext'],
'CairoScaledFont::getFontMatrix' => ['', 'context'=>'cairocontext'],
'CairoScaledFont::getFontOptions' => ['', 'context'=>'cairocontext'],
'CairoScaledFont::getScaleMatrix' => ['void'],
'CairoScaledFont::getType' => ['int'],
'CairoScaledFont::glyphExtents' => ['array', 'glyphs'=>'string'],
'CairoScaledFont::status' => ['int', 'context'=>'cairocontext'],
'CairoScaledFont::textExtents' => ['array', 'text'=>'string', 'context'=>'cairocontext'],
'CairoSolidPattern::__construct' => ['void', 'red'=>'float', 'green'=>'float', 'blue'=>'float', 'alpha='=>'float'],
'CairoSolidPattern::getRgba' => ['array'],
'CairoSurface::__construct' => ['void'],
'CairoSurface::copyPage' => ['', 'context'=>'cairocontext'],
'CairoSurface::createSimilar' => ['void', 'other'=>'cairosurface', 'content'=>'int', 'width'=>'string', 'height'=>'string'],
'CairoSurface::finish' => ['void'],
'CairoSurface::flush' => ['void'],
'CairoSurface::getContent' => ['int'],
'CairoSurface::getDeviceOffset' => ['array'],
'CairoSurface::getFontOptions' => ['', 'context'=>'cairocontext'],
'CairoSurface::getType' => ['int'],
'CairoSurface::markDirty' => ['void'],
'CairoSurface::markDirtyRectangle' => ['void', 'x'=>'string', 'y'=>'string', 'width'=>'string', 'height'=>'string'],
'CairoSurface::setDeviceOffset' => ['void', 'x'=>'string', 'y'=>'string'],
'CairoSurface::setFallbackResolution' => ['void', 'x'=>'string', 'y'=>'string'],
'CairoSurface::showPage' => ['', 'context'=>'cairocontext'],
'CairoSurface::status' => ['int', 'context'=>'cairocontext'],
'CairoSurface::writeToPng' => ['void', 'file'=>'string'],
'CairoSurfacePattern::__construct' => ['void', 'surface'=>'CairoSurface'],
'CairoSurfacePattern::getExtend' => ['int'],
'CairoSurfacePattern::getFilter' => ['int'],
'CairoSurfacePattern::getSurface' => ['void'],
'CairoSurfacePattern::setExtend' => ['void', 'extend'=>'int'],
'CairoSurfacePattern::setFilter' => ['void', 'filter'=>'string'],
'CairoSvgSurface::__construct' => ['void', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'CairoSvgSurface::getVersions' => ['array'],
'CairoSvgSurface::restrictToVersion' => ['void', 'version'=>'string'],
'CairoSvgSurface::versionToString' => ['string', 'version'=>'int'],
'cal_days_in_month' => ['int', 'calendar'=>'int', 'month'=>'int', 'year'=>'int'],
'cal_from_jd' => ['false|array{date:string,month:int,day:int,year:int,dow:int,abbrevdayname:string,dayname:string,abbrevmonth:string,monthname:string}', 'julian_day'=>'int', 'calendar'=>'int'],
'cal_info' => ['array', 'calendar='=>'int'],
'cal_to_jd' => ['int', 'calendar'=>'int', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'calcul_hmac' => ['string', 'clent'=>'string', 'siretcode'=>'string', 'price'=>'string', 'reference'=>'string', 'validity'=>'string', 'taxation'=>'string', 'devise'=>'string', 'language'=>'string'],
'calculhmac' => ['string', 'clent'=>'string', 'data'=>'string'],
'call_user_func' => ['mixed|false', 'callback'=>'callable', '...args='=>'mixed'],
'call_user_func_array' => ['mixed|false', 'callback'=>'callable', 'args'=>'list<mixed>'],
'call_user_method' => ['mixed', 'method_name'=>'string', 'object'=>'object', 'parameter='=>'mixed', '...args='=>'mixed'],
'call_user_method_array' => ['mixed', 'method_name'=>'string', 'object'=>'object', 'params'=>'list<mixed>'],
'CallbackFilterIterator::__construct' => ['void', 'iterator'=>'Iterator', 'func'=>'callable(mixed):bool|callable(mixed,mixed):bool|callable(mixed,mixed,mixed):bool'],
'CallbackFilterIterator::accept' => ['bool'],
'CallbackFilterIterator::current' => ['mixed'],
'CallbackFilterIterator::getInnerIterator' => ['Iterator'],
'CallbackFilterIterator::key' => ['mixed'],
'CallbackFilterIterator::next' => ['void'],
'CallbackFilterIterator::rewind' => ['void'],
'CallbackFilterIterator::valid' => ['bool'],
'ceil' => ['float', 'num'=>'float'],
'chdb::__construct' => ['void', 'pathname'=>'string'],
'chdb::get' => ['string', 'key'=>'string'],
'chdb_create' => ['bool', 'pathname'=>'string', 'data'=>'array'],
'chdir' => ['bool', 'directory'=>'string'],
'checkdate' => ['bool', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'checkdnsrr' => ['bool', 'hostname'=>'string', 'type='=>'string'],
'chgrp' => ['bool', 'filename'=>'string', 'group'=>'string|int'],
'chmod' => ['bool', 'filename'=>'string', 'permissions'=>'int'],
'chop' => ['string', 'string'=>'string', 'characters='=>'string'],
'chown' => ['bool', 'filename'=>'string', 'user'=>'string|int'],
'chr' => ['string', 'codepoint'=>'int'],
'chroot' => ['bool', 'directory'=>'string'],
'chunk_split' => ['string', 'string'=>'string', 'length='=>'int', 'separator='=>'string'],
'class_alias' => ['bool', 'class'=>'string', 'alias'=>'string', 'autoload='=>'bool'],
'class_exists' => ['bool', 'class'=>'string', 'autoload='=>'bool'],
'class_implements' => ['array<string,string>|false', 'object_or_class'=>'object|string', 'autoload='=>'bool'],
'class_parents' => ['array<string, class-string>|false', 'object_or_class'=>'object|string', 'autoload='=>'bool'],
'class_uses' => ['array<string,string>|false', 'object_or_class'=>'object|string', 'autoload='=>'bool'],
'classkit_import' => ['array', 'filename'=>'string'],
'classkit_method_add' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'args'=>'string', 'code'=>'string', 'flags='=>'int'],
'classkit_method_copy' => ['bool', 'dclass'=>'string', 'dmethod'=>'string', 'sclass'=>'string', 'smethod='=>'string'],
'classkit_method_redefine' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'args'=>'string', 'code'=>'string', 'flags='=>'int'],
'classkit_method_remove' => ['bool', 'classname'=>'string', 'methodname'=>'string'],
'classkit_method_rename' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'newname'=>'string'],
'classObj::__construct' => ['void', 'layer'=>'layerObj', 'class'=>'classObj'],
'classObj::addLabel' => ['int', 'label'=>'labelObj'],
'classObj::convertToString' => ['string'],
'classObj::createLegendIcon' => ['imageObj', 'width'=>'int', 'height'=>'int'],
'classObj::deletestyle' => ['int', 'index'=>'int'],
'classObj::drawLegendIcon' => ['int', 'width'=>'int', 'height'=>'int', 'im'=>'imageObj', 'dstX'=>'int', 'dstY'=>'int'],
'classObj::free' => ['void'],
'classObj::getExpressionString' => ['string'],
'classObj::getLabel' => ['labelObj', 'index'=>'int'],
'classObj::getMetaData' => ['int', 'name'=>'string'],
'classObj::getStyle' => ['styleObj', 'index'=>'int'],
'classObj::getTextString' => ['string'],
'classObj::movestyledown' => ['int', 'index'=>'int'],
'classObj::movestyleup' => ['int', 'index'=>'int'],
'classObj::ms_newClassObj' => ['classObj', 'layer'=>'layerObj', 'class'=>'classObj'],
'classObj::removeLabel' => ['labelObj', 'index'=>'int'],
'classObj::removeMetaData' => ['int', 'name'=>'string'],
'classObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'classObj::setExpression' => ['int', 'expression'=>'string'],
'classObj::setMetaData' => ['int', 'name'=>'string', 'value'=>'string'],
'classObj::settext' => ['int', 'text'=>'string'],
'classObj::updateFromString' => ['int', 'snippet'=>'string'],
'clearstatcache' => ['void', 'clear_realpath_cache='=>'bool', 'filename='=>'string'],
'cli_get_process_title' => ['string'],
'cli_set_process_title' => ['bool', 'title'=>'string'],
'ClosedGeneratorException::__clone' => ['void'],
'ClosedGeneratorException::__toString' => ['string'],
'ClosedGeneratorException::getCode' => ['int'],
'ClosedGeneratorException::getFile' => ['string'],
'ClosedGeneratorException::getLine' => ['int'],
'ClosedGeneratorException::getMessage' => ['string'],
'ClosedGeneratorException::getPrevious' => ['Throwable|ClosedGeneratorException|null'],
'ClosedGeneratorException::getTrace' => ['list<array<string,mixed>>'],
'ClosedGeneratorException::getTraceAsString' => ['string'],
'closedir' => ['void', 'dir_handle='=>'resource'],
'closelog' => ['bool'],
'Closure::__construct' => ['void'],
'Closure::__invoke' => ['', '...args='=>''],
'Closure::bind' => ['Closure|false', 'old'=>'Closure', 'to'=>'?object', 'scope='=>'object|string'],
'Closure::bindTo' => ['Closure|false', 'new'=>'?object', 'newscope='=>'object|string'],
'Closure::call' => ['', 'to'=>'object', '...parameters='=>''],
'Closure::fromCallable' => ['Closure', 'callable'=>'callable'],
'clusterObj::convertToString' => ['string'],
'clusterObj::getFilterString' => ['string'],
'clusterObj::getGroupString' => ['string'],
'clusterObj::setFilter' => ['int', 'expression'=>'string'],
'clusterObj::setGroup' => ['int', 'expression'=>'string'],
'Collator::__construct' => ['void', 'locale'=>'string'],
'Collator::asort' => ['bool', '&rw_arr'=>'array', 'sort_flag='=>'int'],
'Collator::compare' => ['int|false', 'string1'=>'string', 'string2'=>'string'],
'Collator::create' => ['?Collator', 'locale'=>'string'],
'Collator::getAttribute' => ['int|false', 'attr'=>'int'],
'Collator::getErrorCode' => ['int'],
'Collator::getErrorMessage' => ['string'],
'Collator::getLocale' => ['string', 'type'=>'int'],
'Collator::getSortKey' => ['string|false', 'string'=>'string'],
'Collator::getStrength' => ['int|false'],
'Collator::setAttribute' => ['bool', 'attr'=>'int', 'value'=>'int'],
'Collator::setStrength' => ['bool', 'strength'=>'int'],
'Collator::sort' => ['bool', '&rw_arr'=>'array', 'sort_flags='=>'int'],
'Collator::sortWithSortKeys' => ['bool', '&rw_arr'=>'array'],
'collator_asort' => ['bool', 'object'=>'collator', '&rw_array'=>'array', 'flags='=>'int'],
'collator_compare' => ['int', 'object'=>'collator', 'string1'=>'string', 'string2'=>'string'],
'collator_create' => ['Collator', 'locale'=>'string'],
'collator_get_attribute' => ['int|false', 'object'=>'collator', 'attribute'=>'int'],
'collator_get_error_code' => ['int', 'object'=>'collator'],
'collator_get_error_message' => ['string', 'object'=>'collator'],
'collator_get_locale' => ['string', 'object'=>'collator', 'type'=>'int'],
'collator_get_sort_key' => ['string', 'object'=>'collator', 'string'=>'string'],
'collator_get_strength' => ['int|false', 'object'=>'collator'],
'collator_set_attribute' => ['bool', 'object'=>'collator', 'attribute'=>'int', 'value'=>'int'],
'collator_set_strength' => ['bool', 'object'=>'collator', 'strength'=>'int'],
'collator_sort' => ['bool', 'object'=>'collator', '&rw_array'=>'array', 'flags='=>'int'],
'collator_sort_with_sort_keys' => ['bool', 'object'=>'collator', '&rw_array'=>'array'],
'Collectable::isGarbage' => ['bool'],
'Collectable::setGarbage' => ['void'],
'colorObj::setHex' => ['int', 'hex'=>'string'],
'colorObj::toHex' => ['string'],
'COM::__call' => ['', 'name'=>'', 'args'=>''],
'COM::__construct' => ['void', 'module_name'=>'string', 'server_name='=>'mixed', 'codepage='=>'int', 'typelib='=>'string'],
'COM::__get' => ['', 'name'=>''],
'COM::__set' => ['void', 'name'=>'', 'value'=>''],
'com_addref' => [''],
'com_create_guid' => ['string'],
'com_event_sink' => ['bool', 'variant'=>'VARIANT', 'sink_object'=>'object', 'sink_interface='=>'mixed'],
'com_get_active_object' => ['VARIANT', 'prog_id'=>'string', 'codepage='=>'int'],
'com_isenum' => ['bool', 'com_module'=>'variant'],
'com_load_typelib' => ['bool', 'typelib_name'=>'string', 'case_insensitive='=>'true'],
'com_message_pump' => ['bool', 'timeout_milliseconds='=>'int'],
'com_print_typeinfo' => ['bool', 'variant'=>'object', 'dispatch_interface='=>'string', 'display_sink='=>'bool'],
'commonmark\cql::__invoke' => ['', 'root'=>'CommonMark\Node', 'handler'=>'callable'],
'commonmark\interfaces\ivisitable::accept' => ['void', 'visitor'=>'CommonMark\Interfaces\IVisitor'],
'commonmark\interfaces\ivisitor::enter' => ['?int|IVisitable', 'visitable'=>'IVisitable'],
'commonmark\interfaces\ivisitor::leave' => ['?int|IVisitable', 'visitable'=>'IVisitable'],
'commonmark\node::accept' => ['void', 'visitor'=>'CommonMark\Interfaces\IVisitor'],
'commonmark\node::appendChild' => ['CommonMark\Node', 'child'=>'CommonMark\Node'],
'commonmark\node::insertAfter' => ['CommonMark\Node', 'sibling'=>'CommonMark\Node'],
'commonmark\node::insertBefore' => ['CommonMark\Node', 'sibling'=>'CommonMark\Node'],
'commonmark\node::prependChild' => ['CommonMark\Node', 'child'=>'CommonMark\Node'],
'commonmark\node::replace' => ['CommonMark\Node', 'target'=>'CommonMark\Node'],
'commonmark\node::unlink' => ['void'],
'commonmark\parse' => ['CommonMark\Node', 'content'=>'string', 'options='=>'int'],
'commonmark\parser::finish' => ['CommonMark\Node'],
'commonmark\parser::parse' => ['void', 'buffer'=>'string'],
'commonmark\render' => ['string', 'node'=>'CommonMark\Node', 'options='=>'int', 'width='=>'int'],
'commonmark\render\html' => ['string', 'node'=>'CommonMark\Node', 'options='=>'int'],
'commonmark\render\latex' => ['string', 'node'=>'CommonMark\Node', 'options='=>'int', 'width='=>'int'],
'commonmark\render\man' => ['string', 'node'=>'CommonMark\Node', 'options='=>'int', 'width='=>'int'],
'commonmark\render\xml' => ['string', 'node'=>'CommonMark\Node', 'options='=>'int'],
'compact' => ['array<string, mixed>', 'var_name'=>'string|array', '...var_names='=>'string|array'],
'COMPersistHelper::__construct' => ['void', 'variant'=>'object'],
'COMPersistHelper::GetCurFile' => ['string'],
'COMPersistHelper::GetCurFileName' => ['string'],
'COMPersistHelper::GetMaxStreamSize' => ['int'],
'COMPersistHelper::InitNew' => ['int'],
'COMPersistHelper::LoadFromFile' => ['bool', 'filename'=>'string', 'flags'=>'int'],
'COMPersistHelper::LoadFromStream' => ['', 'stream'=>''],
'COMPersistHelper::SaveToFile' => ['bool', 'filename'=>'string', 'remember'=>'bool'],
'COMPersistHelper::SaveToStream' => ['int', 'stream'=>''],
'componere\abstract\definition::addInterface' => ['Componere\Abstract\Definition', 'interface'=>'string'],
'componere\abstract\definition::addMethod' => ['Componere\Abstract\Definition', 'name'=>'string', 'method'=>'Componere\Method'],
'componere\abstract\definition::addTrait' => ['Componere\Abstract\Definition', 'trait'=>'string'],
'componere\abstract\definition::getReflector' => ['ReflectionClass'],
'componere\cast' => ['object', 'arg1'=>'string', 'object'=>'object'],
'componere\cast_by_ref' => ['object', 'arg1'=>'string', 'object'=>'object'],
'componere\definition::addConstant' => ['Componere\Definition', 'name'=>'string', 'value'=>'Componere\Value'],
'componere\definition::addProperty' => ['Componere\Definition', 'name'=>'string', 'value'=>'Componere\Value'],
'componere\definition::getClosure' => ['Closure', 'name'=>'string'],
'componere\definition::getClosures' => ['Closure[]'],
'componere\definition::isRegistered' => ['bool'],
'componere\definition::register' => ['void'],
'componere\method::getReflector' => ['ReflectionMethod'],
'componere\method::setPrivate' => ['Method'],
'componere\method::setProtected' => ['Method'],
'componere\method::setStatic' => ['Method'],
'componere\patch::apply' => ['void'],
'componere\patch::derive' => ['Componere\Patch', 'instance'=>'object'],
'componere\patch::getClosure' => ['Closure', 'name'=>'string'],
'componere\patch::getClosures' => ['Closure[]'],
'componere\patch::isApplied' => ['bool'],
'componere\patch::revert' => ['void'],
'componere\value::hasDefault' => ['bool'],
'componere\value::isPrivate' => ['bool'],
'componere\value::isProtected' => ['bool'],
'componere\value::isStatic' => ['bool'],
'componere\value::setPrivate' => ['Value'],
'componere\value::setProtected' => ['Value'],
'componere\value::setStatic' => ['Value'],
'Cond::broadcast' => ['bool', 'condition'=>'long'],
'Cond::create' => ['long'],
'Cond::destroy' => ['bool', 'condition'=>'long'],
'Cond::signal' => ['bool', 'condition'=>'long'],
'Cond::wait' => ['bool', 'condition'=>'long', 'mutex'=>'long', 'timeout='=>'long'],
'confirm_pdo_ibm_compiled' => [''],
'connection_aborted' => ['int'],
'connection_status' => ['int'],
'connection_timeout' => ['int'],
'constant' => ['mixed', 'name'=>'string'],
'convert_cyr_string' => ['string', 'string'=>'string', 'from'=>'string', 'to'=>'string'],
'convert_uudecode' => ['string', 'string'=>'string'],
'convert_uuencode' => ['string', 'string'=>'string'],
'copy' => ['bool', 'from'=>'string', 'to'=>'string', 'context='=>'resource'],
'cos' => ['float', 'num'=>'float'],
'cosh' => ['float', 'num'=>'float'],
'Couchbase\AnalyticsQuery::__construct' => ['void'],
'Couchbase\AnalyticsQuery::fromString' => ['Couchbase\AnalyticsQuery', 'statement'=>'string'],
'Couchbase\basicDecoderV1' => ['mixed', 'bytes'=>'string', 'flags'=>'int', 'datatype'=>'int', 'options'=>'array'],
'Couchbase\basicEncoderV1' => ['array', 'value'=>'mixed', 'options'=>'array'],
'Couchbase\BooleanFieldSearchQuery::__construct' => ['void'],
'Couchbase\BooleanFieldSearchQuery::boost' => ['Couchbase\BooleanFieldSearchQuery', 'boost'=>'float'],
'Couchbase\BooleanFieldSearchQuery::field' => ['Couchbase\BooleanFieldSearchQuery', 'field'=>'string'],
'Couchbase\BooleanFieldSearchQuery::jsonSerialize' => ['array'],
'Couchbase\BooleanSearchQuery::__construct' => ['void'],
'Couchbase\BooleanSearchQuery::boost' => ['Couchbase\BooleanSearchQuery', 'boost'=>'float'],
'Couchbase\BooleanSearchQuery::jsonSerialize' => ['array'],
'Couchbase\BooleanSearchQuery::must' => ['Couchbase\BooleanSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\BooleanSearchQuery::mustNot' => ['Couchbase\BooleanSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\BooleanSearchQuery::should' => ['Couchbase\BooleanSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\Bucket::__construct' => ['void'],
'Couchbase\Bucket::__get' => ['int', 'name'=>'string'],
'Couchbase\Bucket::__set' => ['int', 'name'=>'string', 'value'=>'int'],
'Couchbase\Bucket::append' => ['Couchbase\Document|array', 'ids'=>'array|string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\Bucket::counter' => ['Couchbase\Document|array', 'ids'=>'array|string', 'delta='=>'int', 'options='=>'array'],
'Couchbase\Bucket::decryptFields' => ['array', 'document'=>'array', 'fieldOptions'=>'', 'prefix='=>'string'],
'Couchbase\Bucket::diag' => ['array', 'reportId='=>'string'],
'Couchbase\Bucket::encryptFields' => ['array', 'document'=>'array', 'fieldOptions'=>'', 'prefix='=>'string'],
'Couchbase\Bucket::get' => ['Couchbase\Document|array', 'ids'=>'array|string', 'options='=>'array'],
'Couchbase\Bucket::getAndLock' => ['Couchbase\Document|array', 'ids'=>'array|string', 'lockTime'=>'int', 'options='=>'array'],
'Couchbase\Bucket::getAndTouch' => ['Couchbase\Document|array', 'ids'=>'array|string', 'expiry'=>'int', 'options='=>'array'],
'Couchbase\Bucket::getFromReplica' => ['Couchbase\Document|array', 'ids'=>'array|string', 'options='=>'array'],
'Couchbase\Bucket::getName' => ['string'],
'Couchbase\Bucket::insert' => ['Couchbase\Document|array', 'ids'=>'array|string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\Bucket::listExists' => ['bool', 'id'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::listGet' => ['mixed', 'id'=>'string', 'index'=>'int'],
'Couchbase\Bucket::listPush' => ['', 'id'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::listRemove' => ['', 'id'=>'string', 'index'=>'int'],
'Couchbase\Bucket::listSet' => ['', 'id'=>'string', 'index'=>'int', 'value'=>'mixed'],
'Couchbase\Bucket::listShift' => ['', 'id'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::listSize' => ['int', 'id'=>'string'],
'Couchbase\Bucket::lookupIn' => ['Couchbase\LookupInBuilder', 'id'=>'string'],
'Couchbase\Bucket::manager' => ['Couchbase\BucketManager'],
'Couchbase\Bucket::mapAdd' => ['', 'id'=>'string', 'key'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::mapGet' => ['mixed', 'id'=>'string', 'key'=>'string'],
'Couchbase\Bucket::mapRemove' => ['', 'id'=>'string', 'key'=>'string'],
'Couchbase\Bucket::mapSize' => ['int', 'id'=>'string'],
'Couchbase\Bucket::mutateIn' => ['Couchbase\MutateInBuilder', 'id'=>'string', 'cas'=>'string'],
'Couchbase\Bucket::ping' => ['array', 'services='=>'int', 'reportId='=>'string'],
'Couchbase\Bucket::prepend' => ['Couchbase\Document|array', 'ids'=>'array|string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\Bucket::query' => ['object', 'query'=>'Couchbase\AnalyticsQuery|Couchbase\N1qlQuery|Couchbase\SearchQuery|Couchbase\SpatialViewQuery|Couchbase\ViewQuery', 'jsonAsArray='=>'bool'],
'Couchbase\Bucket::queueAdd' => ['', 'id'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::queueExists' => ['bool', 'id'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::queueRemove' => ['mixed', 'id'=>'string'],
'Couchbase\Bucket::queueSize' => ['int', 'id'=>'string'],
'Couchbase\Bucket::remove' => ['Couchbase\Document|array', 'ids'=>'array|string', 'options='=>'array'],
'Couchbase\Bucket::replace' => ['Couchbase\Document|array', 'ids'=>'array|string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\Bucket::retrieveIn' => ['Couchbase\DocumentFragment', 'id'=>'string', '...paths='=>'array<int,string>'],
'Couchbase\Bucket::setAdd' => ['', 'id'=>'string', 'value'=>'bool|float|int|string'],
'Couchbase\Bucket::setExists' => ['bool', 'id'=>'string', 'value'=>'bool|float|int|string'],
'Couchbase\Bucket::setRemove' => ['', 'id'=>'string', 'value'=>'bool|float|int|string'],
'Couchbase\Bucket::setSize' => ['int', 'id'=>'string'],
'Couchbase\Bucket::setTranscoder' => ['', 'encoder'=>'callable', 'decoder'=>'callable'],
'Couchbase\Bucket::touch' => ['Couchbase\Document|array', 'ids'=>'array|string', 'expiry'=>'int', 'options='=>'array'],
'Couchbase\Bucket::unlock' => ['Couchbase\Document|array', 'ids'=>'array|string', 'options='=>'array'],
'Couchbase\Bucket::upsert' => ['Couchbase\Document|array', 'ids'=>'array|string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\BucketManager::__construct' => ['void'],
'Couchbase\BucketManager::createN1qlIndex' => ['', 'name'=>'string', 'fields'=>'array', 'whereClause='=>'string', 'ignoreIfExist='=>'bool', 'defer='=>'bool'],
'Couchbase\BucketManager::createN1qlPrimaryIndex' => ['', 'customName='=>'string', 'ignoreIfExist='=>'bool', 'defer='=>'bool'],
'Couchbase\BucketManager::dropN1qlIndex' => ['', 'name'=>'string', 'ignoreIfNotExist='=>'bool'],
'Couchbase\BucketManager::dropN1qlPrimaryIndex' => ['', 'customName='=>'string', 'ignoreIfNotExist='=>'bool'],
'Couchbase\BucketManager::flush' => [''],
'Couchbase\BucketManager::getDesignDocument' => ['array', 'name'=>'string'],
'Couchbase\BucketManager::info' => ['array'],
'Couchbase\BucketManager::insertDesignDocument' => ['', 'name'=>'string', 'document'=>'array'],
'Couchbase\BucketManager::listDesignDocuments' => ['array'],
'Couchbase\BucketManager::listN1qlIndexes' => ['array'],
'Couchbase\BucketManager::removeDesignDocument' => ['', 'name'=>'string'],
'Couchbase\BucketManager::upsertDesignDocument' => ['', 'name'=>'string', 'document'=>'array'],
'Couchbase\ClassicAuthenticator::bucket' => ['', 'name'=>'string', 'password'=>'string'],
'Couchbase\ClassicAuthenticator::cluster' => ['', 'username'=>'string', 'password'=>'string'],
'Couchbase\Cluster::__construct' => ['void', 'connstr'=>'string'],
'Couchbase\Cluster::authenticate' => ['null', 'authenticator'=>'Couchbase\Authenticator'],
'Couchbase\Cluster::authenticateAs' => ['null', 'username'=>'string', 'password'=>'string'],
'Couchbase\Cluster::manager' => ['Couchbase\ClusterManager', 'username='=>'string', 'password='=>'string'],
'Couchbase\Cluster::openBucket' => ['Couchbase\Bucket', 'name='=>'string', 'password='=>'string'],
'Couchbase\ClusterManager::__construct' => ['void'],
'Couchbase\ClusterManager::createBucket' => ['', 'name'=>'string', 'options='=>'array'],
'Couchbase\ClusterManager::getUser' => ['array', 'username'=>'string', 'domain='=>'int'],
'Couchbase\ClusterManager::info' => ['array'],
'Couchbase\ClusterManager::listBuckets' => ['array'],
'Couchbase\ClusterManager::listUsers' => ['array', 'domain='=>'int'],
'Couchbase\ClusterManager::removeBucket' => ['', 'name'=>'string'],
'Couchbase\ClusterManager::removeUser' => ['', 'name'=>'string', 'domain='=>'int'],
'Couchbase\ClusterManager::upsertUser' => ['', 'name'=>'string', 'settings'=>'Couchbase\UserSettings', 'domain='=>'int'],
'Couchbase\ConjunctionSearchQuery::__construct' => ['void'],
'Couchbase\ConjunctionSearchQuery::boost' => ['Couchbase\ConjunctionSearchQuery', 'boost'=>'float'],
'Couchbase\ConjunctionSearchQuery::every' => ['Couchbase\ConjunctionSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\ConjunctionSearchQuery::jsonSerialize' => ['array'],
'Couchbase\DateRangeSearchFacet::__construct' => ['void'],
'Couchbase\DateRangeSearchFacet::addRange' => ['Couchbase\DateRangeSearchFacet', 'name'=>'string', 'start'=>'int|string', 'end'=>'int|string'],
'Couchbase\DateRangeSearchFacet::jsonSerialize' => ['array'],
'Couchbase\DateRangeSearchQuery::__construct' => ['void'],
'Couchbase\DateRangeSearchQuery::boost' => ['Couchbase\DateRangeSearchQuery', 'boost'=>'float'],
'Couchbase\DateRangeSearchQuery::dateTimeParser' => ['Couchbase\DateRangeSearchQuery', 'dateTimeParser'=>'string'],
'Couchbase\DateRangeSearchQuery::end' => ['Couchbase\DateRangeSearchQuery', 'end'=>'int|string', 'inclusive='=>'bool'],
'Couchbase\DateRangeSearchQuery::field' => ['Couchbase\DateRangeSearchQuery', 'field'=>'string'],
'Couchbase\DateRangeSearchQuery::jsonSerialize' => ['array'],
'Couchbase\DateRangeSearchQuery::start' => ['Couchbase\DateRangeSearchQuery', 'start'=>'int|string', 'inclusive='=>'bool'],
'Couchbase\defaultDecoder' => ['mixed', 'bytes'=>'string', 'flags'=>'int', 'datatype'=>'int'],
'Couchbase\defaultEncoder' => ['array', 'value'=>'mixed'],
'Couchbase\DisjunctionSearchQuery::__construct' => ['void'],
'Couchbase\DisjunctionSearchQuery::boost' => ['Couchbase\DisjunctionSearchQuery', 'boost'=>'float'],
'Couchbase\DisjunctionSearchQuery::either' => ['Couchbase\DisjunctionSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\DisjunctionSearchQuery::jsonSerialize' => ['array'],
'Couchbase\DisjunctionSearchQuery::min' => ['Couchbase\DisjunctionSearchQuery', 'min'=>'int'],
'Couchbase\DocIdSearchQuery::__construct' => ['void'],
'Couchbase\DocIdSearchQuery::boost' => ['Couchbase\DocIdSearchQuery', 'boost'=>'float'],
'Couchbase\DocIdSearchQuery::docIds' => ['Couchbase\DocIdSearchQuery', '...documentIds='=>'array<int,string>'],
'Couchbase\DocIdSearchQuery::field' => ['Couchbase\DocIdSearchQuery', 'field'=>'string'],
'Couchbase\DocIdSearchQuery::jsonSerialize' => ['array'],
'Couchbase\fastlzCompress' => ['string', 'data'=>'string'],
'Couchbase\fastlzDecompress' => ['string', 'data'=>'string'],
'Couchbase\GeoBoundingBoxSearchQuery::__construct' => ['void'],
'Couchbase\GeoBoundingBoxSearchQuery::boost' => ['Couchbase\GeoBoundingBoxSearchQuery', 'boost'=>'float'],
'Couchbase\GeoBoundingBoxSearchQuery::field' => ['Couchbase\GeoBoundingBoxSearchQuery', 'field'=>'string'],
'Couchbase\GeoBoundingBoxSearchQuery::jsonSerialize' => ['array'],
'Couchbase\GeoDistanceSearchQuery::__construct' => ['void'],
'Couchbase\GeoDistanceSearchQuery::boost' => ['Couchbase\GeoDistanceSearchQuery', 'boost'=>'float'],
'Couchbase\GeoDistanceSearchQuery::field' => ['Couchbase\GeoDistanceSearchQuery', 'field'=>'string'],
'Couchbase\GeoDistanceSearchQuery::jsonSerialize' => ['array'],
'Couchbase\LookupInBuilder::__construct' => ['void'],
'Couchbase\LookupInBuilder::execute' => ['Couchbase\DocumentFragment'],
'Couchbase\LookupInBuilder::exists' => ['Couchbase\LookupInBuilder', 'path'=>'string', 'options='=>'array'],
'Couchbase\LookupInBuilder::get' => ['Couchbase\LookupInBuilder', 'path'=>'string', 'options='=>'array'],
'Couchbase\LookupInBuilder::getCount' => ['Couchbase\LookupInBuilder', 'path'=>'string', 'options='=>'array'],
'Couchbase\MatchAllSearchQuery::__construct' => ['void'],
'Couchbase\MatchAllSearchQuery::boost' => ['Couchbase\MatchAllSearchQuery', 'boost'=>'float'],
'Couchbase\MatchAllSearchQuery::jsonSerialize' => ['array'],
'Couchbase\MatchNoneSearchQuery::__construct' => ['void'],
'Couchbase\MatchNoneSearchQuery::boost' => ['Couchbase\MatchNoneSearchQuery', 'boost'=>'float'],
'Couchbase\MatchNoneSearchQuery::jsonSerialize' => ['array'],
'Couchbase\MatchPhraseSearchQuery::__construct' => ['void'],
'Couchbase\MatchPhraseSearchQuery::analyzer' => ['Couchbase\MatchPhraseSearchQuery', 'analyzer'=>'string'],
'Couchbase\MatchPhraseSearchQuery::boost' => ['Couchbase\MatchPhraseSearchQuery', 'boost'=>'float'],
'Couchbase\MatchPhraseSearchQuery::field' => ['Couchbase\MatchPhraseSearchQuery', 'field'=>'string'],
'Couchbase\MatchPhraseSearchQuery::jsonSerialize' => ['array'],
'Couchbase\MatchSearchQuery::__construct' => ['void'],
'Couchbase\MatchSearchQuery::analyzer' => ['Couchbase\MatchSearchQuery', 'analyzer'=>'string'],
'Couchbase\MatchSearchQuery::boost' => ['Couchbase\MatchSearchQuery', 'boost'=>'float'],
'Couchbase\MatchSearchQuery::field' => ['Couchbase\MatchSearchQuery', 'field'=>'string'],
'Couchbase\MatchSearchQuery::fuzziness' => ['Couchbase\MatchSearchQuery', 'fuzziness'=>'int'],
'Couchbase\MatchSearchQuery::jsonSerialize' => ['array'],
'Couchbase\MatchSearchQuery::prefixLength' => ['Couchbase\MatchSearchQuery', 'prefixLength'=>'int'],
'Couchbase\MutateInBuilder::__construct' => ['void'],
'Couchbase\MutateInBuilder::arrayAddUnique' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::arrayAppend' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::arrayAppendAll' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'values'=>'array', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::arrayInsert' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\MutateInBuilder::arrayInsertAll' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'values'=>'array', 'options='=>'array'],
'Couchbase\MutateInBuilder::arrayPrepend' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::arrayPrependAll' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'values'=>'array', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::counter' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'delta'=>'int', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::execute' => ['Couchbase\DocumentFragment'],
'Couchbase\MutateInBuilder::insert' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::modeDocument' => ['', 'mode'=>'int'],
'Couchbase\MutateInBuilder::remove' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'options='=>'array'],
'Couchbase\MutateInBuilder::replace' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\MutateInBuilder::upsert' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::withExpiry' => ['Couchbase\MutateInBuilder', 'expiry'=>'Couchbase\expiry'],
'Couchbase\MutationState::__construct' => ['void'],
'Couchbase\MutationState::add' => ['', 'source'=>'Couchbase\Document|Couchbase\DocumentFragment|array'],
'Couchbase\MutationState::from' => ['Couchbase\MutationState', 'source'=>'Couchbase\Document|Couchbase\DocumentFragment|array'],
'Couchbase\MutationToken::__construct' => ['void'],
'Couchbase\MutationToken::bucketName' => ['string'],
'Couchbase\MutationToken::from' => ['', 'bucketName'=>'string', 'vbucketId'=>'int', 'vbucketUuid'=>'string', 'sequenceNumber'=>'string'],
'Couchbase\MutationToken::sequenceNumber' => ['string'],
'Couchbase\MutationToken::vbucketId' => ['int'],
'Couchbase\MutationToken::vbucketUuid' => ['string'],
'Couchbase\N1qlIndex::__construct' => ['void'],
'Couchbase\N1qlQuery::__construct' => ['void'],
'Couchbase\N1qlQuery::adhoc' => ['Couchbase\N1qlQuery', 'adhoc'=>'bool'],
'Couchbase\N1qlQuery::consistency' => ['Couchbase\N1qlQuery', 'consistency'=>'int'],
'Couchbase\N1qlQuery::consistentWith' => ['Couchbase\N1qlQuery', 'state'=>'Couchbase\MutationState'],
'Couchbase\N1qlQuery::crossBucket' => ['Couchbase\N1qlQuery', 'crossBucket'=>'bool'],
'Couchbase\N1qlQuery::fromString' => ['Couchbase\N1qlQuery', 'statement'=>'string'],
'Couchbase\N1qlQuery::maxParallelism' => ['Couchbase\N1qlQuery', 'maxParallelism'=>'int'],
'Couchbase\N1qlQuery::namedParams' => ['Couchbase\N1qlQuery', 'params'=>'array'],
'Couchbase\N1qlQuery::pipelineBatch' => ['Couchbase\N1qlQuery', 'pipelineBatch'=>'int'],
'Couchbase\N1qlQuery::pipelineCap' => ['Couchbase\N1qlQuery', 'pipelineCap'=>'int'],
'Couchbase\N1qlQuery::positionalParams' => ['Couchbase\N1qlQuery', 'params'=>'array'],
'Couchbase\N1qlQuery::profile' => ['', 'profileType'=>'string'],
'Couchbase\N1qlQuery::readonly' => ['Couchbase\N1qlQuery', 'readonly'=>'bool'],
'Couchbase\N1qlQuery::scanCap' => ['Couchbase\N1qlQuery', 'scanCap'=>'int'],
'Couchbase\NumericRangeSearchFacet::__construct' => ['void'],
'Couchbase\NumericRangeSearchFacet::addRange' => ['Couchbase\NumericRangeSearchFacet', 'name'=>'string', 'min'=>'float', 'max'=>'float'],
'Couchbase\NumericRangeSearchFacet::jsonSerialize' => ['array'],
'Couchbase\NumericRangeSearchQuery::__construct' => ['void'],
'Couchbase\NumericRangeSearchQuery::boost' => ['Couchbase\NumericRangeSearchQuery', 'boost'=>'float'],
'Couchbase\NumericRangeSearchQuery::field' => ['Couchbase\NumericRangeSearchQuery', 'field'=>'string'],
'Couchbase\NumericRangeSearchQuery::jsonSerialize' => ['array'],
'Couchbase\NumericRangeSearchQuery::max' => ['Couchbase\NumericRangeSearchQuery', 'max'=>'float', 'inclusive='=>'bool'],
'Couchbase\NumericRangeSearchQuery::min' => ['Couchbase\NumericRangeSearchQuery', 'min'=>'float', 'inclusive='=>'bool'],
'Couchbase\passthruDecoder' => ['string', 'bytes'=>'string', 'flags'=>'int', 'datatype'=>'int'],
'Couchbase\passthruEncoder' => ['array', 'value'=>'string'],
'Couchbase\PasswordAuthenticator::password' => ['Couchbase\PasswordAuthenticator', 'password'=>'string'],
'Couchbase\PasswordAuthenticator::username' => ['Couchbase\PasswordAuthenticator', 'username'=>'string'],
'Couchbase\PhraseSearchQuery::__construct' => ['void'],
'Couchbase\PhraseSearchQuery::boost' => ['Couchbase\PhraseSearchQuery', 'boost'=>'float'],
'Couchbase\PhraseSearchQuery::field' => ['Couchbase\PhraseSearchQuery', 'field'=>'string'],
'Couchbase\PhraseSearchQuery::jsonSerialize' => ['array'],
'Couchbase\PrefixSearchQuery::__construct' => ['void'],
'Couchbase\PrefixSearchQuery::boost' => ['Couchbase\PrefixSearchQuery', 'boost'=>'float'],
'Couchbase\PrefixSearchQuery::field' => ['Couchbase\PrefixSearchQuery', 'field'=>'string'],
'Couchbase\PrefixSearchQuery::jsonSerialize' => ['array'],
'Couchbase\QueryStringSearchQuery::__construct' => ['void'],
'Couchbase\QueryStringSearchQuery::boost' => ['Couchbase\QueryStringSearchQuery', 'boost'=>'float'],
'Couchbase\QueryStringSearchQuery::jsonSerialize' => ['array'],
'Couchbase\RegexpSearchQuery::__construct' => ['void'],
'Couchbase\RegexpSearchQuery::boost' => ['Couchbase\RegexpSearchQuery', 'boost'=>'float'],
'Couchbase\RegexpSearchQuery::field' => ['Couchbase\RegexpSearchQuery', 'field'=>'string'],
'Couchbase\RegexpSearchQuery::jsonSerialize' => ['array'],
'Couchbase\SearchQuery::__construct' => ['void', 'indexName'=>'string', 'queryPart'=>'Couchbase\SearchQueryPart'],
'Couchbase\SearchQuery::addFacet' => ['Couchbase\SearchQuery', 'name'=>'string', 'facet'=>'Couchbase\SearchFacet'],
'Couchbase\SearchQuery::boolean' => ['Couchbase\BooleanSearchQuery'],
'Couchbase\SearchQuery::booleanField' => ['Couchbase\BooleanFieldSearchQuery', 'value'=>'bool'],
'Couchbase\SearchQuery::conjuncts' => ['Couchbase\ConjunctionSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\SearchQuery::consistentWith' => ['Couchbase\SearchQuery', 'state'=>'Couchbase\MutationState'],
'Couchbase\SearchQuery::dateRange' => ['Couchbase\DateRangeSearchQuery'],
'Couchbase\SearchQuery::dateRangeFacet' => ['Couchbase\DateRangeSearchFacet', 'field'=>'string', 'limit'=>'int'],
'Couchbase\SearchQuery::disjuncts' => ['Couchbase\DisjunctionSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\SearchQuery::docId' => ['Couchbase\DocIdSearchQuery', '...documentIds='=>'array<int,string>'],
'Couchbase\SearchQuery::explain' => ['Couchbase\SearchQuery', 'explain'=>'bool'],
'Couchbase\SearchQuery::fields' => ['Couchbase\SearchQuery', '...fields='=>'array<int,string>'],
'Couchbase\SearchQuery::geoBoundingBox' => ['Couchbase\GeoBoundingBoxSearchQuery', 'topLeftLongitude'=>'float', 'topLeftLatitude'=>'float', 'bottomRightLongitude'=>'float', 'bottomRightLatitude'=>'float'],
'Couchbase\SearchQuery::geoDistance' => ['Couchbase\GeoDistanceSearchQuery', 'longitude'=>'float', 'latitude'=>'float', 'distance'=>'string'],
'Couchbase\SearchQuery::highlight' => ['Couchbase\SearchQuery', 'style'=>'string', '...fields='=>'array<int,string>'],
'Couchbase\SearchQuery::jsonSerialize' => ['array'],
'Couchbase\SearchQuery::limit' => ['Couchbase\SearchQuery', 'limit'=>'int'],
'Couchbase\SearchQuery::match' => ['Couchbase\MatchSearchQuery', 'match'=>'string'],
'Couchbase\SearchQuery::matchAll' => ['Couchbase\MatchAllSearchQuery'],
'Couchbase\SearchQuery::matchNone' => ['Couchbase\MatchNoneSearchQuery'],
'Couchbase\SearchQuery::matchPhrase' => ['Couchbase\MatchPhraseSearchQuery', '...terms='=>'array<int,string>'],
'Couchbase\SearchQuery::numericRange' => ['Couchbase\NumericRangeSearchQuery'],
'Couchbase\SearchQuery::numericRangeFacet' => ['Couchbase\NumericRangeSearchFacet', 'field'=>'string', 'limit'=>'int'],
'Couchbase\SearchQuery::prefix' => ['Couchbase\PrefixSearchQuery', 'prefix'=>'string'],
'Couchbase\SearchQuery::queryString' => ['Couchbase\QueryStringSearchQuery', 'queryString'=>'string'],
'Couchbase\SearchQuery::regexp' => ['Couchbase\RegexpSearchQuery', 'regexp'=>'string'],
'Couchbase\SearchQuery::serverSideTimeout' => ['Couchbase\SearchQuery', 'serverSideTimeout'=>'int'],
'Couchbase\SearchQuery::skip' => ['Couchbase\SearchQuery', 'skip'=>'int'],
'Couchbase\SearchQuery::sort' => ['Couchbase\SearchQuery', '...sort='=>'array<int,Couchbase\sort>'],
'Couchbase\SearchQuery::term' => ['Couchbase\TermSearchQuery', 'term'=>'string'],
'Couchbase\SearchQuery::termFacet' => ['Couchbase\TermSearchFacet', 'field'=>'string', 'limit'=>'int'],
'Couchbase\SearchQuery::termRange' => ['Couchbase\TermRangeSearchQuery'],
'Couchbase\SearchQuery::wildcard' => ['Couchbase\WildcardSearchQuery', 'wildcard'=>'string'],
'Couchbase\SearchSort::__construct' => ['void'],
'Couchbase\SearchSort::field' => ['Couchbase\SearchSortField', 'field'=>'string'],
'Couchbase\SearchSort::geoDistance' => ['Couchbase\SearchSortGeoDistance', 'field'=>'string', 'longitude'=>'float', 'latitude'=>'float'],
'Couchbase\SearchSort::id' => ['Couchbase\SearchSortId'],
'Couchbase\SearchSort::score' => ['Couchbase\SearchSortScore'],
'Couchbase\SearchSortField::__construct' => ['void'],
'Couchbase\SearchSortField::descending' => ['Couchbase\SearchSortField', 'descending'=>'bool'],
'Couchbase\SearchSortField::field' => ['Couchbase\SearchSortField', 'field'=>'string'],
'Couchbase\SearchSortField::geoDistance' => ['Couchbase\SearchSortGeoDistance', 'field'=>'string', 'longitude'=>'float', 'latitude'=>'float'],
'Couchbase\SearchSortField::id' => ['Couchbase\SearchSortId'],
'Couchbase\SearchSortField::jsonSerialize' => ['mixed'],
'Couchbase\SearchSortField::missing' => ['', 'missing'=>'string'],
'Couchbase\SearchSortField::mode' => ['', 'mode'=>'string'],
'Couchbase\SearchSortField::score' => ['Couchbase\SearchSortScore'],
'Couchbase\SearchSortField::type' => ['', 'type'=>'string'],
'Couchbase\SearchSortGeoDistance::__construct' => ['void'],
'Couchbase\SearchSortGeoDistance::descending' => ['Couchbase\SearchSortGeoDistance', 'descending'=>'bool'],
'Couchbase\SearchSortGeoDistance::field' => ['Couchbase\SearchSortField', 'field'=>'string'],
'Couchbase\SearchSortGeoDistance::geoDistance' => ['Couchbase\SearchSortGeoDistance', 'field'=>'string', 'longitude'=>'float', 'latitude'=>'float'],
'Couchbase\SearchSortGeoDistance::id' => ['Couchbase\SearchSortId'],
'Couchbase\SearchSortGeoDistance::jsonSerialize' => ['mixed'],
'Couchbase\SearchSortGeoDistance::score' => ['Couchbase\SearchSortScore'],
'Couchbase\SearchSortGeoDistance::unit' => ['Couchbase\SearchSortGeoDistance', 'unit'=>'string'],
'Couchbase\SearchSortId::__construct' => ['void'],
'Couchbase\SearchSortId::descending' => ['Couchbase\SearchSortId', 'descending'=>'bool'],
'Couchbase\SearchSortId::field' => ['Couchbase\SearchSortField', 'field'=>'string'],
'Couchbase\SearchSortId::geoDistance' => ['Couchbase\SearchSortGeoDistance', 'field'=>'string', 'longitude'=>'float', 'latitude'=>'float'],
'Couchbase\SearchSortId::id' => ['Couchbase\SearchSortId'],
'Couchbase\SearchSortId::jsonSerialize' => ['mixed'],
'Couchbase\SearchSortId::score' => ['Couchbase\SearchSortScore'],
'Couchbase\SearchSortScore::__construct' => ['void'],
'Couchbase\SearchSortScore::descending' => ['Couchbase\SearchSortScore', 'descending'=>'bool'],
'Couchbase\SearchSortScore::field' => ['Couchbase\SearchSortField', 'field'=>'string'],
'Couchbase\SearchSortScore::geoDistance' => ['Couchbase\SearchSortGeoDistance', 'field'=>'string', 'longitude'=>'float', 'latitude'=>'float'],
'Couchbase\SearchSortScore::id' => ['Couchbase\SearchSortId'],
'Couchbase\SearchSortScore::jsonSerialize' => ['mixed'],
'Couchbase\SearchSortScore::score' => ['Couchbase\SearchSortScore'],
'Couchbase\SpatialViewQuery::__construct' => ['void'],
'Couchbase\SpatialViewQuery::bbox' => ['Couchbase\SpatialViewQuery', 'bbox'=>'array'],
'Couchbase\SpatialViewQuery::consistency' => ['Couchbase\SpatialViewQuery', 'consistency'=>'int'],
'Couchbase\SpatialViewQuery::custom' => ['', 'customParameters'=>'array'],
'Couchbase\SpatialViewQuery::encode' => ['array'],
'Couchbase\SpatialViewQuery::endRange' => ['Couchbase\SpatialViewQuery', 'range'=>'array'],
'Couchbase\SpatialViewQuery::limit' => ['Couchbase\SpatialViewQuery', 'limit'=>'int'],
'Couchbase\SpatialViewQuery::order' => ['Couchbase\SpatialViewQuery', 'order'=>'int'],
'Couchbase\SpatialViewQuery::skip' => ['Couchbase\SpatialViewQuery', 'skip'=>'int'],
'Couchbase\SpatialViewQuery::startRange' => ['Couchbase\SpatialViewQuery', 'range'=>'array'],
'Couchbase\TermRangeSearchQuery::__construct' => ['void'],
'Couchbase\TermRangeSearchQuery::boost' => ['Couchbase\TermRangeSearchQuery', 'boost'=>'float'],
'Couchbase\TermRangeSearchQuery::field' => ['Couchbase\TermRangeSearchQuery', 'field'=>'string'],
'Couchbase\TermRangeSearchQuery::jsonSerialize' => ['array'],
'Couchbase\TermRangeSearchQuery::max' => ['Couchbase\TermRangeSearchQuery', 'max'=>'string', 'inclusive='=>'bool'],
'Couchbase\TermRangeSearchQuery::min' => ['Couchbase\TermRangeSearchQuery', 'min'=>'string', 'inclusive='=>'bool'],
'Couchbase\TermSearchFacet::__construct' => ['void'],
'Couchbase\TermSearchFacet::jsonSerialize' => ['array'],
'Couchbase\TermSearchQuery::__construct' => ['void'],
'Couchbase\TermSearchQuery::boost' => ['Couchbase\TermSearchQuery', 'boost'=>'float'],
'Couchbase\TermSearchQuery::field' => ['Couchbase\TermSearchQuery', 'field'=>'string'],
'Couchbase\TermSearchQuery::fuzziness' => ['Couchbase\TermSearchQuery', 'fuzziness'=>'int'],
'Couchbase\TermSearchQuery::jsonSerialize' => ['array'],
'Couchbase\TermSearchQuery::prefixLength' => ['Couchbase\TermSearchQuery', 'prefixLength'=>'int'],
'Couchbase\UserSettings::fullName' => ['Couchbase\UserSettings', 'fullName'=>'string'],
'Couchbase\UserSettings::password' => ['Couchbase\UserSettings', 'password'=>'string'],
'Couchbase\UserSettings::role' => ['Couchbase\UserSettings', 'role'=>'string', 'bucket='=>'string'],
'Couchbase\ViewQuery::__construct' => ['void'],
'Couchbase\ViewQuery::consistency' => ['Couchbase\ViewQuery', 'consistency'=>'int'],
'Couchbase\ViewQuery::custom' => ['Couchbase\ViewQuery', 'customParameters'=>'array'],
'Couchbase\ViewQuery::encode' => ['array'],
'Couchbase\ViewQuery::from' => ['Couchbase\ViewQuery', 'designDocumentName'=>'string', 'viewName'=>'string'],
'Couchbase\ViewQuery::fromSpatial' => ['Couchbase\SpatialViewQuery', 'designDocumentName'=>'string', 'viewName'=>'string'],
'Couchbase\ViewQuery::group' => ['Couchbase\ViewQuery', 'group'=>'bool'],
'Couchbase\ViewQuery::groupLevel' => ['Couchbase\ViewQuery', 'groupLevel'=>'int'],
'Couchbase\ViewQuery::idRange' => ['Couchbase\ViewQuery', 'startKeyDocumentId'=>'string', 'endKeyDocumentId'=>'string'],
'Couchbase\ViewQuery::key' => ['Couchbase\ViewQuery', 'key'=>'mixed'],
'Couchbase\ViewQuery::keys' => ['Couchbase\ViewQuery', 'keys'=>'array'],
'Couchbase\ViewQuery::limit' => ['Couchbase\ViewQuery', 'limit'=>'int'],
'Couchbase\ViewQuery::order' => ['Couchbase\ViewQuery', 'order'=>'int'],
'Couchbase\ViewQuery::range' => ['Couchbase\ViewQuery', 'startKey'=>'mixed', 'endKey'=>'mixed', 'inclusiveEnd='=>'bool'],
'Couchbase\ViewQuery::reduce' => ['Couchbase\ViewQuery', 'reduce'=>'bool'],
'Couchbase\ViewQuery::skip' => ['Couchbase\ViewQuery', 'skip'=>'int'],
'Couchbase\ViewQueryEncodable::encode' => ['array'],
'Couchbase\WildcardSearchQuery::__construct' => ['void'],
'Couchbase\WildcardSearchQuery::boost' => ['Couchbase\WildcardSearchQuery', 'boost'=>'float'],
'Couchbase\WildcardSearchQuery::field' => ['Couchbase\WildcardSearchQuery', 'field'=>'string'],
'Couchbase\WildcardSearchQuery::jsonSerialize' => ['array'],
'Couchbase\zlibCompress' => ['string', 'data'=>'string'],
'Couchbase\zlibDecompress' => ['string', 'data'=>'string'],
'count' => ['int', 'value'=>'Countable|array|SimpleXMLElement|ResourceBundle', 'mode='=>'int'],
'count_chars' => ['array<int,int>|string', 'input'=>'string', 'mode='=>'int'],
'Countable::count' => ['int'],
'crack_check' => ['bool', 'dictionary'=>'', 'password'=>'string'],
'crack_closedict' => ['bool', 'dictionary='=>'resource'],
'crack_getlastmessage' => ['string'],
'crack_opendict' => ['resource|false', 'dictionary'=>'string'],
'crash' => [''],
'crc32' => ['int', 'string'=>'string'],
'crypt' => ['string', 'string'=>'string', 'salt='=>'string'],
'ctype_alnum' => ['bool', 'text'=>'string|int'],
'ctype_alpha' => ['bool', 'text'=>'string|int'],
'ctype_cntrl' => ['bool', 'text'=>'string|int'],
'ctype_digit' => ['bool', 'text'=>'string|int'],
'ctype_graph' => ['bool', 'text'=>'string|int'],
'ctype_lower' => ['bool', 'text'=>'string|int'],
'ctype_print' => ['bool', 'text'=>'string|int'],
'ctype_punct' => ['bool', 'text'=>'string|int'],
'ctype_space' => ['bool', 'text'=>'string|int'],
'ctype_upper' => ['bool', 'text'=>'string|int'],
'ctype_xdigit' => ['bool', 'text'=>'string|int'],
'cubrid_affected_rows' => ['int', 'req_identifier='=>''],
'cubrid_bind' => ['bool', 'req_identifier'=>'resource', 'bind_param'=>'int', 'bind_value'=>'mixed', 'bind_value_type='=>'string'],
'cubrid_client_encoding' => ['string', 'conn_identifier='=>''],
'cubrid_close' => ['bool', 'conn_identifier='=>''],
'cubrid_close_prepare' => ['bool', 'req_identifier'=>'resource'],
'cubrid_close_request' => ['bool', 'req_identifier'=>'resource'],
'cubrid_col_get' => ['array', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string'],
'cubrid_col_size' => ['int', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string'],
'cubrid_column_names' => ['array', 'req_identifier'=>'resource'],
'cubrid_column_types' => ['array', 'req_identifier'=>'resource'],
'cubrid_commit' => ['bool', 'conn_identifier'=>'resource'],
'cubrid_connect' => ['resource', 'host'=>'string', 'port'=>'int', 'dbname'=>'string', 'userid='=>'string', 'passwd='=>'string'],
'cubrid_connect_with_url' => ['resource', 'conn_url'=>'string', 'userid='=>'string', 'passwd='=>'string'],
'cubrid_current_oid' => ['string', 'req_identifier'=>'resource'],
'cubrid_data_seek' => ['bool', 'req_identifier'=>'', 'row_number'=>'int'],
'cubrid_db_name' => ['string', 'result'=>'array', 'index'=>'int'],
'cubrid_db_parameter' => ['array', 'conn_identifier'=>'resource'],
'cubrid_disconnect' => ['bool', 'conn_identifier'=>'resource'],
'cubrid_drop' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string'],
'cubrid_errno' => ['int', 'conn_identifier='=>''],
'cubrid_error' => ['string', 'connection='=>''],
'cubrid_error_code' => ['int'],
'cubrid_error_code_facility' => ['int'],
'cubrid_error_msg' => ['string'],
'cubrid_execute' => ['bool', 'conn_identifier'=>'', 'sql'=>'string', 'option='=>'int', 'request_identifier='=>''],
'cubrid_fetch' => ['mixed', 'result'=>'resource', 'type='=>'int'],
'cubrid_fetch_array' => ['array', 'result'=>'resource', 'type='=>'int'],
'cubrid_fetch_assoc' => ['array', 'result'=>'resource'],
'cubrid_fetch_field' => ['object', 'result'=>'resource', 'field_offset='=>'int'],
'cubrid_fetch_lengths' => ['array', 'result'=>'resource'],
'cubrid_fetch_object' => ['object', 'result'=>'resource', 'class_name='=>'string', 'params='=>'array'],
'cubrid_fetch_row' => ['array', 'result'=>'resource'],
'cubrid_field_flags' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'cubrid_field_len' => ['int', 'result'=>'resource', 'field_offset'=>'int'],
'cubrid_field_name' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'cubrid_field_seek' => ['bool', 'result'=>'resource', 'field_offset='=>'int'],
'cubrid_field_table' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'cubrid_field_type' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'cubrid_free_result' => ['bool', 'req_identifier'=>'resource'],
'cubrid_get' => ['mixed', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr='=>'mixed'],
'cubrid_get_autocommit' => ['bool', 'conn_identifier'=>'resource'],
'cubrid_get_charset' => ['string', 'conn_identifier'=>'resource'],
'cubrid_get_class_name' => ['string', 'conn_identifier'=>'resource', 'oid'=>'string'],
'cubrid_get_client_info' => ['string'],
'cubrid_get_db_parameter' => ['array', 'conn_identifier'=>'resource'],
'cubrid_get_query_timeout' => ['int', 'req_identifier'=>'resource'],
'cubrid_get_server_info' => ['string', 'conn_identifier'=>'resource'],
'cubrid_insert_id' => ['string', 'conn_identifier='=>'resource'],
'cubrid_is_instance' => ['int', 'conn_identifier'=>'resource', 'oid'=>'string'],
'cubrid_list_dbs' => ['array', 'conn_identifier'=>'resource'],
'cubrid_load_from_glo' => ['int', 'conn_identifier'=>'', 'oid'=>'string', 'file_name'=>'string'],
'cubrid_lob2_bind' => ['bool', 'req_identifier'=>'resource', 'bind_index'=>'int', 'bind_value'=>'mixed', 'bind_value_type='=>'string'],
'cubrid_lob2_close' => ['bool', 'lob_identifier'=>'resource'],
'cubrid_lob2_export' => ['bool', 'lob_identifier'=>'resource', 'file_name'=>'string'],
'cubrid_lob2_import' => ['bool', 'lob_identifier'=>'resource', 'file_name'=>'string'],
'cubrid_lob2_new' => ['resource', 'conn_identifier='=>'resource', 'type='=>'string'],
'cubrid_lob2_read' => ['string', 'lob_identifier'=>'resource', 'length'=>'int'],
'cubrid_lob2_seek' => ['bool', 'lob_identifier'=>'resource', 'offset'=>'int', 'origin='=>'int'],
'cubrid_lob2_seek64' => ['bool', 'lob_identifier'=>'resource', 'offset'=>'string', 'origin='=>'int'],
'cubrid_lob2_size' => ['int', 'lob_identifier'=>'resource'],
'cubrid_lob2_size64' => ['string', 'lob_identifier'=>'resource'],
'cubrid_lob2_tell' => ['int', 'lob_identifier'=>'resource'],
'cubrid_lob2_tell64' => ['string', 'lob_identifier'=>'resource'],
'cubrid_lob2_write' => ['bool', 'lob_identifier'=>'resource', 'buf'=>'string'],
'cubrid_lob_close' => ['bool', 'lob_identifier_array'=>'array'],
'cubrid_lob_export' => ['bool', 'conn_identifier'=>'resource', 'lob_identifier'=>'resource', 'path_name'=>'string'],
'cubrid_lob_get' => ['array', 'conn_identifier'=>'resource', 'sql'=>'string'],
'cubrid_lob_send' => ['bool', 'conn_identifier'=>'resource', 'lob_identifier'=>'resource'],
'cubrid_lob_size' => ['string', 'lob_identifier'=>'resource'],
'cubrid_lock_read' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string'],
'cubrid_lock_write' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string'],
'cubrid_move_cursor' => ['int', 'req_identifier'=>'resource', 'offset'=>'int', 'origin='=>'int'],
'cubrid_new_glo' => ['string', 'conn_identifier'=>'', 'class_name'=>'string', 'file_name'=>'string'],
'cubrid_next_result' => ['bool', 'result'=>'resource'],
'cubrid_num_cols' => ['int', 'req_identifier'=>'resource'],
'cubrid_num_fields' => ['int', 'result'=>'resource'],
'cubrid_num_rows' => ['int', 'req_identifier'=>'resource'],
'cubrid_pconnect' => ['resource', 'host'=>'string', 'port'=>'int', 'dbname'=>'string', 'userid='=>'string', 'passwd='=>'string'],
'cubrid_pconnect_with_url' => ['resource', 'conn_url'=>'string', 'userid='=>'string', 'passwd='=>'string'],
'cubrid_ping' => ['bool', 'conn_identifier='=>''],
'cubrid_prepare' => ['resource', 'conn_identifier'=>'resource', 'prepare_stmt'=>'string', 'option='=>'int'],
'cubrid_put' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr='=>'string', 'value='=>'mixed'],
'cubrid_query' => ['resource', 'query'=>'string', 'conn_identifier='=>''],
'cubrid_real_escape_string' => ['string', 'unescaped_string'=>'string', 'conn_identifier='=>''],
'cubrid_result' => ['string', 'result'=>'resource', 'row'=>'int', 'field='=>''],
'cubrid_rollback' => ['bool', 'conn_identifier'=>'resource'],
'cubrid_save_to_glo' => ['int', 'conn_identifier'=>'', 'oid'=>'string', 'file_name'=>'string'],
'cubrid_schema' => ['array', 'conn_identifier'=>'resource', 'schema_type'=>'int', 'class_name='=>'string', 'attr_name='=>'string'],
'cubrid_send_glo' => ['int', 'conn_identifier'=>'', 'oid'=>'string'],
'cubrid_seq_add' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'seq_element'=>'string'],
'cubrid_seq_drop' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'index'=>'int'],
'cubrid_seq_insert' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'index'=>'int', 'seq_element'=>'string'],
'cubrid_seq_put' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'index'=>'int', 'seq_element'=>'string'],
'cubrid_set_add' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'set_element'=>'string'],
'cubrid_set_autocommit' => ['bool', 'conn_identifier'=>'resource', 'mode'=>'bool'],
'cubrid_set_db_parameter' => ['bool', 'conn_identifier'=>'resource', 'param_type'=>'int', 'param_value'=>'int'],
'cubrid_set_drop' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'set_element'=>'string'],
'cubrid_set_query_timeout' => ['bool', 'req_identifier'=>'resource', 'timeout'=>'int'],
'cubrid_unbuffered_query' => ['resource', 'query'=>'string', 'conn_identifier='=>''],
'cubrid_version' => ['string'],
'curl_close' => ['void', 'handle'=>'CurlHandle'],
'curl_copy_handle' => ['CurlHandle', 'handle'=>'CurlHandle'],
'curl_errno' => ['int', 'handle'=>'CurlHandle'],
'curl_error' => ['string', 'handle'=>'CurlHandle'],
'curl_escape' => ['string|false', 'handle'=>'CurlHandle', 'string'=>'string'],
'curl_exec' => ['bool|string', 'handle'=>'CurlHandle'],
'curl_file_create' => ['CURLFile', 'filename'=>'string', 'mime_type='=>'string|null', 'posted_filename='=>'string|null'],
'curl_getinfo' => ['mixed', 'handle'=>'CurlHandle', 'option='=>'int'],
'curl_init' => ['CurlHandle|false', 'url='=>'string'],
'curl_multi_add_handle' => ['int', 'multi_handle'=>'CurlMultiHandle', 'handle'=>'CurlHandle'],
'curl_multi_close' => ['void', 'multi_handle'=>'CurlMultiHandle'],
'curl_multi_errno' => ['int', 'multi_handle'=>'CurlMultiHandle'],
'curl_multi_exec' => ['int', 'multi_handle'=>'CurlMultiHandle', '&w_still_running'=>'int'],
'curl_multi_getcontent' => ['string', 'handle'=>'CurlHandle'],
'curl_multi_info_read' => ['array|false', 'multi_handle'=>'CurlMultiHandle', '&w_queued_messages='=>'int'],
'curl_multi_init' => ['CurlMultiHandle|false'],
'curl_multi_remove_handle' => ['int', 'multi_handle'=>'CurlMultiHandle', 'handle'=>'CurlHandle'],
'curl_multi_select' => ['int', 'multi_handle'=>'CurlMultiHandle', 'timeout='=>'float'],
'curl_multi_setopt' => ['bool', 'multi_handle'=>'CurlMultiHandle', 'option'=>'int', 'value'=>'mixed'],
'curl_multi_strerror' => ['?string', 'error_code'=>'int'],
'curl_pause' => ['int', 'handle'=>'CurlHandle', 'flags'=>'int'],
'curl_reset' => ['void', 'handle'=>'CurlHandle'],
'curl_setopt' => ['bool', 'handle'=>'CurlHandle', 'option'=>'int', 'value'=>'callable|mixed'],
'curl_setopt_array' => ['bool', 'handle'=>'CurlHandle', 'options'=>'array'],
'curl_share_close' => ['void', 'share_handle'=>'CurlShareHandle'],
'curl_share_errno' => ['int', 'share_handle'=>'CurlShareHandle'],
'curl_share_init' => ['CurlShareHandle'],
'curl_share_setopt' => ['bool', 'share_handle'=>'CurlShareHandle', 'option'=>'int', 'value'=>'mixed'],
'curl_share_strerror' => ['?string', 'error_code'=>'int'],
'curl_strerror' => ['?string', 'error_code'=>'int'],
'curl_unescape' => ['string|false', 'handle'=>'CurlShareHandle', 'string'=>'string'],
'curl_version' => ['array', 'version='=>'int'],
'CURLFile::__construct' => ['void', 'filename'=>'string', 'mimetype='=>'string', 'postfilename='=>'string'],
'CURLFile::__wakeup' => ['void'],
'CURLFile::getFilename' => ['string'],
'CURLFile::getMimeType' => ['string'],
'CURLFile::getPostFilename' => ['string'],
'CURLFile::setMimeType' => ['void', 'mime'=>'string'],
'CURLFile::setPostFilename' => ['void', 'name'=>'string'],
'CURLStringFile::__construct' => ['void', 'data'=>'string', 'postname'=>'string', 'mime='=>'string'],
'current' => ['mixed|false', 'array'=>'array|object'],
'cyrus_authenticate' => ['void', 'connection'=>'resource', 'mechlist='=>'string', 'service='=>'string', 'user='=>'string', 'minssf='=>'int', 'maxssf='=>'int', 'authname='=>'string', 'password='=>'string'],
'cyrus_bind' => ['bool', 'connection'=>'resource', 'callbacks'=>'array'],
'cyrus_close' => ['bool', 'connection'=>'resource'],
'cyrus_connect' => ['resource', 'host='=>'string', 'port='=>'string', 'flags='=>'int'],
'cyrus_query' => ['array', 'connection'=>'resource', 'query'=>'string'],
'cyrus_unbind' => ['bool', 'connection'=>'resource', 'trigger_name'=>'string'],
'date' => ['string', 'format'=>'string', 'timestamp='=>'?int'],
'date_add' => ['DateTime|false', 'object'=>'DateTime', 'interval'=>'DateInterval'],
'date_create' => ['DateTime|false', 'datetime='=>'string', 'timezone='=>'?DateTimeZone'],
'date_create_from_format' => ['DateTime|false', 'format'=>'string', 'datetime'=>'string', 'timezone='=>'?\DateTimeZone'],
'date_create_immutable' => ['DateTimeImmutable|false', 'datetime='=>'string', 'timezone='=>'?DateTimeZone'],
'date_create_immutable_from_format' => ['DateTimeImmutable|false', 'format'=>'string', 'datetime'=>'string', 'timezone='=>'?DateTimeZone'],
'date_date_set' => ['DateTime|false', 'object'=>'DateTime', 'year'=>'int', 'month'=>'int', 'day'=>'int'],
'date_default_timezone_get' => ['string'],
'date_default_timezone_set' => ['bool', 'timezoneId'=>'string'],
'date_diff' => ['DateInterval|false', 'baseObject'=>'DateTimeInterface', 'targetObject'=>'DateTimeInterface', 'absolute='=>'bool'],
'date_format' => ['string', 'object'=>'DateTimeInterface', 'format'=>'string'],
'date_get_last_errors' => ['array{warning_count:int,warnings:array<int,string>,error_count:int,errors:array<int,string>}'],
'date_interval_create_from_date_string' => ['DateInterval', 'datetime'=>'string'],
'date_interval_format' => ['string', 'object'=>'DateInterval', 'format'=>'string'],
'date_isodate_set' => ['DateTime|false', 'object'=>'DateTime', 'year'=>'int', 'week'=>'int', 'dayOfWeek='=>'int|mixed'],
'date_modify' => ['DateTime|false', 'object'=>'DateTime', 'modifier'=>'string'],
'date_offset_get' => ['int|false', 'object'=>'DateTimeInterface'],
'date_parse' => ['array|false', 'datetime'=>'string'],
'date_parse_from_format' => ['array', 'format'=>'string', 'datetime'=>'string'],
'date_sub' => ['DateTime|false', 'object'=>'DateTime', 'interval'=>'DateInterval'],
'date_sun_info' => ['array|false', 'timestamp'=>'int', 'latitude'=>'float', 'longitude'=>'float'],
'date_sunrise' => ['mixed', 'timestamp'=>'int', 'returnFormat='=>'int', 'latitude='=>'float', 'longitude='=>'float', 'zenith='=>'float', 'utcOffset='=>'float'],
'date_sunset' => ['mixed', 'timestamp'=>'int', 'returnFormat='=>'int', 'latitude='=>'float', 'longitude='=>'float', 'zenith='=>'float', 'utcOffset='=>'float'],
'date_time_set' => ['DateTime|false', 'object'=>'', 'hour'=>'', 'minute'=>'', 'second='=>'', 'microsecond='=>''],
'date_timestamp_get' => ['int', 'object'=>'DateTimeInterface'],
'date_timestamp_set' => ['DateTime|false', 'object'=>'DateTime', 'timestamp'=>'int'],
'date_timezone_get' => ['DateTimeZone|false', 'object'=>'DateTimeInterface'],
'date_timezone_set' => ['DateTime|false', 'object'=>'DateTime', 'timezone'=>'DateTimeZone'],
'datefmt_create' => ['IntlDateFormatter|false', 'locale'=>'?string', 'dateType'=>'?int', 'timeType'=>'?int', 'timezone='=>'string|DateTimeZone|IntlTimeZone|null', 'calendar='=>'int|IntlCalendar|null', 'pattern='=>'string'],
'datefmt_format' => ['string|false', 'formatter'=>'IntlDateFormatter', 'datetime'=>'DateTime|IntlCalendar|array|int'],
'datefmt_format_object' => ['string|false', 'datetime'=>'object', 'format='=>'mixed', 'locale='=>'string'],
'datefmt_get_calendar' => ['int', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_calendar_object' => ['IntlCalendar', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_datetype' => ['int', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_error_code' => ['int', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_error_message' => ['string', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_locale' => ['string|false', 'formatter'=>'IntlDateFormatter', 'type='=>'int'],
'datefmt_get_pattern' => ['string', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_timetype' => ['int', 'formatter'=>'IntlDateFormatter'],
'datefmt_get_timezone' => ['IntlTimeZone|false'],
'datefmt_get_timezone_id' => ['string', 'formatter'=>'IntlDateFormatter'],
'datefmt_is_lenient' => ['bool', 'formatter'=>'IntlDateFormatter'],
'datefmt_localtime' => ['array|false', 'formatter'=>'IntlDateFormatter', 'string='=>'string', '&rw_offset='=>'int'],
'datefmt_parse' => ['int|false', 'formatter'=>'IntlDateFormatter', 'string='=>'string', '&rw_offset='=>'int'],
'datefmt_set_calendar' => ['bool', 'formatter'=>'IntlDateFormatter', 'calendar'=>'int'],
'datefmt_set_lenient' => ['?bool', 'formatter'=>'IntlDateFormatter', 'lenient'=>'bool'],
'datefmt_set_pattern' => ['bool', 'formatter'=>'IntlDateFormatter', 'pattern'=>'string'],
'datefmt_set_timezone' => ['bool', 'formatter'=>'mixed'],
'datefmt_set_timezone_id' => ['bool', 'fmt'=>'IntlDateFormatter', 'zone'=>'string'],
'DateInterval::__construct' => ['void', 'spec'=>'string'],
'DateInterval::__set_state' => ['DateInterval', 'array'=>'array'],
'DateInterval::__wakeup' => ['void'],
'DateInterval::createFromDateString' => ['DateInterval', 'time'=>'string'],
'DateInterval::format' => ['string', 'format'=>'string'],
'DatePeriod::__construct' => ['void', 'start'=>'DateTimeInterface', 'interval'=>'DateInterval', 'recur'=>'int', 'options='=>'int'],
'DatePeriod::__construct\'1' => ['void', 'start'=>'DateTimeInterface', 'interval'=>'DateInterval', 'end'=>'DateTimeInterface', 'options='=>'int'],
'DatePeriod::__construct\'2' => ['void', 'iso'=>'string', 'options='=>'int'],
'DatePeriod::__wakeup' => ['void'],
'DatePeriod::getDateInterval' => ['DateInterval'],
'DatePeriod::getEndDate' => ['?DateTimeInterface'],
'DatePeriod::getStartDate' => ['DateTimeInterface'],
'DateTime::__construct' => ['void', 'time='=>'string'],
'DateTime::__construct\'1' => ['void', 'time'=>'?string', 'timezone'=>'?DateTimeZone'],
'DateTime::__set_state' => ['static', 'array'=>'array'],
'DateTime::__wakeup' => ['void'],
'DateTime::add' => ['static', 'interval'=>'DateInterval'],
'DateTime::createFromFormat' => ['static|false', 'format'=>'string', 'time'=>'string', 'timezone='=>'?DateTimeZone'],
'DateTime::createFromImmutable' => ['static', 'object'=>'DateTimeImmutable'],
'DateTime::createFromInterface' => ['self', 'object' => 'DateTimeInterface'],
'DateTime::diff' => ['DateInterval|false', 'datetime2'=>'DateTimeInterface', 'absolute='=>'bool'],
'DateTime::format' => ['string', 'format'=>'string'],
'DateTime::getLastErrors' => ['array{warning_count:int,warnings:array<int,string>,error_count:int,errors:array<int,string>}'],
'DateTime::getOffset' => ['int'],
'DateTime::getTimestamp' => ['int|false'],
'DateTime::getTimezone' => ['DateTimeZone|false'],
'DateTime::modify' => ['static|false', 'modify'=>'string'],
'DateTime::setDate' => ['static', 'year'=>'int', 'month'=>'int', 'day'=>'int'],
'DateTime::setISODate' => ['static', 'year'=>'int', 'week'=>'int', 'day='=>'int'],
'DateTime::setTime' => ['static|false', 'hour'=>'int', 'minute'=>'int', 'second='=>'int', 'microseconds='=>'int'],
'DateTime::setTimestamp' => ['static', 'unixtimestamp'=>'int'],
'DateTime::setTimezone' => ['static', 'timezone'=>'DateTimeZone'],
'DateTime::sub' => ['static', 'interval'=>'DateInterval'],
'DateTimeImmutable::__construct' => ['void', 'time='=>'string'],
'DateTimeImmutable::__construct\'1' => ['void', 'time'=>'?string', 'timezone'=>'?DateTimeZone'],
'DateTimeImmutable::__set_state' => ['static', 'array'=>'array'],
'DateTimeImmutable::__wakeup' => ['void'],
'DateTimeImmutable::add' => ['static', 'interval'=>'DateInterval'],
'DateTimeImmutable::createFromFormat' => ['static|false', 'format'=>'string', 'time'=>'string', 'timezone='=>'?DateTimeZone'],
'DateTimeImmutable::createFromInterface' => ['self', 'object' => 'DateTimeInterface'],
'DateTimeImmutable::createFromMutable' => ['static', 'datetime'=>'DateTime'],
'DateTimeImmutable::diff' => ['DateInterval', 'datetime2'=>'DateTimeInterface', 'absolute='=>'bool'],
'DateTimeImmutable::format' => ['string', 'format'=>'string'],
'DateTimeImmutable::getLastErrors' => ['array{warning_count:int,warnings:array<int,string>,error_count:int,errors:array<int,string>}'],
'DateTimeImmutable::getOffset' => ['int'],
'DateTimeImmutable::getTimestamp' => ['int|false'],
'DateTimeImmutable::getTimezone' => ['DateTimeZone|false'],
'DateTimeImmutable::modify' => ['static', 'modify'=>'string'],
'DateTimeImmutable::setDate' => ['static|false', 'year'=>'int', 'month'=>'int', 'day'=>'int'],
'DateTimeImmutable::setISODate' => ['static|false', 'year'=>'int', 'week'=>'int', 'day='=>'int'],
'DateTimeImmutable::setTime' => ['static|false', 'hour'=>'int', 'minute'=>'int', 'second='=>'int', 'microseconds='=>'int'],
'DateTimeImmutable::setTimestamp' => ['static|false', 'unixtimestamp'=>'int'],
'DateTimeImmutable::setTimezone' => ['static|false', 'timezone'=>'DateTimeZone'],
'DateTimeImmutable::sub' => ['static|false', 'interval'=>'DateInterval'],
'DateTimeInterface::diff' => ['DateInterval', 'datetime2'=>'DateTimeInterface', 'absolute='=>'bool'],
'DateTimeInterface::format' => ['string', 'format'=>'string'],
'DateTimeInterface::getOffset' => ['int'],
'DateTimeInterface::getTimestamp' => ['int|false'],
'DateTimeInterface::getTimezone' => ['DateTimeZone|false'],
'DateTimeZone::__construct' => ['void', 'timezone'=>'string'],
'DateTimeZone::__set_state' => ['DateTimeZone', 'array'=>'array'],
'DateTimeZone::__wakeup' => ['void'],
'DateTimeZone::getLocation' => ['array|false'],
'DateTimeZone::getName' => ['string'],
'DateTimeZone::getOffset' => ['int|false', 'datetime'=>'DateTimeInterface'],
'DateTimeZone::getTransitions' => ['list<array{ts: int, time: string, offset: int, isdst: bool, abbr: string}>|false', 'timestamp_begin='=>'int', 'timestamp_end='=>'int'],
'DateTimeZone::listAbbreviations' => ['array<string, list<array{dst: bool, offset: int, timezone_id: string|null}>>|false'],
'DateTimeZone::listIdentifiers' => ['list<string>', 'timezoneGroup='=>'int', 'countryCode='=>'string|null'],
'db2_autocommit' => ['mixed', 'connection'=>'resource', 'value='=>'int'],
'db2_bind_param' => ['bool', 'stmt'=>'resource', 'parameter_number'=>'int', 'variable_name'=>'string', 'parameter_type='=>'int', 'data_type='=>'int', 'precision='=>'int', 'scale='=>'int'],
'db2_client_info' => ['object|false', 'connection'=>'resource'],
'db2_close' => ['bool', 'connection'=>'resource'],
'db2_column_privileges' => ['resource|false', 'connection'=>'resource', 'qualifier='=>'string', 'schema='=>'string', 'table_name='=>'string', 'column_name='=>'string'],
'db2_columns' => ['resource|false', 'connection'=>'resource', 'qualifier='=>'string', 'schema='=>'string', 'table_name='=>'string', 'column_name='=>'string'],
'db2_commit' => ['bool', 'connection'=>'resource'],
'db2_conn_error' => ['string', 'connection='=>'resource'],
'db2_conn_errormsg' => ['string', 'connection='=>'resource'],
'db2_connect' => ['resource|false', 'database'=>'string', 'username'=>'string', 'password'=>'string', 'options='=>'array'],
'db2_cursor_type' => ['int', 'stmt'=>'resource'],
'db2_escape_string' => ['string', 'string_literal'=>'string'],
'db2_exec' => ['resource|false', 'connection'=>'resource', 'statement'=>'string', 'options='=>'array'],
'db2_execute' => ['bool', 'stmt'=>'resource', 'parameters='=>'array'],
'db2_fetch_array' => ['array|false', 'stmt'=>'resource', 'row_number='=>'int'],
'db2_fetch_assoc' => ['array|false', 'stmt'=>'resource', 'row_number='=>'int'],
'db2_fetch_both' => ['array|false', 'stmt'=>'resource', 'row_number='=>'int'],
'db2_fetch_object' => ['object|false', 'stmt'=>'resource', 'row_number='=>'int'],
'db2_fetch_row' => ['bool', 'stmt'=>'resource', 'row_number='=>'int'],
'db2_field_display_size' => ['int|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_name' => ['string|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_num' => ['int|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_precision' => ['int|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_scale' => ['int|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_type' => ['string|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_width' => ['int|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_foreign_keys' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'table_name'=>'string'],
'db2_free_result' => ['bool', 'stmt'=>'resource'],
'db2_free_stmt' => ['bool', 'stmt'=>'resource'],
'db2_get_option' => ['string|false', 'resource'=>'resource', 'option'=>'string'],
'db2_last_insert_id' => ['string', 'resource'=>'resource'],
'db2_lob_read' => ['string|false', 'stmt'=>'resource', 'colnum'=>'int', 'length'=>'int'],
'db2_next_result' => ['resource|false', 'stmt'=>'resource'],
'db2_num_fields' => ['int|false', 'stmt'=>'resource'],
'db2_num_rows' => ['int', 'stmt'=>'resource'],
'db2_pclose' => ['bool', 'resource'=>'resource'],
'db2_pconnect' => ['resource|false', 'database'=>'string', 'username'=>'string', 'password'=>'string', 'options='=>'array'],
'db2_prepare' => ['resource|false', 'connection'=>'resource', 'statement'=>'string', 'options='=>'array'],
'db2_primary_keys' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'table_name'=>'string'],
'db2_primarykeys' => [''],
'db2_procedure_columns' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'procedure'=>'string', 'parameter'=>'string'],
'db2_procedurecolumns' => [''],
'db2_procedures' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'procedure'=>'string'],
'db2_result' => ['mixed', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_rollback' => ['bool', 'connection'=>'resource'],
'db2_server_info' => ['object|false', 'connection'=>'resource'],
'db2_set_option' => ['bool', 'resource'=>'resource', 'options'=>'array', 'type'=>'int'],
'db2_setoption' => [''],
'db2_special_columns' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'table_name'=>'string', 'scope'=>'int'],
'db2_specialcolumns' => [''],
'db2_statistics' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'table_name'=>'string', 'unique'=>'bool'],
'db2_stmt_error' => ['string', 'stmt='=>'resource'],
'db2_stmt_errormsg' => ['string', 'stmt='=>'resource'],
'db2_table_privileges' => ['resource|false', 'connection'=>'resource', 'qualifier='=>'string', 'schema='=>'string', 'table_name='=>'string'],
'db2_tableprivileges' => [''],
'db2_tables' => ['resource|false', 'connection'=>'resource', 'qualifier='=>'string', 'schema='=>'string', 'table_name='=>'string', 'table_type='=>'string'],
'dba_close' => ['void', 'dba'=>'resource'],
'dba_delete' => ['bool', 'key'=>'string', 'dba'=>'resource'],
'dba_exists' => ['bool', 'key'=>'string', 'dba'=>'resource'],
'dba_fetch' => ['string|false', 'key'=>'string', 'skip'=>'int', 'dba'=>'resource'],
'dba_fetch\'1' => ['string|false', 'key'=>'string', 'skip'=>'resource'],
'dba_firstkey' => ['string', 'dba'=>'resource'],
'dba_handlers' => ['array', 'full_info='=>'bool'],
'dba_insert' => ['bool', 'key'=>'string', 'value'=>'string', 'dba'=>'resource'],
'dba_key_split' => ['array|false', 'key'=>'string'],
'dba_list' => ['array'],
'dba_nextkey' => ['string', 'dba'=>'resource'],
'dba_open' => ['resource', 'path'=>'string', 'mode'=>'string', 'handler='=>'string', '...handler_params='=>'string'],
'dba_optimize' => ['bool', 'dba'=>'resource'],
'dba_popen' => ['resource', 'path'=>'string', 'mode'=>'string', 'handler='=>'string', '...handler_params='=>'string'],
'dba_replace' => ['bool', 'key'=>'string', 'value'=>'string', 'dba'=>'resource'],
'dba_sync' => ['bool', 'dba'=>'resource'],
'dbase_add_record' => ['bool', 'dbase_identifier'=>'resource', 'record'=>'array'],
'dbase_close' => ['bool', 'dbase_identifier'=>'resource'],
'dbase_create' => ['resource|false', 'filename'=>'string', 'fields'=>'array'],
'dbase_delete_record' => ['bool', 'dbase_identifier'=>'resource', 'record_number'=>'int'],
'dbase_get_header_info' => ['array', 'dbase_identifier'=>'resource'],
'dbase_get_record' => ['array', 'dbase_identifier'=>'resource', 'record_number'=>'int'],
'dbase_get_record_with_names' => ['array', 'dbase_identifier'=>'resource', 'record_number'=>'int'],
'dbase_numfields' => ['int', 'dbase_identifier'=>'resource'],
'dbase_numrecords' => ['int', 'dbase_identifier'=>'resource'],
'dbase_open' => ['resource|false', 'filename'=>'string', 'mode'=>'int'],
'dbase_pack' => ['bool', 'dbase_identifier'=>'resource'],
'dbase_replace_record' => ['bool', 'dbase_identifier'=>'resource', 'record'=>'array', 'record_number'=>'int'],
'dbplus_add' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_aql' => ['resource', 'query'=>'string', 'server='=>'string', 'dbpath='=>'string'],
'dbplus_chdir' => ['string', 'newdir='=>'string'],
'dbplus_close' => ['mixed', 'relation'=>'resource'],
'dbplus_curr' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_errcode' => ['string', 'errno='=>'int'],
'dbplus_errno' => ['int'],
'dbplus_find' => ['int', 'relation'=>'resource', 'constraints'=>'array', 'tuple'=>'mixed'],
'dbplus_first' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_flush' => ['int', 'relation'=>'resource'],
'dbplus_freealllocks' => ['int'],
'dbplus_freelock' => ['int', 'relation'=>'resource', 'tuple'=>'string'],
'dbplus_freerlocks' => ['int', 'relation'=>'resource'],
'dbplus_getlock' => ['int', 'relation'=>'resource', 'tuple'=>'string'],
'dbplus_getunique' => ['int', 'relation'=>'resource', 'uniqueid'=>'int'],
'dbplus_info' => ['int', 'relation'=>'resource', 'key'=>'string', 'result'=>'array'],
'dbplus_last' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_lockrel' => ['int', 'relation'=>'resource'],
'dbplus_next' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_open' => ['resource', 'name'=>'string'],
'dbplus_prev' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_rchperm' => ['int', 'relation'=>'resource', 'mask'=>'int', 'user'=>'string', 'group'=>'string'],
'dbplus_rcreate' => ['resource', 'name'=>'string', 'domlist'=>'mixed', 'overwrite='=>'bool'],
'dbplus_rcrtexact' => ['mixed', 'name'=>'string', 'relation'=>'resource', 'overwrite='=>'bool'],
'dbplus_rcrtlike' => ['mixed', 'name'=>'string', 'relation'=>'resource', 'overwrite='=>'int'],
'dbplus_resolve' => ['array', 'relation_name'=>'string'],
'dbplus_restorepos' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_rkeys' => ['mixed', 'relation'=>'resource', 'domlist'=>'mixed'],
'dbplus_ropen' => ['resource', 'name'=>'string'],
'dbplus_rquery' => ['resource', 'query'=>'string', 'dbpath='=>'string'],
'dbplus_rrename' => ['int', 'relation'=>'resource', 'name'=>'string'],
'dbplus_rsecindex' => ['mixed', 'relation'=>'resource', 'domlist'=>'mixed', 'type'=>'int'],
'dbplus_runlink' => ['int', 'relation'=>'resource'],
'dbplus_rzap' => ['int', 'relation'=>'resource'],
'dbplus_savepos' => ['int', 'relation'=>'resource'],
'dbplus_setindex' => ['int', 'relation'=>'resource', 'idx_name'=>'string'],
'dbplus_setindexbynumber' => ['int', 'relation'=>'resource', 'idx_number'=>'int'],
'dbplus_sql' => ['resource', 'query'=>'string', 'server='=>'string', 'dbpath='=>'string'],
'dbplus_tcl' => ['string', 'sid'=>'int', 'script'=>'string'],
'dbplus_tremove' => ['int', 'relation'=>'resource', 'tuple'=>'array', 'current='=>'array'],
'dbplus_undo' => ['int', 'relation'=>'resource'],
'dbplus_undoprepare' => ['int', 'relation'=>'resource'],
'dbplus_unlockrel' => ['int', 'relation'=>'resource'],
'dbplus_unselect' => ['int', 'relation'=>'resource'],
'dbplus_update' => ['int', 'relation'=>'resource', 'old'=>'array', 'new'=>'array'],
'dbplus_xlockrel' => ['int', 'relation'=>'resource'],
'dbplus_xunlockrel' => ['int', 'relation'=>'resource'],
'dbx_close' => ['int', 'link_identifier'=>'object'],
'dbx_compare' => ['int', 'row_a'=>'array', 'row_b'=>'array', 'column_key'=>'string', 'flags='=>'int'],
'dbx_connect' => ['object', 'module'=>'mixed', 'host'=>'string', 'database'=>'string', 'username'=>'string', 'password'=>'string', 'persistent='=>'int'],
'dbx_error' => ['string', 'link_identifier'=>'object'],
'dbx_escape_string' => ['string', 'link_identifier'=>'object', 'text'=>'string'],
'dbx_fetch_row' => ['mixed', 'result_identifier'=>'object'],
'dbx_query' => ['mixed', 'link_identifier'=>'object', 'sql_statement'=>'string', 'flags='=>'int'],
'dbx_sort' => ['bool', 'result'=>'object', 'user_compare_function'=>'string'],
'dcgettext' => ['string', 'domain'=>'string', 'message'=>'string', 'category'=>'int'],
'dcngettext' => ['string', 'domain'=>'string', 'singular'=>'string', 'plural'=>'string', 'count'=>'int', 'category'=>'int'],
'deaggregate' => ['', 'object'=>'object', 'class_name='=>'string'],
'debug_backtrace' => ['list<array{file:string,line:int,function:string,class?:class-string,object?:object,type?:string,args?:list}>', 'options='=>'int', 'limit='=>'int'],
'debug_print_backtrace' => ['void', 'options='=>'int', 'limit='=>'int'],
'debug_zval_dump' => ['void', '...value'=>'mixed'],
'debugger_connect' => [''],
'debugger_connector_pid' => [''],
'debugger_get_server_start_time' => [''],
'debugger_print' => [''],
'debugger_start_debug' => [''],
'decbin' => ['string', 'num'=>'int'],
'dechex' => ['string', 'num'=>'int'],
'decoct' => ['string', 'num'=>'int'],
'define' => ['bool', 'constant_name'=>'string', 'value'=>'mixed', 'case_insensitive='=>'bool'],
'define_syslog_variables' => ['void'],
'defined' => ['bool', 'constant_name'=>'string'],
'deflate_add' => ['string|false', 'context'=>'resource', 'data'=>'string', 'flush_mode='=>'int'],
'deflate_init' => ['resource|false', 'encoding'=>'int', 'options='=>'array'],
'deg2rad' => ['float', 'num'=>'float'],
'dgettext' => ['string', 'domain'=>'string', 'message'=>'string'],
'dio_close' => ['void', 'fd'=>'resource'],
'dio_fcntl' => ['mixed', 'fd'=>'resource', 'cmd'=>'int', 'args='=>'mixed'],
'dio_open' => ['resource|false', 'filename'=>'string', 'flags'=>'int', 'mode='=>'int'],
'dio_read' => ['string', 'fd'=>'resource', 'length='=>'int'],
'dio_seek' => ['int', 'fd'=>'resource', 'pos'=>'int', 'whence='=>'int'],
'dio_stat' => ['?array', 'fd'=>'resource'],
'dio_tcsetattr' => ['bool', 'fd'=>'resource', 'options'=>'array'],
'dio_truncate' => ['bool', 'fd'=>'resource', 'offset'=>'int'],
'dio_write' => ['int', 'fd'=>'resource', 'data'=>'string', 'length='=>'int'],
'dir' => ['Directory|false|null', 'directory'=>'string', 'context='=>'resource'],
'Directory::close' => ['void', 'dir_handle='=>'resource'],
'Directory::read' => ['string|false', 'dir_handle='=>'resource'],
'Directory::rewind' => ['void', 'dir_handle='=>'resource'],
'DirectoryIterator::__construct' => ['void', 'path'=>'string'],
'DirectoryIterator::__toString' => ['string'],
'DirectoryIterator::current' => ['DirectoryIterator'],
'DirectoryIterator::getATime' => ['int'],
'DirectoryIterator::getBasename' => ['string', 'suffix='=>'string'],
'DirectoryIterator::getCTime' => ['int'],
'DirectoryIterator::getExtension' => ['string'],
'DirectoryIterator::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'DirectoryIterator::getFilename' => ['string'],
'DirectoryIterator::getGroup' => ['int'],
'DirectoryIterator::getInode' => ['int'],
'DirectoryIterator::getLinkTarget' => ['string'],
'DirectoryIterator::getMTime' => ['int'],
'DirectoryIterator::getOwner' => ['int'],
'DirectoryIterator::getPath' => ['string'],
'DirectoryIterator::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'DirectoryIterator::getPathname' => ['string'],
'DirectoryIterator::getPerms' => ['int'],
'DirectoryIterator::getRealPath' => ['string'],
'DirectoryIterator::getSize' => ['int'],
'DirectoryIterator::getType' => ['string'],
'DirectoryIterator::isDir' => ['bool'],
'DirectoryIterator::isDot' => ['bool'],
'DirectoryIterator::isExecutable' => ['bool'],
'DirectoryIterator::isFile' => ['bool'],
'DirectoryIterator::isLink' => ['bool'],
'DirectoryIterator::isReadable' => ['bool'],
'DirectoryIterator::isWritable' => ['bool'],
'DirectoryIterator::key' => ['string'],
'DirectoryIterator::next' => ['void'],
'DirectoryIterator::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'DirectoryIterator::rewind' => ['void'],
'DirectoryIterator::seek' => ['void', 'position'=>'int'],
'DirectoryIterator::setFileClass' => ['void', 'class_name='=>'string'],
'DirectoryIterator::setInfoClass' => ['void', 'class_name='=>'string'],
'DirectoryIterator::valid' => ['bool'],
'dirname' => ['string', 'path'=>'string', 'levels='=>'int'],
'disk_free_space' => ['float|false', 'directory'=>'string'],
'disk_total_space' => ['float|false', 'directory'=>'string'],
'diskfreespace' => ['float|false', 'directory'=>'string'],
'display_disabled_function' => [''],
'dl' => ['bool', 'extension_filename'=>'string'],
'dngettext' => ['string', 'domain'=>'string', 'singular'=>'string', 'plural'=>'string', 'count'=>'int'],
'dns_check_record' => ['bool', 'hostname'=>'string', 'type='=>'string'],
'dns_get_mx' => ['bool', 'hostname'=>'string', '&w_hosts'=>'array', '&w_weights'=>'array'],
'dns_get_record' => ['list<array>|false', 'hostname'=>'string', 'type='=>'int', '&w_authoritative_name_servers='=>'array', '&w_additional_records='=>'array', 'raw='=>'bool'],
'dom_document_relaxNG_validate_file' => ['bool', 'filename'=>'string'],
'dom_document_relaxNG_validate_xml' => ['bool', 'source'=>'string'],
'dom_document_schema_validate' => ['bool', 'source'=>'string', 'flags'=>'int'],
'dom_document_schema_validate_file' => ['bool', 'filename'=>'string', 'flags'=>'int'],
'dom_document_xinclude' => ['int', 'options'=>'int'],
'dom_import_simplexml' => ['DOMElement|false', 'node'=>'SimpleXMLElement'],
'dom_xpath_evaluate' => ['', 'expr'=>'string', 'context'=>'DOMNode', 'registernodens'=>'bool'],
'dom_xpath_query' => ['DOMNodeList', 'expr'=>'string', 'context'=>'DOMNode', 'registernodens'=>'bool'],
'dom_xpath_register_ns' => ['bool', 'prefix'=>'string', 'uri'=>'string'],
'dom_xpath_register_php_functions' => [''],
'DomainException::__clone' => ['void'],
'DomainException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?DomainException'],
'DomainException::__toString' => ['string'],
'DomainException::__wakeup' => ['void'],
'DomainException::getCode' => ['int'],
'DomainException::getFile' => ['string'],
'DomainException::getLine' => ['int'],
'DomainException::getMessage' => ['string'],
'DomainException::getPrevious' => ['Throwable|DomainException|null'],
'DomainException::getTrace' => ['list<array<string,mixed>>'],
'DomainException::getTraceAsString' => ['string'],
'DOMAttr::__construct' => ['void', 'name'=>'string', 'value='=>'string'],
'DOMAttr::getLineNo' => ['int'],
'DOMAttr::getNodePath' => ['?string'],
'DOMAttr::hasAttributes' => ['bool'],
'DOMAttr::hasChildNodes' => ['bool'],
'DOMAttr::insertBefore' => ['DOMNode', 'newnode'=>'DOMNode', 'refnode='=>'DOMNode'],
'DOMAttr::isDefaultNamespace' => ['bool', 'namespaceuri'=>'string'],
'DOMAttr::isId' => ['bool'],
'DOMAttr::isSameNode' => ['bool', 'node'=>'DOMNode'],
'DOMAttr::isSupported' => ['bool', 'feature'=>'string', 'version'=>'string'],
'DOMAttr::lookupNamespaceUri' => ['string', 'prefix'=>'string'],
'DOMAttr::lookupPrefix' => ['string', 'namespaceuri'=>'string'],
'DOMAttr::normalize' => ['void'],
'DOMAttr::removeChild' => ['DOMNode', 'oldnode'=>'DOMNode'],
'DOMAttr::replaceChild' => ['DOMNode', 'newnode'=>'DOMNode', 'oldnode'=>'DOMNode'],
'DomAttribute::name' => ['string'],
'DomAttribute::set_value' => ['bool', 'content'=>'string'],
'DomAttribute::specified' => ['bool'],
'DomAttribute::value' => ['string'],
'DOMCdataSection::__construct' => ['void', 'value'=>'string'],
'DOMCharacterData::appendData' => ['void', 'data'=>'string'],
'DOMCharacterData::deleteData' => ['void', 'offset'=>'int', 'count'=>'int'],
'DOMCharacterData::insertData' => ['void', 'offset'=>'int', 'data'=>'string'],
'DOMCharacterData::replaceData' => ['void', 'offset'=>'int', 'count'=>'int', 'data'=>'string'],
'DOMCharacterData::substringData' => ['string', 'offset'=>'int', 'count'=>'int'],
'DOMComment::__construct' => ['void', 'value='=>'string'],
'DOMDocument::__construct' => ['void', 'version='=>'string', 'encoding='=>'string'],
'DOMDocument::createAttribute' => ['DOMAttr|false', 'name'=>'string'],
'DOMDocument::createAttributeNS' => ['DOMAttr|false', 'namespaceuri'=>'string', 'qualifiedname'=>'string'],
'DOMDocument::createCDATASection' => ['DOMCDATASection|false', 'data'=>'string'],
'DOMDocument::createComment' => ['DOMComment|false', 'data'=>'string'],
'DOMDocument::createDocumentFragment' => ['DOMDocumentFragment|false'],
'DOMDocument::createElement' => ['DOMElement|false', 'name'=>'string', 'value='=>'string'],
'DOMDocument::createElementNS' => ['DOMElement|false', 'namespaceuri'=>'string', 'qualifiedname'=>'string', 'value='=>'string'],
'DOMDocument::createEntityReference' => ['DOMEntityReference|false', 'name'=>'string'],
'DOMDocument::createProcessingInstruction' => ['DOMProcessingInstruction|false', 'target'=>'string', 'data='=>'string'],
'DOMDocument::createTextNode' => ['DOMText|false', 'content'=>'string'],
'DOMDocument::getElementById' => ['?DOMElement', 'elementid'=>'string'],
'DOMDocument::getElementsByTagName' => ['DOMNodeList', 'name'=>'string'],
'DOMDocument::getElementsByTagNameNS' => ['DOMNodeList', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMDocument::importNode' => ['DOMNode|false', 'importednode'=>'DOMNode', 'deep='=>'bool'],
'DOMDocument::load' => ['DOMDocument|bool', 'filename'=>'string', 'options='=>'int'],
'DOMDocument::loadHTML' => ['bool', 'source'=>'string', 'options='=>'int'],
'DOMDocument::loadHTMLFile' => ['bool', 'filename'=>'string', 'options='=>'int'],
'DOMDocument::loadXML' => ['DOMDocument|bool', 'source'=>'string', 'options='=>'int'],
'DOMDocument::normalizeDocument' => ['void'],
'DOMDocument::registerNodeClass' => ['bool', 'baseclass'=>'string', 'extendedclass'=>'string'],
'DOMDocument::relaxNGValidate' => ['bool', 'filename'=>'string'],
'DOMDocument::relaxNGValidateSource' => ['bool', 'source'=>'string'],
'DOMDocument::save' => ['int|false', 'filename'=>'string', 'options='=>'int'],
'DOMDocument::saveHTML' => ['string|false', 'node='=>'?DOMNode'],
'DOMDocument::saveHTMLFile' => ['int|false', 'filename'=>'string'],
'DOMDocument::saveXML' => ['string|false', 'node='=>'?DOMNode', 'options='=>'int'],
'DOMDocument::schemaValidate' => ['bool', 'filename'=>'string', 'flags='=>'int'],
'DOMDocument::schemaValidateSource' => ['bool', 'source'=>'string', 'flags='=>'int'],
'DOMDocument::validate' => ['bool'],
'DOMDocument::xinclude' => ['int', 'options='=>'int'],
'DOMDocumentFragment::__construct' => ['void'],
'DOMDocumentFragment::appendXML' => ['bool', 'data'=>'string'],
'DomDocumentType::entities' => ['array'],
'DomDocumentType::internal_subset' => ['bool'],
'DomDocumentType::name' => ['string'],
'DomDocumentType::notations' => ['array'],
'DomDocumentType::public_id' => ['string'],
'DomDocumentType::system_id' => ['string'],
'DOMElement::__construct' => ['void', 'name'=>'string', 'value='=>'string', 'uri='=>'string'],
'DOMElement::get_attribute' => ['string', 'name'=>'string'],
'DOMElement::get_attribute_node' => ['DomAttribute', 'name'=>'string'],
'DOMElement::get_elements_by_tagname' => ['array', 'name'=>'string'],
'DOMElement::getAttribute' => ['string', 'name'=>'string'],
'DOMElement::getAttributeNode' => ['DOMAttr', 'name'=>'string'],
'DOMElement::getAttributeNodeNS' => ['DOMAttr', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMElement::getAttributeNS' => ['string', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMElement::getElementsByTagName' => ['DOMNodeList', 'name'=>'string'],
'DOMElement::getElementsByTagNameNS' => ['DOMNodeList', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMElement::has_attribute' => ['bool', 'name'=>'string'],
'DOMElement::hasAttribute' => ['bool', 'name'=>'string'],
'DOMElement::hasAttributeNS' => ['bool', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMElement::remove_attribute' => ['bool', 'name'=>'string'],
'DOMElement::removeAttribute' => ['bool', 'name'=>'string'],
'DOMElement::removeAttributeNode' => ['bool', 'oldnode'=>'DOMAttr'],
'DOMElement::removeAttributeNS' => ['bool', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMElement::set_attribute' => ['DomAttribute', 'name'=>'string', 'value'=>'string'],
'DOMElement::set_attribute_node' => ['DomNode', 'attr'=>'DOMNode'],
'DOMElement::setAttribute' => ['DOMAttr|false', 'name'=>'string', 'value'=>'string'],
'DOMElement::setAttributeNode' => ['?DOMAttr', 'attr'=>'DOMAttr'],
'DOMElement::setAttributeNodeNS' => ['DOMAttr', 'attr'=>'DOMAttr'],
'DOMElement::setAttributeNS' => ['void', 'namespaceuri'=>'string', 'qualifiedname'=>'string', 'value'=>'string'],
'DOMElement::setIdAttribute' => ['void', 'name'=>'string', 'isid'=>'bool'],
'DOMElement::setIdAttributeNode' => ['void', 'attr'=>'DOMAttr', 'isid'=>'bool'],
'DOMElement::setIdAttributeNS' => ['void', 'namespaceuri'=>'string', 'localname'=>'string', 'isid'=>'bool'],
'DOMElement::tagname' => ['string'],
'DOMEntityReference::__construct' => ['void', 'name'=>'string'],
'DOMImplementation::__construct' => ['void'],
'DOMImplementation::createDocument' => ['DOMDocument', 'namespaceuri='=>'string', 'qualifiedname='=>'string', 'doctype='=>'DOMDocumentType'],
'DOMImplementation::createDocumentType' => ['DOMDocumentType', 'qualifiedname='=>'string', 'publicid='=>'string', 'systemid='=>'string'],
'DOMImplementation::hasFeature' => ['bool', 'feature'=>'string', 'version'=>'string'],
'DOMNamedNodeMap::count' => ['int'],
'DOMNamedNodeMap::getNamedItem' => ['?DOMNode', 'name'=>'string'],
'DOMNamedNodeMap::getNamedItemNS' => ['?DOMNode', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMNamedNodeMap::item' => ['?DOMNode', 'index'=>'int'],
'DomNode::add_namespace' => ['bool', 'uri'=>'string', 'prefix'=>'string'],
'DomNode::append_child' => ['DOMNode', 'newnode'=>'DOMNode'],
'DOMNode::appendChild' => ['DOMNode', 'newnode'=>'DOMNode'],
'DOMNode::C14N' => ['string', 'exclusive='=>'bool', 'with_comments='=>'bool', 'xpath='=>'array', 'ns_prefixes='=>'array'],
'DOMNode::C14NFile' => ['int|false', 'uri='=>'string', 'exclusive='=>'bool', 'with_comments='=>'bool', 'xpath='=>'array', 'ns_prefixes='=>'array'],
'DOMNode::cloneNode' => ['DOMNode', 'deep='=>'bool'],
'DOMNode::getLineNo' => ['int'],
'DOMNode::getNodePath' => ['?string'],
'DOMNode::hasAttributes' => ['bool'],
'DOMNode::hasChildNodes' => ['bool'],
'DOMNode::insertBefore' => ['DOMNode', 'newnode'=>'DOMNode', 'refnode='=>'DOMNode|null'],
'DOMNode::isDefaultNamespace' => ['bool', 'namespaceuri'=>'string'],
'DOMNode::isSameNode' => ['bool', 'node'=>'DOMNode'],
'DOMNode::isSupported' => ['bool', 'feature'=>'string', 'version'=>'string'],
'DOMNode::lookupNamespaceURI' => ['string', 'prefix'=>'string'],
'DOMNode::lookupPrefix' => ['string', 'namespaceuri'=>'string'],
'DOMNode::normalize' => ['void'],
'DOMNode::removeChild' => ['DOMNode', 'oldnode'=>'DOMNode'],
'DOMNode::replaceChild' => ['DOMNode|false', 'newnode'=>'DOMNode', 'oldnode'=>'DOMNode'],
'DOMNodeList::count' => ['int'],
'DOMNodeList::item' => ['?DOMNode', 'index'=>'int'],
'DOMProcessingInstruction::__construct' => ['void', 'name'=>'string', 'value'=>'string'],
'DomProcessingInstruction::data' => ['string'],
'DomProcessingInstruction::target' => ['string'],
'DOMText::__construct' => ['void', 'value='=>'string'],
'DOMText::isElementContentWhitespace' => ['bool'],
'DOMText::isWhitespaceInElementContent' => ['bool'],
'DOMText::splitText' => ['DOMText', 'offset'=>'int'],
'domxml_new_doc' => ['DomDocument', 'version'=>'string'],
'domxml_open_file' => ['DomDocument', 'filename'=>'string', 'mode='=>'int', 'error='=>'array'],
'domxml_open_mem' => ['DomDocument', 'string'=>'string', 'mode='=>'int', 'error='=>'array'],
'domxml_version' => ['string'],
'domxml_xmltree' => ['DomDocument', 'string'=>'string'],
'domxml_xslt_stylesheet' => ['DomXsltStylesheet', 'xsl_buf'=>'string'],
'domxml_xslt_stylesheet_doc' => ['DomXsltStylesheet', 'xsl_doc'=>'DOMDocument'],
'domxml_xslt_stylesheet_file' => ['DomXsltStylesheet', 'xsl_file'=>'string'],
'domxml_xslt_version' => ['int'],
'DOMXPath::__construct' => ['void', 'doc'=>'DOMDocument'],
'DOMXPath::evaluate' => ['mixed', 'expression'=>'string', 'contextnode='=>'?DOMNode', 'registernodens='=>'bool'],
'DOMXPath::query' => ['DOMNodeList|false', 'expression'=>'string', 'contextnode='=>'DOMNode|null', 'registernodens='=>'bool'],
'DOMXPath::registerNamespace' => ['bool', 'prefix'=>'string', 'namespaceuri'=>'string'],
'DOMXPath::registerPhpFunctions' => ['void', 'restrict='=>'mixed'],
'DomXsltStylesheet::process' => ['DomDocument', 'xml_doc'=>'DOMDocument', 'xslt_params='=>'array', 'is_xpath_param='=>'bool', 'profile_filename='=>'string'],
'DomXsltStylesheet::result_dump_file' => ['string', 'xmldoc'=>'DOMDocument', 'filename'=>'string'],
'DomXsltStylesheet::result_dump_mem' => ['string', 'xmldoc'=>'DOMDocument'],
'DOTNET::__call' => ['mixed', 'name'=>'string', 'args'=>''],
'DOTNET::__construct' => ['void', 'assembly_name'=>'string', 'datatype_name'=>'string', 'codepage='=>'int'],
'DOTNET::__get' => ['mixed', 'name'=>'string'],
'DOTNET::__set' => ['void', 'name'=>'string', 'value'=>''],
'dotnet_load' => ['int', 'assembly_name'=>'string', 'datatype_name='=>'string', 'codepage='=>'int'],
'doubleval' => ['float', 'value'=>'mixed'],
'Ds\Collection::clear' => ['void'],
'Ds\Collection::copy' => ['Ds\Collection'],
'Ds\Collection::isEmpty' => ['bool'],
'Ds\Collection::toArray' => ['array'],
'Ds\Deque::__construct' => ['void', 'values='=>'mixed'],
'Ds\Deque::allocate' => ['void', 'capacity'=>'int'],
'Ds\Deque::apply' => ['void', 'callback'=>'callable'],
'Ds\Deque::capacity' => ['int'],
'Ds\Deque::clear' => ['void'],
'Ds\Deque::contains' => ['bool', '...values='=>'mixed'],
'Ds\Deque::copy' => ['Ds\Deque'],
'Ds\Deque::count' => ['int'],
'Ds\Deque::filter' => ['Ds\Deque', 'callback='=>'callable'],
'Ds\Deque::find' => ['mixed', 'value'=>'mixed'],
'Ds\Deque::first' => ['mixed'],
'Ds\Deque::get' => ['void', 'index'=>'int'],
'Ds\Deque::insert' => ['void', 'index'=>'int', '...values='=>'mixed'],
'Ds\Deque::isEmpty' => ['bool'],
'Ds\Deque::join' => ['string', 'glue='=>'string'],
'Ds\Deque::jsonSerialize' => ['array'],
'Ds\Deque::last' => ['mixed'],
'Ds\Deque::map' => ['Ds\Deque', 'callback'=>'callable'],
'Ds\Deque::merge' => ['Ds\Deque', 'values'=>'mixed'],
'Ds\Deque::pop' => ['mixed'],
'Ds\Deque::push' => ['void', '...values='=>'mixed'],
'Ds\Deque::reduce' => ['mixed', 'callback'=>'callable', 'initial='=>'mixed'],
'Ds\Deque::remove' => ['mixed', 'index'=>'int'],
'Ds\Deque::reverse' => ['void'],
'Ds\Deque::reversed' => ['Ds\Deque'],
'Ds\Deque::rotate' => ['void', 'rotations'=>'int'],
'Ds\Deque::set' => ['void', 'index'=>'int', 'value'=>'mixed'],
'Ds\Deque::shift' => ['mixed'],
'Ds\Deque::slice' => ['Ds\Deque', 'index'=>'int', 'length='=>'?int'],
'Ds\Deque::sort' => ['void', 'comparator='=>'callable'],
'Ds\Deque::sorted' => ['Ds\Deque', 'comparator='=>'callable'],
'Ds\Deque::sum' => ['int|float'],
'Ds\Deque::toArray' => ['array'],
'Ds\Deque::unshift' => ['void', '...values='=>'mixed'],
'Ds\Hashable::equals' => ['bool', 'object'=>'mixed'],
'Ds\Hashable::hash' => ['mixed'],
'Ds\Map::__construct' => ['void', 'values='=>'mixed'],
'Ds\Map::allocate' => ['void', 'capacity'=>'int'],
'Ds\Map::apply' => ['void', 'callback'=>'callable'],
'Ds\Map::capacity' => ['int'],
'Ds\Map::clear' => ['void'],
'Ds\Map::copy' => ['Ds\Map'],
'Ds\Map::count' => ['int'],
'Ds\Map::diff' => ['Ds\Map', 'map'=>'Ds\Map'],
'Ds\Map::filter' => ['Ds\Map', 'callback='=>'callable'],
'Ds\Map::first' => ['Ds\Pair'],
'Ds\Map::get' => ['mixed', 'key'=>'mixed', 'default='=>'mixed'],
'Ds\Map::hasKey' => ['bool', 'key'=>'mixed'],
'Ds\Map::hasValue' => ['bool', 'value'=>'mixed'],
'Ds\Map::intersect' => ['Ds\Map', 'map'=>'Ds\Map'],
'Ds\Map::isEmpty' => ['bool'],
'Ds\Map::jsonSerialize' => ['array'],
'Ds\Map::keys' => ['Ds\Set'],
'Ds\Map::ksort' => ['void', 'comparator='=>'callable'],
'Ds\Map::ksorted' => ['Ds\Map', 'comparator='=>'callable'],
'Ds\Map::last' => ['Ds\Pair'],
'Ds\Map::map' => ['Ds\Map', 'callback'=>'callable'],
'Ds\Map::merge' => ['Ds\Map', 'values'=>'mixed'],
'Ds\Map::pairs' => ['Ds\Sequence'],
'Ds\Map::put' => ['void', 'key'=>'mixed', 'value'=>'mixed'],
'Ds\Map::putAll' => ['void', 'values'=>'mixed'],
'Ds\Map::reduce' => ['mixed', 'callback'=>'callable', 'initial='=>'mixed'],
'Ds\Map::remove' => ['mixed', 'key'=>'mixed', 'default='=>'mixed'],
'Ds\Map::reverse' => ['void'],
'Ds\Map::reversed' => ['Ds\Map'],
'Ds\Map::skip' => ['Ds\Pair', 'position'=>'int'],
'Ds\Map::slice' => ['Ds\Map', 'index'=>'int', 'length='=>'?int'],
'Ds\Map::sort' => ['void', 'comparator='=>'callable'],
'Ds\Map::sorted' => ['Ds\Map', 'comparator='=>'callable'],
'Ds\Map::sum' => ['int|float'],
'Ds\Map::toArray' => ['array'],
'Ds\Map::union' => ['Ds\Map', 'map'=>'Ds\Map'],
'Ds\Map::values' => ['Ds\Sequence'],
'Ds\Map::xor' => ['Ds\Map', 'map'=>'Ds\Map'],
'Ds\Pair::__construct' => ['void', 'key='=>'mixed', 'value='=>'mixed'],
'Ds\Pair::clear' => ['void'],
'Ds\Pair::copy' => ['Ds\Pair'],
'Ds\Pair::isEmpty' => ['bool'],
'Ds\Pair::jsonSerialize' => ['array'],
'Ds\Pair::toArray' => ['array'],
'Ds\PriorityQueue::__construct' => ['void'],
'Ds\PriorityQueue::allocate' => ['void', 'capacity'=>'int'],
'Ds\PriorityQueue::capacity' => ['int'],
'Ds\PriorityQueue::clear' => ['void'],
'Ds\PriorityQueue::copy' => ['Ds\PriorityQueue'],
'Ds\PriorityQueue::count' => ['int'],
'Ds\PriorityQueue::isEmpty' => ['bool'],
'Ds\PriorityQueue::jsonSerialize' => ['array'],
'Ds\PriorityQueue::peek' => ['mixed'],
'Ds\PriorityQueue::pop' => ['mixed'],
'Ds\PriorityQueue::push' => ['void', 'value'=>'mixed', 'priority'=>'int'],
'Ds\PriorityQueue::toArray' => ['array'],
'Ds\Queue::__construct' => ['void', 'values='=>'mixed'],
'Ds\Queue::allocate' => ['void', 'capacity'=>'int'],
'Ds\Queue::capacity' => ['int'],
'Ds\Queue::clear' => ['void'],
'Ds\Queue::copy' => ['Ds\Queue'],
'Ds\Queue::count' => ['int'],
'Ds\Queue::isEmpty' => ['bool'],
'Ds\Queue::jsonSerialize' => ['array'],
'Ds\Queue::peek' => ['mixed'],
'Ds\Queue::pop' => ['mixed'],
'Ds\Queue::push' => ['void', '...values='=>'mixed'],
'Ds\Queue::toArray' => ['array'],
'Ds\Sequence::allocate' => ['void', 'capacity'=>'int'],
'Ds\Sequence::apply' => ['void', 'callback'=>'callable'],
'Ds\Sequence::capacity' => ['int'],
'Ds\Sequence::contains' => ['bool', '...values='=>'mixed'],
'Ds\Sequence::filter' => ['Ds\Sequence', 'callback='=>'callable'],
'Ds\Sequence::find' => ['mixed', 'value'=>'mixed'],
'Ds\Sequence::first' => ['mixed'],
'Ds\Sequence::get' => ['mixed', 'index'=>'int'],
'Ds\Sequence::insert' => ['void', 'index'=>'int', '...values='=>'mixed'],
'Ds\Sequence::join' => ['string', 'glue='=>'string'],
'Ds\Sequence::last' => ['void'],
'Ds\Sequence::map' => ['Ds\Sequence', 'callback'=>'callable'],
'Ds\Sequence::merge' => ['Ds\Sequence', 'values'=>'mixed'],
'Ds\Sequence::pop' => ['mixed'],
'Ds\Sequence::push' => ['void', '...values='=>'mixed'],
'Ds\Sequence::reduce' => ['mixed', 'callback'=>'callable', 'initial='=>'mixed'],
'Ds\Sequence::remove' => ['mixed', 'index'=>'int'],
'Ds\Sequence::reverse' => ['void'],
'Ds\Sequence::reversed' => ['Ds\Sequence'],
'Ds\Sequence::rotate' => ['void', 'rotations'=>'int'],
'Ds\Sequence::set' => ['void', 'index'=>'int', 'value'=>'mixed'],
'Ds\Sequence::shift' => ['mixed'],
'Ds\Sequence::slice' => ['Ds\Sequence', 'index'=>'int', 'length='=>'?int'],
'Ds\Sequence::sort' => ['void', 'comparator='=>'callable'],
'Ds\Sequence::sorted' => ['Ds\Sequence', 'comparator='=>'callable'],
'Ds\Sequence::sum' => ['int|float'],
'Ds\Sequence::unshift' => ['void', '...values='=>'mixed'],
'Ds\Set::__construct' => ['void', 'values='=>'mixed'],
'Ds\Set::add' => ['void', '...values='=>'mixed'],
'Ds\Set::allocate' => ['void', 'capacity'=>'int'],
'Ds\Set::capacity' => ['int'],
'Ds\Set::clear' => ['void'],
'Ds\Set::contains' => ['bool', '...values='=>'mixed'],
'Ds\Set::copy' => ['Ds\Set'],
'Ds\Set::count' => ['int'],
'Ds\Set::diff' => ['Ds\Set', 'set'=>'Ds\Set'],
'Ds\Set::filter' => ['Ds\Set', 'callback='=>'callable'],
'Ds\Set::first' => ['mixed'],
'Ds\Set::get' => ['mixed', 'index'=>'int'],
'Ds\Set::intersect' => ['Ds\Set', 'set'=>'Ds\Set'],
'Ds\Set::isEmpty' => ['bool'],
'Ds\Set::join' => ['string', 'glue='=>'string'],
'Ds\Set::jsonSerialize' => ['array'],
'Ds\Set::last' => ['mixed'],
'Ds\Set::merge' => ['Ds\Set', 'values'=>'mixed'],
'Ds\Set::reduce' => ['mixed', 'callback'=>'callable', 'initial='=>'mixed'],
'Ds\Set::remove' => ['void', '...values='=>'mixed'],
'Ds\Set::reverse' => ['void'],
'Ds\Set::reversed' => ['Ds\Set'],
'Ds\Set::slice' => ['Ds\Set', 'index'=>'int', 'length='=>'?int'],
'Ds\Set::sort' => ['void', 'comparator='=>'callable'],
'Ds\Set::sorted' => ['Ds\Set', 'comparator='=>'callable'],
'Ds\Set::sum' => ['int|float'],
'Ds\Set::toArray' => ['array'],
'Ds\Set::union' => ['Ds\Set', 'set'=>'Ds\Set'],
'Ds\Set::xor' => ['Ds\Set', 'set'=>'Ds\Set'],
'Ds\Stack::__construct' => ['void', 'values='=>'mixed'],
'Ds\Stack::allocate' => ['void', 'capacity'=>'int'],
'Ds\Stack::capacity' => ['int'],
'Ds\Stack::clear' => ['void'],
'Ds\Stack::copy' => ['Ds\Stack'],
'Ds\Stack::count' => ['int'],
'Ds\Stack::isEmpty' => ['bool'],
'Ds\Stack::jsonSerialize' => ['array'],
'Ds\Stack::peek' => ['mixed'],
'Ds\Stack::pop' => ['mixed'],
'Ds\Stack::push' => ['void', '...values='=>'mixed'],
'Ds\Stack::toArray' => ['array'],
'Ds\Vector::__construct' => ['void', 'values='=>'mixed'],
'Ds\Vector::allocate' => ['void', 'capacity'=>'int'],
'Ds\Vector::apply' => ['void', 'callback'=>'callable'],
'Ds\Vector::capacity' => ['int'],
'Ds\Vector::clear' => ['void'],
'Ds\Vector::contains' => ['bool', '...values='=>'mixed'],
'Ds\Vector::copy' => ['Ds\Vector'],
'Ds\Vector::count' => ['int'],
'Ds\Vector::filter' => ['Ds\Vector', 'callback='=>'callable'],
'Ds\Vector::find' => ['mixed', 'value'=>'mixed'],
'Ds\Vector::first' => ['mixed'],
'Ds\Vector::get' => ['mixed', 'index'=>'int'],
'Ds\Vector::insert' => ['void', 'index'=>'int', '...values='=>'mixed'],
'Ds\Vector::isEmpty' => ['bool'],
'Ds\Vector::join' => ['string', 'glue='=>'string'],
'Ds\Vector::jsonSerialize' => ['array'],
'Ds\Vector::last' => ['mixed'],
'Ds\Vector::map' => ['Ds\Vector', 'callback'=>'callable'],
'Ds\Vector::merge' => ['Ds\Vector', 'values'=>'mixed'],
'Ds\Vector::pop' => ['mixed'],
'Ds\Vector::push' => ['void', '...values='=>'mixed'],
'Ds\Vector::reduce' => ['mixed', 'callback'=>'callable', 'initial='=>'mixed'],
'Ds\Vector::remove' => ['mixed', 'index'=>'int'],
'Ds\Vector::reverse' => ['void'],
'Ds\Vector::reversed' => ['Ds\Vector'],
'Ds\Vector::rotate' => ['void', 'rotations'=>'int'],
'Ds\Vector::set' => ['void', 'index'=>'int', 'value'=>'mixed'],
'Ds\Vector::shift' => ['mixed'],
'Ds\Vector::slice' => ['Ds\Vector', 'index'=>'int', 'length='=>'?int'],
'Ds\Vector::sort' => ['void', 'comparator='=>'callable'],
'Ds\Vector::sorted' => ['Ds\Vector', 'comparator='=>'callable'],
'Ds\Vector::sum' => ['int|float'],
'Ds\Vector::toArray' => ['array'],
'Ds\Vector::unshift' => ['void', '...values='=>'mixed'],
'easter_date' => ['int', 'year='=>'int'],
'easter_days' => ['int', 'year='=>'int', 'mode='=>'int'],
'echo' => ['void', 'arg1'=>'string', '...args='=>'string'],
'eio_busy' => ['resource', 'delay'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_cancel' => ['void', 'req'=>'resource'],
'eio_chmod' => ['resource', 'path'=>'string', 'mode'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_chown' => ['resource', 'path'=>'string', 'uid'=>'int', 'gid='=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_close' => ['resource', 'fd'=>'mixed', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_custom' => ['resource', 'execute'=>'callable', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_dup2' => ['resource', 'fd'=>'mixed', 'fd2'=>'mixed', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_event_loop' => ['bool'],
'eio_fallocate' => ['resource', 'fd'=>'mixed', 'mode'=>'int', 'offset'=>'int', 'length'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_fchmod' => ['resource', 'fd'=>'mixed', 'mode'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_fchown' => ['resource', 'fd'=>'mixed', 'uid'=>'int', 'gid='=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_fdatasync' => ['resource', 'fd'=>'mixed', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_fstat' => ['resource', 'fd'=>'mixed', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_fstatvfs' => ['resource', 'fd'=>'mixed', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_fsync' => ['resource', 'fd'=>'mixed', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_ftruncate' => ['resource', 'fd'=>'mixed', 'offset='=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_futime' => ['resource', 'fd'=>'mixed', 'atime'=>'float', 'mtime'=>'float', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_get_event_stream' => ['mixed'],
'eio_get_last_error' => ['string', 'req'=>'resource'],
'eio_grp' => ['resource', 'callback'=>'callable', 'data='=>'string'],
'eio_grp_add' => ['void', 'grp'=>'resource', 'req'=>'resource'],
'eio_grp_cancel' => ['void', 'grp'=>'resource'],
'eio_grp_limit' => ['void', 'grp'=>'resource', 'limit'=>'int'],
'eio_init' => ['void'],
'eio_link' => ['resource', 'path'=>'string', 'new_path'=>'string', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_lstat' => ['resource', 'path'=>'string', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_mkdir' => ['resource', 'path'=>'string', 'mode'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_mknod' => ['resource', 'path'=>'string', 'mode'=>'int', 'dev'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_nop' => ['resource', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_npending' => ['int'],
'eio_nready' => ['int'],
'eio_nreqs' => ['int'],
'eio_nthreads' => ['int'],
'eio_open' => ['resource', 'path'=>'string', 'flags'=>'int', 'mode'=>'int', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_poll' => ['int'],
'eio_read' => ['resource', 'fd'=>'mixed', 'length'=>'int', 'offset'=>'int', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_readahead' => ['resource', 'fd'=>'mixed', 'offset'=>'int', 'length'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_readdir' => ['resource', 'path'=>'string', 'flags'=>'int', 'pri'=>'int', 'callback'=>'callable', 'data='=>'string'],
'eio_readlink' => ['resource', 'path'=>'string', 'pri'=>'int', 'callback'=>'callable', 'data='=>'string'],
'eio_realpath' => ['resource', 'path'=>'string', 'pri'=>'int', 'callback'=>'callable', 'data='=>'string'],
'eio_rename' => ['resource', 'path'=>'string', 'new_path'=>'string', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_rmdir' => ['resource', 'path'=>'string', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_seek' => ['resource', 'fd'=>'mixed', 'offset'=>'int', 'whence'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_sendfile' => ['resource', 'out_fd'=>'mixed', 'in_fd'=>'mixed', 'offset'=>'int', 'length'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'string'],
'eio_set_max_idle' => ['void', 'nthreads'=>'int'],
'eio_set_max_parallel' => ['void', 'nthreads'=>'int'],
'eio_set_max_poll_reqs' => ['void', 'nreqs'=>'int'],
'eio_set_max_poll_time' => ['void', 'nseconds'=>'float'],
'eio_set_min_parallel' => ['void', 'nthreads'=>'string'],
'eio_stat' => ['resource', 'path'=>'string', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_statvfs' => ['resource', 'path'=>'string', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_symlink' => ['resource', 'path'=>'string', 'new_path'=>'string', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_sync' => ['resource', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_sync_file_range' => ['resource', 'fd'=>'mixed', 'offset'=>'int', 'nbytes'=>'int', 'flags'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_syncfs' => ['resource', 'fd'=>'mixed', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_truncate' => ['resource', 'path'=>'string', 'offset='=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_unlink' => ['resource', 'path'=>'string', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_utime' => ['resource', 'path'=>'string', 'atime'=>'float', 'mtime'=>'float', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_write' => ['resource', 'fd'=>'mixed', 'string'=>'string', 'length='=>'int', 'offset='=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'empty' => ['bool', 'value'=>'mixed'],
'EmptyIterator::current' => ['mixed'],
'EmptyIterator::key' => ['mixed'],
'EmptyIterator::next' => ['void'],
'EmptyIterator::rewind' => ['void'],
'EmptyIterator::valid' => ['bool'],
'enchant_broker_describe' => ['array', 'broker'=>'resource'],
'enchant_broker_dict_exists' => ['bool', 'broker'=>'resource', 'tag'=>'string'],
'enchant_broker_free' => ['bool', 'broker'=>'resource'],
'enchant_broker_free_dict' => ['bool', 'dictionary'=>'resource'],
'enchant_broker_get_dict_path' => ['string', 'broker'=>'resource', 'type'=>'int'],
'enchant_broker_get_error' => ['string|false', 'broker'=>'resource'],
'enchant_broker_init' => ['resource|false'],
'enchant_broker_list_dicts' => ['array<int,array{lang_tag:string,provider_name:string,provider_desc:string,provider_file:string}>|false', 'broker'=>'resource'],
'enchant_broker_request_dict' => ['resource|false', 'broker'=>'resource', 'tag'=>'string'],
'enchant_broker_request_pwl_dict' => ['resource|false', 'broker'=>'resource', 'filename'=>'string'],
'enchant_broker_set_dict_path' => ['bool', 'broker'=>'resource', 'type'=>'int', 'path'=>'string'],
'enchant_broker_set_ordering' => ['bool', 'broker'=>'resource', 'tag'=>'string', 'ordering'=>'string'],
'enchant_dict_add_to_personal' => ['void', 'dictionary'=>'resource', 'word'=>'string'],
'enchant_dict_add_to_session' => ['void', 'dictionary'=>'resource', 'word'=>'string'],
'enchant_dict_check' => ['bool', 'dictionary'=>'resource', 'word'=>'string'],
'enchant_dict_describe' => ['array', 'dictionary'=>'resource'],
'enchant_dict_get_error' => ['string', 'dictionary'=>'resource'],
'enchant_dict_is_in_session' => ['bool', 'dictionary'=>'resource', 'word'=>'string'],
'enchant_dict_quick_check' => ['bool', 'dictionary'=>'resource', 'word'=>'string', '&w_suggestions='=>'array<int,string>'],
'enchant_dict_store_replacement' => ['void', 'dictionary'=>'resource', 'misspelled'=>'string', 'correct'=>'string'],
'enchant_dict_suggest' => ['array', 'dictionary'=>'resource', 'word'=>'string'],
'end' => ['mixed|false', '&r_array'=>'array|object'],
'Error::__clone' => ['void'],
'Error::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?Error'],
'Error::__toString' => ['string'],
'Error::getCode' => ['int'],
'Error::getFile' => ['string'],
'Error::getLine' => ['int'],
'Error::getMessage' => ['string'],
'Error::getPrevious' => ['Throwable|Error|null'],
'Error::getTrace' => ['list<array<string,mixed>>'],
'Error::getTraceAsString' => ['string'],
'error_clear_last' => ['void'],
'error_get_last' => ['?array{type:int,message:string,file:string,line:int}'],
'error_log' => ['bool', 'message'=>'string', 'message_type='=>'int', 'destination='=>'string', 'additional_headers='=>'string'],
'error_reporting' => ['int', 'error_level='=>'int'],
'ErrorException::__clone' => ['void'],
'ErrorException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'severity='=>'int', 'filename='=>'string', 'lineno='=>'int', 'previous='=>'?Throwable|?ErrorException'],
'ErrorException::__toString' => ['string'],
'ErrorException::getCode' => ['int'],
'ErrorException::getFile' => ['string'],
'ErrorException::getLine' => ['int'],
'ErrorException::getMessage' => ['string'],
'ErrorException::getPrevious' => ['Throwable|ErrorException|null'],
'ErrorException::getSeverity' => ['int'],
'ErrorException::getTrace' => ['list<array<string,mixed>>'],
'ErrorException::getTraceAsString' => ['string'],
'escapeshellarg' => ['string', 'arg'=>'string'],
'escapeshellcmd' => ['string', 'command'=>'string'],
'Ev::backend' => ['int'],
'Ev::depth' => ['int'],
'Ev::embeddableBackends' => ['int'],
'Ev::feedSignal' => ['void', 'signum'=>'int'],
'Ev::feedSignalEvent' => ['void', 'signum'=>'int'],
'Ev::iteration' => ['int'],
'Ev::now' => ['float'],
'Ev::nowUpdate' => ['void'],
'Ev::recommendedBackends' => ['int'],
'Ev::resume' => ['void'],
'Ev::run' => ['void', 'flags='=>'int'],
'Ev::sleep' => ['void', 'seconds'=>'float'],
'Ev::stop' => ['void', 'how='=>'int'],
'Ev::supportedBackends' => ['int'],
'Ev::suspend' => ['void'],
'Ev::time' => ['float'],
'Ev::verify' => ['void'],
'eval' => ['mixed', 'code_str'=>'string'],
'EvCheck::__construct' => ['void', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvCheck::clear' => ['int'],
'EvCheck::createStopped' => ['EvCheck', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvCheck::feed' => ['void', 'events'=>'int'],
'EvCheck::getLoop' => ['EvLoop'],
'EvCheck::invoke' => ['void', 'events'=>'int'],
'EvCheck::keepAlive' => ['void', 'value'=>'bool'],
'EvCheck::setCallback' => ['void', 'callback'=>'callable'],
'EvCheck::start' => ['void'],
'EvCheck::stop' => ['void'],
'EvChild::__construct' => ['void', 'pid'=>'int', 'trace'=>'bool', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvChild::clear' => ['int'],
'EvChild::createStopped' => ['EvChild', 'pid'=>'int', 'trace'=>'bool', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvChild::feed' => ['void', 'events'=>'int'],
'EvChild::getLoop' => ['EvLoop'],
'EvChild::invoke' => ['void', 'events'=>'int'],
'EvChild::keepAlive' => ['void', 'value'=>'bool'],
'EvChild::set' => ['void', 'pid'=>'int', 'trace'=>'bool'],
'EvChild::setCallback' => ['void', 'callback'=>'callable'],
'EvChild::start' => ['void'],
'EvChild::stop' => ['void'],
'EvEmbed::__construct' => ['void', 'other'=>'object', 'callback='=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvEmbed::clear' => ['int'],
'EvEmbed::createStopped' => ['EvEmbed', 'other'=>'object', 'callback='=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvEmbed::feed' => ['void', 'events'=>'int'],
'EvEmbed::getLoop' => ['EvLoop'],
'EvEmbed::invoke' => ['void', 'events'=>'int'],
'EvEmbed::keepAlive' => ['void', 'value'=>'bool'],
'EvEmbed::set' => ['void', 'other'=>'object'],
'EvEmbed::setCallback' => ['void', 'callback'=>'callable'],
'EvEmbed::start' => ['void'],
'EvEmbed::stop' => ['void'],
'EvEmbed::sweep' => ['void'],
'Event::__construct' => ['void', 'base'=>'EventBase', 'fd'=>'mixed', 'what'=>'int', 'cb'=>'callable', 'arg='=>'mixed'],
'Event::add' => ['bool', 'timeout='=>'float'],
'Event::addSignal' => ['bool', 'timeout='=>'float'],
'Event::addTimer' => ['bool', 'timeout='=>'float'],
'Event::del' => ['bool'],
'Event::delSignal' => ['bool'],
'Event::delTimer' => ['bool'],
'Event::free' => ['void'],
'Event::getSupportedMethods' => ['array'],
'Event::pending' => ['bool', 'flags'=>'int'],
'Event::set' => ['bool', 'base'=>'EventBase', 'fd'=>'mixed', 'what='=>'int', 'cb='=>'callable', 'arg='=>'mixed'],
'Event::setPriority' => ['bool', 'priority'=>'int'],
'Event::setTimer' => ['bool', 'base'=>'EventBase', 'cb'=>'callable', 'arg='=>'mixed'],
'Event::signal' => ['Event', 'base'=>'EventBase', 'signum'=>'int', 'cb'=>'callable', 'arg='=>'mixed'],
'Event::timer' => ['Event', 'base'=>'EventBase', 'cb'=>'callable', 'arg='=>'mixed'],
'event_add' => ['bool', 'event'=>'resource', 'timeout='=>'int'],
'event_base_free' => ['void', 'event_base'=>'resource'],
'event_base_loop' => ['int', 'event_base'=>'resource', 'flags='=>'int'],
'event_base_loopbreak' => ['bool', 'event_base'=>'resource'],
'event_base_loopexit' => ['bool', 'event_base'=>'resource', 'timeout='=>'int'],
'event_base_new' => ['resource|false'],
'event_base_priority_init' => ['bool', 'event_base'=>'resource', 'npriorities'=>'int'],
'event_base_reinit' => ['bool', 'event_base'=>'resource'],
'event_base_set' => ['bool', 'event'=>'resource', 'event_base'=>'resource'],
'event_buffer_base_set' => ['bool', 'bevent'=>'resource', 'event_base'=>'resource'],
'event_buffer_disable' => ['bool', 'bevent'=>'resource', 'events'=>'int'],
'event_buffer_enable' => ['bool', 'bevent'=>'resource', 'events'=>'int'],
'event_buffer_fd_set' => ['void', 'bevent'=>'resource', 'fd'=>'resource'],
'event_buffer_free' => ['void', 'bevent'=>'resource'],
'event_buffer_new' => ['resource|false', 'stream'=>'resource', 'readcb'=>'callable|null', 'writecb'=>'callable|null', 'errorcb'=>'callable', 'arg='=>'mixed'],
'event_buffer_priority_set' => ['bool', 'bevent'=>'resource', 'priority'=>'int'],
'event_buffer_read' => ['string', 'bevent'=>'resource', 'data_size'=>'int'],
'event_buffer_set_callback' => ['bool', 'event'=>'resource', 'readcb'=>'mixed', 'writecb'=>'mixed', 'errorcb'=>'mixed', 'arg='=>'mixed'],
'event_buffer_timeout_set' => ['void', 'bevent'=>'resource', 'read_timeout'=>'int', 'write_timeout'=>'int'],
'event_buffer_watermark_set' => ['void', 'bevent'=>'resource', 'events'=>'int', 'lowmark'=>'int', 'highmark'=>'int'],
'event_buffer_write' => ['bool', 'bevent'=>'resource', 'data'=>'string', 'data_size='=>'int'],
'event_del' => ['bool', 'event'=>'resource'],
'event_free' => ['void', 'event'=>'resource'],
'event_new' => ['resource|false'],
'event_priority_set' => ['bool', 'event'=>'resource', 'priority'=>'int'],
'event_set' => ['bool', 'event'=>'resource', 'fd'=>'int|resource', 'events'=>'int', 'callback'=>'callable', 'arg='=>'mixed'],
'event_timer_add' => ['bool', 'event'=>'resource', 'timeout='=>'int'],
'event_timer_del' => ['bool', 'event'=>'resource'],
'event_timer_new' => ['resource|false'],
'event_timer_pending' => ['bool', 'event'=>'resource', 'timeout='=>'int'],
'event_timer_set' => ['bool', 'event'=>'resource', 'callback'=>'callable', 'arg='=>'mixed'],
'EventBase::__construct' => ['void', 'cfg='=>'EventConfig'],
'EventBase::dispatch' => ['void'],
'EventBase::exit' => ['bool', 'timeout='=>'float'],
'EventBase::free' => ['void'],
'EventBase::getFeatures' => ['int'],
'EventBase::getMethod' => ['string', 'cfg='=>'EventConfig'],
'EventBase::getTimeOfDayCached' => ['float'],
'EventBase::gotExit' => ['bool'],
'EventBase::gotStop' => ['bool'],
'EventBase::loop' => ['bool', 'flags='=>'int'],
'EventBase::priorityInit' => ['bool', 'n_priorities'=>'int'],
'EventBase::reInit' => ['bool'],
'EventBase::stop' => ['bool'],
'EventBuffer::__construct' => ['void'],
'EventBuffer::add' => ['bool', 'data'=>'string'],
'EventBuffer::addBuffer' => ['bool', 'buf'=>'EventBuffer'],
'EventBuffer::appendFrom' => ['int', 'buf'=>'EventBuffer', 'length'=>'int'],
'EventBuffer::copyout' => ['int', '&w_data'=>'string', 'max_bytes'=>'int'],
'EventBuffer::drain' => ['bool', 'length'=>'int'],
'EventBuffer::enableLocking' => ['void'],
'EventBuffer::expand' => ['bool', 'length'=>'int'],
'EventBuffer::freeze' => ['bool', 'at_front'=>'bool'],
'EventBuffer::lock' => ['void'],
'EventBuffer::prepend' => ['bool', 'data'=>'string'],
'EventBuffer::prependBuffer' => ['bool', 'buf'=>'EventBuffer'],
'EventBuffer::pullup' => ['string', 'size'=>'int'],
'EventBuffer::read' => ['string', 'max_bytes'=>'int'],
'EventBuffer::readFrom' => ['int', 'fd'=>'mixed', 'howmuch'=>'int'],
'EventBuffer::readLine' => ['string', 'eol_style'=>'int'],
'EventBuffer::search' => ['mixed', 'what'=>'string', 'start='=>'int', 'end='=>'int'],
'EventBuffer::searchEol' => ['mixed', 'start='=>'int', 'eol_style='=>'int'],
'EventBuffer::substr' => ['string', 'start'=>'int', 'length='=>'int'],
'EventBuffer::unfreeze' => ['bool', 'at_front'=>'bool'],
'EventBuffer::unlock' => ['bool'],
'EventBuffer::write' => ['int', 'fd'=>'mixed', 'howmuch='=>'int'],
'EventBufferEvent::__construct' => ['void', 'base'=>'EventBase', 'socket='=>'mixed', 'options='=>'int', 'readcb='=>'callable', 'writecb='=>'callable', 'eventcb='=>'callable'],
'EventBufferEvent::close' => ['void'],
'EventBufferEvent::connect' => ['bool', 'addr'=>'string'],
'EventBufferEvent::connectHost' => ['bool', 'dns_base'=>'EventDnsBase', 'hostname'=>'string', 'port'=>'int', 'family='=>'int'],
'EventBufferEvent::createPair' => ['array', 'base'=>'EventBase', 'options='=>'int'],
'EventBufferEvent::disable' => ['bool', 'events'=>'int'],
'EventBufferEvent::enable' => ['bool', 'events'=>'int'],
'EventBufferEvent::free' => ['void'],
'EventBufferEvent::getDnsErrorString' => ['string'],
'EventBufferEvent::getEnabled' => ['int'],
'EventBufferEvent::getInput' => ['EventBuffer'],
'EventBufferEvent::getOutput' => ['EventBuffer'],
'EventBufferEvent::read' => ['string', 'size'=>'int'],
'EventBufferEvent::readBuffer' => ['bool', 'buf'=>'EventBuffer'],
'EventBufferEvent::setCallbacks' => ['void', 'readcb'=>'callable', 'writecb'=>'callable', 'eventcb'=>'callable', 'arg='=>'string'],
'EventBufferEvent::setPriority' => ['bool', 'priority'=>'int'],
'EventBufferEvent::setTimeouts' => ['bool', 'timeout_read'=>'float', 'timeout_write'=>'float'],
'EventBufferEvent::setWatermark' => ['void', 'events'=>'int', 'lowmark'=>'int', 'highmark'=>'int'],
'EventBufferEvent::sslError' => ['string'],
'EventBufferEvent::sslFilter' => ['EventBufferEvent', 'base'=>'EventBase', 'underlying'=>'EventBufferEvent', 'ctx'=>'EventSslContext', 'state'=>'int', 'options='=>'int'],
'EventBufferEvent::sslGetCipherInfo' => ['string'],
'EventBufferEvent::sslGetCipherName' => ['string'],
'EventBufferEvent::sslGetCipherVersion' => ['string'],
'EventBufferEvent::sslGetProtocol' => ['string'],
'EventBufferEvent::sslRenegotiate' => ['void'],
'EventBufferEvent::sslSocket' => ['EventBufferEvent', 'base'=>'EventBase', 'socket'=>'mixed', 'ctx'=>'EventSslContext', 'state'=>'int', 'options='=>'int'],
'EventBufferEvent::write' => ['bool', 'data'=>'string'],
'EventBufferEvent::writeBuffer' => ['bool', 'buf'=>'EventBuffer'],
'EventConfig::__construct' => ['void'],
'EventConfig::avoidMethod' => ['bool', 'method'=>'string'],
'EventConfig::requireFeatures' => ['bool', 'feature'=>'int'],
'EventConfig::setMaxDispatchInterval' => ['void', 'max_interval'=>'int', 'max_callbacks'=>'int', 'min_priority'=>'int'],
'EventDnsBase::__construct' => ['void', 'base'=>'EventBase', 'initialize'=>'bool'],
'EventDnsBase::addNameserverIp' => ['bool', 'ip'=>'string'],
'EventDnsBase::addSearch' => ['void', 'domain'=>'string'],
'EventDnsBase::clearSearch' => ['void'],
'EventDnsBase::countNameservers' => ['int'],
'EventDnsBase::loadHosts' => ['bool', 'hosts'=>'string'],
'EventDnsBase::parseResolvConf' => ['bool', 'flags'=>'int', 'filename'=>'string'],
'EventDnsBase::setOption' => ['bool', 'option'=>'string', 'value'=>'string'],
'EventDnsBase::setSearchNdots' => ['bool', 'ndots'=>'int'],
'EventHttp::__construct' => ['void', 'base'=>'EventBase', 'ctx='=>'EventSslContext'],
'EventHttp::accept' => ['bool', 'socket'=>'mixed'],
'EventHttp::addServerAlias' => ['bool', 'alias'=>'string'],
'EventHttp::bind' => ['void', 'address'=>'string', 'port'=>'int'],
'EventHttp::removeServerAlias' => ['bool', 'alias'=>'string'],
'EventHttp::setAllowedMethods' => ['void', 'methods'=>'int'],
'EventHttp::setCallback' => ['void', 'path'=>'string', 'cb'=>'string', 'arg='=>'string'],
'EventHttp::setDefaultCallback' => ['void', 'cb'=>'string', 'arg='=>'string'],
'EventHttp::setMaxBodySize' => ['void', 'value'=>'int'],
'EventHttp::setMaxHeadersSize' => ['void', 'value'=>'int'],
'EventHttp::setTimeout' => ['void', 'value'=>'int'],
'EventHttpConnection::__construct' => ['void', 'base'=>'EventBase', 'dns_base'=>'EventDnsBase', 'address'=>'string', 'port'=>'int', 'ctx='=>'EventSslContext'],
'EventHttpConnection::getBase' => ['EventBase'],
'EventHttpConnection::getPeer' => ['void', '&w_address'=>'string', '&w_port'=>'int'],
'EventHttpConnection::makeRequest' => ['bool', 'req'=>'EventHttpRequest', 'type'=>'int', 'uri'=>'string'],
'EventHttpConnection::setCloseCallback' => ['void', 'callback'=>'callable', 'data='=>'mixed'],
'EventHttpConnection::setLocalAddress' => ['void', 'address'=>'string'],
'EventHttpConnection::setLocalPort' => ['void', 'port'=>'int'],
'EventHttpConnection::setMaxBodySize' => ['void', 'max_size'=>'string'],
'EventHttpConnection::setMaxHeadersSize' => ['void', 'max_size'=>'string'],
'EventHttpConnection::setRetries' => ['void', 'retries'=>'int'],
'EventHttpConnection::setTimeout' => ['void', 'timeout'=>'int'],
'EventHttpRequest::__construct' => ['void', 'callback'=>'callable', 'data='=>'mixed'],
'EventHttpRequest::addHeader' => ['bool', 'key'=>'string', 'value'=>'string', 'type'=>'int'],
'EventHttpRequest::cancel' => ['void'],
'EventHttpRequest::clearHeaders' => ['void'],
'EventHttpRequest::closeConnection' => ['void'],
'EventHttpRequest::findHeader' => ['void', 'key'=>'string', 'type'=>'string'],
'EventHttpRequest::free' => ['void'],
'EventHttpRequest::getBufferEvent' => ['EventBufferEvent'],
'EventHttpRequest::getCommand' => ['void'],
'EventHttpRequest::getConnection' => ['EventHttpConnection'],
'EventHttpRequest::getHost' => ['string'],
'EventHttpRequest::getInputBuffer' => ['EventBuffer'],
'EventHttpRequest::getInputHeaders' => ['array'],
'EventHttpRequest::getOutputBuffer' => ['EventBuffer'],
'EventHttpRequest::getOutputHeaders' => ['void'],
'EventHttpRequest::getResponseCode' => ['int'],
'EventHttpRequest::getUri' => ['string'],
'EventHttpRequest::removeHeader' => ['void', 'key'=>'string', 'type'=>'string'],
'EventHttpRequest::sendError' => ['void', 'error'=>'int', 'reason='=>'string'],
'EventHttpRequest::sendReply' => ['void', 'code'=>'int', 'reason'=>'string', 'buf='=>'EventBuffer'],
'EventHttpRequest::sendReplyChunk' => ['void', 'buf'=>'EventBuffer'],
'EventHttpRequest::sendReplyEnd' => ['void'],
'EventHttpRequest::sendReplyStart' => ['void', 'code'=>'int', 'reason'=>'string'],
'EventListener::__construct' => ['void', 'base'=>'EventBase', 'cb'=>'callable', 'data'=>'mixed', 'flags'=>'int', 'backlog'=>'int', 'target'=>'mixed'],
'EventListener::disable' => ['bool'],
'EventListener::enable' => ['bool'],
'EventListener::getBase' => ['void'],
'EventListener::getSocketName' => ['bool', '&w_address'=>'string', '&w_port='=>'mixed'],
'EventListener::setCallback' => ['void', 'cb'=>'callable', 'arg='=>'mixed'],
'EventListener::setErrorCallback' => ['void', 'cb'=>'string'],
'EventSslContext::__construct' => ['void', 'method'=>'string', 'options'=>'string'],
'EventUtil::__construct' => ['void'],
'EventUtil::getLastSocketErrno' => ['int', 'socket='=>'mixed'],
'EventUtil::getLastSocketError' => ['string', 'socket='=>'mixed'],
'EventUtil::getSocketFd' => ['int', 'socket'=>'mixed'],
'EventUtil::getSocketName' => ['bool', 'socket'=>'mixed', '&w_address'=>'string', '&w_port='=>'mixed'],
'EventUtil::setSocketOption' => ['bool', 'socket'=>'mixed', 'level'=>'int', 'optname'=>'int', 'optval'=>'mixed'],
'EventUtil::sslRandPoll' => ['void'],
'EvFork::__construct' => ['void', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvFork::clear' => ['int'],
'EvFork::createStopped' => ['EvFork', 'callback'=>'callable', 'data='=>'string', 'priority='=>'string'],
'EvFork::feed' => ['void', 'events'=>'int'],
'EvFork::getLoop' => ['EvLoop'],
'EvFork::invoke' => ['void', 'events'=>'int'],
'EvFork::keepAlive' => ['void', 'value'=>'bool'],
'EvFork::setCallback' => ['void', 'callback'=>'callable'],
'EvFork::start' => ['void'],
'EvFork::stop' => ['void'],
'EvIdle::__construct' => ['void', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvIdle::clear' => ['int'],
'EvIdle::createStopped' => ['EvIdle', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvIdle::feed' => ['void', 'events'=>'int'],
'EvIdle::getLoop' => ['EvLoop'],
'EvIdle::invoke' => ['void', 'events'=>'int'],
'EvIdle::keepAlive' => ['void', 'value'=>'bool'],
'EvIdle::setCallback' => ['void', 'callback'=>'callable'],
'EvIdle::start' => ['void'],
'EvIdle::stop' => ['void'],
'EvIo::__construct' => ['void', 'fd'=>'mixed', 'events'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvIo::clear' => ['int'],
'EvIo::createStopped' => ['EvIo', 'fd'=>'resource', 'events'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvIo::feed' => ['void', 'events'=>'int'],
'EvIo::getLoop' => ['EvLoop'],
'EvIo::invoke' => ['void', 'events'=>'int'],
'EvIo::keepAlive' => ['void', 'value'=>'bool'],
'EvIo::set' => ['void', 'fd'=>'resource', 'events'=>'int'],
'EvIo::setCallback' => ['void', 'callback'=>'callable'],
'EvIo::start' => ['void'],
'EvIo::stop' => ['void'],
'EvLoop::__construct' => ['void', 'flags='=>'int', 'data='=>'mixed', 'io_interval='=>'float', 'timeout_interval='=>'float'],
'EvLoop::backend' => ['int'],
'EvLoop::check' => ['EvCheck', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::child' => ['EvChild', 'pid'=>'int', 'trace'=>'bool', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::defaultLoop' => ['EvLoop', 'flags='=>'int', 'data='=>'mixed', 'io_interval='=>'float', 'timeout_interval='=>'float'],
'EvLoop::embed' => ['EvEmbed', 'other'=>'EvLoop', 'callback='=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::fork' => ['EvFork', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::idle' => ['EvIdle', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::invokePending' => ['void'],
'EvLoop::io' => ['EvIo', 'fd'=>'resource', 'events'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::loopFork' => ['void'],
'EvLoop::now' => ['float'],
'EvLoop::nowUpdate' => ['void'],
'EvLoop::periodic' => ['EvPeriodic', 'offset'=>'float', 'interval'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::prepare' => ['EvPrepare', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::resume' => ['void'],
'EvLoop::run' => ['void', 'flags='=>'int'],
'EvLoop::signal' => ['EvSignal', 'signum'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::stat' => ['EvStat', 'path'=>'string', 'interval'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::stop' => ['void', 'how='=>'int'],
'EvLoop::suspend' => ['void'],
'EvLoop::timer' => ['EvTimer', 'after'=>'float', 'repeat'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::verify' => ['void'],
'EvPeriodic::__construct' => ['void', 'offset'=>'float', 'interval'=>'string', 'reschedule_cb'=>'callable', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvPeriodic::again' => ['void'],
'EvPeriodic::at' => ['float'],
'EvPeriodic::clear' => ['int'],
'EvPeriodic::createStopped' => ['EvPeriodic', 'offset'=>'float', 'interval'=>'float', 'reschedule_cb'=>'callable', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvPeriodic::feed' => ['void', 'events'=>'int'],
'EvPeriodic::getLoop' => ['EvLoop'],
'EvPeriodic::invoke' => ['void', 'events'=>'int'],
'EvPeriodic::keepAlive' => ['void', 'value'=>'bool'],
'EvPeriodic::set' => ['void', 'offset'=>'float', 'interval'=>'float'],
'EvPeriodic::setCallback' => ['void', 'callback'=>'callable'],
'EvPeriodic::start' => ['void'],
'EvPeriodic::stop' => ['void'],
'EvPrepare::__construct' => ['void', 'callback'=>'string', 'data='=>'string', 'priority='=>'string'],
'EvPrepare::clear' => ['int'],
'EvPrepare::createStopped' => ['EvPrepare', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvPrepare::feed' => ['void', 'events'=>'int'],
'EvPrepare::getLoop' => ['EvLoop'],
'EvPrepare::invoke' => ['void', 'events'=>'int'],
'EvPrepare::keepAlive' => ['void', 'value'=>'bool'],
'EvPrepare::setCallback' => ['void', 'callback'=>'callable'],
'EvPrepare::start' => ['void'],
'EvPrepare::stop' => ['void'],
'EvSignal::__construct' => ['void', 'signum'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvSignal::clear' => ['int'],
'EvSignal::createStopped' => ['EvSignal', 'signum'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvSignal::feed' => ['void', 'events'=>'int'],
'EvSignal::getLoop' => ['EvLoop'],
'EvSignal::invoke' => ['void', 'events'=>'int'],
'EvSignal::keepAlive' => ['void', 'value'=>'bool'],
'EvSignal::set' => ['void', 'signum'=>'int'],
'EvSignal::setCallback' => ['void', 'callback'=>'callable'],
'EvSignal::start' => ['void'],
'EvSignal::stop' => ['void'],
'EvStat::__construct' => ['void', 'path'=>'string', 'interval'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvStat::attr' => ['array'],
'EvStat::clear' => ['int'],
'EvStat::createStopped' => ['EvStat', 'path'=>'string', 'interval'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvStat::feed' => ['void', 'events'=>'int'],
'EvStat::getLoop' => ['EvLoop'],
'EvStat::invoke' => ['void', 'events'=>'int'],
'EvStat::keepAlive' => ['void', 'value'=>'bool'],
'EvStat::prev' => ['array'],
'EvStat::set' => ['void', 'path'=>'string', 'interval'=>'float'],
'EvStat::setCallback' => ['void', 'callback'=>'callable'],
'EvStat::start' => ['void'],
'EvStat::stat' => ['bool'],
'EvStat::stop' => ['void'],
'EvTimer::__construct' => ['void', 'after'=>'float', 'repeat'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvTimer::again' => ['void'],
'EvTimer::clear' => ['int'],
'EvTimer::createStopped' => ['EvTimer', 'after'=>'float', 'repeat'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvTimer::feed' => ['void', 'events'=>'int'],
'EvTimer::getLoop' => ['EvLoop'],
'EvTimer::invoke' => ['void', 'events'=>'int'],
'EvTimer::keepAlive' => ['void', 'value'=>'bool'],
'EvTimer::set' => ['void', 'after'=>'float', 'repeat'=>'float'],
'EvTimer::setCallback' => ['void', 'callback'=>'callable'],
'EvTimer::start' => ['void'],
'EvTimer::stop' => ['void'],
'EvWatcher::__construct' => ['void'],
'EvWatcher::clear' => ['int'],
'EvWatcher::feed' => ['void', 'revents'=>'int'],
'EvWatcher::getLoop' => ['EvLoop'],
'EvWatcher::invoke' => ['void', 'revents'=>'int'],
'EvWatcher::keepalive' => ['bool', 'value='=>'bool'],
'EvWatcher::setCallback' => ['void', 'callback'=>'callable'],
'EvWatcher::start' => ['void'],
'EvWatcher::stop' => ['void'],
'Exception::__clone' => ['void'],
'Exception::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?Exception'],
'Exception::__toString' => ['string'],
'Exception::getCode' => ['int|string'],
'Exception::getFile' => ['string'],
'Exception::getLine' => ['int'],
'Exception::getMessage' => ['string'],
'Exception::getPrevious' => ['?Throwable|?Exception'],
'Exception::getTrace' => ['list<array<string,mixed>>'],
'Exception::getTraceAsString' => ['string'],
'exec' => ['string|false', 'command'=>'string', '&w_output='=>'array', '&w_result_code='=>'int'],
'exif_imagetype' => ['int|false', 'filename'=>'string'],
'exif_read_data' => ['array|false', 'file'=>'string|resource', 'required_sections='=>'string', 'as_arrays='=>'bool', 'read_thumbnail='=>'bool'],
'exif_tagname' => ['string|false', 'index'=>'int'],
'exif_thumbnail' => ['string|false', 'file'=>'string', '&w_width='=>'int', '&w_height='=>'int', '&w_image_type='=>'int'],
'exit' => ['', 'status'=>'string|int'],
'exp' => ['float', 'num'=>'float'],
'expect_expectl' => ['int', 'expect'=>'resource', 'cases'=>'array', 'match='=>'array'],
'expect_popen' => ['resource|false', 'command'=>'string'],
'explode' => ['list<string>', 'separator'=>'string', 'string'=>'string', 'limit='=>'int'],
'expm1' => ['float', 'num'=>'float'],
'extension_loaded' => ['bool', 'extension'=>'string'],
'extract' => ['int', '&rw_array'=>'array', 'flags='=>'int', 'prefix='=>'?string'],
'ezmlm_hash' => ['int', 'addr'=>'string'],
'fam_cancel_monitor' => ['bool', 'fam'=>'resource', 'fam_monitor'=>'resource'],
'fam_close' => ['void', 'fam'=>'resource'],
'fam_monitor_collection' => ['resource', 'fam'=>'resource', 'dirname'=>'string', 'depth'=>'int', 'mask'=>'string'],
'fam_monitor_directory' => ['resource', 'fam'=>'resource', 'dirname'=>'string'],
'fam_monitor_file' => ['resource', 'fam'=>'resource', 'filename'=>'string'],
'fam_next_event' => ['array', 'fam'=>'resource'],
'fam_open' => ['resource|false', 'appname='=>'string'],
'fam_pending' => ['int', 'fam'=>'resource'],
'fam_resume_monitor' => ['bool', 'fam'=>'resource', 'fam_monitor'=>'resource'],
'fam_suspend_monitor' => ['bool', 'fam'=>'resource', 'fam_monitor'=>'resource'],
'fann_cascadetrain_on_data' => ['bool', 'ann'=>'resource', 'data'=>'resource', 'max_neurons'=>'int', 'neurons_between_reports'=>'int', 'desired_error'=>'float'],
'fann_cascadetrain_on_file' => ['bool', 'ann'=>'resource', 'filename'=>'string', 'max_neurons'=>'int', 'neurons_between_reports'=>'int', 'desired_error'=>'float'],
'fann_clear_scaling_params' => ['bool', 'ann'=>'resource'],
'fann_copy' => ['resource|false', 'ann'=>'resource'],
'fann_create_from_file' => ['resource', 'configuration_file'=>'string'],
'fann_create_shortcut' => ['resource|false', 'num_layers'=>'int', 'num_neurons1'=>'int', 'num_neurons2'=>'int', '...args='=>'int'],
'fann_create_shortcut_array' => ['resource|false', 'num_layers'=>'int', 'layers'=>'array'],
'fann_create_sparse' => ['resource|false', 'connection_rate'=>'float', 'num_layers'=>'int', 'num_neurons1'=>'int', 'num_neurons2'=>'int', '...args='=>'int'],
'fann_create_sparse_array' => ['resource|false', 'connection_rate'=>'float', 'num_layers'=>'int', 'layers'=>'array'],
'fann_create_standard' => ['resource|false', 'num_layers'=>'int', 'num_neurons1'=>'int', 'num_neurons2'=>'int', '...args='=>'int'],
'fann_create_standard_array' => ['resource|false', 'num_layers'=>'int', 'layers'=>'array'],
'fann_create_train' => ['resource', 'num_data'=>'int', 'num_input'=>'int', 'num_output'=>'int'],
'fann_create_train_from_callback' => ['resource', 'num_data'=>'int', 'num_input'=>'int', 'num_output'=>'int', 'user_function'=>'callable'],
'fann_descale_input' => ['bool', 'ann'=>'resource', 'input_vector'=>'array'],
'fann_descale_output' => ['bool', 'ann'=>'resource', 'output_vector'=>'array'],
'fann_descale_train' => ['bool', 'ann'=>'resource', 'train_data'=>'resource'],
'fann_destroy' => ['bool', 'ann'=>'resource'],
'fann_destroy_train' => ['bool', 'train_data'=>'resource'],
'fann_duplicate_train_data' => ['resource', 'data'=>'resource'],
'fann_get_activation_function' => ['int|false', 'ann'=>'resource', 'layer'=>'int', 'neuron'=>'int'],
'fann_get_activation_steepness' => ['float|false', 'ann'=>'resource', 'layer'=>'int', 'neuron'=>'int'],
'fann_get_bias_array' => ['array', 'ann'=>'resource'],
'fann_get_bit_fail' => ['int|false', 'ann'=>'resource'],
'fann_get_bit_fail_limit' => ['float|false', 'ann'=>'resource'],
'fann_get_cascade_activation_functions' => ['array|false', 'ann'=>'resource'],
'fann_get_cascade_activation_functions_count' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_activation_steepnesses' => ['array|false', 'ann'=>'resource'],
'fann_get_cascade_activation_steepnesses_count' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_candidate_change_fraction' => ['float|false', 'ann'=>'resource'],
'fann_get_cascade_candidate_limit' => ['float|false', 'ann'=>'resource'],
'fann_get_cascade_candidate_stagnation_epochs' => ['float|false', 'ann'=>'resource'],
'fann_get_cascade_max_cand_epochs' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_max_out_epochs' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_min_cand_epochs' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_min_out_epochs' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_num_candidate_groups' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_num_candidates' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_output_change_fraction' => ['float|false', 'ann'=>'resource'],
'fann_get_cascade_output_stagnation_epochs' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_weight_multiplier' => ['float|false', 'ann'=>'resource'],
'fann_get_connection_array' => ['array', 'ann'=>'resource'],
'fann_get_connection_rate' => ['float|false', 'ann'=>'resource'],
'fann_get_errno' => ['int|false', 'errdat'=>'resource'],
'fann_get_errstr' => ['string|false', 'errdat'=>'resource'],
'fann_get_layer_array' => ['array', 'ann'=>'resource'],
'fann_get_learning_momentum' => ['float|false', 'ann'=>'resource'],
'fann_get_learning_rate' => ['float|false', 'ann'=>'resource'],
'fann_get_MSE' => ['float|false', 'ann'=>'resource'],
'fann_get_network_type' => ['int|false', 'ann'=>'resource'],
'fann_get_num_input' => ['int|false', 'ann'=>'resource'],
'fann_get_num_layers' => ['int|false', 'ann'=>'resource'],
'fann_get_num_output' => ['int|false', 'ann'=>'resource'],
'fann_get_quickprop_decay' => ['float|false', 'ann'=>'resource'],
'fann_get_quickprop_mu' => ['float|false', 'ann'=>'resource'],
'fann_get_rprop_decrease_factor' => ['float|false', 'ann'=>'resource'],
'fann_get_rprop_delta_max' => ['float|false', 'ann'=>'resource'],
'fann_get_rprop_delta_min' => ['float|false', 'ann'=>'resource'],
'fann_get_rprop_delta_zero' => ['float|false', 'ann'=>'resource'],
'fann_get_rprop_increase_factor' => ['float|false', 'ann'=>'resource'],
'fann_get_sarprop_step_error_shift' => ['float|false', 'ann'=>'resource'],
'fann_get_sarprop_step_error_threshold_factor' => ['float|false', 'ann'=>'resource'],
'fann_get_sarprop_temperature' => ['float|false', 'ann'=>'resource'],
'fann_get_sarprop_weight_decay_shift' => ['float|false', 'ann'=>'resource'],
'fann_get_total_connections' => ['int|false', 'ann'=>'resource'],
'fann_get_total_neurons' => ['int|false', 'ann'=>'resource'],
'fann_get_train_error_function' => ['int|false', 'ann'=>'resource'],
'fann_get_train_stop_function' => ['int|false', 'ann'=>'resource'],
'fann_get_training_algorithm' => ['int|false', 'ann'=>'resource'],
'fann_init_weights' => ['bool', 'ann'=>'resource', 'train_data'=>'resource'],
'fann_length_train_data' => ['int|false', 'data'=>'resource'],
'fann_merge_train_data' => ['resource|false', 'data1'=>'resource', 'data2'=>'resource'],
'fann_num_input_train_data' => ['int|false', 'data'=>'resource'],
'fann_num_output_train_data' => ['int|false', 'data'=>'resource'],
'fann_print_error' => ['void', 'errdat'=>'string'],
'fann_randomize_weights' => ['bool', 'ann'=>'resource', 'min_weight'=>'float', 'max_weight'=>'float'],
'fann_read_train_from_file' => ['resource', 'filename'=>'string'],
'fann_reset_errno' => ['void', 'errdat'=>'resource'],
'fann_reset_errstr' => ['void', 'errdat'=>'resource'],
'fann_reset_MSE' => ['bool', 'ann'=>'string'],
'fann_run' => ['array|false', 'ann'=>'resource', 'input'=>'array'],
'fann_save' => ['bool', 'ann'=>'resource', 'configuration_file'=>'string'],
'fann_save_train' => ['bool', 'data'=>'resource', 'file_name'=>'string'],
'fann_scale_input' => ['bool', 'ann'=>'resource', 'input_vector'=>'array'],
'fann_scale_input_train_data' => ['bool', 'train_data'=>'resource', 'new_min'=>'float', 'new_max'=>'float'],
'fann_scale_output' => ['bool', 'ann'=>'resource', 'output_vector'=>'array'],
'fann_scale_output_train_data' => ['bool', 'train_data'=>'resource', 'new_min'=>'float', 'new_max'=>'float'],
'fann_scale_train' => ['bool', 'ann'=>'resource', 'train_data'=>'resource'],
'fann_scale_train_data' => ['bool', 'train_data'=>'resource', 'new_min'=>'float', 'new_max'=>'float'],
'fann_set_activation_function' => ['bool', 'ann'=>'resource', 'activation_function'=>'int', 'layer'=>'int', 'neuron'=>'int'],
'fann_set_activation_function_hidden' => ['bool', 'ann'=>'resource', 'activation_function'=>'int'],
'fann_set_activation_function_layer' => ['bool', 'ann'=>'resource', 'activation_function'=>'int', 'layer'=>'int'],
'fann_set_activation_function_output' => ['bool', 'ann'=>'resource', 'activation_function'=>'int'],
'fann_set_activation_steepness' => ['bool', 'ann'=>'resource', 'activation_steepness'=>'float', 'layer'=>'int', 'neuron'=>'int'],
'fann_set_activation_steepness_hidden' => ['bool', 'ann'=>'resource', 'activation_steepness'=>'float'],
'fann_set_activation_steepness_layer' => ['bool', 'ann'=>'resource', 'activation_steepness'=>'float', 'layer'=>'int'],
'fann_set_activation_steepness_output' => ['bool', 'ann'=>'resource', 'activation_steepness'=>'float'],
'fann_set_bit_fail_limit' => ['bool', 'ann'=>'resource', 'bit_fail_limit'=>'float'],
'fann_set_callback' => ['bool', 'ann'=>'resource', 'callback'=>'callable'],
'fann_set_cascade_activation_functions' => ['bool', 'ann'=>'resource', 'cascade_activation_functions'=>'array'],
'fann_set_cascade_activation_steepnesses' => ['bool', 'ann'=>'resource', 'cascade_activation_steepnesses_count'=>'array'],
'fann_set_cascade_candidate_change_fraction' => ['bool', 'ann'=>'resource', 'cascade_candidate_change_fraction'=>'float'],
'fann_set_cascade_candidate_limit' => ['bool', 'ann'=>'resource', 'cascade_candidate_limit'=>'float'],
'fann_set_cascade_candidate_stagnation_epochs' => ['bool', 'ann'=>'resource', 'cascade_candidate_stagnation_epochs'=>'int'],
'fann_set_cascade_max_cand_epochs' => ['bool', 'ann'=>'resource', 'cascade_max_cand_epochs'=>'int'],
'fann_set_cascade_max_out_epochs' => ['bool', 'ann'=>'resource', 'cascade_max_out_epochs'=>'int'],
'fann_set_cascade_min_cand_epochs' => ['bool', 'ann'=>'resource', 'cascade_min_cand_epochs'=>'int'],
'fann_set_cascade_min_out_epochs' => ['bool', 'ann'=>'resource', 'cascade_min_out_epochs'=>'int'],
'fann_set_cascade_num_candidate_groups' => ['bool', 'ann'=>'resource', 'cascade_num_candidate_groups'=>'int'],
'fann_set_cascade_output_change_fraction' => ['bool', 'ann'=>'resource', 'cascade_output_change_fraction'=>'float'],
'fann_set_cascade_output_stagnation_epochs' => ['bool', 'ann'=>'resource', 'cascade_output_stagnation_epochs'=>'int'],
'fann_set_cascade_weight_multiplier' => ['bool', 'ann'=>'resource', 'cascade_weight_multiplier'=>'float'],
'fann_set_error_log' => ['void', 'errdat'=>'resource', 'log_file'=>'string'],
'fann_set_input_scaling_params' => ['bool', 'ann'=>'resource', 'train_data'=>'resource', 'new_input_min'=>'float', 'new_input_max'=>'float'],
'fann_set_learning_momentum' => ['bool', 'ann'=>'resource', 'learning_momentum'=>'float'],
'fann_set_learning_rate' => ['bool', 'ann'=>'resource', 'learning_rate'=>'float'],
'fann_set_output_scaling_params' => ['bool', 'ann'=>'resource', 'train_data'=>'resource', 'new_output_min'=>'float', 'new_output_max'=>'float'],
'fann_set_quickprop_decay' => ['bool', 'ann'=>'resource', 'quickprop_decay'=>'float'],
'fann_set_quickprop_mu' => ['bool', 'ann'=>'resource', 'quickprop_mu'=>'float'],
'fann_set_rprop_decrease_factor' => ['bool', 'ann'=>'resource', 'rprop_decrease_factor'=>'float'],
'fann_set_rprop_delta_max' => ['bool', 'ann'=>'resource', 'rprop_delta_max'=>'float'],
'fann_set_rprop_delta_min' => ['bool', 'ann'=>'resource', 'rprop_delta_min'=>'float'],
'fann_set_rprop_delta_zero' => ['bool', 'ann'=>'resource', 'rprop_delta_zero'=>'float'],
'fann_set_rprop_increase_factor' => ['bool', 'ann'=>'resource', 'rprop_increase_factor'=>'float'],
'fann_set_sarprop_step_error_shift' => ['bool', 'ann'=>'resource', 'sarprop_step_error_shift'=>'float'],
'fann_set_sarprop_step_error_threshold_factor' => ['bool', 'ann'=>'resource', 'sarprop_step_error_threshold_factor'=>'float'],
'fann_set_sarprop_temperature' => ['bool', 'ann'=>'resource', 'sarprop_temperature'=>'float'],
'fann_set_sarprop_weight_decay_shift' => ['bool', 'ann'=>'resource', 'sarprop_weight_decay_shift'=>'float'],
'fann_set_scaling_params' => ['bool', 'ann'=>'resource', 'train_data'=>'resource', 'new_input_min'=>'float', 'new_input_max'=>'float', 'new_output_min'=>'float', 'new_output_max'=>'float'],
'fann_set_train_error_function' => ['bool', 'ann'=>'resource', 'error_function'=>'int'],
'fann_set_train_stop_function' => ['bool', 'ann'=>'resource', 'stop_function'=>'int'],
'fann_set_training_algorithm' => ['bool', 'ann'=>'resource', 'training_algorithm'=>'int'],
'fann_set_weight' => ['bool', 'ann'=>'resource', 'from_neuron'=>'int', 'to_neuron'=>'int', 'weight'=>'float'],
'fann_set_weight_array' => ['bool', 'ann'=>'resource', 'connections'=>'array'],
'fann_shuffle_train_data' => ['bool', 'train_data'=>'resource'],
'fann_subset_train_data' => ['resource', 'data'=>'resource', 'pos'=>'int', 'length'=>'int'],
'fann_test' => ['bool', 'ann'=>'resource', 'input'=>'array', 'desired_output'=>'array'],
'fann_test_data' => ['float|false', 'ann'=>'resource', 'data'=>'resource'],
'fann_train' => ['bool', 'ann'=>'resource', 'input'=>'array', 'desired_output'=>'array'],
'fann_train_epoch' => ['float|false', 'ann'=>'resource', 'data'=>'resource'],
'fann_train_on_data' => ['bool', 'ann'=>'resource', 'data'=>'resource', 'max_epochs'=>'int', 'epochs_between_reports'=>'int', 'desired_error'=>'float'],
'fann_train_on_file' => ['bool', 'ann'=>'resource', 'filename'=>'string', 'max_epochs'=>'int', 'epochs_between_reports'=>'int', 'desired_error'=>'float'],
'FANNConnection::__construct' => ['void', 'from_neuron'=>'int', 'to_neuron'=>'int', 'weight'=>'float'],
'FANNConnection::getFromNeuron' => ['int'],
'FANNConnection::getToNeuron' => ['int'],
'FANNConnection::getWeight' => ['void'],
'FANNConnection::setWeight' => ['bool', 'weight'=>'float'],
'fastcgi_finish_request' => ['bool'],
'fbsql_affected_rows' => ['int', 'link_identifier='=>'?resource'],
'fbsql_autocommit' => ['bool', 'link_identifier'=>'resource', 'onoff='=>'bool'],
'fbsql_blob_size' => ['int', 'blob_handle'=>'string', 'link_identifier='=>'?resource'],
'fbsql_change_user' => ['bool', 'user'=>'string', 'password'=>'string', 'database='=>'string', 'link_identifier='=>'?resource'],
'fbsql_clob_size' => ['int', 'clob_handle'=>'string', 'link_identifier='=>'?resource'],
'fbsql_close' => ['bool', 'link_identifier='=>'?resource'],
'fbsql_commit' => ['bool', 'link_identifier='=>'?resource'],
'fbsql_connect' => ['resource', 'hostname='=>'string', 'username='=>'string', 'password='=>'string'],
'fbsql_create_blob' => ['string', 'blob_data'=>'string', 'link_identifier='=>'?resource'],
'fbsql_create_clob' => ['string', 'clob_data'=>'string', 'link_identifier='=>'?resource'],
'fbsql_create_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource', 'database_options='=>'string'],
'fbsql_data_seek' => ['bool', 'result'=>'resource', 'row_number'=>'int'],
'fbsql_database' => ['string', 'link_identifier'=>'resource', 'database='=>'string'],
'fbsql_database_password' => ['string', 'link_identifier'=>'resource', 'database_password='=>'string'],
'fbsql_db_query' => ['resource', 'database'=>'string', 'query'=>'string', 'link_identifier='=>'?resource'],
'fbsql_db_status' => ['int', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'fbsql_drop_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'fbsql_errno' => ['int', 'link_identifier='=>'?resource'],
'fbsql_error' => ['string', 'link_identifier='=>'?resource'],
'fbsql_fetch_array' => ['array', 'result'=>'resource', 'result_type='=>'int'],
'fbsql_fetch_assoc' => ['array', 'result'=>'resource'],
'fbsql_fetch_field' => ['object', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_fetch_lengths' => ['array', 'result'=>'resource'],
'fbsql_fetch_object' => ['object', 'result'=>'resource'],
'fbsql_fetch_row' => ['array', 'result'=>'resource'],
'fbsql_field_flags' => ['string', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_field_len' => ['int', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_field_name' => ['string', 'result'=>'resource', 'field_index='=>'int'],
'fbsql_field_seek' => ['bool', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_field_table' => ['string', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_field_type' => ['string', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_free_result' => ['bool', 'result'=>'resource'],
'fbsql_get_autostart_info' => ['array', 'link_identifier='=>'?resource'],
'fbsql_hostname' => ['string', 'link_identifier'=>'resource', 'host_name='=>'string'],
'fbsql_insert_id' => ['int', 'link_identifier='=>'?resource'],
'fbsql_list_dbs' => ['resource', 'link_identifier='=>'?resource'],
'fbsql_list_fields' => ['resource', 'database_name'=>'string', 'table_name'=>'string', 'link_identifier='=>'?resource'],
'fbsql_list_tables' => ['resource', 'database'=>'string', 'link_identifier='=>'?resource'],
'fbsql_next_result' => ['bool', 'result'=>'resource'],
'fbsql_num_fields' => ['int', 'result'=>'resource'],
'fbsql_num_rows' => ['int', 'result'=>'resource'],
'fbsql_password' => ['string', 'link_identifier'=>'resource', 'password='=>'string'],
'fbsql_pconnect' => ['resource', 'hostname='=>'string', 'username='=>'string', 'password='=>'string'],
'fbsql_query' => ['resource', 'query'=>'string', 'link_identifier='=>'?resource', 'batch_size='=>'int'],
'fbsql_read_blob' => ['string', 'blob_handle'=>'string', 'link_identifier='=>'?resource'],
'fbsql_read_clob' => ['string', 'clob_handle'=>'string', 'link_identifier='=>'?resource'],
'fbsql_result' => ['mixed', 'result'=>'resource', 'row='=>'int', 'field='=>'mixed'],
'fbsql_rollback' => ['bool', 'link_identifier='=>'?resource'],
'fbsql_rows_fetched' => ['int', 'result'=>'resource'],
'fbsql_select_db' => ['bool', 'database_name='=>'string', 'link_identifier='=>'?resource'],
'fbsql_set_characterset' => ['void', 'link_identifier'=>'resource', 'characterset'=>'int', 'in_out_both='=>'int'],
'fbsql_set_lob_mode' => ['bool', 'result'=>'resource', 'lob_mode'=>'int'],
'fbsql_set_password' => ['bool', 'link_identifier'=>'resource', 'user'=>'string', 'password'=>'string', 'old_password'=>'string'],
'fbsql_set_transaction' => ['void', 'link_identifier'=>'resource', 'locking'=>'int', 'isolation'=>'int'],
'fbsql_start_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource', 'database_options='=>'string'],
'fbsql_stop_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'fbsql_table_name' => ['string', 'result'=>'resource', 'index'=>'int'],
'fbsql_username' => ['string', 'link_identifier'=>'resource', 'username='=>'string'],
'fbsql_warnings' => ['bool', 'onoff='=>'bool'],
'fclose' => ['bool', 'stream'=>'resource'],
'fdf_add_doc_javascript' => ['bool', 'fdf_document'=>'resource', 'script_name'=>'string', 'script_code'=>'string'],
'fdf_add_template' => ['bool', 'fdf_document'=>'resource', 'newpage'=>'int', 'filename'=>'string', 'template'=>'string', 'rename'=>'int'],
'fdf_close' => ['void', 'fdf_document'=>'resource'],
'fdf_create' => ['resource'],
'fdf_enum_values' => ['bool', 'fdf_document'=>'resource', 'function'=>'callable', 'userdata='=>'mixed'],
'fdf_errno' => ['int'],
'fdf_error' => ['string', 'error_code='=>'int'],
'fdf_get_ap' => ['bool', 'fdf_document'=>'resource', 'field'=>'string', 'face'=>'int', 'filename'=>'string'],
'fdf_get_attachment' => ['array', 'fdf_document'=>'resource', 'fieldname'=>'string', 'savepath'=>'string'],
'fdf_get_encoding' => ['string', 'fdf_document'=>'resource'],
'fdf_get_file' => ['string', 'fdf_document'=>'resource'],
'fdf_get_flags' => ['int', 'fdf_document'=>'resource', 'fieldname'=>'string', 'whichflags'=>'int'],
'fdf_get_opt' => ['mixed', 'fdf_document'=>'resource', 'fieldname'=>'string', 'element='=>'int'],
'fdf_get_status' => ['string', 'fdf_document'=>'resource'],
'fdf_get_value' => ['mixed', 'fdf_document'=>'resource', 'fieldname'=>'string', 'which='=>'int'],
'fdf_get_version' => ['string', 'fdf_document='=>'resource'],
'fdf_header' => ['void'],
'fdf_next_field_name' => ['string', 'fdf_document'=>'resource', 'fieldname='=>'string'],
'fdf_open' => ['resource|false', 'filename'=>'string'],
'fdf_open_string' => ['resource', 'fdf_data'=>'string'],
'fdf_remove_item' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'item'=>'int'],
'fdf_save' => ['bool', 'fdf_document'=>'resource', 'filename='=>'string'],
'fdf_save_string' => ['string', 'fdf_document'=>'resource'],
'fdf_set_ap' => ['bool', 'fdf_document'=>'resource', 'field_name'=>'string', 'face'=>'int', 'filename'=>'string', 'page_number'=>'int'],
'fdf_set_encoding' => ['bool', 'fdf_document'=>'resource', 'encoding'=>'string'],
'fdf_set_file' => ['bool', 'fdf_document'=>'resource', 'url'=>'string', 'target_frame='=>'string'],
'fdf_set_flags' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'whichflags'=>'int', 'newflags'=>'int'],
'fdf_set_javascript_action' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'trigger'=>'int', 'script'=>'string'],
'fdf_set_on_import_javascript' => ['bool', 'fdf_document'=>'resource', 'script'=>'string', 'before_data_import'=>'bool'],
'fdf_set_opt' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'element'=>'int', 'string1'=>'string', 'string2'=>'string'],
'fdf_set_status' => ['bool', 'fdf_document'=>'resource', 'status'=>'string'],
'fdf_set_submit_form_action' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'trigger'=>'int', 'script'=>'string', 'flags'=>'int'],
'fdf_set_target_frame' => ['bool', 'fdf_document'=>'resource', 'frame_name'=>'string'],
'fdf_set_value' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'value'=>'mixed', 'isname='=>'int'],
'fdf_set_version' => ['bool', 'fdf_document'=>'resource', 'version'=>'string'],
'fdiv' => ['float', 'num1'=>'float', 'num2'=>'float'],
'feof' => ['bool', 'stream'=>'resource'],
'fflush' => ['bool', 'stream'=>'resource'],
'fsync' => ['bool', 'stream'=>'resource'],
'fdatasync' => ['bool', 'stream'=>'resource'],
'ffmpeg_animated_gif::__construct' => ['void', 'output_file_path'=>'string', 'width'=>'int', 'height'=>'int', 'frame_rate'=>'int', 'loop_count='=>'int'],
'ffmpeg_animated_gif::addFrame' => ['', 'frame_to_add'=>'ffmpeg_frame'],
'ffmpeg_frame::__construct' => ['void', 'gd_image'=>'resource'],
'ffmpeg_frame::crop' => ['', 'crop_top'=>'int', 'crop_bottom='=>'int', 'crop_left='=>'int', 'crop_right='=>'int'],
'ffmpeg_frame::getHeight' => ['int'],
'ffmpeg_frame::getPresentationTimestamp' => ['int'],
'ffmpeg_frame::getPTS' => ['int'],
'ffmpeg_frame::getWidth' => ['int'],
'ffmpeg_frame::resize' => ['', 'width'=>'int', 'height'=>'int', 'crop_top='=>'int', 'crop_bottom='=>'int', 'crop_left='=>'int', 'crop_right='=>'int'],
'ffmpeg_frame::toGDImage' => ['resource'],
'ffmpeg_movie::__construct' => ['void', 'path_to_media'=>'string', 'persistent'=>'bool'],
'ffmpeg_movie::getArtist' => ['string'],
'ffmpeg_movie::getAudioBitRate' => ['int'],
'ffmpeg_movie::getAudioChannels' => ['int'],
'ffmpeg_movie::getAudioCodec' => ['string'],
'ffmpeg_movie::getAudioSampleRate' => ['int'],
'ffmpeg_movie::getAuthor' => ['string'],
'ffmpeg_movie::getBitRate' => ['int'],
'ffmpeg_movie::getComment' => ['string'],
'ffmpeg_movie::getCopyright' => ['string'],
'ffmpeg_movie::getDuration' => ['int'],
'ffmpeg_movie::getFilename' => ['string'],
'ffmpeg_movie::getFrame' => ['ffmpeg_frame|false', 'framenumber'=>'int'],
'ffmpeg_movie::getFrameCount' => ['int'],
'ffmpeg_movie::getFrameHeight' => ['int'],
'ffmpeg_movie::getFrameNumber' => ['int'],
'ffmpeg_movie::getFrameRate' => ['int'],
'ffmpeg_movie::getFrameWidth' => ['int'],
'ffmpeg_movie::getGenre' => ['string'],
'ffmpeg_movie::getNextKeyFrame' => ['ffmpeg_frame|false'],
'ffmpeg_movie::getPixelFormat' => [''],
'ffmpeg_movie::getTitle' => ['string'],
'ffmpeg_movie::getTrackNumber' => ['int|string'],
'ffmpeg_movie::getVideoBitRate' => ['int'],
'ffmpeg_movie::getVideoCodec' => ['string'],
'ffmpeg_movie::getYear' => ['int|string'],
'ffmpeg_movie::hasAudio' => ['bool'],
'ffmpeg_movie::hasVideo' => ['bool'],
'fgetc' => ['string|false', 'stream'=>'resource'],
'fgetcsv' => ['list<string>|array{0: null}|false|null', 'stream'=>'resource', 'length='=>'int', 'separator='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'fgets' => ['string|false', 'stream'=>'resource', 'length='=>'int'],
'fgetss' => ['string|false', 'fp'=>'resource', 'length='=>'int', 'allowable_tags='=>'string'],
'file' => ['list<string>|false', 'filename'=>'string', 'flags='=>'int', 'context='=>'resource'],
'file_exists' => ['bool', 'filename'=>'string'],
'file_get_contents' => ['string|false', 'filename'=>'string', 'use_include_path='=>'bool', 'context='=>'?resource', 'offset='=>'int', 'length='=>'int'],
'file_put_contents' => ['int|false', 'filename'=>'string', 'data'=>'mixed', 'flags='=>'int', 'context='=>'resource'],
'fileatime' => ['int|false', 'filename'=>'string'],
'filectime' => ['int|false', 'filename'=>'string'],
'filegroup' => ['int|false', 'filename'=>'string'],
'fileinode' => ['int|false', 'filename'=>'string'],
'filemtime' => ['int|false', 'filename'=>'string'],
'fileowner' => ['int|false', 'filename'=>'string'],
'fileperms' => ['int|false', 'filename'=>'string'],
'filepro' => ['bool', 'directory'=>'string'],
'filepro_fieldcount' => ['int'],
'filepro_fieldname' => ['string', 'field_number'=>'int'],
'filepro_fieldtype' => ['string', 'field_number'=>'int'],
'filepro_fieldwidth' => ['int', 'field_number'=>'int'],
'filepro_retrieve' => ['string', 'row_number'=>'int', 'field_number'=>'int'],
'filepro_rowcount' => ['int'],
'filesize' => ['int|false', 'filename'=>'string'],
'FilesystemIterator::__construct' => ['void', 'path'=>'string', 'flags='=>'int'],
'FilesystemIterator::__toString' => ['string'],
'FilesystemIterator::_bad_state_ex' => [''],
'FilesystemIterator::current' => ['mixed'],
'FilesystemIterator::getATime' => ['int'],
'FilesystemIterator::getBasename' => ['string', 'suffix='=>'string'],
'FilesystemIterator::getCTime' => ['int'],
'FilesystemIterator::getExtension' => ['string'],
'FilesystemIterator::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'FilesystemIterator::getFilename' => ['string'],
'FilesystemIterator::getFlags' => ['int'],
'FilesystemIterator::getGroup' => ['int'],
'FilesystemIterator::getInode' => ['int'],
'FilesystemIterator::getLinkTarget' => ['string'],
'FilesystemIterator::getMTime' => ['int'],
'FilesystemIterator::getOwner' => ['int'],
'FilesystemIterator::getPath' => ['string'],
'FilesystemIterator::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'FilesystemIterator::getPathname' => ['string'],
'FilesystemIterator::getPerms' => ['int'],
'FilesystemIterator::getRealPath' => ['string'],
'FilesystemIterator::getSize' => ['int'],
'FilesystemIterator::getType' => ['string'],
'FilesystemIterator::isDir' => ['bool'],
'FilesystemIterator::isDot' => ['bool'],
'FilesystemIterator::isExecutable' => ['bool'],
'FilesystemIterator::isFile' => ['bool'],
'FilesystemIterator::isLink' => ['bool'],
'FilesystemIterator::isReadable' => ['bool'],
'FilesystemIterator::isWritable' => ['bool'],
'FilesystemIterator::key' => ['string'],
'FilesystemIterator::next' => ['void'],
'FilesystemIterator::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'FilesystemIterator::rewind' => ['void'],
'FilesystemIterator::seek' => ['void', 'position'=>'int'],
'FilesystemIterator::setFileClass' => ['void', 'class_name='=>'string'],
'FilesystemIterator::setFlags' => ['void', 'flags='=>'int'],
'FilesystemIterator::setInfoClass' => ['void', 'class_name='=>'string'],
'FilesystemIterator::valid' => ['bool'],
'filetype' => ['string|false', 'filename'=>'string'],
'filter_has_var' => ['bool', 'input_type'=>'int', 'var_name'=>'string'],
'filter_id' => ['int|false', 'name'=>'string'],
'filter_input' => ['mixed|false', 'type'=>'int', 'var_name'=>'string', 'filter='=>'int', 'options='=>'array|int'],
'filter_input_array' => ['mixed|false', 'type'=>'int', 'options='=>'int|array', 'add_empty='=>'bool'],
'filter_list' => ['array'],
'filter_var' => ['mixed|false', 'value'=>'mixed', 'filter='=>'int', 'options='=>'mixed'],
'filter_var_array' => ['mixed|false', 'array'=>'array', 'options='=>'mixed', 'add_empty='=>'bool'],
'FilterIterator::__construct' => ['void', 'iterator'=>'Iterator'],
'FilterIterator::accept' => ['bool'],
'FilterIterator::current' => ['mixed'],
'FilterIterator::getInnerIterator' => ['Iterator'],
'FilterIterator::key' => ['mixed'],
'FilterIterator::next' => ['void'],
'FilterIterator::rewind' => ['void'],
'FilterIterator::valid' => ['bool'],
'finfo::__construct' => ['void', 'options='=>'int', 'magic_file='=>'string'],
'finfo::buffer' => ['string|false', 'string'=>'string', 'options='=>'int', 'context='=>'resource'],
'finfo::file' => ['string|false', 'file_name'=>'string', 'options='=>'int', 'context='=>'resource'],
'finfo::finfo' => ['void', 'options='=>'int', 'magic_file='=>'string'],
'finfo::set_flags' => ['bool', 'options'=>'int'],
'finfo_buffer' => ['string|false', 'finfo'=>'finfo', 'string'=>'string', 'flags='=>'int', 'context='=>'resource'],
'finfo_close' => ['bool', 'finfo'=>'finfo'],
'finfo_file' => ['string|false', 'finfo'=>'finfo', 'filename'=>'string', 'flags='=>'int', 'context='=>'resource'],
'finfo_open' => ['finfo|false', 'flags='=>'int', 'magic_database='=>'string'],
'finfo_set_flags' => ['bool', 'finfo'=>'finfo', 'flags'=>'int'],
'floatval' => ['float', 'value'=>'mixed'],
'flock' => ['bool', 'stream'=>'resource', 'operation'=>'int', '&w_would_block='=>'int'],
'floor' => ['float', 'num'=>'float'],
'flush' => ['void'],
'fmod' => ['float', 'num1'=>'float', 'num2'=>'float'],
'fnmatch' => ['bool', 'pattern'=>'string', 'filename'=>'string', 'flags='=>'int'],
'fopen' => ['resource|false', 'filename'=>'string', 'mode'=>'string', 'use_include_path='=>'bool', 'context='=>'resource|null'],
'forward_static_call' => ['mixed|false', 'callback'=>'callable', '...args='=>'mixed'],
'forward_static_call_array' => ['mixed|false', 'callback'=>'callable', 'args'=>'list<mixed>'],
'fpassthru' => ['int|false', 'stream'=>'resource'],
'fpm_get_status' => ['array|false'],
'fprintf' => ['int', 'stream'=>'resource', 'format'=>'string', '...values='=>'string|int|float'],
'fputcsv' => ['int|false', 'stream'=>'resource', 'fields'=>'array<array-key, null|scalar|Stringable>', 'separator='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'fputs' => ['int|false', 'stream'=>'resource', 'data'=>'string', 'length='=>'int'],
'fread' => ['string|false', 'stream'=>'resource', 'length'=>'int'],
'frenchtojd' => ['int', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'fribidi_log2vis' => ['string', 'string'=>'string', 'direction'=>'string', 'charset'=>'int'],
'fscanf' => ['list<mixed>', 'stream'=>'resource', 'format'=>'string'],
'fscanf\'1' => ['int', 'stream'=>'resource', 'format'=>'string', '&...w_vars='=>'string|int|float'],
'fseek' => ['int', 'stream'=>'resource', 'offset'=>'int', 'whence='=>'int'],
'fsockopen' => ['resource|false', 'hostname'=>'string', 'port='=>'int', '&w_error_code='=>'int', '&w_error_message='=>'string', 'timeout='=>'float'],
'fstat' => ['array|false', 'stream'=>'resource'],
'ftell' => ['int|false', 'stream'=>'resource'],
'ftok' => ['int', 'filename'=>'string', 'project_id'=>'string'],
'ftp_alloc' => ['bool', 'ftp'=>'FTP\Connection', 'size'=>'int', '&w_response='=>'string'],
'ftp_append' => ['bool', 'ftp'=>'FTP\Connection', 'remote_filename'=>'string', 'local_filename'=>'string', 'mode='=>'int'],
'ftp_cdup' => ['bool', 'ftp'=>'FTP\Connection'],
'ftp_chdir' => ['bool', 'ftp'=>'FTP\Connection', 'directory'=>'string'],
'ftp_chmod' => ['int|false', 'ftp'=>'FTP\Connection', 'permissions'=>'int', 'filename'=>'string'],
'ftp_close' => ['bool', 'ftp'=>'FTP\Connection'],
'ftp_connect' => ['FTP\Connection|false', 'hostname'=>'string', 'port='=>'int', 'timeout='=>'int'],
'ftp_delete' => ['bool', 'ftp'=>'FTP\Connection', 'filename'=>'string'],
'ftp_exec' => ['bool', 'ftp'=>'FTP\Connection', 'command'=>'string'],
'ftp_fget' => ['bool', 'ftp'=>'FTP\Connection', 'stream'=>'FTP\Connection', 'remote_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_fput' => ['bool', 'ftp'=>'FTP\Connection', 'remote_filename'=>'string', 'stream'=>'FTP\Connection', 'mode='=>'int', 'offset='=>'int'],
'ftp_get' => ['bool', 'ftp'=>'FTP\Connection', 'local_filename'=>'string', 'remote_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_get_option' => ['mixed|false', 'ftp'=>'FTP\Connection', 'option'=>'int'],
'ftp_login' => ['bool', 'ftp'=>'FTP\Connection', 'username'=>'string', 'password'=>'string'],
'ftp_mdtm' => ['int', 'ftp'=>'FTP\Connection', 'filename'=>'string'],
'ftp_mkdir' => ['string|false', 'ftp'=>'FTP\Connection', 'directory'=>'string'],
'ftp_mlsd' => ['array|false', 'ftp'=>'FTP\Connection', 'directory'=>'string'],
'ftp_nb_continue' => ['int', 'ftp'=>'FTP\Connection'],
'ftp_nb_fget' => ['int', 'ftp'=>'FTP\Connection', 'stream'=>'FTP\Connection', 'remote_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_nb_fput' => ['int', 'ftp'=>'FTP\Connection', 'remote_filename'=>'string', 'stream'=>'FTP\Connection', 'mode='=>'int', 'offset='=>'int'],
'ftp_nb_get' => ['int', 'ftp'=>'FTP\Connection', 'local_filename'=>'string', 'remote_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_nb_put' => ['int', 'ftp'=>'FTP\Connection', 'remote_filename'=>'string', 'local_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_nlist' => ['array|false', 'ftp'=>'FTP\Connection', 'directory'=>'string'],
'ftp_pasv' => ['bool', 'ftp'=>'FTP\Connection', 'enable'=>'bool'],
'ftp_put' => ['bool', 'ftp'=>'FTP\Connection', 'remote_filename'=>'string', 'local_filename'=>'string', 'mode='=>'int', 'offset='=>'int'],
'ftp_pwd' => ['string|false', 'ftp'=>'FTP\Connection'],
'ftp_quit' => ['bool', 'ftp'=>'FTP\Connection'],
'ftp_raw' => ['array', 'ftp'=>'FTP\Connection', 'command'=>'string'],
'ftp_rawlist' => ['array|false', 'ftp'=>'FTP\Connection', 'directory'=>'string', 'recursive='=>'bool'],
'ftp_rename' => ['bool', 'ftp'=>'FTP\Connection', 'from'=>'string', 'to'=>'string'],
'ftp_rmdir' => ['bool', 'ftp'=>'FTP\Connection', 'directory'=>'string'],
'ftp_set_option' => ['bool', 'ftp'=>'FTP\Connection', 'option'=>'int', 'value'=>'mixed'],
'ftp_site' => ['bool', 'ftp'=>'FTP\Connection', 'command'=>'string'],
'ftp_size' => ['int', 'ftp'=>'FTP\Connection', 'filename'=>'string'],
'ftp_ssl_connect' => ['FTP\Connection|false', 'hostname'=>'string', 'port='=>'int', 'timeout='=>'int'],
'ftp_systype' => ['string|false', 'ftp'=>'FTP\Connection'],
'ftruncate' => ['bool', 'stream'=>'resource', 'size'=>'int'],
'func_get_arg' => ['mixed|false', 'position'=>'int'],
'func_get_args' => ['list<mixed>'],
'func_num_args' => ['int'],
'function_exists' => ['bool', 'function'=>'string'],
'fwrite' => ['int|false', 'stream'=>'resource', 'data'=>'string', 'length='=>'int'],
'Fiber::__construct' => ['void', 'callback'=>'callable'],
'Fiber::start' => ['mixed', '...args'=>'mixed'],
'Fiber::resume' => ['mixed', 'value='=>'null|mixed'],
'Fiber::throw' => ['mixed', 'exception'=>'Throwable'],
'Fiber::isStarted' => ['bool'],
'Fiber::isSuspended' => ['bool'],
'Fiber::isRunning' => ['bool'],
'Fiber::isTerminated' => ['bool'],
'Fiber::getReturn' => ['mixed'],
'Fiber::getCurrent' => ['?self'],
'Fiber::suspend' => ['mixed', 'value='=>'null|mixed'],
'FiberError::__construct' => ['void'],
'gc_collect_cycles' => ['int'],
'gc_disable' => ['void'],
'gc_enable' => ['void'],
'gc_enabled' => ['bool'],
'gc_mem_caches' => ['int'],
'gc_status' => ['array{runs:int,collected:int,threshold:int,roots:int}'],
'gd_info' => ['array'],
'gearman_bugreport' => [''],
'gearman_client_add_options' => ['', 'client_object'=>'', 'option'=>''],
'gearman_client_add_server' => ['', 'client_object'=>'', 'host'=>'', 'port'=>''],
'gearman_client_add_servers' => ['', 'client_object'=>'', 'servers'=>''],
'gearman_client_add_task' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_high' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_high_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_low' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_low_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_status' => ['', 'client_object'=>'', 'job_handle'=>'', 'context'=>''],
'gearman_client_clear_fn' => ['', 'client_object'=>''],
'gearman_client_clone' => ['', 'client_object'=>''],
'gearman_client_context' => ['', 'client_object'=>''],
'gearman_client_create' => ['', 'client_object'=>''],
'gearman_client_do' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_high' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_high_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_job_handle' => ['', 'client_object'=>''],
'gearman_client_do_low' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_low_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_normal' => ['', 'client_object'=>'', 'function_name'=>'string', 'workload'=>'string', 'unique'=>'string'],
'gearman_client_do_status' => ['', 'client_object'=>''],
'gearman_client_echo' => ['', 'client_object'=>'', 'workload'=>''],
'gearman_client_errno' => ['', 'client_object'=>''],
'gearman_client_error' => ['', 'client_object'=>''],
'gearman_client_job_status' => ['', 'client_object'=>'', 'job_handle'=>''],
'gearman_client_options' => ['', 'client_object'=>''],
'gearman_client_remove_options' => ['', 'client_object'=>'', 'option'=>''],
'gearman_client_return_code' => ['', 'client_object'=>''],
'gearman_client_run_tasks' => ['', 'data'=>''],
'gearman_client_set_complete_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_context' => ['', 'client_object'=>'', 'context'=>''],
'gearman_client_set_created_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_data_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_exception_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_fail_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_options' => ['', 'client_object'=>'', 'option'=>''],
'gearman_client_set_status_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_timeout' => ['', 'client_object'=>'', 'timeout'=>''],
'gearman_client_set_warning_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_workload_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_timeout' => ['', 'client_object'=>''],
'gearman_client_wait' => ['', 'client_object'=>''],
'gearman_job_function_name' => ['', 'job_object'=>''],
'gearman_job_handle' => ['string'],
'gearman_job_return_code' => ['', 'job_object'=>''],
'gearman_job_send_complete' => ['', 'job_object'=>'', 'result'=>''],
'gearman_job_send_data' => ['', 'job_object'=>'', 'data'=>''],
'gearman_job_send_exception' => ['', 'job_object'=>'', 'exception'=>''],
'gearman_job_send_fail' => ['', 'job_object'=>''],
'gearman_job_send_status' => ['', 'job_object'=>'', 'numerator'=>'', 'denominator'=>''],
'gearman_job_send_warning' => ['', 'job_object'=>'', 'warning'=>''],
'gearman_job_status' => ['array', 'job_handle'=>'string'],
'gearman_job_unique' => ['', 'job_object'=>''],
'gearman_job_workload' => ['', 'job_object'=>''],
'gearman_job_workload_size' => ['', 'job_object'=>''],
'gearman_task_data' => ['', 'task_object'=>''],
'gearman_task_data_size' => ['', 'task_object'=>''],
'gearman_task_denominator' => ['', 'task_object'=>''],
'gearman_task_function_name' => ['', 'task_object'=>''],
'gearman_task_is_known' => ['', 'task_object'=>''],
'gearman_task_is_running' => ['', 'task_object'=>''],
'gearman_task_job_handle' => ['', 'task_object'=>''],
'gearman_task_numerator' => ['', 'task_object'=>''],
'gearman_task_recv_data' => ['', 'task_object'=>'', 'data_len'=>''],
'gearman_task_return_code' => ['', 'task_object'=>''],
'gearman_task_send_workload' => ['', 'task_object'=>'', 'data'=>''],
'gearman_task_unique' => ['', 'task_object'=>''],
'gearman_verbose_name' => ['', 'verbose'=>''],
'gearman_version' => [''],
'gearman_worker_add_function' => ['', 'worker_object'=>'', 'function_name'=>'', 'function'=>'', 'data'=>'', 'timeout'=>''],
'gearman_worker_add_options' => ['', 'worker_object'=>'', 'option'=>''],
'gearman_worker_add_server' => ['', 'worker_object'=>'', 'host'=>'', 'port'=>''],
'gearman_worker_add_servers' => ['', 'worker_object'=>'', 'servers'=>''],
'gearman_worker_clone' => ['', 'worker_object'=>''],
'gearman_worker_create' => [''],
'gearman_worker_echo' => ['', 'worker_object'=>'', 'workload'=>''],
'gearman_worker_errno' => ['', 'worker_object'=>''],
'gearman_worker_error' => ['', 'worker_object'=>''],
'gearman_worker_grab_job' => ['', 'worker_object'=>''],
'gearman_worker_options' => ['', 'worker_object'=>''],
'gearman_worker_register' => ['', 'worker_object'=>'', 'function_name'=>'', 'timeout'=>''],
'gearman_worker_remove_options' => ['', 'worker_object'=>'', 'option'=>''],
'gearman_worker_return_code' => ['', 'worker_object'=>''],
'gearman_worker_set_options' => ['', 'worker_object'=>'', 'option'=>''],
'gearman_worker_set_timeout' => ['', 'worker_object'=>'', 'timeout'=>''],
'gearman_worker_timeout' => ['', 'worker_object'=>''],
'gearman_worker_unregister' => ['', 'worker_object'=>'', 'function_name'=>''],
'gearman_worker_unregister_all' => ['', 'worker_object'=>''],
'gearman_worker_wait' => ['', 'worker_object'=>''],
'gearman_worker_work' => ['', 'worker_object'=>''],
'GearmanClient::__construct' => ['void'],
'GearmanClient::addOptions' => ['bool', 'options'=>'int'],
'GearmanClient::addServer' => ['bool', 'host='=>'string', 'port='=>'int'],
'GearmanClient::addServers' => ['bool', 'servers='=>'string'],
'GearmanClient::addTask' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskBackground' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskHigh' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskHighBackground' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskLow' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskLowBackground' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskStatus' => ['GearmanTask', 'job_handle'=>'string', 'context='=>'string'],
'GearmanClient::clearCallbacks' => ['bool'],
'GearmanClient::clone' => ['GearmanClient'],
'GearmanClient::context' => ['string'],
'GearmanClient::data' => ['string'],
'GearmanClient::do' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doBackground' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doHigh' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doHighBackground' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doJobHandle' => ['string'],
'GearmanClient::doLow' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doLowBackground' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doNormal' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doStatus' => ['array'],
'GearmanClient::echo' => ['bool', 'workload'=>'string'],
'GearmanClient::error' => ['string'],
'GearmanClient::getErrno' => ['int'],
'GearmanClient::jobStatus' => ['array', 'job_handle'=>'string'],
'GearmanClient::options' => [''],
'GearmanClient::ping' => ['bool', 'workload'=>'string'],
'GearmanClient::removeOptions' => ['bool', 'options'=>'int'],
'GearmanClient::returnCode' => ['int'],
'GearmanClient::runTasks' => ['bool'],
'GearmanClient::setClientCallback' => ['void', 'callback'=>'callable'],
'GearmanClient::setCompleteCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setContext' => ['bool', 'context'=>'string'],
'GearmanClient::setCreatedCallback' => ['bool', 'callback'=>'string'],
'GearmanClient::setData' => ['bool', 'data'=>'string'],
'GearmanClient::setDataCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setExceptionCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setFailCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setOptions' => ['bool', 'options'=>'int'],
'GearmanClient::setStatusCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setTimeout' => ['bool', 'timeout'=>'int'],
'GearmanClient::setWarningCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setWorkloadCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::timeout' => ['int'],
'GearmanClient::wait' => [''],
'GearmanJob::__construct' => ['void'],
'GearmanJob::complete' => ['bool', 'result'=>'string'],
'GearmanJob::data' => ['bool', 'data'=>'string'],
'GearmanJob::exception' => ['bool', 'exception'=>'string'],
'GearmanJob::fail' => ['bool'],
'GearmanJob::functionName' => ['string'],
'GearmanJob::handle' => ['string'],
'GearmanJob::returnCode' => ['int'],
'GearmanJob::sendComplete' => ['bool', 'result'=>'string'],
'GearmanJob::sendData' => ['bool', 'data'=>'string'],
'GearmanJob::sendException' => ['bool', 'exception'=>'string'],
'GearmanJob::sendFail' => ['bool'],
'GearmanJob::sendStatus' => ['bool', 'numerator'=>'int', 'denominator'=>'int'],
'GearmanJob::sendWarning' => ['bool', 'warning'=>'string'],
'GearmanJob::setReturn' => ['bool', 'gearman_return_t'=>'string'],
'GearmanJob::status' => ['bool', 'numerator'=>'int', 'denominator'=>'int'],
'GearmanJob::unique' => ['string'],
'GearmanJob::warning' => ['bool', 'warning'=>'string'],
'GearmanJob::workload' => ['string'],
'GearmanJob::workloadSize' => ['int'],
'GearmanTask::__construct' => ['void'],
'GearmanTask::create' => ['GearmanTask'],
'GearmanTask::data' => ['string|false'],
'GearmanTask::dataSize' => ['int|false'],
'GearmanTask::function' => ['string'],
'GearmanTask::functionName' => ['string'],
'GearmanTask::isKnown' => ['bool'],
'GearmanTask::isRunning' => ['bool'],
'GearmanTask::jobHandle' => ['string'],
'GearmanTask::recvData' => ['array|false', 'data_len'=>'int'],
'GearmanTask::returnCode' => ['int'],
'GearmanTask::sendData' => ['int', 'data'=>'string'],
'GearmanTask::sendWorkload' => ['int|false', 'data'=>'string'],
'GearmanTask::taskDenominator' => ['int|false'],
'GearmanTask::taskNumerator' => ['int|false'],
'GearmanTask::unique' => ['string|false'],
'GearmanTask::uuid' => ['string'],
'GearmanWorker::__construct' => ['void'],
'GearmanWorker::addFunction' => ['bool', 'function_name'=>'string', 'function'=>'callable', 'context='=>'mixed', 'timeout='=>'int'],
'GearmanWorker::addOptions' => ['bool', 'option'=>'int'],
'GearmanWorker::addServer' => ['bool', 'host='=>'string', 'port='=>'int'],
'GearmanWorker::addServers' => ['bool', 'servers'=>'string'],
'GearmanWorker::clone' => ['void'],
'GearmanWorker::echo' => ['bool', 'workload'=>'string'],
'GearmanWorker::error' => ['string'],
'GearmanWorker::getErrno' => ['int'],
'GearmanWorker::grabJob' => [''],
'GearmanWorker::options' => ['int'],
'GearmanWorker::register' => ['bool', 'function_name'=>'string', 'timeout='=>'int'],
'GearmanWorker::removeOptions' => ['bool', 'option'=>'int'],
'GearmanWorker::returnCode' => ['int'],
'GearmanWorker::setId' => ['bool', 'id'=>'string'],
'GearmanWorker::setOptions' => ['bool', 'option'=>'int'],
'GearmanWorker::setTimeout' => ['bool', 'timeout'=>'int'],
'GearmanWorker::timeout' => ['int'],
'GearmanWorker::unregister' => ['bool', 'function_name'=>'string'],
'GearmanWorker::unregisterAll' => ['bool'],
'GearmanWorker::wait' => ['bool'],
'GearmanWorker::work' => ['bool'],
'Gender\Gender::__construct' => ['void', 'dsn='=>'string'],
'Gender\Gender::connect' => ['bool', 'dsn'=>'string'],
'Gender\Gender::country' => ['array', 'country'=>'int'],
'Gender\Gender::get' => ['int', 'name'=>'string', 'country='=>'int'],
'Gender\Gender::isNick' => ['array', 'name0'=>'string', 'name1'=>'string', 'country='=>'int'],
'Gender\Gender::similarNames' => ['array', 'name'=>'string', 'country='=>'int'],
'Generator::__wakeup' => ['void'],
'Generator::current' => ['mixed'],
'Generator::getReturn' => ['mixed'],
'Generator::key' => ['mixed'],
'Generator::next' => ['void'],
'Generator::rewind' => ['void'],
'Generator::send' => ['mixed', 'value'=>'mixed'],
'Generator::throw' => ['mixed', 'exception'=>'Exception|Throwable'],
'Generator::valid' => ['bool'],
'geoip_asnum_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_continent_code_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_country_code3_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_country_code_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_country_name_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_database_info' => ['string', 'database='=>'int'],
'geoip_db_avail' => ['bool', 'database'=>'int'],
'geoip_db_filename' => ['string', 'database'=>'int'],
'geoip_db_get_all_info' => ['array'],
'geoip_domain_by_name' => ['string', 'hostname'=>'string'],
'geoip_id_by_name' => ['int', 'hostname'=>'string'],
'geoip_isp_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_netspeedcell_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_org_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_record_by_name' => ['array|false', 'hostname'=>'string'],
'geoip_region_by_name' => ['array|false', 'hostname'=>'string'],
'geoip_region_name_by_code' => ['string|false', 'country_code'=>'string', 'region_code'=>'string'],
'geoip_setup_custom_directory' => ['void', 'path'=>'string'],
'geoip_time_zone_by_country_and_region' => ['string|false', 'country_code'=>'string', 'region_code='=>'string'],
'GEOSGeometry::__toString' => ['string'],
'GEOSGeometry::project' => ['float', 'other'=>'GEOSGeometry', 'normalized'=>'bool'],
'GEOSGeometry::interpolate' => ['GEOSGeometry', 'dist'=>'float', 'normalized'=>'bool'],
'GEOSGeometry::buffer' => ['GEOSGeometry', 'dist'=>'float', 'styleArray'=>'array'],
'GEOSGeometry::offsetCurve' => ['GEOSGeometry', 'dist'=>'float', 'styleArray'=>'array'],
'GEOSGeometry::envelope' => ['GEOSGeometry'],
'GEOSGeometry::intersection' => ['GEOSGeometry', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::convexHull' => ['GEOSGeometry'],
'GEOSGeometry::difference' => ['GEOSGeometry', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::symDifference' => ['GEOSGeometry', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::boundary' => ['GEOSGeometry'],
'GEOSGeometry::union' => ['GEOSGeometry', 'otherGeom='=>'GEOSGeometry'],
'GEOSGeometry::pointOnSurface' => ['GEOSGeometry'],
'GEOSGeometry::centroid' => ['GEOSGeometry'],
'GEOSGeometry::relate' => ['string|bool', 'otherGeom'=>'GEOSGeometry', 'pattern'=>'string'],
'GEOSGeometry::relateBoundaryNodeRule' => ['string', 'otherGeom'=>'GEOSGeometry', 'rule'=>'int'],
'GEOSGeometry::simplify' => ['GEOSGeometry', 'tolerance'=>'float', 'preserveTopology'=>'bool'],
'GEOSGeometry::normalize' => ['GEOSGeometry'],
'GEOSGeometry::extractUniquePoints' => ['GEOSGeometry'],
'GEOSGeometry::disjoint' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::touches' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::intersects' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::crosses' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::within' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::contains' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::overlaps' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::covers' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::coveredBy' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::equals' => ['bool', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::equalsExact' => ['bool', 'geom'=>'GEOSGeometry', 'tolerance'=>'float'],
'GEOSGeometry::isEmpty' => ['bool'],
'GEOSGeometry::checkValidity' => ['array{valid: bool, reason?: string, location?: GEOSGeometry}'],
'GEOSGeometry::isSimple' => ['bool'],
'GEOSGeometry::isRing' => ['bool'],
'GEOSGeometry::hasZ' => ['bool'],
'GEOSGeometry::isClosed' => ['bool'],
'GEOSGeometry::typeName' => ['string'],
'GEOSGeometry::typeId' => ['int'],
'GEOSGeometry::getSRID' => ['int'],
'GEOSGeometry::setSRID' => ['void', 'srid'=>'int'],
'GEOSGeometry::numGeometries' => ['int'],
'GEOSGeometry::geometryN' => ['GEOSGeometry', 'num'=>'int'],
'GEOSGeometry::numInteriorRings' => ['int'],
'GEOSGeometry::numPoints' => ['int'],
'GEOSGeometry::getX' => ['float'],
'GEOSGeometry::getY' => ['float'],
'GEOSGeometry::interiorRingN' => ['GEOSGeometry', 'num'=>'int'],
'GEOSGeometry::exteriorRing' => ['GEOSGeometry'],
'GEOSGeometry::numCoordinates' => ['int'],
'GEOSGeometry::dimension' => ['int'],
'GEOSGeometry::coordinateDimension' => ['int'],
'GEOSGeometry::pointN' => ['GEOSGeometry', 'num'=>'int'],
'GEOSGeometry::startPoint' => ['GEOSGeometry'],
'GEOSGeometry::endPoint' => ['GEOSGeometry'],
'GEOSGeometry::area' => ['float'],
'GEOSGeometry::length' => ['float'],
'GEOSGeometry::distance' => ['float', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::hausdorffDistance' => ['float', 'geom'=>'GEOSGeometry'],
'GEOSGeometry::snapTo' => ['GEOSGeometry', 'geom'=>'GEOSGeometry', 'tolerance'=>'float'],
'GEOSGeometry::node' => ['GEOSGeometry'],
'GEOSGeometry::delaunayTriangulation' => ['GEOSGeometry', 'tolerance'=>'float', 'onlyEdges'=>'bool'],
'GEOSGeometry::voronoiDiagram' => ['GEOSGeometry', 'tolerance'=>'float', 'onlyEdges'=>'bool', 'extent'=>'GEOSGeometry|null'],
'GEOSLineMerge' => ['array', 'geom'=>'GEOSGeometry'],
'GEOSPolygonize' => ['array{rings: GEOSGeometry[], cut_edges?: GEOSGeometry[], dangles: GEOSGeometry[], invalid_rings: GEOSGeometry[]}', 'geom'=>'GEOSGeometry'],
'GEOSRelateMatch' => ['bool', 'matrix'=>'string', 'pattern'=>'string'],
'GEOSSharedPaths' => ['GEOSGeometry', 'geom1'=>'GEOSGeometry', 'geom2'=>'GEOSGeometry'],
'GEOSVersion' => ['string'],
'GEOSWKBReader::__construct' => ['void'],
'GEOSWKBReader::read' => ['GEOSGeometry', 'wkb'=>'string'],
'GEOSWKBReader::readHEX' => ['GEOSGeometry', 'wkb'=>'string'],
'GEOSWKBWriter::__construct' => ['void'],
'GEOSWKBWriter::getOutputDimension' => ['int'],
'GEOSWKBWriter::setOutputDimension' => ['void', 'dim'=>'int'],
'GEOSWKBWriter::getByteOrder' => ['int'],
'GEOSWKBWriter::setByteOrder' => ['void', 'byteOrder'=>'int'],
'GEOSWKBWriter::getIncludeSRID' => ['bool'],
'GEOSWKBWriter::setIncludeSRID' => ['void', 'inc'=>'bool'],
'GEOSWKBWriter::write' => ['string', 'geom'=>'GEOSGeometry'],
'GEOSWKBWriter::writeHEX' => ['string', 'geom'=>'GEOSGeometry'],
'GEOSWKTReader::__construct' => ['void'],
'GEOSWKTReader::read' => ['GEOSGeometry', 'wkt'=>'string'],
'GEOSWKTWriter::__construct' => ['void'],
'GEOSWKTWriter::write' => ['string', 'geom'=>'GEOSGeometry'],
'GEOSWKTWriter::setTrim' => ['void', 'trim'=>'bool'],
'GEOSWKTWriter::setRoundingPrecision' => ['void', 'prec'=>'int'],
'GEOSWKTWriter::setOutputDimension' => ['void', 'dim'=>'int'],
'GEOSWKTWriter::getOutputDimension' => ['int'],
'GEOSWKTWriter::setOld3D' => ['void', 'val'=>'bool'],
'get_browser' => ['array|object|false', 'user_agent='=>'?string', 'return_array='=>'bool'],
'get_call_stack' => [''],
'get_called_class' => ['class-string'],
'get_cfg_var' => ['string|false', 'option'=>'string'],
'get_class' => ['class-string|false', 'object='=>'object'],
'get_class_methods' => ['list<string>|null', 'object_or_class'=>'mixed'],
'get_class_vars' => ['array<string,mixed>', 'class'=>'string'],
'get_current_user' => ['string'],
'get_debug_type' => ['string', 'value'=>'mixed'],
'get_declared_classes' => ['list<class-string>'],
'get_declared_interfaces' => ['list<class-string>'],
'get_declared_traits' => ['list<class-string>|null'],
'get_defined_constants' => ['array<string,int|string|float|bool|null|array|resource>', 'categorize='=>'bool'],
'get_defined_functions' => ['array<string,list<callable-string>>', 'exclude_disabled='=>'bool'],
'get_defined_vars' => ['array'],
'get_extension_funcs' => ['list<callable-string>|false', 'extension'=>'string'],
'get_headers' => ['array|false', 'url'=>'string', 'associative='=>'int', 'context='=>'resource'],
'get_html_translation_table' => ['array', 'table='=>'int', 'flags='=>'int', 'encoding='=>'string'],
'get_include_path' => ['string'],
'get_included_files' => ['list<string>'],
'get_loaded_extensions' => ['list<string>', 'zend_extensions='=>'bool'],
'get_magic_quotes_gpc' => ['int|false'],
'get_magic_quotes_runtime' => ['int|false'],
'get_meta_tags' => ['array', 'filename'=>'string', 'use_include_path='=>'bool'],
'get_object_vars' => ['array<string,mixed>', 'object'=>'object'],
'get_parent_class' => ['class-string|false', 'object_or_class='=>'mixed'],
'get_required_files' => ['list<string>'],
'get_resource_id' => ['int', 'resource'=>'resource'],
'get_resource_type' => ['string', 'resource'=>'resource'],
'get_resources' => ['array<int,resource>', 'type='=>'string'],
'getallheaders' => ['array|false'],
'getcwd' => ['string|false'],
'getdate' => ['array', 'timestamp='=>'int'],
'getenv' => ['string|false', 'name'=>'string', 'local_only='=>'bool'],
'getenv\'1' => ['array<string,string>'],
'gethostbyaddr' => ['string|false', 'ip'=>'string'],
'gethostbyname' => ['string', 'hostname'=>'string'],
'gethostbynamel' => ['list<string>|false', 'hostname'=>'string'],
'gethostname' => ['string|false'],
'getimagesize' => ['array|false', 'filename'=>'string', '&w_image_info='=>'array'],
'getimagesizefromstring' => ['array|false', 'string'=>'string', '&w_image_info='=>'array'],
'getlastmod' => ['int|false'],
'getmxrr' => ['bool', 'hostname'=>'string', '&w_hosts'=>'array', '&w_weights='=>'array'],
'getmygid' => ['int|false'],
'getmyinode' => ['int|false'],
'getmypid' => ['int|false'],
'getmyuid' => ['int|false'],
'getopt' => ['array<string,string>|array<string,false>|array<string,list<mixed>>|false', 'short_options'=>'string', 'long_options='=>'array', '&w_rest_index='=>'int'],
'getprotobyname' => ['int|false', 'protocol'=>'string'],
'getprotobynumber' => ['string', 'protocol'=>'int'],
'getrandmax' => ['int'],
'getrusage' => ['array', 'mode='=>'int'],
'getservbyname' => ['int|false', 'service'=>'string', 'protocol'=>'string'],
'getservbyport' => ['string|false', 'port'=>'int', 'protocol'=>'string'],
'gettext' => ['string', 'message'=>'string'],
'gettimeofday' => ['array<string, int>'],
'gettimeofday\'1' => ['float', 'as_float='=>'true'],
'gettype' => ['string', 'value'=>'mixed'],
'glob' => ['list<string>|false', 'pattern'=>'string', 'flags='=>'int'],
'GlobIterator::__construct' => ['void', 'path'=>'string', 'flags='=>'int'],
'GlobIterator::count' => ['int'],
'GlobIterator::current' => ['FilesystemIterator|SplFileInfo|string'],
'GlobIterator::getATime' => [''],
'GlobIterator::getBasename' => ['', 'suffix='=>'string'],
'GlobIterator::getCTime' => [''],
'GlobIterator::getExtension' => [''],
'GlobIterator::getFileInfo' => [''],
'GlobIterator::getFilename' => [''],
'GlobIterator::getFlags' => ['int'],
'GlobIterator::getGroup' => [''],
'GlobIterator::getInode' => [''],
'GlobIterator::getLinkTarget' => [''],
'GlobIterator::getMTime' => [''],
'GlobIterator::getOwner' => [''],
'GlobIterator::getPath' => [''],
'GlobIterator::getPathInfo' => [''],
'GlobIterator::getPathname' => [''],
'GlobIterator::getPerms' => [''],
'GlobIterator::getRealPath' => [''],
'GlobIterator::getSize' => [''],
'GlobIterator::getType' => [''],
'GlobIterator::isDir' => [''],
'GlobIterator::isDot' => [''],
'GlobIterator::isExecutable' => [''],
'GlobIterator::isFile' => [''],
'GlobIterator::isLink' => [''],
'GlobIterator::isReadable' => [''],
'GlobIterator::isWritable' => [''],
'GlobIterator::key' => ['string'],
'GlobIterator::next' => ['void'],
'GlobIterator::openFile' => [''],
'GlobIterator::rewind' => ['void'],
'GlobIterator::seek' => ['void', 'position'=>'int'],
'GlobIterator::setFileClass' => [''],
'GlobIterator::setFlags' => ['void', 'flags='=>'int'],
'GlobIterator::setInfoClass' => [''],
'GlobIterator::valid' => [''],
'Gmagick::__construct' => ['void', 'filename='=>'string'],
'Gmagick::addimage' => ['Gmagick', 'gmagick'=>'gmagick'],
'Gmagick::addnoiseimage' => ['Gmagick', 'noise'=>'int'],
'Gmagick::annotateimage' => ['Gmagick', 'gmagickdraw'=>'gmagickdraw', 'x'=>'float', 'y'=>'float', 'angle'=>'float', 'text'=>'string'],
'Gmagick::blurimage' => ['Gmagick', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Gmagick::borderimage' => ['Gmagick', 'color'=>'gmagickpixel', 'width'=>'int', 'height'=>'int'],
'Gmagick::charcoalimage' => ['Gmagick', 'radius'=>'float', 'sigma'=>'float'],
'Gmagick::chopimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Gmagick::clear' => ['Gmagick'],
'Gmagick::commentimage' => ['Gmagick', 'comment'=>'string'],
'Gmagick::compositeimage' => ['Gmagick', 'source'=>'gmagick', 'compose'=>'int', 'x'=>'int', 'y'=>'int'],
'Gmagick::cropimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Gmagick::cropthumbnailimage' => ['Gmagick', 'width'=>'int', 'height'=>'int'],
'Gmagick::current' => ['Gmagick'],
'Gmagick::cyclecolormapimage' => ['Gmagick', 'displace'=>'int'],
'Gmagick::deconstructimages' => ['Gmagick'],
'Gmagick::despeckleimage' => ['Gmagick'],
'Gmagick::destroy' => ['bool'],
'Gmagick::drawimage' => ['Gmagick', 'gmagickdraw'=>'gmagickdraw'],
'Gmagick::edgeimage' => ['Gmagick', 'radius'=>'float'],
'Gmagick::embossimage' => ['Gmagick', 'radius'=>'float', 'sigma'=>'float'],
'Gmagick::enhanceimage' => ['Gmagick'],
'Gmagick::equalizeimage' => ['Gmagick'],
'Gmagick::flipimage' => ['Gmagick'],
'Gmagick::flopimage' => ['Gmagick'],
'Gmagick::frameimage' => ['Gmagick', 'color'=>'gmagickpixel', 'width'=>'int', 'height'=>'int', 'inner_bevel'=>'int', 'outer_bevel'=>'int'],
'Gmagick::gammaimage' => ['Gmagick', 'gamma'=>'float'],
'Gmagick::getcopyright' => ['string'],
'Gmagick::getfilename' => ['string'],
'Gmagick::getimagebackgroundcolor' => ['GmagickPixel'],
'Gmagick::getimageblueprimary' => ['array'],
'Gmagick::getimagebordercolor' => ['GmagickPixel'],
'Gmagick::getimagechanneldepth' => ['int', 'channel_type'=>'int'],
'Gmagick::getimagecolors' => ['int'],
'Gmagick::getimagecolorspace' => ['int'],
'Gmagick::getimagecompose' => ['int'],
'Gmagick::getimagedelay' => ['int'],
'Gmagick::getimagedepth' => ['int'],
'Gmagick::getimagedispose' => ['int'],
'Gmagick::getimageextrema' => ['array'],
'Gmagick::getimagefilename' => ['string'],
'Gmagick::getimageformat' => ['string'],
'Gmagick::getimagegamma' => ['float'],
'Gmagick::getimagegreenprimary' => ['array'],
'Gmagick::getimageheight' => ['int'],
'Gmagick::getimagehistogram' => ['array'],
'Gmagick::getimageindex' => ['int'],
'Gmagick::getimageinterlacescheme' => ['int'],
'Gmagick::getimageiterations' => ['int'],
'Gmagick::getimagematte' => ['int'],
'Gmagick::getimagemattecolor' => ['GmagickPixel'],
'Gmagick::getimageprofile' => ['string', 'name'=>'string'],
'Gmagick::getimageredprimary' => ['array'],
'Gmagick::getimagerenderingintent' => ['int'],
'Gmagick::getimageresolution' => ['array'],
'Gmagick::getimagescene' => ['int'],
'Gmagick::getimagesignature' => ['string'],
'Gmagick::getimagetype' => ['int'],
'Gmagick::getimageunits' => ['int'],
'Gmagick::getimagewhitepoint' => ['array'],
'Gmagick::getimagewidth' => ['int'],
'Gmagick::getpackagename' => ['string'],
'Gmagick::getquantumdepth' => ['array'],
'Gmagick::getreleasedate' => ['string'],
'Gmagick::getsamplingfactors' => ['array'],
'Gmagick::getsize' => ['array'],
'Gmagick::getversion' => ['array'],
'Gmagick::hasnextimage' => ['bool'],
'Gmagick::haspreviousimage' => ['bool'],
'Gmagick::implodeimage' => ['mixed', 'radius'=>'float'],
'Gmagick::labelimage' => ['mixed', 'label'=>'string'],
'Gmagick::levelimage' => ['mixed', 'blackpoint'=>'float', 'gamma'=>'float', 'whitepoint'=>'float', 'channel='=>'int'],
'Gmagick::magnifyimage' => ['mixed'],
'Gmagick::mapimage' => ['Gmagick', 'gmagick'=>'gmagick', 'dither'=>'bool'],
'Gmagick::medianfilterimage' => ['void', 'radius'=>'float'],
'Gmagick::minifyimage' => ['Gmagick'],
'Gmagick::modulateimage' => ['Gmagick', 'brightness'=>'float', 'saturation'=>'float', 'hue'=>'float'],
'Gmagick::motionblurimage' => ['Gmagick', 'radius'=>'float', 'sigma'=>'float', 'angle'=>'float'],
'Gmagick::newimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'background'=>'string', 'format='=>'string'],
'Gmagick::nextimage' => ['bool'],
'Gmagick::normalizeimage' => ['Gmagick', 'channel='=>'int'],
'Gmagick::oilpaintimage' => ['Gmagick', 'radius'=>'float'],
'Gmagick::previousimage' => ['bool'],
'Gmagick::profileimage' => ['Gmagick', 'name'=>'string', 'profile'=>'string'],
'Gmagick::quantizeimage' => ['Gmagick', 'numcolors'=>'int', 'colorspace'=>'int', 'treedepth'=>'int', 'dither'=>'bool', 'measureerror'=>'bool'],
'Gmagick::quantizeimages' => ['Gmagick', 'numcolors'=>'int', 'colorspace'=>'int', 'treedepth'=>'int', 'dither'=>'bool', 'measureerror'=>'bool'],
'Gmagick::queryfontmetrics' => ['array', 'draw'=>'gmagickdraw', 'text'=>'string'],
'Gmagick::queryfonts' => ['array', 'pattern='=>'string'],
'Gmagick::queryformats' => ['array', 'pattern='=>'string'],
'Gmagick::radialblurimage' => ['Gmagick', 'angle'=>'float', 'channel='=>'int'],
'Gmagick::raiseimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int', 'raise'=>'bool'],
'Gmagick::read' => ['Gmagick', 'filename'=>'string'],
'Gmagick::readimage' => ['Gmagick', 'filename'=>'string'],
'Gmagick::readimageblob' => ['Gmagick', 'imagecontents'=>'string', 'filename='=>'string'],
'Gmagick::readimagefile' => ['Gmagick', 'fp'=>'resource', 'filename='=>'string'],
'Gmagick::reducenoiseimage' => ['Gmagick', 'radius'=>'float'],
'Gmagick::removeimage' => ['Gmagick'],
'Gmagick::removeimageprofile' => ['string', 'name'=>'string'],
'Gmagick::resampleimage' => ['Gmagick', 'xresolution'=>'float', 'yresolution'=>'float', 'filter'=>'int', 'blur'=>'float'],
'Gmagick::resizeimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'filter'=>'int', 'blur'=>'float', 'fit='=>'bool'],
'Gmagick::rollimage' => ['Gmagick', 'x'=>'int', 'y'=>'int'],
'Gmagick::rotateimage' => ['Gmagick', 'color'=>'mixed', 'degrees'=>'float'],
'Gmagick::scaleimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'fit='=>'bool'],
'Gmagick::separateimagechannel' => ['Gmagick', 'channel'=>'int'],
'Gmagick::setCompressionQuality' => ['Gmagick', 'quality'=>'int'],
'Gmagick::setfilename' => ['Gmagick', 'filename'=>'string'],
'Gmagick::setimagebackgroundcolor' => ['Gmagick', 'color'=>'gmagickpixel'],
'Gmagick::setimageblueprimary' => ['Gmagick', 'x'=>'float', 'y'=>'float'],
'Gmagick::setimagebordercolor' => ['Gmagick', 'color'=>'gmagickpixel'],
'Gmagick::setimagechanneldepth' => ['Gmagick', 'channel'=>'int', 'depth'=>'int'],
'Gmagick::setimagecolorspace' => ['Gmagick', 'colorspace'=>'int'],
'Gmagick::setimagecompose' => ['Gmagick', 'composite'=>'int'],
'Gmagick::setimagedelay' => ['Gmagick', 'delay'=>'int'],
'Gmagick::setimagedepth' => ['Gmagick', 'depth'=>'int'],
'Gmagick::setimagedispose' => ['Gmagick', 'disposetype'=>'int'],
'Gmagick::setimagefilename' => ['Gmagick', 'filename'=>'string'],
'Gmagick::setimageformat' => ['Gmagick', 'imageformat'=>'string'],
'Gmagick::setimagegamma' => ['Gmagick', 'gamma'=>'float'],
'Gmagick::setimagegreenprimary' => ['Gmagick', 'x'=>'float', 'y'=>'float'],
'Gmagick::setimageindex' => ['Gmagick', 'index'=>'int'],
'Gmagick::setimageinterlacescheme' => ['Gmagick', 'interlace'=>'int'],
'Gmagick::setimageiterations' => ['Gmagick', 'iterations'=>'int'],
'Gmagick::setimageprofile' => ['Gmagick', 'name'=>'string', 'profile'=>'string'],
'Gmagick::setimageredprimary' => ['Gmagick', 'x'=>'float', 'y'=>'float'],
'Gmagick::setimagerenderingintent' => ['Gmagick', 'rendering_intent'=>'int'],
'Gmagick::setimageresolution' => ['Gmagick', 'xresolution'=>'float', 'yresolution'=>'float'],
'Gmagick::setimagescene' => ['Gmagick', 'scene'=>'int'],
'Gmagick::setimagetype' => ['Gmagick', 'imgtype'=>'int'],
'Gmagick::setimageunits' => ['Gmagick', 'resolution'=>'int'],
'Gmagick::setimagewhitepoint' => ['Gmagick', 'x'=>'float', 'y'=>'float'],
'Gmagick::setsamplingfactors' => ['Gmagick', 'factors'=>'array'],
'Gmagick::setsize' => ['Gmagick', 'columns'=>'int', 'rows'=>'int'],
'Gmagick::shearimage' => ['Gmagick', 'color'=>'mixed', 'xshear'=>'float', 'yshear'=>'float'],
'Gmagick::solarizeimage' => ['Gmagick', 'threshold'=>'int'],
'Gmagick::spreadimage' => ['Gmagick', 'radius'=>'float'],
'Gmagick::stripimage' => ['Gmagick'],
'Gmagick::swirlimage' => ['Gmagick', 'degrees'=>'float'],
'Gmagick::thumbnailimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'fit='=>'bool'],
'Gmagick::trimimage' => ['Gmagick', 'fuzz'=>'float'],
'Gmagick::write' => ['Gmagick', 'filename'=>'string'],
'Gmagick::writeimage' => ['Gmagick', 'filename'=>'string', 'all_frames='=>'bool'],
'GmagickDraw::annotate' => ['GmagickDraw', 'x'=>'float', 'y'=>'float', 'text'=>'string'],
'GmagickDraw::arc' => ['GmagickDraw', 'sx'=>'float', 'sy'=>'float', 'ex'=>'float', 'ey'=>'float', 'sd'=>'float', 'ed'=>'float'],
'GmagickDraw::bezier' => ['GmagickDraw', 'coordinate_array'=>'array'],
'GmagickDraw::ellipse' => ['GmagickDraw', 'ox'=>'float', 'oy'=>'float', 'rx'=>'float', 'ry'=>'float', 'start'=>'float', 'end'=>'float'],
'GmagickDraw::getfillcolor' => ['GmagickPixel'],
'GmagickDraw::getfillopacity' => ['float'],
'GmagickDraw::getfont' => ['string|false'],
'GmagickDraw::getfontsize' => ['float'],
'GmagickDraw::getfontstyle' => ['int'],
'GmagickDraw::getfontweight' => ['int'],
'GmagickDraw::getstrokecolor' => ['GmagickPixel'],
'GmagickDraw::getstrokeopacity' => ['float'],
'GmagickDraw::getstrokewidth' => ['float'],
'GmagickDraw::gettextdecoration' => ['int'],
'GmagickDraw::gettextencoding' => ['string|false'],
'GmagickDraw::line' => ['GmagickDraw', 'sx'=>'float', 'sy'=>'float', 'ex'=>'float', 'ey'=>'float'],
'GmagickDraw::point' => ['GmagickDraw', 'x'=>'float', 'y'=>'float'],
'GmagickDraw::polygon' => ['GmagickDraw', 'coordinates'=>'array'],
'GmagickDraw::polyline' => ['GmagickDraw', 'coordinate_array'=>'array'],
'GmagickDraw::rectangle' => ['GmagickDraw', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float'],
'GmagickDraw::rotate' => ['GmagickDraw', 'degrees'=>'float'],
'GmagickDraw::roundrectangle' => ['GmagickDraw', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'rx'=>'float', 'ry'=>'float'],
'GmagickDraw::scale' => ['GmagickDraw', 'x'=>'float', 'y'=>'float'],
'GmagickDraw::setfillcolor' => ['GmagickDraw', 'color'=>'string'],
'GmagickDraw::setfillopacity' => ['GmagickDraw', 'fill_opacity'=>'float'],
'GmagickDraw::setfont' => ['GmagickDraw', 'font'=>'string'],
'GmagickDraw::setfontsize' => ['GmagickDraw', 'pointsize'=>'float'],
'GmagickDraw::setfontstyle' => ['GmagickDraw', 'style'=>'int'],
'GmagickDraw::setfontweight' => ['GmagickDraw', 'weight'=>'int'],
'GmagickDraw::setstrokecolor' => ['GmagickDraw', 'color'=>'gmagickpixel'],
'GmagickDraw::setstrokeopacity' => ['GmagickDraw', 'stroke_opacity'=>'float'],
'GmagickDraw::setstrokewidth' => ['GmagickDraw', 'width'=>'float'],
'GmagickDraw::settextdecoration' => ['GmagickDraw', 'decoration'=>'int'],
'GmagickDraw::settextencoding' => ['GmagickDraw', 'encoding'=>'string'],
'GmagickPixel::__construct' => ['void', 'color='=>'string'],
'GmagickPixel::getcolor' => ['mixed', 'as_array='=>'bool', 'normalize_array='=>'bool'],
'GmagickPixel::getcolorcount' => ['int'],
'GmagickPixel::getcolorvalue' => ['float', 'color'=>'int'],
'GmagickPixel::setcolor' => ['GmagickPixel', 'color'=>'string'],
'GmagickPixel::setcolorvalue' => ['GmagickPixel', 'color'=>'int', 'value'=>'float'],
'gmdate' => ['string', 'format'=>'string', 'timestamp='=>'int|null'],
'gmmktime' => ['int|false', 'hour'=>'int', 'minute='=>'int|null', 'second='=>'int|null', 'month='=>'int|null', 'day='=>'int|null', 'year='=>'int|null'],
'GMP::__construct' => ['void'],
'GMP::__toString' => ['numeric-string'],
'GMP::serialize' => ['string'],
'GMP::unserialize' => ['void', 'serialized'=>'string'],
'gmp_abs' => ['GMP', 'num'=>'GMP|string|int'],
'gmp_add' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_and' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_binomial' => ['GMP', 'n'=>'GMP|string|int', 'k'=>'int'],
'gmp_clrbit' => ['void', 'num'=>'GMP|string|int', 'index'=>'int'],
'gmp_cmp' => ['int', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_com' => ['GMP', 'num'=>'GMP|string|int'],
'gmp_div' => ['GMP', 'num1'=>'GMP|resource|string', 'num2'=>'GMP|resource|string', 'rounding_mode='=>'int'],
'gmp_div_q' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int', 'rounding_mode='=>'int'],
'gmp_div_qr' => ['array{0: GMP, 1: GMP}', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int', 'rounding_mode='=>'int'],
'gmp_div_r' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int', 'rounding_mode='=>'int'],
'gmp_divexact' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_export' => ['string|false', 'num'=>'GMP|string|int', 'word_size='=>'int', 'flags='=>'int'],
'gmp_fact' => ['GMP', 'num'=>'int'],
'gmp_gcd' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_gcdext' => ['array<string,GMP>', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_hamdist' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_import' => ['GMP|false', 'data'=>'string', 'word_size='=>'int', 'flags='=>'int'],
'gmp_init' => ['GMP', 'num'=>'int|string', 'base='=>'int'],
'gmp_intval' => ['int', 'num'=>'GMP|string|int'],
'gmp_invert' => ['GMP|false', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_jacobi' => ['int', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_kronecker' => ['int', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_lcm' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_legendre' => ['int', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_mod' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_mul' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_neg' => ['GMP', 'num'=>'GMP|string|int'],
'gmp_nextprime' => ['GMP', 'num'=>'GMP|string|int'],
'gmp_or' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_perfect_power' => ['bool', 'num'=>'GMP|string|int'],
'gmp_perfect_square' => ['bool', 'num'=>'GMP|string|int'],
'gmp_popcount' => ['int', 'num'=>'GMP|string|int'],
'gmp_pow' => ['GMP', 'num'=>'GMP|string|int', 'exponent'=>'int'],
'gmp_powm' => ['GMP', 'num'=>'GMP|string|int', 'exponent'=>'GMP|string|int', 'modulus'=>'GMP|string|int'],
'gmp_prob_prime' => ['int', 'num'=>'GMP|string|int', 'repetitions='=>'int'],
'gmp_random_bits' => ['GMP', 'bits'=>'int'],
'gmp_random_range' => ['GMP', 'min'=>'GMP|string|int', 'max'=>'GMP|string|int'],
'gmp_random_seed' => ['void', 'seed'=>'GMP|string|int'],
'gmp_root' => ['GMP', 'num'=>'GMP|string|int', 'nth'=>'int'],
'gmp_rootrem' => ['array{0: GMP, 1: GMP}', 'num'=>'GMP|string|int', 'nth'=>'int'],
'gmp_scan0' => ['int', 'num1'=>'GMP|string|int', 'start'=>'int'],
'gmp_scan1' => ['int', 'num1'=>'GMP|string|int', 'start'=>'int'],
'gmp_setbit' => ['void', 'num'=>'GMP|string|int', 'index'=>'int', 'value='=>'bool'],
'gmp_sign' => ['int', 'num'=>'GMP|string|int'],
'gmp_sqrt' => ['GMP', 'num'=>'GMP|string|int'],
'gmp_sqrtrem' => ['array{0: GMP, 1: GMP}', 'num'=>'GMP|string|int'],
'gmp_strval' => ['numeric-string', 'num'=>'GMP|string|int', 'base='=>'int'],
'gmp_sub' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmp_testbit' => ['bool', 'num'=>'GMP|string|int', 'index'=>'int'],
'gmp_xor' => ['GMP', 'num1'=>'GMP|string|int', 'num2'=>'GMP|string|int'],
'gmstrftime' => ['string', 'format'=>'string', 'timestamp='=>'int'],
'gnupg::adddecryptkey' => ['bool', 'fingerprint'=>'string', 'passphrase'=>'string'],
'gnupg::addencryptkey' => ['bool', 'fingerprint'=>'string'],
'gnupg::addsignkey' => ['bool', 'fingerprint'=>'string', 'passphrase='=>'string'],
'gnupg::cleardecryptkeys' => ['bool'],
'gnupg::clearencryptkeys' => ['bool'],
'gnupg::clearsignkeys' => ['bool'],
'gnupg::decrypt' => ['string|false', 'text'=>'string'],
'gnupg::decryptverify' => ['array|false', 'text'=>'string', '&plaintext'=>'string'],
'gnupg::encrypt' => ['string|false', 'plaintext'=>'string'],
'gnupg::encryptsign' => ['string|false', 'plaintext'=>'string'],
'gnupg::export' => ['string|false', 'fingerprint'=>'string'],
'gnupg::geterror' => ['string|false'],
'gnupg::getprotocol' => ['int'],
'gnupg::import' => ['array|false', 'keydata'=>'string'],
'gnupg::init' => ['resource'],
'gnupg::keyinfo' => ['array', 'pattern'=>'string'],
'gnupg::setarmor' => ['bool', 'armor'=>'int'],
'gnupg::seterrormode' => ['void', 'errormode'=>'int'],
'gnupg::setsignmode' => ['bool', 'signmode'=>'int'],
'gnupg::sign' => ['string|false', 'plaintext'=>'string'],
'gnupg::verify' => ['array|false', 'signed_text'=>'string', 'signature'=>'string', '&plaintext='=>'string'],
'gnupg_adddecryptkey' => ['bool', 'identifier'=>'resource', 'fingerprint'=>'string', 'passphrase'=>'string'],
'gnupg_addencryptkey' => ['bool', 'identifier'=>'resource', 'fingerprint'=>'string'],
'gnupg_addsignkey' => ['bool', 'identifier'=>'resource', 'fingerprint'=>'string', 'passphrase='=>'string'],
'gnupg_cleardecryptkeys' => ['bool', 'identifier'=>'resource'],
'gnupg_clearencryptkeys' => ['bool', 'identifier'=>'resource'],
'gnupg_clearsignkeys' => ['bool', 'identifier'=>'resource'],
'gnupg_decrypt' => ['string', 'identifier'=>'resource', 'text'=>'string'],
'gnupg_decryptverify' => ['array', 'identifier'=>'resource', 'text'=>'string', 'plaintext'=>'string'],
'gnupg_encrypt' => ['string', 'identifier'=>'resource', 'plaintext'=>'string'],
'gnupg_encryptsign' => ['string', 'identifier'=>'resource', 'plaintext'=>'string'],
'gnupg_export' => ['string', 'identifier'=>'resource', 'fingerprint'=>'string'],
'gnupg_geterror' => ['string', 'identifier'=>'resource'],
'gnupg_getprotocol' => ['int', 'identifier'=>'resource'],
'gnupg_import' => ['array', 'identifier'=>'resource', 'keydata'=>'string'],
'gnupg_init' => ['resource'],
'gnupg_keyinfo' => ['array', 'identifier'=>'resource', 'pattern'=>'string'],
'gnupg_setarmor' => ['bool', 'identifier'=>'resource', 'armor'=>'int'],
'gnupg_seterrormode' => ['void', 'identifier'=>'resource', 'errormode'=>'int'],
'gnupg_setsignmode' => ['bool', 'identifier'=>'resource', 'signmode'=>'int'],
'gnupg_sign' => ['string', 'identifier'=>'resource', 'plaintext'=>'string'],
'gnupg_verify' => ['array', 'identifier'=>'resource', 'signed_text'=>'string', 'signature'=>'string', 'plaintext='=>'string'],
'gopher_parsedir' => ['array', 'dirent'=>'string'],
'grapheme_extract' => ['string|false', 'haystack'=>'string', 'size'=>'int', 'type='=>'int', 'offset='=>'int', '&w_next='=>'int'],
'grapheme_stripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'grapheme_stristr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'beforeNeedle='=>'bool'],
'grapheme_strlen' => ['int|false|null', 'string'=>'string'],
'grapheme_strpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'grapheme_strripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'grapheme_strrpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'grapheme_strstr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'beforeNeedle='=>'bool'],
'grapheme_substr' => ['string|false', 'string'=>'string', 'offset'=>'int', 'length='=>'int'],
'gregoriantojd' => ['int', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'gridObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'Grpc\Call::__construct' => ['void', 'channel'=>'Grpc\Channel', 'method'=>'string', 'absolute_deadline'=>'Grpc\Timeval', 'host_override='=>'mixed'],
'Grpc\Call::cancel' => [''],
'Grpc\Call::getPeer' => ['string'],
'Grpc\Call::setCredentials' => ['int', 'creds_obj'=>'Grpc\CallCredentials'],
'Grpc\Call::startBatch' => ['object', 'batch'=>'array'],
'Grpc\CallCredentials::createComposite' => ['Grpc\CallCredentials', 'cred1'=>'Grpc\CallCredentials', 'cred2'=>'Grpc\CallCredentials'],
'Grpc\CallCredentials::createFromPlugin' => ['Grpc\CallCredentials', 'callback'=>'Closure'],
'Grpc\Channel::__construct' => ['void', 'target'=>'string', 'args='=>'array'],
'Grpc\Channel::close' => [''],
'Grpc\Channel::getConnectivityState' => ['int', 'try_to_connect='=>'bool'],
'Grpc\Channel::getTarget' => ['string'],
'Grpc\Channel::watchConnectivityState' => ['bool', 'last_state'=>'int', 'deadline_obj'=>'Grpc\Timeval'],
'Grpc\ChannelCredentials::createComposite' => ['Grpc\ChannelCredentials', 'cred1'=>'Grpc\ChannelCredentials', 'cred2'=>'Grpc\CallCredentials'],
'Grpc\ChannelCredentials::createDefault' => ['Grpc\ChannelCredentials'],
'Grpc\ChannelCredentials::createInsecure' => ['null'],
'Grpc\ChannelCredentials::createSsl' => ['Grpc\ChannelCredentials', 'pem_root_certs'=>'string', 'pem_private_key='=>'string', 'pem_cert_chain='=>'string'],
'Grpc\ChannelCredentials::setDefaultRootsPem' => ['', 'pem_roots'=>'string'],
'Grpc\Server::__construct' => ['void', 'args'=>'array'],
'Grpc\Server::addHttp2Port' => ['bool', 'addr'=>'string'],
'Grpc\Server::addSecureHttp2Port' => ['bool', 'addr'=>'string', 'creds_obj'=>'Grpc\ServerCredentials'],
'Grpc\Server::requestCall' => ['', 'tag_new'=>'int', 'tag_cancel'=>'int'],
'Grpc\Server::start' => [''],
'Grpc\ServerCredentials::createSsl' => ['object', 'pem_root_certs'=>'string', 'pem_private_key'=>'string', 'pem_cert_chain'=>'string'],
'Grpc\Timeval::__construct' => ['void', 'usec'=>'int'],
'Grpc\Timeval::add' => ['Grpc\Timeval', 'other'=>'Grpc\Timeval'],
'Grpc\Timeval::compare' => ['int', 'a'=>'Grpc\Timeval', 'b'=>'Grpc\Timeval'],
'Grpc\Timeval::infFuture' => ['Grpc\Timeval'],
'Grpc\Timeval::infPast' => ['Grpc\Timeval'],
'Grpc\Timeval::now' => ['Grpc\Timeval'],
'Grpc\Timeval::similar' => ['bool', 'a'=>'Grpc\Timeval', 'b'=>'Grpc\Timeval', 'threshold'=>'Grpc\Timeval'],
'Grpc\Timeval::sleepUntil' => [''],
'Grpc\Timeval::subtract' => ['Grpc\Timeval', 'other'=>'Grpc\Timeval'],
'Grpc\Timeval::zero' => ['Grpc\Timeval'],
'gupnp_context_get_host_ip' => ['string', 'context'=>'resource'],
'gupnp_context_get_port' => ['int', 'context'=>'resource'],
'gupnp_context_get_subscription_timeout' => ['int', 'context'=>'resource'],
'gupnp_context_host_path' => ['bool', 'context'=>'resource', 'local_path'=>'string', 'server_path'=>'string'],
'gupnp_context_new' => ['resource', 'host_ip='=>'string', 'port='=>'int'],
'gupnp_context_set_subscription_timeout' => ['void', 'context'=>'resource', 'timeout'=>'int'],
'gupnp_context_timeout_add' => ['bool', 'context'=>'resource', 'timeout'=>'int', 'callback'=>'mixed', 'arg='=>'mixed'],
'gupnp_context_unhost_path' => ['bool', 'context'=>'resource', 'server_path'=>'string'],
'gupnp_control_point_browse_start' => ['bool', 'cpoint'=>'resource'],
'gupnp_control_point_browse_stop' => ['bool', 'cpoint'=>'resource'],
'gupnp_control_point_callback_set' => ['bool', 'cpoint'=>'resource', 'signal'=>'int', 'callback'=>'mixed', 'arg='=>'mixed'],
'gupnp_control_point_new' => ['resource', 'context'=>'resource', 'target'=>'string'],
'gupnp_device_action_callback_set' => ['bool', 'root_device'=>'resource', 'signal'=>'int', 'action_name'=>'string', 'callback'=>'mixed', 'arg='=>'mixed'],
'gupnp_device_info_get' => ['array', 'root_device'=>'resource'],
'gupnp_device_info_get_service' => ['resource', 'root_device'=>'resource', 'type'=>'string'],
'gupnp_root_device_get_available' => ['bool', 'root_device'=>'resource'],
'gupnp_root_device_get_relative_location' => ['string', 'root_device'=>'resource'],
'gupnp_root_device_new' => ['resource', 'context'=>'resource', 'location'=>'string', 'description_dir'=>'string'],
'gupnp_root_device_set_available' => ['bool', 'root_device'=>'resource', 'available'=>'bool'],
'gupnp_root_device_start' => ['bool', 'root_device'=>'resource'],
'gupnp_root_device_stop' => ['bool', 'root_device'=>'resource'],
'gupnp_service_action_get' => ['mixed', 'action'=>'resource', 'name'=>'string', 'type'=>'int'],
'gupnp_service_action_return' => ['bool', 'action'=>'resource'],
'gupnp_service_action_return_error' => ['bool', 'action'=>'resource', 'error_code'=>'int', 'error_description='=>'string'],
'gupnp_service_action_set' => ['bool', 'action'=>'resource', 'name'=>'string', 'type'=>'int', 'value'=>'mixed'],
'gupnp_service_freeze_notify' => ['bool', 'service'=>'resource'],
'gupnp_service_info_get' => ['array', 'proxy'=>'resource'],
'gupnp_service_info_get_introspection' => ['mixed', 'proxy'=>'resource', 'callback='=>'mixed', 'arg='=>'mixed'],
'gupnp_service_introspection_get_state_variable' => ['array', 'introspection'=>'resource', 'variable_name'=>'string'],
'gupnp_service_notify' => ['bool', 'service'=>'resource', 'name'=>'string', 'type'=>'int', 'value'=>'mixed'],
'gupnp_service_proxy_action_get' => ['mixed', 'proxy'=>'resource', 'action'=>'string', 'name'=>'string', 'type'=>'int'],
'gupnp_service_proxy_action_set' => ['bool', 'proxy'=>'resource', 'action'=>'string', 'name'=>'string', 'value'=>'mixed', 'type'=>'int'],
'gupnp_service_proxy_add_notify' => ['bool', 'proxy'=>'resource', 'value'=>'string', 'type'=>'int', 'callback'=>'mixed', 'arg='=>'mixed'],
'gupnp_service_proxy_callback_set' => ['bool', 'proxy'=>'resource', 'signal'=>'int', 'callback'=>'mixed', 'arg='=>'mixed'],
'gupnp_service_proxy_get_subscribed' => ['bool', 'proxy'=>'resource'],
'gupnp_service_proxy_remove_notify' => ['bool', 'proxy'=>'resource', 'value'=>'string'],
'gupnp_service_proxy_send_action' => ['array', 'proxy'=>'resource', 'action'=>'string', 'in_params'=>'array', 'out_params'=>'array'],
'gupnp_service_proxy_set_subscribed' => ['bool', 'proxy'=>'resource', 'subscribed'=>'bool'],
'gupnp_service_thaw_notify' => ['bool', 'service'=>'resource'],
'gzclose' => ['bool', 'stream'=>'resource'],
'gzcompress' => ['string|false', 'data'=>'string', 'level='=>'int', 'encoding='=>'int'],
'gzdecode' => ['string|false', 'data'=>'string', 'max_length='=>'int'],
'gzdeflate' => ['string|false', 'data'=>'string', 'level='=>'int', 'encoding='=>'int'],
'gzencode' => ['string|false', 'data'=>'string', 'level='=>'int', 'encoding='=>'int'],
'gzeof' => ['bool|int', 'stream'=>'resource'],
'gzfile' => ['list<string>', 'filename'=>'string', 'use_include_path='=>'int'],
'gzgetc' => ['string|false', 'stream'=>'resource'],
'gzgets' => ['string|false', 'stream'=>'resource', 'length='=>'int'],
'gzinflate' => ['string|false', 'data'=>'string', 'max_length='=>'int'],
'gzopen' => ['resource|false', 'filename'=>'string', 'mode'=>'string', 'use_include_path='=>'int'],
'gzpassthru' => ['int|false', 'stream'=>'resource'],
'gzputs' => ['int', 'stream'=>'resource', 'data'=>'string', 'length='=>'int'],
'gzread' => ['string|false', 'stream'=>'resource', 'length'=>'int'],
'gzrewind' => ['bool', 'stream'=>'resource'],
'gzseek' => ['int', 'stream'=>'resource', 'offset'=>'int', 'whence='=>'int'],
'gztell' => ['int|false', 'stream'=>'resource'],
'gzuncompress' => ['string|false', 'data'=>'string', 'max_length='=>'int'],
'gzwrite' => ['int', 'stream'=>'resource', 'data'=>'string', 'length='=>'int'],
'HaruAnnotation::setBorderStyle' => ['bool', 'width'=>'float', 'dash_on'=>'int', 'dash_off'=>'int'],
'HaruAnnotation::setHighlightMode' => ['bool', 'mode'=>'int'],
'HaruAnnotation::setIcon' => ['bool', 'icon'=>'int'],
'HaruAnnotation::setOpened' => ['bool', 'opened'=>'bool'],
'HaruDestination::setFit' => ['bool'],
'HaruDestination::setFitB' => ['bool'],
'HaruDestination::setFitBH' => ['bool', 'top'=>'float'],
'HaruDestination::setFitBV' => ['bool', 'left'=>'float'],
'HaruDestination::setFitH' => ['bool', 'top'=>'float'],
'HaruDestination::setFitR' => ['bool', 'left'=>'float', 'bottom'=>'float', 'right'=>'float', 'top'=>'float'],
'HaruDestination::setFitV' => ['bool', 'left'=>'float'],
'HaruDestination::setXYZ' => ['bool', 'left'=>'float', 'top'=>'float', 'zoom'=>'float'],
'HaruDoc::__construct' => ['void'],
'HaruDoc::addPage' => ['object'],
'HaruDoc::addPageLabel' => ['bool', 'first_page'=>'int', 'style'=>'int', 'first_num'=>'int', 'prefix='=>'string'],
'HaruDoc::createOutline' => ['object', 'title'=>'string', 'parent_outline='=>'object', 'encoder='=>'object'],
'HaruDoc::getCurrentEncoder' => ['object'],
'HaruDoc::getCurrentPage' => ['object'],
'HaruDoc::getEncoder' => ['object', 'encoding'=>'string'],
'HaruDoc::getFont' => ['object', 'fontname'=>'string', 'encoding='=>'string'],
'HaruDoc::getInfoAttr' => ['string', 'type'=>'int'],
'HaruDoc::getPageLayout' => ['int'],
'HaruDoc::getPageMode' => ['int'],
'HaruDoc::getStreamSize' => ['int'],
'HaruDoc::insertPage' => ['object', 'page'=>'object'],
'HaruDoc::loadJPEG' => ['object', 'filename'=>'string'],
'HaruDoc::loadPNG' => ['object', 'filename'=>'string', 'deferred='=>'bool'],
'HaruDoc::loadRaw' => ['object', 'filename'=>'string', 'width'=>'int', 'height'=>'int', 'color_space'=>'int'],
'HaruDoc::loadTTC' => ['string', 'fontfile'=>'string', 'index'=>'int', 'embed='=>'bool'],
'HaruDoc::loadTTF' => ['string', 'fontfile'=>'string', 'embed='=>'bool'],
'HaruDoc::loadType1' => ['string', 'afmfile'=>'string', 'pfmfile='=>'string'],
'HaruDoc::output' => ['bool'],
'HaruDoc::readFromStream' => ['string', 'bytes'=>'int'],
'HaruDoc::resetError' => ['bool'],
'HaruDoc::resetStream' => ['bool'],
'HaruDoc::save' => ['bool', 'file'=>'string'],
'HaruDoc::saveToStream' => ['bool'],
'HaruDoc::setCompressionMode' => ['bool', 'mode'=>'int'],
'HaruDoc::setCurrentEncoder' => ['bool', 'encoding'=>'string'],
'HaruDoc::setEncryptionMode' => ['bool', 'mode'=>'int', 'key_len='=>'int'],
'HaruDoc::setInfoAttr' => ['bool', 'type'=>'int', 'info'=>'string'],
'HaruDoc::setInfoDateAttr' => ['bool', 'type'=>'int', 'year'=>'int', 'month'=>'int', 'day'=>'int', 'hour'=>'int', 'min'=>'int', 'sec'=>'int', 'ind'=>'string', 'off_hour'=>'int', 'off_min'=>'int'],
'HaruDoc::setOpenAction' => ['bool', 'destination'=>'object'],
'HaruDoc::setPageLayout' => ['bool', 'layout'=>'int'],
'HaruDoc::setPageMode' => ['bool', 'mode'=>'int'],
'HaruDoc::setPagesConfiguration' => ['bool', 'page_per_pages'=>'int'],
'HaruDoc::setPassword' => ['bool', 'owner_password'=>'string', 'user_password'=>'string'],
'HaruDoc::setPermission' => ['bool', 'permission'=>'int'],
'HaruDoc::useCNSEncodings' => ['bool'],
'HaruDoc::useCNSFonts' => ['bool'],
'HaruDoc::useCNTEncodings' => ['bool'],
'HaruDoc::useCNTFonts' => ['bool'],
'HaruDoc::useJPEncodings' => ['bool'],
'HaruDoc::useJPFonts' => ['bool'],
'HaruDoc::useKREncodings' => ['bool'],
'HaruDoc::useKRFonts' => ['bool'],
'HaruEncoder::getByteType' => ['int', 'text'=>'string', 'index'=>'int'],
'HaruEncoder::getType' => ['int'],
'HaruEncoder::getUnicode' => ['int', 'character'=>'int'],
'HaruEncoder::getWritingMode' => ['int'],
'HaruFont::getAscent' => ['int'],
'HaruFont::getCapHeight' => ['int'],
'HaruFont::getDescent' => ['int'],
'HaruFont::getEncodingName' => ['string'],
'HaruFont::getFontName' => ['string'],
'HaruFont::getTextWidth' => ['array', 'text'=>'string'],
'HaruFont::getUnicodeWidth' => ['int', 'character'=>'int'],
'HaruFont::getXHeight' => ['int'],
'HaruFont::measureText' => ['int', 'text'=>'string', 'width'=>'float', 'font_size'=>'float', 'char_space'=>'float', 'word_space'=>'float', 'word_wrap='=>'bool'],
'HaruImage::getBitsPerComponent' => ['int'],
'HaruImage::getColorSpace' => ['string'],
'HaruImage::getHeight' => ['int'],
'HaruImage::getSize' => ['array'],
'HaruImage::getWidth' => ['int'],
'HaruImage::setColorMask' => ['bool', 'rmin'=>'int', 'rmax'=>'int', 'gmin'=>'int', 'gmax'=>'int', 'bmin'=>'int', 'bmax'=>'int'],
'HaruImage::setMaskImage' => ['bool', 'mask_image'=>'object'],
'HaruOutline::setDestination' => ['bool', 'destination'=>'object'],
'HaruOutline::setOpened' => ['bool', 'opened'=>'bool'],
'HaruPage::arc' => ['bool', 'x'=>'float', 'y'=>'float', 'ray'=>'float', 'ang1'=>'float', 'ang2'=>'float'],
'HaruPage::beginText' => ['bool'],
'HaruPage::circle' => ['bool', 'x'=>'float', 'y'=>'float', 'ray'=>'float'],
'HaruPage::closePath' => ['bool'],
'HaruPage::concat' => ['bool', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'x'=>'float', 'y'=>'float'],
'HaruPage::createDestination' => ['object'],
'HaruPage::createLinkAnnotation' => ['object', 'rectangle'=>'array', 'destination'=>'object'],
'HaruPage::createTextAnnotation' => ['object', 'rectangle'=>'array', 'text'=>'string', 'encoder='=>'object'],
'HaruPage::createURLAnnotation' => ['object', 'rectangle'=>'array', 'url'=>'string'],
'HaruPage::curveTo' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'HaruPage::curveTo2' => ['bool', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'HaruPage::curveTo3' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x3'=>'float', 'y3'=>'float'],
'HaruPage::drawImage' => ['bool', 'image'=>'object', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'HaruPage::ellipse' => ['bool', 'x'=>'float', 'y'=>'float', 'xray'=>'float', 'yray'=>'float'],
'HaruPage::endPath' => ['bool'],
'HaruPage::endText' => ['bool'],
'HaruPage::eofill' => ['bool'],
'HaruPage::eoFillStroke' => ['bool', 'close_path='=>'bool'],
'HaruPage::fill' => ['bool'],
'HaruPage::fillStroke' => ['bool', 'close_path='=>'bool'],
'HaruPage::getCharSpace' => ['float'],
'HaruPage::getCMYKFill' => ['array'],
'HaruPage::getCMYKStroke' => ['array'],
'HaruPage::getCurrentFont' => ['object'],
'HaruPage::getCurrentFontSize' => ['float'],
'HaruPage::getCurrentPos' => ['array'],
'HaruPage::getCurrentTextPos' => ['array'],
'HaruPage::getDash' => ['array'],
'HaruPage::getFillingColorSpace' => ['int'],
'HaruPage::getFlatness' => ['float'],
'HaruPage::getGMode' => ['int'],
'HaruPage::getGrayFill' => ['float'],
'HaruPage::getGrayStroke' => ['float'],
'HaruPage::getHeight' => ['float'],
'HaruPage::getHorizontalScaling' => ['float'],
'HaruPage::getLineCap' => ['int'],
'HaruPage::getLineJoin' => ['int'],
'HaruPage::getLineWidth' => ['float'],
'HaruPage::getMiterLimit' => ['float'],
'HaruPage::getRGBFill' => ['array'],
'HaruPage::getRGBStroke' => ['array'],
'HaruPage::getStrokingColorSpace' => ['int'],
'HaruPage::getTextLeading' => ['float'],
'HaruPage::getTextMatrix' => ['array'],
'HaruPage::getTextRenderingMode' => ['int'],
'HaruPage::getTextRise' => ['float'],
'HaruPage::getTextWidth' => ['float', 'text'=>'string'],
'HaruPage::getTransMatrix' => ['array'],
'HaruPage::getWidth' => ['float'],
'HaruPage::getWordSpace' => ['float'],
'HaruPage::lineTo' => ['bool', 'x'=>'float', 'y'=>'float'],
'HaruPage::measureText' => ['int', 'text'=>'string', 'width'=>'float', 'wordwrap='=>'bool'],
'HaruPage::moveTextPos' => ['bool', 'x'=>'float', 'y'=>'float', 'set_leading='=>'bool'],
'HaruPage::moveTo' => ['bool', 'x'=>'float', 'y'=>'float'],
'HaruPage::moveToNextLine' => ['bool'],
'HaruPage::rectangle' => ['bool', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'HaruPage::setCharSpace' => ['bool', 'char_space'=>'float'],
'HaruPage::setCMYKFill' => ['bool', 'c'=>'float', 'm'=>'float', 'y'=>'float', 'k'=>'float'],
'HaruPage::setCMYKStroke' => ['bool', 'c'=>'float', 'm'=>'float', 'y'=>'float', 'k'=>'float'],
'HaruPage::setDash' => ['bool', 'pattern'=>'array', 'phase'=>'int'],
'HaruPage::setFlatness' => ['bool', 'flatness'=>'float'],
'HaruPage::setFontAndSize' => ['bool', 'font'=>'object', 'size'=>'float'],
'HaruPage::setGrayFill' => ['bool', 'value'=>'float'],
'HaruPage::setGrayStroke' => ['bool', 'value'=>'float'],
'HaruPage::setHeight' => ['bool', 'height'=>'float'],
'HaruPage::setHorizontalScaling' => ['bool', 'scaling'=>'float'],
'HaruPage::setLineCap' => ['bool', 'cap'=>'int'],
'HaruPage::setLineJoin' => ['bool', 'join'=>'int'],
'HaruPage::setLineWidth' => ['bool', 'width'=>'float'],
'HaruPage::setMiterLimit' => ['bool', 'limit'=>'float'],
'HaruPage::setRGBFill' => ['bool', 'r'=>'float', 'g'=>'float', 'b'=>'float'],
'HaruPage::setRGBStroke' => ['bool', 'r'=>'float', 'g'=>'float', 'b'=>'float'],
'HaruPage::setRotate' => ['bool', 'angle'=>'int'],
'HaruPage::setSize' => ['bool', 'size'=>'int', 'direction'=>'int'],
'HaruPage::setSlideShow' => ['bool', 'type'=>'int', 'disp_time'=>'float', 'trans_time'=>'float'],
'HaruPage::setTextLeading' => ['bool', 'text_leading'=>'float'],
'HaruPage::setTextMatrix' => ['bool', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'x'=>'float', 'y'=>'float'],
'HaruPage::setTextRenderingMode' => ['bool', 'mode'=>'int'],
'HaruPage::setTextRise' => ['bool', 'rise'=>'float'],
'HaruPage::setWidth' => ['bool', 'width'=>'float'],
'HaruPage::setWordSpace' => ['bool', 'word_space'=>'float'],
'HaruPage::showText' => ['bool', 'text'=>'string'],
'HaruPage::showTextNextLine' => ['bool', 'text'=>'string', 'word_space='=>'float', 'char_space='=>'float'],
'HaruPage::stroke' => ['bool', 'close_path='=>'bool'],
'HaruPage::textOut' => ['bool', 'x'=>'float', 'y'=>'float', 'text'=>'string'],
'HaruPage::textRect' => ['bool', 'left'=>'float', 'top'=>'float', 'right'=>'float', 'bottom'=>'float', 'text'=>'string', 'align='=>'int'],
'hash' => ['string|false', 'algo'=>'string', 'data'=>'string', 'binary='=>'bool', 'options='=>'array'],
'hash_algos' => ['list<string>'],
'hash_copy' => ['HashContext', 'context'=>'HashContext'],
'hash_equals' => ['bool', 'known_string'=>'string', 'user_string'=>'string'],
'hash_file' => ['string|false', 'algo'=>'string', 'filename'=>'string', 'binary='=>'bool', 'options='=>'array'],
'hash_final' => ['string', 'context'=>'HashContext', 'binary='=>'bool'],
'hash_hkdf' => ['string|false', 'algo'=>'string', 'key'=>'string', 'length='=>'int', 'info='=>'string', 'salt='=>'string'],
'hash_hmac' => ['string|false', 'algo'=>'string', 'data'=>'string', 'key'=>'string', 'binary='=>'bool'],
'hash_hmac_algos' => ['list<string>'],
'hash_hmac_file' => ['string|false', 'algo'=>'string', 'data'=>'string', 'key'=>'string', 'binary='=>'bool'],
'hash_init' => ['HashContext', 'algo'=>'string', 'flags='=>'int', 'key='=>'string', 'options='=>'array'],
'hash_pbkdf2' => ['string', 'algo'=>'string', 'password'=>'string', 'salt'=>'string', 'iterations'=>'int', 'length='=>'int', 'binary='=>'bool'],
'hash_update' => ['bool', 'context'=>'HashContext', 'data'=>'string'],
'hash_update_file' => ['bool', 'context'=>'HashContext', 'filename'=>'string', 'stream_context='=>'?resource'],
'hash_update_stream' => ['int', 'context'=>'HashContext', 'stream'=>'resource', 'length='=>'int'],
'hashTableObj::clear' => ['void'],
'hashTableObj::get' => ['string', 'key'=>'string'],
'hashTableObj::nextkey' => ['string', 'previousKey'=>'string'],
'hashTableObj::remove' => ['int', 'key'=>'string'],
'hashTableObj::set' => ['int', 'key'=>'string', 'value'=>'string'],
'header' => ['void', 'header'=>'string', 'replace='=>'bool', 'response_code='=>'int'],
'header_register_callback' => ['bool', 'callback'=>'callable():void'],
'header_remove' => ['void', 'name='=>'string'],
'headers_list' => ['list<string>'],
'headers_sent' => ['bool', '&w_filename='=>'string', '&w_line='=>'int'],
'hebrev' => ['string', 'string'=>'string', 'max_chars_per_line='=>'int'],
'hebrevc' => ['string', 'string'=>'string', 'max_chars_per_line='=>'int'],
'hex2bin' => ['string|false', 'string'=>'string'],
'hexdec' => ['int|float', 'hex_string'=>'string'],
'highlight_file' => ['string|bool', 'filename'=>'string', 'return='=>'bool'],
'highlight_string' => ['string|bool', 'string'=>'string', 'return='=>'bool'],
'hrtime' => ['array{0:int,1:int}|false', 'as_number='=>'false'],
'hrtime\'1' => ['int|float|false', 'as_number='=>'true'],
'HRTime\PerformanceCounter::getElapsedTicks' => ['int'],
'HRTime\PerformanceCounter::getFrequency' => ['int'],
'HRTime\PerformanceCounter::getLastElapsedTicks' => ['int'],
'HRTime\PerformanceCounter::getTicks' => ['int'],
'HRTime\PerformanceCounter::getTicksSince' => ['int', 'start'=>'int'],
'HRTime\PerformanceCounter::isRunning' => ['bool'],
'HRTime\PerformanceCounter::start' => ['void'],
'HRTime\PerformanceCounter::stop' => ['void'],
'HRTime\StopWatch::getElapsedTicks' => ['int'],
'HRTime\StopWatch::getElapsedTime' => ['float', 'unit='=>'int'],
'HRTime\StopWatch::getLastElapsedTicks' => ['int'],
'HRTime\StopWatch::getLastElapsedTime' => ['float', 'unit='=>'int'],
'HRTime\StopWatch::isRunning' => ['bool'],
'HRTime\StopWatch::start' => ['void'],
'HRTime\StopWatch::stop' => ['void'],
'html_entity_decode' => ['string', 'string'=>'string', 'flags='=>'int', 'encoding='=>'string'],
'htmlentities' => ['string', 'string'=>'string', 'flags='=>'int', 'encoding='=>'string', 'double_encode='=>'bool'],
'htmlspecialchars' => ['string', 'string'=>'string', 'flags='=>'int', 'encoding='=>'string|null', 'double_encode='=>'bool'],
'htmlspecialchars_decode' => ['string', 'string'=>'string', 'flags='=>'int'],
'http\Client::__construct' => ['void', 'driver='=>'string', 'persistent_handle_id='=>'string'],
'http\Client::addCookies' => ['http\Client', 'cookies='=>'?array'],
'http\Client::addSslOptions' => ['http\Client', 'ssl_options='=>'?array'],
'http\Client::attach' => ['void', 'observer'=>'SplObserver'],
'http\Client::configure' => ['http\Client', 'settings'=>'array'],
'http\Client::count' => ['int'],
'http\Client::dequeue' => ['http\Client', 'request'=>'http\Client\Request'],
'http\Client::detach' => ['void', 'observer'=>'SplObserver'],
'http\Client::enableEvents' => ['http\Client', 'enable='=>'mixed'],
'http\Client::enablePipelining' => ['http\Client', 'enable='=>'mixed'],
'http\Client::enqueue' => ['http\Client', 'request'=>'http\Client\Request', 'callable='=>'mixed'],
'http\Client::getAvailableConfiguration' => ['array'],
'http\Client::getAvailableDrivers' => ['array'],
'http\Client::getAvailableOptions' => ['array'],
'http\Client::getCookies' => ['array'],
'http\Client::getHistory' => ['http\Message'],
'http\Client::getObservers' => ['SplObjectStorage'],
'http\Client::getOptions' => ['array'],
'http\Client::getProgressInfo' => ['null|object', 'request'=>'http\Client\Request'],
'http\Client::getResponse' => ['http\Client\Response|null', 'request='=>'?http\Client\Request'],
'http\Client::getSslOptions' => ['array'],
'http\Client::getTransferInfo' => ['object', 'request'=>'http\Client\Request'],
'http\Client::notify' => ['void', 'request='=>'?http\Client\Request'],
'http\Client::once' => ['bool'],
'http\Client::requeue' => ['http\Client', 'request'=>'http\Client\Request', 'callable='=>'mixed'],
'http\Client::reset' => ['http\Client'],
'http\Client::send' => ['http\Client'],
'http\Client::setCookies' => ['http\Client', 'cookies='=>'?array'],
'http\Client::setDebug' => ['http\Client', 'callback'=>'callable'],
'http\Client::setOptions' => ['http\Client', 'options='=>'?array'],
'http\Client::setSslOptions' => ['http\Client', 'ssl_option='=>'?array'],
'http\Client::wait' => ['bool', 'timeout='=>'mixed'],
'http\Client\Curl\User::init' => ['', 'run'=>'callable'],
'http\Client\Curl\User::once' => [''],
'http\Client\Curl\User::send' => [''],
'http\Client\Curl\User::socket' => ['', 'socket'=>'resource', 'action'=>'int'],
'http\Client\Curl\User::timer' => ['', 'timeout_ms'=>'int'],
'http\Client\Curl\User::wait' => ['', 'timeout_ms='=>'mixed'],
'http\Client\Request::__construct' => ['void', 'method='=>'mixed', 'url='=>'mixed', 'headers='=>'?array', 'body='=>'?http\Message\Body'],
'http\Client\Request::__toString' => ['string'],
'http\Client\Request::addBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Client\Request::addHeader' => ['http\Message', 'header'=>'string', 'value'=>'mixed'],
'http\Client\Request::addHeaders' => ['http\Message', 'headers'=>'array', 'append='=>'mixed'],
'http\Client\Request::addQuery' => ['http\Client\Request', 'query_data'=>'mixed'],
'http\Client\Request::addSslOptions' => ['http\Client\Request', 'ssl_options='=>'?array'],
'http\Client\Request::count' => ['int'],
'http\Client\Request::current' => ['mixed'],
'http\Client\Request::detach' => ['http\Message'],
'http\Client\Request::getBody' => ['http\Message\Body'],
'http\Client\Request::getContentType' => ['null|string'],
'http\Client\Request::getHeader' => ['http\Header|mixed', 'header'=>'string', 'into_class='=>'mixed'],
'http\Client\Request::getHeaders' => ['array'],
'http\Client\Request::getHttpVersion' => ['string'],
'http\Client\Request::getInfo' => ['null|string'],
'http\Client\Request::getOptions' => ['array'],
'http\Client\Request::getParentMessage' => ['http\Message'],
'http\Client\Request::getQuery' => ['null|string'],
'http\Client\Request::getRequestMethod' => ['false|string'],
'http\Client\Request::getRequestUrl' => ['false|string'],
'http\Client\Request::getResponseCode' => ['false|int'],
'http\Client\Request::getResponseStatus' => ['false|string'],
'http\Client\Request::getSslOptions' => ['array'],
'http\Client\Request::getType' => ['int'],
'http\Client\Request::isMultipart' => ['bool', '&boundary='=>'mixed'],
'http\Client\Request::key' => ['int|string'],
'http\Client\Request::next' => ['void'],
'http\Client\Request::prepend' => ['http\Message', 'message'=>'http\Message', 'top='=>'mixed'],
'http\Client\Request::reverse' => ['http\Message'],
'http\Client\Request::rewind' => ['void'],
'http\Client\Request::serialize' => ['string'],
'http\Client\Request::setBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Client\Request::setContentType' => ['http\Client\Request', 'content_type'=>'string'],
'http\Client\Request::setHeader' => ['http\Message', 'header'=>'string', 'value='=>'mixed'],
'http\Client\Request::setHeaders' => ['http\Message', 'headers'=>'array'],
'http\Client\Request::setHttpVersion' => ['http\Message', 'http_version'=>'string'],
'http\Client\Request::setInfo' => ['http\Message', 'http_info'=>'string'],
'http\Client\Request::setOptions' => ['http\Client\Request', 'options='=>'?array'],
'http\Client\Request::setQuery' => ['http\Client\Request', 'query_data='=>'mixed'],
'http\Client\Request::setRequestMethod' => ['http\Message', 'request_method'=>'string'],
'http\Client\Request::setRequestUrl' => ['http\Message', 'url'=>'string'],
'http\Client\Request::setResponseCode' => ['http\Message', 'response_code'=>'int', 'strict='=>'mixed'],
'http\Client\Request::setResponseStatus' => ['http\Message', 'response_status'=>'string'],
'http\Client\Request::setSslOptions' => ['http\Client\Request', 'ssl_options='=>'?array'],
'http\Client\Request::setType' => ['http\Message', 'type'=>'int'],
'http\Client\Request::splitMultipartBody' => ['http\Message'],
'http\Client\Request::toCallback' => ['http\Message', 'callback'=>'callable'],
'http\Client\Request::toStream' => ['http\Message', 'stream'=>'resource'],
'http\Client\Request::toString' => ['string', 'include_parent='=>'mixed'],
'http\Client\Request::unserialize' => ['void', 'serialized'=>'string'],
'http\Client\Request::valid' => ['bool'],
'http\Client\Response::__construct' => ['Iterator'],
'http\Client\Response::__toString' => ['string'],
'http\Client\Response::addBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Client\Response::addHeader' => ['http\Message', 'header'=>'string', 'value'=>'mixed'],
'http\Client\Response::addHeaders' => ['http\Message', 'headers'=>'array', 'append='=>'mixed'],
'http\Client\Response::count' => ['int'],
'http\Client\Response::current' => ['mixed'],
'http\Client\Response::detach' => ['http\Message'],
'http\Client\Response::getBody' => ['http\Message\Body'],
'http\Client\Response::getCookies' => ['array', 'flags='=>'mixed', 'allowed_extras='=>'mixed'],
'http\Client\Response::getHeader' => ['http\Header|mixed', 'header'=>'string', 'into_class='=>'mixed'],
'http\Client\Response::getHeaders' => ['array'],
'http\Client\Response::getHttpVersion' => ['string'],
'http\Client\Response::getInfo' => ['null|string'],
'http\Client\Response::getParentMessage' => ['http\Message'],
'http\Client\Response::getRequestMethod' => ['false|string'],
'http\Client\Response::getRequestUrl' => ['false|string'],
'http\Client\Response::getResponseCode' => ['false|int'],
'http\Client\Response::getResponseStatus' => ['false|string'],
'http\Client\Response::getTransferInfo' => ['mixed|object', 'element='=>'mixed'],
'http\Client\Response::getType' => ['int'],
'http\Client\Response::isMultipart' => ['bool', '&boundary='=>'mixed'],
'http\Client\Response::key' => ['int|string'],
'http\Client\Response::next' => ['void'],
'http\Client\Response::prepend' => ['http\Message', 'message'=>'http\Message', 'top='=>'mixed'],
'http\Client\Response::reverse' => ['http\Message'],
'http\Client\Response::rewind' => ['void'],
'http\Client\Response::serialize' => ['string'],
'http\Client\Response::setBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Client\Response::setHeader' => ['http\Message', 'header'=>'string', 'value='=>'mixed'],
'http\Client\Response::setHeaders' => ['http\Message', 'headers'=>'array'],
'http\Client\Response::setHttpVersion' => ['http\Message', 'http_version'=>'string'],
'http\Client\Response::setInfo' => ['http\Message', 'http_info'=>'string'],
'http\Client\Response::setRequestMethod' => ['http\Message', 'request_method'=>'string'],
'http\Client\Response::setRequestUrl' => ['http\Message', 'url'=>'string'],
'http\Client\Response::setResponseCode' => ['http\Message', 'response_code'=>'int', 'strict='=>'mixed'],
'http\Client\Response::setResponseStatus' => ['http\Message', 'response_status'=>'string'],
'http\Client\Response::setType' => ['http\Message', 'type'=>'int'],
'http\Client\Response::splitMultipartBody' => ['http\Message'],
'http\Client\Response::toCallback' => ['http\Message', 'callback'=>'callable'],
'http\Client\Response::toStream' => ['http\Message', 'stream'=>'resource'],
'http\Client\Response::toString' => ['string', 'include_parent='=>'mixed'],
'http\Client\Response::unserialize' => ['void', 'serialized'=>'string'],
'http\Client\Response::valid' => ['bool'],
'http\Cookie::__construct' => ['void', 'cookie_string='=>'mixed', 'parser_flags='=>'int', 'allowed_extras='=>'array'],
'http\Cookie::__toString' => ['string'],
'http\Cookie::addCookie' => ['http\Cookie', 'cookie_name'=>'string', 'cookie_value'=>'string'],
'http\Cookie::addCookies' => ['http\Cookie', 'cookies'=>'array'],
'http\Cookie::addExtra' => ['http\Cookie', 'extra_name'=>'string', 'extra_value'=>'string'],
'http\Cookie::addExtras' => ['http\Cookie', 'extras'=>'array'],
'http\Cookie::getCookie' => ['null|string', 'name'=>'string'],
'http\Cookie::getCookies' => ['array'],
'http\Cookie::getDomain' => ['string'],
'http\Cookie::getExpires' => ['int'],
'http\Cookie::getExtra' => ['string', 'name'=>'string'],
'http\Cookie::getExtras' => ['array'],
'http\Cookie::getFlags' => ['int'],
'http\Cookie::getMaxAge' => ['int'],
'http\Cookie::getPath' => ['string'],
'http\Cookie::setCookie' => ['http\Cookie', 'cookie_name'=>'string', 'cookie_value='=>'mixed'],
'http\Cookie::setCookies' => ['http\Cookie', 'cookies='=>'mixed'],
'http\Cookie::setDomain' => ['http\Cookie', 'value='=>'mixed'],
'http\Cookie::setExpires' => ['http\Cookie', 'value='=>'mixed'],
'http\Cookie::setExtra' => ['http\Cookie', 'extra_name'=>'string', 'extra_value='=>'mixed'],
'http\Cookie::setExtras' => ['http\Cookie', 'extras='=>'mixed'],
'http\Cookie::setFlags' => ['http\Cookie', 'value='=>'mixed'],
'http\Cookie::setMaxAge' => ['http\Cookie', 'value='=>'mixed'],
'http\Cookie::setPath' => ['http\Cookie', 'value='=>'mixed'],
'http\Cookie::toArray' => ['array'],
'http\Cookie::toString' => ['string'],
'http\Encoding\Stream::__construct' => ['void', 'flags='=>'mixed'],
'http\Encoding\Stream::done' => ['bool'],
'http\Encoding\Stream::finish' => ['string'],
'http\Encoding\Stream::flush' => ['string'],
'http\Encoding\Stream::update' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Debrotli::__construct' => ['void', 'flags='=>'int'],
'http\Encoding\Stream\Debrotli::decode' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Debrotli::done' => ['bool'],
'http\Encoding\Stream\Debrotli::finish' => ['string'],
'http\Encoding\Stream\Debrotli::flush' => ['string'],
'http\Encoding\Stream\Debrotli::update' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Dechunk::__construct' => ['void', 'flags='=>'mixed'],
'http\Encoding\Stream\Dechunk::decode' => ['false|string', 'data'=>'string', '&decoded_len='=>'mixed'],
'http\Encoding\Stream\Dechunk::done' => ['bool'],
'http\Encoding\Stream\Dechunk::finish' => ['string'],
'http\Encoding\Stream\Dechunk::flush' => ['string'],
'http\Encoding\Stream\Dechunk::update' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Deflate::__construct' => ['void', 'flags='=>'mixed'],
'http\Encoding\Stream\Deflate::done' => ['bool'],
'http\Encoding\Stream\Deflate::encode' => ['string', 'data'=>'string', 'flags='=>'mixed'],
'http\Encoding\Stream\Deflate::finish' => ['string'],
'http\Encoding\Stream\Deflate::flush' => ['string'],
'http\Encoding\Stream\Deflate::update' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Enbrotli::__construct' => ['void', 'flags='=>'int'],
'http\Encoding\Stream\Enbrotli::done' => ['bool'],
'http\Encoding\Stream\Enbrotli::encode' => ['string', 'data'=>'string', 'flags='=>'int'],
'http\Encoding\Stream\Enbrotli::finish' => ['string'],
'http\Encoding\Stream\Enbrotli::flush' => ['string'],
'http\Encoding\Stream\Enbrotli::update' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Inflate::__construct' => ['void', 'flags='=>'mixed'],
'http\Encoding\Stream\Inflate::decode' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Inflate::done' => ['bool'],
'http\Encoding\Stream\Inflate::finish' => ['string'],
'http\Encoding\Stream\Inflate::flush' => ['string'],
'http\Encoding\Stream\Inflate::update' => ['string', 'data'=>'string'],
'http\Env::getRequestBody' => ['http\Message\Body', 'body_class_name='=>'mixed'],
'http\Env::getRequestHeader' => ['array|null|string', 'header_name='=>'mixed'],
'http\Env::getResponseCode' => ['int'],
'http\Env::getResponseHeader' => ['array|null|string', 'header_name='=>'mixed'],
'http\Env::getResponseStatusForAllCodes' => ['array'],
'http\Env::getResponseStatusForCode' => ['string', 'code'=>'int'],
'http\Env::negotiate' => ['null|string', 'params'=>'string', 'supported'=>'array', 'primary_type_separator='=>'mixed', '&result_array='=>'mixed'],
'http\Env::negotiateCharset' => ['null|string', 'supported'=>'array', '&result_array='=>'mixed'],
'http\Env::negotiateContentType' => ['null|string', 'supported'=>'array', '&result_array='=>'mixed'],
'http\Env::negotiateEncoding' => ['null|string', 'supported'=>'array', '&result_array='=>'mixed'],
'http\Env::negotiateLanguage' => ['null|string', 'supported'=>'array', '&result_array='=>'mixed'],
'http\Env::setResponseCode' => ['bool', 'code'=>'int'],
'http\Env::setResponseHeader' => ['bool', 'header_name'=>'string', 'header_value='=>'mixed', 'response_code='=>'mixed', 'replace_header='=>'mixed'],
'http\Env\Request::__construct' => ['void'],
'http\Env\Request::__toString' => ['string'],
'http\Env\Request::addBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Env\Request::addHeader' => ['http\Message', 'header'=>'string', 'value'=>'mixed'],
'http\Env\Request::addHeaders' => ['http\Message', 'headers'=>'array', 'append='=>'mixed'],
'http\Env\Request::count' => ['int'],
'http\Env\Request::current' => ['mixed'],
'http\Env\Request::detach' => ['http\Message'],
'http\Env\Request::getBody' => ['http\Message\Body'],
'http\Env\Request::getCookie' => ['mixed', 'name='=>'string', 'type='=>'mixed', 'defval='=>'mixed', 'delete='=>'bool'],
'http\Env\Request::getFiles' => ['array'],
'http\Env\Request::getForm' => ['mixed', 'name='=>'string', 'type='=>'mixed', 'defval='=>'mixed', 'delete='=>'bool'],
'http\Env\Request::getHeader' => ['http\Header|mixed', 'header'=>'string', 'into_class='=>'mixed'],
'http\Env\Request::getHeaders' => ['array'],
'http\Env\Request::getHttpVersion' => ['string'],
'http\Env\Request::getInfo' => ['null|string'],
'http\Env\Request::getParentMessage' => ['http\Message'],
'http\Env\Request::getQuery' => ['mixed', 'name='=>'string', 'type='=>'mixed', 'defval='=>'mixed', 'delete='=>'bool'],
'http\Env\Request::getRequestMethod' => ['false|string'],
'http\Env\Request::getRequestUrl' => ['false|string'],
'http\Env\Request::getResponseCode' => ['false|int'],
'http\Env\Request::getResponseStatus' => ['false|string'],
'http\Env\Request::getType' => ['int'],
'http\Env\Request::isMultipart' => ['bool', '&boundary='=>'mixed'],
'http\Env\Request::key' => ['int|string'],
'http\Env\Request::next' => ['void'],
'http\Env\Request::prepend' => ['http\Message', 'message'=>'http\Message', 'top='=>'mixed'],
'http\Env\Request::reverse' => ['http\Message'],
'http\Env\Request::rewind' => ['void'],
'http\Env\Request::serialize' => ['string'],
'http\Env\Request::setBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Env\Request::setHeader' => ['http\Message', 'header'=>'string', 'value='=>'mixed'],
'http\Env\Request::setHeaders' => ['http\Message', 'headers'=>'array'],
'http\Env\Request::setHttpVersion' => ['http\Message', 'http_version'=>'string'],
'http\Env\Request::setInfo' => ['http\Message', 'http_info'=>'string'],
'http\Env\Request::setRequestMethod' => ['http\Message', 'request_method'=>'string'],
'http\Env\Request::setRequestUrl' => ['http\Message', 'url'=>'string'],
'http\Env\Request::setResponseCode' => ['http\Message', 'response_code'=>'int', 'strict='=>'mixed'],
'http\Env\Request::setResponseStatus' => ['http\Message', 'response_status'=>'string'],
'http\Env\Request::setType' => ['http\Message', 'type'=>'int'],
'http\Env\Request::splitMultipartBody' => ['http\Message'],
'http\Env\Request::toCallback' => ['http\Message', 'callback'=>'callable'],
'http\Env\Request::toStream' => ['http\Message', 'stream'=>'resource'],
'http\Env\Request::toString' => ['string', 'include_parent='=>'mixed'],
'http\Env\Request::unserialize' => ['void', 'serialized'=>'string'],
'http\Env\Request::valid' => ['bool'],
'http\Env\Response::__construct' => ['void'],
'http\Env\Response::__invoke' => ['bool', 'data'=>'string', 'ob_flags='=>'int'],
'http\Env\Response::__toString' => ['string'],
'http\Env\Response::addBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Env\Response::addHeader' => ['http\Message', 'header'=>'string', 'value'=>'mixed'],
'http\Env\Response::addHeaders' => ['http\Message', 'headers'=>'array', 'append='=>'mixed'],
'http\Env\Response::count' => ['int'],
'http\Env\Response::current' => ['mixed'],
'http\Env\Response::detach' => ['http\Message'],
'http\Env\Response::getBody' => ['http\Message\Body'],
'http\Env\Response::getHeader' => ['http\Header|mixed', 'header'=>'string', 'into_class='=>'mixed'],
'http\Env\Response::getHeaders' => ['array'],
'http\Env\Response::getHttpVersion' => ['string'],
'http\Env\Response::getInfo' => ['?string'],
'http\Env\Response::getParentMessage' => ['http\Message'],
'http\Env\Response::getRequestMethod' => ['false|string'],
'http\Env\Response::getRequestUrl' => ['false|string'],
'http\Env\Response::getResponseCode' => ['false|int'],
'http\Env\Response::getResponseStatus' => ['false|string'],
'http\Env\Response::getType' => ['int'],
'http\Env\Response::isCachedByETag' => ['int', 'header_name='=>'string'],
'http\Env\Response::isCachedByLastModified' => ['int', 'header_name='=>'string'],
'http\Env\Response::isMultipart' => ['bool', '&boundary='=>'mixed'],
'http\Env\Response::key' => ['int|string'],
'http\Env\Response::next' => ['void'],
'http\Env\Response::prepend' => ['http\Message', 'message'=>'http\Message', 'top='=>'mixed'],
'http\Env\Response::reverse' => ['http\Message'],
'http\Env\Response::rewind' => ['void'],
'http\Env\Response::send' => ['bool', 'stream='=>'resource'],
'http\Env\Response::serialize' => ['string'],
'http\Env\Response::setBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Env\Response::setCacheControl' => ['http\Env\Response', 'cache_control'=>'string'],
'http\Env\Response::setContentDisposition' => ['http\Env\Response', 'disposition_params'=>'array'],
'http\Env\Response::setContentEncoding' => ['http\Env\Response', 'content_encoding'=>'int'],
'http\Env\Response::setContentType' => ['http\Env\Response', 'content_type'=>'string'],
'http\Env\Response::setCookie' => ['http\Env\Response', 'cookie'=>'mixed'],
'http\Env\Response::setEnvRequest' => ['http\Env\Response', 'env_request'=>'http\Message'],
'http\Env\Response::setEtag' => ['http\Env\Response', 'etag'=>'string'],
'http\Env\Response::setHeader' => ['http\Message', 'header'=>'string', 'value='=>'mixed'],
'http\Env\Response::setHeaders' => ['http\Message', 'headers'=>'array'],
'http\Env\Response::setHttpVersion' => ['http\Message', 'http_version'=>'string'],
'http\Env\Response::setInfo' => ['http\Message', 'http_info'=>'string'],
'http\Env\Response::setLastModified' => ['http\Env\Response', 'last_modified'=>'int'],
'http\Env\Response::setRequestMethod' => ['http\Message', 'request_method'=>'string'],
'http\Env\Response::setRequestUrl' => ['http\Message', 'url'=>'string'],
'http\Env\Response::setResponseCode' => ['http\Message', 'response_code'=>'int', 'strict='=>'mixed'],
'http\Env\Response::setResponseStatus' => ['http\Message', 'response_status'=>'string'],
'http\Env\Response::setThrottleRate' => ['http\Env\Response', 'chunk_size'=>'int', 'delay='=>'float|int'],
'http\Env\Response::setType' => ['http\Message', 'type'=>'int'],
'http\Env\Response::splitMultipartBody' => ['http\Message'],
'http\Env\Response::toCallback' => ['http\Message', 'callback'=>'callable'],
'http\Env\Response::toStream' => ['http\Message', 'stream'=>'resource'],
'http\Env\Response::toString' => ['string', 'include_parent='=>'mixed'],
'http\Env\Response::unserialize' => ['void', 'serialized'=>'string'],
'http\Env\Response::valid' => ['bool'],
'http\Header::__construct' => ['void', 'name='=>'mixed', 'value='=>'mixed'],
'http\Header::__toString' => ['string'],
'http\Header::getParams' => ['http\Params', 'param_sep='=>'mixed', 'arg_sep='=>'mixed', 'val_sep='=>'mixed', 'flags='=>'mixed'],
'http\Header::match' => ['bool', 'value'=>'string', 'flags='=>'mixed'],
'http\Header::negotiate' => ['null|string', 'supported'=>'array', '&result='=>'mixed'],
'http\Header::parse' => ['array|false', 'string'=>'string', 'header_class='=>'mixed'],
'http\Header::serialize' => ['string'],
'http\Header::toString' => ['string'],
'http\Header::unserialize' => ['void', 'serialized'=>'string'],
'http\Header\Parser::getState' => ['int'],
'http\Header\Parser::parse' => ['int', 'data'=>'string', 'flags'=>'int', '&headers'=>'array'],
'http\Header\Parser::stream' => ['int', 'stream'=>'resource', 'flags'=>'int', '&headers'=>'array'],
'http\Message::__construct' => ['void', 'message='=>'mixed', 'greedy='=>'bool'],
'http\Message::__toString' => ['string'],
'http\Message::addBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Message::addHeader' => ['http\Message', 'header'=>'string', 'value'=>'mixed'],
'http\Message::addHeaders' => ['http\Message', 'headers'=>'array', 'append='=>'mixed'],
'http\Message::count' => ['int'],
'http\Message::current' => ['mixed'],
'http\Message::detach' => ['http\Message'],
'http\Message::getBody' => ['http\Message\Body'],
'http\Message::getHeader' => ['http\Header|mixed', 'header'=>'string', 'into_class='=>'mixed'],
'http\Message::getHeaders' => ['array'],
'http\Message::getHttpVersion' => ['string'],
'http\Message::getInfo' => ['null|string'],
'http\Message::getParentMessage' => ['http\Message'],
'http\Message::getRequestMethod' => ['false|string'],
'http\Message::getRequestUrl' => ['false|string'],
'http\Message::getResponseCode' => ['false|int'],
'http\Message::getResponseStatus' => ['false|string'],
'http\Message::getType' => ['int'],
'http\Message::isMultipart' => ['bool', '&boundary='=>'mixed'],
'http\Message::key' => ['int|string'],
'http\Message::next' => ['void'],
'http\Message::prepend' => ['http\Message', 'message'=>'http\Message', 'top='=>'mixed'],
'http\Message::reverse' => ['http\Message'],
'http\Message::rewind' => ['void'],
'http\Message::serialize' => ['string'],
'http\Message::setBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Message::setHeader' => ['http\Message', 'header'=>'string', 'value='=>'mixed'],
'http\Message::setHeaders' => ['http\Message', 'headers'=>'array'],
'http\Message::setHttpVersion' => ['http\Message', 'http_version'=>'string'],
'http\Message::setInfo' => ['http\Message', 'http_info'=>'string'],
'http\Message::setRequestMethod' => ['http\Message', 'request_method'=>'string'],
'http\Message::setRequestUrl' => ['http\Message', 'url'=>'string'],
'http\Message::setResponseCode' => ['http\Message', 'response_code'=>'int', 'strict='=>'mixed'],
'http\Message::setResponseStatus' => ['http\Message', 'response_status'=>'string'],
'http\Message::setType' => ['http\Message', 'type'=>'int'],
'http\Message::splitMultipartBody' => ['http\Message'],
'http\Message::toCallback' => ['http\Message', 'callback'=>'callable'],
'http\Message::toStream' => ['http\Message', 'stream'=>'resource'],
'http\Message::toString' => ['string', 'include_parent='=>'mixed'],
'http\Message::unserialize' => ['void', 'serialized'=>'string'],
'http\Message::valid' => ['bool'],
'http\Message\Body::__construct' => ['void', 'stream='=>'resource'],
'http\Message\Body::__toString' => ['string'],
'http\Message\Body::addForm' => ['http\Message\Body', 'fields='=>'?array', 'files='=>'?array'],
'http\Message\Body::addPart' => ['http\Message\Body', 'message'=>'http\Message'],
'http\Message\Body::append' => ['http\Message\Body', 'string'=>'string'],
'http\Message\Body::etag' => ['false|string'],
'http\Message\Body::getBoundary' => ['null|string'],
'http\Message\Body::getResource' => ['resource'],
'http\Message\Body::serialize' => ['string'],
'http\Message\Body::stat' => ['int|object', 'field='=>'mixed'],
'http\Message\Body::toCallback' => ['http\Message\Body', 'callback'=>'callable', 'offset='=>'mixed', 'maxlen='=>'mixed'],
'http\Message\Body::toStream' => ['http\Message\Body', 'stream'=>'resource', 'offset='=>'mixed', 'maxlen='=>'mixed'],
'http\Message\Body::toString' => ['string'],
'http\Message\Body::unserialize' => ['void', 'serialized'=>'string'],
'http\Message\Parser::getState' => ['int'],
'http\Message\Parser::parse' => ['int', 'data'=>'string', 'flags'=>'int', '&message'=>'http\Message'],
'http\Message\Parser::stream' => ['int', 'stream'=>'resource', 'flags'=>'int', '&message'=>'http\Message'],
'http\Params::__construct' => ['void', 'params='=>'mixed', 'param_sep='=>'mixed', 'arg_sep='=>'mixed', 'val_sep='=>'mixed', 'flags='=>'mixed'],
'http\Params::__toString' => ['string'],
'http\Params::offsetExists' => ['bool', 'name'=>'mixed'],
'http\Params::offsetGet' => ['mixed', 'name'=>'mixed'],
'http\Params::offsetSet' => ['void', 'name'=>'mixed', 'value'=>'mixed'],
'http\Params::offsetUnset' => ['void', 'name'=>'mixed'],
'http\Params::toArray' => ['array'],
'http\Params::toString' => ['string'],
'http\QueryString::__construct' => ['void', 'querystring'=>'string'],
'http\QueryString::__toString' => ['string'],
'http\QueryString::get' => ['http\QueryString|string|mixed', 'name='=>'string', 'type='=>'mixed', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getArray' => ['array|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getBool' => ['bool|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getFloat' => ['float|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getGlobalInstance' => ['http\QueryString'],
'http\QueryString::getInt' => ['int|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getIterator' => ['IteratorAggregate'],
'http\QueryString::getObject' => ['object|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getString' => ['string|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::mod' => ['http\QueryString', 'params='=>'mixed'],
'http\QueryString::offsetExists' => ['bool', 'offset'=>'mixed'],
'http\QueryString::offsetGet' => ['mixed|null', 'offset'=>'mixed'],
'http\QueryString::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'http\QueryString::offsetUnset' => ['void', 'offset'=>'mixed'],
'http\QueryString::serialize' => ['string'],
'http\QueryString::set' => ['http\QueryString', 'params'=>'mixed'],
'http\QueryString::toArray' => ['array'],
'http\QueryString::toString' => ['string'],
'http\QueryString::unserialize' => ['void', 'serialized'=>'string'],
'http\QueryString::xlate' => ['http\QueryString'],
'http\Url::__construct' => ['void', 'old_url='=>'mixed', 'new_url='=>'mixed', 'flags='=>'int'],
'http\Url::__toString' => ['string'],
'http\Url::mod' => ['http\Url', 'parts'=>'mixed', 'flags='=>'float|int|mixed'],
'http\Url::toArray' => ['string[]'],
'http\Url::toString' => ['string'],
'http_build_cookie' => ['string', 'cookie'=>'array'],
'http_build_query' => ['string', 'data'=>'array|object', 'numeric_prefix='=>'string', 'arg_separator='=>'string', 'encoding_type='=>'int'],
'http_build_str' => ['string', 'query'=>'array', 'prefix='=>'?string', 'arg_separator='=>'string'],
'http_build_url' => ['string', 'url='=>'string|array', 'parts='=>'string|array', 'flags='=>'int', 'new_url='=>'array'],
'http_cache_etag' => ['bool', 'etag='=>'string'],
'http_cache_last_modified' => ['bool', 'timestamp_or_expires='=>'int'],
'http_chunked_decode' => ['string|false', 'encoded'=>'string'],
'http_date' => ['string', 'timestamp='=>'int'],
'http_deflate' => ['?string', 'data'=>'string', 'flags='=>'int'],
'http_get' => ['string', 'url'=>'string', 'options='=>'array', 'info='=>'array'],
'http_get_request_body' => ['?string'],
'http_get_request_body_stream' => ['?resource'],
'http_get_request_headers' => ['array'],
'http_head' => ['string', 'url'=>'string', 'options='=>'array', 'info='=>'array'],
'http_inflate' => ['?string', 'data'=>'string'],
'http_match_etag' => ['bool', 'etag'=>'string', 'for_range='=>'bool'],
'http_match_modified' => ['bool', 'timestamp='=>'int', 'for_range='=>'bool'],
'http_match_request_header' => ['bool', 'header'=>'string', 'value'=>'string', 'match_case='=>'bool'],
'http_negotiate_charset' => ['string', 'supported'=>'array', 'result='=>'array'],
'http_negotiate_content_type' => ['string', 'supported'=>'array', 'result='=>'array'],
'http_negotiate_language' => ['string', 'supported'=>'array', 'result='=>'array'],
'http_parse_cookie' => ['stdClass|false', 'cookie'=>'string', 'flags='=>'int', 'allowed_extras='=>'array'],
'http_parse_headers' => ['array|false', 'header'=>'string'],
'http_parse_message' => ['object', 'message'=>'string'],
'http_parse_params' => ['stdClass', 'param'=>'string', 'flags='=>'int'],
'http_persistent_handles_clean' => ['string', 'ident='=>'string'],
'http_persistent_handles_count' => ['stdClass|false'],
'http_persistent_handles_ident' => ['string|false', 'ident='=>'string'],
'http_post_data' => ['string', 'url'=>'string', 'data'=>'string', 'options='=>'array', 'info='=>'array'],
'http_post_fields' => ['string', 'url'=>'string', 'data'=>'array', 'files='=>'array', 'options='=>'array', 'info='=>'array'],
'http_put_data' => ['string', 'url'=>'string', 'data'=>'string', 'options='=>'array', 'info='=>'array'],
'http_put_file' => ['string', 'url'=>'string', 'file'=>'string', 'options='=>'array', 'info='=>'array'],
'http_put_stream' => ['string', 'url'=>'string', 'stream'=>'resource', 'options='=>'array', 'info='=>'array'],
'http_redirect' => ['int|false', 'url='=>'string', 'params='=>'array', 'session='=>'bool', 'status='=>'int'],
'http_request' => ['string', 'method'=>'int', 'url'=>'string', 'body='=>'string', 'options='=>'array', 'info='=>'array'],
'http_request_body_encode' => ['string|false', 'fields'=>'array', 'files'=>'array'],
'http_request_method_exists' => ['bool', 'method'=>'mixed'],
'http_request_method_name' => ['string|false', 'method'=>'int'],
'http_request_method_register' => ['int|false', 'method'=>'string'],
'http_request_method_unregister' => ['bool', 'method'=>'mixed'],
'http_response_code' => ['int|bool', 'response_code='=>'int'],
'http_send_content_disposition' => ['bool', 'filename'=>'string', 'inline='=>'bool'],
'http_send_content_type' => ['bool', 'content_type='=>'string'],
'http_send_data' => ['bool', 'data'=>'string'],
'http_send_file' => ['bool', 'file'=>'string'],
'http_send_last_modified' => ['bool', 'timestamp='=>'int'],
'http_send_status' => ['bool', 'status'=>'int'],
'http_send_stream' => ['bool', 'stream'=>'resource'],
'http_support' => ['int', 'feature='=>'int'],
'http_throttle' => ['void', 'sec'=>'float', 'bytes='=>'int'],
'HttpDeflateStream::__construct' => ['void', 'flags='=>'int'],
'HttpDeflateStream::factory' => ['HttpDeflateStream', 'flags='=>'int', 'class_name='=>'string'],
'HttpDeflateStream::finish' => ['string', 'data='=>'string'],
'HttpDeflateStream::flush' => ['string|false', 'data='=>'string'],
'HttpDeflateStream::update' => ['string|false', 'data'=>'string'],
'HttpInflateStream::__construct' => ['void', 'flags='=>'int'],
'HttpInflateStream::factory' => ['HttpInflateStream', 'flags='=>'int', 'class_name='=>'string'],
'HttpInflateStream::finish' => ['string', 'data='=>'string'],
'HttpInflateStream::flush' => ['string|false', 'data='=>'string'],
'HttpInflateStream::update' => ['string|false', 'data'=>'string'],
'HttpMessage::__construct' => ['void', 'message='=>'string'],
'HttpMessage::__toString' => ['string'],
'HttpMessage::addHeaders' => ['void', 'headers'=>'array', 'append='=>'bool'],
'HttpMessage::count' => ['int'],
'HttpMessage::current' => ['mixed'],
'HttpMessage::detach' => ['HttpMessage'],
'HttpMessage::factory' => ['?HttpMessage', 'raw_message='=>'string', 'class_name='=>'string'],
'HttpMessage::fromEnv' => ['?HttpMessage', 'message_type'=>'int', 'class_name='=>'string'],
'HttpMessage::fromString' => ['?HttpMessage', 'raw_message='=>'string', 'class_name='=>'string'],
'HttpMessage::getBody' => ['string'],
'HttpMessage::getHeader' => ['?string', 'header'=>'string'],
'HttpMessage::getHeaders' => ['array'],
'HttpMessage::getHttpVersion' => ['string'],
'HttpMessage::getInfo' => [''],
'HttpMessage::getParentMessage' => ['HttpMessage'],
'HttpMessage::getRequestMethod' => ['string|false'],
'HttpMessage::getRequestUrl' => ['string|false'],
'HttpMessage::getResponseCode' => ['int'],
'HttpMessage::getResponseStatus' => ['string'],
'HttpMessage::getType' => ['int'],
'HttpMessage::guessContentType' => ['string|false', 'magic_file'=>'string', 'magic_mode='=>'int'],
'HttpMessage::key' => ['int|string'],
'HttpMessage::next' => ['void'],
'HttpMessage::prepend' => ['void', 'message'=>'HttpMessage', 'top='=>'bool'],
'HttpMessage::reverse' => ['HttpMessage'],
'HttpMessage::rewind' => ['void'],
'HttpMessage::send' => ['bool'],
'HttpMessage::serialize' => ['string'],
'HttpMessage::setBody' => ['void', 'body'=>'string'],
'HttpMessage::setHeaders' => ['void', 'headers'=>'array'],
'HttpMessage::setHttpVersion' => ['bool', 'version'=>'string'],
'HttpMessage::setInfo' => ['', 'http_info'=>''],
'HttpMessage::setRequestMethod' => ['bool', 'method'=>'string'],
'HttpMessage::setRequestUrl' => ['bool', 'url'=>'string'],
'HttpMessage::setResponseCode' => ['bool', 'code'=>'int'],
'HttpMessage::setResponseStatus' => ['bool', 'status'=>'string'],
'HttpMessage::setType' => ['void', 'type'=>'int'],
'HttpMessage::toMessageTypeObject' => ['HttpRequest|HttpResponse|null'],
'HttpMessage::toString' => ['string', 'include_parent='=>'bool'],
'HttpMessage::unserialize' => ['void', 'serialized'=>'string'],
'HttpMessage::valid' => ['bool'],
'HttpQueryString::__construct' => ['void', 'global='=>'bool', 'add='=>'mixed'],
'HttpQueryString::__toString' => ['string'],
'HttpQueryString::factory' => ['', 'global'=>'', 'params'=>'', 'class_name'=>''],
'HttpQueryString::get' => ['mixed', 'key='=>'string', 'type='=>'mixed', 'defval='=>'mixed', 'delete='=>'bool'],
'HttpQueryString::getArray' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::getBool' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::getFloat' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::getInt' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::getObject' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::getString' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::mod' => ['HttpQueryString', 'params'=>'mixed'],
'HttpQueryString::offsetExists' => ['bool', 'offset'=>'mixed'],
'HttpQueryString::offsetGet' => ['mixed', 'offset'=>'mixed'],
'HttpQueryString::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'HttpQueryString::offsetUnset' => ['void', 'offset'=>'mixed'],
'HttpQueryString::serialize' => ['string'],
'HttpQueryString::set' => ['string', 'params'=>'mixed'],
'HttpQueryString::singleton' => ['HttpQueryString', 'global='=>'bool'],
'HttpQueryString::toArray' => ['array'],
'HttpQueryString::toString' => ['string'],
'HttpQueryString::unserialize' => ['void', 'serialized'=>'string'],
'HttpQueryString::xlate' => ['bool', 'ie'=>'string', 'oe'=>'string'],
'HttpRequest::__construct' => ['void', 'url='=>'string', 'request_method='=>'int', 'options='=>'array'],
'HttpRequest::addBody' => ['', 'request_body_data'=>''],
'HttpRequest::addCookies' => ['bool', 'cookies'=>'array'],
'HttpRequest::addHeaders' => ['bool', 'headers'=>'array'],
'HttpRequest::addPostFields' => ['bool', 'post_data'=>'array'],
'HttpRequest::addPostFile' => ['bool', 'name'=>'string', 'file'=>'string', 'content_type='=>'string'],
'HttpRequest::addPutData' => ['bool', 'put_data'=>'string'],
'HttpRequest::addQueryData' => ['bool', 'query_params'=>'array'],
'HttpRequest::addRawPostData' => ['bool', 'raw_post_data'=>'string'],
'HttpRequest::addSslOptions' => ['bool', 'options'=>'array'],
'HttpRequest::clearHistory' => ['void'],
'HttpRequest::enableCookies' => ['bool'],
'HttpRequest::encodeBody' => ['', 'fields'=>'', 'files'=>''],
'HttpRequest::factory' => ['', 'url'=>'', 'method'=>'', 'options'=>'', 'class_name'=>''],
'HttpRequest::flushCookies' => [''],
'HttpRequest::get' => ['', 'url'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::getBody' => [''],
'HttpRequest::getContentType' => ['string'],
'HttpRequest::getCookies' => ['array'],
'HttpRequest::getHeaders' => ['array'],
'HttpRequest::getHistory' => ['HttpMessage'],
'HttpRequest::getMethod' => ['int'],
'HttpRequest::getOptions' => ['array'],
'HttpRequest::getPostFields' => ['array'],
'HttpRequest::getPostFiles' => ['array'],
'HttpRequest::getPutData' => ['string'],
'HttpRequest::getPutFile' => ['string'],
'HttpRequest::getQueryData' => ['string'],
'HttpRequest::getRawPostData' => ['string'],
'HttpRequest::getRawRequestMessage' => ['string'],
'HttpRequest::getRawResponseMessage' => ['string'],
'HttpRequest::getRequestMessage' => ['HttpMessage'],
'HttpRequest::getResponseBody' => ['string'],
'HttpRequest::getResponseCode' => ['int'],
'HttpRequest::getResponseCookies' => ['stdClass[]', 'flags='=>'int', 'allowed_extras='=>'array'],
'HttpRequest::getResponseData' => ['array'],
'HttpRequest::getResponseHeader' => ['mixed', 'name='=>'string'],
'HttpRequest::getResponseInfo' => ['mixed', 'name='=>'string'],
'HttpRequest::getResponseMessage' => ['HttpMessage'],
'HttpRequest::getResponseStatus' => ['string'],
'HttpRequest::getSslOptions' => ['array'],
'HttpRequest::getUrl' => ['string'],
'HttpRequest::head' => ['', 'url'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::methodExists' => ['', 'method'=>''],
'HttpRequest::methodName' => ['', 'method_id'=>''],
'HttpRequest::methodRegister' => ['', 'method_name'=>''],
'HttpRequest::methodUnregister' => ['', 'method'=>''],
'HttpRequest::postData' => ['', 'url'=>'', 'data'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::postFields' => ['', 'url'=>'', 'data'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::putData' => ['', 'url'=>'', 'data'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::putFile' => ['', 'url'=>'', 'file'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::putStream' => ['', 'url'=>'', 'stream'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::resetCookies' => ['bool', 'session_only='=>'bool'],
'HttpRequest::send' => ['HttpMessage'],
'HttpRequest::setBody' => ['bool', 'request_body_data='=>'string'],
'HttpRequest::setContentType' => ['bool', 'content_type'=>'string'],
'HttpRequest::setCookies' => ['bool', 'cookies='=>'array'],
'HttpRequest::setHeaders' => ['bool', 'headers='=>'array'],
'HttpRequest::setMethod' => ['bool', 'request_method'=>'int'],
'HttpRequest::setOptions' => ['bool', 'options='=>'array'],
'HttpRequest::setPostFields' => ['bool', 'post_data'=>'array'],
'HttpRequest::setPostFiles' => ['bool', 'post_files'=>'array'],
'HttpRequest::setPutData' => ['bool', 'put_data='=>'string'],
'HttpRequest::setPutFile' => ['bool', 'file='=>'string'],
'HttpRequest::setQueryData' => ['bool', 'query_data'=>'mixed'],
'HttpRequest::setRawPostData' => ['bool', 'raw_post_data='=>'string'],
'HttpRequest::setSslOptions' => ['bool', 'options='=>'array'],
'HttpRequest::setUrl' => ['bool', 'url'=>'string'],
'HttpRequestDataShare::__construct' => ['void'],
'HttpRequestDataShare::__destruct' => ['void'],
'HttpRequestDataShare::attach' => ['', 'request'=>'HttpRequest'],
'HttpRequestDataShare::count' => ['int'],
'HttpRequestDataShare::detach' => ['', 'request'=>'HttpRequest'],
'HttpRequestDataShare::factory' => ['', 'global'=>'', 'class_name'=>''],
'HttpRequestDataShare::reset' => [''],
'HttpRequestDataShare::singleton' => ['', 'global'=>''],
'HttpRequestPool::__construct' => ['void', 'request='=>'HttpRequest'],
'HttpRequestPool::__destruct' => ['void'],
'HttpRequestPool::attach' => ['bool', 'request'=>'HttpRequest'],
'HttpRequestPool::count' => ['int'],
'HttpRequestPool::current' => ['mixed'],
'HttpRequestPool::detach' => ['bool', 'request'=>'HttpRequest'],
'HttpRequestPool::enableEvents' => ['', 'enable'=>''],
'HttpRequestPool::enablePipelining' => ['', 'enable'=>''],
'HttpRequestPool::getAttachedRequests' => ['array'],
'HttpRequestPool::getFinishedRequests' => ['array'],
'HttpRequestPool::key' => ['int|string'],
'HttpRequestPool::next' => ['void'],
'HttpRequestPool::reset' => ['void'],
'HttpRequestPool::rewind' => ['void'],
'HttpRequestPool::send' => ['bool'],
'HttpRequestPool::socketPerform' => ['bool'],
'HttpRequestPool::socketSelect' => ['bool', 'timeout='=>'float'],
'HttpRequestPool::valid' => ['bool'],
'HttpResponse::capture' => ['void'],
'HttpResponse::getBufferSize' => ['int'],
'HttpResponse::getCache' => ['bool'],
'HttpResponse::getCacheControl' => ['string'],
'HttpResponse::getContentDisposition' => ['string'],
'HttpResponse::getContentType' => ['string'],
'HttpResponse::getData' => ['string'],
'HttpResponse::getETag' => ['string'],
'HttpResponse::getFile' => ['string'],
'HttpResponse::getGzip' => ['bool'],
'HttpResponse::getHeader' => ['mixed', 'name='=>'string'],
'HttpResponse::getLastModified' => ['int'],
'HttpResponse::getRequestBody' => ['string'],
'HttpResponse::getRequestBodyStream' => ['resource'],
'HttpResponse::getRequestHeaders' => ['array'],
'HttpResponse::getStream' => ['resource'],
'HttpResponse::getThrottleDelay' => ['float'],
'HttpResponse::guessContentType' => ['string|false', 'magic_file'=>'string', 'magic_mode='=>'int'],
'HttpResponse::redirect' => ['void', 'url='=>'string', 'params='=>'array', 'session='=>'bool', 'status='=>'int'],
'HttpResponse::send' => ['bool', 'clean_ob='=>'bool'],
'HttpResponse::setBufferSize' => ['bool', 'bytes'=>'int'],
'HttpResponse::setCache' => ['bool', 'cache'=>'bool'],
'HttpResponse::setCacheControl' => ['bool', 'control'=>'string', 'max_age='=>'int', 'must_revalidate='=>'bool'],
'HttpResponse::setContentDisposition' => ['bool', 'filename'=>'string', 'inline='=>'bool'],
'HttpResponse::setContentType' => ['bool', 'content_type'=>'string'],
'HttpResponse::setData' => ['bool', 'data'=>'mixed'],
'HttpResponse::setETag' => ['bool', 'etag'=>'string'],
'HttpResponse::setFile' => ['bool', 'file'=>'string'],
'HttpResponse::setGzip' => ['bool', 'gzip'=>'bool'],
'HttpResponse::setHeader' => ['bool', 'name'=>'string', 'value='=>'mixed', 'replace='=>'bool'],
'HttpResponse::setLastModified' => ['bool', 'timestamp'=>'int'],
'HttpResponse::setStream' => ['bool', 'stream'=>'resource'],
'HttpResponse::setThrottleDelay' => ['bool', 'seconds'=>'float'],
'HttpResponse::status' => ['bool', 'status'=>'int'],
'HttpUtil::buildCookie' => ['', 'cookie_array'=>''],
'HttpUtil::buildStr' => ['', 'query'=>'', 'prefix'=>'', 'arg_sep'=>''],
'HttpUtil::buildUrl' => ['', 'url'=>'', 'parts'=>'', 'flags'=>'', '&composed'=>''],
'HttpUtil::chunkedDecode' => ['', 'encoded_string'=>''],
'HttpUtil::date' => ['', 'timestamp'=>''],
'HttpUtil::deflate' => ['', 'plain'=>'', 'flags'=>''],
'HttpUtil::inflate' => ['', 'encoded'=>''],
'HttpUtil::matchEtag' => ['', 'plain_etag'=>'', 'for_range'=>''],
'HttpUtil::matchModified' => ['', 'last_modified'=>'', 'for_range'=>''],
'HttpUtil::matchRequestHeader' => ['', 'header_name'=>'', 'header_value'=>'', 'case_sensitive'=>''],
'HttpUtil::negotiateCharset' => ['', 'supported'=>'', '&result'=>''],
'HttpUtil::negotiateContentType' => ['', 'supported'=>'', '&result'=>''],
'HttpUtil::negotiateLanguage' => ['', 'supported'=>'', '&result'=>''],
'HttpUtil::parseCookie' => ['', 'cookie_string'=>''],
'HttpUtil::parseHeaders' => ['', 'headers_string'=>''],
'HttpUtil::parseMessage' => ['', 'message_string'=>''],
'HttpUtil::parseParams' => ['', 'param_string'=>'', 'flags'=>''],
'HttpUtil::support' => ['', 'feature'=>''],
'hw_api::checkin' => ['bool', 'parameter'=>'array'],
'hw_api::checkout' => ['bool', 'parameter'=>'array'],
'hw_api::children' => ['array', 'parameter'=>'array'],
'hw_api::content' => ['HW_API_Content', 'parameter'=>'array'],
'hw_api::copy' => ['hw_api_content', 'parameter'=>'array'],
'hw_api::dbstat' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::dcstat' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::dstanchors' => ['array', 'parameter'=>'array'],
'hw_api::dstofsrcanchor' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::find' => ['array', 'parameter'=>'array'],
'hw_api::ftstat' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::hwstat' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::identify' => ['bool', 'parameter'=>'array'],
'hw_api::info' => ['array', 'parameter'=>'array'],
'hw_api::insert' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::insertanchor' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::insertcollection' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::insertdocument' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::link' => ['bool', 'parameter'=>'array'],
'hw_api::lock' => ['bool', 'parameter'=>'array'],
'hw_api::move' => ['bool', 'parameter'=>'array'],
'hw_api::object' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::objectbyanchor' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::parents' => ['array', 'parameter'=>'array'],
'hw_api::remove' => ['bool', 'parameter'=>'array'],
'hw_api::replace' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::setcommittedversion' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::srcanchors' => ['array', 'parameter'=>'array'],
'hw_api::srcsofdst' => ['array', 'parameter'=>'array'],
'hw_api::unlock' => ['bool', 'parameter'=>'array'],
'hw_api::user' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::userlist' => ['array', 'parameter'=>'array'],
'hw_api_attribute' => ['HW_API_Attribute', 'name='=>'string', 'value='=>'string'],
'hw_api_attribute::key' => ['string'],
'hw_api_attribute::langdepvalue' => ['string', 'language'=>'string'],
'hw_api_attribute::value' => ['string'],
'hw_api_attribute::values' => ['array'],
'hw_api_content' => ['HW_API_Content', 'content'=>'string', 'mimetype'=>'string'],
'hw_api_content::mimetype' => ['string'],
'hw_api_content::read' => ['string', 'buffer'=>'string', 'length'=>'int'],
'hw_api_error::count' => ['int'],
'hw_api_error::reason' => ['HW_API_Reason'],
'hw_api_object' => ['hw_api_object', 'parameter'=>'array'],
'hw_api_object::assign' => ['bool', 'parameter'=>'array'],
'hw_api_object::attreditable' => ['bool', 'parameter'=>'array'],
'hw_api_object::count' => ['int', 'parameter'=>'array'],
'hw_api_object::insert' => ['bool', 'attribute'=>'hw_api_attribute'],
'hw_api_object::remove' => ['bool', 'name'=>'string'],
'hw_api_object::title' => ['string', 'parameter'=>'array'],
'hw_api_object::value' => ['string', 'name'=>'string'],
'hw_api_reason::description' => ['string'],
'hw_api_reason::type' => ['HW_API_Reason'],
'hw_Array2Objrec' => ['string', 'object_array'=>'array'],
'hw_changeobject' => ['bool', 'link'=>'int', 'objid'=>'int', 'attributes'=>'array'],
'hw_Children' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_ChildrenObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_Close' => ['bool', 'connection'=>'int'],
'hw_Connect' => ['int', 'host'=>'string', 'port'=>'int', 'username='=>'string', 'password='=>'string'],
'hw_connection_info' => ['', 'link'=>'int'],
'hw_cp' => ['int', 'connection'=>'int', 'object_id_array'=>'array', 'destination_id'=>'int'],
'hw_Deleteobject' => ['bool', 'connection'=>'int', 'object_to_delete'=>'int'],
'hw_DocByAnchor' => ['int', 'connection'=>'int', 'anchorid'=>'int'],
'hw_DocByAnchorObj' => ['string', 'connection'=>'int', 'anchorid'=>'int'],
'hw_Document_Attributes' => ['string', 'hw_document'=>'int'],
'hw_Document_BodyTag' => ['string', 'hw_document'=>'int', 'prefix='=>'string'],
'hw_Document_Content' => ['string', 'hw_document'=>'int'],
'hw_Document_SetContent' => ['bool', 'hw_document'=>'int', 'content'=>'string'],
'hw_Document_Size' => ['int', 'hw_document'=>'int'],
'hw_dummy' => ['string', 'link'=>'int', 'id'=>'int', 'msgid'=>'int'],
'hw_EditText' => ['bool', 'connection'=>'int', 'hw_document'=>'int'],
'hw_Error' => ['int', 'connection'=>'int'],
'hw_ErrorMsg' => ['string', 'connection'=>'int'],
'hw_Free_Document' => ['bool', 'hw_document'=>'int'],
'hw_GetAnchors' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetAnchorsObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetAndLock' => ['string', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetChildColl' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetChildCollObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetChildDocColl' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetChildDocCollObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetObject' => ['', 'connection'=>'int', 'objectid'=>'', 'query='=>'string'],
'hw_GetObjectByQuery' => ['array', 'connection'=>'int', 'query'=>'string', 'max_hits'=>'int'],
'hw_GetObjectByQueryColl' => ['array', 'connection'=>'int', 'objectid'=>'int', 'query'=>'string', 'max_hits'=>'int'],
'hw_GetObjectByQueryCollObj' => ['array', 'connection'=>'int', 'objectid'=>'int', 'query'=>'string', 'max_hits'=>'int'],
'hw_GetObjectByQueryObj' => ['array', 'connection'=>'int', 'query'=>'string', 'max_hits'=>'int'],
'hw_GetParents' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetParentsObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_getrellink' => ['string', 'link'=>'int', 'rootid'=>'int', 'sourceid'=>'int', 'destid'=>'int'],
'hw_GetRemote' => ['int', 'connection'=>'int', 'objectid'=>'int'],
'hw_getremotechildren' => ['', 'connection'=>'int', 'object_record'=>'string'],
'hw_GetSrcByDestObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetText' => ['int', 'connection'=>'int', 'objectid'=>'int', 'prefix='=>''],
'hw_getusername' => ['string', 'connection'=>'int'],
'hw_Identify' => ['string', 'link'=>'int', 'username'=>'string', 'password'=>'string'],
'hw_InCollections' => ['array', 'connection'=>'int', 'object_id_array'=>'array', 'collection_id_array'=>'array', 'return_collections'=>'int'],
'hw_Info' => ['string', 'connection'=>'int'],
'hw_InsColl' => ['int', 'connection'=>'int', 'objectid'=>'int', 'object_array'=>'array'],
'hw_InsDoc' => ['int', 'connection'=>'', 'parentid'=>'int', 'object_record'=>'string', 'text='=>'string'],
'hw_insertanchors' => ['bool', 'hwdoc'=>'int', 'anchorecs'=>'array', 'dest'=>'array', 'urlprefixes='=>'array'],
'hw_InsertDocument' => ['int', 'connection'=>'int', 'parent_id'=>'int', 'hw_document'=>'int'],
'hw_InsertObject' => ['int', 'connection'=>'int', 'object_rec'=>'string', 'parameter'=>'string'],
'hw_mapid' => ['int', 'connection'=>'int', 'server_id'=>'int', 'object_id'=>'int'],
'hw_Modifyobject' => ['bool', 'connection'=>'int', 'object_to_change'=>'int', 'remove'=>'array', 'add'=>'array', 'mode='=>'int'],
'hw_mv' => ['int', 'connection'=>'int', 'object_id_array'=>'array', 'source_id'=>'int', 'destination_id'=>'int'],
'hw_New_Document' => ['int', 'object_record'=>'string', 'document_data'=>'string', 'document_size'=>'int'],
'hw_objrec2array' => ['array', 'object_record'=>'string', 'format='=>'array'],
'hw_Output_Document' => ['bool', 'hw_document'=>'int'],
'hw_pConnect' => ['int', 'host'=>'string', 'port'=>'int', 'username='=>'string', 'password='=>'string'],
'hw_PipeDocument' => ['int', 'connection'=>'int', 'objectid'=>'int', 'url_prefixes='=>'array'],
'hw_Root' => ['int'],
'hw_setlinkroot' => ['int', 'link'=>'int', 'rootid'=>'int'],
'hw_stat' => ['string', 'link'=>'int'],
'hw_Unlock' => ['bool', 'connection'=>'int', 'objectid'=>'int'],
'hw_Who' => ['array', 'connection'=>'int'],
'hwapi_attribute_new' => ['HW_API_Attribute', 'name='=>'string', 'value='=>'string'],
'hwapi_content_new' => ['HW_API_Content', 'content'=>'string', 'mimetype'=>'string'],
'hwapi_hgcsp' => ['HW_API', 'hostname'=>'string', 'port='=>'int'],
'hwapi_object_new' => ['hw_api_object', 'parameter'=>'array'],
'hypot' => ['float', 'x'=>'float', 'y'=>'float'],
'ibase_add_user' => ['bool', 'service_handle'=>'resource', 'user_name'=>'string', 'password'=>'string', 'first_name='=>'string', 'middle_name='=>'string', 'last_name='=>'string'],
'ibase_affected_rows' => ['int', 'link_identifier='=>'resource'],
'ibase_backup' => ['mixed', 'service_handle'=>'resource', 'source_db'=>'string', 'dest_file'=>'string', 'options='=>'int', 'verbose='=>'bool'],
'ibase_blob_add' => ['void', 'blob_handle'=>'resource', 'data'=>'string'],
'ibase_blob_cancel' => ['bool', 'blob_handle'=>'resource'],
'ibase_blob_close' => ['string|bool', 'blob_handle'=>'resource'],
'ibase_blob_create' => ['resource', 'link_identifier='=>'resource'],
'ibase_blob_echo' => ['bool', 'link_identifier'=>'', 'blob_id'=>'string'],
'ibase_blob_echo\'1' => ['bool', 'blob_id'=>'string'],
'ibase_blob_get' => ['string|false', 'blob_handle'=>'resource', 'length'=>'int'],
'ibase_blob_import' => ['string|false', 'link_identifier'=>'resource', 'file_handle'=>'resource'],
'ibase_blob_info' => ['array', 'link_identifier'=>'resource', 'blob_id'=>'string'],
'ibase_blob_info\'1' => ['array', 'blob_id'=>'string'],
'ibase_blob_open' => ['resource|false', 'link_identifier'=>'', 'blob_id'=>'string'],
'ibase_blob_open\'1' => ['resource', 'blob_id'=>'string'],
'ibase_close' => ['bool', 'link_identifier='=>'resource'],
'ibase_commit' => ['bool', 'link_identifier='=>'resource'],
'ibase_commit_ret' => ['bool', 'link_identifier='=>'resource'],
'ibase_connect' => ['resource|false', 'database='=>'string', 'username='=>'string', 'password='=>'string', 'charset='=>'string', 'buffers='=>'int', 'dialect='=>'int', 'role='=>'string'],
'ibase_db_info' => ['string', 'service_handle'=>'resource', 'db'=>'string', 'action'=>'int', 'argument='=>'int'],
'ibase_delete_user' => ['bool', 'service_handle'=>'resource', 'user_name'=>'string', 'password='=>'string', 'first_name='=>'string', 'middle_name='=>'string', 'last_name='=>'string'],
'ibase_drop_db' => ['bool', 'link_identifier='=>'resource'],
'ibase_errcode' => ['int|false'],
'ibase_errmsg' => ['string|false'],
'ibase_execute' => ['resource|false', 'query'=>'resource', 'bind_arg='=>'mixed', '...args='=>'mixed'],
'ibase_fetch_assoc' => ['array|false', 'result'=>'resource', 'fetch_flags='=>'int'],
'ibase_fetch_object' => ['object|false', 'result'=>'resource', 'fetch_flags='=>'int'],
'ibase_fetch_row' => ['array|false', 'result'=>'resource', 'fetch_flags='=>'int'],
'ibase_field_info' => ['array', 'query_result'=>'resource', 'field_number'=>'int'],
'ibase_free_event_handler' => ['bool', 'event'=>'resource'],
'ibase_free_query' => ['bool', 'query'=>'resource'],
'ibase_free_result' => ['bool', 'result'=>'resource'],
'ibase_gen_id' => ['int|string', 'generator'=>'string', 'increment='=>'int', 'link_identifier='=>'resource'],
'ibase_maintain_db' => ['bool', 'service_handle'=>'resource', 'db'=>'string', 'action'=>'int', 'argument='=>'int'],
'ibase_modify_user' => ['bool', 'service_handle'=>'resource', 'user_name'=>'string', 'password'=>'string', 'first_name='=>'string', 'middle_name='=>'string', 'last_name='=>'string'],
'ibase_name_result' => ['bool', 'result'=>'resource', 'name'=>'string'],
'ibase_num_fields' => ['int', 'query_result'=>'resource'],
'ibase_num_params' => ['int', 'query'=>'resource'],
'ibase_num_rows' => ['int', 'result_identifier'=>''],
'ibase_param_info' => ['array', 'query'=>'resource', 'field_number'=>'int'],
'ibase_pconnect' => ['resource|false', 'database='=>'string', 'username='=>'string', 'password='=>'string', 'charset='=>'string', 'buffers='=>'int', 'dialect='=>'int', 'role='=>'string'],
'ibase_prepare' => ['resource|false', 'link_identifier'=>'', 'query'=>'string', 'trans_identifier'=>''],
'ibase_query' => ['resource|false', 'link_identifier='=>'resource', 'string='=>'string', 'bind_arg='=>'int', '...args='=>''],
'ibase_restore' => ['mixed', 'service_handle'=>'resource', 'source_file'=>'string', 'dest_db'=>'string', 'options='=>'int', 'verbose='=>'bool'],
'ibase_rollback' => ['bool', 'link_identifier='=>'resource'],
'ibase_rollback_ret' => ['bool', 'link_identifier='=>'resource'],
'ibase_server_info' => ['string', 'service_handle'=>'resource', 'action'=>'int'],
'ibase_service_attach' => ['resource', 'host'=>'string', 'dba_username'=>'string', 'dba_password'=>'string'],
'ibase_service_detach' => ['bool', 'service_handle'=>'resource'],
'ibase_set_event_handler' => ['resource', 'link_identifier'=>'', 'callback'=>'callable', 'event='=>'string', '...args='=>''],
'ibase_set_event_handler\'1' => ['resource', 'callback'=>'callable', 'event'=>'string', '...args'=>''],
'ibase_timefmt' => ['bool', 'format'=>'string', 'columntype='=>'int'],
'ibase_trans' => ['resource|false', 'trans_args='=>'int', 'link_identifier='=>'', '...args='=>''],
'ibase_wait_event' => ['string', 'link_identifier'=>'', 'event='=>'string', '...args='=>''],
'ibase_wait_event\'1' => ['string', 'event'=>'string', '...args'=>''],
'iconv' => ['string|false', 'from_encoding'=>'string', 'to_encoding'=>'string', 'string'=>'string'],
'iconv_get_encoding' => ['mixed', 'type='=>'string'],
'iconv_mime_decode' => ['string|false', 'string'=>'string', 'mode='=>'int', 'encoding='=>'string'],
'iconv_mime_decode_headers' => ['array|false', 'headers'=>'string', 'mode='=>'int', 'encoding='=>'string'],
'iconv_mime_encode' => ['string|false', 'field_name'=>'string', 'field_value'=>'string', 'options='=>'array'],
'iconv_set_encoding' => ['bool', 'type'=>'string', 'encoding'=>'string'],
'iconv_strlen' => ['int|false', 'string'=>'string', 'encoding='=>'string'],
'iconv_strpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string'],
'iconv_strrpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'encoding='=>'string'],
'iconv_substr' => ['string|false', 'string'=>'string', 'offset'=>'int', 'length='=>'int', 'encoding='=>'string'],
'id3_get_frame_long_name' => ['string', 'frameid'=>'string'],
'id3_get_frame_short_name' => ['string', 'frameid'=>'string'],
'id3_get_genre_id' => ['int', 'genre'=>'string'],
'id3_get_genre_list' => ['array'],
'id3_get_genre_name' => ['string', 'genre_id'=>'int'],
'id3_get_tag' => ['array', 'filename'=>'string', 'version='=>'int'],
'id3_get_version' => ['int', 'filename'=>'string'],
'id3_remove_tag' => ['bool', 'filename'=>'string', 'version='=>'int'],
'id3_set_tag' => ['bool', 'filename'=>'string', 'tag'=>'array', 'version='=>'int'],
'idate' => ['int', 'format'=>'string', 'timestamp='=>'int'],
'idn_strerror' => ['string', 'errorcode'=>'int'],
'idn_to_ascii' => ['string|false', 'domain'=>'string', 'flags='=>'int', 'variant='=>'int', '&w_idna_info='=>'array'],
'idn_to_utf8' => ['string|false', 'domain'=>'string', 'flags='=>'int', 'variant='=>'int', '&w_idna_info='=>'array'],
'ifx_affected_rows' => ['int', 'result_id'=>'resource'],
'ifx_blobinfile_mode' => ['bool', 'mode'=>'int'],
'ifx_byteasvarchar' => ['bool', 'mode'=>'int'],
'ifx_close' => ['bool', 'link_identifier='=>'resource'],
'ifx_connect' => ['resource', 'database='=>'string', 'userid='=>'string', 'password='=>'string'],
'ifx_copy_blob' => ['int', 'bid'=>'int'],
'ifx_create_blob' => ['int', 'type'=>'int', 'mode'=>'int', 'param'=>'string'],
'ifx_create_char' => ['int', 'param'=>'string'],
'ifx_do' => ['bool', 'result_id'=>'resource'],
'ifx_error' => ['string', 'link_identifier='=>'resource'],
'ifx_errormsg' => ['string', 'errorcode='=>'int'],
'ifx_fetch_row' => ['array', 'result_id'=>'resource', 'position='=>'mixed'],
'ifx_fieldproperties' => ['array', 'result_id'=>'resource'],
'ifx_fieldtypes' => ['array', 'result_id'=>'resource'],
'ifx_free_blob' => ['bool', 'bid'=>'int'],
'ifx_free_char' => ['bool', 'bid'=>'int'],
'ifx_free_result' => ['bool', 'result_id'=>'resource'],
'ifx_get_blob' => ['string', 'bid'=>'int'],
'ifx_get_char' => ['string', 'bid'=>'int'],
'ifx_getsqlca' => ['array', 'result_id'=>'resource'],
'ifx_htmltbl_result' => ['int', 'result_id'=>'resource', 'html_table_options='=>'string'],
'ifx_nullformat' => ['bool', 'mode'=>'int'],
'ifx_num_fields' => ['int', 'result_id'=>'resource'],
'ifx_num_rows' => ['int', 'result_id'=>'resource'],
'ifx_pconnect' => ['resource', 'database='=>'string', 'userid='=>'string', 'password='=>'string'],
'ifx_prepare' => ['resource', 'query'=>'string', 'link_identifier'=>'resource', 'cursor_def='=>'int', 'blobidarray='=>'mixed'],
'ifx_query' => ['resource', 'query'=>'string', 'link_identifier'=>'resource', 'cursor_type='=>'int', 'blobidarray='=>'mixed'],
'ifx_textasvarchar' => ['bool', 'mode'=>'int'],
'ifx_update_blob' => ['bool', 'bid'=>'int', 'content'=>'string'],
'ifx_update_char' => ['bool', 'bid'=>'int', 'content'=>'string'],
'ifxus_close_slob' => ['bool', 'bid'=>'int'],
'ifxus_create_slob' => ['int', 'mode'=>'int'],
'ifxus_free_slob' => ['bool', 'bid'=>'int'],
'ifxus_open_slob' => ['int', 'bid'=>'int', 'mode'=>'int'],
'ifxus_read_slob' => ['string', 'bid'=>'int', 'nbytes'=>'int'],
'ifxus_seek_slob' => ['int', 'bid'=>'int', 'mode'=>'int', 'offset'=>'int'],
'ifxus_tell_slob' => ['int', 'bid'=>'int'],
'ifxus_write_slob' => ['int', 'bid'=>'int', 'content'=>'string'],
'igbinary_serialize' => ['string|false', 'value'=>'mixed'],
'igbinary_unserialize' => ['mixed', 'string'=>'string'],
'ignore_user_abort' => ['int', 'enable='=>'bool'],
'iis_add_server' => ['int', 'path'=>'string', 'comment'=>'string', 'server_ip'=>'string', 'port'=>'int', 'host_name'=>'string', 'rights'=>'int', 'start_server'=>'int'],
'iis_get_dir_security' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string'],
'iis_get_script_map' => ['string', 'server_instance'=>'int', 'virtual_path'=>'string', 'script_extension'=>'string'],
'iis_get_server_by_comment' => ['int', 'comment'=>'string'],
'iis_get_server_by_path' => ['int', 'path'=>'string'],
'iis_get_server_rights' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string'],
'iis_get_service_state' => ['int', 'service_id'=>'string'],
'iis_remove_server' => ['int', 'server_instance'=>'int'],
'iis_set_app_settings' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string', 'application_scope'=>'string'],
'iis_set_dir_security' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string', 'directory_flags'=>'int'],
'iis_set_script_map' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string', 'script_extension'=>'string', 'engine_path'=>'string', 'allow_scripting'=>'int'],
'iis_set_server_rights' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string', 'directory_flags'=>'int'],
'iis_start_server' => ['int', 'server_instance'=>'int'],
'iis_start_service' => ['int', 'service_id'=>'string'],
'iis_stop_server' => ['int', 'server_instance'=>'int'],
'iis_stop_service' => ['int', 'service_id'=>'string'],
'image_type_to_extension' => ['string', 'image_type'=>'int', 'include_dot='=>'bool'],
'image_type_to_mime_type' => ['string', 'image_type'=>'int'],
'imageaffine' => ['false|GdImage', 'image'=>'GdImage', 'affine'=>'array', 'clip='=>'?array'],
'imageaffinematrixconcat' => ['array{0:float,1:float,2:float,3:float,4:float,5:float}|false', 'matrix1'=>'array', 'matrix2'=>'array'],
'imageaffinematrixget' => ['array{0:float,1:float,2:float,3:float,4:float,5:float}|false', 'type'=>'int', 'options'=>'array|float'],
'imagealphablending' => ['bool', 'image'=>'GdImage', 'enable'=>'bool'],
'imageantialias' => ['bool', 'image'=>'GdImage', 'enable'=>'bool'],
'imagearc' => ['bool', 'image'=>'GdImage', 'center_x'=>'int', 'center_y'=>'int', 'width'=>'int', 'height'=>'int', 'start_angle'=>'int', 'end_angle'=>'int', 'color'=>'int'],
'imageavif' => ['bool', 'image'=>'GdImage', 'file='=>'resource|string|null', 'quality='=>'int', 'speed='=>'int'],
'imagebmp' => ['bool', 'image'=>'GdImage', 'file='=>'resource|string|null', 'compressed='=>'bool'],
'imagechar' => ['bool', 'image'=>'GdImage', 'font'=>'int', 'x'=>'int', 'y'=>'int', 'char'=>'string', 'color'=>'int'],
'imagecharup' => ['bool', 'image'=>'GdImage', 'font'=>'int', 'x'=>'int', 'y'=>'int', 'char'=>'string', 'color'=>'int'],
'imagecolorallocate' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolorallocatealpha' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha'=>'int'],
'imagecolorat' => ['int|false', 'image'=>'GdImage', 'x'=>'int', 'y'=>'int'],
'imagecolorclosest' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolorclosestalpha' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha'=>'int'],
'imagecolorclosesthwb' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolordeallocate' => ['bool', 'image'=>'GdImage', 'color'=>'int'],
'imagecolorexact' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolorexactalpha' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha'=>'int'],
'imagecolormatch' => ['bool', 'image1'=>'GdImage', 'image2'=>'GdImage'],
'imagecolorresolve' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolorresolvealpha' => ['int|false', 'image'=>'GdImage', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha'=>'int'],
'imagecolorset' => ['void', 'image'=>'GdImage', 'color'=>'int', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha='=>'int'],
'imagecolorsforindex' => ['array|false', 'image'=>'GdImage', 'color'=>'int'],
'imagecolorstotal' => ['int|false', 'image'=>'GdImage'],
'imagecolortransparent' => ['int|false', 'image'=>'GdImage', 'color='=>'int'],
'imageconvolution' => ['bool', 'image'=>'GdImage', 'matrix'=>'array', 'divisor'=>'float', 'offset'=>'float'],
'imagecopy' => ['bool', 'dst_image'=>'GdImage', 'src_image'=>'GdImage', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'src_width'=>'int', 'src_height'=>'int'],
'imagecopymerge' => ['bool', 'dst_image'=>'GdImage', 'src_image'=>'GdImage', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'src_width'=>'int', 'src_height'=>'int', 'pct'=>'int'],
'imagecopymergegray' => ['bool', 'dst_image'=>'GdImage', 'src_image'=>'GdImage', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'src_width'=>'int', 'src_height'=>'int', 'pct'=>'int'],
'imagecopyresampled' => ['bool', 'dst_image'=>'GdImage', 'src_image'=>'GdImage', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'dst_width'=>'int', 'dst_height'=>'int', 'src_width'=>'int', 'src_height'=>'int'],
'imagecopyresized' => ['bool', 'dst_image'=>'GdImage', 'src_image'=>'GdImage', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'dst_width'=>'int', 'dst_height'=>'int', 'src_width'=>'int', 'src_height'=>'int'],
'imagecreate' => ['false|GdImage', 'width'=>'int', 'height'=>'int'],
'imagecreatefromavif' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefrombmp' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefromgd' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefromgd2' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefromgd2part' => ['false|GdImage', 'filename'=>'string', 'x'=>'int', 'y'=>'int', 'width'=>'int', 'height'=>'int'],
'imagecreatefromgif' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefromjpeg' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefrompng' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefromstring' => ['false|GdImage', 'data'=>'string'],
'imagecreatefromwbmp' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefromwebp' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefromxbm' => ['false|GdImage', 'filename'=>'string'],
'imagecreatefromxpm' => ['false|GdImage', 'filename'=>'string'],
'imagecreatetruecolor' => ['false|GdImage', 'width'=>'int', 'height'=>'int'],
'imagecrop' => ['false|GdImage', 'image'=>'GdImage', 'rectangle'=>'array'],
'imagecropauto' => ['false|GdImage', 'image'=>'GdImage', 'mode='=>'int', 'threshold='=>'float', 'color='=>'int'],
'imagedashedline' => ['bool', 'image'=>'GdImage', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int', 'color'=>'int'],
'imagedestroy' => ['bool', 'image'=>'GdImage'],
'imageellipse' => ['bool', 'image'=>'GdImage', 'center_x'=>'int', 'center_y'=>'int', 'width'=>'int', 'height'=>'int', 'color'=>'int'],
'imagefill' => ['bool', 'image'=>'GdImage', 'x'=>'int', 'y'=>'int', 'color'=>'int'],
'imagefilledarc' => ['bool', 'image'=>'GdImage', 'center_x'=>'int', 'center_y'=>'int', 'width'=>'int', 'height'=>'int', 'start_angle'=>'int', 'end_angle'=>'int', 'color'=>'int', 'style'=>'int'],
'imagefilledellipse' => ['bool', 'image'=>'GdImage', 'center_x'=>'int', 'center_y'=>'int', 'width'=>'int', 'height'=>'int', 'color'=>'int'],
'imagefilledpolygon' => ['bool', 'image'=>'GdImage', 'points'=>'array', 'num_points_or_color'=>'int', 'color'=>'int'],
'imagefilledrectangle' => ['bool', 'image'=>'GdImage', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int', 'color'=>'int'],
'imagefilltoborder' => ['bool', 'image'=>'GdImage', 'x'=>'int', 'y'=>'int', 'border_color'=>'int', 'color'=>'int'],
'imagefilter' => ['bool', 'image'=>'GdImage', 'filter'=>'int', 'args='=>'int', 'arg2='=>'int', 'arg3='=>'int', 'arg4='=>'int'],
'imageflip' => ['bool', 'image'=>'GdImage', 'mode'=>'int'],
'imagefontheight' => ['int', 'font'=>'int'],
'imagefontwidth' => ['int', 'font'=>'int'],
'imageftbbox' => ['array|false', 'size'=>'float', 'angle'=>'float', 'font_filename'=>'string', 'string'=>'string', 'options='=>'array'],
'imagefttext' => ['array|false', 'image'=>'GdImage', 'size'=>'float', 'angle'=>'float', 'x'=>'int', 'y'=>'int', 'color'=>'int', 'font_filename'=>'string', 'text'=>'string', 'options='=>'array'],
'imagegammacorrect' => ['bool', 'image'=>'GdImage', 'input_gamma'=>'float', 'output_gamma'=>'float'],
'imagegd' => ['bool', 'image'=>'GdImage', 'file='=>'string|resource|null'],
'imagegd2' => ['bool', 'image'=>'GdImage', 'file='=>'string|resource|null', 'chunk_size='=>'int', 'mode='=>'int'],
'imagegetclip' => ['array<int,int>', 'image'=>'GdImage'],
'imagegetinterpolation' => ['int', 'image'=>'GdImage'],
'imagegif' => ['bool', 'image'=>'GdImage', 'file='=>'string|resource|null'],
'imagegrabscreen' => ['false|GdImage'],
'imagegrabwindow' => ['false|GdImage', 'handle'=>'int', 'client_area='=>'int'],
'imageinterlace' => ['int|false', 'image'=>'GdImage', 'enable='=>'int'],
'imageistruecolor' => ['bool', 'image'=>'GdImage'],
'imagejpeg' => ['bool', 'image'=>'GdImage', 'file='=>'string|resource|null', 'quality='=>'int'],
'imagelayereffect' => ['bool', 'image'=>'GdImage', 'effect'=>'int'],
'imageline' => ['bool', 'image'=>'GdImage', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int', 'color'=>'int'],
'imageloadfont' => ['int|false', 'filename'=>'string'],
'imageObj::pasteImage' => ['void', 'srcImg'=>'imageObj', 'transparentColorHex'=>'int', 'dstX'=>'int', 'dstY'=>'int', 'angle'=>'int'],
'imageObj::saveImage' => ['int', 'filename'=>'string', 'oMap'=>'mapObj'],
'imageObj::saveWebImage' => ['string'],
'imageopenpolygon' => ['bool', 'image'=>'GdImage', 'points'=>'array', 'num_points'=>'int', 'color'=>'int'],
'imagepalettecopy' => ['void', 'dst'=>'GdImage', 'src'=>'GdImage'],
'imagepalettetotruecolor' => ['bool', 'image'=>'GdImage'],
'imagepng' => ['bool', 'image'=>'GdImage', 'file='=>'string|resource|null', 'quality='=>'int', 'filters='=>'int'],
'imagepolygon' => ['bool', 'image'=>'GdImage', 'points'=>'array', 'num_points_or_color'=>'int', 'color'=>'int'],
'imagerectangle' => ['bool', 'image'=>'GdImage', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int', 'color'=>'int'],
'imageresolution' => ['array|bool', 'image'=>'GdImage', 'resolution_x='=>'int', 'resolution_y='=>'int'],
'imagerotate' => ['false|GdImage', 'image'=>'GdImage', 'angle'=>'float', 'background_color'=>'int', 'ignore_transparent='=>'int'],
'imagesavealpha' => ['bool', 'image'=>'GdImage', 'enable'=>'bool'],
'imagescale' => ['false|GdImage', 'image'=>'GdImage', 'width'=>'int', 'height='=>'int', 'mode='=>'int'],
'imagesetbrush' => ['bool', 'image'=>'GdImage', 'brush'=>'GdImage'],
'imagesetclip' => ['bool', 'image'=>'GdImage', 'x1'=>'int', 'x2'=>'int', 'y1'=>'int', 'y2'=>'int'],
'imagesetinterpolation' => ['bool', 'image'=>'GdImage', 'method'=>'int'],
'imagesetpixel' => ['bool', 'image'=>'GdImage', 'x'=>'int', 'y'=>'int', 'color'=>'int'],
'imagesetstyle' => ['bool', 'image'=>'GdImage', 'style'=>'non-empty-array'],
'imagesetthickness' => ['bool', 'image'=>'GdImage', 'thickness'=>'int'],
'imagesettile' => ['bool', 'image'=>'GdImage', 'tile'=>'GdImage'],
'imagestring' => ['bool', 'image'=>'GdImage', 'font'=>'int', 'x'=>'int', 'y'=>'int', 'string'=>'string', 'color'=>'int'],
'imagestringup' => ['bool', 'image'=>'GdImage', 'font'=>'int', 'x'=>'int', 'y'=>'int', 'string'=>'string', 'color'=>'int'],
'imagesx' => ['int|false', 'image'=>'GdImage'],
'imagesy' => ['int|false', 'image'=>'GdImage'],
'imagetruecolortopalette' => ['bool', 'image'=>'GdImage', 'dither'=>'bool', 'num_colors'=>'int'],
'imagettfbbox' => ['false|array', 'size'=>'float', 'angle'=>'float', 'font_filename'=>'string', 'string'=>'string'],
'imagettftext' => ['false|array', 'image'=>'GdImage', 'size'=>'float', 'angle'=>'float', 'x'=>'int', 'y'=>'int', 'color'=>'int', 'font_filename'=>'string', 'text'=>'string'],
'imagetypes' => ['int'],
'imagewbmp' => ['bool', 'image'=>'GdImage', 'file='=>'string|resource|null', 'foreground_color='=>'int'],
'imagewebp' => ['bool', 'image'=>'GdImage', 'file='=>'string|resource|null', 'quality='=>'int'],
'imagexbm' => ['bool', 'image'=>'GdImage', 'filename='=>'?string', 'foreground_color='=>'int'],
'Imagick::__construct' => ['void', 'files='=>'string|string[]'],
'Imagick::__toString' => ['string'],
'Imagick::adaptiveBlurImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Imagick::adaptiveResizeImage' => ['bool', 'columns'=>'int', 'rows'=>'int', 'bestfit='=>'bool'],
'Imagick::adaptiveSharpenImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Imagick::adaptiveThresholdImage' => ['bool', 'width'=>'int', 'height'=>'int', 'offset'=>'int'],
'Imagick::addImage' => ['bool', 'source'=>'Imagick'],
'Imagick::addNoiseImage' => ['bool', 'noise_type'=>'int', 'channel='=>'int'],
'Imagick::affineTransformImage' => ['bool', 'matrix'=>'ImagickDraw'],
'Imagick::animateImages' => ['bool', 'x_server'=>'string'],
'Imagick::annotateImage' => ['bool', 'draw_settings'=>'ImagickDraw', 'x'=>'float', 'y'=>'float', 'angle'=>'float', 'text'=>'string'],
'Imagick::appendImages' => ['Imagick', 'stack'=>'bool'],
'Imagick::autoGammaImage' => ['bool', 'channel='=>'int'],
'Imagick::autoLevelImage' => ['void', 'CHANNEL='=>'string'],
'Imagick::autoOrient' => ['bool'],
'Imagick::averageImages' => ['Imagick'],
'Imagick::blackThresholdImage' => ['bool', 'threshold'=>'mixed'],
'Imagick::blueShiftImage' => ['void', 'factor='=>'float'],
'Imagick::blurImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Imagick::borderImage' => ['bool', 'bordercolor'=>'mixed', 'width'=>'int', 'height'=>'int'],
'Imagick::brightnessContrastImage' => ['void', 'brightness'=>'string', 'contrast'=>'string', 'CHANNEL='=>'string'],
'Imagick::charcoalImage' => ['bool', 'radius'=>'float', 'sigma'=>'float'],
'Imagick::chopImage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::clampImage' => ['void', 'CHANNEL='=>'string'],
'Imagick::clear' => ['bool'],
'Imagick::clipImage' => ['bool'],
'Imagick::clipImagePath' => ['void', 'pathname'=>'string', 'inside'=>'string'],
'Imagick::clipPathImage' => ['bool', 'pathname'=>'string', 'inside'=>'bool'],
'Imagick::clone' => ['Imagick'],
'Imagick::clutImage' => ['bool', 'lookup_table'=>'Imagick', 'channel='=>'float'],
'Imagick::coalesceImages' => ['Imagick'],
'Imagick::colorFloodfillImage' => ['bool', 'fill'=>'mixed', 'fuzz'=>'float', 'bordercolor'=>'mixed', 'x'=>'int', 'y'=>'int'],
'Imagick::colorizeImage' => ['bool', 'colorize'=>'mixed', 'opacity'=>'mixed'],
'Imagick::colorMatrixImage' => ['void', 'color_matrix'=>'string'],
'Imagick::combineImages' => ['Imagick', 'channeltype'=>'int'],
'Imagick::commentImage' => ['bool', 'comment'=>'string'],
'Imagick::compareImageChannels' => ['array{Imagick, float}', 'image'=>'Imagick', 'channeltype'=>'int', 'metrictype'=>'int'],
'Imagick::compareImageLayers' => ['Imagick', 'method'=>'int'],
'Imagick::compareImages' => ['array{Imagick, float}', 'compare'=>'Imagick', 'metric'=>'int'],
'Imagick::compositeImage' => ['bool', 'composite_object'=>'Imagick', 'composite'=>'int', 'x'=>'int', 'y'=>'int', 'channel='=>'int'],
'Imagick::compositeImageGravity' => ['bool', 'Imagick'=>'Imagick', 'COMPOSITE_CONSTANT'=>'int', 'GRAVITY_CONSTANT'=>'int'],
'Imagick::contrastImage' => ['bool', 'sharpen'=>'bool'],
'Imagick::contrastStretchImage' => ['bool', 'black_point'=>'float', 'white_point'=>'float', 'channel='=>'int'],
'Imagick::convolveImage' => ['bool', 'kernel'=>'array', 'channel='=>'int'],
'Imagick::count' => ['void', 'mode='=>'string'],
'Imagick::cropImage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::cropThumbnailImage' => ['bool', 'width'=>'int', 'height'=>'int', 'legacy='=>'bool'],
'Imagick::current' => ['Imagick'],
'Imagick::cycleColormapImage' => ['bool', 'displace'=>'int'],
'Imagick::decipherImage' => ['bool', 'passphrase'=>'string'],
'Imagick::deconstructImages' => ['Imagick'],
'Imagick::deleteImageArtifact' => ['bool', 'artifact'=>'string'],
'Imagick::deleteImageProperty' => ['void', 'name'=>'string'],
'Imagick::deskewImage' => ['bool', 'threshold'=>'float'],
'Imagick::despeckleImage' => ['bool'],
'Imagick::destroy' => ['bool'],
'Imagick::displayImage' => ['bool', 'servername'=>'string'],
'Imagick::displayImages' => ['bool', 'servername'=>'string'],
'Imagick::distortImage' => ['bool', 'method'=>'int', 'arguments'=>'array', 'bestfit'=>'bool'],
'Imagick::drawImage' => ['bool', 'draw'=>'ImagickDraw'],
'Imagick::edgeImage' => ['bool', 'radius'=>'float'],
'Imagick::embossImage' => ['bool', 'radius'=>'float', 'sigma'=>'float'],
'Imagick::encipherImage' => ['bool', 'passphrase'=>'string'],
'Imagick::enhanceImage' => ['bool'],
'Imagick::equalizeImage' => ['bool'],
'Imagick::evaluateImage' => ['bool', 'op'=>'int', 'constant'=>'float', 'channel='=>'int'],
'Imagick::evaluateImages' => ['bool', 'EVALUATE_CONSTANT'=>'int'],
'Imagick::exportImagePixels' => ['list<int>', 'x'=>'int', 'y'=>'int', 'width'=>'int', 'height'=>'int', 'map'=>'string', 'storage'=>'int'],
'Imagick::extentImage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::filter' => ['void', 'ImagickKernel'=>'ImagickKernel', 'CHANNEL='=>'int'],
'Imagick::flattenImages' => ['Imagick'],
'Imagick::flipImage' => ['bool'],
'Imagick::floodFillPaintImage' => ['bool', 'fill'=>'mixed', 'fuzz'=>'float', 'target'=>'mixed', 'x'=>'int', 'y'=>'int', 'invert'=>'bool', 'channel='=>'int'],
'Imagick::flopImage' => ['bool'],
'Imagick::forwardFourierTransformimage' => ['void', 'magnitude'=>'bool'],
'Imagick::frameImage' => ['bool', 'matte_color'=>'mixed', 'width'=>'int', 'height'=>'int', 'inner_bevel'=>'int', 'outer_bevel'=>'int'],
'Imagick::functionImage' => ['bool', 'function'=>'int', 'arguments'=>'array', 'channel='=>'int'],
'Imagick::fxImage' => ['Imagick', 'expression'=>'string', 'channel='=>'int'],
'Imagick::gammaImage' => ['bool', 'gamma'=>'float', 'channel='=>'int'],
'Imagick::gaussianBlurImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Imagick::getColorspace' => ['int'],
'Imagick::getCompression' => ['int'],
'Imagick::getCompressionQuality' => ['int'],
'Imagick::getConfigureOptions' => ['string'],
'Imagick::getCopyright' => ['string'],
'Imagick::getFeatures' => ['string'],
'Imagick::getFilename' => ['string'],
'Imagick::getFont' => ['string|false'],
'Imagick::getFormat' => ['string'],
'Imagick::getGravity' => ['int'],
'Imagick::getHDRIEnabled' => ['int'],
'Imagick::getHomeURL' => ['string'],
'Imagick::getImage' => ['Imagick'],
'Imagick::getImageAlphaChannel' => ['int'],
'Imagick::getImageArtifact' => ['string', 'artifact'=>'string'],
'Imagick::getImageAttribute' => ['string', 'key'=>'string'],
'Imagick::getImageBackgroundColor' => ['ImagickPixel'],
'Imagick::getImageBlob' => ['string'],
'Imagick::getImageBluePrimary' => ['array{x:float, y:float}'],
'Imagick::getImageBorderColor' => ['ImagickPixel'],
'Imagick::getImageChannelDepth' => ['int', 'channel'=>'int'],
'Imagick::getImageChannelDistortion' => ['float', 'reference'=>'Imagick', 'channel'=>'int', 'metric'=>'int'],
'Imagick::getImageChannelDistortions' => ['float', 'reference'=>'Imagick', 'metric'=>'int', 'channel='=>'int'],
'Imagick::getImageChannelExtrema' => ['array{minima:int, maxima:int}', 'channel'=>'int'],
'Imagick::getImageChannelKurtosis' => ['array{kurtosis:float, skewness:float}', 'channel='=>'int'],
'Imagick::getImageChannelMean' => ['array{mean:float, standardDeviation:float}', 'channel'=>'int'],
'Imagick::getImageChannelRange' => ['array{minima:float, maxima:float}', 'channel'=>'int'],
'Imagick::getImageChannelStatistics' => ['array<int, array{mean:float, minima:float, maxima:float, standardDeviation:float, depth:int}>'],
'Imagick::getImageClipMask' => ['Imagick'],
'Imagick::getImageColormapColor' => ['ImagickPixel', 'index'=>'int'],
'Imagick::getImageColors' => ['int'],
'Imagick::getImageColorspace' => ['int'],
'Imagick::getImageCompose' => ['int'],
'Imagick::getImageCompression' => ['int'],
'Imagick::getImageCompressionQuality' => ['int'],
'Imagick::getImageDelay' => ['int'],
'Imagick::getImageDepth' => ['int'],
'Imagick::getImageDispose' => ['int'],
'Imagick::getImageDistortion' => ['float', 'reference'=>'magickwand', 'metric'=>'int'],
'Imagick::getImageExtrema' => ['array{min:int, max:int}'],
'Imagick::getImageFilename' => ['string'],
'Imagick::getImageFormat' => ['string'],
'Imagick::getImageGamma' => ['float'],
'Imagick::getImageGeometry' => ['array{width:int, height:int}'],
'Imagick::getImageGravity' => ['int'],
'Imagick::getImageGreenPrimary' => ['array{x:float, y:float}'],
'Imagick::getImageHeight' => ['int'],
'Imagick::getImageHistogram' => ['list<ImagickPixel>'],
'Imagick::getImageIndex' => ['int'],
'Imagick::getImageInterlaceScheme' => ['int'],
'Imagick::getImageInterpolateMethod' => ['int'],
'Imagick::getImageIterations' => ['int'],
'Imagick::getImageLength' => ['int'],
'Imagick::getImageMagickLicense' => ['string'],
'Imagick::getImageMatte' => ['bool'],
'Imagick::getImageMatteColor' => ['ImagickPixel'],
'Imagick::getImageMimeType' => ['string'],
'Imagick::getImageOrientation' => ['int'],
'Imagick::getImagePage' => ['array{width:int, height:int, x:int, y:int}'],
'Imagick::getImagePixelColor' => ['ImagickPixel', 'x'=>'int', 'y'=>'int'],
'Imagick::getImageProfile' => ['string', 'name'=>'string'],
'Imagick::getImageProfiles' => ['array', 'pattern='=>'string', 'only_names='=>'bool'],
'Imagick::getImageProperties' => ['array<int|string, string>', 'pattern='=>'string', 'only_names='=>'bool'],
'Imagick::getImageProperty' => ['string|false', 'name'=>'string'],
'Imagick::getImageRedPrimary' => ['array{x:float, y:float}'],
'Imagick::getImageRegion' => ['Imagick', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::getImageRenderingIntent' => ['int'],
'Imagick::getImageResolution' => ['array{x:float, y:float}'],
'Imagick::getImagesBlob' => ['string'],
'Imagick::getImageScene' => ['int'],
'Imagick::getImageSignature' => ['string'],
'Imagick::getImageSize' => ['int'],
'Imagick::getImageTicksPerSecond' => ['int'],
'Imagick::getImageTotalInkDensity' => ['float'],
'Imagick::getImageType' => ['int'],
'Imagick::getImageUnits' => ['int'],
'Imagick::getImageVirtualPixelMethod' => ['int'],
'Imagick::getImageWhitePoint' => ['array{x:float, y:float}'],
'Imagick::getImageWidth' => ['int'],
'Imagick::getInterlaceScheme' => ['int'],
'Imagick::getIteratorIndex' => ['int'],
'Imagick::getNumberImages' => ['int'],
'Imagick::getOption' => ['string', 'key'=>'string'],
'Imagick::getPackageName' => ['string'],
'Imagick::getPage' => ['array{width:int, height:int, x:int, y:int}'],
'Imagick::getPixelIterator' => ['ImagickPixelIterator'],
'Imagick::getPixelRegionIterator' => ['ImagickPixelIterator', 'x'=>'int', 'y'=>'int', 'columns'=>'int', 'rows'=>'int'],
'Imagick::getPointSize' => ['float'],
'Imagick::getQuantum' => ['int'],
'Imagick::getQuantumDepth' => ['array{quantumDepthLong:int, quantumDepthString:string}'],
'Imagick::getQuantumRange' => ['array{quantumRangeLong:int, quantumRangeString:string}'],
'Imagick::getRegistry' => ['string|false', 'key'=>'string'],
'Imagick::getReleaseDate' => ['string'],
'Imagick::getResource' => ['int', 'type'=>'int'],
'Imagick::getResourceLimit' => ['int', 'type'=>'int'],
'Imagick::getSamplingFactors' => ['array'],
'Imagick::getSize' => ['array{columns:int, rows: int}'],
'Imagick::getSizeOffset' => ['int'],
'Imagick::getVersion' => ['array{versionNumber: int, versionString:string}'],
'Imagick::haldClutImage' => ['bool', 'clut'=>'Imagick', 'channel='=>'int'],
'Imagick::hasNextImage' => ['bool'],
'Imagick::hasPreviousImage' => ['bool'],
'Imagick::identifyFormat' => ['string|false', 'embedText'=>'string'],
'Imagick::identifyImage' => ['array<string, mixed>', 'appendrawoutput='=>'bool'],
'Imagick::identifyImageType' => ['int'],
'Imagick::implodeImage' => ['bool', 'radius'=>'float'],
'Imagick::importImagePixels' => ['bool', 'x'=>'int', 'y'=>'int', 'width'=>'int', 'height'=>'int', 'map'=>'string', 'storage'=>'int', 'pixels'=>'list<int>'],
'Imagick::inverseFourierTransformImage' => ['void', 'complement'=>'string', 'magnitude'=>'string'],
'Imagick::key' => ['int|string'],
'Imagick::labelImage' => ['bool', 'label'=>'string'],
'Imagick::levelImage' => ['bool', 'blackpoint'=>'float', 'gamma'=>'float', 'whitepoint'=>'float', 'channel='=>'int'],
'Imagick::linearStretchImage' => ['bool', 'blackpoint'=>'float', 'whitepoint'=>'float'],
'Imagick::liquidRescaleImage' => ['bool', 'width'=>'int', 'height'=>'int', 'delta_x'=>'float', 'rigidity'=>'float'],
'Imagick::listRegistry' => ['array'],
'Imagick::localContrastImage' => ['bool', 'radius'=>'float', 'strength'=>'float'],
'Imagick::magnifyImage' => ['bool'],
'Imagick::mapImage' => ['bool', 'map'=>'Imagick', 'dither'=>'bool'],
'Imagick::matteFloodfillImage' => ['bool', 'alpha'=>'float', 'fuzz'=>'float', 'bordercolor'=>'mixed', 'x'=>'int', 'y'=>'int'],
'Imagick::medianFilterImage' => ['bool', 'radius'=>'float'],
'Imagick::mergeImageLayers' => ['Imagick', 'layer_method'=>'int'],
'Imagick::minifyImage' => ['bool'],
'Imagick::modulateImage' => ['bool', 'brightness'=>'float', 'saturation'=>'float', 'hue'=>'float'],
'Imagick::montageImage' => ['Imagick', 'draw'=>'ImagickDraw', 'tile_geometry'=>'string', 'thumbnail_geometry'=>'string', 'mode'=>'int', 'frame'=>'string'],
'Imagick::morphImages' => ['Imagick', 'number_frames'=>'int'],
'Imagick::morphology' => ['void', 'morphologyMethod'=>'int', 'iterations'=>'int', 'ImagickKernel'=>'ImagickKernel', 'CHANNEL='=>'string'],
'Imagick::mosaicImages' => ['Imagick'],
'Imagick::motionBlurImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'angle'=>'float', 'channel='=>'int'],
'Imagick::negateImage' => ['bool', 'gray'=>'bool', 'channel='=>'int'],
'Imagick::newImage' => ['bool', 'cols'=>'int', 'rows'=>'int', 'background'=>'mixed', 'format='=>'string'],
'Imagick::newPseudoImage' => ['bool', 'columns'=>'int', 'rows'=>'int', 'pseudostring'=>'string'],
'Imagick::next' => ['void'],
'Imagick::nextImage' => ['bool'],
'Imagick::normalizeImage' => ['bool', 'channel='=>'int'],
'Imagick::oilPaintImage' => ['bool', 'radius'=>'float'],
'Imagick::opaquePaintImage' => ['bool', 'target'=>'mixed', 'fill'=>'mixed', 'fuzz'=>'float', 'invert'=>'bool', 'channel='=>'int'],
'Imagick::optimizeImageLayers' => ['bool'],
'Imagick::orderedPosterizeImage' => ['bool', 'threshold_map'=>'string', 'channel='=>'int'],
'Imagick::paintFloodfillImage' => ['bool', 'fill'=>'mixed', 'fuzz'=>'float', 'bordercolor'=>'mixed', 'x'=>'int', 'y'=>'int', 'channel='=>'int'],
'Imagick::paintOpaqueImage' => ['bool', 'target'=>'mixed', 'fill'=>'mixed', 'fuzz'=>'float', 'channel='=>'int'],
'Imagick::paintTransparentImage' => ['bool', 'target'=>'mixed', 'alpha'=>'float', 'fuzz'=>'float'],
'Imagick::pingImage' => ['bool', 'filename'=>'string'],
'Imagick::pingImageBlob' => ['bool', 'image'=>'string'],
'Imagick::pingImageFile' => ['bool', 'filehandle'=>'resource', 'filename='=>'string'],
'Imagick::polaroidImage' => ['bool', 'properties'=>'ImagickDraw', 'angle'=>'float'],
'Imagick::posterizeImage' => ['bool', 'levels'=>'int', 'dither'=>'bool'],
'Imagick::previewImages' => ['bool', 'preview'=>'int'],
'Imagick::previousImage' => ['bool'],
'Imagick::profileImage' => ['bool', 'name'=>'string', 'profile'=>'string'],
'Imagick::quantizeImage' => ['bool', 'numbercolors'=>'int', 'colorspace'=>'int', 'treedepth'=>'int', 'dither'=>'bool', 'measureerror'=>'bool'],
'Imagick::quantizeImages' => ['bool', 'numbercolors'=>'int', 'colorspace'=>'int', 'treedepth'=>'int', 'dither'=>'bool', 'measureerror'=>'bool'],
'Imagick::queryFontMetrics' => ['array', 'properties'=>'ImagickDraw', 'text'=>'string', 'multiline='=>'bool'],
'Imagick::queryFonts' => ['array', 'pattern='=>'string'],
'Imagick::queryFormats' => ['list<string>', 'pattern='=>'string'],
'Imagick::radialBlurImage' => ['bool', 'angle'=>'float', 'channel='=>'int'],
'Imagick::raiseImage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int', 'raise'=>'bool'],
'Imagick::randomThresholdImage' => ['bool', 'low'=>'float', 'high'=>'float', 'channel='=>'int'],
'Imagick::readImage' => ['bool', 'filename'=>'string'],
'Imagick::readImageBlob' => ['bool', 'image'=>'string', 'filename='=>'string'],
'Imagick::readImageFile' => ['bool', 'filehandle'=>'resource', 'filename='=>'string'],
'Imagick::readImages' => ['Imagick', 'filenames'=>'string'],
'Imagick::recolorImage' => ['bool', 'matrix'=>'list<float>'],
'Imagick::reduceNoiseImage' => ['bool', 'radius'=>'float'],
'Imagick::remapImage' => ['bool', 'replacement'=>'Imagick', 'dither'=>'int'],
'Imagick::removeImage' => ['bool'],
'Imagick::removeImageProfile' => ['string', 'name'=>'string'],
'Imagick::render' => ['bool'],
'Imagick::resampleImage' => ['bool', 'x_resolution'=>'float', 'y_resolution'=>'float', 'filter'=>'int', 'blur'=>'float'],
'Imagick::resetImagePage' => ['bool', 'page'=>'string'],
'Imagick::resetIterator' => [''],
'Imagick::resizeImage' => ['bool', 'columns'=>'int', 'rows'=>'int', 'filter'=>'int', 'blur'=>'float', 'bestfit='=>'bool'],
'Imagick::rewind' => ['void'],
'Imagick::rollImage' => ['bool', 'x'=>'int', 'y'=>'int'],
'Imagick::rotateImage' => ['bool', 'background'=>'mixed', 'degrees'=>'float'],
'Imagick::rotationalBlurImage' => ['void', 'angle'=>'string', 'CHANNEL='=>'string'],
'Imagick::roundCorners' => ['bool', 'x_rounding'=>'float', 'y_rounding'=>'float', 'stroke_width='=>'float', 'displace='=>'float', 'size_correction='=>'float'],
'Imagick::roundCornersImage' => ['', 'xRounding'=>'', 'yRounding'=>'', 'strokeWidth'=>'', 'displace'=>'', 'sizeCorrection'=>''],
'Imagick::sampleImage' => ['bool', 'columns'=>'int', 'rows'=>'int'],
'Imagick::scaleImage' => ['bool', 'cols'=>'int', 'rows'=>'int', 'bestfit='=>'bool'],
'Imagick::segmentImage' => ['bool', 'colorspace'=>'int', 'cluster_threshold'=>'float', 'smooth_threshold'=>'float', 'verbose='=>'bool'],
'Imagick::selectiveBlurImage' => ['void', 'radius'=>'float', 'sigma'=>'float', 'threshold'=>'float', 'CHANNEL'=>'int'],
'Imagick::separateImageChannel' => ['bool', 'channel'=>'int'],
'Imagick::sepiaToneImage' => ['bool', 'threshold'=>'float'],
'Imagick::setAntiAlias' => ['int', 'antialias'=>'bool'],
'Imagick::setBackgroundColor' => ['bool', 'background'=>'mixed'],
'Imagick::setColorspace' => ['bool', 'colorspace'=>'int'],
'Imagick::setCompression' => ['bool', 'compression'=>'int'],
'Imagick::setCompressionQuality' => ['bool', 'quality'=>'int'],
'Imagick::setFilename' => ['bool', 'filename'=>'string'],
'Imagick::setFirstIterator' => ['bool'],
'Imagick::setFont' => ['bool', 'font'=>'string'],
'Imagick::setFormat' => ['bool', 'format'=>'string'],
'Imagick::setGravity' => ['bool', 'gravity'=>'int'],
'Imagick::setImage' => ['bool', 'replace'=>'Imagick'],
'Imagick::setImageAlpha' => ['bool', 'alpha'=>'float'],
'Imagick::setImageAlphaChannel' => ['bool', 'mode'=>'int'],
'Imagick::setImageArtifact' => ['bool', 'artifact'=>'string', 'value'=>'string'],
'Imagick::setImageAttribute' => ['void', 'key'=>'string', 'value'=>'string'],
'Imagick::setImageBackgroundColor' => ['bool', 'background'=>'mixed'],
'Imagick::setImageBias' => ['bool', 'bias'=>'float'],
'Imagick::setImageBiasQuantum' => ['void', 'bias'=>'string'],
'Imagick::setImageBluePrimary' => ['bool', 'x'=>'float', 'y'=>'float'],
'Imagick::setImageBorderColor' => ['bool', 'border'=>'mixed'],
'Imagick::setImageChannelDepth' => ['bool', 'channel'=>'int', 'depth'=>'int'],
'Imagick::setImageChannelMask' => ['', 'channel'=>'int'],
'Imagick::setImageClipMask' => ['bool', 'clip_mask'=>'Imagick'],
'Imagick::setImageColormapColor' => ['bool', 'index'=>'int', 'color'=>'ImagickPixel'],
'Imagick::setImageColorspace' => ['bool', 'colorspace'=>'int'],
'Imagick::setImageCompose' => ['bool', 'compose'=>'int'],
'Imagick::setImageCompression' => ['bool', 'compression'=>'int'],
'Imagick::setImageCompressionQuality' => ['bool', 'quality'=>'int'],
'Imagick::setImageDelay' => ['bool', 'delay'=>'int'],
'Imagick::setImageDepth' => ['bool', 'depth'=>'int'],
'Imagick::setImageDispose' => ['bool', 'dispose'=>'int'],
'Imagick::setImageExtent' => ['bool', 'columns'=>'int', 'rows'=>'int'],
'Imagick::setImageFilename' => ['bool', 'filename'=>'string'],
'Imagick::setImageFormat' => ['bool', 'format'=>'string'],
'Imagick::setImageGamma' => ['bool', 'gamma'=>'float'],
'Imagick::setImageGravity' => ['bool', 'gravity'=>'int'],
'Imagick::setImageGreenPrimary' => ['bool', 'x'=>'float', 'y'=>'float'],
'Imagick::setImageIndex' => ['bool', 'index'=>'int'],
'Imagick::setImageInterlaceScheme' => ['bool', 'interlace_scheme'=>'int'],
'Imagick::setImageInterpolateMethod' => ['bool', 'method'=>'int'],
'Imagick::setImageIterations' => ['bool', 'iterations'=>'int'],
'Imagick::setImageMatte' => ['bool', 'matte'=>'bool'],
'Imagick::setImageMatteColor' => ['bool', 'matte'=>'mixed'],
'Imagick::setImageOpacity' => ['bool', 'opacity'=>'float'],
'Imagick::setImageOrientation' => ['bool', 'orientation'=>'int'],
'Imagick::setImagePage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::setImageProfile' => ['bool', 'name'=>'string', 'profile'=>'string'],
'Imagick::setImageProgressMonitor' => ['', 'filename'=>''],
'Imagick::setImageProperty' => ['bool', 'name'=>'string', 'value'=>'string'],
'Imagick::setImageRedPrimary' => ['bool', 'x'=>'float', 'y'=>'float'],
'Imagick::setImageRenderingIntent' => ['bool', 'rendering_intent'=>'int'],
'Imagick::setImageResolution' => ['bool', 'x_resolution'=>'float', 'y_resolution'=>'float'],
'Imagick::setImageScene' => ['bool', 'scene'=>'int'],
'Imagick::setImageTicksPerSecond' => ['bool', 'ticks_per_second'=>'int'],
'Imagick::setImageType' => ['bool', 'image_type'=>'int'],
'Imagick::setImageUnits' => ['bool', 'units'=>'int'],
'Imagick::setImageVirtualPixelMethod' => ['bool', 'method'=>'int'],
'Imagick::setImageWhitePoint' => ['bool', 'x'=>'float', 'y'=>'float'],
'Imagick::setInterlaceScheme' => ['bool', 'interlace_scheme'=>'int'],
'Imagick::setIteratorIndex' => ['bool', 'index'=>'int'],
'Imagick::setLastIterator' => ['bool'],
'Imagick::setOption' => ['bool', 'key'=>'string', 'value'=>'string'],
'Imagick::setPage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::setPointSize' => ['bool', 'point_size'=>'float'],
'Imagick::setProgressMonitor' => ['void', 'callback'=>'callable'],
'Imagick::setRegistry' => ['void', 'key'=>'string', 'value'=>'string'],
'Imagick::setResolution' => ['bool', 'x_resolution'=>'float', 'y_resolution'=>'float'],
'Imagick::setResourceLimit' => ['bool', 'type'=>'int', 'limit'=>'int'],
'Imagick::setSamplingFactors' => ['bool', 'factors'=>'list<string>'],
'Imagick::setSize' => ['bool', 'columns'=>'int', 'rows'=>'int'],
'Imagick::setSizeOffset' => ['bool', 'columns'=>'int', 'rows'=>'int', 'offset'=>'int'],
'Imagick::setType' => ['bool', 'image_type'=>'int'],
'Imagick::shadeImage' => ['bool', 'gray'=>'bool', 'azimuth'=>'float', 'elevation'=>'float'],
'Imagick::shadowImage' => ['bool', 'opacity'=>'float', 'sigma'=>'float', 'x'=>'int', 'y'=>'int'],
'Imagick::sharpenImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Imagick::shaveImage' => ['bool', 'columns'=>'int', 'rows'=>'int'],
'Imagick::shearImage' => ['bool', 'background'=>'mixed', 'x_shear'=>'float', 'y_shear'=>'float'],
'Imagick::sigmoidalContrastImage' => ['bool', 'sharpen'=>'bool', 'alpha'=>'float', 'beta'=>'float', 'channel='=>'int'],
'Imagick::similarityImage' => ['Imagick', 'Imagick'=>'Imagick', '&bestMatch'=>'array', '&similarity'=>'float', 'similarity_threshold'=>'float', 'metric'=>'int'],
'Imagick::sketchImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'angle'=>'float'],
'Imagick::smushImages' => ['Imagick', 'stack'=>'string', 'offset'=>'string'],
'Imagick::solarizeImage' => ['bool', 'threshold'=>'int'],
'Imagick::sparseColorImage' => ['bool', 'sparse_method'=>'int', 'arguments'=>'array', 'channel='=>'int'],
'Imagick::spliceImage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::spreadImage' => ['bool', 'radius'=>'float'],
'Imagick::statisticImage' => ['void', 'type'=>'int', 'width'=>'int', 'height'=>'int', 'CHANNEL='=>'string'],
'Imagick::steganoImage' => ['Imagick', 'watermark_wand'=>'Imagick', 'offset'=>'int'],
'Imagick::stereoImage' => ['bool', 'offset_wand'=>'Imagick'],
'Imagick::stripImage' => ['bool'],
'Imagick::subImageMatch' => ['Imagick', 'Imagick'=>'Imagick', '&w_offset='=>'array', '&w_similarity='=>'float'],
'Imagick::swirlImage' => ['bool', 'degrees'=>'float'],
'Imagick::textureImage' => ['bool', 'texture_wand'=>'Imagick'],
'Imagick::thresholdImage' => ['bool', 'threshold'=>'float', 'channel='=>'int'],
'Imagick::thumbnailImage' => ['bool', 'columns'=>'int', 'rows'=>'int', 'bestfit='=>'bool', 'fill='=>'bool', 'legacy='=>'bool'],
'Imagick::tintImage' => ['bool', 'tint'=>'mixed', 'opacity'=>'mixed'],
'Imagick::transformImage' => ['Imagick', 'crop'=>'string', 'geometry'=>'string'],
'Imagick::transformImageColorspace' => ['bool', 'colorspace'=>'int'],
'Imagick::transparentPaintImage' => ['bool', 'target'=>'mixed', 'alpha'=>'float', 'fuzz'=>'float', 'invert'=>'bool'],
'Imagick::transposeImage' => ['bool'],
'Imagick::transverseImage' => ['bool'],
'Imagick::trimImage' => ['bool', 'fuzz'=>'float'],
'Imagick::uniqueImageColors' => ['bool'],
'Imagick::unsharpMaskImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'amount'=>'float', 'threshold'=>'float', 'channel='=>'int'],
'Imagick::valid' => ['bool'],
'Imagick::vignetteImage' => ['bool', 'blackpoint'=>'float', 'whitepoint'=>'float', 'x'=>'int', 'y'=>'int'],
'Imagick::waveImage' => ['bool', 'amplitude'=>'float', 'length'=>'float'],
'Imagick::whiteThresholdImage' => ['bool', 'threshold'=>'mixed'],
'Imagick::writeImage' => ['bool', 'filename='=>'string'],
'Imagick::writeImageFile' => ['bool', 'filehandle'=>'resource'],
'Imagick::writeImages' => ['bool', 'filename'=>'string', 'adjoin'=>'bool'],
'Imagick::writeImagesFile' => ['bool', 'filehandle'=>'resource'],
'ImagickDraw::__construct' => ['void'],
'ImagickDraw::affine' => ['bool', 'affine'=>'array<string, float>'],
'ImagickDraw::annotation' => ['bool', 'x'=>'float', 'y'=>'float', 'text'=>'string'],
'ImagickDraw::arc' => ['bool', 'sx'=>'float', 'sy'=>'float', 'ex'=>'float', 'ey'=>'float', 'sd'=>'float', 'ed'=>'float'],
'ImagickDraw::bezier' => ['bool', 'coordinates'=>'list<array{x:float, y:float}>'],
'ImagickDraw::circle' => ['bool', 'ox'=>'float', 'oy'=>'float', 'px'=>'float', 'py'=>'float'],
'ImagickDraw::clear' => ['bool'],
'ImagickDraw::clone' => ['ImagickDraw'],
'ImagickDraw::color' => ['bool', 'x'=>'float', 'y'=>'float', 'paintmethod'=>'int'],
'ImagickDraw::comment' => ['bool', 'comment'=>'string'],
'ImagickDraw::composite' => ['bool', 'compose'=>'int', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float', 'compositewand'=>'Imagick'],
'ImagickDraw::destroy' => ['bool'],
'ImagickDraw::ellipse' => ['bool', 'ox'=>'float', 'oy'=>'float', 'rx'=>'float', 'ry'=>'float', 'start'=>'float', 'end'=>'float'],
'ImagickDraw::getBorderColor' => ['ImagickPixel'],
'ImagickDraw::getClipPath' => ['string|false'],
'ImagickDraw::getClipRule' => ['int'],
'ImagickDraw::getClipUnits' => ['int'],
'ImagickDraw::getDensity' => ['?string'],
'ImagickDraw::getFillColor' => ['ImagickPixel'],
'ImagickDraw::getFillOpacity' => ['float'],
'ImagickDraw::getFillRule' => ['int'],
'ImagickDraw::getFont' => ['string|false'],
'ImagickDraw::getFontFamily' => ['string|false'],
'ImagickDraw::getFontResolution' => ['array'],
'ImagickDraw::getFontSize' => ['float'],
'ImagickDraw::getFontStretch' => ['int'],
'ImagickDraw::getFontStyle' => ['int'],
'ImagickDraw::getFontWeight' => ['int'],
'ImagickDraw::getGravity' => ['int'],
'ImagickDraw::getOpacity' => ['float'],
'ImagickDraw::getStrokeAntialias' => ['bool'],
'ImagickDraw::getStrokeColor' => ['ImagickPixel'],
'ImagickDraw::getStrokeDashArray' => ['array'],
'ImagickDraw::getStrokeDashOffset' => ['float'],
'ImagickDraw::getStrokeLineCap' => ['int'],
'ImagickDraw::getStrokeLineJoin' => ['int'],
'ImagickDraw::getStrokeMiterLimit' => ['int'],
'ImagickDraw::getStrokeOpacity' => ['float'],
'ImagickDraw::getStrokeWidth' => ['float'],
'ImagickDraw::getTextAlignment' => ['int'],
'ImagickDraw::getTextAntialias' => ['bool'],
'ImagickDraw::getTextDecoration' => ['int'],
'ImagickDraw::getTextDirection' => ['bool'],
'ImagickDraw::getTextEncoding' => ['string'],
'ImagickDraw::getTextInterlineSpacing' => ['float'],
'ImagickDraw::getTextInterwordSpacing' => ['float'],
'ImagickDraw::getTextKerning' => ['float'],
'ImagickDraw::getTextUnderColor' => ['ImagickPixel'],
'ImagickDraw::getVectorGraphics' => ['string'],
'ImagickDraw::line' => ['bool', 'sx'=>'float', 'sy'=>'float', 'ex'=>'float', 'ey'=>'float'],
'ImagickDraw::matte' => ['bool', 'x'=>'float', 'y'=>'float', 'paintmethod'=>'int'],
'ImagickDraw::pathClose' => ['bool'],
'ImagickDraw::pathCurveToAbsolute' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToQuadraticBezierAbsolute' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToQuadraticBezierRelative' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToQuadraticBezierSmoothRelative' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToRelative' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToSmoothAbsolute' => ['bool', 'x2'=>'float', 'y2'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToSmoothRelative' => ['bool', 'x2'=>'float', 'y2'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathEllipticArcAbsolute' => ['bool', 'rx'=>'float', 'ry'=>'float', 'x_axis_rotation'=>'float', 'large_arc_flag'=>'bool', 'sweep_flag'=>'bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathEllipticArcRelative' => ['bool', 'rx'=>'float', 'ry'=>'float', 'x_axis_rotation'=>'float', 'large_arc_flag'=>'bool', 'sweep_flag'=>'bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathFinish' => ['bool'],
'ImagickDraw::pathLineToAbsolute' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathLineToHorizontalAbsolute' => ['bool', 'x'=>'float'],
'ImagickDraw::pathLineToHorizontalRelative' => ['bool', 'x'=>'float'],
'ImagickDraw::pathLineToRelative' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathLineToVerticalAbsolute' => ['bool', 'y'=>'float'],
'ImagickDraw::pathLineToVerticalRelative' => ['bool', 'y'=>'float'],
'ImagickDraw::pathMoveToAbsolute' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathMoveToRelative' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathStart' => ['bool'],
'ImagickDraw::point' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::polygon' => ['bool', 'coordinates'=>'list<array{x:float, y:float}>'],
'ImagickDraw::polyline' => ['bool', 'coordinates'=>'list<array{x:float, y:float}>'],
'ImagickDraw::pop' => ['bool'],
'ImagickDraw::popClipPath' => ['bool'],
'ImagickDraw::popDefs' => ['bool'],
'ImagickDraw::popPattern' => ['bool'],
'ImagickDraw::push' => ['bool'],
'ImagickDraw::pushClipPath' => ['bool', 'clip_mask_id'=>'string'],
'ImagickDraw::pushDefs' => ['bool'],
'ImagickDraw::pushPattern' => ['bool', 'pattern_id'=>'string', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'ImagickDraw::rectangle' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float'],
'ImagickDraw::render' => ['bool'],
'ImagickDraw::resetVectorGraphics' => ['void'],
'ImagickDraw::rotate' => ['bool', 'degrees'=>'float'],
'ImagickDraw::roundRectangle' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'rx'=>'float', 'ry'=>'float'],
'ImagickDraw::scale' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::setBorderColor' => ['bool', 'color'=>'ImagickPixel|string'],
'ImagickDraw::setClipPath' => ['bool', 'clip_mask'=>'string'],
'ImagickDraw::setClipRule' => ['bool', 'fill_rule'=>'int'],
'ImagickDraw::setClipUnits' => ['bool', 'clip_units'=>'int'],
'ImagickDraw::setDensity' => ['bool', 'density_string'=>'string'],
'ImagickDraw::setFillAlpha' => ['bool', 'opacity'=>'float'],
'ImagickDraw::setFillColor' => ['bool', 'fill_pixel'=>'ImagickPixel|string'],
'ImagickDraw::setFillOpacity' => ['bool', 'fillopacity'=>'float'],
'ImagickDraw::setFillPatternURL' => ['bool', 'fill_url'=>'string'],
'ImagickDraw::setFillRule' => ['bool', 'fill_rule'=>'int'],
'ImagickDraw::setFont' => ['bool', 'font_name'=>'string'],
'ImagickDraw::setFontFamily' => ['bool', 'font_family'=>'string'],
'ImagickDraw::setFontResolution' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::setFontSize' => ['bool', 'pointsize'=>'float'],
'ImagickDraw::setFontStretch' => ['bool', 'fontstretch'=>'int'],
'ImagickDraw::setFontStyle' => ['bool', 'style'=>'int'],
'ImagickDraw::setFontWeight' => ['bool', 'font_weight'=>'int'],
'ImagickDraw::setGravity' => ['bool', 'gravity'=>'int'],
'ImagickDraw::setOpacity' => ['void', 'opacity'=>'float'],
'ImagickDraw::setResolution' => ['void', 'x_resolution'=>'float', 'y_resolution'=>'float'],
'ImagickDraw::setStrokeAlpha' => ['bool', 'opacity'=>'float'],
'ImagickDraw::setStrokeAntialias' => ['bool', 'stroke_antialias'=>'bool'],
'ImagickDraw::setStrokeColor' => ['bool', 'stroke_pixel'=>'ImagickPixel|string'],
'ImagickDraw::setStrokeDashArray' => ['bool', 'dasharray'=>'list<int|float>'],
'ImagickDraw::setStrokeDashOffset' => ['bool', 'dash_offset'=>'float'],
'ImagickDraw::setStrokeLineCap' => ['bool', 'linecap'=>'int'],
'ImagickDraw::setStrokeLineJoin' => ['bool', 'linejoin'=>'int'],
'ImagickDraw::setStrokeMiterLimit' => ['bool', 'miterlimit'=>'int'],
'ImagickDraw::setStrokeOpacity' => ['bool', 'stroke_opacity'=>'float'],
'ImagickDraw::setStrokePatternURL' => ['bool', 'stroke_url'=>'string'],
'ImagickDraw::setStrokeWidth' => ['bool', 'stroke_width'=>'float'],
'ImagickDraw::setTextAlignment' => ['bool', 'alignment'=>'int'],
'ImagickDraw::setTextAntialias' => ['bool', 'antialias'=>'bool'],
'ImagickDraw::setTextDecoration' => ['bool', 'decoration'=>'int'],
'ImagickDraw::setTextDirection' => ['bool', 'direction'=>'int'],
'ImagickDraw::setTextEncoding' => ['bool', 'encoding'=>'string'],
'ImagickDraw::setTextInterlineSpacing' => ['void', 'spacing'=>'float'],
'ImagickDraw::setTextInterwordSpacing' => ['void', 'spacing'=>'float'],
'ImagickDraw::setTextKerning' => ['void', 'kerning'=>'float'],
'ImagickDraw::setTextUnderColor' => ['bool', 'under_color'=>'ImagickPixel|string'],
'ImagickDraw::setVectorGraphics' => ['bool', 'xml'=>'string'],
'ImagickDraw::setViewbox' => ['bool', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int'],
'ImagickDraw::skewX' => ['bool', 'degrees'=>'float'],
'ImagickDraw::skewY' => ['bool', 'degrees'=>'float'],
'ImagickDraw::translate' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickKernel::addKernel' => ['void', 'ImagickKernel'=>'ImagickKernel'],
'ImagickKernel::addUnityKernel' => ['void'],
'ImagickKernel::fromBuiltin' => ['ImagickKernel', 'kernelType'=>'string', 'kernelString'=>'string'],
'ImagickKernel::fromMatrix' => ['ImagickKernel', 'matrix'=>'list<list<float>>', 'origin='=>'array'],
'ImagickKernel::getMatrix' => ['list<list<float|false>>'],
'ImagickKernel::scale' => ['void'],
'ImagickKernel::separate' => ['ImagickKernel[]'],
'ImagickKernel::seperate' => ['void'],
'ImagickPixel::__construct' => ['void', 'color='=>'string'],
'ImagickPixel::clear' => ['bool'],
'ImagickPixel::clone' => ['void'],
'ImagickPixel::destroy' => ['bool'],
'ImagickPixel::getColor' => ['array{r: int|float, g: int|float, b: int|float, a: int|float}', 'normalized='=>'0|1|2'],
'ImagickPixel::getColorAsString' => ['string'],
'ImagickPixel::getColorCount' => ['int'],
'ImagickPixel::getColorQuantum' => ['mixed'],
'ImagickPixel::getColorValue' => ['float', 'color'=>'int'],
'ImagickPixel::getColorValueQuantum' => ['mixed'],
'ImagickPixel::getHSL' => ['array{hue: float, saturation: float, luminosity: float}'],
'ImagickPixel::getIndex' => ['int'],
'ImagickPixel::isPixelSimilar' => ['bool', 'color'=>'ImagickPixel', 'fuzz'=>'float'],
'ImagickPixel::isPixelSimilarQuantum' => ['bool', 'color'=>'string', 'fuzz='=>'string'],
'ImagickPixel::isSimilar' => ['bool', 'color'=>'ImagickPixel', 'fuzz'=>'float'],
'ImagickPixel::setColor' => ['bool', 'color'=>'string'],
'ImagickPixel::setcolorcount' => ['void', 'colorCount'=>'string'],
'ImagickPixel::setColorFromPixel' => ['bool', 'srcPixel'=>'ImagickPixel'],
'ImagickPixel::setColorValue' => ['bool', 'color'=>'int', 'value'=>'float'],
'ImagickPixel::setColorValueQuantum' => ['void', 'color'=>'int', 'value'=>'mixed'],
'ImagickPixel::setHSL' => ['bool', 'hue'=>'float', 'saturation'=>'float', 'luminosity'=>'float'],
'ImagickPixel::setIndex' => ['void', 'index'=>'int'],
'ImagickPixelIterator::__construct' => ['void', 'wand'=>'Imagick'],
'ImagickPixelIterator::clear' => ['bool'],
'ImagickPixelIterator::current' => ['mixed'],
'ImagickPixelIterator::destroy' => ['bool'],
'ImagickPixelIterator::getCurrentIteratorRow' => ['array'],
'ImagickPixelIterator::getIteratorRow' => ['int'],
'ImagickPixelIterator::getNextIteratorRow' => ['array'],
'ImagickPixelIterator::getpixeliterator' => ['', 'Imagick'=>'Imagick'],
'ImagickPixelIterator::getpixelregioniterator' => ['', 'Imagick'=>'Imagick', 'x'=>'', 'y'=>'', 'columns'=>'', 'rows'=>''],
'ImagickPixelIterator::getPreviousIteratorRow' => ['array'],
'ImagickPixelIterator::key' => ['int|string'],
'ImagickPixelIterator::newPixelIterator' => ['bool', 'wand'=>'Imagick'],
'ImagickPixelIterator::newPixelRegionIterator' => ['bool', 'wand'=>'Imagick', 'x'=>'int', 'y'=>'int', 'columns'=>'int', 'rows'=>'int'],
'ImagickPixelIterator::next' => ['void'],
'ImagickPixelIterator::resetIterator' => ['bool'],
'ImagickPixelIterator::rewind' => ['void'],
'ImagickPixelIterator::setIteratorFirstRow' => ['bool'],
'ImagickPixelIterator::setIteratorLastRow' => ['bool'],
'ImagickPixelIterator::setIteratorRow' => ['bool', 'row'=>'int'],
'ImagickPixelIterator::syncIterator' => ['bool'],
'ImagickPixelIterator::valid' => ['bool'],
'imap_8bit' => ['string|false', 'string'=>'string'],
'imap_alerts' => ['array|false'],
'imap_append' => ['bool', 'imap'=>'IMAP\Connection', 'folder'=>'string', 'message'=>'string', 'options='=>'string', 'internal_date='=>'string'],
'imap_base64' => ['string|false', 'string'=>'string'],
'imap_binary' => ['string|false', 'string'=>'string'],
'imap_body' => ['string|false', 'imap'=>'IMAP\Connection', 'message_num'=>'int', 'flags='=>'int'],
'imap_bodystruct' => ['stdClass|false', 'imap'=>'IMAP\Connection', 'message_num'=>'int', 'section'=>'string'],
'imap_check' => ['stdClass|false', 'imap'=>'IMAP\Connection'],
'imap_clearflag_full' => ['bool', 'imap'=>'IMAP\Connection', 'sequence'=>'string', 'flag'=>'string', 'options='=>'int'],
'imap_close' => ['bool', 'imap'=>'IMAP\Connection', 'flags='=>'int'],
'imap_create' => ['bool', 'imap'=>'IMAP\Connection', 'mailbox'=>'string'],
'imap_createmailbox' => ['bool', 'imap'=>'IMAP\Connection', 'mailbox'=>'string'],
'imap_delete' => ['bool', 'imap'=>'IMAP\Connection', 'message_num'=>'int', 'flags='=>'int'],
'imap_deletemailbox' => ['bool', 'imap'=>'IMAP\Connection', 'mailbox'=>'string'],
'imap_errors' => ['array|false'],
'imap_expunge' => ['bool', 'imap'=>'IMAP\Connection'],
'imap_fetch_overview' => ['array|false', 'imap'=>'IMAP\Connection', 'sequence'=>'string', 'flags='=>'int'],
'imap_fetchbody' => ['string|false', 'imap'=>'IMAP\Connection', 'message_num'=>'int', 'section'=>'string', 'flags='=>'int'],
'imap_fetchheader' => ['string|false', 'imap'=>'IMAP\Connection', 'message_num'=>'int', 'flags='=>'int'],
'imap_fetchmime' => ['string|false', 'imap'=>'IMAP\Connection', 'message_num'=>'int', 'section'=>'string', 'flags='=>'int'],
'imap_fetchstructure' => ['stdClass|false', 'imap'=>'IMAP\Connection', 'message_num'=>'int', 'flags='=>'int'],
'imap_fetchtext' => ['string|false', 'imap'=>'IMAP\Connection', 'message_num'=>'int', 'flags='=>'int'],
'imap_gc' => ['bool', 'imap'=>'IMAP\Connection', 'flags'=>'int'],
'imap_get_quota' => ['array|false', 'imap'=>'IMAP\Connection', 'quota_root'=>'string'],
'imap_get_quotaroot' => ['array|false', 'imap'=>'IMAP\Connection', 'mailbox'=>'string'],
'imap_getacl' => ['array|false', 'imap'=>'IMAP\Connection', 'mailbox'=>'string'],
'imap_getmailboxes' => ['array|false', 'imap'=>'IMAP\Connection', 'reference'=>'string', 'pattern'=>'string'],
'imap_getsubscribed' => ['array|false', 'imap'=>'IMAP\Connection', 'reference'=>'string', 'pattern'=>'string'],
'imap_header' => ['stdClass|false', 'stream_id'=>'resource', 'msg_no'=>'int', 'from_length='=>'int', 'subject_length='=>'int', 'default_host='=>'string'],
'imap_headerinfo' => ['stdClass|false', 'imap'=>'IMAP\Connection', 'message_num'=>'int', 'from_length='=>'int', 'subject_length='=>'int', 'default_host='=>'string|null'],
'imap_headers' => ['array|false', 'imap'=>'IMAP\Connection'],
'imap_last_error' => ['string|false'],
'imap_list' => ['array|false', 'imap'=>'IMAP\Connection', 'reference'=>'string', 'pattern'=>'string'],
'imap_listmailbox' => ['array|false', 'imap'=>'IMAP\Connection', 'reference'=>'string', 'pattern'=>'string'],
'imap_listscan' => ['array|false', 'imap'=>'IMAP\Connection', 'reference'=>'string', 'pattern'=>'string', 'content'=>'string'],
'imap_listsubscribed' => ['array|false', 'imap'=>'IMAP\Connection', 'reference'=>'string', 'pattern'=>'string'],
'imap_lsub' => ['array|false', 'imap'=>'IMAP\Connection', 'reference'=>'string', 'pattern'=>'string'],
'imap_mail' => ['bool', 'to'=>'string', 'subject'=>'string', 'message'=>'string', 'additional_headers='=>'string', 'cc='=>'string', 'bcc='=>'string', 'return_path='=>'string'],
'imap_mail_compose' => ['string|false', 'envelope'=>'array', 'bodies'=>'array'],
'imap_mail_copy' => ['bool', 'imap'=>'IMAP\Connection', 'message_nums'=>'string', 'mailbox'=>'string', 'flags='=>'int'],
'imap_mail_move' => ['bool', 'imap'=>'IMAP\Connection', 'message_nums'=>'string', 'mailbox'=>'string', 'flags='=>'int'],
'imap_mailboxmsginfo' => ['stdClass|false', 'imap'=>'IMAP\Connection'],
'imap_mime_header_decode' => ['array|false', 'string'=>'string'],
'imap_msgno' => ['int|false', 'imap'=>'IMAP\Connection', 'message_uid'=>'int'],
'imap_mutf7_to_utf8' => ['string|false', 'string'=>'string'],
'imap_num_msg' => ['int|false', 'imap'=>'IMAP\Connection'],
'imap_num_recent' => ['int|false', 'imap'=>'IMAP\Connection'],
'imap_open' => ['IMAP\Connection|false', 'mailbox'=>'string', 'user'=>'string', 'password'=>'string', 'flags='=>'int', 'retries='=>'int', 'options='=>'?array'],
'imap_ping' => ['bool', 'imap'=>'IMAP\Connection'],
'imap_qprint' => ['string|false', 'string'=>'string'],
'imap_rename' => ['bool', 'imap'=>'IMAP\Connection', 'from'=>'string', 'to'=>'string'],
'imap_renamemailbox' => ['bool', 'imap'=>'IMAP\Connection', 'from'=>'string', 'to'=>'string'],
'imap_reopen' => ['bool', 'imap'=>'IMAP\Connection', 'mailbox'=>'string', 'flags='=>'int', 'retries='=>'int'],
'imap_rfc822_parse_adrlist' => ['array', 'string'=>'string', 'default_hostname'=>'string'],
'imap_rfc822_parse_headers' => ['stdClass', 'headers'=>'string', 'default_hostname='=>'string'],
'imap_rfc822_write_address' => ['string|false', 'mailbox'=>'?string', 'hostname'=>'?string', 'personal'=>'?string'],
'imap_savebody' => ['bool', 'imap'=>'IMAP\Connection', 'file'=>'string|resource', 'message_num'=>'int', 'section='=>'string', 'flags='=>'int'],
'imap_scan' => ['array|false', 'imap'=>'IMAP\Connection', 'reference'=>'string', 'pattern'=>'string', 'content'=>'string'],
'imap_scanmailbox' => ['array|false', 'imap'=>'IMAP\Connection', 'reference'=>'string', 'pattern'=>'string', 'content'=>'string'],
'imap_search' => ['array|false', 'imap'=>'IMAP\Connection', 'criteria'=>'string', 'flags='=>'int', 'charset='=>'string'],
'imap_set_quota' => ['bool', 'imap'=>'IMAP\Connection', 'quota_root'=>'string', 'mailbox_size'=>'int'],
'imap_setacl' => ['bool', 'imap'=>'IMAP\Connection', 'mailbox'=>'string', 'user_id'=>'string', 'rights'=>'string'],
'imap_setflag_full' => ['bool', 'imap'=>'IMAP\Connection', 'sequence'=>'string', 'flag'=>'string', 'options='=>'int'],
'imap_sort' => ['array|false', 'imap'=>'IMAP\Connection', 'criteria'=>'int', 'reverse'=>'int', 'flags='=>'int', 'search_criteria='=>'string', 'charset='=>'string'],
'imap_status' => ['stdClass|false', 'imap'=>'IMAP\Connection', 'mailbox'=>'string', 'flags'=>'int'],
'imap_subscribe' => ['bool', 'imap'=>'IMAP\Connection', 'mailbox'=>'string'],
'imap_thread' => ['array|false', 'imap'=>'IMAP\Connection', 'flags='=>'int'],
'imap_timeout' => ['int|bool', 'timeout_type'=>'int', 'timeout='=>'int'],
'imap_uid' => ['int|false', 'imap'=>'IMAP\Connection', 'message_num'=>'int'],
'imap_undelete' => ['bool', 'imap'=>'IMAP\Connection', 'message_num'=>'int', 'flags='=>'int'],
'imap_unsubscribe' => ['bool', 'imap'=>'IMAP\Connection', 'mailbox'=>'string'],
'imap_utf7_decode' => ['string|false', 'string'=>'string'],
'imap_utf7_encode' => ['string', 'string'=>'string'],
'imap_utf8' => ['string', 'mime_encoded_text'=>'string'],
'imap_utf8_to_mutf7' => ['string|false', 'string'=>'string'],
'implode' => ['string', 'separator'=>'string', 'array'=>'array'],
'implode\'1' => ['string', 'separator'=>'array'],
'import_request_variables' => ['bool', 'types'=>'string', 'prefix='=>'string'],
'in_array' => ['bool', 'needle'=>'mixed', 'haystack'=>'array', 'strict='=>'bool'],
'inclued_get_data' => ['array'],
'inet_ntop' => ['string|false', 'ip'=>'string'],
'inet_pton' => ['string|false', 'ip'=>'string'],
'InfiniteIterator::__construct' => ['void', 'iterator'=>'Iterator'],
'InfiniteIterator::current' => ['mixed'],
'InfiniteIterator::getInnerIterator' => ['Iterator'],
'InfiniteIterator::key' => ['bool|float|int|string'],
'InfiniteIterator::next' => ['void'],
'InfiniteIterator::rewind' => ['void'],
'InfiniteIterator::valid' => ['bool'],
'inflate_add' => ['string|false', 'context'=>'resource', 'data'=>'string', 'flush_mode='=>'int'],
'inflate_get_read_len' => ['int|false', 'context'=>'resource'],
'inflate_get_status' => ['int|false', 'context'=>'resource'],
'inflate_init' => ['resource|false', 'encoding'=>'int', 'options='=>'array'],
'ingres_autocommit' => ['bool', 'link'=>'resource'],
'ingres_autocommit_state' => ['bool', 'link'=>'resource'],
'ingres_charset' => ['string', 'link'=>'resource'],
'ingres_close' => ['bool', 'link'=>'resource'],
'ingres_commit' => ['bool', 'link'=>'resource'],
'ingres_connect' => ['resource', 'database='=>'string', 'username='=>'string', 'password='=>'string', 'options='=>'array'],
'ingres_cursor' => ['string', 'result'=>'resource'],
'ingres_errno' => ['int', 'link='=>'resource'],
'ingres_error' => ['string', 'link='=>'resource'],
'ingres_errsqlstate' => ['string', 'link='=>'resource'],
'ingres_escape_string' => ['string', 'link'=>'resource', 'source_string'=>'string'],
'ingres_execute' => ['bool', 'result'=>'resource', 'params='=>'array', 'types='=>'string'],
'ingres_fetch_array' => ['array', 'result'=>'resource', 'result_type='=>'int'],
'ingres_fetch_assoc' => ['array', 'result'=>'resource'],
'ingres_fetch_object' => ['object', 'result'=>'resource', 'result_type='=>'int'],
'ingres_fetch_proc_return' => ['int', 'result'=>'resource'],
'ingres_fetch_row' => ['array', 'result'=>'resource'],
'ingres_field_length' => ['int', 'result'=>'resource', 'index'=>'int'],
'ingres_field_name' => ['string', 'result'=>'resource', 'index'=>'int'],
'ingres_field_nullable' => ['bool', 'result'=>'resource', 'index'=>'int'],
'ingres_field_precision' => ['int', 'result'=>'resource', 'index'=>'int'],
'ingres_field_scale' => ['int', 'result'=>'resource', 'index'=>'int'],
'ingres_field_type' => ['string', 'result'=>'resource', 'index'=>'int'],
'ingres_free_result' => ['bool', 'result'=>'resource'],
'ingres_next_error' => ['bool', 'link='=>'resource'],
'ingres_num_fields' => ['int', 'result'=>'resource'],
'ingres_num_rows' => ['int', 'result'=>'resource'],
'ingres_pconnect' => ['resource', 'database='=>'string', 'username='=>'string', 'password='=>'string', 'options='=>'array'],
'ingres_prepare' => ['mixed', 'link'=>'resource', 'query'=>'string'],
'ingres_query' => ['mixed', 'link'=>'resource', 'query'=>'string', 'params='=>'array', 'types='=>'string'],
'ingres_result_seek' => ['bool', 'result'=>'resource', 'position'=>'int'],
'ingres_rollback' => ['bool', 'link'=>'resource'],
'ingres_set_environment' => ['bool', 'link'=>'resource', 'options'=>'array'],
'ingres_unbuffered_query' => ['mixed', 'link'=>'resource', 'query'=>'string', 'params='=>'array', 'types='=>'string'],
'ini_alter' => ['string|false', 'option'=>'string', 'value'=>'string'],
'ini_get' => ['string|false', 'option'=>'string'],
'ini_get_all' => ['array|false', 'extension='=>'?string', 'details='=>'bool'],
'ini_restore' => ['void', 'option'=>'string'],
'ini_set' => ['string|false', 'option'=>'string', 'value'=>'string'],
'inotify_add_watch' => ['int', 'inotify_instance'=>'resource', 'pathname'=>'string', 'mask'=>'int'],
'inotify_init' => ['resource|false'],
'inotify_queue_len' => ['int', 'inotify_instance'=>'resource'],
'inotify_read' => ['array|false', 'inotify_instance'=>'resource'],
'inotify_rm_watch' => ['bool', 'inotify_instance'=>'resource', 'watch_descriptor'=>'int'],
'intdiv' => ['int', 'num1'=>'int', 'num2'=>'int'],
'interface_exists' => ['bool', 'interface'=>'string', 'autoload='=>'bool'],
'intl_error_name' => ['string', 'errorCode'=>'int'],
'intl_get_error_code' => ['int'],
'intl_get_error_message' => ['string'],
'intl_is_failure' => ['bool', 'errorCode'=>'int'],
'IntlBreakIterator::__construct' => ['void'],
'IntlBreakIterator::createCharacterInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlBreakIterator::createCodePointInstance' => ['IntlCodePointBreakIterator'],
'IntlBreakIterator::createLineInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlBreakIterator::createSentenceInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlBreakIterator::createTitleInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlBreakIterator::createWordInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlBreakIterator::current' => ['int'],
'IntlBreakIterator::first' => ['int'],
'IntlBreakIterator::following' => ['int', 'offset'=>'int'],
'IntlBreakIterator::getErrorCode' => ['int'],
'IntlBreakIterator::getErrorMessage' => ['string'],
'IntlBreakIterator::getLocale' => ['string', 'locale_type'=>'string'],
'IntlBreakIterator::getPartsIterator' => ['IntlPartsIterator', 'key_type='=>'int'],
'IntlBreakIterator::getText' => ['string'],
'IntlBreakIterator::isBoundary' => ['bool', 'offset'=>'int'],
'IntlBreakIterator::last' => ['int'],
'IntlBreakIterator::next' => ['int', 'offset='=>'int'],
'IntlBreakIterator::preceding' => ['int', 'offset'=>'int'],
'IntlBreakIterator::previous' => ['int'],
'IntlBreakIterator::setText' => ['bool', 'text'=>'string'],
'intlcal_add' => ['bool', 'calendar'=>'IntlCalendar', 'field'=>'int', 'value'=>'int'],
'intlcal_after' => ['bool', 'calendar'=>'IntlCalendar', 'other'=>'IntlCalendar'],
'intlcal_before' => ['bool', 'calendar'=>'IntlCalendar', 'other'=>'IntlCalendar'],
'intlcal_clear' => ['bool', 'calendar'=>'IntlCalendar', 'field='=>'int'],
'intlcal_create_instance' => ['IntlCalendar', 'timezone='=>'mixed', 'locale='=>'string'],
'intlcal_equals' => ['bool', 'calendar'=>'IntlCalendar', 'other'=>'IntlCalendar'],
'intlcal_field_difference' => ['int', 'calendar'=>'IntlCalendar', 'timestamp'=>'float', 'field'=>'int'],
'intlcal_from_date_time' => ['IntlCalendar', 'datetime'=>'DateTime|string'],
'intlcal_get' => ['mixed', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_actual_maximum' => ['int', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_actual_minimum' => ['int', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_available_locales' => ['array'],
'intlcal_get_day_of_week_type' => ['int', 'calendar'=>'IntlCalendar', 'dayOfWeek'=>'int'],
'intlcal_get_first_day_of_week' => ['int', 'calendar'=>'IntlCalendar'],
'intlcal_get_greatest_minimum' => ['int', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_keyword_values_for_locale' => ['Iterator|false', 'keyword'=>'string', 'locale'=>'string', 'onlyCommon'=>'bool'],
'intlcal_get_least_maximum' => ['int', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_locale' => ['string', 'calendar'=>'IntlCalendar', 'type'=>'int'],
'intlcal_get_maximum' => ['int|false', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_minimal_days_in_first_week' => ['int', 'calendar'=>'IntlCalendar'],
'intlcal_get_minimum' => ['int', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_now' => ['float'],
'intlcal_get_repeated_wall_time_option' => ['int', 'calendar'=>'IntlCalendar'],
'intlcal_get_skipped_wall_time_option' => ['int', 'calendar'=>'IntlCalendar'],
'intlcal_get_time' => ['float', 'calendar'=>'IntlCalendar'],
'intlcal_get_time_zone' => ['IntlTimeZone', 'calendar'=>'IntlCalendar'],
'intlcal_get_type' => ['string', 'calendar'=>'IntlCalendar'],
'intlcal_get_weekend_transition' => ['int', 'calendar'=>'IntlCalendar', 'dayOfWeek'=>'string'],
'intlcal_in_daylight_time' => ['bool', 'calendar'=>'IntlCalendar'],
'intlcal_is_equivalent_to' => ['bool', 'calendar'=>'IntlCalendar', 'other'=>'IntlCalendar'],
'intlcal_is_lenient' => ['bool', 'calendar'=>'IntlCalendar'],
'intlcal_is_set' => ['bool', 'calendar'=>'IntlCalendar', 'field'=>'int'],
'intlcal_is_weekend' => ['bool', 'calendar'=>'IntlCalendar', 'timestamp='=>'float'],
'intlcal_roll' => ['bool', 'calendar'=>'IntlCalendar', 'field'=>'int', 'value'=>'mixed'],
'intlcal_set' => ['bool', 'calendar'=>'IntlCalendar', 'year'=>'int', 'month'=>'int'],
'intlcal_set\'1' => ['bool', 'calendar'=>'IntlCalendar', 'year'=>'int', 'month'=>'int', 'dayOfMonth='=>'int', 'hour='=>'int', 'minute='=>'int', 'second='=>'int'],
'intlcal_set_first_day_of_week' => ['bool', 'calendar'=>'IntlCalendar', 'dayOfWeek'=>'int'],
'intlcal_set_lenient' => ['bool', 'calendar'=>'IntlCalendar', 'lenient'=>'bool'],
'intlcal_set_repeated_wall_time_option' => ['bool', 'calendar'=>'IntlCalendar', 'option'=>'int'],
'intlcal_set_skipped_wall_time_option' => ['bool', 'calendar'=>'IntlCalendar', 'option'=>'int'],
'intlcal_set_time' => ['bool', 'calendar'=>'IntlCalendar', 'timestamp'=>'float'],
'intlcal_set_time_zone' => ['bool', 'calendar'=>'IntlCalendar', 'timezone'=>'mixed'],
'intlcal_to_date_time' => ['DateTime|false', 'calendar'=>'IntlCalendar'],
'IntlCalendar::__construct' => ['void'],
'IntlCalendar::add' => ['bool', 'field'=>'int', 'amount'=>'int'],
'IntlCalendar::after' => ['bool', 'other'=>'IntlCalendar'],
'IntlCalendar::before' => ['bool', 'other'=>'IntlCalendar'],
'IntlCalendar::clear' => ['bool', 'field='=>'int'],
'IntlCalendar::createInstance' => ['IntlCalendar', 'timeZone='=>'mixed', 'locale='=>'string'],
'IntlCalendar::equals' => ['bool', 'other'=>'IntlCalendar'],
'IntlCalendar::fieldDifference' => ['int', 'when'=>'float', 'field'=>'int'],
'IntlCalendar::fromDateTime' => ['IntlCalendar', 'dateTime'=>'DateTime|string'],
'IntlCalendar::get' => ['int', 'field'=>'int'],
'IntlCalendar::getActualMaximum' => ['int', 'field'=>'int'],
'IntlCalendar::getActualMinimum' => ['int', 'field'=>'int'],
'IntlCalendar::getAvailableLocales' => ['array'],
'IntlCalendar::getDayOfWeekType' => ['int', 'dayOfWeek'=>'int'],
'IntlCalendar::getErrorCode' => ['int'],
'IntlCalendar::getErrorMessage' => ['string'],
'IntlCalendar::getFirstDayOfWeek' => ['int'],
'IntlCalendar::getGreatestMinimum' => ['int', 'field'=>'int'],
'IntlCalendar::getKeywordValuesForLocale' => ['Iterator|false', 'key'=>'string', 'locale'=>'string', 'commonlyUsed'=>'bool'],
'IntlCalendar::getLeastMaximum' => ['int', 'field'=>'int'],
'IntlCalendar::getLocale' => ['string', 'localeType'=>'int'],
'IntlCalendar::getMaximum' => ['int|false', 'field'=>'int'],
'IntlCalendar::getMinimalDaysInFirstWeek' => ['int'],
'IntlCalendar::getMinimum' => ['int', 'field'=>'int'],
'IntlCalendar::getNow' => ['float'],
'IntlCalendar::getRepeatedWallTimeOption' => ['int'],
'IntlCalendar::getSkippedWallTimeOption' => ['int'],
'IntlCalendar::getTime' => ['float'],
'IntlCalendar::getTimeZone' => ['IntlTimeZone'],
'IntlCalendar::getType' => ['string'],
'IntlCalendar::getWeekendTransition' => ['int', 'dayOfWeek'=>'string'],
'IntlCalendar::inDaylightTime' => ['bool'],
'IntlCalendar::isEquivalentTo' => ['bool', 'other'=>'IntlCalendar'],
'IntlCalendar::isLenient' => ['bool'],
'IntlCalendar::isSet' => ['bool', 'field'=>'int'],
'IntlCalendar::isWeekend' => ['bool', 'date='=>'float'],
'IntlCalendar::roll' => ['bool', 'field'=>'int', 'amountOrUpOrDown'=>'mixed'],
'IntlCalendar::set' => ['bool', 'field'=>'int', 'value'=>'int'],
'IntlCalendar::set\'1' => ['bool', 'year'=>'int', 'month'=>'int', 'dayOfMonth='=>'int', 'hour='=>'int', 'minute='=>'int', 'second='=>'int'],
'IntlCalendar::setFirstDayOfWeek' => ['bool', 'dayOfWeek'=>'int'],
'IntlCalendar::setLenient' => ['bool', 'isLenient'=>'string'],
'IntlCalendar::setMinimalDaysInFirstWeek' => ['bool', 'minimalDays'=>'int'],
'IntlCalendar::setRepeatedWallTimeOption' => ['bool', 'wallTimeOption'=>'int'],
'IntlCalendar::setSkippedWallTimeOption' => ['bool', 'wallTimeOption'=>'int'],
'IntlCalendar::setTime' => ['bool', 'date'=>'float'],
'IntlCalendar::setTimeZone' => ['bool', 'timeZone'=>'mixed'],
'IntlCalendar::toDateTime' => ['DateTime|false'],
'IntlChar::charAge' => ['array', 'char'=>'int|string'],
'IntlChar::charDigitValue' => ['int', 'codepoint'=>'mixed'],
'IntlChar::charDirection' => ['int', 'codepoint'=>'mixed'],
'IntlChar::charFromName' => ['?int', 'name'=>'string', 'namechoice='=>'int'],
'IntlChar::charMirror' => ['mixed', 'codepoint'=>'mixed'],
'IntlChar::charName' => ['string', 'char'=>'int|string', 'namechoice='=>'int'],
'IntlChar::charType' => ['int', 'codepoint'=>'mixed'],
'IntlChar::chr' => ['string', 'codepoint'=>'mixed'],
'IntlChar::digit' => ['int|false', 'char'=>'int|string', 'radix='=>'int'],
'IntlChar::enumCharNames' => ['void', 'start'=>'mixed', 'limit'=>'mixed', 'callback'=>'callable', 'nameChoice='=>'int'],
'IntlChar::enumCharTypes' => ['void', 'cb='=>'callable'],
'IntlChar::foldCase' => ['int|string', 'char'=>'int|string', 'options='=>'int'],
'IntlChar::forDigit' => ['int', 'digit'=>'int', 'radix'=>'int'],
'IntlChar::getBidiPairedBracket' => ['mixed', 'codepoint'=>'mixed'],
'IntlChar::getBlockCode' => ['int', 'char'=>'int|string'],
'IntlChar::getCombiningClass' => ['int', 'codepoint'=>'mixed'],
'IntlChar::getFC_NFKC_Closure' => ['string', 'char'=>'int|string'],
'IntlChar::getIntPropertyMaxValue' => ['int', 'property'=>'int'],
'IntlChar::getIntPropertyMinValue' => ['int', 'property'=>'int'],
'IntlChar::getIntPropertyMxValue' => ['int', 'property'=>'int'],
'IntlChar::getIntPropertyValue' => ['int', 'char'=>'int|string', 'property'=>'int'],
'IntlChar::getNumericValue' => ['float', 'char'=>'int|string'],
'IntlChar::getPropertyEnum' => ['int', 'alias'=>'string'],
'IntlChar::getPropertyName' => ['string|false', 'property'=>'int', 'namechoice='=>'int'],
'IntlChar::getPropertyValueEnum' => ['int', 'property'=>'int', 'name'=>'string'],
'IntlChar::getPropertyValueName' => ['string|false', 'prop'=>'int', 'value'=>'int', 'namechoice='=>'int'],
'IntlChar::getUnicodeVersion' => ['array'],
'IntlChar::hasBinaryProperty' => ['bool', 'char'=>'int|string', 'property'=>'int'],
'IntlChar::isalnum' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isalpha' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isbase' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isblank' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::iscntrl' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isdefined' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isdigit' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isgraph' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isIDIgnorable' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isIDPart' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isIDStart' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isISOControl' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isJavaIDPart' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isJavaIDStart' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isJavaSpaceChar' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::islower' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isMirrored' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isprint' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::ispunct' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isspace' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::istitle' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isUAlphabetic' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isULowercase' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isupper' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isUUppercase' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isUWhiteSpace' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isWhitespace' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isxdigit' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::ord' => ['int', 'character'=>'mixed'],
'IntlChar::tolower' => ['mixed', 'codepoint'=>'mixed'],
'IntlChar::totitle' => ['mixed', 'codepoint'=>'mixed'],
'IntlChar::toupper' => ['mixed', 'codepoint'=>'mixed'],
'IntlCodePointBreakIterator::__construct' => ['void'],
'IntlCodePointBreakIterator::createCharacterInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlCodePointBreakIterator::createCodePointInstance' => ['IntlCodePointBreakIterator'],
'IntlCodePointBreakIterator::createLineInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlCodePointBreakIterator::createSentenceInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlCodePointBreakIterator::createTitleInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlCodePointBreakIterator::createWordInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlCodePointBreakIterator::current' => ['int'],
'IntlCodePointBreakIterator::first' => ['int'],
'IntlCodePointBreakIterator::following' => ['int', 'offset'=>'string'],
'IntlCodePointBreakIterator::getErrorCode' => ['int'],
'IntlCodePointBreakIterator::getErrorMessage' => ['string'],
'IntlCodePointBreakIterator::getLastCodePoint' => ['int'],
'IntlCodePointBreakIterator::getLocale' => ['string', 'locale_type'=>'string'],
'IntlCodePointBreakIterator::getPartsIterator' => ['IntlPartsIterator', 'key_type='=>'string'],
'IntlCodePointBreakIterator::getText' => ['string'],
'IntlCodePointBreakIterator::isBoundary' => ['bool', 'offset'=>'string'],
'IntlCodePointBreakIterator::last' => ['int'],
'IntlCodePointBreakIterator::next' => ['int', 'offset='=>'string'],
'IntlCodePointBreakIterator::preceding' => ['int', 'offset'=>'string'],
'IntlCodePointBreakIterator::previous' => ['int'],
'IntlCodePointBreakIterator::setText' => ['bool', 'text'=>'string'],
'IntlDateFormatter::__construct' => ['void', 'locale'=>'?string', 'datetype'=>'?int', 'timetype'=>'?int', 'timezone='=>'null|string|IntlTimeZone|DateTimeZone', 'calendar='=>'null|int|IntlCalendar', 'pattern='=>'string'],
'IntlDateFormatter::create' => ['IntlDateFormatter|false', 'locale'=>'?string', 'datetype'=>'?int', 'timetype'=>'?int', 'timezone='=>'null|string|IntlTimeZone|DateTimeZone', 'calendar='=>'int|IntlCalendar', 'pattern='=>'string'],
'IntlDateFormatter::format' => ['string|false', 'args'=>''],
'IntlDateFormatter::formatObject' => ['string|false', 'object'=>'object', 'format='=>'mixed', 'locale='=>'string'],
'IntlDateFormatter::getCalendar' => ['int'],
'IntlDateFormatter::getCalendarObject' => ['IntlCalendar'],
'IntlDateFormatter::getDateType' => ['int'],
'IntlDateFormatter::getErrorCode' => ['int'],
'IntlDateFormatter::getErrorMessage' => ['string'],
'IntlDateFormatter::getLocale' => ['string|false'],
'IntlDateFormatter::getPattern' => ['string'],
'IntlDateFormatter::getTimeType' => ['int'],
'IntlDateFormatter::getTimeZone' => ['IntlTimeZone|false'],
'IntlDateFormatter::getTimeZoneId' => ['string'],
'IntlDateFormatter::isLenient' => ['bool'],
'IntlDateFormatter::localtime' => ['array', 'text_to_parse'=>'string', '&w_parse_pos='=>'int'],
'IntlDateFormatter::parse' => ['int|false', 'text_to_parse'=>'string', '&rw_parse_pos='=>'int'],
'IntlDateFormatter::setCalendar' => ['bool', 'calendar'=>''],
'IntlDateFormatter::setLenient' => ['bool', 'lenient'=>'bool'],
'IntlDateFormatter::setPattern' => ['bool', 'pattern'=>'string'],
'IntlDateFormatter::setTimeZone' => ['bool', 'timezone'=>''],
'IntlDateFormatter::setTimeZoneId' => ['bool', 'zone'=>'string', 'fmt='=>'IntlDateFormatter'],
'IntlException::__clone' => ['void'],
'IntlException::__construct' => ['void'],
'IntlException::__toString' => ['string'],
'IntlException::__wakeup' => ['void'],
'IntlException::getCode' => ['int'],
'IntlException::getFile' => ['string'],
'IntlException::getLine' => ['int'],
'IntlException::getMessage' => ['string'],
'IntlException::getPrevious' => ['?Throwable'],
'IntlException::getTrace' => ['list<array<string,mixed>>'],
'IntlException::getTraceAsString' => ['string'],
'intlgregcal_create_instance' => ['IntlGregorianCalendar', 'timezoneOrYear='=>'mixed', 'localeOrMonth='=>'string'],
'intlgregcal_get_gregorian_change' => ['float', 'calendar'=>'IntlGregorianCalendar'],
'intlgregcal_is_leap_year' => ['bool', 'calendar'=>'int'],
'intlgregcal_set_gregorian_change' => ['void', 'calendar'=>'IntlGregorianCalendar', 'timestamp'=>'float'],
'IntlGregorianCalendar::__construct' => ['void'],
'IntlGregorianCalendar::add' => ['bool', 'field'=>'int', 'amount'=>'int'],
'IntlGregorianCalendar::after' => ['bool', 'other'=>'IntlCalendar'],
'IntlGregorianCalendar::before' => ['bool', 'other'=>'IntlCalendar'],
'IntlGregorianCalendar::clear' => ['bool', 'field='=>'int'],
'IntlGregorianCalendar::createInstance' => ['IntlGregorianCalendar', 'timeZone='=>'mixed', 'locale='=>'string'],
'IntlGregorianCalendar::equals' => ['bool', 'other'=>'IntlCalendar'],
'IntlGregorianCalendar::fieldDifference' => ['int', 'when'=>'float', 'field'=>'int'],
'IntlGregorianCalendar::fromDateTime' => ['IntlCalendar', 'dateTime'=>'DateTime|string'],
'IntlGregorianCalendar::get' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getActualMaximum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getActualMinimum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getAvailableLocales' => ['array'],
'IntlGregorianCalendar::getDayOfWeekType' => ['int', 'dayOfWeek'=>'int'],
'IntlGregorianCalendar::getErrorCode' => ['int'],
'IntlGregorianCalendar::getErrorMessage' => ['string'],
'IntlGregorianCalendar::getFirstDayOfWeek' => ['int'],
'IntlGregorianCalendar::getGreatestMinimum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getGregorianChange' => ['float'],
'IntlGregorianCalendar::getKeywordValuesForLocale' => ['Iterator', 'key'=>'string', 'locale'=>'string', 'commonlyUsed'=>'bool'],
'IntlGregorianCalendar::getLeastMaximum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getLocale' => ['string', 'localeType'=>'int'],
'IntlGregorianCalendar::getMaximum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getMinimalDaysInFirstWeek' => ['int'],
'IntlGregorianCalendar::getMinimum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getNow' => ['float'],
'IntlGregorianCalendar::getRepeatedWallTimeOption' => ['int'],
'IntlGregorianCalendar::getSkippedWallTimeOption' => ['int'],
'IntlGregorianCalendar::getTime' => ['float'],
'IntlGregorianCalendar::getTimeZone' => ['IntlTimeZone'],
'IntlGregorianCalendar::getType' => ['string'],
'IntlGregorianCalendar::getWeekendTransition' => ['int', 'dayOfWeek'=>'string'],
'IntlGregorianCalendar::inDaylightTime' => ['bool'],
'IntlGregorianCalendar::isEquivalentTo' => ['bool', 'other'=>'IntlCalendar'],
'IntlGregorianCalendar::isLeapYear' => ['bool', 'year'=>'int'],
'IntlGregorianCalendar::isLenient' => ['bool'],
'IntlGregorianCalendar::isSet' => ['bool', 'field'=>'int'],
'IntlGregorianCalendar::isWeekend' => ['bool', 'date='=>'float'],
'IntlGregorianCalendar::roll' => ['bool', 'field'=>'int', 'amountOrUpOrDown'=>'mixed'],
'IntlGregorianCalendar::set' => ['bool', 'field'=>'int', 'value'=>'int'],
'IntlGregorianCalendar::set\'1' => ['bool', 'year'=>'int', 'month'=>'int', 'dayOfMonth='=>'int', 'hour='=>'int', 'minute='=>'int', 'second='=>'int'],
'IntlGregorianCalendar::setFirstDayOfWeek' => ['bool', 'dayOfWeek'=>'int'],
'IntlGregorianCalendar::setGregorianChange' => ['bool', 'date'=>'float'],
'IntlGregorianCalendar::setLenient' => ['bool', 'isLenient'=>'string'],
'IntlGregorianCalendar::setMinimalDaysInFirstWeek' => ['bool', 'minimalDays'=>'int'],
'IntlGregorianCalendar::setRepeatedWallTimeOption' => ['bool', 'wallTimeOption'=>'int'],
'IntlGregorianCalendar::setSkippedWallTimeOption' => ['bool', 'wallTimeOption'=>'int'],
'IntlGregorianCalendar::setTime' => ['bool', 'date'=>'float'],
'IntlGregorianCalendar::setTimeZone' => ['bool', 'timeZone'=>'mixed'],
'IntlGregorianCalendar::toDateTime' => ['DateTime'],
'IntlIterator::__construct' => ['void'],
'IntlIterator::current' => ['mixed'],
'IntlIterator::key' => ['string'],
'IntlIterator::next' => ['void'],
'IntlIterator::rewind' => ['void'],
'IntlIterator::valid' => ['bool'],
'IntlPartsIterator::getBreakIterator' => ['IntlBreakIterator'],
'IntlRuleBasedBreakIterator::__construct' => ['void', 'rules'=>'string', 'areCompiled='=>'string'],
'IntlRuleBasedBreakIterator::createCharacterInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlRuleBasedBreakIterator::createCodePointInstance' => ['IntlCodePointBreakIterator'],
'IntlRuleBasedBreakIterator::createLineInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlRuleBasedBreakIterator::createSentenceInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlRuleBasedBreakIterator::createTitleInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlRuleBasedBreakIterator::createWordInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlRuleBasedBreakIterator::current' => ['int'],
'IntlRuleBasedBreakIterator::first' => ['int'],
'IntlRuleBasedBreakIterator::following' => ['int', 'offset'=>'int'],
'IntlRuleBasedBreakIterator::getBinaryRules' => ['string'],
'IntlRuleBasedBreakIterator::getErrorCode' => ['int'],
'IntlRuleBasedBreakIterator::getErrorMessage' => ['string'],
'IntlRuleBasedBreakIterator::getLocale' => ['string', 'locale_type'=>'string'],
'IntlRuleBasedBreakIterator::getPartsIterator' => ['IntlPartsIterator', 'key_type='=>'int'],
'IntlRuleBasedBreakIterator::getRules' => ['string'],
'IntlRuleBasedBreakIterator::getRuleStatus' => ['int'],
'IntlRuleBasedBreakIterator::getRuleStatusVec' => ['array'],
'IntlRuleBasedBreakIterator::getText' => ['string'],
'IntlRuleBasedBreakIterator::isBoundary' => ['bool', 'offset'=>'int'],
'IntlRuleBasedBreakIterator::last' => ['int'],
'IntlRuleBasedBreakIterator::next' => ['int', 'offset='=>'int'],
'IntlRuleBasedBreakIterator::preceding' => ['int', 'offset'=>'int'],
'IntlRuleBasedBreakIterator::previous' => ['int'],
'IntlRuleBasedBreakIterator::setText' => ['bool', 'text'=>'string'],
'IntlTimeZone::countEquivalentIDs' => ['int|false', 'zoneId'=>'string'],
'IntlTimeZone::createDefault' => ['IntlTimeZone'],
'IntlTimeZone::createEnumeration' => ['IntlIterator|false', 'countryOrRawOffset='=>'mixed'],
'IntlTimeZone::createTimeZone' => ['IntlTimeZone|false', 'zoneId'=>'string'],
'IntlTimeZone::createTimeZoneIDEnumeration' => ['IntlIterator|false', 'zoneType'=>'int', 'region='=>'string', 'rawOffset='=>'int'],
'IntlTimeZone::fromDateTimeZone' => ['?IntlTimeZone', 'zoneId'=>'DateTimeZone'],
'IntlTimeZone::getCanonicalID' => ['string|false', 'zoneId'=>'string', '&w_isSystemID='=>'bool'],
'IntlTimeZone::getDisplayName' => ['string|false', 'isDaylight='=>'bool', 'style='=>'int', 'locale='=>'string'],
'IntlTimeZone::getDSTSavings' => ['int'],
'IntlTimeZone::getEquivalentID' => ['string|false', 'zoneId'=>'string', 'index'=>'int'],
'IntlTimeZone::getErrorCode' => ['int'],
'IntlTimeZone::getErrorMessage' => ['string'],
'IntlTimeZone::getGMT' => ['IntlTimeZone'],
'IntlTimeZone::getID' => ['string'],
'IntlTimeZone::getIDForWindowsID' => ['string', 'timezone'=>'string', 'region='=>'string'],
'IntlTimeZone::getOffset' => ['int', 'date'=>'float', 'local'=>'bool', '&w_rawOffset'=>'int', '&w_dstOffset'=>'int'],
'IntlTimeZone::getRawOffset' => ['int'],
'IntlTimeZone::getRegion' => ['string|false', 'zoneId'=>'string'],
'IntlTimeZone::getTZDataVersion' => ['string'],
'IntlTimeZone::getUnknown' => ['IntlTimeZone'],
'IntlTimeZone::getWindowsID' => ['string|false', 'timezone'=>'string'],
'IntlTimeZone::hasSameRules' => ['bool', 'otherTimeZone'=>'IntlTimeZone'],
'IntlTimeZone::toDateTimeZone' => ['DateTimeZone|false'],
'IntlTimeZone::useDaylightTime' => ['bool'],
'intltz_count_equivalent_ids' => ['int', 'timezoneId'=>'string'],
'intltz_create_enumeration' => ['IntlIterator', 'countryOrRawOffset'=>'mixed'],
'intltz_create_time_zone' => ['IntlTimeZone', 'timezoneId'=>'string'],
'intltz_from_date_time_zone' => ['IntlTimeZone', 'timezone'=>'DateTimeZone'],
'intltz_get_canonical_id' => ['string', 'timezoneId'=>'string', '&isSystemId'=>'bool'],
'intltz_get_display_name' => ['string', 'timezone'=>'IntlTimeZone', 'dst'=>'bool', 'style'=>'int', 'locale'=>'string'],
'intltz_get_dst_savings' => ['int', 'timezone'=>'IntlTimeZone'],
'intltz_get_equivalent_id' => ['string', 'timezoneId'=>'string', 'offset'=>'int'],
'intltz_get_error_code' => ['int', 'timezone'=>'IntlTimeZone'],
'intltz_get_error_message' => ['string', 'timezone'=>'IntlTimeZone'],
'intltz_get_id' => ['string', 'timezone'=>'IntlTimeZone'],
'intltz_get_offset' => ['int', 'timezone'=>'IntlTimeZone', 'timestamp'=>'float', 'local'=>'bool', '&rawOffset'=>'int', '&dstOffset'=>'int'],
'intltz_get_raw_offset' => ['int', 'timezone'=>'IntlTimeZone'],
'intltz_get_tz_data_version' => ['string', 'object'=>'IntlTimeZone'],
'intltz_getGMT' => ['IntlTimeZone'],
'intltz_has_same_rules' => ['bool', 'timezone'=>'IntlTimeZone', 'other'=>'IntlTimeZone'],
'intltz_to_date_time_zone' => ['DateTimeZone', 'timezone'=>'IntlTimeZone'],
'intltz_use_daylight_time' => ['bool', 'timezone'=>'IntlTimeZone'],
'intlz_create_default' => ['IntlTimeZone'],
'intval' => ['int', 'value'=>'mixed', 'base='=>'int'],
'InvalidArgumentException::__clone' => ['void'],
'InvalidArgumentException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?InvalidArgumentException'],
'InvalidArgumentException::__toString' => ['string'],
'InvalidArgumentException::getCode' => ['int'],
'InvalidArgumentException::getFile' => ['string'],
'InvalidArgumentException::getLine' => ['int'],
'InvalidArgumentException::getMessage' => ['string'],
'InvalidArgumentException::getPrevious' => ['Throwable|InvalidArgumentException|null'],
'InvalidArgumentException::getTrace' => ['list<array<string,mixed>>'],
'InvalidArgumentException::getTraceAsString' => ['string'],
'ip2long' => ['int|false', 'ip'=>'string'],
'iptcembed' => ['string|bool', 'iptc_data'=>'string', 'filename'=>'string', 'spool='=>'int'],
'iptcparse' => ['array|false', 'iptc_block'=>'string'],
'is_a' => ['bool', 'object_or_class'=>'mixed', 'class'=>'string', 'allow_string='=>'bool'],
'is_array' => ['bool', 'value'=>'mixed'],
'is_bool' => ['bool', 'value'=>'mixed'],
'is_callable' => ['bool', 'value'=>'callable|mixed', 'syntax_only='=>'bool', '&w_callable_name='=>'string'],
'is_countable' => ['bool', 'value'=>'mixed'],
'is_dir' => ['bool', 'filename'=>'string'],
'is_double' => ['bool', 'value'=>'mixed'],
'is_executable' => ['bool', 'filename'=>'string'],
'is_file' => ['bool', 'filename'=>'string'],
'is_finite' => ['bool', 'num'=>'float'],
'is_float' => ['bool', 'value'=>'mixed'],
'is_infinite' => ['bool', 'num'=>'float'],
'is_int' => ['bool', 'value'=>'mixed'],
'is_integer' => ['bool', 'value'=>'mixed'],
'is_iterable' => ['bool', 'value'=>'mixed'],
'is_link' => ['bool', 'filename'=>'string'],
'is_long' => ['bool', 'value'=>'mixed'],
'is_nan' => ['bool', 'num'=>'float'],
'is_null' => ['bool', 'value'=>'mixed'],
'is_numeric' => ['bool', 'value'=>'mixed'],
'is_object' => ['bool', 'value'=>'mixed'],
'is_readable' => ['bool', 'filename'=>'string'],
'is_real' => ['bool', 'value'=>'mixed'],
'is_resource' => ['bool', 'value'=>'mixed'],
'is_scalar' => ['bool', 'value'=>'mixed'],
'is_soap_fault' => ['bool', 'object'=>'mixed'],
'is_string' => ['bool', 'value'=>'mixed'],
'is_subclass_of' => ['bool', 'object_or_class'=>'object|string', 'class'=>'class-string', 'allow_string='=>'bool'],
'is_tainted' => ['bool', 'string'=>'string'],
'is_uploaded_file' => ['bool', 'filename'=>'string'],
'is_writable' => ['bool', 'filename'=>'string'],
'is_writeable' => ['bool', 'filename'=>'string'],
'isset' => ['bool', 'value'=>'mixed', '...rest='=>'mixed'],
'Iterator::current' => ['mixed'],
'Iterator::key' => ['mixed'],
'Iterator::next' => ['void'],
'Iterator::rewind' => ['void'],
'Iterator::valid' => ['bool'],
'iterator_apply' => ['int', 'iterator'=>'Traversable', 'callback'=>'callable(mixed):bool', 'args='=>'array'],
'iterator_count' => ['int', 'iterator'=>'Traversable'],
'iterator_to_array' => ['array', 'iterator'=>'Traversable', 'preserve_keys='=>'bool'],
'IteratorAggregate::getIterator' => ['Traversable'],
'IteratorIterator::__construct' => ['void', 'it'=>'Traversable'],
'IteratorIterator::current' => ['mixed'],
'IteratorIterator::getInnerIterator' => ['Iterator'],
'IteratorIterator::key' => ['mixed'],
'IteratorIterator::next' => ['void'],
'IteratorIterator::rewind' => ['void'],
'IteratorIterator::valid' => ['bool'],
'java_last_exception_clear' => ['void'],
'java_last_exception_get' => ['object'],
'java_reload' => ['array', 'new_jarpath'=>'string'],
'java_require' => ['array', 'new_classpath'=>'string'],
'java_set_encoding' => ['array', 'encoding'=>'string'],
'java_set_ignore_case' => ['void', 'ignore'=>'bool'],
'java_throw_exceptions' => ['void', 'throw'=>'bool'],
'JavaException::getCause' => ['object'],
'jddayofweek' => ['mixed', 'julian_day'=>'int', 'mode='=>'int'],
'jdmonthname' => ['string', 'julian_day'=>'int', 'mode'=>'int'],
'jdtofrench' => ['string', 'julian_day'=>'int'],
'jdtogregorian' => ['string', 'julian_day'=>'int'],
'jdtojewish' => ['string', 'julian_day'=>'int', 'hebrew='=>'bool', 'flags='=>'int'],
'jdtojulian' => ['string', 'julian_day'=>'int'],
'jdtounix' => ['int|false', 'julian_day'=>'int'],
'jewishtojd' => ['int', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'jobqueue_license_info' => ['array'],
'join' => ['string', 'separator'=>'string', 'array'=>'array'],
'join\'1' => ['string', 'separator'=>'array'],
'json_decode' => ['mixed', 'json'=>'string', 'associative='=>'bool', 'depth='=>'int', 'flags='=>'int'],
'json_encode' => ['string|false', 'value'=>'mixed', 'flags='=>'int', 'depth='=>'int'],
'json_last_error' => ['int'],
'json_last_error_msg' => ['string'],
'JsonException::__clone' => ['void'],
'JsonException::__construct' => ['void'],
'JsonException::__toString' => ['string'],
'JsonException::__wakeup' => ['void'],
'JsonException::getCode' => ['int'],
'JsonException::getFile' => ['string'],
'JsonException::getLine' => ['int'],
'JsonException::getMessage' => ['string'],
'JsonException::getPrevious' => ['?Throwable'],
'JsonException::getTrace' => ['list<array<string,mixed>>'],
'JsonException::getTraceAsString' => ['string'],
'JsonIncrementalParser::__construct' => ['void', 'depth'=>'', 'options'=>''],
'JsonIncrementalParser::get' => ['', 'options'=>''],
'JsonIncrementalParser::getError' => [''],
'JsonIncrementalParser::parse' => ['', 'json'=>''],
'JsonIncrementalParser::parseFile' => ['', 'filename'=>''],
'JsonIncrementalParser::reset' => [''],
'JsonSerializable::jsonSerialize' => ['mixed'],
'Judy::__construct' => ['void', 'judy_type'=>'int'],
'Judy::__destruct' => ['void'],
'Judy::byCount' => ['int', 'nth_index'=>'int'],
'Judy::count' => ['int', 'index_start='=>'int', 'index_end='=>'int'],
'Judy::first' => ['mixed', 'index='=>'mixed'],
'Judy::firstEmpty' => ['mixed', 'index='=>'mixed'],
'Judy::free' => ['int'],
'Judy::getType' => ['int'],
'Judy::last' => ['mixed', 'index='=>'string'],
'Judy::lastEmpty' => ['mixed', 'index='=>'int'],
'Judy::memoryUsage' => ['int'],
'Judy::next' => ['mixed', 'index'=>'mixed'],
'Judy::nextEmpty' => ['mixed', 'index'=>'mixed'],
'Judy::offsetExists' => ['bool', 'offset'=>'mixed'],
'Judy::offsetGet' => ['mixed', 'offset'=>'mixed'],
'Judy::offsetSet' => ['bool', 'offset'=>'mixed', 'value'=>'mixed'],
'Judy::offsetUnset' => ['bool', 'offset'=>'mixed'],
'Judy::prev' => ['mixed', 'index'=>'mixed'],
'Judy::prevEmpty' => ['mixed', 'index'=>'mixed'],
'Judy::size' => ['int'],
'judy_type' => ['int', 'array'=>'judy'],
'judy_version' => ['string'],
'juliantojd' => ['int', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'kadm5_chpass_principal' => ['bool', 'handle'=>'resource', 'principal'=>'string', 'password'=>'string'],
'kadm5_create_principal' => ['bool', 'handle'=>'resource', 'principal'=>'string', 'password='=>'string', 'options='=>'array'],
'kadm5_delete_principal' => ['bool', 'handle'=>'resource', 'principal'=>'string'],
'kadm5_destroy' => ['bool', 'handle'=>'resource'],
'kadm5_flush' => ['bool', 'handle'=>'resource'],
'kadm5_get_policies' => ['array', 'handle'=>'resource'],
'kadm5_get_principal' => ['array', 'handle'=>'resource', 'principal'=>'string'],
'kadm5_get_principals' => ['array', 'handle'=>'resource'],
'kadm5_init_with_password' => ['resource', 'admin_server'=>'string', 'realm'=>'string', 'principal'=>'string', 'password'=>'string'],
'kadm5_modify_principal' => ['bool', 'handle'=>'resource', 'principal'=>'string', 'options'=>'array'],
'key' => ['int|string|null', 'array'=>'array|object'],
'key_exists' => ['bool', 'key'=>'string|int', 'array'=>'array'],
'krsort' => ['bool', '&rw_array'=>'array', 'flags='=>'int'],
'ksort' => ['bool', '&rw_array'=>'array', 'flags='=>'int'],
'KTaglib_ID3v2_AttachedPictureFrame::getDescription' => ['string'],
'KTaglib_ID3v2_AttachedPictureFrame::getMimeType' => ['string'],
'KTaglib_ID3v2_AttachedPictureFrame::getType' => ['int'],
'KTaglib_ID3v2_AttachedPictureFrame::savePicture' => ['bool', 'filename'=>'string'],
'KTaglib_ID3v2_AttachedPictureFrame::setMimeType' => ['string', 'type'=>'string'],
'KTaglib_ID3v2_AttachedPictureFrame::setPicture' => ['', 'filename'=>'string'],
'KTaglib_ID3v2_AttachedPictureFrame::setType' => ['', 'type'=>'int'],
'KTaglib_ID3v2_Frame::__toString' => ['string'],
'KTaglib_ID3v2_Frame::getDescription' => ['string'],
'KTaglib_ID3v2_Frame::getMimeType' => ['string'],
'KTaglib_ID3v2_Frame::getSize' => ['int'],
'KTaglib_ID3v2_Frame::getType' => ['int'],
'KTaglib_ID3v2_Frame::savePicture' => ['bool', 'filename'=>'string'],
'KTaglib_ID3v2_Frame::setMimeType' => ['string', 'type'=>'string'],
'KTaglib_ID3v2_Frame::setPicture' => ['void', 'filename'=>'string'],
'KTaglib_ID3v2_Frame::setType' => ['void', 'type'=>'int'],
'KTaglib_ID3v2_Tag::addFrame' => ['bool', 'frame'=>'KTaglib_ID3v2_Frame'],
'KTaglib_ID3v2_Tag::getFrameList' => ['array'],
'KTaglib_MPEG_AudioProperties::getBitrate' => ['int'],
'KTaglib_MPEG_AudioProperties::getChannels' => ['int'],
'KTaglib_MPEG_AudioProperties::getLayer' => ['int'],
'KTaglib_MPEG_AudioProperties::getLength' => ['int'],
'KTaglib_MPEG_AudioProperties::getSampleBitrate' => ['int'],
'KTaglib_MPEG_AudioProperties::getVersion' => ['int'],
'KTaglib_MPEG_AudioProperties::isCopyrighted' => ['bool'],
'KTaglib_MPEG_AudioProperties::isOriginal' => ['bool'],
'KTaglib_MPEG_AudioProperties::isProtectionEnabled' => ['bool'],
'KTaglib_MPEG_File::getAudioProperties' => ['KTaglib_MPEG_File'],
'KTaglib_MPEG_File::getID3v1Tag' => ['KTaglib_ID3v1_Tag', 'create='=>'bool'],
'KTaglib_MPEG_File::getID3v2Tag' => ['KTaglib_ID3v2_Tag', 'create='=>'bool'],
'KTaglib_Tag::getAlbum' => ['string'],
'KTaglib_Tag::getArtist' => ['string'],
'KTaglib_Tag::getComment' => ['string'],
'KTaglib_Tag::getGenre' => ['string'],
'KTaglib_Tag::getTitle' => ['string'],
'KTaglib_Tag::getTrack' => ['int'],
'KTaglib_Tag::getYear' => ['int'],
'KTaglib_Tag::isEmpty' => ['bool'],
'labelcacheObj::freeCache' => ['bool'],
'labelObj::__construct' => ['void'],
'labelObj::convertToString' => ['string'],
'labelObj::deleteStyle' => ['int', 'index'=>'int'],
'labelObj::free' => ['void'],
'labelObj::getBinding' => ['string', 'labelbinding'=>'mixed'],
'labelObj::getExpressionString' => ['string'],
'labelObj::getStyle' => ['styleObj', 'index'=>'int'],
'labelObj::getTextString' => ['string'],
'labelObj::moveStyleDown' => ['int', 'index'=>'int'],
'labelObj::moveStyleUp' => ['int', 'index'=>'int'],
'labelObj::removeBinding' => ['int', 'labelbinding'=>'mixed'],
'labelObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'labelObj::setBinding' => ['int', 'labelbinding'=>'mixed', 'value'=>'string'],
'labelObj::setExpression' => ['int', 'expression'=>'string'],
'labelObj::setText' => ['int', 'text'=>'string'],
'labelObj::updateFromString' => ['int', 'snippet'=>'string'],
'Lapack::eigenValues' => ['array', 'a'=>'array', 'left='=>'array', 'right='=>'array'],
'Lapack::identity' => ['array', 'n'=>'int'],
'Lapack::leastSquaresByFactorisation' => ['array', 'a'=>'array', 'b'=>'array'],
'Lapack::leastSquaresBySVD' => ['array', 'a'=>'array', 'b'=>'array'],
'Lapack::pseudoInverse' => ['array', 'a'=>'array'],
'Lapack::singularValues' => ['array', 'a'=>'array'],
'Lapack::solveLinearEquation' => ['array', 'a'=>'array', 'b'=>'array'],
'layerObj::addFeature' => ['int', 'shape'=>'shapeObj'],
'layerObj::applySLD' => ['int', 'sldxml'=>'string', 'namedlayer'=>'string'],
'layerObj::applySLDURL' => ['int', 'sldurl'=>'string', 'namedlayer'=>'string'],
'layerObj::clearProcessing' => ['void'],
'layerObj::close' => ['void'],
'layerObj::convertToString' => ['string'],
'layerObj::draw' => ['int', 'image'=>'imageObj'],
'layerObj::drawQuery' => ['int', 'image'=>'imageObj'],
'layerObj::free' => ['void'],
'layerObj::generateSLD' => ['string'],
'layerObj::getClass' => ['classObj', 'classIndex'=>'int'],
'layerObj::getClassIndex' => ['int', 'shape'=>'', 'classgroup'=>'', 'numclasses'=>''],
'layerObj::getExtent' => ['rectObj'],
'layerObj::getFilterString' => ['?string'],
'layerObj::getGridIntersectionCoordinates' => ['array'],
'layerObj::getItems' => ['array'],
'layerObj::getMetaData' => ['int', 'name'=>'string'],
'layerObj::getNumResults' => ['int'],
'layerObj::getProcessing' => ['array'],
'layerObj::getProjection' => ['string'],
'layerObj::getResult' => ['resultObj', 'index'=>'int'],
'layerObj::getResultsBounds' => ['rectObj'],
'layerObj::getShape' => ['shapeObj', 'result'=>'resultObj'],
'layerObj::getWMSFeatureInfoURL' => ['string', 'clickX'=>'int', 'clickY'=>'int', 'featureCount'=>'int', 'infoFormat'=>'string'],
'layerObj::isVisible' => ['bool'],
'layerObj::moveclassdown' => ['int', 'index'=>'int'],
'layerObj::moveclassup' => ['int', 'index'=>'int'],
'layerObj::ms_newLayerObj' => ['layerObj', 'map'=>'mapObj', 'layer'=>'layerObj'],
'layerObj::nextShape' => ['shapeObj'],
'layerObj::open' => ['int'],
'layerObj::queryByAttributes' => ['int', 'qitem'=>'string', 'qstring'=>'string', 'mode'=>'int'],
'layerObj::queryByFeatures' => ['int', 'slayer'=>'int'],
'layerObj::queryByPoint' => ['int', 'point'=>'pointObj', 'mode'=>'int', 'buffer'=>'float'],
'layerObj::queryByRect' => ['int', 'rect'=>'rectObj'],
'layerObj::queryByShape' => ['int', 'shape'=>'shapeObj'],
'layerObj::removeClass' => ['?classObj', 'index'=>'int'],
'layerObj::removeMetaData' => ['int', 'name'=>'string'],
'layerObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'layerObj::setConnectionType' => ['int', 'connectiontype'=>'int', 'plugin_library'=>'string'],
'layerObj::setFilter' => ['int', 'expression'=>'string'],
'layerObj::setMetaData' => ['int', 'name'=>'string', 'value'=>'string'],
'layerObj::setProjection' => ['int', 'proj_params'=>'string'],
'layerObj::setWKTProjection' => ['int', 'proj_params'=>'string'],
'layerObj::updateFromString' => ['int', 'snippet'=>'string'],
'lcfirst' => ['string', 'string'=>'string'],
'lcg_value' => ['float'],
'lchgrp' => ['bool', 'filename'=>'string', 'group'=>'string|int'],
'lchown' => ['bool', 'filename'=>'string', 'user'=>'string|int'],
'ldap_8859_to_t61' => ['string', 'value'=>'string'],
'ldap_add' => ['bool', 'ldap'=>'LDAP\Connection', 'dn'=>'string', 'entry'=>'array', 'controls='=>'array'],
'ldap_add_ext' => ['LDAP\Connection|false', 'ldap'=>'LDAP\Connection', 'dn'=>'string', 'entry'=>'array', 'controls='=>'array'],
'ldap_bind' => ['bool', 'ldap'=>'LDAP\Connection', 'dn='=>'string|null', 'password='=>'string|null'],
'ldap_bind_ext' => ['LDAP\Connection|false', 'ldap'=>'LDAP\Connection', 'dn='=>'string|null', 'password='=>'string|null', 'controls='=>'array'],
'ldap_close' => ['bool', 'ldap'=>'LDAP\Connection'],
'ldap_compare' => ['bool|int', 'ldap'=>'LDAP\Connection', 'dn'=>'string', 'attribute'=>'string', 'value'=>'string'],
'ldap_connect' => ['LDAP\Connection|false', 'uri='=>'string', 'port='=>'int', 'wallet='=>'string', 'password='=>'string', 'auth_mode='=>'int'],
'ldap_control_paged_result' => ['bool', 'link_identifier'=>'resource', 'pagesize'=>'int', 'iscritical='=>'bool', 'cookie='=>'string'],
'ldap_control_paged_result_response' => ['bool', 'link_identifier'=>'resource', 'result_identifier'=>'resource', '&w_cookie'=>'string', '&w_estimated'=>'int'],
'ldap_count_entries' => ['int|false', 'ldap'=>'LDAP\Connection', 'result'=>'LDAP\Result'],
'ldap_delete' => ['bool', 'ldap'=>'LDAP\Connection', 'dn'=>'string'],
'ldap_delete_ext' => ['LDAP\Connection|false', 'ldap'=>'LDAP\Connection', 'dn'=>'string', 'controls='=>'array'],
'ldap_dn2ufn' => ['string', 'dn'=>'string'],
'ldap_err2str' => ['string', 'errno'=>'int'],
'ldap_errno' => ['int', 'ldap'=>'LDAP\Connection'],
'ldap_error' => ['string', 'ldap'=>'LDAP\Connection'],
'ldap_escape' => ['string', 'value'=>'string', 'ignore='=>'string', 'flags='=>'int'],
'ldap_exop' => ['mixed', 'ldap'=>'LDAP\Connection', 'reqoid'=>'string', 'reqdata='=>'string', 'serverctrls='=>'array|null', '&w_response_data='=>'string', '&w_response_oid='=>'string'],
'ldap_exop_passwd' => ['bool|string', 'ldap'=>'LDAP\Connection', 'user='=>'string', 'old_password='=>'string', 'new_password='=>'string', '&w_controls='=>'array|null'],
'ldap_exop_refresh' => ['int|false', 'ldap'=>'LDAP\Connection', 'dn'=>'string', 'ttl'=>'int'],
'ldap_exop_whoami' => ['string|false', 'ldap'=>'LDAP\Connection'],
'ldap_explode_dn' => ['array|false', 'dn'=>'string', 'with_attrib'=>'int'],
'ldap_first_attribute' => ['string|false', 'ldap'=>'LDAP\Connection', 'entry'=>'LDAP\ResultEntry'],
'ldap_first_entry' => ['LDAP\Connection|false', 'ldap'=>'LDAP\Connection', 'result'=>'LDAP\Result'],
'ldap_first_reference' => ['LDAP\Connection|false', 'ldap'=>'LDAP\Connection', 'result'=>'LDAP\Result'],
'ldap_free_result' => ['bool', 'ldap'=>'LDAP\Connection'],
'ldap_get_attributes' => ['array|false', 'ldap'=>'LDAP\Connection', 'entry'=>'LDAP\ResultEntry'],
'ldap_get_dn' => ['string|false', 'ldap'=>'LDAP\Connection', 'entry'=>'LDAP\ResultEntry'],
'ldap_get_entries' => ['array|false', 'ldap'=>'LDAP\Connection', 'result'=>'LDAP\Result'],
'ldap_get_option' => ['bool', 'ldap'=>'LDAP\Connection', 'option'=>'int', '&w_value'=>'mixed'],
'ldap_get_values' => ['array|false', 'ldap'=>'LDAP\Connection', 'entry'=>'LDAP\ResultEntry', 'attribute'=>'string'],
'ldap_get_values_len' => ['array|false', 'ldap'=>'LDAP\Connection', 'entry'=>'LDAP\ResultEntry', 'attribute'=>'string'],
'ldap_list' => ['LDAP\Connection|false', 'ldap'=>'resource|array', 'base'=>'string', 'filter'=>'string', 'attributes='=>'array', 'attributes_only='=>'int', 'sizelimit='=>'int', 'timelimit='=>'int', 'deref='=>'int'],
'ldap_mod_add' => ['bool', 'ldap'=>'LDAP\Connection', 'dn'=>'string', 'entry'=>'array'],
'ldap_mod_add_ext' => ['LDAP\Connection|false', 'ldap'=>'LDAP\Connection', 'dn'=>'string', 'entry'=>'array', 'controls='=>'array'],
'ldap_mod_del' => ['bool', 'ldap'=>'LDAP\Connection', 'dn'=>'string', 'entry'=>'array'],
'ldap_mod_del_ext' => ['LDAP\Connection|false', 'ldap'=>'LDAP\Connection', 'dn'=>'string', 'entry'=>'array', 'controls='=>'array'],
'ldap_mod_replace' => ['bool', 'ldap'=>'LDAP\Connection', 'dn'=>'string', 'entry'=>'array'],
'ldap_mod_replace_ext' => ['LDAP\Connection|false', 'ldap'=>'LDAP\Connection', 'dn'=>'string', 'entry'=>'array', 'controls='=>'array'],
'ldap_modify' => ['bool', 'ldap'=>'LDAP\Connection', 'dn'=>'string', 'entry'=>'array'],
'ldap_modify_batch' => ['bool', 'ldap'=>'LDAP\Connection', 'dn'=>'string', 'modifications_info'=>'array'],
'ldap_next_attribute' => ['string|false', 'ldap'=>'LDAP\Connection', 'entry'=>'LDAP\ResultEntry'],
'ldap_next_entry' => ['LDAP\Connection|false', 'ldap'=>'LDAP\Connection', 'result'=>'LDAP\Result'],
'ldap_next_reference' => ['LDAP\Connection|false', 'ldap'=>'LDAP\Connection', 'entry'=>'LDAP\ResultEntry'],
'ldap_parse_exop' => ['bool', 'ldap'=>'LDAP\Connection', 'result'=>'LDAP\Result', '&w_response_data='=>'string', '&w_response_oid='=>'string'],
'ldap_parse_reference' => ['bool', 'ldap'=>'LDAP\Connection', 'entry'=>'LDAP\ResultEntry', 'referrals'=>'array'],
'ldap_parse_result' => ['bool', 'ldap'=>'LDAP\Connection', 'result'=>'LDAP\Result', '&w_error_code'=>'int', '&w_matched_dn='=>'string', '&w_error_message='=>'string', '&w_referrals='=>'array', '&w_controls='=>'array'],
'ldap_read' => ['LDAP\Connection|false', 'ldap'=>'LDAP\Connection|array', 'base'=>'string', 'filter'=>'string', 'attributes='=>'array', 'attributes_only='=>'int', 'sizelimit='=>'int', 'timelimit='=>'int', 'deref='=>'int'],
'ldap_rename' => ['bool', 'ldap'=>'LDAP\Connection', 'dn'=>'string', 'new_rdn'=>'string', 'new_parent'=>'string', 'delete_old_rdn'=>'bool'],
'ldap_rename_ext' => ['LDAP\Connection|false', 'ldap'=>'LDAP\Connection', 'dn'=>'string', 'new_rdn'=>'string', 'new_parent'=>'string', 'delete_old_rdn'=>'bool', 'controls='=>'array'],
'ldap_sasl_bind' => ['bool', 'ldap'=>'LDAP\Connection', 'dn='=>'string', 'password='=>'string', 'mech='=>'string', 'realm='=>'string', 'authc_id='=>'string', 'authz_id='=>'string', 'props='=>'string'],
'ldap_search' => ['LDAP\Connection|false', 'ldap'=>'LDAP\Connection|LDAP\Connection[]', 'base'=>'string', 'filter'=>'string', 'attributes='=>'array', 'attributes_only='=>'int', 'sizelimit='=>'int', 'timelimit='=>'int', 'deref='=>'int'],
'ldap_set_option' => ['bool', 'ldap'=>'LDAP\Connection|null', 'option'=>'int', 'value'=>'mixed'],
'ldap_set_rebind_proc' => ['bool', 'ldap'=>'LDAP\Connection', 'callback'=>'string'],
'ldap_start_tls' => ['bool', 'ldap'=>'resource'],
'ldap_t61_to_8859' => ['string', 'value'=>'string'],
'ldap_unbind' => ['bool', 'ldap'=>'resource'],
'leak' => ['', 'num_bytes'=>'int'],
'leak_variable' => ['', 'variable'=>'', 'leak_data'=>'bool'],
'legendObj::convertToString' => ['string'],
'legendObj::free' => ['void'],
'legendObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'legendObj::updateFromString' => ['int', 'snippet'=>'string'],
'LengthException::__clone' => ['void'],
'LengthException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?LengthException'],
'LengthException::__toString' => ['string'],
'LengthException::getCode' => ['int'],
'LengthException::getFile' => ['string'],
'LengthException::getLine' => ['int'],
'LengthException::getMessage' => ['string'],
'LengthException::getPrevious' => ['Throwable|LengthException|null'],
'LengthException::getTrace' => ['list<array<string,mixed>>'],
'LengthException::getTraceAsString' => ['string'],
'LevelDB::__construct' => ['void', 'name'=>'string', 'options='=>'array', 'read_options='=>'array', 'write_options='=>'array'],
'LevelDB::close' => [''],
'LevelDB::compactRange' => ['', 'start'=>'', 'limit'=>''],
'LevelDB::delete' => ['bool', 'key'=>'string', 'write_options='=>'array'],
'LevelDB::destroy' => ['', 'name'=>'', 'options='=>'array'],
'LevelDB::get' => ['bool|string', 'key'=>'string', 'read_options='=>'array'],
'LevelDB::getApproximateSizes' => ['', 'start'=>'', 'limit'=>''],
'LevelDB::getIterator' => ['LevelDBIterator', 'options='=>'array'],
'LevelDB::getProperty' => ['mixed', 'name'=>'string'],
'LevelDB::getSnapshot' => ['LevelDBSnapshot'],
'LevelDB::put' => ['', 'key'=>'string', 'value'=>'string', 'write_options='=>'array'],
'LevelDB::repair' => ['', 'name'=>'', 'options='=>'array'],
'LevelDB::set' => ['', 'key'=>'string', 'value'=>'string', 'write_options='=>'array'],
'LevelDB::write' => ['', 'batch'=>'LevelDBWriteBatch', 'write_options='=>'array'],
'LevelDBIterator::__construct' => ['void', 'db'=>'LevelDB', 'read_options='=>'array'],
'LevelDBIterator::current' => ['mixed'],
'LevelDBIterator::destroy' => [''],
'LevelDBIterator::getError' => [''],
'LevelDBIterator::key' => ['int|string'],
'LevelDBIterator::last' => [''],
'LevelDBIterator::next' => ['void'],
'LevelDBIterator::prev' => [''],
'LevelDBIterator::rewind' => ['void'],
'LevelDBIterator::seek' => ['', 'key'=>''],
'LevelDBIterator::valid' => ['bool'],
'LevelDBSnapshot::__construct' => ['void', 'db'=>'LevelDB'],
'LevelDBSnapshot::release' => [''],
'LevelDBWriteBatch::__construct' => ['void', 'name'=>'', 'options='=>'array', 'read_options='=>'array', 'write_options='=>'array'],
'LevelDBWriteBatch::clear' => [''],
'LevelDBWriteBatch::delete' => ['', 'key'=>'', 'write_options='=>'array'],
'LevelDBWriteBatch::put' => ['', 'key'=>'', 'value'=>'', 'write_options='=>'array'],
'LevelDBWriteBatch::set' => ['', 'key'=>'', 'value'=>'', 'write_options='=>'array'],
'levenshtein' => ['int', 'string1'=>'string', 'string2'=>'string'],
'levenshtein\'1' => ['int', 'string1'=>'string', 'string2'=>'string', 'insertion_cost'=>'int', 'repetition_cost'=>'int', 'deletion_cost'=>'int'],
'libxml_clear_errors' => ['void'],
'libxml_disable_entity_loader' => ['bool', 'disable='=>'bool'],
'libxml_get_errors' => ['array<int,LibXMLError>'],
'libxml_get_last_error' => ['LibXMLError|false'],
'libxml_set_external_entity_loader' => ['bool', 'resolver_function'=>'callable'],
'libxml_set_streams_context' => ['void', 'context'=>'resource'],
'libxml_use_internal_errors' => ['bool', 'use_errors='=>'bool'],
'LimitIterator::__construct' => ['void', 'iterator'=>'Iterator', 'offset='=>'int', 'count='=>'int'],
'LimitIterator::current' => ['mixed'],
'LimitIterator::getInnerIterator' => ['Iterator'],
'LimitIterator::getPosition' => ['int'],
'LimitIterator::key' => ['mixed'],
'LimitIterator::next' => ['void'],
'LimitIterator::rewind' => ['void'],
'LimitIterator::seek' => ['int', 'position'=>'int'],
'LimitIterator::valid' => ['bool'],
'lineObj::__construct' => ['void'],
'lineObj::add' => ['int', 'point'=>'pointObj'],
'lineObj::addXY' => ['int', 'x'=>'float', 'y'=>'float', 'm'=>'float'],
'lineObj::addXYZ' => ['int', 'x'=>'float', 'y'=>'float', 'z'=>'float', 'm'=>'float'],
'lineObj::ms_newLineObj' => ['lineObj'],
'lineObj::point' => ['pointObj', 'i'=>'int'],
'lineObj::project' => ['int', 'in'=>'projectionObj', 'out'=>'projectionObj'],
'link' => ['bool', 'target'=>'string', 'link'=>'string'],
'linkinfo' => ['int|false', 'path'=>'string'],
'litespeed_request_headers' => ['array'],
'litespeed_response_headers' => ['array'],
'Locale::acceptFromHttp' => ['string|false', 'header'=>'string'],
'Locale::canonicalize' => ['string', 'locale'=>'string'],
'Locale::composeLocale' => ['string', 'subtags'=>'array'],
'Locale::filterMatches' => ['bool', 'langtag'=>'string', 'locale'=>'string', 'canonicalize='=>'bool'],
'Locale::getAllVariants' => ['array', 'locale'=>'string'],
'Locale::getDefault' => ['string'],
'Locale::getDisplayLanguage' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'Locale::getDisplayName' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'Locale::getDisplayRegion' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'Locale::getDisplayScript' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'Locale::getDisplayVariant' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'Locale::getKeywords' => ['array|false', 'locale'=>'string'],
'Locale::getPrimaryLanguage' => ['string', 'locale'=>'string'],
'Locale::getRegion' => ['string', 'locale'=>'string'],
'Locale::getScript' => ['string', 'locale'=>'string'],
'Locale::lookup' => ['string', 'langtag'=>'array', 'locale'=>'string', 'canonicalize='=>'bool', 'default='=>'string'],
'Locale::parseLocale' => ['array', 'locale'=>'string'],
'Locale::setDefault' => ['bool', 'locale'=>'string'],
'locale_accept_from_http' => ['string|false', 'header'=>'string'],
'locale_canonicalize' => ['string', 'locale'=>'string'],
'locale_compose' => ['string|false', 'subtags'=>'array'],
'locale_filter_matches' => ['bool', 'languageTag'=>'string', 'locale'=>'string', 'canonicalize='=>'bool'],
'locale_get_all_variants' => ['array', 'locale'=>'string'],
'locale_get_default' => ['string'],
'locale_get_display_language' => ['string', 'locale'=>'string', 'displayLocale='=>'string'],
'locale_get_display_name' => ['string', 'locale'=>'string', 'displayLocale='=>'string'],
'locale_get_display_region' => ['string', 'locale'=>'string', 'displayLocale='=>'string'],
'locale_get_display_script' => ['string', 'locale'=>'string', 'displayLocale='=>'string'],
'locale_get_display_variant' => ['string', 'locale'=>'string', 'displayLocale='=>'string'],
'locale_get_keywords' => ['array|false', 'locale'=>'string'],
'locale_get_primary_language' => ['string', 'locale'=>'string'],
'locale_get_region' => ['string', 'locale'=>'string'],
'locale_get_script' => ['string', 'locale'=>'string'],
'locale_lookup' => ['string', 'languageTag'=>'array', 'locale'=>'string', 'canonicalize='=>'bool', 'defaultLocale='=>'string'],
'locale_parse' => ['array', 'locale'=>'string'],
'locale_set_default' => ['bool', 'locale'=>'string'],
'localeconv' => ['array'],
'localtime' => ['array', 'timestamp='=>'int', 'associative='=>'bool'],
'log' => ['float', 'num'=>'float', 'base='=>'float'],
'log10' => ['float', 'num'=>'float'],
'log1p' => ['float', 'num'=>'float'],
'LogicException::__clone' => ['void'],
'LogicException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?LogicException'],
'LogicException::__toString' => ['string'],
'LogicException::getCode' => ['int'],
'LogicException::getFile' => ['string'],
'LogicException::getLine' => ['int'],
'LogicException::getMessage' => ['string'],
'LogicException::getPrevious' => ['Throwable|LogicException|null'],
'LogicException::getTrace' => ['list<array<string,mixed>>'],
'LogicException::getTraceAsString' => ['string'],
'long2ip' => ['string', 'ip'=>'string|int'],
'lstat' => ['array|false', 'filename'=>'string'],
'ltrim' => ['string', 'string'=>'string', 'characters='=>'string'],
'Lua::__call' => ['mixed', 'lua_func'=>'callable', 'args='=>'array', 'use_self='=>'int'],
'Lua::__construct' => ['void', 'lua_script_file'=>'string'],
'Lua::assign' => ['?Lua', 'name'=>'string', 'value'=>'mixed'],
'Lua::call' => ['mixed', 'lua_func'=>'callable', 'args='=>'array', 'use_self='=>'int'],
'Lua::eval' => ['mixed', 'statements'=>'string'],
'Lua::getVersion' => ['string'],
'Lua::include' => ['mixed', 'file'=>'string'],
'Lua::registerCallback' => ['Lua|null|false', 'name'=>'string', 'function'=>'callable'],
'LuaClosure::__invoke' => ['void', 'arg'=>'mixed', '...args='=>'mixed'],
'lzf_compress' => ['string', 'data'=>'string'],
'lzf_decompress' => ['string', 'data'=>'string'],
'lzf_optimized_for' => ['int'],
'm_checkstatus' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_completeauthorizations' => ['int', 'conn'=>'resource', 'array'=>'int'],
'm_connect' => ['int', 'conn'=>'resource'],
'm_connectionerror' => ['string', 'conn'=>'resource'],
'm_deletetrans' => ['bool', 'conn'=>'resource', 'identifier'=>'int'],
'm_destroyconn' => ['bool', 'conn'=>'resource'],
'm_destroyengine' => ['void'],
'm_getcell' => ['string', 'conn'=>'resource', 'identifier'=>'int', 'column'=>'string', 'row'=>'int'],
'm_getcellbynum' => ['string', 'conn'=>'resource', 'identifier'=>'int', 'column'=>'int', 'row'=>'int'],
'm_getcommadelimited' => ['string', 'conn'=>'resource', 'identifier'=>'int'],
'm_getheader' => ['string', 'conn'=>'resource', 'identifier'=>'int', 'column_num'=>'int'],
'm_initconn' => ['resource'],
'm_initengine' => ['int', 'location'=>'string'],
'm_iscommadelimited' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_maxconntimeout' => ['bool', 'conn'=>'resource', 'secs'=>'int'],
'm_monitor' => ['int', 'conn'=>'resource'],
'm_numcolumns' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_numrows' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_parsecommadelimited' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_responsekeys' => ['array', 'conn'=>'resource', 'identifier'=>'int'],
'm_responseparam' => ['string', 'conn'=>'resource', 'identifier'=>'int', 'key'=>'string'],
'm_returnstatus' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_setblocking' => ['int', 'conn'=>'resource', 'tf'=>'int'],
'm_setdropfile' => ['int', 'conn'=>'resource', 'directory'=>'string'],
'm_setip' => ['int', 'conn'=>'resource', 'host'=>'string', 'port'=>'int'],
'm_setssl' => ['int', 'conn'=>'resource', 'host'=>'string', 'port'=>'int'],
'm_setssl_cafile' => ['int', 'conn'=>'resource', 'cafile'=>'string'],
'm_setssl_files' => ['int', 'conn'=>'resource', 'sslkeyfile'=>'string', 'sslcertfile'=>'string'],
'm_settimeout' => ['int', 'conn'=>'resource', 'seconds'=>'int'],
'm_sslcert_gen_hash' => ['string', 'filename'=>'string'],
'm_transactionssent' => ['int', 'conn'=>'resource'],
'm_transinqueue' => ['int', 'conn'=>'resource'],
'm_transkeyval' => ['int', 'conn'=>'resource', 'identifier'=>'int', 'key'=>'string', 'value'=>'string'],
'm_transnew' => ['int', 'conn'=>'resource'],
'm_transsend' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_uwait' => ['int', 'microsecs'=>'int'],
'm_validateidentifier' => ['int', 'conn'=>'resource', 'tf'=>'int'],
'm_verifyconnection' => ['bool', 'conn'=>'resource', 'tf'=>'int'],
'm_verifysslcert' => ['bool', 'conn'=>'resource', 'tf'=>'int'],
'magic_quotes_runtime' => ['bool', 'new_setting'=>'bool'],
'mail' => ['bool', 'to'=>'string', 'subject'=>'string', 'message'=>'string', 'additional_headers='=>'string|array|null', 'additional_params='=>'string'],
'mailparse_determine_best_xfer_encoding' => ['string', 'fp'=>'resource'],
'mailparse_msg_create' => ['resource'],
'mailparse_msg_extract_part' => ['void', 'mimemail'=>'resource', 'msgbody'=>'string', 'callbackfunc='=>'callable'],
'mailparse_msg_extract_part_file' => ['string', 'mimemail'=>'resource', 'filename'=>'mixed', 'callbackfunc='=>'callable'],
'mailparse_msg_extract_whole_part_file' => ['string', 'mimemail'=>'resource', 'filename'=>'string', 'callbackfunc='=>'callable'],
'mailparse_msg_free' => ['bool', 'mimemail'=>'resource'],
'mailparse_msg_get_part' => ['resource', 'mimemail'=>'resource', 'mimesection'=>'string'],
'mailparse_msg_get_part_data' => ['array', 'mimemail'=>'resource'],
'mailparse_msg_get_structure' => ['array', 'mimemail'=>'resource'],
'mailparse_msg_parse' => ['bool', 'mimemail'=>'resource', 'data'=>'string'],
'mailparse_msg_parse_file' => ['resource|false', 'filename'=>'string'],
'mailparse_rfc822_parse_addresses' => ['array', 'addresses'=>'string'],
'mailparse_stream_encode' => ['bool', 'sourcefp'=>'resource', 'destfp'=>'resource', 'encoding'=>'string'],
'mailparse_uudecode_all' => ['array', 'fp'=>'resource'],
'mapObj::__construct' => ['void', 'map_file_name'=>'string', 'new_map_path'=>'string'],
'mapObj::appendOutputFormat' => ['int', 'outputFormat'=>'outputformatObj'],
'mapObj::applyconfigoptions' => ['int'],
'mapObj::applySLD' => ['int', 'sldxml'=>'string'],
'mapObj::applySLDURL' => ['int', 'sldurl'=>'string'],
'mapObj::convertToString' => ['string'],
'mapObj::draw' => ['?imageObj'],
'mapObj::drawLabelCache' => ['int', 'image'=>'imageObj'],
'mapObj::drawLegend' => ['imageObj'],
'mapObj::drawQuery' => ['?imageObj'],
'mapObj::drawReferenceMap' => ['imageObj'],
'mapObj::drawScaleBar' => ['imageObj'],
'mapObj::embedLegend' => ['int', 'image'=>'imageObj'],
'mapObj::embedScalebar' => ['int', 'image'=>'imageObj'],
'mapObj::free' => ['void'],
'mapObj::generateSLD' => ['string'],
'mapObj::getAllGroupNames' => ['array'],
'mapObj::getAllLayerNames' => ['array'],
'mapObj::getColorbyIndex' => ['colorObj', 'iCloIndex'=>'int'],
'mapObj::getConfigOption' => ['string', 'key'=>'string'],
'mapObj::getLabel' => ['labelcacheMemberObj', 'index'=>'int'],
'mapObj::getLayer' => ['layerObj', 'index'=>'int'],
'mapObj::getLayerByName' => ['layerObj', 'layer_name'=>'string'],
'mapObj::getLayersDrawingOrder' => ['array'],
'mapObj::getLayersIndexByGroup' => ['array', 'groupname'=>'string'],
'mapObj::getMetaData' => ['int', 'name'=>'string'],
'mapObj::getNumSymbols' => ['int'],
'mapObj::getOutputFormat' => ['?outputformatObj', 'index'=>'int'],
'mapObj::getProjection' => ['string'],
'mapObj::getSymbolByName' => ['int', 'symbol_name'=>'string'],
'mapObj::getSymbolObjectById' => ['symbolObj', 'symbolid'=>'int'],
'mapObj::loadMapContext' => ['int', 'filename'=>'string', 'unique_layer_name'=>'bool'],
'mapObj::loadOWSParameters' => ['int', 'request'=>'OwsrequestObj', 'version'=>'string'],
'mapObj::moveLayerDown' => ['int', 'layerindex'=>'int'],
'mapObj::moveLayerUp' => ['int', 'layerindex'=>'int'],
'mapObj::ms_newMapObjFromString' => ['mapObj', 'map_file_string'=>'string', 'new_map_path'=>'string'],
'mapObj::offsetExtent' => ['int', 'x'=>'float', 'y'=>'float'],
'mapObj::owsDispatch' => ['int', 'request'=>'OwsrequestObj'],
'mapObj::prepareImage' => ['imageObj'],
'mapObj::prepareQuery' => ['void'],
'mapObj::processLegendTemplate' => ['string', 'params'=>'array'],
'mapObj::processQueryTemplate' => ['string', 'params'=>'array', 'generateimages'=>'bool'],
'mapObj::processTemplate' => ['string', 'params'=>'array', 'generateimages'=>'bool'],
'mapObj::queryByFeatures' => ['int', 'slayer'=>'int'],
'mapObj::queryByIndex' => ['int', 'layerindex'=>'', 'tileindex'=>'', 'shapeindex'=>'', 'addtoquery'=>''],
'mapObj::queryByPoint' => ['int', 'point'=>'pointObj', 'mode'=>'int', 'buffer'=>'float'],
'mapObj::queryByRect' => ['int', 'rect'=>'rectObj'],
'mapObj::queryByShape' => ['int', 'shape'=>'shapeObj'],
'mapObj::removeLayer' => ['layerObj', 'nIndex'=>'int'],
'mapObj::removeMetaData' => ['int', 'name'=>'string'],
'mapObj::removeOutputFormat' => ['int', 'name'=>'string'],
'mapObj::save' => ['int', 'filename'=>'string'],
'mapObj::saveMapContext' => ['int', 'filename'=>'string'],
'mapObj::saveQuery' => ['int', 'filename'=>'string', 'results'=>'int'],
'mapObj::scaleExtent' => ['int', 'zoomfactor'=>'float', 'minscaledenom'=>'float', 'maxscaledenom'=>'float'],
'mapObj::selectOutputFormat' => ['int', 'type'=>'string'],
'mapObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'mapObj::setCenter' => ['int', 'center'=>'pointObj'],
'mapObj::setConfigOption' => ['int', 'key'=>'string', 'value'=>'string'],
'mapObj::setExtent' => ['void', 'minx'=>'float', 'miny'=>'float', 'maxx'=>'float', 'maxy'=>'float'],
'mapObj::setFontSet' => ['int', 'fileName'=>'string'],
'mapObj::setMetaData' => ['int', 'name'=>'string', 'value'=>'string'],
'mapObj::setProjection' => ['int', 'proj_params'=>'string', 'bSetUnitsAndExtents'=>'bool'],
'mapObj::setRotation' => ['int', 'rotation_angle'=>'float'],
'mapObj::setSize' => ['int', 'width'=>'int', 'height'=>'int'],
'mapObj::setSymbolSet' => ['int', 'fileName'=>'string'],
'mapObj::setWKTProjection' => ['int', 'proj_params'=>'string', 'bSetUnitsAndExtents'=>'bool'],
'mapObj::zoomPoint' => ['int', 'nZoomFactor'=>'int', 'oPixelPos'=>'pointObj', 'nImageWidth'=>'int', 'nImageHeight'=>'int', 'oGeorefExt'=>'rectObj'],
'mapObj::zoomRectangle' => ['int', 'oPixelExt'=>'rectObj', 'nImageWidth'=>'int', 'nImageHeight'=>'int', 'oGeorefExt'=>'rectObj'],
'mapObj::zoomScale' => ['int', 'nScaleDenom'=>'float', 'oPixelPos'=>'pointObj', 'nImageWidth'=>'int', 'nImageHeight'=>'int', 'oGeorefExt'=>'rectObj', 'oMaxGeorefExt'=>'rectObj'],
'max' => ['mixed', 'value'=>'non-empty-array'],
'max\'1' => ['mixed', 'value'=>'', 'values'=>'', '...args='=>''],
'maxdb::__construct' => ['void', 'host='=>'string', 'username='=>'string', 'passwd='=>'string', 'dbname='=>'string', 'port='=>'int', 'socket='=>'string'],
'maxdb::affected_rows' => ['int', 'link'=>''],
'maxdb::auto_commit' => ['bool', 'link'=>'', 'mode'=>'bool'],
'maxdb::change_user' => ['bool', 'link'=>'', 'user'=>'string', 'password'=>'string', 'database'=>'string'],
'maxdb::character_set_name' => ['string', 'link'=>''],
'maxdb::close' => ['bool', 'link'=>''],
'maxdb::commit' => ['bool', 'link'=>''],
'maxdb::disable_reads_from_master' => ['', 'link'=>''],
'maxdb::errno' => ['int', 'link'=>''],
'maxdb::error' => ['string', 'link'=>''],
'maxdb::field_count' => ['int', 'link'=>''],
'maxdb::get_host_info' => ['string', 'link'=>''],
'maxdb::info' => ['string', 'link'=>''],
'maxdb::insert_id' => ['', 'link'=>''],
'maxdb::kill' => ['bool', 'link'=>'', 'processid'=>'int'],
'maxdb::more_results' => ['bool', 'link'=>''],
'maxdb::multi_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb::next_result' => ['bool', 'link'=>''],
'maxdb::num_rows' => ['int', 'result'=>''],
'maxdb::options' => ['bool', 'link'=>'', 'option'=>'int', 'value'=>''],
'maxdb::ping' => ['bool', 'link'=>''],
'maxdb::prepare' => ['maxdb_stmt', 'link'=>'', 'query'=>'string'],
'maxdb::protocol_version' => ['string', 'link'=>''],
'maxdb::query' => ['', 'link'=>'', 'query'=>'string', 'resultmode='=>'int'],
'maxdb::real_connect' => ['bool', 'link'=>'', 'hostname='=>'string', 'username='=>'string', 'passwd='=>'string', 'dbname='=>'string', 'port='=>'int', 'socket='=>'string'],
'maxdb::real_escape_string' => ['string', 'link'=>'', 'escapestr'=>'string'],
'maxdb::real_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb::rollback' => ['bool', 'link'=>''],
'maxdb::rpl_query_type' => ['int', 'link'=>''],
'maxdb::select_db' => ['bool', 'link'=>'', 'dbname'=>'string'],
'maxdb::send_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb::server_info' => ['string', 'link'=>''],
'maxdb::server_version' => ['int', 'link'=>''],
'maxdb::sqlstate' => ['string', 'link'=>''],
'maxdb::ssl_set' => ['bool', 'link'=>'', 'key'=>'string', 'cert'=>'string', 'ca'=>'string', 'capath'=>'string', 'cipher'=>'string'],
'maxdb::stat' => ['string', 'link'=>''],
'maxdb::stmt_init' => ['object', 'link'=>''],
'maxdb::store_result' => ['bool', 'link'=>''],
'maxdb::thread_id' => ['int', 'link'=>''],
'maxdb::use_result' => ['resource', 'link'=>''],
'maxdb::warning_count' => ['int', 'link'=>''],
'maxdb_affected_rows' => ['int', 'link'=>'resource'],
'maxdb_autocommit' => ['bool', 'link'=>'', 'mode'=>'bool'],
'maxdb_change_user' => ['bool', 'link'=>'', 'user'=>'string', 'password'=>'string', 'database'=>'string'],
'maxdb_character_set_name' => ['string', 'link'=>''],
'maxdb_close' => ['bool', 'link'=>''],
'maxdb_commit' => ['bool', 'link'=>''],
'maxdb_connect' => ['resource', 'host='=>'string', 'username='=>'string', 'passwd='=>'string', 'dbname='=>'string', 'port='=>'int', 'socket='=>'string'],
'maxdb_connect_errno' => ['int'],
'maxdb_connect_error' => ['string'],
'maxdb_data_seek' => ['bool', 'result'=>'', 'offset'=>'int'],
'maxdb_debug' => ['void', 'debug'=>'string'],
'maxdb_disable_reads_from_master' => ['', 'link'=>''],
'maxdb_disable_rpl_parse' => ['bool', 'link'=>'resource'],
'maxdb_dump_debug_info' => ['bool', 'link'=>'resource'],
'maxdb_embedded_connect' => ['resource', 'dbname='=>'string'],
'maxdb_enable_reads_from_master' => ['bool', 'link'=>'resource'],
'maxdb_enable_rpl_parse' => ['bool', 'link'=>'resource'],
'maxdb_errno' => ['int', 'link'=>'resource'],
'maxdb_error' => ['string', 'link'=>'resource'],
'maxdb_fetch_array' => ['', 'result'=>'', 'resulttype='=>'int'],
'maxdb_fetch_assoc' => ['array', 'result'=>''],
'maxdb_fetch_field' => ['', 'result'=>''],
'maxdb_fetch_field_direct' => ['', 'result'=>'', 'fieldnr'=>'int'],
'maxdb_fetch_fields' => ['', 'result'=>''],
'maxdb_fetch_lengths' => ['array', 'result'=>'resource'],
'maxdb_fetch_object' => ['object', 'result'=>'object'],
'maxdb_fetch_row' => ['', 'result'=>''],
'maxdb_field_count' => ['int', 'link'=>''],
'maxdb_field_seek' => ['bool', 'result'=>'', 'fieldnr'=>'int'],
'maxdb_field_tell' => ['int', 'result'=>'resource'],
'maxdb_free_result' => ['', 'result'=>''],
'maxdb_get_client_info' => ['string'],
'maxdb_get_client_version' => ['int'],
'maxdb_get_host_info' => ['string', 'link'=>'resource'],
'maxdb_get_proto_info' => ['string', 'link'=>'resource'],
'maxdb_get_server_info' => ['string', 'link'=>'resource'],
'maxdb_get_server_version' => ['int', 'link'=>'resource'],
'maxdb_info' => ['string', 'link'=>'resource'],
'maxdb_init' => ['resource'],
'maxdb_insert_id' => ['mixed', 'link'=>'resource'],
'maxdb_kill' => ['bool', 'link'=>'', 'processid'=>'int'],
'maxdb_master_query' => ['bool', 'link'=>'resource', 'query'=>'string'],
'maxdb_more_results' => ['bool', 'link'=>'resource'],
'maxdb_multi_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb_next_result' => ['bool', 'link'=>'resource'],
'maxdb_num_fields' => ['int', 'result'=>'resource'],
'maxdb_num_rows' => ['int', 'result'=>'resource'],
'maxdb_options' => ['bool', 'link'=>'', 'option'=>'int', 'value'=>''],
'maxdb_ping' => ['bool', 'link'=>''],
'maxdb_prepare' => ['maxdb_stmt', 'link'=>'', 'query'=>'string'],
'maxdb_query' => ['', 'link'=>'', 'query'=>'string', 'resultmode='=>'int'],
'maxdb_real_connect' => ['bool', 'link'=>'', 'hostname='=>'string', 'username='=>'string', 'passwd='=>'string', 'dbname='=>'string', 'port='=>'int', 'socket='=>'string'],
'maxdb_real_escape_string' => ['string', 'link'=>'', 'escapestr'=>'string'],
'maxdb_real_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb_report' => ['bool', 'flags'=>'int'],
'maxdb_result::current_field' => ['int', 'result'=>''],
'maxdb_result::data_seek' => ['bool', 'result'=>'', 'offset'=>'int'],
'maxdb_result::fetch_array' => ['', 'result'=>'', 'resulttype='=>'int'],
'maxdb_result::fetch_assoc' => ['array', 'result'=>''],
'maxdb_result::fetch_field' => ['', 'result'=>''],
'maxdb_result::fetch_field_direct' => ['', 'result'=>'', 'fieldnr'=>'int'],
'maxdb_result::fetch_fields' => ['', 'result'=>''],
'maxdb_result::fetch_object' => ['object', 'result'=>'object'],
'maxdb_result::fetch_row' => ['', 'result'=>''],
'maxdb_result::field_count' => ['int', 'result'=>''],
'maxdb_result::field_seek' => ['bool', 'result'=>'', 'fieldnr'=>'int'],
'maxdb_result::free' => ['', 'result'=>''],
'maxdb_result::lengths' => ['array', 'result'=>''],
'maxdb_rollback' => ['bool', 'link'=>''],
'maxdb_rpl_parse_enabled' => ['int', 'link'=>'resource'],
'maxdb_rpl_probe' => ['bool', 'link'=>'resource'],
'maxdb_rpl_query_type' => ['int', 'link'=>''],
'maxdb_select_db' => ['bool', 'link'=>'resource', 'dbname'=>'string'],
'maxdb_send_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb_server_end' => ['void'],
'maxdb_server_init' => ['bool', 'server='=>'array', 'groups='=>'array'],
'maxdb_sqlstate' => ['string', 'link'=>'resource'],
'maxdb_ssl_set' => ['bool', 'link'=>'', 'key'=>'string', 'cert'=>'string', 'ca'=>'string', 'capath'=>'string', 'cipher'=>'string'],
'maxdb_stat' => ['string', 'link'=>''],
'maxdb_stmt::affected_rows' => ['int', 'stmt'=>''],
'maxdb_stmt::bind_param' => ['bool', 'stmt'=>'', 'types'=>'string', '&...rw_var'=>''],
'maxdb_stmt::bind_param\'1' => ['bool', 'stmt'=>'', 'types'=>'string', '&rw_var'=>'array'],
'maxdb_stmt::bind_result' => ['bool', 'stmt'=>'', '&w_var1'=>'', '&...w_vars='=>''],
'maxdb_stmt::close' => ['bool', 'stmt'=>''],
'maxdb_stmt::close_long_data' => ['bool', 'stmt'=>'', 'param_nr'=>'int'],
'maxdb_stmt::data_seek' => ['bool', 'statement'=>'', 'offset'=>'int'],
'maxdb_stmt::errno' => ['int', 'stmt'=>''],
'maxdb_stmt::error' => ['string', 'stmt'=>''],
'maxdb_stmt::execute' => ['bool', 'stmt'=>''],
'maxdb_stmt::fetch' => ['bool', 'stmt'=>''],
'maxdb_stmt::free_result' => ['', 'stmt'=>''],
'maxdb_stmt::num_rows' => ['int', 'stmt'=>''],
'maxdb_stmt::param_count' => ['int', 'stmt'=>''],
'maxdb_stmt::prepare' => ['', 'stmt'=>'', 'query'=>'string'],
'maxdb_stmt::reset' => ['bool', 'stmt'=>''],
'maxdb_stmt::result_metadata' => ['resource', 'stmt'=>''],
'maxdb_stmt::send_long_data' => ['bool', 'stmt'=>'', 'param_nr'=>'int', 'data'=>'string'],
'maxdb_stmt::stmt_send_long_data' => ['bool', 'param_nr'=>'int', 'data'=>'string'],
'maxdb_stmt::store_result' => ['bool'],
'maxdb_stmt_affected_rows' => ['int', 'stmt'=>'resource'],
'maxdb_stmt_bind_param' => ['bool', 'stmt'=>'', 'types'=>'string', 'var1'=>'', '...args='=>'', 'var='=>'array'],
'maxdb_stmt_bind_result' => ['bool', 'stmt'=>'', '&w_var1'=>'', '&...w_vars='=>''],
'maxdb_stmt_close' => ['bool', 'stmt'=>''],
'maxdb_stmt_close_long_data' => ['bool', 'stmt'=>'', 'param_nr'=>'int'],
'maxdb_stmt_data_seek' => ['bool', 'statement'=>'', 'offset'=>'int'],
'maxdb_stmt_errno' => ['int', 'stmt'=>'resource'],
'maxdb_stmt_error' => ['string', 'stmt'=>'resource'],
'maxdb_stmt_execute' => ['bool', 'stmt'=>''],
'maxdb_stmt_fetch' => ['bool', 'stmt'=>''],
'maxdb_stmt_free_result' => ['', 'stmt'=>''],
'maxdb_stmt_init' => ['object', 'link'=>''],
'maxdb_stmt_num_rows' => ['int', 'stmt'=>'resource'],
'maxdb_stmt_param_count' => ['int', 'stmt'=>'resource'],
'maxdb_stmt_prepare' => ['', 'stmt'=>'', 'query'=>'string'],
'maxdb_stmt_reset' => ['bool', 'stmt'=>''],
'maxdb_stmt_result_metadata' => ['resource', 'stmt'=>''],
'maxdb_stmt_send_long_data' => ['bool', 'stmt'=>'', 'param_nr'=>'int', 'data'=>'string'],
'maxdb_stmt_sqlstate' => ['string', 'stmt'=>'resource'],
'maxdb_stmt_store_result' => ['bool', 'stmt'=>''],
'maxdb_store_result' => ['bool', 'link'=>''],
'maxdb_thread_id' => ['int', 'link'=>'resource'],
'maxdb_thread_safe' => ['bool'],
'maxdb_use_result' => ['resource', 'link'=>''],
'maxdb_warning_count' => ['int', 'link'=>'resource'],
'mb_check_encoding' => ['bool', 'value='=>'array|string|null', 'encoding='=>'string|null'],
'mb_chr' => ['string|false', 'codepoint'=>'int', 'encoding='=>'string|null'],
'mb_convert_case' => ['string', 'string'=>'string', 'mode'=>'int', 'encoding='=>'string|null'],
'mb_convert_encoding' => ['string|false', 'string'=>'string', 'to_encoding'=>'string', 'from_encoding='=>'array|string|null'],
'mb_convert_encoding\'1' => ['array', 'string'=>'array', 'to_encoding'=>'string', 'from_encoding='=>'array|string|null'],
'mb_convert_kana' => ['string', 'string'=>'string', 'mode='=>'string', 'encoding='=>'string|null'],
'mb_convert_variables' => ['string|false', 'to_encoding'=>'string', 'from_encoding'=>'array|string', '&rw_var'=>'string|array|object', '&...rw_vars='=>'string|array|object'],
'mb_decode_mimeheader' => ['string', 'string'=>'string'],
'mb_decode_numericentity' => ['string', 'string'=>'string', 'map'=>'array', 'encoding='=>'string|null'],
'mb_detect_encoding' => ['string|false', 'string'=>'string', 'encodings='=>'array|string|null', 'strict='=>'bool'],
'mb_detect_order' => ['bool|list<string>', 'encoding='=>'array|string|null'],
'mb_encode_mimeheader' => ['string', 'string'=>'string', 'charset='=>'string|null', 'transfer_encoding='=>'string|null', 'newline='=>'string', 'indent='=>'int'],
'mb_encode_numericentity' => ['string', 'string'=>'string', 'map'=>'array', 'encoding='=>'string|null', 'hex='=>'bool'],
'mb_encoding_aliases' => ['list<string>|false', 'encoding'=>'string'],
'mb_ereg' => ['bool', 'pattern'=>'string', 'string'=>'string', '&w_matches='=>'array|null'],
'mb_ereg_match' => ['bool', 'pattern'=>'string', 'string'=>'string', 'options='=>'string|null'],
'mb_ereg_replace' => ['string|false|null', 'pattern'=>'string', 'replacement'=>'string', 'string'=>'string', 'options='=>'string|null'],
'mb_ereg_replace_callback' => ['string|false', 'pattern'=>'string', 'callback'=>'callable', 'string'=>'string', 'options='=>'string|null'],
'mb_ereg_search' => ['bool', 'pattern='=>'string|null', 'options='=>'string|null'],
'mb_ereg_search_getpos' => ['int'],
'mb_ereg_search_getregs' => ['string[]|false'],
'mb_ereg_search_init' => ['bool', 'string'=>'string', 'pattern='=>'string|null', 'options='=>'string|null'],
'mb_ereg_search_pos' => ['int[]|false', 'pattern='=>'string|null', 'options='=>'string|null'],
'mb_ereg_search_regs' => ['string[]|false', 'pattern='=>'string|null', 'options='=>'string|null'],
'mb_ereg_search_setpos' => ['bool', 'offset'=>'int'],
'mb_eregi' => ['bool', 'pattern'=>'string', 'string'=>'string', '&w_matches='=>'array|null'],
'mb_eregi_replace' => ['string|false|null', 'pattern'=>'string', 'replacement'=>'string', 'string'=>'string', 'options='=>'string|null'],
'mb_get_info' => ['array|string|int|false', 'type='=>'string'],
'mb_http_input' => ['array|string|false', 'type='=>'string|null'],
'mb_http_output' => ['string|bool', 'encoding='=>'string|null'],
'mb_internal_encoding' => ['string|bool', 'encoding='=>'string|null'],
'mb_language' => ['string|bool', 'language='=>'string|null'],
'mb_list_encodings' => ['list<string>'],
'mb_ord' => ['int|false', 'string'=>'string', 'encoding='=>'string|null'],
'mb_output_handler' => ['string', 'string'=>'string', 'status'=>'int'],
'mb_parse_str' => ['bool', 'string'=>'string', '&w_result'=>'array'],
'mb_preferred_mime_name' => ['string|false', 'encoding'=>'string'],
'mb_regex_encoding' => ['string|bool', 'encoding='=>'string|null'],
'mb_regex_set_options' => ['string', 'options='=>'string|null'],
'mb_scrub' => ['string', 'string'=>'string', 'encoding='=>'string|null'],
'mb_send_mail' => ['bool', 'to'=>'string', 'subject'=>'string', 'message'=>'string', 'additional_headers='=>'string|array', 'additional_params='=>'string|null'],
'mb_split' => ['list<string>', 'pattern'=>'string', 'string'=>'string', 'limit='=>'int'],
'mb_str_split' => ['list<string>', 'string'=>'string', 'length='=>'positive-int', 'encoding='=>'string|null'],
'mb_strcut' => ['string', 'string'=>'string', 'start'=>'int', 'length='=>'?int', 'encoding='=>'string|null'],
'mb_strimwidth' => ['string', 'string'=>'string', 'start'=>'int', 'width'=>'int', 'trim_marker='=>'string', 'encoding='=>'string|null'],
'mb_stripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string|null'],
'mb_stristr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool', 'encoding='=>'string|null'],
'mb_strlen' => ['int', 'string'=>'string', 'encoding='=>'string|null'],
'mb_strpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string|null'],
'mb_strrchr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool', 'encoding='=>'string|null'],
'mb_strrichr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool', 'encoding='=>'string|null'],
'mb_strripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string|null'],
'mb_strrpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string|null'],
'mb_strstr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool', 'encoding='=>'string|null'],
'mb_strtolower' => ['lowercase-string', 'string'=>'string', 'encoding='=>'string|null'],
'mb_strtoupper' => ['string', 'string'=>'string', 'encoding='=>'string|null'],
'mb_strwidth' => ['int', 'string'=>'string', 'encoding='=>'string|null'],
'mb_substitute_character' => ['bool|int|string', 'substitute_character='=>'int|string|null'],
'mb_substr' => ['string', 'string'=>'string', 'start'=>'int', 'length='=>'?int', 'encoding='=>'string|null'],
'mb_substr_count' => ['int', 'haystack'=>'string', 'needle'=>'string', 'encoding='=>'string|null'],
'mcrypt_cbc' => ['string', 'cipher'=>'string|int', 'key'=>'string', 'data'=>'string', 'mode'=>'int', 'iv='=>'string'],
'mcrypt_cfb' => ['string', 'cipher'=>'string|int', 'key'=>'string', 'data'=>'string', 'mode'=>'int', 'iv='=>'string'],
'mcrypt_create_iv' => ['string|false', 'size'=>'int', 'source='=>'int'],
'mcrypt_decrypt' => ['string', 'cipher'=>'string', 'key'=>'string', 'data'=>'string', 'mode'=>'string', 'iv='=>'string'],
'mcrypt_ecb' => ['string', 'cipher'=>'string|int', 'key'=>'string', 'data'=>'string', 'mode'=>'int', 'iv='=>'string'],
'mcrypt_enc_get_algorithms_name' => ['string', 'td'=>'resource'],
'mcrypt_enc_get_block_size' => ['int', 'td'=>'resource'],
'mcrypt_enc_get_iv_size' => ['int', 'td'=>'resource'],
'mcrypt_enc_get_key_size' => ['int', 'td'=>'resource'],
'mcrypt_enc_get_modes_name' => ['string', 'td'=>'resource'],
'mcrypt_enc_get_supported_key_sizes' => ['array', 'td'=>'resource'],
'mcrypt_enc_is_block_algorithm' => ['bool', 'td'=>'resource'],
'mcrypt_enc_is_block_algorithm_mode' => ['bool', 'td'=>'resource'],
'mcrypt_enc_is_block_mode' => ['bool', 'td'=>'resource'],
'mcrypt_enc_self_test' => ['int|false', 'td'=>'resource'],
'mcrypt_encrypt' => ['string', 'cipher'=>'string', 'key'=>'string', 'data'=>'string', 'mode'=>'string', 'iv='=>'string'],
'mcrypt_generic' => ['string', 'td'=>'resource', 'data'=>'string'],
'mcrypt_generic_deinit' => ['bool', 'td'=>'resource'],
'mcrypt_generic_end' => ['bool', 'td'=>'resource'],
'mcrypt_generic_init' => ['int|false', 'td'=>'resource', 'key'=>'string', 'iv'=>'string'],
'mcrypt_get_block_size' => ['int', 'cipher'=>'int|string', 'module'=>'string'],
'mcrypt_get_cipher_name' => ['string|false', 'cipher'=>'int|string'],
'mcrypt_get_iv_size' => ['int|false', 'cipher'=>'int|string', 'module'=>'string'],
'mcrypt_get_key_size' => ['int', 'cipher'=>'int|string', 'module'=>'string'],
'mcrypt_list_algorithms' => ['array', 'lib_dir='=>'string'],
'mcrypt_list_modes' => ['array', 'lib_dir='=>'string'],
'mcrypt_module_close' => ['bool', 'td'=>'resource'],
'mcrypt_module_get_algo_block_size' => ['int', 'algorithm'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_get_algo_key_size' => ['int', 'algorithm'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_get_supported_key_sizes' => ['array', 'algorithm'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_is_block_algorithm' => ['bool', 'algorithm'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_is_block_algorithm_mode' => ['bool', 'mode'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_is_block_mode' => ['bool', 'mode'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_open' => ['resource|false', 'cipher'=>'string', 'cipher_directory'=>'string', 'mode'=>'string', 'mode_directory'=>'string'],
'mcrypt_module_self_test' => ['bool', 'algorithm'=>'string', 'lib_dir='=>'string'],
'mcrypt_ofb' => ['string', 'cipher'=>'int|string', 'key'=>'string', 'data'=>'string', 'mode'=>'int', 'iv='=>'string'],
'md5' => ['string', 'string'=>'string', 'binary='=>'bool'],
'md5_file' => ['string|false', 'filename'=>'string', 'binary='=>'bool'],
'mdecrypt_generic' => ['string', 'td'=>'resource', 'data'=>'string'],
'Memcache::add' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'Memcache::addServer' => ['bool', 'host'=>'string', 'port='=>'int', 'persistent='=>'bool', 'weight='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'callable', 'timeoutms='=>'int'],
'Memcache::append' => [''],
'Memcache::cas' => [''],
'Memcache::close' => ['bool'],
'Memcache::connect' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'int'],
'Memcache::decrement' => ['int', 'key'=>'string', 'value='=>'int'],
'Memcache::delete' => ['bool', 'key'=>'string', 'timeout='=>'int'],
'Memcache::findServer' => [''],
'Memcache::flush' => ['bool'],
'Memcache::get' => ['string|array|false', 'key'=>'string', 'flags='=>'array', 'keys='=>'array'],
'Memcache::get\'1' => ['array', 'key'=>'string[]', 'flags='=>'int[]'],
'Memcache::getExtendedStats' => ['array', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'Memcache::getServerStatus' => ['int', 'host'=>'string', 'port='=>'int'],
'Memcache::getStats' => ['array', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'Memcache::getVersion' => ['string'],
'Memcache::increment' => ['int', 'key'=>'string', 'value='=>'int'],
'Memcache::pconnect' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'int'],
'Memcache::prepend' => ['string'],
'Memcache::replace' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'Memcache::set' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'Memcache::setCompressThreshold' => ['bool', 'threshold'=>'int', 'min_savings='=>'float'],
'Memcache::setFailureCallback' => [''],
'Memcache::setServerParams' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'callable'],
'memcache_add' => ['bool', 'memcache_obj'=>'Memcache', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'memcache_add_server' => ['bool', 'memcache_obj'=>'Memcache', 'host'=>'string', 'port='=>'int', 'persistent='=>'bool', 'weight='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'callable', 'timeoutms='=>'int'],
'memcache_append' => ['', 'memcache_obj'=>'Memcache'],
'memcache_cas' => ['', 'memcache_obj'=>'Memcache'],
'memcache_close' => ['bool', 'memcache_obj'=>'Memcache'],
'memcache_connect' => ['Memcache|false', 'host'=>'string', 'port='=>'int', 'timeout='=>'int'],
'memcache_debug' => ['bool', 'on_off'=>'bool'],
'memcache_decrement' => ['int', 'memcache_obj'=>'Memcache', 'key'=>'string', 'value='=>'int'],
'memcache_delete' => ['bool', 'memcache_obj'=>'Memcache', 'key'=>'string', 'timeout='=>'int'],
'memcache_flush' => ['bool', 'memcache_obj'=>'Memcache'],
'memcache_get' => ['string', 'memcache_obj'=>'Memcache', 'key'=>'string', 'flags='=>'int'],
'memcache_get\'1' => ['array', 'memcache_obj'=>'Memcache', 'key'=>'string[]', 'flags='=>'int[]'],
'memcache_get_extended_stats' => ['array', 'memcache_obj'=>'Memcache', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'memcache_get_server_status' => ['int', 'memcache_obj'=>'Memcache', 'host'=>'string', 'port='=>'int'],
'memcache_get_stats' => ['array', 'memcache_obj'=>'Memcache', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'memcache_get_version' => ['string', 'memcache_obj'=>'Memcache'],
'memcache_increment' => ['int', 'memcache_obj'=>'Memcache', 'key'=>'string', 'value='=>'int'],
'memcache_pconnect' => ['Memcache|false', 'host'=>'string', 'port='=>'int', 'timeout='=>'int'],
'memcache_prepend' => ['string', 'memcache_obj'=>'Memcache'],
'memcache_replace' => ['bool', 'memcache_obj'=>'Memcache', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'memcache_set' => ['bool', 'memcache_obj'=>'Memcache', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'memcache_set_compress_threshold' => ['bool', 'memcache_obj'=>'Memcache', 'threshold'=>'int', 'min_savings='=>'float'],
'memcache_set_failure_callback' => ['', 'memcache_obj'=>'Memcache'],
'memcache_set_server_params' => ['bool', 'memcache_obj'=>'Memcache', 'host'=>'string', 'port='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'callable'],
'Memcached::__construct' => ['void', 'persistent_id='=>'mixed|string', 'on_new_object_cb='=>'mixed'],
'Memcached::add' => ['bool', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::addByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::addServer' => ['bool', 'host'=>'string', 'port'=>'int', 'weight='=>'int'],
'Memcached::addServers' => ['bool', 'servers'=>'array'],
'Memcached::append' => ['bool', 'key'=>'string', 'value'=>'string'],
'Memcached::appendByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'value'=>'string'],
'Memcached::cas' => ['bool', 'cas_token'=>'float', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::casByKey' => ['bool', 'cas_token'=>'float', 'server_key'=>'string', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::decrement' => ['int|false', 'key'=>'string', 'offset='=>'int', 'initial_value='=>'int', 'expiry='=>'int'],
'Memcached::decrementByKey' => ['int|false', 'server_key'=>'string', 'key'=>'string', 'offset='=>'int', 'initial_value='=>'int', 'expiry='=>'int'],
'Memcached::delete' => ['bool', 'key'=>'string', 'time='=>'int'],
'Memcached::deleteByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'time='=>'int'],
'Memcached::deleteMulti' => ['array', 'keys'=>'array', 'time='=>'int'],
'Memcached::deleteMultiByKey' => ['bool', 'server_key'=>'string', 'keys'=>'array', 'time='=>'int'],
'Memcached::fetch' => ['array|false'],
'Memcached::fetchAll' => ['array|false'],
'Memcached::flush' => ['bool', 'delay='=>'int'],
'Memcached::flushBuffers' => [''],
'Memcached::get' => ['mixed|false', 'key'=>'string', 'cache_cb='=>'?callable', 'flags='=>'int'],
'Memcached::getAllKeys' => ['array|false'],
'Memcached::getByKey' => ['mixed|false', 'server_key'=>'string', 'key'=>'string', 'value_cb='=>'?callable', 'flags='=>'int'],
'Memcached::getDelayed' => ['bool', 'keys'=>'array', 'with_cas='=>'bool', 'value_cb='=>'callable'],
'Memcached::getDelayedByKey' => ['bool', 'server_key'=>'string', 'keys'=>'array', 'with_cas='=>'bool', 'value_cb='=>'?callable'],
'Memcached::getLastDisconnectedServer' => [''],
'Memcached::getLastErrorCode' => [''],
'Memcached::getLastErrorErrno' => [''],
'Memcached::getLastErrorMessage' => [''],
'Memcached::getMulti' => ['array|false', 'keys'=>'array', 'flags='=>'int'],
'Memcached::getMultiByKey' => ['array|false', 'server_key'=>'string', 'keys'=>'array', 'flags='=>'int'],
'Memcached::getOption' => ['mixed|false', 'option'=>'int'],
'Memcached::getResultCode' => ['int'],
'Memcached::getResultMessage' => ['string'],
'Memcached::getServerByKey' => ['array', 'server_key'=>'string'],
'Memcached::getServerList' => ['array'],
'Memcached::getStats' => ['array', 'type='=>'?string'],
'Memcached::getVersion' => ['array'],
'Memcached::increment' => ['int|false', 'key'=>'string', 'offset='=>'int', 'initial_value='=>'int', 'expiry='=>'int'],
'Memcached::incrementByKey' => ['int|false', 'server_key'=>'string', 'key'=>'string', 'offset='=>'int', 'initial_value='=>'int', 'expiry='=>'int'],
'Memcached::isPersistent' => ['bool'],
'Memcached::isPristine' => ['bool'],
'Memcached::prepend' => ['bool', 'key'=>'string', 'value'=>'string'],
'Memcached::prependByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'value'=>'string'],
'Memcached::quit' => ['bool'],
'Memcached::replace' => ['bool', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::replaceByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::resetServerList' => ['bool'],
'Memcached::set' => ['bool', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::setBucket' => ['', 'host_map'=>'array', 'forward_map'=>'array', 'replicas'=>''],
'Memcached::setByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::setEncodingKey' => ['', 'key'=>''],
'Memcached::setMulti' => ['bool', 'items'=>'array', 'expiration='=>'int'],
'Memcached::setMultiByKey' => ['bool', 'server_key'=>'string', 'items'=>'array', 'expiration='=>'int'],
'Memcached::setOption' => ['bool', 'option'=>'int', 'value'=>'mixed'],
'Memcached::setOptions' => ['bool', 'options'=>'array'],
'Memcached::setSaslAuthData' => ['void', 'username'=>'string', 'password'=>'string'],
'Memcached::touch' => ['bool', 'key'=>'string', 'expiration'=>'int'],
'Memcached::touchByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'expiration'=>'int'],
'MemcachePool::add' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'MemcachePool::addServer' => ['bool', 'host'=>'string', 'port='=>'int', 'persistent='=>'bool', 'weight='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'?callable', 'timeoutms='=>'int'],
'MemcachePool::append' => [''],
'MemcachePool::cas' => [''],
'MemcachePool::close' => ['bool'],
'MemcachePool::connect' => ['bool', 'host'=>'string', 'port'=>'int', 'timeout='=>'int'],
'MemcachePool::decrement' => ['int|false', 'key'=>'', 'value='=>'int|mixed'],
'MemcachePool::delete' => ['bool', 'key'=>'', 'timeout='=>'int|mixed'],
'MemcachePool::findServer' => [''],
'MemcachePool::flush' => ['bool'],
'MemcachePool::get' => ['array|string|false', 'key'=>'array|string', '&flags='=>'array|int'],
'MemcachePool::getExtendedStats' => ['array|false', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'MemcachePool::getServerStatus' => ['int', 'host'=>'string', 'port='=>'int'],
'MemcachePool::getStats' => ['array|false', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'MemcachePool::getVersion' => ['string|false'],
'MemcachePool::increment' => ['int|false', 'key'=>'', 'value='=>'int|mixed'],
'MemcachePool::prepend' => ['string'],
'MemcachePool::replace' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'MemcachePool::set' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'MemcachePool::setCompressThreshold' => ['bool', 'thresold'=>'int', 'min_saving='=>'float'],
'MemcachePool::setFailureCallback' => [''],
'MemcachePool::setServerParams' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'?callable'],
'memory_get_peak_usage' => ['int', 'real_usage='=>'bool'],
'memory_get_usage' => ['int', 'real_usage='=>'bool'],
'MessageFormatter::__construct' => ['void', 'locale'=>'string', 'pattern'=>'string'],
'MessageFormatter::create' => ['MessageFormatter', 'locale'=>'string', 'pattern'=>'string'],
'MessageFormatter::format' => ['false|string', 'args'=>'array'],
'MessageFormatter::formatMessage' => ['false|string', 'locale'=>'string', 'pattern'=>'string', 'args'=>'array'],
'MessageFormatter::getErrorCode' => ['int'],
'MessageFormatter::getErrorMessage' => ['string'],
'MessageFormatter::getLocale' => ['string'],
'MessageFormatter::getPattern' => ['string'],
'MessageFormatter::parse' => ['array|false', 'value'=>'string'],
'MessageFormatter::parseMessage' => ['array|false', 'locale'=>'string', 'pattern'=>'string', 'source'=>'string'],
'MessageFormatter::setPattern' => ['bool', 'pattern'=>'string'],
'metaphone' => ['string|false', 'string'=>'string', 'max_phonemes='=>'int'],
'method_exists' => ['bool', 'object_or_class'=>'object|class-string|interface-string', 'method'=>'string'],
'mhash' => ['string', 'algo'=>'int', 'data'=>'string', 'key='=>'string'],
'mhash_count' => ['int'],
'mhash_get_block_size' => ['int|false', 'algo'=>'int'],
'mhash_get_hash_name' => ['string|false', 'algo'=>'int'],
'mhash_keygen_s2k' => ['string|false', 'algo'=>'int', 'password'=>'string', 'salt'=>'string', 'length'=>'int'],
'microtime' => ['string', 'as_float='=>'false'],
'microtime\'1' => ['float', 'as_float='=>'true'],
'mime_content_type' => ['string|false', 'filename'=>'string|resource'],
'min' => ['mixed', 'value'=>'non-empty-array'],
'min\'1' => ['mixed', 'value'=>'', 'values'=>'', '...args='=>''],
'ming_keypress' => ['int', 'char'=>'string'],
'ming_setcubicthreshold' => ['void', 'threshold'=>'int'],
'ming_setscale' => ['void', 'scale'=>'float'],
'ming_setswfcompression' => ['void', 'level'=>'int'],
'ming_useconstants' => ['void', 'use'=>'int'],
'ming_useswfversion' => ['void', 'version'=>'int'],
'mkdir' => ['bool', 'directory'=>'string', 'permissions='=>'int', 'recursive='=>'bool', 'context='=>'resource'],
'mktime' => ['int|false', 'hour'=>'int', 'minute='=>'int|null', 'second='=>'int|null', 'month='=>'int|null', 'day='=>'int|null', 'year='=>'int|null'],
'money_format' => ['string', 'format'=>'string', 'value'=>'float'],
'Mongo::__construct' => ['void', 'server='=>'string', 'options='=>'array', 'driver_options='=>'array'],
'Mongo::__get' => ['MongoDB', 'dbname'=>'string'],
'Mongo::__toString' => ['string'],
'Mongo::close' => ['bool'],
'Mongo::connect' => ['bool'],
'Mongo::connectUtil' => ['bool'],
'Mongo::dropDB' => ['array', 'db'=>'mixed'],
'Mongo::forceError' => ['bool'],
'Mongo::getConnections' => ['array'],
'Mongo::getHosts' => ['array'],
'Mongo::getPoolSize' => ['int'],
'Mongo::getReadPreference' => ['array'],
'Mongo::getSlave' => ['?string'],
'Mongo::getSlaveOkay' => ['bool'],
'Mongo::getWriteConcern' => ['array'],
'Mongo::killCursor' => ['', 'server_hash'=>'string', 'id'=>'MongoInt64|int'],
'Mongo::lastError' => ['?array'],
'Mongo::listDBs' => ['array'],
'Mongo::pairConnect' => ['bool'],
'Mongo::pairPersistConnect' => ['bool', 'username='=>'string', 'password='=>'string'],
'Mongo::persistConnect' => ['bool', 'username='=>'string', 'password='=>'string'],
'Mongo::poolDebug' => ['array'],
'Mongo::prevError' => ['array'],
'Mongo::resetError' => ['array'],
'Mongo::selectCollection' => ['MongoCollection', 'db'=>'string', 'collection'=>'string'],
'Mongo::selectDB' => ['MongoDB', 'name'=>'string'],
'Mongo::setPoolSize' => ['bool', 'size'=>'int'],
'Mongo::setReadPreference' => ['bool', 'readPreference'=>'string', 'tags='=>'array'],
'Mongo::setSlaveOkay' => ['bool', 'ok='=>'bool'],
'Mongo::switchSlave' => ['string'],
'MongoBinData::__construct' => ['void', 'data'=>'string', 'type='=>'int'],
'MongoBinData::__toString' => ['string'],
'MongoClient::__construct' => ['void', 'server='=>'string', 'options='=>'array', 'driver_options='=>'array'],
'MongoClient::__get' => ['MongoDB', 'dbname'=>'string'],
'MongoClient::__toString' => ['string'],
'MongoClient::close' => ['bool', 'connection='=>'bool|string'],
'MongoClient::connect' => ['bool'],
'MongoClient::dropDB' => ['array', 'db'=>'mixed'],
'MongoClient::getConnections' => ['array'],
'MongoClient::getHosts' => ['array'],
'MongoClient::getReadPreference' => ['array'],
'MongoClient::getWriteConcern' => ['array'],
'MongoClient::killCursor' => ['bool', 'server_hash'=>'string', 'id'=>'int|MongoInt64'],
'MongoClient::listDBs' => ['array'],
'MongoClient::selectCollection' => ['MongoCollection', 'db'=>'string', 'collection'=>'string'],
'MongoClient::selectDB' => ['MongoDB', 'name'=>'string'],
'MongoClient::setReadPreference' => ['bool', 'read_preference'=>'string', 'tags='=>'array'],
'MongoClient::setWriteConcern' => ['bool', 'w'=>'mixed', 'wtimeout='=>'int'],
'MongoClient::switchSlave' => ['string'],
'MongoCode::__construct' => ['void', 'code'=>'string', 'scope='=>'array'],
'MongoCode::__toString' => ['string'],
'MongoCollection::__construct' => ['void', 'db'=>'MongoDB', 'name'=>'string'],
'MongoCollection::__get' => ['MongoCollection', 'name'=>'string'],
'MongoCollection::__toString' => ['string'],
'MongoCollection::aggregate' => ['array', 'op'=>'array', 'op='=>'array', '...args='=>'array'],
'MongoCollection::aggregate\'1' => ['array', 'pipeline'=>'array', 'options='=>'array'],
'MongoCollection::aggregateCursor' => ['MongoCommandCursor', 'command'=>'array', 'options='=>'array'],
'MongoCollection::batchInsert' => ['array|bool', 'a'=>'array', 'options='=>'array'],
'MongoCollection::count' => ['int', 'query='=>'array', 'limit='=>'int', 'skip='=>'int'],
'MongoCollection::createDBRef' => ['array', 'a'=>'array'],
'MongoCollection::createIndex' => ['array', 'keys'=>'array', 'options='=>'array'],
'MongoCollection::deleteIndex' => ['array', 'keys'=>'string|array'],
'MongoCollection::deleteIndexes' => ['array'],
'MongoCollection::distinct' => ['array|false', 'key'=>'string', 'query='=>'array'],
'MongoCollection::drop' => ['array'],
'MongoCollection::ensureIndex' => ['bool', 'keys'=>'array', 'options='=>'array'],
'MongoCollection::find' => ['MongoCursor', 'query='=>'array', 'fields='=>'array'],
'MongoCollection::findAndModify' => ['array', 'query'=>'array', 'update='=>'array', 'fields='=>'array', 'options='=>'array'],
'MongoCollection::findOne' => ['?array', 'query='=>'array', 'fields='=>'array'],
'MongoCollection::getDBRef' => ['array', 'ref'=>'array'],
'MongoCollection::getIndexInfo' => ['array'],
'MongoCollection::getName' => ['string'],
'MongoCollection::getReadPreference' => ['array'],
'MongoCollection::getSlaveOkay' => ['bool'],
'MongoCollection::getWriteConcern' => ['array'],
'MongoCollection::group' => ['array', 'keys'=>'mixed', 'initial'=>'array', 'reduce'=>'MongoCode', 'options='=>'array'],
'MongoCollection::insert' => ['bool|array', 'a'=>'array|object', 'options='=>'array'],
'MongoCollection::parallelCollectionScan' => ['MongoCommandCursor[]', 'num_cursors'=>'int'],
'MongoCollection::remove' => ['bool|array', 'criteria='=>'array', 'options='=>'array'],
'MongoCollection::save' => ['bool|array', 'a'=>'array|object', 'options='=>'array'],
'MongoCollection::setReadPreference' => ['bool', 'read_preference'=>'string', 'tags='=>'array'],
'MongoCollection::setSlaveOkay' => ['bool', 'ok='=>'bool'],
'MongoCollection::setWriteConcern' => ['bool', 'w'=>'mixed', 'wtimeout='=>'int'],
'MongoCollection::toIndexString' => ['string', 'keys'=>'mixed'],
'MongoCollection::update' => ['bool', 'criteria'=>'array', 'newobj'=>'array', 'options='=>'array'],
'MongoCollection::validate' => ['array', 'scan_data='=>'bool'],
'MongoCommandCursor::__construct' => ['void', 'connection'=>'MongoClient', 'ns'=>'string', 'command'=>'array'],
'MongoCommandCursor::batchSize' => ['MongoCommandCursor', 'batchSize'=>'int'],
'MongoCommandCursor::createFromDocument' => ['MongoCommandCursor', 'connection'=>'MongoClient', 'hash'=>'string', 'document'=>'array'],
'MongoCommandCursor::current' => ['array'],
'MongoCommandCursor::dead' => ['bool'],
'MongoCommandCursor::getReadPreference' => ['array'],
'MongoCommandCursor::info' => ['array'],
'MongoCommandCursor::key' => ['int'],
'MongoCommandCursor::next' => ['void'],
'MongoCommandCursor::rewind' => ['array'],
'MongoCommandCursor::setReadPreference' => ['MongoCommandCursor', 'read_preference'=>'string', 'tags='=>'array'],
'MongoCommandCursor::timeout' => ['MongoCommandCursor', 'ms'=>'int'],
'MongoCommandCursor::valid' => ['bool'],
'MongoCursor::__construct' => ['void', 'connection'=>'MongoClient', 'ns'=>'string', 'query='=>'array', 'fields='=>'array'],
'MongoCursor::addOption' => ['MongoCursor', 'key'=>'string', 'value'=>'mixed'],
'MongoCursor::awaitData' => ['MongoCursor', 'wait='=>'bool'],
'MongoCursor::batchSize' => ['MongoCursor', 'num'=>'int'],
'MongoCursor::count' => ['int', 'foundonly='=>'bool'],
'MongoCursor::current' => ['array'],
'MongoCursor::dead' => ['bool'],
'MongoCursor::doQuery' => ['void'],
'MongoCursor::explain' => ['array'],
'MongoCursor::fields' => ['MongoCursor', 'f'=>'array'],
'MongoCursor::getNext' => ['array'],
'MongoCursor::getReadPreference' => ['array'],
'MongoCursor::hasNext' => ['bool'],
'MongoCursor::hint' => ['MongoCursor', 'key_pattern'=>'string|array|object'],
'MongoCursor::immortal' => ['MongoCursor', 'liveforever='=>'bool'],
'MongoCursor::info' => ['array'],
'MongoCursor::key' => ['string'],
'MongoCursor::limit' => ['MongoCursor', 'num'=>'int'],
'MongoCursor::maxTimeMS' => ['MongoCursor', 'ms'=>'int'],
'MongoCursor::next' => ['array'],
'MongoCursor::partial' => ['MongoCursor', 'okay='=>'bool'],
'MongoCursor::reset' => ['void'],
'MongoCursor::rewind' => ['void'],
'MongoCursor::setFlag' => ['MongoCursor', 'flag'=>'int', 'set='=>'bool'],
'MongoCursor::setReadPreference' => ['MongoCursor', 'read_preference'=>'string', 'tags='=>'array'],
'MongoCursor::skip' => ['MongoCursor', 'num'=>'int'],
'MongoCursor::slaveOkay' => ['MongoCursor', 'okay='=>'bool'],
'MongoCursor::snapshot' => ['MongoCursor'],
'MongoCursor::sort' => ['MongoCursor', 'fields'=>'array'],
'MongoCursor::tailable' => ['MongoCursor', 'tail='=>'bool'],
'MongoCursor::timeout' => ['MongoCursor', 'ms'=>'int'],
'MongoCursor::valid' => ['bool'],
'MongoCursorException::__clone' => ['void'],
'MongoCursorException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'MongoCursorException::__toString' => ['string'],
'MongoCursorException::__wakeup' => ['void'],
'MongoCursorException::getCode' => ['int'],
'MongoCursorException::getFile' => ['string'],
'MongoCursorException::getHost' => ['string'],
'MongoCursorException::getLine' => ['int'],
'MongoCursorException::getMessage' => ['string'],
'MongoCursorException::getPrevious' => ['Exception|Throwable'],
'MongoCursorException::getTrace' => ['list<array<string,mixed>>'],
'MongoCursorException::getTraceAsString' => ['string'],
'MongoCursorInterface::__construct' => ['void'],
'MongoCursorInterface::batchSize' => ['MongoCursorInterface', 'batchSize'=>'int'],
'MongoCursorInterface::current' => ['mixed'],
'MongoCursorInterface::dead' => ['bool'],
'MongoCursorInterface::getReadPreference' => ['array'],
'MongoCursorInterface::info' => ['array'],
'MongoCursorInterface::key' => ['int|string'],
'MongoCursorInterface::next' => ['void'],
'MongoCursorInterface::rewind' => ['void'],
'MongoCursorInterface::setReadPreference' => ['MongoCursorInterface', 'read_preference'=>'string', 'tags='=>'array'],
'MongoCursorInterface::timeout' => ['MongoCursorInterface', 'ms'=>'int'],
'MongoCursorInterface::valid' => ['bool'],
'MongoDate::__construct' => ['void', 'second='=>'int', 'usecond='=>'int'],
'MongoDate::__toString' => ['string'],
'MongoDate::toDateTime' => ['DateTime'],
'MongoDB::__construct' => ['void', 'conn'=>'MongoClient', 'name'=>'string'],
'MongoDB::__get' => ['MongoCollection', 'name'=>'string'],
'MongoDB::__toString' => ['string'],
'MongoDB::authenticate' => ['array', 'username'=>'string', 'password'=>'string'],
'MongoDB::command' => ['array', 'command'=>'array'],
'MongoDB::createCollection' => ['MongoCollection', 'name'=>'string', 'capped='=>'bool', 'size='=>'int', 'max='=>'int'],
'MongoDB::createDBRef' => ['array', 'collection'=>'string', 'a'=>'mixed'],
'MongoDB::drop' => ['array'],
'MongoDB::dropCollection' => ['array', 'coll'=>'MongoCollection|string'],
'MongoDB::execute' => ['array', 'code'=>'MongoCode|string', 'args='=>'array'],
'MongoDB::forceError' => ['bool'],
'MongoDB::getCollectionInfo' => ['array', 'options='=>'array'],
'MongoDB::getCollectionNames' => ['array', 'options='=>'array'],
'MongoDB::getDBRef' => ['array', 'ref'=>'array'],
'MongoDB::getGridFS' => ['MongoGridFS', 'prefix='=>'string'],
'MongoDB::getProfilingLevel' => ['int'],
'MongoDB::getReadPreference' => ['array'],
'MongoDB::getSlaveOkay' => ['bool'],
'MongoDB::getWriteConcern' => ['array'],
'MongoDB::lastError' => ['array'],
'MongoDB::listCollections' => ['array'],
'MongoDB::prevError' => ['array'],
'MongoDB::repair' => ['array', 'preserve_cloned_files='=>'bool', 'backup_original_files='=>'bool'],
'MongoDB::resetError' => ['array'],
'MongoDB::selectCollection' => ['MongoCollection', 'name'=>'string'],
'MongoDB::setProfilingLevel' => ['int', 'level'=>'int'],
'MongoDB::setReadPreference' => ['bool', 'read_preference'=>'string', 'tags='=>'array'],
'MongoDB::setSlaveOkay' => ['bool', 'ok='=>'bool'],
'MongoDB::setWriteConcern' => ['bool', 'w'=>'mixed', 'wtimeout='=>'int'],
'MongoDB\BSON\Binary::__construct' => ['void', 'data'=>'string', 'type'=>'int'],
'MongoDB\BSON\Binary::__toString' => ['string'],
'MongoDB\BSON\Binary::getData' => ['string'],
'MongoDB\BSON\Binary::getType' => ['int'],
'MongoDB\BSON\binary::jsonSerialize' => ['mixed'],
'MongoDB\BSON\binary::serialize' => ['string'],
'MongoDB\BSON\binary::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\binaryinterface::__toString' => ['string'],
'MongoDB\BSON\binaryinterface::getData' => ['string'],
'MongoDB\BSON\binaryinterface::getType' => ['int'],
'MongoDB\BSON\dbpointer::__construct' => ['void'],
'MongoDB\BSON\dbpointer::__toString' => ['string'],
'MongoDB\BSON\dbpointer::jsonSerialize' => ['mixed'],
'MongoDB\BSON\dbpointer::serialize' => ['string'],
'MongoDB\BSON\dbpointer::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\Decimal128::__construct' => ['void', 'value='=>'string'],
'MongoDB\BSON\Decimal128::__toString' => ['string'],
'MongoDB\BSON\decimal128::jsonSerialize' => ['mixed'],
'MongoDB\BSON\decimal128::serialize' => ['string'],
'MongoDB\BSON\decimal128::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\decimal128interface::__toString' => ['string'],
'MongoDB\BSON\fromJSON' => ['string', 'json'=>'string'],
'MongoDB\BSON\fromPHP' => ['string', 'value'=>'array|object'],
'MongoDB\BSON\int64::__construct' => ['void'],
'MongoDB\BSON\int64::__toString' => ['string'],
'MongoDB\BSON\int64::jsonSerialize' => ['mixed'],
'MongoDB\BSON\int64::serialize' => ['string'],
'MongoDB\BSON\int64::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\Javascript::__construct' => ['void', 'code'=>'string', 'scope='=>'array|object'],
'MongoDB\BSON\javascript::__toString' => ['string'],
'MongoDB\BSON\javascript::getCode' => ['string'],
'MongoDB\BSON\javascript::getScope' => ['?object'],
'MongoDB\BSON\javascript::jsonSerialize' => ['mixed'],
'MongoDB\BSON\javascript::serialize' => ['string'],
'MongoDB\BSON\javascript::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\javascriptinterface::__toString' => ['string'],
'MongoDB\BSON\javascriptinterface::getCode' => ['string'],
'MongoDB\BSON\javascriptinterface::getScope' => ['?object'],
'MongoDB\BSON\maxkey::__construct' => ['void'],
'MongoDB\BSON\maxkey::jsonSerialize' => ['mixed'],
'MongoDB\BSON\maxkey::serialize' => ['string'],
'MongoDB\BSON\maxkey::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\minkey::__construct' => ['void'],
'MongoDB\BSON\minkey::jsonSerialize' => ['mixed'],
'MongoDB\BSON\minkey::serialize' => ['string'],
'MongoDB\BSON\minkey::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\ObjectId::__construct' => ['void', 'id='=>'string'],
'MongoDB\BSON\ObjectId::__toString' => ['string'],
'MongoDB\BSON\objectid::getTimestamp' => ['int'],
'MongoDB\BSON\objectid::jsonSerialize' => ['mixed'],
'MongoDB\BSON\objectid::serialize' => ['string'],
'MongoDB\BSON\objectid::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\objectidinterface::__toString' => ['string'],
'MongoDB\BSON\objectidinterface::getTimestamp' => ['int'],
'MongoDB\BSON\Regex::__construct' => ['void', 'pattern'=>'string', 'flags='=>'string'],
'MongoDB\BSON\Regex::__toString' => ['string'],
'MongoDB\BSON\Regex::getFlags' => ['string'],
'MongoDB\BSON\Regex::getPattern' => ['string'],
'MongoDB\BSON\regex::jsonSerialize' => ['mixed'],
'MongoDB\BSON\regex::serialize' => ['string'],
'MongoDB\BSON\regex::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\regexinterface::__toString' => ['string'],
'MongoDB\BSON\regexinterface::getFlags' => ['string'],
'MongoDB\BSON\regexinterface::getPattern' => ['string'],
'MongoDB\BSON\Serializable::bsonSerialize' => ['array|object'],
'MongoDB\BSON\symbol::__construct' => ['void'],
'MongoDB\BSON\symbol::__toString' => ['string'],
'MongoDB\BSON\symbol::jsonSerialize' => ['mixed'],
'MongoDB\BSON\symbol::serialize' => ['string'],
'MongoDB\BSON\symbol::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\Timestamp::__construct' => ['void', 'increment'=>'int', 'timestamp'=>'int'],
'MongoDB\BSON\Timestamp::__toString' => ['string'],
'MongoDB\BSON\timestamp::getIncrement' => ['int'],
'MongoDB\BSON\timestamp::getTimestamp' => ['int'],
'MongoDB\BSON\timestamp::jsonSerialize' => ['mixed'],
'MongoDB\BSON\timestamp::serialize' => ['string'],
'MongoDB\BSON\timestamp::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\timestampinterface::__toString' => ['string'],
'MongoDB\BSON\timestampinterface::getIncrement' => ['int'],
'MongoDB\BSON\timestampinterface::getTimestamp' => ['int'],
'MongoDB\BSON\toJSON' => ['string', 'bson'=>'string'],
'MongoDB\BSON\toPHP' => ['object', 'bson'=>'string', 'typeMap='=>'array'],
'MongoDB\BSON\undefined::__construct' => ['void'],
'MongoDB\BSON\undefined::__toString' => ['string'],
'MongoDB\BSON\undefined::jsonSerialize' => ['mixed'],
'MongoDB\BSON\undefined::serialize' => ['string'],
'MongoDB\BSON\undefined::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\Unserializable::bsonUnserialize' => ['void', 'data'=>'array'],
'MongoDB\BSON\UTCDateTime::__construct' => ['void', 'milliseconds='=>'int|DateTimeInterface'],
'MongoDB\BSON\UTCDateTime::__toString' => ['string'],
'MongoDB\BSON\utcdatetime::jsonSerialize' => ['mixed'],
'MongoDB\BSON\utcdatetime::serialize' => ['string'],
'MongoDB\BSON\UTCDateTime::toDateTime' => ['DateTime'],
'MongoDB\BSON\utcdatetime::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\utcdatetimeinterface::__toString' => ['string'],
'MongoDB\BSON\utcdatetimeinterface::toDateTime' => ['DateTime'],
'MongoDB\Driver\BulkWrite::__construct' => ['void', 'ordered='=>'bool'],
'MongoDB\Driver\BulkWrite::count' => ['int'],
'MongoDB\Driver\BulkWrite::delete' => ['void', 'filter'=>'array|object', 'deleteOptions='=>'array'],
'MongoDB\Driver\BulkWrite::insert' => ['void|MongoDB\BSON\ObjectId', 'document'=>'array|object'],
'MongoDB\Driver\BulkWrite::update' => ['void', 'filter'=>'array|object', 'newObj'=>'array|object', 'updateOptions='=>'array'],
'MongoDB\Driver\Command::__construct' => ['void', 'document'=>'array|object'],
'MongoDB\Driver\Cursor::__construct' => ['void', 'server'=>'Server', 'responseDocument'=>'string'],
'MongoDB\Driver\Cursor::getId' => ['MongoDB\Driver\CursorId'],
'MongoDB\Driver\Cursor::getServer' => ['MongoDB\Driver\Server'],
'MongoDB\Driver\Cursor::isDead' => ['bool'],
'MongoDB\Driver\Cursor::setTypeMap' => ['void', 'typemap'=>'array'],
'MongoDB\Driver\Cursor::toArray' => ['array'],
'MongoDB\Driver\CursorId::__construct' => ['void', 'id'=>'string'],
'MongoDB\Driver\CursorId::__toString' => ['string'],
'MongoDB\Driver\CursorId::serialize' => ['string'],
'MongoDB\Driver\CursorId::unserialize' => ['void', 'serialized'=>'string'],
'mongodb\driver\exception\commandexception::getResultDocument' => ['object'],
'MongoDB\Driver\Exception\RuntimeException::__clone' => ['void'],
'MongoDB\Driver\Exception\RuntimeException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?RuntimeException|?Throwable'],
'MongoDB\Driver\Exception\RuntimeException::__toString' => ['string'],
'MongoDB\Driver\Exception\RuntimeException::__wakeup' => ['void'],
'MongoDB\Driver\Exception\RuntimeException::getCode' => ['int'],
'MongoDB\Driver\Exception\RuntimeException::getFile' => ['string'],
'MongoDB\Driver\Exception\RuntimeException::getLine' => ['int'],
'MongoDB\Driver\Exception\RuntimeException::getMessage' => ['string'],
'MongoDB\Driver\Exception\RuntimeException::getPrevious' => ['RuntimeException|Throwable'],
'MongoDB\Driver\Exception\RuntimeException::getTrace' => ['list<array<string,mixed>>'],
'MongoDB\Driver\Exception\RuntimeException::getTraceAsString' => ['string'],
'mongodb\driver\exception\runtimeexception::hasErrorLabel' => ['bool', 'errorLabel'=>'string'],
'MongoDB\Driver\Exception\WriteException::__clone' => ['void'],
'MongoDB\Driver\Exception\WriteException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?RuntimeException|?Throwable'],
'MongoDB\Driver\Exception\WriteException::__toString' => ['string'],
'MongoDB\Driver\Exception\WriteException::__wakeup' => ['void'],
'MongoDB\Driver\Exception\WriteException::getCode' => ['int'],
'MongoDB\Driver\Exception\WriteException::getFile' => ['string'],
'MongoDB\Driver\Exception\WriteException::getLine' => ['int'],
'MongoDB\Driver\Exception\WriteException::getMessage' => ['string'],
'MongoDB\Driver\Exception\WriteException::getPrevious' => ['RuntimeException|Throwable'],
'MongoDB\Driver\Exception\WriteException::getTrace' => ['list<array<string,mixed>>'],
'MongoDB\Driver\Exception\WriteException::getTraceAsString' => ['string'],
'MongoDB\Driver\Exception\WriteException::getWriteResult' => ['MongoDB\Driver\WriteResult'],
'MongoDB\Driver\Manager::__construct' => ['void', 'uri'=>'string', 'options='=>'array', 'driverOptions='=>'array'],
'MongoDB\Driver\Manager::executeBulkWrite' => ['MongoDB\Driver\WriteResult', 'namespace'=>'string', 'bulk'=>'MongoDB\Driver\BulkWrite', 'writeConcern='=>'MongoDB\Driver\WriteConcern'],
'MongoDB\Driver\Manager::executeCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'readPreference='=>'MongoDB\Driver\ReadPreference'],
'MongoDB\Driver\Manager::executeDelete' => ['MongoDB\Driver\WriteResult', 'namespace'=>'string', 'filter'=>'array|object', 'deleteOptions='=>'array', 'writeConcern='=>'MongoDB\Driver\WriteConcern'],
'MongoDB\Driver\Manager::executeInsert' => ['MongoDB\Driver\WriteResult', 'namespace'=>'string', 'document'=>'array|object', 'writeConcern='=>'MongoDB\Driver\WriteConcern'],
'MongoDB\Driver\Manager::executeQuery' => ['MongoDB\Driver\Cursor', 'namespace'=>'string', 'query'=>'MongoDB\Driver\Query', 'readPreference='=>'MongoDB\Driver\ReadPreference'],
'mongodb\driver\manager::executeReadCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'mongodb\driver\manager::executeReadWriteCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'MongoDB\Driver\Manager::executeUpdate' => ['MongoDB\Driver\WriteResult', 'namespace'=>'string', 'filter'=>'array|object', 'newObj'=>'array|object', 'updateOptions='=>'array', 'writeConcern='=>'MongoDB\Driver\WriteConcern'],
'mongodb\driver\manager::executeWriteCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'MongoDB\Driver\Manager::getReadConcern' => ['MongoDB\Driver\ReadConcern'],
'MongoDB\Driver\Manager::getReadPreference' => ['MongoDB\Driver\ReadPreference'],
'MongoDB\Driver\Manager::getServers' => ['MongoDB\Driver\Server[]'],
'MongoDB\Driver\Manager::getWriteConcern' => ['MongoDB\Driver\WriteConcern'],
'MongoDB\Driver\Manager::selectServer' => ['MongoDB\Driver\Server', 'readPreference'=>'MongoDB\Driver\ReadPreference'],
'mongodb\driver\manager::startSession' => ['MongoDB\Driver\Session', 'options='=>'array'],
'mongodb\driver\monitoring\commandfailedevent::getCommandName' => ['string'],
'mongodb\driver\monitoring\commandfailedevent::getDurationMicros' => ['int'],
'mongodb\driver\monitoring\commandfailedevent::getError' => ['Exception'],
'mongodb\driver\monitoring\commandfailedevent::getOperationId' => ['string'],
'mongodb\driver\monitoring\commandfailedevent::getReply' => ['object'],
'mongodb\driver\monitoring\commandfailedevent::getRequestId' => ['string'],
'mongodb\driver\monitoring\commandfailedevent::getServer' => ['MongoDB\Driver\Server'],
'mongodb\driver\monitoring\commandstartedevent::getCommand' => ['object'],
'mongodb\driver\monitoring\commandstartedevent::getCommandName' => ['string'],
'mongodb\driver\monitoring\commandstartedevent::getDatabaseName' => ['string'],
'mongodb\driver\monitoring\commandstartedevent::getOperationId' => ['string'],
'mongodb\driver\monitoring\commandstartedevent::getRequestId' => ['string'],
'mongodb\driver\monitoring\commandstartedevent::getServer' => ['MongoDB\Driver\Server'],
'mongodb\driver\monitoring\commandsubscriber::commandFailed' => ['void', 'event'=>'MongoDB\Driver\Monitoring\CommandFailedEvent'],
'mongodb\driver\monitoring\commandsubscriber::commandStarted' => ['void', 'event'=>'MongoDB\Driver\Monitoring\CommandStartedEvent'],
'mongodb\driver\monitoring\commandsubscriber::commandSucceeded' => ['void', 'event'=>'MongoDB\Driver\Monitoring\CommandSucceededEvent'],
'mongodb\driver\monitoring\commandsucceededevent::getCommandName' => ['string'],
'mongodb\driver\monitoring\commandsucceededevent::getDurationMicros' => ['int'],
'mongodb\driver\monitoring\commandsucceededevent::getOperationId' => ['string'],
'mongodb\driver\monitoring\commandsucceededevent::getReply' => ['object'],
'mongodb\driver\monitoring\commandsucceededevent::getRequestId' => ['string'],
'mongodb\driver\monitoring\commandsucceededevent::getServer' => ['MongoDB\Driver\Server'],
'MongoDB\Driver\Query::__construct' => ['void', 'filter'=>'array|object', 'queryOptions='=>'array'],
'MongoDB\Driver\ReadConcern::__construct' => ['void', 'level='=>'string'],
'MongoDB\Driver\ReadConcern::bsonSerialize' => ['object'],
'MongoDB\Driver\ReadConcern::getLevel' => ['?string'],
'MongoDB\Driver\ReadConcern::isDefault' => ['bool'],
'MongoDB\Driver\ReadConcern::serialize' => ['string'],
'MongoDB\Driver\ReadConcern::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\Driver\ReadPreference::__construct' => ['void', 'mode'=>'string|int', 'tagSets='=>'array', 'options='=>'array'],
'MongoDB\Driver\ReadPreference::bsonSerialize' => ['object'],
'MongoDB\Driver\ReadPreference::getHedge' => ['object|null'],
'MongoDB\Driver\ReadPreference::getMaxStalenessSeconds' => ['int'],
'MongoDB\Driver\ReadPreference::getMode' => ['int'],
'MongoDB\Driver\ReadPreference::getModeString' => ['string'],
'MongoDB\Driver\ReadPreference::getTagSets' => ['array'],
'MongoDB\Driver\ReadPreference::serialize' => ['string'],
'MongoDB\Driver\ReadPreference::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\Driver\Server::__construct' => ['void', 'host'=>'string', 'port'=>'string', 'options='=>'array', 'driverOptions='=>'array'],
'MongoDB\Driver\Server::executeBulkWrite' => ['MongoDB\Driver\WriteResult', 'namespace'=>'string', 'zwrite'=>'BulkWrite'],
'MongoDB\Driver\Server::executeCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command'],
'MongoDB\Driver\Server::executeQuery' => ['MongoDB\Driver\Cursor', 'namespace'=>'string', 'zquery'=>'Query'],
'mongodb\driver\server::executeReadCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'mongodb\driver\server::executeReadWriteCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'mongodb\driver\server::executeWriteCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'MongoDB\Driver\Server::getHost' => ['string'],
'MongoDB\Driver\Server::getInfo' => ['array'],
'MongoDB\Driver\Server::getLatency' => ['int'],
'MongoDB\Driver\Server::getPort' => ['int'],
'MongoDB\Driver\Server::getState' => [''],
'MongoDB\Driver\Server::getTags' => ['array'],
'MongoDB\Driver\Server::getType' => ['int'],
'MongoDB\Driver\Server::isArbiter' => ['bool'],
'MongoDB\Driver\Server::isDelayed' => [''],
'MongoDB\Driver\Server::isHidden' => ['bool'],
'MongoDB\Driver\Server::isPassive' => ['bool'],
'MongoDB\Driver\Server::isPrimary' => ['bool'],
'MongoDB\Driver\Server::isSecondary' => ['bool'],
'mongodb\driver\session::__construct' => ['void'],
'mongodb\driver\session::abortTransaction' => ['void'],
'mongodb\driver\session::advanceClusterTime' => ['void', 'clusterTime'=>'array|object'],
'mongodb\driver\session::advanceOperationTime' => ['void', 'operationTime'=>'MongoDB\BSON\TimestampInterface'],
'mongodb\driver\session::commitTransaction' => ['void'],
'mongodb\driver\session::endSession' => ['void'],
'mongodb\driver\session::getClusterTime' => ['?object'],
'mongodb\driver\session::getLogicalSessionId' => ['object'],
'mongodb\driver\session::getOperationTime' => ['MongoDB\BSON\Timestamp|null'],
'mongodb\driver\session::getTransactionOptions' => ['array|null'],
'mongodb\driver\session::getTransactionState' => ['string'],
'mongodb\driver\session::startTransaction' => ['void', 'options'=>'array|object'],
'MongoDB\Driver\WriteConcern::__construct' => ['void', 'wstring'=>'string|int', 'wtimeout='=>'int', 'journal='=>'bool'],
'MongoDB\Driver\WriteConcern::bsonSerialize' => ['object'],
'MongoDB\Driver\WriteConcern::getJournal' => ['?bool'],
'MongoDB\Driver\WriteConcern::getJurnal' => ['?bool'],
'MongoDB\Driver\WriteConcern::getW' => ['int|null|string'],
'MongoDB\Driver\WriteConcern::getWtimeout' => ['int'],
'MongoDB\Driver\WriteConcern::isDefault' => ['bool'],
'MongoDB\Driver\WriteConcern::serialize' => ['string'],
'MongoDB\Driver\WriteConcern::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\Driver\WriteConcernError::getCode' => ['int'],
'MongoDB\Driver\WriteConcernError::getInfo' => ['mixed'],
'MongoDB\Driver\WriteConcernError::getMessage' => ['string'],
'MongoDB\Driver\WriteError::getCode' => ['int'],
'MongoDB\Driver\WriteError::getIndex' => ['int'],
'MongoDB\Driver\WriteError::getInfo' => ['mixed'],
'MongoDB\Driver\WriteError::getMessage' => ['string'],
'MongoDB\Driver\WriteException::getWriteResult' => [''],
'MongoDB\Driver\WriteResult::getDeletedCount' => ['?int'],
'MongoDB\Driver\WriteResult::getInfo' => [''],
'MongoDB\Driver\WriteResult::getInsertedCount' => ['?int'],
'MongoDB\Driver\WriteResult::getMatchedCount' => ['?int'],
'MongoDB\Driver\WriteResult::getModifiedCount' => ['?int'],
'MongoDB\Driver\WriteResult::getServer' => ['MongoDB\Driver\Server'],
'MongoDB\Driver\WriteResult::getUpsertedCount' => ['?int'],
'MongoDB\Driver\WriteResult::getUpsertedIds' => ['array'],
'MongoDB\Driver\WriteResult::getWriteConcernError' => ['MongoDB\Driver\WriteConcernError|null'],
'MongoDB\Driver\WriteResult::getWriteErrors' => ['MongoDB\Driver\WriteError[]'],
'MongoDB\Driver\WriteResult::isAcknowledged' => ['bool'],
'MongoDBRef::create' => ['array', 'collection'=>'string', 'id'=>'mixed', 'database='=>'string'],
'MongoDBRef::get' => ['?array', 'db'=>'MongoDB', 'ref'=>'array'],
'MongoDBRef::isRef' => ['bool', 'ref'=>'mixed'],
'MongoDeleteBatch::__construct' => ['void', 'collection'=>'MongoCollection', 'write_options='=>'array'],
'MongoException::__clone' => ['void'],
'MongoException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'MongoException::__toString' => ['string'],
'MongoException::__wakeup' => ['void'],
'MongoException::getCode' => ['int'],
'MongoException::getFile' => ['string'],
'MongoException::getLine' => ['int'],
'MongoException::getMessage' => ['string'],
'MongoException::getPrevious' => ['Exception|Throwable'],
'MongoException::getTrace' => ['list<array<string,mixed>>'],
'MongoException::getTraceAsString' => ['string'],
'MongoGridFS::__construct' => ['void', 'db'=>'MongoDB', 'prefix='=>'string', 'chunks='=>'mixed'],
'MongoGridFS::__get' => ['MongoCollection', 'name'=>'string'],
'MongoGridFS::__toString' => ['string'],
'MongoGridFS::aggregate' => ['array', 'pipeline'=>'array', 'op'=>'array', 'pipelineOperators'=>'array'],
'MongoGridFS::aggregateCursor' => ['MongoCommandCursor', 'pipeline'=>'array', 'options'=>'array'],
'MongoGridFS::batchInsert' => ['mixed', 'a'=>'array', 'options='=>'array'],
'MongoGridFS::count' => ['int', 'query='=>'stdClass|array'],
'MongoGridFS::createDBRef' => ['array', 'a'=>'array'],
'MongoGridFS::createIndex' => ['array', 'keys'=>'array', 'options='=>'array'],
'MongoGridFS::delete' => ['bool', 'id'=>'mixed'],
'MongoGridFS::deleteIndex' => ['array', 'keys'=>'array|string'],
'MongoGridFS::deleteIndexes' => ['array'],
'MongoGridFS::distinct' => ['array|bool', 'key'=>'string', 'query='=>'?array'],
'MongoGridFS::drop' => ['array'],
'MongoGridFS::ensureIndex' => ['bool', 'keys'=>'array', 'options='=>'array'],
'MongoGridFS::find' => ['MongoGridFSCursor', 'query='=>'array', 'fields='=>'array'],
'MongoGridFS::findAndModify' => ['array', 'query'=>'array', 'update='=>'?array', 'fields='=>'?array', 'options='=>'?array'],
'MongoGridFS::findOne' => ['?MongoGridFSFile', 'query='=>'mixed', 'fields='=>'mixed'],
'MongoGridFS::get' => ['?MongoGridFSFile', 'id'=>'mixed'],
'MongoGridFS::getDBRef' => ['array', 'ref'=>'array'],
'MongoGridFS::getIndexInfo' => ['array'],
'MongoGridFS::getName' => ['string'],
'MongoGridFS::getReadPreference' => ['array'],
'MongoGridFS::getSlaveOkay' => ['bool'],
'MongoGridFS::group' => ['array', 'keys'=>'mixed', 'initial'=>'array', 'reduce'=>'MongoCode', 'condition='=>'array'],
'MongoGridFS::insert' => ['array|bool', 'a'=>'array|object', 'options='=>'array'],
'MongoGridFS::put' => ['mixed', 'filename'=>'string', 'extra='=>'array'],
'MongoGridFS::remove' => ['bool', 'criteria='=>'array', 'options='=>'array'],
'MongoGridFS::save' => ['array|bool', 'a'=>'array|object', 'options='=>'array'],
'MongoGridFS::setReadPreference' => ['bool', 'read_preference'=>'string', 'tags'=>'array'],
'MongoGridFS::setSlaveOkay' => ['bool', 'ok='=>'bool'],
'MongoGridFS::storeBytes' => ['mixed', 'bytes'=>'string', 'extra='=>'array', 'options='=>'array'],
'MongoGridFS::storeFile' => ['mixed', 'filename'=>'string', 'extra='=>'array', 'options='=>'array'],
'MongoGridFS::storeUpload' => ['mixed', 'name'=>'string', 'filename='=>'string'],
'MongoGridFS::toIndexString' => ['string', 'keys'=>'mixed'],
'MongoGridFS::update' => ['bool', 'criteria'=>'array', 'newobj'=>'array', 'options='=>'array'],
'MongoGridFS::validate' => ['array', 'scan_data='=>'bool'],
'MongoGridFSCursor::__construct' => ['void', 'gridfs'=>'MongoGridFS', 'connection'=>'resource', 'ns'=>'string', 'query'=>'array', 'fields'=>'array'],
'MongoGridFSCursor::addOption' => ['MongoCursor', 'key'=>'string', 'value'=>'mixed'],
'MongoGridFSCursor::awaitData' => ['MongoCursor', 'wait='=>'bool'],
'MongoGridFSCursor::batchSize' => ['MongoCursor', 'batchSize'=>'int'],
'MongoGridFSCursor::count' => ['int', 'all='=>'bool'],
'MongoGridFSCursor::current' => ['MongoGridFSFile'],
'MongoGridFSCursor::dead' => ['bool'],
'MongoGridFSCursor::doQuery' => ['void'],
'MongoGridFSCursor::explain' => ['array'],
'MongoGridFSCursor::fields' => ['MongoCursor', 'f'=>'array'],
'MongoGridFSCursor::getNext' => ['MongoGridFSFile'],
'MongoGridFSCursor::getReadPreference' => ['array'],
'MongoGridFSCursor::hasNext' => ['bool'],
'MongoGridFSCursor::hint' => ['MongoCursor', 'key_pattern'=>'mixed'],
'MongoGridFSCursor::immortal' => ['MongoCursor', 'liveForever='=>'bool'],
'MongoGridFSCursor::info' => ['array'],
'MongoGridFSCursor::key' => ['string'],
'MongoGridFSCursor::limit' => ['MongoCursor', 'num'=>'int'],
'MongoGridFSCursor::maxTimeMS' => ['MongoCursor', 'ms'=>'int'],
'MongoGridFSCursor::next' => ['void'],
'MongoGridFSCursor::partial' => ['MongoCursor', 'okay='=>'bool'],
'MongoGridFSCursor::reset' => ['void'],
'MongoGridFSCursor::rewind' => ['void'],
'MongoGridFSCursor::setFlag' => ['MongoCursor', 'flag'=>'int', 'set='=>'bool'],
'MongoGridFSCursor::setReadPreference' => ['MongoCursor', 'read_preference'=>'string', 'tags'=>'array'],
'MongoGridFSCursor::skip' => ['MongoCursor', 'num'=>'int'],
'MongoGridFSCursor::slaveOkay' => ['MongoCursor', 'okay='=>'bool'],
'MongoGridFSCursor::snapshot' => ['MongoCursor'],
'MongoGridFSCursor::sort' => ['MongoCursor', 'fields'=>'array'],
'MongoGridFSCursor::tailable' => ['MongoCursor', 'tail='=>'bool'],
'MongoGridFSCursor::timeout' => ['MongoCursor', 'ms'=>'int'],
'MongoGridFSCursor::valid' => ['bool'],
'MongoGridfsFile::__construct' => ['void', 'gridfs'=>'MongoGridFS', 'file'=>'array'],
'MongoGridFSFile::getBytes' => ['string'],
'MongoGridFSFile::getFilename' => ['string'],
'MongoGridFSFile::getResource' => ['resource'],
'MongoGridFSFile::getSize' => ['int'],
'MongoGridFSFile::write' => ['int', 'filename='=>'string'],
'MongoId::__construct' => ['void', 'id='=>'string|MongoId'],
'MongoId::__set_state' => ['MongoId', 'props'=>'array'],
'MongoId::__toString' => ['string'],
'MongoId::getHostname' => ['string'],
'MongoId::getInc' => ['int'],
'MongoId::getPID' => ['int'],
'MongoId::getTimestamp' => ['int'],
'MongoId::isValid' => ['bool', 'value'=>'mixed'],
'MongoInsertBatch::__construct' => ['void', 'collection'=>'MongoCollection', 'write_options='=>'array'],
'MongoInt32::__construct' => ['void', 'value'=>'string'],
'MongoInt32::__toString' => ['string'],
'MongoInt64::__construct' => ['void', 'value'=>'string'],
'MongoInt64::__toString' => ['string'],
'MongoLog::getCallback' => ['callable'],
'MongoLog::getLevel' => ['int'],
'MongoLog::getModule' => ['int'],
'MongoLog::setCallback' => ['void', 'log_function'=>'callable'],
'MongoLog::setLevel' => ['void', 'level'=>'int'],
'MongoLog::setModule' => ['void', 'module'=>'int'],
'MongoPool::getSize' => ['int'],
'MongoPool::info' => ['array'],
'MongoPool::setSize' => ['bool', 'size'=>'int'],
'MongoRegex::__construct' => ['void', 'regex'=>'string'],
'MongoRegex::__toString' => ['string'],
'MongoResultException::__clone' => ['void'],
'MongoResultException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'MongoResultException::__toString' => ['string'],
'MongoResultException::__wakeup' => ['void'],
'MongoResultException::getCode' => ['int'],
'MongoResultException::getDocument' => ['array'],
'MongoResultException::getFile' => ['string'],
'MongoResultException::getLine' => ['int'],
'MongoResultException::getMessage' => ['string'],
'MongoResultException::getPrevious' => ['Exception|Throwable'],
'MongoResultException::getTrace' => ['list<array<string,mixed>>'],
'MongoResultException::getTraceAsString' => ['string'],
'MongoTimestamp::__construct' => ['void', 'second='=>'int', 'inc='=>'int'],
'MongoTimestamp::__toString' => ['string'],
'MongoUpdateBatch::__construct' => ['void', 'collection'=>'MongoCollection', 'write_options='=>'array'],
'MongoUpdateBatch::add' => ['bool', 'item'=>'array'],
'MongoUpdateBatch::execute' => ['array', 'write_options'=>'array'],
'MongoWriteBatch::__construct' => ['void', 'collection'=>'MongoCollection', 'batch_type'=>'string', 'write_options'=>'array'],
'MongoWriteBatch::add' => ['bool', 'item'=>'array'],
'MongoWriteBatch::execute' => ['array', 'write_options'=>'array'],
'MongoWriteConcernException::__clone' => ['void'],
'MongoWriteConcernException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'MongoWriteConcernException::__toString' => ['string'],
'MongoWriteConcernException::__wakeup' => ['void'],
'MongoWriteConcernException::getCode' => ['int'],
'MongoWriteConcernException::getDocument' => ['array'],
'MongoWriteConcernException::getFile' => ['string'],
'MongoWriteConcernException::getLine' => ['int'],
'MongoWriteConcernException::getMessage' => ['string'],
'MongoWriteConcernException::getPrevious' => ['Exception|Throwable'],
'MongoWriteConcernException::getTrace' => ['list<array<string,mixed>>'],
'MongoWriteConcernException::getTraceAsString' => ['string'],
'monitor_custom_event' => ['void', 'class'=>'string', 'text'=>'string', 'severe='=>'int', 'user_data='=>'mixed'],
'monitor_httperror_event' => ['void', 'error_code'=>'int', 'url'=>'string', 'severe='=>'int'],
'monitor_license_info' => ['array'],
'monitor_pass_error' => ['void', 'errno'=>'int', 'errstr'=>'string', 'errfile'=>'string', 'errline'=>'int'],
'monitor_set_aggregation_hint' => ['void', 'hint'=>'string'],
'move_uploaded_file' => ['bool', 'from'=>'string', 'to'=>'string'],
'mqseries_back' => ['void', 'hconn'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_begin' => ['void', 'hconn'=>'resource', 'beginoptions'=>'array', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_close' => ['void', 'hconn'=>'resource', 'hobj'=>'resource', 'options'=>'int', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_cmit' => ['void', 'hconn'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_conn' => ['void', 'qmanagername'=>'string', 'hconn'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_connx' => ['void', 'qmanagername'=>'string', 'connoptions'=>'array', 'hconn'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_disc' => ['void', 'hconn'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_get' => ['void', 'hconn'=>'resource', 'hobj'=>'resource', 'md'=>'array', 'gmo'=>'array', 'bufferlength'=>'int', 'msg'=>'string', 'data_length'=>'int', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_inq' => ['void', 'hconn'=>'resource', 'hobj'=>'resource', 'selectorcount'=>'int', 'selectors'=>'array', 'intattrcount'=>'int', 'intattr'=>'resource', 'charattrlength'=>'int', 'charattr'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_open' => ['void', 'hconn'=>'resource', 'objdesc'=>'array', 'option'=>'int', 'hobj'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_put' => ['void', 'hconn'=>'resource', 'hobj'=>'resource', 'md'=>'array', 'pmo'=>'array', 'message'=>'string', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_put1' => ['void', 'hconn'=>'resource', 'objdesc'=>'resource', 'msgdesc'=>'resource', 'pmo'=>'resource', 'buffer'=>'string', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_set' => ['void', 'hconn'=>'resource', 'hobj'=>'resource', 'selectorcount'=>'int', 'selectors'=>'array', 'intattrcount'=>'int', 'intattrs'=>'array', 'charattrlength'=>'int', 'charattrs'=>'array', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_strerror' => ['string', 'reason'=>'int'],
'ms_GetErrorObj' => ['errorObj'],
'ms_GetVersion' => ['string'],
'ms_GetVersionInt' => ['int'],
'ms_iogetStdoutBufferBytes' => ['int'],
'ms_iogetstdoutbufferstring' => ['void'],
'ms_ioinstallstdinfrombuffer' => ['void'],
'ms_ioinstallstdouttobuffer' => ['void'],
'ms_ioresethandlers' => ['void'],
'ms_iostripstdoutbuffercontentheaders' => ['void'],
'ms_iostripstdoutbuffercontenttype' => ['string'],
'ms_ResetErrorList' => ['void'],
'ms_TokenizeMap' => ['array', 'map_file_name'=>'string'],
'msession_connect' => ['bool', 'host'=>'string', 'port'=>'string'],
'msession_count' => ['int'],
'msession_create' => ['bool', 'session'=>'string', 'classname='=>'string', 'data='=>'string'],
'msession_destroy' => ['bool', 'name'=>'string'],
'msession_disconnect' => ['void'],
'msession_find' => ['array', 'name'=>'string', 'value'=>'string'],
'msession_get' => ['string', 'session'=>'string', 'name'=>'string', 'value'=>'string'],
'msession_get_array' => ['array', 'session'=>'string'],
'msession_get_data' => ['string', 'session'=>'string'],
'msession_inc' => ['string', 'session'=>'string', 'name'=>'string'],
'msession_list' => ['array'],
'msession_listvar' => ['array', 'name'=>'string'],
'msession_lock' => ['int', 'name'=>'string'],
'msession_plugin' => ['string', 'session'=>'string', 'value'=>'string', 'param='=>'string'],
'msession_randstr' => ['string', 'param'=>'int'],
'msession_set' => ['bool', 'session'=>'string', 'name'=>'string', 'value'=>'string'],
'msession_set_array' => ['void', 'session'=>'string', 'tuples'=>'array'],
'msession_set_data' => ['bool', 'session'=>'string', 'value'=>'string'],
'msession_timeout' => ['int', 'session'=>'string', 'param='=>'int'],
'msession_uniq' => ['string', 'param'=>'int', 'classname='=>'string', 'data='=>'string'],
'msession_unlock' => ['int', 'session'=>'string', 'key'=>'int'],
'msg_get_queue' => ['resource', 'key'=>'int', 'permissions='=>'int'],
'msg_queue_exists' => ['bool', 'key'=>'int'],
'msg_receive' => ['bool', 'queue'=>'resource', 'desired_message_type'=>'int', '&w_received_message_type'=>'int', 'max_message_size'=>'int', '&w_message'=>'mixed', 'unserialize='=>'bool', 'flags='=>'int', '&w_error_code='=>'int'],
'msg_remove_queue' => ['bool', 'queue'=>'resource'],
'msg_send' => ['bool', 'queue'=>'resource', 'message_type'=>'int', 'message'=>'mixed', 'serialize='=>'bool', 'blocking='=>'bool', '&w_error_code='=>'int'],
'msg_set_queue' => ['bool', 'queue'=>'resource', 'data'=>'array'],
'msg_stat_queue' => ['array', 'queue'=>'resource'],
'msgfmt_create' => ['MessageFormatter', 'locale'=>'string', 'pattern'=>'string'],
'msgfmt_format' => ['string|false', 'formatter'=>'MessageFormatter', 'values'=>'array'],
'msgfmt_format_message' => ['string|false', 'locale'=>'string', 'pattern'=>'string', 'values'=>'array'],
'msgfmt_get_error_code' => ['int', 'formatter'=>'MessageFormatter'],
'msgfmt_get_error_message' => ['string', 'formatter'=>'MessageFormatter'],
'msgfmt_get_locale' => ['string', 'formatter'=>'MessageFormatter'],
'msgfmt_get_pattern' => ['string', 'formatter'=>'MessageFormatter'],
'msgfmt_parse' => ['array|false', 'formatter'=>'MessageFormatter', 'string'=>'string'],
'msgfmt_parse_message' => ['array|false', 'locale'=>'string', 'pattern'=>'string', 'message'=>'string'],
'msgfmt_set_pattern' => ['bool', 'formatter'=>'MessageFormatter', 'pattern'=>'string'],
'msql_affected_rows' => ['int', 'result'=>'resource'],
'msql_close' => ['bool', 'link_identifier='=>'?resource'],
'msql_connect' => ['resource', 'hostname='=>'string'],
'msql_create_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'msql_data_seek' => ['bool', 'result'=>'resource', 'row_number'=>'int'],
'msql_db_query' => ['resource', 'database'=>'string', 'query'=>'string', 'link_identifier='=>'?resource'],
'msql_drop_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'msql_error' => ['string'],
'msql_fetch_array' => ['array', 'result'=>'resource', 'result_type='=>'int'],
'msql_fetch_field' => ['object', 'result'=>'resource', 'field_offset='=>'int'],
'msql_fetch_object' => ['object', 'result'=>'resource'],
'msql_fetch_row' => ['array', 'result'=>'resource'],
'msql_field_flags' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'msql_field_len' => ['int', 'result'=>'resource', 'field_offset'=>'int'],
'msql_field_name' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'msql_field_seek' => ['bool', 'result'=>'resource', 'field_offset'=>'int'],
'msql_field_table' => ['int', 'result'=>'resource', 'field_offset'=>'int'],
'msql_field_type' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'msql_free_result' => ['bool', 'result'=>'resource'],
'msql_list_dbs' => ['resource', 'link_identifier='=>'?resource'],
'msql_list_fields' => ['resource', 'database'=>'string', 'tablename'=>'string', 'link_identifier='=>'?resource'],
'msql_list_tables' => ['resource', 'database'=>'string', 'link_identifier='=>'?resource'],
'msql_num_fields' => ['int', 'result'=>'resource'],
'msql_num_rows' => ['int', 'query_identifier'=>'resource'],
'msql_pconnect' => ['resource', 'hostname='=>'string'],
'msql_query' => ['resource', 'query'=>'string', 'link_identifier='=>'?resource'],
'msql_result' => ['string', 'result'=>'resource', 'row'=>'int', 'field='=>'mixed'],
'msql_select_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'mt_getrandmax' => ['int'],
'mt_rand' => ['int', 'min'=>'int', 'max'=>'int'],
'mt_rand\'1' => ['int'],
'mt_srand' => ['void', 'seed='=>'int', 'mode='=>'int'],
'MultipleIterator::__construct' => ['void', 'flags='=>'int'],
'MultipleIterator::attachIterator' => ['void', 'iterator'=>'Iterator', 'infos='=>'string'],
'MultipleIterator::containsIterator' => ['bool', 'iterator'=>'Iterator'],
'MultipleIterator::countIterators' => ['int'],
'MultipleIterator::current' => ['array|false'],
'MultipleIterator::detachIterator' => ['void', 'iterator'=>'Iterator'],
'MultipleIterator::getFlags' => ['int'],
'MultipleIterator::key' => ['array'],
'MultipleIterator::next' => ['void'],
'MultipleIterator::rewind' => ['void'],
'MultipleIterator::setFlags' => ['int', 'flags'=>'int'],
'MultipleIterator::valid' => ['bool'],
'Mutex::create' => ['long', 'lock='=>'bool'],
'Mutex::destroy' => ['bool', 'mutex'=>'long'],
'Mutex::lock' => ['bool', 'mutex'=>'long'],
'Mutex::trylock' => ['bool', 'mutex'=>'long'],
'Mutex::unlock' => ['bool', 'mutex'=>'long', 'destroy='=>'bool'],
'mysql_xdevapi\baseresult::getWarnings' => ['array'],
'mysql_xdevapi\baseresult::getWarningsCount' => ['integer'],
'mysql_xdevapi\collection::add' => ['mysql_xdevapi\CollectionAdd', 'document'=>'mixed'],
'mysql_xdevapi\collection::addOrReplaceOne' => ['mysql_xdevapi\Result', 'id'=>'string', 'doc'=>'string'],
'mysql_xdevapi\collection::count' => ['integer'],
'mysql_xdevapi\collection::createIndex' => ['void', 'index_name'=>'string', 'index_desc_json'=>'string'],
'mysql_xdevapi\collection::dropIndex' => ['bool', 'index_name'=>'string'],
'mysql_xdevapi\collection::existsInDatabase' => ['bool'],
'mysql_xdevapi\collection::find' => ['mysql_xdevapi\CollectionFind', 'search_condition='=>'string'],
'mysql_xdevapi\collection::getName' => ['string'],
'mysql_xdevapi\collection::getOne' => ['Document', 'id'=>'string'],
'mysql_xdevapi\collection::getSchema' => ['mysql_xdevapi\schema'],
'mysql_xdevapi\collection::getSession' => ['Session'],
'mysql_xdevapi\collection::modify' => ['mysql_xdevapi\CollectionModify', 'search_condition'=>'string'],
'mysql_xdevapi\collection::remove' => ['mysql_xdevapi\CollectionRemove', 'search_condition'=>'string'],
'mysql_xdevapi\collection::removeOne' => ['mysql_xdevapi\Result', 'id'=>'string'],
'mysql_xdevapi\collection::replaceOne' => ['mysql_xdevapi\Result', 'id'=>'string', 'doc'=>'string'],
'mysql_xdevapi\collectionadd::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\collectionfind::bind' => ['mysql_xdevapi\CollectionFind', 'placeholder_values'=>'array'],
'mysql_xdevapi\collectionfind::execute' => ['mysql_xdevapi\DocResult'],
'mysql_xdevapi\collectionfind::fields' => ['mysql_xdevapi\CollectionFind', 'projection'=>'string'],
'mysql_xdevapi\collectionfind::groupBy' => ['mysql_xdevapi\CollectionFind', 'sort_expr'=>'string'],
'mysql_xdevapi\collectionfind::having' => ['mysql_xdevapi\CollectionFind', 'sort_expr'=>'string'],
'mysql_xdevapi\collectionfind::limit' => ['mysql_xdevapi\CollectionFind', 'rows'=>'integer'],
'mysql_xdevapi\collectionfind::lockExclusive' => ['mysql_xdevapi\CollectionFind', 'lock_waiting_option='=>'integer'],
'mysql_xdevapi\collectionfind::lockShared' => ['mysql_xdevapi\CollectionFind', 'lock_waiting_option='=>'integer'],
'mysql_xdevapi\collectionfind::offset' => ['mysql_xdevapi\CollectionFind', 'position'=>'integer'],
'mysql_xdevapi\collectionfind::sort' => ['mysql_xdevapi\CollectionFind', 'sort_expr'=>'string'],
'mysql_xdevapi\collectionmodify::arrayAppend' => ['mysql_xdevapi\CollectionModify', 'collection_field'=>'string', 'expression_or_literal'=>'string'],
'mysql_xdevapi\collectionmodify::arrayInsert' => ['mysql_xdevapi\CollectionModify', 'collection_field'=>'string', 'expression_or_literal'=>'string'],
'mysql_xdevapi\collectionmodify::bind' => ['mysql_xdevapi\CollectionModify', 'placeholder_values'=>'array'],
'mysql_xdevapi\collectionmodify::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\collectionmodify::limit' => ['mysql_xdevapi\CollectionModify', 'rows'=>'integer'],
'mysql_xdevapi\collectionmodify::patch' => ['mysql_xdevapi\CollectionModify', 'document'=>'string'],
'mysql_xdevapi\collectionmodify::replace' => ['mysql_xdevapi\CollectionModify', 'collection_field'=>'string', 'expression_or_literal'=>'string'],
'mysql_xdevapi\collectionmodify::set' => ['mysql_xdevapi\CollectionModify', 'collection_field'=>'string', 'expression_or_literal'=>'string'],
'mysql_xdevapi\collectionmodify::skip' => ['mysql_xdevapi\CollectionModify', 'position'=>'integer'],
'mysql_xdevapi\collectionmodify::sort' => ['mysql_xdevapi\CollectionModify', 'sort_expr'=>'string'],
'mysql_xdevapi\collectionmodify::unset' => ['mysql_xdevapi\CollectionModify', 'fields'=>'array'],
'mysql_xdevapi\collectionremove::bind' => ['mysql_xdevapi\CollectionRemove', 'placeholder_values'=>'array'],
'mysql_xdevapi\collectionremove::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\collectionremove::limit' => ['mysql_xdevapi\CollectionRemove', 'rows'=>'integer'],
'mysql_xdevapi\collectionremove::sort' => ['mysql_xdevapi\CollectionRemove', 'sort_expr'=>'string'],
'mysql_xdevapi\columnresult::getCharacterSetName' => ['string'],
'mysql_xdevapi\columnresult::getCollationName' => ['string'],
'mysql_xdevapi\columnresult::getColumnLabel' => ['string'],
'mysql_xdevapi\columnresult::getColumnName' => ['string'],
'mysql_xdevapi\columnresult::getFractionalDigits' => ['integer'],
'mysql_xdevapi\columnresult::getLength' => ['integer'],
'mysql_xdevapi\columnresult::getSchemaName' => ['string'],
'mysql_xdevapi\columnresult::getTableLabel' => ['string'],
'mysql_xdevapi\columnresult::getTableName' => ['string'],
'mysql_xdevapi\columnresult::getType' => ['integer'],
'mysql_xdevapi\columnresult::isNumberSigned' => ['integer'],
'mysql_xdevapi\columnresult::isPadded' => ['integer'],
'mysql_xdevapi\crudoperationbindable::bind' => ['mysql_xdevapi\CrudOperationBindable', 'placeholder_values'=>'array'],
'mysql_xdevapi\crudoperationlimitable::limit' => ['mysql_xdevapi\CrudOperationLimitable', 'rows'=>'integer'],
'mysql_xdevapi\crudoperationskippable::skip' => ['mysql_xdevapi\CrudOperationSkippable', 'skip'=>'integer'],
'mysql_xdevapi\crudoperationsortable::sort' => ['mysql_xdevapi\CrudOperationSortable', 'sort_expr'=>'string'],
'mysql_xdevapi\databaseobject::existsInDatabase' => ['bool'],
'mysql_xdevapi\databaseobject::getName' => ['string'],
'mysql_xdevapi\databaseobject::getSession' => ['mysql_xdevapi\Session'],
'mysql_xdevapi\docresult::fetchAll' => ['Array'],
'mysql_xdevapi\docresult::fetchOne' => ['Object'],
'mysql_xdevapi\docresult::getWarnings' => ['Array'],
'mysql_xdevapi\docresult::getWarningsCount' => ['integer'],
'mysql_xdevapi\executable::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\getsession' => ['mysql_xdevapi\Session', 'uri'=>'string'],
'mysql_xdevapi\result::getAutoIncrementValue' => ['int'],
'mysql_xdevapi\result::getGeneratedIds' => ['ArrayOfInt'],
'mysql_xdevapi\result::getWarnings' => ['array'],
'mysql_xdevapi\result::getWarningsCount' => ['integer'],
'mysql_xdevapi\rowresult::fetchAll' => ['array'],
'mysql_xdevapi\rowresult::fetchOne' => ['object'],
'mysql_xdevapi\rowresult::getColumnCount' => ['integer'],
'mysql_xdevapi\rowresult::getColumnNames' => ['array'],
'mysql_xdevapi\rowresult::getColumns' => ['array'],
'mysql_xdevapi\rowresult::getWarnings' => ['array'],
'mysql_xdevapi\rowresult::getWarningsCount' => ['integer'],
'mysql_xdevapi\schema::createCollection' => ['mysql_xdevapi\Collection', 'name'=>'string'],
'mysql_xdevapi\schema::dropCollection' => ['bool', 'collection_name'=>'string'],
'mysql_xdevapi\schema::existsInDatabase' => ['bool'],
'mysql_xdevapi\schema::getCollection' => ['mysql_xdevapi\Collection', 'name'=>'string'],
'mysql_xdevapi\schema::getCollectionAsTable' => ['mysql_xdevapi\Table', 'name'=>'string'],
'mysql_xdevapi\schema::getCollections' => ['array'],
'mysql_xdevapi\schema::getName' => ['string'],
'mysql_xdevapi\schema::getSession' => ['mysql_xdevapi\Session'],
'mysql_xdevapi\schema::getTable' => ['mysql_xdevapi\Table', 'name'=>'string'],
'mysql_xdevapi\schema::getTables' => ['array'],
'mysql_xdevapi\schemaobject::getSchema' => ['mysql_xdevapi\Schema'],
'mysql_xdevapi\session::close' => ['bool'],
'mysql_xdevapi\session::commit' => ['Object'],
'mysql_xdevapi\session::createSchema' => ['mysql_xdevapi\Schema', 'schema_name'=>'string'],
'mysql_xdevapi\session::dropSchema' => ['bool', 'schema_name'=>'string'],
'mysql_xdevapi\session::executeSql' => ['Object', 'statement'=>'string'],
'mysql_xdevapi\session::generateUUID' => ['string'],
'mysql_xdevapi\session::getClientId' => ['integer'],
'mysql_xdevapi\session::getSchema' => ['mysql_xdevapi\Schema', 'schema_name'=>'string'],
'mysql_xdevapi\session::getSchemas' => ['array'],
'mysql_xdevapi\session::getServerVersion' => ['integer'],
'mysql_xdevapi\session::killClient' => ['object', 'client_id'=>'integer'],
'mysql_xdevapi\session::listClients' => ['array'],
'mysql_xdevapi\session::quoteName' => ['string', 'name'=>'string'],
'mysql_xdevapi\session::releaseSavepoint' => ['void', 'name'=>'string'],
'mysql_xdevapi\session::rollback' => ['void'],
'mysql_xdevapi\session::rollbackTo' => ['void', 'name'=>'string'],
'mysql_xdevapi\session::setSavepoint' => ['string', 'name='=>'string'],
'mysql_xdevapi\session::sql' => ['mysql_xdevapi\SqlStatement', 'query'=>'string'],
'mysql_xdevapi\session::startTransaction' => ['void'],
'mysql_xdevapi\sqlstatement::bind' => ['mysql_xdevapi\SqlStatement', 'param'=>'string'],
'mysql_xdevapi\sqlstatement::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\sqlstatement::getNextResult' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\sqlstatement::getResult' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\sqlstatement::hasMoreResults' => ['bool'],
'mysql_xdevapi\sqlstatementresult::fetchAll' => ['array'],
'mysql_xdevapi\sqlstatementresult::fetchOne' => ['object'],
'mysql_xdevapi\sqlstatementresult::getAffectedItemsCount' => ['integer'],
'mysql_xdevapi\sqlstatementresult::getColumnCount' => ['integer'],
'mysql_xdevapi\sqlstatementresult::getColumnNames' => ['array'],
'mysql_xdevapi\sqlstatementresult::getColumns' => ['Array'],
'mysql_xdevapi\sqlstatementresult::getGeneratedIds' => ['array'],
'mysql_xdevapi\sqlstatementresult::getLastInsertId' => ['String'],
'mysql_xdevapi\sqlstatementresult::getWarnings' => ['array'],
'mysql_xdevapi\sqlstatementresult::getWarningsCount' => ['integer'],
'mysql_xdevapi\sqlstatementresult::hasData' => ['bool'],
'mysql_xdevapi\sqlstatementresult::nextResult' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\statement::getNextResult' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\statement::getResult' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\statement::hasMoreResults' => ['bool'],
'mysql_xdevapi\table::count' => ['integer'],
'mysql_xdevapi\table::delete' => ['mysql_xdevapi\TableDelete'],
'mysql_xdevapi\table::existsInDatabase' => ['bool'],
'mysql_xdevapi\table::getName' => ['string'],
'mysql_xdevapi\table::getSchema' => ['mysql_xdevapi\Schema'],
'mysql_xdevapi\table::getSession' => ['mysql_xdevapi\Session'],
'mysql_xdevapi\table::insert' => ['mysql_xdevapi\TableInsert', 'columns'=>'mixed', '...args='=>'mixed'],
'mysql_xdevapi\table::isView' => ['bool'],
'mysql_xdevapi\table::select' => ['mysql_xdevapi\TableSelect', 'columns'=>'mixed', '...args='=>'mixed'],
'mysql_xdevapi\table::update' => ['mysql_xdevapi\TableUpdate'],
'mysql_xdevapi\tabledelete::bind' => ['mysql_xdevapi\TableDelete', 'placeholder_values'=>'array'],
'mysql_xdevapi\tabledelete::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\tabledelete::limit' => ['mysql_xdevapi\TableDelete', 'rows'=>'integer'],
'mysql_xdevapi\tabledelete::offset' => ['mysql_xdevapi\TableDelete', 'position'=>'integer'],
'mysql_xdevapi\tabledelete::orderby' => ['mysql_xdevapi\TableDelete', 'orderby_expr'=>'string'],
'mysql_xdevapi\tabledelete::where' => ['mysql_xdevapi\TableDelete', 'where_expr'=>'string'],
'mysql_xdevapi\tableinsert::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\tableinsert::values' => ['mysql_xdevapi\TableInsert', 'row_values'=>'array'],
'mysql_xdevapi\tableselect::bind' => ['mysql_xdevapi\TableSelect', 'placeholder_values'=>'array'],
'mysql_xdevapi\tableselect::execute' => ['mysql_xdevapi\RowResult'],
'mysql_xdevapi\tableselect::groupBy' => ['mysql_xdevapi\TableSelect', 'sort_expr'=>'mixed'],
'mysql_xdevapi\tableselect::having' => ['mysql_xdevapi\TableSelect', 'sort_expr'=>'string'],
'mysql_xdevapi\tableselect::limit' => ['mysql_xdevapi\TableSelect', 'rows'=>'integer'],
'mysql_xdevapi\tableselect::lockExclusive' => ['mysql_xdevapi\TableSelect', 'lock_waiting_option='=>'integer'],
'mysql_xdevapi\tableselect::lockShared' => ['mysql_xdevapi\TableSelect', 'lock_waiting_option='=>'integer'],
'mysql_xdevapi\tableselect::offset' => ['mysql_xdevapi\TableSelect', 'position'=>'integer'],
'mysql_xdevapi\tableselect::orderby' => ['mysql_xdevapi\TableSelect', 'sort_expr'=>'mixed', '...args='=>'mixed'],
'mysql_xdevapi\tableselect::where' => ['mysql_xdevapi\TableSelect', 'where_expr'=>'string'],
'mysql_xdevapi\tableupdate::bind' => ['mysql_xdevapi\TableUpdate', 'placeholder_values'=>'array'],
'mysql_xdevapi\tableupdate::execute' => ['mysql_xdevapi\TableUpdate'],
'mysql_xdevapi\tableupdate::limit' => ['mysql_xdevapi\TableUpdate', 'rows'=>'integer'],
'mysql_xdevapi\tableupdate::orderby' => ['mysql_xdevapi\TableUpdate', 'orderby_expr'=>'mixed', '...args='=>'mixed'],
'mysql_xdevapi\tableupdate::set' => ['mysql_xdevapi\TableUpdate', 'table_field'=>'string', 'expression_or_literal'=>'string'],
'mysql_xdevapi\tableupdate::where' => ['mysql_xdevapi\TableUpdate', 'where_expr'=>'string'],
'mysqli::__construct' => ['void', 'hostname='=>'string|null', 'username='=>'string|null', 'password='=>'string|null', 'database='=>'string|null', 'port='=>'int|null', 'socket='=>'string|null'],
'mysqli::autocommit' => ['bool', 'enable'=>'bool'],
'mysqli::begin_transaction' => ['bool', 'flags='=>'int', 'name='=>'string'],
'mysqli::change_user' => ['bool', 'username'=>'string', 'password'=>'string', 'database'=>'string'],
'mysqli::character_set_name' => ['string'],
'mysqli::close' => ['bool'],
'mysqli::commit' => ['bool', 'flags='=>'int', 'name='=>'string'],
'mysqli::connect' => ['bool', 'hostname='=>'string|null', 'username='=>'string|null', 'password='=>'string|null', 'database='=>'string|null', 'port='=>'int|null', 'socket='=>'string|null'],
'mysqli::debug' => ['bool', 'options'=>'string'],
'mysqli::disable_reads_from_master' => ['bool'],
'mysqli::dump_debug_info' => ['bool'],
'mysqli::escape_string' => ['string', 'string'=>'string'],
'mysqli::get_charset' => ['object'],
'mysqli::get_client_info' => ['string'],
'mysqli::get_connection_stats' => ['array|false'],
'mysqli::get_warnings' => ['mysqli_warning'],
'mysqli::init' => ['mysqli'],
'mysqli::kill' => ['bool', 'process_id'=>'int'],
'mysqli::more_results' => ['bool'],
'mysqli::multi_query' => ['bool', 'query'=>'string'],
'mysqli::next_result' => ['bool'],
'mysqli::options' => ['bool', 'option'=>'int', 'value'=>'mixed'],
'mysqli::ping' => ['bool'],
'mysqli::poll' => ['int|false', '&w_read'=>'array', '&w_write'=>'array', '&w_error'=>'array', 'seconds'=>'int', 'microseconds='=>'int'],
'mysqli::prepare' => ['mysqli_stmt|false', 'query'=>'string'],
'mysqli::query' => ['bool|mysqli_result', 'query'=>'string', 'result_mode='=>'int'],
'mysqli::real_connect' => ['bool', 'hostname='=>'string|null', 'username='=>'string|null', 'password='=>'string|null', 'database='=>'string|null', 'port='=>'int|null', 'socket='=>'string|null', 'flags='=>'int'],
'mysqli::real_escape_string' => ['string', 'string'=>'string'],
'mysqli::real_query' => ['bool', 'query'=>'string'],
'mysqli::reap_async_query' => ['mysqli_result|false'],
'mysqli::refresh' => ['bool', 'flags'=>'int'],
'mysqli::release_savepoint' => ['bool', 'name'=>'string'],
'mysqli::rollback' => ['bool', 'flags='=>'int', 'name='=>'string'],
'mysqli::rpl_query_type' => ['int', 'query'=>'string'],
'mysqli::savepoint' => ['bool', 'name'=>'string'],
'mysqli::select_db' => ['bool', 'database'=>'string'],
'mysqli::send_query' => ['bool', 'query'=>'string'],
'mysqli::set_charset' => ['bool', 'charset'=>'string'],
'mysqli::set_local_infile_default' => ['void'],
'mysqli::set_local_infile_handler' => ['bool', 'read_func='=>'callable'],
'mysqli::ssl_set' => ['bool', 'key'=>'string', 'certificate'=>'string', 'ca_certificate'=>'string', 'ca_path'=>'string', 'cipher_algos'=>'string'],
'mysqli::stat' => ['string|false'],
'mysqli::stmt_init' => ['mysqli_stmt'],
'mysqli::store_result' => ['mysqli_result|false', 'mode='=>'int'],
'mysqli::thread_safe' => ['bool'],
'mysqli::use_result' => ['mysqli_result|false'],
'mysqli_affected_rows' => ['int', 'mysql'=>'mysqli'],
'mysqli_autocommit' => ['bool', 'mysql'=>'mysqli', 'enable'=>'bool'],
'mysqli_begin_transaction' => ['bool', 'mysql'=>'mysqli', 'flags='=>'int', 'name='=>'string'],
'mysqli_change_user' => ['bool', 'mysql'=>'mysqli', 'username'=>'string', 'password'=>'string', 'database'=>'?string'],
'mysqli_character_set_name' => ['string', 'mysql'=>'mysqli'],
'mysqli_close' => ['bool', 'mysql'=>'mysqli'],
'mysqli_commit' => ['bool', 'mysql'=>'mysqli', 'flags='=>'int', 'name='=>'string'],
'mysqli_connect' => ['mysqli|false', 'hostname='=>'string|null', 'username='=>'string|null', 'password='=>'string|null', 'database='=>'string|null', 'port='=>'int|null', 'socket='=>'string|null'],
'mysqli_connect_errno' => ['int'],
'mysqli_connect_error' => ['?string'],
'mysqli_data_seek' => ['bool', 'result'=>'mysqli_result', 'offset'=>'int'],
'mysqli_debug' => ['bool', 'options'=>'string'],
'mysqli_disable_reads_from_master' => ['bool', 'link'=>'mysqli'],
'mysqli_disable_rpl_parse' => ['bool', 'link'=>'mysqli'],
'mysqli_driver::embedded_server_end' => ['void'],
'mysqli_driver::embedded_server_start' => ['bool', 'start'=>'int', 'arguments'=>'array', 'groups'=>'array'],
'mysqli_dump_debug_info' => ['bool', 'mysql'=>'mysqli'],
'mysqli_embedded_server_end' => ['void'],
'mysqli_embedded_server_start' => ['bool', 'start'=>'int', 'arguments'=>'array', 'groups'=>'array'],
'mysqli_enable_reads_from_master' => ['bool', 'link'=>'mysqli'],
'mysqli_enable_rpl_parse' => ['bool', 'link'=>'mysqli'],
'mysqli_errno' => ['int', 'mysql'=>'mysqli'],
'mysqli_error' => ['string', 'mysql'=>'mysqli'],
'mysqli_error_list' => ['array', 'mysql'=>'mysqli'],
'mysqli_escape_string' => ['string', 'mysql'=>'mysqli', 'string'=>'string'],
'mysqli_execute' => ['bool', 'statement'=>'mysqli_stmt', 'params='=>'list<mixed>|null'],
'mysqli_fetch_all' => ['array', 'result'=>'mysqli_result', 'mode='=>'int'],
'mysqli_fetch_array' => ['?array', 'result'=>'mysqli_result', 'mode='=>'int'],
'mysqli_fetch_assoc' => ['array<string,string>|null', 'result'=>'mysqli_result'],
'mysqli_fetch_column' => ['null|int|float|string|false', 'result'=>'mysqli_result', 'column='=>'int'],
'mysqli_fetch_field' => ['object|false', 'result'=>'mysqli_result'],
'mysqli_fetch_field_direct' => ['object|false', 'result'=>'mysqli_result', 'index'=>'int'],
'mysqli_fetch_fields' => ['array|false', 'result'=>'mysqli_result'],
'mysqli_fetch_lengths' => ['array|false', 'result'=>'mysqli_result'],
'mysqli_fetch_object' => ['?object', 'result'=>'mysqli_result', 'class='=>'string', 'constructor_args='=>'?array'],
'mysqli_fetch_row' => ['?array', 'result'=>'mysqli_result'],
'mysqli_field_count' => ['int', 'mysql'=>'mysqli'],
'mysqli_field_seek' => ['bool', 'result'=>'mysqli_result', 'index'=>'int'],
'mysqli_field_tell' => ['int', 'result'=>'mysqli_result'],
'mysqli_free_result' => ['void', 'result'=>'mysqli_result'],
'mysqli_get_cache_stats' => ['array|false'],
'mysqli_get_charset' => ['object', 'mysql'=>'mysqli'],
'mysqli_get_client_info' => ['string', 'mysql'=>'mysqli'],
'mysqli_get_client_stats' => ['array|false'],
'mysqli_get_client_version' => ['int', 'link'=>'mysqli'],
'mysqli_get_connection_stats' => ['array|false', 'mysql'=>'mysqli'],
'mysqli_get_host_info' => ['string', 'mysql'=>'mysqli'],
'mysqli_get_links_stats' => ['array'],
'mysqli_get_proto_info' => ['int', 'mysql'=>'mysqli'],
'mysqli_get_server_info' => ['string', 'mysql'=>'mysqli'],
'mysqli_get_server_version' => ['int', 'mysql'=>'mysqli'],
'mysqli_get_warnings' => ['mysqli_warning', 'mysql'=>'mysqli'],
'mysqli_info' => ['?string', 'mysql'=>'mysqli'],
'mysqli_init' => ['mysqli|false'],
'mysqli_insert_id' => ['int|string', 'mysql'=>'mysqli'],
'mysqli_kill' => ['bool', 'mysql'=>'mysqli', 'process_id'=>'int'],
'mysqli_link_construct' => ['object'],
'mysqli_master_query' => ['bool', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_more_results' => ['bool', 'mysql'=>'mysqli'],
'mysqli_multi_query' => ['bool', 'mysql'=>'mysqli', 'query'=>'string'],
'mysqli_next_result' => ['bool', 'mysql'=>'mysqli'],
'mysqli_num_fields' => ['int', 'result'=>'mysqli_result'],
'mysqli_num_rows' => ['int', 'result'=>'mysqli_result'],
'mysqli_options' => ['bool', 'mysql'=>'mysqli', 'option'=>'int', 'value'=>'mixed'],
'mysqli_ping' => ['bool', 'mysql'=>'mysqli'],
'mysqli_poll' => ['int|false', 'read'=>'array', 'write'=>'array', 'error'=>'array', 'seconds'=>'int', 'microseconds='=>'int'],
'mysqli_prepare' => ['mysqli_stmt|false', 'mysql'=>'mysqli', 'query'=>'string'],
'mysqli_query' => ['mysqli_result|bool', 'mysql'=>'mysqli', 'query'=>'string', 'result_mode='=>'int'],
'mysqli_real_connect' => ['bool', 'mysql='=>'mysqli', 'hostname='=>'string|null', 'username='=>'string|null', 'password='=>'string|null', 'database='=>'string|null', 'port='=>'int|null', 'socket='=>'string|null', 'flags='=>'int'],
'mysqli_real_escape_string' => ['string', 'mysql'=>'mysqli', 'string'=>'string'],
'mysqli_real_query' => ['bool', 'mysql'=>'mysqli', 'query'=>'string'],
'mysqli_reap_async_query' => ['mysqli_result|false', 'mysql'=>'mysqli'],
'mysqli_refresh' => ['bool', 'mysql'=>'mysqli', 'flags'=>'int'],
'mysqli_release_savepoint' => ['bool', 'mysql'=>'mysqli', 'name'=>'string'],
'mysqli_report' => ['bool', 'flags'=>'int'],
'mysqli_result::__construct' => ['void', 'mysql'=>'mysqli', 'result_mode='=>'int'],
'mysqli_result::close' => ['void'],
'mysqli_result::data_seek' => ['bool', 'offset'=>'int'],
'mysqli_result::fetch_all' => ['array', 'mode='=>'int'],
'mysqli_result::fetch_array' => ['?array', 'mode='=>'int'],
'mysqli_result::fetch_assoc' => ['array<string,string>|null'],
'mysqli_result::fetch_column' => ['null|int|float|string|false', 'column='=>'int'],
'mysqli_result::fetch_field' => ['object|false'],
'mysqli_result::fetch_field_direct' => ['object|false', 'index'=>'int'],
'mysqli_result::fetch_fields' => ['array|false'],
'mysqli_result::fetch_object' => ['object|stdClass|null', 'class='=>'string', 'constructor_args='=>'array'],
'mysqli_result::fetch_row' => ['?array'],
'mysqli_result::field_seek' => ['bool', 'index'=>'int'],
'mysqli_result::free' => ['void'],
'mysqli_result::free_result' => ['void'],
'mysqli_rollback' => ['bool', 'mysql'=>'mysqli', 'flags='=>'int', 'name='=>'string'],
'mysqli_rpl_parse_enabled' => ['int', 'link'=>'mysqli'],
'mysqli_rpl_probe' => ['bool', 'link'=>'mysqli'],
'mysqli_rpl_query_type' => ['int', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_savepoint' => ['bool', 'mysql'=>'mysqli', 'name'=>'string'],
'mysqli_savepoint_libmysql' => ['bool'],
'mysqli_select_db' => ['bool', 'mysql'=>'mysqli', 'database'=>'string'],
'mysqli_send_query' => ['bool', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_set_charset' => ['bool', 'mysql'=>'mysqli', 'charset'=>'string'],
'mysqli_set_local_infile_default' => ['void', 'link'=>'mysqli'],
'mysqli_set_local_infile_handler' => ['bool', 'link'=>'mysqli', 'read_func'=>'callable'],
'mysqli_set_opt' => ['bool', 'mysql'=>'mysqli', 'option'=>'int', 'value'=>'mixed'],
'mysqli_slave_query' => ['bool', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_sqlstate' => ['string', 'mysql'=>'mysqli'],
'mysqli_ssl_set' => ['bool', 'mysql'=>'mysqli', 'key'=>'string', 'certificate'=>'string', 'ca_certificate'=>'string', 'ca_path'=>'string', 'cipher_algos'=>'string'],
'mysqli_stat' => ['string|false', 'mysql'=>'mysqli'],
'mysqli_stmt::__construct' => ['void', 'mysql'=>'mysqli', 'query'=>'string'],
'mysqli_stmt::attr_get' => ['false|int', 'attribute'=>'int'],
'mysqli_stmt::attr_set' => ['bool', 'attribute'=>'int', 'value'=>'int'],
'mysqli_stmt::bind_param' => ['bool', 'types'=>'string', '&vars'=>'mixed', '&...args='=>'mixed'],
'mysqli_stmt::bind_result' => ['bool', '&w_var1'=>'', '&...w_vars='=>''],
'mysqli_stmt::close' => ['bool'],
'mysqli_stmt::data_seek' => ['void', 'offset'=>'int'],
'mysqli_stmt::execute' => ['bool', 'params='=>'list<mixed>|null'],
'mysqli_stmt::fetch' => ['bool|null'],
'mysqli_stmt::free_result' => ['void'],
'mysqli_stmt::get_result' => ['mysqli_result|false'],
'mysqli_stmt::get_warnings' => ['object'],
'mysqli_stmt::more_results' => ['bool'],
'mysqli_stmt::next_result' => ['bool'],
'mysqli_stmt::num_rows' => ['int'],
'mysqli_stmt::prepare' => ['bool', 'query'=>'string'],
'mysqli_stmt::reset' => ['bool'],
'mysqli_stmt::result_metadata' => ['mysqli_result|false'],
'mysqli_stmt::send_long_data' => ['bool', 'param_num'=>'int', 'data'=>'string'],
'mysqli_stmt::store_result' => ['bool'],
'mysqli_stmt_affected_rows' => ['int|string', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_attr_get' => ['int|false', 'statement'=>'mysqli_stmt', 'attribute'=>'int'],
'mysqli_stmt_attr_set' => ['bool', 'statement'=>'mysqli_stmt', 'attribute'=>'int', 'value'=>'int'],
'mysqli_stmt_bind_param' => ['bool', 'statement'=>'mysqli_stmt', 'types'=>'string', '&vars'=>'mixed', '&...args='=>'mixed'],
'mysqli_stmt_bind_result' => ['bool', 'statement'=>'mysqli_stmt', '&w_var1'=>'', '&...w_vars='=>''],
'mysqli_stmt_close' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_data_seek' => ['void', 'statement'=>'mysqli_stmt', 'offset'=>'int'],
'mysqli_stmt_errno' => ['int', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_error' => ['string', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_error_list' => ['array', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_execute' => ['bool', 'statement'=>'mysqli_stmt', 'params='=>'list<mixed>|null'],
'mysqli_stmt_fetch' => ['bool|null', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_field_count' => ['int', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_free_result' => ['void', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_get_result' => ['mysqli_result|false', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_get_warnings' => ['object', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_init' => ['mysqli_stmt', 'mysql'=>'mysqli'],
'mysqli_stmt_insert_id' => ['mixed', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_more_results' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_next_result' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_num_rows' => ['int', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_param_count' => ['int', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_prepare' => ['bool', 'statement'=>'mysqli_stmt', 'query'=>'string'],
'mysqli_stmt_reset' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_result_metadata' => ['mysqli_result|false', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_send_long_data' => ['bool', 'statement'=>'mysqli_stmt', 'param_num'=>'int', 'data'=>'string'],
'mysqli_stmt_sqlstate' => ['string', 'statement'=>'mysqli_stmt'],
'mysqli_stmt_store_result' => ['bool', 'statement'=>'mysqli_stmt'],
'mysqli_store_result' => ['mysqli_result|false', 'mysql'=>'mysqli', 'mode='=>'int'],
'mysqli_thread_id' => ['int', 'mysql'=>'mysqli'],
'mysqli_thread_safe' => ['bool'],
'mysqli_use_result' => ['mysqli_result|false', 'mysql'=>'mysqli'],
'mysqli_warning::__construct' => ['void'],
'mysqli_warning::next' => ['bool'],
'mysqli_warning_count' => ['int', 'mysql'=>'mysqli'],
'mysqlnd_memcache_get_config' => ['array', 'connection'=>'mixed'],
'mysqlnd_memcache_set' => ['bool', 'mysql_connection'=>'mixed', 'memcache_connection='=>'Memcached', 'pattern='=>'string', 'callback='=>'callable'],
'mysqlnd_ms_dump_servers' => ['array', 'connection'=>'mixed'],
'mysqlnd_ms_fabric_select_global' => ['array', 'connection'=>'mixed', 'table_name'=>'mixed'],
'mysqlnd_ms_fabric_select_shard' => ['array', 'connection'=>'mixed', 'table_name'=>'mixed', 'shard_key'=>'mixed'],
'mysqlnd_ms_get_last_gtid' => ['string', 'connection'=>'mixed'],
'mysqlnd_ms_get_last_used_connection' => ['array', 'connection'=>'mixed'],
'mysqlnd_ms_get_stats' => ['array'],
'mysqlnd_ms_match_wild' => ['bool', 'table_name'=>'string', 'wildcard'=>'string'],
'mysqlnd_ms_query_is_select' => ['int', 'query'=>'string'],
'mysqlnd_ms_set_qos' => ['bool', 'connection'=>'mixed', 'service_level'=>'int', 'service_level_option='=>'int', 'option_value='=>'mixed'],
'mysqlnd_ms_set_user_pick_server' => ['bool', 'function'=>'string'],
'mysqlnd_ms_xa_begin' => ['int', 'connection'=>'mixed', 'gtrid'=>'string', 'timeout='=>'int'],
'mysqlnd_ms_xa_commit' => ['int', 'connection'=>'mixed', 'gtrid'=>'string'],
'mysqlnd_ms_xa_gc' => ['int', 'connection'=>'mixed', 'gtrid='=>'string', 'ignore_max_retries='=>'bool'],
'mysqlnd_ms_xa_rollback' => ['int', 'connection'=>'mixed', 'gtrid'=>'string'],
'mysqlnd_qc_change_handler' => ['bool', 'handler'=>''],
'mysqlnd_qc_clear_cache' => ['bool'],
'mysqlnd_qc_get_available_handlers' => ['array'],
'mysqlnd_qc_get_cache_info' => ['array'],
'mysqlnd_qc_get_core_stats' => ['array'],
'mysqlnd_qc_get_handler' => ['array'],
'mysqlnd_qc_get_normalized_query_trace_log' => ['array'],
'mysqlnd_qc_get_query_trace_log' => ['array'],
'mysqlnd_qc_set_cache_condition' => ['bool', 'condition_type'=>'int', 'condition'=>'mixed', 'condition_option'=>'mixed'],
'mysqlnd_qc_set_is_select' => ['mixed', 'callback'=>'string'],
'mysqlnd_qc_set_storage_handler' => ['bool', 'handler'=>'string'],
'mysqlnd_qc_set_user_handlers' => ['bool', 'get_hash'=>'string', 'find_query_in_cache'=>'string', 'return_to_cache'=>'string', 'add_query_to_cache_if_not_exists'=>'string', 'query_is_select'=>'string', 'update_query_run_time_stats'=>'string', 'get_stats'=>'string', 'clear_cache'=>'string'],
'mysqlnd_uh_convert_to_mysqlnd' => ['resource', '&rw_mysql_connection'=>'mysqli'],
'mysqlnd_uh_set_connection_proxy' => ['bool', '&rw_connection_proxy'=>'MysqlndUhConnection', '&rw_mysqli_connection='=>'mysqli'],
'mysqlnd_uh_set_statement_proxy' => ['bool', '&rw_statement_proxy'=>'MysqlndUhStatement'],
'MysqlndUhConnection::__construct' => ['void'],
'MysqlndUhConnection::changeUser' => ['bool', 'connection'=>'mysqlnd_connection', 'user'=>'string', 'password'=>'string', 'database'=>'string', 'silent'=>'bool', 'passwd_len'=>'int'],
'MysqlndUhConnection::charsetName' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::close' => ['bool', 'connection'=>'mysqlnd_connection', 'close_type'=>'int'],
'MysqlndUhConnection::connect' => ['bool', 'connection'=>'mysqlnd_connection', 'host'=>'string', 'use'=>'string', 'password'=>'string', 'database'=>'string', 'port'=>'int', 'socket'=>'string', 'mysql_flags'=>'int'],
'MysqlndUhConnection::endPSession' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::escapeString' => ['string', 'connection'=>'mysqlnd_connection', 'escape_string'=>'string'],
'MysqlndUhConnection::getAffectedRows' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getErrorNumber' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getErrorString' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getFieldCount' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getHostInformation' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getLastInsertId' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getLastMessage' => ['void', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getProtocolInformation' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getServerInformation' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getServerStatistics' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getServerVersion' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getSqlstate' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getStatistics' => ['array', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getThreadId' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getWarningCount' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::init' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::killConnection' => ['bool', 'connection'=>'mysqlnd_connection', 'pid'=>'int'],
'MysqlndUhConnection::listFields' => ['array', 'connection'=>'mysqlnd_connection', 'table'=>'string', 'achtung_wild'=>'string'],
'MysqlndUhConnection::listMethod' => ['void', 'connection'=>'mysqlnd_connection', 'query'=>'string', 'achtung_wild'=>'string', 'par1'=>'string'],
'MysqlndUhConnection::moreResults' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::nextResult' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::ping' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::query' => ['bool', 'connection'=>'mysqlnd_connection', 'query'=>'string'],
'MysqlndUhConnection::queryReadResultsetHeader' => ['bool', 'connection'=>'mysqlnd_connection', 'mysqlnd_stmt'=>'mysqlnd_statement'],
'MysqlndUhConnection::reapQuery' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::refreshServer' => ['bool', 'connection'=>'mysqlnd_connection', 'options'=>'int'],
'MysqlndUhConnection::restartPSession' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::selectDb' => ['bool', 'connection'=>'mysqlnd_connection', 'database'=>'string'],
'MysqlndUhConnection::sendClose' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::sendQuery' => ['bool', 'connection'=>'mysqlnd_connection', 'query'=>'string'],
'MysqlndUhConnection::serverDumpDebugInformation' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::setAutocommit' => ['bool', 'connection'=>'mysqlnd_connection', 'mode'=>'int'],
'MysqlndUhConnection::setCharset' => ['bool', 'connection'=>'mysqlnd_connection', 'charset'=>'string'],
'MysqlndUhConnection::setClientOption' => ['bool', 'connection'=>'mysqlnd_connection', 'option'=>'int', 'value'=>'int'],
'MysqlndUhConnection::setServerOption' => ['void', 'connection'=>'mysqlnd_connection', 'option'=>'int'],
'MysqlndUhConnection::shutdownServer' => ['void', 'MYSQLND_UH_RES_MYSQLND_NAME'=>'string', 'level'=>'string'],
'MysqlndUhConnection::simpleCommand' => ['bool', 'connection'=>'mysqlnd_connection', 'command'=>'int', 'arg'=>'string', 'ok_packet'=>'int', 'silent'=>'bool', 'ignore_upsert_status'=>'bool'],
'MysqlndUhConnection::simpleCommandHandleResponse' => ['bool', 'connection'=>'mysqlnd_connection', 'ok_packet'=>'int', 'silent'=>'bool', 'command'=>'int', 'ignore_upsert_status'=>'bool'],
'MysqlndUhConnection::sslSet' => ['bool', 'connection'=>'mysqlnd_connection', 'key'=>'string', 'cert'=>'string', 'ca'=>'string', 'capath'=>'string', 'cipher'=>'string'],
'MysqlndUhConnection::stmtInit' => ['resource', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::storeResult' => ['resource', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::txCommit' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::txRollback' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::useResult' => ['resource', 'connection'=>'mysqlnd_connection'],
'MysqlndUhPreparedStatement::__construct' => ['void'],
'MysqlndUhPreparedStatement::execute' => ['bool', 'statement'=>'mysqlnd_prepared_statement'],
'MysqlndUhPreparedStatement::prepare' => ['bool', 'statement'=>'mysqlnd_prepared_statement', 'query'=>'string'],
'natcasesort' => ['bool', '&rw_array'=>'array'],
'natsort' => ['bool', '&rw_array'=>'array'],
'ncurses_addch' => ['int', 'ch'=>'int'],
'ncurses_addchnstr' => ['int', 's'=>'string', 'n'=>'int'],
'ncurses_addchstr' => ['int', 's'=>'string'],
'ncurses_addnstr' => ['int', 's'=>'string', 'n'=>'int'],
'ncurses_addstr' => ['int', 'text'=>'string'],
'ncurses_assume_default_colors' => ['int', 'fg'=>'int', 'bg'=>'int'],
'ncurses_attroff' => ['int', 'attributes'=>'int'],
'ncurses_attron' => ['int', 'attributes'=>'int'],
'ncurses_attrset' => ['int', 'attributes'=>'int'],
'ncurses_baudrate' => ['int'],
'ncurses_beep' => ['int'],
'ncurses_bkgd' => ['int', 'attrchar'=>'int'],
'ncurses_bkgdset' => ['void', 'attrchar'=>'int'],
'ncurses_border' => ['int', 'left'=>'int', 'right'=>'int', 'top'=>'int', 'bottom'=>'int', 'tl_corner'=>'int', 'tr_corner'=>'int', 'bl_corner'=>'int', 'br_corner'=>'int'],
'ncurses_bottom_panel' => ['int', 'panel'=>'resource'],
'ncurses_can_change_color' => ['bool'],
'ncurses_cbreak' => ['bool'],
'ncurses_clear' => ['bool'],
'ncurses_clrtobot' => ['bool'],
'ncurses_clrtoeol' => ['bool'],
'ncurses_color_content' => ['int', 'color'=>'int', 'r'=>'int', 'g'=>'int', 'b'=>'int'],
'ncurses_color_set' => ['int', 'pair'=>'int'],
'ncurses_curs_set' => ['int', 'visibility'=>'int'],
'ncurses_def_prog_mode' => ['bool'],
'ncurses_def_shell_mode' => ['bool'],
'ncurses_define_key' => ['int', 'definition'=>'string', 'keycode'=>'int'],
'ncurses_del_panel' => ['bool', 'panel'=>'resource'],
'ncurses_delay_output' => ['int', 'milliseconds'=>'int'],
'ncurses_delch' => ['bool'],
'ncurses_deleteln' => ['bool'],
'ncurses_delwin' => ['bool', 'window'=>'resource'],
'ncurses_doupdate' => ['bool'],
'ncurses_echo' => ['bool'],
'ncurses_echochar' => ['int', 'character'=>'int'],
'ncurses_end' => ['int'],
'ncurses_erase' => ['bool'],
'ncurses_erasechar' => ['string'],
'ncurses_filter' => ['void'],
'ncurses_flash' => ['bool'],
'ncurses_flushinp' => ['bool'],
'ncurses_getch' => ['int'],
'ncurses_getmaxyx' => ['void', 'window'=>'resource', 'y'=>'int', 'x'=>'int'],
'ncurses_getmouse' => ['bool', 'mevent'=>'array'],
'ncurses_getyx' => ['void', 'window'=>'resource', 'y'=>'int', 'x'=>'int'],
'ncurses_halfdelay' => ['int', 'tenth'=>'int'],
'ncurses_has_colors' => ['bool'],
'ncurses_has_ic' => ['bool'],
'ncurses_has_il' => ['bool'],
'ncurses_has_key' => ['int', 'keycode'=>'int'],
'ncurses_hide_panel' => ['int', 'panel'=>'resource'],
'ncurses_hline' => ['int', 'charattr'=>'int', 'n'=>'int'],
'ncurses_inch' => ['string'],
'ncurses_init' => ['void'],
'ncurses_init_color' => ['int', 'color'=>'int', 'r'=>'int', 'g'=>'int', 'b'=>'int'],
'ncurses_init_pair' => ['int', 'pair'=>'int', 'fg'=>'int', 'bg'=>'int'],
'ncurses_insch' => ['int', 'character'=>'int'],
'ncurses_insdelln' => ['int', 'count'=>'int'],
'ncurses_insertln' => ['int'],
'ncurses_insstr' => ['int', 'text'=>'string'],
'ncurses_instr' => ['int', 'buffer'=>'string'],
'ncurses_isendwin' => ['bool'],
'ncurses_keyok' => ['int', 'keycode'=>'int', 'enable'=>'bool'],
'ncurses_keypad' => ['int', 'window'=>'resource', 'bf'=>'bool'],
'ncurses_killchar' => ['string'],
'ncurses_longname' => ['string'],
'ncurses_meta' => ['int', 'window'=>'resource', '_8bit'=>'bool'],
'ncurses_mouse_trafo' => ['bool', 'y'=>'int', 'x'=>'int', 'toscreen'=>'bool'],
'ncurses_mouseinterval' => ['int', 'milliseconds'=>'int'],
'ncurses_mousemask' => ['int', 'newmask'=>'int', 'oldmask'=>'int'],
'ncurses_move' => ['int', 'y'=>'int', 'x'=>'int'],
'ncurses_move_panel' => ['int', 'panel'=>'resource', 'startx'=>'int', 'starty'=>'int'],
'ncurses_mvaddch' => ['int', 'y'=>'int', 'x'=>'int', 'c'=>'int'],
'ncurses_mvaddchnstr' => ['int', 'y'=>'int', 'x'=>'int', 's'=>'string', 'n'=>'int'],
'ncurses_mvaddchstr' => ['int', 'y'=>'int', 'x'=>'int', 's'=>'string'],
'ncurses_mvaddnstr' => ['int', 'y'=>'int', 'x'=>'int', 's'=>'string', 'n'=>'int'],
'ncurses_mvaddstr' => ['int', 'y'=>'int', 'x'=>'int', 's'=>'string'],
'ncurses_mvcur' => ['int', 'old_y'=>'int', 'old_x'=>'int', 'new_y'=>'int', 'new_x'=>'int'],
'ncurses_mvdelch' => ['int', 'y'=>'int', 'x'=>'int'],
'ncurses_mvgetch' => ['int', 'y'=>'int', 'x'=>'int'],
'ncurses_mvhline' => ['int', 'y'=>'int', 'x'=>'int', 'attrchar'=>'int', 'n'=>'int'],
'ncurses_mvinch' => ['int', 'y'=>'int', 'x'=>'int'],
'ncurses_mvvline' => ['int', 'y'=>'int', 'x'=>'int', 'attrchar'=>'int', 'n'=>'int'],
'ncurses_mvwaddstr' => ['int', 'window'=>'resource', 'y'=>'int', 'x'=>'int', 'text'=>'string'],
'ncurses_napms' => ['int', 'milliseconds'=>'int'],
'ncurses_new_panel' => ['resource', 'window'=>'resource'],
'ncurses_newpad' => ['resource', 'rows'=>'int', 'cols'=>'int'],
'ncurses_newwin' => ['resource', 'rows'=>'int', 'cols'=>'int', 'y'=>'int', 'x'=>'int'],
'ncurses_nl' => ['bool'],
'ncurses_nocbreak' => ['bool'],
'ncurses_noecho' => ['bool'],
'ncurses_nonl' => ['bool'],
'ncurses_noqiflush' => ['void'],
'ncurses_noraw' => ['bool'],
'ncurses_pair_content' => ['int', 'pair'=>'int', 'f'=>'int', 'b'=>'int'],
'ncurses_panel_above' => ['resource', 'panel'=>'resource'],
'ncurses_panel_below' => ['resource', 'panel'=>'resource'],
'ncurses_panel_window' => ['resource', 'panel'=>'resource'],
'ncurses_pnoutrefresh' => ['int', 'pad'=>'resource', 'pminrow'=>'int', 'pmincol'=>'int', 'sminrow'=>'int', 'smincol'=>'int', 'smaxrow'=>'int', 'smaxcol'=>'int'],
'ncurses_prefresh' => ['int', 'pad'=>'resource', 'pminrow'=>'int', 'pmincol'=>'int', 'sminrow'=>'int', 'smincol'=>'int', 'smaxrow'=>'int', 'smaxcol'=>'int'],
'ncurses_putp' => ['int', 'text'=>'string'],
'ncurses_qiflush' => ['void'],
'ncurses_raw' => ['bool'],
'ncurses_refresh' => ['int', 'ch'=>'int'],
'ncurses_replace_panel' => ['int', 'panel'=>'resource', 'window'=>'resource'],
'ncurses_reset_prog_mode' => ['int'],
'ncurses_reset_shell_mode' => ['int'],
'ncurses_resetty' => ['bool'],
'ncurses_savetty' => ['bool'],
'ncurses_scr_dump' => ['int', 'filename'=>'string'],
'ncurses_scr_init' => ['int', 'filename'=>'string'],
'ncurses_scr_restore' => ['int', 'filename'=>'string'],
'ncurses_scr_set' => ['int', 'filename'=>'string'],
'ncurses_scrl' => ['int', 'count'=>'int'],
'ncurses_show_panel' => ['int', 'panel'=>'resource'],
'ncurses_slk_attr' => ['int'],
'ncurses_slk_attroff' => ['int', 'intarg'=>'int'],
'ncurses_slk_attron' => ['int', 'intarg'=>'int'],
'ncurses_slk_attrset' => ['int', 'intarg'=>'int'],
'ncurses_slk_clear' => ['bool'],
'ncurses_slk_color' => ['int', 'intarg'=>'int'],
'ncurses_slk_init' => ['bool', 'format'=>'int'],
'ncurses_slk_noutrefresh' => ['bool'],
'ncurses_slk_refresh' => ['int'],
'ncurses_slk_restore' => ['int'],
'ncurses_slk_set' => ['bool', 'labelnr'=>'int', 'label'=>'string', 'format'=>'int'],
'ncurses_slk_touch' => ['int'],
'ncurses_standend' => ['int'],
'ncurses_standout' => ['int'],
'ncurses_start_color' => ['int'],
'ncurses_termattrs' => ['bool'],
'ncurses_termname' => ['string'],
'ncurses_timeout' => ['void', 'millisec'=>'int'],
'ncurses_top_panel' => ['int', 'panel'=>'resource'],
'ncurses_typeahead' => ['int', 'fd'=>'int'],
'ncurses_ungetch' => ['int', 'keycode'=>'int'],
'ncurses_ungetmouse' => ['bool', 'mevent'=>'array'],
'ncurses_update_panels' => ['void'],
'ncurses_use_default_colors' => ['bool'],
'ncurses_use_env' => ['void', 'flag'=>'bool'],
'ncurses_use_extended_names' => ['int', 'flag'=>'bool'],
'ncurses_vidattr' => ['int', 'intarg'=>'int'],
'ncurses_vline' => ['int', 'charattr'=>'int', 'n'=>'int'],
'ncurses_waddch' => ['int', 'window'=>'resource', 'ch'=>'int'],
'ncurses_waddstr' => ['int', 'window'=>'resource', 'string'=>'string', 'n='=>'int'],
'ncurses_wattroff' => ['int', 'window'=>'resource', 'attrs'=>'int'],
'ncurses_wattron' => ['int', 'window'=>'resource', 'attrs'=>'int'],
'ncurses_wattrset' => ['int', 'window'=>'resource', 'attrs'=>'int'],
'ncurses_wborder' => ['int', 'window'=>'resource', 'left'=>'int', 'right'=>'int', 'top'=>'int', 'bottom'=>'int', 'tl_corner'=>'int', 'tr_corner'=>'int', 'bl_corner'=>'int', 'br_corner'=>'int'],
'ncurses_wclear' => ['int', 'window'=>'resource'],
'ncurses_wcolor_set' => ['int', 'window'=>'resource', 'color_pair'=>'int'],
'ncurses_werase' => ['int', 'window'=>'resource'],
'ncurses_wgetch' => ['int', 'window'=>'resource'],
'ncurses_whline' => ['int', 'window'=>'resource', 'charattr'=>'int', 'n'=>'int'],
'ncurses_wmouse_trafo' => ['bool', 'window'=>'resource', 'y'=>'int', 'x'=>'int', 'toscreen'=>'bool'],
'ncurses_wmove' => ['int', 'window'=>'resource', 'y'=>'int', 'x'=>'int'],
'ncurses_wnoutrefresh' => ['int', 'window'=>'resource'],
'ncurses_wrefresh' => ['int', 'window'=>'resource'],
'ncurses_wstandend' => ['int', 'window'=>'resource'],
'ncurses_wstandout' => ['int', 'window'=>'resource'],
'ncurses_wvline' => ['int', 'window'=>'resource', 'charattr'=>'int', 'n'=>'int'],
'net_get_interfaces' => ['array<string,array<string,mixed>>|false'],
'newrelic_add_custom_parameter' => ['bool', 'key'=>'string', 'value'=>'bool|float|int|string'],
'newrelic_add_custom_tracer' => ['bool', 'function_name'=>'string'],
'newrelic_background_job' => ['void', 'flag='=>'bool'],
'newrelic_capture_params' => ['void', 'enable='=>'bool'],
'newrelic_custom_metric' => ['bool', 'metric_name'=>'string', 'value'=>'float'],
'newrelic_disable_autorum' => ['true'],
'newrelic_end_of_transaction' => ['void'],
'newrelic_end_transaction' => ['bool', 'ignore='=>'bool'],
'newrelic_get_browser_timing_footer' => ['string', 'include_tags='=>'bool'],
'newrelic_get_browser_timing_header' => ['string', 'include_tags='=>'bool'],
'newrelic_ignore_apdex' => ['void'],
'newrelic_ignore_transaction' => ['void'],
'newrelic_name_transaction' => ['bool', 'name'=>'string'],
'newrelic_notice_error' => ['void', 'message'=>'string', 'exception='=>'Exception|Throwable'],
'newrelic_notice_error\'1' => ['void', 'unused_1'=>'string', 'message'=>'string', 'unused_2'=>'string', 'unused_3'=>'int', 'unused_4='=>''],
'newrelic_record_custom_event' => ['void', 'name'=>'string', 'attributes'=>'array'],
'newrelic_record_datastore_segment' => ['mixed', 'func'=>'callable', 'parameters'=>'array'],
'newrelic_set_appname' => ['bool', 'name'=>'string', 'license='=>'string', 'xmit='=>'bool'],
'newrelic_set_user_attributes' => ['bool', 'user'=>'string', 'account'=>'string', 'product'=>'string'],
'newrelic_start_transaction' => ['bool', 'appname'=>'string', 'license='=>'string'],
'newt_bell' => ['void'],
'newt_button' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string'],
'newt_button_bar' => ['resource', 'buttons'=>'array'],
'newt_centered_window' => ['int', 'width'=>'int', 'height'=>'int', 'title='=>'string'],
'newt_checkbox' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string', 'def_value'=>'string', 'seq='=>'string'],
'newt_checkbox_get_value' => ['string', 'checkbox'=>'resource'],
'newt_checkbox_set_flags' => ['void', 'checkbox'=>'resource', 'flags'=>'int', 'sense'=>'int'],
'newt_checkbox_set_value' => ['void', 'checkbox'=>'resource', 'value'=>'string'],
'newt_checkbox_tree' => ['resource', 'left'=>'int', 'top'=>'int', 'height'=>'int', 'flags='=>'int'],
'newt_checkbox_tree_add_item' => ['void', 'checkboxtree'=>'resource', 'text'=>'string', 'data'=>'mixed', 'flags'=>'int', 'index'=>'int', '...args='=>'int'],
'newt_checkbox_tree_find_item' => ['array', 'checkboxtree'=>'resource', 'data'=>'mixed'],
'newt_checkbox_tree_get_current' => ['mixed', 'checkboxtree'=>'resource'],
'newt_checkbox_tree_get_entry_value' => ['string', 'checkboxtree'=>'resource', 'data'=>'mixed'],
'newt_checkbox_tree_get_multi_selection' => ['array', 'checkboxtree'=>'resource', 'seqnum'=>'string'],
'newt_checkbox_tree_get_selection' => ['array', 'checkboxtree'=>'resource'],
'newt_checkbox_tree_multi' => ['resource', 'left'=>'int', 'top'=>'int', 'height'=>'int', 'seq'=>'string', 'flags='=>'int'],
'newt_checkbox_tree_set_current' => ['void', 'checkboxtree'=>'resource', 'data'=>'mixed'],
'newt_checkbox_tree_set_entry' => ['void', 'checkboxtree'=>'resource', 'data'=>'mixed', 'text'=>'string'],
'newt_checkbox_tree_set_entry_value' => ['void', 'checkboxtree'=>'resource', 'data'=>'mixed', 'value'=>'string'],
'newt_checkbox_tree_set_width' => ['void', 'checkbox_tree'=>'resource', 'width'=>'int'],
'newt_clear_key_buffer' => ['void'],
'newt_cls' => ['void'],
'newt_compact_button' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string'],
'newt_component_add_callback' => ['void', 'component'=>'resource', 'func_name'=>'mixed', 'data'=>'mixed'],
'newt_component_takes_focus' => ['void', 'component'=>'resource', 'takes_focus'=>'bool'],
'newt_create_grid' => ['resource', 'cols'=>'int', 'rows'=>'int'],
'newt_cursor_off' => ['void'],
'newt_cursor_on' => ['void'],
'newt_delay' => ['void', 'microseconds'=>'int'],
'newt_draw_form' => ['void', 'form'=>'resource'],
'newt_draw_root_text' => ['void', 'left'=>'int', 'top'=>'int', 'text'=>'string'],
'newt_entry' => ['resource', 'left'=>'int', 'top'=>'int', 'width'=>'int', 'init_value='=>'string', 'flags='=>'int'],
'newt_entry_get_value' => ['string', 'entry'=>'resource'],
'newt_entry_set' => ['void', 'entry'=>'resource', 'value'=>'string', 'cursor_at_end='=>'bool'],
'newt_entry_set_filter' => ['void', 'entry'=>'resource', 'filter'=>'callable', 'data'=>'mixed'],
'newt_entry_set_flags' => ['void', 'entry'=>'resource', 'flags'=>'int', 'sense'=>'int'],
'newt_finished' => ['int'],
'newt_form' => ['resource', 'vert_bar='=>'resource', 'help='=>'string', 'flags='=>'int'],
'newt_form_add_component' => ['void', 'form'=>'resource', 'component'=>'resource'],
'newt_form_add_components' => ['void', 'form'=>'resource', 'components'=>'array'],
'newt_form_add_hot_key' => ['void', 'form'=>'resource', 'key'=>'int'],
'newt_form_destroy' => ['void', 'form'=>'resource'],
'newt_form_get_current' => ['resource', 'form'=>'resource'],
'newt_form_run' => ['void', 'form'=>'resource', 'exit_struct'=>'array'],
'newt_form_set_background' => ['void', 'from'=>'resource', 'background'=>'int'],
'newt_form_set_height' => ['void', 'form'=>'resource', 'height'=>'int'],
'newt_form_set_size' => ['void', 'form'=>'resource'],
'newt_form_set_timer' => ['void', 'form'=>'resource', 'milliseconds'=>'int'],
'newt_form_set_width' => ['void', 'form'=>'resource', 'width'=>'int'],
'newt_form_watch_fd' => ['void', 'form'=>'resource', 'stream'=>'resource', 'flags='=>'int'],
'newt_get_screen_size' => ['void', 'cols'=>'int', 'rows'=>'int'],
'newt_grid_add_components_to_form' => ['void', 'grid'=>'resource', 'form'=>'resource', 'recurse'=>'bool'],
'newt_grid_basic_window' => ['resource', 'text'=>'resource', 'middle'=>'resource', 'buttons'=>'resource'],
'newt_grid_free' => ['void', 'grid'=>'resource', 'recurse'=>'bool'],
'newt_grid_get_size' => ['void', 'grid'=>'resource', 'width'=>'int', 'height'=>'int'],
'newt_grid_h_close_stacked' => ['resource', 'element1_type'=>'int', 'element1'=>'resource', '...args='=>'resource'],
'newt_grid_h_stacked' => ['resource', 'element1_type'=>'int', 'element1'=>'resource', '...args='=>'resource'],
'newt_grid_place' => ['void', 'grid'=>'resource', 'left'=>'int', 'top'=>'int'],
'newt_grid_set_field' => ['void', 'grid'=>'resource', 'col'=>'int', 'row'=>'int', 'type'=>'int', 'value'=>'resource', 'pad_left'=>'int', 'pad_top'=>'int', 'pad_right'=>'int', 'pad_bottom'=>'int', 'anchor'=>'int', 'flags='=>'int'],
'newt_grid_simple_window' => ['resource', 'text'=>'resource', 'middle'=>'resource', 'buttons'=>'resource'],
'newt_grid_v_close_stacked' => ['resource', 'element1_type'=>'int', 'element1'=>'resource', '...args='=>'resource'],
'newt_grid_v_stacked' => ['resource', 'element1_type'=>'int', 'element1'=>'resource', '...args='=>'resource'],
'newt_grid_wrapped_window' => ['void', 'grid'=>'resource', 'title'=>'string'],
'newt_grid_wrapped_window_at' => ['void', 'grid'=>'resource', 'title'=>'string', 'left'=>'int', 'top'=>'int'],
'newt_init' => ['int'],
'newt_label' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string'],
'newt_label_set_text' => ['void', 'label'=>'resource', 'text'=>'string'],
'newt_listbox' => ['resource', 'left'=>'int', 'top'=>'int', 'height'=>'int', 'flags='=>'int'],
'newt_listbox_append_entry' => ['void', 'listbox'=>'resource', 'text'=>'string', 'data'=>'mixed'],
'newt_listbox_clear' => ['void', 'listobx'=>'resource'],
'newt_listbox_clear_selection' => ['void', 'listbox'=>'resource'],
'newt_listbox_delete_entry' => ['void', 'listbox'=>'resource', 'key'=>'mixed'],
'newt_listbox_get_current' => ['string', 'listbox'=>'resource'],
'newt_listbox_get_selection' => ['array', 'listbox'=>'resource'],
'newt_listbox_insert_entry' => ['void', 'listbox'=>'resource', 'text'=>'string', 'data'=>'mixed', 'key'=>'mixed'],
'newt_listbox_item_count' => ['int', 'listbox'=>'resource'],
'newt_listbox_select_item' => ['void', 'listbox'=>'resource', 'key'=>'mixed', 'sense'=>'int'],
'newt_listbox_set_current' => ['void', 'listbox'=>'resource', 'num'=>'int'],
'newt_listbox_set_current_by_key' => ['void', 'listbox'=>'resource', 'key'=>'mixed'],
'newt_listbox_set_data' => ['void', 'listbox'=>'resource', 'num'=>'int', 'data'=>'mixed'],
'newt_listbox_set_entry' => ['void', 'listbox'=>'resource', 'num'=>'int', 'text'=>'string'],
'newt_listbox_set_width' => ['void', 'listbox'=>'resource', 'width'=>'int'],
'newt_listitem' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string', 'is_default'=>'bool', 'prev_item'=>'resource', 'data'=>'mixed', 'flags='=>'int'],
'newt_listitem_get_data' => ['mixed', 'item'=>'resource'],
'newt_listitem_set' => ['void', 'item'=>'resource', 'text'=>'string'],
'newt_open_window' => ['int', 'left'=>'int', 'top'=>'int', 'width'=>'int', 'height'=>'int', 'title='=>'string'],
'newt_pop_help_line' => ['void'],
'newt_pop_window' => ['void'],
'newt_push_help_line' => ['void', 'text='=>'string'],
'newt_radio_get_current' => ['resource', 'set_member'=>'resource'],
'newt_radiobutton' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string', 'is_default'=>'bool', 'prev_button='=>'resource'],
'newt_redraw_help_line' => ['void'],
'newt_reflow_text' => ['string', 'text'=>'string', 'width'=>'int', 'flex_down'=>'int', 'flex_up'=>'int', 'actual_width'=>'int', 'actual_height'=>'int'],
'newt_refresh' => ['void'],
'newt_resize_screen' => ['void', 'redraw='=>'bool'],
'newt_resume' => ['void'],
'newt_run_form' => ['resource', 'form'=>'resource'],
'newt_scale' => ['resource', 'left'=>'int', 'top'=>'int', 'width'=>'int', 'full_value'=>'int'],
'newt_scale_set' => ['void', 'scale'=>'resource', 'amount'=>'int'],
'newt_scrollbar_set' => ['void', 'scrollbar'=>'resource', 'where'=>'int', 'total'=>'int'],
'newt_set_help_callback' => ['void', 'function'=>'mixed'],
'newt_set_suspend_callback' => ['void', 'function'=>'callable', 'data'=>'mixed'],
'newt_suspend' => ['void'],
'newt_textbox' => ['resource', 'left'=>'int', 'top'=>'int', 'width'=>'int', 'height'=>'int', 'flags='=>'int'],
'newt_textbox_get_num_lines' => ['int', 'textbox'=>'resource'],
'newt_textbox_reflowed' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'char', 'width'=>'int', 'flex_down'=>'int', 'flex_up'=>'int', 'flags='=>'int'],
'newt_textbox_set_height' => ['void', 'textbox'=>'resource', 'height'=>'int'],
'newt_textbox_set_text' => ['void', 'textbox'=>'resource', 'text'=>'string'],
'newt_vertical_scrollbar' => ['resource', 'left'=>'int', 'top'=>'int', 'height'=>'int', 'normal_colorset='=>'int', 'thumb_colorset='=>'int'],
'newt_wait_for_key' => ['void'],
'newt_win_choice' => ['int', 'title'=>'string', 'button1_text'=>'string', 'button2_text'=>'string', 'format'=>'string', 'args='=>'mixed', '...args='=>'mixed'],
'newt_win_entries' => ['int', 'title'=>'string', 'text'=>'string', 'suggested_width'=>'int', 'flex_down'=>'int', 'flex_up'=>'int', 'data_width'=>'int', 'items'=>'array', 'button1'=>'string', '...args='=>'string'],
'newt_win_menu' => ['int', 'title'=>'string', 'text'=>'string', 'suggestedwidth'=>'int', 'flexdown'=>'int', 'flexup'=>'int', 'maxlistheight'=>'int', 'items'=>'array', 'listitem'=>'int', 'button1='=>'string', '...args='=>'string'],
'newt_win_message' => ['void', 'title'=>'string', 'button_text'=>'string', 'format'=>'string', 'args='=>'mixed', '...args='=>'mixed'],
'newt_win_messagev' => ['void', 'title'=>'string', 'button_text'=>'string', 'format'=>'string', 'args'=>'array'],
'newt_win_ternary' => ['int', 'title'=>'string', 'button1_text'=>'string', 'button2_text'=>'string', 'button3_text'=>'string', 'format'=>'string', 'args='=>'mixed', '...args='=>'mixed'],
'next' => ['mixed', '&r_array'=>'array|object'],
'ngettext' => ['string', 'singular'=>'string', 'plural'=>'string', 'count'=>'int'],
'nl2br' => ['string', 'string'=>'string', 'use_xhtml='=>'bool'],
'nl_langinfo' => ['string|false', 'item'=>'int'],
'NoRewindIterator::__construct' => ['void', 'iterator'=>'Iterator'],
'NoRewindIterator::current' => ['mixed'],
'NoRewindIterator::getInnerIterator' => ['Iterator'],
'NoRewindIterator::key' => ['mixed'],
'NoRewindIterator::next' => ['void'],
'NoRewindIterator::rewind' => ['void'],
'NoRewindIterator::valid' => ['bool'],
'Normalizer::getRawDecomposition' => ['string|null', 'input'=>'string'],
'Normalizer::isNormalized' => ['bool', 'input'=>'string', 'form='=>'int'],
'Normalizer::normalize' => ['string', 'input'=>'string', 'form='=>'int'],
'normalizer_get_raw_decomposition' => ['string|null', 'string'=>'string'],
'normalizer_is_normalized' => ['bool', 'string'=>'string', 'form='=>'int'],
'normalizer_normalize' => ['string', 'string'=>'string', 'form='=>'int'],
'notes_body' => ['array', 'server'=>'string', 'mailbox'=>'string', 'msg_number'=>'int'],
'notes_copy_db' => ['bool', 'from_database_name'=>'string', 'to_database_name'=>'string'],
'notes_create_db' => ['bool', 'database_name'=>'string'],
'notes_create_note' => ['bool', 'database_name'=>'string', 'form_name'=>'string'],
'notes_drop_db' => ['bool', 'database_name'=>'string'],
'notes_find_note' => ['int', 'database_name'=>'string', 'name'=>'string', 'type='=>'string'],
'notes_header_info' => ['object', 'server'=>'string', 'mailbox'=>'string', 'msg_number'=>'int'],
'notes_list_msgs' => ['bool', 'db'=>'string'],
'notes_mark_read' => ['bool', 'database_name'=>'string', 'user_name'=>'string', 'note_id'=>'string'],
'notes_mark_unread' => ['bool', 'database_name'=>'string', 'user_name'=>'string', 'note_id'=>'string'],
'notes_nav_create' => ['bool', 'database_name'=>'string', 'name'=>'string'],
'notes_search' => ['array', 'database_name'=>'string', 'keywords'=>'string'],
'notes_unread' => ['array', 'database_name'=>'string', 'user_name'=>'string'],
'notes_version' => ['float', 'database_name'=>'string'],
'nsapi_request_headers' => ['array'],
'nsapi_response_headers' => ['array'],
'nsapi_virtual' => ['bool', 'uri'=>'string'],
'nthmac' => ['string', 'clent'=>'string', 'data'=>'string'],
'number_format' => ['string', 'num'=>'float|int', 'decimals='=>'int'],
'number_format\'1' => ['string', 'num'=>'float|int', 'decimals'=>'int', 'decimal_separator'=>'string', 'thousands_separator'=>'string'],
'NumberFormatter::__construct' => ['void', 'locale'=>'string', 'style'=>'int', 'pattern='=>'string'],
'NumberFormatter::create' => ['NumberFormatter|false', 'locale'=>'string', 'style'=>'int', 'pattern='=>'string'],
'NumberFormatter::format' => ['string|false', 'num'=>'', 'type='=>'int'],
'NumberFormatter::formatCurrency' => ['string', 'num'=>'float', 'currency'=>'string'],
'NumberFormatter::getAttribute' => ['int|false', 'attr'=>'int'],
'NumberFormatter::getErrorCode' => ['int'],
'NumberFormatter::getErrorMessage' => ['string'],
'NumberFormatter::getLocale' => ['string', 'type='=>'int'],
'NumberFormatter::getPattern' => ['string|false'],
'NumberFormatter::getSymbol' => ['string|false', 'attr'=>'int'],
'NumberFormatter::getTextAttribute' => ['string|false', 'attr'=>'int'],
'NumberFormatter::parse' => ['float|false', 'string'=>'string', 'type='=>'int', '&rw_position='=>'int'],
'NumberFormatter::parseCurrency' => ['float|false', 'string'=>'string', '&w_currency'=>'string', '&rw_position='=>'int'],
'NumberFormatter::setAttribute' => ['bool', 'attr'=>'int', 'value'=>''],
'NumberFormatter::setPattern' => ['bool', 'pattern'=>'string'],
'NumberFormatter::setSymbol' => ['bool', 'attr'=>'int', 'symbol'=>'string'],
'NumberFormatter::setTextAttribute' => ['bool', 'attr'=>'int', 'value'=>'string'],
'numfmt_create' => ['NumberFormatter|false', 'locale'=>'string', 'style'=>'int', 'pattern='=>'string'],
'numfmt_format' => ['string|false', 'formatter'=>'NumberFormatter', 'num'=>'int|float', 'type='=>'int'],
'numfmt_format_currency' => ['string|false', 'formatter'=>'NumberFormatter', 'amount'=>'float', 'currency'=>'string'],
'numfmt_get_attribute' => ['int|false', 'formatter'=>'NumberFormatter', 'attribute'=>'int'],
'numfmt_get_error_code' => ['int', 'formatter'=>'NumberFormatter'],
'numfmt_get_error_message' => ['string', 'formatter'=>'NumberFormatter'],
'numfmt_get_locale' => ['string', 'formatter'=>'NumberFormatter', 'type='=>'int'],
'numfmt_get_pattern' => ['string|false', 'formatter'=>'NumberFormatter'],
'numfmt_get_symbol' => ['string|false', 'formatter'=>'NumberFormatter', 'symbol'=>'int'],
'numfmt_get_text_attribute' => ['string|false', 'formatter'=>'NumberFormatter', 'attribute'=>'int'],
'numfmt_parse' => ['float|int|false', 'formatter'=>'NumberFormatter', 'string'=>'string', 'type='=>'int', '&rw_offset='=>'int'],
'numfmt_parse_currency' => ['float|false', 'formatter'=>'NumberFormatter', 'string'=>'string', '&w_currency'=>'string', '&rw_offset='=>'int'],
'numfmt_set_attribute' => ['bool', 'formatter'=>'NumberFormatter', 'attribute'=>'int', 'value'=>'int'],
'numfmt_set_pattern' => ['bool', 'formatter'=>'NumberFormatter', 'pattern'=>'string'],
'numfmt_set_symbol' => ['bool', 'formatter'=>'NumberFormatter', 'symbol'=>'int', 'value'=>'string'],
'numfmt_set_text_attribute' => ['bool', 'formatter'=>'NumberFormatter', 'attribute'=>'int', 'value'=>'string'],
'OAuth::__construct' => ['void', 'consumer_key'=>'string', 'consumer_secret'=>'string', 'signature_method='=>'string', 'auth_type='=>'int'],
'OAuth::__destruct' => ['void'],
'OAuth::disableDebug' => ['bool'],
'OAuth::disableRedirects' => ['bool'],
'OAuth::disableSSLChecks' => ['bool'],
'OAuth::enableDebug' => ['bool'],
'OAuth::enableRedirects' => ['bool'],
'OAuth::enableSSLChecks' => ['bool'],
'OAuth::fetch' => ['mixed', 'protected_resource_url'=>'string', 'extra_parameters='=>'array', 'http_method='=>'string', 'http_headers='=>'array'],
'OAuth::generateSignature' => ['string', 'http_method'=>'string', 'url'=>'string', 'extra_parameters='=>'mixed'],
'OAuth::getAccessToken' => ['array|false', 'access_token_url'=>'string', 'auth_session_handle='=>'string', 'verifier_token='=>'string', 'http_method='=>'string'],
'OAuth::getCAPath' => ['array'],
'OAuth::getLastResponse' => ['string'],
'OAuth::getLastResponseHeaders' => ['string|false'],
'OAuth::getLastResponseInfo' => ['array'],
'OAuth::getRequestHeader' => ['string|false', 'http_method'=>'string', 'url'=>'string', 'extra_parameters='=>'mixed'],
'OAuth::getRequestToken' => ['array|false', 'request_token_url'=>'string', 'callback_url='=>'string', 'http_method='=>'string'],
'OAuth::setAuthType' => ['bool', 'auth_type'=>'int'],
'OAuth::setCAPath' => ['mixed', 'ca_path='=>'string', 'ca_info='=>'string'],
'OAuth::setNonce' => ['mixed', 'nonce'=>'string'],
'OAuth::setRequestEngine' => ['void', 'reqengine'=>'int'],
'OAuth::setRSACertificate' => ['mixed', 'cert'=>'string'],
'OAuth::setSSLChecks' => ['bool', 'sslcheck'=>'int'],
'OAuth::setTimeout' => ['void', 'timeout'=>'int'],
'OAuth::setTimestamp' => ['mixed', 'timestamp'=>'string'],
'OAuth::setToken' => ['bool', 'token'=>'string', 'token_secret'=>'string'],
'OAuth::setVersion' => ['bool', 'version'=>'string'],
'oauth_get_sbs' => ['string', 'http_method'=>'string', 'uri'=>'string', 'request_parameters='=>'array'],
'oauth_urlencode' => ['string', 'uri'=>'string'],
'OAuthProvider::__construct' => ['void', 'params_array='=>'array'],
'OAuthProvider::addRequiredParameter' => ['bool', 'req_params'=>'string'],
'OAuthProvider::callconsumerHandler' => ['void'],
'OAuthProvider::callTimestampNonceHandler' => ['void'],
'OAuthProvider::calltokenHandler' => ['void'],
'OAuthProvider::checkOAuthRequest' => ['void', 'uri='=>'string', 'method='=>'string'],
'OAuthProvider::consumerHandler' => ['void', 'callback_function'=>'callable'],
'OAuthProvider::generateToken' => ['string', 'size'=>'int', 'strong='=>'bool'],
'OAuthProvider::is2LeggedEndpoint' => ['void', 'params_array'=>'mixed'],
'OAuthProvider::isRequestTokenEndpoint' => ['void', 'will_issue_request_token'=>'bool'],
'OAuthProvider::removeRequiredParameter' => ['bool', 'req_params'=>'string'],
'OAuthProvider::reportProblem' => ['string', 'oauthexception'=>'string', 'send_headers='=>'bool'],
'OAuthProvider::setParam' => ['bool', 'param_key'=>'string', 'param_val='=>'mixed'],
'OAuthProvider::setRequestTokenPath' => ['bool', 'path'=>'string'],
'OAuthProvider::timestampNonceHandler' => ['void', 'callback_function'=>'callable'],
'OAuthProvider::tokenHandler' => ['void', 'callback_function'=>'callable'],
'ob_clean' => ['bool'],
'ob_deflatehandler' => ['string', 'data'=>'string', 'mode'=>'int'],
'ob_end_clean' => ['bool'],
'ob_end_flush' => ['bool'],
'ob_etaghandler' => ['string', 'data'=>'string', 'mode'=>'int'],
'ob_flush' => ['bool'],
'ob_get_clean' => ['string|false'],
'ob_get_contents' => ['string|false'],
'ob_get_flush' => ['string|false'],
'ob_get_length' => ['int|false'],
'ob_get_level' => ['int'],
'ob_get_status' => ['array', 'full_status='=>'bool'],
'ob_gzhandler' => ['string|false', 'data'=>'string', 'flags'=>'int'],
'ob_iconv_handler' => ['string', 'contents'=>'string', 'status'=>'int'],
'ob_implicit_flush' => ['void', 'enable='=>'int'],
'ob_inflatehandler' => ['string', 'data'=>'string', 'mode'=>'int'],
'ob_list_handlers' => ['false|list<string>'],
'ob_start' => ['bool', 'callback='=>'string|array|?callable', 'chunk_size='=>'int', 'flags='=>'int'],
'ob_tidyhandler' => ['string', 'input'=>'string', 'mode='=>'int'],
'oci_bind_array_by_name' => ['bool', 'statement'=>'resource', 'param'=>'string', '&rw_var'=>'array', 'max_array_length'=>'int', 'max_item_length='=>'int', 'type='=>'int'],
'oci_bind_by_name' => ['bool', 'statement'=>'resource', 'param'=>'string', '&rw_var'=>'mixed', 'max_length='=>'int', 'type='=>'int'],
'oci_cancel' => ['bool', 'statement'=>'resource'],
'oci_client_version' => ['string'],
'oci_close' => ['bool', 'connection'=>'resource'],
'OCICollection::append' => ['bool', 'value'=>'mixed'],
'OCICollection::assign' => ['bool', 'from'=>'OCI_Collection'],
'OCICollection::assignElem' => ['bool', 'index'=>'int', 'value'=>'mixed'],
'OCICollection::free' => ['bool'],
'OCICollection::getElem' => ['mixed', 'index'=>'int'],
'OCICollection::max' => ['int|false'],
'OCICollection::size' => ['int|false'],
'OCICollection::trim' => ['bool', 'num'=>'int'],
'oci_collection_append' => ['bool', 'collection'=>'string'],
'oci_collection_assign' => ['bool', 'to'=>'object'],
'oci_collection_element_assign' => ['bool', 'collection'=>'int', 'index'=>'string'],
'oci_collection_element_get' => ['string', 'collection'=>'int'],
'oci_collection_max' => ['int'],
'oci_collection_size' => ['int'],
'oci_collection_trim' => ['bool', 'collection'=>'int'],
'oci_commit' => ['bool', 'connection'=>'resource'],
'oci_connect' => ['resource|false', 'username'=>'string', 'password'=>'string', 'connection_string='=>'string', 'encoding='=>'string', 'session_mode='=>'int'],
'oci_define_by_name' => ['bool', 'statement'=>'resource', 'column'=>'string', '&w_var'=>'mixed', 'type='=>'int'],
'oci_error' => ['array|false', 'connection_or_statement='=>'resource'],
'oci_execute' => ['bool', 'statement'=>'resource', 'mode='=>'int'],
'oci_fetch' => ['bool', 'statement'=>'resource'],
'oci_fetch_all' => ['int|false', 'statement'=>'resource', '&w_output'=>'array', 'offset='=>'int', 'limit='=>'int', 'flags='=>'int'],
'oci_fetch_array' => ['array|false', 'statement'=>'resource', 'mode='=>'int'],
'oci_fetch_assoc' => ['array|false', 'statement'=>'resource'],
'oci_fetch_object' => ['object|false', 'statement'=>'resource'],
'oci_fetch_row' => ['array|false', 'statement'=>'resource'],
'oci_field_is_null' => ['bool', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_name' => ['string|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_precision' => ['int|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_scale' => ['int|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_size' => ['int|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_type' => ['mixed|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_field_type_raw' => ['int|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_free_collection' => ['bool'],
'oci_free_cursor' => ['bool', 'statement'=>'resource'],
'oci_free_descriptor' => ['bool'],
'oci_free_statement' => ['bool', 'statement'=>'resource'],
'oci_get_implicit' => ['bool', 'stmt'=>''],
'oci_get_implicit_resultset' => ['resource|false', 'statement'=>'resource'],
'oci_internal_debug' => ['void', 'onoff'=>'bool'],
'OCILob::append' => ['bool', 'lob_from'=>'OCILob'],
'OCILob::close' => ['bool'],
'OCILob::eof' => ['bool'],
'OCILob::erase' => ['int|false', 'offset='=>'int', 'length='=>'int'],
'OCILob::export' => ['bool', 'filename'=>'string', 'start='=>'int', 'length='=>'int'],
'OCILob::flush' => ['bool', 'flag='=>'int'],
'OCILob::free' => ['bool'],
'OCILob::getbuffering' => ['bool'],
'OCILob::import' => ['bool', 'filename'=>'string'],
'OCILob::load' => ['string|false'],
'OCILob::read' => ['string|false', 'length'=>'int'],
'OCILob::rewind' => ['bool'],
'OCILob::save' => ['bool', 'data'=>'string', 'offset='=>'int'],
'OCILob::savefile' => ['bool', 'filename'=>''],
'OCILob::seek' => ['bool', 'offset'=>'int', 'whence='=>'int'],
'OCILob::setbuffering' => ['bool', 'on_off'=>'bool'],
'OCILob::size' => ['int|false'],
'OCILob::tell' => ['int|false'],
'OCILob::truncate' => ['bool', 'length='=>'int'],
'OCILob::write' => ['int|false', 'data'=>'string', 'length='=>'int'],
'OCILob::writeTemporary' => ['bool', 'data'=>'string', 'lob_type='=>'int'],
'OCILob::writetofile' => ['bool', 'filename'=>'', 'start'=>'', 'length'=>''],
'oci_lob_append' => ['bool', 'to'=>'object'],
'oci_lob_close' => ['bool'],
'oci_lob_copy' => ['bool', 'to'=>'OCILob', 'from'=>'OCILob', 'length='=>'int'],
'oci_lob_eof' => ['bool'],
'oci_lob_erase' => ['int', 'lob'=>'int', 'offset'=>'int'],
'oci_lob_export' => ['bool', 'lob'=>'string', 'filename'=>'int', 'offset'=>'int'],
'oci_lob_flush' => ['bool', 'lob'=>'int'],
'oci_lob_import' => ['bool', 'lob'=>'string'],
'oci_lob_is_equal' => ['bool', 'lob1'=>'OCILob', 'lob2'=>'OCILob'],
'oci_lob_load' => ['string'],
'oci_lob_read' => ['string', 'lob'=>'int'],
'oci_lob_rewind' => ['bool'],
'oci_lob_save' => ['bool', 'lob'=>'string', 'data'=>'int'],
'oci_lob_seek' => ['bool', 'lob'=>'int', 'offset'=>'int'],
'oci_lob_size' => ['int'],
'oci_lob_tell' => ['int'],
'oci_lob_truncate' => ['bool', 'lob'=>'int'],
'oci_lob_write' => ['int', 'lob'=>'string', 'data'=>'int'],
'oci_lob_write_temporary' => ['bool', 'value'=>'string', 'lob_type'=>'int'],
'oci_new_collection' => ['OCICollection|false', 'connection'=>'resource', 'type_name'=>'string', 'schema='=>'string'],
'oci_new_connect' => ['resource|false', 'username'=>'string', 'password'=>'string', 'connection_string='=>'string', 'encoding='=>'string', 'session_mode='=>'int'],
'oci_new_cursor' => ['resource|false', 'connection'=>'resource'],
'oci_new_descriptor' => ['OCILob|false', 'connection'=>'resource', 'type='=>'int'],
'oci_num_fields' => ['int|false', 'statement'=>'resource'],
'oci_num_rows' => ['int|false', 'statement'=>'resource'],
'oci_parse' => ['resource|false', 'connection'=>'resource', 'sql'=>'string'],
'oci_password_change' => ['bool', 'connection'=>'resource', 'username'=>'string', 'old_password'=>'string', 'new_password'=>'string'],
'oci_pconnect' => ['resource|false', 'username'=>'string', 'password'=>'string', 'connection_string='=>'string', 'encoding='=>'string', 'session_mode='=>'int'],
'oci_register_taf_callback' => ['bool', 'connection'=>'resource', 'callback='=>'callable'],
'oci_result' => ['mixed|false', 'statement'=>'resource', 'column'=>'mixed'],
'oci_rollback' => ['bool', 'connection'=>'resource'],
'oci_server_version' => ['string|false', 'connection'=>'resource'],
'oci_set_action' => ['bool', 'connection'=>'resource', 'action'=>'string'],
'oci_set_call_timeout' => ['bool', 'connection'=>'resource', 'timeout'=>'int'],
'oci_set_client_identifier' => ['bool', 'connection'=>'resource', 'client_id'=>'string'],
'oci_set_client_info' => ['bool', 'connection'=>'resource', 'client_info'=>'string'],
'oci_set_db_operation' => ['bool', 'connection'=>'resource', 'action'=>'string'],
'oci_set_edition' => ['bool', 'edition'=>'string'],
'oci_set_module_name' => ['bool', 'connection'=>'resource', 'name'=>'string'],
'oci_set_prefetch' => ['bool', 'statement'=>'resource', 'rows'=>'int'],
'oci_statement_type' => ['string|false', 'statement'=>'resource'],
'oci_unregister_taf_callback' => ['bool', 'connection'=>'resource'],
'ocifetchinto' => ['int|bool', 'statement'=>'resource', '&w_result'=>'array', 'mode='=>'int'],
'ocigetbufferinglob' => ['bool'],
'ocisetbufferinglob' => ['bool', 'lob'=>'bool'],
'octdec' => ['int|float', 'octal_string'=>'string'],
'odbc_autocommit' => ['mixed', 'odbc'=>'resource', 'enable='=>'bool'],
'odbc_binmode' => ['bool', 'statement'=>'resource', 'mode'=>'int'],
'odbc_close' => ['void', 'odbc'=>'resource'],
'odbc_close_all' => ['void'],
'odbc_columnprivileges' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'table'=>'string', 'column'=>'string'],
'odbc_columns' => ['resource|false', 'odbc'=>'resource', 'catalog='=>'string', 'schema='=>'string', 'table='=>'string', 'column='=>'string'],
'odbc_commit' => ['bool', 'odbc'=>'resource'],
'odbc_connect' => ['resource|false', 'dsn'=>'string', 'user'=>'string', 'password'=>'string', 'cursor_option='=>'int'],
'odbc_cursor' => ['string', 'statement'=>'resource'],
'odbc_data_source' => ['array|false', 'odbc'=>'resource', 'fetch_type'=>'int'],
'odbc_do' => ['resource', 'odbc'=>'resource', 'query'=>'string', 'flags='=>'int'],
'odbc_error' => ['string', 'odbc='=>'resource'],
'odbc_errormsg' => ['string', 'odbc='=>'resource'],
'odbc_exec' => ['resource', 'odbc'=>'resource', 'query'=>'string', 'flags='=>'int'],
'odbc_execute' => ['bool', 'statement'=>'resource', 'params='=>'array'],
'odbc_fetch_array' => ['array|false', 'statement'=>'resource', 'row='=>'int'],
'odbc_fetch_into' => ['int', 'statement'=>'resource', '&w_array'=>'array', 'row='=>'int'],
'odbc_fetch_object' => ['object|false', 'statement'=>'resource', 'row='=>'int'],
'odbc_fetch_row' => ['bool', 'statement'=>'resource', 'row='=>'int'],
'odbc_field_len' => ['int|false', 'statement'=>'resource', 'field'=>'int'],
'odbc_field_name' => ['string|false', 'statement'=>'resource', 'field'=>'int'],
'odbc_field_num' => ['int|false', 'statement'=>'resource', 'field'=>'string'],
'odbc_field_precision' => ['int', 'statement'=>'resource', 'field'=>'int'],
'odbc_field_scale' => ['int|false', 'statement'=>'resource', 'field'=>'int'],
'odbc_field_type' => ['string|false', 'statement'=>'resource', 'field'=>'int'],
'odbc_foreignkeys' => ['resource|false', 'odbc'=>'resource', 'pk_catalog'=>'string', 'pk_schema'=>'string', 'pk_table'=>'string', 'fk_catalog'=>'string', 'fk_schema'=>'string', 'fk_table'=>'string'],
'odbc_free_result' => ['bool', 'statement'=>'resource'],
'odbc_gettypeinfo' => ['resource', 'odbc'=>'resource', 'data_type='=>'int'],
'odbc_longreadlen' => ['bool', 'statement'=>'resource', 'length'=>'int'],
'odbc_next_result' => ['bool', 'statement'=>'resource'],
'odbc_num_fields' => ['int', 'statement'=>'resource'],
'odbc_num_rows' => ['int', 'statement'=>'resource'],
'odbc_pconnect' => ['resource|false', 'dsn'=>'string', 'user'=>'string', 'password'=>'string', 'cursor_option='=>'int'],
'odbc_prepare' => ['resource|false', 'odbc'=>'resource', 'query'=>'string'],
'odbc_primarykeys' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'table'=>'string'],
'odbc_procedurecolumns' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'procedure'=>'string', 'column'=>'string'],
'odbc_procedures' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'procedure'=>'string'],
'odbc_result' => ['mixed|false', 'statement'=>'resource', 'field'=>'mixed'],
'odbc_result_all' => ['int|false', 'statement'=>'resource', 'format='=>'string'],
'odbc_rollback' => ['bool', 'odbc'=>'resource'],
'odbc_setoption' => ['bool', 'odbc'=>'resource', 'which'=>'int', 'option'=>'int', 'value'=>'int'],
'odbc_specialcolumns' => ['resource|false', 'odbc'=>'resource', 'type'=>'int', 'catalog'=>'string', 'schema'=>'string', 'table'=>'string', 'scope'=>'int', 'nullable'=>'int'],
'odbc_statistics' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'table'=>'string', 'unique'=>'int', 'accuracy'=>'int'],
'odbc_tableprivileges' => ['resource|false', 'odbc'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'table'=>'string'],
'odbc_tables' => ['resource|false', 'odbc'=>'resource', 'catalog='=>'string', 'schema='=>'string', 'table='=>'string', 'types='=>'string'],
'opcache_compile_file' => ['bool', 'filename'=>'string'],
'opcache_get_configuration' => ['array'],
'opcache_get_status' => ['array|false', 'include_scripts='=>'bool'],
'opcache_invalidate' => ['bool', 'filename'=>'string', 'force='=>'bool'],
'opcache_is_script_cached' => ['bool', 'filename'=>'string'],
'opcache_reset' => ['bool'],
'openal_buffer_create' => ['resource'],
'openal_buffer_data' => ['bool', 'buffer'=>'resource', 'format'=>'int', 'data'=>'string', 'freq'=>'int'],
'openal_buffer_destroy' => ['bool', 'buffer'=>'resource'],
'openal_buffer_get' => ['int', 'buffer'=>'resource', 'property'=>'int'],
'openal_buffer_loadwav' => ['bool', 'buffer'=>'resource', 'wavfile'=>'string'],
'openal_context_create' => ['resource', 'device'=>'resource'],
'openal_context_current' => ['bool', 'context'=>'resource'],
'openal_context_destroy' => ['bool', 'context'=>'resource'],
'openal_context_process' => ['bool', 'context'=>'resource'],
'openal_context_suspend' => ['bool', 'context'=>'resource'],
'openal_device_close' => ['bool', 'device'=>'resource'],
'openal_device_open' => ['resource|false', 'device_desc='=>'string'],
'openal_listener_get' => ['mixed', 'property'=>'int'],
'openal_listener_set' => ['bool', 'property'=>'int', 'setting'=>'mixed'],
'openal_source_create' => ['resource'],
'openal_source_destroy' => ['bool', 'source'=>'resource'],
'openal_source_get' => ['mixed', 'source'=>'resource', 'property'=>'int'],
'openal_source_pause' => ['bool', 'source'=>'resource'],
'openal_source_play' => ['bool', 'source'=>'resource'],
'openal_source_rewind' => ['bool', 'source'=>'resource'],
'openal_source_set' => ['bool', 'source'=>'resource', 'property'=>'int', 'setting'=>'mixed'],
'openal_source_stop' => ['bool', 'source'=>'resource'],
'openal_stream' => ['resource', 'source'=>'resource', 'format'=>'int', 'rate'=>'int'],
'opendir' => ['resource|false', 'directory'=>'string', 'context='=>'resource'],
'openlog' => ['bool', 'prefix'=>'string', 'flags'=>'int', 'facility'=>'int'],
'openssl_cipher_iv_length' => ['int|false', 'cipher_algo'=>'string'],
'openssl_csr_export' => ['bool', 'csr'=>'string|resource', '&w_output'=>'string', 'no_text='=>'bool'],
'openssl_csr_export_to_file' => ['bool', 'csr'=>'string|resource', 'output_filename'=>'string', 'no_text='=>'bool'],
'openssl_csr_get_public_key' => ['resource|false', 'csr'=>'string|resource', 'short_names='=>'bool'],
'openssl_csr_get_subject' => ['array|false', 'csr'=>'string|resource', 'short_names='=>'bool'],
'openssl_csr_new' => ['resource|false', 'distinguished_names'=>'array', '&w_private_key'=>'resource', 'options='=>'array', 'extra_attributes='=>'array'],
'openssl_csr_sign' => ['resource|false', 'csr'=>'string|resource', 'ca_certificate'=>'string|resource|null', 'private_key'=>'string|resource|array', 'days'=>'int', 'options='=>'array', 'serial='=>'int'],
'openssl_decrypt' => ['string|false', 'data'=>'string', 'cipher_algo'=>'string', 'passphrase'=>'string', 'options='=>'int', 'iv='=>'string', 'tag='=>'string', 'aad='=>'string'],
'openssl_dh_compute_key' => ['string|false', 'public_key'=>'string', 'private_key'=>'resource'],
'openssl_digest' => ['string|false', 'data'=>'string', 'digest_algo'=>'string', 'binary='=>'bool'],
'openssl_encrypt' => ['string|false', 'data'=>'string', 'cipher_algo'=>'string', 'passphrase'=>'string', 'options='=>'int', 'iv='=>'string', '&w_tag='=>'string', 'aad='=>'string', 'tag_length='=>'int'],
'openssl_error_string' => ['string|false'],
'openssl_free_key' => ['void', 'key'=>'resource'],
'openssl_get_cert_locations' => ['array'],
'openssl_get_cipher_methods' => ['array', 'aliases='=>'bool'],
'openssl_get_curve_names' => ['list<string>'],
'openssl_get_md_methods' => ['array', 'aliases='=>'bool'],
'openssl_get_privatekey' => ['resource|false', 'private_key'=>'string', 'passphrase='=>'string'],
'openssl_get_publickey' => ['resource|false', 'public_key'=>'resource|string'],
'openssl_open' => ['bool', 'data'=>'string', '&w_output'=>'string', 'encrypted_key'=>'string', 'private_key'=>'string|array|resource', 'cipher_algo='=>'string', 'iv='=>'string'],
'openssl_pbkdf2' => ['string|false', 'password'=>'string', 'salt'=>'string', 'key_length'=>'int', 'iterations'=>'int', 'digest_algo='=>'string'],
'openssl_pkcs12_export' => ['bool', 'certificate'=>'string|resource', '&w_output'=>'string', 'private_key'=>'string|array|resource', 'passphrase'=>'string', 'options='=>'array'],
'openssl_pkcs12_export_to_file' => ['bool', 'certificate'=>'string|resource', 'output_filename'=>'string', 'private_key'=>'string|array|resource', 'passphrase'=>'string', 'options='=>'array'],
'openssl_pkcs12_read' => ['bool', 'pkcs12'=>'string', '&w_certificates'=>'array', 'passphrase'=>'string'],
'openssl_pkcs7_decrypt' => ['bool', 'input_filename'=>'string', 'output_filename'=>'string', 'certificate'=>'string|resource', 'private_key='=>'string|resource|array'],
'openssl_pkcs7_encrypt' => ['bool', 'input_filename'=>'string', 'output_filename'=>'string', 'certificate'=>'string|resource|array', 'headers'=>'array', 'flags='=>'int', 'cipher_algo='=>'int'],
'openssl_pkcs7_read' => ['bool', 'input_filename'=>'string', '&w_certificates'=>'array'],
'openssl_pkcs7_sign' => ['bool', 'input_filename'=>'string', 'output_filename'=>'string', 'certificate'=>'string|resource', 'private_key'=>'string|resource|array', 'headers'=>'array', 'flags='=>'int', 'untrusted_certificates_filename='=>'string'],
'openssl_pkcs7_verify' => ['bool|int', 'input_filename'=>'string', 'flags'=>'int', 'signers_certificates_filename='=>'string', 'ca_info='=>'array', 'untrusted_certificates_filename='=>'string', 'content='=>'string', 'output_filename='=>'string'],
'openssl_pkey_derive' => ['string|false', 'public_key'=>'mixed', 'private_key'=>'mixed', 'key_length='=>'?int'],
'openssl_pkey_export' => ['bool', 'key'=>'resource', '&w_output'=>'string', 'passphrase='=>'string|null', 'options='=>'array'],
'openssl_pkey_export_to_file' => ['bool', 'key'=>'resource|string|array', 'output_filename'=>'string', 'passphrase='=>'string|null', 'options='=>'array'],
'openssl_pkey_free' => ['void', 'key'=>'resource'],
'openssl_pkey_get_details' => ['array|false', 'key'=>'resource'],
'openssl_pkey_get_private' => ['OpenSSLAsymmetricKey|false', 'private_key'=>'OpenSSLAsymmetricKey|OpenSSLCertificate|array|string', 'passphrase='=>'?string'],
'openssl_pkey_get_public' => ['resource|false', 'public_key'=>'resource|string'],
'openssl_pkey_new' => ['resource|false', 'options='=>'array'],
'openssl_private_decrypt' => ['bool', 'data'=>'string', '&w_decrypted_data'=>'string', 'private_key'=>'string|resource|array', 'padding='=>'int'],
'openssl_private_encrypt' => ['bool', 'data'=>'string', '&w_encrypted_data'=>'string', 'private_key'=>'string|resource|array', 'padding='=>'int'],
'openssl_public_decrypt' => ['bool', 'data'=>'string', '&w_decrypted_data'=>'string', 'public_key'=>'string|resource', 'padding='=>'int'],
'openssl_public_encrypt' => ['bool', 'data'=>'string', '&w_encrypted_data'=>'string', 'public_key'=>'string|resource', 'padding='=>'int'],
'openssl_random_pseudo_bytes' => ['string|false', 'length'=>'int', '&w_strong_result='=>'bool'],
'openssl_seal' => ['int|false', 'data'=>'string', '&w_sealed_data'=>'string', '&w_encrypted_keys'=>'array', 'public_key'=>'array', 'cipher_algo='=>'string', '&rw_iv='=>'string'],
'openssl_sign' => ['bool', 'data'=>'string', '&w_signature'=>'string', 'private_key'=>'OpenSSLAsymmetricKey|OpenSSLCertificate|array{OpenSSLAsymmetricKey|OpenSSLCertificate|string, string}|string', 'algorithm='=>'int|string'],
'openssl_spki_export' => ['?string', 'spki'=>'string'],
'openssl_spki_export_challenge' => ['?string', 'spki'=>'string'],
'openssl_spki_new' => ['?string', 'private_key'=>'resource', 'challenge'=>'string', 'digest_algo='=>'int'],
'openssl_spki_verify' => ['bool', 'spki'=>'string'],
'openssl_verify' => ['-1|0|1', 'data'=>'string', 'signature'=>'string', 'public_key'=>'resource|string', 'algorithm='=>'int|string'],
'openssl_x509_check_private_key' => ['bool', 'certificate'=>'string|resource', 'private_key'=>'string|resource|array'],
'openssl_x509_checkpurpose' => ['bool|int', 'certificate'=>'string|resource', 'purpose'=>'int', 'ca_info='=>'array', 'untrusted_certificates_file='=>'string'],
'openssl_x509_export' => ['bool', 'certificate'=>'string|resource', '&w_output'=>'string', 'no_text='=>'bool'],
'openssl_x509_export_to_file' => ['bool', 'certificate'=>'string|resource', 'output_filename'=>'string', 'no_text='=>'bool'],
'openssl_x509_fingerprint' => ['string|false', 'certificate'=>'string|resource', 'digest_algo='=>'string', 'binary='=>'bool'],
'openssl_x509_free' => ['void', 'certificate'=>'resource'],
'openssl_x509_parse' => ['array|false', 'certificate'=>'OpenSSLCertificate|string', 'short_names='=>'bool'],
'openssl_x509_read' => ['OpenSSLCertificate|false', 'certificate'=>'OpenSSLCertificate|string'],
'ord' => ['int', 'character'=>'string'],
'OuterIterator::current' => ['mixed'],
'OuterIterator::getInnerIterator' => ['Iterator'],
'OuterIterator::key' => ['int|string'],
'OuterIterator::next' => ['void'],
'OuterIterator::rewind' => ['void'],
'OuterIterator::valid' => ['bool'],
'OutOfBoundsException::__clone' => ['void'],
'OutOfBoundsException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?OutOfBoundsException'],
'OutOfBoundsException::__toString' => ['string'],
'OutOfBoundsException::getCode' => ['int'],
'OutOfBoundsException::getFile' => ['string'],
'OutOfBoundsException::getLine' => ['int'],
'OutOfBoundsException::getMessage' => ['string'],
'OutOfBoundsException::getPrevious' => ['Throwable|OutOfBoundsException|null'],
'OutOfBoundsException::getTrace' => ['list<array<string,mixed>>'],
'OutOfBoundsException::getTraceAsString' => ['string'],
'OutOfRangeException::__clone' => ['void'],
'OutOfRangeException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?OutOfRangeException'],
'OutOfRangeException::__toString' => ['string'],
'OutOfRangeException::getCode' => ['int'],
'OutOfRangeException::getFile' => ['string'],
'OutOfRangeException::getLine' => ['int'],
'OutOfRangeException::getMessage' => ['string'],
'OutOfRangeException::getPrevious' => ['Throwable|OutOfRangeException|null'],
'OutOfRangeException::getTrace' => ['list<array<string,mixed>>'],
'OutOfRangeException::getTraceAsString' => ['string'],
'output_add_rewrite_var' => ['bool', 'name'=>'string', 'value'=>'string'],
'output_cache_disable' => ['void'],
'output_cache_disable_compression' => ['void'],
'output_cache_exists' => ['bool', 'key'=>'string', 'lifetime'=>'int'],
'output_cache_fetch' => ['string', 'key'=>'string', 'function'=>'', 'lifetime'=>'int'],
'output_cache_get' => ['mixed|false', 'key'=>'string', 'lifetime'=>'int'],
'output_cache_output' => ['string', 'key'=>'string', 'function'=>'', 'lifetime'=>'int'],
'output_cache_put' => ['bool', 'key'=>'string', 'data'=>'mixed'],
'output_cache_remove' => ['bool', 'filename'=>''],
'output_cache_remove_key' => ['bool', 'key'=>'string'],
'output_cache_remove_url' => ['bool', 'url'=>'string'],
'output_cache_stop' => ['void'],
'output_reset_rewrite_vars' => ['bool'],
'outputformatObj::getOption' => ['string', 'property_name'=>'string'],
'outputformatObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'outputformatObj::setOption' => ['void', 'property_name'=>'string', 'new_value'=>'string'],
'outputformatObj::validate' => ['int'],
'OverflowException::__clone' => ['void'],
'OverflowException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?OverflowException'],
'OverflowException::__toString' => ['string'],
'OverflowException::getCode' => ['int'],
'OverflowException::getFile' => ['string'],
'OverflowException::getLine' => ['int'],
'OverflowException::getMessage' => ['string'],
'OverflowException::getPrevious' => ['Throwable|OverflowException|null'],
'OverflowException::getTrace' => ['list<array<string,mixed>>'],
'OverflowException::getTraceAsString' => ['string'],
'overload' => ['', 'class_name'=>'string'],
'override_function' => ['bool', 'function_name'=>'string', 'function_args'=>'string', 'function_code'=>'string'],
'OwsrequestObj::__construct' => ['void'],
'OwsrequestObj::addParameter' => ['int', 'name'=>'string', 'value'=>'string'],
'OwsrequestObj::getName' => ['string', 'index'=>'int'],
'OwsrequestObj::getValue' => ['string', 'index'=>'int'],
'OwsrequestObj::getValueByName' => ['string', 'name'=>'string'],
'OwsrequestObj::loadParams' => ['int'],
'OwsrequestObj::setParameter' => ['int', 'name'=>'string', 'value'=>'string'],
'pack' => ['string|false', 'format'=>'string', '...values='=>'mixed'],
'parallel\Future::done' => ['bool'],
'parallel\Future::select' => ['mixed', '&resolving'=>'parallel\Future[]', '&w_resolved'=>'parallel\Future[]', '&w_errored'=>'parallel\Future[]', '&w_timedout='=>'parallel\Future[]', 'timeout='=>'int'],
'parallel\Future::value' => ['mixed', 'timeout='=>'int'],
'parallel\Runtime::__construct' => ['void', 'arg'=>'string|array'],
'parallel\Runtime::__construct\'1' => ['void', 'bootstrap'=>'string', 'configuration'=>'array<string,mixed>'],
'parallel\Runtime::close' => ['void'],
'parallel\Runtime::kill' => ['void'],
'parallel\Runtime::run' => ['?parallel\Future', 'closure'=>'Closure', 'args='=>'array'],
'ParentIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator'],
'ParentIterator::accept' => ['bool'],
'ParentIterator::getChildren' => ['ParentIterator'],
'ParentIterator::hasChildren' => ['bool'],
'ParentIterator::next' => ['void'],
'ParentIterator::rewind' => ['void'],
'ParentIterator::valid' => [''],
'Parle\Lexer::advance' => ['void'],
'Parle\Lexer::build' => ['void'],
'Parle\Lexer::callout' => ['void', 'id'=>'int', 'callback'=>'callable'],
'Parle\Lexer::consume' => ['void', 'data'=>'string'],
'Parle\Lexer::dump' => ['void'],
'Parle\Lexer::getToken' => ['Parle\Token'],
'Parle\Lexer::insertMacro' => ['void', 'name'=>'string', 'regex'=>'string'],
'Parle\Lexer::push' => ['void', 'regex'=>'string', 'id'=>'int'],
'Parle\Lexer::reset' => ['void', 'pos'=>'int'],
'Parle\Parser::advance' => ['void'],
'Parle\Parser::build' => ['void'],
'Parle\Parser::consume' => ['void', 'data'=>'string', 'lexer'=>'Parle\Lexer'],
'Parle\Parser::dump' => ['void'],
'Parle\Parser::errorInfo' => ['Parle\ErrorInfo'],
'Parle\Parser::left' => ['void', 'token'=>'string'],
'Parle\Parser::nonassoc' => ['void', 'token'=>'string'],
'Parle\Parser::precedence' => ['void', 'token'=>'string'],
'Parle\Parser::push' => ['int', 'name'=>'string', 'rule'=>'string'],
'Parle\Parser::reset' => ['void', 'tokenId'=>'int'],
'Parle\Parser::right' => ['void', 'token'=>'string'],
'Parle\Parser::sigil' => ['string', 'idx'=>'array'],
'Parle\Parser::token' => ['void', 'token'=>'string'],
'Parle\Parser::tokenId' => ['int', 'token'=>'string'],
'Parle\Parser::trace' => ['string'],
'Parle\Parser::validate' => ['bool', 'data'=>'string', 'lexer'=>'Parle\Lexer'],
'Parle\RLexer::advance' => ['void'],
'Parle\RLexer::build' => ['void'],
'Parle\RLexer::callout' => ['void', 'id'=>'int', 'callback'=>'callable'],
'Parle\RLexer::consume' => ['void', 'data'=>'string'],
'Parle\RLexer::dump' => ['void'],
'Parle\RLexer::getToken' => ['Parle\Token'],
'parle\rlexer::insertMacro' => ['void', 'name'=>'string', 'regex'=>'string'],
'Parle\RLexer::push' => ['void', 'state'=>'string', 'regex'=>'string', 'newState'=>'string'],
'Parle\RLexer::pushState' => ['int', 'state'=>'string'],
'Parle\RLexer::reset' => ['void', 'pos'=>'int'],
'Parle\RParser::advance' => ['void'],
'Parle\RParser::build' => ['void'],
'Parle\RParser::consume' => ['void', 'data'=>'string', 'lexer'=>'Parle\Lexer'],
'Parle\RParser::dump' => ['void'],
'Parle\RParser::errorInfo' => ['Parle\ErrorInfo'],
'Parle\RParser::left' => ['void', 'token'=>'string'],
'Parle\RParser::nonassoc' => ['void', 'token'=>'string'],
'Parle\RParser::precedence' => ['void', 'token'=>'string'],
'Parle\RParser::push' => ['int', 'name'=>'string', 'rule'=>'string'],
'Parle\RParser::reset' => ['void', 'tokenId'=>'int'],
'Parle\RParser::right' => ['void', 'token'=>'string'],
'Parle\RParser::sigil' => ['string', 'idx'=>'array'],
'Parle\RParser::token' => ['void', 'token'=>'string'],
'Parle\RParser::tokenId' => ['int', 'token'=>'string'],
'Parle\RParser::trace' => ['string'],
'Parle\RParser::validate' => ['bool', 'data'=>'string', 'lexer'=>'Parle\Lexer'],
'Parle\Stack::pop' => ['void'],
'Parle\Stack::push' => ['void', 'item'=>'mixed'],
'parse_ini_file' => ['array|false', 'filename'=>'string', 'process_sections='=>'bool', 'scanner_mode='=>'int'],
'parse_ini_string' => ['array|false', 'ini_string'=>'string', 'process_sections='=>'bool', 'scanner_mode='=>'int'],
'parse_str' => ['void', 'string'=>'string', '&w_result'=>'array'],
'parse_url' => ['mixed|false', 'url'=>'string', 'component='=>'int'],
'ParseError::__clone' => ['void'],
'ParseError::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?ParseError'],
'ParseError::__toString' => ['string'],
'ParseError::getCode' => ['int'],
'ParseError::getFile' => ['string'],
'ParseError::getLine' => ['int'],
'ParseError::getMessage' => ['string'],
'ParseError::getPrevious' => ['Throwable|ParseError|null'],
'ParseError::getTrace' => ['list<array<string,mixed>>'],
'ParseError::getTraceAsString' => ['string'],
'parsekit_compile_file' => ['array', 'filename'=>'string', 'errors='=>'array', 'options='=>'int'],
'parsekit_compile_string' => ['array', 'phpcode'=>'string', 'errors='=>'array', 'options='=>'int'],
'parsekit_func_arginfo' => ['array', 'function'=>'mixed'],
'passthru' => ['void', 'command'=>'string', '&w_result_code='=>'int'],
'password_get_info' => ['array', 'hash'=>'string'],
'password_hash' => ['string', 'password'=>'string', 'algo'=>'int|string|null', 'options='=>'array'],
'password_make_salt' => ['bool', 'password'=>'string', 'hash'=>'string'],
'password_needs_rehash' => ['bool', 'hash'=>'string', 'algo'=>'int|string|null', 'options='=>'array'],
'password_verify' => ['bool', 'password'=>'string', 'hash'=>'string'],
'pathinfo' => ['array|string', 'path'=>'string', 'flags='=>'int'],
'pclose' => ['int', 'handle'=>'resource'],
'pcnlt_sigwaitinfo' => ['int', 'set'=>'array', '&w_siginfo'=>'array'],
'pcntl_alarm' => ['int', 'seconds'=>'int'],
'pcntl_async_signals' => ['bool', 'enable='=>'bool'],
'pcntl_errno' => ['int'],
'pcntl_exec' => ['null|false', 'path'=>'string', 'args='=>'array', 'env_vars='=>'array'],
'pcntl_fork' => ['int'],
'pcntl_get_last_error' => ['int'],
'pcntl_getpriority' => ['int', 'process_id='=>'int', 'mode='=>'int'],
'pcntl_setpriority' => ['bool', 'priority'=>'int', 'process_id='=>'int', 'mode='=>'int'],
'pcntl_signal' => ['bool', 'signal'=>'int', 'handler'=>'callable():void|callable(int):void|callable(int,array):void|int', 'restart_syscalls='=>'bool'],
'pcntl_signal_dispatch' => ['bool'],
'pcntl_signal_get_handler' => ['int|string', 'signal'=>'int'],
'pcntl_sigprocmask' => ['bool', 'mode'=>'int', 'signals'=>'array', '&w_old_signals='=>'array'],
'pcntl_sigtimedwait' => ['int', 'signals'=>'array', '&w_info='=>'array', 'seconds='=>'int', 'nanoseconds='=>'int'],
'pcntl_sigwaitinfo' => ['int', 'signals'=>'array', '&w_info='=>'array'],
'pcntl_strerror' => ['string|false', 'error_code'=>'int'],
'pcntl_wait' => ['int', '&w_status'=>'int', 'flags='=>'int', '&w_resource_usage='=>'array'],
'pcntl_waitpid' => ['int', 'process_id'=>'int', '&w_status'=>'int', 'flags='=>'int', '&w_resource_usage='=>'array'],
'pcntl_wexitstatus' => ['int', 'status'=>'int'],
'pcntl_wifcontinued' => ['bool', 'status'=>'int'],
'pcntl_wifexited' => ['bool', 'status'=>'int'],
'pcntl_wifsignaled' => ['bool', 'status'=>'int'],
'pcntl_wifstopped' => ['bool', 'status'=>'int'],
'pcntl_wstopsig' => ['int', 'status'=>'int'],
'pcntl_wtermsig' => ['int', 'status'=>'int'],
'PDF_activate_item' => ['bool', 'pdfdoc'=>'resource', 'id'=>'int'],
'PDF_add_launchlink' => ['bool', 'pdfdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string'],
'PDF_add_locallink' => ['bool', 'pdfdoc'=>'resource', 'lowerleftx'=>'float', 'lowerlefty'=>'float', 'upperrightx'=>'float', 'upperrighty'=>'float', 'page'=>'int', 'dest'=>'string'],
'PDF_add_nameddest' => ['bool', 'pdfdoc'=>'resource', 'name'=>'string', 'optlist'=>'string'],
'PDF_add_note' => ['bool', 'pdfdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'contents'=>'string', 'title'=>'string', 'icon'=>'string', 'open'=>'int'],
'PDF_add_pdflink' => ['bool', 'pdfdoc'=>'resource', 'bottom_left_x'=>'float', 'bottom_left_y'=>'float', 'up_right_x'=>'float', 'up_right_y'=>'float', 'filename'=>'string', 'page'=>'int', 'dest'=>'string'],
'PDF_add_table_cell' => ['int', 'pdfdoc'=>'resource', 'table'=>'int', 'column'=>'int', 'row'=>'int', 'text'=>'string', 'optlist'=>'string'],
'PDF_add_textflow' => ['int', 'pdfdoc'=>'resource', 'textflow'=>'int', 'text'=>'string', 'optlist'=>'string'],
'PDF_add_thumbnail' => ['bool', 'pdfdoc'=>'resource', 'image'=>'int'],
'PDF_add_weblink' => ['bool', 'pdfdoc'=>'resource', 'lowerleftx'=>'float', 'lowerlefty'=>'float', 'upperrightx'=>'float', 'upperrighty'=>'float', 'url'=>'string'],
'PDF_arc' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float', 'r'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'PDF_arcn' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float', 'r'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'PDF_attach_file' => ['bool', 'pdfdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string', 'description'=>'string', 'author'=>'string', 'mimetype'=>'string', 'icon'=>'string'],
'PDF_begin_document' => ['int', 'pdfdoc'=>'resource', 'filename'=>'string', 'optlist'=>'string'],
'PDF_begin_font' => ['bool', 'pdfdoc'=>'resource', 'filename'=>'string', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float', 'optlist'=>'string'],
'PDF_begin_glyph' => ['bool', 'pdfdoc'=>'resource', 'glyphname'=>'string', 'wx'=>'float', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float'],
'PDF_begin_item' => ['int', 'pdfdoc'=>'resource', 'tag'=>'string', 'optlist'=>'string'],
'PDF_begin_layer' => ['bool', 'pdfdoc'=>'resource', 'layer'=>'int'],
'PDF_begin_page' => ['bool', 'pdfdoc'=>'resource', 'width'=>'float', 'height'=>'float'],
'PDF_begin_page_ext' => ['bool', 'pdfdoc'=>'resource', 'width'=>'float', 'height'=>'float', 'optlist'=>'string'],
'PDF_begin_pattern' => ['int', 'pdfdoc'=>'resource', 'width'=>'float', 'height'=>'float', 'xstep'=>'float', 'ystep'=>'float', 'painttype'=>'int'],
'PDF_begin_template' => ['int', 'pdfdoc'=>'resource', 'width'=>'float', 'height'=>'float'],
'PDF_begin_template_ext' => ['int', 'pdfdoc'=>'resource', 'width'=>'float', 'height'=>'float', 'optlist'=>'string'],
'PDF_circle' => ['bool', 'pdfdoc'=>'resource', 'x'=>'float', 'y'=>'float', 'r'=>'float'],
'PDF_clip' => ['bool', 'p'=>'resource'],
'PDF_close' => ['bool', 'p'=>'resource'],
'PDF_close_image' => ['bool', 'p'=>'resource', 'image'=>'int'],
'PDF_close_pdi' => ['bool', 'p'=>'resource', 'doc'=>'int'],
'PDF_close_pdi_page' => ['bool', 'p'=>'resource', 'page'=>'int'],
'PDF_closepath' => ['bool', 'p'=>'resource'],
'PDF_closepath_fill_stroke' => ['bool', 'p'=>'resource'],
'PDF_closepath_stroke' => ['bool', 'p'=>'resource'],
'PDF_concat' => ['bool', 'p'=>'resource', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float'],
'PDF_continue_text' => ['bool', 'p'=>'resource', 'text'=>'string'],
'PDF_create_3dview' => ['int', 'pdfdoc'=>'resource', 'username'=>'string', 'optlist'=>'string'],
'PDF_create_action' => ['int', 'pdfdoc'=>'resource', 'type'=>'string', 'optlist'=>'string'],
'PDF_create_annotation' => ['bool', 'pdfdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'type'=>'string', 'optlist'=>'string'],
'PDF_create_bookmark' => ['int', 'pdfdoc'=>'resource', 'text'=>'string', 'optlist'=>'string'],
'PDF_create_field' => ['bool', 'pdfdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'name'=>'string', 'type'=>'string', 'optlist'=>'string'],
'PDF_create_fieldgroup' => ['bool', 'pdfdoc'=>'resource', 'name'=>'string', 'optlist'=>'string'],
'PDF_create_gstate' => ['int', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_create_pvf' => ['bool', 'pdfdoc'=>'resource', 'filename'=>'string', 'data'=>'string', 'optlist'=>'string'],
'PDF_create_textflow' => ['int', 'pdfdoc'=>'resource', 'text'=>'string', 'optlist'=>'string'],
'PDF_curveto' => ['bool', 'p'=>'resource', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'PDF_define_layer' => ['int', 'pdfdoc'=>'resource', 'name'=>'string', 'optlist'=>'string'],
'PDF_delete' => ['bool', 'pdfdoc'=>'resource'],
'PDF_delete_pvf' => ['int', 'pdfdoc'=>'resource', 'filename'=>'string'],
'PDF_delete_table' => ['bool', 'pdfdoc'=>'resource', 'table'=>'int', 'optlist'=>'string'],
'PDF_delete_textflow' => ['bool', 'pdfdoc'=>'resource', 'textflow'=>'int'],
'PDF_encoding_set_char' => ['bool', 'pdfdoc'=>'resource', 'encoding'=>'string', 'slot'=>'int', 'glyphname'=>'string', 'uv'=>'int'],
'PDF_end_document' => ['bool', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_end_font' => ['bool', 'pdfdoc'=>'resource'],
'PDF_end_glyph' => ['bool', 'pdfdoc'=>'resource'],
'PDF_end_item' => ['bool', 'pdfdoc'=>'resource', 'id'=>'int'],
'PDF_end_layer' => ['bool', 'pdfdoc'=>'resource'],
'PDF_end_page' => ['bool', 'p'=>'resource'],
'PDF_end_page_ext' => ['bool', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_end_pattern' => ['bool', 'p'=>'resource'],
'PDF_end_template' => ['bool', 'p'=>'resource'],
'PDF_endpath' => ['bool', 'p'=>'resource'],
'PDF_fill' => ['bool', 'p'=>'resource'],
'PDF_fill_imageblock' => ['int', 'pdfdoc'=>'resource', 'page'=>'int', 'blockname'=>'string', 'image'=>'int', 'optlist'=>'string'],
'PDF_fill_pdfblock' => ['int', 'pdfdoc'=>'resource', 'page'=>'int', 'blockname'=>'string', 'contents'=>'int', 'optlist'=>'string'],
'PDF_fill_stroke' => ['bool', 'p'=>'resource'],
'PDF_fill_textblock' => ['int', 'pdfdoc'=>'resource', 'page'=>'int', 'blockname'=>'string', 'text'=>'string', 'optlist'=>'string'],
'PDF_findfont' => ['int', 'p'=>'resource', 'fontname'=>'string', 'encoding'=>'string', 'embed'=>'int'],
'PDF_fit_image' => ['bool', 'pdfdoc'=>'resource', 'image'=>'int', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDF_fit_pdi_page' => ['bool', 'pdfdoc'=>'resource', 'page'=>'int', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDF_fit_table' => ['string', 'pdfdoc'=>'resource', 'table'=>'int', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'optlist'=>'string'],
'PDF_fit_textflow' => ['string', 'pdfdoc'=>'resource', 'textflow'=>'int', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'optlist'=>'string'],
'PDF_fit_textline' => ['bool', 'pdfdoc'=>'resource', 'text'=>'string', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDF_get_apiname' => ['string', 'pdfdoc'=>'resource'],
'PDF_get_buffer' => ['string', 'p'=>'resource'],
'PDF_get_errmsg' => ['string', 'pdfdoc'=>'resource'],
'PDF_get_errnum' => ['int', 'pdfdoc'=>'resource'],
'PDF_get_majorversion' => ['int'],
'PDF_get_minorversion' => ['int'],
'PDF_get_parameter' => ['string', 'p'=>'resource', 'key'=>'string', 'modifier'=>'float'],
'PDF_get_pdi_parameter' => ['string', 'p'=>'resource', 'key'=>'string', 'doc'=>'int', 'page'=>'int', 'reserved'=>'int'],
'PDF_get_pdi_value' => ['float', 'p'=>'resource', 'key'=>'string', 'doc'=>'int', 'page'=>'int', 'reserved'=>'int'],
'PDF_get_value' => ['float', 'p'=>'resource', 'key'=>'string', 'modifier'=>'float'],
'PDF_info_font' => ['float', 'pdfdoc'=>'resource', 'font'=>'int', 'keyword'=>'string', 'optlist'=>'string'],
'PDF_info_matchbox' => ['float', 'pdfdoc'=>'resource', 'boxname'=>'string', 'num'=>'int', 'keyword'=>'string'],
'PDF_info_table' => ['float', 'pdfdoc'=>'resource', 'table'=>'int', 'keyword'=>'string'],
'PDF_info_textflow' => ['float', 'pdfdoc'=>'resource', 'textflow'=>'int', 'keyword'=>'string'],
'PDF_info_textline' => ['float', 'pdfdoc'=>'resource', 'text'=>'string', 'keyword'=>'string', 'optlist'=>'string'],
'PDF_initgraphics' => ['bool', 'p'=>'resource'],
'PDF_lineto' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float'],
'PDF_load_3ddata' => ['int', 'pdfdoc'=>'resource', 'filename'=>'string', 'optlist'=>'string'],
'PDF_load_font' => ['int', 'pdfdoc'=>'resource', 'fontname'=>'string', 'encoding'=>'string', 'optlist'=>'string'],
'PDF_load_iccprofile' => ['int', 'pdfdoc'=>'resource', 'profilename'=>'string', 'optlist'=>'string'],
'PDF_load_image' => ['int', 'pdfdoc'=>'resource', 'imagetype'=>'string', 'filename'=>'string', 'optlist'=>'string'],
'PDF_makespotcolor' => ['int', 'p'=>'resource', 'spotname'=>'string'],
'PDF_moveto' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float'],
'PDF_new' => ['resource'],
'PDF_open_ccitt' => ['int', 'pdfdoc'=>'resource', 'filename'=>'string', 'width'=>'int', 'height'=>'int', 'bitreverse'=>'int', 'k'=>'int', 'blackls1'=>'int'],
'PDF_open_file' => ['bool', 'p'=>'resource', 'filename'=>'string'],
'PDF_open_image' => ['int', 'p'=>'resource', 'imagetype'=>'string', 'source'=>'string', 'data'=>'string', 'length'=>'int', 'width'=>'int', 'height'=>'int', 'components'=>'int', 'bpc'=>'int', 'params'=>'string'],
'PDF_open_image_file' => ['int', 'p'=>'resource', 'imagetype'=>'string', 'filename'=>'string', 'stringparam'=>'string', 'intparam'=>'int'],
'PDF_open_memory_image' => ['int', 'p'=>'resource', 'image'=>'resource'],
'PDF_open_pdi' => ['int', 'pdfdoc'=>'resource', 'filename'=>'string', 'optlist'=>'string', 'length'=>'int'],
'PDF_open_pdi_document' => ['int', 'p'=>'resource', 'filename'=>'string', 'optlist'=>'string'],
'PDF_open_pdi_page' => ['int', 'p'=>'resource', 'doc'=>'int', 'pagenumber'=>'int', 'optlist'=>'string'],
'PDF_pcos_get_number' => ['float', 'p'=>'resource', 'doc'=>'int', 'path'=>'string'],
'PDF_pcos_get_stream' => ['string', 'p'=>'resource', 'doc'=>'int', 'optlist'=>'string', 'path'=>'string'],
'PDF_pcos_get_string' => ['string', 'p'=>'resource', 'doc'=>'int', 'path'=>'string'],
'PDF_place_image' => ['bool', 'pdfdoc'=>'resource', 'image'=>'int', 'x'=>'float', 'y'=>'float', 'scale'=>'float'],
'PDF_place_pdi_page' => ['bool', 'pdfdoc'=>'resource', 'page'=>'int', 'x'=>'float', 'y'=>'float', 'sx'=>'float', 'sy'=>'float'],
'PDF_process_pdi' => ['int', 'pdfdoc'=>'resource', 'doc'=>'int', 'page'=>'int', 'optlist'=>'string'],
'PDF_rect' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'PDF_restore' => ['bool', 'p'=>'resource'],
'PDF_resume_page' => ['bool', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_rotate' => ['bool', 'p'=>'resource', 'phi'=>'float'],
'PDF_save' => ['bool', 'p'=>'resource'],
'PDF_scale' => ['bool', 'p'=>'resource', 'sx'=>'float', 'sy'=>'float'],
'PDF_set_border_color' => ['bool', 'p'=>'resource', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDF_set_border_dash' => ['bool', 'pdfdoc'=>'resource', 'black'=>'float', 'white'=>'float'],
'PDF_set_border_style' => ['bool', 'pdfdoc'=>'resource', 'style'=>'string', 'width'=>'float'],
'PDF_set_gstate' => ['bool', 'pdfdoc'=>'resource', 'gstate'=>'int'],
'PDF_set_info' => ['bool', 'p'=>'resource', 'key'=>'string', 'value'=>'string'],
'PDF_set_layer_dependency' => ['bool', 'pdfdoc'=>'resource', 'type'=>'string', 'optlist'=>'string'],
'PDF_set_parameter' => ['bool', 'p'=>'resource', 'key'=>'string', 'value'=>'string'],
'PDF_set_text_pos' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float'],
'PDF_set_value' => ['bool', 'p'=>'resource', 'key'=>'string', 'value'=>'float'],
'PDF_setcolor' => ['bool', 'p'=>'resource', 'fstype'=>'string', 'colorspace'=>'string', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float'],
'PDF_setdash' => ['bool', 'pdfdoc'=>'resource', 'b'=>'float', 'w'=>'float'],
'PDF_setdashpattern' => ['bool', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_setflat' => ['bool', 'pdfdoc'=>'resource', 'flatness'=>'float'],
'PDF_setfont' => ['bool', 'pdfdoc'=>'resource', 'font'=>'int', 'fontsize'=>'float'],
'PDF_setgray' => ['bool', 'p'=>'resource', 'g'=>'float'],
'PDF_setgray_fill' => ['bool', 'p'=>'resource', 'g'=>'float'],
'PDF_setgray_stroke' => ['bool', 'p'=>'resource', 'g'=>'float'],
'PDF_setlinecap' => ['bool', 'p'=>'resource', 'linecap'=>'int'],
'PDF_setlinejoin' => ['bool', 'p'=>'resource', 'value'=>'int'],
'PDF_setlinewidth' => ['bool', 'p'=>'resource', 'width'=>'float'],
'PDF_setmatrix' => ['bool', 'p'=>'resource', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float'],
'PDF_setmiterlimit' => ['bool', 'pdfdoc'=>'resource', 'miter'=>'float'],
'PDF_setrgbcolor' => ['bool', 'p'=>'resource', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDF_setrgbcolor_fill' => ['bool', 'p'=>'resource', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDF_setrgbcolor_stroke' => ['bool', 'p'=>'resource', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDF_shading' => ['int', 'pdfdoc'=>'resource', 'shtype'=>'string', 'x0'=>'float', 'y0'=>'float', 'x1'=>'float', 'y1'=>'float', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float', 'optlist'=>'string'],
'PDF_shading_pattern' => ['int', 'pdfdoc'=>'resource', 'shading'=>'int', 'optlist'=>'string'],
'PDF_shfill' => ['bool', 'pdfdoc'=>'resource', 'shading'=>'int'],
'PDF_show' => ['bool', 'pdfdoc'=>'resource', 'text'=>'string'],
'PDF_show_boxed' => ['int', 'p'=>'resource', 'text'=>'string', 'left'=>'float', 'top'=>'float', 'width'=>'float', 'height'=>'float', 'mode'=>'string', 'feature'=>'string'],
'PDF_show_xy' => ['bool', 'p'=>'resource', 'text'=>'string', 'x'=>'float', 'y'=>'float'],
'PDF_skew' => ['bool', 'p'=>'resource', 'alpha'=>'float', 'beta'=>'float'],
'PDF_stringwidth' => ['float', 'p'=>'resource', 'text'=>'string', 'font'=>'int', 'fontsize'=>'float'],
'PDF_stroke' => ['bool', 'p'=>'resource'],
'PDF_suspend_page' => ['bool', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_translate' => ['bool', 'p'=>'resource', 'tx'=>'float', 'ty'=>'float'],
'PDF_utf16_to_utf8' => ['string', 'pdfdoc'=>'resource', 'utf16string'=>'string'],
'PDF_utf32_to_utf16' => ['string', 'pdfdoc'=>'resource', 'utf32string'=>'string', 'ordering'=>'string'],
'PDF_utf8_to_utf16' => ['string', 'pdfdoc'=>'resource', 'utf8string'=>'string', 'ordering'=>'string'],
'PDFlib::activate_item' => ['bool', 'id'=>''],
'PDFlib::add_launchlink' => ['bool', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string'],
'PDFlib::add_locallink' => ['bool', 'lowerleftx'=>'float', 'lowerlefty'=>'float', 'upperrightx'=>'float', 'upperrighty'=>'float', 'page'=>'int', 'dest'=>'string'],
'PDFlib::add_nameddest' => ['bool', 'name'=>'string', 'optlist'=>'string'],
'PDFlib::add_note' => ['bool', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'contents'=>'string', 'title'=>'string', 'icon'=>'string', 'open'=>'int'],
'PDFlib::add_pdflink' => ['bool', 'bottom_left_x'=>'float', 'bottom_left_y'=>'float', 'up_right_x'=>'float', 'up_right_y'=>'float', 'filename'=>'string', 'page'=>'int', 'dest'=>'string'],
'PDFlib::add_table_cell' => ['int', 'table'=>'int', 'column'=>'int', 'row'=>'int', 'text'=>'string', 'optlist'=>'string'],
'PDFlib::add_textflow' => ['int', 'textflow'=>'int', 'text'=>'string', 'optlist'=>'string'],
'PDFlib::add_thumbnail' => ['bool', 'image'=>'int'],
'PDFlib::add_weblink' => ['bool', 'lowerleftx'=>'float', 'lowerlefty'=>'float', 'upperrightx'=>'float', 'upperrighty'=>'float', 'url'=>'string'],
'PDFlib::arc' => ['bool', 'x'=>'float', 'y'=>'float', 'r'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'PDFlib::arcn' => ['bool', 'x'=>'float', 'y'=>'float', 'r'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'PDFlib::attach_file' => ['bool', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string', 'description'=>'string', 'author'=>'string', 'mimetype'=>'string', 'icon'=>'string'],
'PDFlib::begin_document' => ['int', 'filename'=>'string', 'optlist'=>'string'],
'PDFlib::begin_font' => ['bool', 'filename'=>'string', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float', 'optlist'=>'string'],
'PDFlib::begin_glyph' => ['bool', 'glyphname'=>'string', 'wx'=>'float', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float'],
'PDFlib::begin_item' => ['int', 'tag'=>'string', 'optlist'=>'string'],
'PDFlib::begin_layer' => ['bool', 'layer'=>'int'],
'PDFlib::begin_page' => ['bool', 'width'=>'float', 'height'=>'float'],
'PDFlib::begin_page_ext' => ['bool', 'width'=>'float', 'height'=>'float', 'optlist'=>'string'],
'PDFlib::begin_pattern' => ['int', 'width'=>'float', 'height'=>'float', 'xstep'=>'float', 'ystep'=>'float', 'painttype'=>'int'],
'PDFlib::begin_template' => ['int', 'width'=>'float', 'height'=>'float'],
'PDFlib::begin_template_ext' => ['int', 'width'=>'float', 'height'=>'float', 'optlist'=>'string'],
'PDFlib::circle' => ['bool', 'x'=>'float', 'y'=>'float', 'r'=>'float'],
'PDFlib::clip' => ['bool'],
'PDFlib::close' => ['bool'],
'PDFlib::close_image' => ['bool', 'image'=>'int'],
'PDFlib::close_pdi' => ['bool', 'doc'=>'int'],
'PDFlib::close_pdi_page' => ['bool', 'page'=>'int'],
'PDFlib::closepath' => ['bool'],
'PDFlib::closepath_fill_stroke' => ['bool'],
'PDFlib::closepath_stroke' => ['bool'],
'PDFlib::concat' => ['bool', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float'],
'PDFlib::continue_text' => ['bool', 'text'=>'string'],
'PDFlib::create_3dview' => ['int', 'username'=>'string', 'optlist'=>'string'],
'PDFlib::create_action' => ['int', 'type'=>'string', 'optlist'=>'string'],
'PDFlib::create_annotation' => ['bool', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'type'=>'string', 'optlist'=>'string'],
'PDFlib::create_bookmark' => ['int', 'text'=>'string', 'optlist'=>'string'],
'PDFlib::create_field' => ['bool', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'name'=>'string', 'type'=>'string', 'optlist'=>'string'],
'PDFlib::create_fieldgroup' => ['bool', 'name'=>'string', 'optlist'=>'string'],
'PDFlib::create_gstate' => ['int', 'optlist'=>'string'],
'PDFlib::create_pvf' => ['bool', 'filename'=>'string', 'data'=>'string', 'optlist'=>'string'],
'PDFlib::create_textflow' => ['int', 'text'=>'string', 'optlist'=>'string'],
'PDFlib::curveto' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'PDFlib::define_layer' => ['int', 'name'=>'string', 'optlist'=>'string'],
'PDFlib::delete' => ['bool'],
'PDFlib::delete_pvf' => ['int', 'filename'=>'string'],
'PDFlib::delete_table' => ['bool', 'table'=>'int', 'optlist'=>'string'],
'PDFlib::delete_textflow' => ['bool', 'textflow'=>'int'],
'PDFlib::encoding_set_char' => ['bool', 'encoding'=>'string', 'slot'=>'int', 'glyphname'=>'string', 'uv'=>'int'],
'PDFlib::end_document' => ['bool', 'optlist'=>'string'],
'PDFlib::end_font' => ['bool'],
'PDFlib::end_glyph' => ['bool'],
'PDFlib::end_item' => ['bool', 'id'=>'int'],
'PDFlib::end_layer' => ['bool'],
'PDFlib::end_page' => ['bool', 'p'=>''],
'PDFlib::end_page_ext' => ['bool', 'optlist'=>'string'],
'PDFlib::end_pattern' => ['bool', 'p'=>''],
'PDFlib::end_template' => ['bool', 'p'=>''],
'PDFlib::endpath' => ['bool', 'p'=>''],
'PDFlib::fill' => ['bool'],
'PDFlib::fill_imageblock' => ['int', 'page'=>'int', 'blockname'=>'string', 'image'=>'int', 'optlist'=>'string'],
'PDFlib::fill_pdfblock' => ['int', 'page'=>'int', 'blockname'=>'string', 'contents'=>'int', 'optlist'=>'string'],
'PDFlib::fill_stroke' => ['bool'],
'PDFlib::fill_textblock' => ['int', 'page'=>'int', 'blockname'=>'string', 'text'=>'string', 'optlist'=>'string'],
'PDFlib::findfont' => ['int', 'fontname'=>'string', 'encoding'=>'string', 'embed'=>'int'],
'PDFlib::fit_image' => ['bool', 'image'=>'int', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDFlib::fit_pdi_page' => ['bool', 'page'=>'int', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDFlib::fit_table' => ['string', 'table'=>'int', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'optlist'=>'string'],
'PDFlib::fit_textflow' => ['string', 'textflow'=>'int', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'optlist'=>'string'],
'PDFlib::fit_textline' => ['bool', 'text'=>'string', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDFlib::get_apiname' => ['string'],
'PDFlib::get_buffer' => ['string'],
'PDFlib::get_errmsg' => ['string'],
'PDFlib::get_errnum' => ['int'],
'PDFlib::get_majorversion' => ['int'],
'PDFlib::get_minorversion' => ['int'],
'PDFlib::get_parameter' => ['string', 'key'=>'string', 'modifier'=>'float'],
'PDFlib::get_pdi_parameter' => ['string', 'key'=>'string', 'doc'=>'int', 'page'=>'int', 'reserved'=>'int'],
'PDFlib::get_pdi_value' => ['float', 'key'=>'string', 'doc'=>'int', 'page'=>'int', 'reserved'=>'int'],
'PDFlib::get_value' => ['float', 'key'=>'string', 'modifier'=>'float'],
'PDFlib::info_font' => ['float', 'font'=>'int', 'keyword'=>'string', 'optlist'=>'string'],
'PDFlib::info_matchbox' => ['float', 'boxname'=>'string', 'num'=>'int', 'keyword'=>'string'],
'PDFlib::info_table' => ['float', 'table'=>'int', 'keyword'=>'string'],
'PDFlib::info_textflow' => ['float', 'textflow'=>'int', 'keyword'=>'string'],
'PDFlib::info_textline' => ['float', 'text'=>'string', 'keyword'=>'string', 'optlist'=>'string'],
'PDFlib::initgraphics' => ['bool'],
'PDFlib::lineto' => ['bool', 'x'=>'float', 'y'=>'float'],
'PDFlib::load_3ddata' => ['int', 'filename'=>'string', 'optlist'=>'string'],
'PDFlib::load_font' => ['int', 'fontname'=>'string', 'encoding'=>'string', 'optlist'=>'string'],
'PDFlib::load_iccprofile' => ['int', 'profilename'=>'string', 'optlist'=>'string'],
'PDFlib::load_image' => ['int', 'imagetype'=>'string', 'filename'=>'string', 'optlist'=>'string'],
'PDFlib::makespotcolor' => ['int', 'spotname'=>'string'],
'PDFlib::moveto' => ['bool', 'x'=>'float', 'y'=>'float'],
'PDFlib::open_ccitt' => ['int', 'filename'=>'string', 'width'=>'int', 'height'=>'int', 'BitReverse'=>'int', 'k'=>'int', 'Blackls1'=>'int'],
'PDFlib::open_file' => ['bool', 'filename'=>'string'],
'PDFlib::open_image' => ['int', 'imagetype'=>'string', 'source'=>'string', 'data'=>'string', 'length'=>'int', 'width'=>'int', 'height'=>'int', 'components'=>'int', 'bpc'=>'int', 'params'=>'string'],
'PDFlib::open_image_file' => ['int', 'imagetype'=>'string', 'filename'=>'string', 'stringparam'=>'string', 'intparam'=>'int'],
'PDFlib::open_memory_image' => ['int', 'image'=>'resource'],
'PDFlib::open_pdi' => ['int', 'filename'=>'string', 'optlist'=>'string', 'length'=>'int'],
'PDFlib::open_pdi_document' => ['int', 'filename'=>'string', 'optlist'=>'string'],
'PDFlib::open_pdi_page' => ['int', 'doc'=>'int', 'pagenumber'=>'int', 'optlist'=>'string'],
'PDFlib::pcos_get_number' => ['float', 'doc'=>'int', 'path'=>'string'],
'PDFlib::pcos_get_stream' => ['string', 'doc'=>'int', 'optlist'=>'string', 'path'=>'string'],
'PDFlib::pcos_get_string' => ['string', 'doc'=>'int', 'path'=>'string'],
'PDFlib::place_image' => ['bool', 'image'=>'int', 'x'=>'float', 'y'=>'float', 'scale'=>'float'],
'PDFlib::place_pdi_page' => ['bool', 'page'=>'int', 'x'=>'float', 'y'=>'float', 'sx'=>'float', 'sy'=>'float'],
'PDFlib::process_pdi' => ['int', 'doc'=>'int', 'page'=>'int', 'optlist'=>'string'],
'PDFlib::rect' => ['bool', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'PDFlib::restore' => ['bool', 'p'=>''],
'PDFlib::resume_page' => ['bool', 'optlist'=>'string'],
'PDFlib::rotate' => ['bool', 'phi'=>'float'],
'PDFlib::save' => ['bool', 'p'=>''],
'PDFlib::scale' => ['bool', 'sx'=>'float', 'sy'=>'float'],
'PDFlib::set_border_color' => ['bool', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDFlib::set_border_dash' => ['bool', 'black'=>'float', 'white'=>'float'],
'PDFlib::set_border_style' => ['bool', 'style'=>'string', 'width'=>'float'],
'PDFlib::set_gstate' => ['bool', 'gstate'=>'int'],
'PDFlib::set_info' => ['bool', 'key'=>'string', 'value'=>'string'],
'PDFlib::set_layer_dependency' => ['bool', 'type'=>'string', 'optlist'=>'string'],
'PDFlib::set_parameter' => ['bool', 'key'=>'string', 'value'=>'string'],
'PDFlib::set_text_pos' => ['bool', 'x'=>'float', 'y'=>'float'],
'PDFlib::set_value' => ['bool', 'key'=>'string', 'value'=>'float'],
'PDFlib::setcolor' => ['bool', 'fstype'=>'string', 'colorspace'=>'string', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float'],
'PDFlib::setdash' => ['bool', 'b'=>'float', 'w'=>'float'],
'PDFlib::setdashpattern' => ['bool', 'optlist'=>'string'],
'PDFlib::setflat' => ['bool', 'flatness'=>'float'],
'PDFlib::setfont' => ['bool', 'font'=>'int', 'fontsize'=>'float'],
'PDFlib::setgray' => ['bool', 'g'=>'float'],
'PDFlib::setgray_fill' => ['bool', 'g'=>'float'],
'PDFlib::setgray_stroke' => ['bool', 'g'=>'float'],
'PDFlib::setlinecap' => ['bool', 'linecap'=>'int'],
'PDFlib::setlinejoin' => ['bool', 'value'=>'int'],
'PDFlib::setlinewidth' => ['bool', 'width'=>'float'],
'PDFlib::setmatrix' => ['bool', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float'],
'PDFlib::setmiterlimit' => ['bool', 'miter'=>'float'],
'PDFlib::setrgbcolor' => ['bool', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDFlib::setrgbcolor_fill' => ['bool', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDFlib::setrgbcolor_stroke' => ['bool', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDFlib::shading' => ['int', 'shtype'=>'string', 'x0'=>'float', 'y0'=>'float', 'x1'=>'float', 'y1'=>'float', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float', 'optlist'=>'string'],
'PDFlib::shading_pattern' => ['int', 'shading'=>'int', 'optlist'=>'string'],
'PDFlib::shfill' => ['bool', 'shading'=>'int'],
'PDFlib::show' => ['bool', 'text'=>'string'],
'PDFlib::show_boxed' => ['int', 'text'=>'string', 'left'=>'float', 'top'=>'float', 'width'=>'float', 'height'=>'float', 'mode'=>'string', 'feature'=>'string'],
'PDFlib::show_xy' => ['bool', 'text'=>'string', 'x'=>'float', 'y'=>'float'],
'PDFlib::skew' => ['bool', 'alpha'=>'float', 'beta'=>'float'],
'PDFlib::stringwidth' => ['float', 'text'=>'string', 'font'=>'int', 'fontsize'=>'float'],
'PDFlib::stroke' => ['bool', 'p'=>''],
'PDFlib::suspend_page' => ['bool', 'optlist'=>'string'],
'PDFlib::translate' => ['bool', 'tx'=>'float', 'ty'=>'float'],
'PDFlib::utf16_to_utf8' => ['string', 'utf16string'=>'string'],
'PDFlib::utf32_to_utf16' => ['string', 'utf32string'=>'string', 'ordering'=>'string'],
'PDFlib::utf8_to_utf16' => ['string', 'utf8string'=>'string', 'ordering'=>'string'],
'PDO::__construct' => ['void', 'dsn'=>'string', 'username='=>'?string', 'passwd='=>'?string', 'options='=>'?array'],
'PDO::__sleep' => ['list<string>'],
'PDO::__wakeup' => ['void'],
'PDO::beginTransaction' => ['bool'],
'PDO::commit' => ['bool'],
'PDO::cubrid_schema' => ['array', 'schema_type'=>'int', 'table_name='=>'string', 'col_name='=>'string'],
'PDO::errorCode' => ['?string'],
'PDO::errorInfo' => ['array{0: ?string, 1: ?int, 2: ?string, 3?: mixed, 4?: mixed}'],
'PDO::exec' => ['int|false', 'query'=>'string'],
'PDO::getAttribute' => ['', 'attribute'=>'int'],
'PDO::getAvailableDrivers' => ['array'],
'PDO::inTransaction' => ['bool'],
'PDO::lastInsertId' => ['string', 'name='=>'string|null'],
'PDO::pgsqlCopyFromArray' => ['bool', 'table_name'=>'string', 'rows'=>'array', 'delimiter'=>'string', 'null_as'=>'string', 'fields'=>'string'],
'PDO::pgsqlCopyFromFile' => ['bool', 'table_name'=>'string', 'filename'=>'string', 'delimiter'=>'string', 'null_as'=>'string', 'fields'=>'string'],
'PDO::pgsqlCopyToArray' => ['array', 'table_name'=>'string', 'delimiter'=>'string', 'null_as'=>'string', 'fields'=>'string'],
'PDO::pgsqlCopyToFile' => ['bool', 'table_name'=>'string', 'filename'=>'string', 'delimiter'=>'string', 'null_as'=>'string', 'fields'=>'string'],
'PDO::pgsqlGetNotify' => ['array{message:string,pid:int,payload?:string}|false', 'result_type='=>'PDO::FETCH_*', 'ms_timeout='=>'int'],
'PDO::pgsqlGetPid' => ['int'],
'PDO::pgsqlLOBCreate' => ['string'],
'PDO::pgsqlLOBOpen' => ['resource', 'oid'=>'string', 'mode='=>'string'],
'PDO::pgsqlLOBUnlink' => ['bool', 'oid'=>'string'],
'PDO::prepare' => ['PDOStatement|false', 'statement'=>'string', 'options='=>'array'],
'PDO::query' => ['PDOStatement|false', 'sql'=>'string'],
'PDO::query\'1' => ['PDOStatement|false', 'sql'=>'string', 'fetch_column'=>'int', 'colno='=>'int'],
'PDO::query\'2' => ['PDOStatement|false', 'sql'=>'string', 'fetch_class'=>'int', 'classname'=>'string', 'ctorargs'=>'array'],
'PDO::query\'3' => ['PDOStatement|false', 'sql'=>'string', 'fetch_into'=>'int', 'object'=>'object'],
'PDO::quote' => ['string|false', 'string'=>'string', 'paramtype='=>'int'],
'PDO::rollBack' => ['bool'],
'PDO::setAttribute' => ['bool', 'attribute'=>'int', 'value'=>''],
'PDO::sqliteCreateAggregate' => ['bool', 'function_name'=>'string', 'step_func'=>'callable', 'finalize_func'=>'callable', 'num_args='=>'int'],
'PDO::sqliteCreateCollation' => ['bool', 'name'=>'string', 'callback'=>'callable'],
'PDO::sqliteCreateFunction' => ['bool', 'function_name'=>'string', 'callback'=>'callable', 'num_args='=>'int'],
'pdo_drivers' => ['array'],
'PDOException::getCode' => ['string'],
'PDOException::getFile' => ['string'],
'PDOException::getLine' => ['int'],
'PDOException::getMessage' => ['string'],
'PDOException::getPrevious' => ['?Throwable'],
'PDOException::getTrace' => ['list<array<string,mixed>>'],
'PDOException::getTraceAsString' => ['string'],
'PDOStatement::__sleep' => ['list<string>'],
'PDOStatement::__wakeup' => ['void'],
'PDOStatement::bindColumn' => ['bool', 'column'=>'mixed', '&rw_var'=>'mixed', 'type='=>'int', 'maxLength='=>'int', 'driverOptions='=>'mixed'],
'PDOStatement::bindParam' => ['bool', 'param,'=>'string|int', '&rw_var'=>'mixed', 'type='=>'int', 'maxLength='=>'int', 'driverOptions='=>'mixed'],
'PDOStatement::bindValue' => ['bool', 'param'=>'string|int', 'value'=>'mixed', 'type='=>'int'],
'PDOStatement::closeCursor' => ['bool'],
'PDOStatement::columnCount' => ['int'],
'PDOStatement::debugDumpParams' => ['bool|null'],
'PDOStatement::errorCode' => ['string|null'],
'PDOStatement::errorInfo' => ['array{0: ?string, 1: ?int, 2: ?string, 3?: mixed, 4?: mixed}'],
'PDOStatement::execute' => ['bool', 'params='=>'?array'],
'PDOStatement::fetch' => ['mixed', 'mode='=>'int', 'cursorOrientation='=>'int', 'cursorOffset='=>'int'],
'PDOStatement::fetchAll' => ['array|false', 'mode='=>'int', '...args='=>'mixed'],
'PDOStatement::fetchColumn' => ['mixed', 'column='=>'int'],
'PDOStatement::fetchObject' => ['object|false', 'class='=>'?string', 'ctorArgs='=>'?array'],
'PDOStatement::getAttribute' => ['mixed', 'attribute'=>'int'],
'PDOStatement::getColumnMeta' => ['array|false', 'column'=>'int'],
'PDOStatement::nextRowset' => ['bool'],
'PDOStatement::rowCount' => ['int'],
'PDOStatement::setAttribute' => ['bool', 'attribute'=>'int', 'value'=>'mixed'],
'PDOStatement::setFetchMode' => ['bool', 'mode'=>'int', '...args='=> 'mixed'],
'pfsockopen' => ['resource|false', 'hostname'=>'string', 'port='=>'int', '&w_error_code='=>'int', '&w_error_message='=>'string', 'timeout='=>'float'],
'pg_affected_rows' => ['int', 'result'=>'\PgSql\Result'],
'pg_cancel_query' => ['bool', 'connection'=>'\PgSql\Connection'],
'pg_client_encoding' => ['string', 'connection='=>'\PgSql\Connection'],
'pg_close' => ['bool', 'connection='=>'\PgSql\Connection'],
'pg_connect' => ['\PgSql\Connection|false', 'connection_string'=>'string', 'flags='=>'int'],
'pg_connect_poll' => ['int', 'connection'=>'\PgSql\Connection'],
'pg_connection_busy' => ['bool', 'connection'=>'\PgSql\Connection'],
'pg_connection_reset' => ['bool', 'connection'=>'\PgSql\Connection'],
'pg_connection_status' => ['int', 'connection'=>'\PgSql\Connection'],
'pg_consume_input' => ['bool', 'connection'=>'\PgSql\Connection'],
'pg_convert' => ['array|false', 'connection'=>'\PgSql\Connection', 'table_name'=>'string', 'values'=>'array', 'flags='=>'int'],
'pg_copy_from' => ['bool', 'connection'=>'\PgSql\Connection', 'table_name'=>'string', 'rows'=>'array', 'separator='=>'string', 'null_as='=>'string'],
'pg_copy_to' => ['array|false', 'connection'=>'\PgSql\Connection', 'table_name'=>'string', 'separator='=>'string', 'null_as='=>'string'],
'pg_dbname' => ['string', 'connection='=>'\PgSql\Connection'],
'pg_delete' => ['string|bool', 'connection'=>'\PgSql\Connection', 'table_name'=>'string', 'conditions'=>'array', 'flags='=>'int'],
'pg_end_copy' => ['bool', 'connection='=>'\PgSql\Connection'],
'pg_escape_bytea' => ['string', 'connection'=>'\PgSql\Connection', 'string'=>'string'],
'pg_escape_bytea\'1' => ['string', 'connection'=>'string'],
'pg_escape_identifier' => ['string|false', 'connection'=>'\PgSql\Connection', 'string'=>'string'],
'pg_escape_identifier\'1' => ['string|false', 'connection'=>'string'],
'pg_escape_literal' => ['string|false', 'connection'=>'\PgSql\Connection', 'string'=>'string'],
'pg_escape_literal\'1' => ['string|false', 'connection'=>'string'],
'pg_escape_string' => ['string', 'connection'=>'\PgSql\Connection', 'string'=>'string'],
'pg_escape_string\'1' => ['string', 'connection'=>'string'],
'pg_exec' => ['\PgSql\Result|false', 'connection'=>'\PgSql\Connection', 'query'=>'string'],
'pg_execute' => ['\PgSql\Result|false', 'connection'=>'\PgSql\Connection', 'statement_name'=>'string', 'params'=>'array'],
'pg_execute\'1' => ['\PgSql\Result|false', 'connection'=>'string', 'statement_name'=>'array'],
'pg_fetch_all' => ['array<array>', 'result'=>'\PgSql\Result', 'result_type='=>'int'],
'pg_fetch_all_columns' => ['array', 'result'=>'\PgSql\Result', 'field='=>'int'],
'pg_fetch_array' => ['array<string|null>|false', 'result'=>'\PgSql\Result', 'row='=>'?int', 'mode='=>'int'],
'pg_fetch_assoc' => ['array<string, mixed>|false', 'result'=>'\PgSql\Result', 'row='=>'?int'],
'pg_fetch_object' => ['object|false', 'result'=>'\PgSql\Result', 'row='=>'?int', 'class='=>'string', 'constructor_args='=>'array'],
'pg_fetch_result' => ['string|false|null', 'result'=>'\PgSql\Result', 'row'=>'string|int'],
'pg_fetch_result\'1' => ['string|false|null', 'result'=>'\PgSql\Result', 'row'=>'?int', 'field'=>'string|int'],
'pg_fetch_row' => ['array|false', 'result'=>'\PgSql\Result', 'row='=>'?int', 'mode='=>'int'],
'pg_field_is_null' => ['int|false', 'result'=>'\PgSql\Result', 'row'=>'string|int'],
'pg_field_is_null\'1' => ['int|false', 'result'=>'\PgSql\Result', 'row'=>'int', 'field'=>'string|int'],
'pg_field_name' => ['string', 'result'=>'\PgSql\Result', 'field'=>'int'],
'pg_field_num' => ['int', 'result'=>'\PgSql\Result', 'field'=>'string'],
'pg_field_prtlen' => ['int|false', 'result'=>'\PgSql\Result', 'row'=>'string|int'],
'pg_field_prtlen\'1' => ['int|false', 'result'=>'\PgSql\Result', 'row'=>'int', 'field'=>'string|int'],
'pg_field_size' => ['int', 'result'=>'\PgSql\Result', 'field'=>'int'],
'pg_field_table' => ['string|int|false', 'result'=>'\PgSql\Result', 'field'=>'int', 'oid_only='=>'bool'],
'pg_field_type' => ['string', 'result'=>'\PgSql\Result', 'field'=>'int'],
'pg_field_type_oid' => ['int|string', 'result'=>'\PgSql\Result', 'field'=>'int'],
'pg_flush' => ['int|bool', 'connection'=>'\PgSql\Connection'],
'pg_free_result' => ['bool', 'result'=>'\PgSql\Result'],
'pg_get_notify' => ['array|false', 'result'=>'\PgSql\Result', 'mode='=>'int'],
'pg_get_pid' => ['int', 'connection'=>'\PgSql\Connection'],
'pg_get_result' => ['\PgSql\Result|false', 'connection='=>'\PgSql\Connection'],
'pg_host' => ['string', 'connection='=>'\PgSql\Connection'],
'pg_insert' => ['\PgSql\Result|string|false', 'connection'=>'\PgSql\Connection', 'table_name'=>'string', 'values'=>'array', 'flags='=>'int'],
'pg_last_error' => ['string', 'connection='=>'\PgSql\Connection', 'operation='=>'int'],
'pg_last_notice' => ['string|array|bool', 'connection'=>'\PgSql\Connection', 'mode='=>'int'],
'pg_last_oid' => ['string|int|false', 'result'=>'\PgSql\Result'],
'pg_lo_close' => ['bool', 'lob'=>'\PgSql\Lob'],
'pg_lo_create' => ['int|string|false', 'connection='=>'\PgSql\Connection', 'oid='=>'int|string'],
'pg_lo_export' => ['bool', 'connection'=>'\PgSql\Connection', 'oid'=>'int|string', 'filename'=>'string'],
'pg_lo_export\'1' => ['bool', 'connection'=>'int|string', 'oid'=>'string'],
'pg_lo_import' => ['int|string|false', 'connection'=>'\PgSql\Connection', 'filename'=>'string', 'oid'=>'string|int'],
'pg_lo_import\'1' => ['int|string|false', 'connection'=>'string', 'filename'=>'string|int'],
'pg_lo_open' => ['\PgSql\Lob|false', 'connection'=>'\PgSql\Connection', 'oid'=>'int|string', 'mode'=>'string'],
'pg_lo_open\'1' => ['\PgSql\Lob|false', 'connection'=>'int|string', 'oid'=>'string'],
'pg_lo_read' => ['string|false', 'lob'=>'\PgSql\Lob', 'length='=>'int'],
'pg_lo_read_all' => ['int', 'lob'=>'\PgSql\Lob'],
'pg_lo_seek' => ['bool', 'lob'=>'\PgSql\Lob', 'offset'=>'int', 'whence='=>'int'],
'pg_lo_tell' => ['int', 'lob'=>'\PgSql\Lob'],
'pg_lo_truncate' => ['bool', 'lob'=>'\PgSql\Lob', 'size'=>'int'],
'pg_lo_unlink' => ['bool', 'connection'=>'\PgSql\Connection', 'oid'=>'int|string'],
'pg_lo_unlink\'1' => ['bool', 'connection'=>'int|string'],
'pg_lo_write' => ['int|false', 'lob'=>'\PgSql\Lob', 'data'=>'string', 'length='=>'int'],
'pg_meta_data' => ['array|false', 'connection'=>'\PgSql\Connection', 'table_name'=>'string', 'extended='=>'bool'],
'pg_num_fields' => ['int', 'result'=>'\PgSql\Result'],
'pg_num_rows' => ['int', 'result'=>'\PgSql\Result'],
'pg_options' => ['string', 'connection='=>'\PgSql\Connection'],
'pg_parameter_status' => ['string|false', 'connection'=>'\PgSql\Connection', 'name'=>'string'],
'pg_parameter_status\'1' => ['string|false', 'connection'=>'string'],
'pg_pconnect' => ['\PgSql\Connection|false', 'connection_string'=>'string', 'flags='=>'string', 'port='=>'string|int', 'options='=>'string', 'tty='=>'string', 'database='=>'string'],
'pg_ping' => ['bool', 'connection='=>'\PgSql\Connection'],
'pg_port' => ['int', 'connection='=>'\PgSql\Connection'],
'pg_prepare' => ['\PgSql\Result|false', 'connection'=>'\PgSql\Connection', 'statement_name'=>'string', 'query'=>'string'],
'pg_prepare\'1' => ['\PgSql\Result|false', 'connection'=>'string', 'statement_name'=>'string'],
'pg_put_line' => ['bool', 'connection'=>'\PgSql\Connection', 'data'=>'string'],
'pg_put_line\'1' => ['bool', 'connection'=>'string'],
'pg_query' => ['\PgSql\Result|false', 'connection'=>'\PgSql\Connection', 'query'=>'string'],
'pg_query\'1' => ['\PgSql\Result|false', 'connection'=>'string'],
'pg_query_params' => ['\PgSql\Result|false', 'connection'=>'\PgSql\Connection', 'query'=>'string', 'params'=>'array'],
'pg_query_params\'1' => ['\PgSql\Result|false', 'connection'=>'string', 'query'=>'array'],
'pg_result_error' => ['string|false', 'result'=>'\PgSql\Result'],
'pg_result_error_field' => ['string|false|null', 'result'=>'\PgSql\Result', 'field_code'=>'int'],
'pg_result_seek' => ['bool', 'result'=>'\PgSql\Result', 'row'=>'int'],
'pg_result_status' => ['string|int', 'result'=>'\PgSql\Result', 'mode='=>'int'],
'pg_select' => ['string|array|false', 'connection'=>'\PgSql\Connection', 'table_name'=>'string', 'assoc_array'=>'array', 'options='=>'int', 'result_type='=>'int'],
'pg_send_execute' => ['bool|int', 'connection'=>'\PgSql\Connection', 'query'=>'string', 'params'=>'array'],
'pg_send_prepare' => ['bool|int', 'connection'=>'\PgSql\Connection', 'statement_name'=>'string', 'query'=>'string'],
'pg_send_query' => ['bool|int', 'connection'=>'\PgSql\Connection', 'query'=>'string'],
'pg_send_query_params' => ['bool|int', 'connection'=>'\PgSql\Connection', 'query'=>'string', 'params'=>'array'],
'pg_set_client_encoding' => ['int', 'connection'=>'\PgSql\Connection', 'encoding'=>'string'],
'pg_set_client_encoding\'1' => ['int', 'connection'=>'string'],
'pg_set_error_verbosity' => ['int|false', 'connection'=>'\PgSql\Connection', 'verbosity'=>'int'],
'pg_set_error_verbosity\'1' => ['int|false', 'connection'=>'int'],
'pg_socket' => ['resource|false', 'connection'=>'\PgSql\Connection'],
'pg_trace' => ['bool', 'filename'=>'string', 'mode='=>'string', 'connection='=>'\PgSql\Connection'],
'pg_transaction_status' => ['int', 'connection'=>'\PgSql\Connection'],
'pg_tty' => ['string', 'connection='=>'\PgSql\Connection'],
'pg_unescape_bytea' => ['string', 'string'=>'string'],
'pg_untrace' => ['bool', 'connection='=>'\PgSql\Connection'],
'pg_update' => ['string|bool', 'connection'=>'\PgSql\Connection', 'table_name'=>'string', 'values'=>'array', 'conditions'=>'array', 'flags='=>'int'],
'pg_version' => ['array', 'connection='=>'\PgSql\Connection'],
'Phar::__construct' => ['void', 'fname'=>'string', 'flags='=>'int', 'alias='=>'string'],
'Phar::addEmptyDir' => ['void', 'dirname'=>'string'],
'Phar::addFile' => ['void', 'file'=>'string', 'localname='=>'string'],
'Phar::addFromString' => ['void', 'localname'=>'string', 'contents'=>'string'],
'Phar::apiVersion' => ['string'],
'Phar::buildFromDirectory' => ['array', 'base_dir'=>'string', 'regex='=>'string'],
'Phar::buildFromIterator' => ['array', 'iter'=>'Iterator', 'base_directory='=>'string'],
'Phar::canCompress' => ['bool', 'method='=>'int'],
'Phar::canWrite' => ['bool'],
'Phar::compress' => ['Phar', 'compression'=>'int', 'extension='=>'string'],
'Phar::compressAllFilesBZIP2' => ['bool'],
'Phar::compressAllFilesGZ' => ['bool'],
'Phar::compressFiles' => ['void', 'compression'=>'int'],
'Phar::convertToData' => ['PharData', 'format='=>'int', 'compression='=>'int', 'extension='=>'string'],
'Phar::convertToExecutable' => ['Phar', 'format='=>'int', 'compression='=>'int', 'extension='=>'string'],
'Phar::copy' => ['bool', 'oldfile'=>'string', 'newfile'=>'string'],
'Phar::count' => ['int'],
'Phar::createDefaultStub' => ['string', 'indexfile='=>'string', 'webindexfile='=>'string'],
'Phar::decompress' => ['Phar', 'extension='=>'string'],
'Phar::decompressFiles' => ['bool'],
'Phar::delete' => ['bool', 'entry'=>'string'],
'Phar::delMetadata' => ['bool'],
'Phar::extractTo' => ['bool', 'pathto'=>'string', 'files='=>'string|array|null', 'overwrite='=>'bool'],
'Phar::getAlias' => ['string'],
'Phar::getMetadata' => ['mixed'],
'Phar::getModified' => ['bool'],
'Phar::getPath' => ['string'],
'Phar::getSignature' => ['array{hash:string, hash_type:string}'],
'Phar::getStub' => ['string'],
'Phar::getSupportedCompression' => ['array'],
'Phar::getSupportedSignatures' => ['array'],
'Phar::getVersion' => ['string'],
'Phar::hasMetadata' => ['bool'],
'Phar::interceptFileFuncs' => ['void'],
'Phar::isBuffering' => ['bool'],
'Phar::isCompressed' => ['mixed|false'],
'Phar::isFileFormat' => ['bool', 'format'=>'int'],
'Phar::isValidPharFilename' => ['bool', 'filename'=>'string', 'executable='=>'bool'],
'Phar::isWritable' => ['bool'],
'Phar::loadPhar' => ['bool', 'filename'=>'string', 'alias='=>'string'],
'Phar::mapPhar' => ['bool', 'alias='=>'string', 'dataoffset='=>'int'],
'Phar::mount' => ['void', 'pharpath'=>'string', 'externalpath'=>'string'],
'Phar::mungServer' => ['void', 'munglist'=>'array'],
'Phar::offsetExists' => ['bool', 'offset'=>'string'],
'Phar::offsetGet' => ['PharFileInfo', 'offset'=>'string'],
'Phar::offsetSet' => ['void', 'offset'=>'string', 'value'=>'string'],
'Phar::offsetUnset' => ['bool', 'offset'=>'string'],
'Phar::running' => ['string', 'retphar='=>'bool'],
'Phar::setAlias' => ['bool', 'alias'=>'string'],
'Phar::setDefaultStub' => ['bool', 'index='=>'string', 'webindex='=>'string'],
'Phar::setMetadata' => ['void', 'metadata'=>''],
'Phar::setSignatureAlgorithm' => ['void', 'sigtype'=>'int', 'privatekey='=>'string'],
'Phar::setStub' => ['bool', 'stub'=>'string', 'length='=>'int'],
'Phar::startBuffering' => ['void'],
'Phar::stopBuffering' => ['void'],
'Phar::uncompressAllFiles' => ['bool'],
'Phar::unlinkArchive' => ['bool', 'archive'=>'string'],
'Phar::webPhar' => ['', 'alias='=>'string', 'index='=>'string', 'f404='=>'string', 'mimetypes='=>'array', 'rewrites='=>'array'],
'PharData::__construct' => ['void', 'fname'=>'string', 'flags='=>'?int', 'alias='=>'?string', 'format='=>'int'],
'PharData::addEmptyDir' => ['bool', 'dirname'=>'string'],
'PharData::addFile' => ['void', 'file'=>'string', 'localname='=>'string'],
'PharData::addFromString' => ['bool', 'localname'=>'string', 'contents'=>'string'],
'PharData::buildFromDirectory' => ['array', 'base_dir'=>'string', 'regex='=>'string'],
'PharData::buildFromIterator' => ['array', 'iter'=>'Iterator', 'base_directory='=>'string'],
'PharData::compress' => ['PharData', 'compression'=>'int', 'extension='=>'string'],
'PharData::compressFiles' => ['bool', 'compression'=>'int'],
'PharData::convertToData' => ['PharData', 'format='=>'int', 'compression='=>'int', 'extension='=>'string'],
'PharData::convertToExecutable' => ['Phar', 'format='=>'int', 'compression='=>'int', 'extension='=>'string'],
'PharData::copy' => ['bool', 'oldfile'=>'string', 'newfile'=>'string'],
'PharData::decompress' => ['PharData', 'extension='=>'string'],
'PharData::decompressFiles' => ['bool'],
'PharData::delete' => ['bool', 'entry'=>'string'],
'PharData::delMetadata' => ['bool'],
'PharData::extractTo' => ['bool', 'pathto'=>'string', 'files='=>'string|array|null', 'overwrite='=>'bool'],
'PharData::isWritable' => ['bool'],
'PharData::offsetExists' => ['bool', 'offset'=>'string'],
'PharData::offsetGet' => ['PharFileInfo', 'offset'=>'string'],
'PharData::offsetSet' => ['void', 'offset'=>'string', 'value'=>'string'],
'PharData::offsetUnset' => ['bool', 'offset'=>'string'],
'PharData::setAlias' => ['bool', 'alias'=>'string'],
'PharData::setDefaultStub' => ['bool', 'index='=>'string', 'webindex='=>'string'],
'phardata::setMetadata' => ['void', 'metadata'=>'mixed'],
'phardata::setSignatureAlgorithm' => ['void', 'sigtype'=>'int'],
'PharData::setStub' => ['bool', 'stub'=>'string', 'length='=>'int'],
'PharFileInfo::__construct' => ['void', 'entry'=>'string'],
'PharFileInfo::chmod' => ['void', 'permissions'=>'int'],
'PharFileInfo::compress' => ['bool', 'compression'=>'int'],
'PharFileInfo::decompress' => ['bool'],
'PharFileInfo::delMetadata' => ['bool'],
'PharFileInfo::getCompressedSize' => ['int'],
'PharFileInfo::getContent' => ['string'],
'PharFileInfo::getCRC32' => ['int'],
'PharFileInfo::getMetadata' => ['mixed'],
'PharFileInfo::getPharFlags' => ['int'],
'PharFileInfo::hasMetadata' => ['bool'],
'PharFileInfo::isCompressed' => ['bool', 'compression_type='=>'int'],
'PharFileInfo::isCompressedBZIP2' => ['bool'],
'PharFileInfo::isCompressedGZ' => ['bool'],
'PharFileInfo::isCRCChecked' => ['bool'],
'PharFileInfo::setCompressedBZIP2' => ['bool'],
'PharFileInfo::setCompressedGZ' => ['bool'],
'PharFileInfo::setMetadata' => ['void', 'metadata'=>'mixed'],
'PharFileInfo::setUncompressed' => ['bool'],
'phdfs::__construct' => ['void', 'ip'=>'string', 'port'=>'string'],
'phdfs::__destruct' => ['void'],
'phdfs::connect' => ['bool'],
'phdfs::copy' => ['bool', 'source_file'=>'string', 'destination_file'=>'string'],
'phdfs::create_directory' => ['bool', 'path'=>'string'],
'phdfs::delete' => ['bool', 'path'=>'string'],
'phdfs::disconnect' => ['bool'],
'phdfs::exists' => ['bool', 'path'=>'string'],
'phdfs::file_info' => ['array', 'path'=>'string'],
'phdfs::list_directory' => ['array', 'path'=>'string'],
'phdfs::read' => ['string', 'path'=>'string', 'length='=>'string'],
'phdfs::rename' => ['bool', 'old_path'=>'string', 'new_path'=>'string'],
'phdfs::tell' => ['int', 'path'=>'string'],
'phdfs::write' => ['bool', 'path'=>'string', 'buffer'=>'string', 'mode='=>'string'],
'php_check_syntax' => ['bool', 'filename'=>'string', 'error_message='=>'string'],
'php_ini_loaded_file' => ['string|false'],
'php_ini_scanned_files' => ['string|false'],
'php_logo_guid' => ['string'],
'php_sapi_name' => ['string'],
'php_strip_whitespace' => ['string', 'filename'=>'string'],
'php_uname' => ['string', 'mode='=>'string'],
'php_user_filter::filter' => ['int', 'in'=>'resource', 'out'=>'resource', '&rw_consumed'=>'int', 'closing'=>'bool'],
'php_user_filter::onClose' => ['void'],
'php_user_filter::onCreate' => ['bool'],
'phpcredits' => ['bool', 'flags='=>'int'],
'phpdbg_break_file' => ['void', 'file'=>'string', 'line'=>'int'],
'phpdbg_break_function' => ['void', 'function'=>'string'],
'phpdbg_break_method' => ['void', 'class'=>'string', 'method'=>'string'],
'phpdbg_break_next' => ['void'],
'phpdbg_clear' => ['void'],
'phpdbg_color' => ['void', 'element'=>'int', 'color'=>'string'],
'phpdbg_end_oplog' => ['array', 'options='=>'array'],
'phpdbg_exec' => ['mixed', 'context='=>'string'],
'phpdbg_get_executable' => ['array', 'options='=>'array'],
'phpdbg_prompt' => ['void', 'string'=>'string'],
'phpdbg_start_oplog' => ['void'],
'phpinfo' => ['bool', 'flags='=>'int'],
'PhpToken::tokenize' => ['list<PhpToken>', 'code'=>'string', 'flags='=>'int'],
'PhpToken::is' => ['bool', 'kind'=>'string|int|string[]|int[]'],
'PhpToken::isIgnorable' => ['bool'],
'PhpToken::getTokenName' => ['string'],
'phpversion' => ['string|false', 'extension='=>'string'],
'pht\AtomicInteger::__construct' => ['void', 'value='=>'int'],
'pht\AtomicInteger::dec' => ['void'],
'pht\AtomicInteger::get' => ['int'],
'pht\AtomicInteger::inc' => ['void'],
'pht\AtomicInteger::lock' => ['void'],
'pht\AtomicInteger::set' => ['void', 'value'=>'int'],
'pht\AtomicInteger::unlock' => ['void'],
'pht\HashTable::lock' => ['void'],
'pht\HashTable::size' => ['int'],
'pht\HashTable::unlock' => ['void'],
'pht\Queue::front' => ['mixed'],
'pht\Queue::lock' => ['void'],
'pht\Queue::pop' => ['mixed'],
'pht\Queue::push' => ['void', 'value'=>'mixed'],
'pht\Queue::size' => ['int'],
'pht\Queue::unlock' => ['void'],
'pht\Runnable::run' => ['void'],
'pht\thread::addClassTask' => ['void', 'className'=>'string', '...ctorArgs='=>'mixed'],
'pht\thread::addFileTask' => ['void', 'fileName'=>'string', '...globals='=>'mixed'],
'pht\thread::addFunctionTask' => ['void', 'func'=>'callable', '...funcArgs='=>'mixed'],
'pht\thread::join' => ['void'],
'pht\thread::start' => ['void'],
'pht\thread::taskCount' => ['int'],
'pht\threaded::lock' => ['void'],
'pht\threaded::unlock' => ['void'],
'pht\Vector::__construct' => ['void', 'size='=>'int', 'value='=>'mixed'],
'pht\Vector::deleteAt' => ['void', 'offset'=>'int'],
'pht\Vector::insertAt' => ['void', 'value'=>'mixed', 'offset'=>'int'],
'pht\Vector::lock' => ['void'],
'pht\Vector::pop' => ['mixed'],
'pht\Vector::push' => ['void', 'value'=>'mixed'],
'pht\Vector::resize' => ['void', 'size'=>'int', 'value='=>'mixed'],
'pht\Vector::shift' => ['mixed'],
'pht\Vector::size' => ['int'],
'pht\Vector::unlock' => ['void'],
'pht\Vector::unshift' => ['void', 'value'=>'mixed'],
'pht\Vector::updateAt' => ['void', 'value'=>'mixed', 'offset'=>'int'],
'pi' => ['float'],
'pointObj::__construct' => ['void'],
'pointObj::distanceToLine' => ['float', 'p1'=>'pointObj', 'p2'=>'pointObj'],
'pointObj::distanceToPoint' => ['float', 'poPoint'=>'pointObj'],
'pointObj::distanceToShape' => ['float', 'shape'=>'shapeObj'],
'pointObj::draw' => ['int', 'map'=>'mapObj', 'layer'=>'layerObj', 'img'=>'imageObj', 'class_index'=>'int', 'text'=>'string'],
'pointObj::ms_newPointObj' => ['pointObj'],
'pointObj::project' => ['int', 'in'=>'projectionObj', 'out'=>'projectionObj'],
'pointObj::setXY' => ['int', 'x'=>'float', 'y'=>'float', 'm'=>'float'],
'pointObj::setXYZ' => ['int', 'x'=>'float', 'y'=>'float', 'z'=>'float', 'm'=>'float'],
'Pool::__construct' => ['void', 'size'=>'int', 'class'=>'string', 'ctor='=>'array'],
'Pool::collect' => ['int', 'collector='=>'Callable'],
'Pool::resize' => ['void', 'size'=>'int'],
'Pool::shutdown' => ['void'],
'Pool::submit' => ['int', 'task'=>'Threaded'],
'Pool::submitTo' => ['int', 'worker'=>'int', 'task'=>'Threaded'],
'popen' => ['resource|false', 'command'=>'string', 'mode'=>'string'],
'pos' => ['mixed', 'array'=>'array'],
'posix_access' => ['bool', 'filename'=>'string', 'flags='=>'int'],
'posix_ctermid' => ['string|false'],
'posix_errno' => ['int'],
'posix_get_last_error' => ['int'],
'posix_getcwd' => ['string|false'],
'posix_getegid' => ['int'],
'posix_geteuid' => ['int'],
'posix_getgid' => ['int'],
'posix_getgrgid' => ['array{name: string, passwd: string, gid: int, members: list<string>}|false', 'group_id'=>'int'],
'posix_getgrnam' => ['array{name: string, passwd: string, gid: int, members: list<string>}|false', 'name'=>'string'],
'posix_getgroups' => ['list<int>|false'],
'posix_getlogin' => ['string|false'],
'posix_getpgid' => ['int|false', 'process_id'=>'int'],
'posix_getpgrp' => ['int'],
'posix_getpid' => ['int'],
'posix_getppid' => ['int'],
'posix_getpwnam' => ['array{name: string, passwd: string, uid: int, gid: int, gecos: string, dir: string, shell: string}|false', 'username'=>'string'],
'posix_getpwuid' => ['array{name: string, passwd: string, uid: int, gid: int, gecos: string, dir: string, shell: string}|false', 'user_id'=>'int'],
'posix_getrlimit' => ['array{"soft core": string, "hard core": string, "soft data": string, "hard data": string, "soft stack": integer, "hard stack": string, "soft totalmem": string, "hard totalmem": string, "soft rss": string, "hard rss": string, "soft maxproc": integer, "hard maxproc": integer, "soft memlock": integer, "hard memlock": integer, "soft cpu": string, "hard cpu": string, "soft filesize": string, "hard filesize": string, "soft openfiles": integer, "hard openfiles": integer}|false'],
'posix_getsid' => ['int|false', 'process_id'=>'int'],
'posix_getuid' => ['int'],
'posix_initgroups' => ['bool', 'username'=>'string', 'group_id'=>'int'],
'posix_isatty' => ['bool', 'file_descriptor'=>'resource|int'],
'posix_kill' => ['bool', 'process_id'=>'int', 'signal'=>'int'],
'posix_mkfifo' => ['bool', 'filename'=>'string', 'permissions'=>'int'],
'posix_mknod' => ['bool', 'filename'=>'string', 'flags'=>'int', 'major='=>'int', 'minor='=>'int'],
'posix_setegid' => ['bool', 'group_id'=>'int'],
'posix_seteuid' => ['bool', 'user_id'=>'int'],
'posix_setgid' => ['bool', 'group_id'=>'int'],
'posix_setpgid' => ['bool', 'process_id'=>'int', 'process_group_id'=>'int'],
'posix_setrlimit' => ['bool', 'resource'=>'int', 'soft_limit'=>'int', 'hard_limit'=>'int'],
'posix_setsid' => ['int'],
'posix_setuid' => ['bool', 'user_id'=>'int'],
'posix_strerror' => ['string', 'error_code'=>'int'],
'posix_times' => ['array{ticks: int, utime: int, stime: int, cutime: int, cstime: int}|false'],
'posix_ttyname' => ['string|false', 'file_descriptor'=>'resource|int'],
'posix_uname' => ['array{sysname: string, nodename: string, release: string, version: string, machine: string, domainname: string}|false'],
'Postal\Expand::expand_address' => ['string[]', 'address'=>'string', 'options='=>'array<string, mixed>'],
'Postal\Parser::parse_address' => ['array<string,string>', 'address'=>'string', 'options='=>'array<string, string>'],
'pow' => ['float|int', 'num'=>'int|float', 'exponent'=>'int|float'],
'preg_filter' => ['null|string|string[]', 'pattern'=>'mixed', 'replacement'=>'mixed', 'subject'=>'mixed', 'limit='=>'int', '&w_count='=>'int'],
'preg_grep' => ['array|false', 'pattern'=>'string', 'array'=>'array', 'flags='=>'int'],
'preg_last_error' => ['int'],
'preg_match' => ['int|false', 'pattern'=>'string', 'subject'=>'string', '&w_matches='=>'string[]', 'flags='=>'0|', 'offset='=>'int'],
'preg_match\'1' => ['int|false', 'pattern'=>'string', 'subject'=>'string', '&w_matches='=>'array', 'flags='=>'int', 'offset='=>'int'],
'preg_match_all' => ['int|false', 'pattern'=>'string', 'subject'=>'string', '&w_matches='=>'array', 'flags='=>'int', 'offset='=>'int'],
'preg_quote' => ['string', 'str'=>'string', 'delimiter='=>'string'],
'preg_replace' => ['string|string[]|null', 'pattern'=>'string|array', 'replacement'=>'string|array', 'subject'=>'string|array', 'limit='=>'int', '&w_count='=>'int'],
'preg_replace_callback' => ['string|null', 'pattern'=>'string|array', 'callback'=>'callable(string[]):string', 'subject'=>'string', 'limit='=>'int', '&w_count='=>'int'],
'preg_replace_callback\'1' => ['string[]|null', 'pattern'=>'string|array', 'callback'=>'callable(string[]):string', 'subject'=>'string[]', 'limit='=>'int', '&w_count='=>'int'],
'preg_replace_callback_array' => ['string|string[]|null', 'pattern'=>'array<string,callable(array):string>', 'subject'=>'string|array', 'limit='=>'int', '&w_count='=>'int'],
'preg_split' => ['list<string>|false', 'pattern'=>'string', 'subject'=>'string', 'limit'=>'int', 'flags='=>'null'],
'preg_split\'1' => ['list<string>|list<list<string|int>>|false', 'pattern'=>'string', 'subject'=>'string', 'limit='=>'int', 'flags='=>'int'],
'prev' => ['mixed', '&r_array'=>'array|object'],
'print' => ['int', 'arg'=>'string'],
'print_r' => ['string', 'value'=>'mixed'],
'print_r\'1' => ['true', 'value'=>'mixed', 'return='=>'bool'],
'printf' => ['int', 'format'=>'string', '...values='=>'string|int|float'],
'proc_close' => ['int', 'process'=>'resource'],
'proc_get_status' => ['array{command: string, pid: int, running: bool, signaled: bool, stopped: bool, exitcode: int, termsig: int, stopsig: int}', 'process'=>'resource'],
'proc_nice' => ['bool', 'priority'=>'int'],
'proc_open' => ['resource|false', 'cmd'=>'string|array', 'descriptorspec'=>'array', '&w_pipes'=>'resource[]', 'cwd='=>'?string', 'env='=>'?array', 'other_options='=>'array'],
'proc_terminate' => ['bool', 'process'=>'resource', 'signal='=>'int'],
'projectionObj::__construct' => ['void', 'projectionString'=>'string'],
'projectionObj::getUnits' => ['int'],
'projectionObj::ms_newProjectionObj' => ['projectionObj', 'projectionString'=>'string'],
'property_exists' => ['bool', 'object_or_class'=>'object|string', 'property'=>'string'],
'ps_add_bookmark' => ['int', 'psdoc'=>'resource', 'text'=>'string', 'parent='=>'int', 'open='=>'int'],
'ps_add_launchlink' => ['bool', 'psdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string'],
'ps_add_locallink' => ['bool', 'psdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'page'=>'int', 'dest'=>'string'],
'ps_add_note' => ['bool', 'psdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'contents'=>'string', 'title'=>'string', 'icon'=>'string', 'open'=>'int'],
'ps_add_pdflink' => ['bool', 'psdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string', 'page'=>'int', 'dest'=>'string'],
'ps_add_weblink' => ['bool', 'psdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'url'=>'string'],
'ps_arc' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'ps_arcn' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'ps_begin_page' => ['bool', 'psdoc'=>'resource', 'width'=>'float', 'height'=>'float'],
'ps_begin_pattern' => ['int', 'psdoc'=>'resource', 'width'=>'float', 'height'=>'float', 'xstep'=>'float', 'ystep'=>'float', 'painttype'=>'int'],
'ps_begin_template' => ['int', 'psdoc'=>'resource', 'width'=>'float', 'height'=>'float'],
'ps_circle' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float', 'radius'=>'float'],
'ps_clip' => ['bool', 'psdoc'=>'resource'],
'ps_close' => ['bool', 'psdoc'=>'resource'],
'ps_close_image' => ['void', 'psdoc'=>'resource', 'imageid'=>'int'],
'ps_closepath' => ['bool', 'psdoc'=>'resource'],
'ps_closepath_stroke' => ['bool', 'psdoc'=>'resource'],
'ps_continue_text' => ['bool', 'psdoc'=>'resource', 'text'=>'string'],
'ps_curveto' => ['bool', 'psdoc'=>'resource', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'ps_delete' => ['bool', 'psdoc'=>'resource'],
'ps_end_page' => ['bool', 'psdoc'=>'resource'],
'ps_end_pattern' => ['bool', 'psdoc'=>'resource'],
'ps_end_template' => ['bool', 'psdoc'=>'resource'],
'ps_fill' => ['bool', 'psdoc'=>'resource'],
'ps_fill_stroke' => ['bool', 'psdoc'=>'resource'],
'ps_findfont' => ['int', 'psdoc'=>'resource', 'fontname'=>'string', 'encoding'=>'string', 'embed='=>'bool'],
'ps_get_buffer' => ['string', 'psdoc'=>'resource'],
'ps_get_parameter' => ['string', 'psdoc'=>'resource', 'name'=>'string', 'modifier='=>'float'],
'ps_get_value' => ['float', 'psdoc'=>'resource', 'name'=>'string', 'modifier='=>'float'],
'ps_hyphenate' => ['array', 'psdoc'=>'resource', 'text'=>'string'],
'ps_include_file' => ['bool', 'psdoc'=>'resource', 'file'=>'string'],
'ps_lineto' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float'],
'ps_makespotcolor' => ['int', 'psdoc'=>'resource', 'name'=>'string', 'reserved='=>'int'],
'ps_moveto' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float'],
'ps_new' => ['resource'],
'ps_open_file' => ['bool', 'psdoc'=>'resource', 'filename='=>'string'],
'ps_open_image' => ['int', 'psdoc'=>'resource', 'type'=>'string', 'source'=>'string', 'data'=>'string', 'length'=>'int', 'width'=>'int', 'height'=>'int', 'components'=>'int', 'bpc'=>'int', 'params'=>'string'],
'ps_open_image_file' => ['int', 'psdoc'=>'resource', 'type'=>'string', 'filename'=>'string', 'stringparam='=>'string', 'intparam='=>'int'],
'ps_open_memory_image' => ['int', 'psdoc'=>'resource', 'gd'=>'int'],
'ps_place_image' => ['bool', 'psdoc'=>'resource', 'imageid'=>'int', 'x'=>'float', 'y'=>'float', 'scale'=>'float'],
'ps_rect' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'ps_restore' => ['bool', 'psdoc'=>'resource'],
'ps_rotate' => ['bool', 'psdoc'=>'resource', 'rot'=>'float'],
'ps_save' => ['bool', 'psdoc'=>'resource'],
'ps_scale' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float'],
'ps_set_border_color' => ['bool', 'psdoc'=>'resource', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'ps_set_border_dash' => ['bool', 'psdoc'=>'resource', 'black'=>'float', 'white'=>'float'],
'ps_set_border_style' => ['bool', 'psdoc'=>'resource', 'style'=>'string', 'width'=>'float'],
'ps_set_info' => ['bool', 'p'=>'resource', 'key'=>'string', 'value'=>'string'],
'ps_set_parameter' => ['bool', 'psdoc'=>'resource', 'name'=>'string', 'value'=>'string'],
'ps_set_text_pos' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float'],
'ps_set_value' => ['bool', 'psdoc'=>'resource', 'name'=>'string', 'value'=>'float'],
'ps_setcolor' => ['bool', 'psdoc'=>'resource', 'type'=>'string', 'colorspace'=>'string', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float'],
'ps_setdash' => ['bool', 'psdoc'=>'resource', 'on'=>'float', 'off'=>'float'],
'ps_setflat' => ['bool', 'psdoc'=>'resource', 'value'=>'float'],
'ps_setfont' => ['bool', 'psdoc'=>'resource', 'fontid'=>'int', 'size'=>'float'],
'ps_setgray' => ['bool', 'psdoc'=>'resource', 'gray'=>'float'],
'ps_setlinecap' => ['bool', 'psdoc'=>'resource', 'type'=>'int'],
'ps_setlinejoin' => ['bool', 'psdoc'=>'resource', 'type'=>'int'],
'ps_setlinewidth' => ['bool', 'psdoc'=>'resource', 'width'=>'float'],
'ps_setmiterlimit' => ['bool', 'psdoc'=>'resource', 'value'=>'float'],
'ps_setoverprintmode' => ['bool', 'psdoc'=>'resource', 'mode'=>'int'],
'ps_setpolydash' => ['bool', 'psdoc'=>'resource', 'arr'=>'float'],
'ps_shading' => ['int', 'psdoc'=>'resource', 'type'=>'string', 'x0'=>'float', 'y0'=>'float', 'x1'=>'float', 'y1'=>'float', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float', 'optlist'=>'string'],
'ps_shading_pattern' => ['int', 'psdoc'=>'resource', 'shadingid'=>'int', 'optlist'=>'string'],
'ps_shfill' => ['bool', 'psdoc'=>'resource', 'shadingid'=>'int'],
'ps_show' => ['bool', 'psdoc'=>'resource', 'text'=>'string'],
'ps_show2' => ['bool', 'psdoc'=>'resource', 'text'=>'string', 'length'=>'int'],
'ps_show_boxed' => ['int', 'psdoc'=>'resource', 'text'=>'string', 'left'=>'float', 'bottom'=>'float', 'width'=>'float', 'height'=>'float', 'hmode'=>'string', 'feature='=>'string'],
'ps_show_xy' => ['bool', 'psdoc'=>'resource', 'text'=>'string', 'x'=>'float', 'y'=>'float'],
'ps_show_xy2' => ['bool', 'psdoc'=>'resource', 'text'=>'string', 'length'=>'int', 'xcoor'=>'float', 'ycoor'=>'float'],
'ps_string_geometry' => ['array', 'psdoc'=>'resource', 'text'=>'string', 'fontid='=>'int', 'size='=>'float'],
'ps_stringwidth' => ['float', 'psdoc'=>'resource', 'text'=>'string', 'fontid='=>'int', 'size='=>'float'],
'ps_stroke' => ['bool', 'psdoc'=>'resource'],
'ps_symbol' => ['bool', 'psdoc'=>'resource', 'ord'=>'int'],
'ps_symbol_name' => ['string', 'psdoc'=>'resource', 'ord'=>'int', 'fontid='=>'int'],
'ps_symbol_width' => ['float', 'psdoc'=>'resource', 'ord'=>'int', 'fontid='=>'int', 'size='=>'float'],
'ps_translate' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float'],
'pspell_add_to_personal' => ['bool', 'dictionary'=>'PSpell\Dictionary', 'word'=>'string'],
'pspell_add_to_session' => ['bool', 'dictionary'=>'PSpell\Dictionary', 'word'=>'string'],
'pspell_check' => ['bool', 'dictionary'=>'PSpell\Dictionary', 'word'=>'string'],
'pspell_clear_session' => ['bool', 'dictionary'=>'PSpell\Dictionary'],
'pspell_config_create' => ['int|false', 'language'=>'string', 'spelling='=>'string', 'jargon='=>'string', 'encoding='=>'string'],
'pspell_config_data_dir' => ['bool', 'config'=>'PSpell\Config', 'directory'=>'string'],
'pspell_config_dict_dir' => ['bool', 'config'=>'PSpell\Config', 'directory'=>'string'],
'pspell_config_ignore' => ['bool', 'config'=>'PSpell\Config', 'min_length'=>'int'],
'pspell_config_mode' => ['bool', 'config'=>'PSpell\Config', 'mode'=>'int'],
'pspell_config_personal' => ['bool', 'config'=>'PSpell\Config', 'filename'=>'string'],
'pspell_config_repl' => ['bool', 'config'=>'PSpell\Config', 'filename'=>'string'],
'pspell_config_runtogether' => ['bool', 'config'=>'PSpell\Config', 'allow'=>'bool'],
'pspell_config_save_repl' => ['bool', 'config'=>'PSpell\Config', 'save'=>'bool'],
'pspell_new' => ['int|false', 'language'=>'string', 'spelling='=>'string', 'jargon='=>'string', 'encoding='=>'string', 'mode='=>'int'],
'pspell_new_config' => ['int|false', 'config'=>'PSpell\Config'],
'pspell_new_personal' => ['int|false', 'filename'=>'string', 'language'=>'string', 'spelling='=>'string', 'jargon='=>'string', 'encoding='=>'string', 'mode='=>'int'],
'pspell_save_wordlist' => ['bool', 'dictionary'=>'PSpell\Dictionary'],
'pspell_store_replacement' => ['bool', 'dictionary'=>'PSpell\Dictionary', 'misspelled'=>'string', 'correct'=>'string'],
'pspell_suggest' => ['array', 'dictionary'=>'PSpell\Dictionary', 'word'=>'string'],
'putenv' => ['bool', 'assignment'=>'string'],
'px_close' => ['bool', 'pxdoc'=>'resource'],
'px_create_fp' => ['bool', 'pxdoc'=>'resource', 'file'=>'resource', 'fielddesc'=>'array'],
'px_date2string' => ['string', 'pxdoc'=>'resource', 'value'=>'int', 'format'=>'string'],
'px_delete' => ['bool', 'pxdoc'=>'resource'],
'px_delete_record' => ['bool', 'pxdoc'=>'resource', 'num'=>'int'],
'px_get_field' => ['array', 'pxdoc'=>'resource', 'fieldno'=>'int'],
'px_get_info' => ['array', 'pxdoc'=>'resource'],
'px_get_parameter' => ['string', 'pxdoc'=>'resource', 'name'=>'string'],
'px_get_record' => ['array', 'pxdoc'=>'resource', 'num'=>'int', 'mode='=>'int'],
'px_get_schema' => ['array', 'pxdoc'=>'resource', 'mode='=>'int'],
'px_get_value' => ['float', 'pxdoc'=>'resource', 'name'=>'string'],
'px_insert_record' => ['int', 'pxdoc'=>'resource', 'data'=>'array'],
'px_new' => ['resource'],
'px_numfields' => ['int', 'pxdoc'=>'resource'],
'px_numrecords' => ['int', 'pxdoc'=>'resource'],
'px_open_fp' => ['bool', 'pxdoc'=>'resource', 'file'=>'resource'],
'px_put_record' => ['bool', 'pxdoc'=>'resource', 'record'=>'array', 'recpos='=>'int'],
'px_retrieve_record' => ['array', 'pxdoc'=>'resource', 'num'=>'int', 'mode='=>'int'],
'px_set_blob_file' => ['bool', 'pxdoc'=>'resource', 'filename'=>'string'],
'px_set_parameter' => ['bool', 'pxdoc'=>'resource', 'name'=>'string', 'value'=>'string'],
'px_set_tablename' => ['void', 'pxdoc'=>'resource', 'name'=>'string'],
'px_set_targetencoding' => ['bool', 'pxdoc'=>'resource', 'encoding'=>'string'],
'px_set_value' => ['bool', 'pxdoc'=>'resource', 'name'=>'string', 'value'=>'float'],
'px_timestamp2string' => ['string', 'pxdoc'=>'resource', 'value'=>'float', 'format'=>'string'],
'px_update_record' => ['bool', 'pxdoc'=>'resource', 'data'=>'array', 'num'=>'int'],
'qdom_error' => ['string'],
'qdom_tree' => ['QDomDocument', 'doc'=>'string'],
'querymapObj::convertToString' => ['string'],
'querymapObj::free' => ['void'],
'querymapObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'querymapObj::updateFromString' => ['int', 'snippet'=>'string'],
'QuickHashIntHash::__construct' => ['void', 'size'=>'int', 'options='=>'int'],
'QuickHashIntHash::add' => ['bool', 'key'=>'int', 'value='=>'int'],
'QuickHashIntHash::delete' => ['bool', 'key'=>'int'],
'QuickHashIntHash::exists' => ['bool', 'key'=>'int'],
'QuickHashIntHash::get' => ['int', 'key'=>'int'],
'QuickHashIntHash::getSize' => ['int'],
'QuickHashIntHash::loadFromFile' => ['QuickHashIntHash', 'filename'=>'string', 'options='=>'int'],
'QuickHashIntHash::loadFromString' => ['QuickHashIntHash', 'contents'=>'string', 'options='=>'int'],
'QuickHashIntHash::saveToFile' => ['void', 'filename'=>'string'],
'QuickHashIntHash::saveToString' => ['string'],
'QuickHashIntHash::set' => ['bool', 'key'=>'int', 'value'=>'int'],
'QuickHashIntHash::update' => ['bool', 'key'=>'int', 'value'=>'int'],
'QuickHashIntSet::__construct' => ['void', 'size'=>'int', 'options='=>'int'],
'QuickHashIntSet::add' => ['bool', 'key'=>'int'],
'QuickHashIntSet::delete' => ['bool', 'key'=>'int'],
'QuickHashIntSet::exists' => ['bool', 'key'=>'int'],
'QuickHashIntSet::getSize' => ['int'],
'QuickHashIntSet::loadFromFile' => ['QuickHashIntSet', 'filename'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashIntSet::loadFromString' => ['QuickHashIntSet', 'contents'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashIntSet::saveToFile' => ['void', 'filename'=>'string'],
'QuickHashIntSet::saveToString' => ['string'],
'QuickHashIntStringHash::__construct' => ['void', 'size'=>'int', 'options='=>'int'],
'QuickHashIntStringHash::add' => ['bool', 'key'=>'int', 'value'=>'string'],
'QuickHashIntStringHash::delete' => ['bool', 'key'=>'int'],
'QuickHashIntStringHash::exists' => ['bool', 'key'=>'int'],
'QuickHashIntStringHash::get' => ['mixed', 'key'=>'int'],
'QuickHashIntStringHash::getSize' => ['int'],
'QuickHashIntStringHash::loadFromFile' => ['QuickHashIntStringHash', 'filename'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashIntStringHash::loadFromString' => ['QuickHashIntStringHash', 'contents'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashIntStringHash::saveToFile' => ['void', 'filename'=>'string'],
'QuickHashIntStringHash::saveToString' => ['string'],
'QuickHashIntStringHash::set' => ['int', 'key'=>'int', 'value'=>'string'],
'QuickHashIntStringHash::update' => ['bool', 'key'=>'int', 'value'=>'string'],
'QuickHashStringIntHash::__construct' => ['void', 'size'=>'int', 'options='=>'int'],
'QuickHashStringIntHash::add' => ['bool', 'key'=>'string', 'value'=>'int'],
'QuickHashStringIntHash::delete' => ['bool', 'key'=>'string'],
'QuickHashStringIntHash::exists' => ['bool', 'key'=>'string'],
'QuickHashStringIntHash::get' => ['mixed', 'key'=>'string'],
'QuickHashStringIntHash::getSize' => ['int'],
'QuickHashStringIntHash::loadFromFile' => ['QuickHashStringIntHash', 'filename'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashStringIntHash::loadFromString' => ['QuickHashStringIntHash', 'contents'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashStringIntHash::saveToFile' => ['void', 'filename'=>'string'],
'QuickHashStringIntHash::saveToString' => ['string'],
'QuickHashStringIntHash::set' => ['int', 'key'=>'string', 'value'=>'int'],
'QuickHashStringIntHash::update' => ['bool', 'key'=>'string', 'value'=>'int'],
'quoted_printable_decode' => ['string', 'string'=>'string'],
'quoted_printable_encode' => ['string', 'string'=>'string'],
'quotemeta' => ['string', 'string'=>'string'],
'rad2deg' => ['float', 'num'=>'float'],
'radius_acct_open' => ['resource|false'],
'radius_add_server' => ['bool', 'radius_handle'=>'resource', 'hostname'=>'string', 'port'=>'int', 'secret'=>'string', 'timeout'=>'int', 'max_tries'=>'int'],
'radius_auth_open' => ['resource|false'],
'radius_close' => ['bool', 'radius_handle'=>'resource'],
'radius_config' => ['bool', 'radius_handle'=>'resource', 'file'=>'string'],
'radius_create_request' => ['bool', 'radius_handle'=>'resource', 'type'=>'int'],
'radius_cvt_addr' => ['string', 'data'=>'string'],
'radius_cvt_int' => ['int', 'data'=>'string'],
'radius_cvt_string' => ['string', 'data'=>'string'],
'radius_demangle' => ['string', 'radius_handle'=>'resource', 'mangled'=>'string'],
'radius_demangle_mppe_key' => ['string', 'radius_handle'=>'resource', 'mangled'=>'string'],
'radius_get_attr' => ['mixed', 'radius_handle'=>'resource'],
'radius_get_tagged_attr_data' => ['string', 'data'=>'string'],
'radius_get_tagged_attr_tag' => ['int', 'data'=>'string'],
'radius_get_vendor_attr' => ['array', 'data'=>'string'],
'radius_put_addr' => ['bool', 'radius_handle'=>'resource', 'type'=>'int', 'addr'=>'string'],
'radius_put_attr' => ['bool', 'radius_handle'=>'resource', 'type'=>'int', 'value'=>'string'],
'radius_put_int' => ['bool', 'radius_handle'=>'resource', 'type'=>'int', 'value'=>'int'],
'radius_put_string' => ['bool', 'radius_handle'=>'resource', 'type'=>'int', 'value'=>'string'],
'radius_put_vendor_addr' => ['bool', 'radius_handle'=>'resource', 'vendor'=>'int', 'type'=>'int', 'addr'=>'string'],
'radius_put_vendor_attr' => ['bool', 'radius_handle'=>'resource', 'vendor'=>'int', 'type'=>'int', 'value'=>'string'],
'radius_put_vendor_int' => ['bool', 'radius_handle'=>'resource', 'vendor'=>'int', 'type'=>'int', 'value'=>'int'],
'radius_put_vendor_string' => ['bool', 'radius_handle'=>'resource', 'vendor'=>'int', 'type'=>'int', 'value'=>'string'],
'radius_request_authenticator' => ['string', 'radius_handle'=>'resource'],
'radius_salt_encrypt_attr' => ['string', 'radius_handle'=>'resource', 'data'=>'string'],
'radius_send_request' => ['int|false', 'radius_handle'=>'resource'],
'radius_server_secret' => ['string', 'radius_handle'=>'resource'],
'radius_strerror' => ['string', 'radius_handle'=>'resource'],
'rand' => ['int', 'min'=>'int', 'max'=>'int'],
'rand\'1' => ['int'],
'random_bytes' => ['string', 'length'=>'int'],
'random_int' => ['int', 'min'=>'int', 'max'=>'int'],
'range' => ['array', 'start'=>'mixed', 'end'=>'mixed', 'step='=>'int|float'],
'RangeException::__clone' => ['void'],
'RangeException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?RangeException'],
'RangeException::__toString' => ['string'],
'RangeException::getCode' => ['int'],
'RangeException::getFile' => ['string'],
'RangeException::getLine' => ['int'],
'RangeException::getMessage' => ['string'],
'RangeException::getPrevious' => ['Throwable|RangeException|null'],
'RangeException::getTrace' => ['list<array<string,mixed>>'],
'RangeException::getTraceAsString' => ['string'],
'rar_allow_broken_set' => ['bool', 'rarfile'=>'RarArchive', 'allow_broken'=>'bool'],
'rar_broken_is' => ['bool', 'rarfile'=>'rararchive'],
'rar_close' => ['bool', 'rarfile'=>'rararchive'],
'rar_comment_get' => ['string', 'rarfile'=>'rararchive'],
'rar_entry_get' => ['RarEntry', 'rarfile'=>'RarArchive', 'entryname'=>'string'],
'rar_list' => ['RarArchive', 'rarfile'=>'rararchive'],
'rar_open' => ['RarArchive', 'filename'=>'string', 'password='=>'string', 'volume_callback='=>'callable'],
'rar_solid_is' => ['bool', 'rarfile'=>'rararchive'],
'rar_wrapper_cache_stats' => ['string'],
'RarArchive::__toString' => ['string'],
'RarArchive::close' => ['bool'],
'RarArchive::getComment' => ['string|null'],
'RarArchive::getEntries' => ['RarEntry[]|false'],
'RarArchive::getEntry' => ['RarEntry|false', 'entryname'=>'string'],
'RarArchive::isBroken' => ['bool'],
'RarArchive::isSolid' => ['bool'],
'RarArchive::open' => ['RarArchive|false', 'filename'=>'string', 'password='=>'string', 'volume_callback='=>'callable'],
'RarArchive::setAllowBroken' => ['bool', 'allow_broken'=>'bool'],
'RarEntry::__toString' => ['string'],
'RarEntry::extract' => ['bool', 'dir'=>'string', 'filepath='=>'string', 'password='=>'string', 'extended_data='=>'bool'],
'RarEntry::getAttr' => ['int|false'],
'RarEntry::getCrc' => ['string|false'],
'RarEntry::getFileTime' => ['string|false'],
'RarEntry::getHostOs' => ['int|false'],
'RarEntry::getMethod' => ['int|false'],
'RarEntry::getName' => ['string|false'],
'RarEntry::getPackedSize' => ['int|false'],
'RarEntry::getStream' => ['resource|false', 'password='=>'string'],
'RarEntry::getUnpackedSize' => ['int|false'],
'RarEntry::getVersion' => ['int|false'],
'RarEntry::isDirectory' => ['bool'],
'RarEntry::isEncrypted' => ['bool'],
'RarException::getCode' => ['int'],
'RarException::getFile' => ['string'],
'RarException::getLine' => ['int'],
'RarException::getMessage' => ['string'],
'RarException::getPrevious' => ['Exception|Throwable'],
'RarException::getTrace' => ['list<array<string,mixed>>'],
'RarException::getTraceAsString' => ['string'],
'RarException::isUsingExceptions' => ['bool'],
'RarException::setUsingExceptions' => ['RarEntry', 'using_exceptions'=>'bool'],
'rawurldecode' => ['string', 'string'=>'string'],
'rawurlencode' => ['string', 'string'=>'string'],
'rd_kafka_err2str' => ['string', 'err'=>'int'],
'rd_kafka_errno' => ['int'],
'rd_kafka_errno2err' => ['int', 'errnox'=>'int'],
'rd_kafka_offset_tail' => ['int', 'cnt'=>'int'],
'RdKafka::addBrokers' => ['int', 'broker_list'=>'string'],
'RdKafka::flush' => ['int', 'timeout_ms'=>'int'],
'RdKafka::getMetadata' => ['RdKafka\Metadata', 'all_topics'=>'bool', 'only_topic='=>'RdKafka\Topic', 'timeout_ms'=>'int'],
'RdKafka::getOutQLen' => ['int'],
'RdKafka::newQueue' => ['RdKafka\Queue'],
'RdKafka::newTopic' => ['RdKafka\Topic', 'topic_name'=>'string', 'topic_conf='=>'?RdKafka\TopicConf'],
'RdKafka::poll' => ['void', 'timeout_ms'=>'int'],
'RdKafka::setLogLevel' => ['void', 'level'=>'int'],
'RdKafka\Conf::dump' => ['array<string, string>'],
'RdKafka\Conf::set' => ['void', 'name'=>'string', 'value'=>'string'],
'RdKafka\Conf::setDefaultTopicConf' => ['void', 'topic_conf'=>'RdKafka\TopicConf'],
'RdKafka\Conf::setDrMsgCb' => ['void', 'callback'=>'callable'],
'RdKafka\Conf::setErrorCb' => ['void', 'callback'=>'callable'],
'RdKafka\Conf::setRebalanceCb' => ['void', 'callback'=>'callable'],
'RdKafka\Conf::setStatsCb' => ['void', 'callback'=>'callable'],
'RdKafka\Consumer::__construct' => ['void', 'conf='=>'?RdKafka\Conf'],
'RdKafka\Consumer::addBrokers' => ['int', 'broker_list'=>'string'],
'RdKafka\Consumer::getMetadata' => ['RdKafka\Metadata', 'all_topics'=>'bool', 'only_topic='=>'RdKafka\Topic', 'timeout_ms'=>'int'],
'RdKafka\Consumer::getOutQLen' => ['int'],
'RdKafka\Consumer::newQueue' => ['RdKafka\Queue'],
'RdKafka\Consumer::newTopic' => ['RdKafka\ConsumerTopic', 'topic_name'=>'string', 'topic_conf='=>'?RdKafka\TopicConf'],
'RdKafka\Consumer::poll' => ['void', 'timeout_ms'=>'int'],
'RdKafka\Consumer::setLogLevel' => ['void', 'level'=>'int'],
'RdKafka\ConsumerTopic::__construct' => ['void'],
'RdKafka\ConsumerTopic::consume' => ['RdKafka\Message', 'partition'=>'int', 'timeout_ms'=>'int'],
'RdKafka\ConsumerTopic::consumeQueueStart' => ['void', 'partition'=>'int', 'offset'=>'int', 'queue'=>'RdKafka\Queue'],
'RdKafka\ConsumerTopic::consumeStart' => ['void', 'partition'=>'int', 'offset'=>'int'],
'RdKafka\ConsumerTopic::consumeStop' => ['void', 'partition'=>'int'],
'RdKafka\ConsumerTopic::getName' => ['string'],
'RdKafka\ConsumerTopic::offsetStore' => ['void', 'partition'=>'int', 'offset'=>'int'],
'RdKafka\KafkaConsumer::__construct' => ['void', 'conf'=>'RdKafka\Conf'],
'RdKafka\KafkaConsumer::assign' => ['void', 'topic_partitions='=>'RdKafka\TopicPartition[]|null'],
'RdKafka\KafkaConsumer::commit' => ['void', 'message_or_offsets='=>'RdKafka\Message|RdKafka\TopicPartition[]|null'],
'RdKafka\KafkaConsumer::commitAsync' => ['void', 'message_or_offsets='=>'RdKafka\Message|RdKafka\TopicPartition[]|null'],
'RdKafka\KafkaConsumer::consume' => ['RdKafka\Message', 'timeout_ms'=>'int'],
'RdKafka\KafkaConsumer::getAssignment' => ['RdKafka\TopicPartition[]'],
'RdKafka\KafkaConsumer::getMetadata' => ['RdKafka\Metadata', 'all_topics'=>'bool', 'only_topic='=>'RdKafka\KafkaConsumerTopic', 'timeout_ms'=>'int'],
'RdKafka\KafkaConsumer::getSubscription' => ['array'],
'RdKafka\KafkaConsumer::subscribe' => ['void', 'topics'=>'array'],
'RdKafka\KafkaConsumer::unsubscribe' => ['void'],
'RdKafka\KafkaConsumerTopic::getName' => ['string'],
'RdKafka\KafkaConsumerTopic::offsetStore' => ['void', 'partition'=>'int', 'offset'=>'int'],
'RdKafka\Message::errstr' => ['string'],
'RdKafka\Metadata::getBrokers' => ['RdKafka\Metadata\Collection'],
'RdKafka\Metadata::getOrigBrokerId' => ['int'],
'RdKafka\Metadata::getOrigBrokerName' => ['string'],
'RdKafka\Metadata::getTopics' => ['RdKafka\Metadata\Collection|RdKafka\Metadata\Topic[]'],
'RdKafka\Metadata\Collection::__construct' => ['void'],
'RdKafka\Metadata\Collection::count' => ['int'],
'RdKafka\Metadata\Collection::current' => ['mixed'],
'RdKafka\Metadata\Collection::key' => ['mixed'],
'RdKafka\Metadata\Collection::next' => ['void'],
'RdKafka\Metadata\Collection::rewind' => ['void'],
'RdKafka\Metadata\Collection::valid' => ['bool'],
'RdKafka\Metadata\Partition::getErr' => ['mixed'],
'RdKafka\Metadata\Partition::getId' => ['int'],
'RdKafka\Metadata\Partition::getIsrs' => ['mixed'],
'RdKafka\Metadata\Partition::getLeader' => ['mixed'],
'RdKafka\Metadata\Partition::getReplicas' => ['mixed'],
'RdKafka\Metadata\Topic::getErr' => ['mixed'],
'RdKafka\Metadata\Topic::getPartitions' => ['RdKafka\Metadata\Partition[]'],
'RdKafka\Metadata\Topic::getTopic' => ['string'],
'RdKafka\Producer::__construct' => ['void', 'conf='=>'?RdKafka\Conf'],
'RdKafka\Producer::addBrokers' => ['int', 'broker_list'=>'string'],
'RdKafka\Producer::getMetadata' => ['RdKafka\Metadata', 'all_topics'=>'bool', 'only_topic='=>'RdKafka\Topic', 'timeout_ms'=>'int'],
'RdKafka\Producer::getOutQLen' => ['int'],
'RdKafka\Producer::newQueue' => ['RdKafka\Queue'],
'RdKafka\Producer::newTopic' => ['RdKafka\ProducerTopic', 'topic_name'=>'string', 'topic_conf='=>'?RdKafka\TopicConf'],
'RdKafka\Producer::poll' => ['void', 'timeout_ms'=>'int'],
'RdKafka\Producer::setLogLevel' => ['void', 'level'=>'int'],
'RdKafka\ProducerTopic::__construct' => ['void'],
'RdKafka\ProducerTopic::getName' => ['string'],
'RdKafka\ProducerTopic::produce' => ['void', 'partition'=>'int', 'msgflags'=>'int', 'payload'=>'string', 'key='=>'?string'],
'RdKafka\ProducerTopic::producev' => ['void', 'partition'=>'int', 'msgflags'=>'int', 'payload'=>'string', 'key='=>'?string', 'headers='=>'?array<string, string>', 'timestamp_ms='=>'?int', 'opaque='=>'?string'],
'RdKafka\Queue::__construct' => ['void'],
'RdKafka\Queue::consume' => ['?RdKafka\Message', 'timeout_ms'=>'string'],
'RdKafka\Topic::getName' => ['string'],
'RdKafka\TopicConf::dump' => ['array<string, string>'],
'RdKafka\TopicConf::set' => ['void', 'name'=>'string', 'value'=>'string'],
'RdKafka\TopicConf::setPartitioner' => ['void', 'partitioner'=>'int'],
'RdKafka\TopicPartition::__construct' => ['void', 'topic'=>'string', 'partition'=>'int', 'offset='=>'int'],
'RdKafka\TopicPartition::getOffset' => ['int'],
'RdKafka\TopicPartition::getPartition' => ['int'],
'RdKafka\TopicPartition::getTopic' => ['string'],
'RdKafka\TopicPartition::setOffset' => ['void', 'offset'=>'string'],
'RdKafka\TopicPartition::setPartition' => ['void', 'partition'=>'string'],
'RdKafka\TopicPartition::setTopic' => ['void', 'topic_name'=>'string'],
'readdir' => ['string|false', 'dir_handle='=>'resource'],
'readfile' => ['int|false', 'filename'=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'readgzfile' => ['int|false', 'filename'=>'string', 'use_include_path='=>'int'],
'readline' => ['string|false', 'prompt='=>'?string'],
'readline_add_history' => ['bool', 'prompt'=>'string'],
'readline_callback_handler_install' => ['bool', 'prompt'=>'string', 'callback'=>'callable'],
'readline_callback_handler_remove' => ['bool'],
'readline_callback_read_char' => ['void'],
'readline_clear_history' => ['bool'],
'readline_completion_function' => ['bool', 'callback'=>'callable'],
'readline_info' => ['mixed', 'var_name='=>'string', 'value='=>'string|int|bool'],
'readline_list_history' => ['array'],
'readline_on_new_line' => ['void'],
'readline_read_history' => ['bool', 'filename='=>'string'],
'readline_redisplay' => ['void'],
'readline_write_history' => ['bool', 'filename='=>'string'],
'readlink' => ['string|false', 'path'=>'string'],
'realpath' => ['string|false', 'path'=>'string'],
'realpath_cache_get' => ['array'],
'realpath_cache_size' => ['int'],
'recode' => ['string', 'request'=>'string', 'string'=>'string'],
'recode_file' => ['bool', 'request'=>'string', 'input'=>'resource', 'output'=>'resource'],
'recode_string' => ['string|false', 'request'=>'string', 'string'=>'string'],
'rectObj::__construct' => ['void'],
'rectObj::draw' => ['int', 'map'=>'mapObj', 'layer'=>'layerObj', 'img'=>'imageObj', 'class_index'=>'int', 'text'=>'string'],
'rectObj::fit' => ['float', 'width'=>'int', 'height'=>'int'],
'rectObj::ms_newRectObj' => ['rectObj'],
'rectObj::project' => ['int', 'in'=>'projectionObj', 'out'=>'projectionObj'],
'rectObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'rectObj::setextent' => ['void', 'minx'=>'float', 'miny'=>'float', 'maxx'=>'float', 'maxy'=>'float'],
'RecursiveArrayIterator::__construct' => ['void', 'array='=>'array|object', 'flags='=>'int'],
'RecursiveArrayIterator::append' => ['void', 'value'=>'mixed'],
'RecursiveArrayIterator::asort' => ['void'],
'RecursiveArrayIterator::count' => ['int'],
'RecursiveArrayIterator::current' => ['mixed'],
'RecursiveArrayIterator::getArrayCopy' => ['array'],
'RecursiveArrayIterator::getChildren' => ['RecursiveArrayIterator'],
'RecursiveArrayIterator::getFlags' => ['void'],
'RecursiveArrayIterator::hasChildren' => ['bool'],
'RecursiveArrayIterator::key' => ['false|int|string'],
'RecursiveArrayIterator::ksort' => ['void'],
'RecursiveArrayIterator::natcasesort' => ['void'],
'RecursiveArrayIterator::natsort' => ['void'],
'RecursiveArrayIterator::next' => ['void'],
'RecursiveArrayIterator::offsetExists' => ['void', 'index'=>'string'],
'RecursiveArrayIterator::offsetGet' => ['mixed', 'index'=>'string'],
'RecursiveArrayIterator::offsetSet' => ['void', 'index'=>'string', 'newval'=>'string'],
'RecursiveArrayIterator::offsetUnset' => ['void', 'index'=>'string'],
'RecursiveArrayIterator::rewind' => ['void'],
'RecursiveArrayIterator::seek' => ['void', 'position'=>'int'],
'RecursiveArrayIterator::serialize' => ['string'],
'RecursiveArrayIterator::setFlags' => ['void', 'flags'=>'string'],
'RecursiveArrayIterator::uasort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'RecursiveArrayIterator::uksort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'RecursiveArrayIterator::unserialize' => ['string', 'serialized'=>'string'],
'RecursiveArrayIterator::valid' => ['bool'],
'RecursiveCachingIterator::__construct' => ['void', 'it'=>'Iterator', 'flags='=>'int'],
'RecursiveCachingIterator::__toString' => ['string'],
'RecursiveCachingIterator::count' => ['int'],
'RecursiveCachingIterator::current' => ['void'],
'RecursiveCachingIterator::getCache' => ['array'],
'RecursiveCachingIterator::getChildren' => ['RecursiveCachingIterator'],
'RecursiveCachingIterator::getFlags' => ['int'],
'RecursiveCachingIterator::getInnerIterator' => ['Iterator'],
'RecursiveCachingIterator::hasChildren' => ['bool'],
'RecursiveCachingIterator::hasNext' => ['bool'],
'RecursiveCachingIterator::key' => ['bool|float|int|string'],
'RecursiveCachingIterator::next' => ['void'],
'RecursiveCachingIterator::offsetExists' => ['bool', 'index'=>'string'],
'RecursiveCachingIterator::offsetGet' => ['string', 'index'=>'string'],
'RecursiveCachingIterator::offsetSet' => ['void', 'index'=>'string', 'newval'=>'string'],
'RecursiveCachingIterator::offsetUnset' => ['void', 'index'=>'string'],
'RecursiveCachingIterator::rewind' => ['void'],
'RecursiveCachingIterator::setFlags' => ['void', 'flags'=>'int'],
'RecursiveCachingIterator::valid' => ['bool'],
'RecursiveCallbackFilterIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator', 'func'=>'callable'],
'RecursiveCallbackFilterIterator::accept' => ['bool'],
'RecursiveCallbackFilterIterator::current' => ['mixed'],
'RecursiveCallbackFilterIterator::getChildren' => ['RecursiveCallbackFilterIterator'],
'RecursiveCallbackFilterIterator::getInnerIterator' => ['Iterator'],
'RecursiveCallbackFilterIterator::hasChildren' => ['bool'],
'RecursiveCallbackFilterIterator::key' => ['bool|float|int|string'],
'RecursiveCallbackFilterIterator::next' => ['void'],
'RecursiveCallbackFilterIterator::rewind' => ['void'],
'RecursiveCallbackFilterIterator::valid' => ['bool'],
'RecursiveDirectoryIterator::__construct' => ['void', 'path'=>'string', 'flags='=>'int'],
'RecursiveDirectoryIterator::__toString' => ['string'],
'RecursiveDirectoryIterator::_bad_state_ex' => [''],
'RecursiveDirectoryIterator::current' => ['string|SplFileInfo|FilesystemIterator'],
'RecursiveDirectoryIterator::getATime' => ['int'],
'RecursiveDirectoryIterator::getBasename' => ['string', 'suffix='=>'string'],
'RecursiveDirectoryIterator::getChildren' => ['RecursiveDirectoryIterator'],
'RecursiveDirectoryIterator::getCTime' => ['int'],
'RecursiveDirectoryIterator::getExtension' => ['string'],
'RecursiveDirectoryIterator::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'RecursiveDirectoryIterator::getFilename' => ['string'],
'RecursiveDirectoryIterator::getFlags' => ['int'],
'RecursiveDirectoryIterator::getGroup' => ['int'],
'RecursiveDirectoryIterator::getInode' => ['int'],
'RecursiveDirectoryIterator::getLinkTarget' => ['string'],
'RecursiveDirectoryIterator::getMTime' => ['int'],
'RecursiveDirectoryIterator::getOwner' => ['int'],
'RecursiveDirectoryIterator::getPath' => ['string'],
'RecursiveDirectoryIterator::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'RecursiveDirectoryIterator::getPathname' => ['string'],
'RecursiveDirectoryIterator::getPerms' => ['int'],
'RecursiveDirectoryIterator::getRealPath' => ['string'],
'RecursiveDirectoryIterator::getSize' => ['int'],
'RecursiveDirectoryIterator::getSubPath' => ['string'],
'RecursiveDirectoryIterator::getSubPathname' => ['string'],
'RecursiveDirectoryIterator::getType' => ['string'],
'RecursiveDirectoryIterator::hasChildren' => ['bool', 'allow_links='=>'bool'],
'RecursiveDirectoryIterator::isDir' => ['bool'],
'RecursiveDirectoryIterator::isDot' => ['bool'],
'RecursiveDirectoryIterator::isExecutable' => ['bool'],
'RecursiveDirectoryIterator::isFile' => ['bool'],
'RecursiveDirectoryIterator::isLink' => ['bool'],
'RecursiveDirectoryIterator::isReadable' => ['bool'],
'RecursiveDirectoryIterator::isWritable' => ['bool'],
'RecursiveDirectoryIterator::key' => ['string'],
'RecursiveDirectoryIterator::next' => ['void'],
'RecursiveDirectoryIterator::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'RecursiveDirectoryIterator::rewind' => ['void'],
'RecursiveDirectoryIterator::seek' => ['void', 'position'=>'int'],
'RecursiveDirectoryIterator::setFileClass' => ['void', 'class_name='=>'string'],
'RecursiveDirectoryIterator::setFlags' => ['void', 'flags='=>'int'],
'RecursiveDirectoryIterator::setInfoClass' => ['void', 'class_name='=>'string'],
'RecursiveDirectoryIterator::valid' => ['bool'],
'RecursiveFilterIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator'],
'RecursiveFilterIterator::accept' => ['bool'],
'RecursiveFilterIterator::current' => ['mixed'],
'RecursiveFilterIterator::getChildren' => ['RecursiveFilterIterator'],
'RecursiveFilterIterator::getInnerIterator' => ['Iterator'],
'RecursiveFilterIterator::hasChildren' => ['bool'],
'RecursiveFilterIterator::key' => ['mixed'],
'RecursiveFilterIterator::next' => ['void'],
'RecursiveFilterIterator::rewind' => ['void'],
'RecursiveFilterIterator::valid' => ['bool'],
'RecursiveIterator::__construct' => ['void'],
'RecursiveIterator::current' => ['mixed'],
'RecursiveIterator::getChildren' => ['RecursiveIterator'],
'RecursiveIterator::hasChildren' => ['bool'],
'RecursiveIterator::key' => ['int|string'],
'RecursiveIterator::next' => ['void'],
'RecursiveIterator::rewind' => ['void'],
'RecursiveIterator::valid' => ['bool'],
'RecursiveIteratorIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator|IteratorAggregate', 'mode='=>'int', 'flags='=>'int'],
'RecursiveIteratorIterator::beginChildren' => ['void'],
'RecursiveIteratorIterator::beginIteration' => ['RecursiveIterator'],
'RecursiveIteratorIterator::callGetChildren' => ['RecursiveIterator'],
'RecursiveIteratorIterator::callHasChildren' => ['bool'],
'RecursiveIteratorIterator::current' => ['mixed'],
'RecursiveIteratorIterator::endChildren' => ['void'],
'RecursiveIteratorIterator::endIteration' => ['RecursiveIterator'],
'RecursiveIteratorIterator::getDepth' => ['int'],
'RecursiveIteratorIterator::getInnerIterator' => ['RecursiveIterator'],
'RecursiveIteratorIterator::getMaxDepth' => ['int|false'],
'RecursiveIteratorIterator::getSubIterator' => ['RecursiveIterator', 'level='=>'int'],
'RecursiveIteratorIterator::key' => ['mixed'],
'RecursiveIteratorIterator::next' => ['void'],
'RecursiveIteratorIterator::nextElement' => ['void'],
'RecursiveIteratorIterator::rewind' => ['void'],
'RecursiveIteratorIterator::setMaxDepth' => ['void', 'max_depth='=>'int'],
'RecursiveIteratorIterator::valid' => ['bool'],
'RecursiveRegexIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator', 'regex'=>'string', 'mode='=>'int', 'flags='=>'int', 'preg_flags='=>'int'],
'RecursiveRegexIterator::accept' => ['bool'],
'RecursiveRegexIterator::current' => [''],
'RecursiveRegexIterator::getChildren' => ['RecursiveRegexIterator'],
'RecursiveRegexIterator::getFlags' => ['int'],
'RecursiveRegexIterator::getInnerIterator' => ['Iterator'],
'RecursiveRegexIterator::getMode' => ['int'],
'RecursiveRegexIterator::getPregFlags' => ['int'],
'RecursiveRegexIterator::getRegex' => ['string'],
'RecursiveRegexIterator::hasChildren' => ['bool'],
'RecursiveRegexIterator::key' => [''],
'RecursiveRegexIterator::next' => [''],
'RecursiveRegexIterator::rewind' => [''],
'RecursiveRegexIterator::setFlags' => ['void', 'new_flags'=>'int'],
'RecursiveRegexIterator::setMode' => ['void', 'new_mode'=>'int'],
'RecursiveRegexIterator::setPregFlags' => ['void', 'new_flags'=>'int'],
'RecursiveRegexIterator::valid' => [''],
'RecursiveTreeIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator|IteratorAggregate', 'flags='=>'int', 'cit_flags='=>'int', 'mode'=>'int'],
'RecursiveTreeIterator::beginChildren' => ['void'],
'RecursiveTreeIterator::beginIteration' => ['RecursiveIterator'],
'RecursiveTreeIterator::callGetChildren' => ['RecursiveIterator'],
'RecursiveTreeIterator::callHasChildren' => ['bool'],
'RecursiveTreeIterator::current' => ['string'],
'RecursiveTreeIterator::endChildren' => ['void'],
'RecursiveTreeIterator::endIteration' => ['void'],
'RecursiveTreeIterator::getDepth' => ['int'],
'RecursiveTreeIterator::getEntry' => ['string'],
'RecursiveTreeIterator::getInnerIterator' => ['RecursiveIterator'],
'RecursiveTreeIterator::getMaxDepth' => ['false|int'],
'RecursiveTreeIterator::getPostfix' => ['string'],
'RecursiveTreeIterator::getPrefix' => ['string'],
'RecursiveTreeIterator::getSubIterator' => ['RecursiveIterator', 'level='=>'int'],
'RecursiveTreeIterator::key' => ['string'],
'RecursiveTreeIterator::next' => ['void'],
'RecursiveTreeIterator::nextElement' => ['void'],
'RecursiveTreeIterator::rewind' => ['void'],
'RecursiveTreeIterator::setMaxDepth' => ['void', 'max_depth='=>'int'],
'RecursiveTreeIterator::setPostfix' => ['void', 'prefix'=>'string'],
'RecursiveTreeIterator::setPrefixPart' => ['void', 'part'=>'int', 'prefix'=>'string'],
'RecursiveTreeIterator::valid' => ['bool'],
'Redis::__construct' => ['void'],
'Redis::__destruct' => ['void'],
'Redis::_prefix' => ['string', 'value'=>'mixed'],
'Redis::_serialize' => ['mixed', 'value'=>'mixed'],
'Redis::_unserialize' => ['mixed', 'value'=>'string'],
'Redis::append' => ['int', 'key'=>'string', 'value'=>'string'],
'Redis::auth' => ['bool', 'password'=>'string'],
'Redis::bgRewriteAOF' => ['bool'],
'Redis::bgSave' => ['bool'],
'Redis::bitCount' => ['int', 'key'=>'string'],
'Redis::bitOp' => ['int', 'operation'=>'string', 'ret_key'=>'string', 'key'=>'string', '...other_keys='=>'string'],
'Redis::bitpos' => ['int', 'key'=>'string', 'bit'=>'int', 'start='=>'int', 'end='=>'int'],
'Redis::blPop' => ['array', 'keys'=>'string[]', 'timeout'=>'int'],
'Redis::blPop\'1' => ['array', 'key'=>'string', 'timeout_or_key'=>'int|string', '...extra_args'=>'int|string'],
'Redis::brPop' => ['array', 'keys'=>'string[]', 'timeout'=>'int'],
'Redis::brPop\'1' => ['array', 'key'=>'string', 'timeout_or_key'=>'int|string', '...extra_args'=>'int|string'],
'Redis::brpoplpush' => ['string|false', 'srcKey'=>'string', 'dstKey'=>'string', 'timeout'=>'int'],
'Redis::clearLastError' => ['bool'],
'Redis::client' => ['mixed', 'command'=>'string', 'arg='=>'string'],
'Redis::close' => ['bool'],
'Redis::command' => ['', '...args'=>''],
'Redis::config' => ['string', 'operation'=>'string', 'key'=>'string', 'value='=>'string'],
'Redis::connect' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'float', 'reserved='=>'null', 'retry_interval='=>'?int', 'read_timeout='=>'float'],
'Redis::dbSize' => ['int'],
'Redis::debug' => ['', 'key'=>''],
'Redis::decr' => ['int', 'key'=>'string'],
'Redis::decrBy' => ['int', 'key'=>'string', 'value'=>'int'],
'Redis::decrByFloat' => ['float', 'key'=>'string', 'value'=>'float'],
'Redis::del' => ['int', 'key'=>'string', '...args'=>'string'],
'Redis::del\'1' => ['int', 'key'=>'string[]'],
'Redis::delete' => ['int', 'key'=>'string', '...args'=>'string'],
'Redis::delete\'1' => ['int', 'key'=>'string[]'],
'Redis::discard' => [''],
'Redis::dump' => ['string|false', 'key'=>'string'],
'Redis::echo' => ['string', 'message'=>'string'],
'Redis::eval' => ['mixed', 'script'=>'', 'args='=>'', 'numKeys='=>''],
'Redis::evalSha' => ['mixed', 'scriptSha'=>'string', 'args='=>'array', 'numKeys='=>'int'],
'Redis::evaluate' => ['mixed', 'script'=>'string', 'args='=>'array', 'numKeys='=>'int'],
'Redis::evaluateSha' => ['', 'scriptSha'=>'string', 'args='=>'array', 'numKeys='=>'int'],
'Redis::exec' => ['array'],
'Redis::exists' => ['int', 'keys'=>'string|string[]'],
'Redis::exists\'1' => ['int', '...keys'=>'string'],
'Redis::expire' => ['bool', 'key'=>'string', 'ttl'=>'int'],
'Redis::expireAt' => ['bool', 'key'=>'string', 'expiry'=>'int'],
'Redis::flushAll' => ['bool', 'async='=>'bool'],
'Redis::flushDb' => ['bool', 'async='=>'bool'],
'Redis::geoAdd' => ['int', 'key'=>'string', 'longitude'=>'float', 'latitude'=>'float', 'member'=>'string', '...other_triples='=>'string|int|float'],
'Redis::geoDist' => ['float', 'key'=>'string', 'member1'=>'string', 'member2'=>'string', 'unit='=>'string'],
'Redis::geoHash' => ['array<int,string>', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'Redis::geoPos' => ['array<int,array{0:string,1:string}>', 'key'=>'string', 'member'=>'string', '...members='=>'string'],
'Redis::geoRadius' => ['array<int,mixed>|int', 'key'=>'string', 'longitude'=>'float', 'latitude'=>'float', 'radius'=>'float', 'unit'=>'float', 'options='=>'array<string,mixed>'],
'Redis::geoRadiusByMember' => ['array<int,mixed>|int', 'key'=>'string', 'member'=>'string', 'radius'=>'float', 'units'=>'string', 'options='=>'array<string,mixed>'],
'Redis::get' => ['string|false', 'key'=>'string'],
'Redis::getAuth' => ['string|false|null'],
'Redis::getBit' => ['int', 'key'=>'string', 'offset'=>'int'],
'Redis::getDBNum' => ['int|false'],
'Redis::getHost' => ['string|false'],
'Redis::getKeys' => ['array<int,string>', 'pattern'=>'string'],
'Redis::getLastError' => ['?string'],
'Redis::getMode' => ['int'],
'Redis::getMultiple' => ['array', 'keys'=>'string[]'],
'Redis::getOption' => ['int', 'name'=>'int'],
'Redis::getPersistentID' => ['string|false|null'],
'Redis::getPort' => ['int|false'],
'Redis::getRange' => ['int', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::getReadTimeout' => ['float|false'],
'Redis::getSet' => ['string', 'key'=>'string', 'string'=>'string'],
'Redis::getTimeout' => ['float|false'],
'Redis::hDel' => ['int|false', 'key'=>'string', 'hashKey1'=>'string', '...otherHashKeys='=>'string'],
'Redis::hExists' => ['bool', 'key'=>'string', 'hashKey'=>'string'],
'Redis::hGet' => ['string|false', 'key'=>'string', 'hashKey'=>'string'],
'Redis::hGetAll' => ['array', 'key'=>'string'],
'Redis::hIncrBy' => ['int', 'key'=>'string', 'hashKey'=>'string', 'value'=>'int'],
'Redis::hIncrByFloat' => ['float', 'key'=>'string', 'field'=>'string', 'increment'=>'float'],
'Redis::hKeys' => ['array', 'key'=>'string'],
'Redis::hLen' => ['int|false', 'key'=>'string'],
'Redis::hMGet' => ['array', 'key'=>'string', 'hashKeys'=>'array'],
'Redis::hMSet' => ['bool', 'key'=>'string', 'hashKeys'=>'array'],
'Redis::hScan' => ['array', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'Redis::hSet' => ['int|false', 'key'=>'string', 'hashKey'=>'string', 'value'=>'string'],
'Redis::hSetNx' => ['bool', 'key'=>'string', 'hashKey'=>'string', 'value'=>'string'],
'Redis::hStrLen' => ['', 'key'=>'', 'member'=>''],
'Redis::hVals' => ['array', 'key'=>'string'],
'Redis::incr' => ['int', 'key'=>'string'],
'Redis::incrBy' => ['int', 'key'=>'string', 'value'=>'int'],
'Redis::incrByFloat' => ['float', 'key'=>'string', 'value'=>'float'],
'Redis::info' => ['array', 'option='=>'string'],
'Redis::isConnected' => ['bool'],
'Redis::keys' => ['array<int,string>', 'pattern'=>'string'],
'Redis::lastSave' => ['int'],
'Redis::lGet' => ['string', 'key'=>'string', 'index'=>'int'],
'Redis::lGetRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::lIndex' => ['string|false', 'key'=>'string', 'index'=>'int'],
'Redis::lInsert' => ['int', 'key'=>'string', 'position'=>'int', 'pivot'=>'string', 'value'=>'string'],
'Redis::listTrim' => ['', 'key'=>'string', 'start'=>'int', 'stop'=>'int'],
'Redis::lLen' => ['int|false', 'key'=>'string'],
'Redis::lPop' => ['string|false', 'key'=>'string'],
'Redis::lPush' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'Redis::lPushx' => ['int|false', 'key'=>'string', 'value'=>'string'],
'Redis::lRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::lRem' => ['int|false', 'key'=>'string', 'value'=>'string', 'count'=>'int'],
'Redis::lRemove' => ['int', 'key'=>'string', 'value'=>'string', 'count'=>'int'],
'Redis::lSet' => ['bool', 'key'=>'string', 'index'=>'int', 'value'=>'string'],
'Redis::lSize' => ['int', 'key'=>'string'],
'Redis::lTrim' => ['array|false', 'key'=>'string', 'start'=>'int', 'stop'=>'int'],
'Redis::mGet' => ['array', 'keys'=>'string[]'],
'Redis::migrate' => ['bool', 'host'=>'string', 'port'=>'int', 'key'=>'string|string[]', 'db'=>'int', 'timeout'=>'int', 'copy='=>'bool', 'replace='=>'bool'],
'Redis::move' => ['bool', 'key'=>'string', 'dbindex'=>'int'],
'Redis::mSet' => ['bool', 'pairs'=>'array'],
'Redis::mSetNx' => ['bool', 'pairs'=>'array'],
'Redis::multi' => ['Redis', 'mode='=>'int'],
'Redis::object' => ['string|long|false', 'info'=>'string', 'key'=>'string'],
'Redis::open' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'float', 'reserved='=>'null', 'retry_interval='=>'?int', 'read_timeout='=>'float'],
'Redis::pconnect' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'float', 'persistent_id='=>'string', 'retry_interval='=>'?int'],
'Redis::persist' => ['bool', 'key'=>'string'],
'Redis::pExpire' => ['bool', 'key'=>'string', 'ttl'=>'int'],
'Redis::pexpireAt' => ['bool', 'key'=>'string', 'expiry'=>'int'],
'Redis::pfAdd' => ['bool', 'key'=>'string', 'elements'=>'array'],
'Redis::pfCount' => ['int', 'key'=>'array|string'],
'Redis::pfMerge' => ['bool', 'destkey'=>'string', 'sourcekeys'=>'array'],
'Redis::ping' => ['string'],
'Redis::pipeline' => ['Redis'],
'Redis::popen' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'float', 'persistent_id='=>'string', 'retry_interval='=>'?int'],
'Redis::psetex' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'Redis::psubscribe' => ['', 'patterns'=>'array', 'callback'=>'array|string'],
'Redis::pttl' => ['int|false', 'key'=>'string'],
'Redis::publish' => ['int', 'channel'=>'string', 'message'=>'string'],
'Redis::pubsub' => ['array|int', 'keyword'=>'string', 'argument='=>'array|string'],
'Redis::punsubscribe' => ['', 'pattern'=>'string', '...other_patterns='=>'string'],
'Redis::randomKey' => ['string'],
'Redis::rawCommand' => ['mixed', 'command'=>'string', '...arguments='=>'mixed'],
'Redis::rename' => ['bool', 'srckey'=>'string', 'dstkey'=>'string'],
'Redis::renameKey' => ['bool', 'srckey'=>'string', 'dstkey'=>'string'],
'Redis::renameNx' => ['bool', 'srckey'=>'string', 'dstkey'=>'string'],
'Redis::resetStat' => ['bool'],
'Redis::restore' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'Redis::role' => ['array', 'nodeParams'=>'string|array{0:string,1:int}'],
'Redis::rPop' => ['string|false', 'key'=>'string'],
'Redis::rpoplpush' => ['string', 'srcKey'=>'string', 'dstKey'=>'string'],
'Redis::rPush' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'Redis::rPushx' => ['int|false', 'key'=>'string', 'value'=>'string'],
'Redis::sAdd' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'Redis::sAddArray' => ['bool', 'key'=>'string', 'values'=>'array'],
'Redis::save' => ['bool'],
'Redis::scan' => ['array<int,string>|false', '&rw_iterator'=>'?int', 'pattern='=>'?string', 'count='=>'?int'],
'Redis::sCard' => ['int', 'key'=>'string'],
'Redis::sContains' => ['', 'key'=>'string', 'value'=>'string'],
'Redis::script' => ['mixed', 'command'=>'string', '...args='=>'mixed'],
'Redis::sDiff' => ['array', 'key1'=>'string', '...other_keys='=>'string'],
'Redis::sDiffStore' => ['int|false', 'dstKey'=>'string', 'key'=>'string', '...other_keys='=>'string'],
'Redis::select' => ['bool', 'dbindex'=>'int'],
'Redis::sendEcho' => ['string', 'msg'=>'string'],
'Redis::set' => ['bool', 'key'=>'string', 'value'=>'mixed', 'options='=>'array'],
'Redis::set\'1' => ['bool', 'key'=>'string', 'value'=>'mixed', 'timeout='=>'int'],
'Redis::setBit' => ['int', 'key'=>'string', 'offset'=>'int', 'value'=>'int'],
'Redis::setEx' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'Redis::setNx' => ['bool', 'key'=>'string', 'value'=>'string'],
'Redis::setOption' => ['bool', 'name'=>'int', 'value'=>'mixed'],
'Redis::setRange' => ['int', 'key'=>'string', 'offset'=>'int', 'end'=>'int'],
'Redis::setTimeout' => ['', 'key'=>'string', 'ttl'=>'int'],
'Redis::sGetMembers' => ['', 'key'=>'string'],
'Redis::sInter' => ['array|false', 'key'=>'string', '...other_keys='=>'string'],
'Redis::sInterStore' => ['int|false', 'dstKey'=>'string', 'key'=>'string', '...other_keys='=>'string'],
'Redis::sIsMember' => ['bool', 'key'=>'string', 'value'=>'string'],
'Redis::slave' => ['bool', 'host'=>'string', 'port'=>'int'],
'Redis::slave\'1' => ['bool', 'host'=>'string', 'port'=>'int'],
'Redis::slaveof' => ['bool', 'host='=>'string', 'port='=>'int'],
'Redis::slowLog' => ['mixed', 'operation'=>'string', 'length='=>'int'],
'Redis::sMembers' => ['array', 'key'=>'string'],
'Redis::sMove' => ['bool', 'srcKey'=>'string', 'dstKey'=>'string', 'member'=>'string'],
'Redis::sort' => ['array|int', 'key'=>'string', 'options='=>'array'],
'Redis::sortAsc' => ['array', 'key'=>'string', 'pattern='=>'string', 'get='=>'string', 'start='=>'int', 'end='=>'int', 'getList='=>'bool'],
'Redis::sortAscAlpha' => ['array', 'key'=>'string', 'pattern='=>'', 'get='=>'string', 'start='=>'int', 'end='=>'int', 'getList='=>'bool'],
'Redis::sortDesc' => ['array', 'key'=>'string', 'pattern='=>'', 'get='=>'string', 'start='=>'int', 'end='=>'int', 'getList='=>'bool'],
'Redis::sortDescAlpha' => ['array', 'key'=>'string', 'pattern='=>'', 'get='=>'string', 'start='=>'int', 'end='=>'int', 'getList='=>'bool'],
'Redis::sPop' => ['string|false', 'key'=>'string'],
'Redis::sRandMember' => ['array|string|false', 'key'=>'string', 'count='=>'int'],
'Redis::sRem' => ['int', 'key'=>'string', 'member1'=>'string', '...other_members='=>'string'],
'Redis::sRemove' => ['int', 'key'=>'string', 'member1'=>'string', '...other_members='=>'string'],
'Redis::sScan' => ['array|bool', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'Redis::sSize' => ['int', 'key'=>'string'],
'Redis::strLen' => ['int', 'key'=>'string'],
'Redis::subscribe' => ['mixed|null', 'channels'=>'array', 'callback'=>'string|array'],
'Redis::substr' => ['', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::sUnion' => ['array', 'key'=>'string', '...other_keys='=>'string'],
'Redis::sUnionStore' => ['int', 'dstKey'=>'string', 'key'=>'string', '...other_keys='=>'string'],
'Redis::swapdb' => ['bool', 'srcdb'=>'int', 'dstdb'=>'int'],
'Redis::time' => ['array'],
'Redis::ttl' => ['int|false', 'key'=>'string'],
'Redis::type' => ['int', 'key'=>'string'],
'Redis::unlink' => ['int', 'key'=>'string', '...args'=>'string'],
'Redis::unlink\'1' => ['int', 'key'=>'string[]'],
'Redis::unsubscribe' => ['', 'channel'=>'string', '...other_channels='=>'string'],
'Redis::unwatch' => [''],
'Redis::wait' => ['int', 'numSlaves'=>'int', 'timeout'=>'int'],
'Redis::watch' => ['void', 'key'=>'string', '...other_keys='=>'string'],
'Redis::xack' => ['', 'str_key'=>'string', 'str_group'=>'string', 'arr_ids'=>'array'],
'Redis::xadd' => ['', 'str_key'=>'string', 'str_id'=>'string', 'arr_fields'=>'array', 'i_maxlen='=>'', 'boo_approximate='=>''],
'Redis::xclaim' => ['', 'str_key'=>'string', 'str_group'=>'string', 'str_consumer'=>'string', 'i_min_idle'=>'', 'arr_ids'=>'array', 'arr_opts='=>'array'],
'Redis::xdel' => ['', 'str_key'=>'string', 'arr_ids'=>'array'],
'Redis::xgroup' => ['', 'str_operation'=>'string', 'str_key='=>'string', 'str_arg1='=>'', 'str_arg2='=>'', 'str_arg3='=>''],
'Redis::xinfo' => ['', 'str_cmd'=>'string', 'str_key='=>'string', 'str_group='=>'string'],
'Redis::xlen' => ['', 'key'=>''],
'Redis::xpending' => ['', 'str_key'=>'string', 'str_group'=>'string', 'str_start='=>'', 'str_end='=>'', 'i_count='=>'', 'str_consumer='=>'string'],
'Redis::xrange' => ['', 'str_key'=>'string', 'str_start'=>'', 'str_end'=>'', 'i_count='=>''],
'Redis::xread' => ['', 'arr_streams'=>'array', 'i_count='=>'', 'i_block='=>''],
'Redis::xreadgroup' => ['', 'str_group'=>'string', 'str_consumer'=>'string', 'arr_streams'=>'array', 'i_count='=>'', 'i_block='=>''],
'Redis::xrevrange' => ['', 'str_key'=>'string', 'str_start'=>'', 'str_end'=>'', 'i_count='=>''],
'Redis::xtrim' => ['', 'str_key'=>'string', 'i_maxlen'=>'', 'boo_approximate='=>''],
'Redis::zAdd' => ['int', 'key'=>'string', 'score1'=>'float', 'value1'=>'string', 'score2='=>'float', 'value2='=>'string', 'scoreN='=>'float', 'valueN='=>'string'],
'Redis::zAdd\'1' => ['int', 'options'=>'array', 'key'=>'string', 'score1'=>'float', 'value1'=>'string', 'score2='=>'float', 'value2='=>'string', 'scoreN='=>'float', 'valueN='=>'string'],
'Redis::zCard' => ['int', 'key'=>'string'],
'Redis::zCount' => ['int', 'key'=>'string', 'start'=>'string', 'end'=>'string'],
'Redis::zDelete' => ['int', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'Redis::zDeleteRangeByRank' => ['', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::zDeleteRangeByScore' => ['', 'key'=>'string', 'start'=>'float', 'end'=>'float'],
'Redis::zIncrBy' => ['float', 'key'=>'string', 'value'=>'float', 'member'=>'string'],
'Redis::zInter' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'Redis::zInterStore' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'Redis::zLexCount' => ['int', 'key'=>'string', 'min'=>'string', 'max'=>'string'],
'Redis::zRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'withscores='=>'bool'],
'Redis::zRangeByLex' => ['array|false', 'key'=>'string', 'min'=>'int', 'max'=>'int', 'offset='=>'int', 'limit='=>'int'],
'Redis::zRangeByScore' => ['array', 'key'=>'string', 'start'=>'int|string', 'end'=>'int|string', 'options='=>'array'],
'Redis::zRank' => ['int', 'key'=>'string', 'member'=>'string'],
'Redis::zRem' => ['int', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'Redis::zRemove' => ['int', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'Redis::zRemoveRangeByRank' => ['int', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::zRemoveRangeByScore' => ['int', 'key'=>'string', 'start'=>'float|string', 'end'=>'float|string'],
'Redis::zRemRangeByLex' => ['int', 'key'=>'string', 'min'=>'string', 'max'=>'string'],
'Redis::zRemRangeByRank' => ['int', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::zRemRangeByScore' => ['int', 'key'=>'string', 'start'=>'float|string', 'end'=>'float|string'],
'Redis::zReverseRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'withscore='=>'bool'],
'Redis::zRevRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'withscore='=>'bool'],
'Redis::zRevRangeByLex' => ['array', 'key'=>'string', 'min'=>'string', 'max'=>'string', 'offset='=>'int', 'limit='=>'int'],
'Redis::zRevRangeByScore' => ['array', 'key'=>'string', 'start'=>'string', 'end'=>'string', 'options='=>'array'],
'Redis::zRevRank' => ['int', 'key'=>'string', 'member'=>'string'],
'Redis::zScan' => ['array|bool', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'Redis::zScore' => ['float|false', 'key'=>'string', 'member'=>'string'],
'Redis::zSize' => ['', 'key'=>'string'],
'Redis::zUnion' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'Redis::zUnionStore' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'RedisArray::__call' => ['mixed', 'function_name'=>'string', 'arguments'=>'array'],
'RedisArray::__construct' => ['void', 'name='=>'string', 'hosts='=>'?array', 'opts='=>'?array'],
'RedisArray::_continuum' => [''],
'RedisArray::_distributor' => [''],
'RedisArray::_function' => ['string'],
'RedisArray::_hosts' => ['array'],
'RedisArray::_instance' => ['', 'host'=>''],
'RedisArray::_rehash' => ['', 'callable='=>'callable'],
'RedisArray::_target' => ['string', 'key'=>'string'],
'RedisArray::bgsave' => [''],
'RedisArray::del' => ['bool', 'key'=>'string', '...args'=>'string'],
'RedisArray::delete' => ['bool', 'key'=>'string', '...args'=>'string'],
'RedisArray::delete\'1' => ['bool', 'key'=>'string[]'],
'RedisArray::discard' => [''],
'RedisArray::exec' => ['array'],
'RedisArray::flushAll' => ['bool', 'async='=>'bool'],
'RedisArray::flushDb' => ['bool', 'async='=>'bool'],
'RedisArray::getMultiple' => ['', 'keys'=>''],
'RedisArray::getOption' => ['', 'opt'=>''],
'RedisArray::info' => ['array'],
'RedisArray::keys' => ['array<int,string>', 'pattern'=>''],
'RedisArray::mGet' => ['array', 'keys'=>'string[]'],
'RedisArray::mSet' => ['bool', 'pairs'=>'array'],
'RedisArray::multi' => ['RedisArray', 'host'=>'string', 'mode='=>'int'],
'RedisArray::ping' => ['string'],
'RedisArray::save' => ['bool'],
'RedisArray::select' => ['', 'index'=>''],
'RedisArray::setOption' => ['', 'opt'=>'', 'value'=>''],
'RedisArray::unlink' => ['int', 'key'=>'string', '...other_keys='=>'string'],
'RedisArray::unlink\'1' => ['int', 'key'=>'string[]'],
'RedisArray::unwatch' => [''],
'RedisCluster::__construct' => ['void', 'name'=>'?string', 'seeds='=>'string[]', 'timeout='=>'float', 'readTimeout='=>'float', 'persistent='=>'bool', 'auth='=>'?string'],
'RedisCluster::_masters' => ['array'],
'RedisCluster::_prefix' => ['string', 'value'=>'mixed'],
'RedisCluster::_redir' => [''],
'RedisCluster::_serialize' => ['mixed', 'value'=>'mixed'],
'RedisCluster::_unserialize' => ['mixed', 'value'=>'string'],
'RedisCluster::append' => ['int', 'key'=>'string', 'value'=>'string'],
'RedisCluster::bgrewriteaof' => ['bool', 'nodeParams'=>'string|array{0:string,1:int}'],
'RedisCluster::bgsave' => ['bool', 'nodeParams'=>'string|array{0:string,1:int}'],
'RedisCluster::bitCount' => ['int', 'key'=>'string'],
'RedisCluster::bitOp' => ['int', 'operation'=>'string', 'retKey'=>'string', 'key1'=>'string', '...other_keys='=>'string'],
'RedisCluster::bitpos' => ['int', 'key'=>'string', 'bit'=>'int', 'start='=>'int', 'end='=>'int'],
'RedisCluster::blPop' => ['array', 'keys'=>'array', 'timeout'=>'int'],
'RedisCluster::brPop' => ['array', 'keys'=>'array', 'timeout'=>'int'],
'RedisCluster::brpoplpush' => ['string|false', 'srcKey'=>'string', 'dstKey'=>'string', 'timeout'=>'int'],
'RedisCluster::clearLastError' => ['bool'],
'RedisCluster::client' => ['', 'nodeParams'=>'string|array{0:string,1:int}', 'subCmd='=>'string', '...args='=>''],
'RedisCluster::close' => [''],
'RedisCluster::cluster' => ['mixed', 'nodeParams'=>'string|array{0:string,1:int}', 'command'=>'string', 'arguments='=>'mixed'],
'RedisCluster::command' => ['array|bool'],
'RedisCluster::config' => ['array|bool', 'nodeParams'=>'string|array{0:string,1:int}', 'operation'=>'string', 'key'=>'string', 'value='=>'string'],
'RedisCluster::dbSize' => ['int', 'nodeParams'=>'string|array{0:string,1:int}'],
'RedisCluster::decr' => ['int', 'key'=>'string'],
'RedisCluster::decrBy' => ['int', 'key'=>'string', 'value'=>'int'],
'RedisCluster::del' => ['int', 'key'=>'string', '...other_keys='=>'string'],
'RedisCluster::del\'1' => ['int', 'key'=>'string[]'],
'RedisCluster::discard' => [''],
'RedisCluster::dump' => ['string|false', 'key'=>'string'],
'RedisCluster::echo' => ['string', 'nodeParams'=>'string|array{0:string,1:int}', 'msg'=>'string'],
'RedisCluster::eval' => ['mixed', 'script'=>'', 'args='=>'', 'numKeys='=>''],
'RedisCluster::evalSha' => ['mixed', 'scriptSha'=>'string', 'args='=>'array', 'numKeys='=>'int'],
'RedisCluster::exec' => ['array|void'],
'RedisCluster::exists' => ['bool', 'key'=>'string'],
'RedisCluster::expire' => ['bool', 'key'=>'string', 'ttl'=>'int'],
'RedisCluster::expireAt' => ['bool', 'key'=>'string', 'timestamp'=>'int'],
'RedisCluster::flushAll' => ['bool', 'nodeParams'=>'string|array{0:string,1:int}', 'async='=>'bool'],
'RedisCluster::flushDB' => ['bool', 'nodeParams'=>'string|array{0:string,1:int}', 'async='=>'bool'],
'RedisCluster::geoAdd' => ['int', 'key'=>'string', 'longitude'=>'float', 'latitude'=>'float', 'member'=>'string', '...other_members='=>'float|string'],
'RedisCluster::geoDist' => ['', 'key'=>'string', 'member1'=>'string', 'member2'=>'string', 'unit='=>'string'],
'RedisCluster::geohash' => ['array<int,string>', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'RedisCluster::geopos' => ['array<int,array{0:string,1:string}>', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'RedisCluster::geoRadius' => ['', 'key'=>'string', 'longitude'=>'float', 'latitude'=>'float', 'radius'=>'float', 'radiusUnit'=>'string', 'options='=>'array'],
'RedisCluster::geoRadiusByMember' => ['string[]', 'key'=>'string', 'member'=>'string', 'radius'=>'float', 'radiusUnit'=>'string', 'options='=>'array'],
'RedisCluster::get' => ['string|false', 'key'=>'string'],
'RedisCluster::getBit' => ['int', 'key'=>'string', 'offset'=>'int'],
'RedisCluster::getLastError' => ['?string'],
'RedisCluster::getMode' => ['int'],
'RedisCluster::getOption' => ['int', 'name'=>'string'],
'RedisCluster::getRange' => ['string', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'RedisCluster::getSet' => ['string', 'key'=>'string', 'value'=>'string'],
'RedisCluster::hDel' => ['int|false', 'key'=>'string', 'hashKey'=>'string', '...other_hashKeys='=>'string[]'],
'RedisCluster::hExists' => ['bool', 'key'=>'string', 'hashKey'=>'string'],
'RedisCluster::hGet' => ['string|false', 'key'=>'string', 'hashKey'=>'string'],
'RedisCluster::hGetAll' => ['array', 'key'=>'string'],
'RedisCluster::hIncrBy' => ['int', 'key'=>'string', 'hashKey'=>'string', 'value'=>'int'],
'RedisCluster::hIncrByFloat' => ['float', 'key'=>'string', 'field'=>'string', 'increment'=>'float'],
'RedisCluster::hKeys' => ['array', 'key'=>'string'],
'RedisCluster::hLen' => ['int|false', 'key'=>'string'],
'RedisCluster::hMGet' => ['array', 'key'=>'string', 'hashKeys'=>'array'],
'RedisCluster::hMSet' => ['bool', 'key'=>'string', 'hashKeys'=>'array'],
'RedisCluster::hScan' => ['array', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'RedisCluster::hSet' => ['int', 'key'=>'string', 'hashKey'=>'string', 'value'=>'string'],
'RedisCluster::hSetNx' => ['bool', 'key'=>'string', 'hashKey'=>'string', 'value'=>'string'],
'RedisCluster::hStrlen' => ['int', 'key'=>'string', 'member'=>'string'],
'RedisCluster::hVals' => ['array', 'key'=>'string'],
'RedisCluster::incr' => ['int', 'key'=>'string'],
'RedisCluster::incrBy' => ['int', 'key'=>'string', 'value'=>'int'],
'RedisCluster::incrByFloat' => ['float', 'key'=>'string', 'increment'=>'float'],
'RedisCluster::info' => ['array', 'nodeParams'=>'string|array{0:string,1:int}', 'option='=>'string'],
'RedisCluster::keys' => ['array', 'pattern'=>'string'],
'RedisCluster::lastSave' => ['int', 'nodeParams'=>'string|array{0:string,1:int}'],
'RedisCluster::lGet' => ['', 'key'=>'string', 'index'=>'int'],
'RedisCluster::lIndex' => ['string|false', 'key'=>'string', 'index'=>'int'],
'RedisCluster::lInsert' => ['int', 'key'=>'string', 'position'=>'int', 'pivot'=>'string', 'value'=>'string'],
'RedisCluster::lLen' => ['int', 'key'=>'string'],
'RedisCluster::lPop' => ['string|false', 'key'=>'string'],
'RedisCluster::lPush' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'RedisCluster::lPushx' => ['int|false', 'key'=>'string', 'value'=>'string'],
'RedisCluster::lRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'RedisCluster::lRem' => ['int|false', 'key'=>'string', 'value'=>'string', 'count'=>'int'],
'RedisCluster::lSet' => ['bool', 'key'=>'string', 'index'=>'int', 'value'=>'string'],
'RedisCluster::lTrim' => ['array|false', 'key'=>'string', 'start'=>'int', 'stop'=>'int'],
'RedisCluster::mget' => ['array', 'array'=>'array'],
'RedisCluster::mset' => ['bool', 'array'=>'array'],
'RedisCluster::msetnx' => ['int', 'array'=>'array'],
'RedisCluster::multi' => ['Redis', 'mode='=>'int'],
'RedisCluster::object' => ['string|int|false', 'string'=>'string', 'key'=>'string'],
'RedisCluster::persist' => ['bool', 'key'=>'string'],
'RedisCluster::pExpire' => ['bool', 'key'=>'string', 'ttl'=>'int'],
'RedisCluster::pExpireAt' => ['bool', 'key'=>'string', 'timestamp'=>'int'],
'RedisCluster::pfAdd' => ['bool', 'key'=>'string', 'elements'=>'array'],
'RedisCluster::pfCount' => ['int', 'key'=>'string'],
'RedisCluster::pfMerge' => ['bool', 'destKey'=>'string', 'sourceKeys'=>'array'],
'RedisCluster::ping' => ['string', 'nodeParams'=>'string|array{0:string,1:int}'],
'RedisCluster::psetex' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'RedisCluster::psubscribe' => ['mixed', 'patterns'=>'array', 'callback'=>'string'],
'RedisCluster::pttl' => ['int', 'key'=>'string'],
'RedisCluster::publish' => ['int', 'channel'=>'string', 'message'=>'string'],
'RedisCluster::pubsub' => ['array', 'nodeParams'=>'string', 'keyword'=>'string', '...argument='=>'string'],
'RedisCluster::punSubscribe' => ['', 'channels'=>'', 'callback'=>''],
'RedisCluster::randomKey' => ['string', 'nodeParams'=>'string|array{0:string,1:int}'],
'RedisCluster::rawCommand' => ['mixed', 'nodeParams'=>'string|array{0:string,1:int}', 'command'=>'string', 'arguments='=>'mixed'],
'RedisCluster::rename' => ['bool', 'srcKey'=>'string', 'dstKey'=>'string'],
'RedisCluster::renameNx' => ['bool', 'srcKey'=>'string', 'dstKey'=>'string'],
'RedisCluster::restore' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'RedisCluster::role' => ['array'],
'RedisCluster::rPop' => ['string|false', 'key'=>'string'],
'RedisCluster::rpoplpush' => ['string|false', 'srcKey'=>'string', 'dstKey'=>'string'],
'RedisCluster::rPush' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'RedisCluster::rPushx' => ['int|false', 'key'=>'string', 'value'=>'string'],
'RedisCluster::sAdd' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'RedisCluster::sAddArray' => ['int|false', 'key'=>'string', 'valueArray'=>'array'],
'RedisCluster::save' => ['bool', 'nodeParams'=>'string|array{0:string,1:int}'],
'RedisCluster::scan' => ['array|false', '&iterator'=>'int', 'nodeParams'=>'string|array{0:string,1:int}', 'pattern='=>'string', 'count='=>'int'],
'RedisCluster::sCard' => ['int', 'key'=>'string'],
'RedisCluster::script' => ['string|bool|array', 'nodeParams'=>'string|array{0:string,1:int}', 'command'=>'string', 'script='=>'string', '...other_scripts='=>'string[]'],
'RedisCluster::sDiff' => ['list<string>', 'key1'=>'string', 'key2'=>'string', '...other_keys='=>'string'],
'RedisCluster::sDiffStore' => ['int', 'dstKey'=>'string', 'key1'=>'string', '...other_keys='=>'string'],
'RedisCluster::set' => ['bool', 'key'=>'string', 'value'=>'string', 'timeout='=>'array|int'],
'RedisCluster::setBit' => ['int', 'key'=>'string', 'offset'=>'int', 'value'=>'bool|int'],
'RedisCluster::setex' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'RedisCluster::setnx' => ['bool', 'key'=>'string', 'value'=>'string'],
'RedisCluster::setOption' => ['bool', 'name'=>'string|int', 'value'=>'string|int'],
'RedisCluster::setRange' => ['string', 'key'=>'string', 'offset'=>'int', 'value'=>'string'],
'RedisCluster::sInter' => ['list<string>', 'key'=>'string', '...other_keys='=>'string'],
'RedisCluster::sInterStore' => ['int', 'dstKey'=>'string', 'key'=>'string', '...other_keys='=>'string'],
'RedisCluster::sIsMember' => ['bool', 'key'=>'string', 'value'=>'string'],
'RedisCluster::slowLog' => ['array|int|bool', 'nodeParams'=>'string|array{0:string,1:int}', 'command'=>'string', 'length='=>'int'],
'RedisCluster::sMembers' => ['list<string>', 'key'=>'string'],
'RedisCluster::sMove' => ['bool', 'srcKey'=>'string', 'dstKey'=>'string', 'member'=>'string'],
'RedisCluster::sort' => ['array', 'key'=>'string', 'option='=>'array'],
'RedisCluster::sPop' => ['string', 'key'=>'string'],
'RedisCluster::sRandMember' => ['array|string', 'key'=>'string', 'count='=>'int'],
'RedisCluster::sRem' => ['int', 'key'=>'string', 'member1'=>'string', '...other_members='=>'string'],
'RedisCluster::sScan' => ['array|false', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'null', 'count='=>'int'],
'RedisCluster::strlen' => ['int', 'key'=>'string'],
'RedisCluster::subscribe' => ['mixed', 'channels'=>'array', 'callback'=>'string'],
'RedisCluster::sUnion' => ['list<string>', 'key1'=>'string', '...other_keys='=>'string'],
'RedisCluster::sUnion\'1' => ['list<string>', 'keys'=>'string[]'],
'RedisCluster::sUnionStore' => ['int', 'dstKey'=>'string', 'key1'=>'string', '...other_keys='=>'string'],
'RedisCluster::time' => ['array'],
'RedisCluster::ttl' => ['int', 'key'=>'string'],
'RedisCluster::type' => ['int', 'key'=>'string'],
'RedisCluster::unlink' => ['int', 'key'=>'string', '...other_keys='=>'string'],
'RedisCluster::unSubscribe' => ['', 'channels'=>'', '...other_channels='=>''],
'RedisCluster::unwatch' => [''],
'RedisCluster::watch' => ['void', 'key'=>'string', '...other_keys='=>'string'],
'RedisCluster::xack' => ['', 'str_key'=>'string', 'str_group'=>'string', 'arr_ids'=>'array'],
'RedisCluster::xadd' => ['', 'str_key'=>'string', 'str_id'=>'string', 'arr_fields'=>'array', 'i_maxlen='=>'', 'boo_approximate='=>''],
'RedisCluster::xclaim' => ['', 'str_key'=>'string', 'str_group'=>'string', 'str_consumer'=>'string', 'i_min_idle'=>'', 'arr_ids'=>'array', 'arr_opts='=>'array'],
'RedisCluster::xdel' => ['', 'str_key'=>'string', 'arr_ids'=>'array'],
'RedisCluster::xgroup' => ['', 'str_operation'=>'string', 'str_key='=>'string', 'str_arg1='=>'', 'str_arg2='=>'', 'str_arg3='=>''],
'RedisCluster::xinfo' => ['', 'str_cmd'=>'string', 'str_key='=>'string', 'str_group='=>'string'],
'RedisCluster::xlen' => ['', 'key'=>''],
'RedisCluster::xpending' => ['', 'str_key'=>'string', 'str_group'=>'string', 'str_start='=>'', 'str_end='=>'', 'i_count='=>'', 'str_consumer='=>'string'],
'RedisCluster::xrange' => ['', 'str_key'=>'string', 'str_start'=>'', 'str_end'=>'', 'i_count='=>''],
'RedisCluster::xread' => ['', 'arr_streams'=>'array', 'i_count='=>'', 'i_block='=>''],
'RedisCluster::xreadgroup' => ['', 'str_group'=>'string', 'str_consumer'=>'string', 'arr_streams'=>'array', 'i_count='=>'', 'i_block='=>''],
'RedisCluster::xrevrange' => ['', 'str_key'=>'string', 'str_start'=>'', 'str_end'=>'', 'i_count='=>''],
'RedisCluster::xtrim' => ['', 'str_key'=>'string', 'i_maxlen'=>'', 'boo_approximate='=>''],
'RedisCluster::zAdd' => ['int', 'key'=>'string', 'score1'=>'float', 'value1'=>'string', 'score2='=>'float', 'value2='=>'string', 'scoreN='=>'float', 'valueN='=>'string'],
'RedisCluster::zCard' => ['int', 'key'=>'string'],
'RedisCluster::zCount' => ['int', 'key'=>'string', 'start'=>'string', 'end'=>'string'],
'RedisCluster::zIncrBy' => ['float', 'key'=>'string', 'value'=>'float', 'member'=>'string'],
'RedisCluster::zInterStore' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'RedisCluster::zLexCount' => ['int', 'key'=>'string', 'min'=>'int', 'max'=>'int'],
'RedisCluster::zRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'withscores='=>'bool'],
'RedisCluster::zRangeByLex' => ['array', 'key'=>'string', 'min'=>'int', 'max'=>'int', 'offset='=>'int', 'limit='=>'int'],
'RedisCluster::zRangeByScore' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'options='=>'array'],
'RedisCluster::zRank' => ['int', 'key'=>'string', 'member'=>'string'],
'RedisCluster::zRem' => ['int', 'key'=>'string', 'member1'=>'string', '...other_members='=>'string'],
'RedisCluster::zRemRangeByLex' => ['array', 'key'=>'string', 'min'=>'int', 'max'=>'int'],
'RedisCluster::zRemRangeByRank' => ['int', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'RedisCluster::zRemRangeByScore' => ['int', 'key'=>'string', 'start'=>'float|string', 'end'=>'float|string'],
'RedisCluster::zRevRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'withscore='=>'bool'],
'RedisCluster::zRevRangeByLex' => ['array', 'key'=>'string', 'min'=>'int', 'max'=>'int', 'offset='=>'int', 'limit='=>'int'],
'RedisCluster::zRevRangeByScore' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'options='=>'array'],
'RedisCluster::zRevRank' => ['int', 'key'=>'string', 'member'=>'string'],
'RedisCluster::zScan' => ['array|false', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'RedisCluster::zScore' => ['float', 'key'=>'string', 'member'=>'string'],
'RedisCluster::zUnionStore' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'Reflection::export' => ['?string', 'r'=>'reflector', 'return='=>'bool'],
'Reflection::getModifierNames' => ['array', 'modifiers'=>'int'],
'ReflectionClass::__clone' => ['void'],
'ReflectionClass::__construct' => ['void', 'argument'=>'object|class-string'],
'ReflectionClass::__toString' => ['string'],
'ReflectionClass::export' => ['?string', 'argument'=>'string|object', 'return='=>'bool'],
'ReflectionClass::getAttributes' => ['list<ReflectionAttribute>', 'name='=>'?string', 'flags='=>'int'],
'ReflectionClass::getConstant' => ['mixed', 'name'=>'string'],
'ReflectionClass::getConstants' => ['array<string,mixed>', 'filter=' => '?int'],
'ReflectionClass::getConstructor' => ['?ReflectionMethod'],
'ReflectionClass::getDefaultProperties' => ['array'],
'ReflectionClass::getDocComment' => ['string|false'],
'ReflectionClass::getEndLine' => ['int|false'],
'ReflectionClass::getExtension' => ['?ReflectionExtension'],
'ReflectionClass::getExtensionName' => ['string|false'],
'ReflectionClass::getFileName' => ['string|false'],
'ReflectionClass::getInterfaceNames' => ['list<class-string>'],
'ReflectionClass::getInterfaces' => ['array<class-string, ReflectionClass>'],
'ReflectionClass::getMethod' => ['ReflectionMethod', 'name'=>'string'],
'ReflectionClass::getMethods' => ['list<ReflectionMethod>', 'filter='=>'int'],
'ReflectionClass::getModifiers' => ['int'],
'ReflectionClass::getName' => ['class-string'],
'ReflectionClass::getNamespaceName' => ['string'],
'ReflectionClass::getParentClass' => ['ReflectionClass|false'],
'ReflectionClass::getProperties' => ['list<ReflectionProperty>', 'filter='=>'int'],
'ReflectionClass::getProperty' => ['ReflectionProperty', 'name'=>'string'],
'ReflectionClass::getReflectionConstant' => ['ReflectionClassConstant|false', 'name'=>'string'],
'ReflectionClass::getReflectionConstants' => ['list<ReflectionClassConstant>', 'filter='=>'?int'],
'ReflectionClass::getShortName' => ['string'],
'ReflectionClass::getStartLine' => ['int|false'],
'ReflectionClass::getStaticProperties' => ['array<string, ReflectionProperty>'],
'ReflectionClass::getStaticPropertyValue' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'ReflectionClass::getTraitAliases' => ['array<string,string>|null'],
'ReflectionClass::getTraitNames' => ['list<trait-string>|null'],
'ReflectionClass::getTraits' => ['array<trait-string,ReflectionClass>'],
'ReflectionClass::hasConstant' => ['bool', 'name'=>'string'],
'ReflectionClass::hasMethod' => ['bool', 'name'=>'string'],
'ReflectionClass::hasProperty' => ['bool', 'name'=>'string'],
'ReflectionClass::implementsInterface' => ['bool', 'interface_name'=>'interface-string|ReflectionClass'],
'ReflectionClass::inNamespace' => ['bool'],
'ReflectionClass::isAbstract' => ['bool'],
'ReflectionClass::isAnonymous' => ['bool'],
'ReflectionClass::isCloneable' => ['bool'],
'ReflectionClass::isFinal' => ['bool'],
'ReflectionClass::isInstance' => ['bool', 'object'=>'object'],
'ReflectionClass::isInstantiable' => ['bool'],
'ReflectionClass::isInterface' => ['bool'],
'ReflectionClass::isInternal' => ['bool'],
'ReflectionClass::isIterable' => ['bool'],
'ReflectionClass::isIterateable' => ['bool'],
'ReflectionClass::isSubclassOf' => ['bool', 'class'=>'class-string|ReflectionClass'],
'ReflectionClass::isTrait' => ['bool'],
'ReflectionClass::isUserDefined' => ['bool'],
'ReflectionClass::newInstance' => ['object', '...args='=>'mixed'],
'ReflectionClass::newInstanceArgs' => ['object', 'args='=>'array<array-key, mixed>'],
'ReflectionClass::newInstanceWithoutConstructor' => ['object'],
'ReflectionClass::setStaticPropertyValue' => ['void', 'name'=>'string', 'value'=>'mixed'],
'ReflectionClassConstant::__construct' => ['void', 'class'=>'mixed', 'name'=>'string'],
'ReflectionClassConstant::__toString' => ['string'],
'ReflectionClassConstant::export' => ['string', 'class'=>'mixed', 'name'=>'string', 'return='=>'bool'],
'ReflectionClassConstant::getAttributes' => ['list<ReflectionAttribute>', 'name='=>'?string', 'flags='=>'int'],
'ReflectionClassConstant::getDeclaringClass' => ['ReflectionClass'],
'ReflectionClassConstant::getDocComment' => ['string|false'],
'ReflectionClassConstant::getModifiers' => ['int'],
'ReflectionClassConstant::getName' => ['string'],
'ReflectionClassConstant::getValue' => ['scalar|array<scalar>|null'],
'ReflectionClassConstant::isPrivate' => ['bool'],
'ReflectionClassConstant::isProtected' => ['bool'],
'ReflectionClassConstant::isPublic' => ['bool'],
'ReflectionExtension::__clone' => ['void'],
'ReflectionExtension::__construct' => ['void', 'name'=>'string'],
'ReflectionExtension::__toString' => ['string'],
'ReflectionExtension::export' => ['?string', 'name'=>'string', 'return='=>'bool'],
'ReflectionExtension::getClasses' => ['array<class-string,ReflectionClass>'],
'ReflectionExtension::getClassNames' => ['list<class-string>'],
'ReflectionExtension::getConstants' => ['array<string,mixed>'],
'ReflectionExtension::getDependencies' => ['array<string,string>'],
'ReflectionExtension::getFunctions' => ['array<string,ReflectionFunction>'],
'ReflectionExtension::getINIEntries' => ['array<string,mixed>'],
'ReflectionExtension::getName' => ['string'],
'ReflectionExtension::getVersion' => ['string'],
'ReflectionExtension::info' => ['void'],
'ReflectionExtension::isPersistent' => ['bool'],
'ReflectionExtension::isTemporary' => ['bool'],
'ReflectionFunction::__construct' => ['void', 'name'=>'callable-string|Closure'],
'ReflectionFunction::__toString' => ['string'],
'ReflectionFunction::export' => ['?string', 'name'=>'string', 'return='=>'bool'],
'ReflectionFunction::getClosure' => ['?Closure'],
'ReflectionFunction::getClosureScopeClass' => ['ReflectionClass'],
'ReflectionFunction::getClosureThis' => ['bool'],
'ReflectionFunction::getDocComment' => ['string|false'],
'ReflectionFunction::getEndLine' => ['int|false'],
'ReflectionFunction::getExtension' => ['?ReflectionExtension'],
'ReflectionFunction::getExtensionName' => ['string|false'],
'ReflectionFunction::getFileName' => ['string|false'],
'ReflectionFunction::getName' => ['callable-string'],
'ReflectionFunction::getNamespaceName' => ['string'],
'ReflectionFunction::getNumberOfParameters' => ['int'],
'ReflectionFunction::getNumberOfRequiredParameters' => ['int'],
'ReflectionFunction::getParameters' => ['list<ReflectionParameter>'],
'ReflectionFunction::getReturnType' => ['?ReflectionType'],
'ReflectionFunction::getShortName' => ['string'],
'ReflectionFunction::getStartLine' => ['int|false'],
'ReflectionFunction::getStaticVariables' => ['array'],
'ReflectionFunction::hasReturnType' => ['bool'],
'ReflectionFunction::inNamespace' => ['bool'],
'ReflectionFunction::invoke' => ['mixed', '...args='=>'mixed'],
'ReflectionFunction::invokeArgs' => ['mixed', 'args'=>'array'],
'ReflectionFunction::isClosure' => ['bool'],
'ReflectionFunction::isDeprecated' => ['bool'],
'ReflectionFunction::isDisabled' => ['bool'],
'ReflectionFunction::isGenerator' => ['bool'],
'ReflectionFunction::isInternal' => ['bool'],
'ReflectionFunction::isUserDefined' => ['bool'],
'ReflectionFunction::isVariadic' => ['bool'],
'ReflectionFunction::returnsReference' => ['bool'],
'ReflectionFunctionAbstract::__clone' => ['void'],
'ReflectionFunctionAbstract::__toString' => ['string'],
'ReflectionFunctionAbstract::export' => ['?string'],
'ReflectionFunctionAbstract::getAttributes' => ['list<ReflectionAttribute>', 'name='=>'?string', 'flags='=>'int'],
'ReflectionFunctionAbstract::getClosureScopeClass' => ['ReflectionClass|null'],
'ReflectionFunctionAbstract::getClosureThis' => ['object|null'],
'ReflectionFunctionAbstract::getDocComment' => ['string|false'],
'ReflectionFunctionAbstract::getEndLine' => ['int|false'],
'ReflectionFunctionAbstract::getExtension' => ['ReflectionExtension'],
'ReflectionFunctionAbstract::getExtensionName' => ['string'],
'ReflectionFunctionAbstract::getFileName' => ['string|false'],
'ReflectionFunctionAbstract::getName' => ['string'],
'ReflectionFunctionAbstract::getNamespaceName' => ['string'],
'ReflectionFunctionAbstract::getNumberOfParameters' => ['int'],
'ReflectionFunctionAbstract::getNumberOfRequiredParameters' => ['int'],
'ReflectionFunctionAbstract::getParameters' => ['list<ReflectionParameter>'],
'ReflectionFunctionAbstract::getReturnType' => ['?ReflectionType'],
'ReflectionFunctionAbstract::getShortName' => ['string'],
'ReflectionFunctionAbstract::getStartLine' => ['int|false'],
'ReflectionFunctionAbstract::getStaticVariables' => ['array'],
'ReflectionFunctionAbstract::hasReturnType' => ['bool'],
'ReflectionFunctionAbstract::inNamespace' => ['bool'],
'ReflectionFunctionAbstract::isClosure' => ['bool'],
'ReflectionFunctionAbstract::isDeprecated' => ['bool'],
'ReflectionFunctionAbstract::isGenerator' => ['bool'],
'ReflectionFunctionAbstract::isInternal' => ['bool'],
'ReflectionFunctionAbstract::isUserDefined' => ['bool'],
'ReflectionFunctionAbstract::isVariadic' => ['bool'],
'ReflectionFunctionAbstract::returnsReference' => ['bool'],
'ReflectionGenerator::__construct' => ['void', 'generator'=>'object'],
'ReflectionGenerator::getExecutingFile' => ['string'],
'ReflectionGenerator::getExecutingGenerator' => ['Generator'],
'ReflectionGenerator::getExecutingLine' => ['int'],
'ReflectionGenerator::getFunction' => ['ReflectionFunctionAbstract'],
'ReflectionGenerator::getThis' => ['?object'],
'ReflectionGenerator::getTrace' => ['array', 'options='=>'int'],
'ReflectionMethod::__construct' => ['void', 'class'=>'class-string|object', 'name'=>'string'],
'ReflectionMethod::__construct\'1' => ['void', 'class_method'=>'string'],
'ReflectionMethod::__toString' => ['string'],
'ReflectionMethod::export' => ['?string', 'class'=>'string', 'name'=>'string', 'return='=>'bool'],
'ReflectionMethod::getClosure' => ['?Closure', 'object='=>'object'],
'ReflectionMethod::getClosureScopeClass' => ['ReflectionClass'],
'ReflectionMethod::getClosureThis' => ['object'],
'ReflectionMethod::getDeclaringClass' => ['ReflectionClass'],
'ReflectionMethod::getDocComment' => ['false|string'],
'ReflectionMethod::getEndLine' => ['false|int'],
'ReflectionMethod::getExtension' => ['ReflectionExtension'],
'ReflectionMethod::getExtensionName' => ['string'],
'ReflectionMethod::getFileName' => ['false|string'],
'ReflectionMethod::getModifiers' => ['int'],
'ReflectionMethod::getName' => ['string'],
'ReflectionMethod::getNamespaceName' => ['string'],
'ReflectionMethod::getNumberOfParameters' => ['int'],
'ReflectionMethod::getNumberOfRequiredParameters' => ['int'],
'ReflectionMethod::getParameters' => ['list<\ReflectionParameter>'],
'ReflectionMethod::getPrototype' => ['ReflectionMethod'],
'ReflectionMethod::getReturnType' => ['?ReflectionType'],
'ReflectionMethod::getShortName' => ['string'],
'ReflectionMethod::getStartLine' => ['false|int'],
'ReflectionMethod::getStaticVariables' => ['array'],
'ReflectionMethod::hasReturnType' => ['bool'],
'ReflectionMethod::inNamespace' => ['bool'],
'ReflectionMethod::invoke' => ['mixed', 'object'=>'?object', '...args='=>'mixed'],
'ReflectionMethod::invokeArgs' => ['mixed', 'object'=>'?object', 'args'=>'array'],
'ReflectionMethod::isAbstract' => ['bool'],
'ReflectionMethod::isClosure' => ['bool'],
'ReflectionMethod::isConstructor' => ['bool'],
'ReflectionMethod::isDeprecated' => ['bool'],
'ReflectionMethod::isDestructor' => ['bool'],
'ReflectionMethod::isFinal' => ['bool'],
'ReflectionMethod::isGenerator' => ['bool'],
'ReflectionMethod::isInternal' => ['bool'],
'ReflectionMethod::isPrivate' => ['bool'],
'ReflectionMethod::isProtected' => ['bool'],
'ReflectionMethod::isPublic' => ['bool'],
'ReflectionMethod::isStatic' => ['bool'],
'ReflectionMethod::isUserDefined' => ['bool'],
'ReflectionMethod::isVariadic' => ['bool'],
'ReflectionMethod::returnsReference' => ['bool'],
'ReflectionMethod::setAccessible' => ['void', 'visible'=>'bool'],
'ReflectionNamedType::__clone' => ['void'],
'ReflectionNamedType::__toString' => ['string'],
'ReflectionNamedType::allowsNull' => ['bool'],
'ReflectionNamedType::getName' => ['string'],
'ReflectionNamedType::isBuiltin' => ['bool'],
'ReflectionObject::__clone' => ['void'],
'ReflectionObject::__construct' => ['void', 'argument'=>'object'],
'ReflectionObject::__toString' => ['string'],
'ReflectionObject::export' => ['?string', 'argument'=>'object', 'return='=>'bool'],
'ReflectionObject::getConstant' => ['mixed', 'name'=>'string'],
'ReflectionObject::getConstants' => ['array<string,mixed>'],
'ReflectionObject::getConstructor' => ['?ReflectionMethod'],
'ReflectionObject::getDefaultProperties' => ['array'],
'ReflectionObject::getDocComment' => ['false|string'],
'ReflectionObject::getEndLine' => ['false|int'],
'ReflectionObject::getExtension' => ['?ReflectionExtension'],
'ReflectionObject::getExtensionName' => ['false|string'],
'ReflectionObject::getFileName' => ['false|string'],
'ReflectionObject::getInterfaceNames' => ['class-string[]'],
'ReflectionObject::getInterfaces' => ['array<string,\ReflectionClass>'],
'ReflectionObject::getMethod' => ['ReflectionMethod', 'name'=>'string'],
'ReflectionObject::getMethods' => ['ReflectionMethod[]', 'filter='=>'int'],
'ReflectionObject::getModifiers' => ['int'],
'ReflectionObject::getName' => ['string'],
'ReflectionObject::getNamespaceName' => ['string'],
'ReflectionObject::getParentClass' => ['ReflectionClass|false'],
'ReflectionObject::getProperties' => ['ReflectionProperty[]', 'filter='=>'int'],
'ReflectionObject::getProperty' => ['ReflectionProperty', 'name'=>'string'],
'ReflectionObject::getReflectionConstant' => ['ReflectionClassConstant', 'name'=>'string'],
'ReflectionObject::getReflectionConstants' => ['list<\ReflectionClassConstant>'],
'ReflectionObject::getShortName' => ['string'],
'ReflectionObject::getStartLine' => ['false|int'],
'ReflectionObject::getStaticProperties' => ['ReflectionProperty[]'],
'ReflectionObject::getStaticPropertyValue' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'ReflectionObject::getTraitAliases' => ['array<string,string>'],
'ReflectionObject::getTraitNames' => ['list<string>'],
'ReflectionObject::getTraits' => ['array<string,\ReflectionClass>'],
'ReflectionObject::hasConstant' => ['bool', 'name'=>'string'],
'ReflectionObject::hasMethod' => ['bool', 'name'=>'string'],
'ReflectionObject::hasProperty' => ['bool', 'name'=>'string'],
'ReflectionObject::implementsInterface' => ['bool', 'interface_name'=>'ReflectionClass|string'],
'ReflectionObject::inNamespace' => ['bool'],
'ReflectionObject::isAbstract' => ['bool'],
'ReflectionObject::isAnonymous' => ['bool'],
'ReflectionObject::isCloneable' => ['bool'],
'ReflectionObject::isFinal' => ['bool'],
'ReflectionObject::isInstance' => ['bool', 'object'=>'object'],
'ReflectionObject::isInstantiable' => ['bool'],
'ReflectionObject::isInterface' => ['bool'],
'ReflectionObject::isInternal' => ['bool'],
'ReflectionObject::isIterable' => ['bool'],
'ReflectionObject::isIterateable' => ['bool'],
'ReflectionObject::isSubclassOf' => ['bool', 'class'=>'ReflectionClass|string'],
'ReflectionObject::isTrait' => ['bool'],
'ReflectionObject::isUserDefined' => ['bool'],
'ReflectionObject::newInstance' => ['object', 'args='=>'mixed', '...args='=>'array'],
'ReflectionObject::newInstanceArgs' => ['object', 'args='=>'array'],
'ReflectionObject::newInstanceWithoutConstructor' => ['object'],
'ReflectionObject::setStaticPropertyValue' => ['void', 'name'=>'string', 'value'=>'string'],
'ReflectionParameter::__clone' => ['void'],
'ReflectionParameter::__construct' => ['void', 'function'=>'', 'parameter'=>''],
'ReflectionParameter::__toString' => ['string'],
'ReflectionParameter::allowsNull' => ['bool'],
'ReflectionParameter::canBePassedByValue' => ['bool'],
'ReflectionParameter::export' => ['?string', 'function'=>'string', 'parameter'=>'string', 'return='=>'bool'],
'ReflectionParameter::getAttributes' => ['list<ReflectionAttribute>', 'name='=>'?string', 'flags='=>'int'],
'ReflectionParameter::getClass' => ['?ReflectionClass'],
'ReflectionParameter::getDeclaringClass' => ['?ReflectionClass'],
'ReflectionParameter::getDeclaringFunction' => ['ReflectionFunctionAbstract'],
'ReflectionParameter::getDefaultValue' => ['mixed'],
'ReflectionParameter::getDefaultValueConstantName' => ['?string'],
'ReflectionParameter::getName' => ['string'],
'ReflectionParameter::getPosition' => ['int'],
'ReflectionParameter::getType' => ['?ReflectionType'],
'ReflectionParameter::hasType' => ['bool'],
'ReflectionParameter::isArray' => ['bool'],
'ReflectionParameter::isCallable' => ['?bool'],
'ReflectionParameter::isDefaultValueAvailable' => ['bool'],
'ReflectionParameter::isDefaultValueConstant' => ['bool'],
'ReflectionParameter::isOptional' => ['bool'],
'ReflectionParameter::isPassedByReference' => ['bool'],
'ReflectionParameter::isVariadic' => ['bool'],
'ReflectionProperty::__clone' => ['void'],
'ReflectionProperty::__construct' => ['void', 'class'=>'', 'name'=>'string'],
'ReflectionProperty::__toString' => ['string'],
'ReflectionProperty::export' => ['?string', 'class'=>'mixed', 'name'=>'string', 'return='=>'bool'],
'ReflectionProperty::getAttributes' => ['list<ReflectionAttribute>', 'name='=>'?string', 'flags='=>'int'],
'ReflectionProperty::getDeclaringClass' => ['ReflectionClass'],
'ReflectionProperty::getDocComment' => ['string|false'],
'ReflectionProperty::getModifiers' => ['int'],
'ReflectionProperty::getName' => ['string'],
'ReflectionProperty::getType' => ['?ReflectionType'],
'ReflectionProperty::getValue' => ['mixed', 'object='=>'object'],
'ReflectionProperty::hasType' => ['bool'],
'ReflectionProperty::isDefault' => ['bool'],
'ReflectionProperty::isPrivate' => ['bool'],
'ReflectionProperty::isProtected' => ['bool'],
'ReflectionProperty::isPublic' => ['bool'],
'ReflectionProperty::isStatic' => ['bool'],
'ReflectionProperty::setAccessible' => ['void', 'visible'=>'bool'],
'ReflectionProperty::setValue' => ['void', 'object'=>'null|object', 'value'=>''],
'ReflectionProperty::setValue\'1' => ['void', 'value'=>''],
'ReflectionType::__clone' => ['void'],
'ReflectionType::__toString' => ['string'],
'ReflectionType::allowsNull' => ['bool'],
'ReflectionUnionType::getTypes' => ['list<ReflectionNamedType>'],
'ReflectionZendExtension::__clone' => ['void'],
'ReflectionZendExtension::__construct' => ['void', 'name'=>'string'],
'ReflectionZendExtension::__toString' => ['string'],
'ReflectionZendExtension::export' => ['?string', 'name'=>'string', 'return='=>'bool'],
'ReflectionZendExtension::getAuthor' => ['string'],
'ReflectionZendExtension::getCopyright' => ['string'],
'ReflectionZendExtension::getName' => ['string'],
'ReflectionZendExtension::getURL' => ['string'],
'ReflectionZendExtension::getVersion' => ['string'],
'Reflector::__toString' => ['string'],
'Reflector::export' => ['?string'],
'RegexIterator::__construct' => ['void', 'iterator'=>'Iterator', 'regex'=>'string', 'mode='=>'int', 'flags='=>'int', 'preg_flags='=>'int'],
'RegexIterator::accept' => ['bool'],
'RegexIterator::current' => ['mixed'],
'RegexIterator::getFlags' => ['int'],
'RegexIterator::getInnerIterator' => ['Iterator'],
'RegexIterator::getMode' => ['int'],
'RegexIterator::getPregFlags' => ['int'],
'RegexIterator::getRegex' => ['string'],
'RegexIterator::key' => ['mixed'],
'RegexIterator::next' => ['void'],
'RegexIterator::rewind' => ['void'],
'RegexIterator::setFlags' => ['void', 'new_flags'=>'int'],
'RegexIterator::setMode' => ['void', 'new_mode'=>'int'],
'RegexIterator::setPregFlags' => ['void', 'new_flags'=>'int'],
'RegexIterator::valid' => ['bool'],
'register_event_handler' => ['bool', 'event_handler_func'=>'string', 'handler_register_name'=>'string', 'event_type_mask'=>'int'],
'register_shutdown_function' => ['void', 'callback'=>'callable', '...args='=>'mixed'],
'register_tick_function' => ['bool', 'callback'=>'callable():void', '...args='=>'mixed'],
'rename' => ['bool', 'from'=>'string', 'to'=>'string', 'context='=>'resource'],
'rename_function' => ['bool', 'original_name'=>'string', 'new_name'=>'string'],
'reset' => ['mixed|false', '&r_array'=>'array|object'],
'ResourceBundle::__construct' => ['void', 'locale'=>'string', 'bundlename'=>'string', 'fallback='=>'bool'],
'ResourceBundle::count' => ['int'],
'ResourceBundle::create' => ['?ResourceBundle', 'locale'=>'string', 'bundlename'=>'string', 'fallback='=>'bool'],
'ResourceBundle::get' => ['', 'index'=>'string|int', 'fallback='=>'bool'],
'ResourceBundle::getErrorCode' => ['int'],
'ResourceBundle::getErrorMessage' => ['string'],
'ResourceBundle::getLocales' => ['array', 'bundlename'=>'string'],
'resourcebundle_count' => ['int', 'bundle'=>'ResourceBundle'],
'resourcebundle_create' => ['?ResourceBundle', 'locale'=>'string', 'bundle'=>'string', 'fallback='=>'bool'],
'resourcebundle_get' => ['mixed|null', 'bundle'=>'ResourceBundle', 'index'=>'string|int', 'fallback='=>'bool'],
'resourcebundle_get_error_code' => ['int', 'bundle'=>'ResourceBundle'],
'resourcebundle_get_error_message' => ['string', 'bundle'=>'ResourceBundle'],
'resourcebundle_locales' => ['array', 'bundle'=>'string'],
'restore_error_handler' => ['true'],
'restore_exception_handler' => ['bool'],
'restore_include_path' => ['void'],
'rewind' => ['bool', 'stream'=>'resource'],
'rewinddir' => ['null|false', 'dir_handle='=>'resource'],
'rmdir' => ['bool', 'directory'=>'string', 'context='=>'resource'],
'round' => ['float', 'num'=>'float', 'precision='=>'int', 'mode='=>'int'],
'rpm_close' => ['bool', 'rpmr'=>'resource'],
'rpm_get_tag' => ['mixed', 'rpmr'=>'resource', 'tagnum'=>'int'],
'rpm_is_valid' => ['bool', 'filename'=>'string'],
'rpm_open' => ['resource|false', 'filename'=>'string'],
'rpm_version' => ['string'],
'rpmaddtag' => ['bool', 'tag'=>'int'],
'rpmdbinfo' => ['array', 'nevr'=>'string', 'full='=>'bool'],
'rpmdbsearch' => ['array', 'pattern'=>'string', 'rpmtag='=>'int', 'rpmmire='=>'int', 'full='=>'bool'],
'rpminfo' => ['array', 'path'=>'string', 'full='=>'bool', 'error='=>'string'],
'rpmvercmp' => ['int', 'evr1'=>'string', 'evr2'=>'string'],
'rrd_create' => ['bool', 'filename'=>'string', 'options'=>'array'],
'rrd_disconnect' => ['void'],
'rrd_error' => ['string'],
'rrd_fetch' => ['array', 'filename'=>'string', 'options'=>'array'],
'rrd_first' => ['int|false', 'file'=>'string', 'raaindex='=>'int'],
'rrd_graph' => ['array|false', 'filename'=>'string', 'options'=>'array'],
'rrd_info' => ['array|false', 'filename'=>'string'],
'rrd_last' => ['int', 'filename'=>'string'],
'rrd_lastupdate' => ['array|false', 'filename'=>'string'],
'rrd_restore' => ['bool', 'xml_file'=>'string', 'rrd_file'=>'string', 'options='=>'array'],
'rrd_tune' => ['bool', 'filename'=>'string', 'options'=>'array'],
'rrd_update' => ['bool', 'filename'=>'string', 'options'=>'array'],
'rrd_version' => ['string'],
'rrd_xport' => ['array|false', 'options'=>'array'],
'rrdc_disconnect' => ['void'],
'RRDCreator::__construct' => ['void', 'path'=>'string', 'starttime='=>'string', 'step='=>'int'],
'RRDCreator::addArchive' => ['void', 'description'=>'string'],
'RRDCreator::addDataSource' => ['void', 'description'=>'string'],
'RRDCreator::save' => ['bool'],
'RRDGraph::__construct' => ['void', 'path'=>'string'],
'RRDGraph::save' => ['array|false'],
'RRDGraph::saveVerbose' => ['array|false'],
'RRDGraph::setOptions' => ['void', 'options'=>'array'],
'RRDUpdater::__construct' => ['void', 'path'=>'string'],
'RRDUpdater::update' => ['bool', 'values'=>'array', 'time='=>'string'],
'rsort' => ['bool', '&rw_array'=>'array', 'flags='=>'int'],
'rtrim' => ['string', 'string'=>'string', 'characters='=>'string'],
'runkit7_constant_add' => ['bool', 'constant_name'=>'string', 'value'=>'mixed', 'new_visibility='=>'int'],
'runkit7_constant_redefine' => ['bool', 'constant_name'=>'string', 'value'=>'mixed', 'new_visibility='=>'?int'],
'runkit7_constant_remove' => ['bool', 'constant_name'=>'string'],
'runkit7_function_add' => ['bool', 'function_name'=>'string', 'argument_list_or_closure'=>'Closure|string', 'code_or_doc_comment='=>'?string', 'return_by_reference='=>'?bool', 'doc_comment='=>'?string', 'return_type='=>'?string', 'is_strict='=>'?bool'],
'runkit7_function_copy' => ['bool', 'source_name'=>'string', 'target_name'=>'string'],
'runkit7_function_redefine' => ['bool', 'function_name'=>'string', 'argument_list_or_closure'=>'Closure|string', 'code_or_doc_comment='=>'?string', 'return_by_reference='=>'?bool', 'doc_comment='=>'?string', 'return_type='=>'?string', 'is_strict='=>'?bool'],
'runkit7_function_remove' => ['bool', 'function_name'=>'string'],
'runkit7_function_rename' => ['bool', 'source_name'=>'string', 'target_name'=>'string'],
'runkit7_import' => ['bool', 'filename'=>'string', 'flags='=>'?int'],
'runkit7_method_add' => ['bool', 'class_name'=>'string', 'method_name'=>'string', 'argument_list_or_closure'=>'Closure|string', 'code_or_flags='=>'int|null|string', 'flags_or_doc_comment='=>'int|null|string', 'doc_comment='=>'?string', 'return_type='=>'?string', 'is_strict='=>'?bool'],
'runkit7_method_copy' => ['bool', 'destination_class'=>'string', 'destination_method'=>'string', 'source_class'=>'string', 'source_method='=>'?string'],
'runkit7_method_redefine' => ['bool', 'class_name'=>'string', 'method_name'=>'string', 'argument_list_or_closure'=>'Closure|string', 'code_or_flags='=>'int|null|string', 'flags_or_doc_comment='=>'int|null|string', 'doc_comment='=>'?string', 'return_type='=>'?string', 'is_strict='=>'?bool'],
'runkit7_method_remove' => ['bool', 'class_name'=>'string', 'method_name'=>'string'],
'runkit7_method_rename' => ['bool', 'class_name'=>'string', 'source_method_name'=>'string', 'source_target_name'=>'string'],
'runkit7_superglobals' => ['array'],
'runkit7_zval_inspect' => ['array', 'value'=>'mixed'],
'runkit_class_adopt' => ['bool', 'classname'=>'string', 'parentname'=>'string'],
'runkit_class_emancipate' => ['bool', 'classname'=>'string'],
'runkit_constant_add' => ['bool', 'constname'=>'string', 'value'=>'mixed'],
'runkit_constant_redefine' => ['bool', 'constname'=>'string', 'newvalue'=>'mixed'],
'runkit_constant_remove' => ['bool', 'constname'=>'string'],
'runkit_function_add' => ['bool', 'funcname'=>'string', 'arglist'=>'string', 'code'=>'string', 'doccomment='=>'?string'],
'runkit_function_add\'1' => ['bool', 'funcname'=>'string', 'closure'=>'Closure', 'doccomment='=>'?string'],
'runkit_function_copy' => ['bool', 'funcname'=>'string', 'targetname'=>'string'],
'runkit_function_redefine' => ['bool', 'funcname'=>'string', 'arglist'=>'string', 'code'=>'string', 'doccomment='=>'?string'],
'runkit_function_redefine\'1' => ['bool', 'funcname'=>'string', 'closure'=>'Closure', 'doccomment='=>'?string'],
'runkit_function_remove' => ['bool', 'funcname'=>'string'],
'runkit_function_rename' => ['bool', 'funcname'=>'string', 'newname'=>'string'],
'runkit_import' => ['bool', 'filename'=>'string', 'flags='=>'int'],
'runkit_lint' => ['bool', 'code'=>'string'],
'runkit_lint_file' => ['bool', 'filename'=>'string'],
'runkit_method_add' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'args'=>'string', 'code'=>'string', 'flags='=>'int', 'doccomment='=>'?string'],
'runkit_method_add\'1' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'closure'=>'Closure', 'flags='=>'int', 'doccomment='=>'?string'],
'runkit_method_copy' => ['bool', 'dclass'=>'string', 'dmethod'=>'string', 'sclass'=>'string', 'smethod='=>'string'],
'runkit_method_redefine' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'args'=>'string', 'code'=>'string', 'flags='=>'int', 'doccomment='=>'?string'],
'runkit_method_redefine\'1' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'closure'=>'Closure', 'flags='=>'int', 'doccomment='=>'?string'],
'runkit_method_remove' => ['bool', 'classname'=>'string', 'methodname'=>'string'],
'runkit_method_rename' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'newname'=>'string'],
'runkit_return_value_used' => ['bool'],
'Runkit_Sandbox::__construct' => ['void', 'options='=>'array'],
'runkit_sandbox_output_handler' => ['mixed', 'sandbox'=>'object', 'callback='=>'mixed'],
'Runkit_Sandbox_Parent' => [''],
'Runkit_Sandbox_Parent::__construct' => ['void'],
'runkit_superglobals' => ['array'],
'runkit_zval_inspect' => ['array', 'value'=>'mixed'],
'RuntimeException::__clone' => ['void'],
'RuntimeException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?RuntimeException'],
'RuntimeException::__toString' => ['string'],
'RuntimeException::getCode' => ['int'],
'RuntimeException::getFile' => ['string'],
'RuntimeException::getLine' => ['int'],
'RuntimeException::getMessage' => ['string'],
'RuntimeException::getPrevious' => ['Throwable|RuntimeException|null'],
'RuntimeException::getTrace' => ['list<array<string,mixed>>'],
'RuntimeException::getTraceAsString' => ['string'],
'SAMConnection::commit' => ['bool'],
'SAMConnection::connect' => ['bool', 'protocol'=>'string', 'properties='=>'array'],
'SAMConnection::disconnect' => ['bool'],
'SAMConnection::errno' => ['int'],
'SAMConnection::error' => ['string'],
'SAMConnection::isConnected' => ['bool'],
'SAMConnection::peek' => ['SAMMessage', 'target'=>'string', 'properties='=>'array'],
'SAMConnection::peekAll' => ['array', 'target'=>'string', 'properties='=>'array'],
'SAMConnection::receive' => ['SAMMessage', 'target'=>'string', 'properties='=>'array'],
'SAMConnection::remove' => ['SAMMessage', 'target'=>'string', 'properties='=>'array'],
'SAMConnection::rollback' => ['bool'],
'SAMConnection::send' => ['string', 'target'=>'string', 'msg'=>'sammessage', 'properties='=>'array'],
'SAMConnection::setDebug' => ['', 'switch'=>'bool'],
'SAMConnection::subscribe' => ['string', 'targettopic'=>'string'],
'SAMConnection::unsubscribe' => ['bool', 'subscriptionid'=>'string', 'targettopic='=>'string'],
'SAMMessage::body' => ['string'],
'SAMMessage::header' => ['object'],
'sapi_windows_cp_conv' => ['string', 'in_codepage'=>'int|string', 'out_codepage'=>'int|string', 'subject'=>'string'],
'sapi_windows_cp_get' => ['int'],
'sapi_windows_cp_is_utf8' => ['bool'],
'sapi_windows_cp_set' => ['bool', 'codepage'=>'int'],
'sapi_windows_vt100_support' => ['bool', 'stream'=>'resource', 'enable='=>'bool'],
'Saxon\SaxonProcessor::__construct' => ['void', 'license='=>'bool', 'cwd='=>'string'],
'Saxon\SaxonProcessor::createAtomicValue' => ['Saxon\XdmValue', 'primitive_type_val'=>'bool|float|int|string'],
'Saxon\SaxonProcessor::newSchemaValidator' => ['Saxon\SchemaValidator'],
'Saxon\SaxonProcessor::newXPathProcessor' => ['Saxon\XPathProcessor'],
'Saxon\SaxonProcessor::newXQueryProcessor' => ['Saxon\XQueryProcessor'],
'Saxon\SaxonProcessor::newXsltProcessor' => ['Saxon\XsltProcessor'],
'Saxon\SaxonProcessor::parseXmlFromFile' => ['Saxon\XdmNode', 'fileName'=>'string'],
'Saxon\SaxonProcessor::parseXmlFromString' => ['Saxon\XdmNode', 'value'=>'string'],
'Saxon\SaxonProcessor::registerPHPFunctions' => ['void', 'library'=>'string'],
'Saxon\SaxonProcessor::setConfigurationProperty' => ['void', 'name'=>'string', 'value'=>'string'],
'Saxon\SaxonProcessor::setcwd' => ['void', 'cwd'=>'string'],
'Saxon\SaxonProcessor::setResourceDirectory' => ['void', 'dir'=>'string'],
'Saxon\SaxonProcessor::version' => ['string'],
'Saxon\SchemaValidator::clearParameters' => ['void'],
'Saxon\SchemaValidator::clearProperties' => ['void'],
'Saxon\SchemaValidator::exceptionClear' => ['void'],
'Saxon\SchemaValidator::getErrorCode' => ['string', 'i'=>'int'],
'Saxon\SchemaValidator::getErrorMessage' => ['string', 'i'=>'int'],
'Saxon\SchemaValidator::getExceptionCount' => ['int'],
'Saxon\SchemaValidator::getValidationReport' => ['Saxon\XdmNode'],
'Saxon\SchemaValidator::registerSchemaFromFile' => ['void', 'fileName'=>'string'],
'Saxon\SchemaValidator::registerSchemaFromString' => ['void', 'schemaStr'=>'string'],
'Saxon\SchemaValidator::setOutputFile' => ['void', 'fileName'=>'string'],
'Saxon\SchemaValidator::setParameter' => ['void', 'name'=>'string', 'value'=>'Saxon\XdmValue'],
'Saxon\SchemaValidator::setProperty' => ['void', 'name'=>'string', 'value'=>'string'],
'Saxon\SchemaValidator::setSourceNode' => ['void', 'node'=>'Saxon\XdmNode'],
'Saxon\SchemaValidator::validate' => ['void', 'filename='=>'?string'],
'Saxon\SchemaValidator::validateToNode' => ['Saxon\XdmNode', 'filename='=>'?string'],
'Saxon\XdmAtomicValue::addXdmItem' => ['', 'item'=>'Saxon\XdmItem'],
'Saxon\XdmAtomicValue::getAtomicValue' => ['?Saxon\XdmAtomicValue'],
'Saxon\XdmAtomicValue::getBooleanValue' => ['bool'],
'Saxon\XdmAtomicValue::getDoubleValue' => ['float'],
'Saxon\XdmAtomicValue::getHead' => ['Saxon\XdmItem'],
'Saxon\XdmAtomicValue::getLongValue' => ['int'],
'Saxon\XdmAtomicValue::getNodeValue' => ['?Saxon\XdmNode'],
'Saxon\XdmAtomicValue::getStringValue' => ['string'],
'Saxon\XdmAtomicValue::isAtomic' => ['true'],
'Saxon\XdmAtomicValue::isNode' => ['bool'],
'Saxon\XdmAtomicValue::itemAt' => ['Saxon\XdmItem', 'index'=>'int'],
'Saxon\XdmAtomicValue::size' => ['int'],
'Saxon\XdmItem::addXdmItem' => ['', 'item'=>'Saxon\XdmItem'],
'Saxon\XdmItem::getAtomicValue' => ['?Saxon\XdmAtomicValue'],
'Saxon\XdmItem::getHead' => ['Saxon\XdmItem'],
'Saxon\XdmItem::getNodeValue' => ['?Saxon\XdmNode'],
'Saxon\XdmItem::getStringValue' => ['string'],
'Saxon\XdmItem::isAtomic' => ['bool'],
'Saxon\XdmItem::isNode' => ['bool'],
'Saxon\XdmItem::itemAt' => ['Saxon\XdmItem', 'index'=>'int'],
'Saxon\XdmItem::size' => ['int'],
'Saxon\XdmNode::addXdmItem' => ['', 'item'=>'Saxon\XdmItem'],
'Saxon\XdmNode::getAtomicValue' => ['?Saxon\XdmAtomicValue'],
'Saxon\XdmNode::getAttributeCount' => ['int'],
'Saxon\XdmNode::getAttributeNode' => ['?Saxon\XdmNode', 'index'=>'int'],
'Saxon\XdmNode::getAttributeValue' => ['?string', 'index'=>'int'],
'Saxon\XdmNode::getChildCount' => ['int'],
'Saxon\XdmNode::getChildNode' => ['?Saxon\XdmNode', 'index'=>'int'],
'Saxon\XdmNode::getHead' => ['Saxon\XdmItem'],
'Saxon\XdmNode::getNodeKind' => ['int'],
'Saxon\XdmNode::getNodeName' => ['string'],
'Saxon\XdmNode::getNodeValue' => ['?Saxon\XdmNode'],
'Saxon\XdmNode::getParent' => ['?Saxon\XdmNode'],
'Saxon\XdmNode::getStringValue' => ['string'],
'Saxon\XdmNode::isAtomic' => ['false'],
'Saxon\XdmNode::isNode' => ['bool'],
'Saxon\XdmNode::itemAt' => ['Saxon\XdmItem', 'index'=>'int'],
'Saxon\XdmNode::size' => ['int'],
'Saxon\XdmValue::addXdmItem' => ['', 'item'=>'Saxon\XdmItem'],
'Saxon\XdmValue::getHead' => ['Saxon\XdmItem'],
'Saxon\XdmValue::itemAt' => ['Saxon\XdmItem', 'index'=>'int'],
'Saxon\XdmValue::size' => ['int'],
'Saxon\XPathProcessor::clearParameters' => ['void'],
'Saxon\XPathProcessor::clearProperties' => ['void'],
'Saxon\XPathProcessor::declareNamespace' => ['void', 'prefix'=>'', 'namespace'=>''],
'Saxon\XPathProcessor::effectiveBooleanValue' => ['bool', 'xpathStr'=>'string'],
'Saxon\XPathProcessor::evaluate' => ['Saxon\XdmValue', 'xpathStr'=>'string'],
'Saxon\XPathProcessor::evaluateSingle' => ['Saxon\XdmItem', 'xpathStr'=>'string'],
'Saxon\XPathProcessor::exceptionClear' => ['void'],
'Saxon\XPathProcessor::getErrorCode' => ['string', 'i'=>'int'],
'Saxon\XPathProcessor::getErrorMessage' => ['string', 'i'=>'int'],
'Saxon\XPathProcessor::getExceptionCount' => ['int'],
'Saxon\XPathProcessor::setBaseURI' => ['void', 'uri'=>'string'],
'Saxon\XPathProcessor::setContextFile' => ['void', 'fileName'=>'string'],
'Saxon\XPathProcessor::setContextItem' => ['void', 'item'=>'Saxon\XdmItem'],
'Saxon\XPathProcessor::setParameter' => ['void', 'name'=>'string', 'value'=>'Saxon\XdmValue'],
'Saxon\XPathProcessor::setProperty' => ['void', 'name'=>'string', 'value'=>'string'],
'Saxon\XQueryProcessor::clearParameters' => ['void'],
'Saxon\XQueryProcessor::clearProperties' => ['void'],
'Saxon\XQueryProcessor::declareNamespace' => ['void', 'prefix'=>'string', 'namespace'=>'string'],
'Saxon\XQueryProcessor::exceptionClear' => ['void'],
'Saxon\XQueryProcessor::getErrorCode' => ['string', 'i'=>'int'],
'Saxon\XQueryProcessor::getErrorMessage' => ['string', 'i'=>'int'],
'Saxon\XQueryProcessor::getExceptionCount' => ['int'],
'Saxon\XQueryProcessor::runQueryToFile' => ['void', 'outfilename'=>'string'],
'Saxon\XQueryProcessor::runQueryToString' => ['?string'],
'Saxon\XQueryProcessor::runQueryToValue' => ['?Saxon\XdmValue'],
'Saxon\XQueryProcessor::setContextItem' => ['void', 'object'=>'Saxon\XdmAtomicValue|Saxon\XdmItem|Saxon\XdmNode|Saxon\XdmValue'],
'Saxon\XQueryProcessor::setContextItemFromFile' => ['void', 'fileName'=>'string'],
'Saxon\XQueryProcessor::setParameter' => ['void', 'name'=>'string', 'value'=>'Saxon\XdmValue'],
'Saxon\XQueryProcessor::setProperty' => ['void', 'name'=>'string', 'value'=>'string'],
'Saxon\XQueryProcessor::setQueryBaseURI' => ['void', 'uri'=>'string'],
'Saxon\XQueryProcessor::setQueryContent' => ['void', 'string'=>'string'],
'Saxon\XQueryProcessor::setQueryFile' => ['void', 'filename'=>'string'],
'Saxon\XQueryProcessor::setQueryItem' => ['void', 'item'=>'Saxon\XdmItem'],
'Saxon\XsltProcessor::clearParameters' => ['void'],
'Saxon\XsltProcessor::clearProperties' => ['void'],
'Saxon\XsltProcessor::compileFromFile' => ['void', 'fileName'=>'string'],
'Saxon\XsltProcessor::compileFromString' => ['void', 'string'=>'string'],
'Saxon\XsltProcessor::compileFromValue' => ['void', 'node'=>'Saxon\XdmNode'],
'Saxon\XsltProcessor::exceptionClear' => ['void'],
'Saxon\XsltProcessor::getErrorCode' => ['string', 'i'=>'int'],
'Saxon\XsltProcessor::getErrorMessage' => ['string', 'i'=>'int'],
'Saxon\XsltProcessor::getExceptionCount' => ['int'],
'Saxon\XsltProcessor::setOutputFile' => ['void', 'fileName'=>'string'],
'Saxon\XsltProcessor::setParameter' => ['void', 'name'=>'string', 'value'=>'Saxon\XdmValue'],
'Saxon\XsltProcessor::setProperty' => ['void', 'name'=>'string', 'value'=>'string'],
'Saxon\XsltProcessor::setSourceFromFile' => ['void', 'filename'=>'string'],
'Saxon\XsltProcessor::setSourceFromXdmValue' => ['void', 'value'=>'Saxon\XdmValue'],
'Saxon\XsltProcessor::transformFileToFile' => ['void', 'sourceFileName'=>'string', 'stylesheetFileName'=>'string', 'outputfileName'=>'string'],
'Saxon\XsltProcessor::transformFileToString' => ['?string', 'sourceFileName'=>'string', 'stylesheetFileName'=>'string'],
'Saxon\XsltProcessor::transformFileToValue' => ['Saxon\XdmValue', 'fileName'=>'string'],
'Saxon\XsltProcessor::transformToFile' => ['void'],
'Saxon\XsltProcessor::transformToString' => ['string'],
'Saxon\XsltProcessor::transformToValue' => ['?Saxon\XdmValue'],
'SCA::createDataObject' => ['SDO_DataObject', 'type_namespace_uri'=>'string', 'type_name'=>'string'],
'SCA::getService' => ['', 'target'=>'string', 'binding='=>'string', 'config='=>'array'],
'SCA_LocalProxy::createDataObject' => ['SDO_DataObject', 'type_namespace_uri'=>'string', 'type_name'=>'string'],
'SCA_SoapProxy::createDataObject' => ['SDO_DataObject', 'type_namespace_uri'=>'string', 'type_name'=>'string'],
'scalebarObj::convertToString' => ['string'],
'scalebarObj::free' => ['void'],
'scalebarObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'scalebarObj::setImageColor' => ['int', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'scalebarObj::updateFromString' => ['int', 'snippet'=>'string'],
'scandir' => ['list<string>|false', 'directory'=>'string', 'sorting_order='=>'int', 'context='=>'resource'],
'SDO_DAS_ChangeSummary::beginLogging' => [''],
'SDO_DAS_ChangeSummary::endLogging' => [''],
'SDO_DAS_ChangeSummary::getChangedDataObjects' => ['SDO_List'],
'SDO_DAS_ChangeSummary::getChangeType' => ['int', 'dataobject'=>'sdo_dataobject'],
'SDO_DAS_ChangeSummary::getOldContainer' => ['SDO_DataObject', 'data_object'=>'sdo_dataobject'],
'SDO_DAS_ChangeSummary::getOldValues' => ['SDO_List', 'data_object'=>'sdo_dataobject'],
'SDO_DAS_ChangeSummary::isLogging' => ['bool'],
'SDO_DAS_DataFactory::addPropertyToType' => ['', 'parent_type_namespace_uri'=>'string', 'parent_type_name'=>'string', 'property_name'=>'string', 'type_namespace_uri'=>'string', 'type_name'=>'string', 'options='=>'array'],
'SDO_DAS_DataFactory::addType' => ['', 'type_namespace_uri'=>'string', 'type_name'=>'string', 'options='=>'array'],
'SDO_DAS_DataFactory::getDataFactory' => ['SDO_DAS_DataFactory'],
'SDO_DAS_DataObject::getChangeSummary' => ['SDO_DAS_ChangeSummary'],
'SDO_DAS_Relational::__construct' => ['void', 'database_metadata'=>'array', 'application_root_type='=>'string', 'sdo_containment_references_metadata='=>'array'],
'SDO_DAS_Relational::applyChanges' => ['', 'database_handle'=>'pdo', 'root_data_object'=>'sdodataobject'],
'SDO_DAS_Relational::createRootDataObject' => ['SDODataObject'],
'SDO_DAS_Relational::executePreparedQuery' => ['SDODataObject', 'database_handle'=>'pdo', 'prepared_statement'=>'pdostatement', 'value_list'=>'array', 'column_specifier='=>'array'],
'SDO_DAS_Relational::executeQuery' => ['SDODataObject', 'database_handle'=>'pdo', 'sql_statement'=>'string', 'column_specifier='=>'array'],
'SDO_DAS_Setting::getListIndex' => ['int'],
'SDO_DAS_Setting::getPropertyIndex' => ['int'],
'SDO_DAS_Setting::getPropertyName' => ['string'],
'SDO_DAS_Setting::getValue' => [''],
'SDO_DAS_Setting::isSet' => ['bool'],
'SDO_DAS_XML::addTypes' => ['', 'xsd_file'=>'string'],
'SDO_DAS_XML::create' => ['SDO_DAS_XML', 'xsd_file='=>'mixed', 'key='=>'string'],
'SDO_DAS_XML::createDataObject' => ['SDO_DataObject', 'namespace_uri'=>'string', 'type_name'=>'string'],
'SDO_DAS_XML::createDocument' => ['SDO_DAS_XML_Document', 'document_element_name'=>'string', 'document_element_namespace_uri'=>'string', 'dataobject='=>'sdo_dataobject'],
'SDO_DAS_XML::loadFile' => ['SDO_XMLDocument', 'xml_file'=>'string'],
'SDO_DAS_XML::loadString' => ['SDO_DAS_XML_Document', 'xml_string'=>'string'],
'SDO_DAS_XML::saveFile' => ['', 'xdoc'=>'sdo_xmldocument', 'xml_file'=>'string', 'indent='=>'int'],
'SDO_DAS_XML::saveString' => ['string', 'xdoc'=>'sdo_xmldocument', 'indent='=>'int'],
'SDO_DAS_XML_Document::getRootDataObject' => ['SDO_DataObject'],
'SDO_DAS_XML_Document::getRootElementName' => ['string'],
'SDO_DAS_XML_Document::getRootElementURI' => ['string'],
'SDO_DAS_XML_Document::setEncoding' => ['', 'encoding'=>'string'],
'SDO_DAS_XML_Document::setXMLDeclaration' => ['', 'xmldeclatation'=>'bool'],
'SDO_DAS_XML_Document::setXMLVersion' => ['', 'xmlversion'=>'string'],
'SDO_DataFactory::create' => ['void', 'type_namespace_uri'=>'string', 'type_name'=>'string'],
'SDO_DataObject::clear' => ['void'],
'SDO_DataObject::createDataObject' => ['SDO_DataObject', 'identifier'=>''],
'SDO_DataObject::getContainer' => ['SDO_DataObject'],
'SDO_DataObject::getSequence' => ['SDO_Sequence'],
'SDO_DataObject::getTypeName' => ['string'],
'SDO_DataObject::getTypeNamespaceURI' => ['string'],
'SDO_Exception::getCause' => [''],
'SDO_List::insert' => ['void', 'value'=>'mixed', 'index='=>'int'],
'SDO_Model_Property::getContainingType' => ['SDO_Model_Type'],
'SDO_Model_Property::getDefault' => [''],
'SDO_Model_Property::getName' => ['string'],
'SDO_Model_Property::getType' => ['SDO_Model_Type'],
'SDO_Model_Property::isContainment' => ['bool'],
'SDO_Model_Property::isMany' => ['bool'],
'SDO_Model_ReflectionDataObject::__construct' => ['void', 'data_object'=>'sdo_dataobject'],
'SDO_Model_ReflectionDataObject::export' => ['mixed', 'rdo'=>'sdo_model_reflectiondataobject', 'return='=>'bool'],
'SDO_Model_ReflectionDataObject::getContainmentProperty' => ['SDO_Model_Property'],
'SDO_Model_ReflectionDataObject::getInstanceProperties' => ['array'],
'SDO_Model_ReflectionDataObject::getType' => ['SDO_Model_Type'],
'SDO_Model_Type::getBaseType' => ['SDO_Model_Type'],
'SDO_Model_Type::getName' => ['string'],
'SDO_Model_Type::getNamespaceURI' => ['string'],
'SDO_Model_Type::getProperties' => ['array'],
'SDO_Model_Type::getProperty' => ['SDO_Model_Property', 'identifier'=>''],
'SDO_Model_Type::isAbstractType' => ['bool'],
'SDO_Model_Type::isDataType' => ['bool'],
'SDO_Model_Type::isInstance' => ['bool', 'data_object'=>'sdo_dataobject'],
'SDO_Model_Type::isOpenType' => ['bool'],
'SDO_Model_Type::isSequencedType' => ['bool'],
'SDO_Sequence::getProperty' => ['SDO_Model_Property', 'sequence_index'=>'int'],
'SDO_Sequence::insert' => ['void', 'value'=>'mixed', 'sequenceindex='=>'int', 'propertyidentifier='=>'mixed'],
'SDO_Sequence::move' => ['void', 'toindex'=>'int', 'fromindex'=>'int'],
'SeasLog::__destruct' => ['void'],
'SeasLog::alert' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::analyzerCount' => ['mixed', 'level'=>'string', 'log_path='=>'string', 'key_word='=>'string'],
'SeasLog::analyzerDetail' => ['mixed', 'level'=>'string', 'log_path='=>'string', 'key_word='=>'string', 'start='=>'int', 'limit='=>'int', 'order='=>'int'],
'SeasLog::closeLoggerStream' => ['bool', 'model'=>'int', 'logger'=>'string'],
'SeasLog::critical' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::debug' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::emergency' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::error' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::flushBuffer' => ['bool'],
'SeasLog::getBasePath' => ['string'],
'SeasLog::getBuffer' => ['array'],
'SeasLog::getBufferEnabled' => ['bool'],
'SeasLog::getDatetimeFormat' => ['string'],
'SeasLog::getLastLogger' => ['string'],
'SeasLog::getRequestID' => ['string'],
'SeasLog::getRequestVariable' => ['bool', 'key'=>'int'],
'SeasLog::info' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::log' => ['bool', 'level'=>'string', 'message='=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::notice' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::setBasePath' => ['bool', 'base_path'=>'string'],
'SeasLog::setDatetimeFormat' => ['bool', 'format'=>'string'],
'SeasLog::setLogger' => ['bool', 'logger'=>'string'],
'SeasLog::setRequestID' => ['bool', 'request_id'=>'string'],
'SeasLog::setRequestVariable' => ['bool', 'key'=>'int', 'value'=>'string'],
'SeasLog::warning' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'seaslog_get_author' => ['string'],
'seaslog_get_version' => ['string'],
'SeekableIterator::__construct' => ['void'],
'SeekableIterator::current' => ['mixed'],
'SeekableIterator::key' => ['int|string'],
'SeekableIterator::next' => ['void'],
'SeekableIterator::rewind' => ['void'],
'SeekableIterator::seek' => ['void', 'position'=>'int'],
'SeekableIterator::valid' => ['bool'],
'sem_acquire' => ['bool', 'semaphore'=>'resource', 'non_blocking='=>'bool'],
'sem_get' => ['resource|false', 'key'=>'int', 'max_acquire='=>'int', 'permissions='=>'int', 'auto_release='=>'int'],
'sem_release' => ['bool', 'semaphore'=>'resource'],
'sem_remove' => ['bool', 'semaphore'=>'resource'],
'Serializable::__construct' => ['void'],
'Serializable::serialize' => ['?string'],
'Serializable::unserialize' => ['void', 'serialized'=>'string'],
'serialize' => ['string', 'value'=>'mixed'],
'ServerRequest::withInput' => ['ServerRequest', 'input'=>'mixed'],
'ServerRequest::withoutParams' => ['ServerRequest', 'params'=>'int|string'],
'ServerRequest::withParam' => ['ServerRequest', 'key'=>'int|string', 'value'=>'mixed'],
'ServerRequest::withParams' => ['ServerRequest', 'params'=>'mixed'],
'ServerRequest::withUrl' => ['ServerRequest', 'url'=>'array'],
'ServerResponse::addHeader' => ['void', 'label'=>'string', 'value'=>'string'],
'ServerResponse::date' => ['string', 'date'=>'string|DateTimeInterface'],
'ServerResponse::getHeader' => ['string', 'label'=>'string'],
'ServerResponse::getHeaders' => ['string[]'],
'ServerResponse::getStatus' => ['int'],
'ServerResponse::getVersion' => ['string'],
'ServerResponse::setHeader' => ['void', 'label'=>'string', 'value'=>'string'],
'ServerResponse::setStatus' => ['void', 'status'=>'int'],
'ServerResponse::setVersion' => ['void', 'version'=>'string'],
'session_abort' => ['bool'],
'session_cache_expire' => ['int', 'value='=>'int'],
'session_cache_limiter' => ['string', 'value='=>'string'],
'session_commit' => ['bool'],
'session_create_id' => ['string', 'prefix='=>'string'],
'session_decode' => ['bool', 'data'=>'string'],
'session_destroy' => ['bool'],
'session_encode' => ['string'],
'session_gc' => ['int|false'],
'session_get_cookie_params' => ['array'],
'session_id' => ['string|false', 'id='=>'string'],
'session_is_registered' => ['bool', 'name'=>'string'],
'session_module_name' => ['string', 'module='=>'string'],
'session_name' => ['string|false', 'name='=>'string'],
'session_pgsql_add_error' => ['bool', 'error_level'=>'int', 'error_message='=>'string'],
'session_pgsql_get_error' => ['array', 'with_error_message='=>'bool'],
'session_pgsql_get_field' => ['string'],
'session_pgsql_reset' => ['bool'],
'session_pgsql_set_field' => ['bool', 'value'=>'string'],
'session_pgsql_status' => ['array'],
'session_regenerate_id' => ['bool', 'delete_old_session='=>'bool'],
'session_register' => ['bool', 'name'=>'mixed', '...args='=>'mixed'],
'session_register_shutdown' => ['void'],
'session_reset' => ['bool'],
'session_save_path' => ['string', 'path='=>'string'],
'session_set_cookie_params' => ['bool', 'lifetime'=>'int', 'path='=>'?string', 'domain='=>'?string', 'secure='=>'?bool', 'httponly='=>'?bool'],
'session_set_cookie_params\'1' => ['bool', 'options'=>'array{lifetime?:int,path?:string,domain?:?string,secure?:bool,httponly?:bool}'],
'session_set_save_handler' => ['bool', 'open'=>'callable(string,string):bool', 'close'=>'callable():bool', 'read'=>'callable(string):string', 'write'=>'callable(string,string):bool', 'destroy'=>'callable(string):bool', 'gc'=>'callable(string):bool', 'create_sid='=>'callable():string', 'validate_sid='=>'callable(string):bool', 'update_timestamp='=>'callable(string):bool'],
'session_set_save_handler\'1' => ['bool', 'open'=>'SessionHandlerInterface', 'close='=>'bool'],
'session_start' => ['bool', 'options='=>'array'],
'session_status' => ['int'],
'session_unregister' => ['bool', 'name'=>'string'],
'session_unset' => ['bool'],
'session_write_close' => ['bool'],
'SessionHandler::close' => ['bool'],
'SessionHandler::create_sid' => ['char'],
'SessionHandler::destroy' => ['bool', 'id'=>'string'],
'SessionHandler::gc' => ['bool', 'maxlifetime'=>'int'],
'SessionHandler::open' => ['bool', 'save_path'=>'string', 'session_name'=>'string'],
'SessionHandler::read' => ['string', 'id'=>'string'],
'SessionHandler::updateTimestamp' => ['bool', 'session_id'=>'string', 'session_data'=>'string'],
'SessionHandler::validateId' => ['bool', 'session_id'=>'string'],
'SessionHandler::write' => ['bool', 'id'=>'string', 'data'=>'string'],
'SessionHandlerInterface::close' => ['bool'],
'SessionHandlerInterface::destroy' => ['bool', 'id'=>'string'],
'SessionHandlerInterface::gc' => ['int|false', 'max_lifetime'=>'int'],
'SessionHandlerInterface::open' => ['bool', 'path'=>'string', 'name'=>'string'],
'SessionHandlerInterface::read' => ['string|false', 'id'=>'string'],
'SessionHandlerInterface::write' => ['bool', 'id'=>'string', 'data'=>'string'],
'SessionIdInterface::create_sid' => ['string'],
'SessionUpdateTimestampHandler::updateTimestamp' => ['bool', 'id'=>'string', 'data'=>'string'],
'SessionUpdateTimestampHandler::validateId' => ['char', 'id'=>'string'],
'SessionUpdateTimestampHandlerInterface::updateTimestamp' => ['bool', 'key'=>'string', 'value'=>'string'],
'SessionUpdateTimestampHandlerInterface::validateId' => ['bool', 'key'=>'string'],
'set_error_handler' => ['null|callable(int,string,string=,int=,array=):bool', 'callback'=>'null|callable(int,string,string=,int=,array=):bool', 'error_levels='=>'int'],
'set_exception_handler' => ['null|callable(Throwable):void', 'callback'=>'null|callable(Throwable):void'],
'set_file_buffer' => ['int', 'stream'=>'resource', 'size'=>'int'],
'set_include_path' => ['string|false', 'include_path'=>'string'],
'set_magic_quotes_runtime' => ['bool', 'new_setting'=>'bool'],
'set_time_limit' => ['bool', 'seconds'=>'int'],
'setcookie' => ['bool', 'name'=>'string', 'value='=>'string', 'expires='=>'int', 'path='=>'string', 'domain='=>'string', 'secure='=>'bool', 'httponly='=>'bool', 'samesite='=>'string', 'url_encode='=>'int'],
'setcookie\'1' => ['bool', 'name'=>'string', 'value='=>'string', 'options='=>'array'],
'setLeftFill' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'setLine' => ['void', 'width'=>'int', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'setlocale' => ['string|false', 'category'=>'int', 'locales'=>'string|0|null', '...rest='=>'string'],
'setlocale\'1' => ['string|false', 'category'=>'int', 'locales'=>'?array'],
'setproctitle' => ['void', 'title'=>'string'],
'setrawcookie' => ['bool', 'name'=>'string', 'value='=>'string', 'expires='=>'int', 'path='=>'string', 'domain='=>'string', 'secure='=>'bool', 'httponly='=>'bool'],
'setrawcookie\'1' => ['bool', 'name'=>'string', 'value='=>'string', 'options='=>'array'],
'setRightFill' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'setthreadtitle' => ['bool', 'title'=>'string'],
'settype' => ['bool', '&rw_var'=>'mixed', 'type'=>'string'],
'sha1' => ['string', 'string'=>'string', 'binary='=>'bool'],
'sha1_file' => ['string|false', 'filename'=>'string', 'binary='=>'bool'],
'sha256' => ['string', 'string'=>'string', 'raw_output='=>'bool'],
'sha256_file' => ['string', 'filename'=>'string', 'raw_output='=>'bool'],
'shapefileObj::__construct' => ['void', 'filename'=>'string', 'type'=>'int'],
'shapefileObj::addPoint' => ['int', 'point'=>'pointObj'],
'shapefileObj::addShape' => ['int', 'shape'=>'shapeObj'],
'shapefileObj::free' => ['void'],
'shapefileObj::getExtent' => ['rectObj', 'i'=>'int'],
'shapefileObj::getPoint' => ['shapeObj', 'i'=>'int'],
'shapefileObj::getShape' => ['shapeObj', 'i'=>'int'],
'shapefileObj::getTransformed' => ['shapeObj', 'map'=>'mapObj', 'i'=>'int'],
'shapefileObj::ms_newShapefileObj' => ['shapefileObj', 'filename'=>'string', 'type'=>'int'],
'shapeObj::__construct' => ['void', 'type'=>'int'],
'shapeObj::add' => ['int', 'line'=>'lineObj'],
'shapeObj::boundary' => ['shapeObj'],
'shapeObj::contains' => ['bool', 'point'=>'pointObj'],
'shapeObj::containsShape' => ['int', 'shape2'=>'shapeObj'],
'shapeObj::convexhull' => ['shapeObj'],
'shapeObj::crosses' => ['int', 'shape'=>'shapeObj'],
'shapeObj::difference' => ['shapeObj', 'shape'=>'shapeObj'],
'shapeObj::disjoint' => ['int', 'shape'=>'shapeObj'],
'shapeObj::draw' => ['int', 'map'=>'mapObj', 'layer'=>'layerObj', 'img'=>'imageObj'],
'shapeObj::equals' => ['int', 'shape'=>'shapeObj'],
'shapeObj::free' => ['void'],
'shapeObj::getArea' => ['float'],
'shapeObj::getCentroid' => ['pointObj'],
'shapeObj::getLabelPoint' => ['pointObj'],
'shapeObj::getLength' => ['float'],
'shapeObj::getPointUsingMeasure' => ['pointObj', 'm'=>'float'],
'shapeObj::getValue' => ['string', 'layer'=>'layerObj', 'filedname'=>'string'],
'shapeObj::intersection' => ['shapeObj', 'shape'=>'shapeObj'],
'shapeObj::intersects' => ['bool', 'shape'=>'shapeObj'],
'shapeObj::line' => ['lineObj', 'i'=>'int'],
'shapeObj::ms_shapeObjFromWkt' => ['shapeObj', 'wkt'=>'string'],
'shapeObj::overlaps' => ['int', 'shape'=>'shapeObj'],
'shapeObj::project' => ['int', 'in'=>'projectionObj', 'out'=>'projectionObj'],
'shapeObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'shapeObj::setBounds' => ['int'],
'shapeObj::simplify' => ['shapeObj|null', 'tolerance'=>'float'],
'shapeObj::symdifference' => ['shapeObj', 'shape'=>'shapeObj'],
'shapeObj::topologyPreservingSimplify' => ['shapeObj|null', 'tolerance'=>'float'],
'shapeObj::touches' => ['int', 'shape'=>'shapeObj'],
'shapeObj::toWkt' => ['string'],
'shapeObj::union' => ['shapeObj', 'shape'=>'shapeObj'],
'shapeObj::within' => ['int', 'shape2'=>'shapeObj'],
'shell_exec' => ['string|false|null', 'command'=>'string'],
'shm_attach' => ['resource', 'key'=>'int', 'size='=>'int', 'permissions='=>'int'],
'shm_detach' => ['bool', 'shm'=>'resource'],
'shm_get_var' => ['mixed', 'shm'=>'resource', 'key'=>'int'],
'shm_has_var' => ['bool', 'shm'=>'resource', 'key'=>'int'],
'shm_put_var' => ['bool', 'shm'=>'resource', 'key'=>'int', 'value'=>'mixed'],
'shm_remove' => ['bool', 'shm'=>'resource'],
'shm_remove_var' => ['bool', 'shm'=>'resource', 'key'=>'int'],
'shmop_close' => ['void', 'shmop'=>'resource'],
'shmop_delete' => ['bool', 'shmop'=>'resource'],
'shmop_open' => ['resource|false', 'key'=>'int', 'mode'=>'string', 'permissions'=>'int', 'size'=>'int'],
'shmop_read' => ['string|false', 'shmop'=>'resource', 'offset'=>'int', 'size'=>'int'],
'shmop_size' => ['int', 'shmop'=>'resource'],
'shmop_write' => ['int|false', 'shmop'=>'resource', 'data'=>'string', 'offset'=>'int'],
'show_source' => ['string|bool', 'filename'=>'string', 'return='=>'bool'],
'shuffle' => ['bool', '&rw_array'=>'array'],
'signeurlpaiement' => ['string', 'clent'=>'string', 'data'=>'string'],
'similar_text' => ['int', 'string1'=>'string', 'string2'=>'string', '&w_percent='=>'float'],
'simplexml_import_dom' => ['SimpleXMLElement|false', 'node'=>'DOMNode', 'class_name='=>'string'],
'simplexml_load_file' => ['SimpleXMLElement|false', 'filename'=>'string', 'class_name='=>'string', 'options='=>'int', 'namespace_or_prefix='=>'string', 'is_prefix='=>'bool'],
'simplexml_load_string' => ['SimpleXMLElement|false', 'data'=>'string', 'class_name='=>'string', 'options='=>'int', 'namespace_or_prefix='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLElement::__construct' => ['void', 'data'=>'string', 'options='=>'int', 'data_is_url='=>'bool', 'ns='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLElement::__get' => ['SimpleXMLElement', 'name'=>'string'],
'SimpleXMLElement::__toString' => ['string'],
'SimpleXMLElement::addAttribute' => ['void', 'name'=>'string', 'value='=>'string', 'ns='=>'string'],
'SimpleXMLElement::addChild' => ['SimpleXMLElement', 'name'=>'string', 'value='=>'string', 'ns='=>'string'],
'SimpleXMLElement::asXML' => ['bool', 'filename'=>'string'],
'SimpleXMLElement::asXML\'1' => ['string|false'],
'SimpleXMLElement::attributes' => ['?SimpleXMLElement', 'ns='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLElement::children' => ['SimpleXMLElement', 'ns='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLElement::count' => ['int'],
'SimpleXMLElement::getDocNamespaces' => ['string[]', 'recursive='=>'bool', 'from_root='=>'bool'],
'SimpleXMLElement::getName' => ['string'],
'SimpleXMLElement::getNamespaces' => ['string[]', 'recursive='=>'bool'],
'SimpleXMLElement::offsetExists' => ['bool', 'offset'=>'int|string'],
'SimpleXMLElement::offsetGet' => ['SimpleXMLElement', 'offset'=>'int|string'],
'SimpleXMLElement::offsetSet' => ['void', 'offset'=>'int|string', 'value'=>'mixed'],
'SimpleXMLElement::offsetUnset' => ['void', 'offset'=>'int|string'],
'SimpleXMLElement::registerXPathNamespace' => ['bool', 'prefix'=>'string', 'ns'=>'string'],
'SimpleXMLElement::saveXML' => ['mixed', 'filename='=>'string'],
'SimpleXMLElement::xpath' => ['SimpleXMLElement[]|false', 'path'=>'string'],
'sin' => ['float', 'num'=>'float'],
'sinh' => ['float', 'num'=>'float'],
'sizeof' => ['int', 'value'=>'Countable|array', 'mode='=>'int'],
'sleep' => ['int|false', 'seconds'=>'positive-int'],
'snmp2_get' => ['string|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp2_getnext' => ['string|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp2_real_walk' => ['array|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp2_set' => ['bool', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'type'=>'string', 'value'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp2_walk' => ['array|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_get' => ['string|false', 'hostname'=>'string', 'security_name'=>'string', 'security_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'privacy_protocol'=>'string', 'privacy_passphrase'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_getnext' => ['string|false', 'hostname'=>'string', 'security_name'=>'string', 'security_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'privacy_protocol'=>'string', 'privacy_passphrase'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_real_walk' => ['array|false', 'hostname'=>'string', 'security_name'=>'string', 'security_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'privacy_protocol'=>'string', 'privacy_passphrase'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_set' => ['bool', 'hostname'=>'string', 'security_name'=>'string', 'security_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'privacy_protocol'=>'string', 'privacy_passphrase'=>'string', 'object_id'=>'string', 'type'=>'string', 'value'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_walk' => ['array|false', 'hostname'=>'string', 'security_name'=>'string', 'security_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'privacy_protocol'=>'string', 'privacy_passphrase'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'SNMP::__construct' => ['void', 'version'=>'int', 'hostname'=>'string', 'community'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'SNMP::close' => ['bool'],
'SNMP::get' => ['array|string|false', 'objectId'=>'string|array', 'preserveKeys='=>'bool'],
'SNMP::getErrno' => ['int'],
'SNMP::getError' => ['string'],
'SNMP::getnext' => ['string|array|false', 'objectId'=>'string|array'],
'SNMP::set' => ['bool', 'objectId'=>'string|array', 'type'=>'string|array', 'value'=>'mixed'],
'SNMP::setSecurity' => ['bool', 'securityLevel'=>'string', 'authProtocol='=>'string', 'authPassphrase='=>'string', 'privacyProtocol='=>'string', 'privacyPassphrase='=>'string', 'contextName='=>'string', 'contextEngineId='=>'string'],
'SNMP::walk' => ['array|false', 'objectId'=>'string', 'suffixAsKey='=>'bool', 'maxRepetitions='=>'int', 'nonRepeaters='=>'int'],
'snmp_get_quick_print' => ['bool'],
'snmp_get_valueretrieval' => ['int'],
'snmp_read_mib' => ['bool', 'filename'=>'string'],
'snmp_set_enum_print' => ['bool', 'enable'=>'int'],
'snmp_set_oid_numeric_print' => ['void', 'format'=>'int'],
'snmp_set_oid_output_format' => ['bool', 'format'=>'int'],
'snmp_set_quick_print' => ['bool', 'enable'=>'bool'],
'snmp_set_valueretrieval' => ['bool', 'method='=>'int'],
'snmpget' => ['string|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmpgetnext' => ['string|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmprealwalk' => ['array|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmpset' => ['bool', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'type'=>'string', 'value'=>'mixed', 'timeout='=>'int', 'retries='=>'int'],
'snmpwalk' => ['array|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmpwalkoid' => ['array|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'SoapClient::__call' => ['', 'function_name'=>'string', 'arguments'=>'array'],
'SoapClient::__construct' => ['void', 'wsdl'=>'mixed', 'options='=>'array|null'],
'SoapClient::__doRequest' => ['string', 'request'=>'string', 'location'=>'string', 'action'=>'string', 'version'=>'int', 'one_way='=>'bool'],
'SoapClient::__getCookies' => ['array'],
'SoapClient::__getFunctions' => ['array'],
'SoapClient::__getLastRequest' => ['string'],
'SoapClient::__getLastRequestHeaders' => ['string'],
'SoapClient::__getLastResponse' => ['string'],
'SoapClient::__getLastResponseHeaders' => ['string'],
'SoapClient::__getTypes' => ['array'],
'SoapClient::__setCookie' => ['', 'name'=>'string', 'value='=>'string'],
'SoapClient::__setLocation' => ['string', 'new_location='=>'string'],
'SoapClient::__setSoapHeaders' => ['bool', 'soapheaders='=>''],
'SoapClient::__soapCall' => ['', 'function_name'=>'string', 'arguments'=>'array', 'options='=>'array', 'input_headers='=>'SoapHeader|array', '&w_output_headers='=>'array'],
'SoapClient::SoapClient' => ['object', 'wsdl'=>'mixed', 'options='=>'array|null'],
'SoapFault::__clone' => ['void'],
'SoapFault::__construct' => ['void', 'faultcode'=>'string', 'faultstring'=>'string', 'faultactor='=>'string', 'detail='=>'string', 'faultname='=>'string', 'headerfault='=>'string'],
'SoapFault::__toString' => ['string'],
'SoapFault::__wakeup' => ['void'],
'SoapFault::getCode' => ['int'],
'SoapFault::getFile' => ['string'],
'SoapFault::getLine' => ['int'],
'SoapFault::getMessage' => ['string'],
'SoapFault::getPrevious' => ['?Exception|?Throwable'],
'SoapFault::getTrace' => ['list<array<string,mixed>>'],
'SoapFault::getTraceAsString' => ['string'],
'SoapFault::SoapFault' => ['object', 'faultcode'=>'string', 'faultstring'=>'string', 'faultactor='=>'string', 'detail='=>'string', 'faultname='=>'string', 'headerfault='=>'string'],
'SoapHeader::__construct' => ['void', 'namespace'=>'string', 'name'=>'string', 'data='=>'mixed', 'mustunderstand='=>'bool', 'actor='=>'string'],
'SoapHeader::SoapHeader' => ['object', 'namespace'=>'string', 'name'=>'string', 'data='=>'mixed', 'mustunderstand='=>'bool', 'actor='=>'string'],
'SoapParam::__construct' => ['void', 'data'=>'mixed', 'name'=>'string'],
'SoapParam::SoapParam' => ['object', 'data'=>'mixed', 'name'=>'string'],
'SoapServer::__construct' => ['void', 'wsdl'=>'?string', 'options='=>'array'],
'SoapServer::addFunction' => ['void', 'functions'=>'mixed'],
'SoapServer::addSoapHeader' => ['void', 'object'=>'SoapHeader'],
'SoapServer::fault' => ['void', 'code'=>'string', 'string'=>'string', 'actor='=>'string', 'details='=>'string', 'name='=>'string'],
'SoapServer::getFunctions' => ['array'],
'SoapServer::handle' => ['void', 'soap_request='=>'string'],
'SoapServer::setClass' => ['void', 'class_name'=>'string', '...args='=>'mixed'],
'SoapServer::setObject' => ['void', 'object'=>'object'],
'SoapServer::setPersistence' => ['void', 'mode'=>'int'],
'SoapServer::SoapServer' => ['object', 'wsdl'=>'?string', 'options='=>'array'],
'SoapVar::__construct' => ['void', 'data'=>'mixed', 'encoding'=>'int', 'type_name='=>'string|null', 'type_namespace='=>'string|null', 'node_name='=>'string|null', 'node_namespace='=>'string|null'],
'SoapVar::SoapVar' => ['object', 'data'=>'mixed', 'encoding'=>'int', 'type_name='=>'string|null', 'type_namespace='=>'string|null', 'node_name='=>'string|null', 'node_namespace='=>'string|null'],
'socket_accept' => ['Socket|false', 'socket'=>'Socket'],
'socket_addrinfo_bind' => ['Socket|false', 'address'=>'AddressInfo'],
'socket_addrinfo_connect' => ['Socket|false', 'address'=>'AddressInfo'],
'socket_addrinfo_explain' => ['array', 'address'=>'AddressInfo'],
'socket_addrinfo_lookup' => ['false|AddressInfo[]', 'host='=>'string|null', 'service='=>'mixed', 'hints='=>'array'],
'socket_bind' => ['bool', 'socket'=>'Socket', 'addr'=>'string', 'port='=>'int'],
'socket_clear_error' => ['void', 'socket='=>'Socket'],
'socket_close' => ['void', 'socket'=>'Socket'],
'socket_cmsg_space' => ['int', 'level'=>'int', 'type'=>'int'],
'socket_connect' => ['bool', 'socket'=>'Socket', 'addr'=>'string', 'port='=>'int'],
'socket_create' => ['Socket|false', 'domain'=>'int', 'type'=>'int', 'protocol'=>'int'],
'socket_create_listen' => ['Socket|false', 'port'=>'int', 'backlog='=>'int'],
'socket_create_pair' => ['bool', 'domain'=>'int', 'type'=>'int', 'protocol'=>'int', '&w_fd'=>'Socket[]'],
'socket_export_stream' => ['resource|false', 'socket'=>'Socket'],
'socket_get_option' => ['mixed|false', 'socket'=>'Socket', 'level'=>'int', 'optname'=>'int'],
'socket_get_status' => ['array', 'stream'=>'Socket'],
'socket_getopt' => ['mixed', 'socket'=>'Socket', 'level'=>'int', 'optname'=>'int'],
'socket_getpeername' => ['bool', 'socket'=>'Socket', '&w_addr'=>'string', '&w_port='=>'int'],
'socket_getsockname' => ['bool', 'socket'=>'Socket', '&w_addr'=>'string', '&w_port='=>'int'],
'socket_import_stream' => ['Socket|false|null', 'stream'=>'resource'],
'socket_last_error' => ['int', 'socket='=>'Socket'],
'socket_listen' => ['bool', 'socket'=>'Socket', 'backlog='=>'int'],
'socket_read' => ['string|false', 'socket'=>'Socket', 'length'=>'int', 'type='=>'int'],
'socket_recv' => ['int|false', 'socket'=>'Socket', '&w_buf'=>'string', 'length'=>'int', 'flags'=>'int'],
'socket_recvfrom' => ['int|false', 'socket'=>'Socket', '&w_buf'=>'string', 'length'=>'int', 'flags'=>'int', '&w_name'=>'string', '&w_port='=>'int'],
'socket_recvmsg' => ['int|false', 'socket'=>'Socket', '&w_message'=>'string', 'flags='=>'int'],
'socket_select' => ['int|false', '&rw_read_fds'=>'Socket[]|null', '&rw_write_fds'=>'Socket[]|null', '&rw_except_fds'=>'Socket[]|null', 'tv_sec'=>'int|null', 'tv_usec='=>'int'],
'socket_send' => ['int|false', 'socket'=>'Socket', 'buf'=>'string', 'length'=>'int', 'flags'=>'int'],
'socket_sendmsg' => ['int|false', 'socket'=>'Socket', 'message'=>'array', 'flags'=>'int'],
'socket_sendto' => ['int|false', 'socket'=>'Socket', 'buf'=>'string', 'length'=>'int', 'flags'=>'int', 'addr'=>'string', 'port='=>'int'],
'socket_set_block' => ['bool', 'socket'=>'Socket'],
'socket_set_blocking' => ['bool', 'socket'=>'Socket', 'mode'=>'int'],
'socket_set_nonblock' => ['bool', 'socket'=>'Socket'],
'socket_set_option' => ['bool', 'socket'=>'Socket', 'level'=>'int', 'optname'=>'int', 'optval'=>'int|string|array'],
'socket_set_timeout' => ['bool', 'stream'=>'resource', 'seconds'=>'int', 'microseconds='=>'int'],
'socket_setopt' => ['void', 'socket'=>'Socket', 'level'=>'int', 'optname'=>'int', 'optval'=>'int|string|array'],
'socket_shutdown' => ['bool', 'socket'=>'Socket', 'how='=>'int'],
'socket_strerror' => ['string', 'errno'=>'int'],
'socket_write' => ['int|false', 'socket'=>'Socket', 'data'=>'string', 'length='=>'int|null'],
'socket_wsaprotocol_info_export' => ['string|false', 'socket'=>'Socket', 'process_id'=>'int'],
'socket_wsaprotocol_info_import' => ['Socket|false', 'info_id'=>'string'],
'socket_wsaprotocol_info_release' => ['bool', 'info_id'=>'string'],
'sodium_add' => ['void', '&rw_string1'=>'string', 'string2'=>'string'],
'sodium_base642bin' => ['string', 'string'=>'string', 'id'=>'int', 'ignore='=>'string'],
'sodium_bin2base64' => ['string', 'string'=>'string', 'id'=>'int'],
'sodium_bin2hex' => ['string', 'string'=>'string'],
'sodium_compare' => ['int', 'string1'=>'string', 'string2'=>'string'],
'sodium_crypto_aead_aes256gcm_decrypt' => ['string|false', 'ciphertext'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_aes256gcm_encrypt' => ['string', 'message'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_aes256gcm_is_available' => ['bool'],
'sodium_crypto_aead_aes256gcm_keygen' => ['string'],
'sodium_crypto_aead_chacha20poly1305_decrypt' => ['string|false', 'ciphertext'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_chacha20poly1305_encrypt' => ['string|false', 'message'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_chacha20poly1305_ietf_decrypt' => ['string|false', 'ciphertext'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_chacha20poly1305_ietf_encrypt' => ['string|false', 'message'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_chacha20poly1305_ietf_keygen' => ['string'],
'sodium_crypto_aead_chacha20poly1305_keygen' => ['string'],
'sodium_crypto_aead_xchacha20poly1305_ietf_decrypt' => ['string|false', 'ciphertext'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_xchacha20poly1305_ietf_encrypt' => ['string|false', 'message'=>'string', 'additional_data'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_xchacha20poly1305_ietf_keygen' => ['string'],
'sodium_crypto_auth' => ['string', 'message'=>'string', 'key'=>'string'],
'sodium_crypto_auth_keygen' => ['string'],
'sodium_crypto_auth_verify' => ['bool', 'mac'=>'string', 'message'=>'string', 'key'=>'string'],
'sodium_crypto_box' => ['string', 'message'=>'string', 'nonce'=>'string', 'key_pair'=>'string'],
'sodium_crypto_box_keypair' => ['string'],
'sodium_crypto_box_keypair_from_secretkey_and_publickey' => ['string', 'secret_key'=>'string', 'public_key'=>'string'],
'sodium_crypto_box_open' => ['string|false', 'ciphertext'=>'string', 'nonce'=>'string', 'key_pair'=>'string'],
'sodium_crypto_box_publickey' => ['string', 'key_pair'=>'string'],
'sodium_crypto_box_publickey_from_secretkey' => ['string', 'secret_key'=>'string'],
'sodium_crypto_box_seal' => ['string', 'message'=>'string', 'public_key'=>'string'],
'sodium_crypto_box_seal_open' => ['string|false', 'ciphertext'=>'string', 'key_pair'=>'string'],
'sodium_crypto_box_secretkey' => ['string', 'key_pair'=>'string'],
'sodium_crypto_box_seed_keypair' => ['string', 'seed'=>'string'],
'sodium_crypto_generichash' => ['string', 'message'=>'string', 'key='=>'?string', 'length='=>'?int'],
'sodium_crypto_generichash_final' => ['string', '&state'=>'string', 'length='=>'?int'],
'sodium_crypto_generichash_init' => ['string', 'key='=>'?string', 'length='=>'?int'],
'sodium_crypto_generichash_keygen' => ['string'],
'sodium_crypto_generichash_update' => ['bool', '&rw_state'=>'string', 'string'=>'string'],
'sodium_crypto_kdf_derive_from_key' => ['string', 'subkey_length'=>'int', 'subkey_id'=>'int', 'context'=>'string', 'key'=>'string'],
'sodium_crypto_kdf_keygen' => ['string'],
'sodium_crypto_kx_client_session_keys' => ['array<int,string>', 'client_keypair'=>'string', 'server_key'=>'string'],
'sodium_crypto_kx_keypair' => ['string'],
'sodium_crypto_kx_publickey' => ['string', 'key_pair'=>'string'],
'sodium_crypto_kx_secretkey' => ['string', 'key_pair'=>'string'],
'sodium_crypto_kx_seed_keypair' => ['string', 'seed'=>'string'],
'sodium_crypto_kx_server_session_keys' => ['array<int,string>', 'server_key_pair'=>'string', 'client_key'=>'string'],
'sodium_crypto_pwhash' => ['string', 'length'=>'int', 'password'=>'string', 'salt'=>'string', 'opslimit'=>'int', 'memlimit'=>'int', 'algo='=>'int'],
'sodium_crypto_pwhash_scryptsalsa208sha256' => ['string', 'length'=>'int', 'password'=>'string', 'salt'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'sodium_crypto_pwhash_scryptsalsa208sha256_str' => ['string', 'password'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'sodium_crypto_pwhash_scryptsalsa208sha256_str_verify' => ['bool', 'hash'=>'string', 'password'=>'string'],
'sodium_crypto_pwhash_str' => ['string', 'password'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'sodium_crypto_pwhash_str_needs_rehash' => ['bool', 'password'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'sodium_crypto_pwhash_str_verify' => ['bool', 'hash'=>'string', 'password'=>'string'],
'sodium_crypto_scalarmult' => ['string', 'n'=>'string', 'p'=>'string'],
'sodium_crypto_scalarmult_base' => ['string', 'secret_key'=>'string'],
'sodium_crypto_secretbox' => ['string', 'message'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_secretbox_keygen' => ['string'],
'sodium_crypto_secretbox_open' => ['string|false', 'ciphertext'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_secretstream_xchacha20poly1305_init_pull' => ['string', 'header'=>'string', 'key'=>'string'],
'sodium_crypto_secretstream_xchacha20poly1305_init_push' => ['array', 'key'=>'string'],
'sodium_crypto_secretstream_xchacha20poly1305_keygen' => ['string'],
'sodium_crypto_secretstream_xchacha20poly1305_pull' => ['array', '&r_state'=>'string', 'ciphertext'=>'string', 'additional_data='=>'string'],
'sodium_crypto_secretstream_xchacha20poly1305_push' => ['string', '&w_state'=>'string', 'message'=>'string', 'additional_data='=>'string', 'tag='=>'int'],
'sodium_crypto_secretstream_xchacha20poly1305_rekey' => ['void', 'state'=>'string'],
'sodium_crypto_shorthash' => ['string', 'message'=>'string', 'key'=>'string'],
'sodium_crypto_shorthash_keygen' => ['string'],
'sodium_crypto_sign' => ['string', 'message'=>'string', 'secret_key'=>'string'],
'sodium_crypto_sign_detached' => ['string', 'message'=>'string', 'secret_key'=>'string'],
'sodium_crypto_sign_ed25519_pk_to_curve25519' => ['string', 'public_key'=>'string'],
'sodium_crypto_sign_ed25519_sk_to_curve25519' => ['string', 'secret_key'=>'string'],
'sodium_crypto_sign_keypair' => ['string'],
'sodium_crypto_sign_keypair_from_secretkey_and_publickey' => ['string', 'secret_key'=>'string', 'public_key'=>'string'],
'sodium_crypto_sign_open' => ['string|false', 'signed_message'=>'string', 'public_key'=>'string'],
'sodium_crypto_sign_publickey' => ['string', 'key_pair'=>'string'],
'sodium_crypto_sign_publickey_from_secretkey' => ['string', 'secret_key'=>'string'],
'sodium_crypto_sign_secretkey' => ['string', 'key_pair'=>'string'],
'sodium_crypto_sign_seed_keypair' => ['string', 'seed'=>'string'],
'sodium_crypto_sign_verify_detached' => ['bool', 'signature'=>'string', 'message'=>'string', 'public_key'=>'string'],
'sodium_crypto_stream' => ['string', 'length'=>'int', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_stream_keygen' => ['string'],
'sodium_crypto_stream_xor' => ['string', 'message'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_hex2bin' => ['string', 'string'=>'string', 'ignore='=>'string'],
'sodium_increment' => ['void', '&rw_string'=>'string'],
'sodium_memcmp' => ['int', 'string1'=>'string', 'string2'=>'string'],
'sodium_memzero' => ['void', '&w_string'=>'string'],
'sodium_pad' => ['string', 'string'=>'string', 'block_size'=>'int'],
'sodium_unpad' => ['string', 'string'=>'string', 'block_size'=>'int'],
'solid_fetch_prev' => ['bool', 'result_id'=>''],
'solr_get_version' => ['string|false'],
'SolrClient::__construct' => ['void', 'clientOptions'=>'array'],
'SolrClient::__destruct' => ['void'],
'SolrClient::addDocument' => ['SolrUpdateResponse', 'doc'=>'SolrInputDocument', 'allowdups='=>'bool', 'commitwithin='=>'int'],
'SolrClient::addDocuments' => ['SolrUpdateResponse', 'docs'=>'array', 'allowdups='=>'bool', 'commitwithin='=>'int'],
'SolrClient::commit' => ['SolrUpdateResponse', 'maxsegments='=>'int', 'waitflush='=>'bool', 'waitsearcher='=>'bool'],
'SolrClient::deleteById' => ['SolrUpdateResponse', 'id'=>'string'],
'SolrClient::deleteByIds' => ['SolrUpdateResponse', 'ids'=>'array'],
'SolrClient::deleteByQueries' => ['SolrUpdateResponse', 'queries'=>'array'],
'SolrClient::deleteByQuery' => ['SolrUpdateResponse', 'query'=>'string'],
'SolrClient::getById' => ['SolrQueryResponse', 'id'=>'string'],
'SolrClient::getByIds' => ['SolrQueryResponse', 'ids'=>'array'],
'SolrClient::getDebug' => ['string'],
'SolrClient::getOptions' => ['array'],
'SolrClient::optimize' => ['SolrUpdateResponse', 'maxsegments='=>'int', 'waitflush='=>'bool', 'waitsearcher='=>'bool'],
'SolrClient::ping' => ['SolrPingResponse'],
'SolrClient::query' => ['SolrQueryResponse', 'query'=>'SolrParams'],
'SolrClient::request' => ['SolrUpdateResponse', 'raw_request'=>'string'],
'SolrClient::rollback' => ['SolrUpdateResponse'],
'SolrClient::setResponseWriter' => ['void', 'responsewriter'=>'string'],
'SolrClient::setServlet' => ['bool', 'type'=>'int', 'value'=>'string'],
'SolrClient::system' => ['SolrGenericResponse'],
'SolrClient::threads' => ['SolrGenericResponse'],
'SolrClientException::__clone' => ['void'],
'SolrClientException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'SolrClientException::__toString' => ['string'],
'SolrClientException::__wakeup' => ['void'],
'SolrClientException::getCode' => ['int'],
'SolrClientException::getFile' => ['string'],
'SolrClientException::getInternalInfo' => ['array'],
'SolrClientException::getLine' => ['int'],
'SolrClientException::getMessage' => ['string'],
'SolrClientException::getPrevious' => ['?Exception|?Throwable'],
'SolrClientException::getTrace' => ['list<array<string,mixed>>'],
'SolrClientException::getTraceAsString' => ['string'],
'SolrCollapseFunction::__construct' => ['void', 'field'=>'string'],
'SolrCollapseFunction::__toString' => ['string'],
'SolrCollapseFunction::getField' => ['string'],
'SolrCollapseFunction::getHint' => ['string'],
'SolrCollapseFunction::getMax' => ['string'],
'SolrCollapseFunction::getMin' => ['string'],
'SolrCollapseFunction::getNullPolicy' => ['string'],
'SolrCollapseFunction::getSize' => ['int'],
'SolrCollapseFunction::setField' => ['SolrCollapseFunction', 'fieldName'=>'string'],
'SolrCollapseFunction::setHint' => ['SolrCollapseFunction', 'hint'=>'string'],
'SolrCollapseFunction::setMax' => ['SolrCollapseFunction', 'max'=>'string'],
'SolrCollapseFunction::setMin' => ['SolrCollapseFunction', 'min'=>'string'],
'SolrCollapseFunction::setNullPolicy' => ['SolrCollapseFunction', 'nullPolicy'=>'string'],
'SolrCollapseFunction::setSize' => ['SolrCollapseFunction', 'size'=>'int'],
'SolrDisMaxQuery::__construct' => ['void', 'q='=>'string'],
'SolrDisMaxQuery::__destruct' => ['void'],
'SolrDisMaxQuery::add' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrDisMaxQuery::addBigramPhraseField' => ['SolrDisMaxQuery', 'field'=>'string', 'boost'=>'string', 'slop='=>'string'],
'SolrDisMaxQuery::addBoostQuery' => ['SolrDisMaxQuery', 'field'=>'string', 'value'=>'string', 'boost='=>'string'],
'SolrDisMaxQuery::addExpandFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrDisMaxQuery::addExpandSortField' => ['SolrQuery', 'field'=>'string', 'order'=>'string'],
'SolrDisMaxQuery::addFacetDateField' => ['SolrQuery', 'dateField'=>'string'],
'SolrDisMaxQuery::addFacetDateOther' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::addFacetField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addFacetQuery' => ['SolrQuery', 'facetQuery'=>'string'],
'SolrDisMaxQuery::addField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrDisMaxQuery::addGroupField' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::addGroupFunction' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::addGroupQuery' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::addGroupSortField' => ['SolrQuery', 'field'=>'string', 'order'=>'int'],
'SolrDisMaxQuery::addHighlightField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addMltField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addMltQueryField' => ['SolrQuery', 'field'=>'string', 'boost'=>'float'],
'SolrDisMaxQuery::addParam' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrDisMaxQuery::addPhraseField' => ['SolrDisMaxQuery', 'field'=>'string', 'boost'=>'string', 'slop='=>'string'],
'SolrDisMaxQuery::addQueryField' => ['SolrDisMaxQuery', 'field'=>'string', 'boost='=>'string'],
'SolrDisMaxQuery::addSortField' => ['SolrQuery', 'field'=>'string', 'order='=>'int'],
'SolrDisMaxQuery::addStatsFacet' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addStatsField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addTrigramPhraseField' => ['SolrDisMaxQuery', 'field'=>'string', 'boost'=>'string', 'slop='=>'string'],
'SolrDisMaxQuery::addUserField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::collapse' => ['SolrQuery', 'collapseFunction'=>'SolrCollapseFunction'],
'SolrDisMaxQuery::get' => ['mixed', 'param_name'=>'string'],
'SolrDisMaxQuery::getExpand' => ['bool'],
'SolrDisMaxQuery::getExpandFilterQueries' => ['array'],
'SolrDisMaxQuery::getExpandQuery' => ['array'],
'SolrDisMaxQuery::getExpandRows' => ['int'],
'SolrDisMaxQuery::getExpandSortFields' => ['array'],
'SolrDisMaxQuery::getFacet' => ['bool'],
'SolrDisMaxQuery::getFacetDateEnd' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetDateFields' => ['array'],
'SolrDisMaxQuery::getFacetDateGap' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetDateHardEnd' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetDateOther' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetDateStart' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetFields' => ['array'],
'SolrDisMaxQuery::getFacetLimit' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetMethod' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetMinCount' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetMissing' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetOffset' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetPrefix' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetQueries' => ['string'],
'SolrDisMaxQuery::getFacetSort' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getFields' => ['string'],
'SolrDisMaxQuery::getFilterQueries' => ['string'],
'SolrDisMaxQuery::getGroup' => ['bool'],
'SolrDisMaxQuery::getGroupCachePercent' => ['int'],
'SolrDisMaxQuery::getGroupFacet' => ['bool'],
'SolrDisMaxQuery::getGroupFields' => ['array'],
'SolrDisMaxQuery::getGroupFormat' => ['string'],
'SolrDisMaxQuery::getGroupFunctions' => ['array'],
'SolrDisMaxQuery::getGroupLimit' => ['int'],
'SolrDisMaxQuery::getGroupMain' => ['bool'],
'SolrDisMaxQuery::getGroupNGroups' => ['bool'],
'SolrDisMaxQuery::getGroupOffset' => ['bool'],
'SolrDisMaxQuery::getGroupQueries' => ['array'],
'SolrDisMaxQuery::getGroupSortFields' => ['array'],
'SolrDisMaxQuery::getGroupTruncate' => ['bool'],
'SolrDisMaxQuery::getHighlight' => ['bool'],
'SolrDisMaxQuery::getHighlightAlternateField' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightFields' => ['array'],
'SolrDisMaxQuery::getHighlightFormatter' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightFragmenter' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightFragsize' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightHighlightMultiTerm' => ['bool'],
'SolrDisMaxQuery::getHighlightMaxAlternateFieldLength' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightMaxAnalyzedChars' => ['int'],
'SolrDisMaxQuery::getHighlightMergeContiguous' => ['bool', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightRegexMaxAnalyzedChars' => ['int'],
'SolrDisMaxQuery::getHighlightRegexPattern' => ['string'],
'SolrDisMaxQuery::getHighlightRegexSlop' => ['float'],
'SolrDisMaxQuery::getHighlightRequireFieldMatch' => ['bool'],
'SolrDisMaxQuery::getHighlightSimplePost' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightSimplePre' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightSnippets' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightUsePhraseHighlighter' => ['bool'],
'SolrDisMaxQuery::getMlt' => ['bool'],
'SolrDisMaxQuery::getMltBoost' => ['bool'],
'SolrDisMaxQuery::getMltCount' => ['int'],
'SolrDisMaxQuery::getMltFields' => ['array'],
'SolrDisMaxQuery::getMltMaxNumQueryTerms' => ['int'],
'SolrDisMaxQuery::getMltMaxNumTokens' => ['int'],
'SolrDisMaxQuery::getMltMaxWordLength' => ['int'],
'SolrDisMaxQuery::getMltMinDocFrequency' => ['int'],
'SolrDisMaxQuery::getMltMinTermFrequency' => ['int'],
'SolrDisMaxQuery::getMltMinWordLength' => ['int'],
'SolrDisMaxQuery::getMltQueryFields' => ['array'],
'SolrDisMaxQuery::getParam' => ['mixed', 'param_name'=>'string'],
'SolrDisMaxQuery::getParams' => ['array'],
'SolrDisMaxQuery::getPreparedParams' => ['array'],
'SolrDisMaxQuery::getQuery' => ['string'],
'SolrDisMaxQuery::getRows' => ['int'],
'SolrDisMaxQuery::getSortFields' => ['array'],
'SolrDisMaxQuery::getStart' => ['int'],
'SolrDisMaxQuery::getStats' => ['bool'],
'SolrDisMaxQuery::getStatsFacets' => ['array'],
'SolrDisMaxQuery::getStatsFields' => ['array'],
'SolrDisMaxQuery::getTerms' => ['bool'],
'SolrDisMaxQuery::getTermsField' => ['string'],
'SolrDisMaxQuery::getTermsIncludeLowerBound' => ['bool'],
'SolrDisMaxQuery::getTermsIncludeUpperBound' => ['bool'],
'SolrDisMaxQuery::getTermsLimit' => ['int'],
'SolrDisMaxQuery::getTermsLowerBound' => ['string'],
'SolrDisMaxQuery::getTermsMaxCount' => ['int'],
'SolrDisMaxQuery::getTermsMinCount' => ['int'],
'SolrDisMaxQuery::getTermsPrefix' => ['string'],
'SolrDisMaxQuery::getTermsReturnRaw' => ['bool'],
'SolrDisMaxQuery::getTermsSort' => ['int'],
'SolrDisMaxQuery::getTermsUpperBound' => ['string'],
'SolrDisMaxQuery::getTimeAllowed' => ['int'],
'SolrDisMaxQuery::removeBigramPhraseField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeBoostQuery' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeExpandFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrDisMaxQuery::removeExpandSortField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeFacetDateField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeFacetDateOther' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::removeFacetField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeFacetQuery' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::removeField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrDisMaxQuery::removeHighlightField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeMltField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeMltQueryField' => ['SolrQuery', 'queryField'=>'string'],
'SolrDisMaxQuery::removePhraseField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeQueryField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeSortField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeStatsFacet' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::removeStatsField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeTrigramPhraseField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeUserField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::serialize' => ['string'],
'SolrDisMaxQuery::set' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrDisMaxQuery::setBigramPhraseFields' => ['SolrDisMaxQuery', 'fields'=>'string'],
'SolrDisMaxQuery::setBigramPhraseSlop' => ['SolrDisMaxQuery', 'slop'=>'string'],
'SolrDisMaxQuery::setBoostFunction' => ['SolrDisMaxQuery', 'function'=>'string'],
'SolrDisMaxQuery::setBoostQuery' => ['SolrDisMaxQuery', 'q'=>'string'],
'SolrDisMaxQuery::setEchoHandler' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setEchoParams' => ['SolrQuery', 'type'=>'string'],
'SolrDisMaxQuery::setExpand' => ['SolrQuery', 'value'=>'bool'],
'SolrDisMaxQuery::setExpandQuery' => ['SolrQuery', 'q'=>'string'],
'SolrDisMaxQuery::setExpandRows' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setExplainOther' => ['SolrQuery', 'query'=>'string'],
'SolrDisMaxQuery::setFacet' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setFacetDateEnd' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetDateGap' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetDateHardEnd' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetDateStart' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetEnumCacheMinDefaultFrequency' => ['SolrQuery', 'frequency'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetLimit' => ['SolrQuery', 'limit'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetMethod' => ['SolrQuery', 'method'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetMinCount' => ['SolrQuery', 'mincount'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetMissing' => ['SolrQuery', 'flag'=>'bool', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetOffset' => ['SolrQuery', 'offset'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetPrefix' => ['SolrQuery', 'prefix'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetSort' => ['SolrQuery', 'facetSort'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setGroup' => ['SolrQuery', 'value'=>'bool'],
'SolrDisMaxQuery::setGroupCachePercent' => ['SolrQuery', 'percent'=>'int'],
'SolrDisMaxQuery::setGroupFacet' => ['SolrQuery', 'value'=>'bool'],
'SolrDisMaxQuery::setGroupFormat' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::setGroupLimit' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setGroupMain' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::setGroupNGroups' => ['SolrQuery', 'value'=>'bool'],
'SolrDisMaxQuery::setGroupOffset' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setGroupTruncate' => ['SolrQuery', 'value'=>'bool'],
'SolrDisMaxQuery::setHighlight' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setHighlightAlternateField' => ['SolrQuery', 'field'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightFormatter' => ['SolrQuery', 'formatter'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightFragmenter' => ['SolrQuery', 'fragmenter'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightFragsize' => ['SolrQuery', 'size'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightHighlightMultiTerm' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setHighlightMaxAlternateFieldLength' => ['SolrQuery', 'fieldLength'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightMaxAnalyzedChars' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setHighlightMergeContiguous' => ['SolrQuery', 'flag'=>'bool', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightRegexMaxAnalyzedChars' => ['SolrQuery', 'maxAnalyzedChars'=>'int'],
'SolrDisMaxQuery::setHighlightRegexPattern' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::setHighlightRegexSlop' => ['SolrQuery', 'factor'=>'float'],
'SolrDisMaxQuery::setHighlightRequireFieldMatch' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setHighlightSimplePost' => ['SolrQuery', 'simplePost'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightSimplePre' => ['SolrQuery', 'simplePre'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightSnippets' => ['SolrQuery', 'value'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightUsePhraseHighlighter' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setMinimumMatch' => ['SolrDisMaxQuery', 'value'=>'string'],
'SolrDisMaxQuery::setMlt' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setMltBoost' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setMltCount' => ['SolrQuery', 'count'=>'int'],
'SolrDisMaxQuery::setMltMaxNumQueryTerms' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setMltMaxNumTokens' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setMltMaxWordLength' => ['SolrQuery', 'maxWordLength'=>'int'],
'SolrDisMaxQuery::setMltMinDocFrequency' => ['SolrQuery', 'minDocFrequency'=>'int'],
'SolrDisMaxQuery::setMltMinTermFrequency' => ['SolrQuery', 'minTermFrequency'=>'int'],
'SolrDisMaxQuery::setMltMinWordLength' => ['SolrQuery', 'minWordLength'=>'int'],
'SolrDisMaxQuery::setOmitHeader' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setParam' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrDisMaxQuery::setPhraseFields' => ['SolrDisMaxQuery', 'fields'=>'string'],
'SolrDisMaxQuery::setPhraseSlop' => ['SolrDisMaxQuery', 'slop'=>'string'],
'SolrDisMaxQuery::setQuery' => ['SolrQuery', 'query'=>'string'],
'SolrDisMaxQuery::setQueryAlt' => ['SolrDisMaxQuery', 'q'=>'string'],
'SolrDisMaxQuery::setQueryPhraseSlop' => ['SolrDisMaxQuery', 'slop'=>'string'],
'SolrDisMaxQuery::setRows' => ['SolrQuery', 'rows'=>'int'],
'SolrDisMaxQuery::setShowDebugInfo' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setStart' => ['SolrQuery', 'start'=>'int'],
'SolrDisMaxQuery::setStats' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setTerms' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setTermsField' => ['SolrQuery', 'fieldname'=>'string'],
'SolrDisMaxQuery::setTermsIncludeLowerBound' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setTermsIncludeUpperBound' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setTermsLimit' => ['SolrQuery', 'limit'=>'int'],
'SolrDisMaxQuery::setTermsLowerBound' => ['SolrQuery', 'lowerBound'=>'string'],
'SolrDisMaxQuery::setTermsMaxCount' => ['SolrQuery', 'frequency'=>'int'],
'SolrDisMaxQuery::setTermsMinCount' => ['SolrQuery', 'frequency'=>'int'],
'SolrDisMaxQuery::setTermsPrefix' => ['SolrQuery', 'prefix'=>'string'],
'SolrDisMaxQuery::setTermsReturnRaw' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setTermsSort' => ['SolrQuery', 'sortType'=>'int'],
'SolrDisMaxQuery::setTermsUpperBound' => ['SolrQuery', 'upperBound'=>'string'],
'SolrDisMaxQuery::setTieBreaker' => ['SolrDisMaxQuery', 'tieBreaker'=>'string'],
'SolrDisMaxQuery::setTimeAllowed' => ['SolrQuery', 'timeAllowed'=>'int'],
'SolrDisMaxQuery::setTrigramPhraseFields' => ['SolrDisMaxQuery', 'fields'=>'string'],
'SolrDisMaxQuery::setTrigramPhraseSlop' => ['SolrDisMaxQuery', 'slop'=>'string'],
'SolrDisMaxQuery::setUserFields' => ['SolrDisMaxQuery', 'fields'=>'string'],
'SolrDisMaxQuery::toString' => ['string', 'url_encode='=>'bool'],
'SolrDisMaxQuery::unserialize' => ['void', 'serialized'=>'string'],
'SolrDisMaxQuery::useDisMaxQueryParser' => ['SolrDisMaxQuery'],
'SolrDisMaxQuery::useEDisMaxQueryParser' => ['SolrDisMaxQuery'],
'SolrDocument::__clone' => ['void'],
'SolrDocument::__construct' => ['void'],
'SolrDocument::__destruct' => ['void'],
'SolrDocument::__get' => ['SolrDocumentField', 'fieldname'=>'string'],
'SolrDocument::__isset' => ['bool', 'fieldname'=>'string'],
'SolrDocument::__set' => ['bool', 'fieldname'=>'string', 'fieldvalue'=>'string'],
'SolrDocument::__unset' => ['bool', 'fieldname'=>'string'],
'SolrDocument::addField' => ['bool', 'fieldname'=>'string', 'fieldvalue'=>'string'],
'SolrDocument::clear' => ['bool'],
'SolrDocument::current' => ['SolrDocumentField'],
'SolrDocument::deleteField' => ['bool', 'fieldname'=>'string'],
'SolrDocument::fieldExists' => ['bool', 'fieldname'=>'string'],
'SolrDocument::getChildDocuments' => ['SolrInputDocument[]'],
'SolrDocument::getChildDocumentsCount' => ['int'],
'SolrDocument::getField' => ['SolrDocumentField|false', 'fieldname'=>'string'],
'SolrDocument::getFieldCount' => ['int|false'],
'SolrDocument::getFieldNames' => ['array|false'],
'SolrDocument::getInputDocument' => ['SolrInputDocument'],
'SolrDocument::hasChildDocuments' => ['bool'],
'SolrDocument::key' => ['string'],
'SolrDocument::merge' => ['bool', 'sourcedoc'=>'solrdocument', 'overwrite='=>'bool'],
'SolrDocument::next' => ['void'],
'SolrDocument::offsetExists' => ['bool', 'fieldname'=>'string'],
'SolrDocument::offsetGet' => ['SolrDocumentField', 'fieldname'=>'string'],
'SolrDocument::offsetSet' => ['void', 'fieldname'=>'string', 'fieldvalue'=>'string'],
'SolrDocument::offsetUnset' => ['void', 'fieldname'=>'string'],
'SolrDocument::reset' => ['bool'],
'SolrDocument::rewind' => ['void'],
'SolrDocument::serialize' => ['string'],
'SolrDocument::sort' => ['bool', 'sortorderby'=>'int', 'sortdirection='=>'int'],
'SolrDocument::toArray' => ['array'],
'SolrDocument::unserialize' => ['void', 'serialized'=>'string'],
'SolrDocument::valid' => ['bool'],
'SolrDocumentField::__construct' => ['void'],
'SolrDocumentField::__destruct' => ['void'],
'SolrException::__clone' => ['void'],
'SolrException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'SolrException::__toString' => ['string'],
'SolrException::__wakeup' => ['void'],
'SolrException::getCode' => ['int'],
'SolrException::getFile' => ['string'],
'SolrException::getInternalInfo' => ['array'],
'SolrException::getLine' => ['int'],
'SolrException::getMessage' => ['string'],
'SolrException::getPrevious' => ['Exception|Throwable'],
'SolrException::getTrace' => ['list<array<string,mixed>>'],
'SolrException::getTraceAsString' => ['string'],
'SolrGenericResponse::__construct' => ['void'],
'SolrGenericResponse::__destruct' => ['void'],
'SolrGenericResponse::getDigestedResponse' => ['string'],
'SolrGenericResponse::getHttpStatus' => ['int'],
'SolrGenericResponse::getHttpStatusMessage' => ['string'],
'SolrGenericResponse::getRawRequest' => ['string'],
'SolrGenericResponse::getRawRequestHeaders' => ['string'],
'SolrGenericResponse::getRawResponse' => ['string'],
'SolrGenericResponse::getRawResponseHeaders' => ['string'],
'SolrGenericResponse::getRequestUrl' => ['string'],
'SolrGenericResponse::getResponse' => ['SolrObject'],
'SolrGenericResponse::setParseMode' => ['bool', 'parser_mode='=>'int'],
'SolrGenericResponse::success' => ['bool'],
'SolrIllegalArgumentException::__clone' => ['void'],
'SolrIllegalArgumentException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'SolrIllegalArgumentException::__toString' => ['string'],
'SolrIllegalArgumentException::__wakeup' => ['void'],
'SolrIllegalArgumentException::getCode' => ['int'],
'SolrIllegalArgumentException::getFile' => ['string'],
'SolrIllegalArgumentException::getInternalInfo' => ['array'],
'SolrIllegalArgumentException::getLine' => ['int'],
'SolrIllegalArgumentException::getMessage' => ['string'],
'SolrIllegalArgumentException::getPrevious' => ['Exception|Throwable'],
'SolrIllegalArgumentException::getTrace' => ['list<array<string,mixed>>'],
'SolrIllegalArgumentException::getTraceAsString' => ['string'],
'SolrIllegalOperationException::__clone' => ['void'],
'SolrIllegalOperationException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'SolrIllegalOperationException::__toString' => ['string'],
'SolrIllegalOperationException::__wakeup' => ['void'],
'SolrIllegalOperationException::getCode' => ['int'],
'SolrIllegalOperationException::getFile' => ['string'],
'SolrIllegalOperationException::getInternalInfo' => ['array'],
'SolrIllegalOperationException::getLine' => ['int'],
'SolrIllegalOperationException::getMessage' => ['string'],
'SolrIllegalOperationException::getPrevious' => ['Exception|Throwable'],
'SolrIllegalOperationException::getTrace' => ['list<array<string,mixed>>'],
'SolrIllegalOperationException::getTraceAsString' => ['string'],
'SolrInputDocument::__clone' => ['void'],
'SolrInputDocument::__construct' => ['void'],
'SolrInputDocument::__destruct' => ['void'],
'SolrInputDocument::addChildDocument' => ['void', 'child'=>'SolrInputDocument'],
'SolrInputDocument::addChildDocuments' => ['void', 'docs'=>'array'],
'SolrInputDocument::addField' => ['bool', 'fieldname'=>'string', 'fieldvalue'=>'string', 'fieldboostvalue='=>'float'],
'SolrInputDocument::clear' => ['bool'],
'SolrInputDocument::deleteField' => ['bool', 'fieldname'=>'string'],
'SolrInputDocument::fieldExists' => ['bool', 'fieldname'=>'string'],
'SolrInputDocument::getBoost' => ['float|false'],
'SolrInputDocument::getChildDocuments' => ['SolrInputDocument[]'],
'SolrInputDocument::getChildDocumentsCount' => ['int'],
'SolrInputDocument::getField' => ['SolrDocumentField|false', 'fieldname'=>'string'],
'SolrInputDocument::getFieldBoost' => ['float|false', 'fieldname'=>'string'],
'SolrInputDocument::getFieldCount' => ['int|false'],
'SolrInputDocument::getFieldNames' => ['array|false'],
'SolrInputDocument::hasChildDocuments' => ['bool'],
'SolrInputDocument::merge' => ['bool', 'sourcedoc'=>'SolrInputDocument', 'overwrite='=>'bool'],
'SolrInputDocument::reset' => ['bool'],
'SolrInputDocument::setBoost' => ['bool', 'documentboostvalue'=>'float'],
'SolrInputDocument::setFieldBoost' => ['bool', 'fieldname'=>'string', 'fieldboostvalue'=>'float'],
'SolrInputDocument::sort' => ['bool', 'sortorderby'=>'int', 'sortdirection='=>'int'],
'SolrInputDocument::toArray' => ['array|false'],
'SolrModifiableParams::__construct' => ['void'],
'SolrModifiableParams::__destruct' => ['void'],
'SolrModifiableParams::add' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrModifiableParams::addParam' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrModifiableParams::get' => ['mixed', 'param_name'=>'string'],
'SolrModifiableParams::getParam' => ['mixed', 'param_name'=>'string'],
'SolrModifiableParams::getParams' => ['array'],
'SolrModifiableParams::getPreparedParams' => ['array'],
'SolrModifiableParams::serialize' => ['string'],
'SolrModifiableParams::set' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrModifiableParams::setParam' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrModifiableParams::toString' => ['string', 'url_encode='=>'bool'],
'SolrModifiableParams::unserialize' => ['void', 'serialized'=>'string'],
'SolrObject::__construct' => ['void'],
'SolrObject::__destruct' => ['void'],
'SolrObject::getPropertyNames' => ['array'],
'SolrObject::offsetExists' => ['bool', 'property_name'=>'string'],
'SolrObject::offsetGet' => ['SolrDocumentField', 'property_name'=>'string'],
'SolrObject::offsetSet' => ['void', 'property_name'=>'string', 'property_value'=>'string'],
'SolrObject::offsetUnset' => ['void', 'property_name'=>'string'],
'SolrParams::__construct' => ['void'],
'SolrParams::add' => ['SolrParams|false', 'name'=>'string', 'value'=>'string'],
'SolrParams::addParam' => ['SolrParams|false', 'name'=>'string', 'value'=>'string'],
'SolrParams::get' => ['mixed', 'param_name'=>'string'],
'SolrParams::getParam' => ['mixed', 'param_name='=>'string'],
'SolrParams::getParams' => ['array'],
'SolrParams::getPreparedParams' => ['array'],
'SolrParams::serialize' => ['string'],
'SolrParams::set' => ['SolrParams|false', 'name'=>'string', 'value'=>'string'],
'SolrParams::setParam' => ['SolrParams|false', 'name'=>'string', 'value'=>'string'],
'SolrParams::toString' => ['string|false', 'url_encode='=>'bool'],
'SolrParams::unserialize' => ['void', 'serialized'=>'string'],
'SolrPingResponse::__construct' => ['void'],
'SolrPingResponse::__destruct' => ['void'],
'SolrPingResponse::getDigestedResponse' => ['string'],
'SolrPingResponse::getHttpStatus' => ['int'],
'SolrPingResponse::getHttpStatusMessage' => ['string'],
'SolrPingResponse::getRawRequest' => ['string'],
'SolrPingResponse::getRawRequestHeaders' => ['string'],
'SolrPingResponse::getRawResponse' => ['string'],
'SolrPingResponse::getRawResponseHeaders' => ['string'],
'SolrPingResponse::getRequestUrl' => ['string'],
'SolrPingResponse::getResponse' => ['string'],
'SolrPingResponse::setParseMode' => ['bool', 'parser_mode='=>'int'],
'SolrPingResponse::success' => ['bool'],
'SolrQuery::__construct' => ['void', 'q='=>'string'],
'SolrQuery::__destruct' => ['void'],
'SolrQuery::add' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrQuery::addExpandFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrQuery::addExpandSortField' => ['SolrQuery', 'field'=>'string', 'order='=>'string'],
'SolrQuery::addFacetDateField' => ['SolrQuery', 'datefield'=>'string'],
'SolrQuery::addFacetDateOther' => ['SolrQuery', 'value'=>'string', 'field_override='=>'string'],
'SolrQuery::addFacetField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::addFacetQuery' => ['SolrQuery', 'facetquery'=>'string'],
'SolrQuery::addField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::addFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrQuery::addGroupField' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::addGroupFunction' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::addGroupQuery' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::addGroupSortField' => ['SolrQuery', 'field'=>'string', 'order='=>'int'],
'SolrQuery::addHighlightField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::addMltField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::addMltQueryField' => ['SolrQuery', 'field'=>'string', 'boost'=>'float'],
'SolrQuery::addParam' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrQuery::addSortField' => ['SolrQuery', 'field'=>'string', 'order='=>'int'],
'SolrQuery::addStatsFacet' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::addStatsField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::collapse' => ['SolrQuery', 'collapseFunction'=>'SolrCollapseFunction'],
'SolrQuery::get' => ['mixed', 'param_name'=>'string'],
'SolrQuery::getExpand' => ['bool'],
'SolrQuery::getExpandFilterQueries' => ['array'],
'SolrQuery::getExpandQuery' => ['array'],
'SolrQuery::getExpandRows' => ['int'],
'SolrQuery::getExpandSortFields' => ['array'],
'SolrQuery::getFacet' => ['?bool'],
'SolrQuery::getFacetDateEnd' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetDateFields' => ['array'],
'SolrQuery::getFacetDateGap' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetDateHardEnd' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetDateOther' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetDateStart' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetFields' => ['array'],
'SolrQuery::getFacetLimit' => ['?int', 'field_override='=>'string'],
'SolrQuery::getFacetMethod' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetMinCount' => ['?int', 'field_override='=>'string'],
'SolrQuery::getFacetMissing' => ['?bool', 'field_override='=>'string'],
'SolrQuery::getFacetOffset' => ['?int', 'field_override='=>'string'],
'SolrQuery::getFacetPrefix' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetQueries' => ['?array'],
'SolrQuery::getFacetSort' => ['int', 'field_override='=>'string'],
'SolrQuery::getFields' => ['?array'],
'SolrQuery::getFilterQueries' => ['?array'],
'SolrQuery::getGroup' => ['bool'],
'SolrQuery::getGroupCachePercent' => ['int'],
'SolrQuery::getGroupFacet' => ['bool'],
'SolrQuery::getGroupFields' => ['array'],
'SolrQuery::getGroupFormat' => ['string'],
'SolrQuery::getGroupFunctions' => ['array'],
'SolrQuery::getGroupLimit' => ['int'],
'SolrQuery::getGroupMain' => ['bool'],
'SolrQuery::getGroupNGroups' => ['bool'],
'SolrQuery::getGroupOffset' => ['int'],
'SolrQuery::getGroupQueries' => ['array'],
'SolrQuery::getGroupSortFields' => ['array'],
'SolrQuery::getGroupTruncate' => ['bool'],
'SolrQuery::getHighlight' => ['bool'],
'SolrQuery::getHighlightAlternateField' => ['?string', 'field_override='=>'string'],
'SolrQuery::getHighlightFields' => ['?array'],
'SolrQuery::getHighlightFormatter' => ['?string', 'field_override='=>'string'],
'SolrQuery::getHighlightFragmenter' => ['?string', 'field_override='=>'string'],
'SolrQuery::getHighlightFragsize' => ['?int', 'field_override='=>'string'],
'SolrQuery::getHighlightHighlightMultiTerm' => ['?bool'],
'SolrQuery::getHighlightMaxAlternateFieldLength' => ['?int', 'field_override='=>'string'],
'SolrQuery::getHighlightMaxAnalyzedChars' => ['?int'],
'SolrQuery::getHighlightMergeContiguous' => ['?bool', 'field_override='=>'string'],
'SolrQuery::getHighlightRegexMaxAnalyzedChars' => ['?int'],
'SolrQuery::getHighlightRegexPattern' => ['?string'],
'SolrQuery::getHighlightRegexSlop' => ['?float'],
'SolrQuery::getHighlightRequireFieldMatch' => ['?bool'],
'SolrQuery::getHighlightSimplePost' => ['?string', 'field_override='=>'string'],
'SolrQuery::getHighlightSimplePre' => ['?string', 'field_override='=>'string'],
'SolrQuery::getHighlightSnippets' => ['?int', 'field_override='=>'string'],
'SolrQuery::getHighlightUsePhraseHighlighter' => ['?bool'],
'SolrQuery::getMlt' => ['?bool'],
'SolrQuery::getMltBoost' => ['?bool'],
'SolrQuery::getMltCount' => ['?int'],
'SolrQuery::getMltFields' => ['?array'],
'SolrQuery::getMltMaxNumQueryTerms' => ['?int'],
'SolrQuery::getMltMaxNumTokens' => ['?int'],
'SolrQuery::getMltMaxWordLength' => ['?int'],
'SolrQuery::getMltMinDocFrequency' => ['?int'],
'SolrQuery::getMltMinTermFrequency' => ['?int'],
'SolrQuery::getMltMinWordLength' => ['?int'],
'SolrQuery::getMltQueryFields' => ['?array'],
'SolrQuery::getParam' => ['?mixed', 'param_name'=>'string'],
'SolrQuery::getParams' => ['?array'],
'SolrQuery::getPreparedParams' => ['?array'],
'SolrQuery::getQuery' => ['?string'],
'SolrQuery::getRows' => ['?int'],
'SolrQuery::getSortFields' => ['?array'],
'SolrQuery::getStart' => ['?int'],
'SolrQuery::getStats' => ['?bool'],
'SolrQuery::getStatsFacets' => ['?array'],
'SolrQuery::getStatsFields' => ['?array'],
'SolrQuery::getTerms' => ['?bool'],
'SolrQuery::getTermsField' => ['?string'],
'SolrQuery::getTermsIncludeLowerBound' => ['?bool'],
'SolrQuery::getTermsIncludeUpperBound' => ['?bool'],
'SolrQuery::getTermsLimit' => ['?int'],
'SolrQuery::getTermsLowerBound' => ['?string'],
'SolrQuery::getTermsMaxCount' => ['?int'],
'SolrQuery::getTermsMinCount' => ['?int'],
'SolrQuery::getTermsPrefix' => ['?string'],
'SolrQuery::getTermsReturnRaw' => ['?bool'],
'SolrQuery::getTermsSort' => ['?int'],
'SolrQuery::getTermsUpperBound' => ['?string'],
'SolrQuery::getTimeAllowed' => ['?int'],
'SolrQuery::removeExpandFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrQuery::removeExpandSortField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeFacetDateField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeFacetDateOther' => ['SolrQuery', 'value'=>'string', 'field_override='=>'string'],
'SolrQuery::removeFacetField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeFacetQuery' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::removeField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrQuery::removeHighlightField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeMltField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeMltQueryField' => ['SolrQuery', 'queryfield'=>'string'],
'SolrQuery::removeSortField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeStatsFacet' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::removeStatsField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::serialize' => ['string'],
'SolrQuery::set' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrQuery::setEchoHandler' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setEchoParams' => ['SolrQuery', 'type'=>'string'],
'SolrQuery::setExpand' => ['SolrQuery', 'value'=>'bool'],
'SolrQuery::setExpandQuery' => ['SolrQuery', 'q'=>'string'],
'SolrQuery::setExpandRows' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setExplainOther' => ['SolrQuery', 'query'=>'string'],
'SolrQuery::setFacet' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setFacetDateEnd' => ['SolrQuery', 'value'=>'string', 'field_override='=>'string'],
'SolrQuery::setFacetDateGap' => ['SolrQuery', 'value'=>'string', 'field_override='=>'string'],
'SolrQuery::setFacetDateHardEnd' => ['SolrQuery', 'value'=>'bool', 'field_override='=>'string'],
'SolrQuery::setFacetDateStart' => ['SolrQuery', 'value'=>'string', 'field_override='=>'string'],
'SolrQuery::setFacetEnumCacheMinDefaultFrequency' => ['SolrQuery', 'frequency'=>'int', 'field_override='=>'string'],
'SolrQuery::setFacetLimit' => ['SolrQuery', 'limit'=>'int', 'field_override='=>'string'],
'SolrQuery::setFacetMethod' => ['SolrQuery', 'method'=>'string', 'field_override='=>'string'],
'SolrQuery::setFacetMinCount' => ['SolrQuery', 'mincount'=>'int', 'field_override='=>'string'],
'SolrQuery::setFacetMissing' => ['SolrQuery', 'flag'=>'bool', 'field_override='=>'string'],
'SolrQuery::setFacetOffset' => ['SolrQuery', 'offset'=>'int', 'field_override='=>'string'],
'SolrQuery::setFacetPrefix' => ['SolrQuery', 'prefix'=>'string', 'field_override='=>'string'],
'SolrQuery::setFacetSort' => ['SolrQuery', 'facetsort'=>'int', 'field_override='=>'string'],
'SolrQuery::setGroup' => ['SolrQuery', 'value'=>'bool'],
'SolrQuery::setGroupCachePercent' => ['SolrQuery', 'percent'=>'int'],
'SolrQuery::setGroupFacet' => ['SolrQuery', 'value'=>'bool'],
'SolrQuery::setGroupFormat' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::setGroupLimit' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setGroupMain' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::setGroupNGroups' => ['SolrQuery', 'value'=>'bool'],
'SolrQuery::setGroupOffset' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setGroupTruncate' => ['SolrQuery', 'value'=>'bool'],
'SolrQuery::setHighlight' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setHighlightAlternateField' => ['SolrQuery', 'field'=>'string', 'field_override='=>'string'],
'SolrQuery::setHighlightFormatter' => ['SolrQuery', 'formatter'=>'string', 'field_override='=>'string'],
'SolrQuery::setHighlightFragmenter' => ['SolrQuery', 'fragmenter'=>'string', 'field_override='=>'string'],
'SolrQuery::setHighlightFragsize' => ['SolrQuery', 'size'=>'int', 'field_override='=>'string'],
'SolrQuery::setHighlightHighlightMultiTerm' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setHighlightMaxAlternateFieldLength' => ['SolrQuery', 'fieldlength'=>'int', 'field_override='=>'string'],
'SolrQuery::setHighlightMaxAnalyzedChars' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setHighlightMergeContiguous' => ['SolrQuery', 'flag'=>'bool', 'field_override='=>'string'],
'SolrQuery::setHighlightRegexMaxAnalyzedChars' => ['SolrQuery', 'maxanalyzedchars'=>'int'],
'SolrQuery::setHighlightRegexPattern' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::setHighlightRegexSlop' => ['SolrQuery', 'factor'=>'float'],
'SolrQuery::setHighlightRequireFieldMatch' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setHighlightSimplePost' => ['SolrQuery', 'simplepost'=>'string', 'field_override='=>'string'],
'SolrQuery::setHighlightSimplePre' => ['SolrQuery', 'simplepre'=>'string', 'field_override='=>'string'],
'SolrQuery::setHighlightSnippets' => ['SolrQuery', 'value'=>'int', 'field_override='=>'string'],
'SolrQuery::setHighlightUsePhraseHighlighter' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setMlt' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setMltBoost' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setMltCount' => ['SolrQuery', 'count'=>'int'],
'SolrQuery::setMltMaxNumQueryTerms' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setMltMaxNumTokens' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setMltMaxWordLength' => ['SolrQuery', 'maxwordlength'=>'int'],
'SolrQuery::setMltMinDocFrequency' => ['SolrQuery', 'mindocfrequency'=>'int'],
'SolrQuery::setMltMinTermFrequency' => ['SolrQuery', 'mintermfrequency'=>'int'],
'SolrQuery::setMltMinWordLength' => ['SolrQuery', 'minwordlength'=>'int'],
'SolrQuery::setOmitHeader' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setParam' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrQuery::setQuery' => ['SolrQuery', 'query'=>'string'],
'SolrQuery::setRows' => ['SolrQuery', 'rows'=>'int'],
'SolrQuery::setShowDebugInfo' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setStart' => ['SolrQuery', 'start'=>'int'],
'SolrQuery::setStats' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setTerms' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setTermsField' => ['SolrQuery', 'fieldname'=>'string'],
'SolrQuery::setTermsIncludeLowerBound' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setTermsIncludeUpperBound' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setTermsLimit' => ['SolrQuery', 'limit'=>'int'],
'SolrQuery::setTermsLowerBound' => ['SolrQuery', 'lowerbound'=>'string'],
'SolrQuery::setTermsMaxCount' => ['SolrQuery', 'frequency'=>'int'],
'SolrQuery::setTermsMinCount' => ['SolrQuery', 'frequency'=>'int'],
'SolrQuery::setTermsPrefix' => ['SolrQuery', 'prefix'=>'string'],
'SolrQuery::setTermsReturnRaw' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setTermsSort' => ['SolrQuery', 'sorttype'=>'int'],
'SolrQuery::setTermsUpperBound' => ['SolrQuery', 'upperbound'=>'string'],
'SolrQuery::setTimeAllowed' => ['SolrQuery', 'timeallowed'=>'int'],
'SolrQuery::toString' => ['string', 'url_encode='=>'bool'],
'SolrQuery::unserialize' => ['void', 'serialized'=>'string'],
'SolrQueryResponse::__construct' => ['void'],
'SolrQueryResponse::__destruct' => ['void'],
'SolrQueryResponse::getDigestedResponse' => ['string'],
'SolrQueryResponse::getHttpStatus' => ['int'],
'SolrQueryResponse::getHttpStatusMessage' => ['string'],
'SolrQueryResponse::getRawRequest' => ['string'],
'SolrQueryResponse::getRawRequestHeaders' => ['string'],
'SolrQueryResponse::getRawResponse' => ['string'],
'SolrQueryResponse::getRawResponseHeaders' => ['string'],
'SolrQueryResponse::getRequestUrl' => ['string'],
'SolrQueryResponse::getResponse' => ['SolrObject'],
'SolrQueryResponse::setParseMode' => ['bool', 'parser_mode='=>'int'],
'SolrQueryResponse::success' => ['bool'],
'SolrResponse::getDigestedResponse' => ['string'],
'SolrResponse::getHttpStatus' => ['int'],
'SolrResponse::getHttpStatusMessage' => ['string'],
'SolrResponse::getRawRequest' => ['string'],
'SolrResponse::getRawRequestHeaders' => ['string'],
'SolrResponse::getRawResponse' => ['string'],
'SolrResponse::getRawResponseHeaders' => ['string'],
'SolrResponse::getRequestUrl' => ['string'],
'SolrResponse::getResponse' => ['SolrObject'],
'SolrResponse::setParseMode' => ['bool', 'parser_mode='=>'int'],
'SolrResponse::success' => ['bool'],
'SolrServerException::__clone' => ['void'],
'SolrServerException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'SolrServerException::__toString' => ['string'],
'SolrServerException::__wakeup' => ['void'],
'SolrServerException::getCode' => ['int'],
'SolrServerException::getFile' => ['string'],
'SolrServerException::getInternalInfo' => ['array'],
'SolrServerException::getLine' => ['int'],
'SolrServerException::getMessage' => ['string'],
'SolrServerException::getPrevious' => ['Exception|Throwable'],
'SolrServerException::getTrace' => ['list<array<string,mixed>>'],
'SolrServerException::getTraceAsString' => ['string'],
'SolrUpdateResponse::__construct' => ['void'],
'SolrUpdateResponse::__destruct' => ['void'],
'SolrUpdateResponse::getDigestedResponse' => ['string'],
'SolrUpdateResponse::getHttpStatus' => ['int'],
'SolrUpdateResponse::getHttpStatusMessage' => ['string'],
'SolrUpdateResponse::getRawRequest' => ['string'],
'SolrUpdateResponse::getRawRequestHeaders' => ['string'],
'SolrUpdateResponse::getRawResponse' => ['string'],
'SolrUpdateResponse::getRawResponseHeaders' => ['string'],
'SolrUpdateResponse::getRequestUrl' => ['string'],
'SolrUpdateResponse::getResponse' => ['SolrObject'],
'SolrUpdateResponse::setParseMode' => ['bool', 'parser_mode='=>'int'],
'SolrUpdateResponse::success' => ['bool'],
'SolrUtils::digestXmlResponse' => ['SolrObject', 'xmlresponse'=>'string', 'parse_mode='=>'int'],
'SolrUtils::escapeQueryChars' => ['string|false', 'string'=>'string'],
'SolrUtils::getSolrVersion' => ['string'],
'SolrUtils::queryPhrase' => ['string', 'string'=>'string'],
'sort' => ['bool', '&rw_array'=>'array', 'flags='=>'int'],
'soundex' => ['string', 'string'=>'string'],
'SphinxClient::__construct' => ['void'],
'SphinxClient::addQuery' => ['int', 'query'=>'string', 'index='=>'string', 'comment='=>'string'],
'SphinxClient::buildExcerpts' => ['array', 'docs'=>'array', 'index'=>'string', 'words'=>'string', 'opts='=>'array'],
'SphinxClient::buildKeywords' => ['array', 'query'=>'string', 'index'=>'string', 'hits'=>'bool'],
'SphinxClient::close' => ['bool'],
'SphinxClient::escapeString' => ['string', 'string'=>'string'],
'SphinxClient::getLastError' => ['string'],
'SphinxClient::getLastWarning' => ['string'],
'SphinxClient::open' => ['bool'],
'SphinxClient::query' => ['array', 'query'=>'string', 'index='=>'string', 'comment='=>'string'],
'SphinxClient::resetFilters' => ['void'],
'SphinxClient::resetGroupBy' => ['void'],
'SphinxClient::runQueries' => ['array'],
'SphinxClient::setArrayResult' => ['bool', 'array_result'=>'bool'],
'SphinxClient::setConnectTimeout' => ['bool', 'timeout'=>'float'],
'SphinxClient::setFieldWeights' => ['bool', 'weights'=>'array'],
'SphinxClient::setFilter' => ['bool', 'attribute'=>'string', 'values'=>'array', 'exclude='=>'bool'],
'SphinxClient::setFilterFloatRange' => ['bool', 'attribute'=>'string', 'min'=>'float', 'max'=>'float', 'exclude='=>'bool'],
'SphinxClient::setFilterRange' => ['bool', 'attribute'=>'string', 'min'=>'int', 'max'=>'int', 'exclude='=>'bool'],
'SphinxClient::setGeoAnchor' => ['bool', 'attrlat'=>'string', 'attrlong'=>'string', 'latitude'=>'float', 'longitude'=>'float'],
'SphinxClient::setGroupBy' => ['bool', 'attribute'=>'string', 'func'=>'int', 'groupsort='=>'string'],
'SphinxClient::setGroupDistinct' => ['bool', 'attribute'=>'string'],
'SphinxClient::setIDRange' => ['bool', 'min'=>'int', 'max'=>'int'],
'SphinxClient::setIndexWeights' => ['bool', 'weights'=>'array'],
'SphinxClient::setLimits' => ['bool', 'offset'=>'int', 'limit'=>'int', 'max_matches='=>'int', 'cutoff='=>'int'],
'SphinxClient::setMatchMode' => ['bool', 'mode'=>'int'],
'SphinxClient::setMaxQueryTime' => ['bool', 'qtime'=>'int'],
'SphinxClient::setOverride' => ['bool', 'attribute'=>'string', 'type'=>'int', 'values'=>'array'],
'SphinxClient::setRankingMode' => ['bool', 'ranker'=>'int'],
'SphinxClient::setRetries' => ['bool', 'count'=>'int', 'delay='=>'int'],
'SphinxClient::setSelect' => ['bool', 'clause'=>'string'],
'SphinxClient::setServer' => ['bool', 'server'=>'string', 'port'=>'int'],
'SphinxClient::setSortMode' => ['bool', 'mode'=>'int', 'sortby='=>'string'],
'SphinxClient::status' => ['array'],
'SphinxClient::updateAttributes' => ['int', 'index'=>'string', 'attributes'=>'array', 'values'=>'array', 'mva='=>'bool'],
'spl_autoload' => ['void', 'class'=>'string', 'file_extensions='=>'string'],
'spl_autoload_call' => ['void', 'class'=>'string'],
'spl_autoload_extensions' => ['string', 'file_extensions='=>'string'],
'spl_autoload_functions' => ['false|list<callable(string):void>'],
'spl_autoload_register' => ['bool', 'callback='=>'callable(string):void', 'throw='=>'bool', 'prepend='=>'bool'],
'spl_autoload_unregister' => ['bool', 'callback'=>'callable(string):void'],
'spl_classes' => ['array'],
'spl_object_hash' => ['string', 'object'=>'object'],
'spl_object_id' => ['int', 'object'=>'object'],
'SplDoublyLinkedList::__construct' => ['void'],
'SplDoublyLinkedList::add' => ['void', 'index'=>'mixed', 'newval'=>'mixed'],
'SplDoublyLinkedList::bottom' => ['mixed'],
'SplDoublyLinkedList::count' => ['int'],
'SplDoublyLinkedList::current' => ['mixed'],
'SplDoublyLinkedList::getIteratorMode' => ['int'],
'SplDoublyLinkedList::isEmpty' => ['bool'],
'SplDoublyLinkedList::key' => ['mixed'],
'SplDoublyLinkedList::next' => ['void'],
'SplDoublyLinkedList::offsetExists' => ['bool', 'index'=>'mixed'],
'SplDoublyLinkedList::offsetGet' => ['mixed', 'index'=>'mixed'],
'SplDoublyLinkedList::offsetSet' => ['void', 'index'=>'mixed', 'newval'=>'mixed'],
'SplDoublyLinkedList::offsetUnset' => ['void', 'index'=>'mixed'],
'SplDoublyLinkedList::pop' => ['mixed'],
'SplDoublyLinkedList::prev' => ['void'],
'SplDoublyLinkedList::push' => ['void', 'value'=>'mixed'],
'SplDoublyLinkedList::rewind' => ['void'],
'SplDoublyLinkedList::serialize' => ['string'],
'SplDoublyLinkedList::setIteratorMode' => ['void', 'flags'=>'int'],
'SplDoublyLinkedList::shift' => ['mixed'],
'SplDoublyLinkedList::top' => ['mixed'],
'SplDoublyLinkedList::unserialize' => ['void', 'serialized'=>'string'],
'SplDoublyLinkedList::unshift' => ['bool', 'value'=>'mixed'],
'SplDoublyLinkedList::valid' => ['bool'],
'SplEnum::__construct' => ['void', 'initial_value='=>'mixed', 'strict='=>'bool'],
'SplEnum::getConstList' => ['array', 'include_default='=>'bool'],
'SplFileInfo::__construct' => ['void', 'file_name'=>'string'],
'SplFileInfo::__toString' => ['string'],
'SplFileInfo::__wakeup' => ['void'],
'SplFileInfo::getATime' => ['int'],
'SplFileInfo::getBasename' => ['string', 'suffix='=>'string'],
'SplFileInfo::getCTime' => ['int'],
'SplFileInfo::getExtension' => ['string'],
'SplFileInfo::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplFileInfo::getFilename' => ['string'],
'SplFileInfo::getGroup' => ['int'],
'SplFileInfo::getInode' => ['int'],
'SplFileInfo::getLinkTarget' => ['string'],
'SplFileInfo::getMTime' => ['int'],
'SplFileInfo::getOwner' => ['int'],
'SplFileInfo::getPath' => ['string'],
'SplFileInfo::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplFileInfo::getPathname' => ['string'],
'SplFileInfo::getPerms' => ['int'],
'SplFileInfo::getRealPath' => ['string|false'],
'SplFileInfo::getSize' => ['int'],
'SplFileInfo::getType' => ['string'],
'SplFileInfo::isDir' => ['bool'],
'SplFileInfo::isExecutable' => ['bool'],
'SplFileInfo::isFile' => ['bool'],
'SplFileInfo::isLink' => ['bool'],
'SplFileInfo::isReadable' => ['bool'],
'SplFileInfo::isWritable' => ['bool'],
'SplFileInfo::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'SplFileInfo::setFileClass' => ['void', 'class_name='=>'string'],
'SplFileInfo::setInfoClass' => ['void', 'class_name='=>'string'],
'SplFileObject::__construct' => ['void', 'filename'=>'string', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>''],
'SplFileObject::__toString' => ['string'],
'SplFileObject::current' => ['string|array|false'],
'SplFileObject::eof' => ['bool'],
'SplFileObject::fflush' => ['bool'],
'SplFileObject::fgetc' => ['string|false'],
'SplFileObject::fgetcsv' => ['list<string>|array{0: null}|false|null', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplFileObject::fgets' => ['string|false'],
'SplFileObject::flock' => ['bool', 'operation'=>'int', '&w_wouldblock='=>'int'],
'SplFileObject::fpassthru' => ['int|false'],
'SplFileObject::fputcsv' => ['int|false', 'fields'=>'array<array-key, null|scalar|Stringable>', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplFileObject::fread' => ['string|false', 'length'=>'int'],
'SplFileObject::fscanf' => ['array|int', 'format'=>'string', '&...w_vars='=>'string|int|float'],
'SplFileObject::fseek' => ['int', 'pos'=>'int', 'whence='=>'int'],
'SplFileObject::fstat' => ['array|false'],
'SplFileObject::ftell' => ['int|false'],
'SplFileObject::ftruncate' => ['bool', 'size'=>'int'],
'SplFileObject::fwrite' => ['int', 'string'=>'string', 'length='=>'int'],
'SplFileObject::getATime' => ['int'],
'SplFileObject::getBasename' => ['string', 'suffix='=>'string'],
'SplFileObject::getChildren' => ['null'],
'SplFileObject::getCsvControl' => ['array'],
'SplFileObject::getCTime' => ['int'],
'SplFileObject::getCurrentLine' => ['string|false'],
'SplFileObject::getExtension' => ['string'],
'SplFileObject::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplFileObject::getFilename' => ['string'],
'SplFileObject::getFlags' => ['int'],
'SplFileObject::getGroup' => ['int'],
'SplFileObject::getInode' => ['int'],
'SplFileObject::getLinkTarget' => ['string'],
'SplFileObject::getMaxLineLen' => ['int'],
'SplFileObject::getMTime' => ['int'],
'SplFileObject::getOwner' => ['int'],
'SplFileObject::getPath' => ['string'],
'SplFileObject::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplFileObject::getPathname' => ['string'],
'SplFileObject::getPerms' => ['int'],
'SplFileObject::getRealPath' => ['false|string'],
'SplFileObject::getSize' => ['int'],
'SplFileObject::getType' => ['string'],
'SplFileObject::hasChildren' => ['false'],
'SplFileObject::isDir' => ['bool'],
'SplFileObject::isExecutable' => ['bool'],
'SplFileObject::isFile' => ['bool'],
'SplFileObject::isLink' => ['bool'],
'SplFileObject::isReadable' => ['bool'],
'SplFileObject::isWritable' => ['bool'],
'SplFileObject::key' => ['int'],
'SplFileObject::next' => ['void'],
'SplFileObject::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'SplFileObject::rewind' => ['void'],
'SplFileObject::seek' => ['void', 'line_pos'=>'int'],
'SplFileObject::setCsvControl' => ['void', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplFileObject::setFileClass' => ['void', 'class_name='=>'string'],
'SplFileObject::setFlags' => ['void', 'flags'=>'int'],
'SplFileObject::setInfoClass' => ['void', 'class_name='=>'string'],
'SplFileObject::setMaxLineLen' => ['void', 'max_len'=>'int'],
'SplFileObject::valid' => ['bool'],
'SplFixedArray::__construct' => ['void', 'size='=>'int'],
'SplFixedArray::__wakeup' => ['void'],
'SplFixedArray::count' => ['int'],
'SplFixedArray::current' => ['mixed'],
'SplFixedArray::fromArray' => ['SplFixedArray', 'data'=>'array', 'save_indexes='=>'bool'],
'SplFixedArray::getSize' => ['int'],
'SplFixedArray::key' => ['int'],
'SplFixedArray::next' => ['void'],
'SplFixedArray::offsetExists' => ['bool', 'index'=>'int'],
'SplFixedArray::offsetGet' => ['mixed', 'index'=>'int'],
'SplFixedArray::offsetSet' => ['void', 'index'=>'int', 'newval'=>'mixed'],
'SplFixedArray::offsetUnset' => ['void', 'index'=>'int'],
'SplFixedArray::rewind' => ['void'],
'SplFixedArray::setSize' => ['bool', 'size'=>'int'],
'SplFixedArray::toArray' => ['array'],
'SplFixedArray::valid' => ['bool'],
'SplHeap::__construct' => ['void'],
'SplHeap::compare' => ['int', 'value1'=>'mixed', 'value2'=>'mixed'],
'SplHeap::count' => ['int'],
'SplHeap::current' => ['mixed'],
'SplHeap::extract' => ['mixed'],
'SplHeap::insert' => ['bool', 'value'=>'mixed'],
'SplHeap::isCorrupted' => ['bool'],
'SplHeap::isEmpty' => ['bool'],
'SplHeap::key' => ['int'],
'SplHeap::next' => ['void'],
'SplHeap::recoverFromCorruption' => ['int'],
'SplHeap::rewind' => ['void'],
'SplHeap::top' => ['mixed'],
'SplHeap::valid' => ['bool'],
'SplMaxHeap::__construct' => ['void'],
'SplMaxHeap::compare' => ['int', 'a'=>'mixed', 'b'=>'mixed'],
'SplMinHeap::compare' => ['int', 'a'=>'mixed', 'b'=>'mixed'],
'SplMinHeap::count' => ['int'],
'SplMinHeap::current' => ['mixed'],
'SplMinHeap::extract' => ['mixed'],
'SplMinHeap::insert' => ['void', 'value'=>'mixed'],
'SplMinHeap::isCorrupted' => ['int'],
'SplMinHeap::isEmpty' => ['bool'],
'SplMinHeap::key' => ['mixed'],
'SplMinHeap::next' => ['void'],
'SplMinHeap::recoverFromCorruption' => ['void'],
'SplMinHeap::rewind' => ['void'],
'SplMinHeap::top' => ['mixed'],
'SplMinHeap::valid' => ['bool'],
'SplObjectStorage::__construct' => ['void'],
'SplObjectStorage::addAll' => ['void', 'os'=>'splobjectstorage'],
'SplObjectStorage::attach' => ['void', 'object'=>'object', 'inf='=>'mixed'],
'SplObjectStorage::contains' => ['bool', 'object'=>'object'],
'SplObjectStorage::count' => ['int'],
'SplObjectStorage::current' => ['object'],
'SplObjectStorage::detach' => ['void', 'object'=>'object'],
'SplObjectStorage::getHash' => ['string', 'object'=>'object'],
'SplObjectStorage::getInfo' => ['mixed'],
'SplObjectStorage::key' => ['int'],
'SplObjectStorage::next' => ['void'],
'SplObjectStorage::offsetExists' => ['bool', 'object'=>'object'],
'SplObjectStorage::offsetGet' => ['mixed', 'object'=>'object'],
'SplObjectStorage::offsetSet' => ['object', 'object'=>'object', 'data='=>'mixed'],
'SplObjectStorage::offsetUnset' => ['object', 'object'=>'object'],
'SplObjectStorage::removeAll' => ['void', 'os'=>'splobjectstorage'],
'SplObjectStorage::removeAllExcept' => ['void', 'os'=>'splobjectstorage'],
'SplObjectStorage::rewind' => ['void'],
'SplObjectStorage::serialize' => ['string'],
'SplObjectStorage::setInfo' => ['void', 'inf'=>'mixed'],
'SplObjectStorage::unserialize' => ['void', 'serialized'=>'string'],
'SplObjectStorage::valid' => ['bool'],
'SplObserver::update' => ['void', 'subject'=>'SplSubject'],
'SplPriorityQueue::__construct' => ['void'],
'SplPriorityQueue::compare' => ['int', 'a'=>'mixed', 'b'=>'mixed'],
'SplPriorityQueue::count' => ['int'],
'SplPriorityQueue::current' => ['mixed'],
'SplPriorityQueue::extract' => ['mixed'],
'SplPriorityQueue::getExtractFlags' => ['int'],
'SplPriorityQueue::insert' => ['bool', 'value'=>'mixed', 'priority'=>'mixed'],
'SplPriorityQueue::isCorrupted' => ['bool'],
'SplPriorityQueue::isEmpty' => ['bool'],
'SplPriorityQueue::key' => ['mixed'],
'SplPriorityQueue::next' => ['void'],
'SplPriorityQueue::recoverFromCorruption' => ['void'],
'SplPriorityQueue::rewind' => ['void'],
'SplPriorityQueue::setExtractFlags' => ['void', 'flags'=>'int'],
'SplPriorityQueue::top' => ['mixed'],
'SplPriorityQueue::valid' => ['bool'],
'SplQueue::dequeue' => ['mixed'],
'SplQueue::enqueue' => ['void', 'value'=>'mixed'],
'SplQueue::getIteratorMode' => ['int'],
'SplQueue::isEmpty' => ['bool'],
'SplQueue::key' => ['mixed'],
'SplQueue::next' => ['void'],
'SplQueue::offsetExists' => ['bool', 'index'=>'mixed'],
'SplQueue::offsetGet' => ['mixed', 'index'=>'mixed'],
'SplQueue::offsetSet' => ['void', 'index'=>'mixed', 'newval'=>'mixed'],
'SplQueue::offsetUnset' => ['void', 'index'=>'mixed'],
'SplQueue::pop' => ['mixed'],
'SplQueue::prev' => ['void'],
'SplQueue::push' => ['void', 'value'=>'mixed'],
'SplQueue::rewind' => ['void'],
'SplQueue::serialize' => ['string'],
'SplQueue::setIteratorMode' => ['void', 'mode'=>'int'],
'SplQueue::shift' => ['mixed'],
'SplQueue::top' => ['mixed'],
'SplQueue::unserialize' => ['void', 'serialized'=>'string'],
'SplQueue::unshift' => ['bool', 'value'=>'mixed'],
'SplQueue::valid' => ['bool'],
'SplStack::__construct' => ['void'],
'SplStack::add' => ['void', 'index'=>'mixed', 'newval'=>'mixed'],
'SplStack::bottom' => ['mixed'],
'SplStack::count' => ['int'],
'SplStack::current' => ['mixed'],
'SplStack::getIteratorMode' => ['int'],
'SplStack::isEmpty' => ['bool'],
'SplStack::key' => ['mixed'],
'SplStack::next' => ['void'],
'SplStack::offsetExists' => ['bool', 'index'=>'mixed'],
'SplStack::offsetGet' => ['mixed', 'index'=>'mixed'],
'SplStack::offsetSet' => ['void', 'index'=>'mixed', 'newval'=>'mixed'],
'SplStack::offsetUnset' => ['void', 'index'=>'mixed'],
'SplStack::pop' => ['mixed'],
'SplStack::prev' => ['void'],
'SplStack::push' => ['void', 'value'=>'mixed'],
'SplStack::rewind' => ['void'],
'SplStack::serialize' => ['string'],
'SplStack::setIteratorMode' => ['void', 'mode'=>'int'],
'SplStack::shift' => ['mixed'],
'SplStack::top' => ['mixed'],
'SplStack::unserialize' => ['void', 'serialized'=>'string'],
'SplStack::unshift' => ['bool', 'value'=>'mixed'],
'SplStack::valid' => ['bool'],
'SplSubject::attach' => ['void', 'observer'=>'SplObserver'],
'SplSubject::detach' => ['void', 'observer'=>'SplObserver'],
'SplSubject::notify' => ['void'],
'SplTempFileObject::__construct' => ['void', 'max_memory='=>'int'],
'SplTempFileObject::__toString' => ['string'],
'SplTempFileObject::_bad_state_ex' => [''],
'SplTempFileObject::current' => ['array|false|string'],
'SplTempFileObject::eof' => ['bool'],
'SplTempFileObject::fflush' => ['bool'],
'SplTempFileObject::fgetc' => ['false|string'],
'SplTempFileObject::fgetcsv' => ['list<string>|array{0: null}|false|null', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplTempFileObject::fgets' => ['string'],
'SplTempFileObject::fgetss' => ['string', 'allowable_tags='=>'string'],
'SplTempFileObject::flock' => ['bool', 'operation'=>'int', '&wouldblock='=>'int'],
'SplTempFileObject::fpassthru' => ['int|false'],
'SplTempFileObject::fputcsv' => ['false|int', 'fields'=>'array<array-key, null|scalar|Stringable>', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplTempFileObject::fread' => ['false|string', 'length'=>'int'],
'SplTempFileObject::fscanf' => ['bool', 'format'=>'string', '&...w_vars='=>'array<int,float>|array<int,int>|array<int,string>'],
'SplTempFileObject::fseek' => ['int', 'pos'=>'int', 'whence='=>'int'],
'SplTempFileObject::fstat' => ['array|false'],
'SplTempFileObject::ftell' => ['int'],
'SplTempFileObject::ftruncate' => ['bool', 'size'=>'int'],
'SplTempFileObject::fwrite' => ['int', 'string'=>'string', 'length='=>'int'],
'SplTempFileObject::getATime' => ['int'],
'SplTempFileObject::getBasename' => ['string', 'suffix='=>'string'],
'SplTempFileObject::getChildren' => ['null'],
'SplTempFileObject::getCsvControl' => ['array'],
'SplTempFileObject::getCTime' => ['int'],
'SplTempFileObject::getCurrentLine' => ['string'],
'SplTempFileObject::getExtension' => ['string'],
'SplTempFileObject::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplTempFileObject::getFilename' => ['string'],
'SplTempFileObject::getFlags' => ['int'],
'SplTempFileObject::getGroup' => ['int'],
'SplTempFileObject::getInode' => ['int'],
'SplTempFileObject::getLinkTarget' => ['string'],
'SplTempFileObject::getMaxLineLen' => ['int'],
'SplTempFileObject::getMTime' => ['int'],
'SplTempFileObject::getOwner' => ['int'],
'SplTempFileObject::getPath' => ['string'],
'SplTempFileObject::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplTempFileObject::getPathname' => ['string'],
'SplTempFileObject::getPerms' => ['int'],
'SplTempFileObject::getRealPath' => ['string'],
'SplTempFileObject::getSize' => ['int'],
'SplTempFileObject::getType' => ['string'],
'SplTempFileObject::hasChildren' => ['bool'],
'SplTempFileObject::isDir' => ['bool'],
'SplTempFileObject::isExecutable' => ['bool'],
'SplTempFileObject::isFile' => ['bool'],
'SplTempFileObject::isLink' => ['bool'],
'SplTempFileObject::isReadable' => ['bool'],
'SplTempFileObject::isWritable' => ['bool'],
'SplTempFileObject::key' => ['int'],
'SplTempFileObject::next' => ['void'],
'SplTempFileObject::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'SplTempFileObject::rewind' => ['void'],
'SplTempFileObject::seek' => ['void', 'line_pos'=>'int'],
'SplTempFileObject::setCsvControl' => ['void', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplTempFileObject::setFileClass' => ['void', 'class_name='=>'string'],
'SplTempFileObject::setFlags' => ['void', 'flags'=>'int'],
'SplTempFileObject::setInfoClass' => ['void', 'class_name='=>'string'],
'SplTempFileObject::setMaxLineLen' => ['void', 'max_len'=>'int'],
'SplTempFileObject::valid' => ['bool'],
'SplType::__construct' => ['void', 'initial_value='=>'mixed', 'strict='=>'bool'],
'Spoofchecker::__construct' => ['void'],
'Spoofchecker::areConfusable' => ['bool', 's1'=>'string', 's2'=>'string', '&w_error='=>'string'],
'Spoofchecker::isSuspicious' => ['bool', 'text'=>'string', '&w_error='=>'string'],
'Spoofchecker::setAllowedLocales' => ['void', 'locale_list'=>'string'],
'Spoofchecker::setChecks' => ['void', 'checks'=>'long'],
'Spoofchecker::setRestrictionLevel' => ['void', 'restriction_level'=>'int'],
'sprintf' => ['string', 'format'=>'string', '...values='=>'string|int|float'],
'SQLite3::__construct' => ['void', 'filename'=>'string', 'flags='=>'int', 'encryptionKey='=>'?string'],
'SQLite3::busyTimeout' => ['bool', 'milliseconds'=>'int'],
'SQLite3::changes' => ['int'],
'SQLite3::close' => ['bool'],
'SQLite3::createAggregate' => ['bool', 'name'=>'string', 'stepCallback'=>'callable', 'finalCallback'=>'callable', 'argCount='=>'int'],
'SQLite3::createCollation' => ['bool', 'name'=>'string', 'callback'=>'callable'],
'SQLite3::createFunction' => ['bool', 'name'=>'string', 'callback'=>'callable', 'argCount='=>'int', 'flags='=>'int'],
'SQLite3::enableExceptions' => ['bool', 'enable='=>'bool'],
'SQLite3::escapeString' => ['string', 'string'=>'string'],
'SQLite3::exec' => ['bool', 'query'=>'string'],
'SQLite3::lastErrorCode' => ['int'],
'SQLite3::lastErrorMsg' => ['string'],
'SQLite3::lastInsertRowID' => ['int'],
'SQLite3::loadExtension' => ['bool', 'name'=>'string'],
'SQLite3::open' => ['void', 'filename'=>'string', 'flags='=>'int', 'encryptionKey='=>'?string'],
'SQLite3::openBlob' => ['resource|false', 'table'=>'string', 'column'=>'string', 'rowid'=>'int', 'database='=>'string', 'flags='=>'int'],
'SQLite3::prepare' => ['SQLite3Stmt|false', 'query'=>'string'],
'SQLite3::query' => ['SQLite3Result|false', 'query'=>'string'],
'SQLite3::querySingle' => ['array|int|string|bool|float|null|false', 'query'=>'string', 'entireRow='=>'bool'],
'SQLite3::version' => ['array'],
'SQLite3Result::__construct' => ['void'],
'SQLite3Result::columnName' => ['string', 'column'=>'int'],
'SQLite3Result::columnType' => ['int', 'column'=>'int'],
'SQLite3Result::fetchArray' => ['array|false', 'mode='=>'int'],
'SQLite3Result::finalize' => ['bool'],
'SQLite3Result::numColumns' => ['int'],
'SQLite3Result::reset' => ['bool'],
'SQLite3Stmt::__construct' => ['void', 'sqlite3'=>'sqlite3', 'query'=>'string'],
'SQLite3Stmt::bindParam' => ['bool', 'param'=>'string|int', '&rw_var'=>'mixed', 'type='=>'int'],
'SQLite3Stmt::bindValue' => ['bool', 'param'=>'string|int', 'value'=>'mixed', 'type='=>'int'],
'SQLite3Stmt::clear' => ['bool'],
'SQLite3Stmt::close' => ['bool'],
'SQLite3Stmt::execute' => ['false|SQLite3Result'],
'SQLite3Stmt::getSQL' => ['string', 'expand='=>'bool'],
'SQLite3Stmt::paramCount' => ['int'],
'SQLite3Stmt::readOnly' => ['bool'],
'SQLite3Stmt::reset' => ['bool'],
'sqlite_array_query' => ['array|false', 'dbhandle'=>'resource', 'query'=>'string', 'result_type='=>'int', 'decode_binary='=>'bool'],
'sqlite_busy_timeout' => ['void', 'dbhandle'=>'resource', 'milliseconds'=>'int'],
'sqlite_changes' => ['int', 'dbhandle'=>'resource'],
'sqlite_close' => ['void', 'dbhandle'=>'resource'],
'sqlite_column' => ['mixed', 'result'=>'resource', 'index_or_name'=>'mixed', 'decode_binary='=>'bool'],
'sqlite_create_aggregate' => ['void', 'dbhandle'=>'resource', 'function_name'=>'string', 'step_func'=>'callable', 'finalize_func'=>'callable', 'num_args='=>'int'],
'sqlite_create_function' => ['void', 'dbhandle'=>'resource', 'function_name'=>'string', 'callback'=>'callable', 'num_args='=>'int'],
'sqlite_current' => ['array|false', 'result'=>'resource', 'result_type='=>'int', 'decode_binary='=>'bool'],
'sqlite_error_string' => ['string', 'error_code'=>'int'],
'sqlite_escape_string' => ['string', 'item'=>'string'],
'sqlite_exec' => ['bool', 'dbhandle'=>'resource', 'query'=>'string', 'error_msg='=>'string'],
'sqlite_factory' => ['SQLiteDatabase', 'filename'=>'string', 'mode='=>'int', 'error_message='=>'string'],
'sqlite_fetch_all' => ['array', 'result'=>'resource', 'result_type='=>'int', 'decode_binary='=>'bool'],
'sqlite_fetch_array' => ['array|false', 'result'=>'resource', 'result_type='=>'int', 'decode_binary='=>'bool'],
'sqlite_fetch_column_types' => ['array|false', 'table_name'=>'string', 'dbhandle'=>'resource', 'result_type='=>'int'],
'sqlite_fetch_object' => ['object', 'result'=>'resource', 'class_name='=>'string', 'ctor_params='=>'array', 'decode_binary='=>'bool'],
'sqlite_fetch_single' => ['string', 'result'=>'resource', 'decode_binary='=>'bool'],
'sqlite_fetch_string' => ['string', 'result'=>'resource', 'decode_binary'=>'bool'],
'sqlite_field_name' => ['string', 'result'=>'resource', 'field_index'=>'int'],
'sqlite_has_more' => ['bool', 'result'=>'resource'],
'sqlite_has_prev' => ['bool', 'result'=>'resource'],
'sqlite_key' => ['int', 'result'=>'resource'],
'sqlite_last_error' => ['int', 'dbhandle'=>'resource'],
'sqlite_last_insert_rowid' => ['int', 'dbhandle'=>'resource'],
'sqlite_libencoding' => ['string'],
'sqlite_libversion' => ['string'],
'sqlite_next' => ['bool', 'result'=>'resource'],
'sqlite_num_fields' => ['int', 'result'=>'resource'],
'sqlite_num_rows' => ['int', 'result'=>'resource'],
'sqlite_open' => ['resource|false', 'filename'=>'string', 'mode='=>'int', 'error_message='=>'string'],
'sqlite_popen' => ['resource|false', 'filename'=>'string', 'mode='=>'int', 'error_message='=>'string'],
'sqlite_prev' => ['bool', 'result'=>'resource'],
'sqlite_query' => ['resource|false', 'dbhandle'=>'resource', 'query'=>'resource|string', 'result_type='=>'int', 'error_msg='=>'string'],
'sqlite_rewind' => ['bool', 'result'=>'resource'],
'sqlite_seek' => ['bool', 'result'=>'resource', 'rownum'=>'int'],
'sqlite_single_query' => ['array', 'db'=>'resource', 'query'=>'string', 'first_row_only='=>'bool', 'decode_binary='=>'bool'],
'sqlite_udf_decode_binary' => ['string', 'data'=>'string'],
'sqlite_udf_encode_binary' => ['string', 'data'=>'string'],
'sqlite_unbuffered_query' => ['SQLiteUnbuffered|false', 'dbhandle'=>'resource', 'query'=>'string', 'result_type='=>'int', 'error_msg='=>'string'],
'sqlite_valid' => ['bool', 'result'=>'resource'],
'SQLiteDatabase::__construct' => ['void', 'filename'=>'', 'mode='=>'int|mixed', '&error_message'=>''],
'SQLiteDatabase::arrayQuery' => ['array', 'query'=>'string', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteDatabase::busyTimeout' => ['int', 'milliseconds'=>'int'],
'SQLiteDatabase::changes' => ['int'],
'SQLiteDatabase::createAggregate' => ['', 'function_name'=>'string', 'step_func'=>'callable', 'finalize_func'=>'callable', 'num_args='=>'int'],
'SQLiteDatabase::createFunction' => ['', 'function_name'=>'string', 'callback'=>'callable', 'num_args='=>'int'],
'SQLiteDatabase::exec' => ['bool', 'query'=>'string', 'error_msg='=>'string'],
'SQLiteDatabase::fetchColumnTypes' => ['array', 'table_name'=>'string', 'result_type='=>'int'],
'SQLiteDatabase::lastError' => ['int'],
'SQLiteDatabase::lastInsertRowid' => ['int'],
'SQLiteDatabase::query' => ['SQLiteResult|false', 'query'=>'string', 'result_type='=>'int', 'error_msg='=>'string'],
'SQLiteDatabase::queryExec' => ['bool', 'query'=>'string', '&w_error_msg='=>'string'],
'SQLiteDatabase::singleQuery' => ['array', 'query'=>'string', 'first_row_only='=>'bool', 'decode_binary='=>'bool'],
'SQLiteDatabase::unbufferedQuery' => ['SQLiteUnbuffered|false', 'query'=>'string', 'result_type='=>'int', 'error_msg='=>'string'],
'SQLiteException::__clone' => ['void'],
'SQLiteException::__construct' => ['void', 'message'=>'', 'code'=>'', 'previous'=>''],
'SQLiteException::__toString' => ['string'],
'SQLiteException::__wakeup' => ['void'],
'SQLiteException::getCode' => ['int'],
'SQLiteException::getFile' => ['string'],
'SQLiteException::getLine' => ['int'],
'SQLiteException::getMessage' => ['string'],
'SQLiteException::getPrevious' => ['RuntimeException|Throwable|null'],
'SQLiteException::getTrace' => ['list<array<string,mixed>>'],
'SQLiteException::getTraceAsString' => ['string'],
'SQLiteResult::__construct' => ['void'],
'SQLiteResult::column' => ['mixed', 'index_or_name'=>'', 'decode_binary='=>'bool'],
'SQLiteResult::count' => ['int'],
'SQLiteResult::current' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteResult::fetch' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteResult::fetchAll' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteResult::fetchObject' => ['object', 'class_name='=>'string', 'ctor_params='=>'array', 'decode_binary='=>'bool'],
'SQLiteResult::fetchSingle' => ['string', 'decode_binary='=>'bool'],
'SQLiteResult::fieldName' => ['string', 'field_index'=>'int'],
'SQLiteResult::hasPrev' => ['bool'],
'SQLiteResult::key' => ['mixed|null'],
'SQLiteResult::next' => ['bool'],
'SQLiteResult::numFields' => ['int'],
'SQLiteResult::numRows' => ['int'],
'SQLiteResult::prev' => ['bool'],
'SQLiteResult::rewind' => ['bool'],
'SQLiteResult::seek' => ['bool', 'rownum'=>'int'],
'SQLiteResult::valid' => ['bool'],
'SQLiteUnbuffered::column' => ['void', 'index_or_name'=>'', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::current' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::fetch' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::fetchAll' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::fetchObject' => ['object', 'class_name='=>'string', 'ctor_params='=>'array', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::fetchSingle' => ['string', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::fieldName' => ['string', 'field_index'=>'int'],
'SQLiteUnbuffered::next' => ['bool'],
'SQLiteUnbuffered::numFields' => ['int'],
'SQLiteUnbuffered::valid' => ['bool'],
'sqlsrv_begin_transaction' => ['bool', 'conn'=>'resource'],
'sqlsrv_cancel' => ['bool', 'stmt'=>'resource'],
'sqlsrv_client_info' => ['array|false', 'conn'=>'resource'],
'sqlsrv_close' => ['bool', 'conn'=>'?resource'],
'sqlsrv_commit' => ['bool', 'conn'=>'resource'],
'sqlsrv_configure' => ['bool', 'setting'=>'string', 'value'=>'mixed'],
'sqlsrv_connect' => ['resource|false', 'serverName'=>'string', 'connectionInfo='=>'array'],
'sqlsrv_errors' => ['?array', 'errorsOrWarnings='=>'int'],
'sqlsrv_execute' => ['bool', 'stmt'=>'resource'],
'sqlsrv_fetch' => ['?bool', 'stmt'=>'resource', 'row='=>'int', 'offset='=>'int'],
'sqlsrv_fetch_array' => ['array|null|false', 'stmt'=>'resource', 'fetchType='=>'int', 'row='=>'int', 'offset='=>'int'],
'sqlsrv_fetch_object' => ['object|null|false', 'stmt'=>'resource', 'className='=>'string', 'ctorParams='=>'array', 'row='=>'int', 'offset='=>'int'],
'sqlsrv_field_metadata' => ['array|false', 'stmt'=>'resource'],
'sqlsrv_free_stmt' => ['bool', 'stmt'=>'resource'],
'sqlsrv_get_config' => ['mixed', 'setting'=>'string'],
'sqlsrv_get_field' => ['mixed', 'stmt'=>'resource', 'fieldIndex'=>'int', 'getAsType='=>'int'],
'sqlsrv_has_rows' => ['bool', 'stmt'=>'resource'],
'sqlsrv_next_result' => ['?bool', 'stmt'=>'resource'],
'sqlsrv_num_fields' => ['int|false', 'stmt'=>'resource'],
'sqlsrv_num_rows' => ['int|false', 'stmt'=>'resource'],
'sqlsrv_prepare' => ['resource|false', 'conn'=>'resource', 'sql'=>'string', 'params='=>'array', 'options='=>'array'],
'sqlsrv_query' => ['resource|false', 'conn'=>'resource', 'sql'=>'string', 'params='=>'array', 'options='=>'array'],
'sqlsrv_rollback' => ['bool', 'conn'=>'resource'],
'sqlsrv_rows_affected' => ['int|false', 'stmt'=>'resource'],
'sqlsrv_send_stream_data' => ['bool', 'stmt'=>'resource'],
'sqlsrv_server_info' => ['array', 'conn'=>'resource'],
'sqrt' => ['float', 'num'=>'float'],
'srand' => ['void', 'seed='=>'int', 'mode='=>'int'],
'sscanf' => ['list<float|int|string|null>|int|null', 'string'=>'string', 'format'=>'string', '&...w_vars='=>'string|int|float|null'],
'ssdeep_fuzzy_compare' => ['int', 'signature1'=>'string', 'signature2'=>'string'],
'ssdeep_fuzzy_hash' => ['string', 'to_hash'=>'string'],
'ssdeep_fuzzy_hash_filename' => ['string', 'file_name'=>'string'],
'ssh2_auth_agent' => ['bool', 'session'=>'resource', 'username'=>'string'],
'ssh2_auth_hostbased_file' => ['bool', 'session'=>'resource', 'username'=>'string', 'hostname'=>'string', 'pubkeyfile'=>'string', 'privkeyfile'=>'string', 'passphrase='=>'string', 'local_username='=>'string'],
'ssh2_auth_none' => ['bool|string[]', 'session'=>'resource', 'username'=>'string'],
'ssh2_auth_password' => ['bool', 'session'=>'resource', 'username'=>'string', 'password'=>'string'],
'ssh2_auth_pubkey_file' => ['bool', 'session'=>'resource', 'username'=>'string', 'pubkeyfile'=>'string', 'privkeyfile'=>'string', 'passphrase='=>'string'],
'ssh2_connect' => ['resource|false', 'host'=>'string', 'port='=>'int', 'methods='=>'array', 'callbacks='=>'array'],
'ssh2_disconnect' => ['bool', 'session'=>'resource'],
'ssh2_exec' => ['resource|false', 'session'=>'resource', 'command'=>'string', 'pty='=>'string', 'env='=>'array', 'width='=>'int', 'height='=>'int', 'width_height_type='=>'int'],
'ssh2_fetch_stream' => ['resource|false', 'channel'=>'resource', 'streamid'=>'int'],
'ssh2_fingerprint' => ['string|false', 'session'=>'resource', 'flags='=>'int'],
'ssh2_forward_accept' => ['resource|false', 'session'=>'resource'],
'ssh2_forward_listen' => ['resource|false', 'session'=>'resource', 'port'=>'int', 'host='=>'string', 'max_connections='=>'string'],
'ssh2_methods_negotiated' => ['array|false', 'session'=>'resource'],
'ssh2_poll' => ['int', '&polldes'=>'array', 'timeout='=>'int'],
'ssh2_publickey_add' => ['bool', 'pkey'=>'resource', 'algoname'=>'string', 'blob'=>'string', 'overwrite='=>'bool', 'attributes='=>'array'],
'ssh2_publickey_init' => ['resource|false', 'session'=>'resource'],
'ssh2_publickey_list' => ['array|false', 'pkey'=>'resource'],
'ssh2_publickey_remove' => ['bool', 'pkey'=>'resource', 'algoname'=>'string', 'blob'=>'string'],
'ssh2_scp_recv' => ['bool', 'session'=>'resource', 'remote_file'=>'string', 'local_file'=>'string'],
'ssh2_scp_send' => ['bool', 'session'=>'resource', 'local_file'=>'string', 'remote_file'=>'string', 'create_mode='=>'int'],
'ssh2_sftp' => ['resource|false', 'session'=>'resource'],
'ssh2_sftp_chmod' => ['bool', 'sftp'=>'resource', 'filename'=>'string', 'mode'=>'int'],
'ssh2_sftp_lstat' => ['array|false', 'sftp'=>'resource', 'path'=>'string'],
'ssh2_sftp_mkdir' => ['bool', 'sftp'=>'resource', 'dirname'=>'string', 'mode='=>'int', 'recursive='=>'bool'],
'ssh2_sftp_readlink' => ['string|false', 'sftp'=>'resource', 'link'=>'string'],
'ssh2_sftp_realpath' => ['string|false', 'sftp'=>'resource', 'filename'=>'string'],
'ssh2_sftp_rename' => ['bool', 'sftp'=>'resource', 'from'=>'string', 'to'=>'string'],
'ssh2_sftp_rmdir' => ['bool', 'sftp'=>'resource', 'dirname'=>'string'],
'ssh2_sftp_stat' => ['array|false', 'sftp'=>'resource', 'path'=>'string'],
'ssh2_sftp_symlink' => ['bool', 'sftp'=>'resource', 'target'=>'string', 'link'=>'string'],
'ssh2_sftp_unlink' => ['bool', 'sftp'=>'resource', 'filename'=>'string'],
'ssh2_shell' => ['resource|false', 'session'=>'resource', 'term_type='=>'string', 'env='=>'array', 'width='=>'int', 'height='=>'int', 'width_height_type='=>'int'],
'ssh2_tunnel' => ['resource|false', 'session'=>'resource', 'host'=>'string', 'port'=>'int'],
'stat' => ['array|false', 'filename'=>'string'],
'stats_absolute_deviation' => ['float', 'a'=>'array'],
'stats_cdf_beta' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_binomial' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_cauchy' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_chisquare' => ['float', 'par1'=>'float', 'par2'=>'float', 'which'=>'int'],
'stats_cdf_exponential' => ['float', 'par1'=>'float', 'par2'=>'float', 'which'=>'int'],
'stats_cdf_f' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_gamma' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_laplace' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_logistic' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_negative_binomial' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_noncentral_chisquare' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_noncentral_f' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'par4'=>'float', 'which'=>'int'],
'stats_cdf_noncentral_t' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_normal' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_poisson' => ['float', 'par1'=>'float', 'par2'=>'float', 'which'=>'int'],
'stats_cdf_t' => ['float', 'par1'=>'float', 'par2'=>'float', 'which'=>'int'],
'stats_cdf_uniform' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_weibull' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_covariance' => ['float', 'a'=>'array', 'b'=>'array'],
'stats_den_uniform' => ['float', 'x'=>'float', 'a'=>'float', 'b'=>'float'],
'stats_dens_beta' => ['float', 'x'=>'float', 'a'=>'float', 'b'=>'float'],
'stats_dens_cauchy' => ['float', 'x'=>'float', 'ave'=>'float', 'stdev'=>'float'],
'stats_dens_chisquare' => ['float', 'x'=>'float', 'dfr'=>'float'],
'stats_dens_exponential' => ['float', 'x'=>'float', 'scale'=>'float'],
'stats_dens_f' => ['float', 'x'=>'float', 'dfr1'=>'float', 'dfr2'=>'float'],
'stats_dens_gamma' => ['float', 'x'=>'float', 'shape'=>'float', 'scale'=>'float'],
'stats_dens_laplace' => ['float', 'x'=>'float', 'ave'=>'float', 'stdev'=>'float'],
'stats_dens_logistic' => ['float', 'x'=>'float', 'ave'=>'float', 'stdev'=>'float'],
'stats_dens_negative_binomial' => ['float', 'x'=>'float', 'n'=>'float', 'pi'=>'float'],
'stats_dens_normal' => ['float', 'x'=>'float', 'ave'=>'float', 'stdev'=>'float'],
'stats_dens_pmf_binomial' => ['float', 'x'=>'float', 'n'=>'float', 'pi'=>'float'],
'stats_dens_pmf_hypergeometric' => ['float', 'n1'=>'float', 'n2'=>'float', 'N1'=>'float', 'N2'=>'float'],
'stats_dens_pmf_negative_binomial' => ['float', 'x'=>'float', 'n'=>'float', 'pi'=>'float'],
'stats_dens_pmf_poisson' => ['float', 'x'=>'float', 'lb'=>'float'],
'stats_dens_t' => ['float', 'x'=>'float', 'dfr'=>'float'],
'stats_dens_uniform' => ['float', 'x'=>'float', 'a'=>'float', 'b'=>'float'],
'stats_dens_weibull' => ['float', 'x'=>'float', 'a'=>'float', 'b'=>'float'],
'stats_harmonic_mean' => ['float', 'a'=>'array'],
'stats_kurtosis' => ['float', 'a'=>'array'],
'stats_rand_gen_beta' => ['float', 'a'=>'float', 'b'=>'float'],
'stats_rand_gen_chisquare' => ['float', 'df'=>'float'],
'stats_rand_gen_exponential' => ['float', 'av'=>'float'],
'stats_rand_gen_f' => ['float', 'dfn'=>'float', 'dfd'=>'float'],
'stats_rand_gen_funiform' => ['float', 'low'=>'float', 'high'=>'float'],
'stats_rand_gen_gamma' => ['float', 'a'=>'float', 'r'=>'float'],
'stats_rand_gen_ibinomial' => ['int', 'n'=>'int', 'pp'=>'float'],
'stats_rand_gen_ibinomial_negative' => ['int', 'n'=>'int', 'p'=>'float'],
'stats_rand_gen_int' => ['int'],
'stats_rand_gen_ipoisson' => ['int', 'mu'=>'float'],
'stats_rand_gen_iuniform' => ['int', 'low'=>'int', 'high'=>'int'],
'stats_rand_gen_noncenral_chisquare' => ['float', 'df'=>'float', 'xnonc'=>'float'],
'stats_rand_gen_noncentral_chisquare' => ['float', 'df'=>'float', 'xnonc'=>'float'],
'stats_rand_gen_noncentral_f' => ['float', 'dfn'=>'float', 'dfd'=>'float', 'xnonc'=>'float'],
'stats_rand_gen_noncentral_t' => ['float', 'df'=>'float', 'xnonc'=>'float'],
'stats_rand_gen_normal' => ['float', 'av'=>'float', 'sd'=>'float'],
'stats_rand_gen_t' => ['float', 'df'=>'float'],
'stats_rand_get_seeds' => ['array'],
'stats_rand_phrase_to_seeds' => ['array', 'phrase'=>'string'],
'stats_rand_ranf' => ['float'],
'stats_rand_setall' => ['void', 'iseed1'=>'int', 'iseed2'=>'int'],
'stats_skew' => ['float', 'a'=>'array'],
'stats_standard_deviation' => ['float', 'a'=>'array', 'sample='=>'bool'],
'stats_stat_binomial_coef' => ['float', 'x'=>'int', 'n'=>'int'],
'stats_stat_correlation' => ['float', 'array1'=>'array', 'array2'=>'array'],
'stats_stat_factorial' => ['float', 'n'=>'int'],
'stats_stat_gennch' => ['float', 'n'=>'int'],
'stats_stat_independent_t' => ['float', 'array1'=>'array', 'array2'=>'array'],
'stats_stat_innerproduct' => ['float', 'array1'=>'array', 'array2'=>'array'],
'stats_stat_noncentral_t' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_stat_paired_t' => ['float', 'array1'=>'array', 'array2'=>'array'],
'stats_stat_percentile' => ['float', 'arr'=>'array', 'perc'=>'float'],
'stats_stat_powersum' => ['float', 'arr'=>'array', 'power'=>'float'],
'stats_variance' => ['float', 'a'=>'array', 'sample='=>'bool'],
'Stomp::__construct' => ['void', 'broker='=>'string', 'username='=>'string', 'password='=>'string', 'headers='=>'array'],
'Stomp::__destruct' => ['bool', 'link'=>''],
'Stomp::abort' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'Stomp::ack' => ['bool', 'msg'=>'', 'headers='=>'array', 'link='=>''],
'Stomp::begin' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'Stomp::commit' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'Stomp::error' => ['string', 'link'=>''],
'Stomp::getReadTimeout' => ['array', 'link'=>''],
'Stomp::getSessionId' => ['string', 'link'=>''],
'Stomp::hasFrame' => ['bool', 'link'=>''],
'Stomp::readFrame' => ['array', 'class_name='=>'string', 'link='=>''],
'Stomp::send' => ['bool', 'destination'=>'string', 'msg'=>'', 'headers='=>'array', 'link='=>''],
'Stomp::setReadTimeout' => ['', 'seconds'=>'int', 'microseconds='=>'int', 'link='=>''],
'Stomp::subscribe' => ['bool', 'destination'=>'string', 'headers='=>'array', 'link='=>''],
'Stomp::unsubscribe' => ['bool', 'destination'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_abort' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_ack' => ['bool', 'msg'=>'', 'headers='=>'array', 'link='=>''],
'stomp_begin' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_close' => ['bool', 'link'=>''],
'stomp_commit' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_connect' => ['resource', 'broker='=>'string', 'username='=>'string', 'password='=>'string', 'headers='=>'array'],
'stomp_connect_error' => ['string'],
'stomp_error' => ['string', 'link'=>''],
'stomp_get_read_timeout' => ['array', 'link'=>''],
'stomp_get_session_id' => ['string', 'link'=>''],
'stomp_has_frame' => ['bool', 'link'=>''],
'stomp_read_frame' => ['array', 'class_name='=>'string', 'link='=>''],
'stomp_send' => ['bool', 'destination'=>'string', 'msg'=>'', 'headers='=>'array', 'link='=>''],
'stomp_set_read_timeout' => ['', 'seconds'=>'int', 'microseconds='=>'int', 'link='=>''],
'stomp_subscribe' => ['bool', 'destination'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_unsubscribe' => ['bool', 'destination'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_version' => ['string'],
'StompException::getDetails' => ['string'],
'StompFrame::__construct' => ['void', 'command='=>'string', 'headers='=>'array', 'body='=>'string'],
'str_contains' => ['bool', 'haystack'=>'string', 'needle'=>'string'],
'str_ends_with' => ['bool', 'haystack'=>'string', 'needle'=>'string'],
'str_getcsv' => ['non-empty-list<?string>', 'string'=>'string', 'separator='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'str_ireplace' => ['string|string[]', 'search'=>'string|array', 'replace'=>'string|array', 'subject'=>'string|array', '&w_count='=>'int'],
'str_pad' => ['string', 'string'=>'string', 'length'=>'int', 'pad_string='=>'string', 'pad_type='=>'int'],
'str_repeat' => ['string', 'string'=>'string', 'times'=>'int'],
'str_replace' => ['string|string[]', 'search'=>'string|array', 'replace'=>'string|array', 'subject'=>'string|array', '&w_count='=>'int'],
'str_rot13' => ['string', 'string'=>'string'],
'str_shuffle' => ['string', 'string'=>'string'],
'str_split' => ['non-empty-list<string>', 'string'=>'string', 'length='=>'positive-int'],
'str_starts_with' => ['bool', 'haystack'=>'string', 'needle'=>'string'],
'str_word_count' => ['array<int, string>|int', 'string'=>'string', 'format='=>'int', 'characters='=>'string'],
'strcasecmp' => ['int', 'string1'=>'string', 'string2'=>'string'],
'strchr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool'],
'strcmp' => ['int', 'string1'=>'string', 'string2'=>'string'],
'strcoll' => ['int', 'string1'=>'string', 'string2'=>'string'],
'strcspn' => ['int', 'string'=>'string', 'characters'=>'string', 'offset='=>'int', 'length='=>'int'],
'stream_bucket_append' => ['void', 'brigade'=>'resource', 'bucket'=>'object'],
'stream_bucket_make_writeable' => ['object', 'brigade'=>'resource'],
'stream_bucket_new' => ['object|false', 'stream'=>'resource', 'buffer'=>'string'],
'stream_bucket_prepend' => ['void', 'brigade'=>'resource', 'bucket'=>'object'],
'stream_context_create' => ['resource', 'options='=>'array', 'params='=>'array'],
'stream_context_get_default' => ['resource', 'options='=>'array'],
'stream_context_get_options' => ['array', 'stream_or_context'=>'resource'],
'stream_context_get_params' => ['array', 'context'=>'resource'],
'stream_context_set_default' => ['resource', 'options'=>'array'],
'stream_context_set_option' => ['bool', 'context'=>'', 'wrapper_or_options'=>'string', 'option_name'=>'string', 'value'=>''],
'stream_context_set_option\'1' => ['bool', 'context'=>'', 'wrapper_or_options'=>'array'],
'stream_context_set_params' => ['bool', 'context'=>'resource', 'params'=>'array'],
'stream_copy_to_stream' => ['int|false', 'from'=>'resource', 'to'=>'resource', 'length='=>'int', 'offset='=>'int'],
'stream_encoding' => ['bool', 'stream'=>'resource', 'encoding='=>'string'],
'stream_filter_append' => ['resource|false', 'stream'=>'resource', 'filter_name'=>'string', 'mode='=>'int', 'params='=>'mixed'],
'stream_filter_prepend' => ['resource|false', 'stream'=>'resource', 'filter_name'=>'string', 'mode='=>'int', 'params='=>'mixed'],
'stream_filter_register' => ['bool', 'filter_name'=>'string', 'class'=>'string'],
'stream_filter_remove' => ['bool', 'stream_filter'=>'resource'],
'stream_get_contents' => ['string|false', 'stream'=>'resource', 'length='=>'int', 'offset='=>'int'],
'stream_get_filters' => ['array'],
'stream_get_line' => ['string|false', 'stream'=>'resource', 'length'=>'int', 'ending='=>'string'],
'stream_get_meta_data' => ['array{timed_out:bool,blocked:bool,eof:bool,unread_bytes:int,stream_type:string,wrapper_type:string,wrapper_data:mixed,mode:string,seekable:bool,uri:string,mediatype:string}', 'stream'=>'resource'],
'stream_get_transports' => ['list<string>'],
'stream_get_wrappers' => ['list<string>'],
'stream_is_local' => ['bool', 'stream'=>'resource|string'],
'stream_isatty' => ['bool', 'stream'=>'resource'],
'stream_notification_callback' => ['callback', 'notification_code'=>'int', 'severity'=>'int', 'message'=>'string', 'message_code'=>'int', 'bytes_transferred'=>'int', 'bytes_max'=>'int'],
'stream_register_wrapper' => ['bool', 'protocol'=>'string', 'class'=>'string', 'flags='=>'int'],
'stream_resolve_include_path' => ['string|false', 'filename'=>'string'],
'stream_select' => ['int|false', '&rw_read'=>'resource[]', '&rw_write'=>'?resource[]', '&rw_except'=>'?resource[]', 'seconds'=>'?int', 'microseconds='=>'?int'],
'stream_set_blocking' => ['bool', 'stream'=>'resource', 'enable'=>'bool'],
'stream_set_chunk_size' => ['int|false', 'stream'=>'resource', 'size'=>'int'],
'stream_set_read_buffer' => ['int', 'stream'=>'resource', 'size'=>'int'],
'stream_set_timeout' => ['bool', 'stream'=>'resource', 'seconds'=>'int', 'microseconds='=>'int'],
'stream_set_write_buffer' => ['int', 'stream'=>'resource', 'size'=>'int'],
'stream_socket_accept' => ['resource|false', 'socket'=>'resource', 'timeout='=>'float', '&w_peer_name='=>'string'],
'stream_socket_client' => ['resource|false', 'address'=>'string', '&w_error_code='=>'int', '&w_error_message='=>'string', 'timeout='=>'float', 'flags='=>'int', 'context='=>'resource'],
'stream_socket_enable_crypto' => ['int|bool', 'stream'=>'resource', 'enable'=>'bool', 'crypto_method='=>'int', 'session_stream='=>'resource'],
'stream_socket_get_name' => ['string', 'socket'=>'resource', 'remote'=>'bool'],
'stream_socket_pair' => ['resource[]|false', 'domain'=>'int', 'type'=>'int', 'protocol'=>'int'],
'stream_socket_recvfrom' => ['string', 'socket'=>'resource', 'length'=>'int', 'flags='=>'int', '&w_address='=>'string'],
'stream_socket_sendto' => ['int', 'socket'=>'resource', 'data'=>'string', 'flags='=>'int', 'address='=>'string'],
'stream_socket_server' => ['resource|false', 'address'=>'string', '&w_error_code='=>'int', '&w_error_message='=>'string', 'flags='=>'int', 'context='=>'resource'],
'stream_socket_shutdown' => ['bool', 'stream'=>'resource', 'mode'=>'int'],
'stream_supports_lock' => ['bool', 'stream'=>'resource'],
'stream_wrapper_register' => ['bool', 'protocol'=>'string', 'class'=>'string', 'flags='=>'int'],
'stream_wrapper_restore' => ['bool', 'protocol'=>'string'],
'stream_wrapper_unregister' => ['bool', 'protocol'=>'string'],
'streamWrapper::__construct' => ['void'],
'streamWrapper::__destruct' => ['void'],
'streamWrapper::dir_closedir' => ['bool'],
'streamWrapper::dir_opendir' => ['bool', 'path'=>'string', 'options'=>'int'],
'streamWrapper::dir_readdir' => ['string'],
'streamWrapper::dir_rewinddir' => ['bool'],
'streamWrapper::mkdir' => ['bool', 'path'=>'string', 'mode'=>'int', 'options'=>'int'],
'streamWrapper::rename' => ['bool', 'path_from'=>'string', 'path_to'=>'string'],
'streamWrapper::rmdir' => ['bool', 'path'=>'string', 'options'=>'int'],
'streamWrapper::stream_cast' => ['resource', 'cast_as'=>'int'],
'streamWrapper::stream_close' => ['void'],
'streamWrapper::stream_eof' => ['bool'],
'streamWrapper::stream_flush' => ['bool'],
'streamWrapper::stream_lock' => ['bool', 'operation'=>'mode'],
'streamWrapper::stream_metadata' => ['bool', 'path'=>'string', 'option'=>'int', 'value'=>'mixed'],
'streamWrapper::stream_open' => ['bool', 'path'=>'string', 'mode'=>'string', 'options'=>'int', 'opened_path'=>'string'],
'streamWrapper::stream_read' => ['string', 'count'=>'int'],
'streamWrapper::stream_seek' => ['bool', 'offset'=>'int', 'whence'=>'int'],
'streamWrapper::stream_set_option' => ['bool', 'option'=>'int', 'arg1'=>'int', 'arg2'=>'int'],
'streamWrapper::stream_stat' => ['array'],
'streamWrapper::stream_tell' => ['int'],
'streamWrapper::stream_truncate' => ['bool', 'new_size'=>'int'],
'streamWrapper::stream_write' => ['int', 'data'=>'string'],
'streamWrapper::unlink' => ['bool', 'path'=>'string'],
'streamWrapper::url_stat' => ['array', 'path'=>'string', 'flags'=>'int'],
'strftime' => ['string', 'format'=>'string', 'timestamp='=>'int'],
'strip_tags' => ['string', 'string'=>'string', 'allowed_tags='=>'string'],
'stripcslashes' => ['string', 'string'=>'string'],
'stripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'stripslashes' => ['string', 'string'=>'string'],
'stristr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool'],
'strlen' => ['int', 'string'=>'string'],
'strnatcasecmp' => ['int', 'string1'=>'string', 'string2'=>'string'],
'strnatcmp' => ['int', 'string1'=>'string', 'string2'=>'string'],
'strncasecmp' => ['int', 'string1'=>'string', 'string2'=>'string', 'length'=>'int'],
'strncmp' => ['int', 'string1'=>'string', 'string2'=>'string', 'length'=>'int'],
'strpbrk' => ['string|false', 'string'=>'string', 'characters'=>'string'],
'strpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'strptime' => ['array|false', 'timestamp'=>'string', 'format'=>'string'],
'strrchr' => ['string|false', 'haystack'=>'string', 'needle'=>'string'],
'strrev' => ['string', 'string'=>'string'],
'strripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'strrpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'strspn' => ['int', 'string'=>'string', 'characters'=>'string', 'offset='=>'int', 'length='=>'int'],
'strstr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'before_needle='=>'bool'],
'strtok' => ['string|false', 'string'=>'string', 'token'=>'string'],
'strtok\'1' => ['string|false', 'string'=>'string'],
'strtolower' => ['lowercase-string', 'string'=>'string'],
'strtotime' => ['int|false', 'datetime'=>'string', 'baseTimestamp='=>'int'],
'strtoupper' => ['string', 'string'=>'string'],
'strtr' => ['string', 'string'=>'string', 'from'=>'string', 'to'=>'string'],
'strtr\'1' => ['string', 'string'=>'string', 'from'=>'array'],
'strval' => ['string', 'value'=>'mixed'],
'styleObj::__construct' => ['void', 'label'=>'labelObj', 'style'=>'styleObj'],
'styleObj::convertToString' => ['string'],
'styleObj::free' => ['void'],
'styleObj::getBinding' => ['string', 'stylebinding'=>'mixed'],
'styleObj::getGeomTransform' => ['string'],
'styleObj::ms_newStyleObj' => ['styleObj', 'class'=>'classObj', 'style'=>'styleObj'],
'styleObj::removeBinding' => ['int', 'stylebinding'=>'mixed'],
'styleObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'styleObj::setBinding' => ['int', 'stylebinding'=>'mixed', 'value'=>'string'],
'styleObj::setGeomTransform' => ['int', 'value'=>'string'],
'styleObj::updateFromString' => ['int', 'snippet'=>'string'],
'substr' => ['string|false', 'string'=>'string', 'offset'=>'int', 'length='=>'int'],
'substr_compare' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset'=>'int', 'length='=>'int', 'case_insensitive='=>'bool'],
'substr_count' => ['int', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'length='=>'int'],
'substr_replace' => ['string|string[]', 'string'=>'string|string[]', 'replace'=>'mixed', 'offset'=>'mixed', 'length='=>'mixed'],
'suhosin_encrypt_cookie' => ['string|false', 'name'=>'string', 'value'=>'string'],
'suhosin_get_raw_cookies' => ['array'],
'SVM::__construct' => ['void'],
'svm::crossvalidate' => ['float', 'problem'=>'array', 'number_of_folds'=>'int'],
'SVM::getOptions' => ['array'],
'SVM::setOptions' => ['bool', 'params'=>'array'],
'svm::train' => ['SVMModel', 'problem'=>'array', 'weights='=>'array'],
'SVMModel::__construct' => ['void', 'filename='=>'string'],
'SVMModel::checkProbabilityModel' => ['bool'],
'SVMModel::getLabels' => ['array'],
'SVMModel::getNrClass' => ['int'],
'SVMModel::getSvmType' => ['int'],
'SVMModel::getSvrProbability' => ['float'],
'SVMModel::load' => ['bool', 'filename'=>'string'],
'SVMModel::predict' => ['float', 'data'=>'array'],
'SVMModel::predict_probability' => ['float', 'data'=>'array'],
'SVMModel::save' => ['bool', 'filename'=>'string'],
'svn_add' => ['bool', 'path'=>'string', 'recursive='=>'bool', 'force='=>'bool'],
'svn_auth_get_parameter' => ['?string', 'key'=>'string'],
'svn_auth_set_parameter' => ['void', 'key'=>'string', 'value'=>'string'],
'svn_blame' => ['array', 'repository_url'=>'string', 'revision_no='=>'int'],
'svn_cat' => ['string', 'repos_url'=>'string', 'revision_no='=>'int'],
'svn_checkout' => ['bool', 'repos'=>'string', 'targetpath'=>'string', 'revision='=>'int', 'flags='=>'int'],
'svn_cleanup' => ['bool', 'workingdir'=>'string'],
'svn_client_version' => ['string'],
'svn_commit' => ['array', 'log'=>'string', 'targets'=>'array', 'dontrecurse='=>'bool'],
'svn_delete' => ['bool', 'path'=>'string', 'force='=>'bool'],
'svn_diff' => ['array', 'path1'=>'string', 'rev1'=>'int', 'path2'=>'string', 'rev2'=>'int'],
'svn_export' => ['bool', 'frompath'=>'string', 'topath'=>'string', 'working_copy='=>'bool', 'revision_no='=>'int'],
'svn_fs_abort_txn' => ['bool', 'txn'=>'resource'],
'svn_fs_apply_text' => ['resource', 'root'=>'resource', 'path'=>'string'],
'svn_fs_begin_txn2' => ['resource', 'repos'=>'resource', 'rev'=>'int'],
'svn_fs_change_node_prop' => ['bool', 'root'=>'resource', 'path'=>'string', 'name'=>'string', 'value'=>'string'],
'svn_fs_check_path' => ['int', 'fsroot'=>'resource', 'path'=>'string'],
'svn_fs_contents_changed' => ['bool', 'root1'=>'resource', 'path1'=>'string', 'root2'=>'resource', 'path2'=>'string'],
'svn_fs_copy' => ['bool', 'from_root'=>'resource', 'from_path'=>'string', 'to_root'=>'resource', 'to_path'=>'string'],
'svn_fs_delete' => ['bool', 'root'=>'resource', 'path'=>'string'],
'svn_fs_dir_entries' => ['array', 'fsroot'=>'resource', 'path'=>'string'],
'svn_fs_file_contents' => ['resource', 'fsroot'=>'resource', 'path'=>'string'],
'svn_fs_file_length' => ['int', 'fsroot'=>'resource', 'path'=>'string'],
'svn_fs_is_dir' => ['bool', 'root'=>'resource', 'path'=>'string'],
'svn_fs_is_file' => ['bool', 'root'=>'resource', 'path'=>'string'],
'svn_fs_make_dir' => ['bool', 'root'=>'resource', 'path'=>'string'],
'svn_fs_make_file' => ['bool', 'root'=>'resource', 'path'=>'string'],
'svn_fs_node_created_rev' => ['int', 'fsroot'=>'resource', 'path'=>'string'],
'svn_fs_node_prop' => ['string', 'fsroot'=>'resource', 'path'=>'string', 'propname'=>'string'],
'svn_fs_props_changed' => ['bool', 'root1'=>'resource', 'path1'=>'string', 'root2'=>'resource', 'path2'=>'string'],
'svn_fs_revision_prop' => ['string', 'fs'=>'resource', 'revnum'=>'int', 'propname'=>'string'],
'svn_fs_revision_root' => ['resource', 'fs'=>'resource', 'revnum'=>'int'],
'svn_fs_txn_root' => ['resource', 'txn'=>'resource'],
'svn_fs_youngest_rev' => ['int', 'fs'=>'resource'],
'svn_import' => ['bool', 'path'=>'string', 'url'=>'string', 'nonrecursive'=>'bool'],
'svn_log' => ['array', 'repos_url'=>'string', 'start_revision='=>'int', 'end_revision='=>'int', 'limit='=>'int', 'flags='=>'int'],
'svn_ls' => ['array', 'repos_url'=>'string', 'revision_no='=>'int', 'recurse='=>'bool', 'peg='=>'bool'],
'svn_mkdir' => ['bool', 'path'=>'string', 'log_message='=>'string'],
'svn_move' => ['mixed', 'src_path'=>'string', 'dst_path'=>'string', 'force='=>'bool'],
'svn_propget' => ['mixed', 'path'=>'string', 'property_name'=>'string', 'recurse='=>'bool', 'revision'=>'int'],
'svn_proplist' => ['mixed', 'path'=>'string', 'recurse='=>'bool', 'revision'=>'int'],
'svn_repos_create' => ['resource', 'path'=>'string', 'config='=>'array', 'fsconfig='=>'array'],
'svn_repos_fs' => ['resource', 'repos'=>'resource'],
'svn_repos_fs_begin_txn_for_commit' => ['resource', 'repos'=>'resource', 'rev'=>'int', 'author'=>'string', 'log_msg'=>'string'],
'svn_repos_fs_commit_txn' => ['int', 'txn'=>'resource'],
'svn_repos_hotcopy' => ['bool', 'repospath'=>'string', 'destpath'=>'string', 'cleanlogs'=>'bool'],
'svn_repos_open' => ['resource', 'path'=>'string'],
'svn_repos_recover' => ['bool', 'path'=>'string'],
'svn_revert' => ['bool', 'path'=>'string', 'recursive='=>'bool'],
'svn_status' => ['array', 'path'=>'string', 'flags='=>'int'],
'svn_update' => ['int|false', 'path'=>'string', 'revno='=>'int', 'recurse='=>'bool'],
'swf_actiongeturl' => ['', 'url'=>'string', 'target'=>'string'],
'swf_actiongotoframe' => ['', 'framenumber'=>'int'],
'swf_actiongotolabel' => ['', 'label'=>'string'],
'swf_actionnextframe' => [''],
'swf_actionplay' => [''],
'swf_actionprevframe' => [''],
'swf_actionsettarget' => ['', 'target'=>'string'],
'swf_actionstop' => [''],
'swf_actiontogglequality' => [''],
'swf_actionwaitforframe' => ['', 'framenumber'=>'int', 'skipcount'=>'int'],
'swf_addbuttonrecord' => ['', 'states'=>'int', 'shapeid'=>'int', 'depth'=>'int'],
'swf_addcolor' => ['', 'r'=>'float', 'g'=>'float', 'b'=>'float', 'a'=>'float'],
'swf_closefile' => ['', 'return_file='=>'int'],
'swf_definebitmap' => ['', 'objid'=>'int', 'image_name'=>'string'],
'swf_definefont' => ['', 'fontid'=>'int', 'fontname'=>'string'],
'swf_defineline' => ['', 'objid'=>'int', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'width'=>'float'],
'swf_definepoly' => ['', 'objid'=>'int', 'coords'=>'array', 'npoints'=>'int', 'width'=>'float'],
'swf_definerect' => ['', 'objid'=>'int', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'width'=>'float'],
'swf_definetext' => ['', 'objid'=>'int', 'string'=>'string', 'docenter'=>'int'],
'swf_endbutton' => [''],
'swf_enddoaction' => [''],
'swf_endshape' => [''],
'swf_endsymbol' => [''],
'swf_fontsize' => ['', 'size'=>'float'],
'swf_fontslant' => ['', 'slant'=>'float'],
'swf_fonttracking' => ['', 'tracking'=>'float'],
'swf_getbitmapinfo' => ['array', 'bitmapid'=>'int'],
'swf_getfontinfo' => ['array'],
'swf_getframe' => ['int'],
'swf_labelframe' => ['', 'name'=>'string'],
'swf_lookat' => ['', 'view_x'=>'float', 'view_y'=>'float', 'view_z'=>'float', 'reference_x'=>'float', 'reference_y'=>'float', 'reference_z'=>'float', 'twist'=>'float'],
'swf_modifyobject' => ['', 'depth'=>'int', 'how'=>'int'],
'swf_mulcolor' => ['', 'r'=>'float', 'g'=>'float', 'b'=>'float', 'a'=>'float'],
'swf_nextid' => ['int'],
'swf_oncondition' => ['', 'transition'=>'int'],
'swf_openfile' => ['', 'filename'=>'string', 'width'=>'float', 'height'=>'float', 'framerate'=>'float', 'r'=>'float', 'g'=>'float', 'b'=>'float'],
'swf_ortho' => ['', 'xmin'=>'float', 'xmax'=>'float', 'ymin'=>'float', 'ymax'=>'float', 'zmin'=>'float', 'zmax'=>'float'],
'swf_ortho2' => ['', 'xmin'=>'float', 'xmax'=>'float', 'ymin'=>'float', 'ymax'=>'float'],
'swf_perspective' => ['', 'fovy'=>'float', 'aspect'=>'float', 'near'=>'float', 'far'=>'float'],
'swf_placeobject' => ['', 'objid'=>'int', 'depth'=>'int'],
'swf_polarview' => ['', 'dist'=>'float', 'azimuth'=>'float', 'incidence'=>'float', 'twist'=>'float'],
'swf_popmatrix' => [''],
'swf_posround' => ['', 'round'=>'int'],
'swf_pushmatrix' => [''],
'swf_removeobject' => ['', 'depth'=>'int'],
'swf_rotate' => ['', 'angle'=>'float', 'axis'=>'string'],
'swf_scale' => ['', 'x'=>'float', 'y'=>'float', 'z'=>'float'],
'swf_setfont' => ['', 'fontid'=>'int'],
'swf_setframe' => ['', 'framenumber'=>'int'],
'swf_shapearc' => ['', 'x'=>'float', 'y'=>'float', 'r'=>'float', 'ang1'=>'float', 'ang2'=>'float'],
'swf_shapecurveto' => ['', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float'],
'swf_shapecurveto3' => ['', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'swf_shapefillbitmapclip' => ['', 'bitmapid'=>'int'],
'swf_shapefillbitmaptile' => ['', 'bitmapid'=>'int'],
'swf_shapefilloff' => [''],
'swf_shapefillsolid' => ['', 'r'=>'float', 'g'=>'float', 'b'=>'float', 'a'=>'float'],
'swf_shapelinesolid' => ['', 'r'=>'float', 'g'=>'float', 'b'=>'float', 'a'=>'float', 'width'=>'float'],
'swf_shapelineto' => ['', 'x'=>'float', 'y'=>'float'],
'swf_shapemoveto' => ['', 'x'=>'float', 'y'=>'float'],
'swf_showframe' => [''],
'swf_startbutton' => ['', 'objid'=>'int', 'type'=>'int'],
'swf_startdoaction' => [''],
'swf_startshape' => ['', 'objid'=>'int'],
'swf_startsymbol' => ['', 'objid'=>'int'],
'swf_textwidth' => ['float', 'string'=>'string'],
'swf_translate' => ['', 'x'=>'float', 'y'=>'float', 'z'=>'float'],
'swf_viewport' => ['', 'xmin'=>'float', 'xmax'=>'float', 'ymin'=>'float', 'ymax'=>'float'],
'SWFAction::__construct' => ['void', 'script'=>'string'],
'SWFBitmap::__construct' => ['void', 'file'=>'', 'alphafile='=>''],
'SWFBitmap::getHeight' => ['float'],
'SWFBitmap::getWidth' => ['float'],
'SWFButton::__construct' => ['void'],
'SWFButton::addAction' => ['void', 'action'=>'swfaction', 'flags'=>'int'],
'SWFButton::addASound' => ['SWFSoundInstance', 'sound'=>'swfsound', 'flags'=>'int'],
'SWFButton::addShape' => ['void', 'shape'=>'swfshape', 'flags'=>'int'],
'SWFButton::setAction' => ['void', 'action'=>'swfaction'],
'SWFButton::setDown' => ['void', 'shape'=>'swfshape'],
'SWFButton::setHit' => ['void', 'shape'=>'swfshape'],
'SWFButton::setMenu' => ['void', 'flag'=>'int'],
'SWFButton::setOver' => ['void', 'shape'=>'swfshape'],
'SWFButton::setUp' => ['void', 'shape'=>'swfshape'],
'SWFDisplayItem::addAction' => ['void', 'action'=>'swfaction', 'flags'=>'int'],
'SWFDisplayItem::addColor' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFDisplayItem::endMask' => ['void'],
'SWFDisplayItem::getRot' => ['float'],
'SWFDisplayItem::getX' => ['float'],
'SWFDisplayItem::getXScale' => ['float'],
'SWFDisplayItem::getXSkew' => ['float'],
'SWFDisplayItem::getY' => ['float'],
'SWFDisplayItem::getYScale' => ['float'],
'SWFDisplayItem::getYSkew' => ['float'],
'SWFDisplayItem::move' => ['void', 'dx'=>'float', 'dy'=>'float'],
'SWFDisplayItem::moveTo' => ['void', 'x'=>'float', 'y'=>'float'],
'SWFDisplayItem::multColor' => ['void', 'red'=>'float', 'green'=>'float', 'blue'=>'float', 'a='=>'float'],
'SWFDisplayItem::remove' => ['void'],
'SWFDisplayItem::rotate' => ['void', 'angle'=>'float'],
'SWFDisplayItem::rotateTo' => ['void', 'angle'=>'float'],
'SWFDisplayItem::scale' => ['void', 'dx'=>'float', 'dy'=>'float'],
'SWFDisplayItem::scaleTo' => ['void', 'x'=>'float', 'y='=>'float'],
'SWFDisplayItem::setDepth' => ['void', 'depth'=>'int'],
'SWFDisplayItem::setMaskLevel' => ['void', 'level'=>'int'],
'SWFDisplayItem::setMatrix' => ['void', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'x'=>'float', 'y'=>'float'],
'SWFDisplayItem::setName' => ['void', 'name'=>'string'],
'SWFDisplayItem::setRatio' => ['void', 'ratio'=>'float'],
'SWFDisplayItem::skewX' => ['void', 'ddegrees'=>'float'],
'SWFDisplayItem::skewXTo' => ['void', 'degrees'=>'float'],
'SWFDisplayItem::skewY' => ['void', 'ddegrees'=>'float'],
'SWFDisplayItem::skewYTo' => ['void', 'degrees'=>'float'],
'SWFFill::moveTo' => ['void', 'x'=>'float', 'y'=>'float'],
'SWFFill::rotateTo' => ['void', 'angle'=>'float'],
'SWFFill::scaleTo' => ['void', 'x'=>'float', 'y='=>'float'],
'SWFFill::skewXTo' => ['void', 'x'=>'float'],
'SWFFill::skewYTo' => ['void', 'y'=>'float'],
'SWFFont::__construct' => ['void', 'filename'=>'string'],
'SWFFont::getAscent' => ['float'],
'SWFFont::getDescent' => ['float'],
'SWFFont::getLeading' => ['float'],
'SWFFont::getShape' => ['string', 'code'=>'int'],
'SWFFont::getUTF8Width' => ['float', 'string'=>'string'],
'SWFFont::getWidth' => ['float', 'string'=>'string'],
'SWFFontChar::addChars' => ['void', 'char'=>'string'],
'SWFFontChar::addUTF8Chars' => ['void', 'char'=>'string'],
'SWFGradient::__construct' => ['void'],
'SWFGradient::addEntry' => ['void', 'ratio'=>'float', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha='=>'int'],
'SWFMorph::__construct' => ['void'],
'SWFMorph::getShape1' => ['SWFShape'],
'SWFMorph::getShape2' => ['SWFShape'],
'SWFMovie::__construct' => ['void', 'version='=>'int'],
'SWFMovie::add' => ['mixed', 'instance'=>'object'],
'SWFMovie::addExport' => ['void', 'char'=>'swfcharacter', 'name'=>'string'],
'SWFMovie::addFont' => ['mixed', 'font'=>'swffont'],
'SWFMovie::importChar' => ['SWFSprite', 'libswf'=>'string', 'name'=>'string'],
'SWFMovie::importFont' => ['SWFFontChar', 'libswf'=>'string', 'name'=>'string'],
'SWFMovie::labelFrame' => ['void', 'label'=>'string'],
'SWFMovie::namedAnchor' => [''],
'SWFMovie::nextFrame' => ['void'],
'SWFMovie::output' => ['int', 'compression='=>'int'],
'SWFMovie::protect' => [''],
'SWFMovie::remove' => ['void', 'instance'=>'object'],
'SWFMovie::save' => ['int', 'filename'=>'string', 'compression='=>'int'],
'SWFMovie::saveToFile' => ['int', 'x'=>'resource', 'compression='=>'int'],
'SWFMovie::setbackground' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'SWFMovie::setDimension' => ['void', 'width'=>'float', 'height'=>'float'],
'SWFMovie::setFrames' => ['void', 'number'=>'int'],
'SWFMovie::setRate' => ['void', 'rate'=>'float'],
'SWFMovie::startSound' => ['SWFSoundInstance', 'sound'=>'swfsound'],
'SWFMovie::stopSound' => ['void', 'sound'=>'swfsound'],
'SWFMovie::streamMP3' => ['int', 'mp3file'=>'mixed', 'skip='=>'float'],
'SWFMovie::writeExports' => ['void'],
'SWFPrebuiltClip::__construct' => ['void', 'file'=>''],
'SWFShape::__construct' => ['void'],
'SWFShape::addFill' => ['SWFFill', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha='=>'int', 'bitmap='=>'swfbitmap', 'flags='=>'int', 'gradient='=>'swfgradient'],
'SWFShape::addFill\'1' => ['SWFFill', 'bitmap'=>'SWFBitmap', 'flags='=>'int'],
'SWFShape::addFill\'2' => ['SWFFill', 'gradient'=>'SWFGradient', 'flags='=>'int'],
'SWFShape::drawArc' => ['void', 'r'=>'float', 'startangle'=>'float', 'endangle'=>'float'],
'SWFShape::drawCircle' => ['void', 'r'=>'float'],
'SWFShape::drawCubic' => ['int', 'bx'=>'float', 'by'=>'float', 'cx'=>'float', 'cy'=>'float', 'dx'=>'float', 'dy'=>'float'],
'SWFShape::drawCubicTo' => ['int', 'bx'=>'float', 'by'=>'float', 'cx'=>'float', 'cy'=>'float', 'dx'=>'float', 'dy'=>'float'],
'SWFShape::drawCurve' => ['int', 'controldx'=>'float', 'controldy'=>'float', 'anchordx'=>'float', 'anchordy'=>'float', 'targetdx='=>'float', 'targetdy='=>'float'],
'SWFShape::drawCurveTo' => ['int', 'controlx'=>'float', 'controly'=>'float', 'anchorx'=>'float', 'anchory'=>'float', 'targetx='=>'float', 'targety='=>'float'],
'SWFShape::drawGlyph' => ['void', 'font'=>'swffont', 'character'=>'string', 'size='=>'int'],
'SWFShape::drawLine' => ['void', 'dx'=>'float', 'dy'=>'float'],
'SWFShape::drawLineTo' => ['void', 'x'=>'float', 'y'=>'float'],
'SWFShape::movePen' => ['void', 'dx'=>'float', 'dy'=>'float'],
'SWFShape::movePenTo' => ['void', 'x'=>'float', 'y'=>'float'],
'SWFShape::setLeftFill' => ['', 'fill'=>'swfgradient', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFShape::setLine' => ['', 'shape'=>'swfshape', 'width'=>'int', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFShape::setRightFill' => ['', 'fill'=>'swfgradient', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFSound' => ['SWFSound', 'filename'=>'string', 'flags='=>'int'],
'SWFSound::__construct' => ['void', 'filename'=>'string', 'flags='=>'int'],
'SWFSoundInstance::loopCount' => ['void', 'point'=>'int'],
'SWFSoundInstance::loopInPoint' => ['void', 'point'=>'int'],
'SWFSoundInstance::loopOutPoint' => ['void', 'point'=>'int'],
'SWFSoundInstance::noMultiple' => ['void'],
'SWFSprite::__construct' => ['void'],
'SWFSprite::add' => ['void', 'object'=>'object'],
'SWFSprite::labelFrame' => ['void', 'label'=>'string'],
'SWFSprite::nextFrame' => ['void'],
'SWFSprite::remove' => ['void', 'object'=>'object'],
'SWFSprite::setFrames' => ['void', 'number'=>'int'],
'SWFSprite::startSound' => ['SWFSoundInstance', 'sount'=>'swfsound'],
'SWFSprite::stopSound' => ['void', 'sount'=>'swfsound'],
'SWFText::__construct' => ['void'],
'SWFText::addString' => ['void', 'string'=>'string'],
'SWFText::addUTF8String' => ['void', 'text'=>'string'],
'SWFText::getAscent' => ['float'],
'SWFText::getDescent' => ['float'],
'SWFText::getLeading' => ['float'],
'SWFText::getUTF8Width' => ['float', 'string'=>'string'],
'SWFText::getWidth' => ['float', 'string'=>'string'],
'SWFText::moveTo' => ['void', 'x'=>'float', 'y'=>'float'],
'SWFText::setColor' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFText::setFont' => ['void', 'font'=>'swffont'],
'SWFText::setHeight' => ['void', 'height'=>'float'],
'SWFText::setSpacing' => ['void', 'spacing'=>'float'],
'SWFTextField::__construct' => ['void', 'flags='=>'int'],
'SWFTextField::addChars' => ['void', 'chars'=>'string'],
'SWFTextField::addString' => ['void', 'string'=>'string'],
'SWFTextField::align' => ['void', 'alignement'=>'int'],
'SWFTextField::setBounds' => ['void', 'width'=>'float', 'height'=>'float'],
'SWFTextField::setColor' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFTextField::setFont' => ['void', 'font'=>'swffont'],
'SWFTextField::setHeight' => ['void', 'height'=>'float'],
'SWFTextField::setIndentation' => ['void', 'width'=>'float'],
'SWFTextField::setLeftMargin' => ['void', 'width'=>'float'],
'SWFTextField::setLineSpacing' => ['void', 'height'=>'float'],
'SWFTextField::setMargins' => ['void', 'left'=>'float', 'right'=>'float'],
'SWFTextField::setName' => ['void', 'name'=>'string'],
'SWFTextField::setPadding' => ['void', 'padding'=>'float'],
'SWFTextField::setRightMargin' => ['void', 'width'=>'float'],
'SWFVideoStream::__construct' => ['void', 'file='=>'string'],
'SWFVideoStream::getNumFrames' => ['int'],
'SWFVideoStream::setDimension' => ['void', 'x'=>'int', 'y'=>'int'],
'Swish::__construct' => ['void', 'index_names'=>'string'],
'Swish::getMetaList' => ['array', 'index_name'=>'string'],
'Swish::getPropertyList' => ['array', 'index_name'=>'string'],
'Swish::prepare' => ['object', 'query='=>'string'],
'Swish::query' => ['object', 'query'=>'string'],
'SwishResult::getMetaList' => ['array'],
'SwishResult::stem' => ['array', 'word'=>'string'],
'SwishResults::getParsedWords' => ['array', 'index_name'=>'string'],
'SwishResults::getRemovedStopwords' => ['array', 'index_name'=>'string'],
'SwishResults::nextResult' => ['object'],
'SwishResults::seekResult' => ['int', 'position'=>'int'],
'SwishSearch::execute' => ['object', 'query='=>'string'],
'SwishSearch::resetLimit' => [''],
'SwishSearch::setLimit' => ['', 'property'=>'string', 'low'=>'string', 'high'=>'string'],
'SwishSearch::setPhraseDelimiter' => ['', 'delimiter'=>'string'],
'SwishSearch::setSort' => ['', 'sort'=>'string'],
'SwishSearch::setStructure' => ['', 'structure'=>'int'],
'swoole\async::dnsLookup' => ['void', 'hostname'=>'string', 'callback'=>'callable'],
'swoole\async::read' => ['bool', 'filename'=>'string', 'callback'=>'callable', 'chunk_size='=>'integer', 'offset='=>'integer'],
'swoole\async::readFile' => ['void', 'filename'=>'string', 'callback'=>'callable'],
'swoole\async::set' => ['void', 'settings'=>'array'],
'swoole\async::write' => ['void', 'filename'=>'string', 'content'=>'string', 'offset='=>'integer', 'callback='=>'callable'],
'swoole\async::writeFile' => ['void', 'filename'=>'string', 'content'=>'string', 'callback='=>'callable', 'flags='=>'string'],
'swoole\atomic::add' => ['integer', 'add_value='=>'integer'],
'swoole\atomic::cmpset' => ['integer', 'cmp_value'=>'integer', 'new_value'=>'integer'],
'swoole\atomic::get' => ['integer'],
'swoole\atomic::set' => ['integer', 'value'=>'integer'],
'swoole\atomic::sub' => ['integer', 'sub_value='=>'integer'],
'swoole\buffer::__destruct' => ['void'],
'swoole\buffer::__toString' => ['string'],
'swoole\buffer::append' => ['integer', 'data'=>'string'],
'swoole\buffer::clear' => ['void'],
'swoole\buffer::expand' => ['integer', 'size'=>'integer'],
'swoole\buffer::read' => ['string', 'offset'=>'integer', 'length'=>'integer'],
'swoole\buffer::recycle' => ['void'],
'swoole\buffer::substr' => ['string', 'offset'=>'integer', 'length='=>'integer', 'remove='=>'bool'],
'swoole\buffer::write' => ['void', 'offset'=>'integer', 'data'=>'string'],
'swoole\channel::__destruct' => ['void'],
'swoole\channel::pop' => ['mixed'],
'swoole\channel::push' => ['bool', 'data'=>'string'],
'swoole\channel::stats' => ['array'],
'swoole\client::__destruct' => ['void'],
'swoole\client::close' => ['bool', 'force='=>'bool'],
'swoole\client::connect' => ['bool', 'host'=>'string', 'port='=>'integer', 'timeout='=>'integer', 'flag='=>'integer'],
'swoole\client::getpeername' => ['array'],
'swoole\client::getsockname' => ['array'],
'swoole\client::isConnected' => ['bool'],
'swoole\client::on' => ['void', 'event'=>'string', 'callback'=>'callable'],
'swoole\client::pause' => ['void'],
'swoole\client::pipe' => ['void', 'socket'=>'string'],
'swoole\client::recv' => ['void', 'size='=>'string', 'flag='=>'string'],
'swoole\client::resume' => ['void'],
'swoole\client::send' => ['integer', 'data'=>'string', 'flag='=>'string'],
'swoole\client::sendfile' => ['bool', 'filename'=>'string', 'offset='=>'int'],
'swoole\client::sendto' => ['bool', 'ip'=>'string', 'port'=>'integer', 'data'=>'string'],
'swoole\client::set' => ['void', 'settings'=>'array'],
'swoole\client::sleep' => ['void'],
'swoole\client::wakeup' => ['void'],
'swoole\connection\iterator::count' => ['int'],
'swoole\connection\iterator::current' => ['Connection'],
'swoole\connection\iterator::key' => ['int'],
'swoole\connection\iterator::next' => ['Connection'],
'swoole\connection\iterator::offsetExists' => ['bool', 'index'=>'int'],
'swoole\connection\iterator::offsetGet' => ['Connection', 'index'=>'string'],
'swoole\connection\iterator::offsetSet' => ['void', 'offset'=>'int', 'connection'=>'mixed'],
'swoole\connection\iterator::offsetUnset' => ['void', 'offset'=>'int'],
'swoole\connection\iterator::rewind' => ['void'],
'swoole\connection\iterator::valid' => ['bool'],
'swoole\coroutine::call_user_func' => ['mixed', 'callback'=>'callable', 'parameter='=>'mixed', '...args='=>'mixed'],
'swoole\coroutine::call_user_func_array' => ['mixed', 'callback'=>'callable', 'param_array'=>'array'],
'swoole\coroutine::cli_wait' => ['ReturnType'],
'swoole\coroutine::create' => ['ReturnType'],
'swoole\coroutine::getuid' => ['ReturnType'],
'swoole\coroutine::resume' => ['ReturnType'],
'swoole\coroutine::suspend' => ['ReturnType'],
'swoole\coroutine\client::__destruct' => ['ReturnType'],
'swoole\coroutine\client::close' => ['ReturnType'],
'swoole\coroutine\client::connect' => ['ReturnType'],
'swoole\coroutine\client::getpeername' => ['ReturnType'],
'swoole\coroutine\client::getsockname' => ['ReturnType'],
'swoole\coroutine\client::isConnected' => ['ReturnType'],
'swoole\coroutine\client::recv' => ['ReturnType'],
'swoole\coroutine\client::send' => ['ReturnType'],
'swoole\coroutine\client::sendfile' => ['ReturnType'],
'swoole\coroutine\client::sendto' => ['ReturnType'],
'swoole\coroutine\client::set' => ['ReturnType'],
'swoole\coroutine\http\client::__destruct' => ['ReturnType'],
'swoole\coroutine\http\client::addFile' => ['ReturnType'],
'swoole\coroutine\http\client::close' => ['ReturnType'],
'swoole\coroutine\http\client::execute' => ['ReturnType'],
'swoole\coroutine\http\client::get' => ['ReturnType'],
'swoole\coroutine\http\client::getDefer' => ['ReturnType'],
'swoole\coroutine\http\client::isConnected' => ['ReturnType'],
'swoole\coroutine\http\client::post' => ['ReturnType'],
'swoole\coroutine\http\client::recv' => ['ReturnType'],
'swoole\coroutine\http\client::set' => ['ReturnType'],
'swoole\coroutine\http\client::setCookies' => ['ReturnType'],
'swoole\coroutine\http\client::setData' => ['ReturnType'],
'swoole\coroutine\http\client::setDefer' => ['ReturnType'],
'swoole\coroutine\http\client::setHeaders' => ['ReturnType'],
'swoole\coroutine\http\client::setMethod' => ['ReturnType'],
'swoole\coroutine\mysql::__destruct' => ['ReturnType'],
'swoole\coroutine\mysql::close' => ['ReturnType'],
'swoole\coroutine\mysql::connect' => ['ReturnType'],
'swoole\coroutine\mysql::getDefer' => ['ReturnType'],
'swoole\coroutine\mysql::query' => ['ReturnType'],
'swoole\coroutine\mysql::recv' => ['ReturnType'],
'swoole\coroutine\mysql::setDefer' => ['ReturnType'],
'swoole\event::add' => ['bool', 'fd'=>'int', 'read_callback'=>'callable', 'write_callback='=>'callable', 'events='=>'string'],
'swoole\event::defer' => ['void', 'callback'=>'mixed'],
'swoole\event::del' => ['bool', 'fd'=>'string'],
'swoole\event::exit' => ['void'],
'swoole\event::set' => ['bool', 'fd'=>'int', 'read_callback='=>'string', 'write_callback='=>'string', 'events='=>'string'],
'swoole\event::wait' => ['void'],
'swoole\event::write' => ['void', 'fd'=>'string', 'data'=>'string'],
'swoole\http\client::__destruct' => ['void'],
'swoole\http\client::addFile' => ['void', 'path'=>'string', 'name'=>'string', 'type='=>'string', 'filename='=>'string', 'offset='=>'string'],
'swoole\http\client::close' => ['void'],
'swoole\http\client::download' => ['void', 'path'=>'string', 'file'=>'string', 'callback'=>'callable', 'offset='=>'integer'],
'swoole\http\client::execute' => ['void', 'path'=>'string', 'callback'=>'string'],
'swoole\http\client::get' => ['void', 'path'=>'string', 'callback'=>'callable'],
'swoole\http\client::isConnected' => ['bool'],
'swoole\http\client::on' => ['void', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\http\client::post' => ['void', 'path'=>'string', 'data'=>'string', 'callback'=>'callable'],
'swoole\http\client::push' => ['void', 'data'=>'string', 'opcode='=>'string', 'finish='=>'string'],
'swoole\http\client::set' => ['void', 'settings'=>'array'],
'swoole\http\client::setCookies' => ['void', 'cookies'=>'array'],
'swoole\http\client::setData' => ['ReturnType', 'data'=>'string'],
'swoole\http\client::setHeaders' => ['void', 'headers'=>'array'],
'swoole\http\client::setMethod' => ['void', 'method'=>'string'],
'swoole\http\client::upgrade' => ['void', 'path'=>'string', 'callback'=>'string'],
'swoole\http\request::__destruct' => ['void'],
'swoole\http\request::rawcontent' => ['string'],
'swoole\http\response::__destruct' => ['void'],
'swoole\http\response::cookie' => ['string', 'name'=>'string', 'value='=>'string', 'expires='=>'string', 'path='=>'string', 'domain='=>'string', 'secure='=>'string', 'httponly='=>'string'],
'swoole\http\response::end' => ['void', 'content='=>'string'],
'swoole\http\response::gzip' => ['ReturnType', 'compress_level='=>'string'],
'swoole\http\response::header' => ['void', 'key'=>'string', 'value'=>'string', 'ucwords='=>'string'],
'swoole\http\response::initHeader' => ['ReturnType'],
'swoole\http\response::rawcookie' => ['ReturnType', 'name'=>'string', 'value='=>'string', 'expires='=>'string', 'path='=>'string', 'domain='=>'string', 'secure='=>'string', 'httponly='=>'string'],
'swoole\http\response::sendfile' => ['ReturnType', 'filename'=>'string', 'offset='=>'int'],
'swoole\http\response::status' => ['ReturnType', 'http_code'=>'string'],
'swoole\http\response::write' => ['void', 'content'=>'string'],
'swoole\http\server::on' => ['void', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\http\server::start' => ['void'],
'swoole\lock::__destruct' => ['void'],
'swoole\lock::lock' => ['void'],
'swoole\lock::lock_read' => ['void'],
'swoole\lock::trylock' => ['void'],
'swoole\lock::trylock_read' => ['void'],
'swoole\lock::unlock' => ['void'],
'swoole\mmap::open' => ['ReturnType', 'filename'=>'string', 'size='=>'string', 'offset='=>'string'],
'swoole\mysql::__destruct' => ['void'],
'swoole\mysql::close' => ['void'],
'swoole\mysql::connect' => ['void', 'server_config'=>'array', 'callback'=>'callable'],
'swoole\mysql::getBuffer' => ['ReturnType'],
'swoole\mysql::on' => ['void', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\mysql::query' => ['ReturnType', 'sql'=>'string', 'callback'=>'callable'],
'swoole\process::__destruct' => ['void'],
'swoole\process::alarm' => ['void', 'interval_usec'=>'integer'],
'swoole\process::close' => ['void'],
'swoole\process::daemon' => ['void', 'nochdir='=>'bool', 'noclose='=>'bool'],
'swoole\process::exec' => ['ReturnType', 'exec_file'=>'string', 'args'=>'string'],
'swoole\process::exit' => ['void', 'exit_code='=>'string'],
'swoole\process::freeQueue' => ['void'],
'swoole\process::kill' => ['void', 'pid'=>'integer', 'signal_no='=>'string'],
'swoole\process::name' => ['void', 'process_name'=>'string'],
'swoole\process::pop' => ['mixed', 'maxsize='=>'integer'],
'swoole\process::push' => ['bool', 'data'=>'string'],
'swoole\process::read' => ['string', 'maxsize='=>'integer'],
'swoole\process::signal' => ['void', 'signal_no'=>'string', 'callback'=>'callable'],
'swoole\process::start' => ['void'],
'swoole\process::statQueue' => ['array'],
'swoole\process::useQueue' => ['bool', 'key'=>'integer', 'mode='=>'integer'],
'swoole\process::wait' => ['array', 'blocking='=>'bool'],
'swoole\process::write' => ['integer', 'data'=>'string'],
'swoole\redis\server::format' => ['ReturnType', 'type'=>'string', 'value='=>'string'],
'swoole\redis\server::setHandler' => ['ReturnType', 'command'=>'string', 'callback'=>'string', 'number_of_string_param='=>'string', 'type_of_array_param='=>'string'],
'swoole\redis\server::start' => ['ReturnType'],
'swoole\serialize::pack' => ['ReturnType', 'data'=>'string', 'is_fast='=>'int'],
'swoole\serialize::unpack' => ['ReturnType', 'data'=>'string', 'args='=>'string'],
'swoole\server::addlistener' => ['void', 'host'=>'string', 'port'=>'integer', 'socket_type'=>'string'],
'swoole\server::addProcess' => ['bool', 'process'=>'swoole_process'],
'swoole\server::after' => ['ReturnType', 'after_time_ms'=>'integer', 'callback'=>'callable', 'param='=>'string'],
'swoole\server::bind' => ['bool', 'fd'=>'integer', 'uid'=>'integer'],
'swoole\server::close' => ['bool', 'fd'=>'integer', 'reset='=>'bool'],
'swoole\server::confirm' => ['bool', 'fd'=>'integer'],
'swoole\server::connection_info' => ['array', 'fd'=>'integer', 'reactor_id='=>'integer'],
'swoole\server::connection_list' => ['array', 'start_fd'=>'integer', 'pagesize='=>'integer'],
'swoole\server::defer' => ['void', 'callback'=>'callable'],
'swoole\server::exist' => ['bool', 'fd'=>'integer'],
'swoole\server::finish' => ['void', 'data'=>'string'],
'swoole\server::getClientInfo' => ['ReturnType', 'fd'=>'integer', 'reactor_id='=>'integer'],
'swoole\server::getClientList' => ['array', 'start_fd'=>'integer', 'pagesize='=>'integer'],
'swoole\server::getLastError' => ['integer'],
'swoole\server::heartbeat' => ['mixed', 'if_close_connection'=>'bool'],
'swoole\server::listen' => ['bool', 'host'=>'string', 'port'=>'integer', 'socket_type'=>'string'],
'swoole\server::on' => ['void', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\server::pause' => ['void', 'fd'=>'integer'],
'swoole\server::protect' => ['void', 'fd'=>'integer', 'is_protected='=>'bool'],
'swoole\server::reload' => ['bool'],
'swoole\server::resume' => ['void', 'fd'=>'integer'],
'swoole\server::send' => ['bool', 'fd'=>'integer', 'data'=>'string', 'reactor_id='=>'integer'],
'swoole\server::sendfile' => ['bool', 'fd'=>'integer', 'filename'=>'string', 'offset='=>'integer'],
'swoole\server::sendMessage' => ['bool', 'worker_id'=>'integer', 'data'=>'string'],
'swoole\server::sendto' => ['bool', 'ip'=>'string', 'port'=>'integer', 'data'=>'string', 'server_socket='=>'string'],
'swoole\server::sendwait' => ['bool', 'fd'=>'integer', 'data'=>'string'],
'swoole\server::set' => ['ReturnType', 'settings'=>'array'],
'swoole\server::shutdown' => ['void'],
'swoole\server::start' => ['void'],
'swoole\server::stats' => ['array'],
'swoole\server::stop' => ['bool', 'worker_id='=>'integer'],
'swoole\server::task' => ['mixed', 'data'=>'string', 'dst_worker_id='=>'integer', 'callback='=>'callable'],
'swoole\server::taskwait' => ['void', 'data'=>'string', 'timeout='=>'float', 'worker_id='=>'integer'],
'swoole\server::taskWaitMulti' => ['void', 'tasks'=>'array', 'timeout_ms='=>'double'],
'swoole\server::tick' => ['void', 'interval_ms'=>'integer', 'callback'=>'callable'],
'swoole\server\port::__destruct' => ['void'],
'swoole\server\port::on' => ['ReturnType', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\server\port::set' => ['void', 'settings'=>'array'],
'swoole\table::column' => ['ReturnType', 'name'=>'string', 'type'=>'string', 'size='=>'integer'],
'swoole\table::count' => ['integer'],
'swoole\table::create' => ['void'],
'swoole\table::current' => ['array'],
'swoole\table::decr' => ['ReturnType', 'key'=>'string', 'column'=>'string', 'decrby='=>'integer'],
'swoole\table::del' => ['void', 'key'=>'string'],
'swoole\table::destroy' => ['void'],
'swoole\table::exist' => ['bool', 'key'=>'string'],
'swoole\table::get' => ['integer', 'row_key'=>'string', 'column_key'=>'string'],
'swoole\table::incr' => ['void', 'key'=>'string', 'column'=>'string', 'incrby='=>'integer'],
'swoole\table::key' => ['string'],
'swoole\table::next' => ['ReturnType'],
'swoole\table::rewind' => ['void'],
'swoole\table::set' => ['VOID', 'key'=>'string', 'value'=>'array'],
'swoole\table::valid' => ['bool'],
'swoole\timer::after' => ['void', 'after_time_ms'=>'int', 'callback'=>'callable'],
'swoole\timer::clear' => ['void', 'timer_id'=>'integer'],
'swoole\timer::exists' => ['bool', 'timer_id'=>'integer'],
'swoole\timer::tick' => ['void', 'interval_ms'=>'integer', 'callback'=>'callable', 'param='=>'string'],
'swoole\websocket\server::exist' => ['bool', 'fd'=>'integer'],
'swoole\websocket\server::on' => ['ReturnType', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\websocket\server::pack' => ['binary', 'data'=>'string', 'opcode='=>'string', 'finish='=>'string', 'mask='=>'string'],
'swoole\websocket\server::push' => ['void', 'fd'=>'string', 'data'=>'string', 'opcode='=>'string', 'finish='=>'string'],
'swoole\websocket\server::unpack' => ['string', 'data'=>'binary'],
'swoole_async_dns_lookup' => ['bool', 'hostname'=>'string', 'callback'=>'callable'],
'swoole_async_read' => ['bool', 'filename'=>'string', 'callback'=>'callable', 'chunk_size='=>'int', 'offset='=>'int'],
'swoole_async_readfile' => ['bool', 'filename'=>'string', 'callback'=>'string'],
'swoole_async_set' => ['void', 'settings'=>'array'],
'swoole_async_write' => ['bool', 'filename'=>'string', 'content'=>'string', 'offset='=>'int', 'callback='=>'callable'],
'swoole_async_writefile' => ['bool', 'filename'=>'string', 'content'=>'string', 'callback='=>'callable', 'flags='=>'int'],
'swoole_client_select' => ['int', 'read_array'=>'array', 'write_array'=>'array', 'error_array'=>'array', 'timeout='=>'float'],
'swoole_cpu_num' => ['int'],
'swoole_errno' => ['int'],
'swoole_event_add' => ['int', 'fd'=>'int', 'read_callback='=>'callable', 'write_callback='=>'callable', 'events='=>'int'],
'swoole_event_defer' => ['bool', 'callback'=>'callable'],
'swoole_event_del' => ['bool', 'fd'=>'int'],
'swoole_event_exit' => ['void'],
'swoole_event_set' => ['bool', 'fd'=>'int', 'read_callback='=>'callable', 'write_callback='=>'callable', 'events='=>'int'],
'swoole_event_wait' => ['void'],
'swoole_event_write' => ['bool', 'fd'=>'int', 'data'=>'string'],
'swoole_get_local_ip' => ['array'],
'swoole_last_error' => ['int'],
'swoole_load_module' => ['mixed', 'filename'=>'string'],
'swoole_select' => ['int', 'read_array'=>'array', 'write_array'=>'array', 'error_array'=>'array', 'timeout='=>'float'],
'swoole_set_process_name' => ['void', 'process_name'=>'string', 'size='=>'int'],
'swoole_strerror' => ['string', 'errno'=>'int', 'error_type='=>'int'],
'swoole_timer_after' => ['int', 'ms'=>'int', 'callback'=>'callable', 'param='=>'mixed'],
'swoole_timer_exists' => ['bool', 'timer_id'=>'int'],
'swoole_timer_tick' => ['int', 'ms'=>'int', 'callback'=>'callable', 'param='=>'mixed'],
'swoole_version' => ['string'],
'symbolObj::__construct' => ['void', 'map'=>'mapObj', 'symbolname'=>'string'],
'symbolObj::free' => ['void'],
'symbolObj::getPatternArray' => ['array'],
'symbolObj::getPointsArray' => ['array'],
'symbolObj::ms_newSymbolObj' => ['int', 'map'=>'mapObj', 'symbolname'=>'string'],
'symbolObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'symbolObj::setImagePath' => ['int', 'filename'=>'string'],
'symbolObj::setPattern' => ['int', 'int'=>'array'],
'symbolObj::setPoints' => ['int', 'double'=>'array'],
'symlink' => ['bool', 'target'=>'string', 'link'=>'string'],
'SyncEvent::__construct' => ['void', 'name='=>'string', 'manual='=>'bool'],
'SyncEvent::fire' => ['bool'],
'SyncEvent::reset' => ['bool'],
'SyncEvent::wait' => ['bool', 'wait='=>'int'],
'SyncMutex::__construct' => ['void', 'name='=>'string'],
'SyncMutex::lock' => ['bool', 'wait='=>'int'],
'SyncMutex::unlock' => ['bool', 'all='=>'bool'],
'SyncReaderWriter::__construct' => ['void', 'name='=>'string', 'autounlock='=>'bool'],
'SyncReaderWriter::readlock' => ['bool', 'wait='=>'int'],
'SyncReaderWriter::readunlock' => ['bool'],
'SyncReaderWriter::writelock' => ['bool', 'wait='=>'int'],
'SyncReaderWriter::writeunlock' => ['bool'],
'SyncSemaphore::__construct' => ['void', 'name='=>'string', 'initialval='=>'int', 'autounlock='=>'bool'],
'SyncSemaphore::lock' => ['bool', 'wait='=>'int'],
'SyncSemaphore::unlock' => ['bool', '&w_prevcount='=>'int'],
'SyncSharedMemory::__construct' => ['void', 'name'=>'string', 'size'=>'int'],
'SyncSharedMemory::first' => ['bool'],
'SyncSharedMemory::read' => ['string', 'start='=>'int', 'length='=>'int'],
'SyncSharedMemory::size' => ['int'],
'SyncSharedMemory::write' => ['int', 'string='=>'string', 'start='=>'int'],
'sys_get_temp_dir' => ['string'],
'sys_getloadavg' => ['array'],
'syslog' => ['bool', 'priority'=>'int', 'message'=>'string'],
'system' => ['string|false', 'command'=>'string', '&w_result_code='=>'int'],
'taint' => ['bool', '&rw_string'=>'string', '&...w_other_strings='=>'string'],
'tan' => ['float', 'num'=>'float'],
'tanh' => ['float', 'num'=>'float'],
'tcpwrap_check' => ['bool', 'daemon'=>'string', 'address'=>'string', 'user='=>'string', 'nodns='=>'bool'],
'tempnam' => ['string|false', 'directory'=>'string', 'prefix'=>'string'],
'textdomain' => ['string', 'domain'=>'string'],
'Thread::__construct' => ['void'],
'Thread::addRef' => ['void'],
'Thread::chunk' => ['array', 'size'=>'int', 'preserve'=>'bool'],
'Thread::count' => ['int'],
'Thread::delRef' => ['void'],
'Thread::detach' => ['void'],
'Thread::extend' => ['bool', 'class'=>'string'],
'Thread::getCreatorId' => ['int'],
'Thread::getCurrentThread' => ['Thread'],
'Thread::getCurrentThreadId' => ['int'],
'Thread::getRefCount' => ['int'],
'Thread::getTerminationInfo' => ['array'],
'Thread::getThreadId' => ['int'],
'Thread::globally' => ['mixed'],
'Thread::isGarbage' => ['bool'],
'Thread::isJoined' => ['bool'],
'Thread::isRunning' => ['bool'],
'Thread::isStarted' => ['bool'],
'Thread::isTerminated' => ['bool'],
'Thread::isWaiting' => ['bool'],
'Thread::join' => ['bool'],
'Thread::kill' => ['void'],
'Thread::lock' => ['bool'],
'Thread::merge' => ['bool', 'from'=>'', 'overwrite='=>'mixed'],
'Thread::notify' => ['bool'],
'Thread::notifyOne' => ['bool'],
'Thread::offsetExists' => ['bool', 'offset'=>'mixed'],
'Thread::offsetGet' => ['mixed', 'offset'=>'mixed'],
'Thread::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'Thread::offsetUnset' => ['void', 'offset'=>'mixed'],
'Thread::pop' => ['bool'],
'Thread::run' => ['void'],
'Thread::setGarbage' => ['void'],
'Thread::shift' => ['bool'],
'Thread::start' => ['bool', 'options='=>'int'],
'Thread::synchronized' => ['mixed', 'block'=>'Closure', '_='=>'mixed'],
'Thread::unlock' => ['bool'],
'Thread::wait' => ['bool', 'timeout='=>'int'],
'Threaded::__construct' => ['void'],
'Threaded::addRef' => ['void'],
'Threaded::chunk' => ['array', 'size'=>'int', 'preserve'=>'bool'],
'Threaded::count' => ['int'],
'Threaded::delRef' => ['void'],
'Threaded::extend' => ['bool', 'class'=>'string'],
'Threaded::from' => ['Threaded', 'run'=>'Closure', 'construct='=>'Closure', 'args='=>'array'],
'Threaded::getRefCount' => ['int'],
'Threaded::getTerminationInfo' => ['array'],
'Threaded::isGarbage' => ['bool'],
'Threaded::isRunning' => ['bool'],
'Threaded::isTerminated' => ['bool'],
'Threaded::isWaiting' => ['bool'],
'Threaded::lock' => ['bool'],
'Threaded::merge' => ['bool', 'from'=>'mixed', 'overwrite='=>'bool'],
'Threaded::notify' => ['bool'],
'Threaded::notifyOne' => ['bool'],
'Threaded::offsetExists' => ['bool', 'offset'=>'mixed'],
'Threaded::offsetGet' => ['mixed', 'offset'=>'mixed'],
'Threaded::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'Threaded::offsetUnset' => ['void', 'offset'=>'mixed'],
'Threaded::pop' => ['bool'],
'Threaded::run' => ['void'],
'Threaded::setGarbage' => ['void'],
'Threaded::shift' => ['mixed'],
'Threaded::synchronized' => ['mixed', 'block'=>'Closure', '...args='=>'mixed'],
'Threaded::unlock' => ['bool'],
'Threaded::wait' => ['bool', 'timeout='=>'int'],
'Throwable::__toString' => ['string'],
'Throwable::getCode' => ['int|string'],
'Throwable::getFile' => ['string'],
'Throwable::getLine' => ['int'],
'Throwable::getMessage' => ['string'],
'Throwable::getPrevious' => ['?Throwable'],
'Throwable::getTrace' => ['list<array<string,mixed>>'],
'Throwable::getTraceAsString' => ['string'],
'tidy::__construct' => ['void', 'filename='=>'string', 'config='=>'', 'encoding='=>'string', 'useIncludePath='=>'bool'],
'tidy::body' => ['tidyNode'],
'tidy::cleanRepair' => ['bool'],
'tidy::diagnose' => ['bool'],
'tidy::getConfig' => ['array'],
'tidy::getHtmlVer' => ['int'],
'tidy::getOpt' => ['mixed', 'option'=>'string'],
'tidy::getOptDoc' => ['string', 'option'=>'string'],
'tidy::getRelease' => ['string'],
'tidy::getStatus' => ['int'],
'tidy::head' => ['tidyNode'],
'tidy::html' => ['tidyNode'],
'tidy::htmlver' => ['int'],
'tidy::isXhtml' => ['bool'],
'tidy::isXml' => ['bool'],
'tidy::parseFile' => ['bool', 'filename'=>'string', 'config='=>'', 'encoding='=>'string', 'useIncludePath='=>'bool'],
'tidy::parseString' => ['bool', 'string'=>'string', 'config='=>'', 'encoding='=>'string'],
'tidy::repairFile' => ['string', 'filename'=>'string', 'config='=>'', 'encoding='=>'string', 'useIncludePath='=>'bool'],
'tidy::repairString' => ['string', 'string'=>'string', 'config='=>'', 'encoding='=>'string'],
'tidy::root' => ['tidyNode'],
'tidy_access_count' => ['int', 'tidy'=>'tidy'],
'tidy_clean_repair' => ['bool', 'tidy'=>'tidy'],
'tidy_config_count' => ['int', 'tidy'=>'tidy'],
'tidy_diagnose' => ['bool', 'tidy'=>'tidy'],
'tidy_error_count' => ['int', 'tidy'=>'tidy'],
'tidy_get_body' => ['tidyNode', 'tidy'=>'tidy'],
'tidy_get_config' => ['array', 'tidy'=>'tidy'],
'tidy_get_error_buffer' => ['string', 'tidy'=>'tidy'],
'tidy_get_head' => ['tidyNode', 'tidy'=>'tidy'],
'tidy_get_html' => ['tidyNode', 'tidy'=>'tidy'],
'tidy_get_html_ver' => ['int', 'tidy'=>'tidy'],
'tidy_get_opt_doc' => ['string', 'tidy'=>'tidy', 'option'=>'string'],
'tidy_get_output' => ['string', 'tidy'=>'tidy'],
'tidy_get_release' => ['string'],
'tidy_get_root' => ['tidyNode', 'tidy'=>'tidy'],
'tidy_get_status' => ['int', 'tidy'=>'tidy'],
'tidy_getopt' => ['mixed', 'tidy'=>'string', 'option'=>'tidy'],
'tidy_is_xhtml' => ['bool', 'tidy'=>'tidy'],
'tidy_is_xml' => ['bool', 'tidy'=>'tidy'],
'tidy_load_config' => ['void', 'filename'=>'string', 'encoding'=>'string'],
'tidy_parse_file' => ['tidy', 'filename'=>'string', 'config='=>'', 'encoding='=>'string', 'useIncludePath='=>'bool'],
'tidy_parse_string' => ['tidy', 'string'=>'string', 'config='=>'', 'encoding='=>'string'],
'tidy_repair_file' => ['string', 'filename'=>'string', 'config='=>'', 'encoding='=>'string', 'useIncludePath='=>'bool'],
'tidy_repair_string' => ['string', 'string'=>'string', 'config='=>'', 'encoding='=>'string'],
'tidy_reset_config' => ['bool'],
'tidy_save_config' => ['bool', 'filename'=>'string'],
'tidy_set_encoding' => ['bool', 'encoding'=>'string'],
'tidy_setopt' => ['bool', 'option'=>'string', 'value'=>'mixed'],
'tidy_warning_count' => ['int', 'tidy'=>'tidy'],
'tidyNode::__construct' => ['void'],
'tidyNode::getParent' => ['tidyNode'],
'tidyNode::hasChildren' => ['bool'],
'tidyNode::hasSiblings' => ['bool'],
'tidyNode::isAsp' => ['bool'],
'tidyNode::isComment' => ['bool'],
'tidyNode::isHtml' => ['bool'],
'tidyNode::isJste' => ['bool'],
'tidyNode::isPhp' => ['bool'],
'tidyNode::isText' => ['bool'],
'time' => ['positive-int'],
'time_nanosleep' => ['array{0:0|positive-int,1:0|positive-int}|bool', 'seconds'=>'positive-int', 'nanoseconds'=>'positive-int'],
'time_sleep_until' => ['bool', 'timestamp'=>'float'],
'timezone_abbreviations_list' => ['array<string, list<array{dst: bool, offset: int, timezone_id: string|null}>>|false'],
'timezone_identifiers_list' => ['list<string>', 'timezoneGroup='=>'int', 'countryCode='=>'?string'],
'timezone_location_get' => ['array|false', 'object'=>'DateTimeZone'],
'timezone_name_from_abbr' => ['string|false', 'abbr'=>'string', 'utcOffset='=>'int', 'isDST='=>'int'],
'timezone_name_get' => ['string', 'object'=>'DateTimeZone'],
'timezone_offset_get' => ['int|false', 'object'=>'DateTimeZone', 'datetime'=>'DateTimeInterface'],
'timezone_open' => ['DateTimeZone|false', 'timezone'=>'string'],
'timezone_transitions_get' => ['list<array{ts: int, time: string, offset: int, isdst: bool, abbr: string}>|false', 'object'=>'DateTimeZone', 'timestampBegin='=>'int', 'timestampEnd='=>'int'],
'timezone_version_get' => ['string'],
'tmpfile' => ['resource|false'],
'token_get_all' => ['list<string|array{0:int,1:string,2:int}>', 'code'=>'string', 'flags='=>'int'],
'token_name' => ['string', 'id'=>'int'],
'TokyoTyrant::__construct' => ['void', 'host='=>'string', 'port='=>'int', 'options='=>'array'],
'TokyoTyrant::add' => ['int|float', 'key'=>'string', 'increment'=>'float', 'type='=>'int'],
'TokyoTyrant::connect' => ['TokyoTyrant', 'host'=>'string', 'port='=>'int', 'options='=>'array'],
'TokyoTyrant::connectUri' => ['TokyoTyrant', 'uri'=>'string'],
'TokyoTyrant::copy' => ['TokyoTyrant', 'path'=>'string'],
'TokyoTyrant::ext' => ['string', 'name'=>'string', 'options'=>'int', 'key'=>'string', 'value'=>'string'],
'TokyoTyrant::fwmKeys' => ['array', 'prefix'=>'string', 'max_recs'=>'int'],
'TokyoTyrant::get' => ['array', 'keys'=>'mixed'],
'TokyoTyrant::getIterator' => ['TokyoTyrantIterator'],
'TokyoTyrant::num' => ['int'],
'TokyoTyrant::out' => ['string', 'keys'=>'mixed'],
'TokyoTyrant::put' => ['TokyoTyrant', 'keys'=>'mixed', 'value='=>'string'],
'TokyoTyrant::putCat' => ['TokyoTyrant', 'keys'=>'mixed', 'value='=>'string'],
'TokyoTyrant::putKeep' => ['TokyoTyrant', 'keys'=>'mixed', 'value='=>'string'],
'TokyoTyrant::putNr' => ['TokyoTyrant', 'keys'=>'mixed', 'value='=>'string'],
'TokyoTyrant::putShl' => ['mixed', 'key'=>'string', 'value'=>'string', 'width'=>'int'],
'TokyoTyrant::restore' => ['mixed', 'log_dir'=>'string', 'timestamp'=>'int', 'check_consistency='=>'bool'],
'TokyoTyrant::setMaster' => ['mixed', 'host'=>'string', 'port'=>'int', 'timestamp'=>'int', 'check_consistency='=>'bool'],
'TokyoTyrant::size' => ['int', 'key'=>'string'],
'TokyoTyrant::stat' => ['array'],
'TokyoTyrant::sync' => ['mixed'],
'TokyoTyrant::tune' => ['TokyoTyrant', 'timeout'=>'float', 'options='=>'int'],
'TokyoTyrant::vanish' => ['mixed'],
'TokyoTyrantIterator::__construct' => ['void', 'object'=>'mixed'],
'TokyoTyrantIterator::current' => ['mixed'],
'TokyoTyrantIterator::key' => ['mixed'],
'TokyoTyrantIterator::next' => ['mixed'],
'TokyoTyrantIterator::rewind' => ['void'],
'TokyoTyrantIterator::valid' => ['bool'],
'TokyoTyrantQuery::__construct' => ['void', 'table'=>'TokyoTyrantTable'],
'TokyoTyrantQuery::addCond' => ['mixed', 'name'=>'string', 'op'=>'int', 'expr'=>'string'],
'TokyoTyrantQuery::count' => ['int'],
'TokyoTyrantQuery::current' => ['array'],
'TokyoTyrantQuery::hint' => ['string'],
'TokyoTyrantQuery::key' => ['string'],
'TokyoTyrantQuery::metaSearch' => ['array', 'queries'=>'array', 'type'=>'int'],
'TokyoTyrantQuery::next' => ['array'],
'TokyoTyrantQuery::out' => ['TokyoTyrantQuery'],
'TokyoTyrantQuery::rewind' => ['bool'],
'TokyoTyrantQuery::search' => ['array'],
'TokyoTyrantQuery::setLimit' => ['mixed', 'max='=>'int', 'skip='=>'int'],
'TokyoTyrantQuery::setOrder' => ['mixed', 'name'=>'string', 'type'=>'int'],
'TokyoTyrantQuery::valid' => ['bool'],
'TokyoTyrantTable::add' => ['void', 'key'=>'string', 'increment'=>'mixed', 'type='=>'string'],
'TokyoTyrantTable::genUid' => ['int'],
'TokyoTyrantTable::get' => ['array', 'keys'=>'mixed'],
'TokyoTyrantTable::getIterator' => ['TokyoTyrantIterator'],
'TokyoTyrantTable::getQuery' => ['TokyoTyrantQuery'],
'TokyoTyrantTable::out' => ['void', 'keys'=>'mixed'],
'TokyoTyrantTable::put' => ['int', 'key'=>'string', 'columns'=>'array'],
'TokyoTyrantTable::putCat' => ['void', 'key'=>'string', 'columns'=>'array'],
'TokyoTyrantTable::putKeep' => ['void', 'key'=>'string', 'columns'=>'array'],
'TokyoTyrantTable::putNr' => ['void', 'keys'=>'mixed', 'value='=>'string'],
'TokyoTyrantTable::putShl' => ['void', 'key'=>'string', 'value'=>'string', 'width'=>'int'],
'TokyoTyrantTable::setIndex' => ['mixed', 'column'=>'string', 'type'=>'int'],
'touch' => ['bool', 'filename'=>'string', 'mtime='=>'int', 'atime='=>'int'],
'trader_acos' => ['array', 'real'=>'array'],
'trader_ad' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'volume'=>'array'],
'trader_add' => ['array', 'real0'=>'array', 'real1'=>'array'],
'trader_adosc' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'volume'=>'array', 'fastPeriod='=>'int', 'slowPeriod='=>'int'],
'trader_adx' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_adxr' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_apo' => ['array', 'real'=>'array', 'fastPeriod='=>'int', 'slowPeriod='=>'int', 'mAType='=>'int'],
'trader_aroon' => ['array', 'high'=>'array', 'low'=>'array', 'timePeriod='=>'int'],
'trader_aroonosc' => ['array', 'high'=>'array', 'low'=>'array', 'timePeriod='=>'int'],
'trader_asin' => ['array', 'real'=>'array'],
'trader_atan' => ['array', 'real'=>'array'],
'trader_atr' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_avgprice' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_bbands' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'nbDevUp='=>'float', 'nbDevDn='=>'float', 'mAType='=>'int'],
'trader_beta' => ['array', 'real0'=>'array', 'real1'=>'array', 'timePeriod='=>'int'],
'trader_bop' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cci' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_cdl2crows' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3blackcrows' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3inside' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3linestrike' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3outside' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3starsinsouth' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3whitesoldiers' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlabandonedbaby' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdladvanceblock' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlbelthold' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlbreakaway' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlclosingmarubozu' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlconcealbabyswall' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlcounterattack' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdldarkcloudcover' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdldoji' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdldojistar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdldragonflydoji' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlengulfing' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdleveningdojistar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdleveningstar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdlgapsidesidewhite' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlgravestonedoji' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhammer' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhangingman' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlharami' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlharamicross' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhighwave' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhikkake' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhikkakemod' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhomingpigeon' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlidentical3crows' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlinneck' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlinvertedhammer' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlkicking' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlkickingbylength' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlladderbottom' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdllongleggeddoji' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdllongline' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlmarubozu' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlmatchinglow' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlmathold' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdlmorningdojistar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdlmorningstar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdlonneck' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlpiercing' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlrickshawman' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlrisefall3methods' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlseparatinglines' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlshootingstar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlshortline' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlspinningtop' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlstalledpattern' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlsticksandwich' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdltakuri' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdltasukigap' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlthrusting' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdltristar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlunique3river' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlupsidegap2crows' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlxsidegap3methods' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_ceil' => ['array', 'real'=>'array'],
'trader_cmo' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_correl' => ['array', 'real0'=>'array', 'real1'=>'array', 'timePeriod='=>'int'],
'trader_cos' => ['array', 'real'=>'array'],
'trader_cosh' => ['array', 'real'=>'array'],
'trader_dema' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_div' => ['array', 'real0'=>'array', 'real1'=>'array'],
'trader_dx' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_ema' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_errno' => ['int'],
'trader_exp' => ['array', 'real'=>'array'],
'trader_floor' => ['array', 'real'=>'array'],
'trader_get_compat' => ['int'],
'trader_get_unstable_period' => ['int', 'functionId'=>'int'],
'trader_ht_dcperiod' => ['array', 'real'=>'array'],
'trader_ht_dcphase' => ['array', 'real'=>'array'],
'trader_ht_phasor' => ['array', 'real'=>'array'],
'trader_ht_sine' => ['array', 'real'=>'array'],
'trader_ht_trendline' => ['array', 'real'=>'array'],
'trader_ht_trendmode' => ['array', 'real'=>'array'],
'trader_kama' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_linearreg' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_linearreg_angle' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_linearreg_intercept' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_linearreg_slope' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_ln' => ['array', 'real'=>'array'],
'trader_log10' => ['array', 'real'=>'array'],
'trader_ma' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'mAType='=>'int'],
'trader_macd' => ['array', 'real'=>'array', 'fastPeriod='=>'int', 'slowPeriod='=>'int', 'signalPeriod='=>'int'],
'trader_macdext' => ['array', 'real'=>'array', 'fastPeriod='=>'int', 'fastMAType='=>'int', 'slowPeriod='=>'int', 'slowMAType='=>'int', 'signalPeriod='=>'int', 'signalMAType='=>'int'],
'trader_macdfix' => ['array', 'real'=>'array', 'signalPeriod='=>'int'],
'trader_mama' => ['array', 'real'=>'array', 'fastLimit='=>'float', 'slowLimit='=>'float'],
'trader_mavp' => ['array', 'real'=>'array', 'periods'=>'array', 'minPeriod='=>'int', 'maxPeriod='=>'int', 'mAType='=>'int'],
'trader_max' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_maxindex' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_medprice' => ['array', 'high'=>'array', 'low'=>'array'],
'trader_mfi' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'volume'=>'array', 'timePeriod='=>'int'],
'trader_midpoint' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_midprice' => ['array', 'high'=>'array', 'low'=>'array', 'timePeriod='=>'int'],
'trader_min' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_minindex' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_minmax' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_minmaxindex' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_minus_di' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_minus_dm' => ['array', 'high'=>'array', 'low'=>'array', 'timePeriod='=>'int'],
'trader_mom' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_mult' => ['array', 'real0'=>'array', 'real1'=>'array'],
'trader_natr' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_obv' => ['array', 'real'=>'array', 'volume'=>'array'],
'trader_plus_di' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_plus_dm' => ['array', 'high'=>'array', 'low'=>'array', 'timePeriod='=>'int'],
'trader_ppo' => ['array', 'real'=>'array', 'fastPeriod='=>'int', 'slowPeriod='=>'int', 'mAType='=>'int'],
'trader_roc' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_rocp' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_rocr' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_rocr100' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_rsi' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_sar' => ['array', 'high'=>'array', 'low'=>'array', 'acceleration='=>'float', 'maximum='=>'float'],
'trader_sarext' => ['array', 'high'=>'array', 'low'=>'array', 'startValue='=>'float', 'offsetOnReverse='=>'float', 'accelerationInitLong='=>'float', 'accelerationLong='=>'float', 'accelerationMaxLong='=>'float', 'accelerationInitShort='=>'float', 'accelerationShort='=>'float', 'accelerationMaxShort='=>'float'],
'trader_set_compat' => ['void', 'compatId'=>'int'],
'trader_set_unstable_period' => ['void', 'functionId'=>'int', 'timePeriod'=>'int'],
'trader_sin' => ['array', 'real'=>'array'],
'trader_sinh' => ['array', 'real'=>'array'],
'trader_sma' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_sqrt' => ['array', 'real'=>'array'],
'trader_stddev' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'nbDev='=>'float'],
'trader_stoch' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'fastK_Period='=>'int', 'slowK_Period='=>'int', 'slowK_MAType='=>'int', 'slowD_Period='=>'int', 'slowD_MAType='=>'int'],
'trader_stochf' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'fastK_Period='=>'int', 'fastD_Period='=>'int', 'fastD_MAType='=>'int'],
'trader_stochrsi' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'fastK_Period='=>'int', 'fastD_Period='=>'int', 'fastD_MAType='=>'int'],
'trader_sub' => ['array', 'real0'=>'array', 'real1'=>'array'],
'trader_sum' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_t3' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'vFactor='=>'float'],
'trader_tan' => ['array', 'real'=>'array'],
'trader_tanh' => ['array', 'real'=>'array'],
'trader_tema' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_trange' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_trima' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_trix' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_tsf' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_typprice' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_ultosc' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod1='=>'int', 'timePeriod2='=>'int', 'timePeriod3='=>'int'],
'trader_var' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'nbDev='=>'float'],
'trader_wclprice' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_willr' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_wma' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trait_exists' => ['?bool', 'trait'=>'string', 'autoload='=>'bool'],
'Transliterator::create' => ['?Transliterator', 'id'=>'string', 'direction='=>'int'],
'Transliterator::createFromRules' => ['?Transliterator', 'rules'=>'string', 'direction='=>'int'],
'Transliterator::createInverse' => ['Transliterator'],
'Transliterator::getErrorCode' => ['int'],
'Transliterator::getErrorMessage' => ['string'],
'Transliterator::listIDs' => ['array'],
'Transliterator::transliterate' => ['string|false', 'subject'=>'string', 'start='=>'int', 'end='=>'int'],
'transliterator_create' => ['?Transliterator', 'id'=>'string', 'direction='=>'int'],
'transliterator_create_from_rules' => ['?Transliterator', 'rules'=>'string', 'direction='=>'int'],
'transliterator_create_inverse' => ['Transliterator', 'transliterator'=>'Transliterator'],
'transliterator_get_error_code' => ['int', 'transliterator'=>'Transliterator'],
'transliterator_get_error_message' => ['string', 'transliterator'=>'Transliterator'],
'transliterator_list_ids' => ['array'],
'transliterator_transliterate' => ['string|false', 'transliterator'=>'Transliterator|string', 'string'=>'string', 'start='=>'int', 'end='=>'int'],
'trigger_error' => ['bool', 'message'=>'string', 'error_level='=>'256|512|1024|16384'],
'trim' => ['string', 'string'=>'string', 'characters='=>'string'],
'TypeError::__clone' => ['void'],
'TypeError::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?TypeError'],
'TypeError::__toString' => ['string'],
'TypeError::getCode' => ['int'],
'TypeError::getFile' => ['string'],
'TypeError::getLine' => ['int'],
'TypeError::getMessage' => ['string'],
'TypeError::getPrevious' => ['Throwable|TypeError|null'],
'TypeError::getTrace' => ['list<array<string,mixed>>'],
'TypeError::getTraceAsString' => ['string'],
'uasort' => ['bool', '&rw_array'=>'array', 'callback'=>'callable(mixed,mixed):int'],
'ucfirst' => ['string', 'string'=>'string'],
'UConverter::__construct' => ['void', 'destination_encoding='=>'string', 'source_encoding='=>'string'],
'UConverter::convert' => ['string', 'string'=>'string', 'reverse='=>'bool'],
'UConverter::fromUCallback' => ['mixed', 'reason'=>'int', 'source'=>'string', 'codePoint'=>'string', '&w_error'=>'int'],
'UConverter::getAliases' => ['array', 'name'=>'string'],
'UConverter::getAvailable' => ['array'],
'UConverter::getDestinationEncoding' => ['string'],
'UConverter::getDestinationType' => ['int'],
'UConverter::getErrorCode' => ['int'],
'UConverter::getErrorMessage' => ['string'],
'UConverter::getSourceEncoding' => ['string'],
'UConverter::getSourceType' => ['int'],
'UConverter::getStandards' => ['array'],
'UConverter::getSubstChars' => ['string'],
'UConverter::reasonText' => ['string', 'reason='=>'int'],
'UConverter::setDestinationEncoding' => ['bool', 'encoding'=>'string'],
'UConverter::setSourceEncoding' => ['bool', 'encoding'=>'string'],
'UConverter::setSubstChars' => ['bool', 'chars'=>'string'],
'UConverter::toUCallback' => ['mixed', 'reason'=>'int', 'source'=>'string', 'codeUnits'=>'string', '&w_error'=>'int'],
'UConverter::transcode' => ['string', 'string'=>'string', 'toEncoding'=>'string', 'fromEncoding'=>'string', 'options='=>'?array'],
'ucwords' => ['string', 'string'=>'string', 'separators='=>'string'],
'udm_add_search_limit' => ['bool', 'agent'=>'resource', 'var'=>'int', 'value'=>'string'],
'udm_alloc_agent' => ['resource', 'dbaddr'=>'string', 'dbmode='=>'string'],
'udm_alloc_agent_array' => ['resource', 'databases'=>'array'],
'udm_api_version' => ['int'],
'udm_cat_list' => ['array', 'agent'=>'resource', 'category'=>'string'],
'udm_cat_path' => ['array', 'agent'=>'resource', 'category'=>'string'],
'udm_check_charset' => ['bool', 'agent'=>'resource', 'charset'=>'string'],
'udm_check_stored' => ['int', 'agent'=>'', 'link'=>'int', 'doc_id'=>'string'],
'udm_clear_search_limits' => ['bool', 'agent'=>'resource'],
'udm_close_stored' => ['int', 'agent'=>'', 'link'=>'int'],
'udm_crc32' => ['int', 'agent'=>'resource', 'string'=>'string'],
'udm_errno' => ['int', 'agent'=>'resource'],
'udm_error' => ['string', 'agent'=>'resource'],
'udm_find' => ['resource', 'agent'=>'resource', 'query'=>'string'],
'udm_free_agent' => ['int', 'agent'=>'resource'],
'udm_free_ispell_data' => ['bool', 'agent'=>'int'],
'udm_free_res' => ['bool', 'res'=>'resource'],
'udm_get_doc_count' => ['int', 'agent'=>'resource'],
'udm_get_res_field' => ['string', 'res'=>'resource', 'row'=>'int', 'field'=>'int'],
'udm_get_res_param' => ['string', 'res'=>'resource', 'param'=>'int'],
'udm_hash32' => ['int', 'agent'=>'resource', 'string'=>'string'],
'udm_load_ispell_data' => ['bool', 'agent'=>'resource', 'var'=>'int', 'val1'=>'string', 'val2'=>'string', 'flag'=>'int'],
'udm_open_stored' => ['int', 'agent'=>'', 'storedaddr'=>'string'],
'udm_set_agent_param' => ['bool', 'agent'=>'resource', 'var'=>'int', 'val'=>'string'],
'ui\area::onDraw' => ['', 'pen'=>'UI\Draw\Pen', 'areaSize'=>'UI\Size', 'clipPoint'=>'UI\Point', 'clipSize'=>'UI\Size'],
'ui\area::onKey' => ['', 'key'=>'string', 'ext'=>'int', 'flags'=>'int'],
'ui\area::onMouse' => ['', 'areaPoint'=>'UI\Point', 'areaSize'=>'UI\Size', 'flags'=>'int'],
'ui\area::redraw' => [''],
'ui\area::scrollTo' => ['', 'point'=>'UI\Point', 'size'=>'UI\Size'],
'ui\area::setSize' => ['', 'size'=>'UI\Size'],
'ui\control::destroy' => [''],
'ui\control::disable' => [''],
'ui\control::enable' => [''],
'ui\control::getParent' => ['UI\Control'],
'ui\control::getTopLevel' => ['int'],
'ui\control::hide' => [''],
'ui\control::isEnabled' => ['bool'],
'ui\control::isVisible' => ['bool'],
'ui\control::setParent' => ['', 'parent'=>'UI\Control'],
'ui\control::show' => [''],
'ui\controls\box::append' => ['int', 'control'=>'Control', 'stretchy='=>'bool'],
'ui\controls\box::delete' => ['bool', 'index'=>'int'],
'ui\controls\box::getOrientation' => ['int'],
'ui\controls\box::isPadded' => ['bool'],
'ui\controls\box::setPadded' => ['', 'padded'=>'bool'],
'ui\controls\button::getText' => ['string'],
'ui\controls\button::onClick' => [''],
'ui\controls\button::setText' => ['', 'text'=>'string'],
'ui\controls\check::getText' => ['string'],
'ui\controls\check::isChecked' => ['bool'],
'ui\controls\check::onToggle' => [''],
'ui\controls\check::setChecked' => ['', 'checked'=>'bool'],
'ui\controls\check::setText' => ['', 'text'=>'string'],
'ui\controls\colorbutton::getColor' => ['UI\Color'],
'ui\controls\colorbutton::onChange' => [''],
'ui\controls\combo::append' => ['', 'text'=>'string'],
'ui\controls\combo::getSelected' => ['int'],
'ui\controls\combo::onSelected' => [''],
'ui\controls\combo::setSelected' => ['', 'index'=>'int'],
'ui\controls\editablecombo::append' => ['', 'text'=>'string'],
'ui\controls\editablecombo::getText' => ['string'],
'ui\controls\editablecombo::onChange' => [''],
'ui\controls\editablecombo::setText' => ['', 'text'=>'string'],
'ui\controls\entry::getText' => ['string'],
'ui\controls\entry::isReadOnly' => ['bool'],
'ui\controls\entry::onChange' => [''],
'ui\controls\entry::setReadOnly' => ['', 'readOnly'=>'bool'],
'ui\controls\entry::setText' => ['', 'text'=>'string'],
'ui\controls\form::append' => ['int', 'label'=>'string', 'control'=>'UI\Control', 'stretchy='=>'bool'],
'ui\controls\form::delete' => ['bool', 'index'=>'int'],
'ui\controls\form::isPadded' => ['bool'],
'ui\controls\form::setPadded' => ['', 'padded'=>'bool'],
'ui\controls\grid::append' => ['', 'control'=>'UI\Control', 'left'=>'int', 'top'=>'int', 'xspan'=>'int', 'yspan'=>'int', 'hexpand'=>'bool', 'halign'=>'int', 'vexpand'=>'bool', 'valign'=>'int'],
'ui\controls\grid::isPadded' => ['bool'],
'ui\controls\grid::setPadded' => ['', 'padding'=>'bool'],
'ui\controls\group::append' => ['', 'control'=>'UI\Control'],
'ui\controls\group::getTitle' => ['string'],
'ui\controls\group::hasMargin' => ['bool'],
'ui\controls\group::setMargin' => ['', 'margin'=>'bool'],
'ui\controls\group::setTitle' => ['', 'title'=>'string'],
'ui\controls\label::getText' => ['string'],
'ui\controls\label::setText' => ['', 'text'=>'string'],
'ui\controls\multilineentry::append' => ['', 'text'=>'string'],
'ui\controls\multilineentry::getText' => ['string'],
'ui\controls\multilineentry::isReadOnly' => ['bool'],
'ui\controls\multilineentry::onChange' => [''],
'ui\controls\multilineentry::setReadOnly' => ['', 'readOnly'=>'bool'],
'ui\controls\multilineentry::setText' => ['', 'text'=>'string'],
'ui\controls\progress::getValue' => ['int'],
'ui\controls\progress::setValue' => ['', 'value'=>'int'],
'ui\controls\radio::append' => ['', 'text'=>'string'],
'ui\controls\radio::getSelected' => ['int'],
'ui\controls\radio::onSelected' => [''],
'ui\controls\radio::setSelected' => ['', 'index'=>'int'],
'ui\controls\slider::getValue' => ['int'],
'ui\controls\slider::onChange' => [''],
'ui\controls\slider::setValue' => ['', 'value'=>'int'],
'ui\controls\spin::getValue' => ['int'],
'ui\controls\spin::onChange' => [''],
'ui\controls\spin::setValue' => ['', 'value'=>'int'],
'ui\controls\tab::append' => ['int', 'name'=>'string', 'control'=>'UI\Control'],
'ui\controls\tab::delete' => ['bool', 'index'=>'int'],
'ui\controls\tab::hasMargin' => ['bool', 'page'=>'int'],
'ui\controls\tab::insertAt' => ['', 'name'=>'string', 'page'=>'int', 'control'=>'UI\Control'],
'ui\controls\tab::pages' => ['int'],
'ui\controls\tab::setMargin' => ['', 'page'=>'int', 'margin'=>'bool'],
'ui\draw\brush::getColor' => ['UI\Draw\Color'],
'ui\draw\brush\gradient::delStop' => ['int', 'index'=>'int'],
'ui\draw\color::getChannel' => ['float', 'channel'=>'int'],
'ui\draw\color::setChannel' => ['void', 'channel'=>'int', 'value'=>'float'],
'ui\draw\matrix::invert' => [''],
'ui\draw\matrix::isInvertible' => ['bool'],
'ui\draw\matrix::multiply' => ['UI\Draw\Matrix', 'matrix'=>'UI\Draw\Matrix'],
'ui\draw\matrix::rotate' => ['', 'point'=>'UI\Point', 'amount'=>'float'],
'ui\draw\matrix::scale' => ['', 'center'=>'UI\Point', 'point'=>'UI\Point'],
'ui\draw\matrix::skew' => ['', 'point'=>'UI\Point', 'amount'=>'UI\Point'],
'ui\draw\matrix::translate' => ['', 'point'=>'UI\Point'],
'ui\draw\path::addRectangle' => ['', 'point'=>'UI\Point', 'size'=>'UI\Size'],
'ui\draw\path::arcTo' => ['', 'point'=>'UI\Point', 'radius'=>'float', 'angle'=>'float', 'sweep'=>'float', 'negative'=>'float'],
'ui\draw\path::bezierTo' => ['', 'point'=>'UI\Point', 'radius'=>'float', 'angle'=>'float', 'sweep'=>'float', 'negative'=>'float'],
'ui\draw\path::closeFigure' => [''],
'ui\draw\path::end' => [''],
'ui\draw\path::lineTo' => ['', 'point'=>'UI\Point', 'radius'=>'float', 'angle'=>'float', 'sweep'=>'float', 'negative'=>'float'],
'ui\draw\path::newFigure' => ['', 'point'=>'UI\Point'],
'ui\draw\path::newFigureWithArc' => ['', 'point'=>'UI\Point', 'radius'=>'float', 'angle'=>'float', 'sweep'=>'float', 'negative'=>'float'],
'ui\draw\pen::clip' => ['', 'path'=>'UI\Draw\Path'],
'ui\draw\pen::restore' => [''],
'ui\draw\pen::save' => [''],
'ui\draw\pen::transform' => ['', 'matrix'=>'UI\Draw\Matrix'],
'ui\draw\pen::write' => ['', 'point'=>'UI\Point', 'layout'=>'UI\Draw\Text\Layout'],
'ui\draw\stroke::getCap' => ['int'],
'ui\draw\stroke::getJoin' => ['int'],
'ui\draw\stroke::getMiterLimit' => ['float'],
'ui\draw\stroke::getThickness' => ['float'],
'ui\draw\stroke::setCap' => ['', 'cap'=>'int'],
'ui\draw\stroke::setJoin' => ['', 'join'=>'int'],
'ui\draw\stroke::setMiterLimit' => ['', 'limit'=>'float'],
'ui\draw\stroke::setThickness' => ['', 'thickness'=>'float'],
'ui\draw\text\font::getAscent' => ['float'],
'ui\draw\text\font::getDescent' => ['float'],
'ui\draw\text\font::getLeading' => ['float'],
'ui\draw\text\font::getUnderlinePosition' => ['float'],
'ui\draw\text\font::getUnderlineThickness' => ['float'],
'ui\draw\text\font\descriptor::getFamily' => ['string'],
'ui\draw\text\font\descriptor::getItalic' => ['int'],
'ui\draw\text\font\descriptor::getSize' => ['float'],
'ui\draw\text\font\descriptor::getStretch' => ['int'],
'ui\draw\text\font\descriptor::getWeight' => ['int'],
'ui\draw\text\font\fontfamilies' => ['array'],
'ui\draw\text\layout::setWidth' => ['', 'width'=>'float'],
'ui\executor::kill' => ['void'],
'ui\executor::onExecute' => ['void'],
'ui\menu::append' => ['UI\MenuItem', 'name'=>'string', 'type='=>'string'],
'ui\menu::appendAbout' => ['UI\MenuItem', 'type='=>'string'],
'ui\menu::appendCheck' => ['UI\MenuItem', 'name'=>'string', 'type='=>'string'],
'ui\menu::appendPreferences' => ['UI\MenuItem', 'type='=>'string'],
'ui\menu::appendQuit' => ['UI\MenuItem', 'type='=>'string'],
'ui\menu::appendSeparator' => [''],
'ui\menuitem::disable' => [''],
'ui\menuitem::enable' => [''],
'ui\menuitem::isChecked' => ['bool'],
'ui\menuitem::onClick' => [''],
'ui\menuitem::setChecked' => ['', 'checked'=>'bool'],
'ui\point::getX' => ['float'],
'ui\point::getY' => ['float'],
'ui\point::setX' => ['', 'point'=>'float'],
'ui\point::setY' => ['', 'point'=>'float'],
'ui\quit' => ['void'],
'ui\run' => ['void', 'flags='=>'int'],
'ui\size::getHeight' => ['float'],
'ui\size::getWidth' => ['float'],
'ui\size::setHeight' => ['', 'size'=>'float'],
'ui\size::setWidth' => ['', 'size'=>'float'],
'ui\window::add' => ['', 'control'=>'UI\Control'],
'ui\window::error' => ['', 'title'=>'string', 'msg'=>'string'],
'ui\window::getSize' => ['UI\Size'],
'ui\window::getTitle' => ['string'],
'ui\window::hasBorders' => ['bool'],
'ui\window::hasMargin' => ['bool'],
'ui\window::isFullScreen' => ['bool'],
'ui\window::msg' => ['', 'title'=>'string', 'msg'=>'string'],
'ui\window::onClosing' => ['int'],
'ui\window::open' => ['string'],
'ui\window::save' => ['string'],
'ui\window::setBorders' => ['', 'borders'=>'bool'],
'ui\window::setFullScreen' => ['', 'full'=>'bool'],
'ui\window::setMargin' => ['', 'margin'=>'bool'],
'ui\window::setSize' => ['', 'size'=>'UI\Size'],
'ui\window::setTitle' => ['', 'title'=>'string'],
'uksort' => ['bool', '&rw_array'=>'array', 'callback'=>'callable(mixed,mixed):int'],
'umask' => ['int', 'mask='=>'int'],
'UnderflowException::__clone' => ['void'],
'UnderflowException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?UnderflowException'],
'UnderflowException::__toString' => ['string'],
'UnderflowException::getCode' => ['int'],
'UnderflowException::getFile' => ['string'],
'UnderflowException::getLine' => ['int'],
'UnderflowException::getMessage' => ['string'],
'UnderflowException::getPrevious' => ['Throwable|UnderflowException|null'],
'UnderflowException::getTrace' => ['list<array<string,mixed>>'],
'UnderflowException::getTraceAsString' => ['string'],
'UnexpectedValueException::__clone' => ['void'],
'UnexpectedValueException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?UnexpectedValueException'],
'UnexpectedValueException::__toString' => ['string'],
'UnexpectedValueException::getCode' => ['int'],
'UnexpectedValueException::getFile' => ['string'],
'UnexpectedValueException::getLine' => ['int'],
'UnexpectedValueException::getMessage' => ['string'],
'UnexpectedValueException::getPrevious' => ['Throwable|UnexpectedValueException|null'],
'UnexpectedValueException::getTrace' => ['list<array<string,mixed>>'],
'UnexpectedValueException::getTraceAsString' => ['string'],
'uniqid' => ['string', 'prefix='=>'string', 'more_entropy='=>'bool'],
'unixtojd' => ['int', 'timestamp='=>'int'],
'unlink' => ['bool', 'filename'=>'string', 'context='=>'resource'],
'unpack' => ['array|false', 'format'=>'string', 'string'=>'string', 'offset='=>'int'],
'unregister_tick_function' => ['void', 'callback'=>'callable'],
'unserialize' => ['mixed', 'data'=>'string', 'options='=>'array{allowed_classes?:string[]|bool}'],
'unset' => ['void', 'var='=>'mixed', '...args='=>'mixed'],
'untaint' => ['bool', '&rw_string'=>'string', '&...rw_strings='=>'string'],
'uopz_allow_exit' => ['void', 'allow'=>'bool'],
'uopz_backup' => ['void', 'class'=>'string', 'function'=>'string'],
'uopz_backup\'1' => ['void', 'function'=>'string'],
'uopz_compose' => ['void', 'name'=>'string', 'classes'=>'array', 'methods='=>'array', 'properties='=>'array', 'flags='=>'int'],
'uopz_copy' => ['Closure', 'class'=>'string', 'function'=>'string'],
'uopz_copy\'1' => ['Closure', 'function'=>'string'],
'uopz_delete' => ['void', 'class'=>'string', 'function'=>'string'],
'uopz_delete\'1' => ['void', 'function'=>'string'],
'uopz_extend' => ['bool', 'class'=>'string', 'parent'=>'string'],
'uopz_flags' => ['int', 'class'=>'string', 'function'=>'string', 'flags'=>'int'],
'uopz_flags\'1' => ['int', 'function'=>'string', 'flags'=>'int'],
'uopz_function' => ['void', 'class'=>'string', 'function'=>'string', 'handler'=>'Closure', 'modifiers='=>'int'],
'uopz_function\'1' => ['void', 'function'=>'string', 'handler'=>'Closure', 'modifiers='=>'int'],
'uopz_get_exit_status' => ['?int'],
'uopz_get_hook' => ['?Closure', 'class'=>'string', 'function'=>'string'],
'uopz_get_hook\'1' => ['?Closure', 'function'=>'string'],
'uopz_get_mock' => ['string|object|null', 'class'=>'string'],
'uopz_get_property' => ['mixed', 'class'=>'object|string', 'property'=>'string'],
'uopz_get_return' => ['mixed', 'class='=>'string', 'function='=>'string'],
'uopz_get_static' => ['?array', 'class'=>'string', 'function'=>'string'],
'uopz_implement' => ['bool', 'class'=>'string', 'interface'=>'string'],
'uopz_overload' => ['void', 'opcode'=>'int', 'callable'=>'Callable'],
'uopz_redefine' => ['bool', 'class'=>'string', 'constant'=>'string', 'value'=>'mixed'],
'uopz_redefine\'1' => ['bool', 'constant'=>'string', 'value'=>'mixed'],
'uopz_rename' => ['void', 'class'=>'string', 'function'=>'string', 'rename'=>'string'],
'uopz_rename\'1' => ['void', 'function'=>'string', 'rename'=>'string'],
'uopz_restore' => ['void', 'class'=>'string', 'function'=>'string'],
'uopz_restore\'1' => ['void', 'function'=>'string'],
'uopz_set_hook' => ['bool', 'class'=>'string', 'function'=>'string', 'hook'=>'Closure'],
'uopz_set_hook\'1' => ['bool', 'function'=>'string', 'hook'=>'Closure'],
'uopz_set_mock' => ['void', 'class'=>'string', 'mock'=>'object|string'],
'uopz_set_property' => ['void', 'class'=>'object|string', 'property'=>'string', 'value'=>'mixed'],
'uopz_set_return' => ['bool', 'class'=>'string', 'function'=>'string', 'value'=>'mixed', 'execute='=>'bool'],
'uopz_set_return\'1' => ['bool', 'function'=>'string', 'value'=>'mixed', 'execute='=>'bool'],
'uopz_set_static' => ['void', 'class'=>'string', 'function'=>'string', 'static'=>'array'],
'uopz_undefine' => ['bool', 'class'=>'string', 'constant'=>'string'],
'uopz_undefine\'1' => ['bool', 'constant'=>'string'],
'uopz_unset_hook' => ['bool', 'class'=>'string', 'function'=>'string'],
'uopz_unset_hook\'1' => ['bool', 'function'=>'string'],
'uopz_unset_mock' => ['void', 'class'=>'string'],
'uopz_unset_return' => ['bool', 'class='=>'string', 'function='=>'string'],
'uopz_unset_return\'1' => ['bool', 'function'=>'string'],
'urldecode' => ['string', 'string'=>'string'],
'urlencode' => ['string', 'string'=>'string'],
'use_soap_error_handler' => ['bool', 'enable='=>'bool'],
'user_error' => ['void', 'message'=>'string', 'error_level='=>'int'],
'usleep' => ['void', 'microseconds'=>'positive-int'],
'usort' => ['bool', '&rw_array'=>'array', 'callback'=>'callable(mixed,mixed):int'],
'utf8_decode' => ['string', 'string'=>'string'],
'utf8_encode' => ['string', 'string'=>'string'],
'V8Js::__construct' => ['void', 'object_name='=>'string', 'variables='=>'array', 'extensions='=>'array', 'report_uncaught_exceptions='=>'bool', 'snapshot_blob='=>'string'],
'V8Js::clearPendingException' => [''],
'V8Js::compileString' => ['resource', 'script'=>'', 'identifier='=>'string'],
'V8Js::createSnapshot' => ['false|string', 'embed_source'=>'string'],
'V8Js::executeScript' => ['', 'script'=>'resource', 'flags='=>'int', 'time_limit='=>'int', 'memory_limit='=>'int'],
'V8Js::executeString' => ['mixed', 'script'=>'string', 'identifier='=>'string', 'flags='=>'int'],
'V8Js::getExtensions' => ['string[]'],
'V8Js::getPendingException' => ['?V8JsException'],
'V8Js::registerExtension' => ['bool', 'extension_name'=>'string', 'script'=>'string', 'dependencies='=>'array', 'auto_enable='=>'bool'],
'V8Js::setAverageObjectSize' => ['', 'average_object_size'=>'int'],
'V8Js::setMemoryLimit' => ['', 'limit'=>'int'],
'V8Js::setModuleLoader' => ['', 'loader'=>'callable'],
'V8Js::setModuleNormaliser' => ['', 'normaliser'=>'callable'],
'V8Js::setTimeLimit' => ['', 'limit'=>'int'],
'V8JsException::getJsFileName' => ['string'],
'V8JsException::getJsLineNumber' => ['int'],
'V8JsException::getJsSourceLine' => ['int'],
'V8JsException::getJsTrace' => ['string'],
'V8JsScriptException::__clone' => ['void'],
'V8JsScriptException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'V8JsScriptException::__toString' => ['string'],
'V8JsScriptException::__wakeup' => ['void'],
'V8JsScriptException::getCode' => ['int'],
'V8JsScriptException::getFile' => ['string'],
'V8JsScriptException::getJsEndColumn' => ['int'],
'V8JsScriptException::getJsFileName' => ['string'],
'V8JsScriptException::getJsLineNumber' => ['int'],
'V8JsScriptException::getJsSourceLine' => ['string'],
'V8JsScriptException::getJsStartColumn' => ['int'],
'V8JsScriptException::getJsTrace' => ['string'],
'V8JsScriptException::getLine' => ['int'],
'V8JsScriptException::getMessage' => ['string'],
'V8JsScriptException::getPrevious' => ['Exception|Throwable'],
'V8JsScriptException::getTrace' => ['list<array<string,mixed>>'],
'V8JsScriptException::getTraceAsString' => ['string'],
'var_dump' => ['void', 'value'=>'mixed', '...values='=>'mixed'],
'var_export' => ['?string', 'value'=>'mixed', 'return='=>'bool'],
'VARIANT::__construct' => ['void', 'value='=>'mixed', 'type='=>'int', 'codepage='=>'int'],
'variant_abs' => ['mixed', 'value'=>'mixed'],
'variant_add' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_and' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_cast' => ['VARIANT', 'variant'=>'VARIANT', 'type'=>'int'],
'variant_cat' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_cmp' => ['int', 'left'=>'mixed', 'right'=>'mixed', 'locale_id='=>'int', 'flags='=>'int'],
'variant_date_from_timestamp' => ['VARIANT', 'timestamp'=>'int'],
'variant_date_to_timestamp' => ['int', 'variant'=>'VARIANT'],
'variant_div' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_eqv' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_fix' => ['mixed', 'value'=>'mixed'],
'variant_get_type' => ['int', 'variant'=>'VARIANT'],
'variant_idiv' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_imp' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_int' => ['mixed', 'value'=>'mixed'],
'variant_mod' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_mul' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_neg' => ['mixed', 'value'=>'mixed'],
'variant_not' => ['mixed', 'value'=>'mixed'],
'variant_or' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_pow' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_round' => ['mixed', 'value'=>'mixed', 'decimals'=>'int'],
'variant_set' => ['void', 'variant'=>'object', 'value'=>'mixed'],
'variant_set_type' => ['void', 'variant'=>'object', 'type'=>'int'],
'variant_sub' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_xor' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'VarnishAdmin::__construct' => ['void', 'args='=>'array'],
'VarnishAdmin::auth' => ['bool'],
'VarnishAdmin::ban' => ['int', 'vcl_regex'=>'string'],
'VarnishAdmin::banUrl' => ['int', 'vcl_regex'=>'string'],
'VarnishAdmin::clearPanic' => ['int'],
'VarnishAdmin::connect' => ['bool'],
'VarnishAdmin::disconnect' => ['bool'],
'VarnishAdmin::getPanic' => ['string'],
'VarnishAdmin::getParams' => ['array'],
'VarnishAdmin::isRunning' => ['bool'],
'VarnishAdmin::setCompat' => ['void', 'compat'=>'int'],
'VarnishAdmin::setHost' => ['void', 'host'=>'string'],
'VarnishAdmin::setIdent' => ['void', 'ident'=>'string'],
'VarnishAdmin::setParam' => ['int', 'name'=>'string', 'value'=>'string|int'],
'VarnishAdmin::setPort' => ['void', 'port'=>'int'],
'VarnishAdmin::setSecret' => ['void', 'secret'=>'string'],
'VarnishAdmin::setTimeout' => ['void', 'timeout'=>'int'],
'VarnishAdmin::start' => ['int'],
'VarnishAdmin::stop' => ['int'],
'VarnishLog::__construct' => ['void', 'args='=>'array'],
'VarnishLog::getLine' => ['array'],
'VarnishLog::getTagName' => ['string', 'index'=>'int'],
'VarnishStat::__construct' => ['void', 'args='=>'array'],
'VarnishStat::getSnapshot' => ['array'],
'version_compare' => ['bool', 'version1'=>'string', 'version2'=>'string', 'operator'=>'\'<\'|\'lt\'|\'<=\'|\'le\'|\'>\'|\'gt\'|\'>=\'|\'ge\'|\'==\'|\'=\'|\'eq\'|\'!=\'|\'<>\'|\'ne\''],
'version_compare\'1' => ['int', 'version1'=>'string', 'version2'=>'string'],
'vfprintf' => ['int', 'stream'=>'resource', 'format'=>'string', 'values'=>'array'],
'virtual' => ['bool', 'uri'=>'string'],
'vpopmail_add_alias_domain' => ['bool', 'domain'=>'string', 'aliasdomain'=>'string'],
'vpopmail_add_alias_domain_ex' => ['bool', 'olddomain'=>'string', 'newdomain'=>'string'],
'vpopmail_add_domain' => ['bool', 'domain'=>'string', 'dir'=>'string', 'uid'=>'int', 'gid'=>'int'],
'vpopmail_add_domain_ex' => ['bool', 'domain'=>'string', 'passwd'=>'string', 'quota='=>'string', 'bounce='=>'string', 'apop='=>'bool'],
'vpopmail_add_user' => ['bool', 'user'=>'string', 'domain'=>'string', 'password'=>'string', 'gecos='=>'string', 'apop='=>'bool'],
'vpopmail_alias_add' => ['bool', 'user'=>'string', 'domain'=>'string', 'alias'=>'string'],
'vpopmail_alias_del' => ['bool', 'user'=>'string', 'domain'=>'string'],
'vpopmail_alias_del_domain' => ['bool', 'domain'=>'string'],
'vpopmail_alias_get' => ['array', 'alias'=>'string', 'domain'=>'string'],
'vpopmail_alias_get_all' => ['array', 'domain'=>'string'],
'vpopmail_auth_user' => ['bool', 'user'=>'string', 'domain'=>'string', 'password'=>'string', 'apop='=>'string'],
'vpopmail_del_domain' => ['bool', 'domain'=>'string'],
'vpopmail_del_domain_ex' => ['bool', 'domain'=>'string'],
'vpopmail_del_user' => ['bool', 'user'=>'string', 'domain'=>'string'],
'vpopmail_error' => ['string'],
'vpopmail_passwd' => ['bool', 'user'=>'string', 'domain'=>'string', 'password'=>'string', 'apop='=>'bool'],
'vpopmail_set_user_quota' => ['bool', 'user'=>'string', 'domain'=>'string', 'quota'=>'string'],
'vprintf' => ['int', 'format'=>'string', 'values'=>'array'],
'vsprintf' => ['string', 'format'=>'string', 'values'=>'array'],
'Vtiful\Kernel\Chart::__construct' => ['void', 'handle'=>'resource', 'type'=>'int'],
'Vtiful\Kernel\Chart::axisNameX' => ['Vtiful\Kernel\Chart', 'name'=>'string'],
'Vtiful\Kernel\Chart::axisNameY' => ['Vtiful\Kernel\Chart', 'name'=>'string'],
'Vtiful\Kernel\Chart::legendSetPosition' => ['Vtiful\Kernel\Chart', 'type'=>'int'],
'Vtiful\Kernel\Chart::series' => ['Vtiful\Kernel\Chart', 'value'=>'string', 'categories='=>'string'],
'Vtiful\Kernel\Chart::seriesName' => ['Vtiful\Kernel\Chart', 'value'=>'string'],
'Vtiful\Kernel\Chart::style' => ['Vtiful\Kernel\Chart', 'style'=>'int'],
'Vtiful\Kernel\Chart::title' => ['Vtiful\Kernel\Chart', 'title'=>'string'],
'Vtiful\Kernel\Chart::toResource' => ['resource'],
'Vtiful\Kernel\Excel::__construct' => ['void', 'config'=>'array'],
'Vtiful\Kernel\Excel::activateSheet' => ['bool', 'sheet_name'=>'string'],
'Vtiful\Kernel\Excel::addSheet' => ['Vtiful\Kernel\Excel', 'sheet_name='=>'?string'],
'Vtiful\Kernel\Excel::autoFilter' => ['Vtiful\Kernel\Excel', 'range'=>'string'],
'Vtiful\Kernel\Excel::checkoutSheet' => ['Vtiful\Kernel\Excel', 'sheet_name'=>'string'],
'Vtiful\Kernel\Excel::close' => ['Vtiful\Kernel\Excel'],
'Vtiful\Kernel\Excel::columnIndexFromString' => ['int', 'index'=>'string'],
'Vtiful\Kernel\Excel::constMemory' => ['Vtiful\Kernel\Excel', 'file_name'=>'string', 'sheet_name='=>'?string'],
'Vtiful\Kernel\Excel::data' => ['Vtiful\Kernel\Excel', 'data'=>'array'],
'Vtiful\Kernel\Excel::defaultFormat' => ['Vtiful\Kernel\Excel', 'format_handle'=>'resource'],
'Vtiful\Kernel\Excel::existSheet' => ['bool', 'sheet_name'=>'string'],
'Vtiful\Kernel\Excel::fileName' => ['Vtiful\Kernel\Excel', 'file_name'=>'string', 'sheet_name='=>'?string'],
'Vtiful\Kernel\Excel::freezePanes' => ['Vtiful\Kernel\Excel', 'row'=>'int', 'column'=>'int'],
'Vtiful\Kernel\Excel::getHandle' => ['resource'],
'Vtiful\Kernel\Excel::getSheetData' => ['array|false'],
'Vtiful\Kernel\Excel::gridline' => ['Vtiful\Kernel\Excel', 'option='=>'int'],
'Vtiful\Kernel\Excel::header' => ['Vtiful\Kernel\Excel', 'header'=>'array', 'format_handle='=>'?resource'],
'Vtiful\Kernel\Excel::insertChart' => ['Vtiful\Kernel\Excel', 'row'=>'int', 'column'=>'int', 'chart_resource'=>'resource'],
'Vtiful\Kernel\Excel::insertComment' => ['Vtiful\Kernel\Excel', 'row'=>'int', 'column'=>'int', 'comment'=>'string'],
'Vtiful\Kernel\Excel::insertDate' => ['Vtiful\Kernel\Excel', 'row'=>'int', 'column'=>'int', 'timestamp'=>'int', 'format='=>'?string', 'format_handle='=>'?resource'],
'Vtiful\Kernel\Excel::insertFormula' => ['Vtiful\Kernel\Excel', 'row'=>'int', 'column'=>'int', 'formula'=>'string', 'format_handle='=>'?resource'],
'Vtiful\Kernel\Excel::insertImage' => ['Vtiful\Kernel\Excel', 'row'=>'int', 'column'=>'int', 'image'=>'string', 'width='=>'?float', 'height='=>'?float'],
'Vtiful\Kernel\Excel::insertText' => ['Vtiful\Kernel\Excel', 'row'=>'int', 'column'=>'int', 'data'=>'int|string|double', 'format='=>'?string', 'format_handle='=>'?resource'],
'Vtiful\Kernel\Excel::insertUrl' => ['Vtiful\Kernel\Excel', 'row'=>'int', 'column'=>'int', 'url'=>'string', 'text='=>'?string', 'tool_tip='=>'?string', 'format='=>'?resource'],
'Vtiful\Kernel\Excel::mergeCells' => ['Vtiful\Kernel\Excel', 'range'=>'string', 'data'=>'string', 'format_handle='=>'?resource'],
'Vtiful\Kernel\Excel::nextCellCallback' => ['void', 'fci'=>'callable(int,int,mixed)', 'sheet_name='=>'?string'],
'Vtiful\Kernel\Excel::nextRow' => ['array|false', 'zv_type_t='=>'?array'],
'Vtiful\Kernel\Excel::openFile' => ['Vtiful\Kernel\Excel', 'zs_file_name'=>'string'],
'Vtiful\Kernel\Excel::openSheet' => ['Vtiful\Kernel\Excel', 'zs_sheet_name='=>'?string', 'zl_flag='=>'?int'],
'Vtiful\Kernel\Excel::output' => ['string'],
'Vtiful\Kernel\Excel::protection' => ['Vtiful\Kernel\Excel', 'password='=>'?string'],
'Vtiful\Kernel\Excel::putCSV' => ['bool', 'fp'=>'resource', 'delimiter_str='=>'?string', 'enclosure_str='=>'?string', 'escape_str='=>'?string'],
'Vtiful\Kernel\Excel::putCSVCallback' => ['bool', 'callback'=>'callable(array):array', 'fp'=>'resource', 'delimiter_str='=>'?string', 'enclosure_str='=>'?string', 'escape_str='=>'?string'],
'Vtiful\Kernel\Excel::setColumn' => ['Vtiful\Kernel\Excel', 'range'=>'string', 'width'=>'float', 'format_handle='=>'?resource'],
'Vtiful\Kernel\Excel::setCurrentSheetHide' => ['Vtiful\Kernel\Excel'],
'Vtiful\Kernel\Excel::setCurrentSheetIsFirst' => ['Vtiful\Kernel\Excel'],
'Vtiful\Kernel\Excel::setGlobalType' => ['Vtiful\Kernel\Excel', 'zv_type_t'=>'int'],
'Vtiful\Kernel\Excel::setLandscape' => ['Vtiful\Kernel\Excel'],
'Vtiful\Kernel\Excel::setMargins' => ['Vtiful\Kernel\Excel', 'left='=>'?float', 'right='=>'?float', 'top='=>'?float', 'bottom='=>'?float'],
'Vtiful\Kernel\Excel::setPaper' => ['Vtiful\Kernel\Excel', 'paper'=>'int'],
'Vtiful\Kernel\Excel::setPortrait' => ['Vtiful\Kernel\Excel'],
'Vtiful\Kernel\Excel::setRow' => ['Vtiful\Kernel\Excel', 'range'=>'string', 'height'=>'float', 'format_handle='=>'?resource'],
'Vtiful\Kernel\Excel::setSkipRows' => ['Vtiful\Kernel\Excel', 'zv_skip_t'=>'int'],
'Vtiful\Kernel\Excel::setType' => ['Vtiful\Kernel\Excel', 'zv_type_t'=>'array'],
'Vtiful\Kernel\Excel::sheetList' => ['array'],
'Vtiful\Kernel\Excel::showComment' => ['Vtiful\Kernel\Excel'],
'Vtiful\Kernel\Excel::stringFromColumnIndex' => ['string', 'index'=>'int'],
'Vtiful\Kernel\Excel::timestampFromDateDouble' => ['int', 'index'=>'?float'],
'Vtiful\Kernel\Excel::validation' => ['Vtiful\Kernel\Excel', 'range'=>'string', 'validation_resource'=>'resource'],
'Vtiful\Kernel\Excel::zoom' => ['Vtiful\Kernel\Excel', 'scale'=>'int'],
'Vtiful\Kernel\Format::__construct' => ['void', 'handle'=>'resource'],
'Vtiful\Kernel\Format::align' => ['Vtiful\Kernel\Format', '...style'=>'int'],
'Vtiful\Kernel\Format::background' => ['Vtiful\Kernel\Format', 'color'=>'int', 'pattern='=>'int'],
'Vtiful\Kernel\Format::bold' => ['Vtiful\Kernel\Format'],
'Vtiful\Kernel\Format::border' => ['Vtiful\Kernel\Format', 'style'=>'int'],
'Vtiful\Kernel\Format::font' => ['Vtiful\Kernel\Format', 'font'=>'string'],
'Vtiful\Kernel\Format::fontColor' => ['Vtiful\Kernel\Format', 'color'=>'int'],
'Vtiful\Kernel\Format::fontSize' => ['Vtiful\Kernel\Format', 'size'=>'float'],
'Vtiful\Kernel\Format::italic' => ['Vtiful\Kernel\Format'],
'Vtiful\Kernel\Format::number' => ['Vtiful\Kernel\Format', 'format'=>'string'],
'Vtiful\Kernel\Format::strikeout' => ['Vtiful\Kernel\Format'],
'Vtiful\Kernel\Format::toResource' => ['resource'],
'Vtiful\Kernel\Format::underline' => ['Vtiful\Kernel\Format', 'style'=>'int'],
'Vtiful\Kernel\Format::unlocked' => ['Vtiful\Kernel\Format'],
'Vtiful\Kernel\Format::wrap' => ['Vtiful\Kernel\Format'],
'Vtiful\Kernel\Validation::__construct' => ['void'],
'Vtiful\Kernel\Validation::criteriaType' => ['?Vtiful\Kernel\Validation', 'type'=>'int'],
'Vtiful\Kernel\Validation::maximumFormula' => ['?Vtiful\Kernel\Validation', 'maximum_formula'=>'string'],
'Vtiful\Kernel\Validation::maximumNumber' => ['?Vtiful\Kernel\Validation', 'maximum_number'=>'float'],
'Vtiful\Kernel\Validation::minimumFormula' => ['?Vtiful\Kernel\Validation', 'minimum_formula'=>'string'],
'Vtiful\Kernel\Validation::minimumNumber' => ['?Vtiful\Kernel\Validation', 'minimum_number'=>'float'],
'Vtiful\Kernel\Validation::toResource' => ['resource'],
'Vtiful\Kernel\Validation::validationType' => ['?Vtiful\Kernel\Validation', 'type'=>'int'],
'Vtiful\Kernel\Validation::valueList' => ['?Vtiful\Kernel\Validation', 'value_list'=>'array'],
'Vtiful\Kernel\Validation::valueNumber' => ['?Vtiful\Kernel\Validation', 'value_number'=>'int'],
'w32api_deftype' => ['bool', 'typename'=>'string', 'member1_type'=>'string', 'member1_name'=>'string', '...args='=>'string'],
'w32api_init_dtype' => ['resource', 'typename'=>'string', 'value'=>'', '...args='=>''],
'w32api_invoke_function' => ['', 'funcname'=>'string', 'argument'=>'', '...args='=>''],
'w32api_register_function' => ['bool', 'library'=>'string', 'function_name'=>'string', 'return_type'=>'string'],
'w32api_set_call_method' => ['', 'method'=>'int'],
'wddx_add_vars' => ['bool', 'packet_id'=>'resource', 'var_names'=>'mixed', '...vars='=>'mixed'],
'wddx_deserialize' => ['mixed', 'packet'=>'string'],
'wddx_packet_end' => ['string', 'packet_id'=>'resource'],
'wddx_packet_start' => ['resource|false', 'comment='=>'string'],
'wddx_serialize_value' => ['string|false', 'value'=>'mixed', 'comment='=>'string'],
'wddx_serialize_vars' => ['string|false', 'var_name'=>'mixed', '...vars='=>'mixed'],
'WeakMap::__construct' => ['void'],
'WeakMap::count' => ['int'],
'WeakMap::current' => ['mixed'],
'WeakMap::key' => ['object'],
'WeakMap::next' => ['void'],
'WeakMap::offsetExists' => ['bool', 'object'=>'object'],
'WeakMap::offsetGet' => ['mixed', 'object'=>'object'],
'WeakMap::offsetSet' => ['void', 'object'=>'object', 'value'=>'mixed'],
'WeakMap::offsetUnset' => ['void', 'object'=>'object'],
'WeakMap::rewind' => ['void'],
'WeakMap::valid' => ['bool'],
'Weakref::acquire' => ['bool'],
'Weakref::get' => ['object'],
'Weakref::release' => ['bool'],
'Weakref::valid' => ['bool'],
'webObj::convertToString' => ['string'],
'webObj::free' => ['void'],
'webObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'webObj::updateFromString' => ['int', 'snippet'=>'string'],
'win32_continue_service' => ['int|false', 'servicename'=>'string', 'machine='=>'string'],
'win32_create_service' => ['int|false', 'details'=>'array', 'machine='=>'string'],
'win32_delete_service' => ['int|false', 'servicename'=>'string', 'machine='=>'string'],
'win32_get_last_control_message' => ['int'],
'win32_pause_service' => ['int|false', 'servicename'=>'string', 'machine='=>'string'],
'win32_ps_list_procs' => ['array'],
'win32_ps_stat_mem' => ['array'],
'win32_ps_stat_proc' => ['array', 'pid='=>'int'],
'win32_query_service_status' => ['array|false|int', 'servicename'=>'string', 'machine='=>'string'],
'win32_send_custom_control' => ['int', 'servicename'=>'string', 'control'=>'int', 'machine='=>'string'],
'win32_set_service_exit_code' => ['int', 'exitCode='=>'int'],
'win32_set_service_exit_mode' => ['bool', 'gracefulMode='=>'bool'],
'win32_set_service_status' => ['bool|int', 'status'=>'int', 'checkpoint='=>'int'],
'win32_start_service' => ['int|false', 'servicename'=>'string', 'machine='=>'string'],
'win32_start_service_ctrl_dispatcher' => ['bool|int', 'name'=>'string'],
'win32_stop_service' => ['int|false', 'servicename'=>'string', 'machine='=>'string'],
'wincache_fcache_fileinfo' => ['array|false', 'summaryonly='=>'bool'],
'wincache_fcache_meminfo' => ['array|false'],
'wincache_lock' => ['bool', 'key'=>'string', 'isglobal='=>'bool'],
'wincache_ocache_fileinfo' => ['array|false', 'summaryonly='=>'bool'],
'wincache_ocache_meminfo' => ['array|false'],
'wincache_refresh_if_changed' => ['bool', 'files='=>'array'],
'wincache_rplist_fileinfo' => ['array|false', 'summaryonly='=>'bool'],
'wincache_rplist_meminfo' => ['array|false'],
'wincache_scache_info' => ['array|false', 'summaryonly='=>'bool'],
'wincache_scache_meminfo' => ['array|false'],
'wincache_ucache_add' => ['bool', 'key'=>'string', 'value'=>'mixed', 'ttl='=>'int'],
'wincache_ucache_add\'1' => ['bool', 'values'=>'array', 'unused='=>'', 'ttl='=>'int'],
'wincache_ucache_cas' => ['bool', 'key'=>'string', 'old_value'=>'int', 'new_value'=>'int'],
'wincache_ucache_clear' => ['bool'],
'wincache_ucache_dec' => ['int|false', 'key'=>'string', 'dec_by='=>'int', 'success='=>'bool'],
'wincache_ucache_delete' => ['bool', 'key'=>'mixed'],
'wincache_ucache_exists' => ['bool', 'key'=>'string'],
'wincache_ucache_get' => ['mixed', 'key'=>'mixed', '&w_success='=>'bool'],
'wincache_ucache_inc' => ['int|false', 'key'=>'string', 'inc_by='=>'int', 'success='=>'bool'],
'wincache_ucache_info' => ['array|false', 'summaryonly='=>'bool', 'key='=>'string'],
'wincache_ucache_meminfo' => ['array|false'],
'wincache_ucache_set' => ['bool', 'key'=>'', 'value'=>'', 'ttl='=>'int'],
'wincache_ucache_set\'1' => ['bool', 'values'=>'array', 'unused='=>'', 'ttl='=>'int'],
'wincache_unlock' => ['bool', 'key'=>'string'],
'wkhtmltox\image\converter::convert' => ['?string'],
'wkhtmltox\image\converter::getVersion' => ['string'],
'wkhtmltox\pdf\converter::add' => ['void', 'object'=>'wkhtmltox\PDF\Object'],
'wkhtmltox\pdf\converter::convert' => ['?string'],
'wkhtmltox\pdf\converter::getVersion' => ['string'],
'wordwrap' => ['string', 'string'=>'string', 'width='=>'int', 'break='=>'string', 'cut_long_words='=>'bool'],
'Worker::__construct' => ['void'],
'Worker::addRef' => ['void'],
'Worker::chunk' => ['array', 'size'=>'int', 'preserve'=>'bool'],
'Worker::collect' => ['int', 'collector='=>'Callable'],
'Worker::count' => ['int'],
'Worker::delRef' => ['void'],
'Worker::detach' => ['void'],
'Worker::extend' => ['bool', 'class'=>'string'],
'Worker::getCreatorId' => ['int'],
'Worker::getCurrentThread' => ['Thread'],
'Worker::getCurrentThreadId' => ['int'],
'Worker::getRefCount' => ['int'],
'Worker::getStacked' => ['int'],
'Worker::getTerminationInfo' => ['array'],
'Worker::getThreadId' => ['int'],
'Worker::globally' => ['mixed'],
'Worker::isGarbage' => ['bool'],
'Worker::isJoined' => ['bool'],
'Worker::isRunning' => ['bool'],
'Worker::isShutdown' => ['bool'],
'Worker::isStarted' => ['bool'],
'Worker::isTerminated' => ['bool'],
'Worker::isWaiting' => ['bool'],
'Worker::isWorking' => ['bool'],
'Worker::join' => ['bool'],
'Worker::kill' => ['bool'],
'Worker::lock' => ['bool'],
'Worker::merge' => ['bool', 'from'=>'', 'overwrite='=>'mixed'],
'Worker::notify' => ['bool'],
'Worker::notifyOne' => ['bool'],
'Worker::offsetExists' => ['bool', 'offset'=>'mixed'],
'Worker::offsetGet' => ['mixed', 'offset'=>'mixed'],
'Worker::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'Worker::offsetUnset' => ['void', 'offset'=>'mixed'],
'Worker::pop' => ['bool'],
'Worker::run' => ['void'],
'Worker::setGarbage' => ['void'],
'Worker::shift' => ['bool'],
'Worker::shutdown' => ['bool'],
'Worker::stack' => ['int', '&rw_work'=>'Threaded'],
'Worker::start' => ['bool', 'options='=>'int'],
'Worker::synchronized' => ['mixed', 'block'=>'Closure', '_='=>'mixed'],
'Worker::unlock' => ['bool'],
'Worker::unstack' => ['int', '&rw_work='=>'Threaded'],
'Worker::wait' => ['bool', 'timeout='=>'int'],
'xattr_get' => ['string', 'filename'=>'string', 'name'=>'string', 'flags='=>'int'],
'xattr_list' => ['array', 'filename'=>'string', 'flags='=>'int'],
'xattr_remove' => ['bool', 'filename'=>'string', 'name'=>'string', 'flags='=>'int'],
'xattr_set' => ['bool', 'filename'=>'string', 'name'=>'string', 'value'=>'string', 'flags='=>'int'],
'xattr_supported' => ['bool', 'filename'=>'string', 'flags='=>'int'],
'xcache_asm' => ['string', 'filename'=>'string'],
'xcache_clear_cache' => ['void', 'type'=>'int', 'id='=>'int'],
'xcache_coredump' => ['string', 'op_type'=>'int'],
'xcache_count' => ['int', 'type'=>'int'],
'xcache_coverager_decode' => ['array', 'data'=>'string'],
'xcache_coverager_get' => ['array', 'clean='=>'bool'],
'xcache_coverager_start' => ['void', 'clean='=>'bool'],
'xcache_coverager_stop' => ['void', 'clean='=>'bool'],
'xcache_dasm_file' => ['string', 'filename'=>'string'],
'xcache_dasm_string' => ['string', 'code'=>'string'],
'xcache_dec' => ['int', 'name'=>'string', 'value='=>'int|mixed', 'ttl='=>'int'],
'xcache_decode' => ['bool', 'filename'=>'string'],
'xcache_encode' => ['string', 'filename'=>'string'],
'xcache_get' => ['mixed', 'name'=>'string'],
'xcache_get_data_type' => ['string', 'type'=>'int'],
'xcache_get_op_spec' => ['string', 'op_type'=>'int'],
'xcache_get_op_type' => ['string', 'op_type'=>'int'],
'xcache_get_opcode' => ['string', 'opcode'=>'int'],
'xcache_get_opcode_spec' => ['string', 'opcode'=>'int'],
'xcache_inc' => ['int', 'name'=>'string', 'value='=>'int|mixed', 'ttl='=>'int'],
'xcache_info' => ['array', 'type'=>'int', 'id'=>'int'],
'xcache_is_autoglobal' => ['string', 'name'=>'string'],
'xcache_isset' => ['bool', 'name'=>'string'],
'xcache_list' => ['array', 'type'=>'int', 'id'=>'int'],
'xcache_set' => ['bool', 'name'=>'string', 'value'=>'mixed', 'ttl='=>'int'],
'xcache_unset' => ['bool', 'name'=>'string'],
'xcache_unset_by_prefix' => ['bool', 'prefix'=>'string'],
'Xcom::__construct' => ['void', 'fabric_url='=>'string', 'fabric_token='=>'string', 'capability_token='=>'string'],
'Xcom::decode' => ['object', 'avro_msg'=>'string', 'json_schema'=>'string'],
'Xcom::encode' => ['string', 'data'=>'stdClass', 'avro_schema'=>'string'],
'Xcom::getDebugOutput' => ['string'],
'Xcom::getLastResponse' => ['string'],
'Xcom::getLastResponseInfo' => ['array'],
'Xcom::getOnboardingURL' => ['string', 'capability_name'=>'string', 'agreement_url'=>'string'],
'Xcom::send' => ['int', 'topic'=>'string', 'data'=>'mixed', 'json_schema='=>'string', 'http_headers='=>'array'],
'Xcom::sendAsync' => ['int', 'topic'=>'string', 'data'=>'mixed', 'json_schema='=>'string', 'http_headers='=>'array'],
'xdebug_break' => ['bool'],
'xdebug_call_class' => ['string', 'depth='=>'int'],
'xdebug_call_file' => ['string', 'depth='=>'int'],
'xdebug_call_function' => ['string', 'depth='=>'int'],
'xdebug_call_line' => ['int', 'depth='=>'int'],
'xdebug_clear_aggr_profiling_data' => ['bool'],
'xdebug_code_coverage_started' => ['bool'],
'xdebug_debug_zval' => ['void', '...varName'=>'string'],
'xdebug_debug_zval_stdout' => ['void', '...varName'=>'string'],
'xdebug_disable' => ['void'],
'xdebug_dump_aggr_profiling_data' => ['bool'],
'xdebug_dump_superglobals' => ['void'],
'xdebug_enable' => ['void'],
'xdebug_get_code_coverage' => ['array'],
'xdebug_get_collected_errors' => ['string', 'clean='=>'bool'],
'xdebug_get_declared_vars' => ['array'],
'xdebug_get_formatted_function_stack' => [''],
'xdebug_get_function_count' => ['int'],
'xdebug_get_function_stack' => ['array', 'message='=>'string', 'options='=>'int'],
'xdebug_get_headers' => ['array'],
'xdebug_get_monitored_functions' => ['array'],
'xdebug_get_profiler_filename' => ['string|false'],
'xdebug_get_stack_depth' => ['int'],
'xdebug_get_tracefile_name' => ['string'],
'xdebug_is_debugger_active' => ['bool'],
'xdebug_is_enabled' => ['bool'],
'xdebug_memory_usage' => ['int'],
'xdebug_peak_memory_usage' => ['int'],
'xdebug_print_function_stack' => ['array', 'message='=>'string', 'options='=>'int'],
'xdebug_set_filter' => ['void', 'group'=>'int', 'list_type'=>'int', 'configuration'=>'array'],
'xdebug_start_code_coverage' => ['void', 'options='=>'int'],
'xdebug_start_error_collection' => ['void'],
'xdebug_start_function_monitor' => ['void', 'list_of_functions_to_monitor'=>'string[]'],
'xdebug_start_trace' => ['void', 'trace_file'=>'', 'options='=>'int|mixed'],
'xdebug_stop_code_coverage' => ['void', 'cleanup='=>'bool'],
'xdebug_stop_error_collection' => ['void'],
'xdebug_stop_function_monitor' => ['void'],
'xdebug_stop_trace' => ['void'],
'xdebug_time_index' => ['float'],
'xdebug_var_dump' => ['void', '...var'=>''],
'xdiff_file_bdiff' => ['bool', 'old_file'=>'string', 'new_file'=>'string', 'dest'=>'string'],
'xdiff_file_bdiff_size' => ['int', 'file'=>'string'],
'xdiff_file_bpatch' => ['bool', 'file'=>'string', 'patch'=>'string', 'dest'=>'string'],
'xdiff_file_diff' => ['bool', 'old_file'=>'string', 'new_file'=>'string', 'dest'=>'string', 'context='=>'int', 'minimal='=>'bool'],
'xdiff_file_diff_binary' => ['bool', 'old_file'=>'string', 'new_file'=>'string', 'dest'=>'string'],
'xdiff_file_merge3' => ['mixed', 'old_file'=>'string', 'new_file1'=>'string', 'new_file2'=>'string', 'dest'=>'string'],
'xdiff_file_patch' => ['mixed', 'file'=>'string', 'patch'=>'string', 'dest'=>'string', 'flags='=>'int'],
'xdiff_file_patch_binary' => ['bool', 'file'=>'string', 'patch'=>'string', 'dest'=>'string'],
'xdiff_file_rabdiff' => ['bool', 'old_file'=>'string', 'new_file'=>'string', 'dest'=>'string'],
'xdiff_string_bdiff' => ['string', 'old_data'=>'string', 'new_data'=>'string'],
'xdiff_string_bdiff_size' => ['int', 'patch'=>'string'],
'xdiff_string_bpatch' => ['string', 'string'=>'string', 'patch'=>'string'],
'xdiff_string_diff' => ['string', 'old_data'=>'string', 'new_data'=>'string', 'context='=>'int', 'minimal='=>'bool'],
'xdiff_string_diff_binary' => ['string', 'old_data'=>'string', 'new_data'=>'string'],
'xdiff_string_merge3' => ['mixed', 'old_data'=>'string', 'new_data1'=>'string', 'new_data2'=>'string', 'error='=>'string'],
'xdiff_string_patch' => ['string', 'string'=>'string', 'patch'=>'string', 'flags='=>'int', '&w_error='=>'string'],
'xdiff_string_patch_binary' => ['string', 'string'=>'string', 'patch'=>'string'],
'xdiff_string_rabdiff' => ['string', 'old_data'=>'string', 'new_data'=>'string'],
'xhprof_disable' => ['array'],
'xhprof_enable' => ['void', 'flags='=>'int', 'options='=>'array'],
'xhprof_sample_disable' => ['array'],
'xhprof_sample_enable' => ['void'],
'xlswriter_get_author' => ['string'],
'xlswriter_get_version' => ['string'],
'xml_error_string' => ['string', 'error_code'=>'int'],
'xml_get_current_byte_index' => ['int|false', 'parser'=>'XMLParser'],
'xml_get_current_column_number' => ['int|false', 'parser'=>'XMLParser'],
'xml_get_current_line_number' => ['int|false', 'parser'=>'XMLParser'],
'xml_get_error_code' => ['int|false', 'parser'=>'XMLParser'],
'xml_parse' => ['int', 'parser'=>'XMLParser', 'data'=>'string', 'is_final='=>'bool'],
'xml_parse_into_struct' => ['int', 'parser'=>'XMLParser', 'data'=>'string', '&w_values'=>'array', '&w_index='=>'array'],
'xml_parser_create' => ['XMLParser', 'encoding='=>'string'],
'xml_parser_create_ns' => ['XMLParser', 'encoding='=>'string', 'separator='=>'string'],
'xml_parser_free' => ['bool', 'parser'=>'XMLParser'],
'xml_parser_get_option' => ['mixed|false', 'parser'=>'XMLParser', 'option'=>'int'],
'xml_parser_set_option' => ['bool', 'parser'=>'XMLParser', 'option'=>'int', 'value'=>'mixed'],
'xml_set_character_data_handler' => ['bool', 'parser'=>'XMLParser', 'handler'=>'callable'],
'xml_set_default_handler' => ['bool', 'parser'=>'XMLParser', 'handler'=>'callable'],
'xml_set_element_handler' => ['bool', 'parser'=>'XMLParser', 'start_handler'=>'callable', 'end_handler'=>'callable'],
'xml_set_end_namespace_decl_handler' => ['bool', 'parser'=>'XMLParser', 'handler'=>'callable'],
'xml_set_external_entity_ref_handler' => ['bool', 'parser'=>'XMLParser', 'handler'=>'callable'],
'xml_set_notation_decl_handler' => ['bool', 'parser'=>'XMLParser', 'handler'=>'callable'],
'xml_set_object' => ['bool', 'parser'=>'XMLParser', 'object'=>'object'],
'xml_set_processing_instruction_handler' => ['bool', 'parser'=>'XMLParser', 'handler'=>'callable'],
'xml_set_start_namespace_decl_handler' => ['bool', 'parser'=>'XMLParser', 'handler'=>'callable'],
'xml_set_unparsed_entity_decl_handler' => ['bool', 'parser'=>'XMLParser', 'handler'=>'callable'],
'XMLDiff\Base::__construct' => ['void', 'nsname'=>'string'],
'XMLDiff\Base::diff' => ['mixed', 'from'=>'mixed', 'to'=>'mixed'],
'XMLDiff\Base::merge' => ['mixed', 'src'=>'mixed', 'diff'=>'mixed'],
'XMLDiff\DOM::diff' => ['DOMDocument', 'from'=>'DOMDocument', 'to'=>'DOMDocument'],
'XMLDiff\DOM::merge' => ['DOMDocument', 'src'=>'DOMDocument', 'diff'=>'DOMDocument'],
'XMLDiff\File::diff' => ['string', 'from'=>'string', 'to'=>'string'],
'XMLDiff\File::merge' => ['string', 'src'=>'string', 'diff'=>'string'],
'XMLDiff\Memory::diff' => ['string', 'from'=>'string', 'to'=>'string'],
'XMLDiff\Memory::merge' => ['string', 'src'=>'string', 'diff'=>'string'],
'XMLReader::close' => ['bool'],
'XMLReader::expand' => ['DOMNode|false', 'basenode='=>'DOMNode'],
'XMLReader::getAttribute' => ['?string', 'name'=>'string'],
'XMLReader::getAttributeNo' => ['?string', 'index'=>'int'],
'XMLReader::getAttributeNs' => ['?string', 'name'=>'string', 'namespaceuri'=>'string'],
'XMLReader::getParserProperty' => ['bool', 'property'=>'int'],
'XMLReader::isValid' => ['bool'],
'XMLReader::lookupNamespace' => ['?string', 'prefix'=>'string'],
'XMLReader::moveToAttribute' => ['bool', 'name'=>'string'],
'XMLReader::moveToAttributeNo' => ['bool', 'index'=>'int'],
'XMLReader::moveToAttributeNs' => ['bool', 'localname'=>'string', 'namespaceuri'=>'string'],
'XMLReader::moveToElement' => ['bool'],
'XMLReader::moveToFirstAttribute' => ['bool'],
'XMLReader::moveToNextAttribute' => ['bool'],
'XMLReader::next' => ['bool', 'localname='=>'string'],
'XMLReader::open' => ['bool', 'uri'=>'string', 'encoding='=>'?string', 'options='=>'int'],
'XMLReader::read' => ['bool'],
'XMLReader::readInnerXML' => ['string'],
'XMLReader::readOuterXML' => ['string'],
'XMLReader::readString' => ['string'],
'XMLReader::setParserProperty' => ['bool', 'property'=>'int', 'value'=>'bool'],
'XMLReader::setRelaxNGSchema' => ['bool', 'filename'=>'string'],
'XMLReader::setRelaxNGSchemaSource' => ['bool', 'source'=>'string'],
'XMLReader::setSchema' => ['bool', 'filename'=>'string'],
'XMLReader::XML' => ['bool', 'source'=>'string', 'encoding='=>'?string', 'options='=>'int'],
'xmlrpc_decode' => ['mixed', 'xml'=>'string', 'encoding='=>'string'],
'xmlrpc_decode_request' => ['?array', 'xml'=>'string', '&w_method'=>'string', 'encoding='=>'string'],
'xmlrpc_encode' => ['string', 'value'=>'mixed'],
'xmlrpc_encode_request' => ['string', 'method'=>'string', 'params'=>'mixed', 'output_options='=>'array'],
'xmlrpc_get_type' => ['string', 'value'=>'mixed'],
'xmlrpc_is_fault' => ['bool', 'arg'=>'array'],
'xmlrpc_parse_method_descriptions' => ['array', 'xml'=>'string'],
'xmlrpc_server_add_introspection_data' => ['int', 'server'=>'resource', 'desc'=>'array'],
'xmlrpc_server_call_method' => ['string', 'server'=>'resource', 'xml'=>'string', 'user_data'=>'mixed', 'output_options='=>'array'],
'xmlrpc_server_create' => ['resource'],
'xmlrpc_server_destroy' => ['int', 'server'=>'resource'],
'xmlrpc_server_register_introspection_callback' => ['bool', 'server'=>'resource', 'function'=>'string'],
'xmlrpc_server_register_method' => ['bool', 'server'=>'resource', 'method_name'=>'string', 'function'=>'string'],
'xmlrpc_set_type' => ['bool', '&rw_value'=>'string|DateTime', 'type'=>'string'],
'XMLWriter::endAttribute' => ['bool'],
'XMLWriter::endCdata' => ['bool'],
'XMLWriter::endComment' => ['bool'],
'XMLWriter::endDocument' => ['bool'],
'XMLWriter::endDtd' => ['bool'],
'XMLWriter::endDtdAttlist' => ['bool'],
'XMLWriter::endDtdElement' => ['bool'],
'XMLWriter::endDtdEntity' => ['bool'],
'XMLWriter::endElement' => ['bool'],
'XMLWriter::endPi' => ['bool'],
'XMLWriter::flush' => ['string|int', 'empty='=>'bool'],
'XMLWriter::fullEndElement' => ['bool'],
'XMLWriter::openMemory' => ['bool'],
'XMLWriter::openUri' => ['bool', 'uri'=>'string'],
'XMLWriter::outputMemory' => ['string', 'flush='=>'bool'],
'XMLWriter::setIndent' => ['bool', 'enable'=>'bool'],
'XMLWriter::setIndentString' => ['bool', 'indentation'=>'string'],
'XMLWriter::startAttribute' => ['bool', 'name'=>'string'],
'XMLWriter::startAttributeNs' => ['bool', 'prefix'=>'?string', 'name'=>'string', 'namespace'=>'?string'],
'XMLWriter::startCdata' => ['bool'],
'XMLWriter::startComment' => ['bool'],
'XMLWriter::startDocument' => ['bool', 'version='=>'?string', 'encoding='=>'?string', 'standalone='=>'?string'],
'XMLWriter::startDtd' => ['bool', 'qualifiedName'=>'string', 'publicId='=>'?string', 'systemId='=>'?string'],
'XMLWriter::startDtdAttlist' => ['bool', 'name'=>'string'],
'XMLWriter::startDtdElement' => ['bool', 'qualifiedName'=>'string'],
'XMLWriter::startDtdEntity' => ['bool', 'name'=>'string', 'isParam'=>'bool'],
'XMLWriter::startElement' => ['bool', 'name'=>'string'],
'XMLWriter::startElementNs' => ['bool', 'prefix'=>'?string', 'name'=>'string', 'namespace'=>'?string'],
'XMLWriter::startPi' => ['bool', 'target'=>'string'],
'XMLWriter::text' => ['bool', 'content'=>'string'],
'XMLWriter::writeAttribute' => ['bool', 'name'=>'string', 'value'=>'string'],
'XMLWriter::writeAttributeNs' => ['bool', 'prefix'=>'?string', 'name'=>'string', 'namespace'=>'?string', 'value'=>'string'],
'XMLWriter::writeCdata' => ['bool', 'content'=>'string'],
'XMLWriter::writeComment' => ['bool', 'content'=>'string'],
'XMLWriter::writeDtd' => ['bool', 'name'=>'string', 'publicId='=>'?string', 'systemId='=>'?string', 'content='=>'?string'],
'XMLWriter::writeDtdAttlist' => ['bool', 'name'=>'string', 'content'=>'string'],
'XMLWriter::writeDtdElement' => ['bool', 'name'=>'string', 'content'=>'string'],
'XMLWriter::writeDtdEntity' => ['bool', 'name'=>'string', 'content'=>'string', 'isParam='=>'bool', 'publicId='=>'?string', 'systemId='=>'?string', 'notationData='=>'?string'],
'XMLWriter::writeElement' => ['bool', 'name'=>'string', 'content='=>'?string'],
'XMLWriter::writeElementNs' => ['bool', 'prefix'=>'?string', 'name'=>'string', 'namespace'=>'?string', 'content='=>'?string'],
'XMLWriter::writePi' => ['bool', 'target'=>'string', 'content'=>'string'],
'XMLWriter::writeRaw' => ['bool', 'content'=>'string'],
'xmlwriter_end_attribute' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_cdata' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_comment' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_document' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_dtd' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_dtd_attlist' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_dtd_element' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_dtd_entity' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_element' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_end_pi' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_flush' => ['string|int', 'writer'=>'XMLWriter', 'empty='=>'bool'],
'xmlwriter_full_end_element' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_open_memory' => ['XMLWriter|false'],
'xmlwriter_open_uri' => ['XMLWriter|false', 'uri'=>'string'],
'xmlwriter_output_memory' => ['string', 'writer'=>'XMLWriter', 'flush='=>'bool'],
'xmlwriter_set_indent' => ['bool', 'writer'=>'XMLWriter', 'enable'=>'bool'],
'xmlwriter_set_indent_string' => ['bool', 'writer'=>'XMLWriter', 'indentation'=>'string'],
'xmlwriter_start_attribute' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string'],
'xmlwriter_start_attribute_ns' => ['bool', 'writer'=>'XMLWriter', 'prefix'=>'?string', 'name'=>'string', 'namespace'=>'?string'],
'xmlwriter_start_cdata' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_start_comment' => ['bool', 'writer'=>'XMLWriter'],
'xmlwriter_start_document' => ['bool', 'writer'=>'XMLWriter', 'version='=>'?string', 'encoding='=>'?string', 'standalone='=>'?string'],
'xmlwriter_start_dtd' => ['bool', 'writer'=>'XMLWriter', 'qualifiedName'=>'string', 'publicId='=>'?string', 'systemId='=>'?string'],
'xmlwriter_start_dtd_attlist' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string'],
'xmlwriter_start_dtd_element' => ['bool', 'writer'=>'XMLWriter', 'qualifiedName'=>'string'],
'xmlwriter_start_dtd_entity' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string', 'isParam'=>'bool'],
'xmlwriter_start_element' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string'],
'xmlwriter_start_element_ns' => ['bool', 'writer'=>'XMLWriter', 'prefix'=>'?string', 'name'=>'string', 'namespace'=>'?string'],
'xmlwriter_start_pi' => ['bool', 'writer'=>'XMLWriter', 'target'=>'string'],
'xmlwriter_text' => ['bool', 'writer'=>'XMLWriter', 'content'=>'string'],
'xmlwriter_write_attribute' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string', 'value'=>'string'],
'xmlwriter_write_attribute_ns' => ['bool', 'writer'=>'XMLWriter', 'prefix'=>'?string', 'name'=>'string', 'namespace'=>'?string', 'value'=>'string'],
'xmlwriter_write_cdata' => ['bool', 'writer'=>'XMLWriter', 'content'=>'string'],
'xmlwriter_write_comment' => ['bool', 'writer'=>'XMLWriter', 'content'=>'string'],
'xmlwriter_write_dtd' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string', 'publicId='=>'?string', 'systemId='=>'?string', 'content='=>'?string'],
'xmlwriter_write_dtd_attlist' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string', 'content'=>'string'],
'xmlwriter_write_dtd_element' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string', 'content'=>'string'],
'xmlwriter_write_dtd_entity' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string', 'content'=>'string', 'isParam='=>'bool', 'publicId='=>'?string', 'systemId='=>'?string', 'notationData='=>'?string'],
'xmlwriter_write_element' => ['bool', 'writer'=>'XMLWriter', 'name'=>'string', 'content='=>'?string'],
'xmlwriter_write_element_ns' => ['bool', 'writer'=>'XMLWriter', 'prefix'=>'?string', 'name'=>'string', 'namespace'=>'?string', 'content='=>'?string'],
'xmlwriter_write_pi' => ['bool', 'writer'=>'XMLWriter', 'target'=>'string', 'content'=>'string'],
'xmlwriter_write_raw' => ['bool', 'writer'=>'XMLWriter', 'content'=>'string'],
'xpath_new_context' => ['XPathContext', 'dom_document'=>'DOMDocument'],
'xpath_register_ns' => ['bool', 'xpath_context'=>'xpathcontext', 'prefix'=>'string', 'uri'=>'string'],
'xpath_register_ns_auto' => ['bool', 'xpath_context'=>'xpathcontext', 'context_node='=>'object'],
'xptr_new_context' => ['XPathContext'],
'xsl_xsltprocessor_get_parameter' => ['string', 'namespace'=>'string', 'name'=>'string'],
'xsl_xsltprocessor_get_security_prefs' => ['int'],
'xsl_xsltprocessor_has_exslt_support' => ['bool'],
'xsl_xsltprocessor_register_php_functions' => ['', 'restrict'=>''],
'xsl_xsltprocessor_remove_parameter' => ['bool', 'namespace'=>'string', 'name'=>'string'],
'xsl_xsltprocessor_set_parameter' => ['bool', 'namespace'=>'string', 'name'=>'', 'value'=>'string'],
'xsl_xsltprocessor_set_profiling' => ['bool', 'filename'=>'string'],
'xsl_xsltprocessor_set_security_prefs' => ['int', 'securityprefs'=>'int'],
'xsl_xsltprocessor_transform_to_uri' => ['int', 'doc'=>'DOMDocument', 'uri'=>'string'],
'xsl_xsltprocessor_transform_to_xml' => ['string', 'doc'=>'DOMDocument'],
'xslt_backend_info' => ['string'],
'xslt_backend_name' => ['string'],
'xslt_backend_version' => ['string'],
'xslt_create' => ['resource'],
'xslt_errno' => ['int', 'xh'=>''],
'xslt_error' => ['string', 'xh'=>''],
'xslt_free' => ['', 'xh'=>''],
'xslt_getopt' => ['int', 'processor'=>''],
'xslt_process' => ['', 'xh'=>'', 'xmlcontainer'=>'string', 'xslcontainer'=>'string', 'resultcontainer='=>'string', 'arguments='=>'array', 'parameters='=>'array'],
'xslt_set_base' => ['', 'xh'=>'', 'uri'=>'string'],
'xslt_set_encoding' => ['', 'xh'=>'', 'encoding'=>'string'],
'xslt_set_error_handler' => ['', 'xh'=>'', 'handler'=>''],
'xslt_set_log' => ['', 'xh'=>'', 'log='=>''],
'xslt_set_object' => ['bool', 'processor'=>'', 'object'=>'object'],
'xslt_set_sax_handler' => ['', 'xh'=>'', 'handlers'=>'array'],
'xslt_set_sax_handlers' => ['', 'processor'=>'', 'handlers'=>'array'],
'xslt_set_scheme_handler' => ['', 'xh'=>'', 'handlers'=>'array'],
'xslt_set_scheme_handlers' => ['', 'xh'=>'', 'handlers'=>'array'],
'xslt_setopt' => ['', 'processor'=>'', 'newmask'=>'int'],
'XSLTProcessor::getParameter' => ['string|false', 'namespace'=>'string', 'name'=>'string'],
'XsltProcessor::getSecurityPrefs' => ['int'],
'XSLTProcessor::hasExsltSupport' => ['bool'],
'XSLTProcessor::importStylesheet' => ['bool', 'stylesheet'=>'object'],
'XSLTProcessor::registerPHPFunctions' => ['void', 'functions='=>'mixed'],
'XSLTProcessor::removeParameter' => ['bool', 'namespace'=>'string', 'name'=>'string'],
'XSLTProcessor::setParameter' => ['bool', 'namespace'=>'string', 'name'=>'string', 'value'=>'string'],
'XSLTProcessor::setParameter\'1' => ['bool', 'namespace'=>'string', 'options'=>'array'],
'XSLTProcessor::setProfiling' => ['bool', 'filename'=>'string'],
'XsltProcessor::setSecurityPrefs' => ['int', 'preferences'=>'int'],
'XSLTProcessor::transformToDoc' => ['DOMDocument|false', 'document'=>'DOMNode'],
'XSLTProcessor::transformToURI' => ['int', 'document'=>'DOMDocument', 'uri'=>'string'],
'XSLTProcessor::transformToXML' => ['string|false', 'document'=>'DOMDocument'],
'yac::__construct' => ['void', 'prefix='=>'string'],
'yac::__get' => ['mixed', 'key'=>'string'],
'yac::__set' => ['mixed', 'key'=>'string', 'value'=>'mixed'],
'yac::delete' => ['bool', 'keys'=>'string|array', 'ttl='=>'int'],
'yac::dump' => ['mixed', 'num'=>'int'],
'yac::flush' => ['bool'],
'yac::get' => ['mixed', 'key'=>'string|array', 'cas='=>'int'],
'yac::info' => ['array'],
'Yaconf::get' => ['mixed', 'name'=>'string', 'default_value='=>'mixed'],
'Yaconf::has' => ['bool', 'name'=>'string'],
'Yaf\Action_Abstract::__clone' => ['void'],
'Yaf\Action_Abstract::__construct' => ['void', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract', 'view'=>'Yaf\View_Interface', 'invokeArgs='=>'?array'],
'Yaf\Action_Abstract::display' => ['bool', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf\Action_Abstract::execute' => ['mixed'],
'Yaf\Action_Abstract::forward' => ['bool', 'module'=>'string', 'controller='=>'string', 'action='=>'string', 'parameters='=>'?array'],
'Yaf\Action_Abstract::getController' => ['Yaf\Controller_Abstract'],
'Yaf\Action_Abstract::getInvokeArg' => ['mixed|null', 'name'=>'string'],
'Yaf\Action_Abstract::getInvokeArgs' => ['array'],
'Yaf\Action_Abstract::getModuleName' => ['string'],
'Yaf\Action_Abstract::getRequest' => ['Yaf\Request_Abstract'],
'Yaf\Action_Abstract::getResponse' => ['Yaf\Response_Abstract'],
'Yaf\Action_Abstract::getView' => ['Yaf\View_Interface'],
'Yaf\Action_Abstract::getViewpath' => ['string'],
'Yaf\Action_Abstract::init' => [''],
'Yaf\Action_Abstract::initView' => ['Yaf\Response_Abstract', 'options='=>'?array'],
'Yaf\Action_Abstract::redirect' => ['bool', 'url'=>'string'],
'Yaf\Action_Abstract::render' => ['string', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf\Action_Abstract::setViewpath' => ['bool', 'view_directory'=>'string'],
'Yaf\Application::__clone' => ['void'],
'Yaf\Application::__construct' => ['void', 'config'=>'array|string', 'envrion='=>'string'],
'Yaf\Application::__destruct' => ['void'],
'Yaf\Application::__sleep' => ['string[]'],
'Yaf\Application::__wakeup' => ['void'],
'Yaf\Application::app' => ['?Yaf\Application'],
'Yaf\Application::bootstrap' => ['Yaf\Application', 'bootstrap='=>'?Yaf\Bootstrap_Abstract'],
'Yaf\Application::clearLastError' => ['void'],
'Yaf\Application::environ' => ['string'],
'Yaf\Application::execute' => ['void', 'entry'=>'callable', '_='=>'string'],
'Yaf\Application::getAppDirectory' => ['string'],
'Yaf\Application::getConfig' => ['Yaf\Config_Abstract'],
'Yaf\Application::getDispatcher' => ['Yaf\Dispatcher'],
'Yaf\Application::getLastErrorMsg' => ['string'],
'Yaf\Application::getLastErrorNo' => ['int'],
'Yaf\Application::getModules' => ['array'],
'Yaf\Application::run' => ['void'],
'Yaf\Application::setAppDirectory' => ['Yaf\Application', 'directory'=>'string'],
'Yaf\Config\Ini::__construct' => ['void', 'config_file'=>'string', 'section='=>'string'],
'Yaf\Config\Ini::__get' => ['', 'name='=>'mixed'],
'Yaf\Config\Ini::__isset' => ['', 'name'=>'string'],
'Yaf\Config\Ini::__set' => ['void', 'name'=>'', 'value'=>''],
'Yaf\Config\Ini::count' => ['int'],
'Yaf\Config\Ini::current' => ['mixed'],
'Yaf\Config\Ini::get' => ['mixed', 'name='=>'mixed'],
'Yaf\Config\Ini::key' => ['int|string'],
'Yaf\Config\Ini::next' => ['void'],
'Yaf\Config\Ini::offsetExists' => ['bool', 'name'=>'mixed'],
'Yaf\Config\Ini::offsetGet' => ['mixed', 'name'=>'mixed'],
'Yaf\Config\Ini::offsetSet' => ['void', 'name'=>'mixed', 'value'=>'mixed'],
'Yaf\Config\Ini::offsetUnset' => ['void', 'name'=>'mixed'],
'Yaf\Config\Ini::readonly' => ['bool'],
'Yaf\Config\Ini::rewind' => ['void'],
'Yaf\Config\Ini::set' => ['Yaf\Config_Abstract', 'name'=>'string', 'value'=>'mixed'],
'Yaf\Config\Ini::toArray' => ['array'],
'Yaf\Config\Ini::valid' => ['bool'],
'Yaf\Config\Simple::__construct' => ['void', 'array'=>'array', 'readonly='=>'string'],
'Yaf\Config\Simple::__get' => ['', 'name='=>'mixed'],
'Yaf\Config\Simple::__isset' => ['', 'name'=>'string'],
'Yaf\Config\Simple::__set' => ['void', 'name'=>'', 'value'=>''],
'Yaf\Config\Simple::count' => ['int'],
'Yaf\Config\Simple::current' => ['mixed'],
'Yaf\Config\Simple::get' => ['mixed', 'name='=>'mixed'],
'Yaf\Config\Simple::key' => ['int|string'],
'Yaf\Config\Simple::next' => ['void'],
'Yaf\Config\Simple::offsetExists' => ['bool', 'name'=>'mixed'],
'Yaf\Config\Simple::offsetGet' => ['mixed', 'name'=>'mixed'],
'Yaf\Config\Simple::offsetSet' => ['void', 'name'=>'mixed', 'value'=>'mixed'],
'Yaf\Config\Simple::offsetUnset' => ['void', 'name'=>'mixed'],
'Yaf\Config\Simple::readonly' => ['bool'],
'Yaf\Config\Simple::rewind' => ['void'],
'Yaf\Config\Simple::set' => ['Yaf\Config_Abstract', 'name'=>'string', 'value'=>'mixed'],
'Yaf\Config\Simple::toArray' => ['array'],
'Yaf\Config\Simple::valid' => ['bool'],
'Yaf\Config_Abstract::__construct' => ['void'],
'Yaf\Config_Abstract::get' => ['mixed', 'name='=>'string'],
'Yaf\Config_Abstract::readonly' => ['bool'],
'Yaf\Config_Abstract::set' => ['Yaf\Config_Abstract', 'name'=>'string', 'value'=>'mixed'],
'Yaf\Config_Abstract::toArray' => ['array'],
'Yaf\Controller_Abstract::__clone' => ['void'],
'Yaf\Controller_Abstract::__construct' => ['void', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract', 'view'=>'Yaf\View_Interface', 'invokeArgs='=>'?array'],
'Yaf\Controller_Abstract::display' => ['bool', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf\Controller_Abstract::forward' => ['bool', 'module'=>'string', 'controller='=>'string', 'action='=>'string', 'parameters='=>'?array'],
'Yaf\Controller_Abstract::getInvokeArg' => ['mixed|null', 'name'=>'string'],
'Yaf\Controller_Abstract::getInvokeArgs' => ['array'],
'Yaf\Controller_Abstract::getModuleName' => ['string'],
'Yaf\Controller_Abstract::getRequest' => ['Yaf\Request_Abstract'],
'Yaf\Controller_Abstract::getResponse' => ['Yaf\Response_Abstract'],
'Yaf\Controller_Abstract::getView' => ['Yaf\View_Interface'],
'Yaf\Controller_Abstract::getViewpath' => ['string'],
'Yaf\Controller_Abstract::init' => [''],
'Yaf\Controller_Abstract::initView' => ['Yaf\Response_Abstract', 'options='=>'?array'],
'Yaf\Controller_Abstract::redirect' => ['bool', 'url'=>'string'],
'Yaf\Controller_Abstract::render' => ['string', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf\Controller_Abstract::setViewpath' => ['bool', 'view_directory'=>'string'],
'Yaf\Dispatcher::__clone' => ['void'],
'Yaf\Dispatcher::__construct' => ['void'],
'Yaf\Dispatcher::__sleep' => ['list<string>'],
'Yaf\Dispatcher::__wakeup' => ['void'],
'Yaf\Dispatcher::autoRender' => ['Yaf\Dispatcher', 'flag='=>'bool'],
'Yaf\Dispatcher::catchException' => ['Yaf\Dispatcher', 'flag='=>'bool'],
'Yaf\Dispatcher::disableView' => ['bool'],
'Yaf\Dispatcher::dispatch' => ['Yaf\Response_Abstract', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Dispatcher::enableView' => ['Yaf\Dispatcher'],
'Yaf\Dispatcher::flushInstantly' => ['Yaf\Dispatcher', 'flag='=>'bool'],
'Yaf\Dispatcher::getApplication' => ['Yaf\Application'],
'Yaf\Dispatcher::getInstance' => ['Yaf\Dispatcher'],
'Yaf\Dispatcher::getRequest' => ['Yaf\Request_Abstract'],
'Yaf\Dispatcher::getRouter' => ['Yaf\Router'],
'Yaf\Dispatcher::initView' => ['Yaf\View_Interface', 'templates_dir'=>'string', 'options='=>'?array'],
'Yaf\Dispatcher::registerPlugin' => ['Yaf\Dispatcher', 'plugin'=>'Yaf\Plugin_Abstract'],
'Yaf\Dispatcher::returnResponse' => ['Yaf\Dispatcher', 'flag'=>'bool'],
'Yaf\Dispatcher::setDefaultAction' => ['Yaf\Dispatcher', 'action'=>'string'],
'Yaf\Dispatcher::setDefaultController' => ['Yaf\Dispatcher', 'controller'=>'string'],
'Yaf\Dispatcher::setDefaultModule' => ['Yaf\Dispatcher', 'module'=>'string'],
'Yaf\Dispatcher::setErrorHandler' => ['Yaf\Dispatcher', 'callback'=>'callable', 'error_types'=>'int'],
'Yaf\Dispatcher::setRequest' => ['Yaf\Dispatcher', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Dispatcher::setView' => ['Yaf\Dispatcher', 'view'=>'Yaf\View_Interface'],
'Yaf\Dispatcher::throwException' => ['Yaf\Dispatcher', 'flag='=>'bool'],
'Yaf\Loader::__clone' => ['void'],
'Yaf\Loader::__construct' => ['void'],
'Yaf\Loader::__sleep' => ['list<string>'],
'Yaf\Loader::__wakeup' => ['void'],
'Yaf\Loader::autoload' => ['bool', 'class_name'=>'string'],
'Yaf\Loader::clearLocalNamespace' => [''],
'Yaf\Loader::getInstance' => ['Yaf\Loader', 'local_library_path='=>'string', 'global_library_path='=>'string'],
'Yaf\Loader::getLibraryPath' => ['string', 'is_global='=>'bool'],
'Yaf\Loader::getLocalNamespace' => ['string'],
'Yaf\Loader::import' => ['bool', 'file'=>'string'],
'Yaf\Loader::isLocalName' => ['bool', 'class_name'=>'string'],
'Yaf\Loader::registerLocalNamespace' => ['bool', 'name_prefix'=>'string|string[]'],
'Yaf\Loader::setLibraryPath' => ['Yaf\Loader', 'directory'=>'string', 'global='=>'bool'],
'Yaf\Plugin_Abstract::dispatchLoopShutdown' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::dispatchLoopStartup' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::postDispatch' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::preDispatch' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::preResponse' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::routerShutdown' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::routerStartup' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Registry::__clone' => ['void'],
'Yaf\Registry::__construct' => ['void'],
'Yaf\Registry::del' => ['bool|void', 'name'=>'string'],
'Yaf\Registry::get' => ['mixed', 'name'=>'string'],
'Yaf\Registry::has' => ['bool', 'name'=>'string'],
'Yaf\Registry::set' => ['bool', 'name'=>'string', 'value'=>'mixed'],
'Yaf\Request\Http::__clone' => ['void'],
'Yaf\Request\Http::__construct' => ['void', 'request_uri'=>'string', 'base_uri'=>'string'],
'Yaf\Request\Http::get' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf\Request\Http::getActionName' => ['string'],
'Yaf\Request\Http::getBaseUri' => ['string'],
'Yaf\Request\Http::getControllerName' => ['string'],
'Yaf\Request\Http::getCookie' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getEnv' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getException' => ['Yaf\Exception'],
'Yaf\Request\Http::getFiles' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getLanguage' => ['string'],
'Yaf\Request\Http::getMethod' => ['string'],
'Yaf\Request\Http::getModuleName' => ['string'],
'Yaf\Request\Http::getParam' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getParams' => ['array'],
'Yaf\Request\Http::getPost' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getQuery' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getRequest' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getRequestUri' => ['string'],
'Yaf\Request\Http::getServer' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::isCli' => ['bool'],
'Yaf\Request\Http::isDispatched' => ['bool'],
'Yaf\Request\Http::isGet' => ['bool'],
'Yaf\Request\Http::isHead' => ['bool'],
'Yaf\Request\Http::isOptions' => ['bool'],
'Yaf\Request\Http::isPost' => ['bool'],
'Yaf\Request\Http::isPut' => ['bool'],
'Yaf\Request\Http::isRouted' => ['bool'],
'Yaf\Request\Http::isXmlHttpRequest' => ['bool'],
'Yaf\Request\Http::setActionName' => ['Yaf\Request_Abstract|bool', 'action'=>'string'],
'Yaf\Request\Http::setBaseUri' => ['bool', 'uri'=>'string'],
'Yaf\Request\Http::setControllerName' => ['Yaf\Request_Abstract|bool', 'controller'=>'string'],
'Yaf\Request\Http::setDispatched' => ['bool'],
'Yaf\Request\Http::setModuleName' => ['Yaf\Request_Abstract|bool', 'module'=>'string'],
'Yaf\Request\Http::setParam' => ['Yaf\Request_Abstract|bool', 'name'=>'array|string', 'value='=>'string'],
'Yaf\Request\Http::setRequestUri' => ['', 'uri'=>'string'],
'Yaf\Request\Http::setRouted' => ['Yaf\Request_Abstract|bool'],
'Yaf\Request\Simple::__clone' => ['void'],
'Yaf\Request\Simple::__construct' => ['void', 'method'=>'string', 'controller'=>'string', 'action'=>'string', 'params='=>'string'],
'Yaf\Request\Simple::get' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf\Request\Simple::getActionName' => ['string'],
'Yaf\Request\Simple::getBaseUri' => ['string'],
'Yaf\Request\Simple::getControllerName' => ['string'],
'Yaf\Request\Simple::getCookie' => ['mixed', 'name='=>'string', 'default='=>'string'],
'Yaf\Request\Simple::getEnv' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Simple::getException' => ['Yaf\Exception'],
'Yaf\Request\Simple::getFiles' => ['array', 'name='=>'mixed', 'default='=>'null'],
'Yaf\Request\Simple::getLanguage' => ['string'],
'Yaf\Request\Simple::getMethod' => ['string'],
'Yaf\Request\Simple::getModuleName' => ['string'],
'Yaf\Request\Simple::getParam' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'Yaf\Request\Simple::getParams' => ['array'],
'Yaf\Request\Simple::getPost' => ['mixed', 'name='=>'string', 'default='=>'string'],
'Yaf\Request\Simple::getQuery' => ['mixed', 'name='=>'string', 'default='=>'string'],
'Yaf\Request\Simple::getRequest' => ['mixed', 'name='=>'string', 'default='=>'string'],
'Yaf\Request\Simple::getRequestUri' => ['string'],
'Yaf\Request\Simple::getServer' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Simple::isCli' => ['bool'],
'Yaf\Request\Simple::isDispatched' => ['bool'],
'Yaf\Request\Simple::isGet' => ['bool'],
'Yaf\Request\Simple::isHead' => ['bool'],
'Yaf\Request\Simple::isOptions' => ['bool'],
'Yaf\Request\Simple::isPost' => ['bool'],
'Yaf\Request\Simple::isPut' => ['bool'],
'Yaf\Request\Simple::isRouted' => ['bool'],
'Yaf\Request\Simple::isXmlHttpRequest' => ['bool'],
'Yaf\Request\Simple::setActionName' => ['Yaf\Request_Abstract|bool', 'action'=>'string'],
'Yaf\Request\Simple::setBaseUri' => ['bool', 'uri'=>'string'],
'Yaf\Request\Simple::setControllerName' => ['Yaf\Request_Abstract|bool', 'controller'=>'string'],
'Yaf\Request\Simple::setDispatched' => ['bool'],
'Yaf\Request\Simple::setModuleName' => ['Yaf\Request_Abstract|bool', 'module'=>'string'],
'Yaf\Request\Simple::setParam' => ['Yaf\Request_Abstract|bool', 'name'=>'array|string', 'value='=>'string'],
'Yaf\Request\Simple::setRequestUri' => ['', 'uri'=>'string'],
'Yaf\Request\Simple::setRouted' => ['Yaf\Request_Abstract|bool'],
'Yaf\Request_Abstract::getActionName' => ['string'],
'Yaf\Request_Abstract::getBaseUri' => ['string'],
'Yaf\Request_Abstract::getControllerName' => ['string'],
'Yaf\Request_Abstract::getEnv' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request_Abstract::getException' => ['Yaf\Exception'],
'Yaf\Request_Abstract::getLanguage' => ['string'],
'Yaf\Request_Abstract::getMethod' => ['string'],
'Yaf\Request_Abstract::getModuleName' => ['string'],
'Yaf\Request_Abstract::getParam' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'Yaf\Request_Abstract::getParams' => ['array'],
'Yaf\Request_Abstract::getRequestUri' => ['string'],
'Yaf\Request_Abstract::getServer' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request_Abstract::isCli' => ['bool'],
'Yaf\Request_Abstract::isDispatched' => ['bool'],
'Yaf\Request_Abstract::isGet' => ['bool'],
'Yaf\Request_Abstract::isHead' => ['bool'],
'Yaf\Request_Abstract::isOptions' => ['bool'],
'Yaf\Request_Abstract::isPost' => ['bool'],
'Yaf\Request_Abstract::isPut' => ['bool'],
'Yaf\Request_Abstract::isRouted' => ['bool'],
'Yaf\Request_Abstract::isXmlHttpRequest' => ['bool'],
'Yaf\Request_Abstract::setActionName' => ['Yaf\Request_Abstract|bool', 'action'=>'string'],
'Yaf\Request_Abstract::setBaseUri' => ['bool', 'uri'=>'string'],
'Yaf\Request_Abstract::setControllerName' => ['Yaf\Request_Abstract|bool', 'controller'=>'string'],
'Yaf\Request_Abstract::setDispatched' => ['bool'],
'Yaf\Request_Abstract::setModuleName' => ['Yaf\Request_Abstract|bool', 'module'=>'string'],
'Yaf\Request_Abstract::setParam' => ['Yaf\Request_Abstract|bool', 'name'=>'array|string', 'value='=>'string'],
'Yaf\Request_Abstract::setRequestUri' => ['', 'uri'=>'string'],
'Yaf\Request_Abstract::setRouted' => ['Yaf\Request_Abstract|bool'],
'Yaf\Response\Cli::__clone' => ['void'],
'Yaf\Response\Cli::__construct' => ['void'],
'Yaf\Response\Cli::__destruct' => ['void'],
'Yaf\Response\Cli::__toString' => ['string'],
'Yaf\Response\Cli::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Cli::clearBody' => ['bool', 'key='=>'string'],
'Yaf\Response\Cli::getBody' => ['mixed', 'key='=>'?string'],
'Yaf\Response\Cli::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Cli::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Http::__clone' => ['void'],
'Yaf\Response\Http::__construct' => ['void'],
'Yaf\Response\Http::__destruct' => ['void'],
'Yaf\Response\Http::__toString' => ['string'],
'Yaf\Response\Http::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Http::clearBody' => ['bool', 'key='=>'string'],
'Yaf\Response\Http::clearHeaders' => ['Yaf\Response_Abstract|false', 'name='=>'string'],
'Yaf\Response\Http::getBody' => ['mixed', 'key='=>'?string'],
'Yaf\Response\Http::getHeader' => ['mixed', 'name='=>'string'],
'Yaf\Response\Http::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Http::response' => ['bool'],
'Yaf\Response\Http::setAllHeaders' => ['bool', 'headers'=>'array'],
'Yaf\Response\Http::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Http::setHeader' => ['bool', 'name'=>'string', 'value'=>'string', 'replace='=>'bool', 'response_code='=>'int'],
'Yaf\Response\Http::setRedirect' => ['bool', 'url'=>'string'],
'Yaf\Response_Abstract::__clone' => ['void'],
'Yaf\Response_Abstract::__construct' => ['void'],
'Yaf\Response_Abstract::__destruct' => ['void'],
'Yaf\Response_Abstract::__toString' => ['void'],
'Yaf\Response_Abstract::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response_Abstract::clearBody' => ['bool', 'key='=>'string'],
'Yaf\Response_Abstract::getBody' => ['mixed', 'key='=>'?string'],
'Yaf\Response_Abstract::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response_Abstract::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Route\Map::__construct' => ['void', 'controller_prefer='=>'bool', 'delimiter='=>'string'],
'Yaf\Route\Map::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route\Map::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route\Regex::__construct' => ['void', 'match'=>'string', 'route'=>'array', 'map='=>'?array', 'verify='=>'?array', 'reverse='=>'string'],
'Yaf\Route\Regex::addConfig' => ['Yaf\Router|bool', 'config'=>'Yaf\Config_Abstract'],
'Yaf\Route\Regex::addRoute' => ['Yaf\Router|bool', 'name'=>'string', 'route'=>'Yaf\Route_Interface'],
'Yaf\Route\Regex::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route\Regex::getCurrentRoute' => ['string'],
'Yaf\Route\Regex::getRoute' => ['Yaf\Route_Interface', 'name'=>'string'],
'Yaf\Route\Regex::getRoutes' => ['Yaf\Route_Interface[]'],
'Yaf\Route\Regex::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route\Rewrite::__construct' => ['void', 'match'=>'string', 'route'=>'array', 'verify='=>'?array', 'reverse='=>'string'],
'Yaf\Route\Rewrite::addConfig' => ['Yaf\Router|bool', 'config'=>'Yaf\Config_Abstract'],
'Yaf\Route\Rewrite::addRoute' => ['Yaf\Router|bool', 'name'=>'string', 'route'=>'Yaf\Route_Interface'],
'Yaf\Route\Rewrite::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route\Rewrite::getCurrentRoute' => ['string'],
'Yaf\Route\Rewrite::getRoute' => ['Yaf\Route_Interface', 'name'=>'string'],
'Yaf\Route\Rewrite::getRoutes' => ['Yaf\Route_Interface[]'],
'Yaf\Route\Rewrite::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route\Simple::__construct' => ['void', 'module_name'=>'string', 'controller_name'=>'string', 'action_name'=>'string'],
'Yaf\Route\Simple::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route\Simple::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route\Supervar::__construct' => ['void', 'supervar_name'=>'string'],
'Yaf\Route\Supervar::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route\Supervar::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route_Interface::__construct' => ['Yaf\Route_Interface'],
'Yaf\Route_Interface::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route_Interface::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route_Static::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route_Static::match' => ['bool', 'uri'=>'string'],
'Yaf\Route_Static::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Router::__construct' => ['void'],
'Yaf\Router::addConfig' => ['Yaf\Router|false', 'config'=>'Yaf\Config_Abstract'],
'Yaf\Router::addRoute' => ['Yaf\Router|false', 'name'=>'string', 'route'=>'Yaf\Route_Interface'],
'Yaf\Router::getCurrentRoute' => ['string'],
'Yaf\Router::getRoute' => ['Yaf\Route_Interface', 'name'=>'string'],
'Yaf\Router::getRoutes' => ['Yaf\Route_Interface[]'],
'Yaf\Router::route' => ['Yaf\Router|false', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Session::__clone' => ['void'],
'Yaf\Session::__construct' => ['void'],
'Yaf\Session::__get' => ['void', 'name'=>''],
'Yaf\Session::__isset' => ['void', 'name'=>''],
'Yaf\Session::__set' => ['void', 'name'=>'', 'value'=>''],
'Yaf\Session::__sleep' => ['list<string>'],
'Yaf\Session::__unset' => ['void', 'name'=>''],
'Yaf\Session::__wakeup' => ['void'],
'Yaf\Session::count' => ['int'],
'Yaf\Session::current' => ['mixed'],
'Yaf\Session::del' => ['Yaf\Session|false', 'name'=>'string'],
'Yaf\Session::get' => ['mixed', 'name'=>'string'],
'Yaf\Session::getInstance' => ['Yaf\Session'],
'Yaf\Session::has' => ['bool', 'name'=>'string'],
'Yaf\Session::key' => ['int|string'],
'Yaf\Session::next' => ['void'],
'Yaf\Session::offsetExists' => ['bool', 'name'=>'mixed'],
'Yaf\Session::offsetGet' => ['mixed', 'name'=>'mixed'],
'Yaf\Session::offsetSet' => ['void', 'name'=>'mixed', 'value'=>'mixed'],
'Yaf\Session::offsetUnset' => ['void', 'name'=>'mixed'],
'Yaf\Session::rewind' => ['void'],
'Yaf\Session::set' => ['Yaf\Session|false', 'name'=>'string', 'value'=>'mixed'],
'Yaf\Session::start' => ['Yaf\Session'],
'Yaf\Session::valid' => ['bool'],
'Yaf\View\Simple::__construct' => ['void', 'template_dir'=>'string', 'options='=>'?array'],
'Yaf\View\Simple::__get' => ['mixed', 'name='=>'null'],
'Yaf\View\Simple::__isset' => ['', 'name'=>'string'],
'Yaf\View\Simple::__set' => ['void', 'name'=>'string', 'value='=>'mixed'],
'Yaf\View\Simple::assign' => ['Yaf\View\Simple', 'name'=>'array|string', 'value='=>'mixed'],
'Yaf\View\Simple::assignRef' => ['Yaf\View\Simple', 'name'=>'string', '&value'=>'mixed'],
'Yaf\View\Simple::clear' => ['Yaf\View\Simple', 'name='=>'string'],
'Yaf\View\Simple::display' => ['bool', 'tpl'=>'string', 'tpl_vars='=>'?array'],
'Yaf\View\Simple::eval' => ['bool|void', 'tpl_str'=>'string', 'vars='=>'?array'],
'Yaf\View\Simple::getScriptPath' => ['string'],
'Yaf\View\Simple::render' => ['string|void', 'tpl'=>'string', 'tpl_vars='=>'?array'],
'Yaf\View\Simple::setScriptPath' => ['Yaf\View\Simple', 'template_dir'=>'string'],
'Yaf\View_Interface::assign' => ['bool', 'name'=>'array|string', 'value'=>'mixed'],
'Yaf\View_Interface::display' => ['bool', 'tpl'=>'string', 'tpl_vars='=>'?array'],
'Yaf\View_Interface::getScriptPath' => ['string'],
'Yaf\View_Interface::render' => ['string', 'tpl'=>'string', 'tpl_vars='=>'?array'],
'Yaf\View_Interface::setScriptPath' => ['void', 'template_dir'=>'string'],
'Yaf_Action_Abstract::__clone' => ['void'],
'Yaf_Action_Abstract::__construct' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract', 'view'=>'Yaf_View_Interface', 'invokeArgs='=>'?array'],
'Yaf_Action_Abstract::display' => ['bool', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf_Action_Abstract::execute' => ['mixed', 'arg='=>'mixed', '...args='=>'mixed'],
'Yaf_Action_Abstract::forward' => ['bool', 'module'=>'string', 'controller='=>'string', 'action='=>'string', 'parameters='=>'?array'],
'Yaf_Action_Abstract::getController' => ['Yaf_Controller_Abstract'],
'Yaf_Action_Abstract::getControllerName' => ['string'],
'Yaf_Action_Abstract::getInvokeArg' => ['mixed|null', 'name'=>'string'],
'Yaf_Action_Abstract::getInvokeArgs' => ['array'],
'Yaf_Action_Abstract::getModuleName' => ['string'],
'Yaf_Action_Abstract::getRequest' => ['Yaf_Request_Abstract'],
'Yaf_Action_Abstract::getResponse' => ['Yaf_Response_Abstract'],
'Yaf_Action_Abstract::getView' => ['Yaf_View_Interface'],
'Yaf_Action_Abstract::getViewpath' => ['string'],
'Yaf_Action_Abstract::init' => [''],
'Yaf_Action_Abstract::initView' => ['Yaf_Response_Abstract', 'options='=>'?array'],
'Yaf_Action_Abstract::redirect' => ['bool', 'url'=>'string'],
'Yaf_Action_Abstract::render' => ['string', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf_Action_Abstract::setViewpath' => ['bool', 'view_directory'=>'string'],
'Yaf_Application::__clone' => ['void'],
'Yaf_Application::__construct' => ['void', 'config'=>'mixed', 'envrion='=>'string'],
'Yaf_Application::__destruct' => ['void'],
'Yaf_Application::__sleep' => ['list<string>'],
'Yaf_Application::__wakeup' => ['void'],
'Yaf_Application::app' => ['?Yaf_Application'],
'Yaf_Application::bootstrap' => ['Yaf_Application', 'bootstrap='=>'Yaf_Bootstrap_Abstract'],
'Yaf_Application::clearLastError' => ['Yaf_Application'],
'Yaf_Application::environ' => ['string'],
'Yaf_Application::execute' => ['void', 'entry'=>'callable', '...args'=>'string'],
'Yaf_Application::getAppDirectory' => ['Yaf_Application'],
'Yaf_Application::getConfig' => ['Yaf_Config_Abstract'],
'Yaf_Application::getDispatcher' => ['Yaf_Dispatcher'],
'Yaf_Application::getLastErrorMsg' => ['string'],
'Yaf_Application::getLastErrorNo' => ['int'],
'Yaf_Application::getModules' => ['array'],
'Yaf_Application::run' => ['void'],
'Yaf_Application::setAppDirectory' => ['Yaf_Application', 'directory'=>'string'],
'Yaf_Config_Abstract::__construct' => ['void'],
'Yaf_Config_Abstract::get' => ['mixed', 'name'=>'string', 'value'=>'mixed'],
'Yaf_Config_Abstract::readonly' => ['bool'],
'Yaf_Config_Abstract::set' => ['Yaf_Config_Abstract'],
'Yaf_Config_Abstract::toArray' => ['array'],
'Yaf_Config_Ini::__construct' => ['void', 'config_file'=>'string', 'section='=>'string'],
'Yaf_Config_Ini::__get' => ['void', 'name='=>'string'],
'Yaf_Config_Ini::__isset' => ['void', 'name'=>'string'],
'Yaf_Config_Ini::__set' => ['void', 'name'=>'string', 'value'=>'mixed'],
'Yaf_Config_Ini::count' => ['void'],
'Yaf_Config_Ini::current' => ['void'],
'Yaf_Config_Ini::get' => ['mixed', 'name='=>'mixed'],
'Yaf_Config_Ini::key' => ['void'],
'Yaf_Config_Ini::next' => ['void'],
'Yaf_Config_Ini::offsetExists' => ['void', 'name'=>'string'],
'Yaf_Config_Ini::offsetGet' => ['void', 'name'=>'string'],
'Yaf_Config_Ini::offsetSet' => ['void', 'name'=>'string', 'value'=>'string'],
'Yaf_Config_Ini::offsetUnset' => ['void', 'name'=>'string'],
'Yaf_Config_Ini::readonly' => ['void'],
'Yaf_Config_Ini::rewind' => ['void'],
'Yaf_Config_Ini::set' => ['Yaf_Config_Abstract', 'name'=>'string', 'value'=>'mixed'],
'Yaf_Config_Ini::toArray' => ['array'],
'Yaf_Config_Ini::valid' => ['void'],
'Yaf_Config_Simple::__construct' => ['void', 'config_file'=>'string', 'section='=>'string'],
'Yaf_Config_Simple::__get' => ['void', 'name='=>'string'],
'Yaf_Config_Simple::__isset' => ['void', 'name'=>'string'],
'Yaf_Config_Simple::__set' => ['void', 'name'=>'string', 'value'=>'string'],
'Yaf_Config_Simple::count' => ['void'],
'Yaf_Config_Simple::current' => ['void'],
'Yaf_Config_Simple::get' => ['mixed', 'name='=>'mixed'],
'Yaf_Config_Simple::key' => ['void'],
'Yaf_Config_Simple::next' => ['void'],
'Yaf_Config_Simple::offsetExists' => ['void', 'name'=>'string'],
'Yaf_Config_Simple::offsetGet' => ['void', 'name'=>'string'],
'Yaf_Config_Simple::offsetSet' => ['void', 'name'=>'string', 'value'=>'string'],
'Yaf_Config_Simple::offsetUnset' => ['void', 'name'=>'string'],
'Yaf_Config_Simple::readonly' => ['void'],
'Yaf_Config_Simple::rewind' => ['void'],
'Yaf_Config_Simple::set' => ['Yaf_Config_Abstract', 'name'=>'string', 'value'=>'mixed'],
'Yaf_Config_Simple::toArray' => ['array'],
'Yaf_Config_Simple::valid' => ['void'],
'Yaf_Controller_Abstract::__clone' => ['void'],
'Yaf_Controller_Abstract::__construct' => ['void'],
'Yaf_Controller_Abstract::display' => ['bool', 'tpl'=>'string', 'parameters='=>'array'],
'Yaf_Controller_Abstract::forward' => ['void', 'action'=>'string', 'parameters='=>'array'],
'Yaf_Controller_Abstract::forward\'1' => ['void', 'controller'=>'string', 'action'=>'string', 'parameters='=>'array'],
'Yaf_Controller_Abstract::forward\'2' => ['void', 'module'=>'string', 'controller'=>'string', 'action'=>'string', 'parameters='=>'array'],
'Yaf_Controller_Abstract::getInvokeArg' => ['void', 'name'=>'string'],
'Yaf_Controller_Abstract::getInvokeArgs' => ['void'],
'Yaf_Controller_Abstract::getModuleName' => ['string'],
'Yaf_Controller_Abstract::getName' => ['string'],
'Yaf_Controller_Abstract::getRequest' => ['Yaf_Request_Abstract'],
'Yaf_Controller_Abstract::getResponse' => ['Yaf_Response_Abstract'],
'Yaf_Controller_Abstract::getView' => ['Yaf_View_Interface'],
'Yaf_Controller_Abstract::getViewpath' => ['void'],
'Yaf_Controller_Abstract::init' => ['void'],
'Yaf_Controller_Abstract::initView' => ['void', 'options='=>'array'],
'Yaf_Controller_Abstract::redirect' => ['bool', 'url'=>'string'],
'Yaf_Controller_Abstract::render' => ['string', 'tpl'=>'string', 'parameters='=>'array'],
'Yaf_Controller_Abstract::setViewpath' => ['void', 'view_directory'=>'string'],
'Yaf_Dispatcher::__clone' => ['void'],
'Yaf_Dispatcher::__construct' => ['void'],
'Yaf_Dispatcher::__sleep' => ['list<string>'],
'Yaf_Dispatcher::__wakeup' => ['void'],
'Yaf_Dispatcher::autoRender' => ['Yaf_Dispatcher', 'flag='=>'bool'],
'Yaf_Dispatcher::catchException' => ['Yaf_Dispatcher', 'flag='=>'bool'],
'Yaf_Dispatcher::disableView' => ['bool'],
'Yaf_Dispatcher::dispatch' => ['Yaf_Response_Abstract', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Dispatcher::enableView' => ['Yaf_Dispatcher'],
'Yaf_Dispatcher::flushInstantly' => ['Yaf_Dispatcher', 'flag='=>'bool'],
'Yaf_Dispatcher::getApplication' => ['Yaf_Application'],
'Yaf_Dispatcher::getDefaultAction' => ['string'],
'Yaf_Dispatcher::getDefaultController' => ['string'],
'Yaf_Dispatcher::getDefaultModule' => ['string'],
'Yaf_Dispatcher::getInstance' => ['Yaf_Dispatcher'],
'Yaf_Dispatcher::getRequest' => ['Yaf_Request_Abstract'],
'Yaf_Dispatcher::getRouter' => ['Yaf_Router'],
'Yaf_Dispatcher::initView' => ['Yaf_View_Interface', 'templates_dir'=>'string', 'options='=>'array'],
'Yaf_Dispatcher::registerPlugin' => ['Yaf_Dispatcher', 'plugin'=>'Yaf_Plugin_Abstract'],
'Yaf_Dispatcher::returnResponse' => ['Yaf_Dispatcher', 'flag'=>'bool'],
'Yaf_Dispatcher::setDefaultAction' => ['Yaf_Dispatcher', 'action'=>'string'],
'Yaf_Dispatcher::setDefaultController' => ['Yaf_Dispatcher', 'controller'=>'string'],
'Yaf_Dispatcher::setDefaultModule' => ['Yaf_Dispatcher', 'module'=>'string'],
'Yaf_Dispatcher::setErrorHandler' => ['Yaf_Dispatcher', 'callback'=>'callable', 'error_types'=>'int'],
'Yaf_Dispatcher::setRequest' => ['Yaf_Dispatcher', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Dispatcher::setView' => ['Yaf_Dispatcher', 'view'=>'Yaf_View_Interface'],
'Yaf_Dispatcher::throwException' => ['Yaf_Dispatcher', 'flag='=>'bool'],
'Yaf_Exception::__construct' => ['void'],
'Yaf_Exception::getPrevious' => ['void'],
'Yaf_Loader::__clone' => ['void'],
'Yaf_Loader::__construct' => ['void'],
'Yaf_Loader::__sleep' => ['list<string>'],
'Yaf_Loader::__wakeup' => ['void'],
'Yaf_Loader::autoload' => ['void'],
'Yaf_Loader::clearLocalNamespace' => ['void'],
'Yaf_Loader::getInstance' => ['Yaf_Loader'],
'Yaf_Loader::getLibraryPath' => ['Yaf_Loader', 'is_global='=>'bool'],
'Yaf_Loader::getLocalNamespace' => ['void'],
'Yaf_Loader::getNamespacePath' => ['string', 'namespaces'=>'string'],
'Yaf_Loader::import' => ['bool'],
'Yaf_Loader::isLocalName' => ['bool'],
'Yaf_Loader::registerLocalNamespace' => ['void', 'prefix'=>'mixed'],
'Yaf_Loader::registerNamespace' => ['bool', 'namespaces'=>'string|array', 'path='=>'string'],
'Yaf_Loader::setLibraryPath' => ['Yaf_Loader', 'directory'=>'string', 'is_global='=>'bool'],
'Yaf_Plugin_Abstract::dispatchLoopShutdown' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::dispatchLoopStartup' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::postDispatch' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::preDispatch' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::preResponse' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::routerShutdown' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::routerStartup' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Registry::__clone' => ['void'],
'Yaf_Registry::__construct' => ['void'],
'Yaf_Registry::del' => ['void', 'name'=>'string'],
'Yaf_Registry::get' => ['mixed', 'name'=>'string'],
'Yaf_Registry::has' => ['bool', 'name'=>'string'],
'Yaf_Registry::set' => ['bool', 'name'=>'string', 'value'=>'string'],
'Yaf_Request_Abstract::clearParams' => ['bool'],
'Yaf_Request_Abstract::getActionName' => ['void'],
'Yaf_Request_Abstract::getBaseUri' => ['void'],
'Yaf_Request_Abstract::getControllerName' => ['void'],
'Yaf_Request_Abstract::getEnv' => ['void', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Abstract::getException' => ['void'],
'Yaf_Request_Abstract::getLanguage' => ['void'],
'Yaf_Request_Abstract::getMethod' => ['void'],
'Yaf_Request_Abstract::getModuleName' => ['void'],
'Yaf_Request_Abstract::getParam' => ['void', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Abstract::getParams' => ['void'],
'Yaf_Request_Abstract::getRequestUri' => ['void'],
'Yaf_Request_Abstract::getServer' => ['void', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Abstract::isCli' => ['void'],
'Yaf_Request_Abstract::isDispatched' => ['void'],
'Yaf_Request_Abstract::isGet' => ['void'],
'Yaf_Request_Abstract::isHead' => ['void'],
'Yaf_Request_Abstract::isOptions' => ['void'],
'Yaf_Request_Abstract::isPost' => ['void'],
'Yaf_Request_Abstract::isPut' => ['void'],
'Yaf_Request_Abstract::isRouted' => ['void'],
'Yaf_Request_Abstract::isXmlHttpRequest' => ['void'],
'Yaf_Request_Abstract::setActionName' => ['void', 'action'=>'string'],
'Yaf_Request_Abstract::setBaseUri' => ['bool', 'uir'=>'string'],
'Yaf_Request_Abstract::setControllerName' => ['void', 'controller'=>'string'],
'Yaf_Request_Abstract::setDispatched' => ['void'],
'Yaf_Request_Abstract::setModuleName' => ['void', 'module'=>'string'],
'Yaf_Request_Abstract::setParam' => ['void', 'name'=>'string', 'value='=>'string'],
'Yaf_Request_Abstract::setRequestUri' => ['void', 'uir'=>'string'],
'Yaf_Request_Abstract::setRouted' => ['void', 'flag='=>'string'],
'Yaf_Request_Http::__clone' => ['void'],
'Yaf_Request_Http::__construct' => ['void'],
'Yaf_Request_Http::get' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Http::getActionName' => ['string'],
'Yaf_Request_Http::getBaseUri' => ['string'],
'Yaf_Request_Http::getControllerName' => ['string'],
'Yaf_Request_Http::getCookie' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Http::getEnv' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf_Request_Http::getException' => ['Yaf_Exception'],
'Yaf_Request_Http::getFiles' => ['void'],
'Yaf_Request_Http::getLanguage' => ['string'],
'Yaf_Request_Http::getMethod' => ['string'],
'Yaf_Request_Http::getModuleName' => ['string'],
'Yaf_Request_Http::getParam' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'Yaf_Request_Http::getParams' => ['array'],
'Yaf_Request_Http::getPost' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Http::getQuery' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Http::getRaw' => ['mixed'],
'Yaf_Request_Http::getRequest' => ['void'],
'Yaf_Request_Http::getRequestUri' => ['string'],
'Yaf_Request_Http::getServer' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf_Request_Http::isCli' => ['bool'],
'Yaf_Request_Http::isDispatched' => ['bool'],
'Yaf_Request_Http::isGet' => ['bool'],
'Yaf_Request_Http::isHead' => ['bool'],
'Yaf_Request_Http::isOptions' => ['bool'],
'Yaf_Request_Http::isPost' => ['bool'],
'Yaf_Request_Http::isPut' => ['bool'],
'Yaf_Request_Http::isRouted' => ['bool'],
'Yaf_Request_Http::isXmlHttpRequest' => ['bool'],
'Yaf_Request_Http::setActionName' => ['Yaf_Request_Abstract|bool', 'action'=>'string'],
'Yaf_Request_Http::setBaseUri' => ['bool', 'uri'=>'string'],
'Yaf_Request_Http::setControllerName' => ['Yaf_Request_Abstract|bool', 'controller'=>'string'],
'Yaf_Request_Http::setDispatched' => ['bool'],
'Yaf_Request_Http::setModuleName' => ['Yaf_Request_Abstract|bool', 'module'=>'string'],
'Yaf_Request_Http::setParam' => ['Yaf_Request_Abstract|bool', 'name'=>'array|string', 'value='=>'string'],
'Yaf_Request_Http::setRequestUri' => ['', 'uri'=>'string'],
'Yaf_Request_Http::setRouted' => ['Yaf_Request_Abstract|bool'],
'Yaf_Request_Simple::__clone' => ['void'],
'Yaf_Request_Simple::__construct' => ['void'],
'Yaf_Request_Simple::get' => ['void'],
'Yaf_Request_Simple::getActionName' => ['string'],
'Yaf_Request_Simple::getBaseUri' => ['string'],
'Yaf_Request_Simple::getControllerName' => ['string'],
'Yaf_Request_Simple::getCookie' => ['void'],
'Yaf_Request_Simple::getEnv' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf_Request_Simple::getException' => ['Yaf_Exception'],
'Yaf_Request_Simple::getFiles' => ['void'],
'Yaf_Request_Simple::getLanguage' => ['string'],
'Yaf_Request_Simple::getMethod' => ['string'],
'Yaf_Request_Simple::getModuleName' => ['string'],
'Yaf_Request_Simple::getParam' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'Yaf_Request_Simple::getParams' => ['array'],
'Yaf_Request_Simple::getPost' => ['void'],
'Yaf_Request_Simple::getQuery' => ['void'],
'Yaf_Request_Simple::getRequest' => ['void'],
'Yaf_Request_Simple::getRequestUri' => ['string'],
'Yaf_Request_Simple::getServer' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf_Request_Simple::isCli' => ['bool'],
'Yaf_Request_Simple::isDispatched' => ['bool'],
'Yaf_Request_Simple::isGet' => ['bool'],
'Yaf_Request_Simple::isHead' => ['bool'],
'Yaf_Request_Simple::isOptions' => ['bool'],
'Yaf_Request_Simple::isPost' => ['bool'],
'Yaf_Request_Simple::isPut' => ['bool'],
'Yaf_Request_Simple::isRouted' => ['bool'],
'Yaf_Request_Simple::isXmlHttpRequest' => ['void'],
'Yaf_Request_Simple::setActionName' => ['Yaf_Request_Abstract|bool', 'action'=>'string'],
'Yaf_Request_Simple::setBaseUri' => ['bool', 'uri'=>'string'],
'Yaf_Request_Simple::setControllerName' => ['Yaf_Request_Abstract|bool', 'controller'=>'string'],
'Yaf_Request_Simple::setDispatched' => ['bool'],
'Yaf_Request_Simple::setModuleName' => ['Yaf_Request_Abstract|bool', 'module'=>'string'],
'Yaf_Request_Simple::setParam' => ['Yaf_Request_Abstract|bool', 'name'=>'array|string', 'value='=>'string'],
'Yaf_Request_Simple::setRequestUri' => ['', 'uri'=>'string'],
'Yaf_Request_Simple::setRouted' => ['Yaf_Request_Abstract|bool'],
'Yaf_Response_Abstract::__clone' => ['void'],
'Yaf_Response_Abstract::__construct' => ['void'],
'Yaf_Response_Abstract::__destruct' => ['void'],
'Yaf_Response_Abstract::__toString' => ['string'],
'Yaf_Response_Abstract::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Abstract::clearBody' => ['bool', 'key='=>'string'],
'Yaf_Response_Abstract::clearHeaders' => ['void'],
'Yaf_Response_Abstract::getBody' => ['mixed', 'key='=>'string'],
'Yaf_Response_Abstract::getHeader' => ['void'],
'Yaf_Response_Abstract::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Abstract::response' => ['void'],
'Yaf_Response_Abstract::setAllHeaders' => ['void'],
'Yaf_Response_Abstract::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Abstract::setHeader' => ['void'],
'Yaf_Response_Abstract::setRedirect' => ['void'],
'Yaf_Response_Cli::__clone' => ['void'],
'Yaf_Response_Cli::__construct' => ['void'],
'Yaf_Response_Cli::__destruct' => ['void'],
'Yaf_Response_Cli::__toString' => ['string'],
'Yaf_Response_Cli::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Cli::clearBody' => ['bool', 'key='=>'string'],
'Yaf_Response_Cli::getBody' => ['mixed', 'key='=>'?string'],
'Yaf_Response_Cli::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Cli::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Http::__clone' => ['void'],
'Yaf_Response_Http::__construct' => ['void'],
'Yaf_Response_Http::__destruct' => ['void'],
'Yaf_Response_Http::__toString' => ['string'],
'Yaf_Response_Http::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Http::clearBody' => ['bool', 'key='=>'string'],
'Yaf_Response_Http::clearHeaders' => ['Yaf_Response_Abstract|false', 'name='=>'string'],
'Yaf_Response_Http::getBody' => ['mixed', 'key='=>'?string'],
'Yaf_Response_Http::getHeader' => ['mixed', 'name='=>'string'],
'Yaf_Response_Http::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Http::response' => ['bool'],
'Yaf_Response_Http::setAllHeaders' => ['bool', 'headers'=>'array'],
'Yaf_Response_Http::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Http::setHeader' => ['bool', 'name'=>'string', 'value'=>'string', 'replace='=>'bool', 'response_code='=>'int'],
'Yaf_Response_Http::setRedirect' => ['bool', 'url'=>'string'],
'Yaf_Route_Interface::__construct' => ['void'],
'Yaf_Route_Interface::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Interface::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Map::__construct' => ['void', 'controller_prefer='=>'string', 'delimiter='=>'string'],
'Yaf_Route_Map::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Map::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Regex::__construct' => ['void', 'match'=>'string', 'route'=>'array', 'map='=>'array', 'verify='=>'array', 'reverse='=>'string'],
'Yaf_Route_Regex::addConfig' => ['Yaf_Router|bool', 'config'=>'Yaf_Config_Abstract'],
'Yaf_Route_Regex::addRoute' => ['Yaf_Router|bool', 'name'=>'string', 'route'=>'Yaf_Route_Interface'],
'Yaf_Route_Regex::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Regex::getCurrentRoute' => ['string'],
'Yaf_Route_Regex::getRoute' => ['Yaf_Route_Interface', 'name'=>'string'],
'Yaf_Route_Regex::getRoutes' => ['Yaf_Route_Interface[]'],
'Yaf_Route_Regex::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Rewrite::__construct' => ['void', 'match'=>'string', 'route'=>'array', 'verify='=>'array'],
'Yaf_Route_Rewrite::addConfig' => ['Yaf_Router|bool', 'config'=>'Yaf_Config_Abstract'],
'Yaf_Route_Rewrite::addRoute' => ['Yaf_Router|bool', 'name'=>'string', 'route'=>'Yaf_Route_Interface'],
'Yaf_Route_Rewrite::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Rewrite::getCurrentRoute' => ['string'],
'Yaf_Route_Rewrite::getRoute' => ['Yaf_Route_Interface', 'name'=>'string'],
'Yaf_Route_Rewrite::getRoutes' => ['Yaf_Route_Interface[]'],
'Yaf_Route_Rewrite::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Simple::__construct' => ['void', 'module_name'=>'string', 'controller_name'=>'string', 'action_name'=>'string'],
'Yaf_Route_Simple::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Simple::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Static::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Static::match' => ['void', 'uri'=>'string'],
'Yaf_Route_Static::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Supervar::__construct' => ['void', 'supervar_name'=>'string'],
'Yaf_Route_Supervar::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Supervar::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Router::__construct' => ['void'],
'Yaf_Router::addConfig' => ['bool', 'config'=>'Yaf_Config_Abstract'],
'Yaf_Router::addRoute' => ['bool', 'name'=>'string', 'route'=>'Yaf_Route_Interface'],
'Yaf_Router::getCurrentRoute' => ['string'],
'Yaf_Router::getRoute' => ['Yaf_Route_Interface', 'name'=>'string'],
'Yaf_Router::getRoutes' => ['mixed'],
'Yaf_Router::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Session::__clone' => ['void'],
'Yaf_Session::__construct' => ['void'],
'Yaf_Session::__get' => ['void', 'name'=>'string'],
'Yaf_Session::__isset' => ['void', 'name'=>'string'],
'Yaf_Session::__set' => ['void', 'name'=>'string', 'value'=>'string'],
'Yaf_Session::__sleep' => ['list<string>'],
'Yaf_Session::__unset' => ['void', 'name'=>'string'],
'Yaf_Session::__wakeup' => ['void'],
'Yaf_Session::count' => ['void'],
'Yaf_Session::current' => ['void'],
'Yaf_Session::del' => ['void', 'name'=>'string'],
'Yaf_Session::get' => ['mixed', 'name'=>'string'],
'Yaf_Session::getInstance' => ['void'],
'Yaf_Session::has' => ['void', 'name'=>'string'],
'Yaf_Session::key' => ['void'],
'Yaf_Session::next' => ['void'],
'Yaf_Session::offsetExists' => ['void', 'name'=>'string'],
'Yaf_Session::offsetGet' => ['void', 'name'=>'string'],
'Yaf_Session::offsetSet' => ['void', 'name'=>'string', 'value'=>'string'],
'Yaf_Session::offsetUnset' => ['void', 'name'=>'string'],
'Yaf_Session::rewind' => ['void'],
'Yaf_Session::set' => ['Yaf_Session|bool', 'name'=>'string', 'value'=>'mixed'],
'Yaf_Session::start' => ['void'],
'Yaf_Session::valid' => ['void'],
'Yaf_View_Interface::assign' => ['bool', 'name'=>'string', 'value='=>'string'],
'Yaf_View_Interface::display' => ['bool', 'tpl'=>'string', 'tpl_vars='=>'array'],
'Yaf_View_Interface::getScriptPath' => ['string'],
'Yaf_View_Interface::render' => ['string', 'tpl'=>'string', 'tpl_vars='=>'array'],
'Yaf_View_Interface::setScriptPath' => ['void', 'template_dir'=>'string'],
'Yaf_View_Simple::__construct' => ['void', 'tempalte_dir'=>'string', 'options='=>'array'],
'Yaf_View_Simple::__get' => ['void', 'name='=>'string'],
'Yaf_View_Simple::__isset' => ['void', 'name'=>'string'],
'Yaf_View_Simple::__set' => ['void', 'name'=>'string', 'value'=>'mixed'],
'Yaf_View_Simple::assign' => ['bool', 'name'=>'string', 'value='=>'mixed'],
'Yaf_View_Simple::assignRef' => ['bool', 'name'=>'string', '&rw_value'=>'mixed'],
'Yaf_View_Simple::clear' => ['bool', 'name='=>'string'],
'Yaf_View_Simple::display' => ['bool', 'tpl'=>'string', 'tpl_vars='=>'array'],
'Yaf_View_Simple::eval' => ['string', 'tpl_content'=>'string', 'tpl_vars='=>'array'],
'Yaf_View_Simple::getScriptPath' => ['string'],
'Yaf_View_Simple::render' => ['string', 'tpl'=>'string', 'tpl_vars='=>'array'],
'Yaf_View_Simple::setScriptPath' => ['bool', 'template_dir'=>'string'],
'yaml_emit' => ['string', 'data'=>'mixed', 'encoding='=>'int', 'linebreak='=>'int'],
'yaml_emit_file' => ['bool', 'filename'=>'string', 'data'=>'mixed', 'encoding='=>'int', 'linebreak='=>'int'],
'yaml_parse' => ['mixed|false', 'input'=>'string', 'pos='=>'int', '&w_ndocs='=>'int', 'callbacks='=>'array'],
'yaml_parse_file' => ['mixed|false', 'filename'=>'string', 'pos='=>'int', '&w_ndocs='=>'int', 'callbacks='=>'array'],
'yaml_parse_url' => ['mixed|false', 'url'=>'string', 'pos='=>'int', '&w_ndocs='=>'int', 'callbacks='=>'array'],
'Yar_Client::__call' => ['void', 'method'=>'string', 'parameters'=>'array'],
'Yar_Client::__construct' => ['void', 'url'=>'string'],
'Yar_Client::setOpt' => ['Yar_Client|false', 'name'=>'int', 'value'=>'mixed'],
'Yar_Client_Exception::__clone' => ['void'],
'Yar_Client_Exception::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'Yar_Client_Exception::__toString' => ['string'],
'Yar_Client_Exception::__wakeup' => ['void'],
'Yar_Client_Exception::getCode' => ['int'],
'Yar_Client_Exception::getFile' => ['string'],
'Yar_Client_Exception::getLine' => ['int'],
'Yar_Client_Exception::getMessage' => ['string'],
'Yar_Client_Exception::getPrevious' => ['?Exception|?Throwable'],
'Yar_Client_Exception::getTrace' => ['list<array<string,mixed>>'],
'Yar_Client_Exception::getTraceAsString' => ['string'],
'Yar_Client_Exception::getType' => ['string'],
'Yar_Concurrent_Client::call' => ['int', 'uri'=>'string', 'method'=>'string', 'parameters'=>'array', 'callback='=>'callable'],
'Yar_Concurrent_Client::loop' => ['bool', 'callback='=>'callable', 'error_callback='=>'callable'],
'Yar_Concurrent_Client::reset' => ['bool'],
'Yar_Server::__construct' => ['void', 'object'=>'Object'],
'Yar_Server::handle' => ['bool'],
'Yar_Server_Exception::__clone' => ['void'],
'Yar_Server_Exception::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'Yar_Server_Exception::__toString' => ['string'],
'Yar_Server_Exception::__wakeup' => ['void'],
'Yar_Server_Exception::getCode' => ['int'],
'Yar_Server_Exception::getFile' => ['string'],
'Yar_Server_Exception::getLine' => ['int'],
'Yar_Server_Exception::getMessage' => ['string'],
'Yar_Server_Exception::getPrevious' => ['?Exception|?Throwable'],
'Yar_Server_Exception::getTrace' => ['list<array<string,mixed>>'],
'Yar_Server_Exception::getTraceAsString' => ['string'],
'Yar_Server_Exception::getType' => ['string'],
'yaz_addinfo' => ['string', 'id'=>'resource'],
'yaz_ccl_conf' => ['void', 'id'=>'resource', 'config'=>'array'],
'yaz_ccl_parse' => ['bool', 'id'=>'resource', 'query'=>'string', '&w_result'=>'array'],
'yaz_close' => ['bool', 'id'=>'resource'],
'yaz_connect' => ['mixed', 'zurl'=>'string', 'options='=>'mixed'],
'yaz_database' => ['bool', 'id'=>'resource', 'databases'=>'string'],
'yaz_element' => ['bool', 'id'=>'resource', 'elementset'=>'string'],
'yaz_errno' => ['int', 'id'=>'resource'],
'yaz_error' => ['string', 'id'=>'resource'],
'yaz_es' => ['void', 'id'=>'resource', 'type'=>'string', 'args'=>'array'],
'yaz_es_result' => ['array', 'id'=>'resource'],
'yaz_get_option' => ['string', 'id'=>'resource', 'name'=>'string'],
'yaz_hits' => ['int', 'id'=>'resource', 'searchresult='=>'array'],
'yaz_itemorder' => ['void', 'id'=>'resource', 'args'=>'array'],
'yaz_present' => ['bool', 'id'=>'resource'],
'yaz_range' => ['void', 'id'=>'resource', 'start'=>'int', 'number'=>'int'],
'yaz_record' => ['string', 'id'=>'resource', 'pos'=>'int', 'type'=>'string'],
'yaz_scan' => ['void', 'id'=>'resource', 'type'=>'string', 'startterm'=>'string', 'flags='=>'array'],
'yaz_scan_result' => ['array', 'id'=>'resource', 'result='=>'array'],
'yaz_schema' => ['void', 'id'=>'resource', 'schema'=>'string'],
'yaz_search' => ['bool', 'id'=>'resource', 'type'=>'string', 'query'=>'string'],
'yaz_set_option' => ['', 'id'=>'', 'name'=>'string', 'value'=>'string', 'options'=>'array'],
'yaz_sort' => ['void', 'id'=>'resource', 'criteria'=>'string'],
'yaz_syntax' => ['void', 'id'=>'resource', 'syntax'=>'string'],
'yaz_wait' => ['mixed', '&rw_options='=>'array'],
'yp_all' => ['void', 'domain'=>'string', 'map'=>'string', 'callback'=>'string'],
'yp_cat' => ['array', 'domain'=>'string', 'map'=>'string'],
'yp_err_string' => ['string', 'errorcode'=>'int'],
'yp_errno' => ['int'],
'yp_first' => ['array', 'domain'=>'string', 'map'=>'string'],
'yp_get_default_domain' => ['string'],
'yp_master' => ['string', 'domain'=>'string', 'map'=>'string'],
'yp_match' => ['string', 'domain'=>'string', 'map'=>'string', 'key'=>'string'],
'yp_next' => ['array', 'domain'=>'string', 'map'=>'string', 'key'=>'string'],
'yp_order' => ['int', 'domain'=>'string', 'map'=>'string'],
'zem_get_extension_info_by_id' => [''],
'zem_get_extension_info_by_name' => [''],
'zem_get_extensions_info' => [''],
'zem_get_license_info' => [''],
'zend_current_obfuscation_level' => ['int'],
'zend_disk_cache_clear' => ['bool', 'namespace='=>'mixed|string'],
'zend_disk_cache_delete' => ['mixed|null', 'key'=>'string'],
'zend_disk_cache_fetch' => ['mixed|null', 'key'=>'string'],
'zend_disk_cache_store' => ['bool', 'key'=>'', 'value'=>'', 'ttl='=>'int|mixed'],
'zend_get_id' => ['array', 'all_ids='=>'all_ids|false'],
'zend_is_configuration_changed' => [''],
'zend_loader_current_file' => ['string'],
'zend_loader_enabled' => ['bool'],
'zend_loader_file_encoded' => ['bool'],
'zend_loader_file_licensed' => ['array'],
'zend_loader_install_license' => ['bool', 'license_file'=>'string', 'override'=>'bool'],
'zend_logo_guid' => ['string'],
'zend_obfuscate_class_name' => ['string', 'class_name'=>'string'],
'zend_obfuscate_function_name' => ['string', 'function_name'=>'string'],
'zend_optimizer_version' => ['string'],
'zend_runtime_obfuscate' => ['void'],
'zend_send_buffer' => ['null|false', 'buffer'=>'string', 'mime_type='=>'string', 'custom_headers='=>'string'],
'zend_send_file' => ['null|false', 'filename'=>'string', 'mime_type='=>'string', 'custom_headers='=>'string'],
'zend_set_configuration_changed' => [''],
'zend_shm_cache_clear' => ['bool', 'namespace='=>'mixed|string'],
'zend_shm_cache_delete' => ['mixed|null', 'key'=>'string'],
'zend_shm_cache_fetch' => ['mixed|null', 'key'=>'string'],
'zend_shm_cache_store' => ['bool', 'key'=>'', 'value'=>'', 'ttl='=>'int|mixed'],
'zend_thread_id' => ['int'],
'zend_version' => ['string'],
'ZendAPI_Job::addJobToQueue' => ['int', 'jobqueue_url'=>'string', 'password'=>'string'],
'ZendAPI_Job::getApplicationID' => [''],
'ZendAPI_Job::getEndTime' => [''],
'ZendAPI_Job::getGlobalVariables' => [''],
'ZendAPI_Job::getHost' => [''],
'ZendAPI_Job::getID' => [''],
'ZendAPI_Job::getInterval' => [''],
'ZendAPI_Job::getJobDependency' => [''],
'ZendAPI_Job::getJobName' => [''],
'ZendAPI_Job::getJobPriority' => [''],
'ZendAPI_Job::getJobStatus' => ['int'],
'ZendAPI_Job::getLastPerformedStatus' => ['int'],
'ZendAPI_Job::getOutput' => ['An'],
'ZendAPI_Job::getPreserved' => [''],
'ZendAPI_Job::getProperties' => ['array'],
'ZendAPI_Job::getScheduledTime' => [''],
'ZendAPI_Job::getScript' => [''],
'ZendAPI_Job::getTimeToNextRepeat' => ['int'],
'ZendAPI_Job::getUserVariables' => [''],
'ZendAPI_Job::setApplicationID' => ['', 'app_id'=>''],
'ZendAPI_Job::setGlobalVariables' => ['', 'vars'=>''],
'ZendAPI_Job::setJobDependency' => ['', 'job_id'=>''],
'ZendAPI_Job::setJobName' => ['', 'name'=>''],
'ZendAPI_Job::setJobPriority' => ['', 'priority'=>'int'],
'ZendAPI_Job::setPreserved' => ['', 'preserved'=>''],
'ZendAPI_Job::setRecurrenceData' => ['', 'interval'=>'', 'end_time='=>'mixed'],
'ZendAPI_Job::setScheduledTime' => ['', 'timestamp'=>''],
'ZendAPI_Job::setScript' => ['', 'script'=>''],
'ZendAPI_Job::setUserVariables' => ['', 'vars'=>''],
'ZendAPI_Job::ZendAPI_Job' => ['Job', 'script'=>'script'],
'ZendAPI_Queue::addJob' => ['int', '&job'=>'Job'],
'ZendAPI_Queue::getAllApplicationIDs' => ['array'],
'ZendAPI_Queue::getAllhosts' => ['array'],
'ZendAPI_Queue::getHistoricJobs' => ['array', 'status'=>'int', 'start_time'=>'', 'end_time'=>'', 'index'=>'int', 'count'=>'int', '&total'=>'int'],
'ZendAPI_Queue::getJob' => ['Job', 'job_id'=>'int'],
'ZendAPI_Queue::getJobsInQueue' => ['array', 'filter_options='=>'array', 'max_jobs='=>'int', 'with_globals_and_output='=>'bool'],
'ZendAPI_Queue::getLastError' => ['string'],
'ZendAPI_Queue::getNumOfJobsInQueue' => ['int', 'filter_options='=>'array'],
'ZendAPI_Queue::getStatistics' => ['array'],
'ZendAPI_Queue::isScriptExists' => ['bool', 'path'=>'string'],
'ZendAPI_Queue::isSuspend' => ['bool'],
'ZendAPI_Queue::login' => ['bool', 'password'=>'string', 'application_id='=>'int'],
'ZendAPI_Queue::removeJob' => ['bool', 'job_id'=>'array|int'],
'ZendAPI_Queue::requeueJob' => ['bool', 'job'=>'Job'],
'ZendAPI_Queue::resumeJob' => ['bool', 'job_id'=>'array|int'],
'ZendAPI_Queue::resumeQueue' => ['bool'],
'ZendAPI_Queue::setMaxHistoryTime' => ['bool'],
'ZendAPI_Queue::suspendJob' => ['bool', 'job_id'=>'array|int'],
'ZendAPI_Queue::suspendQueue' => ['bool'],
'ZendAPI_Queue::updateJob' => ['int', '&job'=>'Job'],
'ZendAPI_Queue::zendapi_queue' => ['ZendAPI_Queue', 'queue_url'=>'string'],
'zip_close' => ['void', 'zip'=>'resource'],
'zip_entry_close' => ['bool', 'zip_ent'=>'resource'],
'zip_entry_compressedsize' => ['int', 'zip_entry'=>'resource'],
'zip_entry_compressionmethod' => ['string', 'zip_entry'=>'resource'],
'zip_entry_filesize' => ['int', 'zip_entry'=>'resource'],
'zip_entry_name' => ['string', 'zip_entry'=>'resource'],
'zip_entry_open' => ['bool', 'zip_dp'=>'resource', 'zip_entry'=>'resource', 'mode='=>'string'],
'zip_entry_read' => ['string|false', 'zip_entry'=>'resource', 'len='=>'int'],
'zip_open' => ['resource|int|false', 'filename'=>'string'],
'zip_read' => ['resource', 'zip'=>'resource'],
'ZipArchive::addEmptyDir' => ['bool', 'dirname'=>'string'],
'ZipArchive::addFile' => ['bool', 'filepath'=>'string', 'entryname='=>'string', 'start='=>'int', 'length='=>'int'],
'ZipArchive::addFromString' => ['bool', 'entryname'=>'string', 'content'=>'string'],
'ZipArchive::addGlob' => ['bool', 'pattern'=>'string', 'flags='=>'int', 'options='=>'array'],
'ZipArchive::addPattern' => ['bool', 'pattern'=>'string', 'path='=>'string', 'options='=>'array'],
'ZipArchive::close' => ['bool'],
'ZipArchive::count' => ['int'],
'ZipArchive::createEmptyDir' => ['bool', 'dirname'=>'string'],
'ZipArchive::deleteIndex' => ['bool', 'index'=>'int'],
'ZipArchive::deleteName' => ['bool', 'name'=>'string'],
'ZipArchive::extractTo' => ['bool', 'pathto'=>'string', 'files='=>'string[]|string'],
'ZipArchive::getArchiveComment' => ['string|false', 'flags='=>'int'],
'ZipArchive::getCommentIndex' => ['string|false', 'index'=>'int', 'flags='=>'int'],
'ZipArchive::getCommentName' => ['string|false', 'name'=>'string', 'flags='=>'int'],
'ZipArchive::getExternalAttributesIndex' => ['bool', 'index'=>'int', '&w_opsys'=>'int', '&w_attr'=>'int', 'flags='=>'int'],
'ZipArchive::getExternalAttributesName' => ['bool', 'name'=>'string', '&w_opsys'=>'int', '&w_attr'=>'int', 'flags='=>'int'],
'ZipArchive::getFromIndex' => ['string|false', 'index'=>'int', 'length='=>'int', 'flags='=>'int'],
'ZipArchive::getFromName' => ['string|false', 'entryname'=>'string', 'length='=>'int', 'flags='=>'int'],
'ZipArchive::getNameIndex' => ['string|false', 'index'=>'int', 'flags='=>'int'],
'ZipArchive::getStatusString' => ['string|false'],
'ZipArchive::getStream' => ['resource|false', 'entryname'=>'string'],
'ZipArchive::isCompressionMethodSupported' => ['bool', 'method'=>'int', 'encode='=>'bool'],
'ZipArchive::isEncryptionMethodSupported' => ['bool', 'method'=>'int', 'encode='=>'bool'],
'ZipArchive::locateName' => ['int|false', 'filename'=>'string', 'flags='=>'int'],
'ZipArchive::open' => ['int|bool', 'source'=>'string', 'flags='=>'int'],
'ZipArchive::registerCancelCallback' => ['bool', 'callback'=>'callable'],
'ZipArchive::registerProgressCallback' => ['bool', 'rate'=>'float', 'callback'=>'callable'],
'ZipArchive::renameIndex' => ['bool', 'index'=>'int', 'new_name'=>'string'],
'ZipArchive::renameName' => ['bool', 'name'=>'string', 'new_name'=>'string'],
'ZipArchive::replaceFile' => ['bool', 'filename'=>'string', 'index'=>'int', 'start='=>'int', 'length='=>'int', 'flags='=>'int'],
'ZipArchive::setArchiveComment' => ['bool', 'comment'=>'string'],
'ZipArchive::setCommentIndex' => ['bool', 'index'=>'int', 'comment'=>'string'],
'ZipArchive::setCommentName' => ['bool', 'name'=>'string', 'comment'=>'string'],
'ZipArchive::setCompressionIndex' => ['bool', 'index'=>'int', 'comp_method'=>'int', 'comp_flags='=>'int'],
'ZipArchive::setCompressionName' => ['bool', 'name'=>'string', 'comp_method'=>'int', 'comp_flags='=>'int'],
'ZipArchive::setEncryptionIndex' => ['bool', 'index'=>'int', 'method'=>'string', 'password='=>'string'],
'ZipArchive::setEncryptionName' => ['bool', 'name'=>'string', 'method'=>'int', 'password='=>'string'],
'ZipArchive::setExternalAttributesIndex' => ['bool', 'index'=>'int', 'opsys'=>'int', 'attr'=>'int', 'flags='=>'int'],
'ZipArchive::setExternalAttributesName' => ['bool', 'name'=>'string', 'opsys'=>'int', 'attr'=>'int', 'flags='=>'int'],
'ZipArchive::setMtimeIndex' => ['bool', 'index'=>'int', 'timestamp'=>'int', 'flags='=>'int'],
'ZipArchive::setMtimeName' => ['bool', 'name'=>'string', 'timestamp'=>'int', 'flags='=>'int'],
'ZipArchive::setPassword' => ['bool', 'password'=>'string'],
'ZipArchive::statIndex' => ['array|false', 'index'=>'int', 'flags='=>'int'],
'ZipArchive::statName' => ['array|false', 'filename'=>'string', 'flags='=>'int'],
'ZipArchive::unchangeAll' => ['bool'],
'ZipArchive::unchangeArchive' => ['bool'],
'ZipArchive::unchangeIndex' => ['bool', 'index'=>'int'],
'ZipArchive::unchangeName' => ['bool', 'name'=>'string'],
'zlib_decode' => ['string|false', 'data'=>'string', 'max_length='=>'int'],
'zlib_encode' => ['string', 'data'=>'string', 'encoding'=>'int', 'level='=>'string|int'],
'zlib_get_coding_type' => ['string|false'],
'ZMQ::__construct' => ['void'],
'ZMQContext::__construct' => ['void', 'io_threads='=>'int', 'is_persistent='=>'bool'],
'ZMQContext::getOpt' => ['int|string', 'key'=>'string'],
'ZMQContext::getSocket' => ['ZMQSocket', 'type'=>'int', 'persistent_id='=>'string', 'on_new_socket='=>'callable'],
'ZMQContext::isPersistent' => ['bool'],
'ZMQContext::setOpt' => ['ZMQContext', 'key'=>'int', 'value'=>'mixed'],
'ZMQDevice::__construct' => ['void', 'frontend'=>'ZMQSocket', 'backend'=>'ZMQSocket', 'listener='=>'ZMQSocket'],
'ZMQDevice::getIdleTimeout' => ['ZMQDevice'],
'ZMQDevice::getTimerTimeout' => ['ZMQDevice'],
'ZMQDevice::run' => ['void'],
'ZMQDevice::setIdleCallback' => ['ZMQDevice', 'cb_func'=>'callable', 'timeout'=>'int', 'user_data='=>'mixed'],
'ZMQDevice::setIdleTimeout' => ['ZMQDevice', 'timeout'=>'int'],
'ZMQDevice::setTimerCallback' => ['ZMQDevice', 'cb_func'=>'callable', 'timeout'=>'int', 'user_data='=>'mixed'],
'ZMQDevice::setTimerTimeout' => ['ZMQDevice', 'timeout'=>'int'],
'ZMQPoll::add' => ['string', 'entry'=>'mixed', 'type'=>'int'],
'ZMQPoll::clear' => ['ZMQPoll'],
'ZMQPoll::count' => ['int'],
'ZMQPoll::getLastErrors' => ['array'],
'ZMQPoll::poll' => ['int', '&w_readable'=>'array', '&w_writable'=>'array', 'timeout='=>'int'],
'ZMQPoll::remove' => ['bool', 'item'=>'mixed'],
'ZMQSocket::__construct' => ['void', 'context'=>'ZMQContext', 'type'=>'int', 'persistent_id='=>'string', 'on_new_socket='=>'callable'],
'ZMQSocket::bind' => ['ZMQSocket', 'dsn'=>'string', 'force='=>'bool'],
'ZMQSocket::connect' => ['ZMQSocket', 'dsn'=>'string', 'force='=>'bool'],
'ZMQSocket::disconnect' => ['ZMQSocket', 'dsn'=>'string'],
'ZMQSocket::getEndpoints' => ['array'],
'ZMQSocket::getPersistentId' => ['?string'],
'ZMQSocket::getSocketType' => ['int'],
'ZMQSocket::getSockOpt' => ['int|string', 'key'=>'string'],
'ZMQSocket::isPersistent' => ['bool'],
'ZMQSocket::recv' => ['string', 'mode='=>'int'],
'ZMQSocket::recvMulti' => ['string[]', 'mode='=>'int'],
'ZMQSocket::send' => ['ZMQSocket', 'message'=>'array', 'mode='=>'int'],
'ZMQSocket::send\'1' => ['ZMQSocket', 'message'=>'string', 'mode='=>'int'],
'ZMQSocket::sendmulti' => ['ZMQSocket', 'message'=>'array', 'mode='=>'int'],
'ZMQSocket::setSockOpt' => ['ZMQSocket', 'key'=>'int', 'value'=>'mixed'],
'ZMQSocket::unbind' => ['ZMQSocket', 'dsn'=>'string'],
'Zookeeper::addAuth' => ['bool', 'scheme'=>'string', 'cert'=>'string', 'completion_cb='=>'callable'],
'Zookeeper::close' => ['void'],
'Zookeeper::connect' => ['void', 'host'=>'string', 'watcher_cb='=>'callable', 'recv_timeout='=>'int'],
'Zookeeper::create' => ['string', 'path'=>'string', 'value'=>'string', 'acls'=>'array', 'flags='=>'int'],
'Zookeeper::delete' => ['bool', 'path'=>'string', 'version='=>'int'],
'Zookeeper::exists' => ['bool', 'path'=>'string', 'watcher_cb='=>'callable'],
'Zookeeper::get' => ['string', 'path'=>'string', 'watcher_cb='=>'callable', 'stat='=>'array', 'max_size='=>'int'],
'Zookeeper::getAcl' => ['array', 'path'=>'string'],
'Zookeeper::getChildren' => ['array|false', 'path'=>'string', 'watcher_cb='=>'callable'],
'Zookeeper::getClientId' => ['int'],
'Zookeeper::getConfig' => ['ZookeeperConfig'],
'Zookeeper::getRecvTimeout' => ['int'],
'Zookeeper::getState' => ['int'],
'Zookeeper::isRecoverable' => ['bool'],
'Zookeeper::set' => ['bool', 'path'=>'string', 'value'=>'string', 'version='=>'int', 'stat='=>'array'],
'Zookeeper::setAcl' => ['bool', 'path'=>'string', 'version'=>'int', 'acl'=>'array'],
'Zookeeper::setDebugLevel' => ['bool', 'logLevel'=>'int'],
'Zookeeper::setDeterministicConnOrder' => ['bool', 'yesOrNo'=>'bool'],
'Zookeeper::setLogStream' => ['bool', 'stream'=>'resource'],
'Zookeeper::setWatcher' => ['bool', 'watcher_cb'=>'callable'],
'zookeeper_dispatch' => ['void'],
'ZookeeperConfig::add' => ['void', 'members'=>'string', 'version='=>'int', 'stat='=>'array'],
'ZookeeperConfig::get' => ['string', 'watcher_cb='=>'callable', 'stat='=>'array'],
'ZookeeperConfig::remove' => ['void', 'id_list'=>'string', 'version='=>'int', 'stat='=>'array'],
'ZookeeperConfig::set' => ['void', 'members'=>'string', 'version='=>'int', 'stat='=>'array'],
];
| 1 | 11,729 | Does psalm support the same logic internally for object-like arrays? Just want to be certain I can indicate this is a contextual return item `crypto?:mixed`. | vimeo-psalm | php |
@@ -658,8 +658,6 @@ void CreateImageTest(VkLayerTest &test, const VkImageCreateInfo *pCreateInfo, st
VkImage image = VK_NULL_HANDLE;
if (code.length()) {
test.Monitor().SetDesiredFailureMsg(kErrorBit, code);
- // Very possible a test didn't check for VK_ERROR_FORMAT_NOT_SUPPORTED
- test.Monitor().SetUnexpectedError("UNASSIGNED-CoreValidation-Image-FormatNotSupported");
} else {
test.Monitor().ExpectSuccess();
} | 1 | /*
* Copyright (c) 2015-2021 The Khronos Group Inc.
* Copyright (c) 2015-2021 Valve Corporation
* Copyright (c) 2015-2021 LunarG, Inc.
* Copyright (c) 2015-2021 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Author: Chia-I Wu <[email protected]>
* Author: Chris Forbes <[email protected]>
* Author: Courtney Goeltzenleuchter <[email protected]>
* Author: Mark Lobodzinski <[email protected]>
* Author: Mike Stroyan <[email protected]>
* Author: Tobin Ehlis <[email protected]>
* Author: Tony Barbour <[email protected]>
* Author: Cody Northrop <[email protected]>
* Author: Dave Houlton <[email protected]>
* Author: Jeremy Kniager <[email protected]>
* Author: Shannon McPherson <[email protected]>
* Author: John Zulauf <[email protected]>
*/
#include "cast_utils.h"
#include "layer_validation_tests.h"
// Global list of sType,size identifiers
std::vector<std::pair<uint32_t, uint32_t>> custom_stype_info{};
VkFormat FindSupportedDepthOnlyFormat(VkPhysicalDevice phy) {
const VkFormat ds_formats[] = {VK_FORMAT_D16_UNORM, VK_FORMAT_X8_D24_UNORM_PACK32, VK_FORMAT_D32_SFLOAT};
for (uint32_t i = 0; i < size(ds_formats); ++i) {
VkFormatProperties format_props;
vk::GetPhysicalDeviceFormatProperties(phy, ds_formats[i], &format_props);
if (format_props.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) {
return ds_formats[i];
}
}
return VK_FORMAT_UNDEFINED;
}
VkFormat FindSupportedStencilOnlyFormat(VkPhysicalDevice phy) {
const VkFormat ds_formats[] = {VK_FORMAT_S8_UINT};
for (uint32_t i = 0; i < size(ds_formats); ++i) {
VkFormatProperties format_props;
vk::GetPhysicalDeviceFormatProperties(phy, ds_formats[i], &format_props);
if (format_props.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) {
return ds_formats[i];
}
}
return VK_FORMAT_UNDEFINED;
}
VkFormat FindSupportedDepthStencilFormat(VkPhysicalDevice phy) {
const VkFormat ds_formats[] = {VK_FORMAT_D16_UNORM_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_D32_SFLOAT_S8_UINT};
for (uint32_t i = 0; i < size(ds_formats); ++i) {
VkFormatProperties format_props;
vk::GetPhysicalDeviceFormatProperties(phy, ds_formats[i], &format_props);
if (format_props.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) {
return ds_formats[i];
}
}
return VK_FORMAT_UNDEFINED;
}
bool ImageFormatIsSupported(VkPhysicalDevice phy, VkFormat format, VkImageTiling tiling, VkFormatFeatureFlags features) {
VkFormatProperties format_props;
vk::GetPhysicalDeviceFormatProperties(phy, format, &format_props);
VkFormatFeatureFlags phy_features =
(VK_IMAGE_TILING_OPTIMAL == tiling ? format_props.optimalTilingFeatures : format_props.linearTilingFeatures);
return (0 != (phy_features & features));
}
bool ImageFormatAndFeaturesSupported(VkPhysicalDevice phy, VkFormat format, VkImageTiling tiling, VkFormatFeatureFlags features) {
VkFormatProperties format_props;
vk::GetPhysicalDeviceFormatProperties(phy, format, &format_props);
VkFormatFeatureFlags phy_features =
(VK_IMAGE_TILING_OPTIMAL == tiling ? format_props.optimalTilingFeatures : format_props.linearTilingFeatures);
return (features == (phy_features & features));
}
bool ImageFormatAndFeaturesSupported(const VkInstance inst, const VkPhysicalDevice phy, const VkImageCreateInfo info,
const VkFormatFeatureFlags features) {
// Verify physical device support of format features
if (!ImageFormatAndFeaturesSupported(phy, info.format, info.tiling, features)) {
return false;
}
// Verify that PhysDevImageFormatProp() also claims support for the specific usage
VkImageFormatProperties props;
VkResult err =
vk::GetPhysicalDeviceImageFormatProperties(phy, info.format, info.imageType, info.tiling, info.usage, info.flags, &props);
if (VK_SUCCESS != err) {
return false;
}
#if 0 // Convinced this chunk doesn't currently add any additional info, but leaving in place because it may be
// necessary with future extensions
// Verify again using version 2, if supported, which *can* return more property data than the original...
// (It's not clear that this is any more definitive than using the original version - but no harm)
PFN_vkGetPhysicalDeviceImageFormatProperties2KHR p_GetPDIFP2KHR =
(PFN_vkGetPhysicalDeviceImageFormatProperties2KHR)vk::GetInstanceProcAddr(inst,
"vkGetPhysicalDeviceImageFormatProperties2KHR");
if (NULL != p_GetPDIFP2KHR) {
VkPhysicalDeviceImageFormatInfo2KHR fmt_info{};
fmt_info.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2_KHR;
fmt_info.pNext = nullptr;
fmt_info.format = info.format;
fmt_info.type = info.imageType;
fmt_info.tiling = info.tiling;
fmt_info.usage = info.usage;
fmt_info.flags = info.flags;
VkImageFormatProperties2KHR fmt_props = {};
fmt_props.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR;
err = p_GetPDIFP2KHR(phy, &fmt_info, &fmt_props);
if (VK_SUCCESS != err) {
return false;
}
}
#endif
return true;
}
bool BufferFormatAndFeaturesSupported(VkPhysicalDevice phy, VkFormat format, VkFormatFeatureFlags features) {
VkFormatProperties format_props;
vk::GetPhysicalDeviceFormatProperties(phy, format, &format_props);
VkFormatFeatureFlags phy_features = format_props.bufferFeatures;
return (features == (phy_features & features));
}
VkPhysicalDevicePushDescriptorPropertiesKHR GetPushDescriptorProperties(VkInstance instance, VkPhysicalDevice gpu) {
// Find address of extension call and make the call -- assumes needed extensions are enabled.
PFN_vkGetPhysicalDeviceProperties2KHR vkGetPhysicalDeviceProperties2KHR =
(PFN_vkGetPhysicalDeviceProperties2KHR)vk::GetInstanceProcAddr(instance, "vkGetPhysicalDeviceProperties2KHR");
assert(vkGetPhysicalDeviceProperties2KHR != nullptr);
// Get the push descriptor limits
auto push_descriptor_prop = LvlInitStruct<VkPhysicalDevicePushDescriptorPropertiesKHR>();
auto prop2 = LvlInitStruct<VkPhysicalDeviceProperties2KHR>(&push_descriptor_prop);
vkGetPhysicalDeviceProperties2KHR(gpu, &prop2);
return push_descriptor_prop;
}
VkPhysicalDeviceSubgroupProperties GetSubgroupProperties(VkInstance instance, VkPhysicalDevice gpu) {
auto subgroup_prop = LvlInitStruct<VkPhysicalDeviceSubgroupProperties>();
auto prop2 = LvlInitStruct<VkPhysicalDeviceProperties2>(&subgroup_prop);
vk::GetPhysicalDeviceProperties2(gpu, &prop2);
return subgroup_prop;
}
VkPhysicalDeviceDescriptorIndexingProperties GetDescriptorIndexingProperties(VkInstance instance, VkPhysicalDevice gpu) {
auto descriptor_indexing_prop = LvlInitStruct<VkPhysicalDeviceDescriptorIndexingProperties>();
auto prop2 = LvlInitStruct<VkPhysicalDeviceProperties2>(&descriptor_indexing_prop);
vk::GetPhysicalDeviceProperties2(gpu, &prop2);
return descriptor_indexing_prop;
}
bool operator==(const VkDebugUtilsLabelEXT &rhs, const VkDebugUtilsLabelEXT &lhs) {
bool is_equal = (rhs.color[0] == lhs.color[0]) && (rhs.color[1] == lhs.color[1]) && (rhs.color[2] == lhs.color[2]) &&
(rhs.color[3] == lhs.color[3]);
if (is_equal) {
if (rhs.pLabelName && lhs.pLabelName) {
is_equal = (0 == strcmp(rhs.pLabelName, lhs.pLabelName));
} else {
is_equal = (rhs.pLabelName == nullptr) && (lhs.pLabelName == nullptr);
}
}
return is_equal;
}
VKAPI_ATTR VkBool32 VKAPI_CALL DebugUtilsCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageTypes,
const VkDebugUtilsMessengerCallbackDataEXT *pCallbackData, void *pUserData) {
auto *data = reinterpret_cast<DebugUtilsLabelCheckData *>(pUserData);
data->callback(pCallbackData, data);
return VK_FALSE;
}
#if GTEST_IS_THREADSAFE
extern "C" void *AddToCommandBuffer(void *arg) {
struct thread_data_struct *data = (struct thread_data_struct *)arg;
for (int i = 0; i < 80000; i++) {
vk::CmdSetEvent(data->commandBuffer, data->event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
if (*data->bailout) {
break;
}
}
return NULL;
}
extern "C" void *UpdateDescriptor(void *arg) {
struct thread_data_struct *data = (struct thread_data_struct *)arg;
VkDescriptorBufferInfo buffer_info = {};
buffer_info.buffer = data->buffer;
buffer_info.offset = 0;
buffer_info.range = 1;
VkWriteDescriptorSet descriptor_write;
memset(&descriptor_write, 0, sizeof(descriptor_write));
descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptor_write.dstSet = data->descriptorSet;
descriptor_write.dstBinding = data->binding;
descriptor_write.descriptorCount = 1;
descriptor_write.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
descriptor_write.pBufferInfo = &buffer_info;
for (int i = 0; i < 80000; i++) {
vk::UpdateDescriptorSets(data->device, 1, &descriptor_write, 0, NULL);
if (*data->bailout) {
break;
}
}
return NULL;
}
#endif // GTEST_IS_THREADSAFE
extern "C" void *ReleaseNullFence(void *arg) {
struct thread_data_struct *data = (struct thread_data_struct *)arg;
for (int i = 0; i < 40000; i++) {
vk::DestroyFence(data->device, VK_NULL_HANDLE, NULL);
if (*data->bailout) {
break;
}
}
return NULL;
}
void TestRenderPassCreate(ErrorMonitor *error_monitor, const VkDevice device, const VkRenderPassCreateInfo *create_info,
bool rp2_supported, const char *rp1_vuid, const char *rp2_vuid) {
VkRenderPass render_pass = VK_NULL_HANDLE;
VkResult err;
if (rp1_vuid) {
// Some tests mismatch attachment type with layout
error_monitor->SetUnexpectedError("VUID-VkSubpassDescription-None-04437");
error_monitor->SetDesiredFailureMsg(kErrorBit, rp1_vuid);
err = vk::CreateRenderPass(device, create_info, nullptr, &render_pass);
if (err == VK_SUCCESS) vk::DestroyRenderPass(device, render_pass, nullptr);
error_monitor->VerifyFound();
}
if (rp2_supported && rp2_vuid) {
PFN_vkCreateRenderPass2KHR vkCreateRenderPass2KHR =
(PFN_vkCreateRenderPass2KHR)vk::GetDeviceProcAddr(device, "vkCreateRenderPass2KHR");
safe_VkRenderPassCreateInfo2 create_info2;
ConvertVkRenderPassCreateInfoToV2KHR(*create_info, &create_info2);
// Some tests mismatch attachment type with layout
error_monitor->SetUnexpectedError("VUID-VkSubpassDescription2-None-04439");
error_monitor->SetDesiredFailureMsg(kErrorBit, rp2_vuid);
err = vkCreateRenderPass2KHR(device, create_info2.ptr(), nullptr, &render_pass);
if (err == VK_SUCCESS) vk::DestroyRenderPass(device, render_pass, nullptr);
error_monitor->VerifyFound();
// For api version >= 1.2, try core entrypoint
PFN_vkCreateRenderPass2 vkCreateRenderPass2 = (PFN_vkCreateRenderPass2)vk::GetDeviceProcAddr(device, "vkCreateRenderPass2");
if (vkCreateRenderPass2) {
// Some tests mismatch attachment type with layout
error_monitor->SetUnexpectedError("VUID-VkSubpassDescription2-None-04439");
error_monitor->SetDesiredFailureMsg(kErrorBit, rp2_vuid);
err = vkCreateRenderPass2(device, create_info2.ptr(), nullptr, &render_pass);
if (err == VK_SUCCESS) vk::DestroyRenderPass(device, render_pass, nullptr);
error_monitor->VerifyFound();
}
}
}
void PositiveTestRenderPassCreate(ErrorMonitor *error_monitor, const VkDevice device, const VkRenderPassCreateInfo *create_info,
bool rp2_supported) {
VkRenderPass render_pass = VK_NULL_HANDLE;
VkResult err;
error_monitor->ExpectSuccess();
err = vk::CreateRenderPass(device, create_info, nullptr, &render_pass);
if (err == VK_SUCCESS) vk::DestroyRenderPass(device, render_pass, nullptr);
error_monitor->VerifyNotFound();
if (rp2_supported) {
PFN_vkCreateRenderPass2KHR vkCreateRenderPass2KHR =
(PFN_vkCreateRenderPass2KHR)vk::GetDeviceProcAddr(device, "vkCreateRenderPass2KHR");
safe_VkRenderPassCreateInfo2 create_info2;
ConvertVkRenderPassCreateInfoToV2KHR(*create_info, &create_info2);
error_monitor->ExpectSuccess();
err = vkCreateRenderPass2KHR(device, create_info2.ptr(), nullptr, &render_pass);
if (err == VK_SUCCESS) vk::DestroyRenderPass(device, render_pass, nullptr);
error_monitor->VerifyNotFound();
}
}
void PositiveTestRenderPass2KHRCreate(ErrorMonitor *error_monitor, const VkDevice device,
const VkRenderPassCreateInfo2KHR *create_info) {
VkRenderPass render_pass = VK_NULL_HANDLE;
VkResult err;
PFN_vkCreateRenderPass2KHR vkCreateRenderPass2KHR =
(PFN_vkCreateRenderPass2KHR)vk::GetDeviceProcAddr(device, "vkCreateRenderPass2KHR");
error_monitor->ExpectSuccess();
err = vkCreateRenderPass2KHR(device, create_info, nullptr, &render_pass);
if (err == VK_SUCCESS) vk::DestroyRenderPass(device, render_pass, nullptr);
error_monitor->VerifyNotFound();
}
void TestRenderPass2KHRCreate(ErrorMonitor *error_monitor, const VkDevice device, const VkRenderPassCreateInfo2KHR *create_info,
const char *rp2_vuid) {
VkRenderPass render_pass = VK_NULL_HANDLE;
VkResult err;
PFN_vkCreateRenderPass2KHR vkCreateRenderPass2KHR =
(PFN_vkCreateRenderPass2KHR)vk::GetDeviceProcAddr(device, "vkCreateRenderPass2KHR");
error_monitor->SetDesiredFailureMsg(kErrorBit, rp2_vuid);
err = vkCreateRenderPass2KHR(device, create_info, nullptr, &render_pass);
if (err == VK_SUCCESS) vk::DestroyRenderPass(device, render_pass, nullptr);
error_monitor->VerifyFound();
}
void TestRenderPassBegin(ErrorMonitor *error_monitor, const VkDevice device, const VkCommandBuffer command_buffer,
const VkRenderPassBeginInfo *begin_info, bool rp2Supported, const char *rp1_vuid, const char *rp2_vuid) {
VkCommandBufferBeginInfo cmd_begin_info = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, nullptr,
VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, nullptr};
if (rp1_vuid) {
vk::BeginCommandBuffer(command_buffer, &cmd_begin_info);
error_monitor->SetDesiredFailureMsg(kErrorBit, rp1_vuid);
vk::CmdBeginRenderPass(command_buffer, begin_info, VK_SUBPASS_CONTENTS_INLINE);
error_monitor->VerifyFound();
vk::ResetCommandBuffer(command_buffer, 0);
}
if (rp2Supported && rp2_vuid) {
PFN_vkCmdBeginRenderPass2KHR vkCmdBeginRenderPass2KHR =
(PFN_vkCmdBeginRenderPass2KHR)vk::GetDeviceProcAddr(device, "vkCmdBeginRenderPass2KHR");
VkSubpassBeginInfoKHR subpass_begin_info = {VK_STRUCTURE_TYPE_SUBPASS_BEGIN_INFO_KHR, nullptr, VK_SUBPASS_CONTENTS_INLINE};
vk::BeginCommandBuffer(command_buffer, &cmd_begin_info);
error_monitor->SetDesiredFailureMsg(kErrorBit, rp2_vuid);
vkCmdBeginRenderPass2KHR(command_buffer, begin_info, &subpass_begin_info);
error_monitor->VerifyFound();
vk::ResetCommandBuffer(command_buffer, 0);
// For api version >= 1.2, try core entrypoint
PFN_vkCmdBeginRenderPass2KHR vkCmdBeginRenderPass2 =
(PFN_vkCmdBeginRenderPass2KHR)vk::GetDeviceProcAddr(device, "vkCmdBeginRenderPass2");
if (vkCmdBeginRenderPass2) {
vk::BeginCommandBuffer(command_buffer, &cmd_begin_info);
error_monitor->SetDesiredFailureMsg(kErrorBit, rp2_vuid);
vkCmdBeginRenderPass2(command_buffer, begin_info, &subpass_begin_info);
error_monitor->VerifyFound();
vk::ResetCommandBuffer(command_buffer, 0);
}
}
}
void ValidOwnershipTransferOp(ErrorMonitor *monitor, VkCommandBufferObj *cb, VkPipelineStageFlags src_stages,
VkPipelineStageFlags dst_stages, const VkBufferMemoryBarrier *buf_barrier,
const VkImageMemoryBarrier *img_barrier) {
monitor->ExpectSuccess();
cb->begin();
uint32_t num_buf_barrier = (buf_barrier) ? 1 : 0;
uint32_t num_img_barrier = (img_barrier) ? 1 : 0;
cb->PipelineBarrier(src_stages, dst_stages, 0, 0, nullptr, num_buf_barrier, buf_barrier, num_img_barrier, img_barrier);
cb->end();
cb->QueueCommandBuffer(); // Implicitly waits
monitor->VerifyNotFound();
}
void ValidOwnershipTransfer(ErrorMonitor *monitor, VkCommandBufferObj *cb_from, VkCommandBufferObj *cb_to,
VkPipelineStageFlags src_stages, VkPipelineStageFlags dst_stages,
const VkBufferMemoryBarrier *buf_barrier, const VkImageMemoryBarrier *img_barrier) {
ValidOwnershipTransferOp(monitor, cb_from, src_stages, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, buf_barrier, img_barrier);
ValidOwnershipTransferOp(monitor, cb_to, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, dst_stages, buf_barrier, img_barrier);
}
void ValidOwnershipTransferOp(ErrorMonitor *monitor, VkCommandBufferObj *cb, const VkBufferMemoryBarrier2KHR *buf_barrier,
const VkImageMemoryBarrier2KHR *img_barrier) {
monitor->ExpectSuccess();
cb->begin();
auto dep_info = lvl_init_struct<VkDependencyInfoKHR>();
dep_info.bufferMemoryBarrierCount = (buf_barrier) ? 1 : 0;
dep_info.pBufferMemoryBarriers = buf_barrier;
dep_info.imageMemoryBarrierCount = (img_barrier) ? 1 : 0;
dep_info.pImageMemoryBarriers = img_barrier;
cb->PipelineBarrier2KHR(&dep_info);
cb->end();
cb->QueueCommandBuffer(); // Implicitly waits
monitor->VerifyNotFound();
}
void ValidOwnershipTransfer(ErrorMonitor *monitor, VkCommandBufferObj *cb_from, VkCommandBufferObj *cb_to,
const VkBufferMemoryBarrier2KHR *buf_barrier, const VkImageMemoryBarrier2KHR *img_barrier) {
VkBufferMemoryBarrier2KHR fixup_buf_barrier;
VkImageMemoryBarrier2KHR fixup_img_barrier;
if (buf_barrier) {
fixup_buf_barrier = *buf_barrier;
fixup_buf_barrier.dstStageMask = VK_PIPELINE_STAGE_2_NONE_KHR;
fixup_buf_barrier.dstAccessMask = 0;
}
if (img_barrier) {
fixup_img_barrier = *img_barrier;
fixup_img_barrier.dstStageMask = VK_PIPELINE_STAGE_2_NONE_KHR;
fixup_img_barrier.dstAccessMask = 0;
}
ValidOwnershipTransferOp(monitor, cb_from, buf_barrier ? &fixup_buf_barrier : nullptr,
img_barrier ? &fixup_img_barrier : nullptr);
if (buf_barrier) {
fixup_buf_barrier = *buf_barrier;
fixup_buf_barrier.srcStageMask = VK_PIPELINE_STAGE_2_NONE_KHR;
fixup_buf_barrier.srcAccessMask = 0;
}
if (img_barrier) {
fixup_img_barrier = *img_barrier;
fixup_img_barrier.srcStageMask = VK_PIPELINE_STAGE_2_NONE_KHR;
fixup_img_barrier.srcAccessMask = 0;
}
ValidOwnershipTransferOp(monitor, cb_to, buf_barrier ? &fixup_buf_barrier : nullptr,
img_barrier ? &fixup_img_barrier : nullptr);
}
VkResult GPDIFPHelper(VkPhysicalDevice dev, const VkImageCreateInfo *ci, VkImageFormatProperties *limits) {
VkImageFormatProperties tmp_limits;
limits = limits ? limits : &tmp_limits;
return vk::GetPhysicalDeviceImageFormatProperties(dev, ci->format, ci->imageType, ci->tiling, ci->usage, ci->flags, limits);
}
VkFormat FindFormatLinearWithoutMips(VkPhysicalDevice gpu, VkImageCreateInfo image_ci) {
image_ci.tiling = VK_IMAGE_TILING_LINEAR;
const VkFormat first_vk_format = static_cast<VkFormat>(1);
const VkFormat last_vk_format = static_cast<VkFormat>(130); // avoid compressed/feature protected, otherwise 184
for (VkFormat format = first_vk_format; format <= last_vk_format; format = static_cast<VkFormat>(format + 1)) {
image_ci.format = format;
// WORKAROUND for dev_sim and mock_icd not containing valid format limits yet
VkFormatProperties format_props;
vk::GetPhysicalDeviceFormatProperties(gpu, format, &format_props);
const VkFormatFeatureFlags core_filter = 0x1FFF;
const auto features = (image_ci.tiling == VK_IMAGE_TILING_LINEAR) ? format_props.linearTilingFeatures & core_filter
: format_props.optimalTilingFeatures & core_filter;
if (!(features & core_filter)) continue;
VkImageFormatProperties img_limits;
if (VK_SUCCESS == GPDIFPHelper(gpu, &image_ci, &img_limits) && img_limits.maxMipLevels == 1) return format;
}
return VK_FORMAT_UNDEFINED;
}
bool FindFormatWithoutSamples(VkPhysicalDevice gpu, VkImageCreateInfo &image_ci) {
const VkFormat first_vk_format = static_cast<VkFormat>(1);
const VkFormat last_vk_format = static_cast<VkFormat>(130); // avoid compressed/feature protected, otherwise 184
for (VkFormat format = first_vk_format; format <= last_vk_format; format = static_cast<VkFormat>(format + 1)) {
image_ci.format = format;
// WORKAROUND for dev_sim and mock_icd not containing valid format limits yet
VkFormatProperties format_props;
vk::GetPhysicalDeviceFormatProperties(gpu, format, &format_props);
const VkFormatFeatureFlags core_filter = 0x1FFF;
const auto features = (image_ci.tiling == VK_IMAGE_TILING_LINEAR) ? format_props.linearTilingFeatures & core_filter
: format_props.optimalTilingFeatures & core_filter;
if (!(features & core_filter)) continue;
for (VkSampleCountFlagBits samples = VK_SAMPLE_COUNT_64_BIT; samples > 0;
samples = static_cast<VkSampleCountFlagBits>(samples >> 1)) {
image_ci.samples = samples;
VkImageFormatProperties img_limits;
if (VK_SUCCESS == GPDIFPHelper(gpu, &image_ci, &img_limits) && !(img_limits.sampleCounts & samples)) return true;
}
}
return false;
}
bool FindUnsupportedImage(VkPhysicalDevice gpu, VkImageCreateInfo &image_ci) {
const VkFormat first_vk_format = static_cast<VkFormat>(1);
const VkFormat last_vk_format = static_cast<VkFormat>(130); // avoid compressed/feature protected, otherwise 184
const std::vector<VkImageTiling> tilings = {VK_IMAGE_TILING_LINEAR, VK_IMAGE_TILING_OPTIMAL};
for (const auto tiling : tilings) {
image_ci.tiling = tiling;
for (VkFormat format = first_vk_format; format <= last_vk_format; format = static_cast<VkFormat>(format + 1)) {
image_ci.format = format;
VkFormatProperties format_props;
vk::GetPhysicalDeviceFormatProperties(gpu, format, &format_props);
const VkFormatFeatureFlags core_filter = 0x1FFF;
const auto features = (tiling == VK_IMAGE_TILING_LINEAR) ? format_props.linearTilingFeatures & core_filter
: format_props.optimalTilingFeatures & core_filter;
if (!(features & core_filter)) continue; // We wand supported by features, but not by ImageFormatProperties
// get as many usage flags as possible
image_ci.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
if (features & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) image_ci.usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
if (features & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) image_ci.usage |= VK_IMAGE_USAGE_STORAGE_BIT;
if (features & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) image_ci.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
if (features & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)
image_ci.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
VkImageFormatProperties img_limits;
if (VK_ERROR_FORMAT_NOT_SUPPORTED == GPDIFPHelper(gpu, &image_ci, &img_limits)) {
return true;
}
}
}
return false;
}
VkFormat FindFormatWithoutFeatures(VkPhysicalDevice gpu, VkImageTiling tiling, VkFormatFeatureFlags undesired_features) {
const VkFormat first_vk_format = static_cast<VkFormat>(1);
const VkFormat last_vk_format = static_cast<VkFormat>(130); // avoid compressed/feature protected, otherwise 184
for (VkFormat format = first_vk_format; format <= last_vk_format; format = static_cast<VkFormat>(format + 1)) {
VkFormatProperties format_props;
vk::GetPhysicalDeviceFormatProperties(gpu, format, &format_props);
const VkFormatFeatureFlags core_filter = 0x1FFF;
const auto features = (tiling == VK_IMAGE_TILING_LINEAR) ? format_props.linearTilingFeatures & core_filter
: format_props.optimalTilingFeatures & core_filter;
const auto valid_features = features & core_filter;
if (undesired_features == UINT32_MAX) {
if (!valid_features) return format;
} else {
if (valid_features && !(valid_features & undesired_features)) return format;
}
}
return VK_FORMAT_UNDEFINED;
}
void AllocateDisjointMemory(VkDeviceObj *device, PFN_vkGetImageMemoryRequirements2KHR fp, VkImage mp_image,
VkDeviceMemory *mp_image_mem, VkImageAspectFlagBits plane) {
VkImagePlaneMemoryRequirementsInfo image_plane_req = {};
image_plane_req.sType = VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO;
image_plane_req.pNext = nullptr;
image_plane_req.planeAspect = plane;
VkImageMemoryRequirementsInfo2 mem_req_info2 = {};
mem_req_info2.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2;
mem_req_info2.pNext = (void *)&image_plane_req;
mem_req_info2.image = mp_image;
VkMemoryRequirements2 mp_image_mem_reqs2 = {};
mp_image_mem_reqs2.sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2;
mp_image_mem_reqs2.pNext = nullptr;
fp(device->device(), &mem_req_info2, &mp_image_mem_reqs2);
VkMemoryAllocateInfo mp_image_alloc_info;
mp_image_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
mp_image_alloc_info.pNext = nullptr;
mp_image_alloc_info.allocationSize = mp_image_mem_reqs2.memoryRequirements.size;
ASSERT_TRUE(device->phy().set_memory_type(mp_image_mem_reqs2.memoryRequirements.memoryTypeBits, &mp_image_alloc_info, 0));
ASSERT_VK_SUCCESS(vk::AllocateMemory(device->device(), &mp_image_alloc_info, NULL, mp_image_mem));
}
void NegHeightViewportTests(VkDeviceObj *m_device, VkCommandBufferObj *m_commandBuffer, ErrorMonitor *m_errorMonitor) {
const auto &limits = m_device->props.limits;
m_commandBuffer->begin();
using std::vector;
struct TestCase {
VkViewport vp;
vector<std::string> vuids;
};
// not necessarily boundary values (unspecified cast rounding), but guaranteed to be over limit
const auto one_before_min_h = NearestSmaller(-static_cast<float>(limits.maxViewportDimensions[1]));
const auto one_past_max_h = NearestGreater(static_cast<float>(limits.maxViewportDimensions[1]));
const auto min_bound = limits.viewportBoundsRange[0];
const auto max_bound = limits.viewportBoundsRange[1];
const auto one_before_min_bound = NearestSmaller(min_bound);
const auto one_past_max_bound = NearestGreater(max_bound);
const vector<TestCase> test_cases = {{{0.0, 0.0, 64.0, one_before_min_h, 0.0, 1.0}, {"VUID-VkViewport-height-01773"}},
{{0.0, 0.0, 64.0, one_past_max_h, 0.0, 1.0}, {"VUID-VkViewport-height-01773"}},
{{0.0, 0.0, 64.0, NAN, 0.0, 1.0}, {"VUID-VkViewport-height-01773"}},
{{0.0, one_before_min_bound, 64.0, 1.0, 0.0, 1.0}, {"VUID-VkViewport-y-01775"}},
{{0.0, one_past_max_bound, 64.0, -1.0, 0.0, 1.0}, {"VUID-VkViewport-y-01776"}},
{{0.0, min_bound, 64.0, -1.0, 0.0, 1.0}, {"VUID-VkViewport-y-01777"}},
{{0.0, max_bound, 64.0, 1.0, 0.0, 1.0}, {"VUID-VkViewport-y-01233"}}};
for (const auto &test_case : test_cases) {
for (const auto &vuid : test_case.vuids) {
if (vuid == "VUID-Undefined")
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "is less than VkPhysicalDeviceLimits::viewportBoundsRange[0]");
else
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, vuid);
}
vk::CmdSetViewport(m_commandBuffer->handle(), 0, 1, &test_case.vp);
m_errorMonitor->VerifyFound();
}
}
void CreateSamplerTest(VkLayerTest &test, const VkSamplerCreateInfo *pCreateInfo, std::string code) {
VkResult err;
VkSampler sampler = VK_NULL_HANDLE;
if (code.length())
test.Monitor().SetDesiredFailureMsg(kErrorBit | kWarningBit, code);
else
test.Monitor().ExpectSuccess();
err = vk::CreateSampler(test.device(), pCreateInfo, NULL, &sampler);
if (code.length())
test.Monitor().VerifyFound();
else
test.Monitor().VerifyNotFound();
if (VK_SUCCESS == err) {
vk::DestroySampler(test.device(), sampler, NULL);
}
}
void CreateBufferTest(VkLayerTest &test, const VkBufferCreateInfo *pCreateInfo, std::string code) {
VkResult err;
VkBuffer buffer = VK_NULL_HANDLE;
if (code.length())
test.Monitor().SetDesiredFailureMsg(kErrorBit, code);
else
test.Monitor().ExpectSuccess();
err = vk::CreateBuffer(test.device(), pCreateInfo, NULL, &buffer);
if (code.length())
test.Monitor().VerifyFound();
else
test.Monitor().VerifyNotFound();
if (VK_SUCCESS == err) {
vk::DestroyBuffer(test.device(), buffer, NULL);
}
}
void CreateImageTest(VkLayerTest &test, const VkImageCreateInfo *pCreateInfo, std::string code) {
VkResult err;
VkImage image = VK_NULL_HANDLE;
if (code.length()) {
test.Monitor().SetDesiredFailureMsg(kErrorBit, code);
// Very possible a test didn't check for VK_ERROR_FORMAT_NOT_SUPPORTED
test.Monitor().SetUnexpectedError("UNASSIGNED-CoreValidation-Image-FormatNotSupported");
} else {
test.Monitor().ExpectSuccess();
}
err = vk::CreateImage(test.device(), pCreateInfo, NULL, &image);
if (code.length())
test.Monitor().VerifyFound();
else
test.Monitor().VerifyNotFound();
if (VK_SUCCESS == err) {
vk::DestroyImage(test.device(), image, NULL);
}
}
void CreateBufferViewTest(VkLayerTest &test, const VkBufferViewCreateInfo *pCreateInfo, const std::vector<std::string> &codes) {
VkResult err;
VkBufferView view = VK_NULL_HANDLE;
if (codes.size())
std::for_each(codes.begin(), codes.end(), [&](const std::string &s) { test.Monitor().SetDesiredFailureMsg(kErrorBit, s); });
else
test.Monitor().ExpectSuccess();
err = vk::CreateBufferView(test.device(), pCreateInfo, NULL, &view);
if (codes.size())
test.Monitor().VerifyFound();
else
test.Monitor().VerifyNotFound();
if (VK_SUCCESS == err) {
vk::DestroyBufferView(test.device(), view, NULL);
}
}
void CreateImageViewTest(VkLayerTest &test, const VkImageViewCreateInfo *pCreateInfo, std::string code) {
VkResult err;
VkImageView view = VK_NULL_HANDLE;
if (code.length())
test.Monitor().SetDesiredFailureMsg(kErrorBit, code);
else
test.Monitor().ExpectSuccess();
err = vk::CreateImageView(test.device(), pCreateInfo, NULL, &view);
if (code.length())
test.Monitor().VerifyFound();
else
test.Monitor().VerifyNotFound();
if (VK_SUCCESS == err) {
vk::DestroyImageView(test.device(), view, NULL);
}
}
VkSamplerCreateInfo SafeSaneSamplerCreateInfo() {
VkSamplerCreateInfo sampler_create_info = {};
sampler_create_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
sampler_create_info.pNext = nullptr;
sampler_create_info.magFilter = VK_FILTER_NEAREST;
sampler_create_info.minFilter = VK_FILTER_NEAREST;
sampler_create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
sampler_create_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
sampler_create_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
sampler_create_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
sampler_create_info.mipLodBias = 0.0;
sampler_create_info.anisotropyEnable = VK_FALSE;
sampler_create_info.maxAnisotropy = 1.0;
sampler_create_info.compareEnable = VK_FALSE;
sampler_create_info.compareOp = VK_COMPARE_OP_NEVER;
sampler_create_info.minLod = 0.0;
sampler_create_info.maxLod = 16.0;
sampler_create_info.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE;
sampler_create_info.unnormalizedCoordinates = VK_FALSE;
return sampler_create_info;
}
VkImageViewCreateInfo SafeSaneImageViewCreateInfo(VkImage image, VkFormat format, VkImageAspectFlags aspect_mask) {
VkImageViewCreateInfo image_view_create_info = {};
image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
image_view_create_info.image = image;
image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
image_view_create_info.format = format;
image_view_create_info.subresourceRange.layerCount = 1;
image_view_create_info.subresourceRange.baseMipLevel = 0;
image_view_create_info.subresourceRange.levelCount = 1;
image_view_create_info.subresourceRange.aspectMask = aspect_mask;
return image_view_create_info;
}
VkImageViewCreateInfo SafeSaneImageViewCreateInfo(const VkImageObj &image, VkFormat format, VkImageAspectFlags aspect_mask) {
return SafeSaneImageViewCreateInfo(image.handle(), format, aspect_mask);
}
bool CheckCreateRenderPass2Support(VkRenderFramework *renderFramework, std::vector<const char *> &device_extension_names) {
if (renderFramework->DeviceExtensionSupported(renderFramework->gpu(), nullptr, VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME)) {
device_extension_names.push_back(VK_KHR_MULTIVIEW_EXTENSION_NAME);
device_extension_names.push_back(VK_KHR_MAINTENANCE_2_EXTENSION_NAME);
device_extension_names.push_back(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME);
return true;
}
return false;
}
bool CheckDescriptorIndexingSupportAndInitFramework(VkRenderFramework *renderFramework,
std::vector<const char *> &instance_extension_names,
std::vector<const char *> &device_extension_names,
VkValidationFeaturesEXT *features, void *userData) {
bool descriptor_indexing = renderFramework->InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
if (descriptor_indexing) {
instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
}
renderFramework->InitFramework(userData, features);
descriptor_indexing = descriptor_indexing && renderFramework->DeviceExtensionSupported(renderFramework->gpu(), nullptr,
VK_KHR_MAINTENANCE_3_EXTENSION_NAME);
descriptor_indexing = descriptor_indexing && renderFramework->DeviceExtensionSupported(
renderFramework->gpu(), nullptr, VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME);
if (descriptor_indexing) {
device_extension_names.push_back(VK_KHR_MAINTENANCE_3_EXTENSION_NAME);
device_extension_names.push_back(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME);
return true;
}
return false;
}
bool CheckTimelineSemaphoreSupportAndInitState(VkRenderFramework *renderFramework) {
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(renderFramework->instance(),
"vkGetPhysicalDeviceFeatures2KHR");
auto timeline_semaphore_features = LvlInitStruct<VkPhysicalDeviceTimelineSemaphoreFeatures>();
auto features2 = LvlInitStruct<VkPhysicalDeviceFeatures2KHR>(&timeline_semaphore_features);
vkGetPhysicalDeviceFeatures2KHR(renderFramework->gpu(), &features2);
if (!timeline_semaphore_features.timelineSemaphore) {
return false;
}
renderFramework->InitState(nullptr, &features2);
return true;
}
bool CheckSynchronization2SupportAndInitState(VkRenderFramework *framework) {
PFN_vkGetPhysicalDeviceFeatures2 vkGetPhysicalDeviceFeatures2 =
(PFN_vkGetPhysicalDeviceFeatures2)vk::GetInstanceProcAddr(framework->instance(),
"vkGetPhysicalDeviceFeatures2");
auto sync2_features = lvl_init_struct<VkPhysicalDeviceSynchronization2FeaturesKHR>();
auto features2 = lvl_init_struct<VkPhysicalDeviceFeatures2>(&sync2_features);
vkGetPhysicalDeviceFeatures2(framework->gpu(), &features2);
if (!sync2_features.synchronization2) {
return false;
}
framework->InitState(nullptr, &features2,VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT);
return true;
}
void VkLayerTest::VKTriangleTest(BsoFailSelect failCase) {
ASSERT_TRUE(m_device && m_device->initialized()); // VKTriangleTest assumes Init() has finished
ASSERT_NO_FATAL_FAILURE(InitViewport());
VkShaderObj vs(m_device, bindStateVertShaderText, VK_SHADER_STAGE_VERTEX_BIT, this);
VkShaderObj ps(m_device, bindStateFragShaderText, VK_SHADER_STAGE_FRAGMENT_BIT, this);
VkPipelineObj pipelineobj(m_device);
pipelineobj.AddDefaultColorAttachment();
pipelineobj.AddShader(&vs);
pipelineobj.AddShader(&ps);
bool failcase_needs_depth = false; // to mark cases that need depth attachment
VkBufferObj index_buffer;
switch (failCase) {
case BsoFailLineWidth: {
pipelineobj.MakeDynamic(VK_DYNAMIC_STATE_LINE_WIDTH);
VkPipelineInputAssemblyStateCreateInfo ia_state = {};
ia_state.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
ia_state.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST;
pipelineobj.SetInputAssembly(&ia_state);
break;
}
case BsoFailLineStipple: {
pipelineobj.MakeDynamic(VK_DYNAMIC_STATE_LINE_STIPPLE_EXT);
VkPipelineInputAssemblyStateCreateInfo ia_state = {};
ia_state.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
ia_state.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST;
pipelineobj.SetInputAssembly(&ia_state);
VkPipelineRasterizationLineStateCreateInfoEXT line_state = {};
line_state.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_LINE_STATE_CREATE_INFO_EXT;
line_state.lineRasterizationMode = VK_LINE_RASTERIZATION_MODE_BRESENHAM_EXT;
line_state.stippledLineEnable = VK_TRUE;
line_state.lineStippleFactor = 0;
line_state.lineStipplePattern = 0;
pipelineobj.SetLineState(&line_state);
break;
}
case BsoFailDepthBias: {
pipelineobj.MakeDynamic(VK_DYNAMIC_STATE_DEPTH_BIAS);
VkPipelineRasterizationStateCreateInfo rs_state = {};
rs_state.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rs_state.depthBiasEnable = VK_TRUE;
rs_state.lineWidth = 1.0f;
pipelineobj.SetRasterization(&rs_state);
break;
}
case BsoFailViewport: {
pipelineobj.MakeDynamic(VK_DYNAMIC_STATE_VIEWPORT);
break;
}
case BsoFailScissor: {
pipelineobj.MakeDynamic(VK_DYNAMIC_STATE_SCISSOR);
break;
}
case BsoFailBlend: {
pipelineobj.MakeDynamic(VK_DYNAMIC_STATE_BLEND_CONSTANTS);
VkPipelineColorBlendAttachmentState att_state = {};
att_state.dstAlphaBlendFactor = VK_BLEND_FACTOR_CONSTANT_COLOR;
att_state.blendEnable = VK_TRUE;
pipelineobj.AddColorAttachment(0, att_state);
break;
}
case BsoFailDepthBounds: {
failcase_needs_depth = true;
pipelineobj.MakeDynamic(VK_DYNAMIC_STATE_DEPTH_BOUNDS);
break;
}
case BsoFailStencilReadMask: {
failcase_needs_depth = true;
pipelineobj.MakeDynamic(VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK);
break;
}
case BsoFailStencilWriteMask: {
failcase_needs_depth = true;
pipelineobj.MakeDynamic(VK_DYNAMIC_STATE_STENCIL_WRITE_MASK);
break;
}
case BsoFailStencilReference: {
failcase_needs_depth = true;
pipelineobj.MakeDynamic(VK_DYNAMIC_STATE_STENCIL_REFERENCE);
break;
}
case BsoFailIndexBuffer:
break;
case BsoFailIndexBufferBadSize:
case BsoFailIndexBufferBadOffset:
case BsoFailIndexBufferBadMapSize:
case BsoFailIndexBufferBadMapOffset: {
// Create an index buffer for these tests.
// There is no need to populate it because we should bail before trying to draw.
uint32_t const indices[] = {0};
VkBufferCreateInfo buffer_info = {};
buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_info.size = 1024;
buffer_info.usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
buffer_info.queueFamilyIndexCount = 1;
buffer_info.pQueueFamilyIndices = indices;
index_buffer.init(*m_device, buffer_info, (VkMemoryPropertyFlags)VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
} break;
case BsoFailCmdClearAttachments:
break;
case BsoFailNone:
break;
default:
break;
}
VkDescriptorSetObj descriptorSet(m_device);
VkImageView *depth_attachment = nullptr;
if (failcase_needs_depth) {
m_depth_stencil_fmt = FindSupportedDepthStencilFormat(gpu());
ASSERT_TRUE(m_depth_stencil_fmt != VK_FORMAT_UNDEFINED);
m_depthStencil->Init(m_device, static_cast<uint32_t>(m_width), static_cast<uint32_t>(m_height), m_depth_stencil_fmt,
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
depth_attachment = m_depthStencil->BindInfo();
}
ASSERT_NO_FATAL_FAILURE(InitRenderTarget(1, depth_attachment));
m_commandBuffer->begin();
GenericDrawPreparation(m_commandBuffer, pipelineobj, descriptorSet, failCase);
m_commandBuffer->BeginRenderPass(m_renderPassBeginInfo);
// render triangle
if (failCase == BsoFailIndexBuffer) {
// Use DrawIndexed w/o an index buffer bound
m_commandBuffer->DrawIndexed(3, 1, 0, 0, 0);
} else if (failCase == BsoFailIndexBufferBadSize) {
// Bind the index buffer and draw one too many indices
m_commandBuffer->BindIndexBuffer(&index_buffer, 0, VK_INDEX_TYPE_UINT16);
m_commandBuffer->DrawIndexed(513, 1, 0, 0, 0);
} else if (failCase == BsoFailIndexBufferBadOffset) {
// Bind the index buffer and draw one past the end of the buffer using the offset
m_commandBuffer->BindIndexBuffer(&index_buffer, 0, VK_INDEX_TYPE_UINT16);
m_commandBuffer->DrawIndexed(512, 1, 1, 0, 0);
} else if (failCase == BsoFailIndexBufferBadMapSize) {
// Bind the index buffer at the middle point and draw one too many indices
m_commandBuffer->BindIndexBuffer(&index_buffer, 512, VK_INDEX_TYPE_UINT16);
m_commandBuffer->DrawIndexed(257, 1, 0, 0, 0);
} else if (failCase == BsoFailIndexBufferBadMapOffset) {
// Bind the index buffer at the middle point and draw one past the end of the buffer
m_commandBuffer->BindIndexBuffer(&index_buffer, 512, VK_INDEX_TYPE_UINT16);
m_commandBuffer->DrawIndexed(256, 1, 1, 0, 0);
} else {
m_commandBuffer->Draw(3, 1, 0, 0);
}
if (failCase == BsoFailCmdClearAttachments) {
VkClearAttachment color_attachment = {};
color_attachment.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
color_attachment.colorAttachment = 2000000000; // Someone who knew what they were doing would use 0 for the index;
VkClearRect clear_rect = {{{0, 0}, {static_cast<uint32_t>(m_width), static_cast<uint32_t>(m_height)}}, 0, 1};
vk::CmdClearAttachments(m_commandBuffer->handle(), 1, &color_attachment, 1, &clear_rect);
}
// finalize recording of the command buffer
m_commandBuffer->EndRenderPass();
m_commandBuffer->end();
m_commandBuffer->QueueCommandBuffer(true);
DestroyRenderTarget();
}
void VkLayerTest::GenericDrawPreparation(VkCommandBufferObj *commandBuffer, VkPipelineObj &pipelineobj,
VkDescriptorSetObj &descriptorSet, BsoFailSelect failCase) {
commandBuffer->ClearAllBuffers(m_renderTargets, m_clear_color, m_depthStencil, m_depth_clear_color, m_stencil_clear_color);
commandBuffer->PrepareAttachments(m_renderTargets, m_depthStencil);
// Make sure depthWriteEnable is set so that Depth fail test will work
// correctly
// Make sure stencilTestEnable is set so that Stencil fail test will work
// correctly
VkStencilOpState stencil = {};
stencil.failOp = VK_STENCIL_OP_KEEP;
stencil.passOp = VK_STENCIL_OP_KEEP;
stencil.depthFailOp = VK_STENCIL_OP_KEEP;
stencil.compareOp = VK_COMPARE_OP_NEVER;
VkPipelineDepthStencilStateCreateInfo ds_ci = {};
ds_ci.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
ds_ci.pNext = NULL;
ds_ci.depthTestEnable = VK_FALSE;
ds_ci.depthWriteEnable = VK_TRUE;
ds_ci.depthCompareOp = VK_COMPARE_OP_NEVER;
ds_ci.depthBoundsTestEnable = VK_FALSE;
if (failCase == BsoFailDepthBounds) {
ds_ci.depthBoundsTestEnable = VK_TRUE;
ds_ci.maxDepthBounds = 0.0f;
ds_ci.minDepthBounds = 0.0f;
}
ds_ci.stencilTestEnable = VK_TRUE;
ds_ci.front = stencil;
ds_ci.back = stencil;
pipelineobj.SetDepthStencil(&ds_ci);
pipelineobj.SetViewport(m_viewports);
pipelineobj.SetScissor(m_scissors);
descriptorSet.CreateVKDescriptorSet(commandBuffer);
VkResult err = pipelineobj.CreateVKPipeline(descriptorSet.GetPipelineLayout(), renderPass());
ASSERT_VK_SUCCESS(err);
vk::CmdBindPipeline(commandBuffer->handle(), VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineobj.handle());
commandBuffer->BindDescriptorSet(descriptorSet);
}
void VkLayerTest::Init(VkPhysicalDeviceFeatures *features, VkPhysicalDeviceFeatures2 *features2,
const VkCommandPoolCreateFlags flags, void *instance_pnext) {
InitFramework(m_errorMonitor, instance_pnext);
InitState(features, features2, flags);
}
VkCommandBufferObj *VkLayerTest::CommandBuffer() { return m_commandBuffer; }
VkLayerTest::VkLayerTest() {
m_enableWSI = false;
// TODO: not quite sure why most of this is here instead of in super
// Add default instance extensions to the list
instance_extensions_.push_back(debug_reporter_.debug_extension_name);
instance_layers_.push_back(kValidationLayerName);
if (VkTestFramework::m_devsim_layer) {
if (InstanceLayerSupported("VK_LAYER_LUNARG_device_simulation")) {
instance_layers_.push_back("VK_LAYER_LUNARG_device_simulation");
} else {
VkTestFramework::m_devsim_layer = false;
printf(" Did not find VK_LAYER_LUNARG_device_simulation layer so it will not be enabled.\n");
}
} else {
if (InstanceLayerSupported("VK_LAYER_LUNARG_device_profile_api"))
instance_layers_.push_back("VK_LAYER_LUNARG_device_profile_api");
}
if (InstanceLayerSupported(kSynchronization2LayerName)) {
instance_layers_.push_back(kSynchronization2LayerName);
}
app_info_.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app_info_.pNext = NULL;
app_info_.pApplicationName = "layer_tests";
app_info_.applicationVersion = 1;
app_info_.pEngineName = "unittest";
app_info_.engineVersion = 1;
app_info_.apiVersion = VK_API_VERSION_1_0;
// Find out what version the instance supports and record the default target instance
auto enumerateInstanceVersion = (PFN_vkEnumerateInstanceVersion)vk::GetInstanceProcAddr(nullptr, "vkEnumerateInstanceVersion");
if (enumerateInstanceVersion) {
enumerateInstanceVersion(&m_instance_api_version);
} else {
m_instance_api_version = VK_API_VERSION_1_0;
}
m_target_api_version = app_info_.apiVersion;
}
bool VkLayerTest::AddSurfaceInstanceExtension() {
m_enableWSI = true;
if (!InstanceExtensionSupported(VK_KHR_SURFACE_EXTENSION_NAME)) {
printf("%s %s extension not supported\n", kSkipPrefix, VK_KHR_SURFACE_EXTENSION_NAME);
return false;
}
instance_extensions_.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
bool bSupport = false;
#if defined(VK_USE_PLATFORM_WIN32_KHR)
if (!InstanceExtensionSupported(VK_KHR_WIN32_SURFACE_EXTENSION_NAME)) {
printf("%s %s extension not supported\n", kSkipPrefix, VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
return false;
}
instance_extensions_.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
bSupport = true;
#endif
#if defined(VK_USE_PLATFORM_ANDROID_KHR) && defined(VALIDATION_APK)
if (!InstanceExtensionSupported(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME)) {
printf("%s %s extension not supported\n", kSkipPrefix, VK_KHR_ANDROID_SURFACE_EXTENSION_NAME);
return false;
}
instance_extensions_.push_back(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME);
bSupport = true;
#endif
#if defined(VK_USE_PLATFORM_XLIB_KHR)
if (!InstanceExtensionSupported(VK_KHR_XLIB_SURFACE_EXTENSION_NAME)) {
printf("%s %s extension not supported\n", kSkipPrefix, VK_KHR_XLIB_SURFACE_EXTENSION_NAME);
return false;
}
auto temp_dpy = XOpenDisplay(NULL);
if (temp_dpy) {
instance_extensions_.push_back(VK_KHR_XLIB_SURFACE_EXTENSION_NAME);
bSupport = true;
XCloseDisplay(temp_dpy);
}
#endif
#if defined(VK_USE_PLATFORM_XCB_KHR)
if (!InstanceExtensionSupported(VK_KHR_XCB_SURFACE_EXTENSION_NAME)) {
printf("%s %s extension not supported\n", kSkipPrefix, VK_KHR_XCB_SURFACE_EXTENSION_NAME);
return false;
}
if (!bSupport) {
auto temp_xcb = xcb_connect(NULL, NULL);
if (temp_xcb) {
instance_extensions_.push_back(VK_KHR_XCB_SURFACE_EXTENSION_NAME);
bSupport = true;
xcb_disconnect(temp_xcb);
}
}
#endif
if (bSupport) return true;
printf("%s No platform's surface extension supported\n", kSkipPrefix);
return false;
}
bool VkLayerTest::AddSwapchainDeviceExtension() {
if (!DeviceExtensionSupported(gpu(), nullptr, VK_KHR_SWAPCHAIN_EXTENSION_NAME)) {
printf("%s %s extension not supported\n", kSkipPrefix, VK_KHR_SWAPCHAIN_EXTENSION_NAME);
return false;
}
m_device_extension_names.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
return true;
}
uint32_t VkLayerTest::SetTargetApiVersion(uint32_t target_api_version) {
if (target_api_version == 0) target_api_version = VK_API_VERSION_1_0;
if (target_api_version <= m_instance_api_version) {
m_target_api_version = target_api_version;
app_info_.apiVersion = m_target_api_version;
}
return m_target_api_version;
}
uint32_t VkLayerTest::DeviceValidationVersion() {
// The validation layers assume the version we are validating to is the apiVersion unless the device apiVersion is lower
return std::min(m_target_api_version, physDevProps().apiVersion);
}
bool VkLayerTest::LoadDeviceProfileLayer(
PFN_vkSetPhysicalDeviceFormatPropertiesEXT &fpvkSetPhysicalDeviceFormatPropertiesEXT,
PFN_vkGetOriginalPhysicalDeviceFormatPropertiesEXT &fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT) {
// Load required functions
fpvkSetPhysicalDeviceFormatPropertiesEXT =
(PFN_vkSetPhysicalDeviceFormatPropertiesEXT)vk::GetInstanceProcAddr(instance(), "vkSetPhysicalDeviceFormatPropertiesEXT");
fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT = (PFN_vkGetOriginalPhysicalDeviceFormatPropertiesEXT)vk::GetInstanceProcAddr(
instance(), "vkGetOriginalPhysicalDeviceFormatPropertiesEXT");
if (!(fpvkSetPhysicalDeviceFormatPropertiesEXT) || !(fpvkGetOriginalPhysicalDeviceFormatPropertiesEXT)) {
printf("%s Can't find device_profile_api functions; skipped.\n", kSkipPrefix);
return 0;
}
return 1;
}
bool VkLayerTest::LoadDeviceProfileLayer(
PFN_vkSetPhysicalDeviceFormatProperties2EXT &fpvkSetPhysicalDeviceFormatProperties2EXT,
PFN_vkGetOriginalPhysicalDeviceFormatProperties2EXT &fpvkGetOriginalPhysicalDeviceFormatProperties2EXT) {
// Load required functions
fpvkSetPhysicalDeviceFormatProperties2EXT =
(PFN_vkSetPhysicalDeviceFormatProperties2EXT)vk::GetInstanceProcAddr(instance(), "vkSetPhysicalDeviceFormatProperties2EXT");
fpvkGetOriginalPhysicalDeviceFormatProperties2EXT =
(PFN_vkGetOriginalPhysicalDeviceFormatProperties2EXT)vk::GetInstanceProcAddr(
instance(), "vkGetOriginalPhysicalDeviceFormatProperties2EXT");
if (!(fpvkSetPhysicalDeviceFormatProperties2EXT) || !(fpvkGetOriginalPhysicalDeviceFormatProperties2EXT)) {
printf("%s Can't find device_profile_api functions; skipped.\n", kSkipPrefix);
return false;
}
return true;
}
bool VkLayerTest::LoadDeviceProfileLayer(PFN_vkSetPhysicalDeviceLimitsEXT &fpvkSetPhysicalDeviceLimitsEXT,
PFN_vkGetOriginalPhysicalDeviceLimitsEXT &fpvkGetOriginalPhysicalDeviceLimitsEXT) {
// Load required functions
fpvkSetPhysicalDeviceLimitsEXT =
(PFN_vkSetPhysicalDeviceLimitsEXT)vk::GetInstanceProcAddr(instance(), "vkSetPhysicalDeviceLimitsEXT");
fpvkGetOriginalPhysicalDeviceLimitsEXT =
(PFN_vkGetOriginalPhysicalDeviceLimitsEXT)vk::GetInstanceProcAddr(instance(), "vkGetOriginalPhysicalDeviceLimitsEXT");
if (!(fpvkSetPhysicalDeviceLimitsEXT) || !(fpvkGetOriginalPhysicalDeviceLimitsEXT)) {
printf("%s Can't find device_profile_api functions; skipped.\n", kSkipPrefix);
return false;
}
return true;
}
bool VkBufferTest::GetTestConditionValid(VkDeviceObj *aVulkanDevice, eTestEnFlags aTestFlag, VkBufferUsageFlags aBufferUsage) {
if (eInvalidDeviceOffset != aTestFlag && eInvalidMemoryOffset != aTestFlag) {
return true;
}
VkDeviceSize offset_limit = 0;
if (eInvalidMemoryOffset == aTestFlag) {
VkBuffer vulkanBuffer;
VkBufferCreateInfo buffer_create_info = {};
buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_create_info.size = 32;
buffer_create_info.usage = aBufferUsage;
vk::CreateBuffer(aVulkanDevice->device(), &buffer_create_info, nullptr, &vulkanBuffer);
VkMemoryRequirements memory_reqs = {};
vk::GetBufferMemoryRequirements(aVulkanDevice->device(), vulkanBuffer, &memory_reqs);
vk::DestroyBuffer(aVulkanDevice->device(), vulkanBuffer, nullptr);
offset_limit = memory_reqs.alignment;
} else if ((VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT) & aBufferUsage) {
offset_limit = aVulkanDevice->props.limits.minTexelBufferOffsetAlignment;
} else if (VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT & aBufferUsage) {
offset_limit = aVulkanDevice->props.limits.minUniformBufferOffsetAlignment;
} else if (VK_BUFFER_USAGE_STORAGE_BUFFER_BIT & aBufferUsage) {
offset_limit = aVulkanDevice->props.limits.minStorageBufferOffsetAlignment;
}
return eOffsetAlignment < offset_limit;
}
VkBufferTest::VkBufferTest(VkDeviceObj *aVulkanDevice, VkBufferUsageFlags aBufferUsage, eTestEnFlags aTestFlag)
: AllocateCurrent(true),
BoundCurrent(false),
CreateCurrent(false),
InvalidDeleteEn(false),
VulkanDevice(aVulkanDevice->device()) {
if (eBindNullBuffer == aTestFlag || eBindFakeBuffer == aTestFlag) {
VkMemoryAllocateInfo memory_allocate_info = {};
memory_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
memory_allocate_info.allocationSize = 1; // fake size -- shouldn't matter for the test
memory_allocate_info.memoryTypeIndex = 0; // fake type -- shouldn't matter for the test
vk::AllocateMemory(VulkanDevice, &memory_allocate_info, nullptr, &VulkanMemory);
VulkanBuffer = (aTestFlag == eBindNullBuffer) ? VK_NULL_HANDLE : (VkBuffer)0xCDCDCDCDCDCDCDCD;
vk::BindBufferMemory(VulkanDevice, VulkanBuffer, VulkanMemory, 0);
} else {
VkBufferCreateInfo buffer_create_info = {};
buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buffer_create_info.size = 32;
buffer_create_info.usage = aBufferUsage;
vk::CreateBuffer(VulkanDevice, &buffer_create_info, nullptr, &VulkanBuffer);
CreateCurrent = true;
VkMemoryRequirements memory_requirements;
vk::GetBufferMemoryRequirements(VulkanDevice, VulkanBuffer, &memory_requirements);
VkMemoryAllocateInfo memory_allocate_info = {};
memory_allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
memory_allocate_info.allocationSize = memory_requirements.size + eOffsetAlignment;
bool pass = aVulkanDevice->phy().set_memory_type(memory_requirements.memoryTypeBits, &memory_allocate_info,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
if (!pass) {
CreateCurrent = false;
vk::DestroyBuffer(VulkanDevice, VulkanBuffer, nullptr);
return;
}
vk::AllocateMemory(VulkanDevice, &memory_allocate_info, NULL, &VulkanMemory);
// NB: 1 is intentionally an invalid offset value
const bool offset_en = eInvalidDeviceOffset == aTestFlag || eInvalidMemoryOffset == aTestFlag;
vk::BindBufferMemory(VulkanDevice, VulkanBuffer, VulkanMemory, offset_en ? eOffsetAlignment : 0);
BoundCurrent = true;
InvalidDeleteEn = (eFreeInvalidHandle == aTestFlag);
}
}
VkBufferTest::~VkBufferTest() {
if (CreateCurrent) {
vk::DestroyBuffer(VulkanDevice, VulkanBuffer, nullptr);
}
if (AllocateCurrent) {
if (InvalidDeleteEn) {
auto bad_memory = CastFromUint64<VkDeviceMemory>(CastToUint64(VulkanMemory) + 1);
vk::FreeMemory(VulkanDevice, bad_memory, nullptr);
}
vk::FreeMemory(VulkanDevice, VulkanMemory, nullptr);
}
}
void SetImageLayout(VkDeviceObj *device, VkImageAspectFlags aspect, VkImage image, VkImageLayout image_layout) {
VkCommandPoolObj pool(device, device->graphics_queue_node_index_);
VkCommandBufferObj cmd_buf(device, &pool);
cmd_buf.begin();
VkImageMemoryBarrier layout_barrier{ VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
nullptr,
0,
VK_ACCESS_MEMORY_READ_BIT,
VK_IMAGE_LAYOUT_UNDEFINED,
image_layout,
VK_QUEUE_FAMILY_IGNORED,
VK_QUEUE_FAMILY_IGNORED,
image,
{aspect, 0, 1, 0, 1} };
cmd_buf.PipelineBarrier(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0, nullptr, 1,
&layout_barrier);
cmd_buf.end();
cmd_buf.QueueCommandBuffer();
}
std::unique_ptr<VkImageObj> VkArmBestPracticesLayerTest::CreateImage(VkFormat format, const uint32_t width,
const uint32_t height,
VkImageUsageFlags attachment_usage) {
auto img = std::unique_ptr<VkImageObj>(new VkImageObj(m_device));
img->Init(width, height, 1, format,
VK_IMAGE_USAGE_SAMPLED_BIT | attachment_usage |
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,
VK_IMAGE_TILING_OPTIMAL);
return img;
}
VkRenderPass VkArmBestPracticesLayerTest::CreateRenderPass(VkFormat format, VkAttachmentLoadOp load_op,
VkAttachmentStoreOp store_op) {
VkRenderPass renderpass{VK_NULL_HANDLE};
// Create renderpass
VkAttachmentDescription attachment = {};
attachment.format = format;
attachment.samples = VK_SAMPLE_COUNT_1_BIT;
attachment.loadOp = load_op;
attachment.storeOp = store_op;
attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachment.finalLayout = VK_IMAGE_LAYOUT_GENERAL;
VkAttachmentReference attachment_reference = {};
attachment_reference.attachment = 0;
attachment_reference.layout = VK_IMAGE_LAYOUT_GENERAL;
VkSubpassDescription subpass = {};
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &attachment_reference;
VkRenderPassCreateInfo rpinf = {
VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
};
rpinf.attachmentCount = 1;
rpinf.pAttachments = &attachment;
rpinf.subpassCount = 1;
rpinf.pSubpasses = &subpass;
rpinf.dependencyCount = 0;
rpinf.pDependencies = nullptr;
vk::CreateRenderPass(m_device->handle(), &rpinf, nullptr, &renderpass);
return renderpass;
}
VkFramebuffer VkArmBestPracticesLayerTest::CreateFramebuffer(const uint32_t width, const uint32_t height, VkImageView image_view,
VkRenderPass renderpass) {
VkFramebuffer framebuffer{VK_NULL_HANDLE};
VkFramebufferCreateInfo framebuffer_create_info = {VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO};
framebuffer_create_info.renderPass = renderpass;
framebuffer_create_info.attachmentCount = 1;
framebuffer_create_info.pAttachments = &image_view;
framebuffer_create_info.width = width;
framebuffer_create_info.height = height;
framebuffer_create_info.layers = 1;
vk::CreateFramebuffer(m_device->handle(), &framebuffer_create_info, nullptr, &framebuffer);
return framebuffer;
}
VkSampler VkArmBestPracticesLayerTest::CreateDefaultSampler() {
VkSampler sampler{VK_NULL_HANDLE};
VkSamplerCreateInfo sampler_create_info = {VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO};
sampler_create_info.magFilter = VK_FILTER_NEAREST;
sampler_create_info.minFilter = VK_FILTER_NEAREST;
sampler_create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
sampler_create_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
sampler_create_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
sampler_create_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
sampler_create_info.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE;
sampler_create_info.maxLod = VK_LOD_CLAMP_NONE;
vk::CreateSampler(m_device->handle(), &sampler_create_info, nullptr, &sampler);
return sampler;
}
bool VkBufferTest::GetBufferCurrent() { return AllocateCurrent && BoundCurrent && CreateCurrent; }
const VkBuffer &VkBufferTest::GetBuffer() { return VulkanBuffer; }
void VkBufferTest::TestDoubleDestroy() {
// Destroy the buffer but leave the flag set, which will cause
// the buffer to be destroyed again in the destructor.
vk::DestroyBuffer(VulkanDevice, VulkanBuffer, nullptr);
}
uint32_t VkVerticesObj::BindIdGenerator;
VkVerticesObj::VkVerticesObj(VkDeviceObj *aVulkanDevice, unsigned aAttributeCount, unsigned aBindingCount, unsigned aByteStride,
VkDeviceSize aVertexCount, const float *aVerticies)
: BoundCurrent(false),
AttributeCount(aAttributeCount),
BindingCount(aBindingCount),
BindId(BindIdGenerator),
PipelineVertexInputStateCreateInfo(),
VulkanMemoryBuffer(aVulkanDevice, static_cast<int>(aByteStride * aVertexCount), reinterpret_cast<const void *>(aVerticies),
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT) {
BindIdGenerator++; // NB: This can wrap w/misuse
VertexInputAttributeDescription = new VkVertexInputAttributeDescription[AttributeCount];
VertexInputBindingDescription = new VkVertexInputBindingDescription[BindingCount];
PipelineVertexInputStateCreateInfo.pVertexAttributeDescriptions = VertexInputAttributeDescription;
PipelineVertexInputStateCreateInfo.vertexAttributeDescriptionCount = AttributeCount;
PipelineVertexInputStateCreateInfo.pVertexBindingDescriptions = VertexInputBindingDescription;
PipelineVertexInputStateCreateInfo.vertexBindingDescriptionCount = BindingCount;
PipelineVertexInputStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
unsigned i = 0;
do {
VertexInputAttributeDescription[i].binding = BindId;
VertexInputAttributeDescription[i].location = i;
VertexInputAttributeDescription[i].format = VK_FORMAT_R32G32B32_SFLOAT;
VertexInputAttributeDescription[i].offset = sizeof(float) * aByteStride;
i++;
} while (AttributeCount < i);
i = 0;
do {
VertexInputBindingDescription[i].binding = BindId;
VertexInputBindingDescription[i].stride = aByteStride;
VertexInputBindingDescription[i].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
i++;
} while (BindingCount < i);
}
VkVerticesObj::~VkVerticesObj() {
if (VertexInputAttributeDescription) {
delete[] VertexInputAttributeDescription;
}
if (VertexInputBindingDescription) {
delete[] VertexInputBindingDescription;
}
}
bool VkVerticesObj::AddVertexInputToPipe(VkPipelineObj &aPipelineObj) {
aPipelineObj.AddVertexInputAttribs(VertexInputAttributeDescription, AttributeCount);
aPipelineObj.AddVertexInputBindings(VertexInputBindingDescription, BindingCount);
return true;
}
bool VkVerticesObj::AddVertexInputToPipeHelpr(CreatePipelineHelper *pipelineHelper) {
pipelineHelper->vi_ci_.pVertexBindingDescriptions = VertexInputBindingDescription;
pipelineHelper->vi_ci_.vertexBindingDescriptionCount = BindingCount;
pipelineHelper->vi_ci_.pVertexAttributeDescriptions = VertexInputAttributeDescription;
pipelineHelper->vi_ci_.vertexAttributeDescriptionCount = AttributeCount;
return true;
}
void VkVerticesObj::BindVertexBuffers(VkCommandBuffer aCommandBuffer, unsigned aOffsetCount, VkDeviceSize *aOffsetList) {
VkDeviceSize *offsetList;
unsigned offsetCount;
if (aOffsetCount) {
offsetList = aOffsetList;
offsetCount = aOffsetCount;
} else {
offsetList = new VkDeviceSize[1]();
offsetCount = 1;
}
vk::CmdBindVertexBuffers(aCommandBuffer, BindId, offsetCount, &VulkanMemoryBuffer.handle(), offsetList);
BoundCurrent = true;
if (!aOffsetCount) {
delete[] offsetList;
}
}
OneOffDescriptorSet::OneOffDescriptorSet(VkDeviceObj *device, const Bindings &bindings,
VkDescriptorSetLayoutCreateFlags layout_flags, void *layout_pnext,
VkDescriptorPoolCreateFlags poolFlags, void *allocate_pnext, int buffer_info_size,
int image_info_size, int buffer_view_size)
: device_{device}, pool_{}, layout_(device, bindings, layout_flags, layout_pnext), set_{} {
VkResult err;
buffer_infos.reserve(buffer_info_size);
image_infos.reserve(image_info_size);
buffer_views.reserve(buffer_view_size);
std::vector<VkDescriptorPoolSize> sizes;
for (const auto &b : bindings) sizes.push_back({b.descriptorType, std::max(1u, b.descriptorCount)});
VkDescriptorPoolCreateInfo dspci = {
VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, nullptr, poolFlags, 1, uint32_t(sizes.size()), sizes.data()};
err = vk::CreateDescriptorPool(device_->handle(), &dspci, nullptr, &pool_);
if (err != VK_SUCCESS) return;
if ((layout_flags & VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR) == 0) {
VkDescriptorSetAllocateInfo alloc_info = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, allocate_pnext, pool_, 1,
&layout_.handle()};
err = vk::AllocateDescriptorSets(device_->handle(), &alloc_info, &set_);
}
}
OneOffDescriptorSet::~OneOffDescriptorSet() {
// No need to destroy set-- it's going away with the pool.
vk::DestroyDescriptorPool(device_->handle(), pool_, nullptr);
}
bool OneOffDescriptorSet::Initialized() { return pool_ != VK_NULL_HANDLE && layout_.initialized() && set_ != VK_NULL_HANDLE; }
void OneOffDescriptorSet::Clear() {
buffer_infos.clear();
image_infos.clear();
buffer_views.clear();
descriptor_writes.clear();
}
void OneOffDescriptorSet::WriteDescriptorBufferInfo(int binding, VkBuffer buffer, VkDeviceSize offset, VkDeviceSize range,
VkDescriptorType descriptorType, uint32_t arrayElement, uint32_t count) {
const auto index = buffer_infos.size();
VkDescriptorBufferInfo buffer_info = {};
buffer_info.buffer = buffer;
buffer_info.offset = offset;
buffer_info.range = range;
for (uint32_t i = 0; i < count; ++i) {
buffer_infos.emplace_back(buffer_info);
}
VkWriteDescriptorSet descriptor_write;
memset(&descriptor_write, 0, sizeof(descriptor_write));
descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptor_write.dstSet = set_;
descriptor_write.dstBinding = binding;
descriptor_write.dstArrayElement = arrayElement;
descriptor_write.descriptorCount = count;
descriptor_write.descriptorType = descriptorType;
descriptor_write.pBufferInfo = &buffer_infos[index];
descriptor_write.pImageInfo = nullptr;
descriptor_write.pTexelBufferView = nullptr;
descriptor_writes.emplace_back(descriptor_write);
}
void OneOffDescriptorSet::WriteDescriptorBufferView(int binding, VkBufferView buffer_view, VkDescriptorType descriptorType,
uint32_t arrayElement, uint32_t count) {
const auto index = buffer_views.size();
for (uint32_t i = 0; i < count; ++i) {
buffer_views.emplace_back(buffer_view);
}
VkWriteDescriptorSet descriptor_write;
memset(&descriptor_write, 0, sizeof(descriptor_write));
descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptor_write.dstSet = set_;
descriptor_write.dstBinding = binding;
descriptor_write.dstArrayElement = arrayElement;
descriptor_write.descriptorCount = count;
descriptor_write.descriptorType = descriptorType;
descriptor_write.pTexelBufferView = &buffer_views[index];
descriptor_write.pImageInfo = nullptr;
descriptor_write.pBufferInfo = nullptr;
descriptor_writes.emplace_back(descriptor_write);
}
void OneOffDescriptorSet::WriteDescriptorImageInfo(int binding, VkImageView image_view, VkSampler sampler,
VkDescriptorType descriptorType, VkImageLayout imageLayout,
uint32_t arrayElement, uint32_t count) {
const auto index = image_infos.size();
VkDescriptorImageInfo image_info = {};
image_info.imageView = image_view;
image_info.sampler = sampler;
image_info.imageLayout = imageLayout;
for (uint32_t i = 0; i < count; ++i) {
image_infos.emplace_back(image_info);
}
VkWriteDescriptorSet descriptor_write;
memset(&descriptor_write, 0, sizeof(descriptor_write));
descriptor_write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptor_write.dstSet = set_;
descriptor_write.dstBinding = binding;
descriptor_write.dstArrayElement = arrayElement;
descriptor_write.descriptorCount = count;
descriptor_write.descriptorType = descriptorType;
descriptor_write.pImageInfo = &image_infos[index];
descriptor_write.pBufferInfo = nullptr;
descriptor_write.pTexelBufferView = nullptr;
descriptor_writes.emplace_back(descriptor_write);
}
void OneOffDescriptorSet::UpdateDescriptorSets() {
vk::UpdateDescriptorSets(device_->handle(), descriptor_writes.size(), descriptor_writes.data(), 0, NULL);
}
CreatePipelineHelper::CreatePipelineHelper(VkLayerTest &test) : layer_test_(test) {}
CreatePipelineHelper::~CreatePipelineHelper() {
VkDevice device = layer_test_.device();
vk::DestroyPipelineCache(device, pipeline_cache_, nullptr);
vk::DestroyPipeline(device, pipeline_, nullptr);
}
void CreatePipelineHelper::InitDescriptorSetInfo() {
dsl_bindings_ = {{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL, nullptr}};
}
void CreatePipelineHelper::InitInputAndVertexInfo() {
vi_ci_.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
ia_ci_.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
ia_ci_.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
}
void CreatePipelineHelper::InitMultisampleInfo() {
pipe_ms_state_ci_.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
pipe_ms_state_ci_.pNext = nullptr;
pipe_ms_state_ci_.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
pipe_ms_state_ci_.sampleShadingEnable = VK_FALSE;
pipe_ms_state_ci_.minSampleShading = 1.0;
pipe_ms_state_ci_.pSampleMask = NULL;
}
void CreatePipelineHelper::InitPipelineLayoutInfo() {
pipeline_layout_ci_.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipeline_layout_ci_.setLayoutCount = 1; // Not really changeable because InitState() sets exactly one pSetLayout
pipeline_layout_ci_.pSetLayouts = nullptr; // must bound after it is created
}
void CreatePipelineHelper::InitViewportInfo() {
viewport_ = {0.0f, 0.0f, 64.0f, 64.0f, 0.0f, 1.0f};
scissor_ = {{0, 0}, {64, 64}};
vp_state_ci_.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
vp_state_ci_.pNext = nullptr;
vp_state_ci_.viewportCount = 1;
vp_state_ci_.pViewports = &viewport_; // ignored if dynamic
vp_state_ci_.scissorCount = 1;
vp_state_ci_.pScissors = &scissor_; // ignored if dynamic
}
void CreatePipelineHelper::InitDynamicStateInfo() {
// Use a "validity" check on the {} initialized structure to detect initialization
// during late bind
}
void CreatePipelineHelper::InitShaderInfo() {
vs_.reset(new VkShaderObj(layer_test_.DeviceObj(), bindStateVertShaderText, VK_SHADER_STAGE_VERTEX_BIT, &layer_test_));
fs_.reset(new VkShaderObj(layer_test_.DeviceObj(), bindStateFragShaderText, VK_SHADER_STAGE_FRAGMENT_BIT, &layer_test_));
// We shouldn't need a fragment shader but add it to be able to run on more devices
shader_stages_ = {vs_->GetStageCreateInfo(), fs_->GetStageCreateInfo()};
}
void CreatePipelineHelper::InitRasterizationInfo() {
rs_state_ci_.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rs_state_ci_.pNext = &line_state_ci_;
rs_state_ci_.flags = 0;
rs_state_ci_.depthClampEnable = VK_FALSE;
rs_state_ci_.rasterizerDiscardEnable = VK_FALSE;
rs_state_ci_.polygonMode = VK_POLYGON_MODE_FILL;
rs_state_ci_.cullMode = VK_CULL_MODE_BACK_BIT;
rs_state_ci_.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rs_state_ci_.depthBiasEnable = VK_FALSE;
rs_state_ci_.lineWidth = 1.0F;
}
void CreatePipelineHelper::InitLineRasterizationInfo() {
line_state_ci_.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_LINE_STATE_CREATE_INFO_EXT;
line_state_ci_.pNext = nullptr;
line_state_ci_.lineRasterizationMode = VK_LINE_RASTERIZATION_MODE_DEFAULT_EXT;
line_state_ci_.stippledLineEnable = VK_FALSE;
line_state_ci_.lineStippleFactor = 0;
line_state_ci_.lineStipplePattern = 0;
}
void CreatePipelineHelper::InitBlendStateInfo() {
cb_ci_.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
cb_ci_.logicOpEnable = VK_FALSE;
cb_ci_.logicOp = VK_LOGIC_OP_COPY; // ignored if enable is VK_FALSE above
cb_ci_.attachmentCount = layer_test_.RenderPassInfo().subpassCount;
ASSERT_TRUE(IsValidVkStruct(layer_test_.RenderPassInfo()));
cb_ci_.pAttachments = &cb_attachments_;
for (int i = 0; i < 4; i++) {
cb_ci_.blendConstants[0] = 1.0F;
}
}
void CreatePipelineHelper::InitGraphicsPipelineInfo() {
// Color-only rendering in a subpass with no depth/stencil attachment
// Active Pipeline Shader Stages
// Vertex Shader
// Fragment Shader
// Required: Fixed-Function Pipeline Stages
// VkPipelineVertexInputStateCreateInfo
// VkPipelineInputAssemblyStateCreateInfo
// VkPipelineViewportStateCreateInfo
// VkPipelineRasterizationStateCreateInfo
// VkPipelineMultisampleStateCreateInfo
// VkPipelineColorBlendStateCreateInfo
gp_ci_.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
gp_ci_.pNext = nullptr;
gp_ci_.flags = VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT;
gp_ci_.pVertexInputState = &vi_ci_;
gp_ci_.pInputAssemblyState = &ia_ci_;
gp_ci_.pTessellationState = nullptr;
gp_ci_.pViewportState = &vp_state_ci_;
gp_ci_.pRasterizationState = &rs_state_ci_;
gp_ci_.pMultisampleState = &pipe_ms_state_ci_;
gp_ci_.pDepthStencilState = nullptr;
gp_ci_.pColorBlendState = &cb_ci_;
gp_ci_.pDynamicState = nullptr;
gp_ci_.renderPass = layer_test_.renderPass();
}
void CreatePipelineHelper::InitPipelineCacheInfo() {
pc_ci_.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
pc_ci_.pNext = nullptr;
pc_ci_.flags = 0;
pc_ci_.initialDataSize = 0;
pc_ci_.pInitialData = nullptr;
}
void CreatePipelineHelper::InitTesselationState() {
// TBD -- add shaders and create_info
}
void CreatePipelineHelper::InitInfo() {
InitDescriptorSetInfo();
InitInputAndVertexInfo();
InitMultisampleInfo();
InitPipelineLayoutInfo();
InitViewportInfo();
InitDynamicStateInfo();
InitShaderInfo();
InitRasterizationInfo();
InitLineRasterizationInfo();
InitBlendStateInfo();
InitGraphicsPipelineInfo();
InitPipelineCacheInfo();
}
void CreatePipelineHelper::InitState() {
VkResult err;
descriptor_set_.reset(new OneOffDescriptorSet(layer_test_.DeviceObj(), dsl_bindings_));
ASSERT_TRUE(descriptor_set_->Initialized());
const std::vector<VkPushConstantRange> push_ranges(
pipeline_layout_ci_.pPushConstantRanges,
pipeline_layout_ci_.pPushConstantRanges + pipeline_layout_ci_.pushConstantRangeCount);
pipeline_layout_ = VkPipelineLayoutObj(layer_test_.DeviceObj(), {&descriptor_set_->layout_}, push_ranges);
err = vk::CreatePipelineCache(layer_test_.device(), &pc_ci_, NULL, &pipeline_cache_);
ASSERT_VK_SUCCESS(err);
}
void CreatePipelineHelper::LateBindPipelineInfo() {
// By value or dynamically located items must be late bound
gp_ci_.layout = pipeline_layout_.handle();
gp_ci_.stageCount = shader_stages_.size();
gp_ci_.pStages = shader_stages_.data();
if ((gp_ci_.pTessellationState == nullptr) && IsValidVkStruct(tess_ci_)) {
gp_ci_.pTessellationState = &tess_ci_;
}
if ((gp_ci_.pDynamicState == nullptr) && IsValidVkStruct(dyn_state_ci_)) {
gp_ci_.pDynamicState = &dyn_state_ci_;
}
if ((gp_ci_.pDepthStencilState == nullptr) && IsValidVkStruct(ds_ci_)) {
gp_ci_.pDepthStencilState = &ds_ci_;
}
}
VkResult CreatePipelineHelper::CreateGraphicsPipeline(bool implicit_destroy, bool do_late_bind) {
VkResult err;
if (do_late_bind) {
LateBindPipelineInfo();
}
if (implicit_destroy && (pipeline_ != VK_NULL_HANDLE)) {
vk::DestroyPipeline(layer_test_.device(), pipeline_, nullptr);
pipeline_ = VK_NULL_HANDLE;
}
err = vk::CreateGraphicsPipelines(layer_test_.device(), pipeline_cache_, 1, &gp_ci_, NULL, &pipeline_);
return err;
}
CreateComputePipelineHelper::CreateComputePipelineHelper(VkLayerTest &test) : layer_test_(test) {}
CreateComputePipelineHelper::~CreateComputePipelineHelper() {
VkDevice device = layer_test_.device();
vk::DestroyPipelineCache(device, pipeline_cache_, nullptr);
vk::DestroyPipeline(device, pipeline_, nullptr);
}
void CreateComputePipelineHelper::InitDescriptorSetInfo() {
dsl_bindings_ = {{0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_ALL, nullptr}};
}
void CreateComputePipelineHelper::InitPipelineLayoutInfo() {
pipeline_layout_ci_.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipeline_layout_ci_.setLayoutCount = 1; // Not really changeable because InitState() sets exactly one pSetLayout
pipeline_layout_ci_.pSetLayouts = nullptr; // must bound after it is created
}
void CreateComputePipelineHelper::InitShaderInfo() {
cs_.reset(new VkShaderObj(layer_test_.DeviceObj(), bindStateMinimalShaderText, VK_SHADER_STAGE_COMPUTE_BIT, &layer_test_));
// We shouldn't need a fragment shader but add it to be able to run on more devices
}
void CreateComputePipelineHelper::InitComputePipelineInfo() {
cp_ci_.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
cp_ci_.pNext = nullptr;
cp_ci_.flags = 0;
}
void CreateComputePipelineHelper::InitPipelineCacheInfo() {
pc_ci_.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
pc_ci_.pNext = nullptr;
pc_ci_.flags = 0;
pc_ci_.initialDataSize = 0;
pc_ci_.pInitialData = nullptr;
}
void CreateComputePipelineHelper::InitInfo() {
InitDescriptorSetInfo();
InitPipelineLayoutInfo();
InitShaderInfo();
InitComputePipelineInfo();
InitPipelineCacheInfo();
}
void CreateComputePipelineHelper::InitState() {
VkResult err;
descriptor_set_.reset(new OneOffDescriptorSet(layer_test_.DeviceObj(), dsl_bindings_));
ASSERT_TRUE(descriptor_set_->Initialized());
const std::vector<VkPushConstantRange> push_ranges(
pipeline_layout_ci_.pPushConstantRanges,
pipeline_layout_ci_.pPushConstantRanges + pipeline_layout_ci_.pushConstantRangeCount);
pipeline_layout_ = VkPipelineLayoutObj(layer_test_.DeviceObj(), {&descriptor_set_->layout_}, push_ranges);
err = vk::CreatePipelineCache(layer_test_.device(), &pc_ci_, NULL, &pipeline_cache_);
ASSERT_VK_SUCCESS(err);
}
void CreateComputePipelineHelper::LateBindPipelineInfo() {
// By value or dynamically located items must be late bound
cp_ci_.layout = pipeline_layout_.handle();
cp_ci_.stage = cs_.get()->GetStageCreateInfo();
}
VkResult CreateComputePipelineHelper::CreateComputePipeline(bool implicit_destroy, bool do_late_bind) {
VkResult err;
if (do_late_bind) {
LateBindPipelineInfo();
}
if (implicit_destroy && (pipeline_ != VK_NULL_HANDLE)) {
vk::DestroyPipeline(layer_test_.device(), pipeline_, nullptr);
pipeline_ = VK_NULL_HANDLE;
}
err = vk::CreateComputePipelines(layer_test_.device(), pipeline_cache_, 1, &cp_ci_, NULL, &pipeline_);
return err;
}
CreateNVRayTracingPipelineHelper::CreateNVRayTracingPipelineHelper(VkLayerTest &test) : layer_test_(test) {}
CreateNVRayTracingPipelineHelper::~CreateNVRayTracingPipelineHelper() {
VkDevice device = layer_test_.device();
vk::DestroyPipelineCache(device, pipeline_cache_, nullptr);
vk::DestroyPipeline(device, pipeline_, nullptr);
}
bool CreateNVRayTracingPipelineHelper::InitInstanceExtensions(VkLayerTest &test,
std::vector<const char *> &instance_extension_names) {
if (test.InstanceExtensionSupported(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) {
instance_extension_names.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
} else {
printf("%s Did not find required instance extension %s; skipped.\n", kSkipPrefix,
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
return false;
}
return true;
}
bool CreateNVRayTracingPipelineHelper::InitDeviceExtensions(VkLayerTest &test, std::vector<const char *> &device_extension_names) {
std::array<const char *, 2> required_device_extensions = {
{VK_NV_RAY_TRACING_EXTENSION_NAME, VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME}};
for (auto device_extension : required_device_extensions) {
if (test.DeviceExtensionSupported(test.gpu(), nullptr, device_extension)) {
device_extension_names.push_back(device_extension);
} else {
printf("%s %s Extension not supported, skipping tests\n", kSkipPrefix, device_extension);
return false;
}
}
return true;
}
void CreateNVRayTracingPipelineHelper::InitShaderGroups() {
{
VkRayTracingShaderGroupCreateInfoNV group = {};
group.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_NV;
group.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV;
group.generalShader = 0;
group.closestHitShader = VK_SHADER_UNUSED_NV;
group.anyHitShader = VK_SHADER_UNUSED_NV;
group.intersectionShader = VK_SHADER_UNUSED_NV;
groups_.push_back(group);
}
{
VkRayTracingShaderGroupCreateInfoNV group = {};
group.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_NV;
group.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV;
group.generalShader = VK_SHADER_UNUSED_NV;
group.closestHitShader = 1;
group.anyHitShader = VK_SHADER_UNUSED_NV;
group.intersectionShader = VK_SHADER_UNUSED_NV;
groups_.push_back(group);
}
{
VkRayTracingShaderGroupCreateInfoNV group = {};
group.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_NV;
group.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV;
group.generalShader = 2;
group.closestHitShader = VK_SHADER_UNUSED_NV;
group.anyHitShader = VK_SHADER_UNUSED_NV;
group.intersectionShader = VK_SHADER_UNUSED_NV;
groups_.push_back(group);
}
}
void CreateNVRayTracingPipelineHelper::InitShaderGroupsKHR() {
{
VkRayTracingShaderGroupCreateInfoKHR group = {};
group.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR;
group.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR;
group.generalShader = 0;
group.closestHitShader = VK_SHADER_UNUSED_KHR;
group.anyHitShader = VK_SHADER_UNUSED_KHR;
group.intersectionShader = VK_SHADER_UNUSED_KHR;
groups_KHR_.push_back(group);
}
{
VkRayTracingShaderGroupCreateInfoKHR group = {};
group.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR;
group.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_KHR;
group.generalShader = VK_SHADER_UNUSED_KHR;
group.closestHitShader = 1;
group.anyHitShader = VK_SHADER_UNUSED_KHR;
group.intersectionShader = VK_SHADER_UNUSED_KHR;
groups_KHR_.push_back(group);
}
{
VkRayTracingShaderGroupCreateInfoKHR group = {};
group.sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_KHR;
group.type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_KHR;
group.generalShader = 2;
group.closestHitShader = VK_SHADER_UNUSED_KHR;
group.anyHitShader = VK_SHADER_UNUSED_KHR;
group.intersectionShader = VK_SHADER_UNUSED_KHR;
groups_KHR_.push_back(group);
}
}
void CreateNVRayTracingPipelineHelper::InitDescriptorSetInfo() {
dsl_bindings_ = {
{0, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_RAYGEN_BIT_NV, nullptr},
{1, VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV, 1, VK_SHADER_STAGE_RAYGEN_BIT_NV, nullptr},
};
}
void CreateNVRayTracingPipelineHelper::InitPipelineLayoutInfo() {
pipeline_layout_ci_.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipeline_layout_ci_.setLayoutCount = 1; // Not really changeable because InitState() sets exactly one pSetLayout
pipeline_layout_ci_.pSetLayouts = nullptr; // must bound after it is created
}
void CreateNVRayTracingPipelineHelper::InitShaderInfo() { // DONE
static const char rayGenShaderText[] = R"glsl(
#version 460 core
#extension GL_NV_ray_tracing : require
layout(set = 0, binding = 0, rgba8) uniform image2D image;
layout(set = 0, binding = 1) uniform accelerationStructureNV as;
layout(location = 0) rayPayloadNV float payload;
void main()
{
vec4 col = vec4(0, 0, 0, 1);
vec3 origin = vec3(float(gl_LaunchIDNV.x)/float(gl_LaunchSizeNV.x), float(gl_LaunchIDNV.y)/float(gl_LaunchSizeNV.y), 1.0);
vec3 dir = vec3(0.0, 0.0, -1.0);
payload = 0.5;
traceNV(as, gl_RayFlagsCullBackFacingTrianglesNV, 0xff, 0, 1, 0, origin, 0.0, dir, 1000.0, 0);
col.y = payload;
imageStore(image, ivec2(gl_LaunchIDNV.xy), col);
}
)glsl";
static char const closestHitShaderText[] = R"glsl(
#version 460 core
#extension GL_NV_ray_tracing : require
layout(location = 0) rayPayloadInNV float hitValue;
void main() {
hitValue = 1.0;
}
)glsl";
static char const missShaderText[] = R"glsl(
#version 460 core
#extension GL_NV_ray_tracing : require
layout(location = 0) rayPayloadInNV float hitValue;
void main() {
hitValue = 0.0;
}
)glsl";
rgs_.reset(new VkShaderObj(layer_test_.DeviceObj(), rayGenShaderText, VK_SHADER_STAGE_RAYGEN_BIT_NV, &layer_test_));
chs_.reset(new VkShaderObj(layer_test_.DeviceObj(), closestHitShaderText, VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV, &layer_test_));
mis_.reset(new VkShaderObj(layer_test_.DeviceObj(), missShaderText, VK_SHADER_STAGE_MISS_BIT_NV, &layer_test_));
shader_stages_ = {rgs_->GetStageCreateInfo(), chs_->GetStageCreateInfo(), mis_->GetStageCreateInfo()};
}
void CreateNVRayTracingPipelineHelper::InitNVRayTracingPipelineInfo() {
rp_ci_.sType = VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV;
rp_ci_.maxRecursionDepth = 0;
rp_ci_.stageCount = shader_stages_.size();
rp_ci_.pStages = shader_stages_.data();
rp_ci_.groupCount = groups_.size();
rp_ci_.pGroups = groups_.data();
}
void CreateNVRayTracingPipelineHelper::InitKHRRayTracingPipelineInfo() {
rp_ci_KHR_.sType = VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV;
rp_ci_KHR_.maxPipelineRayRecursionDepth = 0;
rp_ci_KHR_.stageCount = shader_stages_.size();
rp_ci_KHR_.pStages = shader_stages_.data();
rp_ci_KHR_.groupCount = groups_KHR_.size();
rp_ci_KHR_.pGroups = groups_KHR_.data();
}
void CreateNVRayTracingPipelineHelper::InitPipelineCacheInfo() {
pc_ci_.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
pc_ci_.pNext = nullptr;
pc_ci_.flags = 0;
pc_ci_.initialDataSize = 0;
pc_ci_.pInitialData = nullptr;
}
void CreateNVRayTracingPipelineHelper::InitInfo(bool isKHR) {
isKHR ? InitShaderGroupsKHR() : InitShaderGroups();
InitDescriptorSetInfo();
InitPipelineLayoutInfo();
InitShaderInfo();
isKHR ? InitKHRRayTracingPipelineInfo() : InitNVRayTracingPipelineInfo();
InitPipelineCacheInfo();
}
void CreateNVRayTracingPipelineHelper::InitState() {
VkResult err;
descriptor_set_.reset(new OneOffDescriptorSet(layer_test_.DeviceObj(), dsl_bindings_));
ASSERT_TRUE(descriptor_set_->Initialized());
pipeline_layout_ = VkPipelineLayoutObj(layer_test_.DeviceObj(), {&descriptor_set_->layout_});
err = vk::CreatePipelineCache(layer_test_.device(), &pc_ci_, NULL, &pipeline_cache_);
ASSERT_VK_SUCCESS(err);
}
void CreateNVRayTracingPipelineHelper::LateBindPipelineInfo(bool isKHR) {
// By value or dynamically located items must be late bound
if (isKHR) {
rp_ci_KHR_.layout = pipeline_layout_.handle();
rp_ci_KHR_.stageCount = shader_stages_.size();
rp_ci_KHR_.pStages = shader_stages_.data();
} else {
rp_ci_.layout = pipeline_layout_.handle();
rp_ci_.stageCount = shader_stages_.size();
rp_ci_.pStages = shader_stages_.data();
}
}
VkResult CreateNVRayTracingPipelineHelper::CreateNVRayTracingPipeline(bool implicit_destroy, bool do_late_bind) {
VkResult err;
if (do_late_bind) {
LateBindPipelineInfo();
}
if (implicit_destroy && (pipeline_ != VK_NULL_HANDLE)) {
vk::DestroyPipeline(layer_test_.device(), pipeline_, nullptr);
pipeline_ = VK_NULL_HANDLE;
}
PFN_vkCreateRayTracingPipelinesNV vkCreateRayTracingPipelinesNV =
(PFN_vkCreateRayTracingPipelinesNV)vk::GetInstanceProcAddr(layer_test_.instance(), "vkCreateRayTracingPipelinesNV");
err = vkCreateRayTracingPipelinesNV(layer_test_.device(), pipeline_cache_, 1, &rp_ci_, nullptr, &pipeline_);
return err;
}
VkResult CreateNVRayTracingPipelineHelper::CreateKHRRayTracingPipeline(bool implicit_destroy, bool do_late_bind) {
VkResult err;
if (do_late_bind) {
LateBindPipelineInfo(true /*isKHR*/);
}
if (implicit_destroy && (pipeline_ != VK_NULL_HANDLE)) {
vk::DestroyPipeline(layer_test_.device(), pipeline_, nullptr);
pipeline_ = VK_NULL_HANDLE;
}
PFN_vkCreateRayTracingPipelinesKHR vkCreateRayTracingPipelinesKHR =
(PFN_vkCreateRayTracingPipelinesKHR)vk::GetInstanceProcAddr(layer_test_.instance(), "vkCreateRayTracingPipelinesKHR");
err = vkCreateRayTracingPipelinesKHR(layer_test_.device(), 0, pipeline_cache_, 1, &rp_ci_KHR_, nullptr, &pipeline_);
return err;
}
namespace chain_util {
const void *ExtensionChain::Head() const { return head_; }
} // namespace chain_util
BarrierQueueFamilyBase::QueueFamilyObjs::~QueueFamilyObjs() {
delete command_buffer2;
delete command_buffer;
delete command_pool;
delete queue;
}
void BarrierQueueFamilyBase::QueueFamilyObjs::Init(VkDeviceObj *device, uint32_t qf_index, VkQueue qf_queue,
VkCommandPoolCreateFlags cp_flags) {
index = qf_index;
queue = new VkQueueObj(qf_queue, qf_index);
command_pool = new VkCommandPoolObj(device, qf_index, cp_flags);
command_buffer = new VkCommandBufferObj(device, command_pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, queue);
command_buffer2 = new VkCommandBufferObj(device, command_pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, queue);
};
BarrierQueueFamilyBase::Context::Context(VkLayerTest *test, const std::vector<uint32_t> &queue_family_indices) : layer_test(test) {
if (0 == queue_family_indices.size()) {
return; // This is invalid
}
VkDeviceObj *device_obj = layer_test->DeviceObj();
queue_families.reserve(queue_family_indices.size());
default_index = queue_family_indices[0];
for (auto qfi : queue_family_indices) {
VkQueue queue = device_obj->queue_family_queues(qfi)[0]->handle();
queue_families.emplace(std::make_pair(qfi, QueueFamilyObjs()));
queue_families[qfi].Init(device_obj, qfi, queue, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT);
}
Reset();
}
void BarrierQueueFamilyBase::Context::Reset() {
layer_test->DeviceObj()->wait();
for (auto &qf : queue_families) {
vk::ResetCommandPool(layer_test->device(), qf.second.command_pool->handle(), 0);
}
}
void BarrierQueueFamilyTestHelper::Init(std::vector<uint32_t> *families, bool image_memory, bool buffer_memory) {
VkDeviceObj *device_obj = context_->layer_test->DeviceObj();
image_.Init(32, 32, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_TILING_OPTIMAL, 0, families,
image_memory);
ASSERT_TRUE(image_.initialized());
image_barrier_ = image_.image_memory_barrier(VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_TRANSFER_READ_BIT, image_.Layout(),
image_.Layout(), image_.subresource_range(VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1));
VkMemoryPropertyFlags mem_prop = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
buffer_.init_as_src_and_dst(*device_obj, 256, mem_prop, families, buffer_memory);
ASSERT_TRUE(buffer_.initialized());
buffer_barrier_ = buffer_.buffer_memory_barrier(VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_TRANSFER_READ_BIT, 0, VK_WHOLE_SIZE);
}
void Barrier2QueueFamilyTestHelper::Init(std::vector<uint32_t> *families, bool image_memory, bool buffer_memory) {
VkDeviceObj *device_obj = context_->layer_test->DeviceObj();
image_.Init(32, 32, 1, VK_FORMAT_B8G8R8A8_UNORM, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_TILING_OPTIMAL, 0, families,
image_memory);
ASSERT_TRUE(image_.initialized());
image_barrier_ = image_.image_memory_barrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_TRANSFER_READ_BIT, image_.Layout(),
image_.Layout(), image_.subresource_range(VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1));
VkMemoryPropertyFlags mem_prop = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
buffer_.init_as_src_and_dst(*device_obj, 256, mem_prop, families, buffer_memory);
ASSERT_TRUE(buffer_.initialized());
buffer_barrier_ = buffer_.buffer_memory_barrier(VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_TRANSFER_READ_BIT, 0, VK_WHOLE_SIZE);
}
BarrierQueueFamilyBase::QueueFamilyObjs *BarrierQueueFamilyBase::GetQueueFamilyInfo(Context *context, uint32_t qfi) {
QueueFamilyObjs *qf;
auto qf_it = context->queue_families.find(qfi);
if (qf_it != context->queue_families.end()) {
qf = &(qf_it->second);
} else {
qf = &(context->queue_families[context->default_index]);
}
return qf;
}
void BarrierQueueFamilyTestHelper::operator()(std::string img_err, std::string buf_err, uint32_t src, uint32_t dst, bool positive,
uint32_t queue_family_index, Modifier mod) {
auto &monitor = context_->layer_test->Monitor();
const bool has_img_err = img_err.size() > 0;
const bool has_buf_err = buf_err.size() > 0;
if (has_img_err) monitor.SetDesiredFailureMsg(kErrorBit | kWarningBit, img_err);
if (has_buf_err) monitor.SetDesiredFailureMsg(kErrorBit | kWarningBit, buf_err);
if (!(has_img_err || has_buf_err)) {
monitor.ExpectSuccess();
positive = true;
}
image_barrier_.srcQueueFamilyIndex = src;
image_barrier_.dstQueueFamilyIndex = dst;
buffer_barrier_.srcQueueFamilyIndex = src;
buffer_barrier_.dstQueueFamilyIndex = dst;
QueueFamilyObjs *qf = GetQueueFamilyInfo(context_, queue_family_index);
VkCommandBufferObj *command_buffer = qf->command_buffer;
for (int cb_repeat = 0; cb_repeat < (mod == Modifier::DOUBLE_COMMAND_BUFFER ? 2 : 1); cb_repeat++) {
command_buffer->begin();
for (int repeat = 0; repeat < (mod == Modifier::DOUBLE_RECORD ? 2 : 1); repeat++) {
vk::CmdPipelineBarrier(command_buffer->handle(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 1, &buffer_barrier_, 1, &image_barrier_);
}
command_buffer->end();
command_buffer = qf->command_buffer2; // Second pass (if any) goes to the secondary command_buffer.
}
if (queue_family_index != kInvalidQueueFamily) {
if (mod == Modifier::DOUBLE_COMMAND_BUFFER) {
// the Fence resolves to VK_NULL_HANLE... i.e. no fence
qf->queue->submit({{qf->command_buffer, qf->command_buffer2}}, vk_testing::Fence(), positive);
} else {
qf->command_buffer->QueueCommandBuffer(positive); // Check for success on positive tests only
}
}
if (positive) {
monitor.VerifyNotFound();
} else {
monitor.VerifyFound();
}
context_->Reset();
};
void Barrier2QueueFamilyTestHelper::operator()(std::string img_err, std::string buf_err, uint32_t src, uint32_t dst, bool positive,
uint32_t queue_family_index, Modifier mod) {
auto &monitor = context_->layer_test->Monitor();
if (img_err.length()) monitor.SetDesiredFailureMsg(kErrorBit | kWarningBit, img_err);
if (buf_err.length()) monitor.SetDesiredFailureMsg(kErrorBit | kWarningBit, buf_err);
image_barrier_.srcQueueFamilyIndex = src;
image_barrier_.dstQueueFamilyIndex = dst;
buffer_barrier_.srcQueueFamilyIndex = src;
buffer_barrier_.dstQueueFamilyIndex = dst;
auto dep_info = lvl_init_struct<VkDependencyInfoKHR>();
dep_info.bufferMemoryBarrierCount = 1;
dep_info.pBufferMemoryBarriers = &buffer_barrier_;
dep_info.imageMemoryBarrierCount = 1;
dep_info.pImageMemoryBarriers = &image_barrier_;
QueueFamilyObjs *qf = GetQueueFamilyInfo(context_, queue_family_index);
VkCommandBufferObj *command_buffer = qf->command_buffer;
for (int cb_repeat = 0; cb_repeat < (mod == Modifier::DOUBLE_COMMAND_BUFFER ? 2 : 1); cb_repeat++) {
command_buffer->begin();
for (int repeat = 0; repeat < (mod == Modifier::DOUBLE_RECORD ? 2 : 1); repeat++) {
command_buffer->PipelineBarrier2KHR(&dep_info);
}
command_buffer->end();
command_buffer = qf->command_buffer2; // Second pass (if any) goes to the secondary command_buffer.
}
if (queue_family_index != kInvalidQueueFamily) {
if (mod == Modifier::DOUBLE_COMMAND_BUFFER) {
// the Fence resolves to VK_NULL_HANLE... i.e. no fence
qf->queue->submit({{qf->command_buffer, qf->command_buffer2}}, vk_testing::Fence(), positive);
} else {
qf->command_buffer->QueueCommandBuffer(positive); // Check for success on positive tests only
}
}
if (positive) {
monitor.VerifyNotFound();
} else {
monitor.VerifyFound();
}
context_->Reset();
};
bool InitFrameworkForRayTracingTest(VkRenderFramework *renderFramework, bool isKHR,
std::vector<const char *> &instance_extension_names,
std::vector<const char *> &device_extension_names, void *user_data, bool need_gpu_validation,
bool need_push_descriptors, bool deferred_state_init) {
const std::array<const char *, 1> required_instance_extensions = {{VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME}};
for (const char *required_instance_extension : required_instance_extensions) {
if (renderFramework->InstanceExtensionSupported(required_instance_extension)) {
instance_extension_names.push_back(required_instance_extension);
} else {
printf("%s %s instance extension not supported, skipping test\n", kSkipPrefix, required_instance_extension);
return false;
}
}
VkValidationFeatureEnableEXT enables[] = {VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT};
VkValidationFeatureDisableEXT disables[] = {
VK_VALIDATION_FEATURE_DISABLE_THREAD_SAFETY_EXT, VK_VALIDATION_FEATURE_DISABLE_API_PARAMETERS_EXT,
VK_VALIDATION_FEATURE_DISABLE_OBJECT_LIFETIMES_EXT, VK_VALIDATION_FEATURE_DISABLE_CORE_CHECKS_EXT};
VkValidationFeaturesEXT features = {};
features.sType = VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT;
features.enabledValidationFeatureCount = 1;
features.pEnabledValidationFeatures = enables;
features.disabledValidationFeatureCount = 4;
features.pDisabledValidationFeatures = disables;
VkValidationFeaturesEXT *enabled_features = need_gpu_validation ? &features : nullptr;
renderFramework->InitFramework(user_data, enabled_features);
if (renderFramework->IsPlatform(kMockICD) || renderFramework->DeviceSimulation()) {
printf("%s Test not supported by MockICD, skipping tests\n", kSkipPrefix);
return false;
}
std::vector<const char *> required_device_extensions;
required_device_extensions.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
if (isKHR) {
required_device_extensions.push_back(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME);
required_device_extensions.push_back(VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME);
required_device_extensions.push_back(VK_KHR_RAY_QUERY_EXTENSION_NAME);
required_device_extensions.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
required_device_extensions.push_back(VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME);
required_device_extensions.push_back(VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME);
required_device_extensions.push_back(VK_KHR_SPIRV_1_4_EXTENSION_NAME);
required_device_extensions.push_back(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME);
required_device_extensions.push_back(VK_KHR_PIPELINE_LIBRARY_EXTENSION_NAME);
} else {
required_device_extensions.push_back(VK_NV_RAY_TRACING_EXTENSION_NAME);
}
if (need_push_descriptors) {
required_device_extensions.push_back(VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME);
}
for (const char *required_device_extension : required_device_extensions) {
if (renderFramework->DeviceExtensionSupported(renderFramework->gpu(), nullptr, required_device_extension)) {
device_extension_names.push_back(required_device_extension);
} else {
printf("%s %s device extension not supported, skipping test\n", kSkipPrefix, required_device_extension);
return false;
}
}
if (!deferred_state_init) renderFramework->InitState();
return true;
}
void GetSimpleGeometryForAccelerationStructureTests(const VkDeviceObj &device, VkBufferObj *vbo, VkBufferObj *ibo,
VkGeometryNV *geometry) {
vbo->init(device, 1024, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
VK_BUFFER_USAGE_RAY_TRACING_BIT_NV | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR);
ibo->init(device, 1024, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
VK_BUFFER_USAGE_RAY_TRACING_BIT_NV | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR);
const std::vector<float> vertices = {1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f};
const std::vector<uint32_t> indicies = {0, 1, 2};
uint8_t *mapped_vbo_buffer_data = (uint8_t *)vbo->memory().map();
std::memcpy(mapped_vbo_buffer_data, (uint8_t *)vertices.data(), sizeof(float) * vertices.size());
vbo->memory().unmap();
uint8_t *mapped_ibo_buffer_data = (uint8_t *)ibo->memory().map();
std::memcpy(mapped_ibo_buffer_data, (uint8_t *)indicies.data(), sizeof(uint32_t) * indicies.size());
ibo->memory().unmap();
*geometry = {};
geometry->sType = VK_STRUCTURE_TYPE_GEOMETRY_NV;
geometry->geometryType = VK_GEOMETRY_TYPE_TRIANGLES_NV;
geometry->geometry.triangles.sType = VK_STRUCTURE_TYPE_GEOMETRY_TRIANGLES_NV;
geometry->geometry.triangles.vertexData = vbo->handle();
geometry->geometry.triangles.vertexOffset = 0;
geometry->geometry.triangles.vertexCount = 3;
geometry->geometry.triangles.vertexStride = 12;
geometry->geometry.triangles.vertexFormat = VK_FORMAT_R32G32B32_SFLOAT;
geometry->geometry.triangles.indexData = ibo->handle();
geometry->geometry.triangles.indexOffset = 0;
geometry->geometry.triangles.indexCount = 3;
geometry->geometry.triangles.indexType = VK_INDEX_TYPE_UINT32;
geometry->geometry.triangles.transformData = VK_NULL_HANDLE;
geometry->geometry.triangles.transformOffset = 0;
geometry->geometry.aabbs = {};
geometry->geometry.aabbs.sType = VK_STRUCTURE_TYPE_GEOMETRY_AABB_NV;
}
void VkLayerTest::OOBRayTracingShadersTestBody(bool gpu_assisted) {
std::array<const char *, 1> required_instance_extensions = {{VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME}};
for (auto instance_extension : required_instance_extensions) {
if (InstanceExtensionSupported(instance_extension)) {
m_instance_extension_names.push_back(instance_extension);
} else {
printf("%s Did not find required instance extension %s; skipped.\n", kSkipPrefix, instance_extension);
return;
}
}
VkValidationFeatureEnableEXT validation_feature_enables[] = {VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT};
VkValidationFeatureDisableEXT validation_feature_disables[] = {
VK_VALIDATION_FEATURE_DISABLE_THREAD_SAFETY_EXT, VK_VALIDATION_FEATURE_DISABLE_API_PARAMETERS_EXT,
VK_VALIDATION_FEATURE_DISABLE_OBJECT_LIFETIMES_EXT, VK_VALIDATION_FEATURE_DISABLE_CORE_CHECKS_EXT};
VkValidationFeaturesEXT validation_features = {};
validation_features.sType = VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT;
validation_features.enabledValidationFeatureCount = 1;
validation_features.pEnabledValidationFeatures = validation_feature_enables;
validation_features.disabledValidationFeatureCount = 4;
validation_features.pDisabledValidationFeatures = validation_feature_disables;
bool descriptor_indexing = CheckDescriptorIndexingSupportAndInitFramework(
this, m_instance_extension_names, m_device_extension_names, gpu_assisted ? &validation_features : nullptr, m_errorMonitor);
if (IsPlatform(kMockICD) || DeviceSimulation()) {
printf("%s Test not supported by MockICD, skipping tests\n", kSkipPrefix);
return;
}
std::array<const char *, 2> required_device_extensions = {
{VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME, VK_NV_RAY_TRACING_EXTENSION_NAME}};
for (auto device_extension : required_device_extensions) {
if (DeviceExtensionSupported(gpu(), nullptr, device_extension)) {
m_device_extension_names.push_back(device_extension);
} else {
printf("%s %s Extension not supported, skipping tests\n", kSkipPrefix, device_extension);
return;
}
}
VkPhysicalDeviceFeatures2KHR features2 = {};
auto indexing_features = LvlInitStruct<VkPhysicalDeviceDescriptorIndexingFeaturesEXT>();
if (descriptor_indexing) {
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR =
(PFN_vkGetPhysicalDeviceFeatures2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceFeatures2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceFeatures2KHR != nullptr);
features2 = LvlInitStruct<VkPhysicalDeviceFeatures2KHR>(&indexing_features);
vkGetPhysicalDeviceFeatures2KHR(gpu(), &features2);
if (!indexing_features.runtimeDescriptorArray || !indexing_features.descriptorBindingPartiallyBound ||
!indexing_features.descriptorBindingSampledImageUpdateAfterBind ||
!indexing_features.descriptorBindingVariableDescriptorCount) {
printf("Not all descriptor indexing features supported, skipping descriptor indexing tests\n");
descriptor_indexing = false;
}
}
VkCommandPoolCreateFlags pool_flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
ASSERT_NO_FATAL_FAILURE(InitState(nullptr, &features2, pool_flags));
PFN_vkGetPhysicalDeviceProperties2KHR vkGetPhysicalDeviceProperties2KHR =
(PFN_vkGetPhysicalDeviceProperties2KHR)vk::GetInstanceProcAddr(instance(), "vkGetPhysicalDeviceProperties2KHR");
ASSERT_TRUE(vkGetPhysicalDeviceProperties2KHR != nullptr);
auto ray_tracing_properties = LvlInitStruct<VkPhysicalDeviceRayTracingPropertiesNV>();
auto properties2 = LvlInitStruct<VkPhysicalDeviceProperties2KHR>(&ray_tracing_properties);
vkGetPhysicalDeviceProperties2KHR(gpu(), &properties2);
if (ray_tracing_properties.maxTriangleCount == 0) {
printf("%s Did not find required ray tracing properties; skipped.\n", kSkipPrefix);
return;
}
VkQueue ray_tracing_queue = m_device->m_queue;
uint32_t ray_tracing_queue_family_index = 0;
// If supported, run on the compute only queue.
uint32_t compute_only_queue_family_index = m_device->QueueFamilyMatching(VK_QUEUE_COMPUTE_BIT, VK_QUEUE_GRAPHICS_BIT);
if (compute_only_queue_family_index != UINT32_MAX) {
const auto &compute_only_queues = m_device->queue_family_queues(compute_only_queue_family_index);
if (!compute_only_queues.empty()) {
ray_tracing_queue = compute_only_queues[0]->handle();
ray_tracing_queue_family_index = compute_only_queue_family_index;
}
}
VkCommandPoolObj ray_tracing_command_pool(m_device, ray_tracing_queue_family_index,
VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT);
VkCommandBufferObj ray_tracing_command_buffer(m_device, &ray_tracing_command_pool);
struct AABB {
float min_x;
float min_y;
float min_z;
float max_x;
float max_y;
float max_z;
};
const std::vector<AABB> aabbs = {{-1.0f, -1.0f, -1.0f, +1.0f, +1.0f, +1.0f}};
struct VkGeometryInstanceNV {
float transform[12];
uint32_t instanceCustomIndex : 24;
uint32_t mask : 8;
uint32_t instanceOffset : 24;
uint32_t flags : 8;
uint64_t accelerationStructureHandle;
};
VkDeviceSize aabb_buffer_size = sizeof(AABB) * aabbs.size();
VkBufferObj aabb_buffer;
aabb_buffer.init(*m_device, aabb_buffer_size, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
VK_BUFFER_USAGE_RAY_TRACING_BIT_NV, {ray_tracing_queue_family_index});
uint8_t *mapped_aabb_buffer_data = (uint8_t *)aabb_buffer.memory().map();
std::memcpy(mapped_aabb_buffer_data, (uint8_t *)aabbs.data(), static_cast<std::size_t>(aabb_buffer_size));
aabb_buffer.memory().unmap();
VkGeometryNV geometry = {};
geometry.sType = VK_STRUCTURE_TYPE_GEOMETRY_NV;
geometry.geometryType = VK_GEOMETRY_TYPE_AABBS_NV;
geometry.geometry.triangles = {};
geometry.geometry.triangles.sType = VK_STRUCTURE_TYPE_GEOMETRY_TRIANGLES_NV;
geometry.geometry.aabbs = {};
geometry.geometry.aabbs.sType = VK_STRUCTURE_TYPE_GEOMETRY_AABB_NV;
geometry.geometry.aabbs.aabbData = aabb_buffer.handle();
geometry.geometry.aabbs.numAABBs = static_cast<uint32_t>(aabbs.size());
geometry.geometry.aabbs.offset = 0;
geometry.geometry.aabbs.stride = static_cast<VkDeviceSize>(sizeof(AABB));
geometry.flags = 0;
VkAccelerationStructureInfoNV bot_level_as_info = {};
bot_level_as_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_INFO_NV;
bot_level_as_info.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV;
bot_level_as_info.instanceCount = 0;
bot_level_as_info.geometryCount = 1;
bot_level_as_info.pGeometries = &geometry;
VkAccelerationStructureCreateInfoNV bot_level_as_create_info = {};
bot_level_as_create_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_NV;
bot_level_as_create_info.info = bot_level_as_info;
VkAccelerationStructureObj bot_level_as(*m_device, bot_level_as_create_info);
const std::vector<VkGeometryInstanceNV> instances = {
VkGeometryInstanceNV{
{
// clang-format off
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
// clang-format on
},
0,
0xFF,
0,
VK_GEOMETRY_INSTANCE_TRIANGLE_CULL_DISABLE_BIT_NV,
bot_level_as.opaque_handle(),
},
};
VkDeviceSize instance_buffer_size = sizeof(VkGeometryInstanceNV) * instances.size();
VkBufferObj instance_buffer;
instance_buffer.init(*m_device, instance_buffer_size,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
VK_BUFFER_USAGE_RAY_TRACING_BIT_NV, {ray_tracing_queue_family_index});
uint8_t *mapped_instance_buffer_data = (uint8_t *)instance_buffer.memory().map();
std::memcpy(mapped_instance_buffer_data, (uint8_t *)instances.data(), static_cast<std::size_t>(instance_buffer_size));
instance_buffer.memory().unmap();
VkAccelerationStructureInfoNV top_level_as_info = {};
top_level_as_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_INFO_NV;
top_level_as_info.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_NV;
top_level_as_info.instanceCount = 1;
top_level_as_info.geometryCount = 0;
VkAccelerationStructureCreateInfoNV top_level_as_create_info = {};
top_level_as_create_info.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_NV;
top_level_as_create_info.info = top_level_as_info;
VkAccelerationStructureObj top_level_as(*m_device, top_level_as_create_info);
VkDeviceSize scratch_buffer_size = std::max(bot_level_as.build_scratch_memory_requirements().memoryRequirements.size,
top_level_as.build_scratch_memory_requirements().memoryRequirements.size);
VkBufferObj scratch_buffer;
scratch_buffer.init(*m_device, scratch_buffer_size, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_BUFFER_USAGE_RAY_TRACING_BIT_NV);
ray_tracing_command_buffer.begin();
// Build bot level acceleration structure
ray_tracing_command_buffer.BuildAccelerationStructure(&bot_level_as, scratch_buffer.handle());
// Barrier to prevent using scratch buffer for top level build before bottom level build finishes
VkMemoryBarrier memory_barrier = {};
memory_barrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
memory_barrier.srcAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV | VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV;
memory_barrier.dstAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV | VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV;
ray_tracing_command_buffer.PipelineBarrier(VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV,
VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV, 0, 1, &memory_barrier, 0,
nullptr, 0, nullptr);
// Build top level acceleration structure
ray_tracing_command_buffer.BuildAccelerationStructure(&top_level_as, scratch_buffer.handle(), instance_buffer.handle());
ray_tracing_command_buffer.end();
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &ray_tracing_command_buffer.handle();
vk::QueueSubmit(ray_tracing_queue, 1, &submit_info, VK_NULL_HANDLE);
vk::QueueWaitIdle(ray_tracing_queue);
m_errorMonitor->VerifyNotFound();
VkTextureObj texture(m_device, nullptr);
VkSamplerObj sampler(m_device);
VkDeviceSize storage_buffer_size = 1024;
VkBufferObj storage_buffer;
storage_buffer.init(*m_device, storage_buffer_size, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, {ray_tracing_queue_family_index});
VkDeviceSize shader_binding_table_buffer_size = ray_tracing_properties.shaderGroupBaseAlignment * 4ull;
VkBufferObj shader_binding_table_buffer;
shader_binding_table_buffer.init(*m_device, shader_binding_table_buffer_size,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
VK_BUFFER_USAGE_RAY_TRACING_BIT_NV, {ray_tracing_queue_family_index});
// Setup descriptors!
const VkShaderStageFlags kAllRayTracingStages = VK_SHADER_STAGE_RAYGEN_BIT_NV | VK_SHADER_STAGE_ANY_HIT_BIT_NV |
VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV | VK_SHADER_STAGE_MISS_BIT_NV |
VK_SHADER_STAGE_INTERSECTION_BIT_NV | VK_SHADER_STAGE_CALLABLE_BIT_NV;
void *layout_pnext = nullptr;
void *allocate_pnext = nullptr;
VkDescriptorPoolCreateFlags pool_create_flags = 0;
VkDescriptorSetLayoutCreateFlags layout_create_flags = 0;
VkDescriptorBindingFlagsEXT ds_binding_flags[3] = {};
VkDescriptorSetLayoutBindingFlagsCreateInfoEXT layout_createinfo_binding_flags[1] = {};
if (descriptor_indexing) {
ds_binding_flags[0] = 0;
ds_binding_flags[1] = 0;
ds_binding_flags[2] = VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT_EXT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT;
layout_createinfo_binding_flags[0].sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO_EXT;
layout_createinfo_binding_flags[0].pNext = NULL;
layout_createinfo_binding_flags[0].bindingCount = 3;
layout_createinfo_binding_flags[0].pBindingFlags = ds_binding_flags;
layout_create_flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT;
pool_create_flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT;
layout_pnext = layout_createinfo_binding_flags;
}
// Prepare descriptors
OneOffDescriptorSet ds(m_device,
{
{0, VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV, 1, kAllRayTracingStages, nullptr},
{1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, kAllRayTracingStages, nullptr},
{2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 6, kAllRayTracingStages, nullptr},
},
layout_create_flags, layout_pnext, pool_create_flags);
VkDescriptorSetVariableDescriptorCountAllocateInfoEXT variable_count = {};
uint32_t desc_counts;
if (descriptor_indexing) {
layout_create_flags = 0;
pool_create_flags = 0;
ds_binding_flags[2] =
VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT_EXT | VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT_EXT;
desc_counts = 6; // We'll reserve 8 spaces in the layout, but the descriptor will only use 6
variable_count.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_VARIABLE_DESCRIPTOR_COUNT_ALLOCATE_INFO_EXT;
variable_count.descriptorSetCount = 1;
variable_count.pDescriptorCounts = &desc_counts;
allocate_pnext = &variable_count;
}
OneOffDescriptorSet ds_variable(m_device,
{
{0, VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV, 1, kAllRayTracingStages, nullptr},
{1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, kAllRayTracingStages, nullptr},
{2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 8, kAllRayTracingStages, nullptr},
},
layout_create_flags, layout_pnext, pool_create_flags, allocate_pnext);
VkAccelerationStructureNV top_level_as_handle = top_level_as.handle();
VkWriteDescriptorSetAccelerationStructureNV write_descript_set_as = {};
write_descript_set_as.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_NV;
write_descript_set_as.accelerationStructureCount = 1;
write_descript_set_as.pAccelerationStructures = &top_level_as_handle;
VkDescriptorBufferInfo descriptor_buffer_info = {};
descriptor_buffer_info.buffer = storage_buffer.handle();
descriptor_buffer_info.offset = 0;
descriptor_buffer_info.range = storage_buffer_size;
VkDescriptorImageInfo descriptor_image_infos[6] = {};
for (int i = 0; i < 6; i++) {
descriptor_image_infos[i] = texture.DescriptorImageInfo();
descriptor_image_infos[i].sampler = sampler.handle();
descriptor_image_infos[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
}
VkWriteDescriptorSet descriptor_writes[3] = {};
descriptor_writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptor_writes[0].dstSet = ds.set_;
descriptor_writes[0].dstBinding = 0;
descriptor_writes[0].descriptorCount = 1;
descriptor_writes[0].descriptorType = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV;
descriptor_writes[0].pNext = &write_descript_set_as;
descriptor_writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptor_writes[1].dstSet = ds.set_;
descriptor_writes[1].dstBinding = 1;
descriptor_writes[1].descriptorCount = 1;
descriptor_writes[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
descriptor_writes[1].pBufferInfo = &descriptor_buffer_info;
descriptor_writes[2].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptor_writes[2].dstSet = ds.set_;
descriptor_writes[2].dstBinding = 2;
if (descriptor_indexing) {
descriptor_writes[2].descriptorCount = 5; // Intentionally don't write index 5
} else {
descriptor_writes[2].descriptorCount = 6;
}
descriptor_writes[2].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptor_writes[2].pImageInfo = descriptor_image_infos;
vk::UpdateDescriptorSets(m_device->device(), 3, descriptor_writes, 0, NULL);
if (descriptor_indexing) {
descriptor_writes[0].dstSet = ds_variable.set_;
descriptor_writes[1].dstSet = ds_variable.set_;
descriptor_writes[2].dstSet = ds_variable.set_;
vk::UpdateDescriptorSets(m_device->device(), 3, descriptor_writes, 0, NULL);
}
const VkPipelineLayoutObj pipeline_layout(m_device, {&ds.layout_});
const VkPipelineLayoutObj pipeline_layout_variable(m_device, {&ds_variable.layout_});
const auto SetImagesArrayLength = [](const std::string &shader_template, const std::string &length_str) {
const std::string to_replace = "IMAGES_ARRAY_LENGTH";
std::string result = shader_template;
auto position = result.find(to_replace);
assert(position != std::string::npos);
result.replace(position, to_replace.length(), length_str);
return result;
};
const std::string rgen_source_template = R"(#version 460
#extension GL_EXT_nonuniform_qualifier : require
#extension GL_EXT_samplerless_texture_functions : require
#extension GL_NV_ray_tracing : require
layout(set = 0, binding = 0) uniform accelerationStructureNV topLevelAS;
layout(set = 0, binding = 1, std430) buffer RayTracingSbo {
uint rgen_index;
uint ahit_index;
uint chit_index;
uint miss_index;
uint intr_index;
uint call_index;
uint rgen_ran;
uint ahit_ran;
uint chit_ran;
uint miss_ran;
uint intr_ran;
uint call_ran;
float result1;
float result2;
float result3;
} sbo;
layout(set = 0, binding = 2) uniform texture2D textures[IMAGES_ARRAY_LENGTH];
layout(location = 0) rayPayloadNV vec3 payload;
layout(location = 3) callableDataNV vec3 callableData;
void main() {
sbo.rgen_ran = 1;
executeCallableNV(0, 3);
sbo.result1 = callableData.x;
vec3 origin = vec3(0.0f, 0.0f, -2.0f);
vec3 direction = vec3(0.0f, 0.0f, 1.0f);
traceNV(topLevelAS, gl_RayFlagsNoneNV, 0xFF, 0, 1, 0, origin, 0.001, direction, 10000.0, 0);
sbo.result2 = payload.x;
traceNV(topLevelAS, gl_RayFlagsNoneNV, 0xFF, 0, 1, 0, origin, 0.001, -direction, 10000.0, 0);
sbo.result3 = payload.x;
if (sbo.rgen_index > 0) {
// OOB here:
sbo.result3 = texelFetch(textures[sbo.rgen_index], ivec2(0, 0), 0).x;
}
}
)";
const std::string rgen_source = SetImagesArrayLength(rgen_source_template, "6");
const std::string rgen_source_runtime = SetImagesArrayLength(rgen_source_template, "");
const std::string ahit_source_template = R"(#version 460
#extension GL_EXT_nonuniform_qualifier : require
#extension GL_EXT_samplerless_texture_functions : require
#extension GL_NV_ray_tracing : require
layout(set = 0, binding = 1, std430) buffer StorageBuffer {
uint rgen_index;
uint ahit_index;
uint chit_index;
uint miss_index;
uint intr_index;
uint call_index;
uint rgen_ran;
uint ahit_ran;
uint chit_ran;
uint miss_ran;
uint intr_ran;
uint call_ran;
float result1;
float result2;
float result3;
} sbo;
layout(set = 0, binding = 2) uniform texture2D textures[IMAGES_ARRAY_LENGTH];
hitAttributeNV vec3 hitValue;
layout(location = 0) rayPayloadInNV vec3 payload;
void main() {
sbo.ahit_ran = 2;
payload = vec3(0.1234f);
if (sbo.ahit_index > 0) {
// OOB here:
payload.x = texelFetch(textures[sbo.ahit_index], ivec2(0, 0), 0).x;
}
}
)";
const std::string ahit_source = SetImagesArrayLength(ahit_source_template, "6");
const std::string ahit_source_runtime = SetImagesArrayLength(ahit_source_template, "");
const std::string chit_source_template = R"(#version 460
#extension GL_EXT_nonuniform_qualifier : require
#extension GL_EXT_samplerless_texture_functions : require
#extension GL_NV_ray_tracing : require
layout(set = 0, binding = 1, std430) buffer RayTracingSbo {
uint rgen_index;
uint ahit_index;
uint chit_index;
uint miss_index;
uint intr_index;
uint call_index;
uint rgen_ran;
uint ahit_ran;
uint chit_ran;
uint miss_ran;
uint intr_ran;
uint call_ran;
float result1;
float result2;
float result3;
} sbo;
layout(set = 0, binding = 2) uniform texture2D textures[IMAGES_ARRAY_LENGTH];
layout(location = 0) rayPayloadInNV vec3 payload;
hitAttributeNV vec3 attribs;
void main() {
sbo.chit_ran = 3;
payload = attribs;
if (sbo.chit_index > 0) {
// OOB here:
payload.x = texelFetch(textures[sbo.chit_index], ivec2(0, 0), 0).x;
}
}
)";
const std::string chit_source = SetImagesArrayLength(chit_source_template, "6");
const std::string chit_source_runtime = SetImagesArrayLength(chit_source_template, "");
const std::string miss_source_template = R"(#version 460
#extension GL_EXT_nonuniform_qualifier : enable
#extension GL_EXT_samplerless_texture_functions : require
#extension GL_NV_ray_tracing : require
layout(set = 0, binding = 1, std430) buffer RayTracingSbo {
uint rgen_index;
uint ahit_index;
uint chit_index;
uint miss_index;
uint intr_index;
uint call_index;
uint rgen_ran;
uint ahit_ran;
uint chit_ran;
uint miss_ran;
uint intr_ran;
uint call_ran;
float result1;
float result2;
float result3;
} sbo;
layout(set = 0, binding = 2) uniform texture2D textures[IMAGES_ARRAY_LENGTH];
layout(location = 0) rayPayloadInNV vec3 payload;
void main() {
sbo.miss_ran = 4;
payload = vec3(1.0, 0.0, 0.0);
if (sbo.miss_index > 0) {
// OOB here:
payload.x = texelFetch(textures[sbo.miss_index], ivec2(0, 0), 0).x;
}
}
)";
const std::string miss_source = SetImagesArrayLength(miss_source_template, "6");
const std::string miss_source_runtime = SetImagesArrayLength(miss_source_template, "");
const std::string intr_source_template = R"(#version 460
#extension GL_EXT_nonuniform_qualifier : require
#extension GL_EXT_samplerless_texture_functions : require
#extension GL_NV_ray_tracing : require
layout(set = 0, binding = 1, std430) buffer StorageBuffer {
uint rgen_index;
uint ahit_index;
uint chit_index;
uint miss_index;
uint intr_index;
uint call_index;
uint rgen_ran;
uint ahit_ran;
uint chit_ran;
uint miss_ran;
uint intr_ran;
uint call_ran;
float result1;
float result2;
float result3;
} sbo;
layout(set = 0, binding = 2) uniform texture2D textures[IMAGES_ARRAY_LENGTH];
hitAttributeNV vec3 hitValue;
void main() {
sbo.intr_ran = 5;
hitValue = vec3(0.0f, 0.5f, 0.0f);
reportIntersectionNV(1.0f, 0);
if (sbo.intr_index > 0) {
// OOB here:
hitValue.x = texelFetch(textures[sbo.intr_index], ivec2(0, 0), 0).x;
}
}
)";
const std::string intr_source = SetImagesArrayLength(intr_source_template, "6");
const std::string intr_source_runtime = SetImagesArrayLength(intr_source_template, "");
const std::string call_source_template = R"(#version 460
#extension GL_EXT_nonuniform_qualifier : require
#extension GL_EXT_samplerless_texture_functions : require
#extension GL_NV_ray_tracing : require
layout(set = 0, binding = 1, std430) buffer StorageBuffer {
uint rgen_index;
uint ahit_index;
uint chit_index;
uint miss_index;
uint intr_index;
uint call_index;
uint rgen_ran;
uint ahit_ran;
uint chit_ran;
uint miss_ran;
uint intr_ran;
uint call_ran;
float result1;
float result2;
float result3;
} sbo;
layout(set = 0, binding = 2) uniform texture2D textures[IMAGES_ARRAY_LENGTH];
layout(location = 3) callableDataInNV vec3 callableData;
void main() {
sbo.call_ran = 6;
callableData = vec3(0.1234f);
if (sbo.call_index > 0) {
// OOB here:
callableData.x = texelFetch(textures[sbo.call_index], ivec2(0, 0), 0).x;
}
}
)";
const std::string call_source = SetImagesArrayLength(call_source_template, "6");
const std::string call_source_runtime = SetImagesArrayLength(call_source_template, "");
struct TestCase {
const std::string &rgen_shader_source;
const std::string &ahit_shader_source;
const std::string &chit_shader_source;
const std::string &miss_shader_source;
const std::string &intr_shader_source;
const std::string &call_shader_source;
bool variable_length;
uint32_t rgen_index;
uint32_t ahit_index;
uint32_t chit_index;
uint32_t miss_index;
uint32_t intr_index;
uint32_t call_index;
const char *expected_error;
};
std::vector<TestCase> tests;
tests.push_back({rgen_source, ahit_source, chit_source, miss_source, intr_source, call_source, false, 25, 0, 0, 0, 0, 0,
"Index of 25 used to index descriptor array of length 6."});
tests.push_back({rgen_source, ahit_source, chit_source, miss_source, intr_source, call_source, false, 0, 25, 0, 0, 0, 0,
"Index of 25 used to index descriptor array of length 6."});
tests.push_back({rgen_source, ahit_source, chit_source, miss_source, intr_source, call_source, false, 0, 0, 25, 0, 0, 0,
"Index of 25 used to index descriptor array of length 6."});
tests.push_back({rgen_source, ahit_source, chit_source, miss_source, intr_source, call_source, false, 0, 0, 0, 25, 0, 0,
"Index of 25 used to index descriptor array of length 6."});
tests.push_back({rgen_source, ahit_source, chit_source, miss_source, intr_source, call_source, false, 0, 0, 0, 0, 25, 0,
"Index of 25 used to index descriptor array of length 6."});
tests.push_back({rgen_source, ahit_source, chit_source, miss_source, intr_source, call_source, false, 0, 0, 0, 0, 0, 25,
"Index of 25 used to index descriptor array of length 6."});
if (descriptor_indexing) {
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 25, 0, 0, 0, 0, 0, "Index of 25 used to index descriptor array of length 6."});
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 0, 25, 0, 0, 0, 0, "Index of 25 used to index descriptor array of length 6."});
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 0, 0, 25, 0, 0, 0, "Index of 25 used to index descriptor array of length 6."});
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 0, 0, 0, 25, 0, 0, "Index of 25 used to index descriptor array of length 6."});
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 0, 0, 0, 0, 25, 0, "Index of 25 used to index descriptor array of length 6."});
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 0, 0, 0, 0, 0, 25, "Index of 25 used to index descriptor array of length 6."});
// For this group, 6 is less than max specified (max specified is 8) but more than actual specified (actual specified is 5)
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 6, 0, 0, 0, 0, 0, "Index of 6 used to index descriptor array of length 6."});
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 0, 6, 0, 0, 0, 0, "Index of 6 used to index descriptor array of length 6."});
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 0, 0, 6, 0, 0, 0, "Index of 6 used to index descriptor array of length 6."});
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 0, 0, 0, 6, 0, 0, "Index of 6 used to index descriptor array of length 6."});
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 0, 0, 0, 0, 6, 0, "Index of 6 used to index descriptor array of length 6."});
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 0, 0, 0, 0, 0, 6, "Index of 6 used to index descriptor array of length 6."});
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 5, 0, 0, 0, 0, 0, "Descriptor index 5 is uninitialized."});
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 0, 5, 0, 0, 0, 0, "Descriptor index 5 is uninitialized."});
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 0, 0, 5, 0, 0, 0, "Descriptor index 5 is uninitialized."});
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 0, 0, 0, 5, 0, 0, "Descriptor index 5 is uninitialized."});
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 0, 0, 0, 0, 5, 0, "Descriptor index 5 is uninitialized."});
tests.push_back({rgen_source_runtime, ahit_source_runtime, chit_source_runtime, miss_source_runtime, intr_source_runtime,
call_source_runtime, true, 0, 0, 0, 0, 0, 5, "Descriptor index 5 is uninitialized."});
}
PFN_vkCreateRayTracingPipelinesNV vkCreateRayTracingPipelinesNV = reinterpret_cast<PFN_vkCreateRayTracingPipelinesNV>(
vk::GetDeviceProcAddr(m_device->handle(), "vkCreateRayTracingPipelinesNV"));
ASSERT_TRUE(vkCreateRayTracingPipelinesNV != nullptr);
PFN_vkGetRayTracingShaderGroupHandlesNV vkGetRayTracingShaderGroupHandlesNV =
reinterpret_cast<PFN_vkGetRayTracingShaderGroupHandlesNV>(
vk::GetDeviceProcAddr(m_device->handle(), "vkGetRayTracingShaderGroupHandlesNV"));
ASSERT_TRUE(vkGetRayTracingShaderGroupHandlesNV != nullptr);
PFN_vkCmdTraceRaysNV vkCmdTraceRaysNV =
reinterpret_cast<PFN_vkCmdTraceRaysNV>(vk::GetDeviceProcAddr(m_device->handle(), "vkCmdTraceRaysNV"));
ASSERT_TRUE(vkCmdTraceRaysNV != nullptr);
// Iteration 0 tests with no descriptor set bound (to sanity test "draw" validation). Iteration 1
// tests what's in the test case vector.
for (const auto &test : tests) {
if (gpu_assisted) {
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, test.expected_error);
}
VkShaderObj rgen_shader(m_device, test.rgen_shader_source.c_str(), VK_SHADER_STAGE_RAYGEN_BIT_NV, this, "main");
VkShaderObj ahit_shader(m_device, test.ahit_shader_source.c_str(), VK_SHADER_STAGE_ANY_HIT_BIT_NV, this, "main");
VkShaderObj chit_shader(m_device, test.chit_shader_source.c_str(), VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV, this, "main");
VkShaderObj miss_shader(m_device, test.miss_shader_source.c_str(), VK_SHADER_STAGE_MISS_BIT_NV, this, "main");
VkShaderObj intr_shader(m_device, test.intr_shader_source.c_str(), VK_SHADER_STAGE_INTERSECTION_BIT_NV, this, "main");
VkShaderObj call_shader(m_device, test.call_shader_source.c_str(), VK_SHADER_STAGE_CALLABLE_BIT_NV, this, "main");
VkPipelineShaderStageCreateInfo stage_create_infos[6] = {};
stage_create_infos[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
stage_create_infos[0].stage = VK_SHADER_STAGE_RAYGEN_BIT_NV;
stage_create_infos[0].module = rgen_shader.handle();
stage_create_infos[0].pName = "main";
stage_create_infos[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
stage_create_infos[1].stage = VK_SHADER_STAGE_ANY_HIT_BIT_NV;
stage_create_infos[1].module = ahit_shader.handle();
stage_create_infos[1].pName = "main";
stage_create_infos[2].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
stage_create_infos[2].stage = VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
stage_create_infos[2].module = chit_shader.handle();
stage_create_infos[2].pName = "main";
stage_create_infos[3].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
stage_create_infos[3].stage = VK_SHADER_STAGE_MISS_BIT_NV;
stage_create_infos[3].module = miss_shader.handle();
stage_create_infos[3].pName = "main";
stage_create_infos[4].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
stage_create_infos[4].stage = VK_SHADER_STAGE_INTERSECTION_BIT_NV;
stage_create_infos[4].module = intr_shader.handle();
stage_create_infos[4].pName = "main";
stage_create_infos[5].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
stage_create_infos[5].stage = VK_SHADER_STAGE_CALLABLE_BIT_NV;
stage_create_infos[5].module = call_shader.handle();
stage_create_infos[5].pName = "main";
VkRayTracingShaderGroupCreateInfoNV group_create_infos[4] = {};
group_create_infos[0].sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_NV;
group_create_infos[0].type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV;
group_create_infos[0].generalShader = 0; // rgen
group_create_infos[0].closestHitShader = VK_SHADER_UNUSED_NV;
group_create_infos[0].anyHitShader = VK_SHADER_UNUSED_NV;
group_create_infos[0].intersectionShader = VK_SHADER_UNUSED_NV;
group_create_infos[1].sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_NV;
group_create_infos[1].type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV;
group_create_infos[1].generalShader = 3; // miss
group_create_infos[1].closestHitShader = VK_SHADER_UNUSED_NV;
group_create_infos[1].anyHitShader = VK_SHADER_UNUSED_NV;
group_create_infos[1].intersectionShader = VK_SHADER_UNUSED_NV;
group_create_infos[2].sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_NV;
group_create_infos[2].type = VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV;
group_create_infos[2].generalShader = VK_SHADER_UNUSED_NV;
group_create_infos[2].closestHitShader = 2;
group_create_infos[2].anyHitShader = 1;
group_create_infos[2].intersectionShader = 4;
group_create_infos[3].sType = VK_STRUCTURE_TYPE_RAY_TRACING_SHADER_GROUP_CREATE_INFO_NV;
group_create_infos[3].type = VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV;
group_create_infos[3].generalShader = 5; // call
group_create_infos[3].closestHitShader = VK_SHADER_UNUSED_NV;
group_create_infos[3].anyHitShader = VK_SHADER_UNUSED_NV;
group_create_infos[3].intersectionShader = VK_SHADER_UNUSED_NV;
VkRayTracingPipelineCreateInfoNV pipeline_ci = {};
pipeline_ci.sType = VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV;
pipeline_ci.stageCount = 6;
pipeline_ci.pStages = stage_create_infos;
pipeline_ci.groupCount = 4;
pipeline_ci.pGroups = group_create_infos;
pipeline_ci.maxRecursionDepth = 2;
pipeline_ci.layout = test.variable_length ? pipeline_layout_variable.handle() : pipeline_layout.handle();
VkPipeline pipeline = VK_NULL_HANDLE;
ASSERT_VK_SUCCESS(vkCreateRayTracingPipelinesNV(m_device->handle(), VK_NULL_HANDLE, 1, &pipeline_ci, nullptr, &pipeline));
std::vector<uint8_t> shader_binding_table_data;
shader_binding_table_data.resize(static_cast<std::size_t>(shader_binding_table_buffer_size), 0);
ASSERT_VK_SUCCESS(vkGetRayTracingShaderGroupHandlesNV(m_device->handle(), pipeline, 0, 4,
static_cast<std::size_t>(shader_binding_table_buffer_size),
shader_binding_table_data.data()));
uint8_t *mapped_shader_binding_table_data = (uint8_t *)shader_binding_table_buffer.memory().map();
std::memcpy(mapped_shader_binding_table_data, shader_binding_table_data.data(), shader_binding_table_data.size());
shader_binding_table_buffer.memory().unmap();
ray_tracing_command_buffer.begin();
vk::CmdBindPipeline(ray_tracing_command_buffer.handle(), VK_PIPELINE_BIND_POINT_RAY_TRACING_NV, pipeline);
if (gpu_assisted) {
vk::CmdBindDescriptorSets(ray_tracing_command_buffer.handle(), VK_PIPELINE_BIND_POINT_RAY_TRACING_NV,
test.variable_length ? pipeline_layout_variable.handle() : pipeline_layout.handle(), 0, 1,
test.variable_length ? &ds_variable.set_ : &ds.set_, 0, nullptr);
} else {
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysNV-None-02697");
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "UNASSIGNED-CoreValidation-DrawState-DescriptorSetNotBound");
}
if (gpu_assisted) {
// Need these values to pass mapped storage buffer checks
vkCmdTraceRaysNV(ray_tracing_command_buffer.handle(), shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupHandleSize * 0ull, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupHandleSize * 1ull, ray_tracing_properties.shaderGroupHandleSize,
shader_binding_table_buffer.handle(), ray_tracing_properties.shaderGroupHandleSize * 2ull,
ray_tracing_properties.shaderGroupHandleSize, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupHandleSize * 3ull, ray_tracing_properties.shaderGroupHandleSize,
/*width=*/1, /*height=*/1, /*depth=*/1);
} else {
// offset shall be multiple of shaderGroupBaseAlignment and stride of shaderGroupHandleSize
vkCmdTraceRaysNV(ray_tracing_command_buffer.handle(), shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 0ull, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 1ull, ray_tracing_properties.shaderGroupHandleSize,
shader_binding_table_buffer.handle(), ray_tracing_properties.shaderGroupBaseAlignment * 2ull,
ray_tracing_properties.shaderGroupHandleSize, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 3ull, ray_tracing_properties.shaderGroupHandleSize,
/*width=*/1, /*height=*/1, /*depth=*/1);
}
ray_tracing_command_buffer.end();
// Update the index of the texture that the shaders should read
uint32_t *mapped_storage_buffer_data = (uint32_t *)storage_buffer.memory().map();
mapped_storage_buffer_data[0] = test.rgen_index;
mapped_storage_buffer_data[1] = test.ahit_index;
mapped_storage_buffer_data[2] = test.chit_index;
mapped_storage_buffer_data[3] = test.miss_index;
mapped_storage_buffer_data[4] = test.intr_index;
mapped_storage_buffer_data[5] = test.call_index;
mapped_storage_buffer_data[6] = 0;
mapped_storage_buffer_data[7] = 0;
mapped_storage_buffer_data[8] = 0;
mapped_storage_buffer_data[9] = 0;
mapped_storage_buffer_data[10] = 0;
mapped_storage_buffer_data[11] = 0;
storage_buffer.memory().unmap();
vk::QueueSubmit(ray_tracing_queue, 1, &submit_info, VK_NULL_HANDLE);
vk::QueueWaitIdle(ray_tracing_queue);
m_errorMonitor->VerifyFound();
if (gpu_assisted) {
mapped_storage_buffer_data = (uint32_t *)storage_buffer.memory().map();
ASSERT_TRUE(mapped_storage_buffer_data[6] == 1);
ASSERT_TRUE(mapped_storage_buffer_data[7] == 2);
ASSERT_TRUE(mapped_storage_buffer_data[8] == 3);
ASSERT_TRUE(mapped_storage_buffer_data[9] == 4);
ASSERT_TRUE(mapped_storage_buffer_data[10] == 5);
ASSERT_TRUE(mapped_storage_buffer_data[11] == 6);
storage_buffer.memory().unmap();
} else {
ray_tracing_command_buffer.begin();
vk::CmdBindPipeline(ray_tracing_command_buffer.handle(), VK_PIPELINE_BIND_POINT_RAY_TRACING_NV, pipeline);
vk::CmdBindDescriptorSets(ray_tracing_command_buffer.handle(), VK_PIPELINE_BIND_POINT_RAY_TRACING_NV,
test.variable_length ? pipeline_layout_variable.handle() : pipeline_layout.handle(), 0, 1,
test.variable_length ? &ds_variable.set_ : &ds.set_, 0, nullptr);
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysNV-callableShaderBindingOffset-02462");
VkDeviceSize stride_align = ray_tracing_properties.shaderGroupHandleSize;
VkDeviceSize invalid_max_stride = ray_tracing_properties.maxShaderGroupStride +
(stride_align - (ray_tracing_properties.maxShaderGroupStride %
stride_align)); // should be less than maxShaderGroupStride
VkDeviceSize invalid_stride =
ray_tracing_properties.shaderGroupHandleSize >> 1; // should be multiple of shaderGroupHandleSize
VkDeviceSize invalid_offset =
ray_tracing_properties.shaderGroupBaseAlignment >> 1; // should be multiple of shaderGroupBaseAlignment
vkCmdTraceRaysNV(ray_tracing_command_buffer.handle(), shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 0ull, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 1ull, ray_tracing_properties.shaderGroupHandleSize,
shader_binding_table_buffer.handle(), ray_tracing_properties.shaderGroupBaseAlignment * 2ull,
ray_tracing_properties.shaderGroupHandleSize, shader_binding_table_buffer.handle(), invalid_offset,
ray_tracing_properties.shaderGroupHandleSize,
/*width=*/1, /*height=*/1, /*depth=*/1);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysNV-callableShaderBindingStride-02465");
vkCmdTraceRaysNV(ray_tracing_command_buffer.handle(), shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 0ull, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 1ull, ray_tracing_properties.shaderGroupHandleSize,
shader_binding_table_buffer.handle(), ray_tracing_properties.shaderGroupBaseAlignment * 2ull,
ray_tracing_properties.shaderGroupHandleSize, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment, invalid_stride,
/*width=*/1, /*height=*/1, /*depth=*/1);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysNV-callableShaderBindingStride-02468");
vkCmdTraceRaysNV(ray_tracing_command_buffer.handle(), shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 0ull, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 1ull, ray_tracing_properties.shaderGroupHandleSize,
shader_binding_table_buffer.handle(), ray_tracing_properties.shaderGroupBaseAlignment * 2ull,
ray_tracing_properties.shaderGroupHandleSize, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment, invalid_max_stride,
/*width=*/1, /*height=*/1, /*depth=*/1);
m_errorMonitor->VerifyFound();
// hit shader
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysNV-hitShaderBindingOffset-02460");
vkCmdTraceRaysNV(ray_tracing_command_buffer.handle(), shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 0ull, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 1ull, ray_tracing_properties.shaderGroupHandleSize,
shader_binding_table_buffer.handle(), invalid_offset, ray_tracing_properties.shaderGroupHandleSize,
shader_binding_table_buffer.handle(), ray_tracing_properties.shaderGroupBaseAlignment,
ray_tracing_properties.shaderGroupHandleSize,
/*width=*/1, /*height=*/1, /*depth=*/1);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysNV-hitShaderBindingStride-02464");
vkCmdTraceRaysNV(ray_tracing_command_buffer.handle(), shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 0ull, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 1ull, ray_tracing_properties.shaderGroupHandleSize,
shader_binding_table_buffer.handle(), ray_tracing_properties.shaderGroupBaseAlignment * 2ull,
invalid_stride, shader_binding_table_buffer.handle(), ray_tracing_properties.shaderGroupBaseAlignment,
ray_tracing_properties.shaderGroupHandleSize,
/*width=*/1, /*height=*/1, /*depth=*/1);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysNV-hitShaderBindingStride-02467");
vkCmdTraceRaysNV(ray_tracing_command_buffer.handle(), shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 0ull, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 1ull, ray_tracing_properties.shaderGroupHandleSize,
shader_binding_table_buffer.handle(), ray_tracing_properties.shaderGroupBaseAlignment * 2ull,
invalid_max_stride, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment, ray_tracing_properties.shaderGroupHandleSize,
/*width=*/1, /*height=*/1, /*depth=*/1);
m_errorMonitor->VerifyFound();
// miss shader
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysNV-missShaderBindingOffset-02458");
vkCmdTraceRaysNV(ray_tracing_command_buffer.handle(), shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 0ull, shader_binding_table_buffer.handle(),
invalid_offset, ray_tracing_properties.shaderGroupHandleSize, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 2ull, ray_tracing_properties.shaderGroupHandleSize,
shader_binding_table_buffer.handle(), ray_tracing_properties.shaderGroupBaseAlignment,
ray_tracing_properties.shaderGroupHandleSize,
/*width=*/1, /*height=*/1, /*depth=*/1);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysNV-missShaderBindingStride-02463");
vkCmdTraceRaysNV(ray_tracing_command_buffer.handle(), shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 0ull, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 1ull, invalid_stride,
shader_binding_table_buffer.handle(), ray_tracing_properties.shaderGroupBaseAlignment * 2ull,
ray_tracing_properties.shaderGroupHandleSize, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment, ray_tracing_properties.shaderGroupHandleSize,
/*width=*/1, /*height=*/1, /*depth=*/1);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysNV-missShaderBindingStride-02466");
vkCmdTraceRaysNV(ray_tracing_command_buffer.handle(), shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 0ull, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 1ull, invalid_max_stride,
shader_binding_table_buffer.handle(), ray_tracing_properties.shaderGroupBaseAlignment * 2ull,
ray_tracing_properties.shaderGroupHandleSize, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment, ray_tracing_properties.shaderGroupHandleSize,
/*width=*/1, /*height=*/1, /*depth=*/1);
m_errorMonitor->VerifyFound();
// raygenshader
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysNV-raygenShaderBindingOffset-02456");
vkCmdTraceRaysNV(ray_tracing_command_buffer.handle(), shader_binding_table_buffer.handle(), invalid_offset,
shader_binding_table_buffer.handle(), ray_tracing_properties.shaderGroupBaseAlignment * 1ull,
ray_tracing_properties.shaderGroupHandleSize, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 2ull, ray_tracing_properties.shaderGroupHandleSize,
shader_binding_table_buffer.handle(), ray_tracing_properties.shaderGroupBaseAlignment,
ray_tracing_properties.shaderGroupHandleSize,
/*width=*/1, /*height=*/1, /*depth=*/1);
m_errorMonitor->VerifyFound();
const auto &limits = m_device->props.limits;
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysNV-width-02469");
uint32_t invalid_width = limits.maxComputeWorkGroupCount[0] + 1;
vkCmdTraceRaysNV(ray_tracing_command_buffer.handle(), shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 0ull, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 1ull, ray_tracing_properties.shaderGroupHandleSize,
shader_binding_table_buffer.handle(), ray_tracing_properties.shaderGroupBaseAlignment * 2ull,
ray_tracing_properties.shaderGroupHandleSize, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment, ray_tracing_properties.shaderGroupHandleSize,
/*width=*/invalid_width, /*height=*/1, /*depth=*/1);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysNV-height-02470");
uint32_t invalid_height = limits.maxComputeWorkGroupCount[1] + 1;
vkCmdTraceRaysNV(ray_tracing_command_buffer.handle(), shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 0ull, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 1ull, ray_tracing_properties.shaderGroupHandleSize,
shader_binding_table_buffer.handle(), ray_tracing_properties.shaderGroupBaseAlignment * 2ull,
ray_tracing_properties.shaderGroupHandleSize, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment, ray_tracing_properties.shaderGroupHandleSize,
/*width=*/1, /*height=*/invalid_height, /*depth=*/1);
m_errorMonitor->VerifyFound();
m_errorMonitor->SetDesiredFailureMsg(kErrorBit, "VUID-vkCmdTraceRaysNV-depth-02471");
uint32_t invalid_depth = limits.maxComputeWorkGroupCount[2] + 1;
vkCmdTraceRaysNV(ray_tracing_command_buffer.handle(), shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 0ull, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment * 1ull, ray_tracing_properties.shaderGroupHandleSize,
shader_binding_table_buffer.handle(), ray_tracing_properties.shaderGroupBaseAlignment * 2ull,
ray_tracing_properties.shaderGroupHandleSize, shader_binding_table_buffer.handle(),
ray_tracing_properties.shaderGroupBaseAlignment, ray_tracing_properties.shaderGroupHandleSize,
/*width=*/1, /*height=*/1, /*depth=*/invalid_depth);
m_errorMonitor->VerifyFound();
ray_tracing_command_buffer.end();
}
vk::DestroyPipeline(m_device->handle(), pipeline, nullptr);
}
}
void VkSyncValTest::InitSyncValFramework() {
// Enable synchronization validation
InitFramework(m_errorMonitor, &features_);
}
void print_android(const char *c) {
#ifdef VK_USE_PLATFORM_ANDROID_KHR
__android_log_print(ANDROID_LOG_INFO, "VulkanLayerValidationTests", "%s", c);
#endif // VK_USE_PLATFORM_ANDROID_KHR
}
#if defined(ANDROID) && defined(VALIDATION_APK)
const char *appTag = "VulkanLayerValidationTests";
static bool initialized = false;
static bool active = false;
// Convert Intents to argv
// Ported from Hologram sample, only difference is flexible key
std::vector<std::string> get_args(android_app &app, const char *intent_extra_data_key) {
std::vector<std::string> args;
JavaVM &vm = *app.activity->vm;
JNIEnv *p_env;
if (vm.AttachCurrentThread(&p_env, nullptr) != JNI_OK) return args;
JNIEnv &env = *p_env;
jobject activity = app.activity->clazz;
jmethodID get_intent_method = env.GetMethodID(env.GetObjectClass(activity), "getIntent", "()Landroid/content/Intent;");
jobject intent = env.CallObjectMethod(activity, get_intent_method);
jmethodID get_string_extra_method =
env.GetMethodID(env.GetObjectClass(intent), "getStringExtra", "(Ljava/lang/String;)Ljava/lang/String;");
jvalue get_string_extra_args;
get_string_extra_args.l = env.NewStringUTF(intent_extra_data_key);
jstring extra_str = static_cast<jstring>(env.CallObjectMethodA(intent, get_string_extra_method, &get_string_extra_args));
std::string args_str;
if (extra_str) {
const char *extra_utf = env.GetStringUTFChars(extra_str, nullptr);
args_str = extra_utf;
env.ReleaseStringUTFChars(extra_str, extra_utf);
env.DeleteLocalRef(extra_str);
}
env.DeleteLocalRef(get_string_extra_args.l);
env.DeleteLocalRef(intent);
vm.DetachCurrentThread();
// split args_str
std::stringstream ss(args_str);
std::string arg;
while (std::getline(ss, arg, ' ')) {
if (!arg.empty()) args.push_back(arg);
}
return args;
}
void addFullTestCommentIfPresent(const ::testing::TestInfo &test_info, std::string &error_message) {
const char *const type_param = test_info.type_param();
const char *const value_param = test_info.value_param();
if (type_param != NULL || value_param != NULL) {
error_message.append(", where ");
if (type_param != NULL) {
error_message.append("TypeParam = ").append(type_param);
if (value_param != NULL) error_message.append(" and ");
}
if (value_param != NULL) {
error_message.append("GetParam() = ").append(value_param);
}
}
}
// Inspired by https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md
class LogcatPrinter : public ::testing::EmptyTestEventListener {
// Called before a test starts.
virtual void OnTestStart(const ::testing::TestInfo &test_info) {
__android_log_print(ANDROID_LOG_INFO, appTag, "[ RUN ] %s.%s", test_info.test_case_name(), test_info.name());
}
// Called after a failed assertion or a SUCCEED() invocation.
virtual void OnTestPartResult(const ::testing::TestPartResult &result) {
// If the test part succeeded, we don't need to do anything.
if (result.type() == ::testing::TestPartResult::kSuccess) return;
__android_log_print(ANDROID_LOG_INFO, appTag, "%s in %s:%d %s", result.failed() ? "*** Failure" : "Success",
result.file_name(), result.line_number(), result.summary());
}
// Called after a test ends.
virtual void OnTestEnd(const ::testing::TestInfo &info) {
std::string result;
if (info.result()->Passed()) {
result.append("[ OK ]");
} else {
result.append("[ FAILED ]");
}
result.append(info.test_case_name()).append(".").append(info.name());
if (info.result()->Failed()) addFullTestCommentIfPresent(info, result);
if (::testing::GTEST_FLAG(print_time)) {
std::ostringstream os;
os << info.result()->elapsed_time();
result.append(" (").append(os.str()).append(" ms)");
}
__android_log_print(ANDROID_LOG_INFO, appTag, "%s", result.c_str());
};
};
static int32_t processInput(struct android_app *app, AInputEvent *event) { return 0; }
static void processCommand(struct android_app *app, int32_t cmd) {
switch (cmd) {
case APP_CMD_INIT_WINDOW: {
if (app->window) {
initialized = true;
VkTestFramework::window = app->window;
}
break;
}
case APP_CMD_GAINED_FOCUS: {
active = true;
break;
}
case APP_CMD_LOST_FOCUS: {
active = false;
break;
}
}
}
static void destroyActivity(struct android_app *app) {
ANativeActivity_finish(app->activity);
// Wait for APP_CMD_DESTROY
while (app->destroyRequested == 0) {
struct android_poll_source *source = nullptr;
int events = 0;
int result = ALooper_pollAll(-1, nullptr, &events, reinterpret_cast<void **>(&source));
if ((result >= 0) && (source)) {
source->process(app, source);
} else {
break;
}
}
}
void android_main(struct android_app *app) {
app->onAppCmd = processCommand;
app->onInputEvent = processInput;
while (1) {
int events;
struct android_poll_source *source;
while (ALooper_pollAll(active ? 0 : -1, NULL, &events, (void **)&source) >= 0) {
if (source) {
source->process(app, source);
}
if (app->destroyRequested != 0) {
VkTestFramework::Finish();
return;
}
}
if (initialized && active) {
// Use the following key to send arguments to gtest, i.e.
// --es args "--gtest_filter=-VkLayerTest.foo"
const char key[] = "args";
std::vector<std::string> args = get_args(*app, key);
std::string filter = "";
if (args.size() > 0) {
__android_log_print(ANDROID_LOG_INFO, appTag, "Intent args = %s", args[0].c_str());
filter += args[0];
} else {
__android_log_print(ANDROID_LOG_INFO, appTag, "No Intent args detected");
}
int argc = 2;
char *argv[] = {(char *)"foo", (char *)filter.c_str()};
__android_log_print(ANDROID_LOG_DEBUG, appTag, "filter = %s", argv[1]);
// Route output to files until we can override the gtest output
freopen("/sdcard/Android/data/com.example.VulkanLayerValidationTests/files/out.txt", "w", stdout);
freopen("/sdcard/Android/data/com.example.VulkanLayerValidationTests/files/err.txt", "w", stderr);
::testing::InitGoogleTest(&argc, argv);
::testing::TestEventListeners &listeners = ::testing::UnitTest::GetInstance()->listeners();
listeners.Append(new LogcatPrinter);
VkTestFramework::InitArgs(&argc, argv);
::testing::AddGlobalTestEnvironment(new TestEnvironment);
int result = RUN_ALL_TESTS();
if (result != 0) {
__android_log_print(ANDROID_LOG_INFO, appTag, "==== Tests FAILED ====");
} else {
__android_log_print(ANDROID_LOG_INFO, appTag, "==== Tests PASSED ====");
}
VkTestFramework::Finish();
fclose(stdout);
fclose(stderr);
destroyActivity(app);
raise(SIGTERM);
return;
}
}
}
#endif
#if defined(_WIN32) && !defined(NDEBUG)
#include <crtdbg.h>
#endif
int main(int argc, char **argv) {
int result;
#if defined(_WIN32)
#if !defined(NDEBUG)
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
#endif
// Avoid "Abort, Retry, Ignore" dialog boxes
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
#endif
::testing::InitGoogleTest(&argc, argv);
VkTestFramework::InitArgs(&argc, argv);
::testing::AddGlobalTestEnvironment(new TestEnvironment);
result = RUN_ALL_TESTS();
VkTestFramework::Finish();
return result;
}
| 1 | 20,752 | I can't recall if there was a fix specific to this in the past? | KhronosGroup-Vulkan-ValidationLayers | cpp |
@@ -51,14 +51,15 @@ var _ = duck.VerifyType(&PubSubSource{}, &duckv1alpha1.Conditions{})
// PubSubSourceSpec defines the desired state of the PubSubSource.
type PubSubSourceSpec struct {
- // GcpCredsSecret is the credential to use to poll the GCP PubSubSource Subscription. It is not used
+ // Secret is the credential to use to poll the PubSubSource Subscription. It is not used
// to create or delete the Subscription, only to poll it. The value of the secret entry must be
// a service account key in the JSON format (see
// https://cloud.google.com/iam/docs/creating-managing-service-account-keys).
- GcpCredsSecret corev1.SecretKeySelector `json:"gcpCredsSecret,omitempty"`
+ Secret *corev1.SecretKeySelector `json:"secret,omitempty"`
- // GoogleCloudProject is the ID of the Google Cloud Project that the PubSubSource Topic exists in.
- GoogleCloudProject string `json:"googleCloudProject,omitempty"`
+ // TODO: https://github.com/googleapis/google-cloud-go/blob/master/compute/metadata/metadata.go
+ // Project is the ID of the Google Cloud Project that the PubSubSource Topic exists in.
+ Project string `json:"project,omitempty"`
// Topic is the ID of the GCP PubSubSource Topic to Subscribe to. It must be in the form of the
// unique identifier within the project, not the entire name. E.g. it must be 'laconia', not | 1 | /*
Copyright 2019 Google LLC
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.
*/
package v1alpha1
import (
"fmt"
"github.com/knative/pkg/apis"
"github.com/knative/pkg/apis/duck"
duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
)
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// PubSubSource is the Schema for the gcppubsubsources API.
// +k8s:openapi-gen=true
type PubSubSource struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec PubSubSourceSpec `json:"spec,omitempty"`
Status PubSubSourceStatus `json:"status,omitempty"`
}
// Check that PubSubSource can be validated and can be defaulted.
var _ runtime.Object = (*PubSubSource)(nil)
// Check that PubSubSource will be checked for immutable fields.
var _ apis.Immutable = (*PubSubSource)(nil)
// Check that PubSubSource implements the Conditions duck type.
var _ = duck.VerifyType(&PubSubSource{}, &duckv1alpha1.Conditions{})
// PubSubSourceSpec defines the desired state of the PubSubSource.
type PubSubSourceSpec struct {
// GcpCredsSecret is the credential to use to poll the GCP PubSubSource Subscription. It is not used
// to create or delete the Subscription, only to poll it. The value of the secret entry must be
// a service account key in the JSON format (see
// https://cloud.google.com/iam/docs/creating-managing-service-account-keys).
GcpCredsSecret corev1.SecretKeySelector `json:"gcpCredsSecret,omitempty"`
// GoogleCloudProject is the ID of the Google Cloud Project that the PubSubSource Topic exists in.
GoogleCloudProject string `json:"googleCloudProject,omitempty"`
// Topic is the ID of the GCP PubSubSource Topic to Subscribe to. It must be in the form of the
// unique identifier within the project, not the entire name. E.g. it must be 'laconia', not
// 'projects/my-eventing-project/topics/laconia'.
Topic string `json:"topic,omitempty"`
// Sink is a reference to an object that will resolve to a domain name to use as the sink.
// +optional
Sink *corev1.ObjectReference `json:"sink,omitempty"`
// Transformer is a reference to an object that will resolve to a domain name to use as the transformer.
// +optional
Transformer *corev1.ObjectReference `json:"transformer,omitempty"`
// ServiceAccoutName is the name of the ServiceAccount that will be used to run the Receive
// Adapter Deployment.
ServiceAccountName string `json:"serviceAccountName,omitempty"`
}
const (
// PubSubEventType is the GcpPubSub CloudEvent type, in case PubSubSource doesn't send a
// CloudEvent itself.
PubSubEventType = "google.pubsub.topic.publish"
)
// PubSubEventSource returns the GcpPubSub CloudEvent source value.
func PubSubEventSource(googleCloudProject, topic string) string {
return fmt.Sprintf("//pubsub.googleapis.com/%s/topics/%s", googleCloudProject, topic)
}
const (
// PubSubSourceConditionReady has status True when the PubSubSource is ready to send events.
PubSubSourceConditionReady = duckv1alpha1.ConditionReady
// PubSubSourceConditionSinkProvided has status True when the PubSubSource has been configured with a sink target.
PubSubSourceConditionSinkProvided duckv1alpha1.ConditionType = "SinkProvided"
// PubSubSourceConditionDeployed has status True when the PubSubSource has had it's receive adapter deployment created.
PubSubSourceConditionDeployed duckv1alpha1.ConditionType = "Deployed"
// PubSubSourceConditionSubscribed has status True when a GCP PubSubSource Subscription has been created pointing at the created receive adapter deployment.
PubSubSourceConditionSubscribed duckv1alpha1.ConditionType = "Subscribed"
// PubSubSourceConditionTransformerProvided has status True when the PubSubSource has been configured with a transformer target.
PubSubSourceConditionTransformerProvided duckv1alpha1.ConditionType = "TransformerProvided"
// PubSubSourceConditionEventTypesProvided has status True when the PubSubSource has been configured with event types.
PubSubSourceConditionEventTypesProvided duckv1alpha1.ConditionType = "EventTypesProvided"
)
var pubSubSourceCondSet = duckv1alpha1.NewLivingConditionSet(
PubSubSourceConditionSinkProvided,
PubSubSourceConditionDeployed,
PubSubSourceConditionSubscribed)
// PubSubSourceStatus defines the observed state of PubSubSource.
type PubSubSourceStatus struct {
// inherits duck/v1alpha1 Status, which currently provides:
// * ObservedGeneration - the 'Generation' of the Service that was last processed by the controller.
// * Conditions - the latest available observations of a resource's current state.
duckv1alpha1.Status `json:",inline"`
// SinkURI is the current active sink URI that has been configured for the PubSubSource.
// +optional
SinkURI string `json:"sinkUri,omitempty"`
// TransformerURI is the current active transformer URI that has been configured for the GcpPubSubSource.
// +optional
TransformerURI string `json:"transformerUri,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// PubSubSourceList contains a list of PubSubs.
type PubSubSourceList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []PubSubSource `json:"items"`
}
| 1 | 8,011 | Not sure what the todo is here? Is it to support some kind of defaulting based off of that? | google-knative-gcp | go |
@@ -68,11 +68,18 @@ namespace NLog.Targets.Wrappers
/// Delay the flush until the LogEvent has been confirmed as written
/// </summary>
/// <docgen category='General Options' order='10' />
- public bool AsyncFlush { get => _asyncFlush ?? true;
+ public bool AsyncFlush
+ {
+ get => _asyncFlush ?? true;
set => _asyncFlush = value;
}
private bool? _asyncFlush;
+ /// <summary>
+ /// Only flush when LogEvent matches condition. Ignore explicit-flush, config-reload-flush and shutdown-flush
+ /// </summary>
+ public bool FlushOnConditionOnly { get; set; }
+
private readonly AsyncOperationCounter _pendingManualFlushList = new AsyncOperationCounter();
/// <summary> | 1 | //
// Copyright (c) 2004-2019 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets.Wrappers
{
using NLog.Common;
using NLog.Conditions;
using NLog.Internal;
/// <summary>
/// Causes a flush on a wrapped target if LogEvent satisfies the <see cref="Condition"/>.
/// If condition isn't set, flushes on each write.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/AutoFlushWrapper-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/AutoFlushWrapper/NLog.config" />
/// <p>
/// The above examples assume just one target and a single rule. See below for
/// a programmatic configuration that's equivalent to the above config file:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/AutoFlushWrapper/Simple/Example.cs" />
/// </example>
[Target("AutoFlushWrapper", IsWrapper = true)]
public class AutoFlushTargetWrapper : WrapperTargetBase
{
/// <summary>
/// Gets or sets the condition expression. Log events who meet this condition will cause
/// a flush on the wrapped target.
/// </summary>
/// <docgen category='General Options' order='10' />
public ConditionExpression Condition { get; set; }
/// <summary>
/// Delay the flush until the LogEvent has been confirmed as written
/// </summary>
/// <docgen category='General Options' order='10' />
public bool AsyncFlush { get => _asyncFlush ?? true;
set => _asyncFlush = value;
}
private bool? _asyncFlush;
private readonly AsyncOperationCounter _pendingManualFlushList = new AsyncOperationCounter();
/// <summary>
/// Initializes a new instance of the <see cref="AutoFlushTargetWrapper" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
public AutoFlushTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AutoFlushTargetWrapper" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="name">Name of the target</param>
public AutoFlushTargetWrapper(string name, Target wrappedTarget)
: this(wrappedTarget)
{
Name = name;
}
/// <summary>
/// Initializes a new instance of the <see cref="AutoFlushTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
public AutoFlushTargetWrapper(Target wrappedTarget)
{
WrappedTarget = wrappedTarget;
}
/// <summary>
/// Initializes the target.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
if (!_asyncFlush.HasValue && WrappedTarget is BufferingTargetWrapper)
{
AsyncFlush = false; // Disable AsyncFlush, so the intended trigger works
}
}
/// <summary>
/// Forwards the call to the <see cref="WrapperTargetBase.WrappedTarget"/>.Write()
/// and calls <see cref="Target.Flush(AsyncContinuation)"/> on it if LogEvent satisfies
/// the flush condition or condition is null.
/// </summary>
/// <param name="logEvent">Logging event to be written out.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
if (Condition == null || Condition.Evaluate(logEvent.LogEvent).Equals(true))
{
if (AsyncFlush)
{
AsyncContinuation currentContinuation = logEvent.Continuation;
AsyncContinuation wrappedContinuation = (ex) =>
{
if (ex == null)
WrappedTarget.Flush((e) => { });
_pendingManualFlushList.CompleteOperation(ex);
currentContinuation(ex);
};
_pendingManualFlushList.BeginOperation();
WrappedTarget.WriteAsyncLogEvent(logEvent.LogEvent.WithContinuation(wrappedContinuation));
}
else
{
WrappedTarget.WriteAsyncLogEvent(logEvent);
FlushAsync((e) => { });
}
}
else
{
WrappedTarget.WriteAsyncLogEvent(logEvent);
}
}
/// <summary>
/// Schedules a flush operation, that triggers when all pending flush operations are completed (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
var wrappedContinuation = _pendingManualFlushList.RegisterCompletionNotification(asyncContinuation);
WrappedTarget.Flush(wrappedContinuation);
}
/// <summary>
/// Closes the target.
/// </summary>
protected override void CloseTarget()
{
_pendingManualFlushList.Clear(); // Maybe consider to wait a short while if pending requests?
base.CloseTarget();
}
}
}
| 1 | 19,632 | Not sure about this name. I think "explicit" is also a bit difficult here (I think it should be implicit then) Proposal: FlushOnEvents. Or, It would be cool if we could split into 2 options, FlushOnShutdown and FlushOnReload, but I expect that's far more difficult to implement? | NLog-NLog | .cs |
@@ -32,7 +32,11 @@ from qutebrowser.utils import objreg, qtutils
from qutebrowser.browser.webkit import tabhistory
-pytestmark = pytest.mark.qt_log_ignore('QIODevice::read.*: device not open')
[email protected](autouse=True)
[email protected]_log_ignore('QIODevice::read.*: device not open')
+def autouse(fake_save_manager):
+ yield
+
webengine_refactoring_xfail = pytest.mark.xfail(
True, reason='Broke during QtWebEngine refactoring, will be fixed after ' | 1 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2020 Florian Bruhin (The Compiler) <[email protected]>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""Tests for qutebrowser.misc.sessions."""
import logging
import pytest
import yaml
from PyQt5.QtCore import QUrl, QPoint, QByteArray, QObject
QWebView = pytest.importorskip('PyQt5.QtWebKitWidgets').QWebView
from qutebrowser.misc import sessions
from qutebrowser.misc.sessions import TabHistoryItem as Item
from qutebrowser.utils import objreg, qtutils
from qutebrowser.browser.webkit import tabhistory
pytestmark = pytest.mark.qt_log_ignore('QIODevice::read.*: device not open')
webengine_refactoring_xfail = pytest.mark.xfail(
True, reason='Broke during QtWebEngine refactoring, will be fixed after '
'sessions are refactored too.')
@pytest.fixture
def sess_man(tmp_path):
"""Fixture providing a SessionManager."""
return sessions.SessionManager(base_path=str(tmp_path))
class TestInit:
@pytest.fixture(autouse=True)
def cleanup(self, monkeypatch):
monkeypatch.setattr(sessions, 'session_manager', None)
yield
try:
objreg.delete('session-manager')
except KeyError:
pass
@pytest.mark.parametrize('create_dir', [True, False])
def test_with_standarddir(self, tmp_path, monkeypatch, create_dir):
monkeypatch.setattr(sessions.standarddir, 'data',
lambda: str(tmp_path))
session_dir = tmp_path / 'sessions'
if create_dir:
session_dir.mkdir()
sessions.init()
assert session_dir.exists()
assert sessions.session_manager._base_path == str(session_dir)
def test_did_not_load(sess_man):
assert not sess_man.did_load
class TestExists:
@pytest.mark.parametrize('absolute', [True, False])
def test_existent(self, tmp_path, absolute):
session_dir = tmp_path / 'sessions'
abs_session = tmp_path / 'foo.yml'
rel_session = session_dir / 'foo.yml'
session_dir.mkdir()
abs_session.touch()
rel_session.touch()
man = sessions.SessionManager(str(session_dir))
if absolute:
name = str(abs_session)
else:
name = 'foo'
assert man.exists(name)
@pytest.mark.parametrize('absolute', [True, False])
def test_inexistent(self, tmp_path, absolute):
man = sessions.SessionManager(str(tmp_path))
if absolute:
name = str(tmp_path / 'foo')
else:
name = 'foo'
assert not man.exists(name)
@webengine_refactoring_xfail
class TestSaveTab:
@pytest.mark.parametrize('is_active', [True, False])
def test_active(self, sess_man, webview, is_active):
data = sess_man._save_tab(webview, is_active)
if is_active:
assert data['active']
else:
assert 'active' not in data
def test_no_history(self, sess_man, webview):
data = sess_man._save_tab(webview, active=False)
assert not data['history']
class FakeMainWindow(QObject):
"""Helper class for the fake_main_window fixture.
A fake MainWindow which provides a saveGeometry method.
Needs to be a QObject so sip.isdeleted works.
"""
def __init__(self, geometry, win_id, parent=None):
super().__init__(parent)
self._geometry = QByteArray(geometry)
self.win_id = win_id
def saveGeometry(self):
return self._geometry
@pytest.fixture
def fake_window(tabbed_browser_stubs):
"""Fixture which provides a fake main windows with a tabbedbrowser."""
win0 = FakeMainWindow(b'fake-geometry-0', win_id=0)
objreg.register('main-window', win0, scope='window', window=0)
yield
objreg.delete('main-window', scope='window', window=0)
class TestSaveAll:
def test_no_history(self, sess_man):
# FIXME can this ever actually happen?
assert not objreg.window_registry
data = sess_man._save_all()
assert not data['windows']
@webengine_refactoring_xfail
def test_no_active_window(self, sess_man, fake_window, stubs,
monkeypatch):
qapp = stubs.FakeQApplication(active_window=None)
monkeypatch.setattr(sessions, 'QApplication', qapp)
sess_man._save_all()
@pytest.mark.parametrize('arg, config, current, expected', [
('foo', None, None, 'foo'),
(sessions.default, 'foo', None, 'foo'),
(sessions.default, None, 'foo', 'foo'),
(sessions.default, None, None, 'default'),
])
def test_get_session_name(config_stub, sess_man, arg, config, current,
expected):
config_stub.val.session.default_name = config
sess_man.current = current
assert sess_man._get_session_name(arg) == expected
class TestSave:
@pytest.fixture
def fake_history(self, stubs, tabbed_browser_stubs, monkeypatch, webview):
"""Fixture which provides a window with a fake history."""
win = FakeMainWindow(b'fake-geometry-0', win_id=0)
objreg.register('main-window', win, scope='window', window=0)
browser = tabbed_browser_stubs[0]
qapp = stubs.FakeQApplication(active_window=win)
monkeypatch.setattr(sessions, 'QApplication', qapp)
def set_data(items):
history = browser.widgets()[0].page().history()
stream, _data, user_data = tabhistory.serialize(items)
qtutils.deserialize_stream(stream, history)
for i, data in enumerate(user_data):
history.itemAt(i).setUserData(data)
yield set_data
objreg.delete('main-window', scope='window', window=0)
objreg.delete('tabbed-browser', scope='window', window=0)
def test_no_state_config(self, sess_man, tmp_path, state_config):
session_path = tmp_path / 'foo.yml'
sess_man.save(str(session_path))
assert 'session' not in state_config['general']
def test_last_window_session_none(self, caplog, sess_man, tmp_path):
session_path = tmp_path / 'foo.yml'
with caplog.at_level(logging.ERROR):
sess_man.save(str(session_path), last_window=True)
msg = "last_window_session is None while saving!"
assert caplog.messages == [msg]
assert not session_path.exists()
def test_last_window_session(self, sess_man, tmp_path):
sess_man.save_last_window_session()
session_path = tmp_path / 'foo.yml'
sess_man.save(str(session_path), last_window=True)
data = session_path.read_text('utf-8')
assert data == 'windows: []\n'
@pytest.mark.parametrize('exception', [
OSError('foo'), UnicodeEncodeError('ascii', '', 0, 2, 'foo'),
yaml.YAMLError('foo')])
def test_fake_exception(self, mocker, sess_man, tmp_path, exception):
mocker.patch('qutebrowser.misc.sessions.yaml.dump',
side_effect=exception)
with pytest.raises(sessions.SessionError, match=str(exception)):
sess_man.save(str(tmp_path / 'foo.yml'))
assert not list(tmp_path.glob('*'))
def test_load_next_time(self, tmp_path, state_config, sess_man):
session_path = tmp_path / 'foo.yml'
sess_man.save(str(session_path), load_next_time=True)
assert state_config['general']['session'] == str(session_path)
@webengine_refactoring_xfail
def test_utf_8_invalid(self, tmp_path, sess_man, fake_history):
"""Make sure data containing invalid UTF8 raises SessionError."""
session_path = tmp_path / 'foo.yml'
fake_history([Item(QUrl('http://www.qutebrowser.org/'), '\ud800',
active=True)])
try:
sess_man.save(str(session_path))
except sessions.SessionError:
# This seems to happen on some systems only?!
pass
else:
data = session_path.read_text('utf-8')
assert r'title: "\uD800"' in data
def _set_data(self, browser, tab_id, items):
"""Helper function for test_long_output."""
history = browser.widgets()[tab_id].page().history()
stream, _data, user_data = tabhistory.serialize(items)
qtutils.deserialize_stream(stream, history)
for i, data in enumerate(user_data):
history.itemAt(i).setUserData(data)
class FakeWebView:
"""A QWebView fake which provides a "page" with a load_history method.
Attributes:
loaded_history: The history which has been loaded by load_history, or
None.
raise_error: The exception to raise on load_history, or None.
"""
def __init__(self):
self.loaded_history = None
self.raise_error = None
def page(self):
return self
def load_history(self, data):
self.loaded_history = data
if self.raise_error is not None:
raise self.raise_error # pylint: disable=raising-bad-type
@pytest.fixture
def fake_webview():
return FakeWebView()
@webengine_refactoring_xfail
class TestLoadTab:
def test_no_history(self, sess_man, fake_webview):
sess_man._load_tab(fake_webview, {'history': []})
assert fake_webview.loaded_history == []
def test_load_fail(self, sess_man, fake_webview):
fake_webview.raise_error = ValueError
with pytest.raises(sessions.SessionError):
sess_man._load_tab(fake_webview, {'history': []})
@pytest.mark.parametrize('key, val, expected', [
('zoom', 1.23, 1.23),
('scroll-pos', {'x': 23, 'y': 42}, QPoint(23, 42)),
])
@pytest.mark.parametrize('in_main_data', [True, False])
def test_user_data(self, sess_man, fake_webview, key, val, expected,
in_main_data):
item = {'url': 'http://www.example.com/', 'title': 'foo'}
if in_main_data:
# This information got saved in the main data instead of saving it
# per item - make sure the old format can still be read
# https://github.com/qutebrowser/qutebrowser/issues/728
d = {'history': [item], key: val}
else:
item[key] = val
d = {'history': [item]}
sess_man._load_tab(fake_webview, d)
assert len(fake_webview.loaded_history) == 1
assert fake_webview.loaded_history[0].user_data[key] == expected
@pytest.mark.parametrize('original_url', ['http://example.org/', None])
def test_urls(self, sess_man, fake_webview, original_url):
url = 'http://www.example.com/'
item = {'url': url, 'title': 'foo'}
if original_url is None:
expected = QUrl(url)
else:
item['original-url'] = original_url
expected = QUrl(original_url)
d = {'history': [item]}
sess_man._load_tab(fake_webview, d)
assert len(fake_webview.loaded_history) == 1
loaded_item = fake_webview.loaded_history[0]
assert loaded_item.url == QUrl(url)
assert loaded_item.original_url == expected
class TestListSessions:
def test_no_sessions(self, tmp_path):
sess_man = sessions.SessionManager(str(tmp_path))
assert not sess_man.list_sessions()
def test_with_sessions(self, tmp_path):
(tmp_path / 'foo.yml').touch()
(tmp_path / 'bar.yml').touch()
sess_man = sessions.SessionManager(str(tmp_path))
assert sess_man.list_sessions() == ['bar', 'foo']
def test_with_other_files(self, tmp_path):
(tmp_path / 'foo.yml').touch()
(tmp_path / 'bar.html').touch()
sess_man = sessions.SessionManager(str(tmp_path))
assert sess_man.list_sessions() == ['foo']
| 1 | 21,768 | I don't think that works - you can't mark a fixture. | qutebrowser-qutebrowser | py |
@@ -42,6 +42,12 @@ module Bolt
PUPPETFILE_OPTIONS = %w[proxy forge].freeze
+ DEFAULT_CONFIG_PATHS = [
+ Bolt::Util.windows? ? 'C:\\Program Files\\Puppet Labs\\Bolt\\bolt.yaml' : '/etc/puppetlabs/bolt/bolt.yaml',
+ File.expand_path('.puppetlabs/etc/bolt/bolt.yaml', Bolt::Util.windows? ? ENV['USERPROFILE'] : '~'),
+ File.expand_path('.puppetlabs/bolt.yaml', Bolt::Util.windows? ? ENV['USERPROFILE'] : '~')
+ ].freeze
+
def self.default
new(Bolt::Boltdir.new('.'), {})
end | 1 | # frozen_string_literal: true
require 'etc'
require 'logging'
require 'pathname'
require 'bolt/boltdir'
require 'bolt/transport/ssh'
require 'bolt/transport/winrm'
require 'bolt/transport/orch'
require 'bolt/transport/local'
require 'bolt/transport/local_windows'
require 'bolt/transport/docker'
require 'bolt/transport/remote'
require 'bolt/util'
module Bolt
TRANSPORTS = {
ssh: Bolt::Transport::SSH,
winrm: Bolt::Transport::WinRM,
pcp: Bolt::Transport::Orch,
local: Bolt::Util.windows? ? Bolt::Transport::LocalWindows : Bolt::Transport::Local,
docker: Bolt::Transport::Docker,
remote: Bolt::Transport::Remote
}.freeze
class UnknownTransportError < Bolt::Error
def initialize(transport, uri = nil)
msg = uri.nil? ? "Unknown transport #{transport}" : "Unknown transport #{transport} found for #{uri}"
super(msg, 'bolt/unknown-transport')
end
end
class Config
attr_accessor :concurrency, :format, :trace, :log, :puppetdb, :color, :save_rerun,
:transport, :transports, :inventoryfile, :compile_concurrency, :boltdir,
:puppetfile_config, :plugins, :plugin_hooks, :future
attr_writer :modulepath
TRANSPORT_OPTIONS = %i[password run-as sudo-password extensions sudo-executable
private-key tty tmpdir user connect-timeout disconnect-timeout
cacert token-file service-url interpreters file-protocol smb-port realm].freeze
PUPPETFILE_OPTIONS = %w[proxy forge].freeze
def self.default
new(Bolt::Boltdir.new('.'), {})
end
def self.from_boltdir(boltdir, overrides = {})
data = Bolt::Util.read_config_file(nil, [boltdir.config_file], 'config') || {}
new(boltdir, data, overrides)
end
def self.from_file(configfile, overrides = {})
boltdir = Bolt::Boltdir.new(Pathname.new(configfile).expand_path.dirname)
data = Bolt::Util.read_config_file(configfile, [], 'config') || {}
new(boltdir, data, overrides)
end
def initialize(boltdir, config_data, overrides = {})
@logger = Logging.logger[self]
@boltdir = boltdir
@concurrency = 100
@compile_concurrency = Etc.nprocessors
@transport = 'ssh'
@format = 'human'
@puppetdb = {}
@color = true
@save_rerun = true
@puppetfile_config = {}
@plugins = {}
@plugin_hooks = {}
# add an entry for the default console logger
@log = { 'console' => {} }
@transports = {}
TRANSPORTS.each do |key, transport|
@transports[key] = transport.default_options
end
update_from_file(config_data)
apply_overrides(overrides)
validate
end
def overwrite_transport_data(transport, transports)
@transport = transport
@transports = transports
end
def transport_data_get
{ transport: @transport, transports: @transports }
end
def deep_clone
Bolt::Util.deep_clone(self)
end
def normalize_interpreters(interpreters)
Bolt::Util.walk_keys(interpreters) do |key|
key.chars[0] == '.' ? key : '.' + key
end
end
def normalize_log(target)
return target if target == 'console'
target = target[5..-1] if target.start_with?('file:')
if @future
'file:' + File.expand_path(target, @boltdir.path)
else
'file:' + File.expand_path(target)
end
end
def update_logs(logs)
logs.each_pair do |k, v|
log_name = normalize_log(k)
@log[log_name] ||= {}
log = @log[log_name]
next unless v.is_a?(Hash)
if v.key?('level')
log[:level] = v['level'].to_s
end
if v.key?('append')
log[:append] = v['append']
end
end
end
def update_from_file(data)
@future = data['future'] == true
if data['log'].is_a?(Hash)
update_logs(data['log'])
end
# Expand paths relative to the Boltdir. Any settings that came from the
# CLI will already be absolute, so the expand will be skipped.
if data.key?('modulepath')
moduledirs = if data['modulepath'].is_a?(String)
data['modulepath'].split(File::PATH_SEPARATOR)
else
data['modulepath']
end
@modulepath = moduledirs.map do |moduledir|
File.expand_path(moduledir, @boltdir.path)
end
end
@inventoryfile = File.expand_path(data['inventoryfile'], @boltdir.path) if data.key?('inventoryfile')
if data.key?('puppetfile')
@puppetfile_config = data['puppetfile'].select { |k, _| PUPPETFILE_OPTIONS.include?(k) }
end
@hiera_config = File.expand_path(data['hiera-config'], @boltdir.path) if data.key?('hiera-config')
@compile_concurrency = data['compile-concurrency'] if data.key?('compile-concurrency')
@save_rerun = data['save-rerun'] if data.key?('save-rerun')
@plugins = data['plugins'] if data.key?('plugins')
@plugin_hooks = data['plugin_hooks'] if data.key?('plugin_hooks')
%w[concurrency format puppetdb color].each do |key|
send("#{key}=", data[key]) if data.key?(key)
end
update_transports(data)
end
private :update_from_file
def apply_overrides(options)
%i[concurrency transport format trace modulepath inventoryfile color].each do |key|
send("#{key}=", options[key]) if options.key?(key)
end
@save_rerun = options[:'save-rerun'] if options.key?(:'save-rerun')
if options[:debug]
@log['console'][:level] = :debug
end
@compile_concurrency = options[:'compile-concurrency'] if options[:'compile-concurrency']
TRANSPORTS.each_key do |transport|
transport = @transports[transport]
TRANSPORT_OPTIONS.each do |key|
if options[key]
transport[key.to_s] = Bolt::Util.walk_keys(options[key], &:to_s)
end
end
end
if options.key?(:ssl) # this defaults to true so we need to check the presence of the key
@transports[:winrm]['ssl'] = options[:ssl]
end
if options.key?(:'ssl-verify') # this defaults to true so we need to check the presence of the key
@transports[:winrm]['ssl-verify'] = options[:'ssl-verify']
end
if options.key?(:'host-key-check') # this defaults to true so we need to check the presence of the key
@transports[:ssh]['host-key-check'] = options[:'host-key-check']
end
end
def update_from_inventory(data)
update_transports(data)
end
def update_transports(data)
TRANSPORTS.each do |key, impl|
if data[key.to_s]
selected = impl.filter_options(data[key.to_s])
if @future
to_expand = %w[private-key cacert token-file] & selected.keys
to_expand.each do |opt|
selected[opt] = File.expand_path(selected[opt], @boltdir.path) if opt.is_a?(String)
end
end
@transports[key] = Bolt::Util.deep_merge(@transports[key], selected)
end
if @transports[key]['interpreters']
@transports[key]['interpreters'] = normalize_interpreters(@transports[key]['interpreters'])
end
end
@transport = data['transport'] if data.key?('transport')
end
def transport_conf
{ transport: @transport,
transports: @transports }
end
def default_inventoryfile
[@boltdir.inventory_file]
end
def rerunfile
@boltdir.rerunfile
end
def hiera_config
@hiera_config || @boltdir.hiera_config
end
def puppetfile
@boltdir.puppetfile
end
def modulepath
@modulepath || @boltdir.modulepath
end
def validate
@log.each_pair do |name, params|
if params.key?(:level) && !Bolt::Logger.valid_level?(params[:level])
raise Bolt::ValidationError,
"level of log #{name} must be one of: #{Bolt::Logger.levels.join(', ')}; received #{params[:level]}"
end
if params.key?(:append) && params[:append] != true && params[:append] != false
raise Bolt::ValidationError, "append flag of log #{name} must be a Boolean, received #{params[:append]}"
end
end
unless @concurrency.is_a?(Integer) && @concurrency > 0
raise Bolt::ValidationError, 'Concurrency must be a positive integer'
end
unless @compile_concurrency.is_a?(Integer) && @compile_concurrency > 0
raise Bolt::ValidationError, 'Compile concurrency must be a positive integer'
end
compile_limit = 2 * Etc.nprocessors
unless @compile_concurrency < compile_limit
raise Bolt::ValidationError, "Compilation is CPU-intensive, set concurrency less than #{compile_limit}"
end
unless %w[human json].include? @format
raise Bolt::ValidationError, "Unsupported format: '#{@format}'"
end
Bolt::Util.validate_file('hiera-config', @hiera_config) if @hiera_config
unless @transport.nil? || Bolt::TRANSPORTS.include?(@transport.to_sym)
raise UnknownTransportError, @transport
end
TRANSPORTS.each do |transport, impl|
impl.validate(@transports[transport])
end
end
# Check if there is a case-insensitive match to the path
def check_path_case(type, paths)
return if paths.nil?
matches = matching_paths(paths)
if matches.any?
msg = "WARNING: Bolt is case sensitive when specifying a #{type}. Did you mean:\n"
matches.each { |path| msg += " #{path}\n" }
@logger.warn msg
end
end
def matching_paths(paths)
[*paths].map { |p| Dir.glob([p, casefold(p)]) }.flatten.uniq.reject { |p| [*paths].include?(p) }
end
def casefold(path)
path.chars.map do |l|
l =~ /[A-Za-z]/ ? "[#{l.upcase}#{l.downcase}]" : l
end.join
end
end
end
| 1 | 13,501 | We should not include this path. | puppetlabs-bolt | rb |
@@ -52,6 +52,19 @@ class SlackWebhooknotifierTest(ForsetiTestCase):
self.assertEqual(expected_output.strip(), actual_output.strip())
+ def test_dump_slack_output_for_string_returns_string(self):
+ violation_data = 'Test violation data string'
+ with mock.patch.object(
+ slack_webhook.SlackWebhook,
+ '__init__',
+ lambda x: None):
+ slack_notifier = slack_webhook.SlackWebhook()
+ actual_output = slack_notifier._dump_slack_output(violation_data)
+
+ expected_output = '\t' + '`' + str(violation_data) + '`\n'
+
+ self.assertEqual(expected_output.strip(), actual_output.strip())
+
def test_no_url_no_run_notifier(self):
"""Test that no url for Slack notifier will skip running."""
with mock.patch.object(slack_webhook.SlackWebhook, '__init__', lambda x: None): | 1 | # Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# 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.
"""Tests the email scanner summary notifier."""
import json
import unittest.mock as mock
import unittest
from google.cloud.forseti.notifier.notifiers import slack_webhook
from tests.unittest_utils import ForsetiTestCase
class SlackWebhooknotifierTest(ForsetiTestCase):
"""Tests for the slack_webhook_notifier."""
def test_can_compose_slack_message(self):
"""Test that the slack message is built correctly."""
violation_data = """
{
"role": "READER",
"email": "",
"bucket": "test-bucket-world-readable-123",
"domain": "",
"entity": "allUsers"
}
"""
violation = {'violation_data': json.loads(violation_data),
'resource_id': '123',
'rule_name': 'Public buckets (allUsers)',
'rule_index': 0,
'violation_type': 'BUCKET_VIOLATION',
'id': 1, 'resource_type': 'bucket'}
with mock.patch.object(slack_webhook.SlackWebhook, '__init__', lambda x: None):
slack_notifier = slack_webhook.SlackWebhook()
slack_notifier.resource = 'buckets_acl_violations'
actual_output = slack_notifier._compose(violation=violation)
expected_output = "*type*:\t`buckets_acl_violations`\n*details*:\n\t*bucket*:\t\t`test-bucket-world-readable-123`\n\t*domain*:\t\t`n/a`\n\t*email*:\t\t`n/a`\n\t*entity*:\t\t`allUsers`\n\t*role*:\t\t`READER`"
self.assertEqual(expected_output.strip(), actual_output.strip())
def test_no_url_no_run_notifier(self):
"""Test that no url for Slack notifier will skip running."""
with mock.patch.object(slack_webhook.SlackWebhook, '__init__', lambda x: None):
slack_notifier = slack_webhook.SlackWebhook()
slack_notifier.notification_config = {}
slack_notifier._compose = mock.MagicMock()
slack_notifier.run()
slack_notifier._compose.assert_not_called()
if __name__ == '__main__':
unittest.main()
| 1 | 34,992 | Add newline at end of file | forseti-security-forseti-security | py |
@@ -257,6 +257,9 @@ class DBUpgrader {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_EXCLUDE_FILTER + " TEXT DEFAULT ''");
+ db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ + " ADD COLUMN " + PodDBAdapter.KEY_MINIMAL_DURATION_FILTER + " INTEGER DEFAULT -1");
+
// and now auto refresh
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_KEEP_UPDATED + " INTEGER DEFAULT 1"); | 1 | package de.danoeh.antennapod.core.storage;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaMetadataRetriever;
import android.util.Log;
import de.danoeh.antennapod.model.feed.FeedItem;
import static de.danoeh.antennapod.model.feed.FeedPreferences.SPEED_USE_GLOBAL;
class DBUpgrader {
/**
* Upgrades the given database to a new schema version
*/
static void upgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
if (oldVersion <= 1) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS + " ADD COLUMN "
+ PodDBAdapter.KEY_TYPE + " TEXT");
}
if (oldVersion <= 2) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_SIMPLECHAPTERS
+ " ADD COLUMN " + PodDBAdapter.KEY_LINK + " TEXT");
}
if (oldVersion <= 3) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_ITEMS
+ " ADD COLUMN " + PodDBAdapter.KEY_ITEM_IDENTIFIER + " TEXT");
}
if (oldVersion <= 4) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS + " ADD COLUMN "
+ PodDBAdapter.KEY_FEED_IDENTIFIER + " TEXT");
}
if (oldVersion <= 5) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_DOWNLOAD_LOG
+ " ADD COLUMN " + PodDBAdapter.KEY_REASON_DETAILED + " TEXT");
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_DOWNLOAD_LOG
+ " ADD COLUMN " + PodDBAdapter.KEY_DOWNLOADSTATUS_TITLE + " TEXT");
}
if (oldVersion <= 6) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_SIMPLECHAPTERS
+ " ADD COLUMN " + PodDBAdapter.KEY_CHAPTER_TYPE + " INTEGER");
}
if (oldVersion <= 7) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_MEDIA
+ " ADD COLUMN " + PodDBAdapter.KEY_PLAYBACK_COMPLETION_DATE
+ " INTEGER");
}
if (oldVersion <= 8) {
final int KEY_ID_POSITION = 0;
final int KEY_MEDIA_POSITION = 1;
// Add feeditem column to feedmedia table
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_MEDIA
+ " ADD COLUMN " + PodDBAdapter.KEY_FEEDITEM
+ " INTEGER");
Cursor feeditemCursor = db.query(PodDBAdapter.TABLE_NAME_FEED_ITEMS,
new String[]{PodDBAdapter.KEY_ID, PodDBAdapter.KEY_MEDIA}, "? > 0",
new String[]{PodDBAdapter.KEY_MEDIA}, null, null, null);
if (feeditemCursor.moveToFirst()) {
db.beginTransaction();
ContentValues contentValues = new ContentValues();
do {
long mediaId = feeditemCursor.getLong(KEY_MEDIA_POSITION);
contentValues.put(PodDBAdapter.KEY_FEEDITEM, feeditemCursor.getLong(KEY_ID_POSITION));
db.update(PodDBAdapter.TABLE_NAME_FEED_MEDIA, contentValues, PodDBAdapter.KEY_ID + "=?", new String[]{String.valueOf(mediaId)});
contentValues.clear();
} while (feeditemCursor.moveToNext());
db.setTransactionSuccessful();
db.endTransaction();
}
feeditemCursor.close();
}
if (oldVersion <= 9) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_AUTO_DOWNLOAD
+ " INTEGER DEFAULT 1");
}
if (oldVersion <= 10) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN flattr_status"
+ " INTEGER");
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_ITEMS
+ " ADD COLUMN flattr_status"
+ " INTEGER");
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_MEDIA
+ " ADD COLUMN " + PodDBAdapter.KEY_PLAYED_DURATION
+ " INTEGER");
}
if (oldVersion <= 11) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_USERNAME
+ " TEXT");
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_PASSWORD
+ " TEXT");
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_ITEMS
+ " ADD COLUMN image"
+ " INTEGER");
}
if (oldVersion <= 12) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_IS_PAGED + " INTEGER DEFAULT 0");
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_NEXT_PAGE_LINK + " TEXT");
}
if (oldVersion <= 13) {
// remove duplicate rows in "Chapters" table that were created because of a bug.
db.execSQL(String.format("DELETE FROM %s WHERE %s NOT IN " +
"(SELECT MIN(%s) as %s FROM %s GROUP BY %s,%s,%s,%s,%s)",
PodDBAdapter.TABLE_NAME_SIMPLECHAPTERS,
PodDBAdapter.KEY_ID,
PodDBAdapter.KEY_ID,
PodDBAdapter.KEY_ID,
PodDBAdapter.TABLE_NAME_SIMPLECHAPTERS,
PodDBAdapter.KEY_TITLE,
PodDBAdapter.KEY_START,
PodDBAdapter.KEY_FEEDITEM,
PodDBAdapter.KEY_LINK,
PodDBAdapter.KEY_CHAPTER_TYPE));
}
if (oldVersion <= 14) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_ITEMS
+ " ADD COLUMN " + PodDBAdapter.KEY_AUTO_DOWNLOAD + " INTEGER");
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEED_ITEMS
+ " SET " + PodDBAdapter.KEY_AUTO_DOWNLOAD + " = "
+ "(SELECT " + PodDBAdapter.KEY_AUTO_DOWNLOAD
+ " FROM " + PodDBAdapter.TABLE_NAME_FEEDS
+ " WHERE " + PodDBAdapter.TABLE_NAME_FEEDS + "." + PodDBAdapter.KEY_ID
+ " = " + PodDBAdapter.TABLE_NAME_FEED_ITEMS + "." + PodDBAdapter.KEY_FEED + ")");
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_HIDE + " TEXT");
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_LAST_UPDATE_FAILED + " INTEGER DEFAULT 0");
// create indexes
db.execSQL(PodDBAdapter.CREATE_INDEX_FEEDITEMS_FEED);
db.execSQL(PodDBAdapter.CREATE_INDEX_FEEDMEDIA_FEEDITEM);
db.execSQL(PodDBAdapter.CREATE_INDEX_QUEUE_FEEDITEM);
db.execSQL(PodDBAdapter.CREATE_INDEX_SIMPLECHAPTERS_FEEDITEM);
}
if (oldVersion <= 15) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_MEDIA
+ " ADD COLUMN " + PodDBAdapter.KEY_HAS_EMBEDDED_PICTURE + " INTEGER DEFAULT -1");
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEED_MEDIA
+ " SET " + PodDBAdapter.KEY_HAS_EMBEDDED_PICTURE + "=0"
+ " WHERE " + PodDBAdapter.KEY_DOWNLOADED + "=0");
Cursor c = db.rawQuery("SELECT " + PodDBAdapter.KEY_FILE_URL
+ " FROM " + PodDBAdapter.TABLE_NAME_FEED_MEDIA
+ " WHERE " + PodDBAdapter.KEY_DOWNLOADED + "=1 "
+ " AND " + PodDBAdapter.KEY_HAS_EMBEDDED_PICTURE + "=-1", null);
if (c.moveToFirst()) {
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
do {
String fileUrl = c.getString(0);
try {
mmr.setDataSource(fileUrl);
byte[] image = mmr.getEmbeddedPicture();
if (image != null) {
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEED_MEDIA
+ " SET " + PodDBAdapter.KEY_HAS_EMBEDDED_PICTURE + "=1"
+ " WHERE " + PodDBAdapter.KEY_FILE_URL + "='" + fileUrl + "'");
} else {
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEED_MEDIA
+ " SET " + PodDBAdapter.KEY_HAS_EMBEDDED_PICTURE + "=0"
+ " WHERE " + PodDBAdapter.KEY_FILE_URL + "='" + fileUrl + "'");
}
} catch (Exception e) {
e.printStackTrace();
}
} while (c.moveToNext());
}
c.close();
}
if (oldVersion <= 16) {
String selectNew = "SELECT " + PodDBAdapter.TABLE_NAME_FEED_ITEMS + "." + PodDBAdapter.KEY_ID
+ " FROM " + PodDBAdapter.TABLE_NAME_FEED_ITEMS
+ " INNER JOIN " + PodDBAdapter.TABLE_NAME_FEED_MEDIA + " ON "
+ PodDBAdapter.TABLE_NAME_FEED_ITEMS + "." + PodDBAdapter.KEY_ID + "="
+ PodDBAdapter.TABLE_NAME_FEED_MEDIA + "." + PodDBAdapter.KEY_FEEDITEM
+ " LEFT OUTER JOIN " + PodDBAdapter.TABLE_NAME_QUEUE + " ON "
+ PodDBAdapter.TABLE_NAME_FEED_ITEMS + "." + PodDBAdapter.KEY_ID + "="
+ PodDBAdapter.TABLE_NAME_QUEUE + "." + PodDBAdapter.KEY_FEEDITEM
+ " WHERE "
+ PodDBAdapter.TABLE_NAME_FEED_ITEMS + "." + PodDBAdapter.KEY_READ + " = 0 AND " // unplayed
+ PodDBAdapter.TABLE_NAME_FEED_MEDIA + "." + PodDBAdapter.KEY_DOWNLOADED + " = 0 AND " // undownloaded
+ PodDBAdapter.TABLE_NAME_FEED_MEDIA + "." + PodDBAdapter.KEY_POSITION + " = 0 AND " // not partially played
+ PodDBAdapter.TABLE_NAME_QUEUE + "." + PodDBAdapter.KEY_ID + " IS NULL"; // not in queue
String sql = "UPDATE " + PodDBAdapter.TABLE_NAME_FEED_ITEMS
+ " SET " + PodDBAdapter.KEY_READ + "=" + FeedItem.NEW
+ " WHERE " + PodDBAdapter.KEY_ID + " IN (" + selectNew + ")";
Log.d("Migration", "SQL: " + sql);
db.execSQL(sql);
}
if (oldVersion <= 17) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_AUTO_DELETE_ACTION + " INTEGER DEFAULT 0");
}
if (oldVersion < 1030005) {
db.execSQL("UPDATE FeedItems SET auto_download=0 WHERE " +
"(read=1 OR id IN (SELECT feeditem FROM FeedMedia WHERE position>0 OR downloaded=1)) " +
"AND id NOT IN (SELECT feeditem FROM Queue)");
}
if (oldVersion < 1040001) {
db.execSQL(PodDBAdapter.CREATE_TABLE_FAVORITES);
}
if (oldVersion < 1040002) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_MEDIA
+ " ADD COLUMN " + PodDBAdapter.KEY_LAST_PLAYED_TIME + " INTEGER DEFAULT 0");
}
if (oldVersion < 1040013) {
db.execSQL(PodDBAdapter.CREATE_INDEX_FEEDITEMS_PUBDATE);
db.execSQL(PodDBAdapter.CREATE_INDEX_FEEDITEMS_READ);
}
if (oldVersion < 1050003) {
// Migrates feed list filter data
db.beginTransaction();
// Change to intermediate values to avoid overwriting in the following find/replace
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEEDS + "\n" +
"SET " + PodDBAdapter.KEY_HIDE + " = replace(" + PodDBAdapter.KEY_HIDE + ", 'unplayed', 'noplay')");
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEEDS + "\n" +
"SET " + PodDBAdapter.KEY_HIDE + " = replace(" + PodDBAdapter.KEY_HIDE + ", 'not_queued', 'noqueue')");
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEEDS + "\n" +
"SET " + PodDBAdapter.KEY_HIDE + " = replace(" + PodDBAdapter.KEY_HIDE + ", 'not_downloaded', 'nodl')");
// Replace played, queued, and downloaded with their opposites
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEEDS + "\n" +
"SET " + PodDBAdapter.KEY_HIDE + " = replace(" + PodDBAdapter.KEY_HIDE + ", 'played', 'unplayed')");
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEEDS + "\n" +
"SET " + PodDBAdapter.KEY_HIDE + " = replace(" + PodDBAdapter.KEY_HIDE + ", 'queued', 'not_queued')");
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEEDS + "\n" +
"SET " + PodDBAdapter.KEY_HIDE + " = replace(" + PodDBAdapter.KEY_HIDE + ", 'downloaded', 'not_downloaded')");
// Now replace intermediates for unplayed, not queued, etc. with their opposites
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEEDS + "\n" +
"SET " + PodDBAdapter.KEY_HIDE + " = replace(" + PodDBAdapter.KEY_HIDE + ", 'noplay', 'played')");
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEEDS + "\n" +
"SET " + PodDBAdapter.KEY_HIDE + " = replace(" + PodDBAdapter.KEY_HIDE + ", 'noqueue', 'queued')");
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEEDS + "\n" +
"SET " + PodDBAdapter.KEY_HIDE + " = replace(" + PodDBAdapter.KEY_HIDE + ", 'nodl', 'downloaded')");
// Paused doesn't have an opposite, so unplayed is the next best option
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEEDS + "\n" +
"SET " + PodDBAdapter.KEY_HIDE + " = replace(" + PodDBAdapter.KEY_HIDE + ", 'paused', 'unplayed')");
db.setTransactionSuccessful();
db.endTransaction();
// and now get ready for autodownload filters
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_INCLUDE_FILTER + " TEXT DEFAULT ''");
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_EXCLUDE_FILTER + " TEXT DEFAULT ''");
// and now auto refresh
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_KEEP_UPDATED + " INTEGER DEFAULT 1");
}
if (oldVersion < 1050004) {
// prevent old timestamps to be misinterpreted as ETags
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " SET " + PodDBAdapter.KEY_LASTUPDATE + "=NULL");
}
if (oldVersion < 1060200) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_CUSTOM_TITLE + " TEXT");
}
if (oldVersion < 1060596) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_IMAGE_URL + " TEXT");
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_ITEMS
+ " ADD COLUMN " + PodDBAdapter.KEY_IMAGE_URL + " TEXT");
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEED_ITEMS + " SET " + PodDBAdapter.KEY_IMAGE_URL + " = ("
+ " SELECT " + PodDBAdapter.KEY_DOWNLOAD_URL
+ " FROM " + PodDBAdapter.TABLE_NAME_FEED_IMAGES
+ " WHERE " + PodDBAdapter.TABLE_NAME_FEED_IMAGES + "." + PodDBAdapter.KEY_ID
+ " = " + PodDBAdapter.TABLE_NAME_FEED_ITEMS + ".image)");
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEEDS + " SET " + PodDBAdapter.KEY_IMAGE_URL + " = ("
+ " SELECT " + PodDBAdapter.KEY_DOWNLOAD_URL
+ " FROM " + PodDBAdapter.TABLE_NAME_FEED_IMAGES
+ " WHERE " + PodDBAdapter.TABLE_NAME_FEED_IMAGES + "." + PodDBAdapter.KEY_ID
+ " = " + PodDBAdapter.TABLE_NAME_FEEDS + ".image)");
db.execSQL("DROP TABLE " + PodDBAdapter.TABLE_NAME_FEED_IMAGES);
}
if (oldVersion < 1070400) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_FEED_PLAYBACK_SPEED + " REAL DEFAULT " + SPEED_USE_GLOBAL);
}
if (oldVersion < 1070401) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_SORT_ORDER + " TEXT");
}
if (oldVersion < 1090000) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_FEED_VOLUME_ADAPTION + " INTEGER DEFAULT 0");
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_SIMPLECHAPTERS
+ " ADD COLUMN " + PodDBAdapter.KEY_IMAGE_URL + " TEXT DEFAULT NULL");
}
if (oldVersion < 1090001) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_FEED_SKIP_INTRO + " INTEGER DEFAULT 0;");
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_FEED_SKIP_ENDING + " INTEGER DEFAULT 0;");
}
if (oldVersion < 2020000) {
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_EPISODE_NOTIFICATION + " INTEGER DEFAULT 0;");
}
if (oldVersion < 2030000) {
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEED_ITEMS
+ " SET " + PodDBAdapter.KEY_DESCRIPTION + " = content_encoded, content_encoded = NULL "
+ "WHERE length(" + PodDBAdapter.KEY_DESCRIPTION + ") < length(content_encoded)");
db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEED_ITEMS + " SET content_encoded = NULL");
db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+ " ADD COLUMN " + PodDBAdapter.KEY_FEED_TAGS + " TEXT;");
}
}
}
| 1 | 20,823 | This should be done when updating to the next release (2.5). You currently only perform the upgrade when users go from 1.4 to 1.5, so it will lead to crashes for existing users. | AntennaPod-AntennaPod | java |
@@ -320,6 +320,9 @@ const (
// HiveFeatureGatesEnabledEnvVar is the the environment variable specifying the comma separated list of
// feature gates that are enabled.
HiveFeatureGatesEnabledEnvVar = "HIVE_FEATURE_GATES_ENABLED"
+
+ // CentralMachineManagementAnnotation
+ CentralMachineManagementAnnotation = "hive.openshift.io/clusterName"
)
// GetMergedPullSecretName returns name for merged pull secret name per cluster deployment | 1 | package constants
import (
apihelpers "github.com/openshift/hive/apis/helpers"
hivev1 "github.com/openshift/hive/apis/hive/v1"
)
const (
PlatformAWS = "aws"
PlatformAzure = "azure"
PlatformBaremetal = "baremetal"
PlatformAgentBaremetal = "agent-baremetal"
PlatformGCP = "gcp"
PlatformOpenStack = "openstack"
PlatformUnknown = "unknown"
PlatformVSphere = "vsphere"
mergedPullSecretSuffix = "merged-pull-secret"
// VeleroBackupEnvVar is the name of the environment variable used to tell the controller manager to enable velero backup integration.
VeleroBackupEnvVar = "HIVE_VELERO_BACKUP"
// VeleroNamespaceEnvVar is the name of the environment variable used to tell the controller manager which namespace velero backup objects should be created in.
VeleroNamespaceEnvVar = "HIVE_VELERO_NAMESPACE"
// DeprovisionsDisabledEnvVar is the name of the environment variable used to tell the controller manager to skip
// processing of any ClusterDeprovisions.
DeprovisionsDisabledEnvVar = "DEPROVISIONS_DISABLED"
// MinBackupPeriodSecondsEnvVar is the name of the environment variable used to tell the controller manager the minimum period of time between backups.
MinBackupPeriodSecondsEnvVar = "HIVE_MIN_BACKUP_PERIOD_SECONDS"
// InstallJobLabel is the label used for artifacts specific to Hive cluster installations.
InstallJobLabel = "hive.openshift.io/install"
// UninstallJobLabel is the label used for artifacts specific to Hive cluster deprovision.
UninstallJobLabel = "hive.openshift.io/uninstall"
// MachinePoolNameLabel is the label that is used to identify the MachinePool which owns a particular resource.
MachinePoolNameLabel = "hive.openshift.io/machine-pool-name"
// ClusterDeploymentNameLabel is the label that is used to identify a relationship to a given cluster deployment object.
ClusterDeploymentNameLabel = "hive.openshift.io/cluster-deployment-name"
// ClusterDeprovisionNameLabel is the label that is used to identify a relationship to a given cluster deprovision object.
ClusterDeprovisionNameLabel = "hive.openshift.io/cluster-deprovision-name"
// ClusterProvisionNameLabel is the label that is used to identify a relationship to a given cluster provision object.
ClusterProvisionNameLabel = "hive.openshift.io/cluster-provision-name"
// ClusterPoolNameLabel is the label that is used to signal that a namespace was created to house a
// ClusterDeployment created for a ClusterPool. The label is used to reap namespaces after the ClusterDeployment
// has been deleted.
ClusterPoolNameLabel = "hive.openshift.io/cluster-pool-name"
// SyncSetNameLabel is the label that is used to identify a relationship to a given syncset object.
SyncSetNameLabel = "hive.openshift.io/syncset-name"
// SelectorSyncSetNameLabel is the label that is used to identify a relationship to a given selector syncset object.
SelectorSyncSetNameLabel = "hive.openshift.io/selector-syncset-name"
// PVCTypeLabel is the label that is used to identify what a PVC is being used for.
PVCTypeLabel = "hive.openshift.io/pvc-type"
// PVCTypeInstallLogs is used as a value of PVCTypeLabel that says the PVC specifically stores installer logs.
PVCTypeInstallLogs = "installlogs"
// JobTypeLabel is the label that is used to identify what a Job is being used for.
JobTypeLabel = "hive.openshift.io/job-type"
// JobTypeImageSet is used as a value of JobTypeLabel that says the Job is specifically running to determine which imageset to use.
JobTypeImageSet = "imageset"
// JobTypeDeprovision is used as a value of JobTypeLabel that says the Job is specifically running the deprovisioner.
JobTypeDeprovision = "deprovision"
// JobTypeProvision is used as a value of JobTypeLabel that says the Job is specifically running the provisioner.
JobTypeProvision = "provision"
// DNSZoneTypeLabel is the label that is used to identify what a DNSZone is being used for.
DNSZoneTypeLabel = "hive.openshift.io/dnszone-type"
// DNSZoneTypeChild is used as a value of DNSZoneTypeLabel that says the DNSZone is specifically used as the forwarding zone for the target cluster.
DNSZoneTypeChild = "child"
// SecretTypeLabel is the label that is used to identify what a Secret is being used for.
SecretTypeLabel = "hive.openshift.io/secret-type"
// SecretTypeMergedPullSecret is used as a value of SecretTypeLabel that says the secret is specifically used for storing a pull secret.
SecretTypeMergedPullSecret = "merged-pull-secret"
// SecretTypeKubeConfig is used as a value of SecretTypeLabel that says the secret is specifically used for storing a kubeconfig.
SecretTypeKubeConfig = "kubeconfig"
// SecretTypeKubeAdminCreds is used as a value of SecretTypeLabel that says the secret is specifically used for storing kubeadmin credentials.
SecretTypeKubeAdminCreds = "kubeadmincreds"
// SyncSetTypeLabel is the label that is used to identify what a SyncSet is being used for.
SyncSetTypeLabel = "hive.openshift.io/syncset-type"
// SyncSetTypeControlPlaneCerts is used as a value of SyncSetTypeLabel that says the syncset is specifically used to distribute control plane certificates.
SyncSetTypeControlPlaneCerts = "controlplanecerts"
// SyncSetTypeRemoteIngress is used as a value of SyncSetTypeLabel that says the syncset is specifically used to distribute remote ingress information.
SyncSetTypeRemoteIngress = "remoteingress"
// SyncSetTypeIdentityProvider is used as a value of SyncSetTypeLabel that says the syncset is specifically used to distribute identity provider information.
SyncSetTypeIdentityProvider = "identityprovider"
// GlobalPullSecret is the environment variable for controllers to get the global pull secret
GlobalPullSecret = "GLOBAL_PULL_SECRET"
// DefaultHiveNamespace is the default namespace where core hive components will run. It is used if the environment variable is not defined.
DefaultHiveNamespace = "hive"
// HiveNamespaceEnvVar is the environment variable for the namespace where the core hive-controllers and hiveadmission will run.
// This is set on the deployments by the hive-operator which deploys them, based on the targetNamespace defined in HiveConfig.
// The default is defined above.
HiveNamespaceEnvVar = "HIVE_NS"
// CheckpointName is the name of the object in each namespace in which the namespace's backup information is stored.
CheckpointName = "hive"
// SyncsetPauseAnnotation is a annotation used by clusterDeployment, if it's true, then we will disable syncing to a specific cluster
SyncsetPauseAnnotation = "hive.openshift.io/syncset-pause"
// HiveManagedLabel is a label added to any resources we sync to the remote cluster to help identify that they are
// managed by Hive, and any manual changes may be undone the next time the resource is reconciled.
HiveManagedLabel = "hive.openshift.io/managed"
// DisableInstallLogPasswordRedactionAnnotation is an annotation used on ClusterDeployments to disable the installmanager
// functionality which refuses to print output if it appears to contain a password or sensitive info. This can be
// useful in scenarios where debugging is needed and important info is being redacted. Set to "true".
DisableInstallLogPasswordRedactionAnnotation = "hive.openshift.io/disable-install-log-password-redaction"
// PauseOnInstallFailureAnnotation is an annotation used on ClusterDeployments to trigger a sleep after an install
// failure for the specified duration. This will keep the install pod running and allow a user to rsh in for debug
// purposes. Examples: "1h", "20m".
PauseOnInstallFailureAnnotation = "hive.openshift.io/pause-on-install-failure"
// WaitForInstallCompleteExecutionsAnnotation is an annotation used on ClusterDeployments to set additional waits
// for the cluster provision to complete by running `openshift-install wait-for install-complete` command.
WaitForInstallCompleteExecutionsAnnotation = "hive.openshift.io/wait-for-install-complete-executions"
// ProtectedDeleteAnnotation is an annotation used on ClusterDeployments to indicate that the ClusterDeployment
// cannot be deleted. The annotation must be removed in order to delete the ClusterDeployment.
ProtectedDeleteAnnotation = "hive.openshift.io/protected-delete"
// ProtectedDeleteEnvVar is the name of the environment variable used to tell the controller manager whether
// protected delete is enabled.
ProtectedDeleteEnvVar = "PROTECTED_DELETE"
// RelocateAnnotation is an annotation used on ClusterDeployments and DNSZones to indicate that the resource
// is involved in a relocation between Hive instances.
// The value of the annotation has the format "{ClusterRelocate}/{Status}", where
// {ClusterRelocate} is the name of the ClusterRelocate that is driving the relocation and
// {Status} is the status of the relocate. The status is outgoing, completed, or incoming.
// An outgoing status indicates that the resource is on the source side of an in-progress relocate.
// A completed status indicates that the resource is on the source side of a completed relocate.
// An incoming status indicates that the resource is on the destination side of an in-progress relocate.
RelocateAnnotation = "hive.openshift.io/relocate"
// ManagedDomainsFileEnvVar if present, points to a simple text
// file that includes a valid managed domain per line. Cluster deployments
// requesting that their domains be managed must have a base domain
// that is a direct child of one of the valid domains.
ManagedDomainsFileEnvVar = "MANAGED_DOMAINS_FILE"
// ManagedDomainsVolumeName is the name of the volume that will point
// to the configmap containing the managed domain configuration.
ManagedDomainsVolumeName = "managed-domains"
// GCPCredentialsName is the name of the GCP credentials file or secret key.
GCPCredentialsName = "osServiceAccount.json"
// AzureCredentialsName is the name of the Azure credentials file or secret key.
AzureCredentialsName = "osServicePrincipal.json"
// AzureCredentialsEnvVar is the name of the environment variable pointing to the location
// where Azure credentials can be found.
AzureCredentialsEnvVar = "AZURE_AUTH_LOCATION"
// OpenStackCredentialsName is the name of the OpenStack credentials file.
OpenStackCredentialsName = "clouds.yaml"
// SSHPrivKeyPathEnvVar is the environment variable Hive will set for the installmanager pod to point to the
// path where we mount in the SSH key to be configured on the cluster hosts.
SSHPrivKeyPathEnvVar = "SSH_PRIV_KEY_PATH"
// LibvirtSSHPrivKeyPathEnvVar is the environment variable Hive will set for the installmanager pod to point to the
// path where we mount in the SSH key for connecting to the bare metal libvirt provisioning host.
LibvirtSSHPrivKeyPathEnvVar = "LIBVIRT_SSH_PRIV_KEY_PATH"
// FakeClusterInstallEnvVar is the environment variable Hive will set for the installmanager pod to request
// a fake install.
FakeClusterInstallEnvVar = "FAKE_INSTALL"
// ControlPlaneCertificateSuffix is the suffix used when naming objects having to do control plane certificates.
ControlPlaneCertificateSuffix = "cp-certs"
// ClusterIngressSuffix is the suffix used when naming objects having to do with cluster ingress.
ClusterIngressSuffix = "clusteringress"
// IdentityProviderSuffix is the suffix used when naming objects having to do with identity provider
IdentityProviderSuffix = "idp"
// KubeconfigSecretKey is the key used inside of a secret containing a kubeconfig
KubeconfigSecretKey = "kubeconfig"
// UsernameSecretKey is a key used to store a username inside of a secret containing username / password credentials
UsernameSecretKey = "username"
// PasswordSecretKey is a key used to store a password inside of a secret containing username / password credentials
PasswordSecretKey = "password"
// AWSRoute53Region is the region to use for route53 operations.
AWSRoute53Region = "us-east-1"
// AWSChinaRoute53Region is the region to use for AWS China route53 operations.
AWSChinaRoute53Region = "cn-northwest-1"
// AWSChinaRegionPrefix is the prefix for regions in AWS China.
AWSChinaRegionPrefix = "cn-"
// SSHPrivateKeySecretKey is the key we use in a Kubernetes Secret containing an SSH private key.
SSHPrivateKeySecretKey = "ssh-privatekey"
// RawKubeconfigSecretKey is the key we use in a Kubernetes Secret containing the raw (unmodified) form of
// an admin kubeconfig. (before Hive injects things such as additional CAs)
RawKubeconfigSecretKey = "raw-kubeconfig"
// AWSAccessKeyIDSecretKey is the key we use in a Kubernetes Secret containing AWS credentials for the access key ID.
AWSAccessKeyIDSecretKey = "aws_access_key_id"
// AWSSecretAccessKeySecretKey is the key we use in a Kubernetes Secret containing AWS credentials for the access key ID.
AWSSecretAccessKeySecretKey = "aws_secret_access_key"
// TLSCrtSecretKey is the key we use in a Kubernetes Secret containing a TLS certificate.
TLSCrtSecretKey = "tls.crt"
// TLSKeySecretKey is the key we use in a Kubernetes Secret containing a TLS certificate key.
TLSKeySecretKey = "tls.key"
// VSphereUsernameEnvVar is the environent variable specifying the vSphere username.
VSphereUsernameEnvVar = "GOVC_USERNAME"
// VSpherePasswordEnvVar is the environment variable specifying the vSphere password.
VSpherePasswordEnvVar = "GOVC_PASSWORD"
// VSphereVCenterEnvVar is the environment variable specifying the vSphere vCenter host.
VSphereVCenterEnvVar = "GOVC_HOST"
// VSphereTLSCACertsEnvVar is the environment variable containing : delimited paths to vSphere CA certificates.
VSphereTLSCACertsEnvVar = "GOVC_TLS_CA_CERTS"
// VSphereNetworkEnvVar is the environment variable specifying the vSphere network.
VSphereNetworkEnvVar = "GOVC_NETWORK"
// VSphereDataCenterEnvVar is the environment variable specifying the vSphere datacenter.
VSphereDataCenterEnvVar = "GOVC_DATACENTER"
// VSphereDataStoreEnvVar is the environment variable specifying the vSphere default datastore.
VSphereDataStoreEnvVar = "GOVC_DATASTORE"
// VersionMajorLabel is a label applied to ClusterDeployments to show the version of the cluster
// in the form "[MAJOR]".
VersionMajorLabel = "hive.openshift.io/version-major"
// VersionMajorMinorLabel is a label applied to ClusterDeployments to show the version of the cluster
// in the form "[MAJOR].[MINOR]".
VersionMajorMinorLabel = "hive.openshift.io/version-major-minor"
// VersionMajorMinorPatchLabel is a label applied to ClusterDeployments to show the version of the cluster
// in the form "[MAJOR].[MINOR].[PATCH]".
VersionMajorMinorPatchLabel = "hive.openshift.io/version-major-minor-patch"
// OvirtCredentialsName is the name of the oVirt credentials file.
OvirtCredentialsName = "ovirt-config.yaml"
// OvirtConfigEnvVar is the environment variable specifying the oVirt config path
OvirtConfigEnvVar = "OVIRT_CONFIG"
// AWSCredsMount is the location where the AWS credentials secret is mounted for uninstall pods.
AWSCredsMount = "/etc/aws-creds"
// InstallLogsUploadProviderEnvVar is used to specify which object store provider is being used.
InstallLogsUploadProviderEnvVar = "HIVE_INSTALL_LOGS_UPLOAD_PROVIDER"
// InstallLogsUploadProviderAWS is used to specify that AWS is the cloud provider to upload logs to.
InstallLogsUploadProviderAWS = "aws"
// InstallLogsCredentialsSecretRefEnvVar is the environment variable specifying what secret to use for storing logs.
InstallLogsCredentialsSecretRefEnvVar = "HIVE_INSTALL_LOGS_CREDENTIALS_SECRET"
// InstallLogsAWSRegionEnvVar is the environment variable specifying the region to use with S3
InstallLogsAWSRegionEnvVar = "HIVE_INSTALL_LOGS_AWS_REGION"
// InstallLogsAWSServiceEndpointEnvVar is the environment variable specifying the S3 endpoint to use.
InstallLogsAWSServiceEndpointEnvVar = "HIVE_INSTALL_LOGS_AWS_S3_URL"
// InstallLogsAWSS3BucketEnvVar is the environment variable specifying the S3 bucket to use.
InstallLogsAWSS3BucketEnvVar = "HIVE_INSTALL_LOGS_AWS_S3_BUCKET"
// HiveFakeClusterAnnotation can be set to true on a cluster deployment to create a fake cluster that never
// provisions resources, and all communication with the cluster will be faked.
HiveFakeClusterAnnotation = "hive.openshift.io/fake-cluster"
// ReconcileIDLen is the length of the random strings we generate for contextual loggers in controller
// Reconcile functions.
ReconcileIDLen = 8
// SyncSetMetricsGroupAnnotation can be applied to non-selector SyncSets to make them part of a
// group for which first applied metrics can be reported
SyncSetMetricsGroupAnnotation = "hive.openshift.io/syncset-metrics-group"
// ClusterClaimRemoveClusterAnnotation is used by the cluster claim controller to mark that the cluster
// that are previously claimed is no longer required and therefore should be removed/deprovisioned and removed
// from the pool.
ClusterClaimRemoveClusterAnnotation = "hive.openshift.io/remove-claimed-cluster-from-pool"
// HiveFeatureGatesEnabledEnvVar is the the environment variable specifying the comma separated list of
// feature gates that are enabled.
HiveFeatureGatesEnabledEnvVar = "HIVE_FEATURE_GATES_ENABLED"
)
// GetMergedPullSecretName returns name for merged pull secret name per cluster deployment
func GetMergedPullSecretName(cd *hivev1.ClusterDeployment) string {
return apihelpers.GetResourceName(cd.Name, mergedPullSecretSuffix)
}
| 1 | 16,946 | suggest hive.openshift.io/cluster-machine-management or something to make it more obvious what it is. | openshift-hive | go |
@@ -45,7 +45,7 @@ using Nethermind.JsonRpc.Modules.Eth.FeeHistory;
namespace Nethermind.Init.Steps
{
- [RunnerStepDependencies(typeof(InitializeNetwork), typeof(SetupKeyStore), typeof(InitializeBlockchain), typeof(InitializePlugins))]
+ [RunnerStepDependencies(typeof(InitializeNetwork), typeof(SetupKeyStore), typeof(InitializeBlockchain), typeof(InitializePlugins), typeof(ReviewBlockTree))]
public class RegisterRpcModules : IStep
{
private readonly INethermindApi _api; | 1 | // Copyright (c) 2021 Demerzel Solutions Limited
// This file is part of the Nethermind library.
//
// The Nethermind library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The Nethermind library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the Nethermind. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Nethermind.Api;
using Nethermind.Api.Extensions;
using Nethermind.Consensus;
using Nethermind.Core;
using Nethermind.Init.Steps.Migrations;
using Nethermind.JsonRpc;
using Nethermind.JsonRpc.Modules;
using Nethermind.JsonRpc.Modules.Admin;
using Nethermind.JsonRpc.Modules.DebugModule;
using Nethermind.JsonRpc.Modules.Eth;
using Nethermind.JsonRpc.Modules.Eth.GasPrice;
using Nethermind.JsonRpc.Modules.Evm;
using Nethermind.JsonRpc.Modules.Net;
using Nethermind.JsonRpc.Modules.Parity;
using Nethermind.JsonRpc.Modules.Personal;
using Nethermind.JsonRpc.Modules.Proof;
using Nethermind.JsonRpc.Modules.Subscribe;
using Nethermind.JsonRpc.Modules.Trace;
using Nethermind.JsonRpc.Modules.TxPool;
using Nethermind.JsonRpc.Modules.Web3;
using Nethermind.JsonRpc.Modules.Witness;
using Nethermind.Logging;
using Nethermind.Network.Config;
using Nethermind.JsonRpc.Modules.Eth.FeeHistory;
namespace Nethermind.Init.Steps
{
[RunnerStepDependencies(typeof(InitializeNetwork), typeof(SetupKeyStore), typeof(InitializeBlockchain), typeof(InitializePlugins))]
public class RegisterRpcModules : IStep
{
private readonly INethermindApi _api;
public RegisterRpcModules(INethermindApi api)
{
_api = api;
}
public virtual async Task Execute(CancellationToken cancellationToken)
{
if (_api.BlockTree == null) throw new StepDependencyException(nameof(_api.BlockTree));
if (_api.ReceiptFinder == null) throw new StepDependencyException(nameof(_api.ReceiptFinder));
if (_api.BloomStorage == null) throw new StepDependencyException(nameof(_api.BloomStorage));
if (_api.LogManager == null) throw new StepDependencyException(nameof(_api.LogManager));
IJsonRpcConfig jsonRpcConfig = _api.Config<IJsonRpcConfig>();
if (!jsonRpcConfig.Enabled)
{
return;
}
if (_api.RpcModuleProvider == null) throw new StepDependencyException(nameof(_api.RpcModuleProvider));
if (_api.FileSystem == null) throw new StepDependencyException(nameof(_api.FileSystem));
if (_api.TxPool == null) throw new StepDependencyException(nameof(_api.TxPool));
if (_api.Wallet == null) throw new StepDependencyException(nameof(_api.Wallet));
if (_api.SpecProvider == null) throw new StepDependencyException(nameof(_api.SpecProvider));
if (_api.TxSender == null) throw new StepDependencyException(nameof(_api.TxSender));
if (_api.StateReader == null) throw new StepDependencyException(nameof(_api.StateReader));
if (_api.PeerManager == null) throw new StepDependencyException(nameof(_api.PeerManager));
if (jsonRpcConfig.Enabled)
{
_api.RpcModuleProvider = new RpcModuleProvider(_api.FileSystem, jsonRpcConfig, _api.LogManager);
}
else
{
_api.RpcModuleProvider ??= NullModuleProvider.Instance;
}
// the following line needs to be called in order to make sure that the CLI library is referenced from runner and built alongside
ILogger logger = _api.LogManager.GetClassLogger();
IInitConfig initConfig = _api.Config<IInitConfig>();
IJsonRpcConfig rpcConfig = _api.Config<IJsonRpcConfig>();
INetworkConfig networkConfig = _api.Config<INetworkConfig>();
// lets add threads to support parallel eth_getLogs
ThreadPool.GetMinThreads(out int workerThreads, out int completionPortThreads);
ThreadPool.SetMinThreads(workerThreads + Environment.ProcessorCount, completionPortThreads + Environment.ProcessorCount);
EthModuleFactory ethModuleFactory = new(
_api.TxPool,
_api.TxSender,
_api.Wallet,
_api.BlockTree,
rpcConfig,
_api.LogManager,
_api.StateReader,
_api,
_api.SpecProvider,
_api.ReceiptStorage,
_api.GasPriceOracle,
_api.EthSyncingInfo);
_api.RpcModuleProvider.RegisterBounded(ethModuleFactory, rpcConfig.EthModuleConcurrentInstances ?? Environment.ProcessorCount, rpcConfig.Timeout);
if (_api.DbProvider == null) throw new StepDependencyException(nameof(_api.DbProvider));
if (_api.BlockPreprocessor == null) throw new StepDependencyException(nameof(_api.BlockPreprocessor));
if (_api.BlockValidator == null) throw new StepDependencyException(nameof(_api.BlockValidator));
if (_api.RewardCalculatorSource == null) throw new StepDependencyException(nameof(_api.RewardCalculatorSource));
ProofModuleFactory proofModuleFactory = new(_api.DbProvider, _api.BlockTree, _api.ReadOnlyTrieStore, _api.BlockPreprocessor, _api.ReceiptFinder, _api.SpecProvider, _api.LogManager);
_api.RpcModuleProvider.RegisterBounded(proofModuleFactory, 2, rpcConfig.Timeout);
DebugModuleFactory debugModuleFactory = new(
_api.DbProvider,
_api.BlockTree,
rpcConfig,
_api.BlockValidator,
_api.BlockPreprocessor,
_api.RewardCalculatorSource,
_api.ReceiptStorage,
new ReceiptMigration(_api),
_api.ReadOnlyTrieStore,
_api.ConfigProvider,
_api.SpecProvider,
_api.LogManager);
_api.RpcModuleProvider.RegisterBoundedByCpuCount(debugModuleFactory, rpcConfig.Timeout);
TraceModuleFactory traceModuleFactory = new(
_api.DbProvider,
_api.BlockTree,
_api.ReadOnlyTrieStore,
rpcConfig,
_api.BlockPreprocessor,
_api.RewardCalculatorSource,
_api.ReceiptStorage,
_api.SpecProvider,
_api.LogManager);
_api.RpcModuleProvider.RegisterBoundedByCpuCount(traceModuleFactory, rpcConfig.Timeout);
if (_api.EthereumEcdsa == null) throw new StepDependencyException(nameof(_api.EthereumEcdsa));
if (_api.Wallet == null) throw new StepDependencyException(nameof(_api.Wallet));
PersonalRpcModule personalRpcModule = new(
_api.EthereumEcdsa,
_api.Wallet,
_api.KeyStore);
_api.RpcModuleProvider.RegisterSingle<IPersonalRpcModule>(personalRpcModule);
if (_api.PeerManager == null) throw new StepDependencyException(nameof(_api.PeerManager));
if (_api.StaticNodesManager == null) throw new StepDependencyException(nameof(_api.StaticNodesManager));
if (_api.Enode == null) throw new StepDependencyException(nameof(_api.Enode));
AdminRpcModule adminRpcModule = new(
_api.BlockTree,
networkConfig,
_api.PeerManager,
_api.StaticNodesManager,
_api.Enode,
initConfig.BaseDbPath);
_api.RpcModuleProvider.RegisterSingle<IAdminRpcModule>(adminRpcModule);
if (_api.TxPoolInfoProvider == null) throw new StepDependencyException(nameof(_api.TxPoolInfoProvider));
TxPoolRpcModule txPoolRpcModule = new(_api.TxPoolInfoProvider, _api.LogManager);
_api.RpcModuleProvider.RegisterSingle<ITxPoolRpcModule>(txPoolRpcModule);
if (_api.SyncServer == null) throw new StepDependencyException(nameof(_api.SyncServer));
if (_api.EngineSignerStore == null) throw new StepDependencyException(nameof(_api.EngineSignerStore));
NetRpcModule netRpcModule = new(_api.LogManager, new NetBridge(_api.Enode, _api.SyncServer));
_api.RpcModuleProvider.RegisterSingle<INetRpcModule>(netRpcModule);
ParityRpcModule parityRpcModule = new(
_api.EthereumEcdsa,
_api.TxPool,
_api.BlockTree,
_api.ReceiptFinder,
_api.Enode,
_api.EngineSignerStore,
_api.KeyStore,
_api.SpecProvider,
_api.PeerManager);
_api.RpcModuleProvider.RegisterSingle<IParityRpcModule>(parityRpcModule);
WitnessRpcModule witnessRpcModule = new(_api.WitnessRepository, _api.BlockTree);
_api.RpcModuleProvider.RegisterSingle<IWitnessRpcModule>(witnessRpcModule);
SubscriptionFactory subscriptionFactory = new(
_api.LogManager,
_api.BlockTree,
_api.TxPool,
_api.ReceiptStorage,
_api.FilterStore,
_api.EthSyncingInfo!);
SubscriptionManager subscriptionManager = new(subscriptionFactory, _api.LogManager);
SubscribeRpcModule subscribeRpcModule = new(subscriptionManager);
_api.RpcModuleProvider.RegisterSingle<ISubscribeRpcModule>(subscribeRpcModule);
Web3RpcModule web3RpcModule = new(_api.LogManager);
_api.RpcModuleProvider.RegisterSingle<IWeb3RpcModule>(web3RpcModule);
EvmRpcModule evmRpcModule = new(_api.ManualBlockProductionTrigger);
_api.RpcModuleProvider.RegisterSingle<IEvmRpcModule>(evmRpcModule);
foreach (INethermindPlugin plugin in _api.Plugins)
{
await plugin.InitRpcModules();
}
if (logger.IsDebug) logger.Debug($"RPC modules : {string.Join(", ", _api.RpcModuleProvider.Enabled.OrderBy(x => x))}");
ThisNodeInfo.AddInfo("RPC modules :", $"{string.Join(", ", _api.RpcModuleProvider.Enabled.OrderBy(x => x))}");
}
}
}
| 1 | 26,579 | We explicitly don't want to do that. This was a complaint from users before. | NethermindEth-nethermind | .cs |
@@ -28,6 +28,7 @@ use Thelia\Type\TypeCollection;
* {@inheritdoc}
* @method int getId()
* @method int[] getExclude()
+ * @method int[] getExcludeCode()
* @method string getCode()
* @method string[] getOrder()
*/ | 1 | <?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : [email protected] */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Core\Template\Element\BaseI18nLoop;
use Thelia\Core\Template\Element\PropelSearchLoopInterface;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Model\ModuleQuery;
use Thelia\Type\EnumType;
use Thelia\Type\TypeCollection;
/**
* @package Thelia\Core\Template\Loop
* @author Manuel Raynaud <[email protected]>
*
* {@inheritdoc}
* @method int getId()
* @method int[] getExclude()
* @method string getCode()
* @method string[] getOrder()
*/
abstract class BaseSpecificModule extends BaseI18nLoop implements PropelSearchLoopInterface
{
protected $timestampable = true;
/**
* @return \Thelia\Core\Template\Loop\Argument\ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntTypeArgument('id'),
Argument::createIntListTypeArgument('exclude'),
Argument::createAnyTypeArgument('code'),
new Argument(
'order',
new TypeCollection(
new EnumType(
[
'id',
'id_reverse',
'alpha',
'alpha_reverse',
'manual',
'manual_reverse',
]
)
),
'manual'
)
);
}
public function buildModelCriteria()
{
$search = ModuleQuery::create();
$search->filterByActivate(1);
if (null !== $id = $this->getId()) {
$search->filterById($id);
}
if (null !== $exclude = $this->getExclude()) {
$search->filterById($exclude, Criteria::NOT_IN);
}
if (null !== $code = $this->getCode()) {
$search->filterByCode($code);
}
$this->configureI18nProcessing($search);
$search->filterByType($this->getModuleType(), Criteria::EQUAL);
$order = $this->getOrder();
switch ($order) {
case "id":
$search->orderById(Criteria::ASC);
break;
case "id_reverse":
$search->orderById(Criteria::DESC);
break;
case "alpha":
$search->addAscendingOrderByColumn('i18n_TITLE');
break;
case "alpha_reverse":
$search->addDescendingOrderByColumn('i18n_TITLE');
break;
case "manual_reverse":
$search->orderByPosition(Criteria::DESC);
break;
case "manual":
default:
$search->orderByPosition(Criteria::ASC);
break;
}
return $search;
}
abstract protected function getModuleType();
}
| 1 | 12,400 | Hello, The PHPDoc is `string[]` not `int[]` | thelia-thelia | php |
@@ -20,7 +20,7 @@ import (
"github.com/chaos-mesh/chaos-mesh/pkg/mock"
)
-func applyTc(ctx context.Context, pid uint32, args ...string) error {
+func applyTc(ctx context.Context, pid uint32, enterNS bool, args ...string) error {
// Mock point to return error in unit test
if err := mock.On("TcApplyError"); err != nil {
if e, ok := err.(error); ok { | 1 | // Copyright 2020 Chaos Mesh Authors.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package chaosdaemon
import (
"context"
"github.com/chaos-mesh/chaos-mesh/pkg/bpm"
"github.com/chaos-mesh/chaos-mesh/pkg/mock"
)
func applyTc(ctx context.Context, pid uint32, args ...string) error {
// Mock point to return error in unit test
if err := mock.On("TcApplyError"); err != nil {
if e, ok := err.(error); ok {
return e
}
if ignore, ok := err.(bool); ok && ignore {
return nil
}
}
cmd := bpm.DefaultProcessBuilder("tc", args...).SetNS(pid, bpm.NetNS).SetContext(ctx).Build()
log.Info("tc command", "command", cmd.String(), "args", args)
out, err := cmd.CombinedOutput()
if err != nil {
log.Error(err, "tc command error", "command", cmd.String(), "output", string(out))
return err
}
return nil
}
| 1 | 19,131 | Same issues with parameters order in `ipset_server.go` | chaos-mesh-chaos-mesh | go |
@@ -82,8 +82,8 @@ const (
SystemLocalNamespace = "temporal-system"
// SystemNamespaceID is namespace id for all temporal system workflows
SystemNamespaceID = "32049b68-7872-4094-8e63-d0dd59896a83"
- // SystemNamespaceRetentionDays is retention config for all temporal system workflows
- SystemNamespaceRetentionDays = time.Hour * 24 * 7
+ // SystemNamespaceRetention is retention config for all temporal system workflows
+ SystemNamespaceRetention = time.Hour * 24 * 7
)
const ( | 1 | // The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// 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.
package common
import (
"math"
"time"
)
const (
// FirstEventID is the id of the first event in the history
FirstEventID int64 = 1
// LastEventID is the id of the last possible event in the history
LastEventID int64 = math.MaxInt64
// EmptyEventID is the id of the empty event
EmptyEventID int64 = 0
// EmptyVersion is used as the default value for failover version when no value is provided
EmptyVersion int64 = 0
// EndEventID is the id of the end event, here we use the int64 max
EndEventID int64 = 1<<63 - 1
// BufferedEventID is the id of the buffered event
BufferedEventID int64 = -123
// EmptyEventTaskID is uninitialized id of the task id within event
EmptyEventTaskID int64 = 0
// TransientEventID is the id of the transient event
TransientEventID int64 = -124
// FirstBlobPageToken is the page token identifying the first blob for each history archival
FirstBlobPageToken = 1
// LastBlobNextPageToken is the next page token on the last blob for each history archival
LastBlobNextPageToken = -1
// EndMessageID is the id of the end message, here we use the int64 max
EndMessageID int64 = 1<<63 - 1
)
const (
// FrontendServiceName is the name of the frontend service
FrontendServiceName = "frontend"
// HistoryServiceName is the name of the history service
HistoryServiceName = "history"
// MatchingServiceName is the name of the matching service
MatchingServiceName = "matching"
// WorkerServiceName is the name of the worker service
WorkerServiceName = "worker"
)
const (
// GetHistoryMaxPageSize is the max page size for get history
GetHistoryMaxPageSize = 256
// ReadDLQMessagesPageSize is the max page size for read DLQ messages
ReadDLQMessagesPageSize = 1000
)
// This was flagged by salus as potentially hardcoded credentials. This is a false positive by the scanner and should be
// disregarded.
// #nosec
const (
// SystemGlobalNamespace is global namespace name for temporal system workflows running globally
SystemGlobalNamespace = "temporal-system-global"
// SystemLocalNamespace is namespace name for temporal system workflows running in local cluster
SystemLocalNamespace = "temporal-system"
// SystemNamespaceID is namespace id for all temporal system workflows
SystemNamespaceID = "32049b68-7872-4094-8e63-d0dd59896a83"
// SystemNamespaceRetentionDays is retention config for all temporal system workflows
SystemNamespaceRetentionDays = time.Hour * 24 * 7
)
const (
// MinLongPollTimeout is the minimum context timeout for long poll API, below which
// the request won't be processed
MinLongPollTimeout = time.Second * 2
// CriticalLongPollTimeout is a threshold for the context timeout passed into long poll API,
// below which a warning will be logged
CriticalLongPollTimeout = time.Second * 20
// MaxWorkflowRetentionPeriod is the maximum of workflow retention when registering namespace
// !!! Do NOT simply decrease this number, because it is being used by history scavenger to avoid race condition against history archival.
// Check more details in history scanner(scavenger)
MaxWorkflowRetentionPeriod = 30 * time.Hour * 24
)
const (
// DefaultWorkflowTaskTimeout sets the Default Workflow Task timeout for a Workflow
DefaultWorkflowTaskTimeout = 10 * time.Second
// MaxWorkflowTaskStartToCloseTimeout sets the Max Workflow Task start to close timeout for a Workflow
MaxWorkflowTaskStartToCloseTimeout = 120 * time.Second
)
const (
// DefaultTransactionSizeLimit is the largest allowed transaction size to persistence
DefaultTransactionSizeLimit = 4 * 1024 * 1024
)
// enum for dynamic config AdvancedVisibilityWritingMode
const (
// AdvancedVisibilityWritingModeOff means do not write to advanced visibility store
AdvancedVisibilityWritingModeOff = "off"
// AdvancedVisibilityWritingModeOn means only write to advanced visibility store
AdvancedVisibilityWritingModeOn = "on"
// AdvancedVisibilityWritingModeDual means write to both normal visibility and advanced visibility store
AdvancedVisibilityWritingModeDual = "dual"
)
| 1 | 11,855 | Wow, did it literally mean the retention days is a huge number? | temporalio-temporal | go |
@@ -216,6 +216,11 @@ int FlatCompiler::Compile(int argc, const char **argv) {
flatbuffers::PosixPath(argv[argi]));
include_directories.push_back(
include_directories_storage.back().c_str());
+ } else if (arg == "--bfbs-filenames") {
+ if (++argi > argc) Error("missing path following: " + arg, true);
+ opts.project_root = argv[argi];
+ if (!DirExists(opts.project_root.c_str()))
+ Error(arg + " is not a directory: " + opts.project_root);
} else if (arg == "--conform") {
if (++argi >= argc) Error("missing path following: " + arg, true);
conform_to_schema = flatbuffers::PosixPath(argv[argi]); | 1 | /*
* Copyright 2014 Google Inc. All rights reserved.
*
* 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.
*/
#include "flatbuffers/flatc.h"
#include <list>
namespace flatbuffers {
const char *FLATC_VERSION() { return FLATBUFFERS_VERSION(); }
void FlatCompiler::ParseFile(
flatbuffers::Parser &parser, const std::string &filename,
const std::string &contents,
std::vector<const char *> &include_directories) const {
auto local_include_directory = flatbuffers::StripFileName(filename);
include_directories.push_back(local_include_directory.c_str());
include_directories.push_back(nullptr);
if (!parser.Parse(contents.c_str(), &include_directories[0],
filename.c_str())) {
Error(parser.error_, false, false);
}
if (!parser.error_.empty()) { Warn(parser.error_, false); }
include_directories.pop_back();
include_directories.pop_back();
}
void FlatCompiler::LoadBinarySchema(flatbuffers::Parser &parser,
const std::string &filename,
const std::string &contents) {
if (!parser.Deserialize(reinterpret_cast<const uint8_t *>(contents.c_str()),
contents.size())) {
Error("failed to load binary schema: " + filename, false, false);
}
}
void FlatCompiler::Warn(const std::string &warn, bool show_exe_name) const {
params_.warn_fn(this, warn, show_exe_name);
}
void FlatCompiler::Error(const std::string &err, bool usage,
bool show_exe_name) const {
params_.error_fn(this, err, usage, show_exe_name);
}
std::string FlatCompiler::GetUsageString(const char *program_name) const {
std::stringstream ss;
ss << "Usage: " << program_name << " [OPTION]... FILE... [-- FILE...]\n";
for (size_t i = 0; i < params_.num_generators; ++i) {
const Generator &g = params_.generators[i];
std::stringstream full_name;
full_name << std::setw(16) << std::left << g.generator_opt_long;
const char *name = g.generator_opt_short ? g.generator_opt_short : " ";
const char *help = g.generator_help;
ss << " " << full_name.str() << " " << name << " " << help << ".\n";
}
// clang-format off
// Output width
// 12345678901234567890123456789012345678901234567890123456789012345678901234567890
ss <<
" -o PATH Prefix PATH to all generated files.\n"
" -I PATH Search for includes in the specified path.\n"
" -M Print make rules for generated files.\n"
" --version Print the version number of flatc and exit.\n"
" --strict-json Strict JSON: field names must be / will be quoted,\n"
" no trailing commas in tables/vectors.\n"
" --allow-non-utf8 Pass non-UTF-8 input through parser and emit nonstandard\n"
" \\x escapes in JSON. (Default is to raise parse error on\n"
" non-UTF-8 input.)\n"
" --natural-utf8 Output strings with UTF-8 as human-readable strings.\n"
" By default, UTF-8 characters are printed as \\uXXXX escapes.\n"
" --defaults-json Output fields whose value is the default when\n"
" writing JSON\n"
" --unknown-json Allow fields in JSON that are not defined in the\n"
" schema. These fields will be discared when generating\n"
" binaries.\n"
" --no-prefix Don\'t prefix enum values with the enum type in C++.\n"
" --scoped-enums Use C++11 style scoped and strongly typed enums.\n"
" also implies --no-prefix.\n"
" --gen-includes (deprecated), this is the default behavior.\n"
" If the original behavior is required (no include\n"
" statements) use --no-includes.\n"
" --no-includes Don\'t generate include statements for included\n"
" schemas the generated file depends on (C++ / Python).\n"
" --gen-mutable Generate accessors that can mutate buffers in-place.\n"
" --gen-onefile Generate single output file for C# and Go.\n"
" --gen-name-strings Generate type name functions for C++ and Rust.\n"
" --gen-object-api Generate an additional object-based API.\n"
" --gen-compare Generate operator== for object-based API types.\n"
" --gen-nullable Add Clang _Nullable for C++ pointer. or @Nullable for Java\n"
" --java-checkerframe work Add @Pure for Java.\n"
" --gen-generated Add @Generated annotation for Java\n"
" --gen-jvmstatic Add @JvmStatic annotation for Kotlin methods\n"
" in companion object for interop from Java to Kotlin.\n"
" --gen-all Generate not just code for the current schema files,\n"
" but for all files it includes as well.\n"
" If the language uses a single file for output (by default\n"
" the case for C++ and JS), all code will end up in this one\n"
" file.\n"
" --cpp-include Adds an #include in generated file.\n"
" --cpp-ptr-type T Set object API pointer type (default std::unique_ptr).\n"
" --cpp-str-type T Set object API string type (default std::string).\n"
" T::c_str(), T::length() and T::empty() must be supported.\n"
" The custom type also needs to be constructible from std::string\n"
" (see the --cpp-str-flex-ctor option to change this behavior).\n"
" --cpp-str-flex-ctor Don't construct custom string types by passing std::string\n"
" from Flatbuffers, but (char* + length).\n"
" --cpp-std CPP_STD Generate a C++ code using features of selected C++ standard.\n"
" Supported CPP_STD values:\n"
" * 'c++0x' - generate code compatible with old compilers;\n"
" * 'c++11' - use C++11 code generator (default);\n"
" * 'c++17' - use C++17 features in generated code (experimental).\n"
" --cpp-static-reflection When using C++17, generate extra code to provide compile-time\n"
" (static) reflection of Flatbuffers types. Requires --cpp-std\n"
" to be \"c++17\" or higher.\n"
" --object-prefix Customise class prefix for C++ object-based API.\n"
" --object-suffix Customise class suffix for C++ object-based API.\n"
" Default value is \"T\".\n"
" --go-namespace Generate the overriding namespace in Golang.\n"
" --go-import Generate the overriding import for flatbuffers in Golang\n"
" (default is \"github.com/google/flatbuffers/go\").\n"
" --raw-binary Allow binaries without file_identifier to be read.\n"
" This may crash flatc given a mismatched schema.\n"
" --size-prefixed Input binaries are size prefixed buffers.\n"
" --proto Input is a .proto, translate to .fbs.\n"
" --proto-namespace-suffix Add this namespace to any flatbuffers generated\n"
" SUFFIX from protobufs.\n"
" --oneof-union Translate .proto oneofs to flatbuffer unions.\n"
" --grpc Generate GRPC interfaces for the specified languages.\n"
" --schema Serialize schemas instead of JSON (use with -b).\n"
" --bfbs-comments Add doc comments to the binary schema files.\n"
" --bfbs-builtins Add builtin attributes to the binary schema files.\n"
" --bfbs-gen-embed Generate code to embed the bfbs schema to the source.\n"
" --conform FILE Specify a schema the following schemas should be\n"
" an evolution of. Gives errors if not.\n"
" --conform-includes Include path for the schema given with --conform PATH\n"
" --filename-suffix The suffix appended to the generated file names.\n"
" Default is '_generated'.\n"
" --filename-ext The extension appended to the generated file names.\n"
" Default is language-specific (e.g., '.h' for C++)\n"
" --include-prefix Prefix this path to any generated include statements.\n"
" PATH\n"
" --keep-prefix Keep original prefix of schema include statement.\n"
" --reflect-types Add minimal type reflection to code generation.\n"
" --reflect-names Add minimal type/name reflection.\n"
" --root-type T Select or override the default root_type\n"
" --require-explicit-ids When parsing schemas, require explicit ids (id: x).\n"
" --force-defaults Emit default values in binary output from JSON\n"
" --force-empty When serializing from object API representation,\n"
" force strings and vectors to empty rather than null.\n"
" --force-empty-vectors When serializing from object API representation,\n"
" force vectors to empty rather than null.\n"
" --flexbuffers Used with \"binary\" and \"json\" options, it generates\n"
" data using schema-less FlexBuffers.\n"
" --no-warnings Inhibit all warning messages.\n"
"FILEs may be schemas (must end in .fbs), binary schemas (must end in .bfbs),\n"
"or JSON files (conforming to preceding schema). FILEs after the -- must be\n"
"binary flatbuffer format files.\n"
"Output files are named using the base file name of the input,\n"
"and written to the current directory or the path given by -o.\n"
"example: " << program_name << " -c -b schema1.fbs schema2.fbs data.json\n";
// 12345678901234567890123456789012345678901234567890123456789012345678901234567890
// clang-format on
return ss.str();
}
int FlatCompiler::Compile(int argc, const char **argv) {
if (params_.generators == nullptr || params_.num_generators == 0) {
return 0;
}
flatbuffers::IDLOptions opts;
std::string output_path;
bool any_generator = false;
bool print_make_rules = false;
bool raw_binary = false;
bool schema_binary = false;
bool grpc_enabled = false;
std::vector<std::string> filenames;
std::list<std::string> include_directories_storage;
std::vector<const char *> include_directories;
std::vector<const char *> conform_include_directories;
std::vector<bool> generator_enabled(params_.num_generators, false);
size_t binary_files_from = std::numeric_limits<size_t>::max();
std::string conform_to_schema;
for (int argi = 0; argi < argc; argi++) {
std::string arg = argv[argi];
if (arg[0] == '-') {
if (filenames.size() && arg[1] != '-')
Error("invalid option location: " + arg, true);
if (arg == "-o") {
if (++argi >= argc) Error("missing path following: " + arg, true);
output_path = flatbuffers::ConCatPathFileName(
flatbuffers::PosixPath(argv[argi]), "");
} else if (arg == "-I") {
if (++argi >= argc) Error("missing path following: " + arg, true);
include_directories_storage.push_back(
flatbuffers::PosixPath(argv[argi]));
include_directories.push_back(
include_directories_storage.back().c_str());
} else if (arg == "--conform") {
if (++argi >= argc) Error("missing path following: " + arg, true);
conform_to_schema = flatbuffers::PosixPath(argv[argi]);
} else if (arg == "--conform-includes") {
if (++argi >= argc) Error("missing path following: " + arg, true);
include_directories_storage.push_back(
flatbuffers::PosixPath(argv[argi]));
conform_include_directories.push_back(
include_directories_storage.back().c_str());
} else if (arg == "--include-prefix") {
if (++argi >= argc) Error("missing path following: " + arg, true);
opts.include_prefix = flatbuffers::ConCatPathFileName(
flatbuffers::PosixPath(argv[argi]), "");
} else if (arg == "--keep-prefix") {
opts.keep_include_path = true;
} else if (arg == "--strict-json") {
opts.strict_json = true;
} else if (arg == "--allow-non-utf8") {
opts.allow_non_utf8 = true;
} else if (arg == "--natural-utf8") {
opts.natural_utf8 = true;
} else if (arg == "--go-namespace") {
if (++argi >= argc) Error("missing golang namespace" + arg, true);
opts.go_namespace = argv[argi];
} else if (arg == "--go-import") {
if (++argi >= argc) Error("missing golang import" + arg, true);
opts.go_import = argv[argi];
} else if (arg == "--defaults-json") {
opts.output_default_scalars_in_json = true;
} else if (arg == "--unknown-json") {
opts.skip_unexpected_fields_in_json = true;
} else if (arg == "--no-prefix") {
opts.prefixed_enums = false;
} else if (arg == "--scoped-enums") {
opts.prefixed_enums = false;
opts.scoped_enums = true;
} else if (arg == "--no-union-value-namespacing") {
opts.union_value_namespacing = false;
} else if (arg == "--gen-mutable") {
opts.mutable_buffer = true;
} else if (arg == "--gen-name-strings") {
opts.generate_name_strings = true;
} else if (arg == "--gen-object-api") {
opts.generate_object_based_api = true;
} else if (arg == "--gen-compare") {
opts.gen_compare = true;
} else if (arg == "--cpp-include") {
if (++argi >= argc) Error("missing include following: " + arg, true);
opts.cpp_includes.push_back(argv[argi]);
} else if (arg == "--cpp-ptr-type") {
if (++argi >= argc) Error("missing type following: " + arg, true);
opts.cpp_object_api_pointer_type = argv[argi];
} else if (arg == "--cpp-str-type") {
if (++argi >= argc) Error("missing type following: " + arg, true);
opts.cpp_object_api_string_type = argv[argi];
} else if (arg == "--cpp-str-flex-ctor") {
opts.cpp_object_api_string_flexible_constructor = true;
} else if (arg == "--no-cpp-direct-copy") {
opts.cpp_direct_copy = false;
} else if (arg == "--gen-nullable") {
opts.gen_nullable = true;
} else if (arg == "--java-checkerframework") {
opts.java_checkerframework = true;
} else if (arg == "--gen-generated") {
opts.gen_generated = true;
} else if (arg == "--object-prefix") {
if (++argi >= argc) Error("missing prefix following: " + arg, true);
opts.object_prefix = argv[argi];
} else if (arg == "--object-suffix") {
if (++argi >= argc) Error("missing suffix following: " + arg, true);
opts.object_suffix = argv[argi];
} else if (arg == "--gen-all") {
opts.generate_all = true;
opts.include_dependence_headers = false;
} else if (arg == "--gen-includes") {
// Deprecated, remove this option some time in the future.
Warn("warning: --gen-includes is deprecated (it is now default)\n");
} else if (arg == "--no-includes") {
opts.include_dependence_headers = false;
} else if (arg == "--gen-onefile") {
opts.one_file = true;
} else if (arg == "--raw-binary") {
raw_binary = true;
} else if (arg == "--size-prefixed") {
opts.size_prefixed = true;
} else if (arg == "--") { // Separator between text and binary inputs.
binary_files_from = filenames.size();
} else if (arg == "--proto") {
opts.proto_mode = true;
} else if (arg == "--proto-namespace-suffix") {
if (++argi >= argc) Error("missing namespace suffix" + arg, true);
opts.proto_namespace_suffix = argv[argi];
} else if (arg == "--oneof-union") {
opts.proto_oneof_union = true;
} else if (arg == "--schema") {
schema_binary = true;
} else if (arg == "-M") {
print_make_rules = true;
} else if (arg == "--version") {
printf("flatc version %s\n", FLATC_VERSION());
exit(0);
} else if (arg == "--grpc") {
grpc_enabled = true;
} else if (arg == "--bfbs-comments") {
opts.binary_schema_comments = true;
} else if (arg == "--bfbs-builtins") {
opts.binary_schema_builtins = true;
} else if (arg == "--bfbs-gen-embed") {
opts.binary_schema_gen_embed = true;
} else if (arg == "--reflect-types") {
opts.mini_reflect = IDLOptions::kTypes;
} else if (arg == "--reflect-names") {
opts.mini_reflect = IDLOptions::kTypesAndNames;
} else if (arg == "--require-explicit-ids") {
opts.require_explicit_ids = true;
} else if (arg == "--root-type") {
if (++argi >= argc) Error("missing type following: " + arg, true);
opts.root_type = argv[argi];
} else if (arg == "--filename-suffix") {
if (++argi >= argc) Error("missing filename suffix: " + arg, true);
opts.filename_suffix = argv[argi];
} else if (arg == "--filename-ext") {
if (++argi >= argc) Error("missing filename extension: " + arg, true);
opts.filename_extension = argv[argi];
} else if (arg == "--force-defaults") {
opts.force_defaults = true;
} else if (arg == "--force-empty") {
opts.set_empty_strings_to_null = false;
opts.set_empty_vectors_to_null = false;
} else if (arg == "--force-empty-vectors") {
opts.set_empty_vectors_to_null = false;
} else if (arg == "--java-primitive-has-method") {
opts.java_primitive_has_method = true;
} else if (arg == "--cs-gen-json-serializer") {
opts.cs_gen_json_serializer = true;
} else if (arg == "--flexbuffers") {
opts.use_flexbuffers = true;
} else if (arg == "--gen-jvmstatic") {
opts.gen_jvmstatic = true;
} else if (arg == "--no-warnings") {
opts.no_warnings = true;
} else if (arg == "--cpp-std") {
if (++argi >= argc)
Error("missing C++ standard specification" + arg, true);
opts.cpp_std = argv[argi];
} else if (arg.rfind("--cpp-std=", 0) == 0) {
opts.cpp_std = arg.substr(std::string("--cpp-std=").size());
} else if (arg == "--cpp-static-reflection") {
opts.cpp_static_reflection = true;
} else {
for (size_t i = 0; i < params_.num_generators; ++i) {
if (arg == params_.generators[i].generator_opt_long ||
(params_.generators[i].generator_opt_short &&
arg == params_.generators[i].generator_opt_short)) {
generator_enabled[i] = true;
any_generator = true;
opts.lang_to_generate |= params_.generators[i].lang;
goto found;
}
}
Error("unknown commandline argument: " + arg, true);
found:;
}
} else {
filenames.push_back(flatbuffers::PosixPath(argv[argi]));
}
}
if (!filenames.size()) Error("missing input files", false, true);
if (opts.proto_mode) {
if (any_generator)
Error("cannot generate code directly from .proto files", true);
} else if (!any_generator && conform_to_schema.empty()) {
Error("no options: specify at least one generator.", true);
}
flatbuffers::Parser conform_parser;
if (!conform_to_schema.empty()) {
std::string contents;
if (!flatbuffers::LoadFile(conform_to_schema.c_str(), true, &contents))
Error("unable to load schema: " + conform_to_schema);
if (flatbuffers::GetExtension(conform_to_schema) ==
reflection::SchemaExtension()) {
LoadBinarySchema(conform_parser, conform_to_schema, contents);
} else {
ParseFile(conform_parser, conform_to_schema, contents,
conform_include_directories);
}
}
std::unique_ptr<flatbuffers::Parser> parser(new flatbuffers::Parser(opts));
for (auto file_it = filenames.begin(); file_it != filenames.end();
++file_it) {
auto &filename = *file_it;
std::string contents;
if (!flatbuffers::LoadFile(filename.c_str(), true, &contents))
Error("unable to load file: " + filename);
bool is_binary =
static_cast<size_t>(file_it - filenames.begin()) >= binary_files_from;
auto ext = flatbuffers::GetExtension(filename);
auto is_schema = ext == "fbs" || ext == "proto";
auto is_binary_schema = ext == reflection::SchemaExtension();
if (is_binary) {
parser->builder_.Clear();
parser->builder_.PushFlatBuffer(
reinterpret_cast<const uint8_t *>(contents.c_str()),
contents.length());
if (!raw_binary) {
// Generally reading binaries that do not correspond to the schema
// will crash, and sadly there's no way around that when the binary
// does not contain a file identifier.
// We'd expect that typically any binary used as a file would have
// such an identifier, so by default we require them to match.
if (!parser->file_identifier_.length()) {
Error("current schema has no file_identifier: cannot test if \"" +
filename +
"\" matches the schema, use --raw-binary to read this file"
" anyway.");
} else if (!flatbuffers::BufferHasIdentifier(
contents.c_str(), parser->file_identifier_.c_str(),
opts.size_prefixed)) {
Error("binary \"" + filename +
"\" does not have expected file_identifier \"" +
parser->file_identifier_ +
"\", use --raw-binary to read this file anyway.");
}
}
} else {
// Check if file contains 0 bytes.
if (!opts.use_flexbuffers && !is_binary_schema &&
contents.length() != strlen(contents.c_str())) {
Error("input file appears to be binary: " + filename, true);
}
if (is_schema) {
// If we're processing multiple schemas, make sure to start each
// one from scratch. If it depends on previous schemas it must do
// so explicitly using an include.
parser.reset(new flatbuffers::Parser(opts));
}
if (is_binary_schema) {
LoadBinarySchema(*parser.get(), filename, contents);
}
if (opts.use_flexbuffers) {
if (opts.lang_to_generate == IDLOptions::kJson) {
parser->flex_root_ = flexbuffers::GetRoot(
reinterpret_cast<const uint8_t *>(contents.c_str()),
contents.size());
} else {
parser->flex_builder_.Clear();
ParseFile(*parser.get(), filename, contents, include_directories);
}
} else {
ParseFile(*parser.get(), filename, contents, include_directories);
if (!is_schema && !parser->builder_.GetSize()) {
// If a file doesn't end in .fbs, it must be json/binary. Ensure we
// didn't just parse a schema with a different extension.
Error("input file is neither json nor a .fbs (schema) file: " +
filename,
true);
}
}
if ((is_schema || is_binary_schema) && !conform_to_schema.empty()) {
auto err = parser->ConformTo(conform_parser);
if (!err.empty()) Error("schemas don\'t conform: " + err);
}
if (schema_binary || opts.binary_schema_gen_embed) {
parser->Serialize();
}
if (schema_binary) {
parser->file_extension_ = reflection::SchemaExtension();
}
}
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(filename));
for (size_t i = 0; i < params_.num_generators; ++i) {
parser->opts.lang = params_.generators[i].lang;
if (generator_enabled[i]) {
if (!print_make_rules) {
flatbuffers::EnsureDirExists(output_path);
if ((!params_.generators[i].schema_only ||
(is_schema || is_binary_schema)) &&
!params_.generators[i].generate(*parser.get(), output_path,
filebase)) {
Error(std::string("Unable to generate ") +
params_.generators[i].lang_name + " for " + filebase);
}
} else {
if (params_.generators[i].make_rule == nullptr) {
Error(std::string("Cannot generate make rule for ") +
params_.generators[i].lang_name);
} else {
std::string make_rule = params_.generators[i].make_rule(
*parser.get(), output_path, filename);
if (!make_rule.empty())
printf("%s\n",
flatbuffers::WordWrap(make_rule, 80, " ", " \\").c_str());
}
}
if (grpc_enabled) {
if (params_.generators[i].generateGRPC != nullptr) {
if (!params_.generators[i].generateGRPC(*parser.get(), output_path,
filebase)) {
Error(std::string("Unable to generate GRPC interface for") +
params_.generators[i].lang_name);
}
} else {
Warn(std::string("GRPC interface generator not implemented for ") +
params_.generators[i].lang_name);
}
}
}
}
if (!opts.root_type.empty()) {
if (!parser->SetRootType(opts.root_type.c_str()))
Error("unknown root type: " + opts.root_type);
else if (parser->root_struct_def_->fixed)
Error("root type must be a table");
}
if (opts.proto_mode) GenerateFBS(*parser.get(), output_path, filebase);
// We do not want to generate code for the definitions in this file
// in any files coming up next.
parser->MarkGenerated();
}
return 0;
}
} // namespace flatbuffers
| 1 | 21,130 | you probably didn't intend to touch those files in `scripts/` | google-flatbuffers | java |
@@ -270,6 +270,7 @@ def eval_map(det_results,
iou_thr=0.5,
dataset=None,
logger=None,
+ tpfp_func=None,
nproc=4):
"""Evaluate mAP of a dataset.
| 1 | from multiprocessing import Pool
import mmcv
import numpy as np
from mmcv.utils import print_log
from terminaltables import AsciiTable
from .bbox_overlaps import bbox_overlaps
from .class_names import get_classes
def average_precision(recalls, precisions, mode='area'):
"""Calculate average precision (for single or multiple scales).
Args:
recalls (ndarray): shape (num_scales, num_dets) or (num_dets, )
precisions (ndarray): shape (num_scales, num_dets) or (num_dets, )
mode (str): 'area' or '11points', 'area' means calculating the area
under precision-recall curve, '11points' means calculating
the average precision of recalls at [0, 0.1, ..., 1]
Returns:
float or ndarray: calculated average precision
"""
no_scale = False
if recalls.ndim == 1:
no_scale = True
recalls = recalls[np.newaxis, :]
precisions = precisions[np.newaxis, :]
assert recalls.shape == precisions.shape and recalls.ndim == 2
num_scales = recalls.shape[0]
ap = np.zeros(num_scales, dtype=np.float32)
if mode == 'area':
zeros = np.zeros((num_scales, 1), dtype=recalls.dtype)
ones = np.ones((num_scales, 1), dtype=recalls.dtype)
mrec = np.hstack((zeros, recalls, ones))
mpre = np.hstack((zeros, precisions, zeros))
for i in range(mpre.shape[1] - 1, 0, -1):
mpre[:, i - 1] = np.maximum(mpre[:, i - 1], mpre[:, i])
for i in range(num_scales):
ind = np.where(mrec[i, 1:] != mrec[i, :-1])[0]
ap[i] = np.sum(
(mrec[i, ind + 1] - mrec[i, ind]) * mpre[i, ind + 1])
elif mode == '11points':
for i in range(num_scales):
for thr in np.arange(0, 1 + 1e-3, 0.1):
precs = precisions[i, recalls[i, :] >= thr]
prec = precs.max() if precs.size > 0 else 0
ap[i] += prec
ap /= 11
else:
raise ValueError(
'Unrecognized mode, only "area" and "11points" are supported')
if no_scale:
ap = ap[0]
return ap
def tpfp_imagenet(det_bboxes,
gt_bboxes,
gt_bboxes_ignore=None,
default_iou_thr=0.5,
area_ranges=None):
"""Check if detected bboxes are true positive or false positive.
Args:
det_bbox (ndarray): Detected bboxes of this image, of shape (m, 5).
gt_bboxes (ndarray): GT bboxes of this image, of shape (n, 4).
gt_bboxes_ignore (ndarray): Ignored gt bboxes of this image,
of shape (k, 4). Default: None
default_iou_thr (float): IoU threshold to be considered as matched for
medium and large bboxes (small ones have special rules).
Default: 0.5.
area_ranges (list[tuple] | None): Range of bbox areas to be evaluated,
in the format [(min1, max1), (min2, max2), ...]. Default: None.
Returns:
tuple[np.ndarray]: (tp, fp) whose elements are 0 and 1. The shape of
each array is (num_scales, m).
"""
# an indicator of ignored gts
gt_ignore_inds = np.concatenate(
(np.zeros(gt_bboxes.shape[0], dtype=np.bool),
np.ones(gt_bboxes_ignore.shape[0], dtype=np.bool)))
# stack gt_bboxes and gt_bboxes_ignore for convenience
gt_bboxes = np.vstack((gt_bboxes, gt_bboxes_ignore))
num_dets = det_bboxes.shape[0]
num_gts = gt_bboxes.shape[0]
if area_ranges is None:
area_ranges = [(None, None)]
num_scales = len(area_ranges)
# tp and fp are of shape (num_scales, num_gts), each row is tp or fp
# of a certain scale.
tp = np.zeros((num_scales, num_dets), dtype=np.float32)
fp = np.zeros((num_scales, num_dets), dtype=np.float32)
if gt_bboxes.shape[0] == 0:
if area_ranges == [(None, None)]:
fp[...] = 1
else:
det_areas = (det_bboxes[:, 2] - det_bboxes[:, 0]) * (
det_bboxes[:, 3] - det_bboxes[:, 1])
for i, (min_area, max_area) in enumerate(area_ranges):
fp[i, (det_areas >= min_area) & (det_areas < max_area)] = 1
return tp, fp
ious = bbox_overlaps(det_bboxes, gt_bboxes - 1)
gt_w = gt_bboxes[:, 2] - gt_bboxes[:, 0]
gt_h = gt_bboxes[:, 3] - gt_bboxes[:, 1]
iou_thrs = np.minimum((gt_w * gt_h) / ((gt_w + 10.0) * (gt_h + 10.0)),
default_iou_thr)
# sort all detections by scores in descending order
sort_inds = np.argsort(-det_bboxes[:, -1])
for k, (min_area, max_area) in enumerate(area_ranges):
gt_covered = np.zeros(num_gts, dtype=bool)
# if no area range is specified, gt_area_ignore is all False
if min_area is None:
gt_area_ignore = np.zeros_like(gt_ignore_inds, dtype=bool)
else:
gt_areas = gt_w * gt_h
gt_area_ignore = (gt_areas < min_area) | (gt_areas >= max_area)
for i in sort_inds:
max_iou = -1
matched_gt = -1
# find best overlapped available gt
for j in range(num_gts):
# different from PASCAL VOC: allow finding other gts if the
# best overlaped ones are already matched by other det bboxes
if gt_covered[j]:
continue
elif ious[i, j] >= iou_thrs[j] and ious[i, j] > max_iou:
max_iou = ious[i, j]
matched_gt = j
# there are 4 cases for a det bbox:
# 1. it matches a gt, tp = 1, fp = 0
# 2. it matches an ignored gt, tp = 0, fp = 0
# 3. it matches no gt and within area range, tp = 0, fp = 1
# 4. it matches no gt but is beyond area range, tp = 0, fp = 0
if matched_gt >= 0:
gt_covered[matched_gt] = 1
if not (gt_ignore_inds[matched_gt]
or gt_area_ignore[matched_gt]):
tp[k, i] = 1
elif min_area is None:
fp[k, i] = 1
else:
bbox = det_bboxes[i, :4]
area = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1])
if area >= min_area and area < max_area:
fp[k, i] = 1
return tp, fp
def tpfp_default(det_bboxes,
gt_bboxes,
gt_bboxes_ignore=None,
iou_thr=0.5,
area_ranges=None):
"""Check if detected bboxes are true positive or false positive.
Args:
det_bbox (ndarray): Detected bboxes of this image, of shape (m, 5).
gt_bboxes (ndarray): GT bboxes of this image, of shape (n, 4).
gt_bboxes_ignore (ndarray): Ignored gt bboxes of this image,
of shape (k, 4). Default: None
iou_thr (float): IoU threshold to be considered as matched.
Default: 0.5.
area_ranges (list[tuple] | None): Range of bbox areas to be evaluated,
in the format [(min1, max1), (min2, max2), ...]. Default: None.
Returns:
tuple[np.ndarray]: (tp, fp) whose elements are 0 and 1. The shape of
each array is (num_scales, m).
"""
# an indicator of ignored gts
gt_ignore_inds = np.concatenate(
(np.zeros(gt_bboxes.shape[0], dtype=np.bool),
np.ones(gt_bboxes_ignore.shape[0], dtype=np.bool)))
# stack gt_bboxes and gt_bboxes_ignore for convenience
gt_bboxes = np.vstack((gt_bboxes, gt_bboxes_ignore))
num_dets = det_bboxes.shape[0]
num_gts = gt_bboxes.shape[0]
if area_ranges is None:
area_ranges = [(None, None)]
num_scales = len(area_ranges)
# tp and fp are of shape (num_scales, num_gts), each row is tp or fp of
# a certain scale
tp = np.zeros((num_scales, num_dets), dtype=np.float32)
fp = np.zeros((num_scales, num_dets), dtype=np.float32)
# if there is no gt bboxes in this image, then all det bboxes
# within area range are false positives
if gt_bboxes.shape[0] == 0:
if area_ranges == [(None, None)]:
fp[...] = 1
else:
det_areas = (det_bboxes[:, 2] - det_bboxes[:, 0]) * (
det_bboxes[:, 3] - det_bboxes[:, 1])
for i, (min_area, max_area) in enumerate(area_ranges):
fp[i, (det_areas >= min_area) & (det_areas < max_area)] = 1
return tp, fp
ious = bbox_overlaps(det_bboxes, gt_bboxes)
# for each det, the max iou with all gts
ious_max = ious.max(axis=1)
# for each det, which gt overlaps most with it
ious_argmax = ious.argmax(axis=1)
# sort all dets in descending order by scores
sort_inds = np.argsort(-det_bboxes[:, -1])
for k, (min_area, max_area) in enumerate(area_ranges):
gt_covered = np.zeros(num_gts, dtype=bool)
# if no area range is specified, gt_area_ignore is all False
if min_area is None:
gt_area_ignore = np.zeros_like(gt_ignore_inds, dtype=bool)
else:
gt_areas = (gt_bboxes[:, 2] - gt_bboxes[:, 0]) * (
gt_bboxes[:, 3] - gt_bboxes[:, 1])
gt_area_ignore = (gt_areas < min_area) | (gt_areas >= max_area)
for i in sort_inds:
if ious_max[i] >= iou_thr:
matched_gt = ious_argmax[i]
if not (gt_ignore_inds[matched_gt]
or gt_area_ignore[matched_gt]):
if not gt_covered[matched_gt]:
gt_covered[matched_gt] = True
tp[k, i] = 1
else:
fp[k, i] = 1
# otherwise ignore this detected bbox, tp = 0, fp = 0
elif min_area is None:
fp[k, i] = 1
else:
bbox = det_bboxes[i, :4]
area = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1])
if area >= min_area and area < max_area:
fp[k, i] = 1
return tp, fp
def get_cls_results(det_results, annotations, class_id):
"""Get det results and gt information of a certain class.
Args:
det_results (list[list]): Same as `eval_map()`.
annotations (list[dict]): Same as `eval_map()`.
class_id (int): ID of a specific class.
Returns:
tuple[list[np.ndarray]]: detected bboxes, gt bboxes, ignored gt bboxes
"""
cls_dets = [img_res[class_id] for img_res in det_results]
cls_gts = []
cls_gts_ignore = []
for ann in annotations:
gt_inds = ann['labels'] == class_id
cls_gts.append(ann['bboxes'][gt_inds, :])
if ann.get('labels_ignore', None) is not None:
ignore_inds = ann['labels_ignore'] == class_id
cls_gts_ignore.append(ann['bboxes_ignore'][ignore_inds, :])
else:
cls_gts_ignore.append(np.empty((0, 4), dtype=np.float32))
return cls_dets, cls_gts, cls_gts_ignore
def eval_map(det_results,
annotations,
scale_ranges=None,
iou_thr=0.5,
dataset=None,
logger=None,
nproc=4):
"""Evaluate mAP of a dataset.
Args:
det_results (list[list]): [[cls1_det, cls2_det, ...], ...].
The outer list indicates images, and the inner list indicates
per-class detected bboxes.
annotations (list[dict]): Ground truth annotations where each item of
the list indicates an image. Keys of annotations are:
- `bboxes`: numpy array of shape (n, 4)
- `labels`: numpy array of shape (n, )
- `bboxes_ignore` (optional): numpy array of shape (k, 4)
- `labels_ignore` (optional): numpy array of shape (k, )
scale_ranges (list[tuple] | None): Range of scales to be evaluated,
in the format [(min1, max1), (min2, max2), ...]. A range of
(32, 64) means the area range between (32**2, 64**2).
Default: None.
iou_thr (float): IoU threshold to be considered as matched.
Default: 0.5.
dataset (list[str] | str | None): Dataset name or dataset classes,
there are minor differences in metrics for different datsets, e.g.
"voc07", "imagenet_det", etc. Default: None.
logger (logging.Logger | str | None): The way to print the mAP
summary. See `mmdet.utils.print_log()` for details. Default: None.
nproc (int): Processes used for computing TP and FP.
Default: 4.
Returns:
tuple: (mAP, [dict, dict, ...])
"""
assert len(det_results) == len(annotations)
num_imgs = len(det_results)
num_scales = len(scale_ranges) if scale_ranges is not None else 1
num_classes = len(det_results[0]) # positive class num
area_ranges = ([(rg[0]**2, rg[1]**2) for rg in scale_ranges]
if scale_ranges is not None else None)
pool = Pool(nproc)
eval_results = []
for i in range(num_classes):
# get gt and det bboxes of this class
cls_dets, cls_gts, cls_gts_ignore = get_cls_results(
det_results, annotations, i)
# choose proper function according to datasets to compute tp and fp
if dataset in ['det', 'vid']:
tpfp_func = tpfp_imagenet
else:
tpfp_func = tpfp_default
# compute tp and fp for each image with multiple processes
tpfp = pool.starmap(
tpfp_func,
zip(cls_dets, cls_gts, cls_gts_ignore,
[iou_thr for _ in range(num_imgs)],
[area_ranges for _ in range(num_imgs)]))
tp, fp = tuple(zip(*tpfp))
# calculate gt number of each scale
# ignored gts or gts beyond the specific scale are not counted
num_gts = np.zeros(num_scales, dtype=int)
for j, bbox in enumerate(cls_gts):
if area_ranges is None:
num_gts[0] += bbox.shape[0]
else:
gt_areas = (bbox[:, 2] - bbox[:, 0]) * (
bbox[:, 3] - bbox[:, 1])
for k, (min_area, max_area) in enumerate(area_ranges):
num_gts[k] += np.sum((gt_areas >= min_area)
& (gt_areas < max_area))
# sort all det bboxes by score, also sort tp and fp
cls_dets = np.vstack(cls_dets)
num_dets = cls_dets.shape[0]
sort_inds = np.argsort(-cls_dets[:, -1])
tp = np.hstack(tp)[:, sort_inds]
fp = np.hstack(fp)[:, sort_inds]
# calculate recall and precision with tp and fp
tp = np.cumsum(tp, axis=1)
fp = np.cumsum(fp, axis=1)
eps = np.finfo(np.float32).eps
recalls = tp / np.maximum(num_gts[:, np.newaxis], eps)
precisions = tp / np.maximum((tp + fp), eps)
# calculate AP
if scale_ranges is None:
recalls = recalls[0, :]
precisions = precisions[0, :]
num_gts = num_gts.item()
mode = 'area' if dataset != 'voc07' else '11points'
ap = average_precision(recalls, precisions, mode)
eval_results.append({
'num_gts': num_gts,
'num_dets': num_dets,
'recall': recalls,
'precision': precisions,
'ap': ap
})
pool.close()
if scale_ranges is not None:
# shape (num_classes, num_scales)
all_ap = np.vstack([cls_result['ap'] for cls_result in eval_results])
all_num_gts = np.vstack(
[cls_result['num_gts'] for cls_result in eval_results])
mean_ap = []
for i in range(num_scales):
if np.any(all_num_gts[:, i] > 0):
mean_ap.append(all_ap[all_num_gts[:, i] > 0, i].mean())
else:
mean_ap.append(0.0)
else:
aps = []
for cls_result in eval_results:
if cls_result['num_gts'] > 0:
aps.append(cls_result['ap'])
mean_ap = np.array(aps).mean().item() if aps else 0.0
print_map_summary(
mean_ap, eval_results, dataset, area_ranges, logger=logger)
return mean_ap, eval_results
def print_map_summary(mean_ap,
results,
dataset=None,
scale_ranges=None,
logger=None):
"""Print mAP and results of each class.
A table will be printed to show the gts/dets/recall/AP of each class and
the mAP.
Args:
mean_ap (float): Calculated from `eval_map()`.
results (list[dict]): Calculated from `eval_map()`.
dataset (list[str] | str | None): Dataset name or dataset classes.
scale_ranges (list[tuple] | None): Range of scales to be evaluated.
logger (logging.Logger | str | None): The way to print the mAP
summary. See `mmdet.utils.print_log()` for details. Default: None.
"""
if logger == 'silent':
return
if isinstance(results[0]['ap'], np.ndarray):
num_scales = len(results[0]['ap'])
else:
num_scales = 1
if scale_ranges is not None:
assert len(scale_ranges) == num_scales
num_classes = len(results)
recalls = np.zeros((num_scales, num_classes), dtype=np.float32)
aps = np.zeros((num_scales, num_classes), dtype=np.float32)
num_gts = np.zeros((num_scales, num_classes), dtype=int)
for i, cls_result in enumerate(results):
if cls_result['recall'].size > 0:
recalls[:, i] = np.array(cls_result['recall'], ndmin=2)[:, -1]
aps[:, i] = cls_result['ap']
num_gts[:, i] = cls_result['num_gts']
if dataset is None:
label_names = [str(i) for i in range(num_classes)]
elif mmcv.is_str(dataset):
label_names = get_classes(dataset)
else:
label_names = dataset
if not isinstance(mean_ap, list):
mean_ap = [mean_ap]
header = ['class', 'gts', 'dets', 'recall', 'ap']
for i in range(num_scales):
if scale_ranges is not None:
print_log(f'Scale range {scale_ranges[i]}', logger=logger)
table_data = [header]
for j in range(num_classes):
row_data = [
label_names[j], num_gts[i, j], results[j]['num_dets'],
f'{recalls[i, j]:.3f}', f'{aps[i, j]:.3f}'
]
table_data.append(row_data)
table_data.append(['mAP', '', '', '', f'{mean_ap[i]:.3f}'])
table = AsciiTable(table_data)
table.inner_footing_row_border = True
print_log('\n' + table.table, logger=logger)
| 1 | 21,725 | Similar to `collate_fn`, we may rename it to `tpfp_fn`. | open-mmlab-mmdetection | py |
@@ -320,6 +320,7 @@ export class TopOverlay extends Overlay {
return this.wot.wtTable.holderOffset.top;
}
+
return 0;
} | 1 | import {
addClass,
getScrollbarWidth,
getScrollTop,
getWindowScrollLeft,
hasClass,
outerHeight,
removeClass,
setOverlayPosition,
resetCssTransform,
} from './../../../../helpers/dom/element';
import TopOverlayTable from './../table/top';
import { Overlay } from './_base';
import {
CLONE_TOP,
} from './constants';
/**
* @class TopOverlay
*/
export class TopOverlay extends Overlay {
static get OVERLAY_NAME() {
return CLONE_TOP;
}
/**
* Cached value which holds the previous value of the `fixedRowsTop` option.
* It is used as a comparison value that can be used to detect changes in this value.
*
* @type {number}
*/
cachedFixedRowsTop = -1;
/**
* @param {Walkontable} wotInstance The Walkontable instance.
*/
constructor(wotInstance) {
super(wotInstance);
this.clone = this.makeClone(CLONE_TOP);
this.cachedFixedRowsTop = this.wot.getSetting('fixedRowsTop');
}
/**
* Factory method to create a subclass of `Table` that is relevant to this overlay.
*
* @see Table#constructor
* @param {...*} args Parameters that will be forwarded to the `Table` constructor.
* @returns {Table}
*/
createTable(...args) {
return new TopOverlayTable(...args);
}
/**
* Checks if overlay should be fully rendered.
*
* @returns {boolean}
*/
shouldBeRendered() {
return this.wot.getSetting('shouldRenderTopOverlay');
}
/**
* Updates the top overlay position.
*
* @returns {boolean}
*/
resetFixedPosition() {
if (!this.needFullRender || !this.wot.wtTable.holder.parentNode) {
// removed from DOM
return;
}
const overlayRoot = this.clone.wtTable.holder.parentNode;
const preventOverflow = this.wot.getSetting('preventOverflow');
let headerPosition = 0;
let skipInnerBorderAdjusting = false;
if (this.trimmingContainer === this.wot.rootWindow && (!preventOverflow || preventOverflow !== 'vertical')) {
const { wtTable } = this.wot;
const hiderRect = wtTable.hider.getBoundingClientRect();
const top = Math.ceil(hiderRect.top);
const bottom = Math.ceil(hiderRect.bottom);
const rootHeight = overlayRoot.offsetHeight;
// This checks if the overlay is going to an infinite loop caused by added (or removed)
// `innerBorderTop` class name. Toggling the class name shifts the viewport by 1px and
// triggers the `scroll` event. It causes the table to render. The new render cycle takes into,
// account the shift and toggles the class name again. This causes the next loops. This
// happens only on Chrome (#7256).
//
// When we detect that the table bottom position is the same as the overlay bottom,
// do not toggle the class name.
//
// This workaround will be able to be cleared after merging the SVG borders, which introduces
// frozen lines (no more `innerBorderTop` workaround).
skipInnerBorderAdjusting = bottom === rootHeight;
let finalLeft;
let finalTop;
finalLeft = wtTable.hider.style.left;
finalLeft = finalLeft === '' ? 0 : finalLeft;
if (top < 0 && (bottom - rootHeight) > 0) {
finalTop = -top;
} else {
finalTop = 0;
}
headerPosition = finalTop;
finalTop += 'px';
setOverlayPosition(overlayRoot, finalLeft, finalTop);
} else {
headerPosition = this.getScrollPosition();
resetCssTransform(overlayRoot);
}
const positionChanged = this.adjustHeaderBordersPosition(headerPosition, skipInnerBorderAdjusting);
this.adjustElementsSize();
return positionChanged;
}
/**
* Sets the main overlay's vertical scroll position.
*
* @param {number} pos The scroll position.
* @returns {boolean}
*/
setScrollPosition(pos) {
const rootWindow = this.wot.rootWindow;
let result = false;
if (this.mainTableScrollableElement === rootWindow && rootWindow.scrollY !== pos) {
rootWindow.scrollTo(getWindowScrollLeft(rootWindow), pos);
result = true;
} else if (this.mainTableScrollableElement.scrollTop !== pos) {
this.mainTableScrollableElement.scrollTop = pos;
result = true;
}
return result;
}
/**
* Triggers onScroll hook callback.
*/
onScroll() {
this.wot.getSetting('onScrollHorizontally');
}
/**
* Calculates total sum cells height.
*
* @param {number} from Row index which calculates started from.
* @param {number} to Row index where calculation is finished.
* @returns {number} Height sum.
*/
sumCellSizes(from, to) {
const defaultRowHeight = this.wot.wtSettings.settings.defaultRowHeight;
let row = from;
let sum = 0;
while (row < to) {
const height = this.wot.wtTable.getRowHeight(row);
sum += height === void 0 ? defaultRowHeight : height;
row += 1;
}
return sum;
}
/**
* Adjust overlay root element, childs and master table element sizes (width, height).
*
* @param {boolean} [force=false] When `true`, it adjusts the DOM nodes sizes for that overlay.
*/
adjustElementsSize(force = false) {
this.updateTrimmingContainer();
if (this.needFullRender || force) {
this.adjustRootElementSize();
this.adjustRootChildrenSize();
}
}
/**
* Adjust overlay root element size (width and height).
*/
adjustRootElementSize() {
const { wtTable, rootDocument, rootWindow } = this.wot;
const scrollbarWidth = getScrollbarWidth(rootDocument);
const overlayRoot = this.clone.wtTable.holder.parentNode;
const overlayRootStyle = overlayRoot.style;
const preventOverflow = this.wot.getSetting('preventOverflow');
if (this.trimmingContainer !== rootWindow || preventOverflow === 'horizontal') {
let width = this.wot.wtViewport.getWorkspaceWidth();
if (this.wot.wtOverlays.hasScrollbarRight) {
width -= scrollbarWidth;
}
width = Math.min(width, wtTable.wtRootElement.scrollWidth);
overlayRootStyle.width = `${width}px`;
} else {
overlayRootStyle.width = '';
}
this.clone.wtTable.holder.style.width = overlayRootStyle.width;
let tableHeight = outerHeight(this.clone.wtTable.TABLE);
if (!this.wot.wtTable.hasDefinedSize()) {
tableHeight = 0;
}
overlayRootStyle.height = `${tableHeight}px`;
}
/**
* Adjust overlay root childs size.
*/
adjustRootChildrenSize() {
const { holder } = this.clone.wtTable;
const { selections } = this.wot;
const selectionCornerOffset = Math.abs(selections?.getCell().getBorder(this.wot).cornerCenterPointOffset ?? 0);
this.clone.wtTable.hider.style.width = this.hider.style.width;
holder.style.width = holder.parentNode.style.width;
// Add selection corner protruding part to the holder total height to make sure that
// borders' corner won't be cut after vertical scroll (#6937).
holder.style.height = `${parseInt(holder.parentNode.style.height, 10) + selectionCornerOffset}px`;
}
/**
* Adjust the overlay dimensions and position.
*/
applyToDOM() {
const total = this.wot.getSetting('totalRows');
if (typeof this.wot.wtViewport.rowsRenderCalculator.startPosition === 'number') {
this.spreader.style.top = `${this.wot.wtViewport.rowsRenderCalculator.startPosition}px`;
} else if (total === 0) {
// can happen if there are 0 rows
this.spreader.style.top = '0';
} else {
throw new Error('Incorrect value of the rowsRenderCalculator');
}
this.spreader.style.bottom = '';
if (this.needFullRender) {
this.syncOverlayOffset();
}
}
/**
* Synchronize calculated left position to an element.
*/
syncOverlayOffset() {
if (typeof this.wot.wtViewport.columnsRenderCalculator.startPosition === 'number') {
this.clone.wtTable.spreader.style.left = `${this.wot.wtViewport.columnsRenderCalculator.startPosition}px`;
} else {
this.clone.wtTable.spreader.style.left = '';
}
}
/**
* Scrolls vertically to a row.
*
* @param {number} sourceRow Row index which you want to scroll to.
* @param {boolean} [bottomEdge] If `true`, scrolls according to the bottom edge (top edge is by default).
* @returns {boolean}
*/
scrollTo(sourceRow, bottomEdge) {
const { wot } = this;
const sourceInstance = wot.cloneSource ? wot.cloneSource : wot;
const mainHolder = sourceInstance.wtTable.holder;
let newY = this.getTableParentOffset();
let scrollbarCompensation = 0;
if (bottomEdge && mainHolder.offsetHeight !== mainHolder.clientHeight) {
scrollbarCompensation = getScrollbarWidth(wot.rootDocument);
}
if (bottomEdge) {
const fixedRowsBottom = wot.getSetting('fixedRowsBottom');
const totalRows = wot.getSetting('totalRows');
newY += this.sumCellSizes(0, sourceRow + 1);
newY -= wot.wtViewport.getViewportHeight() - this.sumCellSizes(totalRows - fixedRowsBottom, totalRows);
// Fix 1 pixel offset when cell is selected
newY += 1;
} else {
newY += this.sumCellSizes(wot.getSetting('fixedRowsTop'), sourceRow);
}
newY += scrollbarCompensation;
return this.setScrollPosition(newY);
}
/**
* Gets table parent top position.
*
* @returns {number}
*/
getTableParentOffset() {
if (this.mainTableScrollableElement === this.wot.rootWindow) {
return this.wot.wtTable.holderOffset.top;
}
return 0;
}
/**
* Gets the main overlay's vertical scroll position.
*
* @returns {number} Main table's vertical scroll position.
*/
getScrollPosition() {
return getScrollTop(this.mainTableScrollableElement, this.wot.rootWindow);
}
/**
* Adds css classes to hide the header border's header (cell-selection border hiding issue).
*
* @param {number} position Header Y position if trimming container is window or scroll top if not.
* @param {boolean} [skipInnerBorderAdjusting=false] If `true` the inner border adjusting will be skipped.
* @returns {boolean}
*/
adjustHeaderBordersPosition(position, skipInnerBorderAdjusting = false) {
const masterParent = this.wot.wtTable.holder.parentNode;
const totalColumns = this.wot.getSetting('totalColumns');
if (totalColumns) {
removeClass(masterParent, 'emptyColumns');
} else {
addClass(masterParent, 'emptyColumns');
}
let positionChanged = false;
if (!skipInnerBorderAdjusting) {
const fixedRowsTop = this.wot.getSetting('fixedRowsTop');
const areFixedRowsTopChanged = this.cachedFixedRowsTop !== fixedRowsTop;
const columnHeaders = this.wot.getSetting('columnHeaders');
if ((areFixedRowsTopChanged || fixedRowsTop === 0) && columnHeaders.length > 0) {
const previousState = hasClass(masterParent, 'innerBorderTop');
this.cachedFixedRowsTop = this.wot.getSetting('fixedRowsTop');
if (position || this.wot.getSetting('totalRows') === 0) {
addClass(masterParent, 'innerBorderTop');
positionChanged = !previousState;
} else {
removeClass(masterParent, 'innerBorderTop');
positionChanged = previousState;
}
}
}
// nasty workaround for double border in the header, TODO: find a pure-css solution
if (this.wot.getSetting('rowHeaders').length === 0) {
const secondHeaderCell = this.clone.wtTable.THEAD.querySelectorAll('th:nth-of-type(2)');
if (secondHeaderCell) {
for (let i = 0; i < secondHeaderCell.length; i++) {
secondHeaderCell[i].style['border-left-width'] = 0;
}
}
}
return positionChanged;
}
}
| 1 | 18,489 | Awesome! We may also use negative rule `never` to fix new lines after `return`: `{ blankLine: "never", prev: "return", next: "*" }` | handsontable-handsontable | js |
@@ -0,0 +1,18 @@
+// Copyright 2016 Keybase Inc. All rights reserved.
+// Use of this source code is governed by a BSD
+// license that can be found in the LICENSE file.
+
+package libkbfs
+
+import "errors"
+
+// GetJournalServer returns the JournalServer tied to a particular
+// config.
+func GetJournalServer(config Config) (*JournalServer, error) {
+ bserver := config.BlockServer()
+ jbserver, ok := bserver.(journalBlockServer)
+ if !ok {
+ return nil, errors.New("Write journal not enabled")
+ }
+ return jbserver.jServer, nil
+} | 1 | 1 | 12,125 | Why can't this be a function on the `Config` interface like all the others? | keybase-kbfs | go |
|
@@ -252,7 +252,9 @@ public class FeedItemlistFragment extends Fragment implements AdapterView.OnItem
optionsMenu = menu;
FeedMenuHandler.onCreateOptionsMenu(inflater, menu);
iconTintManager.updateTint();
- MenuItemUtils.setupSearchItem(menu, (MainActivity) getActivity(), feedID);
+ if (feed != null) {
+ MenuItemUtils.setupSearchItem(menu, (MainActivity) getActivity(), feedID, feed.getTitle());
+ }
if (feed == null || feed.getLink() == null) {
menu.findItem(R.id.share_link_item).setVisible(false);
menu.findItem(R.id.visit_website_item).setVisible(false); | 1 | package de.danoeh.antennapod.fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.content.Intent;
import android.graphics.LightingColorFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.joanzapata.iconify.Iconify;
import com.joanzapata.iconify.widget.IconTextView;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.activity.MainActivity;
import de.danoeh.antennapod.adapter.EpisodeItemListAdapter;
import de.danoeh.antennapod.core.asynctask.FeedRemover;
import de.danoeh.antennapod.core.dialog.ConfirmationDialog;
import de.danoeh.antennapod.core.dialog.DownloadRequestErrorDialogCreator;
import de.danoeh.antennapod.core.event.DownloadEvent;
import de.danoeh.antennapod.core.event.DownloaderUpdate;
import de.danoeh.antennapod.core.event.FeedItemEvent;
import de.danoeh.antennapod.core.event.FeedListUpdateEvent;
import de.danoeh.antennapod.core.event.PlaybackPositionEvent;
import de.danoeh.antennapod.core.event.PlayerStatusEvent;
import de.danoeh.antennapod.core.event.UnreadItemsUpdateEvent;
import de.danoeh.antennapod.core.feed.Feed;
import de.danoeh.antennapod.core.feed.FeedEvent;
import de.danoeh.antennapod.core.feed.FeedItem;
import de.danoeh.antennapod.core.feed.FeedItemFilter;
import de.danoeh.antennapod.core.glide.ApGlideSettings;
import de.danoeh.antennapod.core.glide.FastBlurTransformation;
import de.danoeh.antennapod.core.service.download.DownloadService;
import de.danoeh.antennapod.core.storage.DBReader;
import de.danoeh.antennapod.core.storage.DBTasks;
import de.danoeh.antennapod.core.storage.DBWriter;
import de.danoeh.antennapod.core.storage.DownloadRequestException;
import de.danoeh.antennapod.core.storage.DownloadRequester;
import de.danoeh.antennapod.core.util.FeedItemPermutors;
import de.danoeh.antennapod.core.util.FeedItemUtil;
import de.danoeh.antennapod.core.util.Optional;
import de.danoeh.antennapod.core.util.ThemeUtils;
import de.danoeh.antennapod.core.util.gui.MoreContentListFooterUtil;
import de.danoeh.antennapod.dialog.EpisodesApplyActionFragment;
import de.danoeh.antennapod.dialog.FilterDialog;
import de.danoeh.antennapod.dialog.RenameFeedDialog;
import de.danoeh.antennapod.menuhandler.FeedItemMenuHandler;
import de.danoeh.antennapod.menuhandler.FeedMenuHandler;
import de.danoeh.antennapod.menuhandler.MenuItemUtils;
import de.danoeh.antennapod.view.EpisodeItemListRecyclerView;
import de.danoeh.antennapod.view.ToolbarIconTintManager;
import de.danoeh.antennapod.view.viewholder.EpisodeItemViewHolder;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import org.apache.commons.lang3.Validate;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.List;
import java.util.Set;
/**
* Displays a list of FeedItems.
*/
public class FeedItemlistFragment extends Fragment implements AdapterView.OnItemClickListener {
private static final String TAG = "ItemlistFragment";
private static final String ARGUMENT_FEED_ID = "argument.de.danoeh.antennapod.feed_id";
private FeedItemListAdapter adapter;
private MoreContentListFooterUtil nextPageLoader;
private ProgressBar progressBar;
private EpisodeItemListRecyclerView recyclerView;
private TextView txtvTitle;
private IconTextView txtvFailure;
private ImageView imgvBackground;
private ImageView imgvCover;
private TextView txtvInformation;
private TextView txtvAuthor;
private ImageButton butShowInfo;
private ImageButton butShowSettings;
private View header;
private Menu optionsMenu;
private ToolbarIconTintManager iconTintManager;
private long feedID;
private Feed feed;
private boolean headerCreated = false;
private boolean isUpdatingFeed;
private Disposable disposable;
/**
* Creates new ItemlistFragment which shows the Feeditems of a specific
* feed. Sets 'showFeedtitle' to false
*
* @param feedId The id of the feed to show
* @return the newly created instance of an ItemlistFragment
*/
public static FeedItemlistFragment newInstance(long feedId) {
FeedItemlistFragment i = new FeedItemlistFragment();
Bundle b = new Bundle();
b.putLong(ARGUMENT_FEED_ID, feedId);
i.setArguments(b);
return i;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
Bundle args = getArguments();
Validate.notNull(args);
feedID = args.getLong(ARGUMENT_FEED_ID);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.feed_item_list_fragment, container, false);
Toolbar toolbar = root.findViewById(R.id.toolbar);
toolbar.setTitle("");
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
recyclerView = root.findViewById(R.id.recyclerView);
recyclerView.setRecycledViewPool(((MainActivity) getActivity()).getRecycledViewPool());
recyclerView.setVisibility(View.GONE);
progressBar = root.findViewById(R.id.progLoading);
txtvTitle = root.findViewById(R.id.txtvTitle);
txtvAuthor = root.findViewById(R.id.txtvAuthor);
imgvBackground = root.findViewById(R.id.imgvBackground);
imgvCover = root.findViewById(R.id.imgvCover);
butShowInfo = root.findViewById(R.id.butShowInfo);
butShowSettings = root.findViewById(R.id.butShowSettings);
txtvInformation = root.findViewById(R.id.txtvInformation);
txtvFailure = root.findViewById(R.id.txtvFailure);
header = root.findViewById(R.id.headerContainer);
AppBarLayout appBar = root.findViewById(R.id.appBar);
CollapsingToolbarLayout collapsingToolbar = root.findViewById(R.id.collapsing_toolbar);
iconTintManager = new ToolbarIconTintManager(getContext(), toolbar, collapsingToolbar) {
@Override
protected void doTint(Context themedContext) {
if (optionsMenu == null) {
return;
}
optionsMenu.findItem(R.id.sort_items)
.setIcon(ThemeUtils.getDrawableFromAttr(themedContext, R.attr.ic_sort));
optionsMenu.findItem(R.id.filter_items)
.setIcon(ThemeUtils.getDrawableFromAttr(themedContext, R.attr.ic_filter));
optionsMenu.findItem(R.id.refresh_item)
.setIcon(ThemeUtils.getDrawableFromAttr(themedContext, R.attr.navigation_refresh));
optionsMenu.findItem(R.id.action_search)
.setIcon(ThemeUtils.getDrawableFromAttr(themedContext, R.attr.action_search));
}
};
appBar.addOnOffsetChangedListener(iconTintManager);
nextPageLoader = new MoreContentListFooterUtil(root.findViewById(R.id.more_content_list_footer));
nextPageLoader.setClickListener(() -> {
if (feed != null) {
try {
DBTasks.loadNextPageOfFeed(getActivity(), feed, false);
} catch (DownloadRequestException e) {
e.printStackTrace();
DownloadRequestErrorDialogCreator.newRequestErrorDialog(getActivity(), e.getMessage());
}
}
});
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView view, int deltaX, int deltaY) {
super.onScrolled(view, deltaX, deltaY);
boolean hasMorePages = feed != null && feed.isPaged() && feed.getNextPageLink() != null;
nextPageLoader.getRoot().setVisibility(
(recyclerView.isScrolledToBottom() && hasMorePages) ? View.VISIBLE : View.GONE);
}
});
EventBus.getDefault().register(this);
SwipeRefreshLayout swipeRefreshLayout = root.findViewById(R.id.swipeRefresh);
swipeRefreshLayout.setOnRefreshListener(() -> {
try {
DBTasks.forceRefreshFeed(requireContext(), feed, true);
} catch (DownloadRequestException e) {
e.printStackTrace();
}
new Handler(Looper.getMainLooper()).postDelayed(() -> swipeRefreshLayout.setRefreshing(false),
getResources().getInteger(R.integer.swipe_to_refresh_duration_in_ms));
});
loadItems();
return root;
}
@Override
public void onDestroyView() {
super.onDestroyView();
EventBus.getDefault().unregister(this);
if (disposable != null) {
disposable.dispose();
}
adapter = null;
}
private final MenuItemUtils.UpdateRefreshMenuItemChecker updateRefreshMenuItemChecker = new MenuItemUtils.UpdateRefreshMenuItemChecker() {
@Override
public boolean isRefreshing() {
return feed != null && DownloadService.isRunning && DownloadRequester.getInstance().isDownloadingFile(feed);
}
};
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
if (!isAdded()) {
return;
}
super.onCreateOptionsMenu(menu, inflater);
optionsMenu = menu;
FeedMenuHandler.onCreateOptionsMenu(inflater, menu);
iconTintManager.updateTint();
MenuItemUtils.setupSearchItem(menu, (MainActivity) getActivity(), feedID);
if (feed == null || feed.getLink() == null) {
menu.findItem(R.id.share_link_item).setVisible(false);
menu.findItem(R.id.visit_website_item).setVisible(false);
}
isUpdatingFeed = MenuItemUtils.updateRefreshMenuItem(menu, R.id.refresh_item, updateRefreshMenuItemChecker);
}
@Override
public void onPrepareOptionsMenu(@NonNull Menu menu) {
if (feed != null) {
FeedMenuHandler.onPrepareOptionsMenu(menu, feed);
}
}
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int horizontalSpacing = (int) getResources().getDimension(R.dimen.additional_horizontal_spacing);
header.setPadding(horizontalSpacing, header.getPaddingTop(), horizontalSpacing, header.getPaddingBottom());
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (!super.onOptionsItemSelected(item)) {
if (feed == null) {
((MainActivity) getActivity()).showSnackbarAbovePlayer(
R.string.please_wait_for_data, Toast.LENGTH_LONG);
return true;
}
try {
if (!FeedMenuHandler.onOptionsItemClicked(getActivity(), item, feed)) {
switch (item.getItemId()) {
case R.id.episode_actions:
EpisodesApplyActionFragment fragment = EpisodesApplyActionFragment
.newInstance(feed.getItems());
((MainActivity)getActivity()).loadChildFragment(fragment);
return true;
case R.id.rename_item:
new RenameFeedDialog(getActivity(), feed).show();
return true;
case R.id.remove_item:
final FeedRemover remover = new FeedRemover(
getActivity(), feed) {
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
((MainActivity) getActivity()).loadFragment(EpisodesFragment.TAG, null);
}
};
ConfirmationDialog conDialog = new ConfirmationDialog(getActivity(),
R.string.remove_feed_label,
getString(R.string.feed_delete_confirmation_msg, feed.getTitle())) {
@Override
public void onConfirmButtonPressed(
DialogInterface dialog) {
dialog.dismiss();
remover.executeAsync();
}
};
conDialog.createNewDialog().show();
return true;
default:
return false;
}
} else {
return true;
}
} catch (DownloadRequestException e) {
e.printStackTrace();
DownloadRequestErrorDialogCreator.newRequestErrorDialog(getActivity(), e.getMessage());
return true;
}
} else {
return true;
}
}
@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
FeedItem selectedItem = adapter.getSelectedItem();
if (selectedItem == null) {
Log.i(TAG, "Selected item at current position was null, ignoring selection");
return super.onContextItemSelected(item);
}
return FeedItemMenuHandler.onMenuItemClicked(this, item.getItemId(), selectedItem);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (adapter == null) {
return;
}
MainActivity activity = (MainActivity) getActivity();
long[] ids = FeedItemUtil.getIds(feed.getItems());
activity.loadChildFragment(ItemPagerFragment.newInstance(ids, position));
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(FeedEvent event) {
Log.d(TAG, "onEvent() called with: " + "event = [" + event + "]");
if (event.feedId == feedID) {
loadItems();
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(FeedItemEvent event) {
Log.d(TAG, "onEventMainThread() called with: " + "event = [" + event + "]");
if (feed == null || feed.getItems() == null) {
return;
} else if (adapter == null) {
loadItems();
return;
}
for (int i = 0, size = event.items.size(); i < size; i++) {
FeedItem item = event.items.get(i);
int pos = FeedItemUtil.indexOfItemWithId(feed.getItems(), item.getId());
if (pos >= 0) {
feed.getItems().remove(pos);
feed.getItems().add(pos, item);
adapter.notifyItemChangedCompat(pos);
}
}
}
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onEventMainThread(DownloadEvent event) {
Log.d(TAG, "onEventMainThread() called with: " + "event = [" + event + "]");
DownloaderUpdate update = event.update;
if (event.hasChangedFeedUpdateStatus(isUpdatingFeed)) {
updateSyncProgressBarVisibility();
}
if (adapter != null && update.mediaIds.length > 0 && feed != null) {
for (long mediaId : update.mediaIds) {
int pos = FeedItemUtil.indexOfItemWithMediaId(feed.getItems(), mediaId);
if (pos >= 0) {
adapter.notifyItemChangedCompat(pos);
}
}
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(PlaybackPositionEvent event) {
if (adapter != null) {
for (int i = 0; i < adapter.getItemCount(); i++) {
EpisodeItemViewHolder holder = (EpisodeItemViewHolder) recyclerView.findViewHolderForAdapterPosition(i);
if (holder != null && holder.isCurrentlyPlayingItem()) {
holder.notifyPlaybackPositionUpdated(event);
break;
}
}
}
}
private void updateUi() {
loadItems();
updateSyncProgressBarVisibility();
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onPlayerStatusChanged(PlayerStatusEvent event) {
updateUi();
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onUnreadItemsChanged(UnreadItemsUpdateEvent event) {
updateUi();
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onFeedListChanged(FeedListUpdateEvent event) {
if (feed != null && event.contains(feed)) {
updateUi();
}
}
private void updateSyncProgressBarVisibility() {
if (isUpdatingFeed != updateRefreshMenuItemChecker.isRefreshing()) {
getActivity().invalidateOptionsMenu();
}
if (!DownloadRequester.getInstance().isDownloadingFeeds()) {
nextPageLoader.getRoot().setVisibility(View.GONE);
}
nextPageLoader.setLoadingState(DownloadRequester.getInstance().isDownloadingFeeds());
}
private void displayList() {
if (getView() == null) {
Log.e(TAG, "Required root view is not yet created. Stop binding data to UI.");
return;
}
if (adapter == null) {
recyclerView.setAdapter(null);
adapter = new FeedItemListAdapter((MainActivity) getActivity());
recyclerView.setAdapter(adapter);
}
recyclerView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
if (feed != null) {
adapter.updateItems(feed.getItems());
}
getActivity().invalidateOptionsMenu();
updateSyncProgressBarVisibility();
}
private void refreshHeaderView() {
setupHeaderView();
if (recyclerView == null || feed == null) {
Log.e(TAG, "Unable to refresh header view");
return;
}
loadFeedImage();
if (feed.hasLastUpdateFailed()) {
txtvFailure.setVisibility(View.VISIBLE);
} else {
txtvFailure.setVisibility(View.GONE);
}
txtvTitle.setText(feed.getTitle());
txtvAuthor.setText(feed.getAuthor());
if (feed.getItemFilter() != null) {
FeedItemFilter filter = feed.getItemFilter();
if (filter.getValues().length > 0) {
if (feed.hasLastUpdateFailed()) {
RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) txtvInformation.getLayoutParams();
p.addRule(RelativeLayout.BELOW, R.id.txtvFailure);
}
txtvInformation.setText("{md-info-outline} " + this.getString(R.string.filtered_label));
Iconify.addIcons(txtvInformation);
txtvInformation.setOnClickListener((l) -> {
FilterDialog filterDialog = new FilterDialog(requireContext(), feed.getItemFilter()) {
@Override
protected void updateFilter(Set<String> filterValues) {
feed.setItemFilter(filterValues.toArray(new String[0]));
DBWriter.setFeedItemsFilter(feed.getId(), filterValues);
}
};
filterDialog.openDialog();
});
txtvInformation.setVisibility(View.VISIBLE);
} else {
txtvInformation.setVisibility(View.GONE);
}
} else {
txtvInformation.setVisibility(View.GONE);
}
}
private void setupHeaderView() {
if (feed == null || headerCreated) {
return;
}
// https://github.com/bumptech/glide/issues/529
imgvBackground.setColorFilter(new LightingColorFilter(0xff666666, 0x000000));
butShowInfo.setVisibility(View.VISIBLE);
butShowInfo.setOnClickListener(v -> showFeedInfo());
imgvCover.setOnClickListener(v -> showFeedInfo());
butShowSettings.setVisibility(View.VISIBLE);
butShowSettings.setOnClickListener(v -> {
if (feed != null) {
FeedSettingsFragment fragment = FeedSettingsFragment.newInstance(feed);
((MainActivity) getActivity()).loadChildFragment(fragment, TransitionEffect.SLIDE);
}
});
txtvFailure.setOnClickListener(v -> {
Intent intent = new Intent(getContext(), MainActivity.class);
intent.putExtra(MainActivity.EXTRA_FRAGMENT_TAG, DownloadsFragment.TAG);
Bundle args = new Bundle();
args.putInt(DownloadsFragment.ARG_SELECTED_TAB, DownloadsFragment.POS_LOG);
intent.putExtra(MainActivity.EXTRA_FRAGMENT_ARGS, args);
startActivity(intent);
});
headerCreated = true;
}
private void showFeedInfo() {
if (feed != null) {
FeedInfoFragment fragment = FeedInfoFragment.newInstance(feed);
((MainActivity) getActivity()).loadChildFragment(fragment, TransitionEffect.SLIDE);
}
}
private void loadFeedImage() {
Glide.with(getActivity())
.load(feed.getImageLocation())
.apply(new RequestOptions()
.placeholder(R.color.image_readability_tint)
.error(R.color.image_readability_tint)
.diskCacheStrategy(ApGlideSettings.AP_DISK_CACHE_STRATEGY)
.transform(new FastBlurTransformation())
.dontAnimate())
.into(imgvBackground);
Glide.with(getActivity())
.load(feed.getImageLocation())
.apply(new RequestOptions()
.placeholder(R.color.light_gray)
.error(R.color.light_gray)
.diskCacheStrategy(ApGlideSettings.AP_DISK_CACHE_STRATEGY)
.fitCenter()
.dontAnimate())
.into(imgvCover);
}
private void loadItems() {
if (disposable != null) {
disposable.dispose();
}
progressBar.setVisibility(View.VISIBLE);
disposable = Observable.fromCallable(this::loadData)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(result -> {
feed = result.orElse(null);
refreshHeaderView();
displayList();
}, error -> Log.e(TAG, Log.getStackTraceString(error)));
}
@NonNull
private Optional<Feed> loadData() {
Feed feed = DBReader.getFeed(feedID);
if (feed != null && feed.getItemFilter() != null) {
DBReader.loadAdditionalFeedItemListData(feed.getItems());
FeedItemFilter filter = feed.getItemFilter();
feed.setItems(filter.filter(feed.getItems()));
}
if (feed != null && feed.getSortOrder() != null) {
List<FeedItem> feedItems = feed.getItems();
FeedItemPermutors.getPermutor(feed.getSortOrder()).reorder(feedItems);
feed.setItems(feedItems);
}
return Optional.ofNullable(feed);
}
private static class FeedItemListAdapter extends EpisodeItemListAdapter {
public FeedItemListAdapter(MainActivity mainActivity) {
super(mainActivity);
}
@Override
protected void beforeBindViewHolder(EpisodeItemViewHolder holder, int pos) {
holder.coverHolder.setVisibility(View.GONE);
}
}
} | 1 | 17,332 | If the feed is null, the menu items should still be setup. Just the feed title can be left out. That prevents possible flickering when menu items are displayed/hidden for some feeds. | AntennaPod-AntennaPod | java |
@@ -178,8 +178,12 @@ public class Spark3Util {
private static void apply(UpdateSchema pendingUpdate, TableChange.AddColumn add) {
Type type = SparkSchemaUtil.convert(add.dataType());
- pendingUpdate.addColumn(parentName(add.fieldNames()), leafName(add.fieldNames()), type, add.comment());
-
+ if (add.isNullable()) {
+ pendingUpdate.addColumn(parentName(add.fieldNames()), leafName(add.fieldNames()), type, add.comment());
+ } else {
+ pendingUpdate.allowIncompatibleChanges()
+ .addRequiredColumn(parentName(add.fieldNames()), leafName(add.fieldNames()), type, add.comment());
+ }
if (add.position() instanceof TableChange.After) {
TableChange.After after = (TableChange.After) add.position();
String referenceField = peerName(add.fieldNames(), after.column()); | 1 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.iceberg.spark;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.iceberg.PartitionSpec;
import org.apache.iceberg.Schema;
import org.apache.iceberg.TableProperties;
import org.apache.iceberg.UpdateProperties;
import org.apache.iceberg.UpdateSchema;
import org.apache.iceberg.expressions.BoundPredicate;
import org.apache.iceberg.expressions.ExpressionVisitors;
import org.apache.iceberg.expressions.UnboundPredicate;
import org.apache.iceberg.hadoop.HadoopInputFile;
import org.apache.iceberg.io.FileIO;
import org.apache.iceberg.io.InputFile;
import org.apache.iceberg.relocated.com.google.common.base.Joiner;
import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet;
import org.apache.iceberg.transforms.PartitionSpecVisitor;
import org.apache.iceberg.types.Type;
import org.apache.iceberg.types.TypeUtil;
import org.apache.iceberg.types.Types;
import org.apache.iceberg.util.PropertyUtil;
import org.apache.spark.sql.connector.catalog.TableCatalog;
import org.apache.spark.sql.connector.catalog.TableChange;
import org.apache.spark.sql.connector.expressions.Expression;
import org.apache.spark.sql.connector.expressions.Expressions;
import org.apache.spark.sql.connector.expressions.Literal;
import org.apache.spark.sql.connector.expressions.Transform;
import org.apache.spark.sql.types.IntegerType;
import org.apache.spark.sql.types.LongType;
import org.apache.spark.sql.util.CaseInsensitiveStringMap;
public class Spark3Util {
private static final Set<String> LOCALITY_WHITELIST_FS = ImmutableSet.of("hdfs");
private static final Set<String> RESERVED_PROPERTIES = ImmutableSet.of(
TableCatalog.PROP_LOCATION, TableCatalog.PROP_PROVIDER);
private static final Joiner DOT = Joiner.on(".");
private Spark3Util() {
}
public static Map<String, String> rebuildCreateProperties(Map<String, String> createProperties) {
ImmutableMap.Builder<String, String> tableProperties = ImmutableMap.builder();
createProperties.entrySet().stream()
.filter(entry -> !RESERVED_PROPERTIES.contains(entry.getKey()))
.forEach(tableProperties::put);
String provider = createProperties.get(TableCatalog.PROP_PROVIDER);
if ("parquet".equalsIgnoreCase(provider)) {
tableProperties.put(TableProperties.DEFAULT_FILE_FORMAT, "parquet");
} else if ("avro".equalsIgnoreCase(provider)) {
tableProperties.put(TableProperties.DEFAULT_FILE_FORMAT, "avro");
} else if ("orc".equalsIgnoreCase(provider)) {
tableProperties.put(TableProperties.DEFAULT_FILE_FORMAT, "orc");
} else if (provider != null && !"iceberg".equalsIgnoreCase(provider)) {
throw new IllegalArgumentException("Unsupported format in USING: " + provider);
}
return tableProperties.build();
}
/**
* Applies a list of Spark table changes to an {@link UpdateProperties} operation.
*
* @param pendingUpdate an uncommitted UpdateProperties operation to configure
* @param changes a list of Spark table changes
* @return the UpdateProperties operation configured with the changes
*/
public static UpdateProperties applyPropertyChanges(UpdateProperties pendingUpdate, List<TableChange> changes) {
for (TableChange change : changes) {
if (change instanceof TableChange.SetProperty) {
TableChange.SetProperty set = (TableChange.SetProperty) change;
pendingUpdate.set(set.property(), set.value());
} else if (change instanceof TableChange.RemoveProperty) {
TableChange.RemoveProperty remove = (TableChange.RemoveProperty) change;
pendingUpdate.remove(remove.property());
} else {
throw new UnsupportedOperationException("Cannot apply unknown table change: " + change);
}
}
return pendingUpdate;
}
/**
* Applies a list of Spark table changes to an {@link UpdateSchema} operation.
*
* @param pendingUpdate an uncommitted UpdateSchema operation to configure
* @param changes a list of Spark table changes
* @return the UpdateSchema operation configured with the changes
*/
public static UpdateSchema applySchemaChanges(UpdateSchema pendingUpdate, List<TableChange> changes) {
for (TableChange change : changes) {
if (change instanceof TableChange.AddColumn) {
apply(pendingUpdate, (TableChange.AddColumn) change);
} else if (change instanceof TableChange.UpdateColumnType) {
TableChange.UpdateColumnType update = (TableChange.UpdateColumnType) change;
Type newType = SparkSchemaUtil.convert(update.newDataType());
Preconditions.checkArgument(newType.isPrimitiveType(),
"Cannot update '%s', not a primitive type: %s", DOT.join(update.fieldNames()), update.newDataType());
pendingUpdate.updateColumn(DOT.join(update.fieldNames()), newType.asPrimitiveType());
} else if (change instanceof TableChange.UpdateColumnComment) {
TableChange.UpdateColumnComment update = (TableChange.UpdateColumnComment) change;
pendingUpdate.updateColumnDoc(DOT.join(update.fieldNames()), update.newComment());
} else if (change instanceof TableChange.RenameColumn) {
TableChange.RenameColumn rename = (TableChange.RenameColumn) change;
pendingUpdate.renameColumn(DOT.join(rename.fieldNames()), rename.newName());
} else if (change instanceof TableChange.DeleteColumn) {
TableChange.DeleteColumn delete = (TableChange.DeleteColumn) change;
pendingUpdate.deleteColumn(DOT.join(delete.fieldNames()));
} else if (change instanceof TableChange.UpdateColumnNullability) {
TableChange.UpdateColumnNullability update = (TableChange.UpdateColumnNullability) change;
if (update.nullable()) {
pendingUpdate.makeColumnOptional(DOT.join(update.fieldNames()));
} else {
pendingUpdate.requireColumn(DOT.join(update.fieldNames()));
}
} else if (change instanceof TableChange.UpdateColumnPosition) {
apply(pendingUpdate, (TableChange.UpdateColumnPosition) change);
} else {
throw new UnsupportedOperationException("Cannot apply unknown table change: " + change);
}
}
return pendingUpdate;
}
private static void apply(UpdateSchema pendingUpdate, TableChange.UpdateColumnPosition update) {
Preconditions.checkArgument(update.position() != null, "Invalid position: null");
if (update.position() instanceof TableChange.After) {
TableChange.After after = (TableChange.After) update.position();
String referenceField = peerName(update.fieldNames(), after.column());
pendingUpdate.moveAfter(DOT.join(update.fieldNames()), referenceField);
} else if (update.position() instanceof TableChange.First) {
pendingUpdate.moveFirst(DOT.join(update.fieldNames()));
} else {
throw new IllegalArgumentException("Unknown position for reorder: " + update.position());
}
}
private static void apply(UpdateSchema pendingUpdate, TableChange.AddColumn add) {
Type type = SparkSchemaUtil.convert(add.dataType());
pendingUpdate.addColumn(parentName(add.fieldNames()), leafName(add.fieldNames()), type, add.comment());
if (add.position() instanceof TableChange.After) {
TableChange.After after = (TableChange.After) add.position();
String referenceField = peerName(add.fieldNames(), after.column());
pendingUpdate.moveAfter(DOT.join(add.fieldNames()), referenceField);
} else if (add.position() instanceof TableChange.First) {
pendingUpdate.moveFirst(DOT.join(add.fieldNames()));
} else {
Preconditions.checkArgument(add.position() == null,
"Cannot add '%s' at unknown position: %s", DOT.join(add.fieldNames()), add.position());
}
}
/**
* Converts a PartitionSpec to Spark transforms.
*
* @param spec a PartitionSpec
* @return an array of Transforms
*/
public static Transform[] toTransforms(PartitionSpec spec) {
List<Transform> transforms = PartitionSpecVisitor.visit(spec.schema(), spec,
new PartitionSpecVisitor<Transform>() {
@Override
public Transform identity(String sourceName, int sourceId) {
return Expressions.identity(sourceName);
}
@Override
public Transform bucket(String sourceName, int sourceId, int width) {
return Expressions.bucket(width, sourceName);
}
@Override
public Transform truncate(String sourceName, int sourceId, int width) {
return Expressions.apply("truncate", Expressions.column(sourceName), Expressions.literal(width));
}
@Override
public Transform year(String sourceName, int sourceId) {
return Expressions.years(sourceName);
}
@Override
public Transform month(String sourceName, int sourceId) {
return Expressions.months(sourceName);
}
@Override
public Transform day(String sourceName, int sourceId) {
return Expressions.days(sourceName);
}
@Override
public Transform hour(String sourceName, int sourceId) {
return Expressions.hours(sourceName);
}
});
return transforms.toArray(new Transform[0]);
}
/**
* Converts Spark transforms into a {@link PartitionSpec}.
*
* @param schema the table schema
* @param partitioning Spark Transforms
* @return a PartitionSpec
*/
public static PartitionSpec toPartitionSpec(Schema schema, Transform[] partitioning) {
if (partitioning == null || partitioning.length == 0) {
return PartitionSpec.unpartitioned();
}
PartitionSpec.Builder builder = PartitionSpec.builderFor(schema);
for (Transform transform : partitioning) {
Preconditions.checkArgument(transform.references().length == 1,
"Cannot convert transform with more than one column reference: %s", transform);
String colName = DOT.join(transform.references()[0].fieldNames());
switch (transform.name()) {
case "identity":
builder.identity(colName);
break;
case "bucket":
builder.bucket(colName, findWidth(transform));
break;
case "years":
builder.year(colName);
break;
case "months":
builder.month(colName);
break;
case "date":
case "days":
builder.day(colName);
break;
case "date_hour":
case "hours":
builder.hour(colName);
break;
case "truncate":
builder.truncate(colName, findWidth(transform));
break;
default:
throw new UnsupportedOperationException("Transform is not supported: " + transform);
}
}
return builder.build();
}
@SuppressWarnings("unchecked")
private static int findWidth(Transform transform) {
for (Expression expr : transform.arguments()) {
if (expr instanceof Literal) {
if (((Literal) expr).dataType() instanceof IntegerType) {
Literal<Integer> lit = (Literal<Integer>) expr;
Preconditions.checkArgument(lit.value() > 0,
"Unsupported width for transform: %s", transform.describe());
return lit.value();
} else if (((Literal) expr).dataType() instanceof LongType) {
Literal<Long> lit = (Literal<Long>) expr;
Preconditions.checkArgument(lit.value() > 0 && lit.value() < Integer.MAX_VALUE,
"Unsupported width for transform: %s", transform.describe());
if (lit.value() > Integer.MAX_VALUE) {
throw new IllegalArgumentException();
}
return lit.value().intValue();
}
}
}
throw new IllegalArgumentException("Cannot find width for transform: " + transform.describe());
}
private static String leafName(String[] fieldNames) {
Preconditions.checkArgument(fieldNames.length > 0, "Invalid field name: at least one name is required");
return fieldNames[fieldNames.length - 1];
}
private static String peerName(String[] fieldNames, String fieldName) {
if (fieldNames.length > 1) {
String[] peerNames = Arrays.copyOf(fieldNames, fieldNames.length);
peerNames[fieldNames.length - 1] = fieldName;
return DOT.join(peerNames);
}
return fieldName;
}
private static String parentName(String[] fieldNames) {
if (fieldNames.length > 1) {
return DOT.join(Arrays.copyOfRange(fieldNames, 0, fieldNames.length - 1));
}
return null;
}
public static String describe(org.apache.iceberg.expressions.Expression expr) {
return ExpressionVisitors.visit(expr, DescribeExpressionVisitor.INSTANCE);
}
public static String describe(Schema schema) {
return TypeUtil.visit(schema, DescribeSchemaVisitor.INSTANCE);
}
public static String describe(Type type) {
return TypeUtil.visit(type, DescribeSchemaVisitor.INSTANCE);
}
public static boolean isLocalityEnabled(FileIO io, String location, CaseInsensitiveStringMap readOptions) {
InputFile in = io.newInputFile(location);
if (in instanceof HadoopInputFile) {
String scheme = ((HadoopInputFile) in).getFileSystem().getScheme();
return readOptions.getBoolean("locality", LOCALITY_WHITELIST_FS.contains(scheme));
}
return false;
}
public static boolean isVectorizationEnabled(Map<String, String> properties, CaseInsensitiveStringMap readOptions) {
return readOptions.getBoolean("vectorization-enabled",
PropertyUtil.propertyAsBoolean(properties,
TableProperties.PARQUET_VECTORIZATION_ENABLED, TableProperties.PARQUET_VECTORIZATION_ENABLED_DEFAULT));
}
public static int batchSize(Map<String, String> properties, CaseInsensitiveStringMap readOptions) {
return readOptions.getInt("batch-size",
PropertyUtil.propertyAsInt(properties,
TableProperties.PARQUET_BATCH_SIZE, TableProperties.PARQUET_BATCH_SIZE_DEFAULT));
}
public static Long propertyAsLong(CaseInsensitiveStringMap options, String property, Long defaultValue) {
if (defaultValue != null) {
return options.getLong(property, defaultValue);
}
String value = options.get(property);
if (value != null) {
return Long.parseLong(value);
}
return null;
}
public static Integer propertyAsInt(CaseInsensitiveStringMap options, String property, Integer defaultValue) {
if (defaultValue != null) {
return options.getInt(property, defaultValue);
}
String value = options.get(property);
if (value != null) {
return Integer.parseInt(value);
}
return null;
}
public static class DescribeSchemaVisitor extends TypeUtil.SchemaVisitor<String> {
private static final Joiner COMMA = Joiner.on(',');
private static final DescribeSchemaVisitor INSTANCE = new DescribeSchemaVisitor();
private DescribeSchemaVisitor() {
}
@Override
public String schema(Schema schema, String structResult) {
return structResult;
}
@Override
public String struct(Types.StructType struct, List<String> fieldResults) {
return "struct<" + COMMA.join(fieldResults) + ">";
}
@Override
public String field(Types.NestedField field, String fieldResult) {
return field.name() + ": " + fieldResult + (field.isRequired() ? " not null" : "");
}
@Override
public String list(Types.ListType list, String elementResult) {
return "map<" + elementResult + ">";
}
@Override
public String map(Types.MapType map, String keyResult, String valueResult) {
return "map<" + keyResult + ", " + valueResult + ">";
}
@Override
public String primitive(Type.PrimitiveType primitive) {
switch (primitive.typeId()) {
case BOOLEAN:
return "boolean";
case INTEGER:
return "int";
case LONG:
return "bigint";
case FLOAT:
return "float";
case DOUBLE:
return "double";
case DATE:
return "date";
case TIME:
return "time";
case TIMESTAMP:
return "timestamp";
case STRING:
case UUID:
return "string";
case FIXED:
case BINARY:
return "binary";
case DECIMAL:
Types.DecimalType decimal = (Types.DecimalType) primitive;
return "decimal(" + decimal.precision() + "," + decimal.scale() + ")";
}
throw new UnsupportedOperationException("Cannot convert type to SQL: " + primitive);
}
}
private static class DescribeExpressionVisitor extends ExpressionVisitors.ExpressionVisitor<String> {
private static final DescribeExpressionVisitor INSTANCE = new DescribeExpressionVisitor();
private DescribeExpressionVisitor() {
}
@Override
public String alwaysTrue() {
return "true";
}
@Override
public String alwaysFalse() {
return "false";
}
@Override
public String not(String result) {
return "NOT (" + result + ")";
}
@Override
public String and(String leftResult, String rightResult) {
return "(" + leftResult + " AND " + rightResult + ")";
}
@Override
public String or(String leftResult, String rightResult) {
return "(" + leftResult + " OR " + rightResult + ")";
}
@Override
public <T> String predicate(BoundPredicate<T> pred) {
throw new UnsupportedOperationException("Cannot convert bound predicates to SQL");
}
@Override
public <T> String predicate(UnboundPredicate<T> pred) {
switch (pred.op()) {
case IS_NULL:
return pred.ref().name() + " IS NULL";
case NOT_NULL:
return pred.ref().name() + " IS NOT NULL";
case LT:
return pred.ref().name() + " < " + sqlString(pred.literal());
case LT_EQ:
return pred.ref().name() + " <= " + sqlString(pred.literal());
case GT:
return pred.ref().name() + " > " + sqlString(pred.literal());
case GT_EQ:
return pred.ref().name() + " >= " + sqlString(pred.literal());
case EQ:
return pred.ref().name() + " = " + sqlString(pred.literal());
case NOT_EQ:
return pred.ref().name() + " != " + sqlString(pred.literal());
case STARTS_WITH:
return pred.ref().name() + " LIKE '" + pred.literal() + "%'";
case IN:
return pred.ref().name() + " IN (" + sqlString(pred.literals()) + ")";
case NOT_IN:
return pred.ref().name() + " NOT IN (" + sqlString(pred.literals()) + ")";
default:
throw new UnsupportedOperationException("Cannot convert predicate to SQL: " + pred);
}
}
private static <T> String sqlString(List<org.apache.iceberg.expressions.Literal<T>> literals) {
return literals.stream().map(DescribeExpressionVisitor::sqlString).collect(Collectors.joining(", "));
}
private static String sqlString(org.apache.iceberg.expressions.Literal<?> lit) {
if (lit.value() instanceof String) {
return "'" + lit.value() + "'";
} else if (lit.value() instanceof ByteBuffer) {
throw new IllegalArgumentException("Cannot convert bytes to SQL literal: " + lit);
} else {
return lit.value().toString();
}
}
}
}
| 1 | 22,970 | I'm not sure that this should call `allowIncompatibleChanges()` because adding a required column when there are no existing values will break reading the new column in any table with data in it. The only time it is safe to add a required column is if there is no data in the table. What about throwing an exception here instead? I agree that the column should not be optional if NOT NULL was specified. Another alternative is to check whether the table has data and allow the incompatible change if it doesn't have any rows. | apache-iceberg | java |
@@ -154,7 +154,7 @@ class ServiceProvider extends ModuleServiceProvider
*/
WidgetManager::instance()->registerReportWidgets(function($manager){
$manager->registerReportWidget('System\ReportWidgets\Status', [
- 'label' => 'System status',
+ 'label' => Lang::get('backend::lang.dashboard.status.widget_title_default'),
'context' => 'dashboard'
]);
}); | 1 | <?php namespace System;
use App;
use Lang;
use Event;
use Config;
use Backend;
use DbDongle;
use BackendMenu;
use BackendAuth;
use Twig_Environment;
use Twig_Loader_String;
use System\Classes\ErrorHandler;
use System\Classes\MarkupManager;
use System\Classes\PluginManager;
use System\Classes\SettingsManager;
use System\Twig\Engine as TwigEngine;
use System\Twig\Loader as TwigLoader;
use System\Twig\Extension as TwigExtension;
use System\Models\EventLog;
use System\Models\MailSettings;
use System\Models\MailTemplate;
use Backend\Classes\WidgetManager;
use October\Rain\Support\ModuleServiceProvider;
class ServiceProvider extends ModuleServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
/*
* Register self
*/
parent::register('system');
/*
* Register core providers
*/
App::register('October\Rain\Config\ConfigServiceProvider');
App::register('October\Rain\Translation\TranslationServiceProvider');
/*
* Define path constants
*/
if (!defined('PATH_APP')) define('PATH_APP', app_path());
if (!defined('PATH_BASE')) define('PATH_BASE', base_path());
if (!defined('PATH_PUBLIC')) define('PATH_PUBLIC', public_path());
if (!defined('PATH_STORAGE')) define('PATH_STORAGE', storage_path());
if (!defined('PATH_PLUGINS')) define('PATH_PLUGINS', base_path() . Config::get('cms.pluginsDir'));
/*
* Register singletons
*/
App::singleton('string', function(){ return new \October\Rain\Support\Str; });
App::singleton('backend.helper', function(){ return new \Backend\Classes\BackendHelper; });
App::singleton('backend.menu', function() { return \Backend\Classes\NavigationManager::instance(); });
App::singleton('backend.auth', function() { return \Backend\Classes\AuthManager::instance(); });
/*
* Register all plugins
*/
$pluginManager = PluginManager::instance();
$pluginManager->registerAll();
/*
* Error handling for uncaught Exceptions
*/
App::error(function(\Exception $exception, $httpCode){
$handler = new ErrorHandler;
$isConsole = App::runningInConsole();
return $handler->handleException($exception, $httpCode, $isConsole);
});
/*
* Write all log events to the database
*/
Event::listen('illuminate.log', function($level, $message, $context){
if (!DbDongle::hasDatabase())
return;
EventLog::add($message, $level);
});
/*
* Register basic Twig
*/
App::bindShared('twig', function($app) {
$twig = new Twig_Environment(new TwigLoader(), ['auto_reload' => true]);
$twig->addExtension(new TwigExtension);
return $twig;
});
/*
* Register .htm extension for Twig views
*/
App::make('view')->addExtension('htm', 'twig', function() {
return new TwigEngine(App::make('twig'));
});
/*
* Register Twig that will parse strings
*/
App::bindShared('twig.string', function($app) {
$twig = $app['twig'];
$twig->setLoader(new Twig_Loader_String);
return $twig;
});
/*
* Override system mailer with mail settings
*/
Event::listen('mailer.beforeRegister', function() {
if (MailSettings::isConfigured())
MailSettings::applyConfigValues();
});
/*
* Override standard Mailer content with template
*/
Event::listen('mailer.beforeAddContent', function($mailer, $message, $view, $plain, $data){
if (MailTemplate::addContentToMailer($message, $view, $data))
return false;
});
/*
* Register other module providers
*/
foreach (Config::get('cms.loadModules', []) as $module) {
if (strtolower(trim($module)) == 'system') continue;
App::register('\\' . $module . '\ServiceProvider');
}
/*
* Register navigation
*/
BackendMenu::registerCallback(function($manager) {
$manager->registerMenuItems('October.System', [
'system' => [
'label' => 'system::lang.system.menu_label',
'icon' => 'icon-cog',
'url' => Backend::url('system/settings'),
'permissions' => ['backend.manage_users', 'system.*'],
'order' => 1000
]
]);
});
/*
* Register report widgets
*/
WidgetManager::instance()->registerReportWidgets(function($manager){
$manager->registerReportWidget('System\ReportWidgets\Status', [
'label' => 'System status',
'context' => 'dashboard'
]);
});
/*
* Register permissions
*/
BackendAuth::registerCallback(function($manager) {
$manager->registerPermissions('October.System', [
'system.manage_settings' => ['label' => 'system::lang.permissions.manage_system_settings', 'tab' => 'System'],
'system.manage_updates' => ['label' => 'system::lang.permissions.manage_software_updates', 'tab' => 'System'],
'system.manage_mail_templates' => ['label' => 'system::lang.permissions.manage_mail_templates', 'tab' => 'System'],
]);
});
/*
* Register markup tags
*/
MarkupManager::instance()->registerCallback(function($manager){
$manager->registerFunctions([
// Functions
'post' => 'post',
'link_to' => 'link_to',
'link_to_asset' => 'link_to_asset',
'link_to_route' => 'link_to_route',
'link_to_action' => 'link_to_action',
'asset' => 'asset',
'action' => 'action',
'url' => 'url',
'route' => 'route',
'secure_url' => 'secure_url',
'secure_asset' => 'secure_asset',
// Classes
'str_*' => ['Str', '*'],
'url_*' => ['URL', '*'],
'html_*' => ['HTML', '*'],
'form_*' => ['Form', '*'],
'form_macro' => ['Form', '__call'],
]);
$manager->registerFilters([
// Classes
'slug' => ['Str', 'slug'],
'plural' => ['Str', 'plural'],
'singular' => ['Str', 'singular'],
'finish' => ['Str', 'finish'],
'snake' => ['Str', 'snake'],
'camel' => ['Str', 'camel'],
'studly' => ['Str', 'studly'],
'md' => ['October\Rain\Support\Markdown', 'parse'],
]);
});
/*
* Register settings
*/
SettingsManager::instance()->registerCallback(function($manager){
$manager->registerSettingItems('October.System', [
'administrators' => [
'label' => 'backend::lang.user.menu_label',
'description' => 'backend::lang.user.menu_description',
'category' => SettingsManager::CATEGORY_SYSTEM,
'icon' => 'icon-users',
'url' => Backend::url('backend/users'),
'permissions' => ['backend.manage_users'],
'order' => 600
],
'updates' => [
'label' => 'system::lang.updates.menu_label',
'description' => 'system::lang.updates.menu_description',
'category' => SettingsManager::CATEGORY_SYSTEM,
'icon' => 'icon-cloud-download',
'url' => Backend::url('system/updates'),
'permissions' => ['system.manage_updates'],
'order' => 700
],
'event_logs' => [
'label' => 'system::lang.event_log.menu_label',
'description' => 'system::lang.event_log.menu_description',
'category' => SettingsManager::CATEGORY_LOGS,
'icon' => 'icon-exclamation-triangle',
'url' => Backend::url('system/eventlogs'),
'permissions' => ['system.access_event_logs'],
'order' => 800
],
'request_logs' => [
'label' => 'system::lang.request_log.menu_label',
'description' => 'system::lang.request_log.menu_description',
'category' => SettingsManager::CATEGORY_LOGS,
'icon' => 'icon-file-o',
'url' => Backend::url('system/requestlogs'),
'permissions' => ['system.access_request_logs'],
'order' => 800
],
'mail_settings' => [
'label' => 'system::lang.mail.menu_label',
'description' => 'system::lang.mail.menu_description',
'category' => SettingsManager::CATEGORY_MAIL,
'icon' => 'icon-envelope',
'class' => 'System\Models\MailSettings',
'order' => 400,
],
'mail_templates' => [
'label' => 'system::lang.mail_templates.menu_label',
'description' => 'system::lang.mail_templates.menu_description',
'category' => SettingsManager::CATEGORY_MAIL,
'icon' => 'icon-envelope-square',
'url' => Backend::url('system/mailtemplates'),
'order' => 500,
],
]);
});
/*
* Register console commands
*/
$this->registerConsoleCommand('october.up', 'System\Console\OctoberUp');
$this->registerConsoleCommand('october.down', 'System\Console\OctoberDown');
$this->registerConsoleCommand('october.update', 'System\Console\OctoberUpdate');
$this->registerConsoleCommand('october.util', 'System\Console\OctoberUtil');
$this->registerConsoleCommand('plugin.install', 'System\Console\PluginInstall');
$this->registerConsoleCommand('plugin.remove', 'System\Console\PluginRemove');
$this->registerConsoleCommand('plugin.refresh', 'System\Console\PluginRefresh');
/*
* Override clear cache command
*/
App::bindShared('command.cache.clear', function($app) {
return new \System\Console\CacheClear($app['cache'], $app['files']);
});
/*
* Register the sidebar for the System main menu
*/
BackendMenu::registerContextSidenavPartial('October.System', 'system', '@/modules/system/partials/_system_sidebar.htm');
}
/**
* Bootstrap the module events.
*
* @return void
*/
public function boot()
{
/*
* Boot plugins
*/
$pluginManager = PluginManager::instance();
$pluginManager->bootAll();
parent::boot('system');
}
}
| 1 | 10,468 | Early translation , should be logic-less | octobercms-october | php |
@@ -0,0 +1,19 @@
+package proxy
+
+import "net/http"
+
+type interceptor interface {
+ InterceptRequest(*http.Request) (*http.Request, error)
+ InterceptResponse(*http.Response) (*http.Response, error)
+}
+
+type nullInterceptor struct {
+}
+
+func (i nullInterceptor) InterceptRequest(r *http.Request) (*http.Request, error) {
+ return r, nil
+}
+
+func (i nullInterceptor) InterceptResponse(r *http.Response) (*http.Response, error) {
+ return r, nil
+} | 1 | 1 | 8,643 | I don't understand why these functions return a request/response, respectively. In all implementations we actually _modify_ the request/response given as a parameter. Do you envisage situations where we'd want to construct completely fresh request/response objects? Even if we do, it's not something needed atm, so I'd favour in keeping the API minimal. Also, the fact that these functions _may_ mutate the request/response should be noted. | weaveworks-weave | go |
|
@@ -147,8 +147,8 @@ Rails.application.routes.draw do
get 'maintenance', to: 'abouts#maintenance'
get 'tools', to: 'abouts#tools'
- get 'p/compare', to: 'compares#projects', as: :compare_projects
- get 'p/project_graph', to: 'compares#projects_graph', as: :compare_graph_projects
+ get 'p/_compare', to: 'compares#projects', as: :compare_projects
+ get 'p/_project_graph', to: 'compares#projects_graph', as: :compare_graph_projects
get 'projects/:id/stacks', to: 'stacks#project_stacks', constraints: { format: /xml/ }
get 'p/:id/stacks', to: 'stacks#project_stacks', as: :project_stacks, constraints: { format: /xml/ }
get 'p/:id/stacks', to: redirect('/p/%{id}/users'), constraints: { format: /html/ } | 1 | Rails.application.routes.draw do
ActiveAdmin.routes(self)
root to: 'home#index'
use_doorkeeper do
skip_controllers :applications, :authorized_applications
end
resources :sessions, only: [:new, :create] do
collection do
delete :destroy
end
end
resources :stack_entries, only: :new
resources :password_resets, as: :password_reset, only: [:new, :create] do
collection do
get :confirm
patch :reset
end
end
resources :activation_resends, only: [:new, :create]
resources :api_keys, only: :index
resources :domain_blacklists, except: :show
resources :reviews, only: :destroy do
resources :helpfuls, only: :create
end
resources :kudos, only: [:new, :create, :destroy]
resources :people, only: [:index] do
collection { get :rankings }
end
resources :edits, only: [:update]
resources :licenses do
resources :edits, only: [:index]
end
resources :tags, only: [:index, :show]
resources :accounts do
resources :api_keys, constraints: { format: :html }
resources :projects, only: [:index]
resources :positions, only: [:index] do
member do
get :commits_compound_spark
end
collection do
get :one_click_create
end
end
resources :stacks, only: [:index]
resources :account_widgets, path: :widgets, as: :widgets, only: :index do
collection do
get :account_detailed, action: :detailed, as: :detailed
get :account_tiny, action: :tiny, as: :tiny
get :account_rank, action: :rank, as: :rank
end
end
resources :kudos, only: [:index, :show] do
collection do
get :sent
end
end
resources :edits, only: [:index]
resources :posts, only: [:index]
resources :reviews, only: [:index]
resources :positions
resources :position_factories, only: :create
member do
get :confirm_delete
get :disabled
get :settings
get 'password/edit', to: 'passwords#edit'
patch 'password/edit', to: 'passwords#update'
get :edit_privacy, to: 'privacy#edit', as: :edit_account_privacy
patch :edit_privacy, to: 'privacy#update', as: :account_privacy
end
collection do
get :me
get :unsubscribe_emails
end
resources :charts, only: [], module: :accounts do
collection do
get :commits_by_project
get :commits_by_language
get :commits_by_individual_project
end
end
resources :languages, only: :index, module: :accounts
resources :accesses, only: [], module: :accounts do
collection do
post :make_spammer
get :activate
end
end
get 'doorkeeper/oauth_applications/:id/revoke_access' =>
'doorkeeper/oauth_applications#revoke_access', as: :revoke_oauth_access
end
resources :deleted_accounts, only: [:edit, :update]
resources :check_availabilities, only: [] do
collection do
get :account
get :project
get :organization
get :license
end
end
resources :searches, only: [] do
collection do
get :account
end
end
resources :autocompletes, only: [] do
collection do
get :account
get :project
get :licenses
get :contributions
get :tags
end
end
resources :forums do
resources :topics, shallow: true
resources :topics, only: [:show]
end
resources :topics, except: [:index, :new, :create] do
resources :posts, except: [:new]
end
resources :posts, only: :index, as: 'all_posts'
get 'markdown_syntax', to: 'abouts#markdown_syntax'
get 'maintenance', to: 'abouts#maintenance'
get 'tools', to: 'abouts#tools'
get 'p/compare', to: 'compares#projects', as: :compare_projects
get 'p/project_graph', to: 'compares#projects_graph', as: :compare_graph_projects
get 'projects/:id/stacks', to: 'stacks#project_stacks', constraints: { format: /xml/ }
get 'p/:id/stacks', to: 'stacks#project_stacks', as: :project_stacks, constraints: { format: /xml/ }
get 'p/:id/stacks', to: redirect('/p/%{id}/users'), constraints: { format: /html/ }
get 'projects', to: 'projects#index', as: :project_xml_api, constraints: { format: /xml/ }
get 'projects/:project_id/badge_js', to: 'project_widgets#thin_badge', defaults: { format: 'js' }
get 'projects/:project_id/badge.:format', to: 'project_widgets#thin_badge'
get 'p/:project_id/badge_js', to: 'project_widgets#thin_badge', defaults: { format: 'js' }
get 'p/:project_id/badge.:format', to: 'project_widgets#thin_badge'
resources :duplicates, only: [:index, :show] do
member do
post 'resolve/:keep_id', to: 'duplicates#resolve'
end
end
resources :projects, path: :p, except: [:destroy] do
member do
get :users
get :map
get :settings
get :estimated_cost
get :similar_by_tags
get :similar
get 'permissions' => 'permissions#show', as: :permissions
put 'permissions' => 'permissions#update', as: :update_permissions
post 'rate' => 'ratings#rate', as: :rate
delete 'unrate' => 'ratings#unrate', as: :unrate
end
collection do
post :check_forge
end
resources :contributions, path: :contributors, as: :contributors, only: [:index, :show] do
resources :commits
collection do
get :near
get :summary
end
member do
get :commits_compound_spark
get :commits_spark
end
end
resources :rss_subscriptions
resources :licenses, controller: :project_licenses, only: [:index, :new, :create, :destroy]
resources :tags, controller: :project_tags, only: [:index, :create, :destroy] do
collection do
get :related
get :status
end
end
resources :duplicates, except: [:show, :index]
resource :logos, only: [:new, :create, :destroy]
resources :links, except: :show
resources :managers, only: [:index, :new, :create, :edit, :update] do
member do
post :approve
post :reject
end
end
resources :manages, only: [:new]
resources :edits, only: [:index]
resources :enlistments
resources :factoids, only: [:index]
resources :rss_articles, only: :index
resources :project_widgets, path: :widgets, as: :widgets, only: :index do
collection do
get :project_factoids, action: :factoids, as: :factoids
get :project_factoids_stats, action: :factoids_stats, as: :factoids_stats
get :project_basic_stats, action: :basic_stats, as: :basic_stats
get :project_users, action: :users, as: :users
get :project_users_logo, action: :users_logo, as: :users_logo
get :project_search_code, action: :search_code, as: :search_code
get :project_browse_code, action: :browse_code, as: :browse_code
get :project_search_all_code, action: :search_all_code, as: :search_all_code
get :project_languages, action: :languages, as: :languages
get :project_partner_badge, action: :partner_badge, as: :partner_badge
get :project_thin_badge, action: :thin_badge, as: :thin_badge
get :project_cocomo, action: :cocomo, as: :cocomo
end
end
resources :ratings
resources :reviews, except: :show do
collection { get :summary }
resources :helpfuls, only: :create
end
resources :analyses, only: [:index, :show] do
member do
get :languages_summary
get :languages
get :licenses
get :top_commit_volume_chart
get :commits_history
get :committer_history
get :contributor_summary
get :language_history
get :code_history
get :lines_of_code
get :commits_spark
end
resources :activity_facts, only: :index
resources :size_facts, only: :index
end
resources :commits, only: [:index, :show] do
collection { get :summary }
member do
get :statistics
get :events
get :event_details
end
end
resources :contributors do
member do
get :event_details
get :events
end
end
resources :stacks, only: [] do
collection { get :near }
end
resources :aliases, only: [:index, :new, :create] do
collection { get :preferred_names }
member do
post :undo
post :redo
end
end
end
resources :organizations, path: :orgs do
member do
get :settings
get :projects
get :outside_projects
get :outside_committers
get :print_infographic
get :affiliated_committers
get :list_managers
get :claim_projects_list
get :claim_project
put :remove_project
match :new_manager, via: [:get, :post]
get :manage_projects
end
collection do
get :resolve_url_name
end
resources :edits, only: [:index]
resource :logos, only: [:new, :create, :destroy]
resources :managers, only: [:index, :new, :create, :edit, :update] do
member do
post :approve
post :reject
end
end
resources :organization_widgets, path: :widgets, as: :widgets, only: :index do
collection do
get :affiliated_committers_activity
get :open_source_activity
get :portfolio_projects_activity
end
end
end
resources :stacks, only: [:show, :create, :update, :destroy] do
member do
get :similar
get :similar_stacks
get :builder
get :reset
end
resources :stack_entries, only: [:show, :create, :update, :destroy]
resources :stack_ignores, only: [:create] do
collection do
delete :delete_all
end
end
resources :stack_widgets, path: :widgets, as: :widgets, only: :index do
collection do
get :stack_normal, action: :normal, as: :normal
end
end
end
resources :languages, only: [:show, :index] do
collection do
get :compare
get :chart
end
end
resources :contributors, controller: 'contributions' do
resources :invites, only: [:new, :create]
end
resources :explores, only: :index, path: :explore, controller: :explore do
collection do
get :orgs
get :projects
get :demographic_chart
get :orgs_by_thirty_day_commit_volume, defaults: { format: 'js' }
end
end
get 'maintenance' => 'home#maintenance'
get 'repositories/compare' => 'compare_repositories#index', as: :compare_repositories
get 'repositories/chart' => 'compare_repositories#chart', as: :compare_repositories_chart
get 'server_info' => 'home#server_info'
resources :committers, only: [:index, :show] do
member do
post :claim
post :save_claim
end
end
resources :session_projects, only: [:index, :create, :destroy]
get 'sitemap_index.xml', controller: 'sitemap', action: 'index', format: 'xml'
get 'sitemaps/:ctrl/:page.xml', controller: 'sitemap', action: 'show', format: 'xml'
# the unmatched_route must be last as it matches everything
match '*unmatched_route', to: 'application#raise_not_found!', via: :all
end
| 1 | 8,006 | Wasn't there a subsequent reason why we had to keep the `/p/project_graph` route? Outside references or is the proposed solution to the original proposal we us `/p/g` as the `compares#project_graph` route? | blackducksoftware-ohloh-ui | rb |
@@ -44,6 +44,14 @@ public class GenTest {
assertThat(gen.apply(RANDOM)).isEqualTo(3);
}
+ @Test
+ public void shouldCreateGenOfFixedValues() {
+ final Gen<Integer> gen = Gen.fixed(1,2,3);
+ assertThat(gen.apply(RANDOM)).isIn(1,2,3);
+ assertThat(gen.apply(RANDOM)).isIn(1,2,3);
+ assertThat(gen.apply(RANDOM)).isIn(1,2,3);
+ }
+
// -- random number generator (rng)
@Test | 1 | /* / \____ _ _ ____ ______ / \ ____ __ _______
* / / \/ \ / \/ \ / /\__\/ // \/ \ // /\__\ JΛVΛSLΛNG
* _/ / /\ \ \/ / /\ \\__\\ \ // /\ \ /\\/ \ /__\ \ Copyright 2014-2016 Javaslang, http://javaslang.io
* /___/\_/ \_/\____/\_/ \_/\__\/__/\__\_/ \_// \__/\_____/ Licensed under the Apache License, Version 2.0
*/
package javaslang.test;
import javaslang.Tuple;
import javaslang.Tuple2;
import javaslang.collection.List;
import javaslang.collection.Stream;
import org.junit.Test;
import java.util.Arrays;
import java.util.Random;
import java.util.function.Predicate;
import java.util.function.Supplier;
import static org.assertj.core.api.Assertions.assertThat;
public class GenTest {
// equally distributed random number generator
static final Random RANDOM = new Random();
// number of tries to assert a property
static final int TRIES = 1000;
// -- of
@Test
public void shouldCreateConstantGenOfElement() {
final Gen<Integer> gen = Gen.of(1);
assertThat(gen.apply(RANDOM)).isEqualTo(1);
assertThat(gen.apply(RANDOM)).isEqualTo(1);
assertThat(gen.apply(RANDOM)).isEqualTo(1);
}
@Test
public void shouldCreateGenOfSeedAndFunction() {
final Gen<Integer> gen = Gen.of(1, i -> i + 1);
assertThat(gen.apply(RANDOM)).isEqualTo(1);
assertThat(gen.apply(RANDOM)).isEqualTo(2);
assertThat(gen.apply(RANDOM)).isEqualTo(3);
}
// -- random number generator (rng)
@Test
public void shouldUseCustomRandomNumberGenerator() {
final Random rng = new Random() {
private static final long serialVersionUID = 1L;
@Override
public int nextInt(int bound) {
return 0;
}
};
final Gen<Integer> gen = Gen.choose(1, 2);
final Number actual = Stream.continually(() -> gen.apply(rng)).take(10).sum();
assertThat(actual).isEqualTo(10L);
}
// -- choose(int, int)
@Test
public void shouldChooseIntBetweenMinMax() {
assertForAll(() -> Gen.choose(-1, 1).apply(RANDOM), i -> i >= -1 && i <= 1);
}
@Test
public void shouldChooseIntWhenMinEqualsMax() {
assertForAll(() -> Gen.choose(0, 0).apply(RANDOM), i -> i == 0);
}
// -- choose(long, long)
@Test
public void shouldChooseLongBetweenMinMax() {
assertForAll(() -> Gen.choose(-1L, 1L).apply(RANDOM), l -> l >= -1L && l <= 1L);
}
@Test
public void shouldChooseLongWhenMinEqualsMax() {
assertForAll(() -> Gen.choose(0L, 0L).apply(RANDOM), l -> l == 0L);
}
// -- choose(double, double)
@Test
public void shouldChooseDoubleBetweenMinMax() {
assertForAll(() -> Gen.choose(-1.0d, 1.0d).apply(RANDOM), d -> d >= -1.0d && d <= 1.0d);
}
@Test
public void shouldChooseDoubleWhenMinEqualsMax() {
assertForAll(() -> Gen.choose(0.0d, 0.0d).apply(RANDOM), d -> d == 0.0d);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowWhenChooseDoubleAndMinIsNegativeInfinite() {
Gen.choose(Double.NEGATIVE_INFINITY, 0.0d);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowWhenChooseDoubleAndMinIsPositiveInfinite() {
Gen.choose(Double.POSITIVE_INFINITY, 0.0d);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowWhenChooseDoubleAndMinIsNotANumber() {
Gen.choose(Double.NaN, 0.0d);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowWhenChooseDoubleAndMaxIsNegativeInfinite() {
Gen.choose(0.0d, Double.NEGATIVE_INFINITY);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowWhenChooseDoubleAndMaxIsPositiveInfinite() {
Gen.choose(0.0d, Double.POSITIVE_INFINITY);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowWhenChooseDoubleAndMaxIsNotANumber() {
Gen.choose(0.0d, Double.NaN);
}
// -- choose(char, char)
@Test
public void shouldChooseCharBetweenMinMax() {
assertForAll(() -> Gen.choose('A', 'Z').apply(RANDOM), c -> c >= 'A' && c <= 'Z');
}
@Test
public void shouldChooseCharWhenMinEqualsMax() {
assertForAll(() -> Gen.choose('λ', 'λ').apply(RANDOM), c -> c == 'λ');
}
// -- choose(array)
@Test
public void shouldChooseFromASingleArray() throws Exception {
Integer[] i = {1};
assertForAll(() -> Gen.choose(i).apply(RANDOM), c -> c == 1);
}
@Test(expected = RuntimeException.class)
public void shouldFailOnEmptyArray() throws Exception {
Integer[] i = {};
Gen.choose(i).apply(RANDOM);
}
// -- Choose(enum)
enum testEnum {
value1
}
@Test
public void shouldChooseFromEnum() throws Exception {
assertForAll(() -> Gen.choose(testEnum.class).apply(RANDOM), e -> Arrays.asList(testEnum.values()).contains(e));
}
// -- Choose(iterable)
@Test
public void shouldChooseFromIterable() throws Exception {
List<Integer> i = List.of(1);
assertForAll(() -> Gen.choose(i).apply(RANDOM), c -> c == 1);
}
@Test(expected = RuntimeException.class)
public void shouldFailOnEmptyIterable() throws Exception {
List<Integer> i = List.empty();
Gen.choose(i).apply(RANDOM);
}
// -- fail
@Test(expected = RuntimeException.class)
public void shouldFailAlwaysWhenCallingFailingGen() {
Gen.fail().apply(RANDOM);
}
// -- frequency(VarArgs)
@Test(expected = NullPointerException.class)
public void shouldThrowWhenCallingFrequencyOfVarArgsAndArgIsNull() {
Gen.frequency((Tuple2<Integer, Gen<Object>>) null);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowWhenCallingFrequencyOfVarArgsAndArgIsEmpty() {
@SuppressWarnings("unchecked")
final Tuple2<Integer, Gen<Object>>[] empty = (Tuple2<Integer, Gen<Object>>[]) new Tuple2<?, ?>[0];
Gen.frequency(empty);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowWhenCallingFrequencyOfVarArgsAndFrequenceIsNegative() {
final Gen<Integer> gen = Gen.frequency(Tuple.of(-1, Gen.of(-1)));
gen.apply(RANDOM);
}
@Test
public void shouldGenerateElementsAccordingToFrequencyGivenVarArgs() {
final Gen<Integer> gen = Gen.frequency(Tuple.of(0, Gen.of(-1)), Tuple.of(1, Gen.of(1)));
assertForAll(() -> gen.apply(RANDOM), i -> i != -1);
}
// -- frequency(Iterable)
@Test(expected = NullPointerException.class)
public void shouldThrowWhenCallingFrequencyOfIterableAndArgIsNull() {
Gen.frequency((Iterable<Tuple2<Integer, Gen<Object>>>) null);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowWhenCallingFrequencyOfIterableAndArgIsEmpty() {
Gen.frequency(List.empty());
}
@Test
public void shouldGenerateElementsAccordingToFrequencyGivenAnIterable() {
final Gen<Integer> gen = Gen.frequency(List.of(Tuple.of(0, Gen.of(-1)), Tuple.of(1, Gen.of(1))));
assertForAll(() -> gen.apply(RANDOM), i -> i != -1);
}
// -- oneOf(VarArgs)
@Test(expected = NullPointerException.class)
public void shouldThrowWhenCallingOneOfAndVarArgsIsNull() {
Gen.oneOf((Gen<Object>[]) null);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowWhenCallingOneOfAndVarArgsIsEmpty() {
@SuppressWarnings("unchecked")
final Gen<Object>[] empty = (Gen<Object>[]) new Gen<?>[0];
Gen.oneOf(empty);
}
@Test
public void shouldReturnOneOfGivenVarArgs() {
final Gen<Integer> gen = Gen.oneOf(Gen.of(1), Gen.of(2));
assertForAll(() -> gen.apply(RANDOM), i -> i == 1 || i == 2);
}
// -- oneOf(Iterable)
@Test(expected = NullPointerException.class)
public void shouldThrowWhenCallingOneOfAndIterableIsNull() {
Gen.oneOf((Iterable<Gen<Object>>) null);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowWhenCallingOneOfAndIterableIsEmpty() {
Gen.oneOf(List.empty());
}
@Test
public void shouldReturnOneOfGivenIterable() {
final Gen<Integer> gen = Gen.oneOf(List.of(Gen.of(1), Gen.of(2)));
assertForAll(() -> gen.apply(RANDOM), i -> i == 1 || i == 2);
}
// -- arbitrary
@Test
public void shouldConvertGenToArbitrary() {
assertThat(Gen.of(1).arbitrary()).isInstanceOf(Arbitrary.class);
}
// -- map
@Test(expected = NullPointerException.class)
public void shouldThrowWhenCallingMapWithNullArg() {
Gen.of(1).map(null);
}
@Test
public void shouldMapGen() {
final Gen<Integer> gen = Gen.of(1).map(i -> i * 2);
assertForAll(() -> gen.apply(RANDOM), i -> i % 2 == 0);
}
// -- flatMap
@Test(expected = NullPointerException.class)
public void shouldThrowWhenCallingFlatMapWithNullArg() {
Gen.of(1).flatMap(null);
}
@Test
public void shouldFlatMapGen() {
final Gen<Integer> gen = Gen.of(1).flatMap(i -> Gen.of(i * 2));
assertForAll(() -> gen.apply(RANDOM), i -> i % 2 == 0);
}
// -- filter
@Test(expected = NullPointerException.class)
public void shouldThrowWhenCallingFilterWithNullArg() {
Gen.of(1).filter(null);
}
@Test
public void shouldFilterGenerator() {
final Gen<Integer> gen = Gen.choose(1, 2).filter(i -> i % 2 == 0);
assertForAll(() -> gen.apply(RANDOM), i -> i == 2);
}
@Test(expected = IllegalStateException.class)
public void shouldDetectEmptyFilter() {
Gen.of(1).filter(ignored -> false).apply(RANDOM);
}
// -- peek
@Test
public void shouldPeekArbitrary() {
final int[] actual = new int[] { -1 };
final int expected = Gen.of(1).peek(i -> actual[0] = i).apply(new Random());
assertThat(actual[0]).isEqualTo(expected);
}
// -- transform
@Test
public void shouldTransformGen() {
final String s = Gen.of(1).transform(gen -> gen.apply(RANDOM).toString());
assertThat(s).isEqualTo("1");
}
// helpers
<T> void assertForAll(Supplier<T> supplier, Predicate<T> property) {
for (int i = 0; i < TRIES; i++) {
final T element = supplier.get();
if (!property.test(element)) {
throw new AssertionError("predicate did not hold for " + element);
}
}
}
}
| 1 | 7,612 | Any suggestions on how I would even _approach_ writing tests for arbitrary values.... | vavr-io-vavr | java |
@@ -46,8 +46,8 @@ class Theme
*/
protected static $editThemeCache = false;
- const ACTIVE_KEY = 'cms::theme.active';
- const EDIT_KEY = 'cms::theme.edit';
+ private const ACTIVE_KEY = 'cms::theme.active';
+ private const EDIT_KEY = 'cms::theme.edit';
/**
* Loads the theme. | 1 | <?php namespace Cms\Classes;
use App;
use Url;
use File;
use Yaml;
use Lang;
use Cache;
use Event;
use Config;
use Cms\Models\ThemeData;
use System\Models\Parameter;
use October\Rain\Halcyon\Datasource\FileDatasource;
use ApplicationException;
use SystemException;
use DirectoryIterator;
use Exception;
/**
* This class represents the CMS theme.
* CMS theme is a directory that contains all CMS objects - pages, layouts, partials and asset files..
* The theme parameters are specified in the theme.ini file in the theme root directory.
*
* @package october\cms
* @author Alexey Bobkov, Samuel Georges
*/
class Theme
{
/**
* @var string Specifies the theme directory name.
*/
protected $dirName;
/**
* @var mixed Keeps the cached configuration file values.
*/
protected $configCache = null;
/**
* @var mixed Active theme cache in memory
*/
protected static $activeThemeCache = false;
/**
* @var mixed Edit theme cache in memory
*/
protected static $editThemeCache = false;
const ACTIVE_KEY = 'cms::theme.active';
const EDIT_KEY = 'cms::theme.edit';
/**
* Loads the theme.
* @return self
*/
public static function load($dirName)
{
$theme = new static;
$theme->setDirName($dirName);
$theme->registerHalyconDatasource();
return $theme;
}
/**
* Returns the absolute theme path.
* @param string $dirName Optional theme directory. Defaults to $this->getDirName()
* @return string
*/
public function getPath($dirName = null)
{
if (!$dirName) {
$dirName = $this->getDirName();
}
return themes_path().'/'.$dirName;
}
/**
* Sets the theme directory name.
* @return void
*/
public function setDirName($dirName)
{
$this->dirName = $dirName;
}
/**
* Returns the theme directory name.
* @return string
*/
public function getDirName()
{
return $this->dirName;
}
/**
* Helper for {{ theme.id }} twig vars
* Returns a unique string for this theme.
* @return string
*/
public function getId()
{
return snake_case(str_replace('/', '-', $this->getDirName()));
}
/**
* Determines if a theme with given directory name exists
* @param string $dirName The theme directory
* @return bool
*/
public static function exists($dirName)
{
$theme = static::load($dirName);
$path = $theme->getPath();
return File::isDirectory($path);
}
/**
* Returns a list of pages in the theme.
* This method is used internally in the routing process and in the back-end UI.
* @param boolean $skipCache Indicates if the pages should be reloaded from the disk bypassing the cache.
* @return array Returns an array of \Cms\Classes\Page objects.
*/
public function listPages($skipCache = false)
{
return Page::listInTheme($this, $skipCache);
}
/**
* Returns true if this theme is the chosen active theme.
*/
public function isActiveTheme()
{
$activeTheme = self::getActiveTheme();
return $activeTheme && $activeTheme->getDirName() == $this->getDirName();
}
/**
* Returns the active theme code.
* By default the active theme is loaded from the cms.activeTheme parameter,
* but this behavior can be overridden by the cms.theme.getActiveTheme event listener.
* @return string
* If the theme doesn't exist, returns null.
*/
public static function getActiveThemeCode()
{
$activeTheme = Config::get('cms.activeTheme');
if (App::hasDatabase()) {
try {
try {
$dbResult = Cache::remember(self::ACTIVE_KEY, 1440, function () {
return Parameter::applyKey(self::ACTIVE_KEY)->value('value');
});
}
catch (Exception $ex) {
// Cache failed
$dbResult = Parameter::applyKey(self::ACTIVE_KEY)->value('value');
}
}
catch (Exception $ex) {
// Database failed
$dbResult = null;
}
if ($dbResult !== null && static::exists($dbResult)) {
$activeTheme = $dbResult;
}
}
/**
* @event cms.theme.getActiveTheme
* Overrides the active theme code.
*
* If a value is returned from this halting event, it will be used as the active
* theme code. Example usage:
*
* Event::listen('cms.theme.getActiveTheme', function() { return 'mytheme'; });
*
*/
$apiResult = Event::fire('cms.theme.getActiveTheme', [], true);
if ($apiResult !== null) {
$activeTheme = $apiResult;
}
if (!strlen($activeTheme)) {
throw new SystemException(Lang::get('cms::lang.theme.active.not_set'));
}
return $activeTheme;
}
/**
* Returns the active theme object.
* @return \Cms\Classes\Theme Returns the loaded theme object.
* If the theme doesn't exist, returns null.
*/
public static function getActiveTheme()
{
if (self::$activeThemeCache !== false) {
return self::$activeThemeCache;
}
$theme = static::load(static::getActiveThemeCode());
if (!File::isDirectory($theme->getPath())) {
return self::$activeThemeCache = null;
}
return self::$activeThemeCache = $theme;
}
/**
* Sets the active theme.
* The active theme code is stored in the database and overrides the configuration cms.activeTheme parameter.
* @param string $code Specifies the active theme code.
*/
public static function setActiveTheme($code)
{
self::resetCache();
Parameter::set(self::ACTIVE_KEY, $code);
Event::fire('cms.theme.setActiveTheme', compact('code'));
}
/**
* Returns the edit theme code.
* By default the edit theme is loaded from the cms.editTheme parameter,
* but this behavior can be overridden by the cms.theme.getEditTheme event listeners.
* If the edit theme is not defined in the configuration file, the active theme
* is returned.
* @return string
*/
public static function getEditThemeCode()
{
$editTheme = Config::get('cms.editTheme');
if (!$editTheme) {
$editTheme = static::getActiveThemeCode();
}
$apiResult = Event::fire('cms.theme.getEditTheme', [], true);
if ($apiResult !== null) {
$editTheme = $apiResult;
}
if (!strlen($editTheme)) {
throw new SystemException(Lang::get('cms::lang.theme.edit.not_set'));
}
return $editTheme;
}
/**
* Returns the edit theme.
* @return \Cms\Classes\Theme Returns the loaded theme object.
*/
public static function getEditTheme()
{
if (self::$editThemeCache !== false) {
return self::$editThemeCache;
}
$theme = static::load(static::getEditThemeCode());
if (!File::isDirectory($theme->getPath())) {
return self::$editThemeCache = null;
}
return self::$editThemeCache = $theme;
}
/**
* Returns a list of all themes.
* @return array Returns an array of the Theme objects.
*/
public static function all()
{
$it = new DirectoryIterator(themes_path());
$it->rewind();
$result = [];
foreach ($it as $fileinfo) {
if (!$fileinfo->isDir() || $fileinfo->isDot()) {
continue;
}
$theme = static::load($fileinfo->getFilename());
$result[] = $theme;
}
return $result;
}
/**
* Reads the theme.yaml file and returns the theme configuration values.
* @return array Returns the parsed configuration file values.
*/
public function getConfig()
{
if ($this->configCache !== null) {
return $this->configCache;
}
$path = $this->getPath().'/theme.yaml';
if (!File::exists($path)) {
return $this->configCache = [];
}
return $this->configCache = Yaml::parseFile($path);
}
/**
* Returns a value from the theme configuration file by its name.
* @param string $name Specifies the configuration parameter name.
* @param mixed $default Specifies the default value to return in case if the parameter
* doesn't exist in the configuration file.
* @return mixed Returns the parameter value or a default value
*/
public function getConfigValue($name, $default = null)
{
return array_get($this->getConfig(), $name, $default);
}
/**
* Returns an array value from the theme configuration file by its name.
* If the value is a string, it is treated as a YAML file and loaded.
* @param string $name Specifies the configuration parameter name.
* @return array
*/
public function getConfigArray($name)
{
$result = array_get($this->getConfig(), $name, []);
if (is_string($result)) {
$fileName = File::symbolizePath($result);
if (File::isLocalPath($fileName) || realpath($fileName) !== false) {
$path = $fileName;
}
else {
$path = $this->getPath().'/'.$result;
}
if (!File::exists($path)) {
throw new ApplicationException('Path does not exist: '.$path);
}
$result = Yaml::parseFile($path);
}
return (array) $result;
}
/**
* Writes to the theme.yaml file with the supplied array values.
* @param array $values Data to write
* @param array $overwrite If true, undefined values are removed.
* @return void
*/
public function writeConfig($values = [], $overwrite = false)
{
if (!$overwrite) {
$values = $values + (array) $this->getConfig();
}
$path = $this->getPath().'/theme.yaml';
if (!File::exists($path)) {
throw new ApplicationException('Path does not exist: '.$path);
}
$contents = Yaml::render($values);
File::put($path, $contents);
$this->configCache = $values;
}
/**
* Returns the theme preview image URL.
* If the image file doesn't exist returns the placeholder image URL.
* @return string Returns the image URL.
*/
public function getPreviewImageUrl()
{
$previewPath = $this->getConfigValue('previewImage', 'assets/images/theme-preview.png');
if (File::exists($this->getPath().'/'.$previewPath)) {
return Url::asset('themes/'.$this->getDirName().'/'.$previewPath);
}
return Url::asset('modules/cms/assets/images/default-theme-preview.png');
}
/**
* Resets any memory or cache involved with the active or edit theme.
* @return void
*/
public static function resetCache()
{
self::$activeThemeCache = false;
self::$editThemeCache = false;
Cache::forget(self::ACTIVE_KEY);
Cache::forget(self::EDIT_KEY);
}
/**
* Returns true if this theme has form fields that supply customization data.
* @return bool
*/
public function hasCustomData()
{
return $this->getConfigValue('form', false);
}
/**
* Returns data specific to this theme
* @return Cms\Models\ThemeData
*/
public function getCustomData()
{
return ThemeData::forTheme($this);
}
/**
* Ensures this theme is registered as a Halcyon them datasource.
* @return void
*/
public function registerHalyconDatasource()
{
$resolver = App::make('halcyon');
if (!$resolver->hasDatasource($this->dirName)) {
$datasource = new FileDatasource($this->getPath(), App::make('files'));
$resolver->addDatasource($this->dirName, $datasource);
}
}
/**
* Implements the getter functionality.
* @param string $name
* @return void
*/
public function __get($name)
{
if ($this->hasCustomData()) {
$theme = $this->getCustomData();
return $theme->{$name};
}
return null;
}
/**
* Determine if an attribute exists on the object.
* @param string $key
* @return void
*/
public function __isset($key)
{
if ($this->hasCustomData()) {
$theme = $this->getCustomData();
return $theme->offsetExists($key);
}
return false;
}
}
| 1 | 12,955 | Scope declarations for class constants was not added until 7.1, this will not be accepted. | octobercms-october | php |
@@ -126,9 +126,11 @@ void TThreadedServer::onClientDisconnected(TConnectedClient* pClient) {
Synchronized sync(clientMonitor_);
drainDeadClients(); // use the outgoing thread to do some maintenance on our dead client backlog
ClientMap::iterator it = activeClientMap_.find(pClient);
- ClientMap::iterator end = it;
- deadClientMap_.insert(it, ++end);
- activeClientMap_.erase(it);
+ if (it != activeClientMap_.end()) {
+ ClientMap::iterator end = it;
+ deadClientMap_.insert(it, ++end);
+ activeClientMap_.erase(it);
+ }
if (activeClientMap_.empty()) {
clientMonitor_.notify();
} | 1 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
#include <string>
#include <thrift/stdcxx.h>
#include <thrift/concurrency/PlatformThreadFactory.h>
#include <thrift/server/TThreadedServer.h>
namespace apache {
namespace thrift {
namespace server {
using apache::thrift::concurrency::Runnable;
using apache::thrift::concurrency::Synchronized;
using apache::thrift::concurrency::Thread;
using apache::thrift::concurrency::ThreadFactory;
using apache::thrift::protocol::TProtocol;
using apache::thrift::protocol::TProtocolFactory;
using apache::thrift::stdcxx::make_shared;
using apache::thrift::stdcxx::shared_ptr;
using apache::thrift::transport::TServerTransport;
using apache::thrift::transport::TTransport;
using apache::thrift::transport::TTransportException;
using apache::thrift::transport::TTransportFactory;
TThreadedServer::TThreadedServer(const shared_ptr<TProcessorFactory>& processorFactory,
const shared_ptr<TServerTransport>& serverTransport,
const shared_ptr<TTransportFactory>& transportFactory,
const shared_ptr<TProtocolFactory>& protocolFactory,
const shared_ptr<ThreadFactory>& threadFactory)
: TServerFramework(processorFactory, serverTransport, transportFactory, protocolFactory),
threadFactory_(threadFactory) {
}
TThreadedServer::TThreadedServer(const shared_ptr<TProcessor>& processor,
const shared_ptr<TServerTransport>& serverTransport,
const shared_ptr<TTransportFactory>& transportFactory,
const shared_ptr<TProtocolFactory>& protocolFactory,
const shared_ptr<ThreadFactory>& threadFactory)
: TServerFramework(processor, serverTransport, transportFactory, protocolFactory),
threadFactory_(threadFactory) {
}
TThreadedServer::TThreadedServer(const shared_ptr<TProcessorFactory>& processorFactory,
const shared_ptr<TServerTransport>& serverTransport,
const shared_ptr<TTransportFactory>& inputTransportFactory,
const shared_ptr<TTransportFactory>& outputTransportFactory,
const shared_ptr<TProtocolFactory>& inputProtocolFactory,
const shared_ptr<TProtocolFactory>& outputProtocolFactory,
const shared_ptr<ThreadFactory>& threadFactory)
: TServerFramework(processorFactory,
serverTransport,
inputTransportFactory,
outputTransportFactory,
inputProtocolFactory,
outputProtocolFactory),
threadFactory_(threadFactory) {
}
TThreadedServer::TThreadedServer(const shared_ptr<TProcessor>& processor,
const shared_ptr<TServerTransport>& serverTransport,
const shared_ptr<TTransportFactory>& inputTransportFactory,
const shared_ptr<TTransportFactory>& outputTransportFactory,
const shared_ptr<TProtocolFactory>& inputProtocolFactory,
const shared_ptr<TProtocolFactory>& outputProtocolFactory,
const shared_ptr<ThreadFactory>& threadFactory)
: TServerFramework(processor,
serverTransport,
inputTransportFactory,
outputTransportFactory,
inputProtocolFactory,
outputProtocolFactory),
threadFactory_(threadFactory) {
}
TThreadedServer::~TThreadedServer() {
}
void TThreadedServer::serve() {
TServerFramework::serve();
// Ensure post-condition of no active clients
Synchronized s(clientMonitor_);
while (!activeClientMap_.empty()) {
clientMonitor_.wait();
}
drainDeadClients();
}
void TThreadedServer::drainDeadClients() {
// we're in a monitor here
while (!deadClientMap_.empty()) {
ClientMap::iterator it = deadClientMap_.begin();
it->second->join();
deadClientMap_.erase(it);
}
}
void TThreadedServer::onClientConnected(const shared_ptr<TConnectedClient>& pClient) {
Synchronized sync(clientMonitor_);
shared_ptr<TConnectedClientRunner> pRunnable = make_shared<TConnectedClientRunner>(pClient);
shared_ptr<Thread> pThread = threadFactory_->newThread(pRunnable);
pRunnable->thread(pThread);
activeClientMap_.insert(ClientMap::value_type(pClient.get(), pThread));
pThread->start();
}
void TThreadedServer::onClientDisconnected(TConnectedClient* pClient) {
Synchronized sync(clientMonitor_);
drainDeadClients(); // use the outgoing thread to do some maintenance on our dead client backlog
ClientMap::iterator it = activeClientMap_.find(pClient);
ClientMap::iterator end = it;
deadClientMap_.insert(it, ++end);
activeClientMap_.erase(it);
if (activeClientMap_.empty()) {
clientMonitor_.notify();
}
}
TThreadedServer::TConnectedClientRunner::TConnectedClientRunner(const shared_ptr<TConnectedClient>& pClient)
: pClient_(pClient) {
}
TThreadedServer::TConnectedClientRunner::~TConnectedClientRunner() {
}
void TThreadedServer::TConnectedClientRunner::run() /* override */ {
pClient_->run(); // Run the client
pClient_.reset(); // The client is done - release it here rather than in the destructor for safety
}
}
}
} // apache::thrift::server
| 1 | 14,557 | The assertion here is that find should never return end() because this is the only mechanism that reaps items from the activeClientMap. If it == end something went horribly wrong. | apache-thrift | c |
@@ -24,6 +24,12 @@ import (
// A Collection is a set of documents.
type Collection interface {
+ // Key returns the document key, or nil if the document doesn't have one. Key
+ // should not return an error if the key is missing unless the collection cannot
+ // generate a fresh key for a Create action.
+ // The returned key must be comparable.
+ Key(Document) (interface{}, error)
+
// RunActions executes a slice of actions.
//
// If unordered is false, it must appear as if the actions were executed in the | 1 | // Copyright 2019 The Go Cloud Development Kit Authors
//
// 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
//
// https://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.
// Package driver defines a set of interfaces that the docstore package uses to
// interact with the underlying services.
package driver // import "gocloud.dev/internal/docstore/driver"
import (
"context"
"gocloud.dev/internal/gcerr"
)
// A Collection is a set of documents.
type Collection interface {
// RunActions executes a slice of actions.
//
// If unordered is false, it must appear as if the actions were executed in the
// order they appear in the slice, from the client's point of view. The actions
// need not happen atomically, nor does eventual consistency in the provider
// system need to be taken into account. For example, after a write returns
// successfully, the driver can immediately perform a read on the same document,
// even though the provider's semantics does not guarantee that the read will see
// the write. RunActions should return immediately after the first action that fails.
// The returned slice should have a single element.
//
// opts controls the behavior of RunActions and is guaranteed to be non-nil.
RunActions(ctx context.Context, actions []*Action, opts *RunActionsOptions) ActionListError
// RunGetQuery executes a Query.
//
// Implementations can choose to execute the Query as one single request or
// multiple ones, depending on their service offerings.
RunGetQuery(context.Context, *Query) (DocumentIterator, error)
// RunDeleteQuery deletes every document matched by the query.
RunDeleteQuery(context.Context, *Query) error
// RunUpdateQuery updates every document matched by the query.
RunUpdateQuery(context.Context, *Query, []Mod) error
// QueryPlan returns the plan for the query.
QueryPlan(*Query) (string, error)
// As converts i to provider-specific types.
// See https://gocloud.dev/concepts/as/ for background information.
As(i interface{}) bool
// ErrorCode should return a code that describes the error, which was returned by
// one of the other methods in this interface.
ErrorCode(error) gcerr.ErrorCode
}
// ActionKind describes the type of an action.
type ActionKind int
const (
Create ActionKind = iota
Replace
Put
Get
Delete
Update
)
// An Action describes a single operation on a single document.
type Action struct {
Kind ActionKind // the kind of action
Doc Document // the document on which to perform the action
FieldPaths [][]string // field paths to retrieve, for Get only
Mods []Mod // modifications to make, for Update only
}
// A Mod is a modification to a field path in a document.
// At present, the only modifications supported are:
// - set the value at the field path, or create the field path if it doesn't exist
// - delete the field path (when Value is nil)
type Mod struct {
FieldPath []string
Value interface{}
}
// A value representing an increment modification.
type IncOp struct {
Amount interface{}
}
// An ActionListError contains all the errors encountered from a call to RunActions,
// and the positions of the corresponding actions.
type ActionListError []struct {
Index int
Err error
}
// NewActionListError creates an ActionListError from a slice of errors.
// If the ith element err of the slice is non-nil, the resulting ActionListError
// will have an item {i, err}.
func NewActionListError(errs []error) ActionListError {
var alerr ActionListError
for i, err := range errs {
if err != nil {
alerr = append(alerr, struct {
Index int
Err error
}{i, err})
}
}
return alerr
}
// RunActionsOptions controls the behavior of RunActions.
type RunActionsOptions struct {
// Unordered let the actions be executed in any order, perhaps concurrently.
// All of the actions should be executed, even if some fail. The returned
// ActionListError should have an element for each action that fails.
Unordered bool
// BeforeDo is a callback that must be called exactly once before each one or
// group of the underlying provider's actions is executed. asFunc allows
// providers to expose provider-specific types.
BeforeDo func(asFunc func(interface{}) bool) error
}
// A Query defines a query operation to find documents within a collection based
// on a set of requirements.
type Query struct {
// FieldPaths contain a list of field paths the user selects to return in the
// query results. The returned documents should only have these fields
// populated.
FieldPaths [][]string
// Filters contain a list of filters for the query. If there are more than one
// filter, they should be combined with AND.
Filters []Filter
// Limit sets the maximum number of results returned by running the query. When
// Limit <= 0, the driver implementation should return all possible results.
Limit int
// OrderByField is the field to use for sorting the results.
OrderByField string
// OrderAscending specifies the sort direction.
OrderAscending bool
// BeforeQuery is a callback that must be called exactly once before the
// underlying provider's query is executed. asFunc allows providers to expose
// provider-specific types.
BeforeQuery func(asFunc func(interface{}) bool) error
}
// A Filter defines a filter expression used to filter the query result.
// If the value is a number type, the filter uses numeric comparison.
// If the value is a string type, the filter uses UTF-8 string comparison.
// TODO(#1762): support comparison of other types.
type Filter struct {
FieldPath []string // the field path to filter
Op string // the operation, supports =, >, >=, <, <=
Value interface{} // the value to compare using the operation
}
// A DocumentIterator iterates through the results (for Get action).
type DocumentIterator interface {
// Next tries to get the next item in the query result and decodes into Document
// with the driver's codec.
// When there are no more results, it should return io.EOF.
// Once Next returns a non-nil error, it will never be called again.
Next(context.Context, Document) error
// Stop terminates the iterator before Next return io.EOF, allowing any cleanup
// needed.
Stop()
// As converts i to provider-specific types.
// See https://gocloud.dev/concepts/as/ for background information.
As(i interface{}) bool
}
// EqualOp is the name of the equality operator.
// It is defined here to avoid confusion between "=" and "==".
const EqualOp = "="
| 1 | 17,927 | The `unless the collection ...` part reads a little bit hard, maybe separate into its own sentence and explain what it means by `cannot generate a fresh key`? | google-go-cloud | go |
@@ -50,6 +50,9 @@ const (
// The feature is not implemented.
Unimplemented ErrorCode = 6
+
+ // The system was in the wrong state.
+ FailedPrecondition ErrorCode = 7
)
// Call "go generate" whenever you change the above list of error codes. | 1 | // Copyright 2019 The Go Cloud Authors
//
// 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
//
// https://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.
// Package gcerr provides an error type for Go Cloud APIs.
package gcerr
import (
"fmt"
xerrors "golang.org/x/exp/errors"
xfmt "golang.org/x/exp/errors/fmt"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// An ErrorCode describes the error's category.
type ErrorCode int
const (
// Returned by the Code function on a nil error. It is not a valid
// code for an error.
OK ErrorCode = 0
// The error could not be categorized.
Unknown ErrorCode = 1
// The resource was not found.
NotFound ErrorCode = 2
// The resource exists, but it should not.
AlreadyExists ErrorCode = 3
// A value given to a Go Cloud API is incorrect.
InvalidArgument ErrorCode = 4
// Something unexpected happened. Internal errors always indicate
// bugs in Go Cloud (or possibly the underlying provider).
Internal ErrorCode = 5
// The feature is not implemented.
Unimplemented ErrorCode = 6
)
// Call "go generate" whenever you change the above list of error codes.
// To get stringer:
// go get golang.org/x/tools/cmd/stringer
// Make sure $GOPATH/bin or $GOBIN in on your path.
//go:generate stringer -type=ErrorCode
// An Error describes a Go Cloud error.
type Error struct {
Code ErrorCode
msg string
frame xerrors.Frame
err error
}
func (e *Error) Error() string {
if e.msg == "" {
return fmt.Sprintf("code=%v", e.Code)
}
return fmt.Sprintf("%s (code=%v)", e.msg, e.Code)
}
func (e *Error) Format(s fmt.State, c rune) {
xfmt.FormatError(s, c, e)
}
func (e *Error) FormatError(p xerrors.Printer) (next error) {
p.Print(e.Error())
e.frame.Format(p)
return e.err
}
// Unwrap returns the error underlying the receiver, which may be nil.
func (e *Error) Unwrap() error {
return e.err
}
// New returns a new error with the given code, underlying error and message. Pass 1
// for the call depth if New is called from the function raising the error; pass 2 if
// it is called from a helper function that was invoked by the original function; and
// so on.
func New(c ErrorCode, err error, callDepth int, msg string) *Error {
return &Error{
Code: c,
msg: msg,
frame: xerrors.Caller(callDepth),
err: err,
}
}
// Newf uses format and args to format a message, then calls New.
func Newf(c ErrorCode, err error, format string, args ...interface{}) *Error {
return New(c, err, 1, fmt.Sprintf(format, args...))
}
// GRPCCode extracts the gRPC status code and converts it into an ErrorCode.
// It returns Unknown if the error isn't from gRPC.
func GRPCCode(err error) ErrorCode {
switch status.Code(err) {
case codes.NotFound:
return NotFound
case codes.AlreadyExists:
return AlreadyExists
case codes.InvalidArgument:
return InvalidArgument
case codes.Internal:
return Internal
case codes.Unimplemented:
return Unimplemented
default:
return Unknown
}
}
| 1 | 13,793 | Doesn't `gcerr_string.go` need to be updated for this? | google-go-cloud | go |
@@ -2473,6 +2473,8 @@ func (c *Compiler) parseConvert(typeFrom, typeTo types.Type, value llvm.Value, p
switch elemType.Kind() {
case types.Byte:
return c.createRuntimeCall("stringToBytes", []llvm.Value{value}, ""), nil
+ case types.Rune:
+ return c.createRuntimeCall("stringToRunes", []llvm.Value{value}, ""), nil
default:
return llvm.Value{}, c.makeError(pos, "todo: convert from string: "+elemType.String())
} | 1 | package compiler
import (
"errors"
"fmt"
"go/build"
"go/constant"
"go/token"
"go/types"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/tinygo-org/tinygo/ir"
"github.com/tinygo-org/tinygo/loader"
"golang.org/x/tools/go/ssa"
"tinygo.org/x/go-llvm"
)
func init() {
llvm.InitializeAllTargets()
llvm.InitializeAllTargetMCs()
llvm.InitializeAllTargetInfos()
llvm.InitializeAllAsmParsers()
llvm.InitializeAllAsmPrinters()
}
// The TinyGo import path.
const tinygoPath = "github.com/tinygo-org/tinygo"
// Configure the compiler.
type Config struct {
Triple string // LLVM target triple, e.g. x86_64-unknown-linux-gnu (empty string means default)
CPU string // LLVM CPU name, e.g. atmega328p (empty string means default)
Features []string // LLVM CPU features
GOOS string //
GOARCH string //
GC string // garbage collection strategy
PanicStrategy string // panic strategy ("abort" or "trap")
CFlags []string // cflags to pass to cgo
LDFlags []string // ldflags to pass to cgo
DumpSSA bool // dump Go SSA, for compiler debugging
Debug bool // add debug symbols for gdb
GOROOT string // GOROOT
TINYGOROOT string // GOROOT for TinyGo
GOPATH string // GOPATH, like `go env GOPATH`
BuildTags []string // build tags for TinyGo (empty means {Config.GOOS/Config.GOARCH})
}
type Compiler struct {
Config
mod llvm.Module
ctx llvm.Context
builder llvm.Builder
dibuilder *llvm.DIBuilder
cu llvm.Metadata
difiles map[string]llvm.Metadata
machine llvm.TargetMachine
targetData llvm.TargetData
intType llvm.Type
i8ptrType llvm.Type // for convenience
funcPtrAddrSpace int
uintptrType llvm.Type
initFuncs []llvm.Value
interfaceInvokeWrappers []interfaceInvokeWrapper
ir *ir.Program
diagnostics []error
}
type Frame struct {
fn *ir.Function
locals map[ssa.Value]llvm.Value // local variables
blockEntries map[*ssa.BasicBlock]llvm.BasicBlock // a *ssa.BasicBlock may be split up
blockExits map[*ssa.BasicBlock]llvm.BasicBlock // these are the exit blocks
currentBlock *ssa.BasicBlock
phis []Phi
taskHandle llvm.Value
deferPtr llvm.Value
difunc llvm.Metadata
allDeferFuncs []interface{}
deferFuncs map[*ir.Function]int
deferInvokeFuncs map[string]int
deferClosureFuncs map[*ir.Function]int
}
type Phi struct {
ssa *ssa.Phi
llvm llvm.Value
}
func NewCompiler(pkgName string, config Config) (*Compiler, error) {
if config.Triple == "" {
config.Triple = llvm.DefaultTargetTriple()
}
if len(config.BuildTags) == 0 {
config.BuildTags = []string{config.GOOS, config.GOARCH}
}
c := &Compiler{
Config: config,
difiles: make(map[string]llvm.Metadata),
}
target, err := llvm.GetTargetFromTriple(config.Triple)
if err != nil {
return nil, err
}
features := ""
if len(config.Features) > 0 {
features = strings.Join(config.Features, `,`)
}
c.machine = target.CreateTargetMachine(config.Triple, config.CPU, features, llvm.CodeGenLevelDefault, llvm.RelocStatic, llvm.CodeModelDefault)
c.targetData = c.machine.CreateTargetData()
c.ctx = llvm.NewContext()
c.mod = c.ctx.NewModule(pkgName)
c.mod.SetTarget(config.Triple)
c.mod.SetDataLayout(c.targetData.String())
c.builder = c.ctx.NewBuilder()
if c.Debug {
c.dibuilder = llvm.NewDIBuilder(c.mod)
}
c.uintptrType = c.ctx.IntType(c.targetData.PointerSize() * 8)
if c.targetData.PointerSize() <= 4 {
// 8, 16, 32 bits targets
c.intType = c.ctx.Int32Type()
} else if c.targetData.PointerSize() == 8 {
// 64 bits target
c.intType = c.ctx.Int64Type()
} else {
panic("unknown pointer size")
}
c.i8ptrType = llvm.PointerType(c.ctx.Int8Type(), 0)
dummyFuncType := llvm.FunctionType(c.ctx.VoidType(), nil, false)
dummyFunc := llvm.AddFunction(c.mod, "tinygo.dummy", dummyFuncType)
c.funcPtrAddrSpace = dummyFunc.Type().PointerAddressSpace()
dummyFunc.EraseFromParentAsFunction()
return c, nil
}
func (c *Compiler) Packages() []*loader.Package {
return c.ir.LoaderProgram.Sorted()
}
// Return the LLVM module. Only valid after a successful compile.
func (c *Compiler) Module() llvm.Module {
return c.mod
}
// Return the LLVM target data object. Only valid after a successful compile.
func (c *Compiler) TargetData() llvm.TargetData {
return c.targetData
}
// selectGC picks an appropriate GC strategy if none was provided.
func (c *Compiler) selectGC() string {
gc := c.GC
if gc == "" {
gc = "dumb"
}
return gc
}
// Compile the given package path or .go file path. Return an error when this
// fails (in any stage).
func (c *Compiler) Compile(mainPath string) []error {
// Prefix the GOPATH with the system GOROOT, as GOROOT is already set to
// the TinyGo root.
overlayGopath := c.GOPATH
if overlayGopath == "" {
overlayGopath = c.GOROOT
} else {
overlayGopath = c.GOROOT + string(filepath.ListSeparator) + overlayGopath
}
wd, err := os.Getwd()
if err != nil {
return []error{err}
}
lprogram := &loader.Program{
Build: &build.Context{
GOARCH: c.GOARCH,
GOOS: c.GOOS,
GOROOT: c.GOROOT,
GOPATH: c.GOPATH,
CgoEnabled: true,
UseAllFiles: false,
Compiler: "gc", // must be one of the recognized compilers
BuildTags: append([]string{"tinygo", "gc." + c.selectGC()}, c.BuildTags...),
},
OverlayBuild: &build.Context{
GOARCH: c.GOARCH,
GOOS: c.GOOS,
GOROOT: c.TINYGOROOT,
GOPATH: overlayGopath,
CgoEnabled: true,
UseAllFiles: false,
Compiler: "gc", // must be one of the recognized compilers
BuildTags: append([]string{"tinygo", "gc." + c.selectGC()}, c.BuildTags...),
},
OverlayPath: func(path string) string {
// Return the (overlay) import path when it should be overlaid, and
// "" if it should not.
if strings.HasPrefix(path, tinygoPath+"/src/") {
// Avoid issues with packages that are imported twice, one from
// GOPATH and one from TINYGOPATH.
path = path[len(tinygoPath+"/src/"):]
}
switch path {
case "machine", "os", "reflect", "runtime", "runtime/volatile", "sync":
return path
default:
if strings.HasPrefix(path, "device/") || strings.HasPrefix(path, "examples/") {
return path
} else if path == "syscall" {
for _, tag := range c.BuildTags {
if tag == "avr" || tag == "cortexm" || tag == "darwin" {
return path
}
}
}
}
return ""
},
TypeChecker: types.Config{
Sizes: &StdSizes{
IntSize: int64(c.targetData.TypeAllocSize(c.intType)),
PtrSize: int64(c.targetData.PointerSize()),
MaxAlign: int64(c.targetData.PrefTypeAlignment(c.i8ptrType)),
},
},
Dir: wd,
TINYGOROOT: c.TINYGOROOT,
CFlags: c.CFlags,
}
if strings.HasSuffix(mainPath, ".go") {
_, err = lprogram.ImportFile(mainPath)
if err != nil {
return []error{err}
}
} else {
_, err = lprogram.Import(mainPath, wd)
if err != nil {
return []error{err}
}
}
_, err = lprogram.Import("runtime", "")
if err != nil {
return []error{err}
}
err = lprogram.Parse()
if err != nil {
return []error{err}
}
c.ir = ir.NewProgram(lprogram, mainPath)
// Run a simple dead code elimination pass.
c.ir.SimpleDCE()
// Initialize debug information.
if c.Debug {
c.cu = c.dibuilder.CreateCompileUnit(llvm.DICompileUnit{
Language: 0xb, // DW_LANG_C99 (0xc, off-by-one?)
File: mainPath,
Dir: "",
Producer: "TinyGo",
Optimized: true,
})
}
var frames []*Frame
// Declare all named struct types.
for _, t := range c.ir.NamedTypes {
if named, ok := t.Type.Type().(*types.Named); ok {
if _, ok := named.Underlying().(*types.Struct); ok {
t.LLVMType = c.ctx.StructCreateNamed(named.Obj().Pkg().Path() + "." + named.Obj().Name())
}
}
}
// Define all named struct types.
for _, t := range c.ir.NamedTypes {
if named, ok := t.Type.Type().(*types.Named); ok {
if st, ok := named.Underlying().(*types.Struct); ok {
llvmType := c.getLLVMType(st)
t.LLVMType.StructSetBody(llvmType.StructElementTypes(), false)
}
}
}
// Declare all globals.
for _, g := range c.ir.Globals {
typ := g.Type().(*types.Pointer).Elem()
llvmType := c.getLLVMType(typ)
global := c.mod.NamedGlobal(g.LinkName())
if global.IsNil() {
global = llvm.AddGlobal(c.mod, llvmType, g.LinkName())
}
g.LLVMGlobal = global
if !g.IsExtern() {
global.SetLinkage(llvm.InternalLinkage)
global.SetInitializer(c.getZeroValue(llvmType))
}
}
// Declare all functions.
for _, f := range c.ir.Functions {
frames = append(frames, c.parseFuncDecl(f))
}
// Add definitions to declarations.
for _, frame := range frames {
if frame.fn.Synthetic == "package initializer" {
c.initFuncs = append(c.initFuncs, frame.fn.LLVMFn)
}
if frame.fn.CName() != "" {
continue
}
if frame.fn.Blocks == nil {
continue // external function
}
c.parseFunc(frame)
}
// Define the already declared functions that wrap methods for use in
// interfaces.
for _, state := range c.interfaceInvokeWrappers {
c.createInterfaceInvokeWrapper(state)
}
// After all packages are imported, add a synthetic initializer function
// that calls the initializer of each package.
initFn := c.ir.GetFunction(c.ir.Program.ImportedPackage("runtime").Members["initAll"].(*ssa.Function))
initFn.LLVMFn.SetLinkage(llvm.InternalLinkage)
initFn.LLVMFn.SetUnnamedAddr(true)
if c.Debug {
difunc := c.attachDebugInfo(initFn)
pos := c.ir.Program.Fset.Position(initFn.Pos())
c.builder.SetCurrentDebugLocation(uint(pos.Line), uint(pos.Column), difunc, llvm.Metadata{})
}
block := c.ctx.AddBasicBlock(initFn.LLVMFn, "entry")
c.builder.SetInsertPointAtEnd(block)
for _, fn := range c.initFuncs {
c.builder.CreateCall(fn, []llvm.Value{llvm.Undef(c.i8ptrType), llvm.Undef(c.i8ptrType)}, "")
}
c.builder.CreateRetVoid()
// Conserve for goroutine lowering. Without marking these as external, they
// would be optimized away.
realMain := c.mod.NamedFunction(c.ir.MainPkg().Pkg.Path() + ".main")
realMain.SetLinkage(llvm.ExternalLinkage) // keep alive until goroutine lowering
c.mod.NamedFunction("runtime.alloc").SetLinkage(llvm.ExternalLinkage)
c.mod.NamedFunction("runtime.free").SetLinkage(llvm.ExternalLinkage)
c.mod.NamedFunction("runtime.sleepTask").SetLinkage(llvm.ExternalLinkage)
c.mod.NamedFunction("runtime.setTaskPromisePtr").SetLinkage(llvm.ExternalLinkage)
c.mod.NamedFunction("runtime.getTaskPromisePtr").SetLinkage(llvm.ExternalLinkage)
c.mod.NamedFunction("runtime.activateTask").SetLinkage(llvm.ExternalLinkage)
c.mod.NamedFunction("runtime.scheduler").SetLinkage(llvm.ExternalLinkage)
// Load some attributes
getAttr := func(attrName string) llvm.Attribute {
attrKind := llvm.AttributeKindID(attrName)
return c.ctx.CreateEnumAttribute(attrKind, 0)
}
nocapture := getAttr("nocapture")
writeonly := getAttr("writeonly")
readonly := getAttr("readonly")
// Tell the optimizer that runtime.alloc is an allocator, meaning that it
// returns values that are never null and never alias to an existing value.
for _, attrName := range []string{"noalias", "nonnull"} {
c.mod.NamedFunction("runtime.alloc").AddAttributeAtIndex(0, getAttr(attrName))
}
// See emitNilCheck in asserts.go.
c.mod.NamedFunction("runtime.isnil").AddAttributeAtIndex(1, nocapture)
// Memory copy operations do not capture pointers, even though some weird
// pointer arithmetic is happening in the Go implementation.
for _, fnName := range []string{"runtime.memcpy", "runtime.memmove"} {
fn := c.mod.NamedFunction(fnName)
fn.AddAttributeAtIndex(1, nocapture)
fn.AddAttributeAtIndex(1, writeonly)
fn.AddAttributeAtIndex(2, nocapture)
fn.AddAttributeAtIndex(2, readonly)
}
// see: https://reviews.llvm.org/D18355
if c.Debug {
c.mod.AddNamedMetadataOperand("llvm.module.flags",
c.ctx.MDNode([]llvm.Metadata{
llvm.ConstInt(c.ctx.Int32Type(), 1, false).ConstantAsMetadata(), // Error on mismatch
llvm.GlobalContext().MDString("Debug Info Version"),
llvm.ConstInt(c.ctx.Int32Type(), 3, false).ConstantAsMetadata(), // DWARF version
}),
)
c.mod.AddNamedMetadataOperand("llvm.module.flags",
c.ctx.MDNode([]llvm.Metadata{
llvm.ConstInt(c.ctx.Int32Type(), 1, false).ConstantAsMetadata(),
llvm.GlobalContext().MDString("Dwarf Version"),
llvm.ConstInt(c.ctx.Int32Type(), 4, false).ConstantAsMetadata(),
}),
)
c.dibuilder.Finalize()
}
return c.diagnostics
}
func (c *Compiler) getLLVMType(goType types.Type) llvm.Type {
switch typ := goType.(type) {
case *types.Array:
elemType := c.getLLVMType(typ.Elem())
return llvm.ArrayType(elemType, int(typ.Len()))
case *types.Basic:
switch typ.Kind() {
case types.Bool, types.UntypedBool:
return c.ctx.Int1Type()
case types.Int8, types.Uint8:
return c.ctx.Int8Type()
case types.Int16, types.Uint16:
return c.ctx.Int16Type()
case types.Int32, types.Uint32:
return c.ctx.Int32Type()
case types.Int, types.Uint:
return c.intType
case types.Int64, types.Uint64:
return c.ctx.Int64Type()
case types.Float32:
return c.ctx.FloatType()
case types.Float64:
return c.ctx.DoubleType()
case types.Complex64:
return c.ctx.StructType([]llvm.Type{c.ctx.FloatType(), c.ctx.FloatType()}, false)
case types.Complex128:
return c.ctx.StructType([]llvm.Type{c.ctx.DoubleType(), c.ctx.DoubleType()}, false)
case types.String, types.UntypedString:
return c.mod.GetTypeByName("runtime._string")
case types.Uintptr:
return c.uintptrType
case types.UnsafePointer:
return c.i8ptrType
default:
panic("unknown basic type: " + typ.String())
}
case *types.Chan:
return llvm.PointerType(c.mod.GetTypeByName("runtime.channel"), 0)
case *types.Interface:
return c.mod.GetTypeByName("runtime._interface")
case *types.Map:
return llvm.PointerType(c.mod.GetTypeByName("runtime.hashmap"), 0)
case *types.Named:
if _, ok := typ.Underlying().(*types.Struct); ok {
llvmType := c.mod.GetTypeByName(typ.Obj().Pkg().Path() + "." + typ.Obj().Name())
if llvmType.IsNil() {
panic("underlying type not found: " + typ.Obj().Pkg().Path() + "." + typ.Obj().Name())
}
return llvmType
}
return c.getLLVMType(typ.Underlying())
case *types.Pointer:
ptrTo := c.getLLVMType(typ.Elem())
return llvm.PointerType(ptrTo, 0)
case *types.Signature: // function value
return c.getFuncType(typ)
case *types.Slice:
elemType := c.getLLVMType(typ.Elem())
members := []llvm.Type{
llvm.PointerType(elemType, 0),
c.uintptrType, // len
c.uintptrType, // cap
}
return c.ctx.StructType(members, false)
case *types.Struct:
members := make([]llvm.Type, typ.NumFields())
for i := 0; i < typ.NumFields(); i++ {
members[i] = c.getLLVMType(typ.Field(i).Type())
}
if len(members) > 2 && typ.Field(0).Name() == "C union" {
// Not a normal struct but a C union emitted by cgo.
// Such a field name cannot be entered in regular Go code, this must
// be manually inserted in the AST so this is safe.
maxAlign := 0
maxSize := uint64(0)
mainType := members[0]
for _, member := range members {
align := c.targetData.ABITypeAlignment(member)
size := c.targetData.TypeAllocSize(member)
if align > maxAlign {
maxAlign = align
mainType = member
} else if align == maxAlign && size > maxSize {
maxAlign = align
maxSize = size
mainType = member
} else if size > maxSize {
maxSize = size
}
}
members = []llvm.Type{mainType}
mainTypeSize := c.targetData.TypeAllocSize(mainType)
if mainTypeSize < maxSize {
members = append(members, llvm.ArrayType(c.ctx.Int8Type(), int(maxSize-mainTypeSize)))
}
}
return c.ctx.StructType(members, false)
case *types.Tuple:
members := make([]llvm.Type, typ.Len())
for i := 0; i < typ.Len(); i++ {
members[i] = c.getLLVMType(typ.At(i).Type())
}
return c.ctx.StructType(members, false)
default:
panic("unknown type: " + goType.String())
}
}
// Return a zero LLVM value for any LLVM type. Setting this value as an
// initializer has the same effect as setting 'zeroinitializer' on a value.
// Sadly, I haven't found a way to do it directly with the Go API but this works
// just fine.
func (c *Compiler) getZeroValue(typ llvm.Type) llvm.Value {
switch typ.TypeKind() {
case llvm.ArrayTypeKind:
subTyp := typ.ElementType()
subVal := c.getZeroValue(subTyp)
vals := make([]llvm.Value, typ.ArrayLength())
for i := range vals {
vals[i] = subVal
}
return llvm.ConstArray(subTyp, vals)
case llvm.FloatTypeKind, llvm.DoubleTypeKind:
return llvm.ConstFloat(typ, 0.0)
case llvm.IntegerTypeKind:
return llvm.ConstInt(typ, 0, false)
case llvm.PointerTypeKind:
return llvm.ConstPointerNull(typ)
case llvm.StructTypeKind:
types := typ.StructElementTypes()
vals := make([]llvm.Value, len(types))
for i, subTyp := range types {
vals[i] = c.getZeroValue(subTyp)
}
if typ.StructName() != "" {
return llvm.ConstNamedStruct(typ, vals)
} else {
return c.ctx.ConstStruct(vals, false)
}
default:
panic("unknown LLVM zero inititializer: " + typ.String())
}
}
// Is this a pointer type of some sort? Can be unsafe.Pointer or any *T pointer.
func isPointer(typ types.Type) bool {
if _, ok := typ.(*types.Pointer); ok {
return true
} else if typ, ok := typ.(*types.Basic); ok && typ.Kind() == types.UnsafePointer {
return true
} else {
return false
}
}
// Get the DWARF type for this Go type.
func (c *Compiler) getDIType(typ types.Type) llvm.Metadata {
llvmType := c.getLLVMType(typ)
sizeInBytes := c.targetData.TypeAllocSize(llvmType)
switch typ := typ.(type) {
case *types.Array:
return c.dibuilder.CreateArrayType(llvm.DIArrayType{
SizeInBits: sizeInBytes * 8,
AlignInBits: uint32(c.targetData.ABITypeAlignment(llvmType)) * 8,
ElementType: c.getDIType(typ.Elem()),
Subscripts: []llvm.DISubrange{
llvm.DISubrange{
Lo: 0,
Count: typ.Len(),
},
},
})
case *types.Basic:
var encoding llvm.DwarfTypeEncoding
if typ.Info()&types.IsBoolean != 0 {
encoding = llvm.DW_ATE_boolean
} else if typ.Info()&types.IsFloat != 0 {
encoding = llvm.DW_ATE_float
} else if typ.Info()&types.IsComplex != 0 {
encoding = llvm.DW_ATE_complex_float
} else if typ.Info()&types.IsUnsigned != 0 {
encoding = llvm.DW_ATE_unsigned
} else if typ.Info()&types.IsInteger != 0 {
encoding = llvm.DW_ATE_signed
} else if typ.Kind() == types.UnsafePointer {
return c.dibuilder.CreatePointerType(llvm.DIPointerType{
Name: "unsafe.Pointer",
SizeInBits: c.targetData.TypeAllocSize(llvmType) * 8,
AlignInBits: uint32(c.targetData.ABITypeAlignment(llvmType)) * 8,
AddressSpace: 0,
})
} else if typ.Info()&types.IsString != 0 {
return c.dibuilder.CreateStructType(llvm.Metadata{}, llvm.DIStructType{
Name: "string",
SizeInBits: sizeInBytes * 8,
AlignInBits: uint32(c.targetData.ABITypeAlignment(llvmType)) * 8,
Elements: []llvm.Metadata{
c.dibuilder.CreateMemberType(llvm.Metadata{}, llvm.DIMemberType{
Name: "ptr",
SizeInBits: c.targetData.TypeAllocSize(c.i8ptrType) * 8,
AlignInBits: uint32(c.targetData.ABITypeAlignment(c.i8ptrType)) * 8,
OffsetInBits: 0,
Type: c.getDIType(types.NewPointer(types.Typ[types.Byte])),
}),
c.dibuilder.CreateMemberType(llvm.Metadata{}, llvm.DIMemberType{
Name: "len",
SizeInBits: c.targetData.TypeAllocSize(c.uintptrType) * 8,
AlignInBits: uint32(c.targetData.ABITypeAlignment(c.uintptrType)) * 8,
OffsetInBits: c.targetData.ElementOffset(llvmType, 1) * 8,
Type: c.getDIType(types.Typ[types.Uintptr]),
}),
},
})
} else {
panic("unknown basic type")
}
return c.dibuilder.CreateBasicType(llvm.DIBasicType{
Name: typ.String(),
SizeInBits: sizeInBytes * 8,
Encoding: encoding,
})
case *types.Chan:
return c.getDIType(types.NewPointer(c.ir.Program.ImportedPackage("runtime").Members["channel"].(*ssa.Type).Type()))
case *types.Interface:
return c.getDIType(c.ir.Program.ImportedPackage("runtime").Members["_interface"].(*ssa.Type).Type())
case *types.Map:
return c.getDIType(types.NewPointer(c.ir.Program.ImportedPackage("runtime").Members["hashmap"].(*ssa.Type).Type()))
case *types.Named:
return c.dibuilder.CreateTypedef(llvm.DITypedef{
Type: c.getDIType(typ.Underlying()),
Name: typ.String(),
})
case *types.Pointer:
return c.dibuilder.CreatePointerType(llvm.DIPointerType{
Pointee: c.getDIType(typ.Elem()),
SizeInBits: c.targetData.TypeAllocSize(llvmType) * 8,
AlignInBits: uint32(c.targetData.ABITypeAlignment(llvmType)) * 8,
AddressSpace: 0,
})
case *types.Signature:
// actually a closure
fields := llvmType.StructElementTypes()
return c.dibuilder.CreateStructType(llvm.Metadata{}, llvm.DIStructType{
SizeInBits: sizeInBytes * 8,
AlignInBits: uint32(c.targetData.ABITypeAlignment(llvmType)) * 8,
Elements: []llvm.Metadata{
c.dibuilder.CreateMemberType(llvm.Metadata{}, llvm.DIMemberType{
Name: "context",
SizeInBits: c.targetData.TypeAllocSize(fields[1]) * 8,
AlignInBits: uint32(c.targetData.ABITypeAlignment(fields[1])) * 8,
OffsetInBits: 0,
Type: c.getDIType(types.Typ[types.UnsafePointer]),
}),
c.dibuilder.CreateMemberType(llvm.Metadata{}, llvm.DIMemberType{
Name: "fn",
SizeInBits: c.targetData.TypeAllocSize(fields[0]) * 8,
AlignInBits: uint32(c.targetData.ABITypeAlignment(fields[0])) * 8,
OffsetInBits: c.targetData.ElementOffset(llvmType, 1) * 8,
Type: c.getDIType(types.Typ[types.UnsafePointer]),
}),
},
})
case *types.Slice:
fields := llvmType.StructElementTypes()
return c.dibuilder.CreateStructType(llvm.Metadata{}, llvm.DIStructType{
Name: typ.String(),
SizeInBits: sizeInBytes * 8,
AlignInBits: uint32(c.targetData.ABITypeAlignment(llvmType)) * 8,
Elements: []llvm.Metadata{
c.dibuilder.CreateMemberType(llvm.Metadata{}, llvm.DIMemberType{
Name: "ptr",
SizeInBits: c.targetData.TypeAllocSize(fields[0]) * 8,
AlignInBits: uint32(c.targetData.ABITypeAlignment(fields[0])) * 8,
OffsetInBits: 0,
Type: c.getDIType(types.NewPointer(typ.Elem())),
}),
c.dibuilder.CreateMemberType(llvm.Metadata{}, llvm.DIMemberType{
Name: "len",
SizeInBits: c.targetData.TypeAllocSize(c.uintptrType) * 8,
AlignInBits: uint32(c.targetData.ABITypeAlignment(c.uintptrType)) * 8,
OffsetInBits: c.targetData.ElementOffset(llvmType, 1) * 8,
Type: c.getDIType(types.Typ[types.Uintptr]),
}),
c.dibuilder.CreateMemberType(llvm.Metadata{}, llvm.DIMemberType{
Name: "cap",
SizeInBits: c.targetData.TypeAllocSize(c.uintptrType) * 8,
AlignInBits: uint32(c.targetData.ABITypeAlignment(c.uintptrType)) * 8,
OffsetInBits: c.targetData.ElementOffset(llvmType, 2) * 8,
Type: c.getDIType(types.Typ[types.Uintptr]),
}),
},
})
case *types.Struct:
elements := make([]llvm.Metadata, typ.NumFields())
for i := range elements {
field := typ.Field(i)
fieldType := field.Type()
if _, ok := fieldType.Underlying().(*types.Pointer); ok {
// XXX hack to avoid recursive types
fieldType = types.Typ[types.UnsafePointer]
}
llvmField := c.getLLVMType(fieldType)
elements[i] = c.dibuilder.CreateMemberType(llvm.Metadata{}, llvm.DIMemberType{
Name: field.Name(),
SizeInBits: c.targetData.TypeAllocSize(llvmField) * 8,
AlignInBits: uint32(c.targetData.ABITypeAlignment(llvmField)) * 8,
OffsetInBits: c.targetData.ElementOffset(llvmType, i) * 8,
Type: c.getDIType(fieldType),
})
}
return c.dibuilder.CreateStructType(llvm.Metadata{}, llvm.DIStructType{
SizeInBits: sizeInBytes * 8,
AlignInBits: uint32(c.targetData.ABITypeAlignment(llvmType)) * 8,
Elements: elements,
})
default:
panic("unknown type while generating DWARF debug type: " + typ.String())
}
}
func (c *Compiler) parseFuncDecl(f *ir.Function) *Frame {
frame := &Frame{
fn: f,
locals: make(map[ssa.Value]llvm.Value),
blockEntries: make(map[*ssa.BasicBlock]llvm.BasicBlock),
blockExits: make(map[*ssa.BasicBlock]llvm.BasicBlock),
}
var retType llvm.Type
if f.Signature.Results() == nil {
retType = c.ctx.VoidType()
} else if f.Signature.Results().Len() == 1 {
retType = c.getLLVMType(f.Signature.Results().At(0).Type())
} else {
results := make([]llvm.Type, 0, f.Signature.Results().Len())
for i := 0; i < f.Signature.Results().Len(); i++ {
results = append(results, c.getLLVMType(f.Signature.Results().At(i).Type()))
}
retType = c.ctx.StructType(results, false)
}
var paramTypes []llvm.Type
for _, param := range f.Params {
paramType := c.getLLVMType(param.Type())
paramTypeFragments := c.expandFormalParamType(paramType)
paramTypes = append(paramTypes, paramTypeFragments...)
}
// Add an extra parameter as the function context. This context is used in
// closures and bound methods, but should be optimized away when not used.
if !f.IsExported() {
paramTypes = append(paramTypes, c.i8ptrType) // context
paramTypes = append(paramTypes, c.i8ptrType) // parent coroutine
}
fnType := llvm.FunctionType(retType, paramTypes, false)
name := f.LinkName()
frame.fn.LLVMFn = c.mod.NamedFunction(name)
if frame.fn.LLVMFn.IsNil() {
frame.fn.LLVMFn = llvm.AddFunction(c.mod, name, fnType)
}
// External/exported functions may not retain pointer values.
// https://golang.org/cmd/cgo/#hdr-Passing_pointers
if f.IsExported() {
nocaptureKind := llvm.AttributeKindID("nocapture")
nocapture := c.ctx.CreateEnumAttribute(nocaptureKind, 0)
for i, typ := range paramTypes {
if typ.TypeKind() == llvm.PointerTypeKind {
frame.fn.LLVMFn.AddAttributeAtIndex(i+1, nocapture)
}
}
}
return frame
}
func (c *Compiler) attachDebugInfo(f *ir.Function) llvm.Metadata {
pos := c.ir.Program.Fset.Position(f.Syntax().Pos())
return c.attachDebugInfoRaw(f, f.LLVMFn, "", pos.Filename, pos.Line)
}
func (c *Compiler) attachDebugInfoRaw(f *ir.Function, llvmFn llvm.Value, suffix, filename string, line int) llvm.Metadata {
if _, ok := c.difiles[filename]; !ok {
dir, file := filepath.Split(filename)
if dir != "" {
dir = dir[:len(dir)-1]
}
c.difiles[filename] = c.dibuilder.CreateFile(file, dir)
}
// Debug info for this function.
diparams := make([]llvm.Metadata, 0, len(f.Params))
for _, param := range f.Params {
diparams = append(diparams, c.getDIType(param.Type()))
}
diFuncType := c.dibuilder.CreateSubroutineType(llvm.DISubroutineType{
File: c.difiles[filename],
Parameters: diparams,
Flags: 0, // ?
})
difunc := c.dibuilder.CreateFunction(c.difiles[filename], llvm.DIFunction{
Name: f.RelString(nil) + suffix,
LinkageName: f.LinkName() + suffix,
File: c.difiles[filename],
Line: line,
Type: diFuncType,
LocalToUnit: true,
IsDefinition: true,
ScopeLine: 0,
Flags: llvm.FlagPrototyped,
Optimized: true,
})
llvmFn.SetSubprogram(difunc)
return difunc
}
func (c *Compiler) parseFunc(frame *Frame) {
if c.DumpSSA {
fmt.Printf("\nfunc %s:\n", frame.fn.Function)
}
if !frame.fn.LLVMFn.IsDeclaration() {
c.addError(frame.fn.Pos(), "function is already defined:"+frame.fn.LLVMFn.Name())
return
}
if !frame.fn.IsExported() {
frame.fn.LLVMFn.SetLinkage(llvm.InternalLinkage)
frame.fn.LLVMFn.SetUnnamedAddr(true)
}
if frame.fn.IsInterrupt() && strings.HasPrefix(c.Triple, "avr") {
frame.fn.LLVMFn.SetFunctionCallConv(85) // CallingConv::AVR_SIGNAL
}
// Some functions have a pragma controlling the inlining level.
switch frame.fn.Inline() {
case ir.InlineHint:
// Add LLVM inline hint to functions with //go:inline pragma.
inline := c.ctx.CreateEnumAttribute(llvm.AttributeKindID("inlinehint"), 0)
frame.fn.LLVMFn.AddFunctionAttr(inline)
}
// Add debug info, if needed.
if c.Debug {
if frame.fn.Synthetic == "package initializer" {
// Package initializers have no debug info. Create some fake debug
// info to at least have *something*.
frame.difunc = c.attachDebugInfoRaw(frame.fn, frame.fn.LLVMFn, "", "", 0)
} else if frame.fn.Syntax() != nil {
// Create debug info file if needed.
frame.difunc = c.attachDebugInfo(frame.fn)
}
pos := c.ir.Program.Fset.Position(frame.fn.Pos())
c.builder.SetCurrentDebugLocation(uint(pos.Line), uint(pos.Column), frame.difunc, llvm.Metadata{})
}
// Pre-create all basic blocks in the function.
for _, block := range frame.fn.DomPreorder() {
llvmBlock := c.ctx.AddBasicBlock(frame.fn.LLVMFn, block.Comment)
frame.blockEntries[block] = llvmBlock
frame.blockExits[block] = llvmBlock
}
entryBlock := frame.blockEntries[frame.fn.Blocks[0]]
c.builder.SetInsertPointAtEnd(entryBlock)
// Load function parameters
llvmParamIndex := 0
for i, param := range frame.fn.Params {
llvmType := c.getLLVMType(param.Type())
fields := make([]llvm.Value, 0, 1)
for range c.expandFormalParamType(llvmType) {
fields = append(fields, frame.fn.LLVMFn.Param(llvmParamIndex))
llvmParamIndex++
}
frame.locals[param] = c.collapseFormalParam(llvmType, fields)
// Add debug information to this parameter (if available)
if c.Debug && frame.fn.Syntax() != nil {
pos := c.ir.Program.Fset.Position(frame.fn.Syntax().Pos())
diType := c.getDIType(param.Type())
dbgParam := c.dibuilder.CreateParameterVariable(frame.difunc, llvm.DIParameterVariable{
Name: param.Name(),
File: c.difiles[pos.Filename],
Line: pos.Line,
Type: diType,
AlwaysPreserve: true,
ArgNo: i + 1,
})
loc := c.builder.GetCurrentDebugLocation()
if len(fields) == 1 {
expr := c.dibuilder.CreateExpression(nil)
c.dibuilder.InsertValueAtEnd(fields[0], dbgParam, expr, loc, entryBlock)
} else {
fieldOffsets := c.expandFormalParamOffsets(llvmType)
for i, field := range fields {
expr := c.dibuilder.CreateExpression([]int64{
0x1000, // DW_OP_LLVM_fragment
int64(fieldOffsets[i]) * 8, // offset in bits
int64(c.targetData.TypeAllocSize(field.Type())) * 8, // size in bits
})
c.dibuilder.InsertValueAtEnd(field, dbgParam, expr, loc, entryBlock)
}
}
}
}
// Load free variables from the context. This is a closure (or bound
// method).
var context llvm.Value
if !frame.fn.IsExported() {
parentHandle := frame.fn.LLVMFn.LastParam()
parentHandle.SetName("parentHandle")
context = llvm.PrevParam(parentHandle)
context.SetName("context")
}
if len(frame.fn.FreeVars) != 0 {
// Get a list of all variable types in the context.
freeVarTypes := make([]llvm.Type, len(frame.fn.FreeVars))
for i, freeVar := range frame.fn.FreeVars {
freeVarTypes[i] = c.getLLVMType(freeVar.Type())
}
// Load each free variable from the context pointer.
// A free variable is always a pointer when this is a closure, but it
// can be another type when it is a wrapper for a bound method (these
// wrappers are generated by the ssa package).
for i, val := range c.emitPointerUnpack(context, freeVarTypes) {
frame.locals[frame.fn.FreeVars[i]] = val
}
}
if frame.fn.Recover != nil {
// This function has deferred function calls. Set some things up for
// them.
c.deferInitFunc(frame)
}
// Fill blocks with instructions.
for _, block := range frame.fn.DomPreorder() {
if c.DumpSSA {
fmt.Printf("%d: %s:\n", block.Index, block.Comment)
}
c.builder.SetInsertPointAtEnd(frame.blockEntries[block])
frame.currentBlock = block
for _, instr := range block.Instrs {
if _, ok := instr.(*ssa.DebugRef); ok {
continue
}
if c.DumpSSA {
if val, ok := instr.(ssa.Value); ok && val.Name() != "" {
fmt.Printf("\t%s = %s\n", val.Name(), val.String())
} else {
fmt.Printf("\t%s\n", instr.String())
}
}
c.parseInstr(frame, instr)
}
if frame.fn.Name() == "init" && len(block.Instrs) == 0 {
c.builder.CreateRetVoid()
}
}
// Resolve phi nodes
for _, phi := range frame.phis {
block := phi.ssa.Block()
for i, edge := range phi.ssa.Edges {
llvmVal := c.getValue(frame, edge)
llvmBlock := frame.blockExits[block.Preds[i]]
phi.llvm.AddIncoming([]llvm.Value{llvmVal}, []llvm.BasicBlock{llvmBlock})
}
}
}
func (c *Compiler) parseInstr(frame *Frame, instr ssa.Instruction) {
if c.Debug {
pos := c.ir.Program.Fset.Position(instr.Pos())
c.builder.SetCurrentDebugLocation(uint(pos.Line), uint(pos.Column), frame.difunc, llvm.Metadata{})
}
switch instr := instr.(type) {
case ssa.Value:
if value, err := c.parseExpr(frame, instr); err != nil {
// This expression could not be parsed. Add the error to the list
// of diagnostics and continue with an undef value.
// The resulting IR will be incorrect (but valid). However,
// compilation can proceed which is useful because there may be
// more compilation errors which can then all be shown together to
// the user.
c.diagnostics = append(c.diagnostics, err)
frame.locals[instr] = llvm.Undef(c.getLLVMType(instr.Type()))
} else {
frame.locals[instr] = value
}
case *ssa.DebugRef:
// ignore
case *ssa.Defer:
c.emitDefer(frame, instr)
case *ssa.Go:
if instr.Call.IsInvoke() {
c.addError(instr.Pos(), "todo: go on method receiver")
return
}
callee := instr.Call.StaticCallee()
if callee == nil {
c.addError(instr.Pos(), "todo: go on non-direct function (function pointer, etc.)")
return
}
calleeFn := c.ir.GetFunction(callee)
// Mark this function as a 'go' invocation and break invalid
// interprocedural optimizations. For example, heap-to-stack
// transformations are not sound as goroutines can outlive their parent.
calleeType := calleeFn.LLVMFn.Type()
calleeValue := c.builder.CreateBitCast(calleeFn.LLVMFn, c.i8ptrType, "")
calleeValue = c.createRuntimeCall("makeGoroutine", []llvm.Value{calleeValue}, "")
calleeValue = c.builder.CreateBitCast(calleeValue, calleeType, "")
// Get all function parameters to pass to the goroutine.
var params []llvm.Value
for _, param := range instr.Call.Args {
params = append(params, c.getValue(frame, param))
}
if !calleeFn.IsExported() {
params = append(params, llvm.Undef(c.i8ptrType)) // context parameter
params = append(params, llvm.Undef(c.i8ptrType)) // parent coroutine handle
}
c.createCall(calleeValue, params, "")
case *ssa.If:
cond := c.getValue(frame, instr.Cond)
block := instr.Block()
blockThen := frame.blockEntries[block.Succs[0]]
blockElse := frame.blockEntries[block.Succs[1]]
c.builder.CreateCondBr(cond, blockThen, blockElse)
case *ssa.Jump:
blockJump := frame.blockEntries[instr.Block().Succs[0]]
c.builder.CreateBr(blockJump)
case *ssa.MapUpdate:
m := c.getValue(frame, instr.Map)
key := c.getValue(frame, instr.Key)
value := c.getValue(frame, instr.Value)
mapType := instr.Map.Type().Underlying().(*types.Map)
c.emitMapUpdate(mapType.Key(), m, key, value, instr.Pos())
case *ssa.Panic:
value := c.getValue(frame, instr.X)
c.createRuntimeCall("_panic", []llvm.Value{value}, "")
c.builder.CreateUnreachable()
case *ssa.Return:
if len(instr.Results) == 0 {
c.builder.CreateRetVoid()
} else if len(instr.Results) == 1 {
c.builder.CreateRet(c.getValue(frame, instr.Results[0]))
} else {
// Multiple return values. Put them all in a struct.
retVal := c.getZeroValue(frame.fn.LLVMFn.Type().ElementType().ReturnType())
for i, result := range instr.Results {
val := c.getValue(frame, result)
retVal = c.builder.CreateInsertValue(retVal, val, i, "")
}
c.builder.CreateRet(retVal)
}
case *ssa.RunDefers:
c.emitRunDefers(frame)
case *ssa.Send:
c.emitChanSend(frame, instr)
case *ssa.Store:
llvmAddr := c.getValue(frame, instr.Addr)
llvmVal := c.getValue(frame, instr.Val)
c.emitNilCheck(frame, llvmAddr, "store")
if c.targetData.TypeAllocSize(llvmVal.Type()) == 0 {
// nothing to store
return
}
c.builder.CreateStore(llvmVal, llvmAddr)
default:
c.addError(instr.Pos(), "unknown instruction: "+instr.String())
}
}
func (c *Compiler) parseBuiltin(frame *Frame, args []ssa.Value, callName string, pos token.Pos) (llvm.Value, error) {
switch callName {
case "append":
src := c.getValue(frame, args[0])
elems := c.getValue(frame, args[1])
srcBuf := c.builder.CreateExtractValue(src, 0, "append.srcBuf")
srcPtr := c.builder.CreateBitCast(srcBuf, c.i8ptrType, "append.srcPtr")
srcLen := c.builder.CreateExtractValue(src, 1, "append.srcLen")
srcCap := c.builder.CreateExtractValue(src, 2, "append.srcCap")
elemsBuf := c.builder.CreateExtractValue(elems, 0, "append.elemsBuf")
elemsPtr := c.builder.CreateBitCast(elemsBuf, c.i8ptrType, "append.srcPtr")
elemsLen := c.builder.CreateExtractValue(elems, 1, "append.elemsLen")
elemType := srcBuf.Type().ElementType()
elemSize := llvm.ConstInt(c.uintptrType, c.targetData.TypeAllocSize(elemType), false)
result := c.createRuntimeCall("sliceAppend", []llvm.Value{srcPtr, elemsPtr, srcLen, srcCap, elemsLen, elemSize}, "append.new")
newPtr := c.builder.CreateExtractValue(result, 0, "append.newPtr")
newBuf := c.builder.CreateBitCast(newPtr, srcBuf.Type(), "append.newBuf")
newLen := c.builder.CreateExtractValue(result, 1, "append.newLen")
newCap := c.builder.CreateExtractValue(result, 2, "append.newCap")
newSlice := llvm.Undef(src.Type())
newSlice = c.builder.CreateInsertValue(newSlice, newBuf, 0, "")
newSlice = c.builder.CreateInsertValue(newSlice, newLen, 1, "")
newSlice = c.builder.CreateInsertValue(newSlice, newCap, 2, "")
return newSlice, nil
case "cap":
value := c.getValue(frame, args[0])
var llvmCap llvm.Value
switch args[0].Type().(type) {
case *types.Chan:
// Channel. Buffered channels haven't been implemented yet so always
// return 0.
llvmCap = llvm.ConstInt(c.intType, 0, false)
case *types.Slice:
llvmCap = c.builder.CreateExtractValue(value, 2, "cap")
default:
return llvm.Value{}, c.makeError(pos, "todo: cap: unknown type")
}
if c.targetData.TypeAllocSize(llvmCap.Type()) < c.targetData.TypeAllocSize(c.intType) {
llvmCap = c.builder.CreateZExt(llvmCap, c.intType, "len.int")
}
return llvmCap, nil
case "close":
c.emitChanClose(frame, args[0])
return llvm.Value{}, nil
case "complex":
r := c.getValue(frame, args[0])
i := c.getValue(frame, args[1])
t := args[0].Type().Underlying().(*types.Basic)
var cplx llvm.Value
switch t.Kind() {
case types.Float32:
cplx = llvm.Undef(c.ctx.StructType([]llvm.Type{c.ctx.FloatType(), c.ctx.FloatType()}, false))
case types.Float64:
cplx = llvm.Undef(c.ctx.StructType([]llvm.Type{c.ctx.DoubleType(), c.ctx.DoubleType()}, false))
default:
return llvm.Value{}, c.makeError(pos, "unsupported type in complex builtin: "+t.String())
}
cplx = c.builder.CreateInsertValue(cplx, r, 0, "")
cplx = c.builder.CreateInsertValue(cplx, i, 1, "")
return cplx, nil
case "copy":
dst := c.getValue(frame, args[0])
src := c.getValue(frame, args[1])
dstLen := c.builder.CreateExtractValue(dst, 1, "copy.dstLen")
srcLen := c.builder.CreateExtractValue(src, 1, "copy.srcLen")
dstBuf := c.builder.CreateExtractValue(dst, 0, "copy.dstArray")
srcBuf := c.builder.CreateExtractValue(src, 0, "copy.srcArray")
elemType := dstBuf.Type().ElementType()
dstBuf = c.builder.CreateBitCast(dstBuf, c.i8ptrType, "copy.dstPtr")
srcBuf = c.builder.CreateBitCast(srcBuf, c.i8ptrType, "copy.srcPtr")
elemSize := llvm.ConstInt(c.uintptrType, c.targetData.TypeAllocSize(elemType), false)
return c.createRuntimeCall("sliceCopy", []llvm.Value{dstBuf, srcBuf, dstLen, srcLen, elemSize}, "copy.n"), nil
case "delete":
m := c.getValue(frame, args[0])
key := c.getValue(frame, args[1])
return llvm.Value{}, c.emitMapDelete(args[1].Type(), m, key, pos)
case "imag":
cplx := c.getValue(frame, args[0])
return c.builder.CreateExtractValue(cplx, 1, "imag"), nil
case "len":
value := c.getValue(frame, args[0])
var llvmLen llvm.Value
switch args[0].Type().Underlying().(type) {
case *types.Basic, *types.Slice:
// string or slice
llvmLen = c.builder.CreateExtractValue(value, 1, "len")
case *types.Chan:
// Channel. Buffered channels haven't been implemented yet so always
// return 0.
llvmLen = llvm.ConstInt(c.intType, 0, false)
case *types.Map:
llvmLen = c.createRuntimeCall("hashmapLen", []llvm.Value{value}, "len")
default:
return llvm.Value{}, c.makeError(pos, "todo: len: unknown type")
}
if c.targetData.TypeAllocSize(llvmLen.Type()) < c.targetData.TypeAllocSize(c.intType) {
llvmLen = c.builder.CreateZExt(llvmLen, c.intType, "len.int")
}
return llvmLen, nil
case "print", "println":
for i, arg := range args {
if i >= 1 && callName == "println" {
c.createRuntimeCall("printspace", nil, "")
}
value := c.getValue(frame, arg)
typ := arg.Type().Underlying()
switch typ := typ.(type) {
case *types.Basic:
switch typ.Kind() {
case types.String, types.UntypedString:
c.createRuntimeCall("printstring", []llvm.Value{value}, "")
case types.Uintptr:
c.createRuntimeCall("printptr", []llvm.Value{value}, "")
case types.UnsafePointer:
ptrValue := c.builder.CreatePtrToInt(value, c.uintptrType, "")
c.createRuntimeCall("printptr", []llvm.Value{ptrValue}, "")
default:
// runtime.print{int,uint}{8,16,32,64}
if typ.Info()&types.IsInteger != 0 {
name := "print"
if typ.Info()&types.IsUnsigned != 0 {
name += "uint"
} else {
name += "int"
}
name += strconv.FormatUint(c.targetData.TypeAllocSize(value.Type())*8, 10)
c.createRuntimeCall(name, []llvm.Value{value}, "")
} else if typ.Kind() == types.Bool {
c.createRuntimeCall("printbool", []llvm.Value{value}, "")
} else if typ.Kind() == types.Float32 {
c.createRuntimeCall("printfloat32", []llvm.Value{value}, "")
} else if typ.Kind() == types.Float64 {
c.createRuntimeCall("printfloat64", []llvm.Value{value}, "")
} else if typ.Kind() == types.Complex64 {
c.createRuntimeCall("printcomplex64", []llvm.Value{value}, "")
} else if typ.Kind() == types.Complex128 {
c.createRuntimeCall("printcomplex128", []llvm.Value{value}, "")
} else {
return llvm.Value{}, c.makeError(pos, "unknown basic arg type: "+typ.String())
}
}
case *types.Interface:
c.createRuntimeCall("printitf", []llvm.Value{value}, "")
case *types.Map:
c.createRuntimeCall("printmap", []llvm.Value{value}, "")
case *types.Pointer:
ptrValue := c.builder.CreatePtrToInt(value, c.uintptrType, "")
c.createRuntimeCall("printptr", []llvm.Value{ptrValue}, "")
default:
return llvm.Value{}, c.makeError(pos, "unknown arg type: "+typ.String())
}
}
if callName == "println" {
c.createRuntimeCall("printnl", nil, "")
}
return llvm.Value{}, nil // print() or println() returns void
case "real":
cplx := c.getValue(frame, args[0])
return c.builder.CreateExtractValue(cplx, 0, "real"), nil
case "recover":
return c.createRuntimeCall("_recover", nil, ""), nil
case "ssa:wrapnilchk":
// TODO: do an actual nil check?
return c.getValue(frame, args[0]), nil
default:
return llvm.Value{}, c.makeError(pos, "todo: builtin: "+callName)
}
}
func (c *Compiler) parseFunctionCall(frame *Frame, args []ssa.Value, llvmFn, context llvm.Value, exported bool) llvm.Value {
var params []llvm.Value
for _, param := range args {
params = append(params, c.getValue(frame, param))
}
if !exported {
// This function takes a context parameter.
// Add it to the end of the parameter list.
params = append(params, context)
// Parent coroutine handle.
params = append(params, llvm.Undef(c.i8ptrType))
}
return c.createCall(llvmFn, params, "")
}
func (c *Compiler) parseCall(frame *Frame, instr *ssa.CallCommon) (llvm.Value, error) {
if instr.IsInvoke() {
fnCast, args := c.getInvokeCall(frame, instr)
return c.createCall(fnCast, args, ""), nil
}
// Try to call the function directly for trivially static calls.
if fn := instr.StaticCallee(); fn != nil {
name := fn.RelString(nil)
switch {
case name == "device/arm.ReadRegister":
return c.emitReadRegister(instr.Args)
case name == "device/arm.Asm" || name == "device/avr.Asm":
return c.emitAsm(instr.Args)
case name == "device/arm.AsmFull" || name == "device/avr.AsmFull":
return c.emitAsmFull(frame, instr)
case strings.HasPrefix(name, "device/arm.SVCall"):
return c.emitSVCall(frame, instr.Args)
case strings.HasPrefix(name, "syscall.Syscall"):
return c.emitSyscall(frame, instr)
case strings.HasPrefix(name, "runtime/volatile.Load"):
return c.emitVolatileLoad(frame, instr)
case strings.HasPrefix(name, "runtime/volatile.Store"):
return c.emitVolatileStore(frame, instr)
}
targetFunc := c.ir.GetFunction(fn)
if targetFunc.LLVMFn.IsNil() {
return llvm.Value{}, c.makeError(instr.Pos(), "undefined function: "+targetFunc.LinkName())
}
var context llvm.Value
switch value := instr.Value.(type) {
case *ssa.Function:
// Regular function call. No context is necessary.
context = llvm.Undef(c.i8ptrType)
case *ssa.MakeClosure:
// A call on a func value, but the callee is trivial to find. For
// example: immediately applied functions.
funcValue := c.getValue(frame, value)
context = c.extractFuncContext(funcValue)
default:
panic("StaticCallee returned an unexpected value")
}
return c.parseFunctionCall(frame, instr.Args, targetFunc.LLVMFn, context, targetFunc.IsExported()), nil
}
// Builtin or function pointer.
switch call := instr.Value.(type) {
case *ssa.Builtin:
return c.parseBuiltin(frame, instr.Args, call.Name(), instr.Pos())
default: // function pointer
value := c.getValue(frame, instr.Value)
// This is a func value, which cannot be called directly. We have to
// extract the function pointer and context first from the func value.
funcPtr, context, err := c.decodeFuncValue(value, instr.Value.Type().Underlying().(*types.Signature))
if err != nil {
return llvm.Value{}, err
}
c.emitNilCheck(frame, funcPtr, "fpcall")
return c.parseFunctionCall(frame, instr.Args, funcPtr, context, false), nil
}
}
// getValue returns the LLVM value of a constant, function value, global, or
// already processed SSA expression.
func (c *Compiler) getValue(frame *Frame, expr ssa.Value) llvm.Value {
switch expr := expr.(type) {
case *ssa.Const:
return c.parseConst(frame.fn.LinkName(), expr)
case *ssa.Function:
fn := c.ir.GetFunction(expr)
if fn.IsExported() {
c.addError(expr.Pos(), "cannot use an exported function as value: "+expr.String())
return llvm.Undef(c.getLLVMType(expr.Type()))
}
return c.createFuncValue(fn.LLVMFn, llvm.Undef(c.i8ptrType), fn.Signature)
case *ssa.Global:
value := c.ir.GetGlobal(expr).LLVMGlobal
if value.IsNil() {
c.addError(expr.Pos(), "global not found: "+c.ir.GetGlobal(expr).LinkName())
return llvm.Undef(c.getLLVMType(expr.Type()))
}
return value
default:
// other (local) SSA value
if value, ok := frame.locals[expr]; ok {
return value
} else {
// indicates a compiler bug
panic("local has not been parsed: " + expr.String())
}
}
}
// parseExpr translates a Go SSA expression to a LLVM instruction.
func (c *Compiler) parseExpr(frame *Frame, expr ssa.Value) (llvm.Value, error) {
if _, ok := frame.locals[expr]; ok {
// sanity check
panic("local has already been parsed: " + expr.String())
}
switch expr := expr.(type) {
case *ssa.Alloc:
typ := c.getLLVMType(expr.Type().Underlying().(*types.Pointer).Elem())
if expr.Heap {
size := c.targetData.TypeAllocSize(typ)
// Calculate ^uintptr(0)
maxSize := llvm.ConstNot(llvm.ConstInt(c.uintptrType, 0, false)).ZExtValue()
if size > maxSize {
// Size would be truncated if truncated to uintptr.
return llvm.Value{}, c.makeError(expr.Pos(), fmt.Sprintf("value is too big (%v bytes)", size))
}
// TODO: escape analysis
sizeValue := llvm.ConstInt(c.uintptrType, size, false)
buf := c.createRuntimeCall("alloc", []llvm.Value{sizeValue}, expr.Comment)
buf = c.builder.CreateBitCast(buf, llvm.PointerType(typ, 0), "")
return buf, nil
} else {
buf := c.createEntryBlockAlloca(typ, expr.Comment)
if c.targetData.TypeAllocSize(typ) != 0 {
c.builder.CreateStore(c.getZeroValue(typ), buf) // zero-initialize var
}
return buf, nil
}
case *ssa.BinOp:
x := c.getValue(frame, expr.X)
y := c.getValue(frame, expr.Y)
return c.parseBinOp(expr.Op, expr.X.Type(), x, y, expr.Pos())
case *ssa.Call:
// Passing the current task here to the subroutine. It is only used when
// the subroutine is blocking.
return c.parseCall(frame, expr.Common())
case *ssa.ChangeInterface:
// Do not change between interface types: always use the underlying
// (concrete) type in the type number of the interface. Every method
// call on an interface will do a lookup which method to call.
// This is different from how the official Go compiler works, because of
// heap allocation and because it's easier to implement, see:
// https://research.swtch.com/interfaces
return c.getValue(frame, expr.X), nil
case *ssa.ChangeType:
// This instruction changes the type, but the underlying value remains
// the same. This is often a no-op, but sometimes we have to change the
// LLVM type as well.
x := c.getValue(frame, expr.X)
llvmType := c.getLLVMType(expr.Type())
if x.Type() == llvmType {
// Different Go type but same LLVM type (for example, named int).
// This is the common case.
return x, nil
}
// Figure out what kind of type we need to cast.
switch llvmType.TypeKind() {
case llvm.StructTypeKind:
// Unfortunately, we can't just bitcast structs. We have to
// actually create a new struct of the correct type and insert the
// values from the previous struct in there.
value := llvm.Undef(llvmType)
for i := 0; i < llvmType.StructElementTypesCount(); i++ {
field := c.builder.CreateExtractValue(x, i, "changetype.field")
value = c.builder.CreateInsertValue(value, field, i, "changetype.struct")
}
return value, nil
case llvm.PointerTypeKind:
// This can happen with pointers to structs. This case is easy:
// simply bitcast the pointer to the destination type.
return c.builder.CreateBitCast(x, llvmType, "changetype.pointer"), nil
default:
return llvm.Value{}, errors.New("todo: unknown ChangeType type: " + expr.X.Type().String())
}
case *ssa.Const:
panic("const is not an expression")
case *ssa.Convert:
x := c.getValue(frame, expr.X)
return c.parseConvert(expr.X.Type(), expr.Type(), x, expr.Pos())
case *ssa.Extract:
value := c.getValue(frame, expr.Tuple)
result := c.builder.CreateExtractValue(value, expr.Index, "")
return result, nil
case *ssa.Field:
value := c.getValue(frame, expr.X)
if s := expr.X.Type().Underlying().(*types.Struct); s.NumFields() > 2 && s.Field(0).Name() == "C union" {
// Extract a field from a CGo union.
// This could be done directly, but as this is a very infrequent
// operation it's much easier to bitcast it through an alloca.
resultType := c.getLLVMType(expr.Type())
alloca, allocaPtr, allocaSize := c.createTemporaryAlloca(value.Type(), "union.alloca")
c.builder.CreateStore(value, alloca)
bitcast := c.builder.CreateBitCast(alloca, llvm.PointerType(resultType, 0), "union.bitcast")
result := c.builder.CreateLoad(bitcast, "union.result")
c.emitLifetimeEnd(allocaPtr, allocaSize)
return result, nil
}
result := c.builder.CreateExtractValue(value, expr.Field, "")
return result, nil
case *ssa.FieldAddr:
val := c.getValue(frame, expr.X)
// Check for nil pointer before calculating the address, from the spec:
// > For an operand x of type T, the address operation &x generates a
// > pointer of type *T to x. [...] If the evaluation of x would cause a
// > run-time panic, then the evaluation of &x does too.
c.emitNilCheck(frame, val, "gep")
if s := expr.X.Type().(*types.Pointer).Elem().Underlying().(*types.Struct); s.NumFields() > 2 && s.Field(0).Name() == "C union" {
// This is not a regular struct but actually an union.
// That simplifies things, as we can just bitcast the pointer to the
// right type.
ptrType := c.getLLVMType(expr.Type())
return c.builder.CreateBitCast(val, ptrType, ""), nil
} else {
// Do a GEP on the pointer to get the field address.
indices := []llvm.Value{
llvm.ConstInt(c.ctx.Int32Type(), 0, false),
llvm.ConstInt(c.ctx.Int32Type(), uint64(expr.Field), false),
}
return c.builder.CreateInBoundsGEP(val, indices, ""), nil
}
case *ssa.Function:
panic("function is not an expression")
case *ssa.Global:
panic("global is not an expression")
case *ssa.Index:
array := c.getValue(frame, expr.X)
index := c.getValue(frame, expr.Index)
// Check bounds.
arrayLen := expr.X.Type().(*types.Array).Len()
arrayLenLLVM := llvm.ConstInt(c.uintptrType, uint64(arrayLen), false)
c.emitLookupBoundsCheck(frame, arrayLenLLVM, index, expr.Index.Type())
// Can't load directly from array (as index is non-constant), so have to
// do it using an alloca+gep+load.
alloca, allocaPtr, allocaSize := c.createTemporaryAlloca(array.Type(), "index.alloca")
c.builder.CreateStore(array, alloca)
zero := llvm.ConstInt(c.ctx.Int32Type(), 0, false)
ptr := c.builder.CreateInBoundsGEP(alloca, []llvm.Value{zero, index}, "index.gep")
result := c.builder.CreateLoad(ptr, "index.load")
c.emitLifetimeEnd(allocaPtr, allocaSize)
return result, nil
case *ssa.IndexAddr:
val := c.getValue(frame, expr.X)
index := c.getValue(frame, expr.Index)
// Get buffer pointer and length
var bufptr, buflen llvm.Value
switch ptrTyp := expr.X.Type().Underlying().(type) {
case *types.Pointer:
typ := expr.X.Type().Underlying().(*types.Pointer).Elem().Underlying()
switch typ := typ.(type) {
case *types.Array:
bufptr = val
buflen = llvm.ConstInt(c.uintptrType, uint64(typ.Len()), false)
// Check for nil pointer before calculating the address, from
// the spec:
// > For an operand x of type T, the address operation &x
// > generates a pointer of type *T to x. [...] If the
// > evaluation of x would cause a run-time panic, then the
// > evaluation of &x does too.
c.emitNilCheck(frame, bufptr, "gep")
default:
return llvm.Value{}, c.makeError(expr.Pos(), "todo: indexaddr: "+typ.String())
}
case *types.Slice:
bufptr = c.builder.CreateExtractValue(val, 0, "indexaddr.ptr")
buflen = c.builder.CreateExtractValue(val, 1, "indexaddr.len")
default:
return llvm.Value{}, c.makeError(expr.Pos(), "todo: indexaddr: "+ptrTyp.String())
}
// Bounds check.
c.emitLookupBoundsCheck(frame, buflen, index, expr.Index.Type())
switch expr.X.Type().Underlying().(type) {
case *types.Pointer:
indices := []llvm.Value{
llvm.ConstInt(c.ctx.Int32Type(), 0, false),
index,
}
return c.builder.CreateInBoundsGEP(bufptr, indices, ""), nil
case *types.Slice:
return c.builder.CreateInBoundsGEP(bufptr, []llvm.Value{index}, ""), nil
default:
panic("unreachable")
}
case *ssa.Lookup:
value := c.getValue(frame, expr.X)
index := c.getValue(frame, expr.Index)
switch xType := expr.X.Type().Underlying().(type) {
case *types.Basic:
// Value type must be a string, which is a basic type.
if xType.Info()&types.IsString == 0 {
panic("lookup on non-string?")
}
// Bounds check.
length := c.builder.CreateExtractValue(value, 1, "len")
c.emitLookupBoundsCheck(frame, length, index, expr.Index.Type())
// Lookup byte
buf := c.builder.CreateExtractValue(value, 0, "")
bufPtr := c.builder.CreateInBoundsGEP(buf, []llvm.Value{index}, "")
return c.builder.CreateLoad(bufPtr, ""), nil
case *types.Map:
valueType := expr.Type()
if expr.CommaOk {
valueType = valueType.(*types.Tuple).At(0).Type()
}
return c.emitMapLookup(xType.Key(), valueType, value, index, expr.CommaOk, expr.Pos())
default:
panic("unknown lookup type: " + expr.String())
}
case *ssa.MakeChan:
return c.emitMakeChan(expr)
case *ssa.MakeClosure:
return c.parseMakeClosure(frame, expr)
case *ssa.MakeInterface:
val := c.getValue(frame, expr.X)
return c.parseMakeInterface(val, expr.X.Type(), expr.Pos()), nil
case *ssa.MakeMap:
mapType := expr.Type().Underlying().(*types.Map)
llvmKeyType := c.getLLVMType(mapType.Key().Underlying())
llvmValueType := c.getLLVMType(mapType.Elem().Underlying())
keySize := c.targetData.TypeAllocSize(llvmKeyType)
valueSize := c.targetData.TypeAllocSize(llvmValueType)
llvmKeySize := llvm.ConstInt(c.ctx.Int8Type(), keySize, false)
llvmValueSize := llvm.ConstInt(c.ctx.Int8Type(), valueSize, false)
sizeHint := llvm.ConstInt(c.uintptrType, 8, false)
if expr.Reserve != nil {
sizeHint = c.getValue(frame, expr.Reserve)
var err error
sizeHint, err = c.parseConvert(expr.Reserve.Type(), types.Typ[types.Uintptr], sizeHint, expr.Pos())
if err != nil {
return llvm.Value{}, err
}
}
hashmap := c.createRuntimeCall("hashmapMake", []llvm.Value{llvmKeySize, llvmValueSize, sizeHint}, "")
return hashmap, nil
case *ssa.MakeSlice:
sliceLen := c.getValue(frame, expr.Len)
sliceCap := c.getValue(frame, expr.Cap)
sliceType := expr.Type().Underlying().(*types.Slice)
llvmElemType := c.getLLVMType(sliceType.Elem())
elemSize := c.targetData.TypeAllocSize(llvmElemType)
elemSizeValue := llvm.ConstInt(c.uintptrType, elemSize, false)
// Calculate (^uintptr(0)) >> 1, which is the max value that fits in
// uintptr if uintptr were signed.
maxSize := llvm.ConstLShr(llvm.ConstNot(llvm.ConstInt(c.uintptrType, 0, false)), llvm.ConstInt(c.uintptrType, 1, false))
if elemSize > maxSize.ZExtValue() {
// This seems to be checked by the typechecker already, but let's
// check it again just to be sure.
return llvm.Value{}, c.makeError(expr.Pos(), fmt.Sprintf("slice element type is too big (%v bytes)", elemSize))
}
// Bounds checking.
c.emitSliceBoundsCheck(frame, maxSize, sliceLen, sliceCap, expr.Len.Type().(*types.Basic), expr.Cap.Type().(*types.Basic))
// Allocate the backing array.
// TODO: escape analysis
sliceCapCast, err := c.parseConvert(expr.Cap.Type(), types.Typ[types.Uintptr], sliceCap, expr.Pos())
if err != nil {
return llvm.Value{}, err
}
sliceSize := c.builder.CreateBinOp(llvm.Mul, elemSizeValue, sliceCapCast, "makeslice.cap")
slicePtr := c.createRuntimeCall("alloc", []llvm.Value{sliceSize}, "makeslice.buf")
slicePtr = c.builder.CreateBitCast(slicePtr, llvm.PointerType(llvmElemType, 0), "makeslice.array")
// Extend or truncate if necessary. This is safe as we've already done
// the bounds check.
sliceLen, err = c.parseConvert(expr.Len.Type(), types.Typ[types.Uintptr], sliceLen, expr.Pos())
if err != nil {
return llvm.Value{}, err
}
sliceCap, err = c.parseConvert(expr.Cap.Type(), types.Typ[types.Uintptr], sliceCap, expr.Pos())
if err != nil {
return llvm.Value{}, err
}
// Create the slice.
slice := c.ctx.ConstStruct([]llvm.Value{
llvm.Undef(slicePtr.Type()),
llvm.Undef(c.uintptrType),
llvm.Undef(c.uintptrType),
}, false)
slice = c.builder.CreateInsertValue(slice, slicePtr, 0, "")
slice = c.builder.CreateInsertValue(slice, sliceLen, 1, "")
slice = c.builder.CreateInsertValue(slice, sliceCap, 2, "")
return slice, nil
case *ssa.Next:
rangeVal := expr.Iter.(*ssa.Range).X
llvmRangeVal := c.getValue(frame, rangeVal)
it := c.getValue(frame, expr.Iter)
if expr.IsString {
return c.createRuntimeCall("stringNext", []llvm.Value{llvmRangeVal, it}, "range.next"), nil
} else { // map
llvmKeyType := c.getLLVMType(rangeVal.Type().Underlying().(*types.Map).Key())
llvmValueType := c.getLLVMType(rangeVal.Type().Underlying().(*types.Map).Elem())
mapKeyAlloca, mapKeyPtr, mapKeySize := c.createTemporaryAlloca(llvmKeyType, "range.key")
mapValueAlloca, mapValuePtr, mapValueSize := c.createTemporaryAlloca(llvmValueType, "range.value")
ok := c.createRuntimeCall("hashmapNext", []llvm.Value{llvmRangeVal, it, mapKeyPtr, mapValuePtr}, "range.next")
tuple := llvm.Undef(c.ctx.StructType([]llvm.Type{c.ctx.Int1Type(), llvmKeyType, llvmValueType}, false))
tuple = c.builder.CreateInsertValue(tuple, ok, 0, "")
tuple = c.builder.CreateInsertValue(tuple, c.builder.CreateLoad(mapKeyAlloca, ""), 1, "")
tuple = c.builder.CreateInsertValue(tuple, c.builder.CreateLoad(mapValueAlloca, ""), 2, "")
c.emitLifetimeEnd(mapKeyPtr, mapKeySize)
c.emitLifetimeEnd(mapValuePtr, mapValueSize)
return tuple, nil
}
case *ssa.Phi:
phi := c.builder.CreatePHI(c.getLLVMType(expr.Type()), "")
frame.phis = append(frame.phis, Phi{expr, phi})
return phi, nil
case *ssa.Range:
var iteratorType llvm.Type
switch typ := expr.X.Type().Underlying().(type) {
case *types.Basic: // string
iteratorType = c.mod.GetTypeByName("runtime.stringIterator")
case *types.Map:
iteratorType = c.mod.GetTypeByName("runtime.hashmapIterator")
default:
panic("unknown type in range: " + typ.String())
}
it, _, _ := c.createTemporaryAlloca(iteratorType, "range.it")
c.builder.CreateStore(c.getZeroValue(iteratorType), it)
return it, nil
case *ssa.Select:
if len(expr.States) == 0 {
// Shortcuts for some simple selects.
llvmType := c.getLLVMType(expr.Type())
if expr.Blocking {
// Blocks forever:
// select {}
c.createRuntimeCall("deadlockStub", nil, "")
return llvm.Undef(llvmType), nil
} else {
// No-op:
// select {
// default:
// }
retval := llvm.Undef(llvmType)
retval = c.builder.CreateInsertValue(retval, llvm.ConstInt(c.intType, 0xffffffffffffffff, true), 0, "")
return retval, nil // {-1, false}
}
}
return llvm.Value{}, c.makeError(expr.Pos(), "unimplemented: "+expr.String())
case *ssa.Slice:
if expr.Max != nil {
return llvm.Value{}, c.makeError(expr.Pos(), "todo: full slice expressions (with max): "+expr.Type().String())
}
value := c.getValue(frame, expr.X)
var lowType, highType *types.Basic
var low, high llvm.Value
if expr.Low != nil {
lowType = expr.Low.Type().Underlying().(*types.Basic)
low = c.getValue(frame, expr.Low)
if low.Type().IntTypeWidth() < c.uintptrType.IntTypeWidth() {
if lowType.Info()&types.IsUnsigned != 0 {
low = c.builder.CreateZExt(low, c.uintptrType, "")
} else {
low = c.builder.CreateSExt(low, c.uintptrType, "")
}
}
} else {
lowType = types.Typ[types.Uintptr]
low = llvm.ConstInt(c.uintptrType, 0, false)
}
if expr.High != nil {
highType = expr.High.Type().Underlying().(*types.Basic)
high = c.getValue(frame, expr.High)
if high.Type().IntTypeWidth() < c.uintptrType.IntTypeWidth() {
if highType.Info()&types.IsUnsigned != 0 {
high = c.builder.CreateZExt(high, c.uintptrType, "")
} else {
high = c.builder.CreateSExt(high, c.uintptrType, "")
}
}
} else {
highType = types.Typ[types.Uintptr]
}
switch typ := expr.X.Type().Underlying().(type) {
case *types.Pointer: // pointer to array
// slice an array
length := typ.Elem().Underlying().(*types.Array).Len()
llvmLen := llvm.ConstInt(c.uintptrType, uint64(length), false)
if high.IsNil() {
high = llvmLen
}
indices := []llvm.Value{
llvm.ConstInt(c.ctx.Int32Type(), 0, false),
low,
}
c.emitSliceBoundsCheck(frame, llvmLen, low, high, lowType, highType)
// Truncate ints bigger than uintptr. This is after the bounds
// check so it's safe.
if c.targetData.TypeAllocSize(high.Type()) > c.targetData.TypeAllocSize(c.uintptrType) {
high = c.builder.CreateTrunc(high, c.uintptrType, "")
}
if c.targetData.TypeAllocSize(low.Type()) > c.targetData.TypeAllocSize(c.uintptrType) {
low = c.builder.CreateTrunc(low, c.uintptrType, "")
}
sliceLen := c.builder.CreateSub(high, low, "slice.len")
slicePtr := c.builder.CreateInBoundsGEP(value, indices, "slice.ptr")
sliceCap := c.builder.CreateSub(llvmLen, low, "slice.cap")
slice := c.ctx.ConstStruct([]llvm.Value{
llvm.Undef(slicePtr.Type()),
llvm.Undef(c.uintptrType),
llvm.Undef(c.uintptrType),
}, false)
slice = c.builder.CreateInsertValue(slice, slicePtr, 0, "")
slice = c.builder.CreateInsertValue(slice, sliceLen, 1, "")
slice = c.builder.CreateInsertValue(slice, sliceCap, 2, "")
return slice, nil
case *types.Slice:
// slice a slice
oldPtr := c.builder.CreateExtractValue(value, 0, "")
oldLen := c.builder.CreateExtractValue(value, 1, "")
oldCap := c.builder.CreateExtractValue(value, 2, "")
if high.IsNil() {
high = oldLen
}
c.emitSliceBoundsCheck(frame, oldCap, low, high, lowType, highType)
// Truncate ints bigger than uintptr. This is after the bounds
// check so it's safe.
if c.targetData.TypeAllocSize(low.Type()) > c.targetData.TypeAllocSize(c.uintptrType) {
low = c.builder.CreateTrunc(low, c.uintptrType, "")
}
if c.targetData.TypeAllocSize(high.Type()) > c.targetData.TypeAllocSize(c.uintptrType) {
high = c.builder.CreateTrunc(high, c.uintptrType, "")
}
newPtr := c.builder.CreateInBoundsGEP(oldPtr, []llvm.Value{low}, "")
newLen := c.builder.CreateSub(high, low, "")
newCap := c.builder.CreateSub(oldCap, low, "")
slice := c.ctx.ConstStruct([]llvm.Value{
llvm.Undef(newPtr.Type()),
llvm.Undef(c.uintptrType),
llvm.Undef(c.uintptrType),
}, false)
slice = c.builder.CreateInsertValue(slice, newPtr, 0, "")
slice = c.builder.CreateInsertValue(slice, newLen, 1, "")
slice = c.builder.CreateInsertValue(slice, newCap, 2, "")
return slice, nil
case *types.Basic:
if typ.Info()&types.IsString == 0 {
return llvm.Value{}, c.makeError(expr.Pos(), "unknown slice type: "+typ.String())
}
// slice a string
oldPtr := c.builder.CreateExtractValue(value, 0, "")
oldLen := c.builder.CreateExtractValue(value, 1, "")
if high.IsNil() {
high = oldLen
}
c.emitSliceBoundsCheck(frame, oldLen, low, high, lowType, highType)
// Truncate ints bigger than uintptr. This is after the bounds
// check so it's safe.
if c.targetData.TypeAllocSize(low.Type()) > c.targetData.TypeAllocSize(c.uintptrType) {
low = c.builder.CreateTrunc(low, c.uintptrType, "")
}
if c.targetData.TypeAllocSize(high.Type()) > c.targetData.TypeAllocSize(c.uintptrType) {
high = c.builder.CreateTrunc(high, c.uintptrType, "")
}
newPtr := c.builder.CreateInBoundsGEP(oldPtr, []llvm.Value{low}, "")
newLen := c.builder.CreateSub(high, low, "")
str := llvm.Undef(c.mod.GetTypeByName("runtime._string"))
str = c.builder.CreateInsertValue(str, newPtr, 0, "")
str = c.builder.CreateInsertValue(str, newLen, 1, "")
return str, nil
default:
return llvm.Value{}, c.makeError(expr.Pos(), "unknown slice type: "+typ.String())
}
case *ssa.TypeAssert:
return c.parseTypeAssert(frame, expr), nil
case *ssa.UnOp:
return c.parseUnOp(frame, expr)
default:
return llvm.Value{}, c.makeError(expr.Pos(), "todo: unknown expression: "+expr.String())
}
}
func (c *Compiler) parseBinOp(op token.Token, typ types.Type, x, y llvm.Value, pos token.Pos) (llvm.Value, error) {
switch typ := typ.Underlying().(type) {
case *types.Basic:
if typ.Info()&types.IsInteger != 0 {
// Operations on integers
signed := typ.Info()&types.IsUnsigned == 0
switch op {
case token.ADD: // +
return c.builder.CreateAdd(x, y, ""), nil
case token.SUB: // -
return c.builder.CreateSub(x, y, ""), nil
case token.MUL: // *
return c.builder.CreateMul(x, y, ""), nil
case token.QUO: // /
if signed {
return c.builder.CreateSDiv(x, y, ""), nil
} else {
return c.builder.CreateUDiv(x, y, ""), nil
}
case token.REM: // %
if signed {
return c.builder.CreateSRem(x, y, ""), nil
} else {
return c.builder.CreateURem(x, y, ""), nil
}
case token.AND: // &
return c.builder.CreateAnd(x, y, ""), nil
case token.OR: // |
return c.builder.CreateOr(x, y, ""), nil
case token.XOR: // ^
return c.builder.CreateXor(x, y, ""), nil
case token.SHL, token.SHR:
sizeX := c.targetData.TypeAllocSize(x.Type())
sizeY := c.targetData.TypeAllocSize(y.Type())
if sizeX > sizeY {
// x and y must have equal sizes, make Y bigger in this case.
// y is unsigned, this has been checked by the Go type checker.
y = c.builder.CreateZExt(y, x.Type(), "")
} else if sizeX < sizeY {
// What about shifting more than the integer width?
// I'm not entirely sure what the Go spec is on that, but as
// Intel CPUs have undefined behavior when shifting more
// than the integer width I'm assuming it is also undefined
// in Go.
y = c.builder.CreateTrunc(y, x.Type(), "")
}
switch op {
case token.SHL: // <<
return c.builder.CreateShl(x, y, ""), nil
case token.SHR: // >>
if signed {
return c.builder.CreateAShr(x, y, ""), nil
} else {
return c.builder.CreateLShr(x, y, ""), nil
}
default:
panic("unreachable")
}
case token.EQL: // ==
return c.builder.CreateICmp(llvm.IntEQ, x, y, ""), nil
case token.NEQ: // !=
return c.builder.CreateICmp(llvm.IntNE, x, y, ""), nil
case token.AND_NOT: // &^
// Go specific. Calculate "and not" with x & (~y)
inv := c.builder.CreateNot(y, "") // ~y
return c.builder.CreateAnd(x, inv, ""), nil
case token.LSS: // <
if signed {
return c.builder.CreateICmp(llvm.IntSLT, x, y, ""), nil
} else {
return c.builder.CreateICmp(llvm.IntULT, x, y, ""), nil
}
case token.LEQ: // <=
if signed {
return c.builder.CreateICmp(llvm.IntSLE, x, y, ""), nil
} else {
return c.builder.CreateICmp(llvm.IntULE, x, y, ""), nil
}
case token.GTR: // >
if signed {
return c.builder.CreateICmp(llvm.IntSGT, x, y, ""), nil
} else {
return c.builder.CreateICmp(llvm.IntUGT, x, y, ""), nil
}
case token.GEQ: // >=
if signed {
return c.builder.CreateICmp(llvm.IntSGE, x, y, ""), nil
} else {
return c.builder.CreateICmp(llvm.IntUGE, x, y, ""), nil
}
default:
panic("binop on integer: " + op.String())
}
} else if typ.Info()&types.IsFloat != 0 {
// Operations on floats
switch op {
case token.ADD: // +
return c.builder.CreateFAdd(x, y, ""), nil
case token.SUB: // -
return c.builder.CreateFSub(x, y, ""), nil
case token.MUL: // *
return c.builder.CreateFMul(x, y, ""), nil
case token.QUO: // /
return c.builder.CreateFDiv(x, y, ""), nil
case token.EQL: // ==
return c.builder.CreateFCmp(llvm.FloatUEQ, x, y, ""), nil
case token.NEQ: // !=
return c.builder.CreateFCmp(llvm.FloatUNE, x, y, ""), nil
case token.LSS: // <
return c.builder.CreateFCmp(llvm.FloatULT, x, y, ""), nil
case token.LEQ: // <=
return c.builder.CreateFCmp(llvm.FloatULE, x, y, ""), nil
case token.GTR: // >
return c.builder.CreateFCmp(llvm.FloatUGT, x, y, ""), nil
case token.GEQ: // >=
return c.builder.CreateFCmp(llvm.FloatUGE, x, y, ""), nil
default:
panic("binop on float: " + op.String())
}
} else if typ.Info()&types.IsComplex != 0 {
r1 := c.builder.CreateExtractValue(x, 0, "r1")
r2 := c.builder.CreateExtractValue(y, 0, "r2")
i1 := c.builder.CreateExtractValue(x, 1, "i1")
i2 := c.builder.CreateExtractValue(y, 1, "i2")
switch op {
case token.EQL: // ==
req := c.builder.CreateFCmp(llvm.FloatOEQ, r1, r2, "")
ieq := c.builder.CreateFCmp(llvm.FloatOEQ, i1, i2, "")
return c.builder.CreateAnd(req, ieq, ""), nil
case token.NEQ: // !=
req := c.builder.CreateFCmp(llvm.FloatOEQ, r1, r2, "")
ieq := c.builder.CreateFCmp(llvm.FloatOEQ, i1, i2, "")
neq := c.builder.CreateAnd(req, ieq, "")
return c.builder.CreateNot(neq, ""), nil
case token.ADD, token.SUB:
var r, i llvm.Value
switch op {
case token.ADD:
r = c.builder.CreateFAdd(r1, r2, "")
i = c.builder.CreateFAdd(i1, i2, "")
case token.SUB:
r = c.builder.CreateFSub(r1, r2, "")
i = c.builder.CreateFSub(i1, i2, "")
default:
panic("unreachable")
}
cplx := llvm.Undef(c.ctx.StructType([]llvm.Type{r.Type(), i.Type()}, false))
cplx = c.builder.CreateInsertValue(cplx, r, 0, "")
cplx = c.builder.CreateInsertValue(cplx, i, 1, "")
return cplx, nil
case token.MUL:
// Complex multiplication follows the current implementation in
// the Go compiler, with the difference that complex64
// components are not first scaled up to float64 for increased
// precision.
// https://github.com/golang/go/blob/170b8b4b12be50eeccbcdadb8523fb4fc670ca72/src/cmd/compile/internal/gc/ssa.go#L2089-L2127
// The implementation is as follows:
// r := real(a) * real(b) - imag(a) * imag(b)
// i := real(a) * imag(b) + imag(a) * real(b)
// Note: this does NOT follow the C11 specification (annex G):
// http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1548.pdf#page=549
// See https://github.com/golang/go/issues/29846 for a related
// discussion.
r := c.builder.CreateFSub(c.builder.CreateFMul(r1, r2, ""), c.builder.CreateFMul(i1, i2, ""), "")
i := c.builder.CreateFAdd(c.builder.CreateFMul(r1, i2, ""), c.builder.CreateFMul(i1, r2, ""), "")
cplx := llvm.Undef(c.ctx.StructType([]llvm.Type{r.Type(), i.Type()}, false))
cplx = c.builder.CreateInsertValue(cplx, r, 0, "")
cplx = c.builder.CreateInsertValue(cplx, i, 1, "")
return cplx, nil
case token.QUO:
// Complex division.
// Do this in a library call because it's too difficult to do
// inline.
switch r1.Type().TypeKind() {
case llvm.FloatTypeKind:
return c.createRuntimeCall("complex64div", []llvm.Value{x, y}, ""), nil
case llvm.DoubleTypeKind:
return c.createRuntimeCall("complex128div", []llvm.Value{x, y}, ""), nil
default:
panic("unexpected complex type")
}
default:
panic("binop on complex: " + op.String())
}
} else if typ.Info()&types.IsBoolean != 0 {
// Operations on booleans
switch op {
case token.EQL: // ==
return c.builder.CreateICmp(llvm.IntEQ, x, y, ""), nil
case token.NEQ: // !=
return c.builder.CreateICmp(llvm.IntNE, x, y, ""), nil
default:
panic("binop on bool: " + op.String())
}
} else if typ.Kind() == types.UnsafePointer {
// Operations on pointers
switch op {
case token.EQL: // ==
return c.builder.CreateICmp(llvm.IntEQ, x, y, ""), nil
case token.NEQ: // !=
return c.builder.CreateICmp(llvm.IntNE, x, y, ""), nil
default:
panic("binop on pointer: " + op.String())
}
} else if typ.Info()&types.IsString != 0 {
// Operations on strings
switch op {
case token.ADD: // +
return c.createRuntimeCall("stringConcat", []llvm.Value{x, y}, ""), nil
case token.EQL: // ==
return c.createRuntimeCall("stringEqual", []llvm.Value{x, y}, ""), nil
case token.NEQ: // !=
result := c.createRuntimeCall("stringEqual", []llvm.Value{x, y}, "")
return c.builder.CreateNot(result, ""), nil
case token.LSS: // <
return c.createRuntimeCall("stringLess", []llvm.Value{x, y}, ""), nil
case token.LEQ: // <=
result := c.createRuntimeCall("stringLess", []llvm.Value{y, x}, "")
return c.builder.CreateNot(result, ""), nil
case token.GTR: // >
result := c.createRuntimeCall("stringLess", []llvm.Value{x, y}, "")
return c.builder.CreateNot(result, ""), nil
case token.GEQ: // >=
return c.createRuntimeCall("stringLess", []llvm.Value{y, x}, ""), nil
default:
panic("binop on string: " + op.String())
}
} else {
return llvm.Value{}, c.makeError(pos, "todo: unknown basic type in binop: "+typ.String())
}
case *types.Signature:
// Get raw scalars from the function value and compare those.
// Function values may be implemented in multiple ways, but they all
// have some way of getting a scalar value identifying the function.
// This is safe: function pointers are generally not comparable
// against each other, only against nil. So one of these has to be nil.
x = c.extractFuncScalar(x)
y = c.extractFuncScalar(y)
switch op {
case token.EQL: // ==
return c.builder.CreateICmp(llvm.IntEQ, x, y, ""), nil
case token.NEQ: // !=
return c.builder.CreateICmp(llvm.IntNE, x, y, ""), nil
default:
return llvm.Value{}, c.makeError(pos, "binop on signature: "+op.String())
}
case *types.Interface:
switch op {
case token.EQL, token.NEQ: // ==, !=
result := c.createRuntimeCall("interfaceEqual", []llvm.Value{x, y}, "")
if op == token.NEQ {
result = c.builder.CreateNot(result, "")
}
return result, nil
default:
return llvm.Value{}, c.makeError(pos, "binop on interface: "+op.String())
}
case *types.Chan, *types.Map, *types.Pointer:
// Maps are in general not comparable, but can be compared against nil
// (which is a nil pointer). This means they can be trivially compared
// by treating them as a pointer.
// Channels behave as pointers in that they are equal as long as they
// are created with the same call to make or if both are nil.
switch op {
case token.EQL: // ==
return c.builder.CreateICmp(llvm.IntEQ, x, y, ""), nil
case token.NEQ: // !=
return c.builder.CreateICmp(llvm.IntNE, x, y, ""), nil
default:
return llvm.Value{}, c.makeError(pos, "todo: binop on pointer: "+op.String())
}
case *types.Slice:
// Slices are in general not comparable, but can be compared against
// nil. Assume at least one of them is nil to make the code easier.
xPtr := c.builder.CreateExtractValue(x, 0, "")
yPtr := c.builder.CreateExtractValue(y, 0, "")
switch op {
case token.EQL: // ==
return c.builder.CreateICmp(llvm.IntEQ, xPtr, yPtr, ""), nil
case token.NEQ: // !=
return c.builder.CreateICmp(llvm.IntNE, xPtr, yPtr, ""), nil
default:
return llvm.Value{}, c.makeError(pos, "todo: binop on slice: "+op.String())
}
case *types.Array:
// Compare each array element and combine the result. From the spec:
// Array values are comparable if values of the array element type
// are comparable. Two array values are equal if their corresponding
// elements are equal.
result := llvm.ConstInt(c.ctx.Int1Type(), 1, true)
for i := 0; i < int(typ.Len()); i++ {
xField := c.builder.CreateExtractValue(x, i, "")
yField := c.builder.CreateExtractValue(y, i, "")
fieldEqual, err := c.parseBinOp(token.EQL, typ.Elem(), xField, yField, pos)
if err != nil {
return llvm.Value{}, err
}
result = c.builder.CreateAnd(result, fieldEqual, "")
}
switch op {
case token.EQL: // ==
return result, nil
case token.NEQ: // !=
return c.builder.CreateNot(result, ""), nil
default:
return llvm.Value{}, c.makeError(pos, "unknown: binop on struct: "+op.String())
}
case *types.Struct:
// Compare each struct field and combine the result. From the spec:
// Struct values are comparable if all their fields are comparable.
// Two struct values are equal if their corresponding non-blank
// fields are equal.
result := llvm.ConstInt(c.ctx.Int1Type(), 1, true)
for i := 0; i < typ.NumFields(); i++ {
if typ.Field(i).Name() == "_" {
// skip blank fields
continue
}
fieldType := typ.Field(i).Type()
xField := c.builder.CreateExtractValue(x, i, "")
yField := c.builder.CreateExtractValue(y, i, "")
fieldEqual, err := c.parseBinOp(token.EQL, fieldType, xField, yField, pos)
if err != nil {
return llvm.Value{}, err
}
result = c.builder.CreateAnd(result, fieldEqual, "")
}
switch op {
case token.EQL: // ==
return result, nil
case token.NEQ: // !=
return c.builder.CreateNot(result, ""), nil
default:
return llvm.Value{}, c.makeError(pos, "unknown: binop on struct: "+op.String())
}
default:
return llvm.Value{}, c.makeError(pos, "todo: binop type: "+typ.String())
}
}
func (c *Compiler) parseConst(prefix string, expr *ssa.Const) llvm.Value {
switch typ := expr.Type().Underlying().(type) {
case *types.Basic:
llvmType := c.getLLVMType(typ)
if typ.Info()&types.IsBoolean != 0 {
b := constant.BoolVal(expr.Value)
n := uint64(0)
if b {
n = 1
}
return llvm.ConstInt(llvmType, n, false)
} else if typ.Info()&types.IsString != 0 {
str := constant.StringVal(expr.Value)
strLen := llvm.ConstInt(c.uintptrType, uint64(len(str)), false)
objname := prefix + "$string"
global := llvm.AddGlobal(c.mod, llvm.ArrayType(c.ctx.Int8Type(), len(str)), objname)
global.SetInitializer(c.ctx.ConstString(str, false))
global.SetLinkage(llvm.InternalLinkage)
global.SetGlobalConstant(true)
global.SetUnnamedAddr(true)
zero := llvm.ConstInt(c.ctx.Int32Type(), 0, false)
strPtr := c.builder.CreateInBoundsGEP(global, []llvm.Value{zero, zero}, "")
strObj := llvm.ConstNamedStruct(c.mod.GetTypeByName("runtime._string"), []llvm.Value{strPtr, strLen})
return strObj
} else if typ.Kind() == types.UnsafePointer {
if !expr.IsNil() {
value, _ := constant.Uint64Val(expr.Value)
return llvm.ConstIntToPtr(llvm.ConstInt(c.uintptrType, value, false), c.i8ptrType)
}
return llvm.ConstNull(c.i8ptrType)
} else if typ.Info()&types.IsUnsigned != 0 {
n, _ := constant.Uint64Val(expr.Value)
return llvm.ConstInt(llvmType, n, false)
} else if typ.Info()&types.IsInteger != 0 { // signed
n, _ := constant.Int64Val(expr.Value)
return llvm.ConstInt(llvmType, uint64(n), true)
} else if typ.Info()&types.IsFloat != 0 {
n, _ := constant.Float64Val(expr.Value)
return llvm.ConstFloat(llvmType, n)
} else if typ.Kind() == types.Complex64 {
r := c.parseConst(prefix, ssa.NewConst(constant.Real(expr.Value), types.Typ[types.Float32]))
i := c.parseConst(prefix, ssa.NewConst(constant.Imag(expr.Value), types.Typ[types.Float32]))
cplx := llvm.Undef(c.ctx.StructType([]llvm.Type{c.ctx.FloatType(), c.ctx.FloatType()}, false))
cplx = c.builder.CreateInsertValue(cplx, r, 0, "")
cplx = c.builder.CreateInsertValue(cplx, i, 1, "")
return cplx
} else if typ.Kind() == types.Complex128 {
r := c.parseConst(prefix, ssa.NewConst(constant.Real(expr.Value), types.Typ[types.Float64]))
i := c.parseConst(prefix, ssa.NewConst(constant.Imag(expr.Value), types.Typ[types.Float64]))
cplx := llvm.Undef(c.ctx.StructType([]llvm.Type{c.ctx.DoubleType(), c.ctx.DoubleType()}, false))
cplx = c.builder.CreateInsertValue(cplx, r, 0, "")
cplx = c.builder.CreateInsertValue(cplx, i, 1, "")
return cplx
} else {
panic("unknown constant of basic type: " + expr.String())
}
case *types.Chan:
if expr.Value != nil {
panic("expected nil chan constant")
}
return c.getZeroValue(c.getLLVMType(expr.Type()))
case *types.Signature:
if expr.Value != nil {
panic("expected nil signature constant")
}
return c.getZeroValue(c.getLLVMType(expr.Type()))
case *types.Interface:
if expr.Value != nil {
panic("expected nil interface constant")
}
// Create a generic nil interface with no dynamic type (typecode=0).
fields := []llvm.Value{
llvm.ConstInt(c.uintptrType, 0, false),
llvm.ConstPointerNull(c.i8ptrType),
}
return llvm.ConstNamedStruct(c.mod.GetTypeByName("runtime._interface"), fields)
case *types.Pointer:
if expr.Value != nil {
panic("expected nil pointer constant")
}
return llvm.ConstPointerNull(c.getLLVMType(typ))
case *types.Slice:
if expr.Value != nil {
panic("expected nil slice constant")
}
elemType := c.getLLVMType(typ.Elem())
llvmPtr := llvm.ConstPointerNull(llvm.PointerType(elemType, 0))
llvmLen := llvm.ConstInt(c.uintptrType, 0, false)
slice := c.ctx.ConstStruct([]llvm.Value{
llvmPtr, // backing array
llvmLen, // len
llvmLen, // cap
}, false)
return slice
case *types.Map:
if !expr.IsNil() {
// I believe this is not allowed by the Go spec.
panic("non-nil map constant")
}
llvmType := c.getLLVMType(typ)
return c.getZeroValue(llvmType)
default:
panic("unknown constant: " + expr.String())
}
}
func (c *Compiler) parseConvert(typeFrom, typeTo types.Type, value llvm.Value, pos token.Pos) (llvm.Value, error) {
llvmTypeFrom := value.Type()
llvmTypeTo := c.getLLVMType(typeTo)
// Conversion between unsafe.Pointer and uintptr.
isPtrFrom := isPointer(typeFrom.Underlying())
isPtrTo := isPointer(typeTo.Underlying())
if isPtrFrom && !isPtrTo {
return c.builder.CreatePtrToInt(value, llvmTypeTo, ""), nil
} else if !isPtrFrom && isPtrTo {
if !value.IsABinaryOperator().IsNil() && value.InstructionOpcode() == llvm.Add {
// This is probably a pattern like the following:
// unsafe.Pointer(uintptr(ptr) + index)
// Used in functions like memmove etc. for lack of pointer
// arithmetic. Convert it to real pointer arithmatic here.
ptr := value.Operand(0)
index := value.Operand(1)
if !index.IsAPtrToIntInst().IsNil() {
// Swap if necessary, if ptr and index are reversed.
ptr, index = index, ptr
}
if !ptr.IsAPtrToIntInst().IsNil() {
origptr := ptr.Operand(0)
if origptr.Type() == c.i8ptrType {
// This pointer can be calculated from the original
// ptrtoint instruction with a GEP. The leftover inttoptr
// instruction is trivial to optimize away.
// Making it an in bounds GEP even though it's easy to
// create a GEP that is not in bounds. However, we're
// talking about unsafe code here so the programmer has to
// be careful anyway.
return c.builder.CreateInBoundsGEP(origptr, []llvm.Value{index}, ""), nil
}
}
}
return c.builder.CreateIntToPtr(value, llvmTypeTo, ""), nil
}
// Conversion between pointers and unsafe.Pointer.
if isPtrFrom && isPtrTo {
return c.builder.CreateBitCast(value, llvmTypeTo, ""), nil
}
switch typeTo := typeTo.Underlying().(type) {
case *types.Basic:
sizeFrom := c.targetData.TypeAllocSize(llvmTypeFrom)
if typeTo.Info()&types.IsString != 0 {
switch typeFrom := typeFrom.Underlying().(type) {
case *types.Basic:
// Assume a Unicode code point, as that is the only possible
// value here.
// Cast to an i32 value as expected by
// runtime.stringFromUnicode.
if sizeFrom > 4 {
value = c.builder.CreateTrunc(value, c.ctx.Int32Type(), "")
} else if sizeFrom < 4 && typeTo.Info()&types.IsUnsigned != 0 {
value = c.builder.CreateZExt(value, c.ctx.Int32Type(), "")
} else if sizeFrom < 4 {
value = c.builder.CreateSExt(value, c.ctx.Int32Type(), "")
}
return c.createRuntimeCall("stringFromUnicode", []llvm.Value{value}, ""), nil
case *types.Slice:
switch typeFrom.Elem().(*types.Basic).Kind() {
case types.Byte:
return c.createRuntimeCall("stringFromBytes", []llvm.Value{value}, ""), nil
default:
return llvm.Value{}, c.makeError(pos, "todo: convert to string: "+typeFrom.String())
}
default:
return llvm.Value{}, c.makeError(pos, "todo: convert to string: "+typeFrom.String())
}
}
typeFrom := typeFrom.Underlying().(*types.Basic)
sizeTo := c.targetData.TypeAllocSize(llvmTypeTo)
if typeFrom.Info()&types.IsInteger != 0 && typeTo.Info()&types.IsInteger != 0 {
// Conversion between two integers.
if sizeFrom > sizeTo {
return c.builder.CreateTrunc(value, llvmTypeTo, ""), nil
} else if typeFrom.Info()&types.IsUnsigned != 0 { // if unsigned
return c.builder.CreateZExt(value, llvmTypeTo, ""), nil
} else { // if signed
return c.builder.CreateSExt(value, llvmTypeTo, ""), nil
}
}
if typeFrom.Info()&types.IsFloat != 0 && typeTo.Info()&types.IsFloat != 0 {
// Conversion between two floats.
if sizeFrom > sizeTo {
return c.builder.CreateFPTrunc(value, llvmTypeTo, ""), nil
} else if sizeFrom < sizeTo {
return c.builder.CreateFPExt(value, llvmTypeTo, ""), nil
} else {
return value, nil
}
}
if typeFrom.Info()&types.IsFloat != 0 && typeTo.Info()&types.IsInteger != 0 {
// Conversion from float to int.
if typeTo.Info()&types.IsUnsigned != 0 { // if unsigned
return c.builder.CreateFPToUI(value, llvmTypeTo, ""), nil
} else { // if signed
return c.builder.CreateFPToSI(value, llvmTypeTo, ""), nil
}
}
if typeFrom.Info()&types.IsInteger != 0 && typeTo.Info()&types.IsFloat != 0 {
// Conversion from int to float.
if typeFrom.Info()&types.IsUnsigned != 0 { // if unsigned
return c.builder.CreateUIToFP(value, llvmTypeTo, ""), nil
} else { // if signed
return c.builder.CreateSIToFP(value, llvmTypeTo, ""), nil
}
}
if typeFrom.Kind() == types.Complex128 && typeTo.Kind() == types.Complex64 {
// Conversion from complex128 to complex64.
r := c.builder.CreateExtractValue(value, 0, "real.f64")
i := c.builder.CreateExtractValue(value, 1, "imag.f64")
r = c.builder.CreateFPTrunc(r, c.ctx.FloatType(), "real.f32")
i = c.builder.CreateFPTrunc(i, c.ctx.FloatType(), "imag.f32")
cplx := llvm.Undef(c.ctx.StructType([]llvm.Type{c.ctx.FloatType(), c.ctx.FloatType()}, false))
cplx = c.builder.CreateInsertValue(cplx, r, 0, "")
cplx = c.builder.CreateInsertValue(cplx, i, 1, "")
return cplx, nil
}
if typeFrom.Kind() == types.Complex64 && typeTo.Kind() == types.Complex128 {
// Conversion from complex64 to complex128.
r := c.builder.CreateExtractValue(value, 0, "real.f32")
i := c.builder.CreateExtractValue(value, 1, "imag.f32")
r = c.builder.CreateFPExt(r, c.ctx.DoubleType(), "real.f64")
i = c.builder.CreateFPExt(i, c.ctx.DoubleType(), "imag.f64")
cplx := llvm.Undef(c.ctx.StructType([]llvm.Type{c.ctx.DoubleType(), c.ctx.DoubleType()}, false))
cplx = c.builder.CreateInsertValue(cplx, r, 0, "")
cplx = c.builder.CreateInsertValue(cplx, i, 1, "")
return cplx, nil
}
return llvm.Value{}, c.makeError(pos, "todo: convert: basic non-integer type: "+typeFrom.String()+" -> "+typeTo.String())
case *types.Slice:
if basic, ok := typeFrom.(*types.Basic); !ok || basic.Info()&types.IsString == 0 {
panic("can only convert from a string to a slice")
}
elemType := typeTo.Elem().Underlying().(*types.Basic) // must be byte or rune
switch elemType.Kind() {
case types.Byte:
return c.createRuntimeCall("stringToBytes", []llvm.Value{value}, ""), nil
default:
return llvm.Value{}, c.makeError(pos, "todo: convert from string: "+elemType.String())
}
default:
return llvm.Value{}, c.makeError(pos, "todo: convert "+typeTo.String()+" <- "+typeFrom.String())
}
}
func (c *Compiler) parseUnOp(frame *Frame, unop *ssa.UnOp) (llvm.Value, error) {
x := c.getValue(frame, unop.X)
switch unop.Op {
case token.NOT: // !x
return c.builder.CreateNot(x, ""), nil
case token.SUB: // -x
if typ, ok := unop.X.Type().Underlying().(*types.Basic); ok {
if typ.Info()&types.IsInteger != 0 {
return c.builder.CreateSub(llvm.ConstInt(x.Type(), 0, false), x, ""), nil
} else if typ.Info()&types.IsFloat != 0 {
return c.builder.CreateFSub(llvm.ConstFloat(x.Type(), 0.0), x, ""), nil
} else {
return llvm.Value{}, c.makeError(unop.Pos(), "todo: unknown basic type for negate: "+typ.String())
}
} else {
return llvm.Value{}, c.makeError(unop.Pos(), "todo: unknown type for negate: "+unop.X.Type().Underlying().String())
}
case token.MUL: // *x, dereference pointer
unop.X.Type().Underlying().(*types.Pointer).Elem()
if c.targetData.TypeAllocSize(x.Type().ElementType()) == 0 {
// zero-length data
return c.getZeroValue(x.Type().ElementType()), nil
} else if strings.HasSuffix(unop.X.String(), "$funcaddr") {
// CGo function pointer. The cgo part has rewritten CGo function
// pointers as stub global variables of the form:
// var C.add unsafe.Pointer
// Instead of a load from the global, create a bitcast of the
// function pointer itself.
global := c.ir.GetGlobal(unop.X.(*ssa.Global))
name := global.LinkName()[:len(global.LinkName())-len("$funcaddr")]
fn := c.mod.NamedFunction(name)
if fn.IsNil() {
return llvm.Value{}, c.makeError(unop.Pos(), "cgo function not found: "+name)
}
return c.builder.CreateBitCast(fn, c.i8ptrType, ""), nil
} else {
c.emitNilCheck(frame, x, "deref")
load := c.builder.CreateLoad(x, "")
return load, nil
}
case token.XOR: // ^x, toggle all bits in integer
return c.builder.CreateXor(x, llvm.ConstInt(x.Type(), ^uint64(0), false), ""), nil
case token.ARROW: // <-x, receive from channel
return c.emitChanRecv(frame, unop), nil
default:
return llvm.Value{}, c.makeError(unop.Pos(), "todo: unknown unop")
}
}
// IR returns the whole IR as a human-readable string.
func (c *Compiler) IR() string {
return c.mod.String()
}
func (c *Compiler) Verify() error {
return llvm.VerifyModule(c.mod, llvm.PrintMessageAction)
}
func (c *Compiler) ApplyFunctionSections() {
// Put every function in a separate section. This makes it possible for the
// linker to remove dead code (-ffunction-sections).
llvmFn := c.mod.FirstFunction()
for !llvmFn.IsNil() {
if !llvmFn.IsDeclaration() {
name := llvmFn.Name()
llvmFn.SetSection(".text." + name)
}
llvmFn = llvm.NextFunction(llvmFn)
}
}
// Turn all global constants into global variables. This works around a
// limitation on Harvard architectures (e.g. AVR), where constant and
// non-constant pointers point to a different address space.
func (c *Compiler) NonConstGlobals() {
global := c.mod.FirstGlobal()
for !global.IsNil() {
global.SetGlobalConstant(false)
global = llvm.NextGlobal(global)
}
}
// When -wasm-abi flag set to "js" (default),
// replace i64 in an external function with a stack-allocated i64*, to work
// around the lack of 64-bit integers in JavaScript (commonly used together with
// WebAssembly). Once that's resolved, this pass may be avoided.
// See also the -wasm-abi= flag
// https://github.com/WebAssembly/design/issues/1172
func (c *Compiler) ExternalInt64AsPtr() error {
int64Type := c.ctx.Int64Type()
int64PtrType := llvm.PointerType(int64Type, 0)
for fn := c.mod.FirstFunction(); !fn.IsNil(); fn = llvm.NextFunction(fn) {
if fn.Linkage() != llvm.ExternalLinkage {
// Only change externally visible functions (exports and imports).
continue
}
if strings.HasPrefix(fn.Name(), "llvm.") || strings.HasPrefix(fn.Name(), "runtime.") {
// Do not try to modify the signature of internal LLVM functions and
// assume that runtime functions are only temporarily exported for
// coroutine lowering.
continue
}
hasInt64 := false
paramTypes := []llvm.Type{}
// Check return type for 64-bit integer.
fnType := fn.Type().ElementType()
returnType := fnType.ReturnType()
if returnType == int64Type {
hasInt64 = true
paramTypes = append(paramTypes, int64PtrType)
returnType = c.ctx.VoidType()
}
// Check param types for 64-bit integers.
for param := fn.FirstParam(); !param.IsNil(); param = llvm.NextParam(param) {
if param.Type() == int64Type {
hasInt64 = true
paramTypes = append(paramTypes, int64PtrType)
} else {
paramTypes = append(paramTypes, param.Type())
}
}
if !hasInt64 {
// No i64 in the paramter list.
continue
}
// Add $i64wrapper to the real function name as it is only used
// internally.
// Add a new function with the correct signature that is exported.
name := fn.Name()
fn.SetName(name + "$i64wrap")
externalFnType := llvm.FunctionType(returnType, paramTypes, fnType.IsFunctionVarArg())
externalFn := llvm.AddFunction(c.mod, name, externalFnType)
if fn.IsDeclaration() {
// Just a declaration: the definition doesn't exist on the Go side
// so it cannot be called from external code.
// Update all users to call the external function.
// The old $i64wrapper function could be removed, but it may as well
// be left in place.
for use := fn.FirstUse(); !use.IsNil(); use = use.NextUse() {
call := use.User()
c.builder.SetInsertPointBefore(call)
callParams := []llvm.Value{}
var retvalAlloca llvm.Value
if fnType.ReturnType() == int64Type {
retvalAlloca = c.builder.CreateAlloca(int64Type, "i64asptr")
callParams = append(callParams, retvalAlloca)
}
for i := 0; i < call.OperandsCount()-1; i++ {
operand := call.Operand(i)
if operand.Type() == int64Type {
// Pass a stack-allocated pointer instead of the value
// itself.
alloca := c.builder.CreateAlloca(int64Type, "i64asptr")
c.builder.CreateStore(operand, alloca)
callParams = append(callParams, alloca)
} else {
// Unchanged parameter.
callParams = append(callParams, operand)
}
}
if fnType.ReturnType() == int64Type {
// Pass a stack-allocated pointer as the first parameter
// where the return value should be stored, instead of using
// the regular return value.
c.builder.CreateCall(externalFn, callParams, call.Name())
returnValue := c.builder.CreateLoad(retvalAlloca, "retval")
call.ReplaceAllUsesWith(returnValue)
call.EraseFromParentAsInstruction()
} else {
newCall := c.builder.CreateCall(externalFn, callParams, call.Name())
call.ReplaceAllUsesWith(newCall)
call.EraseFromParentAsInstruction()
}
}
} else {
// The function has a definition in Go. This means that it may still
// be called both Go and from external code.
// Keep existing calls with the existing convention in place (for
// better performance), but export a new wrapper function with the
// correct calling convention.
fn.SetLinkage(llvm.InternalLinkage)
fn.SetUnnamedAddr(true)
entryBlock := llvm.AddBasicBlock(externalFn, "entry")
c.builder.SetInsertPointAtEnd(entryBlock)
var callParams []llvm.Value
if fnType.ReturnType() == int64Type {
return errors.New("not yet implemented: exported function returns i64 with -wasm-abi=js; " +
"see https://tinygo.org/compiler-internals/calling-convention/")
}
for i, origParam := range fn.Params() {
paramValue := externalFn.Param(i)
if origParam.Type() == int64Type {
paramValue = c.builder.CreateLoad(paramValue, "i64")
}
callParams = append(callParams, paramValue)
}
retval := c.builder.CreateCall(fn, callParams, "")
if retval.Type().TypeKind() == llvm.VoidTypeKind {
c.builder.CreateRetVoid()
} else {
c.builder.CreateRet(retval)
}
}
}
return nil
}
// Emit object file (.o).
func (c *Compiler) EmitObject(path string) error {
llvmBuf, err := c.machine.EmitToMemoryBuffer(c.mod, llvm.ObjectFile)
if err != nil {
return err
}
return c.writeFile(llvmBuf.Bytes(), path)
}
// Emit LLVM bitcode file (.bc).
func (c *Compiler) EmitBitcode(path string) error {
data := llvm.WriteBitcodeToMemoryBuffer(c.mod).Bytes()
return c.writeFile(data, path)
}
// Emit LLVM IR source file (.ll).
func (c *Compiler) EmitText(path string) error {
data := []byte(c.mod.String())
return c.writeFile(data, path)
}
// Write the data to the file specified by path.
func (c *Compiler) writeFile(data []byte, path string) error {
// Write output to file
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return err
}
_, err = f.Write(data)
if err != nil {
return err
}
return f.Close()
}
| 1 | 7,222 | Both cases allowed by the Go spec are now supported, so it's a bug in the compiler if we get here. You can replace the `todo:` error with a panic. (Note: getting here would be a bug because when we get to SSA level the code has long been type checked and has already been verified as being valid Go). | tinygo-org-tinygo | go |
@@ -551,6 +551,14 @@ class TabbedBrowser(tabwidget.TabWidget):
return
widget.setFocus()
+ def load_prepared_history(self, idx):
+ tab = self.widget(idx)
+ if len(tab.history_prepared) > 0:
+ tab.history.load_items(tab.history_prepared)
+ tab.history_prepared = []
+ #end if
+ #end def load_prepared_history
+
@pyqtSlot(int)
def on_current_changed(self, idx):
"""Set last-focused-tab and leave hinting mode when focus changed.""" | 1 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2016 Florian Bruhin (The Compiler) <[email protected]>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""The main tabbed browser widget."""
import functools
import collections
from PyQt5.QtWidgets import QSizePolicy
from PyQt5.QtCore import pyqtSignal, pyqtSlot, QTimer, QUrl
from PyQt5.QtGui import QIcon
from qutebrowser.config import config
from qutebrowser.keyinput import modeman
from qutebrowser.mainwindow import tabwidget
from qutebrowser.browser import signalfilter, browsertab
from qutebrowser.utils import (log, usertypes, utils, qtutils, objreg,
urlutils, message)
UndoEntry = collections.namedtuple('UndoEntry', ['url', 'history', 'index'])
class TabDeletedError(Exception):
"""Exception raised when _tab_index is called for a deleted tab."""
class TabbedBrowser(tabwidget.TabWidget):
"""A TabWidget with QWebViews inside.
Provides methods to manage tabs, convenience methods to interact with the
current tab (cur_*) and filters signals to re-emit them when they occurred
in the currently visible tab.
For all tab-specific signals (cur_*) emitted by a tab, this happens:
- the signal gets filtered with _filter_signals and self.cur_* gets
emitted if the signal occurred in the current tab.
Attributes:
search_text/search_options: Search parameters which are shared between
all tabs.
_win_id: The window ID this tabbedbrowser is associated with.
_filter: A SignalFilter instance.
_now_focused: The tab which is focused now.
_tab_insert_idx_left: Where to insert a new tab with
tabbar -> new-tab-position set to 'left'.
_tab_insert_idx_right: Same as above, for 'right'.
_undo_stack: List of UndoEntry namedtuples of closed tabs.
shutting_down: Whether we're currently shutting down.
_local_marks: Jump markers local to each page
_global_marks: Jump markers used across all pages
default_window_icon: The qutebrowser window icon
Signals:
cur_progress: Progress of the current tab changed (load_progress).
cur_load_started: Current tab started loading (load_started)
cur_load_finished: Current tab finished loading (load_finished)
cur_url_changed: Current URL changed.
cur_link_hovered: Link hovered in current tab (link_hovered)
cur_scroll_perc_changed: Scroll percentage of current tab changed.
arg 1: x-position in %.
arg 2: y-position in %.
cur_load_status_changed: Loading status of current tab changed.
close_window: The last tab was closed, close this window.
resized: Emitted when the browser window has resized, so the completion
widget can adjust its size to it.
arg: The new size.
current_tab_changed: The current tab changed to the emitted tab.
new_tab: Emits the new WebView and its index when a new tab is opened.
"""
cur_progress = pyqtSignal(int)
cur_load_started = pyqtSignal()
cur_load_finished = pyqtSignal(bool)
cur_url_changed = pyqtSignal(QUrl)
cur_link_hovered = pyqtSignal(str)
cur_scroll_perc_changed = pyqtSignal(int, int)
cur_load_status_changed = pyqtSignal(str)
close_window = pyqtSignal()
resized = pyqtSignal('QRect')
current_tab_changed = pyqtSignal(browsertab.AbstractTab)
new_tab = pyqtSignal(browsertab.AbstractTab, int)
def __init__(self, win_id, parent=None):
super().__init__(win_id, parent)
self._win_id = win_id
self._tab_insert_idx_left = 0
self._tab_insert_idx_right = -1
self.shutting_down = False
self.tabCloseRequested.connect(self.on_tab_close_requested)
self.currentChanged.connect(self.on_current_changed)
self.cur_load_started.connect(self.on_cur_load_started)
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self._undo_stack = []
self._filter = signalfilter.SignalFilter(win_id, self)
self._now_focused = None
self.search_text = None
self.search_options = {}
self._local_marks = {}
self._global_marks = {}
self.default_window_icon = self.window().windowIcon()
objreg.get('config').changed.connect(self.update_favicons)
objreg.get('config').changed.connect(self.update_window_title)
objreg.get('config').changed.connect(self.update_tab_titles)
def __repr__(self):
return utils.get_repr(self, count=self.count())
def _tab_index(self, tab):
"""Get the index of a given tab.
Raises TabDeletedError if the tab doesn't exist anymore.
"""
try:
idx = self.indexOf(tab)
except RuntimeError as e:
log.webview.debug("Got invalid tab ({})!".format(e))
raise TabDeletedError(e)
if idx == -1:
log.webview.debug("Got invalid tab (index is -1)!")
raise TabDeletedError("index is -1!")
return idx
def widgets(self):
"""Get a list of open tab widgets.
We don't implement this as generator so we can delete tabs while
iterating over the list.
"""
w = []
for i in range(self.count()):
w.append(self.widget(i))
return w
@config.change_filter('ui', 'window-title-format')
def update_window_title(self):
"""Change the window title to match the current tab."""
idx = self.currentIndex()
if idx == -1:
# (e.g. last tab removed)
log.webview.debug("Not updating window title because index is -1")
return
fields = self.get_tab_fields(idx)
fields['id'] = self._win_id
fmt = config.get('ui', 'window-title-format')
self.window().setWindowTitle(fmt.format(**fields))
def _connect_tab_signals(self, tab):
"""Set up the needed signals for tab."""
# filtered signals
tab.link_hovered.connect(
self._filter.create(self.cur_link_hovered, tab))
tab.load_progress.connect(
self._filter.create(self.cur_progress, tab))
tab.load_finished.connect(
self._filter.create(self.cur_load_finished, tab))
tab.load_started.connect(
self._filter.create(self.cur_load_started, tab))
tab.scroller.perc_changed.connect(
self._filter.create(self.cur_scroll_perc_changed, tab))
tab.scroller.perc_changed.connect(self.on_scroll_pos_changed)
tab.url_changed.connect(
self._filter.create(self.cur_url_changed, tab))
tab.load_status_changed.connect(
self._filter.create(self.cur_load_status_changed, tab))
tab.url_changed.connect(
functools.partial(self.on_url_changed, tab))
# misc
tab.title_changed.connect(
functools.partial(self.on_title_changed, tab))
tab.icon_changed.connect(
functools.partial(self.on_icon_changed, tab))
tab.load_progress.connect(
functools.partial(self.on_load_progress, tab))
tab.load_finished.connect(
functools.partial(self.on_load_finished, tab))
tab.load_started.connect(
functools.partial(self.on_load_started, tab))
tab.window_close_requested.connect(
functools.partial(self.on_window_close_requested, tab))
tab.new_tab_requested.connect(self.tabopen)
tab.add_history_item.connect(objreg.get('web-history').add_from_tab)
def current_url(self):
"""Get the URL of the current tab.
Intended to be used from command handlers.
Return:
The current URL as QUrl.
"""
idx = self.currentIndex()
return super().tab_url(idx)
def shutdown(self):
"""Try to shut down all tabs cleanly."""
self.shutting_down = True
for tab in self.widgets():
self._remove_tab(tab)
def close_tab(self, tab, *, add_undo=True):
"""Close a tab.
Args:
tab: The QWebView to be closed.
add_undo: Whether the tab close can be undone.
"""
last_close = config.get('tabs', 'last-close')
count = self.count()
if last_close == 'ignore' and count == 1:
return
self._remove_tab(tab, add_undo=add_undo)
if count == 1: # We just closed the last tab above.
if last_close == 'close':
self.close_window.emit()
elif last_close == 'blank':
self.openurl(QUrl('about:blank'), newtab=True)
elif last_close == 'startpage':
url = QUrl(config.get('general', 'startpage')[0])
self.openurl(url, newtab=True)
elif last_close == 'default-page':
url = config.get('general', 'default-page')
self.openurl(url, newtab=True)
def _remove_tab(self, tab, *, add_undo=True):
"""Remove a tab from the tab list and delete it properly.
Args:
tab: The QWebView to be closed.
add_undo: Whether the tab close can be undone.
"""
idx = self.indexOf(tab)
if idx == -1:
raise TabDeletedError("tab {} is not contained in "
"TabbedWidget!".format(tab))
if tab is self._now_focused:
self._now_focused = None
if tab is objreg.get('last-focused-tab', None, scope='window',
window=self._win_id):
objreg.delete('last-focused-tab', scope='window',
window=self._win_id)
if tab.url().isValid():
history_data = tab.history.serialize()
if add_undo:
entry = UndoEntry(tab.url(), history_data, idx)
self._undo_stack.append(entry)
elif tab.url().isEmpty():
# There are some good reasons why a URL could be empty
# (target="_blank" with a download, see [1]), so we silently ignore
# this.
# [1] https://github.com/The-Compiler/qutebrowser/issues/163
pass
else:
# We display a warnings for URLs which are not empty but invalid -
# but we don't return here because we want the tab to close either
# way.
urlutils.invalid_url_error(tab.url(), "saving tab")
tab.shutdown()
self.removeTab(idx)
tab.deleteLater()
def undo(self):
"""Undo removing of a tab."""
# Remove unused tab which may be created after the last tab is closed
last_close = config.get('tabs', 'last-close')
use_current_tab = False
if last_close in ['blank', 'startpage', 'default-page']:
only_one_tab_open = self.count() == 1
no_history = len(self.widget(0).history) == 1
urls = {
'blank': QUrl('about:blank'),
'startpage': QUrl(config.get('general', 'startpage')[0]),
'default-page': config.get('general', 'default-page'),
}
first_tab_url = self.widget(0).url()
last_close_urlstr = urls[last_close].toString().rstrip('/')
first_tab_urlstr = first_tab_url.toString().rstrip('/')
last_close_url_used = first_tab_urlstr == last_close_urlstr
use_current_tab = (only_one_tab_open and no_history and
last_close_url_used)
url, history_data, idx = self._undo_stack.pop()
if use_current_tab:
self.openurl(url, newtab=False)
newtab = self.widget(0)
else:
newtab = self.tabopen(url, background=False, idx=idx)
newtab.history.deserialize(history_data)
@pyqtSlot('QUrl', bool)
def openurl(self, url, newtab):
"""Open a URL, used as a slot.
Args:
url: The URL to open as QUrl.
newtab: True to open URL in a new tab, False otherwise.
"""
qtutils.ensure_valid(url)
if newtab or self.currentWidget() is None:
self.tabopen(url, background=False)
else:
self.currentWidget().openurl(url)
@pyqtSlot(int)
def on_tab_close_requested(self, idx):
"""Close a tab via an index."""
tab = self.widget(idx)
if tab is None:
log.webview.debug("Got invalid tab {} for index {}!".format(
tab, idx))
return
self.close_tab(tab)
@pyqtSlot(browsertab.AbstractTab)
def on_window_close_requested(self, widget):
"""Close a tab with a widget given."""
try:
self.close_tab(widget)
except TabDeletedError:
log.webview.debug("Requested to close {!r} which does not "
"exist!".format(widget))
@pyqtSlot('QUrl')
@pyqtSlot('QUrl', bool)
def tabopen(self, url=None, background=None, explicit=False, idx=None):
"""Open a new tab with a given URL.
Inner logic for open-tab and open-tab-bg.
Also connect all the signals we need to _filter_signals.
Args:
url: The URL to open as QUrl or None for an empty tab.
background: Whether to open the tab in the background.
if None, the background-tabs setting decides.
explicit: Whether the tab was opened explicitly.
If this is set, the new position might be different. With
the default settings we handle it like Chromium does:
- Tabs from clicked links etc. are to the right of
the current.
- Explicitly opened tabs are at the very right.
idx: The index where the new tab should be opened.
Return:
The opened WebView instance.
"""
if url is not None:
qtutils.ensure_valid(url)
log.webview.debug("Creating new tab with URL {}".format(url))
if config.get('tabs', 'tabs-are-windows') and self.count() > 0:
from qutebrowser.mainwindow import mainwindow
window = mainwindow.MainWindow()
window.show()
tabbed_browser = objreg.get('tabbed-browser', scope='window',
window=window.win_id)
return tabbed_browser.tabopen(url, background, explicit)
tab = browsertab.create(win_id=self._win_id, parent=self)
self._connect_tab_signals(tab)
if idx is None:
idx = self._get_new_tab_idx(explicit)
self.insertTab(idx, tab, "")
if url is not None:
tab.openurl(url)
if background is None:
background = config.get('tabs', 'background-tabs')
if background:
self.tab_index_changed.emit(self.currentIndex(), self.count())
else:
self.setCurrentWidget(tab)
tab.show()
self.new_tab.emit(tab, idx)
return tab
def _get_new_tab_idx(self, explicit):
"""Get the index of a tab to insert.
Args:
explicit: Whether the tab was opened explicitly.
Return:
The index of the new tab.
"""
if explicit:
pos = config.get('tabs', 'new-tab-position-explicit')
else:
pos = config.get('tabs', 'new-tab-position')
if pos == 'left':
idx = self._tab_insert_idx_left
# On first sight, we'd think we have to decrement
# self._tab_insert_idx_left here, as we want the next tab to be
# *before* the one we just opened. However, since we opened a tab
# *to the left* of the currently focused tab, indices will shift by
# 1 automatically.
elif pos == 'right':
idx = self._tab_insert_idx_right
self._tab_insert_idx_right += 1
elif pos == 'first':
idx = 0
elif pos == 'last':
idx = -1
else:
raise ValueError("Invalid new-tab-position '{}'.".format(pos))
log.webview.debug("new-tab-position {} -> opening new tab at {}, "
"next left: {} / right: {}".format(
pos, idx, self._tab_insert_idx_left,
self._tab_insert_idx_right))
return idx
@config.change_filter('tabs', 'show-favicons')
def update_favicons(self):
"""Update favicons when config was changed."""
show = config.get('tabs', 'show-favicons')
tabs_are_wins = config.get('tabs', 'tabs-are-windows')
for i, tab in enumerate(self.widgets()):
if show:
self.setTabIcon(i, tab.icon())
if tabs_are_wins:
self.window().setWindowIcon(tab.icon())
else:
self.setTabIcon(i, QIcon())
if tabs_are_wins:
self.window().setWindowIcon(self.default_window_icon)
@pyqtSlot()
def on_load_started(self, tab):
"""Clear icon and update title when a tab started loading.
Args:
tab: The tab where the signal belongs to.
"""
try:
idx = self._tab_index(tab)
except TabDeletedError:
# We can get signals for tabs we already deleted...
return
self.update_tab_title(idx)
if tab.data.keep_icon:
tab.data.keep_icon = False
else:
self.setTabIcon(idx, QIcon())
if (config.get('tabs', 'tabs-are-windows') and
config.get('tabs', 'show-favicons')):
self.window().setWindowIcon(self.default_window_icon)
if idx == self.currentIndex():
self.update_window_title()
@pyqtSlot()
def on_cur_load_started(self):
"""Leave insert/hint mode when loading started."""
modeman.maybe_leave(self._win_id, usertypes.KeyMode.insert,
'load started')
modeman.maybe_leave(self._win_id, usertypes.KeyMode.hint,
'load started')
@pyqtSlot(browsertab.AbstractTab, str)
def on_title_changed(self, tab, text):
"""Set the title of a tab.
Slot for the title_changed signal of any tab.
Args:
tab: The WebView where the title was changed.
text: The text to set.
"""
if not text:
log.webview.debug("Ignoring title change to '{}'.".format(text))
return
try:
idx = self._tab_index(tab)
except TabDeletedError:
# We can get signals for tabs we already deleted...
return
log.webview.debug("Changing title for idx {} to '{}'".format(
idx, text))
self.set_page_title(idx, text)
if idx == self.currentIndex():
self.update_window_title()
@pyqtSlot(browsertab.AbstractTab, QUrl)
def on_url_changed(self, tab, url):
"""Set the new URL as title if there's no title yet.
Args:
tab: The WebView where the title was changed.
url: The new URL.
"""
try:
idx = self._tab_index(tab)
except TabDeletedError:
# We can get signals for tabs we already deleted...
return
if not self.page_title(idx):
self.set_page_title(idx, url.toDisplayString())
@pyqtSlot(browsertab.AbstractTab, QIcon)
def on_icon_changed(self, tab, icon):
"""Set the icon of a tab.
Slot for the iconChanged signal of any tab.
Args:
tab: The WebView where the title was changed.
icon: The new icon
"""
if not config.get('tabs', 'show-favicons'):
return
try:
idx = self._tab_index(tab)
except TabDeletedError:
# We can get signals for tabs we already deleted...
return
self.setTabIcon(idx, icon)
if config.get('tabs', 'tabs-are-windows'):
self.window().setWindowIcon(icon)
@pyqtSlot(usertypes.KeyMode)
def on_mode_left(self, mode):
"""Give focus to current tab if command mode was left."""
if mode in [usertypes.KeyMode.command, usertypes.KeyMode.prompt,
usertypes.KeyMode.yesno]:
widget = self.currentWidget()
log.modes.debug("Left status-input mode, focusing {!r}".format(
widget))
if widget is None:
return
widget.setFocus()
@pyqtSlot(int)
def on_current_changed(self, idx):
"""Set last-focused-tab and leave hinting mode when focus changed."""
if idx == -1 or self.shutting_down:
# closing the last tab (before quitting) or shutting down
return
tab = self.widget(idx)
log.modes.debug("Current tab changed, focusing {!r}".format(tab))
tab.setFocus()
for mode in [usertypes.KeyMode.hint, usertypes.KeyMode.insert,
usertypes.KeyMode.caret, usertypes.KeyMode.passthrough]:
modeman.maybe_leave(self._win_id, mode, 'tab changed')
if self._now_focused is not None:
objreg.register('last-focused-tab', self._now_focused, update=True,
scope='window', window=self._win_id)
self._now_focused = tab
self.current_tab_changed.emit(tab)
QTimer.singleShot(0, self.update_window_title)
self._tab_insert_idx_left = self.currentIndex()
self._tab_insert_idx_right = self.currentIndex() + 1
@pyqtSlot()
def on_cmd_return_pressed(self):
"""Set focus when the commandline closes."""
log.modes.debug("Commandline closed, focusing {!r}".format(self))
def on_load_progress(self, tab, perc):
"""Adjust tab indicator on load progress."""
try:
idx = self._tab_index(tab)
except TabDeletedError:
# We can get signals for tabs we already deleted...
return
start = config.get('colors', 'tabs.indicator.start')
stop = config.get('colors', 'tabs.indicator.stop')
system = config.get('colors', 'tabs.indicator.system')
color = utils.interpolate_color(start, stop, perc, system)
self.set_tab_indicator_color(idx, color)
self.update_tab_title(idx)
if idx == self.currentIndex():
self.update_window_title()
def on_load_finished(self, tab, ok):
"""Adjust tab indicator when loading finished."""
try:
idx = self._tab_index(tab)
except TabDeletedError:
# We can get signals for tabs we already deleted...
return
if ok:
start = config.get('colors', 'tabs.indicator.start')
stop = config.get('colors', 'tabs.indicator.stop')
system = config.get('colors', 'tabs.indicator.system')
color = utils.interpolate_color(start, stop, 100, system)
else:
color = config.get('colors', 'tabs.indicator.error')
self.set_tab_indicator_color(idx, color)
self.update_tab_title(idx)
if idx == self.currentIndex():
self.update_window_title()
@pyqtSlot()
def on_scroll_pos_changed(self):
"""Update tab and window title when scroll position changed."""
idx = self.currentIndex()
if idx == -1:
# (e.g. last tab removed)
log.webview.debug("Not updating scroll position because index is "
"-1")
return
self.update_window_title()
self.update_tab_title(idx)
def resizeEvent(self, e):
"""Extend resizeEvent of QWidget to emit a resized signal afterwards.
Args:
e: The QResizeEvent
"""
super().resizeEvent(e)
self.resized.emit(self.geometry())
def wheelEvent(self, e):
"""Override wheelEvent of QWidget to forward it to the focused tab.
Args:
e: The QWheelEvent
"""
if self._now_focused is not None:
self._now_focused.wheelEvent(e)
else:
e.ignore()
def set_mark(self, key):
"""Set a mark at the current scroll position in the current tab.
Args:
key: mark identifier; capital indicates a global mark
"""
# strip the fragment as it may interfere with scrolling
try:
url = self.current_url().adjusted(QUrl.RemoveFragment)
except qtutils.QtValueError:
# show an error only if the mark is not automatically set
if key != "'":
message.error("Failed to set mark: url invalid")
return
point = self.currentWidget().scroller.pos_px()
if key.isupper():
self._global_marks[key] = point, url
else:
if url not in self._local_marks:
self._local_marks[url] = {}
self._local_marks[url][key] = point
def jump_mark(self, key):
"""Jump to the mark named by `key`.
Args:
key: mark identifier; capital indicates a global mark
"""
try:
# consider urls that differ only in fragment to be identical
urlkey = self.current_url().adjusted(QUrl.RemoveFragment)
except qtutils.QtValueError:
urlkey = None
tab = self.currentWidget()
if key.isupper():
if key in self._global_marks:
point, url = self._global_marks[key]
def callback(ok):
if ok:
self.cur_load_finished.disconnect(callback)
tab.scroller.to_point(point)
self.openurl(url, newtab=False)
self.cur_load_finished.connect(callback)
else:
message.error("Mark {} is not set".format(key))
elif urlkey is None:
message.error("Current URL is invalid!")
elif urlkey in self._local_marks and key in self._local_marks[urlkey]:
point = self._local_marks[urlkey][key]
# save the pre-jump position in the special ' mark
# this has to happen after we read the mark, otherwise jump_mark
# "'" would just jump to the current position every time
self.set_mark("'")
tab.scroller.to_point(point)
else:
message.error("Mark {} is not set".format(key))
| 1 | 16,819 | You can simply do `if tab.history_prepared:` here as empty lists are falsey. | qutebrowser-qutebrowser | py |
@@ -25,6 +25,8 @@ import (
"github.com/jetstack/cert-manager/cmd/ctl/pkg/create"
"github.com/jetstack/cert-manager/cmd/ctl/pkg/create/certificatesigningrequest"
+
+ "github.com/jetstack/cert-manager/cmd/ctl/pkg/install"
)
func NewCmdExperimental(ctx context.Context, ioStreams genericclioptions.IOStreams, factory cmdutil.Factory) *cobra.Command { | 1 | /*
Copyright 2021 The cert-manager Authors.
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.
*/
package experimental
import (
"context"
"github.com/spf13/cobra"
"k8s.io/cli-runtime/pkg/genericclioptions"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
"github.com/jetstack/cert-manager/cmd/ctl/pkg/create"
"github.com/jetstack/cert-manager/cmd/ctl/pkg/create/certificatesigningrequest"
)
func NewCmdExperimental(ctx context.Context, ioStreams genericclioptions.IOStreams, factory cmdutil.Factory) *cobra.Command {
cmds := &cobra.Command{
Use: "experimental",
Aliases: []string{"x"},
Short: "Interact with experimental features",
Long: "Interact with experimental features",
}
create := create.NewCmdCreateBare()
create.AddCommand(certificatesigningrequest.NewCmdCreateCSR(ctx, ioStreams, factory))
cmds.AddCommand(create)
return cmds
}
| 1 | 27,759 | Remove this whitespace | jetstack-cert-manager | go |
@@ -118,12 +118,14 @@ def preprocess_example_input(input_config):
input_path = input_config['input_path']
input_shape = input_config['input_shape']
one_img = mmcv.imread(input_path)
+ one_img = mmcv.imresize(one_img, input_shape[2:][::-1])
+ show_img = one_img.copy()
if 'normalize_cfg' in input_config.keys():
normalize_cfg = input_config['normalize_cfg']
mean = np.array(normalize_cfg['mean'], dtype=np.float32)
std = np.array(normalize_cfg['std'], dtype=np.float32)
one_img = mmcv.imnormalize(one_img, mean, std)
- one_img = mmcv.imresize(one_img, input_shape[2:][::-1]).transpose(2, 0, 1)
+ one_img = one_img.transpose(2, 0, 1)
one_img = torch.from_numpy(one_img).unsqueeze(0).float().requires_grad_(
True)
(_, C, H, W) = input_shape | 1 | from functools import partial
import mmcv
import numpy as np
import torch
from mmcv.runner import load_checkpoint
try:
from mmcv.onnx.symbolic import register_extra_symbolics
except ModuleNotFoundError:
raise NotImplementedError('please update mmcv to version>=v1.0.4')
def generate_inputs_and_wrap_model(config_path, checkpoint_path, input_config):
"""Prepare sample input and wrap model for ONNX export.
The ONNX export API only accept args, and all inputs should be
torch.Tensor or corresponding types (such as tuple of tensor).
So we should call this function before exporting. This function will:
1. generate corresponding inputs which are used to execute the model.
2. Wrap the model's forward function.
For example, the MMDet models' forward function has a parameter
``return_loss:bool``. As we want to set it as False while export API
supports neither bool type or kwargs. So we have to replace the forward
like: ``model.forward = partial(model.forward, return_loss=False)``
Args:
config_path (str): the OpenMMLab config for the model we want to
export to ONNX
checkpoint_path (str): Path to the corresponding checkpoint
input_config (dict): the exactly data in this dict depends on the
framework. For MMSeg, we can just declare the input shape,
and generate the dummy data accordingly. However, for MMDet,
we may pass the real img path, or the NMS will return None
as there is no legal bbox.
Returns:
tuple: (model, tensor_data) wrapped model which can be called by \
model(*tensor_data) and a list of inputs which are used to execute \
the model while exporting.
"""
model = build_model_from_cfg(config_path, checkpoint_path)
one_img, one_meta = preprocess_example_input(input_config)
tensor_data = [one_img]
model.forward = partial(
model.forward, img_metas=[[one_meta]], return_loss=False)
# pytorch has some bug in pytorch1.3, we have to fix it
# by replacing these existing op
opset_version = 11
register_extra_symbolics(opset_version)
return model, tensor_data
def build_model_from_cfg(config_path, checkpoint_path):
"""Build a model from config and load the given checkpoint.
Args:
config_path (str): the OpenMMLab config for the model we want to
export to ONNX
checkpoint_path (str): Path to the corresponding checkpoint
Returns:
torch.nn.Module: the built model
"""
from mmdet.models import build_detector
cfg = mmcv.Config.fromfile(config_path)
# import modules from string list.
if cfg.get('custom_imports', None):
from mmcv.utils import import_modules_from_strings
import_modules_from_strings(**cfg['custom_imports'])
cfg.model.pretrained = None
cfg.data.test.test_mode = True
# build the model
model = build_detector(cfg.model, train_cfg=None, test_cfg=cfg.test_cfg)
load_checkpoint(model, checkpoint_path, map_location='cpu')
model.cpu().eval()
return model
def preprocess_example_input(input_config):
"""Prepare an example input image for ``generate_inputs_and_wrap_model``.
Args:
input_config (dict): customized config describing the example input.
Returns:
tuple: (one_img, one_meta), tensor of the example input image and \
meta information for the example input image.
Examples:
>>> from mmdet.core.export import preprocess_example_input
>>> input_config = {
>>> 'input_shape': (1,3,224,224),
>>> 'input_path': 'demo/demo.jpg',
>>> 'normalize_cfg': {
>>> 'mean': (123.675, 116.28, 103.53),
>>> 'std': (58.395, 57.12, 57.375)
>>> }
>>> }
>>> one_img, one_meta = preprocess_example_input(input_config)
>>> print(one_img.shape)
torch.Size([1, 3, 224, 224])
>>> print(one_meta)
{'img_shape': (224, 224, 3),
'ori_shape': (224, 224, 3),
'pad_shape': (224, 224, 3),
'filename': '<demo>.png',
'scale_factor': 1.0,
'flip': False}
"""
input_path = input_config['input_path']
input_shape = input_config['input_shape']
one_img = mmcv.imread(input_path)
if 'normalize_cfg' in input_config.keys():
normalize_cfg = input_config['normalize_cfg']
mean = np.array(normalize_cfg['mean'], dtype=np.float32)
std = np.array(normalize_cfg['std'], dtype=np.float32)
one_img = mmcv.imnormalize(one_img, mean, std)
one_img = mmcv.imresize(one_img, input_shape[2:][::-1]).transpose(2, 0, 1)
one_img = torch.from_numpy(one_img).unsqueeze(0).float().requires_grad_(
True)
(_, C, H, W) = input_shape
one_meta = {
'img_shape': (H, W, C),
'ori_shape': (H, W, C),
'pad_shape': (H, W, C),
'filename': '<demo>.png',
'scale_factor': 1.0,
'flip': False
}
return one_img, one_meta
| 1 | 21,748 | `show_img` is not normalized while `one_img` is normalized. And line 139 pass `show_img` for pytorch2onnx function. Is this expected behavior? | open-mmlab-mmdetection | py |
@@ -45,11 +45,11 @@ function init(instance) {
let inputOffset = /[-+]?\d+\.?\d*/g.exec(this.textContent);
if (inputOffset) {
inputOffset = inputOffset[0];
+ inputOffset = parseFloat(inputOffset);
+ inputOffset = Math.min(30, Math.max(-30, inputOffset));
// replace current text by considered offset
this.textContent = inputOffset + 's';
-
- inputOffset = parseFloat(inputOffset);
// set new offset
playbackManager.setSubtitleOffset(inputOffset, player);
// synchronize with slider value | 1 |
import { playbackManager } from '../playback/playbackmanager';
import layoutManager from '../layoutManager';
import template from './subtitlesync.template.html';
import './subtitlesync.css';
let player;
let subtitleSyncSlider;
let subtitleSyncTextField;
let subtitleSyncCloseButton;
let subtitleSyncContainer;
function init(instance) {
const parent = document.createElement('div');
document.body.appendChild(parent);
parent.innerHTML = template;
subtitleSyncSlider = parent.querySelector('.subtitleSyncSlider');
subtitleSyncTextField = parent.querySelector('.subtitleSyncTextField');
subtitleSyncCloseButton = parent.querySelector('.subtitleSync-closeButton');
subtitleSyncContainer = parent.querySelector('.subtitleSyncContainer');
if (layoutManager.tv) {
subtitleSyncSlider.classList.add('focusable');
// HACK: Delay to give time for registered element attach (Firefox)
setTimeout(function () {
subtitleSyncSlider.enableKeyboardDragging();
}, 0);
}
subtitleSyncContainer.classList.add('hide');
subtitleSyncTextField.updateOffset = function (offset) {
this.textContent = offset + 's';
};
subtitleSyncTextField.addEventListener('click', function () {
// keep focus to prevent fade with osd
this.hasFocus = true;
});
subtitleSyncTextField.addEventListener('keydown', function (event) {
if (event.key === 'Enter') {
// if input key is enter search for float pattern
let inputOffset = /[-+]?\d+\.?\d*/g.exec(this.textContent);
if (inputOffset) {
inputOffset = inputOffset[0];
// replace current text by considered offset
this.textContent = inputOffset + 's';
inputOffset = parseFloat(inputOffset);
// set new offset
playbackManager.setSubtitleOffset(inputOffset, player);
// synchronize with slider value
subtitleSyncSlider.updateOffset(
getPercentageFromOffset(inputOffset));
} else {
this.textContent = (playbackManager.getPlayerSubtitleOffset(player) || 0) + 's';
}
this.hasFocus = false;
event.preventDefault();
} else {
// keep focus to prevent fade with osd
this.hasFocus = true;
if (event.key.match(/[+-\d.s]/) === null) {
event.preventDefault();
}
}
// FIXME: TV layout will require special handling for navigation keys. But now field is not focusable
event.stopPropagation();
});
subtitleSyncTextField.blur = function () {
// prevent textfield to blur while element has focus
if (!this.hasFocus && this.prototype) {
this.prototype.blur();
}
};
subtitleSyncSlider.updateOffset = function (percent) {
// default value is 0s = 50%
this.value = percent === undefined ? 50 : percent;
};
subtitleSyncSlider.addEventListener('change', function () {
// set new offset
playbackManager.setSubtitleOffset(getOffsetFromPercentage(this.value), player);
// synchronize with textField value
subtitleSyncTextField.updateOffset(
getOffsetFromPercentage(this.value));
});
subtitleSyncSlider.getBubbleHtml = function (value) {
const newOffset = getOffsetFromPercentage(value);
return '<h1 class="sliderBubbleText">' +
(newOffset > 0 ? '+' : '') + parseFloat(newOffset) + 's' +
'</h1>';
};
subtitleSyncCloseButton.addEventListener('click', function () {
playbackManager.disableShowingSubtitleOffset(player);
SubtitleSync.prototype.toggle('forceToHide');
});
instance.element = parent;
}
function getOffsetFromPercentage(value) {
// convert percent to fraction
let offset = (value - 50) / 50;
// multiply by offset min/max range value (-x to +x) :
offset *= 30;
return offset.toFixed(1);
}
function getPercentageFromOffset(value) {
// divide by offset min/max range value (-x to +x) :
let percentValue = value / 30;
// convert fraction to percent
percentValue *= 50;
percentValue += 50;
return Math.min(100, Math.max(0, percentValue.toFixed()));
}
class SubtitleSync {
constructor(currentPlayer) {
player = currentPlayer;
init(this);
}
destroy() {
SubtitleSync.prototype.toggle('forceToHide');
if (player) {
playbackManager.disableShowingSubtitleOffset(player);
playbackManager.setSubtitleOffset(0, player);
}
const elem = this.element;
if (elem) {
elem.parentNode.removeChild(elem);
this.element = null;
}
}
toggle(action) {
if (player && playbackManager.supportSubtitleOffset(player)) {
/* eslint-disable no-fallthrough */
switch (action) {
case undefined:
// if showing subtitle sync is enabled and if there is an external subtitle stream enabled
if (playbackManager.isShowingSubtitleOffsetEnabled(player) && playbackManager.canHandleOffsetOnCurrentSubtitle(player)) {
// if no subtitle offset is defined or element has focus (offset being defined)
if (!(playbackManager.getPlayerSubtitleOffset(player) || subtitleSyncTextField.hasFocus)) {
// set default offset to '0' = 50%
subtitleSyncSlider.value = '50';
subtitleSyncTextField.textContent = '0s';
playbackManager.setSubtitleOffset(0, player);
}
// show subtitle sync
subtitleSyncContainer.classList.remove('hide');
break; // stop here
} // else continue and hide
case 'hide':
// only break if element has focus
if (subtitleSyncTextField.hasFocus) {
break;
}
case 'forceToHide':
subtitleSyncContainer.classList.add('hide');
break;
}
/* eslint-enable no-fallthrough */
}
}
}
export default SubtitleSync;
| 1 | 18,375 | Why is this bounded between -30 and 30? | jellyfin-jellyfin-web | js |
@@ -21,7 +21,7 @@ THE SOFTWARE.
*/
/* HIT_START
- * BUILD: %t %s ../../test_common.cpp EXCLUDE_HIP_PLATFORM all
+ * BUILD: %t %s ../../test_common.cpp EXCLUDE_HIP_PLATFORM nvcc
* TEST: %t
* HIT_END
*/ | 1 | /*
Copyright (c) 2015-2017 Advanced Micro Devices, Inc. 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.
*/
/* HIT_START
* BUILD: %t %s ../../test_common.cpp EXCLUDE_HIP_PLATFORM all
* TEST: %t
* HIT_END
*/
#include "hip/hip_runtime.h"
#include "test_common.h"
void printSep() {
printf(
"======================================================================================\n");
}
//---
// Test copies of a matrix numW by numH
// The subroutine allocates memory , copies to device, runs a vector add kernel, copies back, and
// checks the result.
//
// IN: numW: number of elements in the 1st dimension used for allocation
// IN: numH: number of elements in the 2nd dimension used for allocation
// IN: usePinnedHost : If true, allocate host with hipHostMalloc and is pinned ; else allocate host
// memory with malloc.
//
template <typename T>
void memcpy2Dtest(size_t numW, size_t numH, bool usePinnedHost) {
size_t width = numW * sizeof(T);
size_t sizeElements = width * numH;
printf("memcpy2Dtest: %s<%s> size=%lu (%6.2fMB) W: %d, H:%d, usePinnedHost: %d\n", __func__,
TYPENAME(T), sizeElements, sizeElements / 1024.0 / 1024.0, (int)numW, (int)numH,
usePinnedHost);
T *A_d, *B_d, *C_d;
T *A_h, *B_h, *C_h;
size_t pitch_A, pitch_B, pitch_C;
hipChannelFormatDesc desc = hipCreateChannelDesc<T>();
HipTest::initArrays2DPitch(&A_d, &B_d, &C_d, &pitch_A, &pitch_B, &pitch_C, numW, numH);
HipTest::initArraysForHost(&A_h, &B_h, &C_h, numW * numH, usePinnedHost);
unsigned blocks = HipTest::setNumBlocks(blocksPerCU, threadsPerBlock, numW * numH);
HIPCHECK(hipMemcpy2D(A_d, pitch_A, A_h, width, width, numH, hipMemcpyHostToDevice));
HIPCHECK(hipMemcpy2D(B_d, pitch_B, B_h, width, width, numH, hipMemcpyHostToDevice));
hipLaunchKernelGGL(HipTest::vectorADD, dim3(blocks), dim3(threadsPerBlock), 0, 0, A_d, B_d, C_d,
(pitch_C / sizeof(T)) * numH);
HIPCHECK(hipMemcpy2D(C_h, width, C_d, pitch_C, width, numH, hipMemcpyDeviceToHost));
HIPCHECK(hipDeviceSynchronize());
HipTest::checkVectorADD(A_h, B_h, C_h, numW * numH);
HipTest::freeArrays(A_d, B_d, C_d, A_h, B_h, C_h, usePinnedHost);
printf(" %s success\n", __func__);
}
//---
// Test copies of a matrix numW by numH into a hipArray data structure
// The subroutine allocates memory , copies to device, runs a vector add kernel, copies back, and
// checks the result.
//
// IN: numW: number of elements in the 1st dimension used for allocation
// IN: numH: number of elements in the 2nd dimension used for allocation. If this is 1, then the
// 1-dimensional copy API
// would be used
// IN: usePinnedHost : If true, allocate host with hipHostMalloc and is pinned ; else allocate host
// memory with malloc. IN: usePitch: If true, pads additional memory. This is only valid in the
// 2-dimensional case
//
template <typename T>
void memcpyArraytest(size_t numW, size_t numH, bool usePinnedHost, bool usePitch = false) {
size_t width = numW * sizeof(T);
size_t sizeElements = width * numH;
printf(
"memcpyArraytest: %s<%s> size=%lu (%6.2fMB) W: %d, H: %d, usePinnedHost: %d, usePitch: "
"%d\n",
__func__, TYPENAME(T), sizeElements, sizeElements / 1024.0 / 1024.0, (int)numW, (int)numH,
usePinnedHost, usePitch);
hipArray *A_d, *B_d, *C_d;
T *A_h, *B_h, *C_h;
// 1D
if ((numW >= 1) && (numH == 1)) {
hipChannelFormatDesc desc = hipCreateChannelDesc<T>();
HipTest::initHIPArrays(&A_d, &B_d, &C_d, &desc, numW, 1, 0);
HipTest::initArraysForHost(&A_h, &B_h, &C_h, numW * numH, usePinnedHost);
unsigned blocks = HipTest::setNumBlocks(blocksPerCU, threadsPerBlock, numW * numH);
HIPCHECK(hipMemcpyToArray(A_d, 0, 0, (void*)A_h, width, hipMemcpyHostToDevice));
HIPCHECK(hipMemcpyToArray(B_d, 0, 0, (void*)B_h, width, hipMemcpyHostToDevice));
hipLaunchKernelGGL(HipTest::vectorADD, dim3(blocks), dim3(threadsPerBlock), 0, 0,
(T*)A_d->data, (T*)B_d->data, (T*)C_d->data, numW);
HIPCHECK(hipMemcpy(C_h, C_d->data, width, hipMemcpyDeviceToHost));
HIPCHECK(hipDeviceSynchronize());
HipTest::checkVectorADD(A_h, B_h, C_h, numW);
}
// 2D
else if ((numW >= 1) && (numH >= 1)) {
hipChannelFormatDesc desc = hipCreateChannelDesc<T>();
HipTest::initHIPArrays(&A_d, &B_d, &C_d, &desc, numW, numH, 0);
HipTest::initArraysForHost(&A_h, &B_h, &C_h, numW * numH, usePinnedHost);
unsigned blocks = HipTest::setNumBlocks(blocksPerCU, threadsPerBlock, numW * numH);
if (usePitch) {
T *A_p, *B_p, *C_p;
size_t pitch_A, pitch_B, pitch_C;
HipTest::initArrays2DPitch(&A_p, &B_p, &C_p, &pitch_A, &pitch_B, &pitch_C, numW, numH);
HIPCHECK(hipMemcpy2D(A_p, pitch_A, A_h, width, width, numH, hipMemcpyHostToDevice));
HIPCHECK(hipMemcpy2D(B_p, pitch_B, B_h, width, width, numH, hipMemcpyHostToDevice));
HIPCHECK(hipMemcpy2DToArray(A_d, 0, 0, (void*)A_p, pitch_A, width, numH,
hipMemcpyDeviceToDevice));
HIPCHECK(hipMemcpy2DToArray(B_d, 0, 0, (void*)B_p, pitch_B, width, numH,
hipMemcpyDeviceToDevice));
hipFree(A_p);
hipFree(B_p);
hipFree(C_p);
} else {
HIPCHECK(hipMemcpy2DToArray(A_d, 0, 0, (void*)A_h, width, width, numH,
hipMemcpyHostToDevice));
HIPCHECK(hipMemcpy2DToArray(B_d, 0, 0, (void*)B_h, width, width, numH,
hipMemcpyHostToDevice));
}
hipLaunchKernelGGL(HipTest::vectorADD, dim3(blocks), dim3(threadsPerBlock), 0, 0,
(T*)A_d->data, (T*)B_d->data, (T*)C_d->data, numW * numH);
HIPCHECK(hipMemcpy2D((void*)C_h, width, (void*)C_d->data, width, width, numH,
hipMemcpyDeviceToHost));
HIPCHECK(hipDeviceSynchronize());
HipTest::checkVectorADD(A_h, B_h, C_h, numW * numH);
}
// Unknown
else {
HIPASSERT("Incompatible dimensions" && 0);
}
hipFreeArray(A_d);
hipFreeArray(B_d);
hipFreeArray(C_d);
HipTest::freeArraysForHost(A_h, B_h, C_h, usePinnedHost);
printf(" %s success\n", __func__);
}
//---
// Try many different sizes to memory copy.
template <typename T>
void memcpyArraytest_size(size_t maxElem = 0, size_t offset = 0) {
printf("test: %s<%s>\n", __func__, TYPENAME(T));
int deviceId;
HIPCHECK(hipGetDevice(&deviceId));
size_t free, total;
HIPCHECK(hipMemGetInfo(&free, &total));
if (maxElem == 0) {
maxElem = free / sizeof(T) / 5;
}
printf(
" device#%d: hipMemGetInfo: free=%zu (%4.2fMB) total=%zu (%4.2fMB) maxSize=%6.1fMB "
"offset=%lu\n",
deviceId, free, (float)(free / 1024.0 / 1024.0), total, (float)(total / 1024.0 / 1024.0),
maxElem * sizeof(T) / 1024.0 / 1024.0, offset);
// Test 1D
for (size_t elem = 64; elem + offset <= maxElem; elem *= 2) {
HIPCHECK(hipDeviceReset());
memcpyArraytest<T>(elem + offset, 1, 0); // unpinned host
HIPCHECK(hipDeviceReset());
memcpyArraytest<T>(elem + offset, 1, 1); // pinned host
}
// Test 2D
size_t maxElem2D = sqrt(maxElem);
for (size_t elem = 64; elem + offset <= maxElem2D; elem *= 2) {
HIPCHECK(hipDeviceReset());
memcpyArraytest<T>(elem + offset, elem + offset, 0, 1); // use pitch
}
}
int main(int argc, char* argv[]) {
HipTest::parseStandardArguments(argc, argv, true);
printf("info: set device to %d\n", p_gpuDevice);
HIPCHECK(hipSetDevice(p_gpuDevice));
if (p_tests & 0x1) {
printf("\n\n=== tests&1 (types)\n");
printSep();
HIPCHECK(hipDeviceReset());
size_t width = N / 6;
size_t height = N / 6;
memcpy2Dtest<float>(321, 211, 0);
memcpy2Dtest<double>(322, 211, 0);
memcpy2Dtest<char>(320, 211, 0);
memcpy2Dtest<int>(323, 211, 0);
printf("===\n\n\n");
printf("\n\n=== tests&1 (types)\n");
printSep();
// 2D
memcpyArraytest<float>(320, 211, 0, 0);
memcpyArraytest<unsigned int>(322, 211, 0, 0);
memcpyArraytest<int>(320, 211, 0, 0);
memcpyArraytest<float>(320, 211, 0, 1);
memcpyArraytest<float>(322, 211, 0, 1);
memcpyArraytest<int>(320, 211, 0, 1);
printSep();
// 1D
memcpyArraytest<float>(320, 1, 0);
memcpyArraytest<unsigned int>(322, 1, 0);
memcpyArraytest<int>(320, 1, 0);
printf("===\n\n\n");
}
if (p_tests & 0x4) {
printf("\n\n=== tests&4 (test sizes and offsets)\n");
printSep();
HIPCHECK(hipDeviceReset());
printSep();
memcpyArraytest_size<float>(0, 0);
printSep();
memcpyArraytest_size<float>(0, 64);
printSep();
memcpyArraytest_size<float>(1024 * 1024, 13);
printSep();
memcpyArraytest_size<float>(1024 * 1024, 50);
}
passed();
}
| 1 | 8,114 | I think even you can exclude to run it on nvcc | ROCm-Developer-Tools-HIP | cpp |
@@ -179,7 +179,7 @@ func CreateIstgtConf(cStorVolume *apis.CStorVolume) []byte {
buffer.WriteString(`
PhysRecordLength 4096
`)
- buffer.WriteString(" LUN0 Storage " + cStorVolume.Spec.Capacity + " 32k")
+ buffer.WriteString(" LUN0 Storage " + cStorVolume.Spec.Capacity.String() + " 32k")
buffer.WriteString(`
LUN0 Option Unmap Disable
LUN0 Option WZero Disable | 1 | /*
Copyright 2018 The OpenEBS Authors.
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.
*/
package volume
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/golang/glog"
apis "github.com/openebs/maya/pkg/apis/openebs.io/v1alpha1"
"github.com/openebs/maya/pkg/util"
"github.com/pkg/errors"
)
// VolumeOperator is the name of the tool that makes volume-related operations.
const (
VolumeOperator = "iscsi"
)
//FileOperatorVar is used for doing File Operations
var FileOperatorVar util.FileOperator
//UnixSockVar is used for communication through Unix Socket
var UnixSockVar util.UnixSock
func init() {
UnixSockVar = util.RealUnixSock{}
FileOperatorVar = util.RealFileOperator{}
}
// CreateVolumeTarget creates a new cStor volume istgt config.
func CreateVolumeTarget(cStorVolume *apis.CStorVolume) error {
// create conf file
text := CreateIstgtConf(cStorVolume)
err := FileOperatorVar.Write(util.IstgtConfPath, text, 0644)
if err != nil {
glog.Errorf("Failed to write istgt.conf")
}
glog.Info("Done writing istgt.conf")
// send refresh command to istgt and read the response
_, err = UnixSockVar.SendCommand(util.IstgtRefreshCmd)
if err != nil {
glog.Info("Failed to refresh iscsi service with new configuration.")
}
glog.Info("Creating Iscsi Volume Successful")
return nil
}
// GetVolumeStatus retrieves an array of replica statuses.
func GetVolumeStatus(cStorVolume *apis.CStorVolume) (*apis.CVStatus, error) {
// send replica command to istgt and read the response
statuses, err := UnixSockVar.SendCommand(util.IstgtReplicaCmd)
if err != nil {
glog.Errorf("Failed to list replicas.")
return nil, err
}
stringResp := fmt.Sprintf("%s", statuses)
// Here it is assumed that the arrays statuses contains only one json and
// the chars '}' and '{' are present only in the json string.
// Therefore, the json string begins with '{' and ends with '}'
//
// TODO: Find a better approach
jsonBeginIndex := strings.Index(stringResp, "{")
jsonEndIndex := strings.LastIndex(stringResp, "}")
if jsonBeginIndex >= jsonEndIndex {
return nil, nil
}
return extractReplicaStatusFromJSON(stringResp[jsonBeginIndex : jsonEndIndex+1])
}
// extractReplicaStatusFromJSON recieves a volume name and a json string.
// It then extracts and returns an array of replica statuses.
func extractReplicaStatusFromJSON(str string) (*apis.CVStatus, error) {
// Unmarshal json into CVStatusResponse
cvResponse := apis.CVStatusResponse{}
err := json.Unmarshal([]byte(str), &cvResponse)
if err != nil {
return nil, err
}
if len(cvResponse.CVStatuses) == 0 {
return nil, errors.Errorf("empty volume status from istgt")
}
return &cvResponse.CVStatuses[0], nil
}
// CreateIstgtConf creates istgt.conf file
func CreateIstgtConf(cStorVolume *apis.CStorVolume) []byte {
var buffer bytes.Buffer
buffer.WriteString(`# Global section
[Global]
`)
buffer.WriteString(" NodeBase \"" + cStorVolume.Spec.NodeBase + "\"")
buffer.WriteString(`
PidFile "/var/run/istgt.pid"
AuthFile "/usr/local/etc/istgt/auth.conf"
LogFile "/usr/local/etc/istgt/logfile"
Luworkers 6
MediaDirectory "/mnt"
Timeout 60
NopInInterval 20
MaxR2T 16
DiscoveryAuthMethod None
DiscoveryAuthGroup None
MaxSessions 32
MaxConnections 4
FirstBurstLength 262144
MaxBurstLength 1048576
MaxRecvDataSegmentLength 262144
MaxOutstandingR2T 16
DefaultTime2Wait 2
DefaultTime2Retain 20
OperationalMode 0
# UnitControl section
[UnitControl]
AuthMethod None
AuthGroup None
`)
buffer.WriteString(" Portal UC1 " + cStorVolume.Spec.TargetIP + ":3261\n")
buffer.WriteString(" Netmask " + cStorVolume.Spec.TargetIP + "/8\n")
buffer.WriteString(`
# PortalGroup section
[PortalGroup1]
`)
buffer.WriteString(" Portal DA1 " + cStorVolume.Spec.TargetIP + ":3260\n")
buffer.WriteString(`
# InitiatorGroup section
[InitiatorGroup1]
InitiatorName "ALL"
Netmask "ALL"
[InitiatorGroup2]
InitiatorName "None"
Netmask "None"
# LogicalUnit section
[LogicalUnit1]
`)
buffer.WriteString(" TargetName " + cStorVolume.Name + "\n")
buffer.WriteString(" TargetAlias nicknamefor-" + cStorVolume.Name)
buffer.WriteString(`
Mapping PortalGroup1 InitiatorGroup1
AuthMethod None
AuthGroup None
UseDigest Auto
ReadOnly No
`)
buffer.WriteString(" ReplicationFactor " + strconv.Itoa(cStorVolume.Spec.ReplicationFactor) + "\n")
buffer.WriteString(" ConsistencyFactor " + strconv.Itoa(cStorVolume.Spec.ConsistencyFactor))
buffer.WriteString(`
UnitType Disk
UnitOnline Yes
BlockLength 512
QueueDepth 32
Luworkers 6
`)
buffer.WriteString(" UnitInquiry \"OpenEBS\" \"iscsi\" \"0\" \"" + string(cStorVolume.UID) + "\"")
buffer.WriteString(`
PhysRecordLength 4096
`)
buffer.WriteString(" LUN0 Storage " + cStorVolume.Spec.Capacity + " 32k")
buffer.WriteString(`
LUN0 Option Unmap Disable
LUN0 Option WZero Disable
LUN0 Option ATS Disable
LUN0 Option XCOPY Disable
`)
return buffer.Bytes()
}
// CheckValidVolume checks for validity of CStorVolume resource.
func CheckValidVolume(cStorVolume *apis.CStorVolume) error {
if len(string(cStorVolume.ObjectMeta.UID)) == 0 {
return fmt.Errorf("Invalid volume resource")
}
if len(string(cStorVolume.Spec.TargetIP)) == 0 {
return fmt.Errorf("targetIP cannot be empty")
}
if len(string(cStorVolume.Name)) == 0 {
return fmt.Errorf("volumeName cannot be empty")
}
if len(string(cStorVolume.UID)) == 0 {
return fmt.Errorf("volumeID cannot be empty")
}
if len(string(cStorVolume.Spec.Capacity)) == 0 {
return fmt.Errorf("capacity cannot be empty")
}
if cStorVolume.Spec.ReplicationFactor == 0 {
return fmt.Errorf("replicationFactor cannot be zero")
}
if cStorVolume.Spec.ConsistencyFactor == 0 {
return fmt.Errorf("consistencyFactor cannot be zero")
}
if cStorVolume.Spec.ReplicationFactor < cStorVolume.Spec.ConsistencyFactor {
return fmt.Errorf("replicationFactor cannot be less than consistencyFactor")
}
return nil
}
| 1 | 17,075 | G104: Errors unhandled. (from `gosec`) | openebs-maya | go |
@@ -182,6 +182,11 @@ class ECSTask(luigi.Task):
response = client.run_task(taskDefinition=self.task_def_arn,
overrides=overrides,
cluster=self.cluster)
+
+ if response['failures']:
+ raise Exception(", ".join(["fail to run task {0} reason: {1}".format(failure['arn'], failure['reason'])
+ for failure in response['failures']]))
+
self._task_ids = [task['taskArn'] for task in response['tasks']]
# Wait on task completion | 1 | # -*- coding: utf-8 -*-
#
# Copyright 2015 Outlier Bio, LLC
#
# 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.
#
"""
EC2 Container Service wrapper for Luigi
From the AWS website:
Amazon EC2 Container Service (ECS) is a highly scalable, high performance
container management service that supports Docker containers and allows you
to easily run applications on a managed cluster of Amazon EC2 instances.
To use ECS, you create a taskDefinition_ JSON that defines the `docker run`_
command for one or more containers in a task or service, and then submit this
JSON to the API to run the task.
This `boto3-powered`_ wrapper allows you to create Luigi Tasks to submit ECS
``taskDefinition`` s. You can either pass a dict (mapping directly to the
``taskDefinition`` JSON) OR an Amazon Resource Name (arn) for a previously
registered ``taskDefinition``.
Requires:
- boto3 package
- Amazon AWS credentials discoverable by boto3 (e.g., by using ``aws configure``
from awscli_)
- A running ECS cluster (see `ECS Get Started`_)
Written and maintained by Jake Feala (@jfeala) for Outlier Bio (@outlierbio)
.. _`docker run`: https://docs.docker.com/reference/commandline/run
.. _taskDefinition: http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_defintions.html
.. _`boto3-powered`: https://boto3.readthedocs.io
.. _awscli: https://aws.amazon.com/cli
.. _`ECS Get Started`: http://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_GetStarted.html
"""
import time
import logging
import luigi
logger = logging.getLogger('luigi-interface')
try:
import boto3
client = boto3.client('ecs')
except ImportError:
logger.warning('boto3 is not installed. ECSTasks require boto3')
POLL_TIME = 2
def _get_task_statuses(task_ids, cluster):
"""
Retrieve task statuses from ECS API
Returns list of {RUNNING|PENDING|STOPPED} for each id in task_ids
"""
response = client.describe_tasks(tasks=task_ids, cluster=cluster)
# Error checking
if response['failures'] != []:
raise Exception('There were some failures:\n{0}'.format(
response['failures']))
status_code = response['ResponseMetadata']['HTTPStatusCode']
if status_code != 200:
msg = 'Task status request received status code {0}:\n{1}'
raise Exception(msg.format(status_code, response))
return [t['lastStatus'] for t in response['tasks']]
def _track_tasks(task_ids, cluster):
"""Poll task status until STOPPED"""
while True:
statuses = _get_task_statuses(task_ids, cluster)
if all([status == 'STOPPED' for status in statuses]):
logger.info('ECS tasks {0} STOPPED'.format(','.join(task_ids)))
break
time.sleep(POLL_TIME)
logger.debug('ECS task status for tasks {0}: {1}'.format(task_ids, statuses))
class ECSTask(luigi.Task):
"""
Base class for an Amazon EC2 Container Service Task
Amazon ECS requires you to register "tasks", which are JSON descriptions
for how to issue the ``docker run`` command. This Luigi Task can either
run a pre-registered ECS taskDefinition, OR register the task on the fly
from a Python dict.
:param task_def_arn: pre-registered task definition ARN (Amazon Resource
Name), of the form::
arn:aws:ecs:<region>:<user_id>:task-definition/<family>:<tag>
:param task_def: dict describing task in taskDefinition JSON format, for
example::
task_def = {
'family': 'hello-world',
'volumes': [],
'containerDefinitions': [
{
'memory': 1,
'essential': True,
'name': 'hello-world',
'image': 'ubuntu',
'command': ['/bin/echo', 'hello world']
}
]
}
:param cluster: str defining the ECS cluster to use.
When this is not defined it will use the default one.
"""
task_def_arn = luigi.OptionalParameter(default=None)
task_def = luigi.OptionalParameter(default=None)
cluster = luigi.Parameter(default='default')
@property
def ecs_task_ids(self):
"""Expose the ECS task ID"""
if hasattr(self, '_task_ids'):
return self._task_ids
@property
def command(self):
"""
Command passed to the containers
Override to return list of dicts with keys 'name' and 'command',
describing the container names and commands to pass to the container.
Directly corresponds to the `overrides` parameter of runTask API. For
example::
[
{
'name': 'myContainer',
'command': ['/bin/sleep', '60']
}
]
"""
pass
def run(self):
if (not self.task_def and not self.task_def_arn) or \
(self.task_def and self.task_def_arn):
raise ValueError(('Either (but not both) a task_def (dict) or'
'task_def_arn (string) must be assigned'))
if not self.task_def_arn:
# Register the task and get assigned taskDefinition ID (arn)
response = client.register_task_definition(**self.task_def)
self.task_def_arn = response['taskDefinition']['taskDefinitionArn']
# Submit the task to AWS ECS and get assigned task ID
# (list containing 1 string)
if self.command:
overrides = {'containerOverrides': self.command}
else:
overrides = {}
response = client.run_task(taskDefinition=self.task_def_arn,
overrides=overrides,
cluster=self.cluster)
self._task_ids = [task['taskArn'] for task in response['tasks']]
# Wait on task completion
_track_tasks(self._task_ids, self.cluster)
| 1 | 18,591 | will `failure` always include `arn` and `reason` in its dictionary? If so, :+1: | spotify-luigi | py |
@@ -46,13 +46,13 @@ module Bolt
@logger = Logging.logger[self]
end
- def with_events(target, callback)
+ def with_events(target, callback, action)
callback&.call(type: :node_start, target: target)
result = begin
yield
rescue StandardError, NotImplementedError => e
- Bolt::Result.from_exception(target, e)
+ Bolt::Result.from_exception(target, e, action: action)
end
callback&.call(type: :node_result, result: result) | 1 | # frozen_string_literal: true
require 'logging'
require 'bolt/result'
module Bolt
module Transport
# This class provides the default behavior for Transports. A Transport is
# responsible for uploading files and running commands, scripts, and tasks
# on Targets.
#
# Bolt executes work on the Transport in "batches". To do that, it calls
# the batches() method, which is responsible for dividing the list of
# Targets into batches according to how it wants to handle them. It will
# then call Transport#batch_task, or the corresponding method for another
# operation, passing a list of Targets. The Transport returns a list of
# Bolt::Result objects, one per Target. Each batch is executed on a
# separate thread, controlled by the `concurrency` setting, so many batches
# may be running in parallel.
#
# The default batch implementation splits the list of Targets into batches
# of 1. It then calls run_task(), or a corresponding method for other
# operations, passing in the single Target.
#
# Most Transport implementations, like the SSH and WinRM transports, don't
# need to do their own batching, since they only operate on a single Target
# at a time. Those Transports can implement the run_task() and related
# methods, which will automatically handle running many Targets in
# parallel, and will handle publishing start and finish events for each
# Target.
#
# Transports that need their own batching, like the Orch transport, can
# instead override the batches() method to split Targets into sets that can
# be executed together, and override the batch_task() and related methods
# to execute a batch of nodes. In that case, those Transports should accept
# a block argument and call it with a :node_start event for each Target
# before executing, and a :node_result event for each Target after
# execution.
class Base
STDIN_METHODS = %w[both stdin].freeze
ENVIRONMENT_METHODS = %w[both environment].freeze
attr_reader :logger
def initialize
@logger = Logging.logger[self]
end
def with_events(target, callback)
callback&.call(type: :node_start, target: target)
result = begin
yield
rescue StandardError, NotImplementedError => e
Bolt::Result.from_exception(target, e)
end
callback&.call(type: :node_result, result: result)
result
end
def provided_features
[]
end
def default_input_method(_executable)
'both'
end
def select_implementation(target, task)
impl = task.select_implementation(target, provided_features)
impl['input_method'] ||= default_input_method(impl['path'])
impl
end
def select_interpreter(executable, interpreters)
interpreters[Pathname(executable).extname] if interpreters
end
# Transform a parameter map to an environment variable map, with parameter names prefixed
# with 'PT_' and values transformed to JSON unless they're strings.
def envify_params(params)
params.each_with_object({}) do |(k, v), h|
v = v.to_json unless v.is_a?(String)
h["PT_#{k}"] = v
end
end
# Raises an error if more than one target was given in the batch.
#
# The default implementations of batch_* strictly assume the transport is
# using the default batch size of 1. This method ensures that is the
# case and raises an error if it's not.
def assert_batch_size_one(method, targets)
if targets.length > 1
message = "#{self.class.name} must implement #{method} to support batches (got #{targets.length} nodes)"
raise NotImplementedError, message
end
end
# Runs the given task on a batch of nodes.
#
# The default implementation only supports batches of size 1 and will fail otherwise.
#
# Transports may override this method to implement their own batch processing.
def batch_task(targets, task, arguments, options = {}, &callback)
assert_batch_size_one("batch_task()", targets)
target = targets.first
with_events(target, callback) do
@logger.debug { "Running task run '#{task}' on #{target.safe_name}" }
run_task(target, task, arguments, options)
end
end
# Runs the given command on a batch of nodes.
#
# The default implementation only supports batches of size 1 and will fail otherwise.
#
# Transports may override this method to implement their own batch processing.
def batch_command(targets, command, options = {}, &callback)
assert_batch_size_one("batch_command()", targets)
target = targets.first
with_events(target, callback) do
@logger.debug("Running command '#{command}' on #{target.safe_name}")
run_command(target, command, options)
end
end
# Runs the given script on a batch of nodes.
#
# The default implementation only supports batches of size 1 and will fail otherwise.
#
# Transports may override this method to implement their own batch processing.
def batch_script(targets, script, arguments, options = {}, &callback)
assert_batch_size_one("batch_script()", targets)
target = targets.first
with_events(target, callback) do
@logger.debug { "Running script '#{script}' on #{target.safe_name}" }
run_script(target, script, arguments, options)
end
end
# Uploads the given source file to the destination location on a batch of nodes.
#
# The default implementation only supports batches of size 1 and will fail otherwise.
#
# Transports may override this method to implement their own batch processing.
def batch_upload(targets, source, destination, options = {}, &callback)
assert_batch_size_one("batch_upload()", targets)
target = targets.first
with_events(target, callback) do
@logger.debug { "Uploading: '#{source}' to #{destination} on #{target.safe_name}" }
upload(target, source, destination, options)
end
end
def batch_connected?(targets)
assert_batch_size_one("connected?()", targets)
connected?(targets.first)
end
# Split the given list of targets into a list of batches. The default
# implementation returns single-node batches.
#
# Transports may override this method, and the corresponding batch_*
# methods, to implement their own batch processing.
def batches(targets)
targets.map { |target| [target] }
end
# Transports should override this method with their own implementation of running a command.
def run_command(*_args)
raise NotImplementedError, "run_command() must be implemented by the transport class"
end
# Transports should override this method with their own implementation of running a script.
def run_script(*_args)
raise NotImplementedError, "run_script() must be implemented by the transport class"
end
# Transports should override this method with their own implementation of running a task.
def run_task(*_args)
raise NotImplementedError, "run_task() must be implemented by the transport class"
end
# Transports should override this method with their own implementation of file upload.
def upload(*_args)
raise NotImplementedError, "upload() must be implemented by the transport class"
end
# Transports should override this method with their own implementation of a connection test.
def connected?(_targets)
raise NotImplementedError, "connected?() must be implemented by the transport class"
end
# Unwraps any Sensitive data in an arguments Hash, so the plain-text is passed
# to the Task/Script.
#
# This works on deeply nested data structures composed of Hashes, Arrays, and
# and plain-old data types (int, string, etc).
def unwrap_sensitive_args(arguments)
# Skip this if Puppet isn't loaded
return arguments unless defined?(Puppet::Pops::Types::PSensitiveType::Sensitive)
case arguments
when Array
# iterate over the array, unwrapping all elements
arguments.map { |x| unwrap_sensitive_args(x) }
when Hash
# iterate over the arguments hash and unwrap all keys and values
arguments.each_with_object({}) { |(k, v), h|
h[unwrap_sensitive_args(k)] = unwrap_sensitive_args(v)
}
when Puppet::Pops::Types::PSensitiveType::Sensitive
# this value is Sensitive, unwrap it
unwrap_sensitive_args(arguments.unwrap)
else
# unknown data type, just return it
arguments
end
end
end
end
end
| 1 | 14,415 | Should this be optional, or default to 'action' as well? | puppetlabs-bolt | rb |
@@ -16,6 +16,12 @@ package client
import (
"context"
+ "github.com/pkg/errors"
+ "k8s.io/apimachinery/pkg/types"
+ ctrl "sigs.k8s.io/controller-runtime"
+
+ "github.com/chaos-mesh/chaos-mesh/controllers/config"
+
"google.golang.org/grpc"
v1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client" | 1 | // Copyright 2020 Chaos Mesh Authors.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package client
import (
"context"
"google.golang.org/grpc"
v1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
chaosdaemon "github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
grpcUtils "github.com/chaos-mesh/chaos-mesh/pkg/grpc"
"github.com/chaos-mesh/chaos-mesh/pkg/mock"
)
// ChaosDaemonClientInterface represents the ChaosDaemonClient, it's used to simply unit test
type ChaosDaemonClientInterface interface {
chaosdaemon.ChaosDaemonClient
Close() error
}
// GrpcChaosDaemonClient would act like chaosdaemon.ChaosDaemonClient with a Close method
type GrpcChaosDaemonClient struct {
chaosdaemon.ChaosDaemonClient
conn *grpc.ClientConn
}
func (c *GrpcChaosDaemonClient) Close() error {
return c.conn.Close()
}
// NewChaosDaemonClient would create ChaosDaemonClient
func NewChaosDaemonClient(ctx context.Context, c client.Client, pod *v1.Pod, port int) (ChaosDaemonClientInterface, error) {
if cli := mock.On("MockChaosDaemonClient"); cli != nil {
return cli.(ChaosDaemonClientInterface), nil
}
if err := mock.On("NewChaosDaemonClientError"); err != nil {
return nil, err.(error)
}
cc, err := grpcUtils.CreateGrpcConnection(ctx, c, pod, port)
if err != nil {
return nil, err
}
return &GrpcChaosDaemonClient{
ChaosDaemonClient: chaosdaemon.NewChaosDaemonClient(cc),
conn: cc,
}, nil
}
// NewChaosDaemonClientLocally would create ChaosDaemonClient in localhost
func NewChaosDaemonClientLocally(port int) (ChaosDaemonClientInterface, error) {
if cli := mock.On("MockChaosDaemonClient"); cli != nil {
return cli.(ChaosDaemonClientInterface), nil
}
if err := mock.On("NewChaosDaemonClientError"); err != nil {
return nil, err.(error)
}
cc, err := grpcUtils.CreateGrpcConnectionWithAddress("localhost", port)
if err != nil {
return nil, err
}
return &GrpcChaosDaemonClient{
ChaosDaemonClient: chaosdaemon.NewChaosDaemonClient(cc),
conn: cc,
}, nil
}
| 1 | 19,785 | how about formating this import? | chaos-mesh-chaos-mesh | go |
@@ -177,13 +177,14 @@ def getReviewPosition():
globalVars.reviewPosition,globalVars.reviewPositionObj=review.getPositionForCurrentMode(obj)
return globalVars.reviewPosition
-def setReviewPosition(reviewPosition,clearNavigatorObject=True):
+def setReviewPosition(reviewPosition,clearNavigatorObject=True, isCaret=False):
"""Sets a TextInfo instance as the review position. if clearNavigatorObject is true, It sets the current navigator object to None so that the next time the navigator object is asked for it fetches it from the review position.
"""
globalVars.reviewPosition=reviewPosition.copy()
globalVars.reviewPositionObj=reviewPosition.obj
if clearNavigatorObject: globalVars.navigatorObject=None
- braille.handler.handleReviewMove()
+ eventHandler.lastReviewMoveDueToFollowing = isCaret
+ braille.handler.handleReviewMove(shouldAutoTether=not isCaret)
def getNavigatorObject():
"""Gets the current navigator object. Navigator objects can be used to navigate around the operating system (with the number pad) with out moving the focus. If the navigator object is not set, it fetches it from the review position. | 1 | #api.py
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2006-2012 NVDA Contributors
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
"""General functions for NVDA"""
import config
import textInfos
import review
import globalVars
from logHandler import log
import ui
import treeInterceptorHandler
import virtualBuffers
import NVDAObjects
import NVDAObjects.IAccessible
import winUser
import controlTypes
import win32clipboard
import win32con
import eventHandler
import braille
import watchdog
import appModuleHandler
#User functions
def getFocusObject():
"""
Gets the current object with focus.
@returns: the object with focus
@rtype: L{NVDAObjects.NVDAObject}
"""
return globalVars.focusObject
def getForegroundObject():
"""Gets the current foreground object.
@returns: the current foreground object
@rtype: L{NVDAObjects.NVDAObject}
"""
return globalVars.foregroundObject
def setForegroundObject(obj):
"""Stores the given object as the current foreground object. (Note: it does not physically change the operating system foreground window, but only allows NVDA to keep track of what it is).
@param obj: the object that will be stored as the current foreground object
@type obj: NVDAObjects.NVDAObject
"""
if not isinstance(obj,NVDAObjects.NVDAObject):
return False
globalVars.foregroundObject=obj
return True
def setFocusObject(obj):
"""Stores an object as the current focus object. (Note: this does not physically change the window with focus in the operating system, but allows NVDA to keep track of the correct object).
Before overriding the last object, this function calls event_loseFocus on the object to notify it that it is loosing focus.
@param obj: the object that will be stored as the focus object
@type obj: NVDAObjects.NVDAObject
"""
if not isinstance(obj,NVDAObjects.NVDAObject):
return False
if globalVars.focusObject:
eventHandler.executeEvent("loseFocus",globalVars.focusObject)
oldFocusLine=globalVars.focusAncestors
#add the old focus to the old focus ancestors, but only if its not None (is none at NVDA initialization)
if globalVars.focusObject:
oldFocusLine.append(globalVars.focusObject)
oldAppModules=[o.appModule for o in oldFocusLine if o and o.appModule]
appModuleHandler.cleanup()
ancestors=[]
tempObj=obj
matchedOld=False
focusDifferenceLevel=0
oldFocusLineLength=len(oldFocusLine)
# Starting from the focus, move up the ancestor chain.
safetyCount=0
while tempObj:
if safetyCount<100:
safetyCount+=1
else:
try:
log.error("Never ending focus ancestry: last object: %s, %s, window class %s, application name %s"%(tempObj.name,controlTypes.roleLabels[tempObj.role],tempObj.windowClassName,tempObj.appModule.appName))
except:
pass
tempObj=getDesktopObject()
# Scan backwards through the old ancestors looking for a match.
for index in xrange(oldFocusLineLength-1,-1,-1):
watchdog.alive()
if tempObj==oldFocusLine[index]:
# Match! The old and new focus ancestors converge at this point.
# Copy the old ancestors up to and including this object.
origAncestors=oldFocusLine[0:index+1]
#make sure to cache the last old ancestor as a parent on the first new ancestor so as not to leave a broken parent cache
if ancestors and origAncestors:
ancestors[0].container=origAncestors[-1]
origAncestors.extend(ancestors)
ancestors=origAncestors
focusDifferenceLevel=index+1
# We don't need to process any more in either this loop or the outer loop; we have all of the ancestors.
matchedOld=True
break
if matchedOld:
break
# We're moving backwards along the ancestor chain, so add this to the start of the list.
ancestors.insert(0,tempObj)
container=tempObj.container
tempObj.container=container # Cache the parent.
tempObj=container
#Remove the final new ancestor as this will be the new focus object
del ancestors[-1]
# #5467: Ensure that the appModule of the real focus is included in the newAppModule list for profile switching
# Rather than an original focus ancestor which happened to match the new focus.
newAppModules=[o.appModule for o in ancestors if o and o.appModule]
if obj.appModule:
newAppModules.append(obj.appModule)
try:
treeInterceptorHandler.cleanup()
except watchdog.CallCancelled:
pass
treeInterceptorObject=None
o=None
watchdog.alive()
for o in ancestors[focusDifferenceLevel:]+[obj]:
try:
treeInterceptorObject=treeInterceptorHandler.update(o)
except:
log.exception("Error updating tree interceptor")
#Always make sure that the focus object's treeInterceptor is forced to either the found treeInterceptor (if its in it) or to None
#This is to make sure that the treeInterceptor does not have to be looked up, which can cause problems for winInputHook
if obj is o or obj in treeInterceptorObject:
obj.treeInterceptor=treeInterceptorObject
else:
obj.treeInterceptor=None
# #3804: handleAppSwitch should be called as late as possible,
# as triggers must not be out of sync with global focus variables.
# setFocusObject shouldn't fail earlier anyway, but it's best to be safe.
appModuleHandler.handleAppSwitch(oldAppModules,newAppModules)
# Set global focus variables.
globalVars.focusDifferenceLevel=focusDifferenceLevel
globalVars.focusObject=obj
globalVars.focusAncestors=ancestors
braille.invalidateCachedFocusAncestors(focusDifferenceLevel)
if config.conf["reviewCursor"]["followFocus"]:
setNavigatorObject(obj,isFocus=True)
return True
def getFocusDifferenceLevel():
return globalVars.focusDifferenceLevel
def getFocusAncestors():
return globalVars.focusAncestors
def getMouseObject():
"""Returns the object that is directly under the mouse"""
return globalVars.mouseObject
def setMouseObject(obj):
"""Tells NVDA to remember the given object as the object that is directly under the mouse"""
globalVars.mouseObject=obj
def getDesktopObject():
"""Get the desktop object"""
return globalVars.desktopObject
def setDesktopObject(obj):
"""Tells NVDA to remember the given object as the desktop object"""
globalVars.desktopObject=obj
def getReviewPosition():
"""Retreaves the current TextInfo instance representing the user's review position. If it is not set, it uses the user's set navigator object and creates a TextInfo from that.
"""
if globalVars.reviewPosition:
return globalVars.reviewPosition
else:
obj=globalVars.navigatorObject
globalVars.reviewPosition,globalVars.reviewPositionObj=review.getPositionForCurrentMode(obj)
return globalVars.reviewPosition
def setReviewPosition(reviewPosition,clearNavigatorObject=True):
"""Sets a TextInfo instance as the review position. if clearNavigatorObject is true, It sets the current navigator object to None so that the next time the navigator object is asked for it fetches it from the review position.
"""
globalVars.reviewPosition=reviewPosition.copy()
globalVars.reviewPositionObj=reviewPosition.obj
if clearNavigatorObject: globalVars.navigatorObject=None
braille.handler.handleReviewMove()
def getNavigatorObject():
"""Gets the current navigator object. Navigator objects can be used to navigate around the operating system (with the number pad) with out moving the focus. If the navigator object is not set, it fetches it from the review position.
@returns: the current navigator object
@rtype: L{NVDAObjects.NVDAObject}
"""
if globalVars.navigatorObject:
return globalVars.navigatorObject
else:
if review.getCurrentMode()=='object':
obj=globalVars.reviewPosition.obj
else:
try:
obj=globalVars.reviewPosition.NVDAObjectAtStart
except (NotImplementedError,LookupError):
obj=globalVars.reviewPosition.obj
globalVars.navigatorObject=getattr(obj,'rootNVDAObject',None) or obj
return globalVars.navigatorObject
def setNavigatorObject(obj,isFocus=False):
"""Sets an object to be the current navigator object. Navigator objects can be used to navigate around the operating system (with the number pad) with out moving the focus. It also sets the current review position to None so that next time the review position is asked for, it is created from the navigator object.
@param obj: the object that will be set as the current navigator object
@type obj: NVDAObjects.NVDAObject
@param isFocus: true if the navigator object was set due to a focus change.
@type isFocus: bool
"""
if not isinstance(obj,NVDAObjects.NVDAObject):
return False
globalVars.navigatorObject=obj
oldPos=globalVars.reviewPosition
oldPosObj=globalVars.reviewPositionObj
globalVars.reviewPosition=None
globalVars.reviewPositionObj=None
reviewMode=review.getCurrentMode()
# #3320: If in document review yet there is no document to review the mode should be forced to object.
if reviewMode=='document' and (not isinstance(obj.treeInterceptor,treeInterceptorHandler.DocumentTreeInterceptor) or not obj.treeInterceptor.isReady or obj.treeInterceptor.passThrough):
review.setCurrentMode('object',False)
elif isinstance(obj.treeInterceptor,treeInterceptorHandler.DocumentTreeInterceptor) and obj.treeInterceptor.isReady and not obj.treeInterceptor.passThrough:
if reviewMode=='object':
review.setCurrentMode('document',False)
if isFocus:
globalVars.reviewPosition=obj.treeInterceptor.makeTextInfo(textInfos.POSITION_CARET)
globalVars.reviewPositionObj=globalVars.reviewPosition
eventHandler.executeEvent("becomeNavigatorObject",obj)
def isTypingProtected():
"""Checks to see if key echo should be suppressed because the focus is currently on an object that has its protected state set.
@returns: True if it should be suppressed, False otherwise.
@rtype: boolean
"""
focusObject=getFocusObject()
if focusObject and (controlTypes.STATE_PROTECTED in focusObject.states or focusObject.role==controlTypes.ROLE_PASSWORDEDIT):
return True
else:
return False
def createStateList(states):
"""Breaks down the given integer in to a list of numbers that are 2 to the power of their position."""
return [x for x in [1<<y for y in xrange(32)] if x&states]
def moveMouseToNVDAObject(obj):
"""Moves the mouse to the given NVDA object's position"""
location=obj.location
if location and (len(location)==4):
(left,top,width,height)=location
x=(left+left+width)/2
y=(top+top+height)/2
winUser.setCursorPos(x,y)
def processPendingEvents(processEventQueue=True):
# Import late to avoid circular import.
import IAccessibleHandler
import JABHandler
import wx
import queueHandler
watchdog.alive()
wx.Yield()
JABHandler.pumpAll()
IAccessibleHandler.pumpAll()
import baseObject
baseObject.AutoPropertyObject.invalidateCaches()
if processEventQueue:
queueHandler.flushQueue(queueHandler.eventQueue)
def copyToClip(text):
"""Copies the given text to the windows clipboard.
@returns: True if it succeeds, False otherwise.
@rtype: boolean
@param text: the text which will be copied to the clipboard
@type text: string
"""
if isinstance(text,basestring) and len(text)>0 and not text.isspace():
try:
win32clipboard.OpenClipboard()
except win32clipboard.error:
return False
try:
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(win32con.CF_UNICODETEXT, text)
finally:
win32clipboard.CloseClipboard()
win32clipboard.OpenClipboard() # there seems to be a bug so to retrieve unicode text we have to reopen the clipboard
try:
got = win32clipboard.GetClipboardData(win32con.CF_UNICODETEXT)
finally:
win32clipboard.CloseClipboard()
if got == text:
return True
return False
def getClipData():
"""Receives text from the windows clipboard.
@returns: Clipboard text
@rtype: string
"""
text = ""
win32clipboard.OpenClipboard()
try:
text = win32clipboard.GetClipboardData(win32con.CF_UNICODETEXT)
finally:
win32clipboard.CloseClipboard()
return text
def getStatusBar():
"""Obtain the status bar for the current foreground object.
@return: The status bar object or C{None} if no status bar was found.
@rtype: L{NVDAObjects.NVDAObject}
"""
# The status bar is usually at the bottom of the screen.
# Therefore, get the object at the bottom left of the foreground object using screen coordinates.
foreground = getForegroundObject()
location=foreground.location
if not location:
return None
left, top, width, height = location
bottom = top + height - 1
obj = getDesktopObject().objectFromPoint(left, bottom)
# We may have landed in a child of the status bar, so search the ancestry for a status bar.
while obj and not obj.role == controlTypes.ROLE_STATUSBAR:
obj = obj.parent
return obj
def getStatusBarText(obj):
"""Get the text from a status bar.
This includes the name of the status bar and the names and values of all of its children.
@param obj: The status bar.
@type obj: L{NVDAObjects.NVDAObject}
@return: The status bar text.
@rtype: str
"""
text = obj.name or ""
if text:
text += " "
return text + " ".join(chunk for child in obj.children for chunk in (child.name, child.value) if chunk and isinstance(chunk, basestring) and not chunk.isspace())
def filterFileName(name):
"""Replaces invalid characters in a given string to make a windows compatible file name.
@param name: The file name to filter.
@type name: str
@returns: The filtered file name.
@rtype: str
"""
invalidChars=':?*\|<>/"'
for c in invalidChars:
name=name.replace(c,'_')
return name
def getCaretObject():
"""Gets the object which contains the caret.
This is normally the focus object.
However, if the focus object has a tree interceptor which is not in focus mode,
the tree interceptor will be returned.
@return: The object containing the caret.
@rtype: L{baseObject.ScriptableObject}
"""
obj = getFocusObject()
ti = obj.treeInterceptor
if isinstance(ti,treeInterceptorHandler.DocumentTreeInterceptor) and ti.isReady and not ti.passThrough:
return ti
return obj
| 1 | 20,304 | Comma police. :) Also, the docstring needs updating. | nvaccess-nvda | py |
@@ -51,6 +51,7 @@ type driver struct {
volume.QuiesceDriver
volume.CredsDriver
volume.CloudBackupDriver
+ volume.CloudMigrateDriver
kv kvdb.Kvdb
thisCluster cluster.Cluster
} | 1 | /*
Package fake provides an in-memory fake driver implementation
Copyright 2018 Portworx
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.
*/
package fake
import (
"encoding/json"
"fmt"
"time"
"github.com/sirupsen/logrus"
"strings"
"github.com/libopenstorage/openstorage/api"
"github.com/libopenstorage/openstorage/cluster"
"github.com/libopenstorage/openstorage/volume"
"github.com/libopenstorage/openstorage/volume/drivers/common"
"github.com/pborman/uuid"
"github.com/portworx/kvdb"
"github.com/portworx/kvdb/mem"
)
const (
Name = "fake"
credsKeyPrefix = "/fake/credentials"
backupsKeyPrefix = "/fake/backups"
restoresKeyPrefix = "/fake/restores"
schedPrefix = "/fake/schedules"
Type = api.DriverType_DRIVER_TYPE_BLOCK
)
// Implements the open storage volume interface.
type driver struct {
volume.IODriver
volume.StoreEnumerator
volume.StatsDriver
volume.QuiesceDriver
volume.CredsDriver
volume.CloudBackupDriver
kv kvdb.Kvdb
thisCluster cluster.Cluster
}
type fakeCred struct {
Id string
Params map[string]string
}
type fakeBackups struct {
Spec api.VolumeSpec
Info api.CloudBackupInfo
Status api.CloudBackupStatus
ClusterId string
}
type fakeSchedules struct {
Id string
Info api.CloudBackupScheduleInfo
}
func Init(params map[string]string) (volume.VolumeDriver, error) {
return new(params)
}
func new(params map[string]string) (*driver, error) {
// This instance of the KVDB is Always in memory and created for each instance of the fake driver
// It is not necessary to run a single instance, and it helps tests create a new kvdb on each test
kv, err := kvdb.New(mem.Name, "fake_test", []string{}, nil, logrus.Panicf)
if err != nil {
return nil, err
}
inst := &driver{
IODriver: volume.IONotSupported,
StoreEnumerator: common.NewDefaultStoreEnumerator(Name, kv),
StatsDriver: volume.StatsNotSupported,
QuiesceDriver: volume.QuiesceNotSupported,
kv: kv,
}
inst.thisCluster, err = cluster.Inst()
if err != nil {
return nil, err
}
volumeInfo, err := inst.StoreEnumerator.Enumerate(&api.VolumeLocator{}, nil)
if err == nil {
for _, info := range volumeInfo {
if info.Status == api.VolumeStatus_VOLUME_STATUS_NONE {
info.Status = api.VolumeStatus_VOLUME_STATUS_UP
inst.UpdateVol(info)
}
}
}
logrus.Println("Fake driver initialized")
return inst, nil
}
func (d *driver) Name() string {
return Name
}
func (d *driver) Type() api.DriverType {
return Type
}
// Status diagnostic information
func (d *driver) Status() [][2]string {
return [][2]string{}
}
//
// These functions below implement the volume driver interface.
//
func (d *driver) Create(
locator *api.VolumeLocator,
source *api.Source,
spec *api.VolumeSpec) (string, error) {
if spec.Size == 0 {
return "", fmt.Errorf("Volume size cannot be zero")
}
volumeID := strings.TrimSuffix(uuid.New(), "\n")
if _, err := d.GetVol(volumeID); err == nil {
return "", fmt.Errorf("volume with that id already exists")
}
// snapshot passes nil volumelabels
if locator.VolumeLabels == nil {
locator.VolumeLabels = make(map[string]string)
}
v := common.NewVolume(
volumeID,
api.FSType_FS_TYPE_XFS,
locator,
source,
spec,
)
if err := d.CreateVol(v); err != nil {
return "", err
}
return v.Id, nil
}
func (d *driver) Delete(volumeID string) error {
_, err := d.GetVol(volumeID)
if err != nil {
logrus.Println(err)
return err
}
err = d.DeleteVol(volumeID)
if err != nil {
logrus.Println(err)
return err
}
return nil
}
func (d *driver) MountedAt(mountpath string) string {
return ""
}
func (d *driver) Mount(volumeID string, mountpath string, options map[string]string) error {
v, err := d.GetVol(volumeID)
if err != nil {
logrus.Println(err)
return err
}
v.AttachPath = append(v.AttachPath, mountpath)
return d.UpdateVol(v)
}
func (d *driver) Unmount(volumeID string, mountpath string, options map[string]string) error {
v, err := d.GetVol(volumeID)
if err != nil {
return err
}
if len(v.AttachPath) == 0 {
return fmt.Errorf("Device %v not mounted", volumeID)
}
v.AttachPath = nil
return d.UpdateVol(v)
}
func (d *driver) Snapshot(volumeID string, readonly bool, locator *api.VolumeLocator) (string, error) {
volIDs := []string{volumeID}
vols, err := d.Inspect(volIDs)
if err != nil {
return "", nil
}
source := &api.Source{Parent: volumeID}
logrus.Infof("Creating snap vol name: %s", locator.Name)
newVolumeID, err := d.Create(locator, source, vols[0].Spec)
if err != nil {
return "", nil
}
return newVolumeID, nil
}
func (d *driver) Restore(volumeID string, snapID string) error {
if _, err := d.Inspect([]string{volumeID, snapID}); err != nil {
return err
}
return nil
}
func (d *driver) SnapshotGroup(groupID string, labels map[string]string) (*api.GroupSnapCreateResponse, error) {
// We can return something here.
return nil, volume.ErrNotSupported
}
func (d *driver) Attach(volumeID string, attachOptions map[string]string) (string, error) {
return "/dev/fake/" + volumeID, nil
}
func (d *driver) Detach(volumeID string, options map[string]string) error {
return nil
}
func (d *driver) Set(volumeID string, locator *api.VolumeLocator, spec *api.VolumeSpec) error {
if spec != nil {
return volume.ErrNotSupported
}
v, err := d.GetVol(volumeID)
if err != nil {
return err
}
if locator != nil {
v.Locator = locator
}
return d.UpdateVol(v)
}
func (d *driver) Shutdown() {}
func (d *driver) CredsCreate(
params map[string]string,
) (string, error) {
id := uuid.New()
_, err := d.kv.Put(credsKeyPrefix+"/"+id, &fakeCred{
Id: id,
Params: params,
}, 0)
if err != nil {
return "", err
}
return id, nil
}
func (d *driver) CredsDelete(
uuid string,
) error {
d.kv.Delete(credsKeyPrefix + "/" + uuid)
return nil
}
func (d *driver) CredsEnumerate() (map[string]interface{}, error) {
kvp, err := d.kv.Enumerate(credsKeyPrefix)
if err != nil {
return nil, err
}
creds := make(map[string]interface{}, len(kvp))
for _, v := range kvp {
elem := &fakeCred{}
if err := json.Unmarshal(v.Value, elem); err != nil {
return nil, err
}
creds[elem.Id] = elem.Params
}
return creds, nil
}
func (d *driver) CredsValidate(uuid string) error {
// All we can do here is just to check if it exists
_, err := d.kv.Get(credsKeyPrefix + "/" + uuid)
if err != nil {
return fmt.Errorf("Credential id %s not found", uuid)
}
return nil
}
// CloudBackupCreate uploads snapshot of a volume to the cloud
func (d *driver) CloudBackupCreate(input *api.CloudBackupCreateRequest) error {
_, err := d.cloudBackupCreate(input)
return err
}
// cloudBackupCreate uploads snapshot of a volume to the cloud and returns the
// backup id
func (d *driver) cloudBackupCreate(input *api.CloudBackupCreateRequest) (string, error) {
// Confirm credential id
if err := d.CredsValidate(input.CredentialUUID); err != nil {
return "", err
}
// Get volume info
vols, err := d.Inspect([]string{input.VolumeID})
if err != nil {
return "", fmt.Errorf("Volume id not found")
}
if len(vols) < 1 {
return "", fmt.Errorf("Internal error. Volume found but no data returned")
}
vol := vols[0]
if vol.GetSpec() == nil {
return "", fmt.Errorf("Internal error. Volume has no specificiation")
}
// Save cloud backup
id := uuid.New()
clusterInfo, err := d.thisCluster.Enumerate()
if err != nil {
return "", err
}
_, err = d.kv.Put(backupsKeyPrefix+"/"+id, &fakeBackups{
Spec: *vol.GetSpec(),
ClusterId: clusterInfo.Id,
Status: api.CloudBackupStatus{
OpType: api.CloudBackupOp,
Status: api.CloudBackupStatusDone,
BytesDone: vol.GetSpec().GetSize(),
StartTime: time.Now(),
CompletedTime: time.Now().Local().Add(1 * time.Second),
NodeID: clusterInfo.NodeId,
},
Info: api.CloudBackupInfo{
ID: id,
SrcVolumeID: input.VolumeID,
SrcVolumeName: vol.GetLocator().GetName(),
Timestamp: time.Now(),
Metadata: map[string]string{
"fake": "backup",
},
Status: string(api.CloudBackupStatusDone),
},
}, 0)
if err != nil {
return "", err
}
return id, nil
}
// CloudBackupRestore downloads a cloud backup and restores it to a volume
func (d *driver) CloudBackupRestore(
input *api.CloudBackupRestoreRequest,
) (*api.CloudBackupRestoreResponse, error) {
// Confirm credential id
if err := d.CredsValidate(input.CredentialUUID); err != nil {
return nil, err
}
// Get the cloud data
var backup *fakeBackups
_, err := d.kv.GetVal(backupsKeyPrefix+"/"+input.ID, &backup)
if err != nil {
return nil, err
}
volid, err := d.Create(&api.VolumeLocator{Name: input.RestoreVolumeName}, &api.Source{}, &backup.Spec)
if err != nil {
return nil, err
}
vols, err := d.Inspect([]string{volid})
if err != nil {
return nil, fmt.Errorf("Volume id not found")
}
if len(vols) < 1 {
return nil, fmt.Errorf("Internal error. Volume found but no data returned")
}
vol := vols[0]
if vol.GetSpec() == nil {
return nil, fmt.Errorf("Internal error. Volume has no specificiation")
}
id := uuid.New()
clusterInfo, err := d.thisCluster.Enumerate()
if err != nil {
return nil, err
}
_, err = d.kv.Put(restoresKeyPrefix+"/"+id, &fakeBackups{
Spec: *vol.GetSpec(),
ClusterId: clusterInfo.Id,
Status: api.CloudBackupStatus{
OpType: api.CloudRestoreOp,
Status: api.CloudBackupStatusDone,
BytesDone: vol.GetSpec().GetSize(),
StartTime: time.Now(),
CompletedTime: time.Now().Local().Add(1 * time.Second),
NodeID: clusterInfo.NodeId,
},
Info: api.CloudBackupInfo{
ID: id,
SrcVolumeID: backup.Info.SrcVolumeID,
SrcVolumeName: backup.Info.SrcVolumeName,
Timestamp: time.Now(),
Metadata: map[string]string{
"fake": "restore",
},
Status: string(api.CloudBackupStatusDone),
},
}, 0)
if err != nil {
return nil, err
}
return &api.CloudBackupRestoreResponse{
RestoreVolumeID: volid,
}, nil
}
// CloudBackupDelete deletes the specified backup in cloud
func (d *driver) CloudBackupDelete(input *api.CloudBackupDeleteRequest) error {
// Confirm credential id
if err := d.CredsValidate(input.CredentialUUID); err != nil {
return err
}
d.kv.Delete(backupsKeyPrefix + "/" + input.ID)
return nil
}
// CloudBackupEnumerate enumerates the backups for a given cluster/credential/volumeID
func (d *driver) CloudBackupEnumerate(input *api.CloudBackupEnumerateRequest) (*api.CloudBackupEnumerateResponse, error) {
// Confirm credential id
if err := d.CredsValidate(input.CredentialUUID); err != nil {
return nil, err
}
// Get volume info
if len(input.SrcVolumeID) != 0 {
vols, err := d.Inspect([]string{input.SrcVolumeID})
if err != nil {
return nil, fmt.Errorf("Volume id not found")
}
if len(vols) < 1 {
return nil, fmt.Errorf("Internal error. Volume found but no data returned")
}
vol := vols[0]
if vol.GetSpec() == nil {
return nil, fmt.Errorf("Internal error. Volume has no specificiation")
}
}
backups := make([]api.CloudBackupInfo, 0)
kvp, err := d.kv.Enumerate(backupsKeyPrefix)
if err != nil {
return nil, err
}
for _, v := range kvp {
elem := &fakeBackups{}
if err := json.Unmarshal(v.Value, elem); err != nil {
return nil, err
}
if len(input.SrcVolumeID) == 0 && len(input.ClusterID) == 0 {
backups = append(backups, elem.Info)
} else if input.SrcVolumeID == elem.Info.SrcVolumeID {
backups = append(backups, elem.Info)
} else if input.ClusterID == elem.ClusterId {
backups = append(backups, elem.Info)
}
}
return &api.CloudBackupEnumerateResponse{
Backups: backups,
}, nil
}
// CloudBackupDelete deletes all the backups for a given volume in cloud
func (d *driver) CloudBackupDeleteAll(input *api.CloudBackupDeleteAllRequest) error {
// Confirm credential id
if err := d.CredsValidate(input.CredentialUUID); err != nil {
return err
}
// Get volume info
if len(input.SrcVolumeID) != 0 {
vols, err := d.Inspect([]string{input.SrcVolumeID})
if err != nil {
return fmt.Errorf("Volume id not found")
}
if len(vols) < 1 {
return fmt.Errorf("Internal error. Volume found but no data returned")
}
vol := vols[0]
if vol.GetSpec() == nil {
return fmt.Errorf("Internal error. Volume has no specificiation")
}
}
kvp, err := d.kv.Enumerate(backupsKeyPrefix)
if err != nil {
return err
}
for _, v := range kvp {
elem := &fakeBackups{}
if err := json.Unmarshal(v.Value, elem); err != nil {
return err
}
if len(input.SrcVolumeID) == 0 && len(input.ClusterID) == 0 {
d.kv.Delete(backupsKeyPrefix + "/" + elem.Info.ID)
} else if input.SrcVolumeID == elem.Info.SrcVolumeID {
d.kv.Delete(backupsKeyPrefix + "/" + elem.Info.ID)
} else if input.ClusterID == elem.ClusterId {
d.kv.Delete(backupsKeyPrefix + "/" + elem.Info.ID)
}
}
return nil
}
// CloudBackupStatus indicates the most recent status of backup/restores
func (d *driver) CloudBackupStatus(input *api.CloudBackupStatusRequest) (*api.CloudBackupStatusResponse, error) {
clusterInfo, err := d.thisCluster.Enumerate()
if err != nil {
return nil, fmt.Errorf("Failed to get cluster information: %v", err)
}
statuses := make(map[string]api.CloudBackupStatus)
backups, err := d.kv.Enumerate(backupsKeyPrefix)
if err != nil {
return nil, err
}
restores, err := d.kv.Enumerate(restoresKeyPrefix)
if err != nil {
return nil, err
}
kvps := append(backups, restores...)
for _, v := range kvps {
elem := &fakeBackups{}
if err := json.Unmarshal(v.Value, elem); err != nil {
return nil, err
}
if len(input.SrcVolumeID) == 0 && !input.Local {
statuses[elem.Info.ID] = elem.Status
} else if input.SrcVolumeID == elem.Info.SrcVolumeID {
statuses[elem.Info.ID] = elem.Status
} else if input.Local && clusterInfo.NodeId == elem.Status.NodeID {
statuses[elem.Info.ID] = elem.Status
}
}
return &api.CloudBackupStatusResponse{
Statuses: statuses,
}, nil
}
// CloudBackupCatalog displays listing of backup content
func (d *driver) CloudBackupCatalog(input *api.CloudBackupCatalogRequest) (*api.CloudBackupCatalogResponse, error) {
// Confirm credential id
if err := d.CredsValidate(input.CredentialUUID); err != nil {
return nil, err
}
// Get the cloud data
var backup *fakeBackups
_, err := d.kv.GetVal(backupsKeyPrefix+"/"+input.ID, &backup)
if err != nil {
return nil, err
}
return &api.CloudBackupCatalogResponse{
Contents: []string{
"/one/two/three.gz",
"/fake.img",
},
}, nil
}
// CloudBackupHistory displays past backup/restore operations on a volume
func (d *driver) CloudBackupHistory(input *api.CloudBackupHistoryRequest) (*api.CloudBackupHistoryResponse, error) {
resp, err := d.CloudBackupStatus(&api.CloudBackupStatusRequest{
SrcVolumeID: input.SrcVolumeID,
})
if err != nil {
return nil, err
}
items := make([]api.CloudBackupHistoryItem, len(resp.Statuses))
i := 0
for id, v := range resp.Statuses {
var elem *fakeBackups
var err error
if v.OpType == api.CloudBackupOp {
_, err = d.kv.GetVal(backupsKeyPrefix+"/"+id, &elem)
} else {
_, err = d.kv.GetVal(restoresKeyPrefix+"/"+id, &elem)
}
if err != nil {
return nil, err
}
items[i] = api.CloudBackupHistoryItem{
SrcVolumeID: elem.Info.SrcVolumeID,
Timestamp: elem.Status.CompletedTime,
Status: string(elem.Status.Status),
}
i++
}
return &api.CloudBackupHistoryResponse{
HistoryList: items,
}, nil
}
// CloudBackupStateChange allows a current backup state transisions(pause/resume/stop)
func (d *driver) CloudBackupStateChange(input *api.CloudBackupStateChangeRequest) error {
if len(input.SrcVolumeID) == 0 {
return fmt.Errorf("Source volume id must be provided")
}
resp, err := d.CloudBackupStatus(&api.CloudBackupStatusRequest{
SrcVolumeID: input.SrcVolumeID,
})
if err != nil {
return err
}
for id, status := range resp.Statuses {
save := false
if status.Status == api.CloudBackupStatusPaused {
save = true
if input.RequestedState == api.CloudBackupRequestedStateResume {
status.Status = api.CloudBackupStatusActive
} else if input.RequestedState == api.CloudBackupRequestedStateStop {
status.Status = api.CloudBackupStatusStopped
}
} else if status.Status == api.CloudBackupStatusActive {
save = true
if input.RequestedState == api.CloudBackupRequestedStatePause {
status.Status = api.CloudBackupStatusPaused
} else if input.RequestedState == api.CloudBackupRequestedStateStop {
status.Status = api.CloudBackupStatusStopped
}
}
if save {
var prefix string
if status.OpType == api.CloudBackupOp {
prefix = backupsKeyPrefix
} else {
prefix = restoresKeyPrefix
}
var elem *fakeBackups
_, err := d.kv.GetVal(prefix+"/"+id, &elem)
if err != nil {
return err
}
elem.Status = status
_, err = d.kv.Update(prefix+"/"+id, elem, 0)
if err != nil {
return err
}
}
}
return nil
}
// CloudBackupSchedCreate creates a schedule backup volume to cloud
func (d *driver) CloudBackupSchedCreate(
input *api.CloudBackupSchedCreateRequest,
) (*api.CloudBackupSchedCreateResponse, error) {
// Confirm credential id
if err := d.CredsValidate(input.CredentialUUID); err != nil {
return nil, err
}
// Check volume
vols, err := d.Inspect([]string{input.SrcVolumeID})
if err != nil {
return nil, fmt.Errorf("Volume id not found")
}
if len(vols) < 1 {
return nil, fmt.Errorf("Internal error. Volume found but no data returned")
}
vol := vols[0]
if vol.GetSpec() == nil {
return nil, fmt.Errorf("Internal error. Volume has no specificiation")
}
id := uuid.New()
_, err = d.kv.Put(schedPrefix+"/"+id, &fakeSchedules{
Id: id,
Info: api.CloudBackupScheduleInfo{
SrcVolumeID: input.SrcVolumeID,
CredentialUUID: input.CredentialUUID,
Schedule: input.Schedule,
MaxBackups: input.MaxBackups,
},
}, 0)
if err != nil {
return nil, err
}
return &api.CloudBackupSchedCreateResponse{
UUID: id,
}, nil
}
// CloudBackupSchedDelete delete a volume backup schedule to cloud
func (d *driver) CloudBackupSchedDelete(input *api.CloudBackupSchedDeleteRequest) error {
d.kv.Delete(schedPrefix + "/" + input.UUID)
return nil
}
// CloudBackupSchedEnumerate enumerates the configured backup schedules in the cluster
func (d *driver) CloudBackupSchedEnumerate() (*api.CloudBackupSchedEnumerateResponse, error) {
kvp, err := d.kv.Enumerate(schedPrefix)
if err != nil {
return nil, err
}
schedules := make(map[string]api.CloudBackupScheduleInfo, len(kvp))
for _, v := range kvp {
elem := &fakeSchedules{}
if err := json.Unmarshal(v.Value, elem); err != nil {
return nil, err
}
schedules[elem.Id] = elem.Info
}
return &api.CloudBackupSchedEnumerateResponse{
Schedules: schedules,
}, nil
}
| 1 | 7,061 | Implement an in-memory implementation of this in the fake driver. | libopenstorage-openstorage | go |
@@ -0,0 +1,13 @@
+require 'spec_helper'
+
+describe 'shows/_show.html.erb' do
+ it 'includes published episodes count' do
+ show = create(:show)
+ create_list(:video, 2, :published, watchable: show)
+ create(:video, watchable: show)
+
+ render 'shows/show', show: show
+
+ expect(rendered).to include('2 episodes')
+ end
+end | 1 | 1 | 9,355 | Same question as the other view spec regarding not actually saving records. | thoughtbot-upcase | rb |
|
@@ -269,9 +269,9 @@ namespace NLog.Config
factory.RegisterItemsFromAssembly(extensionAssembly);
success = true;
}
- catch (Exception)
+ catch (Exception ex)
{
- InternalLogger.Warn("Auto loading assembly file: {0} failed! Skipping this file.", extensionDll);
+ InternalLogger.Warn(ex, "Auto loading assembly file: {0} failed! Skipping this file.", extensionDll);
}
if (success)
{ | 1 | //
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.IO;
using System.Linq;
using NLog.Common;
namespace NLog.Config
{
using System;
using System.Collections.Generic;
using System.Reflection;
using NLog.Conditions;
using NLog.Filters;
using NLog.Internal;
using NLog.LayoutRenderers;
using NLog.Layouts;
using NLog.Targets;
using NLog.Time;
/// <summary>
/// Provides registration information for named items (targets, layouts, layout renderers, etc.) managed by NLog.
/// </summary>
public class ConfigurationItemFactory
{
private static ConfigurationItemFactory defaultInstance = null;
private readonly IList<object> allFactories;
private readonly Factory<Target, TargetAttribute> targets;
private readonly Factory<Filter, FilterAttribute> filters;
private readonly Factory<LayoutRenderer, LayoutRendererAttribute> layoutRenderers;
private readonly Factory<Layout, LayoutAttribute> layouts;
private readonly MethodFactory<ConditionMethodsAttribute, ConditionMethodAttribute> conditionMethods;
private readonly Factory<LayoutRenderer, AmbientPropertyAttribute> ambientProperties;
private readonly Factory<TimeSource, TimeSourceAttribute> timeSources;
/// <summary>
/// Initializes a new instance of the <see cref="ConfigurationItemFactory"/> class.
/// </summary>
/// <param name="assemblies">The assemblies to scan for named items.</param>
public ConfigurationItemFactory(params Assembly[] assemblies)
{
this.CreateInstance = FactoryHelper.CreateInstance;
this.targets = new Factory<Target, TargetAttribute>(this);
this.filters = new Factory<Filter, FilterAttribute>(this);
this.layoutRenderers = new Factory<LayoutRenderer, LayoutRendererAttribute>(this);
this.layouts = new Factory<Layout, LayoutAttribute>(this);
this.conditionMethods = new MethodFactory<ConditionMethodsAttribute, ConditionMethodAttribute>();
this.ambientProperties = new Factory<LayoutRenderer, AmbientPropertyAttribute>(this);
this.timeSources = new Factory<TimeSource, TimeSourceAttribute>(this);
this.allFactories = new List<object>
{
this.targets,
this.filters,
this.layoutRenderers,
this.layouts,
this.conditionMethods,
this.ambientProperties,
this.timeSources,
};
foreach (var asm in assemblies)
{
this.RegisterItemsFromAssembly(asm);
}
}
/// <summary>
/// Gets or sets default singleton instance of <see cref="ConfigurationItemFactory"/>.
/// </summary>
/// <remarks>
/// This property implements lazy instantiation so that the <see cref="ConfigurationItemFactory"/> is not built before
/// the internal logger is configured.
/// </remarks>
public static ConfigurationItemFactory Default
{
get
{
if (defaultInstance == null)
defaultInstance = BuildDefaultFactory();
return defaultInstance;
}
set { defaultInstance = value; }
}
/// <summary>
/// Gets or sets the creator delegate used to instantiate configuration objects.
/// </summary>
/// <remarks>
/// By overriding this property, one can enable dependency injection or interception for created objects.
/// </remarks>
public ConfigurationItemCreator CreateInstance { get; set; }
/// <summary>
/// Gets the <see cref="Target"/> factory.
/// </summary>
/// <value>The target factory.</value>
public INamedItemFactory<Target, Type> Targets
{
get { return this.targets; }
}
/// <summary>
/// Gets the <see cref="Filter"/> factory.
/// </summary>
/// <value>The filter factory.</value>
public INamedItemFactory<Filter, Type> Filters
{
get { return this.filters; }
}
/// <summary>
/// Gets the <see cref="LayoutRenderer"/> factory.
/// </summary>
/// <value>The layout renderer factory.</value>
public INamedItemFactory<LayoutRenderer, Type> LayoutRenderers
{
get { return this.layoutRenderers; }
}
/// <summary>
/// Gets the <see cref="LayoutRenderer"/> factory.
/// </summary>
/// <value>The layout factory.</value>
public INamedItemFactory<Layout, Type> Layouts
{
get { return this.layouts; }
}
/// <summary>
/// Gets the ambient property factory.
/// </summary>
/// <value>The ambient property factory.</value>
public INamedItemFactory<LayoutRenderer, Type> AmbientProperties
{
get { return this.ambientProperties; }
}
/// <summary>
/// Gets the time source factory.
/// </summary>
/// <value>The time source factory.</value>
public INamedItemFactory<TimeSource, Type> TimeSources
{
get { return this.timeSources; }
}
/// <summary>
/// Gets the condition method factory.
/// </summary>
/// <value>The condition method factory.</value>
public INamedItemFactory<MethodInfo, MethodInfo> ConditionMethods
{
get { return this.conditionMethods; }
}
/// <summary>
/// Registers named items from the assembly.
/// </summary>
/// <param name="assembly">The assembly.</param>
public void RegisterItemsFromAssembly(Assembly assembly)
{
this.RegisterItemsFromAssembly(assembly, string.Empty);
}
/// <summary>
/// Registers named items from the assembly.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <param name="itemNamePrefix">Item name prefix.</param>
public void RegisterItemsFromAssembly(Assembly assembly, string itemNamePrefix)
{
InternalLogger.Debug("ScanAssembly('{0}')", assembly.FullName);
var typesToScan = assembly.SafeGetTypes();
foreach (IFactory f in this.allFactories)
{
f.ScanTypes(typesToScan, itemNamePrefix);
}
}
/// <summary>
/// Clears the contents of all factories.
/// </summary>
public void Clear()
{
foreach (IFactory f in this.allFactories)
{
f.Clear();
}
}
/// <summary>
/// Registers the type.
/// </summary>
/// <param name="type">The type to register.</param>
/// <param name="itemNamePrefix">The item name prefix.</param>
public void RegisterType(Type type, string itemNamePrefix)
{
foreach (IFactory f in this.allFactories)
{
f.RegisterType(type, itemNamePrefix);
}
}
/// <summary>
/// Builds the default configuration item factory.
/// </summary>
/// <returns>Default factory.</returns>
private static ConfigurationItemFactory BuildDefaultFactory()
{
var nlogAssembly = typeof(ILogger).Assembly;
var factory = new ConfigurationItemFactory(nlogAssembly);
factory.RegisterExtendedItems();
#if !SILVERLIGHT
var assemblyLocation = Path.GetDirectoryName(new Uri(nlogAssembly.CodeBase).LocalPath);
if (assemblyLocation == null)
{
InternalLogger.Warn("No auto loading because Nlog.dll location is unknown");
return factory;
}
var extensionDlls = Directory.GetFiles(assemblyLocation, "NLog*.dll")
.Select(Path.GetFileName)
.Where(x => !x.Equals("NLog.dll", StringComparison.OrdinalIgnoreCase))
.Where(x => !x.Equals("NLog.UnitTests.dll", StringComparison.OrdinalIgnoreCase))
.Where(x => !x.Equals("NLog.Extended.dll", StringComparison.OrdinalIgnoreCase))
.Select(x => Path.Combine(assemblyLocation, x));
InternalLogger.Debug("Start auto loading, location: {0}", assemblyLocation);
foreach (var extensionDll in extensionDlls)
{
InternalLogger.Info("Auto loading assembly file: {0}", extensionDll);
var success = false;
try
{
var extensionAssembly = Assembly.LoadFrom(extensionDll);
InternalLogger.LogAssemblyVersion(extensionAssembly);
factory.RegisterItemsFromAssembly(extensionAssembly);
success = true;
}
catch (Exception)
{
InternalLogger.Warn("Auto loading assembly file: {0} failed! Skipping this file.", extensionDll);
}
if (success)
{
InternalLogger.Info("Auto loading assembly file: {0} succeeded!", extensionDll);
}
}
InternalLogger.Debug("Auto loading done");
#endif
return factory;
}
/// <summary>
/// Registers items in NLog.Extended.dll using late-bound types, so that we don't need a reference to NLog.Extended.dll.
/// </summary>
private void RegisterExtendedItems()
{
string suffix = typeof(ILogger).AssemblyQualifiedName;
string myAssemblyName = "NLog,";
string extendedAssemblyName = "NLog.Extended,";
int p = suffix.IndexOf(myAssemblyName, StringComparison.OrdinalIgnoreCase);
if (p >= 0)
{
suffix = ", " + extendedAssemblyName + suffix.Substring(p + myAssemblyName.Length);
// register types
string targetsNamespace = typeof(DebugTarget).Namespace;
this.targets.RegisterNamedType("AspNetTrace", targetsNamespace + ".AspNetTraceTarget" + suffix);
this.targets.RegisterNamedType("MSMQ", targetsNamespace + ".MessageQueueTarget" + suffix);
this.targets.RegisterNamedType("AspNetBufferingWrapper", targetsNamespace + ".Wrappers.AspNetBufferingTargetWrapper" + suffix);
// register layout renderers
string layoutRenderersNamespace = typeof(MessageLayoutRenderer).Namespace;
this.layoutRenderers.RegisterNamedType("appsetting", layoutRenderersNamespace + ".AppSettingLayoutRenderer" + suffix);
this.layoutRenderers.RegisterNamedType("aspnet-application", layoutRenderersNamespace + ".AspNetApplicationValueLayoutRenderer" + suffix);
this.layoutRenderers.RegisterNamedType("aspnet-request", layoutRenderersNamespace + ".AspNetRequestValueLayoutRenderer" + suffix);
this.layoutRenderers.RegisterNamedType("aspnet-sessionid", layoutRenderersNamespace + ".AspNetSessionIDLayoutRenderer" + suffix);
this.layoutRenderers.RegisterNamedType("aspnet-session", layoutRenderersNamespace + ".AspNetSessionValueLayoutRenderer" + suffix);
this.layoutRenderers.RegisterNamedType("aspnet-user-authtype", layoutRenderersNamespace + ".AspNetUserAuthTypeLayoutRenderer" + suffix);
this.layoutRenderers.RegisterNamedType("aspnet-user-identity", layoutRenderersNamespace + ".AspNetUserIdentityLayoutRenderer" + suffix);
}
}
}
}
| 1 | 12,465 | Rethrow for `MustBeRethrown()`-exceptions? | NLog-NLog | .cs |
@@ -43,11 +43,13 @@ class RandomSampler(BaseSampler):
Tensor or ndarray: sampled indices.
"""
assert len(gallery) >= num
-
is_tensor = isinstance(gallery, torch.Tensor)
if not is_tensor:
- gallery = torch.tensor(
- gallery, dtype=torch.long, device=torch.cuda.current_device())
+ if torch.cuda.is_available():
+ device = torch.cuda.current_device()
+ else:
+ device = 'cpu'
+ gallery = torch.tensor(gallery, dtype=torch.long, device=device)
perm = torch.randperm(gallery.numel(), device=gallery.device)[:num]
rand_inds = gallery[perm]
if not is_tensor: | 1 | import torch
from ..builder import BBOX_SAMPLERS
from .base_sampler import BaseSampler
@BBOX_SAMPLERS.register_module()
class RandomSampler(BaseSampler):
"""Random sampler.
Args:
num (int): Number of samples
pos_fraction (float): Fraction of positive samples
neg_pos_up (int, optional): Upper bound number of negative and
positive samples. Defaults to -1.
add_gt_as_proposals (bool, optional): Whether to add ground truth
boxes as proposals. Defaults to True.
"""
def __init__(self,
num,
pos_fraction,
neg_pos_ub=-1,
add_gt_as_proposals=True,
**kwargs):
from mmdet.core.bbox import demodata
super(RandomSampler, self).__init__(num, pos_fraction, neg_pos_ub,
add_gt_as_proposals)
self.rng = demodata.ensure_rng(kwargs.get('rng', None))
def random_choice(self, gallery, num):
"""Random select some elements from the gallery.
If `gallery` is a Tensor, the returned indices will be a Tensor;
If `gallery` is a ndarray or list, the returned indices will be a
ndarray.
Args:
gallery (Tensor | ndarray | list): indices pool.
num (int): expected sample num.
Returns:
Tensor or ndarray: sampled indices.
"""
assert len(gallery) >= num
is_tensor = isinstance(gallery, torch.Tensor)
if not is_tensor:
gallery = torch.tensor(
gallery, dtype=torch.long, device=torch.cuda.current_device())
perm = torch.randperm(gallery.numel(), device=gallery.device)[:num]
rand_inds = gallery[perm]
if not is_tensor:
rand_inds = rand_inds.cpu().numpy()
return rand_inds
def _sample_pos(self, assign_result, num_expected, **kwargs):
"""Randomly sample some positive samples."""
pos_inds = torch.nonzero(assign_result.gt_inds > 0, as_tuple=False)
if pos_inds.numel() != 0:
pos_inds = pos_inds.squeeze(1)
if pos_inds.numel() <= num_expected:
return pos_inds
else:
return self.random_choice(pos_inds, num_expected)
def _sample_neg(self, assign_result, num_expected, **kwargs):
"""Randomly sample some negative samples."""
neg_inds = torch.nonzero(assign_result.gt_inds == 0, as_tuple=False)
if neg_inds.numel() != 0:
neg_inds = neg_inds.squeeze(1)
if len(neg_inds) <= num_expected:
return neg_inds
else:
return self.random_choice(neg_inds, num_expected)
| 1 | 21,729 | May clean the unnecessary modification. | open-mmlab-mmdetection | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.