file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
show.go | package commands
import (
"bk/utils"
"github.com/urfave/cli"
"os"
"fmt"
"io/ioutil"
"strings"
)
func Show(c *cli.Context) error {
historyFileName, e := utils.HistoryFile()
historyFile, e := os.OpenFile(historyFileName, os.O_RDONLY, 0400)
defer historyFile.Close()
if e != nil |
bytes, e := ioutil.ReadAll(historyFile)
if e != nil {
return e
}
texts := string(bytes)
texts = strings.TrimRight(texts, "\n")
if len(texts) == 0 {
return nil
}
fmt.Println(texts)
return nil
}
| {
return e
} |
tests.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase, override_settings
from django.contrib.auth import get_user_model
import json
import responses
## responses:
def kong_login_success():
responses.add(
responses.POST,
'https://kong:8443/test/oauth2/token',
body=json.dumps({'refresh_token': 'rtoken', 'token_type': 'bearer', 'access_token': 'atoken', 'expires_in': 7200}),
status=200,
content_type='application/json'
)
class OAuthTestCase(TestCase):
def login(self, data):
return self.client.post('/oauth2/token/', json.dumps(data), content_type="application/json")
@override_settings(KONG_GATEWAY_URL='https://kong:8443')
@responses.activate
def setUp(self):
self.user = get_user_model().objects.create_user(username='admin', password='testtest1234')
data = {
"username": "admin",
"password": "testtest1234",
"client_id": "cliendid",
"client_secret": "secret"
}
kong_login_success()
self.result = self.login(data)
def test_is_ok(self):
assert self.result.status_code == 200
@responses.activate # assert no response is made
def | (self):
data = {
"username": "foo",
"password": "bar",
}
result = self.login(data)
assert result.status_code == 401
| test_invalid_login_returns_401 |
goarraylru.go | package goarraylru
type LRU struct {
Collisions uint
Buckets uint
Size uint
Wrap bool
Cache []*Node
Hash func(uint) uint
Evict func(index uint, value interface{})
Evictable bool
}
type LRUOpts struct {
Collisions *uint
BucketSize *uint
IndexedValues *bool
Evict *func(index uint, value interface{})
}
type Node struct {
Index *uint
Value interface{}
}
func (lru *LRU) Init(max uint, opts LRUOpts) {
if opts.Collisions != nil {
lru.Collisions = FactorOfTwo(*opts.Collisions)
} else if opts.BucketSize != nil {
lru.Collisions = FactorOfTwo(*opts.BucketSize)
} else {
lru.Collisions = FactorOfTwo(4)
}
lru.Buckets = FactorOf(max, lru.Collisions) / lru.Collisions
// Using 16bit hasing to bucket. As such the index must be <0xffff(65536).
for lru.Buckets > 65536 {
lru.Buckets >>= 1
lru.Collisions <<= 1
}
lru.Size = lru.Buckets * lru.Collisions
// If Indexed values doesn't exist default to false.
if opts.IndexedValues != nil {
lru.Wrap = !*opts.IndexedValues
} else {
lru.Wrap = true
}
lru.Cache = make([]*Node, lru.Size)
// The LRU Hash member is a function.
if lru.Buckets == 65536 {
lru.Hash = Crc16
} else {
lru.Hash = MaskedHash(lru.Buckets - 1)
}
if opts.Evict != nil {
lru.Evict = *opts.Evict
lru.Evictable = true
} else {
lru.Evictable = false
}
}
func (lru *LRU) Set(index uint, val interface{}) {
var pageStart, pageEnd, ptr uint
pageStart = lru.Collisions * lru.Hash(index)
pageEnd = pageStart + lru.Collisions
ptr = pageStart
var page *Node
page = nil
for ptr < pageEnd {
page = lru.Cache[ptr]
if page == nil {
// There is no existing version so store the new data.
if lru.Wrap {
page = &Node{&index, val}
} else {
page = &Node{nil, val}
}
Move(lru.Cache, pageStart, ptr, page)
return
}
if page.Index != nil {
if *page.Index == index {
page.Value = val
Move(lru.Cache, pageStart, ptr, page)
return
}
}
ptr++
}
// In this case the bucket is full so update the oldest element.
if lru.Wrap {
if lru.Evict != nil {
lru.Evict(*page.Index, page.Value)
}
page.Index = &index
page.Value = val
} else {
if lru.Evict != nil {
lru.Evict(0, page)
}
lru.Cache[ptr-1] = &Node{nil, val}
}
Move(lru.Cache, pageStart, ptr-1, page)
}
func (lru *LRU) Get(index uint) *Node {
var pageStart, pageEnd, ptr uint
pageStart = lru.Collisions * lru.Hash(index)
pageEnd = pageStart + lru.Collisions
ptr = pageStart
for ptr < pageEnd {
var page *Node
page = lru.Cache[ptr]
ptr++
if page == nil {
return nil
}
if page.Index == nil {
continue
}
if *page.Index != index {
continue
}
Move(lru.Cache, pageStart, ptr-1, page)
return page
}
return nil
}
func Move(list []*Node, index uint, itemIndex uint, item *Node) {
var indexBefore uint
for itemIndex > index {
indexBefore = itemIndex - 1
list[itemIndex] = list[indexBefore]
}
list[index] = item
}
func FactorOf(n, factor uint) uint {
n = FactorOfTwo(n)
for n&(factor-1) != 0 {
n <<= 1
}
return n
}
func FactorOfTwo(n uint) uint |
func MaskedHash(mask uint) func(uint) uint {
return func(n uint) uint {
return Crc16(n) & mask
}
}
| {
if n != 0 && (n&(n-1)) == 0 {
return n
}
var p uint
p = 1
for p < n {
p <<= 1
}
return p
} |
deployer.go | package deployer
import (
"fmt"
"reflect"
"github.com/rancher/norman/controller"
alertutil "github.com/rancher/rancher/pkg/controllers/user/alert/common"
"github.com/rancher/rancher/pkg/controllers/user/alert/manager"
"github.com/rancher/rancher/pkg/controllers/user/helm/common"
"github.com/rancher/rancher/pkg/monitoring"
monitorutil "github.com/rancher/rancher/pkg/monitoring"
"github.com/rancher/rancher/pkg/ref"
"github.com/rancher/rancher/pkg/settings"
appsv1beta2 "github.com/rancher/types/apis/apps/v1beta2"
"github.com/rancher/types/apis/core/v1"
mgmtv3 "github.com/rancher/types/apis/management.cattle.io/v3"
projectv3 "github.com/rancher/types/apis/project.cattle.io/v3"
rbacv1 "github.com/rancher/types/apis/rbac.authorization.k8s.io/v1"
"github.com/rancher/types/config"
"golang.org/x/sync/errgroup"
"gopkg.in/yaml.v2"
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/labels"
"k8s.io/apimachinery/pkg/runtime"
)
var (
creatorIDAnn = "field.cattle.io/creatorId"
systemProjectLabel = map[string]string{"authz.management.cattle.io/system-project": "true"}
)
type Deployer struct {
clusterName string
alertManager *manager.AlertManager
clusterAlertGroupLister mgmtv3.ClusterAlertGroupLister
projectAlertGroupLister mgmtv3.ProjectAlertGroupLister
notifierLister mgmtv3.NotifierLister
projectLister mgmtv3.ProjectLister
clusters mgmtv3.ClusterInterface
appDeployer *appDeployer
operaterDeployer *operaterDeployer
}
type appDeployer struct {
appsGetter projectv3.AppsGetter
namespaces v1.NamespaceInterface
secrets v1.SecretInterface
templateVersions mgmtv3.TemplateVersionInterface
statefulsets appsv1beta2.StatefulSetInterface
}
type operaterDeployer struct {
templateVersions mgmtv3.TemplateVersionInterface
projectsGetter mgmtv3.ProjectsGetter
appsGetter projectv3.AppsGetter
rbacs rbacv1.Interface
cores v1.Interface
apps appsv1beta2.Interface
}
func NewDeployer(cluster *config.UserContext, manager *manager.AlertManager) *Deployer {
appsgetter := cluster.Management.Project
ad := &appDeployer{
appsGetter: appsgetter,
namespaces: cluster.Core.Namespaces(metav1.NamespaceAll),
secrets: cluster.Core.Secrets(metav1.NamespaceAll),
templateVersions: cluster.Management.Management.TemplateVersions(metav1.NamespaceAll),
statefulsets: cluster.Apps.StatefulSets(metav1.NamespaceAll),
}
op := &operaterDeployer{
templateVersions: cluster.Management.Management.TemplateVersions(metav1.NamespaceAll),
projectsGetter: cluster.Management.Management,
appsGetter: appsgetter,
rbacs: cluster.RBAC,
cores: cluster.Core,
}
return &Deployer{
clusterName: cluster.ClusterName,
alertManager: manager,
clusterAlertGroupLister: cluster.Management.Management.ClusterAlertGroups(cluster.ClusterName).Controller().Lister(),
projectAlertGroupLister: cluster.Management.Management.ProjectAlertGroups(metav1.NamespaceAll).Controller().Lister(),
notifierLister: cluster.Management.Management.Notifiers(cluster.ClusterName).Controller().Lister(),
projectLister: cluster.Management.Management.Projects(cluster.ClusterName).Controller().Lister(),
clusters: cluster.Management.Management.Clusters(metav1.NamespaceAll),
appDeployer: ad,
operaterDeployer: op,
}
}
func (d *Deployer) ProjectGroupSync(key string, alert *mgmtv3.ProjectAlertGroup) (runtime.Object, error) {
return nil, d.sync()
}
func (d *Deployer) ClusterGroupSync(key string, alert *mgmtv3.ClusterAlertGroup) (runtime.Object, error) {
return nil, d.sync()
}
func (d *Deployer) ProjectRuleSync(key string, alert *mgmtv3.ProjectAlertRule) (runtime.Object, error) {
return nil, d.sync()
}
func (d *Deployer) ClusterRuleSync(key string, alert *mgmtv3.ClusterAlertRule) (runtime.Object, error) {
return nil, d.sync()
}
// //deploy or clean up resources(alertmanager deployment, service, namespace) required by alerting.
func (d *Deployer) sync() error {
appName, appTargetNamespace := monitorutil.ClusterAlertManagerInfo()
defaultSystemProjects, err := d.projectLister.List(metav1.NamespaceAll, labels.Set(systemProjectLabel).AsSelector())
if err != nil {
return fmt.Errorf("list system project failed, %v", err)
}
if len(defaultSystemProjects) == 0 {
return fmt.Errorf("get system project failed")
}
systemProject := defaultSystemProjects[0]
if systemProject == nil {
return fmt.Errorf("get system project failed")
}
systemProjectCreator := systemProject.Annotations[creatorIDAnn]
systemProjectID := ref.Ref(systemProject)
needDeploy, err := d.needDeploy()
if err != nil {
return fmt.Errorf("check alertmanager deployment failed, %v", err)
}
cluster, err := d.clusters.Get(d.clusterName, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("get cluster %s failed, %v", d.clusterName, err)
}
newCluster := cluster.DeepCopy()
newCluster.Spec.EnableClusterAlerting = needDeploy
if err = d.operaterDeployer.sync(newCluster); err != nil {
return err
}
if needDeploy {
if d.alertManager.IsDeploy, err = d.appDeployer.deploy(appName, appTargetNamespace, systemProjectID, systemProjectCreator); err != nil {
return fmt.Errorf("deploy alertmanager failed, %v", err)
}
if err = d.appDeployer.isDeploySuccess(newCluster, alertutil.GetAlertManagerDaemonsetName(appName), appTargetNamespace); err != nil {
return err
}
} else {
if d.alertManager.IsDeploy, err = d.appDeployer.cleanup(appName, appTargetNamespace, systemProjectID); err != nil {
return fmt.Errorf("clean up alertmanager failed, %v", err)
}
if mgmtv3.ClusterConditionAlertingEnabled.IsTrue(newCluster) {
mgmtv3.ClusterConditionAlertingEnabled.False(newCluster)
}
}
if !reflect.DeepEqual(cluster, newCluster) {
_, err = d.clusters.Update(newCluster)
if err != nil {
return fmt.Errorf("update cluster %v failed, %v", d.clusterName, err)
}
}
return nil
}
// //only deploy the alertmanager when notifier is configured and alert is using it.
func (d *Deployer) needDeploy() (bool, error) {
notifiers, err := d.notifierLister.List("", labels.NewSelector())
if err != nil {
return false, err
} | if len(notifiers) == 0 {
return false, err
}
clusterAlerts, err := d.clusterAlertGroupLister.List("", labels.NewSelector())
if err != nil {
return false, err
}
for _, alert := range clusterAlerts {
if len(alert.Spec.Recipients) > 0 {
return true, nil
}
}
projectAlerts, err := d.projectAlertGroupLister.List("", labels.NewSelector())
if err != nil {
return false, nil
}
for _, alert := range projectAlerts {
if controller.ObjectInCluster(d.clusterName, alert) {
if len(alert.Spec.Recipients) > 0 {
return true, nil
}
}
}
return false, nil
}
func (d *appDeployer) isDeploySuccess(cluster *mgmtv3.Cluster, appName, appTargetNamespace string) error {
_, err := mgmtv3.ClusterConditionAlertingEnabled.DoUntilTrue(cluster, func() (runtime.Object, error) {
_, err := d.statefulsets.GetNamespaced(appTargetNamespace, appName, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("failed to get Alertmanager Deployment information, %v", err)
}
return cluster, nil
})
return err
}
func (d *appDeployer) cleanup(appName, appTargetNamespace, systemProjectID string) (bool, error) {
_, systemProjectName := ref.Parse(systemProjectID)
var errgrp errgroup.Group
errgrp.Go(func() error {
return d.appsGetter.Apps(systemProjectName).Delete(appName, &metav1.DeleteOptions{})
})
errgrp.Go(func() error {
secretName := alertutil.GetAlertManagerSecretName(appName)
return d.secrets.DeleteNamespaced(appTargetNamespace, secretName, &metav1.DeleteOptions{})
})
if err := errgrp.Wait(); err != nil && !apierrors.IsNotFound(err) {
return false, err
}
return false, nil
}
func (d *appDeployer) getSecret(secretName, secretNamespace string) *corev1.Secret {
cfg := manager.GetAlertManagerDefaultConfig()
data, err := yaml.Marshal(cfg)
if err != nil {
return nil
}
return &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Namespace: secretNamespace,
Name: secretName,
},
Data: map[string][]byte{
"alertmanager.yaml": data,
"notification.tmpl": []byte(NotificationTmpl),
},
}
}
func (d *appDeployer) deploy(appName, appTargetNamespace, systemProjectID, systemProjectCreator string) (bool, error) {
_, systemProjectName := ref.Parse(systemProjectID)
ns := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: appTargetNamespace,
},
}
if _, err := d.namespaces.Create(ns); err != nil && !apierrors.IsAlreadyExists(err) {
return false, fmt.Errorf("create ns %s failed, %v", appTargetNamespace, err)
}
secretName := alertutil.GetAlertManagerSecretName(appName)
secret := d.getSecret(secretName, appTargetNamespace)
if _, err := d.secrets.Create(secret); err != nil && !apierrors.IsAlreadyExists(err) {
return false, fmt.Errorf("create secret %s:%s failed, %v", appTargetNamespace, appName, err)
}
app, err := d.appsGetter.Apps(systemProjectName).Get(appName, metav1.GetOptions{})
if err != nil && !apierrors.IsNotFound(err) {
return false, fmt.Errorf("failed to query %q App in %s Project, %v", appName, systemProjectName, err)
}
if app.Name == appName {
if app.DeletionTimestamp != nil {
return false, fmt.Errorf("stale %q App in %s Project is still on terminating", appName, systemProjectName)
}
return true, nil
}
catalogID := settings.SystemMonitoringCatalogID.Get()
templateVersionID, err := common.ParseExternalID(catalogID)
if err != nil {
return false, fmt.Errorf("failed to parse catalog ID %q, %v", catalogID, err)
}
if _, err := d.templateVersions.Get(templateVersionID, metav1.GetOptions{}); err != nil {
return false, fmt.Errorf("failed to find catalog by ID %q, %v", catalogID, err)
}
app = &projectv3.App{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
creatorIDAnn: systemProjectCreator,
},
Labels: monitorutil.OwnedLabels(appName, appTargetNamespace, monitorutil.SystemLevel),
Name: appName,
Namespace: systemProjectName,
},
Spec: projectv3.AppSpec{
Answers: map[string]string{
"alertmanager.enabled": "true",
"alertmanager.serviceMonitor.enabled": "true",
"alertmanager.apiGroup": monitorutil.APIVersion.Group,
"alertmanager.enabledRBAC": "false",
"alertmanager.configFromSecret": secret.Name,
},
Description: "Alertmanager for Rancher Monitoring",
ExternalID: catalogID,
ProjectName: systemProjectID,
TargetNamespace: appTargetNamespace,
},
}
if _, err := d.appsGetter.Apps(systemProjectName).Create(app); err != nil && !apierrors.IsAlreadyExists(err) {
return false, fmt.Errorf("failed to create %q App, %v", appName, err)
}
return true, nil
}
func (od *operaterDeployer) sync(cluster *mgmtv3.Cluster) error {
return monitoring.SyncServiceMonitor(cluster, od.cores, od.rbacs, od.appsGetter, od.projectsGetter, od.templateVersions)
} | |
poll.go | package login
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"time"
"github.com/stripe/stripe-cli/pkg/stripe"
)
const maxAttemptsDefault = 2 * 60
const intervalDefault = 1 * time.Second
// PollAPIKeyResponse returns the data of the polling client login
type PollAPIKeyResponse struct {
Redeemed bool `json:"redeemed"`
AccountID string `json:"account_id"`
AccountDisplayName string `json:"account_display_name"`
LiveModeAPIKey string `json:"livemode_key_secret"`
LiveModePublishableKey string `json:"livemode_key_publishable"`
TestModeAPIKey string `json:"testmode_key_secret"`
TestModePublishableKey string `json:"testmode_key_publishable"`
}
// PollForKey polls Stripe at the specified interval until either the API key is available or we've reached the max attempts.
func PollForKey(pollURL string, interval time.Duration, maxAttempts int) (*PollAPIKeyResponse, *Account, error) {
var response PollAPIKeyResponse
if maxAttempts == 0 {
maxAttempts = maxAttemptsDefault
}
if interval == 0 {
interval = intervalDefault
}
parsedURL, err := url.Parse(pollURL)
if err != nil |
baseURL := &url.URL{Scheme: parsedURL.Scheme, Host: parsedURL.Host}
client := &stripe.Client{
BaseURL: baseURL,
}
var count = 0
for count < maxAttempts {
res, err := client.PerformRequest(http.MethodGet, parsedURL.Path, parsedURL.Query().Encode(), nil)
if err != nil {
return nil, nil, err
}
defer res.Body.Close()
bodyBytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, nil, err
}
if res.StatusCode != http.StatusOK {
return nil, nil, fmt.Errorf("unexpected http status code: %d %s", res.StatusCode, string(bodyBytes))
}
jsonErr := json.Unmarshal(bodyBytes, &response)
if jsonErr != nil {
return nil, nil, jsonErr
}
if response.Redeemed {
account := &Account{
ID: response.AccountID,
}
account.Settings.Dashboard.DisplayName = response.AccountDisplayName
return &response, account, nil
}
count++
time.Sleep(interval)
}
return nil, nil, errors.New("exceeded max attempts")
}
| {
return nil, nil, err
} |
test_user_model.py | from plato.test.base import BaseTestCase
from sqlalchemy.exc import IntegrityError
from plato import db
from plato.model.user import User
from plato.test.utils import add_user
class TestUserModel(BaseTestCase):
def test_user_model(self):
user = add_user('foo', '[email protected]', 'test_pwd')
self.assertTrue(user.id)
self.assertEqual('foo', user.username)
self.assertEqual('[email protected]', user.email)
self.assertTrue(user.active)
self.assertTrue(user.created_at)
self.assertTrue(user.password)
self.assertTrue(user.admin == False)
def test_add_user_duplicate_username(self):
add_user('foo', '[email protected]', 'test_pwd') | self.assertRaises(IntegrityError, db.session.commit)
def test_add_user_duplicate_email(self):
add_user('foo', '[email protected]', 'test_pwd')
duplicate_user = User('foo_1', '[email protected]', 'test_pwd')
db.session.add(duplicate_user)
self.assertRaises(IntegrityError, db.session.commit)
def test_passwords_are_random(self):
user_foo = add_user('foo', '[email protected]', 'test_pwd')
user_bar = add_user('bar', '[email protected]', 'test_pwd')
self.assertNotEqual(user_foo.password, user_bar.password)
def test_encode_auth_token(self):
user = add_user('[email protected]', '[email protected]', 'test')
auth_token = user.encode_auth_token(user.id)
self.assertTrue(isinstance(auth_token, bytes))
def test_decode_auth_token(self):
user = add_user('[email protected]', '[email protected]', 'test')
auth_token = user.encode_auth_token(user.id)
self.assertTrue(isinstance(auth_token, bytes))
self.assertTrue(User.decode_auth_token(auth_token), user.id) | duplicate_user = User('foo', '[email protected]', 'test_pwd')
db.session.add(duplicate_user) |
insert_header_footer_request.go | /*
* --------------------------------------------------------------------------------
* <copyright company="Aspose" file="insert_header_footer_request.go">
* Copyright (c) 2021 Aspose.Words for Cloud
* </copyright>
* <summary>
* 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.
* </summary>
* --------------------------------------------------------------------------------
*/
package models
import (
"io"
"fmt"
"net/url"
"strings"
"encoding/json"
)
// InsertHeaderFooterRequest contains request data for WordsApiService.InsertHeaderFooter method.
type InsertHeaderFooterRequest struct {
// The filename of the input document.
Name *string
// The path to the section in the document tree.
SectionPath *string
// Type of header/footer.
HeaderFooterType *string
/* optional (nil or map[string]interface{}) with one or more of key / value pairs:
key: "folder" value: (string) Original document folder.
key: "storage" value: (string) Original document storage.
key: "loadEncoding" value: (string) Encoding that will be used to load an HTML (or TXT) document if the encoding is not specified in HTML.
key: "password" value: (string) Password for opening an encrypted document.
key: "destFileName" value: (string) Result path of the document after the operation. If this parameter is omitted then result of the operation will be saved as the source document.
key: "revisionAuthor" value: (string) Initials of the author to use for revisions.If you set this parameter and then make some changes to the document programmatically, save the document and later open the document in MS Word you will see these changes as revisions.
key: "revisionDateTime" value: (string) The date and time to use for revisions. */
Optionals map[string]interface{}
}
func (data *InsertHeaderFooterRequest) CreateRequestData() (RequestData, error) {
var result RequestData
result.Method = strings.ToUpper("put")
// create path and map variables
result.Path = "/words/{name}/{sectionPath}/headersfooters"
result.Path = strings.Replace(result.Path, "{"+"name"+"}", fmt.Sprintf("%v", *data.Name), -1)
result.Path = strings.Replace(result.Path, "{"+"sectionPath"+"}", fmt.Sprintf("%v", *data.SectionPath), -1)
result.Path = strings.Replace(result.Path, "/<nil>", "", -1)
result.Path = strings.Replace(result.Path, "//", "/", -1)
result.HeaderParams = make(map[string]string)
result.QueryParams = url.Values{}
result.FormParams = make([]FormParamContainer, 0)
if err := typeCheckParameter(data.Optionals["folder"], "string", "data.Optionals[folder]"); err != nil {
return result, err
}
if err := typeCheckParameter(data.Optionals["storage"], "string", "data.Optionals[storage]"); err != nil {
return result, err
}
if err := typeCheckParameter(data.Optionals["loadEncoding"], "string", "data.Optionals[loadEncoding]"); err != nil {
return result, err
}
if err := typeCheckParameter(data.Optionals["password"], "string", "data.Optionals[password]"); err != nil {
return result, err
}
if err := typeCheckParameter(data.Optionals["destFileName"], "string", "data.Optionals[destFileName]"); err != nil {
return result, err
}
if err := typeCheckParameter(data.Optionals["revisionAuthor"], "string", "data.Optionals[revisionAuthor]"); err != nil {
return result, err
}
if err := typeCheckParameter(data.Optionals["revisionDateTime"], "string", "data.Optionals[revisionDateTime]"); err != nil {
return result, err
}
if localVarTempParam, localVarOk := data.Optionals["folder"].(string); localVarOk {
result.QueryParams.Add("Folder", parameterToString(localVarTempParam, ""))
} | }
if localVarTempParam, localVarOk := data.Optionals["loadEncoding"].(string); localVarOk {
result.QueryParams.Add("LoadEncoding", parameterToString(localVarTempParam, ""))
}
if localVarTempParam, localVarOk := data.Optionals["password"].(string); localVarOk {
result.QueryParams.Add("Password", parameterToString(localVarTempParam, ""))
}
if localVarTempParam, localVarOk := data.Optionals["destFileName"].(string); localVarOk {
result.QueryParams.Add("DestFileName", parameterToString(localVarTempParam, ""))
}
if localVarTempParam, localVarOk := data.Optionals["revisionAuthor"].(string); localVarOk {
result.QueryParams.Add("RevisionAuthor", parameterToString(localVarTempParam, ""))
}
if localVarTempParam, localVarOk := data.Optionals["revisionDateTime"].(string); localVarOk {
result.QueryParams.Add("RevisionDateTime", parameterToString(localVarTempParam, ""))
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{ "application/xml", "application/json", }
// set Content-Type header
localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
result.HeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{
"application/xml",
"application/json",
}
// set Accept header
localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
result.HeaderParams["Accept"] = localVarHttpHeaderAccept
}
result.PostBody = &data.HeaderFooterType
return result, nil
}
func (data *InsertHeaderFooterRequest) CreateResponse(reader io.Reader) (result interface{}, err error) {
var successPayload HeaderFooterResponse
if err = json.NewDecoder(reader).Decode(&successPayload); err != nil {
return successPayload, err
}
return successPayload, err
} |
if localVarTempParam, localVarOk := data.Optionals["storage"].(string); localVarOk {
result.QueryParams.Add("Storage", parameterToString(localVarTempParam, "")) |
mod.rs | use self::kmeansclustering::KMeansProblem;
use super::zle::ZleSymbol;
mod kmeansclustering;
#[derive(Clone, Copy)]
#[non_exhaustive]
/// Strategy for using Huffman Tables
///
/// * [EncodingStrategy::Single] - every block of 900k uses a single huffman code table
/// * [EncodingStrategy::BlockWise] - usage of code tables in 50 byte chunks is optimized using Lloyd's algorithm with given parameters
pub enum EncodingStrategy {
BlockWise {
num_clusters: usize,
num_iterations: usize,
},
Single,
}
pub(crate) struct SinglePropabilityMap {
frequencies: Vec<usize>,
symbol_count: usize,
}
impl SinglePropabilityMap {
pub(crate) fn create(size: usize) -> Self {
SinglePropabilityMap {
frequencies: vec![0; size + 1],
symbol_count: 0,
}
}
}
impl SymbolReporter for SinglePropabilityMap {
fn report_symbol(&mut self, symbol: &ZleSymbol) {
self.symbol_count += 1;
match symbol {
ZleSymbol::RunA => {
self.frequencies[0] += 1;
}
ZleSymbol::RunB => {
self.frequencies[1] += 1;
}
ZleSymbol::Number(i) => {
self.frequencies[*i as usize + 1] += 1;
}
}
}
fn finalize(&mut self) -> ReportedSymbols {
let table = IntoFrequencyTable {
frequencies: self.frequencies.clone(),
};
ReportedSymbols {
reported_frequencies: vec![table.clone(), table],
selectors: vec![0; (self.symbol_count as f32 / 50.0).ceil() as usize],
}
}
}
pub(crate) struct BlockWisePropabilityMap {
current_frequencies: Vec<u8>,
pub(crate) maps: Vec<Vec<u8>>,
pub(crate) size: usize,
counter: usize,
num_iterations: usize,
num_clusters: usize,
}
impl BlockWisePropabilityMap {
pub(crate) fn create(size: usize, num_clusters: usize, num_iterations: usize) -> Self {
Self {
current_frequencies: vec![0; size + 1],
maps: vec![],
counter: 0,
size,
num_clusters,
num_iterations,
}
}
}
impl SymbolReporter for BlockWisePropabilityMap {
fn report_symbol(&mut self, symbol: &ZleSymbol) {
match symbol {
ZleSymbol::RunA => {
self.current_frequencies[0] += 1;
}
ZleSymbol::RunB => {
self.current_frequencies[1] += 1;
}
ZleSymbol::Number(i) => {
self.current_frequencies[*i as usize + 1] += 1;
}
}
self.counter += 1;
if self.counter >= 50 {
self.maps.push(std::mem::replace(
&mut self.current_frequencies,
vec![0; self.size + 1],
));
self.counter = 0;
}
}
fn finalize(&mut self) -> ReportedSymbols {
self.maps.push(std::mem::replace(
&mut self.current_frequencies,
vec![0; self.size + 1],
));
let p = KMeansProblem {
dimension: self.size + 1,
data: &self.maps,
num_iterations: self.num_iterations,
num_clusters: self.num_clusters,
};
let tables = p.solve();
ReportedSymbols {
reported_frequencies: tables
.means
.iter()
.map(|x| IntoFrequencyTable {
frequencies: x.iter().map(|x| *x as usize).collect::<Vec<_>>(),
})
.collect::<Vec<_>>(),
selectors: tables.assignments,
}
}
}
pub(crate) trait SymbolReporter {
fn report_symbol(&mut self, symbol: &ZleSymbol);
fn finalize(&mut self) -> ReportedSymbols;
} |
pub(crate) struct ReportedSymbols {
pub(crate) reported_frequencies: Vec<IntoFrequencyTable>,
pub(crate) selectors: Vec<u8>,
}
#[derive(Clone)]
pub(crate) struct IntoFrequencyTable {
pub(crate) frequencies: Vec<usize>,
}
impl IntoFrequencyTable {
pub(crate) fn iterate(self) -> impl Iterator<Item = (ZleSymbol, usize)> {
self.frequencies
.into_iter()
.enumerate()
.map(|(symbol, frequency)| match symbol {
0 => (ZleSymbol::RunA, frequency),
1 => (ZleSymbol::RunB, frequency),
x => (ZleSymbol::Number((x - 1) as u8), frequency),
})
}
} | |
nodemon-debug.js | var nodemon = require('gulp-nodemon')
module.exports = function () {
return nodemon({
script: './main.js' | })
} |
|
Movie.py | from database.queries.insert_queries import INSERT_MOVIE
from database.queries.update_queries import UPDATE_MOVIE
from database.queries.delete_queries import DELETE_MOVIE
from database.queries.select_queries import SELECT_MOVIES_ORDERED_BY_RATING,\
SELECT_PROJECTION_FOR_MOVIE, \
SELECT_MOVIE_BY_ID
from database.connection.execute_query import execute_query
from settings.SharedVariables import SharedVariables
from prettytable import PrettyTable
class Movies:
def __init__(self):
try:
self.data = execute_query(SELECT_MOVIES_ORDERED_BY_RATING, [])
except Exception:
print("Database not initilized or connected")
def __str__(self):
t = PrettyTable(SharedVariables.movie_col)
for row in self.data:
t.add_row([row[0], row[1], row[2]])
return str(t)
@staticmethod
def get_movie(id):
try:
data = execute_query(SELECT_MOVIE_BY_ID, [id, ])
except Exception:
print("Database not initilized or connected")
t = PrettyTable(SharedVariables.movie_col)
for row in data:
t.add_row([row[0], row[1], row[2]])
return str(t)
@staticmethod
def add_movie(name, rating):
try:
execute_query(INSERT_MOVIE, [name, rating, ], commit=True)
except Exception:
print("Database not initilized or connected")
@staticmethod
def delete_movie(id):
|
@staticmethod
def update_movie(id, name, rating):
try:
execute_query(UPDATE_MOVIE, [name, rating, id, ], commit=True)
except Exception:
print("Database not initilized or connected")
@staticmethod
def movie_projections(id):
try:
data = execute_query(SELECT_PROJECTION_FOR_MOVIE, [id, ])
t = PrettyTable(SharedVariables.projection_col)
for row in data:
t.add_row([row[0], row[1], row[2], row[3], (100 - row[4])])
return str(t)
except Exception:
print("Database not initilized or connected!")
if __name__ == '__main__':
from database.connection.database_connection import Database
SharedVariables.database = Database()
Movies.add_movie("Baywatch", 10)
print(Movies.get_movie(2))
| try:
execute_query(DELETE_MOVIE, [id, ], commit=True)
except Exception:
print("Database not initilized or connected") |
merge_request_builder.go | package merge
import (
ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9 "github.com/microsoft/kiota/abstractions/go"
)
// MergeRequestBuilder builds and executes requests for operations under \users\{user-id}\insights\trending\{trending-id}\resource\microsoft.graph.workbookRange\microsoft.graph.merge
type MergeRequestBuilder struct {
// Path parameters for the request
pathParameters map[string]string;
// The request adapter to use to execute the requests.
requestAdapter ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestAdapter;
// Url template to use to build the URL for the current request builder
urlTemplate string;
}
// MergeRequestBuilderPostOptions options for Post
type MergeRequestBuilderPostOptions struct {
//
Body *MergeRequestBody;
// Request headers
H map[string]string;
// Request options
O []ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestOption;
// Response handler to use in place of the default response handling provided by the core service
ResponseHandler ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.ResponseHandler;
}
// NewMergeRequestBuilderInternal instantiates a new MergeRequestBuilder and sets the default values.
func NewMergeRequestBuilderInternal(pathParameters map[string]string, requestAdapter ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestAdapter)(*MergeRequestBuilder) {
m := &MergeRequestBuilder{
}
m.urlTemplate = "{+baseurl}/users/{user_id}/insights/trending/{trending_id}/resource/microsoft.graph.workbookRange/microsoft.graph.merge";
urlTplParams := make(map[string]string)
for idx, item := range pathParameters {
urlTplParams[idx] = item
}
m.pathParameters = pathParameters;
m.requestAdapter = requestAdapter;
return m
}
// NewMergeRequestBuilder instantiates a new MergeRequestBuilder and sets the default values.
func NewMergeRequestBuilder(rawUrl string, requestAdapter ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestAdapter)(*MergeRequestBuilder) {
urlParams := make(map[string]string)
urlParams["request-raw-url"] = rawUrl
return NewMergeRequestBuilderInternal(urlParams, requestAdapter)
}
// CreatePostRequestInformation invoke action merge
func (m *MergeRequestBuilder) CreatePostRequestInformation(options *MergeRequestBuilderPostOptions)(*ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestInformation, error) {
requestInfo := ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.NewRequestInformation()
requestInfo.UrlTemplate = m.urlTemplate
requestInfo.PathParameters = m.pathParameters
requestInfo.Method = ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.POST
requestInfo.SetContentFromParsable(m.requestAdapter, "application/json", options.Body)
if options != nil && options.H != nil {
requestInfo.Headers = options.H
}
if options != nil && len(options.O) != 0 {
err := requestInfo.AddRequestOptions(options.O...)
if err != nil {
return nil, err
}
}
return requestInfo, nil
}
// Post invoke action merge
func (m *MergeRequestBuilder) Post(options *MergeRequestBuilderPostOptions)(error) {
requestInfo, err := m.CreatePostRequestInformation(options);
if err != nil {
return err
}
err = m.requestAdapter.SendNoContentAsync(*requestInfo, nil, nil)
if err != nil |
return nil
}
| {
return err
} |
NutritionOrder_Nutrient.rs | #![allow(unused_imports, non_camel_case_types)]
use crate::model::CodeableConcept::CodeableConcept;
use crate::model::Extension::Extension;
use crate::model::Quantity::Quantity;
use serde_json::json;
use serde_json::value::Value;
use std::borrow::Cow;
/// A request to supply a diet, formula feeding (enteral) or oral nutritional
/// supplement to a patient/resident.
#[derive(Debug)]
pub struct NutritionOrder_Nutrient<'a> {
pub(crate) value: Cow<'a, Value>,
}
impl NutritionOrder_Nutrient<'_> {
pub fn new(value: &Value) -> NutritionOrder_Nutrient {
NutritionOrder_Nutrient {
value: Cow::Borrowed(value),
}
}
pub fn to_json(&self) -> Value {
(*self.value).clone()
}
/// The quantity of the specified nutrient to include in diet.
pub fn amount(&self) -> Option<Quantity> {
if let Some(val) = self.value.get("amount") {
return Some(Quantity {
value: Cow::Borrowed(val),
});
}
return None;
}
/// May be used to represent additional information that is not part of the basic
/// definition of the element. To make the use of extensions safe and manageable,
/// there is a strict set of governance applied to the definition and use of
/// extensions. Though any implementer can define an extension, there is a set of
/// requirements that SHALL be met as part of the definition of the extension.
pub fn extension(&self) -> Option<Vec<Extension>> {
if let Some(Value::Array(val)) = self.value.get("extension") {
return Some(
val.into_iter()
.map(|e| Extension {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
/// Unique id for the element within a resource (for internal references). This may
/// be any string value that does not contain spaces.
pub fn id(&self) -> Option<&str> {
if let Some(Value::String(string)) = self.value.get("id") {
return Some(string);
}
return None;
}
/// The nutrient that is being modified such as carbohydrate or sodium.
pub fn modifier(&self) -> Option<CodeableConcept> {
if let Some(val) = self.value.get("modifier") {
return Some(CodeableConcept {
value: Cow::Borrowed(val),
});
}
return None;
}
/// May be used to represent additional information that is not part of the basic
/// definition of the element and that modifies the understanding of the element in
/// which it is contained and/or the understanding of the containing element's
/// descendants. Usually modifier elements provide negation or qualification. To
/// make the use of extensions safe and manageable, there is a strict set of
/// governance applied to the definition and use of extensions. Though any
/// implementer can define an extension, there is a set of requirements that SHALL
/// be met as part of the definition of the extension. Applications processing a
/// resource are required to check for modifier extensions. Modifier extensions
/// SHALL NOT change the meaning of any elements on Resource or DomainResource
/// (including cannot change the meaning of modifierExtension itself).
pub fn modifier_extension(&self) -> Option<Vec<Extension>> {
if let Some(Value::Array(val)) = self.value.get("modifierExtension") {
return Some(
val.into_iter()
.map(|e| Extension {
value: Cow::Borrowed(e),
})
.collect::<Vec<_>>(),
);
}
return None;
}
pub fn validate(&self) -> bool {
if let Some(_val) = self.amount() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self.extension() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
if let Some(_val) = self.id() {}
if let Some(_val) = self.modifier() {
if !_val.validate() {
return false;
}
}
if let Some(_val) = self.modifier_extension() {
if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) {
return false;
}
}
return true;
}
}
#[derive(Debug)]
pub struct | {
pub(crate) value: Value,
}
impl NutritionOrder_NutrientBuilder {
pub fn build(&self) -> NutritionOrder_Nutrient {
NutritionOrder_Nutrient {
value: Cow::Owned(self.value.clone()),
}
}
pub fn with(existing: NutritionOrder_Nutrient) -> NutritionOrder_NutrientBuilder {
NutritionOrder_NutrientBuilder {
value: (*existing.value).clone(),
}
}
pub fn new() -> NutritionOrder_NutrientBuilder {
let mut __value: Value = json!({});
return NutritionOrder_NutrientBuilder { value: __value };
}
pub fn amount<'a>(&'a mut self, val: Quantity) -> &'a mut NutritionOrder_NutrientBuilder {
self.value["amount"] = json!(val.value);
return self;
}
pub fn extension<'a>(
&'a mut self,
val: Vec<Extension>,
) -> &'a mut NutritionOrder_NutrientBuilder {
self.value["extension"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
pub fn id<'a>(&'a mut self, val: &str) -> &'a mut NutritionOrder_NutrientBuilder {
self.value["id"] = json!(val);
return self;
}
pub fn modifier<'a>(
&'a mut self,
val: CodeableConcept,
) -> &'a mut NutritionOrder_NutrientBuilder {
self.value["modifier"] = json!(val.value);
return self;
}
pub fn modifier_extension<'a>(
&'a mut self,
val: Vec<Extension>,
) -> &'a mut NutritionOrder_NutrientBuilder {
self.value["modifierExtension"] =
json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
return self;
}
}
| NutritionOrder_NutrientBuilder |
convert.py | # -*- coding: utf-8 -*-
"""
@Time : 2020/10/21 10:39
@Auth : Qi
@IDE : PyCharm
@Title: 6. Z 字形变换
@Link : https://leetcode-cn.com/problems/zigzag-conversion/
"""
class Solution:
def convert( | : str, numRows: int) -> str:
if numRows <= 0:
return ''
if numRows == 1:
return s
ret = ''
for i in range(numRows):
tmp = i
time = numRows * 2 - 2
while tmp < len(s):
if i == 0 or i == numRows - 1 and tmp:
ret += s[tmp]
tmp += time
else:
ret += s[tmp]
if tmp + time - i * 2 < len(s):
ret += s[tmp + time - i * 2]
else:
break
tmp += time
return ret
if __name__ == '__main__':
# 测试用例
s = Solution()
print(s.convert('ABCDE', 4))
| self, s |
build.rs | fn main() -> Result<(), Box<dyn std::error::Error>> | {
tonic_build::configure().build_server(true).compile(
&[
"../api/matching-engine/matchingEngine.proto",
"../api/user-service/userService.proto",
],
&["../api/"],
)?;
Ok(())
} |
|
server.ts | import { RequestListener } from 'http'
import { createApp, createError, useBody } from 'h3'
import { Storage } from './types'
import { stringify } from './_utils'
export interface StorageServerOptions {
}
export interface StorageServer {
handle: RequestListener
}
export function | (storage: Storage, _opts: StorageServerOptions = {}): StorageServer {
const app = createApp()
app.use(async (req, res) => {
// GET => getItem
if (req.method === 'GET') {
const val = await storage.getItem(req.url!)
if (!val) {
const keys = await storage.getKeys(req.url)
return keys.map(key => key.replace(/:/g, '/'))
}
return stringify(val)
}
// HEAD => hasItem + meta (mtime)
if (req.method === 'HEAD') {
const _hasItem = await storage.hasItem(req.url!)
res.statusCode = _hasItem ? 200 : 404
if (_hasItem) {
const meta = await storage.getMeta(req.url!)
if (meta.mtime) {
res.setHeader('Last-Modified', new Date(meta.mtime).toUTCString())
}
}
return ''
}
// PUT => setItem
if (req.method === 'PUT') {
const val = await useBody(req)
await storage.setItem(req.url!, val)
return 'OK'
}
// DELETE => removeItem
if (req.method === 'DELETE') {
await storage.removeItem(req.url!)
return 'OK'
}
throw createError({
statusCode: 405,
statusMessage: 'Method Not Allowd'
})
})
return {
handle: app
}
}
| createStorageServer |
wrappers.pb.go | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. 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.
// Wrappers for primitive (non-message) types. These types are useful
// for embedding primitives in the `google.protobuf.Any` type and for places
// where we need to distinguish between the absence of a primitive
// typed field and its default value.
//
// These wrappers have no meaningful use within repeated fields as they lack
// the ability to detect presence on individual elements.
// These wrappers have no meaningful use within a map or a oneof since
// individual entries of a map or fields of a oneof can already detect presence.
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/protobuf/wrappers.proto
package wrapperspb
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
// Wrapper message for `double`.
//
// The JSON representation for `DoubleValue` is JSON number.
type DoubleValue struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// The double value.
Value float64 `protobuf:"fixed64,1,opt,name=value,proto3" json:"value,omitempty"`
}
func (x *DoubleValue) Reset() {
*x = DoubleValue{}
if protoimpl.UnsafeEnabled {
mi := &file_google_protobuf_wrappers_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *DoubleValue) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DoubleValue) ProtoMessage() {}
func (x *DoubleValue) ProtoReflect() protoreflect.Message {
mi := &file_google_protobuf_wrappers_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DoubleValue.ProtoReflect.Descriptor instead.
func (*DoubleValue) Descriptor() ([]byte, []int) {
return file_google_protobuf_wrappers_proto_rawDescGZIP(), []int{0}
}
func (x *DoubleValue) GetValue() float64 {
if x != nil {
return x.Value
}
return 0
}
// Wrapper message for `float`.
//
// The JSON representation for `FloatValue` is JSON number.
type FloatValue struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// The float value.
Value float32 `protobuf:"fixed32,1,opt,name=value,proto3" json:"value,omitempty"`
}
func (x *FloatValue) Reset() {
*x = FloatValue{}
if protoimpl.UnsafeEnabled {
mi := &file_google_protobuf_wrappers_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *FloatValue) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*FloatValue) ProtoMessage() {}
func (x *FloatValue) ProtoReflect() protoreflect.Message {
mi := &file_google_protobuf_wrappers_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use FloatValue.ProtoReflect.Descriptor instead.
func (*FloatValue) Descriptor() ([]byte, []int) {
return file_google_protobuf_wrappers_proto_rawDescGZIP(), []int{1}
}
func (x *FloatValue) GetValue() float32 {
if x != nil {
return x.Value
}
return 0
}
// Wrapper message for `int64`.
//
// The JSON representation for `Int64Value` is JSON string.
type Int64Value struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// The int64 value.
Value int64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
}
func (x *Int64Value) Reset() {
*x = Int64Value{}
if protoimpl.UnsafeEnabled {
mi := &file_google_protobuf_wrappers_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Int64Value) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Int64Value) ProtoMessage() {}
func (x *Int64Value) ProtoReflect() protoreflect.Message {
mi := &file_google_protobuf_wrappers_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Int64Value.ProtoReflect.Descriptor instead.
func (*Int64Value) Descriptor() ([]byte, []int) {
return file_google_protobuf_wrappers_proto_rawDescGZIP(), []int{2}
}
func (x *Int64Value) GetValue() int64 {
if x != nil {
return x.Value
}
return 0
}
// Wrapper message for `uint64`.
//
// The JSON representation for `UInt64Value` is JSON string.
type UInt64Value struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// The uint64 value.
Value uint64 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
}
func (x *UInt64Value) Reset() {
*x = UInt64Value{}
if protoimpl.UnsafeEnabled {
mi := &file_google_protobuf_wrappers_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *UInt64Value) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UInt64Value) ProtoMessage() {}
func (x *UInt64Value) ProtoReflect() protoreflect.Message {
mi := &file_google_protobuf_wrappers_proto_msgTypes[3]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UInt64Value.ProtoReflect.Descriptor instead.
func (*UInt64Value) Descriptor() ([]byte, []int) {
return file_google_protobuf_wrappers_proto_rawDescGZIP(), []int{3}
}
func (x *UInt64Value) GetValue() uint64 {
if x != nil {
return x.Value
}
return 0
}
// Wrapper message for `int32`.
//
// The JSON representation for `Int32Value` is JSON number.
type Int32Value struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// The int32 value.
Value int32 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
}
func (x *Int32Value) Reset() {
*x = Int32Value{}
if protoimpl.UnsafeEnabled {
mi := &file_google_protobuf_wrappers_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Int32Value) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Int32Value) ProtoMessage() {}
func (x *Int32Value) ProtoReflect() protoreflect.Message {
mi := &file_google_protobuf_wrappers_proto_msgTypes[4]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Int32Value.ProtoReflect.Descriptor instead.
func (*Int32Value) Descriptor() ([]byte, []int) {
return file_google_protobuf_wrappers_proto_rawDescGZIP(), []int{4}
}
func (x *Int32Value) GetValue() int32 {
if x != nil {
return x.Value
}
return 0
}
// Wrapper message for `uint32`.
//
// The JSON representation for `UInt32Value` is JSON number.
type UInt32Value struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// The uint32 value.
Value uint32 `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
}
func (x *UInt32Value) Reset() {
*x = UInt32Value{}
if protoimpl.UnsafeEnabled {
mi := &file_google_protobuf_wrappers_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *UInt32Value) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UInt32Value) ProtoMessage() {}
func (x *UInt32Value) ProtoReflect() protoreflect.Message {
mi := &file_google_protobuf_wrappers_proto_msgTypes[5]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UInt32Value.ProtoReflect.Descriptor instead.
func (*UInt32Value) Descriptor() ([]byte, []int) {
return file_google_protobuf_wrappers_proto_rawDescGZIP(), []int{5}
}
func (x *UInt32Value) GetValue() uint32 {
if x != nil {
return x.Value
}
return 0
}
// Wrapper message for `bool`.
//
// The JSON representation for `BoolValue` is JSON `true` and `false`.
type BoolValue struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// The bool value.
Value bool `protobuf:"varint,1,opt,name=value,proto3" json:"value,omitempty"`
}
func (x *BoolValue) Reset() {
*x = BoolValue{}
if protoimpl.UnsafeEnabled {
mi := &file_google_protobuf_wrappers_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *BoolValue) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*BoolValue) ProtoMessage() {}
func (x *BoolValue) ProtoReflect() protoreflect.Message {
mi := &file_google_protobuf_wrappers_proto_msgTypes[6]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use BoolValue.ProtoReflect.Descriptor instead.
func (*BoolValue) Descriptor() ([]byte, []int) {
return file_google_protobuf_wrappers_proto_rawDescGZIP(), []int{6}
}
func (x *BoolValue) GetValue() bool {
if x != nil {
return x.Value
}
return false
}
// Wrapper message for `string`.
//
// The JSON representation for `StringValue` is JSON string.
type StringValue struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// The string value.
Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
}
func (x *StringValue) Reset() {
*x = StringValue{}
if protoimpl.UnsafeEnabled {
mi := &file_google_protobuf_wrappers_proto_msgTypes[7]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *StringValue) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*StringValue) ProtoMessage() {}
func (x *StringValue) ProtoReflect() protoreflect.Message {
mi := &file_google_protobuf_wrappers_proto_msgTypes[7]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use StringValue.ProtoReflect.Descriptor instead.
func (*StringValue) Descriptor() ([]byte, []int) {
return file_google_protobuf_wrappers_proto_rawDescGZIP(), []int{7}
}
func (x *StringValue) GetValue() string {
if x != nil {
return x.Value
}
return ""
}
// Wrapper message for `bytes`.
//
// The JSON representation for `BytesValue` is JSON string.
type BytesValue struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// The bytes value.
Value []byte `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
}
func (x *BytesValue) Reset() {
*x = BytesValue{}
if protoimpl.UnsafeEnabled {
mi := &file_google_protobuf_wrappers_proto_msgTypes[8]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *BytesValue) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*BytesValue) ProtoMessage() {}
func (x *BytesValue) ProtoReflect() protoreflect.Message {
mi := &file_google_protobuf_wrappers_proto_msgTypes[8]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use BytesValue.ProtoReflect.Descriptor instead.
func (*BytesValue) Descriptor() ([]byte, []int) {
return file_google_protobuf_wrappers_proto_rawDescGZIP(), []int{8}
}
func (x *BytesValue) GetValue() []byte {
if x != nil {
return x.Value
}
return nil
}
var File_google_protobuf_wrappers_proto protoreflect.FileDescriptor
var file_google_protobuf_wrappers_proto_rawDesc = []byte{
0x0a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75,
0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x12, 0x0f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75,
0x66, 0x22, 0x23, 0x0a, 0x0b, 0x44, 0x6f, 0x75, 0x62, 0x6c, 0x65, 0x56, 0x61, 0x6c, 0x75, 0x65,
0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x01, 0x52,
0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x22, 0x0a, 0x0a, 0x46, 0x6c, 0x6f, 0x61, 0x74, 0x56,
0x61, 0x6c, 0x75, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20,
0x01, 0x28, 0x02, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x22, 0x0a, 0x0a, 0x49, 0x6e,
0x74, 0x36, 0x34, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75,
0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x23,
0x0a, 0x0b, 0x55, 0x49, 0x6e, 0x74, 0x36, 0x34, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x14, 0x0a,
0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x05, 0x76, 0x61,
0x6c, 0x75, 0x65, 0x22, 0x22, 0x0a, 0x0a, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75,
0x65, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05,
0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x23, 0x0a, 0x0b, 0x55, 0x49, 0x6e, 0x74, 0x33,
0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18,
0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x21, 0x0a, 0x09,
0x42, 0x6f, 0x6f, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c,
0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22,
0x23, 0x0a, 0x0b, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x14,
0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76,
0x61, 0x6c, 0x75, 0x65, 0x22, 0x22, 0x0a, 0x0a, 0x42, 0x79, 0x74, 0x65, 0x73, 0x56, 0x61, 0x6c,
0x75, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28,
0x0c, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x42, 0x83, 0x01, 0x0a, 0x13, 0x63, 0x6f, 0x6d,
0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66,
0x42, 0x0d, 0x57, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50,
0x01, 0x5a, 0x31, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67,
0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x79,
0x70, 0x65, 0x73, 0x2f, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65,
0x72, 0x73, 0x70, 0x62, 0xf8, 0x01, 0x01, 0xa2, 0x02, 0x03, 0x47, 0x50, 0x42, 0xaa, 0x02, 0x1e,
0x47, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e,
0x57, 0x65, 0x6c, 0x6c, 0x4b, 0x6e, 0x6f, 0x77, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x73, 0x62, 0x06,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_google_protobuf_wrappers_proto_rawDescOnce sync.Once
file_google_protobuf_wrappers_proto_rawDescData = file_google_protobuf_wrappers_proto_rawDesc
)
func file_google_protobuf_wrappers_proto_rawDescGZIP() []byte {
file_google_protobuf_wrappers_proto_rawDescOnce.Do(func() {
file_google_protobuf_wrappers_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_protobuf_wrappers_proto_rawDescData)
})
return file_google_protobuf_wrappers_proto_rawDescData
}
var file_google_protobuf_wrappers_proto_msgTypes = make([]protoimpl.MessageInfo, 9)
var file_google_protobuf_wrappers_proto_goTypes = []interface{}{
(*DoubleValue)(nil), // 0: google.protobuf.DoubleValue
(*FloatValue)(nil), // 1: google.protobuf.FloatValue
(*Int64Value)(nil), // 2: google.protobuf.Int64Value
(*UInt64Value)(nil), // 3: google.protobuf.UInt64Value
(*Int32Value)(nil), // 4: google.protobuf.Int32Value
(*UInt32Value)(nil), // 5: google.protobuf.UInt32Value
(*BoolValue)(nil), // 6: google.protobuf.BoolValue
(*StringValue)(nil), // 7: google.protobuf.StringValue
(*BytesValue)(nil), // 8: google.protobuf.BytesValue
}
var file_google_protobuf_wrappers_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_google_protobuf_wrappers_proto_init() }
func | () {
if File_google_protobuf_wrappers_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_google_protobuf_wrappers_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*DoubleValue); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_google_protobuf_wrappers_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*FloatValue); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_google_protobuf_wrappers_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Int64Value); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_google_protobuf_wrappers_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*UInt64Value); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_google_protobuf_wrappers_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Int32Value); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_google_protobuf_wrappers_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*UInt32Value); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_google_protobuf_wrappers_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*BoolValue); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_google_protobuf_wrappers_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*StringValue); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_google_protobuf_wrappers_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*BytesValue); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_google_protobuf_wrappers_proto_rawDesc,
NumEnums: 0,
NumMessages: 9,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_google_protobuf_wrappers_proto_goTypes,
DependencyIndexes: file_google_protobuf_wrappers_proto_depIdxs,
MessageInfos: file_google_protobuf_wrappers_proto_msgTypes,
}.Build()
File_google_protobuf_wrappers_proto = out.File
file_google_protobuf_wrappers_proto_rawDesc = nil
file_google_protobuf_wrappers_proto_goTypes = nil
file_google_protobuf_wrappers_proto_depIdxs = nil
}
| file_google_protobuf_wrappers_proto_init |
export.js | /*
Subcommand to export the metadata from a Salesforce Org. Replicates
the 'export' subcommand functionality from the Force.com CLI.
*/
var path = require("path");
var fse = require('fs-extra');
var child_process = require('child_process');
var allMetadataNames=new Array();
function | (opts) {
this.options = opts;
if (!this.options.directory) {
this.options.directory='.';
}
try {
var fstat=fse.statSync(this.options.directory);
} catch (e) {
fse.mkdirsSync(this.options.directory);
}
this.packageFilePath=path.join(this.options.directory, 'package.xml');
if (!this.options.sfdxUser) {
console.log('Missing -u (--username) parameter');
process.exit(1);
}
}
ExportCommand.prototype.execute = function () {
console.log('Exporting metadata');
this.getFolderMetadata();
this.getAllMetadata();
var standardObjects=this.getStandardObjects();
this.startPackage();
for (var idx=0; idx<allMetadataNames.length; idx++) {
var mdName=allMetadataNames[idx];
this.startTypeInPackage();
switch(mdName) {
case 'Dashboard':
var dbFolders=this.foldersByType['Dashboard'];
for (var folderId in dbFolders) {
if (dbFolders.hasOwnProperty(folderId)) {
var folder=dbFolders[folderId];
this.addPackageMember(folder.Name);
for (var dbIdx=0; dbIdx<folder.members.length; dbIdx++) {
var dashboard=folder.members[dbIdx];
this.addPackageMember(folder.Name + '/' + dashboard.DeveloperName);
}
}
}
break;
case 'EmailTemplate':
var etFolders=this.foldersByType['Email'];
for (var folderId in etFolders) {
if (etFolders.hasOwnProperty(folderId)) {
var folder=etFolders[folderId];
this.addPackageMember(folder.Name);
for (var etIdx=0; etIdx<folder.members.length; etIdx++) {
var emailTemplate=folder.members[etIdx];
this.addPackageMember(folder.Name + '/' + emailTemplate.DeveloperName);
}
}
}
break;
case 'Document':
var docFolders=this.foldersByType['Document'];
for (var folderId in docFolders) {
if (docFolders.hasOwnProperty(folderId)) {
var folder=docFolders[folderId];
this.addPackageMember(folder.Name);
for (var docIdx=0; docIdx<folder.members.length; docIdx++) {
var Document=folder.members[docIdx];
this.addPackageMember(folder.Name + '/' + Document.DeveloperName);
}
}
}
break;
case 'CustomObject':
for (var soIdx=0; soIdx<standardObjects.length; soIdx++) {
this.addPackageMember(standardObjects[soIdx]);
}
default:
this.addPackageMember('*');
}
this.endTypeInPackage(mdName);
}
this.endPackage();
console.log('Extracting metadata');
child_process.execFileSync('sfdx',
['force:mdapi:retrieve',
'-u', this.options.sfdxUser,
'-r', this.options.directory,
'-k', this.packageFilePath]);
console.log('Metadata written to ' + path.join(this.options.directory, 'unpackaged.zip'));
}
/*
* Extract standard object names as these need to be explicitly named
* when retrieving
*/
ExportCommand.prototype.getStandardObjects=function() {
var standardObjectsObj=child_process.execFileSync('sfdx',
['force:schema:sobject:list',
'-u', this.options.sfdxUser,
'-c', 'standard']);
var standardObjectsString=standardObjectsObj.toString();
standardObjects=standardObjectsString.split('\n');
for (var idx=standardObjects.length-1; idx>=0; idx--) {
if ( (standardObjects[idx].endsWith('__Tag')) ||
(standardObjects[idx].endsWith('__History')) ||
(standardObjects[idx].endsWith('__Tags')) ) {
standardObjects.splice(idx, 1);
}
}
return standardObjects;
}
/*
* Functions to write the package.xml manifest file
* Will be refactored out if other commands need them
*/
ExportCommand.prototype.startPackage=function() {
fse.writeFileSync(this.packageFilePath,
'<?xml version="1.0" encoding="UTF-8"?>\n' +
'<Package xmlns="http://soap.sforce.com/2006/04/metadata">\n');
}
ExportCommand.prototype.endPackage=function() {
fse.appendFileSync(this.packageFilePath,
' <version>51.0</version>\n' +
'</Package>\n');
}
ExportCommand.prototype.addPackageMember = function(member) {
fse.appendFileSync(this.packageFilePath, ' <members>' + member + '</members>\n');
}
ExportCommand.prototype.startTypeInPackage = function(cfg)
{
fse.appendFileSync(this.packageFilePath, ' <types>\n');
}
ExportCommand.prototype.endTypeInPackage = function(name) {
fse.appendFileSync(this.packageFilePath, ' <name>' + name + '</name>\n' +
' </types>\n');
}
ExportCommand.prototype.getFolderMetadata = function() {
this.buildFolderStructure();
this.getReports();
this.getDashboards();
this.getEmailTemplates();
this.getDocuments();
}
ExportCommand.prototype.buildFolderStructure = function() {
let query="Select Id, Name, DeveloperName, Type, NamespacePrefix from Folder where DeveloperName!=null";
let foldersJSON=child_process.execFileSync('sfdx',
['force:data:soql:query',
'-q', query,
'-u', this.options.sfdxUser,
'--json']);
let folders=JSON.parse(foldersJSON);
this.foldersByType={'Dashboard':{},
'Report':{},
'Email':{},
'Document':{}}
for (var idx=0; idx<folders.result.records.length; idx++) {
var folder=folders.result.records[idx];
var foldersForType=this.foldersByType[folder.Type];
if (foldersForType) {
if (!foldersForType[folder.Id]) {
foldersForType[folder.Id]={'Name': folder.DeveloperName, 'members': []};
}
}
}
}
ExportCommand.prototype.getReports = function() {
let query="Select Id, DeveloperName, OwnerId from Report";
let reportsJSON=child_process.execFileSync('sfdx',
['force:data:soql:query',
'-q', query,
'-u', this.options.sfdxUser,
'--json']);
let reports=JSON.parse(reportsJSON);
for (var idx=0; idx<reports.result.records.length; idx++) {
var report=reports.result.records[idx];
var foldersForReports=this.foldersByType['Report'];
var folderForThisReport=foldersForReports[report.OwnerId];
if (folderForThisReport) {
folderForThisReport.members.push(report);
}
}
}
ExportCommand.prototype.getDashboards = function() {
let query="Select Id, DeveloperName, FolderId from Dashboard";
let dashboardsJSON=child_process.execFileSync('sfdx',
['force:data:soql:query',
'-q', query,
'-u', this.options.sfdxUser,
'--json']);
let dashboards=JSON.parse(dashboardsJSON);
for (var idx=0; idx<dashboards.result.records.length; idx++) {
var dashboard=dashboards.result.records[idx];
var foldersForDashboards=this.foldersByType['Dashboard'];
var folderForThisDashboard=foldersForDashboards[dashboard.FolderId];
if (folderForThisDashboard) {
folderForThisDashboard.members.push(dashboard);
}
}
}
ExportCommand.prototype.getDocuments = function() {
let query="Select Id, DeveloperName, FolderId from Document";
let documentsJSON=child_process.execFileSync('sfdx',
['force:data:soql:query',
'-q', query,
'-u', this.options.sfdxUser,
'--json']);
let documents=JSON.parse(documentsJSON);
for (var idx=0; idx<documents.result.records.length; idx++) {
var document=documents.result.records[idx];
var foldersForDocuments=this.foldersByType['Document'];
var folderForThisDocument=foldersForDocuments[document.FolderId];
if (folderForThisDocument) {
folderForThisDocument.members.push(document);
}
}
}
ExportCommand.prototype.getEmailTemplates = function() {
let query="Select Id, DeveloperName, FolderId from EmailTemplate";
let templateJSON=child_process.execFileSync('sfdx',
['force:data:soql:query',
'-q', query,
'-u', this.options.sfdxUser,
'--json']);
let templates=JSON.parse(templateJSON);
for (var idx=0; idx<templates.result.records.length; idx++) {
var template=templates.result.records[idx];
var foldersForTemplates=this.foldersByType['Email'];
var folderForThisTemplate=foldersForTemplates[template.FolderId];
if (folderForThisTemplate) {
folderForThisTemplate.members.push(template);
}
}
}
/*
* Extract all metadata objects names in the org
*/
ExportCommand.prototype.getAllMetadata=function() {
let metataDataJSON=child_process.execFileSync('sfdx',
['force:mdapi:describemetadata',
'-u', this.options.sfdxUser,
'--json']);
let metadatas=JSON.parse(metataDataJSON);
for (var idx=0; idx<metadatas.result.metadataObjects.length; idx++) {
allMetadataNames.push(metadatas.result.metadataObjects[idx].xmlName);
}
}
module.exports=ExportCommand; | ExportCommand |
lib.rs | //! A [`metrics`][metrics]-compatible exporter that outputs metrics to clients over TCP.
//!
//! This exporter creates a TCP server, that when connected to, will stream individual metrics to
//! the client using a Protocol Buffers encoding.
//!
//! # Backpressure
//! The exporter has configurable buffering, which allows users to trade off how many metrics they
//! want to be queued up at any given time. This buffer limit applies both to incoming metrics, as
//! well as the individual buffers for each connected client.
//!
//! By default, the buffer limit is set at 1024 metrics. When the incoming buffer -- metrics being
//! fed to the exported -- is full, metrics will be dropped. If a client's buffer is full,
//! potentially due to slow network conditions or slow processing, then messages in the client's
//! buffer will be dropped in FIFO order in order to allow the exporter to continue fanning out
//! metrics to clients.
//!
//! If no buffer limit is set, then te exporter will ingest and enqueue as many metrics as possible,
//! potentially up until the point of memory exhaustion. A buffer limit is advised for this reason,
//! even if it is many multiples of the default.
//!
//! # Encoding
//! Metrics are encoded using Protocol Buffers. The protocol file can be found in the repository at
//! `proto/event.proto`.
//!
//! # Usage
//! The TCP exporter can be constructed by creating a [`TcpBuilder`], configuring it as needed, and
//! calling [`TcpBuilder::install`] to both spawn the TCP server as well as install the exporter
//! globally.
//!
//! If necessary, the recorder itself can be returned so that it can be composed separately, while
//! still installing the TCP server itself, by calling [`TcpBuilder::build`].
//!
//! ```
//! # use metrics_exporter_tcp::TcpBuilder;
//! # fn direct() {
//! // Install the exporter directly:
//! let builder = TcpBuilder::new();
//! builder.install().expect("failed to install TCP exporter");
//!
//! // Or install the TCP server and get the recorder:
//! let builder = TcpBuilder::new();
//! let recorder = builder.build().expect("failed to install TCP exporter");
//! # }
//! ```
//!
//! [metrics]: https://docs.rs/metrics
#![deny(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg), deny(broken_intra_doc_links))]
use std::io::{self, Write};
use std::net::SocketAddr;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use std::thread;
use std::time::SystemTime;
use std::{
collections::{BTreeMap, HashMap, VecDeque},
sync::atomic::AtomicUsize,
};
use bytes::Bytes;
use crossbeam_channel::{bounded, unbounded, Receiver, Sender};
use metrics::{GaugeValue, Key, Recorder, SetRecorderError, Unit};
use mio::{
net::{TcpListener, TcpStream},
Events, Interest, Poll, Token, Waker,
};
use prost::{EncodeError, Message};
use tracing::{error, trace, trace_span};
const WAKER: Token = Token(0);
const LISTENER: Token = Token(1);
const START_TOKEN: Token = Token(2);
const CLIENT_INTEREST: Interest = Interest::READABLE.add(Interest::WRITABLE);
mod proto {
include!(concat!(env!("OUT_DIR"), "/event.proto.rs"));
}
use self::proto::metadata::MetricType;
enum MetricValue {
Counter(u64),
Gauge(GaugeValue),
Histogram(f64),
}
enum Event {
Metadata(Key, MetricType, Option<Unit>, Option<&'static str>),
Metric(Key, MetricValue),
}
/// Errors that could occur while installing a TCP recorder/exporter.
#[derive(Debug)]
pub enum Error {
/// Creating the networking event loop did not succeed.
Io(io::Error),
/// Installing the recorder did not succeed.
Recorder(SetRecorderError),
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Self {
Error::Io(e)
}
}
impl From<SetRecorderError> for Error {
fn from(e: SetRecorderError) -> Self {
Error::Recorder(e)
}
}
#[derive(Clone)]
struct State {
client_count: Arc<AtomicUsize>,
should_send: Arc<AtomicBool>,
waker: Arc<Waker>,
}
impl State {
pub fn from_waker(waker: Waker) -> State {
State {
client_count: Arc::new(AtomicUsize::new(0)),
should_send: Arc::new(AtomicBool::new(false)),
waker: Arc::new(waker),
}
}
pub fn should_send(&self) -> bool {
self.should_send.load(Ordering::Acquire)
}
pub fn increment_clients(&self) {
self.client_count.fetch_add(1, Ordering::AcqRel);
self.should_send.store(true, Ordering::Release);
}
pub fn decrement_clients(&self) {
let count = self.client_count.fetch_sub(1, Ordering::AcqRel);
if count == 1 {
self.should_send.store(false, Ordering::Release);
}
}
pub fn wake(&self) {
let _ = self.waker.wake();
}
}
/// A TCP recorder.
pub struct TcpRecorder {
tx: Sender<Event>,
state: State,
}
/// Builder for creating and installing a TCP recorder/exporter.
pub struct TcpBuilder {
listen_addr: SocketAddr,
buffer_size: Option<usize>,
}
impl TcpBuilder {
/// Creates a new `TcpBuilder`.
pub fn new() -> TcpBuilder {
TcpBuilder {
listen_addr: ([0, 0, 0, 0], 5000).into(),
buffer_size: Some(1024),
}
}
/// Sets the listen address.
///
/// The exporter will accept connections on this address and immediately begin forwarding
/// metrics to the client.
///
/// Defaults to `0.0.0.0:5000`.
pub fn listen_address<A>(mut self, addr: A) -> TcpBuilder
where
A: Into<SocketAddr>,
{
self.listen_addr = addr.into();
self
}
/// Sets the buffer size for internal operations.
///
/// The buffer size controls two operational aspects: the number of metrics processed
/// per iteration of the event loop, and the number of buffered metrics each client
/// can hold.
///
/// This setting allows trading off responsiveness for throughput, where a smaller buffer
/// size will ensure that metrics are pushed to clients sooner, versus a larger buffer
/// size that allows us to push more at a time.
///
/// As well, the larger the buffer, the more messages a client can temporarily hold.
/// Clients have a circular buffer implementation so if their buffers are full, metrics
/// will be dropped as necessary to avoid backpressure in the recorder.
pub fn buffer_size(mut self, size: Option<usize>) -> TcpBuilder {
self.buffer_size = size;
self
}
/// Installs the recorder and exporter.
///
/// An error will be returned if there's an issue with creating the TCP server or with
/// installing the recorder as the global recorder.
pub fn install(self) -> Result<(), Error> {
let recorder = self.build()?;
metrics::set_boxed_recorder(Box::new(recorder))?;
Ok(())
}
/// Builds and installs the exporter, but returns the recorder.
///
/// In most cases, users should prefer to use [`TcpBuilder::install`] to create and install
/// the recorder and exporter automatically for them. If a caller is combining recorders,
/// however, then this method allows the caller the flexibility to do so.
pub fn build(self) -> Result<TcpRecorder, Error> {
let buffer_size = self.buffer_size;
let (tx, rx) = match buffer_size {
None => unbounded(),
Some(size) => bounded(size),
};
let poll = Poll::new()?;
let waker = Waker::new(poll.registry(), WAKER)?;
let mut listener = TcpListener::bind(self.listen_addr)?;
poll.registry()
.register(&mut listener, LISTENER, Interest::READABLE)?;
let state = State::from_waker(waker);
let recorder = TcpRecorder {
tx,
state: state.clone(),
};
thread::spawn(move || run_transport(poll, listener, rx, state, buffer_size));
Ok(recorder)
}
}
impl Default for TcpBuilder {
fn default() -> Self {
TcpBuilder::new()
}
}
impl TcpRecorder {
fn register_metric(
&self,
key: Key,
metric_type: MetricType,
unit: Option<Unit>,
description: Option<&'static str>,
) {
let _ = self
.tx
.try_send(Event::Metadata(key, metric_type, unit, description));
self.state.wake();
}
fn push_metric(&self, key: Key, value: MetricValue) {
if self.state.should_send() {
let _ = self.tx.try_send(Event::Metric(key, value));
self.state.wake();
}
}
}
impl Recorder for TcpRecorder {
fn register_counter(&self, key: Key, unit: Option<Unit>, description: Option<&'static str>) {
self.register_metric(key, MetricType::Counter, unit, description);
}
fn register_gauge(&self, key: Key, unit: Option<Unit>, description: Option<&'static str>) {
self.register_metric(key, MetricType::Gauge, unit, description);
}
fn register_histogram(&self, key: Key, unit: Option<Unit>, description: Option<&'static str>) {
self.register_metric(key, MetricType::Histogram, unit, description);
}
fn increment_counter(&self, key: Key, value: u64) {
self.push_metric(key, MetricValue::Counter(value));
}
fn update_gauge(&self, key: Key, value: GaugeValue) {
self.push_metric(key, MetricValue::Gauge(value));
}
fn record_histogram(&self, key: Key, value: f64) {
self.push_metric(key, MetricValue::Histogram(value));
}
}
fn run_transport(
mut poll: Poll,
listener: TcpListener,
rx: Receiver<Event>,
state: State,
buffer_size: Option<usize>,
) {
let buffer_limit = buffer_size.unwrap_or(std::usize::MAX);
let mut events = Events::with_capacity(1024);
let mut clients = HashMap::new();
let mut clients_to_remove = Vec::new();
let mut metadata = HashMap::new();
let mut next_token = START_TOKEN;
let mut buffered_pmsgs = VecDeque::with_capacity(buffer_limit);
loop {
let _span = trace_span!("transport");
// Poll until we get something. All events -- metrics wake-ups and network I/O -- flow
// through here so we can block without issue.
let _evspan = trace_span!("event loop");
if let Err(e) = poll.poll(&mut events, None) {
error!(error = %e, "error during poll");
continue;
}
drop(_evspan);
// Technically, this is an abuse of size_hint() but Mio will return the number of events
// for both parts of the tuple.
trace!(events = events.iter().size_hint().0, "return from poll");
let _pspan = trace_span!("process events");
for event in events.iter() {
match event.token() {
WAKER => {
// Read until we hit our buffer limit or there are no more messages.
let _mrxspan = trace_span!("metrics in");
loop {
if buffered_pmsgs.len() >= buffer_limit {
// We didn't drain ourselves here, so schedule a future wake so we
// continue to drain remaining metrics.
state.wake();
break;
}
let msg = match rx.try_recv() {
Ok(msg) => msg,
Err(e) if e.is_empty() => {
trace!("metric rx drained");
break;
} | };
match msg {
Event::Metadata(key, metric_type, unit, desc) => {
let entry = metadata
.entry(key)
.or_insert_with(|| (metric_type, None, None));
let (_, uentry, dentry) = entry;
*uentry = unit;
*dentry = desc;
}
Event::Metric(key, value) => {
match convert_metric_to_protobuf_encoded(key, value) {
Ok(pmsg) => buffered_pmsgs.push_back(pmsg),
Err(e) => error!(error = ?e, "error encoding metric"),
}
}
}
}
drop(_mrxspan);
if buffered_pmsgs.is_empty() {
trace!("woken for metrics but no pmsgs buffered");
continue;
}
// Now fan out each of these items to each client.
for (token, (conn, wbuf, msgs)) in clients.iter_mut() {
// Before we potentially do any draining, try and drive the connection to
// make sure space is freed up as much as possible.
let done = drive_connection(conn, wbuf, msgs);
if done {
clients_to_remove.push(*token);
state.decrement_clients();
continue;
}
// With the encoded metrics, we push them into each client's internal
// list. We try to write as many of those buffers as possible to the
// client before being told to back off. If we encounter a partial write
// of a buffer, we store the remaining of that message in a special field
// so that we don't write incomplete metrics to the client.
//
// If there are more messages to hand off to a client than the client's
// internal list has room for, we remove as many as needed to do so. This
// means we prioritize sending newer metrics if connections are backed up.
let available = if msgs.len() < buffer_limit {
buffer_limit - msgs.len()
} else {
0
};
let to_drain = buffered_pmsgs.len().saturating_sub(available);
let _ = msgs.drain(0..to_drain);
msgs.extend(buffered_pmsgs.iter().take(buffer_limit).cloned());
let done = drive_connection(conn, wbuf, msgs);
if done {
clients_to_remove.push(*token);
state.decrement_clients();
}
}
// We've pushed each metric into each client's internal list, so we can clear
// ourselves and continue on.
buffered_pmsgs.clear();
// Remove any clients that were done.
for token in clients_to_remove.drain(..) {
if let Some((conn, _, _)) = clients.get_mut(&token) {
trace!(?conn, ?token, "removing client");
clients.remove(&token);
state.decrement_clients();
}
}
}
LISTENER => {
// Accept as many new connections as we can.
loop {
match listener.accept() {
Ok((mut conn, _)) => {
// Get our client's token and register the connection.
let token = next(&mut next_token);
poll.registry()
.register(&mut conn, token, CLIENT_INTEREST)
.expect("failed to register interest for client connection");
state.increment_clients();
// Start tracking them, and enqueue all of the metadata.
let metadata = generate_metadata_messages(&metadata);
clients
.insert(token, (conn, None, metadata))
.ok_or(())
.expect_err("client mapped to existing token!");
}
Err(ref e) if would_block(e) => break,
Err(e) => {
error!("caught error while accepting client connections: {:?}", e);
return;
}
}
}
}
token => {
if event.is_writable() {
if let Some((conn, wbuf, msgs)) = clients.get_mut(&token) {
let done = drive_connection(conn, wbuf, msgs);
if done {
trace!(?conn, ?token, "removing client");
clients.remove(&token);
state.decrement_clients();
}
}
}
}
}
}
}
}
fn generate_metadata_messages(
metadata: &HashMap<Key, (MetricType, Option<Unit>, Option<&'static str>)>,
) -> VecDeque<Bytes> {
let mut bufs = VecDeque::new();
for (key, (metric_type, unit, desc)) in metadata.iter() {
let msg = convert_metadata_to_protobuf_encoded(key, *metric_type, unit.clone(), *desc)
.expect("failed to encode metadata buffer");
bufs.push_back(msg);
}
bufs
}
#[tracing::instrument(skip(wbuf, msgs))]
fn drive_connection(
conn: &mut TcpStream,
wbuf: &mut Option<Bytes>,
msgs: &mut VecDeque<Bytes>,
) -> bool {
trace!(?conn, "driving client");
loop {
let mut buf = match wbuf.take() {
// Send the leftover buffer first, if we have one.
Some(buf) => buf,
None => match msgs.pop_front() {
Some(msg) => msg,
None => {
trace!("client write queue drained");
return false;
}
},
};
match conn.write(&buf) {
// Zero write = client closed their connection, so remove 'em.
Ok(0) => {
trace!(?conn, "zero write, closing client");
return true;
}
Ok(n) if n < buf.len() => {
// We sent part of the buffer, but not everything. Keep track of the remaining
// chunk of the buffer. TODO: do we need to reregister ourselves to track writable
// status??
let remaining = buf.split_off(n);
trace!(
?conn,
written = n,
remaining = remaining.len(),
"partial write"
);
wbuf.replace(remaining);
return false;
}
Ok(_) => continue,
Err(ref e) if would_block(e) => return false,
Err(ref e) if interrupted(e) => return drive_connection(conn, wbuf, msgs),
Err(e) => {
error!(?conn, error = %e, "write failed");
return true;
}
}
}
}
fn convert_metadata_to_protobuf_encoded(
key: &Key,
metric_type: MetricType,
unit: Option<Unit>,
desc: Option<&'static str>,
) -> Result<Bytes, EncodeError> {
let name = key.name().to_string();
let metadata = proto::Metadata {
name,
metric_type: metric_type.into(),
unit: unit.map(|u| proto::metadata::Unit::UnitValue(u.as_str().to_owned())),
description: desc.map(|d| proto::metadata::Description::DescriptionValue(d.to_owned())),
};
let event = proto::Event {
event: Some(proto::event::Event::Metadata(metadata)),
};
let mut buf = Vec::new();
event.encode_length_delimited(&mut buf)?;
Ok(Bytes::from(buf))
}
fn convert_metric_to_protobuf_encoded(key: Key, value: MetricValue) -> Result<Bytes, EncodeError> {
let name = key.name().to_string();
let labels = key
.labels()
.map(|label| (label.key().to_owned(), label.value().to_owned()))
.collect::<BTreeMap<_, _>>();
let mvalue = match value {
MetricValue::Counter(cv) => proto::metric::Value::Counter(proto::Counter { value: cv }),
MetricValue::Gauge(gv) => match gv {
GaugeValue::Absolute(val) => proto::metric::Value::Gauge(proto::Gauge {
value: Some(proto::gauge::Value::Absolute(val)),
}),
GaugeValue::Increment(val) => proto::metric::Value::Gauge(proto::Gauge {
value: Some(proto::gauge::Value::Increment(val)),
}),
GaugeValue::Decrement(val) => proto::metric::Value::Gauge(proto::Gauge {
value: Some(proto::gauge::Value::Decrement(val)),
}),
},
MetricValue::Histogram(hv) => {
proto::metric::Value::Histogram(proto::Histogram { value: hv })
}
};
let now: prost_types::Timestamp = SystemTime::now().into();
let metric = proto::Metric {
name,
labels,
timestamp: Some(now),
value: Some(mvalue),
};
let event = proto::Event {
event: Some(proto::event::Event::Metric(metric)),
};
let mut buf = Vec::new();
event.encode_length_delimited(&mut buf)?;
Ok(Bytes::from(buf))
}
fn next(current: &mut Token) -> Token {
let next = current.0;
current.0 += 1;
Token(next)
}
fn would_block(err: &io::Error) -> bool {
err.kind() == io::ErrorKind::WouldBlock
}
fn interrupted(err: &io::Error) -> bool {
err.kind() == io::ErrorKind::Interrupted
} | // If our sender is dead, we can't do anything else, so just return.
Err(_) => return, |
andy.ts | // Adding a reference to get it to be included even though it
// is not used in the prod build by any code | export * from './midi';
export * from './metronome'; | // import './midi/patchBank';
export * from './digital'; |
handshake.rs | use crate::{convert, gen, PROTOCOL_VERSION};
use chain_core::property;
use network_core::client::block::HandshakeError;
use futures::prelude::*;
use std::marker::PhantomData;
type ResponseFuture = tower_grpc::client::unary::ResponseFuture<
gen::node::HandshakeResponse,
tower_hyper::client::ResponseFuture<hyper::client::conn::ResponseFuture>,
hyper::Body,
>;
pub struct HandshakeFuture<Id> {
inner: ResponseFuture,
_phantom: PhantomData<Id>,
}
impl<Id> HandshakeFuture<Id> {
pub fn new(inner: ResponseFuture) -> Self {
HandshakeFuture {
inner,
_phantom: PhantomData,
}
}
}
impl<Id> Future for HandshakeFuture<Id>
where
Id: property::BlockId + property::Deserialize,
{
type Item = Id;
type Error = HandshakeError;
fn | (&mut self) -> Poll<Self::Item, Self::Error> {
let res = match self.inner.poll() {
Ok(Async::NotReady) => return Ok(Async::NotReady),
Ok(Async::Ready(res)) => res.into_inner(),
Err(status) => return Err(HandshakeError::Rpc(convert::error_from_grpc(status))),
};
if res.version != PROTOCOL_VERSION {
return Err(HandshakeError::UnsupportedVersion(
res.version.to_string().into(),
));
}
let block0_id = convert::deserialize_bytes(&res.block0)?;
Ok(Async::Ready(block0_id))
}
}
| poll |
plugin.min.js | tinymce.PluginManager.add("emoticons",function(e,t){function | (){var e;return e='<table role="presentation" class="mce-grid">',tinymce.each(i,function(n){e+="<tr>",tinymce.each(n,function(n){var i=t+"/img/smiley-"+n+".gif";e+='<td><a href="#" data-mce-url="'+i+'" tabindex="-1"><img src="'+i+'" style="width: 18px; height: 18px"></a></td>'}),e+="</tr>"}),e+="</table>"}var i=[["cool","cry","embarassed","foot-in-mouth"],["frown","innocent","kiss","laughing"],["money-mouth","sealed","smile","surprised"],["tongue-out","undecided","wink","yell"]];e.addButton("emoticons",{type:"panelbutton",popoverAlign:"bc-tl",panel:{autohide:!0,html:n,onclick:function(t){var n=e.dom.getParent(t.target,"a");n&&(e.insertContent('<img src="'+n.getAttribute("data-mce-url")+'" />'),this.hide())}},tooltip:"Emoticons"})}); | n |
proxy_test.py | #!/usr/bin/env python2
# Copyright (c) 2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import socket
import traceback, sys
from binascii import hexlify
import time, os
from socks5 import Socks5Configuration, Socks5Command, Socks5Server, AddressType
from test_framework import BitcoinTestFramework
from util import *
'''
Test plan:
- Start bitcoind's with different proxy configurations
- Use addnode to initiate connections
- Verify that proxies are connected to, and the right connection command is given
- Proxy configurations to test on bitcoind side:
- `-proxy` (proxy everything)
- `-onion` (proxy just onions)
- `-proxyrandomize` Circuit randomization
- Proxy configurations to test on proxy side,
- support no authentication (other proxy)
- support no authentication + user/pass authentication (Tor)
- proxy on IPv6
- Create various proxies (as threads)
- Create bitcoinds that connect to them
- Manipulate the bitcoinds using addnode (onetry) an observe effects
addnode connect to IPv4
addnode connect to IPv6
addnode connect to onion
addnode connect to generic DNS name
'''
class ProxyTest(BitcoinTestFramework):
def __init__(self):
# Create two proxies on different ports
# ... one unauthenticated
self.conf1 = Socks5Configuration()
self.conf1.addr = ('127.0.0.1', 13000 + (os.getpid() % 1000))
self.conf1.unauth = True
self.conf1.auth = False
# ... one supporting authenticated and unauthenticated (Tor)
self.conf2 = Socks5Configuration()
self.conf2.addr = ('127.0.0.1', 14000 + (os.getpid() % 1000))
self.conf2.unauth = True
self.conf2.auth = True
# ... one on IPv6 with similar configuration
self.conf3 = Socks5Configuration()
self.conf3.af = socket.AF_INET6
self.conf3.addr = ('::1', 15000 + (os.getpid() % 1000))
self.conf3.unauth = True
self.conf3.auth = True
self.serv1 = Socks5Server(self.conf1)
self.serv1.start()
self.serv2 = Socks5Server(self.conf2)
self.serv2.start()
self.serv3 = Socks5Server(self.conf3)
self.serv3.start()
def setup_nodes(self):
# Note: proxies are not used to connect to local nodes
# this is because the proxy to use is based on CService.GetNetwork(), which return NET_UNROUTABLE for localhost
return start_nodes(4, self.options.tmpdir, extra_args=[
['-listen', '-debug=net', '-debug=proxy', '-proxy=%s:%i' % (self.conf1.addr),'-proxyrandomize=1'],
['-listen', '-debug=net', '-debug=proxy', '-proxy=%s:%i' % (self.conf1.addr),'-onion=%s:%i' % (self.conf2.addr),'-proxyrandomize=0'],
['-listen', '-debug=net', '-debug=proxy', '-proxy=%s:%i' % (self.conf2.addr),'-proxyrandomize=1'],
['-listen', '-debug=net', '-debug=proxy', '-proxy=[%s]:%i' % (self.conf3.addr),'-proxyrandomize=0']
])
def node_test(self, node, proxies, auth):
rv = []
# Test: outgoing IPv4 connection through node
node.addnode("15.61.23.23:1234", "onetry")
cmd = proxies[0].queue.get()
assert(isinstance(cmd, Socks5Command))
# Note: bitcoind's SOCKS5 implementation only sends atyp DOMAINNAME, even if connecting directly to IPv4/IPv6
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, "15.61.23.23")
assert_equal(cmd.port, 1234)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
# Test: outgoing IPv6 connection through node
node.addnode("[1233:3432:2434:2343:3234:2345:6546:4534]:5443", "onetry")
cmd = proxies[1].queue.get()
assert(isinstance(cmd, Socks5Command))
# Note: bitcoind's SOCKS5 implementation only sends atyp DOMAINNAME, even if connecting directly to IPv4/IPv6
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, "1233:3432:2434:2343:3234:2345:6546:4534")
assert_equal(cmd.port, 5443)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
# Test: outgoing onion connection through node
node.addnode("Orboxvj7kcklujarx.onion:9116", "onetry")
cmd = proxies[2].queue.get()
assert(isinstance(cmd, Socks5Command))
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, "Orboxvj7kcklujarx.onion")
assert_equal(cmd.port, 9116)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
# Test: outgoing DNS name connection through node
node.addnode("node.noumenon:8333", "onetry")
cmd = proxies[3].queue.get()
assert(isinstance(cmd, Socks5Command))
assert_equal(cmd.atyp, AddressType.DOMAINNAME)
assert_equal(cmd.addr, "node.noumenon")
assert_equal(cmd.port, 8333)
if not auth:
assert_equal(cmd.username, None)
assert_equal(cmd.password, None)
rv.append(cmd)
return rv
def run_test(self):
# basic -proxy
|
if __name__ == '__main__':
ProxyTest().main()
| self.node_test(self.nodes[0], [self.serv1, self.serv1, self.serv1, self.serv1], False)
# -proxy plus -onion
self.node_test(self.nodes[1], [self.serv1, self.serv1, self.serv2, self.serv1], False)
# -proxy plus -onion, -proxyrandomize
rv = self.node_test(self.nodes[2], [self.serv2, self.serv2, self.serv2, self.serv2], True)
# Check that credentials as used for -proxyrandomize connections are unique
credentials = set((x.username,x.password) for x in rv)
assert_equal(len(credentials), 4)
# proxy on IPv6 localhost
self.node_test(self.nodes[3], [self.serv3, self.serv3, self.serv3, self.serv3], False) |
public-types.ts | export enum ViewMode {
QuarterDay = "Quarter Day",
HalfDay = "Half Day",
Day = "Day",
/** ISO-8601 week */
Week = "Week",
Month = "Month",
}
export type TaskType = "task" | "milestone" | "project";
export interface Task {
id: string;
type: TaskType;
name: string;
start: Date;
end: Date;
/**
* From 0 to 100
*/
progress: number;
styles?: {
backgroundColor?: string;
backgroundSelectedColor?: string;
progressColor?: string;
progressSelectedColor?: string;
};
isDisabled?: boolean;
project?: string;
dependencies?: string[];
hideChildren?: boolean;
parentId?: any;
title?: string;
}
export interface EventOption {
/**
* Time step value for date changes.
*/
timeStep?: number;
/**
* Invokes on bar select on unselect.
*/
onSelect?: (task: Task, isSelected: boolean) => void;
/**
* Invokes on bar double click.
*/
onDoubleClick?: (task: Task) => void;
/**
* Invokes on end and start time change. Chart undoes operation if method return false or error.
*/
onDateChange?: (
task: Task,
children: Task[]
) => void | boolean | Promise<void> | Promise<boolean>;
/**
* Invokes on progress change. Chart undoes operation if method return false or error.
*/ | ) => void | boolean | Promise<void> | Promise<boolean>;
/**
* Invokes on delete selected task. Chart undoes operation if method return false or error.
*/
onDelete?: (task: Task) => void | boolean | Promise<void> | Promise<boolean>;
/**
* Invokes on expander on task list
*/
onExpanderClick?: (task: Task) => void;
onVisibilityChanged?: (data: any) => void;
}
export interface DisplayOption {
viewMode?: ViewMode;
/**
* Specifies the month name language. Able formats: ISO 639-2, Java Locale
*/
locale?: string;
rtl?: boolean;
}
export interface StylingOption {
headerHeight?: number;
columnWidth?: number;
listCellWidth?: string;
rowHeight?: number;
ganttHeight?: number;
barCornerRadius?: number;
handleWidth?: number;
fontFamily?: string;
fontSize?: string;
/**
* How many of row width can be taken by task.
* From 0 to 100
*/
barFill?: number;
barProgressColor?: string;
barProgressSelectedColor?: string;
barBackgroundColor?: string;
barBackgroundSelectedColor?: string;
projectProgressColor?: string;
projectProgressSelectedColor?: string;
projectBackgroundColor?: string;
projectBackgroundSelectedColor?: string;
milestoneBackgroundColor?: string;
milestoneBackgroundSelectedColor?: string;
arrowColor?: string;
arrowIndent?: number;
todayColor?: string;
TooltipContent?: React.FC<{
task: Task;
fontSize: string;
fontFamily: string;
}>;
TaskListHeader?: React.FC<{
headerHeight: number;
rowWidth: string;
fontFamily: string;
fontSize: string;
}>;
TaskListTable?: React.FC<{
rowHeight: number;
rowWidth: string;
fontFamily: string;
fontSize: string;
locale: string;
tasks: Task[];
selectedTaskId: string;
/**
* Sets selected task by id
*/
setSelectedTask: (taskId: string) => void;
onExpanderClick: (task: Task) => void;
}>;
}
export interface GanttProps extends EventOption, DisplayOption, StylingOption {
tasks: Task[];
} | onProgressChange?: (
task: Task,
children: Task[] |
a-tic-tac-toe-tomek.py | def transpose(grid):
return [''.join(line) for line in zip(*grid)]
def chk_hori(grid):
for line in grid:
if all(c in 'XT' for c in line):
return 'X won'
if all(c in 'OT' for c in line):
return 'O won'
def chk_diag(grid):
if all(grid[i][i] in 'XT' for i in range(len(grid))):
return 'X won'
if all(grid[i][i] in 'OT' for i in range(len(grid))):
return 'O won'
def chk_won(grid):
|
def chk_full(grid):
return not any('.' in line for line in grid)
for case in range(int(input())):
grid = [input() for _ in range(4)]
input()
answer = chk_won(grid)
if not answer:
answer = 'Draw' if chk_full(grid) else 'Game has not completed'
print('Case #{}: {}'.format(case+1, answer))
| for _ in range(2):
for chk in [chk_hori, chk_diag]:
answer = chk(grid)
if answer:
return answer
grid = transpose(reversed(grid)) |
index.tsx | // tslint:disable: no-console react-this-binding-issue
import * as React from "react";
import * as ReactDOM from "react-dom";
import { GatewayExample } from "./main";
import "./style.scss";
const Index = () => {
return <div className="test-background">
<GatewayExample />
</div>;
};
| ReactDOM.render(<Index />, document.getElementById("root") as HTMLElement); | |
offset_date_time.rs | #[cfg(feature = "std")]
use crate::error;
use crate::{
format::parse::{parse, ParsedItems},
internals, Date, DeferredFormat, Duration, Format, ParseResult, PrimitiveDateTime, Time,
UtcOffset, Weekday,
};
#[cfg(not(feature = "std"))]
use alloc::{
borrow::ToOwned,
string::{String, ToString},
};
#[cfg(feature = "std")]
use core::convert::From;
use core::{
cmp::Ordering,
fmt::{self, Display},
hash::{Hash, Hasher},
ops::{Add, AddAssign, Sub, SubAssign},
time::Duration as StdDuration,
};
#[cfg(feature = "std")]
use standback::convert::TryFrom;
#[cfg(feature = "serde")]
use standback::convert::TryInto;
#[cfg(feature = "std")]
use std::time::SystemTime;
/// A [`PrimitiveDateTime`] with a [`UtcOffset`].
///
/// All comparisons are performed using the UTC time.
// Internally, an `OffsetDateTime` is a thin wrapper around a
// [`PrimitiveDateTime`] coupled with a [`UtcOffset`]. This offset is added to
// the date, time, or datetime as necessary for presentation or returning from a
// function.
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(into = "crate::serde::PrimitiveDateTime"))]
#[derive(Debug, Clone, Copy, Eq)]
pub struct OffsetDateTime {
/// The `PrimitiveDateTime`, which is _always_ UTC.
utc_datetime: PrimitiveDateTime,
/// The `UtcOffset`, which will be added to the `PrimitiveDateTime` as necessary.
offset: UtcOffset,
}
#[cfg(feature = "serde")]
impl<'a> serde::Deserialize<'a> for OffsetDateTime {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'a>,
{
crate::serde::PrimitiveDateTime::deserialize(deserializer)?
.try_into()
.map_err(serde::de::Error::custom)
}
}
impl OffsetDateTime {
/// Create a new `OffsetDateTime` from the provided `PrimitiveDateTime` and
/// `UtcOffset`. The `PrimitiveDateTime` is assumed to be in the provided
/// offset.
// TODO Should this be made public?
pub(crate) fn new_assuming_offset(utc_datetime: PrimitiveDateTime, offset: UtcOffset) -> Self {
Self {
utc_datetime: utc_datetime - offset.as_duration(),
offset,
}
}
/// Create a new `OffsetDateTime` from the provided `PrimitiveDateTime` and
/// `UtcOffset`. The `PrimitiveDateTime` is assumed to be in UTC.
// TODO Should this be made public?
pub(crate) const fn new_assuming_utc(utc_datetime: PrimitiveDateTime) -> Self {
Self {
utc_datetime,
offset: UtcOffset::UTC,
}
}
/// Create a new `OffsetDateTime` with the current date and time in UTC.
///
/// ```rust
/// # #![allow(deprecated)]
/// # use time::{OffsetDateTime, offset};
/// assert!(OffsetDateTime::now().year() >= 2019);
/// assert_eq!(OffsetDateTime::now().offset(), offset!(UTC));
/// ```
#[deprecated(
since = "0.2.11",
note = "This function returns a value with an offset of UTC, which is not apparent from \
its name alone. You should use `OffsetDateTime::now_utc()` instead."
)]
#[cfg(feature = "std")]
#[cfg_attr(__time_02_docs, doc(cfg(feature = "std")))]
pub fn now() -> Self {
SystemTime::now().into()
}
/// Create a new `OffsetDateTime` with the current date and time in UTC.
///
/// ```rust
/// # use time::{OffsetDateTime, offset};
/// assert!(OffsetDateTime::now_utc().year() >= 2019);
/// assert_eq!(OffsetDateTime::now_utc().offset(), offset!(UTC));
/// ```
#[cfg(feature = "std")]
#[cfg_attr(__time_02_docs, doc(cfg(feature = "std")))]
pub fn now_utc() -> Self {
SystemTime::now().into()
}
/// Create a new `OffsetDateTime` with the current date and time in the
/// local offset.
///
/// ```rust
/// # use time::OffsetDateTime;
/// assert!(OffsetDateTime::now_local().year() >= 2019);
/// ```
#[cfg(feature = "std")]
#[cfg_attr(__time_02_docs, doc(cfg(feature = "std")))]
pub fn now_local() -> Self {
let t = Self::now_utc();
t.to_offset(UtcOffset::local_offset_at(t))
}
/// Attempt to create a new `OffsetDateTime` with the current date and time
/// in the local offset. If the offset cannot be determined, an error is
/// returned.
///
/// ```rust
/// # use time::OffsetDateTime;
/// assert!(OffsetDateTime::try_now_local().is_ok());
/// ```
#[cfg(feature = "std")]
#[cfg_attr(__time_02_docs, doc(cfg(feature = "std")))]
pub fn try_now_local() -> Result<Self, error::IndeterminateOffset> {
let t = Self::now_utc();
Ok(t.to_offset(UtcOffset::try_local_offset_at(t)?))
}
/// Convert the `OffsetDateTime` from the current `UtcOffset` to the
/// provided `UtcOffset`.
///
/// ```rust
/// # use time::{date, offset};
/// assert_eq!(
/// date!(2000-01-01)
/// .midnight()
/// .assume_utc()
/// .to_offset(offset!(-1))
/// .year(),
/// 1999,
/// );
///
/// // Let's see what time Sydney's new year's celebration is in New York
/// // and Los Angeles.
///
/// // Construct midnight on new year's in Sydney. This is equivalent to
/// // 13:00 UTC.
/// let sydney = date!(2000-01-01).midnight().assume_offset(offset!(+11));
/// let new_york = sydney.to_offset(offset!(-5));
/// let los_angeles = sydney.to_offset(offset!(-8));
/// assert_eq!(sydney.hour(), 0);
/// assert_eq!(new_york.hour(), 8);
/// assert_eq!(los_angeles.hour(), 5);
/// ```
pub const fn to_offset(self, offset: UtcOffset) -> Self {
Self {
utc_datetime: self.utc_datetime,
offset,
}
}
/// Midnight, 1 January, 1970 (UTC).
///
/// ```rust
/// # use time::{date, OffsetDateTime};
/// assert_eq!(
/// OffsetDateTime::unix_epoch(),
/// date!(1970-01-01)
/// .midnight()
/// .assume_utc(),
/// );
/// ```
pub const fn unix_epoch() -> Self {
internals::Date::from_yo_unchecked(1970, 1)
.midnight()
.assume_utc()
}
/// Create an `OffsetDateTime` from the provided [Unix timestamp](https://en.wikipedia.org/wiki/Unix_time).
///
/// ```rust
/// # use time::{date, OffsetDateTime};
/// assert_eq!(
/// OffsetDateTime::from_unix_timestamp(0),
/// OffsetDateTime::unix_epoch(),
/// );
/// assert_eq!(
/// OffsetDateTime::from_unix_timestamp(1_546_300_800),
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc(),
/// );
/// ```
///
/// If you have a timestamp-nanosecond pair, you can use something along the
/// lines of the following:
///
/// ```rust
/// # use time::{Duration, OffsetDateTime, ext::NumericalDuration};
/// let (timestamp, nanos) = (1, 500_000_000);
/// assert_eq!(
/// OffsetDateTime::from_unix_timestamp(timestamp) + Duration::nanoseconds(nanos),
/// OffsetDateTime::unix_epoch() + 1.5.seconds()
/// );
/// ```
pub fn from_unix_timestamp(timestamp: i64) -> Self {
OffsetDateTime::unix_epoch() + Duration::seconds(timestamp)
}
/// Construct an `OffsetDateTime` from the provided Unix timestamp (in
/// nanoseconds).
///
/// ```rust
/// # use time::{date, OffsetDateTime};
/// assert_eq!(
/// OffsetDateTime::from_unix_timestamp_nanos(0),
/// OffsetDateTime::unix_epoch(),
/// );
/// assert_eq!(
/// OffsetDateTime::from_unix_timestamp_nanos(1_546_300_800_000_000_000),
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc(),
/// );
/// ```
///
/// Note that the range of timestamps possible here is far larger than the
/// valid range of dates storable in this crate. It is the _user's
/// responsibility_ to ensure the timestamp provided as a parameter is
/// valid. No behavior is guaranteed if this parameter would not result in a
/// valid value.
pub fn from_unix_timestamp_nanos(timestamp: i128) -> Self {
OffsetDateTime::unix_epoch() + Duration::nanoseconds_i128(timestamp)
}
/// Get the `UtcOffset`.
///
/// ```rust
/// # use time::{date, offset};
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .offset(),
/// offset!(UTC),
/// );
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_offset(offset!(+1))
/// .offset(),
/// offset!(+1),
/// );
/// ```
pub const fn offset(self) -> UtcOffset {
self.offset
}
/// Get the [Unix timestamp](https://en.wikipedia.org/wiki/Unix_time).
///
/// ```rust
/// # use time::{date, offset};
/// assert_eq!(
/// date!(1970-01-01)
/// .midnight()
/// .assume_utc()
/// .timestamp(),
/// 0,
/// );
/// assert_eq!(
/// date!(1970-01-01)
/// .midnight()
/// .assume_utc()
/// .to_offset(offset!(-1))
/// .timestamp(),
/// 0,
/// );
/// ```
pub fn timestamp(self) -> i64 {
(self - Self::unix_epoch()).whole_seconds()
}
/// Get the Unix timestamp in nanoseconds.
///
/// ```rust
/// use time::{date, offset, time};
/// assert_eq!(
/// date!(1970-01-01)
/// .midnight()
/// .assume_utc()
/// .timestamp_nanos(),
/// 0,
/// );
/// assert_eq!(
/// date!(1970-01-01)
/// .with_time(time!(1:00))
/// .assume_utc()
/// .to_offset(offset!(-1))
/// .timestamp_nanos(),
/// 3_600_000_000_000,
/// );
/// ```
pub fn timestamp_nanos(self) -> i128 {
(self - Self::unix_epoch()).whole_nanoseconds()
}
/// Get the `Date` in the stored offset.
///
/// ```rust
/// # use time::{date, offset};
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .date(),
/// date!(2019-01-01),
/// );
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .to_offset(offset!(-1))
/// .date(),
/// date!(2018-12-31),
/// );
/// ```
pub fn date(self) -> Date {
(self.utc_datetime + self.offset.as_duration()).date()
}
/// Get the `Time` in the stored offset.
///
/// ```rust
/// # use time::{date, offset, time};
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .time(),
/// time!(0:00)
/// );
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .to_offset(offset!(-1))
/// .time(),
/// time!(23:00)
/// );
/// ```
pub fn time(self) -> Time {
(self.utc_datetime + self.offset.as_duration()).time()
}
/// Get the year of the date in the stored offset.
///
/// ```rust
/// # use time::{date, offset, time};
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .year(),
/// 2019,
/// );
/// assert_eq!(
/// date!(2019-12-31)
/// .with_time(time!(23:00))
/// .assume_utc()
/// .to_offset(offset!(+1))
/// .year(),
/// 2020,
/// );
/// assert_eq!(
/// date!(2020-01-01)
/// .midnight()
/// .assume_utc()
/// .year(),
/// 2020,
/// );
/// ```
pub fn year(self) -> i32 {
self.date().year()
}
/// Get the month of the date in the stored offset. If fetching both the
/// month and day, it is more efficient to use
/// [`OffsetDateTime::month_day`].
///
/// The returned value will always be in the range `1..=12`.
///
/// ```rust
/// # use time::{date, offset, time};
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .month(),
/// 1,
/// );
/// assert_eq!(
/// date!(2019-12-31)
/// .with_time(time!(23:00))
/// .assume_utc()
/// .to_offset(offset!(+1))
/// .month(),
/// 1,
/// );
/// ```
pub fn month(self) -> u8 {
self.date().month()
}
/// Get the day of the date in the stored offset. If fetching both the month
/// and day, it is more efficient to use [`OffsetDateTime::month_day`].
///
/// The returned value will always be in the range `1..=31`.
///
/// ```rust
/// # use time::{date, offset, time};
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .day(),
/// 1,
/// );
/// assert_eq!(
/// date!(2019-12-31)
/// .with_time(time!(23:00))
/// .assume_utc()
/// .to_offset(offset!(+1))
/// .day(),
/// 1,
/// );
/// ```
pub fn day(self) -> u8 {
self.date().day()
}
/// Get the month and day of the date in the stored offset.
///
/// The month component will always be in the range `1..=12`;
/// the day component in `1..=31`.
///
/// ```rust
/// # use time::{date, offset, time};
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .month_day(),
/// (1, 1),
/// );
/// assert_eq!(
/// date!(2019-12-31)
/// .with_time(time!(23:00))
/// .assume_utc()
/// .to_offset(offset!(+1))
/// .month_day(),
/// (1, 1),
/// );
/// ```
pub fn month_day(self) -> (u8, u8) {
self.date().month_day()
}
/// Get the day of the year of the date in the stored offset.
///
/// The returned value will always be in the range `1..=366`.
///
/// ```rust
/// # use time::{date, offset, time};
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .ordinal(),
/// 1,
/// );
/// assert_eq!(
/// date!(2019-12-31)
/// .with_time(time!(23:00))
/// .assume_utc()
/// .to_offset(offset!(+1))
/// .ordinal(),
/// 1,
/// );
/// ```
pub fn ordinal(self) -> u16 {
self.date().ordinal()
}
/// Get the ISO 8601 year and week number in the stored offset.
///
/// ```rust
/// # use time::date;
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .iso_year_week(),
/// (2019, 1),
/// );
/// assert_eq!(
/// date!(2019-10-04)
/// .midnight()
/// .assume_utc()
/// .iso_year_week(),
/// (2019, 40),
/// );
/// assert_eq!(
/// date!(2020-01-01)
/// .midnight()
/// .assume_utc()
/// .iso_year_week(),
/// (2020, 1),
/// );
/// assert_eq!(
/// date!(2020-12-31)
/// .midnight()
/// .assume_utc()
/// .iso_year_week(),
/// (2020, 53),
/// );
/// assert_eq!(
/// date!(2021-01-01)
/// .midnight()
/// .assume_utc()
/// .iso_year_week(),
/// (2020, 53),
/// );
/// ```
pub fn iso_year_week(self) -> (i32, u8) {
self.date().iso_year_week()
}
/// Get the ISO week number of the date in the stored offset.
///
/// The returned value will always be in the range `1..=53`.
///
/// ```rust
/// # use time::date;
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .week(),
/// 1,
/// );
/// assert_eq!(
/// date!(2020-01-01)
/// .midnight()
/// .assume_utc()
/// .week(),
/// 1,
/// );
/// assert_eq!(
/// date!(2020-12-31)
/// .midnight()
/// .assume_utc()
/// .week(),
/// 53,
/// );
/// assert_eq!(
/// date!(2021-01-01)
/// .midnight()
/// .assume_utc()
/// .week(),
/// 53,
/// );
/// ```
pub fn week(self) -> u8 {
self.date().week()
}
/// Get the weekday of the date in the stored offset.
///
/// This current uses [Zeller's congruence](https://en.wikipedia.org/wiki/Zeller%27s_congruence)
/// internally.
///
/// ```rust
/// # use time::{date, Weekday::*};
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .weekday(),
/// Tuesday,
/// );
/// assert_eq!(
/// date!(2019-02-01)
/// .midnight()
/// .assume_utc()
/// .weekday(),
/// Friday,
/// );
/// assert_eq!(
/// date!(2019-03-01)
/// .midnight()
/// .assume_utc()
/// .weekday(),
/// Friday,
/// );
/// ```
pub fn weekday(self) -> Weekday {
self.date().weekday() |
/// Get the clock hour in the stored offset.
///
/// The returned value will always be in the range `0..24`.
///
/// ```rust
/// # use time::{date, time, offset};
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .hour(),
/// 0,
/// );
/// assert_eq!(
/// date!(2019-01-01)
/// .with_time(time!(23:59:59))
/// .assume_utc()
/// .to_offset(offset!(-2))
/// .hour(),
/// 21,
/// );
/// ```
pub fn hour(self) -> u8 {
self.time().hour()
}
/// Get the minute within the hour in the stored offset.
///
/// The returned value will always be in the range `0..60`.
///
/// ```rust
/// # use time::{date, offset, time};
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .minute(),
/// 0,
/// );
/// assert_eq!(
/// date!(2019-01-01)
/// .with_time(time!(23:59:59))
/// .assume_utc()
/// .to_offset(offset!(+0:30))
/// .minute(),
/// 29,
/// );
/// ```
pub fn minute(self) -> u8 {
self.time().minute()
}
/// Get the second within the minute in the stored offset.
///
/// The returned value will always be in the range `0..60`.
///
/// ```rust
/// # use time::{date, offset, time};
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .second(),
/// 0,
/// );
/// assert_eq!(
/// date!(2019-01-01)
/// .with_time(time!(23:59:59))
/// .assume_utc()
/// .to_offset(offset!(+0:00:30))
/// .second(),
/// 29,
/// );
/// ```
pub fn second(self) -> u8 {
self.time().second()
}
/// Get the milliseconds within the second in the stored offset.
///
/// The returned value will always be in the range `0..1_000`.
///
/// ```rust
/// # use time::{date, time};
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .millisecond(),
/// 0,
/// );
/// assert_eq!(
/// date!(2019-01-01)
/// .with_time(time!(23:59:59.999))
/// .assume_utc()
/// .millisecond(),
/// 999,
/// );
/// ```
pub fn millisecond(self) -> u16 {
self.time().millisecond()
}
/// Get the microseconds within the second in the stored offset.
///
/// The returned value will always be in the range `0..1_000_000`.
///
/// ```rust
/// # use time::{date, time};
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .microsecond(),
/// 0,
/// );
/// assert_eq!(
/// date!(2019-01-01)
/// .with_time(time!(23:59:59.999_999))
/// .assume_utc()
/// .microsecond(),
/// 999_999,
/// );
/// ```
pub fn microsecond(self) -> u32 {
self.time().microsecond()
}
/// Get the nanoseconds within the second in the stored offset.
///
/// The returned value will always be in the range `0..1_000_000_000`.
///
/// ```rust
/// # use time::{date, time};
/// assert_eq!(
/// date!(2019-01-01)
/// .midnight()
/// .assume_utc()
/// .nanosecond(),
/// 0,
/// );
/// assert_eq!(
/// date!(2019-01-01)
/// .with_time(time!(23:59:59.999_999_999))
/// .assume_utc()
/// .nanosecond(),
/// 999_999_999,
/// );
/// ```
pub fn nanosecond(self) -> u32 {
self.time().nanosecond()
}
}
/// Methods that allow formatting the `OffsetDateTime`.
impl OffsetDateTime {
/// Format the `OffsetDateTime` using the provided string.
///
/// ```rust
/// # use time::{date};
/// assert_eq!(
/// date!(2019-01-02)
/// .midnight()
/// .assume_utc()
/// .format("%F %r %z"),
/// "2019-01-02 12:00:00 am +0000",
/// );
/// ```
pub fn format(self, format: impl Into<Format>) -> String {
self.lazy_format(format).to_string()
}
/// Format the `OffsetDateTime` using the provided string.
///
/// ```rust
/// # use time::date;
/// assert_eq!(
/// date!(2019-01-02)
/// .midnight()
/// .assume_utc()
/// .lazy_format("%F %r %z")
/// .to_string(),
/// "2019-01-02 12:00:00 am +0000",
/// );
/// ```
pub fn lazy_format(self, format: impl Into<Format>) -> impl Display {
DeferredFormat::new(format)
.with_date(self.date())
.with_time(self.time())
.with_offset(self.offset())
.to_owned()
}
/// Attempt to parse an `OffsetDateTime` using the provided string.
///
/// ```rust
/// # use time::{date, OffsetDateTime, time};
/// assert_eq!(
/// OffsetDateTime::parse("2019-01-02 00:00:00 +0000", "%F %T %z"),
/// Ok(date!(2019-01-02).midnight().assume_utc()),
/// );
/// assert_eq!(
/// OffsetDateTime::parse("2019-002 23:59:59 +0000", "%Y-%j %T %z"),
/// Ok(date!(2019-002).with_time(time!(23:59:59)).assume_utc()),
/// );
/// assert_eq!(
/// OffsetDateTime::parse("2019-W01-3 12:00:00 pm +0000", "%G-W%V-%u %r %z"),
/// Ok(date!(2019-W01-3).with_time(time!(12:00)).assume_utc()),
/// );
/// ```
pub fn parse(s: impl AsRef<str>, format: impl Into<Format>) -> ParseResult<Self> {
Self::try_from_parsed_items(parse(s.as_ref(), &format.into())?)
}
/// Given the items already parsed, attempt to create an `OffsetDateTime`.
pub(crate) fn try_from_parsed_items(items: ParsedItems) -> ParseResult<Self> {
let offset = UtcOffset::try_from_parsed_items(items)?;
Ok(PrimitiveDateTime::try_from_parsed_items(items)?.assume_offset(offset))
}
}
impl Display for OffsetDateTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {} {}", self.date(), self.time(), self.offset())
}
}
impl PartialEq for OffsetDateTime {
fn eq(&self, rhs: &Self) -> bool {
self.utc_datetime.eq(&rhs.utc_datetime)
}
}
impl PartialOrd for OffsetDateTime {
fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
Some(self.cmp(rhs))
}
}
impl Ord for OffsetDateTime {
fn cmp(&self, rhs: &Self) -> Ordering {
self.utc_datetime.cmp(&rhs.utc_datetime)
}
}
impl Hash for OffsetDateTime {
fn hash<H: Hasher>(&self, hasher: &mut H) {
// We need to distinguish this from a `PrimitiveDateTime`, which would
// otherwise conflict.
hasher.write(b"OffsetDateTime");
self.utc_datetime.hash(hasher);
}
}
impl Add<Duration> for OffsetDateTime {
type Output = Self;
fn add(self, duration: Duration) -> Self::Output {
Self {
utc_datetime: self.utc_datetime + duration,
offset: self.offset,
}
}
}
impl Add<StdDuration> for OffsetDateTime {
type Output = Self;
fn add(self, duration: StdDuration) -> Self::Output {
Self {
utc_datetime: self.utc_datetime + duration,
offset: self.offset,
}
}
}
impl AddAssign<Duration> for OffsetDateTime {
fn add_assign(&mut self, duration: Duration) {
*self = *self + duration;
}
}
impl AddAssign<StdDuration> for OffsetDateTime {
fn add_assign(&mut self, duration: StdDuration) {
*self = *self + duration;
}
}
impl Sub<Duration> for OffsetDateTime {
type Output = Self;
fn sub(self, duration: Duration) -> Self::Output {
Self {
utc_datetime: self.utc_datetime - duration,
offset: self.offset,
}
}
}
impl Sub<StdDuration> for OffsetDateTime {
type Output = Self;
fn sub(self, duration: StdDuration) -> Self::Output {
Self {
utc_datetime: self.utc_datetime - duration,
offset: self.offset,
}
}
}
impl SubAssign<Duration> for OffsetDateTime {
fn sub_assign(&mut self, duration: Duration) {
*self = *self - duration;
}
}
impl SubAssign<StdDuration> for OffsetDateTime {
fn sub_assign(&mut self, duration: StdDuration) {
*self = *self - duration;
}
}
impl Sub<OffsetDateTime> for OffsetDateTime {
type Output = Duration;
fn sub(self, rhs: Self) -> Self::Output {
self.utc_datetime - rhs.utc_datetime
}
}
#[cfg(feature = "std")]
impl Add<Duration> for SystemTime {
type Output = Self;
fn add(self, duration: Duration) -> Self::Output {
if duration.is_zero() {
self
} else if duration.is_positive() {
self + duration.abs_std()
} else {
// duration.is_negative()
self - duration.abs_std()
}
}
}
#[cfg(feature = "std")]
impl AddAssign<Duration> for SystemTime {
fn add_assign(&mut self, duration: Duration) {
*self = *self + duration;
}
}
#[cfg(feature = "std")]
impl Sub<Duration> for SystemTime {
type Output = Self;
fn sub(self, duration: Duration) -> Self::Output {
(OffsetDateTime::from(self) - duration).into()
}
}
#[cfg(feature = "std")]
impl SubAssign<Duration> for SystemTime {
fn sub_assign(&mut self, duration: Duration) {
*self = *self - duration;
}
}
#[cfg(feature = "std")]
impl Sub<SystemTime> for OffsetDateTime {
type Output = Duration;
fn sub(self, rhs: SystemTime) -> Self::Output {
self - Self::from(rhs)
}
}
#[cfg(feature = "std")]
impl Sub<OffsetDateTime> for SystemTime {
type Output = Duration;
fn sub(self, rhs: OffsetDateTime) -> Self::Output {
OffsetDateTime::from(self) - rhs
}
}
#[cfg(feature = "std")]
impl PartialEq<SystemTime> for OffsetDateTime {
fn eq(&self, rhs: &SystemTime) -> bool {
self == &Self::from(*rhs)
}
}
#[cfg(feature = "std")]
impl PartialEq<OffsetDateTime> for SystemTime {
fn eq(&self, rhs: &OffsetDateTime) -> bool {
&OffsetDateTime::from(*self) == rhs
}
}
#[cfg(feature = "std")]
impl PartialOrd<SystemTime> for OffsetDateTime {
fn partial_cmp(&self, other: &SystemTime) -> Option<Ordering> {
self.partial_cmp(&Self::from(*other))
}
}
#[cfg(feature = "std")]
impl PartialOrd<OffsetDateTime> for SystemTime {
fn partial_cmp(&self, other: &OffsetDateTime) -> Option<Ordering> {
OffsetDateTime::from(*self).partial_cmp(other)
}
}
#[cfg(feature = "std")]
impl From<SystemTime> for OffsetDateTime {
// There is definitely some way to have this conversion be infallible, but
// it won't be an issue for over 500 years.
fn from(system_time: SystemTime) -> Self {
let duration = match system_time.duration_since(SystemTime::UNIX_EPOCH) {
Ok(duration) => Duration::try_from(duration)
.expect("overflow converting `std::time::Duration` to `time::Duration`"),
Err(err) => -Duration::try_from(err.duration())
.expect("overflow converting `std::time::Duration` to `time::Duration`"),
};
Self::unix_epoch() + duration
}
}
#[cfg(feature = "std")]
impl From<OffsetDateTime> for SystemTime {
fn from(datetime: OffsetDateTime) -> Self {
let duration = datetime - OffsetDateTime::unix_epoch();
if duration.is_zero() {
Self::UNIX_EPOCH
} else if duration.is_positive() {
Self::UNIX_EPOCH + duration.abs_std()
} else {
// duration.is_negative()
Self::UNIX_EPOCH - duration.abs_std()
}
}
} | } |
trca.py | """TRCA utils."""
import numpy as np
from scipy.signal import filtfilt, cheb1ord, cheby1
from scipy import stats
def round_half_up(num, decimals=0):
"""Round half up round the last decimal of the number.
The rules are:
from 0 to 4 rounds down
from 5 to 9 rounds up
Parameters
----------
num : float
Number to round
decimals : number of decimals
Returns
-------
num rounded
"""
multiplier = 10 ** decimals
return int(np.floor(num * multiplier + 0.5) / multiplier)
def normfit(data, ci=0.95):
"""Compute the mean, std and confidence interval for them.
Parameters
----------
data : array, shape=()
Input data.
ci : float
Confidence interval (default=0.95).
Returns
-------
m : mean
sigma : std deviation
[m - h, m + h] : confidence interval of the mean
[sigmaCI_lower, sigmaCI_upper] : confidence interval of the std
"""
arr = 1.0 * np.array(data)
num = len(arr)
avg, std_err = np.mean(arr), stats.sem(arr)
h_int = std_err * stats.t.ppf((1 + ci) / 2., num - 1)
var = np.var(data, ddof=1)
var_ci_upper = var * (num - 1) / stats.chi2.ppf((1 - ci) / 2, num - 1)
var_ci_lower = var * (num - 1) / stats.chi2.ppf(1 - (1 - ci) / 2, num - 1)
sigma = np.sqrt(var)
sigma_ci_lower = np.sqrt(var_ci_lower)
sigma_ci_upper = np.sqrt(var_ci_upper)
return avg, sigma, [avg - h_int, avg +
h_int], [sigma_ci_lower, sigma_ci_upper]
def itr(n, p, t):
"""Compute information transfer rate (ITR).
Definition in [1]_.
Parameters
----------
n : int
Number of targets.
p : float
Target identification accuracy (0 <= p <= 1).
t : float
Average time for a selection (s).
Returns
-------
itr : float
Information transfer rate [bits/min] |
References
----------
.. [1] M. Cheng, X. Gao, S. Gao, and D. Xu,
"Design and Implementation of a Brain-Computer Interface With High
Transfer Rates", IEEE Trans. Biomed. Eng. 49, 1181-1186, 2002.
"""
itr = 0
if (p < 0 or 1 < p):
raise ValueError('Accuracy need to be between 0 and 1.')
elif (p < 1 / n):
raise ValueError('ITR might be incorrect because accuracy < chance')
itr = 0
elif (p == 1):
itr = np.log2(n) * 60 / t
else:
itr = (np.log2(n) + p * np.log2(p) + (1 - p) *
np.log2((1 - p) / (n - 1))) * 60 / t
return itr
def bandpass(eeg, sfreq, Wp, Ws):
"""Filter bank design for decomposing EEG data into sub-band components.
Parameters
----------
eeg : np.array, shape=(n_samples, n_chans[, n_trials])
Training data.
sfreq : int
Sampling frequency of the data.
Wp : 2-tuple
Passband for Chebyshev filter.
Ws : 2-tuple
Stopband for Chebyshev filter.
Returns
-------
y: np.array, shape=(n_trials, n_chans, n_samples)
Sub-band components decomposed by a filter bank.
See Also
--------
scipy.signal.cheb1ord :
Chebyshev type I filter order selection.
"""
# Chebyshev type I filter order selection.
N, Wn = cheb1ord(Wp, Ws, 3, 40, fs=sfreq)
# Chebyshev type I filter design
B, A = cheby1(N, 0.5, Wn, btype="bandpass", fs=sfreq)
# the arguments 'axis=0, padtype='odd', padlen=3*(max(len(B),len(A))-1)'
# correspond to Matlab filtfilt : https://dsp.stackexchange.com/a/47945
y = filtfilt(B, A, eeg, axis=0, padtype='odd',
padlen=3 * (max(len(B), len(A)) - 1))
return y | |
main.py | import pymongo
from flask import Flask, jsonify, request
def get_db_connection(uri):
client = pymongo.MongoClient(uri)
return client.cryptongo
app = Flask(__name__)
db_connection = get_db_connection('mongodb://localhost:27017/')
def get_documents():
params = {}
name = request.args.get('name', '')
limit = int(request.args.get('limit', 0))
if name:
params.update({'name': name})
cursor = db_connection.tickers.find(params, {'_id':0, 'ticker_hash':0}).limit(limit)
return list(cursor)
def get_top20():
params = {}
name = request.args.get('name', '')
limit = int(request.args.get('limit', 0))
if name:
params.update({'name': name})
params.update({'rank': {'$lte': 20}})
cursor = db_connection.tickers.find(
params, {'_id': 0, 'ticker_hash': 0}
).limit(limit)
return list(cursor)
def remove_currency():
params = {}
name = request.args.get('name', '')
if name:
params.update({'name': name})
else:
return False
return db_connection.tickers.delete_many(params).deleted_count
#Correr el comando "FLASK_APP=main.py flask run"
@app.route("/")
def index():
return jsonify(
{
'name': 'Cryptongo API'
}
)
@app.route('/tickers', methods=['GET', 'DELETE'])
def tickers():
if request.method == 'GET':
return jsonify(get_documents())
elif request.method == 'DELETE':
result = remove_currency()
if result > 0:
|
else:
return jsonify({
'error': 'No se encontraron los documentos'
}), 404
@app.route("/top20", methods=['GET'])
def top20():
return jsonify(
get_top20()
)
| return jsonify({
'text': 'Documentos eliminados'
}), 204 |
w15.rs | #[doc = "Register `W15` reader"]
pub struct R(crate::R<W15_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<W15_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<W15_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<W15_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `W15` writer"]
pub struct W(crate::W<W15_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<W15_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<W15_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<W15_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `BUF15` reader - data buffer"]
pub struct BUF15_R(crate::FieldReader<u32, u32>);
impl BUF15_R {
#[inline(always)]
pub(crate) fn new(bits: u32) -> Self {
BUF15_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for BUF15_R {
type Target = crate::FieldReader<u32, u32>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
} | }
impl<'a> BUF15_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = value as u32;
self.w
}
}
impl R {
#[doc = "Bits 0:31 - data buffer"]
#[inline(always)]
pub fn buf15(&self) -> BUF15_R {
BUF15_R::new(self.bits as u32)
}
}
impl W {
#[doc = "Bits 0:31 - data buffer"]
#[inline(always)]
pub fn buf15(&mut self) -> BUF15_W {
BUF15_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "SPI1 memory data buffer15\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [w15](index.html) module"]
pub struct W15_SPEC;
impl crate::RegisterSpec for W15_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [w15::R](R) reader structure"]
impl crate::Readable for W15_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [w15::W](W) writer structure"]
impl crate::Writable for W15_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets W15 to value 0"]
impl crate::Resettable for W15_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
} | }
#[doc = "Field `BUF15` writer - data buffer"]
pub struct BUF15_W<'a> {
w: &'a mut W, |
slashed-variable.test.js | var expect = require('chai').expect;
describe('Slashed variables', function() {
var testrun;
before(function(done) {
this.run({
environment: {
values: [{key: 'fo/o', type: 'text', value: 'alpha', enabled: true},
{key: 'b\\ar', type: 'text', value: 'beta', enabled: true}]
},
collection: {
item: [{
request: 'https://postman-echo.com/get?foo={{fo/o}}&bar={{b\\ar}}'
}]
}
}, function(err, results) {
testrun = results;
done(err);
});
});
it('should have sent the request successfully', function() {
expect(testrun).to.be.ok; | expect(testrun.request.getCall(0).args[0]).to.be.null;
});
it('should have resolved the variables', function() {
var response = testrun.request.getCall(0).args[2],
query;
expect(response).to.have.property('code', 200);
query = response.json().args;
expect(query).to.deep.include({
foo: 'alpha',
bar: 'beta'
});
});
it('should have completed the run', function() {
expect(testrun).to.be.ok;
expect(testrun.done.getCall(0).args[0]).to.be.null;
expect(testrun).to.nested.include({
'done.calledOnce': true,
'start.calledOnce': true
});
});
}); | expect(testrun).to.nested.include({
'request.calledOnce': true
});
|
parser.go | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package parser
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"strconv"
"strings"
"text/scanner"
"gidl/ir"
)
type Parser struct {
scanner scanner.Scanner
lookaheads []token
}
func | (name string, input io.Reader) *Parser {
var p Parser
p.scanner.Position.Filename = name
p.scanner.Init(input)
return &p
}
func (p *Parser) Parse() (ir.All, error) {
var result ir.All
for !p.peekTokenKind(tEof) {
if err := p.parseSection(&result); err != nil {
return ir.All{}, err
}
}
// TODO(FIDL-754) Add validation checks for error codes after parsing.
return result, nil
}
type tokenKind uint
const (
_ tokenKind = iota
tEof
tText
tString
tLacco
tRacco
tComma
tColon
tNeg
tLparen
tRparen
tEqual
tLsquare
tRsquare
)
var tokenKindStrings = []string{
"<invalid>",
"<eof>",
"<text>",
"<string>",
"{",
"}",
",",
":",
"-",
"(",
")",
"=",
"[",
"]",
}
var (
isUnitTokenKind = make(map[tokenKind]bool)
textToTokenKind = make(map[string]tokenKind)
)
func init() {
for index, text := range tokenKindStrings {
if strings.HasPrefix(text, "<") && strings.HasSuffix(text, ">") {
continue
}
kind := tokenKind(index)
isUnitTokenKind[kind] = true
textToTokenKind[text] = kind
}
}
func (kind tokenKind) String() string {
if index := int(kind); index < len(tokenKindStrings) {
return tokenKindStrings[index]
}
return fmt.Sprintf("%d", kind)
}
type token struct {
kind tokenKind
value string
line, column int
}
func (t token) String() string {
if isUnitTokenKind[t.kind] {
return t.kind.String()
} else {
return t.value
}
}
type bodyElement uint
const (
_ bodyElement = iota
isType
isValue
isBytes
isErr
isBindingsAllowlist
isBindingsDenylist
)
func (kind bodyElement) String() string {
switch kind {
case isType:
return "type"
case isValue:
return "value"
case isBytes:
return "bytes"
case isErr:
return "err"
case isBindingsAllowlist:
return "bindings_allowlist"
case isBindingsDenylist:
return "bindings_denylist"
default:
panic("unsupported kind")
}
}
type body struct {
Type string
Value ir.Value
Encodings []ir.Encoding
Err ir.ErrorCode
BindingsAllowlist *[]string
BindingsDenylist *[]string
}
type sectionMetadata struct {
requiredKinds map[bodyElement]bool
optionalKinds map[bodyElement]bool
setter func(name string, body body, all *ir.All)
}
var sections = map[string]sectionMetadata{
"success": {
requiredKinds: map[bodyElement]bool{isValue: true, isBytes: true},
optionalKinds: map[bodyElement]bool{isBindingsAllowlist: true, isBindingsDenylist: true},
setter: func(name string, body body, all *ir.All) {
encodeSuccess := ir.EncodeSuccess{
Name: name,
Value: body.Value,
Encodings: body.Encodings,
BindingsAllowlist: body.BindingsAllowlist,
BindingsDenylist: body.BindingsDenylist,
}
all.EncodeSuccess = append(all.EncodeSuccess, encodeSuccess)
decodeSuccess := ir.DecodeSuccess{
Name: name,
Value: body.Value,
Encodings: body.Encodings,
BindingsAllowlist: body.BindingsAllowlist,
BindingsDenylist: body.BindingsDenylist,
}
all.DecodeSuccess = append(all.DecodeSuccess, decodeSuccess)
},
},
"encode_success": {
requiredKinds: map[bodyElement]bool{isValue: true, isBytes: true},
optionalKinds: map[bodyElement]bool{isBindingsAllowlist: true},
setter: func(name string, body body, all *ir.All) {
result := ir.EncodeSuccess{
Name: name,
Value: body.Value,
Encodings: body.Encodings,
BindingsAllowlist: body.BindingsAllowlist,
}
all.EncodeSuccess = append(all.EncodeSuccess, result)
},
},
"decode_success": {
requiredKinds: map[bodyElement]bool{isValue: true, isBytes: true},
optionalKinds: map[bodyElement]bool{isBindingsAllowlist: true},
setter: func(name string, body body, all *ir.All) {
result := ir.DecodeSuccess{
Name: name,
Value: body.Value,
Encodings: body.Encodings,
BindingsAllowlist: body.BindingsAllowlist,
}
all.DecodeSuccess = append(all.DecodeSuccess, result)
},
},
"encode_failure": {
requiredKinds: map[bodyElement]bool{isValue: true, isErr: true},
optionalKinds: map[bodyElement]bool{isBindingsAllowlist: true, isBindingsDenylist: true},
setter: func(name string, body body, all *ir.All) {
result := ir.EncodeFailure{
Name: name,
Value: body.Value,
WireFormats: ir.AllWireFormats(),
Err: body.Err,
BindingsAllowlist: body.BindingsAllowlist,
BindingsDenylist: body.BindingsDenylist,
}
all.EncodeFailure = append(all.EncodeFailure, result)
},
},
"decode_failure": {
requiredKinds: map[bodyElement]bool{isType: true, isBytes: true, isErr: true},
optionalKinds: map[bodyElement]bool{isBindingsAllowlist: true, isBindingsDenylist: true},
setter: func(name string, body body, all *ir.All) {
result := ir.DecodeFailure{
Name: name,
Type: body.Type,
Encodings: body.Encodings,
Err: body.Err,
BindingsAllowlist: body.BindingsAllowlist,
BindingsDenylist: body.BindingsDenylist,
}
all.DecodeFailure = append(all.DecodeFailure, result)
},
},
}
func (p *Parser) parseSection(all *ir.All) error {
section, name, err := p.parsePreamble()
if err != nil {
return err
}
body, err := p.parseBody(section.requiredKinds, section.optionalKinds)
if err != nil {
return err
}
section.setter(name, body, all)
return nil
}
func (p *Parser) parsePreamble() (sectionMetadata, string, error) {
tok, ok := p.consumeToken(tText)
if !ok {
return sectionMetadata{}, "", p.failExpectedToken(tText, tok)
}
section, ok := sections[tok.value]
if !ok {
return sectionMetadata{}, "", p.newParseError(tok, "unknown section %s", tok.value)
}
tok, ok = p.consumeToken(tLparen)
if !ok {
return sectionMetadata{}, "", p.failExpectedToken(tLparen, tok)
}
tok, ok = p.consumeToken(tString)
if !ok {
return sectionMetadata{}, "", p.failExpectedToken(tString, tok)
}
name := tok.value
tok, ok = p.consumeToken(tRparen)
if !ok {
return sectionMetadata{}, "", p.failExpectedToken(tRparen, tok)
}
return section, name, nil
}
func (p *Parser) parseBody(requiredKinds map[bodyElement]bool, optionalKinds map[bodyElement]bool) (body, error) {
var (
result body
parsedKinds = make(map[bodyElement]bool)
bodyTok = p.peekToken()
)
err := p.parseCommaSeparated(tLacco, tRacco, func() error {
return p.parseSingleBodyElement(&result, parsedKinds)
})
if err != nil {
return result, err
}
for requiredKind := range requiredKinds {
if !parsedKinds[requiredKind] {
return result, p.newParseError(bodyTok, "missing required parameter '%s'", requiredKind)
}
}
for parsedKind := range parsedKinds {
if !requiredKinds[parsedKind] && !optionalKinds[parsedKind] {
return result, p.newParseError(bodyTok, "parameter '%s' does not apply to element", parsedKind)
}
}
return result, nil
}
func (p *Parser) parseSingleBodyElement(result *body, all map[bodyElement]bool) error {
tok, ok := p.consumeToken(tText)
if !ok {
return p.failExpectedToken(tText, tok)
}
if tok, ok := p.consumeToken(tEqual); !ok {
return p.failExpectedToken(tEqual, tok)
}
var kind bodyElement
switch tok.value {
case "type":
tok, ok := p.consumeToken(tText)
if !ok {
return p.failExpectedToken(tText, tok)
}
result.Type = tok.value
kind = isType
case "value":
val, err := p.parseValue()
if err != nil {
return err
}
result.Value = val
kind = isValue
case "bytes":
encodings, err := p.parseByteSection()
if err != nil {
return err
}
result.Encodings = encodings
kind = isBytes
case "err":
errorCode, err := p.parseErrorCode()
if err != nil {
return err
}
result.Err = errorCode
kind = isErr
case "bindings_allowlist":
languages, err := p.parseTextSlice()
if err != nil {
return err
}
result.BindingsAllowlist = &languages
kind = isBindingsAllowlist
case "bindings_denylist":
languages, err := p.parseTextSlice()
if err != nil {
return err
}
result.BindingsDenylist = &languages
kind = isBindingsDenylist
default:
return p.newParseError(tok, "must be type, value, bytes, err, bindings_allowlist or bindings_denylist")
}
if all[kind] {
return p.newParseError(tok, "duplicate %s found", kind)
}
all[kind] = true
return nil
}
func (p *Parser) parseValue() (interface{}, error) {
switch p.peekToken().kind {
case tText:
tok := p.nextToken()
if '0' <= tok.value[0] && tok.value[0] <= '9' {
return parseNum(tok, false)
}
if tok.value == "null" {
return nil, nil
}
if tok.value == "true" {
return true, nil
}
if tok.value == "false" {
return false, nil
}
return p.parseObject(tok.value)
case tLsquare:
return p.parseSlice()
case tString:
return p.nextToken().value, nil
case tNeg:
p.nextToken()
if tok, ok := p.consumeToken(tText); !ok {
return nil, p.failExpectedToken(tText, tok)
} else {
return parseNum(tok, true)
}
default:
return nil, p.newParseError(p.peekToken(), "expected value")
}
}
func parseNum(tok token, neg bool) (interface{}, error) {
if strings.Contains(tok.value, ".") {
val, err := strconv.ParseFloat(tok.value, 64)
if err != nil {
return nil, err
}
if neg {
return -val, nil
} else {
return val, nil
}
} else {
val, err := strconv.ParseUint(tok.value, 0, 64)
if err != nil {
return nil, err
}
if neg {
return -int64(val), nil
} else {
return uint64(val), nil
}
}
}
func (p *Parser) parseObject(name string) (interface{}, error) {
obj := ir.Object{Name: name}
err := p.parseCommaSeparated(tLacco, tRacco, func() error {
tokFieldName, ok := p.consumeToken(tText)
if !ok {
return p.failExpectedToken(tText, tokFieldName)
}
if tok, ok := p.consumeToken(tColon); !ok {
return p.failExpectedToken(tColon, tok)
}
val, err := p.parseValue()
if err != nil {
return err
}
obj.Fields = append(obj.Fields, ir.Field{Key: decodeFieldKey(tokFieldName.value), Value: val})
return nil
})
if err != nil {
return nil, err
}
return obj, nil
}
// Field can be referenced by either name or ordinal.
func decodeFieldKey(field string) ir.FieldKey {
if ord, err := strconv.ParseInt(field, 0, 64); err == nil {
return ir.FieldKey{Ordinal: uint64(ord)}
}
return ir.FieldKey{Name: field}
}
func (p *Parser) parseErrorCode() (ir.ErrorCode, error) {
tok, ok := p.consumeToken(tText)
if !ok {
return "", p.failExpectedToken(tText, tok)
}
code := ir.ErrorCode(tok.value)
if _, ok := ir.AllErrorCodes[code]; !ok {
return "", p.newParseError(tok, "unknown error code")
}
return code, nil
}
func (p *Parser) parseSlice() ([]interface{}, error) {
var result []interface{}
err := p.parseCommaSeparated(tLsquare, tRsquare, func() error {
val, err := p.parseValue()
if err != nil {
return err
}
result = append(result, val)
return nil
})
if err != nil {
return nil, err
}
return result, nil
}
func (p *Parser) parseTextSlice() ([]string, error) {
var result []string
err := p.parseCommaSeparated(tLsquare, tRsquare, func() error {
if tok, ok := p.consumeToken(tText); !ok {
return p.failExpectedToken(tText, tok)
} else {
result = append(result, tok.value)
return nil
}
})
if err != nil {
return nil, err
}
return result, nil
}
func (p *Parser) parseByteSection() ([]ir.Encoding, error) {
firstTok := p.peekToken()
if firstTok.kind == tLsquare {
if b, err := p.parseByteList(); err == nil {
return []ir.Encoding{{
// Default to the old wire format.
WireFormat: ir.OldWireFormat,
Bytes: b,
}}, nil
} else {
return nil, err
}
}
var res []ir.Encoding
wireFormats := map[ir.WireFormat]struct{}{}
err := p.parseCommaSeparated(tLacco, tRacco, func() error {
tok, ok := p.consumeToken(tText)
if !ok {
return p.failExpectedToken(tText, tok)
}
if teq, ok := p.consumeToken(tEqual); !ok {
return p.failExpectedToken(tEqual, teq)
}
b, err := p.parseByteList()
if err != nil {
return err
}
wf, err := ir.WireFormatByName(tok.value)
if err != nil {
return err
}
if _, ok := wireFormats[wf]; ok {
return p.newParseError(tok, "duplicate wire format: %s", tok.value)
}
wireFormats[wf] = struct{}{}
res = append(res, ir.Encoding{
WireFormat: wf,
Bytes: b,
})
return nil
})
if err != nil {
return nil, err
}
if len(res) == 0 {
return nil, p.newParseError(firstTok, "no bytes provided for any wire format")
}
return res, nil
}
func (p *Parser) parseByteList() ([]byte, error) {
var bytes []byte
err := p.parseCommaSeparated(tLsquare, tRsquare, func() error {
// Read the byte size.
tok, ok := p.consumeToken(tText)
if !ok {
return p.failExpectedToken(tText, tok)
}
if p.peekTokenKind(tText) {
// First token was the label. Now get the byte size.
tok, _ = p.consumeToken(tText)
}
byteSize, err := strconv.ParseUint(tok.value, 10, 64)
if err != nil {
return p.newParseError(tok, "error parsing byte block size: %v", err)
}
if byteSize == 0 {
return p.newParseError(tok, "expected non-zero byte size")
}
if tok, ok := p.consumeToken(tColon); !ok {
return p.failExpectedToken(tColon, tok)
}
// Read the type.
tok, ok = p.consumeToken(tText)
if !ok {
return p.failExpectedToken(tText, tok)
}
var handler func(byteSize int) ([]byte, error)
switch tok.value {
case "raw":
handler = p.parseByteBlockRaw
case "num":
handler = p.parseByteBlockNum
case "padding":
handler = p.parseByteBlockPadding
default:
return p.newParseError(tok, "unknown byte block type %q", tok.value)
}
if b, err := handler(int(byteSize)); err != nil {
return err
} else if len(b) != int(byteSize) {
return p.newParseError(tok, "byte block produced of incorrect size. got %d, want %d", len(b), byteSize)
} else {
bytes = append(bytes, b...)
}
return nil
})
if err != nil {
return nil, err
}
return bytes, nil
}
func (p *Parser) parseByteBlockRaw(byteSize int) ([]byte, error) {
res := make([]byte, 0, byteSize)
err := p.parseCommaSeparated(tLparen, tRparen, func() error {
b, err := p.parseByte()
if err != nil {
return err
}
res = append(res, b)
return nil
})
return res, err
}
func (p *Parser) parseByteBlockNum(byteSize int) ([]byte, error) {
if tok, ok := p.consumeToken(tLparen); !ok {
return nil, p.failExpectedToken(tLparen, tok)
}
neg := p.peekTokenKind(tNeg)
if neg {
p.consumeToken(tNeg)
}
tok, ok := p.consumeToken(tText)
if !ok {
return nil, p.failExpectedToken(tText, tok)
}
buf := make([]byte, 8)
uintVal, err := strconv.ParseUint(tok.value, 0, 64)
if err != nil {
return nil, p.newParseError(tok, "error parsing unsigned integer num: %v", err)
}
if neg {
intVal := -int64(uintVal)
if intVal>>(uint(byteSize)*8-1) < -1 {
return nil, p.newParseError(tok, "num value %d exceeds byte size %d", intVal, byteSize)
}
uintVal = uint64(intVal)
} else {
if uintVal>>(uint(byteSize)*8) > 0 {
return nil, p.newParseError(tok, "num value %d exceeds byte size %d", uintVal, byteSize)
}
}
binary.LittleEndian.PutUint64(buf, uintVal)
if tok, ok := p.consumeToken(tRparen); !ok {
return nil, p.failExpectedToken(tRparen, tok)
}
return buf[:byteSize], nil
}
func (p *Parser) parseByteBlockPadding(byteSize int) ([]byte, error) {
if !p.peekTokenKind(tLparen) {
return bytes.Repeat([]byte{0}, byteSize), nil
}
if tok, ok := p.consumeToken(tLparen); !ok {
return nil, p.failExpectedToken(tLparen, tok)
}
b, err := p.parseByte()
if err != nil {
return nil, err
}
if tok, ok := p.consumeToken(tRparen); !ok {
return nil, p.failExpectedToken(tRparen, tok)
}
return bytes.Repeat([]byte{b}, byteSize), nil
}
func (p *Parser) parseByte() (byte, error) {
tok, ok := p.consumeToken(tText)
if !ok {
return 0, p.failExpectedToken(tText, tok)
}
if len(tok.value) == 3 && tok.value[0] == '\'' && tok.value[2] == '\'' {
return tok.value[1], nil
}
b, err := strconv.ParseUint(tok.value, 0, 8)
if err != nil {
return 0, p.newParseError(tok, err.Error())
}
return byte(b), nil
}
func (p *Parser) parseCommaSeparated(beginTok, endTok tokenKind, handler func() error) error {
if tok, ok := p.consumeToken(beginTok); !ok {
return p.failExpectedToken(beginTok, tok)
}
for !p.peekTokenKind(endTok) {
if err := handler(); err != nil {
return err
}
if !p.peekTokenKind(endTok) {
if tok, ok := p.consumeToken(tComma); !ok {
return p.failExpectedToken(tComma, tok)
}
}
}
if tok, ok := p.consumeToken(endTok); !ok {
return p.failExpectedToken(endTok, tok)
}
return nil
}
func (p *Parser) consumeToken(kind tokenKind) (token, bool) {
tok := p.nextToken()
return tok, tok.kind == kind
}
func (p *Parser) peekTokenKind(kind tokenKind) bool {
return p.peekToken().kind == kind
}
func (p *Parser) peekToken() token {
if len(p.lookaheads) == 0 {
tok := p.nextToken()
p.lookaheads = append(p.lookaheads, tok)
}
return p.lookaheads[0]
}
func (p *Parser) nextToken() token {
if len(p.lookaheads) != 0 {
var tok token
tok, p.lookaheads = p.lookaheads[0], p.lookaheads[1:]
return tok
}
return p.scanToken()
}
func (p *Parser) scanToken() token {
// eof
if tok := p.scanner.Scan(); tok == scanner.EOF {
return token{tEof, "", 0, 0}
}
pos := p.scanner.Position
// unit tokens
text := p.scanner.TokenText()
if kind, ok := textToTokenKind[text]; ok {
return token{kind, text, pos.Line, pos.Column}
}
// string
if text[0] == '"' {
// TODO escape
return token{tString, text[1 : len(text)-1], pos.Line, pos.Column}
}
// text
return token{tText, text, pos.Line, pos.Column}
}
type parseError struct {
input string
line, column int
message string
}
// Assert parseError implements error interface
var _ error = &parseError{}
func (err *parseError) Error() string {
return fmt.Sprintf("%s:%d:%d: %s", err.input, err.line, err.column, err.message)
}
func (p *Parser) failExpectedToken(want tokenKind, got token) error {
return p.newParseError(got, "unexpected tokenKind: want %q, got %q (value: %q)", want, got.kind, got.value)
}
func (p *Parser) newParseError(tok token, format string, a ...interface{}) error {
return &parseError{
input: p.scanner.Position.Filename,
line: tok.line,
column: tok.column,
message: fmt.Sprintf(format, a...),
}
}
| NewParser |
index.tsx | import React, { useMemo } from 'react';
import { ReactComponent as BinanceChainWallet } from './Logos/BinanceChainWallet.svg';
import { ReactComponent as Ledger } from './Logos/Ledger.svg';
import { ReactComponent as MathWallet } from './Logos/MathWallet.svg';
import { ReactComponent as MetaMask } from './Logos/MetaMask.svg';
import { ReactComponent as TokenPocket } from './Logos/TokenPocket.svg';
import { ReactComponent as TrustWallet } from './Logos/TrustWallet.svg';
| 'Math Wallet',
'MetaMask',
'TokenPocket',
'Trust Wallet',
] as const;
export type DefaultWalletProvider = typeof DEFAULT_WALLET_PROVIDERS[number];
export type WalletProvider = {
name: string;
icon: React.ReactNode;
href: string;
description?: React.ReactNode;
};
export const useWalletProviders = () => {
const binanceWalletUrl = useMemo(() => {
if (typeof window !== 'undefined') {
if (navigator?.userAgent.indexOf('Firefox') !== -1) {
return 'https://addons.mozilla.org/en-US/firefox/addon/binance-chain';
}
}
return 'https://chrome.google.com/webstore/detail/binance-chain-wallet/fhbohimaelbohpjbbldcngcnapndodjp';
}, []);
return {
providers: {
/* eslint-disable prettier/prettier */
'Binance Chain Wallet': {
name: 'Binance Chain Wallet',
icon: <BinanceChainWallet />,
href: binanceWalletUrl,
},
'Ledger': {
name: 'Ledger',
icon: <Ledger />,
href: 'https://www.ledger.com',
},
'Math Wallet': {
name: 'Math Wallet',
icon: <MathWallet />,
href: 'https://mathwallet.org',
},
'MetaMask': {
name: 'MetaMask',
icon: <MetaMask />,
href: 'https://metamask.io/index.html',
},
'TokenPocket': {
name: 'TokenPocket',
icon: <TokenPocket />,
href: 'https://www.tokenpocket.pro',
},
'Trust Wallet': {
name: 'Trust Wallet',
icon: <TrustWallet />,
href: 'https://trustwallet.com',
},
/* eslint-enable prettier/prettier */
},
};
}; | export const DEFAULT_WALLET_PROVIDERS = [
'Binance Chain Wallet',
'Ledger', |
polling.py | from telegram import constants
from telegram.ext import Updater
from distutils.version import LooseVersion
from telegram import __version__ as ptb_version
from utils import functions, globals, log
logger = log.get_logger(name='Bot')
def | (args):
request_kwargs = {
'proxy_url': args.proxy} if args.proxy is not None else None
updater = Updater(token=args.api_secret, use_context=True,
request_kwargs=request_kwargs)
dispatcher = updater.dispatcher
globals.dispatcher = dispatcher
functions.load_all_funcs(dispatcher, args)
if LooseVersion(ptb_version) >= LooseVersion('13.5'):
updater.start_polling(allowed_updates=constants.UPDATE_ALL_TYPES)
else:
logger.warn('PTB version < 13.5, not all update types are listening')
updater.start_polling() | polling |
Python.py | # -*- coding: utf-8 -*-
try:
from PySide import QtWidgets
except:
from PyQt5 import QtWidgets
class Python:
def | (self):
print("Hi")
| __init__ |
saarlouis.py | #!/usr/bin/python3
from botbase import *
_saarlouis_c = re.compile(r"insgesamt:\s*([0-9.]+)")
_saarlouis_d = re.compile(r"Verstorben:\s*([0-9.]+)")
_saarlouis_g = re.compile(r"Genesen:\s*([0-9.]+)")
def saarlouis(sheets):
import bs4
soup = get_soup("https://www.kreis-saarlouis.de/Corona-Virus/Corona-Ticker.htm?")
content = soup.find(id="content_frame")
ps = []
cur = next(content.find("hr").parent.children)
stop = cur.findNext("hr")
while cur is not None:
if isinstance(cur, bs4.Tag): ps.extend([p for p in cur.find_all(text=True) if not p.strip() == ""])
cur = cur.nextSibling
if cur == stop:
if len(ps) >= 4: break
stop = cur.findNext("hr")
#for p in ps: print("A",p)
#date = check_date(p[0], "Merzig-Wadern")
if not (today().strftime("%d.%m.%Y") in ps[0] or today().strftime("%d.%m.%y") in ps[0]): raise NotYetAvailableException("Saarlouis noch alt: "+ps[0]) | for p in ps:
m = _saarlouis_c.search(p)
if m: args["c"] = force_int(m.group(1))
m = _saarlouis_d.search(p)
if m: args["d"] = force_int(m.group(1))
m = _saarlouis_g.search(p)
if m: args["g"] = force_int(m.group(1))
assert "c" in args and "d" in args and "g" in args, "No data - yet?"
update(sheets, 10044, **args, sig="Bot", ignore_delta=False)
return True
schedule.append(Task(15, 30, 20, 35, 600, saarlouis, 10044))
if __name__ == '__main__': saarlouis(googlesheets()) | args={} |
index.spec.ts | // tslint:disable:no-any
import { ItemNotFoundError } from '@js-items/foundation';
import testItem from '@js-items/foundation/dist/functions/utils/testItem';
import { config, jsonOptions } from '../../utils/testConfig';
import updateItem from './index';
beforeEach(() => jest.clearAllMocks());
const filter = {
id: { $eq: testItem.id },
};
const defaultOptions = {
id: testItem.id,
patch: testItem,
};
const updateMock = jest.fn(() => ({
json: () => Promise.resolve({ item: testItem }),
}));
describe('@updateItem', () => {
it('updates item without filter', async () => {
const createFilterMock = jest.fn(() => ({}));
const updateItemOptionsMock = jest.fn(() => ({}));
const { item } = await updateItem({
...config,
createFilter: createFilterMock,
ky: () => Promise.resolve({patch: updateMock}) as any,
updateItemOptions: updateItemOptionsMock,
})(defaultOptions);
expect(updateItemOptionsMock).toBeCalledWith(testItem);
expect(createFilterMock).toBeCalledWith({});
expect(config.convertDocumentIntoItem).toBeCalledWith(testItem);
expect(item).toEqual(testItem);
expect(updateMock).toBeCalledWith(`${config.itemUrl}/${testItem.id}`, {
json: { ...testItem },
searchParams: { filter: JSON.stringify({}) },
});
});
it('updates item with custom filter and search params', async () => {
const createFilterMock = jest.fn(() => filter);
const updateItemOptionsMock = jest.fn(() => ({
searchParams: { pretty: 'false' },
}));
await updateItem({
...config,
createFilter: createFilterMock,
ky: () => Promise.resolve({patch: updateMock}) as any,
updateItemOptions: updateItemOptionsMock,
})({ ...defaultOptions, filter });
expect(createFilterMock).toBeCalledWith(filter);
expect(updateMock).toBeCalledWith(`${config.itemUrl}/${testItem.id}`, {
json: { ...testItem },
searchParams: { filter: JSON.stringify(filter), pretty: 'false' },
});
});
it('does not update item', async () => {
const error = new ItemNotFoundError('TestItem');
const facadeConfig = {
...config,
ky: jest.fn(() => Promise.reject(error)),
updateItemOptions: jsonOptions,
};
try {
await updateItem(facadeConfig)(defaultOptions);
} catch (e) {
expect(e).toEqual(error);
}
}); | }); |
|
cost_update_service.rs | //! this service receives instruction ExecuteTimings from replay_stage,
//! update cost_model which is shared with banking_stage to optimize
//! packing transactions into block; it also triggers persisting cost
//! table to blockstore.
use crate::cost_model::CostModel;
use solana_ledger::blockstore::Blockstore;
use solana_measure::measure::Measure;
use solana_runtime::bank::ExecuteTimings;
use solana_sdk::timing::timestamp;
use std::{
sync::{
atomic::{AtomicBool, Ordering},
mpsc::Receiver,
Arc, RwLock,
},
thread::{self, Builder, JoinHandle},
time::Duration,
};
#[derive(Default)]
pub struct CostUpdateServiceTiming {
last_print: u64,
update_cost_model_count: u64,
update_cost_model_elapsed: u64,
persist_cost_table_elapsed: u64,
}
impl CostUpdateServiceTiming {
fn update(
&mut self,
update_cost_model_count: u64,
update_cost_model_elapsed: u64,
persist_cost_table_elapsed: u64,
) {
self.update_cost_model_count += update_cost_model_count;
self.update_cost_model_elapsed += update_cost_model_elapsed;
self.persist_cost_table_elapsed += persist_cost_table_elapsed;
let now = timestamp();
let elapsed_ms = now - self.last_print;
if elapsed_ms > 1000 {
datapoint_info!(
"cost-update-service-stats",
("total_elapsed_us", elapsed_ms * 1000, i64),
(
"update_cost_model_count",
self.update_cost_model_count as i64,
i64
),
(
"update_cost_model_elapsed",
self.update_cost_model_elapsed as i64,
i64
),
(
"persist_cost_table_elapsed",
self.persist_cost_table_elapsed as i64,
i64
),
);
*self = CostUpdateServiceTiming::default();
self.last_print = now;
}
}
}
pub type CostUpdateReceiver = Receiver<ExecuteTimings>;
pub struct CostUpdateService {
thread_hdl: JoinHandle<()>,
}
impl CostUpdateService {
#[allow(clippy::new_ret_no_self)]
pub fn new(
exit: Arc<AtomicBool>,
blockstore: Arc<Blockstore>,
cost_model: Arc<RwLock<CostModel>>,
cost_update_receiver: CostUpdateReceiver,
) -> Self {
let thread_hdl = Builder::new()
.name("solana-cost-update-service".to_string())
.spawn(move || {
Self::service_loop(exit, blockstore, cost_model, cost_update_receiver);
})
.unwrap();
Self { thread_hdl }
}
pub fn join(self) -> thread::Result<()> {
self.thread_hdl.join()
}
fn service_loop(
exit: Arc<AtomicBool>,
blockstore: Arc<Blockstore>,
cost_model: Arc<RwLock<CostModel>>,
cost_update_receiver: CostUpdateReceiver,
) {
let mut cost_update_service_timing = CostUpdateServiceTiming::default();
let mut dirty: bool;
let mut update_count: u64;
let wait_timer = Duration::from_millis(100);
loop {
if exit.load(Ordering::Relaxed) {
break;
}
dirty = false;
update_count = 0_u64;
let mut update_cost_model_time = Measure::start("update_cost_model_time");
for cost_update in cost_update_receiver.try_iter() {
dirty |= Self::update_cost_model(&cost_model, &cost_update);
update_count += 1;
}
update_cost_model_time.stop();
let mut persist_cost_table_time = Measure::start("persist_cost_table_time");
if dirty {
Self::persist_cost_table(&blockstore, &cost_model);
}
persist_cost_table_time.stop();
cost_update_service_timing.update(
update_count,
update_cost_model_time.as_us(),
persist_cost_table_time.as_us(),
);
thread::sleep(wait_timer);
}
}
fn update_cost_model(cost_model: &RwLock<CostModel>, execute_timings: &ExecuteTimings) -> bool {
let mut dirty = false;
{
let mut cost_model_mutable = cost_model.write().unwrap();
for (program_id, timing) in &execute_timings.details.per_program_timings {
if timing.count < 1 {
continue;
}
let units = timing.accumulated_units / timing.count as u64;
match cost_model_mutable.upsert_instruction_cost(program_id, units) {
Ok(c) => {
debug!(
"after replayed into bank, instruction {:?} has averaged cost {}",
program_id, c
);
dirty = true;
}
Err(err) => {
debug!(
"after replayed into bank, instruction {:?} failed to update cost, err: {}",
program_id, err
);
}
}
}
}
debug!(
"after replayed into bank, updated cost model instruction cost table, current values: {:?}",
cost_model.read().unwrap().get_instruction_cost_table()
);
dirty
}
fn persist_cost_table(blockstore: &Blockstore, cost_model: &RwLock<CostModel>) {
let cost_model_read = cost_model.read().unwrap();
let cost_table = cost_model_read.get_instruction_cost_table();
let db_records = blockstore.read_program_costs().expect("read programs");
// delete records from blockstore if they are no longer in cost_table
db_records.iter().for_each(|(pubkey, _)| {
if cost_table.get(pubkey).is_none() {
blockstore
.delete_program_cost(pubkey)
.expect("delete old program");
}
});
for (key, cost) in cost_table.iter() {
blockstore
.write_program_cost(key, cost)
.expect("persist program costs to blockstore");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use solana_program_runtime::ProgramTiming;
use solana_sdk::pubkey::Pubkey;
#[test]
fn test_update_cost_model_with_empty_execute_timings() {
let cost_model = Arc::new(RwLock::new(CostModel::default()));
let empty_execute_timings = ExecuteTimings::default();
CostUpdateService::update_cost_model(&cost_model, &empty_execute_timings);
assert_eq!(
0,
cost_model
.read()
.unwrap()
.get_instruction_cost_table()
.len()
);
}
#[test]
fn test_update_cost_model_with_execute_timings() |
}
| {
let cost_model = Arc::new(RwLock::new(CostModel::default()));
let mut execute_timings = ExecuteTimings::default();
let program_key_1 = Pubkey::new_unique();
let mut expected_cost: u64;
// add new program
{
let accumulated_us: u64 = 1000;
let accumulated_units: u64 = 100;
let count: u32 = 10;
expected_cost = accumulated_units / count as u64;
execute_timings.details.per_program_timings.insert(
program_key_1,
ProgramTiming {
accumulated_us,
accumulated_units,
count,
},
);
CostUpdateService::update_cost_model(&cost_model, &execute_timings);
assert_eq!(
1,
cost_model
.read()
.unwrap()
.get_instruction_cost_table()
.len()
);
assert_eq!(
Some(&expected_cost),
cost_model
.read()
.unwrap()
.get_instruction_cost_table()
.get(&program_key_1)
);
}
// update program
{
let accumulated_us: u64 = 2000;
let accumulated_units: u64 = 200;
let count: u32 = 10;
// to expect new cost is Average(new_value, existing_value)
expected_cost = ((accumulated_units / count as u64) + expected_cost) / 2;
execute_timings.details.per_program_timings.insert(
program_key_1,
ProgramTiming {
accumulated_us,
accumulated_units,
count,
},
);
CostUpdateService::update_cost_model(&cost_model, &execute_timings);
assert_eq!(
1,
cost_model
.read()
.unwrap()
.get_instruction_cost_table()
.len()
);
assert_eq!(
Some(&expected_cost),
cost_model
.read()
.unwrap()
.get_instruction_cost_table()
.get(&program_key_1)
);
}
} |
execute.py | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# 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.
''' execute.py '''
import contextlib
import os
import subprocess
import shlex
import tarfile
import tempfile
import traceback
from heron.common.src.python.utils.log import Log
from heron.tools.cli.src.python.result import SimpleResult, ProcessResult, Status
from heron.common.src.python import pex_loader
from heron.tools.cli.src.python import opts
from heron.tools.cli.src.python import jars
from heron.tools.common.src.python.utils import config
################################################################################
def | (class_name, lib_jars, extra_jars=None, args=None, java_defines=None):
'''
Execute a heron class given the args and the jars needed for class path
:param class_name:
:param lib_jars:
:param extra_jars:
:param args:
:param java_defines:
:return:
'''
# default optional params to empty list if not provided
if extra_jars is None:
extra_jars = []
if args is None:
args = []
if java_defines is None:
java_defines = []
# Format all java -D options that need to be passed while running
# the class locally.
java_opts = ['-D' + opt for opt in java_defines]
java_path = config.get_java_path()
if java_path is None:
err_context = "Unable to find java command"
return SimpleResult(Status.InvocationError, err_context)
# Construct the command line for the sub process to run
# Because of the way Python execute works,
# the java opts must be passed as part of the list
all_args = [java_path, "-client", "-Xmx1g"] + \
java_opts + \
["-cp", config.get_classpath(extra_jars + lib_jars)]
all_args += [class_name] + list(args)
# set heron_config environment variable
heron_env = os.environ.copy()
heron_env['HERON_OPTIONS'] = opts.get_heron_config()
# print the verbose message
Log.debug("Invoking class using command: `%s`", ' '.join(shlex.quote(a) for a in all_args))
Log.debug("Heron options: {%s}", str(heron_env["HERON_OPTIONS"]))
# invoke the command with subprocess and print error message, if any
# pylint: disable=consider-using-with
process = subprocess.Popen(all_args, env=heron_env, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, universal_newlines=True, bufsize=1)
# stdout message has the information Java program sends back
# stderr message has extra information, such as debugging message
return ProcessResult(process)
def heron_tar(class_name, topology_tar, arguments, tmpdir_root, java_defines):
'''
:param class_name:
:param topology_tar:
:param arguments:
:param tmpdir_root:
:param java_defines:
:return:
'''
# Extract tar to a tmp folder.
tmpdir = tempfile.mkdtemp(dir=tmpdir_root, prefix='tmp')
with contextlib.closing(tarfile.open(topology_tar)) as tar:
tar.extractall(path=tmpdir)
# A tar generated by pants has all dependency jars under libs/
# in addition to the topology jar at top level. Pants keeps
# filename for jar and tar the same except for extension.
topology_jar = os.path.basename(topology_tar).replace(".tar.gz", "").replace(".tar", "") + ".jar"
extra_jars = [
os.path.join(tmpdir, topology_jar),
os.path.join(tmpdir, "*"),
os.path.join(tmpdir, "libs/*")
]
lib_jars = config.get_heron_libs(jars.topology_jars())
# Now execute the class
return heron_class(class_name, lib_jars, extra_jars, arguments, java_defines)
def heron_pex(topology_pex, topology_class_name, args=None):
"""Use a topology defined in a PEX."""
Log.debug("Importing %s from %s", topology_class_name, topology_pex)
if topology_class_name == '-':
# loading topology by running its main method (if __name__ == "__main__")
heron_env = os.environ.copy()
heron_env['HERON_OPTIONS'] = opts.get_heron_config()
cmd = [topology_pex]
if args is not None:
cmd.extend(args)
Log.debug("Invoking class using command: ``%s''", ' '.join(cmd))
Log.debug('Heron options: {%s}', str(heron_env['HERON_OPTIONS']))
# invoke the command with subprocess and print error message, if any
# pylint: disable=consider-using-with
process = subprocess.Popen(cmd, env=heron_env, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, universal_newlines=True, bufsize=1)
# pylint: disable=fixme
# todo(rli): improve python topology submission workflow
return ProcessResult(process)
try:
# loading topology from Topology's subclass (no main method)
# to support specifying the name of topology
Log.debug("args: %s", args)
if args is not None and isinstance(args, (list, tuple)) and len(args) > 0:
opts.set_config('cmdline.topology.name', args[0])
os.environ["HERON_OPTIONS"] = opts.get_heron_config()
Log.debug("Heron options: {%s}", os.environ["HERON_OPTIONS"])
pex_loader.load_pex(topology_pex)
topology_class = pex_loader.import_and_get_class(topology_pex, topology_class_name)
topology_class.write()
return SimpleResult(Status.Ok)
except Exception as ex:
Log.debug(traceback.format_exc())
err_context = f"Topology {topology_class_name} failed to be loaded from the given pex: {ex}"
return SimpleResult(Status.HeronError, err_context)
return None
# pylint: disable=superfluous-parens
def heron_cpp(topology_binary, args=None):
Log.debug("Executing %s", topology_binary)
heron_env = os.environ.copy()
heron_env['HERON_OPTIONS'] = opts.get_heron_config()
cmd = [topology_binary]
if args is not None:
cmd.extend(args)
Log.debug("Invoking binary using command: ``%s''", ' '.join(cmd))
Log.debug('Heron options: {%s}', str(heron_env['HERON_OPTIONS']))
print(f"""Invoking class using command: ``{' '.join(cmd)}''""")
print(f"Heron options: {str(heron_env['HERON_OPTIONS'])}")
# invoke the command with subprocess and print error message, if any
# pylint: disable=consider-using-with
proc = subprocess.Popen(cmd, env=heron_env, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, universal_newlines=True, bufsize=1)
return ProcessResult(proc)
| heron_class |
layer_serialization.py | # Copyright 2019 The TensorFlow 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.
# ==============================================================================
"""Classes and functions implementing Layer SavedModel serialization."""
from keras.mixed_precision import policy
from keras.saving.saved_model import base_serialization
from keras.saving.saved_model import constants
from keras.saving.saved_model import save_impl
from keras.saving.saved_model import serialized_attributes
from keras.utils import generic_utils
import tensorflow.compat.v2 as tf
class LayerSavedModelSaver(base_serialization.SavedModelSaver):
"""Implements Layer SavedModel serialization."""
@property
def object_identifier(self):
return constants.LAYER_IDENTIFIER
@property
def python_properties(self):
# TODO(kathywu): Add python property validator
return self._python_properties_internal()
def _python_properties_internal(self):
|
def objects_to_serialize(self, serialization_cache):
return (self._get_serialized_attributes(
serialization_cache).objects_to_serialize)
def functions_to_serialize(self, serialization_cache):
return (self._get_serialized_attributes(
serialization_cache).functions_to_serialize)
def _get_serialized_attributes(self, serialization_cache):
"""Generates or retrieves serialized attributes from cache."""
keras_cache = serialization_cache.setdefault(constants.KERAS_CACHE_KEY, {})
if self.obj in keras_cache:
return keras_cache[self.obj]
serialized_attr = keras_cache[self.obj] = (
serialized_attributes.SerializedAttributes.new(self.obj))
if (save_impl.should_skip_serialization(self.obj) or
self.obj._must_restore_from_config): # pylint: disable=protected-access
return serialized_attr
object_dict, function_dict = self._get_serialized_attributes_internal(
serialization_cache)
serialized_attr.set_and_validate_objects(object_dict)
serialized_attr.set_and_validate_functions(function_dict)
return serialized_attr
def _get_serialized_attributes_internal(self, serialization_cache):
"""Returns dictionary of serialized attributes."""
objects = save_impl.wrap_layer_objects(self.obj, serialization_cache)
functions = save_impl.wrap_layer_functions(self.obj, serialization_cache)
# Attribute validator requires that the default save signature is added to
# function dict, even if the value is None.
functions['_default_save_signature'] = None
return objects, functions
# TODO(kathywu): Move serialization utils (and related utils from
# generic_utils.py) to a separate file.
def get_serialized(obj):
with generic_utils.skip_failed_serialization():
# Store the config dictionary, which may be used when reviving the object.
# When loading, the program will attempt to revive the object from config,
# and if that fails, the object will be revived from the SavedModel.
return generic_utils.serialize_keras_object(obj)
class InputLayerSavedModelSaver(base_serialization.SavedModelSaver):
"""InputLayer serialization."""
@property
def object_identifier(self):
return constants.INPUT_LAYER_IDENTIFIER
@property
def python_properties(self):
return dict(
class_name=type(self.obj).__name__,
name=self.obj.name,
dtype=self.obj.dtype,
sparse=self.obj.sparse,
ragged=self.obj.ragged,
batch_input_shape=self.obj._batch_input_shape, # pylint: disable=protected-access
config=self.obj.get_config())
def objects_to_serialize(self, serialization_cache):
return {}
def functions_to_serialize(self, serialization_cache):
return {}
class RNNSavedModelSaver(LayerSavedModelSaver):
"""RNN layer serialization."""
@property
def object_identifier(self):
return constants.RNN_LAYER_IDENTIFIER
def _get_serialized_attributes_internal(self, serialization_cache):
objects, functions = (
super(RNNSavedModelSaver, self)._get_serialized_attributes_internal(
serialization_cache))
states = tf.__internal__.tracking.wrap(self.obj.states)
# SaveModel require all the objects to be Trackable when saving.
# If the states is still a tuple after wrap_or_unwrap, it means it doesn't
# contain any trackable item within it, eg empty tuple or (None, None) for
# stateless ConvLSTM2D. We convert them to list so that wrap_or_unwrap can
# make it a Trackable again for saving. When loaded, ConvLSTM2D is
# able to handle the tuple/list conversion.
if isinstance(states, tuple):
states = tf.__internal__.tracking.wrap(list(states))
objects['states'] = states
return objects, functions
class VocabularySavedModelSaver(LayerSavedModelSaver):
"""Handles vocabulary layer serialization.
This class is needed for StringLookup, IntegerLookup, and TextVectorization,
which all have a vocabulary as part of the config. Currently, we keep this
vocab as part of the config until saving, when we need to clear it to avoid
initializing a StaticHashTable twice (once when restoring the config and once
when restoring restoring module resources). After clearing the vocab, we
presist a property to the layer indicating it was constructed with a vocab.
"""
@property
def python_properties(self):
# TODO(kathywu): Add python property validator
metadata = self._python_properties_internal()
# Clear the vocabulary from the config during saving.
metadata['config']['vocabulary'] = None
# Persist a property to track that a vocabulary was passed on construction.
metadata['config']['has_input_vocabulary'] = self.obj._has_input_vocabulary # pylint: disable=protected-access
return metadata
| """Returns dictionary of all python properties."""
# TODO(kathywu): Add support for metrics serialization.
# TODO(kathywu): Synchronize with the keras spec (go/keras-json-spec) once
# the python config serialization has caught up.
metadata = dict(
name=self.obj.name,
trainable=self.obj.trainable,
expects_training_arg=self.obj._expects_training_arg, # pylint: disable=protected-access
dtype=policy.serialize(self.obj._dtype_policy), # pylint: disable=protected-access
batch_input_shape=getattr(self.obj, '_batch_input_shape', None),
stateful=self.obj.stateful,
must_restore_from_config=self.obj._must_restore_from_config, # pylint: disable=protected-access
)
metadata.update(get_serialized(self.obj))
if self.obj.input_spec is not None:
# Layer's input_spec has already been type-checked in the property setter.
metadata['input_spec'] = tf.nest.map_structure(
lambda x: generic_utils.serialize_keras_object(x) if x else None,
self.obj.input_spec)
if (self.obj.activity_regularizer is not None and
hasattr(self.obj.activity_regularizer, 'get_config')):
metadata['activity_regularizer'] = generic_utils.serialize_keras_object(
self.obj.activity_regularizer)
if self.obj._build_input_shape is not None: # pylint: disable=protected-access
metadata['build_input_shape'] = self.obj._build_input_shape # pylint: disable=protected-access
return metadata |
h2_gen.go | // Copyright 2017 The go-hep Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Automatically generated. DO NOT EDIT.
package rootio
import (
"bytes"
"fmt"
"math"
"reflect"
)
// H2F implements ROOT TH2F
type H2F struct {
th2
arr ArrayF
}
func (*H2F) isH2() {}
// Class returns the ROOT class name.
func (*H2F) Class() string {
return "TH2F"
}
func (h *H2F) Array() ArrayF {
return h.arr
}
// Rank returns the number of dimensions of this histogram.
func (h *H2F) Rank() int {
return 2
}
// NbinsX returns the number of bins in X.
func (h *H2F) NbinsX() int {
return h.th1.xaxis.nbins
}
// XAxis returns the axis along X.
func (h *H2F) XAxis() Axis {
return &h.th1.xaxis
}
// XBinCenter returns the bin center value in X.
func (h *H2F) XBinCenter(i int) float64 {
return float64(h.th1.xaxis.BinCenter(i))
}
// XBinContent returns the bin content value in X.
func (h *H2F) XBinContent(i int) float64 {
return float64(h.arr.Data[i])
}
// XBinError returns the bin error in X.
func (h *H2F) XBinError(i int) float64 {
if len(h.th1.sumw2.Data) > 0 {
return math.Sqrt(float64(h.th1.sumw2.Data[i]))
}
return math.Sqrt(math.Abs(float64(h.arr.Data[i])))
}
// XBinLowEdge returns the bin lower edge value in X.
func (h *H2F) XBinLowEdge(i int) float64 {
return h.th1.xaxis.BinLowEdge(i)
}
// XBinWidth returns the bin width in X.
func (h *H2F) XBinWidth(i int) float64 {
return h.th1.xaxis.BinWidth(i)
}
// NbinsY returns the number of bins in Y.
func (h *H2F) NbinsY() int {
return h.th1.yaxis.nbins
}
// YAxis returns the axis along Y.
func (h *H2F) YAxis() Axis {
return &h.th1.yaxis
}
// YBinCenter returns the bin center value in Y.
func (h *H2F) YBinCenter(i int) float64 {
return float64(h.th1.yaxis.BinCenter(i))
}
// YBinContent returns the bin content value in Y.
func (h *H2F) YBinContent(i int) float64 {
return float64(h.arr.Data[i])
}
// YBinError returns the bin error in Y.
func (h *H2F) YBinError(i int) float64 {
if len(h.th1.sumw2.Data) > 0 {
return math.Sqrt(float64(h.th1.sumw2.Data[i]))
}
return math.Sqrt(math.Abs(float64(h.arr.Data[i])))
}
// YBinLowEdge returns the bin lower edge value in Y.
func (h *H2F) YBinLowEdge(i int) float64 {
return h.th1.yaxis.BinLowEdge(i)
}
// YBinWidth returns the bin width in Y.
func (h *H2F) YBinWidth(i int) float64 {
return h.th1.yaxis.BinWidth(i)
}
// bin returns the regularized bin number given an (x,y) bin index pair.
func (h *H2F) bin(ix, iy int) int {
nx := h.th1.xaxis.nbins + 1 // overflow bin
ny := h.th1.yaxis.nbins + 1 // overflow bin
switch {
case ix < 0:
ix = 0
case ix > nx:
ix = nx
}
switch {
case iy < 0:
iy = 0
case iy > ny:
iy = ny
}
return ix + (nx+1)*iy
}
func (h *H2F) dist2D(ix, iy int) dist2D {
i := h.bin(ix, iy)
vx := h.XBinContent(i)
xerr := h.XBinError(i)
nx := h.entries(vx, xerr)
vy := h.YBinContent(i)
yerr := h.YBinError(i)
ny := h.entries(vy, yerr)
sumw := h.arr.Data[i]
sumw2 := 0.0
if len(h.th1.sumw2.Data) > 0 {
sumw2 = h.th1.sumw2.Data[i]
}
return dist2D{
x: dist0D{
n: nx,
sumw: float64(sumw),
sumw2: float64(sumw2),
},
y: dist0D{
n: ny,
sumw: float64(sumw),
sumw2: float64(sumw2),
},
}
}
func (h *H2F) entries(height, err float64) int64 {
if height <= 0 {
return 0
}
v := height / err
return int64(v*v + 0.5)
}
func (h *H2F) MarshalYODA() ([]byte, error) {
var (
nx = h.NbinsX()
ny = h.NbinsY()
xinrange = 1
yinrange = 1
dflow = [8]dist2D{
h.dist2D(0, 0),
h.dist2D(0, yinrange),
h.dist2D(0, ny+1),
h.dist2D(nx+1, 0),
h.dist2D(nx+1, yinrange),
h.dist2D(nx+1, ny+1),
h.dist2D(xinrange, 0),
h.dist2D(xinrange, ny+1),
}
dtot = dist2D{
x: dist0D{
n: int64(h.Entries()),
sumw: float64(h.SumW()),
sumw2: float64(h.SumW2()),
sumwx: float64(h.SumWX()),
sumwx2: float64(h.SumWX2()),
},
y: dist0D{
n: int64(h.Entries()),
sumw: float64(h.SumW()),
sumw2: float64(h.SumW2()),
sumwx: float64(h.SumWY()),
sumwx2: float64(h.SumWY2()),
},
sumWXY: h.SumWXY(),
}
dists = make([]dist2D, int(nx*ny))
)
for ix := 0; ix < nx; ix++ {
for iy := 0; iy < ny; iy++ {
i := iy*nx + ix
dists[i] = h.dist2D(ix+1, iy+1)
}
}
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "BEGIN YODA_HISTO2D /%s\n", h.Name())
fmt.Fprintf(buf, "Path=/%s\n", h.Name())
fmt.Fprintf(buf, "Title=%s\n", h.Title())
fmt.Fprintf(buf, "Type=Histo2D\n")
fmt.Fprintf(buf, "# Mean: %e\n", math.NaN())
fmt.Fprintf(buf, "# Volume: %e\n", math.NaN())
fmt.Fprintf(buf, "# ID\t ID\t sumw\t sumw2\t sumwx\t sumwx2\t sumwy\t sumwy2\t sumwxy\t numEntries\n")
var name = "Total "
d := &dtot
fmt.Fprintf(
buf,
"%s\t%s\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%d\n",
name, name,
d.SumW(), d.SumW2(), d.SumWX(), d.SumWX2(), d.SumWY(), d.SumWY2(), d.sumWXY, d.Entries(),
)
if false { // FIXME(sbinet)
for _, d := range dflow {
fmt.Fprintf(
buf,
"%s\t%s\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%d\n",
name, name,
d.SumW(), d.SumW2(), d.SumWX(), d.SumWX2(), d.SumWY(), d.SumWY2(), d.sumWXY, d.Entries(),
)
}
} else {
// outflows
fmt.Fprintf(buf, "# 2D outflow persistency not currently supported until API is stable\n")
}
// bins
fmt.Fprintf(buf, "# xlow\t xhigh\t ylow\t yhigh\t sumw\t sumw2\t sumwx\t sumwx2\t sumwy\t sumwy2\t sumwxy\t numEntries\n")
for ix := 0; ix < nx; ix++ {
for iy := 0; iy < ny; iy++ {
xmin := h.XBinLowEdge(ix + 1)
xmax := h.XBinWidth(ix+1) + xmin
ymin := h.YBinLowEdge(iy + 1)
ymax := h.YBinWidth(iy+1) + ymin
i := iy*nx + ix
d := &dists[i]
fmt.Fprintf(
buf,
"%e\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%d\n",
xmin, xmax, ymin, ymax,
d.SumW(), d.SumW2(), d.SumWX(), d.SumWX2(), d.SumWY(), d.SumWY2(), d.sumWXY, d.Entries(),
)
}
}
fmt.Fprintf(buf, "END YODA_HISTO2D\n\n")
return buf.Bytes(), nil
}
func (h *H2F) UnmarshalROOT(r *RBuffer) error {
if r.err != nil {
return r.err
}
beg := r.Pos()
vers, pos, bcnt := r.ReadVersion()
if vers < 1 {
return errorf("rootio: TH2F version too old (%d<1)", vers)
}
for _, v := range []ROOTUnmarshaler{
&h.th2,
&h.arr,
} {
if err := v.UnmarshalROOT(r); err != nil {
r.err = err
return r.err
}
}
r.CheckByteCount(pos, bcnt, beg, "TH2F")
return r.err
}
func init() {
f := func() reflect.Value {
o := &H2F{}
return reflect.ValueOf(o)
}
Factory.add("TH2F", f)
Factory.add("*rootio.H2F", f)
}
var (
_ Object = (*H2F)(nil)
_ Named = (*H2F)(nil)
_ H2 = (*H2F)(nil)
_ ROOTUnmarshaler = (*H2F)(nil)
)
// H2D implements ROOT TH2D
type H2D struct {
th2
arr ArrayD
}
func (*H2D) isH2() {}
// Class returns the ROOT class name.
func (*H2D) Class() string {
return "TH2D"
}
func (h *H2D) Array() ArrayD {
return h.arr
}
// Rank returns the number of dimensions of this histogram.
func (h *H2D) Rank() int {
return 2
}
// NbinsX returns the number of bins in X.
func (h *H2D) NbinsX() int {
return h.th1.xaxis.nbins
}
// XAxis returns the axis along X.
func (h *H2D) XAxis() Axis {
return &h.th1.xaxis
}
// XBinCenter returns the bin center value in X.
func (h *H2D) XBinCenter(i int) float64 {
return float64(h.th1.xaxis.BinCenter(i))
}
// XBinContent returns the bin content value in X.
func (h *H2D) XBinContent(i int) float64 {
return float64(h.arr.Data[i])
}
// XBinError returns the bin error in X.
func (h *H2D) XBinError(i int) float64 {
if len(h.th1.sumw2.Data) > 0 {
return math.Sqrt(float64(h.th1.sumw2.Data[i]))
}
return math.Sqrt(math.Abs(float64(h.arr.Data[i])))
}
// XBinLowEdge returns the bin lower edge value in X.
func (h *H2D) XBinLowEdge(i int) float64 {
return h.th1.xaxis.BinLowEdge(i)
}
// XBinWidth returns the bin width in X.
func (h *H2D) XBinWidth(i int) float64 {
return h.th1.xaxis.BinWidth(i)
}
// NbinsY returns the number of bins in Y.
func (h *H2D) NbinsY() int {
return h.th1.yaxis.nbins
}
// YAxis returns the axis along Y.
func (h *H2D) YAxis() Axis {
return &h.th1.yaxis
}
// YBinCenter returns the bin center value in Y.
func (h *H2D) YBinCenter(i int) float64 {
return float64(h.th1.yaxis.BinCenter(i))
}
// YBinContent returns the bin content value in Y.
func (h *H2D) YBinContent(i int) float64 {
return float64(h.arr.Data[i])
}
// YBinError returns the bin error in Y.
func (h *H2D) YBinError(i int) float64 {
if len(h.th1.sumw2.Data) > 0 {
return math.Sqrt(float64(h.th1.sumw2.Data[i]))
}
return math.Sqrt(math.Abs(float64(h.arr.Data[i])))
}
// YBinLowEdge returns the bin lower edge value in Y.
func (h *H2D) YBinLowEdge(i int) float64 {
return h.th1.yaxis.BinLowEdge(i)
}
// YBinWidth returns the bin width in Y.
func (h *H2D) YBinWidth(i int) float64 {
return h.th1.yaxis.BinWidth(i)
}
// bin returns the regularized bin number given an (x,y) bin index pair.
func (h *H2D) bin(ix, iy int) int {
nx := h.th1.xaxis.nbins + 1 // overflow bin
ny := h.th1.yaxis.nbins + 1 // overflow bin
switch {
case ix < 0:
ix = 0
case ix > nx:
ix = nx
}
switch {
case iy < 0:
iy = 0
case iy > ny:
iy = ny
}
return ix + (nx+1)*iy
}
func (h *H2D) dist2D(ix, iy int) dist2D {
i := h.bin(ix, iy)
vx := h.XBinContent(i)
xerr := h.XBinError(i)
nx := h.entries(vx, xerr)
vy := h.YBinContent(i)
yerr := h.YBinError(i)
ny := h.entries(vy, yerr)
sumw := h.arr.Data[i]
sumw2 := 0.0
if len(h.th1.sumw2.Data) > 0 {
sumw2 = h.th1.sumw2.Data[i]
}
return dist2D{
x: dist0D{
n: nx,
sumw: float64(sumw),
sumw2: float64(sumw2),
},
y: dist0D{
n: ny,
sumw: float64(sumw),
sumw2: float64(sumw2),
},
}
}
func (h *H2D) entries(height, err float64) int64 {
if height <= 0 {
return 0
}
v := height / err
return int64(v*v + 0.5)
}
func (h *H2D) MarshalYODA() ([]byte, error) {
var (
nx = h.NbinsX()
ny = h.NbinsY()
xinrange = 1
yinrange = 1
dflow = [8]dist2D{
h.dist2D(0, 0),
h.dist2D(0, yinrange),
h.dist2D(0, ny+1),
h.dist2D(nx+1, 0),
h.dist2D(nx+1, yinrange),
h.dist2D(nx+1, ny+1),
h.dist2D(xinrange, 0),
h.dist2D(xinrange, ny+1),
}
dtot = dist2D{
x: dist0D{
n: int64(h.Entries()),
sumw: float64(h.SumW()),
sumw2: float64(h.SumW2()),
sumwx: float64(h.SumWX()),
sumwx2: float64(h.SumWX2()),
},
y: dist0D{
n: int64(h.Entries()),
sumw: float64(h.SumW()),
sumw2: float64(h.SumW2()),
sumwx: float64(h.SumWY()),
sumwx2: float64(h.SumWY2()),
},
sumWXY: h.SumWXY(),
}
dists = make([]dist2D, int(nx*ny))
)
for ix := 0; ix < nx; ix++ {
for iy := 0; iy < ny; iy++ {
i := iy*nx + ix
dists[i] = h.dist2D(ix+1, iy+1)
}
}
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "BEGIN YODA_HISTO2D /%s\n", h.Name())
fmt.Fprintf(buf, "Path=/%s\n", h.Name())
fmt.Fprintf(buf, "Title=%s\n", h.Title())
fmt.Fprintf(buf, "Type=Histo2D\n")
fmt.Fprintf(buf, "# Mean: %e\n", math.NaN())
fmt.Fprintf(buf, "# Volume: %e\n", math.NaN())
fmt.Fprintf(buf, "# ID\t ID\t sumw\t sumw2\t sumwx\t sumwx2\t sumwy\t sumwy2\t sumwxy\t numEntries\n")
var name = "Total "
d := &dtot
fmt.Fprintf(
buf,
"%s\t%s\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%d\n",
name, name,
d.SumW(), d.SumW2(), d.SumWX(), d.SumWX2(), d.SumWY(), d.SumWY2(), d.sumWXY, d.Entries(),
)
if false { // FIXME(sbinet)
for _, d := range dflow {
fmt.Fprintf(
buf,
"%s\t%s\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%d\n",
name, name,
d.SumW(), d.SumW2(), d.SumWX(), d.SumWX2(), d.SumWY(), d.SumWY2(), d.sumWXY, d.Entries(),
)
}
} else {
// outflows
fmt.Fprintf(buf, "# 2D outflow persistency not currently supported until API is stable\n")
}
// bins
fmt.Fprintf(buf, "# xlow\t xhigh\t ylow\t yhigh\t sumw\t sumw2\t sumwx\t sumwx2\t sumwy\t sumwy2\t sumwxy\t numEntries\n")
for ix := 0; ix < nx; ix++ {
for iy := 0; iy < ny; iy++ {
xmin := h.XBinLowEdge(ix + 1)
xmax := h.XBinWidth(ix+1) + xmin
ymin := h.YBinLowEdge(iy + 1)
ymax := h.YBinWidth(iy+1) + ymin
i := iy*nx + ix
d := &dists[i]
fmt.Fprintf(
buf,
"%e\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%d\n",
xmin, xmax, ymin, ymax,
d.SumW(), d.SumW2(), d.SumWX(), d.SumWX2(), d.SumWY(), d.SumWY2(), d.sumWXY, d.Entries(),
)
}
}
fmt.Fprintf(buf, "END YODA_HISTO2D\n\n")
return buf.Bytes(), nil
}
func (h *H2D) UnmarshalROOT(r *RBuffer) error {
if r.err != nil {
return r.err
}
beg := r.Pos()
vers, pos, bcnt := r.ReadVersion()
if vers < 1 {
return errorf("rootio: TH2D version too old (%d<1)", vers)
}
for _, v := range []ROOTUnmarshaler{
&h.th2,
&h.arr,
} {
if err := v.UnmarshalROOT(r); err != nil {
r.err = err
return r.err
}
}
r.CheckByteCount(pos, bcnt, beg, "TH2D")
return r.err
}
func | () {
f := func() reflect.Value {
o := &H2D{}
return reflect.ValueOf(o)
}
Factory.add("TH2D", f)
Factory.add("*rootio.H2D", f)
}
var (
_ Object = (*H2D)(nil)
_ Named = (*H2D)(nil)
_ H2 = (*H2D)(nil)
_ ROOTUnmarshaler = (*H2D)(nil)
)
// H2I implements ROOT TH2I
type H2I struct {
th2
arr ArrayI
}
func (*H2I) isH2() {}
// Class returns the ROOT class name.
func (*H2I) Class() string {
return "TH2I"
}
func (h *H2I) Array() ArrayI {
return h.arr
}
// Rank returns the number of dimensions of this histogram.
func (h *H2I) Rank() int {
return 2
}
// NbinsX returns the number of bins in X.
func (h *H2I) NbinsX() int {
return h.th1.xaxis.nbins
}
// XAxis returns the axis along X.
func (h *H2I) XAxis() Axis {
return &h.th1.xaxis
}
// XBinCenter returns the bin center value in X.
func (h *H2I) XBinCenter(i int) float64 {
return float64(h.th1.xaxis.BinCenter(i))
}
// XBinContent returns the bin content value in X.
func (h *H2I) XBinContent(i int) float64 {
return float64(h.arr.Data[i])
}
// XBinError returns the bin error in X.
func (h *H2I) XBinError(i int) float64 {
if len(h.th1.sumw2.Data) > 0 {
return math.Sqrt(float64(h.th1.sumw2.Data[i]))
}
return math.Sqrt(math.Abs(float64(h.arr.Data[i])))
}
// XBinLowEdge returns the bin lower edge value in X.
func (h *H2I) XBinLowEdge(i int) float64 {
return h.th1.xaxis.BinLowEdge(i)
}
// XBinWidth returns the bin width in X.
func (h *H2I) XBinWidth(i int) float64 {
return h.th1.xaxis.BinWidth(i)
}
// NbinsY returns the number of bins in Y.
func (h *H2I) NbinsY() int {
return h.th1.yaxis.nbins
}
// YAxis returns the axis along Y.
func (h *H2I) YAxis() Axis {
return &h.th1.yaxis
}
// YBinCenter returns the bin center value in Y.
func (h *H2I) YBinCenter(i int) float64 {
return float64(h.th1.yaxis.BinCenter(i))
}
// YBinContent returns the bin content value in Y.
func (h *H2I) YBinContent(i int) float64 {
return float64(h.arr.Data[i])
}
// YBinError returns the bin error in Y.
func (h *H2I) YBinError(i int) float64 {
if len(h.th1.sumw2.Data) > 0 {
return math.Sqrt(float64(h.th1.sumw2.Data[i]))
}
return math.Sqrt(math.Abs(float64(h.arr.Data[i])))
}
// YBinLowEdge returns the bin lower edge value in Y.
func (h *H2I) YBinLowEdge(i int) float64 {
return h.th1.yaxis.BinLowEdge(i)
}
// YBinWidth returns the bin width in Y.
func (h *H2I) YBinWidth(i int) float64 {
return h.th1.yaxis.BinWidth(i)
}
// bin returns the regularized bin number given an (x,y) bin index pair.
func (h *H2I) bin(ix, iy int) int {
nx := h.th1.xaxis.nbins + 1 // overflow bin
ny := h.th1.yaxis.nbins + 1 // overflow bin
switch {
case ix < 0:
ix = 0
case ix > nx:
ix = nx
}
switch {
case iy < 0:
iy = 0
case iy > ny:
iy = ny
}
return ix + (nx+1)*iy
}
func (h *H2I) dist2D(ix, iy int) dist2D {
i := h.bin(ix, iy)
vx := h.XBinContent(i)
xerr := h.XBinError(i)
nx := h.entries(vx, xerr)
vy := h.YBinContent(i)
yerr := h.YBinError(i)
ny := h.entries(vy, yerr)
sumw := h.arr.Data[i]
sumw2 := 0.0
if len(h.th1.sumw2.Data) > 0 {
sumw2 = h.th1.sumw2.Data[i]
}
return dist2D{
x: dist0D{
n: nx,
sumw: float64(sumw),
sumw2: float64(sumw2),
},
y: dist0D{
n: ny,
sumw: float64(sumw),
sumw2: float64(sumw2),
},
}
}
func (h *H2I) entries(height, err float64) int64 {
if height <= 0 {
return 0
}
v := height / err
return int64(v*v + 0.5)
}
func (h *H2I) MarshalYODA() ([]byte, error) {
var (
nx = h.NbinsX()
ny = h.NbinsY()
xinrange = 1
yinrange = 1
dflow = [8]dist2D{
h.dist2D(0, 0),
h.dist2D(0, yinrange),
h.dist2D(0, ny+1),
h.dist2D(nx+1, 0),
h.dist2D(nx+1, yinrange),
h.dist2D(nx+1, ny+1),
h.dist2D(xinrange, 0),
h.dist2D(xinrange, ny+1),
}
dtot = dist2D{
x: dist0D{
n: int64(h.Entries()),
sumw: float64(h.SumW()),
sumw2: float64(h.SumW2()),
sumwx: float64(h.SumWX()),
sumwx2: float64(h.SumWX2()),
},
y: dist0D{
n: int64(h.Entries()),
sumw: float64(h.SumW()),
sumw2: float64(h.SumW2()),
sumwx: float64(h.SumWY()),
sumwx2: float64(h.SumWY2()),
},
sumWXY: h.SumWXY(),
}
dists = make([]dist2D, int(nx*ny))
)
for ix := 0; ix < nx; ix++ {
for iy := 0; iy < ny; iy++ {
i := iy*nx + ix
dists[i] = h.dist2D(ix+1, iy+1)
}
}
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "BEGIN YODA_HISTO2D /%s\n", h.Name())
fmt.Fprintf(buf, "Path=/%s\n", h.Name())
fmt.Fprintf(buf, "Title=%s\n", h.Title())
fmt.Fprintf(buf, "Type=Histo2D\n")
fmt.Fprintf(buf, "# Mean: %e\n", math.NaN())
fmt.Fprintf(buf, "# Volume: %e\n", math.NaN())
fmt.Fprintf(buf, "# ID\t ID\t sumw\t sumw2\t sumwx\t sumwx2\t sumwy\t sumwy2\t sumwxy\t numEntries\n")
var name = "Total "
d := &dtot
fmt.Fprintf(
buf,
"%s\t%s\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%d\n",
name, name,
d.SumW(), d.SumW2(), d.SumWX(), d.SumWX2(), d.SumWY(), d.SumWY2(), d.sumWXY, d.Entries(),
)
if false { // FIXME(sbinet)
for _, d := range dflow {
fmt.Fprintf(
buf,
"%s\t%s\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%d\n",
name, name,
d.SumW(), d.SumW2(), d.SumWX(), d.SumWX2(), d.SumWY(), d.SumWY2(), d.sumWXY, d.Entries(),
)
}
} else {
// outflows
fmt.Fprintf(buf, "# 2D outflow persistency not currently supported until API is stable\n")
}
// bins
fmt.Fprintf(buf, "# xlow\t xhigh\t ylow\t yhigh\t sumw\t sumw2\t sumwx\t sumwx2\t sumwy\t sumwy2\t sumwxy\t numEntries\n")
for ix := 0; ix < nx; ix++ {
for iy := 0; iy < ny; iy++ {
xmin := h.XBinLowEdge(ix + 1)
xmax := h.XBinWidth(ix+1) + xmin
ymin := h.YBinLowEdge(iy + 1)
ymax := h.YBinWidth(iy+1) + ymin
i := iy*nx + ix
d := &dists[i]
fmt.Fprintf(
buf,
"%e\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%e\t%d\n",
xmin, xmax, ymin, ymax,
d.SumW(), d.SumW2(), d.SumWX(), d.SumWX2(), d.SumWY(), d.SumWY2(), d.sumWXY, d.Entries(),
)
}
}
fmt.Fprintf(buf, "END YODA_HISTO2D\n\n")
return buf.Bytes(), nil
}
func (h *H2I) UnmarshalROOT(r *RBuffer) error {
if r.err != nil {
return r.err
}
beg := r.Pos()
vers, pos, bcnt := r.ReadVersion()
if vers < 1 {
return errorf("rootio: TH2I version too old (%d<1)", vers)
}
for _, v := range []ROOTUnmarshaler{
&h.th2,
&h.arr,
} {
if err := v.UnmarshalROOT(r); err != nil {
r.err = err
return r.err
}
}
r.CheckByteCount(pos, bcnt, beg, "TH2I")
return r.err
}
func init() {
f := func() reflect.Value {
o := &H2I{}
return reflect.ValueOf(o)
}
Factory.add("TH2I", f)
Factory.add("*rootio.H2I", f)
}
var (
_ Object = (*H2I)(nil)
_ Named = (*H2I)(nil)
_ H2 = (*H2I)(nil)
_ ROOTUnmarshaler = (*H2I)(nil)
)
| init |
_web_application_firewall_policies_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from msrest.polling import LROPoller, NoPolling
from msrestazure.polling.arm_polling import ARMPolling
from .. import models
class WebApplicationFirewallPoliciesOperations(object):
"""WebApplicationFirewallPoliciesOperations operations.
You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
:ivar api_version: Client API version. Constant value: "2019-12-01".
"""
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.api_version = "2019-12-01"
self.config = config
def list(
self, resource_group_name, custom_headers=None, raw=False, **operation_config):
"""Lists all of the protection policies within a resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of WebApplicationFirewallPolicy
:rtype:
~azure.mgmt.network.v2019_12_01.models.WebApplicationFirewallPolicyPaged[~azure.mgmt.network.v2019_12_01.models.WebApplicationFirewallPolicy]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
def prepare_request(next_link=None):
if not next_link:
# Construct URL
url = self.list.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
else:
url = next_link
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
return request
def internal_paging(next_link=None):
request = prepare_request(next_link)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
# Deserialize response
header_dict = None
if raw:
header_dict = {}
deserialized = models.WebApplicationFirewallPolicyPaged(internal_paging, self._deserialize.dependencies, header_dict)
return deserialized
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies'}
def list_all(
self, custom_headers=None, raw=False, **operation_config):
"""Gets all the WAF policies in a subscription.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of WebApplicationFirewallPolicy
:rtype:
~azure.mgmt.network.v2019_12_01.models.WebApplicationFirewallPolicyPaged[~azure.mgmt.network.v2019_12_01.models.WebApplicationFirewallPolicy]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
def prepare_request(next_link=None):
if not next_link:
# Construct URL
url = self.list_all.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
else:
url = next_link
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
return request
def internal_paging(next_link=None):
request = prepare_request(next_link)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
# Deserialize response
header_dict = None
if raw:
header_dict = {}
deserialized = models.WebApplicationFirewallPolicyPaged(internal_paging, self._deserialize.dependencies, header_dict)
return deserialized
list_all.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies'}
def get(
self, resource_group_name, policy_name, custom_headers=None, raw=False, **operation_config):
"""Retrieve protection policy with specified name within a resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param policy_name: The name of the policy.
:type policy_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WebApplicationFirewallPolicy or ClientRawResponse if raw=true
:rtype:
~azure.mgmt.network.v2019_12_01.models.WebApplicationFirewallPolicy or
~msrest.pipeline.ClientRawResponse
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
# Construct URL
url = self.get.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'policyName': self._serialize.url("policy_name", policy_name, 'str', max_length=128),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WebApplicationFirewallPolicy', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies/{policyName}'}
def create_or_update(
self, resource_group_name, policy_name, parameters, custom_headers=None, raw=False, **operation_config):
"""Creates or update policy with specified rule set name within a resource
group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param policy_name: The name of the policy.
:type policy_name: str
:param parameters: Policy to be created.
:type parameters:
~azure.mgmt.network.v2019_12_01.models.WebApplicationFirewallPolicy
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: WebApplicationFirewallPolicy or ClientRawResponse if raw=true
:rtype:
~azure.mgmt.network.v2019_12_01.models.WebApplicationFirewallPolicy or
~msrest.pipeline.ClientRawResponse
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
# Construct URL
url = self.create_or_update.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'policyName': self._serialize.url("policy_name", policy_name, 'str', max_length=128),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct body
body_content = self._serialize.body(parameters, 'WebApplicationFirewallPolicy')
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 201]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('WebApplicationFirewallPolicy', response)
if response.status_code == 201:
deserialized = self._deserialize('WebApplicationFirewallPolicy', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies/{policyName}'}
def _delete_initial(
self, resource_group_name, policy_name, custom_headers=None, raw=False, **operation_config):
# Construct URL
url = self.delete.metadata['url']
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'policyName': self._serialize.url("policy_name", policy_name, 'str', max_length=128),
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200, 202, 204]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def delete(
self, resource_group_name, policy_name, custom_headers=None, raw=False, polling=True, **operation_config):
"""Deletes Policy.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param policy_name: The name of the policy.
:type policy_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns None or
ClientRawResponse<None> if raw==True
:rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
raw_result = self._delete_initial(
resource_group_name=resource_group_name,
policy_name=policy_name,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
|
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies/{policyName}'}
| if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response |
textholder.py | # encoding: utf-8
from typing import Optional, Union
class Indent:
class IdentStart:
def __init__(self, text):
self.text = text
class IdentEnd:
def __init__(self, text):
self.text = text
class IdentEndLater:
def __init__(self, text):
self.text = text
def __init__(self, text: Optional[Union[str, "TextHolder"]] = None):
self.text = text
def __add__(self, other: str):
assert self.text is None
return Indent(other)
def __radd__(self, other: str):
assert self.text is None
return Indent.IdentStart(other)
def __rsub__(self, other: str):
assert self.text is None
return Indent.IdentEnd(other)
class IndentLater:
def __rsub__(self, other: str):
return Indent.IdentEndLater(other)
class TextHolder:
def __init__(self, text: Optional[str] = None):
super().__init__()
if text is None:
text = ""
self.text = text
self.ident_text = " "
self._ident = 0
def __add__(self, other: Union[str, int]):
if isinstance(other, Indent.IdentStart):
self.append(other.text)
self.ident(1)
elif isinstance(other, Indent.IdentEnd):
self.ident(-1)
self.append(other.text)
elif isinstance(other, Indent.IdentEndLater):
self.append(other.text)
self.ident(-1)
elif isinstance(other, Indent):
self.append(
TextHolder(str(other.text)).ident_all(
n=self._ident + 1, ident_text=self.ident_text
),
add_ident=False,
)
elif isinstance(other, str):
self.append(other)
elif isinstance(other, TextHolder):
self.append( | n=self._ident, ident_text=self.ident_text
),
add_ident=False,
)
elif isinstance(other, int):
self.ident(other)
else:
raise TypeError(f"can only add str or int, but {type(other)} got")
return self
def __sub__(self, other):
if isinstance(other, int):
self.ident(-other)
else:
raise TypeError(f"can only add str or int, but {type(other)} got")
return self
def __bool__(self):
return bool(self.text)
def __str__(self):
return self.text
def append(
self,
text: Union[str, "TextHolder"],
ensure_new_line=True,
ignore_empty=True,
add_ident=True,
):
strtext = str(text)
if ignore_empty and not strtext:
return self
if not strtext.endswith("\n") and ensure_new_line:
strtext += "\n"
if add_ident:
self.text += self._ident * self.ident_text + strtext
else:
self.text += strtext
return self
def ident_all(self, n: int = 1, ident_text: str = None):
if ident_text is None:
ident_text = self.ident_text
text = self.text
if text.endswith("\n"):
text = text[:-1]
return "\n".join([ident_text * n + i for i in text.split("\n")])
def ident(self, n: int = 1):
self._ident += n
return self | TextHolder(str(other.text)).ident_all( |
holder.rs | use std::collections::HashMap;
use crate::handlers::issuance::holder::state_machine::HolderSM;
use crate::handlers::issuance::messages::CredentialIssuanceMessage;
use crate::messages::a2a::A2AMessage;
use crate::handlers::connection::connection::Connection;
use crate::messages::issuance::credential_offer::CredentialOffer;
use crate::error::prelude::*;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Holder {
holder_sm: HolderSM
}
#[derive(Debug, PartialEq)]
pub enum HolderState {
OfferReceived,
RequestSent,
Finished,
Failed
}
impl Holder {
pub fn create(credential_offer: CredentialOffer, source_id: &str) -> VcxResult<Holder> {
trace!("Holder::holder_create_credential >>> credential_offer: {:?}, source_id: {:?}", credential_offer, source_id);
let holder_sm = HolderSM::new(credential_offer, source_id.to_string());
Ok(Holder { holder_sm })
}
pub fn send_request(&mut self, my_pw_did: String, send_message: impl Fn(&A2AMessage) -> VcxResult<()>) -> VcxResult<()> {
self.step(CredentialIssuanceMessage::CredentialRequestSend(my_pw_did), Some(&send_message))
}
pub fn is_terminal_state(&self) -> bool {
self.holder_sm.is_terminal_state()
}
pub fn find_message_to_handle(&self, messages: HashMap<String, A2AMessage>) -> Option<(String, A2AMessage)> {
self.holder_sm.find_message_to_handle(messages)
}
pub fn get_state(&self) -> HolderState {
self.holder_sm.get_state()
}
pub fn get_source_id(&self) -> String {
self.holder_sm.get_source_id()
}
pub fn get_credential(&self) -> VcxResult<(String, A2AMessage)> {
self.holder_sm.get_credential()
}
pub fn get_attributes(&self) -> VcxResult<String> {
self.holder_sm.get_attributes()
}
pub fn get_attachment(&self) -> VcxResult<String> {
self.holder_sm.get_attachment()
}
pub fn get_tails_location(&self) -> VcxResult<String> {
self.holder_sm.get_tails_location()
}
pub fn get_tails_hash(&self) -> VcxResult<String> {
self.holder_sm.get_tails_hash()
}
pub fn get_rev_reg_id(&self) -> VcxResult<String> {
self.holder_sm.get_rev_reg_id()
}
pub fn is_revokable(&self) -> VcxResult<bool> {
self.holder_sm.is_revokable()
}
pub fn delete_credential(&self) -> VcxResult<()> {
self.holder_sm.delete_credential()
}
pub fn get_credential_status(&self) -> VcxResult<u32> {
Ok(self.holder_sm.credential_status())
}
pub fn | (&mut self, message: CredentialIssuanceMessage, send_message: Option<&impl Fn(&A2AMessage) -> VcxResult<()>>) -> VcxResult<()> {
self.holder_sm = self.holder_sm.clone().handle_message(message, send_message)?;
Ok(())
}
pub fn update_state(&mut self, connection: &Connection) -> VcxResult<HolderState> {
trace!("Holder::update_state >>> ");
if self.is_terminal_state() { return Ok(self.get_state()); }
let send_message = connection.send_message_closure()?;
let messages = connection.get_messages()?;
if let Some((uid, msg)) = self.find_message_to_handle(messages) {
self.step(msg.into(), Some(&send_message))?;
connection.update_message_status(uid)?;
}
Ok(self.get_state())
}
}
| step |
yeux.ts | import { defer, Deferred } from './defer'
type PoolState = 0 | 1
const ACTIVE: PoolState = 0
const POOLED: PoolState = 1
export interface ObjectPool<T extends object> {
get(): Promise<T>
add(value: T): void
close(onClose: (value: T) => Promise<void> | void): Promise<void>
}
interface Request<T extends object> extends Deferred<T> {
newValue: Promise<T>
}
/** Create an object pool. */
export function | <T extends object>(
create: () => T | Promise<T>,
reset?: (value: T) => void
): ObjectPool<T> {
const pooled: T[] = []
const poolStates = new WeakMap<T, PoolState>()
// Promises for get calls that will use a pooled
// object when it becomes available.
const requests: Request<T>[] = []
// Promises for new objects that will be pooled
// if not used before then.
const surplus: Promise<T>[] = []
return {
async get() {
let value = pooled.shift()
if (value == null) {
// If a previous get call resulted in a surplus,
// use that instead of creating a new object.
const pendingValue = surplus.shift()
const newValue = pendingValue ? pendingValue : create()
if (newValue instanceof Promise) {
const request = defer() as Request<T>
request.newValue = newValue
// If an old value is pooled before the new value
// is ready, use that instead.
requests.push(request)
// Pool the new value if an old value became available
// before this value was ready.
newValue.then(value => {
let index = requests.indexOf(request)
if (index >= 0) {
requests.splice(index, 1)
request.resolve(value)
} else {
// Pool the new object only if our promise is still
// in the surplus, which means no other get call
// has needed to use it.
index = surplus.indexOf(newValue)
if (index >= 0) {
surplus.splice(index, 1)
this.add(value)
}
}
})
// Reject the current request or remove this promise from
// the surplus if `create` throws an error.
newValue.catch(err => {
let index = requests.indexOf(request)
if (index >= 0) {
requests.splice(index, 1)
request.reject(err)
} else if (!pendingValue) {
const index = surplus.indexOf(newValue)
if (index >= 0) {
surplus.splice(index, 1)
}
}
})
value = await request
} else {
value = newValue
}
}
poolStates.set(value, ACTIVE)
return value
},
add(value) {
if (poolStates.get(value) !== POOLED) {
poolStates.set(value, POOLED)
reset?.(value)
const get = requests.shift()
if (get) {
surplus.push(get.newValue)
get.resolve(value)
} else {
pooled.push(value)
}
}
},
async close(onClose) {
const noop = () => {}
await Promise.all(
pooled
.map(onClose)
.concat(surplus.map(promise => promise.then(onClose, noop)))
)
},
}
}
| yeux |
App.js | import React, {Component} from 'react';
import { Route } from 'react-router-dom';
import './App.css';
import MainUserInterface from './components/MainUserInterface'; | render() {
return (
<div className="App">
<Route exact path="/" component={MainUserInterface} />
</div>
);
}
}
export default App; |
class App extends Component {
|
instantiate.go | // Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file implements instantiation of generic types
// through substitution of type parameters by type arguments.
package types
import (
"errors"
"fmt"
"go/token"
)
// Instantiate instantiates the type orig with the given type arguments targs.
// orig must be a *Named or a *Signature type. If there is no error, the
// resulting Type is an instantiated type of the same kind (either a *Named or
// a *Signature). Methods attached to a *Named type are also instantiated, and
// associated with a new *Func that has the same position as the original
// method, but nil function scope.
//
// If ctxt is non-nil, it may be used to de-duplicate the instance against
// previous instances with the same identity. As a special case, generic
// *Signature origin types are only considered identical if they are pointer
// equivalent, so that instantiating distinct (but possibly identical)
// signatures will yield different instances. The use of a shared context does
// not guarantee that identical instances are deduplicated in all cases.
//
// If validate is set, Instantiate verifies that the number of type arguments
// and parameters match, and that the type arguments satisfy their
// corresponding type constraints. If verification fails, the resulting error
// may wrap an *ArgumentError indicating which type argument did not satisfy
// its corresponding type parameter constraint, and why.
//
// If validate is not set, Instantiate does not verify the type argument count
// or whether the type arguments satisfy their constraints. Instantiate is
// guaranteed to not return an error, but may panic. Specifically, for
// *Signature types, Instantiate will panic immediately if the type argument
// count is incorrect; for *Named types, a panic may occur later inside the
// *Named API.
func Instantiate(ctxt *Context, orig Type, targs []Type, validate bool) (Type, error) |
// instance instantiates the given original (generic) function or type with the
// provided type arguments and returns the resulting instance. If an identical
// instance exists already in the given contexts, it returns that instance,
// otherwise it creates a new one.
//
// If expanding is non-nil, it is the Named instance type currently being
// expanded. If ctxt is non-nil, it is the context associated with the current
// type-checking pass or call to Instantiate. At least one of expanding or ctxt
// must be non-nil.
//
// For Named types the resulting instance may be unexpanded.
func (check *Checker) instance(pos token.Pos, orig Type, targs []Type, expanding *Named, ctxt *Context) (res Type) {
// The order of the contexts below matters: we always prefer instances in the
// expanding instance context in order to preserve reference cycles.
//
// Invariant: if expanding != nil, the returned instance will be the instance
// recorded in expanding.inst.ctxt.
var ctxts []*Context
if expanding != nil {
ctxts = append(ctxts, expanding.inst.ctxt)
}
if ctxt != nil {
ctxts = append(ctxts, ctxt)
}
assert(len(ctxts) > 0)
// Compute all hashes; hashes may differ across contexts due to different
// unique IDs for Named types within the hasher.
hashes := make([]string, len(ctxts))
for i, ctxt := range ctxts {
hashes[i] = ctxt.instanceHash(orig, targs)
}
// If local is non-nil, updateContexts return the type recorded in
// local.
updateContexts := func(res Type) Type {
for i := len(ctxts) - 1; i >= 0; i-- {
res = ctxts[i].update(hashes[i], orig, targs, res)
}
return res
}
// typ may already have been instantiated with identical type arguments. In
// that case, re-use the existing instance.
for i, ctxt := range ctxts {
if inst := ctxt.lookup(hashes[i], orig, targs); inst != nil {
return updateContexts(inst)
}
}
switch orig := orig.(type) {
case *Named:
res = check.newNamedInstance(pos, orig, targs, expanding) // substituted lazily
case *Signature:
assert(expanding == nil) // function instances cannot be reached from Named types
tparams := orig.TypeParams()
if !check.validateTArgLen(pos, tparams.Len(), len(targs)) {
return Typ[Invalid]
}
if tparams.Len() == 0 {
return orig // nothing to do (minor optimization)
}
sig := check.subst(pos, orig, makeSubstMap(tparams.list(), targs), nil, ctxt).(*Signature)
// If the signature doesn't use its type parameters, subst
// will not make a copy. In that case, make a copy now (so
// we can set tparams to nil w/o causing side-effects).
if sig == orig {
copy := *sig
sig = ©
}
// After instantiating a generic signature, it is not generic
// anymore; we need to set tparams to nil.
sig.tparams = nil
res = sig
default:
// only types and functions can be generic
panic(fmt.Sprintf("%v: cannot instantiate %v", pos, orig))
}
// Update all contexts; it's possible that we've lost a race.
return updateContexts(res)
}
// validateTArgLen verifies that the length of targs and tparams matches,
// reporting an error if not. If validation fails and check is nil,
// validateTArgLen panics.
func (check *Checker) validateTArgLen(pos token.Pos, ntparams, ntargs int) bool {
if ntargs != ntparams {
// TODO(gri) provide better error message
if check != nil {
check.errorf(atPos(pos), _WrongTypeArgCount, "got %d arguments but %d type parameters", ntargs, ntparams)
return false
}
panic(fmt.Sprintf("%v: got %d arguments but %d type parameters", pos, ntargs, ntparams))
}
return true
}
func (check *Checker) verify(pos token.Pos, tparams []*TypeParam, targs []Type, ctxt *Context) (int, error) {
smap := makeSubstMap(tparams, targs)
for i, tpar := range tparams {
// Ensure that we have a (possibly implicit) interface as type bound (issue #51048).
tpar.iface()
// The type parameter bound is parameterized with the same type parameters
// as the instantiated type; before we can use it for bounds checking we
// need to instantiate it with the type arguments with which we instantiated
// the parameterized type.
bound := check.subst(pos, tpar.bound, smap, nil, ctxt)
if err := check.implements(targs[i], bound); err != nil {
return i, err
}
}
return -1, nil
}
// implements checks if V implements T and reports an error if it doesn't.
// The receiver may be nil if implements is called through an exported
// API call such as AssignableTo.
func (check *Checker) implements(V, T Type) error {
Vu := under(V)
Tu := under(T)
if Vu == Typ[Invalid] || Tu == Typ[Invalid] {
return nil // avoid follow-on errors
}
if p, _ := Vu.(*Pointer); p != nil && under(p.base) == Typ[Invalid] {
return nil // avoid follow-on errors (see issue #49541 for an example)
}
errorf := func(format string, args ...any) error {
return errors.New(check.sprintf(format, args...))
}
Ti, _ := Tu.(*Interface)
if Ti == nil {
var cause string
if isInterfacePtr(Tu) {
cause = check.sprintf("type %s is pointer to interface, not interface", T)
} else {
cause = check.sprintf("%s is not an interface", T)
}
return errorf("%s does not implement %s (%s)", V, T, cause)
}
// Every type satisfies the empty interface.
if Ti.Empty() {
return nil
}
// T is not the empty interface (i.e., the type set of T is restricted)
// An interface V with an empty type set satisfies any interface.
// (The empty set is a subset of any set.)
Vi, _ := Vu.(*Interface)
if Vi != nil && Vi.typeSet().IsEmpty() {
return nil
}
// type set of V is not empty
// No type with non-empty type set satisfies the empty type set.
if Ti.typeSet().IsEmpty() {
return errorf("cannot implement %s (empty type set)", T)
}
// V must implement T's methods, if any.
if m, wrong := check.missingMethod(V, Ti, true); m != nil /* !Implements(V, Ti) */ {
return errorf("%s does not implement %s %s", V, T, check.missingMethodReason(V, T, m, wrong))
}
// If T is comparable, V must be comparable.
// Remember as a pending error and report only if we don't have a more specific error.
var pending error
if Ti.IsComparable() && !comparable(V, false, nil, nil) {
pending = errorf("%s does not implement comparable", V)
}
// V must also be in the set of types of T, if any.
// Constraints with empty type sets were already excluded above.
if !Ti.typeSet().hasTerms() {
return pending // nothing to do
}
// If V is itself an interface, each of its possible types must be in the set
// of T types (i.e., the V type set must be a subset of the T type set).
// Interfaces V with empty type sets were already excluded above.
if Vi != nil {
if !Vi.typeSet().subsetOf(Ti.typeSet()) {
// TODO(gri) report which type is missing
return errorf("%s does not implement %s", V, T)
}
return pending
}
// Otherwise, V's type must be included in the iface type set.
var alt Type
if Ti.typeSet().is(func(t *term) bool {
if !t.includes(V) {
// If V ∉ t.typ but V ∈ ~t.typ then remember this type
// so we can suggest it as an alternative in the error
// message.
if alt == nil && !t.tilde && Identical(t.typ, under(t.typ)) {
tt := *t
tt.tilde = true
if tt.includes(V) {
alt = t.typ
}
}
return true
}
return false
}) {
if alt != nil {
return errorf("%s does not implement %s (possibly missing ~ for %s in constraint %s)", V, T, alt, T)
} else {
return errorf("%s does not implement %s (%s missing in %s)", V, T, V, Ti.typeSet().terms)
}
}
return pending
}
| {
if ctxt == nil {
ctxt = NewContext()
}
if validate {
var tparams []*TypeParam
switch t := orig.(type) {
case *Named:
tparams = t.TypeParams().list()
case *Signature:
tparams = t.TypeParams().list()
}
if len(targs) != len(tparams) {
return nil, fmt.Errorf("got %d type arguments but %s has %d type parameters", len(targs), orig, len(tparams))
}
if i, err := (*Checker)(nil).verify(token.NoPos, tparams, targs, ctxt); err != nil {
return nil, &ArgumentError{i, err}
}
}
inst := (*Checker)(nil).instance(token.NoPos, orig, targs, nil, ctxt)
return inst, nil
} |
unary_expression.js | /* -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
* File Name : unary_expression.js
* Created at : 2017-08-18
* Updated at : 2017-08-20
* Author : jeefo
* Purpose :
* Description :
_._._._._._._._._._._._._._._._._._._._._.*/
// ignore:start
/* globals */
/* exported */
// ignore:end
var argument_handler = function (_pp, token) {
if (token.argument) {
var pp = _pp.$new(token.argument),
action = pp.actions.invoke(pp, pp.parse(pp.code)[0].expression),
has_action = pp.action(action); | }
}
};
var negation_expression = function (_pp, code) {
var pp = _pp.$new(),
stmt = pp.parse(code)[0],
token = stmt.expression;
switch (token.type) {
case "EqualityExpression" :
switch (token.operator) {
case "==" :
case "===" :
token.operator = "!==";
break;
case "!=" :
case "!==" :
token.operator = "===";
break;
}
return `${ pp.compiler.compile(token.left) } ${ token.operator } ${ pp.compiler.compile(token.right) }`;
}
};
module.exports = {
name : "UnaryExpression",
handler : function (_pp, token) {
var action = argument_handler(_pp, token);
if (action) {
if (token.operator === '!') {
return _pp.replace(token, negation_expression(_pp, action.value));
}
return action;
}
}
}; |
if (has_action) {
return _pp.replace(token.argument, pp.code); |
stake_distribution.rs | use crate::{ | config::RewardParams,
fee::LinearFee,
rewards::Ratio,
stake::Stake,
testing::{
ledger::ConfigBuilder,
scenario::{prepare_scenario, stake_pool, wallet},
verifiers::LedgerStateVerifier,
},
value::Value,
};
use chain_addr::Discrimination;
use std::num::{NonZeroU32, NonZeroU64};
#[test]
pub fn stake_distribution_to_many_stake_pools() {
let (mut ledger, controller) = prepare_scenario()
.with_config(
ConfigBuilder::new()
.with_discrimination(Discrimination::Test)
.with_fee(LinearFee::new(1, 1, 1)),
)
.with_initials(vec![
wallet("Alice").with(1_000).owns("alice_stake_pool"),
wallet("Bob").with(1_000).owns("bob_stake_pool"),
wallet("Clarice").with(1_000).owns("clarice_stake_pool"),
wallet("David").with(1_003),
])
.build()
.unwrap();
let alice_stake_pool = controller.stake_pool("alice_stake_pool").unwrap();
let bob_stake_pool = controller.stake_pool("bob_stake_pool").unwrap();
let clarice_stake_pool = controller.stake_pool("clarice_stake_pool").unwrap();
let david = controller.wallet("David").unwrap();
let delegation_ratio = vec![
(&alice_stake_pool, 2u8),
(&bob_stake_pool, 3u8),
(&clarice_stake_pool, 5u8),
];
controller
.delegates_to_many(&david, &delegation_ratio, &mut ledger)
.unwrap();
let expected_distribution = vec![
(alice_stake_pool.id(), Value(200)),
(bob_stake_pool.id(), Value(300)),
(clarice_stake_pool.id(), Value(500)),
];
LedgerStateVerifier::new(ledger.into())
.info("after delegation to many stake pools")
.distribution()
.pools_distribution_is(expected_distribution);
}
#[test]
pub fn stake_distribution_changes_after_rewards_are_collected() {
let (mut ledger, controller) = prepare_scenario()
.with_config(
ConfigBuilder::new()
.with_rewards(Value(100))
.with_treasury(Value(0))
.with_rewards_params(RewardParams::Linear {
constant: 10,
ratio: Ratio {
numerator: 1,
denominator: NonZeroU64::new(1).unwrap(),
},
epoch_start: 0,
epoch_rate: NonZeroU32::new(1).unwrap(),
}),
)
.with_initials(vec![
wallet("Alice").with(1_000).owns("alice_stake_pool"),
wallet("Bob").with(1_000),
wallet("Clarice").with(1_000),
])
.with_stake_pools(vec![stake_pool("alice_stake_pool").tax_ratio(1, 1)])
.build()
.unwrap();
let alice_stake_pool = controller.stake_pool("alice_stake_pool").unwrap();
let alice = controller.wallet("Alice").unwrap();
controller
.owner_delegates(&alice, &alice_stake_pool, &mut ledger)
.unwrap();
LedgerStateVerifier::new(ledger.clone().into())
.info("before rewards collection")
.distribution()
.unassigned_is(Stake::from_value(Value(2000)))
.pools_distribution_is(vec![(alice_stake_pool.id(), Value(1000))]);
assert!(ledger.apply_empty_optimum_block(&alice_stake_pool).is_ok());
ledger.distribute_rewards().unwrap();
LedgerStateVerifier::new(ledger.into())
.info("after rewards collection")
.distribution()
.unassigned_is(Stake::from_value(Value(2000)))
.pools_distribution_is(vec![(alice_stake_pool.id(), Value(1009))]);
} | |
print_full_operation.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::{print_fragment, print_operation};
use fnv::FnvHashMap;
use graphql_ir::{
FragmentDefinition, FragmentSpread, OperationDefinition, Program, ScalarField, Visitor,
};
use interner::StringKey;
use std::sync::Arc;
pub fn print_full_operation(program: &Program, operation: &OperationDefinition) -> String {
let mut printer = OperationPrinter::new(program);
printer.print(operation)
}
pub struct OperationPrinter<'s> {
fragment_result: FnvHashMap<StringKey, String>,
reachable_fragments: FnvHashMap<StringKey, Arc<FragmentDefinition>>,
program: &'s Program,
}
impl<'s> OperationPrinter<'s> {
pub fn new(program: &'s Program) -> Self {
Self {
fragment_result: Default::default(),
reachable_fragments: Default::default(),
program,
}
}
pub fn print(&mut self, operation: &OperationDefinition) -> String {
let mut result = print_operation(&self.program.schema, operation);
self.visit_operation(operation);
let mut fragments: Vec<(StringKey, Arc<FragmentDefinition>)> =
self.reachable_fragments.drain().collect();
fragments.sort_unstable_by_key(|(name, _)| *name);
for (_, fragment) in fragments {
result.push_str("\n\n");
result.push_str(self.print_fragment(&fragment));
}
result.push('\n');
result
}
fn print_fragment(&mut self, fragment: &FragmentDefinition) -> &str |
}
impl<'s, 'ir> Visitor for OperationPrinter<'s> {
const NAME: &'static str = "OperationPrinter";
const VISIT_ARGUMENTS: bool = false;
const VISIT_DIRECTIVES: bool = false;
fn visit_fragment_spread(&mut self, spread: &FragmentSpread) {
if self.reachable_fragments.contains_key(&spread.fragment.item) {
return;
}
let fragment = self.program.fragment(spread.fragment.item).unwrap();
self.reachable_fragments
.insert(spread.fragment.item, Arc::clone(fragment));
self.visit_fragment(fragment);
}
fn visit_scalar_field(&mut self, _field: &ScalarField) {
// Stop
}
}
| {
let schema = &self.program.schema;
self.fragment_result
.entry(fragment.name.item)
.or_insert_with(|| print_fragment(schema, fragment))
} |
fixes.go | package emilia
import (
"strings"
"github.com/thecsw/darkness/internals"
)
// EnrichHeadings shifts heading levels to their correct layouts and
// adds some additional information to the headings for later export
func EnrichHeadings(page *internals.Page) |
// ResolveComments resolves heading comments and cleans up the page if
// COMMENT headings are encountered
func ResolveComments(page *internals.Page) {
start, headingLevel, searching := -1, -1, false
for i, content := range page.Contents {
if !content.IsHeading() {
continue
}
if strings.HasPrefix(content.Heading, "COMMENT ") && !searching {
start = i
headingLevel = content.HeadingLevel
searching = true
continue
}
if searching && content.HeadingLevel <= headingLevel {
page.Contents = append(page.Contents[:start], page.Contents[i:]...)
start, headingLevel, searching = -1, -1, false
}
}
// Still searching till the end? then set the finish to the last element
if searching {
page.Contents = page.Contents[:start]
}
}
| {
// Normalizing headings
if Config.Website.NormalizeHeadings {
minHeadingLevel := 999
// Find the smallest heading
for i := range page.Contents {
c := &page.Contents[i]
if !c.IsHeading() {
continue
}
if c.HeadingLevel < minHeadingLevel {
minHeadingLevel = c.HeadingLevel
}
}
// Shift everything over
for i := range page.Contents {
c := &page.Contents[i]
if !c.IsHeading() {
continue
}
c.HeadingLevel -= (minHeadingLevel - 2)
}
}
// Mark the first heading
for i := range page.Contents {
c := &page.Contents[i]
if c.IsHeading() {
c.HeadingFirst = true
break
}
}
// Mark the last heading
for i := len(page.Contents) - 1; i >= 0; i-- {
c := &page.Contents[i]
if c.IsHeading() {
c.HeadingLast = true
break
}
}
// Mark headings that are children
currentLevel := 0
for i := range page.Contents {
c := &page.Contents[i]
if !c.IsHeading() {
continue
}
if c.HeadingLevel > currentLevel {
c.HeadingChild = true
}
currentLevel = c.HeadingLevel
}
} |
createSendEventForFacet.js | function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
import isFacetRefined from "./isFacetRefined.js";
export function createSendEventForFacet(_ref) {
var instantSearchInstance = _ref.instantSearchInstance,
helper = _ref.helper,
attribute = _ref.attribute,
widgetType = _ref.widgetType;
var sendEventForFacet = function sendEventForFacet() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var eventType = args[0],
facetValue = args[1],
_args$ = args[2],
eventName = _args$ === void 0 ? 'Filter Applied' : _args$;
if (args.length === 1 && _typeof(args[0]) === 'object') {
instantSearchInstance.sendEventToInsights(args[0]);
} else if (eventType === 'click' && (args.length === 2 || args.length === 3)) {
if (!isFacetRefined(helper, attribute, facetValue)) {
// send event only when the facet is being checked "ON" | payload: {
eventName: eventName,
index: helper.getIndex(),
filters: ["".concat(attribute, ":").concat(facetValue)]
},
attribute: attribute
});
}
} else if (process.env.NODE_ENV === 'development') {
throw new Error("You need to pass two arguments like:\n sendEvent('click', facetValue);\n\nIf you want to send a custom payload, you can pass one object: sendEvent(customPayload);\n");
}
};
return sendEventForFacet;
} | instantSearchInstance.sendEventToInsights({
insightsMethod: 'clickedFilters',
widgetType: widgetType,
eventType: eventType, |
update_endpoint_list_item_route.ts | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { IRouter } from 'kibana/server';
import { ENDPOINT_LIST_ITEM_URL } from '../../common/constants';
import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps';
import { validate } from '../../common/siem_common_deps';
import {
UpdateEndpointListItemSchemaDecoded,
exceptionListItemSchema,
updateEndpointListItemSchema,
} from '../../common/schemas';
import { getExceptionListClient } from '.';
export const updateEndpointListItemRoute = (router: IRouter): void => {
router.put(
{
options: { | validate: {
body: buildRouteValidation<
typeof updateEndpointListItemSchema,
UpdateEndpointListItemSchemaDecoded
>(updateEndpointListItemSchema),
},
},
async (context, request, response) => {
const siemResponse = buildSiemResponse(response);
try {
const {
description,
id,
name,
meta,
type,
_tags,
_version,
comments,
entries,
item_id: itemId,
tags,
} = request.body;
const exceptionLists = getExceptionListClient(context);
const exceptionListItem = await exceptionLists.updateEndpointListItem({
_tags,
_version,
comments,
description,
entries,
id,
itemId,
meta,
name,
tags,
type,
});
if (exceptionListItem == null) {
if (id != null) {
return siemResponse.error({
body: `list item id: "${id}" not found`,
statusCode: 404,
});
} else {
return siemResponse.error({
body: `list item item_id: "${itemId}" not found`,
statusCode: 404,
});
}
} else {
const [validated, errors] = validate(exceptionListItem, exceptionListItemSchema);
if (errors != null) {
return siemResponse.error({ body: errors, statusCode: 500 });
} else {
return response.ok({ body: validated ?? {} });
}
}
} catch (err) {
const error = transformError(err);
return siemResponse.error({
body: error.message,
statusCode: error.statusCode,
});
}
}
);
}; | tags: ['access:lists-all'],
},
path: ENDPOINT_LIST_ITEM_URL, |
xormstore.go | /*
Package xormstore is a XORM backend for gorilla sessions
Simplest form:
store, err := xormstore.New(engine, []byte("secret-hash-key"))
All options:
store, err := xormstore.NewOptions(
engine, // *xorm.Engine
xormstore.Options{
TableName: "sessions", // "sessions" is default
SkipCreateTable: false, // false is default
},
[]byte("secret-hash-key"), // 32 or 64 bytes recommended, required
[]byte("secret-encyption-key")) // nil, 16, 24 or 32 bytes, optional
if err != nil {
// xormstore can not be initialized
}
// some more settings, see sessions.Options
store.SessionOpts.Secure = true
store.SessionOpts.HttpOnly = true
store.SessionOpts.MaxAge = 60 * 60 * 24 * 60
If you want periodic cleanup of expired sessions:
quit := make(chan struct{})
go store.PeriodicCleanup(1*time.Hour, quit)
For more information about the keys see https://github.com/gorilla/securecookie
For API to use in HTTP handlers see https://github.com/gorilla/sessions
*/
package xormstore
import (
"encoding/base32"
"net/http"
"strings"
"time"
"github.com/lafriks/xormstore/util"
"github.com/go-xorm/xorm"
"github.com/gorilla/context"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
)
const sessionIDLen = 32
const defaultTableName = "sessions"
const defaultMaxAge = 60 * 60 * 24 * 30 // 30 days
const defaultPath = "/"
// Options for xormstore
type Options struct {
TableName string
SkipCreateTable bool
}
// Store represent a xormstore
type Store struct {
e *xorm.Engine
opts Options
Codecs []securecookie.Codec
SessionOpts *sessions.Options
}
type xormSession struct {
ID string `xorm:"VARCHAR(400) PK NAME 'id'"`
Data string `xorm:"TEXT"`
CreatedUnix util.TimeStamp `xorm:"created"`
UpdatedUnix util.TimeStamp `xorm:"updated"`
ExpiresUnix util.TimeStamp `xorm:"INDEX"`
tableName string `xorm:"-"` // just to store table name for easier access
}
// Define a type for context keys so that they can't clash with anything else stored in context
type contextKey string
func (xs *xormSession) TableName() string {
return xs.tableName
}
// New creates a new xormstore session
func New(e *xorm.Engine, keyPairs ...[]byte) (*Store, error) {
return NewOptions(e, Options{}, keyPairs...)
}
// NewOptions creates a new xormstore session with options
func | (e *xorm.Engine, opts Options, keyPairs ...[]byte) (*Store, error) {
st := &Store{
e: e,
opts: opts,
Codecs: securecookie.CodecsFromPairs(keyPairs...),
SessionOpts: &sessions.Options{
Path: defaultPath,
MaxAge: defaultMaxAge,
},
}
if st.opts.TableName == "" {
st.opts.TableName = defaultTableName
}
if !st.opts.SkipCreateTable {
if err := st.e.Sync2(&xormSession{tableName: st.opts.TableName}); err != nil {
return nil, err
}
}
return st, nil
}
// Get returns a session for the given name after adding it to the registry.
func (st *Store) Get(r *http.Request, name string) (*sessions.Session, error) {
return sessions.GetRegistry(r).Get(st, name)
}
// New creates a session with name without adding it to the registry.
func (st *Store) New(r *http.Request, name string) (*sessions.Session, error) {
session := sessions.NewSession(st, name)
opts := *st.SessionOpts
session.Options = &opts
st.MaxAge(st.SessionOpts.MaxAge)
// try fetch from db if there is a cookie
if cookie, err := r.Cookie(name); err == nil {
if err := securecookie.DecodeMulti(name, cookie.Value, &session.ID, st.Codecs...); err != nil {
return session, nil
}
s := &xormSession{tableName: st.opts.TableName}
if has, err := st.e.Where("id = ? AND expires_unix >= ?", session.ID, util.TimeStampNow()).Get(s); !has || err != nil {
return session, nil
}
if err := securecookie.DecodeMulti(session.Name(), s.Data, &session.Values, st.Codecs...); err != nil {
return session, nil
}
context.Set(r, contextKey(name), s)
}
return session, nil
}
// Save session and set cookie header
func (st *Store) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error {
s, _ := context.Get(r, contextKey(session.Name())).(*xormSession)
// delete if max age is < 0
if session.Options.MaxAge < 0 {
if s != nil {
if _, err := st.e.Delete(&xormSession{
ID: session.ID,
tableName: st.opts.TableName,
}); err != nil {
return err
}
}
http.SetCookie(w, sessions.NewCookie(session.Name(), "", session.Options))
return nil
}
data, err := securecookie.EncodeMulti(session.Name(), session.Values, st.Codecs...)
if err != nil {
return err
}
now := util.TimeStampNow()
expire := now.AddDuration(time.Second * time.Duration(session.Options.MaxAge))
if s == nil {
// generate random session ID key suitable for storage in the db
session.ID = strings.TrimRight(
base32.StdEncoding.EncodeToString(
securecookie.GenerateRandomKey(sessionIDLen)), "=")
s = &xormSession{
ID: session.ID,
Data: data,
CreatedUnix: now,
UpdatedUnix: now,
ExpiresUnix: expire,
tableName: st.opts.TableName,
}
if _, err := st.e.Insert(s); err != nil {
return err
}
context.Set(r, contextKey(session.Name()), s)
} else {
s.Data = data
s.UpdatedUnix = now
s.ExpiresUnix = expire
if _, err := st.e.ID(s.ID).Cols("data", "updated_unix", "expires_unix").Update(s); err != nil {
return err
}
}
// set session id cookie
id, err := securecookie.EncodeMulti(session.Name(), session.ID, st.Codecs...)
if err != nil {
return err
}
http.SetCookie(w, sessions.NewCookie(session.Name(), id, session.Options))
return nil
}
// MaxAge sets the maximum age for the store and the underlying cookie
// implementation. Individual sessions can be deleted by setting
// Options.MaxAge = -1 for that session.
func (st *Store) MaxAge(age int) {
st.SessionOpts.MaxAge = age
for _, codec := range st.Codecs {
if sc, ok := codec.(*securecookie.SecureCookie); ok {
sc.MaxAge(age)
}
}
}
// MaxLength restricts the maximum length of new sessions to l.
// If l is 0 there is no limit to the size of a session, use with caution.
// The default is 4096 (default for securecookie)
func (st *Store) MaxLength(l int) {
for _, c := range st.Codecs {
if codec, ok := c.(*securecookie.SecureCookie); ok {
codec.MaxLength(l)
}
}
}
// Cleanup deletes expired sessions
func (st *Store) Cleanup() {
st.e.Where("expires_unix < ?", util.TimeStampNow()).Delete(&xormSession{tableName: st.opts.TableName})
}
// PeriodicCleanup runs Cleanup every interval. Close quit channel to stop.
func (st *Store) PeriodicCleanup(interval time.Duration, quit <-chan struct{}) {
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-t.C:
st.Cleanup()
case <-quit:
return
}
}
}
| NewOptions |
results.go | package api
import "github.com/oasisprotocol/oasis-core/go/common/crypto/signature"
// RoundResults contains information about how a particular round was executed by the consensus
// layer.
type RoundResults struct {
// Messages are the results of executing emitted runtime messages.
Messages []*MessageEvent `json:"messages,omitempty"`
// GoodComputeEntities are the public keys of compute nodes' controlling entities that
// positively contributed to the round by replicating the computation correctly.
GoodComputeEntities []signature.PublicKey `json:"good_compute_entities,omitempty"`
// BadComputeEntities are the public keys of compute nodes' controlling entities that | BadComputeEntities []signature.PublicKey `json:"bad_compute_entities,omitempty"`
} | // negatively contributed to the round by causing discrepancies. |
gpu_configuration.go | /*
* HCS API
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* API version: 2.1
* Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
*/
package hcsschema
type GpuConfiguration struct {
// The mode used to assign GPUs to the guest.
AssignmentMode string `json:"AssignmentMode,omitempty"`
// This only applies to List mode, and is ignored in other modes.
// In GPU-P, string is GPU device interface, and unit16 is partition id. HCS simply assigns the partition with the input id. | // In GPU-PV, string is GPU device interface, and unit16 is 0xffff. HCS needs to find an available partition to assign.
AssignmentRequest map[string]uint16 `json:"AssignmentRequest,omitempty"`
// Whether we allow vendor extension.
AllowVendorExtension bool `json:"AllowVendorExtension,omitempty"`
} | |
message.go | package discord
type Message struct {
ID Snowflake `json:"id,string"`
Type MessageType `json:"type"`
ChannelID Snowflake `json:"channel_id,string"`
GuildID Snowflake `json:"guild_id,string,omitempty"`
// The author object follows the structure of the user object, but is only
// a valid user in the case where the message is generated by a user or bot
// user. If the message is generated by a webhook, the author object
// corresponds to the webhook's id, username, and avatar. You can tell if a
// message is generated by a webhook by checking for the webhook_id on the
// message object.
Author User `json:"author"`
// The member object exists in MESSAGE_CREATE and MESSAGE_UPDATE
// events from text-based guild channels.
Member *Member `json:"member,omitempty"`
Content string `json:"content"`
Timestamp Timestamp `json:"timestamp,omitempty"`
EditedTimestamp *Timestamp `json:"edited_timestamp,omitempty"`
TTS bool `json:"tts"`
Pinned bool `json:"pinned"`
// The user objects in the mentions array will only have the partial
// member field present in MESSAGE_CREATE and MESSAGE_UPDATE events from
// text-based guild channels.
Mentions []GuildUser `json:"mentions"`
MentionRoleIDs []Snowflake `json:"mention_roles"`
MentionEveryone bool `json:"mention_everyone"`
// Not all channel mentions in a message will appear in mention_channels.
MentionChannels []ChannelMention `json:"mention_channels,omitempty"`
Attachments []Attachment `json:"attachments"`
Embeds []Embed `json:"embeds"`
Reactions []Reaction `json:"reaction,omitempty"`
// Used for validating a message was sent
Nonce string `json:"nonce,omitempty"`
WebhookID Snowflake `json:"webhook_id,string,omitempty"`
Activity *MessageActivity `json:"activity,omitempty"`
Application *MessageApplication `json:"application,omitempty"`
Reference *MessageReference `json:"message_reference,omitempty"`
Flags MessageFlags `json:"flags"`
}
// URL generates a Discord client URL to the message. If the message doesn't
// have a GuildID, it will generate a URL with the guild "@me".
func (m Message) URL() string {
var head = "https://discordapp.com/channels/"
var tail = "/" + m.ChannelID.String() + "/" + m.ID.String()
if !m.GuildID.Valid() |
return head + m.GuildID.String() + tail
}
type MessageType uint8
const (
DefaultMessage MessageType = iota
RecipientAddMessage
RecipientRemoveMessage
CallMessage
ChannelNameChangeMessage
ChannelIconChangeMessage
ChannelPinnedMessage
GuildMemberJoinMessage
NitroBoostMessage
NitroTier1Message
NitroTier2Message
NitroTier3Message
ChannelFollowAddMessage
)
type MessageFlags uint8
const (
CrosspostedMessage MessageFlags = 1 << iota
MessageIsCrosspost
SuppressEmbeds
SourceMessageDeleted
UrgentMessage
)
type ChannelMention struct {
ChannelID Snowflake `json:"id,string"`
GuildID Snowflake `json:"guild_id,string"`
ChannelType ChannelType `json:"type"`
ChannelName string `json:"name"`
}
type GuildUser struct {
User
Member *Member `json:"member,omitempty"`
}
//
type MessageActivity struct {
Type MessageActivityType `json:"type"`
// From a Rich Presence event
PartyID string `json:"party_id,omitempty"`
}
type MessageActivityType uint8
const (
JoinMessage MessageActivityType = iota + 1
SpectateMessage
ListenMessage
JoinRequestMessage
)
//
type MessageApplication struct {
ID Snowflake `json:"id,string"`
CoverID string `json:"cover_image,omitempty"`
Description string `json:"description"`
Icon string `json:"icon"`
Name string `json:"name"`
}
//
type MessageReference struct {
ChannelID Snowflake `json:"channel_id,string"`
// Field might not be provided
MessageID Snowflake `json:"message_id,string,omitempty"`
GuildID Snowflake `json:"guild_id,string,omitempty"`
}
//
type Attachment struct {
ID Snowflake `json:"id,string"`
Filename string `json:"filename"`
Size uint64 `json:"size"`
URL URL `json:"url"`
Proxy URL `json:"proxy_url"`
// Only if Image
Height uint `json:"height,omitempty"`
Width uint `json:"width,omitempty"`
}
//
type Reaction struct {
Count int `json:"count"`
Me bool `json:"me"` // for current user
Emoji Emoji `json:"emoji"`
}
| {
return head + "@me" + tail
} |
get_private_cancel_responses.go | // Code generated by go-swagger; DO NOT EDIT.
package operations
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
strfmt "github.com/go-openapi/strfmt"
models "github.com/adampointer/go-deribit/models"
)
// GetPrivateCancelReader is a Reader for the GetPrivateCancel structure.
type GetPrivateCancelReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *GetPrivateCancelReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewGetPrivateCancelOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
default:
return nil, runtime.NewAPIError("unknown error", response, response.Code())
}
}
// NewGetPrivateCancelOK creates a GetPrivateCancelOK with default headers values
func NewGetPrivateCancelOK() *GetPrivateCancelOK {
return &GetPrivateCancelOK{}
}
/*GetPrivateCancelOK handles this case with default header values.
foo
*/
type GetPrivateCancelOK struct {
Payload *models.PrivateCancelResponse
}
func (o *GetPrivateCancelOK) Error() string {
return fmt.Sprintf("[GET /private/cancel][%d] getPrivateCancelOK %+v", 200, o.Payload)
}
|
o.Payload = new(models.PrivateCancelResponse)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
} | func (o *GetPrivateCancelOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { |
icr.rs | #[doc = "Writer for register ICR"]
pub type W = crate::W<u32, super::ICR>;
#[doc = "Register ICR `reset()`'s with value 0"]
impl crate::ResetValue for super::ICR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Write proxy for field `DOWNCF`"]
pub struct DOWNCF_W<'a> {
w: &'a mut W,
}
impl<'a> DOWNCF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Write proxy for field `UPCF`"]
pub struct | <'a> {
w: &'a mut W,
}
impl<'a> UPCF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Write proxy for field `ARROKCF`"]
pub struct ARROKCF_W<'a> {
w: &'a mut W,
}
impl<'a> ARROKCF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Write proxy for field `CMPOKCF`"]
pub struct CMPOKCF_W<'a> {
w: &'a mut W,
}
impl<'a> CMPOKCF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Write proxy for field `EXTTRIGCF`"]
pub struct EXTTRIGCF_W<'a> {
w: &'a mut W,
}
impl<'a> EXTTRIGCF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Write proxy for field `ARRMCF`"]
pub struct ARRMCF_W<'a> {
w: &'a mut W,
}
impl<'a> ARRMCF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Write proxy for field `CMPMCF`"]
pub struct CMPMCF_W<'a> {
w: &'a mut W,
}
impl<'a> CMPMCF_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
impl W {
#[doc = "Bit 6 - Direction change to down Clear Flag"]
#[inline(always)]
pub fn downcf(&mut self) -> DOWNCF_W {
DOWNCF_W { w: self }
}
#[doc = "Bit 5 - Direction change to UP Clear Flag"]
#[inline(always)]
pub fn upcf(&mut self) -> UPCF_W {
UPCF_W { w: self }
}
#[doc = "Bit 4 - Autoreload register update OK Clear Flag"]
#[inline(always)]
pub fn arrokcf(&mut self) -> ARROKCF_W {
ARROKCF_W { w: self }
}
#[doc = "Bit 3 - Compare register update OK Clear Flag"]
#[inline(always)]
pub fn cmpokcf(&mut self) -> CMPOKCF_W {
CMPOKCF_W { w: self }
}
#[doc = "Bit 2 - External trigger valid edge Clear Flag"]
#[inline(always)]
pub fn exttrigcf(&mut self) -> EXTTRIGCF_W {
EXTTRIGCF_W { w: self }
}
#[doc = "Bit 1 - Autoreload match Clear Flag"]
#[inline(always)]
pub fn arrmcf(&mut self) -> ARRMCF_W {
ARRMCF_W { w: self }
}
#[doc = "Bit 0 - compare match Clear Flag"]
#[inline(always)]
pub fn cmpmcf(&mut self) -> CMPMCF_W {
CMPMCF_W { w: self }
}
}
| UPCF_W |
kdtreetest.rs | // test of Kd-Tree
use kdtree::KdTree;
//use kdtree::ErrorKind;
use kdtree::distance::squared_euclidean;
use ppmpa::ray::algebra::*; | use ppmpa::ray::optics::*;
use ppmpa::ray::physics::*;
fn main() {
let dimensions = 3;
let mut kdtree = KdTree::new(dimensions);
let p1 = Photon::new(&Wavelength::Red, &Ray::new(&Vector3::new(0.0, 0.0, 0.0), &Vector3::EY));
let p2 = Photon::new(&Wavelength::Green, &Ray::new(&Vector3::new(1.0, 1.0, 0.0), &Vector3::EX));
let p3 = Photon::new(&Wavelength::Blue, &Ray::new(&Vector3::new(1.0, 1.0, 1.0), &Vector3::EZ));
let p4 = Photon::new(&Wavelength::Red, &Ray::new(&Vector3::new(-1.0, -1.0, -1.0), &Vector3::EY));
let p5 = Photon::new(&Wavelength::Green, &Ray::new(&Vector3::new(2.0, 2.0, 2.0), &Vector3::EX));
let p6 = Photon::new(&Wavelength::Blue, &Ray::new(&Vector3::new(2.0, 2.0, 2.0), &Vector3::EZ));
kdtree.add(p1.ray.pos.v, p1).unwrap();
kdtree.add(p2.ray.pos.v, p2).unwrap();
kdtree.add(p3.ray.pos.v, p3).unwrap();
kdtree.add(p4.ray.pos.v, p4).unwrap();
kdtree.add(p5.ray.pos.v, p5).unwrap();
kdtree.add(p6.ray.pos.v, p6).unwrap();
println!("SIZE:{}", kdtree.size());
println!("\nNEAREST 2 Photons");
for p in kdtree.nearest(&Vector3::new(0.0, 0.0, 0.0).v, 2, &squared_euclidean).unwrap().iter() {
println!("P: {:?}", p);
}
println!("\nNEAREST 3 Photons");
for p in kdtree.nearest(&Vector3::new(0.0, 0.0, 0.0).v, 3, &squared_euclidean).unwrap().iter() {
println!("P: {:?}", p);
}
println!("\nWITHIN 2.5");
for p in kdtree.within(&Vector3::new(0.0, 0.0, 0.0).v, 2.5, &squared_euclidean).unwrap().iter() {
println!("P: {:?}", p);
}
println!("\nWITHIN 12.0");
for p in kdtree.within(&Vector3::new(0.0, 0.0, 0.0).v, 3.5*3.5, &squared_euclidean).unwrap().iter() {
println!("P: {:?}", p);
}
} | use ppmpa::ray::geometry::*; |
main.rs | //! Demonstrates how to use the fly camera
extern crate amethyst; | use amethyst::core::transform::TransformBundle;
use amethyst::input::InputBundle;
use amethyst::prelude::*;
use amethyst::renderer::{DrawShaded, PosNormTex};
use amethyst::utils::application_root_dir;
use amethyst::utils::scene::BasicScenePrefab;
use amethyst::Error;
type MyPrefabData = BasicScenePrefab<Vec<PosNormTex>>;
struct ExampleState;
impl<'a, 'b> SimpleState<'a, 'b> for ExampleState {
fn on_start(&mut self, data: StateData<GameData>) {
let prefab_handle = data.world.exec(|loader: PrefabLoader<MyPrefabData>| {
loader.load("prefab/arc_ball_camera.ron", RonFormat, (), ())
});
data.world.create_entity().with(prefab_handle).build();
}
}
fn main() -> Result<(), Error> {
amethyst::start_logger(Default::default());
let app_root = application_root_dir();
let resources_directory = format!("{}/examples/assets", app_root);
let display_config_path = format!(
"{}/examples/arc_ball_camera/resources/display_config.ron",
app_root
);
let key_bindings_path = format!("{}/examples/arc_ball_camera/resources/input.ron", app_root);
let game_data = GameDataBuilder::default()
.with(PrefabLoaderSystem::<MyPrefabData>::default(), "", &[])
.with_bundle(TransformBundle::new().with_dep(&[]))?
.with_bundle(
InputBundle::<String, String>::new().with_bindings_from_file(&key_bindings_path)?,
)?
.with_bundle(ArcBallControlBundle::<String, String>::new())?
.with_basic_renderer(display_config_path, DrawShaded::<PosNormTex>::new(), false)?;
let mut game = Application::build(resources_directory, ExampleState)?.build(game_data)?;
game.run();
Ok(())
} |
use amethyst::assets::{PrefabLoader, PrefabLoaderSystem, RonFormat};
use amethyst::controls::ArcBallControlBundle; |
miniwdl_s3_progressive_upload.py | """
Plugin for uploading output files to S3 "progressively," meaning to upload each task's output files
immediately upon task completion, instead of waiting for the whole workflow to finish. (The latter
technique, which doesn't need a plugin at all, is illustrated in ../upload_output_files.sh)
To enable, install this plugin (`pip3 install .` & confirm listed by `miniwdl --version`) and set
the environment variable MINIWDL__S3_PROGRESSIVE_UPLOAD__URI_PREFIX to a S3 URI prefix under which
to store the output files (e.g. "s3://my_bucket/workflow123_outputs"). The prefix should be set
uniquely for each run, to prevent different runs from overwriting each others' outputs.
Shells out to the AWS CLI, which must be pre-configured so that "aws s3 cp ..." into the specified
bucket works (without explicit auth-related arguments).
Deposits into each successful task/workflow run directory and S3 folder, an additional file
outputs.s3.json which copies outputs.json replacing local file paths with the uploaded S3 URIs.
(The JSON printed to miniwdl standard output keeps local paths.)
Limitations:
1) All task output files are uploaded, even ones that aren't top-level workflow outputs. (We can't,
at the moment of task completion, necessarily predict which files the calling workflow will
finally output.)
2) Doesn't upload (or rewrite outputs JSON for) workflow output files that weren't generated by a
task, e.g. outputting an input file, or a file generated by write_lines() etc. in the workflow.
(We could handle such stragglers by uploading them at workflow completion; it just hasn't been
needed yet.)
"""
import os
import subprocess
import threading
import json
import WDL
from WDL._util import StructuredLogMessage as _
_uploaded_files = {}
_uploaded_files_lock = threading.Lock()
def task(cfg, logger, run_id, run_dir, task, **recv):
"""
on completion of any task, upload its output files to S3, and record the S3 URI corresponding
to each local file (keyed by inode) in _uploaded_files
"""
logger = logger.getChild("s3_progressive_upload")
# ignore inputs
recv = yield recv
# ignore command/runtime/container
recv = yield recv
if not cfg.has_option("s3_progressive_upload", "uri_prefix"):
logger.debug("skipping because MINIWDL__S3_PROGRESSIVE_UPLOAD__URI_PREFIX is unset")
elif not run_id[-1].startswith("download-"):
s3prefix = cfg["s3_progressive_upload"]["uri_prefix"]
assert s3prefix.startswith("s3://"), "MINIWDL__S3_PROGRESSIVE_UPLOAD__URI_PREFIX invalid"
# for each file under out/
def _raise(ex):
raise ex
links_dir = os.path.join(run_dir, "out")
for (dn, subdirs, files) in os.walk(links_dir, onerror=_raise):
assert dn == links_dir or dn.startswith(links_dir + "/")
for fn in files:
# upload to S3
abs_fn = os.path.join(dn, fn)
s3uri = os.path.join(s3prefix, *run_id[1:], dn[(len(links_dir) + 1) :], fn)
s3cp(logger, abs_fn, s3uri)
# record in _uploaded_files (keyed by inode, so that it can be found from any
# symlink or hardlink)
with _uploaded_files_lock:
_uploaded_files[inode(abs_fn)] = s3uri
logger.info(_("task output uploaded", file=abs_fn, uri=s3uri))
# write outputs_s3.json using _uploaded_files
write_outputs_s3_json(
logger, recv["outputs"], run_dir, os.path.join(s3prefix, *run_id[1:]), task.name
)
yield recv
def workflow(cfg, logger, run_id, run_dir, workflow, **recv):
"""
on workflow completion, add a file outputs.s3.json to the run directory, which is outputs.json
with local filenames rewritten to the uploaded S3 URIs (as previously recorded on completion of
each task).
"""
logger = logger.getChild("s3_progressive_upload")
# ignore inputs
recv = yield recv
if cfg.has_option("s3_progressive_upload", "uri_prefix"):
# write outputs.s3.json using _uploaded_files
write_outputs_s3_json(
logger,
recv["outputs"],
run_dir,
os.path.join(cfg["s3_progressive_upload"]["uri_prefix"], *run_id[1:]),
workflow.name,
)
yield recv
def write_outputs_s3_json(logger, outputs, run_dir, s3prefix, namespace):
# rewrite uploaded files to their S3 URIs
def rewriter(fn):
try:
return _uploaded_files[inode(fn)]
except:
logger.warning(
_(
"output file wasn't uploaded to S3; keeping local path in outputs.s3.json",
file=fn,
)
)
return fn
with _uploaded_files_lock:
outputs_s3 = WDL.Value.rewrite_env_files(outputs, rewriter)
# get json dict of rewritten outputs
outputs_s3_json = WDL.values_to_json(outputs_s3, namespace=namespace)
# write to outputs.s3.json
fn = os.path.join(run_dir, "outputs.s3.json")
with open(fn, "w") as outfile:
json.dump(outputs_s3_json, outfile, indent=2)
outfile.write("\n")
s3cp(logger, fn, os.path.join(s3prefix, "outputs.s3.json"))
def | (logger, fn, s3uri):
# shell out to `aws s3 cp` instead of calling boto3 directly, to minimize contention added to
# miniwdl's GIL
cmd = ["aws", "s3", "cp", fn, s3uri, "--follow-symlinks", "--only-show-errors"]
logger.debug(" ".join(cmd))
rslt = subprocess.run(cmd, stderr=subprocess.PIPE)
if rslt.returncode != 0:
logger.error(
_(
"failed uploading output file",
cmd=" ".join(cmd),
exit_status=rslt.returncode,
stderr=rslt.stderr.decode("utf-8"),
)
)
raise WDL.Error.RuntimeError("failed: " + " ".join(cmd))
def inode(link):
st = os.stat(os.path.realpath(link))
return (st.st_dev, st.st_ino)
| s3cp |
config.rs | #[derive(Deserialize,Debug,Default)]
pub struct PocketConfig {
pub access_token: String,
pub consumer_key: String,
pub article_count: usize,
}
#[derive(Deserialize,Debug,Default)]
pub struct | {
pub chat_id: i64,
pub bot_token: String,
}
#[derive(Deserialize,Debug,Default)]
pub struct Config {
pub telegram: TelegramConfig,
pub pocket: PocketConfig,
}
| TelegramConfig |
models.py | # -*- coding: utf-8 -*-
from cmscloud.template_api import registry
from django.conf import settings
def get_meta_version(max_version):
|
META_TAG = '<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=%(meta_version)s">'
registry.add_to_head(META_TAG % {'meta_version': get_meta_version(settings.GOOGLE_CHROME_FRAME_MAX_VERSION)})
PROMPT_SCRIPT = """<!--[if lte IE %(max_version)s ]>
<script src="//ajax.googleapis.com/ajax/libs/chrome-frame/1.0.2/CFInstall.min.js"></script>
<script>window.attachEvent("onload",function(){CFInstall.check({mode:"overlay"})})</script>
<![endif]-->"""
if getattr(settings, 'GOOGLE_CHROME_FRAME_PROMPT', False):
registry.add_to_tail(PROMPT_SCRIPT % {'max_version': settings.GOOGLE_CHROME_FRAME_MAX_VERSION})
| max_version = int(max_version)
assert 6 <= max_version <= 9
if max_version == 9:
return '1'
else:
return 'IE%d' % (max_version, ) |
test_util.py | from scirpy.util import (
_is_na,
_is_false,
_is_true,
_normalize_counts,
_is_symmetric,
_reduce_nonzero,
_translate_dna_to_protein,
)
from scirpy.util.graph import layout_components
from itertools import combinations
import igraph as ig
import numpy as np
import pandas as pd
import numpy.testing as npt
import pytest
import scipy.sparse
from .fixtures import adata_tra
import warnings
def test_reduce_nonzero():
A = np.array([[0, 0, 3], [1, 2, 5], [7, 0, 0]])
B = np.array([[1, 0, 3], [2, 1, 0], [6, 0, 5]])
A_csr = scipy.sparse.csr_matrix(A)
B_csr = scipy.sparse.csr_matrix(B)
A_csc = scipy.sparse.csc_matrix(A)
B_csc = scipy.sparse.csc_matrix(B)
expected = np.array([[1, 0, 3], [1, 1, 5], [6, 0, 5]])
with pytest.raises(ValueError):
_reduce_nonzero(A, B)
npt.assert_equal(_reduce_nonzero(A_csr, B_csr).toarray(), expected)
npt.assert_equal(_reduce_nonzero(A_csc, B_csc).toarray(), expected)
npt.assert_equal(_reduce_nonzero(A_csr, A_csr.copy()).toarray(), A_csr.toarray())
def test_is_symmatric():
M = np.array([[1, 2, 2], [2, 1, 3], [2, 3, 1]])
S_csr = scipy.sparse.csr_matrix(M)
S_csc = scipy.sparse.csc_matrix(M)
S_lil = scipy.sparse.lil_matrix(M)
assert _is_symmetric(M)
assert _is_symmetric(S_csr)
assert _is_symmetric(S_csc)
assert _is_symmetric(S_lil)
M = np.array([[1, 2, 2], [2, 1, np.nan], [2, np.nan, np.nan]])
S_csr = scipy.sparse.csr_matrix(M)
S_csc = scipy.sparse.csc_matrix(M)
S_lil = scipy.sparse.lil_matrix(M)
assert _is_symmetric(M)
assert _is_symmetric(S_csr)
assert _is_symmetric(S_csc)
assert _is_symmetric(S_lil)
M = np.array([[1, 2, 2], [2, 1, 3], [3, 2, 1]])
S_csr = scipy.sparse.csr_matrix(M)
S_csc = scipy.sparse.csc_matrix(M)
S_lil = scipy.sparse.lil_matrix(M)
assert not _is_symmetric(M)
assert not _is_symmetric(S_csr)
assert not _is_symmetric(S_csc)
assert not _is_symmetric(S_lil)
def test_is_na():
warnings.filterwarnings("error")
assert _is_na(None)
assert _is_na(np.nan)
assert _is_na("nan")
assert not _is_na(42)
assert not _is_na("Foobar")
assert not _is_na(dict())
array_test = np.array(["None", "nan", None, np.nan, "foobar"])
array_expect = np.array([True, True, True, True, False])
array_test_bool = np.array([True, False, True])
array_expect_bool = np.array([False, False, False])
npt.assert_equal(_is_na(array_test), array_expect)
npt.assert_equal(_is_na(pd.Series(array_test)), array_expect)
npt.assert_equal(_is_na(array_test_bool), array_expect_bool)
npt.assert_equal(_is_na(pd.Series(array_test_bool)), array_expect_bool)
def test_is_false():
warnings.filterwarnings("error")
assert _is_false(False)
assert _is_false(0)
assert _is_false("") | assert _is_false("false")
assert not _is_false(42)
assert not _is_false(True)
assert not _is_false("true")
assert not _is_false("foobar")
assert not _is_false(np.nan)
assert not _is_false(None)
assert not _is_false("nan")
assert not _is_false("None")
array_test = np.array(
["False", "false", 0, 1, True, False, "true", "Foobar", np.nan, "nan"],
dtype=object,
)
array_test_str = array_test.astype("str")
array_expect = np.array(
[True, True, True, False, False, True, False, False, False, False]
)
array_test_bool = np.array([True, False, True])
array_expect_bool = np.array([False, True, False])
npt.assert_equal(_is_false(array_test), array_expect)
npt.assert_equal(_is_false(array_test_str), array_expect)
npt.assert_equal(_is_false(pd.Series(array_test)), array_expect)
npt.assert_equal(_is_false(pd.Series(array_test_str)), array_expect)
npt.assert_equal(_is_false(array_test_bool), array_expect_bool)
npt.assert_equal(_is_false(pd.Series(array_test_bool)), array_expect_bool)
def test_is_true():
warnings.filterwarnings("error")
assert not _is_true(False)
assert not _is_true(0)
assert not _is_true("")
assert not _is_true("False")
assert not _is_true("false")
assert not _is_true("0")
assert not _is_true(np.nan)
assert not _is_true(None)
assert not _is_true("nan")
assert not _is_true("None")
assert _is_true(42)
assert _is_true(True)
assert _is_true("true")
assert _is_true("foobar")
assert _is_true("True")
array_test = np.array(
["False", "false", 0, 1, True, False, "true", "Foobar", np.nan, "nan"],
dtype=object,
)
array_test_str = array_test.astype("str")
array_expect = np.array(
[False, False, False, True, True, False, True, True, False, False]
)
array_test_bool = np.array([True, False, True])
array_expect_bool = np.array([True, False, True])
npt.assert_equal(_is_true(array_test), array_expect)
npt.assert_equal(_is_true(array_test_str), array_expect)
npt.assert_equal(_is_true(pd.Series(array_test)), array_expect)
npt.assert_equal(_is_true(pd.Series(array_test_str)), array_expect)
npt.assert_equal(_is_true(array_test_bool), array_expect_bool)
npt.assert_equal(_is_true(pd.Series(array_test_bool)), array_expect_bool)
@pytest.fixture
def group_df():
return pd.DataFrame().assign(
cell=["c1", "c2", "c3", "c4", "c5", "c6"],
sample=["s2", "s1", "s2", "s2", "s2", "s1"],
)
def test_normalize_counts(group_df):
with pytest.raises(ValueError):
_normalize_counts(group_df, True, None)
npt.assert_equal(_normalize_counts(group_df, False), [1] * 6)
npt.assert_equal(
_normalize_counts(group_df, "sample"), [0.25, 0.5, 0.25, 0.25, 0.25, 0.5]
)
npt.assert_equal(
_normalize_counts(group_df, True, "sample"), [0.25, 0.5, 0.25, 0.25, 0.25, 0.5]
)
def test_layout_components():
g = ig.Graph()
# add 100 unconnected nodes
g.add_vertices(100)
# add 50 2-node components
g.add_vertices(100)
g.add_edges([(ii, ii + 1) for ii in range(100, 200, 2)])
# add 33 3-node components
g.add_vertices(100)
for ii in range(200, 299, 3):
g.add_edges([(ii, ii + 1), (ii, ii + 2), (ii + 1, ii + 2)])
# add a couple of larger components
n = 300
for ii in np.random.randint(4, 30, size=10):
g.add_vertices(ii)
g.add_edges(combinations(range(n, n + ii), 2))
n += ii
layout_components(g, arrange_boxes="size", component_layout="fr")
try:
layout_components(g, arrange_boxes="rpack", component_layout="fr")
except ImportError:
warnings.warn(
"The 'rpack' layout-test was skipped because rectangle "
"packer is not installed. "
)
layout_components(g, arrange_boxes="squarify", component_layout="fr")
def test_translate_dna_to_protein(adata_tra):
for nt, aa in zip(adata_tra.obs["IR_VJ_1_cdr3_nt"], adata_tra.obs["IR_VJ_1_cdr3"]):
assert _translate_dna_to_protein(nt) == aa | assert _is_false("False") |
main.rs | use compiler::*;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs::{self, DirEntry};
use std::io;
use std::path::Path;
#[derive(Debug)]
enum ModuleAnalysisTestResult {
UnexpectedDiagnostic(Diagnostic),
ExpectedWarningButGotError(Diagnostic),
ExpectedErrorButGotWarning(Diagnostic),
MissingError { line: usize, comment: String },
MissingWarning { line: usize, comment: String },
}
fn main() -> io::Result<()> {
// must be run from workspace root:
let cases_dir = Path::new("tests/cases").canonicalize()?;
let mut all_results = HashMap::new();
visit_pluma_files(&cases_dir, &mut all_results, &|entry, all_results| {
let current_dir = std::env::current_dir().unwrap();
let entry_path = &entry.path();
let short_path = entry_path.strip_prefix(current_dir).unwrap();
let module_results = check_module(entry_path);
all_results.insert(path_to_string(&short_path), module_results);
})?;
let mut failures = 0;
for (path, module_results) in all_results {
if module_results.is_empty() {
println!("\x1b[32m✔\x1b[0m {}", path);
} else {
eprintln!("\x1b[31m𝙭\x1b[0m {}", path);
eprintln!("{:#?}", module_results);
failures += 1;
}
}
if failures > 0 {
eprintln!("\n\x1b[31m𝙭\x1b[0m FAILED: {} errors", failures);
std::process::exit(47);
}
println!("\n\x1b[32m✔\x1b[0m All passed!");
Ok(())
}
fn check_module(path: &Path) -> Vec<ModuleAnalysisTestResult> {
let mut compiler = Compiler::from_options(CompilerOptions {
entry_path: path_to_string(path),
mode: CompilerMode::Debug,
output_path: None,
})
.expect("compiler from options");
let mut module_results = Vec::new();
// First, parse/analyze and get the results/comments
let check_result = compiler.check();
let parsed_module = &compiler.modules[&compiler.entry_module_name];
let parsed_comments = &mut parsed_module.comments.clone();
// Then, for each diagnostic that came back, check if we had an expect comment for it:
if let Err(diagnostics) = check_result {
for diagnostic in diagnostics {
let line_number =
parsed_module.get_line_for_position(diagnostic.pos.expect("pos for diagnostic"));
if let Some(comment_for_line) = parsed_comments.get(&line_number) {
if comment_for_line.starts_with(" expect-error") {
if diagnostic.is_error() {
// OK, we expected an error here. Remove it from the map
// so we don't count it again later.
parsed_comments.remove(&line_number);
} else {
// We expected an error, but got a warning:
module_results.push(ModuleAnalysisTestResult::ExpectedErrorButGotWarning(
diagnostic,
))
}
} else if comment_for_line.starts_with(" expect-warning") {
if diagnostic.is_error() {
// We expected a warning, but got an error:
module_results.push(ModuleAnalysisTestResult::ExpectedWarningButGotError(
diagnostic,
))
} else {
// OK, we expected a warning here. Remove it from the map
// so we don't count it again later.
parsed_comments.remove(&line_number);
}
} else {
module_results.push(ModuleAnalysisTestResult::UnexpectedDiagnostic(diagnostic));
}
} else {
module_results.push(ModuleAnalysisTestResult::UnexpectedDiagnostic(diagnostic));
}
}
}
// Then, check if we have any comments that did not result in diagnostics:
for (line_number, comment) in parsed_comments {
if comment.starts_with(" expect-error") {
module_results.push(ModuleAnalysisTestResult::MissingError {
line: *line_number,
comment: comment.to_string(),
})
} else if comment.starts_with(" expect-warning") {
module_results.push(ModuleAnalysisTestResult::MissingWarning {
line: *line_number,
comment: comment.to_string(),
})
}
}
module_results
}
fn visit_pluma_files(
dir: &Path,
results: &mut HashMap<String, Vec<ModuleAnalysisTestResult>>,
cb: &dyn Fn(&DirEntry, &mut HashMap<String, Vec<ModuleAnalysisTestResult>>),
) -> io::Result<()> {
if dir.is_dir() {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
visit_pluma_files(&path, results, cb)?;
} else if let Some(extension) = path.extension() {
if extension == OsStr::new("pa") {
cb(&entry, results);
}
}
}
}
Ok(())
}
fn path_to_string(path: &Path) -> String {
path.to | _string_lossy().to_owned().to_string()
}
|
|
v1beta1_event_list.py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.22
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from kubernetes.client.configuration import Configuration
class V1beta1EventList(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'api_version': 'str',
'items': 'list[V1beta1Event]',
'kind': 'str',
'metadata': 'V1ListMeta'
}
attribute_map = {
'api_version': 'apiVersion',
'items': 'items',
'kind': 'kind',
'metadata': 'metadata'
}
def | (self, api_version=None, items=None, kind=None, metadata=None, local_vars_configuration=None): # noqa: E501
"""V1beta1EventList - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._api_version = None
self._items = None
self._kind = None
self._metadata = None
self.discriminator = None
if api_version is not None:
self.api_version = api_version
self.items = items
if kind is not None:
self.kind = kind
if metadata is not None:
self.metadata = metadata
@property
def api_version(self):
"""Gets the api_version of this V1beta1EventList. # noqa: E501
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:return: The api_version of this V1beta1EventList. # noqa: E501
:rtype: str
"""
return self._api_version
@api_version.setter
def api_version(self, api_version):
"""Sets the api_version of this V1beta1EventList.
APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501
:param api_version: The api_version of this V1beta1EventList. # noqa: E501
:type: str
"""
self._api_version = api_version
@property
def items(self):
"""Gets the items of this V1beta1EventList. # noqa: E501
items is a list of schema objects. # noqa: E501
:return: The items of this V1beta1EventList. # noqa: E501
:rtype: list[V1beta1Event]
"""
return self._items
@items.setter
def items(self, items):
"""Sets the items of this V1beta1EventList.
items is a list of schema objects. # noqa: E501
:param items: The items of this V1beta1EventList. # noqa: E501
:type: list[V1beta1Event]
"""
if self.local_vars_configuration.client_side_validation and items is None: # noqa: E501
raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501
self._items = items
@property
def kind(self):
"""Gets the kind of this V1beta1EventList. # noqa: E501
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:return: The kind of this V1beta1EventList. # noqa: E501
:rtype: str
"""
return self._kind
@kind.setter
def kind(self, kind):
"""Sets the kind of this V1beta1EventList.
Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501
:param kind: The kind of this V1beta1EventList. # noqa: E501
:type: str
"""
self._kind = kind
@property
def metadata(self):
"""Gets the metadata of this V1beta1EventList. # noqa: E501
:return: The metadata of this V1beta1EventList. # noqa: E501
:rtype: V1ListMeta
"""
return self._metadata
@metadata.setter
def metadata(self, metadata):
"""Sets the metadata of this V1beta1EventList.
:param metadata: The metadata of this V1beta1EventList. # noqa: E501
:type: V1ListMeta
"""
self._metadata = metadata
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1beta1EventList):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1beta1EventList):
return True
return self.to_dict() != other.to_dict()
| __init__ |
__init__.py | """
AWS module - Keep the aws services adpaters
Version: 1.0.0
"""
def change_endpoint(cls):
endpoint_url = cls.config.get('LOCALSTACK_ENDPOINT', None)
# Fix para tratar diff entre docker/local
if endpoint_url == 'http://0.0.0.0:4566' or \
endpoint_url == 'http://localstack:4566':
old_value = endpoint_url
cls.config.set('LOCALSTACK_ENDPOINT', 'http://localhost:4566')
endpoint_url = cls.config.get('LOCALSTACK_ENDPOINT', None)
cls.logger.debug( | 'Changing the endpoint from {} to {}'.format(old_value, endpoint_url))
# override the property
cls.endpoint_url = endpoint_url | |
api.go | // Copyright © 2022, Cisco Systems Inc.
// Use of this source code is governed by an MIT-style license that can be
// found in the LICENSE file or at https://opensource.org/licenses/MIT.
package statuschange
import (
"context"
"cto-github.cisco.com/NFV-BU/go-msx/stream"
"encoding/json"
)
type MessageProducer interface {
Message(context.Context) (Message, error)
}
func PublishFromProducer(ctx context.Context, producer MessageProducer) (err error) {
msg, err := producer.Message(ctx)
if err != nil {
return err
}
return Publish(ctx, msg)
}
func Publish(ctx context.Context, message Message) error { | return err
}
return stream.Publish(ctx, TopicStatusChange, bytes, nil)
} | bytes, err := json.Marshal(message)
if err != nil { |
dcim_power_panels_update_responses.go | // Code generated by go-swagger; DO NOT EDIT.
// Copyright 2018 The go-netbox 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 dcim
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
strfmt "github.com/go-openapi/strfmt"
models "github.com/netbox-community/go-netbox/netbox/models"
)
// DcimPowerPanelsUpdateReader is a Reader for the DcimPowerPanelsUpdate structure.
type DcimPowerPanelsUpdateReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *DcimPowerPanelsUpdateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewDcimPowerPanelsUpdateOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
default:
return nil, runtime.NewAPIError("unknown error", response, response.Code())
}
}
| return &DcimPowerPanelsUpdateOK{}
}
/*DcimPowerPanelsUpdateOK handles this case with default header values.
DcimPowerPanelsUpdateOK dcim power panels update o k
*/
type DcimPowerPanelsUpdateOK struct {
Payload *models.PowerPanel
}
func (o *DcimPowerPanelsUpdateOK) Error() string {
return fmt.Sprintf("[PUT /dcim/power-panels/{id}/][%d] dcimPowerPanelsUpdateOK %+v", 200, o.Payload)
}
func (o *DcimPowerPanelsUpdateOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.PowerPanel)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
} | // NewDcimPowerPanelsUpdateOK creates a DcimPowerPanelsUpdateOK with default headers values
func NewDcimPowerPanelsUpdateOK() *DcimPowerPanelsUpdateOK { |
systemjs.config_menu.js | /**
* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
*/
(function(global) {
// map tells the System loader where to look for things
var map = {
'menu_app': '/resources/angular2/login/menu_app', // 'dist',
'@angular': '/resources/angular2/login/node_modules/@angular',
'angular2-in-memory-web-api': '/resources/angular2/login/node_modules/angular2-in-memory-web-api',
'rxjs': '/resources/angular2/login/node_modules/rxjs',
'primeng': '/resources/angular2/login/node_modules/primeng'
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'menu_app': { main: 'main.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
'primeng': { defaultExtension: 'js' }
};
var ngPackageNames = [
'common',
'compiler',
'core',
'forms',
'http',
'platform-browser',
'platform-browser-dynamic',
'router',
'router-deprecated',
'upgrade',
];
// Individual files (~300 requests):
function | (pkgName) {
packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
}
// Bundled (~40 requests):
function packUmd(pkgName) {
packages['@angular/'+pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
}
// Most environments should use UMD; some (Karma) need the individual index files
var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
// Add package entries for angular packages
ngPackageNames.forEach(setPackageConfig);
var config = {
map: map,
packages: packages
};
System.config(config);
})(this);
| packIndex |
create-if.js | /**
* @file 创建 if 指令元素
* @author errorrik([email protected])
*/
var each = require('../util/each');
var genStumpHTML = require('./gen-stump-html');
var nodeInit = require('./node-init');
var NodeType = require('./node-type');
var nodeEvalExpr = require('./node-eval-expr');
var rinseCondANode = require('./rinse-cond-anode');
var createNode = require('./create-node');
var createReverseNode = require('./create-reverse-node');
var getNodeStumpParent = require('./get-node-stump-parent');
var elementUpdateChildren = require('./element-update-children');
var nodeOwnSimpleDispose = require('./node-own-simple-dispose');
var nodeOwnGetStumpEl = require('./node-own-get-stump-el');
/**
* 创建 if 指令元素
*
* @param {Object} options 初始化参数
* @return {Object}
*/
function createIf(options) {
var node = nodeInit(options);
node.children = [];
node.nodeType = NodeType.IF;
node.dispose = nodeOwnSimpleDispose;
node._getEl = nodeOwnGetStumpEl;
node._attachHTML = ifOwnAttachHTML;
node._update = ifOwnUpdate;
node.cond = node.aNode.directives.get('if').value;
// #[begin] reverse
var walker = options.reverseWalker;
if (walker) {
options.reverseWalker = null;
if (nodeEvalExpr(node, node.cond)) {
node.elseIndex = -1;
node.children[0] = createReverseNode(
rinseCondANode(node.aNode),
walker,
node
);
}
else {
each(node.aNode.elses, function (elseANode, index) {
var elif = elseANode.directives.get('elif');
if (!elif || elif && nodeEvalExpr(node, elif.value)) {
node.elseIndex = index;
node.children[0] = createReverseNode(
rinseCondANode(elseANode),
walker,
node
);
return false;
}
});
}
}
// #[end]
return node;
}
/**
* attach元素的html
*
* @param {Object} buf html串存储对象
*/
function ifOwnAttachHTML(buf) {
var me = this;
var | var child;
if (nodeEvalExpr(me, me.cond)) {
child = createNode(rinseCondANode(me.aNode), me);
elseIndex = -1;
}
else {
each(me.aNode.elses, function (elseANode, index) {
var elif = elseANode.directives.get('elif');
if (!elif || elif && nodeEvalExpr(me, elif.value)) {
child = createNode(rinseCondANode(elseANode), me);
elseIndex = index;
return false;
}
});
}
if (child) {
me.children[0] = child;
child._attachHTML(buf);
me.elseIndex = elseIndex;
}
genStumpHTML(this, buf);
}
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
*/
function ifOwnUpdate(changes) {
var me = this;
var childANode = me.aNode;
var elseIndex;
if (nodeEvalExpr(this, this.cond)) {
elseIndex = -1;
}
else {
each(me.aNode.elses, function (elseANode, index) {
var elif = elseANode.directives.get('elif');
if (elif && nodeEvalExpr(me, elif.value) || !elif) {
elseIndex = index;
childANode = elseANode;
return false;
}
});
}
if (elseIndex === me.elseIndex) {
elementUpdateChildren(me, changes);
}
else {
var child = me.children[0];
me.children.length = 0;
if (child) {
child._ondisposed = newChild;
child.dispose();
}
else {
newChild();
}
me.elseIndex = elseIndex;
}
function newChild() {
if (typeof elseIndex !== 'undefined') {
var child = createNode(rinseCondANode(childANode), me);
var parentEl = getNodeStumpParent(me);
child.attach(parentEl, me._getEl() || parentEl.firstChild);
me.children[0] = child;
}
}
}
exports = module.exports = createIf;
| elseIndex;
|
operator.go | package jsast
// Operator order from Javascript
const (
LowestPrec = 0 // non-operators
UnaryPrec = 16
HighestPrec = 21
)
// Precedence returns the operator precedence of the binary
// operator op. If op is not a binary operator, the result
// is LowestPrecedence.
//
// This is not an exhaustive view of Javascript operators
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
func | (op string) int {
switch op {
case "**":
return 15
case "*", "/", "%":
return 14
case "+", "-":
return 13
case "<<", ">>", ">>>":
return 12
case "<", "<=", ">", ">=":
return 11
case "==", "!=", "===", "!==":
return 10
case "&":
return 9
case "^":
return 8
case "|":
return 7
case "&&":
return 6
case "||":
return 5
}
return LowestPrec
}
| Precedence |
abstract-array.ts | import { IArray, ILinkedList, ITree } from "@Interface/specific";
import { IList } from "@Interface/common";
import { Console } from "@Utils/emphasize";
import { ArrayTypes, ListTypes, TreeTypes, ListPrintOrder } from "@Utils/types";
import { ICompareFunc } from "@Utils/compare";
import { Errors } from "@Utils/error-handling";
import { QuickSort, SortMethods } from "@Algorithm/sort";
import { Validation, ValidateParams, PositiveSaftInt, SafeInt } from "@Utils/decorator";
import { ArrayFactory } from "@DataStructure/array";
import { LinkedListFactory } from "@DataStructure/linked-list";
import { BinaryTreeFactory } from "@DataStructure/tree";
export abstract class AbstractArray<T> implements IArray<T> {
[n: number]: T; // index signature to present Array
@PositiveSaftInt()
protected _capacity: number;
@PositiveSaftInt()
protected _incrementals: number;
@PositiveSaftInt()
protected _size: number;
@SafeInt()
protected _idxOfLastElm: number;
protected _compare: ICompareFunc<T>;
get length(): number {
return this._capacity;
};
get size(): number {
return this._size
};
get head(): T {
return this[0];
}
get tail(): T {
return this[this._capacity - 1];
}
constructor(capacity: number, compare: ICompareFunc<T>, incrementals: number) {
this._size = 0;
this._idxOfLastElm = -1;
this._capacity = capacity;
this._compare = compare;
this._incrementals = incrementals
}
abstract insertByIndex(value: T, index: number): this
abstract append(value: T): this;
abstract map<U>(callbackfn: (value: T, index: number, current: IArray<T>) => U, ICompareFunc?: ICompareFunc<U>, thisArg?: any): IArray<U>
toArray(arrayType: ArrayTypes): IArray<T> {
const currLength = this._capacity;
const array = ArrayFactory.create<T>(arrayType, this._compare, currLength);
for (let index = 0; index < currLength; index++) {
if (!this[index]) continue;
array.append(this[index])
}
return array;
}
toList(listType: ListTypes): ILinkedList<T> {
const currLength = this._capacity;
const list = LinkedListFactory.create<T>(listType);
for (let index = 0; index < currLength; index++) {
if (!this[index]) continue;
list.append(this[index]);
}
return list;
}
toTree(treeType: TreeTypes): ITree<T> {
const currLength = this._capacity;
const tree = BinaryTreeFactory.create<T>(treeType, this._compare);
for (let index = 0; index < currLength; index++) {
if (!this[index]) continue;
tree.append(this[index]);
}
return tree;
}
@Validation('index')
removeByIndex(@ValidateParams('number') index: number): T {
const idx = this._getValidIndex(index);
const value = this[idx];
const isValidValue = this._isValidValue(this[idx]);
for (let i = idx + 1; i <= this._idxOfLastElm; i++) {
this[i - 1] = this[i];
}
for (let k = idx + 1 - this._capacity; k <= this._idxOfLastElm - this._capacity; k++) {
this[k - 1] = this[k];
}
this[this._idxOfLastElm] = undefined;
this[this._idxOfLastElm - this._capacity] = undefined;
while (!this._isValidValue(this[this._idxOfLastElm])) {
this._idxOfLastElm -= 1;
} // need to refactor!!!
if (isValidValue) {
this._size -= 1
};
return value;
}
@Validation()
updateByIndex(@ValidateParams() value: T, @ValidateParams('number') index: number): this {
const idx = this._getValidIndex(index);
this[idx] = value;
this[idx - this._capacity] = value;
return this;
}
@Validation('index')
getByIndex(@ValidateParams('number') index: number): T {
return this[this._getValidIndex(index)]
}
sort(sortMethod: SortMethods = SortMethods.Quick): this { | @Validation('value')
indexOf(@ValidateParams() value: T): number {
for (let i = 0; i < this._capacity; i++) {
if (this._compare(this[i]).isEqualTo(value)) {
return i
}
}
return -1;
}
reverse(): this {
let i = 0, j = this._capacity - 1;
let ii = i - this._capacity, jj = -1;
while (i < j) {
let temp = this[i];
this[i] = this[j];
this[j] = temp;
temp = this[ii];
this[ii] = this[jj];
this[jj] = temp;
i += 1;
j -= 1;
ii += 1;
jj -= 1;
}
this._idxOfLastElm = this._findNewIdxOfLastElm();
return this;
}
@Validation('value')
contains(@ValidateParams() value: T): boolean {
return this.indexOf(value) !== -1;
}
@Validation('value')
remove(@ValidateParams() value: T): this {
const idx = this.indexOf(value);
if (idx === -1) return this;
this.removeByIndex(idx);
return this;
}
isEmpty(): boolean {
return this._size === 0;
}
print(order: ListPrintOrder = ListPrintOrder.FromHeadToTail): this {
if (order === ListPrintOrder.FromHeadToTail) return this._printFromHeadToTail();
if (order === ListPrintOrder.FromTailToHead) return this._printFromTailToHead();
throw new Errors.InvalidArgument(Errors.Msg.UnacceptablePrintOrder);
}
clear(): this {
for (let i = 0; i <= this._idxOfLastElm; i++) {
this[i] = undefined;
this[i - this._capacity] = undefined;
}
this._idxOfLastElm = -1;
this._size = 0;
return this;
}
forEach(callbackfn: (value: T, index: number, current: IList<T>) => void, thisArg?: any): void {
const capacity = this._capacity;
for (let idx = 0; idx < capacity; idx++) {
callbackfn(this[idx], idx, this);
this[idx - this._capacity] = this[idx];
}
}
protected _getValidIndex(index: number): number {
if (index >= this._capacity || index + this._capacity < 0) {
throw new Errors.OutOfBoundary(Errors.Msg.NoMoreSpace);
}
if (index < 0) {
return index + this._capacity;
}
return index;
}
protected _isValidValue(value: T) {
return value !== undefined
&& value !== null
&& Number(value) !== NaN
&& Number(value) !== Infinity
&& String(value) !== ""
}
protected _quickSort(compare?: ICompareFunc<T>): this {
QuickSort(this, 0, this._capacity - 1, compare); // positive indice
QuickSort(this, 0 - this._capacity, -1, compare); // negative indice
this._idxOfLastElm = this._findNewIdxOfLastElm();
return this;
}
protected _findNewIdxOfLastElm(): number {
let kk = this._capacity - 1;
while (!this[kk] && kk >= 0) { kk -= 1; }
return kk;
}
private _printFromHeadToTail(): this {
let str = "[ "
for (let i = 0; i <= this._idxOfLastElm; i++) {
str += `${this[i]}`;
if (i === this._idxOfLastElm) break;
str += `, `
}
str += ` ]`;
Console.OK(`Array Printing from HEAD to TAIL: ${str}`);
return this;
}
private _printFromTailToHead(): this {
let str = "[ "
for (let i = this._idxOfLastElm - 1; i >= 0; i--) {
str += `${this[i]}`;
if (i === 0) break;
str += `, `
}
str += ` ]`;
Console.OK(`Array Printing from TAIL to HEAD: ${str}`);
return this;
}
} | return this._quickSort(this._compare);
}
|
common_connection.py | try:
from prawframe.obfuscation import Scrambler
except ImportError:
from .obfuscation import Encryptor
def bytes_packet(_bytes, termination_string=']'):
"""
Create a packet containing the amount of bytes for the proceeding data.
:param _bytes:
:param termination_string:
:return:
"""
return '{}{}'.format(len(_bytes), termination_string)
def scrambles_input_unscrambles_output(func):
scrambler = Encryptor().load_key_file()
def decorator(*args, **kwargs):
args = list(args)
args[0] = scrambler.encrypt(args[0])
result = func(*args, **kwargs)
descrabled = scrambler.decrypt(result)
return descrabled
return decorator
def unscrambles_output(func):
scrambler = Encryptor().load_key_file()
def decorator(*args, **kwargs):
args = list(args)
scrambled_result = func(*args, **kwargs)
result = scrambler.decrypt(scrambled_result)
return result
return decorator
def scrambles_input(func):
scrambler = Encryptor().load_key_file()
def | (*args, **kwargs):
args = list(args)
args[0] = scrambler.encrypt(args[0])
result = func(*args, **kwargs)
return result
return decorator
| decorator |
workflow.go | /*
Copyright 2021 The KubeVela 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 service
import (
"context"
"errors"
"fmt"
"strconv"
"helm.sh/helm/v3/pkg/time"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/klog/v2"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/yaml"
"github.com/oam-dev/kubevela/apis/core.oam.dev/common"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/pkg/apiserver/domain/model"
"github.com/oam-dev/kubevela/pkg/apiserver/domain/repository"
"github.com/oam-dev/kubevela/pkg/apiserver/infrastructure/datastore"
assembler "github.com/oam-dev/kubevela/pkg/apiserver/interfaces/api/assembler/v1"
apisv1 "github.com/oam-dev/kubevela/pkg/apiserver/interfaces/api/dto/v1"
"github.com/oam-dev/kubevela/pkg/apiserver/utils"
"github.com/oam-dev/kubevela/pkg/apiserver/utils/bcode"
"github.com/oam-dev/kubevela/pkg/apiserver/utils/log"
"github.com/oam-dev/kubevela/pkg/oam"
"github.com/oam-dev/kubevela/pkg/oam/util"
utils2 "github.com/oam-dev/kubevela/pkg/utils"
"github.com/oam-dev/kubevela/pkg/utils/apply"
"github.com/oam-dev/kubevela/pkg/workflow/tasks/custom"
wfTypes "github.com/oam-dev/kubevela/pkg/workflow/types"
)
// WorkflowService workflow manage api
type WorkflowService interface {
ListApplicationWorkflow(ctx context.Context, app *model.Application) ([]*apisv1.WorkflowBase, error)
GetWorkflow(ctx context.Context, app *model.Application, workflowName string) (*model.Workflow, error)
DetailWorkflow(ctx context.Context, workflow *model.Workflow) (*apisv1.DetailWorkflowResponse, error)
GetApplicationDefaultWorkflow(ctx context.Context, app *model.Application) (*model.Workflow, error)
DeleteWorkflow(ctx context.Context, app *model.Application, workflowName string) error
DeleteWorkflowByApp(ctx context.Context, app *model.Application) error
CreateOrUpdateWorkflow(ctx context.Context, app *model.Application, req apisv1.CreateWorkflowRequest) (*apisv1.DetailWorkflowResponse, error)
UpdateWorkflow(ctx context.Context, workflow *model.Workflow, req apisv1.UpdateWorkflowRequest) (*apisv1.DetailWorkflowResponse, error)
CreateWorkflowRecord(ctx context.Context, appModel *model.Application, app *v1beta1.Application, workflow *model.Workflow) error
ListWorkflowRecords(ctx context.Context, workflow *model.Workflow, page, pageSize int) (*apisv1.ListWorkflowRecordsResponse, error)
DetailWorkflowRecord(ctx context.Context, workflow *model.Workflow, recordName string) (*apisv1.DetailWorkflowRecordResponse, error)
SyncWorkflowRecord(ctx context.Context) error
ResumeRecord(ctx context.Context, appModel *model.Application, workflow *model.Workflow, recordName string) error
TerminateRecord(ctx context.Context, appModel *model.Application, workflow *model.Workflow, recordName string) error
RollbackRecord(ctx context.Context, appModel *model.Application, workflow *model.Workflow, recordName, revisionName string) error
CountWorkflow(ctx context.Context, app *model.Application) int64
}
// NewWorkflowService new workflow service
func NewWorkflowService() WorkflowService {
return &workflowServiceImpl{}
}
type workflowServiceImpl struct {
Store datastore.DataStore `inject:"datastore"`
KubeClient client.Client `inject:"kubeClient"`
Apply apply.Applicator `inject:"apply"`
EnvService EnvService `inject:""`
}
// DeleteWorkflow delete application workflow
func (w *workflowServiceImpl) DeleteWorkflow(ctx context.Context, app *model.Application, workflowName string) error {
var workflow = &model.Workflow{
Name: workflowName,
AppPrimaryKey: app.PrimaryKey(),
}
var record = model.WorkflowRecord{
AppPrimaryKey: workflow.AppPrimaryKey,
WorkflowName: workflow.Name,
}
records, err := w.Store.List(ctx, &record, &datastore.ListOptions{})
if err != nil {
log.Logger.Errorf("list workflow %s record failure %s", utils2.Sanitize(workflow.PrimaryKey()), err.Error())
}
for _, record := range records {
if err := w.Store.Delete(ctx, record); err != nil {
log.Logger.Errorf("delete workflow record %s failure %s", record.PrimaryKey(), err.Error())
}
}
if err := w.Store.Delete(ctx, workflow); err != nil {
if errors.Is(err, datastore.ErrRecordNotExist) {
return bcode.ErrWorkflowNotExist
}
return err
}
return nil
}
func (w *workflowServiceImpl) DeleteWorkflowByApp(ctx context.Context, app *model.Application) error {
var workflow = &model.Workflow{
AppPrimaryKey: app.PrimaryKey(),
}
workflows, err := w.Store.List(ctx, workflow, &datastore.ListOptions{})
if err != nil {
if errors.Is(err, datastore.ErrRecordNotExist) {
return nil
}
return err
}
for i := range workflows {
workflow := workflows[i].(*model.Workflow)
var record = model.WorkflowRecord{
AppPrimaryKey: workflow.AppPrimaryKey,
WorkflowName: workflow.Name,
}
records, err := w.Store.List(ctx, &record, &datastore.ListOptions{})
if err != nil {
log.Logger.Errorf("list workflow %s record failure %s", workflow.PrimaryKey(), err.Error())
}
for _, record := range records {
if err := w.Store.Delete(ctx, record); err != nil {
log.Logger.Errorf("delete workflow record %s failure %s", record.PrimaryKey(), err.Error())
}
}
if err := w.Store.Delete(ctx, workflow); err != nil {
log.Logger.Errorf("delete workflow %s failure %s", workflow.PrimaryKey(), err.Error())
}
}
return nil
}
func (w *workflowServiceImpl) CreateOrUpdateWorkflow(ctx context.Context, app *model.Application, req apisv1.CreateWorkflowRequest) (*apisv1.DetailWorkflowResponse, error) {
if req.EnvName == "" {
return nil, bcode.ErrWorkflowNoEnv
}
workflow, err := w.GetWorkflow(ctx, app, req.Name)
if err != nil && errors.Is(err, datastore.ErrRecordNotExist) {
return nil, err
}
var steps []model.WorkflowStep
for _, step := range req.Steps {
properties, err := model.NewJSONStructByString(step.Properties)
if err != nil {
log.Logger.Errorf("parse trait properties failire %w", err)
return nil, bcode.ErrInvalidProperties
}
steps = append(steps, model.WorkflowStep{
Name: step.Name,
Type: step.Type,
Alias: step.Alias,
Inputs: step.Inputs,
Outputs: step.Outputs,
Description: step.Description,
DependsOn: step.DependsOn,
Properties: properties,
})
}
if workflow != nil {
workflow.Steps = steps
workflow.Alias = req.Alias
workflow.Description = req.Description
workflow.Default = req.Default
if err := w.Store.Put(ctx, workflow); err != nil {
return nil, err
}
} else {
// It is allowed to set multiple workflows as default, and only one takes effect.
workflow = &model.Workflow{
Steps: steps,
Name: req.Name,
Alias: req.Alias,
Description: req.Description,
Default: req.Default,
EnvName: req.EnvName,
AppPrimaryKey: app.PrimaryKey(),
}
log.Logger.Infof("create workflow %s for app %s", utils2.Sanitize(req.Name), utils2.Sanitize(app.PrimaryKey()))
if err := w.Store.Add(ctx, workflow); err != nil {
return nil, err
}
}
return w.DetailWorkflow(ctx, workflow)
}
func (w *workflowServiceImpl) UpdateWorkflow(ctx context.Context, workflow *model.Workflow, req apisv1.UpdateWorkflowRequest) (*apisv1.DetailWorkflowResponse, error) {
modeSteps, err := assembler.CreateWorkflowStepModel(req.Steps)
if err != nil {
return nil, err
}
workflow.Description = req.Description
// It is allowed to set multiple workflows as default, and only one takes effect.
if req.Default != nil {
workflow.Default = req.Default
}
if err := repository.UpdateWorkflowSteps(ctx, w.Store, workflow, modeSteps); err != nil {
return nil, err
}
return w.DetailWorkflow(ctx, workflow)
}
// DetailWorkflow detail workflow
func (w *workflowServiceImpl) DetailWorkflow(ctx context.Context, workflow *model.Workflow) (*apisv1.DetailWorkflowResponse, error) {
return &apisv1.DetailWorkflowResponse{
WorkflowBase: assembler.ConvertWorkflowBase(workflow),
}, nil
}
// GetWorkflow get workflow model
func (w *workflowServiceImpl) GetWorkflow(ctx context.Context, app *model.Application, workflowName string) (*model.Workflow, error) {
return repository.GetWorkflowForApp(ctx, w.Store, app, workflowName)
}
// ListApplicationWorkflow list application workflows
func (w *workflowServiceImpl) ListApplicationWorkflow(ctx context.Context, app *model.Application) ([]*apisv1.WorkflowBase, error) {
var workflow = model.Workflow{
AppPrimaryKey: app.PrimaryKey(),
}
workflows, err := w.Store.List(ctx, &workflow, &datastore.ListOptions{})
if err != nil {
return nil, err
}
var list []*apisv1.WorkflowBase
for _, workflow := range workflows {
wm := workflow.(*model.Workflow)
base := assembler.ConvertWorkflowBase(wm)
list = append(list, &base)
}
return list, nil
}
// GetApplicationDefaultWorkflow get application default workflow
func (w *workflowServiceImpl) GetApplicationDefaultWorkflow(ctx context.Context, app *model.Application) (*model.Workflow, error) {
var defaultEnable = true
var workflow = model.Workflow{
AppPrimaryKey: app.PrimaryKey(),
Default: &defaultEnable,
}
workflows, err := w.Store.List(ctx, &workflow, &datastore.ListOptions{})
if err != nil {
return nil, err
}
if len(workflows) > 0 {
return workflows[0].(*model.Workflow), nil
}
return nil, bcode.ErrWorkflowNoDefault
}
// ListWorkflowRecords list workflow record
func (w *workflowServiceImpl) ListWorkflowRecords(ctx context.Context, workflow *model.Workflow, page, pageSize int) (*apisv1.ListWorkflowRecordsResponse, error) {
var record = model.WorkflowRecord{
AppPrimaryKey: workflow.AppPrimaryKey,
WorkflowName: workflow.Name,
}
records, err := w.Store.List(ctx, &record, &datastore.ListOptions{Page: page, PageSize: pageSize})
if err != nil {
return nil, err
}
resp := &apisv1.ListWorkflowRecordsResponse{
Records: []apisv1.WorkflowRecord{},
}
for _, raw := range records {
record, ok := raw.(*model.WorkflowRecord)
if ok {
resp.Records = append(resp.Records, *assembler.ConvertFromRecordModel(record))
}
}
count, err := w.Store.Count(ctx, &record, nil)
if err != nil {
return nil, err
}
resp.Total = count
return resp, nil
}
// DetailWorkflowRecord get workflow record detail with name
func (w *workflowServiceImpl) DetailWorkflowRecord(ctx context.Context, workflow *model.Workflow, recordName string) (*apisv1.DetailWorkflowRecordResponse, error) {
var record = model.WorkflowRecord{
AppPrimaryKey: workflow.AppPrimaryKey,
WorkflowName: workflow.Name,
Name: recordName,
}
err := w.Store.Get(ctx, &record)
if err != nil {
if errors.Is(err, datastore.ErrRecordNotExist) {
return nil, bcode.ErrWorkflowRecordNotExist
}
return nil, err
}
var revision = model.ApplicationRevision{
AppPrimaryKey: record.AppPrimaryKey,
Version: record.RevisionPrimaryKey,
}
err = w.Store.Get(ctx, &revision)
if err != nil {
if errors.Is(err, datastore.ErrRecordNotExist) {
return nil, bcode.ErrApplicationRevisionNotExist
}
return nil, err
}
return &apisv1.DetailWorkflowRecordResponse{
WorkflowRecord: *assembler.ConvertFromRecordModel(&record),
DeployTime: revision.CreateTime,
DeployUser: revision.DeployUser,
Note: revision.Note,
TriggerType: revision.TriggerType,
}, nil
}
func (w *workflowServiceImpl) SyncWorkflowRecord(ctx context.Context) error {
var record = model.WorkflowRecord{
Finished: "false",
}
// list all unfinished workflow records
records, err := w.Store.List(ctx, &record, &datastore.ListOptions{})
if err != nil {
return err
}
for _, item := range records {
app := &v1beta1.Application{}
record := item.(*model.WorkflowRecord)
workflow := &model.Workflow{
Name: record.WorkflowName,
AppPrimaryKey: record.AppPrimaryKey,
}
if err := w.Store.Get(ctx, workflow); err != nil {
klog.ErrorS(err, "failed to get workflow", "app name", record.AppPrimaryKey, "workflow name", record.WorkflowName, "record name", record.Name)
continue
}
appName := record.AppPrimaryKey
if err := w.KubeClient.Get(ctx, types.NamespacedName{
Name: appName,
Namespace: record.Namespace,
}, app); err != nil {
klog.ErrorS(err, "failed to get app", "oam app name", appName, "workflow name", record.WorkflowName, "record name", record.Name)
continue
}
// try to sync the status from the running application
if app.Annotations != nil && app.Status.Workflow != nil && app.Status.Workflow.AppRevision == record.Name {
if err := w.syncWorkflowStatus(ctx, app, record.Name, app.Name); err != nil {
klog.ErrorS(err, "failed to sync workflow status", "oam app name", appName, "workflow name", record.WorkflowName, "record name", record.Name)
}
continue
}
// try to sync the status from the controller revision
cr := &appsv1.ControllerRevision{}
if err := w.KubeClient.Get(ctx, types.NamespacedName{
Name: fmt.Sprintf("record-%s-%s", appName, record.Name),
Namespace: record.Namespace,
}, cr); err != nil {
klog.ErrorS(err, "failed to get controller revision", "oam app name", appName, "workflow name", record.WorkflowName, "record name", record.Name)
continue
}
appInRevision, err := util.RawExtension2Application(cr.Data)
if err != nil {
klog.ErrorS(err, "failed to get app data in controller revision", "controller revision name", cr.Name, "app name", appName, "workflow name", record.WorkflowName, "record name", record.Name)
continue
}
if err := w.syncWorkflowStatus(ctx, appInRevision, record.Name, cr.Name); err != nil {
klog.ErrorS(err, "failed to sync workflow status", "oam app name", appName, "workflow name", record.WorkflowName, "record name", record.Name)
continue
}
}
return nil
}
func (w *workflowServiceImpl) syncWorkflowStatus(ctx context.Context, app *v1beta1.Application, recordName, source string) error {
var record = &model.WorkflowRecord{
AppPrimaryKey: app.Annotations[oam.AnnotationAppName],
Name: recordName,
}
if err := w.Store.Get(ctx, record); err != nil {
if errors.Is(err, datastore.ErrRecordNotExist) {
return bcode.ErrWorkflowRecordNotExist
}
return err
}
var revision = &model.ApplicationRevision{
AppPrimaryKey: app.Annotations[oam.AnnotationAppName],
Version: record.RevisionPrimaryKey,
}
if err := w.Store.Get(ctx, revision); err != nil {
if errors.Is(err, datastore.ErrRecordNotExist) {
return bcode.ErrApplicationRevisionNotExist
}
return err
}
if app.Status.Workflow != nil {
status := app.Status.Workflow
summaryStatus := model.RevisionStatusRunning
if status.Finished {
summaryStatus = model.RevisionStatusComplete
}
if status.Terminated {
summaryStatus = model.RevisionStatusTerminated
}
record.Status = summaryStatus
stepStatus := make(map[string]*common.WorkflowStepStatus, len(status.Steps))
for i, step := range status.Steps {
stepStatus[step.Name] = &status.Steps[i]
}
for i, step := range record.Steps {
if stepStatus[step.Name] != nil {
record.Steps[i].Phase = stepStatus[step.Name].Phase
record.Steps[i].Message = stepStatus[step.Name].Message
record.Steps[i].Reason = stepStatus[step.Name].Reason
record.Steps[i].FirstExecuteTime = stepStatus[step.Name].FirstExecuteTime.Time
record.Steps[i].LastExecuteTime = stepStatus[step.Name].LastExecuteTime.Time
}
}
record.Finished = strconv.FormatBool(status.Finished)
if err := w.Store.Put(ctx, record); err != nil {
return err
}
revision.Status = summaryStatus
if err := w.Store.Put(ctx, revision); err != nil {
return err
}
}
if record.Finished == "true" {
klog.InfoS("successfully sync workflow status", "oam app name", app.Name, "workflow name", record.WorkflowName, "record name", record.Name, "status", record.Status, "sync source", source)
}
return nil
}
func (w *workflowServiceImpl) CreateWorkflowRecord(ctx context.Context, appModel *model.Application, app *v1beta1.Application, workflow *model.Workflow) error {
if app.Annotations == nil {
return fmt.Errorf("empty annotations in application")
}
if app.Annotations[oam.AnnotationPublishVersion] == "" {
return fmt.Errorf("failed to get record version from application")
}
if app.Annotations[oam.AnnotationDeployVersion] == "" {
return fmt.Errorf("failed to get deploy version from application")
}
steps := make([]model.WorkflowStepStatus, len(workflow.Steps))
for i, step := range workflow.Steps {
steps[i] = model.WorkflowStepStatus{
Name: step.Name,
Alias: step.Alias,
Type: step.Type,
}
}
if err := w.Store.Add(ctx, &model.WorkflowRecord{
WorkflowName: workflow.Name,
WorkflowAlias: workflow.Alias,
AppPrimaryKey: appModel.PrimaryKey(),
RevisionPrimaryKey: app.Annotations[oam.AnnotationDeployVersion],
Name: app.Annotations[oam.AnnotationPublishVersion],
Namespace: app.Namespace,
Finished: "false",
StartTime: time.Now().Time,
Steps: steps,
Status: model.RevisionStatusRunning,
}); err != nil {
return err
}
if err := resetRevisionsAndRecords(ctx, w.Store, appModel.PrimaryKey(), workflow.Name, app.Annotations[oam.AnnotationDeployVersion], app.Annotations[oam.AnnotationPublishVersion]); err != nil {
return err
}
return nil
}
func resetRevisionsAndRecords(ctx context.Context, ds datastore.DataStore, appName, workflowName, skipRevision, skipRecord string) error {
// set revision status' status to terminate
var revision = model.ApplicationRevision{
AppPrimaryKey: appName,
Status: model.RevisionStatusRunning,
}
// list all running revisions
revisions, err := ds.List(ctx, &revision, &datastore.ListOptions{})
if err != nil {
return err
}
for _, raw := range revisions {
revision, ok := raw.(*model.ApplicationRevision)
if ok {
if revision.Version == skipRevision {
continue
}
revision.Status = model.RevisionStatusTerminated
if err := ds.Put(ctx, revision); err != nil {
klog.Info("failed to set rest revisions' status to terminate", "app name", appName, "revision version", revision.Version, "error", err)
}
}
}
// set rest records' status to terminate
var record = model.WorkflowRecord{
WorkflowName: workflowName,
AppPrimaryKey: appName,
Finished: "false",
}
// list all unfinished workflow records
records, err := ds.List(ctx, &record, &datastore.ListOptions{})
if err != nil {
return err
}
for _, raw := range records {
record, ok := raw.(*model.WorkflowRecord)
if ok {
if record.Name == skipRecord {
continue
}
record.Status = model.RevisionStatusTerminated
record.Finished = "true"
for i, step := range record.Steps {
if step.Phase == common.WorkflowStepPhaseRunning {
record.Steps[i].Phase = common.WorkflowStepPhaseStopped
}
}
if err := ds.Put(ctx, record); err != nil {
klog.Info("failed to set rest records' status to terminate", "app name", appName, "workflow name", record.WorkflowName, "record name", record.Name, "error", err)
}
}
}
return nil
}
func (w *workflowServiceImpl) CountWorkflow(ctx context.Context, app *model.Application) int64 {
count, err := w.Store.Count(ctx, &model.Workflow{AppPrimaryKey: app.PrimaryKey()}, &datastore.FilterOptions{})
if err != nil {
log.Logger.Errorf("count app %s workflow failure %s", app.PrimaryKey(), err.Error())
}
return count
}
func (w *workflowServiceImpl) ResumeRecord(ctx context.Context, appModel *model.Application, workflow *model.Workflow, recordName string) error {
oamApp, err := w.checkRecordRunning(ctx, appModel, workflow.EnvName)
if err != nil {
return err
}
if err := ResumeWorkflow(ctx, w.KubeClient, oamApp); err != nil {
return err
}
if err := w.syncWorkflowStatus(ctx, oamApp, recordName, oamApp.Name); err != nil {
return err
}
return nil
}
func (w *workflowServiceImpl) TerminateRecord(ctx context.Context, appModel *model.Application, workflow *model.Workflow, recordName string) error {
oamApp, err := w.checkRecordRunning(ctx, appModel, workflow.EnvName)
if err != nil {
return err
}
if err := TerminateWorkflow(ctx, w.KubeClient, oamApp); err != nil {
return err
}
if err := w.syncWorkflowStatus(ctx, oamApp, recordName, oamApp.Name); err != nil {
return err
}
return nil
}
// ResumeWorkflow resume workflow
func ResumeWorkflow(ctx context.Context, kubecli client.Client, app *v1beta1.Application) error {
app.Status.Workflow.Suspend = false
steps := app.Status.Workflow.Steps
for i, step := range steps {
if step.Type == wfTypes.WorkflowStepTypeSuspend && step.Phase == common.WorkflowStepPhaseRunning {
steps[i].Phase = common.WorkflowStepPhaseSucceeded
}
for j, sub := range step.SubStepsStatus {
if sub.Type == wfTypes.WorkflowStepTypeSuspend && sub.Phase == common.WorkflowStepPhaseRunning {
steps[i].SubStepsStatus[j].Phase = common.WorkflowStepPhaseSucceeded
}
}
}
if err := kubecli.Status().Patch(ctx, app, client.Merge); err != nil {
return err
}
return nil
}
// TerminateWorkflow terminate workflow
func TerminateWorkflow(ctx context.Context, kubecli client.Client, app *v1beta1.Application) error {
// set the workflow terminated to true
app.Status.Workflow.Terminated = true
// set the workflow suspend to false
app.Status.Workflow.Suspend = false
steps := app.Status.Workflow.Steps
for i, step := range steps {
switch step.Phase {
case common.WorkflowStepPhaseFailed:
if step.Reason != custom.StatusReasonFailedAfterRetries && step.Reason != custom.StatusReasonTimeout {
steps[i].Reason = custom.StatusReasonTerminate
}
case common.WorkflowStepPhaseRunning:
steps[i].Phase = common.WorkflowStepPhaseFailed
steps[i].Reason = custom.StatusReasonTerminate
default:
}
for j, sub := range step.SubStepsStatus {
switch sub.Phase {
case common.WorkflowStepPhaseFailed:
if sub.Reason != custom.StatusReasonFailedAfterRetries && sub.Reason != custom.StatusReasonTimeout {
steps[i].SubStepsStatus[j].Phase = custom.StatusReasonTerminate
}
case common.WorkflowStepPhaseRunning:
steps[i].SubStepsStatus[j].Phase = common.WorkflowStepPhaseFailed
steps[i].SubStepsStatus[j].Reason = custom.StatusReasonTerminate
default:
}
}
}
if err := kubecli.Status().Patch(ctx, app, client.Merge); err != nil {
return err
}
return nil
}
func (w *workflowServiceImpl) RollbackRecord(ctx context.Context, appModel *model.Application, workflow *model.Workflow, recordName, revisionVersion string) error {
if revisionVersion == "" {
// find the latest complete revision version
var revision = model.ApplicationRevision{
AppPrimaryKey: appModel.Name,
Status: model.RevisionStatusComplete,
WorkflowName: workflow.Name,
EnvName: workflow.EnvName,
}
revisions, err := w.Store.List(ctx, &revision, &datastore.ListOptions{
Page: 1,
PageSize: 1,
SortBy: []datastore.SortOption{{Key: "createTime", Order: datastore.SortOrderDescending}},
})
if err != nil {
return err
}
if len(revisions) == 0 {
return bcode.ErrApplicationNoReadyRevision
}
revisionVersion = revisions[0].Index()["version"]
log.Logger.Infof("select lastest complete revision %s", revisions[0].Index()["version"])
}
var record = &model.WorkflowRecord{
AppPrimaryKey: appModel.PrimaryKey(),
Name: recordName,
}
if err := w.Store.Get(ctx, record); err != nil {
return err
}
oamApp, err := w.checkRecordRunning(ctx, appModel, workflow.EnvName)
if err != nil {
return err
}
var originalRevision = &model.ApplicationRevision{
AppPrimaryKey: appModel.Name,
Version: record.RevisionPrimaryKey,
}
if err := w.Store.Get(ctx, originalRevision); err != nil {
return err
}
var rollbackRevision = &model.ApplicationRevision{
AppPrimaryKey: appModel.Name,
Version: revisionVersion,
}
if err := w.Store.Get(ctx, rollbackRevision); err != nil {
return err
}
// update the original revision status to rollback
originalRevision.Status = model.RevisionStatusRollback
originalRevision.RollbackVersion = revisionVersion
originalRevision.UpdateTime = time.Now().Time
if err := w.Store.Put(ctx, originalRevision); err != nil {
return err
}
rollBackApp := &v1beta1.Application{}
if err := yaml.Unmarshal([]byte(rollbackRevision.ApplyAppConfig), rollBackApp); err != nil {
return err
}
// replace the application spec
oamApp.Spec.Components = rollBackApp.Spec.Components
oamApp.Spec.Policies = rollBackApp.Spec.Policies
if oamApp.Annotations == nil {
oamApp.Annotations = make(map[string]string)
}
newRecordName := utils.GenerateVersion(record.WorkflowName)
oamApp.Annotations[oam.AnnotationDeployVersion] = revisionVersion
oamApp.Annotations[oam.AnnotationPublishVersion] = newRecordName
// create a new workflow record
if err := w.CreateWorkflowRecord(ctx, appModel, oamApp, workflow); err != nil {
return err
}
if err := w.Apply.Apply(ctx, oamApp); err != nil {
// rollback error case
if err := w.Store.Delete(ctx, &model.WorkflowRecord{Name: newRecordName}); err != nil {
klog.Error(err, "failed to delete record", newRecordName)
}
return err
}
return nil
}
func (w *workflowServiceImpl) checkRecordRunning(ctx context.Context, appModel *model.Application, envName string) (*v1beta1.Application, error) {
oamApp := &v1beta1.Application{}
env, err := w.EnvService.GetEnv(ctx, envName)
if err != nil {
return nil, err
}
if err := w.KubeClient.Get(ctx, types.NamespacedName{Name: appModel.Name, Namespace: env.Namespace}, oamApp); err != nil {
return nil, err
}
if oamApp.Status.Workflow != nil && !oamApp.Status.Workflow.Suspend && !oamApp.Status.Workflow.Terminated && !oamApp.Status.Workflow.Finished |
oamApp.SetGroupVersionKind(v1beta1.ApplicationKindVersionKind)
return oamApp, nil
}
| {
return nil, fmt.Errorf("workflow is still running, can not operate a running workflow")
} |
refresh_token_grant_test.go | /*
* Copyright © 2015-2018 Aeneas Rekkas <[email protected]>
*
* 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.
*
* @author Aeneas Rekkas <[email protected]>
* @copyright 2015-2018 Aeneas Rekkas <[email protected]>
* @license Apache-2.0
*
*/
package integration_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/oauth2"
"github.com/toruta39/fosite"
"github.com/toruta39/fosite/compose"
"github.com/toruta39/fosite/handler/openid"
"github.com/toruta39/fosite/internal"
"github.com/toruta39/fosite/token/jwt"
)
type introspectionResponse struct {
Active bool `json:"active"`
ClientID string `json:"client_id,omitempty"`
Scope string `json:"scope,omitempty"`
Audience []string `json:"aud,omitempty"`
ExpiresAt int64 `json:"exp,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
Subject string `json:"sub,omitempty"`
Username string `json:"username,omitempty"`
}
func T | t *testing.T) {
session := &defaultSession{
DefaultSession: &openid.DefaultSession{
Claims: &jwt.IDTokenClaims{
Subject: "peter",
},
Headers: &jwt.Headers{},
Subject: "peter",
Username: "peteru",
},
}
fc := new(compose.Config)
fc.RefreshTokenLifespan = -1
f := compose.ComposeAllEnabled(fc, fositeStore, []byte("some-secret-thats-random-some-secret-thats-random-"), internal.MustRSAKey())
ts := mockServer(t, f, session)
defer ts.Close()
oauthClient := newOAuth2Client(ts)
state := "1234567890"
fositeStore.Clients["my-client"].(*fosite.DefaultClient).RedirectURIs[0] = ts.URL + "/callback"
refreshCheckClient := &fosite.DefaultClient{
ID: "refresh-client",
Secret: []byte(`$2a$10$IxMdI6d.LIRZPpSfEwNoeu4rY3FhDREsxFJXikcgdRRAStxUlsuEO`), // = "foobar"
RedirectURIs: []string{ts.URL + "/callback"},
ResponseTypes: []string{"id_token", "code", "token", "token code", "id_token code", "token id_token", "token code id_token"},
GrantTypes: []string{"implicit", "refresh_token", "authorization_code", "password", "client_credentials"},
Scopes: []string{"fosite", "offline", "openid"},
Audience: []string{"https://www.ory.sh/api"},
}
fositeStore.Clients["refresh-client"] = refreshCheckClient
fositeStore.Clients["my-client"].(*fosite.DefaultClient).RedirectURIs[0] = ts.URL + "/callback"
for _, c := range []struct {
description string
setup func(t *testing.T)
pass bool
params []oauth2.AuthCodeOption
check func(t *testing.T, original, refreshed *oauth2.Token, or, rr *introspectionResponse)
beforeRefresh func(t *testing.T)
mockServer func(t *testing.T) *httptest.Server
}{
{
description: "should fail because refresh scope missing",
setup: func(t *testing.T) {
oauthClient.Scopes = []string{"fosite"}
},
pass: false,
},
{
description: "should pass but not yield id token",
setup: func(t *testing.T) {
oauthClient.Scopes = []string{"offline"}
},
pass: true,
check: func(t *testing.T, original, refreshed *oauth2.Token, or, rr *introspectionResponse) {
assert.NotEqual(t, original.RefreshToken, refreshed.RefreshToken)
assert.NotEqual(t, original.AccessToken, refreshed.AccessToken)
assert.Nil(t, refreshed.Extra("id_token"))
},
},
{
description: "should pass and yield id token",
params: []oauth2.AuthCodeOption{oauth2.SetAuthURLParam("audience", "https://www.ory.sh/api")},
setup: func(t *testing.T) {
oauthClient.Scopes = []string{"fosite", "offline", "openid"}
},
pass: true,
check: func(t *testing.T, original, refreshed *oauth2.Token, or, rr *introspectionResponse) {
assert.NotEqual(t, original.RefreshToken, refreshed.RefreshToken)
assert.NotEqual(t, original.AccessToken, refreshed.AccessToken)
assert.NotEqual(t, original.Extra("id_token"), refreshed.Extra("id_token"))
assert.NotNil(t, refreshed.Extra("id_token"))
assert.NotEmpty(t, or.Audience)
assert.NotEmpty(t, or.ClientID)
assert.NotEmpty(t, or.Scope)
assert.NotEmpty(t, or.ExpiresAt)
assert.NotEmpty(t, or.IssuedAt)
assert.True(t, or.Active)
assert.EqualValues(t, "peter", or.Subject)
assert.EqualValues(t, "peteru", or.Username)
assert.EqualValues(t, or.Audience, rr.Audience)
assert.EqualValues(t, or.ClientID, rr.ClientID)
assert.EqualValues(t, or.Scope, rr.Scope)
assert.NotEqual(t, or.ExpiresAt, rr.ExpiresAt)
assert.True(t, or.ExpiresAt < rr.ExpiresAt)
assert.NotEqual(t, or.IssuedAt, rr.IssuedAt)
assert.True(t, or.IssuedAt < rr.IssuedAt)
assert.EqualValues(t, or.Active, rr.Active)
assert.EqualValues(t, or.Subject, rr.Subject)
assert.EqualValues(t, or.Username, rr.Username)
},
},
{
description: "should fail because scope is no longer allowed",
setup: func(t *testing.T) {
oauthClient.ClientID = refreshCheckClient.ID
oauthClient.Scopes = []string{"fosite", "offline", "openid"}
},
beforeRefresh: func(t *testing.T) {
refreshCheckClient.Scopes = []string{"offline", "openid"}
},
pass: false,
},
{
description: "should fail because audience is no longer allowed",
params: []oauth2.AuthCodeOption{oauth2.SetAuthURLParam("audience", "https://www.ory.sh/api")},
setup: func(t *testing.T) {
oauthClient.ClientID = refreshCheckClient.ID
oauthClient.Scopes = []string{"fosite", "offline", "openid"}
refreshCheckClient.Scopes = []string{"fosite", "offline", "openid"}
},
beforeRefresh: func(t *testing.T) {
refreshCheckClient.Audience = []string{"https://www.not-ory.sh/api"}
},
pass: false,
},
{
description: "should fail with expired refresh token",
setup: func(t *testing.T) {
fc = new(compose.Config)
fc.RefreshTokenLifespan = time.Nanosecond
f = compose.ComposeAllEnabled(fc, fositeStore, []byte("some-secret-thats-random-some-secret-thats-random-"), internal.MustRSAKey())
ts = mockServer(t, f, session)
oauthClient = newOAuth2Client(ts)
oauthClient.Scopes = []string{"fosite", "offline", "openid"}
fositeStore.Clients["my-client"].(*fosite.DefaultClient).RedirectURIs[0] = ts.URL + "/callback"
},
pass: false,
},
{
description: "should pass with limited but not expired refresh token",
setup: func(t *testing.T) {
fc = new(compose.Config)
fc.RefreshTokenLifespan = time.Minute
f = compose.ComposeAllEnabled(fc, fositeStore, []byte("some-secret-thats-random-some-secret-thats-random-"), internal.MustRSAKey())
ts = mockServer(t, f, session)
oauthClient = newOAuth2Client(ts)
oauthClient.Scopes = []string{"fosite", "offline", "openid"}
fositeStore.Clients["my-client"].(*fosite.DefaultClient).RedirectURIs[0] = ts.URL + "/callback"
},
beforeRefresh: func(t *testing.T) {
refreshCheckClient.Audience = []string{}
},
pass: true,
check: func(t *testing.T, original, refreshed *oauth2.Token, or, rr *introspectionResponse) {},
},
} {
t.Run("case="+c.description, func(t *testing.T) {
c.setup(t)
var intro = func(token string, p interface{}) {
req, err := http.NewRequest("POST", ts.URL+"/introspect", strings.NewReader(url.Values{"token": {token}}.Encode()))
require.NoError(t, err)
req.SetBasicAuth("refresh-client", "foobar")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
r, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, r.StatusCode)
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
require.NoError(t, dec.Decode(p))
}
resp, err := http.Get(oauthClient.AuthCodeURL(state, c.params...))
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
if resp.StatusCode != http.StatusOK {
return
}
token, err := oauthClient.Exchange(oauth2.NoContext, resp.Request.URL.Query().Get("code"))
require.NoError(t, err)
require.NotEmpty(t, token.AccessToken)
var ob introspectionResponse
intro(token.AccessToken, &ob)
t.Logf("Token %s\n", token)
token.Expiry = token.Expiry.Add(-time.Hour * 24)
if c.beforeRefresh != nil {
c.beforeRefresh(t)
}
tokenSource := oauthClient.TokenSource(oauth2.NoContext, token)
// This sleep guarantees time difference in exp/iat
time.Sleep(time.Second * 2)
refreshed, err := tokenSource.Token()
if c.pass {
require.NoError(t, err)
var rb introspectionResponse
intro(refreshed.AccessToken, &rb)
c.check(t, token, refreshed, &ob, &rb)
} else {
require.Error(t, err)
}
})
}
}
| estRefreshTokenFlow( |
io.go | package lib
import (
"io"
"github.com/dop251/goja"
"github.com/zengming00/go-server-js/nodejs/require"
)
func | () {
require.RegisterNativeModule("io", func(runtime *goja.Runtime, module *goja.Object) {
o := module.Get("exports").(*goja.Object)
o.Set("copy", func(call goja.FunctionCall) goja.Value {
p0 := GetNativeType(runtime, &call, 0)
dst, ok := p0.(io.Writer)
if !ok {
panic(runtime.NewTypeError("p0 is not io.Writer type:%T", p0))
}
p1 := GetNativeType(runtime, &call, 1)
src, ok := p1.(io.Reader)
if !ok {
panic(runtime.NewTypeError("p1 is not io.Reader type:%T", p1))
}
written, err := io.Copy(dst, src)
if err != nil {
return MakeErrorValue(runtime, err)
}
return MakeReturnValue(runtime, written)
})
})
}
| init |
context.rs | /*
* Copyright (c) 2021. Aberic - 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.
*/
use std::borrow::Borrow;
use std::collections::HashMap;
use std::hash::Hash;
use std::net::TcpStream;
use crate::{Header, Response, Status, Version, Requester};
use crate::http::header::{ContentType, Cookie};
use crate::http::url::authority::{Addr, Userinfo};
use crate::http::values::FileHeader;
use crate::utils::errors::StarryResult;
#[derive(Debug)]
pub struct Context {
requester: Requester<TcpStream>,
response: Response,
fields: HashMap<String, String>,
/// 是否已经执行过response方法
pub(crate) executed: bool,
}
/// request相关
impl Context {
pub(crate) fn new(requester: Requester<TcpStream>, fields: HashMap<String, String>, compress: bool) -> Self {
let version = requester.version();
let connection = !requester.request.close;
Context { requester, response: Response::new(version, connection, compress), fields, executed: false }
}
// pub fn get_request(&self) -> StarryResult<Request> {
// self.request.try_clone()
// }
pub fn req_header(&self) -> Header {
self.requester.header()
}
pub fn req_header_get<K: ?Sized>(&self, k: &K) -> Option<String> where
K: Borrow<K>,
K: Hash + Eq,
String: Borrow<K>, {
self.requester.header_get(k)
}
pub fn req_userinfo(&self) -> Option<Userinfo> {
self.requester.userinfo()
}
pub fn req_path(&self) -> String {
self.requester.path()
}
pub fn req_client_addr(&self) -> Addr {
self.requester.addr()
}
/// 如果请求头指示客户端正在发起websocket握手,则IsWebsocket返回true
///
/// WebSocket, Http 2的协议升级过程,都需要Connection,Upgrade两个字端来联合完成。
/// 比如初始化WebSocket请求:
///
/// ```header
/// Host: echo.websocket.org
/// Connection: Upgrade
/// Upgrade: websocket
/// ```
pub fn req_is_web_socket(&self) -> bool {
match self.req_header_get("Connection") {
Some(src) => if src.ne("upgrade") {
return false;
},
None => return false,
}
match self.req_header_get("Upgrade") {
Some(src) => if src.eq("websocket") {
return true;
},
None => return false,
}
false
}
pub fn req_cookies(&self) -> Vec<Cookie> {
self.requester.cookies()
}
pub fn req_cookie_get(&self, cookie_name: &str) -> Option<Cookie> {
self.requester.cookie_get(cookie_name)
}
/// 返回对应于请求表单中定义参数值的引用。
pub fn req_form<K: ?Sized>(&mut self, k: &K) -> StarryResult<Option<String>> where
K: Borrow<K>,
K: Hash + Eq,
String: Borrow<K>, {
self.requester.form_value(k)
}
/// 返回对应于请求表单中定义的参数存在性。
pub fn req_have_form<K: ?Sized>(&mut self, k: &K) -> StarryResult<bool> where
K: Borrow<K>,
K: Hash + Eq,
String: Borrow<K>, {
self.requester.have_form_value(k)
}
/// 请求表单中定义的参数数量
pub fn req_count_form(&mut self) -> StarryResult<usize> {
self.requester.count_form_value()
}
/// 返回对应于URI请求参数中定义参数值的引用。
pub fn req_param<K: ?Sized>(&self, k: &K) -> Option<String> where
K: Borrow<K>,
K: Hash + Eq,
String: Borrow<K>, {
self.requester.param_value(k)
}
/// 返回对应于URI请求参数中定义的参数存在性。
pub fn req_have_param<K: ?Sized>(&self, k: &K) -> bool where
K: Borrow<K>,
K: Hash + Eq,
String: Borrow<K>, {
self.requester.have_param_value(k)
}
/// URI请求参数中定义的参数数量
pub fn req_count_param(&self) -> usize {
self.requester.count_param_value()
}
/// 返回对应于URI资源路径中定义参数值的引用。
/// 键可以是映射的键类型的任何借用形式,但是借用形式上的Hash和Eq必须与键类型匹配。
pub fn req_field<K: ?Sized>(&self, k: &K) -> Option<String> where
K: Borrow<K>,
K: Hash + Eq,
String: Borrow<K>, {
match self.fields.get(k) {
Some(src) => Some(src.clone()),
None => None
}
}
/// 返回对应于URI资源路径中定义的参数存在性。
pub fn req_have_field<K: ?Sized>(&self, k: &K) -> bool where
K: Borrow<K>,
K: Hash + Eq,
String: Borrow<K>, {
match self.fields.get(k) {
Some(_) => true,
None => false,
}
}
/// URI资源路径中定义的参数数量
pub fn req_count_fields(&self) -> usize {
self.fields.len()
}
/// 返回对应于请求表单中定义参数对应附件的引用。
pub fn req_form_file<K: ?Sized>(&mut self, k: &K) -> StarryResult<Option<FileHeader>> where
K: Borrow<K>,
K: Hash + Eq,
String: Borrow<K>, {
Ok(self.requester.multipart_form()?.get(k))
}
}
/// response相关
impl Context {
pub fn get_response(&self) -> Response {
self.response.clone()
}
pub fn resp_add_header(&mut self, k: String, v: String) {
self.response.add_header(k, v)
}
pub fn resp_add_header_str(&mut self, k: &str, v: &str) {
self.response.add_header_str(k, v)
}
pub fn resp_set_header(&mut self, k: String, v: String) {
self.response.set_header(k, v)
}
pub fn resp_set_header_str(&mut self, k: &str, v: &str) {
self.response.set_header_str(k, v)
}
pub fn resp_add_cookie(&mut self, cookie: Cookie) {
self.response.add_set_cookie(cookie)
}
pub fn resp_status(&mut self, status: Status) {
self.response.status(status)
}
pub fn resp_version(&mut self, version: Version) {
self.response.version(version)
}
pub fn resp_content_type(&mut self, src: ContentType) {
self.response.set_content_type(src)
}
pub fn resp_body(&mut self, body: Vec<u8>) {
self.response.write(body, self.requester.accept_encoding())
}
pub fn resp_body_slice(&mut self, body: &'static [u8]) {
self.response.write_slice(body, self.requester.accept_encoding())
}
pub fn resp_bodies(&mut self, body: Vec<u8>, content_type: ContentType) {
self.response.write_type(body, content_type, self.requester.accept_encoding())
}
| slices(&mut self, body: &'static [u8], content_type: ContentType) {
self.response.write_slice_type(body, content_type, self.requester.accept_encoding())
}
pub fn response(&mut self) {
self.executed = true;
match self.requester.response(self.response.clone()) {
Ok(()) => {}
Err(err) => log::error!("response failed! {}", err)
}
}
}
| pub fn resp_body_ |
mapper_001.rs | use super::{CartridgeReadTarget, Mapper, Mirroring};
const CHR_MODE_MASK: u8 = 0b10000;
const PRG_MODE_MASK: u8 = 0b01100;
pub struct Mapper001 {
prg_banks: u8,
prg_bank_selector_32: u8,
prg_bank_selector_16_lo: u8,
prg_bank_selector_16_hi: u8,
chr_bank_selector_8: u8,
chr_bank_selector_4_lo: u8,
chr_bank_selector_4_hi: u8,
load_register: u8,
load_register_count: u8,
control_register: u8,
ram_data: [u8; 0x2000],
mirroring: Mirroring,
}
impl Mapper001 {
pub fn new(prg_banks: u8, mirroring: Mirroring, save_data: Option<&[u8]>) -> Self {
let mut ram_data = [0u8; 0x2000];
// Load the save data
if let Some(save_data) = save_data {
ram_data
.iter_mut()
.zip(save_data.iter())
.for_each(|(r, s)| *r = *s)
};
Self {
prg_banks,
prg_bank_selector_32: 0,
prg_bank_selector_16_lo: 0,
prg_bank_selector_16_hi: prg_banks - 1,
chr_bank_selector_8: 0,
chr_bank_selector_4_lo: 0,
chr_bank_selector_4_hi: 0,
load_register: 0,
load_register_count: 0,
control_register: 0x0C,
ram_data,
mirroring,
}
}
} | fn cpu_map_read(&self, addr: u16) -> CartridgeReadTarget {
match addr {
0x6000..=0x7FFF => {
// Read from RAM
CartridgeReadTarget::PrgRam(self.ram_data[(addr & 0x1FFF) as usize])
// TODO: windowed RAM?
}
_ => {
if (self.control_register & PRG_MODE_MASK) > 1 {
// 16K PRG mode
match addr {
0x8000..=0xBFFF => CartridgeReadTarget::PrgRom(
(self.prg_bank_selector_16_lo as usize) * 0x4000
+ (addr & 0x3FFF) as usize,
),
0xC000..=0xFFFF => CartridgeReadTarget::PrgRom(
(self.prg_bank_selector_16_hi as usize) * 0x4000
+ (addr & 0x3FFF) as usize,
),
_ => {
log::warn!("Attempted to read address w/o known mapping {:#06x}", addr);
CartridgeReadTarget::PrgRom(0)
}
}
} else {
// 32K PRG mode
CartridgeReadTarget::PrgRom(
(self.prg_bank_selector_32 as usize) * 0x8000 + (addr & 0x7FFF) as usize,
)
}
}
}
}
fn cpu_map_write(&mut self, addr: u16, data: u8) {
if (0x6000..=0x7FFF).contains(&addr) {
// Write to RAM
self.ram_data[(addr & 0x1FFF) as usize] = data; // TODO: windowed RAM?
return;
}
if (data & 0x80) == 0x80 {
// Reset load register
self.load_register = 0;
self.load_register_count = 0;
self.control_register |= 0x0C;
return;
}
// Add new bit to load register
self.load_register >>= 1;
self.load_register |= (data & 0x01) << 4;
self.load_register_count += 1;
// Check if load register is full
if self.load_register_count == 5 {
// Check target of write using bit 14 and 13 from the address
match addr & 0x6000 {
0x0000 => {
// Control register
self.control_register = self.load_register & 0x1F;
match self.control_register & 0x03 {
0 => self.mirroring = Mirroring::OneScreenLower,
1 => self.mirroring = Mirroring::OneScreenUpper,
2 => self.mirroring = Mirroring::Vertical,
_ => self.mirroring = Mirroring::Horizontal,
}
}
0x2000 => {
// CHR bank 0
if (self.control_register & CHR_MODE_MASK) != 0 {
self.chr_bank_selector_4_lo = self.load_register & 0x1F;
} else {
self.chr_bank_selector_8 = self.load_register & 0x1E;
}
}
0x4000 => {
// CHR bank 1
self.chr_bank_selector_4_hi = self.load_register & 0x1F;
}
0x6000 => {
// PRG bank
match (self.control_register & PRG_MODE_MASK) >> 2 {
2 => {
// 16K mode, fix low bank
self.prg_bank_selector_16_lo = 0;
self.prg_bank_selector_16_hi = self.load_register & 0x0F;
}
3 => {
// 16K mode, fix high bank
self.prg_bank_selector_16_lo = self.load_register & 0x0F;
self.prg_bank_selector_16_hi = self.prg_banks - 1;
}
_ => {
// 32K mode
self.prg_bank_selector_32 = (self.load_register & 0x0E) >> 1;
}
}
}
_ => unreachable!(),
}
// Reset load register
self.load_register = 0x00;
self.load_register_count = 0;
}
}
fn ppu_map_read(&mut self, addr: u16) -> usize {
if (self.control_register & CHR_MODE_MASK) != 0 {
// 4K CHR mode
match addr {
0x0000..=0x0FFF => {
(self.chr_bank_selector_4_lo as usize) * 0x1000 + (addr & 0x0FFF) as usize
}
_ => (self.chr_bank_selector_4_hi as usize) * 0x1000 + (addr & 0x0FFF) as usize,
}
} else {
// 8K CHR mode
(self.chr_bank_selector_8 as usize) * 0x2000 + (addr & 0x1FFF) as usize
}
}
fn ppu_map_write(&self, addr: u16) -> Option<usize> {
Some((self.chr_bank_selector_8 as usize) * 0x2000 + (addr & 0x1FFF) as usize)
}
fn mirroring(&self) -> Mirroring {
self.mirroring
}
fn get_sram(&self) -> Option<&[u8]> {
Some(&self.ram_data)
}
#[cfg(feature = "debugger")]
fn get_prg_bank(&self, addr: u16) -> Option<u8> {
match addr {
0x0000..=0x7FFF => None,
_ => {
if (self.control_register & PRG_MODE_MASK) > 1 {
// 16K PRG mode
match addr {
0x8000..=0xBFFF => Some(self.prg_bank_selector_16_lo),
0xC000..=0xFFFF => Some(self.prg_bank_selector_16_hi),
_ => None,
}
} else {
// 32K PRG mode
Some(self.prg_bank_selector_32)
}
}
}
}
} |
impl Mapper for Mapper001 { |
context-menu-holder.component.d.ts | /*!
* @license
* Copyright 2016 Alfresco Software, Ltd.
*
* 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.
*/
import { OverlayContainer } from '@angular/cdk/overlay';
import { ViewportRuler } from '@angular/cdk/scrolling';
import { OnDestroy, OnInit, Renderer2 } from '@angular/core';
import { MatMenuTrigger } from '@angular/material';
import { ContextMenuService } from './context-menu.service';
/**
* @deprecated: context-menu-holder is deprecated, use adf-context-menu-holder instead.
*/
export declare class | implements OnInit, OnDestroy {
private viewport;
private overlayContainer;
private contextMenuService;
private renderer;
links: any[];
private mouseLocation;
private menuElement;
private openSubscription;
private closeSubscription;
private contextSubscription;
private contextMenuListenerFn;
showIcons: boolean;
menuTrigger: MatMenuTrigger;
onShowContextMenu(event?: MouseEvent): void;
onResize(event: any): void;
constructor(viewport: ViewportRuler, overlayContainer: OverlayContainer, contextMenuService: ContextMenuService, renderer: Renderer2);
ngOnInit(): void;
ngOnDestroy(): void;
onMenuItemClick(event: Event, menuItem: any): void;
showMenu(e: any, links: any): void;
setPositionAfterCDKrecalculation(): void;
readonly mdMenuElement: any;
private locationCss();
private setPosition();
private getContextMenuElement();
}
| ContextMenuHolderComponent |
test_checkpoint.rs | // Copyright 2020 Tyler Neely
//
// 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.
mod util;
use pretty_assertions::assert_eq;
use rocksdb_silk::{checkpoint::Checkpoint, Options, DB};
use util::DBPath;
#[test]
pub fn test_single_checkpoint() |
#[test]
pub fn test_multi_checkpoints() {
const PATH_PREFIX: &str = "_rust_rocksdb_cp_multi_";
// Create DB with some data
let db_path = DBPath::new(&format!("{}db1", PATH_PREFIX));
let mut opts = Options::default();
opts.create_if_missing(true);
let db = DB::open(&opts, &db_path).unwrap();
db.put(b"k1", b"v1").unwrap();
db.put(b"k2", b"v2").unwrap();
db.put(b"k3", b"v3").unwrap();
db.put(b"k4", b"v4").unwrap();
// Create first checkpoint
let cp1 = Checkpoint::new(&db).unwrap();
let cp1_path = DBPath::new(&format!("{}cp1", PATH_PREFIX));
cp1.create_checkpoint(&cp1_path).unwrap();
// Verify checkpoint
let cp = DB::open_default(&cp1_path).unwrap();
assert_eq!(cp.get(b"k1").unwrap().unwrap(), b"v1");
assert_eq!(cp.get(b"k2").unwrap().unwrap(), b"v2");
assert_eq!(cp.get(b"k3").unwrap().unwrap(), b"v3");
assert_eq!(cp.get(b"k4").unwrap().unwrap(), b"v4");
// Change some existing keys
db.put(b"k1", b"modified").unwrap();
db.put(b"k2", b"changed").unwrap();
// Add some new keys
db.put(b"k5", b"v5").unwrap();
db.put(b"k6", b"v6").unwrap();
// Create another checkpoint
let cp2 = Checkpoint::new(&db).unwrap();
let cp2_path = DBPath::new(&format!("{}cp2", PATH_PREFIX));
cp2.create_checkpoint(&cp2_path).unwrap();
// Verify second checkpoint
let cp = DB::open_default(&cp2_path).unwrap();
assert_eq!(cp.get(b"k1").unwrap().unwrap(), b"modified");
assert_eq!(cp.get(b"k2").unwrap().unwrap(), b"changed");
assert_eq!(cp.get(b"k5").unwrap().unwrap(), b"v5");
assert_eq!(cp.get(b"k6").unwrap().unwrap(), b"v6");
}
| {
const PATH_PREFIX: &str = "_rust_rocksdb_cp_single_";
// Create DB with some data
let db_path = DBPath::new(&format!("{}db1", PATH_PREFIX));
let mut opts = Options::default();
opts.create_if_missing(true);
let db = DB::open(&opts, &db_path).unwrap();
db.put(b"k1", b"v1").unwrap();
db.put(b"k2", b"v2").unwrap();
db.put(b"k3", b"v3").unwrap();
db.put(b"k4", b"v4").unwrap();
// Create checkpoint
let cp1 = Checkpoint::new(&db).unwrap();
let cp1_path = DBPath::new(&format!("{}cp1", PATH_PREFIX));
cp1.create_checkpoint(&cp1_path).unwrap();
// Verify checkpoint
let cp = DB::open_default(&cp1_path).unwrap();
assert_eq!(cp.get(b"k1").unwrap().unwrap(), b"v1");
assert_eq!(cp.get(b"k2").unwrap().unwrap(), b"v2");
assert_eq!(cp.get(b"k3").unwrap().unwrap(), b"v3");
assert_eq!(cp.get(b"k4").unwrap().unwrap(), b"v4");
} |
kfservice_validation_test.go | /*
Copyright 2019 kubeflow.org.
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 v1alpha2
import (
"fmt"
"testing"
"github.com/onsi/gomega"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func makeTestKFService() KFService {
kfservice := KFService{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "default",
},
Spec: KFServiceSpec{
Default: EndpointSpec{
Predictor: PredictorSpec{
Tensorflow: &TensorflowSpec{StorageURI: "gs://testbucket/testmodel"},
},
},
},
}
kfservice.Default()
return kfservice
}
func TestValidStorageURIPrefixOK(t *testing.T) {
g := gomega.NewGomegaWithT(t)
for _, prefix := range SupportedStorageURIPrefixList {
kfsvc := makeTestKFService()
kfsvc.Spec.Default.Predictor.Tensorflow.StorageURI = prefix + "foo/bar"
g.Expect(kfsvc.ValidateCreate()).Should(gomega.Succeed())
}
}
func TestEmptyStorageURIPrefixOK(t *testing.T) {
g := gomega.NewGomegaWithT(t)
kfsvc := makeTestKFService()
kfsvc.Spec.Default.Predictor.Tensorflow.StorageURI = ""
g.Expect(kfsvc.ValidateCreate()).Should(gomega.Succeed())
}
func TestLocalPathStorageURIPrefixOK(t *testing.T) {
g := gomega.NewGomegaWithT(t)
kfsvc := makeTestKFService()
kfsvc.Spec.Default.Predictor.Tensorflow.StorageURI = "some/relative/path"
g.Expect(kfsvc.ValidateCreate()).Should(gomega.Succeed())
kfsvc.Spec.Default.Predictor.Tensorflow.StorageURI = "/some/absolute/path"
g.Expect(kfsvc.ValidateCreate()).Should(gomega.Succeed())
kfsvc.Spec.Default.Predictor.Tensorflow.StorageURI = "/"
g.Expect(kfsvc.ValidateCreate()).Should(gomega.Succeed())
kfsvc.Spec.Default.Predictor.Tensorflow.StorageURI = "foo"
g.Expect(kfsvc.ValidateCreate()).Should(gomega.Succeed())
}
func TestAzureBlobOK(t *testing.T) {
g := gomega.NewGomegaWithT(t)
kfsvc := makeTestKFService()
kfsvc.Spec.Default.Predictor.Tensorflow.StorageURI = "https://kfserving.blob.core.windows.net/tensorrt/simple_string/"
g.Expect(kfsvc.ValidateCreate()).Should(gomega.Succeed())
kfsvc.Spec.Default.Predictor.Tensorflow.StorageURI = "https://kfserving.blob.core.windows.net/tensorrt/simple_string"
g.Expect(kfsvc.ValidateCreate()).Should(gomega.Succeed())
kfsvc.Spec.Default.Predictor.Tensorflow.StorageURI = "https://kfserving.blob.core.windows.net/tensorrt/"
g.Expect(kfsvc.ValidateCreate()).Should(gomega.Succeed())
kfsvc.Spec.Default.Predictor.Tensorflow.StorageURI = "https://kfserving.blob.core.windows.net/tensorrt"
g.Expect(kfsvc.ValidateCreate()).Should(gomega.Succeed())
}
func TestAzureBlobNoAccountFails(t *testing.T) {
g := gomega.NewGomegaWithT(t)
kfsvc := makeTestKFService()
kfsvc.Spec.Default.Predictor.Tensorflow.StorageURI = "https://blob.core.windows.net/tensorrt/simple_string/"
g.Expect(kfsvc.ValidateCreate()).ShouldNot(gomega.Succeed())
}
func | (t *testing.T) {
g := gomega.NewGomegaWithT(t)
kfsvc := makeTestKFService()
kfsvc.Spec.Default.Predictor.Tensorflow.StorageURI = "https://foo.blob.core.windows.net/"
g.Expect(kfsvc.ValidateCreate()).ShouldNot(gomega.Succeed())
}
func TestUnkownStorageURIPrefixFails(t *testing.T) {
g := gomega.NewGomegaWithT(t)
kfsvc := makeTestKFService()
kfsvc.Spec.Default.Predictor.Tensorflow.StorageURI = "blob://foo/bar"
g.Expect(kfsvc.ValidateCreate()).ShouldNot(gomega.Succeed())
}
func TestRejectMultipleModelSpecs(t *testing.T) {
g := gomega.NewGomegaWithT(t)
kfsvc := makeTestKFService()
kfsvc.Spec.Default.Predictor.Custom = &CustomSpec{Container: v1.Container{}}
g.Expect(kfsvc.ValidateCreate()).Should(gomega.MatchError(ExactlyOnePredictorViolatedError))
}
func TestRejectModelSpecMissing(t *testing.T) {
g := gomega.NewGomegaWithT(t)
kfsvc := makeTestKFService()
kfsvc.Spec.Default.Predictor.Tensorflow = nil
g.Expect(kfsvc.ValidateCreate()).Should(gomega.MatchError(ExactlyOnePredictorViolatedError))
}
func TestRejectMultipleCanaryModelSpecs(t *testing.T) {
g := gomega.NewGomegaWithT(t)
kfsvc := makeTestKFService()
kfsvc.Spec.Canary = &EndpointSpec{
Predictor: PredictorSpec{
Custom: &CustomSpec{Container: v1.Container{}},
Tensorflow: kfsvc.Spec.Default.Predictor.Tensorflow,
},
}
g.Expect(kfsvc.ValidateCreate()).Should(gomega.MatchError(ExactlyOnePredictorViolatedError))
}
func TestRejectCanaryModelSpecMissing(t *testing.T) {
g := gomega.NewGomegaWithT(t)
kfsvc := makeTestKFService()
kfsvc.Spec.Canary = &EndpointSpec{
Predictor: PredictorSpec{},
}
g.Expect(kfsvc.ValidateCreate()).Should(gomega.MatchError(ExactlyOnePredictorViolatedError))
}
func TestRejectBadCanaryTrafficValues(t *testing.T) {
g := gomega.NewGomegaWithT(t)
kfsvc := makeTestKFService()
kfsvc.Spec.Canary = &kfsvc.Spec.Default
kfsvc.Spec.CanaryTrafficPercent = -1
g.Expect(kfsvc.ValidateCreate()).Should(gomega.MatchError(TrafficBoundsExceededError))
kfsvc.Spec.CanaryTrafficPercent = 101
g.Expect(kfsvc.ValidateCreate()).Should(gomega.MatchError(TrafficBoundsExceededError))
}
func TestRejectTrafficProvidedWithoutCanary(t *testing.T) {
g := gomega.NewGomegaWithT(t)
kfsvc := makeTestKFService()
kfsvc.Spec.CanaryTrafficPercent = 1
g.Expect(kfsvc.ValidateCreate()).Should(gomega.MatchError(TrafficProvidedWithoutCanaryError))
}
func TestBadReplicaValues(t *testing.T) {
g := gomega.NewGomegaWithT(t)
kfsvc := makeTestKFService()
kfsvc.Spec.Default.Predictor.MinReplicas = -1
g.Expect(kfsvc.ValidateCreate()).Should(gomega.MatchError(MinReplicasLowerBoundExceededError))
kfsvc.Spec.Default.Predictor.MinReplicas = 1
kfsvc.Spec.Default.Predictor.MaxReplicas = -1
g.Expect(kfsvc.ValidateCreate()).Should(gomega.MatchError(MaxReplicasLowerBoundExceededError))
kfsvc.Spec.Default.Predictor.MinReplicas = 2
kfsvc.Spec.Default.Predictor.MaxReplicas = 1
g.Expect(kfsvc.ValidateCreate()).Should(gomega.MatchError(MinReplicasShouldBeLessThanMaxError))
}
func TestCustomBadFields(t *testing.T) {
g := gomega.NewGomegaWithT(t)
kfsvc := makeTestKFService()
kfsvc.Spec.Default.Predictor.Tensorflow = nil
kfsvc.Spec.Default.Predictor.Custom = &CustomSpec{
v1.Container{
Name: "foo",
Image: "custom:0.1",
Stdin: true,
StdinOnce: true,
},
}
g.Expect(kfsvc.ValidateCreate()).Should(gomega.MatchError("Custom container validation error: must not set the field(s): stdin, stdinOnce"))
}
func TestCustomOK(t *testing.T) {
g := gomega.NewGomegaWithT(t)
kfsvc := makeTestKFService()
kfsvc.Spec.Default.Predictor.Tensorflow = nil
kfsvc.Spec.Default.Predictor.Custom = &CustomSpec{
v1.Container{
Image: "custom:0.1",
},
}
err := kfsvc.ValidateCreate()
fmt.Println(err)
g.Expect(kfsvc.ValidateCreate()).Should(gomega.Succeed())
}
func TestRejectBadTransformer(t *testing.T) {
g := gomega.NewGomegaWithT(t)
kfsvc := makeTestKFService()
kfsvc.Spec.Default.Transformer = &TransformerSpec{}
g.Expect(kfsvc.ValidateCreate()).Should(gomega.MatchError(ExactlyOneTransformerViolatedError))
}
func TestRejectBadExplainer(t *testing.T) {
g := gomega.NewGomegaWithT(t)
kfsvc := makeTestKFService()
kfsvc.Spec.Default.Explainer = &ExplainerSpec{}
g.Expect(kfsvc.ValidateCreate()).Should(gomega.MatchError(ExactlyOneExplainerViolatedError))
}
| TestAzureBlobNoContainerFails |
types.ts | namespace ts {
// branded string type used to store absolute, normalized and canonicalized paths
// arbitrary file name can be converted to Path via toPath function
export type Path = string & { __pathBrand: any };
/* @internal */
export type MatchingKeys<TRecord, TMatch, K extends keyof TRecord = keyof TRecord> = K extends (TRecord[K] extends TMatch ? K : never) ? K : never;
export interface TextRange {
pos: number;
end: number;
}
export interface ReadonlyTextRange {
readonly pos: number;
readonly end: number;
}
// token > SyntaxKind.Identifier => token is a keyword
// Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
export const enum SyntaxKind {
Unknown,
EndOfFileToken,
SingleLineCommentTrivia,
MultiLineCommentTrivia,
NewLineTrivia,
WhitespaceTrivia,
// We detect and preserve #! on the first line
ShebangTrivia,
// We detect and provide better error recovery when we encounter a git merge marker. This
// allows us to edit files with git-conflict markers in them in a much more pleasant manner.
ConflictMarkerTrivia,
// Literals
NumericLiteral,
BigIntLiteral,
StringLiteral,
JsxText,
JsxTextAllWhiteSpaces,
RegularExpressionLiteral,
NoSubstitutionTemplateLiteral,
// Pseudo-literals
TemplateHead,
TemplateMiddle,
TemplateTail,
// Punctuation
OpenBraceToken,
CloseBraceToken,
OpenParenToken,
CloseParenToken,
OpenBracketToken,
CloseBracketToken,
DotToken,
DotDotDotToken,
SemicolonToken,
CommaToken,
QuestionDotToken,
LessThanToken,
LessThanSlashToken,
GreaterThanToken,
LessThanEqualsToken,
GreaterThanEqualsToken,
EqualsEqualsToken,
ExclamationEqualsToken,
EqualsEqualsEqualsToken,
ExclamationEqualsEqualsToken,
EqualsGreaterThanToken,
PlusToken,
MinusToken,
AsteriskToken,
AsteriskAsteriskToken,
SlashToken,
PercentToken,
PlusPlusToken,
MinusMinusToken,
LessThanLessThanToken,
GreaterThanGreaterThanToken,
GreaterThanGreaterThanGreaterThanToken,
AmpersandToken,
BarToken,
CaretToken,
ExclamationToken,
TildeToken,
AmpersandAmpersandToken,
BarBarToken,
QuestionToken,
ColonToken,
AtToken,
QuestionQuestionToken,
/** Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. */
BacktickToken,
// Assignments
EqualsToken,
PlusEqualsToken,
MinusEqualsToken,
AsteriskEqualsToken,
AsteriskAsteriskEqualsToken,
SlashEqualsToken,
PercentEqualsToken,
LessThanLessThanEqualsToken,
GreaterThanGreaterThanEqualsToken,
GreaterThanGreaterThanGreaterThanEqualsToken,
AmpersandEqualsToken,
BarEqualsToken,
BarBarEqualsToken,
AmpersandAmpersandEqualsToken,
QuestionQuestionEqualsToken,
CaretEqualsToken,
// Identifiers and PrivateIdentifiers
Identifier,
PrivateIdentifier,
// Reserved words
BreakKeyword,
CaseKeyword,
CatchKeyword,
ClassKeyword,
ConstKeyword,
ContinueKeyword,
DebuggerKeyword,
DefaultKeyword,
DeleteKeyword,
DoKeyword,
ElseKeyword,
EnumKeyword,
ExportKeyword,
ExtendsKeyword,
FalseKeyword,
FinallyKeyword,
ForKeyword,
FunctionKeyword,
IfKeyword,
ImportKeyword,
InKeyword,
InstanceOfKeyword,
NewKeyword,
NullKeyword,
ReturnKeyword,
SuperKeyword,
SwitchKeyword,
ThisKeyword,
ThrowKeyword,
TrueKeyword,
TryKeyword,
TypeOfKeyword,
VarKeyword,
VoidKeyword,
WhileKeyword,
WithKeyword,
// Strict mode reserved words
ImplementsKeyword,
InterfaceKeyword,
LetKeyword,
PackageKeyword,
PrivateKeyword,
ProtectedKeyword,
PublicKeyword,
StaticKeyword,
YieldKeyword,
// Contextual keywords
AbstractKeyword,
AsKeyword,
AssertsKeyword,
AnyKeyword,
AsyncKeyword,
AwaitKeyword,
BooleanKeyword,
ConstructorKeyword,
DeclareKeyword,
GetKeyword,
InferKeyword,
IntrinsicKeyword,
IsKeyword,
KeyOfKeyword,
ModuleKeyword,
NamespaceKeyword,
NeverKeyword,
ReadonlyKeyword,
RequireKeyword,
NumberKeyword,
ObjectKeyword,
SetKeyword,
StringKeyword,
SymbolKeyword,
TypeKeyword,
UndefinedKeyword,
UniqueKeyword,
UnknownKeyword,
FromKeyword,
GlobalKeyword,
BigIntKeyword,
OverrideKeyword,
OfKeyword, // LastKeyword and LastToken and LastContextualKeyword
// Parse tree nodes
// Names
QualifiedName,
ComputedPropertyName,
// Signature elements
TypeParameter,
Parameter,
Decorator,
// TypeMember
PropertySignature,
PropertyDeclaration,
MethodSignature,
MethodDeclaration,
Constructor,
GetAccessor,
SetAccessor,
CallSignature,
ConstructSignature,
IndexSignature,
// Type
TypePredicate,
TypeReference,
FunctionType,
ConstructorType,
TypeQuery,
TypeLiteral,
ArrayType,
TupleType,
OptionalType,
RestType,
UnionType,
IntersectionType,
ConditionalType,
InferType,
ParenthesizedType,
ThisType,
TypeOperator,
IndexedAccessType,
MappedType,
LiteralType,
NamedTupleMember,
TemplateLiteralType,
TemplateLiteralTypeSpan,
ImportType,
// Binding patterns
ObjectBindingPattern,
ArrayBindingPattern,
BindingElement,
// Expression
ArrayLiteralExpression,
ObjectLiteralExpression,
PropertyAccessExpression,
ElementAccessExpression,
CallExpression,
NewExpression,
TaggedTemplateExpression,
TypeAssertionExpression,
ParenthesizedExpression,
FunctionExpression,
ArrowFunction,
DeleteExpression,
TypeOfExpression,
VoidExpression,
AwaitExpression,
PrefixUnaryExpression,
PostfixUnaryExpression,
BinaryExpression,
ConditionalExpression,
TemplateExpression,
YieldExpression,
SpreadElement,
ClassExpression,
OmittedExpression,
ExpressionWithTypeArguments,
AsExpression,
NonNullExpression,
MetaProperty,
SyntheticExpression,
// Misc
TemplateSpan,
SemicolonClassElement,
// Element
Block,
EmptyStatement,
VariableStatement,
ExpressionStatement,
IfStatement,
DoStatement,
WhileStatement,
ForStatement,
ForInStatement,
ForOfStatement,
ContinueStatement,
BreakStatement,
ReturnStatement,
WithStatement,
SwitchStatement,
LabeledStatement,
ThrowStatement,
TryStatement,
DebuggerStatement,
VariableDeclaration,
VariableDeclarationList,
FunctionDeclaration,
ClassDeclaration,
InterfaceDeclaration,
TypeAliasDeclaration,
EnumDeclaration,
ModuleDeclaration,
ModuleBlock,
CaseBlock,
NamespaceExportDeclaration,
ImportEqualsDeclaration,
ImportDeclaration,
ImportClause,
NamespaceImport,
NamedImports,
ImportSpecifier,
ExportAssignment,
ExportDeclaration,
NamedExports,
NamespaceExport,
ExportSpecifier,
MissingDeclaration,
// Module references
ExternalModuleReference,
// JSX
JsxElement,
JsxSelfClosingElement,
JsxOpeningElement,
JsxClosingElement,
JsxFragment,
JsxOpeningFragment,
JsxClosingFragment,
JsxAttribute,
JsxAttributes,
JsxSpreadAttribute,
JsxExpression,
// Clauses
CaseClause,
DefaultClause,
HeritageClause,
CatchClause,
// Property assignments
PropertyAssignment,
ShorthandPropertyAssignment,
SpreadAssignment,
// Enum
EnumMember,
// Unparsed
UnparsedPrologue,
UnparsedPrepend,
UnparsedText,
UnparsedInternalText,
UnparsedSyntheticReference,
// Top-level nodes
SourceFile,
Bundle,
UnparsedSource,
InputFiles,
// JSDoc nodes
JSDocTypeExpression,
JSDocNameReference,
JSDocAllType, // The * type
JSDocUnknownType, // The ? type
JSDocNullableType,
JSDocNonNullableType,
JSDocOptionalType,
JSDocFunctionType,
JSDocVariadicType,
JSDocNamepathType, // https://jsdoc.app/about-namepaths.html
JSDocComment,
JSDocText,
JSDocTypeLiteral,
JSDocSignature,
JSDocLink,
JSDocTag,
JSDocAugmentsTag,
JSDocImplementsTag,
JSDocAuthorTag,
JSDocDeprecatedTag,
JSDocClassTag,
JSDocPublicTag,
JSDocPrivateTag,
JSDocProtectedTag,
JSDocReadonlyTag,
JSDocOverrideTag,
JSDocCallbackTag,
JSDocEnumTag,
JSDocParameterTag,
JSDocReturnTag,
JSDocThisTag,
JSDocTypeTag,
JSDocTemplateTag,
JSDocTypedefTag,
JSDocSeeTag,
JSDocPropertyTag,
// Synthesized list
SyntaxList,
// Transformation nodes
NotEmittedStatement,
PartiallyEmittedExpression,
CommaListExpression,
MergeDeclarationMarker,
EndOfDeclarationMarker,
SyntheticReferenceExpression,
// Enum value count
Count,
// Markers
FirstAssignment = EqualsToken,
LastAssignment = CaretEqualsToken,
FirstCompoundAssignment = PlusEqualsToken,
LastCompoundAssignment = CaretEqualsToken,
FirstReservedWord = BreakKeyword,
LastReservedWord = WithKeyword,
FirstKeyword = BreakKeyword,
LastKeyword = OfKeyword,
FirstFutureReservedWord = ImplementsKeyword,
LastFutureReservedWord = YieldKeyword,
FirstTypeNode = TypePredicate,
LastTypeNode = ImportType,
FirstPunctuation = OpenBraceToken,
LastPunctuation = CaretEqualsToken,
FirstToken = Unknown,
LastToken = LastKeyword,
FirstTriviaToken = SingleLineCommentTrivia,
LastTriviaToken = ConflictMarkerTrivia,
FirstLiteralToken = NumericLiteral,
LastLiteralToken = NoSubstitutionTemplateLiteral,
FirstTemplateToken = NoSubstitutionTemplateLiteral,
LastTemplateToken = TemplateTail,
FirstBinaryOperator = LessThanToken,
LastBinaryOperator = CaretEqualsToken,
FirstStatement = VariableStatement,
LastStatement = DebuggerStatement,
FirstNode = QualifiedName,
FirstJSDocNode = JSDocTypeExpression,
LastJSDocNode = JSDocPropertyTag,
FirstJSDocTagNode = JSDocTag,
LastJSDocTagNode = JSDocPropertyTag,
/* @internal */ FirstContextualKeyword = AbstractKeyword,
/* @internal */ LastContextualKeyword = OfKeyword,
}
export type TriviaSyntaxKind =
| SyntaxKind.SingleLineCommentTrivia
| SyntaxKind.MultiLineCommentTrivia
| SyntaxKind.NewLineTrivia
| SyntaxKind.WhitespaceTrivia
| SyntaxKind.ShebangTrivia
| SyntaxKind.ConflictMarkerTrivia
;
export type LiteralSyntaxKind =
| SyntaxKind.NumericLiteral
| SyntaxKind.BigIntLiteral
| SyntaxKind.StringLiteral
| SyntaxKind.JsxText
| SyntaxKind.JsxTextAllWhiteSpaces
| SyntaxKind.RegularExpressionLiteral
| SyntaxKind.NoSubstitutionTemplateLiteral
;
export type PseudoLiteralSyntaxKind =
| SyntaxKind.TemplateHead
| SyntaxKind.TemplateMiddle
| SyntaxKind.TemplateTail
;
export type PunctuationSyntaxKind =
| SyntaxKind.OpenBraceToken
| SyntaxKind.CloseBraceToken
| SyntaxKind.OpenParenToken
| SyntaxKind.CloseParenToken
| SyntaxKind.OpenBracketToken
| SyntaxKind.CloseBracketToken
| SyntaxKind.DotToken
| SyntaxKind.DotDotDotToken
| SyntaxKind.SemicolonToken
| SyntaxKind.CommaToken
| SyntaxKind.QuestionDotToken
| SyntaxKind.LessThanToken
| SyntaxKind.LessThanSlashToken
| SyntaxKind.GreaterThanToken
| SyntaxKind.LessThanEqualsToken
| SyntaxKind.GreaterThanEqualsToken
| SyntaxKind.EqualsEqualsToken
| SyntaxKind.ExclamationEqualsToken
| SyntaxKind.EqualsEqualsEqualsToken
| SyntaxKind.ExclamationEqualsEqualsToken
| SyntaxKind.EqualsGreaterThanToken
| SyntaxKind.PlusToken
| SyntaxKind.MinusToken
| SyntaxKind.AsteriskToken
| SyntaxKind.AsteriskAsteriskToken
| SyntaxKind.SlashToken
| SyntaxKind.PercentToken
| SyntaxKind.PlusPlusToken
| SyntaxKind.MinusMinusToken
| SyntaxKind.LessThanLessThanToken
| SyntaxKind.GreaterThanGreaterThanToken
| SyntaxKind.GreaterThanGreaterThanGreaterThanToken
| SyntaxKind.AmpersandToken
| SyntaxKind.BarToken
| SyntaxKind.CaretToken
| SyntaxKind.ExclamationToken
| SyntaxKind.TildeToken
| SyntaxKind.AmpersandAmpersandToken
| SyntaxKind.BarBarToken
| SyntaxKind.QuestionQuestionToken
| SyntaxKind.QuestionToken
| SyntaxKind.ColonToken
| SyntaxKind.AtToken
| SyntaxKind.BacktickToken
| SyntaxKind.EqualsToken
| SyntaxKind.PlusEqualsToken
| SyntaxKind.MinusEqualsToken
| SyntaxKind.AsteriskEqualsToken
| SyntaxKind.AsteriskAsteriskEqualsToken
| SyntaxKind.SlashEqualsToken
| SyntaxKind.PercentEqualsToken
| SyntaxKind.LessThanLessThanEqualsToken
| SyntaxKind.GreaterThanGreaterThanEqualsToken
| SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken
| SyntaxKind.AmpersandEqualsToken
| SyntaxKind.BarEqualsToken
| SyntaxKind.CaretEqualsToken
;
export type KeywordSyntaxKind =
| SyntaxKind.AbstractKeyword
| SyntaxKind.AnyKeyword
| SyntaxKind.AsKeyword
| SyntaxKind.AssertsKeyword
| SyntaxKind.AsyncKeyword
| SyntaxKind.AwaitKeyword
| SyntaxKind.BigIntKeyword
| SyntaxKind.BooleanKeyword
| SyntaxKind.BreakKeyword
| SyntaxKind.CaseKeyword
| SyntaxKind.CatchKeyword
| SyntaxKind.ClassKeyword
| SyntaxKind.ConstKeyword
| SyntaxKind.ConstructorKeyword
| SyntaxKind.ContinueKeyword
| SyntaxKind.DebuggerKeyword
| SyntaxKind.DeclareKeyword
| SyntaxKind.DefaultKeyword
| SyntaxKind.DeleteKeyword
| SyntaxKind.DoKeyword
| SyntaxKind.ElseKeyword
| SyntaxKind.EnumKeyword
| SyntaxKind.ExportKeyword
| SyntaxKind.ExtendsKeyword
| SyntaxKind.FalseKeyword
| SyntaxKind.FinallyKeyword
| SyntaxKind.ForKeyword
| SyntaxKind.FromKeyword
| SyntaxKind.FunctionKeyword
| SyntaxKind.GetKeyword
| SyntaxKind.GlobalKeyword
| SyntaxKind.IfKeyword
| SyntaxKind.ImplementsKeyword
| SyntaxKind.ImportKeyword
| SyntaxKind.InferKeyword
| SyntaxKind.InKeyword
| SyntaxKind.InstanceOfKeyword
| SyntaxKind.InterfaceKeyword
| SyntaxKind.IntrinsicKeyword
| SyntaxKind.IsKeyword
| SyntaxKind.KeyOfKeyword
| SyntaxKind.LetKeyword
| SyntaxKind.ModuleKeyword
| SyntaxKind.NamespaceKeyword
| SyntaxKind.NeverKeyword
| SyntaxKind.NewKeyword
| SyntaxKind.NullKeyword
| SyntaxKind.NumberKeyword
| SyntaxKind.ObjectKeyword
| SyntaxKind.OfKeyword
| SyntaxKind.PackageKeyword
| SyntaxKind.PrivateKeyword
| SyntaxKind.ProtectedKeyword
| SyntaxKind.PublicKeyword
| SyntaxKind.ReadonlyKeyword
| SyntaxKind.OverrideKeyword
| SyntaxKind.RequireKeyword
| SyntaxKind.ReturnKeyword
| SyntaxKind.SetKeyword
| SyntaxKind.StaticKeyword
| SyntaxKind.StringKeyword
| SyntaxKind.SuperKeyword
| SyntaxKind.SwitchKeyword
| SyntaxKind.SymbolKeyword
| SyntaxKind.ThisKeyword
| SyntaxKind.ThrowKeyword
| SyntaxKind.TrueKeyword
| SyntaxKind.TryKeyword
| SyntaxKind.TypeKeyword
| SyntaxKind.TypeOfKeyword
| SyntaxKind.UndefinedKeyword
| SyntaxKind.UniqueKeyword
| SyntaxKind.UnknownKeyword
| SyntaxKind.VarKeyword
| SyntaxKind.VoidKeyword
| SyntaxKind.WhileKeyword
| SyntaxKind.WithKeyword
| SyntaxKind.YieldKeyword
;
export type ModifierSyntaxKind =
| SyntaxKind.AbstractKeyword
| SyntaxKind.AsyncKeyword
| SyntaxKind.ConstKeyword
| SyntaxKind.DeclareKeyword
| SyntaxKind.DefaultKeyword
| SyntaxKind.ExportKeyword
| SyntaxKind.PrivateKeyword
| SyntaxKind.ProtectedKeyword
| SyntaxKind.PublicKeyword
| SyntaxKind.ReadonlyKeyword
| SyntaxKind.OverrideKeyword
| SyntaxKind.StaticKeyword
;
export type KeywordTypeSyntaxKind =
| SyntaxKind.AnyKeyword
| SyntaxKind.BigIntKeyword
| SyntaxKind.BooleanKeyword
| SyntaxKind.IntrinsicKeyword
| SyntaxKind.NeverKeyword
| SyntaxKind.NumberKeyword
| SyntaxKind.ObjectKeyword
| SyntaxKind.StringKeyword
| SyntaxKind.SymbolKeyword
| SyntaxKind.UndefinedKeyword
| SyntaxKind.UnknownKeyword
| SyntaxKind.VoidKeyword
;
/* @internal */
export type TypeNodeSyntaxKind =
| KeywordTypeSyntaxKind
| SyntaxKind.TypePredicate
| SyntaxKind.TypeReference
| SyntaxKind.FunctionType
| SyntaxKind.ConstructorType
| SyntaxKind.TypeQuery
| SyntaxKind.TypeLiteral
| SyntaxKind.ArrayType
| SyntaxKind.TupleType
| SyntaxKind.NamedTupleMember
| SyntaxKind.OptionalType
| SyntaxKind.RestType
| SyntaxKind.UnionType
| SyntaxKind.IntersectionType
| SyntaxKind.ConditionalType
| SyntaxKind.InferType
| SyntaxKind.ParenthesizedType
| SyntaxKind.ThisType
| SyntaxKind.TypeOperator
| SyntaxKind.IndexedAccessType
| SyntaxKind.MappedType
| SyntaxKind.LiteralType
| SyntaxKind.TemplateLiteralType
| SyntaxKind.TemplateLiteralTypeSpan
| SyntaxKind.ImportType
| SyntaxKind.ExpressionWithTypeArguments
| SyntaxKind.JSDocTypeExpression
| SyntaxKind.JSDocAllType
| SyntaxKind.JSDocUnknownType
| SyntaxKind.JSDocNonNullableType
| SyntaxKind.JSDocNullableType
| SyntaxKind.JSDocOptionalType
| SyntaxKind.JSDocFunctionType
| SyntaxKind.JSDocVariadicType
| SyntaxKind.JSDocNamepathType
| SyntaxKind.JSDocSignature
| SyntaxKind.JSDocTypeLiteral
;
export type TokenSyntaxKind =
| SyntaxKind.Unknown
| SyntaxKind.EndOfFileToken
| TriviaSyntaxKind
| LiteralSyntaxKind
| PseudoLiteralSyntaxKind
| PunctuationSyntaxKind
| SyntaxKind.Identifier
| KeywordSyntaxKind
;
export type JsxTokenSyntaxKind =
| SyntaxKind.LessThanSlashToken
| SyntaxKind.EndOfFileToken
| SyntaxKind.ConflictMarkerTrivia
| SyntaxKind.JsxText
| SyntaxKind.JsxTextAllWhiteSpaces
| SyntaxKind.OpenBraceToken
| SyntaxKind.LessThanToken
;
export type JSDocSyntaxKind =
| SyntaxKind.EndOfFileToken
| SyntaxKind.WhitespaceTrivia
| SyntaxKind.AtToken
| SyntaxKind.NewLineTrivia
| SyntaxKind.AsteriskToken
| SyntaxKind.OpenBraceToken
| SyntaxKind.CloseBraceToken
| SyntaxKind.LessThanToken
| SyntaxKind.GreaterThanToken
| SyntaxKind.OpenBracketToken
| SyntaxKind.CloseBracketToken
| SyntaxKind.EqualsToken
| SyntaxKind.CommaToken
| SyntaxKind.DotToken
| SyntaxKind.Identifier
| SyntaxKind.BacktickToken
| SyntaxKind.Unknown
| KeywordSyntaxKind
;
export const enum NodeFlags {
None = 0,
Let = 1 << 0, // Variable declaration
Const = 1 << 1, // Variable declaration
NestedNamespace = 1 << 2, // Namespace declaration
Synthesized = 1 << 3, // Node was synthesized during transformation
Namespace = 1 << 4, // Namespace declaration
OptionalChain = 1 << 5, // Chained MemberExpression rooted to a pseudo-OptionalExpression
ExportContext = 1 << 6, // Export context (initialized by binding)
ContainsThis = 1 << 7, // Interface contains references to "this"
HasImplicitReturn = 1 << 8, // If function implicitly returns on one of codepaths (initialized by binding)
HasExplicitReturn = 1 << 9, // If function has explicit reachable return on one of codepaths (initialized by binding)
GlobalAugmentation = 1 << 10, // Set if module declaration is an augmentation for the global scope
HasAsyncFunctions = 1 << 11, // If the file has async functions (initialized by binding)
DisallowInContext = 1 << 12, // If node was parsed in a context where 'in-expressions' are not allowed
YieldContext = 1 << 13, // If node was parsed in the 'yield' context created when parsing a generator
DecoratorContext = 1 << 14, // If node was parsed as part of a decorator
AwaitContext = 1 << 15, // If node was parsed in the 'await' context created when parsing an async function
ThisNodeHasError = 1 << 16, // If the parser encountered an error when parsing the code that created this node
JavaScriptFile = 1 << 17, // If node was parsed in a JavaScript
ThisNodeOrAnySubNodesHasError = 1 << 18, // If this node or any of its children had an error
HasAggregatedChildData = 1 << 19, // If we've computed data from children and cached it in this node
// These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid
// walking the tree if the flags are not set. However, these flags are just a approximation
// (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared.
// During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag.
// This means that the tree will always be traversed during module resolution, or when looking for external module indicators.
// However, the removal operation should not occur often and in the case of the
// removal, it is likely that users will add the import anyway.
// The advantage of this approach is its simplicity. For the case of batch compilation,
// we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used.
/* @internal */ PossiblyContainsDynamicImport = 1 << 20,
/* @internal */ PossiblyContainsImportMeta = 1 << 21,
JSDoc = 1 << 22, // If node was parsed inside jsdoc
/* @internal */ Ambient = 1 << 23, // If node was inside an ambient context -- a declaration file, or inside something with the `declare` modifier.
/* @internal */ InWithStatement = 1 << 24, // If any ancestor of node was the `statement` of a WithStatement (not the `expression`)
JsonFile = 1 << 25, // If node was parsed in a Json
/* @internal */ TypeCached = 1 << 26, // If a type was cached for node at any point
/* @internal */ Deprecated = 1 << 27, // If has '@deprecated' JSDoc tag
BlockScoped = Let | Const,
ReachabilityCheckFlags = HasImplicitReturn | HasExplicitReturn,
ReachabilityAndEmitFlags = ReachabilityCheckFlags | HasAsyncFunctions,
// Parsing context flags
ContextFlags = DisallowInContext | YieldContext | DecoratorContext | AwaitContext | JavaScriptFile | InWithStatement | Ambient,
// Exclude these flags when parsing a Type
TypeExcludesFlags = YieldContext | AwaitContext,
// Represents all flags that are potentially set once and
// never cleared on SourceFiles which get re-used in between incremental parses.
// See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`.
/* @internal */ PermanentlySetIncrementalFlags = PossiblyContainsDynamicImport | PossiblyContainsImportMeta,
}
export const enum ModifierFlags {
None = 0,
Export = 1 << 0, // Declarations
Ambient = 1 << 1, // Declarations
Public = 1 << 2, // Property/Method
Private = 1 << 3, // Property/Method
Protected = 1 << 4, // Property/Method
Static = 1 << 5, // Property/Method
Readonly = 1 << 6, // Property/Method
Abstract = 1 << 7, // Class/Method/ConstructSignature
Async = 1 << 8, // Property/Method/Function
Default = 1 << 9, // Function/Class (export default declaration)
Const = 1 << 11, // Const enum
HasComputedJSDocModifiers = 1 << 12, // Indicates the computed modifier flags include modifiers from JSDoc.
Deprecated = 1 << 13, // Deprecated tag.
Override = 1 << 14, // Override method.
HasComputedFlags = 1 << 29, // Modifier flags have been computed
AccessibilityModifier = Public | Private | Protected,
// Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
ParameterPropertyModifier = AccessibilityModifier | Readonly | Override,
NonPublicAccessibilityModifier = Private | Protected,
TypeScriptModifier = Ambient | Public | Private | Protected | Readonly | Abstract | Const | Override,
ExportDefault = Export | Default,
All = Export | Ambient | Public | Private | Protected | Static | Readonly | Abstract | Async | Default | Const | Deprecated | Override
}
export const enum JsxFlags {
None = 0,
/** An element from a named property of the JSX.IntrinsicElements interface */
IntrinsicNamedElement = 1 << 0,
/** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
IntrinsicIndexedElement = 1 << 1,
IntrinsicElement = IntrinsicNamedElement | IntrinsicIndexedElement,
}
/* @internal */
export const enum RelationComparisonResult {
Succeeded = 1 << 0, // Should be truthy
Failed = 1 << 1,
Reported = 1 << 2,
ReportsUnmeasurable = 1 << 3,
ReportsUnreliable = 1 << 4,
ReportsMask = ReportsUnmeasurable | ReportsUnreliable
}
/* @internal */
export type NodeId = number;
export interface Node extends ReadonlyTextRange {
readonly kind: SyntaxKind;
readonly flags: NodeFlags;
/* @internal */ modifierFlagsCache: ModifierFlags;
/* @internal */ readonly transformFlags: TransformFlags; // Flags for transforms
readonly decorators?: NodeArray<Decorator>; // Array of decorators (in document order)
readonly modifiers?: ModifiersArray; // Array of modifiers
/* @internal */ id?: NodeId; // Unique id (used to look up NodeLinks)
readonly parent: Node; // Parent node (initialized by binding)
/* @internal */ original?: Node; // The original node if this is an updated node.
/* @internal */ symbol: Symbol; // Symbol declared by node (initialized by binding)
/* @internal */ locals?: SymbolTable; // Locals associated with node (initialized by binding)
/* @internal */ nextContainer?: Node; // Next container in declaration order (initialized by binding)
/* @internal */ localSymbol?: Symbol; // Local symbol declared by node (initialized by binding only for exported nodes)
/* @internal */ flowNode?: FlowNode; // Associated FlowNode (initialized by binding)
/* @internal */ emitNode?: EmitNode; // Associated EmitNode (initialized by transforms)
/* @internal */ contextualType?: Type; // Used to temporarily assign a contextual type during overload resolution
/* @internal */ inferenceContext?: InferenceContext; // Inference context for contextual type
}
export interface JSDocContainer {
/* @internal */ jsDoc?: JSDoc[]; // JSDoc that directly precedes this node
/* @internal */ jsDocCache?: readonly JSDocTag[]; // Cache for getJSDocTags
}
export type HasJSDoc =
| ParameterDeclaration
| CallSignatureDeclaration
| ConstructSignatureDeclaration
| MethodSignature
| PropertySignature
| ArrowFunction
| ParenthesizedExpression
| SpreadAssignment
| ShorthandPropertyAssignment
| PropertyAssignment
| FunctionExpression
| EmptyStatement
| DebuggerStatement
| Block
| VariableStatement
| ExpressionStatement
| IfStatement
| DoStatement
| WhileStatement
| ForStatement
| ForInStatement
| ForOfStatement
| BreakStatement
| ContinueStatement
| ReturnStatement
| WithStatement
| SwitchStatement
| LabeledStatement
| ThrowStatement
| TryStatement
| FunctionDeclaration
| ConstructorDeclaration
| MethodDeclaration
| VariableDeclaration
| PropertyDeclaration
| AccessorDeclaration
| ClassLikeDeclaration
| InterfaceDeclaration
| TypeAliasDeclaration
| EnumMember
| EnumDeclaration
| ModuleDeclaration
| ImportEqualsDeclaration
| ImportDeclaration
| NamespaceExportDeclaration
| ExportAssignment
| IndexSignatureDeclaration
| FunctionTypeNode
| ConstructorTypeNode
| JSDocFunctionType
| ExportDeclaration
| NamedTupleMember
| EndOfFileToken
;
export type HasType =
| SignatureDeclaration
| VariableDeclaration
| ParameterDeclaration
| PropertySignature
| PropertyDeclaration
| TypePredicateNode
| ParenthesizedTypeNode
| TypeOperatorNode
| MappedTypeNode
| AssertionExpression
| TypeAliasDeclaration
| JSDocTypeExpression
| JSDocNonNullableType
| JSDocNullableType
| JSDocOptionalType
| JSDocVariadicType
;
export type HasTypeArguments =
| CallExpression
| NewExpression
| TaggedTemplateExpression
| JsxOpeningElement
| JsxSelfClosingElement;
export type HasInitializer =
| HasExpressionInitializer
| ForStatement
| ForInStatement
| ForOfStatement
| JsxAttribute
;
export type HasExpressionInitializer =
| VariableDeclaration
| ParameterDeclaration
| BindingElement
| PropertySignature
| PropertyDeclaration
| PropertyAssignment
| EnumMember
;
// NOTE: Changing this list requires changes to `canHaveModifiers` in factory/utilities.ts and `updateModifiers` in factory/nodeFactory.ts
/* @internal */
export type HasModifiers =
| ParameterDeclaration
| PropertySignature
| PropertyDeclaration
| MethodSignature
| MethodDeclaration
| ConstructorDeclaration
| GetAccessorDeclaration
| SetAccessorDeclaration
| IndexSignatureDeclaration
| FunctionExpression
| ArrowFunction
| ClassExpression
| VariableStatement
| FunctionDeclaration
| ClassDeclaration
| InterfaceDeclaration
| TypeAliasDeclaration
| EnumDeclaration
| ModuleDeclaration
| ImportEqualsDeclaration
| ImportDeclaration
| ExportAssignment
| ExportDeclaration
;
/* @internal */
export type MutableNodeArray<T extends Node> = NodeArray<T> & T[];
export interface NodeArray<T extends Node> extends ReadonlyArray<T>, ReadonlyTextRange {
hasTrailingComma?: boolean;
/* @internal */ transformFlags: TransformFlags; // Flags for transforms, possibly undefined
}
// TODO(rbuckton): Constraint 'TKind' to 'TokenSyntaxKind'
export interface Token<TKind extends SyntaxKind> extends Node {
readonly kind: TKind;
}
export type EndOfFileToken = Token<SyntaxKind.EndOfFileToken> & JSDocContainer;
// Punctuation
export interface PunctuationToken<TKind extends PunctuationSyntaxKind> extends Token<TKind> {
}
export type DotToken = PunctuationToken<SyntaxKind.DotToken>;
export type DotDotDotToken = PunctuationToken<SyntaxKind.DotDotDotToken>;
export type QuestionToken = PunctuationToken<SyntaxKind.QuestionToken>;
export type ExclamationToken = PunctuationToken<SyntaxKind.ExclamationToken>;
export type ColonToken = PunctuationToken<SyntaxKind.ColonToken>;
export type EqualsToken = PunctuationToken<SyntaxKind.EqualsToken>;
export type AsteriskToken = PunctuationToken<SyntaxKind.AsteriskToken>;
export type EqualsGreaterThanToken = PunctuationToken<SyntaxKind.EqualsGreaterThanToken>;
export type PlusToken = PunctuationToken<SyntaxKind.PlusToken>;
export type MinusToken = PunctuationToken<SyntaxKind.MinusToken>;
export type QuestionDotToken = PunctuationToken<SyntaxKind.QuestionDotToken>;
// Keywords
export interface KeywordToken<TKind extends KeywordSyntaxKind> extends Token<TKind> {
}
export type AssertsKeyword = KeywordToken<SyntaxKind.AssertsKeyword>;
export type AwaitKeyword = KeywordToken<SyntaxKind.AwaitKeyword>;
/** @deprecated Use `AwaitKeyword` instead. */
export type AwaitKeywordToken = AwaitKeyword;
/** @deprecated Use `AssertsKeyword` instead. */
export type AssertsToken = AssertsKeyword;
export interface ModifierToken<TKind extends ModifierSyntaxKind> extends KeywordToken<TKind> {
}
export type AbstractKeyword = ModifierToken<SyntaxKind.AbstractKeyword>;
export type AsyncKeyword = ModifierToken<SyntaxKind.AsyncKeyword>;
export type ConstKeyword = ModifierToken<SyntaxKind.ConstKeyword>;
export type DeclareKeyword = ModifierToken<SyntaxKind.DeclareKeyword>;
export type DefaultKeyword = ModifierToken<SyntaxKind.DefaultKeyword>;
export type ExportKeyword = ModifierToken<SyntaxKind.ExportKeyword>;
export type PrivateKeyword = ModifierToken<SyntaxKind.PrivateKeyword>;
export type ProtectedKeyword = ModifierToken<SyntaxKind.ProtectedKeyword>;
export type PublicKeyword = ModifierToken<SyntaxKind.PublicKeyword>;
export type ReadonlyKeyword = ModifierToken<SyntaxKind.ReadonlyKeyword>;
export type OverrideKeyword = ModifierToken<SyntaxKind.OverrideKeyword>;
export type StaticKeyword = ModifierToken<SyntaxKind.StaticKeyword>;
/** @deprecated Use `ReadonlyKeyword` instead. */
export type ReadonlyToken = ReadonlyKeyword;
export type Modifier =
| AbstractKeyword
| AsyncKeyword
| ConstKeyword
| DeclareKeyword
| DefaultKeyword
| ExportKeyword
| PrivateKeyword
| ProtectedKeyword
| PublicKeyword
| OverrideKeyword
| ReadonlyKeyword
| StaticKeyword
;
export type AccessibilityModifier =
| PublicKeyword
| PrivateKeyword
| ProtectedKeyword
;
export type ParameterPropertyModifier =
| AccessibilityModifier
| ReadonlyKeyword
;
export type ClassMemberModifier =
| AccessibilityModifier
| ReadonlyKeyword
| StaticKeyword
;
export type ModifiersArray = NodeArray<Modifier>;
export const enum GeneratedIdentifierFlags {
// Kinds
None = 0, // Not automatically generated.
/*@internal*/ Auto = 1, // Automatically generated identifier.
/*@internal*/ Loop = 2, // Automatically generated identifier with a preference for '_i'.
/*@internal*/ Unique = 3, // Unique name based on the 'text' property.
/*@internal*/ Node = 4, // Unique name based on the node in the 'original' property.
/*@internal*/ KindMask = 7, // Mask to extract the kind of identifier from its flags.
// Flags
ReservedInNestedScopes = 1 << 3, // Reserve the generated name in nested scopes
Optimistic = 1 << 4, // First instance won't use '_#' if there's no conflict
FileLevel = 1 << 5, // Use only the file identifiers list and not generated names to search for conflicts
AllowNameSubstitution = 1 << 6, // Used by `module.ts` to indicate generated nodes which can have substitutions performed upon them (as they were generated by an earlier transform phase)
}
export interface Identifier extends PrimaryExpression, Declaration {
readonly kind: SyntaxKind.Identifier;
/**
* Prefer to use `id.unescapedText`. (Note: This is available only in services, not internally to the TypeScript compiler.)
* Text of identifier, but if the identifier begins with two underscores, this will begin with three.
*/
readonly escapedText: __String;
readonly originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later
/*@internal*/ readonly autoGenerateFlags?: GeneratedIdentifierFlags; // Specifies whether to auto-generate the text for an identifier.
/*@internal*/ readonly autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name.
/*@internal*/ generatedImportReference?: ImportSpecifier; // Reference to the generated import specifier this identifier refers to
isInJSDocNamespace?: boolean; // if the node is a member in a JSDoc namespace
/*@internal*/ typeArguments?: NodeArray<TypeNode | TypeParameterDeclaration>; // Only defined on synthesized nodes. Though not syntactically valid, used in emitting diagnostics, quickinfo, and signature help.
/*@internal*/ jsdocDotPos?: number; // Identifier occurs in JSDoc-style generic: Id.<T>
}
// Transient identifier node (marked by id === -1)
export interface TransientIdentifier extends Identifier {
resolvedSymbol: Symbol;
}
/*@internal*/
export interface GeneratedIdentifier extends Identifier {
autoGenerateFlags: GeneratedIdentifierFlags;
}
export interface QualifiedName extends Node {
readonly kind: SyntaxKind.QualifiedName;
readonly left: EntityName;
readonly right: Identifier;
/*@internal*/ jsdocDotPos?: number; // QualifiedName occurs in JSDoc-style generic: Id1.Id2.<T>
}
export type EntityName = Identifier | QualifiedName;
export type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | PrivateIdentifier;
export type MemberName = Identifier | PrivateIdentifier;
export type DeclarationName =
| Identifier
| PrivateIdentifier
| StringLiteralLike
| NumericLiteral
| ComputedPropertyName
| ElementAccessExpression
| BindingPattern
| EntityNameExpression;
export interface Declaration extends Node {
_declarationBrand: any;
}
export interface NamedDeclaration extends Declaration {
readonly name?: DeclarationName;
}
/* @internal */
export interface DynamicNamedDeclaration extends NamedDeclaration {
readonly name: ComputedPropertyName;
}
/* @internal */
export interface DynamicNamedBinaryExpression extends BinaryExpression {
readonly left: ElementAccessExpression;
}
/* @internal */
// A declaration that supports late-binding (used in checker)
export interface LateBoundDeclaration extends DynamicNamedDeclaration {
readonly name: LateBoundName;
}
/* @internal */
export interface LateBoundBinaryExpressionDeclaration extends DynamicNamedBinaryExpression {
readonly left: LateBoundElementAccessExpression;
}
/* @internal */
export interface LateBoundElementAccessExpression extends ElementAccessExpression {
readonly argumentExpression: EntityNameExpression;
}
export interface DeclarationStatement extends NamedDeclaration, Statement {
readonly name?: Identifier | StringLiteral | NumericLiteral;
}
export interface ComputedPropertyName extends Node {
readonly kind: SyntaxKind.ComputedPropertyName;
readonly parent: Declaration;
readonly expression: Expression;
}
export interface PrivateIdentifier extends Node {
readonly kind: SyntaxKind.PrivateIdentifier;
// escaping not strictly necessary
// avoids gotchas in transforms and utils
readonly escapedText: __String;
}
/* @internal */
// A name that supports late-binding (used in checker)
export interface LateBoundName extends ComputedPropertyName {
readonly expression: EntityNameExpression;
}
export interface Decorator extends Node {
readonly kind: SyntaxKind.Decorator;
readonly parent: NamedDeclaration;
readonly expression: LeftHandSideExpression;
}
export interface TypeParameterDeclaration extends NamedDeclaration {
readonly kind: SyntaxKind.TypeParameter;
readonly parent: DeclarationWithTypeParameterChildren | InferTypeNode;
readonly name: Identifier;
/** Note: Consider calling `getEffectiveConstraintOfTypeParameter` */
readonly constraint?: TypeNode;
readonly default?: TypeNode;
// For error recovery purposes.
expression?: Expression;
}
export interface SignatureDeclarationBase extends NamedDeclaration, JSDocContainer {
readonly kind: SignatureDeclaration["kind"];
readonly name?: PropertyName;
readonly typeParameters?: NodeArray<TypeParameterDeclaration>;
readonly parameters: NodeArray<ParameterDeclaration>;
readonly type?: TypeNode;
/* @internal */ typeArguments?: NodeArray<TypeNode>; // Used for quick info, replaces typeParameters for instantiated signatures
}
export type SignatureDeclaration =
| CallSignatureDeclaration
| ConstructSignatureDeclaration
| MethodSignature
| IndexSignatureDeclaration
| FunctionTypeNode
| ConstructorTypeNode
| JSDocFunctionType
| FunctionDeclaration
| MethodDeclaration
| ConstructorDeclaration
| AccessorDeclaration
| FunctionExpression
| ArrowFunction;
export interface CallSignatureDeclaration extends SignatureDeclarationBase, TypeElement {
readonly kind: SyntaxKind.CallSignature;
}
export interface ConstructSignatureDeclaration extends SignatureDeclarationBase, TypeElement {
readonly kind: SyntaxKind.ConstructSignature;
}
export type BindingName = Identifier | BindingPattern;
export interface VariableDeclaration extends NamedDeclaration, JSDocContainer {
readonly kind: SyntaxKind.VariableDeclaration;
readonly parent: VariableDeclarationList | CatchClause;
readonly name: BindingName; // Declared variable name
readonly exclamationToken?: ExclamationToken; // Optional definite assignment assertion
readonly type?: TypeNode; // Optional type annotation
readonly initializer?: Expression; // Optional initializer
}
/* @internal */
export type InitializedVariableDeclaration = VariableDeclaration & { readonly initializer: Expression };
export interface VariableDeclarationList extends Node {
readonly kind: SyntaxKind.VariableDeclarationList;
readonly parent: VariableStatement | ForStatement | ForOfStatement | ForInStatement;
readonly declarations: NodeArray<VariableDeclaration>;
}
export interface ParameterDeclaration extends NamedDeclaration, JSDocContainer {
readonly kind: SyntaxKind.Parameter;
readonly parent: SignatureDeclaration;
readonly dotDotDotToken?: DotDotDotToken; // Present on rest parameter
readonly name: BindingName; // Declared parameter name.
readonly questionToken?: QuestionToken; // Present on optional parameter
readonly type?: TypeNode; // Optional type annotation
readonly initializer?: Expression; // Optional initializer
}
export interface BindingElement extends NamedDeclaration {
readonly kind: SyntaxKind.BindingElement;
readonly parent: BindingPattern;
readonly propertyName?: PropertyName; // Binding property name (in object binding pattern)
readonly dotDotDotToken?: DotDotDotToken; // Present on rest element (in object binding pattern)
readonly name: BindingName; // Declared binding element name
readonly initializer?: Expression; // Optional initializer
}
/*@internal*/
export type BindingElementGrandparent = BindingElement["parent"]["parent"];
export interface PropertySignature extends TypeElement, JSDocContainer {
readonly kind: SyntaxKind.PropertySignature;
readonly name: PropertyName; // Declared property name
readonly questionToken?: QuestionToken; // Present on optional property
readonly type?: TypeNode; // Optional type annotation
initializer?: Expression; // Present for use with reporting a grammar error
}
export interface PropertyDeclaration extends ClassElement, JSDocContainer {
readonly kind: SyntaxKind.PropertyDeclaration;
readonly parent: ClassLikeDeclaration;
readonly name: PropertyName;
readonly questionToken?: QuestionToken; // Present for use with reporting a grammar error
readonly exclamationToken?: ExclamationToken;
readonly type?: TypeNode;
readonly initializer?: Expression; // Optional initializer
}
/*@internal*/
export interface PrivateIdentifierPropertyDeclaration extends PropertyDeclaration {
name: PrivateIdentifier;
}
/*@internal*/
export interface PrivateIdentifierMethodDeclaration extends MethodDeclaration {
name: PrivateIdentifier;
}
/*@internal*/
export interface PrivateIdentifierGetAccessorDeclaration extends GetAccessorDeclaration {
name: PrivateIdentifier;
}
/*@internal*/
export interface PrivateIdentifierSetAccessorDeclaration extends SetAccessorDeclaration {
name: PrivateIdentifier;
}
/*@internal*/
export type PrivateIdentifierAccessorDeclaration = PrivateIdentifierGetAccessorDeclaration | PrivateIdentifierSetAccessorDeclaration;
/*@internal*/
export type PrivateClassElementDeclaration =
| PrivateIdentifierPropertyDeclaration
| PrivateIdentifierMethodDeclaration
| PrivateIdentifierGetAccessorDeclaration
| PrivateIdentifierSetAccessorDeclaration;
/* @internal */
export type InitializedPropertyDeclaration = PropertyDeclaration & { readonly initializer: Expression };
export interface ObjectLiteralElement extends NamedDeclaration {
_objectLiteralBrand: any;
readonly name?: PropertyName;
}
/** Unlike ObjectLiteralElement, excludes JSXAttribute and JSXSpreadAttribute. */
export type ObjectLiteralElementLike
= PropertyAssignment
| ShorthandPropertyAssignment
| SpreadAssignment
| MethodDeclaration
| AccessorDeclaration
;
export interface PropertyAssignment extends ObjectLiteralElement, JSDocContainer {
readonly kind: SyntaxKind.PropertyAssignment;
readonly parent: ObjectLiteralExpression;
readonly name: PropertyName;
readonly questionToken?: QuestionToken; // Present for use with reporting a grammar error
readonly exclamationToken?: ExclamationToken; // Present for use with reporting a grammar error
readonly initializer: Expression;
}
export interface ShorthandPropertyAssignment extends ObjectLiteralElement, JSDocContainer {
readonly kind: SyntaxKind.ShorthandPropertyAssignment;
readonly parent: ObjectLiteralExpression;
readonly name: Identifier;
readonly questionToken?: QuestionToken;
readonly exclamationToken?: ExclamationToken;
// used when ObjectLiteralExpression is used in ObjectAssignmentPattern
// it is a grammar error to appear in actual object initializer:
readonly equalsToken?: EqualsToken;
readonly objectAssignmentInitializer?: Expression;
}
export interface SpreadAssignment extends ObjectLiteralElement, JSDocContainer {
readonly kind: SyntaxKind.SpreadAssignment;
readonly parent: ObjectLiteralExpression;
readonly expression: Expression;
}
export type VariableLikeDeclaration =
| VariableDeclaration
| ParameterDeclaration
| BindingElement
| PropertyDeclaration
| PropertyAssignment
| PropertySignature
| JsxAttribute
| ShorthandPropertyAssignment
| EnumMember
| JSDocPropertyTag
| JSDocParameterTag;
export interface PropertyLikeDeclaration extends NamedDeclaration {
readonly name: PropertyName;
}
export interface ObjectBindingPattern extends Node {
readonly kind: SyntaxKind.ObjectBindingPattern;
readonly parent: VariableDeclaration | ParameterDeclaration | BindingElement;
readonly elements: NodeArray<BindingElement>;
}
export interface ArrayBindingPattern extends Node {
readonly kind: SyntaxKind.ArrayBindingPattern;
readonly parent: VariableDeclaration | ParameterDeclaration | BindingElement;
readonly elements: NodeArray<ArrayBindingElement>;
}
export type BindingPattern = ObjectBindingPattern | ArrayBindingPattern;
export type ArrayBindingElement = BindingElement | OmittedExpression;
/**
* Several node kinds share function-like features such as a signature,
* a name, and a body. These nodes should extend FunctionLikeDeclarationBase.
* Examples:
* - FunctionDeclaration
* - MethodDeclaration
* - AccessorDeclaration
*/
export interface FunctionLikeDeclarationBase extends SignatureDeclarationBase {
_functionLikeDeclarationBrand: any;
readonly asteriskToken?: AsteriskToken;
readonly questionToken?: QuestionToken;
readonly exclamationToken?: ExclamationToken;
readonly body?: Block | Expression;
/* @internal */ endFlowNode?: FlowNode;
/* @internal */ returnFlowNode?: FlowNode;
}
export type FunctionLikeDeclaration =
| FunctionDeclaration
| MethodDeclaration
| GetAccessorDeclaration
| SetAccessorDeclaration
| ConstructorDeclaration
| FunctionExpression
| ArrowFunction;
/** @deprecated Use SignatureDeclaration */
export type FunctionLike = SignatureDeclaration;
export interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement {
readonly kind: SyntaxKind.FunctionDeclaration;
readonly name?: Identifier;
readonly body?: FunctionBody;
}
export interface MethodSignature extends SignatureDeclarationBase, TypeElement {
readonly kind: SyntaxKind.MethodSignature;
readonly parent: ObjectTypeDeclaration;
readonly name: PropertyName;
}
// Note that a MethodDeclaration is considered both a ClassElement and an ObjectLiteralElement.
// Both the grammars for ClassDeclaration and ObjectLiteralExpression allow for MethodDeclarations
// as child elements, and so a MethodDeclaration satisfies both interfaces. This avoids the
// alternative where we would need separate kinds/types for ClassMethodDeclaration and
// ObjectLiteralMethodDeclaration, which would look identical.
//
// Because of this, it may be necessary to determine what sort of MethodDeclaration you have
// at later stages of the compiler pipeline. In that case, you can either check the parent kind
// of the method, or use helpers like isObjectLiteralMethodDeclaration
export interface MethodDeclaration extends FunctionLikeDeclarationBase, ClassElement, ObjectLiteralElement, JSDocContainer {
readonly kind: SyntaxKind.MethodDeclaration;
readonly parent: ClassLikeDeclaration | ObjectLiteralExpression;
readonly name: PropertyName;
readonly body?: FunctionBody;
/* @internal*/ exclamationToken?: ExclamationToken; // Present for use with reporting a grammar error
}
export interface ConstructorDeclaration extends FunctionLikeDeclarationBase, ClassElement, JSDocContainer {
readonly kind: SyntaxKind.Constructor;
readonly parent: ClassLikeDeclaration;
readonly body?: FunctionBody;
/* @internal */ typeParameters?: NodeArray<TypeParameterDeclaration>; // Present for use with reporting a grammar error
/* @internal */ type?: TypeNode; // Present for use with reporting a grammar error
}
/** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */
export interface SemicolonClassElement extends ClassElement {
readonly kind: SyntaxKind.SemicolonClassElement;
readonly parent: ClassLikeDeclaration;
}
// See the comment on MethodDeclaration for the intuition behind GetAccessorDeclaration being a
// ClassElement and an ObjectLiteralElement.
export interface GetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer {
readonly kind: SyntaxKind.GetAccessor;
readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration;
readonly name: PropertyName;
readonly body?: FunctionBody;
/* @internal */ typeParameters?: NodeArray<TypeParameterDeclaration>; // Present for use with reporting a grammar error
}
// See the comment on MethodDeclaration for the intuition behind SetAccessorDeclaration being a
// ClassElement and an ObjectLiteralElement.
export interface SetAccessorDeclaration extends FunctionLikeDeclarationBase, ClassElement, TypeElement, ObjectLiteralElement, JSDocContainer {
readonly kind: SyntaxKind.SetAccessor;
readonly parent: ClassLikeDeclaration | ObjectLiteralExpression | TypeLiteralNode | InterfaceDeclaration;
readonly name: PropertyName;
readonly body?: FunctionBody;
/* @internal */ typeParameters?: NodeArray<TypeParameterDeclaration>; // Present for use with reporting a grammar error
/* @internal */ type?: TypeNode; // Present for use with reporting a grammar error
}
export type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration;
export interface IndexSignatureDeclaration extends SignatureDeclarationBase, ClassElement, TypeElement {
readonly kind: SyntaxKind.IndexSignature;
readonly parent: ObjectTypeDeclaration;
readonly type: TypeNode;
}
export interface TypeNode extends Node {
_typeNodeBrand: any;
}
/* @internal */
export interface TypeNode extends Node {
readonly kind: TypeNodeSyntaxKind;
}
export interface KeywordTypeNode<TKind extends KeywordTypeSyntaxKind = KeywordTypeSyntaxKind> extends KeywordToken<TKind>, TypeNode {
readonly kind: TKind;
}
export interface ImportTypeNode extends NodeWithTypeArguments {
readonly kind: SyntaxKind.ImportType;
readonly isTypeOf: boolean;
readonly argument: TypeNode;
readonly qualifier?: EntityName;
}
/* @internal */
export type LiteralImportTypeNode = ImportTypeNode & { readonly argument: LiteralTypeNode & { readonly literal: StringLiteral } };
export interface ThisTypeNode extends TypeNode {
readonly kind: SyntaxKind.ThisType;
}
export type FunctionOrConstructorTypeNode = FunctionTypeNode | ConstructorTypeNode;
export interface FunctionOrConstructorTypeNodeBase extends TypeNode, SignatureDeclarationBase {
readonly kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType;
readonly type: TypeNode;
}
export interface FunctionTypeNode extends FunctionOrConstructorTypeNodeBase {
readonly kind: SyntaxKind.FunctionType;
}
export interface ConstructorTypeNode extends FunctionOrConstructorTypeNodeBase {
readonly kind: SyntaxKind.ConstructorType;
}
export interface NodeWithTypeArguments extends TypeNode {
readonly typeArguments?: NodeArray<TypeNode>;
}
export type TypeReferenceType = TypeReferenceNode | ExpressionWithTypeArguments;
export interface TypeReferenceNode extends NodeWithTypeArguments {
readonly kind: SyntaxKind.TypeReference;
readonly typeName: EntityName;
}
export interface TypePredicateNode extends TypeNode {
readonly kind: SyntaxKind.TypePredicate;
readonly parent: SignatureDeclaration | JSDocTypeExpression;
readonly assertsModifier?: AssertsToken;
readonly parameterName: Identifier | ThisTypeNode;
readonly type?: TypeNode;
}
export interface TypeQueryNode extends TypeNode {
readonly kind: SyntaxKind.TypeQuery;
readonly exprName: EntityName;
}
// A TypeLiteral is the declaration node for an anonymous symbol.
export interface TypeLiteralNode extends TypeNode, Declaration {
readonly kind: SyntaxKind.TypeLiteral;
readonly members: NodeArray<TypeElement>;
}
export interface ArrayTypeNode extends TypeNode {
readonly kind: SyntaxKind.ArrayType;
readonly elementType: TypeNode;
}
export interface TupleTypeNode extends TypeNode {
readonly kind: SyntaxKind.TupleType;
readonly elements: NodeArray<TypeNode | NamedTupleMember>;
}
export interface NamedTupleMember extends TypeNode, JSDocContainer, Declaration {
readonly kind: SyntaxKind.NamedTupleMember;
readonly dotDotDotToken?: Token<SyntaxKind.DotDotDotToken>;
readonly name: Identifier;
readonly questionToken?: Token<SyntaxKind.QuestionToken>;
readonly type: TypeNode;
}
export interface OptionalTypeNode extends TypeNode {
readonly kind: SyntaxKind.OptionalType;
readonly type: TypeNode;
}
export interface RestTypeNode extends TypeNode {
readonly kind: SyntaxKind.RestType;
readonly type: TypeNode;
}
export type UnionOrIntersectionTypeNode = UnionTypeNode | IntersectionTypeNode;
export interface UnionTypeNode extends TypeNode {
readonly kind: SyntaxKind.UnionType;
readonly types: NodeArray<TypeNode>;
}
export interface IntersectionTypeNode extends TypeNode {
readonly kind: SyntaxKind.IntersectionType;
readonly types: NodeArray<TypeNode>;
}
export interface ConditionalTypeNode extends TypeNode {
readonly kind: SyntaxKind.ConditionalType;
readonly checkType: TypeNode;
readonly extendsType: TypeNode;
readonly trueType: TypeNode;
readonly falseType: TypeNode;
}
export interface InferTypeNode extends TypeNode {
readonly kind: SyntaxKind.InferType;
readonly typeParameter: TypeParameterDeclaration;
}
export interface ParenthesizedTypeNode extends TypeNode {
readonly kind: SyntaxKind.ParenthesizedType;
readonly type: TypeNode;
}
export interface TypeOperatorNode extends TypeNode {
readonly kind: SyntaxKind.TypeOperator;
readonly operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword;
readonly type: TypeNode;
}
/* @internal */
export interface UniqueTypeOperatorNode extends TypeOperatorNode {
readonly operator: SyntaxKind.UniqueKeyword;
}
export interface IndexedAccessTypeNode extends TypeNode {
readonly kind: SyntaxKind.IndexedAccessType;
readonly objectType: TypeNode;
readonly indexType: TypeNode;
}
export interface MappedTypeNode extends TypeNode, Declaration {
readonly kind: SyntaxKind.MappedType;
readonly readonlyToken?: ReadonlyToken | PlusToken | MinusToken;
readonly typeParameter: TypeParameterDeclaration;
readonly nameType?: TypeNode;
readonly questionToken?: QuestionToken | PlusToken | MinusToken;
readonly type?: TypeNode;
}
export interface LiteralTypeNode extends TypeNode {
readonly kind: SyntaxKind.LiteralType;
readonly literal: NullLiteral | BooleanLiteral | LiteralExpression | PrefixUnaryExpression;
}
export interface StringLiteral extends LiteralExpression, Declaration {
readonly kind: SyntaxKind.StringLiteral;
/* @internal */ readonly textSourceNode?: Identifier | StringLiteralLike | NumericLiteral; // Allows a StringLiteral to get its text from another node (used by transforms).
/** Note: this is only set when synthesizing a node, not during parsing. */
/* @internal */ readonly singleQuote?: boolean;
}
export type StringLiteralLike = StringLiteral | NoSubstitutionTemplateLiteral;
export type PropertyNameLiteral = Identifier | StringLiteralLike | NumericLiteral;
export interface TemplateLiteralTypeNode extends TypeNode {
kind: SyntaxKind.TemplateLiteralType,
readonly head: TemplateHead;
readonly templateSpans: NodeArray<TemplateLiteralTypeSpan>;
}
export interface TemplateLiteralTypeSpan extends TypeNode {
readonly kind: SyntaxKind.TemplateLiteralTypeSpan,
readonly parent: TemplateLiteralTypeNode;
readonly type: TypeNode;
readonly literal: TemplateMiddle | TemplateTail;
}
// Note: 'brands' in our syntax nodes serve to give us a small amount of nominal typing.
// Consider 'Expression'. Without the brand, 'Expression' is actually no different
// (structurally) than 'Node'. Because of this you can pass any Node to a function that
// takes an Expression without any error. By using the 'brands' we ensure that the type
// checker actually thinks you have something of the right type. Note: the brands are
// never actually given values. At runtime they have zero cost.
export interface Expression extends Node {
_expressionBrand: any;
}
export interface OmittedExpression extends Expression {
readonly kind: SyntaxKind.OmittedExpression;
}
// Represents an expression that is elided as part of a transformation to emit comments on a
// not-emitted node. The 'expression' property of a PartiallyEmittedExpression should be emitted.
export interface PartiallyEmittedExpression extends LeftHandSideExpression {
readonly kind: SyntaxKind.PartiallyEmittedExpression;
readonly expression: Expression;
}
export interface UnaryExpression extends Expression {
_unaryExpressionBrand: any;
}
/** Deprecated, please use UpdateExpression */
export type IncrementExpression = UpdateExpression;
export interface UpdateExpression extends UnaryExpression {
_updateExpressionBrand: any;
}
// see: https://tc39.github.io/ecma262/#prod-UpdateExpression
// see: https://tc39.github.io/ecma262/#prod-UnaryExpression
export type PrefixUnaryOperator
= SyntaxKind.PlusPlusToken
| SyntaxKind.MinusMinusToken
| SyntaxKind.PlusToken
| SyntaxKind.MinusToken
| SyntaxKind.TildeToken
| SyntaxKind.ExclamationToken;
export interface PrefixUnaryExpression extends UpdateExpression {
readonly kind: SyntaxKind.PrefixUnaryExpression;
readonly operator: PrefixUnaryOperator;
readonly operand: UnaryExpression;
}
// see: https://tc39.github.io/ecma262/#prod-UpdateExpression
export type PostfixUnaryOperator
= SyntaxKind.PlusPlusToken
| SyntaxKind.MinusMinusToken
;
export interface PostfixUnaryExpression extends UpdateExpression {
readonly kind: SyntaxKind.PostfixUnaryExpression;
readonly operand: LeftHandSideExpression;
readonly operator: PostfixUnaryOperator;
}
export interface LeftHandSideExpression extends UpdateExpression {
_leftHandSideExpressionBrand: any;
}
export interface MemberExpression extends LeftHandSideExpression {
_memberExpressionBrand: any;
}
export interface PrimaryExpression extends MemberExpression {
_primaryExpressionBrand: any;
}
export interface NullLiteral extends PrimaryExpression {
readonly kind: SyntaxKind.NullKeyword;
}
export interface TrueLiteral extends PrimaryExpression {
readonly kind: SyntaxKind.TrueKeyword;
}
export interface FalseLiteral extends PrimaryExpression {
readonly kind: SyntaxKind.FalseKeyword;
}
export type BooleanLiteral = TrueLiteral | FalseLiteral;
export interface ThisExpression extends PrimaryExpression {
readonly kind: SyntaxKind.ThisKeyword;
}
export interface SuperExpression extends PrimaryExpression {
readonly kind: SyntaxKind.SuperKeyword;
}
export interface ImportExpression extends PrimaryExpression {
readonly kind: SyntaxKind.ImportKeyword;
}
export interface DeleteExpression extends UnaryExpression {
readonly kind: SyntaxKind.DeleteExpression;
readonly expression: UnaryExpression;
}
export interface TypeOfExpression extends UnaryExpression {
readonly kind: SyntaxKind.TypeOfExpression;
readonly expression: UnaryExpression;
}
export interface VoidExpression extends UnaryExpression {
readonly kind: SyntaxKind.VoidExpression;
readonly expression: UnaryExpression;
}
export interface AwaitExpression extends UnaryExpression {
readonly kind: SyntaxKind.AwaitExpression;
readonly expression: UnaryExpression;
}
export interface YieldExpression extends Expression {
readonly kind: SyntaxKind.YieldExpression;
readonly asteriskToken?: AsteriskToken;
readonly expression?: Expression;
}
export interface SyntheticExpression extends Expression {
readonly kind: SyntaxKind.SyntheticExpression;
readonly isSpread: boolean;
readonly type: Type;
readonly tupleNameSource?: ParameterDeclaration | NamedTupleMember;
}
// see: https://tc39.github.io/ecma262/#prod-ExponentiationExpression
export type ExponentiationOperator =
| SyntaxKind.AsteriskAsteriskToken
;
// see: https://tc39.github.io/ecma262/#prod-MultiplicativeOperator
export type MultiplicativeOperator =
| SyntaxKind.AsteriskToken
| SyntaxKind.SlashToken
| SyntaxKind.PercentToken
;
// see: https://tc39.github.io/ecma262/#prod-MultiplicativeExpression
export type MultiplicativeOperatorOrHigher =
| ExponentiationOperator
| MultiplicativeOperator
;
// see: https://tc39.github.io/ecma262/#prod-AdditiveExpression
export type AdditiveOperator =
| SyntaxKind.PlusToken
| SyntaxKind.MinusToken
;
// see: https://tc39.github.io/ecma262/#prod-AdditiveExpression
export type AdditiveOperatorOrHigher =
| MultiplicativeOperatorOrHigher
| AdditiveOperator
;
// see: https://tc39.github.io/ecma262/#prod-ShiftExpression
export type ShiftOperator =
| SyntaxKind.LessThanLessThanToken
| SyntaxKind.GreaterThanGreaterThanToken
| SyntaxKind.GreaterThanGreaterThanGreaterThanToken
;
// see: https://tc39.github.io/ecma262/#prod-ShiftExpression
export type ShiftOperatorOrHigher =
| AdditiveOperatorOrHigher
| ShiftOperator
;
// see: https://tc39.github.io/ecma262/#prod-RelationalExpression
export type RelationalOperator =
| SyntaxKind.LessThanToken
| SyntaxKind.LessThanEqualsToken
| SyntaxKind.GreaterThanToken
| SyntaxKind.GreaterThanEqualsToken
| SyntaxKind.InstanceOfKeyword
| SyntaxKind.InKeyword
;
// see: https://tc39.github.io/ecma262/#prod-RelationalExpression
export type RelationalOperatorOrHigher =
| ShiftOperatorOrHigher
| RelationalOperator
;
// see: https://tc39.github.io/ecma262/#prod-EqualityExpression
export type EqualityOperator =
| SyntaxKind.EqualsEqualsToken
| SyntaxKind.EqualsEqualsEqualsToken
| SyntaxKind.ExclamationEqualsEqualsToken
| SyntaxKind.ExclamationEqualsToken
;
// see: https://tc39.github.io/ecma262/#prod-EqualityExpression
export type EqualityOperatorOrHigher =
| RelationalOperatorOrHigher
| EqualityOperator;
// see: https://tc39.github.io/ecma262/#prod-BitwiseANDExpression
// see: https://tc39.github.io/ecma262/#prod-BitwiseXORExpression
// see: https://tc39.github.io/ecma262/#prod-BitwiseORExpression
export type BitwiseOperator =
| SyntaxKind.AmpersandToken
| SyntaxKind.BarToken
| SyntaxKind.CaretToken
;
// see: https://tc39.github.io/ecma262/#prod-BitwiseANDExpression
// see: https://tc39.github.io/ecma262/#prod-BitwiseXORExpression
// see: https://tc39.github.io/ecma262/#prod-BitwiseORExpression
export type BitwiseOperatorOrHigher =
| EqualityOperatorOrHigher
| BitwiseOperator
;
// see: https://tc39.github.io/ecma262/#prod-LogicalANDExpression
// see: https://tc39.github.io/ecma262/#prod-LogicalORExpression
export type LogicalOperator =
| SyntaxKind.AmpersandAmpersandToken
| SyntaxKind.BarBarToken
;
// see: https://tc39.github.io/ecma262/#prod-LogicalANDExpression
// see: https://tc39.github.io/ecma262/#prod-LogicalORExpression
export type LogicalOperatorOrHigher =
| BitwiseOperatorOrHigher
| LogicalOperator
;
// see: https://tc39.github.io/ecma262/#prod-AssignmentOperator
export type CompoundAssignmentOperator =
| SyntaxKind.PlusEqualsToken
| SyntaxKind.MinusEqualsToken
| SyntaxKind.AsteriskAsteriskEqualsToken
| SyntaxKind.AsteriskEqualsToken
| SyntaxKind.SlashEqualsToken
| SyntaxKind.PercentEqualsToken
| SyntaxKind.AmpersandEqualsToken
| SyntaxKind.BarEqualsToken
| SyntaxKind.CaretEqualsToken
| SyntaxKind.LessThanLessThanEqualsToken
| SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken
| SyntaxKind.GreaterThanGreaterThanEqualsToken
| SyntaxKind.BarBarEqualsToken
| SyntaxKind.AmpersandAmpersandEqualsToken
| SyntaxKind.QuestionQuestionEqualsToken
;
// see: https://tc39.github.io/ecma262/#prod-AssignmentExpression
export type AssignmentOperator =
| SyntaxKind.EqualsToken
| CompoundAssignmentOperator
;
// see: https://tc39.github.io/ecma262/#prod-AssignmentExpression
export type AssignmentOperatorOrHigher =
| SyntaxKind.QuestionQuestionToken
| LogicalOperatorOrHigher
| AssignmentOperator
;
// see: https://tc39.github.io/ecma262/#prod-Expression
export type BinaryOperator =
| AssignmentOperatorOrHigher
| SyntaxKind.CommaToken
;
export type LogicalOrCoalescingAssignmentOperator
= SyntaxKind.AmpersandAmpersandEqualsToken
| SyntaxKind.BarBarEqualsToken
| SyntaxKind.QuestionQuestionEqualsToken
;
export type BinaryOperatorToken = Token<BinaryOperator>;
export interface BinaryExpression extends Expression, Declaration {
readonly kind: SyntaxKind.BinaryExpression;
readonly left: Expression;
readonly operatorToken: BinaryOperatorToken;
readonly right: Expression;
}
export type AssignmentOperatorToken = Token<AssignmentOperator>;
export interface AssignmentExpression<TOperator extends AssignmentOperatorToken> extends BinaryExpression {
readonly left: LeftHandSideExpression;
readonly operatorToken: TOperator;
}
export interface ObjectDestructuringAssignment extends AssignmentExpression<EqualsToken> {
readonly left: ObjectLiteralExpression;
}
export interface ArrayDestructuringAssignment extends AssignmentExpression<EqualsToken> {
readonly left: ArrayLiteralExpression;
}
export type DestructuringAssignment =
| ObjectDestructuringAssignment
| ArrayDestructuringAssignment
;
export type BindingOrAssignmentElement =
| VariableDeclaration
| ParameterDeclaration
| ObjectBindingOrAssignmentElement
| ArrayBindingOrAssignmentElement
;
export type ObjectBindingOrAssignmentElement =
| BindingElement
| PropertyAssignment // AssignmentProperty
| ShorthandPropertyAssignment // AssignmentProperty
| SpreadAssignment // AssignmentRestProperty
;
export type ArrayBindingOrAssignmentElement =
| BindingElement
| OmittedExpression // Elision
| SpreadElement // AssignmentRestElement
| ArrayLiteralExpression // ArrayAssignmentPattern
| ObjectLiteralExpression // ObjectAssignmentPattern
| AssignmentExpression<EqualsToken> // AssignmentElement
| Identifier // DestructuringAssignmentTarget
| PropertyAccessExpression // DestructuringAssignmentTarget
| ElementAccessExpression // DestructuringAssignmentTarget
;
export type BindingOrAssignmentElementRestIndicator =
| DotDotDotToken // from BindingElement
| SpreadElement // AssignmentRestElement
| SpreadAssignment // AssignmentRestProperty
;
export type BindingOrAssignmentElementTarget =
| BindingOrAssignmentPattern
| Identifier
| PropertyAccessExpression
| ElementAccessExpression
| OmittedExpression;
export type ObjectBindingOrAssignmentPattern =
| ObjectBindingPattern
| ObjectLiteralExpression // ObjectAssignmentPattern
;
export type ArrayBindingOrAssignmentPattern =
| ArrayBindingPattern
| ArrayLiteralExpression // ArrayAssignmentPattern
;
export type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression;
export type BindingOrAssignmentPattern = ObjectBindingOrAssignmentPattern | ArrayBindingOrAssignmentPattern;
export interface ConditionalExpression extends Expression {
readonly kind: SyntaxKind.ConditionalExpression;
readonly condition: Expression;
readonly questionToken: QuestionToken;
readonly whenTrue: Expression;
readonly colonToken: ColonToken;
readonly whenFalse: Expression;
}
export type FunctionBody = Block;
export type ConciseBody = FunctionBody | Expression;
export interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclarationBase, JSDocContainer {
readonly kind: SyntaxKind.FunctionExpression;
readonly name?: Identifier;
readonly body: FunctionBody; // Required, whereas the member inherited from FunctionDeclaration is optional
}
export interface ArrowFunction extends Expression, FunctionLikeDeclarationBase, JSDocContainer {
readonly kind: SyntaxKind.ArrowFunction;
readonly equalsGreaterThanToken: EqualsGreaterThanToken;
readonly body: ConciseBody;
readonly name: never;
}
// The text property of a LiteralExpression stores the interpreted value of the literal in text form. For a StringLiteral,
// or any literal of a template, this means quotes have been removed and escapes have been converted to actual characters.
// For a NumericLiteral, the stored value is the toString() representation of the number. For example 1, 1.00, and 1e0 are all stored as just "1".
export interface LiteralLikeNode extends Node {
text: string;
isUnterminated?: boolean;
hasExtendedUnicodeEscape?: boolean;
}
export interface TemplateLiteralLikeNode extends LiteralLikeNode {
rawText?: string;
/* @internal */
templateFlags?: TokenFlags;
}
// The text property of a LiteralExpression stores the interpreted value of the literal in text form. For a StringLiteral,
// or any literal of a template, this means quotes have been removed and escapes have been converted to actual characters.
// For a NumericLiteral, the stored value is the toString() representation of the number. For example 1, 1.00, and 1e0 are all stored as just "1".
export interface LiteralExpression extends LiteralLikeNode, PrimaryExpression {
_literalExpressionBrand: any;
}
export interface RegularExpressionLiteral extends LiteralExpression {
readonly kind: SyntaxKind.RegularExpressionLiteral;
}
export interface NoSubstitutionTemplateLiteral extends LiteralExpression, TemplateLiteralLikeNode, Declaration {
readonly kind: SyntaxKind.NoSubstitutionTemplateLiteral;
/* @internal */
templateFlags?: TokenFlags;
}
export const enum TokenFlags {
None = 0,
/* @internal */
PrecedingLineBreak = 1 << 0,
/* @internal */
PrecedingJSDocComment = 1 << 1,
/* @internal */
Unterminated = 1 << 2,
/* @internal */
ExtendedUnicodeEscape = 1 << 3,
Scientific = 1 << 4, // e.g. `10e2`
Octal = 1 << 5, // e.g. `0777`
HexSpecifier = 1 << 6, // e.g. `0x00000000`
BinarySpecifier = 1 << 7, // e.g. `0b0110010000000000`
OctalSpecifier = 1 << 8, // e.g. `0o777`
/* @internal */
ContainsSeparator = 1 << 9, // e.g. `0b1100_0101`
/* @internal */
UnicodeEscape = 1 << 10,
/* @internal */
ContainsInvalidEscape = 1 << 11, // e.g. `\uhello`
/* @internal */
BinaryOrOctalSpecifier = BinarySpecifier | OctalSpecifier,
/* @internal */
NumericLiteralFlags = Scientific | Octal | HexSpecifier | BinaryOrOctalSpecifier | ContainsSeparator,
/* @internal */
TemplateLiteralLikeFlags = ContainsInvalidEscape,
}
export interface NumericLiteral extends LiteralExpression, Declaration {
readonly kind: SyntaxKind.NumericLiteral;
/* @internal */
readonly numericLiteralFlags: TokenFlags;
}
export interface BigIntLiteral extends LiteralExpression {
readonly kind: SyntaxKind.BigIntLiteral;
}
export type LiteralToken =
| NumericLiteral
| BigIntLiteral
| StringLiteral
| JsxText
| RegularExpressionLiteral
| NoSubstitutionTemplateLiteral
;
export interface TemplateHead extends TemplateLiteralLikeNode {
readonly kind: SyntaxKind.TemplateHead;
readonly parent: TemplateExpression | TemplateLiteralTypeNode;
/* @internal */
templateFlags?: TokenFlags;
}
export interface TemplateMiddle extends TemplateLiteralLikeNode {
readonly kind: SyntaxKind.TemplateMiddle;
readonly parent: TemplateSpan | TemplateLiteralTypeSpan;
/* @internal */
templateFlags?: TokenFlags;
}
export interface TemplateTail extends TemplateLiteralLikeNode {
readonly kind: SyntaxKind.TemplateTail;
readonly parent: TemplateSpan | TemplateLiteralTypeSpan;
/* @internal */
templateFlags?: TokenFlags;
}
export type PseudoLiteralToken =
| TemplateHead
| TemplateMiddle
| TemplateTail
;
export type TemplateLiteralToken =
| NoSubstitutionTemplateLiteral
| PseudoLiteralToken
;
export interface TemplateExpression extends PrimaryExpression {
readonly kind: SyntaxKind.TemplateExpression;
readonly head: TemplateHead;
readonly templateSpans: NodeArray<TemplateSpan>;
}
export type TemplateLiteral =
| TemplateExpression
| NoSubstitutionTemplateLiteral
;
// Each of these corresponds to a substitution expression and a template literal, in that order.
// The template literal must have kind TemplateMiddleLiteral or TemplateTailLiteral.
export interface TemplateSpan extends Node {
readonly kind: SyntaxKind.TemplateSpan;
readonly parent: TemplateExpression;
readonly expression: Expression;
readonly literal: TemplateMiddle | TemplateTail;
}
export interface ParenthesizedExpression extends PrimaryExpression, JSDocContainer {
readonly kind: SyntaxKind.ParenthesizedExpression;
readonly expression: Expression;
}
export interface ArrayLiteralExpression extends PrimaryExpression {
readonly kind: SyntaxKind.ArrayLiteralExpression;
readonly elements: NodeArray<Expression>;
/* @internal */
multiLine?: boolean;
}
export interface SpreadElement extends Expression {
readonly kind: SyntaxKind.SpreadElement;
readonly parent: ArrayLiteralExpression | CallExpression | NewExpression;
readonly expression: Expression;
}
/**
* This interface is a base interface for ObjectLiteralExpression and JSXAttributes to extend from. JSXAttributes is similar to
* ObjectLiteralExpression in that it contains array of properties; however, JSXAttributes' properties can only be
* JSXAttribute or JSXSpreadAttribute. ObjectLiteralExpression, on the other hand, can only have properties of type
* ObjectLiteralElement (e.g. PropertyAssignment, ShorthandPropertyAssignment etc.)
*/
export interface ObjectLiteralExpressionBase<T extends ObjectLiteralElement> extends PrimaryExpression, Declaration {
readonly properties: NodeArray<T>;
}
// An ObjectLiteralExpression is the declaration node for an anonymous symbol.
export interface ObjectLiteralExpression extends ObjectLiteralExpressionBase<ObjectLiteralElementLike> {
readonly kind: SyntaxKind.ObjectLiteralExpression;
/* @internal */
multiLine?: boolean;
}
export type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression;
export type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression;
export type AccessExpression = PropertyAccessExpression | ElementAccessExpression;
export interface PropertyAccessExpression extends MemberExpression, NamedDeclaration {
readonly kind: SyntaxKind.PropertyAccessExpression;
readonly expression: LeftHandSideExpression;
readonly questionDotToken?: QuestionDotToken;
readonly name: MemberName;
}
/*@internal*/
export interface PrivateIdentifierPropertyAccessExpression extends PropertyAccessExpression {
readonly name: PrivateIdentifier;
}
export interface PropertyAccessChain extends PropertyAccessExpression {
_optionalChainBrand: any;
readonly name: MemberName;
}
/* @internal */
export interface PropertyAccessChainRoot extends PropertyAccessChain {
readonly questionDotToken: QuestionDotToken;
}
export interface SuperPropertyAccessExpression extends PropertyAccessExpression {
readonly expression: SuperExpression;
}
/** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */
export interface PropertyAccessEntityNameExpression extends PropertyAccessExpression {
_propertyAccessExpressionLikeQualifiedNameBrand?: any;
readonly expression: EntityNameExpression;
readonly name: Identifier;
}
export interface ElementAccessExpression extends MemberExpression {
readonly kind: SyntaxKind.ElementAccessExpression;
readonly expression: LeftHandSideExpression;
readonly questionDotToken?: QuestionDotToken;
readonly argumentExpression: Expression;
}
export interface ElementAccessChain extends ElementAccessExpression {
_optionalChainBrand: any;
}
/* @internal */
export interface ElementAccessChainRoot extends ElementAccessChain {
readonly questionDotToken: QuestionDotToken;
}
export interface SuperElementAccessExpression extends ElementAccessExpression {
readonly expression: SuperExpression;
}
// see: https://tc39.github.io/ecma262/#prod-SuperProperty
export type SuperProperty = SuperPropertyAccessExpression | SuperElementAccessExpression;
export interface CallExpression extends LeftHandSideExpression, Declaration {
readonly kind: SyntaxKind.CallExpression;
readonly expression: LeftHandSideExpression;
readonly questionDotToken?: QuestionDotToken;
readonly typeArguments?: NodeArray<TypeNode>;
readonly arguments: NodeArray<Expression>;
}
export interface CallChain extends CallExpression {
_optionalChainBrand: any;
}
/* @internal */
export interface CallChainRoot extends CallChain {
readonly questionDotToken: QuestionDotToken;
}
export type OptionalChain =
| PropertyAccessChain
| ElementAccessChain
| CallChain
| NonNullChain
;
/* @internal */
export type OptionalChainRoot =
| PropertyAccessChainRoot
| ElementAccessChainRoot
| CallChainRoot
;
/** @internal */
export type BindableObjectDefinePropertyCall = CallExpression & {
readonly arguments: readonly [BindableStaticNameExpression, StringLiteralLike | NumericLiteral, ObjectLiteralExpression] & Readonly<TextRange>;
};
/** @internal */
export type BindableStaticNameExpression =
| EntityNameExpression
| BindableStaticElementAccessExpression
;
/** @internal */
export type LiteralLikeElementAccessExpression = ElementAccessExpression & Declaration & {
readonly argumentExpression: StringLiteralLike | NumericLiteral;
};
/** @internal */
export type BindableStaticElementAccessExpression = LiteralLikeElementAccessExpression & {
readonly expression: BindableStaticNameExpression;
};
/** @internal */
export type BindableElementAccessExpression = ElementAccessExpression & {
readonly expression: BindableStaticNameExpression;
};
/** @internal */
export type BindableStaticAccessExpression =
| PropertyAccessEntityNameExpression
| BindableStaticElementAccessExpression
;
/** @internal */
export type BindableAccessExpression =
| PropertyAccessEntityNameExpression
| BindableElementAccessExpression
;
/** @internal */
export interface BindableStaticPropertyAssignmentExpression extends BinaryExpression {
readonly left: BindableStaticAccessExpression;
}
/** @internal */
export interface BindablePropertyAssignmentExpression extends BinaryExpression {
readonly left: BindableAccessExpression;
}
// see: https://tc39.github.io/ecma262/#prod-SuperCall
export interface SuperCall extends CallExpression {
readonly expression: SuperExpression;
}
export interface ImportCall extends CallExpression {
readonly expression: ImportExpression;
}
export interface ExpressionWithTypeArguments extends NodeWithTypeArguments {
readonly kind: SyntaxKind.ExpressionWithTypeArguments;
readonly parent: HeritageClause | JSDocAugmentsTag | JSDocImplementsTag;
readonly expression: LeftHandSideExpression;
}
export interface NewExpression extends PrimaryExpression, Declaration {
readonly kind: SyntaxKind.NewExpression;
readonly expression: LeftHandSideExpression;
readonly typeArguments?: NodeArray<TypeNode>;
readonly arguments?: NodeArray<Expression>;
}
export interface TaggedTemplateExpression extends MemberExpression {
readonly kind: SyntaxKind.TaggedTemplateExpression;
readonly tag: LeftHandSideExpression;
readonly typeArguments?: NodeArray<TypeNode>;
readonly template: TemplateLiteral;
/*@internal*/ questionDotToken?: QuestionDotToken; // NOTE: Invalid syntax, only used to report a grammar error.
}
export type CallLikeExpression =
| CallExpression
| NewExpression
| TaggedTemplateExpression
| Decorator
| JsxOpeningLikeElement
;
export interface AsExpression extends Expression {
readonly kind: SyntaxKind.AsExpression;
readonly expression: Expression;
readonly type: TypeNode;
}
export interface TypeAssertion extends UnaryExpression {
readonly kind: SyntaxKind.TypeAssertionExpression;
readonly type: TypeNode;
readonly expression: UnaryExpression;
}
export type AssertionExpression =
| TypeAssertion
| AsExpression
;
export interface NonNullExpression extends LeftHandSideExpression {
readonly kind: SyntaxKind.NonNullExpression;
readonly expression: Expression;
}
export interface NonNullChain extends NonNullExpression {
_optionalChainBrand: any;
}
// NOTE: MetaProperty is really a MemberExpression, but we consider it a PrimaryExpression
// for the same reasons we treat NewExpression as a PrimaryExpression.
export interface MetaProperty extends PrimaryExpression {
readonly kind: SyntaxKind.MetaProperty;
readonly keywordToken: SyntaxKind.NewKeyword | SyntaxKind.ImportKeyword;
readonly name: Identifier;
}
/* @internal */
export interface ImportMetaProperty extends MetaProperty {
readonly keywordToken: SyntaxKind.ImportKeyword;
readonly name: Identifier & { readonly escapedText: __String & "meta" };
}
/// A JSX expression of the form <TagName attrs>...</TagName>
export interface JsxElement extends PrimaryExpression {
readonly kind: SyntaxKind.JsxElement;
readonly openingElement: JsxOpeningElement;
readonly children: NodeArray<JsxChild>;
readonly closingElement: JsxClosingElement;
}
/// Either the opening tag in a <Tag>...</Tag> pair or the lone <Tag /> in a self-closing form
export type JsxOpeningLikeElement =
| JsxSelfClosingElement
| JsxOpeningElement
;
export type JsxAttributeLike =
| JsxAttribute
| JsxSpreadAttribute
;
export type JsxTagNameExpression =
| Identifier
| ThisExpression
| JsxTagNamePropertyAccess
;
export interface JsxTagNamePropertyAccess extends PropertyAccessExpression {
readonly expression: JsxTagNameExpression;
}
export interface JsxAttributes extends ObjectLiteralExpressionBase<JsxAttributeLike> {
readonly kind: SyntaxKind.JsxAttributes;
readonly parent: JsxOpeningLikeElement;
}
/// The opening element of a <Tag>...</Tag> JsxElement
export interface JsxOpeningElement extends Expression {
readonly kind: SyntaxKind.JsxOpeningElement;
readonly parent: JsxElement;
readonly tagName: JsxTagNameExpression;
readonly typeArguments?: NodeArray<TypeNode>;
readonly attributes: JsxAttributes;
}
/// A JSX expression of the form <TagName attrs />
export interface JsxSelfClosingElement extends PrimaryExpression {
readonly kind: SyntaxKind.JsxSelfClosingElement;
readonly tagName: JsxTagNameExpression;
readonly typeArguments?: NodeArray<TypeNode>;
readonly attributes: JsxAttributes;
}
/// A JSX expression of the form <>...</>
export interface JsxFragment extends PrimaryExpression {
readonly kind: SyntaxKind.JsxFragment;
readonly openingFragment: JsxOpeningFragment;
readonly children: NodeArray<JsxChild>;
readonly closingFragment: JsxClosingFragment;
}
/// The opening element of a <>...</> JsxFragment
export interface JsxOpeningFragment extends Expression {
readonly kind: SyntaxKind.JsxOpeningFragment;
readonly parent: JsxFragment;
}
/// The closing element of a <>...</> JsxFragment
export interface JsxClosingFragment extends Expression {
readonly kind: SyntaxKind.JsxClosingFragment;
readonly parent: JsxFragment;
}
export interface JsxAttribute extends ObjectLiteralElement {
readonly kind: SyntaxKind.JsxAttribute;
readonly parent: JsxAttributes;
readonly name: Identifier;
/// JSX attribute initializers are optional; <X y /> is sugar for <X y={true} />
readonly initializer?: StringLiteral | JsxExpression;
}
export interface JsxSpreadAttribute extends ObjectLiteralElement {
readonly kind: SyntaxKind.JsxSpreadAttribute;
readonly parent: JsxAttributes;
readonly expression: Expression;
}
export interface JsxClosingElement extends Node {
readonly kind: SyntaxKind.JsxClosingElement;
readonly parent: JsxElement;
readonly tagName: JsxTagNameExpression;
}
export interface JsxExpression extends Expression {
readonly kind: SyntaxKind.JsxExpression;
readonly parent: JsxElement | JsxAttributeLike;
readonly dotDotDotToken?: Token<SyntaxKind.DotDotDotToken>;
readonly expression?: Expression;
}
export interface JsxText extends LiteralLikeNode {
readonly kind: SyntaxKind.JsxText;
readonly parent: JsxElement;
readonly containsOnlyTriviaWhiteSpaces: boolean;
}
export type JsxChild =
| JsxText
| JsxExpression
| JsxElement
| JsxSelfClosingElement
| JsxFragment
;
export interface Statement extends Node, JSDocContainer {
_statementBrand: any;
}
// Represents a statement that is elided as part of a transformation to emit comments on a
// not-emitted node.
export interface NotEmittedStatement extends Statement {
readonly kind: SyntaxKind.NotEmittedStatement;
}
/**
* Marks the end of transformed declaration to properly emit exports.
*/
/* @internal */
export interface EndOfDeclarationMarker extends Statement {
readonly kind: SyntaxKind.EndOfDeclarationMarker;
}
/**
* A list of comma-separated expressions. This node is only created by transformations.
*/
export interface CommaListExpression extends Expression {
readonly kind: SyntaxKind.CommaListExpression;
readonly elements: NodeArray<Expression>;
}
/**
* Marks the beginning of a merged transformed declaration.
*/
/* @internal */
export interface MergeDeclarationMarker extends Statement {
readonly kind: SyntaxKind.MergeDeclarationMarker;
}
/* @internal */
export interface SyntheticReferenceExpression extends LeftHandSideExpression {
readonly kind: SyntaxKind.SyntheticReferenceExpression;
readonly expression: Expression;
readonly thisArg: Expression;
}
export interface EmptyStatement extends Statement {
readonly kind: SyntaxKind.EmptyStatement;
}
export interface DebuggerStatement extends Statement {
readonly kind: SyntaxKind.DebuggerStatement;
}
export interface MissingDeclaration extends DeclarationStatement {
/*@internal*/ decorators?: NodeArray<Decorator>; // Present for use with reporting a grammar error
/*@internal*/ modifiers?: ModifiersArray; // Present for use with reporting a grammar error
readonly kind: SyntaxKind.MissingDeclaration;
readonly name?: Identifier;
}
export type BlockLike =
| SourceFile
| Block
| ModuleBlock
| CaseOrDefaultClause
;
export interface Block extends Statement {
readonly kind: SyntaxKind.Block;
readonly statements: NodeArray<Statement>;
/*@internal*/ multiLine?: boolean;
}
export interface VariableStatement extends Statement {
/* @internal*/ decorators?: NodeArray<Decorator>; // Present for use with reporting a grammar error
readonly kind: SyntaxKind.VariableStatement;
readonly declarationList: VariableDeclarationList;
}
export interface ExpressionStatement extends Statement {
readonly kind: SyntaxKind.ExpressionStatement;
readonly expression: Expression;
}
/* @internal */
export interface PrologueDirective extends ExpressionStatement {
readonly expression: StringLiteral;
}
export interface IfStatement extends Statement {
readonly kind: SyntaxKind.IfStatement;
readonly expression: Expression;
readonly thenStatement: Statement;
readonly elseStatement?: Statement;
}
export interface IterationStatement extends Statement {
readonly statement: Statement;
}
export interface DoStatement extends IterationStatement {
readonly kind: SyntaxKind.DoStatement;
readonly expression: Expression;
}
export interface WhileStatement extends IterationStatement {
readonly kind: SyntaxKind.WhileStatement;
readonly expression: Expression;
}
export type ForInitializer =
| VariableDeclarationList
| Expression
;
export interface ForStatement extends IterationStatement {
readonly kind: SyntaxKind.ForStatement;
readonly initializer?: ForInitializer;
readonly condition?: Expression;
readonly incrementor?: Expression;
}
export type ForInOrOfStatement =
| ForInStatement
| ForOfStatement
;
export interface ForInStatement extends IterationStatement {
readonly kind: SyntaxKind.ForInStatement;
readonly initializer: ForInitializer;
readonly expression: Expression;
}
export interface ForOfStatement extends IterationStatement {
readonly kind: SyntaxKind.ForOfStatement;
readonly awaitModifier?: AwaitKeywordToken;
readonly initializer: ForInitializer;
readonly expression: Expression;
}
export interface BreakStatement extends Statement {
readonly kind: SyntaxKind.BreakStatement;
readonly label?: Identifier;
}
export interface ContinueStatement extends Statement {
readonly kind: SyntaxKind.ContinueStatement;
readonly label?: Identifier;
}
export type BreakOrContinueStatement =
| BreakStatement
| ContinueStatement
;
export interface ReturnStatement extends Statement {
readonly kind: SyntaxKind.ReturnStatement;
readonly expression?: Expression;
}
export interface WithStatement extends Statement {
readonly kind: SyntaxKind.WithStatement;
readonly expression: Expression;
readonly statement: Statement;
}
export interface SwitchStatement extends Statement {
readonly kind: SyntaxKind.SwitchStatement;
readonly expression: Expression;
readonly caseBlock: CaseBlock;
possiblyExhaustive?: boolean; // initialized by binding
}
export interface CaseBlock extends Node {
readonly kind: SyntaxKind.CaseBlock;
readonly parent: SwitchStatement;
readonly clauses: NodeArray<CaseOrDefaultClause>;
}
export interface CaseClause extends Node {
readonly kind: SyntaxKind.CaseClause;
readonly parent: CaseBlock;
readonly expression: Expression;
readonly statements: NodeArray<Statement>;
/* @internal */ fallthroughFlowNode?: FlowNode;
}
export interface DefaultClause extends Node {
readonly kind: SyntaxKind.DefaultClause;
readonly parent: CaseBlock;
readonly statements: NodeArray<Statement>;
/* @internal */ fallthroughFlowNode?: FlowNode;
}
export type CaseOrDefaultClause =
| CaseClause
| DefaultClause
;
export interface LabeledStatement extends Statement {
readonly kind: SyntaxKind.LabeledStatement;
readonly label: Identifier;
readonly statement: Statement;
}
export interface ThrowStatement extends Statement {
readonly kind: SyntaxKind.ThrowStatement;
readonly expression: Expression;
}
export interface TryStatement extends Statement {
readonly kind: SyntaxKind.TryStatement;
readonly tryBlock: Block;
readonly catchClause?: CatchClause;
readonly finallyBlock?: Block;
}
export interface CatchClause extends Node {
readonly kind: SyntaxKind.CatchClause;
readonly parent: TryStatement;
readonly variableDeclaration?: VariableDeclaration;
readonly block: Block;
}
export type ObjectTypeDeclaration =
| ClassLikeDeclaration
| InterfaceDeclaration
| TypeLiteralNode
;
export type DeclarationWithTypeParameters =
| DeclarationWithTypeParameterChildren
| JSDocTypedefTag
| JSDocCallbackTag
| JSDocSignature
;
export type DeclarationWithTypeParameterChildren =
| SignatureDeclaration
| ClassLikeDeclaration
| InterfaceDeclaration
| TypeAliasDeclaration
| JSDocTemplateTag
;
export interface ClassLikeDeclarationBase extends NamedDeclaration, JSDocContainer {
readonly kind: SyntaxKind.ClassDeclaration | SyntaxKind.ClassExpression;
readonly name?: Identifier;
readonly typeParameters?: NodeArray<TypeParameterDeclaration>;
readonly heritageClauses?: NodeArray<HeritageClause>;
readonly members: NodeArray<ClassElement>;
}
export interface ClassDeclaration extends ClassLikeDeclarationBase, DeclarationStatement {
readonly kind: SyntaxKind.ClassDeclaration;
/** May be undefined in `export default class { ... }`. */
readonly name?: Identifier;
}
export interface ClassExpression extends ClassLikeDeclarationBase, PrimaryExpression {
readonly kind: SyntaxKind.ClassExpression;
}
export type ClassLikeDeclaration =
| ClassDeclaration
| ClassExpression
;
export interface ClassElement extends NamedDeclaration {
_classElementBrand: any;
readonly name?: PropertyName;
}
export interface TypeElement extends NamedDeclaration {
_typeElementBrand: any;
readonly name?: PropertyName;
readonly questionToken?: QuestionToken;
}
export interface InterfaceDeclaration extends DeclarationStatement, JSDocContainer {
readonly kind: SyntaxKind.InterfaceDeclaration;
readonly name: Identifier;
readonly typeParameters?: NodeArray<TypeParameterDeclaration>;
readonly heritageClauses?: NodeArray<HeritageClause>;
readonly members: NodeArray<TypeElement>;
}
export interface HeritageClause extends Node {
readonly kind: SyntaxKind.HeritageClause;
readonly parent: InterfaceDeclaration | ClassLikeDeclaration;
readonly token: SyntaxKind.ExtendsKeyword | SyntaxKind.ImplementsKeyword;
readonly types: NodeArray<ExpressionWithTypeArguments>;
}
export interface TypeAliasDeclaration extends DeclarationStatement, JSDocContainer {
readonly kind: SyntaxKind.TypeAliasDeclaration;
readonly name: Identifier;
readonly typeParameters?: NodeArray<TypeParameterDeclaration>;
readonly type: TypeNode;
}
export interface EnumMember extends NamedDeclaration, JSDocContainer {
readonly kind: SyntaxKind.EnumMember;
readonly parent: EnumDeclaration;
// This does include ComputedPropertyName, but the parser will give an error
// if it parses a ComputedPropertyName in an EnumMember
readonly name: PropertyName;
readonly initializer?: Expression;
}
export interface EnumDeclaration extends DeclarationStatement, JSDocContainer {
readonly kind: SyntaxKind.EnumDeclaration;
readonly name: Identifier;
readonly members: NodeArray<EnumMember>;
}
export type ModuleName =
| Identifier
| StringLiteral
;
export type ModuleBody =
| NamespaceBody
| JSDocNamespaceBody
;
/* @internal */
export interface AmbientModuleDeclaration extends ModuleDeclaration {
readonly body?: ModuleBlock;
}
export interface ModuleDeclaration extends DeclarationStatement, JSDocContainer {
readonly kind: SyntaxKind.ModuleDeclaration;
readonly parent: ModuleBody | SourceFile;
readonly name: ModuleName;
readonly body?: ModuleBody | JSDocNamespaceDeclaration;
}
export type NamespaceBody =
| ModuleBlock
| NamespaceDeclaration
;
export interface NamespaceDeclaration extends ModuleDeclaration {
readonly name: Identifier;
readonly body: NamespaceBody;
}
export type JSDocNamespaceBody =
| Identifier
| JSDocNamespaceDeclaration
;
export interface JSDocNamespaceDeclaration extends ModuleDeclaration {
readonly name: Identifier;
readonly body?: JSDocNamespaceBody;
}
export interface ModuleBlock extends Node, Statement {
readonly kind: SyntaxKind.ModuleBlock;
readonly parent: ModuleDeclaration;
readonly statements: NodeArray<Statement>;
}
export type ModuleReference =
| EntityName
| ExternalModuleReference
;
/**
* One of:
* - import x = require("mod");
* - import x = M.x;
*/
export interface ImportEqualsDeclaration extends DeclarationStatement, JSDocContainer {
readonly kind: SyntaxKind.ImportEqualsDeclaration;
readonly parent: SourceFile | ModuleBlock;
readonly name: Identifier;
readonly isTypeOnly: boolean;
// 'EntityName' for an internal module reference, 'ExternalModuleReference' for an external
// module reference.
readonly moduleReference: ModuleReference;
}
export interface ExternalModuleReference extends Node {
readonly kind: SyntaxKind.ExternalModuleReference;
readonly parent: ImportEqualsDeclaration;
readonly expression: Expression;
}
// In case of:
// import "mod" => importClause = undefined, moduleSpecifier = "mod"
// In rest of the cases, module specifier is string literal corresponding to module
// ImportClause information is shown at its declaration below.
export interface ImportDeclaration extends Statement {
readonly kind: SyntaxKind.ImportDeclaration;
readonly parent: SourceFile | ModuleBlock;
readonly importClause?: ImportClause;
/** If this is not a StringLiteral it will be a grammar error. */
readonly moduleSpecifier: Expression;
}
export type NamedImportBindings =
| NamespaceImport
| NamedImports
;
export type NamedExportBindings =
| NamespaceExport
| NamedExports
;
// In case of:
// import d from "mod" => name = d, namedBinding = undefined
// import * as ns from "mod" => name = undefined, namedBinding: NamespaceImport = { name: ns }
// import d, * as ns from "mod" => name = d, namedBinding: NamespaceImport = { name: ns }
// import { a, b as x } from "mod" => name = undefined, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]}
// import d, { a, b as x } from "mod" => name = d, namedBinding: NamedImports = { elements: [{ name: a }, { name: x, propertyName: b}]}
export interface ImportClause extends NamedDeclaration {
readonly kind: SyntaxKind.ImportClause;
readonly parent: ImportDeclaration;
readonly isTypeOnly: boolean;
readonly name?: Identifier; // Default binding
readonly namedBindings?: NamedImportBindings;
}
export interface NamespaceImport extends NamedDeclaration {
readonly kind: SyntaxKind.NamespaceImport;
readonly parent: ImportClause;
readonly name: Identifier;
}
export interface NamespaceExport extends NamedDeclaration {
readonly kind: SyntaxKind.NamespaceExport;
readonly parent: ExportDeclaration;
readonly name: Identifier
}
export interface NamespaceExportDeclaration extends DeclarationStatement, JSDocContainer {
readonly kind: SyntaxKind.NamespaceExportDeclaration;
readonly name: Identifier;
/* @internal */ decorators?: NodeArray<Decorator>; // Present for use with reporting a grammar error
/* @internal */ modifiers?: ModifiersArray; // Present for use with reporting a grammar error
}
export interface ExportDeclaration extends DeclarationStatement, JSDocContainer {
readonly kind: SyntaxKind.ExportDeclaration;
readonly parent: SourceFile | ModuleBlock;
readonly isTypeOnly: boolean;
/** Will not be assigned in the case of `export * from "foo";` */
readonly exportClause?: NamedExportBindings;
/** If this is not a StringLiteral it will be a grammar error. */
readonly moduleSpecifier?: Expression;
}
export interface NamedImports extends Node {
readonly kind: SyntaxKind.NamedImports;
readonly parent: ImportClause;
readonly elements: NodeArray<ImportSpecifier>;
}
export interface NamedExports extends Node {
readonly kind: SyntaxKind.NamedExports;
readonly parent: ExportDeclaration;
readonly elements: NodeArray<ExportSpecifier>;
}
export type NamedImportsOrExports = NamedImports | NamedExports;
export interface ImportSpecifier extends NamedDeclaration {
readonly kind: SyntaxKind.ImportSpecifier;
readonly parent: NamedImports;
readonly propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent)
readonly name: Identifier; // Declared name
}
export interface ExportSpecifier extends NamedDeclaration {
readonly kind: SyntaxKind.ExportSpecifier;
readonly parent: NamedExports;
readonly propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent)
readonly name: Identifier; // Declared name
}
export type ImportOrExportSpecifier =
| ImportSpecifier
| ExportSpecifier
;
export type TypeOnlyCompatibleAliasDeclaration =
| ImportClause
| ImportEqualsDeclaration
| NamespaceImport
| ImportOrExportSpecifier
;
/**
* This is either an `export =` or an `export default` declaration.
* Unless `isExportEquals` is set, this node was parsed as an `export default`.
*/
export interface ExportAssignment extends DeclarationStatement, JSDocContainer {
readonly kind: SyntaxKind.ExportAssignment;
readonly parent: SourceFile;
readonly isExportEquals?: boolean;
readonly expression: Expression;
}
export interface FileReference extends TextRange {
fileName: string;
}
export interface CheckJsDirective extends TextRange {
enabled: boolean;
}
export type CommentKind = SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia;
export interface CommentRange extends TextRange {
hasTrailingNewLine?: boolean;
kind: CommentKind;
}
export interface SynthesizedComment extends CommentRange {
text: string;
pos: -1;
end: -1;
hasLeadingNewline?: boolean;
}
// represents a top level: { type } expression in a JSDoc comment.
export interface JSDocTypeExpression extends TypeNode {
readonly kind: SyntaxKind.JSDocTypeExpression;
readonly type: TypeNode;
}
export interface JSDocNameReference extends Node {
readonly kind: SyntaxKind.JSDocNameReference;
readonly name: EntityName;
}
export interface JSDocType extends TypeNode {
_jsDocTypeBrand: any;
}
export interface JSDocAllType extends JSDocType {
readonly kind: SyntaxKind.JSDocAllType;
}
export interface JSDocUnknownType extends JSDocType {
readonly kind: SyntaxKind.JSDocUnknownType;
}
export interface JSDocNonNullableType extends JSDocType {
readonly kind: SyntaxKind.JSDocNonNullableType;
readonly type: TypeNode;
}
export interface JSDocNullableType extends JSDocType {
readonly kind: SyntaxKind.JSDocNullableType;
readonly type: TypeNode;
}
export interface JSDocOptionalType extends JSDocType {
readonly kind: SyntaxKind.JSDocOptionalType;
readonly type: TypeNode;
}
export interface JSDocFunctionType extends JSDocType, SignatureDeclarationBase {
readonly kind: SyntaxKind.JSDocFunctionType;
}
export interface JSDocVariadicType extends JSDocType {
readonly kind: SyntaxKind.JSDocVariadicType;
readonly type: TypeNode;
}
export interface JSDocNamepathType extends JSDocType {
readonly kind: SyntaxKind.JSDocNamepathType;
readonly type: TypeNode;
}
export type JSDocTypeReferencingNode =
| JSDocVariadicType
| JSDocOptionalType
| JSDocNullableType
| JSDocNonNullableType
;
export interface JSDoc extends Node {
readonly kind: SyntaxKind.JSDocComment;
readonly parent: HasJSDoc;
readonly tags?: NodeArray<JSDocTag>;
readonly comment?: string | NodeArray<JSDocText | JSDocLink>;
}
export interface JSDocTag extends Node {
readonly parent: JSDoc | JSDocTypeLiteral;
readonly tagName: Identifier;
readonly comment?: string | NodeArray<JSDocText | JSDocLink>;
}
export interface JSDocLink extends Node {
readonly kind: SyntaxKind.JSDocLink;
readonly name?: EntityName;
text: string;
}
export interface JSDocText extends Node {
readonly kind: SyntaxKind.JSDocText;
text: string;
}
export interface JSDocUnknownTag extends JSDocTag {
readonly kind: SyntaxKind.JSDocTag;
}
/**
* Note that `@extends` is a synonym of `@augments`.
* Both tags are represented by this interface.
*/
export interface JSDocAugmentsTag extends JSDocTag {
readonly kind: SyntaxKind.JSDocAugmentsTag;
readonly class: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression };
}
export interface JSDocImplementsTag extends JSDocTag {
readonly kind: SyntaxKind.JSDocImplementsTag;
readonly class: ExpressionWithTypeArguments & { readonly expression: Identifier | PropertyAccessEntityNameExpression };
}
export interface JSDocAuthorTag extends JSDocTag {
readonly kind: SyntaxKind.JSDocAuthorTag;
}
export interface JSDocDeprecatedTag extends JSDocTag {
kind: SyntaxKind.JSDocDeprecatedTag;
}
export interface JSDocClassTag extends JSDocTag {
readonly kind: SyntaxKind.JSDocClassTag;
}
export interface JSDocPublicTag extends JSDocTag {
readonly kind: SyntaxKind.JSDocPublicTag;
}
export interface JSDocPrivateTag extends JSDocTag {
readonly kind: SyntaxKind.JSDocPrivateTag;
}
export interface JSDocProtectedTag extends JSDocTag {
readonly kind: SyntaxKind.JSDocProtectedTag;
}
export interface JSDocReadonlyTag extends JSDocTag {
readonly kind: SyntaxKind.JSDocReadonlyTag;
}
export interface JSDocOverrideTag extends JSDocTag {
readonly kind: SyntaxKind.JSDocOverrideTag;
}
export interface JSDocEnumTag extends JSDocTag, Declaration {
readonly kind: SyntaxKind.JSDocEnumTag;
readonly parent: JSDoc;
readonly typeExpression: JSDocTypeExpression;
}
export interface JSDocThisTag extends JSDocTag {
readonly kind: SyntaxKind.JSDocThisTag;
readonly typeExpression: JSDocTypeExpression;
}
export interface JSDocTemplateTag extends JSDocTag {
readonly kind: SyntaxKind.JSDocTemplateTag;
readonly constraint: JSDocTypeExpression | undefined;
readonly typeParameters: NodeArray<TypeParameterDeclaration>;
}
export interface JSDocSeeTag extends JSDocTag {
readonly kind: SyntaxKind.JSDocSeeTag;
readonly name?: JSDocNameReference;
}
export interface JSDocReturnTag extends JSDocTag {
readonly kind: SyntaxKind.JSDocReturnTag;
readonly typeExpression?: JSDocTypeExpression;
}
export interface JSDocTypeTag extends JSDocTag {
readonly kind: SyntaxKind.JSDocTypeTag;
readonly typeExpression: JSDocTypeExpression;
}
export interface JSDocTypedefTag extends JSDocTag, NamedDeclaration {
readonly kind: SyntaxKind.JSDocTypedefTag;
readonly parent: JSDoc;
readonly fullName?: JSDocNamespaceDeclaration | Identifier;
readonly name?: Identifier;
readonly typeExpression?: JSDocTypeExpression | JSDocTypeLiteral;
}
export interface JSDocCallbackTag extends JSDocTag, NamedDeclaration {
readonly kind: SyntaxKind.JSDocCallbackTag;
readonly parent: JSDoc;
readonly fullName?: JSDocNamespaceDeclaration | Identifier;
readonly name?: Identifier;
readonly typeExpression: JSDocSignature;
}
export interface JSDocSignature extends JSDocType, Declaration {
readonly kind: SyntaxKind.JSDocSignature;
readonly typeParameters?: readonly JSDocTemplateTag[];
readonly parameters: readonly JSDocParameterTag[];
readonly type: JSDocReturnTag | undefined;
}
export interface JSDocPropertyLikeTag extends JSDocTag, Declaration {
readonly parent: JSDoc;
readonly name: EntityName;
readonly typeExpression?: JSDocTypeExpression;
/** Whether the property name came before the type -- non-standard for JSDoc, but Typescript-like */
readonly isNameFirst: boolean;
readonly isBracketed: boolean;
}
export interface JSDocPropertyTag extends JSDocPropertyLikeTag {
readonly kind: SyntaxKind.JSDocPropertyTag;
}
export interface JSDocParameterTag extends JSDocPropertyLikeTag {
readonly kind: SyntaxKind.JSDocParameterTag;
}
export interface JSDocTypeLiteral extends JSDocType {
readonly kind: SyntaxKind.JSDocTypeLiteral;
readonly jsDocPropertyTags?: readonly JSDocPropertyLikeTag[];
/** If true, then this type literal represents an *array* of its type. */
readonly isArrayType: boolean;
}
// NOTE: Ensure this is up-to-date with src/debug/debug.ts
export const enum FlowFlags {
Unreachable = 1 << 0, // Unreachable code
Start = 1 << 1, // Start of flow graph
BranchLabel = 1 << 2, // Non-looping junction
LoopLabel = 1 << 3, // Looping junction
Assignment = 1 << 4, // Assignment
TrueCondition = 1 << 5, // Condition known to be true
FalseCondition = 1 << 6, // Condition known to be false
SwitchClause = 1 << 7, // Switch statement clause
ArrayMutation = 1 << 8, // Potential array mutation
Call = 1 << 9, // Potential assertion call
ReduceLabel = 1 << 10, // Temporarily reduce antecedents of label
Referenced = 1 << 11, // Referenced as antecedent once
Shared = 1 << 12, // Referenced as antecedent more than once
Label = BranchLabel | LoopLabel,
Condition = TrueCondition | FalseCondition,
}
export type FlowNode =
| FlowStart
| FlowLabel
| FlowAssignment
| FlowCall
| FlowCondition
| FlowSwitchClause
| FlowArrayMutation
| FlowCall
| FlowReduceLabel;
export interface FlowNodeBase {
flags: FlowFlags;
id?: number; // Node id used by flow type cache in checker
}
// FlowStart represents the start of a control flow. For a function expression or arrow
// function, the node property references the function (which in turn has a flowNode
// property for the containing control flow).
export interface FlowStart extends FlowNodeBase {
node?: FunctionExpression | ArrowFunction | MethodDeclaration;
}
// FlowLabel represents a junction with multiple possible preceding control flows.
export interface FlowLabel extends FlowNodeBase {
antecedents: FlowNode[] | undefined;
}
// FlowAssignment represents a node that assigns a value to a narrowable reference,
// i.e. an identifier or a dotted name that starts with an identifier or 'this'.
export interface FlowAssignment extends FlowNodeBase {
node: Expression | VariableDeclaration | BindingElement;
antecedent: FlowNode;
}
export interface FlowCall extends FlowNodeBase {
node: CallExpression;
antecedent: FlowNode;
}
// FlowCondition represents a condition that is known to be true or false at the
// node's location in the control flow.
export interface FlowCondition extends FlowNodeBase {
node: Expression;
antecedent: FlowNode;
}
export interface FlowSwitchClause extends FlowNodeBase {
switchStatement: SwitchStatement;
clauseStart: number; // Start index of case/default clause range
clauseEnd: number; // End index of case/default clause range
antecedent: FlowNode;
}
// FlowArrayMutation represents a node potentially mutates an array, i.e. an
// operation of the form 'x.push(value)', 'x.unshift(value)' or 'x[n] = value'.
export interface FlowArrayMutation extends FlowNodeBase {
node: CallExpression | BinaryExpression;
antecedent: FlowNode;
}
export interface FlowReduceLabel extends FlowNodeBase {
target: FlowLabel;
antecedents: FlowNode[];
antecedent: FlowNode;
}
export type FlowType = Type | IncompleteType;
// Incomplete types occur during control flow analysis of loops. An IncompleteType
// is distinguished from a regular type by a flags value of zero. Incomplete type
// objects are internal to the getFlowTypeOfReference function and never escape it.
export interface IncompleteType {
flags: TypeFlags; // No flags set
type: Type; // The type marked incomplete
}
export interface AmdDependency {
path: string;
name?: string;
}
/* @internal */
/**
* Subset of properties from SourceFile that are used in multiple utility functions
*/
export interface SourceFileLike {
readonly text: string;
lineMap?: readonly number[];
/* @internal */
getPositionOfLineAndCharacter?(line: number, character: number, allowEdits?: true): number;
}
/* @internal */
export interface RedirectInfo {
/** Source file this redirects to. */
readonly redirectTarget: SourceFile;
/**
* Source file for the duplicate package. This will not be used by the Program,
* but we need to keep this around so we can watch for changes in underlying.
*/
readonly unredirected: SourceFile;
}
// Source files are declarations when they are external modules.
export interface SourceFile extends Declaration {
readonly kind: SyntaxKind.SourceFile;
readonly statements: NodeArray<Statement>;
readonly endOfFileToken: Token<SyntaxKind.EndOfFileToken>;
fileName: string;
/* @internal */ path: Path;
text: string;
/** Resolved path can be different from path property,
* when file is included through project reference is mapped to its output instead of source
* in that case resolvedPath = path to output file
* path = input file's path
*/
/* @internal */ resolvedPath: Path;
/** Original file name that can be different from fileName,
* when file is included through project reference is mapped to its output instead of source
* in that case originalFileName = name of input file
* fileName = output file's name
*/
/* @internal */ originalFileName: string;
/**
* If two source files are for the same version of the same package, one will redirect to the other.
* (See `createRedirectSourceFile` in program.ts.)
* The redirect will have this set. The redirected-to source file will be in `redirectTargetsMap`.
*/
/* @internal */ redirectInfo?: RedirectInfo;
amdDependencies: readonly AmdDependency[];
moduleName?: string;
referencedFiles: readonly FileReference[];
typeReferenceDirectives: readonly FileReference[];
libReferenceDirectives: readonly FileReference[];
languageVariant: LanguageVariant;
isDeclarationFile: boolean;
// this map is used by transpiler to supply alternative names for dependencies (i.e. in case of bundling)
/* @internal */
renamedDependencies?: ReadonlyESMap<string, string>;
/**
* lib.d.ts should have a reference comment like
*
* /// <reference no-default-lib="true"/>
*
* If any other file has this comment, it signals not to include lib.d.ts
* because this containing file is intended to act as a default library.
*/
hasNoDefaultLib: boolean;
languageVersion: ScriptTarget;
/* @internal */ scriptKind: ScriptKind;
/**
* The first "most obvious" node that makes a file an external module.
* This is intended to be the first top-level import/export,
* but could be arbitrarily nested (e.g. `import.meta`).
*/
/* @internal */ externalModuleIndicator?: Node;
// The first node that causes this file to be a CommonJS module
/* @internal */ commonJsModuleIndicator?: Node;
// JS identifier-declarations that are intended to merge with globals
/* @internal */ jsGlobalAugmentations?: SymbolTable;
/* @internal */ identifiers: ESMap<string, string>; // Map from a string to an interned string
/* @internal */ nodeCount: number;
/* @internal */ identifierCount: number;
/* @internal */ symbolCount: number;
// File-level diagnostics reported by the parser (includes diagnostics about /// references
// as well as code diagnostics).
/* @internal */ parseDiagnostics: DiagnosticWithLocation[];
// File-level diagnostics reported by the binder.
/* @internal */ bindDiagnostics: DiagnosticWithLocation[];
/* @internal */ bindSuggestionDiagnostics?: DiagnosticWithLocation[];
// File-level JSDoc diagnostics reported by the JSDoc parser
/* @internal */ jsDocDiagnostics?: DiagnosticWithLocation[];
// Stores additional file-level diagnostics reported by the program
/* @internal */ additionalSyntacticDiagnostics?: readonly DiagnosticWithLocation[];
// Stores a line map for the file.
// This field should never be used directly to obtain line map, use getLineMap function instead.
/* @internal */ lineMap: readonly number[];
/* @internal */ classifiableNames?: ReadonlySet<__String>;
// Comments containing @ts-* directives, in order.
/* @internal */ commentDirectives?: CommentDirective[];
// Stores a mapping 'external module reference text' -> 'resolved file name' | undefined
// It is used to resolve module names in the checker.
// Content of this field should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead
/* @internal */ resolvedModules?: ESMap<string, ResolvedModuleFull | undefined>;
/* @internal */ resolvedTypeReferenceDirectiveNames: ESMap<string, ResolvedTypeReferenceDirective | undefined>;
/* @internal */ imports: readonly StringLiteralLike[];
// Identifier only if `declare global`
/* @internal */ moduleAugmentations: readonly (StringLiteral | Identifier)[];
/* @internal */ patternAmbientModules?: PatternAmbientModule[];
/* @internal */ ambientModuleNames: readonly string[];
/* @internal */ checkJsDirective?: CheckJsDirective;
/* @internal */ version: string;
/* @internal */ pragmas: ReadonlyPragmaMap;
/* @internal */ localJsxNamespace?: __String;
/* @internal */ localJsxFragmentNamespace?: __String;
/* @internal */ localJsxFactory?: EntityName;
/* @internal */ localJsxFragmentFactory?: EntityName;
/* @internal */ exportedModulesFromDeclarationEmit?: ExportedModulesFromDeclarationEmit;
/* @internal */ endFlowNode?: FlowNode;
}
/* @internal */
export interface CommentDirective {
range: TextRange;
type: CommentDirectiveType,
}
/* @internal */
export const enum CommentDirectiveType {
ExpectError,
Ignore,
}
/*@internal*/
export type ExportedModulesFromDeclarationEmit = readonly Symbol[];
export interface Bundle extends Node {
readonly kind: SyntaxKind.Bundle;
readonly prepends: readonly (InputFiles | UnparsedSource)[];
readonly sourceFiles: readonly SourceFile[];
/* @internal */ syntheticFileReferences?: readonly FileReference[];
/* @internal */ syntheticTypeReferences?: readonly FileReference[];
/* @internal */ syntheticLibReferences?: readonly FileReference[];
/* @internal */ hasNoDefaultLib?: boolean;
}
export interface InputFiles extends Node {
readonly kind: SyntaxKind.InputFiles;
javascriptPath?: string;
javascriptText: string;
javascriptMapPath?: string;
javascriptMapText?: string;
declarationPath?: string;
declarationText: string;
declarationMapPath?: string;
declarationMapText?: string;
/*@internal*/ buildInfoPath?: string;
/*@internal*/ buildInfo?: BuildInfo;
/*@internal*/ oldFileOfCurrentEmit?: boolean;
}
export interface UnparsedSource extends Node {
readonly kind: SyntaxKind.UnparsedSource;
fileName: string;
text: string;
readonly prologues: readonly UnparsedPrologue[];
helpers: readonly UnscopedEmitHelper[] | undefined;
// References and noDefaultLibAre Dts only
referencedFiles: readonly FileReference[];
typeReferenceDirectives: readonly string[] | undefined;
libReferenceDirectives: readonly FileReference[];
hasNoDefaultLib?: boolean;
sourceMapPath?: string;
sourceMapText?: string;
readonly syntheticReferences?: readonly UnparsedSyntheticReference[];
readonly texts: readonly UnparsedSourceText[];
/*@internal*/ oldFileOfCurrentEmit?: boolean;
/*@internal*/ parsedSourceMap?: RawSourceMap | false | undefined;
// Adding this to satisfy services, fix later
/*@internal*/
getLineAndCharacterOfPosition(pos: number): LineAndCharacter;
}
export type UnparsedSourceText =
| UnparsedPrepend
| UnparsedTextLike
;
export type UnparsedNode =
| UnparsedPrologue
| UnparsedSourceText
| UnparsedSyntheticReference
;
export interface UnparsedSection extends Node {
readonly kind: SyntaxKind;
readonly parent: UnparsedSource;
readonly data?: string;
}
export interface UnparsedPrologue extends UnparsedSection {
readonly kind: SyntaxKind.UnparsedPrologue;
readonly parent: UnparsedSource;
readonly data: string;
}
export interface UnparsedPrepend extends UnparsedSection {
readonly kind: SyntaxKind.UnparsedPrepend;
readonly parent: UnparsedSource;
readonly data: string;
readonly texts: readonly UnparsedTextLike[];
}
export interface UnparsedTextLike extends UnparsedSection {
readonly kind: SyntaxKind.UnparsedText | SyntaxKind.UnparsedInternalText;
readonly parent: UnparsedSource;
}
export interface UnparsedSyntheticReference extends UnparsedSection {
readonly kind: SyntaxKind.UnparsedSyntheticReference;
readonly parent: UnparsedSource;
/*@internal*/ readonly section: BundleFileHasNoDefaultLib | BundleFileReference;
}
export interface JsonSourceFile extends SourceFile {
readonly statements: NodeArray<JsonObjectExpressionStatement>;
}
export interface TsConfigSourceFile extends JsonSourceFile {
extendedSourceFiles?: string[];
/*@internal*/ configFileSpecs?: ConfigFileSpecs;
}
export interface JsonMinusNumericLiteral extends PrefixUnaryExpression {
readonly kind: SyntaxKind.PrefixUnaryExpression;
readonly operator: SyntaxKind.MinusToken;
readonly operand: NumericLiteral;
}
export type JsonObjectExpression =
| ObjectLiteralExpression
| ArrayLiteralExpression
| JsonMinusNumericLiteral
| NumericLiteral
| StringLiteral
| BooleanLiteral
| NullLiteral
;
export interface JsonObjectExpressionStatement extends ExpressionStatement {
readonly expression: JsonObjectExpression;
}
export interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
getSourceFile(fileName: string): SourceFile | undefined;
getSourceFileByPath(path: Path): SourceFile | undefined;
getCurrentDirectory(): string;
}
export interface ParseConfigHost {
useCaseSensitiveFileNames: boolean;
readDirectory(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[], depth?: number): readonly string[];
/**
* Gets a value indicating whether the specified path exists and is a file.
* @param path The path to test.
*/
fileExists(path: string): boolean;
readFile(path: string): string | undefined;
trace?(s: string): void;
}
/**
* Branded string for keeping track of when we've turned an ambiguous path
* specified like "./blah" to an absolute path to an actual
* tsconfig file, e.g. "/root/blah/tsconfig.json"
*/
export type ResolvedConfigFileName = string & { _isResolvedConfigFileName: never };
export type WriteFileCallback = (
fileName: string,
data: string,
writeByteOrderMark: boolean,
onError?: (message: string) => void,
sourceFiles?: readonly SourceFile[],
) => void;
export class | { }
export interface CancellationToken {
isCancellationRequested(): boolean;
/** @throws OperationCanceledException if isCancellationRequested is true */
throwIfCancellationRequested(): void;
}
/*@internal*/
export enum FileIncludeKind {
RootFile,
SourceFromProjectReference,
OutputFromProjectReference,
Import,
ReferenceFile,
TypeReferenceDirective,
LibFile,
LibReferenceDirective,
AutomaticTypeDirectiveFile
}
/*@internal*/
export interface RootFile {
kind: FileIncludeKind.RootFile,
index: number;
}
/*@internal*/
export interface LibFile {
kind: FileIncludeKind.LibFile;
index?: number;
}
/*@internal*/
export type ProjectReferenceFileKind = FileIncludeKind.SourceFromProjectReference |
FileIncludeKind.OutputFromProjectReference;
/*@internal*/
export interface ProjectReferenceFile {
kind: ProjectReferenceFileKind;
index: number;
}
/*@internal*/
export type ReferencedFileKind = FileIncludeKind.Import |
FileIncludeKind.ReferenceFile |
FileIncludeKind.TypeReferenceDirective |
FileIncludeKind.LibReferenceDirective;
/*@internal*/
export interface ReferencedFile {
kind: ReferencedFileKind;
file: Path;
index: number;
}
/*@internal*/
export interface AutomaticTypeDirectiveFile {
kind: FileIncludeKind.AutomaticTypeDirectiveFile;
typeReference: string;
packageId: PackageId | undefined;
}
/*@internal*/
export type FileIncludeReason =
RootFile |
LibFile |
ProjectReferenceFile |
ReferencedFile |
AutomaticTypeDirectiveFile;
/*@internal*/
export const enum FilePreprocessingDiagnosticsKind {
FilePreprocessingReferencedDiagnostic,
FilePreprocessingFileExplainingDiagnostic
}
/*@internal*/
export interface FilePreprocessingReferencedDiagnostic {
kind: FilePreprocessingDiagnosticsKind.FilePreprocessingReferencedDiagnostic;
reason: ReferencedFile;
diagnostic: DiagnosticMessage;
args?: (string | number | undefined)[];
}
/*@internal*/
export interface FilePreprocessingFileExplainingDiagnostic {
kind: FilePreprocessingDiagnosticsKind.FilePreprocessingFileExplainingDiagnostic;
file?: Path;
fileProcessingReason: FileIncludeReason;
diagnostic: DiagnosticMessage;
args?: (string | number | undefined)[];
}
/*@internal*/
export type FilePreprocessingDiagnostics = FilePreprocessingReferencedDiagnostic | FilePreprocessingFileExplainingDiagnostic;
export interface Program extends ScriptReferenceHost {
getCurrentDirectory(): string;
/**
* Get a list of root file names that were passed to a 'createProgram'
*/
getRootFileNames(): readonly string[];
/**
* Get a list of files in the program
*/
getSourceFiles(): readonly SourceFile[];
/**
* Get a list of file names that were passed to 'createProgram' or referenced in a
* program source file but could not be located.
*/
/* @internal */
getMissingFilePaths(): readonly Path[];
/* @internal */
getFilesByNameMap(): ESMap<string, SourceFile | false | undefined>;
/**
* Emits the JavaScript and declaration files. If targetSourceFile is not specified, then
* the JavaScript and declaration files will be produced for all the files in this program.
* If targetSourceFile is specified, then only the JavaScript and declaration for that
* specific file will be generated.
*
* If writeFile is not specified then the writeFile callback from the compiler host will be
* used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter
* will be invoked when writing the JavaScript and declaration files.
*/
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult;
/*@internal*/
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers, forceDtsEmit?: boolean): EmitResult; // eslint-disable-line @typescript-eslint/unified-signatures
getOptionsDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[];
getGlobalDiagnostics(cancellationToken?: CancellationToken): readonly Diagnostic[];
getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[];
/** The first time this is called, it will return global diagnostics (no location). */
getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[];
getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[];
getConfigFileParsingDiagnostics(): readonly Diagnostic[];
/* @internal */ getSuggestionDiagnostics(sourceFile: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[];
/* @internal */ getBindAndCheckDiagnostics(sourceFile: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[];
/* @internal */ getProgramDiagnostics(sourceFile: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[];
/**
* Gets a type checker that can be used to semantically analyze source files in the program.
*/
getTypeChecker(): TypeChecker;
/* @internal */ getCommonSourceDirectory(): string;
// For testing purposes only. Should not be used by any other consumers (including the
// language service).
/* @internal */ getDiagnosticsProducingTypeChecker(): TypeChecker;
/* @internal */ dropDiagnosticsProducingTypeChecker(): void;
/* @internal */ getCachedSemanticDiagnostics(sourceFile?: SourceFile): readonly Diagnostic[] | undefined;
/* @internal */ getClassifiableNames(): Set<__String>;
getNodeCount(): number;
getIdentifierCount(): number;
getSymbolCount(): number;
getTypeCount(): number;
getInstantiationCount(): number;
getRelationCacheSizes(): { assignable: number, identity: number, subtype: number, strictSubtype: number };
/* @internal */ getFileProcessingDiagnostics(): FilePreprocessingDiagnostics[] | undefined;
/* @internal */ getResolvedTypeReferenceDirectives(): ESMap<string, ResolvedTypeReferenceDirective | undefined>;
isSourceFileFromExternalLibrary(file: SourceFile): boolean;
isSourceFileDefaultLibrary(file: SourceFile): boolean;
// For testing purposes only.
// This is set on created program to let us know how the program was created using old program
/* @internal */ readonly structureIsReused: StructureIsReused;
/* @internal */ getSourceFileFromReference(referencingFile: SourceFile | UnparsedSource, ref: FileReference): SourceFile | undefined;
/* @internal */ getLibFileFromReference(ref: FileReference): SourceFile | undefined;
/** Given a source file, get the name of the package it was imported from. */
/* @internal */ sourceFileToPackageName: ESMap<string, string>;
/** Set of all source files that some other source file redirects to. */
/* @internal */ redirectTargetsMap: MultiMap<string, string>;
/** Is the file emitted file */
/* @internal */ isEmittedFile(file: string): boolean;
/* @internal */ getFileIncludeReasons(): MultiMap<Path, FileIncludeReason>;
/* @internal */ useCaseSensitiveFileNames(): boolean;
/* @internal */ getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined;
getProjectReferences(): readonly ProjectReference[] | undefined;
getResolvedProjectReferences(): readonly (ResolvedProjectReference | undefined)[] | undefined;
/*@internal*/ getProjectReferenceRedirect(fileName: string): string | undefined;
/*@internal*/ getResolvedProjectReferenceToRedirect(fileName: string): ResolvedProjectReference | undefined;
/*@internal*/ forEachResolvedProjectReference<T>(cb: (resolvedProjectReference: ResolvedProjectReference) => T | undefined): T | undefined;
/*@internal*/ getResolvedProjectReferenceByPath(projectReferencePath: Path): ResolvedProjectReference | undefined;
/*@internal*/ isSourceOfProjectReferenceRedirect(fileName: string): boolean;
/*@internal*/ getProgramBuildInfo?(): ProgramBuildInfo | undefined;
/*@internal*/ emitBuildInfo(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult;
/**
* This implementation handles file exists to be true if file is source of project reference redirect when program is created using useSourceOfProjectReferenceRedirect
*/
/*@internal*/ fileExists(fileName: string): boolean;
}
/*@internal*/
export interface Program extends TypeCheckerHost, ModuleSpecifierResolutionHost {
}
/* @internal */
export type RedirectTargetsMap = ReadonlyESMap<string, readonly string[]>;
export interface ResolvedProjectReference {
commandLine: ParsedCommandLine;
sourceFile: SourceFile;
references?: readonly (ResolvedProjectReference | undefined)[];
}
/* @internal */
export const enum StructureIsReused {
Not,
SafeModules,
Completely,
}
export type CustomTransformerFactory = (context: TransformationContext) => CustomTransformer;
export interface CustomTransformer {
transformSourceFile(node: SourceFile): SourceFile;
transformBundle(node: Bundle): Bundle;
}
export interface CustomTransformers {
/** Custom transformers to evaluate before built-in .js transformations. */
before?: (TransformerFactory<SourceFile> | CustomTransformerFactory)[];
/** Custom transformers to evaluate after built-in .js transformations. */
after?: (TransformerFactory<SourceFile> | CustomTransformerFactory)[];
/** Custom transformers to evaluate after built-in .d.ts transformations. */
afterDeclarations?: (TransformerFactory<Bundle | SourceFile> | CustomTransformerFactory)[];
}
/*@internal*/
export interface EmitTransformers {
scriptTransformers: readonly TransformerFactory<SourceFile | Bundle>[];
declarationTransformers: readonly TransformerFactory<SourceFile | Bundle>[];
}
export interface SourceMapSpan {
/** Line number in the .js file. */
emittedLine: number;
/** Column number in the .js file. */
emittedColumn: number;
/** Line number in the .ts file. */
sourceLine: number;
/** Column number in the .ts file. */
sourceColumn: number;
/** Optional name (index into names array) associated with this span. */
nameIndex?: number;
/** .ts file (index into sources array) associated with this span */
sourceIndex: number;
}
/* @internal */
export interface SourceMapEmitResult {
inputSourceFileNames: readonly string[]; // Input source file (which one can use on program to get the file), 1:1 mapping with the sourceMap.sources list
sourceMap: RawSourceMap;
}
/** Return code used by getEmitOutput function to indicate status of the function */
export enum ExitStatus {
// Compiler ran successfully. Either this was a simple do-nothing compilation (for example,
// when -version or -help was provided, or this was a normal compilation, no diagnostics
// were produced, and all outputs were generated successfully.
Success = 0,
// Diagnostics were produced and because of them no code was generated.
DiagnosticsPresent_OutputsSkipped = 1,
// Diagnostics were produced and outputs were generated in spite of them.
DiagnosticsPresent_OutputsGenerated = 2,
// When build skipped because passed in project is invalid
InvalidProject_OutputsSkipped = 3,
// When build is skipped because project references form cycle
ProjectReferenceCycle_OutputsSkipped = 4,
/** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */
ProjectReferenceCycle_OutputsSkupped = 4,
}
export interface EmitResult {
emitSkipped: boolean;
/** Contains declaration emit diagnostics */
diagnostics: readonly Diagnostic[];
emittedFiles?: string[]; // Array of files the compiler wrote to disk
/* @internal */ sourceMaps?: SourceMapEmitResult[]; // Array of sourceMapData if compiler emitted sourcemaps
/* @internal */ exportedModulesFromDeclarationEmit?: ExportedModulesFromDeclarationEmit;
}
/* @internal */
export interface TypeCheckerHost extends ModuleSpecifierResolutionHost {
getCompilerOptions(): CompilerOptions;
getSourceFiles(): readonly SourceFile[];
getSourceFile(fileName: string): SourceFile | undefined;
getResolvedTypeReferenceDirectives(): ReadonlyESMap<string, ResolvedTypeReferenceDirective | undefined>;
getProjectReferenceRedirect(fileName: string): string | undefined;
isSourceOfProjectReferenceRedirect(fileName: string): boolean;
readonly redirectTargetsMap: RedirectTargetsMap;
}
export interface TypeChecker {
getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;
getDeclaredTypeOfSymbol(symbol: Symbol): Type;
getPropertiesOfType(type: Type): Symbol[];
getPropertyOfType(type: Type, propertyName: string): Symbol | undefined;
getPrivateIdentifierPropertyOfType(leftType: Type, name: string, location: Node): Symbol | undefined;
/* @internal */ getTypeOfPropertyOfType(type: Type, propertyName: string): Type | undefined;
getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo | undefined;
getSignaturesOfType(type: Type, kind: SignatureKind): readonly Signature[];
getIndexTypeOfType(type: Type, kind: IndexKind): Type | undefined;
getBaseTypes(type: InterfaceType): BaseType[];
getBaseTypeOfLiteralType(type: Type): Type;
getWidenedType(type: Type): Type;
/* @internal */
getPromisedTypeOfPromise(promise: Type, errorNode?: Node): Type | undefined;
/* @internal */
getAwaitedType(type: Type): Type | undefined;
getReturnTypeOfSignature(signature: Signature): Type;
/**
* Gets the type of a parameter at a given position in a signature.
* Returns `any` if the index is not valid.
*/
/* @internal */ getParameterType(signature: Signature, parameterIndex: number): Type;
getNullableType(type: Type, flags: TypeFlags): Type;
getNonNullableType(type: Type): Type;
/* @internal */ getNonOptionalType(type: Type): Type;
/* @internal */ isNullableType(type: Type): boolean;
getTypeArguments(type: TypeReference): readonly Type[];
// TODO: GH#18217 `xToDeclaration` calls are frequently asserted as defined.
/** Note that the resulting nodes cannot be checked. */
typeToTypeNode(type: Type, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeNode | undefined;
/* @internal */ typeToTypeNode(type: Type, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined, tracker?: SymbolTracker): TypeNode | undefined; // eslint-disable-line @typescript-eslint/unified-signatures
/** Note that the resulting nodes cannot be checked. */
signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): SignatureDeclaration & {typeArguments?: NodeArray<TypeNode>} | undefined;
/* @internal */ signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined, tracker?: SymbolTracker): SignatureDeclaration & {typeArguments?: NodeArray<TypeNode>} | undefined; // eslint-disable-line @typescript-eslint/unified-signatures
/** Note that the resulting nodes cannot be checked. */
indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): IndexSignatureDeclaration | undefined;
/* @internal */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined, tracker?: SymbolTracker): IndexSignatureDeclaration | undefined; // eslint-disable-line @typescript-eslint/unified-signatures
/** Note that the resulting nodes cannot be checked. */
symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): EntityName | undefined;
/** Note that the resulting nodes cannot be checked. */
symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): Expression | undefined;
/** Note that the resulting nodes cannot be checked. */
symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): NodeArray<TypeParameterDeclaration> | undefined;
/** Note that the resulting nodes cannot be checked. */
symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): ParameterDeclaration | undefined;
/** Note that the resulting nodes cannot be checked. */
typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration: Node | undefined, flags: NodeBuilderFlags | undefined): TypeParameterDeclaration | undefined;
getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[];
getSymbolAtLocation(node: Node): Symbol | undefined;
getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[];
/**
* The function returns the value (local variable) symbol of an identifier in the short-hand property assignment.
* This is necessary as an identifier in short-hand property assignment can contains two meaning: property name and property value.
*/
getShorthandAssignmentValueSymbol(location: Node | undefined): Symbol | undefined;
getExportSpecifierLocalTargetSymbol(location: ExportSpecifier | Identifier): Symbol | undefined;
/**
* If a symbol is a local symbol with an associated exported symbol, returns the exported symbol.
* Otherwise returns its input.
* For example, at `export type T = number;`:
* - `getSymbolAtLocation` at the location `T` will return the exported symbol for `T`.
* - But the result of `getSymbolsInScope` will contain the *local* symbol for `T`, not the exported symbol.
* - Calling `getExportSymbolOfSymbol` on that local symbol will return the exported symbol.
*/
getExportSymbolOfSymbol(symbol: Symbol): Symbol;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol | undefined;
getTypeOfAssignmentPattern(pattern: AssignmentPattern): Type;
getTypeAtLocation(node: Node): Type;
getTypeFromTypeNode(node: TypeNode): Type;
signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string;
typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string;
symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): string;
typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string;
/* @internal */ writeSignature(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind, writer?: EmitTextWriter): string;
/* @internal */ writeType(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags, writer?: EmitTextWriter): string;
/* @internal */ writeSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags, writer?: EmitTextWriter): string;
/* @internal */ writeTypePredicate(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags, writer?: EmitTextWriter): string;
getFullyQualifiedName(symbol: Symbol): string;
getAugmentedPropertiesOfType(type: Type): Symbol[];
getRootSymbols(symbol: Symbol): readonly Symbol[];
getSymbolOfExpando(node: Node, allowDeclaration: boolean): Symbol | undefined;
getContextualType(node: Expression): Type | undefined;
/* @internal */ getContextualType(node: Expression, contextFlags?: ContextFlags): Type | undefined; // eslint-disable-line @typescript-eslint/unified-signatures
/* @internal */ getContextualTypeForObjectLiteralElement(element: ObjectLiteralElementLike): Type | undefined;
/* @internal */ getContextualTypeForArgumentAtIndex(call: CallLikeExpression, argIndex: number): Type | undefined;
/* @internal */ getContextualTypeForJsxAttribute(attribute: JsxAttribute | JsxSpreadAttribute): Type | undefined;
/* @internal */ isContextSensitive(node: Expression | MethodDeclaration | ObjectLiteralElementLike | JsxAttributeLike): boolean;
/* @internal */ getTypeOfPropertyOfContextualType(type: Type, name: __String): Type | undefined;
/**
* returns unknownSignature in the case of an error.
* returns undefined if the node is not valid.
* @param argumentCount Apparent number of arguments, passed in case of a possibly incomplete call. This should come from an ArgumentListInfo. See `signatureHelp.ts`.
*/
getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined;
/* @internal */ getResolvedSignatureForSignatureHelp(node: CallLikeExpression, candidatesOutArray?: Signature[], argumentCount?: number): Signature | undefined;
/* @internal */ getExpandedParameters(sig: Signature): readonly (readonly Symbol[])[];
/* @internal */ hasEffectiveRestParameter(sig: Signature): boolean;
getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature | undefined;
isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined;
isUndefinedSymbol(symbol: Symbol): boolean;
isArgumentsSymbol(symbol: Symbol): boolean;
isUnknownSymbol(symbol: Symbol): boolean;
/* @internal */ getMergedSymbol(symbol: Symbol): Symbol;
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined;
isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): boolean;
/** Exclude accesses to private properties or methods with a `this` parameter that `type` doesn't satisfy. */
/* @internal */ isValidPropertyAccessForCompletions(node: PropertyAccessExpression | ImportTypeNode | QualifiedName, type: Type, property: Symbol): boolean;
/** Follow all aliases to get the original symbol. */
getAliasedSymbol(symbol: Symbol): Symbol;
/** Follow a *single* alias to get the immediately aliased symbol. */
/* @internal */ getImmediateAliasedSymbol(symbol: Symbol): Symbol | undefined;
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
/** Unlike `getExportsOfModule`, this includes properties of an `export =` value. */
/* @internal */ getExportsAndPropertiesOfModule(moduleSymbol: Symbol): Symbol[];
getJsxIntrinsicTagNamesAt(location: Node): Symbol[];
isOptionalParameter(node: ParameterDeclaration): boolean;
getAmbientModules(): Symbol[];
tryGetMemberInModuleExports(memberName: string, moduleSymbol: Symbol): Symbol | undefined;
/**
* Unlike `tryGetMemberInModuleExports`, this includes properties of an `export =` value.
* Does *not* return properties of primitive types.
*/
/* @internal */ tryGetMemberInModuleExportsAndProperties(memberName: string, moduleSymbol: Symbol): Symbol | undefined;
getApparentType(type: Type): Type;
/* @internal */ getSuggestedSymbolForNonexistentProperty(name: MemberName | string, containingType: Type): Symbol | undefined;
/* @internal */ getSuggestedSymbolForNonexistentJSXAttribute(name: Identifier | string, containingType: Type): Symbol | undefined;
/* @internal */ getSuggestionForNonexistentProperty(name: MemberName | string, containingType: Type): string | undefined;
/* @internal */ getSuggestedSymbolForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): Symbol | undefined;
/* @internal */ getSuggestionForNonexistentSymbol(location: Node, name: string, meaning: SymbolFlags): string | undefined;
/* @internal */ getSuggestedSymbolForNonexistentModule(node: Identifier, target: Symbol): Symbol | undefined;
/* @internal */ getSuggestionForNonexistentExport(node: Identifier, target: Symbol): string | undefined;
getBaseConstraintOfType(type: Type): Type | undefined;
getDefaultFromTypeParameter(type: Type): Type | undefined;
/* @internal */ getAnyType(): Type;
/* @internal */ getStringType(): Type;
/* @internal */ getNumberType(): Type;
/* @internal */ getBooleanType(): Type;
/* @internal */ getFalseType(fresh?: boolean): Type;
/* @internal */ getTrueType(fresh?: boolean): Type;
/* @internal */ getVoidType(): Type;
/* @internal */ getUndefinedType(): Type;
/* @internal */ getNullType(): Type;
/* @internal */ getESSymbolType(): Type;
/* @internal */ getNeverType(): Type;
/* @internal */ getOptionalType(): Type;
/* @internal */ getUnionType(types: Type[], subtypeReduction?: UnionReduction): Type;
/* @internal */ createArrayType(elementType: Type): Type;
/* @internal */ getElementTypeOfArrayType(arrayType: Type): Type | undefined;
/* @internal */ createPromiseType(type: Type): Type;
/* @internal */ isTypeAssignableTo(source: Type, target: Type): boolean;
/* @internal */ createAnonymousType(symbol: Symbol | undefined, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexInfo: IndexInfo | undefined, numberIndexInfo: IndexInfo | undefined): Type;
/* @internal */ createSignature(
declaration: SignatureDeclaration,
typeParameters: readonly TypeParameter[] | undefined,
thisParameter: Symbol | undefined,
parameters: readonly Symbol[],
resolvedReturnType: Type,
typePredicate: TypePredicate | undefined,
minArgumentCount: number,
flags: SignatureFlags
): Signature;
/* @internal */ createSymbol(flags: SymbolFlags, name: __String): TransientSymbol;
/* @internal */ createIndexInfo(type: Type, isReadonly: boolean, declaration?: SignatureDeclaration): IndexInfo;
/* @internal */ isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node | undefined, meaning: SymbolFlags, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult;
/* @internal */ tryFindAmbientModule(moduleName: string): Symbol | undefined;
/* @internal */ tryFindAmbientModuleWithoutAugmentations(moduleName: string): Symbol | undefined;
/* @internal */ getSymbolWalker(accept?: (symbol: Symbol) => boolean): SymbolWalker;
// Should not be called directly. Should only be accessed through the Program instance.
/* @internal */ getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[];
/* @internal */ getGlobalDiagnostics(): Diagnostic[];
/* @internal */ getEmitResolver(sourceFile?: SourceFile, cancellationToken?: CancellationToken): EmitResolver;
/* @internal */ getNodeCount(): number;
/* @internal */ getIdentifierCount(): number;
/* @internal */ getSymbolCount(): number;
/* @internal */ getTypeCount(): number;
/* @internal */ getInstantiationCount(): number;
/* @internal */ getRelationCacheSizes(): { assignable: number, identity: number, subtype: number, strictSubtype: number };
/* @internal */ getRecursionIdentity(type: Type): object | undefined;
/* @internal */ isArrayType(type: Type): boolean;
/* @internal */ isTupleType(type: Type): boolean;
/* @internal */ isArrayLikeType(type: Type): boolean;
/**
* True if `contextualType` should not be considered for completions because
* e.g. it specifies `kind: "a"` and obj has `kind: "b"`.
*/
/* @internal */ isTypeInvalidDueToUnionDiscriminant(contextualType: Type, obj: ObjectLiteralExpression | JsxAttributes): boolean;
/**
* For a union, will include a property if it's defined in *any* of the member types.
* So for `{ a } | { b }`, this will include both `a` and `b`.
* Does not include properties of primitive types.
*/
/* @internal */ getAllPossiblePropertiesOfTypes(type: readonly Type[]): Symbol[];
/* @internal */ resolveName(name: string, location: Node | undefined, meaning: SymbolFlags, excludeGlobals: boolean): Symbol | undefined;
/* @internal */ getJsxNamespace(location?: Node): string;
/* @internal */ getJsxFragmentFactory(location: Node): string | undefined;
/**
* Note that this will return undefined in the following case:
* // a.ts
* export namespace N { export class C { } }
* // b.ts
* <<enclosingDeclaration>>
* Where `C` is the symbol we're looking for.
* This should be called in a loop climbing parents of the symbol, so we'll get `N`.
*/
/* @internal */ getAccessibleSymbolChain(symbol: Symbol, enclosingDeclaration: Node | undefined, meaning: SymbolFlags, useOnlyExternalAliasing: boolean): Symbol[] | undefined;
/* @internal */ getTypePredicateOfSignature(signature: Signature): TypePredicate | undefined;
/* @internal */ resolveExternalModuleName(moduleSpecifier: Expression): Symbol | undefined;
/**
* An external module with an 'export =' declaration resolves to the target of the 'export =' declaration,
* and an external module with no 'export =' declaration resolves to the module itself.
*/
/* @internal */ resolveExternalModuleSymbol(symbol: Symbol): Symbol;
/** @param node A location where we might consider accessing `this`. Not necessarily a ThisExpression. */
/* @internal */ tryGetThisTypeAt(node: Node, includeGlobalThis?: boolean): Type | undefined;
/* @internal */ getTypeArgumentConstraint(node: TypeNode): Type | undefined;
/**
* Does *not* get *all* suggestion diagnostics, just the ones that were convenient to report in the checker.
* Others are added in computeSuggestionDiagnostics.
*/
/* @internal */ getSuggestionDiagnostics(file: SourceFile, cancellationToken?: CancellationToken): readonly DiagnosticWithLocation[];
/**
* Depending on the operation performed, it may be appropriate to throw away the checker
* if the cancellation token is triggered. Typically, if it is used for error checking
* and the operation is cancelled, then it should be discarded, otherwise it is safe to keep.
*/
runWithCancellationToken<T>(token: CancellationToken, cb: (checker: TypeChecker) => T): T;
/* @internal */ getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol: Symbol): readonly TypeParameter[] | undefined;
/* @internal */ isDeclarationVisible(node: Declaration | AnyImportSyntax): boolean;
}
/* @internal */
export const enum UnionReduction {
None = 0,
Literal,
Subtype,
}
/* @internal */
export const enum ContextFlags {
None = 0,
Signature = 1 << 0, // Obtaining contextual signature
NoConstraints = 1 << 1, // Don't obtain type variable constraints
Completions = 1 << 2, // Ignore inference to current node and parent nodes out to the containing call for completions
SkipBindingPatterns = 1 << 3, // Ignore contextual types applied by binding patterns
}
// NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
export const enum NodeBuilderFlags {
None = 0,
// Options
NoTruncation = 1 << 0, // Don't truncate result
WriteArrayAsGenericType = 1 << 1, // Write Array<T> instead T[]
GenerateNamesForShadowedTypeParams = 1 << 2, // When a type parameter T is shadowing another T, generate a name for it so it can still be referenced
UseStructuralFallback = 1 << 3, // When an alias cannot be named by its symbol, rather than report an error, fallback to a structural printout if possible
ForbidIndexedAccessSymbolReferences = 1 << 4, // Forbid references like `I["a"]["b"]` - print `typeof I.a<x>.b<y>` instead
WriteTypeArgumentsOfSignature = 1 << 5, // Write the type arguments instead of type parameters of the signature
UseFullyQualifiedType = 1 << 6, // Write out the fully qualified type name (eg. Module.Type, instead of Type)
UseOnlyExternalAliasing = 1 << 7, // Only use external aliases for a symbol
SuppressAnyReturnType = 1 << 8, // If the return type is any-like and can be elided, don't offer a return type.
WriteTypeParametersInQualifiedName = 1 << 9,
MultilineObjectLiterals = 1 << 10, // Always write object literals across multiple lines
WriteClassExpressionAsTypeLiteral = 1 << 11, // Write class {} as { new(): {} } - used for mixin declaration emit
UseTypeOfFunction = 1 << 12, // Build using typeof instead of function type literal
OmitParameterModifiers = 1 << 13, // Omit modifiers on parameters
UseAliasDefinedOutsideCurrentScope = 1 << 14, // Allow non-visible aliases
UseSingleQuotesForStringLiteralType = 1 << 28, // Use single quotes for string literal type
NoTypeReduction = 1 << 29, // Don't call getReducedType
NoUndefinedOptionalParameterType = 1 << 30, // Do not add undefined to optional parameter type
// Error handling
AllowThisInObjectLiteral = 1 << 15,
AllowQualifiedNameInPlaceOfIdentifier = 1 << 16,
/** @deprecated AllowQualifedNameInPlaceOfIdentifier. Use AllowQualifiedNameInPlaceOfIdentifier instead. */
AllowQualifedNameInPlaceOfIdentifier = AllowQualifiedNameInPlaceOfIdentifier,
AllowAnonymousIdentifier = 1 << 17,
AllowEmptyUnionOrIntersection = 1 << 18,
AllowEmptyTuple = 1 << 19,
AllowUniqueESSymbolType = 1 << 20,
AllowEmptyIndexInfoType = 1 << 21,
// Errors (cont.)
AllowNodeModulesRelativePaths = 1 << 26,
/* @internal */ DoNotIncludeSymbolChain = 1 << 27, // Skip looking up and printing an accessible symbol chain
IgnoreErrors = AllowThisInObjectLiteral | AllowQualifiedNameInPlaceOfIdentifier | AllowAnonymousIdentifier | AllowEmptyUnionOrIntersection | AllowEmptyTuple | AllowEmptyIndexInfoType | AllowNodeModulesRelativePaths,
// State
InObjectTypeLiteral = 1 << 22,
InTypeAlias = 1 << 23, // Writing type in type alias declaration
InInitialEntityName = 1 << 24, // Set when writing the LHS of an entity name or entity name expression
}
// Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
export const enum TypeFormatFlags {
None = 0,
NoTruncation = 1 << 0, // Don't truncate typeToString result
WriteArrayAsGenericType = 1 << 1, // Write Array<T> instead T[]
// hole because there's a hole in node builder flags
UseStructuralFallback = 1 << 3, // When an alias cannot be named by its symbol, rather than report an error, fallback to a structural printout if possible
// hole because there's a hole in node builder flags
WriteTypeArgumentsOfSignature = 1 << 5, // Write the type arguments instead of type parameters of the signature
UseFullyQualifiedType = 1 << 6, // Write out the fully qualified type name (eg. Module.Type, instead of Type)
// hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead
SuppressAnyReturnType = 1 << 8, // If the return type is any-like, don't offer a return type.
// hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead
MultilineObjectLiterals = 1 << 10, // Always print object literals across multiple lines (only used to map into node builder flags)
WriteClassExpressionAsTypeLiteral = 1 << 11, // Write a type literal instead of (Anonymous class)
UseTypeOfFunction = 1 << 12, // Write typeof instead of function type literal
OmitParameterModifiers = 1 << 13, // Omit modifiers on parameters
UseAliasDefinedOutsideCurrentScope = 1 << 14, // For a `type T = ... ` defined in a different file, write `T` instead of its value, even though `T` can't be accessed in the current scope.
UseSingleQuotesForStringLiteralType = 1 << 28, // Use single quotes for string literal type
NoTypeReduction = 1 << 29, // Don't call getReducedType
// Error Handling
AllowUniqueESSymbolType = 1 << 20, // This is bit 20 to align with the same bit in `NodeBuilderFlags`
// TypeFormatFlags exclusive
AddUndefined = 1 << 17, // Add undefined to types of initialized, non-optional parameters
WriteArrowStyleSignature = 1 << 18, // Write arrow style signature
// State
InArrayType = 1 << 19, // Writing an array element type
InElementType = 1 << 21, // Writing an array or union element type
InFirstTypeArgument = 1 << 22, // Writing first type argument of the instantiated type
InTypeAlias = 1 << 23, // Writing type in type alias declaration
/** @deprecated */ WriteOwnNameForAnyLike = 0, // Does nothing
NodeBuilderFlagsMask = NoTruncation | WriteArrayAsGenericType | UseStructuralFallback | WriteTypeArgumentsOfSignature |
UseFullyQualifiedType | SuppressAnyReturnType | MultilineObjectLiterals | WriteClassExpressionAsTypeLiteral |
UseTypeOfFunction | OmitParameterModifiers | UseAliasDefinedOutsideCurrentScope | AllowUniqueESSymbolType | InTypeAlias |
UseSingleQuotesForStringLiteralType | NoTypeReduction,
}
export const enum SymbolFormatFlags {
None = 0x00000000,
// Write symbols's type argument if it is instantiated symbol
// eg. class C<T> { p: T } <-- Show p as C<T>.p here
// var a: C<number>;
// var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p
WriteTypeParametersOrArguments = 0x00000001,
// Use only external alias information to get the symbol name in the given context
// eg. module m { export class c { } } import x = m.c;
// When this flag is specified m.c will be used to refer to the class instead of alias symbol x
UseOnlyExternalAliasing = 0x00000002,
// Build symbol name using any nodes needed, instead of just components of an entity name
AllowAnyNodeKind = 0x00000004,
// Prefer aliases which are not directly visible
UseAliasDefinedOutsideCurrentScope = 0x00000008,
// Skip building an accessible symbol chain
/* @internal */ DoNotIncludeSymbolChain = 0x00000010,
}
/* @internal */
export interface SymbolWalker {
/** Note: Return values are not ordered. */
walkType(root: Type): { visitedTypes: readonly Type[], visitedSymbols: readonly Symbol[] };
/** Note: Return values are not ordered. */
walkSymbol(root: Symbol): { visitedTypes: readonly Type[], visitedSymbols: readonly Symbol[] };
}
// This was previously deprecated in our public API, but is still used internally
/* @internal */
interface SymbolWriter extends SymbolTracker {
writeKeyword(text: string): void;
writeOperator(text: string): void;
writePunctuation(text: string): void;
writeSpace(text: string): void;
writeStringLiteral(text: string): void;
writeParameter(text: string): void;
writeProperty(text: string): void;
writeSymbol(text: string, symbol: Symbol): void;
writeLine(force?: boolean): void;
increaseIndent(): void;
decreaseIndent(): void;
clear(): void;
}
/* @internal */
export const enum SymbolAccessibility {
Accessible,
NotAccessible,
CannotBeNamed
}
/* @internal */
export const enum SyntheticSymbolKind {
UnionOrIntersection,
Spread
}
export const enum TypePredicateKind {
This,
Identifier,
AssertsThis,
AssertsIdentifier
}
export interface TypePredicateBase {
kind: TypePredicateKind;
type: Type | undefined;
}
export interface ThisTypePredicate extends TypePredicateBase {
kind: TypePredicateKind.This;
parameterName: undefined;
parameterIndex: undefined;
type: Type;
}
export interface IdentifierTypePredicate extends TypePredicateBase {
kind: TypePredicateKind.Identifier;
parameterName: string;
parameterIndex: number;
type: Type;
}
export interface AssertsThisTypePredicate extends TypePredicateBase {
kind: TypePredicateKind.AssertsThis;
parameterName: undefined;
parameterIndex: undefined;
type: Type | undefined;
}
export interface AssertsIdentifierTypePredicate extends TypePredicateBase {
kind: TypePredicateKind.AssertsIdentifier;
parameterName: string;
parameterIndex: number;
type: Type | undefined;
}
export type TypePredicate = ThisTypePredicate | IdentifierTypePredicate | AssertsThisTypePredicate | AssertsIdentifierTypePredicate;
/* @internal */
export type AnyImportSyntax = ImportDeclaration | ImportEqualsDeclaration;
/* @internal */
export type AnyImportOrRequire = AnyImportSyntax | RequireVariableDeclaration;
/* @internal */
export type AnyImportOrRequireStatement = AnyImportSyntax | RequireVariableStatement;
/* @internal */
export type AnyImportOrReExport = AnyImportSyntax | ExportDeclaration;
/* @internal */
export interface ValidImportTypeNode extends ImportTypeNode {
argument: LiteralTypeNode & { literal: StringLiteral };
}
/* @internal */
export type AnyValidImportOrReExport =
| (ImportDeclaration | ExportDeclaration) & { moduleSpecifier: StringLiteral }
| ImportEqualsDeclaration & { moduleReference: ExternalModuleReference & { expression: StringLiteral } }
| RequireOrImportCall
| ValidImportTypeNode;
/* @internal */
export type RequireOrImportCall = CallExpression & { expression: Identifier, arguments: [StringLiteralLike] };
/* @internal */
export interface RequireVariableDeclaration extends VariableDeclaration {
readonly initializer: RequireOrImportCall;
}
/* @internal */
export interface RequireVariableStatement extends VariableStatement {
readonly declarationList: RequireVariableDeclarationList;
}
/* @internal */
export interface RequireVariableDeclarationList extends VariableDeclarationList {
readonly declarations: NodeArray<RequireVariableDeclaration>;
}
/* @internal */
export type LateVisibilityPaintedStatement =
| AnyImportSyntax
| VariableStatement
| ClassDeclaration
| FunctionDeclaration
| ModuleDeclaration
| TypeAliasDeclaration
| InterfaceDeclaration
| EnumDeclaration;
/* @internal */
export interface SymbolVisibilityResult {
accessibility: SymbolAccessibility;
aliasesToMakeVisible?: LateVisibilityPaintedStatement[]; // aliases that need to have this symbol visible
errorSymbolName?: string; // Optional symbol name that results in error
errorNode?: Node; // optional node that results in error
}
/* @internal */
export interface SymbolAccessibilityResult extends SymbolVisibilityResult {
errorModuleName?: string; // If the symbol is not visible from module, module's name
}
/* @internal */
export interface AllAccessorDeclarations {
firstAccessor: AccessorDeclaration;
secondAccessor: AccessorDeclaration | undefined;
getAccessor: GetAccessorDeclaration | undefined;
setAccessor: SetAccessorDeclaration | undefined;
}
/** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */
/* @internal */
export enum TypeReferenceSerializationKind {
// The TypeReferenceNode could not be resolved.
// The type name should be emitted using a safe fallback.
Unknown,
// The TypeReferenceNode resolves to a type with a constructor
// function that can be reached at runtime (e.g. a `class`
// declaration or a `var` declaration for the static side
// of a type, such as the global `Promise` type in lib.d.ts).
TypeWithConstructSignatureAndValue,
// The TypeReferenceNode resolves to a Void-like, Nullable, or Never type.
VoidNullableOrNeverType,
// The TypeReferenceNode resolves to a Number-like type.
NumberLikeType,
// The TypeReferenceNode resolves to a BigInt-like type.
BigIntLikeType,
// The TypeReferenceNode resolves to a String-like type.
StringLikeType,
// The TypeReferenceNode resolves to a Boolean-like type.
BooleanType,
// The TypeReferenceNode resolves to an Array-like type.
ArrayLikeType,
// The TypeReferenceNode resolves to the ESSymbol type.
ESSymbolType,
// The TypeReferenceNode resolved to the global Promise constructor symbol.
Promise,
// The TypeReferenceNode resolves to a Function type or a type with call signatures.
TypeWithCallSignature,
// The TypeReferenceNode resolves to any other type.
ObjectType,
}
/* @internal */
export interface EmitResolver {
hasGlobalName(name: string): boolean;
getReferencedExportContainer(node: Identifier, prefixLocals?: boolean): SourceFile | ModuleDeclaration | EnumDeclaration | undefined;
getReferencedImportDeclaration(node: Identifier): Declaration | undefined;
getReferencedDeclarationWithCollidingName(node: Identifier): Declaration | undefined;
isDeclarationWithCollidingName(node: Declaration): boolean;
isValueAliasDeclaration(node: Node): boolean;
isReferencedAliasDeclaration(node: Node, checkChildren?: boolean): boolean;
isTopLevelValueImportEqualsWithEntityName(node: ImportEqualsDeclaration): boolean;
getNodeCheckFlags(node: Node): NodeCheckFlags;
isDeclarationVisible(node: Declaration | AnyImportSyntax): boolean;
isLateBound(node: Declaration): node is LateBoundDeclaration;
collectLinkedAliases(node: Identifier, setVisibility?: boolean): Node[] | undefined;
isImplementationOfOverload(node: SignatureDeclaration): boolean | undefined;
isRequiredInitializedParameter(node: ParameterDeclaration): boolean;
isOptionalUninitializedParameterProperty(node: ParameterDeclaration): boolean;
isExpandoFunctionDeclaration(node: FunctionDeclaration): boolean;
getPropertiesOfContainerFunction(node: Declaration): Symbol[];
createTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration | PropertyAccessExpression, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker, addUndefined?: boolean): TypeNode | undefined;
createReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker): TypeNode | undefined;
createTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker): TypeNode | undefined;
createLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration, tracker: SymbolTracker): Expression;
isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node | undefined, meaning: SymbolFlags | undefined, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult;
isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult;
// Returns the constant value this property access resolves to, or 'undefined' for a non-constant
getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): string | number | undefined;
getReferencedValueDeclaration(reference: Identifier): Declaration | undefined;
getTypeReferenceSerializationKind(typeName: EntityName, location?: Node): TypeReferenceSerializationKind;
isOptionalParameter(node: ParameterDeclaration): boolean;
moduleExportsSomeValue(moduleReferenceExpression: Expression): boolean;
isArgumentsLocalBinding(node: Identifier): boolean;
getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration | ImportTypeNode | ImportCall): SourceFile | undefined;
getTypeReferenceDirectivesForEntityName(name: EntityNameOrEntityNameExpression): string[] | undefined;
getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[] | undefined;
isLiteralConstDeclaration(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): boolean;
getJsxFactoryEntity(location?: Node): EntityName | undefined;
getJsxFragmentFactoryEntity(location?: Node): EntityName | undefined;
getAllAccessorDeclarations(declaration: AccessorDeclaration): AllAccessorDeclarations;
getSymbolOfExternalModuleSpecifier(node: StringLiteralLike): Symbol | undefined;
isBindingCapturedByNode(node: Node, decl: VariableDeclaration | BindingElement): boolean;
getDeclarationStatementsForSourceFile(node: SourceFile, flags: NodeBuilderFlags, tracker: SymbolTracker, bundled?: boolean): Statement[] | undefined;
isImportRequiredByAugmentation(decl: ImportDeclaration): boolean;
}
export const enum SymbolFlags {
None = 0,
FunctionScopedVariable = 1 << 0, // Variable (var) or parameter
BlockScopedVariable = 1 << 1, // A block-scoped variable (let or const)
Property = 1 << 2, // Property or enum member
EnumMember = 1 << 3, // Enum member
Function = 1 << 4, // Function
Class = 1 << 5, // Class
Interface = 1 << 6, // Interface
ConstEnum = 1 << 7, // Const enum
RegularEnum = 1 << 8, // Enum
ValueModule = 1 << 9, // Instantiated module
NamespaceModule = 1 << 10, // Uninstantiated module
TypeLiteral = 1 << 11, // Type Literal or mapped type
ObjectLiteral = 1 << 12, // Object Literal
Method = 1 << 13, // Method
Constructor = 1 << 14, // Constructor
GetAccessor = 1 << 15, // Get accessor
SetAccessor = 1 << 16, // Set accessor
Signature = 1 << 17, // Call, construct, or index signature
TypeParameter = 1 << 18, // Type parameter
TypeAlias = 1 << 19, // Type alias
ExportValue = 1 << 20, // Exported value marker (see comment in declareModuleMember in binder)
Alias = 1 << 21, // An alias for another symbol (see comment in isAliasSymbolDeclaration in checker)
Prototype = 1 << 22, // Prototype property (no source representation)
ExportStar = 1 << 23, // Export * declaration
Optional = 1 << 24, // Optional property
Transient = 1 << 25, // Transient symbol (created during type check)
Assignment = 1 << 26, // Assignment treated as declaration (eg `this.prop = 1`)
ModuleExports = 1 << 27, // Symbol for CommonJS `module` of `module.exports`
/* @internal */
All = FunctionScopedVariable | BlockScopedVariable | Property | EnumMember | Function | Class | Interface | ConstEnum | RegularEnum | ValueModule | NamespaceModule | TypeLiteral
| ObjectLiteral | Method | Constructor | GetAccessor | SetAccessor | Signature | TypeParameter | TypeAlias | ExportValue | Alias | Prototype | ExportStar | Optional | Transient,
Enum = RegularEnum | ConstEnum,
Variable = FunctionScopedVariable | BlockScopedVariable,
Value = Variable | Property | EnumMember | ObjectLiteral | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor,
Type = Class | Interface | Enum | EnumMember | TypeLiteral | TypeParameter | TypeAlias,
Namespace = ValueModule | NamespaceModule | Enum,
Module = ValueModule | NamespaceModule,
Accessor = GetAccessor | SetAccessor,
// Variables can be redeclared, but can not redeclare a block-scoped declaration with the
// same name, or any other value that is not a variable, e.g. ValueModule or Class
FunctionScopedVariableExcludes = Value & ~FunctionScopedVariable,
// Block-scoped declarations are not allowed to be re-declared
// they can not merge with anything in the value space
BlockScopedVariableExcludes = Value,
ParameterExcludes = Value,
PropertyExcludes = None,
EnumMemberExcludes = Value | Type,
FunctionExcludes = Value & ~(Function | ValueModule | Class),
ClassExcludes = (Value | Type) & ~(ValueModule | Interface | Function), // class-interface mergability done in checker.ts
InterfaceExcludes = Type & ~(Interface | Class),
RegularEnumExcludes = (Value | Type) & ~(RegularEnum | ValueModule), // regular enums merge only with regular enums and modules
ConstEnumExcludes = (Value | Type) & ~ConstEnum, // const enums merge only with const enums
ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule),
NamespaceModuleExcludes = 0,
MethodExcludes = Value & ~Method,
GetAccessorExcludes = Value & ~SetAccessor,
SetAccessorExcludes = Value & ~GetAccessor,
TypeParameterExcludes = Type & ~TypeParameter,
TypeAliasExcludes = Type,
AliasExcludes = Alias,
ModuleMember = Variable | Function | Class | Interface | Enum | Module | TypeAlias | Alias,
ExportHasLocal = Function | Class | Enum | ValueModule,
BlockScoped = BlockScopedVariable | Class | Enum,
PropertyOrAccessor = Property | Accessor,
ClassMember = Method | Accessor | Property,
/* @internal */
ExportSupportsDefaultModifier = Class | Function | Interface,
/* @internal */
ExportDoesNotSupportDefaultModifier = ~ExportSupportsDefaultModifier,
/* @internal */
// The set of things we consider semantically classifiable. Used to speed up the LS during
// classification.
Classifiable = Class | Enum | TypeAlias | Interface | TypeParameter | Module | Alias,
/* @internal */
LateBindingContainer = Class | Interface | TypeLiteral | ObjectLiteral | Function,
}
/* @internal */
export type SymbolId = number;
export interface Symbol {
flags: SymbolFlags; // Symbol flags
escapedName: __String; // Name of symbol
declarations?: Declaration[]; // Declarations associated with this symbol
valueDeclaration?: Declaration; // First value declaration of the symbol
members?: SymbolTable; // Class, interface or object literal instance members
exports?: SymbolTable; // Module exports
globalExports?: SymbolTable; // Conditional global UMD exports
/* @internal */ id?: SymbolId; // Unique id (used to look up SymbolLinks)
/* @internal */ mergeId?: number; // Merge id (used to look up merged symbol)
/* @internal */ parent?: Symbol; // Parent symbol
/* @internal */ exportSymbol?: Symbol; // Exported symbol associated with this symbol
/* @internal */ constEnumOnlyModule?: boolean; // True if module contains only const enums or other modules with only const enums
/* @internal */ isReferenced?: SymbolFlags; // True if the symbol is referenced elsewhere. Keeps track of the meaning of a reference in case a symbol is both a type parameter and parameter.
/* @internal */ isReplaceableByMethod?: boolean; // Can this Javascript class property be replaced by a method symbol?
/* @internal */ isAssigned?: boolean; // True if the symbol is a parameter with assignments
/* @internal */ assignmentDeclarationMembers?: ESMap<number, Declaration>; // detected late-bound assignment declarations associated with the symbol
}
/* @internal */
export interface SymbolLinks {
immediateTarget?: Symbol; // Immediate target of an alias. May be another alias. Do not access directly, use `checker.getImmediateAliasedSymbol` instead.
target?: Symbol; // Resolved (non-alias) target of an alias
type?: Type; // Type of value symbol
writeType?: Type; // Type of value symbol in write contexts
nameType?: Type; // Type associated with a late-bound symbol
uniqueESSymbolType?: Type; // UniqueESSymbol type for a symbol
declaredType?: Type; // Type of class, interface, enum, type alias, or type parameter
typeParameters?: TypeParameter[]; // Type parameters of type alias (undefined if non-generic)
outerTypeParameters?: TypeParameter[]; // Outer type parameters of anonymous object type
instantiations?: ESMap<string, Type>; // Instantiations of generic type alias (undefined if non-generic)
aliasSymbol?: Symbol; // Alias associated with generic type alias instantiation
aliasTypeArguments?: readonly Type[] // Alias type arguments (if any)
inferredClassSymbol?: ESMap<SymbolId, TransientSymbol>; // Symbol of an inferred ES5 constructor function
mapper?: TypeMapper; // Type mapper for instantiation alias
referenced?: boolean; // True if alias symbol has been referenced as a value that can be emitted
constEnumReferenced?: boolean; // True if alias symbol resolves to a const enum and is referenced as a value ('referenced' will be false)
containingType?: UnionOrIntersectionType; // Containing union or intersection type for synthetic property
leftSpread?: Symbol; // Left source for synthetic spread property
rightSpread?: Symbol; // Right source for synthetic spread property
syntheticOrigin?: Symbol; // For a property on a mapped or spread type, points back to the original property
isDiscriminantProperty?: boolean; // True if discriminant synthetic property
resolvedExports?: SymbolTable; // Resolved exports of module or combined early- and late-bound static members of a class.
resolvedMembers?: SymbolTable; // Combined early- and late-bound members of a symbol
exportsChecked?: boolean; // True if exports of external module have been checked
typeParametersChecked?: boolean; // True if type parameters of merged class and interface declarations have been checked.
isDeclarationWithCollidingName?: boolean; // True if symbol is block scoped redeclaration
bindingElement?: BindingElement; // Binding element associated with property symbol
exportsSomeValue?: boolean; // True if module exports some value (not just types)
enumKind?: EnumKind; // Enum declaration classification
originatingImport?: ImportDeclaration | ImportCall; // Import declaration which produced the symbol, present if the symbol is marked as uncallable but had call signatures in `resolveESModuleSymbol`
lateSymbol?: Symbol; // Late-bound symbol for a computed property
specifierCache?: ESMap<string, string>; // For symbols corresponding to external modules, a cache of incoming path -> module specifier name mappings
extendedContainers?: Symbol[]; // Containers (other than the parent) which this symbol is aliased in
extendedContainersByFile?: ESMap<NodeId, Symbol[]>; // Containers (other than the parent) which this symbol is aliased in
variances?: VarianceFlags[]; // Alias symbol type argument variance cache
deferralConstituents?: Type[]; // Calculated list of constituents for a deferred type
deferralParent?: Type; // Source union/intersection of a deferred type
cjsExportMerged?: Symbol; // Version of the symbol with all non export= exports merged with the export= target
typeOnlyDeclaration?: TypeOnlyCompatibleAliasDeclaration | false; // First resolved alias declaration that makes the symbol only usable in type constructs
isConstructorDeclaredProperty?: boolean; // Property declared through 'this.x = ...' assignment in constructor
tupleLabelDeclaration?: NamedTupleMember | ParameterDeclaration; // Declaration associated with the tuple's label
}
/* @internal */
export const enum EnumKind {
Numeric, // Numeric enum (each member has a TypeFlags.Enum type)
Literal // Literal enum (each member has a TypeFlags.EnumLiteral type)
}
/* @internal */
export const enum CheckFlags {
Instantiated = 1 << 0, // Instantiated symbol
SyntheticProperty = 1 << 1, // Property in union or intersection type
SyntheticMethod = 1 << 2, // Method in union or intersection type
Readonly = 1 << 3, // Readonly transient symbol
ReadPartial = 1 << 4, // Synthetic property present in some but not all constituents
WritePartial = 1 << 5, // Synthetic property present in some but only satisfied by an index signature in others
HasNonUniformType = 1 << 6, // Synthetic property with non-uniform type in constituents
HasLiteralType = 1 << 7, // Synthetic property with at least one literal type in constituents
ContainsPublic = 1 << 8, // Synthetic property with public constituent(s)
ContainsProtected = 1 << 9, // Synthetic property with protected constituent(s)
ContainsPrivate = 1 << 10, // Synthetic property with private constituent(s)
ContainsStatic = 1 << 11, // Synthetic property with static constituent(s)
Late = 1 << 12, // Late-bound symbol for a computed property with a dynamic name
ReverseMapped = 1 << 13, // Property of reverse-inferred homomorphic mapped type
OptionalParameter = 1 << 14, // Optional parameter
RestParameter = 1 << 15, // Rest parameter
DeferredType = 1 << 16, // Calculation of the type of this symbol is deferred due to processing costs, should be fetched with `getTypeOfSymbolWithDeferredType`
HasNeverType = 1 << 17, // Synthetic property with at least one never type in constituents
Mapped = 1 << 18, // Property of mapped type
StripOptional = 1 << 19, // Strip optionality in mapped property
Synthetic = SyntheticProperty | SyntheticMethod,
Discriminant = HasNonUniformType | HasLiteralType,
Partial = ReadPartial | WritePartial
}
/* @internal */
export interface TransientSymbol extends Symbol, SymbolLinks {
checkFlags: CheckFlags;
}
/* @internal */
export interface MappedSymbol extends TransientSymbol {
mappedType: MappedType;
keyType: Type;
}
/* @internal */
export interface ReverseMappedSymbol extends TransientSymbol {
propertyType: Type;
mappedType: MappedType;
constraintType: IndexType;
}
export const enum InternalSymbolName {
Call = "__call", // Call signatures
Constructor = "__constructor", // Constructor implementations
New = "__new", // Constructor signatures
Index = "__index", // Index signatures
ExportStar = "__export", // Module export * declarations
Global = "__global", // Global self-reference
Missing = "__missing", // Indicates missing symbol
Type = "__type", // Anonymous type literal symbol
Object = "__object", // Anonymous object literal declaration
JSXAttributes = "__jsxAttributes", // Anonymous JSX attributes object literal declaration
Class = "__class", // Unnamed class expression
Function = "__function", // Unnamed function expression
Computed = "__computed", // Computed property name declaration with dynamic name
Resolving = "__resolving__", // Indicator symbol used to mark partially resolved type aliases
ExportEquals = "export=", // Export assignment symbol
Default = "default", // Default export symbol (technically not wholly internal, but included here for usability)
This = "this",
}
/**
* This represents a string whose leading underscore have been escaped by adding extra leading underscores.
* The shape of this brand is rather unique compared to others we've used.
* Instead of just an intersection of a string and an object, it is that union-ed
* with an intersection of void and an object. This makes it wholly incompatible
* with a normal string (which is good, it cannot be misused on assignment or on usage),
* while still being comparable with a normal string via === (also good) and castable from a string.
*/
export type __String = (string & { __escapedIdentifier: void }) | (void & { __escapedIdentifier: void }) | InternalSymbolName; // eslint-disable-line @typescript-eslint/naming-convention
/** ReadonlyMap where keys are `__String`s. */
export interface ReadonlyUnderscoreEscapedMap<T> extends ReadonlyESMap<__String, T> {
}
/** Map where keys are `__String`s. */
export interface UnderscoreEscapedMap<T> extends ESMap<__String, T>, ReadonlyUnderscoreEscapedMap<T> {
}
/** SymbolTable based on ES6 Map interface. */
export type SymbolTable = UnderscoreEscapedMap<Symbol>;
/** Used to track a `declare module "foo*"`-like declaration. */
/* @internal */
export interface PatternAmbientModule {
pattern: Pattern;
symbol: Symbol;
}
/* @internal */
export const enum NodeCheckFlags {
TypeChecked = 0x00000001, // Node has been type checked
LexicalThis = 0x00000002, // Lexical 'this' reference
CaptureThis = 0x00000004, // Lexical 'this' used in body
CaptureNewTarget = 0x00000008, // Lexical 'new.target' used in body
SuperInstance = 0x00000100, // Instance 'super' reference
SuperStatic = 0x00000200, // Static 'super' reference
ContextChecked = 0x00000400, // Contextual types have been assigned
AsyncMethodWithSuper = 0x00000800, // An async method that reads a value from a member of 'super'.
AsyncMethodWithSuperBinding = 0x00001000, // An async method that assigns a value to a member of 'super'.
CaptureArguments = 0x00002000, // Lexical 'arguments' used in body
EnumValuesComputed = 0x00004000, // Values for enum members have been computed, and any errors have been reported for them.
LexicalModuleMergesWithClass = 0x00008000, // Instantiated lexical module declaration is merged with a previous class declaration.
LoopWithCapturedBlockScopedBinding = 0x00010000, // Loop that contains block scoped variable captured in closure
ContainsCapturedBlockScopeBinding = 0x00020000, // Part of a loop that contains block scoped variable captured in closure
CapturedBlockScopedBinding = 0x00040000, // Block-scoped binding that is captured in some function
BlockScopedBindingInLoop = 0x00080000, // Block-scoped binding with declaration nested inside iteration statement
ClassWithBodyScopedClassBinding = 0x00100000, // Decorated class that contains a binding to itself inside of the class body.
BodyScopedClassBinding = 0x00200000, // Binding to a decorated class inside of the class's body.
NeedsLoopOutParameter = 0x00400000, // Block scoped binding whose value should be explicitly copied outside of the converted loop
AssignmentsMarked = 0x00800000, // Parameter assignments have been marked
ClassWithConstructorReference = 0x01000000, // Class that contains a binding to its constructor inside of the class body.
ConstructorReferenceInClass = 0x02000000, // Binding to a class constructor inside of the class's body.
ContainsClassWithPrivateIdentifiers = 0x04000000, // Marked on all block-scoped containers containing a class with private identifiers.
}
/* @internal */
export interface NodeLinks {
flags: NodeCheckFlags; // Set of flags specific to Node
resolvedType?: Type; // Cached type of type node
resolvedEnumType?: Type; // Cached constraint type from enum jsdoc tag
resolvedSignature?: Signature; // Cached signature of signature node or call expression
resolvedSymbol?: Symbol; // Cached name resolution result
resolvedIndexInfo?: IndexInfo; // Cached indexing info resolution result
effectsSignature?: Signature; // Signature with possible control flow effects
enumMemberValue?: string | number; // Constant value of enum member
isVisible?: boolean; // Is this node visible
containsArgumentsReference?: boolean; // Whether a function-like declaration contains an 'arguments' reference
hasReportedStatementInAmbientContext?: boolean; // Cache boolean if we report statements in ambient context
jsxFlags: JsxFlags; // flags for knowing what kind of element/attributes we're dealing with
resolvedJsxElementAttributesType?: Type; // resolved element attributes type of a JSX openinglike element
resolvedJsxElementAllAttributesType?: Type; // resolved all element attributes type of a JSX openinglike element
resolvedJSDocType?: Type; // Resolved type of a JSDoc type reference
switchTypes?: Type[]; // Cached array of switch case expression types
jsxNamespace?: Symbol | false; // Resolved jsx namespace symbol for this node
jsxImplicitImportContainer?: Symbol | false; // Resolved module symbol the implicit jsx import of this file should refer to
contextFreeType?: Type; // Cached context-free type used by the first pass of inference; used when a function's return is partially contextually sensitive
deferredNodes?: ESMap<NodeId, Node>; // Set of nodes whose checking has been deferred
capturedBlockScopeBindings?: Symbol[]; // Block-scoped bindings captured beneath this part of an IterationStatement
outerTypeParameters?: TypeParameter[]; // Outer type parameters of anonymous object type
isExhaustive?: boolean; // Is node an exhaustive switch statement
skipDirectInference?: true; // Flag set by the API `getContextualType` call on a node when `Completions` is passed to force the checker to skip making inferences to a node's type
declarationRequiresScopeChange?: boolean; // Set by `useOuterVariableScopeInParameter` in checker when downlevel emit would change the name resolution scope inside of a parameter.
}
export const enum TypeFlags {
Any = 1 << 0,
Unknown = 1 << 1,
String = 1 << 2,
Number = 1 << 3,
Boolean = 1 << 4,
Enum = 1 << 5,
BigInt = 1 << 6,
StringLiteral = 1 << 7,
NumberLiteral = 1 << 8,
BooleanLiteral = 1 << 9,
EnumLiteral = 1 << 10, // Always combined with StringLiteral, NumberLiteral, or Union
BigIntLiteral = 1 << 11,
ESSymbol = 1 << 12, // Type of symbol primitive introduced in ES6
UniqueESSymbol = 1 << 13, // unique symbol
Void = 1 << 14,
Undefined = 1 << 15,
Null = 1 << 16,
Never = 1 << 17, // Never type
TypeParameter = 1 << 18, // Type parameter
Object = 1 << 19, // Object type
Union = 1 << 20, // Union (T | U)
Intersection = 1 << 21, // Intersection (T & U)
Index = 1 << 22, // keyof T
IndexedAccess = 1 << 23, // T[K]
Conditional = 1 << 24, // T extends U ? X : Y
Substitution = 1 << 25, // Type parameter substitution
NonPrimitive = 1 << 26, // intrinsic object type
TemplateLiteral = 1 << 27, // Template literal type
StringMapping = 1 << 28, // Uppercase/Lowercase type
/* @internal */
AnyOrUnknown = Any | Unknown,
/* @internal */
Nullable = Undefined | Null,
Literal = StringLiteral | NumberLiteral | BigIntLiteral | BooleanLiteral,
Unit = Literal | UniqueESSymbol | Nullable,
StringOrNumberLiteral = StringLiteral | NumberLiteral,
/* @internal */
StringOrNumberLiteralOrUnique = StringLiteral | NumberLiteral | UniqueESSymbol,
/* @internal */
DefinitelyFalsy = StringLiteral | NumberLiteral | BigIntLiteral | BooleanLiteral | Void | Undefined | Null,
PossiblyFalsy = DefinitelyFalsy | String | Number | BigInt | Boolean,
/* @internal */
Intrinsic = Any | Unknown | String | Number | BigInt | Boolean | BooleanLiteral | ESSymbol | Void | Undefined | Null | Never | NonPrimitive,
/* @internal */
Primitive = String | Number | BigInt | Boolean | Enum | EnumLiteral | ESSymbol | Void | Undefined | Null | Literal | UniqueESSymbol,
StringLike = String | StringLiteral | TemplateLiteral | StringMapping,
NumberLike = Number | NumberLiteral | Enum,
BigIntLike = BigInt | BigIntLiteral,
BooleanLike = Boolean | BooleanLiteral,
EnumLike = Enum | EnumLiteral,
ESSymbolLike = ESSymbol | UniqueESSymbol,
VoidLike = Void | Undefined,
/* @internal */
DisjointDomains = NonPrimitive | StringLike | NumberLike | BigIntLike | BooleanLike | ESSymbolLike | VoidLike | Null,
UnionOrIntersection = Union | Intersection,
StructuredType = Object | Union | Intersection,
TypeVariable = TypeParameter | IndexedAccess,
InstantiableNonPrimitive = TypeVariable | Conditional | Substitution,
InstantiablePrimitive = Index | TemplateLiteral | StringMapping,
Instantiable = InstantiableNonPrimitive | InstantiablePrimitive,
StructuredOrInstantiable = StructuredType | Instantiable,
/* @internal */
ObjectFlagsType = Any | Nullable | Never | Object | Union | Intersection,
/* @internal */
Simplifiable = IndexedAccess | Conditional,
/* @internal */
Substructure = Object | Union | Intersection | Index | IndexedAccess | Conditional | Substitution | TemplateLiteral | StringMapping,
// 'Narrowable' types are types where narrowing actually narrows.
// This *should* be every type other than null, undefined, void, and never
Narrowable = Any | Unknown | StructuredOrInstantiable | StringLike | NumberLike | BigIntLike | BooleanLike | ESSymbol | UniqueESSymbol | NonPrimitive,
/* @internal */
NotPrimitiveUnion = Any | Unknown | Enum | Void | Never | Object | Intersection | Instantiable,
// The following flags are aggregated during union and intersection type construction
/* @internal */
IncludesMask = Any | Unknown | Primitive | Never | Object | Union | Intersection | NonPrimitive | TemplateLiteral,
// The following flags are used for different purposes during union and intersection type construction
/* @internal */
IncludesStructuredOrInstantiable = TypeParameter,
/* @internal */
IncludesNonWideningType = Index,
/* @internal */
IncludesWildcard = IndexedAccess,
/* @internal */
IncludesEmptyObject = Conditional,
}
export type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
/* @internal */
export type TypeId = number;
// Properties common to all types
export interface Type {
flags: TypeFlags; // Flags
/* @internal */ id: TypeId; // Unique ID
/* @internal */ checker: TypeChecker;
symbol: Symbol; // Symbol associated with type (if any)
pattern?: DestructuringPattern; // Destructuring pattern represented by type (if any)
aliasSymbol?: Symbol; // Alias associated with type
aliasTypeArguments?: readonly Type[]; // Alias type arguments (if any)
/* @internal */ aliasTypeArgumentsContainsMarker?: boolean; // Alias type arguments (if any)
/* @internal */
permissiveInstantiation?: Type; // Instantiation with type parameters mapped to wildcard type
/* @internal */
restrictiveInstantiation?: Type; // Instantiation with type parameters mapped to unconstrained form
/* @internal */
immediateBaseConstraint?: Type; // Immediate base constraint cache
/* @internal */
widened?: Type; // Cached widened form of the type
}
/* @internal */
// Intrinsic types (TypeFlags.Intrinsic)
export interface IntrinsicType extends Type {
intrinsicName: string; // Name of intrinsic type
objectFlags: ObjectFlags;
}
/* @internal */
export interface NullableType extends IntrinsicType {
objectFlags: ObjectFlags;
}
/* @internal */
export interface FreshableIntrinsicType extends IntrinsicType {
freshType: IntrinsicType; // Fresh version of type
regularType: IntrinsicType; // Regular version of type
}
/* @internal */
export type FreshableType = LiteralType | FreshableIntrinsicType;
// String literal types (TypeFlags.StringLiteral)
// Numeric literal types (TypeFlags.NumberLiteral)
// BigInt literal types (TypeFlags.BigIntLiteral)
export interface LiteralType extends Type {
value: string | number | PseudoBigInt; // Value of literal
freshType: LiteralType; // Fresh version of type
regularType: LiteralType; // Regular version of type
}
// Unique symbol types (TypeFlags.UniqueESSymbol)
export interface UniqueESSymbolType extends Type {
symbol: Symbol;
escapedName: __String;
}
export interface StringLiteralType extends LiteralType {
value: string;
}
export interface NumberLiteralType extends LiteralType {
value: number;
}
export interface BigIntLiteralType extends LiteralType {
value: PseudoBigInt;
}
// Enum types (TypeFlags.Enum)
export interface EnumType extends Type {
}
// Types included in TypeFlags.ObjectFlagsType have an objectFlags property. Some ObjectFlags
// are specific to certain types and reuse the same bit position. Those ObjectFlags require a check
// for a certain TypeFlags value to determine their meaning.
export const enum ObjectFlags {
Class = 1 << 0, // Class
Interface = 1 << 1, // Interface
Reference = 1 << 2, // Generic type reference
Tuple = 1 << 3, // Synthesized generic tuple type
Anonymous = 1 << 4, // Anonymous
Mapped = 1 << 5, // Mapped
Instantiated = 1 << 6, // Instantiated anonymous or mapped type
ObjectLiteral = 1 << 7, // Originates in an object literal
EvolvingArray = 1 << 8, // Evolving array type
ObjectLiteralPatternWithComputedProperties = 1 << 9, // Object literal pattern with computed properties
ReverseMapped = 1 << 10, // Object contains a property from a reverse-mapped type
JsxAttributes = 1 << 11, // Jsx attributes type
MarkerType = 1 << 12, // Marker type used for variance probing
JSLiteral = 1 << 13, // Object type declared in JS - disables errors on read/write of nonexisting members
FreshLiteral = 1 << 14, // Fresh object literal
ArrayLiteral = 1 << 15, // Originates in an array literal
/* @internal */
PrimitiveUnion = 1 << 16, // Union of only primitive types
/* @internal */
ContainsWideningType = 1 << 17, // Type is or contains undefined or null widening type
/* @internal */
ContainsObjectOrArrayLiteral = 1 << 18, // Type is or contains object literal type
/* @internal */
NonInferrableType = 1 << 19, // Type is or contains anyFunctionType or silentNeverType
/* @internal */
CouldContainTypeVariablesComputed = 1 << 20, // CouldContainTypeVariables flag has been computed
/* @internal */
CouldContainTypeVariables = 1 << 21, // Type could contain a type variable
ClassOrInterface = Class | Interface,
/* @internal */
RequiresWidening = ContainsWideningType | ContainsObjectOrArrayLiteral,
/* @internal */
PropagatingFlags = ContainsWideningType | ContainsObjectOrArrayLiteral | NonInferrableType,
// Object flags that uniquely identify the kind of ObjectType
/* @internal */
ObjectTypeKindMask = ClassOrInterface | Reference | Tuple | Anonymous | Mapped | ReverseMapped | EvolvingArray,
// Flags that require TypeFlags.Object
ContainsSpread = 1 << 22, // Object literal contains spread operation
ObjectRestType = 1 << 23, // Originates in object rest declaration
/* @internal */
IsClassInstanceClone = 1 << 24, // Type is a clone of a class instance type
// Flags that require TypeFlags.Object and ObjectFlags.Reference
/* @internal */
IdenticalBaseTypeCalculated = 1 << 25, // has had `getSingleBaseForNonAugmentingSubtype` invoked on it already
/* @internal */
IdenticalBaseTypeExists = 1 << 26, // has a defined cachedEquivalentBaseType member
// Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution
/* @internal */
IsGenericObjectTypeComputed = 1 << 22, // IsGenericObjectType flag has been computed
/* @internal */
IsGenericObjectType = 1 << 23, // Union or intersection contains generic object type
/* @internal */
IsGenericIndexTypeComputed = 1 << 24, // IsGenericIndexType flag has been computed
/* @internal */
IsGenericIndexType = 1 << 25, // Union or intersection contains generic index type
// Flags that require TypeFlags.Union
/* @internal */
ContainsIntersections = 1 << 26, // Union contains intersections
// Flags that require TypeFlags.Intersection
/* @internal */
IsNeverIntersectionComputed = 1 << 26, // IsNeverLike flag has been computed
/* @internal */
IsNeverIntersection = 1 << 27, // Intersection reduces to never
}
/* @internal */
export type ObjectFlagsType = NullableType | ObjectType | UnionType | IntersectionType;
// Object types (TypeFlags.ObjectType)
export interface ObjectType extends Type {
objectFlags: ObjectFlags;
/* @internal */ members?: SymbolTable; // Properties by name
/* @internal */ properties?: Symbol[]; // Properties
/* @internal */ callSignatures?: readonly Signature[]; // Call signatures of type
/* @internal */ constructSignatures?: readonly Signature[]; // Construct signatures of type
/* @internal */ stringIndexInfo?: IndexInfo; // String indexing info
/* @internal */ numberIndexInfo?: IndexInfo; // Numeric indexing info
/* @internal */ objectTypeWithoutAbstractConstructSignatures?: ObjectType;
}
/** Class and interface types (ObjectFlags.Class and ObjectFlags.Interface). */
export interface InterfaceType extends ObjectType {
typeParameters: TypeParameter[] | undefined; // Type parameters (undefined if non-generic)
outerTypeParameters: TypeParameter[] | undefined; // Outer type parameters (undefined if none)
localTypeParameters: TypeParameter[] | undefined; // Local type parameters (undefined if none)
thisType: TypeParameter | undefined; // The "this" type (undefined if none)
/* @internal */
resolvedBaseConstructorType?: Type; // Resolved base constructor type of class
/* @internal */
resolvedBaseTypes: BaseType[]; // Resolved base types
/* @internal */
baseTypesResolved?: boolean;
}
// Object type or intersection of object types
export type BaseType = ObjectType | IntersectionType | TypeVariable; // Also `any` and `object`
export interface InterfaceTypeWithDeclaredMembers extends InterfaceType {
declaredProperties: Symbol[]; // Declared members
declaredCallSignatures: Signature[]; // Declared call signatures
declaredConstructSignatures: Signature[]; // Declared construct signatures
declaredStringIndexInfo?: IndexInfo; // Declared string indexing info
declaredNumberIndexInfo?: IndexInfo; // Declared numeric indexing info
}
/**
* Type references (ObjectFlags.Reference). When a class or interface has type parameters or
* a "this" type, references to the class or interface are made using type references. The
* typeArguments property specifies the types to substitute for the type parameters of the
* class or interface and optionally includes an extra element that specifies the type to
* substitute for "this" in the resulting instantiation. When no extra argument is present,
* the type reference itself is substituted for "this". The typeArguments property is undefined
* if the class or interface has no type parameters and the reference isn't specifying an
* explicit "this" argument.
*/
export interface TypeReference extends ObjectType {
target: GenericType; // Type reference target
node?: TypeReferenceNode | ArrayTypeNode | TupleTypeNode;
/* @internal */
mapper?: TypeMapper;
/* @internal */
resolvedTypeArguments?: readonly Type[]; // Resolved type reference type arguments
/* @internal */
literalType?: TypeReference; // Clone of type with ObjectFlags.ArrayLiteral set
/* @internal */
cachedEquivalentBaseType?: Type; // Only set on references to class or interfaces with a single base type and no augmentations
}
export interface DeferredTypeReference extends TypeReference {
/* @internal */
node: TypeReferenceNode | ArrayTypeNode | TupleTypeNode;
/* @internal */
mapper?: TypeMapper;
/* @internal */
instantiations?: ESMap<string, Type>; // Instantiations of generic type alias (undefined if non-generic)
}
/* @internal */
export const enum VarianceFlags {
Invariant = 0, // Neither covariant nor contravariant
Covariant = 1 << 0, // Covariant
Contravariant = 1 << 1, // Contravariant
Bivariant = Covariant | Contravariant, // Both covariant and contravariant
Independent = 1 << 2, // Unwitnessed type parameter
VarianceMask = Invariant | Covariant | Contravariant | Independent, // Mask containing all measured variances without the unmeasurable flag
Unmeasurable = 1 << 3, // Variance result is unusable - relationship relies on structural comparisons which are not reflected in generic relationships
Unreliable = 1 << 4, // Variance result is unreliable - checking may produce false negatives, but not false positives
AllowsStructuralFallback = Unmeasurable | Unreliable,
}
// Generic class and interface types
export interface GenericType extends InterfaceType, TypeReference {
/* @internal */
instantiations: ESMap<string, TypeReference>; // Generic instantiation cache
/* @internal */
variances?: VarianceFlags[]; // Variance of each type parameter
}
export const enum ElementFlags {
Required = 1 << 0, // T
Optional = 1 << 1, // T?
Rest = 1 << 2, // ...T[]
Variadic = 1 << 3, // ...T
Fixed = Required | Optional,
Variable = Rest | Variadic,
NonRequired = Optional | Rest | Variadic,
NonRest = Required | Optional | Variadic,
}
export interface TupleType extends GenericType {
elementFlags: readonly ElementFlags[];
minLength: number; // Number of required or variadic elements
fixedLength: number; // Number of initial required or optional elements
hasRestElement: boolean; // True if tuple has any rest or variadic elements
combinedFlags: ElementFlags;
readonly: boolean;
labeledElementDeclarations?: readonly (NamedTupleMember | ParameterDeclaration)[];
}
export interface TupleTypeReference extends TypeReference {
target: TupleType;
}
export interface UnionOrIntersectionType extends Type {
types: Type[]; // Constituent types
/* @internal */
objectFlags: ObjectFlags;
/* @internal */
propertyCache?: SymbolTable; // Cache of resolved properties
/* @internal */
propertyCacheWithoutObjectFunctionPropertyAugment?: SymbolTable; // Cache of resolved properties that does not augment function or object type properties
/* @internal */
resolvedProperties: Symbol[];
/* @internal */
resolvedIndexType: IndexType;
/* @internal */
resolvedStringIndexType: IndexType;
/* @internal */
resolvedBaseConstraint: Type;
}
export interface UnionType extends UnionOrIntersectionType {
/* @internal */
resolvedReducedType?: Type;
/* @internal */
regularType?: UnionType;
/* @internal */
origin?: Type; // Denormalized union, intersection, or index type in which union originates
/* @internal */
keyPropertyName?: __String; // Property with unique unit type that exists in every object/intersection in union type
/* @internal */
constituentMap?: ESMap<TypeId, Type>; // Constituents keyed by unit type discriminants
}
export interface IntersectionType extends UnionOrIntersectionType {
/* @internal */
resolvedApparentType: Type;
}
export type StructuredType = ObjectType | UnionType | IntersectionType;
/* @internal */
// An instantiated anonymous type has a target and a mapper
export interface AnonymousType extends ObjectType {
target?: AnonymousType; // Instantiation target
mapper?: TypeMapper; // Instantiation mapper
instantiations?: ESMap<string, Type>; // Instantiations of generic type alias (undefined if non-generic)
}
/* @internal */
export interface MappedType extends AnonymousType {
declaration: MappedTypeNode;
typeParameter?: TypeParameter;
constraintType?: Type;
nameType?: Type;
templateType?: Type;
modifiersType?: Type;
resolvedApparentType?: Type;
containsError?: boolean;
}
export interface EvolvingArrayType extends ObjectType {
elementType: Type; // Element expressions of evolving array type
finalArrayType?: Type; // Final array type of evolving array type
}
/* @internal */
export interface ReverseMappedType extends ObjectType {
source: Type;
mappedType: MappedType;
constraintType: IndexType;
}
/* @internal */
// Resolved object, union, or intersection type
export interface ResolvedType extends ObjectType, UnionOrIntersectionType {
members: SymbolTable; // Properties by name
properties: Symbol[]; // Properties
callSignatures: readonly Signature[]; // Call signatures of type
constructSignatures: readonly Signature[]; // Construct signatures of type
}
/* @internal */
// Object literals are initially marked fresh. Freshness disappears following an assignment,
// before a type assertion, or when an object literal's type is widened. The regular
// version of a fresh type is identical except for the TypeFlags.FreshObjectLiteral flag.
export interface FreshObjectLiteralType extends ResolvedType {
regularType: ResolvedType; // Regular version of fresh type
}
/* @internal */
export interface IterationTypes {
readonly yieldType: Type;
readonly returnType: Type;
readonly nextType: Type;
}
// Just a place to cache element types of iterables and iterators
/* @internal */
export interface IterableOrIteratorType extends ObjectType, UnionType {
iterationTypesOfGeneratorReturnType?: IterationTypes;
iterationTypesOfAsyncGeneratorReturnType?: IterationTypes;
iterationTypesOfIterable?: IterationTypes;
iterationTypesOfIterator?: IterationTypes;
iterationTypesOfAsyncIterable?: IterationTypes;
iterationTypesOfAsyncIterator?: IterationTypes;
iterationTypesOfIteratorResult?: IterationTypes;
}
/* @internal */
export interface PromiseOrAwaitableType extends ObjectType, UnionType {
promiseTypeOfPromiseConstructor?: Type;
promisedTypeOfPromise?: Type;
awaitedTypeOfType?: Type;
}
/* @internal */
export interface SyntheticDefaultModuleType extends Type {
syntheticType?: Type;
}
export interface InstantiableType extends Type {
/* @internal */
resolvedBaseConstraint?: Type;
/* @internal */
resolvedIndexType?: IndexType;
/* @internal */
resolvedStringIndexType?: IndexType;
}
// Type parameters (TypeFlags.TypeParameter)
export interface TypeParameter extends InstantiableType {
/** Retrieve using getConstraintFromTypeParameter */
/* @internal */
constraint?: Type; // Constraint
/* @internal */
default?: Type;
/* @internal */
target?: TypeParameter; // Instantiation target
/* @internal */
mapper?: TypeMapper; // Instantiation mapper
/* @internal */
isThisType?: boolean;
/* @internal */
resolvedDefaultType?: Type;
}
// Indexed access types (TypeFlags.IndexedAccess)
// Possible forms are T[xxx], xxx[T], or xxx[keyof T], where T is a type variable
export interface IndexedAccessType extends InstantiableType {
objectType: Type;
indexType: Type;
/**
* @internal
* Indicates that --noUncheckedIndexedAccess may introduce 'undefined' into
* the resulting type, depending on how type variable constraints are resolved.
*/
noUncheckedIndexedAccessCandidate: boolean;
constraint?: Type;
simplifiedForReading?: Type;
simplifiedForWriting?: Type;
}
export type TypeVariable = TypeParameter | IndexedAccessType;
// keyof T types (TypeFlags.Index)
export interface IndexType extends InstantiableType {
type: InstantiableType | UnionOrIntersectionType;
/* @internal */
stringsOnly: boolean;
}
export interface ConditionalRoot {
node: ConditionalTypeNode;
checkType: Type;
extendsType: Type;
isDistributive: boolean;
inferTypeParameters?: TypeParameter[];
outerTypeParameters?: TypeParameter[];
instantiations?: Map<Type>;
aliasSymbol?: Symbol;
aliasTypeArguments?: Type[];
}
// T extends U ? X : Y (TypeFlags.Conditional)
export interface ConditionalType extends InstantiableType {
root: ConditionalRoot;
checkType: Type;
extendsType: Type;
resolvedTrueType: Type;
resolvedFalseType: Type;
/* @internal */
resolvedInferredTrueType?: Type; // The `trueType` instantiated with the `combinedMapper`, if present
/* @internal */
resolvedDefaultConstraint?: Type;
/* @internal */
mapper?: TypeMapper;
/* @internal */
combinedMapper?: TypeMapper;
}
export interface TemplateLiteralType extends InstantiableType {
texts: readonly string[]; // Always one element longer than types
types: readonly Type[]; // Always at least one element
}
export interface StringMappingType extends InstantiableType {
symbol: Symbol;
type: Type;
}
// Type parameter substitution (TypeFlags.Substitution)
// Substitution types are created for type parameters or indexed access types that occur in the
// true branch of a conditional type. For example, in 'T extends string ? Foo<T> : Bar<T>', the
// reference to T in Foo<T> is resolved as a substitution type that substitutes 'string & T' for T.
// Thus, if Foo has a 'string' constraint on its type parameter, T will satisfy it. Substitution
// types disappear upon instantiation (just like type parameters).
export interface SubstitutionType extends InstantiableType {
objectFlags: ObjectFlags;
baseType: Type; // Target type
substitute: Type; // Type to substitute for type parameter
}
/* @internal */
export const enum JsxReferenceKind {
Component,
Function,
Mixed
}
export const enum SignatureKind {
Call,
Construct,
}
/* @internal */
export const enum SignatureFlags {
None = 0,
// Propagating flags
HasRestParameter = 1 << 0, // Indicates last parameter is rest parameter
HasLiteralTypes = 1 << 1, // Indicates signature is specialized
Abstract = 1 << 2, // Indicates signature comes from an abstract class, abstract construct signature, or abstract constructor type
// Non-propagating flags
IsInnerCallChain = 1 << 3, // Indicates signature comes from a CallChain nested in an outer OptionalChain
IsOuterCallChain = 1 << 4, // Indicates signature comes from a CallChain that is the outermost chain of an optional expression
IsUntypedSignatureInJSFile = 1 << 5, // Indicates signature is from a js file and has no types
// We do not propagate `IsInnerCallChain` or `IsOuterCallChain` to instantiated signatures, as that would result in us
// attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when
// instantiating the return type.
PropagatingFlags = HasRestParameter | HasLiteralTypes | Abstract | IsUntypedSignatureInJSFile,
CallChainFlags = IsInnerCallChain | IsOuterCallChain,
}
export interface Signature {
/* @internal */ flags: SignatureFlags;
/* @internal */ checker?: TypeChecker;
declaration?: SignatureDeclaration | JSDocSignature; // Originating declaration
typeParameters?: readonly TypeParameter[]; // Type parameters (undefined if non-generic)
parameters: readonly Symbol[]; // Parameters
/* @internal */
thisParameter?: Symbol; // symbol of this-type parameter
/* @internal */
// See comment in `instantiateSignature` for why these are set lazily.
resolvedReturnType?: Type; // Lazily set by `getReturnTypeOfSignature`.
/* @internal */
// Lazily set by `getTypePredicateOfSignature`.
// `undefined` indicates a type predicate that has not yet been computed.
// Uses a special `noTypePredicate` sentinel value to indicate that there is no type predicate. This looks like a TypePredicate at runtime to avoid polymorphism.
resolvedTypePredicate?: TypePredicate;
/* @internal */
minArgumentCount: number; // Number of non-optional parameters
/* @internal */
resolvedMinArgumentCount?: number; // Number of non-optional parameters (excluding trailing `void`)
/* @internal */
target?: Signature; // Instantiation target
/* @internal */
mapper?: TypeMapper; // Instantiation mapper
/* @internal */
compositeSignatures?: Signature[]; // Underlying signatures of a union/intersection signature
/* @internal */
compositeKind?: TypeFlags; // TypeFlags.Union if the underlying signatures are from union members, otherwise TypeFlags.Intersection
/* @internal */
erasedSignatureCache?: Signature; // Erased version of signature (deferred)
/* @internal */
canonicalSignatureCache?: Signature; // Canonical version of signature (deferred)
/* @internal */
baseSignatureCache?: Signature; // Base version of signature (deferred)
/* @internal */
optionalCallSignatureCache?: { inner?: Signature, outer?: Signature }; // Optional chained call version of signature (deferred)
/* @internal */
isolatedSignatureType?: ObjectType; // A manufactured type that just contains the signature for purposes of signature comparison
/* @internal */
instantiations?: ESMap<string, Signature>; // Generic signature instantiation cache
}
export const enum IndexKind {
String,
Number,
}
export interface IndexInfo {
type: Type;
isReadonly: boolean;
declaration?: IndexSignatureDeclaration;
}
/* @internal */
export const enum TypeMapKind {
Simple,
Array,
Function,
Composite,
Merged,
}
/* @internal */
export type TypeMapper =
| { kind: TypeMapKind.Simple, source: Type, target: Type }
| { kind: TypeMapKind.Array, sources: readonly Type[], targets: readonly Type[] | undefined }
| { kind: TypeMapKind.Function, func: (t: Type) => Type }
| { kind: TypeMapKind.Composite | TypeMapKind.Merged, mapper1: TypeMapper, mapper2: TypeMapper };
export const enum InferencePriority {
NakedTypeVariable = 1 << 0, // Naked type variable in union or intersection type
SpeculativeTuple = 1 << 1, // Speculative tuple inference
SubstituteSource = 1 << 2, // Source of inference originated within a substitution type's substitute
HomomorphicMappedType = 1 << 3, // Reverse inference for homomorphic mapped type
PartialHomomorphicMappedType = 1 << 4, // Partial reverse inference for homomorphic mapped type
MappedTypeConstraint = 1 << 5, // Reverse inference for mapped type
ContravariantConditional = 1 << 6, // Conditional type in contravariant position
ReturnType = 1 << 7, // Inference made from return type of generic function
LiteralKeyof = 1 << 8, // Inference made from a string literal to a keyof T
NoConstraints = 1 << 9, // Don't infer from constraints of instantiable types
AlwaysStrict = 1 << 10, // Always use strict rules for contravariant inferences
MaxValue = 1 << 11, // Seed for inference priority tracking
PriorityImpliesCombination = ReturnType | MappedTypeConstraint | LiteralKeyof, // These priorities imply that the resulting type should be a combination of all candidates
Circularity = -1, // Inference circularity (value less than all other priorities)
}
/* @internal */
export interface InferenceInfo {
typeParameter: TypeParameter; // Type parameter for which inferences are being made
candidates: Type[] | undefined; // Candidates in covariant positions (or undefined)
contraCandidates: Type[] | undefined; // Candidates in contravariant positions (or undefined)
inferredType?: Type; // Cache for resolved inferred type
priority?: InferencePriority; // Priority of current inference set
topLevel: boolean; // True if all inferences are to top level occurrences
isFixed: boolean; // True if inferences are fixed
impliedArity?: number;
}
/* @internal */
export const enum InferenceFlags {
None = 0, // No special inference behaviors
NoDefault = 1 << 0, // Infer unknownType for no inferences (otherwise anyType or emptyObjectType)
AnyDefault = 1 << 1, // Infer anyType for no inferences (otherwise emptyObjectType)
SkippedGenericFunction = 1 << 2, // A generic function was skipped during inference
}
/**
* Ternary values are defined such that
* x & y picks the lesser in the order False < Unknown < Maybe < True, and
* x | y picks the greater in the order False < Unknown < Maybe < True.
* Generally, Ternary.Maybe is used as the result of a relation that depends on itself, and
* Ternary.Unknown is used as the result of a variance check that depends on itself. We make
* a distinction because we don't want to cache circular variance check results.
*/
/* @internal */
export const enum Ternary {
False = 0,
Unknown = 1,
Maybe = 3,
True = -1
}
/* @internal */
export type TypeComparer = (s: Type, t: Type, reportErrors?: boolean) => Ternary;
/* @internal */
export interface InferenceContext {
inferences: InferenceInfo[]; // Inferences made for each type parameter
signature?: Signature; // Generic signature for which inferences are made (if any)
flags: InferenceFlags; // Inference flags
compareTypes: TypeComparer; // Type comparer function
mapper: TypeMapper; // Mapper that fixes inferences
nonFixingMapper: TypeMapper; // Mapper that doesn't fix inferences
returnMapper?: TypeMapper; // Type mapper for inferences from return types (if any)
inferredTypeParameters?: readonly TypeParameter[]; // Inferred type parameters for function result
}
/* @internal */
export interface WideningContext {
parent?: WideningContext; // Parent context
propertyName?: __String; // Name of property in parent
siblings?: Type[]; // Types of siblings
resolvedProperties?: Symbol[]; // Properties occurring in sibling object literals
}
/* @internal */
export const enum AssignmentDeclarationKind {
None,
/// exports.name = expr
/// module.exports.name = expr
ExportsProperty,
/// module.exports = expr
ModuleExports,
/// className.prototype.name = expr
PrototypeProperty,
/// this.name = expr
ThisProperty,
// F.name = expr
Property,
// F.prototype = { ... }
Prototype,
// Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) });
// Object.defineProperty(x, 'name', { get: Function, set: Function });
// Object.defineProperty(x, 'name', { get: Function });
// Object.defineProperty(x, 'name', { set: Function });
ObjectDefinePropertyValue,
// Object.defineProperty(exports || module.exports, 'name', ...);
ObjectDefinePropertyExports,
// Object.defineProperty(Foo.prototype, 'name', ...);
ObjectDefinePrototypeProperty,
}
/** @deprecated Use FileExtensionInfo instead. */
export type JsFileExtensionInfo = FileExtensionInfo;
export interface FileExtensionInfo {
extension: string;
isMixedContent: boolean;
scriptKind?: ScriptKind;
}
export interface DiagnosticMessage {
key: string;
category: DiagnosticCategory;
code: number;
message: string;
reportsUnnecessary?: {};
reportsDeprecated?: {};
/* @internal */
elidedInCompatabilityPyramid?: boolean;
}
/**
* A linked list of formatted diagnostic messages to be used as part of a multiline message.
* It is built from the bottom up, leaving the head to be the "main" diagnostic.
* While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage,
* the difference is that messages are all preformatted in DMC.
*/
export interface DiagnosticMessageChain {
messageText: string;
category: DiagnosticCategory;
code: number;
next?: DiagnosticMessageChain[];
}
export interface Diagnostic extends DiagnosticRelatedInformation {
/** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */
reportsUnnecessary?: {};
reportsDeprecated?: {}
source?: string;
relatedInformation?: DiagnosticRelatedInformation[];
/* @internal */ skippedOn?: keyof CompilerOptions;
}
export interface DiagnosticRelatedInformation {
category: DiagnosticCategory;
code: number;
file: SourceFile | undefined;
start: number | undefined;
length: number | undefined;
messageText: string | DiagnosticMessageChain;
}
export interface DiagnosticWithLocation extends Diagnostic {
file: SourceFile;
start: number;
length: number;
}
/* @internal*/
export interface DiagnosticWithDetachedLocation extends Diagnostic {
file: undefined;
fileName: string;
start: number;
length: number;
}
export enum DiagnosticCategory {
Warning,
Error,
Suggestion,
Message
}
/* @internal */
export function diagnosticCategoryName(d: { category: DiagnosticCategory }, lowerCase = true): string {
const name = DiagnosticCategory[d.category];
return lowerCase ? name.toLowerCase() : name;
}
export enum ModuleResolutionKind {
Classic = 1,
NodeJs = 2
}
export interface PluginImport {
name: string;
}
export interface ProjectReference {
/** A normalized path on disk */
path: string;
/** The path as the user originally wrote it */
originalPath?: string;
/** True if the output of this reference should be prepended to the output of this project. Only valid for --outFile compilations */
prepend?: boolean;
/** True if it is intended that this reference form a circularity */
circular?: boolean;
}
export enum WatchFileKind {
FixedPollingInterval,
PriorityPollingInterval,
DynamicPriorityPolling,
FixedChunkSizePolling,
UseFsEvents,
UseFsEventsOnParentDirectory,
}
export enum WatchDirectoryKind {
UseFsEvents,
FixedPollingInterval,
DynamicPriorityPolling,
FixedChunkSizePolling,
}
export enum PollingWatchKind {
FixedInterval,
PriorityInterval,
DynamicPriority,
FixedChunkSize,
}
export type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike<string[]> | PluginImport[] | ProjectReference[] | null | undefined;
export interface CompilerOptions {
/*@internal*/ all?: boolean;
allowJs?: boolean;
/*@internal*/ allowNonTsExtensions?: boolean;
allowSyntheticDefaultImports?: boolean;
allowUmdGlobalAccess?: boolean;
allowUnreachableCode?: boolean;
allowUnusedLabels?: boolean;
alwaysStrict?: boolean; // Always combine with strict property
baseUrl?: string;
/** An error if set - this should only go through the -b pipeline and not actually be observed */
/*@internal*/
build?: boolean;
charset?: string;
checkJs?: boolean;
/* @internal */ configFilePath?: string;
/** configFile is set as non enumerable property so as to avoid checking of json source files */
/* @internal */ readonly configFile?: TsConfigSourceFile;
declaration?: boolean;
declarationMap?: boolean;
emitDeclarationOnly?: boolean;
declarationDir?: string;
/* @internal */ diagnostics?: boolean;
/* @internal */ extendedDiagnostics?: boolean;
disableSizeLimit?: boolean;
disableSourceOfProjectReferenceRedirect?: boolean;
disableSolutionSearching?: boolean;
disableReferencedProjectLoad?: boolean;
downlevelIteration?: boolean;
emitBOM?: boolean;
emitDecoratorMetadata?: boolean;
experimentalDecorators?: boolean;
forceConsistentCasingInFileNames?: boolean;
/*@internal*/generateCpuProfile?: string;
/*@internal*/generateTrace?: string;
/*@internal*/help?: boolean;
importHelpers?: boolean;
importsNotUsedAsValues?: ImportsNotUsedAsValues;
/*@internal*/init?: boolean;
inlineSourceMap?: boolean;
inlineSources?: boolean;
isolatedModules?: boolean;
jsx?: JsxEmit;
keyofStringsOnly?: boolean;
lib?: string[];
/*@internal*/listEmittedFiles?: boolean;
/*@internal*/listFiles?: boolean;
/*@internal*/explainFiles?: boolean;
/*@internal*/listFilesOnly?: boolean;
locale?: string;
mapRoot?: string;
maxNodeModuleJsDepth?: number;
module?: ModuleKind;
moduleResolution?: ModuleResolutionKind;
newLine?: NewLineKind;
noEmit?: boolean;
/*@internal*/noEmitForJsFiles?: boolean;
noEmitHelpers?: boolean;
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noFallthroughCasesInSwitch?: boolean;
noImplicitAny?: boolean; // Always combine with strict property
noImplicitReturns?: boolean;
noImplicitThis?: boolean; // Always combine with strict property
noStrictGenericChecks?: boolean;
noUnusedLocals?: boolean;
noUnusedParameters?: boolean;
noImplicitUseStrict?: boolean;
noPropertyAccessFromIndexSignature?: boolean;
assumeChangesOnlyAffectDirectDependencies?: boolean;
noLib?: boolean;
noResolve?: boolean;
noUncheckedIndexedAccess?: boolean;
out?: string;
outDir?: string;
outFile?: string;
paths?: MapLike<string[]>;
/** The directory of the config file that specified 'paths'. Used to resolve relative paths when 'baseUrl' is absent. */
/*@internal*/ pathsBasePath?: string;
/*@internal*/ plugins?: PluginImport[];
preserveConstEnums?: boolean;
noImplicitOverride?: boolean;
preserveSymlinks?: boolean;
/* @internal */ preserveWatchOutput?: boolean;
project?: string;
/* @internal */ pretty?: boolean;
reactNamespace?: string;
jsxFactory?: string;
jsxFragmentFactory?: string;
jsxImportSource?: string;
composite?: boolean;
incremental?: boolean;
tsBuildInfoFile?: string;
removeComments?: boolean;
rootDir?: string;
rootDirs?: string[];
skipLibCheck?: boolean;
skipDefaultLibCheck?: boolean;
sourceMap?: boolean;
sourceRoot?: string;
strict?: boolean;
strictFunctionTypes?: boolean; // Always combine with strict property
strictBindCallApply?: boolean; // Always combine with strict property
strictNullChecks?: boolean; // Always combine with strict property
strictPropertyInitialization?: boolean; // Always combine with strict property
stripInternal?: boolean;
suppressExcessPropertyErrors?: boolean;
suppressImplicitAnyIndexErrors?: boolean;
/* @internal */ suppressOutputPathCheck?: boolean;
target?: ScriptTarget; // TODO: GH#18217 frequently asserted as defined
traceResolution?: boolean;
resolveJsonModule?: boolean;
types?: string[];
/** Paths used to compute primary types search locations */
typeRoots?: string[];
/*@internal*/ version?: boolean;
/*@internal*/ watch?: boolean;
esModuleInterop?: boolean;
/* @internal */ showConfig?: boolean;
useDefineForClassFields?: boolean;
[option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined;
}
export interface WatchOptions {
watchFile?: WatchFileKind;
watchDirectory?: WatchDirectoryKind;
fallbackPolling?: PollingWatchKind;
synchronousWatchDirectory?: boolean;
excludeDirectories?: string[];
excludeFiles?: string[];
[option: string]: CompilerOptionsValue | undefined;
}
export interface TypeAcquisition {
/**
* @deprecated typingOptions.enableAutoDiscovery
* Use typeAcquisition.enable instead.
*/
enableAutoDiscovery?: boolean;
enable?: boolean;
include?: string[];
exclude?: string[];
disableFilenameBasedTypeAcquisition?: boolean;
[option: string]: CompilerOptionsValue | undefined;
}
export enum ModuleKind {
None = 0,
CommonJS = 1,
AMD = 2,
UMD = 3,
System = 4,
// NOTE: ES module kinds should be contiguous to more easily check whether a module kind is *any* ES module kind.
// Non-ES module kinds should not come between ES2015 (the earliest ES module kind) and ESNext (the last ES
// module kind).
ES2015 = 5,
ES2020 = 6,
ESNext = 99
}
export const enum JsxEmit {
None = 0,
Preserve = 1,
React = 2,
ReactNative = 3,
ReactJSX = 4,
ReactJSXDev = 5,
}
export const enum ImportsNotUsedAsValues {
Remove,
Preserve,
Error
}
export const enum NewLineKind {
CarriageReturnLineFeed = 0,
LineFeed = 1
}
export interface LineAndCharacter {
/** 0-based. */
line: number;
/*
* 0-based. This value denotes the character position in line and is different from the 'column' because of tab characters.
*/
character: number;
}
export const enum ScriptKind {
Unknown = 0,
JS = 1,
JSX = 2,
TS = 3,
TSX = 4,
External = 5,
JSON = 6,
/**
* Used on extensions that doesn't define the ScriptKind but the content defines it.
* Deferred extensions are going to be included in all project contexts.
*/
Deferred = 7
}
export const enum ScriptTarget {
ES3 = 0,
ES5 = 1,
ES2015 = 2,
ES2016 = 3,
ES2017 = 4,
ES2018 = 5,
ES2019 = 6,
ES2020 = 7,
ES2021 = 8,
ESNext = 99,
JSON = 100,
Latest = ESNext,
}
export const enum LanguageVariant {
Standard,
JSX
}
/** Either a parsed command line or a parsed tsconfig.json */
export interface ParsedCommandLine {
options: CompilerOptions;
typeAcquisition?: TypeAcquisition;
fileNames: string[];
projectReferences?: readonly ProjectReference[];
watchOptions?: WatchOptions;
raw?: any;
errors: Diagnostic[];
wildcardDirectories?: MapLike<WatchDirectoryFlags>;
compileOnSave?: boolean;
}
export const enum WatchDirectoryFlags {
None = 0,
Recursive = 1 << 0,
}
/* @internal */
export interface ConfigFileSpecs {
filesSpecs: readonly string[] | undefined;
/**
* Present to report errors (user specified specs), validatedIncludeSpecs are used for file name matching
*/
includeSpecs: readonly string[] | undefined;
/**
* Present to report errors (user specified specs), validatedExcludeSpecs are used for file name matching
*/
excludeSpecs: readonly string[] | undefined;
validatedFilesSpec: readonly string[] | undefined;
validatedIncludeSpecs: readonly string[] | undefined;
validatedExcludeSpecs: readonly string[] | undefined;
}
/* @internal */
export type RequireResult<T = {}> =
| { module: T, modulePath?: string, error: undefined }
| { module: undefined, modulePath?: undefined, error: { stack?: string, message?: string } };
export interface CreateProgramOptions {
rootNames: readonly string[];
options: CompilerOptions;
projectReferences?: readonly ProjectReference[];
host?: CompilerHost;
oldProgram?: Program;
configFileParsingDiagnostics?: readonly Diagnostic[];
}
/* @internal */
export interface CommandLineOptionBase {
name: string;
type: "string" | "number" | "boolean" | "object" | "list" | ESMap<string, number | string>; // a value of a primitive type, or an object literal mapping named values to actual values
isFilePath?: boolean; // True if option value is a path or fileName
shortName?: string; // A short mnemonic for convenience - for instance, 'h' can be used in place of 'help'
description?: DiagnosticMessage; // The message describing what the command line switch does
paramType?: DiagnosticMessage; // The name to be used for a non-boolean option's parameter
isTSConfigOnly?: boolean; // True if option can only be specified via tsconfig.json file
isCommandLineOnly?: boolean;
showInSimplifiedHelpView?: boolean;
category?: DiagnosticMessage;
strictFlag?: true; // true if the option is one of the flag under strict
affectsSourceFile?: true; // true if we should recreate SourceFiles after this option changes
affectsModuleResolution?: true; // currently same effect as `affectsSourceFile`
affectsBindDiagnostics?: true; // true if this affects binding (currently same effect as `affectsSourceFile`)
affectsSemanticDiagnostics?: true; // true if option affects semantic diagnostics
affectsEmit?: true; // true if the options affects emit
transpileOptionValue?: boolean | undefined; // If set this means that the option should be set to this value when transpiling
extraValidation?: (value: CompilerOptionsValue) => [DiagnosticMessage, ...string[]] | undefined; // Additional validation to be performed for the value to be valid
}
/* @internal */
export interface CommandLineOptionOfPrimitiveType extends CommandLineOptionBase {
type: "string" | "number" | "boolean";
}
/* @internal */
export interface CommandLineOptionOfCustomType extends CommandLineOptionBase {
type: ESMap<string, number | string>; // an object literal mapping named values to actual values
}
/* @internal */
export interface AlternateModeDiagnostics {
diagnostic: DiagnosticMessage;
getOptionsNameMap: () => OptionsNameMap;
}
/* @internal */
export interface DidYouMeanOptionsDiagnostics {
alternateMode?: AlternateModeDiagnostics;
optionDeclarations: CommandLineOption[];
unknownOptionDiagnostic: DiagnosticMessage,
unknownDidYouMeanDiagnostic: DiagnosticMessage,
}
/* @internal */
export interface TsConfigOnlyOption extends CommandLineOptionBase {
type: "object";
elementOptions?: ESMap<string, CommandLineOption>;
extraKeyDiagnostics?: DidYouMeanOptionsDiagnostics;
}
/* @internal */
export interface CommandLineOptionOfListType extends CommandLineOptionBase {
type: "list";
element: CommandLineOptionOfCustomType | CommandLineOptionOfPrimitiveType | TsConfigOnlyOption;
}
/* @internal */
export type CommandLineOption = CommandLineOptionOfCustomType | CommandLineOptionOfPrimitiveType | TsConfigOnlyOption | CommandLineOptionOfListType;
/* @internal */
export const enum CharacterCodes {
nullCharacter = 0,
maxAsciiCharacter = 0x7F,
lineFeed = 0x0A, // \n
carriageReturn = 0x0D, // \r
lineSeparator = 0x2028,
paragraphSeparator = 0x2029,
nextLine = 0x0085,
// Unicode 3.0 space characters
space = 0x0020, // " "
nonBreakingSpace = 0x00A0, //
enQuad = 0x2000,
emQuad = 0x2001,
enSpace = 0x2002,
emSpace = 0x2003,
threePerEmSpace = 0x2004,
fourPerEmSpace = 0x2005,
sixPerEmSpace = 0x2006,
figureSpace = 0x2007,
punctuationSpace = 0x2008,
thinSpace = 0x2009,
hairSpace = 0x200A,
zeroWidthSpace = 0x200B,
narrowNoBreakSpace = 0x202F,
ideographicSpace = 0x3000,
mathematicalSpace = 0x205F,
ogham = 0x1680,
_ = 0x5F,
$ = 0x24,
_0 = 0x30,
_1 = 0x31,
_2 = 0x32,
_3 = 0x33,
_4 = 0x34,
_5 = 0x35,
_6 = 0x36,
_7 = 0x37,
_8 = 0x38,
_9 = 0x39,
a = 0x61,
b = 0x62,
c = 0x63,
d = 0x64,
e = 0x65,
f = 0x66,
g = 0x67,
h = 0x68,
i = 0x69,
j = 0x6A,
k = 0x6B,
l = 0x6C,
m = 0x6D,
n = 0x6E,
o = 0x6F,
p = 0x70,
q = 0x71,
r = 0x72,
s = 0x73,
t = 0x74,
u = 0x75,
v = 0x76,
w = 0x77,
x = 0x78,
y = 0x79,
z = 0x7A,
A = 0x41,
B = 0x42,
C = 0x43,
D = 0x44,
E = 0x45,
F = 0x46,
G = 0x47,
H = 0x48,
I = 0x49,
J = 0x4A,
K = 0x4B,
L = 0x4C,
M = 0x4D,
N = 0x4E,
O = 0x4F,
P = 0x50,
Q = 0x51,
R = 0x52,
S = 0x53,
T = 0x54,
U = 0x55,
V = 0x56,
W = 0x57,
X = 0x58,
Y = 0x59,
Z = 0x5a,
ampersand = 0x26, // &
asterisk = 0x2A, // *
at = 0x40, // @
backslash = 0x5C, // \
backtick = 0x60, // `
bar = 0x7C, // |
caret = 0x5E, // ^
closeBrace = 0x7D, // }
closeBracket = 0x5D, // ]
closeParen = 0x29, // )
colon = 0x3A, // :
comma = 0x2C, // ,
dot = 0x2E, // .
doubleQuote = 0x22, // "
equals = 0x3D, // =
exclamation = 0x21, // !
greaterThan = 0x3E, // >
hash = 0x23, // #
lessThan = 0x3C, // <
minus = 0x2D, // -
openBrace = 0x7B, // {
openBracket = 0x5B, // [
openParen = 0x28, // (
percent = 0x25, // %
plus = 0x2B, // +
question = 0x3F, // ?
semicolon = 0x3B, // ;
singleQuote = 0x27, // '
slash = 0x2F, // /
tilde = 0x7E, // ~
backspace = 0x08, // \b
formFeed = 0x0C, // \f
byteOrderMark = 0xFEFF,
tab = 0x09, // \t
verticalTab = 0x0B, // \v
}
export interface ModuleResolutionHost {
// TODO: GH#18217 Optional methods frequently used as non-optional
fileExists(fileName: string): boolean;
// readFile function is used to read arbitrary text files on disk, i.e. when resolution procedure needs the content of 'package.json'
// to determine location of bundled typings for node module
readFile(fileName: string): string | undefined;
trace?(s: string): void;
directoryExists?(directoryName: string): boolean;
/**
* Resolve a symbolic link.
* @see https://nodejs.org/api/fs.html#fs_fs_realpathsync_path_options
*/
realpath?(path: string): string;
getCurrentDirectory?(): string;
getDirectories?(path: string): string[];
}
/**
* Represents the result of module resolution.
* Module resolution will pick up tsx/jsx/js files even if '--jsx' and '--allowJs' are turned off.
* The Program will then filter results based on these flags.
*
* Prefer to return a `ResolvedModuleFull` so that the file type does not have to be inferred.
*/
export interface ResolvedModule {
/** Path of the file the module was resolved to. */
resolvedFileName: string;
/** True if `resolvedFileName` comes from `node_modules`. */
isExternalLibraryImport?: boolean;
}
/**
* ResolvedModule with an explicitly provided `extension` property.
* Prefer this over `ResolvedModule`.
* If changing this, remember to change `moduleResolutionIsEqualTo`.
*/
export interface ResolvedModuleFull extends ResolvedModule {
/* @internal */
readonly originalPath?: string;
/**
* Extension of resolvedFileName. This must match what's at the end of resolvedFileName.
* This is optional for backwards-compatibility, but will be added if not provided.
*/
extension: Extension;
packageId?: PackageId;
}
/**
* Unique identifier with a package name and version.
* If changing this, remember to change `packageIdIsEqual`.
*/
export interface PackageId {
/**
* Name of the package.
* Should not include `@types`.
* If accessing a non-index file, this should include its name e.g. "foo/bar".
*/
name: string;
/**
* Name of a submodule within this package.
* May be "".
*/
subModuleName: string;
/** Version of the package, e.g. "1.2.3" */
version: string;
}
export const enum Extension {
Ts = ".ts",
Tsx = ".tsx",
Dts = ".d.ts",
Js = ".js",
Jsx = ".jsx",
Json = ".json",
TsBuildInfo = ".tsbuildinfo"
}
export interface ResolvedModuleWithFailedLookupLocations {
readonly resolvedModule: ResolvedModuleFull | undefined;
/* @internal */
readonly failedLookupLocations: string[];
}
export interface ResolvedTypeReferenceDirective {
// True if the type declaration file was found in a primary lookup location
primary: boolean;
// The location of the .d.ts file we located, or undefined if resolution failed
resolvedFileName: string | undefined;
packageId?: PackageId;
/** True if `resolvedFileName` comes from `node_modules`. */
isExternalLibraryImport?: boolean;
}
export interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations {
readonly resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined;
readonly failedLookupLocations: string[];
}
/* @internal */
export type HasInvalidatedResolution = (sourceFile: Path) => boolean;
/* @internal */
export type HasChangedAutomaticTypeDirectiveNames = () => boolean;
export interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined;
getSourceFileByPath?(fileName: string, path: Path, languageVersion: ScriptTarget, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean): SourceFile | undefined;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
readDirectory?(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[], depth?: number): string[];
/*
* CompilerHost must either implement resolveModuleNames (in case if it wants to be completely in charge of
* module name resolution) or provide implementation for methods from ModuleResolutionHost (in this case compiler
* will apply built-in module resolution logic and use members of ModuleResolutionHost to ask host specific questions).
* If resolveModuleNames is implemented then implementation for members from ModuleResolutionHost can be just
* 'throw new Error("NotImplemented")'
*/
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions): (ResolvedModule | undefined)[];
/**
* This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files
*/
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions): (ResolvedTypeReferenceDirective | undefined)[];
getEnvironmentVariable?(name: string): string | undefined;
/* @internal */ onReleaseOldSourceFile?(oldSourceFile: SourceFile, oldOptions: CompilerOptions, hasSourceFileByPath: boolean): void;
/* @internal */ onReleaseParsedCommandLine?(configFileName: string, oldResolvedRef: ResolvedProjectReference | undefined, optionOptions: CompilerOptions): void;
/* @internal */ hasInvalidatedResolution?: HasInvalidatedResolution;
/* @internal */ hasChangedAutomaticTypeDirectiveNames?: HasChangedAutomaticTypeDirectiveNames;
createHash?(data: string): string;
getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined;
/* @internal */ useSourceOfProjectReferenceRedirect?(): boolean;
// TODO: later handle this in better way in builder host instead once the api for tsbuild finalizes and doesn't use compilerHost as base
/*@internal*/createDirectory?(directory: string): void;
/*@internal*/getSymlinkCache?(): SymlinkCache;
// For testing:
/*@internal*/ disableUseFileVersionAsSignature?: boolean;
}
/** true if --out otherwise source file name */
/*@internal*/
export type SourceOfProjectReferenceRedirect = string | true;
/*@internal*/
export interface ResolvedProjectReferenceCallbacks {
getSourceOfProjectReferenceRedirect(fileName: string): SourceOfProjectReferenceRedirect | undefined;
forEachResolvedProjectReference<T>(cb: (resolvedProjectReference: ResolvedProjectReference) => T | undefined): T | undefined;
}
/* @internal */
export const enum TransformFlags {
None = 0,
// Facts
// - Flags used to indicate that a node or subtree contains syntax that requires transformation.
ContainsTypeScript = 1 << 0,
ContainsJsx = 1 << 1,
ContainsESNext = 1 << 2,
ContainsES2021 = 1 << 3,
ContainsES2020 = 1 << 4,
ContainsES2019 = 1 << 5,
ContainsES2018 = 1 << 6,
ContainsES2017 = 1 << 7,
ContainsES2016 = 1 << 8,
ContainsES2015 = 1 << 9,
ContainsGenerator = 1 << 10,
ContainsDestructuringAssignment = 1 << 11,
// Markers
// - Flags used to indicate that a subtree contains a specific transformation.
ContainsTypeScriptClassSyntax = 1 << 12, // Decorators, Property Initializers, Parameter Property Initializers
ContainsLexicalThis = 1 << 13,
ContainsRestOrSpread = 1 << 14,
ContainsObjectRestOrSpread = 1 << 15,
ContainsComputedPropertyName = 1 << 16,
ContainsBlockScopedBinding = 1 << 17,
ContainsBindingPattern = 1 << 18,
ContainsYield = 1 << 19,
ContainsAwait = 1 << 20,
ContainsHoistedDeclarationOrCompletion = 1 << 21,
ContainsDynamicImport = 1 << 22,
ContainsClassFields = 1 << 23,
ContainsPossibleTopLevelAwait = 1 << 24,
// Please leave this as 1 << 29.
// It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
// It is a good reminder of how much room we have left
HasComputedFlags = 1 << 29, // Transform flags have been computed.
// Assertions
// - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
AssertTypeScript = ContainsTypeScript,
AssertJsx = ContainsJsx,
AssertESNext = ContainsESNext,
AssertES2021 = ContainsES2021,
AssertES2020 = ContainsES2020,
AssertES2019 = ContainsES2019,
AssertES2018 = ContainsES2018,
AssertES2017 = ContainsES2017,
AssertES2016 = ContainsES2016,
AssertES2015 = ContainsES2015,
AssertGenerator = ContainsGenerator,
AssertDestructuringAssignment = ContainsDestructuringAssignment,
// Scope Exclusions
// - Bitmasks that exclude flags from propagating out of a specific context
// into the subtree flags of their container.
OuterExpressionExcludes = HasComputedFlags,
PropertyAccessExcludes = OuterExpressionExcludes,
NodeExcludes = PropertyAccessExcludes,
ArrowFunctionExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsBlockScopedBinding | ContainsYield | ContainsAwait | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread | ContainsPossibleTopLevelAwait,
FunctionExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsAwait | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread | ContainsPossibleTopLevelAwait,
ConstructorExcludes = NodeExcludes | ContainsLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsAwait | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread | ContainsPossibleTopLevelAwait,
MethodOrAccessorExcludes = NodeExcludes | ContainsLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsAwait | ContainsHoistedDeclarationOrCompletion | ContainsBindingPattern | ContainsObjectRestOrSpread,
PropertyExcludes = NodeExcludes | ContainsLexicalThis,
ClassExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsComputedPropertyName,
ModuleExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsLexicalThis | ContainsBlockScopedBinding | ContainsHoistedDeclarationOrCompletion | ContainsPossibleTopLevelAwait,
TypeExcludes = ~ContainsTypeScript,
ObjectLiteralExcludes = NodeExcludes | ContainsTypeScriptClassSyntax | ContainsComputedPropertyName | ContainsObjectRestOrSpread,
ArrayLiteralOrCallOrNewExcludes = NodeExcludes | ContainsRestOrSpread,
VariableDeclarationListExcludes = NodeExcludes | ContainsBindingPattern | ContainsObjectRestOrSpread,
ParameterExcludes = NodeExcludes,
CatchClauseExcludes = NodeExcludes | ContainsObjectRestOrSpread,
BindingPatternExcludes = NodeExcludes | ContainsRestOrSpread,
// Propagating flags
// - Bitmasks for flags that should propagate from a child
PropertyNamePropagatingFlags = ContainsLexicalThis,
// Masks
// - Additional bitmasks
}
export interface SourceMapRange extends TextRange {
source?: SourceMapSource;
}
export interface SourceMapSource {
fileName: string;
text: string;
/* @internal */ lineMap: readonly number[];
skipTrivia?: (pos: number) => number;
}
/* @internal */
export interface EmitNode {
annotatedNodes?: Node[]; // Tracks Parse-tree nodes with EmitNodes for eventual cleanup.
flags: EmitFlags; // Flags that customize emit
leadingComments?: SynthesizedComment[]; // Synthesized leading comments
trailingComments?: SynthesizedComment[]; // Synthesized trailing comments
commentRange?: TextRange; // The text range to use when emitting leading or trailing comments
sourceMapRange?: SourceMapRange; // The text range to use when emitting leading or trailing source mappings
tokenSourceMapRanges?: (SourceMapRange | undefined)[]; // The text range to use when emitting source mappings for tokens
constantValue?: string | number; // The constant value of an expression
externalHelpersModuleName?: Identifier; // The local name for an imported helpers module
externalHelpers?: boolean;
helpers?: EmitHelper[]; // Emit helpers for the node
startsOnNewLine?: boolean; // If the node should begin on a new line
}
export const enum EmitFlags {
None = 0,
SingleLine = 1 << 0, // The contents of this node should be emitted on a single line.
AdviseOnEmitNode = 1 << 1, // The printer should invoke the onEmitNode callback when printing this node.
NoSubstitution = 1 << 2, // Disables further substitution of an expression.
CapturesThis = 1 << 3, // The function captures a lexical `this`
NoLeadingSourceMap = 1 << 4, // Do not emit a leading source map location for this node.
NoTrailingSourceMap = 1 << 5, // Do not emit a trailing source map location for this node.
NoSourceMap = NoLeadingSourceMap | NoTrailingSourceMap, // Do not emit a source map location for this node.
NoNestedSourceMaps = 1 << 6, // Do not emit source map locations for children of this node.
NoTokenLeadingSourceMaps = 1 << 7, // Do not emit leading source map location for token nodes.
NoTokenTrailingSourceMaps = 1 << 8, // Do not emit trailing source map location for token nodes.
NoTokenSourceMaps = NoTokenLeadingSourceMaps | NoTokenTrailingSourceMaps, // Do not emit source map locations for tokens of this node.
NoLeadingComments = 1 << 9, // Do not emit leading comments for this node.
NoTrailingComments = 1 << 10, // Do not emit trailing comments for this node.
NoComments = NoLeadingComments | NoTrailingComments, // Do not emit comments for this node.
NoNestedComments = 1 << 11,
HelperName = 1 << 12, // The Identifier refers to an *unscoped* emit helper (one that is emitted at the top of the file)
ExportName = 1 << 13, // Ensure an export prefix is added for an identifier that points to an exported declaration with a local name (see SymbolFlags.ExportHasLocal).
LocalName = 1 << 14, // Ensure an export prefix is not added for an identifier that points to an exported declaration.
InternalName = 1 << 15, // The name is internal to an ES5 class body function.
Indented = 1 << 16, // Adds an explicit extra indentation level for class and function bodies when printing (used to match old emitter).
NoIndentation = 1 << 17, // Do not indent the node.
AsyncFunctionBody = 1 << 18,
ReuseTempVariableScope = 1 << 19, // Reuse the existing temp variable scope during emit.
CustomPrologue = 1 << 20, // Treat the statement as if it were a prologue directive (NOTE: Prologue directives are *not* transformed).
NoHoisting = 1 << 21, // Do not hoist this declaration in --module system
HasEndOfDeclarationMarker = 1 << 22, // Declaration has an associated NotEmittedStatement to mark the end of the declaration
Iterator = 1 << 23, // The expression to a `yield*` should be treated as an Iterator when down-leveling, not an Iterable.
NoAsciiEscaping = 1 << 24, // When synthesizing nodes that lack an original node or textSourceNode, we want to write the text on the node with ASCII escaping substitutions.
/*@internal*/ TypeScriptClassWrapper = 1 << 25, // The node is an IIFE class wrapper created by the ts transform.
/*@internal*/ NeverApplyImportHelper = 1 << 26, // Indicates the node should never be wrapped with an import star helper (because, for example, it imports tslib itself)
/*@internal*/ IgnoreSourceNewlines = 1 << 27, // Overrides `printerOptions.preserveSourceNewlines` to print this node (and all descendants) with default whitespace.
}
export interface EmitHelperBase {
readonly name: string; // A unique name for this helper.
readonly scoped: boolean; // Indicates whether the helper MUST be emitted in the current scope.
readonly text: string | ((node: EmitHelperUniqueNameCallback) => string); // ES3-compatible raw script text, or a function yielding such a string
readonly priority?: number; // Helpers with a higher priority are emitted earlier than other helpers on the node.
readonly dependencies?: EmitHelper[]
}
export interface ScopedEmitHelper extends EmitHelperBase {
readonly scoped: true;
}
export interface UnscopedEmitHelper extends EmitHelperBase {
readonly scoped: false; // Indicates whether the helper MUST be emitted in the current scope.
/* @internal */
readonly importName?: string; // The name of the helper to use when importing via `--importHelpers`.
readonly text: string; // ES3-compatible raw script text, or a function yielding such a string
}
export type EmitHelper = ScopedEmitHelper | UnscopedEmitHelper;
/* @internal */
export type UniqueNameHandler = (baseName: string, checkFn?: (name: string) => boolean, optimistic?: boolean) => string;
export type EmitHelperUniqueNameCallback = (name: string) => string;
/**
* Used by the checker, this enum keeps track of external emit helpers that should be type
* checked.
*/
/* @internal */
export const enum ExternalEmitHelpers {
Extends = 1 << 0, // __extends (used by the ES2015 class transformation)
Assign = 1 << 1, // __assign (used by Jsx and ESNext object spread transformations)
Rest = 1 << 2, // __rest (used by ESNext object rest transformation)
Decorate = 1 << 3, // __decorate (used by TypeScript decorators transformation)
Metadata = 1 << 4, // __metadata (used by TypeScript decorators transformation)
Param = 1 << 5, // __param (used by TypeScript decorators transformation)
Awaiter = 1 << 6, // __awaiter (used by ES2017 async functions transformation)
Generator = 1 << 7, // __generator (used by ES2015 generator transformation)
Values = 1 << 8, // __values (used by ES2015 for..of and yield* transformations)
Read = 1 << 9, // __read (used by ES2015 iterator destructuring transformation)
SpreadArray = 1 << 10, // __spreadArray (used by ES2015 array spread and argument list spread transformations)
Await = 1 << 11, // __await (used by ES2017 async generator transformation)
AsyncGenerator = 1 << 12, // __asyncGenerator (used by ES2017 async generator transformation)
AsyncDelegator = 1 << 13, // __asyncDelegator (used by ES2017 async generator yield* transformation)
AsyncValues = 1 << 14, // __asyncValues (used by ES2017 for..await..of transformation)
ExportStar = 1 << 15, // __exportStar (used by CommonJS/AMD/UMD module transformation)
ImportStar = 1 << 16, // __importStar (used by CommonJS/AMD/UMD module transformation)
ImportDefault = 1 << 17, // __importStar (used by CommonJS/AMD/UMD module transformation)
MakeTemplateObject = 1 << 18, // __makeTemplateObject (used for constructing template string array objects)
ClassPrivateFieldGet = 1 << 19, // __classPrivateFieldGet (used by the class private field transformation)
ClassPrivateFieldSet = 1 << 20, // __classPrivateFieldSet (used by the class private field transformation)
CreateBinding = 1 << 21, // __createBinding (use by the module transform for (re)exports and namespace imports)
FirstEmitHelper = Extends,
LastEmitHelper = CreateBinding,
// Helpers included by ES2015 for..of
ForOfIncludes = Values,
// Helpers included by ES2017 for..await..of
ForAwaitOfIncludes = AsyncValues,
// Helpers included by ES2017 async generators
AsyncGeneratorIncludes = Await | AsyncGenerator,
// Helpers included by yield* in ES2017 async generators
AsyncDelegatorIncludes = Await | AsyncDelegator | AsyncValues,
// Helpers included by ES2015 spread
SpreadIncludes = Read | SpreadArray,
}
export const enum EmitHint {
SourceFile, // Emitting a SourceFile
Expression, // Emitting an Expression
IdentifierName, // Emitting an IdentifierName
MappedTypeParameter, // Emitting a TypeParameterDeclaration inside of a MappedTypeNode
Unspecified, // Emitting an otherwise unspecified node
EmbeddedStatement, // Emitting an embedded statement
JsxAttributeValue, // Emitting a JSX attribute value
}
/* @internal */
export interface SourceFileMayBeEmittedHost {
getCompilerOptions(): CompilerOptions;
isSourceFileFromExternalLibrary(file: SourceFile): boolean;
getResolvedProjectReferenceToRedirect(fileName: string): ResolvedProjectReference | undefined;
isSourceOfProjectReferenceRedirect(fileName: string): boolean;
}
/* @internal */
export interface EmitHost extends ScriptReferenceHost, ModuleSpecifierResolutionHost, SourceFileMayBeEmittedHost {
getSourceFiles(): readonly SourceFile[];
useCaseSensitiveFileNames(): boolean;
getCurrentDirectory(): string;
getLibFileFromReference(ref: FileReference): SourceFile | undefined;
getCommonSourceDirectory(): string;
getCanonicalFileName(fileName: string): string;
getNewLine(): string;
isEmitBlocked(emitFileName: string): boolean;
getPrependNodes(): readonly (InputFiles | UnparsedSource)[];
writeFile: WriteFileCallback;
getProgramBuildInfo(): ProgramBuildInfo | undefined;
getSourceFileFromReference: Program["getSourceFileFromReference"];
readonly redirectTargetsMap: RedirectTargetsMap;
}
/* @internal */
export interface PropertyDescriptorAttributes {
enumerable?: boolean | Expression;
configurable?: boolean | Expression;
writable?: boolean | Expression;
value?: Expression;
get?: Expression;
set?: Expression;
}
export const enum OuterExpressionKinds {
Parentheses = 1 << 0,
TypeAssertions = 1 << 1,
NonNullAssertions = 1 << 2,
PartiallyEmittedExpressions = 1 << 3,
Assertions = TypeAssertions | NonNullAssertions,
All = Parentheses | Assertions | PartiallyEmittedExpressions
}
/* @internal */
export type OuterExpression =
| ParenthesizedExpression
| TypeAssertion
| AsExpression
| NonNullExpression
| PartiallyEmittedExpression;
export type TypeOfTag = "undefined" | "number" | "bigint" | "boolean" | "string" | "symbol" | "object" | "function";
/* @internal */
export interface CallBinding {
target: LeftHandSideExpression;
thisArg: Expression;
}
/* @internal */
export interface ParenthesizerRules {
getParenthesizeLeftSideOfBinaryForOperator(binaryOperator: SyntaxKind): (leftSide: Expression) => Expression;
getParenthesizeRightSideOfBinaryForOperator(binaryOperator: SyntaxKind): (rightSide: Expression) => Expression;
parenthesizeLeftSideOfBinary(binaryOperator: SyntaxKind, leftSide: Expression): Expression;
parenthesizeRightSideOfBinary(binaryOperator: SyntaxKind, leftSide: Expression | undefined, rightSide: Expression): Expression;
parenthesizeExpressionOfComputedPropertyName(expression: Expression): Expression;
parenthesizeConditionOfConditionalExpression(condition: Expression): Expression;
parenthesizeBranchOfConditionalExpression(branch: Expression): Expression;
parenthesizeExpressionOfExportDefault(expression: Expression): Expression;
parenthesizeExpressionOfNew(expression: Expression): LeftHandSideExpression;
parenthesizeLeftSideOfAccess(expression: Expression): LeftHandSideExpression;
parenthesizeOperandOfPostfixUnary(operand: Expression): LeftHandSideExpression;
parenthesizeOperandOfPrefixUnary(operand: Expression): UnaryExpression;
parenthesizeExpressionsOfCommaDelimitedList(elements: readonly Expression[]): NodeArray<Expression>;
parenthesizeExpressionForDisallowedComma(expression: Expression): Expression;
parenthesizeExpressionOfExpressionStatement(expression: Expression): Expression;
parenthesizeConciseBodyOfArrowFunction(body: Expression): Expression;
parenthesizeConciseBodyOfArrowFunction(body: ConciseBody): ConciseBody;
parenthesizeMemberOfConditionalType(member: TypeNode): TypeNode;
parenthesizeMemberOfElementType(member: TypeNode): TypeNode;
parenthesizeElementTypeOfArrayType(member: TypeNode): TypeNode;
parenthesizeConstituentTypesOfUnionOrIntersectionType(members: readonly TypeNode[]): NodeArray<TypeNode>;
parenthesizeTypeArguments(typeParameters: readonly TypeNode[] | undefined): NodeArray<TypeNode> | undefined;
}
/* @internal */
export interface NodeConverters {
convertToFunctionBlock(node: ConciseBody, multiLine?: boolean): Block;
convertToFunctionExpression(node: FunctionDeclaration): FunctionExpression;
convertToArrayAssignmentElement(element: ArrayBindingOrAssignmentElement): Expression;
convertToObjectAssignmentElement(element: ObjectBindingOrAssignmentElement): ObjectLiteralElementLike;
convertToAssignmentPattern(node: BindingOrAssignmentPattern): AssignmentPattern;
convertToObjectAssignmentPattern(node: ObjectBindingOrAssignmentPattern): ObjectLiteralExpression;
convertToArrayAssignmentPattern(node: ArrayBindingOrAssignmentPattern): ArrayLiteralExpression;
convertToAssignmentElementTarget(node: BindingOrAssignmentElementTarget): Expression;
}
export interface NodeFactory {
/* @internal */ readonly parenthesizer: ParenthesizerRules;
/* @internal */ readonly converters: NodeConverters;
createNodeArray<T extends Node>(elements?: readonly T[], hasTrailingComma?: boolean): NodeArray<T>;
//
// Literals
//
createNumericLiteral(value: string | number, numericLiteralFlags?: TokenFlags): NumericLiteral;
createBigIntLiteral(value: string | PseudoBigInt): BigIntLiteral;
createStringLiteral(text: string, isSingleQuote?: boolean): StringLiteral;
/* @internal*/ createStringLiteral(text: string, isSingleQuote?: boolean, hasExtendedUnicodeEscape?: boolean): StringLiteral; // eslint-disable-line @typescript-eslint/unified-signatures
createStringLiteralFromNode(sourceNode: PropertyNameLiteral, isSingleQuote?: boolean): StringLiteral;
createRegularExpressionLiteral(text: string): RegularExpressionLiteral;
//
// Identifiers
//
createIdentifier(text: string): Identifier;
/* @internal */ createIdentifier(text: string, typeArguments?: readonly (TypeNode | TypeParameterDeclaration)[], originalKeywordKind?: SyntaxKind): Identifier; // eslint-disable-line @typescript-eslint/unified-signatures
/* @internal */ updateIdentifier(node: Identifier, typeArguments: NodeArray<TypeNode | TypeParameterDeclaration> | undefined): Identifier;
/**
* Create a unique temporary variable.
* @param recordTempVariable An optional callback used to record the temporary variable name. This
* should usually be a reference to `hoistVariableDeclaration` from a `TransformationContext`, but
* can be `undefined` if you plan to record the temporary variable manually.
* @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes
* during emit so that the variable can be referenced in a nested function body. This is an alternative to
* setting `EmitFlags.ReuseTempVariableScope` on the nested function itself.
*/
createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, reservedInNestedScopes?: boolean): Identifier;
/**
* Create a unique temporary variable for use in a loop.
* @param reservedInNestedScopes When `true`, reserves the temporary variable name in all nested scopes
* during emit so that the variable can be referenced in a nested function body. This is an alternative to
* setting `EmitFlags.ReuseTempVariableScope` on the nested function itself.
*/
createLoopVariable(reservedInNestedScopes?: boolean): Identifier;
/** Create a unique name based on the supplied text. */
createUniqueName(text: string, flags?: GeneratedIdentifierFlags): Identifier;
/** Create a unique name generated for a node. */
getGeneratedNameForNode(node: Node | undefined, flags?: GeneratedIdentifierFlags): Identifier;
createPrivateIdentifier(text: string): PrivateIdentifier
//
// Punctuation
//
createToken(token: SyntaxKind.SuperKeyword): SuperExpression;
createToken(token: SyntaxKind.ThisKeyword): ThisExpression;
createToken(token: SyntaxKind.NullKeyword): NullLiteral;
createToken(token: SyntaxKind.TrueKeyword): TrueLiteral;
createToken(token: SyntaxKind.FalseKeyword): FalseLiteral;
createToken<TKind extends PunctuationSyntaxKind>(token: TKind): PunctuationToken<TKind>;
createToken<TKind extends KeywordTypeSyntaxKind>(token: TKind): KeywordTypeNode<TKind>;
createToken<TKind extends ModifierSyntaxKind>(token: TKind): ModifierToken<TKind>;
createToken<TKind extends KeywordSyntaxKind>(token: TKind): KeywordToken<TKind>;
createToken<TKind extends SyntaxKind.Unknown | SyntaxKind.EndOfFileToken>(token: TKind): Token<TKind>;
/*@internal*/ createToken<TKind extends SyntaxKind>(token: TKind): Token<TKind>;
//
// Reserved words
//
createSuper(): SuperExpression;
createThis(): ThisExpression;
createNull(): NullLiteral;
createTrue(): TrueLiteral;
createFalse(): FalseLiteral;
//
// Modifiers
//
createModifier<T extends ModifierSyntaxKind>(kind: T): ModifierToken<T>;
createModifiersFromModifierFlags(flags: ModifierFlags): Modifier[];
//
// Names
//
createQualifiedName(left: EntityName, right: string | Identifier): QualifiedName;
updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName;
createComputedPropertyName(expression: Expression): ComputedPropertyName;
updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName;
//
// Signature elements
//
createTypeParameterDeclaration(name: string | Identifier, constraint?: TypeNode, defaultType?: TypeNode): TypeParameterDeclaration;
updateTypeParameterDeclaration(node: TypeParameterDeclaration, name: Identifier, constraint: TypeNode | undefined, defaultType: TypeNode | undefined): TypeParameterDeclaration;
createParameterDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken?: QuestionToken, type?: TypeNode, initializer?: Expression): ParameterDeclaration;
updateParameterDeclaration(node: ParameterDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, dotDotDotToken: DotDotDotToken | undefined, name: string | BindingName, questionToken: QuestionToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): ParameterDeclaration;
createDecorator(expression: Expression): Decorator;
updateDecorator(node: Decorator, expression: Expression): Decorator;
//
// Type Elements
//
createPropertySignature(modifiers: readonly Modifier[] | undefined, name: PropertyName | string, questionToken: QuestionToken | undefined, type: TypeNode | undefined): PropertySignature;
updatePropertySignature(node: PropertySignature, modifiers: readonly Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, type: TypeNode | undefined): PropertySignature;
createPropertyDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration;
updatePropertyDeclaration(node: PropertyDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionOrExclamationToken: QuestionToken | ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): PropertyDeclaration;
createMethodSignature(modifiers: readonly Modifier[] | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): MethodSignature;
updateMethodSignature(node: MethodSignature, modifiers: readonly Modifier[] | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): MethodSignature;
createMethodDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration;
updateMethodDeclaration(node: MethodDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: PropertyName, questionToken: QuestionToken | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): MethodDeclaration;
createConstructorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration;
updateConstructorDeclaration(node: ConstructorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], body: Block | undefined): ConstructorDeclaration;
createGetAccessorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration;
updateGetAccessorDeclaration(node: GetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): GetAccessorDeclaration;
createSetAccessorDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration;
updateSetAccessorDeclaration(node: SetAccessorDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: PropertyName, parameters: readonly ParameterDeclaration[], body: Block | undefined): SetAccessorDeclaration;
createCallSignature(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): CallSignatureDeclaration;
updateCallSignature(node: CallSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): CallSignatureDeclaration;
createConstructSignature(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): ConstructSignatureDeclaration;
updateConstructSignature(node: ConstructSignatureDeclaration, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode | undefined): ConstructSignatureDeclaration;
createIndexSignature(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration;
/* @internal */ createIndexSignature(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): IndexSignatureDeclaration; // eslint-disable-line @typescript-eslint/unified-signatures
updateIndexSignature(node: IndexSignatureDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): IndexSignatureDeclaration;
createTemplateLiteralTypeSpan(type: TypeNode, literal: TemplateMiddle | TemplateTail): TemplateLiteralTypeSpan;
updateTemplateLiteralTypeSpan(node: TemplateLiteralTypeSpan, type: TypeNode, literal: TemplateMiddle | TemplateTail): TemplateLiteralTypeSpan;
//
// Types
//
createKeywordTypeNode<TKind extends KeywordTypeSyntaxKind>(kind: TKind): KeywordTypeNode<TKind>;
createTypePredicateNode(assertsModifier: AssertsKeyword | undefined, parameterName: Identifier | ThisTypeNode | string, type: TypeNode | undefined): TypePredicateNode;
updateTypePredicateNode(node: TypePredicateNode, assertsModifier: AssertsKeyword | undefined, parameterName: Identifier | ThisTypeNode, type: TypeNode | undefined): TypePredicateNode;
createTypeReferenceNode(typeName: string | EntityName, typeArguments?: readonly TypeNode[]): TypeReferenceNode;
updateTypeReferenceNode(node: TypeReferenceNode, typeName: EntityName, typeArguments: NodeArray<TypeNode> | undefined): TypeReferenceNode;
createFunctionTypeNode(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): FunctionTypeNode;
updateFunctionTypeNode(node: FunctionTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode): FunctionTypeNode;
createConstructorTypeNode(modifiers: readonly Modifier[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): ConstructorTypeNode;
/** @deprecated */
createConstructorTypeNode(typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode): ConstructorTypeNode;
updateConstructorTypeNode(node: ConstructorTypeNode, modifiers: readonly Modifier[] | undefined, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode): ConstructorTypeNode;
/** @deprecated */
updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode): ConstructorTypeNode;
createTypeQueryNode(exprName: EntityName): TypeQueryNode;
updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode;
createTypeLiteralNode(members: readonly TypeElement[] | undefined): TypeLiteralNode;
updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray<TypeElement>): TypeLiteralNode;
createArrayTypeNode(elementType: TypeNode): ArrayTypeNode;
updateArrayTypeNode(node: ArrayTypeNode, elementType: TypeNode): ArrayTypeNode;
createTupleTypeNode(elements: readonly (TypeNode | NamedTupleMember)[]): TupleTypeNode;
updateTupleTypeNode(node: TupleTypeNode, elements: readonly (TypeNode | NamedTupleMember)[]): TupleTypeNode;
createNamedTupleMember(dotDotDotToken: DotDotDotToken | undefined, name: Identifier, questionToken: QuestionToken | undefined, type: TypeNode): NamedTupleMember;
updateNamedTupleMember(node: NamedTupleMember, dotDotDotToken: DotDotDotToken | undefined, name: Identifier, questionToken: QuestionToken | undefined, type: TypeNode): NamedTupleMember;
createOptionalTypeNode(type: TypeNode): OptionalTypeNode;
updateOptionalTypeNode(node: OptionalTypeNode, type: TypeNode): OptionalTypeNode;
createRestTypeNode(type: TypeNode): RestTypeNode;
updateRestTypeNode(node: RestTypeNode, type: TypeNode): RestTypeNode;
createUnionTypeNode(types: readonly TypeNode[]): UnionTypeNode;
updateUnionTypeNode(node: UnionTypeNode, types: NodeArray<TypeNode>): UnionTypeNode;
createIntersectionTypeNode(types: readonly TypeNode[]): IntersectionTypeNode;
updateIntersectionTypeNode(node: IntersectionTypeNode, types: NodeArray<TypeNode>): IntersectionTypeNode;
createConditionalTypeNode(checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode;
updateConditionalTypeNode(node: ConditionalTypeNode, checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode): ConditionalTypeNode;
createInferTypeNode(typeParameter: TypeParameterDeclaration): InferTypeNode;
updateInferTypeNode(node: InferTypeNode, typeParameter: TypeParameterDeclaration): InferTypeNode;
createImportTypeNode(argument: TypeNode, qualifier?: EntityName, typeArguments?: readonly TypeNode[], isTypeOf?: boolean): ImportTypeNode;
updateImportTypeNode(node: ImportTypeNode, argument: TypeNode, qualifier: EntityName | undefined, typeArguments: readonly TypeNode[] | undefined, isTypeOf?: boolean): ImportTypeNode;
createParenthesizedType(type: TypeNode): ParenthesizedTypeNode;
updateParenthesizedType(node: ParenthesizedTypeNode, type: TypeNode): ParenthesizedTypeNode;
createThisTypeNode(): ThisTypeNode;
createTypeOperatorNode(operator: SyntaxKind.KeyOfKeyword | SyntaxKind.UniqueKeyword | SyntaxKind.ReadonlyKeyword, type: TypeNode): TypeOperatorNode;
updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode;
createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
createMappedTypeNode(readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode;
updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode;
createLiteralTypeNode(literal: LiteralTypeNode["literal"]): LiteralTypeNode;
updateLiteralTypeNode(node: LiteralTypeNode, literal: LiteralTypeNode["literal"]): LiteralTypeNode;
createTemplateLiteralType(head: TemplateHead, templateSpans: readonly TemplateLiteralTypeSpan[]): TemplateLiteralTypeNode;
updateTemplateLiteralType(node: TemplateLiteralTypeNode, head: TemplateHead, templateSpans: readonly TemplateLiteralTypeSpan[]): TemplateLiteralTypeNode;
//
// Binding Patterns
//
createObjectBindingPattern(elements: readonly BindingElement[]): ObjectBindingPattern;
updateObjectBindingPattern(node: ObjectBindingPattern, elements: readonly BindingElement[]): ObjectBindingPattern;
createArrayBindingPattern(elements: readonly ArrayBindingElement[]): ArrayBindingPattern;
updateArrayBindingPattern(node: ArrayBindingPattern, elements: readonly ArrayBindingElement[]): ArrayBindingPattern;
createBindingElement(dotDotDotToken: DotDotDotToken | undefined, propertyName: string | PropertyName | undefined, name: string | BindingName, initializer?: Expression): BindingElement;
updateBindingElement(node: BindingElement, dotDotDotToken: DotDotDotToken | undefined, propertyName: PropertyName | undefined, name: BindingName, initializer: Expression | undefined): BindingElement;
//
// Expression
//
createArrayLiteralExpression(elements?: readonly Expression[], multiLine?: boolean): ArrayLiteralExpression;
updateArrayLiteralExpression(node: ArrayLiteralExpression, elements: readonly Expression[]): ArrayLiteralExpression;
createObjectLiteralExpression(properties?: readonly ObjectLiteralElementLike[], multiLine?: boolean): ObjectLiteralExpression;
updateObjectLiteralExpression(node: ObjectLiteralExpression, properties: readonly ObjectLiteralElementLike[]): ObjectLiteralExpression;
createPropertyAccessExpression(expression: Expression, name: string | MemberName): PropertyAccessExpression;
updatePropertyAccessExpression(node: PropertyAccessExpression, expression: Expression, name: MemberName): PropertyAccessExpression;
createPropertyAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, name: string | MemberName): PropertyAccessChain;
updatePropertyAccessChain(node: PropertyAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, name: MemberName): PropertyAccessChain;
createElementAccessExpression(expression: Expression, index: number | Expression): ElementAccessExpression;
updateElementAccessExpression(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression): ElementAccessExpression;
createElementAccessChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, index: number | Expression): ElementAccessChain;
updateElementAccessChain(node: ElementAccessChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, argumentExpression: Expression): ElementAccessChain;
createCallExpression(expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined): CallExpression;
updateCallExpression(node: CallExpression, expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[]): CallExpression;
createCallChain(expression: Expression, questionDotToken: QuestionDotToken | undefined, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined): CallChain;
updateCallChain(node: CallChain, expression: Expression, questionDotToken: QuestionDotToken | undefined, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[]): CallChain;
createNewExpression(expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined): NewExpression;
updateNewExpression(node: NewExpression, expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[] | undefined): NewExpression;
createTaggedTemplateExpression(tag: Expression, typeArguments: readonly TypeNode[] | undefined, template: TemplateLiteral): TaggedTemplateExpression;
updateTaggedTemplateExpression(node: TaggedTemplateExpression, tag: Expression, typeArguments: readonly TypeNode[] | undefined, template: TemplateLiteral): TaggedTemplateExpression;
createTypeAssertion(type: TypeNode, expression: Expression): TypeAssertion;
updateTypeAssertion(node: TypeAssertion, type: TypeNode, expression: Expression): TypeAssertion;
createParenthesizedExpression(expression: Expression): ParenthesizedExpression;
updateParenthesizedExpression(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression;
createFunctionExpression(modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[] | undefined, type: TypeNode | undefined, body: Block): FunctionExpression;
updateFunctionExpression(node: FunctionExpression, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block): FunctionExpression;
createArrowFunction(modifiers: readonly Modifier[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken | undefined, body: ConciseBody): ArrowFunction;
updateArrowFunction(node: ArrowFunction, modifiers: readonly Modifier[] | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, equalsGreaterThanToken: EqualsGreaterThanToken, body: ConciseBody): ArrowFunction;
createDeleteExpression(expression: Expression): DeleteExpression;
updateDeleteExpression(node: DeleteExpression, expression: Expression): DeleteExpression;
createTypeOfExpression(expression: Expression): TypeOfExpression;
updateTypeOfExpression(node: TypeOfExpression, expression: Expression): TypeOfExpression;
createVoidExpression(expression: Expression): VoidExpression;
updateVoidExpression(node: VoidExpression, expression: Expression): VoidExpression;
createAwaitExpression(expression: Expression): AwaitExpression;
updateAwaitExpression(node: AwaitExpression, expression: Expression): AwaitExpression;
createPrefixUnaryExpression(operator: PrefixUnaryOperator, operand: Expression): PrefixUnaryExpression;
updatePrefixUnaryExpression(node: PrefixUnaryExpression, operand: Expression): PrefixUnaryExpression;
createPostfixUnaryExpression(operand: Expression, operator: PostfixUnaryOperator): PostfixUnaryExpression;
updatePostfixUnaryExpression(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression;
createBinaryExpression(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression;
updateBinaryExpression(node: BinaryExpression, left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression): BinaryExpression;
createConditionalExpression(condition: Expression, questionToken: QuestionToken | undefined, whenTrue: Expression, colonToken: ColonToken | undefined, whenFalse: Expression): ConditionalExpression;
updateConditionalExpression(node: ConditionalExpression, condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression): ConditionalExpression;
createTemplateExpression(head: TemplateHead, templateSpans: readonly TemplateSpan[]): TemplateExpression;
updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: readonly TemplateSpan[]): TemplateExpression;
createTemplateHead(text: string, rawText?: string, templateFlags?: TokenFlags): TemplateHead;
createTemplateHead(text: string | undefined, rawText: string, templateFlags?: TokenFlags): TemplateHead;
createTemplateMiddle(text: string, rawText?: string, templateFlags?: TokenFlags): TemplateMiddle;
createTemplateMiddle(text: string | undefined, rawText: string, templateFlags?: TokenFlags): TemplateMiddle;
createTemplateTail(text: string, rawText?: string, templateFlags?: TokenFlags): TemplateTail;
createTemplateTail(text: string | undefined, rawText: string, templateFlags?: TokenFlags): TemplateTail;
createNoSubstitutionTemplateLiteral(text: string, rawText?: string): NoSubstitutionTemplateLiteral;
createNoSubstitutionTemplateLiteral(text: string | undefined, rawText: string): NoSubstitutionTemplateLiteral;
/* @internal */ createLiteralLikeNode(kind: LiteralToken["kind"] | SyntaxKind.JsxTextAllWhiteSpaces, text: string): LiteralToken;
/* @internal */ createTemplateLiteralLikeNode(kind: TemplateLiteralToken["kind"], text: string, rawText: string, templateFlags: TokenFlags | undefined): TemplateLiteralLikeNode;
createYieldExpression(asteriskToken: AsteriskToken, expression: Expression): YieldExpression;
createYieldExpression(asteriskToken: undefined, expression: Expression | undefined): YieldExpression;
/* @internal */ createYieldExpression(asteriskToken: AsteriskToken | undefined, expression: Expression | undefined): YieldExpression; // eslint-disable-line @typescript-eslint/unified-signatures
updateYieldExpression(node: YieldExpression, asteriskToken: AsteriskToken | undefined, expression: Expression | undefined): YieldExpression;
createSpreadElement(expression: Expression): SpreadElement;
updateSpreadElement(node: SpreadElement, expression: Expression): SpreadElement;
createClassExpression(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression;
updateClassExpression(node: ClassExpression, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassExpression;
createOmittedExpression(): OmittedExpression;
createExpressionWithTypeArguments(expression: Expression, typeArguments: readonly TypeNode[] | undefined): ExpressionWithTypeArguments;
updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, expression: Expression, typeArguments: readonly TypeNode[] | undefined): ExpressionWithTypeArguments;
createAsExpression(expression: Expression, type: TypeNode): AsExpression;
updateAsExpression(node: AsExpression, expression: Expression, type: TypeNode): AsExpression;
createNonNullExpression(expression: Expression): NonNullExpression;
updateNonNullExpression(node: NonNullExpression, expression: Expression): NonNullExpression;
createNonNullChain(expression: Expression): NonNullChain;
updateNonNullChain(node: NonNullChain, expression: Expression): NonNullChain;
createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty;
updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty;
//
// Misc
//
createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan;
updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan;
createSemicolonClassElement(): SemicolonClassElement;
//
// Element
//
createBlock(statements: readonly Statement[], multiLine?: boolean): Block;
updateBlock(node: Block, statements: readonly Statement[]): Block;
createVariableStatement(modifiers: readonly Modifier[] | undefined, declarationList: VariableDeclarationList | readonly VariableDeclaration[]): VariableStatement;
updateVariableStatement(node: VariableStatement, modifiers: readonly Modifier[] | undefined, declarationList: VariableDeclarationList): VariableStatement;
createEmptyStatement(): EmptyStatement;
createExpressionStatement(expression: Expression): ExpressionStatement;
updateExpressionStatement(node: ExpressionStatement, expression: Expression): ExpressionStatement;
createIfStatement(expression: Expression, thenStatement: Statement, elseStatement?: Statement): IfStatement;
updateIfStatement(node: IfStatement, expression: Expression, thenStatement: Statement, elseStatement: Statement | undefined): IfStatement;
createDoStatement(statement: Statement, expression: Expression): DoStatement;
updateDoStatement(node: DoStatement, statement: Statement, expression: Expression): DoStatement;
createWhileStatement(expression: Expression, statement: Statement): WhileStatement;
updateWhileStatement(node: WhileStatement, expression: Expression, statement: Statement): WhileStatement;
createForStatement(initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement): ForStatement;
updateForStatement(node: ForStatement, initializer: ForInitializer | undefined, condition: Expression | undefined, incrementor: Expression | undefined, statement: Statement): ForStatement;
createForInStatement(initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement;
updateForInStatement(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement;
createForOfStatement(awaitModifier: AwaitKeyword | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement;
updateForOfStatement(node: ForOfStatement, awaitModifier: AwaitKeyword | undefined, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement;
createContinueStatement(label?: string | Identifier): ContinueStatement;
updateContinueStatement(node: ContinueStatement, label: Identifier | undefined): ContinueStatement;
createBreakStatement(label?: string | Identifier): BreakStatement;
updateBreakStatement(node: BreakStatement, label: Identifier | undefined): BreakStatement;
createReturnStatement(expression?: Expression): ReturnStatement;
updateReturnStatement(node: ReturnStatement, expression: Expression | undefined): ReturnStatement;
createWithStatement(expression: Expression, statement: Statement): WithStatement;
updateWithStatement(node: WithStatement, expression: Expression, statement: Statement): WithStatement;
createSwitchStatement(expression: Expression, caseBlock: CaseBlock): SwitchStatement;
updateSwitchStatement(node: SwitchStatement, expression: Expression, caseBlock: CaseBlock): SwitchStatement;
createLabeledStatement(label: string | Identifier, statement: Statement): LabeledStatement;
updateLabeledStatement(node: LabeledStatement, label: Identifier, statement: Statement): LabeledStatement;
createThrowStatement(expression: Expression): ThrowStatement;
updateThrowStatement(node: ThrowStatement, expression: Expression): ThrowStatement;
createTryStatement(tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement;
updateTryStatement(node: TryStatement, tryBlock: Block, catchClause: CatchClause | undefined, finallyBlock: Block | undefined): TryStatement;
createDebuggerStatement(): DebuggerStatement;
createVariableDeclaration(name: string | BindingName, exclamationToken?: ExclamationToken, type?: TypeNode, initializer?: Expression): VariableDeclaration;
updateVariableDeclaration(node: VariableDeclaration, name: BindingName, exclamationToken: ExclamationToken | undefined, type: TypeNode | undefined, initializer: Expression | undefined): VariableDeclaration;
createVariableDeclarationList(declarations: readonly VariableDeclaration[], flags?: NodeFlags): VariableDeclarationList;
updateVariableDeclarationList(node: VariableDeclarationList, declarations: readonly VariableDeclaration[]): VariableDeclarationList;
createFunctionDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration;
updateFunctionDeclaration(node: FunctionDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, asteriskToken: AsteriskToken | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined, body: Block | undefined): FunctionDeclaration;
createClassDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration;
updateClassDeclaration(node: ClassDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier | undefined, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly ClassElement[]): ClassDeclaration;
createInterfaceDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration;
updateInterfaceDeclaration(node: InterfaceDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, heritageClauses: readonly HeritageClause[] | undefined, members: readonly TypeElement[]): InterfaceDeclaration;
createTypeAliasDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration;
updateTypeAliasDeclaration(node: TypeAliasDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, typeParameters: readonly TypeParameterDeclaration[] | undefined, type: TypeNode): TypeAliasDeclaration;
createEnumDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: string | Identifier, members: readonly EnumMember[]): EnumDeclaration;
updateEnumDeclaration(node: EnumDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: Identifier, members: readonly EnumMember[]): EnumDeclaration;
createModuleDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined, flags?: NodeFlags): ModuleDeclaration;
updateModuleDeclaration(node: ModuleDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, name: ModuleName, body: ModuleBody | undefined): ModuleDeclaration;
createModuleBlock(statements: readonly Statement[]): ModuleBlock;
updateModuleBlock(node: ModuleBlock, statements: readonly Statement[]): ModuleBlock;
createCaseBlock(clauses: readonly CaseOrDefaultClause[]): CaseBlock;
updateCaseBlock(node: CaseBlock, clauses: readonly CaseOrDefaultClause[]): CaseBlock;
createNamespaceExportDeclaration(name: string | Identifier): NamespaceExportDeclaration;
updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration;
createImportEqualsDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration;
updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration;
createImportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration;
updateImportDeclaration(node: ImportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration;
createImportClause(isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause;
updateImportClause(node: ImportClause, isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause;
createNamespaceImport(name: Identifier): NamespaceImport;
updateNamespaceImport(node: NamespaceImport, name: Identifier): NamespaceImport;
createNamespaceExport(name: Identifier): NamespaceExport;
updateNamespaceExport(node: NamespaceExport, name: Identifier): NamespaceExport;
createNamedImports(elements: readonly ImportSpecifier[]): NamedImports;
updateNamedImports(node: NamedImports, elements: readonly ImportSpecifier[]): NamedImports;
createImportSpecifier(propertyName: Identifier | undefined, name: Identifier): ImportSpecifier;
updateImportSpecifier(node: ImportSpecifier, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier;
createExportAssignment(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment;
updateExportAssignment(node: ExportAssignment, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, expression: Expression): ExportAssignment;
createExportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression): ExportDeclaration;
updateExportDeclaration(node: ExportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined): ExportDeclaration;
createNamedExports(elements: readonly ExportSpecifier[]): NamedExports;
updateNamedExports(node: NamedExports, elements: readonly ExportSpecifier[]): NamedExports;
createExportSpecifier(propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier;
updateExportSpecifier(node: ExportSpecifier, propertyName: Identifier | undefined, name: Identifier): ExportSpecifier;
/* @internal*/ createMissingDeclaration(): MissingDeclaration;
//
// Module references
//
createExternalModuleReference(expression: Expression): ExternalModuleReference;
updateExternalModuleReference(node: ExternalModuleReference, expression: Expression): ExternalModuleReference;
//
// JSDoc
//
createJSDocAllType(): JSDocAllType;
createJSDocUnknownType(): JSDocUnknownType;
createJSDocNonNullableType(type: TypeNode): JSDocNonNullableType;
updateJSDocNonNullableType(node: JSDocNonNullableType, type: TypeNode): JSDocNonNullableType;
createJSDocNullableType(type: TypeNode): JSDocNullableType;
updateJSDocNullableType(node: JSDocNullableType, type: TypeNode): JSDocNullableType;
createJSDocOptionalType(type: TypeNode): JSDocOptionalType;
updateJSDocOptionalType(node: JSDocOptionalType, type: TypeNode): JSDocOptionalType;
createJSDocFunctionType(parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): JSDocFunctionType;
updateJSDocFunctionType(node: JSDocFunctionType, parameters: readonly ParameterDeclaration[], type: TypeNode | undefined): JSDocFunctionType;
createJSDocVariadicType(type: TypeNode): JSDocVariadicType;
updateJSDocVariadicType(node: JSDocVariadicType, type: TypeNode): JSDocVariadicType;
createJSDocNamepathType(type: TypeNode): JSDocNamepathType;
updateJSDocNamepathType(node: JSDocNamepathType, type: TypeNode): JSDocNamepathType;
createJSDocTypeExpression(type: TypeNode): JSDocTypeExpression;
updateJSDocTypeExpression(node: JSDocTypeExpression, type: TypeNode): JSDocTypeExpression;
createJSDocNameReference(name: EntityName): JSDocNameReference;
updateJSDocNameReference(node: JSDocNameReference, name: EntityName): JSDocNameReference;
createJSDocLink(name: EntityName | undefined, text: string): JSDocLink;
updateJSDocLink(node: JSDocLink, name: EntityName | undefined, text: string): JSDocLink;
createJSDocTypeLiteral(jsDocPropertyTags?: readonly JSDocPropertyLikeTag[], isArrayType?: boolean): JSDocTypeLiteral;
updateJSDocTypeLiteral(node: JSDocTypeLiteral, jsDocPropertyTags: readonly JSDocPropertyLikeTag[] | undefined, isArrayType: boolean | undefined): JSDocTypeLiteral;
createJSDocSignature(typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type?: JSDocReturnTag): JSDocSignature;
updateJSDocSignature(node: JSDocSignature, typeParameters: readonly JSDocTemplateTag[] | undefined, parameters: readonly JSDocParameterTag[], type: JSDocReturnTag | undefined): JSDocSignature;
createJSDocTemplateTag(tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocTemplateTag;
updateJSDocTemplateTag(node: JSDocTemplateTag, tagName: Identifier | undefined, constraint: JSDocTypeExpression | undefined, typeParameters: readonly TypeParameterDeclaration[], comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocTemplateTag;
createJSDocTypedefTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression | JSDocTypeLiteral, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocTypedefTag;
updateJSDocTypedefTag(node: JSDocTypedefTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | JSDocTypeLiteral | undefined, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocTypedefTag;
createJSDocParameterTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocParameterTag;
updateJSDocParameterTag(node: JSDocParameterTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocParameterTag;
createJSDocPropertyTag(tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression?: JSDocTypeExpression, isNameFirst?: boolean, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocPropertyTag;
updateJSDocPropertyTag(node: JSDocPropertyTag, tagName: Identifier | undefined, name: EntityName, isBracketed: boolean, typeExpression: JSDocTypeExpression | undefined, isNameFirst: boolean, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocPropertyTag;
createJSDocTypeTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocTypeTag;
updateJSDocTypeTag(node: JSDocTypeTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocTypeTag;
createJSDocSeeTag(tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocSeeTag;
updateJSDocSeeTag(node: JSDocSeeTag, tagName: Identifier | undefined, nameExpression: JSDocNameReference | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocSeeTag;
createJSDocReturnTag(tagName: Identifier | undefined, typeExpression?: JSDocTypeExpression, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocReturnTag;
updateJSDocReturnTag(node: JSDocReturnTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocReturnTag;
createJSDocThisTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocThisTag;
updateJSDocThisTag(node: JSDocThisTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocThisTag;
createJSDocEnumTag(tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocEnumTag;
updateJSDocEnumTag(node: JSDocEnumTag, tagName: Identifier | undefined, typeExpression: JSDocTypeExpression, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocEnumTag;
createJSDocCallbackTag(tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName?: Identifier | JSDocNamespaceDeclaration, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocCallbackTag;
updateJSDocCallbackTag(node: JSDocCallbackTag, tagName: Identifier | undefined, typeExpression: JSDocSignature, fullName: Identifier | JSDocNamespaceDeclaration | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocCallbackTag;
createJSDocAugmentsTag(tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocAugmentsTag;
updateJSDocAugmentsTag(node: JSDocAugmentsTag, tagName: Identifier | undefined, className: JSDocAugmentsTag["class"], comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocAugmentsTag;
createJSDocImplementsTag(tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocImplementsTag;
updateJSDocImplementsTag(node: JSDocImplementsTag, tagName: Identifier | undefined, className: JSDocImplementsTag["class"], comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocImplementsTag;
createJSDocAuthorTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocAuthorTag;
updateJSDocAuthorTag(node: JSDocAuthorTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocAuthorTag;
createJSDocClassTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocClassTag;
updateJSDocClassTag(node: JSDocClassTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocClassTag;
createJSDocPublicTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocPublicTag;
updateJSDocPublicTag(node: JSDocPublicTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocPublicTag;
createJSDocPrivateTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocPrivateTag;
updateJSDocPrivateTag(node: JSDocPrivateTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocPrivateTag;
createJSDocProtectedTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocProtectedTag;
updateJSDocProtectedTag(node: JSDocProtectedTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocProtectedTag;
createJSDocReadonlyTag(tagName: Identifier | undefined, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocReadonlyTag;
updateJSDocReadonlyTag(node: JSDocReadonlyTag, tagName: Identifier | undefined, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocReadonlyTag;
createJSDocUnknownTag(tagName: Identifier, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocUnknownTag;
updateJSDocUnknownTag(node: JSDocUnknownTag, tagName: Identifier, comment: string | NodeArray<JSDocText | JSDocLink> | undefined): JSDocUnknownTag;
createJSDocDeprecatedTag(tagName: Identifier, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocDeprecatedTag;
updateJSDocDeprecatedTag(node: JSDocDeprecatedTag, tagName: Identifier, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocDeprecatedTag;
createJSDocOverrideTag(tagName: Identifier, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocOverrideTag;
updateJSDocOverrideTag(node: JSDocOverrideTag, tagName: Identifier, comment?: string | NodeArray<JSDocText | JSDocLink>): JSDocOverrideTag;
createJSDocText(text: string): JSDocText;
updateJSDocText(node: JSDocText, text: string): JSDocText;
createJSDocComment(comment?: string | NodeArray<JSDocText | JSDocLink> | undefined, tags?: readonly JSDocTag[] | undefined): JSDoc;
updateJSDocComment(node: JSDoc, comment: string | NodeArray<JSDocText | JSDocLink> | undefined, tags: readonly JSDocTag[] | undefined): JSDoc;
//
// JSX
//
createJsxElement(openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement;
updateJsxElement(node: JsxElement, openingElement: JsxOpeningElement, children: readonly JsxChild[], closingElement: JsxClosingElement): JsxElement;
createJsxSelfClosingElement(tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxSelfClosingElement;
updateJsxSelfClosingElement(node: JsxSelfClosingElement, tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxSelfClosingElement;
createJsxOpeningElement(tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxOpeningElement;
updateJsxOpeningElement(node: JsxOpeningElement, tagName: JsxTagNameExpression, typeArguments: readonly TypeNode[] | undefined, attributes: JsxAttributes): JsxOpeningElement;
createJsxClosingElement(tagName: JsxTagNameExpression): JsxClosingElement;
updateJsxClosingElement(node: JsxClosingElement, tagName: JsxTagNameExpression): JsxClosingElement;
createJsxFragment(openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment): JsxFragment;
createJsxText(text: string, containsOnlyTriviaWhiteSpaces?: boolean): JsxText;
updateJsxText(node: JsxText, text: string, containsOnlyTriviaWhiteSpaces?: boolean): JsxText;
createJsxOpeningFragment(): JsxOpeningFragment;
createJsxJsxClosingFragment(): JsxClosingFragment;
updateJsxFragment(node: JsxFragment, openingFragment: JsxOpeningFragment, children: readonly JsxChild[], closingFragment: JsxClosingFragment): JsxFragment;
createJsxAttribute(name: Identifier, initializer: StringLiteral | JsxExpression | undefined): JsxAttribute;
updateJsxAttribute(node: JsxAttribute, name: Identifier, initializer: StringLiteral | JsxExpression | undefined): JsxAttribute;
createJsxAttributes(properties: readonly JsxAttributeLike[]): JsxAttributes;
updateJsxAttributes(node: JsxAttributes, properties: readonly JsxAttributeLike[]): JsxAttributes;
createJsxSpreadAttribute(expression: Expression): JsxSpreadAttribute;
updateJsxSpreadAttribute(node: JsxSpreadAttribute, expression: Expression): JsxSpreadAttribute;
createJsxExpression(dotDotDotToken: DotDotDotToken | undefined, expression: Expression | undefined): JsxExpression;
updateJsxExpression(node: JsxExpression, expression: Expression | undefined): JsxExpression;
//
// Clauses
//
createCaseClause(expression: Expression, statements: readonly Statement[]): CaseClause;
updateCaseClause(node: CaseClause, expression: Expression, statements: readonly Statement[]): CaseClause;
createDefaultClause(statements: readonly Statement[]): DefaultClause;
updateDefaultClause(node: DefaultClause, statements: readonly Statement[]): DefaultClause;
createHeritageClause(token: HeritageClause["token"], types: readonly ExpressionWithTypeArguments[]): HeritageClause;
updateHeritageClause(node: HeritageClause, types: readonly ExpressionWithTypeArguments[]): HeritageClause;
createCatchClause(variableDeclaration: string | VariableDeclaration | undefined, block: Block): CatchClause;
updateCatchClause(node: CatchClause, variableDeclaration: VariableDeclaration | undefined, block: Block): CatchClause;
//
// Property assignments
//
createPropertyAssignment(name: string | PropertyName, initializer: Expression): PropertyAssignment;
updatePropertyAssignment(node: PropertyAssignment, name: PropertyName, initializer: Expression): PropertyAssignment;
createShorthandPropertyAssignment(name: string | Identifier, objectAssignmentInitializer?: Expression): ShorthandPropertyAssignment;
updateShorthandPropertyAssignment(node: ShorthandPropertyAssignment, name: Identifier, objectAssignmentInitializer: Expression | undefined): ShorthandPropertyAssignment;
createSpreadAssignment(expression: Expression): SpreadAssignment;
updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment;
//
// Enum
//
createEnumMember(name: string | PropertyName, initializer?: Expression): EnumMember;
updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined): EnumMember;
//
// Top-level nodes
//
createSourceFile(statements: readonly Statement[], endOfFileToken: EndOfFileToken, flags: NodeFlags): SourceFile;
updateSourceFile(node: SourceFile, statements: readonly Statement[], isDeclarationFile?: boolean, referencedFiles?: readonly FileReference[], typeReferences?: readonly FileReference[], hasNoDefaultLib?: boolean, libReferences?: readonly FileReference[]): SourceFile;
/* @internal */ createUnparsedSource(prologues: readonly UnparsedPrologue[], syntheticReferences: readonly UnparsedSyntheticReference[] | undefined, texts: readonly UnparsedSourceText[]): UnparsedSource;
/* @internal */ createUnparsedPrologue(data?: string): UnparsedPrologue;
/* @internal */ createUnparsedPrepend(data: string | undefined, texts: readonly UnparsedSourceText[]): UnparsedPrepend;
/* @internal */ createUnparsedTextLike(data: string | undefined, internal: boolean): UnparsedTextLike;
/* @internal */ createUnparsedSyntheticReference(section: BundleFileHasNoDefaultLib | BundleFileReference): UnparsedSyntheticReference;
/* @internal */ createInputFiles(): InputFiles;
//
// Synthetic Nodes
//
/* @internal */ createSyntheticExpression(type: Type, isSpread?: boolean, tupleNameSource?: ParameterDeclaration | NamedTupleMember): SyntheticExpression;
/* @internal */ createSyntaxList(children: Node[]): SyntaxList;
//
// Transformation nodes
//
createNotEmittedStatement(original: Node): NotEmittedStatement;
/* @internal */ createEndOfDeclarationMarker(original: Node): EndOfDeclarationMarker;
/* @internal */ createMergeDeclarationMarker(original: Node): MergeDeclarationMarker;
createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression;
updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression;
/* @internal */ createSyntheticReferenceExpression(expression: Expression, thisArg: Expression): SyntheticReferenceExpression;
/* @internal */ updateSyntheticReferenceExpression(node: SyntheticReferenceExpression, expression: Expression, thisArg: Expression): SyntheticReferenceExpression;
createCommaListExpression(elements: readonly Expression[]): CommaListExpression;
updateCommaListExpression(node: CommaListExpression, elements: readonly Expression[]): CommaListExpression;
createBundle(sourceFiles: readonly SourceFile[], prepends?: readonly (UnparsedSource | InputFiles)[]): Bundle;
updateBundle(node: Bundle, sourceFiles: readonly SourceFile[], prepends?: readonly (UnparsedSource | InputFiles)[]): Bundle;
//
// Common operators
//
createComma(left: Expression, right: Expression): BinaryExpression;
createAssignment(left: ObjectLiteralExpression | ArrayLiteralExpression, right: Expression): DestructuringAssignment;
createAssignment(left: Expression, right: Expression): AssignmentExpression<EqualsToken>;
createLogicalOr(left: Expression, right: Expression): BinaryExpression;
createLogicalAnd(left: Expression, right: Expression): BinaryExpression;
createBitwiseOr(left: Expression, right: Expression): BinaryExpression;
createBitwiseXor(left: Expression, right: Expression): BinaryExpression;
createBitwiseAnd(left: Expression, right: Expression): BinaryExpression;
createStrictEquality(left: Expression, right: Expression): BinaryExpression;
createStrictInequality(left: Expression, right: Expression): BinaryExpression;
createEquality(left: Expression, right: Expression): BinaryExpression;
createInequality(left: Expression, right: Expression): BinaryExpression;
createLessThan(left: Expression, right: Expression): BinaryExpression;
createLessThanEquals(left: Expression, right: Expression): BinaryExpression;
createGreaterThan(left: Expression, right: Expression): BinaryExpression;
createGreaterThanEquals(left: Expression, right: Expression): BinaryExpression;
createLeftShift(left: Expression, right: Expression): BinaryExpression;
createRightShift(left: Expression, right: Expression): BinaryExpression;
createUnsignedRightShift(left: Expression, right: Expression): BinaryExpression;
createAdd(left: Expression, right: Expression): BinaryExpression;
createSubtract(left: Expression, right: Expression): BinaryExpression;
createMultiply(left: Expression, right: Expression): BinaryExpression;
createDivide(left: Expression, right: Expression): BinaryExpression;
createModulo(left: Expression, right: Expression): BinaryExpression;
createExponent(left: Expression, right: Expression): BinaryExpression;
createPrefixPlus(operand: Expression): PrefixUnaryExpression;
createPrefixMinus(operand: Expression): PrefixUnaryExpression;
createPrefixIncrement(operand: Expression): PrefixUnaryExpression;
createPrefixDecrement(operand: Expression): PrefixUnaryExpression;
createBitwiseNot(operand: Expression): PrefixUnaryExpression;
createLogicalNot(operand: Expression): PrefixUnaryExpression;
createPostfixIncrement(operand: Expression): PostfixUnaryExpression;
createPostfixDecrement(operand: Expression): PostfixUnaryExpression;
//
// Compound Nodes
//
createImmediatelyInvokedFunctionExpression(statements: readonly Statement[]): CallExpression;
createImmediatelyInvokedFunctionExpression(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression;
createImmediatelyInvokedArrowFunction(statements: readonly Statement[]): CallExpression;
createImmediatelyInvokedArrowFunction(statements: readonly Statement[], param: ParameterDeclaration, paramValue: Expression): CallExpression;
createVoidZero(): VoidExpression;
createExportDefault(expression: Expression): ExportAssignment;
createExternalModuleExport(exportName: Identifier): ExportDeclaration;
/* @internal */ createTypeCheck(value: Expression, tag: TypeOfTag): Expression;
/* @internal */ createMethodCall(object: Expression, methodName: string | Identifier, argumentsList: readonly Expression[]): CallExpression;
/* @internal */ createGlobalMethodCall(globalObjectName: string, globalMethodName: string, argumentsList: readonly Expression[]): CallExpression;
/* @internal */ createFunctionBindCall(target: Expression, thisArg: Expression, argumentsList: readonly Expression[]): CallExpression;
/* @internal */ createFunctionCallCall(target: Expression, thisArg: Expression, argumentsList: readonly Expression[]): CallExpression;
/* @internal */ createFunctionApplyCall(target: Expression, thisArg: Expression, argumentsExpression: Expression): CallExpression;
/* @internal */ createObjectDefinePropertyCall(target: Expression, propertyName: string | Expression, attributes: Expression): CallExpression;
/* @internal */ createPropertyDescriptor(attributes: PropertyDescriptorAttributes, singleLine?: boolean): ObjectLiteralExpression;
/* @internal */ createArraySliceCall(array: Expression, start?: number | Expression): CallExpression;
/* @internal */ createArrayConcatCall(array: Expression, values: readonly Expression[]): CallExpression;
/* @internal */ createCallBinding(expression: Expression, recordTempVariable: (temp: Identifier) => void, languageVersion?: ScriptTarget, cacheIdentifiers?: boolean): CallBinding;
/* @internal */ inlineExpressions(expressions: readonly Expression[]): Expression;
/**
* Gets the internal name of a declaration. This is primarily used for declarations that can be
* referred to by name in the body of an ES5 class function body. An internal name will *never*
* be prefixed with an module or namespace export modifier like "exports." when emitted as an
* expression. An internal name will also *never* be renamed due to a collision with a block
* scoped variable.
*
* @param node The declaration.
* @param allowComments A value indicating whether comments may be emitted for the name.
* @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
*/
/* @internal */ getInternalName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier;
/**
* Gets the local name of a declaration. This is primarily used for declarations that can be
* referred to by name in the declaration's immediate scope (classes, enums, namespaces). A
* local name will *never* be prefixed with an module or namespace export modifier like
* "exports." when emitted as an expression.
*
* @param node The declaration.
* @param allowComments A value indicating whether comments may be emitted for the name.
* @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
*/
/* @internal */ getLocalName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier;
/**
* Gets the export name of a declaration. This is primarily used for declarations that can be
* referred to by name in the declaration's immediate scope (classes, enums, namespaces). An
* export name will *always* be prefixed with a module or namespace export modifier like
* `"exports."` when emitted as an expression if the name points to an exported symbol.
*
* @param node The declaration.
* @param allowComments A value indicating whether comments may be emitted for the name.
* @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
*/
/* @internal */ getExportName(node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier;
/**
* Gets the name of a declaration for use in declarations.
*
* @param node The declaration.
* @param allowComments A value indicating whether comments may be emitted for the name.
* @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
*/
/* @internal */ getDeclarationName(node: Declaration | undefined, allowComments?: boolean, allowSourceMaps?: boolean): Identifier;
/**
* Gets a namespace-qualified name for use in expressions.
*
* @param ns The namespace identifier.
* @param name The name.
* @param allowComments A value indicating whether comments may be emitted for the name.
* @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
*/
/* @internal */ getNamespaceMemberName(ns: Identifier, name: Identifier, allowComments?: boolean, allowSourceMaps?: boolean): PropertyAccessExpression;
/**
* Gets the exported name of a declaration for use in expressions.
*
* An exported name will *always* be prefixed with an module or namespace export modifier like
* "exports." if the name points to an exported symbol.
*
* @param ns The namespace identifier.
* @param node The declaration.
* @param allowComments A value indicating whether comments may be emitted for the name.
* @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
*/
/* @internal */ getExternalModuleOrNamespaceExportName(ns: Identifier | undefined, node: Declaration, allowComments?: boolean, allowSourceMaps?: boolean): Identifier | PropertyAccessExpression;
//
// Utilities
//
restoreOuterExpressions(outerExpression: Expression | undefined, innerExpression: Expression, kinds?: OuterExpressionKinds): Expression;
/* @internal */ restoreEnclosingLabel(node: Statement, outermostLabeledStatement: LabeledStatement | undefined, afterRestoreLabelCallback?: (node: LabeledStatement) => void): Statement;
/* @internal */ createUseStrictPrologue(): PrologueDirective;
/**
* Copies any necessary standard and custom prologue-directives into target array.
* @param source origin statements array
* @param target result statements array
* @param ensureUseStrict boolean determining whether the function need to add prologue-directives
* @param visitor Optional callback used to visit any custom prologue directives.
*/
/* @internal */ copyPrologue(source: readonly Statement[], target: Push<Statement>, ensureUseStrict?: boolean, visitor?: (node: Node) => VisitResult<Node>): number;
/**
* Copies only the standard (string-expression) prologue-directives into the target statement-array.
* @param source origin statements array
* @param target result statements array
* @param ensureUseStrict boolean determining whether the function need to add prologue-directives
*/
/* @internal */ copyStandardPrologue(source: readonly Statement[], target: Push<Statement>, ensureUseStrict?: boolean): number;
/**
* Copies only the custom prologue-directives into target statement-array.
* @param source origin statements array
* @param target result statements array
* @param statementOffset The offset at which to begin the copy.
* @param visitor Optional callback used to visit any custom prologue directives.
*/
/* @internal */ copyCustomPrologue(source: readonly Statement[], target: Push<Statement>, statementOffset: number, visitor?: (node: Node) => VisitResult<Node>, filter?: (node: Node) => boolean): number;
/* @internal */ copyCustomPrologue(source: readonly Statement[], target: Push<Statement>, statementOffset: number | undefined, visitor?: (node: Node) => VisitResult<Node>, filter?: (node: Node) => boolean): number | undefined;
/* @internal */ ensureUseStrict(statements: NodeArray<Statement>): NodeArray<Statement>;
/* @internal */ liftToBlock(nodes: readonly Node[]): Statement;
/**
* Merges generated lexical declarations into a new statement list.
*/
/* @internal */ mergeLexicalEnvironment(statements: NodeArray<Statement>, declarations: readonly Statement[] | undefined): NodeArray<Statement>;
/**
* Appends generated lexical declarations to an array of statements.
*/
/* @internal */ mergeLexicalEnvironment(statements: Statement[], declarations: readonly Statement[] | undefined): Statement[];
/**
* Creates a shallow, memberwise clone of a node.
* - The result will have its `original` pointer set to `node`.
* - The result will have its `pos` and `end` set to `-1`.
* - *DO NOT USE THIS* if a more appropriate function is available.
*/
/* @internal */ cloneNode<T extends Node | undefined>(node: T): T;
/* @internal */ updateModifiers<T extends HasModifiers>(node: T, modifiers: readonly Modifier[] | ModifierFlags): T;
}
/* @internal */
export const enum LexicalEnvironmentFlags {
None = 0,
InParameters = 1 << 0, // currently visiting a parameter list
VariablesHoistedInParameters = 1 << 1 // a temp variable was hoisted while visiting a parameter list
}
export interface CoreTransformationContext {
readonly factory: NodeFactory;
/** Gets the compiler options supplied to the transformer. */
getCompilerOptions(): CompilerOptions;
/** Starts a new lexical environment. */
startLexicalEnvironment(): void;
/* @internal */ setLexicalEnvironmentFlags(flags: LexicalEnvironmentFlags, value: boolean): void;
/* @internal */ getLexicalEnvironmentFlags(): LexicalEnvironmentFlags;
/** Suspends the current lexical environment, usually after visiting a parameter list. */
suspendLexicalEnvironment(): void;
/** Resumes a suspended lexical environment, usually before visiting a function body. */
resumeLexicalEnvironment(): void;
/** Ends a lexical environment, returning any declarations. */
endLexicalEnvironment(): Statement[] | undefined;
/** Hoists a function declaration to the containing scope. */
hoistFunctionDeclaration(node: FunctionDeclaration): void;
/** Hoists a variable declaration to the containing scope. */
hoistVariableDeclaration(node: Identifier): void;
/*@internal*/ startBlockScope(): void;
/*@internal*/ endBlockScope(): Statement[] | undefined;
/*@internal*/ addBlockScopedVariable(node: Identifier): void;
/** Adds an initialization statement to the top of the lexical environment. */
/* @internal */
addInitializationStatement(node: Statement): void;
}
export interface TransformationContext extends CoreTransformationContext {
/*@internal*/ getEmitResolver(): EmitResolver;
/*@internal*/ getEmitHost(): EmitHost;
/*@internal*/ getEmitHelperFactory(): EmitHelperFactory;
/** Records a request for a non-scoped emit helper in the current context. */
requestEmitHelper(helper: EmitHelper): void;
/** Gets and resets the requested non-scoped emit helpers. */
readEmitHelpers(): EmitHelper[] | undefined;
/** Enables expression substitutions in the pretty printer for the provided SyntaxKind. */
enableSubstitution(kind: SyntaxKind): void;
/** Determines whether expression substitutions are enabled for the provided node. */
isSubstitutionEnabled(node: Node): boolean;
/**
* Hook used by transformers to substitute expressions just before they
* are emitted by the pretty printer.
*
* NOTE: Transformation hooks should only be modified during `Transformer` initialization,
* before returning the `NodeTransformer` callback.
*/
onSubstituteNode: (hint: EmitHint, node: Node) => Node;
/**
* Enables before/after emit notifications in the pretty printer for the provided
* SyntaxKind.
*/
enableEmitNotification(kind: SyntaxKind): void;
/**
* Determines whether before/after emit notifications should be raised in the pretty
* printer when it emits a node.
*/
isEmitNotificationEnabled(node: Node): boolean;
/**
* Hook used to allow transformers to capture state before or after
* the printer emits a node.
*
* NOTE: Transformation hooks should only be modified during `Transformer` initialization,
* before returning the `NodeTransformer` callback.
*/
onEmitNode: (hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) => void;
/* @internal */ addDiagnostic(diag: DiagnosticWithLocation): void;
}
export interface TransformationResult<T extends Node> {
/** Gets the transformed source files. */
transformed: T[];
/** Gets diagnostics for the transformation. */
diagnostics?: DiagnosticWithLocation[];
/**
* Gets a substitute for a node, if one is available; otherwise, returns the original node.
*
* @param hint A hint as to the intended usage of the node.
* @param node The node to substitute.
*/
substituteNode(hint: EmitHint, node: Node): Node;
/**
* Emits a node with possible notification.
*
* @param hint A hint as to the intended usage of the node.
* @param node The node to emit.
* @param emitCallback A callback used to emit the node.
*/
emitNodeWithNotification(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void;
/**
* Indicates if a given node needs an emit notification
*
* @param node The node to emit.
*/
isEmitNotificationEnabled?(node: Node): boolean;
/**
* Clean up EmitNode entries on any parse-tree nodes.
*/
dispose(): void;
}
/**
* A function that is used to initialize and return a `Transformer` callback, which in turn
* will be used to transform one or more nodes.
*/
export type TransformerFactory<T extends Node> = (context: TransformationContext) => Transformer<T>;
/**
* A function that transforms a node.
*/
export type Transformer<T extends Node> = (node: T) => T;
/**
* A function that accepts and possibly transforms a node.
*/
export type Visitor = (node: Node) => VisitResult<Node>;
export interface NodeVisitor {
<T extends Node>(nodes: T, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: readonly Node[]) => T): T;
<T extends Node>(nodes: T | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, lift?: (node: readonly Node[]) => T): T | undefined;
}
export interface NodesVisitor {
<T extends Node>(nodes: NodeArray<T>, visitor: Visitor | undefined, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray<T>;
<T extends Node>(nodes: NodeArray<T> | undefined, visitor: Visitor | undefined, test?: (node: Node) => boolean, start?: number, count?: number): NodeArray<T> | undefined;
}
export type VisitResult<T extends Node> = T | T[] | undefined;
export interface Printer {
/**
* Print a node and its subtree as-is, without any emit transformations.
* @param hint A value indicating the purpose of a node. This is primarily used to
* distinguish between an `Identifier` used in an expression position, versus an
* `Identifier` used as an `IdentifierName` as part of a declaration. For most nodes you
* should just pass `Unspecified`.
* @param node The node to print. The node and its subtree are printed as-is, without any
* emit transformations.
* @param sourceFile A source file that provides context for the node. The source text of
* the file is used to emit the original source content for literals and identifiers, while
* the identifiers of the source file are used when generating unique names to avoid
* collisions.
*/
printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string;
/**
* Prints a list of nodes using the given format flags
*/
printList<T extends Node>(format: ListFormat, list: NodeArray<T>, sourceFile: SourceFile): string;
/**
* Prints a source file as-is, without any emit transformations.
*/
printFile(sourceFile: SourceFile): string;
/**
* Prints a bundle of source files as-is, without any emit transformations.
*/
printBundle(bundle: Bundle): string;
/*@internal*/ writeNode(hint: EmitHint, node: Node, sourceFile: SourceFile | undefined, writer: EmitTextWriter): void;
/*@internal*/ writeList<T extends Node>(format: ListFormat, list: NodeArray<T> | undefined, sourceFile: SourceFile | undefined, writer: EmitTextWriter): void;
/*@internal*/ writeFile(sourceFile: SourceFile, writer: EmitTextWriter, sourceMapGenerator: SourceMapGenerator | undefined): void;
/*@internal*/ writeBundle(bundle: Bundle, writer: EmitTextWriter, sourceMapGenerator: SourceMapGenerator | undefined): void;
/*@internal*/ bundleFileInfo?: BundleFileInfo;
}
/*@internal*/
export const enum BundleFileSectionKind {
Prologue = "prologue",
EmitHelpers = "emitHelpers",
NoDefaultLib = "no-default-lib",
Reference = "reference",
Type = "type",
Lib = "lib",
Prepend = "prepend",
Text = "text",
Internal = "internal",
// comments?
}
/*@internal*/
export interface BundleFileSectionBase extends TextRange {
kind: BundleFileSectionKind;
data?: string;
}
/*@internal*/
export interface BundleFilePrologue extends BundleFileSectionBase {
kind: BundleFileSectionKind.Prologue;
data: string;
}
/*@internal*/
export interface BundleFileEmitHelpers extends BundleFileSectionBase {
kind: BundleFileSectionKind.EmitHelpers;
data: string;
}
/*@internal*/
export interface BundleFileHasNoDefaultLib extends BundleFileSectionBase {
kind: BundleFileSectionKind.NoDefaultLib;
}
/*@internal*/
export interface BundleFileReference extends BundleFileSectionBase {
kind: BundleFileSectionKind.Reference | BundleFileSectionKind.Type | BundleFileSectionKind.Lib;
data: string;
}
/*@internal*/
export interface BundleFilePrepend extends BundleFileSectionBase {
kind: BundleFileSectionKind.Prepend;
data: string;
texts: BundleFileTextLike[];
}
/*@internal*/
export type BundleFileTextLikeKind = BundleFileSectionKind.Text | BundleFileSectionKind.Internal;
/*@internal*/
export interface BundleFileTextLike extends BundleFileSectionBase {
kind: BundleFileTextLikeKind;
}
/*@internal*/
export type BundleFileSection =
BundleFilePrologue
| BundleFileEmitHelpers
| BundleFileHasNoDefaultLib
| BundleFileReference
| BundleFilePrepend
| BundleFileTextLike;
/*@internal*/
export interface SourceFilePrologueDirectiveExpression extends TextRange {
text: string;
}
/*@internal*/
export interface SourceFilePrologueDirective extends TextRange {
expression: SourceFilePrologueDirectiveExpression;
}
/*@internal*/
export interface SourceFilePrologueInfo {
file: number;
text: string;
directives: SourceFilePrologueDirective[];
}
/*@internal*/
export interface SourceFileInfo {
// List of helpers in own source files emitted if no prepend is present
helpers?: string[];
prologues?: SourceFilePrologueInfo[];
}
/*@internal*/
export interface BundleFileInfo {
sections: BundleFileSection[];
sources?: SourceFileInfo;
}
/*@internal*/
export interface BundleBuildInfo {
js?: BundleFileInfo;
dts?: BundleFileInfo;
commonSourceDirectory: string;
sourceFiles: readonly string[];
}
/* @internal */
export interface BuildInfo {
bundle?: BundleBuildInfo;
program?: ProgramBuildInfo;
version: string;
}
export interface PrintHandlers {
/**
* A hook used by the Printer when generating unique names to avoid collisions with
* globally defined names that exist outside of the current source file.
*/
hasGlobalName?(name: string): boolean;
/**
* A hook used by the Printer to provide notifications prior to emitting a node. A
* compatible implementation **must** invoke `emitCallback` with the provided `hint` and
* `node` values.
* @param hint A hint indicating the intended purpose of the node.
* @param node The node to emit.
* @param emitCallback A callback that, when invoked, will emit the node.
* @example
* ```ts
* var printer = createPrinter(printerOptions, {
* onEmitNode(hint, node, emitCallback) {
* // set up or track state prior to emitting the node...
* emitCallback(hint, node);
* // restore state after emitting the node...
* }
* });
* ```
*/
onEmitNode?(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void;
/**
* A hook used to check if an emit notification is required for a node.
* @param node The node to emit.
*/
isEmitNotificationEnabled?(node: Node): boolean;
/**
* A hook used by the Printer to perform just-in-time substitution of a node. This is
* primarily used by node transformations that need to substitute one node for another,
* such as replacing `myExportedVar` with `exports.myExportedVar`.
* @param hint A hint indicating the intended purpose of the node.
* @param node The node to emit.
* @example
* ```ts
* var printer = createPrinter(printerOptions, {
* substituteNode(hint, node) {
* // perform substitution if necessary...
* return node;
* }
* });
* ```
*/
substituteNode?(hint: EmitHint, node: Node): Node;
/*@internal*/ onEmitSourceMapOfNode?: (hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) => void;
/*@internal*/ onEmitSourceMapOfToken?: (node: Node | undefined, token: SyntaxKind, writer: (s: string) => void, pos: number, emitCallback: (token: SyntaxKind, writer: (s: string) => void, pos: number) => number) => number;
/*@internal*/ onEmitSourceMapOfPosition?: (pos: number) => void;
/*@internal*/ onSetSourceFile?: (node: SourceFile) => void;
/*@internal*/ onBeforeEmitNode?: (node: Node | undefined) => void;
/*@internal*/ onAfterEmitNode?: (node: Node | undefined) => void;
/*@internal*/ onBeforeEmitNodeArray?: (nodes: NodeArray<any> | undefined) => void;
/*@internal*/ onAfterEmitNodeArray?: (nodes: NodeArray<any> | undefined) => void;
/*@internal*/ onBeforeEmitToken?: (node: Node) => void;
/*@internal*/ onAfterEmitToken?: (node: Node) => void;
}
export interface PrinterOptions {
removeComments?: boolean;
newLine?: NewLineKind;
omitTrailingSemicolon?: boolean;
noEmitHelpers?: boolean;
/*@internal*/ module?: CompilerOptions["module"];
/*@internal*/ target?: CompilerOptions["target"];
/*@internal*/ sourceMap?: boolean;
/*@internal*/ inlineSourceMap?: boolean;
/*@internal*/ inlineSources?: boolean;
/*@internal*/ extendedDiagnostics?: boolean;
/*@internal*/ onlyPrintJsDocStyle?: boolean;
/*@internal*/ neverAsciiEscape?: boolean;
/*@internal*/ writeBundleFileInfo?: boolean;
/*@internal*/ recordInternalSection?: boolean;
/*@internal*/ stripInternal?: boolean;
/*@internal*/ preserveSourceNewlines?: boolean;
/*@internal*/ terminateUnterminatedLiterals?: boolean;
/*@internal*/ relativeToBuildInfo?: (path: string) => string;
}
/* @internal */
export interface RawSourceMap {
version: 3;
file: string;
sourceRoot?: string | null;
sources: string[];
sourcesContent?: (string | null)[] | null;
mappings: string;
names?: string[] | null;
}
/**
* Generates a source map.
*/
/* @internal */
export interface SourceMapGenerator {
getSources(): readonly string[];
/**
* Adds a source to the source map.
*/
addSource(fileName: string): number;
/**
* Set the content for a source.
*/
setSourceContent(sourceIndex: number, content: string | null): void;
/**
* Adds a name.
*/
addName(name: string): number;
/**
* Adds a mapping without source information.
*/
addMapping(generatedLine: number, generatedCharacter: number): void;
/**
* Adds a mapping with source information.
*/
addMapping(generatedLine: number, generatedCharacter: number, sourceIndex: number, sourceLine: number, sourceCharacter: number, nameIndex?: number): void;
/**
* Appends a source map.
*/
appendSourceMap(generatedLine: number, generatedCharacter: number, sourceMap: RawSourceMap, sourceMapPath: string, start?: LineAndCharacter, end?: LineAndCharacter): void;
/**
* Gets the source map as a `RawSourceMap` object.
*/
toJSON(): RawSourceMap;
/**
* Gets the string representation of the source map.
*/
toString(): string;
}
/* @internal */
export interface DocumentPositionMapperHost {
getSourceFileLike(fileName: string): SourceFileLike | undefined;
getCanonicalFileName(path: string): string;
log(text: string): void;
}
/**
* Maps positions between source and generated files.
*/
/* @internal */
export interface DocumentPositionMapper {
getSourcePosition(input: DocumentPosition): DocumentPosition;
getGeneratedPosition(input: DocumentPosition): DocumentPosition;
}
/* @internal */
export interface DocumentPosition {
fileName: string;
pos: number;
}
/* @internal */
export interface EmitTextWriter extends SymbolWriter {
write(s: string): void;
writeTrailingSemicolon(text: string): void;
writeComment(text: string): void;
getText(): string;
rawWrite(s: string): void;
writeLiteral(s: string): void;
getTextPos(): number;
getLine(): number;
getColumn(): number;
getIndent(): number;
isAtStartOfLine(): boolean;
hasTrailingComment(): boolean;
hasTrailingWhitespace(): boolean;
getTextPosWithWriteLine?(): number;
}
export interface GetEffectiveTypeRootsHost {
directoryExists?(directoryName: string): boolean;
getCurrentDirectory?(): string;
}
/*@internal*/
export interface ModuleSpecifierResolutionHost {
useCaseSensitiveFileNames?(): boolean;
fileExists(path: string): boolean;
getCurrentDirectory(): string;
directoryExists?(path: string): boolean;
readFile?(path: string): string | undefined;
realpath?(path: string): string;
getSymlinkCache?(): SymlinkCache;
getModuleSpecifierCache?(): ModuleSpecifierCache;
getGlobalTypingsCacheLocation?(): string | undefined;
getNearestAncestorDirectoryWithPackageJson?(fileName: string, rootDir?: string): string | undefined;
getSourceFiles(): readonly SourceFile[];
readonly redirectTargetsMap: RedirectTargetsMap;
getProjectReferenceRedirect(fileName: string): string | undefined;
isSourceOfProjectReferenceRedirect(fileName: string): boolean;
getFileIncludeReasons(): MultiMap<Path, FileIncludeReason>;
}
/* @internal */
export interface ModulePath {
path: string;
isInNodeModules: boolean;
isRedirect: boolean;
}
/* @internal */
export interface ModuleSpecifierCache {
get(fromFileName: Path, toFileName: Path): boolean | readonly ModulePath[] | undefined;
set(fromFileName: Path, toFileName: Path, moduleSpecifiers: boolean | readonly ModulePath[]): void;
clear(): void;
count(): number;
}
// Note: this used to be deprecated in our public API, but is still used internally
/* @internal */
export interface SymbolTracker {
// Called when the symbol writer encounters a symbol to write. Currently only used by the
// declaration emitter to help determine if it should patch up the final declaration file
// with import statements it previously saw (but chose not to emit).
trackSymbol?(symbol: Symbol, enclosingDeclaration: Node | undefined, meaning: SymbolFlags): void;
reportInaccessibleThisError?(): void;
reportPrivateInBaseOfClassExpression?(propertyName: string): void;
reportInaccessibleUniqueSymbolError?(): void;
reportCyclicStructureError?(): void;
reportLikelyUnsafeImportRequiredError?(specifier: string): void;
reportTruncationError?(): void;
moduleResolverHost?: ModuleSpecifierResolutionHost & { getCommonSourceDirectory(): string };
trackReferencedAmbientModule?(decl: ModuleDeclaration, symbol: Symbol): void;
trackExternalModuleSymbolOfImportTypeNode?(symbol: Symbol): void;
reportNonlocalAugmentation?(containingFile: SourceFile, parentSymbol: Symbol, augmentingSymbol: Symbol): void;
}
export interface TextSpan {
start: number;
length: number;
}
export interface TextChangeRange {
span: TextSpan;
newLength: number;
}
/* @internal */
export interface DiagnosticCollection {
// Adds a diagnostic to this diagnostic collection.
add(diagnostic: Diagnostic): void;
// Returns the first existing diagnostic that is equivalent to the given one (sans related information)
lookup(diagnostic: Diagnostic): Diagnostic | undefined;
// Gets all the diagnostics that aren't associated with a file.
getGlobalDiagnostics(): Diagnostic[];
// If fileName is provided, gets all the diagnostics associated with that file name.
// Otherwise, returns all the diagnostics (global and file associated) in this collection.
getDiagnostics(): Diagnostic[];
getDiagnostics(fileName: string): DiagnosticWithLocation[];
}
// SyntaxKind.SyntaxList
export interface SyntaxList extends Node {
kind: SyntaxKind.SyntaxList;
_children: Node[];
}
export const enum ListFormat {
None = 0,
// Line separators
SingleLine = 0, // Prints the list on a single line (default).
MultiLine = 1 << 0, // Prints the list on multiple lines.
PreserveLines = 1 << 1, // Prints the list using line preservation if possible.
LinesMask = SingleLine | MultiLine | PreserveLines,
// Delimiters
NotDelimited = 0, // There is no delimiter between list items (default).
BarDelimited = 1 << 2, // Each list item is space-and-bar (" |") delimited.
AmpersandDelimited = 1 << 3, // Each list item is space-and-ampersand (" &") delimited.
CommaDelimited = 1 << 4, // Each list item is comma (",") delimited.
AsteriskDelimited = 1 << 5, // Each list item is asterisk ("\n *") delimited, used with JSDoc.
DelimitersMask = BarDelimited | AmpersandDelimited | CommaDelimited | AsteriskDelimited,
AllowTrailingComma = 1 << 6, // Write a trailing comma (",") if present.
// Whitespace
Indented = 1 << 7, // The list should be indented.
SpaceBetweenBraces = 1 << 8, // Inserts a space after the opening brace and before the closing brace.
SpaceBetweenSiblings = 1 << 9, // Inserts a space between each sibling node.
// Brackets/Braces
Braces = 1 << 10, // The list is surrounded by "{" and "}".
Parenthesis = 1 << 11, // The list is surrounded by "(" and ")".
AngleBrackets = 1 << 12, // The list is surrounded by "<" and ">".
SquareBrackets = 1 << 13, // The list is surrounded by "[" and "]".
BracketsMask = Braces | Parenthesis | AngleBrackets | SquareBrackets,
OptionalIfUndefined = 1 << 14, // Do not emit brackets if the list is undefined.
OptionalIfEmpty = 1 << 15, // Do not emit brackets if the list is empty.
Optional = OptionalIfUndefined | OptionalIfEmpty,
// Other
PreferNewLine = 1 << 16, // Prefer adding a LineTerminator between synthesized nodes.
NoTrailingNewLine = 1 << 17, // Do not emit a trailing NewLine for a MultiLine list.
NoInterveningComments = 1 << 18, // Do not emit comments between each node
NoSpaceIfEmpty = 1 << 19, // If the literal is empty, do not add spaces between braces.
SingleElement = 1 << 20,
SpaceAfterList = 1 << 21, // Add space after list
// Precomputed Formats
Modifiers = SingleLine | SpaceBetweenSiblings | NoInterveningComments,
HeritageClauses = SingleLine | SpaceBetweenSiblings,
SingleLineTypeLiteralMembers = SingleLine | SpaceBetweenBraces | SpaceBetweenSiblings,
MultiLineTypeLiteralMembers = MultiLine | Indented | OptionalIfEmpty,
SingleLineTupleTypeElements = CommaDelimited | SpaceBetweenSiblings | SingleLine,
MultiLineTupleTypeElements = CommaDelimited | Indented | SpaceBetweenSiblings | MultiLine,
UnionTypeConstituents = BarDelimited | SpaceBetweenSiblings | SingleLine,
IntersectionTypeConstituents = AmpersandDelimited | SpaceBetweenSiblings | SingleLine,
ObjectBindingPatternElements = SingleLine | AllowTrailingComma | SpaceBetweenBraces | CommaDelimited | SpaceBetweenSiblings | NoSpaceIfEmpty,
ArrayBindingPatternElements = SingleLine | AllowTrailingComma | CommaDelimited | SpaceBetweenSiblings | NoSpaceIfEmpty,
ObjectLiteralExpressionProperties = PreserveLines | CommaDelimited | SpaceBetweenSiblings | SpaceBetweenBraces | Indented | Braces | NoSpaceIfEmpty,
ArrayLiteralExpressionElements = PreserveLines | CommaDelimited | SpaceBetweenSiblings | AllowTrailingComma | Indented | SquareBrackets,
CommaListElements = CommaDelimited | SpaceBetweenSiblings | SingleLine,
CallExpressionArguments = CommaDelimited | SpaceBetweenSiblings | SingleLine | Parenthesis,
NewExpressionArguments = CommaDelimited | SpaceBetweenSiblings | SingleLine | Parenthesis | OptionalIfUndefined,
TemplateExpressionSpans = SingleLine | NoInterveningComments,
SingleLineBlockStatements = SpaceBetweenBraces | SpaceBetweenSiblings | SingleLine,
MultiLineBlockStatements = Indented | MultiLine,
VariableDeclarationList = CommaDelimited | SpaceBetweenSiblings | SingleLine,
SingleLineFunctionBodyStatements = SingleLine | SpaceBetweenSiblings | SpaceBetweenBraces,
MultiLineFunctionBodyStatements = MultiLine,
ClassHeritageClauses = SingleLine,
ClassMembers = Indented | MultiLine,
InterfaceMembers = Indented | MultiLine,
EnumMembers = CommaDelimited | Indented | MultiLine,
CaseBlockClauses = Indented | MultiLine,
NamedImportsOrExportsElements = CommaDelimited | SpaceBetweenSiblings | AllowTrailingComma | SingleLine | SpaceBetweenBraces | NoSpaceIfEmpty,
JsxElementOrFragmentChildren = SingleLine | NoInterveningComments,
JsxElementAttributes = SingleLine | SpaceBetweenSiblings | NoInterveningComments,
CaseOrDefaultClauseStatements = Indented | MultiLine | NoTrailingNewLine | OptionalIfEmpty,
HeritageClauseTypes = CommaDelimited | SpaceBetweenSiblings | SingleLine,
SourceFileStatements = MultiLine | NoTrailingNewLine,
Decorators = MultiLine | Optional | SpaceAfterList,
TypeArguments = CommaDelimited | SpaceBetweenSiblings | SingleLine | AngleBrackets | Optional,
TypeParameters = CommaDelimited | SpaceBetweenSiblings | SingleLine | AngleBrackets | Optional,
Parameters = CommaDelimited | SpaceBetweenSiblings | SingleLine | Parenthesis,
IndexSignatureParameters = CommaDelimited | SpaceBetweenSiblings | SingleLine | Indented | SquareBrackets,
JSDocComment = MultiLine | AsteriskDelimited,
}
/* @internal */
export const enum PragmaKindFlags {
None = 0,
/**
* Triple slash comment of the form
* /// <pragma-name argname="value" />
*/
TripleSlashXML = 1 << 0,
/**
* Single line comment of the form
* // @pragma-name argval1 argval2
* or
* /// @pragma-name argval1 argval2
*/
SingleLine = 1 << 1,
/**
* Multiline non-jsdoc pragma of the form
* /* @pragma-name argval1 argval2 * /
*/
MultiLine = 1 << 2,
All = TripleSlashXML | SingleLine | MultiLine,
Default = All,
}
/* @internal */
interface PragmaArgumentSpecification<TName extends string> {
name: TName; // Determines the name of the key in the resulting parsed type, type parameter to cause literal type inference
optional?: boolean;
captureSpan?: boolean;
}
/* @internal */
export interface PragmaDefinition<T1 extends string = string, T2 extends string = string, T3 extends string = string, T4 extends string = string> {
args?:
| readonly [PragmaArgumentSpecification<T1>]
| readonly [PragmaArgumentSpecification<T1>, PragmaArgumentSpecification<T2>]
| readonly [PragmaArgumentSpecification<T1>, PragmaArgumentSpecification<T2>, PragmaArgumentSpecification<T3>]
| readonly [PragmaArgumentSpecification<T1>, PragmaArgumentSpecification<T2>, PragmaArgumentSpecification<T3>, PragmaArgumentSpecification<T4>];
// If not present, defaults to PragmaKindFlags.Default
kind?: PragmaKindFlags;
}
// While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
// fancy effectively defining it twice, once in value-space and once in type-space
/* @internal */
export const commentPragmas = {
"reference": {
args: [
{ name: "types", optional: true, captureSpan: true },
{ name: "lib", optional: true, captureSpan: true },
{ name: "path", optional: true, captureSpan: true },
{ name: "no-default-lib", optional: true }
],
kind: PragmaKindFlags.TripleSlashXML
},
"amd-dependency": {
args: [{ name: "path" }, { name: "name", optional: true }],
kind: PragmaKindFlags.TripleSlashXML
},
"amd-module": {
args: [{ name: "name" }],
kind: PragmaKindFlags.TripleSlashXML
},
"ts-check": {
kind: PragmaKindFlags.SingleLine
},
"ts-nocheck": {
kind: PragmaKindFlags.SingleLine
},
"jsx": {
args: [{ name: "factory" }],
kind: PragmaKindFlags.MultiLine
},
"jsxfrag": {
args: [{ name: "factory" }],
kind: PragmaKindFlags.MultiLine
},
"jsximportsource": {
args: [{ name: "factory" }],
kind: PragmaKindFlags.MultiLine
},
"jsxruntime": {
args: [{ name: "factory" }],
kind: PragmaKindFlags.MultiLine
},
} as const;
/* @internal */
type PragmaArgTypeMaybeCapture<TDesc> = TDesc extends {captureSpan: true} ? {value: string, pos: number, end: number} : string;
/* @internal */
type PragmaArgTypeOptional<TDesc, TName extends string> =
TDesc extends {optional: true}
? {[K in TName]?: PragmaArgTypeMaybeCapture<TDesc>}
: {[K in TName]: PragmaArgTypeMaybeCapture<TDesc>};
/* @internal */
type UnionToIntersection<U> =
(U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
/* @internal */
type ArgumentDefinitionToFieldUnion<T extends readonly PragmaArgumentSpecification<any>[]> = {
[K in keyof T]: PragmaArgTypeOptional<T[K], T[K] extends {name: infer TName} ? TName extends string ? TName : never : never>
}[Extract<keyof T, number>]; // The mapped type maps over only the tuple members, but this reindex gets _all_ members - by extracting only `number` keys, we get only the tuple members
/**
* Maps a pragma definition into the desired shape for its arguments object
*/
/* @internal */
type PragmaArgumentType<KPrag extends keyof ConcretePragmaSpecs> =
ConcretePragmaSpecs[KPrag] extends { args: readonly PragmaArgumentSpecification<any>[] }
? UnionToIntersection<ArgumentDefinitionToFieldUnion<ConcretePragmaSpecs[KPrag]["args"]>>
: never;
/* @internal */
type ConcretePragmaSpecs = typeof commentPragmas;
/* @internal */
export type PragmaPseudoMap = {[K in keyof ConcretePragmaSpecs]: {arguments: PragmaArgumentType<K>, range: CommentRange}};
/* @internal */
export type PragmaPseudoMapEntry = {[K in keyof PragmaPseudoMap]: {name: K, args: PragmaPseudoMap[K]}}[keyof PragmaPseudoMap];
/* @internal */
export interface ReadonlyPragmaMap extends ReadonlyESMap<string, PragmaPseudoMap[keyof PragmaPseudoMap] | PragmaPseudoMap[keyof PragmaPseudoMap][]> {
get<TKey extends keyof PragmaPseudoMap>(key: TKey): PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][];
forEach(action: <TKey extends keyof PragmaPseudoMap>(value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][], key: TKey) => void): void;
}
/**
* A strongly-typed es6 map of pragma entries, the values of which are either a single argument
* value (if only one was found), or an array of multiple argument values if the pragma is present
* in multiple places
*/
/* @internal */
export interface PragmaMap extends ESMap<string, PragmaPseudoMap[keyof PragmaPseudoMap] | PragmaPseudoMap[keyof PragmaPseudoMap][]>, ReadonlyPragmaMap {
set<TKey extends keyof PragmaPseudoMap>(key: TKey, value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][]): this;
get<TKey extends keyof PragmaPseudoMap>(key: TKey): PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][];
forEach(action: <TKey extends keyof PragmaPseudoMap>(value: PragmaPseudoMap[TKey] | PragmaPseudoMap[TKey][], key: TKey) => void): void;
}
/* @internal */
export interface CommentDirectivesMap {
getUnusedExpectations(): CommentDirective[];
markUsed(matchedLine: number): boolean;
}
export interface UserPreferences {
readonly disableSuggestions?: boolean;
readonly quotePreference?: "auto" | "double" | "single";
readonly includeCompletionsForModuleExports?: boolean;
readonly includeCompletionsForImportStatements?: boolean;
readonly includeCompletionsWithSnippetText?: boolean;
readonly includeAutomaticOptionalChainCompletions?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative";
/** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */
readonly importModuleSpecifierEnding?: "auto" | "minimal" | "index" | "js";
readonly allowTextChangesInNewFiles?: boolean;
readonly providePrefixAndSuffixTextForRename?: boolean;
readonly includePackageJsonAutoImports?: "auto" | "on" | "off";
readonly provideRefactorNotApplicableReason?: boolean;
}
/** Represents a bigint literal value without requiring bigint support */
export interface PseudoBigInt {
negative: boolean;
base10Value: string;
}
}
| OperationCanceledException |
lamdba_caller.py | import boto3
import json
s3 = boto3.resource('s3')
def | (event, context):
bucket = s3.Bucket("diotsoumas-book-tracker-config-files")
sns_client = boto3.client('sns')
arn = "arn:aws:sns:eu-west-1:169367514751:Lamdba-caller"
for obj in bucket.objects.filter():
message = {"s3_key": obj.key}
response = sns_client.publish(
TargetArn=arn,
Message=json.dumps({'default': json.dumps(message)}),
MessageStructure='json'
) | lambda_handler |
log.py | import time
def | (method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
if 'log_time' in kw:
name = kw.get('log_name', method.__name__.upper())
kw['log_time'][name] = int((te - ts) * 1000)
else:
print('%r %2.2f ms' % (method.__name__, (te - ts) * 1000))
return result
return timed | timeit |
main.rs | use whim_tool_plugins::*;
use windows_backend::Action;
use windows_backend::WindowsKeysBackend;
// use whim_tool_roulette::Roulette;
use std::{collections::HashMap, thread};
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::{borrow::BorrowMut, cell::RefCell};
mod plugins_manager;
use plugins_manager::PluginsManager;
#[macro_use]
extern crate lazy_static;
lazy_static! {
static ref PLUGINS_MANAGER: Arc<Mutex<PluginsManager>> =
Arc::new(Mutex::new(PluginsManager::default()));
static ref WINDOWS_KEY_BACKEND: Arc<Mutex<WindowsKeysBackend>> =
Arc::new(Mutex::new(WindowsKeysBackend::new()));
}
struct WhimToolLoop;
impl Action for WhimToolLoop {
fn do_something(&mut self, action: usize, vk_code: u32, scan_code: u32) -> isize {
//Action
//256 按下
//257 弹起
//512 MOUSE MOVE
//513 MOUSE L DOWN
//514 MOUSE L UP
//516 MOUSE R DOWN
//517 MOUSE R UP
//519 MOUSE M DOWN
//520 MOUSE M UP
//522 MOUSE M Drop
let mut key_code: Option<usize> = None;
let mut postion: Option<Point> = None;
if action == 256 || action == 257 {
key_code = Some(vk_code as usize);
} else {
postion = Some(Point {
x: vk_code,
y: scan_code,
});
}
// println!("Action: {:?}, Code: {:?}", action, vk_code);
let trigger_code = TriggerCode {
trigger: Trigger::from(action),
key_code: key_code,
mouse_position: postion,
};
self.action(trigger_code);
return 0 as isize; //返回1则中断所有操作
}
}
impl WhimToolLoop {
fn action(&mut self, trigger_code: TriggerCode) {
std::thread::spawn(move || {
let mut pm = (*PLUGINS_MANAGER).lock().unwrap();
pm.plugins_excute(&trigger_code);
});
}
}
fn main() {
let tool_loop = WhimToolLoop;
unsafe {
let mut pm = (*PLUGINS_MANAGER).lock().unwrap();
let wkb = (*WINDOWS_KEY_BACKEND).lock().unwrap();
wkb.install_mouse_hook();
wkb.set_action(Rc::new(RefCell::new(tool_loop)));
pm.iterate_file();
}
unsafe {
// std::thread::spawn(move || {
// let wkb = (*WINDOWS_KEY_BACKEND).lock().unwrap();
// wkb.message_loop();
// });
// loop{}
let wkb = (*WINDOWS_KEY_BACKEND).lock().unwrap();
loop {
wkb.message_loop();
}
}
} | //#![windows_subsystem = "windows"]
use libloading::{Library, Symbol}; |
|
index.js | import { writeFileSync } from 'fs';
import { join, posix } from 'path';
import { fileURLToPath } from 'url';
import esbuild from 'esbuild';
/**
* @typedef {import('esbuild').BuildOptions} BuildOptions
*/
const ssrFunctionRoute = '/api/__render';
/**
* Validate the static web app configuration does not override the minimum config for the adapter to work correctly.
* @param config {import('./types/swa').CustomStaticWebAppConfig}
* */
function validateCustomConfig(config) {
if (config) {
if ('navigationFallback' in config) {
throw new Error('customStaticWebAppConfig cannot override navigationFallback.');
}
if (config.routes && config.routes.find((route) => route.route === '*')) {
throw new Error(`customStaticWebAppConfig cannot override '*' route.`);
}
}
}
/** @type {import('.')} */
export default function ({ debug = false, customStaticWebAppConfig = {} } = {}) {
return {
name: 'adapter-azure-swa',
async adapt(builder) {
validateCustomConfig(customStaticWebAppConfig);
if (!customStaticWebAppConfig.routes) {
customStaticWebAppConfig.routes = [];
}
/** @type {import('./types/swa').StaticWebAppConfig} */
const swaConfig = {
...customStaticWebAppConfig,
routes: [
...customStaticWebAppConfig.routes,
{
route: '*',
methods: ['POST', 'PUT', 'DELETE'],
rewrite: ssrFunctionRoute
},
{
route: `/${builder.appDir}/*`,
headers: {
'cache-control': 'public, immutable, max-age=31536000' | }
}
],
navigationFallback: {
rewrite: ssrFunctionRoute
}
};
const tmp = builder.getBuildDirectory('azure-tmp');
const publish = 'build';
const staticDir = join(publish, 'static');
const apiDir = join('api', 'render');
const entry = `${tmp}/entry.js`;
builder.log.minor(`Publishing to "${publish}"`);
builder.rimraf(tmp);
builder.rimraf(publish);
builder.rimraf(apiDir);
builder.log.minor('Prerendering static pages...');
const prerendered = await builder.prerender({
dest: staticDir
});
if (!prerendered.paths.includes('/')) {
// Azure SWA requires an index.html to be present
// If the root was not pre-rendered, add a placeholder index.html
// Route all requests for the index to the SSR function
writeFileSync(`${staticDir}/index.html`, '');
swaConfig.routes.push(
{
route: '/index.html',
rewrite: ssrFunctionRoute
},
{
route: '/',
rewrite: ssrFunctionRoute
}
);
}
const files = fileURLToPath(new URL('./files', import.meta.url));
builder.log.minor('Generating serverless function...');
// use posix because of https://github.com/sveltejs/kit/pull/3200
const relativePath = posix.relative(tmp, builder.getServerDirectory());
builder.copy(join(files, 'entry.js'), entry, {
replace: {
APP: `${relativePath}/app.js`,
MANIFEST: './manifest.js',
DEBUG: debug.toString()
}
});
writeFileSync(
`${tmp}/manifest.js`,
`export const manifest = ${builder.generateManifest({
relativePath
})};\n`
);
writeFileSync(`${publish}/staticwebapp.config.json`, JSON.stringify(swaConfig));
builder.copy(join(files, 'api'), apiDir);
/** @type {BuildOptions} */
const default_options = {
entryPoints: [entry],
outfile: join(apiDir, 'index.js'),
bundle: true,
platform: 'node',
target: 'node12'
};
await esbuild.build(default_options);
builder.log.minor('Copying assets...');
builder.writeStatic(staticDir);
builder.writeClient(staticDir);
}
};
} | |
graph_funcs.py | import tensorflow as tf
############################################################
# Miscellenous Graph Functions
############################################################
def trim_zeros_graph(boxes, name='trim_zeros'):
|
def batch_pack_graph(x, counts, num_rows):
"""Picks different number of values from each row
in x depending on the values in counts.
"""
outputs = []
for i in range(num_rows):
outputs.append(x[i, :counts[i]])
return tf.concat(outputs, axis=0)
def norm_boxes_graph(boxes, shape):
"""Converts boxes from pixel coordinates to normalized coordinates.
boxes: [..., (y1, x1, y2, x2)] in pixel coordinates
shape: [..., (height, width)] in pixels
Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
coordinates it's inside the box.
Returns:
[..., (y1, x1, y2, x2)] in normalized coordinates
"""
h, w = tf.split(tf.cast(shape, tf.float32), 2)
scale = tf.concat([h, w, h, w], axis=-1) - tf.constant(1.0)
shift = tf.constant([0., 0., 1., 1.])
return tf.divide(boxes - shift, scale)
def denorm_boxes_graph(boxes, shape):
"""Converts boxes from normalized coordinates to pixel coordinates.
boxes: [..., (y1, x1, y2, x2)] in normalized coordinates
shape: [..., (height, width)] in pixels
Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
coordinates it's inside the box.
Returns:
[..., (y1, x1, y2, x2)] in pixel coordinates
"""
h, w = tf.split(tf.cast(shape, tf.float32), 2)
scale = tf.concat([h, w, h, w], axis=-1) - tf.constant(1.0)
shift = tf.constant([0., 0., 1., 1.])
return tf.cast(tf.round(tf.multiply(boxes, scale) + shift), tf.int32)
def overlaps_graph(boxes1, boxes2):
"""Computes IoU overlaps between two sets of boxes.
boxes1, boxes2: [N, (y1, x1, y2, x2)].
"""
# 1. Tile boxes2 and repeat boxes1. This allows us to compare
# every boxes1 against every boxes2 without loops.
# TF doesn't have an equivalent to np.repeat() so simulate it
# using tf.tile() and tf.reshape.
b1 = tf.reshape(tf.tile(tf.expand_dims(boxes1, 1),
[1, 1, tf.shape(boxes2)[0]]), [-1, 4])
b2 = tf.tile(boxes2, [tf.shape(boxes1)[0], 1])
# 2. Compute intersections
b1_y1, b1_x1, b1_y2, b1_x2 = tf.split(b1, 4, axis=1)
b2_y1, b2_x1, b2_y2, b2_x2 = tf.split(b2, 4, axis=1)
y1 = tf.maximum(b1_y1, b2_y1)
x1 = tf.maximum(b1_x1, b2_x1)
y2 = tf.minimum(b1_y2, b2_y2)
x2 = tf.minimum(b1_x2, b2_x2)
intersection = tf.maximum(x2 - x1, 0) * tf.maximum(y2 - y1, 0)
# 3. Compute unions
b1_area = (b1_y2 - b1_y1) * (b1_x2 - b1_x1)
b2_area = (b2_y2 - b2_y1) * (b2_x2 - b2_x1)
union = b1_area + b2_area - intersection
# 4. Compute IoU and reshape to [boxes1, boxes2]
iou = intersection / union
overlaps = tf.reshape(iou, [tf.shape(boxes1)[0], tf.shape(boxes2)[0]])
return overlaps
def batch_slice(inputs, graph_fn, batch_size, names=None):
"""Splits inputs into slices and feeds each slice to a copy of the given
computation graph and then combines the results. It allows you to run a
graph on a batch of inputs even if the graph is written to support one
instance only.
inputs: list of tensors. All must have the same first dimension length
graph_fn: A function that returns a TF tensor that's part of a graph.
batch_size: number of slices to divide the data into.
names: If provided, assigns names to the resulting tensors.
"""
if not isinstance(inputs, list):
inputs = [inputs]
outputs = []
for i in range(batch_size):
inputs_slice = [x[i] for x in inputs]
output_slice = graph_fn(*inputs_slice)
if not isinstance(output_slice, (tuple, list)):
output_slice = [output_slice]
outputs.append(output_slice)
# Change outputs from a list of slices where each is
# a list of outputs to a list of outputs and each has
# a list of slices
outputs = list(zip(*outputs))
if names is None:
names = [None] * len(outputs)
result = [tf.stack(o, axis=0, name=n)
for o, n in zip(outputs, names)]
if len(result) == 1:
result = result[0]
return result
def norm_boxes_graph(boxes, shape):
"""Converts boxes from pixel coordinates to normalized coordinates.
boxes: [..., (y1, x1, y2, x2)] in pixel coordinates
shape: [..., (height, width)] in pixels
Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
coordinates it's inside the box.
Returns:
[..., (y1, x1, y2, x2)] in normalized coordinates
"""
h, w = tf.split(tf.cast(shape, tf.float32), 2)
scale = tf.concat([h, w, h, w], axis=-1) - tf.constant(1.0)
shift = tf.constant([0., 0., 1., 1.])
return tf.divide(boxes - shift, scale)
def denorm_boxes_graph(boxes, shape):
"""Converts boxes from normalized coordinates to pixel coordinates.
boxes: [..., (y1, x1, y2, x2)] in normalized coordinates
shape: [..., (height, width)] in pixels
Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
coordinates it's inside the box.
Returns:
[..., (y1, x1, y2, x2)] in pixel coordinates
"""
h, w = tf.split(tf.cast(shape, tf.float32), 2)
scale = tf.concat([h, w, h, w], axis=-1) - tf.constant(1.0)
shift = tf.constant([0., 0., 1., 1.])
return tf.cast(tf.round(tf.multiply(boxes, scale) + shift), tf.int32) | """Often boxes are represented with matrices of shape [N, 4] and
are padded with zeros. This removes zero boxes.
boxes: [N, 4] matrix of boxes.
non_zeros: [N] a 1D boolean mask identifying the rows to keep
"""
non_zeros = tf.cast(tf.reduce_sum(tf.abs(boxes), axis=1), tf.bool)
boxes = tf.boolean_mask(boxes, non_zeros, name=name)
return boxes, non_zeros |
client.go | package videosearch
//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/provider"
)
// Client is the sdk client struct, each func corresponds to an OpenAPI
type Client struct {
sdk.Client
}
// NewClient creates a sdk client with environment variables
func NewClient() (client *Client, err error) {
client = &Client{}
err = client.Init()
return
}
// NewClientWithProvider creates a sdk client with providers
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithProvider(regionId string, providers ...provider.Provider) (client *Client, err error) {
client = &Client{}
var pc provider.Provider
if len(providers) == 0 {
pc = provider.DefaultChain
} else {
pc = provider.NewProviderChain(providers)
}
err = client.InitWithProviderChain(regionId, pc)
return
}
// NewClientWithOptions creates a sdk client with regionId/sdkConfig/credential
// this is the common api to create a sdk client
func NewClientWithOptions(regionId string, config *sdk.Config, credential auth.Credential) (client *Client, err error) {
client = &Client{}
err = client.InitWithOptions(regionId, config, credential)
return
}
// NewClientWithAccessKey is a shortcut to create sdk client with accesskey
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) {
client = &Client{}
err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret)
return
}
// NewClientWithStsToken is a shortcut to create sdk client with sts token
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func | (regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) {
client = &Client{}
err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken)
return
}
// NewClientWithRamRoleArn is a shortcut to create sdk client with ram roleArn
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) {
client = &Client{}
err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName)
return
}
// NewClientWithRamRoleArn is a shortcut to create sdk client with ram roleArn and policy
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithRamRoleArnAndPolicy(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy string) (client *Client, err error) {
client = &Client{}
err = client.InitWithRamRoleArnAndPolicy(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName, policy)
return
}
// NewClientWithEcsRamRole is a shortcut to create sdk client with ecs ram role
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) {
client = &Client{}
err = client.InitWithEcsRamRole(regionId, roleName)
return
}
// NewClientWithRsaKeyPair is a shortcut to create sdk client with rsa key pair
// usage: https://github.com/aliyun/alibaba-cloud-sdk-go/blob/master/docs/2-Client-EN.md
func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) {
client = &Client{}
err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration)
return
}
| NewClientWithStsToken |
fal_action.rs | use std::process::Command;
pub trait FalAction {
fn execute(&mut self, input: &str);
}
pub struct ExecuteAction {
pub launch_cmd: String,
}
pub struct LaunchAction {
pub launch_cmd: String,
}
pub struct NoAction {}
pub struct OpenInBrowserAction {}
pub struct ComputeExpressionAction {}
pub struct NagivateFileSystemAction {}
pub struct CustomAction {}
impl FalAction for ExecuteAction {
fn execute(&mut self, _: &str) {
if cfg!(target_os = "windows") {
Command::new("cmd")
.args(&["/C", self.launch_cmd.as_str()])
.output()
.expect("failed to execute process")
} else {
Command::new("sh")
.arg("-c")
.arg(self.launch_cmd.as_str())
.output()
.expect("failed to execute process")
};
}
}
impl FalAction for LaunchAction {
fn execute(&mut self, file_path: &str) {
Command::new(file_path)
.output()
.expect("failed to execute program");
} | impl FalAction for NoAction {
fn execute(&mut self, _: &str) {}
}
impl FalAction for OpenInBrowserAction {
fn execute(&mut self, input: &str) {
todo!()
}
}
impl FalAction for ComputeExpressionAction {
fn execute(&mut self, input: &str) {
todo!()
}
}
impl FalAction for NagivateFileSystemAction {
fn execute(&mut self, input: &str) {
todo!()
}
}
impl FalAction for CustomAction {
fn execute(&mut self, input: &str) {
todo!()
}
} | } |
PDUSessionResourceToReleaseItemHOCmd.go | package ngapType
import "github.com/free5gc/aper"
// Need to import "github.com/free5gc/aper" if it uses "aper" | type PDUSessionResourceToReleaseItemHOCmd struct {
PDUSessionID PDUSessionID
HandoverPreparationUnsuccessfulTransfer aper.OctetString
IEExtensions *ProtocolExtensionContainerPDUSessionResourceToReleaseItemHOCmdExtIEs `aper:"optional"`
} | |
index.js | import Router from 'vue-router'
import Vue from 'vue'
import { before, resolve, after } from '@/router/hooks'
Vue.use(Router)
const router = new Router({
mode: 'history',
base: window.config.path,
routes: [
{
path: '/',
component: () => import('@/pages/Dashboard'),
name: 'dashboard',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/login',
component: () => import('@/pages/Auth/Login'), | meta: {
requiresAuth: false,
layout: 'error'
}
},
{
path: '/insight',
component: () => import('@/pages/SEO/Insight'),
name: 'insight',
meta: {
requiresAuth: true,
layout: 'admin'
},
},
{
path: '/blueprints',
component: () => import('@/pages/Blueprints/Index'),
name: 'blueprints',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/blueprints/:blueprint/edit',
component: () => import('@/pages/Blueprints/Edit'),
name: 'blueprints.edit',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/taxonomies',
component: () => import('@/pages/Taxonomies/Index'),
name: 'taxonomies',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/taxonomies/create',
component: () => import('@/pages/Taxonomies/Create'),
name: 'taxonomies.create',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/taxonomies/:taxonomy/edit',
component: () => import('@/pages/Taxonomies/Edit'),
name: 'taxonomies.edit',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/navigation',
component: () => import('@/pages/Navigation/Index'),
name: 'navigation',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/navigation/create',
component: () => import('@/pages/Navigation/Create'),
name: 'navigation.create',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/navigation/:navigation/edit',
component: () => import('@/pages/Navigation/Edit'),
name: 'navigation.edit',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/navigation/:navigation/links',
component: () => import('@/pages/Links/Index'),
name: 'links',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/navigation/:navigation/links/create',
component: () => import('@/pages/Links/Create'),
name: 'links.create',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/navigation/:navigation/links/:link/edit',
component: () => import('@/pages/Links/Edit'),
name: 'links.edit',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/matrices',
component: () => import('@/pages/Matrices/Index'),
name: 'matrices',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/matrices/create',
component: () => import('@/pages/Matrices/Create'),
name: 'matrices.create',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/matrices/:matrix/edit',
component: () => import('@/pages/Matrices/Edit'),
name: 'matrices.edit',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/single/:single',
component: () => import('@/pages/Singles/Index'),
name: 'single.index',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/single/:single/edit',
component: () => import('@/pages/Singles/Edit'),
name: 'single.edit',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/collection/:collection',
component: () => import('@/pages/Collections/Index'),
name: 'collection.index',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/collection/:collection/create',
component: () => import('@/pages/Collections/Create'),
name: 'collection.create',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/collection/:collection/:id/edit',
component: () => import('@/pages/Collections/Edit'),
name: 'collection.edit',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/taxonomies/:taxonomy',
component: () => import('@/pages/Terms/Index'),
name: 'terms.index',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/taxonomies/:taxonomy/create',
component: () => import('@/pages/Terms/Create'),
name: 'terms.create',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/taxonomies/:taxonomy/:id/edit',
component: () => import('@/pages/Terms/Edit'),
name: 'terms.edit',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/fieldsets',
component: () => import('@/pages/Fieldsets/Index'),
name: 'fieldsets',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/fieldsets/create',
component: () => import('@/pages/Fieldsets/Create'),
name: 'fieldsets.create',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/fieldsets/:fieldset/edit',
component: () => import('@/pages/Fieldsets/Edit'),
name: 'fieldsets.edit',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/forms',
component: () => import('@/pages/Forms/Index'),
name: 'forms',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/forms/create',
component: () => import('@/pages/Forms/Create'),
name: 'forms.create',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/forms/:form/edit',
component: () => import('@/pages/Forms/Edit'),
name: 'forms.edit',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/inbox',
component: () => import('@/pages/Inbox/Index'),
name: 'inbox',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/users',
component: () => import('@/pages/Users/Index'),
name: 'users',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/users/create',
component: () => import('@/pages/Users/Create'),
name: 'users.create',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/users/:user/edit',
component: () => import('@/pages/Users/Edit'),
name: 'users.edit',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/users/:user',
component: () => import('@/pages/Users/Show'),
name: 'users.show',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/users/:role',
component: () => import('@/pages/Users/Index'),
name: 'users.role',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/roles',
component: () => import('@/pages/Roles/Index'),
name: 'roles',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/roles/create',
component: () => import('@/pages/Roles/Create'),
name: 'roles.create',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/roles/:role/edit',
component: () => import('@/pages/Roles/Edit'),
name: 'roles.edit',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/roles/:role',
component: () => import('@/pages/Roles/Show'),
name: 'roles.show',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/permissions',
component: () => import('@/pages/Permissions'),
name: 'permissions',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/settings',
component: () => import('@/pages/Settings/Index'),
name: 'settings',
meta: {
requiresAuth: true,
layout: 'admin',
}
},
{
path: '/settings/:group',
component: () => import('@/pages/Settings/Edit'),
name: 'setting.group',
meta: {
requiresAuth: true,
layout: 'admin',
}
},
{
path: '/theme',
component: () => import('@/pages/Theme'),
name: 'theme',
meta: {
requiresAuth: true,
layout: 'admin',
}
},
{
path: '/customize',
component: () => import('@/pages/Customize'),
name: 'customize',
meta: {
requiresAuth: true,
layout: 'blank',
}
},
{
path: '/files/:disk',
alias: '/files',
component: () => import('@/pages/FileManager/Index'),
name: 'file-manager.index',
meta: {
requiresAuth: true,
layout: 'admin',
}
},
{
path: '/files/:disk/:file',
component: () => import('@/pages/FileManager/Show'),
name: 'file-manager.show',
meta: {
requiresAuth: true,
layout: 'admin',
}
},
{
path: '/logs',
component: () => import('@/pages/Logs/Index'),
name: 'logs.index',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/backups',
component: () => import('@/pages/Backups/Index'),
name: 'backups',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/backups/:backup',
component: () => import('@/pages/Backups/Show'),
name: 'backups.show',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/scripts',
component: () => import('@/pages/Scripts/Index'),
name: 'scripts',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/scripts/create',
component: () => import('@/pages/Scripts/Create'),
name: 'scripts.create',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/scripts/:script/edit',
component: () => import('@/pages/Scripts/Edit'),
name: 'scripts.edit',
meta: {
requiresAuth: true,
layout: 'admin',
},
},
{
path: '/updates',
component: () => import('@/pages/Updates/Index'),
name: 'updates',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/disks',
component: () => import('@/pages/Disks/Index'),
name: 'disks',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/disks/create',
component: () => import('@/pages/Disks/Create'),
name: 'disks.create',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/disks/:disk/edit',
component: () => import('@/pages/Disks/Edit'),
name: 'disks.edit',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/styleguide',
component: () => import('@/pages/Styleguide/Index'),
name: 'styleguide',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/styleguide/tables',
component: () => import('@/pages/Styleguide/Tables'),
name: 'styleguide.tables',
meta: {
requiresAuth: true,
layout: 'admin'
}
},
{
path: '/403',
component: () => import('@/pages/403'),
name: '403',
meta: {
layout: 'error'
}
},
{
path: '/404',
component: () => import('@/pages/404'),
name: '404',
meta: {
layout: 'error'
}
},
{
path: '*',
redirect: '/404'
},
],
})
router.beforeEach(before)
router.beforeResolve(resolve)
router.afterEach(after)
export default router | name: 'login', |
app.js | angular.module('app', [
'ngRoute',
'projectsinfo',
'dashboard',
'projects',
'admin',
'services.breadcrumbs',
'services.i18nNotifications',
'services.httpRequestTracker',
'security',
'directives.crud',
'templates.app',
'templates.common']);
angular.module('app').constant('MONGOLAB_CONFIG', {
baseUrl: '/databases/',
dbName: 'angular-app-jgs'
});
//TODO: move those messages to a separate module
angular.module('app').constant('I18N.MESSAGES', {
'errors.route.changeError':'Route change error',
'crud.user.save.success':"A user with id '{{id}}' was saved successfully.",
'crud.user.remove.success':"A user with id '{{id}}' was removed successfully.",
'crud.user.remove.error':"Something went wrong when removing user with id '{{id}}'.",
'crud.user.save.error':"Something went wrong when saving a user...",
'crud.project.save.success':"A project with id '{{id}}' was saved successfully.",
'crud.project.remove.success':"A project with id '{{id}}' was removed successfully.",
'crud.project.save.error':"Something went wrong when saving a project...",
'login.reason.notAuthorized':"You do not have the necessary access permissions. Do you want to login as someone else?",
'login.reason.notAuthenticated':"You must be logged in to access this part of the application.",
'login.error.invalidCredentials': "Login failed. Please check your credentials and try again.",
'login.error.serverError': "There was a problem with authenticating: {{exception}}."
});
angular.module('app').config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.otherwise({redirectTo:'/projectsinfo'});
}]);
angular.module('app').run(['security', function(security) {
// Get the current user when the application starts
// (in case they are still logged in from a previous session)
security.requestCurrentUser();
}]);
angular.module('app').controller('AppCtrl', ['$scope', 'i18nNotifications', 'localizedMessages', function($scope, i18nNotifications) {
$scope.notifications = i18nNotifications;
$scope.removeNotification = function (notification) {
i18nNotifications.remove(notification);
};
$scope.$on('$routeChangeError', function(event, current, previous, rejection){
i18nNotifications.pushForCurrentRoute('errors.route.changeError', 'error', {}, {rejection: rejection});
});
}]);
angular.module('app').controller('HeaderCtrl', ['$scope', '$location', '$route', 'security', 'breadcrumbs', 'notifications', 'httpRequestTracker',
function ($scope, $location, $route, security, breadcrumbs, notifications, httpRequestTracker) {
$scope.location = $location; | $scope.isAuthenticated = security.isAuthenticated;
$scope.isAdmin = security.isAdmin;
$scope.home = function () {
if (security.isAuthenticated()) {
$location.path('/dashboard');
} else {
$location.path('/projectsinfo');
}
};
$scope.isNavbarActive = function (navBarPath) {
return navBarPath === breadcrumbs.getFirst().name;
};
$scope.hasPendingRequests = function () {
return httpRequestTracker.hasPendingRequests();
};
}]); | $scope.breadcrumbs = breadcrumbs;
|
FormTextInput.tsx | import classNames from 'classnames';
import React, { ChangeEventHandler, Component, ReactNode } from 'react';
import ErrorMessage from '../ErrorMessage';
import createDescribedBy from './util/createDescribedBy';
interface Props {
error?: ReactNode | string;
hint?: string;
id: string;
label: ReactNode | string;
name: string;
onChange?: ChangeEventHandler<HTMLInputElement>;
width?: 20 | 10 | 5 | 4 | 3 | 2;
}
class FormTextInput extends Component<Props> {
private handleChange: ChangeEventHandler<HTMLInputElement> = event => {
if (this.props.onChange) {
this.props.onChange(event);
}
};
public render() {
const { error, hint, id, label, name, width } = this.props;
return (
<>
<label className="govuk-label" htmlFor={id}>
{label}
</label>
{hint && (
<span id={`${id}-hint`} className="govuk-hint">
{hint}
</span>
)}
{error && <ErrorMessage id={`${id}-error`}>{error}</ErrorMessage>}
<input
aria-describedby={createDescribedBy({
id,
error: !!error,
hint: !!hint,
})}
type="text"
className={classNames('govuk-input', {
[`govuk-input--width-${width}`]: width !== undefined,
})}
id={id}
name={name}
onChange={this.handleChange}
/>
</> | );
}
}
export default FormTextInput; | |
listDeviceFailoverTars.go | // *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package latest
import (
"github.com/pulumi/pulumi/sdk/v2/go/pulumi"
)
// The list of all devices in a resource and their eligibility status as a failover target device.
// Latest API Version: 2017-06-01.
//
// Deprecated: The 'latest' version is deprecated. Please migrate to the function in the top-level module: 'azure-nextgen:storsimple:listDeviceFailoverTars'.
func | (ctx *pulumi.Context, args *ListDeviceFailoverTarsArgs, opts ...pulumi.InvokeOption) (*ListDeviceFailoverTarsResult, error) {
var rv ListDeviceFailoverTarsResult
err := ctx.Invoke("azure-nextgen:storsimple/latest:listDeviceFailoverTars", args, &rv, opts...)
if err != nil {
return nil, err
}
return &rv, nil
}
type ListDeviceFailoverTarsArgs struct {
// The manager name
ManagerName string `pulumi:"managerName"`
// The resource group name
ResourceGroupName string `pulumi:"resourceGroupName"`
// The source device name on which failover is performed.
SourceDeviceName string `pulumi:"sourceDeviceName"`
// The list of path IDs of the volume containers that needs to be failed-over, for which we want to fetch the eligible targets.
VolumeContainers []string `pulumi:"volumeContainers"`
}
// The list of all devices in a resource and their eligibility status as a failover target device.
type ListDeviceFailoverTarsResult struct {
// The list of all the failover targets.
Value []FailoverTargetResponse `pulumi:"value"`
}
| ListDeviceFailoverTars |
state.rs | #![cfg_attr(not(feature = "program"), allow(unused))]
use num_enum::TryFromPrimitive;
use std::{
cell::RefMut, convert::identity, convert::TryInto, mem::size_of, num::NonZeroU64, ops::DerefMut,
};
use arrayref::{array_ref, array_refs, mut_array_refs};
use bytemuck::{
bytes_of, bytes_of_mut, cast, cast_slice, cast_slice_mut, from_bytes_mut, try_cast_mut,
try_cast_slice_mut, try_from_bytes_mut, Pod, Zeroable,
};
use enumflags2::BitFlags;
use num_traits::FromPrimitive;
use safe_transmute::{self, to_bytes::transmute_to_bytes, trivial::TriviallyTransmutable};
use solana_program::{
account_info::AccountInfo,
program_error::ProgramError,
program_pack::Pack,
pubkey::Pubkey,
rent::Rent,
sysvar::{Sysvar, SysvarId},
};
use spl_token::error::TokenError;
use crate::{
critbit::Slab,
error::{DexErrorCode, DexResult, SourceFileId},
fees::{self, FeeTier},
instruction::{
disable_authority, fee_sweeper, msrm_token, srm_token, CancelOrderInstructionV2,
InitializeMarketInstruction, MarketInstruction, NewOrderInstructionV3, SelfTradeBehavior,
SendTakeInstruction,
},
matching::{OrderBookState, OrderType, RequestProceeds, Side},
};
declare_check_assert_macros!(SourceFileId::State);
pub trait ToAlignedBytes {
fn to_aligned_bytes(&self) -> [u64; 4];
}
impl ToAlignedBytes for Pubkey {
#[inline]
fn to_aligned_bytes(&self) -> [u64; 4] {
cast(self.to_bytes())
}
}
#[derive(Copy, Clone, BitFlags, Debug, Eq, PartialEq)]
#[repr(u64)]
pub enum AccountFlag {
Initialized = 1u64 << 0,
Market = 1u64 << 1,
OpenOrders = 1u64 << 2,
RequestQueue = 1u64 << 3,
EventQueue = 1u64 << 4,
Bids = 1u64 << 5,
Asks = 1u64 << 6,
Disabled = 1u64 << 7,
Closed = 1u64 << 8,
}
#[derive(Copy, Clone)]
#[cfg_attr(target_endian = "little", derive(Debug))]
#[repr(packed)]
pub struct MarketState {
// 0
pub account_flags: u64, // Initialized, Market
// 1
pub own_address: [u64; 4],
// 5
pub vault_signer_nonce: u64,
// 6
pub coin_mint: [u64; 4],
// 10
pub pc_mint: [u64; 4],
// 14
pub coin_vault: [u64; 4],
// 18
pub coin_deposits_total: u64,
// 19
pub coin_fees_accrued: u64,
// 20
pub pc_vault: [u64; 4],
// 24
pub pc_deposits_total: u64,
// 25
pub pc_fees_accrued: u64,
// 26
pub pc_dust_threshold: u64,
// 27
pub req_q: [u64; 4],
// 31
pub event_q: [u64; 4],
// 35
pub bids: [u64; 4],
// 39
pub asks: [u64; 4],
// 43
pub coin_lot_size: u64,
// 44
pub pc_lot_size: u64,
// 45
pub fee_rate_bps: u64,
// 46
pub referrer_rebates_accrued: u64,
}
#[cfg(target_endian = "little")]
unsafe impl Zeroable for MarketState {}
#[cfg(target_endian = "little")]
unsafe impl Pod for MarketState {}
#[cfg(target_endian = "little")]
unsafe impl TriviallyTransmutable for MarketState {}
pub const ACCOUNT_HEAD_PADDING: &[u8; 5] = b"serum";
pub const ACCOUNT_TAIL_PADDING: &[u8; 7] = b"padding";
fn init_account_padding(data: &mut [u8]) -> DexResult<&mut [[u8; 8]]> {
check_assert!(data.len() >= 12)?;
let (head, data, tail) = mut_array_refs![data, 5; ..; 7];
*head = *ACCOUNT_HEAD_PADDING;
*tail = *ACCOUNT_TAIL_PADDING;
Ok(try_cast_slice_mut(data).or(check_unreachable!())?)
}
fn check_account_padding(data: &mut [u8]) -> DexResult<&mut [[u8; 8]]> {
check_assert!(data.len() >= 12)?;
let (head, data, tail) = mut_array_refs![data, 5; ..; 7];
check_assert_eq!(head, ACCOUNT_HEAD_PADDING)?;
check_assert_eq!(tail, ACCOUNT_TAIL_PADDING)?;
Ok(try_cast_slice_mut(data).or(check_unreachable!())?)
}
fn strip_account_padding(padded_data: &mut [u8], init_allowed: bool) -> DexResult<&mut [[u8; 8]]> {
if init_allowed {
init_account_padding(padded_data)
} else {
check_account_padding(padded_data)
}
}
pub fn strip_header<'a, H: Pod, D: Pod>(
account: &'a AccountInfo,
init_allowed: bool,
) -> DexResult<(RefMut<'a, H>, RefMut<'a, [D]>)> {
let mut result = Ok(());
let (header, inner): (RefMut<'a, [H]>, RefMut<'a, [D]>) =
RefMut::map_split(account.try_borrow_mut_data()?, |padded_data| {
let dummy_value: (&mut [H], &mut [D]) = (&mut [], &mut []);
let padded_data: &mut [u8] = *padded_data;
let u64_data = match strip_account_padding(padded_data, init_allowed) {
Ok(u64_data) => u64_data,
Err(e) => {
result = Err(e);
return dummy_value;
}
};
let data: &mut [u8] = cast_slice_mut(u64_data);
let (header_bytes, inner_bytes) = data.split_at_mut(size_of::<H>());
let header: &mut H;
let inner: &mut [D];
header = match try_from_bytes_mut(header_bytes) {
Ok(h) => h,
Err(_e) => {
result = Err(assertion_error!().into());
return dummy_value;
}
};
inner = remove_slop_mut(inner_bytes);
(std::slice::from_mut(header), inner)
});
result?;
let header = RefMut::map(header, |s| s.first_mut().unwrap_or_else(|| unreachable!()));
Ok((header, inner))
}
impl MarketState {
#[inline]
pub fn load<'a>(
market_account: &'a AccountInfo,
program_id: &Pubkey,
) -> DexResult<RefMut<'a, Self>> {
check_assert_eq!(market_account.owner, program_id)?;
let mut account_data: RefMut<'a, [u8]>;
let state: RefMut<'a, Self>;
account_data = RefMut::map(market_account.try_borrow_mut_data()?, |data| *data);
check_account_padding(&mut account_data)?;
state = RefMut::map(account_data, |data| {
from_bytes_mut(cast_slice_mut(
check_account_padding(data).unwrap_or_else(|_| unreachable!()),
))
});
state.check_flags()?;
Ok(state)
}
#[inline]
pub fn check_flags(&self) -> DexResult {
let flags = BitFlags::from_bits(self.account_flags)
.map_err(|_| DexErrorCode::InvalidMarketFlags)?;
let required_flags = AccountFlag::Initialized | AccountFlag::Market;
if flags != required_flags {
Err(DexErrorCode::InvalidMarketFlags)?
}
Ok(())
}
pub fn load_orders_mut<'a>(
&self,
orders_account: &'a AccountInfo,
owner_account: Option<&AccountInfo>,
program_id: &Pubkey,
rent: Option<Rent>,
) -> DexResult<RefMut<'a, OpenOrders>> {
check_assert_eq!(orders_account.owner, program_id)?;
let mut open_orders: RefMut<'a, OpenOrders>;
let open_orders_data_len = orders_account.data_len();
let open_orders_lamports = orders_account.lamports();
let (_, data) = strip_header::<[u8; 0], u8>(orders_account, true)?;
open_orders = RefMut::map(data, |data| from_bytes_mut(data));
if open_orders.account_flags == 0 {
let rent = rent.ok_or(DexErrorCode::RentNotProvided)?;
let owner_account = owner_account.ok_or(DexErrorCode::OwnerAccountNotProvided)?;
if !rent.is_exempt(open_orders_lamports, open_orders_data_len) {
return Err(DexErrorCode::OrdersNotRentExempt)?;
}
open_orders.init(
&identity(self.own_address),
&owner_account.key.to_aligned_bytes(),
)?;
}
open_orders.check_flags()?;
check_assert_eq!(identity(open_orders.market), identity(self.own_address))
.map_err(|_| DexErrorCode::WrongOrdersAccount)?;
if let Some(owner) = owner_account {
check_assert_eq!(&identity(open_orders.owner), &owner.key.to_aligned_bytes())
.map_err(|_| DexErrorCode::WrongOrdersAccount)?;
}
Ok(open_orders)
}
pub fn load_bids_mut<'a>(&self, bids: &'a AccountInfo) -> DexResult<RefMut<'a, Slab>> {
check_assert_eq!(&bids.key.to_aligned_bytes(), &identity(self.bids))
.map_err(|_| DexErrorCode::WrongBidsAccount)?;
let (header, buf) = strip_header::<OrderBookStateHeader, u8>(bids, false)?;
let flags = BitFlags::from_bits(header.account_flags).unwrap();
check_assert_eq!(&flags, &(AccountFlag::Initialized | AccountFlag::Bids))?;
Ok(RefMut::map(buf, Slab::new))
}
pub fn load_asks_mut<'a>(&self, asks: &'a AccountInfo) -> DexResult<RefMut<'a, Slab>> {
check_assert_eq!(&asks.key.to_aligned_bytes(), &identity(self.asks))
.map_err(|_| DexErrorCode::WrongAsksAccount)?;
let (header, buf) = strip_header::<OrderBookStateHeader, u8>(asks, false)?;
let flags = BitFlags::from_bits(header.account_flags).unwrap();
check_assert_eq!(&flags, &(AccountFlag::Initialized | AccountFlag::Asks))?;
Ok(RefMut::map(buf, Slab::new))
}
fn load_request_queue_mut<'a>(&self, queue: &'a AccountInfo) -> DexResult<RequestQueue<'a>> {
check_assert_eq!(&queue.key.to_aligned_bytes(), &identity(self.req_q))
.map_err(|_| DexErrorCode::WrongRequestQueueAccount)?;
let (header, buf) = strip_header::<RequestQueueHeader, Request>(queue, false)?;
let flags = BitFlags::from_bits(header.account_flags).unwrap();
check_assert_eq!(
&flags,
&(AccountFlag::Initialized | AccountFlag::RequestQueue)
)?;
Ok(Queue { header, buf })
}
fn load_event_queue_mut<'a>(&self, queue: &'a AccountInfo) -> DexResult<EventQueue<'a>> {
check_assert_eq!(&queue.key.to_aligned_bytes(), &identity(self.event_q))
.map_err(|_| DexErrorCode::WrongEventQueueAccount)?;
let (header, buf) = strip_header::<EventQueueHeader, Event>(queue, false)?;
let flags = BitFlags::from_bits(header.account_flags).unwrap();
check_assert_eq!(
&flags,
&(AccountFlag::Initialized | AccountFlag::EventQueue)
)?;
Ok(Queue { header, buf })
}
#[inline]
fn check_coin_vault(&self, vault: account_parser::TokenAccount) -> DexResult {
if identity(self.coin_vault) != vault.inner().key.to_aligned_bytes() {
Err(DexErrorCode::WrongCoinVault)?
}
Ok(())
}
#[inline]
fn check_pc_vault(&self, vault: account_parser::TokenAccount) -> DexResult {
if identity(self.pc_vault) != vault.inner().key.to_aligned_bytes() {
Err(DexErrorCode::WrongPcVault)?
}
Ok(())
}
#[inline]
fn check_coin_payer(&self, payer: account_parser::TokenAccount) -> DexResult {
if &payer.inner().try_borrow_data()?[..32] != transmute_to_bytes(&identity(self.coin_mint))
{
Err(DexErrorCode::WrongCoinMint)?
}
Ok(())
}
#[inline]
fn check_pc_payer(&self, payer: account_parser::TokenAccount) -> DexResult {
if &payer.inner().try_borrow_data()?[..32] != transmute_to_bytes(&identity(self.pc_mint)) {
Err(DexErrorCode::WrongPcMint)?
}
Ok(())
}
#[inline]
fn load_fee_tier(
&self,
expected_owner: &[u64; 4],
srm_or_msrm_account: Option<account_parser::TokenAccount>,
) -> DexResult<FeeTier> {
let srm_or_msrm_account = match srm_or_msrm_account {
Some(a) => a,
None => return Ok(FeeTier::Base),
};
let data = srm_or_msrm_account.inner().try_borrow_data()?;
let mut aligned_data: [u64; 9] = Zeroable::zeroed();
bytes_of_mut(&mut aligned_data).copy_from_slice(&data[..72]);
let (mint, owner, &[balance]) = array_refs![&aligned_data, 4, 4, 1];
check_assert_eq!(owner, expected_owner)?;
if mint == &srm_token::ID.to_aligned_bytes() {
return Ok(FeeTier::from_srm_and_msrm_balances(balance, 0));
}
if mint == &msrm_token::ID.to_aligned_bytes() {
return Ok(FeeTier::from_srm_and_msrm_balances(0, balance));
}
Ok(FeeTier::from_srm_and_msrm_balances(0, 0))
}
fn check_enabled(&self) -> DexResult {
let flags = BitFlags::from_bits(self.account_flags).unwrap();
if flags.contains(AccountFlag::Disabled) {
return Err(DexErrorCode::MarketIsDisabled.into());
}
Ok(())
}
fn pubkey(&self) -> Pubkey {
Pubkey::new(cast_slice(&identity(self.own_address) as &[_]))
}
}
#[repr(packed)]
#[derive(Copy, Clone)]
#[cfg_attr(feature = "fuzz", derive(Debug))]
pub struct OpenOrders {
pub account_flags: u64, // Initialized, OpenOrders
pub market: [u64; 4],
pub owner: [u64; 4],
pub native_coin_free: u64,
pub native_coin_total: u64,
pub native_pc_free: u64,
pub native_pc_total: u64,
pub free_slot_bits: u128,
pub is_bid_bits: u128,
pub orders: [u128; 128],
// Using Option<NonZeroU64> in a pod type requires nightly
pub client_order_ids: [u64; 128],
pub referrer_rebates_accrued: u64,
}
unsafe impl Pod for OpenOrders {}
unsafe impl Zeroable for OpenOrders {}
impl OpenOrders {
fn check_flags(&self) -> DexResult {
let flags = BitFlags::from_bits(self.account_flags)
.map_err(|_| DexErrorCode::InvalidMarketFlags)?;
let required_flags = AccountFlag::Initialized | AccountFlag::OpenOrders;
if flags != required_flags {
Err(DexErrorCode::WrongOrdersAccount)?
}
Ok(())
}
fn init(&mut self, market: &[u64; 4], owner: &[u64; 4]) -> DexResult<()> {
check_assert_eq!(self.account_flags, 0)?;
self.account_flags = (AccountFlag::Initialized | AccountFlag::OpenOrders).bits();
self.market = *market;
self.owner = *owner;
self.native_coin_total = 0;
self.native_coin_free = 0;
self.native_pc_total = 0;
self.native_pc_free = 0;
self.free_slot_bits = std::u128::MAX;
Ok(())
}
fn credit_locked_coin(&mut self, native_coin_amount: u64) {
self.native_coin_total = self
.native_coin_total
.checked_add(native_coin_amount)
.unwrap();
}
fn credit_locked_pc(&mut self, native_pc_amount: u64) {
self.native_pc_total = self.native_pc_total.checked_add(native_pc_amount).unwrap();
}
fn lock_free_coin(&mut self, native_coin_amount: u64) {
self.native_coin_free = self
.native_coin_free
.checked_sub(native_coin_amount)
.unwrap();
}
fn lock_free_pc(&mut self, native_pc_amount: u64) {
self.native_pc_free = self.native_pc_free.checked_sub(native_pc_amount).unwrap();
}
pub fn unlock_coin(&mut self, native_coin_amount: u64) {
self.native_coin_free = self
.native_coin_free
.checked_add(native_coin_amount)
.unwrap();
assert!(self.native_coin_free <= self.native_coin_total);
}
pub fn unlock_pc(&mut self, native_pc_amount: u64) {
self.native_pc_free = self.native_pc_free.checked_add(native_pc_amount).unwrap();
assert!(self.native_pc_free <= self.native_pc_total);
}
fn slot_is_free(&self, slot: u8) -> bool {
let slot_mask = 1u128 << slot;
self.free_slot_bits & slot_mask != 0
}
#[inline]
fn iter_filled_slots(&self) -> impl Iterator<Item = u8> {
struct Iter {
bits: u128,
}
impl Iterator for Iter {
type Item = u8;
#[inline(always)]
fn next(&mut self) -> Option<Self::Item> {
if self.bits == 0 {
None
} else {
let next = self.bits.trailing_zeros();
let mask = 1u128 << next;
self.bits &= !mask;
Some(next as u8)
}
}
}
Iter {
bits: !self.free_slot_bits,
}
}
#[inline]
fn orders_with_client_ids(&self) -> impl Iterator<Item = (NonZeroU64, u128, Side)> + '_ {
self.iter_filled_slots().filter_map(move |slot| {
let client_order_id = NonZeroU64::new(self.client_order_ids[slot as usize])?;
let order_id = self.orders[slot as usize];
let side = self.slot_side(slot).unwrap();
Some((client_order_id, order_id, side))
})
}
pub fn slot_side(&self, slot: u8) -> Option<Side> {
let slot_mask = 1u128 << slot;
if self.free_slot_bits & slot_mask != 0 {
None
} else if self.is_bid_bits & slot_mask != 0 {
Some(Side::Bid)
} else {
Some(Side::Ask)
}
}
pub fn remove_order(&mut self, slot: u8) -> DexResult {
check_assert!(slot < 128)?;
check_assert!(!self.slot_is_free(slot))?;
let slot_mask = 1u128 << slot;
self.orders[slot as usize] = 0;
self.client_order_ids[slot as usize] = 0;
self.free_slot_bits |= slot_mask;
self.is_bid_bits &= !slot_mask;
Ok(())
}
fn add_order(&mut self, id: u128, side: Side) -> DexResult<u8> {
if self.free_slot_bits == 0 {
Err(DexErrorCode::TooManyOpenOrders)?;
}
let slot = self.free_slot_bits.trailing_zeros();
check_assert!(self.slot_is_free(slot as u8))?;
let slot_mask = 1u128 << slot;
self.free_slot_bits &= !slot_mask;
match side {
Side::Bid => {
self.is_bid_bits |= slot_mask;
}
Side::Ask => {
self.is_bid_bits &= !slot_mask;
}
};
self.orders[slot as usize] = id;
Ok(slot as u8)
}
}
pub trait QueueHeader: Pod {
type Item: Pod + Copy;
fn head(&self) -> u64;
fn set_head(&mut self, value: u64);
fn count(&self) -> u64;
fn set_count(&mut self, value: u64);
fn incr_event_id(&mut self);
fn decr_event_id(&mut self, n: u64);
}
pub struct Queue<'a, H: QueueHeader> {
header: RefMut<'a, H>,
buf: RefMut<'a, [H::Item]>,
}
impl<'a, H: QueueHeader> Queue<'a, H> {
pub fn new(header: RefMut<'a, H>, buf: RefMut<'a, [H::Item]>) -> Self |
#[inline]
pub fn len(&self) -> u64 {
self.header.count()
}
#[inline]
pub fn full(&self) -> bool {
self.header.count() as usize == self.buf.len()
}
#[inline]
pub fn empty(&self) -> bool {
self.header.count() == 0
}
#[inline]
pub fn push_back(&mut self, value: H::Item) -> Result<(), H::Item> {
if self.full() {
return Err(value);
}
let slot = ((self.header.head() + self.header.count()) as usize) % self.buf.len();
self.buf[slot] = value;
let count = self.header.count();
self.header.set_count(count + 1);
self.header.incr_event_id();
Ok(())
}
#[inline]
pub fn peek_front(&self) -> Option<&H::Item> {
if self.empty() {
return None;
}
Some(&self.buf[self.header.head() as usize])
}
#[inline]
pub fn peek_front_mut(&mut self) -> Option<&mut H::Item> {
if self.empty() {
return None;
}
Some(&mut self.buf[self.header.head() as usize])
}
#[inline]
pub fn pop_front(&mut self) -> Result<H::Item, ()> {
if self.empty() {
return Err(());
}
let value = self.buf[self.header.head() as usize];
let count = self.header.count();
self.header.set_count(count - 1);
let head = self.header.head();
self.header.set_head((head + 1) % self.buf.len() as u64);
Ok(value)
}
#[inline]
pub fn revert_pushes(&mut self, desired_len: u64) -> DexResult<()> {
check_assert!(desired_len <= self.header.count())?;
let len_diff = self.header.count() - desired_len;
self.header.set_count(desired_len);
self.header.decr_event_id(len_diff);
Ok(())
}
pub fn iter(&self) -> impl Iterator<Item = &H::Item> {
QueueIterator {
queue: self,
index: 0,
}
}
}
struct QueueIterator<'a, 'b, H: QueueHeader> {
queue: &'b Queue<'a, H>,
index: u64,
}
impl<'a, 'b, H: QueueHeader> Iterator for QueueIterator<'a, 'b, H> {
type Item = &'b H::Item;
fn next(&mut self) -> Option<Self::Item> {
if self.index == self.queue.len() {
None
} else {
let item = &self.queue.buf
[(self.queue.header.head() + self.index) as usize % self.queue.buf.len()];
self.index += 1;
Some(item)
}
}
}
#[derive(Copy, Clone, Debug)]
#[repr(packed)]
pub struct RequestQueueHeader {
account_flags: u64, // Initialized, RequestQueue
head: u64,
count: u64,
next_seq_num: u64,
}
unsafe impl Zeroable for RequestQueueHeader {}
unsafe impl Pod for RequestQueueHeader {}
impl QueueHeader for RequestQueueHeader {
type Item = Request;
fn head(&self) -> u64 {
self.head
}
fn set_head(&mut self, value: u64) {
self.head = value;
}
fn count(&self) -> u64 {
self.count
}
fn set_count(&mut self, value: u64) {
self.count = value;
}
#[inline(always)]
fn incr_event_id(&mut self) {}
#[inline(always)]
fn decr_event_id(&mut self, _n: u64) {}
}
pub type RequestQueue<'a> = Queue<'a, RequestQueueHeader>;
impl RequestQueue<'_> {
fn gen_order_id(&mut self, limit_price: u64, side: Side) -> u128 {
let seq_num = self.gen_seq_num();
let upper = (limit_price as u128) << 64;
let lower = match side {
Side::Bid => !seq_num,
Side::Ask => seq_num,
};
upper | (lower as u128)
}
fn gen_seq_num(&mut self) -> u64 {
let seq_num = self.header.next_seq_num;
self.header.next_seq_num += 1;
seq_num
}
}
#[derive(Copy, Clone, BitFlags, Debug)]
#[repr(u8)]
enum RequestFlag {
NewOrder = 0x01,
CancelOrder = 0x02,
Bid = 0x04,
PostOnly = 0x08,
ImmediateOrCancel = 0x10,
DecrementTakeOnSelfTrade = 0x20,
}
#[derive(Copy, Clone, Debug)]
#[repr(packed)]
pub struct Request {
request_flags: u8,
owner_slot: u8,
fee_tier: u8,
self_trade_behavior: u8,
padding: [u8; 4],
max_coin_qty_or_cancel_id: u64,
native_pc_qty_locked: u64,
order_id: u128,
owner: [u64; 4],
client_order_id: u64,
}
unsafe impl Zeroable for Request {}
unsafe impl Pod for Request {}
#[derive(Debug)]
pub enum RequestView {
NewOrder {
side: Side,
order_type: OrderType,
owner_slot: u8,
fee_tier: FeeTier,
order_id: u128,
max_coin_qty: NonZeroU64,
native_pc_qty_locked: Option<NonZeroU64>,
owner: [u64; 4],
client_order_id: Option<NonZeroU64>,
self_trade_behavior: SelfTradeBehavior,
},
CancelOrder {
side: Side,
order_id: u128,
cancel_id: u64,
expected_owner_slot: u8,
expected_owner: [u64; 4],
client_order_id: Option<NonZeroU64>,
},
}
impl Request {
#[inline(always)]
pub fn new(view: RequestView) -> Self {
match view {
RequestView::NewOrder {
side,
order_type,
owner_slot,
fee_tier,
order_id,
owner,
max_coin_qty,
native_pc_qty_locked,
client_order_id,
self_trade_behavior,
} => {
let mut flags = BitFlags::from_flag(RequestFlag::NewOrder);
if side == Side::Bid {
flags.insert(RequestFlag::Bid);
}
match order_type {
OrderType::PostOnly => flags |= RequestFlag::PostOnly,
OrderType::ImmediateOrCancel => flags |= RequestFlag::ImmediateOrCancel,
OrderType::Limit => (),
};
Request {
request_flags: flags.bits(),
owner_slot,
fee_tier: fee_tier.into(),
self_trade_behavior: self_trade_behavior.into(),
padding: Zeroable::zeroed(),
order_id,
owner,
max_coin_qty_or_cancel_id: max_coin_qty.get(),
native_pc_qty_locked: native_pc_qty_locked.map_or(0, NonZeroU64::get),
client_order_id: client_order_id.map_or(0, NonZeroU64::get),
}
}
RequestView::CancelOrder {
side,
expected_owner_slot,
order_id,
expected_owner,
cancel_id,
client_order_id,
} => {
let mut flags = BitFlags::from_flag(RequestFlag::CancelOrder);
if side == Side::Bid {
flags.insert(RequestFlag::Bid);
}
Request {
request_flags: flags.bits(),
max_coin_qty_or_cancel_id: cancel_id,
order_id,
owner_slot: expected_owner_slot,
fee_tier: 0,
self_trade_behavior: 0,
owner: expected_owner,
native_pc_qty_locked: 0,
padding: Zeroable::zeroed(),
client_order_id: client_order_id.map_or(0, NonZeroU64::get),
}
}
}
}
#[inline(always)]
pub fn as_view(&self) -> DexResult<RequestView> {
let flags = BitFlags::from_bits(self.request_flags).unwrap();
let side = if flags.contains(RequestFlag::Bid) {
Side::Bid
} else {
Side::Ask
};
if flags.contains(RequestFlag::NewOrder) {
let allowed_flags = {
use RequestFlag::*;
NewOrder | Bid | PostOnly | ImmediateOrCancel
};
check_assert!(allowed_flags.contains(flags))?;
let post_only = flags.contains(RequestFlag::PostOnly);
let ioc = flags.contains(RequestFlag::ImmediateOrCancel);
let order_type = match (post_only, ioc) {
(true, false) => OrderType::PostOnly,
(false, true) => OrderType::ImmediateOrCancel,
(false, false) => OrderType::Limit,
(true, true) => unreachable!(),
};
let fee_tier = FeeTier::try_from_primitive(self.fee_tier).or(check_unreachable!())?;
let self_trade_behavior =
SelfTradeBehavior::try_from_primitive(self.self_trade_behavior)
.or(check_unreachable!())?;
Ok(RequestView::NewOrder {
side,
order_type,
owner_slot: self.owner_slot,
fee_tier,
self_trade_behavior,
order_id: self.order_id,
owner: self.owner,
max_coin_qty: NonZeroU64::new(self.max_coin_qty_or_cancel_id).unwrap(),
native_pc_qty_locked: NonZeroU64::new(self.native_pc_qty_locked),
client_order_id: NonZeroU64::new(self.client_order_id),
})
} else {
check_assert!(flags.contains(RequestFlag::CancelOrder))?;
let allowed_flags = {
use RequestFlag::*;
CancelOrder | Bid
};
check_assert!(allowed_flags.contains(flags))?;
Ok(RequestView::CancelOrder {
side,
cancel_id: self.max_coin_qty_or_cancel_id,
order_id: self.order_id,
expected_owner_slot: self.owner_slot,
expected_owner: self.owner,
client_order_id: NonZeroU64::new(self.client_order_id),
})
}
}
}
#[derive(Copy, Clone, Debug)]
#[repr(packed)]
pub struct EventQueueHeader {
account_flags: u64, // Initialized, EventQueue
head: u64,
count: u64,
seq_num: u64,
}
unsafe impl Zeroable for EventQueueHeader {}
unsafe impl Pod for EventQueueHeader {}
unsafe impl TriviallyTransmutable for EventQueueHeader {}
unsafe impl TriviallyTransmutable for RequestQueueHeader {}
impl QueueHeader for EventQueueHeader {
type Item = Event;
fn head(&self) -> u64 {
self.head
}
fn set_head(&mut self, value: u64) {
self.head = value;
}
fn count(&self) -> u64 {
self.count
}
fn set_count(&mut self, value: u64) {
self.count = value;
}
fn incr_event_id(&mut self) {
self.seq_num += 1;
}
fn decr_event_id(&mut self, n: u64) {
self.seq_num -= n;
}
}
pub type EventQueue<'a> = Queue<'a, EventQueueHeader>;
#[derive(Copy, Clone, BitFlags, Debug)]
#[repr(u8)]
enum EventFlag {
Fill = 0x1,
Out = 0x2,
Bid = 0x4,
Maker = 0x8,
ReleaseFunds = 0x10,
}
impl EventFlag {
#[inline]
fn from_side(side: Side) -> BitFlags<Self> {
match side {
Side::Bid => EventFlag::Bid.into(),
Side::Ask => BitFlags::empty(),
}
}
#[inline]
fn flags_to_side(flags: BitFlags<Self>) -> Side {
if flags.contains(EventFlag::Bid) {
Side::Bid
} else {
Side::Ask
}
}
}
#[derive(Copy, Clone, Debug)]
#[repr(packed)]
pub struct Event {
event_flags: u8,
owner_slot: u8,
fee_tier: u8,
_padding: [u8; 5],
native_qty_released: u64,
native_qty_paid: u64,
native_fee_or_rebate: u64,
order_id: u128,
pub owner: [u64; 4],
client_order_id: u64,
}
unsafe impl Zeroable for Event {}
unsafe impl Pod for Event {}
unsafe impl TriviallyTransmutable for Event {}
unsafe impl TriviallyTransmutable for Request {}
impl Event {
#[inline(always)]
pub fn new(view: EventView) -> Self {
match view {
EventView::Fill {
side,
maker,
native_qty_paid,
native_qty_received,
native_fee_or_rebate,
order_id,
owner,
owner_slot,
fee_tier,
client_order_id,
} => {
let maker_flag = if maker {
BitFlags::from_flag(EventFlag::Maker).bits()
} else {
0
};
let event_flags =
(EventFlag::from_side(side) | EventFlag::Fill).bits() | maker_flag;
Event {
event_flags,
owner_slot,
fee_tier: fee_tier.into(),
_padding: Zeroable::zeroed(),
native_qty_released: native_qty_received,
native_qty_paid,
native_fee_or_rebate,
order_id,
owner,
client_order_id: client_order_id.map_or(0, NonZeroU64::get),
}
}
EventView::Out {
side,
release_funds,
native_qty_unlocked,
native_qty_still_locked,
order_id,
owner,
owner_slot,
client_order_id,
} => {
let release_funds_flag = if release_funds {
BitFlags::from_flag(EventFlag::ReleaseFunds).bits()
} else {
0
};
let event_flags =
(EventFlag::from_side(side) | EventFlag::Out).bits() | release_funds_flag;
Event {
event_flags,
owner_slot,
fee_tier: 0,
_padding: Zeroable::zeroed(),
native_qty_released: native_qty_unlocked,
native_qty_paid: native_qty_still_locked,
native_fee_or_rebate: 0,
order_id,
owner,
client_order_id: client_order_id.map_or(0, NonZeroU64::get),
}
}
}
}
#[inline(always)]
pub fn as_view(&self) -> DexResult<EventView> {
let flags = BitFlags::from_bits(self.event_flags).unwrap();
let side = EventFlag::flags_to_side(flags);
let client_order_id = NonZeroU64::new(self.client_order_id);
if flags.contains(EventFlag::Fill) {
let allowed_flags = {
use EventFlag::*;
Fill | Bid | Maker
};
check_assert!(allowed_flags.contains(flags))?;
return Ok(EventView::Fill {
side,
maker: flags.contains(EventFlag::Maker),
native_qty_paid: self.native_qty_paid,
native_qty_received: self.native_qty_released,
native_fee_or_rebate: self.native_fee_or_rebate,
order_id: self.order_id,
owner: self.owner,
owner_slot: self.owner_slot,
fee_tier: self.fee_tier.try_into().or(check_unreachable!())?,
client_order_id,
});
}
let allowed_flags = {
use EventFlag::*;
Out | Bid | ReleaseFunds
};
check_assert!(allowed_flags.contains(flags))?;
Ok(EventView::Out {
side,
release_funds: flags.contains(EventFlag::ReleaseFunds),
native_qty_unlocked: self.native_qty_released,
native_qty_still_locked: self.native_qty_paid,
order_id: self.order_id,
owner: self.owner,
owner_slot: self.owner_slot,
client_order_id,
})
}
}
#[derive(Debug)]
pub enum EventView {
Fill {
side: Side,
maker: bool,
native_qty_paid: u64,
native_qty_received: u64,
native_fee_or_rebate: u64,
order_id: u128,
owner: [u64; 4],
owner_slot: u8,
fee_tier: FeeTier,
client_order_id: Option<NonZeroU64>,
},
Out {
side: Side,
release_funds: bool,
native_qty_unlocked: u64,
native_qty_still_locked: u64,
order_id: u128,
owner: [u64; 4],
owner_slot: u8,
client_order_id: Option<NonZeroU64>,
},
}
impl EventView {
fn side(&self) -> Side {
match self {
&EventView::Fill { side, .. } | &EventView::Out { side, .. } => side,
}
}
}
#[derive(Copy, Clone)]
#[repr(packed)]
struct OrderBookStateHeader {
account_flags: u64, // Initialized, (Bids or Asks)
}
unsafe impl Zeroable for OrderBookStateHeader {}
unsafe impl Pod for OrderBookStateHeader {}
pub enum State {}
fn gen_vault_signer_seeds<'a>(nonce: &'a u64, market: &'a Pubkey) -> [&'a [u8]; 2] {
[market.as_ref(), bytes_of(nonce)]
}
#[cfg(not(any(test, feature = "fuzz")))]
#[inline]
pub fn gen_vault_signer_key(
nonce: u64,
market: &Pubkey,
program_id: &Pubkey,
) -> Result<Pubkey, ProgramError> {
let seeds = gen_vault_signer_seeds(&nonce, market);
Ok(Pubkey::create_program_address(&seeds, program_id)?)
}
#[cfg(any(test, feature = "fuzz"))]
pub fn gen_vault_signer_key(
nonce: u64,
market: &Pubkey,
_program_id: &Pubkey,
) -> Result<Pubkey, ProgramError> {
gen_vault_signer_seeds(&nonce, market);
Ok(Pubkey::default())
}
#[cfg(not(any(test, feature = "fuzz")))]
fn invoke_spl_token(
instruction: &solana_program::instruction::Instruction,
account_infos: &[AccountInfo],
signers_seeds: &[&[&[u8]]],
) -> solana_program::entrypoint::ProgramResult {
solana_program::program::invoke_signed(instruction, account_infos, signers_seeds)
}
#[cfg(any(test, feature = "fuzz"))]
fn invoke_spl_token(
instruction: &solana_program::instruction::Instruction,
account_infos: &[AccountInfo],
_signers_seeds: &[&[&[u8]]],
) -> solana_program::entrypoint::ProgramResult {
assert_eq!(instruction.program_id, spl_token::ID);
let account_infos: Vec<AccountInfo> = instruction
.accounts
.iter()
.map(|meta| {
account_infos
.iter()
.find(|info| *info.key == meta.pubkey)
.unwrap()
.clone()
})
.collect();
spl_token::processor::Processor::process(
&instruction.program_id,
&account_infos,
&instruction.data,
)?;
Ok(())
}
#[cfg(feature = "program")]
fn send_from_vault<'a, 'b: 'a>(
native_amount: u64,
recipient: account_parser::TokenAccount<'a, 'b>,
vault: account_parser::TokenAccount<'a, 'b>,
spl_token_program: account_parser::SplTokenProgram<'a, 'b>,
vault_signer: account_parser::VaultSigner<'a, 'b>,
vault_signer_seeds: &[&[u8]],
) -> DexResult {
let deposit_instruction = spl_token::instruction::transfer(
&spl_token::ID,
vault.inner().key,
recipient.inner().key,
&vault_signer.inner().key,
&[],
native_amount,
)?;
let accounts: &[AccountInfo] = &[
vault.inner().clone(),
recipient.inner().clone(),
vault_signer.inner().clone(),
spl_token_program.inner().clone(),
];
invoke_spl_token(&deposit_instruction, &accounts[..], &[vault_signer_seeds])
.map_err(|_| DexErrorCode::TransferFailed)?;
Ok(())
}
pub(crate) mod account_parser {
use super::*;
macro_rules! declare_validated_account_wrapper {
($WrapperT:ident, $validate:expr $(, $a:ident : $t:ty)*) => {
#[derive(Copy, Clone)]
pub struct $WrapperT<'a, 'b: 'a>(&'a AccountInfo<'b>);
impl<'a, 'b: 'a> $WrapperT<'a, 'b> {
fn new(account: &'a AccountInfo<'b> $(,$a: $t)*) -> DexResult<Self> {
let validate_result: DexResult = $validate(account $(,$a)*);
validate_result?;
Ok($WrapperT(account))
}
#[inline(always)]
#[allow(unused)]
pub fn inner(self) -> &'a AccountInfo<'b> {
self.0
}
}
}
}
declare_validated_account_wrapper!(SplTokenProgram, |account: &AccountInfo| {
check_assert_eq!(*account.key, spl_token::ID)?;
Ok(())
});
declare_validated_account_wrapper!(TokenMint, |mint: &AccountInfo| {
check_assert_eq!(*mint.owner, spl_token::ID)?;
let data = mint.try_borrow_data()?;
check_assert_eq!(data.len(), spl_token::state::Mint::LEN)?;
let is_initialized = data[0x2d];
check_assert_eq!(is_initialized, 1u8)?;
Ok(())
});
declare_validated_account_wrapper!(TokenAccount, |account: &AccountInfo| {
check_assert_eq!(*account.owner, spl_token::ID)?;
let data = account.try_borrow_data()?;
check_assert_eq!(data.len(), spl_token::state::Account::LEN)?;
let is_initialized = data[0x6c];
check_assert_eq!(is_initialized, 1u8)?;
Ok(())
});
macro_rules! declare_validated_token_account_wrapper {
($WrapperT:ident, $validate:expr $(, $a:ident : $t:ty)*) => {
#[derive(Copy, Clone)]
pub struct $WrapperT<'a, 'b: 'a>(TokenAccount<'a, 'b>);
impl<'a, 'b: 'a> $WrapperT<'a, 'b> {
fn new(token_account: TokenAccount<'a, 'b> $(,$a: $t)*) -> DexResult<Self> {
let validate_result: DexResult = $validate(token_account $(,$a)*);
validate_result?;
Ok($WrapperT(token_account))
}
fn from_account(account: &'a AccountInfo<'b> $(,$a: $t)*) -> DexResult<Self> {
let token_account = TokenAccount::new(account)?;
Self::new(token_account $(,$a)*)
}
#[inline(always)]
pub fn token_account(self) -> TokenAccount<'a, 'b> {
self.0
}
#[inline(always)]
#[allow(unused)]
pub fn account(self) -> &'a AccountInfo<'b> {
self.0.inner()
}
}
}
}
declare_validated_account_wrapper!(RentSysvarAccount, |account: &AccountInfo| {
check_assert!(Rent::check_id(account.key))?;
Ok(())
});
declare_validated_account_wrapper!(SignerAccount, |account: &AccountInfo| {
check_assert!(account.is_signer)?;
Ok(())
});
declare_validated_account_wrapper!(SigningFeeSweeper, |account: &AccountInfo| {
check_assert!(account.is_signer)?;
check_assert_eq!(account.key, &fee_sweeper::ID)?;
Ok(())
});
declare_validated_account_wrapper!(SigningDisableAuthority, |account: &AccountInfo| {
check_assert!(account.is_signer)?;
check_assert_eq!(account.key, &disable_authority::ID)?;
Ok(())
});
declare_validated_token_account_wrapper!(
CoinVault,
|token_account: TokenAccount, market: &MarketState| {
market.check_coin_vault(token_account)
},
market: &MarketState
);
declare_validated_token_account_wrapper!(
PcVault,
|token_account: TokenAccount, market: &MarketState| {
market.check_pc_vault(token_account)
},
market: &MarketState
);
declare_validated_token_account_wrapper!(
CoinWallet,
|token_account: TokenAccount, market: &MarketState| {
market.check_coin_payer(token_account)
},
market: &MarketState
);
declare_validated_token_account_wrapper!(
PcWallet,
|token_account: TokenAccount, market: &MarketState| {
market.check_pc_payer(token_account)
},
market: &MarketState
);
declare_validated_account_wrapper!(
VaultSigner,
|account: &AccountInfo, market: &MarketState, program_id: &Pubkey| {
let vault_signer_key =
gen_vault_signer_key(market.vault_signer_nonce, &market.pubkey(), program_id)?;
Ok(check_assert_eq!(&vault_signer_key, account.key)?)
},
market: &MarketState,
program_id: &Pubkey
);
impl<'a, 'b: 'a> TokenAccount<'a, 'b> {
pub fn balance(self) -> DexResult<u64> {
let data = self.inner().try_borrow_data()?;
Ok(u64::from_le_bytes(*array_ref![data, 64, 8]))
}
}
#[derive(Copy, Clone)]
pub struct TokenAccountAndMint<'a, 'b: 'a> {
account: TokenAccount<'a, 'b>,
mint: TokenMint<'a, 'b>,
}
impl<'a, 'b: 'a> TokenAccountAndMint<'a, 'b> {
fn new(account: TokenAccount<'a, 'b>, mint: TokenMint<'a, 'b>) -> DexResult<Self> {
let account_data = account.0.try_borrow_data()?;
check_assert_eq!(mint.0.key.as_ref(), &account_data[..32])?;
Ok(TokenAccountAndMint { account, mint })
}
pub fn get_account(self) -> TokenAccount<'a, 'b> {
self.account
}
pub fn get_mint(self) -> TokenMint<'a, 'b> {
self.mint
}
}
pub struct InitializeMarketArgs<'a, 'b: 'a> {
pub program_id: &'a Pubkey,
pub instruction: &'a InitializeMarketInstruction,
serum_dex_accounts: &'a [AccountInfo<'b>; 5],
pub coin_vault_and_mint: TokenAccountAndMint<'a, 'b>,
pub pc_vault_and_mint: TokenAccountAndMint<'a, 'b>,
}
impl<'a, 'b: 'a> InitializeMarketArgs<'a, 'b> {
pub fn new(
program_id: &'a Pubkey,
instruction: &'a InitializeMarketInstruction,
accounts: &'a [AccountInfo<'b>],
) -> DexResult<Self> {
check_assert_eq!(accounts.len(), 10)?;
let accounts = array_ref![accounts, 0, 10];
let (unchecked_serum_dex_accounts, unchecked_vaults, unchecked_mints, unchecked_rent) =
array_refs![accounts, 5, 2, 2, 1];
{
let rent_sysvar = RentSysvarAccount::new(&unchecked_rent[0])?;
let rent = Rent::from_account_info(rent_sysvar.inner()).or(check_unreachable!())?;
let (_, must_be_rent_exempt, _) = array_refs![accounts, 0; ..; 1];
for account in must_be_rent_exempt {
let data_len = account.data_len();
let lamports = account.lamports();
check_assert!(rent.is_exempt(lamports, data_len))?;
}
}
let mut checked_vaults = [None, None];
for account in unchecked_serum_dex_accounts {
check_assert_eq!(account.owner, program_id)?;
let data = account.try_borrow_data()?;
check_assert_eq!(data.len() % 8, 4)?;
check_assert!(data.len() >= 20)?;
let (padding5, header, _, padding7) = array_refs![&data, 5, 8; .. ; 7];
check_assert_eq!(*padding5, [0u8; 5])?;
check_assert_eq!(*header, [0u8; 8])?;
check_assert_eq!(*padding7, [0u8; 7])?;
}
let serum_dex_accounts = unchecked_serum_dex_accounts;
let vault_owner_key_bytes = gen_vault_signer_key(
instruction.vault_signer_nonce,
serum_dex_accounts[0].key,
program_id,
)?
.to_bytes();
for i in 0..=1 {
let vault = TokenAccount::new(&unchecked_vaults[i])?;
let mint = TokenMint::new(&unchecked_mints[i])?;
// check that the vaults are owned by the market's withdrawal authority key
let vault_data = vault.0.try_borrow_data()?;
let vault_owner = array_ref![vault_data, 0x20, 0x20];
check_assert_eq!(vault_owner, &vault_owner_key_bytes)?;
// check that the vault has no delegate
let delegate_tag = array_ref![vault_data, 0x48, 0x4];
check_assert_eq!(*delegate_tag, [0u8; 4])?;
checked_vaults[i] = Some(TokenAccountAndMint::new(vault, mint)?);
}
let [coin_vault_and_mint, pc_vault_and_mint] = match checked_vaults {
[Some(cvm), Some(pvm)] => [cvm, pvm],
_ => check_unreachable!()?,
};
Ok(InitializeMarketArgs {
program_id,
instruction,
serum_dex_accounts,
coin_vault_and_mint,
pc_vault_and_mint,
})
}
pub fn get_market(&self) -> &'a AccountInfo<'b> {
&self.serum_dex_accounts[0]
}
pub fn get_req_q(&self) -> &'a AccountInfo<'b> {
&self.serum_dex_accounts[1]
}
pub fn get_event_q(&self) -> &'a AccountInfo<'b> {
&self.serum_dex_accounts[2]
}
pub fn get_bids(&self) -> &'a AccountInfo<'b> {
&self.serum_dex_accounts[3]
}
pub fn get_asks(&self) -> &'a AccountInfo<'b> {
&self.serum_dex_accounts[4]
}
}
pub struct SendTakeArgs<'a, 'b: 'a> {
pub instruction: &'a SendTakeInstruction,
pub signer: SignerAccount<'a, 'b>,
pub req_q: RequestQueue<'a>,
pub event_q: EventQueue<'a>,
pub order_book_state: OrderBookState<'a>,
pub coin_wallet: CoinWallet<'a, 'b>,
pub pc_wallet: PcWallet<'a, 'b>,
pub coin_vault: CoinVault<'a, 'b>,
pub pc_vault: PcVault<'a, 'b>,
pub spl_token_program: SplTokenProgram<'a, 'b>,
pub fee_tier: FeeTier,
}
impl<'a, 'b: 'a> SendTakeArgs<'a, 'b> {
pub fn with_parsed_args<T>(
program_id: &'a Pubkey,
instruction: &'a SendTakeInstruction,
accounts: &'a [AccountInfo<'b>],
f: impl FnOnce(SendTakeArgs) -> DexResult<T>,
) -> DexResult<T> {
const MIN_ACCOUNTS: usize = 11;
check_assert!(accounts.len() == MIN_ACCOUNTS || accounts.len() == MIN_ACCOUNTS + 1)?;
let (fixed_accounts, fee_discount_account): (
&'a [AccountInfo<'b>; MIN_ACCOUNTS],
&'a [AccountInfo<'b>],
) = array_refs![accounts, MIN_ACCOUNTS; .. ;];
let &[
ref market_acc,
ref req_q_acc,
ref event_q_acc,
ref bids_acc,
ref asks_acc,
ref coin_wallet_acc,
ref pc_wallet_acc,
ref signer_acc,
ref coin_vault_acc,
ref pc_vault_acc,
ref spl_token_program_acc,
]: &'a [AccountInfo<'b>; MIN_ACCOUNTS] = fixed_accounts;
let srm_or_msrm_account = match fee_discount_account {
&[] => None,
&[ref account] => Some(TokenAccount::new(account)?),
_ => check_unreachable!()?,
};
let mut market: RefMut<'a, MarketState> = MarketState::load(market_acc, program_id)?;
let signer = SignerAccount::new(signer_acc)?;
let fee_tier = market
.load_fee_tier(&signer.inner().key.to_aligned_bytes(), srm_or_msrm_account)
.or(check_unreachable!())?;
let req_q = market.load_request_queue_mut(req_q_acc)?;
let event_q = market.load_event_queue_mut(event_q_acc)?;
let coin_wallet = CoinWallet::from_account(coin_wallet_acc, &market)?;
let pc_wallet = PcWallet::from_account(pc_wallet_acc, &market)?;
let coin_vault = CoinVault::from_account(coin_vault_acc, &market)?;
let pc_vault = PcVault::from_account(pc_vault_acc, &market)?;
let spl_token_program = SplTokenProgram::new(spl_token_program_acc)?;
let mut bids = market.load_bids_mut(bids_acc).or(check_unreachable!())?;
let mut asks = market.load_asks_mut(asks_acc).or(check_unreachable!())?;
let order_book_state = OrderBookState {
bids: bids.deref_mut(),
asks: asks.deref_mut(),
market_state: market.deref_mut(),
};
let args = SendTakeArgs {
instruction,
signer,
req_q,
event_q,
fee_tier,
coin_wallet,
pc_wallet,
coin_vault,
pc_vault,
order_book_state,
spl_token_program,
};
f(args)
}
}
pub struct NewOrderV3Args<'a, 'b: 'a> {
pub instruction: &'a NewOrderInstructionV3,
pub open_orders: &'a mut OpenOrders,
pub open_orders_address: [u64; 4],
pub owner: SignerAccount<'a, 'b>,
pub req_q: RequestQueue<'a>,
pub event_q: EventQueue<'a>,
pub order_book_state: OrderBookState<'a>,
pub payer: TokenAccount<'a, 'b>,
pub coin_vault: CoinVault<'a, 'b>,
pub pc_vault: PcVault<'a, 'b>,
pub spl_token_program: SplTokenProgram<'a, 'b>,
pub fee_tier: FeeTier,
}
impl<'a, 'b: 'a> NewOrderV3Args<'a, 'b> {
pub fn with_parsed_args<T>(
program_id: &'a Pubkey,
instruction: &'a NewOrderInstructionV3,
accounts: &'a [AccountInfo<'b>],
f: impl FnOnce(NewOrderV3Args) -> DexResult<T>,
) -> DexResult<T> {
const MIN_ACCOUNTS: usize = 12;
check_assert!(accounts.len() == MIN_ACCOUNTS || accounts.len() == MIN_ACCOUNTS + 1)?;
let (fixed_accounts, fee_discount_account): (
&'a [AccountInfo<'b>; MIN_ACCOUNTS],
&'a [AccountInfo<'b>],
) = array_refs![accounts, MIN_ACCOUNTS; .. ;];
let &[
ref market_acc,
ref open_orders_acc,
ref req_q_acc,
ref event_q_acc,
ref bids_acc,
ref asks_acc,
ref payer_acc,
ref owner_acc,
ref coin_vault_acc,
ref pc_vault_acc,
ref spl_token_program_acc,
ref rent_sysvar_acc,
]: &'a [AccountInfo<'b>; MIN_ACCOUNTS] = fixed_accounts;
let srm_or_msrm_account = match fee_discount_account {
&[] => None,
&[ref account] => Some(TokenAccount::new(account)?),
_ => check_unreachable!()?,
};
let mut market: RefMut<'a, MarketState> = MarketState::load(market_acc, program_id)?;
let rent = {
let rent_sysvar = RentSysvarAccount::new(rent_sysvar_acc)?;
Rent::from_account_info(rent_sysvar.inner()).or(check_unreachable!())?
};
let owner = SignerAccount::new(owner_acc)?;
let fee_tier =
market.load_fee_tier(&owner.inner().key.to_aligned_bytes(), srm_or_msrm_account)?;
let mut open_orders = market.load_orders_mut(
open_orders_acc,
Some(owner.inner()),
program_id,
Some(rent),
)?;
let open_orders_address = open_orders_acc.key.to_aligned_bytes();
let req_q = market.load_request_queue_mut(req_q_acc)?;
let event_q = market.load_event_queue_mut(event_q_acc)?;
let payer = TokenAccount::new(payer_acc)?;
match instruction.side {
Side::Bid => market.check_pc_payer(payer).or(check_unreachable!())?,
Side::Ask => market.check_coin_payer(payer).or(check_unreachable!())?,
};
let coin_vault = CoinVault::from_account(coin_vault_acc, &market)?;
let pc_vault = PcVault::from_account(pc_vault_acc, &market)?;
market.check_enabled()?;
let spl_token_program = SplTokenProgram::new(spl_token_program_acc)?;
let mut bids = market.load_bids_mut(bids_acc).or(check_unreachable!())?;
let mut asks = market.load_asks_mut(asks_acc).or(check_unreachable!())?;
let order_book_state = OrderBookState {
bids: bids.deref_mut(),
asks: asks.deref_mut(),
market_state: market.deref_mut(),
};
let args = NewOrderV3Args {
instruction,
order_book_state,
open_orders: open_orders.deref_mut(),
open_orders_address,
owner,
req_q,
event_q,
payer,
coin_vault,
pc_vault,
spl_token_program,
fee_tier,
};
f(args)
}
}
pub struct ConsumeEventsArgs<'a, 'b: 'a> {
pub limit: u16,
pub program_id: &'a Pubkey,
pub open_orders_accounts: &'a [AccountInfo<'b>],
pub market: &'a mut MarketState,
pub event_q: EventQueue<'a>,
}
impl<'a, 'b: 'a> ConsumeEventsArgs<'a, 'b> {
pub fn with_parsed_args<T>(
program_id: &'a Pubkey,
accounts: &'a [AccountInfo<'b>],
limit: u16,
f: impl FnOnce(ConsumeEventsArgs) -> DexResult<T>,
) -> DexResult<T> {
check_assert!(accounts.len() >= 5)?;
#[rustfmt::skip]
let (
&[],
open_orders_accounts,
&[ref market_acc],
&[ref event_q_acc],
_unused
) = array_refs![accounts, 0; .. ; 1, 1, 2];
let mut market = MarketState::load(market_acc, program_id)?;
let event_q = market.load_event_queue_mut(event_q_acc)?;
let args = ConsumeEventsArgs {
limit,
program_id,
open_orders_accounts,
market: market.deref_mut(),
event_q,
};
f(args)
}
}
pub struct CancelOrderV2Args<'a, 'b: 'a> {
pub instruction: &'a CancelOrderInstructionV2,
pub open_orders_address: [u64; 4],
pub open_orders: &'a mut OpenOrders,
pub open_orders_signer: SignerAccount<'a, 'b>,
pub order_book_state: OrderBookState<'a>,
pub event_q: EventQueue<'a>,
}
impl<'a, 'b: 'a> CancelOrderV2Args<'a, 'b> {
pub fn with_parsed_args<T>(
program_id: &'a Pubkey,
accounts: &'a [AccountInfo<'b>],
instruction: &'a CancelOrderInstructionV2,
f: impl FnOnce(CancelOrderV2Args) -> DexResult<T>,
) -> DexResult<T> {
check_assert!(accounts.len() >= 6)?;
#[rustfmt::skip]
let &[
ref market_acc,
ref bids_acc,
ref asks_acc,
ref open_orders_acc,
ref open_orders_signer_acc,
ref event_q_acc,
] = array_ref![accounts, 0, 6];
let mut market = MarketState::load(market_acc, program_id).or(check_unreachable!())?;
let open_orders_signer = SignerAccount::new(open_orders_signer_acc)?;
let mut open_orders = market.load_orders_mut(
open_orders_acc,
Some(open_orders_signer.inner()),
program_id,
None,
)?;
let open_orders_address = open_orders_acc.key.to_aligned_bytes();
let mut bids = market.load_bids_mut(bids_acc).or(check_unreachable!())?;
let mut asks = market.load_asks_mut(asks_acc).or(check_unreachable!())?;
let event_q = market.load_event_queue_mut(event_q_acc)?;
let order_book_state = OrderBookState {
bids: bids.deref_mut(),
asks: asks.deref_mut(),
market_state: market.deref_mut(),
};
let args = CancelOrderV2Args {
instruction,
open_orders_address,
open_orders: open_orders.deref_mut(),
open_orders_signer,
order_book_state,
event_q,
};
f(args)
}
}
pub struct CancelOrderByClientIdV2Args<'a, 'b: 'a> {
pub client_order_id: NonZeroU64,
pub open_orders_address: [u64; 4],
pub open_orders: &'a mut OpenOrders,
pub open_orders_signer: SignerAccount<'a, 'b>,
pub order_book_state: OrderBookState<'a>,
pub event_q: EventQueue<'a>,
}
impl<'a, 'b: 'a> CancelOrderByClientIdV2Args<'a, 'b> {
pub fn with_parsed_args<T>(
program_id: &'a Pubkey,
accounts: &'a [AccountInfo<'b>],
client_order_id: u64,
f: impl FnOnce(CancelOrderByClientIdV2Args) -> DexResult<T>,
) -> DexResult<T> {
check_assert!(accounts.len() >= 6)?;
#[rustfmt::skip]
let &[
ref market_acc,
ref bids_acc,
ref asks_acc,
ref open_orders_acc,
ref open_orders_signer_acc,
ref event_q_acc,
] = array_ref![accounts, 0, 6];
let client_order_id = NonZeroU64::new(client_order_id).ok_or(assertion_error!())?;
let mut market = MarketState::load(market_acc, program_id).or(check_unreachable!())?;
let open_orders_signer = SignerAccount::new(open_orders_signer_acc)?;
let mut open_orders = market.load_orders_mut(
open_orders_acc,
Some(open_orders_signer.inner()),
program_id,
None,
)?;
let open_orders_address = open_orders_acc.key.to_aligned_bytes();
let mut bids = market.load_bids_mut(bids_acc).or(check_unreachable!())?;
let mut asks = market.load_asks_mut(asks_acc).or(check_unreachable!())?;
let event_q = market.load_event_queue_mut(event_q_acc)?;
let order_book_state = OrderBookState {
bids: bids.deref_mut(),
asks: asks.deref_mut(),
market_state: market.deref_mut(),
};
let args = CancelOrderByClientIdV2Args {
client_order_id,
open_orders_address,
open_orders: open_orders.deref_mut(),
open_orders_signer,
order_book_state,
event_q,
};
f(args)
}
}
pub struct SettleFundsArgs<'a, 'b: 'a> {
pub market: &'a mut MarketState,
pub open_orders: &'a mut OpenOrders,
pub coin_vault: CoinVault<'a, 'b>,
pub pc_vault: PcVault<'a, 'b>,
pub coin_wallet: CoinWallet<'a, 'b>,
pub pc_wallet: PcWallet<'a, 'b>,
pub vault_signer: VaultSigner<'a, 'b>,
pub spl_token_program: SplTokenProgram<'a, 'b>,
pub referrer: Option<PcWallet<'a, 'b>>,
}
impl<'a, 'b: 'a> SettleFundsArgs<'a, 'b> {
pub fn with_parsed_args<T>(
program_id: &'a Pubkey,
accounts: &'a [AccountInfo<'b>],
f: impl FnOnce(SettleFundsArgs) -> DexResult<T>,
) -> DexResult<T> {
check_assert!(accounts.len() == 9 || accounts.len() == 10)?;
#[rustfmt::skip]
let (&[
ref market_acc,
ref open_orders_acc,
ref owner_acc,
ref coin_vault_acc,
ref pc_vault_acc,
ref coin_wallet_acc,
ref pc_wallet_acc,
ref vault_signer_acc,
ref spl_token_program_acc,
], remaining_accounts) = array_refs![accounts, 9; ..;];
let spl_token_program = SplTokenProgram::new(spl_token_program_acc)?;
let mut market = MarketState::load(market_acc, program_id)?;
let owner = SignerAccount::new(owner_acc).or(check_unreachable!())?;
let coin_vault =
CoinVault::from_account(coin_vault_acc, &market).or(check_unreachable!())?;
let pc_vault = PcVault::from_account(pc_vault_acc, &market).or(check_unreachable!())?;
let coin_wallet =
CoinWallet::from_account(coin_wallet_acc, &market).or(check_unreachable!())?;
let pc_wallet =
PcWallet::from_account(pc_wallet_acc, &market).or(check_unreachable!())?;
let referrer = match remaining_accounts {
&[] => None,
&[ref referrer_acc] => {
Some(PcWallet::from_account(referrer_acc, &market).or(check_unreachable!())?)
}
_ => check_unreachable!()?,
};
let vault_signer = VaultSigner::new(vault_signer_acc, &market, program_id)?;
let mut open_orders =
market.load_orders_mut(open_orders_acc, Some(owner.inner()), program_id, None)?;
let args = SettleFundsArgs {
market: market.deref_mut(),
open_orders: open_orders.deref_mut(),
coin_vault,
pc_vault,
coin_wallet,
pc_wallet,
vault_signer,
spl_token_program,
referrer,
};
f(args)
}
}
pub struct DisableMarketArgs<'a, 'b: 'a> {
pub market: &'a mut MarketState,
pub authorization: SigningDisableAuthority<'a, 'b>,
}
impl<'a, 'b: 'a> DisableMarketArgs<'a, 'b> {
pub fn with_parsed_args<T>(
program_id: &'a Pubkey,
accounts: &'a [AccountInfo<'b>],
f: impl FnOnce(DisableMarketArgs) -> DexResult<T>,
) -> DexResult<T> {
check_assert_eq!(accounts.len(), 2)?;
let &[ref market_acc, ref signer_acc] = array_ref![accounts, 0, 2];
let mut market = MarketState::load(market_acc, program_id)?;
let authorization = SigningDisableAuthority::new(signer_acc)?;
let args = DisableMarketArgs {
market: market.deref_mut(),
authorization,
};
f(args)
}
}
pub struct SweepFeesArgs<'a, 'b: 'a> {
pub market: &'a mut MarketState,
pub pc_vault: PcVault<'a, 'b>,
pub fee_receiver: PcWallet<'a, 'b>,
pub vault_signer: VaultSigner<'a, 'b>,
pub spl_token_program: SplTokenProgram<'a, 'b>,
pub authorization: SigningFeeSweeper<'a, 'b>,
}
impl<'a, 'b: 'a> SweepFeesArgs<'a, 'b> {
pub fn with_parsed_args<T>(
program_id: &'a Pubkey,
accounts: &'a [AccountInfo<'b>],
f: impl FnOnce(SweepFeesArgs) -> DexResult<T>,
) -> DexResult<T> {
check_assert_eq!(accounts.len(), 6)?;
#[rustfmt::skip]
let &[
ref market_acc,
ref pc_vault_acc,
ref sweep_authority_acc,
ref pc_wallet_acc,
ref vault_signer_acc,
ref spl_token_program
] = array_ref![accounts, 0, 6];
let mut market = MarketState::load(market_acc, program_id)?;
let pc_vault = PcVault::from_account(pc_vault_acc, &market)?;
let fee_receiver = PcWallet::from_account(pc_wallet_acc, &market)?;
let vault_signer = VaultSigner::new(vault_signer_acc, &market, program_id)?;
let spl_token_program = SplTokenProgram::new(spl_token_program)?;
let authorization = SigningFeeSweeper::new(sweep_authority_acc)?;
let args = SweepFeesArgs {
market: market.deref_mut(),
pc_vault,
fee_receiver,
vault_signer,
spl_token_program,
authorization,
};
f(args)
}
}
pub struct CloseOpenOrdersArgs<'a, 'b: 'a> {
pub open_orders: &'a mut OpenOrders,
pub open_orders_acc: &'a AccountInfo<'b>,
pub dest_acc: &'a AccountInfo<'b>,
}
impl<'a, 'b: 'a> CloseOpenOrdersArgs<'a, 'b> {
pub fn with_parsed_args<T>(
program_id: &'a Pubkey,
accounts: &'a [AccountInfo<'b>],
f: impl FnOnce(CloseOpenOrdersArgs) -> DexResult<T>,
) -> DexResult<T> {
// Parse accounts.
check_assert_eq!(accounts.len(), 4)?;
#[rustfmt::skip]
let &[
ref open_orders_acc,
ref owner_acc,
ref dest_acc,
ref market_acc,
] = array_ref![accounts, 0, 4];
// Validate the accounts given are valid.
let owner = SignerAccount::new(owner_acc)?;
let market: RefMut<'a, MarketState> = MarketState::load(market_acc, program_id)?;
let mut open_orders =
market.load_orders_mut(open_orders_acc, Some(owner.inner()), program_id, None)?;
// Only accounts with no funds associated with them can be closed.
if open_orders.free_slot_bits != std::u128::MAX {
return Err(DexErrorCode::TooManyOpenOrders.into());
}
if open_orders.native_coin_total != 0 {
solana_program::msg!(
"Base currency total must be zero to close the open orders account"
);
return Err(DexErrorCode::TooManyOpenOrders.into());
}
if open_orders.native_pc_total != 0 {
solana_program::msg!(
"Quote currency total must be zero to close the open orders account"
);
return Err(DexErrorCode::TooManyOpenOrders.into());
}
// Invoke processor.
f(CloseOpenOrdersArgs {
open_orders: open_orders.deref_mut(),
open_orders_acc,
dest_acc,
})
}
}
pub struct InitOpenOrdersArgs;
impl InitOpenOrdersArgs {
pub fn with_parsed_args<T>(
program_id: &Pubkey,
accounts: &[AccountInfo],
f: impl FnOnce(InitOpenOrdersArgs) -> DexResult<T>,
) -> DexResult<T> {
// Parse accounts.
check_assert_eq!(accounts.len(), 4)?;
#[rustfmt::skip]
let &[
ref open_orders_acc,
ref owner_acc,
ref market_acc,
ref rent_acc,
] = array_ref![accounts, 0, 4];
// Validate the accounts given are valid.
let rent = {
let rent_sysvar = RentSysvarAccount::new(rent_acc)?;
Rent::from_account_info(rent_sysvar.inner()).or(check_unreachable!())?
};
let owner = SignerAccount::new(owner_acc)?;
let market = MarketState::load(market_acc, program_id)?;
// Perform open orders initialization.
let _open_orders = market.load_orders_mut(
open_orders_acc,
Some(owner.inner()),
program_id,
Some(rent),
)?;
// Invoke processor.
f(InitOpenOrdersArgs)
}
}
}
#[inline]
fn remove_slop<T: Pod>(bytes: &[u8]) -> &[T] {
let slop = bytes.len() % size_of::<T>();
let new_len = bytes.len() - slop;
cast_slice(&bytes[..new_len])
}
#[inline]
fn remove_slop_mut<T: Pod>(bytes: &mut [u8]) -> &mut [T] {
let slop = bytes.len() % size_of::<T>();
let new_len = bytes.len() - slop;
cast_slice_mut(&mut bytes[..new_len])
}
#[cfg_attr(not(feature = "program"), allow(unused))]
impl State {
#[cfg(feature = "program")]
pub fn process(program_id: &Pubkey, accounts: &[AccountInfo], input: &[u8]) -> DexResult {
let instruction = MarketInstruction::unpack(input).ok_or(ProgramError::InvalidArgument)?;
match instruction {
MarketInstruction::InitializeMarket(ref inner) => Self::process_initialize_market(
account_parser::InitializeMarketArgs::new(program_id, inner, accounts)?,
)?,
MarketInstruction::NewOrder(_inner) => {
unimplemented!()
}
MarketInstruction::NewOrderV2(_inner) => {
unimplemented!()
}
MarketInstruction::NewOrderV3(ref inner) => {
account_parser::NewOrderV3Args::with_parsed_args(
program_id,
inner,
accounts,
Self::process_new_order_v3,
)?
}
MarketInstruction::MatchOrders(_limit) => {}
MarketInstruction::ConsumeEvents(limit) => {
account_parser::ConsumeEventsArgs::with_parsed_args(
program_id,
accounts,
limit,
Self::process_consume_events,
)?
}
MarketInstruction::CancelOrder(_inner) => {
unimplemented!()
}
MarketInstruction::CancelOrderV2(ref inner) => {
account_parser::CancelOrderV2Args::with_parsed_args(
program_id,
accounts,
inner,
Self::process_cancel_order_v2,
)?
}
MarketInstruction::SettleFunds => account_parser::SettleFundsArgs::with_parsed_args(
program_id,
accounts,
Self::process_settle_funds,
)?,
MarketInstruction::CancelOrderByClientId(_client_id) => {
unimplemented!()
}
MarketInstruction::CancelOrderByClientIdV2(client_id) => {
account_parser::CancelOrderByClientIdV2Args::with_parsed_args(
program_id,
accounts,
client_id,
Self::process_cancel_order_by_client_id_v2,
)?
}
MarketInstruction::DisableMarket => {
account_parser::DisableMarketArgs::with_parsed_args(
program_id,
accounts,
Self::process_disable_market,
)?
}
MarketInstruction::SweepFees => account_parser::SweepFeesArgs::with_parsed_args(
program_id,
accounts,
Self::process_sweep_fees,
)?,
MarketInstruction::SendTake(ref inner) => {
account_parser::SendTakeArgs::with_parsed_args(
program_id,
inner,
accounts,
Self::process_send_take,
)?
}
MarketInstruction::CloseOpenOrders => {
account_parser::CloseOpenOrdersArgs::with_parsed_args(
program_id,
accounts,
Self::process_close_open_orders,
)?
}
MarketInstruction::InitOpenOrders => {
account_parser::InitOpenOrdersArgs::with_parsed_args(
program_id,
accounts,
Self::process_init_open_orders,
)?
}
};
Ok(())
}
#[cfg(feature = "program")]
fn process_send_take(_args: account_parser::SendTakeArgs) -> DexResult {
unimplemented!()
}
fn process_init_open_orders(_args: account_parser::InitOpenOrdersArgs) -> DexResult {
Ok(())
}
fn process_close_open_orders(args: account_parser::CloseOpenOrdersArgs) -> DexResult {
let account_parser::CloseOpenOrdersArgs {
open_orders,
open_orders_acc,
dest_acc,
} = args;
// Transfer all lamports to the destination.
let dest_starting_lamports = dest_acc.lamports();
**dest_acc.lamports.borrow_mut() = dest_starting_lamports
.checked_add(open_orders_acc.lamports())
.unwrap();
**open_orders_acc.lamports.borrow_mut() = 0;
// Mark the account as closed to prevent it from being used before
// garbage collection.
open_orders.account_flags = AccountFlag::Closed as u64;
Ok(())
}
#[cfg(feature = "program")]
fn process_settle_funds(args: account_parser::SettleFundsArgs) -> DexResult {
let account_parser::SettleFundsArgs {
market,
mut open_orders,
coin_vault,
pc_vault,
coin_wallet,
pc_wallet,
vault_signer,
spl_token_program,
referrer,
} = args;
let native_coin_amount = open_orders.native_coin_free;
let mut native_pc_amount = open_orders.native_pc_free;
market.coin_deposits_total -= native_coin_amount;
market.pc_deposits_total -= native_pc_amount;
open_orders.native_coin_free = 0;
open_orders.native_pc_free = 0;
open_orders.native_coin_total = open_orders
.native_coin_total
.checked_sub(native_coin_amount)
.unwrap();
open_orders.native_pc_total = open_orders
.native_pc_total
.checked_sub(native_pc_amount)
.unwrap();
let nonce = market.vault_signer_nonce;
let market_pubkey = market.pubkey();
let vault_signer_seeds = gen_vault_signer_seeds(&nonce, &market_pubkey);
match referrer {
Some(referrer_pc_wallet) if open_orders.referrer_rebates_accrued > 0 => {
// If referrer is same as user, send_from_vault once
if referrer_pc_wallet.account().key == pc_wallet.account().key {
native_pc_amount = native_pc_amount
.checked_add(open_orders.referrer_rebates_accrued)
.unwrap();
} else {
send_from_vault(
open_orders.referrer_rebates_accrued,
referrer_pc_wallet.token_account(),
pc_vault.token_account(),
spl_token_program,
vault_signer,
&vault_signer_seeds,
)?;
};
}
_ => {
market.pc_fees_accrued += open_orders.referrer_rebates_accrued;
}
};
market.referrer_rebates_accrued -= open_orders.referrer_rebates_accrued;
open_orders.referrer_rebates_accrued = 0;
let token_infos: [(
u64,
account_parser::TokenAccount,
account_parser::TokenAccount,
); 2] = [
(
native_coin_amount,
coin_wallet.token_account(),
coin_vault.token_account(),
),
(
native_pc_amount,
pc_wallet.token_account(),
pc_vault.token_account(),
),
];
for &(token_amount, wallet_account, vault) in token_infos.iter() {
send_from_vault(
token_amount,
wallet_account,
vault,
spl_token_program,
vault_signer,
&vault_signer_seeds,
)?;
}
Ok(())
}
fn process_cancel_order_by_client_id_v2(
args: account_parser::CancelOrderByClientIdV2Args,
) -> DexResult {
let account_parser::CancelOrderByClientIdV2Args {
client_order_id,
open_orders_address,
open_orders,
open_orders_signer: _,
mut order_book_state,
mut event_q,
} = args;
let (_, order_id, side) = open_orders
.orders_with_client_ids()
.find(|entry| client_order_id == entry.0)
.ok_or(DexErrorCode::ClientIdNotFound)?;
order_book_state.cancel_order_v2(
side,
open_orders_address,
open_orders,
order_id,
&mut event_q,
)
}
fn process_cancel_order_v2(args: account_parser::CancelOrderV2Args) -> DexResult {
let account_parser::CancelOrderV2Args {
instruction: &CancelOrderInstructionV2 { side, order_id },
open_orders_address,
open_orders,
open_orders_signer: _,
mut order_book_state,
mut event_q,
} = args;
order_book_state.cancel_order_v2(
side,
open_orders_address,
open_orders,
order_id,
&mut event_q,
)
}
fn process_consume_events(args: account_parser::ConsumeEventsArgs) -> DexResult {
let account_parser::ConsumeEventsArgs {
limit,
program_id,
open_orders_accounts,
market,
mut event_q,
} = args;
for _i in 0u16..limit {
let event = match event_q.peek_front() {
None => break,
Some(e) => e,
};
let view = event.as_view()?;
let owner: [u64; 4] = event.owner;
let owner_index: Result<usize, usize> = open_orders_accounts
.binary_search_by_key(&owner, |account_info| account_info.key.to_aligned_bytes());
let mut open_orders: RefMut<OpenOrders> = match owner_index {
Err(_) => break,
Ok(i) => {
market.load_orders_mut(&open_orders_accounts[i], None, program_id, None)?
}
};
check_assert!(event.owner_slot < 128)?;
check_assert_eq!(&open_orders.slot_side(event.owner_slot), &Some(view.side()))?;
check_assert_eq!(
open_orders.orders[event.owner_slot as usize],
event.order_id
)?;
match event.as_view()? {
EventView::Fill {
side,
maker,
native_qty_paid,
native_qty_received,
native_fee_or_rebate,
fee_tier: _,
order_id: _,
owner: _,
owner_slot,
client_order_id,
} => {
match side {
Side::Bid if maker => {
open_orders.native_pc_total -= native_qty_paid;
open_orders.native_coin_total += native_qty_received;
open_orders.native_coin_free += native_qty_received;
open_orders.native_pc_free += native_fee_or_rebate;
}
Side::Ask if maker => {
open_orders.native_coin_total -= native_qty_paid;
open_orders.native_pc_total += native_qty_received;
open_orders.native_pc_free += native_qty_received;
}
_ => (),
};
if let Some(client_id) = client_order_id {
debug_assert_eq!(
client_id.get(),
identity(open_orders.client_order_ids[owner_slot as usize])
);
}
}
EventView::Out {
side,
release_funds,
native_qty_unlocked,
native_qty_still_locked,
order_id: _,
owner: _,
owner_slot,
client_order_id,
} => {
let fully_out = native_qty_still_locked == 0;
match side {
Side::Bid => {
if release_funds {
open_orders.native_pc_free += native_qty_unlocked;
}
check_assert!(
open_orders.native_pc_free <= open_orders.native_pc_total
)?;
}
Side::Ask => {
if release_funds {
open_orders.native_coin_free += native_qty_unlocked;
}
check_assert!(
open_orders.native_coin_free <= open_orders.native_coin_total
)?;
}
};
if let Some(client_id) = client_order_id {
debug_assert_eq!(
client_id.get(),
identity(open_orders.client_order_ids[owner_slot as usize])
);
}
if fully_out {
open_orders.remove_order(owner_slot)?;
}
}
};
event_q
.pop_front()
.map_err(|()| DexErrorCode::ConsumeEventsQueueFailure)?;
}
Ok(())
}
#[cfg(feature = "program")]
fn process_new_order_v3(args: account_parser::NewOrderV3Args) -> DexResult {
let account_parser::NewOrderV3Args {
instruction,
mut order_book_state,
open_orders,
open_orders_address,
mut req_q,
mut event_q,
payer,
owner,
coin_vault,
pc_vault,
spl_token_program,
fee_tier,
} = args;
check_assert_eq!(req_q.header.count(), 0)?;
let deposit_amount;
let deposit_vault;
let native_pc_qty_locked;
match instruction.side {
Side::Bid => {
let lock_qty_native = instruction.max_native_pc_qty_including_fees;
native_pc_qty_locked = Some(lock_qty_native);
let free_qty_to_lock = lock_qty_native.get().min(open_orders.native_pc_free);
deposit_amount = lock_qty_native.get() - free_qty_to_lock;
deposit_vault = pc_vault.token_account();
if payer.balance()? < deposit_amount {
return Err(DexErrorCode::InsufficientFunds.into());
}
open_orders.lock_free_pc(free_qty_to_lock);
open_orders.credit_locked_pc(deposit_amount);
order_book_state.market_state.pc_deposits_total = order_book_state
.market_state
.pc_deposits_total
.checked_add(deposit_amount)
.unwrap();
}
Side::Ask => {
native_pc_qty_locked = None;
let lock_qty_native = instruction
.max_coin_qty
.get()
.checked_mul(order_book_state.market_state.coin_lot_size)
.ok_or(DexErrorCode::InsufficientFunds)?;
let free_qty_to_lock = lock_qty_native.min(open_orders.native_coin_free);
deposit_amount = lock_qty_native - free_qty_to_lock;
deposit_vault = coin_vault.token_account();
if payer.balance()? < deposit_amount {
return Err(DexErrorCode::InsufficientFunds.into());
}
open_orders.lock_free_coin(free_qty_to_lock);
open_orders.credit_locked_coin(deposit_amount);
order_book_state.market_state.coin_deposits_total = order_book_state
.market_state
.coin_deposits_total
.checked_add(deposit_amount)
.unwrap();
}
};
if deposit_amount != 0 {
let balance_before = deposit_vault.balance()?;
let deposit_instruction = spl_token::instruction::transfer(
&spl_token::ID,
payer.inner().key,
deposit_vault.inner().key,
owner.inner().key,
&[],
deposit_amount,
)
.unwrap();
invoke_spl_token(
&deposit_instruction,
&[
payer.inner().clone(),
deposit_vault.inner().clone(),
owner.inner().clone(),
spl_token_program.inner().clone(),
],
&[],
)
.map_err(|err| match err {
ProgramError::Custom(i) => match TokenError::from_u32(i) {
Some(TokenError::InsufficientFunds) => DexErrorCode::InsufficientFunds,
_ => DexErrorCode::TransferFailed,
},
_ => DexErrorCode::TransferFailed,
})?;
let balance_after = deposit_vault.balance()?;
let balance_change = balance_after.checked_sub(balance_before);
check_assert_eq!(Some(deposit_amount), balance_change)?;
}
let order_id = req_q.gen_order_id(instruction.limit_price.get(), instruction.side);
let owner_slot = open_orders.add_order(order_id, instruction.side)?;
open_orders.client_order_ids[owner_slot as usize] = instruction.client_order_id;
let mut proceeds = RequestProceeds::zero();
let request = RequestView::NewOrder {
side: instruction.side,
order_type: instruction.order_type,
order_id,
fee_tier,
self_trade_behavior: instruction.self_trade_behavior,
owner: open_orders_address,
owner_slot,
max_coin_qty: instruction.max_coin_qty,
native_pc_qty_locked,
client_order_id: NonZeroU64::new(instruction.client_order_id),
};
let mut limit = instruction.limit;
let unfilled_portion = order_book_state.process_orderbook_request(
&request,
open_orders,
&mut event_q,
&mut proceeds,
&mut limit,
)?;
check_assert!(unfilled_portion.is_none())?;
{
let coin_lot_size = order_book_state.market_state.coin_lot_size;
let RequestProceeds {
coin_unlocked,
coin_credit,
native_pc_unlocked,
native_pc_credit,
coin_debit,
native_pc_debit,
} = proceeds;
let native_coin_unlocked = coin_unlocked.checked_mul(coin_lot_size).unwrap();
let native_coin_credit = coin_credit.checked_mul(coin_lot_size).unwrap();
let native_coin_debit = coin_debit.checked_mul(coin_lot_size).unwrap();
open_orders.credit_locked_coin(native_coin_credit);
open_orders.unlock_coin(native_coin_credit);
open_orders.unlock_coin(native_coin_unlocked);
open_orders.credit_locked_pc(native_pc_credit);
open_orders.unlock_pc(native_pc_credit);
open_orders.unlock_pc(native_pc_unlocked);
open_orders.native_coin_total = open_orders
.native_coin_total
.checked_sub(native_coin_debit)
.unwrap();
open_orders.native_pc_total = open_orders
.native_pc_total
.checked_sub(native_pc_debit)
.unwrap();
check_assert!(open_orders.native_coin_free <= open_orders.native_coin_total)?;
check_assert!(open_orders.native_pc_free <= open_orders.native_pc_total)?;
}
Ok(())
}
fn process_disable_market(args: account_parser::DisableMarketArgs) -> DexResult {
let account_parser::DisableMarketArgs {
market,
authorization: _,
} = args;
market.account_flags = market.account_flags | (AccountFlag::Disabled as u64);
Ok(())
}
#[cfg(feature = "program")]
fn process_sweep_fees(args: account_parser::SweepFeesArgs) -> DexResult {
let account_parser::SweepFeesArgs {
mut market,
pc_vault,
fee_receiver,
vault_signer,
spl_token_program,
authorization: _,
} = args;
let token_amount = market.pc_fees_accrued;
market.pc_fees_accrued = 0;
let nonce = market.vault_signer_nonce;
let market_pubkey = market.pubkey();
let vault_signer_seeds = gen_vault_signer_seeds(&nonce, &market_pubkey);
send_from_vault(
token_amount,
fee_receiver.token_account(),
pc_vault.token_account(),
spl_token_program,
vault_signer,
&vault_signer_seeds,
)
}
fn process_initialize_market(args: account_parser::InitializeMarketArgs) -> DexResult {
let &InitializeMarketInstruction {
coin_lot_size,
pc_lot_size,
fee_rate_bps,
vault_signer_nonce,
pc_dust_threshold,
} = args.instruction;
let market = args.get_market();
let req_q = args.get_req_q();
let event_q = args.get_event_q();
let bids = args.get_bids();
let asks = args.get_asks();
let coin_vault = args.coin_vault_and_mint.get_account().inner();
let coin_mint = args.coin_vault_and_mint.get_mint().inner();
let pc_vault = args.pc_vault_and_mint.get_account().inner();
let pc_mint = args.pc_vault_and_mint.get_mint().inner();
// initialize request queue
let mut rq_data = req_q.try_borrow_mut_data()?;
const RQ_HEADER_WORDS: usize = size_of::<RequestQueueHeader>() / size_of::<u64>();
let rq_view = init_account_padding(&mut rq_data)?;
let (rq_hdr_array, rq_buf_words) = mut_array_refs![rq_view, RQ_HEADER_WORDS; .. ;];
let rq_buf: &[Request] = remove_slop(cast_slice(rq_buf_words));
if rq_buf.is_empty() {
Err(DexErrorCode::RequestQueueEmpty)?
}
let rq_hdr: &mut RequestQueueHeader =
try_cast_mut(rq_hdr_array).or(check_unreachable!())?;
*rq_hdr = RequestQueueHeader {
account_flags: (AccountFlag::Initialized | AccountFlag::RequestQueue).bits(),
head: 0,
count: 0,
next_seq_num: 0,
};
// initialize event queue
let mut eq_data = event_q.try_borrow_mut_data().unwrap();
const EQ_HEADER_WORDS: usize = size_of::<EventQueueHeader>() / size_of::<u64>();
let eq_view = init_account_padding(&mut eq_data)?;
check_assert!(eq_view.len() > EQ_HEADER_WORDS)?;
let (eq_hdr_array, eq_buf_words) = mut_array_refs![eq_view, EQ_HEADER_WORDS; .. ;];
let eq_buf: &[Event] = remove_slop(cast_slice(eq_buf_words));
if eq_buf.len() < 128 {
Err(DexErrorCode::EventQueueTooSmall)?
}
let eq_hdr: &mut EventQueueHeader = try_cast_mut(eq_hdr_array).or(check_unreachable!())?;
*eq_hdr = EventQueueHeader {
account_flags: (AccountFlag::Initialized | AccountFlag::EventQueue).bits(),
head: 0,
count: 0,
seq_num: 0,
};
// initialize orderbook storage
for (flag, account) in &[(AccountFlag::Bids, bids), (AccountFlag::Asks, asks)] {
let mut ob_data = account.try_borrow_mut_data().unwrap();
let ob_view = init_account_padding(&mut ob_data)?;
const OB_HEADER_WORDS: usize = size_of::<OrderBookStateHeader>() / size_of::<u64>();
check_assert!(ob_view.len() > OB_HEADER_WORDS)?;
let (hdr_array, slab_words) = mut_array_refs![ob_view, OB_HEADER_WORDS; .. ;];
let ob_hdr: &mut OrderBookStateHeader =
try_cast_mut(hdr_array).or(check_unreachable!())?;
*ob_hdr = OrderBookStateHeader {
account_flags: (AccountFlag::Initialized | *flag).bits(),
};
let slab = Slab::new(cast_slice_mut(slab_words));
slab.assert_minimum_capacity(100)?;
}
// initialize market
let mut market_data = market.try_borrow_mut_data()?;
let market_view = init_account_padding(&mut market_data)?;
let market_hdr: &mut MarketState =
try_from_bytes_mut(cast_slice_mut(market_view)).or(check_unreachable!())?;
*market_hdr = MarketState {
coin_lot_size,
pc_lot_size,
own_address: market.key.to_aligned_bytes(),
account_flags: (AccountFlag::Initialized | AccountFlag::Market).bits(),
coin_mint: coin_mint.key.to_aligned_bytes(),
coin_vault: coin_vault.key.to_aligned_bytes(),
coin_deposits_total: 0,
coin_fees_accrued: 0,
req_q: req_q.key.to_aligned_bytes(),
event_q: event_q.key.to_aligned_bytes(),
bids: bids.key.to_aligned_bytes(),
asks: asks.key.to_aligned_bytes(),
pc_mint: pc_mint.key.to_aligned_bytes(),
pc_vault: pc_vault.key.to_aligned_bytes(),
pc_deposits_total: 0,
pc_fees_accrued: 0,
vault_signer_nonce,
pc_dust_threshold,
fee_rate_bps: fee_rate_bps as u64,
referrer_rebates_accrued: 0,
};
Ok(())
}
}
| {
Self { header, buf }
} |
traits2.rs | // traits2.rs
//
// Your task is to implement the trait
// `AppendBar' for a vector of strings.
//
// To implement this trait, consider for
// a moment what it means to 'append "Bar"'
// to a vector of strings.
//
// No boiler plate code this time,
// you can do this!
trait AppendBar {
fn append_bar(self) -> Self;
}
//TODO: Add your code here
impl AppendBar for Vec<String> { | fn append_bar(mut self) -> Self {
self.push(String::from("Bar"));
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn is_vec_pop_eq_bar() {
let mut foo = vec![String::from("Foo")].append_bar();
assert_eq!(foo.pop().unwrap(), String::from("Bar"));
assert_eq!(foo.pop().unwrap(), String::from("Foo"));
}
} | |
lib.rs | #![doc = "generated by AutoRust 0.1.0"]
#[cfg(feature = "package-metadata-2021-07-01-preview")]
pub mod package_metadata_2021_07_01_preview;
#[cfg(all(feature = "package-metadata-2021-07-01-preview", not(feature = "no-default-version")))]
pub use package_metadata_2021_07_01_preview::{models, operations};
#[cfg(feature = "package-artifacts-composite-v1")]
pub mod package_artifacts_composite_v1;
#[cfg(all(feature = "package-artifacts-composite-v1", not(feature = "no-default-version")))]
pub use package_artifacts_composite_v1::{models, operations};
#[cfg(feature = "package-artifacts-2021-06-01-preview")]
pub mod package_artifacts_2021_06_01_preview;
#[cfg(all(feature = "package-artifacts-2021-06-01-preview", not(feature = "no-default-version")))]
pub use package_artifacts_2021_06_01_preview::{models, operations};
#[cfg(feature = "package-vnet-2021-06-01-preview")]
pub mod package_vnet_2021_06_01_preview;
#[cfg(all(feature = "package-vnet-2021-06-01-preview", not(feature = "no-default-version")))]
pub use package_vnet_2021_06_01_preview::{models, operations};
#[cfg(feature = "package-kql-script-2021-06-preview")]
pub mod package_kql_script_2021_06_preview;
#[cfg(all(feature = "package-kql-script-2021-06-preview", not(feature = "no-default-version")))]
pub use package_kql_script_2021_06_preview::{models, operations};
#[cfg(feature = "package-artifacts-2020-12-01")]
pub mod package_artifacts_2020_12_01;
#[cfg(all(feature = "package-artifacts-2020-12-01", not(feature = "no-default-version")))]
pub use package_artifacts_2020_12_01::{models, operations};
#[cfg(feature = "package-monitoring-2020-12-01")]
pub mod package_monitoring_2020_12_01;
#[cfg(all(feature = "package-monitoring-2020-12-01", not(feature = "no-default-version")))]
pub use package_monitoring_2020_12_01::{models, operations};
#[cfg(feature = "package-access-control-2020-12-01")]
pub mod package_access_control_2020_12_01;
#[cfg(all(feature = "package-access-control-2020-12-01", not(feature = "no-default-version")))]
pub use package_access_control_2020_12_01::{models, operations};
#[cfg(feature = "package-vnet-2020-12-01")]
pub mod package_vnet_2020_12_01;
#[cfg(all(feature = "package-vnet-2020-12-01", not(feature = "no-default-version")))]
pub use package_vnet_2020_12_01::{models, operations};
#[cfg(feature = "package-spark-2020-12-01")]
pub mod package_spark_2020_12_01;
#[cfg(all(feature = "package-spark-2020-12-01", not(feature = "no-default-version")))]
pub use package_spark_2020_12_01::{models, operations};
#[cfg(feature = "package-spark-2019-11-01-preview")]
pub mod package_spark_2019_11_01_preview;
#[cfg(all(feature = "package-spark-2019-11-01-preview", not(feature = "no-default-version")))]
pub use package_spark_2019_11_01_preview::{models, operations};
#[cfg(feature = "package-artifacts-2019-06-01-preview")]
pub mod package_artifacts_2019_06_01_preview;
#[cfg(all(feature = "package-artifacts-2019-06-01-preview", not(feature = "no-default-version")))]
pub use package_artifacts_2019_06_01_preview::{models, operations};
#[cfg(feature = "package-access-control-2020-02-01-preview")]
pub mod package_access_control_2020_02_01_preview;
#[cfg(all(feature = "package-access-control-2020-02-01-preview", not(feature = "no-default-version")))]
pub use package_access_control_2020_02_01_preview::{models, operations};
#[cfg(feature = "package-access-control-2020-08-01-preview")]
pub mod package_access_control_2020_08_01_preview;
#[cfg(all(feature = "package-access-control-2020-08-01-preview", not(feature = "no-default-version")))]
pub use package_access_control_2020_08_01_preview::{models, operations};
#[cfg(feature = "package-vnet-2019-06-01-preview")]
pub mod package_vnet_2019_06_01_preview;
#[cfg(all(feature = "package-vnet-2019-06-01-preview", not(feature = "no-default-version")))]
pub use package_vnet_2019_06_01_preview::{models, operations};
#[cfg(feature = "package-monitoring-2019-11-01-preview")]
pub mod package_monitoring_2019_11_01_preview;
use azure_core::setters;
#[cfg(all(feature = "package-monitoring-2019-11-01-preview", not(feature = "no-default-version")))]
pub use package_monitoring_2019_11_01_preview::{models, operations};
pub fn config(
http_client: std::sync::Arc<dyn azure_core::HttpClient>,
token_credential: Box<dyn azure_core::TokenCredential>,
) -> OperationConfigBuilder {
OperationConfigBuilder {
http_client,
base_path: None,
token_credential,
token_credential_resource: None,
}
}
pub struct OperationConfigBuilder {
http_client: std::sync::Arc<dyn azure_core::HttpClient>,
base_path: Option<String>,
token_credential: Box<dyn azure_core::TokenCredential>,
token_credential_resource: Option<String>,
}
impl OperationConfigBuilder {
setters! { base_path : String => Some (base_path) , token_credential_resource : String => Some (token_credential_resource) , }
pub fn build(self) -> OperationConfig {
OperationConfig {
http_client: self.http_client,
base_path: self.base_path.unwrap_or("https://management.azure.com".to_owned()),
token_credential: Some(self.token_credential),
token_credential_resource: self.token_credential_resource.unwrap_or("https://management.azure.com/".to_owned()),
}
}
}
pub struct | {
http_client: std::sync::Arc<dyn azure_core::HttpClient>,
base_path: String,
token_credential: Option<Box<dyn azure_core::TokenCredential>>,
token_credential_resource: String,
}
impl OperationConfig {
pub fn http_client(&self) -> &dyn azure_core::HttpClient {
self.http_client.as_ref()
}
pub fn base_path(&self) -> &str {
self.base_path.as_str()
}
pub fn token_credential(&self) -> Option<&dyn azure_core::TokenCredential> {
self.token_credential.as_deref()
}
pub fn token_credential_resource(&self) -> &str {
self.token_credential_resource.as_str()
}
}
| OperationConfig |
zsyscall_openbsd_amd64.go | // mksyscall.pl -openbsd -tags openbsd,amd64 syscall_bsd.go syscall_openbsd.go syscall_openbsd_amd64.go
// Code generated by the command above; DO NOT EDIT.
// +build openbsd,amd64
package syscall
import "unsafe"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setgroups(ngid int, gid *_Gid_t) (err error) {
_, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) {
r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0)
wpid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) {
r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func socket(domain int, typ int, proto int) (fd int, err error) {
r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) {
_, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) {
_, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
_, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
_, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Shutdown(s int, how int) (err error) {
_, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) {
_, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) {
r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) {
r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
var _p0 unsafe.Pointer
if len(mib) > 0 {
_p0 = unsafe.Pointer(&mib[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func utimes(path string, timeval *[2]Timeval) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func futimes(fd int, timeval *[2]Timeval) (err error) {
_, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func fcntl(fd int, cmd int, arg int) (val int, err error) {
r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg))
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func pipe2(p *[2]_C_int, flags int) (err error) {
_, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) {
r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0)
nfd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getdents(fd int, buf []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Access(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
_, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chflags(path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chmod(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chown(path string, uid int, gid int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chroot(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Close(fd int) (err error) {
_, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Dup(fd int) (nfd int, err error) {
r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
nfd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Dup2(from int, to int) (err error) {
_, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchdir(fd int) (err error) {
_, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchflags(fd int, flags int) (err error) {
_, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchmod(fd int, mode uint32) (err error) {
_, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchown(fd int, uid int, gid int) (err error) {
_, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Flock(fd int, how int) (err error) {
_, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fpathconf(fd int, name int) (val int, err error) {
r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstat(fd int, stat *Stat_t) (err error) {
_, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstatfs(fd int, stat *Statfs_t) (err error) {
_, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fsync(fd int) (err error) {
_, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Ftruncate(fd int, length int64) (err error) {
_, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getegid() (egid int) {
r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0)
egid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Geteuid() (uid int) {
r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getgid() (gid int) {
r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0)
gid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpgid(pid int) (pgid int, err error) {
r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0)
pgid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpgrp() (pgrp int) {
r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
pgrp = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpid() (pid int) {
r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0)
pid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getppid() (ppid int) {
r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0)
ppid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpriority(which int, who int) (prio int, err error) {
r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0)
prio = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrlimit(which int, lim *Rlimit) (err error) {
_, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrusage(who int, rusage *Rusage) (err error) {
_, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getsid(pid int) (sid int, err error) {
r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0)
sid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Gettimeofday(tv *Timeval) (err error) {
_, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getuid() (uid int) {
r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Issetugid() (tainted bool) {
r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0)
tainted = bool(r0 != 0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Kill(pid int, signum Signal) (err error) {
_, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Kqueue() (fd int, err error) {
r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Lchown(path string, uid int, gid int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Link(path string, link string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Listen(s int, backlog int) (err error) {
_, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Lstat(path string, stat *Stat_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdir(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkfifo(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mknod(path string, mode uint32, dev int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Nanosleep(time *Timespec, leftover *Timespec) (err error) {
_, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Open(path string, mode int, perm uint32) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pathconf(path string, name int) (val int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pread(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pwrite(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func read(fd int, p []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Readlink(path string, buf []byte) (n int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 unsafe.Pointer
if len(buf) > 0 {
_p1 = unsafe.Pointer(&buf[0])
} else {
_p1 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Rename(from string, to string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(from)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(to)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Revoke(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Rmdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
r0, _, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(whence), 0, 0)
newoffset = int64(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
_, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setegid(egid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Seteuid(euid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setgid(gid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setlogin(name string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setpgid(pid int, pgid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setpriority(which int, who int, prio int) (err error) {
_, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setregid(rgid int, egid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setreuid(ruid int, euid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setrlimit(which int, lim *Rlimit) (err error) {
_, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setsid() (pid int, err error) {
r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0)
pid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Settimeofday(tp *Timeval) (err error) {
_, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setuid(uid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Stat(path string, stat *Stat_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Statfs(path string, stat *Statfs_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Symlink(path string, link string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Sync() (err error) {
_, _, e1 := Syscall(SYS_SYNC, 0, 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Truncate(path string, length int64) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Umask(newmask int) (oldmask int) {
r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
oldmask = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func | (path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unmount(path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func write(fd int, p []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), 0, 0)
ret = uintptr(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func munmap(addr uintptr, length uintptr) (err error) {
_, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func readlen(fd int, buf *byte, nbuf int) (n int, err error) {
r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func writelen(fd int, buf *byte, nbuf int) (n int, err error) {
r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func utimensat(dirfd int, path string, times *[2]Timespec, flag int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flag), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getcwd(buf []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
| Unlink |
filter_poly.py | '''
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/NAIP/filter_poly.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td>
<td><a target="_blank" href="https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/NAIP/filter_poly.ipynb"><img width=26px src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png" />Notebook Viewer</a></td>
<td><a target="_blank" href="https://mybinder.org/v2/gh/giswqs/earthengine-py-notebooks/master?filepath=NAIP/filter_poly.ipynb"><img width=58px src="https://mybinder.org/static/images/logo_social.png" />Run in binder</a></td>
<td><a target="_blank" href="https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/NAIP/filter_poly.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a></td>
</table>
'''
# %%
'''
## Install Earth Engine API
Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](https://github.com/python-visualization/folium) package and implements several methods for displaying Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, `Map.centerObject()`, and `Map.setOptions()`.
The following script checks if the geehydro package has been installed. If not, it will install geehydro, which automatically install its dependencies, including earthengine-api and folium.
'''
# %%
import subprocess
try:
import geehydro
except ImportError:
print('geehydro package not installed. Installing ...')
subprocess.check_call(["python", '-m', 'pip', 'install', 'geehydro'])
# %%
'''
Import libraries
'''
# %%
import ee
import folium
import geehydro
# %%
'''
Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once.
'''
# %%
try:
ee.Initialize()
except Exception as e:
ee.Authenticate()
ee.Initialize()
# %%
'''
## Create an interactive map
This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function.
The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `ESRI`.
'''
# %%
Map = folium.Map(location=[40, -100], zoom_start=4)
Map.setOptions('HYBRID')
# %%
'''
## Add Earth Engine Python script
'''
# %%
collection = ee.ImageCollection('USDA/NAIP/DOQQ') | [-99.2116928100586, 46.72404725733022],
[-99.21443939208984, 46.772037733479884],
[-99.30267333984375, 46.77321343419932]]])
centroid = polys.centroid()
lng, lat = centroid.getInfo()['coordinates']
print("lng = {}, lat = {}".format(lng, lat))
lng_lat = ee.Geometry.Point(lng, lat)
naip = collection.filterBounds(polys)
naip_2015 = naip.filterDate('2015-01-01', '2015-12-31')
ppr = naip_2015.mosaic()
count = naip_2015.size().getInfo()
print("Count: ", count)
# print(naip_2015.size().getInfo())
# vis = {'bands': ['N', 'R', 'G']}
# Map.setCenter(lng, lat, 12)
# Map.addLayer(ppr,vis)
# Map.addLayer(polys)
downConfig = {'scale': 30, "maxPixels": 1.0E13, 'driveFolder': 'image'} # scale means resolution.
img_lst = naip_2015.toList(100)
for i in range(0, count):
image = ee.Image(img_lst.get(i))
name = image.get('system:index').getInfo()
# print(name)
task = ee.batch.Export.image(image, name, downConfig)
task.start()
# %%
'''
## Display Earth Engine data layers
'''
# %%
Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True)
Map |
polys = ee.Geometry.Polygon(
[[[-99.29615020751953, 46.725459351792374], |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.